PetaJsonEmit.cs 31 KB

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