forked from stleary/JSON-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJSONLexer.java
More file actions
826 lines (781 loc) · 28.8 KB
/
JSONLexer.java
File metadata and controls
826 lines (781 loc) · 28.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
package org.json.stream;
/*
Copyright (c) 2002 JSON.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
The Software shall be used for Good, not Evil.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import org.json.JSONException;
import org.json.JSONParseException;
import org.json.ParsePosition;
import org.json.Scanner;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import java.nio.charset.Charset;
/**
* A {@code JSONLexer} takes a source stream and extracts characters and tokens
* from it. It does not perform any sanity checks on the order that
* tokens appear. It is used by {@link JSONStreamReader} class to tokenise
* JSON source streams.
*
* @author JSON.org
* @version 2016-06-08
*/
public final class JSONLexer {
/**
* Tokens that can be identified with at most one character lookahead.
* Produced by {@link JSONLexer} and consumed by the {@link JSONStreamReader}
* class.
*/
public enum Token {
STRING_VALUE,
NUMBER_VALUE,
NULL_VALUE,
TRUE_VALUE,
FALSE_VALUE,
START_ARRAY,
END_ARRAY,
START_OBJECT,
END_OBJECT,
KEY_SEPARATOR,
VALUE_SEPARATOR,
END
}
private final Scanner scanner;
/**
* Construct a {@code JSONLexer} from a {@code Reader}.
*
* @param reader A reader.
*/
public JSONLexer(Reader reader) {
scanner = new Scanner(reader);
}
/**
* Construct a {@code JSONLexer} from an {@code InputStream} and a supplied
* {@code Charset}.
*
* @param inputStream the input stream containing the JSON data
* @param charset the character set with which to interpret the
* input stream
*/
public JSONLexer(InputStream inputStream, Charset charset) {
scanner = new Scanner(inputStream, charset);
}
/**
* Construct a {@code JSONLexer} from a {@code String}.
*
* @param s A source string.
*/
public JSONLexer(String s) {
scanner = new Scanner(new StringReader(s));
}
/**
* Get the next char in the stream, skipping insignificant whitespace.
* Control characters less than U+0020, apart from newline and
* carriage return, result in an error.
*
* @throws JSONException
* @return A character, or 0 if there are no more characters.
*/
private char nextClean() throws JSONException {
for (;;) {
char c = scanner.next();
switch(c) {
case (char)0:
if (scanner.end()) {
return c;
} else {
throw new JSONParseException("Illegal control code",
scanner.parsePosition());
}
case (char)1:
case (char)2:
case (char)3:
case (char)4:
case (char)5:
case (char)6:
case (char)7:
case (char)8:
case (char)11:
case (char)12:
case (char)14:
case (char)15:
case (char)16:
case (char)17:
case (char)18:
case (char)19:
case (char)20:
case (char)21:
case (char)22:
case (char)23:
case (char)24:
case (char)25:
case (char)26:
case (char)27:
case (char)28:
case (char)29:
case (char)30:
case (char)31:
throw new JSONParseException("Illegal control code",
scanner.parsePosition());
case (char)9: // \t
case (char)10: // \n
case (char)13: // \r
case (char)32: // ' '
// valid whitespace
break;
default:
return c;
}
}
}
/**
* Get the type of the next token in the stream, skipping whitespace.
* This parses the literal tokens and separators only.
*
* @return the Token type representing the next token type
*/
public Token nextTokenType() throws JSONException {
char c = nextClean();
switch(c) {
case '{':
return Token.START_OBJECT;
case '}':
return Token.END_OBJECT;
case '[':
return Token.START_ARRAY;
case ']':
return Token.END_ARRAY;
case ':':
return Token.KEY_SEPARATOR;
case ',':
return Token.VALUE_SEPARATOR;
case (char)0:
if(scanner.end()) {
return Token.END;
}
case '"':
scanner.back();
return Token.STRING_VALUE;
case 't':
scanner.next('r');
scanner.next('u');
scanner.next('e');
return Token.TRUE_VALUE;
case 'f':
scanner.next('a');
scanner.next('l');
scanner.next('s');
scanner.next('e');
return Token.FALSE_VALUE;
case 'n':
scanner.next('u');
scanner.next('l');
scanner.next('l');
return Token.NULL_VALUE;
case '-':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
scanner.back();
return Token.NUMBER_VALUE;
default:
throw new JSONParseException("Unexpected value", scanner.parsePosition());
}
}
/**
* Return the characters up to the next close quote character.
* Backslash escape sequences are processed. The formal JSON format only
* allows string values within double quotes.
*
* @param sb the Appendable to which the String value is appended
* @param <T> a subtype of {@code Appendable}, returned to the caller
* for chaining purposes
* @return the supplied Appendable object
* @throws JSONException Unterminated string.
*/
public <T extends Appendable> T nextString(T sb) throws JSONException {
char c = scanner.next();
if(c != '"') {
throw new JSONParseException("Unexpected string delimiter",
scanner.parsePosition());
}
try {
for (;;) {
c = scanner.next();
switch (c) {
case (char)0:
case (char)10: // \n
case (char)13: // \r
throw new JSONParseException("Unterminated string",
scanner.parsePosition());
case (char)1:
case (char)2:
case (char)3:
case (char)4:
case (char)5:
case (char)6:
case (char)7:
case (char)8:
case (char)9:
case (char)11:
case (char)12:
case (char)14:
case (char)15:
case (char)16:
case (char)17:
case (char)18:
case (char)19:
case (char)20:
case (char)21:
case (char)22:
case (char)23:
case (char)24:
case (char)25:
case (char)26:
case (char)27:
case (char)28:
case (char)29:
case (char)30:
case (char)31:
throw new JSONParseException("Unescaped control code",
scanner.parsePosition());
case '\\':
c = scanner.next();
switch (c) {
case 'b':
sb.append('\b');
break;
case 't':
sb.append('\t');
break;
case 'n':
sb.append('\n');
break;
case 'f':
sb.append('\f');
break;
case 'r':
sb.append('\r');
break;
case 'u':
try {
sb.append((char) Integer.parseInt(next4HexDigits(), 16));
} catch (NumberFormatException e) {
throw new JSONParseException("Illegal unicode escape", e,
scanner.parsePosition());
}
break;
case '"':
case '\\':
case '/':
sb.append(c);
break;
default:
throw new JSONParseException("Illegal escape",
scanner.parsePosition());
}
break;
case '"':
return sb;
default:
sb.append(c);
break;
}
}
} catch (IOException e) {
throw new JSONParseException("IOException", e, scanner.parsePosition());
}
}
/**
* Return the characters up to the next close quote character.
* Backslash escape sequences are processed. The formal JSON format only
* allows string values within double quotes.
* <p>
* Most practical parsers will limit the length of a string to one
* expressible by a {@code String} object, or writable to a {@code File}.
* </p>
*
* @param sb the Appendable to which the String value is appended
* @param maxLen the maximum length of the decoded string value,
* <= 0 to limit to Long.MAX_VALUE
* @param <T> a subtype of {@code Appendable}, returned to the caller
* for chaining purposes
* @return the supplied Appendable object
* @throws JSONException Unterminated string.
*/
public <T extends Appendable> T nextString(T sb, long maxLen) throws JSONException {
char c = scanner.next();
if (maxLen <= 0) {
maxLen = Long.MAX_VALUE;
}
if(c != '"') {
throw new JSONParseException("Unexpected string delimiter",
scanner.parsePosition());
}
try {
for (long len = 0; len < maxLen; len++) {
c = scanner.next();
switch (c) {
case (char)0:
case (char)10: // \n
case (char)13: // \r
throw new JSONParseException("Unterminated string",
scanner.parsePosition());
case (char)1:
case (char)2:
case (char)3:
case (char)4:
case (char)5:
case (char)6:
case (char)7:
case (char)8:
case (char)9:
case (char)11:
case (char)12:
case (char)14:
case (char)15:
case (char)16:
case (char)17:
case (char)18:
case (char)19:
case (char)20:
case (char)21:
case (char)22:
case (char)23:
case (char)24:
case (char)25:
case (char)26:
case (char)27:
case (char)28:
case (char)29:
case (char)30:
case (char)31:
throw new JSONParseException("Unescaped control code",
scanner.parsePosition());
case '\\':
c = scanner.next();
switch (c) {
case 'b':
sb.append('\b');
break;
case 't':
sb.append('\t');
break;
case 'n':
sb.append('\n');
break;
case 'f':
sb.append('\f');
break;
case 'r':
sb.append('\r');
break;
case 'u':
try {
sb.append((char) Integer.parseInt(next4HexDigits(), 16));
} catch (NumberFormatException e) {
throw new JSONParseException("Illegal unicode escape", e,
scanner.parsePosition());
}
break;
case '"':
case '\\':
case '/':
sb.append(c);
break;
default:
throw new JSONParseException("Illegal escape",
scanner.parsePosition());
}
break;
case '"':
return sb;
default:
sb.append(c);
break;
}
}
} catch (IOException e) {
throw new JSONParseException("IOException", e, scanner.parsePosition());
}
throw new JSONParseException("String value too long", scanner.parsePosition());
}
/**
* Skip the characters up to the next close quote character.
* Backslash processing is done. The formal JSON format only allows
* strings in double quotes.
*
* @throws JSONException Unterminated string.
*/
public void skipString() throws JSONException {
char c = scanner.next();
if(c != '"') {
throw new JSONParseException("Unexpected string delimiter",
scanner.parsePosition());
}
for (;;) {
c = scanner.next();
switch (c) {
case (char)0:
case (char)10: // \n
case (char)13: // \r
throw new JSONParseException("Unterminated string",
scanner.parsePosition());
case (char)1:
case (char)2:
case (char)3:
case (char)4:
case (char)5:
case (char)6:
case (char)7:
case (char)8:
case (char)9:
case (char)11:
case (char)12:
case (char)14:
case (char)15:
case (char)16:
case (char)17:
case (char)18:
case (char)19:
case (char)20:
case (char)21:
case (char)22:
case (char)23:
case (char)24:
case (char)25:
case (char)26:
case (char)27:
case (char)28:
case (char)29:
case (char)30:
case (char)31:
throw new JSONParseException("Unescaped control code",
scanner.parsePosition());
case '\\':
c = scanner.next();
switch (c) {
case 'b':
case 't':
case 'n':
case 'f':
case 'r':
case '"':
case '\\':
case '/':
break;
case 'u':
next4HexDigits();
break;
default:
throw new JSONParseException("Illegal escape",
scanner.parsePosition());
}
break;
case '"':
return;
default:
break;
}
}
}
/**
* Get the next 4 hexadecimal chars in the stream, and return them as a
* String value. Any character outside the hexadecimal range is
* immediately rejected.
*
* @return a String containing the 4 hexadecimal characters
*/
private String next4HexDigits() throws JSONException {
char[] chars = new char[4];
for (int pos = 0; pos < 4; pos += 1) {
char c = scanner.next();
if (scanner.end()) {
throw new JSONParseException("Substring bounds error",
scanner.parsePosition());
} else if((c >= '0' && c <= '9')
|| (c >= 'a' && c <= 'f')
|| (c >= 'A' && c <= 'F')) {
chars[pos] = c;
} else {
throw new JSONParseException("Illegal unicode escape",
scanner.parsePosition());
}
}
return String.valueOf(chars);
}
/**
* Parse a number strictly according to the JSON specification.
*
* @param sb The Appendable to which the parsed character sequence is
* appended
* @return {@code true} if the number is a floating point value, otherwise
* {@code false} to indicate an integer value
*/
public boolean nextNumber(Appendable sb) throws JSONException {
boolean dbl = false;
char c = scanner.next();
try {
// likely digit
if(c == '-') {
sb.append(c);
c = scanner.next();
}
if(c == '0') {
sb.append(c);
c = scanner.next();
} else if((c >= '1') && (c <= '9')) {
sb.append(c);
// whole number values
c = scanner.next();
while((c >= '0') && (c <= '9')) {
sb.append(c);
c = scanner.next();
}
} else {
throw new JSONParseException("Expected number", scanner.parsePosition());
}
if(c == '.') {
dbl = true;
sb.append(c);
// at least one digit after decimal
c = scanner.next();
if ((c >= '0') && (c <= '9')) {
sb.append(c);
c = scanner.next();
} else {
throw new JSONParseException("Expected number", scanner.parsePosition());
}
// remaining decimal place values
while((c >= '0') && (c <= '9')) {
sb.append(c);
c = scanner.next();
}
}
if((c == 'e') || (c == 'E')) {
dbl = true;
sb.append(c);
// exponent values
c = scanner.next();
if((c == '+') || (c == '-')) {
sb.append(c);
c = scanner.next();
}
if((c >= '0') && (c <= '9')) {
sb.append(c);
c = scanner.next();
} else {
throw new JSONParseException("Expected exponent value",
scanner.parsePosition());
}
while((c >= '0') && (c <= '9')) {
sb.append(c);
c = scanner.next();
}
}
scanner.back();
} catch (IOException e) {
throw new JSONParseException("IO exception", e, scanner.parsePosition());
}
return dbl;
}
/**
* Parse a number strictly according to the JSON specification.
* <p>
* Most practical JSON parsers limit the number values to those
* expressible by {@code Long} or {@code Double} values.</p>
*
* @param sb The Appendable to which the parsed character sequence is
* appended
* @param mDigits maximum number of mantissa digits to be parsed,
* <= 0 to limit to {@code Integer.MAX_VALUE}
* @param eDigits maximum number of exponent digits to be parsed,
* 0 for no exponent, or < 0 to limit to
* {@code Integer.MAX_VALUE}
* @return {@code true} if the number is a floating point value, otherwise
* {@code false} to indicate an integer value
*/
public boolean nextNumber(Appendable sb, int mDigits, int eDigits) throws JSONException {
int m = 0, e = 0;
boolean dbl = false;
char c = scanner.next();
if(mDigits <= 0) {
mDigits = Integer.MAX_VALUE;
}
if(eDigits < 0) {
eDigits = Integer.MAX_VALUE;
}
try {
// likely digit
if(c == '-') {
sb.append(c);
c = scanner.next();
}
if(c == '0') {
sb.append(c);
m++;
c = scanner.next();
} else if((c >= '1') && (c <= '9')) {
sb.append(c);
m++;
// whole number values
c = scanner.next();
while((c >= '0') && (c <= '9') && (m <= mDigits)) {
sb.append(c);
m++;
c = scanner.next();
}
} else {
throw new JSONParseException("Expected number", scanner.parsePosition());
}
if(m > mDigits) {
throw new JSONParseException("Number overflow", scanner.parsePosition());
}
if(c == '.') {
dbl = true;
sb.append(c);
// at least one digit after decimal
c = scanner.next();
if ((c >= '0') && (c <= '9')) {
sb.append(c);
m++;
c = scanner.next();
} else {
throw new JSONParseException("Expected number", scanner.parsePosition());
}
// remaining decimal place values
while((c >= '0') && (c <= '9') && (m <= mDigits)) {
sb.append(c);
m++;
c = scanner.next();
}
if(m > mDigits) {
throw new JSONParseException("Number overflow", scanner.parsePosition());
}
}
if((c == 'e') || (c == 'E')) {
dbl = true;
sb.append(c);
// exponent values
c = scanner.next();
if((c == '+') || (c == '-')) {
sb.append(c);
c = scanner.next();
}
if((c >= '0') && (c <= '9')) {
sb.append(c);
e++;
c = scanner.next();
} else {
throw new JSONParseException("Expected exponent value",
scanner.parsePosition());
}
while((c >= '0') && (c <= '9') && (e <= eDigits)) {
sb.append(c);
e++;
c = scanner.next();
}
if(e > eDigits) {
throw new JSONParseException("Number overflow",
scanner.parsePosition());
}
}
scanner.back();
} catch (IOException ex) {
throw new JSONParseException("IO exception", ex, scanner.parsePosition());
}
return dbl;
}
/**
* Skip a number strictly according to the JSON specification.
*/
public void skipNumber() throws JSONException {
char c = scanner.next();
// likely digit
if(c == '-') {
c = scanner.next();
}
if(c == '0') {
c = scanner.next();
} else if((c >= '1') && (c <= '9')) {
// whole number values
c = scanner.next();
while((c >= '0') && (c <= '9')) {
c = scanner.next();
}
} else {
throw new JSONParseException("Expected number", scanner.parsePosition());
}
if(c == '.') {
// at least one digit after decimal
c = scanner.next();
if ((c >= '0') && (c <= '9')) {
c = scanner.next();
} else {
throw new JSONParseException("Expected number", scanner.parsePosition());
}
// remaining decimal place values
while((c >= '0') && (c <= '9')) {
c = scanner.next();
}
}
if((c == 'e') || (c == 'E')) {
// exponent values
c = scanner.next();
if((c == '+') || (c == '-')) {
c = scanner.next();
}
if((c >= '0') && (c <= '9')) {
c = scanner.next();
} else {
throw new JSONParseException("Expected exponent value",
scanner.parsePosition());
}
while((c >= '0') && (c <= '9')) {
c = scanner.next();
}
}
scanner.back();
}
/**
* Indicates the current position of the scanner.
*
* @return a {@code ParsePosition} representing the current location of
* the scanner
*/
public ParsePosition parsePosition() {
return scanner.parsePosition();
}
/**
* Make a printable string of this {@code JSONLexer}.
*
* @return "JSONLexer at {index} [character {character} line {line}]"
*/
@Override
public String toString() {
return "JSONLexer " + scanner.parsePosition().getPositionDetails();
}
}