summaryrefslogtreecommitdiff
path: root/pango/json/gtkjsonparser.c
blob: 91048fec428986a008a4e29860862be7c7f8b797 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
/*
 * Copyright © 2021 Benjamin Otte
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library. If not, see <http://www.gnu.org/licenses/>.
 *
 * Authors: Benjamin Otte <otte@gnome.org>
 */


#include "config.h"

#include "gtkjsonparserprivate.h"

typedef struct _GtkJsonBlock GtkJsonBlock;

typedef enum {
  GTK_JSON_BLOCK_TOPLEVEL,
  GTK_JSON_BLOCK_OBJECT,
  GTK_JSON_BLOCK_ARRAY,
} GtkJsonBlockType;

struct _GtkJsonBlock
{
  GtkJsonBlockType type;
  const guchar *value; /* start of current value to be consumed by external code */
  const guchar *member_name; /* name of current value, only used for object types */
  gsize index; /* index of the current element */
};

struct _GtkJsonParser
{
  GBytes *bytes;
  const guchar *reader; /* current read head, pointing as far as we've read */
  const guchar *end; /* pointer after end of data we're reading */

  GError *error; /* if an error has happened, it's stored here. Errors aren't recoverable. */

  GtkJsonBlock *block; /* current block */
  GtkJsonBlock *blocks; /* blocks array */
  GtkJsonBlock *blocks_end; /* blocks array */
  GtkJsonBlock blocks_preallocated[128]; /* preallocated */
};

typedef enum {
  WHITESPACE     = (1 << 4),
  STRING_ELEMENT = (1 << 5),
  STRING_MARKER  = (1 << 6),
} JsonCharacterType;

#define JSON_CHARACTER_NODE_MASK ((1 << 4) - 1)

