-
Notifications
You must be signed in to change notification settings - Fork 344
/
Copy pathparser.c
1365 lines (1171 loc) · 43.8 KB
/
parser.c
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
#include "ruby.h"
#include "ruby/encoding.h"
/* shims */
/* This is the fallback definition from Ruby 3.4 */
#ifndef RBIMPL_STDBOOL_H
#if defined(__cplusplus)
# if defined(HAVE_STDBOOL_H) && (__cplusplus >= 201103L)
# include <cstdbool>
# endif
#elif defined(HAVE_STDBOOL_H)
# include <stdbool.h>
#elif !defined(HAVE__BOOL)
typedef unsigned char _Bool;
# define bool _Bool
# define true ((_Bool)+1)
# define false ((_Bool)+0)
# define __bool_true_false_are_defined
#endif
#endif
#ifndef RB_UNLIKELY
#define RB_UNLIKELY(expr) expr
#endif
#ifndef RB_LIKELY
#define RB_LIKELY(expr) expr
#endif
static VALUE mJSON, eNestingError, Encoding_UTF_8;
static VALUE CNaN, CInfinity, CMinusInfinity;
static ID i_chr, i_aset, i_aref,
i_leftshift, i_new, i_try_convert, i_uminus, i_encode;
static VALUE sym_max_nesting, sym_allow_nan, sym_allow_trailing_comma, sym_symbolize_names, sym_freeze,
sym_decimal_class, sym_on_load;
static int binary_encindex;
static int utf8_encindex;
#ifndef HAVE_RB_HASH_BULK_INSERT
// For TruffleRuby
void
rb_hash_bulk_insert(long count, const VALUE *pairs, VALUE hash)
{
long index = 0;
while (index < count) {
VALUE name = pairs[index++];
VALUE value = pairs[index++];
rb_hash_aset(hash, name, value);
}
RB_GC_GUARD(hash);
}
#endif
#ifndef HAVE_RB_HASH_NEW_CAPA
#define rb_hash_new_capa(n) rb_hash_new()
#endif
/* name cache */
#include <string.h>
#include <ctype.h>
// Object names are likely to be repeated, and are frozen.
// As such we can re-use them if we keep a cache of the ones we've seen so far,
// and save much more expensive lookups into the global fstring table.
// This cache implementation is deliberately simple, as we're optimizing for compactness,
// to be able to fit safely on the stack.
// As such, binary search into a sorted array gives a good tradeoff between compactness and
// performance.
#define JSON_RVALUE_CACHE_CAPA 63
typedef struct rvalue_cache_struct {
int length;
VALUE entries[JSON_RVALUE_CACHE_CAPA];
} rvalue_cache;
static rb_encoding *enc_utf8;
#define JSON_RVALUE_CACHE_MAX_ENTRY_LENGTH 55
static inline VALUE build_interned_string(const char *str, const long length)
{
# ifdef HAVE_RB_ENC_INTERNED_STR
return rb_enc_interned_str(str, length, enc_utf8);
# else
VALUE rstring = rb_utf8_str_new(str, length);
return rb_funcall(rb_str_freeze(rstring), i_uminus, 0);
# endif
}
static inline VALUE build_symbol(const char *str, const long length)
{
return rb_str_intern(build_interned_string(str, length));
}
static void rvalue_cache_insert_at(rvalue_cache *cache, int index, VALUE rstring)
{
MEMMOVE(&cache->entries[index + 1], &cache->entries[index], VALUE, cache->length - index);
cache->length++;
cache->entries[index] = rstring;
}
static inline int rstring_cache_cmp(const char *str, const long length, VALUE rstring)
{
long rstring_length = RSTRING_LEN(rstring);
if (length == rstring_length) {
return memcmp(str, RSTRING_PTR(rstring), length);
} else {
return (int)(length - rstring_length);
}
}
static VALUE rstring_cache_fetch(rvalue_cache *cache, const char *str, const long length)
{
if (RB_UNLIKELY(length > JSON_RVALUE_CACHE_MAX_ENTRY_LENGTH)) {
// Common names aren't likely to be very long. So we just don't
// cache names above an arbitrary threshold.
return Qfalse;
}
if (RB_UNLIKELY(!isalpha((unsigned char)str[0]))) {
// Simple heuristic, if the first character isn't a letter,
// we're much less likely to see this string again.
// We mostly want to cache strings that are likely to be repeated.
return Qfalse;
}
int low = 0;
int high = cache->length - 1;
int mid = 0;
int last_cmp = 0;
while (low <= high) {
mid = (high + low) >> 1;
VALUE entry = cache->entries[mid];
last_cmp = rstring_cache_cmp(str, length, entry);
if (last_cmp == 0) {
return entry;
} else if (last_cmp > 0) {
low = mid + 1;
} else {
high = mid - 1;
}
}
if (RB_UNLIKELY(memchr(str, '\\', length))) {
// We assume the overwhelming majority of names don't need to be escaped.
// But if they do, we have to fallback to the slow path.
return Qfalse;
}
VALUE rstring = build_interned_string(str, length);
if (cache->length < JSON_RVALUE_CACHE_CAPA) {
if (last_cmp > 0) {
mid += 1;
}
rvalue_cache_insert_at(cache, mid, rstring);
}
return rstring;
}
static VALUE rsymbol_cache_fetch(rvalue_cache *cache, const char *str, const long length)
{
if (RB_UNLIKELY(length > JSON_RVALUE_CACHE_MAX_ENTRY_LENGTH)) {
// Common names aren't likely to be very long. So we just don't
// cache names above an arbitrary threshold.
return Qfalse;
}
if (RB_UNLIKELY(!isalpha((unsigned char)str[0]))) {
// Simple heuristic, if the first character isn't a letter,
// we're much less likely to see this string again.
// We mostly want to cache strings that are likely to be repeated.
return Qfalse;
}
int low = 0;
int high = cache->length - 1;
int mid = 0;
int last_cmp = 0;
while (low <= high) {
mid = (high + low) >> 1;
VALUE entry = cache->entries[mid];
last_cmp = rstring_cache_cmp(str, length, rb_sym2str(entry));
if (last_cmp == 0) {
return entry;
} else if (last_cmp > 0) {
low = mid + 1;
} else {
high = mid - 1;
}
}
if (RB_UNLIKELY(memchr(str, '\\', length))) {
// We assume the overwhelming majority of names don't need to be escaped.
// But if they do, we have to fallback to the slow path.
return Qfalse;
}
VALUE rsymbol = build_symbol(str, length);
if (cache->length < JSON_RVALUE_CACHE_CAPA) {
if (last_cmp > 0) {
mid += 1;
}
rvalue_cache_insert_at(cache, mid, rsymbol);
}
return rsymbol;
}
/* rvalue stack */
#define RVALUE_STACK_INITIAL_CAPA 128
enum rvalue_stack_type {
RVALUE_STACK_HEAP_ALLOCATED = 0,
RVALUE_STACK_STACK_ALLOCATED = 1,
};
typedef struct rvalue_stack_struct {
enum rvalue_stack_type type;
long capa;
long head;
VALUE *ptr;
} rvalue_stack;
static rvalue_stack *rvalue_stack_spill(rvalue_stack *old_stack, VALUE *handle, rvalue_stack **stack_ref);
static rvalue_stack *rvalue_stack_grow(rvalue_stack *stack, VALUE *handle, rvalue_stack **stack_ref)
{
long required = stack->capa * 2;
if (stack->type == RVALUE_STACK_STACK_ALLOCATED) {
stack = rvalue_stack_spill(stack, handle, stack_ref);
} else {
REALLOC_N(stack->ptr, VALUE, required);
stack->capa = required;
}
return stack;
}
static VALUE rvalue_stack_push(rvalue_stack *stack, VALUE value, VALUE *handle, rvalue_stack **stack_ref)
{
if (RB_UNLIKELY(stack->head >= stack->capa)) {
stack = rvalue_stack_grow(stack, handle, stack_ref);
}
stack->ptr[stack->head] = value;
stack->head++;
return value;
}
static inline VALUE *rvalue_stack_peek(rvalue_stack *stack, long count)
{
return stack->ptr + (stack->head - count);
}
static inline void rvalue_stack_pop(rvalue_stack *stack, long count)
{
stack->head -= count;
}
static void rvalue_stack_mark(void *ptr)
{
rvalue_stack *stack = (rvalue_stack *)ptr;
long index;
for (index = 0; index < stack->head; index++) {
rb_gc_mark(stack->ptr[index]);
}
}
static void rvalue_stack_free(void *ptr)
{
rvalue_stack *stack = (rvalue_stack *)ptr;
if (stack) {
ruby_xfree(stack->ptr);
ruby_xfree(stack);
}
}
static size_t rvalue_stack_memsize(const void *ptr)
{
const rvalue_stack *stack = (const rvalue_stack *)ptr;
return sizeof(rvalue_stack) + sizeof(VALUE) * stack->capa;
}
static const rb_data_type_t JSON_Parser_rvalue_stack_type = {
"JSON::Ext::Parser/rvalue_stack",
{
.dmark = rvalue_stack_mark,
.dfree = rvalue_stack_free,
.dsize = rvalue_stack_memsize,
},
0, 0,
RUBY_TYPED_FREE_IMMEDIATELY,
};
static rvalue_stack *rvalue_stack_spill(rvalue_stack *old_stack, VALUE *handle, rvalue_stack **stack_ref)
{
rvalue_stack *stack;
*handle = TypedData_Make_Struct(0, rvalue_stack, &JSON_Parser_rvalue_stack_type, stack);
*stack_ref = stack;
MEMCPY(stack, old_stack, rvalue_stack, 1);
stack->capa = old_stack->capa << 1;
stack->ptr = ALLOC_N(VALUE, stack->capa);
stack->type = RVALUE_STACK_HEAP_ALLOCATED;
MEMCPY(stack->ptr, old_stack->ptr, VALUE, old_stack->head);
return stack;
}
static void rvalue_stack_eagerly_release(VALUE handle)
{
if (handle) {
rvalue_stack *stack;
TypedData_Get_Struct(handle, rvalue_stack, &JSON_Parser_rvalue_stack_type, stack);
RTYPEDDATA_DATA(handle) = NULL;
rvalue_stack_free(stack);
}
}
#ifndef HAVE_STRNLEN
static size_t strnlen(const char *s, size_t maxlen)
{
char *p;
return ((p = memchr(s, '\0', maxlen)) ? p - s : maxlen);
}
#endif
#define PARSE_ERROR_FRAGMENT_LEN 32
#ifdef RBIMPL_ATTR_NORETURN
RBIMPL_ATTR_NORETURN()
#endif
static void raise_parse_error(const char *format, const char *start)
{
unsigned char buffer[PARSE_ERROR_FRAGMENT_LEN + 1];
size_t len = start ? strnlen(start, PARSE_ERROR_FRAGMENT_LEN) : 0;
const char *ptr = start;
if (len == PARSE_ERROR_FRAGMENT_LEN) {
MEMCPY(buffer, start, char, PARSE_ERROR_FRAGMENT_LEN);
while (buffer[len - 1] >= 0x80 && buffer[len - 1] < 0xC0) { // Is continuation byte
len--;
}
if (buffer[len - 1] >= 0xC0) { // multibyte character start
len--;
}
buffer[len] = '\0';
ptr = (const char *)buffer;
}
rb_enc_raise(enc_utf8, rb_path2class("JSON::ParserError"), format, ptr);
}
/* unicode */
static const signed char digit_values[256] = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1,
-1, -1, -1, -1, -1, -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1
};
static uint32_t unescape_unicode(const unsigned char *p)
{
signed char b;
uint32_t result = 0;
b = digit_values[p[0]];
if (b < 0) raise_parse_error("incomplete unicode character escape sequence at '%s'", (char *)p - 2);
result = (result << 4) | (unsigned char)b;
b = digit_values[p[1]];
if (b < 0) raise_parse_error("incomplete unicode character escape sequence at '%s'", (char *)p - 2);
result = (result << 4) | (unsigned char)b;
b = digit_values[p[2]];
if (b < 0) raise_parse_error("incomplete unicode character escape sequence at '%s'", (char *)p - 2);
result = (result << 4) | (unsigned char)b;
b = digit_values[p[3]];
if (b < 0) raise_parse_error("incomplete unicode character escape sequence at '%s'", (char *)p - 2);
result = (result << 4) | (unsigned char)b;
return result;
}
static int convert_UTF32_to_UTF8(char *buf, uint32_t ch)
{
int len = 1;
if (ch <= 0x7F) {
buf[0] = (char) ch;
} else if (ch <= 0x07FF) {
buf[0] = (char) ((ch >> 6) | 0xC0);
buf[1] = (char) ((ch & 0x3F) | 0x80);
len++;
} else if (ch <= 0xFFFF) {
buf[0] = (char) ((ch >> 12) | 0xE0);
buf[1] = (char) (((ch >> 6) & 0x3F) | 0x80);
buf[2] = (char) ((ch & 0x3F) | 0x80);
len += 2;
} else if (ch <= 0x1fffff) {
buf[0] =(char) ((ch >> 18) | 0xF0);
buf[1] =(char) (((ch >> 12) & 0x3F) | 0x80);
buf[2] =(char) (((ch >> 6) & 0x3F) | 0x80);
buf[3] =(char) ((ch & 0x3F) | 0x80);
len += 3;
} else {
buf[0] = '?';
}
return len;
}
typedef struct JSON_ParserStruct {
VALUE on_load_proc;
VALUE decimal_class;
ID decimal_method_id;
int max_nesting;
bool allow_nan;
bool allow_trailing_comma;
bool parsing_name;
bool symbolize_names;
bool freeze;
} JSON_ParserConfig;
typedef struct JSON_ParserStateStruct {
VALUE stack_handle;
const char *cursor;
const char *end;
rvalue_stack *stack;
rvalue_cache name_cache;
int in_array;
int current_nesting;
} JSON_ParserState;
#define GET_PARSER_CONFIG \
JSON_ParserConfig *config; \
TypedData_Get_Struct(self, JSON_ParserConfig, &JSON_ParserConfig_type, config)
static const rb_data_type_t JSON_ParserConfig_type;
static const bool whitespace[256] = {
[' '] = 1,
['\t'] = 1,
['\n'] = 1,
['\r'] = 1,
['/'] = 1,
};
static void
json_eat_comments(JSON_ParserState *state)
{
if (state->cursor + 1 < state->end) {
switch(state->cursor[1]) {
case '/': {
state->cursor = memchr(state->cursor, '\n', state->end - state->cursor);
if (!state->cursor) {
state->cursor = state->end;
} else {
state->cursor++;
}
break;
}
case '*': {
state->cursor += 2;
while (true) {
state->cursor = memchr(state->cursor, '*', state->end - state->cursor);
if (!state->cursor) {
state->cursor = state->end;
raise_parse_error("unexpected end of input, expected closing '*/'", state->cursor);
} else {
state->cursor++;
if (state->cursor < state->end && *state->cursor == '/') {
state->cursor++;
break;
}
}
}
break;
}
default:
raise_parse_error("unexpected token at '%s'", state->cursor);
break;
}
} else {
raise_parse_error("unexpected token at '%s'", state->cursor);
}
}
static inline void
json_eat_whitespace(JSON_ParserState *state)
{
while (state->cursor < state->end && RB_UNLIKELY(whitespace[(unsigned char)*state->cursor])) {
if (RB_LIKELY(*state->cursor != '/')) {
state->cursor++;
} else {
json_eat_comments(state);
}
}
}
static inline VALUE build_string(const char *start, const char *end, bool intern, bool symbolize)
{
if (symbolize) {
intern = true;
}
VALUE result;
# ifdef HAVE_RB_ENC_INTERNED_STR
if (intern) {
result = rb_enc_interned_str(start, (long)(end - start), enc_utf8);
} else {
result = rb_utf8_str_new(start, (long)(end - start));
}
# else
result = rb_utf8_str_new(start, (long)(end - start));
if (intern) {
result = rb_funcall(rb_str_freeze(result), i_uminus, 0);
}
# endif
if (symbolize) {
result = rb_str_intern(result);
}
return result;
}
static inline VALUE json_string_fastpath(JSON_ParserState *state, const char *string, const char *stringEnd, bool is_name, bool intern, bool symbolize)
{
size_t bufferSize = stringEnd - string;
if (is_name && state->in_array) {
VALUE cached_key;
if (RB_UNLIKELY(symbolize)) {
cached_key = rsymbol_cache_fetch(&state->name_cache, string, bufferSize);
} else {
cached_key = rstring_cache_fetch(&state->name_cache, string, bufferSize);
}
if (RB_LIKELY(cached_key)) {
return cached_key;
}
}
return build_string(string, stringEnd, intern, symbolize);
}
static VALUE json_string_unescape(JSON_ParserState *state, const char *string, const char *stringEnd, bool is_name, bool intern, bool symbolize)
{
size_t bufferSize = stringEnd - string;
const char *p = string, *pe = string, *unescape, *bufferStart;
char *buffer;
int unescape_len;
char buf[4];
if (is_name && state->in_array) {
VALUE cached_key;
if (RB_UNLIKELY(symbolize)) {
cached_key = rsymbol_cache_fetch(&state->name_cache, string, bufferSize);
} else {
cached_key = rstring_cache_fetch(&state->name_cache, string, bufferSize);
}
if (RB_LIKELY(cached_key)) {
return cached_key;
}
}
VALUE result = rb_str_buf_new(bufferSize);
rb_enc_associate_index(result, utf8_encindex);
buffer = RSTRING_PTR(result);
bufferStart = buffer;
while (pe < stringEnd && (pe = memchr(pe, '\\', stringEnd - pe))) {
unescape = (char *) "?";
unescape_len = 1;
if (pe > p) {
MEMCPY(buffer, p, char, pe - p);
buffer += pe - p;
}
switch (*++pe) {
case 'n':
unescape = (char *) "\n";
break;
case 'r':
unescape = (char *) "\r";
break;
case 't':
unescape = (char *) "\t";
break;
case '"':
unescape = (char *) "\"";
break;
case '\\':
unescape = (char *) "\\";
break;
case 'b':
unescape = (char *) "\b";
break;
case 'f':
unescape = (char *) "\f";
break;
case 'u':
if (pe > stringEnd - 5) {
raise_parse_error("incomplete unicode character escape sequence at '%s'", p);
} else {
uint32_t ch = unescape_unicode((unsigned char *) ++pe);
pe += 3;
/* To handle values above U+FFFF, we take a sequence of
* \uXXXX escapes in the U+D800..U+DBFF then
* U+DC00..U+DFFF ranges, take the low 10 bits from each
* to make a 20-bit number, then add 0x10000 to get the
* final codepoint.
*
* See Unicode 15: 3.8 "Surrogates", 5.3 "Handling
* Surrogate Pairs in UTF-16", and 23.6 "Surrogates
* Area".
*/
if ((ch & 0xFC00) == 0xD800) {
pe++;
if (pe > stringEnd - 6) {
raise_parse_error("incomplete surrogate pair at '%s'", p);
}
if (pe[0] == '\\' && pe[1] == 'u') {
uint32_t sur = unescape_unicode((unsigned char *) pe + 2);
ch = (((ch & 0x3F) << 10) | ((((ch >> 6) & 0xF) + 1) << 16)
| (sur & 0x3FF));
pe += 5;
} else {
unescape = (char *) "?";
break;
}
}
unescape_len = convert_UTF32_to_UTF8(buf, ch);
unescape = buf;
}
break;
default:
p = pe;
continue;
}
MEMCPY(buffer, unescape, char, unescape_len);
buffer += unescape_len;
p = ++pe;
}
if (stringEnd > p) {
MEMCPY(buffer, p, char, stringEnd - p);
buffer += stringEnd - p;
}
rb_str_set_len(result, buffer - bufferStart);
if (symbolize) {
result = rb_str_intern(result);
} else if (intern) {
result = rb_funcall(rb_str_freeze(result), i_uminus, 0);
}
return result;
}
#define MAX_FAST_INTEGER_SIZE 18
static inline VALUE fast_decode_integer(const char *p, const char *pe)
{
bool negative = false;
if (*p == '-') {
negative = true;
p++;
}
long long memo = 0;
while (p < pe) {
memo *= 10;
memo += *p - '0';
p++;
}
if (negative) {
memo = -memo;
}
return LL2NUM(memo);
}
static VALUE json_decode_large_integer(const char *start, long len)
{
VALUE buffer_v;
char *buffer = RB_ALLOCV_N(char, buffer_v, len + 1);
MEMCPY(buffer, start, char, len);
buffer[len] = '\0';
VALUE number = rb_cstr2inum(buffer, 10);
RB_ALLOCV_END(buffer_v);
return number;
}
static inline VALUE
json_decode_integer(const char *start, const char *end)
{
long len = end - start;
if (RB_LIKELY(len < MAX_FAST_INTEGER_SIZE)) {
return fast_decode_integer(start, end);
}
return json_decode_large_integer(start, len);
}
static VALUE json_decode_large_float(const char *start, long len)
{
VALUE buffer_v;
char *buffer = RB_ALLOCV_N(char, buffer_v, len + 1);
MEMCPY(buffer, start, char, len);
buffer[len] = '\0';
VALUE number = DBL2NUM(rb_cstr_to_dbl(buffer, 1));
RB_ALLOCV_END(buffer_v);
return number;
}
static VALUE json_decode_float(JSON_ParserConfig *config, const char *start, const char *end)
{
long len = end - start;
if (RB_UNLIKELY(config->decimal_class)) {
VALUE text = rb_str_new(start, len);
return rb_funcallv(config->decimal_class, config->decimal_method_id, 1, &text);
} else if (RB_LIKELY(len < 64)) {
char buffer[64];
MEMCPY(buffer, start, char, len);
buffer[len] = '\0';
return DBL2NUM(rb_cstr_to_dbl(buffer, 1));
} else {
return json_decode_large_float(start, len);
}
}
static inline VALUE json_decode_array(JSON_ParserState *state, JSON_ParserConfig *config, long count)
{
VALUE array = rb_ary_new_from_values(count, rvalue_stack_peek(state->stack, count));
rvalue_stack_pop(state->stack, count);
if (config->freeze) {
RB_OBJ_FREEZE(array);
}
return array;
}
static inline VALUE json_decode_object(JSON_ParserState *state, JSON_ParserConfig *config, long count)
{
VALUE object = rb_hash_new_capa(count);
rb_hash_bulk_insert(count, rvalue_stack_peek(state->stack, count), object);
rvalue_stack_pop(state->stack, count);
if (config->freeze) {
RB_OBJ_FREEZE(object);
}
return object;
}
static inline VALUE json_decode_string(JSON_ParserState *state, JSON_ParserConfig *config, const char *start, const char *end, bool escaped, bool is_name)
{
VALUE string;
bool intern = is_name || config->freeze;
bool symbolize = is_name && config->symbolize_names;
if (escaped) {
string = json_string_unescape(state, start, end, is_name, intern, symbolize);
} else {
string = json_string_fastpath(state, start, end, is_name, intern, symbolize);
}
return string;
}
static inline VALUE json_push_value(JSON_ParserState *state, JSON_ParserConfig *config, VALUE value)
{
if (RB_UNLIKELY(config->on_load_proc)) {
value = rb_proc_call_with_block(config->on_load_proc, 1, &value, Qnil);
}
rvalue_stack_push(state->stack, value, &state->stack_handle, &state->stack);
return value;
}
static const bool string_scan[256] = {
// ASCII Control Characters
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
// ASCII Characters
0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // '"'
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, // '\\'
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
};
static inline VALUE json_parse_string(JSON_ParserState *state, JSON_ParserConfig *config, bool is_name)
{
state->cursor++;
const char *start = state->cursor;
bool escaped = false;
while (state->cursor < state->end) {
if (RB_UNLIKELY(string_scan[(unsigned char)*state->cursor])) {
switch (*state->cursor) {
case '"': {
VALUE string = json_decode_string(state, config, start, state->cursor, escaped, is_name);
state->cursor++;
return json_push_value(state, config, string);
}
case '\\': {
state->cursor++;
escaped = true;
if ((unsigned char)*state->cursor < 0x20) {
raise_parse_error("invalid ASCII control character in string: %s", state->cursor);
}
break;
}
default:
raise_parse_error("invalid ASCII control character in string: %s", state->cursor);
break;
}
}
state->cursor++;
}
raise_parse_error("unexpected end of input, expected closing \"", state->cursor);
return Qfalse;
}
static VALUE json_parse_any(JSON_ParserState *state, JSON_ParserConfig *config)
{
json_eat_whitespace(state);
if (state->cursor >= state->end) {
raise_parse_error("unexpected end of input", state->cursor);
}
switch (*state->cursor) {
case 'n':
if ((state->end - state->cursor >= 4) && (memcmp(state->cursor, "null", 4) == 0)) {
state->cursor += 4;
return json_push_value(state, config, Qnil);
}
raise_parse_error("unexpected token at '%s'", state->cursor);
break;
case 't':
if ((state->end - state->cursor >= 4) && (memcmp(state->cursor, "true", 4) == 0)) {
state->cursor += 4;
return json_push_value(state, config, Qtrue);
}
raise_parse_error("unexpected token at '%s'", state->cursor);
break;
case 'f':
// Note: memcmp with a small power of two compile to an integer comparison
if ((state->end - state->cursor >= 5) && (memcmp(state->cursor + 1, "alse", 4) == 0)) {
state->cursor += 5;
return json_push_value(state, config, Qfalse);
}
raise_parse_error("unexpected token at '%s'", state->cursor);
break;
case 'N':
// Note: memcmp with a small power of two compile to an integer comparison
if (config->allow_nan && (state->end - state->cursor >= 3) && (memcmp(state->cursor + 1, "aN", 2) == 0)) {
state->cursor += 3;
return json_push_value(state, config, CNaN);
}
raise_parse_error("unexpected token at '%s'", state->cursor);
break;
case 'I':
if (config->allow_nan && (state->end - state->cursor >= 8) && (memcmp(state->cursor, "Infinity", 8) == 0)) {
state->cursor += 8;
return json_push_value(state, config, CInfinity);
}
raise_parse_error("unexpected token at '%s'", state->cursor);
break;
case '-':
// Note: memcmp with a small power of two compile to an integer comparison
if ((state->end - state->cursor >= 9) && (memcmp(state->cursor + 1, "Infinity", 8) == 0)) {
if (config->allow_nan) {
state->cursor += 9;
return json_push_value(state, config, CMinusInfinity);
} else {
raise_parse_error("unexpected token at '%s'", state->cursor);
}
}
// Fallthrough
case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': {
bool integer = true;
// /\A-?(0|[1-9]\d*)(\.\d+)?([Ee][-+]?\d+)?/
const char *start = state->cursor;
state->cursor++;
while ((state->cursor < state->end) && (*state->cursor >= '0') && (*state->cursor <= '9')) {
state->cursor++;
}
long integer_length = state->cursor - start;
if (RB_UNLIKELY(start[0] == '0' && integer_length > 1)) {
raise_parse_error("invalid number: %s", start);
} else if (RB_UNLIKELY(integer_length > 2 && start[0] == '-' && start[1] == '0')) {
raise_parse_error("invalid number: %s", start);
} else if (RB_UNLIKELY(integer_length == 1 && start[0] == '-')) {
raise_parse_error("invalid number: %s", start);
}
if ((state->cursor < state->end) && (*state->cursor == '.')) {
integer = false;
state->cursor++;
if (state->cursor == state->end || *state->cursor < '0' || *state->cursor > '9') {
raise_parse_error("invalid number: %s", state->cursor);
}
while ((state->cursor < state->end) && (*state->cursor >= '0') && (*state->cursor <= '9')) {
state->cursor++;
}
}
if ((state->cursor < state->end) && ((*state->cursor == 'e') || (*state->cursor == 'E'))) {
integer = false;
state->cursor++;
if ((state->cursor < state->end) && ((*state->cursor == '+') || (*state->cursor == '-'))) {
state->cursor++;
}
if (state->cursor == state->end || *state->cursor < '0' || *state->cursor > '9') {
raise_parse_error("invalid number: %s", state->cursor);
}
while ((state->cursor < state->end) && (*state->cursor >= '0') && (*state->cursor <= '9')) {
state->cursor++;
}
}
if (integer) {
return json_push_value(state, config, json_decode_integer(start, state->cursor));
}
return json_push_value(state, config, json_decode_float(config, start, state->cursor));
}
case '"': {
// %r{\A"[^"\\\t\n\x00]*(?:\\[bfnrtu\\/"][^"\\]*)*"}
return json_parse_string(state, config, false);
break;
}
case '[': {
state->cursor++;
json_eat_whitespace(state);
long stack_head = state->stack->head;
if ((state->cursor < state->end) && (*state->cursor == ']')) {
state->cursor++;
return json_push_value(state, config, json_decode_array(state, config, 0));
} else {
state->current_nesting++;
if (RB_UNLIKELY(config->max_nesting && (config->max_nesting < state->current_nesting))) {
rb_raise(eNestingError, "nesting of %d is too deep", state->current_nesting);
}
state->in_array++;
json_parse_any(state, config);
}
while (true) {
json_eat_whitespace(state);
if (state->cursor < state->end) {
if (*state->cursor == ']') {
state->cursor++;
long count = state->stack->head - stack_head;
state->current_nesting--;
state->in_array--;
return json_push_value(state, config, json_decode_array(state, config, count));
}
if (*state->cursor == ',') {
state->cursor++;