Emit.cs 34 KB

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