static const guchar json_character_table[256] = {
  ['\t'] = WHITESPACE,
  ['\r'] = WHITESPACE,
  ['\n'] = WHITESPACE,
  [' ']  = WHITESPACE | STRING_ELEMENT,
  ['!']  = STRING_ELEMENT,
  ['"']  = GTK_JSON_STRING | STRING_MARKER,
  ['#']  = STRING_ELEMENT,
  ['$']  = STRING_ELEMENT,
  ['%']  = STRING_ELEMENT,
  ['&']  = STRING_ELEMENT,
  ['\''] = STRING_ELEMENT,
  ['(']  = STRING_ELEMENT,
  [')']  = STRING_ELEMENT,
  ['*']  = STRING_ELEMENT,
  ['+']  = STRING_ELEMENT,
  [',']  = STRING_ELEMENT,
  ['-']  = GTK_JSON_NUMBER | STRING_ELEMENT,
  ['.']  = STRING_ELEMENT,
  ['/']  = STRING_ELEMENT,
  ['0']  = GTK_JSON_NUMBER | STRING_ELEMENT,
  ['1']  = GTK_JSON_NUMBER | STRING_ELEMENT,
  ['2']  = GTK_JSON_NUMBER | STRING_ELEMENT,
  ['3']  = GTK_JSON_NUMBER | STRING_ELEMENT,
  ['4']  = GTK_JSON_NUMBER | STRING_ELEMENT,
  ['5']  = GTK_JSON_NUMBER | STRING_ELEMENT,
  ['6']  = GTK_JSON_NUMBER | STRING_ELEMENT,
  ['7']  = GTK_JSON_NUMBER | STRING_ELEMENT,
  ['8']  = GTK_JSON_NUMBER | STRING_ELEMENT,
  ['9']  = GTK_JSON_NUMBER | STRING_ELEMENT,
  [':']  = STRING_ELEMENT,
  [';']  = STRING_ELEMENT,
  ['<']  = STRING_ELEMENT,
  ['=']  = STRING_ELEMENT,
  ['>']  = STRING_ELEMENT,
  ['?']  = STRING_ELEMENT,
  ['@']  = STRING_ELEMENT,
  ['A']  = STRING_ELEMENT,
  ['B']  = STRING_ELEMENT,
  ['C']  = STRING_ELEMENT,
  ['D']  = STRING_ELEMENT,
  ['E']  = STRING_ELEMENT,
  ['F']  = STRING_ELEMENT,
  ['G']  = STRING_ELEMENT,
  ['H']  = STRING_ELEMENT,
  ['I']  = STRING_ELEMENT,
  ['J']  = STRING_ELEMENT,
  ['K']  = STRING_ELEMENT,
  ['L']  = STRING_ELEMENT,
  ['M']  = STRING_ELEMENT,
  ['N']  = STRING_ELEMENT,
  ['O']  = STRING_ELEMENT,
  ['P']  = STRING_ELEMENT,
  ['Q']  = STRING_ELEMENT,
  ['R']  = STRING_ELEMENT,
  ['S']  = STRING_ELEMENT,
  ['T']  = STRING_ELEMENT,
  ['U']  = STRING_ELEMENT,
  ['V']  = STRING_ELEMENT,
  ['W']  = STRING_ELEMENT,
  ['X']  = STRING_ELEMENT,
  ['Y']  = STRING_ELEMENT,
  ['Z']  = STRING_ELEMENT,
  ['[']  = GTK_JSON_ARRAY | STRING_ELEMENT,
  ['\\'] = STRING_MARKER,
  [']']  = STRING_ELEMENT,
  ['^']  = STRING_ELEMENT,
  ['_']  = STRING_ELEMENT,
  ['`']  = STRING_ELEMENT,
  ['a']  = STRING_ELEMENT,
  ['b']  = STRING_ELEMENT,
  ['c']  = STRING_ELEMENT,
  ['d']  = STRING_ELEMENT,
  ['e']  = STRING_ELEMENT,
  ['f']  = GTK_JSON_BOOLEAN | STRING_ELEMENT,
  ['g']  = STRING_ELEMENT,
  ['h']  = STRING_ELEMENT,
  ['i']  = STRING_ELEMENT,
  ['j']  = STRING_ELEMENT,
  ['k']  = STRING_ELEMENT,
  ['l']  = STRING_ELEMENT,
  ['m']  = STRING_ELEMENT,
  ['n']  = GTK_JSON_NULL | STRING_ELEMENT,
  ['o']  = STRING_ELEMENT,
  ['p']  = STRING_ELEMENT,
  ['q']  = STRING_ELEMENT,
  ['r']  = STRING_ELEMENT,
  ['s']  = STRING_ELEMENT,
  ['t']  = GTK_JSON_BOOLEAN | STRING_ELEMENT,
  ['u']  = STRING_ELEMENT,
  ['v']  = STRING_ELEMENT,
  ['w']  = STRING_ELEMENT,
  ['x']  = STRING_ELEMENT,
  ['y']  = STRING_ELEMENT,
  ['z']  = STRING_ELEMENT,
  ['{']  = GTK_JSON_OBJECT | STRING_ELEMENT,
  ['|']  = STRING_ELEMENT,
  ['}']  = STRING_ELEMENT,
  ['~']  = STRING_ELEMENT,
  [127]  = STRING_ELEMENT,
};

static const guchar *
json_skip_characters (const guchar      *start,
                      const guchar      *end,
                      JsonCharacterType  type)
{
  const guchar *s;

  for (s = start; s < end; s++)
    {
      if (!(json_character_table[*s] & type))
        break;
    }
  return s;
}

static const guchar *
json_find_character (const guchar      *start,
                     JsonCharacterType  type)
{
  const guchar *s;

  for (s = start; ; s++)
    {
      if ((json_character_table[*s] & type))
        break;
    }
  return s;
}

static void
gtk_json_parser_value_error (GtkJsonParser *self,
                             const char  *format,
                             ...) G_GNUC_PRINTF(2, 3);
static void
gtk_json_parser_value_error (GtkJsonParser *self,
                             const char  *format,
                             ...)
{
  va_list args;

  if (self->error)
    return;

  va_start (args, format);
  self->error = g_error_new_valist (G_FILE_ERROR,
                                    G_FILE_ERROR_FAILED,
                                    format, args);
  va_end (args);
}

static void
gtk_json_parser_syntax_error (GtkJsonParser *self,
                              const char  *format,
                              ...) G_GNUC_PRINTF(2, 3);
