-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathparser.c
More file actions
2839 lines (2422 loc) · 92.3 KB
/
Copy pathparser.c
File metadata and controls
2839 lines (2422 loc) · 92.3 KB
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 "../json.h"
#include "../vendor/fast_float_parser.h"
#include "../simd/simd.h"
static VALUE mJSON, eNestingError, eParserError, Encoding_UTF_8;
static VALUE CNaN, CInfinity, CMinusInfinity, JSON_empty_string;
static ID i_new, i_try_convert, i_encode, i_at_line, i_at_column;
#ifndef HAVE_RB_STR_TO_INTERNED_STR
static ID i_uminus;
#endif
static VALUE sym_max_nesting, sym_allow_nan, sym_allow_trailing_comma, sym_allow_comments,
sym_allow_control_characters, sym_allow_invalid_escape, sym_symbolize_names,
sym_freeze, sym_decimal_class, sym_on_load, sym_allow_duplicate_key;
static int binary_encindex;
static int utf8_encindex;
#ifndef HAVE_RB_HASH_BULK_INSERT
// For TruffleRuby
static 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
#ifndef HAVE_RB_STR_TO_INTERNED_STR
static VALUE rb_str_to_interned_str(VALUE str)
{
return rb_funcall(rb_str_freeze(str), i_uminus, 0);
}
#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 void rvalue_cache_mark(rvalue_cache *cache)
{
for (int index = 0; index < cache->length; index++) {
rb_gc_mark_movable(cache->entries[index]);
}
}
static void rvalue_cache_compact(rvalue_cache *cache)
{
for (int index = 0; index < cache->length; index++) {
cache->entries[index] = rb_gc_location(cache->entries[index]);
}
}
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;
}
#define rstring_cache_memcmp memcmp
#if JSON_CPU_LITTLE_ENDIAN_64BITS
#if __has_builtin(__builtin_bswap64)
#undef rstring_cache_memcmp
ALWAYS_INLINE(static) int rstring_cache_memcmp(const char *str, const char *rptr, const long length)
{
// The libc memcmp has numerous complex optimizations, but in this particular case,
// we know the string is small (JSON_RVALUE_CACHE_MAX_ENTRY_LENGTH), so being able to
// inline a simpler memcmp outperforms calling the libc version.
long i = 0;
for (; i + 8 <= length; i += 8) {
uint64_t a, b;
memcpy(&a, str + i, 8);
memcpy(&b, rptr + i, 8);
if (a != b) {
a = __builtin_bswap64(a);
b = __builtin_bswap64(b);
return (a < b) ? -1 : 1;
}
}
for (; i < length; i++) {
if (str[i] != rptr[i]) {
return (str[i] < rptr[i]) ? -1 : 1;
}
}
return 0;
}
#endif
#endif
ALWAYS_INLINE(static) int rstring_cache_cmp(const char *str, const long length, VALUE rstring)
{
const char *rstring_ptr;
long rstring_length;
RSTRING_GETMEM(rstring, rstring_ptr, rstring_length);
if (length == rstring_length) {
return rstring_cache_memcmp(str, rstring_ptr, length);
} else {
return (int)(length - rstring_length);
}
}
ALWAYS_INLINE(static) VALUE rstring_cache_fetch(rvalue_cache *cache, const char *str, const long length)
{
int low = 0;
int high = cache->length - 1;
while (low <= high) {
int mid = (high + low) >> 1;
VALUE entry = cache->entries[mid];
int cmp = rstring_cache_cmp(str, length, entry);
if (cmp == 0) {
return entry;
} else if (cmp > 0) {
low = mid + 1;
} else {
high = mid - 1;
}
}
VALUE rstring = build_interned_string(str, length);
if (cache->length < JSON_RVALUE_CACHE_CAPA) {
rvalue_cache_insert_at(cache, low, rstring);
}
return rstring;
}
static VALUE rsymbol_cache_fetch(rvalue_cache *cache, const char *str, const long length)
{
int low = 0;
int high = cache->length - 1;
while (low <= high) {
int mid = (high + low) >> 1;
VALUE entry = cache->entries[mid];
int cmp = rstring_cache_cmp(str, length, rb_sym2str(entry));
if (cmp == 0) {
return entry;
} else if (cmp > 0) {
low = mid + 1;
} else {
high = mid - 1;
}
}
VALUE rsymbol = build_symbol(str, length);
if (cache->length < JSON_RVALUE_CACHE_CAPA) {
rvalue_cache_insert_at(cache, low, 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 ? stack->capa * 2 : RVALUE_STACK_INITIAL_CAPA;
if (stack->type == RVALUE_STACK_STACK_ALLOCATED) {
stack = rvalue_stack_spill(stack, handle, stack_ref);
} else {
JSON_SIZED_REALLOC_N(stack->ptr, VALUE, required, stack->capa);
stack->capa = required;
}
return stack;
}
static VALUE rvalue_stack_push(rvalue_stack *stack, VALUE value, VALUE *handle, rvalue_stack **stack_ref)
{
JSON_ASSERT(stack->type != RVALUE_STACK_STACK_ALLOCATED || handle);
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;
if (stack && stack->ptr) {
for (index = 0; index < stack->head; index++) {
rb_gc_mark_movable(stack->ptr[index]);
}
}
}
static void rvalue_stack_free_buffer(rvalue_stack *stack)
{
JSON_SIZED_FREE_N(stack->ptr, stack->capa);
stack->ptr = NULL;
}
static void rvalue_stack_free(void *ptr)
{
rvalue_stack *stack = (rvalue_stack *)ptr;
if (stack) {
rvalue_stack_free_buffer(stack);
#ifndef HAVE_RUBY_TYPED_EMBEDDABLE
JSON_SIZED_FREE(stack);
#endif
}
}
static size_t rvalue_stack_memsize(const void *ptr)
{
const rvalue_stack *stack = (const rvalue_stack *)ptr;
size_t memsize = sizeof(VALUE) * stack->capa;
#ifndef HAVE_RUBY_TYPED_EMBEDDABLE
memsize += sizeof(rvalue_stack);
#endif
return memsize;
}
static void rvalue_stack_compact(void *ptr)
{
rvalue_stack *stack = (rvalue_stack *)ptr;
long index;
if (stack && stack->ptr) {
for (index = 0; index < stack->head; index++) {
stack->ptr[index] = rb_gc_location(stack->ptr[index]);
}
}
}
static const rb_data_type_t JSON_Parser_rvalue_stack_type = {
.wrap_struct_name = "JSON::Ext::Parser/rvalue_stack",
.function = {
.dmark = rvalue_stack_mark,
.dfree = rvalue_stack_free,
.dsize = rvalue_stack_memsize,
.dcompact = rvalue_stack_compact,
},
// We deliberately don't declare rvalue_stack as RUBY_TYPED_WB_PROTECTED
// because it churns a lot of values so trigering write barriers every time is very costly.
.flags = RUBY_TYPED_THREAD_SAFE_FREE | RUBY_TYPED_EMBEDDABLE,
};
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);
#ifdef HAVE_RUBY_TYPED_EMBEDDABLE
rvalue_stack_free_buffer(stack);
#else
rvalue_stack_free(stack);
RTYPEDDATA_DATA(handle) = NULL;
#endif
}
}
/* frame stack */
// Iterative (non-recursive) parsing keeps an explicit stack of the containers
// currently being built, instead of relying on the C call stack. Each frame
// only needs enough bookkeeping to close its container: which kind it is, the
// rvalue_stack position where its children start (so we know how many to pop),
// and the cursor at its opening brace (used to rewind for duplicate key
// errors). Frames hold no VALUEs, so this stack needs no GC marking; it reuses
// the same stack-allocated-with-heap-spill strategy as the rvalue_stack so that
// it's freed even if parsing raises.
//
// The lifecycle helpers below (grow/push/peek/pop/spill/free/eagerly_release
// and the rb_data_type_t) deliberately mirror their rvalue_stack counterparts
// -- the element type and the absence of a mark function are the only real
// differences. Keep the two in sync: a fix to the spill/release or
// HAVE_RUBY_TYPED_EMBEDDABLE handling in one almost certainly belongs in the
// other.
#define JSON_FRAME_STACK_INITIAL_CAPA 32
enum json_frame_type {
JSON_FRAME_ROOT, // == JSON_PHASE_DONE
JSON_FRAME_ARRAY, // == JSON_PHASE_ARRAY_COMMA
JSON_FRAME_OBJECT, // = JSON_PHASE_OBJECT_COMMA
};
// Where a frame is within its container's grammar. This is the entirety of the
// parser's "what to do next" state: json_parse_any dispatches on the top
// frame's phase and holds no resume state in C locals, so a parse can stop at
// any value boundary and be resumed purely from the (persistable) frame stack.
//
// The first three phases are deliberately equal to the corresponding json_frame_type
// to simplify the transition of phase in json_value_completed.
enum json_frame_phase {
JSON_PHASE_DONE = JSON_FRAME_ROOT, // root only: the document value has been parsed
JSON_PHASE_ARRAY_COMMA = JSON_FRAME_ARRAY, // after a value: expecting ',' or the closing ']'
JSON_PHASE_OBJECT_COMMA = JSON_FRAME_OBJECT, // after a value: expecting ',' or the closing '}'
JSON_PHASE_VALUE, // expecting a value (document root, array element, or object value after ':')
JSON_PHASE_OBJECT_KEY, // expecting a '"' key (after '{' or ',')
JSON_PHASE_OBJECT_COLON, // object only: after a key, expecting ':'
};
typedef struct json_frame_struct {
enum json_frame_type type;
enum json_frame_phase phase;
long value_stack_head; // rvalue_stack->head when this container opened
size_t start_offset; // object frames only (the '{'); NULL otherwise
} json_frame;
typedef struct json_frame_stack_struct {
enum rvalue_stack_type type; // shared with rvalue_stack: is ptr stack- or heap-allocated
long capa;
long head;
json_frame *ptr;
} json_frame_stack;
enum deprecatable_action {
JSON_DEPRECATED = 0,
JSON_IGNORE,
JSON_RAISE,
};
typedef struct JSON_ParserStruct {
VALUE on_load_proc;
VALUE decimal_class;
ID decimal_method_id;
enum deprecatable_action on_duplicate_key;
enum deprecatable_action on_comment;
int max_nesting;
bool allow_nan;
bool allow_trailing_comma;
bool allow_control_characters;
bool allow_invalid_escape;
bool symbolize_names;
bool freeze;
} JSON_ParserConfig;
typedef struct JSON_ParserStateStruct {
VALUE *value_stack_handle;
VALUE *frame_stack_handle;
const char *start;
const char *cursor;
const char *end;
rvalue_stack *value_stack;
json_frame_stack *frames;
rvalue_cache name_cache;
int in_array;
int current_nesting;
unsigned int emitted_deprecations;
VALUE parser;
} JSON_ParserState;
static json_frame_stack *json_frame_stack_spill(json_frame_stack *old_stack, VALUE *handle, json_frame_stack **stack_ref);
static json_frame_stack *json_frame_stack_grow(json_frame_stack *stack, VALUE *handle, json_frame_stack **stack_ref)
{
long required = stack->capa ? stack->capa * 2 : JSON_FRAME_STACK_INITIAL_CAPA;
if (stack->type == RVALUE_STACK_STACK_ALLOCATED) {
stack = json_frame_stack_spill(stack, handle, stack_ref);
} else {
JSON_SIZED_REALLOC_N(stack->ptr, json_frame, required, stack->capa);
stack->capa = required;
}
return stack;
}
static json_frame *json_frame_stack_push(JSON_ParserState *state, json_frame frame)
{
json_frame_stack *stack = state->frames;
JSON_ASSERT(stack->type != RVALUE_STACK_STACK_ALLOCATED || state->frame_stack_handle);
if (RB_UNLIKELY(stack->head >= stack->capa)) {
stack = json_frame_stack_grow(stack, state->frame_stack_handle, &state->frames);
}
json_frame *frame_ptr = &stack->ptr[stack->head++];
*frame_ptr = frame;
return frame_ptr;
}
static inline json_frame *json_frame_stack_peek(json_frame_stack *stack)
{
return &stack->ptr[stack->head - 1];
}
static inline void json_frame_stack_pop(json_frame_stack *stack)
{
stack->head--;
}
static void json_frame_stack_free_buffer(json_frame_stack *stack)
{
JSON_SIZED_FREE_N(stack->ptr, stack->capa);
stack->ptr = NULL;
}
static void json_frame_stack_free(void *ptr)
{
json_frame_stack *stack = (json_frame_stack *)ptr;
if (stack) {
json_frame_stack_free_buffer(stack);
#ifndef HAVE_RUBY_TYPED_EMBEDDABLE
JSON_SIZED_FREE(stack);
#endif
}
}
static size_t json_frame_stack_memsize(const void *ptr)
{
const json_frame_stack *stack = (const json_frame_stack *)ptr;
size_t memsize = sizeof(json_frame) * stack->capa;
#ifndef HAVE_RUBY_TYPED_EMBEDDABLE
memsize += sizeof(json_frame_stack);
#endif
return memsize;
}
static const rb_data_type_t JSON_Parser_frame_stack_type = {
.wrap_struct_name = "JSON::Ext::Parser/frame_stack",
.function = {
.dmark = NULL,
.dfree = json_frame_stack_free,
.dsize = json_frame_stack_memsize,
},
.flags = RUBY_TYPED_THREAD_SAFE_FREE | RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_EMBEDDABLE,
};
static json_frame_stack *json_frame_stack_spill(json_frame_stack *old_stack, VALUE *handle, json_frame_stack **stack_ref)
{
json_frame_stack *stack;
*handle = TypedData_Make_Struct(0, json_frame_stack, &JSON_Parser_frame_stack_type, stack);
*stack_ref = stack;
MEMCPY(stack, old_stack, json_frame_stack, 1);
stack->capa = old_stack->capa << 1;
stack->ptr = ALLOC_N(json_frame, stack->capa);
stack->type = RVALUE_STACK_HEAP_ALLOCATED;
MEMCPY(stack->ptr, old_stack->ptr, json_frame, old_stack->head);
return stack;
}
static void json_frame_stack_eagerly_release(VALUE handle)
{
if (handle) {
json_frame_stack *stack;
TypedData_Get_Struct(handle, json_frame_stack, &JSON_Parser_frame_stack_type, stack);
#ifdef HAVE_RUBY_TYPED_EMBEDDABLE
json_frame_stack_free_buffer(stack);
#else
json_frame_stack_free(stack);
RTYPEDDATA_DATA(handle) = NULL;
#endif
}
}
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;
}
static inline size_t rest(JSON_ParserState *state) {
return state->end - state->cursor;
}
static inline bool eos(JSON_ParserState *state) {
return state->cursor >= state->end;
}
static inline char peek(JSON_ParserState *state)
{
if (RB_UNLIKELY(eos(state))) {
return 0;
}
return *state->cursor;
}
static void cursor_position(JSON_ParserState *state, long *line_out, long *column_out)
{
JSON_ASSERT(state->cursor <= state->end);
// Redundant but helpful for hardening
if (RB_UNLIKELY(state->cursor > state->end)) {
state->cursor = state->end;
}
const char *cursor = state->cursor;
long column = 0;
long line = 1;
while (cursor >= state->start) {
if (*cursor-- == '\n') {
line++;
break;
}
column++;
}
while (cursor >= state->start) {
if (*cursor-- == '\n') {
line++;
}
}
*line_out = line;
*column_out = column;
}
static const unsigned int MAX_DEPRECATIONS = 5;
static void emit_parse_warning(const char *message, JSON_ParserState *state)
{
long line, column;
cursor_position(state, &line, &column);
VALUE warning = rb_sprintf("%s at line %ld column %ld", message, line, column);
rb_funcall(mJSON, rb_intern("deprecation_warning"), 1, warning);
}
#define PARSE_ERROR_FRAGMENT_LEN 32
static VALUE build_parse_error_message(const char *format, JSON_ParserState *state)
{
unsigned char buffer[PARSE_ERROR_FRAGMENT_LEN + 3];
const char *ptr = "EOF";
if (state->cursor && state->cursor < state->end) {
ptr = state->cursor;
size_t len = 0;
while (len < PARSE_ERROR_FRAGMENT_LEN) {
char ch = ptr[len];
if (!ch || ch == '\n' || ch == ' ' || ch == '\t' || ch == '\r') {
break;
}
len++;
}
if (len) {
buffer[0] = '\'';
MEMCPY(buffer + 1, ptr, char, len);
while (buffer[len] >= 0x80 && buffer[len] < 0xC0) { // Is continuation byte
len--;
}
if (buffer[len] >= 0xC0) { // multibyte character start
len--;
}
buffer[len + 1] = '\'';
buffer[len + 2] = '\0';
ptr = (const char *)buffer;
}
}
return rb_enc_sprintf(enc_utf8, format, ptr);
}
static VALUE parse_error_new(JSON_ParserState *state, VALUE message, long line, long column, bool eos)
{
VALUE exc = rb_exc_new_str(eParserError, message);
rb_ivar_set(exc, i_at_line, LONG2NUM(line));
rb_ivar_set(exc, i_at_column, LONG2NUM(column));
return exc;
}
NORETURN(static) void raise_parse_error(const char *format, JSON_ParserState *state, bool eos)
{
if (state->parser) {
if (eos) {
// the error will be swallowed by ResumableParser#parse, so no
// point building a message or backtrace.
rb_throw_obj(state->parser, state->parser);
} else {
// line and columns can't be accurate in resumable
rb_exc_raise(parse_error_new(state, build_parse_error_message(format, state), 0, 0, eos));
}
} else {
VALUE message = build_parse_error_message(format, state);
long line, column;
cursor_position(state, &line, &column);
rb_str_catf(message, " at line %ld column %ld", line, column);
rb_exc_raise(parse_error_new(state, message, line, column, eos));
}
}
NORETURN(static) void raise_eos_error(const char *format, JSON_ParserState *state)
{
raise_parse_error(format, state, true);
}
NORETURN(static) void raise_syntax_error(const char *format, JSON_ParserState *state)
{
raise_parse_error(format, state, false);
}
NORETURN(static) void raise_parse_error_at(const char *format, JSON_ParserState *state, const char *at, bool eos)
{
state->cursor = at;
raise_parse_error(format, state, eos);
}
NORETURN(static) void raise_eos_error_at(const char *format, JSON_ParserState *state, const char *at)
{
raise_parse_error_at(format, state, at, true);
}
NORETURN(static) void raise_syntax_error_at(const char *format, JSON_ParserState *state, const char *at)
{
raise_parse_error_at(format, state, at, false);
}
/* 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(JSON_ParserState *state, const char *sp, const char *spe)
{
if (RB_UNLIKELY(sp > spe - 4)) {
raise_eos_error_at("incomplete unicode character escape sequence at %s", state, sp - 2);
}
const unsigned char *p = (const unsigned char *)sp;
const signed char b0 = digit_values[p[0]];
const signed char b1 = digit_values[p[1]];
const signed char b2 = digit_values[p[2]];
const signed char b3 = digit_values[p[3]];
if (RB_UNLIKELY((signed char)(b0 | b1 | b2 | b3) < 0)) {
raise_syntax_error_at("incomplete unicode character escape sequence at %s", state, sp - 2);
}
return ((uint32_t)b0 << 12) | ((uint32_t)b1 << 8) | ((uint32_t)b2 << 4) | (uint32_t)b3;
}
#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;
const char *COMMENT_DEPRECATION_MESSAGE = "Encountered comment in JSON. This will raise an error in json 3.0 unless enabled via `allow_comments: true`";
NOINLINE(static) void
json_eat_comments(JSON_ParserState *state, JSON_ParserConfig *config)
{
if (config->on_comment == JSON_RAISE) {
raise_syntax_error("unexpected token %s", state);
}
const char *start = state->cursor;
state->cursor++;
switch (peek(state)) {
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++;
while (true) {
const char *next_match = memchr(state->cursor, '*', state->end - state->cursor);
if (!next_match) {
raise_eos_error_at("unterminated comment, expected closing '*/'", state, start);
}
state->cursor = next_match + 1;
if (peek(state) == '/') {
state->cursor++;
break;
}
}
break;
}
default:
raise_parse_error_at("unexpected token %s", state, start, eos(state));
break;
}
if (config->on_comment == JSON_DEPRECATED && state->emitted_deprecations < MAX_DEPRECATIONS) {
state->emitted_deprecations++;
emit_parse_warning(COMMENT_DEPRECATION_MESSAGE, state);
}
}
ALWAYS_INLINE(static) void
json_eat_whitespace(JSON_ParserState *state, JSON_ParserConfig *config, bool include_comments)
{
while (true) {
switch (peek(state)) {
case ' ':
state->cursor++;
break;
case '\n':
state->cursor++;
// Heuristic: if we see a newline, there is likely consecutive spaces after it.
#if JSON_CPU_LITTLE_ENDIAN_64BITS
while (rest(state) > 8) {
uint64_t chunk;
memcpy(&chunk, state->cursor, sizeof(uint64_t));
if (chunk == 0x2020202020202020) {
state->cursor += 8;
continue;
}
uint32_t consecutive_spaces = trailing_zeros64(chunk ^ 0x2020202020202020) / CHAR_BIT;
state->cursor += consecutive_spaces;
break;
}
#endif
break;
case '\t':
case '\r':
state->cursor++;
break;
case '/':
if (!include_comments) {
return;
}
json_eat_comments(state, config);
break;
default:
return;
}
}
}
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 bool json_string_cacheable_p(const char *string, size_t length)
{
// We mostly want to cache strings that are likely to be repeated.
// Simple heuristics:
// - Common names aren't likely to be very long. So we just don't cache names above an arbitrary threshold.
// - If the first character isn't a letter, we're much less likely to see this string again.
return length <= JSON_RVALUE_CACHE_MAX_ENTRY_LENGTH && rb_isalpha(string[0]);
}
static inline VALUE json_string_fastpath(JSON_ParserState *state, JSON_ParserConfig *config, const char *string, const char *stringEnd, bool is_name)
{
bool intern = is_name || config->freeze;
bool symbolize = is_name && config->symbolize_names;
size_t bufferSize = stringEnd - string;
if (is_name && state->in_array && RB_LIKELY(json_string_cacheable_p(string, bufferSize))) {
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);
}
#define JSON_MAX_UNESCAPE_POSITIONS 16
typedef struct _json_unescape_positions {
long size;
const char **positions;
unsigned long additional_backslashes;
} JSON_UnescapePositions;
static inline const char *json_next_backslash(const char *pe, const char *stringEnd, JSON_UnescapePositions *positions)
{
while (positions->size) {
positions->size--;
const char *next_position = positions->positions[0];
positions->positions++;
if (next_position >= pe) {
return next_position;
}
}
if (positions->additional_backslashes) {
positions->additional_backslashes--;
return memchr(pe, '\\', stringEnd - pe);
}
return NULL;
}
NOINLINE(static) VALUE json_string_unescape(JSON_ParserState *state, JSON_ParserConfig *config, const char *string, const char *stringEnd, bool is_name, JSON_UnescapePositions *positions)
{
bool intern = is_name || config->freeze;
bool symbolize = is_name && config->symbolize_names;
size_t bufferSize = stringEnd - string;
const char *p = string, *pe = string, *bufferStart;
char *buffer;
VALUE result = rb_str_buf_new(bufferSize);
rb_enc_associate_index(result, utf8_encindex);
buffer = RSTRING_PTR(result);
bufferStart = buffer;
#define APPEND_CHAR(chr) *buffer++ = chr; p = ++pe;
while (pe < stringEnd && (pe = json_next_backslash(pe, stringEnd, positions))) {
if (pe > p) {
MEMCPY(buffer, p, char, pe - p);
buffer += pe - p;
}
switch (*++pe) {
case '"':
case '/':
p = pe; // nothing to unescape just need to skip the backslash
break;
case '\\':
APPEND_CHAR('\\');
break;
case 'n':
APPEND_CHAR('\n');
break;
case 'r':
APPEND_CHAR('\r');
break;
case 't':
APPEND_CHAR('\t');
break;
case 'b':
APPEND_CHAR('\b');
break;
case 'f':
APPEND_CHAR('\f');
break;
case 'u': {
uint32_t ch = unescape_unicode(state, ++pe, stringEnd);
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".