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.

503 lines
22 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. #if NET3
  15. using Net3_Proxy;
  16. using Array = Net3_Proxy.Array;
  17. #endif
  18. [assembly: InternalsVisibleTo(IPA.Config.Stores.GeneratedStore.GeneratedAssemblyName)]
  19. namespace IPA.Config.Stores
  20. {
  21. /// <summary>
  22. /// A class providing an extension for <see cref="Config"/> to make it easy to use generated
  23. /// config stores.
  24. /// </summary>
  25. public static class GeneratedStoreExtensions
  26. {
  27. /// <summary>
  28. /// Creates a generated <see cref="IConfigStore"/> of type <typeparamref name="T"/>, registers it to
  29. /// the <see cref="Config"/> object, and returns it. This also forces a synchronous config load via
  30. /// <see cref="Config.LoadSync"/> if <paramref name="loadSync"/> is <see langword="true"/>.
  31. /// </summary>
  32. /// <remarks>
  33. /// <para>
  34. /// <typeparamref name="T"/> must be a non-<see langword="sealed"/> <see langword="class"/>.
  35. /// </para>
  36. /// <para>
  37. /// TODO: describe details of generated stores
  38. /// </para>
  39. /// </remarks>
  40. /// <typeparam name="T">the type to wrap</typeparam>
  41. /// <param name="cfg">the <see cref="Config"/> to register to</param>
  42. /// <param name="loadSync">whether to synchronously load the content, or trigger an async load</param>
  43. /// <returns>a generated instance of <typeparamref name="T"/> as a special <see cref="IConfigStore"/></returns>
  44. public static T Generated<T>(this Config cfg, bool loadSync = true) where T : class
  45. {
  46. var ret = GeneratedStore.Create<T>();
  47. cfg.SetStore(ret as IConfigStore);
  48. if (loadSync)
  49. cfg.LoadSync();
  50. else
  51. cfg.LoadAsync();
  52. return ret;
  53. }
  54. }
  55. internal static class GeneratedStore
  56. {
  57. internal interface IGeneratedStore
  58. {
  59. /// <summary>
  60. /// serializes/deserializes to Value
  61. /// </summary>
  62. Value Values { get; set; }
  63. Type Type { get; }
  64. IGeneratedStore Parent { get; }
  65. Impl Impl { get; }
  66. }
  67. internal class Impl : IConfigStore
  68. {
  69. private IGeneratedStore generated;
  70. internal static ConstructorInfo Ctor = typeof(Impl).GetConstructor(new[] { typeof(IGeneratedStore) });
  71. public Impl(IGeneratedStore store) => generated = store;
  72. private readonly AutoResetEvent resetEvent = new AutoResetEvent(false);
  73. public WaitHandle SyncObject => resetEvent;
  74. internal static MethodInfo SyncObjectGetMethod = typeof(Impl).GetProperty(nameof(SyncObject)).GetGetMethod();
  75. public ReaderWriterLockSlim WriteSyncObject { get; } = new ReaderWriterLockSlim();
  76. internal static MethodInfo WriteSyncObjectGetMethod = typeof(Impl).GetProperty(nameof(WriteSyncObject)).GetGetMethod();
  77. internal static MethodInfo ImplSignalChangedMethod = typeof(Impl).GetMethod(nameof(ImplSignalChanged));
  78. public static void ImplSignalChanged(IGeneratedStore s) => FindImpl(s).SignalChanged();
  79. public void SignalChanged() => resetEvent.Set();
  80. internal static MethodInfo ImplTakeReadMethod = typeof(Impl).GetMethod(nameof(ImplTakeRead));
  81. public static void ImplTakeRead(IGeneratedStore s) => FindImpl(s).TakeRead();
  82. public void TakeRead() => WriteSyncObject.EnterReadLock();
  83. internal static MethodInfo ImplReleaseReadMethod = typeof(Impl).GetMethod(nameof(ImplReleaseRead));
  84. public static void ImplReleaseRead(IGeneratedStore s) => FindImpl(s).ReleaseRead();
  85. public void ReleaseRead() => WriteSyncObject.ExitWriteLock();
  86. internal static MethodInfo ImplTakeWriteMethod = typeof(Impl).GetMethod(nameof(ImplTakeWrite));
  87. public static void ImplTakeWrite(IGeneratedStore s) => FindImpl(s).TakeWrite();
  88. public void TakeWrite() => WriteSyncObject.EnterWriteLock();
  89. internal static MethodInfo ImplReleaseWriteMethod = typeof(Impl).GetMethod(nameof(ImplReleaseWrite));
  90. public static void ImplReleaseWrite(IGeneratedStore s) => FindImpl(s).ReleaseWrite();
  91. public void ReleaseWrite() => WriteSyncObject.ExitWriteLock();
  92. internal static MethodInfo FindImplMethod = typeof(Impl).GetMethod(nameof(FindImpl));
  93. public static Impl FindImpl(IGeneratedStore store)
  94. {
  95. while (store != null) store = store.Parent; // walk to the top of the tree
  96. return store?.Impl;
  97. }
  98. internal static MethodInfo ReadFromMethod = typeof(Impl).GetMethod(nameof(ReadFrom));
  99. public void ReadFrom(IConfigProvider provider)
  100. {
  101. // TODO: implement
  102. Logger.config.Debug("Generated impl ReadFrom");
  103. Logger.config.Debug($"Read {provider.Load()}");
  104. }
  105. internal static MethodInfo WriteToMethod = typeof(Impl).GetMethod(nameof(WriteTo));
  106. public void WriteTo(IConfigProvider provider)
  107. {
  108. var values = generated.Values;
  109. // TODO: implement
  110. Logger.config.Debug("Generated impl WriteTo");
  111. }
  112. }
  113. private static Dictionary<Type, Func<IGeneratedStore, IConfigStore>> generatedCreators = new Dictionary<Type, Func<IGeneratedStore, IConfigStore>>();
  114. private static Dictionary<Type, Dictionary<string, Type>> memberMaps = new Dictionary<Type, Dictionary<string, Type>>();
  115. public static T Create<T>() where T : class => (T)Create(typeof(T));
  116. public static IConfigStore Create(Type type) => Create(type, null);
  117. private static IConfigStore Create(Type type, IGeneratedStore parent)
  118. {
  119. if (generatedCreators.TryGetValue(type, out var creator))
  120. return creator(parent);
  121. else
  122. {
  123. creator = MakeCreator(type);
  124. generatedCreators.Add(type, creator);
  125. return creator(parent);
  126. }
  127. }
  128. internal const string GeneratedAssemblyName = "IPA.Config.Generated";
  129. private static AssemblyBuilder assembly = null;
  130. private static AssemblyBuilder Assembly
  131. {
  132. get
  133. {
  134. if (assembly == null)
  135. {
  136. var name = new AssemblyName(GeneratedAssemblyName);
  137. assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.RunAndSave);
  138. }
  139. return assembly;
  140. }
  141. }
  142. internal static void DebugSaveAssembly(string file)
  143. {
  144. Assembly.Save(file);
  145. }
  146. private static ModuleBuilder module = null;
  147. private static ModuleBuilder Module
  148. {
  149. get
  150. {
  151. if (module == null)
  152. module = Assembly.DefineDynamicModule(Assembly.GetName().Name + ".dll");
  153. return module;
  154. }
  155. }
  156. private struct SerializedMemberInfo
  157. {
  158. public string Name;
  159. public MemberInfo Member;
  160. public bool IsVirtual;
  161. public Type Type;
  162. }
  163. private static Func<IGeneratedStore, IConfigStore> MakeCreator(Type type)
  164. {
  165. var baseCtor = type.GetConstructor(Type.EmptyTypes); // get a default constructor
  166. if (baseCtor == null)
  167. throw new ArgumentException("Config type does not have a public parameterless constructor");
  168. var typeBuilder = Module.DefineType($"{type.FullName}.Generated",
  169. TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.Class, type);
  170. var typeField = typeBuilder.DefineField("<>_type", typeof(Type), FieldAttributes.Private | FieldAttributes.InitOnly);
  171. var implField = typeBuilder.DefineField("<>_impl", typeof(Impl), FieldAttributes.Private | FieldAttributes.InitOnly);
  172. var parentField = typeBuilder.DefineField("<>_parent", typeof(IGeneratedStore), FieldAttributes.Private | FieldAttributes.InitOnly);
  173. var GetTypeFromHandle = typeof(Type).GetMethod(nameof(Type.GetTypeFromHandle));
  174. // TODO: possibly move all of this manual IL over to Linq.Expressions
  175. #region Parse base object structure
  176. var baseChanged = type.GetMethod("Changed", BindingFlags.Public | BindingFlags.Instance, null, Type.EmptyTypes, Array.Empty<ParameterModifier>());
  177. if (baseChanged != null && !baseChanged.IsVirtual) baseChanged = null; // limit this to just the one thing
  178. var structure = new Dictionary<string, SerializedMemberInfo>();
  179. // TODO: incorporate attributes
  180. // only looks at public properties
  181. foreach (var prop in type.GetProperties(BindingFlags.Instance | BindingFlags.Public))
  182. {
  183. var smi = new SerializedMemberInfo
  184. {
  185. Name = prop.Name,
  186. Member = prop,
  187. IsVirtual = (prop.GetGetMethod(true)?.IsVirtual ?? false) ||
  188. (prop.GetSetMethod(true)?.IsVirtual ?? false),
  189. Type = prop.PropertyType
  190. };
  191. structure.Add(smi.Name, smi);
  192. }
  193. // only look at public fields
  194. foreach (var field in type.GetFields(BindingFlags.Instance | BindingFlags.Public))
  195. {
  196. var smi = new SerializedMemberInfo
  197. {
  198. Name = field.Name,
  199. Member = field,
  200. IsVirtual = false,
  201. Type = field.FieldType
  202. };
  203. structure.Add(smi.Name, smi);
  204. }
  205. #endregion
  206. #region Constructor
  207. // takes its parent
  208. var ctor = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new[] { typeof(IGeneratedStore) });
  209. {
  210. var il = ctor.GetILGenerator();
  211. il.Emit(OpCodes.Ldarg_0); // keep this at bottom of stack
  212. il.Emit(OpCodes.Dup);
  213. il.Emit(OpCodes.Call, baseCtor);
  214. il.Emit(OpCodes.Dup);
  215. il.Emit(OpCodes.Ldarg_1); // load parent
  216. il.Emit(OpCodes.Stfld, parentField);
  217. il.Emit(OpCodes.Dup);
  218. il.Emit(OpCodes.Ldtoken, type);
  219. il.Emit(OpCodes.Call, GetTypeFromHandle); // effectively typeof(type)
  220. il.Emit(OpCodes.Stfld, typeField);
  221. il.Emit(OpCodes.Dup);
  222. il.Emit(OpCodes.Dup);
  223. il.Emit(OpCodes.Newobj, Impl.Ctor);
  224. il.Emit(OpCodes.Stfld, implField);
  225. foreach (var kvp in structure)
  226. EmitMemberFix(il, kvp.Value);
  227. il.Emit(OpCodes.Pop);
  228. il.Emit(OpCodes.Ret);
  229. }
  230. #endregion
  231. const MethodAttributes propertyMethodAttr = MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig;
  232. const MethodAttributes virtualPropertyMethodAttr = propertyMethodAttr | MethodAttributes.Virtual | MethodAttributes.Final;
  233. const MethodAttributes virtualMemberMethod = MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.Final;
  234. #region IGeneratedStore
  235. typeBuilder.AddInterfaceImplementation(typeof(IGeneratedStore));
  236. var IGeneratedStore_t = typeof(IGeneratedStore);
  237. var IGeneratedStore_GetImpl = IGeneratedStore_t.GetProperty(nameof(IGeneratedStore.Impl)).GetGetMethod();
  238. var IGeneratedStore_GetType = IGeneratedStore_t.GetProperty(nameof(IGeneratedStore.Type)).GetGetMethod();
  239. var IGeneratedStore_GetParent = IGeneratedStore_t.GetProperty(nameof(IGeneratedStore.Parent)).GetGetMethod();
  240. var IGeneratedStore_GetValues = IGeneratedStore_t.GetProperty(nameof(IGeneratedStore.Values)).GetGetMethod();
  241. var IGeneratedStore_SetValues = IGeneratedStore_t.GetProperty(nameof(IGeneratedStore.Values)).GetSetMethod();
  242. #region IGeneratedStore.Impl
  243. var implProp = typeBuilder.DefineProperty(nameof(IGeneratedStore.Impl), PropertyAttributes.None, typeof(Impl), null);
  244. var implPropGet = typeBuilder.DefineMethod($"<g>{nameof(IGeneratedStore.Impl)}", virtualPropertyMethodAttr, implProp.PropertyType, Type.EmptyTypes);
  245. implProp.SetGetMethod(implPropGet);
  246. typeBuilder.DefineMethodOverride(implPropGet, IGeneratedStore_GetImpl);
  247. {
  248. var il = implPropGet.GetILGenerator();
  249. il.Emit(OpCodes.Ldarg_0); // load this
  250. il.Emit(OpCodes.Ldfld, implField); // load impl field
  251. il.Emit(OpCodes.Ret);
  252. }
  253. #endregion
  254. #region IGeneratedStore.Type
  255. var typeProp = typeBuilder.DefineProperty(nameof(IGeneratedStore.Type), PropertyAttributes.None, typeof(Type), null);
  256. var typePropGet = typeBuilder.DefineMethod($"<g>{nameof(IGeneratedStore.Type)}", virtualPropertyMethodAttr, typeProp.PropertyType, Type.EmptyTypes);
  257. typeProp.SetGetMethod(typePropGet);
  258. typeBuilder.DefineMethodOverride(typePropGet, IGeneratedStore_GetType);
  259. {
  260. var il = typePropGet.GetILGenerator();
  261. il.Emit(OpCodes.Ldarg_0); // load this
  262. il.Emit(OpCodes.Ldfld, typeField); // load impl field
  263. il.Emit(OpCodes.Ret);
  264. }
  265. #endregion
  266. #region IGeneratedStore.Parent
  267. var parentProp = typeBuilder.DefineProperty(nameof(IGeneratedStore.Parent), PropertyAttributes.None, typeof(IGeneratedStore), null);
  268. var parentPropGet = typeBuilder.DefineMethod($"<g>{nameof(IGeneratedStore.Parent)}", virtualPropertyMethodAttr, parentProp.PropertyType, Type.EmptyTypes);
  269. parentProp.SetGetMethod(parentPropGet);
  270. typeBuilder.DefineMethodOverride(parentPropGet, IGeneratedStore_GetParent);
  271. {
  272. var il = parentPropGet.GetILGenerator();
  273. il.Emit(OpCodes.Ldarg_0); // load this
  274. il.Emit(OpCodes.Ldfld, parentField); // load impl field
  275. il.Emit(OpCodes.Ret);
  276. }
  277. #endregion
  278. #region IGeneratedStore.Values
  279. var valuesProp = typeBuilder.DefineProperty(nameof(IGeneratedStore.Values), PropertyAttributes.None, typeof(Value), null);
  280. var valuesPropGet = typeBuilder.DefineMethod($"<g>{nameof(IGeneratedStore.Values)}", virtualPropertyMethodAttr, valuesProp.PropertyType, Type.EmptyTypes);
  281. var valuesPropSet = typeBuilder.DefineMethod($"<s>{nameof(IGeneratedStore.Values)}", virtualPropertyMethodAttr, null, new[] { valuesProp.PropertyType });
  282. valuesProp.SetGetMethod(valuesPropGet);
  283. typeBuilder.DefineMethodOverride(valuesPropGet, IGeneratedStore_GetValues);
  284. valuesProp.SetSetMethod(valuesPropSet);
  285. typeBuilder.DefineMethodOverride(valuesPropSet, IGeneratedStore_SetValues);
  286. { // this is non-locking because the only code that will call this will already own the correct lock
  287. var il = valuesPropGet.GetILGenerator();
  288. // TODO: implement get_Values
  289. il.Emit(OpCodes.Ldnull);
  290. il.Emit(OpCodes.Ret);
  291. }
  292. { // this is non-locking because the only code that will call this will already own the correct lock
  293. var il = valuesPropSet.GetILGenerator();
  294. // TODO: implement set_Values
  295. il.Emit(OpCodes.Ret);
  296. }
  297. #endregion
  298. #endregion
  299. #region IConfigStore
  300. typeBuilder.AddInterfaceImplementation(typeof(IConfigStore));
  301. var IConfigStore_t = typeof(IConfigStore);
  302. var IConfigStore_GetSyncObject = IConfigStore_t.GetProperty(nameof(IConfigStore.SyncObject)).GetGetMethod();
  303. var IConfigStore_GetWriteSyncObject = IConfigStore_t.GetProperty(nameof(IConfigStore.WriteSyncObject)).GetGetMethod();
  304. var IConfigStore_WriteTo = IConfigStore_t.GetMethod(nameof(IConfigStore.WriteTo));
  305. var IConfigStore_ReadFrom = IConfigStore_t.GetMethod(nameof(IConfigStore.ReadFrom));
  306. #region IConfigStore.SyncObject
  307. var syncObjProp = typeBuilder.DefineProperty(nameof(IConfigStore.SyncObject), PropertyAttributes.None, typeof(WaitHandle), null);
  308. var syncObjPropGet = typeBuilder.DefineMethod($"<g>{nameof(IConfigStore.SyncObject)}", virtualPropertyMethodAttr, syncObjProp.PropertyType, Type.EmptyTypes);
  309. syncObjProp.SetGetMethod(syncObjPropGet);
  310. typeBuilder.DefineMethodOverride(syncObjPropGet, IConfigStore_GetSyncObject);
  311. {
  312. var il = syncObjPropGet.GetILGenerator();
  313. il.Emit(OpCodes.Ldarg_0);
  314. il.Emit(OpCodes.Call, Impl.FindImplMethod);
  315. il.Emit(OpCodes.Tailcall);
  316. il.Emit(OpCodes.Call, Impl.SyncObjectGetMethod);
  317. il.Emit(OpCodes.Ret);
  318. }
  319. #endregion
  320. #region IConfigStore.WriteSyncObject
  321. var writeSyncObjProp = typeBuilder.DefineProperty(nameof(IConfigStore.WriteSyncObject), PropertyAttributes.None, typeof(WaitHandle), null);
  322. var writeSyncObjPropGet = typeBuilder.DefineMethod($"<g>{nameof(IConfigStore.WriteSyncObject)}", virtualPropertyMethodAttr, writeSyncObjProp.PropertyType, Type.EmptyTypes);
  323. writeSyncObjProp.SetGetMethod(writeSyncObjPropGet);
  324. typeBuilder.DefineMethodOverride(writeSyncObjPropGet, IConfigStore_GetWriteSyncObject);
  325. {
  326. var il = writeSyncObjPropGet.GetILGenerator();
  327. il.Emit(OpCodes.Ldarg_0);
  328. il.Emit(OpCodes.Call, Impl.FindImplMethod);
  329. il.Emit(OpCodes.Tailcall);
  330. il.Emit(OpCodes.Call, Impl.WriteSyncObjectGetMethod);
  331. il.Emit(OpCodes.Ret);
  332. }
  333. #endregion
  334. #region IConfigStore.WriteTo
  335. var writeTo = typeBuilder.DefineMethod($"<>{nameof(IConfigStore.WriteTo)}", virtualMemberMethod, null, new[] { typeof(IConfigProvider) });
  336. typeBuilder.DefineMethodOverride(writeTo, IConfigStore_WriteTo);
  337. {
  338. var il = writeTo.GetILGenerator();
  339. il.Emit(OpCodes.Ldarg_0);
  340. il.Emit(OpCodes.Call, Impl.FindImplMethod);
  341. il.Emit(OpCodes.Ldarg_1);
  342. il.Emit(OpCodes.Tailcall);
  343. il.Emit(OpCodes.Call, Impl.WriteToMethod);
  344. il.Emit(OpCodes.Ret);
  345. }
  346. #endregion
  347. #region IConfigStore.ReadFrom
  348. var readFrom = typeBuilder.DefineMethod($"<>{nameof(IConfigStore.ReadFrom)}", virtualMemberMethod, null, new[] { typeof(IConfigProvider) });
  349. typeBuilder.DefineMethodOverride(readFrom, IConfigStore_ReadFrom);
  350. {
  351. var il = readFrom.GetILGenerator();
  352. il.Emit(OpCodes.Ldarg_0);
  353. il.Emit(OpCodes.Call, Impl.FindImplMethod);
  354. il.Emit(OpCodes.Ldarg_1);
  355. il.Emit(OpCodes.Tailcall);
  356. il.Emit(OpCodes.Call, Impl.ReadFromMethod);
  357. il.Emit(OpCodes.Ret);
  358. }
  359. #endregion
  360. #endregion
  361. #region Changed
  362. var coreChanged = typeBuilder.DefineMethod(
  363. "<>Changed",
  364. MethodAttributes.Public | MethodAttributes.HideBySig,
  365. null, Type.EmptyTypes);
  366. {
  367. var il = coreChanged.GetILGenerator();
  368. il.Emit(OpCodes.Ldarg_0);
  369. il.Emit(OpCodes.Call, Impl.ImplSignalChangedMethod);
  370. il.Emit(OpCodes.Ret); // simply call our impl's SignalChanged method and return
  371. }
  372. if (baseChanged != null) {
  373. var changedMethod = typeBuilder.DefineMethod( // copy to override baseChanged
  374. baseChanged.Name,
  375. MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.Final | MethodAttributes.HideBySig,
  376. null, Type.EmptyTypes);
  377. typeBuilder.DefineMethodOverride(changedMethod, baseChanged);
  378. {
  379. var il = changedMethod.GetILGenerator();
  380. il.Emit(OpCodes.Ldarg_0);
  381. il.Emit(OpCodes.Call, baseChanged); // call base
  382. il.Emit(OpCodes.Ldarg_0);
  383. il.Emit(OpCodes.Tailcall);
  384. il.Emit(OpCodes.Call, coreChanged); // call back to the core change method
  385. il.Emit(OpCodes.Ret);
  386. }
  387. coreChanged = changedMethod; // switch to calling this version instead of just the default
  388. }
  389. #endregion
  390. // TODO: generate overrides for all the virtual properties
  391. var genType = typeBuilder.CreateType();
  392. var parentParam = Expression.Parameter(typeof(IGeneratedStore), "parent");
  393. var creatorDel = Expression.Lambda<Func<IGeneratedStore, IConfigStore>>(
  394. Expression.New(ctor, parentParam), parentParam
  395. ).Compile();
  396. { // register a member map
  397. var dict = new Dictionary<string, Type>();
  398. foreach (var kvp in structure)
  399. dict.Add(kvp.Key, kvp.Value.Type);
  400. memberMaps.Add(type, dict);
  401. }
  402. return creatorDel;
  403. }
  404. // expects the this param to be on the stack
  405. private static void EmitMemberFix(ILGenerator il, SerializedMemberInfo member)
  406. {
  407. }
  408. }
  409. }