JsonReader.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842
  1. //
  2. // JsonWriter.cs
  3. //
  4. // Author:
  5. // Atsushi Enomoto <[email protected]>
  6. //
  7. // Copyright (C) 2007 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. class PushbackReader : StreamReader
  37. {
  38. Stack<int> pushback;
  39. public PushbackReader (Stream stream, Encoding encoding) : base (stream, encoding)
  40. {
  41. pushback = new Stack<int>();
  42. }
  43. public PushbackReader (Stream stream) : base (stream, true)
  44. {
  45. pushback = new Stack<int>();
  46. }
  47. public override void Close ()
  48. {
  49. pushback.Clear ();
  50. }
  51. public override int Peek ()
  52. {
  53. if (pushback.Count > 0) {
  54. return pushback.Peek ();
  55. }
  56. else {
  57. return base.Peek ();
  58. }
  59. }
  60. public override int Read ()
  61. {
  62. if (pushback.Count > 0) {
  63. return pushback.Pop ();
  64. }
  65. else {
  66. return base.Read ();
  67. }
  68. }
  69. public void Pushback (int ch)
  70. {
  71. pushback.Push (ch);
  72. }
  73. }
  74. // FIXME: quotas check
  75. class JsonReader : XmlDictionaryReader, IXmlJsonReaderInitializer, IXmlLineInfo
  76. {
  77. class ElementInfo
  78. {
  79. public readonly string Name;
  80. public readonly string Type;
  81. public bool HasContent;
  82. public ElementInfo (string name, string type)
  83. {
  84. this.Name = name;
  85. this.Type = type;
  86. }
  87. }
  88. enum AttributeState
  89. {
  90. None,
  91. Type,
  92. TypeValue,
  93. RuntimeType,
  94. RuntimeTypeValue
  95. }
  96. PushbackReader reader;
  97. XmlDictionaryReaderQuotas quotas;
  98. OnXmlDictionaryReaderClose on_close;
  99. XmlNameTable name_table = new NameTable ();
  100. XmlNodeType current_node;
  101. AttributeState attr_state;
  102. string simple_value;
  103. string next_element;
  104. string current_runtime_type, next_object_content_name;
  105. ReadState read_state = ReadState.Initial;
  106. bool content_stored;
  107. bool finished;
  108. Stack<ElementInfo> elements = new Stack<ElementInfo> ();
  109. int line = 1, column = 0;
  110. // Constructors
  111. public JsonReader (byte [] buffer, int offset, int count, Encoding encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose)
  112. {
  113. SetInput (buffer, offset, count, encoding, quotas, onClose);
  114. }
  115. public JsonReader (Stream stream, Encoding encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose)
  116. {
  117. SetInput (stream, encoding, quotas, onClose);
  118. }
  119. internal bool LameSilverlightLiteralParser { get; set; }
  120. // IXmlLineInfo
  121. public bool HasLineInfo ()
  122. {
  123. return true;
  124. }
  125. public int LineNumber {
  126. get { return line; }
  127. }
  128. public int LinePosition {
  129. get { return column; }
  130. }
  131. // IXmlJsonReaderInitializer
  132. public void SetInput (byte [] buffer, int offset, int count, Encoding encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose)
  133. {
  134. SetInput (new MemoryStream (buffer, offset, count), encoding, quotas, onClose);
  135. }
  136. public void SetInput (Stream stream, Encoding encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose)
  137. {
  138. if (encoding != null)
  139. reader = new PushbackReader (stream, encoding);
  140. else
  141. reader = new PushbackReader (stream);
  142. if (quotas == null)
  143. throw new ArgumentNullException ("quotas");
  144. this.quotas = quotas;
  145. this.on_close = onClose;
  146. }
  147. // XmlDictionaryReader
  148. public override int AttributeCount {
  149. get { return current_node != XmlNodeType.Element ? 0 : current_runtime_type != null ? 2 : 1; }
  150. }
  151. public override string BaseURI {
  152. get { return String.Empty; }
  153. }
  154. public override int Depth {
  155. get {
  156. int mod = 0;
  157. switch (attr_state) {
  158. case AttributeState.Type:
  159. case AttributeState.RuntimeType:
  160. mod++;
  161. break;
  162. case AttributeState.TypeValue:
  163. case AttributeState.RuntimeTypeValue:
  164. mod += 2;
  165. break;
  166. case AttributeState.None:
  167. if (NodeType == XmlNodeType.Text)
  168. mod++;
  169. break;
  170. }
  171. return read_state != ReadState.Interactive ? 0 : elements.Count - 1 + mod;
  172. }
  173. }
  174. public override bool EOF {
  175. get {
  176. switch (read_state) {
  177. case ReadState.Closed:
  178. case ReadState.EndOfFile:
  179. return true;
  180. default:
  181. return false;
  182. }
  183. }
  184. }
  185. public override bool HasValue {
  186. get {
  187. switch (NodeType) {
  188. case XmlNodeType.Attribute:
  189. case XmlNodeType.Text:
  190. return true;
  191. default:
  192. return false;
  193. }
  194. }
  195. }
  196. public override bool IsEmptyElement {
  197. get { return false; }
  198. }
  199. public override string LocalName {
  200. get {
  201. switch (attr_state) {
  202. case AttributeState.Type:
  203. return "type";
  204. case AttributeState.RuntimeType:
  205. return "__type";
  206. }
  207. switch (NodeType) {
  208. case XmlNodeType.Element:
  209. case XmlNodeType.EndElement:
  210. return elements.Peek ().Name;
  211. default:
  212. return String.Empty;
  213. }
  214. }
  215. }
  216. public override string NamespaceURI {
  217. get { return String.Empty; }
  218. }
  219. public override XmlNameTable NameTable {
  220. get { return name_table; }
  221. }
  222. public override XmlNodeType NodeType {
  223. get {
  224. switch (attr_state) {
  225. case AttributeState.Type:
  226. case AttributeState.RuntimeType:
  227. return XmlNodeType.Attribute;
  228. case AttributeState.TypeValue:
  229. case AttributeState.RuntimeTypeValue:
  230. return XmlNodeType.Text;
  231. default:
  232. return current_node;
  233. }
  234. }
  235. }
  236. public override string Prefix {
  237. get { return String.Empty; }
  238. }
  239. public override ReadState ReadState {
  240. get { return read_state; }
  241. }
  242. public override string Value {
  243. get {
  244. switch (attr_state) {
  245. case AttributeState.Type:
  246. case AttributeState.TypeValue:
  247. return elements.Peek ().Type;
  248. case AttributeState.RuntimeType:
  249. case AttributeState.RuntimeTypeValue:
  250. return current_runtime_type;
  251. default:
  252. return current_node == XmlNodeType.Text ? simple_value : String.Empty;
  253. }
  254. }
  255. }
  256. public override void Close ()
  257. {
  258. if (on_close != null) {
  259. on_close (this);
  260. on_close = null;
  261. }
  262. read_state = ReadState.Closed;
  263. }
  264. public override string GetAttribute (int index)
  265. {
  266. if (index == 0 && current_node == XmlNodeType.Element)
  267. return elements.Peek ().Type;
  268. else if (index == 1 && current_runtime_type != null)
  269. return current_runtime_type;
  270. 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");
  271. }
  272. public override string GetAttribute (string name)
  273. {
  274. if (current_node != XmlNodeType.Element)
  275. return null;
  276. switch (name) {
  277. case "type":
  278. return elements.Peek ().Type;
  279. case "__type":
  280. return current_runtime_type;
  281. default:
  282. return null;
  283. }
  284. }
  285. public override string GetAttribute (string localName, string ns)
  286. {
  287. if (ns == String.Empty)
  288. return GetAttribute (localName);
  289. else
  290. return null;
  291. }
  292. public override string LookupNamespace (string prefix)
  293. {
  294. if (prefix == null)
  295. throw new ArgumentNullException ("prefix");
  296. else if (prefix.Length == 0)
  297. return String.Empty;
  298. return null;
  299. }
  300. public override bool MoveToAttribute (string name)
  301. {
  302. if (current_node != XmlNodeType.Element)
  303. return false;
  304. switch (name) {
  305. case "type":
  306. attr_state = AttributeState.Type;
  307. return true;
  308. case "__type":
  309. if (current_runtime_type == null)
  310. return false;
  311. attr_state = AttributeState.RuntimeType;
  312. return true;
  313. default:
  314. return false;
  315. }
  316. }
  317. public override bool MoveToAttribute (string localName, string ns)
  318. {
  319. if (ns != String.Empty)
  320. return false;
  321. return MoveToAttribute (localName);
  322. }
  323. public override bool MoveToElement ()
  324. {
  325. if (attr_state == AttributeState.None)
  326. return false;
  327. attr_state = AttributeState.None;
  328. return true;
  329. }
  330. public override bool MoveToFirstAttribute ()
  331. {
  332. if (current_node != XmlNodeType.Element)
  333. return false;
  334. attr_state = AttributeState.Type;
  335. return true;
  336. }
  337. public override bool MoveToNextAttribute ()
  338. {
  339. if (attr_state == AttributeState.None)
  340. return MoveToFirstAttribute ();
  341. else
  342. return MoveToAttribute ("__type");
  343. }
  344. public override bool ReadAttributeValue ()
  345. {
  346. switch (attr_state) {
  347. case AttributeState.Type:
  348. attr_state = AttributeState.TypeValue;
  349. return true;
  350. case AttributeState.RuntimeType:
  351. attr_state = AttributeState.RuntimeTypeValue;
  352. return true;
  353. }
  354. return false;
  355. }
  356. public override void ResolveEntity ()
  357. {
  358. throw new NotSupportedException ();
  359. }
  360. public override bool Read ()
  361. {
  362. switch (read_state) {
  363. case ReadState.EndOfFile:
  364. case ReadState.Closed:
  365. case ReadState.Error:
  366. return false;
  367. case ReadState.Initial:
  368. read_state = ReadState.Interactive;
  369. next_element = "root";
  370. current_node = XmlNodeType.Element;
  371. break;
  372. }
  373. MoveToElement ();
  374. if (content_stored) {
  375. if (current_node == XmlNodeType.Element) {
  376. if (elements.Peek ().Type == "null") {
  377. // since null is not consumed as text content, it skips Text state.
  378. current_node = XmlNodeType.EndElement;
  379. content_stored = false;
  380. }
  381. else
  382. current_node = XmlNodeType.Text;
  383. return true;
  384. } else if (current_node == XmlNodeType.Text) {
  385. current_node = XmlNodeType.EndElement;
  386. content_stored = false;
  387. return true;
  388. }
  389. }
  390. else if (current_node == XmlNodeType.EndElement) {
  391. // clear EndElement state
  392. elements.Pop ();
  393. if (elements.Count > 0)
  394. elements.Peek ().HasContent = true;
  395. else
  396. finished = true;
  397. }
  398. SkipWhitespaces ();
  399. attr_state = AttributeState.None;
  400. // Default. May be overriden only as EndElement or None.
  401. current_node = XmlNodeType.Element;
  402. if (!ReadContent (false))
  403. return false;
  404. if (finished)
  405. throw XmlError ("Multiple top-level content is not allowed");
  406. return true;
  407. }
  408. bool TryReadString (string str)
  409. {
  410. for (int i = 0; i < str.Length; i ++) {
  411. int ch = ReadChar ();
  412. if (ch != str[i]) {
  413. for (int j = i; j >= 0; j--)
  414. PushbackChar (j);
  415. return false;
  416. }
  417. }
  418. return true;
  419. }
  420. bool ReadContent (bool objectValue)
  421. {
  422. int ch = ReadChar ();
  423. if (ch < 0) {
  424. ReadEndOfStream ();
  425. return false;
  426. }
  427. bool itemMustFollow = false;
  428. if (!objectValue && elements.Count > 0 && elements.Peek ().HasContent) {
  429. if (ch == ',') {
  430. switch (elements.Peek ().Type) {
  431. case "object":
  432. case "array":
  433. SkipWhitespaces ();
  434. ch = ReadChar ();
  435. itemMustFollow = true;
  436. break;
  437. }
  438. }
  439. else if (ch != '}' && ch != ']')
  440. throw XmlError ("Comma is required unless an array or object is at the end");
  441. }
  442. if (elements.Count > 0 && elements.Peek ().Type == "array")
  443. next_element = "item";
  444. else if (next_object_content_name != null) {
  445. next_element = next_object_content_name;
  446. next_object_content_name = null;
  447. if (ch != ':')
  448. throw XmlError ("':' is expected after a name of an object content");
  449. SkipWhitespaces ();
  450. ReadContent (true);
  451. return true;
  452. }
  453. switch (ch) {
  454. case '{':
  455. ReadStartObject ();
  456. return true;
  457. case '[':
  458. ReadStartArray ();
  459. return true;
  460. case '}':
  461. if (itemMustFollow)
  462. throw XmlError ("Invalid comma before an end of object");
  463. if (objectValue)
  464. throw XmlError ("Invalid end of object as an object content");
  465. ReadEndObject ();
  466. return true;
  467. case ']':
  468. if (itemMustFollow)
  469. throw XmlError ("Invalid comma before an end of array");
  470. if (objectValue)
  471. throw XmlError ("Invalid end of array as an object content");
  472. ReadEndArray ();
  473. return true;
  474. case '"':
  475. bool lame = LameSilverlightLiteralParser && ch != '"';
  476. string s = ReadStringLiteral (lame);
  477. if (!objectValue && elements.Count > 0 && elements.Peek ().Type == "object") {
  478. next_element = s;
  479. SkipWhitespaces ();
  480. if (!lame)
  481. Expect (':');
  482. SkipWhitespaces ();
  483. ReadContent (true);
  484. }
  485. else
  486. ReadAsSimpleContent ("string", s);
  487. return true;
  488. case '-':
  489. ReadNumber (ch);
  490. return true;
  491. case 'n':
  492. if (TryReadString("ull")) {
  493. ReadAsSimpleContent ("null", "null");
  494. return true;
  495. }
  496. else {
  497. // the pushback for 'n' is taken care of by the
  498. // default case if we're in lame silverlight literal
  499. // mode
  500. goto default;
  501. }
  502. case 't':
  503. if (TryReadString ("rue")) {
  504. ReadAsSimpleContent ("boolean", "true");
  505. return true;
  506. }
  507. else {
  508. // the pushback for 't' is taken care of by the
  509. // default case if we're in lame silverlight literal
  510. // mode
  511. goto default;
  512. }
  513. case 'f':
  514. if (TryReadString ("alse")) {
  515. ReadAsSimpleContent ("boolean", "false");
  516. return true;
  517. }
  518. else {
  519. // the pushback for 'f' is taken care of by the
  520. // default case if we're in lame silverlight literal
  521. // mode
  522. goto default;
  523. }
  524. default:
  525. if ('0' <= ch && ch <= '9') {
  526. ReadNumber (ch);
  527. return true;
  528. }
  529. if (LameSilverlightLiteralParser) {
  530. PushbackChar (ch);
  531. goto case '"';
  532. }
  533. throw XmlError (String.Format ("Unexpected token: '{0}' ({1:X04})", (char) ch, (int) ch));
  534. }
  535. }
  536. void ReadStartObject ()
  537. {
  538. ElementInfo ei = new ElementInfo (next_element, "object");
  539. elements.Push (ei);
  540. SkipWhitespaces ();
  541. if (PeekChar () == '"') { // it isn't premise: the object might be empty
  542. ReadChar ();
  543. string s = ReadStringLiteral ();
  544. if (s == "__type") {
  545. SkipWhitespaces ();
  546. Expect (':');
  547. SkipWhitespaces ();
  548. Expect ('"');
  549. current_runtime_type = ReadStringLiteral ();
  550. SkipWhitespaces ();
  551. ei.HasContent = true;
  552. }
  553. else
  554. next_object_content_name = s;
  555. }
  556. }
  557. void ReadStartArray ()
  558. {
  559. elements.Push (new ElementInfo (next_element, "array"));
  560. }
  561. void ReadEndObject ()
  562. {
  563. if (elements.Count == 0 || elements.Peek ().Type != "object")
  564. throw XmlError ("Unexpected end of object");
  565. current_node = XmlNodeType.EndElement;
  566. }
  567. void ReadEndArray ()
  568. {
  569. if (elements.Count == 0 || elements.Peek ().Type != "array")
  570. throw XmlError ("Unexpected end of array");
  571. current_node = XmlNodeType.EndElement;
  572. }
  573. void ReadEndOfStream ()
  574. {
  575. if (elements.Count > 0)
  576. throw XmlError (String.Format ("{0} missing end of arrays or objects", elements.Count));
  577. read_state = ReadState.EndOfFile;
  578. current_node = XmlNodeType.None;
  579. }
  580. void ReadAsSimpleContent (string type, string value)
  581. {
  582. elements.Push (new ElementInfo (next_element, type));
  583. simple_value = value;
  584. content_stored = true;
  585. }
  586. void ReadNumber (int ch)
  587. {
  588. elements.Push (new ElementInfo (next_element, "number"));
  589. content_stored = true;
  590. int init = ch;
  591. int prev;
  592. bool floating = false, exp = false;
  593. StringBuilder sb = new StringBuilder ();
  594. bool cont = true;
  595. do {
  596. sb.Append ((char) ch);
  597. prev = ch;
  598. ch = ReadChar ();
  599. if (prev == '-' && !IsNumber (ch)) // neither '.', '-' or '+' nor anything else is valid
  600. throw XmlError ("Invalid JSON number");
  601. switch (ch) {
  602. case 'e':
  603. case 'E':
  604. if (exp)
  605. throw XmlError ("Invalid JSON number token. Either 'E' or 'e' must not occur more than once");
  606. if (!IsNumber (prev))
  607. throw XmlError ("Invalid JSON number token. only a number is valid before 'E' or 'e'");
  608. exp = true;
  609. break;
  610. case '.':
  611. if (floating)
  612. throw XmlError ("Invalid JSON number token. '.' must not occur twice");
  613. if (exp)
  614. throw XmlError ("Invalid JSON number token. '.' must not occur after 'E' or 'e'");
  615. floating = true;
  616. break;
  617. case '+':
  618. case '-':
  619. if (prev == 'E' || prev == 'e')
  620. break;
  621. goto default;
  622. default:
  623. if (!IsNumber (ch)) {
  624. PushbackChar (ch);
  625. cont = false;
  626. }
  627. break;
  628. }
  629. } while (cont);
  630. if (!IsNumber (prev)) // only number is valid at the end
  631. throw XmlError ("Invalid JSON number");
  632. simple_value = sb.ToString ();
  633. if (init == '0' && !floating && !exp && simple_value != "0")
  634. throw XmlError ("Invalid JSON number");
  635. }
  636. bool IsNumber (int c)
  637. {
  638. return '0' <= c && c <= '9';
  639. }
  640. StringBuilder vb = new StringBuilder ();
  641. string ReadStringLiteral ()
  642. {
  643. return ReadStringLiteral (false);
  644. }
  645. string ReadStringLiteral (bool endWithColon)
  646. {
  647. vb.Length = 0;
  648. while (true) {
  649. int c = ReadChar ();
  650. if (c < 0)
  651. throw XmlError ("JSON string is not closed");
  652. if (c == '"' && !endWithColon)
  653. return vb.ToString ();
  654. else if (c == ':' && endWithColon)
  655. return vb.ToString ();
  656. else if (c != '\\') {
  657. vb.Append ((char) c);
  658. continue;
  659. }
  660. // escaped expression
  661. c = ReadChar ();
  662. if (c < 0)
  663. throw XmlError ("Invalid JSON string literal; incomplete escape sequence");
  664. switch (c) {
  665. case '"':
  666. case '\\':
  667. case '/':
  668. vb.Append ((char) c);
  669. break;
  670. case 'b':
  671. vb.Append ('\x8');
  672. break;
  673. case 'f':
  674. vb.Append ('\f');
  675. break;
  676. case 'n':
  677. vb.Append ('\n');
  678. break;
  679. case 'r':
  680. vb.Append ('\r');
  681. break;
  682. case 't':
  683. vb.Append ('\t');
  684. break;
  685. case 'u':
  686. ushort cp = 0;
  687. for (int i = 0; i < 4; i++) {
  688. if ((c = ReadChar ()) < 0)
  689. throw XmlError ("Incomplete unicode character escape literal");
  690. cp *= 16;
  691. if ('0' <= c && c <= '9')
  692. cp += (ushort) (c - '0');
  693. if ('A' <= c && c <= 'F')
  694. cp += (ushort) (c - 'A' + 10);
  695. if ('a' <= c && c <= 'f')
  696. cp += (ushort) (c - 'a' + 10);
  697. }
  698. vb.Append ((char) cp);
  699. break;
  700. default:
  701. throw XmlError ("Invalid JSON string literal; unexpected escape character");
  702. }
  703. }
  704. }
  705. int PeekChar ()
  706. {
  707. return reader.Peek ();
  708. }
  709. int ReadChar ()
  710. {
  711. int v = reader.Read ();
  712. if (v == '\n') {
  713. line++;
  714. column = 0;
  715. }
  716. else
  717. column++;
  718. return v;
  719. }
  720. void PushbackChar (int ch)
  721. {
  722. // FIXME handle lines (and columns? ugh, how?)
  723. reader.Pushback (ch);
  724. }
  725. void SkipWhitespaces ()
  726. {
  727. do {
  728. switch (PeekChar ()) {
  729. case ' ':
  730. case '\t':
  731. case '\r':
  732. case '\n':
  733. ReadChar ();
  734. continue;
  735. default:
  736. return;
  737. }
  738. } while (true);
  739. }
  740. void Expect (char c)
  741. {
  742. int v = ReadChar ();
  743. if (v < 0)
  744. throw XmlError (String.Format ("Expected '{0}' but got EOF", c));
  745. if (v != c)
  746. throw XmlError (String.Format ("Expected '{0}' but got '{1}'", c, (char) v));
  747. }
  748. Exception XmlError (string s)
  749. {
  750. return new XmlException (String.Format ("{0} ({1},{2})", s, line, column));
  751. }
  752. }
  753. }