Debian Codegraph @

src/org/eclipse/parsson/JsonParserImpl.java

raw symbols SCIP
1 /*
2 * Copyright (c) 2012, 2024 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 java.io.IOException;
20 import java.io.InputStream;
21 import java.io.InputStreamReader;
22 import java.io.Reader;
23 import java.math.BigDecimal;
24 import java.nio.charset.Charset;
25 import java.util.AbstractMap;
26 import java.util.Map;
27 import java.util.NoSuchElementException;
28 import java.util.Objects;
29 import java.util.Spliterator;
30 import java.util.Spliterators;
31 import java.util.function.Consumer;
32 import java.util.function.Function;
33 import java.util.stream.Stream;
34 import java.util.stream.StreamSupport;
35
36 import jakarta.json.JsonArray;
37 import jakarta.json.JsonArrayBuilder;
38 import jakarta.json.JsonException;
39 import jakarta.json.JsonObject;
40 import jakarta.json.JsonObjectBuilder;
41 import jakarta.json.JsonValue;
42 import jakarta.json.stream.JsonLocation;
43 import jakarta.json.stream.JsonParser;
44 import jakarta.json.stream.JsonParsingException;
45
46 import org.eclipse.parsson.JsonTokenizer.JsonToken;
47
48 /**
49 * JSON parser implementation. NoneContext, ArrayContext, ObjectContext is used
50 * to go to next parser state.
51 *
52 * @author Jitendra Kotamraju
53 * @author Kin-man Chung
54 */
55 public class JsonParserImpl implements JsonParser {
56
57 private Context currentContext = new NoneContext();
58 private Event currentEvent;
59
60 private final Stack stack;
61 private final JsonTokenizer tokenizer;
62 private boolean closed = false;
63
64 private final JsonContext jsonContext;
65
66 public JsonParserImpl(Reader reader, JsonContext jsonContext) {
67 this.jsonContext = jsonContext;
68 stack = new Stack(jsonContext.depthLimit());
69 this.tokenizer = new JsonTokenizer(reader, jsonContext);
70 }
71
72 public JsonParserImpl(InputStream in, JsonContext jsonContext) {
73 this.jsonContext = jsonContext;
74 stack = new Stack(jsonContext.depthLimit());
75 UnicodeDetectingInputStream uin = new UnicodeDetectingInputStream(in);
76 this.tokenizer = new JsonTokenizer(new InputStreamReader(uin, uin.getCharset()), jsonContext);
77 }
78
79 public JsonParserImpl(InputStream in, Charset encoding, JsonContext jsonContext) {
80 this.jsonContext = jsonContext;
81 stack = new Stack(jsonContext.depthLimit());
82 this.tokenizer = new JsonTokenizer(new InputStreamReader(in, encoding), jsonContext);
83 }
84
85 @Override
86 public String getString() {
87 if (currentEvent == Event.KEY_NAME || currentEvent == Event.VALUE_STRING
88 || currentEvent == Event.VALUE_NUMBER) {
89 return tokenizer.getValue();
90 }
91 throw new IllegalStateException(
92 JsonMessages.PARSER_GETSTRING_ERR(currentEvent));
93 }
94
95 private <T> T getNumberValue(Function<JsonTokenizer, T> tokenizerFunction, Function<Event, String> exceptionMessageFunction) {
96 if (currentEvent != Event.VALUE_NUMBER) {
97 throw new IllegalStateException(
98 exceptionMessageFunction.apply(currentEvent));
99 }
100 return tokenizerFunction.apply(tokenizer);
101 }
102
103 @Override
104 public boolean isIntegralNumber() {
105 return getNumberValue(JsonTokenizer::isIntegral, JsonMessages::PARSER_ISINTEGRALNUMBER_ERR);
106 }
107
108 @Override
109 public int getInt() {
110 return getNumberValue(JsonTokenizer::getInt, JsonMessages::PARSER_GETINT_ERR);
111 }
112
113 boolean isDefinitelyInt() {
114 return tokenizer.isDefinitelyInt();
115 }
116
117 boolean isDefinitelyLong() {
118 return tokenizer.isDefinitelyLong();
119 }
120
121 @Override
122 public long getLong() {
123 return getNumberValue(JsonTokenizer::getLong, JsonMessages::PARSER_GETLONG_ERR);
124 }
125
126 @Override
127 public BigDecimal getBigDecimal() {
128 return getNumberValue(JsonTokenizer::getBigDecimal, JsonMessages::PARSER_GETBIGDECIMAL_ERR);
129 }
130
131 @Override
132 public JsonArray getArray() {
133 if (currentEvent != Event.START_ARRAY) {
134 throw new IllegalStateException(
135 JsonMessages.PARSER_GETARRAY_ERR(currentEvent));
136 }
137 return getArray(new JsonArrayBuilderImpl(jsonContext));
138 }
139
140 @Override
141 public JsonObject getObject() {
142 if (currentEvent != Event.START_OBJECT) {
143 throw new IllegalStateException(
144 JsonMessages.PARSER_GETOBJECT_ERR(currentEvent));
145 }
146 return getObject(new JsonObjectBuilderImpl(jsonContext));
147 }
148
149 @Override
150 public JsonValue getValue() {
151 switch (currentEvent) {
152 case START_ARRAY:
153 return getArray(new JsonArrayBuilderImpl(jsonContext));
154 case START_OBJECT:
155 return getObject(new JsonObjectBuilderImpl(jsonContext));
156 case KEY_NAME:
157 case VALUE_STRING:
158 return new JsonStringImpl(getCharSequence());
159 case VALUE_NUMBER:
160 if (isDefinitelyInt()) {
161 return JsonNumberImpl.getJsonNumber(getInt(), jsonContext.bigIntegerScaleLimit());
162 } else if (isDefinitelyLong()) {
163 return JsonNumberImpl.getJsonNumber(getLong(), jsonContext.bigIntegerScaleLimit());
164 }
165 return JsonNumberImpl.getJsonNumber(getBigDecimal(), jsonContext.bigIntegerScaleLimit());
166 case VALUE_TRUE:
167 return JsonValue.TRUE;
168 case VALUE_FALSE:
169 return JsonValue.FALSE;
170 case VALUE_NULL:
171 return JsonValue.NULL;
172 case END_ARRAY:
173 case END_OBJECT:
174 default:
175 throw new IllegalStateException(JsonMessages.PARSER_GETVALUE_ERR(currentEvent));
176 }
177 }
178
179 @Override
180 public Stream<JsonValue> getArrayStream() {
181 if (currentEvent != Event.START_ARRAY) {
182 throw new IllegalStateException(
183 JsonMessages.PARSER_GETARRAY_ERR(currentEvent));
184 }
185 Spliterator<JsonValue> spliterator =
186 new Spliterators.AbstractSpliterator<JsonValue>(Long.MAX_VALUE, Spliterator.ORDERED) {
187 @Override
188 public Spliterator<JsonValue> trySplit() {
189 return null;
190 }
191
192 @Override
193 public boolean tryAdvance(Consumer<? super JsonValue> action) {
194 if (action == null) {
195 throw new NullPointerException();
196 }
197 if (!hasNext()) {
198 return false;
199 }
200 if (next() == JsonParser.Event.END_ARRAY) {
201 return false;
202 }
203 action.accept(getValue());
204 return true;
205 }
206 };
207 return StreamSupport.stream(spliterator, false);
208 }
209
210 @Override
211 public Stream<Map.Entry<String, JsonValue>> getObjectStream() {
212 if (currentEvent != Event.START_OBJECT) {
213 throw new IllegalStateException(
214 JsonMessages.PARSER_GETOBJECT_ERR(currentEvent));
215 }
216 Spliterator<Map.Entry<String, JsonValue>> spliterator =
217 new Spliterators.AbstractSpliterator<Map.Entry<String, JsonValue>>(Long.MAX_VALUE, Spliterator.ORDERED) {
218 @Override
219 public Spliterator<Map.Entry<String, JsonValue>> trySplit() {
220 return null;
221 }
222
223 @Override
224 public boolean tryAdvance(Consumer<? super Map.Entry<String, JsonValue>> action) {
225 if (action == null) {
226 throw new NullPointerException();
227 }
228 if (!hasNext()) {
229 return false;
230 }
231 JsonParser.Event e = next();
232 if (e == JsonParser.Event.END_OBJECT) {
233 return false;
234 }
235 if (e != JsonParser.Event.KEY_NAME) {
236 throw new JsonException(JsonMessages.INTERNAL_ERROR());
237 }
238 String key = getString();
239 if (!hasNext()) {
240 throw new JsonException(JsonMessages.INTERNAL_ERROR());
241 }
242 next();
243 JsonValue value = getValue();
244 action.accept(new AbstractMap.SimpleImmutableEntry<>(key, value));
245 return true;
246 }
247 };
248 return StreamSupport.stream(spliterator, false);
249 }
250
251 @Override
252 public Stream<JsonValue> getValueStream() {
253 if (! (currentContext instanceof NoneContext)) {
254 throw new IllegalStateException(
255 JsonMessages.PARSER_GETVALUESTREAM_ERR());
256 }
257 Spliterator<JsonValue> spliterator =
258 new Spliterators.AbstractSpliterator<JsonValue>(Long.MAX_VALUE, Spliterator.ORDERED) {
259 @Override
260 public Spliterator<JsonValue> trySplit() {
261 return null;
262 }
263
264 @Override
265 public boolean tryAdvance(Consumer<? super JsonValue> action) {
266 if (action == null) {
267 throw new NullPointerException();
268 }
269 if (!hasNext()) {
270 return false;
271 }
272 next();
273 action.accept(getValue());
274 return true;
275 }
276 };
277 return StreamSupport.stream(spliterator, false);
278 }
279
280 @Override
281 public void skipArray() {
282 if (currentContext instanceof ArrayContext) {
283 currentContext.skip();
284 currentContext = stack.pop();
285 currentEvent = Event.END_ARRAY;
286 }
287 }
288
289 @Override
290 public void skipObject() {
291 if (currentContext instanceof ObjectContext) {
292 currentContext.skip();
293 currentContext = stack.pop();
294 currentEvent = Event.END_OBJECT;
295 }
296 }
297
298 private JsonArray getArray(JsonArrayBuilder builder) {
299 while(hasNext()) {
300 JsonParser.Event e = next();
301 if (e == JsonParser.Event.END_ARRAY) {
302 return builder.build();
303 }
304 builder.add(getValue());
305 }
306 throw parsingException(JsonToken.EOF, "[CURLYOPEN, SQUAREOPEN, STRING, NUMBER, TRUE, FALSE, NULL, SQUARECLOSE]");
307 }
308
309 private CharSequence getCharSequence() {
310 if (currentEvent == Event.KEY_NAME || currentEvent == Event.VALUE_STRING
311 || currentEvent == Event.VALUE_NUMBER) {
312 return tokenizer.getCharSequence();
313 }
314 throw new IllegalStateException(JsonMessages.PARSER_GETSTRING_ERR(currentEvent));
315 }
316
317 private JsonObject getObject(JsonObjectBuilder builder) {
318 while(hasNext()) {
319 JsonParser.Event e = next();
320 if (e == JsonParser.Event.END_OBJECT) {
321 return builder.build();
322 }
323 String key = getString();
324 next();
325 builder.add(key, getValue());
326 }
327 throw parsingException(JsonToken.EOF, "[STRING, CURLYCLOSE]");
328 }
329
330 @Override
331 public JsonLocation getLocation() {
332 return tokenizer.getLocation();
333 }
334
335 public JsonLocation getLastCharLocation() {
336 return tokenizer.getLastCharLocation();
337 }
338
339 @Override
340 public boolean hasNext() {
341 if (stack.isEmpty() && (currentEvent != null && currentEvent.compareTo(Event.KEY_NAME) > 0)) {
342 JsonToken token = tokenizer.nextToken();
343 if (token != JsonToken.EOF) {
344 throw new JsonParsingException(JsonMessages.PARSER_EXPECTED_EOF(token),
345 getLastCharLocation());
346 }
347 return false;
348 } else if (!stack.isEmpty() && !tokenizer.hasNextToken()) {
349 currentEvent = currentContext.getNextEvent();
350 return false;
351 }
352 return true;
353 }
354
355 @Override
356 public Event next() {
357 if (!hasNext()) {
358 throw new NoSuchElementException();
359 }
360 return currentEvent = currentContext.getNextEvent();
361 }
362
363 @Override
364 public Event currentEvent() {
365 return currentEvent;
366 }
367
368 @Override
369 public void close() {
370 if (!closed) {
371 try {
372 tokenizer.close();
373 closed = true;
374 } catch (IOException e) {
375 throw new JsonException(JsonMessages.PARSER_TOKENIZER_CLOSE_IO(), e);
376 }
377 }
378 }
379
380 // Using the optimized stack impl as we don't require other things
381 // like iterator etc.
382 private static final class Stack {
383 int size = 0;
384 final int limit;
385 private Context head;
386
387 Stack(int size) {
388 this.limit = size;
389 }
390
391 private void push(Context context) {
392 if (++size >= limit) {
393 throw new RuntimeException(JsonMessages.PARSER_INPUT_NESTED_TOO_DEEP(size));
394 }
395 context.next = head;
396 head = context;
397 }
398
399 private Context pop() {
400 if (head == null) {
401 throw new NoSuchElementException();
402 }
403 size--;
404 Context temp = head;
405 head = head.next;
406 return temp;
407 }
408
409 private Context peek() {
410 return head;
411 }
412
413 private boolean isEmpty() {
414 return head == null;
415 }
416 }
417
418 private abstract class Context {
419 Context next;
420 abstract Event getNextEvent();
421 abstract void skip();
422
423 protected Event nextEventIfValueOrObjectOrArrayStart(JsonToken token) {
424 if (token.isValue()) {
425 return token.getEvent();
426 } else if (token == JsonToken.CURLYOPEN) {
427 stack.push(currentContext);
428 currentContext = new ObjectContext();
429 return Event.START_OBJECT;
430 } else if (token == JsonToken.SQUAREOPEN) {
431 stack.push(currentContext);
432 currentContext = new ArrayContext();
433 return Event.START_ARRAY;
434 }
435 return null;
436 }
437 }
438
439 private final class NoneContext extends Context {
440 @Override
441 public Event getNextEvent() {
442 // Handle 1. { 2. [ 3. value
443 JsonToken token = tokenizer.nextToken();
444 Event event = nextEventIfValueOrObjectOrArrayStart(token);
445 if (event != null) {
446 return event;
447 }
448 throw parsingException(token, "[CURLYOPEN, SQUAREOPEN, STRING, NUMBER, TRUE, FALSE, NULL]");
449 }
450
451 @Override
452 void skip() {
453 // no-op
454 }
455 }
456
457 private JsonParsingException parsingException(JsonToken token, String expectedTokens) {
458 JsonLocation location = getLastCharLocation();
459 return new JsonParsingException(
460 JsonMessages.PARSER_INVALID_TOKEN(token, location, expectedTokens), location);
461 }
462
463 private abstract class SkippingContext extends Context {
464 private final JsonToken openToken;
465 private final JsonToken closeToken;
466
467 private boolean firstValue = true;
468
469 private SkippingContext(JsonToken openToken, JsonToken closeToken) {
470 this.openToken = Objects.requireNonNull(openToken);
471 this.closeToken = Objects.requireNonNull(closeToken);
472 }
473
474 @Override
475 void skip() {
476 JsonToken token;
477 int depth = 1;
478 do {
479 token = tokenizer.nextToken();
480 if (token == closeToken) {
481 depth--;
482 }
483 if (token == openToken) {
484 depth++;
485 }
486 } while (!(token == closeToken && depth == 0));
487 }
488
489 JsonToken firstValueOrJsonToken(JsonToken token) {
490 if (firstValue) {
491 firstValue = false;
492 } else {
493 if (token != JsonToken.COMMA) {
494 throw parsingException(token, "[COMMA]");
495 }
496 token = tokenizer.nextToken();
497 }
498 return token;
499 }
500 }
501
502 private final class ObjectContext extends SkippingContext {
503 private ObjectContext() {
504 super(JsonToken.CURLYOPEN, JsonToken.CURLYCLOSE);
505 }
506
507 /*
508 * Some more things could be optimized. For example, instead
509 * tokenizer.nextToken(), one could use tokenizer.matchColonToken() to
510 * match ':'. That might optimize a bit, but will fragment nextToken().
511 * I think the current one is more readable.
512 *
513 */
514 @Override
515 public Event getNextEvent() {
516 // Handle 1. } 2. name:value 3. ,name:value
517 JsonToken token = tokenizer.nextToken();
518 if (token == JsonToken.EOF) {
519 switch (currentEvent) {
520 case START_OBJECT:
521 throw parsingException(token, "[STRING, CURLYCLOSE]");
522 case KEY_NAME:
523 throw parsingException(token, "[COLON]");
524 default:
525 throw parsingException(token, "[COMMA, CURLYCLOSE]");
526 }
527 } else if (currentEvent == Event.KEY_NAME) {
528 // Handle 1. :value
529 if (token != JsonToken.COLON) {
530 throw parsingException(token, "[COLON]");
531 }
532 token = tokenizer.nextToken();
533 Event event = nextEventIfValueOrObjectOrArrayStart(token);
534 if (event != null) {
535 return event;
536 }
537 throw parsingException(token, "[CURLYOPEN, SQUAREOPEN, STRING, NUMBER, TRUE, FALSE, NULL]");
538 } else {
539 // Handle 1. } 2. name 3. ,name
540 if (token == JsonToken.CURLYCLOSE) {
541 currentContext = stack.pop();
542 return Event.END_OBJECT;
543 }
544
545 token = firstValueOrJsonToken(token);
546 if (token == JsonToken.STRING) {
547 return Event.KEY_NAME;
548 }
549 throw parsingException(token, "[STRING]");
550 }
551 }
552 }
553
554 private final class ArrayContext extends SkippingContext {
555
556 private ArrayContext() {
557 super(JsonToken.SQUAREOPEN, JsonToken.SQUARECLOSE);
558 }
559
560 // Handle 1. ] 2. value 3. ,value
561 @Override
562 public Event getNextEvent() {
563 JsonToken token = tokenizer.nextToken();
564 if (token == JsonToken.EOF) {
565 throw parsingException(token, (Objects.requireNonNull(currentEvent) == Event.START_ARRAY) ?
566 "[CURLYOPEN, SQUAREOPEN, STRING, NUMBER, TRUE, FALSE, NULL]" : "[COMMA, CURLYCLOSE]");
567 }
568 if (token == JsonToken.SQUARECLOSE) {
569 currentContext = stack.pop();
570 return Event.END_ARRAY;
571 }
572 token = firstValueOrJsonToken(token);
573
574 Event event = nextEventIfValueOrObjectOrArrayStart(token);
575 if (event != null) {
576 return event;
577 }
578 throw parsingException(token, "[CURLYOPEN, SQUAREOPEN, STRING, NUMBER, TRUE, FALSE, NULL]");
579 }
580 }
581 }