JsonReader.cs 25 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099
  1. //
  2. // JsonReader.cs
  3. //
  4. // Author:
  5. // Atsushi Enomoto <[email protected]>
  6. //
  7. // Copyright (C) 2007-2011 Novell, Inc (http://www.novell.com)
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining
  10. // a copy of this software and associated documentation files (the
  11. // "Software"), to deal in the Software without restriction, including
  12. // without limitation the rights to use, copy, modify, merge, publish,
  13. // distribute, sublicense, and/or sell copies of the Software, and to
  14. // permit persons to whom the Software is furnished to do so, subject to
  15. // the following conditions:
  16. //
  17. // The above copyright notice and this permission notice shall be
  18. // included in all copies or substantial portions of the Software.
  19. //
  20. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  21. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  22. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  23. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  24. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  25. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  26. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  27. //
  28. using System;
  29. using System.Collections.Generic;
  30. using System.Globalization;
  31. using System.IO;
  32. using System.Text;
  33. using System.Xml;
  34. namespace System.Runtime.Serialization.Json
  35. {
  36. // It is a subset of XmlInputStream from System.XML.
  37. class EncodingDetecingInputStream : Stream
  38. {
  39. internal static readonly Encoding StrictUTF8, Strict1234UTF32, StrictBigEndianUTF16, StrictUTF16;
  40. static EncodingDetecingInputStream ()
  41. {
  42. StrictUTF8 = new UTF8Encoding (false, true);
  43. Strict1234UTF32 = new UTF32Encoding (true, false, true);
  44. StrictBigEndianUTF16 = new UnicodeEncoding (true, false, true);
  45. StrictUTF16 = new UnicodeEncoding (false, false, true);
  46. }
  47. Encoding enc;
  48. Stream stream;
  49. byte[] buffer;
  50. int bufLength;
  51. int bufPos;
  52. static XmlException encodingException = new XmlException ("invalid encoding specification.");
  53. public EncodingDetecingInputStream (Stream stream)
  54. {
  55. if (stream == null)
  56. throw new ArgumentNullException ("stream");
  57. Initialize (stream);
  58. }
  59. private void Initialize (Stream stream)
  60. {
  61. buffer = new byte [6];
  62. this.stream = stream;
  63. enc = StrictUTF8; // Default to UTF8 if we can't guess it
  64. bufLength = stream.Read (buffer, 0, buffer.Length);
  65. if (bufLength == -1 || bufLength == 0) {
  66. return;
  67. }
  68. int c = ReadByteSpecial ();
  69. switch (c) {
  70. case 0xFF:
  71. c = ReadByteSpecial ();
  72. if (c == 0xFE) {
  73. // BOM-ed little endian utf-16
  74. enc = Encoding.Unicode;
  75. } else {
  76. // It doesn't start from "<?xml" then its encoding is utf-8
  77. bufPos = 0;
  78. }
  79. break;
  80. case 0xFE:
  81. c = ReadByteSpecial ();
  82. if (c == 0xFF) {
  83. // BOM-ed big endian utf-16
  84. enc = Encoding.BigEndianUnicode;
  85. return;
  86. } else {
  87. // It doesn't start from "<?xml" then its encoding is utf-8
  88. bufPos = 0;
  89. }
  90. break;
  91. case 0xEF:
  92. c = ReadByteSpecial ();
  93. if (c == 0xBB) {
  94. c = ReadByteSpecial ();
  95. if (c != 0xBF) {
  96. bufPos = 0;
  97. }
  98. } else {
  99. buffer [--bufPos] = 0xEF;
  100. }
  101. break;
  102. case 0:
  103. // It could still be 1234/2143/3412 variants of UTF32, but only 1234 version is available on .NET.
  104. c = ReadByteSpecial ();
  105. if (c == 0)
  106. enc = Strict1234UTF32;
  107. else
  108. enc = StrictBigEndianUTF16;
  109. break;
  110. default:
  111. c = ReadByteSpecial ();
  112. if (c == 0)
  113. enc = StrictUTF16;
  114. bufPos = 0;
  115. break;
  116. }
  117. }
  118. // Just like readbyte, but grows the buffer too.
  119. int ReadByteSpecial ()
  120. {
  121. if (bufLength > bufPos)
  122. return buffer [bufPos++];
  123. byte [] newbuf = new byte [buffer.Length * 2];
  124. Buffer.BlockCopy (buffer, 0, newbuf, 0, bufLength);
  125. int nbytes = stream.Read (newbuf, bufLength, buffer.Length);
  126. if (nbytes == -1 || nbytes == 0)
  127. return -1;
  128. bufLength += nbytes;
  129. buffer = newbuf;
  130. return buffer [bufPos++];
  131. }
  132. public Encoding ActualEncoding {
  133. get { return enc; }
  134. }
  135. #region Public Overrides
  136. public override bool CanRead {
  137. get {
  138. if (bufLength > bufPos)
  139. return true;
  140. else
  141. return stream.CanRead;
  142. }
  143. }
  144. // FIXME: It should support base stream's CanSeek.
  145. public override bool CanSeek {
  146. get { return false; } // stream.CanSeek; }
  147. }
  148. public override bool CanWrite {
  149. get { return false; }
  150. }
  151. public override long Length {
  152. get {
  153. return stream.Length;
  154. }
  155. }
  156. public override long Position {
  157. get {
  158. return stream.Position - bufLength + bufPos;
  159. }
  160. set {
  161. if(value < bufLength)
  162. bufPos = (int)value;
  163. else
  164. stream.Position = value - bufLength;
  165. }
  166. }
  167. public override void Close ()
  168. {
  169. stream.Close ();
  170. }
  171. public override void Flush ()
  172. {
  173. stream.Flush ();
  174. }
  175. public override int Read (byte[] buffer, int offset, int count)
  176. {
  177. int ret;
  178. if (count <= bufLength - bufPos) { // all from buffer
  179. Buffer.BlockCopy (this.buffer, bufPos, buffer, offset, count);
  180. bufPos += count;
  181. ret = count;
  182. } else {
  183. int bufRest = bufLength - bufPos;
  184. if (bufLength > bufPos) {
  185. Buffer.BlockCopy (this.buffer, bufPos, buffer, offset, bufRest);
  186. bufPos += bufRest;
  187. }
  188. ret = bufRest +
  189. stream.Read (buffer, offset + bufRest, count - bufRest);
  190. }
  191. return ret;
  192. }
  193. public override int ReadByte ()
  194. {
  195. if (bufLength > bufPos) {
  196. return buffer [bufPos++];
  197. }
  198. return stream.ReadByte ();
  199. }
  200. public override long Seek (long offset, System.IO.SeekOrigin origin)
  201. {
  202. int bufRest = bufLength - bufPos;
  203. if (origin == SeekOrigin.Current)
  204. if (offset < bufRest)
  205. return buffer [bufPos + offset];
  206. else
  207. return stream.Seek (offset - bufRest, origin);
  208. else
  209. return stream.Seek (offset, origin);
  210. }
  211. public override void SetLength (long value)
  212. {
  213. stream.SetLength (value);
  214. }
  215. public override void Write (byte[] buffer, int offset, int count)
  216. {
  217. throw new NotSupportedException ();
  218. }
  219. #endregion
  220. }
  221. class PushbackReader : StreamReader
  222. {
  223. Stack<int> pushback;
  224. public PushbackReader (Stream stream, Encoding encoding) : base (stream, encoding)
  225. {
  226. pushback = new Stack<int>();
  227. }
  228. public PushbackReader (Stream stream) : this (new EncodingDetecingInputStream (stream))
  229. {
  230. }
  231. public PushbackReader (EncodingDetecingInputStream stream) : this (stream, stream.ActualEncoding)
  232. {
  233. }
  234. public override void Close ()
  235. {
  236. pushback.Clear ();
  237. }
  238. public override int Peek ()
  239. {
  240. if (pushback.Count > 0) {
  241. return pushback.Peek ();
  242. }
  243. else {
  244. return base.Peek ();
  245. }
  246. }
  247. public override int Read ()
  248. {
  249. if (pushback.Count > 0) {
  250. return pushback.Pop ();
  251. }
  252. else {
  253. return base.Read ();
  254. }
  255. }
  256. public void Pushback (int ch)
  257. {
  258. pushback.Push (ch);
  259. }
  260. }
  261. // FIXME: quotas check
  262. class JsonReader : XmlDictionaryReader, IXmlJsonReaderInitializer, IXmlLineInfo
  263. {
  264. class ElementInfo
  265. {
  266. public readonly string Name;
  267. public readonly string Type;
  268. public bool HasContent;
  269. public ElementInfo (string name, string type)
  270. {
  271. this.Name = name;
  272. this.Type = type;
  273. }
  274. }
  275. enum AttributeState
  276. {
  277. None,
  278. Type,
  279. TypeValue,
  280. RuntimeType,
  281. RuntimeTypeValue
  282. }
  283. PushbackReader reader;
  284. XmlDictionaryReaderQuotas quotas;
  285. OnXmlDictionaryReaderClose on_close;
  286. XmlNameTable name_table = new NameTable ();
  287. XmlNodeType current_node;
  288. AttributeState attr_state;
  289. string simple_value;
  290. string next_element;
  291. string current_runtime_type, next_object_content_name;
  292. ReadState read_state = ReadState.Initial;
  293. bool content_stored;
  294. bool finished;
  295. Stack<ElementInfo> elements = new Stack<ElementInfo> ();
  296. int line = 1, column = 0;
  297. // Constructors
  298. public JsonReader (byte [] buffer, int offset, int count, Encoding encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose)
  299. {
  300. SetInput (buffer, offset, count, encoding, quotas, onClose);
  301. }
  302. public JsonReader (Stream stream, Encoding encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose)
  303. {
  304. SetInput (stream, encoding, quotas, onClose);
  305. }
  306. internal bool LameSilverlightLiteralParser { get; set; }
  307. // IXmlLineInfo
  308. public bool HasLineInfo ()
  309. {
  310. return true;
  311. }
  312. public int LineNumber {
  313. get { return line; }
  314. }
  315. public int LinePosition {
  316. get { return column; }
  317. }
  318. // IXmlJsonReaderInitializer
  319. public void SetInput (byte [] buffer, int offset, int count, Encoding encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose)
  320. {
  321. SetInput (new MemoryStream (buffer, offset, count), encoding, quotas, onClose);
  322. }
  323. public void SetInput (Stream stream, Encoding encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose)
  324. {
  325. if (encoding != null)
  326. reader = new PushbackReader (stream, encoding);
  327. else
  328. reader = new PushbackReader (stream);
  329. if (quotas == null)
  330. throw new ArgumentNullException ("quotas");
  331. this.quotas = quotas;
  332. this.on_close = onClose;
  333. }
  334. // XmlDictionaryReader
  335. public override int AttributeCount {
  336. get { return current_node != XmlNodeType.Element ? 0 : current_runtime_type != null ? 2 : 1; }
  337. }
  338. public override string BaseURI {
  339. get { return String.Empty; }
  340. }
  341. public override int Depth {
  342. get {
  343. int mod = 0;
  344. switch (attr_state) {
  345. case AttributeState.Type:
  346. case AttributeState.RuntimeType:
  347. mod++;
  348. break;
  349. case AttributeState.TypeValue:
  350. case AttributeState.RuntimeTypeValue:
  351. mod += 2;
  352. break;
  353. case AttributeState.None:
  354. if (NodeType == XmlNodeType.Text)
  355. mod++;
  356. break;
  357. }
  358. return read_state != ReadState.Interactive ? 0 : elements.Count - 1 + mod;
  359. }
  360. }
  361. public override bool EOF {
  362. get {
  363. switch (read_state) {
  364. case ReadState.Closed:
  365. case ReadState.EndOfFile:
  366. return true;
  367. default:
  368. return false;
  369. }
  370. }
  371. }
  372. public override bool HasValue {
  373. get {
  374. switch (NodeType) {
  375. case XmlNodeType.Attribute:
  376. case XmlNodeType.Text:
  377. return true;
  378. default:
  379. return false;
  380. }
  381. }
  382. }
  383. public override bool IsEmptyElement {
  384. get { return false; }
  385. }
  386. public override string LocalName {
  387. get {
  388. switch (attr_state) {
  389. case AttributeState.Type:
  390. return "type";
  391. case AttributeState.RuntimeType:
  392. return "__type";
  393. }
  394. switch (NodeType) {
  395. case XmlNodeType.Element:
  396. case XmlNodeType.EndElement:
  397. return elements.Peek ().Name;
  398. default:
  399. return String.Empty;
  400. }
  401. }
  402. }
  403. public override string NamespaceURI {
  404. get { return String.Empty; }
  405. }
  406. public override XmlNameTable NameTable {
  407. get { return name_table; }
  408. }
  409. public override XmlNodeType NodeType {
  410. get {
  411. switch (attr_state) {
  412. case AttributeState.Type:
  413. case AttributeState.RuntimeType:
  414. return XmlNodeType.Attribute;
  415. case AttributeState.TypeValue:
  416. case AttributeState.RuntimeTypeValue:
  417. return XmlNodeType.Text;
  418. default:
  419. return current_node;
  420. }
  421. }
  422. }
  423. public override string Prefix {
  424. get { return String.Empty; }
  425. }
  426. public override ReadState ReadState {
  427. get { return read_state; }
  428. }
  429. public override string Value {
  430. get {
  431. switch (attr_state) {
  432. case AttributeState.Type:
  433. case AttributeState.TypeValue:
  434. return elements.Peek ().Type;
  435. case AttributeState.RuntimeType:
  436. case AttributeState.RuntimeTypeValue:
  437. return current_runtime_type;
  438. default:
  439. return current_node == XmlNodeType.Text ? simple_value : String.Empty;
  440. }
  441. }
  442. }
  443. public override void Close ()
  444. {
  445. if (on_close != null) {
  446. on_close (this);
  447. on_close = null;
  448. }
  449. read_state = ReadState.Closed;
  450. }
  451. public override string GetAttribute (int index)
  452. {
  453. if (index == 0 && current_node == XmlNodeType.Element)
  454. return elements.Peek ().Type;
  455. else if (index == 1 && current_runtime_type != null)
  456. return current_runtime_type;
  457. throw new ArgumentOutOfRangeException ("index", "Index is must be either 0 or 1 when there is an explicit __type in the object, and only valid on an element on this XmlDictionaryReader");
  458. }
  459. public override string GetAttribute (string name)
  460. {
  461. if (current_node != XmlNodeType.Element)
  462. return null;
  463. switch (name) {
  464. case "type":
  465. return elements.Peek ().Type;
  466. case "__type":
  467. return current_runtime_type;
  468. default:
  469. return null;
  470. }
  471. }
  472. public override string GetAttribute (string localName, string ns)
  473. {
  474. if (ns == String.Empty)
  475. return GetAttribute (localName);
  476. else
  477. return null;
  478. }
  479. public override string LookupNamespace (string prefix)
  480. {
  481. if (prefix == null)
  482. throw new ArgumentNullException ("prefix");
  483. else if (prefix.Length == 0)
  484. return String.Empty;
  485. return null;
  486. }
  487. public override bool MoveToAttribute (string name)
  488. {
  489. if (current_node != XmlNodeType.Element)
  490. return false;
  491. switch (name) {
  492. case "type":
  493. attr_state = AttributeState.Type;
  494. return true;
  495. case "__type":
  496. if (current_runtime_type == null)
  497. return false;
  498. attr_state = AttributeState.RuntimeType;
  499. return true;
  500. default:
  501. return false;
  502. }
  503. }
  504. public override bool MoveToAttribute (string localName, string ns)
  505. {
  506. if (ns != String.Empty)
  507. return false;
  508. return MoveToAttribute (localName);
  509. }
  510. public override bool MoveToElement ()
  511. {
  512. if (attr_state == AttributeState.None)
  513. return false;
  514. attr_state = AttributeState.None;
  515. return true;
  516. }
  517. public override bool MoveToFirstAttribute ()
  518. {
  519. if (current_node != XmlNodeType.Element)
  520. return false;
  521. attr_state = AttributeState.Type;
  522. return true;
  523. }
  524. public override bool MoveToNextAttribute ()
  525. {
  526. if (attr_state == AttributeState.None)
  527. return MoveToFirstAttribute ();
  528. else
  529. return MoveToAttribute ("__type");
  530. }
  531. public override bool ReadAttributeValue ()
  532. {
  533. switch (attr_state) {
  534. case AttributeState.Type:
  535. attr_state = AttributeState.TypeValue;
  536. return true;
  537. case AttributeState.RuntimeType:
  538. attr_state = AttributeState.RuntimeTypeValue;
  539. return true;
  540. }
  541. return false;
  542. }
  543. public override void ResolveEntity ()
  544. {
  545. throw new NotSupportedException ();
  546. }
  547. public override bool Read ()
  548. {
  549. switch (read_state) {
  550. case ReadState.EndOfFile:
  551. case ReadState.Closed:
  552. case ReadState.Error:
  553. return false;
  554. case ReadState.Initial:
  555. read_state = ReadState.Interactive;
  556. next_element = "root";
  557. current_node = XmlNodeType.Element;
  558. break;
  559. }
  560. MoveToElement ();
  561. if (content_stored) {
  562. if (current_node == XmlNodeType.Element) {
  563. if (elements.Peek ().Type == "null") {
  564. // since null is not consumed as text content, it skips Text state.
  565. current_node = XmlNodeType.EndElement;
  566. content_stored = false;
  567. }
  568. else
  569. current_node = XmlNodeType.Text;
  570. return true;
  571. } else if (current_node == XmlNodeType.Text) {
  572. current_node = XmlNodeType.EndElement;
  573. content_stored = false;
  574. return true;
  575. }
  576. }
  577. else if (current_node == XmlNodeType.EndElement) {
  578. // clear EndElement state
  579. elements.Pop ();
  580. if (elements.Count > 0)
  581. elements.Peek ().HasContent = true;
  582. else
  583. finished = true;
  584. }
  585. SkipWhitespaces ();
  586. attr_state = AttributeState.None;
  587. // Default. May be overriden only as EndElement or None.
  588. current_node = XmlNodeType.Element;
  589. if (!ReadContent (false))
  590. return false;
  591. if (finished)
  592. throw XmlError ("Multiple top-level content is not allowed");
  593. return true;
  594. }
  595. bool TryReadString (string str)
  596. {
  597. for (int i = 0; i < str.Length; i ++) {
  598. int ch = ReadChar ();
  599. if (ch != str[i]) {
  600. for (int j = i; j >= 0; j--)
  601. PushbackChar (j);
  602. return false;
  603. }
  604. }
  605. return true;
  606. }
  607. bool ReadContent (bool objectValue)
  608. {
  609. int ch = ReadChar ();
  610. if (ch < 0) {
  611. ReadEndOfStream ();
  612. return false;
  613. }
  614. bool itemMustFollow = false;
  615. if (!objectValue && elements.Count > 0 && elements.Peek ().HasContent) {
  616. if (ch == ',') {
  617. switch (elements.Peek ().Type) {
  618. case "object":
  619. case "array":
  620. SkipWhitespaces ();
  621. ch = ReadChar ();
  622. itemMustFollow = true;
  623. break;
  624. }
  625. }
  626. else if (ch != '}' && ch != ']')
  627. throw XmlError ("Comma is required unless an array or object is at the end");
  628. }
  629. if (elements.Count > 0 && elements.Peek ().Type == "array")
  630. next_element = "item";
  631. else if (next_object_content_name != null) {
  632. next_element = next_object_content_name;
  633. next_object_content_name = null;
  634. if (ch != ':')
  635. throw XmlError ("':' is expected after a name of an object content");
  636. SkipWhitespaces ();
  637. ReadContent (true);
  638. return true;
  639. }
  640. switch (ch) {
  641. case '{':
  642. ReadStartObject ();
  643. return true;
  644. case '[':
  645. ReadStartArray ();
  646. return true;
  647. case '}':
  648. if (itemMustFollow)
  649. throw XmlError ("Invalid comma before an end of object");
  650. if (objectValue)
  651. throw XmlError ("Invalid end of object as an object content");
  652. ReadEndObject ();
  653. return true;
  654. case ']':
  655. if (itemMustFollow)
  656. throw XmlError ("Invalid comma before an end of array");
  657. if (objectValue)
  658. throw XmlError ("Invalid end of array as an object content");
  659. ReadEndArray ();
  660. return true;
  661. case '"':
  662. bool lame = LameSilverlightLiteralParser && ch != '"';
  663. string s = ReadStringLiteral (lame);
  664. if (!objectValue && elements.Count > 0 && elements.Peek ().Type == "object") {
  665. next_element = s;
  666. SkipWhitespaces ();
  667. if (!lame)
  668. Expect (':');
  669. SkipWhitespaces ();
  670. ReadContent (true);
  671. }
  672. else
  673. ReadAsSimpleContent ("string", s);
  674. return true;
  675. case '-':
  676. ReadNumber (ch);
  677. return true;
  678. case 'n':
  679. if (TryReadString("ull")) {
  680. ReadAsSimpleContent ("null", "null");
  681. return true;
  682. }
  683. else {
  684. // the pushback for 'n' is taken care of by the
  685. // default case if we're in lame silverlight literal
  686. // mode
  687. goto default;
  688. }
  689. case 't':
  690. if (TryReadString ("rue")) {
  691. ReadAsSimpleContent ("boolean", "true");
  692. return true;
  693. }
  694. else {
  695. // the pushback for 't' is taken care of by the
  696. // default case if we're in lame silverlight literal
  697. // mode
  698. goto default;
  699. }
  700. case 'f':
  701. if (TryReadString ("alse")) {
  702. ReadAsSimpleContent ("boolean", "false");
  703. return true;
  704. }
  705. else {
  706. // the pushback for 'f' is taken care of by the
  707. // default case if we're in lame silverlight literal
  708. // mode
  709. goto default;
  710. }
  711. default:
  712. if ('0' <= ch && ch <= '9') {
  713. ReadNumber (ch);
  714. return true;
  715. }
  716. if (LameSilverlightLiteralParser) {
  717. PushbackChar (ch);
  718. goto case '"';
  719. }
  720. throw XmlError (String.Format ("Unexpected token: '{0}' ({1:X04})", (char) ch, (int) ch));
  721. }
  722. }
  723. void ReadStartObject ()
  724. {
  725. ElementInfo ei = new ElementInfo (next_element, "object");
  726. elements.Push (ei);
  727. SkipWhitespaces ();
  728. if (PeekChar () == '"') { // it isn't premise: the object might be empty
  729. ReadChar ();
  730. string s = ReadStringLiteral ();
  731. if (s == "__type") {
  732. SkipWhitespaces ();
  733. Expect (':');
  734. SkipWhitespaces ();
  735. Expect ('"');
  736. current_runtime_type = ReadStringLiteral ();
  737. SkipWhitespaces ();
  738. ei.HasContent = true;
  739. }
  740. else
  741. next_object_content_name = s;
  742. }
  743. }
  744. void ReadStartArray ()
  745. {
  746. elements.Push (new ElementInfo (next_element, "array"));
  747. }
  748. void ReadEndObject ()
  749. {
  750. if (elements.Count == 0 || elements.Peek ().Type != "object")
  751. throw XmlError ("Unexpected end of object");
  752. current_node = XmlNodeType.EndElement;
  753. }
  754. void ReadEndArray ()
  755. {
  756. if (elements.Count == 0 || elements.Peek ().Type != "array")
  757. throw XmlError ("Unexpected end of array");
  758. current_node = XmlNodeType.EndElement;
  759. }
  760. void ReadEndOfStream ()
  761. {
  762. if (elements.Count > 0)
  763. throw XmlError (String.Format ("{0} missing end of arrays or objects", elements.Count));
  764. read_state = ReadState.EndOfFile;
  765. current_node = XmlNodeType.None;
  766. }
  767. void ReadAsSimpleContent (string type, string value)
  768. {
  769. elements.Push (new ElementInfo (next_element, type));
  770. simple_value = value;
  771. content_stored = true;
  772. }
  773. void ReadNumber (int ch)
  774. {
  775. elements.Push (new ElementInfo (next_element, "number"));
  776. content_stored = true;
  777. int init = ch;
  778. int prev;
  779. bool floating = false, exp = false;
  780. StringBuilder sb = new StringBuilder ();
  781. bool cont = true;
  782. do {
  783. sb.Append ((char) ch);
  784. prev = ch;
  785. ch = ReadChar ();
  786. if (prev == '-' && !IsNumber (ch)) // neither '.', '-' or '+' nor anything else is valid
  787. throw XmlError ("Invalid JSON number");
  788. switch (ch) {
  789. case 'e':
  790. case 'E':
  791. if (exp)
  792. throw XmlError ("Invalid JSON number token. Either 'E' or 'e' must not occur more than once");
  793. if (!IsNumber (prev))
  794. throw XmlError ("Invalid JSON number token. only a number is valid before 'E' or 'e'");
  795. exp = true;
  796. break;
  797. case '.':
  798. if (floating)
  799. throw XmlError ("Invalid JSON number token. '.' must not occur twice");
  800. if (exp)
  801. throw XmlError ("Invalid JSON number token. '.' must not occur after 'E' or 'e'");
  802. floating = true;
  803. break;
  804. case '+':
  805. case '-':
  806. if (prev == 'E' || prev == 'e')
  807. break;
  808. goto default;
  809. default:
  810. if (!IsNumber (ch)) {
  811. PushbackChar (ch);
  812. cont = false;
  813. }
  814. break;
  815. }
  816. } while (cont);
  817. if (!IsNumber (prev)) // only number is valid at the end
  818. throw XmlError ("Invalid JSON number");
  819. simple_value = sb.ToString ();
  820. if (init == '0' && !floating && !exp && simple_value != "0")
  821. throw XmlError ("Invalid JSON number");
  822. }
  823. bool IsNumber (int c)
  824. {
  825. return '0' <= c && c <= '9';
  826. }
  827. StringBuilder vb = new StringBuilder ();
  828. string ReadStringLiteral ()
  829. {
  830. return ReadStringLiteral (false);
  831. }
  832. string ReadStringLiteral (bool endWithColon)
  833. {
  834. vb.Length = 0;
  835. while (true) {
  836. int c = ReadChar ();
  837. if (c < 0)
  838. throw XmlError ("JSON string is not closed");
  839. if (c == '"' && !endWithColon)
  840. return vb.ToString ();
  841. else if (c == ':' && endWithColon)
  842. return vb.ToString ();
  843. else if (c != '\\') {
  844. vb.Append ((char) c);
  845. continue;
  846. }
  847. // escaped expression
  848. c = ReadChar ();
  849. if (c < 0)
  850. throw XmlError ("Invalid JSON string literal; incomplete escape sequence");
  851. switch (c) {
  852. case '"':
  853. case '\\':
  854. case '/':
  855. vb.Append ((char) c);
  856. break;
  857. case 'b':
  858. vb.Append ('\x8');
  859. break;
  860. case 'f':
  861. vb.Append ('\f');
  862. break;
  863. case 'n':
  864. vb.Append ('\n');
  865. break;
  866. case 'r':
  867. vb.Append ('\r');
  868. break;
  869. case 't':
  870. vb.Append ('\t');
  871. break;
  872. case 'u':
  873. ushort cp = 0;
  874. for (int i = 0; i < 4; i++) {
  875. if ((c = ReadChar ()) < 0)
  876. throw XmlError ("Incomplete unicode character escape literal");
  877. cp *= 16;
  878. if ('0' <= c && c <= '9')
  879. cp += (ushort) (c - '0');
  880. if ('A' <= c && c <= 'F')
  881. cp += (ushort) (c - 'A' + 10);
  882. if ('a' <= c && c <= 'f')
  883. cp += (ushort) (c - 'a' + 10);
  884. }
  885. vb.Append ((char) cp);
  886. break;
  887. default:
  888. throw XmlError ("Invalid JSON string literal; unexpected escape character");
  889. }
  890. }
  891. }
  892. int PeekChar ()
  893. {
  894. return reader.Peek ();
  895. }
  896. int ReadChar ()
  897. {
  898. int v = reader.Read ();
  899. if (v == '\n') {
  900. line++;
  901. column = 0;
  902. }
  903. else
  904. column++;
  905. return v;
  906. }
  907. void PushbackChar (int ch)
  908. {
  909. // FIXME handle lines (and columns? ugh, how?)
  910. reader.Pushback (ch);
  911. }
  912. void SkipWhitespaces ()
  913. {
  914. do {
  915. switch (PeekChar ()) {
  916. case ' ':
  917. case '\t':
  918. case '\r':
  919. case '\n':
  920. ReadChar ();
  921. continue;
  922. default:
  923. return;
  924. }
  925. } while (true);
  926. }
  927. void Expect (char c)
  928. {
  929. int v = ReadChar ();
  930. if (v < 0)
  931. throw XmlError (String.Format ("Expected '{0}' but got EOF", c));
  932. if (v != c)
  933. throw XmlError (String.Format ("Expected '{0}' but got '{1}'", c, (char) v));
  934. }
  935. Exception XmlError (string s)
  936. {
  937. return new XmlException (String.Format ("{0} ({1},{2})", s, line, column));
  938. }
  939. // This reads the current element and all its content as a string,
  940. // with no processing done except for advancing the reader.
  941. public override string ReadInnerXml ()
  942. {
  943. if (NodeType != XmlNodeType.Element)
  944. return base.ReadInnerXml ();
  945. StringBuilder sb = new StringBuilder ();
  946. bool isobject = elements.Peek ().Type == "object";
  947. char end = isobject ? '}' : ']';
  948. char start = isobject ? '{' : '[';
  949. int count = 1;
  950. sb.Append (start);
  951. // add the first child manually, it's already been read
  952. // but hasn't been processed yet
  953. if (isobject && !String.IsNullOrEmpty (next_object_content_name))
  954. sb.Append ("\"" + next_object_content_name + "\"");
  955. // keep reading until we hit the end marker, no processing is
  956. // done on anything
  957. do {
  958. char c = (char)ReadChar ();
  959. sb.Append (c);
  960. if (c == start)
  961. ++count;
  962. else if (c == end)
  963. --count;
  964. } while (count > 0);
  965. // Replace the content we've read with an empty object so it gets
  966. // skipped on the following Read
  967. reader.Pushback (end);
  968. if (isobject) {
  969. reader.Pushback ('"');
  970. reader.Pushback ('"');
  971. reader.Pushback (':');
  972. }
  973. // Skip the element
  974. Read ();
  975. return sb.ToString ();
  976. }
  977. }
  978. }