json_lib.c 55.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/* Copyright (c) 2016, 2020, MariaDB Corporation.

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; version 2 of the License.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335  USA */

16
#include <my_global.h>
17
#include <string.h>
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
#include <m_ctype.h>
#include "json_lib.h"

/*
  JSON escaping lets user specify UTF16 codes of characters.
  So we're going to need the UTF16 charset capabilities. Let's import
  them from the utf16 charset.
*/
int my_utf16_uni(CHARSET_INFO *cs,
                 my_wc_t *pwc, const uchar *s, const uchar *e);
int my_uni_utf16(CHARSET_INFO *cs, my_wc_t wc, uchar *s, uchar *e);


void json_string_set_str(json_string_t *s,
                         const uchar *str, const uchar *end)
{
  s->c_str= str;
  s->str_end= end;
}


void json_string_set_cs(json_string_t *s, CHARSET_INFO *i_cs)
{
  s->cs= i_cs;
  s->error= 0;
  s->wc= i_cs->cset->mb_wc;
}


static void json_string_setup(json_string_t *s,
                              CHARSET_INFO *i_cs, const uchar *str,
                              const uchar *end)
{
  json_string_set_cs(s, i_cs);
  json_string_set_str(s, str, end);
}


enum json_char_classes {
  C_EOS,    /* end of string */
  C_LCURB,  /* {  */
  C_RCURB,  /* } */
  C_LSQRB,  /* [ */
  C_RSQRB,  /* ] */
  C_COLON,  /* : */
  C_COMMA,  /* , */
  C_QUOTE,  /* " */
  C_DIGIT,  /* -0123456789 */
  C_LOW_F,  /* 'f' (for "false") */
  C_LOW_N,  /* 'n' (for "null") */
  C_LOW_T,  /* 't' (for "true") */
  C_ETC,    /* everything else */
  C_ERR,    /* character disallowed in JSON */
  C_BAD,    /* invalid character, charset handler cannot read it */
  NR_C_CLASSES, /* Counter for classes that handled with functions. */
  C_SPACE   /* space. Doesn't need specific handlers, so after the counter.*/
};


/*
  This array maps first 128 Unicode Code Points into classes.
  The remaining Unicode characters should be mapped to C_ETC.
*/

static enum json_char_classes json_chr_map[128] = {
  C_ERR,   C_ERR,   C_ERR,   C_ERR,   C_ERR,   C_ERR,   C_ERR,   C_ERR,
  C_ERR,   C_SPACE, C_SPACE, C_ERR,   C_ERR,   C_SPACE, C_ERR,   C_ERR,
  C_ERR,   C_ERR,   C_ERR,   C_ERR,   C_ERR,   C_ERR,   C_ERR,   C_ERR,
  C_ERR,   C_ERR,   C_ERR,   C_ERR,   C_ERR,   C_ERR,   C_ERR,   C_ERR,

  C_SPACE, C_ETC,   C_QUOTE, C_ETC,   C_ETC,   C_ETC,   C_ETC,   C_ETC,
  C_ETC,   C_ETC,   C_ETC,   C_ETC,   C_COMMA, C_DIGIT, C_ETC,   C_ETC,
  C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT, C_DIGIT,
  C_DIGIT, C_DIGIT, C_COLON, C_ETC,   C_ETC,   C_ETC,   C_ETC,   C_ETC,

  C_ETC,   C_ETC,   C_ETC,   C_ETC,   C_ETC,   C_ETC,   C_ETC,   C_ETC,
  C_ETC,   C_ETC,   C_ETC,   C_ETC,   C_ETC,   C_ETC,   C_ETC,   C_ETC,
  C_ETC,   C_ETC,   C_ETC,   C_ETC,   C_ETC,   C_ETC,   C_ETC,   C_ETC,
  C_ETC,   C_ETC,   C_ETC,   C_LSQRB, C_ETC,   C_RSQRB, C_ETC,   C_ETC,

  C_ETC,   C_ETC,   C_ETC,   C_ETC,   C_ETC,   C_ETC,   C_LOW_F, C_ETC,
  C_ETC,   C_ETC,   C_ETC,   C_ETC,   C_ETC,   C_ETC,   C_LOW_N, C_ETC,
  C_ETC,   C_ETC,   C_ETC,   C_ETC,   C_LOW_T, C_ETC,   C_ETC,   C_ETC,
  C_ETC,   C_ETC,   C_ETC,   C_LCURB, C_ETC,   C_RCURB, C_ETC,   C_ETC
};


/*
  JSON parser actually has more states than the 'enum json_states'
  declares. But the rest of the states aren't seen to the user so let's
  specify them here to avoid confusion.
*/

enum json_all_states {
  JST_DONE= NR_JSON_USER_STATES,         /* ok to finish     */
  JST_OBJ_CONT= NR_JSON_USER_STATES+1,   /* object continues */
  JST_ARRAY_CONT= NR_JSON_USER_STATES+2, /* array continues  */
  JST_READ_VALUE= NR_JSON_USER_STATES+3, /* value is being read */
  NR_JSON_STATES= NR_JSON_USER_STATES+4
};


typedef int (*json_state_handler)(json_engine_t *);


/* The string is broken. */
static int unexpected_eos(json_engine_t *j)
{
  j->s.error= JE_EOS;
  return 1;
}


/* This symbol here breaks the JSON syntax. */
static int syntax_error(json_engine_t *j)
{
  j->s.error= JE_SYN;
  return 1;
}


/* Value of object. */
static int mark_object(json_engine_t *j)
{
  j->state= JST_OBJ_START;
143
  if (++j->stack_p < JSON_DEPTH_LIMIT)
144
  {
145
    j->stack[j->stack_p]= JST_OBJ_CONT;
146 147 148 149
    return 0;
  }
  j->s.error= JE_DEPTH;
  return 1;
150 151 152 153 154 155 156 157 158
}


/* Read value of object. */
static int read_obj(json_engine_t *j)
{
  j->state= JST_OBJ_START;
  j->value_type= JSON_VALUE_OBJECT;
  j->value= j->value_begin;
159
  if (++j->stack_p < JSON_DEPTH_LIMIT)
160
  {
161
    j->stack[j->stack_p]= JST_OBJ_CONT;
162 163 164 165
    return 0;
  }
  j->s.error= JE_DEPTH;
  return 1;
166 167 168 169 170 171 172
}


/* Value of array. */
static int mark_array(json_engine_t *j)
{
  j->state= JST_ARRAY_START;
173
  if (++j->stack_p < JSON_DEPTH_LIMIT)
174
  {
175
    j->stack[j->stack_p]= JST_ARRAY_CONT;
176 177 178 179 180
    j->value= j->value_begin;
    return 0;
  }
  j->s.error= JE_DEPTH;
  return 1;
181 182 183 184 185 186 187 188
}

/* Read value of object. */
static int read_array(json_engine_t *j)
{
  j->state= JST_ARRAY_START;
  j->value_type= JSON_VALUE_ARRAY;
  j->value= j->value_begin;
189
  if (++j->stack_p < JSON_DEPTH_LIMIT)
190
  {
191
    j->stack[j->stack_p]= JST_ARRAY_CONT;
192 193 194 195
    return 0;
  }
  j->s.error= JE_DEPTH;
  return 1;
196 197 198 199 200 201 202
}



/*
  Character classes inside the JSON string constant.
  We mostly need this to parse escaping properly.
luz.paz's avatar
luz.paz committed
203
  Escapings available in JSON are:
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
  \" - quotation mark
  \\ - backslash
  \b - backspace UNICODE 8
  \f - formfeed UNICODE 12
  \n - newline UNICODE 10
  \r - carriage return UNICODE 13
  \t - horizontal tab UNICODE 9
  \u{four-hex-digits} - code in UCS16 character set
*/
enum json_string_char_classes {
  S_0= 0,
  S_1= 1,
  S_2= 2,
  S_3= 3,
  S_4= 4,
  S_5= 5,
  S_6= 6,
  S_7= 7,
  S_8= 8,
  S_9= 9,
  S_A= 10,
  S_B= 11,
  S_C= 12,
  S_D= 13,
  S_E= 14,
  S_F= 15,
  S_ETC= 36,    /* rest of characters. */
  S_QUOTE= 37,
  S_BKSL= 38, /* \ */
  S_ERR= 100,   /* disallowed */
};


/* This maps characters to their types inside a string constant. */
static enum json_string_char_classes json_instr_chr_map[128] = {
  S_ERR,   S_ERR,   S_ERR,   S_ERR,   S_ERR,   S_ERR,   S_ERR,   S_ERR,
  S_ERR,   S_ERR,   S_ERR,   S_ERR,   S_ERR,   S_ERR,   S_ERR,   S_ERR,
  S_ERR,   S_ERR,   S_ERR,   S_ERR,   S_ERR,   S_ERR,   S_ERR,   S_ERR,
  S_ERR,   S_ERR,   S_ERR,   S_ERR,   S_ERR,   S_ERR,   S_ERR,   S_ERR,

  S_ETC,   S_ETC,   S_QUOTE, S_ETC,   S_ETC,   S_ETC,   S_ETC,   S_ETC,
  S_ETC,   S_ETC,   S_ETC,   S_ETC,   S_ETC,   S_ETC,   S_ETC,   S_ETC,
  S_0,     S_1,     S_2,     S_3,     S_4,     S_5,     S_6,     S_7,
  S_8,     S_9,     S_ETC,   S_ETC,   S_ETC,   S_ETC,   S_ETC,   S_ETC,

  S_ETC,   S_A,     S_B,     S_C,     S_D,     S_E,     S_F,     S_ETC,
  S_ETC,   S_ETC,   S_ETC,   S_ETC,   S_ETC,   S_ETC,   S_ETC,   S_ETC,
  S_ETC,   S_ETC,   S_ETC,   S_ETC,   S_ETC,   S_ETC,   S_ETC,   S_ETC,
  S_ETC,   S_ETC,   S_ETC,   S_ETC,   S_BKSL,  S_ETC,   S_ETC,   S_ETC,

