LCOV - code coverage report
Current view: top level - gcc - json-parsing.cc (source / functions) Coverage Total Hit
Test: gcc.info Lines: 85.7 % 1216 1042
Test Date: 2026-11-14 16:39:50 Functions: 96.5 % 57 55
Legend: Lines:     hit not hit

            Line data    Source code
       1              : /* JSON parsing
       2              :    Copyright (C) 2017-2026 Free Software Foundation, Inc.
       3              :    Contributed by David Malcolm <dmalcolm@redhat.com>.
       4              : 
       5              : This file is part of GCC.
       6              : 
       7              : GCC is free software; you can redistribute it and/or modify it under
       8              : the terms of the GNU General Public License as published by the Free
       9              : Software Foundation; either version 3, or (at your option) any later
      10              : version.
      11              : 
      12              : GCC is distributed in the hope that it will be useful, but WITHOUT ANY
      13              : WARRANTY; without even the implied warranty of MERCHANTABILITY or
      14              : FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
      15              : for more details.
      16              : 
      17              : You should have received a copy of the GNU General Public License
      18              : along with GCC; see the file COPYING3.  If not see
      19              : <http://www.gnu.org/licenses/>.  */
      20              : 
      21              : #define INCLUDE_MAP
      22              : #include "config.h"
      23              : #include "system.h"
      24              : #include "coretypes.h"
      25              : #include "json-parsing.h"
      26              : #include "pretty-print.h"
      27              : #include "math.h"
      28              : #include "selftest.h"
      29              : 
      30              : using namespace json;
      31              : 
      32              : /* Declarations relating to parsing JSON, all within an
      33              :    anonymous namespace.  */
      34              : 
      35              : namespace {
      36              : 
      37              : /* A typedef representing a single unicode character.  */
      38              : 
      39              : typedef unsigned unichar;
      40              : 
      41              : /* An enum for discriminating different kinds of JSON token.  */
      42              : 
      43              : enum token_id
      44              : {
      45              :   TOK_ERROR,
      46              : 
      47              :   TOK_EOF,
      48              : 
      49              :   /* Punctuation.  */
      50              :   TOK_OPEN_SQUARE,
      51              :   TOK_OPEN_CURLY,
      52              :   TOK_CLOSE_SQUARE,
      53              :   TOK_CLOSE_CURLY,
      54              :   TOK_COLON,
      55              :   TOK_COMMA,
      56              : 
      57              :   /* Literal names.  */
      58              :   TOK_TRUE,
      59              :   TOK_FALSE,
      60              :   TOK_NULL,
      61              : 
      62              :   TOK_STRING,
      63              :   TOK_FLOAT_NUMBER,
      64              :   TOK_INTEGER_NUMBER
      65              : };
      66              : 
      67              : /* Human-readable descriptions of enum token_id.  */
      68              : 
      69              : static const char *token_id_name[] = {
      70              :   "error",
      71              :   "EOF",
      72              :   "'['",
      73              :   "'{'",
      74              :   "']'",
      75              :   "'}'",
      76              :   "':'",
      77              :   "','",
      78              :   "'true'",
      79              :   "'false'",
      80              :   "'null'",
      81              :   "string",
      82              :   "number",
      83              :   "number"
      84              : };
      85              : 
      86              : /* Tokens within the JSON lexer.  */
      87              : 
      88              : struct token
      89              : {
      90              :   /* The kind of token.  */
      91              :   enum token_id id;
      92              : 
      93              :   /* The location of this token within the unicode
      94              :      character stream.  */
      95              :   location_map::range range;
      96              : 
      97              :   union
      98              :   {
      99              :     /* Value for TOK_ERROR and TOK_STRING.  */
     100              :     char *string;
     101              : 
     102              :     /* Value for TOK_FLOAT_NUMBER.  */
     103              :     double float_number;
     104              : 
     105              :     /* Value for TOK_INTEGER_NUMBER.  */
     106              :     long integer_number;
     107              :   } u;
     108              : };
     109              : 
     110              : /* A class for lexing JSON.  */
     111              : 
     112              : class lexer
     113              : {
     114              :  public:
     115              :   lexer (bool support_comments);
     116              :   ~lexer ();
     117              : 
     118              :   std::unique_ptr<error> add_utf8 (size_t length, const char *utf8_buf);
     119              : 
     120              :   const token *peek ();
     121              : 
     122              :   void consume ();
     123              : 
     124              :  private:
     125              :   bool get_char (unichar &out_char, location_map::point *out_point);
     126              :   void unget_char ();
     127              :   location_map::point get_next_point () const;
     128              :   static void dump_token (FILE *outf, const token *tok);
     129              :   void lex_token (token *out);
     130              :   void lex_string (token *out);
     131              :   void lex_number (token *out, unichar first_char);
     132              :   bool rest_of_literal (token *out, const char *suffix);
     133              :   std::unique_ptr<error> make_error (const char *msg);
     134              :   bool consume_single_line_comment (token *out);
     135              :   bool consume_multiline_comment (token *out);
     136              : 
     137              :  private:
     138              :   auto_vec<unichar> m_buffer;
     139              :   int m_next_char_idx;
     140              :   int m_next_char_line;
     141              :   int m_next_char_column;
     142              :   int m_prev_line_final_column; /* for handling unget_char after a '\n'.  */
     143              : 
     144              :   static const int MAX_TOKENS = 1;
     145              :   token m_next_tokens[MAX_TOKENS];
     146              :   int m_num_next_tokens;
     147              : 
     148              :   bool m_support_comments;
     149              : };
     150              : 
     151              : /* A class for parsing JSON.  */
     152              : 
     153              : class parser
     154              : {
     155              :  public:
     156              :   parser (location_map *out_loc_map,
     157              :           bool support_comments);
     158              :   ~parser ();
     159              : 
     160              :   std::unique_ptr<error>
     161              :   add_utf8 (size_t length, const char *utf8_buf);
     162              : 
     163              :   parser_result_t parse_value (int depth);
     164              :   parser_result_t parse_object (int depth);
     165              :   parser_result_t parse_array (int depth);
     166              : 
     167              :   std::unique_ptr<error>
     168              :   require_eof ();
     169              : 
     170              :  private:
     171              :   location_map::point get_next_token_start ();
     172              :   location_map::point get_next_token_end ();
     173              : 
     174              :   std::unique_ptr<error>
     175              :   require (enum token_id tok_id);
     176              : 
     177              :   result<enum token_id, std::unique_ptr<error>>
     178              :   require_one_of (enum token_id tok_id_a, enum token_id tok_id_b);
     179              : 
     180              :   std::unique_ptr<error>
     181              :   error_at (const location_map::range &r,
     182              :             const char *fmt, ...) ATTRIBUTE_PRINTF_3;
     183              : 
     184              :   void maybe_record_range (json::value *jv, const location_map::range &r);
     185              :   void maybe_record_range (json::value *jv,
     186              :                            const location_map::point &start,
     187              :                            const location_map::point &end);
     188              : 
     189              :  private:
     190              :   lexer m_lexer;
     191              :   location_map *m_loc_map;
     192              : };
     193              : 
     194              : } // anonymous namespace for parsing implementation
     195              : 
     196              : /* Parser implementation.  */
     197              : 
     198              : /* lexer's ctor.  */
     199              : 
     200          120 : lexer::lexer (bool support_comments)
     201          120 : : m_buffer (), m_next_char_idx (0),
     202          120 :   m_next_char_line (1), m_next_char_column (0),
     203          120 :   m_prev_line_final_column (-1),
     204          120 :   m_num_next_tokens (0),
     205          120 :   m_support_comments (support_comments)
     206              : {
     207            0 : }
     208              : 
     209              : /* lexer's dtor.  */
     210              : 
     211          120 : lexer::~lexer ()
     212              : {
     213          140 :   while (m_num_next_tokens > 0)
     214           20 :     consume ();
     215          120 : }
     216              : 
     217              : /* Peek the next token.  */
     218              : 
     219              : const token *
     220         1004 : lexer::peek ()
     221              : {
     222         1004 :   if (m_num_next_tokens == 0)
     223              :     {
     224          720 :       lex_token (&m_next_tokens[0]);
     225          720 :       m_num_next_tokens++;
     226              :     }
     227         1004 :   return &m_next_tokens[0];
     228              : }
     229              : 
     230              : /* Consume the next token.  */
     231              : 
     232              : void
     233          720 : lexer::consume ()
     234              : {
     235          720 :   if (m_num_next_tokens == 0)
     236            0 :     peek ();
     237              : 
     238          720 :   gcc_assert (m_num_next_tokens > 0);
     239          720 :   gcc_assert (m_num_next_tokens <= MAX_TOKENS);
     240              : 
     241          720 :   if (0)
     242              :     {
     243              :       fprintf (stderr, "consuming token: ");
     244              :       dump_token (stderr, &m_next_tokens[0]);
     245              :       fprintf (stderr, "\n");
     246              :     }
     247              : 
     248          720 :   if (m_next_tokens[0].id == TOK_ERROR
     249          720 :       || m_next_tokens[0].id == TOK_STRING)
     250          136 :     free (m_next_tokens[0].u.string);
     251              : 
     252          720 :   m_num_next_tokens--;
     253          720 :   memmove (&m_next_tokens[0], &m_next_tokens[1],
     254          720 :            sizeof (token) * m_num_next_tokens);
     255          720 : }
     256              : 
     257              : /* Add LENGTH bytes of UTF-8 encoded text from UTF8_BUF to this lexer's
     258              :    buffer.
     259              :    Return null if successful, or the error if there was a problem.  */
     260              : 
     261              : std::unique_ptr<error>
     262          120 : lexer::add_utf8 (size_t length, const char *utf8_buf)
     263              : {
     264              :   /* Adapted from charset.c:one_utf8_to_cppchar.  */
     265          120 :   static const uchar masks[6] = { 0x7F, 0x1F, 0x0F, 0x07, 0x03, 0x01 };
     266          120 :   static const uchar patns[6] = { 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC };
     267              : 
     268          120 :   const uchar *inbuf = (const unsigned char *) (utf8_buf);
     269          120 :   const uchar **inbufp = &inbuf;
     270          120 :   size_t *inbytesleftp = &length;
     271              : 
     272        10112 :   while (length > 0)
     273              :     {
     274         9992 :       unichar c;
     275         9992 :       const uchar *inbuf = *inbufp;
     276         9992 :       size_t nbytes, i;
     277              : 
     278         9992 :       c = *inbuf;
     279         9992 :       if (c < 0x80)
     280              :         {
     281         9956 :           m_buffer.safe_push (c);
     282         9956 :           *inbytesleftp -= 1;
     283         9956 :           *inbufp += 1;
     284         9956 :           continue;
     285              :         }
     286              : 
     287              :       /* The number of leading 1-bits in the first byte indicates how many
     288              :          bytes follow.  */
     289           72 :       for (nbytes = 2; nbytes < 7; nbytes++)
     290           72 :         if ((c & ~masks[nbytes-1]) == patns[nbytes-1])
     291           36 :           goto found;
     292            0 :       return make_error ("ill-formed UTF-8 sequence");
     293           36 :     found:
     294              : 
     295           36 :       if (*inbytesleftp < nbytes)
     296            0 :         return make_error ("ill-formed UTF-8 sequence");
     297              : 
     298           36 :       c = (c & masks[nbytes-1]);
     299           36 :       inbuf++;
     300          108 :       for (i = 1; i < nbytes; i++)
     301              :         {
     302           72 :           unichar n = *inbuf++;
     303           72 :           if ((n & 0xC0) != 0x80)
     304            0 :             return make_error ("ill-formed UTF-8 sequence");
     305           72 :           c = ((c << 6) + (n & 0x3F));
     306              :         }
     307              : 
     308              :       /* Make sure the shortest possible encoding was used.  */
     309           36 :       if ((   c <=      0x7F && nbytes > 1)
     310           36 :           || (c <=     0x7FF && nbytes > 2)
     311           36 :           || (c <=    0xFFFF && nbytes > 3)
     312           36 :           || (c <=  0x1FFFFF && nbytes > 4)
     313           36 :           || (c <= 0x3FFFFFF && nbytes > 5))
     314            0 :         return make_error ("ill-formed UTF-8:"
     315            0 :                            " shortest possible encoding not used");
     316              : 
     317              :       /* Make sure the character is valid.  */
     318           36 :       if (c > 0x7FFFFFFF || (c >= 0xD800 && c <= 0xDFFF))
     319            0 :         return make_error ("ill-formed UTF-8: invalid character");
     320              : 
     321           36 :       m_buffer.safe_push (c);
     322           36 :       *inbufp = inbuf;
     323           36 :       *inbytesleftp -= nbytes;
     324              :     }
     325          120 :   return nullptr;
     326              : }
     327              : 
     328              : /* Attempt to get the next unicode character from this lexer's buffer.
     329              :    If successful, write it to OUT_CHAR, and its location to *OUT_POINT,
     330              :    and return true.
     331              :    Otherwise, return false.  */
     332              : 
     333              : bool
     334        10028 : lexer::get_char (unichar &out_char, location_map::point *out_point)
     335              : {
     336        20052 :   if (m_next_char_idx >= (int)m_buffer.length ())
     337              :     return false;
     338              : 
     339         9892 :   if (out_point)
     340         2884 :     *out_point = get_next_point ();
     341         9892 :   out_char = m_buffer[m_next_char_idx++];
     342              : 
     343         9892 :   if (out_char == '\n')
     344              :     {
     345          252 :       m_next_char_line++;
     346          252 :       m_prev_line_final_column = m_next_char_column;
     347          252 :       m_next_char_column = 0;
     348              :     }
     349              :   else
     350         9640 :     m_next_char_column++;
     351              : 
     352              :   return true;
     353              : }
     354              : 
     355              : /* Undo the last successful get_char.  */
     356              : 
     357              : void
     358          496 : lexer::unget_char ()
     359              : {
     360          496 :   --m_next_char_idx;
     361          496 :   if (m_next_char_column > 0)
     362          456 :     --m_next_char_column;
     363              :   else
     364              :     {
     365           40 :       m_next_char_line--;
     366           40 :       m_next_char_column = m_prev_line_final_column;
     367              :       /* We don't support more than one unget_char in a row.  */
     368           40 :       gcc_assert (m_prev_line_final_column != -1);
     369           40 :       m_prev_line_final_column = -1;
     370              :     }
     371          496 : }
     372              : 
     373              : /* Get the location of the next char.  */
     374              : 
     375              : location_map::point
     376         2976 : lexer::get_next_point () const
     377              : {
     378         2976 :   location_map::point result;
     379         2976 :   result.m_unichar_idx = m_next_char_idx;
     380         2976 :   result.m_line = m_next_char_line;
     381         2976 :   result.m_column = m_next_char_column;
     382         2884 :   return result;
     383              : }
     384              : 
     385              : /* Print a textual representation of TOK to OUTF.
     386              :    This is intended for debugging the lexer and parser,
     387              :    rather than for user-facing output.  */
     388              : 
     389              : void
     390            0 : lexer::dump_token (FILE *outf, const token *tok)
     391              : {
     392            0 :   switch (tok->id)
     393              :     {
     394            0 :     case TOK_ERROR:
     395            0 :       fprintf (outf, "TOK_ERROR (\"%s\")", tok->u.string);
     396            0 :       break;
     397              : 
     398            0 :     case TOK_EOF:
     399            0 :       fprintf (outf, "TOK_EOF");
     400            0 :       break;
     401              : 
     402            0 :     case TOK_OPEN_SQUARE:
     403            0 :       fprintf (outf, "TOK_OPEN_SQUARE");
     404            0 :       break;
     405              : 
     406            0 :     case TOK_OPEN_CURLY:
     407            0 :       fprintf (outf, "TOK_OPEN_CURLY");
     408            0 :       break;
     409              : 
     410            0 :     case TOK_CLOSE_SQUARE:
     411            0 :       fprintf (outf, "TOK_CLOSE_SQUARE");
     412            0 :       break;
     413              : 
     414            0 :     case TOK_CLOSE_CURLY:
     415            0 :       fprintf (outf, "TOK_CLOSE_CURLY");
     416            0 :       break;
     417              : 
     418            0 :     case TOK_COLON:
     419            0 :       fprintf (outf, "TOK_COLON");
     420            0 :       break;
     421              : 
     422            0 :     case TOK_COMMA:
     423            0 :       fprintf (outf, "TOK_COMMA");
     424            0 :       break;
     425              : 
     426            0 :     case TOK_TRUE:
     427            0 :       fprintf (outf, "TOK_TRUE");
     428            0 :       break;
     429              : 
     430            0 :     case TOK_FALSE:
     431            0 :       fprintf (outf, "TOK_FALSE");
     432            0 :       break;
     433              : 
     434            0 :     case TOK_NULL:
     435            0 :       fprintf (outf, "TOK_NULL");
     436            0 :       break;
     437              : 
     438            0 :     case TOK_STRING:
     439            0 :       fprintf (outf, "TOK_STRING (\"%s\")", tok->u.string);
     440            0 :       break;
     441              : 
     442            0 :     case TOK_FLOAT_NUMBER:
     443            0 :       fprintf (outf, "TOK_FLOAT_NUMBER (%f)", tok->u.float_number);
     444            0 :       break;
     445              : 
     446            0 :     case TOK_INTEGER_NUMBER:
     447            0 :       fprintf (outf, "TOK_INTEGER_NUMBER (%ld)", tok->u.integer_number);
     448            0 :       break;
     449              : 
     450            0 :     default:
     451            0 :       gcc_unreachable ();
     452            0 :       break;
     453              :     }
     454            0 : }
     455              : 
     456              : /* Treat "//" as a comment to the end of the line.
     457              : 
     458              :    This isn't compliant with the JSON spec,
     459              :    but is very handy for writing DejaGnu tests.
     460              : 
     461              :    Return true if EOF and populate *OUT, false otherwise.  */
     462              : 
     463              : bool
     464           16 : lexer::consume_single_line_comment (token *out)
     465              : {
     466          208 :   while (1)
     467              :     {
     468          112 :       unichar next_char;
     469          112 :       if (!get_char (next_char, nullptr))
     470              :         {
     471            0 :           out->id = TOK_EOF;
     472            0 :           location_map::point p = get_next_point ();
     473            0 :           out->range.m_start = p;
     474            0 :           out->range.m_end = p;
     475            0 :           return true;
     476              :         }
     477          112 :       if (next_char == '\n')
     478              :         return false;
     479           96 :     }
     480              : }
     481              : 
     482              : /* Treat '/' '*' as a multiline comment until the next closing '*' '/'.
     483              : 
     484              :    This isn't compliant with the JSON spec,
     485              :    but is very handy for writing DejaGnu tests.
     486              : 
     487              :    Return true if EOF and populate *OUT, false otherwise.  */
     488              : 
     489              : bool
     490           20 : lexer::consume_multiline_comment (token *out)
     491              : {
     492         6876 :   while (1)
     493              :     {
     494         6876 :       unichar next_char;
     495         6876 :       if (!get_char (next_char, nullptr))
     496              :         {
     497            0 :           out->id = TOK_ERROR;
     498            0 :           gcc_unreachable (); // TODO
     499              :           location_map::point p = get_next_point ();
     500              :           out->range.m_start = p;
     501              :           out->range.m_end = p;
     502              :           return true;
     503              :         }
     504         6876 :       if (next_char != '*')
     505         6856 :         continue;
     506           20 :       if (!get_char (next_char, nullptr))
     507              :         {
     508            0 :           out->id = TOK_ERROR;
     509            0 :           gcc_unreachable (); // TODO
     510              :           location_map::point p = get_next_point ();
     511              :           out->range.m_start = p;
     512              :           out->range.m_end = p;
     513              :           return true;
     514              :         }
     515           20 :       if (next_char == '/')
     516           20 :         return false;
     517              :     }
     518              : }
     519              : 
     520              : /* Attempt to lex the input buffer, writing the next token to OUT.
     521              :    On errors, TOK_ERROR (or TOK_EOF) is written to OUT.  */
     522              : 
     523              : void
     524          720 : lexer::lex_token (token *out)
     525              : {
     526              :   /* Skip to next non-whitespace char.  */
     527         1540 :   unichar next_char;
     528         1540 :   location_map::point start_point;
     529         1540 :   while (1)
     530              :     {
     531         1540 :       if (!get_char (next_char, &start_point))
     532              :         {
     533           92 :           out->id = TOK_EOF;
     534           92 :           location_map::point p = get_next_point ();
     535           92 :           out->range.m_start = p;
     536           92 :           out->range.m_end = p;
     537           92 :           return;
     538              :         }
     539         1448 :       if (m_support_comments)
     540          612 :         if (next_char == '/')
     541              :           {
     542           36 :             location_map::point point;
     543           36 :             unichar next_next_char;
     544           36 :             if (get_char (next_next_char, &point))
     545              :               {
     546           36 :                 switch (next_next_char)
     547              :                   {
     548           16 :                   case '/':
     549           16 :                     if (consume_single_line_comment (out))
     550            0 :                       return;
     551           36 :                     continue;
     552           20 :                   case '*':
     553           20 :                     if (consume_multiline_comment (out))
     554              :                       return;
     555           20 :                     continue;
     556            0 :                   default:
     557              :                     /* A stray single '/'.  Break out of loop, so that we
     558              :                        handle it below as an unexpected character.  */
     559            0 :                     goto non_whitespace;
     560              :                   }
     561              :               }
     562              :           }
     563         1412 :       if (next_char != ' '
     564         1412 :           && next_char != '\t'
     565          724 :           && next_char != '\n'
     566          628 :           && next_char != '\r')
     567              :         break;
     568              :     }
     569              : 
     570          628 :  non_whitespace:
     571              : 
     572          628 :   out->range.m_start = start_point;
     573          628 :   out->range.m_end = start_point;
     574              : 
     575          628 :   switch (next_char)
     576              :     {
     577           24 :     case '[':
     578           24 :       out->id = TOK_OPEN_SQUARE;
     579           24 :       break;
     580              : 
     581           28 :     case '{':
     582           28 :       out->id = TOK_OPEN_CURLY;
     583           28 :       break;
     584              : 
     585           20 :     case ']':
     586           20 :       out->id = TOK_CLOSE_SQUARE;
     587           20 :       break;
     588              : 
     589           24 :     case '}':
     590           24 :       out->id = TOK_CLOSE_CURLY;
     591           24 :       break;
     592              : 
     593           76 :     case ':':
     594           76 :       out->id = TOK_COLON;
     595           76 :       break;
     596              : 
     597          108 :     case ',':
     598          108 :       out->id = TOK_COMMA;
     599          108 :       break;
     600              : 
     601          120 :     case '"':
     602          120 :       lex_string (out);
     603          120 :       break;
     604              : 
     605          184 :     case '-':
     606          184 :     case '0':
     607          184 :     case '1':
     608          184 :     case '2':
     609          184 :     case '3':
     610          184 :     case '4':
     611          184 :     case '5':
     612          184 :     case '6':
     613          184 :     case '7':
     614          184 :     case '8':
     615          184 :     case '9':
     616          184 :       lex_number (out, next_char);
     617          184 :       break;
     618              : 
     619            8 :     case 't':
     620              :       /* Handle literal "true".  */
     621            8 :       if (rest_of_literal (out, "rue"))
     622              :         {
     623            8 :           out->id = TOK_TRUE;
     624            8 :           break;
     625              :         }
     626              :       else
     627            0 :         goto err;
     628              : 
     629            8 :     case 'f':
     630              :       /* Handle literal "false".  */
     631            8 :       if (rest_of_literal (out, "alse"))
     632              :         {
     633            8 :           out->id = TOK_FALSE;
     634            8 :           break;
     635              :         }
     636              :       else
     637            0 :         goto err;
     638              : 
     639           16 :     case 'n':
     640              :       /* Handle literal "null".  */
     641           16 :       if (rest_of_literal (out, "ull"))
     642              :         {
     643           12 :           out->id = TOK_NULL;
     644           12 :           break;
     645              :         }
     646              :       else
     647            4 :         goto err;
     648              : 
     649           16 :     err:
     650           16 :     default:
     651           16 :       out->id = TOK_ERROR;
     652           16 :       out->u.string = xasprintf ("unexpected character: '%c'", next_char);
     653           16 :       break;
     654              :     }
     655              : }
     656              : 
     657              : /* Having consumed an open-quote character from the lexer's buffer, attempt
     658              :    to lex the rest of a JSON string, writing the result to OUT (or TOK_ERROR)
     659              :    if an error occurred.
     660              :    (ECMA-404 section 9; RFC 7159 section 7).  */
     661              : 
     662              : void
     663          120 : lexer::lex_string (token *out)
     664              : {
     665          120 :   auto_vec<unichar> content;
     666          120 :   bool still_going = true;
     667          716 :   while (still_going)
     668              :     {
     669          596 :       unichar uc;
     670          596 :       if (!get_char (uc, &out->range.m_end))
     671              :         {
     672            0 :           out->id = TOK_ERROR;
     673            0 :           out->range.m_end = get_next_point ();
     674            0 :           out->u.string = xstrdup ("EOF within string");
     675            0 :           return;
     676              :         }
     677          596 :       switch (uc)
     678              :         {
     679              :         case '"':
     680              :           still_going = false;
     681              :           break;
     682           32 :         case '\\':
     683           32 :           {
     684           32 :             unichar next_char;
     685           32 :             if (!get_char (next_char, &out->range.m_end))
     686              :               {
     687            0 :                 out->id = TOK_ERROR;
     688            0 :                 out->range.m_end = get_next_point ();
     689            0 :                 out->u.string = xstrdup ("EOF within string");;
     690            0 :                 return;
     691              :               }
     692           32 :             switch (next_char)
     693              :               {
     694           16 :               case '"':
     695           16 :               case '\\':
     696           16 :               case '/':
     697           16 :                 content.safe_push (next_char);
     698           16 :                 break;
     699              : 
     700            0 :               case 'b':
     701            0 :                 content.safe_push ('\b');
     702            0 :                 break;
     703              : 
     704            0 :               case 'f':
     705            0 :                 content.safe_push ('\f');
     706            0 :                 break;
     707              : 
     708            0 :               case 'n':
     709            0 :                 content.safe_push ('\n');
     710            0 :                 break;
     711              : 
     712            0 :               case 'r':
     713            0 :                 content.safe_push ('\r');
     714            0 :                 break;
     715              : 
     716            0 :               case 't':
     717            0 :                 content.safe_push ('\t');
     718            0 :                 break;
     719              : 
     720           16 :               case 'u':
     721           16 :                 {
     722           16 :                   unichar result = 0;
     723           80 :                   for (int i = 0; i < 4; i++)
     724              :                     {
     725           64 :                       unichar hexdigit;
     726           64 :                       if (!get_char (hexdigit, &out->range.m_end))
     727              :                         {
     728            0 :                           out->id = TOK_ERROR;
     729            0 :                           out->range.m_end = get_next_point ();
     730            0 :                           out->u.string = xstrdup ("EOF within string");
     731            0 :                           return;
     732              :                         }
     733           64 :                       result <<= 4;
     734           64 :                       if (hexdigit >= '0' && hexdigit <= '9')
     735           60 :                         result += hexdigit - '0';
     736            4 :                       else if (hexdigit >= 'a' && hexdigit <= 'f')
     737            4 :                         result += (hexdigit - 'a') + 10;
     738            0 :                       else if (hexdigit >= 'A' && hexdigit <= 'F')
     739            0 :                         result += (hexdigit - 'A') + 10;
     740              :                       else
     741              :                         {
     742            0 :                           out->id = TOK_ERROR;
     743            0 :                           out->range.m_start = out->range.m_end;
     744            0 :                           out->u.string = xstrdup ("bogus hex char");
     745            0 :                           return;
     746              :                         }
     747              :                     }
     748           16 :                   content.safe_push (result);
     749              :                 }
     750           16 :                 break;
     751              : 
     752            0 :               default:
     753            0 :                 out->id = TOK_ERROR;
     754            0 :                 out->u.string = xstrdup ("unrecognized escape char");
     755            0 :                 return;
     756              :               }
     757              :           }
     758           32 :           break;
     759              : 
     760          444 :         default:
     761              :           /* Reject unescaped control characters U+0000 through U+001F
     762              :              (ECMA-404 section 9 para 1; RFC 7159 section 7 para 1).  */
     763          444 :           if (uc <= 0x1f)
     764              :             {
     765            0 :                 out->id = TOK_ERROR;
     766            0 :                 out->range.m_start = out->range.m_end;
     767            0 :                 out->u.string = xstrdup ("unescaped control char");
     768            0 :                 return;
     769              :             }
     770              : 
     771              :           /* Otherwise, add regular unicode code point.  */
     772          444 :           content.safe_push (uc);
     773          444 :           break;
     774              :         }
     775              :     }
     776              : 
     777          120 :   out->id = TOK_STRING;
     778              : 
     779          240 :   auto_vec<char> utf8_buf;
     780              :   // Adapted from libcpp/charset.c:one_cppchar_to_utf8
     781          596 :   for (unsigned i = 0; i < content.length (); i++)
     782              :     {
     783          476 :       static const uchar masks[6] =  { 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC };
     784          476 :       static const uchar limits[6] = { 0x80, 0xE0, 0xF0, 0xF8, 0xFC, 0xFE };
     785          476 :       size_t nbytes;
     786          476 :       uchar buf[6], *p = &buf[6];
     787          476 :       unichar c = content[i];
     788              : 
     789          476 :       nbytes = 1;
     790          476 :       if (c < 0x80)
     791          444 :         *--p = c;
     792              :       else
     793              :         {
     794           64 :           do
     795              :             {
     796           64 :               *--p = ((c & 0x3F) | 0x80);
     797           64 :               c >>= 6;
     798           64 :               nbytes++;
     799              :             }
     800           64 :           while (c >= 0x3F || (c & limits[nbytes-1]));
     801           32 :           *--p = (c | masks[nbytes-1]);
     802              :         }
     803              : 
     804         1016 :       while (p < &buf[6])
     805          540 :         utf8_buf.safe_push (*p++);
     806              :     }
     807              : 
     808          236 :   out->u.string = XNEWVEC (char, utf8_buf.length () + 1);
     809          660 :   for (unsigned i = 0; i < utf8_buf.length (); i++)
     810          540 :     out->u.string[i] = utf8_buf[i];
     811          236 :   out->u.string[utf8_buf.length ()] = '\0';
     812          120 : }
     813              : 
     814              : /* Having consumed FIRST_CHAR, an initial digit or '-' character from
     815              :    the lexer's buffer attempt to lex the rest of a JSON number, writing
     816              :    the result to OUT (or TOK_ERROR) if an error occurred.
     817              :    (ECMA-404 section 8; RFC 7159 section 6).  */
     818              : 
     819              : void
     820          184 : lexer::lex_number (token *out, unichar first_char)
     821              : {
     822          184 :   bool negate = false;
     823          184 :   double value = 0.0;
     824          184 :   if (first_char == '-')
     825              :     {
     826           12 :       negate = true;
     827           12 :       if (!get_char (first_char, &out->range.m_end))
     828              :         {
     829            0 :           out->id = TOK_ERROR;
     830            0 :           out->range.m_start = out->range.m_end;
     831            0 :           out->u.string = xstrdup ("expected digit");
     832            0 :           return;
     833              :         }
     834              :     }
     835              : 
     836          184 :   if (first_char == '0')
     837              :     value = 0.0;
     838          172 :   else if (!ISDIGIT (first_char))
     839              :     {
     840            0 :       out->id = TOK_ERROR;
     841            0 :       out->range.m_start = out->range.m_end;
     842            0 :       out->u.string = xstrdup ("expected digit");
     843            0 :       return;
     844              :     }
     845              :   else
     846              :     {
     847              :       /* Got a nonzero digit; expect zero or more digits.  */
     848          172 :       value = first_char - '0';
     849          404 :       while (1)
     850              :         {
     851          288 :           unichar uc;
     852          288 :           location_map::point point;
     853          288 :           if (!get_char (uc, &point))
     854              :             break;
     855          280 :           if (ISDIGIT (uc))
     856              :             {
     857          116 :               value *= 10;
     858          116 :               value += uc -'0';
     859          116 :               out->range.m_end = point;
     860          116 :               continue;
     861              :             }
     862              :           else
     863              :             {
     864          164 :               unget_char ();
     865          164 :               break;
     866              :             }
     867          116 :         }
     868              :     }
     869              : 
     870              :   /* Optional '.', followed by one or more decimals.  */
     871          184 :   unichar next_char;
     872          184 :   location_map::point point;
     873          184 :   if (get_char (next_char, &point))
     874              :     {
     875          176 :       if (next_char == '.')
     876              :         {
     877              :           /* Parse decimal digits.  */
     878              :           bool had_digit = false;
     879              :           double digit_factor = 0.1;
     880           44 :           while (get_char (next_char, &point))
     881              :             {
     882           40 :               if (!ISDIGIT (next_char))
     883              :                 {
     884            8 :                   unget_char ();
     885            8 :                   break;
     886              :                 }
     887           32 :               value += (next_char - '0') * digit_factor;
     888           32 :               digit_factor *= 0.1;
     889           32 :               had_digit = true;
     890           32 :               out->range.m_end = point;
     891              :             }
     892           12 :           if (!had_digit)
     893              :             {
     894            0 :               out->id = TOK_ERROR;
     895            0 :               out->range.m_start = point;
     896            0 :               out->range.m_start = point;
     897            0 :               out->u.string = xstrdup ("expected digit");
     898            0 :               return;
     899              :             }
     900              :         }
     901              :       else
     902          164 :         unget_char ();
     903              :     }
     904              : 
     905              :   /* Parse 'e' and 'E'.  */
     906          184 :   unichar exponent_char;
     907          184 :   if (get_char (exponent_char, &point))
     908              :     {
     909          172 :       if (exponent_char == 'e' || exponent_char == 'E')
     910              :         {
     911              :           /* Optional +/-.  */
     912           16 :           unichar sign_char;
     913           16 :           int exponent = 0;
     914           16 :           bool negate_exponent = false;
     915           16 :           bool had_exponent_digit = false;
     916           16 :           if (!get_char (sign_char, &point))
     917              :             {
     918            0 :               out->id = TOK_ERROR;
     919            0 :               out->range.m_start = point;
     920            0 :               out->range.m_start = point;
     921            0 :               out->u.string = xstrdup ("EOF within exponent");
     922            0 :               return;
     923              :             }
     924           16 :           if (sign_char == '-')
     925              :             negate_exponent = true;
     926           12 :           else if (sign_char == '+')
     927              :             ;
     928            8 :           else if (ISDIGIT (sign_char))
     929              :             {
     930            8 :               exponent = sign_char - '0';
     931            8 :               had_exponent_digit = true;
     932              :             }
     933              :           else
     934              :             {
     935            0 :               out->id = TOK_ERROR;
     936            0 :               out->range.m_start = point;
     937            0 :               out->range.m_start = point;
     938            0 :               out->u.string
     939            0 :                 = xstrdup ("expected '-','+' or digit within exponent");
     940            0 :               return;
     941              :             }
     942           16 :           out->range.m_end = point;
     943              : 
     944              :           /* One or more digits (we might have seen the digit above,
     945              :              though).  */
     946           32 :           while (1)
     947              :             {
     948           24 :               unichar uc;
     949           24 :               location_map::point point;
     950           24 :               if (!get_char (uc, &point))
     951              :                 break;
     952           12 :               if (ISDIGIT (uc))
     953              :                 {
     954            8 :                   exponent *= 10;
     955            8 :                   exponent += uc -'0';
     956            8 :                   had_exponent_digit = true;
     957            8 :                   out->range.m_end = point;
     958            8 :                   continue;
     959              :                 }
     960              :               else
     961              :                 {
     962            4 :                   unget_char ();
     963            4 :                   break;
     964              :                 }
     965            8 :             }
     966           16 :           if (!had_exponent_digit)
     967              :             {
     968            0 :               out->id = TOK_ERROR;
     969            0 :               out->range.m_start = point;
     970            0 :               out->range.m_start = point;
     971            0 :               out->u.string = xstrdup ("expected digit within exponent");
     972            0 :               return;
     973              :             }
     974           16 :           if (negate_exponent)
     975            4 :             exponent = -exponent;
     976           16 :           value = value * pow (10, exponent);
     977              :         }
     978              :       else
     979          156 :         unget_char ();
     980              :     }
     981              : 
     982          184 :   if (negate)
     983           12 :     value = -value;
     984              : 
     985          184 :   if (value == (long)value)
     986              :     {
     987          168 :       out->id = TOK_INTEGER_NUMBER;
     988          168 :       out->u.integer_number = value;
     989              :     }
     990              :   else
     991              :     {
     992           16 :       out->id = TOK_FLOAT_NUMBER;
     993           16 :       out->u.float_number = value;
     994              :     }
     995              : }
     996              : 
     997              : /* Determine if the next characters to be lexed match SUFFIX.
     998              :    SUFFIX must be pure ASCII and not contain newlines.
     999              :    If so, consume the characters and return true.
    1000              :    Otherwise, return false.  */
    1001              : 
    1002              : bool
    1003           32 : lexer::rest_of_literal (token *out, const char *suffix)
    1004              : {
    1005           32 :   int suffix_idx = 0;
    1006           32 :   int buf_idx = m_next_char_idx;
    1007          216 :   while (1)
    1008              :     {
    1009          124 :       if (suffix[suffix_idx] == '\0')
    1010              :         {
    1011           28 :           m_next_char_idx += suffix_idx;
    1012           28 :           m_next_char_column += suffix_idx;
    1013           28 :           out->range.m_end.m_unichar_idx += suffix_idx;
    1014           28 :           out->range.m_end.m_column += suffix_idx;
    1015           28 :           return true;
    1016              :         }
    1017          192 :       if (buf_idx >= (int)m_buffer.length ())
    1018              :         return false;
    1019              :       /* This assumes that suffix is ASCII.  */
    1020           96 :       if (m_buffer[buf_idx] != (unichar)suffix[suffix_idx])
    1021              :         return false;
    1022           92 :       buf_idx++;
    1023           92 :       suffix_idx++;
    1024              :     }
    1025              : }
    1026              : 
    1027              : /* Create a new error instance for MSG, using the location of the next
    1028              :    character for the location of the error.  */
    1029              : 
    1030              : std::unique_ptr<error>
    1031            0 : lexer::make_error (const char *msg)
    1032              : {
    1033            0 :   location_map::point p;
    1034            0 :   p.m_unichar_idx = m_next_char_idx;
    1035            0 :   p.m_line = m_next_char_line;
    1036            0 :   p.m_column = m_next_char_column;
    1037            0 :   location_map::range r;
    1038            0 :   r.m_start = p;
    1039            0 :   r.m_end = p;
    1040            0 :   return std::make_unique<error> (r, xstrdup (msg));
    1041              : }
    1042              : 
    1043              : /* parser's ctor.  */
    1044              : 
    1045          100 : parser::parser (location_map *out_loc_map,
    1046              :                 bool support_comments)
    1047          100 : : m_lexer (support_comments), m_loc_map (out_loc_map)
    1048              : {
    1049            0 : }
    1050              : 
    1051              : /* parser's dtor.  */
    1052              : 
    1053          100 : parser::~parser ()
    1054              : {
    1055          100 :   if (m_loc_map)
    1056           96 :     m_loc_map->on_finished_parsing ();
    1057          100 : }
    1058              : 
    1059              : /* Add LENGTH bytes of UTF-8 encoded text from UTF8_BUF to this parser's
    1060              :    lexer's buffer.  */
    1061              : 
    1062              : std::unique_ptr<error>
    1063          100 : parser::add_utf8 (size_t length, const char *utf8_buf)
    1064              : {
    1065            0 :   return m_lexer.add_utf8 (length, utf8_buf);
    1066              : }
    1067              : 
    1068              : /* Parse a JSON value (object, array, number, string, or literal).
    1069              :    (ECMA-404 section 5; RFC 7159 section 3).  */
    1070              : 
    1071              : parser_result_t
    1072          248 : parser::parse_value (int depth)
    1073              : {
    1074          248 :   const token *tok = m_lexer.peek ();
    1075              : 
    1076              :   /* Avoid stack overflow with deeply-nested inputs; RFC 7159 section 9
    1077              :      states: "An implementation may set limits on the maximum depth
    1078              :      of nesting.".
    1079              : 
    1080              :      Ideally we'd avoid this limit (e.g. by rewriting parse_value,
    1081              :      parse_object, and parse_array into a single function with a vec of
    1082              :      state).  */
    1083          248 :   const int MAX_DEPTH = 100;
    1084          248 :   if (depth >= MAX_DEPTH)
    1085            0 :     return error_at (tok->range, "maximum nesting depth exceeded: %i",
    1086            0 :                      MAX_DEPTH);
    1087              : 
    1088          248 :   switch (tok->id)
    1089              :     {
    1090           24 :     case TOK_OPEN_CURLY:
    1091           24 :       return parse_object (depth);
    1092              : 
    1093           36 :     case TOK_STRING:
    1094           36 :       {
    1095           36 :         auto val = std::make_unique<string> (tok->u.string);
    1096           36 :         m_lexer.consume ();
    1097           36 :         maybe_record_range (val.get (), tok->range);
    1098           36 :         return parser_result_t (std::move (val));
    1099           36 :       }
    1100              : 
    1101           20 :     case TOK_OPEN_SQUARE:
    1102           20 :       return parse_array (depth);
    1103              : 
    1104           12 :     case TOK_FLOAT_NUMBER:
    1105           12 :       {
    1106           12 :         auto val = std::make_unique<float_number> (tok->u.float_number);
    1107           12 :         m_lexer.consume ();
    1108           12 :         maybe_record_range (val.get (), tok->range);
    1109           12 :         return parser_result_t (std::move (val));
    1110           12 :       }
    1111              : 
    1112          128 :     case TOK_INTEGER_NUMBER:
    1113          128 :       {
    1114          128 :         auto val = std::make_unique<integer_number> (tok->u.integer_number);
    1115          128 :         m_lexer.consume ();
    1116          128 :         maybe_record_range (val.get (), tok->range);
    1117          128 :         return parser_result_t (std::move (val));
    1118          128 :       }
    1119              : 
    1120            4 :     case TOK_TRUE:
    1121            4 :       {
    1122            4 :         auto val = std::make_unique<literal> (JSON_TRUE);
    1123            4 :         m_lexer.consume ();
    1124            4 :         maybe_record_range (val.get (), tok->range);
    1125            4 :         return parser_result_t (std::move (val));
    1126            4 :       }
    1127              : 
    1128            4 :     case TOK_FALSE:
    1129            4 :       {
    1130            4 :         auto val = std::make_unique<literal> (JSON_FALSE);
    1131            4 :         m_lexer.consume ();
    1132            4 :         maybe_record_range (val.get (), tok->range);
    1133            4 :         return parser_result_t (std::move (val));
    1134            4 :       }
    1135              : 
    1136            8 :     case TOK_NULL:
    1137            8 :       {
    1138            8 :         auto val = std::make_unique<literal> (JSON_NULL);
    1139            8 :         m_lexer.consume ();
    1140            8 :         maybe_record_range (val.get (), tok->range);
    1141            8 :         return parser_result_t (std::move (val));
    1142            8 :       }
    1143              : 
    1144            8 :     case TOK_ERROR:
    1145            8 :       return error_at (tok->range, "invalid JSON token: %s", tok->u.string);
    1146              : 
    1147            4 :     default:
    1148            4 :       return error_at (tok->range, "expected a JSON value but got %s",
    1149            4 :                        token_id_name[tok->id]);
    1150              :     }
    1151              : }
    1152              : 
    1153              : /* Parse a JSON object.
    1154              :    (ECMA-404 section 6; RFC 7159 section 4).  */
    1155              : 
    1156              : parser_result_t
    1157           24 : parser::parse_object (int depth)
    1158              : {
    1159           48 :   location_map::point start = get_next_token_start ();
    1160              : 
    1161           24 :   require (TOK_OPEN_CURLY);
    1162              : 
    1163           24 :   auto obj = std::make_unique<object> ();
    1164              : 
    1165           24 :   const token *tok = m_lexer.peek ();
    1166           24 :   if (tok->id == TOK_CLOSE_CURLY)
    1167              :     {
    1168            8 :       location_map::point end = get_next_token_end ();
    1169            4 :       maybe_record_range (obj.get (), start, end);
    1170            4 :       if (auto err = require (TOK_CLOSE_CURLY))
    1171            4 :         return parser_result_t (std::move (err));
    1172            4 :       return parser_result_t (std::move (obj));
    1173              :     }
    1174           20 :   if (tok->id != TOK_STRING)
    1175            0 :     return error_at (tok->range,
    1176              :                      "expected string for object key after '{'; got %s",
    1177            0 :                      token_id_name[tok->id]);
    1178           56 :   while (true)
    1179              :     {
    1180           76 :       tok = m_lexer.peek ();
    1181           76 :       if (tok->id != TOK_STRING)
    1182            0 :         return error_at (tok->range,
    1183              :                          "expected string for object key after ','; got %s",
    1184            0 :                          token_id_name[tok->id]);
    1185           76 :       label_text key = label_text::take (xstrdup (tok->u.string));
    1186           76 :       m_lexer.consume ();
    1187              : 
    1188           76 :       if (auto err = require (TOK_COLON))
    1189           76 :         return parser_result_t (std::move (err));
    1190              : 
    1191           76 :       parser_result_t r = parse_value (depth + 1);
    1192           76 :       if (r.m_err)
    1193            0 :         return r;
    1194           76 :       if (!r.m_val)
    1195            0 :         return parser_result_t (std::move (obj));
    1196              : 
    1197              :       /* We don't enforce uniqueness for keys.  */
    1198           76 :       obj->set (key.get (), std::move (r.m_val));
    1199              : 
    1200          152 :       location_map::point end = get_next_token_end ();
    1201           76 :       result<enum token_id, std::unique_ptr<error>> result
    1202           76 :         (require_one_of (TOK_COMMA, TOK_CLOSE_CURLY));
    1203           76 :       if (result.m_err)
    1204            4 :         return parser_result_t (std::move (result.m_err));
    1205           72 :       if (result.m_val == TOK_COMMA)
    1206           56 :         continue;
    1207              :       else
    1208              :         {
    1209              :           /* TOK_CLOSE_CURLY.  */
    1210           16 :           maybe_record_range (obj.get (), start, end);
    1211           16 :           return parser_result_t (std::move (obj));
    1212              :         }
    1213          152 :     }
    1214           24 : }
    1215              : 
    1216              : /* Parse a JSON array.
    1217              :    (ECMA-404 section 7; RFC 7159 section 5).  */
    1218              : 
    1219              : parser_result_t
    1220           20 : parser::parse_array (int depth)
    1221              : {
    1222           40 :   location_map::point start = get_next_token_start ();
    1223           20 :   if (auto err = require (TOK_OPEN_SQUARE))
    1224           20 :     return parser_result_t (std::move (err));
    1225              : 
    1226           20 :   auto arr = std::make_unique<array> ();
    1227              : 
    1228           20 :   const token *tok = m_lexer.peek ();
    1229           20 :   if (tok->id == TOK_CLOSE_SQUARE)
    1230              :     {
    1231            0 :       location_map::point end = get_next_token_end ();
    1232            0 :       maybe_record_range (arr.get (), start, end);
    1233            0 :       m_lexer.consume ();
    1234            0 :       return parser_result_t (std::move (arr));
    1235              :     }
    1236              : 
    1237          124 :   while (true)
    1238              :     {
    1239           72 :       parser_result_t r = parse_value (depth + 1);
    1240           72 :       if (r.m_err)
    1241            0 :         return r;
    1242              : 
    1243           72 :       arr->append (std::move (r.m_val));
    1244              : 
    1245          144 :       location_map::point end = get_next_token_end ();
    1246           72 :       result<enum token_id, std::unique_ptr<error>> result
    1247           72 :         (require_one_of (TOK_COMMA, TOK_CLOSE_SQUARE));
    1248           72 :       if (result.m_err)
    1249            4 :         return parser_result_t (std::move (result.m_err));
    1250           68 :       if (result.m_val == TOK_COMMA)
    1251           52 :         continue;
    1252              :       else
    1253              :         {
    1254              :           /* TOK_CLOSE_SQUARE.  */
    1255           16 :           maybe_record_range (arr.get (), start, end);
    1256           16 :           return parser_result_t (std::move (arr));
    1257              :         }
    1258          144 :     }
    1259           20 : }
    1260              : 
    1261              : /* Get the start point of the next token.  */
    1262              : 
    1263              : location_map::point
    1264           44 : parser::get_next_token_start ()
    1265              : {
    1266           44 :   const token *tok = m_lexer.peek ();
    1267           44 :   return tok->range.m_start;
    1268              : }
    1269              : 
    1270              : /* Get the end point of the next token.  */
    1271              : 
    1272              : location_map::point
    1273          152 : parser::get_next_token_end ()
    1274              : {
    1275          152 :   const token *tok = m_lexer.peek ();
    1276          152 :   return tok->range.m_end;
    1277              : }
    1278              : 
    1279              : /* Require an EOF, or fail if there is surplus input.  */
    1280              : 
    1281              : std::unique_ptr<error>
    1282           80 : parser::require_eof ()
    1283              : {
    1284            0 :   return require (TOK_EOF);
    1285              : }
    1286              : 
    1287              : /* Consume the next token, issuing an error if it is not of kind TOK_ID.  */
    1288              : 
    1289              : std::unique_ptr<error>
    1290          204 : parser::require (enum token_id tok_id)
    1291              : {
    1292          204 :   const token *tok = m_lexer.peek ();
    1293          204 :   if (tok->id != tok_id)
    1294              :     {
    1295            0 :       if (tok->id == TOK_ERROR)
    1296            0 :         return error_at (tok->range,
    1297              :                          "expected %s; got bad token: %s",
    1298            0 :                          token_id_name[tok_id], tok->u.string);
    1299              :       else
    1300            0 :         return error_at (tok->range,
    1301            0 :                          "expected %s; got %s", token_id_name[tok_id],
    1302            0 :                          token_id_name[tok->id]);
    1303              :     }
    1304          204 :   m_lexer.consume ();
    1305          204 :   return nullptr;
    1306              : }
    1307              : 
    1308              : /* Consume the next token, issuing an error if it is not of
    1309              :    kind TOK_ID_A or TOK_ID_B.
    1310              :    Return which kind it was.  */
    1311              : 
    1312              : result<enum token_id, std::unique_ptr<error>>
    1313          148 : parser::require_one_of (enum token_id tok_id_a, enum token_id tok_id_b)
    1314              : {
    1315          148 :   const token *tok = m_lexer.peek ();
    1316          148 :   if ((tok->id != tok_id_a)
    1317           40 :       && (tok->id != tok_id_b))
    1318              :     {
    1319            8 :       if (tok->id == TOK_ERROR)
    1320            0 :         return error_at (tok->range, "expected %s or %s; got bad token: %s",
    1321            0 :                          token_id_name[tok_id_a], token_id_name[tok_id_b],
    1322            0 :                          tok->u.string);
    1323              :       else
    1324            8 :         return error_at (tok->range, "expected %s or %s; got %s",
    1325            8 :                          token_id_name[tok_id_a], token_id_name[tok_id_b],
    1326            8 :                          token_id_name[tok->id]);
    1327              :     }
    1328          140 :   enum token_id id = tok->id;
    1329          140 :   m_lexer.consume ();
    1330          140 :   return result<enum token_id, std::unique_ptr<error>> (id);
    1331              : }
    1332              : 
    1333              : /* Generate a parsing error.  */
    1334              : 
    1335              : std::unique_ptr<error>
    1336           20 : parser::error_at (const location_map::range &r, const char *fmt, ...)
    1337              : {
    1338           20 :   va_list ap;
    1339           20 :   va_start (ap, fmt);
    1340           20 :   char *formatted_msg = xvasprintf (fmt, ap);
    1341           20 :   va_end (ap);
    1342              : 
    1343           20 :   return std::make_unique<error> (r, formatted_msg);
    1344              : }
    1345              : 
    1346              : /* Record that JV has range R within the input file.  */
    1347              : 
    1348              : void
    1349          192 : parser::maybe_record_range (json::value *jv, const location_map::range &r)
    1350              : {
    1351          192 :   if (m_loc_map)
    1352          148 :     m_loc_map->record_range_for_value (jv, r);
    1353          192 : }
    1354              : 
    1355              : /* Record that JV has range START to END within the input file.  */
    1356              : 
    1357              : void
    1358           36 : parser::maybe_record_range (json::value *jv,
    1359              :                             const location_map::point &start,
    1360              :                             const location_map::point &end)
    1361              : {
    1362           36 :   if (m_loc_map)
    1363              :     {
    1364           28 :       location_map::range r;
    1365           28 :       r.m_start = start;
    1366           28 :       r.m_end = end;
    1367           28 :       m_loc_map->record_range_for_value (jv, r);
    1368              :     }
    1369           36 : }
    1370              : 
    1371              : /* Attempt to parse the UTF-8 encoded buffer at UTF8_BUF
    1372              :    of the given LENGTH.
    1373              :    If ALLOW_COMMENTS is true, then allow C and C++ style-comments in the
    1374              :    buffer, as an extension to JSON, otherwise forbid them.
    1375              :    If successful, return an json::value in the result.
    1376              :    if there was a problem, return a json::error in the result.
    1377              :    If OUT_LOC_MAP is non-NULL, notify *OUT_LOC_MAP about
    1378              :    source locations of nodes seen during parsing.  */
    1379              : 
    1380              : parser_result_t
    1381          100 : json::parse_utf8_string (size_t length,
    1382              :                          const char *utf8_buf,
    1383              :                          bool allow_comments,
    1384              :                          location_map *out_loc_map)
    1385              : {
    1386          100 :   parser p (out_loc_map, allow_comments);
    1387          100 :   if (auto err = p.add_utf8 (length, utf8_buf))
    1388          100 :     return parser_result_t (std::move (err));
    1389          100 :   parser_result_t r = p.parse_value (0);
    1390          100 :   if (r.m_err)
    1391           20 :     return r;
    1392           80 :   if (auto err = p.require_eof ())
    1393           80 :     return parser_result_t (std::move (err));
    1394           80 :   return r;
    1395          100 : }
    1396              : 
    1397              : /* Attempt to parse the nil-terminated UTF-8 encoded buffer at
    1398              :    UTF8_BUF.
    1399              :    If ALLOW_COMMENTS is true, then allow C and C++ style-comments in the
    1400              :    buffer, as an extension to JSON, otherwise forbid them.
    1401              :    If successful, return a non-NULL json::value *.
    1402              :    if there was a problem, return NULL and write an error
    1403              :    message to err_out, which must be deleted by the caller.
    1404              :    If OUT_LOC_MAP is non-NULL, notify *OUT_LOC_MAP about
    1405              :    source locations of nodes seen during parsing.  */
    1406              : 
    1407              : json::parser_result_t
    1408          100 : json::parse_utf8_string (const char *utf8,
    1409              :                          bool allow_comments,
    1410              :                          location_map *out_loc_map)
    1411              : {
    1412          100 :   return parse_utf8_string (strlen (utf8), utf8, allow_comments,
    1413          100 :                             out_loc_map);
    1414              : }
    1415              : 
    1416              : 
    1417              : #if CHECKING_P
    1418              : 
    1419              : namespace selftest {
    1420              : 
    1421              : /* Selftests.  */
    1422              : 
    1423              : /* Implementation detail of ASSERT_RANGE_EQ.  */
    1424              : 
    1425              : static void
    1426          424 : assert_point_eq (const location &loc,
    1427              :                  const location_map::point &actual_point,
    1428              :                  size_t exp_unichar_idx, int exp_line, int exp_column)
    1429              : {
    1430          424 :   ASSERT_EQ_AT (loc, actual_point.m_unichar_idx, exp_unichar_idx);
    1431          424 :   ASSERT_EQ_AT (loc, actual_point.m_line, exp_line);
    1432          424 :   ASSERT_EQ_AT (loc, actual_point.m_column, exp_column);
    1433          424 : }
    1434              : 
    1435              : /* Implementation detail of ASSERT_RANGE_EQ.  */
    1436              : 
    1437              : static void
    1438          212 : assert_range_eq (const location &loc,
    1439              :                  const location_map::range &actual_range,
    1440              :                  /* Expected location.  */
    1441              :                  size_t start_unichar_idx, int start_line, int start_column,
    1442              :                  size_t end_unichar_idx, int end_line, int end_column)
    1443              : {
    1444          212 :   assert_point_eq (loc, actual_range.m_start,
    1445              :                    start_unichar_idx, start_line, start_column);
    1446          212 :   assert_point_eq (loc, actual_range.m_end,
    1447              :                    end_unichar_idx, end_line, end_column);
    1448          212 : }
    1449              : 
    1450              : /* Assert that ACTUAL_RANGE starts at
    1451              :    (START_UNICHAR_IDX, START_LINE, START_COLUMN)
    1452              :    and ends at (END_UNICHAR_IDX, END_LINE, END_COLUMN).  */
    1453              : 
    1454              : #define ASSERT_RANGE_EQ(ACTUAL_RANGE, \
    1455              :                         START_UNICHAR_IDX, START_LINE, START_COLUMN,    \
    1456              :                         END_UNICHAR_IDX, END_LINE, END_COLUMN)          \
    1457              :   assert_range_eq ((SELFTEST_LOCATION), (ACTUAL_RANGE), \
    1458              :                    (START_UNICHAR_IDX), (START_LINE), (START_COLUMN),   \
    1459              :                    (END_UNICHAR_IDX), (END_LINE), (END_COLUMN))
    1460              : 
    1461              : /* Implementation detail of ASSERT_ERR_EQ.  */
    1462              : 
    1463              : static void
    1464           16 : assert_err_eq (const location &loc,
    1465              :                const json::error *actual_err,
    1466              :                /* Expected location.  */
    1467              :                size_t start_unichar_idx, int start_line, int start_column,
    1468              :                size_t end_unichar_idx, int end_line, int end_column,
    1469              :                const char *expected_msg)
    1470              : {
    1471           16 :   ASSERT_TRUE_AT (loc, actual_err);
    1472           16 :   const location_map::range &actual_range = actual_err->get_range ();
    1473           16 :   ASSERT_EQ_AT (loc, actual_range.m_start.m_unichar_idx, start_unichar_idx);
    1474           16 :   ASSERT_EQ_AT (loc, actual_range.m_start.m_line, start_line);
    1475           16 :   ASSERT_EQ_AT (loc, actual_range.m_start.m_column, start_column);
    1476           16 :   ASSERT_EQ_AT (loc, actual_range.m_end.m_unichar_idx, end_unichar_idx);
    1477           16 :   ASSERT_EQ_AT (loc, actual_range.m_end.m_line, end_line);
    1478           16 :   ASSERT_EQ_AT (loc, actual_range.m_end.m_column, end_column);
    1479           16 :   ASSERT_STREQ_AT (loc, actual_err->get_msg (), expected_msg);
    1480           16 : }
    1481              : 
    1482              : /* Assert that ACTUAL_ERR is a non-NULL json::error *,
    1483              :    with message EXPECTED_MSG, and that its location starts
    1484              :    at (START_UNICHAR_IDX, START_LINE, START_COLUMN)
    1485              :    and ends at (END_UNICHAR_IDX, END_LINE, END_COLUMN).  */
    1486              : 
    1487              : #define ASSERT_ERR_EQ(ACTUAL_ERR, \
    1488              :                       START_UNICHAR_IDX, START_LINE, START_COLUMN,      \
    1489              :                       END_UNICHAR_IDX, END_LINE, END_COLUMN,    \
    1490              :                       EXPECTED_MSG)                 \
    1491              :   assert_err_eq ((SELFTEST_LOCATION), (ACTUAL_ERR), \
    1492              :                  (START_UNICHAR_IDX), (START_LINE), (START_COLUMN),     \
    1493              :                  (END_UNICHAR_IDX), (END_LINE), (END_COLUMN),   \
    1494              :                  (EXPECTED_MSG))
    1495              : 
    1496              : /* Implementation detail of ASSERT_JSON_POINTER_EQ.  */
    1497              : 
    1498              : static void
    1499           28 : assert_json_pointer_eq (const location &loc,
    1500              :                         const json::value *jv,
    1501              :                         const char *expected_str)
    1502              : {
    1503           28 :   pretty_printer pp;
    1504           28 :   ASSERT_TRUE_AT (loc, jv);
    1505           28 :   jv->print_pointer (&pp);
    1506           28 :   ASSERT_STREQ_AT (loc, pp_formatted_text (&pp), expected_str);
    1507           28 : }
    1508              : 
    1509              : /* Assert that JV is a non-NULL json::value *, and that
    1510              :    jv->print_pointer prints EXPECTED_STR.  */
    1511              : 
    1512              : #define ASSERT_JSON_POINTER_EQ(JV, EXPECTED_STR) \
    1513              :   assert_json_pointer_eq ((SELFTEST_LOCATION), (JV), (EXPECTED_STR))
    1514              : 
    1515              : /* Verify that the JSON lexer works as expected.  */
    1516              : 
    1517              : static void
    1518            4 : test_lexer ()
    1519              : {
    1520            4 :   lexer l (false);
    1521            4 :   const char *str
    1522              :     /*  0         1         2         3         4         .  */
    1523              :     /*  01234567890123456789012345678901234567890123456789.  */
    1524              :     = ("    1066   -1  \n"
    1525              :        "    -273.15 1e6\n"
    1526              :        "  [   ] null   true  false  {  }  \"foo\" \n");
    1527            4 :   auto err = l.add_utf8 (strlen (str), str);
    1528            4 :   ASSERT_EQ (err, nullptr);
    1529              : 
    1530              :   /* Line 1.  */
    1531            4 :   {
    1532            4 :     const size_t line_offset = 0;
    1533              : 
    1534              :     /* Expect token: "1066" in columns 4-7.  */
    1535            4 :     {
    1536            4 :       const token *tok = l.peek ();
    1537            4 :       ASSERT_EQ (tok->id, TOK_INTEGER_NUMBER);
    1538            4 :       ASSERT_EQ (tok->u.integer_number, 1066);
    1539            4 :       ASSERT_RANGE_EQ (tok->range,
    1540              :                        line_offset + 4, 1, 4,
    1541              :                        line_offset + 7, 1, 7);
    1542            4 :       l.consume ();
    1543              :     }
    1544              :     /* Expect token: "-1" in columns 11-12.  */
    1545            4 :     {
    1546            4 :       const token *tok = l.peek ();
    1547            4 :       ASSERT_EQ (tok->id, TOK_INTEGER_NUMBER);
    1548            4 :       ASSERT_EQ (tok->u.integer_number, -1);
    1549            4 :       ASSERT_RANGE_EQ (tok->range,
    1550              :                        line_offset + 11, 1, 11,
    1551              :                        line_offset + 12, 1, 12);
    1552            4 :       l.consume ();
    1553              :     }
    1554              :   }
    1555              : 
    1556              :   /* Line 2.  */
    1557            4 :   {
    1558            4 :     const size_t line_offset = 16;
    1559              : 
    1560              :     /* Expect token: "-273.15" in columns 4-10.  */
    1561            4 :     {
    1562            4 :       const token *tok = l.peek ();
    1563            4 :       ASSERT_EQ (tok->id, TOK_FLOAT_NUMBER);
    1564            4 :       ASSERT_EQ (int(tok->u.float_number), int(-273.15));
    1565            4 :       ASSERT_RANGE_EQ (tok->range,
    1566              :                        line_offset + 4, 2, 4,
    1567              :                        line_offset + 10, 2, 10);
    1568            4 :       l.consume ();
    1569              :     }
    1570              :     /* Expect token: "1e6" in columns 12-14.  */
    1571            4 :     {
    1572            4 :       const token *tok = l.peek ();
    1573            4 :       ASSERT_EQ (tok->id, TOK_INTEGER_NUMBER);
    1574            4 :       ASSERT_EQ (tok->u.integer_number, 1000000);
    1575            4 :       ASSERT_RANGE_EQ (tok->range,
    1576              :                        line_offset + 12, 2, 12,
    1577              :                        line_offset + 14, 2, 14);
    1578            4 :       l.consume ();
    1579              :     }
    1580              :   }
    1581              : 
    1582              :   /* Line 3.  */
    1583            4 :   {
    1584            4 :     const size_t line_offset = 32;
    1585              : 
    1586              :     /* Expect token: "[".  */
    1587            4 :     {
    1588            4 :       const token *tok = l.peek ();
    1589            4 :       ASSERT_EQ (tok->id, TOK_OPEN_SQUARE);
    1590            4 :       ASSERT_RANGE_EQ (tok->range,
    1591              :                        line_offset + 2, 3, 2,
    1592              :                        line_offset + 2, 3, 2);
    1593            4 :       l.consume ();
    1594              :     }
    1595              :     /* Expect token: "]".  */
    1596            4 :     {
    1597            4 :       const token *tok = l.peek ();
    1598            4 :       ASSERT_EQ (tok->id, TOK_CLOSE_SQUARE);
    1599            4 :       ASSERT_RANGE_EQ (tok->range,
    1600              :                        line_offset + 6, 3, 6,
    1601              :                        line_offset + 6, 3, 6);
    1602            4 :       l.consume ();
    1603              :     }
    1604              :     /* Expect token: "null".  */
    1605            4 :     {
    1606            4 :       const token *tok = l.peek ();
    1607            4 :       ASSERT_EQ (tok->id, TOK_NULL);
    1608            4 :       ASSERT_RANGE_EQ (tok->range,
    1609              :                        line_offset + 8, 3, 8,
    1610              :                        line_offset + 11, 3, 11);
    1611            4 :       l.consume ();
    1612              :     }
    1613              :     /* Expect token: "true".  */
    1614            4 :     {
    1615            4 :       const token *tok = l.peek ();
    1616            4 :       ASSERT_EQ (tok->id, TOK_TRUE);
    1617            4 :       ASSERT_RANGE_EQ (tok->range,
    1618              :                        line_offset + 15, 3, 15,
    1619              :                        line_offset + 18, 3, 18);
    1620            4 :       l.consume ();
    1621              :     }
    1622              :     /* Expect token: "false".  */
    1623            4 :     {
    1624            4 :       const token *tok = l.peek ();
    1625            4 :       ASSERT_EQ (tok->id, TOK_FALSE);
    1626            4 :       ASSERT_RANGE_EQ (tok->range,
    1627              :                        line_offset + 21, 3, 21,
    1628              :                        line_offset + 25, 3, 25);
    1629            4 :       l.consume ();
    1630              :     }
    1631              :     /* Expect token: "{".  */
    1632            4 :     {
    1633            4 :       const token *tok = l.peek ();
    1634            4 :       ASSERT_EQ (tok->id, TOK_OPEN_CURLY);
    1635            4 :       ASSERT_RANGE_EQ (tok->range,
    1636              :                        line_offset + 28, 3, 28,
    1637              :                        line_offset + 28, 3, 28);
    1638            4 :       l.consume ();
    1639              :     }
    1640              :     /* Expect token: "}".  */
    1641            4 :     {
    1642            4 :       const token *tok = l.peek ();
    1643            4 :       ASSERT_EQ (tok->id, TOK_CLOSE_CURLY);
    1644            4 :       ASSERT_RANGE_EQ (tok->range,
    1645              :                        line_offset + 31, 3, 31,
    1646              :                        line_offset + 31, 3, 31);
    1647            4 :       l.consume ();
    1648              :     }
    1649              :     /* Expect token: "\"foo\"".  */
    1650            4 :     {
    1651            4 :       const token *tok = l.peek ();
    1652            4 :       ASSERT_EQ (tok->id, TOK_STRING);
    1653            4 :       ASSERT_RANGE_EQ (tok->range,
    1654              :                        line_offset + 34, 3, 34,
    1655              :                        line_offset + 38, 3, 38);
    1656            4 :       l.consume ();
    1657              :     }
    1658              :   }
    1659            4 : }
    1660              : 
    1661              : /* Verify that the JSON lexer complains about single-line comments
    1662              :    when comments are disabled.  */
    1663              : 
    1664              : static void
    1665            4 : test_lexing_unsupported_single_line_comment ()
    1666              : {
    1667            4 :   lexer l (false);
    1668            4 :   const char *str
    1669              :     /*  0         1         2         3         4         .  */
    1670              :     /*  01234567890123456789012345678901234567890123456789.  */
    1671              :     = ("    1066   // Hello world\n");
    1672            4 :   auto err = l.add_utf8 (strlen (str), str);
    1673            4 :   ASSERT_EQ (err, nullptr);
    1674              : 
    1675              :   /* Line 1.  */
    1676            4 :   {
    1677            4 :     const size_t line_offset = 0;
    1678            4 :     const int line_1 = 1;
    1679              : 
    1680              :     /* Expect token: "1066" in columns 4-7.  */
    1681            4 :     {
    1682            4 :       const token *tok = l.peek ();
    1683            4 :       ASSERT_EQ (tok->id, TOK_INTEGER_NUMBER);
    1684            4 :       ASSERT_EQ (tok->u.integer_number, 1066);
    1685            4 :       ASSERT_RANGE_EQ (tok->range,
    1686              :                        line_offset + 4, line_1, 4,
    1687              :                        line_offset + 7, line_1, 7);
    1688            4 :       l.consume ();
    1689              :     }
    1690              : 
    1691              :     /* Expect error.  */
    1692            4 :     {
    1693            4 :       const token *tok = l.peek ();
    1694            4 :       ASSERT_EQ (tok->id, TOK_ERROR);
    1695            4 :       ASSERT_STREQ (tok->u.string, "unexpected character: '/'");
    1696            4 :       ASSERT_RANGE_EQ (tok->range,
    1697              :                        line_offset + 11, line_1, 11,
    1698              :                        line_offset + 11, line_1, 11);
    1699            4 :       l.consume ();
    1700              :     }
    1701              :   }
    1702            4 : }
    1703              : 
    1704              : /* Verify that the JSON lexer complains about multiline comments
    1705              :    when comments are disabled.  */
    1706              : 
    1707              : static void
    1708            4 : test_lexing_unsupported_multiline_comment ()
    1709              : {
    1710            4 :   lexer l (false);
    1711            4 :   const char *str
    1712              :     /*  0         1         2         3         4         .  */
    1713              :     /*  01234567890123456789012345678901234567890123456789.  */
    1714              :     = ("    1066   /* Hello world\n"
    1715              :        " continuation of comment\n"
    1716              :        " end of comment */  42\n");
    1717            4 :   auto err = l.add_utf8 (strlen (str), str);
    1718            4 :   ASSERT_EQ (err, nullptr);
    1719              : 
    1720              :   /* Line 1.  */
    1721            4 :   {
    1722            4 :     const size_t line_offset = 0;
    1723            4 :     const int line_1 = 1;
    1724              : 
    1725              :     /* Expect token: "1066" in line 1, columns 4-7.  */
    1726            4 :     {
    1727            4 :       const token *tok = l.peek ();
    1728            4 :       ASSERT_EQ (tok->id, TOK_INTEGER_NUMBER);
    1729            4 :       ASSERT_EQ (tok->u.integer_number, 1066);
    1730            4 :       ASSERT_RANGE_EQ (tok->range,
    1731              :                        line_offset + 4, line_1, 4,
    1732              :                        line_offset + 7, line_1, 7);
    1733            4 :       l.consume ();
    1734              :     }
    1735              : 
    1736              :     /* Expect error.  */
    1737            4 :     {
    1738            4 :       const token *tok = l.peek ();
    1739            4 :       ASSERT_EQ (tok->id, TOK_ERROR);
    1740            4 :       ASSERT_STREQ (tok->u.string, "unexpected character: '/'");
    1741            4 :       ASSERT_RANGE_EQ (tok->range,
    1742              :                        line_offset + 11, line_1, 11,
    1743              :                        line_offset + 11, line_1, 11);
    1744            4 :       l.consume ();
    1745              :     }
    1746              :   }
    1747            4 : }
    1748              : 
    1749              : /* Verify that the JSON lexer handles single-line comments
    1750              :    when comments are enabled.  */
    1751              : 
    1752              : static void
    1753            4 : test_lexing_supported_single_line_comment ()
    1754              : {
    1755            4 :   lexer l (true);
    1756            4 :   const char *str
    1757              :     /*  0         1         2         3         4         .  */
    1758              :     /*  01234567890123456789012345678901234567890123456789.  */
    1759              :     = ("    1066   // Hello world\n"
    1760              :        "     42   // etc\n");
    1761            4 :   auto err = l.add_utf8 (strlen (str), str);
    1762            4 :   ASSERT_EQ (err, nullptr);
    1763              : 
    1764            4 :   const size_t line_1_offset = 0;
    1765            4 :   const size_t line_2_offset = 26;
    1766            4 :   const size_t line_3_offset = line_2_offset + 17;
    1767              : 
    1768              :   /* Expect token: "1066" in line 1, columns 4-7.  */
    1769            4 :   {
    1770            4 :     const int line_1 = 1;
    1771            4 :     const token *tok = l.peek ();
    1772            4 :     ASSERT_EQ (tok->id, TOK_INTEGER_NUMBER);
    1773            4 :     ASSERT_EQ (tok->u.integer_number, 1066);
    1774            4 :     ASSERT_RANGE_EQ (tok->range,
    1775              :                      line_1_offset + 4, line_1, 4,
    1776              :                      line_1_offset + 7, line_1, 7);
    1777            4 :     l.consume ();
    1778              :   }
    1779              : 
    1780              :   /* Expect token: "42" in line 2, columns 5-6.  */
    1781            4 :   {
    1782            4 :     const int line_2 = 2;
    1783            4 :     const token *tok = l.peek ();
    1784            4 :     ASSERT_EQ (tok->id, TOK_INTEGER_NUMBER);
    1785            4 :     ASSERT_EQ (tok->u.integer_number, 42);
    1786            4 :     ASSERT_RANGE_EQ (tok->range,
    1787              :                      line_2_offset + 5, line_2, 5,
    1788              :                      line_2_offset + 6, line_2, 6);
    1789            4 :     l.consume ();
    1790              :   }
    1791              : 
    1792              :   /* Expect EOF.  */
    1793            4 :   {
    1794            4 :     const int line_3 = 3;
    1795            4 :     const token *tok = l.peek ();
    1796            4 :     ASSERT_EQ (tok->id, TOK_EOF);
    1797            4 :     ASSERT_RANGE_EQ (tok->range,
    1798              :                      line_3_offset + 0, line_3, 0,
    1799              :                      line_3_offset + 0, line_3, 0);
    1800            4 :     l.consume ();
    1801              :   }
    1802            4 : }
    1803              : 
    1804              : /* Verify that the JSON lexer handles multiline comments
    1805              :    when comments are enabled.  */
    1806              : 
    1807              : static void
    1808            4 : test_lexing_supported_multiline_comment ()
    1809              : {
    1810            4 :   lexer l (true);
    1811            4 :   const char *str
    1812              :     /*  0         1         2         3         4         .  */
    1813              :     /*  01234567890123456789012345678901234567890123456789.  */
    1814              :     = ("    1066   /* Hello world\n"
    1815              :        " continuation of comment\n"
    1816              :        " end of comment */  42\n");
    1817            4 :   auto err = l.add_utf8 (strlen (str), str);
    1818            4 :   ASSERT_EQ (err, nullptr);
    1819              : 
    1820            4 :   const size_t line_1_offset = 0;
    1821            4 :   const size_t line_2_offset = 26;
    1822            4 :   const size_t line_3_offset = line_2_offset + 25;
    1823            4 :   const size_t line_4_offset = line_3_offset + 23;
    1824              : 
    1825              :   /* Expect token: "1066" in line 1, columns 4-7.  */
    1826            4 :   {
    1827            4 :     const int line_1 = 1;
    1828            4 :     const token *tok = l.peek ();
    1829            4 :     ASSERT_EQ (tok->id, TOK_INTEGER_NUMBER);
    1830            4 :     ASSERT_EQ (tok->u.integer_number, 1066);
    1831            4 :     ASSERT_RANGE_EQ (tok->range,
    1832              :                      line_1_offset + 4, line_1, 4,
    1833              :                      line_1_offset + 7, line_1, 7);
    1834            4 :     l.consume ();
    1835              :   }
    1836              : 
    1837              :   /* Expect token: "42" in line 3, columns 20-21.  */
    1838            4 :   {
    1839            4 :     const int line_3 = 3;
    1840            4 :     const token *tok = l.peek ();
    1841            4 :     ASSERT_EQ (tok->id, TOK_INTEGER_NUMBER);
    1842            4 :     ASSERT_EQ (tok->u.integer_number, 42);
    1843            4 :     ASSERT_RANGE_EQ (tok->range,
    1844              :                      line_3_offset + 20, line_3, 20,
    1845              :                      line_3_offset + 21, line_3, 21);
    1846            4 :     l.consume ();
    1847              :   }
    1848              : 
    1849              :   /* Expect EOF.  */
    1850            4 :   {
    1851            4 :     const int line_4 = 4;
    1852            4 :     const token *tok = l.peek ();
    1853            4 :     ASSERT_EQ (tok->id, TOK_EOF);
    1854            4 :     ASSERT_RANGE_EQ (tok->range,
    1855              :                      line_4_offset + 0, line_4, 0,
    1856              :                      line_4_offset + 0, line_4, 0);
    1857            4 :     l.consume ();
    1858              :   }
    1859            4 : }
    1860              : 
    1861              : /* Helper class for writing JSON parsing testcases.
    1862              :    Attempts to parse a string in ctor, and captures the result (either
    1863              :    a json::value or a json::error), and a location map.  */
    1864              : 
    1865              : struct parser_testcase
    1866              : {
    1867              : public:
    1868           96 :   parser_testcase (const char *utf8_string, bool allow_comments = false)
    1869           96 :   : m_loc_map (),
    1870           96 :     m_result (parse_utf8_string (utf8_string, allow_comments, &m_loc_map))
    1871              :   {
    1872           96 :   }
    1873              : 
    1874           96 :   const json::value *get_value () const { return m_result.m_val.get (); }
    1875          100 :   const json::error *get_error () const { return m_result.m_err.get (); }
    1876              : 
    1877              :   const location_map::range *
    1878          124 :   get_range_for_value (const json::value *jv) const
    1879              :   {
    1880          248 :     return m_loc_map.get_range_for_value (jv);
    1881              :   }
    1882              : 
    1883              : private:
    1884              :   /* Concrete implementation of location_map for use in
    1885              :      JSON parsing selftests.  */
    1886              :   class test_location_map : public location_map
    1887              :   {
    1888              :   public:
    1889          176 :     void record_range_for_value (json::value *jv, const range &r) final override
    1890              :     {
    1891          176 :       m_map.put (jv, r);
    1892          176 :     }
    1893              : 
    1894          124 :     range *get_range_for_value (const json::value *jv) const
    1895              :     {
    1896          124 :       return const_cast<hash_map<const json::value *, range> &> (m_map)
    1897          124 :         .get (jv);
    1898              :     }
    1899              : 
    1900              :   private:
    1901              :     hash_map<const json::value *, range> m_map;
    1902              :   };
    1903              : 
    1904              :   test_location_map m_loc_map;
    1905              :   json::parser_result_t m_result;
    1906              : };
    1907              : 
    1908              : /* Verify that parse_utf8_string works as expected.  */
    1909              : 
    1910              : static void
    1911            4 : test_parse_string ()
    1912              : {
    1913            4 :   const int line_1 = 1;
    1914              : 
    1915            4 :   {
    1916            4 :     parser_testcase tc ("\"foo\"");
    1917            4 :     ASSERT_EQ (tc.get_error (), nullptr);
    1918            4 :     const json::value *jv = tc.get_value ();
    1919            4 :     ASSERT_EQ (jv->get_kind (), JSON_STRING);
    1920            4 :     ASSERT_STREQ (as_a <const json::string *> (jv)->get_string (), "foo");
    1921            4 :     ASSERT_JSON_PRINT_EQ (*jv, true, "\"foo\"");
    1922            4 :     auto range = tc.get_range_for_value (jv);
    1923            4 :     ASSERT_TRUE (range);
    1924            4 :     ASSERT_RANGE_EQ (*range,
    1925              :                      0, line_1, 0,
    1926              :                      4, line_1, 4);
    1927            4 :   }
    1928              : 
    1929            4 :   {
    1930            4 :     const char *contains_quotes = "\"before \\\"quoted\\\" after\"";
    1931            4 :     parser_testcase tc (contains_quotes);
    1932            4 :     ASSERT_EQ (tc.get_error (), nullptr);
    1933            4 :     const json::value *jv = tc.get_value ();
    1934            4 :     ASSERT_EQ (jv->get_kind (), JSON_STRING);
    1935            4 :     ASSERT_STREQ (as_a <const json::string *> (jv)->get_string (),
    1936              :                   "before \"quoted\" after");
    1937            4 :     ASSERT_JSON_PRINT_EQ (*jv, true, contains_quotes);
    1938            4 :     auto range = tc.get_range_for_value (jv);
    1939            4 :     ASSERT_TRUE (range);
    1940            4 :     ASSERT_RANGE_EQ (*range,
    1941              :                      0, line_1, 0,
    1942              :                      24, line_1, 24);
    1943            4 :   }
    1944              : 
    1945              :   /* Test of non-ASCII input.  This string is the Japanese word "mojibake",
    1946              :      written as C octal-escaped UTF-8.  */
    1947            4 :   const char *mojibake = (/* Opening quote.  */
    1948              :                           "\""
    1949              :                           /* U+6587 CJK UNIFIED IDEOGRAPH-6587
    1950              :                              UTF-8: 0xE6 0x96 0x87
    1951              :                              C octal escaped UTF-8: \346\226\207.  */
    1952              :                           "\346\226\207"
    1953              :                           /* U+5B57 CJK UNIFIED IDEOGRAPH-5B57
    1954              :                              UTF-8: 0xE5 0xAD 0x97
    1955              :                              C octal escaped UTF-8: \345\255\227.  */
    1956              :                           "\345\255\227"
    1957              :                           /* U+5316 CJK UNIFIED IDEOGRAPH-5316
    1958              :                              UTF-8: 0xE5 0x8C 0x96
    1959              :                              C octal escaped UTF-8: \345\214\226.  */
    1960              :                           "\345\214\226"
    1961              :                           /* U+3051 HIRAGANA LETTER KE
    1962              :                              UTF-8: 0xE3 0x81 0x91
    1963              :                              C octal escaped UTF-8: \343\201\221.  */
    1964              :                           "\343\201\221"
    1965              :                           /* Closing quote.  */
    1966              :                           "\"");
    1967            4 :   {
    1968            4 :     parser_testcase tc (mojibake);
    1969            4 :     ASSERT_EQ (tc.get_error (), nullptr);
    1970            4 :     const json::value *jv = tc.get_value ();
    1971            4 :     ASSERT_EQ (jv->get_kind (), JSON_STRING);
    1972              :     /* Result of get_string should be UTF-8 encoded, without quotes.  */
    1973            4 :     ASSERT_STREQ (as_a <const json::string *> (jv)->get_string (),
    1974              :                   "\346\226\207" "\345\255\227" "\345\214\226" "\343\201\221");
    1975              :     /* Result of dump should be UTF-8 encoded, with quotes.  */
    1976            4 :     ASSERT_JSON_PRINT_EQ (*jv, false, mojibake);
    1977            4 :     auto range = tc.get_range_for_value (jv);
    1978            4 :     ASSERT_TRUE (range);
    1979            4 :     ASSERT_RANGE_EQ (*range,
    1980              :                      0, line_1, 0,
    1981              :                      5, line_1, 5);
    1982            4 :   }
    1983              : 
    1984              :   /* Test of \u-escaped unicode.  This is "mojibake" again, as above.  */
    1985            4 :   {
    1986            4 :     const char *escaped_unicode = "\"\\u6587\\u5b57\\u5316\\u3051\"";
    1987            4 :     parser_testcase tc (escaped_unicode);
    1988            4 :     ASSERT_EQ (tc.get_error (), nullptr);
    1989            4 :     const json::value *jv = tc.get_value ();
    1990            4 :     ASSERT_EQ (jv->get_kind (), JSON_STRING);
    1991              :     /* Result of get_string should be UTF-8 encoded, without quotes.  */
    1992            4 :     ASSERT_STREQ (as_a <const json::string *> (jv)->get_string (),
    1993              :                   "\346\226\207" "\345\255\227" "\345\214\226" "\343\201\221");
    1994              :     /* Result of dump should be UTF-8 encoded, with quotes.  */
    1995            4 :     ASSERT_JSON_PRINT_EQ (*jv, false, mojibake);
    1996            4 :     auto range = tc.get_range_for_value (jv);
    1997            4 :     ASSERT_TRUE (range);
    1998            4 :     ASSERT_RANGE_EQ (*range,
    1999              :                      0, line_1, 0,
    2000              :                      25, line_1, 25);
    2001            4 :   }
    2002            4 : }
    2003              : 
    2004              : /* Verify that we can parse various kinds of JSON numbers.  */
    2005              : 
    2006              : static void
    2007            4 : test_parse_number ()
    2008              : {
    2009            4 :   const int line_1 = 1;
    2010              : 
    2011            4 :   {
    2012            4 :     parser_testcase tc ("42");
    2013            4 :     ASSERT_EQ (tc.get_error (), nullptr);
    2014            4 :     const json::value *jv = tc.get_value ();
    2015            4 :     ASSERT_EQ (jv->get_kind (), JSON_INTEGER);
    2016            4 :     ASSERT_EQ (as_a <const json::integer_number *> (jv)->get (), 42.0);
    2017            4 :     ASSERT_JSON_PRINT_EQ (*jv, true, "42");
    2018            4 :     auto range = tc.get_range_for_value (jv);
    2019            4 :     ASSERT_TRUE (range);
    2020            4 :     ASSERT_RANGE_EQ (*range,
    2021              :                      0, line_1, 0,
    2022              :                      1, line_1, 1);
    2023            4 :   }
    2024              : 
    2025              :   /* Negative number.  */
    2026            4 :   {
    2027            4 :     parser_testcase tc ("-17");
    2028            4 :     ASSERT_EQ (tc.get_error (), nullptr);
    2029            4 :     const json::value *jv = tc.get_value ();
    2030            4 :     ASSERT_EQ (jv->get_kind (), JSON_INTEGER);
    2031            4 :     ASSERT_EQ (as_a<const json::integer_number *> (jv)->get (), -17.0);
    2032            4 :     ASSERT_JSON_PRINT_EQ (*jv, true, "-17");
    2033            4 :     auto range = tc.get_range_for_value (jv);
    2034            4 :     ASSERT_TRUE (range);
    2035            4 :     ASSERT_RANGE_EQ (*range,
    2036              :                      0, line_1, 0,
    2037              :                      2, line_1, 2);
    2038            4 :   }
    2039              : 
    2040              :   /* Decimal.  */
    2041            4 :   {
    2042            4 :     parser_testcase tc ("3.141");
    2043            4 :     ASSERT_EQ (tc.get_error (), nullptr);
    2044            4 :     const json::value *jv = tc.get_value ();
    2045            4 :     ASSERT_EQ (JSON_FLOAT, jv->get_kind ());
    2046            4 :     ASSERT_NEAR (3.141, ((const json::float_number *)jv)->get (), 0.001);
    2047            4 :     auto range = tc.get_range_for_value (jv);
    2048            4 :     ASSERT_TRUE (range);
    2049            4 :     ASSERT_RANGE_EQ (*range,
    2050              :                      0, line_1, 0,
    2051              :                      4, line_1, 4);
    2052            4 :   }
    2053              : 
    2054              :   /* Exponents.  */
    2055            4 :   {
    2056            4 :     {
    2057            4 :       parser_testcase tc ("3.141e+0");
    2058            4 :       ASSERT_EQ (tc.get_error (), nullptr);
    2059            4 :       const json::value *jv = tc.get_value ();
    2060            4 :       ASSERT_EQ (jv->get_kind (), JSON_FLOAT);
    2061            4 :       ASSERT_NEAR (as_a <const json::float_number *> (jv)->get (), 3.141, 0.1);
    2062            4 :       auto range = tc.get_range_for_value (jv);
    2063            4 :       ASSERT_TRUE (range);
    2064            4 :       ASSERT_RANGE_EQ (*range,
    2065              :                        0, line_1, 0,
    2066              :                        7, line_1, 7);
    2067            4 :     }
    2068            4 :     {
    2069            4 :       parser_testcase tc ("42e2");
    2070            4 :       ASSERT_EQ (tc.get_error (), nullptr);
    2071            4 :       const json::value *jv = tc.get_value ();
    2072            4 :       ASSERT_EQ (jv->get_kind (), JSON_INTEGER);
    2073            4 :       ASSERT_EQ (as_a <const json::integer_number *> (jv)->get (), 4200);
    2074            4 :       ASSERT_JSON_PRINT_EQ (*jv, true, "4200");
    2075            4 :       auto range = tc.get_range_for_value (jv);
    2076            4 :       ASSERT_TRUE (range);
    2077            4 :       ASSERT_RANGE_EQ (*range,
    2078              :                        0, line_1, 0,
    2079              :                        3, line_1, 3);
    2080            4 :     }
    2081            4 :     {
    2082            4 :       parser_testcase tc ("42e-1");
    2083            4 :       ASSERT_EQ (tc.get_error (), nullptr);
    2084            4 :       const json::value *jv = tc.get_value ();
    2085            4 :       ASSERT_EQ (jv->get_kind (), JSON_FLOAT);
    2086            4 :       ASSERT_NEAR (as_a <const json::float_number *> (jv)->get (), 4.2, 0.1);
    2087            4 :       auto range = tc.get_range_for_value (jv);
    2088            4 :       ASSERT_TRUE (range);
    2089            4 :       ASSERT_RANGE_EQ (*range,
    2090              :                        0, line_1, 0,
    2091              :                        4, line_1, 4);
    2092            4 :     }
    2093              :   }
    2094            4 : }
    2095              : 
    2096              : /* Verify that JSON array parsing works.  */
    2097              : 
    2098              : static void
    2099            4 : test_parse_array ()
    2100              : {
    2101            4 :   const int line_1 = 1;
    2102              : 
    2103            4 :   parser_testcase tc ("[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]");
    2104            4 :   ASSERT_EQ (tc.get_error (), nullptr);
    2105            4 :   const json::value *jv = tc.get_value ();
    2106            4 :   ASSERT_EQ (jv->get_kind (), JSON_ARRAY);
    2107            4 :   const json::array *arr = as_a <const json::array *> (jv);
    2108            4 :   ASSERT_EQ (arr->length (), 10);
    2109            4 :   auto range = tc.get_range_for_value (jv);
    2110            4 :   ASSERT_TRUE (range);
    2111            4 :   ASSERT_RANGE_EQ (*range,
    2112              :                    0, line_1, 0,
    2113              :                    29, line_1, 29);
    2114           44 :   for (int i = 0; i < 10; i++)
    2115              :     {
    2116           40 :       json::value *element = arr->get (i);
    2117           40 :       ASSERT_EQ (element->get_kind (), JSON_INTEGER);
    2118           40 :       ASSERT_EQ (as_a <json::integer_number *> (element)->get (), i);
    2119           40 :       range = tc.get_range_for_value (element);
    2120           40 :       ASSERT_TRUE (range);
    2121           40 :       const int offset = 1 + (i * 3);
    2122           40 :       ASSERT_RANGE_EQ (*range,
    2123              :                        offset, line_1, offset,
    2124              :                        offset, line_1, offset);
    2125              :     }
    2126            4 :   ASSERT_JSON_PRINT_EQ (*jv, false, "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]");
    2127            4 : }
    2128              : 
    2129              : /* Verify that JSON object parsing works.  */
    2130              : 
    2131              : static void
    2132            4 : test_parse_object ()
    2133              : {
    2134            4 :   const int line_1 = 1;
    2135            4 :   std::unique_ptr<error> err;
    2136              :   /*                   0            1            2         3  .  */
    2137              :   /*                   01 2345 678 9012 345 6789 0123456789012.  */
    2138            4 :   parser_testcase tc ("{\"foo\": \"bar\", \"baz\": [42, null]}");
    2139              : 
    2140            4 :   ASSERT_EQ (tc.get_error (), nullptr);
    2141            4 :   const json::value *jv = tc.get_value ();
    2142            4 :   ASSERT_NE (jv, nullptr);
    2143            4 :   ASSERT_EQ (jv->get_kind (), JSON_OBJECT);
    2144            4 :   auto range = tc.get_range_for_value (jv);
    2145            4 :   ASSERT_TRUE (range);
    2146            4 :   ASSERT_RANGE_EQ (*range,
    2147              :                    0, line_1, 0,
    2148              :                    32, line_1, 32);
    2149            4 :   const json::object *jo = static_cast <const json::object *> (jv);
    2150            4 :   ASSERT_JSON_POINTER_EQ (jv, "");
    2151              : 
    2152            4 :   json::value *foo_value = jo->get ("foo");
    2153            4 :   ASSERT_NE (foo_value, nullptr);
    2154            4 :   ASSERT_EQ (foo_value->get_kind (), JSON_STRING);
    2155            4 :   ASSERT_STREQ (as_a <json::string *> (foo_value)->get_string (), "bar");
    2156            4 :   range = tc.get_range_for_value (foo_value);
    2157            4 :   ASSERT_TRUE (range);
    2158            4 :   ASSERT_RANGE_EQ (*range,
    2159              :                    8, line_1, 8,
    2160              :                    12, line_1, 12);
    2161            4 :   ASSERT_JSON_POINTER_EQ (foo_value, "/foo");
    2162              : 
    2163            4 :   json::value *baz_value = jo->get ("baz");
    2164            4 :   ASSERT_NE (baz_value, nullptr);
    2165            4 :   ASSERT_EQ (baz_value->get_kind (), JSON_ARRAY);
    2166            4 :   range = tc.get_range_for_value (baz_value);
    2167            4 :   ASSERT_TRUE (range);
    2168            4 :   ASSERT_RANGE_EQ (*range,
    2169              :                    22, line_1, 22,
    2170              :                    31, line_1, 31);
    2171            4 :   ASSERT_JSON_POINTER_EQ (baz_value, "/baz");
    2172              : 
    2173            4 :   json::array *baz_array = as_a <json::array *> (baz_value);
    2174            4 :   ASSERT_EQ (baz_array->length (), 2);
    2175              : 
    2176            4 :   json::value *element0 = baz_array->get (0);
    2177            4 :   ASSERT_EQ (as_a <json::integer_number *> (element0)->get (), 42);
    2178            4 :   range = tc.get_range_for_value (element0);
    2179            4 :   ASSERT_TRUE (range);
    2180            4 :   ASSERT_RANGE_EQ (*range,
    2181              :                    23, line_1, 23,
    2182              :                    24, line_1, 24);
    2183            4 :   ASSERT_JSON_POINTER_EQ (element0, "/baz/0");
    2184              : 
    2185            4 :   json::value *element1 = baz_array->get (1);
    2186            4 :   ASSERT_EQ (element1->get_kind (), JSON_NULL);
    2187            4 :   range = tc.get_range_for_value (element1);
    2188            4 :   ASSERT_TRUE (range);
    2189            4 :   ASSERT_RANGE_EQ (*range,
    2190              :                    27, line_1, 27,
    2191              :                    30, line_1, 30);
    2192            4 :   ASSERT_JSON_POINTER_EQ (element1, "/baz/1");
    2193            4 : }
    2194              : 
    2195              : /* Verify that the JSON literals "true", "false" and "null" are parsed
    2196              :    correctly.  */
    2197              : 
    2198              : static void
    2199            4 : test_parse_literals ()
    2200              : {
    2201            4 :   const int line_1 = 1;
    2202            4 :   {
    2203            4 :     parser_testcase tc ("true");
    2204            4 :     ASSERT_EQ (tc.get_error (), nullptr);
    2205            4 :     const json::value *jv = tc.get_value ();
    2206            4 :     ASSERT_NE (jv, nullptr);
    2207            4 :     ASSERT_EQ (jv->get_kind (), JSON_TRUE);
    2208            4 :     ASSERT_JSON_PRINT_EQ (*jv, false, "true");
    2209            4 :     auto range = tc.get_range_for_value (jv);
    2210            4 :     ASSERT_TRUE (range);
    2211            4 :     ASSERT_RANGE_EQ (*range,
    2212              :                      0, line_1, 0,
    2213              :                      3, line_1, 3);
    2214            4 :   }
    2215              : 
    2216            4 :   {
    2217            4 :     parser_testcase tc ("false");
    2218            4 :     ASSERT_EQ (tc.get_error (), nullptr);
    2219            4 :     const json::value *jv = tc.get_value ();
    2220            4 :     ASSERT_NE (jv, nullptr);
    2221            4 :     ASSERT_EQ (jv->get_kind (), JSON_FALSE);
    2222            4 :     ASSERT_JSON_PRINT_EQ (*jv, false, "false");
    2223            4 :     auto range = tc.get_range_for_value (jv);
    2224            4 :     ASSERT_TRUE (range);
    2225            4 :     ASSERT_RANGE_EQ (*range,
    2226              :                      0, line_1, 0,
    2227              :                      4, line_1, 4);
    2228            4 :   }
    2229              : 
    2230            4 :   {
    2231            4 :     parser_testcase tc ("null");
    2232            4 :     ASSERT_EQ (tc.get_error (), nullptr);
    2233            4 :     const json::value *jv = tc.get_value ();
    2234            4 :     ASSERT_NE (jv, nullptr);
    2235            4 :     ASSERT_EQ (jv->get_kind (), JSON_NULL);
    2236            4 :     ASSERT_JSON_PRINT_EQ (*jv, false, "null");
    2237            4 :     auto range = tc.get_range_for_value (jv);
    2238            4 :     ASSERT_TRUE (range);
    2239            4 :     ASSERT_RANGE_EQ (*range,
    2240              :                      0, line_1, 0,
    2241              :                      3, line_1, 3);
    2242            4 :   }
    2243            4 : }
    2244              : 
    2245              : /* Verify that we can parse a simple JSON-RPC request.  */
    2246              : 
    2247              : static void
    2248            4 : test_parse_jsonrpc ()
    2249              : {
    2250            4 :   std::unique_ptr<error> err;
    2251            4 :   const char *request
    2252              :     /*  0           1            2           3          4.  */
    2253              :     /*  01 23456789 012 3456 789 0123456 789 012345678 90.  */
    2254              :     = ("{\"jsonrpc\": \"2.0\", \"method\": \"subtract\",\n"
    2255              :     /*  0           1         2           3          4.  */
    2256              :     /*  0 1234567 8901234567890 1234 56789012345678 90.  */
    2257              :        " \"params\": [42, 23], \"id\": 1}");
    2258            4 :   const int line_1 = 1;
    2259            4 :   const int line_2 = 2;
    2260            4 :   const size_t line_2_offset = 41;
    2261            4 :   parser_testcase tc (request);
    2262            4 :   ASSERT_EQ (tc.get_error (), nullptr);
    2263            4 :   const json::value *jv = tc.get_value ();
    2264            4 :   ASSERT_NE (jv, nullptr);
    2265            4 :   auto range = tc.get_range_for_value (jv);
    2266            4 :   ASSERT_TRUE (range);
    2267            4 :   ASSERT_RANGE_EQ (*range,
    2268              :                    0, line_1, 0,
    2269              :                    line_2_offset + 28, line_2, 28);
    2270            4 : }
    2271              : 
    2272              : /* Verify that we can parse an empty JSON object.  */
    2273              : 
    2274              : static void
    2275            4 : test_parse_empty_object ()
    2276              : {
    2277            4 :   const int line_1 = 1;
    2278            4 :   std::unique_ptr<error> err;
    2279            4 :   parser_testcase tc ("{}");
    2280            4 :   ASSERT_EQ (tc.get_error (), nullptr);
    2281            4 :   const json::value *jv = tc.get_value ();
    2282            4 :   ASSERT_NE (jv, nullptr);
    2283            4 :   ASSERT_EQ (jv->get_kind (), JSON_OBJECT);
    2284            4 :   ASSERT_JSON_PRINT_EQ (*jv, true, "{}");
    2285            4 :   auto range = tc.get_range_for_value (jv);
    2286            4 :   ASSERT_TRUE (range);
    2287            4 :   ASSERT_RANGE_EQ (*range,
    2288              :                    0, line_1, 0,
    2289              :                    1, line_1, 1);
    2290            4 : }
    2291              : 
    2292              : /* Verify that comment-parsing can be enabled or disabled.  */
    2293              : 
    2294              : static void
    2295            4 : test_parsing_comments ()
    2296              : {
    2297            4 :   const char *str = ("// foo\n"
    2298              :                      "/*...\n"
    2299              :                      "...*/ 42 // bar\n"
    2300              :                      "/* etc */\n");
    2301              : 
    2302              :   /* Parsing with comment support disabled.  */
    2303            4 :   {
    2304            4 :     parser_testcase tc (str);
    2305            4 :     ASSERT_NE (tc.get_error (), nullptr);
    2306            4 :     ASSERT_STREQ (tc.get_error ()->get_msg (),
    2307              :                   "invalid JSON token: unexpected character: '/'");
    2308            4 :     ASSERT_EQ (tc.get_value (), nullptr);
    2309            4 :   }
    2310              : 
    2311              :   /* Parsing with comment support enabled.  */
    2312            4 :   {
    2313            4 :     parser_testcase tc (str, true);
    2314            4 :     ASSERT_EQ (tc.get_error (), nullptr);
    2315            4 :     const json::value *jv = tc.get_value ();
    2316            4 :     ASSERT_NE (jv, nullptr);
    2317            4 :     ASSERT_EQ (jv->get_kind (), JSON_INTEGER);
    2318            4 :     ASSERT_EQ (((const json::integer_number *)jv)->get (), 42);
    2319            4 :   }
    2320            4 : }
    2321              : 
    2322              : /* Verify that JSON Pointers are correctly escaped.  */
    2323              : 
    2324              : static void
    2325            4 : test_pointer_escaping ()
    2326              : {
    2327            4 :   std::unique_ptr<error> err;
    2328              :   /* Example adapted from RFC 6901 section 5.  */
    2329            4 :   parser_testcase tc
    2330              :     ("     {\n"
    2331              :      "      \"a/b\": 1,\n"
    2332              :      "      \"m~n\": 8\n"
    2333            4 :      "   }\n");
    2334            4 :   ASSERT_EQ (tc.get_error (), nullptr);
    2335            4 :   const json::value *jv = tc.get_value ();
    2336            4 :   ASSERT_NE (jv, nullptr);
    2337            4 :   ASSERT_EQ (jv->get_kind (), JSON_OBJECT);
    2338              : 
    2339            4 :   auto jo = static_cast <const json::object *> (jv);
    2340            4 :   ASSERT_JSON_POINTER_EQ (jo->get ("a/b"), "/a~1b");
    2341            4 :   ASSERT_JSON_POINTER_EQ (jo->get ("m~n"), "/m~0n");
    2342            4 : }
    2343              : 
    2344              : /* Verify that we can parse an empty JSON string.  */
    2345              : 
    2346              : static void
    2347            4 : test_error_empty_string ()
    2348              : {
    2349            4 :   const int line_1 = 1;
    2350            4 :   parser_testcase tc ("");
    2351            4 :   ASSERT_ERR_EQ (tc.get_error (),
    2352              :                  0, line_1, 0,
    2353              :                  0, line_1, 0,
    2354              :                  "expected a JSON value but got EOF");
    2355            4 :   ASSERT_EQ (tc.get_value (), nullptr);
    2356            4 : }
    2357              : 
    2358              : /* Verify that JSON parsing gracefully handles an invalid token.  */
    2359              : 
    2360              : static void
    2361            4 : test_error_bad_token ()
    2362              : {
    2363            4 :   const int line_1 = 1;
    2364            4 :   parser_testcase tc ("  not valid ");
    2365            4 :   ASSERT_ERR_EQ (tc.get_error (),
    2366              :                  2, line_1, 2,
    2367              :                  2, line_1, 2,
    2368              :                  "invalid JSON token: unexpected character: 'n'");
    2369            4 :   ASSERT_EQ (tc.get_value (), nullptr);
    2370            4 : }
    2371              : 
    2372              : /* Verify that JSON parsing gracefully handles a missing comma
    2373              :    within an object.  */
    2374              : 
    2375              : static void
    2376            4 : test_error_object_with_missing_comma ()
    2377              : {
    2378            4 :   const int line_1 = 1;
    2379              :   /*                  0           1           2.  */
    2380              :   /*                  01 2345 6789012 3456 7890.  */
    2381            4 :   const char *json = "{\"foo\" : 42 \"bar\"";
    2382            4 :   parser_testcase tc (json);
    2383            4 :   ASSERT_ERR_EQ (tc.get_error (),
    2384              :                  12, line_1, 12,
    2385              :                  16, line_1, 16,
    2386              :                  "expected ',' or '}'; got string");
    2387            4 :   ASSERT_EQ (tc.get_value (), nullptr);
    2388            4 : }
    2389              : 
    2390              : /* Verify that JSON parsing gracefully handles a missing comma
    2391              :    within an array.  */
    2392              : 
    2393              : static void
    2394            4 : test_error_array_with_missing_comma ()
    2395              : {
    2396            4 :   const int line_1 = 1;
    2397              :   /*                  01234567.  */
    2398            4 :   const char *json = "[0, 1 42]";
    2399            4 :   parser_testcase tc (json);
    2400            4 :   ASSERT_ERR_EQ (tc.get_error (),
    2401              :                  6, line_1, 6,
    2402              :                  7, line_1, 7,
    2403              :                  "expected ',' or ']'; got number");
    2404            4 :   ASSERT_EQ (tc.get_value (), nullptr);
    2405            4 : }
    2406              : 
    2407              : /* Run all of the selftests within this file.  */
    2408              : 
    2409              : void
    2410            4 : json_parser_cc_tests ()
    2411              : {
    2412            4 :   test_lexer ();
    2413            4 :   test_lexing_unsupported_single_line_comment ();
    2414            4 :   test_lexing_unsupported_multiline_comment ();
    2415            4 :   test_lexing_supported_single_line_comment ();
    2416            4 :   test_lexing_supported_multiline_comment ();
    2417            4 :   test_parse_string ();
    2418            4 :   test_parse_number ();
    2419            4 :   test_parse_array ();
    2420            4 :   test_parse_object ();
    2421            4 :   test_parse_literals ();
    2422            4 :   test_parse_jsonrpc ();
    2423            4 :   test_parse_empty_object ();
    2424            4 :   test_parsing_comments ();
    2425            4 :   test_pointer_escaping ();
    2426            4 :   test_error_empty_string ();
    2427            4 :   test_error_bad_token ();
    2428            4 :   test_error_object_with_missing_comma ();
    2429            4 :   test_error_array_with_missing_comma ();
    2430            4 : }
    2431              : 
    2432              : } // namespace selftest
    2433              : 
    2434              : #endif /* #if CHECKING_P */
        

Generated by: LCOV version 2.5.0-beta

LCOV profile is generated on x86_64 machine using following configure options: configure --disable-bootstrap --enable-coverage=opt --enable-languages=c,c++,fortran,go,jit,lto,rust,m2 --enable-host-shared. GCC test suite is run with the built compiler.