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.

728 lines
34 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.ComponentModel;
  7. using System.Linq;
  8. using System.Linq.Expressions;
  9. using System.Reflection;
  10. using System.Reflection.Emit;
  11. using System.Text;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. #if NET3
  15. using Net3_Proxy;
  16. using Array = Net3_Proxy.Array;
  17. #endif
  18. namespace IPA.Config.Stores
  19. {
  20. internal static partial class GeneratedStoreImpl
  21. {
  22. internal delegate IConfigStore GeneratedStoreCreator(IGeneratedStore parent);
  23. private static void GetMethodThis(ILGenerator il) => il.Emit(OpCodes.Ldarg_0);
  24. private static (GeneratedStoreCreator ctor, Type type) MakeCreator(Type type)
  25. { // note that this does not and should not use converters by default for everything
  26. if (!type.IsClass) throw new ArgumentException("Config type is not a class");
  27. var baseCtor = type.GetConstructor(Type.EmptyTypes); // get a default constructor
  28. if (baseCtor == null)
  29. throw new ArgumentException("Config type does not have a public parameterless constructor");
  30. #region Parse base object structure
  31. const BindingFlags overrideMemberFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
  32. var baseChanged = type.GetMethod("Changed", overrideMemberFlags, null, Type.EmptyTypes, Array.Empty<ParameterModifier>());
  33. if (baseChanged != null && IsMethodInvalid(baseChanged, typeof(void))) baseChanged = null;
  34. var baseOnReload = type.GetMethod("OnReload", overrideMemberFlags, null, Type.EmptyTypes, Array.Empty<ParameterModifier>());
  35. if (baseOnReload != null && IsMethodInvalid(baseOnReload, typeof(void))) baseOnReload = null;
  36. var baseCopyFrom = type.GetMethod("CopyFrom", overrideMemberFlags, null, new[] { type }, Array.Empty<ParameterModifier>());
  37. if (baseCopyFrom != null && IsMethodInvalid(baseCopyFrom, typeof(void))) baseCopyFrom = null;
  38. var baseChangeTransaction = type.GetMethod("ChangeTransaction", overrideMemberFlags, null, Type.EmptyTypes, Array.Empty<ParameterModifier>());
  39. if (baseChangeTransaction != null && IsMethodInvalid(baseChangeTransaction, typeof(IDisposable))) baseChangeTransaction = null;
  40. var isINotifyPropertyChanged = type.FindInterfaces((i, t) => i == (Type)t, typeof(INotifyPropertyChanged)).Length != 0;
  41. var hasNotifyAttribute = type.GetCustomAttribute<NotifyPropertyChangesAttribute>() != null;
  42. var structure = ReadObjectMembers(type);
  43. if (!structure.Any())
  44. Logger.config.Warn($"Custom type {type.FullName} has no accessible members");
  45. #endregion
  46. var typeBuilder = Module.DefineType($"{type.FullName}<Generated>",
  47. TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.Class, type);
  48. var typeField = typeBuilder.DefineField("<>_type", typeof(Type), FieldAttributes.Private | FieldAttributes.InitOnly);
  49. var implField = typeBuilder.DefineField("<>_impl", typeof(Impl), FieldAttributes.Private | FieldAttributes.InitOnly);
  50. var parentField = typeBuilder.DefineField("<>_parent", typeof(IGeneratedStore), FieldAttributes.Private | FieldAttributes.InitOnly);
  51. /*#region Converter fields
  52. var uniqueConverterTypes = structure.Where(m => m.HasConverter).Select(m => m.Converter).Distinct().ToArray();
  53. var converterFields = new Dictionary<Type, FieldInfo>(uniqueConverterTypes.Length);
  54. foreach (var convType in uniqueConverterTypes)
  55. {
  56. var field = typeBuilder.DefineField($"<converter>_{convType}", convType,
  57. FieldAttributes.Private | FieldAttributes.InitOnly | FieldAttributes.Static);
  58. converterFields.Add(convType, field);
  59. foreach (var member in structure.Where(m => m.HasConverter && m.Converter == convType))
  60. member.ConverterField = field;
  61. }
  62. #endregion
  63. #region Static constructor
  64. var cctor = typeBuilder.DefineConstructor(MethodAttributes.Static, CallingConventions.Standard, Type.EmptyTypes);
  65. {
  66. var il = cctor.GetILGenerator();
  67. foreach (var kvp in converterFields)
  68. {
  69. var typeCtor = kvp.Key.GetConstructor(Type.EmptyTypes);
  70. il.Emit(OpCodes.Newobj, typeCtor);
  71. il.Emit(OpCodes.Stsfld, kvp.Value);
  72. }
  73. il.Emit(OpCodes.Ret);
  74. }
  75. #endregion*/
  76. //CreateAndInitializeConvertersFor(type, structure);
  77. #region Constructor
  78. var ctor = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new[] { typeof(IGeneratedStore) });
  79. {
  80. var il = ctor.GetILGenerator();
  81. il.Emit(OpCodes.Ldarg_0); // keep this at bottom of stack
  82. il.Emit(OpCodes.Dup);
  83. il.Emit(OpCodes.Call, baseCtor);
  84. il.Emit(OpCodes.Dup);
  85. il.Emit(OpCodes.Ldarg_1); // load parent
  86. il.Emit(OpCodes.Stfld, parentField);
  87. il.Emit(OpCodes.Dup);
  88. EmitTypeof(il, type);
  89. il.Emit(OpCodes.Stfld, typeField);
  90. var noImplLabel = il.DefineLabel();
  91. il.Emit(OpCodes.Ldarg_1);
  92. il.Emit(OpCodes.Brtrue, noImplLabel);
  93. il.Emit(OpCodes.Dup);
  94. il.Emit(OpCodes.Dup);
  95. il.Emit(OpCodes.Newobj, Impl.Ctor);
  96. il.Emit(OpCodes.Stfld, implField);
  97. il.MarkLabel(noImplLabel);
  98. var GetLocal = MakeLocalAllocator(il);
  99. foreach (var member in structure)
  100. {
  101. if (NeedsCorrection(member))
  102. EmitLoadCorrectStore(il, member, false, true, GetLocal, GetMethodThis, GetMethodThis, GetMethodThis);
  103. }
  104. il.Emit(OpCodes.Pop);
  105. il.Emit(OpCodes.Ret);
  106. }
  107. #endregion
  108. const MethodAttributes propertyMethodAttr = MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig;
  109. const MethodAttributes virtualPropertyMethodAttr = propertyMethodAttr | MethodAttributes.Virtual | MethodAttributes.Final;
  110. const MethodAttributes virtualMemberMethod = MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.Final;
  111. #region INotifyPropertyChanged
  112. MethodBuilder notifyChanged = null;
  113. if (isINotifyPropertyChanged || hasNotifyAttribute)
  114. {
  115. var INotifyPropertyChanged_t = typeof(INotifyPropertyChanged);
  116. typeBuilder.AddInterfaceImplementation(INotifyPropertyChanged_t);
  117. var INotifyPropertyChanged_PropertyChanged =
  118. INotifyPropertyChanged_t.GetEvent(nameof(INotifyPropertyChanged.PropertyChanged));
  119. var PropertyChangedEventHandler_t = typeof(PropertyChangedEventHandler);
  120. var PropertyChangedEventHander_Invoke = PropertyChangedEventHandler_t.GetMethod(nameof(PropertyChangedEventHandler.Invoke));
  121. var PropertyChangedEventArgs_t = typeof(PropertyChangedEventArgs);
  122. var PropertyChangedEventArgs_ctor = PropertyChangedEventArgs_t.GetConstructor(new[] { typeof(string) });
  123. var Delegate_t = typeof(Delegate);
  124. var Delegate_Combine = Delegate_t.GetMethod(nameof(Delegate.Combine), BindingFlags.Static | BindingFlags.Public, null,
  125. new[] { Delegate_t, Delegate_t }, Array.Empty<ParameterModifier>());
  126. var Delegate_Remove = Delegate_t.GetMethod(nameof(Delegate.Remove), BindingFlags.Static | BindingFlags.Public, null,
  127. new[] { Delegate_t, Delegate_t }, Array.Empty<ParameterModifier>());
  128. var CompareExchange = typeof(Interlocked).GetMethods()
  129. .Where(m => m.Name == nameof(Interlocked.CompareExchange))
  130. .Where(m => m.ContainsGenericParameters)
  131. .Where(m => m.GetParameters().Length == 3).First()
  132. .MakeGenericMethod(PropertyChangedEventHandler_t);
  133. var basePropChangedEvent = type.GetEvents()
  134. .Where(e => e.GetAddMethod().GetBaseDefinition().DeclaringType == INotifyPropertyChanged_t)
  135. .FirstOrDefault();
  136. var basePropChangedAdd = basePropChangedEvent?.GetAddMethod();
  137. var basePropChangedRemove = basePropChangedEvent?.GetRemoveMethod();
  138. var PropertyChanged_backing = typeBuilder.DefineField("<event>PropertyChanged", PropertyChangedEventHandler_t, FieldAttributes.Private);
  139. var add_PropertyChanged = typeBuilder.DefineMethod("<add>PropertyChanged",
  140. MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Final | MethodAttributes.Virtual,
  141. null, new[] { PropertyChangedEventHandler_t });
  142. typeBuilder.DefineMethodOverride(add_PropertyChanged, INotifyPropertyChanged_PropertyChanged.GetAddMethod());
  143. if (basePropChangedAdd != null)
  144. typeBuilder.DefineMethodOverride(add_PropertyChanged, basePropChangedAdd);
  145. {
  146. var il = add_PropertyChanged.GetILGenerator();
  147. var loopLabel = il.DefineLabel();
  148. var delTemp = il.DeclareLocal(PropertyChangedEventHandler_t);
  149. il.Emit(OpCodes.Ldarg_0);
  150. il.Emit(OpCodes.Ldfld, PropertyChanged_backing);
  151. il.MarkLabel(loopLabel);
  152. il.Emit(OpCodes.Stloc, delTemp);
  153. il.Emit(OpCodes.Ldarg_0);
  154. il.Emit(OpCodes.Ldflda, PropertyChanged_backing);
  155. il.Emit(OpCodes.Ldloc, delTemp);
  156. il.Emit(OpCodes.Ldarg_1);
  157. il.Emit(OpCodes.Call, Delegate_Combine);
  158. il.Emit(OpCodes.Castclass, PropertyChangedEventHandler_t);
  159. il.Emit(OpCodes.Ldloc, delTemp);
  160. il.Emit(OpCodes.Call, CompareExchange);
  161. il.Emit(OpCodes.Dup);
  162. il.Emit(OpCodes.Ldloc, delTemp);
  163. il.Emit(OpCodes.Bne_Un_S, loopLabel);
  164. il.Emit(OpCodes.Ret);
  165. }
  166. var remove_PropertyChanged = typeBuilder.DefineMethod("<remove>PropertyChanged",
  167. MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Final | MethodAttributes.Virtual,
  168. null, new[] { PropertyChangedEventHandler_t });
  169. typeBuilder.DefineMethodOverride(remove_PropertyChanged, INotifyPropertyChanged_PropertyChanged.GetRemoveMethod());
  170. if (basePropChangedRemove != null)
  171. typeBuilder.DefineMethodOverride(remove_PropertyChanged, basePropChangedRemove);
  172. {
  173. var il = remove_PropertyChanged.GetILGenerator();
  174. var loopLabel = il.DefineLabel();
  175. var delTemp = il.DeclareLocal(PropertyChangedEventHandler_t);
  176. il.Emit(OpCodes.Ldarg_0);
  177. il.Emit(OpCodes.Ldfld, PropertyChanged_backing);
  178. il.MarkLabel(loopLabel);
  179. il.Emit(OpCodes.Stloc, delTemp);
  180. il.Emit(OpCodes.Ldarg_0);
  181. il.Emit(OpCodes.Ldflda, PropertyChanged_backing);
  182. il.Emit(OpCodes.Ldloc, delTemp);
  183. il.Emit(OpCodes.Ldarg_1);
  184. il.Emit(OpCodes.Call, Delegate_Remove);
  185. il.Emit(OpCodes.Castclass, PropertyChangedEventHandler_t);
  186. il.Emit(OpCodes.Ldloc, delTemp);
  187. il.Emit(OpCodes.Call, CompareExchange);
  188. il.Emit(OpCodes.Dup);
  189. il.Emit(OpCodes.Ldloc, delTemp);
  190. il.Emit(OpCodes.Bne_Un_S, loopLabel);
  191. il.Emit(OpCodes.Ret);
  192. }
  193. var PropertyChanged_event = typeBuilder.DefineEvent(nameof(INotifyPropertyChanged.PropertyChanged), EventAttributes.None, PropertyChangedEventHandler_t);
  194. PropertyChanged_event.SetAddOnMethod(add_PropertyChanged);
  195. PropertyChanged_event.SetRemoveOnMethod(remove_PropertyChanged);
  196. notifyChanged = typeBuilder.DefineMethod("<>NotifyChanged",
  197. MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Final, null, new[] { typeof(string) });
  198. {
  199. var il = notifyChanged.GetILGenerator();
  200. var invokeNonNull = il.DefineLabel();
  201. il.Emit(OpCodes.Ldarg_0);
  202. il.Emit(OpCodes.Ldfld, PropertyChanged_backing);
  203. il.Emit(OpCodes.Dup);
  204. il.Emit(OpCodes.Brtrue, invokeNonNull);
  205. il.Emit(OpCodes.Pop);
  206. il.Emit(OpCodes.Ret);
  207. il.MarkLabel(invokeNonNull);
  208. il.Emit(OpCodes.Ldarg_0);
  209. il.Emit(OpCodes.Ldarg_1);
  210. il.Emit(OpCodes.Newobj, PropertyChangedEventArgs_ctor);
  211. il.Emit(OpCodes.Call, PropertyChangedEventHander_Invoke);
  212. il.Emit(OpCodes.Ret);
  213. }
  214. }
  215. #endregion
  216. #region IGeneratedStore
  217. typeBuilder.AddInterfaceImplementation(typeof(IGeneratedStore));
  218. var IGeneratedStore_t = typeof(IGeneratedStore);
  219. var IGeneratedStore_GetImpl = IGeneratedStore_t.GetProperty(nameof(IGeneratedStore.Impl)).GetGetMethod();
  220. var IGeneratedStore_GetType = IGeneratedStore_t.GetProperty(nameof(IGeneratedStore.Type)).GetGetMethod();
  221. var IGeneratedStore_GetParent = IGeneratedStore_t.GetProperty(nameof(IGeneratedStore.Parent)).GetGetMethod();
  222. var IGeneratedStore_Serialize = IGeneratedStore_t.GetMethod(nameof(IGeneratedStore.Serialize));
  223. var IGeneratedStore_Deserialize = IGeneratedStore_t.GetMethod(nameof(IGeneratedStore.Deserialize));
  224. var IGeneratedStore_OnReload = IGeneratedStore_t.GetMethod(nameof(IGeneratedStore.OnReload));
  225. var IGeneratedStore_Changed = IGeneratedStore_t.GetMethod(nameof(IGeneratedStore.Changed));
  226. var IGeneratedStore_ChangeTransaction = IGeneratedStore_t.GetMethod(nameof(IGeneratedStore.ChangeTransaction));
  227. #region IGeneratedStore.OnReload
  228. var onReload = typeBuilder.DefineMethod($"<>{nameof(IGeneratedStore.OnReload)}", virtualMemberMethod, null, Type.EmptyTypes);
  229. typeBuilder.DefineMethodOverride(onReload, IGeneratedStore_OnReload);
  230. if (baseOnReload != null) typeBuilder.DefineMethodOverride(onReload, baseOnReload);
  231. {
  232. var il = onReload.GetILGenerator();
  233. if (baseOnReload != null)
  234. {
  235. il.Emit(OpCodes.Ldarg_0); // load this
  236. il.Emit(OpCodes.Tailcall);
  237. il.Emit(OpCodes.Call, baseOnReload); // load impl field
  238. }
  239. il.Emit(OpCodes.Ret);
  240. }
  241. #endregion
  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.Serialize
  279. var serializeGen = typeBuilder.DefineMethod($"<>{nameof(IGeneratedStore.Serialize)}", virtualPropertyMethodAttr, IGeneratedStore_Serialize.ReturnType, Type.EmptyTypes);
  280. typeBuilder.DefineMethodOverride(serializeGen, IGeneratedStore_Serialize);
  281. { // this is non-locking because the only code that will call this will already own the correct lock
  282. var il = serializeGen.GetILGenerator();
  283. var GetLocal = MakeLocalAllocator(il);
  284. EmitSerializeStructure(il, structure, GetLocal, GetMethodThis);
  285. il.Emit(OpCodes.Ret);
  286. }
  287. #endregion
  288. #region IGeneratedStore.Deserialize
  289. var deserializeGen = typeBuilder.DefineMethod($"<>{nameof(IGeneratedStore.Deserialize)}", virtualPropertyMethodAttr, null,
  290. new[] { IGeneratedStore_Deserialize.GetParameters()[0].ParameterType });
  291. typeBuilder.DefineMethodOverride(deserializeGen, IGeneratedStore_Deserialize);
  292. { // this is non-locking because the only code that will call this will already own the correct lock
  293. var il = deserializeGen.GetILGenerator();
  294. var Map_t = typeof(Map);
  295. var Map_TryGetValue = Map_t.GetMethod(nameof(Map.TryGetValue));
  296. var Object_GetType = typeof(object).GetMethod(nameof(Object.GetType));
  297. var valueLocal = il.DeclareLocal(typeof(Value));
  298. var mapLocal = il.DeclareLocal(typeof(Map));
  299. var nonNull = il.DefineLabel();
  300. il.Emit(OpCodes.Ldarg_1);
  301. il.Emit(OpCodes.Brtrue, nonNull);
  302. EmitLogError(il, "Attempting to deserialize null", tailcall: true);
  303. il.Emit(OpCodes.Ret);
  304. il.MarkLabel(nonNull);
  305. il.Emit(OpCodes.Ldarg_1);
  306. il.Emit(OpCodes.Isinst, Map_t);
  307. il.Emit(OpCodes.Dup); // duplicate cloned value
  308. il.Emit(OpCodes.Stloc, mapLocal);
  309. var notMapError = il.DefineLabel();
  310. il.Emit(OpCodes.Brtrue, notMapError);
  311. // handle error
  312. EmitLogError(il, $"Invalid root for deserializing {type.FullName}", tailcall: true,
  313. expected: il => EmitTypeof(il, Map_t), found: il =>
  314. {
  315. il.Emit(OpCodes.Ldarg_1);
  316. il.Emit(OpCodes.Callvirt, Object_GetType);
  317. });
  318. il.Emit(OpCodes.Ret);
  319. il.MarkLabel(notMapError);
  320. var GetLocal = MakeLocalAllocator(il);
  321. // head of stack is Map instance
  322. EmitDeserializeStructure(il, structure, mapLocal, valueLocal, GetLocal, GetMethodThis, GetMethodThis);
  323. if (notifyChanged != null)
  324. {
  325. foreach (var member in structure)
  326. {
  327. il.Emit(OpCodes.Ldarg_0);
  328. il.Emit(OpCodes.Ldstr, member.Name);
  329. il.Emit(OpCodes.Call, notifyChanged);
  330. }
  331. }
  332. il.Emit(OpCodes.Ret);
  333. }
  334. #endregion
  335. #endregion
  336. #region IConfigStore
  337. typeBuilder.AddInterfaceImplementation(typeof(IConfigStore));
  338. var IConfigStore_t = typeof(IConfigStore);
  339. var IConfigStore_GetSyncObject = IConfigStore_t.GetProperty(nameof(IConfigStore.SyncObject)).GetGetMethod();
  340. var IConfigStore_GetWriteSyncObject = IConfigStore_t.GetProperty(nameof(IConfigStore.WriteSyncObject)).GetGetMethod();
  341. var IConfigStore_WriteTo = IConfigStore_t.GetMethod(nameof(IConfigStore.WriteTo));
  342. var IConfigStore_ReadFrom = IConfigStore_t.GetMethod(nameof(IConfigStore.ReadFrom));
  343. #region IConfigStore.SyncObject
  344. var syncObjProp = typeBuilder.DefineProperty(nameof(IConfigStore.SyncObject), PropertyAttributes.None, typeof(WaitHandle), null);
  345. var syncObjPropGet = typeBuilder.DefineMethod($"<g>{nameof(IConfigStore.SyncObject)}", virtualPropertyMethodAttr, syncObjProp.PropertyType, Type.EmptyTypes);
  346. syncObjProp.SetGetMethod(syncObjPropGet);
  347. typeBuilder.DefineMethodOverride(syncObjPropGet, IConfigStore_GetSyncObject);
  348. {
  349. var il = syncObjPropGet.GetILGenerator();
  350. il.Emit(OpCodes.Ldarg_0);
  351. il.Emit(OpCodes.Tailcall);
  352. il.Emit(OpCodes.Call, Impl.ImplGetSyncObjectMethod);
  353. il.Emit(OpCodes.Ret);
  354. }
  355. #endregion
  356. #region IConfigStore.WriteSyncObject
  357. var writeSyncObjProp = typeBuilder.DefineProperty(nameof(IConfigStore.WriteSyncObject), PropertyAttributes.None, typeof(WaitHandle), null);
  358. var writeSyncObjPropGet = typeBuilder.DefineMethod($"<g>{nameof(IConfigStore.WriteSyncObject)}", virtualPropertyMethodAttr, writeSyncObjProp.PropertyType, Type.EmptyTypes);
  359. writeSyncObjProp.SetGetMethod(writeSyncObjPropGet);
  360. typeBuilder.DefineMethodOverride(writeSyncObjPropGet, IConfigStore_GetWriteSyncObject);
  361. {
  362. var il = writeSyncObjPropGet.GetILGenerator();
  363. il.Emit(OpCodes.Ldarg_0);
  364. il.Emit(OpCodes.Tailcall);
  365. il.Emit(OpCodes.Call, Impl.ImplGetWriteSyncObjectMethod);
  366. il.Emit(OpCodes.Ret);
  367. }
  368. #endregion
  369. #region IConfigStore.WriteTo
  370. var writeTo = typeBuilder.DefineMethod($"<>{nameof(IConfigStore.WriteTo)}", virtualMemberMethod, null, new[] { typeof(ConfigProvider) });
  371. typeBuilder.DefineMethodOverride(writeTo, IConfigStore_WriteTo);
  372. {
  373. var il = writeTo.GetILGenerator();
  374. il.Emit(OpCodes.Ldarg_0);
  375. il.Emit(OpCodes.Ldarg_1);
  376. il.Emit(OpCodes.Tailcall);
  377. il.Emit(OpCodes.Call, Impl.ImplWriteToMethod);
  378. il.Emit(OpCodes.Ret);
  379. }
  380. #endregion
  381. #region IConfigStore.ReadFrom
  382. var readFrom = typeBuilder.DefineMethod($"<>{nameof(IConfigStore.ReadFrom)}", virtualMemberMethod, null, new[] { typeof(ConfigProvider) });
  383. typeBuilder.DefineMethodOverride(readFrom, IConfigStore_ReadFrom);
  384. {
  385. var il = readFrom.GetILGenerator();
  386. il.Emit(OpCodes.Ldarg_0);
  387. il.Emit(OpCodes.Ldarg_1);
  388. il.Emit(OpCodes.Tailcall);
  389. il.Emit(OpCodes.Call, Impl.ImplReadFromMethod);
  390. il.Emit(OpCodes.Ret);
  391. }
  392. #endregion
  393. #endregion
  394. #region Changed
  395. var coreChanged = typeBuilder.DefineMethod(
  396. "<>Changed",
  397. virtualMemberMethod,
  398. null, Type.EmptyTypes);
  399. typeBuilder.DefineMethodOverride(coreChanged, IGeneratedStore_Changed);
  400. if (baseChanged != null)
  401. typeBuilder.DefineMethodOverride(coreChanged, baseChanged);
  402. {
  403. var il = coreChanged.GetILGenerator();
  404. if (baseChanged != null)
  405. {
  406. il.Emit(OpCodes.Ldarg_0);
  407. il.Emit(OpCodes.Call, baseChanged); // call base
  408. }
  409. il.Emit(OpCodes.Ldarg_0);
  410. il.Emit(OpCodes.Tailcall);
  411. il.Emit(OpCodes.Call, Impl.ImplSignalChangedMethod);
  412. il.Emit(OpCodes.Ret); // simply call our impl's SignalChanged method and return
  413. }
  414. #endregion
  415. #region ChangeTransaction
  416. var coreChangeTransaction = typeBuilder.DefineMethod(
  417. "<>ChangeTransaction",
  418. virtualMemberMethod,
  419. typeof(IDisposable), Type.EmptyTypes);
  420. typeBuilder.DefineMethodOverride(coreChangeTransaction, IGeneratedStore_ChangeTransaction);
  421. if (baseChangeTransaction != null)
  422. typeBuilder.DefineMethodOverride(coreChangeTransaction, baseChangeTransaction);
  423. {
  424. var il = coreChangeTransaction.GetILGenerator();
  425. il.Emit(OpCodes.Ldarg_0);
  426. if (baseChangeTransaction != null)
  427. {
  428. il.Emit(OpCodes.Ldarg_0);
  429. il.Emit(OpCodes.Call, baseChangeTransaction);
  430. }
  431. else
  432. il.Emit(OpCodes.Ldnull);
  433. il.Emit(OpCodes.Tailcall);
  434. il.Emit(OpCodes.Call, Impl.ImplChangeTransactionMethod);
  435. il.Emit(OpCodes.Ret);
  436. }
  437. #endregion
  438. #region IGeneratedStore<T>
  439. var IGeneratedStore_T_t = typeof(IGeneratedStore<>).MakeGenericType(type);
  440. typeBuilder.AddInterfaceImplementation(IGeneratedStore_T_t);
  441. var IGeneratedStore_T_CopyFrom = IGeneratedStore_T_t.GetMethod(nameof(IGeneratedStore<Config>.CopyFrom));
  442. #region IGeneratedStore<T>.CopyFrom
  443. var copyFrom = typeBuilder.DefineMethod($"<>{nameof(IGeneratedStore<Config>.CopyFrom)}", virtualMemberMethod, null, new[] { type, typeof(bool) });
  444. typeBuilder.DefineMethodOverride(copyFrom, IGeneratedStore_T_CopyFrom);
  445. {
  446. var il = copyFrom.GetILGenerator();
  447. var transactionLocal = il.DeclareLocal(IDisposable_t);
  448. var startLock = il.DefineLabel();
  449. il.Emit(OpCodes.Ldarg_2);
  450. il.Emit(OpCodes.Brfalse, startLock);
  451. il.Emit(OpCodes.Ldarg_0);
  452. il.Emit(OpCodes.Call, coreChangeTransaction); // take the write lock
  453. il.Emit(OpCodes.Stloc, transactionLocal);
  454. il.MarkLabel(startLock);
  455. var GetLocal = MakeLocalAllocator(il);
  456. foreach (var member in structure)
  457. {
  458. il.BeginExceptionBlock();
  459. EmitLoadCorrectStore(il, member, false, false, GetLocal, il => il.Emit(OpCodes.Ldarg_1), GetMethodThis, GetMethodThis);
  460. il.BeginCatchBlock(typeof(Exception));
  461. EmitWarnException(il, $"Error while copying from member {member.Name}");
  462. il.EndExceptionBlock();
  463. }
  464. if (notifyChanged != null)
  465. {
  466. foreach (var member in structure)
  467. {
  468. il.Emit(OpCodes.Ldarg_0);
  469. il.Emit(OpCodes.Ldstr, member.Name);
  470. il.Emit(OpCodes.Call, notifyChanged);
  471. }
  472. }
  473. var endLock = il.DefineLabel();
  474. il.Emit(OpCodes.Ldarg_2);
  475. il.Emit(OpCodes.Brfalse, endLock);
  476. il.Emit(OpCodes.Ldloc, transactionLocal);
  477. il.Emit(OpCodes.Callvirt, IDisposable_Dispose);
  478. il.MarkLabel(endLock);
  479. il.Emit(OpCodes.Ret);
  480. }
  481. #endregion
  482. #endregion
  483. #region base.CopyFrom
  484. if (baseCopyFrom != null)
  485. {
  486. var pubCopyFrom = typeBuilder.DefineMethod(
  487. baseCopyFrom.Name,
  488. virtualMemberMethod,
  489. null, new[] { type });
  490. typeBuilder.DefineMethodOverride(pubCopyFrom, baseCopyFrom);
  491. {
  492. var il = pubCopyFrom.GetILGenerator();
  493. il.Emit(OpCodes.Ldarg_0);
  494. il.Emit(OpCodes.Call, coreChangeTransaction);
  495. il.Emit(OpCodes.Ldarg_0);
  496. il.Emit(OpCodes.Ldarg_1);
  497. il.Emit(OpCodes.Ldc_I4_0);
  498. il.Emit(OpCodes.Call, copyFrom); // call internal
  499. il.Emit(OpCodes.Ldarg_0);
  500. il.Emit(OpCodes.Ldarg_1);
  501. il.Emit(OpCodes.Call, baseCopyFrom); // call base
  502. il.Emit(OpCodes.Tailcall);
  503. il.Emit(OpCodes.Callvirt, IDisposable_Dispose); // dispose transaction (which calls changed)
  504. il.Emit(OpCodes.Ret);
  505. }
  506. }
  507. #endregion
  508. #region Members
  509. foreach (var member in structure.Where(m => m.IsVirtual))
  510. { // IsVirtual implies !IsField
  511. var prop = member.Member as PropertyInfo;
  512. var get = prop.GetGetMethod(true);
  513. var set = prop.GetSetMethod(true);
  514. var propBuilder = typeBuilder.DefineProperty($"{member.Name}#", PropertyAttributes.None, member.Type, null);
  515. var propGet = typeBuilder.DefineMethod($"<g>{propBuilder.Name}", virtualPropertyMethodAttr, member.Type, Type.EmptyTypes);
  516. propBuilder.SetGetMethod(propGet);
  517. typeBuilder.DefineMethodOverride(propGet, get);
  518. {
  519. var il = propGet.GetILGenerator();
  520. var local = il.DeclareLocal(member.Type);
  521. il.Emit(OpCodes.Ldarg_0);
  522. il.Emit(OpCodes.Call, Impl.ImplTakeReadMethod); // take the read lock
  523. il.BeginExceptionBlock();
  524. il.Emit(OpCodes.Ldarg_0);
  525. il.Emit(OpCodes.Call, get); // call base getter
  526. il.Emit(OpCodes.Stloc, local);
  527. il.BeginFinallyBlock();
  528. il.Emit(OpCodes.Ldarg_0);
  529. il.Emit(OpCodes.Call, Impl.ImplReleaseReadMethod); // release the read lock
  530. il.EndExceptionBlock();
  531. il.Emit(OpCodes.Ldloc, local);
  532. il.Emit(OpCodes.Ret);
  533. }
  534. var propSet = typeBuilder.DefineMethod($"<s>{propBuilder.Name}", virtualPropertyMethodAttr, null, new[] { member.Type });
  535. propBuilder.SetSetMethod(propSet);
  536. typeBuilder.DefineMethodOverride(propSet, set);
  537. {
  538. var il = propSet.GetILGenerator();
  539. var transactionLocal = il.DeclareLocal(IDisposable_t);
  540. var GetLocal = MakeLocalAllocator(il);
  541. il.Emit(OpCodes.Ldarg_0);
  542. il.Emit(OpCodes.Call, coreChangeTransaction); // take the write lock
  543. il.Emit(OpCodes.Stloc, transactionLocal);
  544. il.BeginExceptionBlock();
  545. il.Emit(OpCodes.Ldarg_0);
  546. il.Emit(OpCodes.Ldarg_1);
  547. EmitCorrectMember(il, member, false, false, GetLocal, GetMethodThis, GetMethodThis);
  548. il.Emit(OpCodes.Call, set);
  549. il.BeginFinallyBlock();
  550. il.Emit(OpCodes.Ldloc, transactionLocal);
  551. il.Emit(OpCodes.Callvirt, IDisposable_Dispose);
  552. il.EndExceptionBlock();
  553. if (notifyChanged != null)
  554. {
  555. il.Emit(OpCodes.Ldarg_0);
  556. il.Emit(OpCodes.Ldstr, member.Name);
  557. il.Emit(OpCodes.Call, notifyChanged);
  558. }
  559. il.Emit(OpCodes.Ret);
  560. }
  561. }
  562. #endregion
  563. var genType = typeBuilder.CreateType();
  564. var parentParam = Expression.Parameter(typeof(IGeneratedStore), "parent");
  565. var creatorDel = Expression.Lambda<GeneratedStoreCreator>(
  566. Expression.New(ctor, parentParam), parentParam
  567. ).Compile();
  568. return (creatorDel, genType);
  569. }
  570. }
  571. }