  S_ETC,   S_A,     S_B,     S_C,     S_D,     S_E,     S_F,     S_ETC,
  S_ETC,   S_ETC,   S_ETC,   S_ETC,   S_ETC,   S_ETC,   S_ETC,   S_ETC,
  S_ETC,   S_ETC,   S_ETC,   S_ETC,   S_ETC,   S_ETC,   S_ETC,   S_ETC,
  S_ETC,   S_ETC,   S_ETC,   S_ETC,   S_ETC,   S_ETC,   S_ETC,   S_ETC
};


static int read_4_hexdigits(json_string_t *s, uchar *dest)
{
  int i, t, c_len;
  for (i=0; i<4; i++)
  {
    if ((c_len= json_next_char(s)) <= 0)
      return s->error= json_eos(s) ? JE_EOS : JE_BAD_CHR;

269
    if (s->c_next >= 128 || (t= json_instr_chr_map[s->c_next]) > S_F)
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
      return s->error= JE_SYN;

    s->c_str+= c_len;
    dest[i/2]+= (i % 2) ? t : t*16;
  }
  return 0;
}


static int json_handle_esc(json_string_t *s)
{
  int t, c_len;
  
  if ((c_len= json_next_char(s)) <= 0)
    return s->error= json_eos(s) ? JE_EOS : JE_BAD_CHR;

  s->c_str+= c_len;
  switch (s->c_next)
  {
    case 'b':
      s->c_next= 8;
      return 0;
    case 'f':
      s->c_next= 12;
      return 0;
    case 'n':
      s->c_next= 10;
      return 0;
    case 'r':
      s->c_next= 13;
      return 0;
    case 't':
      s->c_next= 9;
      return 0;
  }

  if (s->c_next < 128 && (t= json_instr_chr_map[s->c_next]) == S_ERR)
  {
    s->c_str-= c_len;
    return s->error= JE_ESCAPING;
  }


  if (s->c_next != 'u')
    return 0;

  {
    /*
      Read the four-hex-digits code.
      If symbol is not in the Basic Multilingual Plane, we're reading
      the string for the next four digits to compose the UTF-16 surrogate pair.
    */
    uchar code[4]= {0,0,0,0};

    if (read_4_hexdigits(s, code))
      return 1;

    if ((c_len= my_utf16_uni(0, &s->c_next, code, code+2)) == 2)
      return 0;

    if (c_len != MY_CS_TOOSMALL4)
      return s->error= JE_BAD_CHR;

    if ((c_len= json_next_char(s)) <= 0)
      return s->error= json_eos(s) ? JE_EOS : JE_BAD_CHR;
    if (s->c_next != '\\')
      return s->error= JE_SYN;

338
    s->c_str+= c_len;
339 340 341 342
    if ((c_len= json_next_char(s)) <= 0)
      return s->error= json_eos(s) ? JE_EOS : JE_BAD_CHR;
    if (s->c_next != 'u')
      return s->error= JE_SYN;
343
    s->c_str+= c_len;
344 345 346 347

    if (read_4_hexdigits(s, code+2))
      return 1;

348
    if ((c_len= my_utf16_uni(0, &s->c_next, code, code+4)) == 4)
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
      return 0;
  }
  return s->error= JE_BAD_CHR;
}


int json_read_string_const_chr(json_string_t *js)
{
  int c_len;

  if ((c_len= json_next_char(js)) > 0)
  {
    js->c_str+= c_len;
    return (js->c_next == '\\') ? json_handle_esc(js) : 0;
  }
  js->error= json_eos(js) ? JE_EOS : JE_BAD_CHR; 
  return 1;
}


static int skip_str_constant(json_engine_t *j)
{
  int t, c_len;
  for (;;)
  {
    if ((c_len= json_next_char(&j->s)) > 0)
    {
      j->s.c_str+= c_len;
      if (j->s.c_next >= 128 || ((t=json_instr_chr_map[j->s.c_next]) <= S_ETC))
        continue;

      if (j->s.c_next == '"')
        break;
      if (j->s.c_next == '\\')
      {
384
        j->value_escaped= 1;
385 386 387 388 389 390 391 392 393 394 395
        if (json_handle_esc(&j->s))
          return 1;
        continue;
      }
      /* Symbol not allowed in JSON. */
      return j->s.error= JE_NOT_JSON_CHR;
    }
    else
      return j->s.error= json_eos(&j->s) ? JE_EOS : JE_BAD_CHR; 
  }

396
  j->state= j->stack[j->stack_p];
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
  return 0;
}


/* Scalar string. */
static int v_string(json_engine_t *j)
{
  return skip_str_constant(j) || json_scan_next(j);
}


/* Read scalar string. */
static int read_strn(json_engine_t *j)
{
  j->value= j->s.c_str;
412
  j->value_type= JSON_VALUE_STRING;
413
  j->value_escaped= 0;
414 415 416 417

  if (skip_str_constant(j))
    return 1;

418
  j->state= j->stack[j->stack_p];
419
  j->value_len= (int)(j->s.c_str - j->value) - 1;
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
  return 0;
}


/*
  We have dedicated parser for numeric constants. It's similar
  to the main JSON parser, we similarly define character classes,
  map characters to classes and implement the state-per-class
  table. Though we don't create functions that handle
  particular classes, just specify what new state should parser
  get in this case.
*/
enum json_num_char_classes {
  N_MINUS,
  N_PLUS,
  N_ZERO,
  N_DIGIT,
  N_POINT,
  N_E,
  N_END,
  N_EEND,
  N_ERR,
  N_NUM_CLASSES
};


static enum json_num_char_classes json_num_chr_map[128] = {
  N_ERR,   N_ERR,   N_ERR,   N_ERR,   N_ERR,   N_ERR,   N_ERR,   N_ERR,
  N_ERR,   N_END,   N_END,   N_ERR,   N_ERR,   N_END,   N_ERR,   N_ERR,
  N_ERR,   N_ERR,   N_ERR,   N_ERR,   N_ERR,   N_ERR,   N_ERR,   N_ERR,
  N_ERR,   N_ERR,   N_ERR,   N_ERR,   N_ERR,   N_ERR,   N_ERR,   N_ERR,

  N_END,   N_EEND,  N_EEND,  N_EEND,  N_EEND,  N_EEND,  N_EEND,  N_EEND,
  N_EEND,  N_EEND,  N_EEND,  N_PLUS,  N_END,   N_MINUS, N_POINT, N_EEND,
  N_ZERO,  N_DIGIT, N_DIGIT, N_DIGIT, N_DIGIT, N_DIGIT, N_DIGIT, N_DIGIT,
  N_DIGIT, N_DIGIT, N_EEND,  N_EEND,  N_EEND,  N_EEND,  N_EEND,  N_EEND,

  N_EEND,  N_EEND,  N_EEND,  N_EEND,  N_EEND,  N_E,     N_EEND,  N_EEND,
  N_EEND,  N_EEND,  N_EEND,  N_EEND,  N_EEND,  N_EEND,  N_EEND,  N_EEND,
  N_EEND,  N_EEND,  N_EEND,  N_EEND,  N_EEND,  N_EEND,  N_EEND,  N_EEND,
  N_EEND,  N_EEND,  N_EEND,  N_EEND,  N_EEND,  N_END,   N_EEND,  N_EEND,

  N_EEND,  N_EEND,  N_EEND,  N_EEND,  N_EEND,  N_E,     N_EEND,  N_EEND,
  N_EEND,  N_EEND,  N_EEND,  N_EEND,  N_EEND,  N_EEND,  N_EEND,  N_EEND,
  N_EEND,  N_EEND,  N_EEND,  N_EEND,  N_EEND,  N_EEND,  N_EEND,  N_EEND,
  N_EEND,  N_EEND,  N_EEND,  N_EEND,  N_EEND,   N_END,   N_EEND,  N_EEND,
};


enum json_num_states {
  NS_OK,  /* Number ended. */
  NS_GO,  /* Initial state. */
  NS_GO1, /* If the number starts with '-'. */
  NS_Z,   /* If the number starts with '0'. */
  NS_Z1,  /* If the numbers starts with '-0'. */
  NS_INT, /* Integer part. */
  NS_FRAC,/* Fractional part. */
  NS_EX,  /* Exponential part begins. */
  NS_EX1, /* Exponential part continues. */
  NS_NUM_STATES
};


static int json_num_states[NS_NUM_STATES][N_NUM_CLASSES]=
{
/*         -        +       0        1..9    POINT    E       END_OK   ERROR */
/*OK*/   { JE_SYN,  JE_SYN, JE_SYN,   JE_SYN, JE_SYN,  JE_SYN, JE_SYN, JE_BAD_CHR },
/*GO*/   { NS_GO1,  JE_SYN, NS_Z,     NS_INT, JE_SYN,  JE_SYN, JE_SYN, JE_BAD_CHR },
/*GO1*/  { JE_SYN,  JE_SYN, NS_Z1,    NS_INT, JE_SYN,  JE_SYN, JE_SYN, JE_BAD_CHR },
/*ZERO*/ { JE_SYN,  JE_SYN, JE_SYN,   JE_SYN, NS_FRAC, JE_SYN, NS_OK,  JE_BAD_CHR },
490
/*ZE1*/  { JE_SYN,  JE_SYN, JE_SYN,   JE_SYN, NS_FRAC, JE_SYN, NS_OK,  JE_BAD_CHR },
491 492
/*INT*/  { JE_SYN,  JE_SYN, NS_INT,   NS_INT, NS_FRAC, NS_EX,  NS_OK,  JE_BAD_CHR },
/*FRAC*/ { JE_SYN,  JE_SYN, NS_FRAC,  NS_FRAC,JE_SYN,  NS_EX,  NS_OK,  JE_BAD_CHR },
493 494
/*EX*/   { NS_EX,   NS_EX,  NS_EX1,   NS_EX1, JE_SYN,  JE_SYN, JE_SYN, JE_BAD_CHR }, 
/*EX1*/  { JE_SYN,  JE_SYN, NS_EX1,   NS_EX1, JE_SYN,  JE_SYN, NS_OK,  JE_BAD_CHR }
495 496 497
};


