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.

742 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. #region Constructor
  77. var ctor = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new[] { typeof(IGeneratedStore) });
  78. {
  79. var il = ctor.GetILGenerator();
  80. il.Emit(OpCodes.Ldarg_0); // keep this at bottom of stack
  81. il.Emit(OpCodes.Dup);
  82. il.Emit(OpCodes.Call, baseCtor);
  83. il.Emit(OpCodes.Dup);
  84. il.Emit(OpCodes.Ldarg_1); // load parent
  85. il.Emit(OpCodes.Stfld, parentField);
  86. il.Emit(OpCodes.Dup);
  87. EmitTypeof(il, type);
  88. il.Emit(OpCodes.Stfld, typeField);
  89. var noImplLabel = il.DefineLabel();
  90. il.Emit(OpCodes.Ldarg_1);
  91. il.Emit(OpCodes.Brtrue, noImplLabel);
  92. il.Emit(OpCodes.Dup);
  93. il.Emit(OpCodes.Dup);
  94. il.Emit(OpCodes.Newobj, Impl.Ctor);
  95. il.Emit(OpCodes.Stfld, implField);
  96. il.MarkLabel(noImplLabel);
  97. var GetLocal = MakeGetLocal(il);
  98. foreach (var member in structure)
  99. {
  100. if (NeedsCorrection(member))
  101. EmitLoadCorrectStore(il, member, false, true, GetLocal, GetMethodThis, GetMethodThis, GetMethodThis);
  102. }
  103. il.Emit(OpCodes.Pop);
  104. il.Emit(OpCodes.Ret);
  105. }
  106. #endregion
  107. const MethodAttributes propertyMethodAttr = MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig;
  108. const MethodAttributes virtualPropertyMethodAttr = propertyMethodAttr | MethodAttributes.Virtual | MethodAttributes.Final;
  109. const MethodAttributes virtualMemberMethod = MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.Final;
  110. #region INotifyPropertyChanged
  111. MethodBuilder notifyChanged = null;
  112. if (isINotifyPropertyChanged || hasNotifyAttribute)
  113. {
  114. var INotifyPropertyChanged_t = typeof(INotifyPropertyChanged);
  115. typeBuilder.AddInterfaceImplementation(INotifyPropertyChanged_t);
  116. var INotifyPropertyChanged_PropertyChanged =
  117. INotifyPropertyChanged_t.GetEvent(nameof(INotifyPropertyChanged.PropertyChanged));
  118. var PropertyChangedEventHandler_t = typeof(PropertyChangedEventHandler);
  119. var PropertyChangedEventHander_Invoke = PropertyChangedEventHandler_t.GetMethod(nameof(PropertyChangedEventHandler.Invoke));
  120. var PropertyChangedEventArgs_t = typeof(PropertyChangedEventArgs);
  121. var PropertyChangedEventArgs_ctor = PropertyChangedEventArgs_t.GetConstructor(new[] { typeof(string) });
  122. var Delegate_t = typeof(Delegate);
  123. var Delegate_Combine = Delegate_t.GetMethod(nameof(Delegate.Combine), BindingFlags.Static | BindingFlags.Public, null,
  124. new[] { Delegate_t, Delegate_t }, Array.Empty<ParameterModifier>());
  125. var Delegate_Remove = Delegate_t.GetMethod(nameof(Delegate.Remove), BindingFlags.Static | BindingFlags.Public, null,
  126. new[] { Delegate_t, Delegate_t }, Array.Empty<ParameterModifier>());
  127. var CompareExchange = typeof(Interlocked).GetMethods()
  128. .Where(m => m.Name == nameof(Interlocked.CompareExchange))
  129. .Where(m => m.ContainsGenericParameters)
  130. .Where(m => m.GetParameters().Length == 3).First()
  131. .MakeGenericMethod(PropertyChangedEventHandler_t);
  132. var basePropChangedEvent = type.GetEvents()
  133. .Where(e => e.GetAddMethod().GetBaseDefinition().DeclaringType == INotifyPropertyChanged_t)
  134. .FirstOrDefault();
  135. var basePropChangedAdd = basePropChangedEvent?.GetAddMethod();
  136. var basePropChangedRemove = basePropChangedEvent?.GetRemoveMethod();
  137. var PropertyChanged_backing = typeBuilder.DefineField("<event>PropertyChanged", PropertyChangedEventHandler_t, FieldAttributes.Private);
  138. var add_PropertyChanged = typeBuilder.DefineMethod("<add>PropertyChanged",
  139. MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Final | MethodAttributes.Virtual,
  140. null, new[] { PropertyChangedEventHandler_t });
  141. typeBuilder.DefineMethodOverride(add_PropertyChanged, INotifyPropertyChanged_PropertyChanged.GetAddMethod());
  142. if (basePropChangedAdd != null)
  143. typeBuilder.DefineMethodOverride(add_PropertyChanged, basePropChangedAdd);
  144. {
  145. var il = add_PropertyChanged.GetILGenerator();
  146. var loopLabel = il.DefineLabel();
  147. var delTemp = il.DeclareLocal(PropertyChangedEventHandler_t);
  148. il.Emit(OpCodes.Ldarg_0);
  149. il.Emit(OpCodes.Ldfld, PropertyChanged_backing);
  150. il.MarkLabel(loopLabel);
  151. il.Emit(OpCodes.Stloc, delTemp);
  152. il.Emit(OpCodes.Ldarg_0);
  153. il.Emit(OpCodes.Ldflda, PropertyChanged_backing);
  154. il.Emit(OpCodes.Ldloc, delTemp);
  155. il.Emit(OpCodes.Ldarg_1);
  156. il.Emit(OpCodes.Call, Delegate_Combine);
  157. il.Emit(OpCodes.Castclass, PropertyChangedEventHandler_t);
  158. il.Emit(OpCodes.Ldloc, delTemp);
  159. il.Emit(OpCodes.Call, CompareExchange);
  160. il.Emit(OpCodes.Dup);
  161. il.Emit(OpCodes.Ldloc, delTemp);
  162. il.Emit(OpCodes.Bne_Un_S, loopLabel);
  163. il.Emit(OpCodes.Ret);
  164. }
  165. var remove_PropertyChanged = typeBuilder.DefineMethod("<remove>PropertyChanged",
  166. MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Final | MethodAttributes.Virtual,
  167. null, new[] { PropertyChangedEventHandler_t });
  168. typeBuilder.DefineMethodOverride(remove_PropertyChanged, INotifyPropertyChanged_PropertyChanged.GetRemoveMethod());
  169. if (basePropChangedRemove != null)
  170. typeBuilder.DefineMethodOverride(remove_PropertyChanged, basePropChangedRemove);
  171. {
  172. var il = remove_PropertyChanged.GetILGenerator();
  173. var loopLabel = il.DefineLabel();
  174. var delTemp = il.DeclareLocal(PropertyChangedEventHandler_t);
  175. il.Emit(OpCodes.Ldarg_0);
  176. il.Emit(OpCodes.Ldfld, PropertyChanged_backing);
  177. il.MarkLabel(loopLabel);
  178. il.Emit(OpCodes.Stloc, delTemp);
  179. il.Emit(OpCodes.Ldarg_0);
  180. il.Emit(OpCodes.Ldflda, PropertyChanged_backing);
  181. il.Emit(OpCodes.Ldloc, delTemp);
  182. il.Emit(OpCodes.Ldarg_1);
  183. il.Emit(OpCodes.Call, Delegate_Remove);
  184. il.Emit(OpCodes.Castclass, PropertyChangedEventHandler_t);
  185. il.Emit(OpCodes.Ldloc, delTemp);
  186. il.Emit(OpCodes.Call, CompareExchange);
  187. il.Emit(OpCodes.Dup);
  188. il.Emit(OpCodes.Ldloc, delTemp);
  189. il.Emit(OpCodes.Bne_Un_S, loopLabel);
  190. il.Emit(OpCodes.Ret);
  191. }
  192. var PropertyChanged_event = typeBuilder.DefineEvent(nameof(INotifyPropertyChanged.PropertyChanged), EventAttributes.None, PropertyChangedEventHandler_t);
  193. PropertyChanged_event.SetAddOnMethod(add_PropertyChanged);
  194. PropertyChanged_event.SetRemoveOnMethod(remove_PropertyChanged);
  195. notifyChanged = typeBuilder.DefineMethod("<>NotifyChanged",
  196. MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Final, null, new[] { typeof(string) });
  197. {
  198. var il = notifyChanged.GetILGenerator();
  199. var invokeNonNull = il.DefineLabel();
  200. il.Emit(OpCodes.Ldarg_0);
  201. il.Emit(OpCodes.Ldfld, PropertyChanged_backing);
  202. il.Emit(OpCodes.Dup);
  203. il.Emit(OpCodes.Brtrue, invokeNonNull);
  204. il.Emit(OpCodes.Pop);
  205. il.Emit(OpCodes.Ret);
  206. il.MarkLabel(invokeNonNull);
  207. il.Emit(OpCodes.Ldarg_0);
  208. il.Emit(OpCodes.Ldarg_1);
  209. il.Emit(OpCodes.Newobj, PropertyChangedEventArgs_ctor);
  210. il.Emit(OpCodes.Call, PropertyChangedEventHander_Invoke);
  211. il.Emit(OpCodes.Ret);
  212. }
  213. }
  214. #endregion
  215. #region IGeneratedStore
  216. typeBuilder.AddInterfaceImplementation(typeof(IGeneratedStore));
  217. var IGeneratedStore_t = typeof(IGeneratedStore);
  218. var IGeneratedStore_GetImpl = IGeneratedStore_t.GetProperty(nameof(IGeneratedStore.Impl)).GetGetMethod();
  219. var IGeneratedStore_GetType = IGeneratedStore_t.GetProperty(nameof(IGeneratedStore.Type)).GetGetMethod();
  220. var IGeneratedStore_GetParent = IGeneratedStore_t.GetProperty(nameof(IGeneratedStore.Parent)).GetGetMethod();
  221. var IGeneratedStore_Serialize = IGeneratedStore_t.GetMethod(nameof(IGeneratedStore.Serialize));
  222. var IGeneratedStore_Deserialize = IGeneratedStore_t.GetMethod(nameof(IGeneratedStore.Deserialize));
  223. var IGeneratedStore_OnReload = IGeneratedStore_t.GetMethod(nameof(IGeneratedStore.OnReload));
  224. var IGeneratedStore_Changed = IGeneratedStore_t.GetMethod(nameof(IGeneratedStore.Changed));
  225. var IGeneratedStore_ChangeTransaction = IGeneratedStore_t.GetMethod(nameof(IGeneratedStore.ChangeTransaction));
  226. #region IGeneratedStore.OnReload
  227. var onReload = typeBuilder.DefineMethod($"<>{nameof(IGeneratedStore.OnReload)}", virtualMemberMethod, null, Type.EmptyTypes);
  228. typeBuilder.DefineMethodOverride(onReload, IGeneratedStore_OnReload);
  229. if (baseOnReload != null) typeBuilder.DefineMethodOverride(onReload, baseOnReload);
  230. {
  231. var il = onReload.GetILGenerator();
  232. if (baseOnReload != null)
  233. {
  234. il.Emit(OpCodes.Ldarg_0); // load this
  235. il.Emit(OpCodes.Tailcall);
  236. il.Emit(OpCodes.Call, baseOnReload); // load impl field
  237. }
  238. il.Emit(OpCodes.Ret);
  239. }
  240. #endregion
  241. #region IGeneratedStore.Impl
  242. var implProp = typeBuilder.DefineProperty(nameof(IGeneratedStore.Impl), PropertyAttributes.None, typeof(Impl), null);
  243. var implPropGet = typeBuilder.DefineMethod($"<g>{nameof(IGeneratedStore.Impl)}", virtualPropertyMethodAttr, implProp.PropertyType, Type.EmptyTypes);
  244. implProp.SetGetMethod(implPropGet);
  245. typeBuilder.DefineMethodOverride(implPropGet, IGeneratedStore_GetImpl);
  246. {
  247. var il = implPropGet.GetILGenerator();
  248. il.Emit(OpCodes.Ldarg_0); // load this
  249. il.Emit(OpCodes.Ldfld, implField); // load impl field
  250. il.Emit(OpCodes.Ret);
  251. }
  252. #endregion
  253. #region IGeneratedStore.Type
  254. var typeProp = typeBuilder.DefineProperty(nameof(IGeneratedStore.Type), PropertyAttributes.None, typeof(Type), null);
  255. var typePropGet = typeBuilder.DefineMethod($"<g>{nameof(IGeneratedStore.Type)}", virtualPropertyMethodAttr, typeProp.PropertyType, Type.EmptyTypes);
  256. typeProp.SetGetMethod(typePropGet);
  257. typeBuilder.DefineMethodOverride(typePropGet, IGeneratedStore_GetType);
  258. {
  259. var il = typePropGet.GetILGenerator();
  260. il.Emit(OpCodes.Ldarg_0); // load this
  261. il.Emit(OpCodes.Ldfld, typeField); // load impl field
  262. il.Emit(OpCodes.Ret);
  263. }
  264. #endregion
  265. #region IGeneratedStore.Parent
  266. var parentProp = typeBuilder.DefineProperty(nameof(IGeneratedStore.Parent), PropertyAttributes.None, typeof(IGeneratedStore), null);
  267. var parentPropGet = typeBuilder.DefineMethod($"<g>{nameof(IGeneratedStore.Parent)}", virtualPropertyMethodAttr, parentProp.PropertyType, Type.EmptyTypes);
  268. parentProp.SetGetMethod(parentPropGet);
  269. typeBuilder.DefineMethodOverride(parentPropGet, IGeneratedStore_GetParent);
  270. {
  271. var il = parentPropGet.GetILGenerator();
  272. il.Emit(OpCodes.Ldarg_0); // load this
  273. il.Emit(OpCodes.Ldfld, parentField); // load impl field
  274. il.Emit(OpCodes.Ret);
  275. }
  276. #endregion
  277. #region IGeneratedStore.Serialize
  278. var serializeGen = typeBuilder.DefineMethod($"<>{nameof(IGeneratedStore.Serialize)}", virtualPropertyMethodAttr, IGeneratedStore_Serialize.ReturnType, Type.EmptyTypes);
  279. typeBuilder.DefineMethodOverride(serializeGen, IGeneratedStore_Serialize);
  280. { // this is non-locking because the only code that will call this will already own the correct lock
  281. var il = serializeGen.GetILGenerator();
  282. var Map_Add = typeof(Map).GetMethod(nameof(Map.Add));
  283. var mapLocal = il.DeclareLocal(typeof(Map));
  284. var GetLocal = MakeGetLocal(il);
  285. var valLocal = GetLocal(typeof(Value));
  286. il.Emit(OpCodes.Call, typeof(Value).GetMethod(nameof(Value.Map)));
  287. il.Emit(OpCodes.Stloc, mapLocal);
  288. foreach (var member in structure)
  289. {
  290. EmitSerializeMember(il, member, GetLocal);
  291. il.Emit(OpCodes.Stloc, valLocal);
  292. il.Emit(OpCodes.Ldloc, mapLocal);
  293. il.Emit(OpCodes.Ldstr, member.Name);
  294. il.Emit(OpCodes.Ldloc, valLocal);
  295. il.Emit(OpCodes.Call, Map_Add);
  296. }
  297. il.Emit(OpCodes.Ldloc, mapLocal);
  298. il.Emit(OpCodes.Ret);
  299. }
  300. #endregion
  301. #region IGeneratedStore.Deserialize
  302. var deserializeGen = typeBuilder.DefineMethod($"<>{nameof(IGeneratedStore.Deserialize)}", virtualPropertyMethodAttr, null,
  303. new[] { IGeneratedStore_Deserialize.GetParameters()[0].ParameterType });
  304. typeBuilder.DefineMethodOverride(deserializeGen, IGeneratedStore_Deserialize);
  305. { // this is non-locking because the only code that will call this will already own the correct lock
  306. var il = deserializeGen.GetILGenerator();
  307. var Map_t = typeof(Map);
  308. var Map_TryGetValue = Map_t.GetMethod(nameof(Map.TryGetValue));
  309. var Object_GetType = typeof(object).GetMethod(nameof(Object.GetType));
  310. var valueLocal = il.DeclareLocal(typeof(Value));
  311. var mapLocal = il.DeclareLocal(typeof(Map));
  312. var nonNull = il.DefineLabel();
  313. il.Emit(OpCodes.Ldarg_1);
  314. il.Emit(OpCodes.Brtrue, nonNull);
  315. EmitLogError(il, "Attempting to deserialize null", tailcall: true);
  316. il.Emit(OpCodes.Ret);
  317. il.MarkLabel(nonNull);
  318. il.Emit(OpCodes.Ldarg_1);
  319. il.Emit(OpCodes.Isinst, Map_t);
  320. il.Emit(OpCodes.Dup); // duplicate cloned value
  321. il.Emit(OpCodes.Stloc, mapLocal);
  322. var notMapError = il.DefineLabel();
  323. il.Emit(OpCodes.Brtrue, notMapError);
  324. // handle error
  325. EmitLogError(il, $"Invalid root for deserializing {type.FullName}", tailcall: true,
  326. expected: il => EmitTypeof(il, Map_t), found: il =>
  327. {
  328. il.Emit(OpCodes.Ldarg_1);
  329. il.Emit(OpCodes.Callvirt, Object_GetType);
  330. });
  331. il.Emit(OpCodes.Ret);
  332. il.MarkLabel(notMapError);
  333. var GetLocal = MakeGetLocal(il);
  334. // head of stack is Map instance
  335. EmitDeserializeStructure(il, structure, mapLocal, valueLocal, GetLocal, GetMethodThis, GetMethodThis);
  336. if (notifyChanged != null)
  337. {
  338. foreach (var member in structure)
  339. {
  340. il.Emit(OpCodes.Ldarg_0);
  341. il.Emit(OpCodes.Ldstr, member.Name);
  342. il.Emit(OpCodes.Call, notifyChanged);
  343. }
  344. }
  345. il.Emit(OpCodes.Ret);
  346. }
  347. #endregion
  348. #endregion
  349. #region IConfigStore
  350. typeBuilder.AddInterfaceImplementation(typeof(IConfigStore));
  351. var IConfigStore_t = typeof(IConfigStore);
  352. var IConfigStore_GetSyncObject = IConfigStore_t.GetProperty(nameof(IConfigStore.SyncObject)).GetGetMethod();
  353. var IConfigStore_GetWriteSyncObject = IConfigStore_t.GetProperty(nameof(IConfigStore.WriteSyncObject)).GetGetMethod();
  354. var IConfigStore_WriteTo = IConfigStore_t.GetMethod(nameof(IConfigStore.WriteTo));
  355. var IConfigStore_ReadFrom = IConfigStore_t.GetMethod(nameof(IConfigStore.ReadFrom));
  356. #region IConfigStore.SyncObject
  357. var syncObjProp = typeBuilder.DefineProperty(nameof(IConfigStore.SyncObject), PropertyAttributes.None, typeof(WaitHandle), null);
  358. var syncObjPropGet = typeBuilder.DefineMethod($"<g>{nameof(IConfigStore.SyncObject)}", virtualPropertyMethodAttr, syncObjProp.PropertyType, Type.EmptyTypes);
  359. syncObjProp.SetGetMethod(syncObjPropGet);
  360. typeBuilder.DefineMethodOverride(syncObjPropGet, IConfigStore_GetSyncObject);
  361. {
  362. var il = syncObjPropGet.GetILGenerator();
  363. il.Emit(OpCodes.Ldarg_0);
  364. il.Emit(OpCodes.Tailcall);
  365. il.Emit(OpCodes.Call, Impl.ImplGetSyncObjectMethod);
  366. il.Emit(OpCodes.Ret);
  367. }
  368. #endregion
  369. #region IConfigStore.WriteSyncObject
  370. var writeSyncObjProp = typeBuilder.DefineProperty(nameof(IConfigStore.WriteSyncObject), PropertyAttributes.None, typeof(WaitHandle), null);
  371. var writeSyncObjPropGet = typeBuilder.DefineMethod($"<g>{nameof(IConfigStore.WriteSyncObject)}", virtualPropertyMethodAttr, writeSyncObjProp.PropertyType, Type.EmptyTypes);
  372. writeSyncObjProp.SetGetMethod(writeSyncObjPropGet);
  373. typeBuilder.DefineMethodOverride(writeSyncObjPropGet, IConfigStore_GetWriteSyncObject);
  374. {
  375. var il = writeSyncObjPropGet.GetILGenerator();
  376. il.Emit(OpCodes.Ldarg_0);
  377. il.Emit(OpCodes.Tailcall);
  378. il.Emit(OpCodes.Call, Impl.ImplGetWriteSyncObjectMethod);
  379. il.Emit(OpCodes.Ret);
  380. }
  381. #endregion
  382. #region IConfigStore.WriteTo
  383. var writeTo = typeBuilder.DefineMethod($"<>{nameof(IConfigStore.WriteTo)}", virtualMemberMethod, null, new[] { typeof(ConfigProvider) });
  384. typeBuilder.DefineMethodOverride(writeTo, IConfigStore_WriteTo);
  385. {
  386. var il = writeTo.GetILGenerator();
  387. il.Emit(OpCodes.Ldarg_0);
  388. il.Emit(OpCodes.Ldarg_1);
  389. il.Emit(OpCodes.Tailcall);
  390. il.Emit(OpCodes.Call, Impl.ImplWriteToMethod);
  391. il.Emit(OpCodes.Ret);
  392. }
  393. #endregion
  394. #region IConfigStore.ReadFrom
  395. var readFrom = typeBuilder.DefineMethod($"<>{nameof(IConfigStore.ReadFrom)}", virtualMemberMethod, null, new[] { typeof(ConfigProvider) });
  396. typeBuilder.DefineMethodOverride(readFrom, IConfigStore_ReadFrom);
  397. {
  398. var il = readFrom.GetILGenerator();
  399. il.Emit(OpCodes.Ldarg_0);
  400. il.Emit(OpCodes.Ldarg_1);
  401. il.Emit(OpCodes.Tailcall);
  402. il.Emit(OpCodes.Call, Impl.ImplReadFromMethod);
  403. il.Emit(OpCodes.Ret);
  404. }
  405. #endregion
  406. #endregion
  407. #region Changed
  408. var coreChanged = typeBuilder.DefineMethod(
  409. "<>Changed",
  410. virtualMemberMethod,
  411. null, Type.EmptyTypes);
  412. typeBuilder.DefineMethodOverride(coreChanged, IGeneratedStore_Changed);
  413. if (baseChanged != null)
  414. typeBuilder.DefineMethodOverride(coreChanged, baseChanged);
  415. {
  416. var il = coreChanged.GetILGenerator();
  417. if (baseChanged != null)
  418. {
  419. il.Emit(OpCodes.Ldarg_0);
  420. il.Emit(OpCodes.Call, baseChanged); // call base
  421. }
  422. il.Emit(OpCodes.Ldarg_0);
  423. il.Emit(OpCodes.Tailcall);
  424. il.Emit(OpCodes.Call, Impl.ImplSignalChangedMethod);
  425. il.Emit(OpCodes.Ret); // simply call our impl's SignalChanged method and return
  426. }
  427. #endregion
  428. #region ChangeTransaction
  429. var coreChangeTransaction = typeBuilder.DefineMethod(
  430. "<>ChangeTransaction",
  431. virtualMemberMethod,
  432. typeof(IDisposable), Type.EmptyTypes);
  433. typeBuilder.DefineMethodOverride(coreChangeTransaction, IGeneratedStore_ChangeTransaction);
  434. if (baseChangeTransaction != null)
  435. typeBuilder.DefineMethodOverride(coreChangeTransaction, baseChangeTransaction);
  436. {
  437. var il = coreChangeTransaction.GetILGenerator();
  438. il.Emit(OpCodes.Ldarg_0);
  439. if (baseChangeTransaction != null)
  440. {
  441. il.Emit(OpCodes.Ldarg_0);
  442. il.Emit(OpCodes.Call, baseChangeTransaction);
  443. }
  444. else
  445. il.Emit(OpCodes.Ldnull);
  446. il.Emit(OpCodes.Tailcall);
  447. il.Emit(OpCodes.Call, Impl.ImplChangeTransactionMethod);
  448. il.Emit(OpCodes.Ret);
  449. }
  450. #endregion
  451. #region IGeneratedStore<T>
  452. var IGeneratedStore_T_t = typeof(IGeneratedStore<>).MakeGenericType(type);
  453. typeBuilder.AddInterfaceImplementation(IGeneratedStore_T_t);
  454. var IGeneratedStore_T_CopyFrom = IGeneratedStore_T_t.GetMethod(nameof(IGeneratedStore<Config>.CopyFrom));
  455. #region IGeneratedStore<T>.CopyFrom
  456. var copyFrom = typeBuilder.DefineMethod($"<>{nameof(IGeneratedStore<Config>.CopyFrom)}", virtualMemberMethod, null, new[] { type, typeof(bool) });
  457. typeBuilder.DefineMethodOverride(copyFrom, IGeneratedStore_T_CopyFrom);
  458. {
  459. var il = copyFrom.GetILGenerator();
  460. var transactionLocal = il.DeclareLocal(IDisposable_t);
  461. var startLock = il.DefineLabel();
  462. il.Emit(OpCodes.Ldarg_2);
  463. il.Emit(OpCodes.Brfalse, startLock);
  464. il.Emit(OpCodes.Ldarg_0);
  465. il.Emit(OpCodes.Call, coreChangeTransaction); // take the write lock
  466. il.Emit(OpCodes.Stloc, transactionLocal);
  467. il.MarkLabel(startLock);
  468. var GetLocal = MakeGetLocal(il);
  469. foreach (var member in structure)
  470. {
  471. il.BeginExceptionBlock();
  472. EmitLoadCorrectStore(il, member, false, false, GetLocal, il => il.Emit(OpCodes.Ldarg_1), GetMethodThis, GetMethodThis);
  473. il.BeginCatchBlock(typeof(Exception));
  474. EmitWarnException(il, $"Error while copying from member {member.Name}");
  475. il.EndExceptionBlock();
  476. }
  477. if (notifyChanged != null)
  478. {
  479. foreach (var member in structure)
  480. {
  481. il.Emit(OpCodes.Ldarg_0);
  482. il.Emit(OpCodes.Ldstr, member.Name);
  483. il.Emit(OpCodes.Call, notifyChanged);
  484. }
  485. }
  486. var endLock = il.DefineLabel();
  487. il.Emit(OpCodes.Ldarg_2);
  488. il.Emit(OpCodes.Brfalse, endLock);
  489. il.Emit(OpCodes.Ldloc, transactionLocal);
  490. il.Emit(OpCodes.Callvirt, IDisposable_Dispose);
  491. il.MarkLabel(endLock);
  492. il.Emit(OpCodes.Ret);
  493. }
  494. #endregion
  495. #endregion
  496. #region base.CopyFrom
  497. if (baseCopyFrom != null)
  498. {
  499. var pubCopyFrom = typeBuilder.DefineMethod(
  500. baseCopyFrom.Name,
  501. virtualMemberMethod,
  502. null, new[] { type });
  503. typeBuilder.DefineMethodOverride(pubCopyFrom, baseCopyFrom);
  504. {
  505. var il = pubCopyFrom.GetILGenerator();
  506. il.Emit(OpCodes.Ldarg_0);
  507. il.Emit(OpCodes.Call, coreChangeTransaction);
  508. il.Emit(OpCodes.Ldarg_0);
  509. il.Emit(OpCodes.Ldarg_1);
  510. il.Emit(OpCodes.Ldc_I4_0);
  511. il.Emit(OpCodes.Call, copyFrom); // call internal
  512. il.Emit(OpCodes.Ldarg_0);
  513. il.Emit(OpCodes.Ldarg_1);
  514. il.Emit(OpCodes.Call, baseCopyFrom); // call base
  515. il.Emit(OpCodes.Tailcall);
  516. il.Emit(OpCodes.Callvirt, IDisposable_Dispose); // dispose transaction (which calls changed)
  517. il.Emit(OpCodes.Ret);
  518. }
  519. }
  520. #endregion
  521. #region Members
  522. foreach (var member in structure.Where(m => m.IsVirtual))
  523. { // IsVirtual implies !IsField
  524. var prop = member.Member as PropertyInfo;
  525. var get = prop.GetGetMethod(true);
  526. var set = prop.GetSetMethod(true);
  527. var propBuilder = typeBuilder.DefineProperty($"{member.Name}#", PropertyAttributes.None, member.Type, null);
  528. var propGet = typeBuilder.DefineMethod($"<g>{propBuilder.Name}", virtualPropertyMethodAttr, member.Type, Type.EmptyTypes);
  529. propBuilder.SetGetMethod(propGet);
  530. typeBuilder.DefineMethodOverride(propGet, get);
  531. {
  532. var il = propGet.GetILGenerator();
  533. var local = il.DeclareLocal(member.Type);
  534. il.Emit(OpCodes.Ldarg_0);
  535. il.Emit(OpCodes.Call, Impl.ImplTakeReadMethod); // take the read lock
  536. il.BeginExceptionBlock();
  537. il.Emit(OpCodes.Ldarg_0);
  538. il.Emit(OpCodes.Call, get); // call base getter
  539. il.Emit(OpCodes.Stloc, local);
  540. il.BeginFinallyBlock();
  541. il.Emit(OpCodes.Ldarg_0);
  542. il.Emit(OpCodes.Call, Impl.ImplReleaseReadMethod); // release the read lock
  543. il.EndExceptionBlock();
  544. il.Emit(OpCodes.Ldloc, local);
  545. il.Emit(OpCodes.Ret);
  546. }
  547. var propSet = typeBuilder.DefineMethod($"<s>{propBuilder.Name}", virtualPropertyMethodAttr, null, new[] { member.Type });
  548. propBuilder.SetSetMethod(propSet);
  549. typeBuilder.DefineMethodOverride(propSet, set);
  550. {
  551. var il = propSet.GetILGenerator();
  552. var transactionLocal = il.DeclareLocal(IDisposable_t);
  553. var GetLocal = MakeGetLocal(il);
  554. il.Emit(OpCodes.Ldarg_0);
  555. il.Emit(OpCodes.Call, coreChangeTransaction); // take the write lock
  556. il.Emit(OpCodes.Stloc, transactionLocal);
  557. il.BeginExceptionBlock();
  558. il.Emit(OpCodes.Ldarg_0);
  559. il.Emit(OpCodes.Ldarg_1);
  560. EmitCorrectMember(il, member, false, false, GetLocal, GetMethodThis, GetMethodThis);
  561. il.Emit(OpCodes.Call, set);
  562. il.BeginFinallyBlock();
  563. il.Emit(OpCodes.Ldloc, transactionLocal);
  564. il.Emit(OpCodes.Callvirt, IDisposable_Dispose);
  565. il.EndExceptionBlock();
  566. if (notifyChanged != null)
  567. {
  568. il.Emit(OpCodes.Ldarg_0);
  569. il.Emit(OpCodes.Ldstr, member.Name);
  570. il.Emit(OpCodes.Call, notifyChanged);
  571. }
  572. il.Emit(OpCodes.Ret);
  573. }
  574. }
  575. #endregion
  576. var genType = typeBuilder.CreateType();
  577. var parentParam = Expression.Parameter(typeof(IGeneratedStore), "parent");
  578. var creatorDel = Expression.Lambda<GeneratedStoreCreator>(
  579. Expression.New(ctor, parentParam), parentParam
  580. ).Compile();
  581. return (creatorDel, genType);
  582. }
  583. }
  584. }