Debian Codegraph @

src/org/eclipse/parsson/JsonTokenizer.java

raw symbols SCIP
1 /*
2 * Copyright (c) 2012, 2023 Oracle and/or its affiliates. All rights reserved.
3 *
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v. 2.0, which is available at
6 * http://www.eclipse.org/legal/epl-2.0.
7 *
8 * This Source Code may also be made available under the following Secondary
9 * Licenses when the conditions for such availability set forth in the
10 * Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
11 * version 2 with the GNU Classpath Exception, which is available at
12 * https://www.gnu.org/software/classpath/license.html.
13 *
14 * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
15 */
16
17 package org.eclipse.parsson;
18
19 import jakarta.json.JsonException;
20 import jakarta.json.stream.JsonLocation;
21 import jakarta.json.stream.JsonParser;
22 import jakarta.json.stream.JsonParsingException;
23 import java.io.Closeable;
24 import java.io.IOException;
25 import java.io.Reader;
26 import java.math.BigDecimal;
27 import java.util.Arrays;
28
29 import jakarta.json.stream.JsonParser.Event;
30
31 /**
32 * JSON Tokenizer
33 *
34 * @author Jitendra Kotamraju
35 */
36 final class JsonTokenizer implements Closeable {
37 // Table to look up hex ch -> value (for e.g HEX['F'] = 15, HEX['5'] = 5)
38 private final static int[] HEX = new int[128];
39 static {
40 Arrays.fill(HEX, -1);
41 for (int i='0'; i <= '9'; i++) {
42 HEX[i] = i-'0';
43 }
44 for (int i='A'; i <= 'F'; i++) {
45 HEX[i] = 10+i-'A';
46 }
47 for (int i='a'; i <= 'f'; i++) {
48 HEX[i] = 10+i-'a';
49 }
50 }
51 private final static int HEX_LENGTH = HEX.length;
52
53 private final JsonContext jsonContext;
54
55 private final Reader reader;
56
57 // Internal buffer that is used for parsing. It is also used
58 // for storing current string and number value token
59 private char[] buf;
60
61 // Indexes in buffer
62 //
63 // XXXssssssssssssXXXXXXXXXXXXXXXXXXXXXXrrrrrrrrrrrrrrXXXXXX
64 // ^ ^ ^ ^
65 // | | | |
66 // storeBegin storeEnd readBegin readEnd
67 private int readBegin;
68 private int readEnd;
69 private int storeBegin;
70 private int storeEnd;
71
72 // line number of the current pointer of parsing char
73 private long lineNo = 1;
74
75 // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
76 // ^
77 // |
78 // bufferOffset
79 //
80 // offset of the last \r\n or \n. will be used to calculate column number
81 // of a token or an error. This may be outside of the buffer.
82 private long lastLineOffset = 0;
83 // offset in the stream for the start of the buffer, will be used in
84 // calculating JsonLocation's stream offset, column no.
85 private long bufferOffset = 0;
86 private boolean closed = false;
87
88 private boolean minus;
89 private boolean fracOrExp;
90 private BigDecimal bd;
91
92 enum JsonToken {
93 CURLYOPEN(Event.START_OBJECT, false),
94 SQUAREOPEN(Event.START_ARRAY, false),
95 COLON(null, false),
96 COMMA(null, false),
97 STRING(Event.VALUE_STRING, true),
98 NUMBER(Event.VALUE_NUMBER, true),
99 TRUE(Event.VALUE_TRUE, true),
100 FALSE(Event.VALUE_FALSE, true),
101 NULL(Event.VALUE_NULL, true),
102 CURLYCLOSE(Event.END_OBJECT, false),
103 SQUARECLOSE(Event.END_ARRAY, false),
104 EOF(null, false);
105
106 private final JsonParser.Event event;
107 private final boolean value;
108
109 JsonToken(JsonParser.Event event, boolean value) {
110 this.event = event;
111 this.value = value;
112 }
113
114 JsonParser.Event getEvent() {
115 return event;
116 }
117
118 boolean isValue() {
119 return value;
120 }
121 }
122
123 JsonTokenizer(Reader reader, JsonContext jsonContext) {
124 this.reader = reader;
125 this.jsonContext = jsonContext;
126 buf = jsonContext.bufferPool().take();
127 }
128
129 private void readString() {
130 // when inPlace is true, no need to copy chars
131 boolean inPlace = true;
132 storeBegin = storeEnd = readBegin;
133
134 do {
135 // Write unescaped char block within the current buffer
136 if (inPlace) {
137 int ch;
138 while(readBegin < readEnd && ((ch=buf[readBegin]) >= 0x20) && ch != '\\') {
139 if (ch == '"') {
140 storeEnd = readBegin++; // ++ to consume quote char
141 return; // Got the entire string
142 }
143 readBegin++; // consume unescaped char
144 }
145 storeEnd = readBegin;
146 }
147
148 // string may be crossing buffer boundaries and may contain
149 // escaped characters.
150 int ch = read();
151 if (ch >= 0x20 && ch != 0x22 && ch != 0x5c) {
152 if (!inPlace) {
153 buf[storeEnd] = (char)ch;
154 }
155 storeEnd++;
156 continue;
157 }
158 switch (ch) {
159 case '\\':
160 inPlace = false; // Now onwards need to copy chars
161 unescape();
162 break;
163 case '"':
164 return;
165 default:
166 throw unexpectedChar(ch);
167 }
168 } while (true);
169 }
170
171 private void unescape() {
172 int ch = read();
173 switch (ch) {
174 case 'b':
175 buf[storeEnd++] = '\b';
176 break;
177 case 't':
178 buf[storeEnd++] = '\t';
179 break;
180 case 'n':
181 buf[storeEnd++] = '\n';
182 break;
183 case 'f':
184 buf[storeEnd++] = '\f';
185 break;
186 case 'r':
187 buf[storeEnd++] = '\r';
188 break;
189 case '"':
190 case '\\':
191 case '/':
192 buf[storeEnd++] = (char)ch;
193 break;
194 case 'u': {
195 int unicode = 0;
196 for (int i = 0; i < 4; i++) {
197 int ch3 = read();
198 int digit = (ch3 >= 0 && ch3 < HEX_LENGTH) ? HEX[ch3] : -1;
199 if (digit < 0) {
200 throw unexpectedChar(ch3);
201 }
202 unicode = (unicode << 4)|digit;
203 }
204 buf[storeEnd++] = (char)unicode;
205 break;
206 }
207 default:
208 throw unexpectedChar(ch);
209 }
210 }
211
212 // Reads a number char. If the char is within the buffer, directly
213 // reads from the buffer. Otherwise, uses read() which takes care
214 // of resizing, filling up the buf, adjusting the pointers
215 private int readNumberChar() {
216 if (readBegin < readEnd) {
217 return buf[readBegin++];
218 } else {
219 storeEnd = readBegin;
220 return read();
221 }
222 }
223
224 private void readNumber(int ch) {
225 storeBegin = storeEnd = readBegin-1;
226 // sign
227 if (ch == '-') {
228 this.minus = true;
229 ch = readNumberChar();
230 if (ch < '0' || ch >'9') {
231 throw unexpectedChar(ch);
232 }
233 }
234
235 // int
236 if (ch == '0') {
237 ch = readNumberChar();
238 } else {
239 do {
240 ch = readNumberChar();
241 } while (ch >= '0' && ch <= '9');
242 }
243
244 // frac
245 if (ch == '.') {
246 this.fracOrExp = true;
247 int count = 0;
248 do {
249 ch = readNumberChar();
250 count++;
251 } while (ch >= '0' && ch <= '9');
252 if (count == 1) {
253 throw unexpectedChar(ch);
254 }
255 }
256
257 // exp
258 if (ch == 'e' || ch == 'E') {
259 this.fracOrExp = true;
260 ch = readNumberChar();
261 if (ch == '+' || ch == '-') {
262 ch = readNumberChar();
263 }
264 int count;
265 for (count = 0; ch >= '0' && ch <= '9'; count++) {
266 ch = readNumberChar();
267 }
268 if (count == 0) {
269 throw unexpectedChar(ch);
270 }
271 }
272 if (ch != -1) {
273 // Only reset readBegin if eof has not been reached
274 readBegin--;
275 storeEnd = readBegin;
276 }
277 }
278
279 private void readTrue() {
280 int ch1 = read();
281 if (ch1 != 'r') {
282 throw expectedChar(ch1, 'r');
283 }
284 int ch2 = read();
285 if (ch2 != 'u') {
286 throw expectedChar(ch2, 'u');
287 }
288 int ch3 = read();
289 if (ch3 != 'e') {
290 throw expectedChar(ch3, 'e');
291 }
292 }
293
294 private void readFalse() {
295 int ch1 = read();
296 if (ch1 != 'a') {
297 throw expectedChar(ch1, 'a');
298 }
299 int ch2 = read();
300 if (ch2 != 'l') {
301 throw expectedChar(ch2, 'l');
302 }
303 int ch3 = read();
304 if (ch3 != 's') {
305 throw expectedChar(ch3, 's');
306 }
307 int ch4 = read();
308 if (ch4 != 'e') {
309 throw expectedChar(ch4, 'e');
310 }
311 }
312
313 private void readNull() {
314 int ch1 = read();
315 if (ch1 != 'u') {
316 throw expectedChar(ch1, 'u');
317 }
318 int ch2 = read();
319 if (ch2 != 'l') {
320 throw expectedChar(ch2, 'l');
321 }
322 int ch3 = read();
323 if (ch3 != 'l') {
324 throw expectedChar(ch3, 'l');
325 }
326 }
327
328 /*
329 * Could be optimized if the parser uses separate methods to match colon
330 * etc (that would avoid the switch statement cost in certain cases)
331 */
332 JsonToken nextToken() {
333 reset();
334 int ch = read();
335
336 // whitespace
337 while (ch == 0x20 || ch == 0x09 || ch == 0x0a || ch == 0x0d) {
338 if (ch == '\r') {
339 ++lineNo;
340 ch = read();
341 if (ch == '\n') {
342 lastLineOffset = bufferOffset+readBegin;
343 } else {
344 lastLineOffset = bufferOffset+readBegin-1;
345 continue;
346 }
347 } else if (ch == '\n') {
348 ++lineNo;
349 lastLineOffset = bufferOffset+readBegin;
350 }
351 ch = read();
352 }
353
354 switch (ch) {
355 case '"':
356 readString();
357 return JsonToken.STRING;
358 case '{':
359 return JsonToken.CURLYOPEN;
360 case '[':
361 return JsonToken.SQUAREOPEN;
362 case ':':
363 return JsonToken.COLON;
364 case ',':
365 return JsonToken.COMMA;
366 case 't':
367 readTrue();
368 return JsonToken.TRUE;
369 case 'f':
370 readFalse();
371 return JsonToken.FALSE;
372 case 'n':
373 readNull();
374 return JsonToken.NULL;
375 case ']':
376 return JsonToken.SQUARECLOSE;
377 case '}':
378 return JsonToken.CURLYCLOSE;
379 case '0':
380 case '1':
381 case '2':
382 case '3':
383 case '4':
384 case '5':
385 case '6':
386 case '7':
387 case '8':
388 case '9':
389 case '-':
390 readNumber(ch);
391 return JsonToken.NUMBER;
392 case -1:
393 return JsonToken.EOF;
394 default:
395 throw unexpectedChar(ch);
396 }
397 }
398
399 boolean hasNextToken() {
400 reset();
401 int ch = peek();
402
403 // whitespace
404 while (ch == 0x20 || ch == 0x09 || ch == 0x0a || ch == 0x0d) {
405 if (ch == '\r') {
406 ++lineNo;
407 ++readBegin;
408 ch = peek();
409 if (ch == '\n') {
410 lastLineOffset = bufferOffset+readBegin+1;
411 } else {
412 lastLineOffset = bufferOffset+readBegin;
413 continue;
414 }
415 } else if (ch == '\n') {
416 ++lineNo;
417 lastLineOffset = bufferOffset+readBegin+1;
418 }
419 ++readBegin;
420 ch = peek();
421 }
422 return ch != -1;
423 }
424
425 private int peek() {
426 try {
427 if (readBegin == readEnd) { // need to fill the buffer
428 int len = fillBuf();
429 if (len == -1) {
430 return -1;
431 }
432 assert len != 0;
433 readBegin = storeEnd;
434 readEnd = readBegin+len;
435 }
436 return buf[readBegin];
437 } catch (IOException ioe) {
438 throw new JsonException(JsonMessages.TOKENIZER_IO_ERR(), ioe);
439 }
440 }
441
442 // Gives the location of the last char. Used for
443 // JsonParsingException.getLocation
444 JsonLocation getLastCharLocation() {
445 // Already read the char, so subtracting -1
446 return new JsonLocationImpl(lineNo, bufferOffset +readBegin-lastLineOffset, bufferOffset +readBegin-1);
447 }
448
449 // Gives the parser location. Used for JsonParser.getLocation
450 JsonLocation getLocation() {
451 return new JsonLocationImpl(lineNo, bufferOffset +readBegin-lastLineOffset+1, bufferOffset +readBegin);
452 }
453
454 private int read() {
455 try {
456 if (readBegin == readEnd) { // need to fill the buffer
457 int len = fillBuf();
458 if (len == -1) {
459 return -1;
460 }
461 assert len != 0;
462 readBegin = storeEnd;
463 readEnd = readBegin+len;
464 }
465 return buf[readBegin++];
466 } catch (IOException ioe) {
467 throw new JsonException(JsonMessages.TOKENIZER_IO_ERR(), ioe);
468 }
469 }
470
471 private int fillBuf() throws IOException {
472 if (storeEnd != 0) {
473 int storeLen = storeEnd-storeBegin;
474 if (storeLen > 0) {
475 // there is some store data
476 if (storeLen == buf.length) {
477 // buffer is full, double the capacity
478 char[] doubleBuf = Arrays.copyOf(buf, 2 * buf.length);
479 jsonContext.bufferPool().recycle(buf);
480 buf = doubleBuf;
481 } else {
482 // Left shift all the stored data to make space
483 System.arraycopy(buf, storeBegin, buf, 0, storeLen);
484 storeEnd = storeLen;
485 storeBegin = 0;
486 bufferOffset += readBegin-storeEnd;
487 }
488 } else {
489 storeBegin = storeEnd = 0;
490 bufferOffset += readBegin;
491 }
492 } else {
493 bufferOffset += readBegin;
494 }
495 // Fill the rest of the buf
496 return reader.read(buf, storeEnd, buf.length-storeEnd);
497 }
498
499 // state associated with the current token is no more valid
500 private void reset() {
501 if (storeEnd != 0) {
502 storeBegin = 0;
503 storeEnd = 0;
504 bd = null;
505 minus = false;
506 fracOrExp = false;
507 }
508 }
509
510 String getValue() {
511 return new String(buf, storeBegin, storeEnd-storeBegin);
512 }
513
514 CharSequence getCharSequence() {
515 int len = storeEnd - storeBegin;
516 return new StringBuilder(len).append(buf, storeBegin, len);
517 }
518
519 BigDecimal getBigDecimal() {
520 if (bd == null) {
521 int sourceLen = storeEnd - storeBegin;
522 if (sourceLen > jsonContext.bigDecimalLengthLimit()) {
523 throw new UnsupportedOperationException(
524 String.format(
525 "Number of BigDecimal source characters %d exceeded maximal allowed value of %d",
526 sourceLen, jsonContext.bigDecimalLengthLimit()));
527 }
528 bd = new BigDecimal(buf, storeBegin, sourceLen);
529 }
530 return bd;
531 }
532
533 int getInt() {
534 // no need to create BigDecimal for common integer values (1-9 digits)
535 int storeLen = storeEnd-storeBegin;
536 if (!fracOrExp && (storeLen <= 9 || (minus && storeLen <= 10))) {
537 int num = 0;
538 int i = minus ? 1 : 0;
539 for(; i < storeLen; i++) {
540 num = num * 10 + (buf[storeBegin+i] - '0');
541 }
542 return minus ? -num : num;
543 } else {
544 return getBigDecimal().intValue();
545 }
546 }
547
548 long getLong() {
549 // no need to create BigDecimal for common integer values (1-18 digits)
550 int storeLen = storeEnd-storeBegin;
551 if (!fracOrExp && (storeLen <= 18 || (minus && storeLen <= 19))) {
552 long num = 0;
553 int i = minus ? 1 : 0;
554 for(; i < storeLen; i++) {
555 num = num * 10 + (buf[storeBegin+i] - '0');
556 }
557 return minus ? -num : num;
558 } else {
559 return getBigDecimal().longValue();
560 }
561 }
562
563 // returns true for common integer values (1-9 digits).
564 // So there are cases it will return false even though the number is int
565 boolean isDefinitelyInt() {
566 int storeLen = storeEnd-storeBegin;
567 return !fracOrExp && (storeLen <= 9 || (minus && storeLen <= 10));
568 }
569
570 // returns true for common long values (1-18 digits).
571 // So there are cases it will return false even though the number is long
572 boolean isDefinitelyLong() {
573 int storeLen = storeEnd-storeBegin;
574 return !fracOrExp && (storeLen <= 18 || (minus && storeLen <= 19));
575 }
576
577 boolean isIntegral() {
578 return !fracOrExp || getBigDecimal().scale() == 0;
579 }
580
581 @Override
582 public void close() throws IOException {
583 if (!closed) {
584 reader.close();
585 jsonContext.bufferPool().recycle(buf);
586 closed = true;
587 }
588 }
589
590 private JsonParsingException unexpectedChar(int ch) {
591 JsonLocation location = getLastCharLocation();
592 return new JsonParsingException(
593 JsonMessages.TOKENIZER_UNEXPECTED_CHAR(ch, location), location);
594 }
595
596 private JsonParsingException expectedChar(int unexpected, char expected) {
597 JsonLocation location = getLastCharLocation();
598 return new JsonParsingException(
599 JsonMessages.TOKENIZER_EXPECTED_CHAR(unexpected, location, expected), location);
600 }
601
602 }