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.

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