static void
gtk_json_parser_syntax_error (GtkJsonParser *self,
                              const char  *format,
                              ...)
{
  va_list args;

  if (self->error)
    return;

  va_start (args, format);
  self->error = g_error_new_valist (G_FILE_ERROR,
                                    G_FILE_ERROR_FAILED,
                                    format, args);
  va_end (args);
}

static gboolean
gtk_json_parser_is_eof (GtkJsonParser *self)
{
  return self->reader >= self->end || *self->reader == '\0';
}

static gsize
gtk_json_parser_remaining (GtkJsonParser *self)
{
  g_return_val_if_fail (self->reader <= self->end, 0);

  return self->end - self->reader;
}

static void
gtk_json_parser_skip_whitespace (GtkJsonParser *self)
{
  self->reader = json_skip_characters (self->reader, self->end, WHITESPACE);
}

static gboolean
gtk_json_parser_has_char (GtkJsonParser *self,
                          char           c)
{
  return gtk_json_parser_remaining (self) && *self->reader == c;
}

static gboolean
gtk_json_parser_try_char (GtkJsonParser *self,
                          char           c)
{
  if (!gtk_json_parser_has_char (self, c))
    return FALSE;

  self->reader++;
  return TRUE;
}

static gboolean
gtk_json_parser_try_identifier_len (GtkJsonParser *self,
                                    const char    *ident,
                                    gsize          len)
{
  if (gtk_json_parser_remaining (self) < len)
    return FALSE;

  if (memcmp (self->reader, ident, len) != 0)
    return FALSE;

  self->reader += len;
  return TRUE;
}

#define gtk_json_parser_try_identifier(parser, ident) gtk_json_parser_try_identifier_len(parser, ident, strlen(ident))

/*
 * decode_utf16_surrogate_pair:
 * @first: the first UTF-16 code point
 * @second: the second UTF-16 code point
 *
 * Decodes a surrogate pair of UTF-16 code points into the equivalent
 * Unicode code point.
 *
 * If the code points are not valid, 0 is returned.
 *
 * Returns: the Unicode code point equivalent to the surrogate pair
 */
static inline gunichar
decode_utf16_surrogate_pair (gunichar first,
                             gunichar second)
{
  if (0xd800 > first || first > 0xdbff ||
      0xdc00 > second || second > 0xdfff)
    return 0;

  return 0x10000
       | (first & 0x3ff) << 10
       | (second & 0x3ff);
}

static gsize
gtk_json_unescape_char (const guchar *json_escape,
                        char          out_data[6],
                        gsize        *out_len)
{
  switch (json_escape[1])
    {
    case '"':
    case '\\':
    case '/':
      out_data[0] = json_escape[1];
      *out_len = 1;
      return 2;
    case 'b':
      out_data[0] = '\b';
      *out_len = 1;
      return 2;
    case 'f':
      out_data[0] = '\f';
      *out_len = 1;
      return 2;
    case 'n':
      out_data[0] = '\n';
      *out_len = 1;
      return 2;
    case 'r':
      out_data[0] = '\r';
      *out_len = 1;
      return 2;
    case 't':
      out_data[0] = '\t';
      *out_len = 1;
      return 2;
    case 'u':
      {
        gunichar unichar = (g_ascii_xdigit_value (json_escape[2]) << 12) |
                           (g_ascii_xdigit_value (json_escape[3]) <<  8) |
                           (g_ascii_xdigit_value (json_escape[4]) <<  4) |
                           (g_ascii_xdigit_value (json_escape[5]));
        gsize result = 6;

        /* resolve UTF-16 surrogates for Unicode characters not in the BMP,
         * as per ECMA 404, § 9, "String"
         */
        if (g_unichar_type (unichar) == G_UNICODE_SURROGATE)
          {
            unichar = decode_utf16_surrogate_pair (unichar,
                                                   (g_ascii_xdigit_value (json_escape[8])  << 12) |
                                                   (g_ascii_xdigit_value (json_escape[9])  <<  8) |
                                                   (g_ascii_xdigit_value (json_escape[10]) <<  4) |
                                                   (g_ascii_xdigit_value (json_escape[11])));
            result += 6;
          }
        *out_len = g_unichar_to_utf8 (unichar, out_data);
        return result;
        }
    default:
      g_assert_not_reached ();
      return 0;
    }
}
                   
