JavaScriptReader.cs 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Globalization;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Text;
  8. namespace System.Runtime.Serialization.Json
  9. {
  10. internal class JavaScriptReader
  11. {
  12. TextReader r;
  13. int line = 1, column = 0;
  14. bool raise_on_number_error; // FIXME: use it
  15. public JavaScriptReader (TextReader reader, bool raiseOnNumberError)
  16. {
  17. if (reader == null)
  18. throw new ArgumentNullException ("reader");
  19. this.r = reader;
  20. raise_on_number_error = raiseOnNumberError;
  21. }
  22. public object Read ()
  23. {
  24. object v = ReadCore ();
  25. SkipSpaces ();
  26. if (r.Read () >= 0)
  27. throw JsonError (String.Format ("extra characters in JSON input"));
  28. return v;
  29. }
  30. object ReadCore ()
  31. {
  32. SkipSpaces ();
  33. int c = PeekChar ();
  34. if (c < 0)
  35. throw JsonError ("Incomplete JSON input");
  36. switch (c) {
  37. case '[':
  38. ReadChar ();
  39. var list = new List<object> ();
  40. SkipSpaces ();
  41. if (PeekChar () == ']') {
  42. ReadChar ();
  43. return list;
  44. }
  45. while (true) {
  46. list.Add (ReadCore ());
  47. SkipSpaces ();
  48. c = PeekChar ();
  49. if (c != ',')
  50. break;
  51. ReadChar ();
  52. continue;
  53. }
  54. if (ReadChar () != ']')
  55. throw JsonError ("JSON array must end with ']'");
  56. return list.ToArray ();
  57. case '{':
  58. ReadChar ();
  59. var obj = new Dictionary<string,object> ();
  60. SkipSpaces ();
  61. if (PeekChar () == '}') {
  62. ReadChar ();
  63. return obj;
  64. }
  65. while (true) {
  66. SkipSpaces ();
  67. if (PeekChar () == '}')
  68. break;
  69. string name = ReadStringLiteral ();
  70. SkipSpaces ();
  71. Expect (':');
  72. SkipSpaces ();
  73. obj [name] = ReadCore (); // it does not reject duplicate names.
  74. SkipSpaces ();
  75. c = ReadChar ();
  76. if (c == ',')
  77. continue;
  78. if (c == '}')
  79. break;
  80. }
  81. #if MONOTOUCH
  82. int idx = 0;
  83. KeyValuePair<string, object> [] ret = new KeyValuePair<string, object>[obj.Count];
  84. foreach (KeyValuePair <string, object> kvp in obj)
  85. ret [idx++] = kvp;
  86. return ret;
  87. #else
  88. return obj.ToArray ();
  89. #endif
  90. case 't':
  91. Expect ("true");
  92. return true;
  93. case 'f':
  94. Expect ("false");
  95. return false;
  96. case 'n':
  97. Expect ("null");
  98. // FIXME: what should we return?
  99. return (string) null;
  100. case '"':
  101. return ReadStringLiteral ();
  102. default:
  103. if ('0' <= c && c <= '9' || c == '-')
  104. return ReadNumericLiteral ();
  105. else
  106. throw JsonError (String.Format ("Unexpected character '{0}'", (char) c));
  107. }
  108. }
  109. int peek;
  110. bool has_peek;
  111. bool prev_lf;
  112. int PeekChar ()
  113. {
  114. if (!has_peek) {
  115. peek = r.Read ();
  116. has_peek = true;
  117. }
  118. return peek;
  119. }
  120. int ReadChar ()
  121. {
  122. int v = has_peek ? peek : r.Read ();
  123. has_peek = false;
  124. if (prev_lf) {
  125. line++;
  126. column = 0;
  127. prev_lf = false;
  128. }
  129. if (v == '\n')
  130. prev_lf = true;
  131. column++;
  132. return v;
  133. }
  134. void SkipSpaces ()
  135. {
  136. while (true) {
  137. switch (PeekChar ()) {
  138. case ' ': case '\t': case '\r': case '\n':
  139. ReadChar ();
  140. continue;
  141. default:
  142. return;
  143. }
  144. }
  145. }
  146. // It could return either int, long or decimal, depending on the parsed value.
  147. object ReadNumericLiteral ()
  148. {
  149. bool negative = false;
  150. if (PeekChar () == '-') {
  151. negative = true;
  152. ReadChar ();
  153. if (PeekChar () < 0)
  154. throw JsonError ("Invalid JSON numeric literal; extra negation");
  155. }
  156. int c;
  157. decimal val = 0;
  158. int x = 0;
  159. bool zeroStart = PeekChar () == '0';
  160. for (; ; x++) {
  161. c = PeekChar ();
  162. if (c < '0' || '9' < c)
  163. break;
  164. val = val * 10 + (c - '0');
  165. ReadChar ();
  166. if (zeroStart && x == 1 && c == '0')
  167. throw JsonError ("leading multiple zeros are not allowed");
  168. }
  169. // fraction
  170. bool hasFrac = false;
  171. decimal frac = 0;
  172. int fdigits = 0;
  173. if (PeekChar () == '.') {
  174. hasFrac = true;
  175. ReadChar ();
  176. if (PeekChar () < 0)
  177. throw JsonError ("Invalid JSON numeric literal; extra dot");
  178. decimal d = 10;
  179. while (true) {
  180. c = PeekChar ();
  181. if (c < '0' || '9' < c)
  182. break;
  183. ReadChar ();
  184. frac += (c - '0') / d;
  185. d *= 10;
  186. fdigits++;
  187. }
  188. if (fdigits == 0)
  189. throw JsonError ("Invalid JSON numeric literal; extra dot");
  190. }
  191. frac = Decimal.Round (frac, fdigits);
  192. c = PeekChar ();
  193. if (c != 'e' && c != 'E') {
  194. if (!hasFrac) {
  195. if (negative && int.MinValue <= -val ||
  196. !negative && val <= int.MaxValue)
  197. return (int) (negative ? -val : val);
  198. if (negative && long.MinValue <= -val ||
  199. !negative && val <= long.MaxValue)
  200. return (long) (negative ? -val : val);
  201. }
  202. var v = val + frac;
  203. return negative ? -v : v;
  204. }
  205. // exponent
  206. ReadChar ();
  207. int exp = 0;
  208. if (PeekChar () < 0)
  209. throw new ArgumentException ("Invalid JSON numeric literal; incomplete exponent");
  210. bool negexp = false;
  211. c = PeekChar ();
  212. if (c == '-') {
  213. ReadChar ();
  214. negexp = true;
  215. }
  216. else if (c == '+')
  217. ReadChar ();
  218. if (PeekChar () < 0)
  219. throw JsonError ("Invalid JSON numeric literal; incomplete exponent");
  220. while (true) {
  221. c = PeekChar ();
  222. if (c < '0' || '9' < c)
  223. break;
  224. exp = exp * 10 + (c - '0');
  225. ReadChar ();
  226. }
  227. // it is messy to handle exponent, so I just use Decimal.Parse() with assured JSON format.
  228. int [] bits = Decimal.GetBits (val + frac);
  229. return new Decimal (bits [0], bits [1], bits [2], negative, (byte) exp);
  230. }
  231. StringBuilder vb = new StringBuilder ();
  232. string ReadStringLiteral ()
  233. {
  234. if (PeekChar () != '"')
  235. throw JsonError ("Invalid JSON string literal format");
  236. ReadChar ();
  237. vb.Length = 0;
  238. while (true) {
  239. int c = ReadChar ();
  240. if (c < 0)
  241. throw JsonError ("JSON string is not closed");
  242. if (c == '"')
  243. return vb.ToString ();
  244. else if (c != '\\') {
  245. vb.Append ((char) c);
  246. continue;
  247. }
  248. // escaped expression
  249. c = ReadChar ();
  250. if (c < 0)
  251. throw JsonError ("Invalid JSON string literal; incomplete escape sequence");
  252. switch (c) {
  253. case '"':
  254. case '\\':
  255. case '/':
  256. vb.Append ((char) c);
  257. break;
  258. case 'b':
  259. vb.Append ('\x8');
  260. break;
  261. case 'f':
  262. vb.Append ('\f');
  263. break;
  264. case 'n':
  265. vb.Append ('\n');
  266. break;
  267. case 'r':
  268. vb.Append ('\r');
  269. break;
  270. case 't':
  271. vb.Append ('\t');
  272. break;
  273. case 'u':
  274. ushort cp = 0;
  275. for (int i = 0; i < 4; i++) {
  276. cp <<= 4;
  277. if ((c = ReadChar ()) < 0)
  278. throw JsonError ("Incomplete unicode character escape literal");
  279. if ('0' <= c && c <= '9')
  280. cp += (ushort) (c - '0');
  281. if ('A' <= c && c <= 'F')
  282. cp += (ushort) (c - 'A' + 10);
  283. if ('a' <= c && c <= 'f')
  284. cp += (ushort) (c - 'a' + 10);
  285. }
  286. vb.Append ((char) cp);
  287. break;
  288. default:
  289. throw JsonError ("Invalid JSON string literal; unexpected escape character");
  290. }
  291. }
  292. }
  293. void Expect (char expected)
  294. {
  295. int c;
  296. if ((c = ReadChar ()) != expected)
  297. throw JsonError (String.Format ("Expected '{0}', got '{1}'", expected, (char) c));
  298. }
  299. void Expect (string expected)
  300. {
  301. int c;
  302. for (int i = 0; i < expected.Length; i++)
  303. if ((c = ReadChar ()) != expected [i])
  304. throw JsonError (String.Format ("Expected '{0}', differed at {1}", expected, i));
  305. }
  306. Exception JsonError (string msg)
  307. {
  308. return new ArgumentException (String.Format ("{0}. At line {1}, column {2}", msg, line, column));
  309. }
  310. }
  311. }