JavaScriptReader.cs 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  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. string name = ReadStringLiteral ();
  68. SkipSpaces ();
  69. Expect (':');
  70. SkipSpaces ();
  71. obj [name] = ReadCore (); // it does not reject duplicate names.
  72. SkipSpaces ();
  73. c = ReadChar ();
  74. if (c == ',')
  75. continue;
  76. if (c == '}')
  77. break;
  78. }
  79. return obj.ToArray ();
  80. case 't':
  81. Expect ("true");
  82. return true;
  83. case 'f':
  84. Expect ("false");
  85. return false;
  86. case 'n':
  87. Expect ("null");
  88. // FIXME: what should we return?
  89. return (string) null;
  90. case '"':
  91. return ReadStringLiteral ();
  92. default:
  93. if ('0' <= c && c <= '9' || c == '-')
  94. return ReadNumericLiteral ();
  95. else
  96. throw JsonError (String.Format ("Unexpected character '{0}'", (char) c));
  97. }
  98. }
  99. int peek;
  100. bool has_peek;
  101. bool prev_lf;
  102. int PeekChar ()
  103. {
  104. if (!has_peek) {
  105. peek = r.Read ();
  106. has_peek = true;
  107. }
  108. return peek;
  109. }
  110. int ReadChar ()
  111. {
  112. int v = has_peek ? peek : r.Read ();
  113. has_peek = false;
  114. if (prev_lf) {
  115. line++;
  116. column = 0;
  117. prev_lf = false;
  118. }
  119. if (v == '\n')
  120. prev_lf = true;
  121. column++;
  122. return v;
  123. }
  124. void SkipSpaces ()
  125. {
  126. while (true) {
  127. switch (PeekChar ()) {
  128. case ' ': case '\t': case '\r': case '\n':
  129. ReadChar ();
  130. continue;
  131. default:
  132. return;
  133. }
  134. }
  135. }
  136. // It could return either int, long or decimal, depending on the parsed value.
  137. object ReadNumericLiteral ()
  138. {
  139. bool negative = false;
  140. if (PeekChar () == '-') {
  141. negative = true;
  142. ReadChar ();
  143. if (PeekChar () < 0)
  144. throw JsonError ("Invalid JSON numeric literal; extra negation");
  145. }
  146. int c;
  147. decimal val = 0;
  148. int x = 0;
  149. bool zeroStart = PeekChar () == '0';
  150. for (; ; x++) {
  151. c = PeekChar ();
  152. if (c < '0' || '9' < c)
  153. break;
  154. val = val * 10 + (c - '0');
  155. ReadChar ();
  156. if (zeroStart && x == 1 && c == '0')
  157. throw JsonError ("leading multiple zeros are not allowed");
  158. }
  159. // fraction
  160. bool hasFrac = false;
  161. decimal frac = 0;
  162. int fdigits = 0;
  163. if (PeekChar () == '.') {
  164. hasFrac = true;
  165. ReadChar ();
  166. if (PeekChar () < 0)
  167. throw JsonError ("Invalid JSON numeric literal; extra dot");
  168. decimal d = 10;
  169. while (true) {
  170. c = PeekChar ();
  171. if (c < '0' || '9' < c)
  172. break;
  173. ReadChar ();
  174. frac += (c - '0') / d;
  175. d *= 10;
  176. fdigits++;
  177. }
  178. if (fdigits == 0)
  179. throw JsonError ("Invalid JSON numeric literal; extra dot");
  180. }
  181. frac = Decimal.Round (frac, fdigits);
  182. c = PeekChar ();
  183. if (c != 'e' && c != 'E') {
  184. if (!hasFrac) {
  185. if (negative && int.MinValue <= -val ||
  186. !negative && val <= int.MaxValue)
  187. return (int) (negative ? -val : val);
  188. if (negative && long.MinValue <= -val ||
  189. !negative && val <= long.MaxValue)
  190. return (long) (negative ? -val : val);
  191. }
  192. var v = val + frac;
  193. return negative ? -v : v;
  194. }
  195. // exponent
  196. ReadChar ();
  197. int exp = 0;
  198. if (PeekChar () < 0)
  199. throw new ArgumentException ("Invalid JSON numeric literal; incomplete exponent");
  200. bool negexp = false;
  201. c = PeekChar ();
  202. if (c == '-') {
  203. ReadChar ();
  204. negexp = true;
  205. }
  206. else if (c == '+')
  207. ReadChar ();
  208. if (PeekChar () < 0)
  209. throw JsonError ("Invalid JSON numeric literal; incomplete exponent");
  210. while (true) {
  211. c = PeekChar ();
  212. if (c < '0' || '9' < c)
  213. break;
  214. exp = exp * 10 + (c - '0');
  215. ReadChar ();
  216. }
  217. // it is messy to handle exponent, so I just use Decimal.Parse() with assured JSON format.
  218. int [] bits = Decimal.GetBits (val + frac);
  219. return new Decimal (bits [0], bits [1], bits [2], negative, (byte) exp);
  220. }
  221. StringBuilder vb = new StringBuilder ();
  222. string ReadStringLiteral ()
  223. {
  224. if (PeekChar () != '"')
  225. throw JsonError ("Invalid JSON string literal format");
  226. ReadChar ();
  227. vb.Length = 0;
  228. while (true) {
  229. int c = ReadChar ();
  230. if (c < 0)
  231. throw JsonError ("JSON string is not closed");
  232. if (c == '"')
  233. return vb.ToString ();
  234. else if (c != '\\') {
  235. vb.Append ((char) c);
  236. continue;
  237. }
  238. // escaped expression
  239. c = ReadChar ();
  240. if (c < 0)
  241. throw JsonError ("Invalid JSON string literal; incomplete escape sequence");
  242. switch (c) {
  243. case '"':
  244. case '\\':
  245. case '/':
  246. vb.Append ((char) c);
  247. break;
  248. case 'b':
  249. vb.Append ('\x8');
  250. break;
  251. case 'f':
  252. vb.Append ('\f');
  253. break;
  254. case 'n':
  255. vb.Append ('\n');
  256. break;
  257. case 'r':
  258. vb.Append ('\r');
  259. break;
  260. case 't':
  261. vb.Append ('\t');
  262. break;
  263. case 'u':
  264. ushort cp = 0;
  265. for (int i = 0; i < 4; i++) {
  266. cp <<= 4;
  267. if ((c = ReadChar ()) < 0)
  268. throw JsonError ("Incomplete unicode character escape literal");
  269. if ('0' <= c && c <= '9')
  270. cp += (ushort) (c - '0');
  271. if ('A' <= c && c <= 'F')
  272. cp += (ushort) (c - 'A' + 10);
  273. if ('a' <= c && c <= 'f')
  274. cp += (ushort) (c - 'a' + 10);
  275. }
  276. vb.Append ((char) cp);
  277. break;
  278. default:
  279. throw JsonError ("Invalid JSON string literal; unexpected escape character");
  280. }
  281. }
  282. }
  283. void Expect (char expected)
  284. {
  285. int c;
  286. if ((c = ReadChar ()) != expected)
  287. throw JsonError (String.Format ("Expected '{0}', got '{1}'", expected, (char) c));
  288. }
  289. void Expect (string expected)
  290. {
  291. int c;
  292. for (int i = 0; i < expected.Length; i++)
  293. if ((c = ReadChar ()) != expected [i])
  294. throw JsonError (String.Format ("Expected '{0}', differed at {1}", expected, i));
  295. }
  296. Exception JsonError (string msg)
  297. {
  298. return new ArgumentException (String.Format ("{0}. At line {1}, column {2}", msg, line, column));
  299. }
  300. }
  301. }