/* The escaped string MUST be valid json, so it must begin
 * with " and end with " and must not contain any invalid
 * escape codes.
 * This function is meant to be fast
 */
static char *
gtk_json_unescape_string (const guchar *escaped)
{
  char buf[6];
  gsize buf_size;
  GString *string;
  const guchar *last, *s;

  string = NULL;

  g_assert (*escaped == '"');
  last = escaped + 1;
  for (s = json_find_character (last, STRING_MARKER);
       *s != '"';
       s = json_find_character (last, STRING_MARKER))
    {
      g_assert (*s == '\\');
      if (string == NULL)
        string = g_string_new (NULL);
      g_string_append_len (string, (const char *) last, s - last);
      last = s + gtk_json_unescape_char (s, buf, &buf_size);
      g_string_append_len (string, buf, buf_size);
    }

  if (string)
    {
      g_string_append_len (string, (const char *) last, s - last);
      return g_string_free (string, FALSE);
    }
  else
    {
      return g_strndup ((const char *) last, s - last);
    }
}

static gboolean
gtk_json_parser_parse_string (GtkJsonParser *self)
{
  if (!gtk_json_parser_try_char (self, '"'))
    {
      gtk_json_parser_syntax_error (self, "Not a string");
      return FALSE;
    }

  self->reader = json_skip_characters (self->reader, self->end, STRING_ELEMENT);

  while (gtk_json_parser_remaining (self))
    {
      if (*self->reader < 0x20)
        {
          gtk_json_parser_syntax_error (self, "Disallowed control character in string literal");
          return FALSE;
        }
      else if (*self->reader > 127)
        {
          gunichar c = g_utf8_get_char_validated ((const char *) self->reader, gtk_json_parser_remaining (self));
          if (c == (gunichar) -2 || c == (gunichar) -1)
            {
              gtk_json_parser_syntax_error (self, "Invalid UTF-8");
              return FALSE;
            }
          self->reader = (const guchar *) g_utf8_next_char ((const char *) self->reader);
        }
      else if (*self->reader == '"')
        {
          self->reader++;
          return TRUE;
        }
      else if (*self->reader == '\\')
        {
          if (gtk_json_parser_remaining (self) < 2)
            goto end;
          self->reader++;
          switch (*self->reader)
            {
            case '"':
            case '\\':
            case '/':
            case 'b':
            case 'f':
            case 'n':
            case 'r':
            case 't':
              break;

            case 'u':
              /* lots of work necessary to validate the unicode escapes here */
              if (gtk_json_parser_remaining (self) < 5 ||
                  !g_ascii_isxdigit (self->reader[1]) ||
                  !g_ascii_isxdigit (self->reader[2]) ||
                  !g_ascii_isxdigit (self->reader[3]) ||
                  !g_ascii_isxdigit (self->reader[4]))
                {
                  gtk_json_parser_syntax_error (self, "Invalid Unicode escape sequence");
                  return FALSE;
                }
              else
                {
                  gunichar unichar = (g_ascii_xdigit_value (self->reader[1]) << 12) |
                                     (g_ascii_xdigit_value (self->reader[2]) <<  8) |
                                     (g_ascii_xdigit_value (self->reader[3]) <<  4) |
                                     (g_ascii_xdigit_value (self->reader[4]));

                  self->reader += 4;
                  /* resolve UTF-16 surrogates for Unicode characters not in the BMP,
                   * as per ECMA 404, § 9, "String"
                   */
                  if (g_unichar_type (unichar) == G_UNICODE_SURROGATE)
                    {
                      if (gtk_json_parser_remaining (self) >= 7 &&
                          self->reader[1] == '\\' &&
                          self->reader[2] == 'u' &&
                          g_ascii_isxdigit (self->reader[3]) &&
                          g_ascii_isxdigit (self->reader[4]) &&
                          g_ascii_isxdigit (self->reader[5]) &&
                          g_ascii_isxdigit (self->reader[6]))
                        {
                          unichar = decode_utf16_surrogate_pair (unichar,
                                                                 (g_ascii_xdigit_value (self->reader[3]) << 12) |
                                                                 (g_ascii_xdigit_value (self->reader[4]) <<  8) |
                                                                 (g_ascii_xdigit_value (self->reader[5]) <<  4) |
                                                                 (g_ascii_xdigit_value (self->reader[6])));
                          self->reader += 6;
                        }
                      else
                        {
                          unichar = 0;
                        }
                    }

                  if (unichar == 0)
                    {
                      gtk_json_parser_syntax_error (self, "Invalid UTF-16 surrogate pair");
                      return FALSE;
                    }
                }
              break;
            default:
              gtk_json_parser_syntax_error (self, "Unknown escape sequence");
              return FALSE;
            }
          self->reader++;
        }

      self->reader = json_skip_characters (self->reader, self->end, STRING_ELEMENT);
    }

end:
  gtk_json_parser_syntax_error (self, "Unterminated string literal");
  return FALSE;
}

