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

/mcs/class/System.ServiceModel.Web/System.Runtime.Serialization.Json/JavaScriptReader.cs

https://bitbucket.org/danipen/mono
C# | 342 lines | 330 code | 9 blank | 3 comment | 38 complexity | 50cfe381145ae5bafeb940b87891a73d MD5 | raw file
Possible License(s): Unlicense, Apache-2.0, LGPL-2.0, MPL-2.0-no-copyleft-exception, CC-BY-SA-3.0, GPL-2.0
  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. if (negexp)
  229. return new Decimal ((double) (val + frac) / Math.Pow (10, exp));
  230. int [] bits = Decimal.GetBits (val + frac);
  231. return new Decimal (bits [0], bits [1], bits [2], negative, (byte) exp);
  232. }
  233. StringBuilder vb = new StringBuilder ();
  234. string ReadStringLiteral ()
  235. {
  236. if (PeekChar () != '"')
  237. throw JsonError ("Invalid JSON string literal format");
  238. ReadChar ();
  239. vb.Length = 0;
  240. while (true) {
  241. int c = ReadChar ();
  242. if (c < 0)
  243. throw JsonError ("JSON string is not closed");
  244. if (c == '"')
  245. return vb.ToString ();
  246. else if (c != '\\') {
  247. vb.Append ((char) c);
  248. continue;
  249. }
  250. // escaped expression
  251. c = ReadChar ();
  252. if (c < 0)
  253. throw JsonError ("Invalid JSON string literal; incomplete escape sequence");
  254. switch (c) {
  255. case '"':
  256. case '\\':
  257. case '/':
  258. vb.Append ((char) c);
  259. break;
  260. case 'b':
  261. vb.Append ('\x8');
  262. break;
  263. case 'f':
  264. vb.Append ('\f');
  265. break;
  266. case 'n':
  267. vb.Append ('\n');
  268. break;
  269. case 'r':
  270. vb.Append ('\r');
  271. break;
  272. case 't':
  273. vb.Append ('\t');
  274. break;
  275. case 'u':
  276. ushort cp = 0;
  277. for (int i = 0; i < 4; i++) {
  278. cp <<= 4;
  279. if ((c = ReadChar ()) < 0)
  280. throw JsonError ("Incomplete unicode character escape literal");
  281. if ('0' <= c && c <= '9')
  282. cp += (ushort) (c - '0');
  283. if ('A' <= c && c <= 'F')
  284. cp += (ushort) (c - 'A' + 10);
  285. if ('a' <= c && c <= 'f')
  286. cp += (ushort) (c - 'a' + 10);
  287. }
  288. vb.Append ((char) cp);
  289. break;
  290. default:
  291. throw JsonError ("Invalid JSON string literal; unexpected escape character");
  292. }
  293. }
  294. }
  295. void Expect (char expected)
  296. {
  297. int c;
  298. if ((c = ReadChar ()) != expected)
  299. throw JsonError (String.Format ("Expected '{0}', got '{1}'", expected, (char) c));
  300. }
  301. void Expect (string expected)
  302. {
  303. for (int i = 0; i < expected.Length; i++)
  304. if (ReadChar () != expected [i])
  305. throw JsonError (String.Format ("Expected '{0}', differed at {1}", expected, i));
  306. }
  307. Exception JsonError (string msg)
  308. {
  309. return new ArgumentException (String.Format ("{0}. At line {1}, column {2}", msg, line, column));
  310. }
  311. }
  312. }