Debian Codegraph @

net/sf/saxon/ma/json/JsonParser.java

raw symbols SCIP
1 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2 // Copyright (c) 2018 Saxonica Limited.
3 // This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
4 // If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
5 // This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0.
6 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
7
8 package net.sf.saxon.ma.json;
9
10 import net.sf.saxon.expr.XPathContext;
11 import net.sf.saxon.om.NameChecker;
12 import net.sf.saxon.om.Sequence;
13 import net.sf.saxon.trans.Err;
14 import net.sf.saxon.trans.XPathException;
15 import net.sf.saxon.tree.util.FastStringBuffer;
16 import net.sf.saxon.type.StringToDouble;
17 import net.sf.saxon.value.BooleanValue;
18 import net.sf.saxon.value.StringValue;
19 import net.sf.saxon.value.Whitespace;
20
21 import java.util.Map;
22
23 /**
24 * Parser for JSON, which notifies parsing events to a JsonHandler
25 */
26 public class JsonParser {
27
28 public static final int ESCAPE = 1;
29 public static final int ALLOW_ANY_TOP_LEVEL = 2;
30 public static final int LIBERAL = 4;
31 public static final int VALIDATE = 8;
32 public static final int DEBUG = 16;
33 public static final int DUPLICATES_RETAINED = 32;
34 public static final int DUPLICATES_LAST = 64;
35 public static final int DUPLICATES_FIRST = 128;
36 public static final int DUPLICATES_REJECTED = 256;
37
38 public static final int DUPLICATES_SPECIFIED = DUPLICATES_FIRST | DUPLICATES_LAST | DUPLICATES_RETAINED | DUPLICATES_REJECTED;
39
40 private static final String ERR_GRAMMAR = "FOJS0001";
41 private static final String ERR_DUPLICATE = "FOJS0003";
42 private static final String ERR_SCHEMA = "FOJS0004";
43 private static final String ERR_OPTIONS = "FOJS0005";
44 private static final String ERR_LIMITS = "FOJS0001"; // No specific code in spec
45
46 /**
47 * Create a JSON parser
48 */
49
50 public JsonParser() {
51 }
52
53 /**
54 * Parse the JSON string according to supplied options
55 *
56 * @param input JSON input string
57 * @param flags options for the conversion as a map of xs:string : value pairs
58 * @param handler event handler to which parsing events are notified
59 * @param context XPath evaluation context
60 * @throws XPathException if the syntax of the input is incorrect
61 */
62 public void parse(String input, int flags, JsonHandler handler, XPathContext context) throws XPathException {
63 if (input.isEmpty()) {
64 invalidJSON("An empty string is not valid JSON", ERR_GRAMMAR);
65 }
66
67 JsonTokenizer t = new JsonTokenizer(input);
68 t.next();
69
70 parseConstruct(handler, t, flags, context);
71
72 if (t.next() != JsonTokenizer.EOF) {
73 invalidJSON("Unexpected token beyond end of JSON input", ERR_GRAMMAR);
74 }
75
76 }
77
78
79 public static int getFlags(Map<String, Sequence<?>> options, XPathContext context, Boolean allowValidate) throws XPathException {
80 int flags = 0;
81 BooleanValue debug = (BooleanValue) options.get("debug");
82 if (debug != null && debug.getBooleanValue()) {
83 flags |= DEBUG;
84 }
85
86 boolean escape = ((BooleanValue) options.get("escape")).getBooleanValue();
87 if (escape) {
88 flags |= ESCAPE;
89 if (options.get("fallback") != null) {
90 throw new XPathException("Cannot specify a fallback function when escape=true", "FOJS0005");
91 }
92 }
93
94 if (((BooleanValue) options.get("liberal")).getBooleanValue()) {
95 flags |= LIBERAL;
96 flags |= ALLOW_ANY_TOP_LEVEL;
97 }
98
99 boolean validate = false;
100 if (allowValidate) {
101 validate = ((BooleanValue) options.get("validate")).getBooleanValue();
102 if (validate) {
103 if (!context.getController().getExecutable().isSchemaAware()) {
104 error("Requiring validation on non-schema-aware processor", ERR_SCHEMA);
105 }
106 flags |= VALIDATE;
107 }
108 }
109
110 if (options.containsKey("duplicates")) {
111 String duplicates = ((StringValue) options.get("duplicates")).getStringValue();
112 switch (duplicates) {
113 case "reject":
114 flags |= DUPLICATES_REJECTED;
115 break;
116 case "use-last":
117 flags |= DUPLICATES_LAST;
118 break;
119 case "use-first":
120 flags |= DUPLICATES_FIRST;
121 break;
122 case "retain":
123 flags |= DUPLICATES_RETAINED;
124 break;
125 default:
126 error("Invalid value for 'duplicates' option", ERR_OPTIONS);
127 break;
128 }
129 if (validate && "retain".equals(duplicates)) {
130 error("The options validate:true and duplicates:retain cannot be used together", ERR_OPTIONS);
131 }
132 }
133 return flags;
134 }
135
136 /**
137 * Parse a JSON construct (top-level or nested)
138 *
139 * @param handler the handler to generate the result
140 * @param tokenizer the tokenizer, positioned at the first token of the construct to be read
141 * @param flags parsing options
142 * @param context XPath evaluation context
143 * @throws net.sf.saxon.trans.XPathException if a dynamic error occurs (for example, invalid JSON input)
144 */
145
146 private void parseConstruct(JsonHandler handler, JsonTokenizer tokenizer, int flags, XPathContext context) throws XPathException {
147 boolean debug = (flags & DEBUG) != 0;
148 if (debug) {
149 System.err.println("token:" + tokenizer.currentToken + " :" + tokenizer.currentTokenValue);
150 }
151 switch (tokenizer.currentToken) {
152 case JsonTokenizer.LCURLY:
153 parseObject(handler, tokenizer, flags, context);
154 break;
155
156 case JsonTokenizer.LSQB:
157 parseArray(handler, tokenizer, flags, context);
158 break;
159
160 case JsonTokenizer.NUMERIC_LITERAL:
161 String lexical = tokenizer.currentTokenValue.toString();
162 double d = parseNumericLiteral(lexical, flags);
163 handler.writeNumeric(lexical, d);
164 break;
165
166 case JsonTokenizer.TRUE:
167 handler.writeBoolean(true);
168 break;
169
170 case JsonTokenizer.FALSE:
171 handler.writeBoolean(false);
172 break;
173
174 case JsonTokenizer.NULL:
175 handler.writeNull();
176 break;
177
178 case JsonTokenizer.STRING_LITERAL:
179 String literal = tokenizer.currentTokenValue.toString();
180 handler.writeString(unescape(literal, flags, ERR_GRAMMAR));
181 break;
182
183 default:
184 invalidJSON("Unexpected symbol: " + tokenizer.currentTokenValue, ERR_GRAMMAR);
185 }
186 }
187
188 /**
189 * Parse a JSON object (or map), i.e. construct delimited by curly braces
190 *
191 * @param handler the handler to generate the result
192 * @param tokenizer the tokenizer, positioned at the object to be read
193 * @param flags parsing options as a set of flags
194 * @param context XPath evaluation context
195 * @throws net.sf.saxon.trans.XPathException if a dynamic error occurs (such as invalid JSON input)
196 */
197
198 private void parseObject(JsonHandler handler, JsonTokenizer tokenizer, int flags, XPathContext context) throws XPathException {
199 boolean liberal = (flags & LIBERAL) != 0;
200 handler.startMap();
201 int tok = tokenizer.next();
202 while (tok != JsonTokenizer.RCURLY) {
203 if (tok != JsonTokenizer.STRING_LITERAL && !(tok == JsonTokenizer.UNQUOTED_STRING && liberal)) {
204 invalidJSON("Property name must be a string literal", ERR_GRAMMAR);
205 }
206 String key = tokenizer.currentTokenValue.toString();
207 key = unescape(key, flags, ERR_GRAMMAR);
208 String reEscaped = handler.reEscape(key);
209 tok = tokenizer.next();
210 if (tok != JsonTokenizer.COLON) {
211 invalidJSON("Missing colon after \"" + Err.wrap(key) + "\"", ERR_GRAMMAR);
212 }
213 tokenizer.next();
214 boolean duplicate = handler.setKey(key, reEscaped);
215 if (duplicate && ((flags & DUPLICATES_REJECTED) != 0)) {
216 invalidJSON("Duplicate key value \"" + Err.wrap(key) + "\"", ERR_DUPLICATE);
217 }
218 try {
219 if (!duplicate || ((flags & (DUPLICATES_LAST | DUPLICATES_RETAINED)) != 0)) {
220 parseConstruct(handler, tokenizer, flags, context);
221 } else {
222 // retain first: parse the duplicate value but discard it
223 JsonHandler h2 = new JsonHandler();
224 h2.setContext(context);
225 parseConstruct(h2, tokenizer, flags, context);
226 }
227 } catch (StackOverflowError e) {
228 invalidJSON("Objects are too deeply nested", ERR_LIMITS);
229 }
230 tok = tokenizer.next();
231 if (tok == JsonTokenizer.COMMA) {
232 tok = tokenizer.next();
233 if (tok == JsonTokenizer.RCURLY) {
234 if (liberal) {
235 break; // tolerate the trailing comma
236 } else {
237 invalidJSON("Trailing comma after entry in object", ERR_GRAMMAR);
238 }
239 }
240 } else if (tok == JsonTokenizer.RCURLY) {
241 break;
242 } else {
243 invalidJSON("Unexpected token after value of \"" + Err.wrap(key) + "\" property", ERR_GRAMMAR);
244 }
245 }
246 handler.endMap();
247 }
248
249 /**
250 * Parse a JSON array, i.e. construct delimited by square brackets
251 *
252 * @param handler the handler to generate the result
253 * @param tokenizer the tokenizer, positioned at the object to be read
254 * @param flags parsing options
255 * @param context XPath evaluation context
256 * @throws net.sf.saxon.trans.XPathException if a dynamic error occurs (such as invalid JSON input)
257 */
258
259 private void parseArray(JsonHandler handler, JsonTokenizer tokenizer, int flags, XPathContext context) throws XPathException {
260 boolean liberal = (flags & LIBERAL) != 0;
261 handler.startArray();
262 int tok = tokenizer.next();
263 if (tok == JsonTokenizer.RSQB) {
264 handler.endArray();
265 return;
266 }
267 while (true) {
268 try {
269 parseConstruct(handler, tokenizer, flags, context);
270 } catch (StackOverflowError e) {
271 invalidJSON("Arrays are too deeply nested", ERR_LIMITS);
272 }
273 tok = tokenizer.next();
274 if (tok == JsonTokenizer.COMMA) {
275 tok = tokenizer.next();
276 if (tok == JsonTokenizer.RSQB) {
277 if (liberal) {
278 break;// tolerate the trailing comma
279 } else {
280 invalidJSON("Trailing comma after entry in array", ERR_GRAMMAR);
281 }
282 }
283 } else if (tok == JsonTokenizer.RSQB) {
284 break;
285 } else {
286 invalidJSON("Unexpected token (" + toString(tok, tokenizer.currentTokenValue.toString()) +
287 ") after entry in array", ERR_GRAMMAR);
288 }
289 }
290 handler.endArray();
291 }
292
293 /**
294 * Parse a JSON numeric literal,
295 *
296 * @param token the numeric literal to be parsed and converted
297 * @param flags parsing options
298 * @return the result of parsing and conversion to XDM
299 * @throws net.sf.saxon.trans.XPathException if a dynamic error occurs (such as invalid JSON input)
300 */
301
302 private double parseNumericLiteral(String token, int flags) throws XPathException {
303 try {
304 if ((flags & LIBERAL) == 0) {
305 // extra checks on the number disabled by choosing spec="liberal"
306 if (token.startsWith("+")) {
307 invalidJSON("Leading + sign not allowed: " + token, ERR_GRAMMAR);
308 } else {
309 String t = token;
310 if (t.startsWith("-")) {
311 t = t.substring(1);
312 }
313 if (t.startsWith("0") &&
314 !(t.equals("0") || t.startsWith("0.") || t.startsWith("0e") || t.startsWith("0E"))) {
315 invalidJSON("Redundant leading zeroes not allowed: " + token, ERR_GRAMMAR);
316 }
317 if (t.endsWith(".") || t.contains(".e") || t.contains(".E")) {
318 invalidJSON("Empty fractional part not allowed", ERR_GRAMMAR);
319 }
320 if (t.startsWith(".")) {
321 invalidJSON("Empty integer part not allowed", ERR_GRAMMAR);
322 }
323 }
324 }
325 return StringToDouble.getInstance().stringToNumber(token);
326 } catch (NumberFormatException e) {
327 invalidJSON("Invalid numeric literal: " + e.getMessage(), ERR_GRAMMAR);
328 return Double.NaN;
329 }
330 }
331
332 /**
333 * Unescape a JSON string literal,
334 *
335 * @param literal the string literal to be processed
336 * @param flags parsing options
337 * @param errorCode Error code
338 * @return the result of parsing and conversion to XDM
339 * @throws net.sf.saxon.trans.XPathException if a dynamic error occurs (such as invalid JSON input)
340 */
341
342 public static String unescape(String literal, int flags, String errorCode) throws XPathException {
343 if (literal.indexOf('\\') < 0) {
344 return literal;
345 }
346 boolean liberal = (flags & LIBERAL) != 0;
347 FastStringBuffer buffer = new FastStringBuffer(literal.length());
348 for (int i = 0; i < literal.length(); i++) {
349 char c = literal.charAt(i);
350 if (c == '\\') {
351 if (i++ == literal.length() - 1) {
352 throw new XPathException("Invalid JSON escape: String " + Err.wrap(literal) + " ends in backslash", errorCode);
353 }
354 switch (literal.charAt(i)) {
355 case '"':
356 buffer.append('"');
357 break;
358 case '\\':
359 buffer.append('\\');
360 break;
361 case '/':
362 buffer.append('/');
363 break;
364 case 'b':
365 buffer.append('\b');
366 break;
367 case 'f':
368 buffer.append('\f');
369 break;
370 case 'n':
371 buffer.append('\n');
372 break;
373 case 'r':
374 buffer.append('\r');
375 break;
376 case 't':
377 buffer.append('\t');
378 break;
379 case 'u':
380 try {
381 String hex = literal.substring(i + 1, i + 5);
382 int code = Integer.parseInt(hex, 16);
383 buffer.append((char) code);
384 i += 4;
385 } catch (Exception e) {
386 if (liberal) {
387 buffer.append("\\u");
388 } else {
389 throw new XPathException("Invalid JSON escape: \\u must be followed by four hex characters", errorCode);
390 }
391 }
392 break;
393 default:
394 if (liberal) {
395 buffer.append(literal.charAt(i));
396 } else {
397 char next = literal.charAt(i);
398 String xx = next < 256 ? next + "" : "x" + Integer.toHexString(next);
399 throw new XPathException("Unknown escape sequence \\" + xx, errorCode);
400 }
401 }
402 } else {
403 buffer.append(c);
404 }
405 }
406 return buffer.toString();
407 }
408
409 /**
410 * Throw an error
411 *
412 * @param message the error message
413 * @param code the error code to be used
414 * @throws net.sf.saxon.trans.XPathException always
415 */
416
417 private static void error(String message, String code)
418 throws XPathException {
419 throw new XPathException(message, code);
420 }
421
422 /**
423 * Throw an error
424 *
425 * @param message the error message
426 * @param code the error code to be used
427 * @throws net.sf.saxon.trans.XPathException always
428 */
429
430 private void invalidJSON(String message, String code)
431 throws XPathException {
432 error("Invalid JSON input: " + message, code);
433 }
434
435
436 /**
437 * Inner class to do the tokenization
438 */
439
440 private class JsonTokenizer {
441
442 private String input;
443 private int position;
444 public int currentToken;
445 public FastStringBuffer currentTokenValue = new FastStringBuffer(FastStringBuffer.C64);
446
447 public final static int LSQB = 1;
448 public final static int RSQB = 2;
449 public static final int LCURLY = 3;
450 public static final int RCURLY = 4;
451 public static final int STRING_LITERAL = 5;
452 public static final int NUMERIC_LITERAL = 6;
453 public static final int TRUE = 7;
454 public static final int FALSE = 8;
455 public static final int NULL = 9;
456 public static final int COLON = 10;
457 public static final int COMMA = 11;
458 public static final int UNQUOTED_STRING = 12; // for "liberal" parsing only
459 public static final int EOF = 999;
460
461 public JsonTokenizer(String input) {
462 this.input = input;
463 this.position = 0;
464 // Ignore a leading BOM
465 if (!input.isEmpty() && input.charAt(0) == 65279) {
466 position++;
467 }
468 }
469
470 public int next() throws XPathException {
471 currentToken = readToken();
472 return currentToken;
473 }
474
475 private int readToken() throws XPathException {
476 if (position >= input.length()) {
477 return EOF;
478 }
479 while (Whitespace.isWhitespace(input.charAt(position))) {
480 if (++position >= input.length()) {
481 return EOF;
482 }
483 }
484 char ch = input.charAt(position++);
485 switch (ch) {
486 case '[':
487 return LSQB;
488 case '{':
489 return LCURLY;
490 case ']':
491 return RSQB;
492 case '}':
493 return RCURLY;
494 case '"':
495 currentTokenValue.setLength(0);
496 boolean afterBackslash = false;
497 while (true) {
498 if (position >= input.length()) {
499 invalidJSON("Unclosed quotes in string literal", ERR_GRAMMAR);
500 }
501 char c = input.charAt(position++);
502 if (c < 32) {
503 invalidJSON("Unescaped control character (x" + Integer.toHexString(c) + ")", ERR_GRAMMAR);
504 }
505 if (afterBackslash && c == 'u') {
506 try {
507 String hex = input.substring(position, position + 4);
508 //noinspection ResultOfMethodCallIgnored
509 Integer.parseInt(hex, 16);
510 } catch (Exception e) {
511 invalidJSON("\\u must be followed by four hex characters", ERR_GRAMMAR);
512 }
513 }
514 if (c == '"' && !afterBackslash) {
515 break;
516 } else {
517 currentTokenValue.append(c);
518 afterBackslash = c == '\\' && !afterBackslash;
519 }
520 }
521 return STRING_LITERAL;
522 case ':':
523 return COLON;
524 case ',':
525 return COMMA;
526 case '-':
527 case '+': // for liberal parsing
528 case '.': // for liberal parsing
529 case '0':
530 case '1':
531 case '2':
532 case '3':
533 case '4':
534 case '5':
535 case '6':
536 case '7':
537 case '8':
538 case '9':
539 currentTokenValue.setLength(0);
540 currentTokenValue.append(ch);
541 if (position < input.length()) { // We could be in ECMA mode when there is a single digit
542 while (true) {
543 char c = input.charAt(position);
544 if ((c >= '0' && c <= '9') || c == '-' || c == '+' || c == '.' || c == 'e' || c == 'E') {
545 currentTokenValue.append(c);
546 if (++position >= input.length()) {
547 break;
548 }
549 } else {
550 break;
551 }
552 }
553 }
554 return NUMERIC_LITERAL;
555 default: {
556 // Allow unquoted strings in liberal mode
557 if (NameChecker.isNCNameChar(ch)) {
558 currentTokenValue.setLength(0);
559 currentTokenValue.append(ch);
560 while (position < input.length()) {
561 char c = input.charAt(position);
562 if (NameChecker.isNCNameChar(c)) {
563 currentTokenValue.append(c);
564 position++;
565 } else {
566 break;
567 }
568 }
569 String val = currentTokenValue.toString();
570 switch (val) {
571 case "true":
572 return TRUE;
573 case "false":
574 return FALSE;
575 case "null":
576 return NULL;
577 default:
578 return UNQUOTED_STRING;
579 }
580 } else {
581 char c = input.charAt(--position);
582 invalidJSON("Unexpected character '" + c + "' (\\u" +
583 Integer.toHexString(c) + ") at position " + position, ERR_GRAMMAR);
584 return -1;
585 }
586 }
587 }
588 }
589 }
590
591
592 public static String toString(int token, String currentTokenValue) {
593 switch (token) {
594 case JsonTokenizer.LSQB:
595 return "[";
596 case JsonTokenizer.RSQB:
597 return "]";
598 case JsonTokenizer.LCURLY:
599 return "{";
600 case JsonTokenizer.RCURLY:
601 return "}";
602 case JsonTokenizer.STRING_LITERAL:
603 return "string (\"" + currentTokenValue + "\")";
604 case JsonTokenizer.NUMERIC_LITERAL:
605 return "number (" + currentTokenValue + ")";
606 case JsonTokenizer.TRUE:
607 return "true";
608 case JsonTokenizer.FALSE:
609 return "false";
610 case JsonTokenizer.NULL:
611 return "null";
612 case JsonTokenizer.COLON:
613 return ":";
614 case JsonTokenizer.COMMA:
615 return ",";
616 case JsonTokenizer.EOF:
617 return "<eof>";
618 default:
619 return "<" + token + ">";
620 }
621 }
622
623
624 }
625
626 // Copyright (c) 2018 Saxonica Limited.