static gboolean
gtk_json_parser_parse_number (GtkJsonParser *self)
{
  /* sign */
  gtk_json_parser_try_char (self, '-');

  /* integer part */
  if (!gtk_json_parser_try_char (self, '0'))
    {
      if (gtk_json_parser_is_eof (self) ||
          !g_ascii_isdigit (*self->reader))
        goto out;

      self->reader++;

      while (!gtk_json_parser_is_eof (self) && g_ascii_isdigit (*self->reader))
        self->reader++;
    }

  /* fractional part */
  if (gtk_json_parser_remaining (self) >= 2 && *self->reader == '.' && g_ascii_isdigit (self->reader[1]))
    {
      self->reader += 2;

      while (!gtk_json_parser_is_eof (self) && g_ascii_isdigit (*self->reader))
        self->reader++;
    }

  /* exponent */
  if (gtk_json_parser_remaining (self) >= 2 && (self->reader[0] == 'e' || self->reader[0] == 'E') &&
      (g_ascii_isdigit (self->reader[1]) ||
       (gtk_json_parser_remaining (self) >= 3 && (self->reader[1] == '+' || self->reader[1] == '-') && g_ascii_isdigit (self->reader[2]))))
    {
      self->reader += 2;

      while (!gtk_json_parser_is_eof (self) && g_ascii_isdigit (*self->reader))
        self->reader++;
    }
  return TRUE;

out:
  gtk_json_parser_syntax_error (self, "Not a valid number");
  return FALSE;
}

static gboolean
gtk_json_parser_parse_value (GtkJsonParser *self)
{
  if (gtk_json_parser_is_eof (self))
    {
      gtk_json_parser_syntax_error (self, "Unexpected end of document");
      return FALSE;
    }

  switch (json_character_table[*self->block->value] & JSON_CHARACTER_NODE_MASK)
  {
    case GTK_JSON_STRING:
      return gtk_json_parser_parse_string (self);
    
    case GTK_JSON_NUMBER:
      return gtk_json_parser_parse_number (self);

    case GTK_JSON_NULL:
      if (gtk_json_parser_try_identifier (self, "null"))
        return TRUE;
      break;

    case GTK_JSON_BOOLEAN:
      if (gtk_json_parser_try_identifier (self, "true") ||
          gtk_json_parser_try_identifier (self, "false"))
        return TRUE;
      break;

    case GTK_JSON_OBJECT:
    case GTK_JSON_ARRAY:
      /* don't preparse objects */
      return TRUE;

    default:
      break;
  }

  gtk_json_parser_syntax_error (self, "Expected a value");
  return FALSE;
}

static void
gtk_json_parser_push_block (GtkJsonParser    *self,
                            GtkJsonBlockType  type)
{
  self->block++;
  if (self->block == self->blocks_end)
    {
      gsize old_size = self->blocks_end - self->blocks;
      gsize new_size = old_size + 128;

      if (self->blocks == self->blocks_preallocated)
        {
          self->blocks = g_new (GtkJsonBlock, new_size);
          memcpy (self->blocks, self->blocks_preallocated, sizeof (GtkJsonBlock) * G_N_ELEMENTS (self->blocks_preallocated));
        }
      else
        {
          self->blocks = g_renew (GtkJsonBlock, self->blocks, new_size);
        }
      self->blocks_end = self->blocks + new_size;
      self->block = self->blocks + old_size;
    }

  self->block->type = type;
  self->block->member_name = 0;
  self->block->value = 0;
  self->block->index = 0;
}
                     
