PageRenderTime 50ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/trunk/managed/Json131/Src/Newtonsoft.Json/JsonReader.cs

https://bitbucket.org/KyanhaLLC/opensim-libs
C# | 897 lines | 814 code | 30 blank | 53 comment | 32 complexity | c451b3e81a262615681d2757952cc0f6 MD5 | raw file
Possible License(s): Apache-2.0, BSD-2-Clause, MIT, LGPL-2.1, LGPL-3.0, GPL-2.0, CC-BY-SA-3.0, GPL-3.0, BSD-3-Clause
  1. #region License
  2. // Copyright (c) 2007 James Newton-King
  3. //
  4. // Permission is hereby granted, free of charge, to any person
  5. // obtaining a copy of this software and associated documentation
  6. // files (the "Software"), to deal in the Software without
  7. // restriction, including without limitation the rights to use,
  8. // copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the
  10. // Software is furnished to do so, subject to the following
  11. // conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be
  14. // included in all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  17. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  18. // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  19. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  20. // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  21. // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  22. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  23. // OTHER DEALINGS IN THE SOFTWARE.
  24. #endregion
  25. using System;
  26. using System.Collections.Generic;
  27. using System.Text;
  28. using System.IO;
  29. using System.Xml;
  30. using System.Globalization;
  31. namespace Newtonsoft.Json
  32. {
  33. /// <summary>
  34. /// Represents a reader that provides fast, non-cached, forward-only access to serialized Json data.
  35. /// </summary>
  36. public class JsonReader : IDisposable
  37. {
  38. private enum State
  39. {
  40. Start,
  41. Complete,
  42. Property,
  43. ObjectStart,
  44. Object,
  45. ArrayStart,
  46. Array,
  47. Closed,
  48. PostValue,
  49. Constructor,
  50. ConstructorEnd,
  51. Error,
  52. Finished
  53. }
  54. private TextReader _reader;
  55. private char _currentChar;
  56. // current Token data
  57. private JsonToken _token;
  58. private object _value;
  59. private Type _valueType;
  60. private char _quoteChar;
  61. private StringBuffer _buffer;
  62. //private StringBuilder _testBuffer;
  63. private State _currentState;
  64. private int _top;
  65. private List<JsonType> _stack;
  66. /// <summary>
  67. /// Gets the quotation mark character used to enclose the value of a string.
  68. /// </summary>
  69. public char QuoteChar
  70. {
  71. get { return _quoteChar; }
  72. }
  73. /// <summary>
  74. /// Gets the type of the current Json token.
  75. /// </summary>
  76. public JsonToken TokenType
  77. {
  78. get { return _token; }
  79. }
  80. /// <summary>
  81. /// Gets the text value of the current Json token.
  82. /// </summary>
  83. public object Value
  84. {
  85. get { return _value; }
  86. }
  87. /// <summary>
  88. /// Gets The Common Language Runtime (CLR) type for the current Json token.
  89. /// </summary>
  90. public Type ValueType
  91. {
  92. get { return _valueType; }
  93. }
  94. /// <summary>
  95. /// Initializes a new instance of the <see cref="JsonReader"/> class with the specified <see cref="TextReader"/>.
  96. /// </summary>
  97. /// <param name="reader">The <c>TextReader</c> containing the XML data to read.</param>
  98. public JsonReader(TextReader reader)
  99. {
  100. if (reader == null)
  101. throw new ArgumentNullException("reader");
  102. _reader = reader;
  103. _buffer = new StringBuffer(4096);
  104. //_testBuffer = new StringBuilder();
  105. _currentState = State.Start;
  106. _stack = new List<JsonType>();
  107. _top = 0;
  108. Push(JsonType.None);
  109. }
  110. private void Push(JsonType value)
  111. {
  112. _stack.Add(value);
  113. _top++;
  114. }
  115. private JsonType Pop()
  116. {
  117. JsonType value = Peek();
  118. _stack.RemoveAt(_stack.Count - 1);
  119. _top--;
  120. return value;
  121. }
  122. private JsonType Peek()
  123. {
  124. return _stack[_top - 1];
  125. }
  126. private void ParseString(char quote)
  127. {
  128. bool stringTerminated = false;
  129. while (!stringTerminated && MoveNext())
  130. {
  131. switch (_currentChar)
  132. {
  133. //case 0:
  134. //case 0x0A:
  135. //case 0x0D:
  136. // throw new JsonReaderException("Unterminated string");
  137. case '\\':
  138. if (MoveNext())
  139. {
  140. switch (_currentChar)
  141. {
  142. case 'b':
  143. _buffer.Append('\b');
  144. break;
  145. case 't':
  146. _buffer.Append('\t');
  147. break;
  148. case 'n':
  149. _buffer.Append('\n');
  150. break;
  151. case 'f':
  152. _buffer.Append('\f');
  153. break;
  154. case 'r':
  155. _buffer.Append('\r');
  156. break;
  157. case 'u':
  158. //_buffer.Append((char) Integer.parseInt(next(4), 16));
  159. break;
  160. case 'x':
  161. //_buffer.Append((char) Integer.parseInt(next(2), 16));
  162. break;
  163. default:
  164. _buffer.Append(_currentChar);
  165. break;
  166. }
  167. }
  168. else
  169. {
  170. throw new JsonReaderException("Unterminated string. Expected delimiter: " + quote);
  171. }
  172. break;
  173. case '"':
  174. case '\'':
  175. if (_currentChar == quote)
  176. stringTerminated = true;
  177. else
  178. goto default;
  179. break;
  180. default:
  181. _buffer.Append(_currentChar);
  182. break;
  183. }
  184. }
  185. if (!stringTerminated)
  186. throw new JsonReaderException("Unterminated string. Expected delimiter: " + quote);
  187. ClearCurrentChar();
  188. _currentState = State.PostValue;
  189. _token = JsonToken.String;
  190. _value = _buffer.ToString();
  191. _buffer.Position = 0;
  192. _valueType = typeof(string);
  193. _quoteChar = quote;
  194. }
  195. private bool MoveNext()
  196. {
  197. int value = _reader.Read();
  198. if (value != -1)
  199. {
  200. _currentChar = (char)value;
  201. //_testBuffer.Append(_currentChar);
  202. return true;
  203. }
  204. else
  205. {
  206. return false;
  207. }
  208. }
  209. private bool HasNext()
  210. {
  211. return (_reader.Peek() != -1);
  212. }
  213. private char PeekNext()
  214. {
  215. return (char)_reader.Peek();
  216. }
  217. private void ClearCurrentChar()
  218. {
  219. _currentChar = '\0';
  220. }
  221. private bool MoveTo(char value)
  222. {
  223. while (MoveNext())
  224. {
  225. if (_currentChar == value)
  226. return true;
  227. }
  228. return false;
  229. }
  230. /// <summary>
  231. /// Reads the next Json token from the stream.
  232. /// </summary>
  233. /// <returns></returns>
  234. public bool Read()
  235. {
  236. while (true)
  237. {
  238. if (_currentChar == '\0')
  239. {
  240. if (!MoveNext())
  241. return false;
  242. }
  243. switch (_currentState)
  244. {
  245. case State.Start:
  246. case State.Property:
  247. case State.Array:
  248. case State.ArrayStart:
  249. return ParseValue();
  250. case State.Complete:
  251. break;
  252. case State.Object:
  253. case State.ObjectStart:
  254. return ParseObject();
  255. case State.PostValue:
  256. // returns true if it hits
  257. // end of object or array
  258. if (ParsePostValue())
  259. return true;
  260. break;
  261. case State.Closed:
  262. break;
  263. case State.Error:
  264. break;
  265. default:
  266. throw new JsonReaderException("Unexpected state: " + _currentState);
  267. }
  268. }
  269. }
  270. private bool ParsePostValue()
  271. {
  272. do
  273. {
  274. switch (_currentChar)
  275. {
  276. case '}':
  277. SetToken(JsonToken.EndObject);
  278. ClearCurrentChar();
  279. return true;
  280. case ']':
  281. SetToken(JsonToken.EndArray);
  282. ClearCurrentChar();
  283. return true;
  284. case '/':
  285. ParseComment();
  286. return true;
  287. case ',':
  288. // finished paring
  289. SetStateBasedOnCurrent();
  290. ClearCurrentChar();
  291. return false;
  292. default:
  293. if (char.IsWhiteSpace(_currentChar))
  294. {
  295. // eat whitespace
  296. ClearCurrentChar();
  297. }
  298. else
  299. {
  300. throw new JsonReaderException("After parsing a value an unexpected character was encoutered: " + _currentChar);
  301. }
  302. break;
  303. }
  304. } while (MoveNext());
  305. return false;
  306. }
  307. private bool ParseObject()
  308. {
  309. do
  310. {
  311. switch (_currentChar)
  312. {
  313. case '}':
  314. SetToken(JsonToken.EndObject);
  315. return true;
  316. case '/':
  317. ParseComment();
  318. return true;
  319. case ',':
  320. SetToken(JsonToken.Undefined);
  321. return true;
  322. default:
  323. if (char.IsWhiteSpace(_currentChar))
  324. {
  325. // eat
  326. }
  327. else
  328. {
  329. return ParseProperty();
  330. }
  331. break;
  332. }
  333. } while (MoveNext());
  334. return false;
  335. }
  336. private bool ParseProperty()
  337. {
  338. if (ValidIdentifierChar(_currentChar))
  339. {
  340. ParseUnquotedProperty();
  341. }
  342. else if (_currentChar == '"' || _currentChar == '\'')
  343. {
  344. ParseQuotedProperty(_currentChar);
  345. }
  346. else
  347. {
  348. throw new JsonReaderException("Invalid property identifier character: " + _currentChar);
  349. }
  350. // finished property. move to colon
  351. if (_currentChar != ':')
  352. {
  353. MoveTo(':');
  354. }
  355. SetToken(JsonToken.PropertyName, _buffer.ToString());
  356. _buffer.Position = 0;
  357. return true;
  358. }
  359. private void ParseQuotedProperty(char quoteChar)
  360. {
  361. // parse property name until quoted char is hit
  362. while (MoveNext())
  363. {
  364. if (_currentChar == quoteChar)
  365. {
  366. return;
  367. }
  368. else
  369. {
  370. _buffer.Append(_currentChar);
  371. }
  372. }
  373. throw new JsonReaderException("Unclosed quoted property. Expected: " + quoteChar);
  374. }
  375. private bool ValidIdentifierChar(char value)
  376. {
  377. return (char.IsLetterOrDigit(_currentChar) || _currentChar == '_' || _currentChar == '$');
  378. }
  379. private void ParseUnquotedProperty()
  380. {
  381. // parse unquoted property name until whitespace or colon
  382. _buffer.Append(_currentChar);
  383. while (MoveNext())
  384. {
  385. if (char.IsWhiteSpace(_currentChar) || _currentChar == ':')
  386. {
  387. break;
  388. }
  389. else if (ValidIdentifierChar(_currentChar))
  390. {
  391. _buffer.Append(_currentChar);
  392. }
  393. else
  394. {
  395. throw new JsonReaderException("Invalid JavaScript property identifier character: " + _currentChar);
  396. }
  397. }
  398. }
  399. private void SetToken(JsonToken newToken)
  400. {
  401. SetToken(newToken, null);
  402. }
  403. private void SetToken(JsonToken newToken, object value)
  404. {
  405. _token = newToken;
  406. switch (newToken)
  407. {
  408. case JsonToken.StartObject:
  409. _currentState = State.ObjectStart;
  410. Push(JsonType.Object);
  411. ClearCurrentChar();
  412. break;
  413. case JsonToken.StartArray:
  414. _currentState = State.ArrayStart;
  415. Push(JsonType.Array);
  416. ClearCurrentChar();
  417. break;
  418. case JsonToken.EndObject:
  419. ValidateEnd(JsonToken.EndObject);
  420. ClearCurrentChar();
  421. _currentState = State.PostValue;
  422. break;
  423. case JsonToken.EndArray:
  424. ValidateEnd(JsonToken.EndArray);
  425. ClearCurrentChar();
  426. _currentState = State.PostValue;
  427. break;
  428. case JsonToken.PropertyName:
  429. _currentState = State.Property;
  430. ClearCurrentChar();
  431. break;
  432. case JsonToken.Undefined:
  433. case JsonToken.Integer:
  434. case JsonToken.Float:
  435. case JsonToken.Boolean:
  436. case JsonToken.Null:
  437. case JsonToken.Constructor:
  438. case JsonToken.Date:
  439. _currentState = State.PostValue;
  440. break;
  441. }
  442. if (value != null)
  443. {
  444. _value = value;
  445. _valueType = value.GetType();
  446. }
  447. else
  448. {
  449. _value = null;
  450. _valueType = null;
  451. }
  452. }
  453. private bool ParseValue()
  454. {
  455. do
  456. {
  457. switch (_currentChar)
  458. {
  459. case '"':
  460. case '\'':
  461. ParseString(_currentChar);
  462. return true;
  463. case 't':
  464. ParseTrue();
  465. return true;
  466. case 'f':
  467. ParseFalse();
  468. return true;
  469. case 'n':
  470. if (HasNext())
  471. {
  472. char next = PeekNext();
  473. if (next == 'u')
  474. ParseNull();
  475. else if (next == 'e')
  476. ParseConstructor();
  477. else
  478. throw new JsonReaderException("Unexpected character encountered while parsing value: " + _currentChar);
  479. }
  480. else
  481. {
  482. throw new JsonReaderException("Unexpected end");
  483. }
  484. return true;
  485. case '/':
  486. ParseComment();
  487. return true;
  488. case 'u':
  489. ParseUndefined();
  490. return true;
  491. case '{':
  492. SetToken(JsonToken.StartObject);
  493. return true;
  494. case '[':
  495. SetToken(JsonToken.StartArray);
  496. return true;
  497. case '}':
  498. SetToken(JsonToken.EndObject);
  499. return true;
  500. case ']':
  501. SetToken(JsonToken.EndArray);
  502. return true;
  503. case ',':
  504. SetToken(JsonToken.Undefined);
  505. //ClearCurrentChar();
  506. return true;
  507. case ')':
  508. if (_currentState == State.Constructor)
  509. {
  510. _currentState = State.ConstructorEnd;
  511. return false;
  512. }
  513. else
  514. {
  515. throw new JsonReaderException("Unexpected character encountered while parsing value: " + _currentChar);
  516. }
  517. default:
  518. if (char.IsWhiteSpace(_currentChar))
  519. {
  520. // eat
  521. }
  522. else if (char.IsNumber(_currentChar) || _currentChar == '-' || _currentChar == '.')
  523. {
  524. ParseNumber();
  525. return true;
  526. }
  527. else
  528. {
  529. throw new JsonReaderException("Unexpected character encountered while parsing value: " + _currentChar);
  530. }
  531. break;
  532. }
  533. } while (MoveNext());
  534. return false;
  535. }
  536. private bool EatWhitespace(bool oneOrMore)
  537. {
  538. bool whitespace = false;
  539. while (char.IsWhiteSpace(_currentChar))
  540. {
  541. whitespace = true;
  542. MoveNext();
  543. }
  544. return (!oneOrMore || whitespace);
  545. }
  546. private void ParseConstructor()
  547. {
  548. if (MatchValue("new", true))
  549. {
  550. if (EatWhitespace(true))
  551. {
  552. while (char.IsLetter(_currentChar))
  553. {
  554. _buffer.Append(_currentChar);
  555. MoveNext();
  556. }
  557. string constructorName = _buffer.ToString();
  558. _buffer.Position = 0;
  559. List<object> parameters = new List<object>();
  560. EatWhitespace(false);
  561. if (_currentChar == '(' && MoveNext())
  562. {
  563. _currentState = State.Constructor;
  564. while (ParseValue())
  565. {
  566. parameters.Add(_value);
  567. _currentState = State.Constructor;
  568. }
  569. if (string.CompareOrdinal(constructorName, "Date") == 0)
  570. {
  571. long javaScriptTicks = Convert.ToInt64(parameters[0]);
  572. DateTime date = JavaScriptConvert.ConvertJavaScriptTicksToDateTime(javaScriptTicks);
  573. SetToken(JsonToken.Date, date);
  574. }
  575. else
  576. {
  577. JavaScriptConstructor constructor = new JavaScriptConstructor(constructorName, new JavaScriptParameters(parameters));
  578. if (_currentState == State.ConstructorEnd)
  579. {
  580. SetToken(JsonToken.Constructor, constructor);
  581. }
  582. }
  583. // move past ')'
  584. MoveNext();
  585. }
  586. }
  587. }
  588. }
  589. private void ParseNumber()
  590. {
  591. // parse until seperator character or end
  592. bool end = false;
  593. do
  594. {
  595. if (CurrentIsSeperator())
  596. end = true;
  597. else
  598. _buffer.Append(_currentChar);
  599. } while (!end && MoveNext());
  600. string number = _buffer.ToString();
  601. object numberValue;
  602. JsonToken numberType;
  603. if (number.IndexOf('.') == -1)
  604. {
  605. numberValue = Convert.ToInt64(_buffer.ToString(), CultureInfo.InvariantCulture);
  606. numberType = JsonToken.Integer;
  607. }
  608. else
  609. {
  610. numberValue = Convert.ToDouble(_buffer.ToString(), CultureInfo.InvariantCulture);
  611. numberType = JsonToken.Float;
  612. }
  613. _buffer.Position = 0;
  614. SetToken(numberType, numberValue);
  615. }
  616. private void ValidateEnd(JsonToken endToken)
  617. {
  618. JsonType currentObject = Pop();
  619. if (GetTypeForCloseToken(endToken) != currentObject)
  620. throw new JsonReaderException(string.Format("JsonToken {0} is not valid for closing JsonType {1}.", endToken, currentObject));
  621. }
  622. private void SetStateBasedOnCurrent()
  623. {
  624. JsonType currentObject = Peek();
  625. switch (currentObject)
  626. {
  627. case JsonType.Object:
  628. _currentState = State.Object;
  629. break;
  630. case JsonType.Array:
  631. _currentState = State.Array;
  632. break;
  633. case JsonType.None:
  634. _currentState = State.Finished;
  635. break;
  636. default:
  637. throw new JsonReaderException("While setting the reader state back to current object an unexpected JsonType was encountered: " + currentObject);
  638. }
  639. }
  640. private JsonType GetTypeForCloseToken(JsonToken token)
  641. {
  642. switch (token)
  643. {
  644. case JsonToken.EndObject:
  645. return JsonType.Object;
  646. case JsonToken.EndArray:
  647. return JsonType.Array;
  648. default:
  649. throw new JsonReaderException("Not a valid close JsonToken: " + token);
  650. }
  651. }
  652. private void ParseComment()
  653. {
  654. // should have already parsed / character before reaching this method
  655. MoveNext();
  656. if (_currentChar == '*')
  657. {
  658. while (MoveNext())
  659. {
  660. if (_currentChar == '*')
  661. {
  662. if (MoveNext())
  663. {
  664. if (_currentChar == '/')
  665. {
  666. break;
  667. }
  668. else
  669. {
  670. _buffer.Append('*');
  671. _buffer.Append(_currentChar);
  672. }
  673. }
  674. }
  675. else
  676. {
  677. _buffer.Append(_currentChar);
  678. }
  679. }
  680. }
  681. else
  682. {
  683. throw new JsonReaderException("Error parsing comment. Expected: *");
  684. }
  685. SetToken(JsonToken.Comment, _buffer.ToString());
  686. _buffer.Position = 0;
  687. ClearCurrentChar();
  688. }
  689. private bool MatchValue(string value)
  690. {
  691. int i = 0;
  692. do
  693. {
  694. if (_currentChar != value[i])
  695. {
  696. break;
  697. }
  698. i++;
  699. }
  700. while (i < value.Length && MoveNext());
  701. return (i == value.Length);
  702. }
  703. private bool MatchValue(string value, bool noTrailingNonSeperatorCharacters)
  704. {
  705. // will match value and then move to the next character, checking that it is a seperator character
  706. bool match = MatchValue(value);
  707. if (!noTrailingNonSeperatorCharacters)
  708. return match;
  709. else
  710. return (match && (!MoveNext() || CurrentIsSeperator()));
  711. }
  712. private bool CurrentIsSeperator()
  713. {
  714. switch (_currentChar)
  715. {
  716. case '}':
  717. case ']':
  718. case ',':
  719. return true;
  720. case '/':
  721. // check next character to see if start of a comment
  722. return (HasNext() && PeekNext() == '*');
  723. case ')':
  724. if (_currentState == State.Constructor)
  725. return true;
  726. break;
  727. default:
  728. if (char.IsWhiteSpace(_currentChar))
  729. return true;
  730. break;
  731. }
  732. return false;
  733. }
  734. private void ParseTrue()
  735. {
  736. // check characters equal 'true'
  737. // and that it is followed by either a seperator character
  738. // or the text ends
  739. if (MatchValue(JavaScriptConvert.True, true))
  740. {
  741. SetToken(JsonToken.Boolean, true);
  742. }
  743. else
  744. {
  745. throw new JsonReaderException("Error parsing boolean value.");
  746. }
  747. }
  748. private void ParseNull()
  749. {
  750. if (MatchValue(JavaScriptConvert.Null, true))
  751. {
  752. SetToken(JsonToken.Null);
  753. }
  754. else
  755. {
  756. throw new JsonReaderException("Error parsing null value.");
  757. }
  758. }
  759. private void ParseUndefined()
  760. {
  761. if (MatchValue(JavaScriptConvert.Undefined, true))
  762. {
  763. SetToken(JsonToken.Undefined);
  764. }
  765. else
  766. {
  767. throw new JsonReaderException("Error parsing undefined value.");
  768. }
  769. }
  770. private void ParseFalse()
  771. {
  772. if (MatchValue(JavaScriptConvert.False, true))
  773. {
  774. SetToken(JsonToken.Boolean, false);
  775. }
  776. else
  777. {
  778. throw new JsonReaderException("Error parsing boolean value.");
  779. }
  780. }
  781. void IDisposable.Dispose()
  782. {
  783. Dispose(true);
  784. }
  785. private void Dispose(bool disposing)
  786. {
  787. if (_currentState != State.Closed && disposing)
  788. Close();
  789. }
  790. /// <summary>
  791. /// Changes the <see cref="State"/> to Closed.
  792. /// </summary>
  793. public void Close()
  794. {
  795. _currentState = State.Closed;
  796. _token = JsonToken.None;
  797. _value = null;
  798. _valueType = null;
  799. if (_reader != null)
  800. _reader.Close();
  801. if (_buffer != null)
  802. _buffer.Clear();
  803. }
  804. }
  805. }