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.

1843 lines
83 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. using System.ComponentModel;
  19. #if NET3
  20. using Net3_Proxy;
  21. using Array = Net3_Proxy.Array;
  22. #endif
  23. [assembly: InternalsVisibleTo(IPA.Config.Stores.GeneratedExtension.AssemblyVisibilityTarget)]
  24. namespace IPA.Config.Stores
  25. {
  26. /// <summary>
  27. /// A class providing an extension for <see cref="Config"/> to make it easy to use generated
  28. /// config stores.
  29. /// </summary>
  30. public static class GeneratedExtension
  31. {
  32. /// <summary>
  33. /// The name of the assembly that internals must be visible to to allow internal protection.
  34. /// </summary>
  35. public const string AssemblyVisibilityTarget = GeneratedStore.GeneratedAssemblyName;
  36. /// <summary>
  37. /// Creates a generated <see cref="IConfigStore"/> of type <typeparamref name="T"/>, registers it to
  38. /// the <see cref="Config"/> object, and returns it. This also forces a synchronous config load via
  39. /// <see cref="Config.LoadSync"/> if <paramref name="loadSync"/> is <see langword="true"/>.
  40. /// </summary>
  41. /// <remarks>
  42. /// <para>
  43. /// <typeparamref name="T"/> must be a public non-<see langword="sealed"/> class.
  44. /// It can also be internal, but in that case, then your assembly must have the following attribute
  45. /// to allow the generated code to reference it.
  46. /// <code>
  47. /// [assembly: InternalsVisibleTo(IPA.Config.Stores.GeneratedExtension.AssemblyVisibilityTarget)]
  48. /// </code>
  49. /// </para>
  50. /// <para>
  51. /// Only fields and properties that are public or protected will be considered, and only properties
  52. /// where both the getter and setter are public or protected are considered. Any fields or properties
  53. /// with an <see cref="IgnoreAttribute"/> applied to them are also ignored. Having properties be <see langword="virtual"/> is not strictly
  54. /// necessary, however it allows the generated type to keep track of changes and lock around them so that the config will auto-save.
  55. /// </para>
  56. /// <para>
  57. /// All of the attributes in the <see cref="Attributes"/> namespace are handled as described by them.
  58. /// </para>
  59. /// <para>
  60. /// If the <typeparamref name="T"/> declares a public or protected, <see langword="virtual"/>
  61. /// method <c>Changed()</c>, then that method may be called to artificially signal to the runtime that the content of the object
  62. /// has changed. That method will also be called after the write locks are released when a property is set anywhere in the owning
  63. /// tree. This will only be called on the outermost generated object of the config structure, even if the change being signaled
  64. /// is somewhere deep into the tree. TODO: is this a good idea?
  65. /// </para>
  66. /// <para>
  67. /// Similarly, <typeparamref name="T"/> can declare a public or protected, <see langword="virtual"/>
  68. /// method <c>OnReload()</c>, which will be called on the filesystem reader thread after the object has been repopulated with new data
  69. /// 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
  70. /// object of the config structure.
  71. /// </para>
  72. /// <para>
  73. /// Similarly, <typeparamref name="T"/> can declare a public or protected, <see langword="virtual"/>
  74. /// method <c>CopyFrom(ConfigType)</c> (the first parameter is the type it is defined on), which may be called to copy the properties from
  75. /// another object of its type easily, and more importantly, as only one change. Its body will be executed after the values have been copied.
  76. /// </para>
  77. /// <para>
  78. /// Similarly, <typeparamref name="T"/> can declare a public or protected, <see langword="virtual"/>
  79. /// method <c>ChangeTransaction()</c> returning <see cref="IDisposable"/>, which may be called to get an object representing a transactional
  80. /// change. This may be used to change a lot of properties at once without triggering a save multiple times. Ideally, this is used in a
  81. /// <see langword="using"/> block or declaration. The <see cref="IDisposable"/> returned from your implementation will have its
  82. /// <see cref="IDisposable.Dispose"/> called <i>after</i> <c>Changed()</c> is called, but <i>before</i> the write lock is released.
  83. /// Unless you have a very good reason to use the nested <see cref="IDisposable"/>, avoid it.
  84. /// </para>
  85. /// <para>
  86. /// If <typeparamref name="T"/> is marked with <see cref="NotifyPropertyChangesAttribute"/>, the resulting object will implement
  87. /// <see cref="INotifyPropertyChanged"/>. Similarly, if <typeparamref name="T"/> implements <see cref="INotifyPropertyChanged"/>,
  88. /// the resulting object will implement it and notify it too.
  89. /// </para>
  90. /// </remarks>
  91. /// <typeparam name="T">the type to wrap</typeparam>
  92. /// <param name="cfg">the <see cref="Config"/> to register to</param>
  93. /// <param name="loadSync">whether to synchronously load the content, or trigger an async load</param>
  94. /// <returns>a generated instance of <typeparamref name="T"/> as a special <see cref="IConfigStore"/></returns>
  95. public static T Generated<T>(this Config cfg, bool loadSync = true) where T : class
  96. {
  97. var ret = GeneratedStore.Create<T>();
  98. cfg.SetStore(ret as IConfigStore);
  99. if (loadSync)
  100. cfg.LoadSync();
  101. else
  102. cfg.LoadAsync();
  103. return ret;
  104. }
  105. }
  106. internal static class GeneratedStore
  107. {
  108. internal interface IGeneratedStore
  109. {
  110. Type Type { get; }
  111. IGeneratedStore Parent { get; }
  112. Impl Impl { get; }
  113. void OnReload();
  114. void Changed();
  115. IDisposable ChangeTransaction();
  116. Value Serialize();
  117. void Deserialize(Value val);
  118. }
  119. internal interface IGeneratedStore<T> : IGeneratedStore where T : class
  120. {
  121. void CopyFrom(T source, bool useLock);
  122. }
  123. internal interface IGeneratedPropertyChanged : INotifyPropertyChanged
  124. {
  125. PropertyChangedEventHandler PropertyChangedEvent { get; }
  126. }
  127. internal class Impl : IConfigStore
  128. {
  129. private readonly IGeneratedStore generated;
  130. private bool inChangeTransaction = false;
  131. private bool changedInTransaction = false;
  132. internal static ConstructorInfo Ctor = typeof(Impl).GetConstructor(new[] { typeof(IGeneratedStore) });
  133. public Impl(IGeneratedStore store) => generated = store;
  134. private readonly AutoResetEvent resetEvent = new AutoResetEvent(false);
  135. public WaitHandle SyncObject => resetEvent;
  136. public static WaitHandle ImplGetSyncObject(IGeneratedStore s) => FindImpl(s).SyncObject;
  137. internal static MethodInfo ImplGetSyncObjectMethod = typeof(Impl).GetMethod(nameof(ImplGetSyncObject));
  138. public ReaderWriterLockSlim WriteSyncObject { get; } = new ReaderWriterLockSlim();
  139. public static ReaderWriterLockSlim ImplGetWriteSyncObject(IGeneratedStore s) => FindImpl(s)?.WriteSyncObject;
  140. internal static MethodInfo ImplGetWriteSyncObjectMethod = typeof(Impl).GetMethod(nameof(ImplGetWriteSyncObject));
  141. internal static MethodInfo ImplSignalChangedMethod = typeof(Impl).GetMethod(nameof(ImplSignalChanged));
  142. public static void ImplSignalChanged(IGeneratedStore s) => FindImpl(s).SignalChanged();
  143. public void SignalChanged() => resetEvent.Set();
  144. internal static MethodInfo ImplInvokeChangedMethod = typeof(Impl).GetMethod(nameof(ImplInvokeChanged));
  145. public static void ImplInvokeChanged(IGeneratedStore s) => FindImpl(s).InvokeChanged();
  146. public void InvokeChanged() => generated.Changed();
  147. internal static MethodInfo ImplTakeReadMethod = typeof(Impl).GetMethod(nameof(ImplTakeRead));
  148. public static void ImplTakeRead(IGeneratedStore s) => FindImpl(s).TakeRead();
  149. public void TakeRead()
  150. {
  151. if (!WriteSyncObject.IsWriteLockHeld)
  152. WriteSyncObject.EnterReadLock();
  153. }
  154. internal static MethodInfo ImplReleaseReadMethod = typeof(Impl).GetMethod(nameof(ImplReleaseRead));
  155. public static void ImplReleaseRead(IGeneratedStore s) => FindImpl(s).ReleaseRead();
  156. public void ReleaseRead()
  157. {
  158. if (!WriteSyncObject.IsWriteLockHeld)
  159. WriteSyncObject.ExitReadLock();
  160. }
  161. internal static MethodInfo ImplTakeWriteMethod = typeof(Impl).GetMethod(nameof(ImplTakeWrite));
  162. public static void ImplTakeWrite(IGeneratedStore s) => FindImpl(s).TakeWrite();
  163. public void TakeWrite() => WriteSyncObject.EnterWriteLock();
  164. internal static MethodInfo ImplReleaseWriteMethod = typeof(Impl).GetMethod(nameof(ImplReleaseWrite));
  165. public static void ImplReleaseWrite(IGeneratedStore s) => FindImpl(s).ReleaseWrite();
  166. public void ReleaseWrite() => WriteSyncObject.ExitWriteLock();
  167. internal static MethodInfo ImplChangeTransactionMethod = typeof(Impl).GetMethod(nameof(ImplChangeTransaction));
  168. public static IDisposable ImplChangeTransaction(IGeneratedStore s, IDisposable nest) => FindImpl(s).ChangeTransaction(nest);
  169. // TODO: improve trasactionals so they don't always save in every case
  170. public IDisposable ChangeTransaction(IDisposable nest, bool takeWrite = true)
  171. => GetFreeTransaction().InitWith(this, !inChangeTransaction, nest, takeWrite && !WriteSyncObject.IsWriteLockHeld);
  172. private ChangeTransactionObj GetFreeTransaction()
  173. => freeTransactionObjs.Count > 0 ? freeTransactionObjs.Pop()
  174. : new ChangeTransactionObj();
  175. // TODO: maybe sometimes clean this?
  176. private static readonly Stack<ChangeTransactionObj> freeTransactionObjs = new Stack<ChangeTransactionObj>();
  177. private sealed class ChangeTransactionObj : IDisposable
  178. {
  179. private struct Data
  180. {
  181. public readonly Impl impl;
  182. public readonly bool owns;
  183. public readonly bool ownsWrite;
  184. public readonly IDisposable nested;
  185. public Data(Impl impl, bool owning, bool takeWrite, IDisposable nest)
  186. {
  187. this.impl = impl; owns = owning; ownsWrite = takeWrite; nested = nest;
  188. }
  189. }
  190. private Data data;
  191. public ChangeTransactionObj InitWith(Impl impl, bool owning, IDisposable nest, bool takeWrite)
  192. {
  193. data = new Data(impl, owning, takeWrite, nest);
  194. if (data.owns)
  195. impl.inChangeTransaction = true;
  196. if (data.ownsWrite)
  197. impl.TakeWrite();
  198. return this;
  199. }
  200. public void Dispose() => Dispose(true);
  201. private void Dispose(bool addToStore)
  202. {
  203. if (data.owns)
  204. {
  205. data.impl.inChangeTransaction = false;
  206. data.impl.InvokeChanged();
  207. }
  208. data.nested?.Dispose();
  209. if (data.ownsWrite)
  210. data.impl.ReleaseWrite();
  211. if (addToStore)
  212. freeTransactionObjs.Push(this);
  213. }
  214. ~ChangeTransactionObj() => Dispose(false);
  215. }
  216. public static Impl FindImpl(IGeneratedStore store)
  217. {
  218. while (store?.Parent != null) store = store.Parent; // walk to the top of the tree
  219. return store?.Impl;
  220. }
  221. internal static MethodInfo ImplReadFromMethod = typeof(Impl).GetMethod(nameof(ImplReadFrom));
  222. public static void ImplReadFrom(IGeneratedStore s, ConfigProvider provider) => FindImpl(s).ReadFrom(provider);
  223. public void ReadFrom(ConfigProvider provider)
  224. {
  225. var values = provider.Load();
  226. Logger.config.Debug("Generated impl ReadFrom");
  227. Logger.config.Debug($"Read {values}");
  228. generated.Deserialize(values);
  229. using var transaction = generated.ChangeTransaction();
  230. generated.OnReload();
  231. }
  232. internal static MethodInfo ImplWriteToMethod = typeof(Impl).GetMethod(nameof(ImplWriteTo));
  233. public static void ImplWriteTo(IGeneratedStore s, ConfigProvider provider) => FindImpl(s).WriteTo(provider);
  234. public void WriteTo(ConfigProvider provider)
  235. {
  236. var values = generated.Serialize();
  237. Logger.config.Debug("Generated impl WriteTo");
  238. Logger.config.Debug($"Serialized {values}");
  239. provider.Store(values);
  240. }
  241. }
  242. private static readonly Dictionary<Type, (GeneratedStoreCreator ctor, Type type)> generatedCreators = new Dictionary<Type, (GeneratedStoreCreator ctor, Type type)>();
  243. public static T Create<T>() where T : class => (T)Create(typeof(T));
  244. public static IConfigStore Create(Type type) => Create(type, null);
  245. private static readonly MethodInfo CreateGParent =
  246. typeof(GeneratedStore).GetMethod(nameof(Create), BindingFlags.NonPublic | BindingFlags.Static, null,
  247. CallingConventions.Any, new[] { typeof(IGeneratedStore) }, Array.Empty<ParameterModifier>());
  248. internal static T Create<T>(IGeneratedStore parent) where T : class => (T)Create(typeof(T), parent);
  249. private static IConfigStore Create(Type type, IGeneratedStore parent)
  250. => GetCreator(type)(parent);
  251. internal static GeneratedStoreCreator GetCreator(Type t)
  252. {
  253. if (generatedCreators.TryGetValue(t, out var gen))
  254. return gen.ctor;
  255. else
  256. {
  257. gen = MakeCreator(t);
  258. generatedCreators.Add(t, gen);
  259. return gen.ctor;
  260. }
  261. }
  262. internal static Type GetGeneratedType(Type t)
  263. {
  264. if (generatedCreators.TryGetValue(t, out var gen))
  265. return gen.type;
  266. else
  267. {
  268. gen = MakeCreator(t);
  269. generatedCreators.Add(t, gen);
  270. return gen.type;
  271. }
  272. }
  273. internal const string GeneratedAssemblyName = "IPA.Config.Generated";
  274. private static AssemblyBuilder assembly = null;
  275. private static AssemblyBuilder Assembly
  276. {
  277. get
  278. {
  279. if (assembly == null)
  280. {
  281. var name = new AssemblyName(GeneratedAssemblyName);
  282. assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.RunAndSave);
  283. }
  284. return assembly;
  285. }
  286. }
  287. internal static void DebugSaveAssembly(string file)
  288. {
  289. Assembly.Save(file);
  290. }
  291. private static ModuleBuilder module = null;
  292. private static ModuleBuilder Module
  293. {
  294. get
  295. {
  296. if (module == null)
  297. module = Assembly.DefineDynamicModule(Assembly.GetName().Name, Assembly.GetName().Name + ".dll");
  298. return module;
  299. }
  300. }
  301. private class SerializedMemberInfo
  302. {
  303. public string Name;
  304. public MemberInfo Member;
  305. public Type Type;
  306. public bool AllowNull;
  307. public bool IsVirtual;
  308. public bool IsField;
  309. public bool IsNullable; // signifies whether this is a Nullable<T>
  310. public bool HasConverter;
  311. public bool IsGenericConverter; // used so we can call directly to the generic version if it is
  312. public Type Converter;
  313. public Type ConverterBase;
  314. public Type ConverterTarget;
  315. public FieldInfo ConverterField;
  316. // invalid for objects with IsNullabe false
  317. public Type NullableWrappedType => Nullable.GetUnderlyingType(Type);
  318. // invalid for objects with IsNullabe false
  319. public PropertyInfo Nullable_HasValue => Type.GetProperty(nameof(Nullable<int>.HasValue));
  320. // invalid for objects with IsNullabe false
  321. public PropertyInfo Nullable_Value => Type.GetProperty(nameof(Nullable<int>.Value));
  322. // invalid for objects with IsNullabe false
  323. public ConstructorInfo Nullable_Construct => Type.GetConstructor(new[] { NullableWrappedType });
  324. }
  325. internal delegate IConfigStore GeneratedStoreCreator(IGeneratedStore parent);
  326. private static bool IsMethodInvalid(MethodInfo m, Type ret) => !m.IsVirtual || m.ReturnType != ret;
  327. private static (GeneratedStoreCreator ctor, Type type) MakeCreator(Type type)
  328. { // note that this does not and should not use converters by default for everything
  329. if (!type.IsClass) throw new ArgumentException("Config type is not a class");
  330. var baseCtor = type.GetConstructor(Type.EmptyTypes); // get a default constructor
  331. if (baseCtor == null)
  332. throw new ArgumentException("Config type does not have a public parameterless constructor");
  333. #region Parse base object structure
  334. const BindingFlags overrideMemberFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
  335. var baseChanged = type.GetMethod("Changed", overrideMemberFlags, null, Type.EmptyTypes, Array.Empty<ParameterModifier>());
  336. if (baseChanged != null && IsMethodInvalid(baseChanged, typeof(void))) baseChanged = null;
  337. var baseOnReload = type.GetMethod("OnReload", overrideMemberFlags, null, Type.EmptyTypes, Array.Empty<ParameterModifier>());
  338. if (baseOnReload != null && IsMethodInvalid(baseOnReload, typeof(void))) baseOnReload = null;
  339. var baseCopyFrom = type.GetMethod("CopyFrom", overrideMemberFlags, null, new[] { type }, Array.Empty<ParameterModifier>());
  340. if (baseCopyFrom != null && IsMethodInvalid(baseCopyFrom, typeof(void))) baseCopyFrom = null;
  341. var baseChangeTransaction = type.GetMethod("ChangeTransaction", overrideMemberFlags, null, Type.EmptyTypes, Array.Empty<ParameterModifier>());
  342. if (baseChangeTransaction != null && IsMethodInvalid(baseChangeTransaction, typeof(IDisposable))) baseChangeTransaction = null;
  343. var isINotifyPropertyChanged = type.FindInterfaces((i, t) => i == (Type)t, typeof(INotifyPropertyChanged)).Length != 0;
  344. var hasNotifyAttribute = type.GetCustomAttribute<NotifyPropertyChangesAttribute>() != null;
  345. var structure = new List<SerializedMemberInfo>();
  346. bool ProcessAttributesFor(ref SerializedMemberInfo member)
  347. {
  348. var attrs = member.Member.GetCustomAttributes(true);
  349. var ignores = attrs.Select(o => o as IgnoreAttribute).NonNull();
  350. if (ignores.Any()) // we ignore
  351. {
  352. return false;
  353. }
  354. var nonNullables = attrs.Select(o => o as NonNullableAttribute).NonNull();
  355. member.Name = member.Member.Name;
  356. member.IsNullable = member.Type.IsGenericType
  357. && member.Type.GetGenericTypeDefinition() == typeof(Nullable<>);
  358. member.AllowNull = !nonNullables.Any() && (!member.Type.IsValueType || member.IsNullable);
  359. var nameAttr = attrs.Select(o => o as SerializedNameAttribute).NonNull().FirstOrDefault();
  360. if (nameAttr != null)
  361. member.Name = nameAttr.Name;
  362. member.HasConverter = false;
  363. var converterAttr = attrs.Select(o => o as UseConverterAttribute).NonNull().FirstOrDefault();
  364. if (converterAttr != null)
  365. {
  366. member.Converter = converterAttr.ConverterType;
  367. member.IsGenericConverter = converterAttr.IsGenericConverter;
  368. if (member.Converter.GetConstructor(Type.EmptyTypes) == null)
  369. {
  370. Logger.config.Warn($"{type.FullName}'s member {member.Member.Name} requests a converter that is not default-constructible");
  371. goto endConverterAttr; // is there a better control flow structure to do this?
  372. }
  373. if (member.Converter.ContainsGenericParameters)
  374. {
  375. Logger.config.Warn($"{type.FullName}'s member {member.Member.Name} requests a converter that has unfilled type parameters");
  376. goto endConverterAttr;
  377. }
  378. if (member.Converter.IsInterface || member.Converter.IsAbstract)
  379. {
  380. Logger.config.Warn($"{type.FullName}'s member {member.Member.Name} requests a converter that is not constructible");
  381. goto endConverterAttr;
  382. }
  383. var targetType = converterAttr.ConverterTargetType;
  384. if (!member.IsGenericConverter)
  385. {
  386. try
  387. {
  388. var conv = Activator.CreateInstance(converterAttr.ConverterType) as IValueConverter;
  389. targetType = conv.Type;
  390. }
  391. catch
  392. {
  393. Logger.config.Warn($"{type.FullName}'s member {member.Member.Name} requests a converter who's target type could not be determined");
  394. goto endConverterAttr;
  395. }
  396. }
  397. if (targetType != member.Type)
  398. {
  399. Logger.config.Warn($"{type.FullName}'s member {member.Member.Name} requests a converter that is not of the member's type");
  400. goto endConverterAttr;
  401. }
  402. member.ConverterTarget = targetType;
  403. if (member.IsGenericConverter)
  404. member.ConverterBase = typeof(ValueConverter<>).MakeGenericType(targetType);
  405. else
  406. member.ConverterBase = typeof(IValueConverter);
  407. member.HasConverter = true;
  408. }
  409. endConverterAttr:
  410. return true;
  411. }
  412. // only looks at public/protected properties
  413. foreach (var prop in type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
  414. {
  415. if (prop.GetSetMethod(true)?.IsPrivate ?? true)
  416. { // we enter this block if the setter is inacessible or doesn't exist
  417. continue; // ignore props without setter
  418. }
  419. if (prop.GetGetMethod(true)?.IsPrivate ?? true)
  420. { // we enter this block if the getter is inacessible or doesn't exist
  421. continue; // ignore props without getter
  422. }
  423. var smi = new SerializedMemberInfo
  424. {
  425. Member = prop,
  426. IsVirtual = (prop.GetGetMethod(true)?.IsVirtual ?? false) ||
  427. (prop.GetSetMethod(true)?.IsVirtual ?? false),
  428. IsField = false,
  429. Type = prop.PropertyType
  430. };
  431. if (!ProcessAttributesFor(ref smi)) continue;
  432. structure.Add(smi);
  433. }
  434. // only look at public/protected fields
  435. foreach (var field in type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
  436. {
  437. if (field.IsPrivate) continue;
  438. var smi = new SerializedMemberInfo
  439. {
  440. Member = field,
  441. IsVirtual = false,
  442. IsField = true,
  443. Type = field.FieldType
  444. };
  445. if (!ProcessAttributesFor(ref smi)) continue;
  446. structure.Add(smi);
  447. }
  448. #endregion
  449. var typeBuilder = Module.DefineType($"{type.FullName}<Generated>",
  450. TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.Class, type);
  451. var typeField = typeBuilder.DefineField("<>_type", typeof(Type), FieldAttributes.Private | FieldAttributes.InitOnly);
  452. var implField = typeBuilder.DefineField("<>_impl", typeof(Impl), FieldAttributes.Private | FieldAttributes.InitOnly);
  453. var parentField = typeBuilder.DefineField("<>_parent", typeof(IGeneratedStore), FieldAttributes.Private | FieldAttributes.InitOnly);
  454. #region Converter fields
  455. var uniqueConverterTypes = structure.Where(m => m.HasConverter).Select(m => m.Converter).Distinct().ToArray();
  456. var converterFields = new Dictionary<Type, FieldInfo>(uniqueConverterTypes.Length);
  457. foreach (var convType in uniqueConverterTypes)
  458. {
  459. var field = typeBuilder.DefineField($"<converter>_{convType}", convType,
  460. FieldAttributes.Private | FieldAttributes.InitOnly | FieldAttributes.Static);
  461. converterFields.Add(convType, field);
  462. foreach (var member in structure.Where(m => m.HasConverter && m.Converter == convType))
  463. member.ConverterField = field;
  464. }
  465. #endregion
  466. #region Static constructor
  467. var cctor = typeBuilder.DefineConstructor(MethodAttributes.Static, CallingConventions.Standard, Type.EmptyTypes);
  468. {
  469. var il = cctor.GetILGenerator();
  470. foreach (var kvp in converterFields)
  471. {
  472. var typeCtor = kvp.Key.GetConstructor(Type.EmptyTypes);
  473. il.Emit(OpCodes.Newobj, typeCtor);
  474. il.Emit(OpCodes.Stsfld, kvp.Value);
  475. }
  476. il.Emit(OpCodes.Ret);
  477. }
  478. #endregion
  479. #region Constructor
  480. var ctor = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new[] { typeof(IGeneratedStore) });
  481. {
  482. var il = ctor.GetILGenerator();
  483. il.Emit(OpCodes.Ldarg_0); // keep this at bottom of stack
  484. il.Emit(OpCodes.Dup);
  485. il.Emit(OpCodes.Call, baseCtor);
  486. il.Emit(OpCodes.Dup);
  487. il.Emit(OpCodes.Ldarg_1); // load parent
  488. il.Emit(OpCodes.Stfld, parentField);
  489. il.Emit(OpCodes.Dup);
  490. EmitTypeof(il, type);
  491. il.Emit(OpCodes.Stfld, typeField);
  492. var noImplLabel = il.DefineLabel();
  493. il.Emit(OpCodes.Ldarg_1);
  494. il.Emit(OpCodes.Brtrue, noImplLabel);
  495. il.Emit(OpCodes.Dup);
  496. il.Emit(OpCodes.Dup);
  497. il.Emit(OpCodes.Newobj, Impl.Ctor);
  498. il.Emit(OpCodes.Stfld, implField);
  499. il.MarkLabel(noImplLabel);
  500. var GetLocal = MakeGetLocal(il);
  501. foreach (var member in structure)
  502. {
  503. EmitStore(il, member, il =>
  504. {
  505. EmitLoad(il, member); // load the member
  506. EmitCorrectMember(il, member, false, true, GetLocal); // correct it
  507. });
  508. }
  509. il.Emit(OpCodes.Pop);
  510. il.Emit(OpCodes.Ret);
  511. }
  512. #endregion
  513. const MethodAttributes propertyMethodAttr = MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig;
  514. const MethodAttributes virtualPropertyMethodAttr = propertyMethodAttr | MethodAttributes.Virtual | MethodAttributes.Final;
  515. const MethodAttributes virtualMemberMethod = MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.Final;
  516. #region INotifyPropertyChanged
  517. MethodBuilder notifyChanged = null;
  518. if (isINotifyPropertyChanged || hasNotifyAttribute)
  519. {
  520. var INotifyPropertyChanged_t = typeof(INotifyPropertyChanged);
  521. typeBuilder.AddInterfaceImplementation(INotifyPropertyChanged_t);
  522. var INotifyPropertyChanged_PropertyChanged =
  523. INotifyPropertyChanged_t.GetEvent(nameof(INotifyPropertyChanged.PropertyChanged));
  524. var PropertyChangedEventHandler_t = typeof(PropertyChangedEventHandler);
  525. var PropertyChangedEventHander_Invoke = PropertyChangedEventHandler_t.GetMethod(nameof(PropertyChangedEventHandler.Invoke));
  526. var PropertyChangedEventArgs_t = typeof(PropertyChangedEventArgs);
  527. var PropertyChangedEventArgs_ctor = PropertyChangedEventArgs_t.GetConstructor(new[] { typeof(string) });
  528. var Delegate_t = typeof(Delegate);
  529. var Delegate_Combine = Delegate_t.GetMethod(nameof(Delegate.Combine), BindingFlags.Static | BindingFlags.Public, null,
  530. new[] { Delegate_t, Delegate_t }, Array.Empty<ParameterModifier>());
  531. var Delegate_Remove = Delegate_t.GetMethod(nameof(Delegate.Remove), BindingFlags.Static | BindingFlags.Public, null,
  532. new[] { Delegate_t, Delegate_t }, Array.Empty<ParameterModifier>());
  533. var CompareExchange = typeof(Interlocked).GetMethods()
  534. .Where(m => m.Name == nameof(Interlocked.CompareExchange))
  535. .Where(m => m.ContainsGenericParameters)
  536. .Where(m => m.GetParameters().Length == 3).First()
  537. .MakeGenericMethod(PropertyChangedEventHandler_t);
  538. var PropertyChanged_backing = typeBuilder.DefineField("<event>PropertyChanged", PropertyChangedEventHandler_t, FieldAttributes.Private);
  539. var add_PropertyChanged = typeBuilder.DefineMethod("<add>PropertyChanged",
  540. MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Final | MethodAttributes.Virtual,
  541. null, new[] { PropertyChangedEventHandler_t });
  542. typeBuilder.DefineMethodOverride(add_PropertyChanged, INotifyPropertyChanged_PropertyChanged.GetAddMethod());
  543. {
  544. var il = add_PropertyChanged.GetILGenerator();
  545. var loopLabel = il.DefineLabel();
  546. var delTemp = il.DeclareLocal(PropertyChangedEventHandler_t);
  547. il.Emit(OpCodes.Ldarg_0);
  548. il.Emit(OpCodes.Ldfld, PropertyChanged_backing);
  549. il.MarkLabel(loopLabel);
  550. il.Emit(OpCodes.Stloc, delTemp);
  551. il.Emit(OpCodes.Ldarg_0);
  552. il.Emit(OpCodes.Ldflda, PropertyChanged_backing);
  553. il.Emit(OpCodes.Ldloc, delTemp);
  554. il.Emit(OpCodes.Ldarg_1);
  555. il.Emit(OpCodes.Call, Delegate_Combine);
  556. il.Emit(OpCodes.Castclass, PropertyChangedEventHandler_t);
  557. il.Emit(OpCodes.Ldloc, delTemp);
  558. il.Emit(OpCodes.Call, CompareExchange);
  559. il.Emit(OpCodes.Dup);
  560. il.Emit(OpCodes.Ldloc, delTemp);
  561. il.Emit(OpCodes.Bne_Un_S, loopLabel);
  562. il.Emit(OpCodes.Ret);
  563. }
  564. var remove_PropertyChanged = typeBuilder.DefineMethod("<remove>PropertyChanged",
  565. MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Final | MethodAttributes.Virtual,
  566. null, new[] { PropertyChangedEventHandler_t });
  567. typeBuilder.DefineMethodOverride(remove_PropertyChanged, INotifyPropertyChanged_PropertyChanged.GetRemoveMethod());
  568. {
  569. var il = remove_PropertyChanged.GetILGenerator();
  570. var loopLabel = il.DefineLabel();
  571. var delTemp = il.DeclareLocal(PropertyChangedEventHandler_t);
  572. il.Emit(OpCodes.Ldarg_0);
  573. il.Emit(OpCodes.Ldfld, PropertyChanged_backing);
  574. il.MarkLabel(loopLabel);
  575. il.Emit(OpCodes.Stloc, delTemp);
  576. il.Emit(OpCodes.Ldarg_0);
  577. il.Emit(OpCodes.Ldflda, PropertyChanged_backing);
  578. il.Emit(OpCodes.Ldloc, delTemp);
  579. il.Emit(OpCodes.Ldarg_1);
  580. il.Emit(OpCodes.Call, Delegate_Remove);
  581. il.Emit(OpCodes.Castclass, PropertyChangedEventHandler_t);
  582. il.Emit(OpCodes.Ldloc, delTemp);
  583. il.Emit(OpCodes.Call, CompareExchange);
  584. il.Emit(OpCodes.Dup);
  585. il.Emit(OpCodes.Ldloc, delTemp);
  586. il.Emit(OpCodes.Bne_Un_S, loopLabel);
  587. il.Emit(OpCodes.Ret);
  588. }
  589. var PropertyChanged_event = typeBuilder.DefineEvent(nameof(INotifyPropertyChanged.PropertyChanged), EventAttributes.None, PropertyChangedEventHandler_t);
  590. PropertyChanged_event.SetAddOnMethod(add_PropertyChanged);
  591. PropertyChanged_event.SetRemoveOnMethod(remove_PropertyChanged);
  592. notifyChanged = typeBuilder.DefineMethod("<>NotifyChanged",
  593. MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Final, null, new[] { typeof(string) });
  594. {
  595. var il = notifyChanged.GetILGenerator();
  596. var invokeNonNull = il.DefineLabel();
  597. il.Emit(OpCodes.Ldarg_0);
  598. il.Emit(OpCodes.Ldfld, PropertyChanged_backing);
  599. il.Emit(OpCodes.Dup);
  600. il.Emit(OpCodes.Brtrue, invokeNonNull);
  601. il.Emit(OpCodes.Pop);
  602. il.Emit(OpCodes.Ret);
  603. il.MarkLabel(invokeNonNull);
  604. il.Emit(OpCodes.Ldarg_0);
  605. il.Emit(OpCodes.Ldarg_1);
  606. il.Emit(OpCodes.Newobj, PropertyChangedEventArgs_ctor);
  607. il.Emit(OpCodes.Call, PropertyChangedEventHander_Invoke);
  608. il.Emit(OpCodes.Ret);
  609. }
  610. }
  611. #endregion
  612. #region IGeneratedStore
  613. typeBuilder.AddInterfaceImplementation(typeof(IGeneratedStore));
  614. var IGeneratedStore_t = typeof(IGeneratedStore);
  615. var IGeneratedStore_GetImpl = IGeneratedStore_t.GetProperty(nameof(IGeneratedStore.Impl)).GetGetMethod();
  616. var IGeneratedStore_GetType = IGeneratedStore_t.GetProperty(nameof(IGeneratedStore.Type)).GetGetMethod();
  617. var IGeneratedStore_GetParent = IGeneratedStore_t.GetProperty(nameof(IGeneratedStore.Parent)).GetGetMethod();
  618. var IGeneratedStore_Serialize = IGeneratedStore_t.GetMethod(nameof(IGeneratedStore.Serialize));
  619. var IGeneratedStore_Deserialize = IGeneratedStore_t.GetMethod(nameof(IGeneratedStore.Deserialize));
  620. var IGeneratedStore_OnReload = IGeneratedStore_t.GetMethod(nameof(IGeneratedStore.OnReload));
  621. var IGeneratedStore_Changed = IGeneratedStore_t.GetMethod(nameof(IGeneratedStore.Changed));
  622. var IGeneratedStore_ChangeTransaction = IGeneratedStore_t.GetMethod(nameof(IGeneratedStore.ChangeTransaction));
  623. #region IGeneratedStore.OnReload
  624. var onReload = typeBuilder.DefineMethod($"<>{nameof(IGeneratedStore.OnReload)}", virtualMemberMethod, null, Type.EmptyTypes);
  625. typeBuilder.DefineMethodOverride(onReload, IGeneratedStore_OnReload);
  626. if (baseOnReload != null) typeBuilder.DefineMethodOverride(onReload, baseOnReload);
  627. {
  628. var il = onReload.GetILGenerator();
  629. if (baseOnReload != null)
  630. {
  631. il.Emit(OpCodes.Ldarg_0); // load this
  632. il.Emit(OpCodes.Tailcall);
  633. il.Emit(OpCodes.Call, baseOnReload); // load impl field
  634. }
  635. il.Emit(OpCodes.Ret);
  636. }
  637. #endregion
  638. #region IGeneratedStore.Impl
  639. var implProp = typeBuilder.DefineProperty(nameof(IGeneratedStore.Impl), PropertyAttributes.None, typeof(Impl), null);
  640. var implPropGet = typeBuilder.DefineMethod($"<g>{nameof(IGeneratedStore.Impl)}", virtualPropertyMethodAttr, implProp.PropertyType, Type.EmptyTypes);
  641. implProp.SetGetMethod(implPropGet);
  642. typeBuilder.DefineMethodOverride(implPropGet, IGeneratedStore_GetImpl);
  643. {
  644. var il = implPropGet.GetILGenerator();
  645. il.Emit(OpCodes.Ldarg_0); // load this
  646. il.Emit(OpCodes.Ldfld, implField); // load impl field
  647. il.Emit(OpCodes.Ret);
  648. }
  649. #endregion
  650. #region IGeneratedStore.Type
  651. var typeProp = typeBuilder.DefineProperty(nameof(IGeneratedStore.Type), PropertyAttributes.None, typeof(Type), null);
  652. var typePropGet = typeBuilder.DefineMethod($"<g>{nameof(IGeneratedStore.Type)}", virtualPropertyMethodAttr, typeProp.PropertyType, Type.EmptyTypes);
  653. typeProp.SetGetMethod(typePropGet);
  654. typeBuilder.DefineMethodOverride(typePropGet, IGeneratedStore_GetType);
  655. {
  656. var il = typePropGet.GetILGenerator();
  657. il.Emit(OpCodes.Ldarg_0); // load this
  658. il.Emit(OpCodes.Ldfld, typeField); // load impl field
  659. il.Emit(OpCodes.Ret);
  660. }
  661. #endregion
  662. #region IGeneratedStore.Parent
  663. var parentProp = typeBuilder.DefineProperty(nameof(IGeneratedStore.Parent), PropertyAttributes.None, typeof(IGeneratedStore), null);
  664. var parentPropGet = typeBuilder.DefineMethod($"<g>{nameof(IGeneratedStore.Parent)}", virtualPropertyMethodAttr, parentProp.PropertyType, Type.EmptyTypes);
  665. parentProp.SetGetMethod(parentPropGet);
  666. typeBuilder.DefineMethodOverride(parentPropGet, IGeneratedStore_GetParent);
  667. {
  668. var il = parentPropGet.GetILGenerator();
  669. il.Emit(OpCodes.Ldarg_0); // load this
  670. il.Emit(OpCodes.Ldfld, parentField); // load impl field
  671. il.Emit(OpCodes.Ret);
  672. }
  673. #endregion
  674. #region IGeneratedStore.Serialize
  675. var serializeGen = typeBuilder.DefineMethod($"<>{nameof(IGeneratedStore.Serialize)}", virtualPropertyMethodAttr, IGeneratedStore_Serialize.ReturnType, Type.EmptyTypes);
  676. typeBuilder.DefineMethodOverride(serializeGen, IGeneratedStore_Serialize);
  677. { // this is non-locking because the only code that will call this will already own the correct lock
  678. var il = serializeGen.GetILGenerator();
  679. var Map_Add = typeof(Map).GetMethod(nameof(Map.Add));
  680. var mapLocal = il.DeclareLocal(typeof(Map));
  681. var GetLocal = MakeGetLocal(il);
  682. var valLocal = GetLocal(typeof(Value));
  683. il.Emit(OpCodes.Call, typeof(Value).GetMethod(nameof(Value.Map)));
  684. il.Emit(OpCodes.Stloc, mapLocal);
  685. foreach (var member in structure)
  686. {
  687. EmitSerializeMember(il, member, GetLocal);
  688. il.Emit(OpCodes.Stloc, valLocal);
  689. il.Emit(OpCodes.Ldloc, mapLocal);
  690. il.Emit(OpCodes.Ldstr, member.Name);
  691. il.Emit(OpCodes.Ldloc, valLocal);
  692. il.Emit(OpCodes.Call, Map_Add);
  693. }
  694. il.Emit(OpCodes.Ldloc, mapLocal);
  695. il.Emit(OpCodes.Ret);
  696. }
  697. #endregion
  698. #region IGeneratedStore.Deserialize
  699. var deserializeGen = typeBuilder.DefineMethod($"<>{nameof(IGeneratedStore.Deserialize)}", virtualPropertyMethodAttr, null,
  700. new[] { IGeneratedStore_Deserialize.GetParameters()[0].ParameterType });
  701. typeBuilder.DefineMethodOverride(deserializeGen, IGeneratedStore_Deserialize);
  702. { // this is non-locking because the only code that will call this will already own the correct lock
  703. var il = deserializeGen.GetILGenerator();
  704. var Map_t = typeof(Map);
  705. var Map_TryGetValue = Map_t.GetMethod(nameof(Map.TryGetValue));
  706. var Object_GetType = typeof(object).GetMethod(nameof(Object.GetType));
  707. var valueLocal = il.DeclareLocal(typeof(Value));
  708. var mapLocal = il.DeclareLocal(typeof(Map));
  709. var nonNull = il.DefineLabel();
  710. il.Emit(OpCodes.Ldarg_1);
  711. il.Emit(OpCodes.Brtrue, nonNull);
  712. EmitLogError(il, "Attempting to deserialize null", tailcall: true);
  713. il.Emit(OpCodes.Ret);
  714. il.MarkLabel(nonNull);
  715. il.Emit(OpCodes.Ldarg_1);
  716. il.Emit(OpCodes.Isinst, Map_t);
  717. il.Emit(OpCodes.Dup); // duplicate cloned value
  718. il.Emit(OpCodes.Stloc, mapLocal);
  719. var notMapError = il.DefineLabel();
  720. il.Emit(OpCodes.Brtrue, notMapError);
  721. // handle error
  722. EmitLogError(il, $"Invalid root for deserializing {type.FullName}", tailcall: true,
  723. expected: il => EmitTypeof(il, Map_t), found: il =>
  724. {
  725. il.Emit(OpCodes.Ldarg_1);
  726. il.Emit(OpCodes.Callvirt, Object_GetType);
  727. });
  728. il.Emit(OpCodes.Ret);
  729. var nextLabel = notMapError;
  730. var GetLocal = MakeGetLocal(il);
  731. // head of stack is Map instance
  732. foreach (var member in structure)
  733. {
  734. il.MarkLabel(nextLabel);
  735. nextLabel = il.DefineLabel();
  736. var endErrorLabel = il.DefineLabel();
  737. il.Emit(OpCodes.Ldloc, mapLocal);
  738. il.Emit(OpCodes.Ldstr, member.Name);
  739. il.Emit(OpCodes.Ldloca_S, valueLocal);
  740. il.Emit(OpCodes.Call, Map_TryGetValue);
  741. il.Emit(OpCodes.Brtrue_S, endErrorLabel);
  742. EmitLogError(il, $"Missing key {member.Name}", tailcall: false);
  743. il.Emit(OpCodes.Br, nextLabel);
  744. il.MarkLabel(endErrorLabel);
  745. il.Emit(OpCodes.Ldloc_S, valueLocal);
  746. EmitDeserializeMember(il, member, nextLabel, il => il.Emit(OpCodes.Ldloc_S, valueLocal), GetLocal);
  747. }
  748. il.MarkLabel(nextLabel);
  749. if (notifyChanged != null)
  750. {
  751. foreach (var member in structure)
  752. {
  753. il.Emit(OpCodes.Ldarg_0);
  754. il.Emit(OpCodes.Ldstr, member.Name);
  755. il.Emit(OpCodes.Call, notifyChanged);
  756. }
  757. }
  758. il.Emit(OpCodes.Ret);
  759. }
  760. #endregion
  761. #endregion
  762. #region IConfigStore
  763. typeBuilder.AddInterfaceImplementation(typeof(IConfigStore));
  764. var IConfigStore_t = typeof(IConfigStore);
  765. var IConfigStore_GetSyncObject = IConfigStore_t.GetProperty(nameof(IConfigStore.SyncObject)).GetGetMethod();
  766. var IConfigStore_GetWriteSyncObject = IConfigStore_t.GetProperty(nameof(IConfigStore.WriteSyncObject)).GetGetMethod();
  767. var IConfigStore_WriteTo = IConfigStore_t.GetMethod(nameof(IConfigStore.WriteTo));
  768. var IConfigStore_ReadFrom = IConfigStore_t.GetMethod(nameof(IConfigStore.ReadFrom));
  769. #region IConfigStore.SyncObject
  770. var syncObjProp = typeBuilder.DefineProperty(nameof(IConfigStore.SyncObject), PropertyAttributes.None, typeof(WaitHandle), null);
  771. var syncObjPropGet = typeBuilder.DefineMethod($"<g>{nameof(IConfigStore.SyncObject)}", virtualPropertyMethodAttr, syncObjProp.PropertyType, Type.EmptyTypes);
  772. syncObjProp.SetGetMethod(syncObjPropGet);
  773. typeBuilder.DefineMethodOverride(syncObjPropGet, IConfigStore_GetSyncObject);
  774. {
  775. var il = syncObjPropGet.GetILGenerator();
  776. il.Emit(OpCodes.Ldarg_0);
  777. il.Emit(OpCodes.Tailcall);
  778. il.Emit(OpCodes.Call, Impl.ImplGetSyncObjectMethod);
  779. il.Emit(OpCodes.Ret);
  780. }
  781. #endregion
  782. #region IConfigStore.WriteSyncObject
  783. var writeSyncObjProp = typeBuilder.DefineProperty(nameof(IConfigStore.WriteSyncObject), PropertyAttributes.None, typeof(WaitHandle), null);
  784. var writeSyncObjPropGet = typeBuilder.DefineMethod($"<g>{nameof(IConfigStore.WriteSyncObject)}", virtualPropertyMethodAttr, writeSyncObjProp.PropertyType, Type.EmptyTypes);
  785. writeSyncObjProp.SetGetMethod(writeSyncObjPropGet);
  786. typeBuilder.DefineMethodOverride(writeSyncObjPropGet, IConfigStore_GetWriteSyncObject);
  787. {
  788. var il = writeSyncObjPropGet.GetILGenerator();
  789. il.Emit(OpCodes.Ldarg_0);
  790. il.Emit(OpCodes.Tailcall);
  791. il.Emit(OpCodes.Call, Impl.ImplGetWriteSyncObjectMethod);
  792. il.Emit(OpCodes.Ret);
  793. }
  794. #endregion
  795. #region IConfigStore.WriteTo
  796. var writeTo = typeBuilder.DefineMethod($"<>{nameof(IConfigStore.WriteTo)}", virtualMemberMethod, null, new[] { typeof(ConfigProvider) });
  797. typeBuilder.DefineMethodOverride(writeTo, IConfigStore_WriteTo);
  798. {
  799. var il = writeTo.GetILGenerator();
  800. il.Emit(OpCodes.Ldarg_0);
  801. il.Emit(OpCodes.Ldarg_1);
  802. il.Emit(OpCodes.Tailcall);
  803. il.Emit(OpCodes.Call, Impl.ImplWriteToMethod);
  804. il.Emit(OpCodes.Ret);
  805. }
  806. #endregion
  807. #region IConfigStore.ReadFrom
  808. var readFrom = typeBuilder.DefineMethod($"<>{nameof(IConfigStore.ReadFrom)}", virtualMemberMethod, null, new[] { typeof(ConfigProvider) });
  809. typeBuilder.DefineMethodOverride(readFrom, IConfigStore_ReadFrom);
  810. {
  811. var il = readFrom.GetILGenerator();
  812. il.Emit(OpCodes.Ldarg_0);
  813. il.Emit(OpCodes.Ldarg_1);
  814. il.Emit(OpCodes.Tailcall);
  815. il.Emit(OpCodes.Call, Impl.ImplReadFromMethod);
  816. il.Emit(OpCodes.Ret);
  817. }
  818. #endregion
  819. #endregion
  820. #region Changed
  821. var coreChanged = typeBuilder.DefineMethod(
  822. "<>Changed",
  823. virtualMemberMethod,
  824. null, Type.EmptyTypes);
  825. typeBuilder.DefineMethodOverride(coreChanged, IGeneratedStore_Changed);
  826. if (baseChanged != null)
  827. typeBuilder.DefineMethodOverride(coreChanged, baseChanged);
  828. {
  829. var il = coreChanged.GetILGenerator();
  830. if (baseChanged != null)
  831. {
  832. il.Emit(OpCodes.Ldarg_0);
  833. il.Emit(OpCodes.Call, baseChanged); // call base
  834. }
  835. il.Emit(OpCodes.Ldarg_0);
  836. il.Emit(OpCodes.Tailcall);
  837. il.Emit(OpCodes.Call, Impl.ImplSignalChangedMethod);
  838. il.Emit(OpCodes.Ret); // simply call our impl's SignalChanged method and return
  839. }
  840. #endregion
  841. #region ChangeTransaction
  842. var coreChangeTransaction = typeBuilder.DefineMethod(
  843. "<>ChangeTransaction",
  844. virtualMemberMethod,
  845. typeof(IDisposable), Type.EmptyTypes);
  846. typeBuilder.DefineMethodOverride(coreChangeTransaction, IGeneratedStore_ChangeTransaction);
  847. if (baseChangeTransaction != null)
  848. typeBuilder.DefineMethodOverride(coreChangeTransaction, baseChangeTransaction);
  849. {
  850. var il = coreChangeTransaction.GetILGenerator();
  851. il.Emit(OpCodes.Ldarg_0);
  852. if (baseChangeTransaction != null)
  853. {
  854. il.Emit(OpCodes.Ldarg_0);
  855. il.Emit(OpCodes.Call, baseChangeTransaction);
  856. }
  857. else
  858. il.Emit(OpCodes.Ldnull);
  859. il.Emit(OpCodes.Tailcall);
  860. il.Emit(OpCodes.Call, Impl.ImplChangeTransactionMethod);
  861. il.Emit(OpCodes.Ret);
  862. }
  863. #endregion
  864. #region IGeneratedStore<T>
  865. var IGeneratedStore_T_t = typeof(IGeneratedStore<>).MakeGenericType(type);
  866. typeBuilder.AddInterfaceImplementation(IGeneratedStore_T_t);
  867. var IGeneratedStore_T_CopyFrom = IGeneratedStore_T_t.GetMethod(nameof(IGeneratedStore<Config>.CopyFrom));
  868. #region IGeneratedStore<T>.CopyFrom
  869. var copyFrom = typeBuilder.DefineMethod($"<>{nameof(IGeneratedStore<Config>.CopyFrom)}", virtualMemberMethod, null, new[] { type, typeof(bool) });
  870. typeBuilder.DefineMethodOverride(copyFrom, IGeneratedStore_T_CopyFrom);
  871. {
  872. var il = copyFrom.GetILGenerator();
  873. var transactionLocal = il.DeclareLocal(IDisposable_t);
  874. var startLock = il.DefineLabel();
  875. il.Emit(OpCodes.Ldarg_2);
  876. il.Emit(OpCodes.Brfalse, startLock);
  877. il.Emit(OpCodes.Ldarg_0);
  878. il.Emit(OpCodes.Call, coreChangeTransaction); // take the write lock
  879. il.Emit(OpCodes.Stloc, transactionLocal);
  880. il.MarkLabel(startLock);
  881. var GetLocal = MakeGetLocal(il);
  882. foreach (var member in structure)
  883. {
  884. il.BeginExceptionBlock();
  885. EmitStore(il, member, il =>
  886. {
  887. EmitLoad(il, member, il => il.Emit(OpCodes.Ldarg_1));
  888. EmitCorrectMember(il, member, false, false, GetLocal);
  889. });
  890. il.BeginCatchBlock(typeof(Exception));
  891. EmitWarnException(il, $"Error while copying from member {member.Name}");
  892. il.EndExceptionBlock();
  893. }
  894. if (notifyChanged != null)
  895. {
  896. foreach (var member in structure)
  897. {
  898. il.Emit(OpCodes.Ldarg_0);
  899. il.Emit(OpCodes.Ldstr, member.Name);
  900. il.Emit(OpCodes.Call, notifyChanged);
  901. }
  902. }
  903. var endLock = il.DefineLabel();
  904. il.Emit(OpCodes.Ldarg_2);
  905. il.Emit(OpCodes.Brfalse, endLock);
  906. il.Emit(OpCodes.Ldloc, transactionLocal);
  907. il.Emit(OpCodes.Callvirt, IDisposable_Dispose);
  908. il.MarkLabel(endLock);
  909. il.Emit(OpCodes.Ret);
  910. }
  911. #endregion
  912. #endregion
  913. #region base.CopyFrom
  914. if (baseCopyFrom != null)
  915. {
  916. var pubCopyFrom = typeBuilder.DefineMethod(
  917. baseCopyFrom.Name,
  918. virtualMemberMethod,
  919. null, new[] { type });
  920. typeBuilder.DefineMethodOverride(pubCopyFrom, baseCopyFrom);
  921. {
  922. var il = pubCopyFrom.GetILGenerator();
  923. il.Emit(OpCodes.Ldarg_0);
  924. il.Emit(OpCodes.Call, coreChangeTransaction);
  925. il.Emit(OpCodes.Ldarg_0);
  926. il.Emit(OpCodes.Ldarg_1);
  927. il.Emit(OpCodes.Ldc_I4_0);
  928. il.Emit(OpCodes.Call, copyFrom); // call internal
  929. il.Emit(OpCodes.Ldarg_0);
  930. il.Emit(OpCodes.Ldarg_1);
  931. il.Emit(OpCodes.Call, baseCopyFrom); // call base
  932. il.Emit(OpCodes.Tailcall);
  933. il.Emit(OpCodes.Callvirt, IDisposable_Dispose); // dispose transaction (which calls changed)
  934. il.Emit(OpCodes.Ret);
  935. }
  936. }
  937. #endregion
  938. #region Members
  939. foreach (var member in structure.Where(m => m.IsVirtual))
  940. { // IsVirtual implies !IsField
  941. var prop = member.Member as PropertyInfo;
  942. var get = prop.GetGetMethod(true);
  943. var set = prop.GetSetMethod(true);
  944. var propBuilder = typeBuilder.DefineProperty($"{member.Name}#", PropertyAttributes.None, member.Type, null);
  945. var propGet = typeBuilder.DefineMethod($"<g>{propBuilder.Name}", virtualPropertyMethodAttr, member.Type, Type.EmptyTypes);
  946. propBuilder.SetGetMethod(propGet);
  947. typeBuilder.DefineMethodOverride(propGet, get);
  948. {
  949. var il = propGet.GetILGenerator();
  950. var local = il.DeclareLocal(member.Type);
  951. il.Emit(OpCodes.Ldarg_0);
  952. il.Emit(OpCodes.Call, Impl.ImplTakeReadMethod); // take the read lock
  953. il.BeginExceptionBlock();
  954. il.Emit(OpCodes.Ldarg_0);
  955. il.Emit(OpCodes.Call, get); // call base getter
  956. il.Emit(OpCodes.Stloc, local);
  957. il.BeginFinallyBlock();
  958. il.Emit(OpCodes.Ldarg_0);
  959. il.Emit(OpCodes.Call, Impl.ImplReleaseReadMethod); // release the read lock
  960. il.EndExceptionBlock();
  961. il.Emit(OpCodes.Ldloc, local);
  962. il.Emit(OpCodes.Ret);
  963. }
  964. var propSet = typeBuilder.DefineMethod($"<s>{propBuilder.Name}", virtualPropertyMethodAttr, null, new[] { member.Type });
  965. propBuilder.SetSetMethod(propSet);
  966. typeBuilder.DefineMethodOverride(propSet, set);
  967. { // TODO: decide if i want to correct the value before or after i take the write lock
  968. var il = propSet.GetILGenerator();
  969. var transactionLocal = il.DeclareLocal(IDisposable_t);
  970. var GetLocal = MakeGetLocal(il);
  971. il.Emit(OpCodes.Ldarg_0);
  972. il.Emit(OpCodes.Call, coreChangeTransaction); // take the write lock
  973. il.Emit(OpCodes.Stloc, transactionLocal);
  974. il.BeginExceptionBlock();
  975. il.Emit(OpCodes.Ldarg_0);
  976. il.Emit(OpCodes.Ldarg_1);
  977. EmitCorrectMember(il, member, false, false, GetLocal);
  978. il.Emit(OpCodes.Call, set);
  979. il.BeginFinallyBlock();
  980. il.Emit(OpCodes.Ldloc, transactionLocal);
  981. il.Emit(OpCodes.Callvirt, IDisposable_Dispose);
  982. il.EndExceptionBlock();
  983. if (notifyChanged != null)
  984. {
  985. il.Emit(OpCodes.Ldarg_0);
  986. il.Emit(OpCodes.Ldstr, member.Name);
  987. il.Emit(OpCodes.Call, notifyChanged);
  988. }
  989. il.Emit(OpCodes.Ret);
  990. }
  991. }
  992. #endregion
  993. var genType = typeBuilder.CreateType();
  994. var parentParam = Expression.Parameter(typeof(IGeneratedStore), "parent");
  995. var creatorDel = Expression.Lambda<GeneratedStoreCreator>(
  996. Expression.New(ctor, parentParam), parentParam
  997. ).Compile();
  998. return (creatorDel, genType);
  999. }
  1000. #region Logs
  1001. private static readonly MethodInfo LogErrorMethod = typeof(GeneratedStore).GetMethod(nameof(LogError), BindingFlags.NonPublic | BindingFlags.Static);
  1002. internal static void LogError(Type expected, Type found, string message)
  1003. {
  1004. Logger.config.Notice($"{message}{(expected == null ? "" : $" (expected {expected}, found {found?.ToString() ?? "null"})")}");
  1005. }
  1006. private static readonly MethodInfo LogWarningMethod = typeof(GeneratedStore).GetMethod(nameof(LogWarning), BindingFlags.NonPublic | BindingFlags.Static);
  1007. internal static void LogWarning(string message)
  1008. {
  1009. Logger.config.Warn(message);
  1010. }
  1011. private static readonly MethodInfo LogWarningExceptionMethod = typeof(GeneratedStore).GetMethod(nameof(LogWarningException), BindingFlags.NonPublic | BindingFlags.Static);
  1012. internal static void LogWarningException(Exception exception)
  1013. {
  1014. Logger.config.Warn(exception);
  1015. }
  1016. #endregion
  1017. #region Correction
  1018. private static bool NeedsCorrection(SerializedMemberInfo member)
  1019. {
  1020. var expectType = GetExpectedValueTypeForType(member.IsNullable ? member.NullableWrappedType : member.Type);
  1021. if (expectType == typeof(Map)) // TODO: make this slightly saner
  1022. return true;
  1023. return false;
  1024. }
  1025. // expects start value on stack, exits with final value on stack
  1026. private static void EmitCorrectMember(ILGenerator il, SerializedMemberInfo member, bool shouldLock, bool alwaysNew, GetLocal GetLocal)
  1027. {
  1028. if (!NeedsCorrection(member)) return;
  1029. var endLabel = il.DefineLabel();
  1030. if (member.IsNullable)
  1031. {
  1032. il.Emit(OpCodes.Dup);
  1033. il.Emit(OpCodes.Call, member.Nullable_HasValue.GetGetMethod());
  1034. il.Emit(OpCodes.Brfalse, endLabel);
  1035. il.Emit(OpCodes.Call, member.Nullable_Value.GetGetMethod());
  1036. }
  1037. // TODO: impl the rest of this
  1038. // currently the only thing for this is where expect == Map, so do generate shit
  1039. var copyFrom = typeof(IGeneratedStore<>).MakeGenericType(member.Type).GetMethod(nameof(IGeneratedStore<Config>.CopyFrom));
  1040. var noCreate = il.DefineLabel();
  1041. var valLocal = GetLocal(member.Type);
  1042. if (!alwaysNew)
  1043. {
  1044. il.Emit(OpCodes.Dup);
  1045. il.Emit(OpCodes.Isinst, typeof(IGeneratedStore));
  1046. il.Emit(OpCodes.Brtrue_S, endLabel); // our input is already something we like
  1047. }
  1048. il.Emit(OpCodes.Stloc, valLocal);
  1049. if (!alwaysNew)
  1050. {
  1051. EmitLoad(il, member, il => il.Emit(OpCodes.Ldarg_0));
  1052. il.Emit(OpCodes.Dup);
  1053. il.Emit(OpCodes.Isinst, typeof(IGeneratedStore));
  1054. il.Emit(OpCodes.Brtrue_S, noCreate);
  1055. il.Emit(OpCodes.Pop);
  1056. }
  1057. EmitCreateChildGenerated(il, member.Type);
  1058. il.MarkLabel(noCreate);
  1059. il.Emit(OpCodes.Dup);
  1060. il.Emit(OpCodes.Ldloc, valLocal);
  1061. il.Emit(shouldLock ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0);
  1062. il.Emit(OpCodes.Callvirt, copyFrom);
  1063. // TODO: impl the rest of this
  1064. if (member.IsNullable)
  1065. il.Emit(OpCodes.Newobj, member.Nullable_Construct);
  1066. il.MarkLabel(endLabel);
  1067. }
  1068. #endregion
  1069. #region Utility
  1070. private delegate LocalBuilder GetLocal(Type type, int idx = 0);
  1071. private static GetLocal MakeGetLocal(ILGenerator il)
  1072. { // TODO: improve this shit a bit so that i can release a hold of a variable and do more auto managing
  1073. var locals = new List<LocalBuilder>();
  1074. LocalBuilder GetLocal(Type ty, int i = 0)
  1075. {
  1076. var builder = locals.Where(b => b.LocalType == ty).Skip(i).FirstOrDefault();
  1077. if (builder == null)
  1078. {
  1079. builder = il.DeclareLocal(ty);
  1080. locals.Add(builder);
  1081. }
  1082. return builder;
  1083. }
  1084. return GetLocal;
  1085. }
  1086. private static void EmitLoad(ILGenerator il, SerializedMemberInfo member, Action<ILGenerator> thisarg = null)
  1087. {
  1088. if (thisarg == null)
  1089. thisarg = il => il.Emit(OpCodes.Ldarg_0);
  1090. thisarg(il); // load this
  1091. if (member.IsField)
  1092. il.Emit(OpCodes.Ldfld, member.Member as FieldInfo);
  1093. else
  1094. { // member is a property
  1095. var prop = member.Member as PropertyInfo;
  1096. var getter = prop.GetGetMethod();
  1097. if (getter == null) throw new InvalidOperationException($"Property {member.Name} does not have a getter and is not ignored");
  1098. il.Emit(OpCodes.Call, getter);
  1099. }
  1100. }
  1101. private static void EmitStore(ILGenerator il, SerializedMemberInfo member, Action<ILGenerator> value)
  1102. {
  1103. il.Emit(OpCodes.Ldarg_0); // load this
  1104. value(il);
  1105. if (member.IsField)
  1106. il.Emit(OpCodes.Stfld, member.Member as FieldInfo);
  1107. else
  1108. { // member is a property
  1109. var prop = member.Member as PropertyInfo;
  1110. var setter = prop.GetSetMethod();
  1111. if (setter == null) throw new InvalidOperationException($"Property {member.Name} does not have a setter and is not ignored");
  1112. il.Emit(OpCodes.Call, setter);
  1113. }
  1114. }
  1115. private static void EmitWarnException(ILGenerator il, string v)
  1116. {
  1117. il.Emit(OpCodes.Ldstr, v);
  1118. il.Emit(OpCodes.Call, LogWarningMethod);
  1119. il.Emit(OpCodes.Call, LogWarningExceptionMethod);
  1120. }
  1121. private static void EmitLogError(ILGenerator il, string message, bool tailcall = false, Action<ILGenerator> expected = null, Action<ILGenerator> found = null)
  1122. {
  1123. if (expected == null) expected = il => il.Emit(OpCodes.Ldnull);
  1124. if (found == null) found = il => il.Emit(OpCodes.Ldnull);
  1125. expected(il);
  1126. found(il);
  1127. il.Emit(OpCodes.Ldstr, message);
  1128. if (tailcall) il.Emit(OpCodes.Tailcall);
  1129. il.Emit(OpCodes.Call, LogErrorMethod);
  1130. }
  1131. private static readonly MethodInfo Type_GetTypeFromHandle = typeof(Type).GetMethod(nameof(Type.GetTypeFromHandle));
  1132. private static void EmitTypeof(ILGenerator il, Type type)
  1133. {
  1134. il.Emit(OpCodes.Ldtoken, type);
  1135. il.Emit(OpCodes.Call, Type_GetTypeFromHandle);
  1136. }
  1137. private static Type IDisposable_t = typeof(IDisposable);
  1138. private static MethodInfo IDisposable_Dispose = IDisposable_t.GetMethod(nameof(IDisposable.Dispose));
  1139. private static Type Decimal_t = typeof(decimal);
  1140. private static ConstructorInfo Decimal_FromFloat = Decimal_t.GetConstructor(new[] { typeof(float) });
  1141. private static ConstructorInfo Decimal_FromDouble = Decimal_t.GetConstructor(new[] { typeof(double) });
  1142. private static ConstructorInfo Decimal_FromInt = Decimal_t.GetConstructor(new[] { typeof(int) });
  1143. private static ConstructorInfo Decimal_FromUInt = Decimal_t.GetConstructor(new[] { typeof(uint) });
  1144. private static ConstructorInfo Decimal_FromLong = Decimal_t.GetConstructor(new[] { typeof(long) });
  1145. private static ConstructorInfo Decimal_FromULong = Decimal_t.GetConstructor(new[] { typeof(ulong) });
  1146. private static void EmitNumberConvertTo(ILGenerator il, Type to, Type from)
  1147. { // WARNING: THIS USES THE NO-OVERFLOW OPCODES
  1148. if (to == from) return;
  1149. if (to == Decimal_t)
  1150. {
  1151. if (from == typeof(float)) il.Emit(OpCodes.Newobj, Decimal_FromFloat);
  1152. else if (from == typeof(double)) il.Emit(OpCodes.Newobj, Decimal_FromDouble);
  1153. else if (from == typeof(long)) il.Emit(OpCodes.Newobj, Decimal_FromLong);
  1154. else if (from == typeof(ulong)) il.Emit(OpCodes.Newobj, Decimal_FromULong);
  1155. else if (from == typeof(int)) il.Emit(OpCodes.Newobj, Decimal_FromInt);
  1156. else if (from == typeof(uint)) il.Emit(OpCodes.Newobj, Decimal_FromUInt);
  1157. else if (from == typeof(IntPtr))
  1158. {
  1159. EmitNumberConvertTo(il, typeof(long), from);
  1160. EmitNumberConvertTo(il, to, typeof(long));
  1161. }
  1162. else if (from == typeof(UIntPtr))
  1163. {
  1164. EmitNumberConvertTo(il, typeof(ulong), from);
  1165. EmitNumberConvertTo(il, to, typeof(ulong));
  1166. }
  1167. else
  1168. { // if the source is anything else, we first convert to int because that can contain all other values
  1169. EmitNumberConvertTo(il, typeof(int), from);
  1170. EmitNumberConvertTo(il, to, typeof(int));
  1171. };
  1172. }
  1173. else if (from == Decimal_t)
  1174. {
  1175. if (to == typeof(IntPtr))
  1176. {
  1177. EmitNumberConvertTo(il, typeof(long), from);
  1178. EmitNumberConvertTo(il, to, typeof(long));
  1179. }
  1180. else if (to == typeof(UIntPtr))
  1181. {
  1182. EmitNumberConvertTo(il, typeof(ulong), from);
  1183. EmitNumberConvertTo(il, to, typeof(ulong));
  1184. }
  1185. else
  1186. {
  1187. var method = Decimal_t.GetMethod($"To{to.Name}"); // conveniently, this is the pattern of the to* names
  1188. il.Emit(OpCodes.Call, method);
  1189. }
  1190. }
  1191. else if (to == typeof(IntPtr)) il.Emit(OpCodes.Conv_I);
  1192. else if (to == typeof(UIntPtr)) il.Emit(OpCodes.Conv_U);
  1193. else if (to == typeof(sbyte)) il.Emit(OpCodes.Conv_I1);
  1194. else if (to == typeof(byte)) il.Emit(OpCodes.Conv_U1);
  1195. else if (to == typeof(short)) il.Emit(OpCodes.Conv_I2);
  1196. else if (to == typeof(ushort)) il.Emit(OpCodes.Conv_U2);
  1197. else if (to == typeof(int)) il.Emit(OpCodes.Conv_I4);
  1198. else if (to == typeof(uint)) il.Emit(OpCodes.Conv_U4);
  1199. else if (to == typeof(long)) il.Emit(OpCodes.Conv_I8);
  1200. else if (to == typeof(ulong)) il.Emit(OpCodes.Conv_U8);
  1201. else if (to == typeof(float))
  1202. {
  1203. if (from == typeof(byte)
  1204. || from == typeof(ushort)
  1205. || from == typeof(uint)
  1206. || from == typeof(ulong)
  1207. || from == typeof(UIntPtr)) il.Emit(OpCodes.Conv_R_Un);
  1208. il.Emit(OpCodes.Conv_R4);
  1209. }
  1210. else if (to == typeof(double))
  1211. {
  1212. if (from == typeof(byte)
  1213. || from == typeof(ushort)
  1214. || from == typeof(uint)
  1215. || from == typeof(ulong)
  1216. || from == typeof(UIntPtr)) il.Emit(OpCodes.Conv_R_Un);
  1217. il.Emit(OpCodes.Conv_R8);
  1218. }
  1219. }
  1220. private static void EmitCreateChildGenerated(ILGenerator il, Type childType)
  1221. {
  1222. var method = CreateGParent.MakeGenericMethod(childType);
  1223. il.Emit(OpCodes.Ldarg_0);
  1224. il.Emit(OpCodes.Call, method);
  1225. }
  1226. #endregion
  1227. #region Serialize
  1228. // emit takes no args, leaves Value at top of stack
  1229. private static void EmitSerializeMember(ILGenerator il, SerializedMemberInfo member, GetLocal GetLocal)
  1230. {
  1231. EmitLoad(il, member);
  1232. var endSerialize = il.DefineLabel();
  1233. if (member.AllowNull)
  1234. {
  1235. var passedNull = il.DefineLabel();
  1236. il.Emit(OpCodes.Dup);
  1237. if (member.IsNullable)
  1238. il.Emit(OpCodes.Call, member.Nullable_HasValue.GetGetMethod());
  1239. il.Emit(OpCodes.Brtrue, passedNull);
  1240. il.Emit(OpCodes.Pop);
  1241. il.Emit(OpCodes.Ldnull);
  1242. il.Emit(OpCodes.Br, endSerialize);
  1243. il.MarkLabel(passedNull);
  1244. }
  1245. if (member.IsNullable)
  1246. il.Emit(OpCodes.Call, member.Nullable_Value.GetGetMethod());
  1247. var targetType = GetExpectedValueTypeForType(member.Type);
  1248. if (member.HasConverter)
  1249. {
  1250. var stlocal = GetLocal(member.Type);
  1251. var valLocal = GetLocal(typeof(Value));
  1252. il.Emit(OpCodes.Stloc, stlocal);
  1253. il.BeginExceptionBlock();
  1254. il.Emit(OpCodes.Ldsfld, member.ConverterField);
  1255. il.Emit(OpCodes.Ldloc, stlocal);
  1256. if (member.IsGenericConverter)
  1257. {
  1258. var toValueBase = member.ConverterBase.GetMethod(nameof(ValueConverter<int>.ToValue),
  1259. new[] { member.ConverterTarget, typeof(object) });
  1260. var toValue = member.Converter.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
  1261. .FirstOrDefault(m => m.GetBaseDefinition() == toValueBase) ?? toValueBase;
  1262. il.Emit(OpCodes.Ldarg_0);
  1263. il.Emit(OpCodes.Call, toValue);
  1264. }
  1265. else
  1266. {
  1267. var toValueBase = typeof(IValueConverter).GetMethod(nameof(IValueConverter.ToValue),
  1268. new[] { typeof(object), typeof(object) });
  1269. var toValue = member.Converter.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
  1270. .FirstOrDefault(m => m.GetBaseDefinition() == toValueBase) ?? toValueBase;
  1271. il.Emit(OpCodes.Box);
  1272. il.Emit(OpCodes.Ldarg_0);
  1273. il.Emit(OpCodes.Call, toValue);
  1274. }
  1275. il.Emit(OpCodes.Stloc, valLocal);
  1276. il.BeginCatchBlock(typeof(Exception));
  1277. EmitWarnException(il, "Error serializing member using converter");
  1278. il.Emit(OpCodes.Ldnull);
  1279. il.Emit(OpCodes.Stloc, valLocal);
  1280. il.EndExceptionBlock();
  1281. il.Emit(OpCodes.Ldloc, valLocal);
  1282. }
  1283. else if (targetType == typeof(Text))
  1284. { // only happens when arg is a string or char
  1285. var TextCreate = typeof(Value).GetMethod(nameof(Value.Text));
  1286. if (member.Type == typeof(char))
  1287. {
  1288. var strFromChar = typeof(char).GetMethod(nameof(char.ToString), new[] { typeof(char) });
  1289. il.Emit(OpCodes.Call, strFromChar);
  1290. }
  1291. il.Emit(OpCodes.Call, TextCreate);
  1292. }
  1293. else if (targetType == typeof(Boolean))
  1294. {
  1295. var BoolCreate = typeof(Value).GetMethod(nameof(Value.Bool));
  1296. il.Emit(OpCodes.Call, BoolCreate);
  1297. }
  1298. else if (targetType == typeof(Integer))
  1299. {
  1300. var IntCreate = typeof(Value).GetMethod(nameof(Value.Integer));
  1301. EmitNumberConvertTo(il, IntCreate.GetParameters()[0].ParameterType, member.Type);
  1302. il.Emit(OpCodes.Call, IntCreate);
  1303. }
  1304. else if (targetType == typeof(FloatingPoint))
  1305. {
  1306. var FloatCreate = typeof(Value).GetMethod(nameof(Value.Float));
  1307. EmitNumberConvertTo(il, FloatCreate.GetParameters()[0].ParameterType, member.Type);
  1308. il.Emit(OpCodes.Call, FloatCreate);
  1309. }
  1310. else if (targetType == typeof(List))
  1311. {
  1312. // TODO: impl this (enumerables)
  1313. il.Emit(OpCodes.Pop);
  1314. il.Emit(OpCodes.Ldnull);
  1315. }
  1316. else if (targetType == typeof(Map))
  1317. {
  1318. // TODO: support other aggregate types
  1319. // for now, we assume that its a generated type implementing IGeneratedStore
  1320. var IGeneratedStore_Serialize = typeof(IGeneratedStore).GetMethod(nameof(IGeneratedStore.Serialize));
  1321. il.Emit(OpCodes.Callvirt, IGeneratedStore_Serialize);
  1322. }
  1323. il.MarkLabel(endSerialize);
  1324. }
  1325. #endregion
  1326. #region Deserialize
  1327. private static Type GetExpectedValueTypeForType(Type valT)
  1328. {
  1329. if (typeof(Value).IsAssignableFrom(valT)) // this is a Value subtype
  1330. return valT;
  1331. if (valT == typeof(string)
  1332. || valT == typeof(char)) return typeof(Text);
  1333. if (valT == typeof(bool)) return typeof(Boolean);
  1334. if (valT == typeof(byte)
  1335. || valT == typeof(sbyte)
  1336. || valT == typeof(short)
  1337. || valT == typeof(ushort)
  1338. || valT == typeof(int)
  1339. || valT == typeof(uint)
  1340. || valT == typeof(long)
  1341. || valT == typeof(IntPtr)) return typeof(Integer);
  1342. if (valT == typeof(float)
  1343. || valT == typeof(double)
  1344. || valT == typeof(decimal)
  1345. || valT == typeof(ulong) // ulong gets put into this, because decimal can hold it
  1346. || valT == typeof(UIntPtr)) return typeof(FloatingPoint);
  1347. if (typeof(IEnumerable).IsAssignableFrom(valT)) return typeof(List);
  1348. // TODO: fill this out the rest of the way
  1349. return typeof(Map); // default for various objects
  1350. }
  1351. private static void EmitDeserializeGeneratedValue(ILGenerator il, SerializedMemberInfo member, Type srcType, GetLocal GetLocal)
  1352. {
  1353. var IGeneratedStore_Deserialize = typeof(IGeneratedStore).GetMethod(nameof(IGeneratedStore.Deserialize));
  1354. var valuel = GetLocal(srcType, 0);
  1355. var noCreate = il.DefineLabel();
  1356. il.Emit(OpCodes.Stloc, valuel);
  1357. EmitLoad(il, member, il => il.Emit(OpCodes.Ldarg_0));
  1358. il.Emit(OpCodes.Dup);
  1359. il.Emit(OpCodes.Isinst, typeof(IGeneratedStore));
  1360. il.Emit(OpCodes.Brtrue_S, noCreate);
  1361. il.Emit(OpCodes.Pop);
  1362. EmitCreateChildGenerated(il, member.Type);
  1363. il.MarkLabel(noCreate);
  1364. il.Emit(OpCodes.Dup);
  1365. il.Emit(OpCodes.Ldloc, valuel);
  1366. il.Emit(OpCodes.Callvirt, IGeneratedStore_Deserialize);
  1367. }
  1368. private static void EmitDeserializeNullable(ILGenerator il, SerializedMemberInfo member, Type expected, GetLocal GetLocal)
  1369. {
  1370. EmitDeserializeValue(il, member, member.NullableWrappedType, expected, GetLocal);
  1371. il.Emit(OpCodes.Newobj, member.Nullable_Construct);
  1372. }
  1373. // top of stack is the Value to deserialize; the type will be as returned from GetExpectedValueTypeForType
  1374. // after, top of stack will be thing to write to field
  1375. private static void EmitDeserializeValue(ILGenerator il, SerializedMemberInfo member, Type targetType, Type expected, GetLocal GetLocal)
  1376. {
  1377. if (typeof(Value).IsAssignableFrom(targetType)) return; // do nothing
  1378. if (expected == typeof(Text))
  1379. {
  1380. var getter = expected.GetProperty(nameof(Text.Value)).GetGetMethod();
  1381. il.Emit(OpCodes.Call, getter);
  1382. if (targetType == typeof(char))
  1383. {
  1384. var strIndex = typeof(string).GetProperty("Chars").GetGetMethod(); // string's indexer is specially named Chars
  1385. il.Emit(OpCodes.Ldc_I4_0);
  1386. il.Emit(OpCodes.Call, strIndex);
  1387. }
  1388. }
  1389. else if (expected == typeof(Boolean))
  1390. {
  1391. var getter = expected.GetProperty(nameof(Boolean.Value)).GetGetMethod();
  1392. il.Emit(OpCodes.Call, getter);
  1393. }
  1394. else if (expected == typeof(Integer))
  1395. {
  1396. var getter = expected.GetProperty(nameof(Integer.Value)).GetGetMethod();
  1397. il.Emit(OpCodes.Call, getter);
  1398. EmitNumberConvertTo(il, targetType, getter.ReturnType);
  1399. }
  1400. else if (expected == typeof(FloatingPoint))
  1401. {
  1402. var getter = expected.GetProperty(nameof(FloatingPoint.Value)).GetGetMethod();
  1403. il.Emit(OpCodes.Call, getter);
  1404. EmitNumberConvertTo(il, targetType, getter.ReturnType);
  1405. } // TODO: implement stuff for lists and maps of various types (probably call out somewhere else to figure out what to do)
  1406. else if (expected == typeof(Map))
  1407. {
  1408. EmitDeserializeGeneratedValue(il, member, expected, GetLocal);
  1409. }
  1410. else
  1411. {
  1412. il.Emit(OpCodes.Pop);
  1413. il.Emit(OpCodes.Ldnull);
  1414. }
  1415. }
  1416. private static void EmitDeserializeConverter(ILGenerator il, SerializedMemberInfo member, Label nextLabel, GetLocal GetLocal)
  1417. {
  1418. var stlocal = GetLocal(typeof(Value));
  1419. var valLocal = GetLocal(member.Type);
  1420. il.Emit(OpCodes.Stloc, stlocal);
  1421. il.BeginExceptionBlock();
  1422. il.Emit(OpCodes.Ldsfld, member.ConverterField);
  1423. il.Emit(OpCodes.Ldloc, stlocal);
  1424. il.Emit(OpCodes.Ldarg_0);
  1425. if (member.IsGenericConverter)
  1426. {
  1427. var fromValueBase = member.ConverterBase.GetMethod(nameof(ValueConverter<int>.FromValue),
  1428. new[] { typeof(Value), typeof(object) });
  1429. var fromValue = member.Converter.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
  1430. .FirstOrDefault(m => m.GetBaseDefinition() == fromValueBase) ?? fromValueBase;
  1431. il.Emit(OpCodes.Call, fromValue);
  1432. }
  1433. else
  1434. {
  1435. var fromValueBase = typeof(IValueConverter).GetMethod(nameof(IValueConverter.FromValue),
  1436. new[] { typeof(Value), typeof(object) });
  1437. var fromValue = member.Converter.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
  1438. .FirstOrDefault(m => m.GetBaseDefinition() == fromValueBase) ?? fromValueBase;
  1439. il.Emit(OpCodes.Call, fromValue);
  1440. if (member.Type.IsValueType)
  1441. il.Emit(OpCodes.Unbox);
  1442. }
  1443. il.Emit(OpCodes.Stloc, valLocal);
  1444. il.BeginCatchBlock(typeof(Exception));
  1445. EmitWarnException(il, "Error occurred while deserializing");
  1446. il.Emit(OpCodes.Leave, nextLabel);
  1447. il.EndExceptionBlock();
  1448. il.Emit(OpCodes.Ldloc, valLocal);
  1449. }
  1450. // emit takes the value being deserialized, logs on error, leaves nothing on stack
  1451. private static void EmitDeserializeMember(ILGenerator il, SerializedMemberInfo member, Label nextLabel, Action<ILGenerator> getValue, GetLocal GetLocal)
  1452. {
  1453. var Object_GetType = typeof(object).GetMethod(nameof(Object.GetType));
  1454. var implLabel = il.DefineLabel();
  1455. var passedTypeCheck = il.DefineLabel();
  1456. var expectType = GetExpectedValueTypeForType(member.IsNullable ? member.NullableWrappedType : member.Type);
  1457. il.Emit(OpCodes.Dup);
  1458. il.Emit(OpCodes.Brtrue_S, implLabel); // null check
  1459. if (!member.AllowNull)
  1460. {
  1461. il.Emit(OpCodes.Pop);
  1462. EmitLogError(il, $"Member {member.Name} ({member.Type}) not nullable", tailcall: false,
  1463. expected: il => EmitTypeof(il, expectType));
  1464. il.Emit(OpCodes.Br, nextLabel);
  1465. }
  1466. else if (member.IsNullable)
  1467. {
  1468. il.Emit(OpCodes.Pop);
  1469. var valTLocal = GetLocal(member.Type, 0);
  1470. il.Emit(OpCodes.Ldloca, valTLocal);
  1471. il.Emit(OpCodes.Initobj, member.Type);
  1472. EmitStore(il, member, il => il.Emit(OpCodes.Ldloc, valTLocal));
  1473. il.Emit(OpCodes.Br, nextLabel);
  1474. }
  1475. else
  1476. {
  1477. il.Emit(OpCodes.Pop);
  1478. EmitStore(il, member, il => il.Emit(OpCodes.Ldnull));
  1479. il.Emit(OpCodes.Br, nextLabel);
  1480. }
  1481. if (!member.HasConverter)
  1482. {
  1483. il.MarkLabel(implLabel);
  1484. il.Emit(OpCodes.Isinst, expectType); //replaces on stack
  1485. il.Emit(OpCodes.Dup); // duplicate cloned value
  1486. il.Emit(OpCodes.Brtrue, passedTypeCheck); // null check
  1487. }
  1488. var errorHandle = il.DefineLabel();
  1489. // special cases to handle coersion between Float and Int
  1490. if (member.HasConverter)
  1491. il.MarkLabel(implLabel);
  1492. else if (expectType == typeof(FloatingPoint))
  1493. {
  1494. var specialTypeCheck = il.DefineLabel();
  1495. il.Emit(OpCodes.Pop);
  1496. getValue(il);
  1497. il.Emit(OpCodes.Isinst, typeof(Integer)); //replaces on stack
  1498. il.Emit(OpCodes.Dup); // duplicate cloned value
  1499. il.Emit(OpCodes.Brfalse, errorHandle); // null check
  1500. var Integer_CoerceToFloat = typeof(Integer).GetMethod(nameof(Integer.AsFloat));
  1501. il.Emit(OpCodes.Call, Integer_CoerceToFloat);
  1502. il.Emit(OpCodes.Br, passedTypeCheck);
  1503. }
  1504. else if (expectType == typeof(Integer))
  1505. {
  1506. var specialTypeCheck = il.DefineLabel();
  1507. il.Emit(OpCodes.Pop);
  1508. getValue(il);
  1509. il.Emit(OpCodes.Isinst, typeof(FloatingPoint)); //replaces on stack
  1510. il.Emit(OpCodes.Dup); // duplicate cloned value
  1511. il.Emit(OpCodes.Brfalse, errorHandle); // null check
  1512. var Float_CoerceToInt = typeof(FloatingPoint).GetMethod(nameof(FloatingPoint.AsInteger));
  1513. il.Emit(OpCodes.Call, Float_CoerceToInt);
  1514. il.Emit(OpCodes.Br, passedTypeCheck);
  1515. }
  1516. if (!member.HasConverter)
  1517. {
  1518. il.MarkLabel(errorHandle);
  1519. il.Emit(OpCodes.Pop);
  1520. EmitLogError(il, $"Unexpected type deserializing {member.Name}", tailcall: false,
  1521. expected: il => EmitTypeof(il, expectType), found: il =>
  1522. {
  1523. getValue(il);
  1524. il.Emit(OpCodes.Callvirt, Object_GetType);
  1525. });
  1526. il.Emit(OpCodes.Br, nextLabel);
  1527. }
  1528. il.MarkLabel(passedTypeCheck);
  1529. var local = GetLocal(member.Type, 0);
  1530. if (member.HasConverter) EmitDeserializeConverter(il, member, nextLabel, GetLocal);
  1531. else if (member.IsNullable) EmitDeserializeNullable(il, member, expectType, GetLocal);
  1532. else EmitDeserializeValue(il, member, member.Type, expectType, GetLocal);
  1533. il.Emit(OpCodes.Stloc, local);
  1534. EmitStore(il, member, il => il.Emit(OpCodes.Ldloc, local));
  1535. }
  1536. #endregion
  1537. }
  1538. }