static void
gtk_json_parser_pop_block (GtkJsonParser *self)
{
  g_assert (self->block > self->blocks);
  self->block--;
}

GtkJsonParser *
gtk_json_parser_new_for_string (const char *string,
                                gssize      size)
{
  GtkJsonParser *self;
  GBytes *bytes;

  bytes = g_bytes_new (string, size >= 0 ? size : strlen (string));

  self = gtk_json_parser_new_for_bytes (bytes);

  g_bytes_unref (bytes);

  return self;
}

GtkJsonParser *
gtk_json_parser_new_for_bytes (GBytes *bytes)
{
  GtkJsonParser *self;
  gsize size;

  g_return_val_if_fail (bytes != NULL, NULL);

  self = g_slice_new0 (GtkJsonParser);

  self->bytes = g_bytes_ref (bytes);
  self->reader = g_bytes_get_data (bytes, &size);
  self->end = self->reader + size;

  self->blocks = self->blocks_preallocated;
  self->blocks_end = self->blocks + G_N_ELEMENTS (self->blocks_preallocated);
  self->block = self->blocks;
  self->block->type = GTK_JSON_BLOCK_TOPLEVEL;

  gtk_json_parser_skip_whitespace (self);
  self->block->value = self->reader;
  gtk_json_parser_parse_value (self);

  return self;
}

void
gtk_json_parser_free (GtkJsonParser *self)
{
  if (self == NULL)
    return;

  g_clear_error (&self->error);

  g_bytes_unref (self->bytes);

  if (self->blocks != self->blocks_preallocated)
    g_free (self->blocks);

  g_slice_free (GtkJsonParser, self);
}

static gboolean
gtk_json_parser_skip_block (GtkJsonParser *self)
{
  if (self->reader != self->block->value)
    return TRUE;

  if (*self->reader == '{')
    {
      return gtk_json_parser_start_object (self) &&
             gtk_json_parser_end (self);
    }
  else if (*self->reader == '[')
    {
      return gtk_json_parser_start_array (self) &&
             gtk_json_parser_end (self);
    }
  else
    {
      g_assert_not_reached ();
      return FALSE;
    }
}

gboolean
gtk_json_parser_next (GtkJsonParser *self)
{
  if (self->error)
    return FALSE;

  if (self->block->value == NULL)
    return FALSE;

  if (!gtk_json_parser_skip_block (self))
    {
      g_assert (self->error);
      return FALSE;
    }

  switch (self->block->type)
    {
    case GTK_JSON_BLOCK_TOPLEVEL:
      gtk_json_parser_skip_whitespace (self);
      if (gtk_json_parser_is_eof (self))
        {
          self->block->value = NULL;
          if (gtk_json_parser_remaining (self))
            {
              gtk_json_parser_syntax_error (self, "Unexpected nul byte in document");
            }
        }
      else
        {
          gtk_json_parser_syntax_error (self, "Data at end of document");
        }
      return FALSE;

    case GTK_JSON_BLOCK_OBJECT:
      gtk_json_parser_skip_whitespace (self);
      if (gtk_json_parser_is_eof (self))
        {
          gtk_json_parser_syntax_error (self, "Unexpected end of document");
          self->block->member_name = NULL;
          self->block->value = NULL;
        }
      if (gtk_json_parser_has_char (self, '}'))
        {
          self->block->member_name = NULL;
          self->block->value = NULL;
          return FALSE;
        }
      if (!gtk_json_parser_try_char (self, ','))
        {
          gtk_json_parser_syntax_error (self, "Expected a ',' to separate object members");
          return FALSE;
        }
      gtk_json_parser_skip_whitespace (self);
      self->block->member_name = self->reader;

      if (!gtk_json_parser_parse_string (self))
        return FALSE;
      gtk_json_parser_skip_whitespace (self);
      if (!gtk_json_parser_try_char (self, ':'))
        {
          gtk_json_parser_syntax_error (self, "Missing ':' after member name");
          return FALSE;
        }

      gtk_json_parser_skip_whitespace (self);
      self->block->value = self->reader;
      if (!gtk_json_parser_parse_value (self))
        return FALSE;
      break;

    case GTK_JSON_BLOCK_ARRAY:
      gtk_json_parser_skip_whitespace (self);
      if (gtk_json_parser_is_eof (self))
        {
          gtk_json_parser_syntax_error (self, "Unexpected end of document");
          self->block->member_name = NULL;
          self->block->value = NULL;
        }
      if (gtk_json_parser_has_char (self, ']'))
        {
          self->block->value = NULL;
          return FALSE;
        }

      if (!gtk_json_parser_try_char (self, ','))
        {
          gtk_json_parser_syntax_error (self, "Expected a ',' to separate array members");
          return FALSE;
        }

      gtk_json_parser_skip_whitespace (self);
      self->block->value = self->reader;
      if (!gtk_json_parser_parse_value (self))
        return FALSE;
      break;

    default:
      g_assert_not_reached ();
      break;
    }

  return TRUE;
}

