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.

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