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