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.

1389 lines
61 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. // TODO: support converters
  259. bool ProcessAttributesFor(ref SerializedMemberInfo member)
  260. {
  261. var attrs = member.Member.GetCustomAttributes(true);
  262. var ignores = attrs.Select(o => o as IgnoreAttribute).NonNull();
  263. if (ignores.Any()) // we ignore
  264. {
  265. return false;
  266. }
  267. var nonNullables = attrs.Select(o => o as NonNullableAttribute).NonNull();
  268. member.Name = member.Member.Name;
  269. member.IsNullable = member.Type.IsGenericType
  270. && member.Type.GetGenericTypeDefinition() == typeof(Nullable<>);
  271. member.AllowNull = !nonNullables.Any() && (!member.Type.IsValueType || member.IsNullable);
  272. var nameAttr = attrs.Select(o => o as SerializedNameAttribute).NonNull().FirstOrDefault();
  273. if (nameAttr != null)
  274. member.Name = nameAttr.Name;
  275. member.HasConverter = false;
  276. var converterAttr = attrs.Select(o => o as UseConverterAttribute).NonNull().FirstOrDefault();
  277. if (converterAttr != null)
  278. {
  279. member.Converter = converterAttr.ConverterType;
  280. member.IsGenericConverter = converterAttr.IsGenericConverter;
  281. if (member.Converter.GetConstructor(Type.EmptyTypes) == null)
  282. {
  283. Logger.config.Warn($"{type.FullName}'s member {member.Member.Name} requests a converter that is not default-constructible");
  284. goto endConverterAttr; // is there a better control flow structure to do this?
  285. }
  286. if (member.Converter.ContainsGenericParameters)
  287. {
  288. Logger.config.Warn($"{type.FullName}'s member {member.Member.Name} requests a converter that has unfilled type parameters");
  289. goto endConverterAttr;
  290. }
  291. if (member.Converter.IsInterface || member.Converter.IsAbstract)
  292. {
  293. Logger.config.Warn($"{type.FullName}'s member {member.Member.Name} requests a converter that is not constructible");
  294. goto endConverterAttr;
  295. }
  296. var targetType = converterAttr.ConverterTargetType;
  297. if (!member.IsGenericConverter)
  298. {
  299. try
  300. {
  301. var conv = Activator.CreateInstance(converterAttr.ConverterType) as IValueConverter;
  302. targetType = conv.Type;
  303. }
  304. catch
  305. {
  306. Logger.config.Warn($"{type.FullName}'s member {member.Member.Name} requests a converter who's target type could not be determined");
  307. goto endConverterAttr;
  308. }
  309. }
  310. if (targetType != member.Type)
  311. {
  312. Logger.config.Warn($"{type.FullName}'s member {member.Member.Name} requests a converter that is not of the member's type");
  313. goto endConverterAttr;
  314. }
  315. member.ConverterTarget = targetType;
  316. if (member.IsGenericConverter)
  317. member.ConverterBase = typeof(ValueConverter<>).MakeGenericType(targetType);
  318. else
  319. member.ConverterBase = typeof(IValueConverter);
  320. member.HasConverter = true;
  321. }
  322. endConverterAttr:
  323. return true;
  324. }
  325. // only looks at public/protected properties
  326. foreach (var prop in type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
  327. {
  328. if (prop.GetSetMethod(true)?.IsPrivate ?? true)
  329. { // we enter this block if the setter is inacessible or doesn't exist
  330. continue; // ignore props without setter
  331. }
  332. if (prop.GetGetMethod(true)?.IsPrivate ?? true)
  333. { // we enter this block if the getter is inacessible or doesn't exist
  334. continue; // ignore props without getter
  335. }
  336. var smi = new SerializedMemberInfo
  337. {
  338. Member = prop,
  339. IsVirtual = (prop.GetGetMethod(true)?.IsVirtual ?? false) ||
  340. (prop.GetSetMethod(true)?.IsVirtual ?? false),
  341. IsField = false,
  342. Type = prop.PropertyType
  343. };
  344. if (!ProcessAttributesFor(ref smi)) continue;
  345. structure.Add(smi);
  346. }
  347. // only look at public/protected fields
  348. foreach (var field in type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
  349. {
  350. if (field.IsPrivate) continue;
  351. var smi = new SerializedMemberInfo
  352. {
  353. Member = field,
  354. IsVirtual = false,
  355. IsField = true,
  356. Type = field.FieldType
  357. };
  358. if (!ProcessAttributesFor(ref smi)) continue;
  359. structure.Add(smi);
  360. }
  361. #endregion
  362. #region Converter fields
  363. var uniqueConverterTypes = structure.Where(m => m.HasConverter).Select(m => m.Converter).Distinct().ToArray();
  364. var converterFields = new Dictionary<Type, FieldInfo>(uniqueConverterTypes.Length);
  365. foreach (var convType in uniqueConverterTypes)
  366. {
  367. var field = typeBuilder.DefineField($"<converter>_{convType}", convType,
  368. FieldAttributes.Private | FieldAttributes.InitOnly | FieldAttributes.Static);
  369. converterFields.Add(convType, field);
  370. foreach (var member in structure.Where(m => m.HasConverter && m.Converter == convType))
  371. member.ConverterField = field;
  372. }
  373. #endregion
  374. #region Static constructor
  375. var cctor = typeBuilder.DefineConstructor(MethodAttributes.Static, CallingConventions.Standard, Type.EmptyTypes);
  376. {
  377. var il = cctor.GetILGenerator();
  378. foreach (var kvp in converterFields)
  379. {
  380. var typeCtor = kvp.Key.GetConstructor(Type.EmptyTypes);
  381. il.Emit(OpCodes.Newobj, typeCtor);
  382. il.Emit(OpCodes.Stsfld, kvp.Value);
  383. }
  384. il.Emit(OpCodes.Ret);
  385. }
  386. #endregion
  387. #region Constructor
  388. var ctor = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new[] { typeof(IGeneratedStore) });
  389. {
  390. var il = ctor.GetILGenerator();
  391. il.Emit(OpCodes.Ldarg_0); // keep this at bottom of stack
  392. il.Emit(OpCodes.Dup);
  393. il.Emit(OpCodes.Call, baseCtor);
  394. il.Emit(OpCodes.Dup);
  395. il.Emit(OpCodes.Ldarg_1); // load parent
  396. il.Emit(OpCodes.Stfld, parentField);
  397. il.Emit(OpCodes.Dup);
  398. EmitTypeof(il, type);
  399. il.Emit(OpCodes.Stfld, typeField);
  400. il.Emit(OpCodes.Dup);
  401. il.Emit(OpCodes.Dup);
  402. il.Emit(OpCodes.Newobj, Impl.Ctor);
  403. il.Emit(OpCodes.Stfld, implField);
  404. var GetLocal = MakeGetLocal(il);
  405. foreach (var member in structure)
  406. {
  407. EmitMemberFix(il, member, GetLocal);
  408. }
  409. il.Emit(OpCodes.Pop);
  410. il.Emit(OpCodes.Ret);
  411. }
  412. #endregion
  413. const MethodAttributes propertyMethodAttr = MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig;
  414. const MethodAttributes virtualPropertyMethodAttr = propertyMethodAttr | MethodAttributes.Virtual | MethodAttributes.Final;
  415. const MethodAttributes virtualMemberMethod = MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.Final;
  416. #region IGeneratedStore
  417. typeBuilder.AddInterfaceImplementation(typeof(IGeneratedStore));
  418. var IGeneratedStore_t = typeof(IGeneratedStore);
  419. var IGeneratedStore_GetImpl = IGeneratedStore_t.GetProperty(nameof(IGeneratedStore.Impl)).GetGetMethod();
  420. var IGeneratedStore_GetType = IGeneratedStore_t.GetProperty(nameof(IGeneratedStore.Type)).GetGetMethod();
  421. var IGeneratedStore_GetParent = IGeneratedStore_t.GetProperty(nameof(IGeneratedStore.Parent)).GetGetMethod();
  422. var IGeneratedStore_Serialize = IGeneratedStore_t.GetMethod(nameof(IGeneratedStore.Serialize));
  423. var IGeneratedStore_Deserialize = IGeneratedStore_t.GetMethod(nameof(IGeneratedStore.Deserialize));
  424. var IGeneratedStore_OnReload = IGeneratedStore_t.GetMethod(nameof(IGeneratedStore.OnReload));
  425. var IGeneratedStore_Changed = IGeneratedStore_t.GetMethod(nameof(IGeneratedStore.Changed));
  426. #region IGeneratedStore.OnReload
  427. var onReload = typeBuilder.DefineMethod($"<>{nameof(IGeneratedStore.OnReload)}", virtualMemberMethod, null, Type.EmptyTypes);
  428. typeBuilder.DefineMethodOverride(onReload, IGeneratedStore_OnReload);
  429. if (baseOnReload != null) typeBuilder.DefineMethodOverride(onReload, baseOnReload);
  430. {
  431. var il = onReload.GetILGenerator();
  432. if (baseOnReload != null)
  433. {
  434. il.Emit(OpCodes.Ldarg_0); // load this
  435. il.Emit(OpCodes.Tailcall);
  436. il.Emit(OpCodes.Call, baseOnReload); // load impl field
  437. }
  438. il.Emit(OpCodes.Ret);
  439. }
  440. #endregion
  441. #region IGeneratedStore.Impl
  442. var implProp = typeBuilder.DefineProperty(nameof(IGeneratedStore.Impl), PropertyAttributes.None, typeof(Impl), null);
  443. var implPropGet = typeBuilder.DefineMethod($"<g>{nameof(IGeneratedStore.Impl)}", virtualPropertyMethodAttr, implProp.PropertyType, Type.EmptyTypes);
  444. implProp.SetGetMethod(implPropGet);
  445. typeBuilder.DefineMethodOverride(implPropGet, IGeneratedStore_GetImpl);
  446. {
  447. var il = implPropGet.GetILGenerator();
  448. il.Emit(OpCodes.Ldarg_0); // load this
  449. il.Emit(OpCodes.Ldfld, implField); // load impl field
  450. il.Emit(OpCodes.Ret);
  451. }
  452. #endregion
  453. #region IGeneratedStore.Type
  454. var typeProp = typeBuilder.DefineProperty(nameof(IGeneratedStore.Type), PropertyAttributes.None, typeof(Type), null);
  455. var typePropGet = typeBuilder.DefineMethod($"<g>{nameof(IGeneratedStore.Type)}", virtualPropertyMethodAttr, typeProp.PropertyType, Type.EmptyTypes);
  456. typeProp.SetGetMethod(typePropGet);
  457. typeBuilder.DefineMethodOverride(typePropGet, IGeneratedStore_GetType);
  458. {
  459. var il = typePropGet.GetILGenerator();
  460. il.Emit(OpCodes.Ldarg_0); // load this
  461. il.Emit(OpCodes.Ldfld, typeField); // load impl field
  462. il.Emit(OpCodes.Ret);
  463. }
  464. #endregion
  465. #region IGeneratedStore.Parent
  466. var parentProp = typeBuilder.DefineProperty(nameof(IGeneratedStore.Parent), PropertyAttributes.None, typeof(IGeneratedStore), null);
  467. var parentPropGet = typeBuilder.DefineMethod($"<g>{nameof(IGeneratedStore.Parent)}", virtualPropertyMethodAttr, parentProp.PropertyType, Type.EmptyTypes);
  468. parentProp.SetGetMethod(parentPropGet);
  469. typeBuilder.DefineMethodOverride(parentPropGet, IGeneratedStore_GetParent);
  470. {
  471. var il = parentPropGet.GetILGenerator();
  472. il.Emit(OpCodes.Ldarg_0); // load this
  473. il.Emit(OpCodes.Ldfld, parentField); // load impl field
  474. il.Emit(OpCodes.Ret);
  475. }
  476. #endregion
  477. #region IGeneratedStore.Serialize
  478. var serializeGen = typeBuilder.DefineMethod($"<>{nameof(IGeneratedStore.Serialize)}", virtualPropertyMethodAttr, IGeneratedStore_Serialize.ReturnType, Type.EmptyTypes);
  479. typeBuilder.DefineMethodOverride(serializeGen, IGeneratedStore_Serialize);
  480. { // this is non-locking because the only code that will call this will already own the correct lock
  481. var il = serializeGen.GetILGenerator();
  482. var Map_Add = typeof(Map).GetMethod(nameof(Map.Add));
  483. il.Emit(OpCodes.Call, typeof(Value).GetMethod(nameof(Value.Map)));
  484. // the map is now at the top of the stack
  485. var GetLocal = MakeGetLocal(il);
  486. foreach (var member in structure)
  487. {
  488. il.Emit(OpCodes.Dup);
  489. il.Emit(OpCodes.Ldstr, member.Name); // TODO: make this behave with annotations
  490. EmitSerializeMember(il, member, GetLocal);
  491. il.Emit(OpCodes.Call, Map_Add);
  492. }
  493. // the map is still at the top of the stack, return it
  494. il.Emit(OpCodes.Ret);
  495. }
  496. #endregion
  497. #region IGeneratedStore.Deserialize
  498. var deserializeGen = typeBuilder.DefineMethod($"<>{nameof(IGeneratedStore.Deserialize)}", virtualPropertyMethodAttr, null,
  499. new[] { IGeneratedStore_Deserialize.GetParameters()[0].ParameterType });
  500. typeBuilder.DefineMethodOverride(deserializeGen, IGeneratedStore_Deserialize);
  501. { // this is non-locking because the only code that will call this will already own the correct lock
  502. var il = deserializeGen.GetILGenerator();
  503. var Map_t = typeof(Map);
  504. var Map_TryGetValue = Map_t.GetMethod(nameof(Map.TryGetValue));
  505. var Object_GetType = typeof(object).GetMethod(nameof(Object.GetType));
  506. var valueLocal = il.DeclareLocal(typeof(Value));
  507. var nonNull = il.DefineLabel();
  508. il.Emit(OpCodes.Ldarg_1);
  509. il.Emit(OpCodes.Brtrue, nonNull);
  510. EmitLogError(il, "Attempting to deserialize null", tailcall: true);
  511. il.Emit(OpCodes.Ret);
  512. il.MarkLabel(nonNull);
  513. il.Emit(OpCodes.Ldarg_1);
  514. il.Emit(OpCodes.Isinst, Map_t);
  515. il.Emit(OpCodes.Dup); // duplicate cloned value
  516. var notMapError = il.DefineLabel();
  517. il.Emit(OpCodes.Brtrue, notMapError);
  518. // handle error
  519. il.Emit(OpCodes.Pop); // removes the duplicate value
  520. EmitLogError(il, $"Invalid root for deserializing {type.FullName}", tailcall: true,
  521. expected: il => EmitTypeof(il, Map_t), found: il =>
  522. {
  523. il.Emit(OpCodes.Ldarg_1);
  524. il.Emit(OpCodes.Callvirt, Object_GetType);
  525. });
  526. il.Emit(OpCodes.Ret);
  527. var nextLabel = notMapError;
  528. var GetLocal = MakeGetLocal(il);
  529. // head of stack is Map instance
  530. foreach (var member in structure)
  531. {
  532. il.MarkLabel(nextLabel);
  533. nextLabel = il.DefineLabel();
  534. var endErrorLabel = il.DefineLabel();
  535. il.Emit(OpCodes.Dup);
  536. il.Emit(OpCodes.Ldstr, member.Name);
  537. il.Emit(OpCodes.Ldloca_S, valueLocal);
  538. il.Emit(OpCodes.Call, Map_TryGetValue);
  539. il.Emit(OpCodes.Brtrue_S, endErrorLabel);
  540. EmitLogError(il, $"Missing key {member.Name}", tailcall: false);
  541. il.Emit(OpCodes.Br, nextLabel);
  542. il.MarkLabel(endErrorLabel);
  543. il.Emit(OpCodes.Ldloc_S, valueLocal);
  544. EmitDeserializeMember(il, member, nextLabel, il => il.Emit(OpCodes.Ldloc_S, valueLocal), GetLocal);
  545. }
  546. il.MarkLabel(nextLabel);
  547. il.Emit(OpCodes.Pop); // removes the duplicate value
  548. il.Emit(OpCodes.Ret);
  549. }
  550. #endregion
  551. #endregion
  552. #region IConfigStore
  553. typeBuilder.AddInterfaceImplementation(typeof(IConfigStore));
  554. var IConfigStore_t = typeof(IConfigStore);
  555. var IConfigStore_GetSyncObject = IConfigStore_t.GetProperty(nameof(IConfigStore.SyncObject)).GetGetMethod();
  556. var IConfigStore_GetWriteSyncObject = IConfigStore_t.GetProperty(nameof(IConfigStore.WriteSyncObject)).GetGetMethod();
  557. var IConfigStore_WriteTo = IConfigStore_t.GetMethod(nameof(IConfigStore.WriteTo));
  558. var IConfigStore_ReadFrom = IConfigStore_t.GetMethod(nameof(IConfigStore.ReadFrom));
  559. #region IConfigStore.SyncObject
  560. var syncObjProp = typeBuilder.DefineProperty(nameof(IConfigStore.SyncObject), PropertyAttributes.None, typeof(WaitHandle), null);
  561. var syncObjPropGet = typeBuilder.DefineMethod($"<g>{nameof(IConfigStore.SyncObject)}", virtualPropertyMethodAttr, syncObjProp.PropertyType, Type.EmptyTypes);
  562. syncObjProp.SetGetMethod(syncObjPropGet);
  563. typeBuilder.DefineMethodOverride(syncObjPropGet, IConfigStore_GetSyncObject);
  564. {
  565. var il = syncObjPropGet.GetILGenerator();
  566. il.Emit(OpCodes.Ldarg_0);
  567. il.Emit(OpCodes.Call, Impl.FindImplMethod);
  568. il.Emit(OpCodes.Tailcall);
  569. il.Emit(OpCodes.Call, Impl.SyncObjectGetMethod);
  570. il.Emit(OpCodes.Ret);
  571. }
  572. #endregion
  573. #region IConfigStore.WriteSyncObject
  574. var writeSyncObjProp = typeBuilder.DefineProperty(nameof(IConfigStore.WriteSyncObject), PropertyAttributes.None, typeof(WaitHandle), null);
  575. var writeSyncObjPropGet = typeBuilder.DefineMethod($"<g>{nameof(IConfigStore.WriteSyncObject)}", virtualPropertyMethodAttr, writeSyncObjProp.PropertyType, Type.EmptyTypes);
  576. writeSyncObjProp.SetGetMethod(writeSyncObjPropGet);
  577. typeBuilder.DefineMethodOverride(writeSyncObjPropGet, IConfigStore_GetWriteSyncObject);
  578. {
  579. var il = writeSyncObjPropGet.GetILGenerator();
  580. il.Emit(OpCodes.Ldarg_0);
  581. il.Emit(OpCodes.Call, Impl.FindImplMethod);
  582. il.Emit(OpCodes.Tailcall);
  583. il.Emit(OpCodes.Call, Impl.WriteSyncObjectGetMethod);
  584. il.Emit(OpCodes.Ret);
  585. }
  586. #endregion
  587. #region IConfigStore.WriteTo
  588. var writeTo = typeBuilder.DefineMethod($"<>{nameof(IConfigStore.WriteTo)}", virtualMemberMethod, null, new[] { typeof(IConfigProvider) });
  589. typeBuilder.DefineMethodOverride(writeTo, IConfigStore_WriteTo);
  590. {
  591. var il = writeTo.GetILGenerator();
  592. il.Emit(OpCodes.Ldarg_0);
  593. il.Emit(OpCodes.Call, Impl.FindImplMethod);
  594. il.Emit(OpCodes.Ldarg_1);
  595. il.Emit(OpCodes.Tailcall);
  596. il.Emit(OpCodes.Call, Impl.WriteToMethod);
  597. il.Emit(OpCodes.Ret);
  598. }
  599. #endregion
  600. #region IConfigStore.ReadFrom
  601. var readFrom = typeBuilder.DefineMethod($"<>{nameof(IConfigStore.ReadFrom)}", virtualMemberMethod, null, new[] { typeof(IConfigProvider) });
  602. typeBuilder.DefineMethodOverride(readFrom, IConfigStore_ReadFrom);
  603. {
  604. var il = readFrom.GetILGenerator();
  605. il.Emit(OpCodes.Ldarg_0);
  606. il.Emit(OpCodes.Call, Impl.FindImplMethod);
  607. il.Emit(OpCodes.Ldarg_1);
  608. il.Emit(OpCodes.Tailcall);
  609. il.Emit(OpCodes.Call, Impl.ReadFromMethod);
  610. il.Emit(OpCodes.Ret);
  611. }
  612. #endregion
  613. #endregion
  614. #region Changed
  615. var coreChanged = typeBuilder.DefineMethod(
  616. "<>Changed",
  617. virtualMemberMethod,
  618. null, Type.EmptyTypes);
  619. {
  620. var il = coreChanged.GetILGenerator();
  621. il.Emit(OpCodes.Ldarg_0);
  622. il.Emit(OpCodes.Call, Impl.ImplSignalChangedMethod);
  623. il.Emit(OpCodes.Ret); // simply call our impl's SignalChanged method and return
  624. }
  625. if (baseChanged != null) {
  626. var changedMethod = typeBuilder.DefineMethod( // copy to override baseChanged
  627. baseChanged.Name,
  628. virtualMemberMethod,
  629. null, Type.EmptyTypes);
  630. typeBuilder.DefineMethodOverride(changedMethod, baseChanged);
  631. {
  632. var il = changedMethod.GetILGenerator();
  633. il.Emit(OpCodes.Ldarg_0);
  634. il.Emit(OpCodes.Call, baseChanged); // call base
  635. il.Emit(OpCodes.Ldarg_0);
  636. il.Emit(OpCodes.Tailcall);
  637. il.Emit(OpCodes.Call, coreChanged); // call back to the core change method
  638. il.Emit(OpCodes.Ret);
  639. }
  640. coreChanged = changedMethod; // switch to calling this version instead of just the default
  641. }
  642. typeBuilder.DefineMethodOverride(coreChanged, IGeneratedStore_Changed);
  643. #endregion
  644. #region Members
  645. foreach (var member in structure.Where(m => m.IsVirtual))
  646. { // IsVirtual implies !IsField
  647. var prop = member.Member as PropertyInfo;
  648. var get = prop.GetGetMethod(true);
  649. var set = prop.GetSetMethod(true);
  650. var propBuilder = typeBuilder.DefineProperty($"{member.Name}#", PropertyAttributes.None, member.Type, null);
  651. var propGet = typeBuilder.DefineMethod($"<g>{propBuilder.Name}", virtualPropertyMethodAttr, member.Type, Type.EmptyTypes);
  652. propBuilder.SetGetMethod(propGet);
  653. typeBuilder.DefineMethodOverride(propGet, get);
  654. {
  655. var il = propGet.GetILGenerator();
  656. var local = il.DeclareLocal(member.Type);
  657. il.Emit(OpCodes.Ldarg_0);
  658. il.Emit(OpCodes.Call, Impl.ImplTakeReadMethod); // take the read lock
  659. il.BeginExceptionBlock();
  660. il.Emit(OpCodes.Ldarg_0);
  661. il.Emit(OpCodes.Call, get); // call base getter
  662. il.Emit(OpCodes.Stloc, local);
  663. il.BeginFinallyBlock();
  664. il.Emit(OpCodes.Ldarg_0);
  665. il.Emit(OpCodes.Call, Impl.ImplReleaseReadMethod); // release the read lock
  666. il.EndExceptionBlock();
  667. il.Emit(OpCodes.Ldloc, local);
  668. il.Emit(OpCodes.Ret);
  669. }
  670. var propSet = typeBuilder.DefineMethod($"<s>{propBuilder.Name}", virtualPropertyMethodAttr, null, new[] { member.Type });
  671. propBuilder.SetSetMethod(propSet);
  672. typeBuilder.DefineMethodOverride(propSet, set);
  673. { // TODO: decide if i want to correct the value before or after i take the write lock
  674. var il = propSet.GetILGenerator();
  675. il.Emit(OpCodes.Ldarg_0);
  676. il.Emit(OpCodes.Call, Impl.ImplTakeWriteMethod); // take the write lock
  677. il.BeginExceptionBlock();
  678. il.Emit(OpCodes.Ldarg_0);
  679. il.Emit(OpCodes.Ldarg_1);
  680. EmitCorrectMember(il, member);
  681. il.Emit(OpCodes.Call, set);
  682. il.BeginFinallyBlock();
  683. il.Emit(OpCodes.Ldarg_0);
  684. il.Emit(OpCodes.Call, Impl.ImplReleaseWriteMethod); // release the write lock
  685. il.EndExceptionBlock();
  686. il.Emit(OpCodes.Ldarg_0);
  687. il.Emit(OpCodes.Call, Impl.ImplInvokeChangedMethod);
  688. il.Emit(OpCodes.Ret);
  689. }
  690. }
  691. #endregion
  692. var genType = typeBuilder.CreateType();
  693. var parentParam = Expression.Parameter(typeof(IGeneratedStore), "parent");
  694. var creatorDel = Expression.Lambda<GeneratedStoreCreator>(
  695. Expression.New(ctor, parentParam), parentParam
  696. ).Compile();
  697. return (creatorDel, genType);
  698. }
  699. private delegate LocalBuilder GetLocal(Type type, int idx = 0);
  700. private static GetLocal MakeGetLocal(ILGenerator il)
  701. { // TODO: improve this shit a bit so that i can release a hold of a variable and do more auto managing
  702. var locals = new List<LocalBuilder>();
  703. LocalBuilder GetLocal(Type ty, int i = 0)
  704. { // TODO: pull this garbage out somewhere sane somehow
  705. var builder = locals.Where(b => b.LocalType == ty).Skip(i).FirstOrDefault();
  706. if (builder == null)
  707. {
  708. builder = il.DeclareLocal(ty);
  709. locals.Add(builder);
  710. }
  711. return builder;
  712. }
  713. return GetLocal;
  714. }
  715. private static readonly MethodInfo LogErrorMethod = typeof(GeneratedStore).GetMethod(nameof(LogError), BindingFlags.NonPublic | BindingFlags.Static);
  716. internal static void LogError(Type expected, Type found, string message)
  717. {
  718. Logger.config.Notice($"{message}{(expected == null ? "" : $" (expected {expected}, found {found?.ToString() ?? "null"})")}");
  719. }
  720. private static bool NeedsCorrection(SerializedMemberInfo member)
  721. {
  722. return false;
  723. }
  724. // expects start value on stack, exits with final value on stack
  725. private static void EmitCorrectMember(ILGenerator il, SerializedMemberInfo member)
  726. {
  727. if (!NeedsCorrection(member)) return;
  728. // TODO: impl
  729. }
  730. // expects the this param to be on the stack
  731. private static void EmitMemberFix(ILGenerator il, SerializedMemberInfo member, GetLocal GetLocal)
  732. {
  733. if (!NeedsCorrection(member)) return;
  734. var local = GetLocal(member.Type);
  735. EmitLoad(il, member); // load the member
  736. EmitCorrectMember(il, member); // correct it
  737. il.Emit(OpCodes.Stloc, local);
  738. EmitStore(il, member, il => il.Emit(OpCodes.Ldloc, local));
  739. }
  740. #region Utility
  741. private static void EmitLoad(ILGenerator il, SerializedMemberInfo member)
  742. {
  743. il.Emit(OpCodes.Ldarg_0); // load this
  744. if (member.IsField)
  745. il.Emit(OpCodes.Ldfld, member.Member as FieldInfo);
  746. else
  747. { // member is a property
  748. var prop = member.Member as PropertyInfo;
  749. var getter = prop.GetGetMethod();
  750. if (getter == null) throw new InvalidOperationException($"Property {member.Name} does not have a getter and is not ignored");
  751. il.Emit(OpCodes.Call, getter);
  752. }
  753. }
  754. private static void EmitStore(ILGenerator il, SerializedMemberInfo member, Action<ILGenerator> value)
  755. {
  756. il.Emit(OpCodes.Ldarg_0); // load this
  757. value(il);
  758. if (member.IsField)
  759. il.Emit(OpCodes.Stfld, member.Member as FieldInfo);
  760. else
  761. { // member is a property
  762. var prop = member.Member as PropertyInfo;
  763. var setter = prop.GetSetMethod();
  764. if (setter == null) throw new InvalidOperationException($"Property {member.Name} does not have a setter and is not ignored");
  765. il.Emit(OpCodes.Call, setter);
  766. }
  767. }
  768. private static void EmitLogError(ILGenerator il, string message, bool tailcall = false, Action<ILGenerator> expected = null, Action<ILGenerator> found = null)
  769. {
  770. if (expected == null) expected = il => il.Emit(OpCodes.Ldnull);
  771. if (found == null) found = il => il.Emit(OpCodes.Ldnull);
  772. expected(il);
  773. found(il);
  774. il.Emit(OpCodes.Ldstr, message);
  775. if (tailcall) il.Emit(OpCodes.Tailcall);
  776. il.Emit(OpCodes.Call, LogErrorMethod);
  777. }
  778. private static readonly MethodInfo Type_GetTypeFromHandle = typeof(Type).GetMethod(nameof(Type.GetTypeFromHandle));
  779. private static void EmitTypeof(ILGenerator il, Type type)
  780. {
  781. il.Emit(OpCodes.Ldtoken, type);
  782. il.Emit(OpCodes.Call, Type_GetTypeFromHandle);
  783. }
  784. private static Type Decimal_t = typeof(decimal);
  785. private static ConstructorInfo Decimal_FromFloat = Decimal_t.GetConstructor(new[] { typeof(float) });
  786. private static ConstructorInfo Decimal_FromDouble = Decimal_t.GetConstructor(new[] { typeof(double) });
  787. private static ConstructorInfo Decimal_FromInt = Decimal_t.GetConstructor(new[] { typeof(int) });
  788. private static ConstructorInfo Decimal_FromUInt = Decimal_t.GetConstructor(new[] { typeof(uint) });
  789. private static ConstructorInfo Decimal_FromLong = Decimal_t.GetConstructor(new[] { typeof(long) });
  790. private static ConstructorInfo Decimal_FromULong = Decimal_t.GetConstructor(new[] { typeof(ulong) });
  791. private static void EmitNumberConvertTo(ILGenerator il, Type to, Type from)
  792. { // WARNING: THIS USES THE NO-OVERFLOW OPCODES
  793. if (to == from) return;
  794. if (to == Decimal_t)
  795. {
  796. if (from == typeof(float)) il.Emit(OpCodes.Newobj, Decimal_FromFloat);
  797. else if (from == typeof(double)) il.Emit(OpCodes.Newobj, Decimal_FromDouble);
  798. else if (from == typeof(long)) il.Emit(OpCodes.Newobj, Decimal_FromLong);
  799. else if (from == typeof(ulong)) il.Emit(OpCodes.Newobj, Decimal_FromULong);
  800. else if (from == typeof(int)) il.Emit(OpCodes.Newobj, Decimal_FromInt);
  801. else if (from == typeof(uint)) il.Emit(OpCodes.Newobj, Decimal_FromUInt);
  802. else if (from == typeof(IntPtr))
  803. {
  804. EmitNumberConvertTo(il, typeof(long), from);
  805. EmitNumberConvertTo(il, to, typeof(long));
  806. }
  807. else if (from == typeof(UIntPtr))
  808. {
  809. EmitNumberConvertTo(il, typeof(ulong), from);
  810. EmitNumberConvertTo(il, to, typeof(ulong));
  811. }
  812. else
  813. { // if the source is anything else, we first convert to int because that can contain all other values
  814. EmitNumberConvertTo(il, typeof(int), from);
  815. EmitNumberConvertTo(il, to, typeof(int));
  816. };
  817. }
  818. else if (from == Decimal_t)
  819. {
  820. if (to == typeof(IntPtr))
  821. {
  822. EmitNumberConvertTo(il, typeof(long), from);
  823. EmitNumberConvertTo(il, to, typeof(long));
  824. }
  825. else if (to == typeof(UIntPtr))
  826. {
  827. EmitNumberConvertTo(il, typeof(ulong), from);
  828. EmitNumberConvertTo(il, to, typeof(ulong));
  829. }
  830. else
  831. {
  832. var method = Decimal_t.GetMethod($"To{to.Name}"); // conveniently, this is the pattern of the to* names
  833. il.Emit(OpCodes.Call, method);
  834. }
  835. }
  836. else if (to == typeof(IntPtr)) il.Emit(OpCodes.Conv_I);
  837. else if (to == typeof(UIntPtr)) il.Emit(OpCodes.Conv_U);
  838. else if (to == typeof(sbyte)) il.Emit(OpCodes.Conv_I1);
  839. else if (to == typeof(byte)) il.Emit(OpCodes.Conv_U1);
  840. else if (to == typeof(short)) il.Emit(OpCodes.Conv_I2);
  841. else if (to == typeof(ushort)) il.Emit(OpCodes.Conv_U2);
  842. else if (to == typeof(int)) il.Emit(OpCodes.Conv_I4);
  843. else if (to == typeof(uint)) il.Emit(OpCodes.Conv_U4);
  844. else if (to == typeof(long)) il.Emit(OpCodes.Conv_I8);
  845. else if (to == typeof(ulong)) il.Emit(OpCodes.Conv_U8);
  846. else if (to == typeof(float))
  847. {
  848. if (from == typeof(byte)
  849. || from == typeof(ushort)
  850. || from == typeof(uint)
  851. || from == typeof(ulong)
  852. || from == typeof(UIntPtr)) il.Emit(OpCodes.Conv_R_Un);
  853. il.Emit(OpCodes.Conv_R4);
  854. }
  855. else if (to == typeof(double))
  856. {
  857. if (from == typeof(byte)
  858. || from == typeof(ushort)
  859. || from == typeof(uint)
  860. || from == typeof(ulong)
  861. || from == typeof(UIntPtr)) il.Emit(OpCodes.Conv_R_Un);
  862. il.Emit(OpCodes.Conv_R8);
  863. }
  864. }
  865. private static void EmitCreateChildGenerated(ILGenerator il, Type childType)
  866. {
  867. var method = CreateGParent.MakeGenericMethod(childType);
  868. il.Emit(OpCodes.Ldarg_0);
  869. il.Emit(OpCodes.Call, method);
  870. }
  871. #endregion
  872. #region Serialize
  873. // emit takes no args, leaves Value at top of stack
  874. private static void EmitSerializeMember(ILGenerator il, SerializedMemberInfo member, GetLocal GetLocal)
  875. {
  876. EmitLoad(il, member);
  877. var endSerialize = il.DefineLabel();
  878. if (member.AllowNull)
  879. {
  880. var passedNull = il.DefineLabel();
  881. il.Emit(OpCodes.Dup);
  882. if (member.IsNullable)
  883. il.Emit(OpCodes.Call, member.Nullable_HasValue.GetGetMethod());
  884. il.Emit(OpCodes.Brtrue, passedNull);
  885. il.Emit(OpCodes.Pop);
  886. il.Emit(OpCodes.Ldnull);
  887. il.Emit(OpCodes.Br, endSerialize);
  888. il.MarkLabel(passedNull);
  889. }
  890. if (member.IsNullable)
  891. il.Emit(OpCodes.Call, member.Nullable_Value.GetGetMethod());
  892. var targetType = GetExpectedValueTypeForType(member.Type);
  893. if (member.HasConverter)
  894. {
  895. var stlocal = GetLocal(member.Type);
  896. if (member.IsGenericConverter)
  897. {
  898. var toValue = member.ConverterBase.GetMethod(nameof(ValueConverter<int>.ToValue),
  899. new[] { member.ConverterTarget, typeof(object) });
  900. il.Emit(OpCodes.Stloc, stlocal);
  901. il.Emit(OpCodes.Ldsfld, member.ConverterField);
  902. il.Emit(OpCodes.Ldloc, stlocal);
  903. il.Emit(OpCodes.Ldarg_0);
  904. il.Emit(OpCodes.Callvirt, toValue);
  905. }
  906. else
  907. {
  908. var toValue = typeof(IValueConverter).GetMethod(nameof(IValueConverter.ToValue),
  909. new[] { typeof(object), typeof(object) });
  910. il.Emit(OpCodes.Stloc, stlocal);
  911. il.Emit(OpCodes.Ldsfld, member.ConverterField);
  912. il.Emit(OpCodes.Ldloc, stlocal);
  913. if (member.Type.IsValueType)
  914. il.Emit(OpCodes.Box);
  915. il.Emit(OpCodes.Ldarg_0);
  916. il.Emit(OpCodes.Callvirt, toValue);
  917. }
  918. }
  919. else if (targetType == typeof(Text))
  920. { // only happens when arg is a string or char
  921. var TextCreate = typeof(Value).GetMethod(nameof(Value.Text));
  922. if (member.Type == typeof(char))
  923. {
  924. var strFromChar = typeof(char).GetMethod(nameof(char.ToString), new[] { typeof(char) });
  925. il.Emit(OpCodes.Call, strFromChar);
  926. }
  927. il.Emit(OpCodes.Call, TextCreate);
  928. }
  929. else if (targetType == typeof(Boolean))
  930. {
  931. var BoolCreate = typeof(Value).GetMethod(nameof(Value.Bool));
  932. il.Emit(OpCodes.Call, BoolCreate);
  933. }
  934. else if (targetType == typeof(Integer))
  935. {
  936. var IntCreate = typeof(Value).GetMethod(nameof(Value.Integer));
  937. EmitNumberConvertTo(il, IntCreate.GetParameters()[0].ParameterType, member.Type);
  938. il.Emit(OpCodes.Call, IntCreate);
  939. }
  940. else if (targetType == typeof(FloatingPoint))
  941. {
  942. var FloatCreate = typeof(Value).GetMethod(nameof(Value.Float));
  943. EmitNumberConvertTo(il, FloatCreate.GetParameters()[0].ParameterType, member.Type);
  944. il.Emit(OpCodes.Call, FloatCreate);
  945. }
  946. else if (targetType == typeof(List))
  947. {
  948. // TODO: impl this (enumerables)
  949. il.Emit(OpCodes.Pop);
  950. il.Emit(OpCodes.Ldnull);
  951. }
  952. else if (targetType == typeof(Map))
  953. {
  954. // TODO: support other aggregate types
  955. // for now, we assume that its a generated type implementing IGeneratedStore
  956. var IGeneratedStore_Serialize = typeof(IGeneratedStore).GetMethod(nameof(IGeneratedStore.Serialize));
  957. il.Emit(OpCodes.Callvirt, IGeneratedStore_Serialize);
  958. }
  959. il.MarkLabel(endSerialize);
  960. // TODO: implement converters
  961. }
  962. #endregion
  963. #region Deserialize
  964. private static Type GetExpectedValueTypeForType(Type valT)
  965. {
  966. if (typeof(Value).IsAssignableFrom(valT)) // this is a Value subtype
  967. return valT;
  968. if (valT == typeof(string)
  969. || valT == typeof(char)) return typeof(Text);
  970. if (valT == typeof(bool)) return typeof(Boolean);
  971. if (valT == typeof(byte)
  972. || valT == typeof(sbyte)
  973. || valT == typeof(short)
  974. || valT == typeof(ushort)
  975. || valT == typeof(int)
  976. || valT == typeof(uint)
  977. || valT == typeof(long)
  978. || valT == typeof(IntPtr)) return typeof(Integer);
  979. if (valT == typeof(float)
  980. || valT == typeof(double)
  981. || valT == typeof(decimal)
  982. || valT == typeof(ulong) // ulong gets put into this, because decimal can hold it
  983. || valT == typeof(UIntPtr)) return typeof(FloatingPoint);
  984. if (typeof(IEnumerable).IsAssignableFrom(valT)) return typeof(List);
  985. // TODO: fill this out the rest of the way
  986. // TODO: support converters
  987. return typeof(Map); // default for various objects
  988. }
  989. private static void EmitDeserializeGeneratedValue(ILGenerator il, Type targetType, Type srcType, GetLocal GetLocal)
  990. {
  991. var IGeneratedStore_Deserialize = typeof(IGeneratedStore).GetMethod(nameof(IGeneratedStore.Deserialize));
  992. var valuel = GetLocal(srcType, 0);
  993. il.Emit(OpCodes.Stloc, valuel);
  994. EmitCreateChildGenerated(il, targetType);
  995. il.Emit(OpCodes.Dup);
  996. il.Emit(OpCodes.Ldloc, valuel);
  997. il.Emit(OpCodes.Callvirt, IGeneratedStore_Deserialize);
  998. }
  999. private static void EmitDeserializeNullable(ILGenerator il, SerializedMemberInfo member, Type expected, GetLocal GetLocal)
  1000. {
  1001. EmitDeserializeValue(il, member.NullableWrappedType, expected, GetLocal);
  1002. il.Emit(OpCodes.Newobj, member.Nullable_Construct);
  1003. }
  1004. // top of stack is the Value to deserialize; the type will be as returned from GetExpectedValueTypeForType
  1005. // after, top of stack will be thing to write to field
  1006. private static void EmitDeserializeValue(ILGenerator il, Type targetType, Type expected, GetLocal GetLocal)
  1007. {
  1008. if (typeof(Value).IsAssignableFrom(targetType)) return; // do nothing
  1009. if (expected == typeof(Text))
  1010. {
  1011. var getter = expected.GetProperty(nameof(Text.Value)).GetGetMethod();
  1012. il.Emit(OpCodes.Call, getter);
  1013. if (targetType == typeof(char))
  1014. {
  1015. var strIndex = typeof(string).GetProperty("Chars").GetGetMethod(); // string's indexer is specially named Chars
  1016. il.Emit(OpCodes.Ldc_I4_0);
  1017. il.Emit(OpCodes.Call, strIndex);
  1018. }
  1019. }
  1020. else if (expected == typeof(Boolean))
  1021. {
  1022. var getter = expected.GetProperty(nameof(Boolean.Value)).GetGetMethod();
  1023. il.Emit(OpCodes.Call, getter);
  1024. }
  1025. else if (expected == typeof(Integer))
  1026. {
  1027. var getter = expected.GetProperty(nameof(Integer.Value)).GetGetMethod();
  1028. il.Emit(OpCodes.Call, getter);
  1029. EmitNumberConvertTo(il, targetType, getter.ReturnType);
  1030. }
  1031. else if (expected == typeof(FloatingPoint))
  1032. {
  1033. var getter = expected.GetProperty(nameof(FloatingPoint.Value)).GetGetMethod();
  1034. il.Emit(OpCodes.Call, getter);
  1035. EmitNumberConvertTo(il, targetType, getter.ReturnType);
  1036. } // TODO: implement stuff for lists and maps of various types (probably call out somewhere else to figure out what to do)
  1037. else if (expected == typeof(Map))
  1038. {
  1039. EmitDeserializeGeneratedValue(il, targetType, expected, GetLocal);
  1040. }
  1041. else // TODO: support converters
  1042. {
  1043. il.Emit(OpCodes.Pop);
  1044. il.Emit(OpCodes.Ldnull);
  1045. }
  1046. }
  1047. private static void EmitDeserializeConverter(ILGenerator il, SerializedMemberInfo member, GetLocal GetLocal)
  1048. {
  1049. var stlocal = GetLocal(typeof(Value));
  1050. if (member.IsGenericConverter)
  1051. {
  1052. var fromValue = member.ConverterBase.GetMethod(nameof(ValueConverter<int>.FromValue),
  1053. new[] { typeof(Value), typeof(object) });
  1054. il.Emit(OpCodes.Stloc, stlocal);
  1055. il.Emit(OpCodes.Ldsfld, member.ConverterField);
  1056. il.Emit(OpCodes.Ldloc, stlocal);
  1057. il.Emit(OpCodes.Ldarg_0);
  1058. il.Emit(OpCodes.Callvirt, fromValue);
  1059. }
  1060. else
  1061. {
  1062. var fromValue = typeof(IValueConverter).GetMethod(nameof(IValueConverter.FromValue),
  1063. new[] { typeof(Value), typeof(object) });
  1064. il.Emit(OpCodes.Stloc, stlocal);
  1065. il.Emit(OpCodes.Ldsfld, member.ConverterField);
  1066. il.Emit(OpCodes.Ldloc, stlocal);
  1067. if (member.Type.IsValueType)
  1068. il.Emit(OpCodes.Box);
  1069. il.Emit(OpCodes.Ldarg_0);
  1070. il.Emit(OpCodes.Callvirt, fromValue);
  1071. }
  1072. }
  1073. // emit takes the value being deserialized, logs on error, leaves nothing on stack
  1074. private static void EmitDeserializeMember(ILGenerator il, SerializedMemberInfo member, Label nextLabel, Action<ILGenerator> getValue, GetLocal GetLocal)
  1075. {
  1076. var Object_GetType = typeof(object).GetMethod(nameof(Object.GetType));
  1077. var implLabel = il.DefineLabel();
  1078. var passedTypeCheck = il.DefineLabel();
  1079. var expectType = GetExpectedValueTypeForType(member.IsNullable ? member.NullableWrappedType : member.Type);
  1080. il.Emit(OpCodes.Dup);
  1081. il.Emit(OpCodes.Brtrue_S, implLabel); // null check
  1082. if (!member.AllowNull)
  1083. {
  1084. il.Emit(OpCodes.Pop);
  1085. EmitLogError(il, $"Member {member.Name} ({member.Type}) not nullable", tailcall: false,
  1086. expected: il => EmitTypeof(il, expectType));
  1087. il.Emit(OpCodes.Br, nextLabel);
  1088. }
  1089. else if (member.IsNullable)
  1090. {
  1091. il.Emit(OpCodes.Pop);
  1092. var valTLocal = GetLocal(member.Type, 0);
  1093. il.Emit(OpCodes.Ldloca, valTLocal);
  1094. il.Emit(OpCodes.Initobj, member.Type);
  1095. EmitStore(il, member, il => il.Emit(OpCodes.Ldloc, valTLocal));
  1096. il.Emit(OpCodes.Br, nextLabel);
  1097. }
  1098. else
  1099. {
  1100. il.Emit(OpCodes.Pop);
  1101. EmitStore(il, member, il => il.Emit(OpCodes.Ldnull));
  1102. il.Emit(OpCodes.Br, nextLabel);
  1103. }
  1104. il.MarkLabel(implLabel);
  1105. if (member.HasConverter)
  1106. il.Emit(OpCodes.Br, passedTypeCheck);
  1107. else
  1108. {
  1109. il.Emit(OpCodes.Isinst, expectType); //replaces on stack
  1110. il.Emit(OpCodes.Dup); // duplicate cloned value
  1111. il.Emit(OpCodes.Brtrue, passedTypeCheck); // null check
  1112. }
  1113. var errorHandle = il.DefineLabel();
  1114. // special cases to handle coersion between Float and Int
  1115. if (member.HasConverter) { } // do nothing here
  1116. else if (expectType == typeof(FloatingPoint))
  1117. {
  1118. var specialTypeCheck = il.DefineLabel();
  1119. il.Emit(OpCodes.Pop);
  1120. getValue(il);
  1121. il.Emit(OpCodes.Isinst, typeof(Integer)); //replaces on stack
  1122. il.Emit(OpCodes.Dup); // duplicate cloned value
  1123. il.Emit(OpCodes.Brfalse, errorHandle); // null check
  1124. var Integer_CoerceToFloat = typeof(Integer).GetMethod(nameof(Integer.AsFloat));
  1125. il.Emit(OpCodes.Call, Integer_CoerceToFloat);
  1126. il.Emit(OpCodes.Br, passedTypeCheck);
  1127. }
  1128. else if (expectType == typeof(Integer))
  1129. {
  1130. var specialTypeCheck = il.DefineLabel();
  1131. il.Emit(OpCodes.Pop);
  1132. getValue(il);
  1133. il.Emit(OpCodes.Isinst, typeof(FloatingPoint)); //replaces on stack
  1134. il.Emit(OpCodes.Dup); // duplicate cloned value
  1135. il.Emit(OpCodes.Brfalse, errorHandle); // null check
  1136. var Float_CoerceToInt = typeof(FloatingPoint).GetMethod(nameof(FloatingPoint.AsInteger));
  1137. il.Emit(OpCodes.Call, Float_CoerceToInt);
  1138. il.Emit(OpCodes.Br, passedTypeCheck);
  1139. }
  1140. il.MarkLabel(errorHandle);
  1141. il.Emit(OpCodes.Pop);
  1142. EmitLogError(il, $"Unexpected type deserializing {member.Name}", tailcall: false,
  1143. expected: il => EmitTypeof(il, expectType), found: il =>
  1144. {
  1145. getValue(il);
  1146. il.Emit(OpCodes.Callvirt, Object_GetType);
  1147. });
  1148. il.Emit(OpCodes.Br, nextLabel);
  1149. il.MarkLabel(passedTypeCheck);
  1150. var local = GetLocal(member.Type, 0);
  1151. if (member.HasConverter) EmitDeserializeConverter(il, member, GetLocal);
  1152. else if (member.IsNullable) EmitDeserializeNullable(il, member, expectType, GetLocal);
  1153. else EmitDeserializeValue(il, member.Type, expectType, GetLocal);
  1154. il.Emit(OpCodes.Stloc, local);
  1155. EmitStore(il, member, il => il.Emit(OpCodes.Ldloc, local));
  1156. }
  1157. #endregion
  1158. }
  1159. }