GtkJsonNode
gtk_json_parser_get_node (GtkJsonParser *self)
{
  if (self->error)
    return GTK_JSON_NONE;

  if (self->block->value == NULL)
    return GTK_JSON_NONE;

  return (json_character_table[*self->block->value] & JSON_CHARACTER_NODE_MASK);
}

const GError *
gtk_json_parser_get_error (GtkJsonParser *self)
{
  return self->error;
}

char *
gtk_json_parser_get_member_name (GtkJsonParser *self)
{
  if (self->error)
    return NULL;

  if (self->block->type != GTK_JSON_BLOCK_OBJECT)
    return NULL;

  if (self->block->member_name == NULL)
    return NULL;

  return gtk_json_unescape_string (self->block->member_name);
}

gssize
gtk_json_parser_select_member (GtkJsonParser      *self,
                               const char * const *options)
{
  char *member_name;
  gssize i;

  member_name = gtk_json_parser_get_member_name (self);
  if (member_name == NULL)
    return -1;

  for (i = 0; options[i]; i++)
    {
      if (strcmp (member_name, options[i]) == 0)
        break;
    }
  if (options[i] == NULL)
    i = -1;

  g_free (member_name);

  return i;
}

gboolean
gtk_json_parser_get_boolean (GtkJsonParser *self)
{
  if (self->error)
    return FALSE;

  if (self->block->value == NULL)
    return FALSE;

  if (*self->block->value == 't')
    return TRUE;
  else if (*self->block->value == 'f')
    return FALSE;

  gtk_json_parser_value_error (self, "Expected a boolean value");
  return FALSE;
}

double
gtk_json_parser_get_number (GtkJsonParser *self)
{
  double result;

  if (self->error)
    return 0;

  if (self->block->value == NULL)
    return 0;

  if (!strchr ("-0123456789", *self->block->value))
    {
      gtk_json_parser_value_error (self, "Expected a number");
      return 0;
    }

  errno = 0;
  if (gtk_json_parser_remaining (self) == 0)
    {
      /* need terminated string here */
      char *s = g_strndup ((const char *) self->block->value, self->reader - self->block->value);
      result = g_ascii_strtod (s, NULL);
      g_free (s);
    }
  else
    {
      result = g_ascii_strtod ((const char *) self->block->value, NULL);
    }

  if (errno)
    {
      if (errno == ERANGE)
        gtk_json_parser_value_error (self, "Number out of range");
      else
        gtk_json_parser_value_error (self, "%s", g_strerror (errno));

      return 0;
    }

  return result;
}