498 499 500 501 502 503 504 505 506 507 508 509 510 511
static uint json_num_state_flags[NS_NUM_STATES]=
{
/*OK*/   0,
/*GO*/   0,
/*GO1*/  JSON_NUM_NEG,
/*ZERO*/ 0,
/*ZE1*/  0,
/*INT*/  0,
/*FRAC*/ JSON_NUM_FRAC_PART,
/*EX*/   JSON_NUM_EXP,
/*EX1*/  0,
};


512 513 514 515 516
static int skip_num_constant(json_engine_t *j)
{
  int state= json_num_states[NS_GO][json_num_chr_map[j->s.c_next]];
  int c_len;

517
  j->num_flags= 0;
518 519
  for (;;)
  {
520
    j->num_flags|= json_num_state_flags[state];
521
    if ((c_len= json_next_char(&j->s)) > 0 && j->s.c_next < 128)
522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
    {
      if ((state= json_num_states[state][json_num_chr_map[j->s.c_next]]) > 0)
      {
        j->s.c_str+= c_len;
        continue;
      }
      break;
    }

    if ((j->s.error=
          json_eos(&j->s) ? json_num_states[state][N_END] : JE_BAD_CHR) < 0)
      return 1;
    else
      break;
  }

538
  j->state= j->stack[j->stack_p];
539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556
  return 0;
}


/* Scalar numeric. */
static int v_number(json_engine_t *j)
{
  return skip_num_constant(j) || json_scan_next(j);
}


/* Read numeric constant. */
static int read_num(json_engine_t *j)
{
  j->value= j->value_begin;
  if (skip_num_constant(j) == 0)
  {
    j->value_type= JSON_VALUE_NUMBER;
557
    j->value_len= (int)(j->s.c_str - j->value_begin);
558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576
    return 0;
  }
  return 1;
}


/* Check that the JSON string matches the argument and skip it. */
static int skip_string_verbatim(json_string_t *s, const char *str)
{
  int c_len;
  while (*str)
  {
    if ((c_len= json_next_char(s)) > 0)
    {
      if (s->c_next == (my_wc_t) *(str++))
      {
        s->c_str+= c_len;
        continue;
      }
577
      return s->error= JE_SYN;
578
    }
579
    return s->error= json_eos(s) ? JE_EOS : JE_BAD_CHR; 
580 581 582 583 584 585 586 587 588 589 590
  }

  return 0;
}


/* Scalar false. */
static int v_false(json_engine_t *j)
{
  if (skip_string_verbatim(&j->s, "alse"))
   return 1;
591
  j->state= j->stack[j->stack_p];
592 593 594 595 596 597 598 599 600
  return json_scan_next(j);
}


/* Scalar null. */
static int v_null(json_engine_t *j)
{
  if (skip_string_verbatim(&j->s, "ull"))
   return 1;
601
  j->state= j->stack[j->stack_p];
602 603 604 605 606 607 608 609 610
  return json_scan_next(j);
}


/* Scalar true. */
static int v_true(json_engine_t *j)
{
  if (skip_string_verbatim(&j->s, "rue"))
   return 1;
611
  j->state= j->stack[j->stack_p];
612 613 614 615 616 617 618 619 620
  return json_scan_next(j);
}


/* Read false. */
static int read_false(json_engine_t *j)
{
  j->value_type= JSON_VALUE_FALSE;
  j->value= j->value_begin;
621
  j->state= j->stack[j->stack_p];
622 623 624 625 626 627 628 629 630 631
  j->value_len= 5;
  return skip_string_verbatim(&j->s, "alse");
}


/* Read null. */
static int read_null(json_engine_t *j)
{
  j->value_type= JSON_VALUE_NULL;
  j->value= j->value_begin;
632
  j->state= j->stack[j->stack_p];
633 634 635 636 637 638 639 640 641 642
  j->value_len= 4;
  return skip_string_verbatim(&j->s, "ull");
}


/* Read true. */
static int read_true(json_engine_t *j)
{
  j->value_type= JSON_VALUE_TRUE;
  j->value= j->value_begin;
643
  j->state= j->stack[j->stack_p];
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
  j->value_len= 4;
  return skip_string_verbatim(&j->s, "rue");
}


/* Disallowed character. */
static int not_json_chr(json_engine_t *j)
{
  j->s.error= JE_NOT_JSON_CHR;
  return 1;
}


/* Bad character. */
static int bad_chr(json_engine_t *j)
{
  j->s.error= JE_BAD_CHR;
  return 1;
}


/* Correct finish. */
static int done(json_engine_t *j  __attribute__((unused)))
{
  return 1;
}


/* End of the object. */
static int end_object(json_engine_t *j)
{
  j->stack_p--;
  j->state= JST_OBJ_END;
  return 0;
}


/* End of the array. */
static int end_array(json_engine_t *j)
{
  j->stack_p--;
  j->state= JST_ARRAY_END;
  return 0;
}


/* Start reading key name. */
static int read_keyname(json_engine_t *j)
{
  j->state= JST_KEY;
  return 0;
}


static void get_first_nonspace(json_string_t *js, int *t_next, int *c_len)
{
  do
  {
    if ((*c_len= json_next_char(js)) <= 0)
      *t_next= json_eos(js) ? C_EOS : C_BAD;
    else
    {
      *t_next= (js->c_next < 128) ? json_chr_map[js->c_next] : C_ETC;
      js->c_str+= *c_len;
    }
  } while (*t_next == C_SPACE);
}


/* Next key name. */
static int next_key(json_engine_t *j)
{
  int t_next, c_len;
  get_first_nonspace(&j->s, &t_next, &c_len);

  if (t_next == C_QUOTE)
  {
    j->state= JST_KEY;
    return 0;
  }

  j->s.error= (t_next == C_EOS)  ? JE_EOS :
              ((t_next == C_BAD) ? JE_BAD_CHR :
                                   JE_SYN);
  return 1;
}


/* Forward declarations. */
static int skip_colon(json_engine_t *j);
static int skip_key(json_engine_t *j);
static int struct_end_cb(json_engine_t *j);
static int struct_end_qb(json_engine_t *j);
static int struct_end_cm(json_engine_t *j);
static int struct_end_eos(json_engine_t *j);


static int next_item(json_engine_t *j)
{
  j->state= JST_VALUE;
  return 0;
}


static int array_item(json_engine_t *j)
{
  j->state= JST_VALUE;
  j->s.c_str-= j->sav_c_len;
  return 0;
}


static json_state_handler json_actions[NR_JSON_STATES][NR_C_CLASSES]=
/*
   EOS              {            }             [             ]
   :                ,            "             -0..9         f
   n                t              ETC          ERR           BAD
*/
{
  {/*VALUE*/
    unexpected_eos, mark_object, syntax_error, mark_array,   syntax_error,
    syntax_error,   syntax_error,v_string,     v_number,     v_false,
    v_null,         v_true,       syntax_error, not_json_chr, bad_chr},
  {/*KEY*/
    unexpected_eos, skip_key,    skip_key,     skip_key,     skip_key,
    skip_key,       skip_key,    skip_colon,   skip_key,     skip_key,
    skip_key,       skip_key,     skip_key,     not_json_chr, bad_chr},
  {/*OBJ_START*/
    unexpected_eos, syntax_error, end_object,  syntax_error, syntax_error,
    syntax_error,   syntax_error, read_keyname, syntax_error, syntax_error,
    syntax_error,   syntax_error,   syntax_error,    not_json_chr, bad_chr},
  {/*OBJ_END*/
    struct_end_eos, syntax_error, struct_end_cb, syntax_error, struct_end_qb,
    syntax_error,   struct_end_cm,syntax_error,  syntax_error, syntax_error,
    syntax_error,   syntax_error,  syntax_error,    not_json_chr, bad_chr},
  {/*ARRAY_START*/
    unexpected_eos, array_item,   syntax_error, array_item,   end_array,
    syntax_error,   syntax_error, array_item,  array_item,  array_item,
    array_item,    array_item,    syntax_error,    not_json_chr, bad_chr},
  {/*ARRAY_END*/
    struct_end_eos, syntax_error, struct_end_cb, syntax_error,  struct_end_qb,
    syntax_error,   struct_end_cm, syntax_error, syntax_error,  syntax_error,
    syntax_error,   syntax_error,  syntax_error,    not_json_chr, bad_chr},
  {/*DONE*/
    done,           syntax_error, syntax_error, syntax_error, syntax_error,
    syntax_error,   syntax_error, syntax_error, syntax_error, syntax_error,
    syntax_error,   syntax_error, syntax_error, not_json_chr, bad_chr},
  {/*OBJ_CONT*/
792
    unexpected_eos, syntax_error, end_object,    syntax_error,   syntax_error,
793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809
    syntax_error,   next_key,     syntax_error,  syntax_error,   syntax_error,
    syntax_error,    syntax_error,    syntax_error,    not_json_chr, bad_chr},
  {/*ARRAY_CONT*/
    unexpected_eos, syntax_error, syntax_error,  syntax_error, end_array,
    syntax_error,   next_item,    syntax_error,  syntax_error, syntax_error,
    syntax_error,    syntax_error,    syntax_error,    not_json_chr, bad_chr},
  {/*READ_VALUE*/
    unexpected_eos, read_obj,     syntax_error,  read_array,    syntax_error,
    syntax_error,   syntax_error, read_strn,     read_num,      read_false,
    read_null,      read_true,    syntax_error,    not_json_chr, bad_chr},
};



