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.

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