OLD | NEW |
| (Empty) |
1 // Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file | |
2 // for details. All rights reserved. Use of this source code is governed by a | |
3 // BSD-style license that can be found in the LICENSE file. | |
4 | |
5 #library("json"); | |
6 | |
7 // TODO(devoncarew): this file is a copy of client/json/dart_json.dart and shoul
d be deleted as | |
8 // soon as it is no longer referenced from frog_server.dart. | |
9 | |
10 // Pure Dart implementation of JSON protocol. | |
11 | |
12 /** | |
13 * Utility class to parse JSON and serialize objects to JSON. | |
14 */ | |
15 class JSON { | |
16 /** | |
17 * Parses [:json:] and build the corresponding object. | |
18 */ | |
19 static parse(String json) { | |
20 return JsonParser.parse(json); | |
21 } | |
22 | |
23 /** | |
24 * Serializes [:object:] into JSON string. | |
25 */ | |
26 static String stringify(Object object) { | |
27 return JsonStringifier.stringify(object); | |
28 } | |
29 } | |
30 | |
31 //// Implementation /////////////////////////////////////////////////////////// | |
32 | |
33 /** | |
34 * Union-like class for JSON tokens. | |
35 */ | |
36 class JsonToken { | |
37 static final int STRING = 0; | |
38 static final int NUMBER = 1; | |
39 static final int NULL = 2; | |
40 static final int FALSE = 3; | |
41 static final int TRUE = 4; | |
42 static final int RBRACKET = 5; | |
43 static final int LBRACKET = 6; | |
44 static final int RBRACE = 7; | |
45 static final int LBRACE = 8; | |
46 static final int COLON = 9; | |
47 static final int COMMA = 10; | |
48 | |
49 final int kind; | |
50 final String _s; | |
51 final num _n; | |
52 | |
53 String get str() { | |
54 assert(kind == STRING); | |
55 return _s; | |
56 } | |
57 | |
58 num get number() { | |
59 assert(kind == NUMBER); | |
60 return _n; | |
61 } | |
62 | |
63 const JsonToken._internal(this.kind, this._s, this._n); | |
64 | |
65 factory JsonToken.string(String s) { | |
66 return new JsonToken._internal(STRING, s, 0); | |
67 } | |
68 factory JsonToken.number(num n) { | |
69 return new JsonToken._internal(NUMBER, '', n); | |
70 } | |
71 factory JsonToken.atom(int kind) { | |
72 return new JsonToken._internal(kind, '', 0); | |
73 } | |
74 | |
75 String toString() { | |
76 switch (kind) { | |
77 case STRING: | |
78 return 'STRING(${str})'; | |
79 | |
80 case NUMBER: | |
81 return 'NUMBER(${number})'; | |
82 | |
83 case NULL: | |
84 return 'ATOM(null)'; | |
85 | |
86 case FALSE: | |
87 return 'ATOM(false)'; | |
88 | |
89 case TRUE: | |
90 return 'ATOM(true)'; | |
91 | |
92 case RBRACKET: | |
93 return 'ATOM(])'; | |
94 | |
95 case LBRACKET: | |
96 return 'ATOM([)'; | |
97 | |
98 case RBRACE: | |
99 return 'ATOM(})'; | |
100 | |
101 case LBRACE: | |
102 return 'ATOM({)'; | |
103 | |
104 case COLON: | |
105 return 'ATOM(:)'; | |
106 | |
107 case COMMA: | |
108 return 'ATOM(,)'; | |
109 } | |
110 } | |
111 } | |
112 | |
113 typedef bool Predicate(int c); | |
114 | |
115 class JsonTokenizer { | |
116 static final int BACKSPACE = 8; // '\b'.charCodeAt(0) | |
117 static final int TAB = 9; // '\t'.charCodeAt(0) | |
118 static final int NEW_LINE = 10; // '\n'.charCodeAt(0) | |
119 static final int FORM_FEED = 12; // '\f'.charCodeAt(0) | |
120 static final int LINE_FEED = 13; // '\r'.charCodeAt(0) | |
121 static final int SPACE = 32; // ' '.charCodeAt(0) | |
122 static final int QUOTE = 34; // '"'.charCodeAt(0) | |
123 static final int PLUS = 43; // '+'.charCodeAt(0) | |
124 static final int COMMA = 44; // ','.charCodeAt(0) | |
125 static final int MINUS = 45; // '-'.charCodeAt(0) | |
126 static final int DOT = 46; // '.'.charCodeAt(0) | |
127 static final int SLASH = 47; // '/'.charCodeAt(0) | |
128 static final int ZERO = 48; // '0'.charCodeAt(0) | |
129 static final int NINE = 57; // '9'.charCodeAt(0) | |
130 static final int COLON = 58; // ':'.charCodeAt(0) | |
131 static final int A_BIG = 65; // 'A'.charCodeAt(0) | |
132 static final int E_BIG = 69; // 'E'.charCodeAt(0) | |
133 static final int Z_BIG = 90; // 'Z'.charCodeAt(0) | |
134 static final int LBRACKET = 91; // '['.charCodeAt(0) | |
135 static final int BACKSLASH = 92; // '\\'.charCodeAt(0) | |
136 static final int RBRACKET = 93; // ']'.charCodeAt(0) | |
137 static final int A_SMALL = 97; // 'a'.charCodeAt(0) | |
138 static final int B_SMALL = 98; // 'b'.charCodeAt(0) | |
139 static final int E_SMALL = 101; // 'e'.charCodeAt(0) | |
140 static final int N_SMALL = 110; // 'n'.charCodeAt(0) | |
141 static final int R_SMALL = 114; // 'r'.charCodeAt(0) | |
142 static final int Z_SMALL = 122; // 'z'.charCodeAt(0) | |
143 static final int LBRACE = 123; // '{'.charCodeAt(0) | |
144 static final int RBRACE = 125; // '}'.charCodeAt(0) | |
145 | |
146 JsonTokenizer(String s) : _s = s + ' ', _pos = 0, _len = s.length + 1 {} | |
147 | |
148 /** | |
149 * Fetches next token or [:null:] if the stream has been exhausted. | |
150 */ | |
151 JsonToken next() { | |
152 while (_pos < _len && isWhitespace(_s.charCodeAt(_pos))) { | |
153 _pos++; | |
154 } | |
155 if (_pos == _len) { | |
156 return null; | |
157 } | |
158 | |
159 final int cur = _s.charCodeAt(_pos); | |
160 switch (true) { | |
161 case cur == QUOTE: | |
162 _pos++; | |
163 List<int> charCodes = new List<int>(); | |
164 while (_pos < _len) { | |
165 int c = _s.charCodeAt(_pos); | |
166 if (c == QUOTE) { | |
167 break; | |
168 } | |
169 if (c == BACKSLASH) { | |
170 _pos++; | |
171 if (_pos == _len) { | |
172 throw '\\ at the end'; | |
173 } | |
174 | |
175 switch (_s[_pos]) { | |
176 case '"': | |
177 c = QUOTE; | |
178 break; | |
179 case '\\': | |
180 c = BACKSLASH; | |
181 break; | |
182 case '/': | |
183 c = SLASH; | |
184 break; | |
185 case 'b': | |
186 c = BACKSPACE; | |
187 break; | |
188 case 'n': | |
189 c = NEW_LINE; | |
190 break; | |
191 case 'r': | |
192 c = LINE_FEED; | |
193 break; | |
194 case 'f': | |
195 c = FORM_FEED; | |
196 break; | |
197 case 't': | |
198 c = TAB; | |
199 break; | |
200 case 'u': | |
201 if (_pos + 5 > _len) { | |
202 throw 'Invalid unicode esacape sequence: \\' + | |
203 _s.substring(_pos, _len); | |
204 } | |
205 final codeString = _s.substring(_pos + 1, _pos + 5); | |
206 c = Math.parseInt('0x' + codeString); | |
207 if (c >= 128) { | |
208 // TODO(jmessery): the VM doesn't support 2-byte strings yet | |
209 // see runtime/lib/string.cc:49 | |
210 // So instead we replace these characters with '?' | |
211 c = '?'.charCodeAt(0); | |
212 } | |
213 _pos += 4; | |
214 break; | |
215 default: | |
216 throw 'Invalid esacape sequence: \\' + _s[_pos]; | |
217 } | |
218 } | |
219 charCodes.add(c); | |
220 _pos++; | |
221 } | |
222 if (_pos == _len) { | |
223 throw 'Unmatched quote'; | |
224 } | |
225 | |
226 final String body = new String.fromCharCodes(charCodes); | |
227 _pos++; | |
228 return new JsonToken.string(body); | |
229 | |
230 case cur == MINUS || isDigit(cur): | |
231 skipDigits() { | |
232 _scanWhile((int c) => isDigit(c), 'Invalid number'); | |
233 } | |
234 | |
235 int c = cur; | |
236 final int startPos = _pos; | |
237 int value = 0; | |
238 bool isNegative = false; | |
239 if (c == MINUS) { | |
240 isNegative = true; | |
241 _pos++; | |
242 c = _s.charCodeAt(_pos); | |
243 } | |
244 while (isDigit(c)) { | |
245 value = value * 10 + c - ZERO; | |
246 _pos++; | |
247 c = _s.charCodeAt(_pos); | |
248 } | |
249 | |
250 if (c != DOT) { | |
251 if (c != E_SMALL && cur != E_BIG) { | |
252 if (isNegative) value = -value; | |
253 return new JsonToken.number(value); | |
254 } | |
255 } else { | |
256 _pos++; | |
257 skipDigits(); | |
258 c = _s.charCodeAt(_pos); | |
259 } | |
260 | |
261 if (c == E_SMALL || c == E_BIG) { | |
262 // TODO: consider keeping E+ as an integer. | |
263 _pos++; | |
264 c = _s.charCodeAt(_pos); | |
265 if (c == PLUS || c == MINUS) { | |
266 _pos++; | |
267 } | |
268 skipDigits(); | |
269 } | |
270 | |
271 final String body = _s.substring(startPos, _pos); | |
272 return new JsonToken.number(Math.parseDouble(body)); | |
273 | |
274 case cur == LBRACE: | |
275 _pos++; | |
276 return new JsonToken.atom(JsonToken.LBRACE); | |
277 | |
278 case cur == RBRACE: | |
279 _pos++; | |
280 return new JsonToken.atom(JsonToken.RBRACE); | |
281 | |
282 case cur == LBRACKET: | |
283 _pos++; | |
284 return new JsonToken.atom(JsonToken.LBRACKET); | |
285 | |
286 case cur == RBRACKET: | |
287 _pos++; | |
288 return new JsonToken.atom(JsonToken.RBRACKET); | |
289 | |
290 case cur == COMMA: | |
291 _pos++; | |
292 return new JsonToken.atom(JsonToken.COMMA); | |
293 | |
294 case cur == COLON: | |
295 _pos++; | |
296 return new JsonToken.atom(JsonToken.COLON); | |
297 | |
298 case isLetter(cur): | |
299 final int startPos = _pos; | |
300 _pos++; | |
301 while (_pos < _len && isLetter(_s.charCodeAt(_pos))) { | |
302 _pos++; | |
303 } | |
304 final String body = _s.substring(startPos, _pos); | |
305 switch (body) { | |
306 case 'null': | |
307 return new JsonToken.atom(JsonToken.NULL); | |
308 | |
309 case 'false': | |
310 return new JsonToken.atom(JsonToken.FALSE); | |
311 | |
312 case 'true': | |
313 return new JsonToken.atom(JsonToken.TRUE); | |
314 | |
315 default: | |
316 throw 'Unexpected sequence ${body}'; | |
317 } | |
318 // TODO: Bogous, to please DartVM. | |
319 return null; | |
320 | |
321 default: | |
322 throw 'Invalid token'; | |
323 } | |
324 } | |
325 | |
326 final String _s; | |
327 int _pos; | |
328 final int _len; | |
329 | |
330 void _scanWhile(Predicate predicate, String errorMsg) { | |
331 while (_pos < _len && predicate(_s.charCodeAt(_pos))) { | |
332 _pos++; | |
333 } | |
334 if (_pos == _len) { | |
335 throw errorMsg; | |
336 } | |
337 } | |
338 | |
339 // TODO other kind of whitespace. | |
340 static bool isWhitespace(int c) { | |
341 return c == SPACE || c == TAB || c == NEW_LINE || c == LINE_FEED; | |
342 } | |
343 static bool isDigit(int c) { | |
344 return (ZERO <= c) && (c <= NINE); | |
345 } | |
346 static bool isLetter(int c) { | |
347 return ((A_SMALL <= c) && (c <= Z_SMALL)) || ((A_BIG <= c) && (c <= Z_BIG))
; | |
348 } | |
349 } | |
350 | |
351 class JsonParser { | |
352 static parse(String json) { | |
353 return new JsonParser._internal(json)._parseToplevel(); | |
354 } | |
355 | |
356 final JsonTokenizer _tokenizer; | |
357 | |
358 JsonParser._internal(String json) : _tokenizer = new JsonTokenizer(json) {} | |
359 | |
360 _parseToplevel() { | |
361 JsonToken token = _tokenizer.next(); | |
362 final result = _parseValue(token); | |
363 token = _tokenizer.next(); | |
364 if (token !== null) { | |
365 throw 'Junk at the end'; | |
366 } | |
367 return result; | |
368 } | |
369 | |
370 _parseValue(final JsonToken token) { | |
371 if (token === null) { | |
372 throw 'Nothing to parse'; | |
373 } | |
374 switch (token.kind) { | |
375 case JsonToken.STRING: | |
376 return token.str; | |
377 | |
378 case JsonToken.NUMBER: | |
379 return token.number; | |
380 | |
381 case JsonToken.NULL: | |
382 return null; | |
383 | |
384 case JsonToken.FALSE: | |
385 return false; | |
386 | |
387 case JsonToken.TRUE: | |
388 return true; | |
389 | |
390 case JsonToken.LBRACE: | |
391 return _parseObject(); | |
392 | |
393 case JsonToken.LBRACKET: | |
394 return _parseList(); | |
395 | |
396 default: | |
397 throw 'Unexpected token: ${token}'; | |
398 } | |
399 } | |
400 | |
401 _parseObject() { | |
402 Map<String, Object> object = new Map<String, Object>(); | |
403 | |
404 _parseSequence(JsonToken.RBRACE, (JsonToken token) { | |
405 _assertTokenKind(token, JsonToken.STRING); | |
406 final String key = token.str; | |
407 | |
408 token = _tokenizer.next(); | |
409 _assertTokenKind(token, JsonToken.COLON); | |
410 | |
411 token = _tokenizer.next(); | |
412 final value = _parseValue(token); | |
413 | |
414 object[key] = value; | |
415 }); | |
416 | |
417 return object; | |
418 } | |
419 | |
420 _parseList() { | |
421 List<Object> list = new List<Object>(); | |
422 | |
423 _parseSequence(JsonToken.RBRACKET, (JsonToken token) { | |
424 final value = _parseValue(token); | |
425 list.add(value); | |
426 }); | |
427 | |
428 return list; | |
429 } | |
430 | |
431 void _parseSequence(int endTokenKind, void parseElement(JsonToken token)) { | |
432 JsonToken token = _tokenizer.next(); | |
433 if (token === null) { | |
434 throw 'Unexpected end of stream'; | |
435 } | |
436 if (token.kind == endTokenKind) { | |
437 return; | |
438 } | |
439 | |
440 parseElement(token); | |
441 | |
442 token = _tokenizer.next(); | |
443 if (token === null) { | |
444 throw 'Expected either comma or terminator'; | |
445 } | |
446 while (token.kind != endTokenKind) { | |
447 _assertTokenKind(token, JsonToken.COMMA); | |
448 | |
449 token = _tokenizer.next(); | |
450 parseElement(token); | |
451 | |
452 token = _tokenizer.next(); | |
453 } | |
454 } | |
455 | |
456 void _assertTokenKind(JsonToken token, int kind) { | |
457 if (token === null || token.kind != kind) { | |
458 throw 'Unexpected token kind: token = ${token}, expected kind = ${kind}'; | |
459 } | |
460 } | |
461 | |
462 // TODO: consider factor out error throwing code and build more complicated | |
463 // data structure to provide more info for a caller. | |
464 } | |
465 | |
466 // TODO: proper base class. | |
467 class JsonUnsupportedObjectType { | |
468 const JsonUnsupportedObjectType(); | |
469 } | |
470 | |
471 class JsonStringifier { | |
472 static String stringify(final object) { | |
473 JsonStringifier stringifier = new JsonStringifier._internal(); | |
474 stringifier._stringify(object); | |
475 return stringifier._result; | |
476 } | |
477 | |
478 JsonStringifier._internal() | |
479 : _sb = new StringBuffer(), _seen = new List<Object>() {} | |
480 StringBuffer _sb; | |
481 List<Object> _seen; // TODO: that should be identity set. | |
482 String get _result() { return _sb.toString(); } | |
483 | |
484 static String _numberToString(num x) { | |
485 // TODO: need some more investigation what to do with precision | |
486 // of double values. | |
487 switch (true) { | |
488 case x is int: | |
489 return x.toString(); | |
490 | |
491 case x is double: | |
492 return x.toString(); | |
493 | |
494 default: | |
495 return x.toDouble().toString(); | |
496 } | |
497 } | |
498 | |
499 // TODO: add others. | |
500 static bool _needsEscape(int charCode) { | |
501 return JsonTokenizer.QUOTE == charCode || JsonTokenizer.BACKSLASH == charCod
e | |
502 || JsonTokenizer.NEW_LINE == charCode || JsonTokenizer.LINE_FEED == charCo
de; | |
503 } | |
504 | |
505 static void _escape(StringBuffer sb, String s) { | |
506 // TODO: support \u code points. | |
507 // TODO: use writeCodePoint when implemented. | |
508 // TODO: use for each if implemented. | |
509 final int length = s.length; | |
510 bool needsEscape = false; | |
511 final charCodes = new List<int>(); | |
512 for (int i = 0; i < length; i++) { | |
513 int charCode = s.charCodeAt(i); | |
514 if (_needsEscape(charCode)) { | |
515 charCodes.add(JsonTokenizer.BACKSLASH); | |
516 needsEscape = true; | |
517 | |
518 if (JsonTokenizer.NEW_LINE == charCode) { | |
519 charCode = JsonTokenizer.N_SMALL; | |
520 } else if (JsonTokenizer.LINE_FEED == charCode) { | |
521 charCode = JsonTokenizer.R_SMALL; | |
522 } | |
523 } | |
524 charCodes.add(charCode); | |
525 } | |
526 sb.add(needsEscape ? new String.fromCharCodes(charCodes) : s); | |
527 } | |
528 | |
529 void _checkCycle(final object) { | |
530 // TODO: use Iterables. | |
531 for (int i = 0; i < _seen.length; i++) { | |
532 if (_seen[i] === object) { | |
533 throw 'Cyclic structure'; | |
534 } | |
535 } | |
536 _seen.add(object); | |
537 } | |
538 | |
539 void _stringify(final object) { | |
540 switch (true) { | |
541 case object is num: | |
542 // TODO: use writeOn. | |
543 _sb.add(_numberToString(object)); | |
544 return; | |
545 | |
546 case object === true: | |
547 _sb.add('true'); | |
548 return; | |
549 | |
550 case object === false: | |
551 _sb.add('false'); | |
552 return; | |
553 | |
554 case object === null: | |
555 _sb.add('null'); | |
556 return; | |
557 | |
558 case object is String: | |
559 _sb.add('"'); | |
560 _escape(_sb, object); | |
561 _sb.add('"'); | |
562 return; | |
563 | |
564 case object is List: | |
565 _checkCycle(object); | |
566 List a = object; | |
567 _sb.add('['); | |
568 if (a.length > 0) { | |
569 _stringify(a[0]); | |
570 // TODO: switch to Iterables. | |
571 for (int i = 1; i < a.length; i++) { | |
572 _sb.add(','); | |
573 _stringify(a[i]); | |
574 } | |
575 } | |
576 _sb.add(']'); | |
577 _seen.removeLast(); | |
578 return; | |
579 | |
580 case object is Map: | |
581 _checkCycle(object); | |
582 Map<String, Object> m = object; | |
583 _sb.add('{'); | |
584 bool first = true; | |
585 m.forEach((String key, Object value) { | |
586 if (!first) { | |
587 _sb.add(',"'); | |
588 } else { | |
589 _sb.add('"'); | |
590 } | |
591 _escape(_sb, key); | |
592 _sb.add('":'); | |
593 _stringify(value); | |
594 first = false; | |
595 }); | |
596 _sb.add('}'); | |
597 _seen.removeLast(); | |
598 return; | |
599 | |
600 default: | |
601 throw const JsonUnsupportedObjectType(); | |
602 } | |
603 } | |
604 } | |
OLD | NEW |