int json_scan_start(json_engine_t *je,
                    CHARSET_INFO *i_cs, const uchar *str, const uchar *end)
{
810 811
  static const uchar no_time_to_die= 0;

812 813
  json_string_setup(&je->s, i_cs, str, end);
  je->stack[0]= JST_DONE;
814
  je->stack_p= 0;
815
  je->state= JST_VALUE;
816
  je->killed_ptr = (uchar*)&no_time_to_die;
817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845
  return 0;
}


/* Skip colon and the value. */
static int skip_colon(json_engine_t *j)
{
  int t_next, c_len;

  get_first_nonspace(&j->s, &t_next, &c_len);

  if (t_next == C_COLON)
  {
    get_first_nonspace(&j->s, &t_next, &c_len);
    return json_actions[JST_VALUE][t_next](j);
 }

  j->s.error= (t_next == C_EOS)  ? JE_EOS :
              ((t_next == C_BAD) ? JE_BAD_CHR:
                                   JE_SYN);

  return 1;
}


/* Skip colon and the value. */
static int skip_key(json_engine_t *j)
{
  int t_next, c_len;
846

847
  if (j->s.c_next< 128 && json_instr_chr_map[j->s.c_next] == S_BKSL &&
848 849 850
      json_handle_esc(&j->s))
    return 1;

851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867
  while (json_read_keyname_chr(j) == 0) {}

  if (j->s.error)
    return 1;

  get_first_nonspace(&j->s, &t_next, &c_len);
  return json_actions[JST_VALUE][t_next](j);
}


/*
  Handle EOS after the end of an object or array.
  To do that we should pop the stack to see if
  we are inside an object, or an array, and
  run our 'state machine' accordingly.
*/
static int struct_end_eos(json_engine_t *j)
868
{ return json_actions[j->stack[j->stack_p]][C_EOS](j); }
869 870 871 872 873 874 875 876 877


/*
  Handle '}' after the end of an object or array.
  To do that we should pop the stack to see if
  we are inside an object, or an array, and
  run our 'state machine' accordingly.
*/
static int struct_end_cb(json_engine_t *j)
878
{ return json_actions[j->stack[j->stack_p]][C_RCURB](j); }
879 880 881 882 883 884 885 886 887


/*
  Handle ']' after the end of an object or array.
  To do that we should pop the stack to see if
  we are inside an object, or an array, and
  run our 'state machine' accordingly.
*/
static int struct_end_qb(json_engine_t *j)
888
{ return json_actions[j->stack[j->stack_p]][C_RSQRB](j); }
889 890 891 892 893 894 895 896 897


/*
  Handle ',' after the end of an object or array.
  To do that we should pop the stack to see if
  we are inside an object, or an array, and
  run our 'state machine' accordingly.
*/
static int struct_end_cm(json_engine_t *j)
898
{ return json_actions[j->stack[j->stack_p]][C_COMMA](j); }
899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915


int json_read_keyname_chr(json_engine_t *j)
{
  int c_len, t;

  if ((c_len= json_next_char(&j->s)) > 0)
  {
    j->s.c_str+= c_len;
    if (j->s.c_next>= 128 || (t= json_instr_chr_map[j->s.c_next]) <= S_ETC)
      return 0;

    switch (t)
    {
    case S_QUOTE:
      for (;;)  /* Skip spaces until ':'. */
      {
916
        if ((c_len= json_next_char(&j->s)) > 0)
917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953
        {
          if (j->s.c_next == ':')
          {
            j->s.c_str+= c_len;
            j->state= JST_VALUE;
            return 1;
          }

          if (j->s.c_next < 128 && json_chr_map[j->s.c_next] == C_SPACE)
          {
            j->s.c_str+= c_len;
            continue;
          }
          j->s.error= JE_SYN;
          break;
        }
        j->s.error= json_eos(&j->s) ? JE_EOS : JE_BAD_CHR;
        break;
      }
      return 1;
    case S_BKSL:
      return json_handle_esc(&j->s);
    case S_ERR:
      j->s.c_str-= c_len;
      j->s.error= JE_STRING_CONST;
      return 1;
    }
  }
  j->s.error= json_eos(&j->s) ? JE_EOS : JE_BAD_CHR; 
  return 1;
}


int json_read_value(json_engine_t *j)
{
  int t_next, c_len, res;

954
  j->value_type= JSON_VALUE_UNINITIALIZED;
955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976
  if (j->state == JST_KEY)
  {
    while (json_read_keyname_chr(j) == 0) {}

    if (j->s.error)
      return 1;
  }

  get_first_nonspace(&j->s, &t_next, &c_len);

  j->value_begin= j->s.c_str-c_len;
  res= json_actions[JST_READ_VALUE][t_next](j);
  j->value_end= j->s.c_str;
  return res;
}


int json_scan_next(json_engine_t *j)
{
  int t_next;

  get_first_nonspace(&j->s, &t_next, &j->sav_c_len);
977
  return *j->killed_ptr || json_actions[j->state][t_next](j);
978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993
}


enum json_path_chr_classes {
  P_EOS,    /* end of string */
  P_USD,    /* $ */
  P_ASTER,  /* * */
  P_LSQRB,  /* [ */
  P_RSQRB,  /* ] */
  P_POINT,  /* . */
  P_ZERO,   /* 0 */
  P_DIGIT,  /* 123456789 */
  P_L,      /* l (for "lax") */
  P_S,      /* s (for "strict") */
  P_SPACE,  /* space */
  P_BKSL,   /* \ */
994
  P_QUOTE,  /* " */
995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
  P_ETC,    /* everything else */
  P_ERR,    /* character disallowed in JSON*/
  P_BAD,    /* invalid character */
  N_PATH_CLASSES,
};


static enum json_path_chr_classes json_path_chr_map[128] = {
  P_ERR,   P_ERR,   P_ERR,   P_ERR,   P_ERR,   P_ERR,   P_ERR,   P_ERR,
  P_ERR,   P_SPACE, P_SPACE, P_ERR,   P_ERR,   P_SPACE, P_ERR,   P_ERR,
  P_ERR,   P_ERR,   P_ERR,   P_ERR,   P_ERR,   P_ERR,   P_ERR,   P_ERR,
  P_ERR,   P_ERR,   P_ERR,   P_ERR,   P_ERR,   P_ERR,   P_ERR,   P_ERR,

1008
  P_SPACE, P_ETC,   P_QUOTE, P_ETC,   P_USD,   P_ETC,   P_ETC,   P_ETC,
1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029
  P_ETC,   P_ETC,   P_ASTER, P_ETC,   P_ETC,   P_ETC,   P_POINT, P_ETC,
  P_ZERO,  P_DIGIT, P_DIGIT, P_DIGIT, P_DIGIT, P_DIGIT, P_DIGIT, P_DIGIT,
  P_DIGIT, P_DIGIT, P_ETC,   P_ETC,   P_ETC,   P_ETC,   P_ETC,   P_ETC,

  P_ETC,   P_ETC,   P_ETC,   P_ETC,   P_ETC,   P_ETC,   P_ETC,   P_ETC,
  P_ETC,   P_ETC,   P_ETC,   P_ETC,   P_L,     P_ETC,   P_ETC,   P_ETC,
  P_ETC,   P_ETC,   P_S,     P_ETC,   P_ETC,   P_ETC,   P_ETC,   P_ETC,
  P_ETC,   P_ETC,   P_ETC,   P_LSQRB, P_BKSL, P_RSQRB, P_ETC,   P_ETC,

  P_ETC,   P_ETC,   P_ETC,   P_ETC,   P_ETC,   P_ETC,   P_ETC,   P_ETC,
  P_ETC,   P_ETC,   P_ETC,   P_ETC,   P_L,     P_ETC,   P_ETC,   P_ETC,
  P_ETC,   P_ETC,   P_S,     P_ETC,   P_ETC,   P_ETC,   P_ETC,   P_ETC,
  P_ETC,   P_ETC,   P_ETC,   P_ETC,   P_ETC,   P_ETC,   P_ETC,   P_ETC
};


enum json_path_states {
  PS_GO,  /* Initial state. */
  PS_LAX, /* Parse the 'lax' keyword. */
  PS_PT,  /* New path's step begins. */
  PS_AR,  /* Parse array step. */
1030
  PS_SAR, /* space after the '['. */
1031 1032 1033 1034 1035 1036 1037
  PS_AWD, /* Array wildcard. */
  PS_Z,   /* '0' (as an array item number). */
  PS_INT, /* Parse integer (as an array item number). */
  PS_AS,  /* Space. */
  PS_KEY, /* Key. */
  PS_KNM, /* Parse key name. */
  PS_KWD, /* Key wildcard. */
1038 1039
  PS_AST, /* Asterisk. */
  PS_DWD, /* Double wildcard. */
1040 1041
  PS_KEYX, /* Key started with quote ("). */
  PS_KNMX, /* Parse quoted key name. */
1042 1043 1044
  N_PATH_STATES, /* Below are states that aren't in the transitions table. */
  PS_SCT,  /* Parse the 'strict' keyword. */
  PS_EKY,  /* '.' after the keyname so next step is the key. */
1045
  PS_EKYX, /* Closing " for the quoted keyname. */
1046 1047
  PS_EAR,  /* '[' after the keyname so next step is the array. */
  PS_ESC,  /* Escaping in the keyname. */
1048
  PS_ESCX, /* Escaping in the quoted keyname. */
1049 1050 1051 1052 1053 1054 1055 1056 1057
  PS_OK,   /* Path normally ended. */
  PS_KOK   /* EOS after the keyname so end the path normally. */
};