int
gtk_json_parser_get_int (GtkJsonParser *self)
{
  int result;

  if (self->error)
    return 0;

  if (self->block->value == NULL)
    return 0;

  if (!strchr ("-0123456789", *self->block->value))
    {
      gtk_json_parser_value_error (self, "Expected a number");
      return 0;
    }

  errno = 0;
  if (gtk_json_parser_remaining (self) == 0)
    {
      /* need terminated string here */
      char *s = g_strndup ((const char *) self->block->value, self->reader - self->block->value);
      result = g_ascii_strtod (s, NULL);
      g_free (s);
    }
  else
    {
      result = (int) g_ascii_strtoll ((const char *) self->block->value, NULL, 10);
    }

  if (errno)
    {
      if (errno == ERANGE)
        gtk_json_parser_value_error (self, "Number out of range");
      else
        gtk_json_parser_value_error (self, "%s", g_strerror (errno));

      return 0;
    }

  return result;
}

#if 0
int                     gtk_json_parser_get_int                 (GtkJsonParser          *self);
guint                   gtk_json_parser_get_uint                (GtkJsonParser          *self);
#endif

char *
gtk_json_parser_get_string (GtkJsonParser *self)
{
  if (self->error)
    return g_strdup ("");

  if (self->block->value == NULL)
    return g_strdup ("");

  if (*self->block->value != '"')
    {
      gtk_json_parser_value_error (self, "Expected a string");
      return g_strdup ("");
    }

  return gtk_json_unescape_string (self->block->value);
}

gboolean
gtk_json_parser_start_object (GtkJsonParser *self)
{
  if (self->error)
    return FALSE;

  if (!gtk_json_parser_try_char (self, '{'))
    {
      gtk_json_parser_value_error (self, "Expected an object");
      return FALSE;
    }

  gtk_json_parser_push_block (self, GTK_JSON_BLOCK_OBJECT);

  gtk_json_parser_skip_whitespace (self);
  if (gtk_json_parser_is_eof (self))
    {
      gtk_json_parser_syntax_error (self, "Unexpected end of document");
      return FALSE;
    }
  if (gtk_json_parser_has_char (self, '}'))
    return TRUE;
  self->block->member_name = self->reader;

  if (!gtk_json_parser_parse_string (self))
    return FALSE;
  gtk_json_parser_skip_whitespace (self);
  if (!gtk_json_parser_try_char (self, ':'))
    {
      gtk_json_parser_syntax_error (self, "Missing ':' after member name");
      return FALSE;
    }

  gtk_json_parser_skip_whitespace (self);
  self->block->value = self->reader;
  if (!gtk_json_parser_parse_value (self))
    return FALSE;

  return TRUE;
}

gboolean
gtk_json_parser_start_array (GtkJsonParser *self)
{
  if (self->error)
    return FALSE;

  if (!gtk_json_parser_try_char (self, '['))
    {
      gtk_json_parser_value_error (self, "Expected an array");
      return FALSE;
    }

  gtk_json_parser_push_block (self, GTK_JSON_BLOCK_ARRAY);
  gtk_json_parser_skip_whitespace (self);
  if (gtk_json_parser_is_eof (self))
    {
      gtk_json_parser_syntax_error (self, "Unexpected end of document");
      return FALSE;
    }
  if (gtk_json_parser_has_char (self, ']'))
    {
      self->block->value = NULL;
      return TRUE;
    }
  self->block->value = self->reader;
  if (!gtk_json_parser_parse_value (self))
    return FALSE;

  return TRUE;
}

gboolean
gtk_json_parser_end (GtkJsonParser *self)
{
  char bracket;

  g_return_val_if_fail (self != NULL, FALSE);

  while (gtk_json_parser_next (self));

  if (self->error)
    return FALSE;

  switch (self->block->type)
    {
    case GTK_JSON_BLOCK_OBJECT:
      bracket = '}';
      break;
    case GTK_JSON_BLOCK_ARRAY:
      bracket = ']';
      break;
    case GTK_JSON_BLOCK_TOPLEVEL:
    default:
      g_return_val_if_reached (FALSE);
    }

  if (!gtk_json_parser_try_char (self, bracket))
    {
      gtk_json_parser_syntax_error (self, "No terminating '%c'", bracket);
      return FALSE;
    }

  gtk_json_parser_pop_block (self);

  return TRUE;
}

void
gtk_json_parser_set_error (GtkJsonParser *self,
                           GError        *error)
{
  if (self->error)
    g_error_free (error);
  else
    self->error = error;
}