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.

896 lines
40 KiB

  1. using IPA.Config.Data;
  2. using IPA.Logging;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Reflection;
  7. using System.Reflection.Emit;
  8. using System.Text;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. using System.Linq.Expressions;
  12. using System.Runtime.CompilerServices;
  13. using System.IO;
  14. using Boolean = IPA.Config.Data.Boolean;
  15. using System.Collections;
  16. #if NET3
  17. using Net3_Proxy;
  18. using Array = Net3_Proxy.Array;
  19. #endif
  20. [assembly: InternalsVisibleTo(IPA.Config.Stores.GeneratedStore.GeneratedAssemblyName)]
  21. namespace IPA.Config.Stores
  22. {
  23. /// <summary>
  24. /// A class providing an extension for <see cref="Config"/> to make it easy to use generated
  25. /// config stores.
  26. /// </summary>
  27. public static class GeneratedExtension
  28. {
  29. /// <summary>
  30. /// The name of the assembly that internals must be visible to to allow internal protection.
  31. /// </summary>
  32. public const string AssemblyVisibilityTarget = GeneratedStore.GeneratedAssemblyName;
  33. /// <summary>
  34. /// Creates a generated <see cref="IConfigStore"/> of type <typeparamref name="T"/>, registers it to
  35. /// the <see cref="Config"/> object, and returns it. This also forces a synchronous config load via
  36. /// <see cref="Config.LoadSync"/> if <paramref name="loadSync"/> is <see langword="true"/>.
  37. /// </summary>
  38. /// <remarks>
  39. /// <para>
  40. /// <typeparamref name="T"/> must be a public non-<see langword="sealed"/> <see langword="class"/>.
  41. /// It can also be internal, but in that case, then your assembly must have the following attribute
  42. /// to allow the generated code to reference it.
  43. /// <code>
  44. /// [assembly: InternalsVisibleTo(IPA.Config.Stores.GeneratedExtension.AssemblyVisibilityTarget)]
  45. /// </code>
  46. /// </para>
  47. /// <para>
  48. /// If the <typeparamref name="T"/> declares a <see langword="public"/> or <see langword="protected"/>, <see langword="virtual"/>
  49. /// method <c>Changed()</c>, then that method may be called to artificially signal to the runtime that the content of the object
  50. /// has changed. That method will also be called after the write locks are released when a property is set anywhere in the owning
  51. /// tree. This will only be called on the outermost generated object of the config structure, even if the change being signaled
  52. /// is somewhere deep into the tree.
  53. /// </para>
  54. /// <para>
  55. /// Similarly, <typeparamref name="T"/> can declare a <see langword="public"/> or <see langword="protected"/>, <see langword="virtual"/>
  56. /// method <c>OnReload()</c>, which will be called on the filesystem reader thread after the object has been repopulated with new data
  57. /// 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
  58. /// object of the config structure.
  59. /// </para>
  60. /// <para>
  61. /// TODO: describe details of generated stores
  62. /// </para>
  63. /// </remarks>
  64. /// <typeparam name="T">the type to wrap</typeparam>
  65. /// <param name="cfg">the <see cref="Config"/> to register to</param>
  66. /// <param name="loadSync">whether to synchronously load the content, or trigger an async load</param>
  67. /// <returns>a generated instance of <typeparamref name="T"/> as a special <see cref="IConfigStore"/></returns>
  68. public static T Generated<T>(this Config cfg, bool loadSync = true) where T : class
  69. {
  70. var ret = GeneratedStore.Create<T>();
  71. cfg.SetStore(ret as IConfigStore);
  72. if (loadSync)
  73. cfg.LoadSync();
  74. else
  75. cfg.LoadAsync();
  76. return ret;
  77. }
  78. }
  79. internal static class GeneratedStore
  80. {
  81. internal interface IGeneratedStore
  82. {
  83. /// <summary>
  84. /// serializes/deserializes to Value
  85. /// </summary>
  86. Value Values { get; set; }
  87. Type Type { get; }
  88. IGeneratedStore Parent { get; }
  89. Impl Impl { get; }
  90. void OnReload();
  91. }
  92. internal class Impl : IConfigStore
  93. {
  94. private IGeneratedStore generated;
  95. internal static ConstructorInfo Ctor = typeof(Impl).GetConstructor(new[] { typeof(IGeneratedStore) });
  96. public Impl(IGeneratedStore store) => generated = store;
  97. private readonly AutoResetEvent resetEvent = new AutoResetEvent(false);
  98. public WaitHandle SyncObject => resetEvent;
  99. internal static MethodInfo SyncObjectGetMethod = typeof(Impl).GetProperty(nameof(SyncObject)).GetGetMethod();
  100. public ReaderWriterLockSlim WriteSyncObject { get; } = new ReaderWriterLockSlim();
  101. internal static MethodInfo WriteSyncObjectGetMethod = typeof(Impl).GetProperty(nameof(WriteSyncObject)).GetGetMethod();
  102. internal static MethodInfo ImplSignalChangedMethod = typeof(Impl).GetMethod(nameof(ImplSignalChanged));
  103. public static void ImplSignalChanged(IGeneratedStore s) => FindImpl(s).SignalChanged();
  104. public void SignalChanged() => resetEvent.Set();
  105. internal static MethodInfo ImplTakeReadMethod = typeof(Impl).GetMethod(nameof(ImplTakeRead));
  106. public static void ImplTakeRead(IGeneratedStore s) => FindImpl(s).TakeRead();
  107. public void TakeRead() => WriteSyncObject.EnterReadLock();
  108. internal static MethodInfo ImplReleaseReadMethod = typeof(Impl).GetMethod(nameof(ImplReleaseRead));
  109. public static void ImplReleaseRead(IGeneratedStore s) => FindImpl(s).ReleaseRead();
  110. public void ReleaseRead() => WriteSyncObject.ExitReadLock();
  111. internal static MethodInfo ImplTakeWriteMethod = typeof(Impl).GetMethod(nameof(ImplTakeWrite));
  112. public static void ImplTakeWrite(IGeneratedStore s) => FindImpl(s).TakeWrite();
  113. public void TakeWrite() => WriteSyncObject.EnterWriteLock();
  114. internal static MethodInfo ImplReleaseWriteMethod = typeof(Impl).GetMethod(nameof(ImplReleaseWrite));
  115. public static void ImplReleaseWrite(IGeneratedStore s) => FindImpl(s).ReleaseWrite();
  116. public void ReleaseWrite() => WriteSyncObject.ExitWriteLock();
  117. internal static MethodInfo FindImplMethod = typeof(Impl).GetMethod(nameof(FindImpl));
  118. public static Impl FindImpl(IGeneratedStore store)
  119. {
  120. while (store?.Parent != null) store = store.Parent; // walk to the top of the tree
  121. return store?.Impl;
  122. }
  123. internal static MethodInfo ReadFromMethod = typeof(Impl).GetMethod(nameof(ReadFrom));
  124. public void ReadFrom(IConfigProvider provider)
  125. {
  126. var values = provider.Load();
  127. Logger.config.Debug("Generated impl ReadFrom");
  128. Logger.config.Debug($"Read {values}");
  129. generated.Values = values;
  130. ReleaseWrite();
  131. generated.OnReload();
  132. TakeWrite(); // must take again for runtime to be happy (which is unfortunate)
  133. }
  134. internal static MethodInfo WriteToMethod = typeof(Impl).GetMethod(nameof(WriteTo));
  135. public void WriteTo(IConfigProvider provider)
  136. {
  137. var values = generated.Values;
  138. Logger.config.Debug("Generated impl WriteTo");
  139. Logger.config.Debug($"Serialized {values}");
  140. provider.Store(values);
  141. }
  142. }
  143. private static Dictionary<Type, Func<IGeneratedStore, IConfigStore>> generatedCreators = new Dictionary<Type, Func<IGeneratedStore, IConfigStore>>();
  144. private static Dictionary<Type, Dictionary<string, Type>> memberMaps = new Dictionary<Type, Dictionary<string, Type>>();
  145. public static T Create<T>() where T : class => (T)Create(typeof(T));
  146. public static IConfigStore Create(Type type) => Create(type, null);
  147. private static readonly MethodInfo CreateGParent =
  148. typeof(GeneratedStore).GetMethod(nameof(Create), BindingFlags.NonPublic | BindingFlags.Static, null,
  149. CallingConventions.Any, new[] { typeof(IGeneratedStore) }, Array.Empty<ParameterModifier>());
  150. internal static T Create<T>(IGeneratedStore parent) where T : class => (T)Create(typeof(T), parent);
  151. private static IConfigStore Create(Type type, IGeneratedStore parent)
  152. {
  153. if (generatedCreators.TryGetValue(type, out var creator))
  154. return creator(parent);
  155. else
  156. {
  157. creator = MakeCreator(type);
  158. generatedCreators.Add(type, creator);
  159. return creator(parent);
  160. }
  161. }
  162. internal const string GeneratedAssemblyName = "IPA.Config.Generated";
  163. private static AssemblyBuilder assembly = null;
  164. private static AssemblyBuilder Assembly
  165. {
  166. get
  167. {
  168. if (assembly == null)
  169. {
  170. var name = new AssemblyName(GeneratedAssemblyName);
  171. assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.RunAndSave);
  172. }
  173. return assembly;
  174. }
  175. }
  176. internal static void DebugSaveAssembly(string file)
  177. {
  178. Assembly.Save(file);
  179. }
  180. private static ModuleBuilder module = null;
  181. private static ModuleBuilder Module
  182. {
  183. get
  184. {
  185. if (module == null)
  186. module = Assembly.DefineDynamicModule(Assembly.GetName().Name, Assembly.GetName().Name + ".dll");
  187. return module;
  188. }
  189. }
  190. private struct SerializedMemberInfo
  191. {
  192. public string Name;
  193. public MemberInfo Member;
  194. public bool IsVirtual;
  195. public bool IsField;
  196. public Type Type;
  197. }
  198. private static Func<IGeneratedStore, IConfigStore> MakeCreator(Type type)
  199. {
  200. var baseCtor = type.GetConstructor(Type.EmptyTypes); // get a default constructor
  201. if (baseCtor == null)
  202. throw new ArgumentException("Config type does not have a public parameterless constructor");
  203. var typeBuilder = Module.DefineType($"{type.FullName}<Generated>",
  204. TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.Class, type);
  205. var typeField = typeBuilder.DefineField("<>_type", typeof(Type), FieldAttributes.Private | FieldAttributes.InitOnly);
  206. var implField = typeBuilder.DefineField("<>_impl", typeof(Impl), FieldAttributes.Private | FieldAttributes.InitOnly);
  207. var parentField = typeBuilder.DefineField("<>_parent", typeof(IGeneratedStore), FieldAttributes.Private | FieldAttributes.InitOnly);
  208. // none of this can be Expressions because CompileToMethod requires a static target method for some dumbass reason
  209. #region Parse base object structure
  210. var baseChanged = type.GetMethod("Changed", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, Array.Empty<ParameterModifier>());
  211. if (baseChanged != null && !baseChanged.IsVirtual) baseChanged = null; // limit this to just the one thing
  212. var baseOnReload = type.GetMethod("OnReload", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, Array.Empty<ParameterModifier>());
  213. if (baseOnReload != null && !baseOnReload.IsVirtual) baseOnReload = null; // limit this to just the one thing
  214. var structure = new List<SerializedMemberInfo>();
  215. // TODO: incorporate attributes/base types
  216. // TODO: ignore probs without setter
  217. // only looks at public properties
  218. foreach (var prop in type.GetProperties(BindingFlags.Instance | BindingFlags.Public))
  219. {
  220. var smi = new SerializedMemberInfo
  221. {
  222. Name = prop.Name,
  223. Member = prop,
  224. IsVirtual = (prop.GetGetMethod(true)?.IsVirtual ?? false) ||
  225. (prop.GetSetMethod(true)?.IsVirtual ?? false),
  226. IsField = false,
  227. Type = prop.PropertyType
  228. };
  229. structure.Add(smi);
  230. }
  231. // only look at public fields
  232. foreach (var field in type.GetFields(BindingFlags.Instance | BindingFlags.Public))
  233. {
  234. var smi = new SerializedMemberInfo
  235. {
  236. Name = field.Name,
  237. Member = field,
  238. IsVirtual = false,
  239. IsField = true,
  240. Type = field.FieldType
  241. };
  242. structure.Add(smi);
  243. }
  244. #endregion
  245. #region Constructor
  246. var ctor = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new[] { typeof(IGeneratedStore) });
  247. { // because this is a constructor, it has to be raw IL
  248. var il = ctor.GetILGenerator();
  249. il.Emit(OpCodes.Ldarg_0); // keep this at bottom of stack
  250. il.Emit(OpCodes.Dup);
  251. il.Emit(OpCodes.Call, baseCtor);
  252. il.Emit(OpCodes.Dup);
  253. il.Emit(OpCodes.Ldarg_1); // load parent
  254. il.Emit(OpCodes.Stfld, parentField);
  255. il.Emit(OpCodes.Dup);
  256. EmitTypeof(il, type);
  257. il.Emit(OpCodes.Stfld, typeField);
  258. il.Emit(OpCodes.Dup);
  259. il.Emit(OpCodes.Dup);
  260. il.Emit(OpCodes.Newobj, Impl.Ctor);
  261. il.Emit(OpCodes.Stfld, implField);
  262. foreach (var member in structure)
  263. EmitMemberFix(il, member);
  264. il.Emit(OpCodes.Pop);
  265. il.Emit(OpCodes.Ret);
  266. }
  267. #endregion
  268. const MethodAttributes propertyMethodAttr = MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig;
  269. const MethodAttributes virtualPropertyMethodAttr = propertyMethodAttr | MethodAttributes.Virtual | MethodAttributes.Final;
  270. const MethodAttributes virtualMemberMethod = MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.Final;
  271. #region IGeneratedStore
  272. typeBuilder.AddInterfaceImplementation(typeof(IGeneratedStore));
  273. var IGeneratedStore_t = typeof(IGeneratedStore);
  274. var IGeneratedStore_GetImpl = IGeneratedStore_t.GetProperty(nameof(IGeneratedStore.Impl)).GetGetMethod();
  275. var IGeneratedStore_GetType = IGeneratedStore_t.GetProperty(nameof(IGeneratedStore.Type)).GetGetMethod();
  276. var IGeneratedStore_GetParent = IGeneratedStore_t.GetProperty(nameof(IGeneratedStore.Parent)).GetGetMethod();
  277. var IGeneratedStore_GetValues = IGeneratedStore_t.GetProperty(nameof(IGeneratedStore.Values)).GetGetMethod();
  278. var IGeneratedStore_SetValues = IGeneratedStore_t.GetProperty(nameof(IGeneratedStore.Values)).GetSetMethod();
  279. var IGeneratedStore_OnReload = IGeneratedStore_t.GetMethod(nameof(IGeneratedStore.OnReload));
  280. #region IGeneratedStore.OnReload
  281. var onReload = typeBuilder.DefineMethod($"<>{nameof(IGeneratedStore.OnReload)}", virtualMemberMethod, null, Type.EmptyTypes);
  282. typeBuilder.DefineMethodOverride(onReload, IGeneratedStore_OnReload);
  283. if (baseOnReload != null) typeBuilder.DefineMethodOverride(onReload, baseOnReload);
  284. {
  285. var il = onReload.GetILGenerator();
  286. if (baseOnReload != null)
  287. {
  288. il.Emit(OpCodes.Ldarg_0); // load this
  289. il.Emit(OpCodes.Tailcall);
  290. il.Emit(OpCodes.Call, baseOnReload); // load impl field
  291. }
  292. il.Emit(OpCodes.Ret);
  293. }
  294. #endregion
  295. #region IGeneratedStore.Impl
  296. var implProp = typeBuilder.DefineProperty(nameof(IGeneratedStore.Impl), PropertyAttributes.None, typeof(Impl), null);
  297. var implPropGet = typeBuilder.DefineMethod($"<g>{nameof(IGeneratedStore.Impl)}", virtualPropertyMethodAttr, implProp.PropertyType, Type.EmptyTypes);
  298. implProp.SetGetMethod(implPropGet);
  299. typeBuilder.DefineMethodOverride(implPropGet, IGeneratedStore_GetImpl);
  300. {
  301. var il = implPropGet.GetILGenerator();
  302. il.Emit(OpCodes.Ldarg_0); // load this
  303. il.Emit(OpCodes.Ldfld, implField); // load impl field
  304. il.Emit(OpCodes.Ret);
  305. }
  306. #endregion
  307. #region IGeneratedStore.Type
  308. var typeProp = typeBuilder.DefineProperty(nameof(IGeneratedStore.Type), PropertyAttributes.None, typeof(Type), null);
  309. var typePropGet = typeBuilder.DefineMethod($"<g>{nameof(IGeneratedStore.Type)}", virtualPropertyMethodAttr, typeProp.PropertyType, Type.EmptyTypes);
  310. typeProp.SetGetMethod(typePropGet);
  311. typeBuilder.DefineMethodOverride(typePropGet, IGeneratedStore_GetType);
  312. {
  313. var il = typePropGet.GetILGenerator();
  314. il.Emit(OpCodes.Ldarg_0); // load this
  315. il.Emit(OpCodes.Ldfld, typeField); // load impl field
  316. il.Emit(OpCodes.Ret);
  317. }
  318. #endregion
  319. #region IGeneratedStore.Parent
  320. var parentProp = typeBuilder.DefineProperty(nameof(IGeneratedStore.Parent), PropertyAttributes.None, typeof(IGeneratedStore), null);
  321. var parentPropGet = typeBuilder.DefineMethod($"<g>{nameof(IGeneratedStore.Parent)}", virtualPropertyMethodAttr, parentProp.PropertyType, Type.EmptyTypes);
  322. parentProp.SetGetMethod(parentPropGet);
  323. typeBuilder.DefineMethodOverride(parentPropGet, IGeneratedStore_GetParent);
  324. {
  325. var il = parentPropGet.GetILGenerator();
  326. il.Emit(OpCodes.Ldarg_0); // load this
  327. il.Emit(OpCodes.Ldfld, parentField); // load impl field
  328. il.Emit(OpCodes.Ret);
  329. }
  330. #endregion
  331. #region IGeneratedStore.Values
  332. var valuesProp = typeBuilder.DefineProperty(nameof(IGeneratedStore.Values), PropertyAttributes.None, typeof(Value), null);
  333. var valuesPropGet = typeBuilder.DefineMethod($"<g>{nameof(IGeneratedStore.Values)}", virtualPropertyMethodAttr, valuesProp.PropertyType, Type.EmptyTypes);
  334. var valuesPropSet = typeBuilder.DefineMethod($"<s>{nameof(IGeneratedStore.Values)}", virtualPropertyMethodAttr, null, new[] { valuesProp.PropertyType });
  335. valuesProp.SetGetMethod(valuesPropGet);
  336. typeBuilder.DefineMethodOverride(valuesPropGet, IGeneratedStore_GetValues);
  337. valuesProp.SetSetMethod(valuesPropSet);
  338. typeBuilder.DefineMethodOverride(valuesPropSet, IGeneratedStore_SetValues);
  339. { // this is non-locking because the only code that will call this will already own the correct lock
  340. var il = valuesPropGet.GetILGenerator();
  341. var Map_Add = typeof(Map).GetMethod(nameof(Map.Add));
  342. il.Emit(OpCodes.Call, typeof(Value).GetMethod(nameof(Value.Map)));
  343. // the map is now at the top of the stack
  344. foreach (var member in structure)
  345. {
  346. il.Emit(OpCodes.Dup);
  347. il.Emit(OpCodes.Ldstr, member.Name); // TODO: make this behave with annotations
  348. EmitSerializeMember(il, member);
  349. il.Emit(OpCodes.Call, Map_Add);
  350. }
  351. // the map is still at the top of the stack, return it
  352. il.Emit(OpCodes.Ret);
  353. }
  354. { // this is non-locking because the only code that will call this will already own the correct lock
  355. var il = valuesPropSet.GetILGenerator();
  356. var Map_t = typeof(Map);
  357. var Map_TryGetValue = Map_t.GetMethod(nameof(Map.TryGetValue));
  358. var Object_GetType = typeof(object).GetMethod(nameof(Object.GetType));
  359. var valueLocal = il.DeclareLocal(typeof(Value));
  360. var nonNull = il.DefineLabel();
  361. il.Emit(OpCodes.Ldarg_1);
  362. il.Emit(OpCodes.Brtrue, nonNull);
  363. EmitLogError(il, "Attempting to deserialize null", tailcall: true);
  364. il.Emit(OpCodes.Ret);
  365. il.MarkLabel(nonNull);
  366. il.Emit(OpCodes.Ldarg_1);
  367. il.Emit(OpCodes.Isinst, Map_t);
  368. il.Emit(OpCodes.Dup); // duplicate cloned value
  369. var notMapError = il.DefineLabel();
  370. il.Emit(OpCodes.Brtrue, notMapError);
  371. // handle error
  372. il.Emit(OpCodes.Pop); // removes the duplicate value
  373. EmitLogError(il, $"Invalid root for deserializing {type.FullName}", tailcall: true,
  374. expected: il => EmitTypeof(il, Map_t), found: il =>
  375. {
  376. il.Emit(OpCodes.Ldarg_1);
  377. il.Emit(OpCodes.Callvirt, Object_GetType);
  378. });
  379. il.Emit(OpCodes.Ret);
  380. var nextLabel = notMapError;
  381. var locals = new List<LocalBuilder>();
  382. // head of stack is Map instance
  383. foreach (var member in structure)
  384. {
  385. il.MarkLabel(nextLabel);
  386. nextLabel = il.DefineLabel();
  387. var endErrorLabel = il.DefineLabel();
  388. il.Emit(OpCodes.Dup);
  389. il.Emit(OpCodes.Ldstr, member.Name);
  390. il.Emit(OpCodes.Ldloca_S, valueLocal);
  391. il.Emit(OpCodes.Call, Map_TryGetValue);
  392. il.Emit(OpCodes.Brtrue_S, endErrorLabel);
  393. EmitLogError(il, $"Missing key {member.Name}", tailcall: false);
  394. il.Emit(OpCodes.Br, nextLabel);
  395. il.MarkLabel(endErrorLabel);
  396. il.Emit(OpCodes.Ldloc_S, valueLocal);
  397. EmitDeserializeMember(il, member, nextLabel, il => il.Emit(OpCodes.Ldloc_S, valueLocal), locals);
  398. }
  399. il.MarkLabel(nextLabel);
  400. il.Emit(OpCodes.Pop); // removes the duplicate value
  401. il.Emit(OpCodes.Ret);
  402. }
  403. #endregion
  404. #endregion
  405. #region IConfigStore
  406. typeBuilder.AddInterfaceImplementation(typeof(IConfigStore));
  407. var IConfigStore_t = typeof(IConfigStore);
  408. var IConfigStore_GetSyncObject = IConfigStore_t.GetProperty(nameof(IConfigStore.SyncObject)).GetGetMethod();
  409. var IConfigStore_GetWriteSyncObject = IConfigStore_t.GetProperty(nameof(IConfigStore.WriteSyncObject)).GetGetMethod();
  410. var IConfigStore_WriteTo = IConfigStore_t.GetMethod(nameof(IConfigStore.WriteTo));
  411. var IConfigStore_ReadFrom = IConfigStore_t.GetMethod(nameof(IConfigStore.ReadFrom));
  412. #region IConfigStore.SyncObject
  413. var syncObjProp = typeBuilder.DefineProperty(nameof(IConfigStore.SyncObject), PropertyAttributes.None, typeof(WaitHandle), null);
  414. var syncObjPropGet = typeBuilder.DefineMethod($"<g>{nameof(IConfigStore.SyncObject)}", virtualPropertyMethodAttr, syncObjProp.PropertyType, Type.EmptyTypes);
  415. syncObjProp.SetGetMethod(syncObjPropGet);
  416. typeBuilder.DefineMethodOverride(syncObjPropGet, IConfigStore_GetSyncObject);
  417. {
  418. var il = syncObjPropGet.GetILGenerator();
  419. il.Emit(OpCodes.Ldarg_0);
  420. il.Emit(OpCodes.Call, Impl.FindImplMethod);
  421. il.Emit(OpCodes.Tailcall);
  422. il.Emit(OpCodes.Call, Impl.SyncObjectGetMethod);
  423. il.Emit(OpCodes.Ret);
  424. }
  425. #endregion
  426. #region IConfigStore.WriteSyncObject
  427. var writeSyncObjProp = typeBuilder.DefineProperty(nameof(IConfigStore.WriteSyncObject), PropertyAttributes.None, typeof(WaitHandle), null);
  428. var writeSyncObjPropGet = typeBuilder.DefineMethod($"<g>{nameof(IConfigStore.WriteSyncObject)}", virtualPropertyMethodAttr, writeSyncObjProp.PropertyType, Type.EmptyTypes);
  429. writeSyncObjProp.SetGetMethod(writeSyncObjPropGet);
  430. typeBuilder.DefineMethodOverride(writeSyncObjPropGet, IConfigStore_GetWriteSyncObject);
  431. {
  432. var il = writeSyncObjPropGet.GetILGenerator();
  433. il.Emit(OpCodes.Ldarg_0);
  434. il.Emit(OpCodes.Call, Impl.FindImplMethod);
  435. il.Emit(OpCodes.Tailcall);
  436. il.Emit(OpCodes.Call, Impl.WriteSyncObjectGetMethod);
  437. il.Emit(OpCodes.Ret);
  438. }
  439. #endregion
  440. #region IConfigStore.WriteTo
  441. var writeTo = typeBuilder.DefineMethod($"<>{nameof(IConfigStore.WriteTo)}", virtualMemberMethod, null, new[] { typeof(IConfigProvider) });
  442. typeBuilder.DefineMethodOverride(writeTo, IConfigStore_WriteTo);
  443. {
  444. var il = writeTo.GetILGenerator();
  445. il.Emit(OpCodes.Ldarg_0);
  446. il.Emit(OpCodes.Call, Impl.FindImplMethod);
  447. il.Emit(OpCodes.Ldarg_1);
  448. il.Emit(OpCodes.Tailcall);
  449. il.Emit(OpCodes.Call, Impl.WriteToMethod);
  450. il.Emit(OpCodes.Ret);
  451. }
  452. #endregion
  453. #region IConfigStore.ReadFrom
  454. var readFrom = typeBuilder.DefineMethod($"<>{nameof(IConfigStore.ReadFrom)}", virtualMemberMethod, null, new[] { typeof(IConfigProvider) });
  455. typeBuilder.DefineMethodOverride(readFrom, IConfigStore_ReadFrom);
  456. {
  457. var il = readFrom.GetILGenerator();
  458. il.Emit(OpCodes.Ldarg_0);
  459. il.Emit(OpCodes.Call, Impl.FindImplMethod);
  460. il.Emit(OpCodes.Ldarg_1);
  461. il.Emit(OpCodes.Tailcall);
  462. il.Emit(OpCodes.Call, Impl.ReadFromMethod);
  463. il.Emit(OpCodes.Ret);
  464. }
  465. #endregion
  466. #endregion
  467. #region Changed
  468. var coreChanged = typeBuilder.DefineMethod(
  469. "<>Changed",
  470. MethodAttributes.Public | MethodAttributes.HideBySig,
  471. null, Type.EmptyTypes);
  472. {
  473. var il = coreChanged.GetILGenerator();
  474. il.Emit(OpCodes.Ldarg_0);
  475. il.Emit(OpCodes.Call, Impl.ImplSignalChangedMethod);
  476. il.Emit(OpCodes.Ret); // simply call our impl's SignalChanged method and return
  477. }
  478. if (baseChanged != null) {
  479. var changedMethod = typeBuilder.DefineMethod( // copy to override baseChanged
  480. baseChanged.Name,
  481. MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.Final | MethodAttributes.HideBySig,
  482. null, Type.EmptyTypes);
  483. typeBuilder.DefineMethodOverride(changedMethod, baseChanged);
  484. {
  485. var il = changedMethod.GetILGenerator();
  486. il.Emit(OpCodes.Ldarg_0);
  487. il.Emit(OpCodes.Call, baseChanged); // call base
  488. il.Emit(OpCodes.Ldarg_0);
  489. il.Emit(OpCodes.Tailcall);
  490. il.Emit(OpCodes.Call, coreChanged); // call back to the core change method
  491. il.Emit(OpCodes.Ret);
  492. }
  493. coreChanged = changedMethod; // switch to calling this version instead of just the default
  494. }
  495. #endregion
  496. // TODO: generate overrides for all the virtual properties
  497. var genType = typeBuilder.CreateType();
  498. var parentParam = Expression.Parameter(typeof(IGeneratedStore), "parent");
  499. var creatorDel = Expression.Lambda<Func<IGeneratedStore, IConfigStore>>(
  500. Expression.New(ctor, parentParam), parentParam
  501. ).Compile();
  502. { // register a member map
  503. var dict = new Dictionary<string, Type>();
  504. foreach (var member in structure)
  505. dict.Add(member.Name, member.Type);
  506. memberMaps.Add(type, dict);
  507. }
  508. return creatorDel;
  509. }
  510. #region Utility
  511. private static void EmitLogError(ILGenerator il, string message, bool tailcall = false, Action<ILGenerator> expected = null, Action<ILGenerator> found = null)
  512. {
  513. if (expected == null) expected = il => il.Emit(OpCodes.Ldnull);
  514. if (found == null) found = il => il.Emit(OpCodes.Ldnull);
  515. expected(il);
  516. found(il);
  517. il.Emit(OpCodes.Ldstr, message);
  518. if (tailcall) il.Emit(OpCodes.Tailcall);
  519. il.Emit(OpCodes.Call, LogErrorMethod);
  520. }
  521. private static readonly MethodInfo Type_GetTypeFromHandle = typeof(Type).GetMethod(nameof(Type.GetTypeFromHandle));
  522. private static void EmitTypeof(ILGenerator il, Type type)
  523. {
  524. il.Emit(OpCodes.Ldtoken, type);
  525. il.Emit(OpCodes.Call, Type_GetTypeFromHandle);
  526. }
  527. private static void EmitNumberConvertTo(ILGenerator il, Type to, Type from)
  528. { // WARNING: THIS USES THE NO-OVERFLOW OPCODES
  529. if (to == typeof(IntPtr)) il.Emit(OpCodes.Conv_I);
  530. else if (to == typeof(UIntPtr)) il.Emit(OpCodes.Conv_U);
  531. else if (to == typeof(sbyte)) il.Emit(OpCodes.Conv_I1);
  532. else if (to == typeof(byte)) il.Emit(OpCodes.Conv_U1);
  533. else if (to == typeof(short)) il.Emit(OpCodes.Conv_I2);
  534. else if (to == typeof(ushort)) il.Emit(OpCodes.Conv_U2);
  535. else if (to == typeof(int)) il.Emit(OpCodes.Conv_I4);
  536. else if (to == typeof(uint)) il.Emit(OpCodes.Conv_U4);
  537. else if (to == typeof(long)) il.Emit(OpCodes.Conv_I8);
  538. else if (to == typeof(ulong)) il.Emit(OpCodes.Conv_U8);
  539. else if (to == typeof(float))
  540. {
  541. if (from == typeof(byte)
  542. || from == typeof(ushort)
  543. || from == typeof(uint)
  544. || from == typeof(ulong)
  545. || from == typeof(UIntPtr)) il.Emit(OpCodes.Conv_R_Un);
  546. il.Emit(OpCodes.Conv_R4);
  547. }
  548. else if (to == typeof(double))
  549. {
  550. if (from == typeof(byte)
  551. || from == typeof(ushort)
  552. || from == typeof(uint)
  553. || from == typeof(ulong)
  554. || from == typeof(UIntPtr)) il.Emit(OpCodes.Conv_R_Un);
  555. il.Emit(OpCodes.Conv_R8);
  556. }
  557. }
  558. private static void EmitCreateChildGenerated(ILGenerator il, Type childType)
  559. {
  560. var method = CreateGParent.MakeGenericMethod(childType);
  561. il.Emit(OpCodes.Ldarg_0);
  562. il.Emit(OpCodes.Call, method);
  563. }
  564. #endregion
  565. private static readonly MethodInfo LogErrorMethod = typeof(GeneratedStore).GetMethod(nameof(LogError), BindingFlags.NonPublic | BindingFlags.Static);
  566. internal static void LogError(Type expected, Type found, string message)
  567. {
  568. Logger.config.Notice($"{message}{(expected == null ? "" : $" (expected {expected}, found {found?.ToString() ?? "null"})")}");
  569. }
  570. // expects the this param to be on the stack
  571. private static void EmitMemberFix(ILGenerator il, SerializedMemberInfo member)
  572. {
  573. // TODO: impl
  574. }
  575. #region Serialize
  576. // emit takes no args, leaves Value at top of stack
  577. private static void EmitSerializeMember(ILGenerator il, SerializedMemberInfo member)
  578. {
  579. // TODO: impl
  580. il.Emit(OpCodes.Ldnull);
  581. }
  582. #endregion
  583. #region Deserialize
  584. private static Type GetExpectedValueTypeForType(Type valT)
  585. {
  586. if (typeof(Value).IsAssignableFrom(valT)) // this is a Value subtype
  587. return valT;
  588. if (valT == typeof(string)) return typeof(Text);
  589. if (valT == typeof(bool)) return typeof(Boolean);
  590. if (valT == typeof(byte)
  591. || valT == typeof(sbyte)
  592. || valT == typeof(short)
  593. || valT == typeof(ushort)
  594. || valT == typeof(int)
  595. || valT == typeof(uint)
  596. || valT == typeof(long)
  597. || valT == typeof(ulong)) return typeof(Integer);
  598. if (valT == typeof(float)
  599. || valT == typeof(double)
  600. || valT == typeof(decimal)) return typeof(FloatingPoint);
  601. if (typeof(IEnumerable).IsAssignableFrom(valT)) return typeof(List);
  602. // TODO: fill this out the rest of the way
  603. // TODO: support converters
  604. return typeof(Map); // default for various objects
  605. }
  606. private static void EmitDeserializeGeneratedValue(ILGenerator il, Type targetType, Type srcType, Func<Type, int, LocalBuilder> GetLocal)
  607. {
  608. var IGeneratedStore_ValueSet = typeof(IGeneratedStore).GetProperty(nameof(IGeneratedStore.Values)).GetSetMethod();
  609. var valuel = GetLocal(srcType, 0);
  610. il.Emit(OpCodes.Stloc, valuel);
  611. EmitCreateChildGenerated(il, targetType);
  612. il.Emit(OpCodes.Dup);
  613. il.Emit(OpCodes.Ldloc, valuel);
  614. il.Emit(OpCodes.Callvirt, IGeneratedStore_ValueSet);
  615. }
  616. // top of stack is the Value to deserialize; the type will be as returned from GetExpectedValueTypeForType
  617. // after, top of stack will be thing to write to field
  618. private static void EmitDeserializeValue(ILGenerator il, Type targetType, Label nextLabel, Func<Type, int, LocalBuilder> GetLocal)
  619. {
  620. if (typeof(Value).IsAssignableFrom(targetType)) return; // do nothing
  621. var expected = GetExpectedValueTypeForType(targetType);
  622. if (expected == typeof(Text))
  623. {
  624. var getter = expected.GetProperty(nameof(Text.Value)).GetGetMethod();
  625. il.Emit(OpCodes.Call, getter);
  626. }
  627. else if (expected == typeof(Boolean))
  628. {
  629. var getter = expected.GetProperty(nameof(Boolean.Value)).GetGetMethod();
  630. il.Emit(OpCodes.Call, getter);
  631. }
  632. else if (expected == typeof(Integer))
  633. {
  634. var getter = expected.GetProperty(nameof(Integer.Value)).GetGetMethod();
  635. il.Emit(OpCodes.Call, getter);
  636. EmitNumberConvertTo(il, targetType, getter.ReturnType);
  637. }
  638. else if (expected == typeof(FloatingPoint))
  639. {
  640. var getter = expected.GetProperty(nameof(FloatingPoint.Value)).GetGetMethod();
  641. il.Emit(OpCodes.Call, getter);
  642. EmitNumberConvertTo(il, targetType, getter.ReturnType);
  643. } // TODO: implement stuff for lists and maps of various types (probably call out somewhere else to figure out what to do)
  644. else if (expected == typeof(Map))
  645. {
  646. EmitDeserializeGeneratedValue(il, targetType, expected, GetLocal);
  647. }
  648. else // TODO: support converters
  649. {
  650. il.Emit(OpCodes.Pop);
  651. il.Emit(OpCodes.Ldnull);
  652. }
  653. }
  654. // emit takes the value being deserialized, logs on error, leaves nothing on stack
  655. private static void EmitDeserializeMember(ILGenerator il, SerializedMemberInfo member, Label nextLabel, Action<ILGenerator> getValue, List<LocalBuilder> locals)
  656. {
  657. var Object_GetType = typeof(object).GetMethod(nameof(Object.GetType));
  658. var implLabel = il.DefineLabel();
  659. var passedTypeCheck = il.DefineLabel();
  660. var expectType = GetExpectedValueTypeForType(member.Type);
  661. void EmitStore(Action<ILGenerator> value)
  662. {
  663. il.Emit(OpCodes.Ldarg_0); // load this
  664. value(il);
  665. if (member.IsField)
  666. il.Emit(OpCodes.Stfld, member.Member as FieldInfo);
  667. else
  668. { // member is a property
  669. var prop = member.Member as PropertyInfo;
  670. var setter = prop.GetSetMethod();
  671. if (setter == null) throw new InvalidOperationException($"Property {member.Name} does not have a setter and is not ignored");
  672. il.Emit(OpCodes.Call, setter);
  673. }
  674. }
  675. LocalBuilder GetLocal(Type ty, int i = 0)
  676. {
  677. var builder = locals.Where(b => b.LocalType == ty).Skip(i).FirstOrDefault();
  678. if (builder == null)
  679. {
  680. builder = il.DeclareLocal(ty);
  681. locals.Add(builder);
  682. }
  683. return builder;
  684. }
  685. il.Emit(OpCodes.Dup);
  686. il.Emit(OpCodes.Brtrue_S, implLabel); // null check
  687. if (member.Type.IsValueType)
  688. {
  689. il.Emit(OpCodes.Pop);
  690. EmitLogError(il, $"Member {member.Name} ({member.Type}) not nullable", tailcall: false,
  691. expected: il => EmitTypeof(il, expectType));
  692. il.Emit(OpCodes.Br, nextLabel);
  693. }
  694. else
  695. {
  696. il.Emit(OpCodes.Pop);
  697. EmitStore(il => il.Emit(OpCodes.Ldnull));
  698. il.Emit(OpCodes.Br, nextLabel);
  699. }
  700. il.MarkLabel(implLabel);
  701. il.Emit(OpCodes.Isinst, expectType); //replaces on stack
  702. il.Emit(OpCodes.Dup); // duplicate cloned value
  703. il.Emit(OpCodes.Brtrue, passedTypeCheck); // null check
  704. var errorHandle = il.DefineLabel();
  705. // special cases to handle coersion between Float and Int
  706. if (expectType == typeof(FloatingPoint))
  707. {
  708. var specialTypeCheck = il.DefineLabel();
  709. il.Emit(OpCodes.Pop);
  710. getValue(il);
  711. il.Emit(OpCodes.Isinst, typeof(Integer)); //replaces on stack
  712. il.Emit(OpCodes.Dup); // duplicate cloned value
  713. il.Emit(OpCodes.Brfalse, errorHandle); // null check
  714. var Integer_CoerceToFloat = typeof(Integer).GetMethod(nameof(Integer.AsFloat));
  715. il.Emit(OpCodes.Call, Integer_CoerceToFloat);
  716. il.Emit(OpCodes.Br, passedTypeCheck);
  717. }
  718. else if (expectType == typeof(Integer))
  719. {
  720. var specialTypeCheck = il.DefineLabel();
  721. il.Emit(OpCodes.Pop);
  722. getValue(il);
  723. il.Emit(OpCodes.Isinst, typeof(FloatingPoint)); //replaces on stack
  724. il.Emit(OpCodes.Dup); // duplicate cloned value
  725. il.Emit(OpCodes.Brfalse, errorHandle); // null check
  726. var Float_CoerceToInt = typeof(FloatingPoint).GetMethod(nameof(FloatingPoint.AsInteger));
  727. il.Emit(OpCodes.Call, Float_CoerceToInt);
  728. il.Emit(OpCodes.Br, passedTypeCheck);
  729. }
  730. il.MarkLabel(errorHandle);
  731. il.Emit(OpCodes.Pop);
  732. EmitLogError(il, $"Unexpected type deserializing {member.Name}", tailcall: false,
  733. expected: il => EmitTypeof(il, expectType), found: il =>
  734. {
  735. getValue(il);
  736. il.Emit(OpCodes.Callvirt, Object_GetType);
  737. });
  738. il.Emit(OpCodes.Br, nextLabel);
  739. il.MarkLabel(passedTypeCheck);
  740. var local = GetLocal(member.Type);
  741. EmitDeserializeValue(il, member.Type, nextLabel, GetLocal);
  742. il.Emit(OpCodes.Stloc, local);
  743. EmitStore(il => il.Emit(OpCodes.Ldloc, local));
  744. }
  745. #endregion
  746. }
  747. }