static int json_path_transitions[N_PATH_STATES][N_PATH_CLASSES]=
{
/*
            EOS       $,      *       [       ]       .       0
1058 1059
            1..9    L       S       SPACE   \       "       ETC
            ERR              BAD
1060 1061
*/
/* GO  */ { JE_EOS, PS_PT,  JE_SYN, JE_SYN, JE_SYN, JE_SYN, JE_SYN,
1062 1063
            JE_SYN, PS_LAX, PS_SCT, PS_GO,  JE_SYN, JE_SYN, JE_SYN,
            JE_NOT_JSON_CHR, JE_BAD_CHR},
1064
/* LAX */ { JE_EOS, JE_SYN, JE_SYN, JE_SYN, JE_SYN, JE_SYN, JE_SYN,
1065 1066
            JE_SYN, PS_LAX, JE_SYN, PS_GO,  JE_SYN, JE_SYN, JE_SYN,
            JE_NOT_JSON_CHR, JE_BAD_CHR},
1067
/* PT */  { PS_OK,  JE_SYN, PS_AST, PS_AR,  JE_SYN, PS_KEY, JE_SYN, JE_SYN,
1068 1069
            JE_SYN, JE_SYN, JE_SYN, JE_SYN, JE_SYN, JE_SYN,
            JE_NOT_JSON_CHR, JE_BAD_CHR},
1070
/* AR */  { JE_EOS, JE_SYN, PS_AWD, JE_SYN, JE_SYN, JE_SYN, PS_Z,
1071 1072 1073 1074
            PS_INT, JE_SYN, JE_SYN, PS_SAR, JE_SYN, JE_SYN, JE_SYN,
            JE_NOT_JSON_CHR, JE_BAD_CHR},
/* SAR */ { JE_EOS, JE_SYN, PS_AWD, JE_SYN, PS_PT,  JE_SYN, PS_Z,
            PS_INT, JE_SYN, JE_SYN, PS_SAR, JE_SYN, JE_SYN, JE_SYN,
1075
            JE_NOT_JSON_CHR, JE_BAD_CHR},
1076
/* AWD */ { JE_EOS, JE_SYN, JE_SYN, JE_SYN, PS_PT,  JE_SYN, JE_SYN,
1077 1078
            JE_SYN, JE_SYN, JE_SYN, PS_AS,  JE_SYN, JE_SYN, JE_SYN,
            JE_NOT_JSON_CHR, JE_BAD_CHR},
1079
/* Z */   { JE_EOS, JE_SYN, JE_SYN, JE_SYN, PS_PT,  JE_SYN, JE_SYN,
1080 1081
            JE_SYN, JE_SYN, JE_SYN, PS_AS,  JE_SYN, JE_SYN, JE_SYN,
            JE_NOT_JSON_CHR, JE_BAD_CHR},
1082
/* INT */ { JE_EOS, JE_SYN, JE_SYN, JE_SYN, PS_PT,  JE_SYN, PS_INT,
1083 1084
            PS_INT, JE_SYN, JE_SYN, PS_AS,  JE_SYN, JE_SYN, JE_SYN,
            JE_NOT_JSON_CHR, JE_BAD_CHR},
1085
/* AS */  { JE_EOS, JE_SYN, JE_SYN, JE_SYN, PS_PT,  JE_SYN, JE_SYN, JE_SYN,
1086 1087
            JE_SYN, JE_SYN, PS_AS,  JE_SYN, JE_SYN, JE_SYN,
            JE_NOT_JSON_CHR, JE_BAD_CHR},
1088
/* KEY */ { JE_EOS, PS_KNM, PS_KWD, JE_SYN, PS_KNM, JE_SYN, PS_KNM,
1089 1090
            PS_KNM, PS_KNM, PS_KNM, PS_KNM, JE_SYN, PS_KEYX, PS_KNM,
            JE_NOT_JSON_CHR, JE_BAD_CHR},
1091
/* KNM */ { PS_KOK, PS_KNM, PS_AST, PS_EAR, PS_KNM, PS_EKY, PS_KNM,
1092 1093
            PS_KNM, PS_KNM, PS_KNM, PS_KNM, PS_ESC, PS_KNM, PS_KNM,
            JE_NOT_JSON_CHR, JE_BAD_CHR},
1094
/* KWD */ { PS_OK,  JE_SYN, JE_SYN, PS_AR,  JE_SYN, PS_EKY, JE_SYN,
1095 1096
            JE_SYN, JE_SYN, JE_SYN, JE_SYN, JE_SYN, JE_SYN, JE_SYN,
            JE_NOT_JSON_CHR, JE_BAD_CHR},
1097
/* AST */ { JE_SYN, JE_SYN, PS_DWD, JE_SYN, JE_SYN, JE_SYN, JE_SYN,
1098 1099
            JE_SYN, JE_SYN, JE_SYN, JE_SYN, JE_SYN, JE_SYN, JE_SYN,
            JE_NOT_JSON_CHR, JE_BAD_CHR},
1100
/* DWD */ { JE_SYN, JE_SYN, PS_AST, PS_AR,  JE_SYN, PS_KEY, JE_SYN, JE_SYN,
1101 1102 1103 1104 1105 1106 1107 1108
            JE_SYN, JE_SYN, JE_SYN, JE_SYN, JE_SYN, JE_SYN,
            JE_NOT_JSON_CHR, JE_BAD_CHR},
/* KEYX*/ { JE_EOS, PS_KNMX, PS_KNMX, PS_KNMX, PS_KNMX, PS_KNMX, PS_KNMX,
            PS_KNMX,PS_KNMX, PS_KNMX, PS_KNMX, PS_ESCX, PS_EKYX, PS_KNMX,
            JE_NOT_JSON_CHR, JE_BAD_CHR},
/* KNMX */{ JE_EOS, PS_KNMX, PS_KNMX, PS_KNMX, PS_KNMX, PS_KNMX, PS_KNMX,
            PS_KNMX, PS_KNMX, PS_KNMX, PS_KNMX,PS_ESCX, PS_EKYX, PS_KNMX,
            JE_NOT_JSON_CHR, JE_BAD_CHR},
1109 1110 1111 1112 1113 1114 1115
};


int json_path_setup(json_path_t *p,
                    CHARSET_INFO *i_cs, const uchar *str, const uchar *end)
{
  int c_len, t_next, state= PS_GO;
1116
  enum json_path_step_types double_wildcard= JSON_PATH_KEY_NULL;
1117 1118 1119

  json_string_setup(&p->s, i_cs, str, end);

1120
  p->steps[0].type= JSON_PATH_ARRAY_WILD;
1121 1122
  p->last_step= p->steps;
  p->mode_strict= FALSE;
1123
  p->types_used= JSON_PATH_KEY_NULL;
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149

  do
  {
    if ((c_len= json_next_char(&p->s)) <= 0)
      t_next= json_eos(&p->s) ? P_EOS : P_BAD;
    else
      t_next= (p->s.c_next >= 128) ? P_ETC : json_path_chr_map[p->s.c_next];

    if ((state= json_path_transitions[state][t_next]) < 0)
      return p->s.error= state;

    p->s.c_str+= c_len;

    switch (state)
    {
    case PS_LAX:
      if ((p->s.error= skip_string_verbatim(&p->s, "ax")))
        return 1;
      p->mode_strict= FALSE;
      continue;
    case PS_SCT:
      if ((p->s.error= skip_string_verbatim(&p->s, "rict")))
        return 1;
      p->mode_strict= TRUE;
      state= PS_LAX;
      continue;
1150
    case PS_KWD:
1151
    case PS_AWD:
1152
      p->last_step->type|= JSON_PATH_WILD;
1153
      p->types_used|= JSON_PATH_WILD;
1154 1155 1156 1157 1158
      continue;
    case PS_INT:
      p->last_step->n_item*= 10;
      p->last_step->n_item+= p->s.c_next - '0';
      continue;
1159 1160 1161 1162
    case PS_EKYX:
      p->last_step->key_end= p->s.c_str - c_len;
      state= PS_PT;
      continue;
1163 1164 1165
    case PS_EKY:
      p->last_step->key_end= p->s.c_str - c_len;
      state= PS_KEY;
1166
      /* fall through */
1167 1168
    case PS_KEY:
      p->last_step++;
1169 1170
      if (p->last_step - p->steps >= JSON_DEPTH_LIMIT)
        return p->s.error= JE_DEPTH;
1171
      p->types_used|= p->last_step->type= JSON_PATH_KEY | double_wildcard;
1172
      double_wildcard= JSON_PATH_KEY_NULL;
1173
      /* fall through */
1174
    case PS_KEYX:
1175 1176 1177 1178 1179
      p->last_step->key= p->s.c_str;
      continue;
    case PS_EAR:
      p->last_step->key_end= p->s.c_str - c_len;
      state= PS_AR;
1180
      /* fall through */
1181 1182
    case PS_AR:
      p->last_step++;
1183 1184
      if (p->last_step - p->steps >= JSON_DEPTH_LIMIT)
        return p->s.error= JE_DEPTH;
1185
      p->types_used|= p->last_step->type= JSON_PATH_ARRAY | double_wildcard;
1186
      double_wildcard= JSON_PATH_KEY_NULL;
1187 1188 1189 1190 1191
      p->last_step->n_item= 0;
      continue;
    case PS_ESC:
      if (json_handle_esc(&p->s))
        return 1;
1192 1193 1194 1195 1196 1197
      state= PS_KNM;
      continue;
    case PS_ESCX:
      if (json_handle_esc(&p->s))
        return 1;
      state= PS_KNMX;
1198 1199 1200 1201
      continue;
    case PS_KOK:
      p->last_step->key_end= p->s.c_str - c_len;
      state= PS_OK;
1202 1203 1204 1205
      break; /* 'break' as the loop supposed to end after that. */
    case PS_DWD:
      double_wildcard= JSON_PATH_DOUBLE_WILD;
      continue;
1206 1207 1208
    };
  } while (state != PS_OK);

1209
  return double_wildcard ? (p->s.error= JE_SYN) : 0;
1210 1211 1212
}


1213
int json_skip_to_level(json_engine_t *j, int level)
1214
{
1215 1216 1217 1218
  do {
    if (j->stack_p < level)
      return 0;
  } while (json_scan_next(j) == 0);
1219 1220 1221 1222 1223

  return 1;
}


