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.

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