Emit.cs 37 KB

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