1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244
/*
  works as json_skip_level() but also counts items on the current
  level skipped.
*/
int json_skip_level_and_count(json_engine_t *j, int *n_items_skipped)
{
  int level= j->stack_p;

  *n_items_skipped= 0;
  while (json_scan_next(j) == 0)
  {
    if (j->stack_p < level)
      return 0;
    if (j->stack_p == level && j->state == JST_VALUE)
      (*n_items_skipped)++;
  }

  return 1;
}


1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256
int json_skip_key(json_engine_t *j)
{
  if (json_read_value(j))
    return 1;

  if (json_value_scalar(j))
    return 0;

  return json_skip_level(j);
}


1257 1258
#define SKIPPED_STEP_MARK ((uint) ~0)

1259 1260 1261 1262 1263 1264 1265 1266
/*
  Current step of the patch matches the JSON construction.
  Now we should either stop the search or go to the next
  step of the path.
*/
static int handle_match(json_engine_t *je, json_path_t *p,
                        json_path_step_t **p_cur_step, uint *array_counters)
{
1267 1268
  json_path_step_t *next_step= *p_cur_step + 1;

1269 1270 1271 1272 1273 1274
  DBUG_ASSERT(*p_cur_step < p->last_step);

  if (json_read_value(je))
    return 1;

  if (json_value_scalar(je))
1275 1276 1277 1278 1279 1280 1281 1282 1283
  {
    while (next_step->type == JSON_PATH_ARRAY && next_step->n_item == 0)
    {
      if (++next_step > p->last_step)
      {
        je->s.c_str= je->value_begin;
        return 1;
      }
    }
1284
    return 0;
1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295
  }

  if (next_step->type == JSON_PATH_ARRAY && next_step->n_item == 0 &&
      je->value_type & JSON_VALUE_OBJECT)
  {
    do
    {
      array_counters[next_step - p->steps]= SKIPPED_STEP_MARK;
      if (++next_step > p->last_step)
      {
        je->s.c_str= je->value_begin;
1296
        je->stack_p--;
1297 1298 1299 1300
        return 1;
      }
    } while (next_step->type == JSON_PATH_ARRAY && next_step->n_item == 0);
  }
1301

1302 1303

  array_counters[next_step - p->steps]= 0;
1304

1305
  if ((int) je->value_type !=
1306
      (int) (next_step->type & JSON_PATH_KEY_OR_ARRAY))
1307 1308
    return json_skip_level(je);

1309
  *p_cur_step= next_step;
1310 1311 1312 1313 1314 1315 1316 1317
  return 0;
}


/*
  Check if the name of the current JSON key matches
  the step of the path.
*/
1318
int json_key_matches(json_engine_t *je, json_string_t *k)
1319 1320 1321 1322 1323 1324 1325 1326
{
  while (json_read_keyname_chr(je) == 0)
  {
    if (json_read_string_const_chr(k) ||
        je->s.c_next != k->c_next)
      return 0;
  }

1327
  return json_read_string_const_chr(k);
1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344
}


int json_find_path(json_engine_t *je,
                   json_path_t *p, json_path_step_t **p_cur_step,
                   uint *array_counters)
{
  json_string_t key_name;

  json_string_set_cs(&key_name, p->s.cs);

  do
  {
    json_path_step_t *cur_step= *p_cur_step;
    switch (je->state)
    {
    case JST_KEY:
1345 1346
      DBUG_ASSERT(cur_step->type & JSON_PATH_KEY);
      if (!(cur_step->type & JSON_PATH_WILD))
1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360
      {
        json_string_set_str(&key_name, cur_step->key, cur_step->key_end);
        if (!json_key_matches(je, &key_name))
        {
          if (json_skip_key(je))
            goto exit;
          continue;
        }
      }
      if (cur_step == p->last_step ||
          handle_match(je, p, p_cur_step, array_counters))
        goto exit;
      break;
    case JST_VALUE:
1361 1362
      DBUG_ASSERT(cur_step->type & JSON_PATH_ARRAY);
      if (cur_step->type & JSON_PATH_WILD ||
1363
          cur_step->n_item == array_counters[cur_step - p->steps]++)
1364 1365 1366 1367 1368 1369 1370 1371 1372 1373
      {
        /* Array item matches. */
        if (cur_step == p->last_step ||
            handle_match(je, p, p_cur_step, array_counters))
          goto exit;
      }
      else
        json_skip_array_item(je);
      break;
    case JST_OBJ_END:
1374 1375 1376
      do
      {
        (*p_cur_step)--;
1377 1378
      } while (*p_cur_step > p->steps &&
               array_counters[*p_cur_step - p->steps] == SKIPPED_STEP_MARK);
1379
      break;
1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423
    case JST_ARRAY_END:
      (*p_cur_step)--;
      break;
    default:
      DBUG_ASSERT(0);
      break;
    };
  } while (json_scan_next(je) == 0);

  /* No luck. */
  return 1;

exit:
  return je->s.error;
}


int json_find_paths_first(json_engine_t *je, json_find_paths_t *state,
                          uint n_paths, json_path_t *paths, uint *path_depths)
{
  state->n_paths= n_paths;
  state->paths= paths;
  state->cur_depth= 0;
  state->path_depths= path_depths;
  return json_find_paths_next(je, state);
}


int json_find_paths_next(json_engine_t *je, json_find_paths_t *state)
{
  uint p_c;
  int path_found, no_match_found;
  do
  {
    switch (je->state)
    {
    case JST_KEY:
      path_found= FALSE;
      no_match_found= TRUE;
      for (p_c=0; p_c < state->n_paths; p_c++)
      {
        json_path_step_t *cur_step;
        if (state->path_depths[p_c] <
              state->cur_depth /* Path already failed. */ ||
1424 1425
            !((cur_step= state->paths[p_c].steps + state->cur_depth)->type &
              JSON_PATH_KEY))
1426 1427
          continue;

1428
        if (!(cur_step->type & JSON_PATH_WILD))
1429 1430 1431 1432 1433 1434 1435
        {
          json_string_t key_name;
          json_string_setup(&key_name, state->paths[p_c].s.cs,
                            cur_step->key, cur_step->key_end);
          if (!json_key_matches(je, &key_name))
            continue;
        }
1436
        if (cur_step == state->paths[p_c].last_step + state->cur_depth)
1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461
          path_found= TRUE;
        else
        {
          no_match_found= FALSE;
          state->path_depths[p_c]= state->cur_depth + 1;
        }
      }
      if (path_found)
        /* Return the result. */
        goto exit;
      if (no_match_found)
      {
        /* No possible paths left to check. Just skip the level. */
        if (json_skip_level(je))
          goto exit;
      }

      break;
    case JST_VALUE:
      path_found= FALSE;
      no_match_found= TRUE;
      for (p_c=0; p_c < state->n_paths; p_c++)
      {
        json_path_step_t *cur_step;
        if (state->path_depths[p_c]< state->cur_depth /* Path already failed. */ ||
1462 1463
            !((cur_step= state->paths[p_c].steps + state->cur_depth)->type &
              JSON_PATH_ARRAY))
1464
          continue;
1465
        if (cur_step->type & JSON_PATH_WILD ||
1466 1467 1468
            cur_step->n_item == state->array_counters[state->cur_depth])
        {
          /* Array item matches. */
1469
          if (cur_step == state->paths[p_c].last_step + state->cur_depth)
1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493
            path_found= TRUE;
          else
          {
            no_match_found= FALSE;
            state->path_depths[p_c]= state->cur_depth + 1;
          }
        }
      }

      if (path_found)
        goto exit;

      if (no_match_found)
        json_skip_array_item(je);

      state->array_counters[state->cur_depth]++;
      break;
    case JST_OBJ_START:
    case JST_ARRAY_START:
      for (p_c=0; p_c < state->n_paths; p_c++)
      {
        if (state->path_depths[p_c] < state->cur_depth)
          /* Path already failed. */
          continue;
1494
        if (state->paths[p_c].steps[state->cur_depth].type &
Alexey Botchkov's avatar
Alexey Botchkov committed
1495
            ((je->state == JST_OBJ_START) ? JSON_PATH_KEY : JSON_PATH_ARRAY))
1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531
          state->path_depths[p_c]++;
      }
      state->cur_depth++;
      break;
    case JST_OBJ_END:
    case JST_ARRAY_END:
      for (p_c=0; p_c < state->n_paths; p_c++)
      {
        if (state->path_depths[p_c] < state->cur_depth)
          continue;
        state->path_depths[p_c]--;
      }
      state->cur_depth--;
      break;
    default:
      DBUG_ASSERT(0);
      break;
    };
  } while (json_scan_next(je) == 0);

  /* No luck. */
  return 1;

exit:
  return je->s.error;
}


int json_append_ascii(CHARSET_INFO *json_cs,
                      uchar *json, uchar *json_end,
                      const uchar *ascii, const uchar *ascii_end)
{
  const uchar *json_start= json;
  while (ascii < ascii_end)
  {
    int c_len;
1532
    if ((c_len= my_ci_wc_mb(json_cs, (my_wc_t) *ascii, json, json_end)) > 0)
1533 1534 1535 1536 1537 1538 1539 1540 1541 1542
    {
      json+= c_len;
      ascii++;
      continue;
    }

    /* Error return. */
    return c_len;
  }

1543
  return (int)(json - json_start);
1544 1545 1546 1547 1548 1549 1550 1551
}


