Emit.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807
  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 IJsonReader
  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. // Write the Json key
  114. il.Emit(OpCodes.Ldarg_0);
  115. il.Emit(OpCodes.Ldstr, m.JsonKey);
  116. il.Emit(OpCodes.Callvirt, typeof(IJsonWriter).GetMethod("WriteKeyNoEscaping", new Type[] { typeof(string) }));
  117. // Load the writer
  118. il.Emit(OpCodes.Ldarg_0);
  119. // Get the member type
  120. var memberType = m.MemberType;
  121. // Load the target object
  122. if (type.IsValueType)
  123. {
  124. il.Emit(OpCodes.Ldloca, locTypedObj);
  125. }
  126. else
  127. {
  128. il.Emit(OpCodes.Ldloc, locTypedObj);
  129. }
  130. // Work out if we need the value or it's address on the stack
  131. bool NeedValueAddress = (memberType.IsValueType && (toStringTypes.Contains(memberType) || otherSupportedTypes.Contains(memberType)));
  132. if (Nullable.GetUnderlyingType(memberType) != null)
  133. {
  134. NeedValueAddress = true;
  135. }
  136. // Property?
  137. if (pi != null)
  138. {
  139. // Call property's get method
  140. if (type.IsValueType)
  141. il.Emit(OpCodes.Call, pi.GetGetMethod(true));
  142. else
  143. il.Emit(OpCodes.Callvirt, pi.GetGetMethod(true));
  144. // If we need the address then store in a local and take it's address
  145. if (NeedValueAddress)
  146. {
  147. var locTemp = il.DeclareLocal(memberType);
  148. il.Emit(OpCodes.Stloc, locTemp);
  149. il.Emit(OpCodes.Ldloca, locTemp);
  150. }
  151. }
  152. // Field?
  153. var fi = m.Member as FieldInfo;
  154. if (fi != null)
  155. {
  156. if (NeedValueAddress)
  157. {
  158. il.Emit(OpCodes.Ldflda, fi);
  159. }
  160. else
  161. {
  162. il.Emit(OpCodes.Ldfld, fi);
  163. }
  164. }
  165. Label? lblFinished = null;
  166. // Is it a nullable type?
  167. var typeUnderlying = Nullable.GetUnderlyingType(memberType);
  168. if (typeUnderlying != null)
  169. {
  170. // Duplicate the address so we can call get_HasValue() and then get_Value()
  171. il.Emit(OpCodes.Dup);
  172. // Define some labels
  173. var lblHasValue = il.DefineLabel();
  174. lblFinished = il.DefineLabel();
  175. // Call has_Value
  176. il.Emit(OpCodes.Call, memberType.GetProperty("HasValue").GetGetMethod());
  177. il.Emit(OpCodes.Brtrue, lblHasValue);
  178. // No value, write "null:
  179. il.Emit(OpCodes.Pop);
  180. il.Emit(OpCodes.Ldstr, "null");
  181. il.Emit(OpCodes.Callvirt, typeof(IJsonWriter).GetMethod("WriteRaw", new Type[] { typeof(string) }));
  182. il.Emit(OpCodes.Br_S, lblFinished.Value);
  183. // Get it's value
  184. il.MarkLabel(lblHasValue);
  185. il.Emit(OpCodes.Call, memberType.GetProperty("Value").GetGetMethod());
  186. // Switch to the underlying type from here on
  187. memberType = typeUnderlying;
  188. NeedValueAddress = (memberType.IsValueType && (toStringTypes.Contains(memberType) || otherSupportedTypes.Contains(memberType)));
  189. // Work out again if we need the address of the value
  190. if (NeedValueAddress)
  191. {
  192. var locTemp = il.DeclareLocal(memberType);
  193. il.Emit(OpCodes.Stloc, locTemp);
  194. il.Emit(OpCodes.Ldloca, locTemp);
  195. }
  196. }
  197. // ToString()
  198. if (toStringTypes.Contains(memberType))
  199. {
  200. // Convert to string
  201. il.Emit(OpCodes.Ldloc, locInvariant);
  202. il.Emit(OpCodes.Call, memberType.GetMethod("ToString", new Type[] { typeof(IFormatProvider) }));
  203. il.Emit(OpCodes.Callvirt, typeof(IJsonWriter).GetMethod("WriteRaw", new Type[] { typeof(string) }));
  204. }
  205. // ToString("R")
  206. else if (memberType == typeof(float) || memberType == typeof(double))
  207. {
  208. il.Emit(OpCodes.Ldstr, "R");
  209. il.Emit(OpCodes.Ldloc, locInvariant);
  210. il.Emit(OpCodes.Call, memberType.GetMethod("ToString", new Type[] { typeof(string), typeof(IFormatProvider) }));
  211. il.Emit(OpCodes.Callvirt, typeof(IJsonWriter).GetMethod("WriteRaw", new Type[] { typeof(string) }));
  212. }
  213. // String?
  214. else if (memberType == typeof(string))
  215. {
  216. il.Emit(OpCodes.Callvirt, typeof(IJsonWriter).GetMethod("WriteStringLiteral", new Type[] { typeof(string) }));
  217. }
  218. // Char?
  219. else if (memberType == typeof(char))
  220. {
  221. il.Emit(OpCodes.Call, memberType.GetMethod("ToString", new Type[] { }));
  222. il.Emit(OpCodes.Callvirt, typeof(IJsonWriter).GetMethod("WriteStringLiteral", new Type[] { typeof(string) }));
  223. }
  224. // Bool?
  225. else if (memberType == typeof(bool))
  226. {
  227. var lblTrue = il.DefineLabel();
  228. var lblCont = il.DefineLabel();
  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. // Unsupported type, pass through
  241. if (memberType.IsValueType)
  242. {
  243. il.Emit(OpCodes.Box, memberType);
  244. }
  245. il.Emit(OpCodes.Callvirt, typeof(IJsonWriter).GetMethod("WriteValue", new Type[] { typeof(object) }));
  246. }
  247. if (lblFinished.HasValue)
  248. il.MarkLabel(lblFinished.Value);
  249. }
  250. // Call IJsonWritten
  251. if (typeof(IJsonWritten).IsAssignableFrom(type))
  252. {
  253. if (type.IsValueType)
  254. {
  255. il.Emit(OpCodes.Ldloca, locTypedObj);
  256. il.Emit(OpCodes.Ldarg_0);
  257. il.Emit(OpCodes.Call, type.GetInterfaceMap(typeof(IJsonWritten)).TargetMethods[0]);
  258. }
  259. else
  260. {
  261. il.Emit(OpCodes.Ldloc, locTypedObj);
  262. il.Emit(OpCodes.Castclass, typeof(IJsonWriting));
  263. il.Emit(OpCodes.Ldarg_0);
  264. il.Emit(OpCodes.Callvirt, typeof(IJsonWriting).GetMethod("OnJsonWritten", new Type[] { typeof(IJsonWriter) }));
  265. }
  266. }
  267. // Done!
  268. il.Emit(OpCodes.Ret);
  269. var impl = (Action<IJsonWriter, object>)method.CreateDelegate(typeof(Action<IJsonWriter, object>));
  270. // Wrap it in a call to WriteDictionary
  271. return (w, obj) =>
  272. {
  273. w.WriteDictionary(() =>
  274. {
  275. impl(w, obj);
  276. });
  277. };
  278. }
  279. }
  280. // Pseudo box lets us pass a value type by reference. Used during
  281. // deserialization of value types.
  282. interface IPseudoBox
  283. {
  284. object GetValue();
  285. }
  286. [Obfuscation(Exclude = true, ApplyToMembers = true)]
  287. class PseudoBox<T> : IPseudoBox where T : struct
  288. {
  289. public T value = default(T);
  290. object IPseudoBox.GetValue() { return value; }
  291. }
  292. // Make a parser for value types
  293. public static Func<IJsonReader, Type, object> MakeParser(Type type)
  294. {
  295. System.Diagnostics.Debug.Assert(type.IsValueType);
  296. // ParseJson method?
  297. var parseJson = ReflectionInfo.FindParseJson(type);
  298. if (parseJson != null)
  299. {
  300. if (parseJson.GetParameters()[0].ParameterType == typeof(IJsonReader))
  301. {
  302. var method = new DynamicMethod("invoke_ParseJson", typeof(Object), new Type[] { typeof(IJsonReader), typeof(Type) }, true);
  303. var il = method.GetILGenerator();
  304. il.Emit(OpCodes.Ldarg_0);
  305. il.Emit(OpCodes.Call, parseJson);
  306. il.Emit(OpCodes.Box, type);
  307. il.Emit(OpCodes.Ret);
  308. return (Func<IJsonReader,Type,object>)method.CreateDelegate(typeof(Func<IJsonReader,Type,object>));
  309. }
  310. else
  311. {
  312. var method = new DynamicMethod("invoke_ParseJson", typeof(Object), new Type[] { typeof(string) }, true);
  313. var il = method.GetILGenerator();
  314. il.Emit(OpCodes.Ldarg_0);
  315. il.Emit(OpCodes.Call, parseJson);
  316. il.Emit(OpCodes.Box, type);
  317. il.Emit(OpCodes.Ret);
  318. var invoke = (Func<string, object>)method.CreateDelegate(typeof(Func<string, object>));
  319. return (r, t) =>
  320. {
  321. if (r.GetLiteralKind() == LiteralKind.String)
  322. {
  323. var o = invoke(r.GetLiteralString());
  324. r.NextToken();
  325. return o;
  326. }
  327. throw new InvalidDataException(string.Format("Expected string literal for type {0}", type.FullName));
  328. };
  329. }
  330. }
  331. else
  332. {
  333. // Get the reflection info for this type
  334. var ri = ReflectionInfo.GetReflectionInfo(type);
  335. if (ri == null)
  336. return null;
  337. // We'll create setters for each property/field
  338. var setters = new Dictionary<string, Action<IJsonReader, object>>();
  339. // Store the value in a pseudo box until it's fully initialized
  340. var boxType = typeof(PseudoBox<>).MakeGenericType(type);
  341. // Process all members
  342. foreach (var m in ri.Members)
  343. {
  344. // Ignore write only properties
  345. var pi = m.Member as PropertyInfo;
  346. var fi = m.Member as FieldInfo;
  347. if (pi != null && pi.GetSetMethod(true) == null)
  348. {
  349. continue;
  350. }
  351. // Create a dynamic method that can do the work
  352. var method = new DynamicMethod("dynamic_parser", null, new Type[] { typeof(IJsonReader), typeof(object) }, true);
  353. var il = method.GetILGenerator();
  354. // Load the target
  355. il.Emit(OpCodes.Ldarg_1);
  356. il.Emit(OpCodes.Castclass, boxType);
  357. il.Emit(OpCodes.Ldflda, boxType.GetField("value"));
  358. // Get the value
  359. GenerateGetJsonValue(m, il);
  360. // Assign it
  361. if (pi != null)
  362. il.Emit(OpCodes.Call, pi.GetSetMethod(true));
  363. if (fi != null)
  364. il.Emit(OpCodes.Stfld, fi);
  365. // Done
  366. il.Emit(OpCodes.Ret);
  367. // Store in the map of setters
  368. setters.Add(m.JsonKey, (Action<IJsonReader, object>)method.CreateDelegate(typeof(Action<IJsonReader, object>)));
  369. }
  370. // Create helpers to invoke the interfaces (this is painful but avoids having to really box
  371. // the value in order to call the interface).
  372. Action<object, IJsonReader> invokeLoading = MakeInterfaceCall(type, typeof(IJsonLoading));
  373. Action<object, IJsonReader> invokeLoaded = MakeInterfaceCall(type, typeof(IJsonLoaded));
  374. Func<object, IJsonReader, string, bool> invokeField = MakeLoadFieldCall(type);
  375. // Create the parser
  376. Func<IJsonReader, Type, object> parser = (reader, Type) =>
  377. {
  378. // Create pseudobox (ie: new PseudoBox<Type>)
  379. var box = DecoratingActivator.CreateInstance(boxType);
  380. // Call IJsonLoading
  381. if (invokeLoading != null)
  382. invokeLoading(box, reader);
  383. // Read the dictionary
  384. reader.ParseDictionary(key =>
  385. {
  386. // Call IJsonLoadField
  387. if (invokeField != null && invokeField(box, reader, key))
  388. return;
  389. // Get a setter and invoke it if found
  390. Action<IJsonReader, object> setter;
  391. if (setters.TryGetValue(key, out setter))
  392. {
  393. setter(reader, box);
  394. }
  395. });
  396. // IJsonLoaded
  397. if (invokeLoaded != null)
  398. invokeLoaded(box, reader);
  399. // Return the value
  400. return ((IPseudoBox)box).GetValue();
  401. };
  402. // Done
  403. return parser;
  404. }
  405. }
  406. // Helper to make the call to a PsuedoBox value's IJsonLoading or IJsonLoaded
  407. static Action<object, IJsonReader> MakeInterfaceCall(Type type, Type tItf)
  408. {
  409. // Interface supported?
  410. if (!tItf.IsAssignableFrom(type))
  411. return null;
  412. // Resolve the box type
  413. var boxType = typeof(PseudoBox<>).MakeGenericType(type);
  414. // Create method
  415. var method = new DynamicMethod("dynamic_invoke_" + tItf.Name, null, new Type[] { typeof(object), typeof(IJsonReader) }, true);
  416. var il = method.GetILGenerator();
  417. // Call interface method
  418. il.Emit(OpCodes.Ldarg_0);
  419. il.Emit(OpCodes.Castclass, boxType);
  420. il.Emit(OpCodes.Ldflda, boxType.GetField("value"));
  421. il.Emit(OpCodes.Ldarg_1);
  422. il.Emit(OpCodes.Call, type.GetInterfaceMap(tItf).TargetMethods[0]);
  423. il.Emit(OpCodes.Ret);
  424. // Done
  425. return (Action<object, IJsonReader>)method.CreateDelegate(typeof(Action<object, IJsonReader>));
  426. }
  427. // Similar to above but for IJsonLoadField
  428. static Func<object, IJsonReader, string, bool> MakeLoadFieldCall(Type type)
  429. {
  430. // Interface supported?
  431. var tItf = typeof(IJsonLoadField);
  432. if (!tItf.IsAssignableFrom(type))
  433. return null;
  434. // Resolve the box type
  435. var boxType = typeof(PseudoBox<>).MakeGenericType(type);
  436. // Create method
  437. var method = new DynamicMethod("dynamic_invoke_" + tItf.Name, typeof(bool), new Type[] { typeof(object), typeof(IJsonReader), typeof(string) }, true);
  438. var il = method.GetILGenerator();
  439. // Call interface method
  440. il.Emit(OpCodes.Ldarg_0);
  441. il.Emit(OpCodes.Castclass, boxType);
  442. il.Emit(OpCodes.Ldflda, boxType.GetField("value"));
  443. il.Emit(OpCodes.Ldarg_1);
  444. il.Emit(OpCodes.Ldarg_2);
  445. il.Emit(OpCodes.Call, type.GetInterfaceMap(tItf).TargetMethods[0]);
  446. il.Emit(OpCodes.Ret);
  447. // Done
  448. return (Func<object, IJsonReader, string, bool>)method.CreateDelegate(typeof(Func<object, IJsonReader, string, bool>));
  449. }
  450. // Create an "into parser" that can parse from IJsonReader into a reference type (ie: a class)
  451. public static Action<IJsonReader, object> MakeIntoParser(Type type)
  452. {
  453. System.Diagnostics.Debug.Assert(!type.IsValueType);
  454. // Get the reflection info for this type
  455. var ri = ReflectionInfo.GetReflectionInfo(type);
  456. if (ri == null)
  457. return null;
  458. // We'll create setters for each property/field
  459. var setters = new Dictionary<string, Action<IJsonReader, object>>();
  460. // Process all members
  461. foreach (var m in ri.Members)
  462. {
  463. // Ignore write only properties
  464. var pi = m.Member as PropertyInfo;
  465. var fi = m.Member as FieldInfo;
  466. if (pi != null && pi.GetSetMethod(true) == null)
  467. {
  468. continue;
  469. }
  470. // Ignore read only properties that has KeepInstance attribute
  471. if (pi != null && pi.GetGetMethod(true) == null && m.KeepInstance)
  472. {
  473. continue;
  474. }
  475. // Create a dynamic method that can do the work
  476. var method = new DynamicMethod("dynamic_parser", null, new Type[] { typeof(IJsonReader), typeof(object) }, true);
  477. var il = method.GetILGenerator();
  478. // Load the target
  479. il.Emit(OpCodes.Ldarg_1);
  480. il.Emit(OpCodes.Castclass, type);
  481. // Try to keep existing instance?
  482. if (m.KeepInstance)
  483. {
  484. // Get existing existing instance
  485. il.Emit(OpCodes.Dup);
  486. if (pi != null)
  487. il.Emit(OpCodes.Callvirt, pi.GetGetMethod(true));
  488. else
  489. il.Emit(OpCodes.Ldfld, fi);
  490. var existingInstance = il.DeclareLocal(m.MemberType);
  491. var lblExistingInstanceNull = il.DefineLabel();
  492. // Keep a copy of the existing instance in a locale
  493. il.Emit(OpCodes.Dup);
  494. il.Emit(OpCodes.Stloc, existingInstance);
  495. // Compare to null
  496. il.Emit(OpCodes.Ldnull);
  497. il.Emit(OpCodes.Ceq);
  498. il.Emit(OpCodes.Brtrue_S, lblExistingInstanceNull);
  499. il.Emit(OpCodes.Ldarg_0); // reader
  500. il.Emit(OpCodes.Ldloc, existingInstance); // into
  501. il.Emit(OpCodes.Callvirt, typeof(IJsonReader).GetMethod("ParseInto", new Type[] { typeof(Object) }));
  502. il.Emit(OpCodes.Pop); // Clean up target left on stack (1)
  503. il.Emit(OpCodes.Ret);
  504. il.MarkLabel(lblExistingInstanceNull);
  505. }
  506. // Get the value from IJsonReader
  507. GenerateGetJsonValue(m, il);
  508. // Assign it
  509. if (pi != null)
  510. il.Emit(OpCodes.Callvirt, pi.GetSetMethod(true));
  511. if (fi != null)
  512. il.Emit(OpCodes.Stfld, fi);
  513. // Done
  514. il.Emit(OpCodes.Ret);
  515. // Store the handler in map
  516. setters.Add(m.JsonKey, (Action<IJsonReader, object>)method.CreateDelegate(typeof(Action<IJsonReader, object>)));
  517. }
  518. // Now create the parseInto delegate
  519. Action<IJsonReader, object> parseInto = (reader, obj) =>
  520. {
  521. // Call IJsonLoading
  522. var loading = obj as IJsonLoading;
  523. if (loading != null)
  524. loading.OnJsonLoading(reader);
  525. // Cache IJsonLoadField
  526. var lf = obj as IJsonLoadField;
  527. // Read dictionary keys
  528. reader.ParseDictionary(key =>
  529. {
  530. // Call IJsonLoadField
  531. if (lf != null && lf.OnJsonField(reader, key))
  532. return;
  533. // Call setters
  534. Action<IJsonReader, object> setter;
  535. if (setters.TryGetValue(key, out setter))
  536. {
  537. setter(reader, obj);
  538. }
  539. });
  540. // Call IJsonLoaded
  541. var loaded = obj as IJsonLoaded;
  542. if (loaded != null)
  543. loaded.OnJsonLoaded(reader);
  544. };
  545. // Since we've created the ParseInto handler, we might as well register
  546. // as a Parse handler too.
  547. RegisterIntoParser(type, parseInto);
  548. // Done
  549. return parseInto;
  550. }
  551. // Registers a ParseInto handler as Parse handler that instantiates the object
  552. // and then parses into it.
  553. static void RegisterIntoParser(Type type, Action<IJsonReader, object> parseInto)
  554. {
  555. // Check type has a parameterless constructor
  556. var con = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[0], null);
  557. if (con == null)
  558. return;
  559. // Create a dynamic method that can do the work
  560. var method = new DynamicMethod("dynamic_factory", typeof(object), new Type[] { typeof(IJsonReader), typeof(Action<IJsonReader, object>) }, true);
  561. var il = method.GetILGenerator();
  562. // Create the new object
  563. var locObj = il.DeclareLocal(typeof(object));
  564. il.Emit(OpCodes.Newobj, con);
  565. il.Emit(OpCodes.Dup); // For return value
  566. il.Emit(OpCodes.Stloc, locObj);
  567. il.Emit(OpCodes.Ldarg_1); // parseinto delegate
  568. il.Emit(OpCodes.Ldarg_0); // IJsonReader
  569. il.Emit(OpCodes.Ldloc, locObj); // new object instance
  570. il.Emit(OpCodes.Callvirt, typeof(Action<IJsonReader, object>).GetMethod("Invoke"));
  571. il.Emit(OpCodes.Ret);
  572. var factory = (Func<IJsonReader, Action<IJsonReader, object>, object>)method.CreateDelegate(typeof(Func<IJsonReader, Action<IJsonReader, object>, object>));
  573. Json.RegisterParser(type, (reader, type2) =>
  574. {
  575. return factory(reader, parseInto);
  576. });
  577. }
  578. // Generate the MSIL to retrieve a value for a particular field or property from a IJsonReader
  579. private static void GenerateGetJsonValue(JsonMemberInfo m, ILGenerator il)
  580. {
  581. Action<string> generateCallToHelper = helperName =>
  582. {
  583. // Call the helper
  584. il.Emit(OpCodes.Ldarg_0);
  585. il.Emit(OpCodes.Call, typeof(Emit).GetMethod(helperName, new Type[] { typeof(IJsonReader) }));
  586. // Move to next token
  587. il.Emit(OpCodes.Ldarg_0);
  588. il.Emit(OpCodes.Callvirt, typeof(IJsonReader).GetMethod("NextToken", new Type[] { }));
  589. };
  590. Type[] numericTypes = new Type[] {
  591. typeof(int), typeof(uint), typeof(long), typeof(ulong),
  592. typeof(short), typeof(ushort), typeof(decimal),
  593. typeof(byte), typeof(sbyte),
  594. typeof(double), typeof(float)
  595. };
  596. if (m.MemberType == typeof(string))
  597. {
  598. generateCallToHelper("GetLiteralString");
  599. }
  600. else if (m.MemberType == typeof(bool))
  601. {
  602. generateCallToHelper("GetLiteralBool");
  603. }
  604. else if (m.MemberType == typeof(char))
  605. {
  606. generateCallToHelper("GetLiteralChar");
  607. }
  608. else if (numericTypes.Contains(m.MemberType))
  609. {
  610. // Get raw number string
  611. il.Emit(OpCodes.Ldarg_0);
  612. il.Emit(OpCodes.Call, typeof(Emit).GetMethod("GetLiteralNumber", new Type[] { typeof(IJsonReader) }));
  613. // Convert to a string
  614. il.Emit(OpCodes.Call, typeof(CultureInfo).GetProperty("InvariantCulture").GetGetMethod());
  615. il.Emit(OpCodes.Call, m.MemberType.GetMethod("Parse", new Type[] { typeof(string), typeof(IFormatProvider) }));
  616. //
  617. il.Emit(OpCodes.Ldarg_0);
  618. il.Emit(OpCodes.Callvirt, typeof(IJsonReader).GetMethod("NextToken", new Type[] { }));
  619. }
  620. else
  621. {
  622. il.Emit(OpCodes.Ldarg_0);
  623. il.Emit(OpCodes.Ldtoken, m.MemberType);
  624. il.Emit(OpCodes.Call, typeof(Type).GetMethod("GetTypeFromHandle", new Type[] { typeof(RuntimeTypeHandle) }));
  625. il.Emit(OpCodes.Callvirt, typeof(IJsonReader).GetMethod("Parse", new Type[] { typeof(Type) }));
  626. il.Emit(m.MemberType.IsValueType ? OpCodes.Unbox_Any : OpCodes.Castclass, m.MemberType);
  627. }
  628. }
  629. // Helper to fetch a literal bool from an IJsonReader
  630. [Obfuscation(Exclude = true)]
  631. public static bool GetLiteralBool(IJsonReader r)
  632. {
  633. switch (r.GetLiteralKind())
  634. {
  635. case LiteralKind.True:
  636. return true;
  637. case LiteralKind.False:
  638. return false;
  639. default:
  640. throw new InvalidDataException("expected a boolean value");
  641. }
  642. }
  643. // Helper to fetch a literal character from an IJsonReader
  644. [Obfuscation(Exclude = true)]
  645. public static char GetLiteralChar(IJsonReader r)
  646. {
  647. if (r.GetLiteralKind() != LiteralKind.String)
  648. throw new InvalidDataException("expected a single character string literal");
  649. var str = r.GetLiteralString();
  650. if (str == null || str.Length != 1)
  651. throw new InvalidDataException("expected a single character string literal");
  652. return str[0];
  653. }
  654. // Helper to fetch a literal string from an IJsonReader
  655. [Obfuscation(Exclude = true)]
  656. public static string GetLiteralString(IJsonReader r)
  657. {
  658. switch (r.GetLiteralKind())
  659. {
  660. case LiteralKind.Null: return null;
  661. case LiteralKind.String: return r.GetLiteralString();
  662. }
  663. throw new InvalidDataException("expected a string literal");
  664. }
  665. // Helper to fetch a literal number from an IJsonReader (returns the raw string)
  666. [Obfuscation(Exclude = true)]
  667. public static string GetLiteralNumber(IJsonReader r)
  668. {
  669. switch (r.GetLiteralKind())
  670. {
  671. case LiteralKind.SignedInteger:
  672. case LiteralKind.UnsignedInteger:
  673. case LiteralKind.FloatingPoint:
  674. return r.GetLiteralString();
  675. }
  676. throw new InvalidDataException("expected a numeric literal");
  677. }
  678. }
  679. }
  680. #endif