Emit.cs 33 KB

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