int json_unescape(CHARSET_INFO *json_cs,
                  const uchar *json_str, const uchar *json_end,
                  CHARSET_INFO *res_cs, uchar *res, uchar *res_end)
{
  json_string_t s;
1552 1553
  const uchar *res_b= res;

1554 1555 1556 1557
  json_string_setup(&s, json_cs, json_str, json_end);
  while (json_read_string_const_chr(&s) == 0)
  {
    int c_len;
1558
    if ((c_len= my_ci_wc_mb(res_cs, s.c_next, res, res_end)) > 0)
1559 1560 1561 1562 1563 1564 1565 1566 1567 1568
    {
      res+= c_len;
      continue;
    }
    if (c_len == MY_CS_ILUNI)
    {
      /*
        Result charset doesn't support the json's character.
        Let's replace it with the '?' symbol.
      */
1569
      if ((c_len= my_ci_wc_mb(res_cs, '?', res, res_end)) > 0)
1570 1571 1572 1573 1574 1575 1576 1577 1578
      {
        res+= c_len;
        continue;
      }
    }
    /* Result buffer is too small. */
    return -1;
  }

1579
  return s.error==JE_EOS ? (int)(res - res_b) : -1;
1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627
}


/* When we need to replace a character with the escaping. */
enum json_esc_char_classes {
  ESC_= 0,    /* No need to escape. */
  ESC_U= 'u', /* Character not allowed in JSON. Always escape as \uXXXX. */
  ESC_B= 'b', /* Backspace. Escape as \b */
  ESC_F= 'f', /* Formfeed. Escape as \f */
  ESC_N= 'n', /* Newline. Escape as \n */
  ESC_R= 'r', /* Return. Escape as \r */
  ESC_T= 't', /* Tab. Escape as \s */
  ESC_BS= '\\'  /* Backslash or '"'. Escape by the \\ prefix. */
};


/* This specifies how we should escape the character. */
static enum json_esc_char_classes json_escape_chr_map[0x60] = {
  ESC_U,   ESC_U,   ESC_U,   ESC_U,   ESC_U,   ESC_U,   ESC_U,   ESC_U,
  ESC_B,   ESC_T,   ESC_N,   ESC_U,   ESC_F,   ESC_R,   ESC_U,   ESC_U,
  ESC_U,   ESC_U,   ESC_U,   ESC_U,   ESC_U,   ESC_U,   ESC_U,   ESC_U,
  ESC_U,   ESC_U,   ESC_U,   ESC_U,   ESC_U,   ESC_U,   ESC_U,   ESC_U,

  ESC_,    ESC_,    ESC_BS,  ESC_,    ESC_,    ESC_,    ESC_,    ESC_,
  ESC_,    ESC_,    ESC_,    ESC_,    ESC_,    ESC_,    ESC_,    ESC_,
  ESC_,    ESC_,    ESC_,    ESC_,    ESC_,    ESC_,    ESC_,    ESC_,
  ESC_,    ESC_,    ESC_,    ESC_,    ESC_,    ESC_,    ESC_,    ESC_,

  ESC_,    ESC_,    ESC_,    ESC_,    ESC_,    ESC_,    ESC_,    ESC_,
  ESC_,    ESC_,    ESC_,    ESC_,    ESC_,    ESC_,    ESC_,    ESC_,
  ESC_,    ESC_,    ESC_,    ESC_,    ESC_,    ESC_,    ESC_,    ESC_,
  ESC_,    ESC_,    ESC_,    ESC_,    ESC_BS,  ESC_,    ESC_,    ESC_,
};


static const char hexconv[16] = "0123456789ABCDEF";


int json_escape(CHARSET_INFO *str_cs,
                const uchar *str, const uchar *str_end,
                CHARSET_INFO *json_cs, uchar *json, uchar *json_end)
{
  const uchar *json_start= json;

  while (str < str_end)
  {
    my_wc_t c_chr;
    int c_len;
1628
    if ((c_len= my_ci_mb_wc(str_cs, &c_chr, str, str_end)) > 0)
1629 1630 1631 1632
    {
      enum json_esc_char_classes c_class;
      
      str+= c_len;
1633
      if (c_chr >= 0x60 || (c_class= json_escape_chr_map[c_chr]) == ESC_)
1634
      {
1635
        if ((c_len= my_ci_wc_mb(json_cs, c_chr, json, json_end)) > 0)
1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649
        {
          json+= c_len;
          continue;
        }
        if (c_len < 0)
        {
          /* JSON buffer is depleted. */
          return -1;
        }

        /* JSON charset cannot convert this character. */
        c_class= ESC_U;
      }

1650 1651
      if ((c_len= my_ci_wc_mb(json_cs, '\\', json, json_end)) <= 0 ||
          (c_len= my_ci_wc_mb(json_cs, (c_class == ESC_BS) ? c_chr : c_class,
1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690
                                       json+= c_len, json_end)) <= 0)
      {
        /* JSON buffer is depleted. */
        return -1;
      }
      json+= c_len;

      if (c_class != ESC_U)
        continue;

      {
        /* We have to use /uXXXX escaping. */
        uchar utf16buf[4];
        uchar code_str[8];
        int u_len= my_uni_utf16(0, c_chr, utf16buf, utf16buf + 4);

        code_str[0]= hexconv[utf16buf[0] >> 4];
        code_str[1]= hexconv[utf16buf[0] & 15];
        code_str[2]= hexconv[utf16buf[1] >> 4];
        code_str[3]= hexconv[utf16buf[1] & 15];

        if (u_len > 2)
        {
          code_str[4]= hexconv[utf16buf[2] >> 4];
          code_str[5]= hexconv[utf16buf[2] & 15];
          code_str[6]= hexconv[utf16buf[3] >> 4];
          code_str[7]= hexconv[utf16buf[3] & 15];
        }
        
        if ((c_len= json_append_ascii(json_cs, json, json_end,
                                      code_str, code_str+u_len*2)) > 0)
        {
          json+= c_len;
          continue;
        }
        /* JSON buffer is depleted. */
        return -1;
      }
    }
1691 1692
    else /* c_len == 0, an illegal symbol. */
      return -1;
1693 1694
  }

1695
  return (int)(json - json_start);
1696
}
1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744


int json_get_path_start(json_engine_t *je, CHARSET_INFO *i_cs,
                        const uchar *str, const uchar *end,
                        json_path_t *p)
{
  json_scan_start(je, i_cs, str, end);
  p->last_step= p->steps - 1; 
  return 0;
}


int json_get_path_next(json_engine_t *je, json_path_t *p)
{
  if (p->last_step < p->steps)
  {
    if (json_read_value(je))
      return 1;

    p->last_step= p->steps;
    p->steps[0].type= JSON_PATH_ARRAY_WILD;
    p->steps[0].n_item= 0;
    return 0;
  }
  else
  {
    if (json_value_scalar(je))
    {
      if (p->last_step->type & JSON_PATH_ARRAY)
        p->last_step->n_item++;
    }
    else
    {
      p->last_step++;
      p->last_step->type= (enum json_path_step_types) je->value_type;
      p->last_step->n_item= 0;
    }

    if (json_scan_next(je))
      return 1;
  }

  do
  {
    switch (je->state)
    {
    case JST_KEY:
      p->last_step->key= je->s.c_str;
1745 1746
      do
      {
1747
        p->last_step->key_end= je->s.c_str;
1748
      } while (json_read_keyname_chr(je) == 0);
1749 1750 1751 1752
      if (je->s.error)
        return 1;
      /* Now we have je.state == JST_VALUE, so let's handle it. */

1753
      /* fall through */
1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772
    case JST_VALUE:
      if (json_read_value(je))
        return 1;
      return 0;
    case JST_OBJ_END:
    case JST_ARRAY_END:
      p->last_step--;
      if (p->last_step->type & JSON_PATH_ARRAY)
        p->last_step->n_item++;
      break;
    default:
      break;
    }
  } while (json_scan_next(je) == 0);

  return 1;
}


1773 1774 1775 1776
int json_path_parts_compare(
    const json_path_step_t *a, const json_path_step_t *a_end,
    const json_path_step_t *b, const json_path_step_t *b_end,
    enum json_value_types vt)
1777
{
1778
  int res, res2;
1779

1780
  while (a <= a_end)
1781
  {
1782 1783 1784 1785 1786 1787 1788 1789 1790
    if (b > b_end)
    {
      while (vt != JSON_VALUE_ARRAY &&
             (a->type & JSON_PATH_ARRAY_WILD) == JSON_PATH_ARRAY &&
             a->n_item == 0)
      {
        if (++a > a_end)
          return 0;
      }
1791
      return -2;
1792 1793 1794 1795
    }

    DBUG_ASSERT((b->type & (JSON_PATH_WILD | JSON_PATH_DOUBLE_WILD)) == 0);

1796
    
1797
    if (a->type & JSON_PATH_ARRAY)
1798
    {
1799 1800 1801 1802
      if (b->type & JSON_PATH_ARRAY)
      {
        if ((a->type & JSON_PATH_WILD) || a->n_item == b->n_item)
          goto step_fits;
1803
        goto step_failed;
1804
      }
1805
      if ((a->type & JSON_PATH_WILD) == 0 && a->n_item == 0)
1806 1807
        goto step_fits_autowrap;
      goto step_failed;
1808 1809 1810
    }
    else /* JSON_PATH_KEY */
    {
1811 1812 1813 1814 1815 1816
      if (!(b->type & JSON_PATH_KEY))
        goto step_failed;
    
      if (!(a->type & JSON_PATH_WILD) &&
          (a->key_end - a->key != b->key_end - b->key ||
           memcmp(a->key, b->key, a->key_end - a->key) != 0))
1817 1818
        goto step_failed;

1819 1820
      goto step_fits;
    }
1821
step_failed:
1822
    if (!(a->type & JSON_PATH_DOUBLE_WILD))
1823
      return -1;
1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859
    b++;
    continue;

step_fits:
    b++;
    if (!(a->type & JSON_PATH_DOUBLE_WILD))
    {
      a++;
      continue;
    }

    /* Double wild handling needs recursions. */
    res= json_path_parts_compare(a+1, a_end, b, b_end, vt);
    if (res == 0)
      return 0;

    res2= json_path_parts_compare(a, a_end, b, b_end, vt);

    return (res2 >= 0) ? res2 : res;

step_fits_autowrap:
    if (!(a->type & JSON_PATH_DOUBLE_WILD))
    {
      a++;
      continue;
    }

    /* Double wild handling needs recursions. */
    res= json_path_parts_compare(a+1, a_end, b+1, b_end, vt);
    if (res == 0)
      return 0;

    res2= json_path_parts_compare(a, a_end, b+1, b_end, vt);

    return (res2 >= 0) ? res2 : res;

1860 1861
  }

1862
  return b <= b_end;
1863 1864 1865
}


