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.

1418 lines
62 KiB

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