Emit.cs 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864
  1. // JsonKit v0.5 - A simple but flexible Json library in a single .cs file.
  2. //
  3. // Copyright (C) 2014 Topten Software (contact@toptensoftware.com) All rights reserved.
  4. //
  5. // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this product
  6. // except in compliance with the License. You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software distributed under the
  11. // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
  12. // either express or implied. See the License for the specific language governing permissions
  13. // and limitations under the License.
  14. #if !JSONKIT_NO_EMIT
  15. using System;
  16. using System.Collections.Generic;
  17. using System.Linq;
  18. using System.IO;
  19. using System.Reflection;
  20. using System.Globalization;
  21. using System.Reflection.Emit;
  22. namespace Topten.JsonKit
  23. {
  24. static class Emit
  25. {
  26. // Generates a function that when passed an object of specified type, renders it to an IJsonWriter
  27. public static Action<IJsonWriter, object> MakeFormatter(Type type)
  28. {
  29. var formatJson = ReflectionInfo.FindFormatJson(type);
  30. if (formatJson != null)
  31. {
  32. var method = new DynamicMethod("invoke_formatJson", null, new Type[] { typeof(IJsonWriter), typeof(Object) }, true);
  33. var il = method.GetILGenerator();
  34. if (formatJson.ReturnType == typeof(string))
  35. {
  36. // w.WriteStringLiteral(o.FormatJson())
  37. il.Emit(OpCodes.Ldarg_0);
  38. il.Emit(OpCodes.Ldarg_1);
  39. il.Emit(OpCodes.Unbox, type);
  40. il.Emit(OpCodes.Call, formatJson);
  41. il.Emit(OpCodes.Callvirt, typeof(IJsonWriter).GetMethod("WriteStringLiteral"));
  42. }
  43. else
  44. {
  45. // o.FormatJson(w);
  46. il.Emit(OpCodes.Ldarg_1);
  47. il.Emit(type.IsValueType ? OpCodes.Unbox : OpCodes.Castclass, type);
  48. il.Emit(OpCodes.Ldarg_0);
  49. il.Emit(type.IsValueType ? OpCodes.Call : OpCodes.Callvirt, formatJson);
  50. }
  51. il.Emit(OpCodes.Ret);
  52. return (Action<IJsonWriter, object>)method.CreateDelegate(typeof(Action<IJsonWriter, object>));
  53. }
  54. else
  55. {
  56. // Get the reflection info for this type
  57. var ri = ReflectionInfo.GetReflectionInfo(type);
  58. if (ri == null)
  59. return null;
  60. // Create a dynamic method that can do the work
  61. var method = new DynamicMethod("dynamic_formatter", null, new Type[] { typeof(IJsonWriter), typeof(object) }, true);
  62. var il = method.GetILGenerator();
  63. // Cast/unbox the target object and store in local variable
  64. var locTypedObj = il.DeclareLocal(type);
  65. il.Emit(OpCodes.Ldarg_1);
  66. il.Emit(type.IsValueType ? OpCodes.Unbox_Any : OpCodes.Castclass, type);
  67. il.Emit(OpCodes.Stloc, locTypedObj);
  68. // Get Invariant CultureInfo (since we'll probably be needing this)
  69. var locInvariant = il.DeclareLocal(typeof(IFormatProvider));
  70. il.Emit(OpCodes.Call, typeof(CultureInfo).GetProperty("InvariantCulture").GetGetMethod());
  71. il.Emit(OpCodes.Stloc, locInvariant);
  72. // These are the types we'll call .ToString(Culture.InvariantCulture) on
  73. var toStringTypes = new Type[] {
  74. typeof(int), typeof(uint), typeof(long), typeof(ulong),
  75. typeof(short), typeof(ushort), typeof(decimal),
  76. typeof(byte), typeof(sbyte)
  77. };
  78. // Theses types we also generate for
  79. var otherSupportedTypes = new Type[] {
  80. typeof(double), typeof(float), typeof(string), typeof(char)
  81. };
  82. // Call IJsonWriting if implemented
  83. if (typeof(IJsonWriting).IsAssignableFrom(type))
  84. {
  85. if (type.IsValueType)
  86. {
  87. il.Emit(OpCodes.Ldloca, locTypedObj);
  88. il.Emit(OpCodes.Ldarg_0);
  89. il.Emit(OpCodes.Call, type.GetInterfaceMap(typeof(IJsonWriting)).TargetMethods[0]);
  90. }
  91. else
  92. {
  93. il.Emit(OpCodes.Ldloc, locTypedObj);
  94. il.Emit(OpCodes.Castclass, typeof(IJsonWriting));
  95. il.Emit(OpCodes.Ldarg_0);
  96. il.Emit(OpCodes.Callvirt, typeof(IJsonWriting).GetMethod("OnJsonWriting", new Type[] { typeof(IJsonWriter) }));
  97. }
  98. }
  99. // Process all members
  100. foreach (var m in ri.Members)
  101. {
  102. // Dont save deprecated properties
  103. if (m.Deprecated)
  104. {
  105. continue;
  106. }
  107. // Ignore write only properties
  108. var pi = m.Member as PropertyInfo;
  109. if (pi != null && pi.GetGetMethod(true) == null)
  110. {
  111. continue;
  112. }
  113. // Get the member type
  114. var memberType = m.MemberType;
  115. // Get the field/property value and store it in a local
  116. LocalBuilder locValue = il.DeclareLocal(memberType);
  117. il.Emit(type.IsValueType ? OpCodes.Ldloca : OpCodes.Ldloc, locTypedObj);
  118. if (pi != null)
  119. {
  120. il.Emit(type.IsValueType ? OpCodes.Call : OpCodes.Callvirt, pi.GetGetMethod(true));
  121. }
  122. if (m.Member is FieldInfo fi)
  123. {
  124. il.Emit(OpCodes.Ldfld, fi);
  125. }
  126. il.Emit(OpCodes.Stloc, locValue);
  127. // A label for early exit if not writing this member
  128. Label lblFinishedMember = il.DefineLabel();
  129. // Helper to generate IL to write the key
  130. void EmitWriteKey()
  131. {
  132. // Write the Json key
  133. il.Emit(OpCodes.Ldarg_0);
  134. il.Emit(OpCodes.Ldstr, m.JsonKey);
  135. il.Emit(OpCodes.Callvirt, typeof(IJsonWriter).GetMethod("WriteKeyNoEscaping", new Type[] { typeof(string) }));
  136. }
  137. // Is it a nullable type?
  138. var typeUnderlying = Nullable.GetUnderlyingType(memberType);
  139. if (typeUnderlying != null)
  140. {
  141. // Define some labels
  142. var lblHasValue = il.DefineLabel();
  143. // Call HasValue
  144. il.Emit(OpCodes.Ldloca, locValue);
  145. il.Emit(OpCodes.Call, memberType.GetProperty("HasValue").GetGetMethod());
  146. il.Emit(OpCodes.Brtrue, lblHasValue);
  147. // HasValue returned false, so either omit the key entirely, or write it as "null"
  148. if (!m.ExcludeIfNull)
  149. {
  150. // Write the key
  151. EmitWriteKey();
  152. // No value, write "null"
  153. il.Emit(OpCodes.Ldarg_0);
  154. il.Emit(OpCodes.Ldstr, "null");
  155. il.Emit(OpCodes.Callvirt, typeof(IJsonWriter).GetMethod("WriteRaw", new Type[] { typeof(string) }));
  156. }
  157. il.Emit(OpCodes.Br_S, lblFinishedMember);
  158. // Get it's value
  159. il.MarkLabel(lblHasValue);
  160. il.Emit(OpCodes.Ldloca, locValue);
  161. il.Emit(OpCodes.Call, memberType.GetProperty("Value").GetGetMethod());
  162. // Switch to the underlying type from here on
  163. locValue = il.DeclareLocal(typeUnderlying);
  164. il.Emit(OpCodes.Stloc, locValue);
  165. memberType = typeUnderlying;
  166. }
  167. else
  168. {
  169. if (m.ExcludeIfNull && !type.IsValueType)
  170. {
  171. il.Emit(OpCodes.Ldloc, locValue);
  172. il.Emit(OpCodes.Brfalse_S, lblFinishedMember);
  173. }
  174. }
  175. if (m.ExcludeIfEquals != null)
  176. {
  177. il.Emit(OpCodes.Ldloc, locValue);
  178. var targetValue = Convert.ChangeType(m.ExcludeIfEquals, m.MemberType);
  179. LoadContantFromObject(il, targetValue);
  180. il.Emit(OpCodes.Ceq);
  181. il.Emit(OpCodes.Brtrue_S, lblFinishedMember);
  182. }
  183. // ToString()
  184. if (toStringTypes.Contains(memberType))
  185. {
  186. EmitWriteKey();
  187. il.Emit(OpCodes.Ldarg_0);
  188. il.Emit(memberType.IsValueType ? OpCodes.Ldloca : OpCodes.Ldloc, locValue);
  189. il.Emit(OpCodes.Ldloc, locInvariant);
  190. il.Emit(OpCodes.Call, memberType.GetMethod("ToString", new Type[] { typeof(IFormatProvider) }));
  191. il.Emit(OpCodes.Callvirt, typeof(IJsonWriter).GetMethod("WriteRaw", new Type[] { typeof(string) }));
  192. }
  193. // ToString("R")
  194. else if (memberType == typeof(float) || memberType == typeof(double))
  195. {
  196. EmitWriteKey();
  197. il.Emit(OpCodes.Ldarg_0);
  198. il.Emit(memberType.IsValueType ? OpCodes.Ldloca : OpCodes.Ldloc, locValue);
  199. il.Emit(OpCodes.Ldstr, "R");
  200. il.Emit(OpCodes.Ldloc, locInvariant);
  201. il.Emit(OpCodes.Call, memberType.GetMethod("ToString", new Type[] { typeof(string), typeof(IFormatProvider) }));
  202. il.Emit(OpCodes.Callvirt, typeof(IJsonWriter).GetMethod("WriteRaw", new Type[] { typeof(string) }));
  203. }
  204. // String?
  205. else if (memberType == typeof(string))
  206. {
  207. EmitWriteKey();
  208. il.Emit(OpCodes.Ldarg_0);
  209. il.Emit(OpCodes.Ldloc, locValue);
  210. il.Emit(OpCodes.Callvirt, typeof(IJsonWriter).GetMethod("WriteStringLiteral", new Type[] { typeof(string) }));
  211. }
  212. // Char?
  213. else if (memberType == typeof(char))
  214. {
  215. EmitWriteKey();
  216. il.Emit(OpCodes.Ldarg_0);
  217. il.Emit(OpCodes.Ldloca, locValue);
  218. il.Emit(OpCodes.Call, memberType.GetMethod("ToString", new Type[] { }));
  219. il.Emit(OpCodes.Callvirt, typeof(IJsonWriter).GetMethod("WriteStringLiteral", new Type[] { typeof(string) }));
  220. }
  221. // Bool?
  222. else if (memberType == typeof(bool))
  223. {
  224. EmitWriteKey();
  225. il.Emit(OpCodes.Ldarg_0);
  226. var lblTrue = il.DefineLabel();
  227. var lblCont = il.DefineLabel();
  228. il.Emit(OpCodes.Ldloc, locValue);
  229. il.Emit(OpCodes.Brtrue_S, lblTrue);
  230. il.Emit(OpCodes.Ldstr, "false");
  231. il.Emit(OpCodes.Br_S, lblCont);
  232. il.MarkLabel(lblTrue);
  233. il.Emit(OpCodes.Ldstr, "true");
  234. il.MarkLabel(lblCont);
  235. il.Emit(OpCodes.Callvirt, typeof(IJsonWriter).GetMethod("WriteRaw", new Type[] { typeof(string) }));
  236. }
  237. // NB: We don't support DateTime as it's format can be changed
  238. else
  239. {
  240. // Load writer
  241. il.Emit(OpCodes.Ldarg_0);
  242. // Load value
  243. il.Emit(OpCodes.Ldloc, locValue);
  244. if (memberType.IsValueType)
  245. il.Emit(OpCodes.Box, memberType);
  246. // Write the key and value
  247. if (m.ExcludeIfEmpty)
  248. {
  249. il.Emit(OpCodes.Ldstr, m.JsonKey);
  250. il.Emit(OpCodes.Call, typeof(Emit).GetMethod("WriteKeyAndValueCheckIfEmpty"));
  251. }
  252. else
  253. {
  254. EmitWriteKey();
  255. il.Emit(OpCodes.Callvirt, typeof(IJsonWriter).GetMethod("WriteValue", new Type[] { typeof(object) }));
  256. }
  257. }
  258. il.MarkLabel(lblFinishedMember);
  259. }
  260. // Call IJsonWritten
  261. if (typeof(IJsonWritten).IsAssignableFrom(type))
  262. {
  263. if (type.IsValueType)
  264. {
  265. il.Emit(OpCodes.Ldloca, locTypedObj);
  266. il.Emit(OpCodes.Ldarg_0);
  267. il.Emit(OpCodes.Call, type.GetInterfaceMap(typeof(IJsonWritten)).TargetMethods[0]);
  268. }
  269. else
  270. {
  271. il.Emit(OpCodes.Ldloc, locTypedObj);
  272. il.Emit(OpCodes.Castclass, typeof(IJsonWriting));
  273. il.Emit(OpCodes.Ldarg_0);
  274. il.Emit(OpCodes.Callvirt, typeof(IJsonWriting).GetMethod("OnJsonWritten", new Type[] { typeof(IJsonWriter) }));
  275. }
  276. }
  277. // Done!
  278. il.Emit(OpCodes.Ret);
  279. var impl = (Action<IJsonWriter, object>)method.CreateDelegate(typeof(Action<IJsonWriter, object>));
  280. // Wrap it in a call to WriteDictionary
  281. return (w, obj) =>
  282. {
  283. w.WriteDictionary(() =>
  284. {
  285. impl(w, obj);
  286. });
  287. };
  288. }
  289. }
  290. static void LoadContantFromObject(ILGenerator il, object value)
  291. {
  292. switch (Type.GetTypeCode(value.GetType()))
  293. {
  294. case TypeCode.Boolean:
  295. il.Emit(OpCodes.Ldc_I4, ((bool)value) ? 1 : 0);
  296. break;
  297. case TypeCode.Char:
  298. case TypeCode.SByte:
  299. case TypeCode.Byte:
  300. case TypeCode.Int16:
  301. case TypeCode.UInt16:
  302. case TypeCode.Int32:
  303. case TypeCode.UInt32:
  304. il.Emit(OpCodes.Ldc_I4, (int)value);
  305. break;
  306. case TypeCode.Int64:
  307. case TypeCode.UInt64:
  308. il.Emit(OpCodes.Ldc_I8, (long)value);
  309. break;
  310. case TypeCode.Single:
  311. il.Emit(OpCodes.Ldc_R4, (float)value);
  312. break;
  313. case TypeCode.Double:
  314. il.Emit(OpCodes.Ldc_R8, (double)value);
  315. break;
  316. default:
  317. throw new InvalidOperationException($"JsonKit doesn't support the type `{value.GetType().ToString()}` for ExcludeIfEquals");
  318. }
  319. }
  320. public static void WriteKeyAndValueCheckIfEmpty(IJsonWriter w, object o, string key)
  321. {
  322. if (o == null)
  323. return;
  324. // Check if empty
  325. if (o is System.Collections.IEnumerable e)
  326. {
  327. if (!e.GetEnumerator().MoveNext())
  328. return;
  329. }
  330. w.WriteKeyNoEscaping(key);
  331. w.WriteValue(o);
  332. }
  333. // Pseudo box lets us pass a value type by reference. Used during
  334. // deserialization of value types.
  335. interface IPseudoBox
  336. {
  337. object GetValue();
  338. }
  339. [Obfuscation(Exclude = true, ApplyToMembers = true)]
  340. class PseudoBox<T> : IPseudoBox where T : struct
  341. {
  342. public T value = default(T);
  343. object IPseudoBox.GetValue() { return value; }
  344. }
  345. // Make a parser for value types
  346. public static Func<IJsonReader, Type, object> MakeParser(Type type)
  347. {
  348. System.Diagnostics.Debug.Assert(type.IsValueType);
  349. // ParseJson method?
  350. var parseJson = ReflectionInfo.FindParseJson(type);
  351. if (parseJson != null)
  352. {
  353. if (parseJson.GetParameters()[0].ParameterType == typeof(IJsonReader))
  354. {
  355. var method = new DynamicMethod("invoke_ParseJson", typeof(Object), new Type[] { typeof(IJsonReader), typeof(Type) }, true);
  356. var il = method.GetILGenerator();
  357. il.Emit(OpCodes.Ldarg_0);
  358. il.Emit(OpCodes.Call, parseJson);
  359. il.Emit(OpCodes.Box, type);
  360. il.Emit(OpCodes.Ret);
  361. return (Func<IJsonReader,Type,object>)method.CreateDelegate(typeof(Func<IJsonReader,Type,object>));
  362. }
  363. else
  364. {
  365. var method = new DynamicMethod("invoke_ParseJson", typeof(Object), new Type[] { typeof(string) }, true);
  366. var il = method.GetILGenerator();
  367. il.Emit(OpCodes.Ldarg_0);
  368. il.Emit(OpCodes.Call, parseJson);
  369. il.Emit(OpCodes.Box, type);
  370. il.Emit(OpCodes.Ret);
  371. var invoke = (Func<string, object>)method.CreateDelegate(typeof(Func<string, object>));
  372. return (r, t) =>
  373. {
  374. if (r.GetLiteralKind() == LiteralKind.String)
  375. {
  376. var o = invoke(r.GetLiteralString());
  377. r.NextToken();
  378. return o;
  379. }
  380. throw new InvalidDataException(string.Format("Expected string literal for type {0}", type.FullName));
  381. };
  382. }
  383. }
  384. else
  385. {
  386. // Get the reflection info for this type
  387. var ri = ReflectionInfo.GetReflectionInfo(type);
  388. if (ri == null)
  389. return null;
  390. // We'll create setters for each property/field
  391. var setters = new Dictionary<string, Action<IJsonReader, object>>();
  392. // Store the value in a pseudo box until it's fully initialized
  393. var boxType = typeof(PseudoBox<>).MakeGenericType(type);
  394. // Process all members
  395. foreach (var m in ri.Members)
  396. {
  397. // Ignore write only properties
  398. var pi = m.Member as PropertyInfo;
  399. var fi = m.Member as FieldInfo;
  400. if (pi != null && pi.GetSetMethod(true) == null)
  401. {
  402. continue;
  403. }
  404. // Create a dynamic method that can do the work
  405. var method = new DynamicMethod("dynamic_parser", null, new Type[] { typeof(IJsonReader), typeof(object) }, true);
  406. var il = method.GetILGenerator();
  407. // Load the target
  408. il.Emit(OpCodes.Ldarg_1);
  409. il.Emit(OpCodes.Castclass, boxType);
  410. il.Emit(OpCodes.Ldflda, boxType.GetField("value"));
  411. // Get the value
  412. GenerateGetJsonValue(m, il);
  413. // Assign it
  414. if (pi != null)
  415. il.Emit(OpCodes.Call, pi.GetSetMethod(true));
  416. if (fi != null)
  417. il.Emit(OpCodes.Stfld, fi);
  418. // Done
  419. il.Emit(OpCodes.Ret);
  420. // Store in the map of setters
  421. setters.Add(m.JsonKey, (Action<IJsonReader, object>)method.CreateDelegate(typeof(Action<IJsonReader, object>)));
  422. }
  423. // Create helpers to invoke the interfaces (this is painful but avoids having to really box
  424. // the value in order to call the interface).
  425. Action<object, IJsonReader> invokeLoading = MakeInterfaceCall(type, typeof(IJsonLoading));
  426. Action<object, IJsonReader> invokeLoaded = MakeInterfaceCall(type, typeof(IJsonLoaded));
  427. Func<object, IJsonReader, string, bool> invokeField = MakeLoadFieldCall(type);
  428. // Create the parser
  429. Func<IJsonReader, Type, object> parser = (reader, Type) =>
  430. {
  431. // Create pseudobox (ie: new PseudoBox<Type>)
  432. var box = DecoratingActivator.CreateInstance(boxType);
  433. // Call IJsonLoading
  434. if (invokeLoading != null)
  435. invokeLoading(box, reader);
  436. // Read the dictionary
  437. reader.ParseDictionary(key =>
  438. {
  439. // Call IJsonLoadField
  440. if (invokeField != null && invokeField(box, reader, key))
  441. return;
  442. // Get a setter and invoke it if found
  443. Action<IJsonReader, object> setter;
  444. if (setters.TryGetValue(key, out setter))
  445. {
  446. setter(reader, box);
  447. }
  448. });
  449. // IJsonLoaded
  450. if (invokeLoaded != null)
  451. invokeLoaded(box, reader);
  452. // Return the value
  453. return ((IPseudoBox)box).GetValue();
  454. };
  455. // Done
  456. return parser;
  457. }
  458. }
  459. // Helper to make the call to a PsuedoBox value's IJsonLoading or IJsonLoaded
  460. static Action<object, IJsonReader> MakeInterfaceCall(Type type, Type tItf)
  461. {
  462. // Interface supported?
  463. if (!tItf.IsAssignableFrom(type))
  464. return null;
  465. // Resolve the box type
  466. var boxType = typeof(PseudoBox<>).MakeGenericType(type);
  467. // Create method
  468. var method = new DynamicMethod("dynamic_invoke_" + tItf.Name, null, new Type[] { typeof(object), typeof(IJsonReader) }, true);
  469. var il = method.GetILGenerator();
  470. // Call interface method
  471. il.Emit(OpCodes.Ldarg_0);
  472. il.Emit(OpCodes.Castclass, boxType);
  473. il.Emit(OpCodes.Ldflda, boxType.GetField("value"));
  474. il.Emit(OpCodes.Ldarg_1);
  475. il.Emit(OpCodes.Call, type.GetInterfaceMap(tItf).TargetMethods[0]);
  476. il.Emit(OpCodes.Ret);
  477. // Done
  478. return (Action<object, IJsonReader>)method.CreateDelegate(typeof(Action<object, IJsonReader>));
  479. }
  480. // Similar to above but for IJsonLoadField
  481. static Func<object, IJsonReader, string, bool> MakeLoadFieldCall(Type type)
  482. {
  483. // Interface supported?
  484. var tItf = typeof(IJsonLoadField);
  485. if (!tItf.IsAssignableFrom(type))
  486. return null;
  487. // Resolve the box type
  488. var boxType = typeof(PseudoBox<>).MakeGenericType(type);
  489. // Create method
  490. var method = new DynamicMethod("dynamic_invoke_" + tItf.Name, typeof(bool), new Type[] { typeof(object), typeof(IJsonReader), typeof(string) }, true);
  491. var il = method.GetILGenerator();
  492. // Call interface method
  493. il.Emit(OpCodes.Ldarg_0);
  494. il.Emit(OpCodes.Castclass, boxType);
  495. il.Emit(OpCodes.Ldflda, boxType.GetField("value"));
  496. il.Emit(OpCodes.Ldarg_1);
  497. il.Emit(OpCodes.Ldarg_2);
  498. il.Emit(OpCodes.Call, type.GetInterfaceMap(tItf).TargetMethods[0]);
  499. il.Emit(OpCodes.Ret);
  500. // Done
  501. return (Func<object, IJsonReader, string, bool>)method.CreateDelegate(typeof(Func<object, IJsonReader, string, bool>));
  502. }
  503. // Create an "into parser" that can parse from IJsonReader into a reference type (ie: a class)
  504. public static Action<IJsonReader, object> MakeIntoParser(Type type)
  505. {
  506. System.Diagnostics.Debug.Assert(!type.IsValueType);
  507. // Get the reflection info for this type
  508. var ri = ReflectionInfo.GetReflectionInfo(type);
  509. if (ri == null)
  510. return null;
  511. // We'll create setters for each property/field
  512. var setters = new Dictionary<string, Action<IJsonReader, object>>();
  513. // Process all members
  514. foreach (var m in ri.Members)
  515. {
  516. // Ignore write only properties
  517. var pi = m.Member as PropertyInfo;
  518. var fi = m.Member as FieldInfo;
  519. if (pi != null && pi.GetSetMethod(true) == null)
  520. {
  521. continue;
  522. }
  523. // Ignore read only properties that has KeepInstance attribute
  524. if (pi != null && pi.GetGetMethod(true) == null && m.KeepInstance)
  525. {
  526. continue;
  527. }
  528. // Create a dynamic method that can do the work
  529. var method = new DynamicMethod("dynamic_parser", null, new Type[] { typeof(IJsonReader), typeof(object) }, true);
  530. var il = method.GetILGenerator();
  531. // Load the target
  532. il.Emit(OpCodes.Ldarg_1);
  533. il.Emit(OpCodes.Castclass, type);
  534. // Try to keep existing instance?
  535. if (m.KeepInstance)
  536. {
  537. // Get existing existing instance
  538. il.Emit(OpCodes.Dup);
  539. if (pi != null)
  540. il.Emit(OpCodes.Callvirt, pi.GetGetMethod(true));
  541. else
  542. il.Emit(OpCodes.Ldfld, fi);
  543. var existingInstance = il.DeclareLocal(m.MemberType);
  544. var lblExistingInstanceNull = il.DefineLabel();
  545. // Keep a copy of the existing instance in a locale
  546. il.Emit(OpCodes.Dup);
  547. il.Emit(OpCodes.Stloc, existingInstance);
  548. // Compare to null
  549. il.Emit(OpCodes.Ldnull);
  550. il.Emit(OpCodes.Ceq);
  551. il.Emit(OpCodes.Brtrue_S, lblExistingInstanceNull);
  552. il.Emit(OpCodes.Ldarg_0); // reader
  553. il.Emit(OpCodes.Ldloc, existingInstance); // into
  554. il.Emit(OpCodes.Callvirt, typeof(IJsonReader).GetMethod("ParseInto", new Type[] { typeof(Object) }));
  555. il.Emit(OpCodes.Pop); // Clean up target left on stack (1)
  556. il.Emit(OpCodes.Ret);
  557. il.MarkLabel(lblExistingInstanceNull);
  558. }
  559. // Get the value from IJsonReader
  560. GenerateGetJsonValue(m, il);
  561. // Assign it
  562. if (pi != null)
  563. il.Emit(OpCodes.Callvirt, pi.GetSetMethod(true));
  564. if (fi != null)
  565. il.Emit(OpCodes.Stfld, fi);
  566. // Done
  567. il.Emit(OpCodes.Ret);
  568. // Store the handler in map
  569. setters.Add(m.JsonKey, (Action<IJsonReader, object>)method.CreateDelegate(typeof(Action<IJsonReader, object>)));
  570. }
  571. // Now create the parseInto delegate
  572. Action<IJsonReader, object> parseInto = (reader, obj) =>
  573. {
  574. // Call IJsonLoading
  575. var loading = obj as IJsonLoading;
  576. if (loading != null)
  577. loading.OnJsonLoading(reader);
  578. // Cache IJsonLoadField
  579. var lf = obj as IJsonLoadField;
  580. // Read dictionary keys
  581. reader.ParseDictionary(key =>
  582. {
  583. // Call IJsonLoadField
  584. if (lf != null && lf.OnJsonField(reader, key))
  585. return;
  586. // Call setters
  587. Action<IJsonReader, object> setter;
  588. if (setters.TryGetValue(key, out setter))
  589. {
  590. setter(reader, obj);
  591. }
  592. });
  593. // Call IJsonLoaded
  594. var loaded = obj as IJsonLoaded;
  595. if (loaded != null)
  596. loaded.OnJsonLoaded(reader);
  597. };
  598. // Since we've created the ParseInto handler, we might as well register
  599. // as a Parse handler too.
  600. RegisterIntoParser(type, parseInto);
  601. // Done
  602. return parseInto;
  603. }
  604. // Registers a ParseInto handler as Parse handler that instantiates the object
  605. // and then parses into it.
  606. static void RegisterIntoParser(Type type, Action<IJsonReader, object> parseInto)
  607. {
  608. // Check type has a parameterless constructor
  609. var con = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[0], null);
  610. if (con == null)
  611. return;
  612. // Create a dynamic method that can do the work
  613. var method = new DynamicMethod("dynamic_factory", typeof(object), new Type[] { typeof(IJsonReader), typeof(Action<IJsonReader, object>) }, true);
  614. var il = method.GetILGenerator();
  615. // Create the new object
  616. var locObj = il.DeclareLocal(typeof(object));
  617. il.Emit(OpCodes.Newobj, con);
  618. il.Emit(OpCodes.Dup); // For return value
  619. il.Emit(OpCodes.Stloc, locObj);
  620. il.Emit(OpCodes.Ldarg_1); // parseinto delegate
  621. il.Emit(OpCodes.Ldarg_0); // IJsonReader
  622. il.Emit(OpCodes.Ldloc, locObj); // new object instance
  623. il.Emit(OpCodes.Callvirt, typeof(Action<IJsonReader, object>).GetMethod("Invoke"));
  624. il.Emit(OpCodes.Ret);
  625. var factory = (Func<IJsonReader, Action<IJsonReader, object>, object>)method.CreateDelegate(typeof(Func<IJsonReader, Action<IJsonReader, object>, object>));
  626. Json.RegisterParser(type, (reader, type2) =>
  627. {
  628. return factory(reader, parseInto);
  629. });
  630. }
  631. // Generate the MSIL to retrieve a value for a particular field or property from a IJsonReader
  632. private static void GenerateGetJsonValue(JsonMemberInfo m, ILGenerator il)
  633. {
  634. Action<string> generateCallToHelper = helperName =>
  635. {
  636. // Call the helper
  637. il.Emit(OpCodes.Ldarg_0);
  638. il.Emit(OpCodes.Call, typeof(Emit).GetMethod(helperName, new Type[] { typeof(IJsonReader) }));
  639. // Move to next token
  640. il.Emit(OpCodes.Ldarg_0);
  641. il.Emit(OpCodes.Callvirt, typeof(IJsonReader).GetMethod("NextToken", new Type[] { }));
  642. };
  643. Type[] numericTypes = new Type[] {
  644. typeof(int), typeof(uint), typeof(long), typeof(ulong),
  645. typeof(short), typeof(ushort), typeof(decimal),
  646. typeof(byte), typeof(sbyte),
  647. typeof(double), typeof(float)
  648. };
  649. if (m.MemberType == typeof(string))
  650. {
  651. generateCallToHelper("GetLiteralString");
  652. }
  653. else if (m.MemberType == typeof(bool))
  654. {
  655. generateCallToHelper("GetLiteralBool");
  656. }
  657. else if (m.MemberType == typeof(char))
  658. {
  659. generateCallToHelper("GetLiteralChar");
  660. }
  661. else if (numericTypes.Contains(m.MemberType))
  662. {
  663. // Get raw number string
  664. il.Emit(OpCodes.Ldarg_0);
  665. il.Emit(OpCodes.Call, typeof(Emit).GetMethod("GetLiteralNumber", new Type[] { typeof(IJsonReader) }));
  666. // Convert to a string
  667. il.Emit(OpCodes.Call, typeof(CultureInfo).GetProperty("InvariantCulture").GetGetMethod());
  668. il.Emit(OpCodes.Call, m.MemberType.GetMethod("Parse", new Type[] { typeof(string), typeof(IFormatProvider) }));
  669. //
  670. il.Emit(OpCodes.Ldarg_0);
  671. il.Emit(OpCodes.Callvirt, typeof(IJsonReader).GetMethod("NextToken", new Type[] { }));
  672. }
  673. else
  674. {
  675. il.Emit(OpCodes.Ldarg_0);
  676. il.Emit(OpCodes.Ldtoken, m.MemberType);
  677. il.Emit(OpCodes.Call, typeof(Type).GetMethod("GetTypeFromHandle", new Type[] { typeof(RuntimeTypeHandle) }));
  678. il.Emit(OpCodes.Callvirt, typeof(IJsonReader).GetMethod("Parse", new Type[] { typeof(Type) }));
  679. il.Emit(m.MemberType.IsValueType ? OpCodes.Unbox_Any : OpCodes.Castclass, m.MemberType);
  680. }
  681. }
  682. // Helper to fetch a literal bool from an IJsonReader
  683. [Obfuscation(Exclude = true)]
  684. public static bool GetLiteralBool(IJsonReader r)
  685. {
  686. switch (r.GetLiteralKind())
  687. {
  688. case LiteralKind.True:
  689. return true;
  690. case LiteralKind.False:
  691. return false;
  692. default:
  693. throw new InvalidDataException("expected a boolean value");
  694. }
  695. }
  696. // Helper to fetch a literal character from an IJsonReader
  697. [Obfuscation(Exclude = true)]
  698. public static char GetLiteralChar(IJsonReader r)
  699. {
  700. if (r.GetLiteralKind() != LiteralKind.String)
  701. throw new InvalidDataException("expected a single character string literal");
  702. var str = r.GetLiteralString();
  703. if (str == null || str.Length != 1)
  704. throw new InvalidDataException("expected a single character string literal");
  705. return str[0];
  706. }
  707. // Helper to fetch a literal string from an IJsonReader
  708. [Obfuscation(Exclude = true)]
  709. public static string GetLiteralString(IJsonReader r)
  710. {
  711. switch (r.GetLiteralKind())
  712. {
  713. case LiteralKind.Null: return null;
  714. case LiteralKind.String: return r.GetLiteralString();
  715. }
  716. throw new InvalidDataException("expected a string literal");
  717. }
  718. // Helper to fetch a literal number from an IJsonReader (returns the raw string)
  719. [Obfuscation(Exclude = true)]
  720. public static string GetLiteralNumber(IJsonReader r)
  721. {
  722. switch (r.GetLiteralKind())
  723. {
  724. case LiteralKind.SignedInteger:
  725. case LiteralKind.UnsignedInteger:
  726. case LiteralKind.FloatingPoint:
  727. return r.GetLiteralString();
  728. }
  729. throw new InvalidDataException("expected a numeric literal");
  730. }
  731. }
  732. }
  733. #endif