2 /*-------------------------------------------------------------------------
5 * Lexical parser for jsonpath datatype
7 * Splits jsonpath string into tokens represented as JsonPathString structs.
8 * Decodes unicode and hex escaped strings.
10 * Copyright (c) 2019, PostgreSQL Global Development Group
13 * src/backend/utils/adt/jsonpath_scan.l
15 *-------------------------------------------------------------------------
20 #include "mb/pg_wchar.h"
21 #include "nodes/pg_list.h"
23 static JsonPathString scanstring;
25 /* Handles to the buffer that the lexer uses internally */
26 static YY_BUFFER_STATE scanbufhandle;
28 static int scanbuflen;
30 static void addstring(bool init, char *s, int l);
31 static void addchar(bool init, char s);
32 static enum yytokentype checkKeyword(void);
33 static void parseUnicode(char *s, int l);
34 static void parseHexChar(char *s);
36 /* Avoid exit() on fatal scanner errors (a bit ugly -- see yy_fatal_error) */
38 #define fprintf(file, fmt, msg) fprintf_to_ereport(fmt, msg)
41 fprintf_to_ereport(const char *fmt, const char *msg)
43 ereport(ERROR, (errmsg_internal("%s", msg)));
49 %option never-interactive
55 %option prefix="jsonpath_yy"
62 * We use exclusive states for quoted and non-quoted strings,
63 * quoted variable names and C-style comments.
65 * <xq> - quoted strings
66 * <xnq> - non-quoted strings
67 * <xvq> - quoted variable names
68 * <xc> - C-style comment
76 special [\?\%\$\.\[\]\{\}\(\)\|\&\!\=\<\>\@\#\,\*:\-\+\/]
78 /* "other" means anything that's not special, blank, or '\' or '"' */
79 other [^\?\%\$\.\[\]\{\}\(\)\|\&\!\=\<\>\@\#\,\*:\-\+\/\\\" \t\n\r\f]
82 integer (0|[1-9]{digit}*)
83 decimal {integer}\.{digit}+
84 decimalfail {integer}\.
85 real ({integer}|{decimal})[Ee][-+]?{digit}+
86 realfail1 ({integer}|{decimal})[Ee]
87 realfail2 ({integer}|{decimal})[Ee][-+]
90 unicode \\u({hex_dig}{4}|\{{hex_dig}{1,6}\})
91 unicodefail \\u({hex_dig}{0,3}|\{{hex_dig}{0,6})
92 hex_char \\x{hex_dig}{2}
93 hex_fail \\x{hex_dig}{0,1}
98 addstring(false, yytext, yyleng);
102 yylval->str = scanstring;
104 return checkKeyword();
108 yylval->str = scanstring;
112 <xnq>({special}|\") {
113 yylval->str = scanstring;
116 return checkKeyword();
120 yylval->str = scanstring;
122 return checkKeyword();
125 <xnq,xq,xvq>\\b { addchar(false, '\b'); }
127 <xnq,xq,xvq>\\f { addchar(false, '\f'); }
129 <xnq,xq,xvq>\\n { addchar(false, '\n'); }
131 <xnq,xq,xvq>\\r { addchar(false, '\r'); }
133 <xnq,xq,xvq>\\t { addchar(false, '\t'); }
135 <xnq,xq,xvq>\\v { addchar(false, '\v'); }
137 <xnq,xq,xvq>{unicode}+ { parseUnicode(yytext, yyleng); }
139 <xnq,xq,xvq>{hex_char} { parseHexChar(yytext); }
141 <xnq,xq,xvq>{unicode}*{unicodefail} { yyerror(NULL, "invalid unicode sequence"); }
143 <xnq,xq,xvq>{hex_fail} { yyerror(NULL, "invalid hex character sequence"); }
145 <xnq,xq,xvq>{unicode}+\\ {
146 /* throw back the \\, and treat as unicode */
148 parseUnicode(yytext, yyleng);
151 <xnq,xq,xvq>\\. { addchar(false, yytext[1]); }
153 <xnq,xq,xvq>\\ { yyerror(NULL, "unexpected end after backslash"); }
155 <xq,xvq><<EOF>> { yyerror(NULL, "unexpected end of quoted string"); }
158 yylval->str = scanstring;
164 yylval->str = scanstring;
169 <xq,xvq>[^\\\"]+ { addstring(false, yytext, yyleng); }
171 <xc>\*\/ { BEGIN INITIAL; }
177 <xc><<EOF>> { yyerror(NULL, "unexpected end of comment"); }
179 \&\& { return AND_P; }
181 \|\| { return OR_P; }
185 \*\* { return ANY_P; }
187 \< { return LESS_P; }
189 \<\= { return LESSEQUAL_P; }
191 \=\= { return EQUAL_P; }
193 \<\> { return NOTEQUAL_P; }
195 \!\= { return NOTEQUAL_P; }
197 \>\= { return GREATEREQUAL_P; }
199 \> { return GREATER_P; }
202 addstring(true, yytext + 1, yyleng - 1);
203 addchar(false, '\0');
204 yylval->str = scanstring;
213 {special} { return *yytext; }
215 {blank}+ { /* ignore */ }
223 addstring(true, yytext, yyleng);
224 addchar(false, '\0');
225 yylval->str = scanstring;
230 addstring(true, yytext, yyleng);
231 addchar(false, '\0');
232 yylval->str = scanstring;
237 addstring(true, yytext, yyleng);
238 addchar(false, '\0');
239 yylval->str = scanstring;
244 /* throw back the ., and treat as integer */
246 addstring(true, yytext, yyleng);
247 addchar(false, '\0');
248 yylval->str = scanstring;
252 ({realfail1}|{realfail2}) { yyerror(NULL, "invalid floating point number"); }
266 addstring(true, yytext, yyleng);
270 <<EOF>> { yyterminate(); }
275 jsonpath_yyerror(JsonPathParseResult **result, const char *message)
277 if (*yytext == YY_END_OF_BUFFER_CHAR)
280 (errcode(ERRCODE_SYNTAX_ERROR),
281 /* translator: %s is typically "syntax error" */
282 errmsg("%s at end of jsonpath input", _(message))));
287 (errcode(ERRCODE_SYNTAX_ERROR),
288 /* translator: first %s is typically "syntax error" */
289 errmsg("%s at or near \"%s\" of jsonpath input",
290 _(message), yytext)));
294 typedef struct JsonPathKeyword
303 * Array of key words should be sorted by length and then
306 static const JsonPathKeyword keywords[] = {
307 { 2, false, IS_P, "is"},
308 { 2, false, TO_P, "to"},
309 { 3, false, ABS_P, "abs"},
310 { 3, false, LAX_P, "lax"},
311 { 4, false, FLAG_P, "flag"},
312 { 4, false, LAST_P, "last"},
313 { 4, true, NULL_P, "null"},
314 { 4, false, SIZE_P, "size"},
315 { 4, true, TRUE_P, "true"},
316 { 4, false, TYPE_P, "type"},
317 { 4, false, WITH_P, "with"},
318 { 5, true, FALSE_P, "false"},
319 { 5, false, FLOOR_P, "floor"},
320 { 6, false, DOUBLE_P, "double"},
321 { 6, false, EXISTS_P, "exists"},
322 { 6, false, STARTS_P, "starts"},
323 { 6, false, STRICT_P, "strict"},
324 { 7, false, CEILING_P, "ceiling"},
325 { 7, false, UNKNOWN_P, "unknown"},
326 { 8, false, KEYVALUE_P, "keyvalue"},
327 { 10,false, LIKE_REGEX_P, "like_regex"},
330 /* Check if current scanstring value is a keyword */
331 static enum yytokentype
336 const JsonPathKeyword *StopLow = keywords,
337 *StopHigh = keywords + lengthof(keywords),
340 if (scanstring.len > keywords[lengthof(keywords) - 1].len)
343 while (StopLow < StopHigh)
345 StopMiddle = StopLow + ((StopHigh - StopLow) >> 1);
347 if (StopMiddle->len == scanstring.len)
348 diff = pg_strncasecmp(StopMiddle->keyword, scanstring.val,
351 diff = StopMiddle->len - scanstring.len;
354 StopLow = StopMiddle + 1;
356 StopHigh = StopMiddle;
359 if (StopMiddle->lowercase)
360 diff = strncmp(StopMiddle->keyword, scanstring.val,
364 res = StopMiddle->val;
374 * Called before any actual parsing is done
377 jsonpath_scanner_init(const char *str, int slen)
383 * Might be left over after ereport()
388 * Make a scan buffer with special termination needed by flex.
392 scanbuf = palloc(slen + 2);
393 memcpy(scanbuf, str, slen);
394 scanbuf[slen] = scanbuf[slen + 1] = YY_END_OF_BUFFER_CHAR;
395 scanbufhandle = yy_scan_buffer(scanbuf, slen + 2);
402 * Called after parsing is done to clean up after jsonpath_scanner_init()
405 jsonpath_scanner_finish(void)
407 yy_delete_buffer(scanbufhandle);
412 * Resize scanstring so that it can append string of given length.
413 * Reinitialize if required.
416 resizeString(bool init, int appendLen)
420 scanstring.total = Max(32, appendLen);
421 scanstring.val = (char *) palloc(scanstring.total);
426 if (scanstring.len + appendLen >= scanstring.total)
428 while (scanstring.len + appendLen >= scanstring.total)
429 scanstring.total *= 2;
430 scanstring.val = repalloc(scanstring.val, scanstring.total);
435 /* Add set of bytes at "s" of length "l" to scanstring */
437 addstring(bool init, char *s, int l)
439 resizeString(init, l + 1);
440 memcpy(scanstring.val + scanstring.len, s, l);
444 /* Add single byte "c" to scanstring */
446 addchar(bool init, char c)
448 resizeString(init, 1);
449 scanstring.val[scanstring.len] = c;
454 /* Interface to jsonpath parser */
455 JsonPathParseResult *
456 parsejsonpath(const char *str, int len)
458 JsonPathParseResult *parseresult;
460 jsonpath_scanner_init(str, len);
462 if (jsonpath_yyparse((void *) &parseresult) != 0)
463 jsonpath_yyerror(NULL, "bogus input"); /* shouldn't happen */
465 jsonpath_scanner_finish();
470 /* Turn hex character into integer */
474 if (c >= '0' && c <= '9')
476 if (c >= 'a' && c <= 'f')
477 return c - 'a' + 0xA;
478 if (c >= 'A' && c <= 'F')
479 return c - 'A' + 0xA;
480 jsonpath_yyerror(NULL, "invalid hexadecimal digit");
481 return 0; /* not reached */
484 /* Add given unicode character to scanstring */
486 addUnicodeChar(int ch)
489 * For UTF8, replace the escape sequence by the actual
490 * utf8 character in lex->strval. Do this also for other
491 * encodings if the escape designates an ASCII character,
492 * otherwise raise an error.
497 /* We can't allow this, since our TEXT type doesn't */
499 (errcode(ERRCODE_UNTRANSLATABLE_CHARACTER),
500 errmsg("unsupported Unicode escape sequence"),
501 errdetail("\\u0000 cannot be converted to text.")));
503 else if (GetDatabaseEncoding() == PG_UTF8)
508 unicode_to_utf8(ch, (unsigned char *) utf8str);
509 utf8len = pg_utf_mblen((unsigned char *) utf8str);
510 addstring(false, utf8str, utf8len);
512 else if (ch <= 0x007f)
515 * This is the only way to designate things like a
516 * form feed character in JSON, so it's useful in all
519 addchar(false, (char) ch);
524 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
525 errmsg("invalid input syntax for type %s", "jsonpath"),
526 errdetail("Unicode escape values cannot be used for code "
527 "point values above 007F when the server encoding "
532 /* Add unicode character and process its hi surrogate */
534 addUnicode(int ch, int *hi_surrogate)
536 if (ch >= 0xd800 && ch <= 0xdbff)
538 if (*hi_surrogate != -1)
540 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
541 errmsg("invalid input syntax for type %s", "jsonpath"),
542 errdetail("Unicode high surrogate must not follow "
543 "a high surrogate.")));
544 *hi_surrogate = (ch & 0x3ff) << 10;
547 else if (ch >= 0xdc00 && ch <= 0xdfff)
549 if (*hi_surrogate == -1)
551 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
552 errmsg("invalid input syntax for type %s", "jsonpath"),
553 errdetail("Unicode low surrogate must follow a high "
555 ch = 0x10000 + *hi_surrogate + (ch & 0x3ff);
558 else if (*hi_surrogate != -1)
561 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
562 errmsg("invalid input syntax for type %s", "jsonpath"),
563 errdetail("Unicode low surrogate must follow a high "
571 * parseUnicode was adopted from json_lex_string() in
572 * src/backend/utils/adt/json.c
575 parseUnicode(char *s, int l)
578 int hi_surrogate = -1;
580 for (i = 2; i < l; i += 2) /* skip '\u' */
585 if (s[i] == '{') /* parse '\u{XX...}' */
587 while (s[++i] != '}' && i < l)
588 ch = (ch << 4) | hexval(s[i]);
591 else /* parse '\uXXXX' */
593 for (j = 0; j < 4 && i < l; j++)
594 ch = (ch << 4) | hexval(s[i++]);
597 addUnicode(ch, &hi_surrogate);
600 if (hi_surrogate != -1)
603 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
604 errmsg("invalid input syntax for type %s", "jsonpath"),
605 errdetail("Unicode low surrogate must follow a high "
610 /* Parse sequence of hex-encoded characters */
612 parseHexChar(char *s)
614 int ch = (hexval(s[2]) << 4) |
621 * Interface functions to make flex use palloc() instead of malloc().
622 * It'd be better to make these static, but flex insists otherwise.
626 jsonpath_yyalloc(yy_size_t bytes)
628 return palloc(bytes);
632 jsonpath_yyrealloc(void *ptr, yy_size_t bytes)
635 return repalloc(ptr, bytes);
637 return palloc(bytes);
641 jsonpath_yyfree(void *ptr)