PetaJson.cs 131 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321
  1. // PetaJson v0.5 - A simple but flexible Json library in a single .cs file.
  2. //
  3. // Copyright (C) 2014 Topten Software (contact@toptensoftware.com) All rights reserved.
  4. //
  5. // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this product
  6. // except in compliance with the License. You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software distributed under the
  11. // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
  12. // either express or implied. See the License for the specific language governing permissions
  13. // and limitations under the License.
  14. // Define PETAJSON_NO_DYNAMIC to disable Expando support
  15. // Define PETAJSON_NO_EMIT to disable Reflection.Emit
  16. // Define PETAJSON_NO_DATACONTRACT to disable support for [DataContract]/[DataMember]
  17. using System;
  18. using System.Collections.Generic;
  19. using System.Linq;
  20. using System.Text;
  21. using System.IO;
  22. using System.Reflection;
  23. using System.Globalization;
  24. using System.Collections;
  25. using System.Threading;
  26. #if !PETAJSON_NO_DYNAMIC
  27. using System.Dynamic;
  28. #endif
  29. #if !PETAJSON_NO_EMIT
  30. using System.Reflection.Emit;
  31. #endif
  32. #if !PETAJSON_NO_DATACONTRACT
  33. using System.Runtime.Serialization;
  34. #endif
  35. namespace PetaJson
  36. {
  37. // Pass to format/write/parse functions to override defaults
  38. [Flags]
  39. public enum JsonOptions
  40. {
  41. None = 0,
  42. WriteWhitespace = 0x00000001,
  43. DontWriteWhitespace = 0x00000002,
  44. StrictParser = 0x00000004,
  45. NonStrictParser = 0x00000008,
  46. }
  47. // API
  48. public static class Json
  49. {
  50. static Json()
  51. {
  52. WriteWhitespaceDefault = true;
  53. StrictParserDefault = false;
  54. #if !PETAJSON_NO_EMIT
  55. Json.SetFormatterResolver(Internal.Emit.MakeFormatter);
  56. Json.SetParserResolver(Internal.Emit.MakeParser);
  57. Json.SetIntoParserResolver(Internal.Emit.MakeIntoParser);
  58. #endif
  59. }
  60. // Pretty format default
  61. public static bool WriteWhitespaceDefault
  62. {
  63. get;
  64. set;
  65. }
  66. // Strict parser
  67. public static bool StrictParserDefault
  68. {
  69. get;
  70. set;
  71. }
  72. // Write an object to a text writer
  73. public static void Write(TextWriter w, object o, JsonOptions options = JsonOptions.None)
  74. {
  75. var writer = new Internal.Writer(w, ResolveOptions(options));
  76. writer.WriteValue(o);
  77. }
  78. static void DeleteFile(string filename)
  79. {
  80. try
  81. {
  82. System.IO.File.Delete(filename);
  83. }
  84. catch
  85. {
  86. // Don't care
  87. }
  88. }
  89. // Write a file atomically by writing to a temp file and then renaming it - prevents corrupted files if crash
  90. // in middle of writing file.
  91. public static void WriteFileAtomic(string filename, object o, JsonOptions options = JsonOptions.None)
  92. {
  93. var tempName = filename + ".tmp";
  94. try
  95. {
  96. // Write the temp file
  97. WriteFile(tempName, o, options);
  98. // Delete the original file
  99. DeleteFile(filename);
  100. // Rename the temp file
  101. System.IO.File.Move(tempName, filename);
  102. }
  103. catch
  104. {
  105. DeleteFile(tempName);
  106. throw;
  107. }
  108. }
  109. // Write an object to a file
  110. public static void WriteFile(string filename, object o, JsonOptions options = JsonOptions.None)
  111. {
  112. using (var w = new StreamWriter(filename))
  113. {
  114. Write(w, o, options);
  115. }
  116. }
  117. // Format an object as a json string
  118. public static string Format(object o, JsonOptions options = JsonOptions.None)
  119. {
  120. var sw = new StringWriter();
  121. var writer = new Internal.Writer(sw, ResolveOptions(options));
  122. writer.WriteValue(o);
  123. return sw.ToString();
  124. }
  125. // Parse an object of specified type from a text reader
  126. public static object Parse(TextReader r, Type type, JsonOptions options = JsonOptions.None)
  127. {
  128. Internal.Reader reader = null;
  129. try
  130. {
  131. reader = new Internal.Reader(r, ResolveOptions(options));
  132. var retv = reader.Parse(type);
  133. reader.CheckEOF();
  134. return retv;
  135. }
  136. catch (Exception x)
  137. {
  138. var loc = reader == null ? new JsonLineOffset() : reader.CurrentTokenPosition;
  139. Console.WriteLine("Exception thrown while parsing JSON at {0}, context:{1}\n{2}", loc, reader.Context, x.ToString());
  140. throw new JsonParseException(x, reader.Context, loc);
  141. }
  142. }
  143. // Parse an object of specified type from a text reader
  144. public static T Parse<T>(TextReader r, JsonOptions options = JsonOptions.None)
  145. {
  146. return (T)Parse(r, typeof(T), options);
  147. }
  148. // Parse from text reader into an already instantied object
  149. public static void ParseInto(TextReader r, Object into, JsonOptions options = JsonOptions.None)
  150. {
  151. if (into == null)
  152. throw new NullReferenceException();
  153. if (into.GetType().IsValueType)
  154. throw new InvalidOperationException("Can't ParseInto a value type");
  155. Internal.Reader reader = null;
  156. try
  157. {
  158. reader = new Internal.Reader(r, ResolveOptions(options));
  159. reader.ParseInto(into);
  160. reader.CheckEOF();
  161. }
  162. catch (Exception x)
  163. {
  164. var loc = reader == null ? new JsonLineOffset() : reader.CurrentTokenPosition;
  165. Console.WriteLine("Exception thrown while parsing JSON at {0}, context:{1}\n{2}", loc, reader.Context, x.ToString());
  166. throw new JsonParseException(x,reader.Context,loc);
  167. }
  168. }
  169. // Parse an object of specified type from a file
  170. public static object ParseFile(string filename, Type type, JsonOptions options = JsonOptions.None)
  171. {
  172. using (var r = new StreamReader(filename))
  173. {
  174. return Parse(r, type, options);
  175. }
  176. }
  177. // Parse an object of specified type from a file
  178. public static T ParseFile<T>(string filename, JsonOptions options = JsonOptions.None)
  179. {
  180. using (var r = new StreamReader(filename))
  181. {
  182. return Parse<T>(r, options);
  183. }
  184. }
  185. // Parse from file into an already instantied object
  186. public static void ParseFileInto(string filename, Object into, JsonOptions options = JsonOptions.None)
  187. {
  188. using (var r = new StreamReader(filename))
  189. {
  190. ParseInto(r, into, options);
  191. }
  192. }
  193. // Parse an object from a string
  194. public static object Parse(string data, Type type, JsonOptions options = JsonOptions.None)
  195. {
  196. return Parse(new StringReader(data), type, options);
  197. }
  198. // Parse an object from a string
  199. public static T Parse<T>(string data, JsonOptions options = JsonOptions.None)
  200. {
  201. return (T)Parse<T>(new StringReader(data), options);
  202. }
  203. // Parse from string into an already instantiated object
  204. public static void ParseInto(string data, Object into, JsonOptions options = JsonOptions.None)
  205. {
  206. ParseInto(new StringReader(data), into, options);
  207. }
  208. // Create a clone of an object
  209. public static T Clone<T>(T source)
  210. {
  211. return (T)Reparse(source.GetType(), source);
  212. }
  213. // Create a clone of an object (untyped)
  214. public static object Clone(object source)
  215. {
  216. return Reparse(source.GetType(), source);
  217. }
  218. // Clone an object into another instance
  219. public static void CloneInto(object dest, object source)
  220. {
  221. ReparseInto(dest, source);
  222. }
  223. // Reparse an object by writing to a stream and re-reading (possibly
  224. // as a different type).
  225. public static object Reparse(Type type, object source)
  226. {
  227. if (source == null)
  228. return null;
  229. var ms = new MemoryStream();
  230. try
  231. {
  232. // Write
  233. var w = new StreamWriter(ms);
  234. Json.Write(w, source);
  235. w.Flush();
  236. // Read
  237. ms.Seek(0, SeekOrigin.Begin);
  238. var r = new StreamReader(ms);
  239. return Json.Parse(r, type);
  240. }
  241. finally
  242. {
  243. ms.Dispose();
  244. }
  245. }
  246. // Typed version of above
  247. public static T Reparse<T>(object source)
  248. {
  249. return (T)Reparse(typeof(T), source);
  250. }
  251. // Reparse one object into another object
  252. public static void ReparseInto(object dest, object source)
  253. {
  254. var ms = new MemoryStream();
  255. try
  256. {
  257. // Write
  258. var w = new StreamWriter(ms);
  259. Json.Write(w, source);
  260. w.Flush();
  261. // Read
  262. ms.Seek(0, SeekOrigin.Begin);
  263. var r = new StreamReader(ms);
  264. Json.ParseInto(r, dest);
  265. }
  266. finally
  267. {
  268. ms.Dispose();
  269. }
  270. }
  271. // Register a callback that can format a value of a particular type into json
  272. public static void RegisterFormatter(Type type, Action<IJsonWriter, object> formatter)
  273. {
  274. Internal.Writer._formatters[type] = formatter;
  275. }
  276. // Typed version of above
  277. public static void RegisterFormatter<T>(Action<IJsonWriter, T> formatter)
  278. {
  279. RegisterFormatter(typeof(T), (w, o) => formatter(w, (T)o));
  280. }
  281. // Register a parser for a specified type
  282. public static void RegisterParser(Type type, Func<IJsonReader, Type, object> parser)
  283. {
  284. Internal.Reader._parsers.Set(type, parser);
  285. }
  286. // Register a typed parser
  287. public static void RegisterParser<T>(Func<IJsonReader, Type, T> parser)
  288. {
  289. RegisterParser(typeof(T), (r, t) => parser(r, t));
  290. }
  291. // Simpler version for simple types
  292. public static void RegisterParser(Type type, Func<object, object> parser)
  293. {
  294. RegisterParser(type, (r, t) => r.ReadLiteral(parser));
  295. }
  296. // Simpler and typesafe parser for simple types
  297. public static void RegisterParser<T>(Func<object, T> parser)
  298. {
  299. RegisterParser(typeof(T), literal => parser(literal));
  300. }
  301. // Register an into parser
  302. public static void RegisterIntoParser(Type type, Action<IJsonReader, object> parser)
  303. {
  304. Internal.Reader._intoParsers.Set(type, parser);
  305. }
  306. // Register an into parser
  307. public static void RegisterIntoParser<T>(Action<IJsonReader, object> parser)
  308. {
  309. RegisterIntoParser(typeof(T), parser);
  310. }
  311. // Register a factory for instantiating objects (typically abstract classes)
  312. // Callback will be invoked for each key in the dictionary until it returns an object
  313. // instance and which point it will switch to serialization using reflection
  314. public static void RegisterTypeFactory(Type type, Func<IJsonReader, string, object> factory)
  315. {
  316. Internal.Reader._typeFactories.Set(type, factory);
  317. }
  318. // Register a callback to provide a formatter for a newly encountered type
  319. public static void SetFormatterResolver(Func<Type, Action<IJsonWriter, object>> resolver)
  320. {
  321. Internal.Writer._formatterResolver = resolver;
  322. }
  323. // Register a callback to provide a parser for a newly encountered value type
  324. public static void SetParserResolver(Func<Type, Func<IJsonReader, Type, object>> resolver)
  325. {
  326. Internal.Reader._parserResolver = resolver;
  327. }
  328. // Register a callback to provide a parser for a newly encountered reference type
  329. public static void SetIntoParserResolver(Func<Type, Action<IJsonReader, object>> resolver)
  330. {
  331. Internal.Reader._intoParserResolver = resolver;
  332. }
  333. public static bool WalkPath(this IDictionary<string, object> This, string Path, bool create, Func<IDictionary<string,object>,string, bool> leafCallback)
  334. {
  335. // Walk the path
  336. var parts = Path.Split('.');
  337. for (int i = 0; i < parts.Length-1; i++)
  338. {
  339. object val;
  340. if (!This.TryGetValue(parts[i], out val))
  341. {
  342. if (!create)
  343. return false;
  344. val = new Dictionary<string, object>();
  345. This[parts[i]] = val;
  346. }
  347. This = (IDictionary<string,object>)val;
  348. }
  349. // Process the leaf
  350. return leafCallback(This, parts[parts.Length-1]);
  351. }
  352. public static bool PathExists(this IDictionary<string, object> This, string Path)
  353. {
  354. return This.WalkPath(Path, false, (dict, key) => dict.ContainsKey(key));
  355. }
  356. public static object GetPath(this IDictionary<string, object> This, Type type, string Path, object def)
  357. {
  358. This.WalkPath(Path, false, (dict, key) =>
  359. {
  360. object val;
  361. if (dict.TryGetValue(key, out val))
  362. {
  363. if (val == null)
  364. def = val;
  365. else if (type.IsAssignableFrom(val.GetType()))
  366. def = val;
  367. else
  368. def = Reparse(type, val);
  369. }
  370. return true;
  371. });
  372. return def;
  373. }
  374. // Ensure there's an object of type T at specified path
  375. public static T GetObjectAtPath<T>(this IDictionary<string, object> This, string Path) where T:class,new()
  376. {
  377. T retVal = null;
  378. This.WalkPath(Path, true, (dict, key) =>
  379. {
  380. object val;
  381. dict.TryGetValue(key, out val);
  382. retVal = val as T;
  383. if (retVal == null)
  384. {
  385. retVal = val == null ? new T() : Reparse<T>(val);
  386. dict[key] = retVal;
  387. }
  388. return true;
  389. });
  390. return retVal;
  391. }
  392. public static T GetPath<T>(this IDictionary<string, object> This, string Path, T def = default(T))
  393. {
  394. return (T)This.GetPath(typeof(T), Path, def);
  395. }
  396. public static void SetPath(this IDictionary<string, object> This, string Path, object value)
  397. {
  398. This.WalkPath(Path, true, (dict, key) => { dict[key] = value; return true; });
  399. }
  400. // Resolve passed options
  401. static JsonOptions ResolveOptions(JsonOptions options)
  402. {
  403. JsonOptions resolved = JsonOptions.None;
  404. if ((options & (JsonOptions.WriteWhitespace|JsonOptions.DontWriteWhitespace))!=0)
  405. resolved |= options & (JsonOptions.WriteWhitespace | JsonOptions.DontWriteWhitespace);
  406. else
  407. resolved |= WriteWhitespaceDefault ? JsonOptions.WriteWhitespace : JsonOptions.DontWriteWhitespace;
  408. if ((options & (JsonOptions.StrictParser | JsonOptions.NonStrictParser)) != 0)
  409. resolved |= options & (JsonOptions.StrictParser | JsonOptions.NonStrictParser);
  410. else
  411. resolved |= StrictParserDefault ? JsonOptions.StrictParser : JsonOptions.NonStrictParser;
  412. return resolved;
  413. }
  414. }
  415. // Called before loading via reflection
  416. [Obfuscation(Exclude = true, ApplyToMembers = true)]
  417. public interface IJsonLoading
  418. {
  419. void OnJsonLoading(IJsonReader r);
  420. }
  421. // Called after loading via reflection
  422. [Obfuscation(Exclude = true, ApplyToMembers = true)]
  423. public interface IJsonLoaded
  424. {
  425. void OnJsonLoaded(IJsonReader r);
  426. }
  427. // Called for each field while loading from reflection
  428. // Return true if handled
  429. [Obfuscation(Exclude = true, ApplyToMembers = true)]
  430. public interface IJsonLoadField
  431. {
  432. bool OnJsonField(IJsonReader r, string key);
  433. }
  434. // Called when about to write using reflection
  435. [Obfuscation(Exclude = true, ApplyToMembers = true)]
  436. public interface IJsonWriting
  437. {
  438. void OnJsonWriting(IJsonWriter w);
  439. }
  440. // Called after written using reflection
  441. [Obfuscation(Exclude = true, ApplyToMembers = true)]
  442. public interface IJsonWritten
  443. {
  444. void OnJsonWritten(IJsonWriter w);
  445. }
  446. // Describes the current literal in the json stream
  447. public enum LiteralKind
  448. {
  449. None,
  450. String,
  451. Null,
  452. True,
  453. False,
  454. SignedInteger,
  455. UnsignedInteger,
  456. FloatingPoint,
  457. }
  458. // Passed to registered parsers
  459. [Obfuscation(Exclude=true, ApplyToMembers=true)]
  460. public interface IJsonReader
  461. {
  462. object Parse(Type type);
  463. T Parse<T>();
  464. void ParseInto(object into);
  465. object ReadLiteral(Func<object, object> converter);
  466. void ParseDictionary(Action<string> callback);
  467. void ParseArray(Action callback);
  468. LiteralKind GetLiteralKind();
  469. string GetLiteralString();
  470. void NextToken();
  471. }
  472. // Passed to registered formatters
  473. [Obfuscation(Exclude = true, ApplyToMembers = true)]
  474. public interface IJsonWriter
  475. {
  476. void WriteStringLiteral(string str);
  477. void WriteRaw(string str);
  478. void WriteArray(Action callback);
  479. void WriteDictionary(Action callback);
  480. void WriteValue(object value);
  481. void WriteElement();
  482. void WriteKey(string key);
  483. void WriteKeyNoEscaping(string key);
  484. }
  485. // Exception thrown for any parse error
  486. public class JsonParseException : Exception
  487. {
  488. public JsonParseException(Exception inner, string context, JsonLineOffset position) :
  489. base(string.Format("JSON parse error at {0}{1} - {2}", position, string.IsNullOrEmpty(context) ? "" : string.Format(", context {0}", context), inner.Message), inner)
  490. {
  491. Position = position;
  492. Context = context;
  493. }
  494. public JsonLineOffset Position;
  495. public string Context;
  496. }
  497. // Represents a line and character offset position in the source Json
  498. public struct JsonLineOffset
  499. {
  500. public int Line;
  501. public int Offset;
  502. public override string ToString()
  503. {
  504. return string.Format("line {0}, character {1}", Line + 1, Offset + 1);
  505. }
  506. }
  507. // Used to decorate fields and properties that should be serialized
  508. //
  509. // - [Json] on class or struct causes all public fields and properties to be serialized
  510. // - [Json] on a public or non-public field or property causes that member to be serialized
  511. // - [JsonExclude] on a field or property causes that field to be not serialized
  512. // - A class or struct with no [Json] attribute has all public fields/properties serialized
  513. // - A class or struct with no [Json] attribute but a [Json] attribute on one or more members only serializes those members
  514. //
  515. // Use [Json("keyname")] to explicitly specify the key to be used
  516. // [Json] without the keyname will be serialized using the name of the member with the first letter lowercased.
  517. //
  518. // [Json(KeepInstance=true)] causes container/subobject types to be serialized into the existing member instance (if not null)
  519. //
  520. // You can also use the system supplied DataContract and DataMember attributes. They'll only be used if there
  521. // are no PetaJson attributes on the class or it's members. You must specify DataContract on the type and
  522. // DataMember on any fields/properties that require serialization. There's no need for exclude attribute.
  523. // When using DataMember, the name of the field or property is used as is - the first letter is left in upper case
  524. //
  525. [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Property | AttributeTargets.Field)]
  526. public class JsonAttribute : Attribute
  527. {
  528. public JsonAttribute()
  529. {
  530. _key = null;
  531. }
  532. public JsonAttribute(string key)
  533. {
  534. _key = key;
  535. }
  536. // Key used to save this field/property
  537. string _key;
  538. public string Key
  539. {
  540. get { return _key; }
  541. }
  542. // If true uses ParseInto to parse into the existing object instance
  543. // If false, creates a new instance as assigns it to the property
  544. public bool KeepInstance
  545. {
  546. get;
  547. set;
  548. }
  549. // If true, the property will be loaded, but not saved
  550. // Use to upgrade deprecated persisted settings, but not
  551. // write them back out again
  552. public bool Deprecated
  553. {
  554. get;
  555. set;
  556. }
  557. }
  558. // See comments for JsonAttribute above
  559. [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
  560. public class JsonExcludeAttribute : Attribute
  561. {
  562. public JsonExcludeAttribute()
  563. {
  564. }
  565. }
  566. // Apply to enum values to specify which enum value to select
  567. // if the supplied json value doesn't match any.
  568. // If not found throws an exception
  569. // eg, any unknown values in the json will be mapped to Fruit.unknown
  570. //
  571. // [JsonUnknown(Fruit.unknown)]
  572. // enum Fruit
  573. // {
  574. // unknown,
  575. // Apple,
  576. // Pear,
  577. // }
  578. [AttributeUsage(AttributeTargets.Enum)]
  579. public class JsonUnknownAttribute : Attribute
  580. {
  581. public JsonUnknownAttribute(object unknownValue)
  582. {
  583. UnknownValue = unknownValue;
  584. }
  585. public object UnknownValue
  586. {
  587. get;
  588. private set;
  589. }
  590. }
  591. namespace Internal
  592. {
  593. [Obfuscation(Exclude = true, ApplyToMembers = true)]
  594. public enum Token
  595. {
  596. EOF,
  597. Identifier,
  598. Literal,
  599. OpenBrace,
  600. CloseBrace,
  601. OpenSquare,
  602. CloseSquare,
  603. Equal,
  604. Colon,
  605. SemiColon,
  606. Comma,
  607. }
  608. // Helper to create instances but include the type name in the thrown exception
  609. public static class DecoratingActivator
  610. {
  611. public static object CreateInstance(Type t)
  612. {
  613. try
  614. {
  615. return Activator.CreateInstance(t);
  616. }
  617. catch (Exception x)
  618. {
  619. throw new InvalidOperationException(string.Format("Failed to create instance of type '{0}'", t.FullName), x);
  620. }
  621. }
  622. }
  623. public class Reader : IJsonReader
  624. {
  625. static Reader()
  626. {
  627. // Setup default resolvers
  628. _parserResolver = ResolveParser;
  629. _intoParserResolver = ResolveIntoParser;
  630. Func<IJsonReader, Type, object> simpleConverter = (reader, type) =>
  631. {
  632. return reader.ReadLiteral(literal => Convert.ChangeType(literal, type, CultureInfo.InvariantCulture));
  633. };
  634. Func<IJsonReader, Type, object> numberConverter = (reader, type) =>
  635. {
  636. switch (reader.GetLiteralKind())
  637. {
  638. case LiteralKind.SignedInteger:
  639. case LiteralKind.UnsignedInteger:
  640. case LiteralKind.FloatingPoint:
  641. object val = Convert.ChangeType(reader.GetLiteralString(), type, CultureInfo.InvariantCulture);
  642. reader.NextToken();
  643. return val;
  644. }
  645. throw new InvalidDataException("expected a numeric literal");
  646. };
  647. // Default type handlers
  648. _parsers.Set(typeof(string), simpleConverter);
  649. _parsers.Set(typeof(char), simpleConverter);
  650. _parsers.Set(typeof(bool), simpleConverter);
  651. _parsers.Set(typeof(byte), numberConverter);
  652. _parsers.Set(typeof(sbyte), numberConverter);
  653. _parsers.Set(typeof(short), numberConverter);
  654. _parsers.Set(typeof(ushort), numberConverter);
  655. _parsers.Set(typeof(int), numberConverter);
  656. _parsers.Set(typeof(uint), numberConverter);
  657. _parsers.Set(typeof(long), numberConverter);
  658. _parsers.Set(typeof(ulong), numberConverter);
  659. _parsers.Set(typeof(decimal), numberConverter);
  660. _parsers.Set(typeof(float), numberConverter);
  661. _parsers.Set(typeof(double), numberConverter);
  662. _parsers.Set(typeof(DateTime), (reader, type) =>
  663. {
  664. return reader.ReadLiteral(literal => Utils.FromUnixMilliseconds((long)Convert.ChangeType(literal, typeof(long), CultureInfo.InvariantCulture)));
  665. });
  666. _parsers.Set(typeof(byte[]), (reader, type) =>
  667. {
  668. return reader.ReadLiteral(literal => Convert.FromBase64String((string)Convert.ChangeType(literal, typeof(string), CultureInfo.InvariantCulture)));
  669. });
  670. }
  671. public Reader(TextReader r, JsonOptions options)
  672. {
  673. _tokenizer = new Tokenizer(r, options);
  674. _options = options;
  675. }
  676. Tokenizer _tokenizer;
  677. JsonOptions _options;
  678. List<string> _contextStack = new List<string>();
  679. public string Context
  680. {
  681. get
  682. {
  683. return string.Join(".", _contextStack);
  684. }
  685. }
  686. static Action<IJsonReader, object> ResolveIntoParser(Type type)
  687. {
  688. var ri = ReflectionInfo.GetReflectionInfo(type);
  689. if (ri != null)
  690. return ri.ParseInto;
  691. else
  692. return null;
  693. }
  694. static Func<IJsonReader, Type, object> ResolveParser(Type type)
  695. {
  696. // See if the Type has a static parser method - T ParseJson(IJsonReader)
  697. var parseJson = ReflectionInfo.FindParseJson(type);
  698. if (parseJson != null)
  699. {
  700. if (parseJson.GetParameters()[0].ParameterType == typeof(IJsonReader))
  701. {
  702. return (r, t) => parseJson.Invoke(null, new Object[] { r });
  703. }
  704. else
  705. {
  706. return (r, t) =>
  707. {
  708. if (r.GetLiteralKind() == LiteralKind.String)
  709. {
  710. var o = parseJson.Invoke(null, new Object[] { r.GetLiteralString() });
  711. r.NextToken();
  712. return o;
  713. }
  714. throw new InvalidDataException(string.Format("Expected string literal for type {0}", type.FullName));
  715. };
  716. }
  717. }
  718. return (r, t) =>
  719. {
  720. var into = DecoratingActivator.CreateInstance(type);
  721. r.ParseInto(into);
  722. return into;
  723. };
  724. }
  725. public JsonLineOffset CurrentTokenPosition
  726. {
  727. get { return _tokenizer.CurrentTokenPosition; }
  728. }
  729. // ReadLiteral is implemented with a converter callback so that any
  730. // errors on converting to the target type are thrown before the tokenizer
  731. // is advanced to the next token. This ensures error location is reported
  732. // at the start of the literal, not the following token.
  733. public object ReadLiteral(Func<object, object> converter)
  734. {
  735. _tokenizer.Check(Token.Literal);
  736. var retv = converter(_tokenizer.LiteralValue);
  737. _tokenizer.NextToken();
  738. return retv;
  739. }
  740. public void CheckEOF()
  741. {
  742. _tokenizer.Check(Token.EOF);
  743. }
  744. public object Parse(Type type)
  745. {
  746. // Null?
  747. if (_tokenizer.CurrentToken == Token.Literal && _tokenizer.LiteralKind == LiteralKind.Null)
  748. {
  749. _tokenizer.NextToken();
  750. return null;
  751. }
  752. // Handle nullable types
  753. var typeUnderlying = Nullable.GetUnderlyingType(type);
  754. if (typeUnderlying != null)
  755. type = typeUnderlying;
  756. // See if we have a reader
  757. Func<IJsonReader, Type, object> parser;
  758. if (Reader._parsers.TryGetValue(type, out parser))
  759. {
  760. return parser(this, type);
  761. }
  762. // See if we have factory
  763. Func<IJsonReader, string, object> factory;
  764. if (Reader._typeFactories.TryGetValue(type, out factory))
  765. {
  766. // Try first without passing dictionary keys
  767. object into = factory(this, null);
  768. if (into == null)
  769. {
  770. // This is a awkward situation. The factory requires a value from the dictionary
  771. // in order to create the target object (typically an abstract class with the class
  772. // kind recorded in the Json). Since there's no guarantee of order in a json dictionary
  773. // we can't assume the required key is first.
  774. // So, create a bookmark on the tokenizer, read keys until the factory returns an
  775. // object instance and then rewind the tokenizer and continue
  776. // Create a bookmark so we can rewind
  777. _tokenizer.CreateBookmark();
  778. // Skip the opening brace
  779. _tokenizer.Skip(Token.OpenBrace);
  780. // First pass to work out type
  781. ParseDictionaryKeys(key =>
  782. {
  783. // Try to instantiate the object
  784. into = factory(this, key);
  785. return into == null;
  786. });
  787. // Move back to start of the dictionary
  788. _tokenizer.RewindToBookmark();
  789. // Quit if still didn't get an object from the factory
  790. if (into == null)
  791. throw new InvalidOperationException("Factory didn't create object instance (probably due to a missing key in the Json)");
  792. }
  793. // Second pass
  794. ParseInto(into);
  795. // Done
  796. return into;
  797. }
  798. // Do we already have an into parser?
  799. Action<IJsonReader, object> intoParser;
  800. if (Reader._intoParsers.TryGetValue(type, out intoParser))
  801. {
  802. var into = DecoratingActivator.CreateInstance(type);
  803. ParseInto(into);
  804. return into;
  805. }
  806. // Enumerated type?
  807. if (type.IsEnum)
  808. {
  809. if (type.GetCustomAttributes(typeof(FlagsAttribute), false).Any())
  810. return ReadLiteral(literal => {
  811. try
  812. {
  813. return Enum.Parse(type, (string)literal);
  814. }
  815. catch
  816. {
  817. return Enum.ToObject(type, literal);
  818. }
  819. });
  820. else
  821. return ReadLiteral(literal => {
  822. try
  823. {
  824. return Enum.Parse(type, (string)literal);
  825. }
  826. catch (Exception)
  827. {
  828. var attr = type.GetCustomAttributes(typeof(JsonUnknownAttribute), false).FirstOrDefault();
  829. if (attr==null)
  830. throw;
  831. return ((JsonUnknownAttribute)attr).UnknownValue;
  832. }
  833. });
  834. }
  835. // Array?
  836. if (type.IsArray && type.GetArrayRank() == 1)
  837. {
  838. // First parse as a List<>
  839. var listType = typeof(List<>).MakeGenericType(type.GetElementType());
  840. var list = DecoratingActivator.CreateInstance(listType);
  841. ParseInto(list);
  842. return listType.GetMethod("ToArray").Invoke(list, null);
  843. }
  844. // Convert interfaces to concrete types
  845. if (type.IsInterface)
  846. type = Utils.ResolveInterfaceToClass(type);
  847. // Untyped dictionary?
  848. if (_tokenizer.CurrentToken == Token.OpenBrace && (type.IsAssignableFrom(typeof(IDictionary<string, object>))))
  849. {
  850. #if !PETAJSON_NO_DYNAMIC
  851. var container = (new ExpandoObject()) as IDictionary<string, object>;
  852. #else
  853. var container = new Dictionary<string, object>();
  854. #endif
  855. ParseDictionary(key =>
  856. {
  857. container[key] = Parse(typeof(Object));
  858. });
  859. return container;
  860. }
  861. // Untyped list?
  862. if (_tokenizer.CurrentToken == Token.OpenSquare && (type.IsAssignableFrom(typeof(List<object>))))
  863. {
  864. var container = new List<object>();
  865. ParseArray(() =>
  866. {
  867. container.Add(Parse(typeof(Object)));
  868. });
  869. return container;
  870. }
  871. // Untyped literal?
  872. if (_tokenizer.CurrentToken == Token.Literal && type.IsAssignableFrom(_tokenizer.LiteralType))
  873. {
  874. var lit = _tokenizer.LiteralValue;
  875. _tokenizer.NextToken();
  876. return lit;
  877. }
  878. // Call value type resolver
  879. if (type.IsValueType)
  880. {
  881. var tp = _parsers.Get(type, () => _parserResolver(type));
  882. if (tp != null)
  883. {
  884. return tp(this, type);
  885. }
  886. }
  887. // Call reference type resolver
  888. if (type.IsClass && type != typeof(object))
  889. {
  890. var into = DecoratingActivator.CreateInstance(type);
  891. ParseInto(into);
  892. return into;
  893. }
  894. // Give up
  895. throw new InvalidDataException(string.Format("syntax error, unexpected token {0}", _tokenizer.CurrentToken));
  896. }
  897. // Parse into an existing object instance
  898. public void ParseInto(object into)
  899. {
  900. if (into == null)
  901. return;
  902. if (_tokenizer.CurrentToken == Token.Literal && _tokenizer.LiteralKind == LiteralKind.Null)
  903. {
  904. throw new InvalidOperationException("can't parse null into existing instance");
  905. //return;
  906. }
  907. var type = into.GetType();
  908. // Existing parse into handler?
  909. Action<IJsonReader,object> parseInto;
  910. if (_intoParsers.TryGetValue(type, out parseInto))
  911. {
  912. parseInto(this, into);
  913. return;
  914. }
  915. // Generic dictionary?
  916. var dictType = Utils.FindGenericInterface(type, typeof(IDictionary<,>));
  917. if (dictType!=null)
  918. {
  919. // Get the key and value types
  920. var typeKey = dictType.GetGenericArguments()[0];
  921. var typeValue = dictType.GetGenericArguments()[1];
  922. // Parse it
  923. IDictionary dict = (IDictionary)into;
  924. dict.Clear();
  925. ParseDictionary(key =>
  926. {
  927. dict.Add(Convert.ChangeType(key, typeKey), Parse(typeValue));
  928. });
  929. return;
  930. }
  931. // Generic list
  932. var listType = Utils.FindGenericInterface(type, typeof(IList<>));
  933. if (listType!=null)
  934. {
  935. // Get element type
  936. var typeElement = listType.GetGenericArguments()[0];
  937. // Parse it
  938. IList list = (IList)into;
  939. list.Clear();
  940. ParseArray(() =>
  941. {
  942. list.Add(Parse(typeElement));
  943. });
  944. return;
  945. }
  946. // Untyped dictionary
  947. var objDict = into as IDictionary;
  948. if (objDict != null)
  949. {
  950. objDict.Clear();
  951. ParseDictionary(key =>
  952. {
  953. objDict[key] = Parse(typeof(Object));
  954. });
  955. return;
  956. }
  957. // Untyped list
  958. var objList = into as IList;
  959. if (objList!=null)
  960. {
  961. objList.Clear();
  962. ParseArray(() =>
  963. {
  964. objList.Add(Parse(typeof(Object)));
  965. });
  966. return;
  967. }
  968. // Try to resolve a parser
  969. var intoParser = _intoParsers.Get(type, () => _intoParserResolver(type));
  970. if (intoParser != null)
  971. {
  972. intoParser(this, into);
  973. return;
  974. }
  975. throw new InvalidOperationException(string.Format("Don't know how to parse into type '{0}'", type.FullName));
  976. }
  977. public T Parse<T>()
  978. {
  979. return (T)Parse(typeof(T));
  980. }
  981. public LiteralKind GetLiteralKind()
  982. {
  983. return _tokenizer.LiteralKind;
  984. }
  985. public string GetLiteralString()
  986. {
  987. return _tokenizer.String;
  988. }
  989. public void NextToken()
  990. {
  991. _tokenizer.NextToken();
  992. }
  993. // Parse a dictionary
  994. public void ParseDictionary(Action<string> callback)
  995. {
  996. _tokenizer.Skip(Token.OpenBrace);
  997. ParseDictionaryKeys(key => { callback(key); return true; });
  998. _tokenizer.Skip(Token.CloseBrace);
  999. }
  1000. // Parse dictionary keys, calling callback for each one. Continues until end of input
  1001. // or when callback returns false
  1002. private void ParseDictionaryKeys(Func<string, bool> callback)
  1003. {
  1004. // End?
  1005. while (_tokenizer.CurrentToken != Token.CloseBrace)
  1006. {
  1007. // Parse the key
  1008. string key = null;
  1009. if (_tokenizer.CurrentToken == Token.Identifier && (_options & JsonOptions.StrictParser)==0)
  1010. {
  1011. key = _tokenizer.String;
  1012. }
  1013. else if (_tokenizer.CurrentToken == Token.Literal && _tokenizer.LiteralKind == LiteralKind.String)
  1014. {
  1015. key = (string)_tokenizer.LiteralValue;
  1016. }
  1017. else
  1018. {
  1019. throw new InvalidDataException("syntax error, expected string literal or identifier");
  1020. }
  1021. _tokenizer.NextToken();
  1022. _tokenizer.Skip(Token.Colon);
  1023. // Remember current position
  1024. var pos = _tokenizer.CurrentTokenPosition;
  1025. // Call the callback, quit if cancelled
  1026. _contextStack.Add(key);
  1027. bool doDefaultProcessing = callback(key);
  1028. _contextStack.RemoveAt(_contextStack.Count-1);
  1029. if (!doDefaultProcessing)
  1030. return;
  1031. // If the callback didn't read anything from the tokenizer, then skip it ourself
  1032. if (pos.Line == _tokenizer.CurrentTokenPosition.Line && pos.Offset == _tokenizer.CurrentTokenPosition.Offset)
  1033. {
  1034. Parse(typeof(object));
  1035. }
  1036. // Separating/trailing comma
  1037. if (_tokenizer.SkipIf(Token.Comma))
  1038. {
  1039. if ((_options & JsonOptions.StrictParser) != 0 && _tokenizer.CurrentToken == Token.CloseBrace)
  1040. {
  1041. throw new InvalidDataException("Trailing commas not allowed in strict mode");
  1042. }
  1043. continue;
  1044. }
  1045. // End
  1046. break;
  1047. }
  1048. }
  1049. // Parse an array
  1050. public void ParseArray(Action callback)
  1051. {
  1052. _tokenizer.Skip(Token.OpenSquare);
  1053. int index = 0;
  1054. while (_tokenizer.CurrentToken != Token.CloseSquare)
  1055. {
  1056. _contextStack.Add(string.Format("[{0}]", index));
  1057. callback();
  1058. _contextStack.RemoveAt(_contextStack.Count-1);
  1059. if (_tokenizer.SkipIf(Token.Comma))
  1060. {
  1061. if ((_options & JsonOptions.StrictParser)!=0 && _tokenizer.CurrentToken==Token.CloseSquare)
  1062. {
  1063. throw new InvalidDataException("Trailing commas not allowed in strict mode");
  1064. }
  1065. continue;
  1066. }
  1067. break;
  1068. }
  1069. _tokenizer.Skip(Token.CloseSquare);
  1070. }
  1071. // Yikes!
  1072. public static Func<Type, Action<IJsonReader, object>> _intoParserResolver;
  1073. public static Func<Type, Func<IJsonReader, Type, object>> _parserResolver;
  1074. public static ThreadSafeCache<Type, Func<IJsonReader, Type, object>> _parsers = new ThreadSafeCache<Type, Func<IJsonReader, Type, object>>();
  1075. public static ThreadSafeCache<Type, Action<IJsonReader, object>> _intoParsers = new ThreadSafeCache<Type, Action<IJsonReader, object>>();
  1076. public static ThreadSafeCache<Type, Func<IJsonReader, string, object>> _typeFactories = new ThreadSafeCache<Type, Func<IJsonReader, string, object>>();
  1077. }
  1078. public class Writer : IJsonWriter
  1079. {
  1080. static Writer()
  1081. {
  1082. _formatterResolver = ResolveFormatter;
  1083. // Register standard formatters
  1084. _formatters.Add(typeof(string), (w, o) => w.WriteStringLiteral((string)o));
  1085. _formatters.Add(typeof(char), (w, o) => w.WriteStringLiteral(((char)o).ToString()));
  1086. _formatters.Add(typeof(bool), (w, o) => w.WriteRaw(((bool)o) ? "true" : "false"));
  1087. Action<IJsonWriter, object> convertWriter = (w, o) => w.WriteRaw((string)Convert.ChangeType(o, typeof(string), System.Globalization.CultureInfo.InvariantCulture));
  1088. _formatters.Add(typeof(int), convertWriter);
  1089. _formatters.Add(typeof(uint), convertWriter);
  1090. _formatters.Add(typeof(long), convertWriter);
  1091. _formatters.Add(typeof(ulong), convertWriter);
  1092. _formatters.Add(typeof(short), convertWriter);
  1093. _formatters.Add(typeof(ushort), convertWriter);
  1094. _formatters.Add(typeof(decimal), convertWriter);
  1095. _formatters.Add(typeof(byte), convertWriter);
  1096. _formatters.Add(typeof(sbyte), convertWriter);
  1097. _formatters.Add(typeof(DateTime), (w, o) => convertWriter(w, Utils.ToUnixMilliseconds((DateTime)o)));
  1098. _formatters.Add(typeof(float), (w, o) => w.WriteRaw(((float)o).ToString("R", System.Globalization.CultureInfo.InvariantCulture)));
  1099. _formatters.Add(typeof(double), (w, o) => w.WriteRaw(((double)o).ToString("R", System.Globalization.CultureInfo.InvariantCulture)));
  1100. _formatters.Add(typeof(byte[]), (w, o) =>
  1101. {
  1102. w.WriteRaw("\"");
  1103. w.WriteRaw(Convert.ToBase64String((byte[])o));
  1104. w.WriteRaw("\"");
  1105. });
  1106. }
  1107. public static Func<Type, Action<IJsonWriter, object>> _formatterResolver;
  1108. public static Dictionary<Type, Action<IJsonWriter, object>> _formatters = new Dictionary<Type, Action<IJsonWriter, object>>();
  1109. static Action<IJsonWriter, object> ResolveFormatter(Type type)
  1110. {
  1111. // Try `void FormatJson(IJsonWriter)`
  1112. var formatJson = ReflectionInfo.FindFormatJson(type);
  1113. if (formatJson != null)
  1114. {
  1115. if (formatJson.ReturnType==typeof(void))
  1116. return (w, obj) => formatJson.Invoke(obj, new Object[] { w });
  1117. if (formatJson.ReturnType == typeof(string))
  1118. return (w, obj) => w.WriteStringLiteral((string)formatJson.Invoke(obj, new Object[] { }));
  1119. }
  1120. var ri = ReflectionInfo.GetReflectionInfo(type);
  1121. if (ri != null)
  1122. return ri.Write;
  1123. else
  1124. return null;
  1125. }
  1126. public Writer(TextWriter w, JsonOptions options)
  1127. {
  1128. _writer = w;
  1129. _atStartOfLine = true;
  1130. _needElementSeparator = false;
  1131. _options = options;
  1132. }
  1133. private TextWriter _writer;
  1134. private int IndentLevel;
  1135. private bool _atStartOfLine;
  1136. private bool _needElementSeparator = false;
  1137. private JsonOptions _options;
  1138. private char _currentBlockKind = '\0';
  1139. // Move to the next line
  1140. public void NextLine()
  1141. {
  1142. if (_atStartOfLine)
  1143. return;
  1144. if ((_options & JsonOptions.WriteWhitespace)!=0)
  1145. {
  1146. WriteRaw("\n");
  1147. WriteRaw(new string('\t', IndentLevel));
  1148. }
  1149. _atStartOfLine = true;
  1150. }
  1151. // Start the next element, writing separators and white space
  1152. void NextElement()
  1153. {
  1154. if (_needElementSeparator)
  1155. {
  1156. WriteRaw(",");
  1157. NextLine();
  1158. }
  1159. else
  1160. {
  1161. NextLine();
  1162. IndentLevel++;
  1163. WriteRaw(_currentBlockKind.ToString());
  1164. NextLine();
  1165. }
  1166. _needElementSeparator = true;
  1167. }
  1168. // Write next array element
  1169. public void WriteElement()
  1170. {
  1171. if (_currentBlockKind != '[')
  1172. throw new InvalidOperationException("Attempt to write array element when not in array block");
  1173. NextElement();
  1174. }
  1175. // Write next dictionary key
  1176. public void WriteKey(string key)
  1177. {
  1178. if (_currentBlockKind != '{')
  1179. throw new InvalidOperationException("Attempt to write dictionary element when not in dictionary block");
  1180. NextElement();
  1181. WriteStringLiteral(key);
  1182. WriteRaw(((_options & JsonOptions.WriteWhitespace) != 0) ? ": " : ":");
  1183. }
  1184. // Write an already escaped dictionary key
  1185. public void WriteKeyNoEscaping(string key)
  1186. {
  1187. if (_currentBlockKind != '{')
  1188. throw new InvalidOperationException("Attempt to write dictionary element when not in dictionary block");
  1189. NextElement();
  1190. WriteRaw("\"");
  1191. WriteRaw(key);
  1192. WriteRaw("\"");
  1193. WriteRaw(((_options & JsonOptions.WriteWhitespace) != 0) ? ": " : ":");
  1194. }
  1195. // Write anything
  1196. public void WriteRaw(string str)
  1197. {
  1198. _atStartOfLine = false;
  1199. _writer.Write(str);
  1200. }
  1201. static int IndexOfEscapeableChar(string str, int pos)
  1202. {
  1203. int length = str.Length;
  1204. while (pos < length)
  1205. {
  1206. var ch = str[pos];
  1207. if (ch == '\\' || ch == '/' || ch == '\"' || (ch>=0 && ch <= 0x1f) || (ch >= 0x7f && ch <=0x9f) || ch==0x2028 || ch== 0x2029)
  1208. return pos;
  1209. pos++;
  1210. }
  1211. return -1;
  1212. }
  1213. public void WriteStringLiteral(string str)
  1214. {
  1215. _atStartOfLine = false;
  1216. if (str == null)
  1217. {
  1218. _writer.Write("null");
  1219. return;
  1220. }
  1221. _writer.Write("\"");
  1222. int pos = 0;
  1223. int escapePos;
  1224. while ((escapePos = IndexOfEscapeableChar(str, pos)) >= 0)
  1225. {
  1226. if (escapePos > pos)
  1227. _writer.Write(str.Substring(pos, escapePos - pos));
  1228. switch (str[escapePos])
  1229. {
  1230. case '\"': _writer.Write("\\\""); break;
  1231. case '\\': _writer.Write("\\\\"); break;
  1232. case '/': _writer.Write("\\/"); break;
  1233. case '\b': _writer.Write("\\b"); break;
  1234. case '\f': _writer.Write("\\f"); break;
  1235. case '\n': _writer.Write("\\n"); break;
  1236. case '\r': _writer.Write("\\r"); break;
  1237. case '\t': _writer.Write("\\t"); break;
  1238. default:
  1239. _writer.Write(string.Format("\\u{0:x4}", (int)str[escapePos]));
  1240. break;
  1241. }
  1242. pos = escapePos + 1;
  1243. }
  1244. if (str.Length > pos)
  1245. _writer.Write(str.Substring(pos));
  1246. _writer.Write("\"");
  1247. }
  1248. // Write an array or dictionary block
  1249. private void WriteBlock(string open, string close, Action callback)
  1250. {
  1251. var prevBlockKind = _currentBlockKind;
  1252. _currentBlockKind = open[0];
  1253. var didNeedElementSeparator = _needElementSeparator;
  1254. _needElementSeparator = false;
  1255. callback();
  1256. if (_needElementSeparator)
  1257. {
  1258. IndentLevel--;
  1259. NextLine();
  1260. }
  1261. else
  1262. {
  1263. WriteRaw(open);
  1264. }
  1265. WriteRaw(close);
  1266. _needElementSeparator = didNeedElementSeparator;
  1267. _currentBlockKind = prevBlockKind;
  1268. }
  1269. // Write an array
  1270. public void WriteArray(Action callback)
  1271. {
  1272. WriteBlock("[", "]", callback);
  1273. }
  1274. // Write a dictionary
  1275. public void WriteDictionary(Action callback)
  1276. {
  1277. WriteBlock("{", "}", callback);
  1278. }
  1279. // Write any value
  1280. public void WriteValue(object value)
  1281. {
  1282. _atStartOfLine = false;
  1283. // Special handling for null
  1284. if (value == null)
  1285. {
  1286. _writer.Write("null");
  1287. return;
  1288. }
  1289. var type = value.GetType();
  1290. // Handle nullable types
  1291. var typeUnderlying = Nullable.GetUnderlyingType(type);
  1292. if (typeUnderlying != null)
  1293. type = typeUnderlying;
  1294. // Look up type writer
  1295. Action<IJsonWriter, object> typeWriter;
  1296. if (_formatters.TryGetValue(type, out typeWriter))
  1297. {
  1298. // Write it
  1299. typeWriter(this, value);
  1300. return;
  1301. }
  1302. // Enumerated type?
  1303. if (type.IsEnum)
  1304. {
  1305. if (type.GetCustomAttributes(typeof(FlagsAttribute), false).Any())
  1306. WriteRaw(Convert.ToUInt32(value).ToString(CultureInfo.InvariantCulture));
  1307. else
  1308. WriteStringLiteral(value.ToString());
  1309. return;
  1310. }
  1311. // Dictionary?
  1312. var d = value as System.Collections.IDictionary;
  1313. if (d != null)
  1314. {
  1315. WriteDictionary(() =>
  1316. {
  1317. foreach (var key in d.Keys)
  1318. {
  1319. WriteKey(key.ToString());
  1320. WriteValue(d[key]);
  1321. }
  1322. });
  1323. return;
  1324. }
  1325. // Dictionary?
  1326. var dso = value as IDictionary<string,object>;
  1327. if (dso != null)
  1328. {
  1329. WriteDictionary(() =>
  1330. {
  1331. foreach (var key in dso.Keys)
  1332. {
  1333. WriteKey(key.ToString());
  1334. WriteValue(dso[key]);
  1335. }
  1336. });
  1337. return;
  1338. }
  1339. // Array?
  1340. var e = value as System.Collections.IEnumerable;
  1341. if (e != null)
  1342. {
  1343. WriteArray(() =>
  1344. {
  1345. foreach (var i in e)
  1346. {
  1347. WriteElement();
  1348. WriteValue(i);
  1349. }
  1350. });
  1351. return;
  1352. }
  1353. // Resolve a formatter
  1354. var formatter = _formatterResolver(type);
  1355. if (formatter != null)
  1356. {
  1357. _formatters[type] = formatter;
  1358. formatter(this, value);
  1359. return;
  1360. }
  1361. // Give up
  1362. throw new InvalidDataException(string.Format("Don't know how to write '{0}' to json", value.GetType()));
  1363. }
  1364. }
  1365. // Information about a field or property found through reflection
  1366. public class JsonMemberInfo
  1367. {
  1368. // The Json key for this member
  1369. public string JsonKey;
  1370. // True if should keep existing instance (reference types only)
  1371. public bool KeepInstance;
  1372. // True if deprecated
  1373. public bool Deprecated;
  1374. // Reflected member info
  1375. MemberInfo _mi;
  1376. public MemberInfo Member
  1377. {
  1378. get { return _mi; }
  1379. set
  1380. {
  1381. // Store it
  1382. _mi = value;
  1383. // Also create getters and setters
  1384. if (_mi is PropertyInfo)
  1385. {
  1386. GetValue = (obj) => ((PropertyInfo)_mi).GetValue(obj, null);
  1387. SetValue = (obj, val) => ((PropertyInfo)_mi).SetValue(obj, val, null);
  1388. }
  1389. else
  1390. {
  1391. GetValue = ((FieldInfo)_mi).GetValue;
  1392. SetValue = ((FieldInfo)_mi).SetValue;
  1393. }
  1394. }
  1395. }
  1396. // Member type
  1397. public Type MemberType
  1398. {
  1399. get
  1400. {
  1401. if (Member is PropertyInfo)
  1402. {
  1403. return ((PropertyInfo)Member).PropertyType;
  1404. }
  1405. else
  1406. {
  1407. return ((FieldInfo)Member).FieldType;
  1408. }
  1409. }
  1410. }
  1411. // Get/set helpers
  1412. public Action<object, object> SetValue;
  1413. public Func<object, object> GetValue;
  1414. }
  1415. // Stores reflection info about a type
  1416. public class ReflectionInfo
  1417. {
  1418. // List of members to be serialized
  1419. public List<JsonMemberInfo> Members;
  1420. // Cache of these ReflectionInfos's
  1421. static ThreadSafeCache<Type, ReflectionInfo> _cache = new ThreadSafeCache<Type, ReflectionInfo>();
  1422. public static MethodInfo FindFormatJson(Type type)
  1423. {
  1424. if (type.IsValueType)
  1425. {
  1426. // Try `void FormatJson(IJsonWriter)`
  1427. var formatJson = type.GetMethod("FormatJson", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { typeof(IJsonWriter) }, null);
  1428. if (formatJson != null && formatJson.ReturnType == typeof(void))
  1429. return formatJson;
  1430. // Try `string FormatJson()`
  1431. formatJson = type.GetMethod("FormatJson", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { }, null);
  1432. if (formatJson != null && formatJson.ReturnType == typeof(string))
  1433. return formatJson;
  1434. }
  1435. return null;
  1436. }
  1437. public static MethodInfo FindParseJson(Type type)
  1438. {
  1439. // Try `T ParseJson(IJsonReader)`
  1440. var parseJson = type.GetMethod("ParseJson", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { typeof(IJsonReader) }, null);
  1441. if (parseJson != null && parseJson.ReturnType == type)
  1442. return parseJson;
  1443. // Try `T ParseJson(string)`
  1444. parseJson = type.GetMethod("ParseJson", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static, null, new Type[] { typeof(string) }, null);
  1445. if (parseJson != null && parseJson.ReturnType == type)
  1446. return parseJson;
  1447. return null;
  1448. }
  1449. // Write one of these types
  1450. public void Write(IJsonWriter w, object val)
  1451. {
  1452. w.WriteDictionary(() =>
  1453. {
  1454. var writing = val as IJsonWriting;
  1455. if (writing != null)
  1456. writing.OnJsonWriting(w);
  1457. foreach (var jmi in Members.Where(x=>!x.Deprecated))
  1458. {
  1459. w.WriteKeyNoEscaping(jmi.JsonKey);
  1460. w.WriteValue(jmi.GetValue(val));
  1461. }
  1462. var written = val as IJsonWritten;
  1463. if (written != null)
  1464. written.OnJsonWritten(w);
  1465. });
  1466. }
  1467. // Read one of these types.
  1468. // NB: Although PetaJson.JsonParseInto only works on reference type, when using reflection
  1469. // it also works for value types so we use the one method for both
  1470. public void ParseInto(IJsonReader r, object into)
  1471. {
  1472. var loading = into as IJsonLoading;
  1473. if (loading != null)
  1474. loading.OnJsonLoading(r);
  1475. r.ParseDictionary(key =>
  1476. {
  1477. ParseFieldOrProperty(r, into, key);
  1478. });
  1479. var loaded = into as IJsonLoaded;
  1480. if (loaded != null)
  1481. loaded.OnJsonLoaded(r);
  1482. }
  1483. // The member info is stored in a list (as opposed to a dictionary) so that
  1484. // the json is written in the same order as the fields/properties are defined
  1485. // On loading, we assume the fields will be in the same order, but need to
  1486. // handle if they're not. This function performs a linear search, but
  1487. // starts after the last found item as an optimization that should work
  1488. // most of the time.
  1489. int _lastFoundIndex = 0;
  1490. bool FindMemberInfo(string name, out JsonMemberInfo found)
  1491. {
  1492. for (int i = 0; i < Members.Count; i++)
  1493. {
  1494. int index = (i + _lastFoundIndex) % Members.Count;
  1495. var jmi = Members[index];
  1496. if (jmi.JsonKey == name)
  1497. {
  1498. _lastFoundIndex = index;
  1499. found = jmi;
  1500. return true;
  1501. }
  1502. }
  1503. found = null;
  1504. return false;
  1505. }
  1506. // Parse a value from IJsonReader into an object instance
  1507. public void ParseFieldOrProperty(IJsonReader r, object into, string key)
  1508. {
  1509. // IJsonLoadField
  1510. var lf = into as IJsonLoadField;
  1511. if (lf != null && lf.OnJsonField(r, key))
  1512. return;
  1513. // Find member
  1514. JsonMemberInfo jmi;
  1515. if (FindMemberInfo(key, out jmi))
  1516. {
  1517. // Try to keep existing instance
  1518. if (jmi.KeepInstance)
  1519. {
  1520. var subInto = jmi.GetValue(into);
  1521. if (subInto != null)
  1522. {
  1523. r.ParseInto(subInto);
  1524. return;
  1525. }
  1526. }
  1527. // Parse and set
  1528. var val = r.Parse(jmi.MemberType);
  1529. jmi.SetValue(into, val);
  1530. return;
  1531. }
  1532. }
  1533. // Get the reflection info for a specified type
  1534. public static ReflectionInfo GetReflectionInfo(Type type)
  1535. {
  1536. // Check cache
  1537. return _cache.Get(type, () =>
  1538. {
  1539. var allMembers = Utils.GetAllFieldsAndProperties(type);
  1540. // Does type have a [Json] attribute
  1541. bool typeMarked = type.GetCustomAttributes(typeof(JsonAttribute), true).OfType<JsonAttribute>().Any();
  1542. // Do any members have a [Json] attribute
  1543. bool anyFieldsMarked = allMembers.Any(x => x.GetCustomAttributes(typeof(JsonAttribute), false).OfType<JsonAttribute>().Any());
  1544. #if !PETAJSON_NO_DATACONTRACT
  1545. // Try with DataContract and friends
  1546. if (!typeMarked && !anyFieldsMarked && type.GetCustomAttributes(typeof(DataContractAttribute), true).OfType<DataContractAttribute>().Any())
  1547. {
  1548. var ri = CreateReflectionInfo(type, mi =>
  1549. {
  1550. // Get attributes
  1551. var attr = mi.GetCustomAttributes(typeof(DataMemberAttribute), false).OfType<DataMemberAttribute>().FirstOrDefault();
  1552. if (attr != null)
  1553. {
  1554. return new JsonMemberInfo()
  1555. {
  1556. Member = mi,
  1557. JsonKey = attr.Name ?? mi.Name, // No lower case first letter if using DataContract/Member
  1558. };
  1559. }
  1560. return null;
  1561. });
  1562. ri.Members.Sort((a, b) => String.CompareOrdinal(a.JsonKey, b.JsonKey)); // Match DataContractJsonSerializer
  1563. return ri;
  1564. }
  1565. #endif
  1566. {
  1567. // Should we serialize all public methods?
  1568. bool serializeAllPublics = typeMarked || !anyFieldsMarked;
  1569. // Build
  1570. var ri = CreateReflectionInfo(type, mi =>
  1571. {
  1572. // Explicitly excluded?
  1573. if (mi.GetCustomAttributes(typeof(JsonExcludeAttribute), false).Any())
  1574. return null;
  1575. // Get attributes
  1576. var attr = mi.GetCustomAttributes(typeof(JsonAttribute), false).OfType<JsonAttribute>().FirstOrDefault();
  1577. if (attr != null)
  1578. {
  1579. return new JsonMemberInfo()
  1580. {
  1581. Member = mi,
  1582. JsonKey = attr.Key ?? mi.Name.Substring(0, 1).ToLower() + mi.Name.Substring(1),
  1583. KeepInstance = attr.KeepInstance,
  1584. Deprecated = attr.Deprecated,
  1585. };
  1586. }
  1587. // Serialize all publics?
  1588. if (serializeAllPublics && Utils.IsPublic(mi))
  1589. {
  1590. return new JsonMemberInfo()
  1591. {
  1592. Member = mi,
  1593. JsonKey = mi.Name.Substring(0, 1).ToLower() + mi.Name.Substring(1),
  1594. };
  1595. }
  1596. return null;
  1597. });
  1598. return ri;
  1599. }
  1600. });
  1601. }
  1602. public static ReflectionInfo CreateReflectionInfo(Type type, Func<MemberInfo, JsonMemberInfo> callback)
  1603. {
  1604. // Work out properties and fields
  1605. var members = Utils.GetAllFieldsAndProperties(type).Select(x => callback(x)).Where(x => x != null).ToList();
  1606. // Anything with KeepInstance must be a reference type
  1607. var invalid = members.FirstOrDefault(x => x.KeepInstance && x.MemberType.IsValueType);
  1608. if (invalid!=null)
  1609. {
  1610. throw new InvalidOperationException(string.Format("KeepInstance=true can only be applied to reference types ({0}.{1})", type.FullName, invalid.Member));
  1611. }
  1612. // Must have some members
  1613. if (!members.Any())
  1614. return null;
  1615. // Create reflection info
  1616. return new ReflectionInfo() { Members = members };
  1617. }
  1618. }
  1619. public class ThreadSafeCache<TKey, TValue>
  1620. {
  1621. public ThreadSafeCache()
  1622. {
  1623. }
  1624. public TValue Get(TKey key, Func<TValue> createIt)
  1625. {
  1626. // Check if already exists
  1627. _lock.EnterReadLock();
  1628. try
  1629. {
  1630. TValue val;
  1631. if (_map.TryGetValue(key, out val))
  1632. return val;
  1633. }
  1634. finally
  1635. {
  1636. _lock.ExitReadLock();
  1637. }
  1638. // Nope, take lock and try again
  1639. _lock.EnterWriteLock();
  1640. try
  1641. {
  1642. // Check again before creating it
  1643. TValue val;
  1644. if (!_map.TryGetValue(key, out val))
  1645. {
  1646. // Store the new one
  1647. val = createIt();
  1648. _map[key] = val;
  1649. }
  1650. return val;
  1651. }
  1652. finally
  1653. {
  1654. _lock.ExitWriteLock();
  1655. }
  1656. }
  1657. public bool TryGetValue(TKey key, out TValue val)
  1658. {
  1659. _lock.EnterReadLock();
  1660. try
  1661. {
  1662. return _map.TryGetValue(key, out val);
  1663. }
  1664. finally
  1665. {
  1666. _lock.ExitReadLock();
  1667. }
  1668. }
  1669. public void Set(TKey key, TValue value)
  1670. {
  1671. _lock.EnterWriteLock();
  1672. try
  1673. {
  1674. _map[key] = value;
  1675. }
  1676. finally
  1677. {
  1678. _lock.ExitWriteLock();
  1679. }
  1680. }
  1681. Dictionary<TKey, TValue> _map = new Dictionary<TKey,TValue>();
  1682. ReaderWriterLockSlim _lock = new ReaderWriterLockSlim();
  1683. }
  1684. internal static class Utils
  1685. {
  1686. // Get all fields and properties of a type
  1687. public static IEnumerable<MemberInfo> GetAllFieldsAndProperties(Type t)
  1688. {
  1689. if (t == null)
  1690. return Enumerable.Empty<FieldInfo>();
  1691. BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly;
  1692. return t.GetMembers(flags).Where(x => x is FieldInfo || x is PropertyInfo).Concat(GetAllFieldsAndProperties(t.BaseType));
  1693. }
  1694. public static Type FindGenericInterface(Type type, Type tItf)
  1695. {
  1696. foreach (var t in type.GetInterfaces())
  1697. {
  1698. // Is this a generic list?
  1699. if (t.IsGenericType && t.GetGenericTypeDefinition() == tItf)
  1700. return t;
  1701. }
  1702. return null;
  1703. }
  1704. public static bool IsPublic(MemberInfo mi)
  1705. {
  1706. // Public field
  1707. var fi = mi as FieldInfo;
  1708. if (fi != null)
  1709. return fi.IsPublic;
  1710. // Public property
  1711. // (We only check the get method so we can work with anonymous types)
  1712. var pi = mi as PropertyInfo;
  1713. if (pi != null)
  1714. {
  1715. var gm = pi.GetGetMethod(true);
  1716. return (gm != null && gm.IsPublic);
  1717. }
  1718. return false;
  1719. }
  1720. public static Type ResolveInterfaceToClass(Type tItf)
  1721. {
  1722. // Generic type
  1723. if (tItf.IsGenericType)
  1724. {
  1725. var genDef = tItf.GetGenericTypeDefinition();
  1726. // IList<> -> List<>
  1727. if (genDef == typeof(IList<>))
  1728. {
  1729. return typeof(List<>).MakeGenericType(tItf.GetGenericArguments());
  1730. }
  1731. // IDictionary<string,> -> Dictionary<string,>
  1732. if (genDef == typeof(IDictionary<,>) && tItf.GetGenericArguments()[0] == typeof(string))
  1733. {
  1734. return typeof(Dictionary<,>).MakeGenericType(tItf.GetGenericArguments());
  1735. }
  1736. }
  1737. // IEnumerable -> List<object>
  1738. if (tItf == typeof(IEnumerable))
  1739. return typeof(List<object>);
  1740. // IDicitonary -> Dictionary<string,object>
  1741. if (tItf == typeof(IDictionary))
  1742. return typeof(Dictionary<string, object>);
  1743. return tItf;
  1744. }
  1745. public static long ToUnixMilliseconds(DateTime This)
  1746. {
  1747. return (long)This.Subtract(new DateTime(1970, 1, 1)).TotalMilliseconds;
  1748. }
  1749. public static DateTime FromUnixMilliseconds(long timeStamp)
  1750. {
  1751. return new DateTime(1970, 1, 1).AddMilliseconds(timeStamp);
  1752. }
  1753. }
  1754. public class Tokenizer
  1755. {
  1756. public Tokenizer(TextReader r, JsonOptions options)
  1757. {
  1758. _underlying = r;
  1759. _options = options;
  1760. FillBuffer();
  1761. NextChar();
  1762. NextToken();
  1763. }
  1764. private JsonOptions _options;
  1765. private StringBuilder _sb = new StringBuilder();
  1766. private TextReader _underlying;
  1767. private char[] _buf = new char[4096];
  1768. private int _pos;
  1769. private int _bufUsed;
  1770. private StringBuilder _rewindBuffer;
  1771. private int _rewindBufferPos;
  1772. private JsonLineOffset _currentCharPos;
  1773. private char _currentChar;
  1774. private Stack<ReaderState> _bookmarks = new Stack<ReaderState>();
  1775. public JsonLineOffset CurrentTokenPosition;
  1776. public Token CurrentToken;
  1777. public LiteralKind LiteralKind;
  1778. public string String;
  1779. public object LiteralValue
  1780. {
  1781. get
  1782. {
  1783. if (CurrentToken != Token.Literal)
  1784. throw new InvalidOperationException("token is not a literal");
  1785. switch (LiteralKind)
  1786. {
  1787. case LiteralKind.Null: return null;
  1788. case LiteralKind.False: return false;
  1789. case LiteralKind.True: return true;
  1790. case LiteralKind.String: return String;
  1791. case LiteralKind.SignedInteger: return long.Parse(String, CultureInfo.InvariantCulture);
  1792. case LiteralKind.UnsignedInteger: return ulong.Parse(String, CultureInfo.InvariantCulture);
  1793. case LiteralKind.FloatingPoint: return double.Parse(String, CultureInfo.InvariantCulture);
  1794. }
  1795. return null;
  1796. }
  1797. }
  1798. public Type LiteralType
  1799. {
  1800. get
  1801. {
  1802. if (CurrentToken != Token.Literal)
  1803. throw new InvalidOperationException("token is not a literal");
  1804. switch (LiteralKind)
  1805. {
  1806. case LiteralKind.Null: return typeof(Object);
  1807. case LiteralKind.False: return typeof(Boolean);
  1808. case LiteralKind.True: return typeof(Boolean);
  1809. case LiteralKind.String: return typeof(string);
  1810. case LiteralKind.SignedInteger: return typeof(long);
  1811. case LiteralKind.UnsignedInteger: return typeof(ulong);
  1812. case LiteralKind.FloatingPoint: return typeof(double);
  1813. }
  1814. return null;
  1815. }
  1816. }
  1817. // This object represents the entire state of the reader and is used for rewind
  1818. struct ReaderState
  1819. {
  1820. public ReaderState(Tokenizer tokenizer)
  1821. {
  1822. _currentCharPos = tokenizer._currentCharPos;
  1823. _currentChar = tokenizer._currentChar;
  1824. _string = tokenizer.String;
  1825. _literalKind = tokenizer.LiteralKind;
  1826. _rewindBufferPos = tokenizer._rewindBufferPos;
  1827. _currentTokenPos = tokenizer.CurrentTokenPosition;
  1828. _currentToken = tokenizer.CurrentToken;
  1829. }
  1830. public void Apply(Tokenizer tokenizer)
  1831. {
  1832. tokenizer._currentCharPos = _currentCharPos;
  1833. tokenizer._currentChar = _currentChar;
  1834. tokenizer._rewindBufferPos = _rewindBufferPos;
  1835. tokenizer.CurrentToken = _currentToken;
  1836. tokenizer.CurrentTokenPosition = _currentTokenPos;
  1837. tokenizer.String = _string;
  1838. tokenizer.LiteralKind = _literalKind;
  1839. }
  1840. private JsonLineOffset _currentCharPos;
  1841. private JsonLineOffset _currentTokenPos;
  1842. private char _currentChar;
  1843. private Token _currentToken;
  1844. private LiteralKind _literalKind;
  1845. private string _string;
  1846. private int _rewindBufferPos;
  1847. }
  1848. // Create a rewind bookmark
  1849. public void CreateBookmark()
  1850. {
  1851. _bookmarks.Push(new ReaderState(this));
  1852. if (_rewindBuffer == null)
  1853. {
  1854. _rewindBuffer = new StringBuilder();
  1855. _rewindBufferPos = 0;
  1856. }
  1857. }
  1858. // Discard bookmark
  1859. public void DiscardBookmark()
  1860. {
  1861. _bookmarks.Pop();
  1862. if (_bookmarks.Count == 0)
  1863. {
  1864. _rewindBuffer = null;
  1865. _rewindBufferPos = 0;
  1866. }
  1867. }
  1868. // Rewind to a bookmark
  1869. public void RewindToBookmark()
  1870. {
  1871. _bookmarks.Pop().Apply(this);
  1872. }
  1873. // Fill buffer by reading from underlying TextReader
  1874. void FillBuffer()
  1875. {
  1876. _bufUsed = _underlying.Read(_buf, 0, _buf.Length);
  1877. _pos = 0;
  1878. }
  1879. // Get the next character from the input stream
  1880. // (this function could be extracted into a few different methods, but is mostly inlined
  1881. // for performance - yes it makes a difference)
  1882. public char NextChar()
  1883. {
  1884. if (_rewindBuffer == null)
  1885. {
  1886. if (_pos >= _bufUsed)
  1887. {
  1888. if (_bufUsed > 0)
  1889. {
  1890. FillBuffer();
  1891. }
  1892. if (_bufUsed == 0)
  1893. {
  1894. return _currentChar = '\0';
  1895. }
  1896. }
  1897. // Next
  1898. _currentCharPos.Offset++;
  1899. return _currentChar = _buf[_pos++];
  1900. }
  1901. if (_rewindBufferPos < _rewindBuffer.Length)
  1902. {
  1903. _currentCharPos.Offset++;
  1904. return _currentChar = _rewindBuffer[_rewindBufferPos++];
  1905. }
  1906. else
  1907. {
  1908. if (_pos >= _bufUsed && _bufUsed > 0)
  1909. FillBuffer();
  1910. _currentChar = _bufUsed == 0 ? '\0' : _buf[_pos++];
  1911. _rewindBuffer.Append(_currentChar);
  1912. _rewindBufferPos++;
  1913. _currentCharPos.Offset++;
  1914. return _currentChar;
  1915. }
  1916. }
  1917. // Read the next token from the input stream
  1918. // (Mostly inline for performance)
  1919. public void NextToken()
  1920. {
  1921. while (true)
  1922. {
  1923. // Skip whitespace and handle line numbers
  1924. while (true)
  1925. {
  1926. if (_currentChar == '\r')
  1927. {
  1928. if (NextChar() == '\n')
  1929. {
  1930. NextChar();
  1931. }
  1932. _currentCharPos.Line++;
  1933. _currentCharPos.Offset = 0;
  1934. }
  1935. else if (_currentChar == '\n')
  1936. {
  1937. if (NextChar() == '\r')
  1938. {
  1939. NextChar();
  1940. }
  1941. _currentCharPos.Line++;
  1942. _currentCharPos.Offset = 0;
  1943. }
  1944. else if (_currentChar == ' ')
  1945. {
  1946. NextChar();
  1947. }
  1948. else if (_currentChar == '\t')
  1949. {
  1950. NextChar();
  1951. }
  1952. else
  1953. break;
  1954. }
  1955. // Remember position of token
  1956. CurrentTokenPosition = _currentCharPos;
  1957. // Handle common characters first
  1958. switch (_currentChar)
  1959. {
  1960. case '/':
  1961. // Comments not support in strict mode
  1962. if ((_options & JsonOptions.StrictParser) != 0)
  1963. {
  1964. throw new InvalidDataException(string.Format("syntax error, unexpected character '{0}'", _currentChar));
  1965. }
  1966. // Process comment
  1967. NextChar();
  1968. switch (_currentChar)
  1969. {
  1970. case '/':
  1971. NextChar();
  1972. while (_currentChar!='\0' && _currentChar != '\r' && _currentChar != '\n')
  1973. {
  1974. NextChar();
  1975. }
  1976. break;
  1977. case '*':
  1978. bool endFound = false;
  1979. while (!endFound && _currentChar!='\0')
  1980. {
  1981. if (_currentChar == '*')
  1982. {
  1983. NextChar();
  1984. if (_currentChar == '/')
  1985. {
  1986. endFound = true;
  1987. }
  1988. }
  1989. NextChar();
  1990. }
  1991. break;
  1992. default:
  1993. throw new InvalidDataException("syntax error, unexpected character after slash");
  1994. }
  1995. continue;
  1996. case '\"':
  1997. case '\'':
  1998. {
  1999. _sb.Length = 0;
  2000. var quoteKind = _currentChar;
  2001. NextChar();
  2002. while (_currentChar!='\0')
  2003. {
  2004. if (_currentChar == '\\')
  2005. {
  2006. NextChar();
  2007. var escape = _currentChar;
  2008. switch (escape)
  2009. {
  2010. case '\"': _sb.Append('\"'); break;
  2011. case '\\': _sb.Append('\\'); break;
  2012. case '/': _sb.Append('/'); break;
  2013. case 'b': _sb.Append('\b'); break;
  2014. case 'f': _sb.Append('\f'); break;
  2015. case 'n': _sb.Append('\n'); break;
  2016. case 'r': _sb.Append('\r'); break;
  2017. case 't': _sb.Append('\t'); break;
  2018. case 'u':
  2019. var sbHex = new StringBuilder();
  2020. for (int i = 0; i < 4; i++)
  2021. {
  2022. NextChar();
  2023. sbHex.Append(_currentChar);
  2024. }
  2025. _sb.Append((char)Convert.ToUInt16(sbHex.ToString(), 16));
  2026. break;
  2027. default:
  2028. throw new InvalidDataException(string.Format("Invalid escape sequence in string literal: '\\{0}'", _currentChar));
  2029. }
  2030. }
  2031. else if (_currentChar == quoteKind)
  2032. {
  2033. String = _sb.ToString();
  2034. CurrentToken = Token.Literal;
  2035. LiteralKind = LiteralKind.String;
  2036. NextChar();
  2037. return;
  2038. }
  2039. else
  2040. {
  2041. _sb.Append(_currentChar);
  2042. }
  2043. NextChar();
  2044. }
  2045. throw new InvalidDataException("syntax error, unterminated string literal");
  2046. }
  2047. case '{': CurrentToken = Token.OpenBrace; NextChar(); return;
  2048. case '}': CurrentToken = Token.CloseBrace; NextChar(); return;
  2049. case '[': CurrentToken = Token.OpenSquare; NextChar(); return;
  2050. case ']': CurrentToken = Token.CloseSquare; NextChar(); return;
  2051. case '=': CurrentToken = Token.Equal; NextChar(); return;
  2052. case ':': CurrentToken = Token.Colon; NextChar(); return;
  2053. case ';': CurrentToken = Token.SemiColon; NextChar(); return;
  2054. case ',': CurrentToken = Token.Comma; NextChar(); return;
  2055. case '\0': CurrentToken = Token.EOF; return;
  2056. }
  2057. // Number?
  2058. if (char.IsDigit(_currentChar) || _currentChar == '-')
  2059. {
  2060. TokenizeNumber();
  2061. return;
  2062. }
  2063. // Identifier? (checked for after everything else as identifiers are actually quite rare in valid json)
  2064. if (Char.IsLetter(_currentChar) || _currentChar == '_' || _currentChar == '$')
  2065. {
  2066. // Find end of identifier
  2067. _sb.Length = 0;
  2068. while (Char.IsLetterOrDigit(_currentChar) || _currentChar == '_' || _currentChar == '$')
  2069. {
  2070. _sb.Append(_currentChar);
  2071. NextChar();
  2072. }
  2073. String = _sb.ToString();
  2074. // Handle special identifiers
  2075. switch (String)
  2076. {
  2077. case "true":
  2078. LiteralKind = LiteralKind.True;
  2079. CurrentToken = Token.Literal;
  2080. return;
  2081. case "false":
  2082. LiteralKind = LiteralKind.False;
  2083. CurrentToken = Token.Literal;
  2084. return;
  2085. case "null":
  2086. LiteralKind = LiteralKind.Null;
  2087. CurrentToken = Token.Literal;
  2088. return;
  2089. }
  2090. CurrentToken = Token.Identifier;
  2091. return;
  2092. }
  2093. // What the?
  2094. throw new InvalidDataException(string.Format("syntax error, unexpected character '{0}'", _currentChar));
  2095. }
  2096. }
  2097. // Parse a sequence of characters that could make up a valid number
  2098. // For performance, we don't actually parse it into a number yet. When using PetaJsonEmit we parse
  2099. // later, directly into a value type to avoid boxing
  2100. private void TokenizeNumber()
  2101. {
  2102. _sb.Length = 0;
  2103. // Leading negative sign
  2104. bool signed = false;
  2105. if (_currentChar == '-')
  2106. {
  2107. signed = true;
  2108. _sb.Append(_currentChar);
  2109. NextChar();
  2110. }
  2111. // Hex prefix?
  2112. bool hex = false;
  2113. if (_currentChar == '0' && (_options & JsonOptions.StrictParser)==0)
  2114. {
  2115. _sb.Append(_currentChar);
  2116. NextChar();
  2117. if (_currentChar == 'x' || _currentChar == 'X')
  2118. {
  2119. _sb.Append(_currentChar);
  2120. NextChar();
  2121. hex = true;
  2122. }
  2123. }
  2124. // Process characters, but vaguely figure out what type it is
  2125. bool cont = true;
  2126. bool fp = false;
  2127. while (cont)
  2128. {
  2129. switch (_currentChar)
  2130. {
  2131. case '0':
  2132. case '1':
  2133. case '2':
  2134. case '3':
  2135. case '4':
  2136. case '5':
  2137. case '6':
  2138. case '7':
  2139. case '8':
  2140. case '9':
  2141. _sb.Append(_currentChar);
  2142. NextChar();
  2143. break;
  2144. case 'A':
  2145. case 'a':
  2146. case 'B':
  2147. case 'b':
  2148. case 'C':
  2149. case 'c':
  2150. case 'D':
  2151. case 'd':
  2152. case 'F':
  2153. case 'f':
  2154. if (!hex)
  2155. cont = false;
  2156. else
  2157. {
  2158. _sb.Append(_currentChar);
  2159. NextChar();
  2160. }
  2161. break;
  2162. case '.':
  2163. if (hex)
  2164. {
  2165. cont = false;
  2166. }
  2167. else
  2168. {
  2169. fp = true;
  2170. _sb.Append(_currentChar);
  2171. NextChar();
  2172. }
  2173. break;
  2174. case 'E':
  2175. case 'e':
  2176. if (!hex)
  2177. {
  2178. fp = true;
  2179. _sb.Append(_currentChar);
  2180. NextChar();
  2181. if (_currentChar == '+' || _currentChar == '-')
  2182. {
  2183. _sb.Append(_currentChar);
  2184. NextChar();
  2185. }
  2186. }
  2187. break;
  2188. default:
  2189. cont = false;
  2190. break;
  2191. }
  2192. }
  2193. if (char.IsLetter(_currentChar))
  2194. throw new InvalidDataException(string.Format("syntax error, invalid character following number '{0}'", _sb.ToString()));
  2195. // Setup token
  2196. String = _sb.ToString();
  2197. CurrentToken = Token.Literal;
  2198. // Setup literal kind
  2199. if (fp)
  2200. {
  2201. LiteralKind = LiteralKind.FloatingPoint;
  2202. }
  2203. else if (signed)
  2204. {
  2205. LiteralKind = LiteralKind.SignedInteger;
  2206. }
  2207. else
  2208. {
  2209. LiteralKind = LiteralKind.UnsignedInteger;
  2210. }
  2211. }
  2212. // Check the current token, throw exception if mismatch
  2213. public void Check(Token tokenRequired)
  2214. {
  2215. if (tokenRequired != CurrentToken)
  2216. {
  2217. throw new InvalidDataException(string.Format("syntax error, expected {0} found {1}", tokenRequired, CurrentToken));
  2218. }
  2219. }
  2220. // Skip token which must match
  2221. public void Skip(Token tokenRequired)
  2222. {
  2223. Check(tokenRequired);
  2224. NextToken();
  2225. }
  2226. // Skip token if it matches
  2227. public bool SkipIf(Token tokenRequired)
  2228. {
  2229. if (tokenRequired == CurrentToken)
  2230. {
  2231. NextToken();
  2232. return true;
  2233. }
  2234. return false;
  2235. }
  2236. }
  2237. #if !PETAJSON_NO_EMIT
  2238. static class Emit
  2239. {
  2240. // Generates a function that when passed an object of specified type, renders it to an IJsonReader
  2241. public static Action<IJsonWriter, object> MakeFormatter(Type type)
  2242. {
  2243. var formatJson = ReflectionInfo.FindFormatJson(type);
  2244. if (formatJson != null)
  2245. {
  2246. var method = new DynamicMethod("invoke_formatJson", null, new Type[] { typeof(IJsonWriter), typeof(Object) }, true);
  2247. var il = method.GetILGenerator();
  2248. if (formatJson.ReturnType == typeof(string))
  2249. {
  2250. // w.WriteStringLiteral(o.FormatJson())
  2251. il.Emit(OpCodes.Ldarg_0);
  2252. il.Emit(OpCodes.Ldarg_1);
  2253. il.Emit(OpCodes.Unbox, type);
  2254. il.Emit(OpCodes.Call, formatJson);
  2255. il.Emit(OpCodes.Callvirt, typeof(IJsonWriter).GetMethod("WriteStringLiteral"));
  2256. }
  2257. else
  2258. {
  2259. // o.FormatJson(w);
  2260. il.Emit(OpCodes.Ldarg_1);
  2261. il.Emit(type.IsValueType ? OpCodes.Unbox : OpCodes.Castclass, type);
  2262. il.Emit(OpCodes.Ldarg_0);
  2263. il.Emit(type.IsValueType ? OpCodes.Call : OpCodes.Callvirt, formatJson);
  2264. }
  2265. il.Emit(OpCodes.Ret);
  2266. return (Action<IJsonWriter, object>)method.CreateDelegate(typeof(Action<IJsonWriter, object>));
  2267. }
  2268. else
  2269. {
  2270. // Get the reflection info for this type
  2271. var ri = ReflectionInfo.GetReflectionInfo(type);
  2272. if (ri == null)
  2273. return null;
  2274. // Create a dynamic method that can do the work
  2275. var method = new DynamicMethod("dynamic_formatter", null, new Type[] { typeof(IJsonWriter), typeof(object) }, true);
  2276. var il = method.GetILGenerator();
  2277. // Cast/unbox the target object and store in local variable
  2278. var locTypedObj = il.DeclareLocal(type);
  2279. il.Emit(OpCodes.Ldarg_1);
  2280. il.Emit(type.IsValueType ? OpCodes.Unbox_Any : OpCodes.Castclass, type);
  2281. il.Emit(OpCodes.Stloc, locTypedObj);
  2282. // Get Invariant CultureInfo (since we'll probably be needing this)
  2283. var locInvariant = il.DeclareLocal(typeof(IFormatProvider));
  2284. il.Emit(OpCodes.Call, typeof(CultureInfo).GetProperty("InvariantCulture").GetGetMethod());
  2285. il.Emit(OpCodes.Stloc, locInvariant);
  2286. // These are the types we'll call .ToString(Culture.InvariantCulture) on
  2287. var toStringTypes = new Type[] {
  2288. typeof(int), typeof(uint), typeof(long), typeof(ulong),
  2289. typeof(short), typeof(ushort), typeof(decimal),
  2290. typeof(byte), typeof(sbyte)
  2291. };
  2292. // Theses types we also generate for
  2293. var otherSupportedTypes = new Type[] {
  2294. typeof(double), typeof(float), typeof(string), typeof(char)
  2295. };
  2296. // Call IJsonWriting if implemented
  2297. if (typeof(IJsonWriting).IsAssignableFrom(type))
  2298. {
  2299. if (type.IsValueType)
  2300. {
  2301. il.Emit(OpCodes.Ldloca, locTypedObj);
  2302. il.Emit(OpCodes.Ldarg_0);
  2303. il.Emit(OpCodes.Call, type.GetInterfaceMap(typeof(IJsonWriting)).TargetMethods[0]);
  2304. }
  2305. else
  2306. {
  2307. il.Emit(OpCodes.Ldloc, locTypedObj);
  2308. il.Emit(OpCodes.Castclass, typeof(IJsonWriting));
  2309. il.Emit(OpCodes.Ldarg_0);
  2310. il.Emit(OpCodes.Callvirt, typeof(IJsonWriting).GetMethod("OnJsonWriting", new Type[] { typeof(IJsonWriter) }));
  2311. }
  2312. }
  2313. // Process all members
  2314. foreach (var m in ri.Members)
  2315. {
  2316. // Dont save deprecated properties
  2317. if (m.Deprecated)
  2318. {
  2319. continue;
  2320. }
  2321. // Ignore write only properties
  2322. var pi = m.Member as PropertyInfo;
  2323. if (pi != null && pi.GetGetMethod(true) == null)
  2324. {
  2325. continue;
  2326. }
  2327. // Write the Json key
  2328. il.Emit(OpCodes.Ldarg_0);
  2329. il.Emit(OpCodes.Ldstr, m.JsonKey);
  2330. il.Emit(OpCodes.Callvirt, typeof(IJsonWriter).GetMethod("WriteKeyNoEscaping", new Type[] { typeof(string) }));
  2331. // Load the writer
  2332. il.Emit(OpCodes.Ldarg_0);
  2333. // Get the member type
  2334. var memberType = m.MemberType;
  2335. // Load the target object
  2336. if (type.IsValueType)
  2337. {
  2338. il.Emit(OpCodes.Ldloca, locTypedObj);
  2339. }
  2340. else
  2341. {
  2342. il.Emit(OpCodes.Ldloc, locTypedObj);
  2343. }
  2344. // Work out if we need the value or it's address on the stack
  2345. bool NeedValueAddress = (memberType.IsValueType && (toStringTypes.Contains(memberType) || otherSupportedTypes.Contains(memberType)));
  2346. if (Nullable.GetUnderlyingType(memberType) != null)
  2347. {
  2348. NeedValueAddress = true;
  2349. }
  2350. // Property?
  2351. if (pi != null)
  2352. {
  2353. // Call property's get method
  2354. if (type.IsValueType)
  2355. il.Emit(OpCodes.Call, pi.GetGetMethod(true));
  2356. else
  2357. il.Emit(OpCodes.Callvirt, pi.GetGetMethod(true));
  2358. // If we need the address then store in a local and take it's address
  2359. if (NeedValueAddress)
  2360. {
  2361. var locTemp = il.DeclareLocal(memberType);
  2362. il.Emit(OpCodes.Stloc, locTemp);
  2363. il.Emit(OpCodes.Ldloca, locTemp);
  2364. }
  2365. }
  2366. // Field?
  2367. var fi = m.Member as FieldInfo;
  2368. if (fi != null)
  2369. {
  2370. if (NeedValueAddress)
  2371. {
  2372. il.Emit(OpCodes.Ldflda, fi);
  2373. }
  2374. else
  2375. {
  2376. il.Emit(OpCodes.Ldfld, fi);
  2377. }
  2378. }
  2379. Label? lblFinished = null;
  2380. // Is it a nullable type?
  2381. var typeUnderlying = Nullable.GetUnderlyingType(memberType);
  2382. if (typeUnderlying != null)
  2383. {
  2384. // Duplicate the address so we can call get_HasValue() and then get_Value()
  2385. il.Emit(OpCodes.Dup);
  2386. // Define some labels
  2387. var lblHasValue = il.DefineLabel();
  2388. lblFinished = il.DefineLabel();
  2389. // Call has_Value
  2390. il.Emit(OpCodes.Call, memberType.GetProperty("HasValue").GetGetMethod());
  2391. il.Emit(OpCodes.Brtrue, lblHasValue);
  2392. // No value, write "null:
  2393. il.Emit(OpCodes.Pop);
  2394. il.Emit(OpCodes.Ldstr, "null");
  2395. il.Emit(OpCodes.Callvirt, typeof(IJsonWriter).GetMethod("WriteRaw", new Type[] { typeof(string) }));
  2396. il.Emit(OpCodes.Br_S, lblFinished.Value);
  2397. // Get it's value
  2398. il.MarkLabel(lblHasValue);
  2399. il.Emit(OpCodes.Call, memberType.GetProperty("Value").GetGetMethod());
  2400. // Switch to the underlying type from here on
  2401. memberType = typeUnderlying;
  2402. NeedValueAddress = (memberType.IsValueType && (toStringTypes.Contains(memberType) || otherSupportedTypes.Contains(memberType)));
  2403. // Work out again if we need the address of the value
  2404. if (NeedValueAddress)
  2405. {
  2406. var locTemp = il.DeclareLocal(memberType);
  2407. il.Emit(OpCodes.Stloc, locTemp);
  2408. il.Emit(OpCodes.Ldloca, locTemp);
  2409. }
  2410. }
  2411. // ToString()
  2412. if (toStringTypes.Contains(memberType))
  2413. {
  2414. // Convert to string
  2415. il.Emit(OpCodes.Ldloc, locInvariant);
  2416. il.Emit(OpCodes.Call, memberType.GetMethod("ToString", new Type[] { typeof(IFormatProvider) }));
  2417. il.Emit(OpCodes.Callvirt, typeof(IJsonWriter).GetMethod("WriteRaw", new Type[] { typeof(string) }));
  2418. }
  2419. // ToString("R")
  2420. else if (memberType == typeof(float) || memberType == typeof(double))
  2421. {
  2422. il.Emit(OpCodes.Ldstr, "R");
  2423. il.Emit(OpCodes.Ldloc, locInvariant);
  2424. il.Emit(OpCodes.Call, memberType.GetMethod("ToString", new Type[] { typeof(string), typeof(IFormatProvider) }));
  2425. il.Emit(OpCodes.Callvirt, typeof(IJsonWriter).GetMethod("WriteRaw", new Type[] { typeof(string) }));
  2426. }
  2427. // String?
  2428. else if (memberType == typeof(string))
  2429. {
  2430. il.Emit(OpCodes.Callvirt, typeof(IJsonWriter).GetMethod("WriteStringLiteral", new Type[] { typeof(string) }));
  2431. }
  2432. // Char?
  2433. else if (memberType == typeof(char))
  2434. {
  2435. il.Emit(OpCodes.Call, memberType.GetMethod("ToString", new Type[] { }));
  2436. il.Emit(OpCodes.Callvirt, typeof(IJsonWriter).GetMethod("WriteStringLiteral", new Type[] { typeof(string) }));
  2437. }
  2438. // Bool?
  2439. else if (memberType == typeof(bool))
  2440. {
  2441. var lblTrue = il.DefineLabel();
  2442. var lblCont = il.DefineLabel();
  2443. il.Emit(OpCodes.Brtrue_S, lblTrue);
  2444. il.Emit(OpCodes.Ldstr, "false");
  2445. il.Emit(OpCodes.Br_S, lblCont);
  2446. il.MarkLabel(lblTrue);
  2447. il.Emit(OpCodes.Ldstr, "true");
  2448. il.MarkLabel(lblCont);
  2449. il.Emit(OpCodes.Callvirt, typeof(IJsonWriter).GetMethod("WriteRaw", new Type[] { typeof(string) }));
  2450. }
  2451. // NB: We don't support DateTime as it's format can be changed
  2452. else
  2453. {
  2454. // Unsupported type, pass through
  2455. if (memberType.IsValueType)
  2456. {
  2457. il.Emit(OpCodes.Box, memberType);
  2458. }
  2459. il.Emit(OpCodes.Callvirt, typeof(IJsonWriter).GetMethod("WriteValue", new Type[] { typeof(object) }));
  2460. }
  2461. if (lblFinished.HasValue)
  2462. il.MarkLabel(lblFinished.Value);
  2463. }
  2464. // Call IJsonWritten
  2465. if (typeof(IJsonWritten).IsAssignableFrom(type))
  2466. {
  2467. if (type.IsValueType)
  2468. {
  2469. il.Emit(OpCodes.Ldloca, locTypedObj);
  2470. il.Emit(OpCodes.Ldarg_0);
  2471. il.Emit(OpCodes.Call, type.GetInterfaceMap(typeof(IJsonWritten)).TargetMethods[0]);
  2472. }
  2473. else
  2474. {
  2475. il.Emit(OpCodes.Ldloc, locTypedObj);
  2476. il.Emit(OpCodes.Castclass, typeof(IJsonWriting));
  2477. il.Emit(OpCodes.Ldarg_0);
  2478. il.Emit(OpCodes.Callvirt, typeof(IJsonWriting).GetMethod("OnJsonWritten", new Type[] { typeof(IJsonWriter) }));
  2479. }
  2480. }
  2481. // Done!
  2482. il.Emit(OpCodes.Ret);
  2483. var impl = (Action<IJsonWriter, object>)method.CreateDelegate(typeof(Action<IJsonWriter, object>));
  2484. // Wrap it in a call to WriteDictionary
  2485. return (w, obj) =>
  2486. {
  2487. w.WriteDictionary(() =>
  2488. {
  2489. impl(w, obj);
  2490. });
  2491. };
  2492. }
  2493. }
  2494. // Pseudo box lets us pass a value type by reference. Used during
  2495. // deserialization of value types.
  2496. interface IPseudoBox
  2497. {
  2498. object GetValue();
  2499. }
  2500. [Obfuscation(Exclude = true, ApplyToMembers = true)]
  2501. class PseudoBox<T> : IPseudoBox where T : struct
  2502. {
  2503. public T value = default(T);
  2504. object IPseudoBox.GetValue() { return value; }
  2505. }
  2506. // Make a parser for value types
  2507. public static Func<IJsonReader, Type, object> MakeParser(Type type)
  2508. {
  2509. System.Diagnostics.Debug.Assert(type.IsValueType);
  2510. // ParseJson method?
  2511. var parseJson = ReflectionInfo.FindParseJson(type);
  2512. if (parseJson != null)
  2513. {
  2514. if (parseJson.GetParameters()[0].ParameterType == typeof(IJsonReader))
  2515. {
  2516. var method = new DynamicMethod("invoke_ParseJson", typeof(Object), new Type[] { typeof(IJsonReader), typeof(Type) }, true);
  2517. var il = method.GetILGenerator();
  2518. il.Emit(OpCodes.Ldarg_0);
  2519. il.Emit(OpCodes.Call, parseJson);
  2520. il.Emit(OpCodes.Box, type);
  2521. il.Emit(OpCodes.Ret);
  2522. return (Func<IJsonReader,Type,object>)method.CreateDelegate(typeof(Func<IJsonReader,Type,object>));
  2523. }
  2524. else
  2525. {
  2526. var method = new DynamicMethod("invoke_ParseJson", typeof(Object), new Type[] { typeof(string) }, true);
  2527. var il = method.GetILGenerator();
  2528. il.Emit(OpCodes.Ldarg_0);
  2529. il.Emit(OpCodes.Call, parseJson);
  2530. il.Emit(OpCodes.Box, type);
  2531. il.Emit(OpCodes.Ret);
  2532. var invoke = (Func<string, object>)method.CreateDelegate(typeof(Func<string, object>));
  2533. return (r, t) =>
  2534. {
  2535. if (r.GetLiteralKind() == LiteralKind.String)
  2536. {
  2537. var o = invoke(r.GetLiteralString());
  2538. r.NextToken();
  2539. return o;
  2540. }
  2541. throw new InvalidDataException(string.Format("Expected string literal for type {0}", type.FullName));
  2542. };
  2543. }
  2544. }
  2545. else
  2546. {
  2547. // Get the reflection info for this type
  2548. var ri = ReflectionInfo.GetReflectionInfo(type);
  2549. if (ri == null)
  2550. return null;
  2551. // We'll create setters for each property/field
  2552. var setters = new Dictionary<string, Action<IJsonReader, object>>();
  2553. // Store the value in a pseudo box until it's fully initialized
  2554. var boxType = typeof(PseudoBox<>).MakeGenericType(type);
  2555. // Process all members
  2556. foreach (var m in ri.Members)
  2557. {
  2558. // Ignore write only properties
  2559. var pi = m.Member as PropertyInfo;
  2560. var fi = m.Member as FieldInfo;
  2561. if (pi != null && pi.GetSetMethod(true) == null)
  2562. {
  2563. continue;
  2564. }
  2565. // Create a dynamic method that can do the work
  2566. var method = new DynamicMethod("dynamic_parser", null, new Type[] { typeof(IJsonReader), typeof(object) }, true);
  2567. var il = method.GetILGenerator();
  2568. // Load the target
  2569. il.Emit(OpCodes.Ldarg_1);
  2570. il.Emit(OpCodes.Castclass, boxType);
  2571. il.Emit(OpCodes.Ldflda, boxType.GetField("value"));
  2572. // Get the value
  2573. GenerateGetJsonValue(m, il);
  2574. // Assign it
  2575. if (pi != null)
  2576. il.Emit(OpCodes.Call, pi.GetSetMethod(true));
  2577. if (fi != null)
  2578. il.Emit(OpCodes.Stfld, fi);
  2579. // Done
  2580. il.Emit(OpCodes.Ret);
  2581. // Store in the map of setters
  2582. setters.Add(m.JsonKey, (Action<IJsonReader, object>)method.CreateDelegate(typeof(Action<IJsonReader, object>)));
  2583. }
  2584. // Create helpers to invoke the interfaces (this is painful but avoids having to really box
  2585. // the value in order to call the interface).
  2586. Action<object, IJsonReader> invokeLoading = MakeInterfaceCall(type, typeof(IJsonLoading));
  2587. Action<object, IJsonReader> invokeLoaded = MakeInterfaceCall(type, typeof(IJsonLoaded));
  2588. Func<object, IJsonReader, string, bool> invokeField = MakeLoadFieldCall(type);
  2589. // Create the parser
  2590. Func<IJsonReader, Type, object> parser = (reader, Type) =>
  2591. {
  2592. // Create pseudobox (ie: new PseudoBox<Type>)
  2593. var box = DecoratingActivator.CreateInstance(boxType);
  2594. // Call IJsonLoading
  2595. if (invokeLoading != null)
  2596. invokeLoading(box, reader);
  2597. // Read the dictionary
  2598. reader.ParseDictionary(key =>
  2599. {
  2600. // Call IJsonLoadField
  2601. if (invokeField != null && invokeField(box, reader, key))
  2602. return;
  2603. // Get a setter and invoke it if found
  2604. Action<IJsonReader, object> setter;
  2605. if (setters.TryGetValue(key, out setter))
  2606. {
  2607. setter(reader, box);
  2608. }
  2609. });
  2610. // IJsonLoaded
  2611. if (invokeLoaded != null)
  2612. invokeLoaded(box, reader);
  2613. // Return the value
  2614. return ((IPseudoBox)box).GetValue();
  2615. };
  2616. // Done
  2617. return parser;
  2618. }
  2619. }
  2620. // Helper to make the call to a PsuedoBox value's IJsonLoading or IJsonLoaded
  2621. static Action<object, IJsonReader> MakeInterfaceCall(Type type, Type tItf)
  2622. {
  2623. // Interface supported?
  2624. if (!tItf.IsAssignableFrom(type))
  2625. return null;
  2626. // Resolve the box type
  2627. var boxType = typeof(PseudoBox<>).MakeGenericType(type);
  2628. // Create method
  2629. var method = new DynamicMethod("dynamic_invoke_" + tItf.Name, null, new Type[] { typeof(object), typeof(IJsonReader) }, true);
  2630. var il = method.GetILGenerator();
  2631. // Call interface method
  2632. il.Emit(OpCodes.Ldarg_0);
  2633. il.Emit(OpCodes.Castclass, boxType);
  2634. il.Emit(OpCodes.Ldflda, boxType.GetField("value"));
  2635. il.Emit(OpCodes.Ldarg_1);
  2636. il.Emit(OpCodes.Call, type.GetInterfaceMap(tItf).TargetMethods[0]);
  2637. il.Emit(OpCodes.Ret);
  2638. // Done
  2639. return (Action<object, IJsonReader>)method.CreateDelegate(typeof(Action<object, IJsonReader>));
  2640. }
  2641. // Similar to above but for IJsonLoadField
  2642. static Func<object, IJsonReader, string, bool> MakeLoadFieldCall(Type type)
  2643. {
  2644. // Interface supported?
  2645. var tItf = typeof(IJsonLoadField);
  2646. if (!tItf.IsAssignableFrom(type))
  2647. return null;
  2648. // Resolve the box type
  2649. var boxType = typeof(PseudoBox<>).MakeGenericType(type);
  2650. // Create method
  2651. var method = new DynamicMethod("dynamic_invoke_" + tItf.Name, typeof(bool), new Type[] { typeof(object), typeof(IJsonReader), typeof(string) }, true);
  2652. var il = method.GetILGenerator();
  2653. // Call interface method
  2654. il.Emit(OpCodes.Ldarg_0);
  2655. il.Emit(OpCodes.Castclass, boxType);
  2656. il.Emit(OpCodes.Ldflda, boxType.GetField("value"));
  2657. il.Emit(OpCodes.Ldarg_1);
  2658. il.Emit(OpCodes.Ldarg_2);
  2659. il.Emit(OpCodes.Call, type.GetInterfaceMap(tItf).TargetMethods[0]);
  2660. il.Emit(OpCodes.Ret);
  2661. // Done
  2662. return (Func<object, IJsonReader, string, bool>)method.CreateDelegate(typeof(Func<object, IJsonReader, string, bool>));
  2663. }
  2664. // Create an "into parser" that can parse from IJsonReader into a reference type (ie: a class)
  2665. public static Action<IJsonReader, object> MakeIntoParser(Type type)
  2666. {
  2667. System.Diagnostics.Debug.Assert(!type.IsValueType);
  2668. // Get the reflection info for this type
  2669. var ri = ReflectionInfo.GetReflectionInfo(type);
  2670. if (ri == null)
  2671. return null;
  2672. // We'll create setters for each property/field
  2673. var setters = new Dictionary<string, Action<IJsonReader, object>>();
  2674. // Process all members
  2675. foreach (var m in ri.Members)
  2676. {
  2677. // Ignore write only properties
  2678. var pi = m.Member as PropertyInfo;
  2679. var fi = m.Member as FieldInfo;
  2680. if (pi != null && pi.GetSetMethod(true) == null)
  2681. {
  2682. continue;
  2683. }
  2684. // Ignore read only properties that has KeepInstance attribute
  2685. if (pi != null && pi.GetGetMethod(true) == null && m.KeepInstance)
  2686. {
  2687. continue;
  2688. }
  2689. // Create a dynamic method that can do the work
  2690. var method = new DynamicMethod("dynamic_parser", null, new Type[] { typeof(IJsonReader), typeof(object) }, true);
  2691. var il = method.GetILGenerator();
  2692. // Load the target
  2693. il.Emit(OpCodes.Ldarg_1);
  2694. il.Emit(OpCodes.Castclass, type);
  2695. // Try to keep existing instance?
  2696. if (m.KeepInstance)
  2697. {
  2698. // Get existing existing instance
  2699. il.Emit(OpCodes.Dup);
  2700. if (pi != null)
  2701. il.Emit(OpCodes.Callvirt, pi.GetGetMethod(true));
  2702. else
  2703. il.Emit(OpCodes.Ldfld, fi);
  2704. var existingInstance = il.DeclareLocal(m.MemberType);
  2705. var lblExistingInstanceNull = il.DefineLabel();
  2706. // Keep a copy of the existing instance in a locale
  2707. il.Emit(OpCodes.Dup);
  2708. il.Emit(OpCodes.Stloc, existingInstance);
  2709. // Compare to null
  2710. il.Emit(OpCodes.Ldnull);
  2711. il.Emit(OpCodes.Ceq);
  2712. il.Emit(OpCodes.Brtrue_S, lblExistingInstanceNull);
  2713. il.Emit(OpCodes.Ldarg_0); // reader
  2714. il.Emit(OpCodes.Ldloc, existingInstance); // into
  2715. il.Emit(OpCodes.Callvirt, typeof(IJsonReader).GetMethod("ParseInto", new Type[] { typeof(Object) }));
  2716. il.Emit(OpCodes.Pop); // Clean up target left on stack (1)
  2717. il.Emit(OpCodes.Ret);
  2718. il.MarkLabel(lblExistingInstanceNull);
  2719. }
  2720. // Get the value from IJsonReader
  2721. GenerateGetJsonValue(m, il);
  2722. // Assign it
  2723. if (pi != null)
  2724. il.Emit(OpCodes.Callvirt, pi.GetSetMethod(true));
  2725. if (fi != null)
  2726. il.Emit(OpCodes.Stfld, fi);
  2727. // Done
  2728. il.Emit(OpCodes.Ret);
  2729. // Store the handler in map
  2730. setters.Add(m.JsonKey, (Action<IJsonReader, object>)method.CreateDelegate(typeof(Action<IJsonReader, object>)));
  2731. }
  2732. // Now create the parseInto delegate
  2733. Action<IJsonReader, object> parseInto = (reader, obj) =>
  2734. {
  2735. // Call IJsonLoading
  2736. var loading = obj as IJsonLoading;
  2737. if (loading != null)
  2738. loading.OnJsonLoading(reader);
  2739. // Cache IJsonLoadField
  2740. var lf = obj as IJsonLoadField;
  2741. // Read dictionary keys
  2742. reader.ParseDictionary(key =>
  2743. {
  2744. // Call IJsonLoadField
  2745. if (lf != null && lf.OnJsonField(reader, key))
  2746. return;
  2747. // Call setters
  2748. Action<IJsonReader, object> setter;
  2749. if (setters.TryGetValue(key, out setter))
  2750. {
  2751. setter(reader, obj);
  2752. }
  2753. });
  2754. // Call IJsonLoaded
  2755. var loaded = obj as IJsonLoaded;
  2756. if (loaded != null)
  2757. loaded.OnJsonLoaded(reader);
  2758. };
  2759. // Since we've created the ParseInto handler, we might as well register
  2760. // as a Parse handler too.
  2761. RegisterIntoParser(type, parseInto);
  2762. // Done
  2763. return parseInto;
  2764. }
  2765. // Registers a ParseInto handler as Parse handler that instantiates the object
  2766. // and then parses into it.
  2767. static void RegisterIntoParser(Type type, Action<IJsonReader, object> parseInto)
  2768. {
  2769. // Check type has a parameterless constructor
  2770. var con = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[0], null);
  2771. if (con == null)
  2772. return;
  2773. // Create a dynamic method that can do the work
  2774. var method = new DynamicMethod("dynamic_factory", typeof(object), new Type[] { typeof(IJsonReader), typeof(Action<IJsonReader, object>) }, true);
  2775. var il = method.GetILGenerator();
  2776. // Create the new object
  2777. var locObj = il.DeclareLocal(typeof(object));
  2778. il.Emit(OpCodes.Newobj, con);
  2779. il.Emit(OpCodes.Dup); // For return value
  2780. il.Emit(OpCodes.Stloc, locObj);
  2781. il.Emit(OpCodes.Ldarg_1); // parseinto delegate
  2782. il.Emit(OpCodes.Ldarg_0); // IJsonReader
  2783. il.Emit(OpCodes.Ldloc, locObj); // new object instance
  2784. il.Emit(OpCodes.Callvirt, typeof(Action<IJsonReader, object>).GetMethod("Invoke"));
  2785. il.Emit(OpCodes.Ret);
  2786. var factory = (Func<IJsonReader, Action<IJsonReader, object>, object>)method.CreateDelegate(typeof(Func<IJsonReader, Action<IJsonReader, object>, object>));
  2787. Json.RegisterParser(type, (reader, type2) =>
  2788. {
  2789. return factory(reader, parseInto);
  2790. });
  2791. }
  2792. // Generate the MSIL to retrieve a value for a particular field or property from a IJsonReader
  2793. private static void GenerateGetJsonValue(JsonMemberInfo m, ILGenerator il)
  2794. {
  2795. Action<string> generateCallToHelper = helperName =>
  2796. {
  2797. // Call the helper
  2798. il.Emit(OpCodes.Ldarg_0);
  2799. il.Emit(OpCodes.Call, typeof(Emit).GetMethod(helperName, new Type[] { typeof(IJsonReader) }));
  2800. // Move to next token
  2801. il.Emit(OpCodes.Ldarg_0);
  2802. il.Emit(OpCodes.Callvirt, typeof(IJsonReader).GetMethod("NextToken", new Type[] { }));
  2803. };
  2804. Type[] numericTypes = new Type[] {
  2805. typeof(int), typeof(uint), typeof(long), typeof(ulong),
  2806. typeof(short), typeof(ushort), typeof(decimal),
  2807. typeof(byte), typeof(sbyte),
  2808. typeof(double), typeof(float)
  2809. };
  2810. if (m.MemberType == typeof(string))
  2811. {
  2812. generateCallToHelper("GetLiteralString");
  2813. }
  2814. else if (m.MemberType == typeof(bool))
  2815. {
  2816. generateCallToHelper("GetLiteralBool");
  2817. }
  2818. else if (m.MemberType == typeof(char))
  2819. {
  2820. generateCallToHelper("GetLiteralChar");
  2821. }
  2822. else if (numericTypes.Contains(m.MemberType))
  2823. {
  2824. // Get raw number string
  2825. il.Emit(OpCodes.Ldarg_0);
  2826. il.Emit(OpCodes.Call, typeof(Emit).GetMethod("GetLiteralNumber", new Type[] { typeof(IJsonReader) }));
  2827. // Convert to a string
  2828. il.Emit(OpCodes.Call, typeof(CultureInfo).GetProperty("InvariantCulture").GetGetMethod());
  2829. il.Emit(OpCodes.Call, m.MemberType.GetMethod("Parse", new Type[] { typeof(string), typeof(IFormatProvider) }));
  2830. //
  2831. il.Emit(OpCodes.Ldarg_0);
  2832. il.Emit(OpCodes.Callvirt, typeof(IJsonReader).GetMethod("NextToken", new Type[] { }));
  2833. }
  2834. else
  2835. {
  2836. il.Emit(OpCodes.Ldarg_0);
  2837. il.Emit(OpCodes.Ldtoken, m.MemberType);
  2838. il.Emit(OpCodes.Call, typeof(Type).GetMethod("GetTypeFromHandle", new Type[] { typeof(RuntimeTypeHandle) }));
  2839. il.Emit(OpCodes.Callvirt, typeof(IJsonReader).GetMethod("Parse", new Type[] { typeof(Type) }));
  2840. il.Emit(m.MemberType.IsValueType ? OpCodes.Unbox_Any : OpCodes.Castclass, m.MemberType);
  2841. }
  2842. }
  2843. // Helper to fetch a literal bool from an IJsonReader
  2844. [Obfuscation(Exclude = true)]
  2845. public static bool GetLiteralBool(IJsonReader r)
  2846. {
  2847. switch (r.GetLiteralKind())
  2848. {
  2849. case LiteralKind.True:
  2850. return true;
  2851. case LiteralKind.False:
  2852. return false;
  2853. default:
  2854. throw new InvalidDataException("expected a boolean value");
  2855. }
  2856. }
  2857. // Helper to fetch a literal character from an IJsonReader
  2858. [Obfuscation(Exclude = true)]
  2859. public static char GetLiteralChar(IJsonReader r)
  2860. {
  2861. if (r.GetLiteralKind() != LiteralKind.String)
  2862. throw new InvalidDataException("expected a single character string literal");
  2863. var str = r.GetLiteralString();
  2864. if (str == null || str.Length != 1)
  2865. throw new InvalidDataException("expected a single character string literal");
  2866. return str[0];
  2867. }
  2868. // Helper to fetch a literal string from an IJsonReader
  2869. [Obfuscation(Exclude = true)]
  2870. public static string GetLiteralString(IJsonReader r)
  2871. {
  2872. switch (r.GetLiteralKind())
  2873. {
  2874. case LiteralKind.Null: return null;
  2875. case LiteralKind.String: return r.GetLiteralString();
  2876. }
  2877. throw new InvalidDataException("expected a string literal");
  2878. }
  2879. // Helper to fetch a literal number from an IJsonReader (returns the raw string)
  2880. [Obfuscation(Exclude = true)]
  2881. public static string GetLiteralNumber(IJsonReader r)
  2882. {
  2883. switch (r.GetLiteralKind())
  2884. {
  2885. case LiteralKind.SignedInteger:
  2886. case LiteralKind.UnsignedInteger:
  2887. case LiteralKind.FloatingPoint:
  2888. return r.GetLiteralString();
  2889. }
  2890. throw new InvalidDataException("expected a numeric literal");
  2891. }
  2892. }
  2893. #endif
  2894. }
  2895. }