1866 1867 1868 1869 1870 1871 1872
int json_path_compare(const json_path_t *a, const json_path_t *b,
                      enum json_value_types vt)
{
  return json_path_parts_compare(a->steps+1, a->last_step,
                                 b->steps+1, b->last_step, vt);
}

1873

1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888
static enum json_types smart_read_value(json_engine_t *je,
                                        const char **value, int *value_len)
{
  if (json_read_value(je))
    goto err_return;

  *value= (char *) je->value;

  if (json_value_scalar(je))
    *value_len= je->value_len;
  else
  {
    if (json_skip_level(je))
      goto err_return;

1889
    *value_len= (int) ((char *) je->s.c_str - *value);
1890 1891
  }

1892 1893 1894 1895 1896 1897 1898 1899 1900
  compile_time_assert((int) JSON_VALUE_OBJECT == (int) JSV_OBJECT);
  compile_time_assert((int) JSON_VALUE_ARRAY == (int) JSV_ARRAY);
  compile_time_assert((int) JSON_VALUE_STRING == (int) JSV_STRING);
  compile_time_assert((int) JSON_VALUE_NUMBER == (int) JSV_NUMBER);
  compile_time_assert((int) JSON_VALUE_TRUE == (int) JSV_TRUE);
  compile_time_assert((int) JSON_VALUE_FALSE == (int) JSV_FALSE);
  compile_time_assert((int) JSON_VALUE_NULL == (int) JSV_NULL);

  return (enum json_types) je->value_type;
1901 1902 1903 1904 1905 1906

err_return:
  return JSV_BAD_JSON;
}


1907
enum json_types json_type(const char *js, const char *js_end,
1908
                          const char **value, int *value_len)
1909
{
1910 1911 1912 1913 1914 1915
  json_engine_t je;

  json_scan_start(&je, &my_charset_utf8mb4_bin,(const uchar *) js,
                  (const uchar *) js_end);

  return smart_read_value(&je, value, value_len);
1916 1917 1918 1919 1920
}


enum json_types json_get_array_item(const char *js, const char *js_end,
                                    int n_item,
1921
                                    const char **value, int *value_len)
1922
{
1923 1924
  json_engine_t je;
  int c_item= 0;
1925

1926 1927
  json_scan_start(&je, &my_charset_utf8mb4_bin,(const uchar *) js,
                  (const uchar *) js_end);
1928

1929 1930 1931
  if (json_read_value(&je) ||
      je.value_type != JSON_VALUE_ARRAY)
    goto err_return;
1932

1933 1934 1935 1936 1937 1938 1939
  while (!json_scan_next(&je))
  {
    switch (je.state)
    {
    case JST_VALUE:
      if (c_item == n_item)
        return smart_read_value(&je, value, value_len);
1940

1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955
      if (json_skip_key(&je))
        goto err_return;

      c_item++;
      break;

    case JST_ARRAY_END:
      *value= (const char *) (je.s.c_str - je.sav_c_len);
      *value_len= c_item;
      return JSV_NOTHING;
    }
  }

err_return:
  return JSV_BAD_JSON;
1956 1957
}

1958

Sergei Golubchik's avatar
Sergei Golubchik committed
1959 1960
/** Simple json lookup for a value by the key.

1961 1962 1963
  Expects JSON object.
  Only scans the 'first level' of the object, not
  the nested structures.
Sergei Golubchik's avatar
Sergei Golubchik committed
1964

1965 1966
  @param js          [in]       json object to search in
  @param js_end      [in]       end of json string
Sergei Golubchik's avatar
Sergei Golubchik committed
1967
  @param key         [in]       key to search for
1968
  @param key_end     [in]         - " -
Sergei Golubchik's avatar
Sergei Golubchik committed
1969 1970 1971
  @param value_start [out]      pointer into js (value or closing })
  @param value_len   [out]      length of the value found or number of keys

1972 1973 1974 1975
  @retval the type of the key value
  @retval JSV_BAD_JSON - syntax error found reading JSON.
                         or not JSON object.
  @retval JSV_NOTHING - no such key found.
Sergei Golubchik's avatar
Sergei Golubchik committed
1976
*/
1977
enum json_types json_get_object_key(const char *js, const char *js_end,
1978
                                    const char *key,
1979
                                    const char **value, int *value_len)
Sergei Golubchik's avatar
Sergei Golubchik committed
1980
{
1981
  const char *key_end= key + strlen(key);
Sergei Golubchik's avatar
Sergei Golubchik committed
1982 1983 1984 1985 1986
  json_engine_t je;
  json_string_t key_name;
  int n_keys= 0;

  json_string_set_cs(&key_name, &my_charset_utf8mb4_bin);
1987

Sergei Golubchik's avatar
Sergei Golubchik committed
1988
  json_scan_start(&je, &my_charset_utf8mb4_bin,(const uchar *) js,
1989
                  (const uchar *) js_end);
Sergei Golubchik's avatar
Sergei Golubchik committed
1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001

  if (json_read_value(&je) ||
      je.value_type != JSON_VALUE_OBJECT)
    goto err_return;

  while (!json_scan_next(&je))
  {
    switch (je.state)
    {
    case JST_KEY:
      n_keys++;
      json_string_set_str(&key_name, (const uchar *) key,
2002 2003 2004 2005 2006 2007 2008
                          (const uchar *) key_end);
      if (json_key_matches(&je, &key_name))
        return smart_read_value(&je, value, value_len);

      if (json_skip_key(&je))
        goto err_return;

Sergei Golubchik's avatar
Sergei Golubchik committed
2009 2010 2011
      break;

    case JST_OBJ_END:
2012
      *value= (const char *) (je.s.c_str - je.sav_c_len);
Sergei Golubchik's avatar
Sergei Golubchik committed
2013
      *value_len= n_keys;
2014
      return JSV_NOTHING;
Sergei Golubchik's avatar
Sergei Golubchik committed
2015 2016 2017 2018
    }
  }

err_return:
2019
  return JSV_BAD_JSON;
Sergei Golubchik's avatar
Sergei Golubchik committed
2020 2021
}

2022

2023 2024 2025 2026 2027 2028 2029
enum json_types json_get_object_nkey(const char *js __attribute__((unused)),
                                     const char *js_end __attribute__((unused)),
                                     int nkey __attribute__((unused)),
                                     const char **keyname __attribute__((unused)),
                                     const char **keyname_end __attribute__((unused)),
                                     const char **value __attribute__((unused)),
                                     int *value_len __attribute__((unused)))
2030 2031 2032 2033 2034
{
  return JSV_NOTHING;
}


Sergei Golubchik's avatar
Sergei Golubchik committed
2035 2036 2037 2038
/** Check if json is valid (well-formed)

  @retval 0 - success, json is well-formed
  @retval 1 - error, json is invalid
2039 2040
*/
int json_valid(const char *js, size_t js_len, CHARSET_INFO *cs)
Sergei Golubchik's avatar
Sergei Golubchik committed
2041 2042 2043 2044 2045 2046
{
  json_engine_t je;
  json_scan_start(&je, cs, (const uchar *) js, (const uchar *) js + js_len);
  while (json_scan_next(&je) == 0) /* no-op */ ;
  return je.s.error == 0;
}
2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132


/*
  Expects the JSON object as an js argument, and the key name.
  Looks for this key in the object and returns
  the location of all the text related to it.
  The text includes the comma, separating this key.

  comma_pos - the hint where the comma is. It is important
       if you plan to replace the key rather than just cut.
    1  - comma is on the left
    2  - comma is on the right.
    0  - no comma at all (the object has just this single key)
 
  if no such key found *key_start is set to NULL.
*/
int json_locate_key(const char *js, const char *js_end,
                    const char *kname,
                    const char **key_start, const char **key_end,
                    int *comma_pos)
{
  const char *kname_end= kname + strlen(kname);
  json_engine_t je;
  json_string_t key_name;
  int t_next, c_len, match_result;

  json_string_set_cs(&key_name, &my_charset_utf8mb4_bin);

  json_scan_start(&je, &my_charset_utf8mb4_bin,(const uchar *) js,
                  (const uchar *) js_end);

  if (json_read_value(&je) ||
      je.value_type != JSON_VALUE_OBJECT)
    goto err_return;

  *key_start= (const char *) je.s.c_str;
  *comma_pos= 0;

  while (!json_scan_next(&je))
  {
    switch (je.state)
    {
    case JST_KEY:
      json_string_set_str(&key_name, (const uchar *) kname,
                          (const uchar *) kname_end);
      match_result= json_key_matches(&je, &key_name);
      if (json_skip_key(&je))
        goto err_return;
      get_first_nonspace(&je.s, &t_next, &c_len);
      je.s.c_str-= c_len;

      if (match_result)
      {
        *key_end= (const char *) je.s.c_str;

        if (*comma_pos == 1)
          return 0;

        DBUG_ASSERT(*comma_pos == 0);

        if (t_next == C_COMMA)
        {
          *key_end+= c_len;
          *comma_pos= 2;
        }
        else if (t_next == C_RCURB)
          *comma_pos= 0;
        else
          goto err_return;
        return 0;
      }

      *key_start= (const char *) je.s.c_str;
      *comma_pos= 1;
      break;

    case JST_OBJ_END:
      *key_start= NULL;
      return 0;
    }
  }

err_return:
  return 1;

}