json 2.11.3 → 2.21.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,48 +1,25 @@
1
- #include "ruby.h"
2
- #include "ruby/encoding.h"
1
+ #include "../json.h"
2
+ #include "../vendor/fast_float_parser.h"
3
+ #include "../simd/simd.h"
3
4
 
4
- /* shims */
5
- /* This is the fallback definition from Ruby 3.4 */
5
+ static VALUE mJSON, eNestingError, eParserError, Encoding_UTF_8;
6
+ static VALUE CNaN, CInfinity, CMinusInfinity, JSON_empty_string;
6
7
 
7
- #ifndef RBIMPL_STDBOOL_H
8
- #if defined(__cplusplus)
9
- # if defined(HAVE_STDBOOL_H) && (__cplusplus >= 201103L)
10
- # include <cstdbool>
11
- # endif
12
- #elif defined(HAVE_STDBOOL_H)
13
- # include <stdbool.h>
14
- #elif !defined(HAVE__BOOL)
15
- typedef unsigned char _Bool;
16
- # define bool _Bool
17
- # define true ((_Bool)+1)
18
- # define false ((_Bool)+0)
19
- # define __bool_true_false_are_defined
20
- #endif
21
- #endif
22
-
23
- #ifndef RB_UNLIKELY
24
- #define RB_UNLIKELY(expr) expr
8
+ static ID i_new, i_try_convert, i_encode, i_at_line, i_at_column;
9
+ #ifndef HAVE_RB_STR_TO_INTERNED_STR
10
+ static ID i_uminus;
25
11
  #endif
26
12
 
27
- #ifndef RB_LIKELY
28
- #define RB_LIKELY(expr) expr
29
- #endif
30
-
31
- static VALUE mJSON, eNestingError, Encoding_UTF_8;
32
- static VALUE CNaN, CInfinity, CMinusInfinity;
33
-
34
- static ID i_chr, i_aset, i_aref,
35
- i_leftshift, i_new, i_try_convert, i_uminus, i_encode;
36
-
37
- static VALUE sym_max_nesting, sym_allow_nan, sym_allow_trailing_comma, sym_symbolize_names, sym_freeze,
38
- sym_decimal_class, sym_on_load;
13
+ static VALUE sym_max_nesting, sym_allow_nan, sym_allow_trailing_comma, sym_allow_comments,
14
+ sym_allow_control_characters, sym_allow_invalid_escape, sym_symbolize_names,
15
+ sym_freeze, sym_decimal_class, sym_on_load, sym_allow_duplicate_key;
39
16
 
40
17
  static int binary_encindex;
41
18
  static int utf8_encindex;
42
19
 
43
20
  #ifndef HAVE_RB_HASH_BULK_INSERT
44
21
  // For TruffleRuby
45
- void
22
+ static void
46
23
  rb_hash_bulk_insert(long count, const VALUE *pairs, VALUE hash)
47
24
  {
48
25
  long index = 0;
@@ -59,6 +36,12 @@ rb_hash_bulk_insert(long count, const VALUE *pairs, VALUE hash)
59
36
  #define rb_hash_new_capa(n) rb_hash_new()
60
37
  #endif
61
38
 
39
+ #ifndef HAVE_RB_STR_TO_INTERNED_STR
40
+ static VALUE rb_str_to_interned_str(VALUE str)
41
+ {
42
+ return rb_funcall(rb_str_freeze(str), i_uminus, 0);
43
+ }
44
+ #endif
62
45
 
63
46
  /* name cache */
64
47
 
@@ -78,6 +61,20 @@ typedef struct rvalue_cache_struct {
78
61
  VALUE entries[JSON_RVALUE_CACHE_CAPA];
79
62
  } rvalue_cache;
80
63
 
64
+ static void rvalue_cache_mark(rvalue_cache *cache)
65
+ {
66
+ for (int index = 0; index < cache->length; index++) {
67
+ rb_gc_mark_movable(cache->entries[index]);
68
+ }
69
+ }
70
+
71
+ static void rvalue_cache_compact(rvalue_cache *cache)
72
+ {
73
+ for (int index = 0; index < cache->length; index++) {
74
+ cache->entries[index] = rb_gc_location(cache->entries[index]);
75
+ }
76
+ }
77
+
81
78
  static rb_encoding *enc_utf8;
82
79
 
83
80
  #define JSON_RVALUE_CACHE_MAX_ENTRY_LENGTH 55
@@ -104,116 +101,104 @@ static void rvalue_cache_insert_at(rvalue_cache *cache, int index, VALUE rstring
104
101
  cache->entries[index] = rstring;
105
102
  }
106
103
 
107
- static inline int rstring_cache_cmp(const char *str, const long length, VALUE rstring)
104
+ #define rstring_cache_memcmp memcmp
105
+
106
+ #if JSON_CPU_LITTLE_ENDIAN_64BITS
107
+ #if __has_builtin(__builtin_bswap64)
108
+ #undef rstring_cache_memcmp
109
+ ALWAYS_INLINE(static) int rstring_cache_memcmp(const char *str, const char *rptr, const long length)
108
110
  {
109
- long rstring_length = RSTRING_LEN(rstring);
110
- if (length == rstring_length) {
111
- return memcmp(str, RSTRING_PTR(rstring), length);
112
- } else {
113
- return (int)(length - rstring_length);
111
+ // The libc memcmp has numerous complex optimizations, but in this particular case,
112
+ // we know the string is small (JSON_RVALUE_CACHE_MAX_ENTRY_LENGTH), so being able to
113
+ // inline a simpler memcmp outperforms calling the libc version.
114
+ long i = 0;
115
+
116
+ for (; i + 8 <= length; i += 8) {
117
+ uint64_t a, b;
118
+ memcpy(&a, str + i, 8);
119
+ memcpy(&b, rptr + i, 8);
120
+ if (a != b) {
121
+ a = __builtin_bswap64(a);
122
+ b = __builtin_bswap64(b);
123
+ return (a < b) ? -1 : 1;
124
+ }
125
+ }
126
+
127
+ for (; i < length; i++) {
128
+ if (str[i] != rptr[i]) {
129
+ return (str[i] < rptr[i]) ? -1 : 1;
130
+ }
114
131
  }
132
+
133
+ return 0;
115
134
  }
135
+ #endif
136
+ #endif
116
137
 
117
- static VALUE rstring_cache_fetch(rvalue_cache *cache, const char *str, const long length)
138
+ ALWAYS_INLINE(static) int rstring_cache_cmp(const char *str, const long length, VALUE rstring)
118
139
  {
119
- if (RB_UNLIKELY(length > JSON_RVALUE_CACHE_MAX_ENTRY_LENGTH)) {
120
- // Common names aren't likely to be very long. So we just don't
121
- // cache names above an arbitrary threshold.
122
- return Qfalse;
123
- }
140
+ const char *rstring_ptr;
141
+ long rstring_length;
124
142
 
125
- if (RB_UNLIKELY(!isalpha((unsigned char)str[0]))) {
126
- // Simple heuristic, if the first character isn't a letter,
127
- // we're much less likely to see this string again.
128
- // We mostly want to cache strings that are likely to be repeated.
129
- return Qfalse;
143
+ RSTRING_GETMEM(rstring, rstring_ptr, rstring_length);
144
+
145
+ if (length == rstring_length) {
146
+ return rstring_cache_memcmp(str, rstring_ptr, length);
147
+ } else {
148
+ return (int)(length - rstring_length);
130
149
  }
150
+ }
131
151
 
152
+ ALWAYS_INLINE(static) VALUE rstring_cache_fetch(rvalue_cache *cache, const char *str, const long length)
153
+ {
132
154
  int low = 0;
133
155
  int high = cache->length - 1;
134
- int mid = 0;
135
- int last_cmp = 0;
136
156
 
137
157
  while (low <= high) {
138
- mid = (high + low) >> 1;
158
+ int mid = (high + low) >> 1;
139
159
  VALUE entry = cache->entries[mid];
140
- last_cmp = rstring_cache_cmp(str, length, entry);
160
+ int cmp = rstring_cache_cmp(str, length, entry);
141
161
 
142
- if (last_cmp == 0) {
162
+ if (cmp == 0) {
143
163
  return entry;
144
- } else if (last_cmp > 0) {
164
+ } else if (cmp > 0) {
145
165
  low = mid + 1;
146
166
  } else {
147
167
  high = mid - 1;
148
168
  }
149
169
  }
150
170
 
151
- if (RB_UNLIKELY(memchr(str, '\\', length))) {
152
- // We assume the overwhelming majority of names don't need to be escaped.
153
- // But if they do, we have to fallback to the slow path.
154
- return Qfalse;
155
- }
156
-
157
171
  VALUE rstring = build_interned_string(str, length);
158
172
 
159
173
  if (cache->length < JSON_RVALUE_CACHE_CAPA) {
160
- if (last_cmp > 0) {
161
- mid += 1;
162
- }
163
-
164
- rvalue_cache_insert_at(cache, mid, rstring);
174
+ rvalue_cache_insert_at(cache, low, rstring);
165
175
  }
166
176
  return rstring;
167
177
  }
168
178
 
169
179
  static VALUE rsymbol_cache_fetch(rvalue_cache *cache, const char *str, const long length)
170
180
  {
171
- if (RB_UNLIKELY(length > JSON_RVALUE_CACHE_MAX_ENTRY_LENGTH)) {
172
- // Common names aren't likely to be very long. So we just don't
173
- // cache names above an arbitrary threshold.
174
- return Qfalse;
175
- }
176
-
177
- if (RB_UNLIKELY(!isalpha((unsigned char)str[0]))) {
178
- // Simple heuristic, if the first character isn't a letter,
179
- // we're much less likely to see this string again.
180
- // We mostly want to cache strings that are likely to be repeated.
181
- return Qfalse;
182
- }
183
-
184
181
  int low = 0;
185
182
  int high = cache->length - 1;
186
- int mid = 0;
187
- int last_cmp = 0;
188
183
 
189
184
  while (low <= high) {
190
- mid = (high + low) >> 1;
185
+ int mid = (high + low) >> 1;
191
186
  VALUE entry = cache->entries[mid];
192
- last_cmp = rstring_cache_cmp(str, length, rb_sym2str(entry));
187
+ int cmp = rstring_cache_cmp(str, length, rb_sym2str(entry));
193
188
 
194
- if (last_cmp == 0) {
189
+ if (cmp == 0) {
195
190
  return entry;
196
- } else if (last_cmp > 0) {
191
+ } else if (cmp > 0) {
197
192
  low = mid + 1;
198
193
  } else {
199
194
  high = mid - 1;
200
195
  }
201
196
  }
202
197
 
203
- if (RB_UNLIKELY(memchr(str, '\\', length))) {
204
- // We assume the overwhelming majority of names don't need to be escaped.
205
- // But if they do, we have to fallback to the slow path.
206
- return Qfalse;
207
- }
208
-
209
198
  VALUE rsymbol = build_symbol(str, length);
210
199
 
211
200
  if (cache->length < JSON_RVALUE_CACHE_CAPA) {
212
- if (last_cmp > 0) {
213
- mid += 1;
214
- }
215
-
216
- rvalue_cache_insert_at(cache, mid, rsymbol);
201
+ rvalue_cache_insert_at(cache, low, rsymbol);
217
202
  }
218
203
  return rsymbol;
219
204
  }
@@ -238,12 +223,12 @@ static rvalue_stack *rvalue_stack_spill(rvalue_stack *old_stack, VALUE *handle,
238
223
 
239
224
  static rvalue_stack *rvalue_stack_grow(rvalue_stack *stack, VALUE *handle, rvalue_stack **stack_ref)
240
225
  {
241
- long required = stack->capa * 2;
226
+ long required = stack->capa ? stack->capa * 2 : RVALUE_STACK_INITIAL_CAPA;
242
227
 
243
228
  if (stack->type == RVALUE_STACK_STACK_ALLOCATED) {
244
229
  stack = rvalue_stack_spill(stack, handle, stack_ref);
245
230
  } else {
246
- REALLOC_N(stack->ptr, VALUE, required);
231
+ JSON_SIZED_REALLOC_N(stack->ptr, VALUE, required, stack->capa);
247
232
  stack->capa = required;
248
233
  }
249
234
  return stack;
@@ -251,11 +236,15 @@ static rvalue_stack *rvalue_stack_grow(rvalue_stack *stack, VALUE *handle, rvalu
251
236
 
252
237
  static VALUE rvalue_stack_push(rvalue_stack *stack, VALUE value, VALUE *handle, rvalue_stack **stack_ref)
253
238
  {
239
+ JSON_ASSERT(stack->type != RVALUE_STACK_STACK_ALLOCATED || handle);
240
+
254
241
  if (RB_UNLIKELY(stack->head >= stack->capa)) {
255
242
  stack = rvalue_stack_grow(stack, handle, stack_ref);
256
243
  }
244
+
257
245
  stack->ptr[stack->head] = value;
258
246
  stack->head++;
247
+
259
248
  return value;
260
249
  }
261
250
 
@@ -273,35 +262,62 @@ static void rvalue_stack_mark(void *ptr)
273
262
  {
274
263
  rvalue_stack *stack = (rvalue_stack *)ptr;
275
264
  long index;
276
- for (index = 0; index < stack->head; index++) {
277
- rb_gc_mark(stack->ptr[index]);
265
+ if (stack && stack->ptr) {
266
+ for (index = 0; index < stack->head; index++) {
267
+ rb_gc_mark_movable(stack->ptr[index]);
268
+ }
278
269
  }
279
270
  }
280
271
 
272
+ static void rvalue_stack_free_buffer(rvalue_stack *stack)
273
+ {
274
+ JSON_SIZED_FREE_N(stack->ptr, stack->capa);
275
+ stack->ptr = NULL;
276
+ }
277
+
281
278
  static void rvalue_stack_free(void *ptr)
282
279
  {
283
280
  rvalue_stack *stack = (rvalue_stack *)ptr;
284
281
  if (stack) {
285
- ruby_xfree(stack->ptr);
286
- ruby_xfree(stack);
282
+ rvalue_stack_free_buffer(stack);
283
+ #ifndef HAVE_RUBY_TYPED_EMBEDDABLE
284
+ JSON_SIZED_FREE(stack);
285
+ #endif
287
286
  }
288
287
  }
289
288
 
290
289
  static size_t rvalue_stack_memsize(const void *ptr)
291
290
  {
292
291
  const rvalue_stack *stack = (const rvalue_stack *)ptr;
293
- return sizeof(rvalue_stack) + sizeof(VALUE) * stack->capa;
292
+ size_t memsize = sizeof(VALUE) * stack->capa;
293
+ #ifndef HAVE_RUBY_TYPED_EMBEDDABLE
294
+ memsize += sizeof(rvalue_stack);
295
+ #endif
296
+ return memsize;
297
+ }
298
+
299
+ static void rvalue_stack_compact(void *ptr)
300
+ {
301
+ rvalue_stack *stack = (rvalue_stack *)ptr;
302
+ long index;
303
+ if (stack && stack->ptr) {
304
+ for (index = 0; index < stack->head; index++) {
305
+ stack->ptr[index] = rb_gc_location(stack->ptr[index]);
306
+ }
307
+ }
294
308
  }
295
309
 
296
310
  static const rb_data_type_t JSON_Parser_rvalue_stack_type = {
297
- "JSON::Ext::Parser/rvalue_stack",
298
- {
311
+ .wrap_struct_name = "JSON::Ext::Parser/rvalue_stack",
312
+ .function = {
299
313
  .dmark = rvalue_stack_mark,
300
314
  .dfree = rvalue_stack_free,
301
315
  .dsize = rvalue_stack_memsize,
316
+ .dcompact = rvalue_stack_compact,
302
317
  },
303
- 0, 0,
304
- RUBY_TYPED_FREE_IMMEDIATELY,
318
+ // We deliberately don't declare rvalue_stack as RUBY_TYPED_WB_PROTECTED
319
+ // because it churns a lot of values so trigering write barriers every time is very costly.
320
+ .flags = RUBY_TYPED_THREAD_SAFE_FREE | RUBY_TYPED_EMBEDDABLE,
305
321
  };
306
322
 
307
323
  static rvalue_stack *rvalue_stack_spill(rvalue_stack *old_stack, VALUE *handle, rvalue_stack **stack_ref)
@@ -323,85 +339,210 @@ static void rvalue_stack_eagerly_release(VALUE handle)
323
339
  if (handle) {
324
340
  rvalue_stack *stack;
325
341
  TypedData_Get_Struct(handle, rvalue_stack, &JSON_Parser_rvalue_stack_type, stack);
326
- RTYPEDDATA_DATA(handle) = NULL;
342
+ #ifdef HAVE_RUBY_TYPED_EMBEDDABLE
343
+ rvalue_stack_free_buffer(stack);
344
+ #else
327
345
  rvalue_stack_free(stack);
346
+ RTYPEDDATA_DATA(handle) = NULL;
347
+ #endif
328
348
  }
329
349
  }
330
350
 
351
+ /* frame stack */
352
+
353
+ // Iterative (non-recursive) parsing keeps an explicit stack of the containers
354
+ // currently being built, instead of relying on the C call stack. Each frame
355
+ // only needs enough bookkeeping to close its container: which kind it is, the
356
+ // rvalue_stack position where its children start (so we know how many to pop),
357
+ // and the cursor at its opening brace (used to rewind for duplicate key
358
+ // errors). Frames hold no VALUEs, so this stack needs no GC marking; it reuses
359
+ // the same stack-allocated-with-heap-spill strategy as the rvalue_stack so that
360
+ // it's freed even if parsing raises.
361
+ //
362
+ // The lifecycle helpers below (grow/push/peek/pop/spill/free/eagerly_release
363
+ // and the rb_data_type_t) deliberately mirror their rvalue_stack counterparts
364
+ // -- the element type and the absence of a mark function are the only real
365
+ // differences. Keep the two in sync: a fix to the spill/release or
366
+ // HAVE_RUBY_TYPED_EMBEDDABLE handling in one almost certainly belongs in the
367
+ // other.
368
+ #define JSON_FRAME_STACK_INITIAL_CAPA 32
369
+
370
+ enum json_frame_type {
371
+ JSON_FRAME_ROOT, // == JSON_PHASE_DONE
372
+ JSON_FRAME_ARRAY, // == JSON_PHASE_ARRAY_COMMA
373
+ JSON_FRAME_OBJECT, // = JSON_PHASE_OBJECT_COMMA
374
+ };
375
+
376
+ // Where a frame is within its container's grammar. This is the entirety of the
377
+ // parser's "what to do next" state: json_parse_any dispatches on the top
378
+ // frame's phase and holds no resume state in C locals, so a parse can stop at
379
+ // any value boundary and be resumed purely from the (persistable) frame stack.
380
+ //
381
+ // The first three phases are deliberately equal to the corresponding json_frame_type
382
+ // to simplify the transition of phase in json_value_completed.
383
+ enum json_frame_phase {
384
+ JSON_PHASE_DONE = JSON_FRAME_ROOT, // root only: the document value has been parsed
385
+ JSON_PHASE_ARRAY_COMMA = JSON_FRAME_ARRAY, // after a value: expecting ',' or the closing ']'
386
+ JSON_PHASE_OBJECT_COMMA = JSON_FRAME_OBJECT, // after a value: expecting ',' or the closing '}'
387
+ JSON_PHASE_VALUE, // expecting a value (document root, array element, or object value after ':')
388
+ JSON_PHASE_OBJECT_KEY, // expecting a '"' key (after '{' or ',')
389
+ JSON_PHASE_OBJECT_COLON, // object only: after a key, expecting ':'
390
+ };
391
+
392
+ typedef struct json_frame_struct {
393
+ enum json_frame_type type;
394
+ enum json_frame_phase phase;
395
+ long value_stack_head; // rvalue_stack->head when this container opened
396
+ size_t start_offset; // object frames only (the '{'); NULL otherwise
397
+ } json_frame;
398
+
399
+ typedef struct json_frame_stack_struct {
400
+ enum rvalue_stack_type type; // shared with rvalue_stack: is ptr stack- or heap-allocated
401
+ long capa;
402
+ long head;
403
+ json_frame *ptr;
404
+ } json_frame_stack;
405
+
406
+ enum deprecatable_action {
407
+ JSON_DEPRECATED = 0,
408
+ JSON_IGNORE,
409
+ JSON_RAISE,
410
+ };
411
+
412
+ typedef struct JSON_ParserStruct {
413
+ VALUE on_load_proc;
414
+ VALUE decimal_class;
415
+ ID decimal_method_id;
416
+ enum deprecatable_action on_duplicate_key;
417
+ enum deprecatable_action on_comment;
418
+ int max_nesting;
419
+ bool allow_nan;
420
+ bool allow_trailing_comma;
421
+ bool allow_control_characters;
422
+ bool allow_invalid_escape;
423
+ bool symbolize_names;
424
+ bool freeze;
425
+ } JSON_ParserConfig;
426
+
427
+ typedef struct JSON_ParserStateStruct {
428
+ VALUE *value_stack_handle;
429
+ VALUE *frame_stack_handle;
430
+ const char *start;
431
+ const char *cursor;
432
+ const char *end;
433
+ rvalue_stack *value_stack;
434
+ json_frame_stack *frames;
435
+ rvalue_cache name_cache;
436
+ int in_array;
437
+ int current_nesting;
438
+ unsigned int emitted_deprecations;
439
+ VALUE parser;
440
+ } JSON_ParserState;
441
+
442
+ static json_frame_stack *json_frame_stack_spill(json_frame_stack *old_stack, VALUE *handle, json_frame_stack **stack_ref);
331
443
 
332
- #ifndef HAVE_STRNLEN
333
- static size_t strnlen(const char *s, size_t maxlen)
444
+ static json_frame_stack *json_frame_stack_grow(json_frame_stack *stack, VALUE *handle, json_frame_stack **stack_ref)
334
445
  {
335
- char *p;
336
- return ((p = memchr(s, '\0', maxlen)) ? p - s : maxlen);
446
+ long required = stack->capa ? stack->capa * 2 : JSON_FRAME_STACK_INITIAL_CAPA;
447
+
448
+ if (stack->type == RVALUE_STACK_STACK_ALLOCATED) {
449
+ stack = json_frame_stack_spill(stack, handle, stack_ref);
450
+ } else {
451
+ JSON_SIZED_REALLOC_N(stack->ptr, json_frame, required, stack->capa);
452
+ stack->capa = required;
453
+ }
454
+ return stack;
337
455
  }
338
- #endif
339
456
 
340
- #define PARSE_ERROR_FRAGMENT_LEN 32
341
- #ifdef RBIMPL_ATTR_NORETURN
342
- RBIMPL_ATTR_NORETURN()
343
- #endif
344
- static void raise_parse_error(const char *format, const char *start)
457
+ static json_frame *json_frame_stack_push(JSON_ParserState *state, json_frame frame)
345
458
  {
346
- unsigned char buffer[PARSE_ERROR_FRAGMENT_LEN + 1];
459
+ json_frame_stack *stack = state->frames;
347
460
 
348
- size_t len = start ? strnlen(start, PARSE_ERROR_FRAGMENT_LEN) : 0;
349
- const char *ptr = start;
461
+ JSON_ASSERT(stack->type != RVALUE_STACK_STACK_ALLOCATED || state->frame_stack_handle);
350
462
 
351
- if (len == PARSE_ERROR_FRAGMENT_LEN) {
352
- MEMCPY(buffer, start, char, PARSE_ERROR_FRAGMENT_LEN);
463
+ if (RB_UNLIKELY(stack->head >= stack->capa)) {
464
+ stack = json_frame_stack_grow(stack, state->frame_stack_handle, &state->frames);
465
+ }
353
466
 
354
- while (buffer[len - 1] >= 0x80 && buffer[len - 1] < 0xC0) { // Is continuation byte
355
- len--;
356
- }
467
+ json_frame *frame_ptr = &stack->ptr[stack->head++];
468
+ *frame_ptr = frame;
469
+ return frame_ptr;
470
+ }
357
471
 
358
- if (buffer[len - 1] >= 0xC0) { // multibyte character start
359
- len--;
360
- }
472
+ static inline json_frame *json_frame_stack_peek(json_frame_stack *stack)
473
+ {
474
+ return &stack->ptr[stack->head - 1];
475
+ }
361
476
 
362
- buffer[len] = '\0';
363
- ptr = (const char *)buffer;
364
- }
477
+ static inline void json_frame_stack_pop(json_frame_stack *stack)
478
+ {
479
+ stack->head--;
480
+ }
365
481
 
366
- rb_enc_raise(enc_utf8, rb_path2class("JSON::ParserError"), format, ptr);
482
+ static void json_frame_stack_free_buffer(json_frame_stack *stack)
483
+ {
484
+ JSON_SIZED_FREE_N(stack->ptr, stack->capa);
485
+ stack->ptr = NULL;
367
486
  }
368
487
 
369
- /* unicode */
488
+ static void json_frame_stack_free(void *ptr)
489
+ {
490
+ json_frame_stack *stack = (json_frame_stack *)ptr;
491
+ if (stack) {
492
+ json_frame_stack_free_buffer(stack);
493
+ #ifndef HAVE_RUBY_TYPED_EMBEDDABLE
494
+ JSON_SIZED_FREE(stack);
495
+ #endif
496
+ }
497
+ }
370
498
 
371
- static const signed char digit_values[256] = {
372
- -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
373
- -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
374
- -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1,
375
- -1, -1, -1, -1, -1, -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1,
376
- -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
377
- 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
378
- -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
379
- -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
380
- -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
381
- -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
382
- -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
383
- -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
384
- -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
385
- -1, -1, -1, -1, -1, -1, -1
499
+ static size_t json_frame_stack_memsize(const void *ptr)
500
+ {
501
+ const json_frame_stack *stack = (const json_frame_stack *)ptr;
502
+
503
+ size_t memsize = sizeof(json_frame) * stack->capa;
504
+ #ifndef HAVE_RUBY_TYPED_EMBEDDABLE
505
+ memsize += sizeof(json_frame_stack);
506
+ #endif
507
+ return memsize;
508
+ }
509
+
510
+ static const rb_data_type_t JSON_Parser_frame_stack_type = {
511
+ .wrap_struct_name = "JSON::Ext::Parser/frame_stack",
512
+ .function = {
513
+ .dmark = NULL,
514
+ .dfree = json_frame_stack_free,
515
+ .dsize = json_frame_stack_memsize,
516
+ },
517
+ .flags = RUBY_TYPED_THREAD_SAFE_FREE | RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_EMBEDDABLE,
386
518
  };
387
519
 
388
- static uint32_t unescape_unicode(const unsigned char *p)
389
- {
390
- signed char b;
391
- uint32_t result = 0;
392
- b = digit_values[p[0]];
393
- if (b < 0) raise_parse_error("incomplete unicode character escape sequence at '%s'", (char *)p - 2);
394
- result = (result << 4) | (unsigned char)b;
395
- b = digit_values[p[1]];
396
- if (b < 0) raise_parse_error("incomplete unicode character escape sequence at '%s'", (char *)p - 2);
397
- result = (result << 4) | (unsigned char)b;
398
- b = digit_values[p[2]];
399
- if (b < 0) raise_parse_error("incomplete unicode character escape sequence at '%s'", (char *)p - 2);
400
- result = (result << 4) | (unsigned char)b;
401
- b = digit_values[p[3]];
402
- if (b < 0) raise_parse_error("incomplete unicode character escape sequence at '%s'", (char *)p - 2);
403
- result = (result << 4) | (unsigned char)b;
404
- return result;
520
+ static json_frame_stack *json_frame_stack_spill(json_frame_stack *old_stack, VALUE *handle, json_frame_stack **stack_ref)
521
+ {
522
+ json_frame_stack *stack;
523
+ *handle = TypedData_Make_Struct(0, json_frame_stack, &JSON_Parser_frame_stack_type, stack);
524
+ *stack_ref = stack;
525
+ MEMCPY(stack, old_stack, json_frame_stack, 1);
526
+
527
+ stack->capa = old_stack->capa << 1;
528
+ stack->ptr = ALLOC_N(json_frame, stack->capa);
529
+ stack->type = RVALUE_STACK_HEAP_ALLOCATED;
530
+ MEMCPY(stack->ptr, old_stack->ptr, json_frame, old_stack->head);
531
+ return stack;
532
+ }
533
+
534
+ static void json_frame_stack_eagerly_release(VALUE handle)
535
+ {
536
+ if (handle) {
537
+ json_frame_stack *stack;
538
+ TypedData_Get_Struct(handle, json_frame_stack, &JSON_Parser_frame_stack_type, stack);
539
+ #ifdef HAVE_RUBY_TYPED_EMBEDDABLE
540
+ json_frame_stack_free_buffer(stack);
541
+ #else
542
+ json_frame_stack_free(stack);
543
+ RTYPEDDATA_DATA(handle) = NULL;
544
+ #endif
545
+ }
405
546
  }
406
547
 
407
548
  static int convert_UTF32_to_UTF8(char *buf, uint32_t ch)
@@ -430,149 +571,361 @@ static int convert_UTF32_to_UTF8(char *buf, uint32_t ch)
430
571
  return len;
431
572
  }
432
573
 
433
- typedef struct JSON_ParserStruct {
434
- VALUE on_load_proc;
435
- VALUE decimal_class;
436
- ID decimal_method_id;
437
- int max_nesting;
438
- bool allow_nan;
439
- bool allow_trailing_comma;
440
- bool parsing_name;
441
- bool symbolize_names;
442
- bool freeze;
443
- } JSON_ParserConfig;
574
+ static inline size_t rest(JSON_ParserState *state) {
575
+ return state->end - state->cursor;
576
+ }
444
577
 
445
- typedef struct JSON_ParserStateStruct {
446
- VALUE stack_handle;
447
- const char *cursor;
448
- const char *end;
449
- rvalue_stack *stack;
450
- rvalue_cache name_cache;
451
- int in_array;
452
- int current_nesting;
453
- } JSON_ParserState;
578
+ static inline bool eos(JSON_ParserState *state) {
579
+ return state->cursor >= state->end;
580
+ }
454
581
 
455
- #define GET_PARSER_CONFIG \
456
- JSON_ParserConfig *config; \
457
- TypedData_Get_Struct(self, JSON_ParserConfig, &JSON_ParserConfig_type, config)
582
+ static inline char peek(JSON_ParserState *state)
583
+ {
584
+ if (RB_UNLIKELY(eos(state))) {
585
+ return 0;
586
+ }
587
+ return *state->cursor;
588
+ }
458
589
 
459
- static const rb_data_type_t JSON_ParserConfig_type;
590
+ static void cursor_position(JSON_ParserState *state, long *line_out, long *column_out)
591
+ {
592
+ JSON_ASSERT(!state->parser);
593
+ JSON_ASSERT(state->cursor);
594
+ JSON_ASSERT(state->cursor <= state->end);
460
595
 
461
- static const bool whitespace[256] = {
462
- [' '] = 1,
463
- ['\t'] = 1,
464
- ['\n'] = 1,
465
- ['\r'] = 1,
466
- ['/'] = 1,
467
- };
596
+ // Redundant but helpful for hardening
597
+ if (RB_UNLIKELY(state->cursor > state->end)) {
598
+ state->cursor = state->end;
599
+ }
468
600
 
469
- static void
470
- json_eat_comments(JSON_ParserState *state)
471
- {
472
- if (state->cursor + 1 < state->end) {
473
- switch(state->cursor[1]) {
474
- case '/': {
475
- state->cursor = memchr(state->cursor, '\n', state->end - state->cursor);
476
- if (!state->cursor) {
477
- state->cursor = state->end;
478
- } else {
479
- state->cursor++;
480
- }
481
- break;
482
- }
483
- case '*': {
484
- state->cursor += 2;
485
- while (true) {
486
- state->cursor = memchr(state->cursor, '*', state->end - state->cursor);
487
- if (!state->cursor) {
488
- state->cursor = state->end;
489
- raise_parse_error("unexpected end of input, expected closing '*/'", state->cursor);
490
- } else {
491
- state->cursor++;
492
- if (state->cursor < state->end && *state->cursor == '/') {
493
- state->cursor++;
494
- break;
495
- }
496
- }
497
- }
498
- break;
499
- }
500
- default:
501
- raise_parse_error("unexpected token at '%s'", state->cursor);
502
- break;
601
+ const char *cursor = state->cursor;
602
+ long column = 0;
603
+ long line = 1;
604
+
605
+ while (cursor >= state->start) {
606
+ if (*cursor-- == '\n') {
607
+ line++;
608
+ break;
503
609
  }
504
- } else {
505
- raise_parse_error("unexpected token at '%s'", state->cursor);
610
+ column++;
506
611
  }
507
- }
508
612
 
509
- static inline void
510
- json_eat_whitespace(JSON_ParserState *state)
511
- {
512
- while (state->cursor < state->end && RB_UNLIKELY(whitespace[(unsigned char)*state->cursor])) {
513
- if (RB_LIKELY(*state->cursor != '/')) {
514
- state->cursor++;
515
- } else {
516
- json_eat_comments(state);
613
+ while (cursor >= state->start) {
614
+ if (*cursor-- == '\n') {
615
+ line++;
517
616
  }
518
617
  }
618
+ *line_out = line;
619
+ *column_out = column;
519
620
  }
520
621
 
521
- static inline VALUE build_string(const char *start, const char *end, bool intern, bool symbolize)
622
+ static const unsigned int MAX_DEPRECATIONS = 5;
623
+
624
+ static void emit_parse_warning(const char *message, JSON_ParserState *state)
522
625
  {
523
- if (symbolize) {
524
- intern = true;
525
- }
526
- VALUE result;
527
- # ifdef HAVE_RB_ENC_INTERNED_STR
528
- if (intern) {
529
- result = rb_enc_interned_str(start, (long)(end - start), enc_utf8);
626
+ VALUE warning;
627
+ if (state->parser) { // line and columns can't be accurate in resumable
628
+ warning = rb_utf8_str_new_cstr(message);
530
629
  } else {
531
- result = rb_utf8_str_new(start, (long)(end - start));
532
- }
533
- # else
534
- result = rb_utf8_str_new(start, (long)(end - start));
535
- if (intern) {
536
- result = rb_funcall(rb_str_freeze(result), i_uminus, 0);
630
+ long line, column;
631
+ cursor_position(state, &line, &column);
632
+ warning = rb_sprintf("%s at line %ld column %ld", message, line, column);
537
633
  }
538
- # endif
634
+ rb_funcall(mJSON, rb_intern("deprecation_warning"), 1, warning);
635
+ }
539
636
 
540
- if (symbolize) {
541
- result = rb_str_intern(result);
637
+ #define PARSE_ERROR_FRAGMENT_LEN 32
638
+
639
+ static VALUE build_parse_error_message(const char *format, JSON_ParserState *state)
640
+ {
641
+ unsigned char buffer[PARSE_ERROR_FRAGMENT_LEN + 3];
642
+
643
+ const char *ptr = "EOF";
644
+ if (state->cursor && state->cursor < state->end) {
645
+ ptr = state->cursor;
646
+ size_t len = 0;
647
+ while (len < PARSE_ERROR_FRAGMENT_LEN) {
648
+ char ch = ptr[len];
649
+ if (!ch || ch == '\n' || ch == ' ' || ch == '\t' || ch == '\r') {
650
+ break;
651
+ }
652
+ len++;
653
+ }
654
+
655
+ if (len) {
656
+ buffer[0] = '\'';
657
+ MEMCPY(buffer + 1, ptr, char, len);
658
+
659
+ while (buffer[len] >= 0x80 && buffer[len] < 0xC0) { // Is continuation byte
660
+ len--;
661
+ }
662
+
663
+ if (buffer[len] >= 0xC0) { // multibyte character start
664
+ len--;
665
+ }
666
+
667
+ buffer[len + 1] = '\'';
668
+ buffer[len + 2] = '\0';
669
+ ptr = (const char *)buffer;
670
+ }
542
671
  }
543
672
 
544
- return result;
673
+ return rb_enc_sprintf(enc_utf8, format, ptr);
545
674
  }
546
675
 
547
- static inline VALUE json_string_fastpath(JSON_ParserState *state, const char *string, const char *stringEnd, bool is_name, bool intern, bool symbolize)
676
+ static VALUE parse_error_new(JSON_ParserState *state, VALUE message, long line, long column, bool eos)
548
677
  {
549
- size_t bufferSize = stringEnd - string;
678
+ VALUE exc = rb_exc_new_str(eParserError, message);
679
+ rb_ivar_set(exc, i_at_line, LONG2NUM(line));
680
+ rb_ivar_set(exc, i_at_column, LONG2NUM(column));
681
+ return exc;
682
+ }
550
683
 
551
- if (is_name && state->in_array) {
552
- VALUE cached_key;
553
- if (RB_UNLIKELY(symbolize)) {
554
- cached_key = rsymbol_cache_fetch(&state->name_cache, string, bufferSize);
684
+ NORETURN(static) void raise_parse_error(const char *format, JSON_ParserState *state, bool eos)
685
+ {
686
+ if (state->parser) {
687
+ if (eos) {
688
+ // the error will be swallowed by ResumableParser#parse, so no
689
+ // point building a message or backtrace.
690
+ rb_throw_obj(state->parser, state->parser);
555
691
  } else {
556
- cached_key = rstring_cache_fetch(&state->name_cache, string, bufferSize);
692
+ // line and columns can't be accurate in resumable
693
+ rb_exc_raise(parse_error_new(state, build_parse_error_message(format, state), 0, 0, eos));
557
694
  }
695
+ } else {
696
+ VALUE message = build_parse_error_message(format, state);
697
+ long line, column;
698
+ cursor_position(state, &line, &column);
699
+ rb_str_catf(message, " at line %ld column %ld", line, column);
700
+ rb_exc_raise(parse_error_new(state, message, line, column, eos));
701
+ }
702
+ }
558
703
 
559
- if (RB_LIKELY(cached_key)) {
560
- return cached_key;
704
+ NORETURN(static) void raise_eos_error(const char *format, JSON_ParserState *state)
705
+ {
706
+ raise_parse_error(format, state, true);
707
+ }
708
+
709
+ NORETURN(static) void raise_syntax_error(const char *format, JSON_ParserState *state)
710
+ {
711
+ raise_parse_error(format, state, false);
712
+ }
713
+
714
+ NORETURN(static) void raise_parse_error_at(const char *format, JSON_ParserState *state, const char *at, bool eos)
715
+ {
716
+ state->cursor = at;
717
+ raise_parse_error(format, state, eos);
718
+ }
719
+
720
+ NORETURN(static) void raise_eos_error_at(const char *format, JSON_ParserState *state, const char *at)
721
+ {
722
+ raise_parse_error_at(format, state, at, true);
723
+ }
724
+
725
+ NORETURN(static) void raise_syntax_error_at(const char *format, JSON_ParserState *state, const char *at)
726
+ {
727
+ raise_parse_error_at(format, state, at, false);
728
+ }
729
+
730
+ /* unicode */
731
+
732
+ static const signed char digit_values[256] = {
733
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
734
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
735
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1,
736
+ -1, -1, -1, -1, -1, -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1,
737
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
738
+ 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
739
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
740
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
741
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
742
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
743
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
744
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
745
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
746
+ -1, -1, -1, -1, -1, -1, -1
747
+ };
748
+
749
+ static uint32_t unescape_unicode(JSON_ParserState *state, const char *sp, const char *spe)
750
+ {
751
+ if (RB_UNLIKELY(sp > spe - 4)) {
752
+ raise_eos_error_at("incomplete unicode character escape sequence at %s", state, sp - 2);
753
+ }
754
+
755
+ const unsigned char *p = (const unsigned char *)sp;
756
+
757
+ const signed char b0 = digit_values[p[0]];
758
+ const signed char b1 = digit_values[p[1]];
759
+ const signed char b2 = digit_values[p[2]];
760
+ const signed char b3 = digit_values[p[3]];
761
+
762
+ if (RB_UNLIKELY((signed char)(b0 | b1 | b2 | b3) < 0)) {
763
+ raise_syntax_error_at("incomplete unicode character escape sequence at %s", state, sp - 2);
764
+ }
765
+
766
+ return ((uint32_t)b0 << 12) | ((uint32_t)b1 << 8) | ((uint32_t)b2 << 4) | (uint32_t)b3;
767
+ }
768
+
769
+ #define GET_PARSER_CONFIG \
770
+ JSON_ParserConfig *config; \
771
+ TypedData_Get_Struct(self, JSON_ParserConfig, &JSON_ParserConfig_type, config)
772
+
773
+ static const rb_data_type_t JSON_ParserConfig_type;
774
+
775
+ const char *COMMENT_DEPRECATION_MESSAGE = "Encountered comment in JSON. This will raise an error in json 3.0 unless enabled via `allow_comments: true`";
776
+ NOINLINE(static) void
777
+ json_eat_comments(JSON_ParserState *state, JSON_ParserConfig *config, const char *resume_pos)
778
+ {
779
+ if (config->on_comment == JSON_RAISE) {
780
+ raise_syntax_error("unexpected token %s", state);
781
+ }
782
+
783
+ const char *start = state->cursor;
784
+ // An incomplete comment suspends a resumable parse by rewinding the cursor
785
+ // and throwing. Callers that already consumed a token not yet committed to
786
+ // the frame stack pass resume_pos so the rewind re-reads that token too.
787
+ // Non-resumable error positions keep pointing at the comment either way.
788
+ const char *rewind_pos = (state->parser && resume_pos) ? resume_pos : start;
789
+ state->cursor++;
790
+
791
+ switch (peek(state)) {
792
+ case '/': {
793
+ const char *newline = memchr(state->cursor, '\n', state->end - state->cursor);
794
+ if (!newline) {
795
+ // state->parser marks resumable mode, where the buffer end is only a
796
+ // chunk boundary: the terminating newline may still arrive, so leave
797
+ // the comment unterminated instead of consuming to end as a one-shot
798
+ // parse would.
799
+ if (state->parser) {
800
+ raise_eos_error_at("unterminated comment, expected end of line", state, rewind_pos);
801
+ }
802
+ state->cursor = state->end;
803
+ } else {
804
+ state->cursor = newline + 1;
805
+ }
806
+ break;
807
+ }
808
+ case '*': {
809
+ state->cursor++;
810
+
811
+ while (true) {
812
+ const char *next_match = memchr(state->cursor, '*', state->end - state->cursor);
813
+ if (!next_match) {
814
+ raise_eos_error_at("unterminated comment, expected closing '*/'", state, rewind_pos);
815
+ }
816
+
817
+ state->cursor = next_match + 1;
818
+ if (peek(state) == '/') {
819
+ state->cursor++;
820
+ break;
821
+ }
822
+ }
823
+ break;
561
824
  }
825
+ default:
826
+ raise_parse_error_at("unexpected token %s", state, eos(state) ? rewind_pos : start, eos(state));
827
+ break;
562
828
  }
563
829
 
564
- return build_string(string, stringEnd, intern, symbolize);
830
+ if (config->on_comment == JSON_DEPRECATED && state->emitted_deprecations < MAX_DEPRECATIONS) {
831
+ state->emitted_deprecations++;
832
+ emit_parse_warning(COMMENT_DEPRECATION_MESSAGE, state);
833
+ }
834
+ }
835
+
836
+ ALWAYS_INLINE(static) void
837
+ json_eat_whitespace_resume_at(JSON_ParserState *state, JSON_ParserConfig *config, bool include_comments, const char *resume_pos)
838
+ {
839
+ while (true) {
840
+ switch (peek(state)) {
841
+ case ' ':
842
+ state->cursor++;
843
+ break;
844
+ case '\n':
845
+ state->cursor++;
846
+
847
+ // Heuristic: if we see a newline, there is likely consecutive spaces after it.
848
+ #if JSON_CPU_LITTLE_ENDIAN_64BITS
849
+ while (rest(state) > 8) {
850
+ uint64_t chunk;
851
+ memcpy(&chunk, state->cursor, sizeof(uint64_t));
852
+ if (chunk == 0x2020202020202020) {
853
+ state->cursor += 8;
854
+ continue;
855
+ }
856
+
857
+ uint32_t consecutive_spaces = trailing_zeros64(chunk ^ 0x2020202020202020) / CHAR_BIT;
858
+ state->cursor += consecutive_spaces;
859
+ break;
860
+ }
861
+ #endif
862
+ break;
863
+ case '\t':
864
+ case '\r':
865
+ state->cursor++;
866
+ break;
867
+ case '/':
868
+ if (!include_comments) {
869
+ return;
870
+ }
871
+
872
+ json_eat_comments(state, config, resume_pos);
873
+ break;
874
+
875
+ default:
876
+ return;
877
+ }
878
+ }
879
+ }
880
+
881
+ ALWAYS_INLINE(static) void
882
+ json_eat_whitespace(JSON_ParserState *state, JSON_ParserConfig *config, bool include_comments)
883
+ {
884
+ json_eat_whitespace_resume_at(state, config, include_comments, NULL);
885
+ }
886
+
887
+ static inline VALUE build_string(const char *start, const char *end, bool intern, bool symbolize)
888
+ {
889
+ if (symbolize) {
890
+ intern = true;
891
+ }
892
+ VALUE result;
893
+ # ifdef HAVE_RB_ENC_INTERNED_STR
894
+ if (intern) {
895
+ result = rb_enc_interned_str(start, (long)(end - start), enc_utf8);
896
+ } else {
897
+ result = rb_utf8_str_new(start, (long)(end - start));
898
+ }
899
+ # else
900
+ result = rb_utf8_str_new(start, (long)(end - start));
901
+ if (intern) {
902
+ result = rb_funcall(rb_str_freeze(result), i_uminus, 0);
903
+ }
904
+ # endif
905
+
906
+ if (symbolize) {
907
+ result = rb_str_intern(result);
908
+ }
909
+
910
+ return result;
911
+ }
912
+
913
+ static inline bool json_string_cacheable_p(const char *string, size_t length)
914
+ {
915
+ // We mostly want to cache strings that are likely to be repeated.
916
+ // Simple heuristics:
917
+ // - Common names aren't likely to be very long. So we just don't cache names above an arbitrary threshold.
918
+ // - If the first character isn't a letter, we're much less likely to see this string again.
919
+ return length <= JSON_RVALUE_CACHE_MAX_ENTRY_LENGTH && rb_isalpha(string[0]);
565
920
  }
566
921
 
567
- static VALUE json_string_unescape(JSON_ParserState *state, const char *string, const char *stringEnd, bool is_name, bool intern, bool symbolize)
922
+ static inline VALUE json_string_fastpath(JSON_ParserState *state, JSON_ParserConfig *config, const char *string, const char *stringEnd, bool is_name)
568
923
  {
924
+ bool intern = is_name || config->freeze;
925
+ bool symbolize = is_name && config->symbolize_names;
569
926
  size_t bufferSize = stringEnd - string;
570
- const char *p = string, *pe = string, *unescape, *bufferStart;
571
- char *buffer;
572
- int unescape_len;
573
- char buf[4];
574
927
 
575
- if (is_name && state->in_array) {
928
+ if (is_name && state->in_array && RB_LIKELY(json_string_cacheable_p(string, bufferSize))) {
576
929
  VALUE cached_key;
577
930
  if (RB_UNLIKELY(symbolize)) {
578
931
  cached_key = rsymbol_cache_fetch(&state->name_cache, string, bufferSize);
@@ -585,83 +938,134 @@ static VALUE json_string_unescape(JSON_ParserState *state, const char *string, c
585
938
  }
586
939
  }
587
940
 
941
+ return build_string(string, stringEnd, intern, symbolize);
942
+ }
943
+
944
+ #define JSON_MAX_UNESCAPE_POSITIONS 16
945
+ typedef struct _json_unescape_positions {
946
+ long size;
947
+ const char **positions;
948
+ unsigned long additional_backslashes;
949
+ } JSON_UnescapePositions;
950
+
951
+ static inline const char *json_next_backslash(const char *pe, const char *stringEnd, JSON_UnescapePositions *positions)
952
+ {
953
+ while (positions->size) {
954
+ positions->size--;
955
+ const char *next_position = positions->positions[0];
956
+ positions->positions++;
957
+ if (next_position >= pe) {
958
+ return next_position;
959
+ }
960
+ }
961
+
962
+ if (positions->additional_backslashes) {
963
+ positions->additional_backslashes--;
964
+ return memchr(pe, '\\', stringEnd - pe);
965
+ }
966
+
967
+ return NULL;
968
+ }
969
+
970
+ NOINLINE(static) VALUE json_string_unescape(JSON_ParserState *state, JSON_ParserConfig *config, const char *string, const char *stringEnd, bool is_name, JSON_UnescapePositions *positions)
971
+ {
972
+ bool intern = is_name || config->freeze;
973
+ bool symbolize = is_name && config->symbolize_names;
974
+ size_t bufferSize = stringEnd - string;
975
+ const char *p = string, *pe = string, *bufferStart;
976
+ char *buffer;
977
+
588
978
  VALUE result = rb_str_buf_new(bufferSize);
589
979
  rb_enc_associate_index(result, utf8_encindex);
590
980
  buffer = RSTRING_PTR(result);
591
981
  bufferStart = buffer;
592
982
 
593
- while (pe < stringEnd && (pe = memchr(pe, '\\', stringEnd - pe))) {
594
- unescape = (char *) "?";
595
- unescape_len = 1;
983
+ #define APPEND_CHAR(chr) *buffer++ = chr; p = ++pe;
984
+
985
+ while (pe < stringEnd && (pe = json_next_backslash(pe, stringEnd, positions))) {
596
986
  if (pe > p) {
597
987
  MEMCPY(buffer, p, char, pe - p);
598
988
  buffer += pe - p;
599
989
  }
600
990
  switch (*++pe) {
991
+ case '"':
992
+ case '/':
993
+ p = pe; // nothing to unescape just need to skip the backslash
994
+ break;
995
+ case '\\':
996
+ APPEND_CHAR('\\');
997
+ break;
601
998
  case 'n':
602
- unescape = (char *) "\n";
999
+ APPEND_CHAR('\n');
603
1000
  break;
604
1001
  case 'r':
605
- unescape = (char *) "\r";
1002
+ APPEND_CHAR('\r');
606
1003
  break;
607
1004
  case 't':
608
- unescape = (char *) "\t";
609
- break;
610
- case '"':
611
- unescape = (char *) "\"";
612
- break;
613
- case '\\':
614
- unescape = (char *) "\\";
1005
+ APPEND_CHAR('\t');
615
1006
  break;
616
1007
  case 'b':
617
- unescape = (char *) "\b";
1008
+ APPEND_CHAR('\b');
618
1009
  break;
619
1010
  case 'f':
620
- unescape = (char *) "\f";
1011
+ APPEND_CHAR('\f');
621
1012
  break;
622
- case 'u':
623
- if (pe > stringEnd - 5) {
624
- raise_parse_error("incomplete unicode character escape sequence at '%s'", p);
625
- } else {
626
- uint32_t ch = unescape_unicode((unsigned char *) ++pe);
627
- pe += 3;
628
- /* To handle values above U+FFFF, we take a sequence of
629
- * \uXXXX escapes in the U+D800..U+DBFF then
630
- * U+DC00..U+DFFF ranges, take the low 10 bits from each
631
- * to make a 20-bit number, then add 0x10000 to get the
632
- * final codepoint.
633
- *
634
- * See Unicode 15: 3.8 "Surrogates", 5.3 "Handling
635
- * Surrogate Pairs in UTF-16", and 23.6 "Surrogates
636
- * Area".
637
- */
638
- if ((ch & 0xFC00) == 0xD800) {
639
- pe++;
640
- if (pe > stringEnd - 6) {
641
- raise_parse_error("incomplete surrogate pair at '%s'", p);
642
- }
643
- if (pe[0] == '\\' && pe[1] == 'u') {
644
- uint32_t sur = unescape_unicode((unsigned char *) pe + 2);
645
- ch = (((ch & 0x3F) << 10) | ((((ch >> 6) & 0xF) + 1) << 16)
646
- | (sur & 0x3FF));
647
- pe += 5;
648
- } else {
649
- unescape = (char *) "?";
650
- break;
1013
+ case 'u': {
1014
+ uint32_t ch = unescape_unicode(state, ++pe, stringEnd);
1015
+ pe += 3;
1016
+ /* To handle values above U+FFFF, we take a sequence of
1017
+ * \uXXXX escapes in the U+D800..U+DBFF then
1018
+ * U+DC00..U+DFFF ranges, take the low 10 bits from each
1019
+ * to make a 20-bit number, then add 0x10000 to get the
1020
+ * final codepoint.
1021
+ *
1022
+ * See Unicode 15: 3.8 "Surrogates", 5.3 "Handling
1023
+ * Surrogate Pairs in UTF-16", and 23.6 "Surrogates
1024
+ * Area".
1025
+ */
1026
+ if ((ch & 0xFC00) == 0xD800) {
1027
+ pe++;
1028
+ if (RB_LIKELY((pe <= stringEnd - 6) && memcmp(pe, "\\u", 2) == 0)) {
1029
+ uint32_t sur = unescape_unicode(state, pe + 2, stringEnd);
1030
+
1031
+ if (RB_UNLIKELY((sur & 0xFC00) != 0xDC00)) {
1032
+ raise_syntax_error_at("invalid surrogate pair at %s", state, p);
651
1033
  }
1034
+
1035
+ ch = (((ch & 0x3F) << 10) | ((((ch >> 6) & 0xF) + 1) << 16) | (sur & 0x3FF));
1036
+ pe += 5;
1037
+ } else {
1038
+ raise_syntax_error_at("incomplete surrogate pair at %s", state, p);
1039
+ break;
652
1040
  }
653
- unescape_len = convert_UTF32_to_UTF8(buf, ch);
654
- unescape = buf;
655
1041
  }
1042
+
1043
+ int unescape_len = convert_UTF32_to_UTF8(buffer, ch);
1044
+ buffer += unescape_len;
1045
+ p = ++pe;
656
1046
  break;
1047
+ }
1048
+ case 0:
1049
+ return Qundef;
657
1050
  default:
658
- p = pe;
659
- continue;
1051
+ if ((unsigned char)*pe < 0x20) {
1052
+ if (!config->allow_control_characters) {
1053
+ if (*pe == '\n') {
1054
+ raise_syntax_error_at("Invalid unescaped newline character (\\n) in string: %s", state, pe - 1);
1055
+ }
1056
+ raise_syntax_error_at("invalid ASCII control character in string: %s", state, pe - 1);
1057
+ }
1058
+ }
1059
+
1060
+ if (config->allow_invalid_escape) {
1061
+ APPEND_CHAR(*pe);
1062
+ } else {
1063
+ raise_syntax_error_at("invalid escape character in string: %s", state, pe - 1);
1064
+ }
1065
+ break;
660
1066
  }
661
- MEMCPY(buffer, unescape, char, unescape_len);
662
- buffer += unescape_len;
663
- p = ++pe;
664
1067
  }
1068
+ #undef APPEND_CHAR
665
1069
 
666
1070
  if (stringEnd > p) {
667
1071
  MEMCPY(buffer, p, char, stringEnd - p);
@@ -672,87 +1076,104 @@ static VALUE json_string_unescape(JSON_ParserState *state, const char *string, c
672
1076
  if (symbolize) {
673
1077
  result = rb_str_intern(result);
674
1078
  } else if (intern) {
675
- result = rb_funcall(rb_str_freeze(result), i_uminus, 0);
1079
+ result = rb_str_to_interned_str(result);
676
1080
  }
677
1081
 
678
1082
  return result;
679
1083
  }
680
1084
 
681
1085
  #define MAX_FAST_INTEGER_SIZE 18
682
- static inline VALUE fast_decode_integer(const char *p, const char *pe)
683
- {
684
- bool negative = false;
685
- if (*p == '-') {
686
- negative = true;
687
- p++;
688
- }
1086
+ #define MAX_NUMBER_STACK_BUFFER 128
689
1087
 
690
- long long memo = 0;
691
- while (p < pe) {
692
- memo *= 10;
693
- memo += *p - '0';
694
- p++;
695
- }
1088
+ typedef VALUE (*json_number_decode_func_t)(const char *ptr);
696
1089
 
697
- if (negative) {
698
- memo = -memo;
1090
+ static inline VALUE json_decode_large_number(const char *start, long len, json_number_decode_func_t func)
1091
+ {
1092
+ if (RB_LIKELY(len < MAX_NUMBER_STACK_BUFFER)) {
1093
+ char buffer[MAX_NUMBER_STACK_BUFFER];
1094
+ MEMCPY(buffer, start, char, len);
1095
+ buffer[len] = '\0';
1096
+ return func(buffer);
1097
+ } else {
1098
+ VALUE buffer_v = rb_str_tmp_new(len);
1099
+ char *buffer = RSTRING_PTR(buffer_v);
1100
+ MEMCPY(buffer, start, char, len);
1101
+ buffer[len] = '\0';
1102
+ VALUE number = func(buffer);
1103
+ RB_GC_GUARD(buffer_v);
1104
+ return number;
699
1105
  }
700
- return LL2NUM(memo);
701
1106
  }
702
1107
 
703
- static VALUE json_decode_large_integer(const char *start, long len)
1108
+ static VALUE json_decode_inum(const char *buffer)
1109
+ {
1110
+ return rb_cstr2inum(buffer, 10);
1111
+ }
1112
+
1113
+ NOINLINE(static) VALUE json_decode_large_integer(const char *start, long len)
704
1114
  {
705
- VALUE buffer_v;
706
- char *buffer = RB_ALLOCV_N(char, buffer_v, len + 1);
707
- MEMCPY(buffer, start, char, len);
708
- buffer[len] = '\0';
709
- VALUE number = rb_cstr2inum(buffer, 10);
710
- RB_ALLOCV_END(buffer_v);
711
- return number;
1115
+ return json_decode_large_number(start, len, json_decode_inum);
712
1116
  }
713
1117
 
714
- static inline VALUE
715
- json_decode_integer(const char *start, const char *end)
1118
+ static inline VALUE json_decode_integer(uint64_t mantissa, int mantissa_digits, bool negative, const char *start, const char *end)
716
1119
  {
717
- long len = end - start;
718
- if (RB_LIKELY(len < MAX_FAST_INTEGER_SIZE)) {
719
- return fast_decode_integer(start, end);
1120
+ if (RB_LIKELY(mantissa_digits < MAX_FAST_INTEGER_SIZE)) {
1121
+ if (negative) {
1122
+ return INT64T2NUM(-((int64_t)mantissa));
720
1123
  }
721
- return json_decode_large_integer(start, len);
1124
+ return UINT64T2NUM(mantissa);
1125
+ }
1126
+
1127
+ return json_decode_large_integer(start, end - start);
722
1128
  }
723
1129
 
724
- static VALUE json_decode_large_float(const char *start, long len)
1130
+ static VALUE json_decode_dnum(const char *buffer)
725
1131
  {
726
- VALUE buffer_v;
727
- char *buffer = RB_ALLOCV_N(char, buffer_v, len + 1);
728
- MEMCPY(buffer, start, char, len);
729
- buffer[len] = '\0';
730
- VALUE number = DBL2NUM(rb_cstr_to_dbl(buffer, 1));
731
- RB_ALLOCV_END(buffer_v);
732
- return number;
1132
+ return DBL2NUM(rb_cstr_to_dbl(buffer, 1));
733
1133
  }
734
1134
 
735
- static VALUE json_decode_float(JSON_ParserConfig *config, const char *start, const char *end)
1135
+ NOINLINE(static) VALUE json_decode_large_float(const char *start, long len)
736
1136
  {
737
- long len = end - start;
1137
+ return json_decode_large_number(start, len, json_decode_dnum);
1138
+ }
738
1139
 
1140
+ /* Ruby JSON optimized float decoder using vendored Ryu algorithm
1141
+ * Accepts pre-extracted mantissa and exponent from first-pass validation
1142
+ */
1143
+ static inline VALUE json_decode_float(JSON_ParserConfig *config, uint64_t mantissa, int mantissa_digits, int64_t exponent, bool negative,
1144
+ const char *start, const char *end)
1145
+ {
739
1146
  if (RB_UNLIKELY(config->decimal_class)) {
740
- VALUE text = rb_str_new(start, len);
1147
+ VALUE text = rb_str_new(start, end - start);
741
1148
  return rb_funcallv(config->decimal_class, config->decimal_method_id, 1, &text);
742
- } else if (RB_LIKELY(len < 64)) {
743
- char buffer[64];
744
- MEMCPY(buffer, start, char, len);
745
- buffer[len] = '\0';
746
- return DBL2NUM(rb_cstr_to_dbl(buffer, 1));
747
- } else {
748
- return json_decode_large_float(start, len);
749
1149
  }
1150
+
1151
+ if (RB_UNLIKELY(exponent > INT32_MAX)) {
1152
+ return negative ? CMinusInfinity : CInfinity;
1153
+ }
1154
+
1155
+ if (RB_UNLIKELY(exponent < INT32_MIN)) {
1156
+ return rb_float_new(negative ? -0.0 : 0.0);
1157
+ }
1158
+
1159
+ if (RB_UNLIKELY(mantissa_digits > 18 || mantissa_digits + exponent < -307)) {
1160
+ // If the value is so small that it definitely underflows to 0.0, return early
1161
+ // to avoid triggering a "Float out of range" warning from rb_cstr_to_dbl.
1162
+ // When mantissa_digits + exponent < -324, value < 10^(-324) < DBL_TRUE_MIN/2,
1163
+ // so it rounds to 0 in IEEE 754 round-to-nearest.
1164
+ if (RB_UNLIKELY(mantissa_digits + exponent < -324)) {
1165
+ return rb_float_new(negative ? -0.0 : 0.0);
1166
+ }
1167
+ return json_decode_large_float(start, end - start);
1168
+ }
1169
+
1170
+ return DBL2NUM(ffp_s2d(exponent, mantissa, negative));
750
1171
  }
751
1172
 
752
1173
  static inline VALUE json_decode_array(JSON_ParserState *state, JSON_ParserConfig *config, long count)
753
1174
  {
754
- VALUE array = rb_ary_new_from_values(count, rvalue_stack_peek(state->stack, count));
755
- rvalue_stack_pop(state->stack, count);
1175
+ VALUE array = rb_ary_new_from_values(count, rvalue_stack_peek(state->value_stack, count));
1176
+ rvalue_stack_pop(state->value_stack, count);
756
1177
 
757
1178
  if (config->freeze) {
758
1179
  RB_OBJ_FREEZE(array);
@@ -761,32 +1182,91 @@ static inline VALUE json_decode_array(JSON_ParserState *state, JSON_ParserConfig
761
1182
  return array;
762
1183
  }
763
1184
 
764
- static inline VALUE json_decode_object(JSON_ParserState *state, JSON_ParserConfig *config, long count)
1185
+ static VALUE json_find_duplicated_key(size_t count, const VALUE *pairs)
765
1186
  {
766
- VALUE object = rb_hash_new_capa(count);
767
- rb_hash_bulk_insert(count, rvalue_stack_peek(state->stack, count), object);
1187
+ VALUE set = rb_hash_new_capa(count / 2);
1188
+ for (size_t index = 0; index < count; index += 2) {
1189
+ size_t before = RHASH_SIZE(set);
1190
+ VALUE key = pairs[index];
1191
+ rb_hash_aset(set, key, Qtrue);
1192
+ if (RHASH_SIZE(set) == before) {
1193
+ if (RB_SYMBOL_P(key)) {
1194
+ return rb_sym2str(key);
1195
+ }
1196
+ return key;
1197
+ }
1198
+ }
1199
+ return Qfalse;
1200
+ }
1201
+
1202
+ NOINLINE(static) void emit_duplicate_key_warning(JSON_ParserState *state, VALUE duplicate_key)
1203
+ {
1204
+ VALUE message = rb_sprintf(
1205
+ "detected duplicate key %"PRIsVALUE" in JSON object. This will raise an error in json 3.0 unless enabled via `allow_duplicate_key: true`",
1206
+ rb_inspect(duplicate_key)
1207
+ );
768
1208
 
769
- rvalue_stack_pop(state->stack, count);
1209
+ emit_parse_warning(RSTRING_PTR(message), state);
1210
+ RB_GC_GUARD(message);
1211
+ }
770
1212
 
771
- if (config->freeze) {
772
- RB_OBJ_FREEZE(object);
1213
+ NORETURN(static) void raise_duplicate_key_error(JSON_ParserState *state, VALUE duplicate_key)
1214
+ {
1215
+ VALUE message = rb_sprintf(
1216
+ "duplicate key %"PRIsVALUE,
1217
+ rb_inspect(duplicate_key)
1218
+ );
1219
+
1220
+ rb_str_concat(message, build_parse_error_message("", state));
1221
+ if (state->parser) { // line and columns can't be accurate in resumable
1222
+ rb_exc_raise(parse_error_new(state, message, 0, 0, false));
1223
+ } else {
1224
+ long line, column;
1225
+ cursor_position(state, &line, &column);
1226
+ rb_str_catf(message, " at line %ld column %ld", line, column);
1227
+ rb_exc_raise(parse_error_new(state, message, line, column, false));
773
1228
  }
1229
+ }
774
1230
 
775
- return object;
1231
+ NOINLINE(static) void json_on_duplicate_key(JSON_ParserState *state, JSON_ParserConfig *config, size_t count, const VALUE *pairs)
1232
+ {
1233
+ switch (config->on_duplicate_key) {
1234
+ case JSON_IGNORE:
1235
+ return;
1236
+
1237
+ case JSON_DEPRECATED:
1238
+ // Only emit the first few deprecations to avoid spamming.
1239
+ if (state->emitted_deprecations < MAX_DEPRECATIONS) {
1240
+ state->emitted_deprecations++;
1241
+ emit_duplicate_key_warning(state, json_find_duplicated_key(count, pairs));
1242
+ }
1243
+ return;
1244
+
1245
+ case JSON_RAISE:
1246
+ raise_duplicate_key_error(state, json_find_duplicated_key(count, pairs));
1247
+ return;
1248
+ }
1249
+ UNREACHABLE;
776
1250
  }
777
1251
 
778
- static inline VALUE json_decode_string(JSON_ParserState *state, JSON_ParserConfig *config, const char *start, const char *end, bool escaped, bool is_name)
1252
+ static inline VALUE json_decode_object(JSON_ParserState *state, JSON_ParserConfig *config, size_t count)
779
1253
  {
780
- VALUE string;
781
- bool intern = is_name || config->freeze;
782
- bool symbolize = is_name && config->symbolize_names;
783
- if (escaped) {
784
- string = json_string_unescape(state, start, end, is_name, intern, symbolize);
785
- } else {
786
- string = json_string_fastpath(state, start, end, is_name, intern, symbolize);
1254
+ size_t entries_count = count / 2;
1255
+ VALUE object = rb_hash_new_capa(entries_count);
1256
+ const VALUE *pairs = rvalue_stack_peek(state->value_stack, count);
1257
+ rb_hash_bulk_insert(count, pairs, object);
1258
+
1259
+ if (RB_UNLIKELY(RHASH_SIZE(object) < entries_count)) {
1260
+ json_on_duplicate_key(state, config, count, pairs);
787
1261
  }
788
1262
 
789
- return string;
1263
+ rvalue_stack_pop(state->value_stack, count);
1264
+
1265
+ if (config->freeze) {
1266
+ RB_OBJ_FREEZE(object);
1267
+ }
1268
+
1269
+ return object;
790
1270
  }
791
1271
 
792
1272
  static inline VALUE json_push_value(JSON_ParserState *state, JSON_ParserConfig *config, VALUE value)
@@ -794,11 +1274,11 @@ static inline VALUE json_push_value(JSON_ParserState *state, JSON_ParserConfig *
794
1274
  if (RB_UNLIKELY(config->on_load_proc)) {
795
1275
  value = rb_proc_call_with_block(config->on_load_proc, 1, &value, Qnil);
796
1276
  }
797
- rvalue_stack_push(state->stack, value, &state->stack_handle, &state->stack);
1277
+ rvalue_stack_push(state->value_stack, value, state->value_stack_handle, &state->value_stack);
798
1278
  return value;
799
1279
  }
800
1280
 
801
- static const bool string_scan[256] = {
1281
+ static const bool string_scan_table[256] = {
802
1282
  // ASCII Control Characters
803
1283
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
804
1284
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
@@ -811,292 +1291,671 @@ static const bool string_scan[256] = {
811
1291
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
812
1292
  };
813
1293
 
814
- static inline VALUE json_parse_string(JSON_ParserState *state, JSON_ParserConfig *config, bool is_name)
1294
+ #ifdef HAVE_SIMD
1295
+ static SIMD_Implementation simd_impl = SIMD_NONE;
1296
+ #endif /* HAVE_SIMD */
1297
+
1298
+ ALWAYS_INLINE(static) bool string_scan(JSON_ParserState *state)
815
1299
  {
816
- state->cursor++;
817
- const char *start = state->cursor;
818
- bool escaped = false;
1300
+ #ifdef HAVE_SIMD
1301
+ #if defined(HAVE_SIMD_NEON)
819
1302
 
820
- while (state->cursor < state->end) {
821
- if (RB_UNLIKELY(string_scan[(unsigned char)*state->cursor])) {
822
- switch (*state->cursor) {
823
- case '"': {
824
- VALUE string = json_decode_string(state, config, start, state->cursor, escaped, is_name);
825
- state->cursor++;
826
- return json_push_value(state, config, string);
827
- }
828
- case '\\': {
829
- state->cursor++;
830
- escaped = true;
831
- if ((unsigned char)*state->cursor < 0x20) {
832
- raise_parse_error("invalid ASCII control character in string: %s", state->cursor);
833
- }
834
- break;
1303
+ uint64_t mask = 0;
1304
+ if (string_scan_simd_neon(&state->cursor, state->end, &mask)) {
1305
+ state->cursor += trailing_zeros64(mask) >> 2;
1306
+ return true;
1307
+ }
1308
+
1309
+ #elif defined(HAVE_SIMD_SSE2)
1310
+ if (simd_impl == SIMD_SSE2) {
1311
+ int mask = 0;
1312
+ if (string_scan_simd_sse2(&state->cursor, state->end, &mask)) {
1313
+ state->cursor += trailing_zeros(mask);
1314
+ return true;
1315
+ }
1316
+ }
1317
+ #endif /* HAVE_SIMD_NEON or HAVE_SIMD_SSE2 */
1318
+ #endif /* HAVE_SIMD */
1319
+
1320
+ while (!eos(state)) {
1321
+ if (RB_UNLIKELY(string_scan_table[(unsigned char)*state->cursor])) {
1322
+ return true;
1323
+ }
1324
+ state->cursor++;
1325
+ }
1326
+
1327
+ // If the string ended with an unterminated escape sequence, we might
1328
+ // have gone past the end.
1329
+ if (RB_UNLIKELY(state->cursor > state->end)) {
1330
+ state->cursor = state->end;
1331
+ }
1332
+
1333
+ return false;
1334
+ }
1335
+
1336
+ static VALUE json_parse_escaped_string(JSON_ParserState *state, JSON_ParserConfig *config, bool is_name, const char *start)
1337
+ {
1338
+ const char *backslashes[JSON_MAX_UNESCAPE_POSITIONS];
1339
+ JSON_UnescapePositions positions = {
1340
+ .size = 0,
1341
+ .positions = backslashes,
1342
+ .additional_backslashes = 0,
1343
+ };
1344
+
1345
+ do {
1346
+ switch (*state->cursor) {
1347
+ case '"': {
1348
+ VALUE string = json_string_unescape(state, config, start, state->cursor, is_name, &positions);
1349
+ state->cursor++;
1350
+ return string;
1351
+ }
1352
+ case '\\': {
1353
+ if (RB_LIKELY(positions.size < JSON_MAX_UNESCAPE_POSITIONS)) {
1354
+ backslashes[positions.size] = state->cursor;
1355
+ positions.size++;
1356
+ } else {
1357
+ positions.additional_backslashes++;
835
1358
  }
836
- default:
837
- raise_parse_error("invalid ASCII control character in string: %s", state->cursor);
838
- break;
1359
+ state->cursor++;
1360
+ break;
839
1361
  }
1362
+ default:
1363
+ if (!config->allow_control_characters) {
1364
+ raise_syntax_error("invalid ASCII control character in string: %s", state);
1365
+ }
1366
+ break;
840
1367
  }
841
1368
 
842
1369
  state->cursor++;
1370
+ } while (string_scan(state));
1371
+
1372
+ return Qundef;
1373
+ }
1374
+
1375
+ ALWAYS_INLINE(static) VALUE json_parse_string(JSON_ParserState *state, JSON_ParserConfig *config, bool is_name)
1376
+ {
1377
+ state->cursor++;
1378
+ const char *start = state->cursor;
1379
+
1380
+ if (RB_UNLIKELY(!string_scan(state))) {
1381
+ return Qundef;
843
1382
  }
844
1383
 
845
- raise_parse_error("unexpected end of input, expected closing \"", state->cursor);
846
- return Qfalse;
1384
+ VALUE string;
1385
+ if (RB_LIKELY(*state->cursor == '"')) {
1386
+ string = json_string_fastpath(state, config, start, state->cursor, is_name);
1387
+ state->cursor++;
1388
+ }
1389
+ else {
1390
+ string = json_parse_escaped_string(state, config, is_name, start);
1391
+ }
1392
+
1393
+ return string;
1394
+ }
1395
+
1396
+ #if JSON_CPU_LITTLE_ENDIAN_64BITS
1397
+ // From: https://lemire.me/blog/2022/01/21/swar-explained-parsing-eight-digits/
1398
+ // Additional References:
1399
+ // https://johnnylee-sde.github.io/Fast-numeric-string-to-int/
1400
+ // http://0x80.pl/notesen/2014-10-12-parsing-decimal-numbers-part-1-swar.html
1401
+ static inline uint64_t decode_8digits_unrolled(uint64_t val) {
1402
+ const uint64_t mask = 0x000000FF000000FF;
1403
+ const uint64_t mul1 = 0x000F424000000064; // 100 + (1000000ULL << 32)
1404
+ const uint64_t mul2 = 0x0000271000000001; // 1 + (10000ULL << 32)
1405
+ val -= 0x3030303030303030;
1406
+ val = (val * 10) + (val >> 8); // val = (val * 2561) >> 8;
1407
+ val = (((val & mask) * mul1) + (((val >> 16) & mask) * mul2)) >> 32;
1408
+ return val;
1409
+ }
1410
+
1411
+ static inline uint64_t decode_4digits_unrolled(uint32_t val) {
1412
+ const uint32_t mask = 0x000000FF;
1413
+ const uint32_t mul1 = 100;
1414
+ val -= 0x30303030;
1415
+ val = (val * 10) + (val >> 8); // val = (val * 2561) >> 8;
1416
+ val = ((val & mask) * mul1) + (((val >> 16) & mask));
1417
+ return val;
847
1418
  }
1419
+ #endif
848
1420
 
849
- static VALUE json_parse_any(JSON_ParserState *state, JSON_ParserConfig *config)
1421
+ static inline int json_parse_digits(JSON_ParserState *state, uint64_t *accumulator)
850
1422
  {
851
- json_eat_whitespace(state);
852
- if (state->cursor >= state->end) {
853
- raise_parse_error("unexpected end of input", state->cursor);
1423
+ const char *start = state->cursor;
1424
+
1425
+ #if JSON_CPU_LITTLE_ENDIAN_64BITS
1426
+ while (rest(state) >= sizeof(uint64_t)) {
1427
+ uint64_t next_8bytes;
1428
+ memcpy(&next_8bytes, state->cursor, sizeof(uint64_t));
1429
+
1430
+ // From: https://github.com/simdjson/simdjson/blob/32b301893c13d058095a07d9868edaaa42ee07aa/include/simdjson/generic/numberparsing.h#L333
1431
+ // Branchless version of: http://0x80.pl/articles/swar-digits-validate.html
1432
+ uint64_t match = (next_8bytes & 0xF0F0F0F0F0F0F0F0) | (((next_8bytes + 0x0606060606060606) & 0xF0F0F0F0F0F0F0F0) >> 4);
1433
+
1434
+ if (match == 0x3333333333333333) { // 8 consecutive digits
1435
+ *accumulator = (*accumulator * 100000000) + decode_8digits_unrolled(next_8bytes);
1436
+ state->cursor += 8;
1437
+ continue;
1438
+ }
1439
+
1440
+ uint32_t consecutive_digits = trailing_zeros64(match ^ 0x3333333333333333) / CHAR_BIT;
1441
+
1442
+ if (consecutive_digits >= 4) {
1443
+ *accumulator = (*accumulator * 10000) + decode_4digits_unrolled((uint32_t)next_8bytes);
1444
+ state->cursor += 4;
1445
+ consecutive_digits -= 4;
1446
+ }
1447
+
1448
+ while (consecutive_digits) {
1449
+ *accumulator = *accumulator * 10 + (*state->cursor - '0');
1450
+ consecutive_digits--;
1451
+ state->cursor++;
1452
+ }
1453
+
1454
+ return (int)(state->cursor - start);
854
1455
  }
1456
+ #endif
855
1457
 
856
- switch (*state->cursor) {
857
- case 'n':
858
- if ((state->end - state->cursor >= 4) && (memcmp(state->cursor, "null", 4) == 0)) {
859
- state->cursor += 4;
860
- return json_push_value(state, config, Qnil);
861
- }
1458
+ char next_char;
1459
+ while (rb_isdigit(next_char = peek(state))) {
1460
+ *accumulator = *accumulator * 10 + (next_char - '0');
1461
+ state->cursor++;
1462
+ }
1463
+ return (int)(state->cursor - start);
1464
+ }
862
1465
 
863
- raise_parse_error("unexpected token at '%s'", state->cursor);
864
- break;
865
- case 't':
866
- if ((state->end - state->cursor >= 4) && (memcmp(state->cursor, "true", 4) == 0)) {
867
- state->cursor += 4;
868
- return json_push_value(state, config, Qtrue);
869
- }
1466
+ static inline VALUE json_parse_number(JSON_ParserState *state, JSON_ParserConfig *config, bool negative, const char *start, bool resumable)
1467
+ {
1468
+ bool integer = true;
1469
+ const char first_digit = *state->cursor;
870
1470
 
871
- raise_parse_error("unexpected token at '%s'", state->cursor);
872
- break;
873
- case 'f':
874
- // Note: memcmp with a small power of two compile to an integer comparison
875
- if ((state->end - state->cursor >= 5) && (memcmp(state->cursor + 1, "alse", 4) == 0)) {
876
- state->cursor += 5;
877
- return json_push_value(state, config, Qfalse);
878
- }
1471
+ // Variables for Ryu optimization - extract digits during parsing
1472
+ int64_t exponent = 0;
1473
+ int decimal_point_pos = -1;
1474
+ uint64_t mantissa = 0;
879
1475
 
880
- raise_parse_error("unexpected token at '%s'", state->cursor);
881
- break;
882
- case 'N':
883
- // Note: memcmp with a small power of two compile to an integer comparison
884
- if (config->allow_nan && (state->end - state->cursor >= 3) && (memcmp(state->cursor + 1, "aN", 2) == 0)) {
885
- state->cursor += 3;
886
- return json_push_value(state, config, CNaN);
887
- }
1476
+ // Parse integer part and extract mantissa digits
1477
+ int mantissa_digits = json_parse_digits(state, &mantissa);
888
1478
 
889
- raise_parse_error("unexpected token at '%s'", state->cursor);
890
- break;
891
- case 'I':
892
- if (config->allow_nan && (state->end - state->cursor >= 8) && (memcmp(state->cursor, "Infinity", 8) == 0)) {
893
- state->cursor += 8;
894
- return json_push_value(state, config, CInfinity);
895
- }
1479
+ if (RB_UNLIKELY((first_digit == '0' && mantissa_digits > 1) || (negative && mantissa_digits == 0))) {
1480
+ return Qundef;
1481
+ }
896
1482
 
897
- raise_parse_error("unexpected token at '%s'", state->cursor);
898
- break;
899
- case '-':
900
- // Note: memcmp with a small power of two compile to an integer comparison
901
- if ((state->end - state->cursor >= 9) && (memcmp(state->cursor + 1, "Infinity", 8) == 0)) {
902
- if (config->allow_nan) {
903
- state->cursor += 9;
904
- return json_push_value(state, config, CMinusInfinity);
905
- } else {
906
- raise_parse_error("unexpected token at '%s'", state->cursor);
907
- }
908
- }
909
- // Fallthrough
910
- case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': {
911
- bool integer = true;
1483
+ // Parse fractional part
1484
+ if (peek(state) == '.') {
1485
+ integer = false;
1486
+ decimal_point_pos = mantissa_digits; // Remember position of decimal point
1487
+ state->cursor++;
912
1488
 
913
- // /\A-?(0|[1-9]\d*)(\.\d+)?([Ee][-+]?\d+)?/
914
- const char *start = state->cursor;
1489
+ int fractional_digits = json_parse_digits(state, &mantissa);
1490
+ mantissa_digits += fractional_digits;
1491
+
1492
+ if (RB_UNLIKELY(!fractional_digits)) {
1493
+ return Qundef;
1494
+ }
1495
+ }
1496
+
1497
+ // Parse exponent
1498
+ if (rb_tolower(peek(state)) == 'e') {
1499
+ integer = false;
1500
+ state->cursor++;
1501
+
1502
+ bool negative_exponent = false;
1503
+ const char next_char = peek(state);
1504
+ if (next_char == '-' || next_char == '+') {
1505
+ negative_exponent = next_char == '-';
915
1506
  state->cursor++;
1507
+ }
916
1508
 
917
- while ((state->cursor < state->end) && (*state->cursor >= '0') && (*state->cursor <= '9')) {
918
- state->cursor++;
919
- }
1509
+ uint64_t abs_exponent = 0;
1510
+ int exponent_digits = json_parse_digits(state, &abs_exponent);
920
1511
 
921
- long integer_length = state->cursor - start;
1512
+ if (RB_UNLIKELY(!exponent_digits)) {
1513
+ return Qundef;
1514
+ }
922
1515
 
923
- if (RB_UNLIKELY(start[0] == '0' && integer_length > 1)) {
924
- raise_parse_error("invalid number: %s", start);
925
- } else if (RB_UNLIKELY(integer_length > 2 && start[0] == '-' && start[1] == '0')) {
926
- raise_parse_error("invalid number: %s", start);
927
- } else if (RB_UNLIKELY(integer_length == 1 && start[0] == '-')) {
928
- raise_parse_error("invalid number: %s", start);
929
- }
1516
+ if (RB_UNLIKELY(exponent_digits >= 20 || abs_exponent > (uint64_t)INT64_MAX)) {
1517
+ exponent = negative_exponent ? INT64_MIN : INT64_MAX;
1518
+ } else {
1519
+ exponent = negative_exponent ? -(int64_t)abs_exponent : (int64_t)abs_exponent;
1520
+ }
1521
+ }
930
1522
 
931
- if ((state->cursor < state->end) && (*state->cursor == '.')) {
932
- integer = false;
933
- state->cursor++;
1523
+ // A number touching the end of the buffer may still grow in a later chunk,
1524
+ // so the caller will rewind and wait. Decoding it now would build a value
1525
+ // -- for a long run of digits, an expensive bignum -- only to discard it,
1526
+ // and repeating that on every resumed chunk is quadratic in the number's
1527
+ // length. The digit scan above already advanced the cursor, which is all
1528
+ // the caller needs to detect the incomplete number.
1529
+ if (RB_UNLIKELY(resumable && eos(state))) {
1530
+ return Qundef;
1531
+ }
1532
+
1533
+ if (integer) {
1534
+ return json_decode_integer(mantissa, mantissa_digits, negative, start, state->cursor);
1535
+ }
1536
+
1537
+ // Adjust exponent based on decimal point position
1538
+ if (decimal_point_pos >= 0) {
1539
+ exponent -= (mantissa_digits - decimal_point_pos);
1540
+ }
1541
+
1542
+ return json_decode_float(config, mantissa, mantissa_digits, exponent, negative, start, state->cursor);
1543
+ }
1544
+
1545
+ // How many values (array elements, or interleaved object keys+values) have been
1546
+ // pushed onto the rvalue stack since this container opened. Used to size the
1547
+ // bulk decode on close, and to tell the first key/colon from later ones.
1548
+ static inline long json_frame_entry_count(const json_frame *frame, const rvalue_stack *value_stack)
1549
+ {
1550
+ return value_stack->head - frame->value_stack_head;
1551
+ }
1552
+
1553
+ // A complete value now sits on top of the rvalue stack. Advance the frame that
1554
+ // was waiting for it: the root document is done, or the enclosing container
1555
+ // moves on to expecting a ',' or its closing bracket. The caller passes the
1556
+ // frame it already has in hand -- the one that was expecting the value -- which
1557
+ // after a container close is the freshly re-exposed parent.
1558
+ static inline enum json_frame_phase json_value_completed(json_frame *frame)
1559
+ {
1560
+ JSON_ASSERT((int)JSON_PHASE_DONE == (int)JSON_FRAME_ROOT);
1561
+ JSON_ASSERT((int)JSON_PHASE_ARRAY_COMMA == (int)JSON_FRAME_ARRAY);
1562
+ JSON_ASSERT((int)JSON_PHASE_OBJECT_COMMA == (int)JSON_FRAME_OBJECT);
1563
+
1564
+ return frame->phase = (enum json_frame_phase) frame->type;
1565
+ }
1566
+
1567
+ ALWAYS_INLINE(static) void json_match_keyword(JSON_ParserState *state, const char *keyword, size_t offset)
1568
+ {
1569
+ // It is assumed that since `keyword` is always a literal, the compiler is able to constantize this
1570
+ // `strlen` and several other computations in that routine.
1571
+
1572
+ size_t len = strlen(keyword);
1573
+
1574
+ // Note: memcmp with a small power of two and a literal string compile to an integer comparison /
1575
+ // That's why we sometime compare starting from the first byte and sometimes from the second.
1576
+ if (rest(state) >= len && (memcmp(state->cursor + offset, keyword + offset, len - offset) == 0)) {
1577
+ state->cursor += len;
1578
+ return;
1579
+ }
1580
+
1581
+ bool eos = rest(state) < len && memcmp(state->cursor, keyword, rest(state)) == 0;
1582
+ raise_parse_error("unexpected token %s", state, eos);
1583
+ }
934
1584
 
935
- if (state->cursor == state->end || *state->cursor < '0' || *state->cursor > '9') {
936
- raise_parse_error("invalid number: %s", state->cursor);
1585
+ // Parse an arbitrary JSON value iteratively. This is a state machine driven
1586
+ // entirely by the top frame's phase so it can stop at any value boundary and
1587
+ // resume purely from the frame stack. A JSON_FRAME_ROOT frame sits at the
1588
+ // bottom of the stack, so the stack is never empty mid-parse and the document
1589
+ // itself is just another frame whose value, once parsed, leaves its phase DONE.
1590
+ // When invoked in resumable mode, it returns true after parsing a complete document.
1591
+ // If reaching EOS without having parsed a complete document, either returns false
1592
+ // of raise a JSON::ParserError tagged with `@eos=true`.
1593
+ ALWAYS_INLINE(static) bool json_parse_any(JSON_ParserState *state, JSON_ParserConfig *config, bool resumable)
1594
+ {
1595
+ json_frame *frame = json_frame_stack_peek(state->frames);
1596
+
1597
+ switch (frame->phase) {
1598
+ case JSON_PHASE_DONE: JSON_UNREACHABLE_RETURN(false);
1599
+ case JSON_PHASE_ARRAY_COMMA: goto JSON_PHASE_ARRAY_COMMA;
1600
+ case JSON_PHASE_OBJECT_COMMA: goto JSON_PHASE_OBJECT_COMMA;
1601
+ case JSON_PHASE_VALUE: goto JSON_PHASE_VALUE;
1602
+ case JSON_PHASE_OBJECT_KEY: goto JSON_PHASE_OBJECT_KEY;
1603
+ case JSON_PHASE_OBJECT_COLON: goto JSON_PHASE_OBJECT_COLON;
1604
+ }
1605
+ JSON_UNREACHABLE_RETURN(false);
1606
+
1607
+ JSON_PHASE_VALUE: {
1608
+ json_eat_whitespace(state, config, true);
1609
+
1610
+ // A trailing comma lands us here expecting an element but finding the
1611
+ // closing bracket; hand off to ARRAY_COMMA to close. An empty array
1612
+ // closes inline at '[', so this position is only reached after a ','.
1613
+ if (config->allow_trailing_comma && frame->type == JSON_FRAME_ARRAY && peek(state) == ']') {
1614
+ goto JSON_PHASE_ARRAY_COMMA;
1615
+ }
1616
+
1617
+ VALUE value;
1618
+ const char *value_start = state->cursor;
1619
+
1620
+ switch (peek(state)) {
1621
+ case 'n':
1622
+ json_match_keyword(state, "null", 0);
1623
+ value = Qnil;
1624
+ break;
1625
+
1626
+ case 't':
1627
+ json_match_keyword(state, "true", 0);
1628
+ value = Qtrue;
1629
+ break;
1630
+
1631
+ case 'f':
1632
+ json_match_keyword(state, "false", 1);
1633
+ value = Qfalse;
1634
+ break;
1635
+
1636
+ case 'N':
1637
+ if (!config->allow_nan) {
1638
+ raise_syntax_error("unexpected token %s", state);
937
1639
  }
938
1640
 
939
- while ((state->cursor < state->end) && (*state->cursor >= '0') && (*state->cursor <= '9')) {
940
- state->cursor++;
1641
+ json_match_keyword(state, "NaN", 1);
1642
+ value = CNaN;
1643
+ break;
1644
+
1645
+ case 'I':
1646
+ if (!config->allow_nan) {
1647
+ raise_syntax_error("unexpected token %s", state);
941
1648
  }
942
- }
943
1649
 
944
- if ((state->cursor < state->end) && ((*state->cursor == 'e') || (*state->cursor == 'E'))) {
945
- integer = false;
1650
+ json_match_keyword(state, "Infinity", 0);
1651
+ value = CInfinity;
1652
+ break;
1653
+
1654
+ case '-': {
946
1655
  state->cursor++;
947
- if ((state->cursor < state->end) && ((*state->cursor == '+') || (*state->cursor == '-'))) {
948
- state->cursor++;
1656
+
1657
+ value = json_parse_number(state, config, true, value_start, resumable);
1658
+
1659
+ if (RB_UNLIKELY(UNDEF_P(value) && config->allow_nan && peek(state) == 'I')) {
1660
+ state->cursor = value_start;
1661
+ json_match_keyword(state, "-Infinity", 1);
1662
+ value = CMinusInfinity;
1663
+ break;
949
1664
  }
950
1665
 
951
- if (state->cursor == state->end || *state->cursor < '0' || *state->cursor > '9') {
952
- raise_parse_error("invalid number: %s", state->cursor);
1666
+ // Top level numbers are ambiguous when parsing streams, we can't
1667
+ // know if we parsed all the digits if we hit EOS.
1668
+ if (RB_UNLIKELY(resumable && eos(state))) {
1669
+ state->cursor = value_start;
1670
+ return false;
953
1671
  }
954
1672
 
955
- while ((state->cursor < state->end) && (*state->cursor >= '0') && (*state->cursor <= '9')) {
956
- state->cursor++;
1673
+ if (RB_UNLIKELY(UNDEF_P(value))) {
1674
+ raise_syntax_error_at("invalid number: %s", state, value_start);
957
1675
  }
1676
+ break;
958
1677
  }
959
1678
 
960
- if (integer) {
961
- return json_push_value(state, config, json_decode_integer(start, state->cursor));
962
- }
963
- return json_push_value(state, config, json_decode_float(config, start, state->cursor));
964
- }
965
- case '"': {
966
- // %r{\A"[^"\\\t\n\x00]*(?:\\[bfnrtu\\/"][^"\\]*)*"}
967
- return json_parse_string(state, config, false);
968
- break;
969
- }
970
- case '[': {
971
- state->cursor++;
972
- json_eat_whitespace(state);
973
- long stack_head = state->stack->head;
1679
+ case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': {
1680
+ value = json_parse_number(state, config, false, value_start, resumable);
974
1681
 
975
- if ((state->cursor < state->end) && (*state->cursor == ']')) {
976
- state->cursor++;
977
- return json_push_value(state, config, json_decode_array(state, config, 0));
978
- } else {
979
- state->current_nesting++;
980
- if (RB_UNLIKELY(config->max_nesting && (config->max_nesting < state->current_nesting))) {
981
- rb_raise(eNestingError, "nesting of %d is too deep", state->current_nesting);
1682
+ // Top level numbers are ambiguous when parsing streams, we can't
1683
+ // know if we parsed all the digits if we hit EOS.
1684
+ if (RB_UNLIKELY(resumable && eos(state))) {
1685
+ state->cursor = value_start;
1686
+ return false;
982
1687
  }
983
- state->in_array++;
984
- json_parse_any(state, config);
1688
+
1689
+ if (RB_UNLIKELY(UNDEF_P(value))) {
1690
+ raise_syntax_error_at("invalid number: %s", state, value_start);
1691
+ }
1692
+ break;
985
1693
  }
986
1694
 
987
- while (true) {
988
- json_eat_whitespace(state);
989
-
990
- if (state->cursor < state->end) {
991
- if (*state->cursor == ']') {
992
- state->cursor++;
993
- long count = state->stack->head - stack_head;
994
- state->current_nesting--;
995
- state->in_array--;
996
- return json_push_value(state, config, json_decode_array(state, config, count));
997
- }
1695
+ case '"': {
1696
+ // %r{\A"[^"\\\t\n\x00]*(?:\\[bfnrtu\\/"][^"\\]*)*"}
1697
+ value = json_parse_string(state, config, false);
998
1698
 
999
- if (*state->cursor == ',') {
1000
- state->cursor++;
1001
- if (config->allow_trailing_comma) {
1002
- json_eat_whitespace(state);
1003
- if ((state->cursor < state->end) && (*state->cursor == ']')) {
1004
- continue;
1005
- }
1006
- }
1007
- json_parse_any(state, config);
1008
- continue;
1699
+ if (RB_UNLIKELY(UNDEF_P(value))) {
1700
+ bool is_eos = eos(state);
1701
+ if (resumable && is_eos) {
1702
+ state->cursor = value_start;
1703
+ return false;
1009
1704
  }
1705
+ raise_parse_error("unexpected end of input, expected closing \"", state, is_eos);
1010
1706
  }
1011
-
1012
- raise_parse_error("expected ',' or ']' after array value", state->cursor);
1707
+ break;
1013
1708
  }
1014
- break;
1015
- }
1016
- case '{': {
1017
- state->cursor++;
1018
- json_eat_whitespace(state);
1019
- long stack_head = state->stack->head;
1020
1709
 
1021
- if ((state->cursor < state->end) && (*state->cursor == '}')) {
1710
+ case '[': {
1022
1711
  state->cursor++;
1023
- return json_push_value(state, config, json_decode_object(state, config, 0));
1024
- } else {
1712
+ // The '[' is consumed but its frame is only pushed below, so a
1713
+ // comment suspending here must resume from the bracket.
1714
+ json_eat_whitespace_resume_at(state, config, true, value_start);
1715
+
1716
+ const char next = peek(state);
1717
+ if (next == ']') {
1718
+ state->cursor++;
1719
+ value = json_decode_array(state, config, 0);
1720
+ break;
1721
+ } else if (resumable && eos(state)) {
1722
+ state->cursor = value_start;
1723
+ return false;
1724
+ }
1725
+
1025
1726
  state->current_nesting++;
1026
1727
  if (RB_UNLIKELY(config->max_nesting && (config->max_nesting < state->current_nesting))) {
1027
1728
  rb_raise(eNestingError, "nesting of %d is too deep", state->current_nesting);
1028
1729
  }
1730
+ state->in_array++;
1731
+
1732
+ // Phase stays VALUE: the next iteration reads the first element.
1733
+ frame = json_frame_stack_push(state, (json_frame){
1734
+ .type = JSON_FRAME_ARRAY,
1735
+ .phase = JSON_PHASE_VALUE,
1736
+ .value_stack_head = state->value_stack->head,
1737
+ });
1738
+ goto JSON_PHASE_VALUE;
1739
+ }
1740
+
1741
+ case '{': {
1742
+ state->cursor++;
1743
+ // Same as '[': the frame is only pushed below.
1744
+ json_eat_whitespace_resume_at(state, config, true, value_start);
1029
1745
 
1030
- if (*state->cursor != '"') {
1031
- raise_parse_error("expected object key, got '%s", state->cursor);
1746
+ if (peek(state) == '}') {
1747
+ state->cursor++;
1748
+ value = json_decode_object(state, config, 0);
1749
+ break;
1750
+ } else if (resumable && eos(state)) {
1751
+ state->cursor = value_start;
1752
+ return false;
1032
1753
  }
1033
- json_parse_string(state, config, true);
1034
1754
 
1035
- json_eat_whitespace(state);
1036
- if ((state->cursor >= state->end) || (*state->cursor != ':')) {
1037
- raise_parse_error("expected ':' after object key", state->cursor);
1755
+ state->current_nesting++;
1756
+ if (RB_UNLIKELY(config->max_nesting && (config->max_nesting < state->current_nesting))) {
1757
+ rb_raise(eNestingError, "nesting of %d is too deep", state->current_nesting);
1038
1758
  }
1039
- state->cursor++;
1040
1759
 
1041
- json_parse_any(state, config);
1760
+ // Phase KEY: the next iteration reads the first key.
1761
+ frame = json_frame_stack_push(state, (json_frame){
1762
+ .type = JSON_FRAME_OBJECT,
1763
+ .phase = JSON_PHASE_OBJECT_KEY,
1764
+ .value_stack_head = state->value_stack->head,
1765
+ .start_offset = value_start - state->start,
1766
+ });
1767
+ goto JSON_PHASE_OBJECT_KEY;
1042
1768
  }
1043
1769
 
1044
- while (true) {
1045
- json_eat_whitespace(state);
1046
-
1047
- if (state->cursor < state->end) {
1048
- if (*state->cursor == '}') {
1049
- state->cursor++;
1050
- state->current_nesting--;
1051
- long count = state->stack->head - stack_head;
1052
- return json_push_value(state, config, json_decode_object(state, config, count));
1053
- }
1770
+ case 0:
1771
+ // peek() returns 0 both at end-of-stream and for a literal NUL byte in the
1772
+ // buffer. Only a genuine EOS means "feed me more"; a NUL byte that is not at
1773
+ // EOS is just an invalid character.
1774
+ if (eos(state)) {
1775
+ return false;
1776
+ } else {
1777
+ raise_syntax_error("unexpected NULL byte: %s", state);
1778
+ }
1779
+ default:
1780
+ raise_syntax_error("unexpected character: %s", state);
1781
+ }
1054
1782
 
1055
- if (*state->cursor == ',') {
1056
- state->cursor++;
1057
- json_eat_whitespace(state);
1783
+ json_push_value(state, config, value);
1784
+ json_value_completed(frame);
1058
1785
 
1059
- if (config->allow_trailing_comma) {
1060
- if ((state->cursor < state->end) && (*state->cursor == '}')) {
1061
- continue;
1062
- }
1063
- }
1786
+ switch (frame->phase) {
1787
+ case JSON_PHASE_DONE: return true;
1788
+ case JSON_PHASE_ARRAY_COMMA: goto JSON_PHASE_ARRAY_COMMA;
1789
+ case JSON_PHASE_OBJECT_COMMA: goto JSON_PHASE_OBJECT_COMMA;
1790
+ case JSON_PHASE_VALUE: goto JSON_PHASE_VALUE;
1791
+ case JSON_PHASE_OBJECT_KEY: JSON_UNREACHABLE_RETURN(false);
1792
+ case JSON_PHASE_OBJECT_COLON: goto JSON_PHASE_OBJECT_COLON;
1793
+ }
1794
+ JSON_UNREACHABLE_RETURN(false);
1795
+ }
1064
1796
 
1065
- if (*state->cursor != '"') {
1066
- raise_parse_error("expected object key, got: '%s'", state->cursor);
1067
- }
1068
- json_parse_string(state, config, true);
1797
+ JSON_PHASE_OBJECT_KEY: {
1798
+ JSON_ASSERT(frame->type == JSON_FRAME_OBJECT);
1069
1799
 
1070
- json_eat_whitespace(state);
1071
- if ((state->cursor >= state->end) || (*state->cursor != ':')) {
1072
- raise_parse_error("expected ':' after object key, got: '%s", state->cursor);
1073
- }
1074
- state->cursor++;
1800
+ json_eat_whitespace(state, config, true);
1075
1801
 
1076
- json_parse_any(state, config);
1802
+ // A trailing comma lands us here expecting a key but finding the closing
1803
+ // brace; hand off to OBJECT_COMMA to close. An empty object closes inline
1804
+ // at '{', so this position is only reached after a ','.
1805
+ if (config->allow_trailing_comma && peek(state) == '}') {
1806
+ goto JSON_PHASE_OBJECT_COMMA;
1807
+ }
1077
1808
 
1078
- continue;
1079
- }
1809
+ const char *start = state->cursor;
1810
+
1811
+ if (RB_LIKELY(peek(state) == '"')) {
1812
+ VALUE string = json_parse_string(state, config, true);
1813
+ if (UNDEF_P(string)) {
1814
+ if (resumable) {
1815
+ state->cursor = start;
1816
+ return false;
1817
+ } else {
1818
+ raise_syntax_error("unexpected end of input, expected closing \"", state);
1080
1819
  }
1820
+ }
1821
+ json_push_value(state, config, string);
1822
+ frame->phase = JSON_PHASE_OBJECT_COLON;
1823
+ goto JSON_PHASE_OBJECT_COLON;
1824
+ } else if (resumable && eos(state)) {
1825
+ return false;
1826
+ } else {
1827
+ // The message differs for the first key vs. a key after a
1828
+ // ',': the first is the only one reached with nothing pushed
1829
+ // for this object yet.
1830
+ if (json_frame_entry_count(frame, state->value_stack) == 0) {
1831
+ raise_syntax_error("expected object key, got %s", state);
1832
+ } else {
1833
+ raise_syntax_error("expected object key, got: %s", state);
1834
+ }
1835
+ }
1836
+ JSON_UNREACHABLE_RETURN(false);
1837
+ }
1838
+
1839
+ JSON_PHASE_OBJECT_COLON: {
1840
+ JSON_ASSERT(frame->type == JSON_FRAME_OBJECT);
1081
1841
 
1082
- raise_parse_error("expected ',' or '}' after object value, got: '%s'", state->cursor);
1842
+ json_eat_whitespace(state, config, true);
1843
+
1844
+ if (RB_LIKELY(peek(state) == ':')) {
1845
+ state->cursor++;
1846
+ frame->phase = JSON_PHASE_VALUE;
1847
+ goto JSON_PHASE_VALUE;
1848
+ } else if (resumable && eos(state)) {
1849
+ return false;
1850
+ } else {
1851
+ // First colon (only the first pair's key is pushed, nothing
1852
+ // else) vs. a later one.
1853
+ if (json_frame_entry_count(frame, state->value_stack) == 1) {
1854
+ raise_syntax_error("expected ':' after object key", state);
1855
+ } else {
1856
+ raise_syntax_error("expected ':' after object key, got: %s", state);
1083
1857
  }
1084
- break;
1085
1858
  }
1859
+ JSON_UNREACHABLE_RETURN(false);
1860
+ }
1086
1861
 
1087
- default:
1088
- raise_parse_error("unexpected character: '%s'", state->cursor);
1089
- break;
1862
+ JSON_PHASE_ARRAY_COMMA: {
1863
+ JSON_ASSERT(frame->type == JSON_FRAME_ARRAY);
1864
+
1865
+ json_eat_whitespace(state, config, true);
1866
+
1867
+ const char next_char = peek(state);
1868
+
1869
+ if (RB_LIKELY(next_char == ',')) {
1870
+ state->cursor++;
1871
+ // Commit the phase before eating the whitespace that follows: an
1872
+ // incomplete comment there would suspend the parse, and a phase not
1873
+ // yet advanced past the ',' would drop it on resume. A trailing comma
1874
+ // is recognized in JSON_PHASE_VALUE once the ']' is in the buffer.
1875
+ frame->phase = JSON_PHASE_VALUE;
1876
+ goto JSON_PHASE_VALUE;
1877
+ } else if (next_char == ']') {
1878
+ state->cursor++;
1879
+ long count = json_frame_entry_count(frame, state->value_stack);
1880
+ state->current_nesting--;
1881
+ state->in_array--;
1882
+
1883
+ json_push_value(state, config, json_decode_array(state, config, count));
1884
+ json_frame_stack_pop(state->frames);
1885
+ frame = json_frame_stack_peek(state->frames);
1886
+
1887
+ json_value_completed(frame);
1888
+
1889
+ switch (frame->phase) {
1890
+ case JSON_PHASE_DONE: return true;
1891
+ case JSON_PHASE_ARRAY_COMMA: goto JSON_PHASE_ARRAY_COMMA;
1892
+ case JSON_PHASE_OBJECT_COMMA: goto JSON_PHASE_OBJECT_COMMA;
1893
+ case JSON_PHASE_VALUE: goto JSON_PHASE_VALUE;
1894
+ case JSON_PHASE_OBJECT_KEY: JSON_UNREACHABLE_RETURN(false);
1895
+ case JSON_PHASE_OBJECT_COLON: goto JSON_PHASE_OBJECT_COLON;
1896
+ }
1897
+ } else if (resumable && eos(state)) {
1898
+ return false;
1899
+ } else {
1900
+ raise_syntax_error("expected ',' or ']' after array value", state);
1901
+ }
1902
+ JSON_UNREACHABLE_RETURN(false);
1903
+ }
1904
+
1905
+ JSON_PHASE_OBJECT_COMMA: {
1906
+ JSON_ASSERT(frame->type == JSON_FRAME_OBJECT);
1907
+
1908
+ json_eat_whitespace(state, config, true);
1909
+ const char next_char = peek(state);
1910
+
1911
+ if (RB_LIKELY(next_char == ',')) {
1912
+ state->cursor++;
1913
+ // Commit the phase before eating the whitespace that follows: an
1914
+ // incomplete comment there would suspend the parse, and a phase not
1915
+ // yet advanced past the ',' would drop it on resume. A trailing comma
1916
+ // is recognized in JSON_PHASE_OBJECT_KEY once the '}' is in the buffer.
1917
+ frame->phase = JSON_PHASE_OBJECT_KEY;
1918
+ goto JSON_PHASE_OBJECT_KEY;
1919
+ } else if (next_char == '}') {
1920
+ state->cursor++;
1921
+ state->current_nesting--;
1922
+ size_t count = json_frame_entry_count(frame, state->value_stack);
1923
+
1924
+ // Temporary rewind cursor in case an error is raised
1925
+ const char *final_cursor = state->cursor;
1926
+ state->cursor = state->start + frame->start_offset;
1927
+ VALUE object = json_decode_object(state, config, count);
1928
+ state->cursor = final_cursor;
1929
+
1930
+ json_push_value(state, config, object);
1931
+ json_frame_stack_pop(state->frames);
1932
+ frame = json_frame_stack_peek(state->frames);
1933
+ json_value_completed(frame);
1934
+
1935
+ switch (frame->phase) {
1936
+ case JSON_PHASE_DONE: return true;
1937
+ case JSON_PHASE_ARRAY_COMMA: goto JSON_PHASE_ARRAY_COMMA;
1938
+ case JSON_PHASE_OBJECT_COMMA: goto JSON_PHASE_OBJECT_COMMA;
1939
+ case JSON_PHASE_VALUE: goto JSON_PHASE_VALUE;
1940
+ case JSON_PHASE_OBJECT_KEY: JSON_UNREACHABLE_RETURN(false);
1941
+ case JSON_PHASE_OBJECT_COLON: goto JSON_PHASE_OBJECT_COLON;
1942
+ }
1943
+ } else if (resumable && eos(state)) {
1944
+ return false;
1945
+ } else {
1946
+ raise_syntax_error("expected ',' or '}' after object value, got: %s", state);
1947
+ }
1948
+ JSON_UNREACHABLE_RETURN(false);
1090
1949
  }
1091
1950
 
1092
- raise_parse_error("unreacheable: '%s'", state->cursor);
1951
+ JSON_UNREACHABLE_RETURN(false);
1093
1952
  }
1094
1953
 
1095
- static void json_ensure_eof(JSON_ParserState *state)
1954
+ static void json_ensure_eof(JSON_ParserState *state, JSON_ParserConfig *config)
1096
1955
  {
1097
- json_eat_whitespace(state);
1098
- if (state->cursor != state->end) {
1099
- raise_parse_error("unexpected token at end of stream '%s'", state->cursor);
1956
+ json_eat_whitespace(state, config, true);
1957
+ if (!eos(state)) {
1958
+ raise_syntax_error("unexpected token at end of stream %s", state);
1100
1959
  }
1101
1960
  }
1102
1961
 
@@ -1114,37 +1973,59 @@ static void json_ensure_eof(JSON_ParserState *state)
1114
1973
 
1115
1974
  static VALUE convert_encoding(VALUE source)
1116
1975
  {
1117
- int encindex = RB_ENCODING_GET(source);
1976
+ StringValue(source);
1977
+ int encindex = RB_ENCODING_GET(source);
1978
+
1979
+ if (RB_LIKELY(encindex == utf8_encindex)) {
1980
+ return source;
1981
+ }
1118
1982
 
1119
- if (RB_LIKELY(encindex == utf8_encindex)) {
1983
+ if (encindex == binary_encindex) {
1984
+ // For historical reason, we silently reinterpret binary strings as UTF-8
1985
+ return rb_enc_associate_index(rb_str_dup(source), utf8_encindex);
1986
+ }
1987
+
1988
+ source = rb_funcall(source, i_encode, 1, Encoding_UTF_8);
1989
+ StringValue(source);
1120
1990
  return source;
1121
- }
1991
+ }
1122
1992
 
1123
- if (encindex == binary_encindex) {
1124
- // For historical reason, we silently reinterpret binary strings as UTF-8
1125
- return rb_enc_associate_index(rb_str_dup(source), utf8_encindex);
1126
- }
1993
+ struct parser_config_init_args {
1994
+ JSON_ParserConfig *config;
1995
+ VALUE self;
1996
+ VALUE unknown_keywords;
1997
+ bool strict;
1998
+ };
1127
1999
 
1128
- return rb_funcall(source, i_encode, 1, Encoding_UTF_8);
2000
+ static void parser_config_wb_write(VALUE self, VALUE *dest, VALUE val)
2001
+ {
2002
+ *dest = val;
2003
+ if (self) RB_OBJ_WRITTEN(self, Qundef, val);
1129
2004
  }
1130
2005
 
1131
2006
  static int parser_config_init_i(VALUE key, VALUE val, VALUE data)
1132
2007
  {
1133
- JSON_ParserConfig *config = (JSON_ParserConfig *)data;
1134
-
1135
- if (key == sym_max_nesting) { config->max_nesting = RTEST(val) ? FIX2INT(val) : 0; }
1136
- else if (key == sym_allow_nan) { config->allow_nan = RTEST(val); }
1137
- else if (key == sym_allow_trailing_comma) { config->allow_trailing_comma = RTEST(val); }
1138
- else if (key == sym_symbolize_names) { config->symbolize_names = RTEST(val); }
1139
- else if (key == sym_freeze) { config->freeze = RTEST(val); }
1140
- else if (key == sym_on_load) { config->on_load_proc = RTEST(val) ? val : Qfalse; }
1141
- else if (key == sym_decimal_class) {
2008
+ struct parser_config_init_args *args = (struct parser_config_init_args *)data;
2009
+ JSON_ParserConfig *config = args->config;
2010
+ VALUE self = args->self;
2011
+
2012
+ if (key == sym_max_nesting) { config->max_nesting = RTEST(val) ? FIX2INT(val) : 0; }
2013
+ else if (key == sym_allow_nan) { config->allow_nan = RTEST(val); }
2014
+ else if (key == sym_allow_trailing_comma) { config->allow_trailing_comma = RTEST(val); }
2015
+ else if (key == sym_allow_comments) { config->on_comment = RTEST(val) ? JSON_IGNORE : JSON_RAISE; }
2016
+ else if (key == sym_allow_control_characters) { config->allow_control_characters = RTEST(val); }
2017
+ else if (key == sym_allow_invalid_escape) { config->allow_invalid_escape = RTEST(val); }
2018
+ else if (key == sym_symbolize_names) { config->symbolize_names = RTEST(val); }
2019
+ else if (key == sym_freeze) { config->freeze = RTEST(val); }
2020
+ else if (key == sym_on_load) { parser_config_wb_write(self, &config->on_load_proc, RTEST(val) ? val : Qfalse); }
2021
+ else if (key == sym_allow_duplicate_key) { config->on_duplicate_key = RTEST(val) ? JSON_IGNORE : JSON_RAISE; }
2022
+ else if (key == sym_decimal_class) {
1142
2023
  if (RTEST(val)) {
1143
2024
  if (rb_respond_to(val, i_try_convert)) {
1144
- config->decimal_class = val;
2025
+ parser_config_wb_write(self, &config->decimal_class, val);
1145
2026
  config->decimal_method_id = i_try_convert;
1146
2027
  } else if (rb_respond_to(val, i_new)) {
1147
- config->decimal_class = val;
2028
+ parser_config_wb_write(self, &config->decimal_class, val);
1148
2029
  config->decimal_method_id = i_new;
1149
2030
  } else if (RB_TYPE_P(val, T_CLASS)) {
1150
2031
  VALUE name = rb_class_name(val);
@@ -1153,7 +2034,7 @@ static int parser_config_init_i(VALUE key, VALUE val, VALUE data)
1153
2034
  if (last_colon) {
1154
2035
  const char *mod_path_end = last_colon - 1;
1155
2036
  VALUE mod_path = rb_str_substr(name, 0, mod_path_end - name_cstr);
1156
- config->decimal_class = rb_path_to_class(mod_path);
2037
+ parser_config_wb_write(self, &config->decimal_class, rb_path_to_class(mod_path));
1157
2038
 
1158
2039
  const char *method_name_beg = last_colon + 1;
1159
2040
  long before_len = method_name_beg - name_cstr;
@@ -1161,28 +2042,48 @@ static int parser_config_init_i(VALUE key, VALUE val, VALUE data)
1161
2042
  VALUE method_name = rb_str_substr(name, before_len, len);
1162
2043
  config->decimal_method_id = SYM2ID(rb_str_intern(method_name));
1163
2044
  } else {
1164
- config->decimal_class = rb_mKernel;
2045
+ parser_config_wb_write(self, &config->decimal_class, rb_mKernel);
1165
2046
  config->decimal_method_id = SYM2ID(rb_str_intern(name));
1166
2047
  }
1167
2048
  }
1168
2049
  }
1169
2050
  }
2051
+ else if (args->strict) {
2052
+ if (!args->unknown_keywords) {
2053
+ args->unknown_keywords = rb_obj_hide(rb_ary_new());
2054
+ }
2055
+ rb_ary_push(args->unknown_keywords, key);
2056
+ }
1170
2057
 
1171
2058
  return ST_CONTINUE;
1172
2059
  }
1173
2060
 
1174
- static void parser_config_init(JSON_ParserConfig *config, VALUE opts)
2061
+ static void parser_config_init(JSON_ParserConfig *config, VALUE opts, VALUE self, bool strict)
1175
2062
  {
1176
2063
  config->max_nesting = 100;
1177
2064
 
1178
- if (!NIL_P(opts)) {
1179
- Check_Type(opts, T_HASH);
1180
- if (RHASH_SIZE(opts) > 0) {
1181
- // We assume in most cases few keys are set so it's faster to go over
1182
- // the provided keys than to check all possible keys.
1183
- rb_hash_foreach(opts, parser_config_init_i, (VALUE)config);
1184
- }
2065
+ struct parser_config_init_args args = {
2066
+ .config = config,
2067
+ .self = self,
2068
+ .strict = strict,
2069
+ };
2070
+
2071
+ if (NIL_P(opts)) return;
2072
+ Check_Type(opts, T_HASH);
2073
+ if (RHASH_SIZE(opts) == 0) return;
1185
2074
 
2075
+ // We assume in most cases few keys are set so it's faster to go over
2076
+ // the provided keys than to check all possible keys.
2077
+ rb_hash_foreach(opts, parser_config_init_i, (VALUE)&args);
2078
+
2079
+ if (RB_UNLIKELY(args.unknown_keywords)) {
2080
+ if (RARRAY_LEN(args.unknown_keywords) == 1) {
2081
+ rb_raise(rb_eArgError, "unknown keyword: %" PRIsVALUE, RARRAY_AREF(args.unknown_keywords, 0));
2082
+ }
2083
+ else {
2084
+ VALUE keywords = rb_ary_join(args.unknown_keywords, rb_utf8_str_new_cstr(", "));
2085
+ rb_raise(rb_eArgError, "unknown keywords: %" PRIsVALUE, keywords);
2086
+ }
1186
2087
  }
1187
2088
  }
1188
2089
 
@@ -1191,61 +2092,90 @@ static void parser_config_init(JSON_ParserConfig *config, VALUE opts)
1191
2092
  *
1192
2093
  * Creates a new JSON::Ext::ParserConfig instance.
1193
2094
  *
1194
- * It will be configured by the _opts_ hash. _opts_ can have the following
1195
- * keys:
2095
+ * Argument +opts+, if given, contains a \Hash of options for the parsing.
2096
+ * See {Parsing Options}[#module-JSON-label-Parsing+Options].
1196
2097
  *
1197
- * _opts_ can have the following keys:
1198
- * * *max_nesting*: The maximum depth of nesting allowed in the parsed data
1199
- * structures. Disable depth checking with :max_nesting => false|nil|0, it
1200
- * defaults to 100.
1201
- * * *allow_nan*: If set to true, allow NaN, Infinity and -Infinity in
1202
- * defiance of RFC 4627 to be parsed by the Parser. This option defaults to
1203
- * false.
1204
- * * *symbolize_names*: If set to true, returns symbols for the names
1205
- * (keys) in a JSON object. Otherwise strings are returned, which is
1206
- * also the default. It's not possible to use this option in
1207
- * conjunction with the *create_additions* option.
1208
- * * *decimal_class*: Specifies which class to use instead of the default
1209
- * (Float) when parsing decimal numbers. This class must accept a single
1210
- * string argument in its constructor.
1211
2098
  */
1212
2099
  static VALUE cParserConfig_initialize(VALUE self, VALUE opts)
1213
2100
  {
2101
+ rb_check_frozen(self);
1214
2102
  GET_PARSER_CONFIG;
1215
2103
 
1216
- parser_config_init(config, opts);
1217
-
1218
- RB_OBJ_WRITTEN(self, Qundef, config->decimal_class);
2104
+ parser_config_init(config, opts, self, false);
1219
2105
 
1220
2106
  return self;
1221
2107
  }
1222
2108
 
1223
- static VALUE cParser_parse(JSON_ParserConfig *config, VALUE Vsource)
2109
+ static VALUE cParser_parse(JSON_ParserConfig *config, VALUE src)
1224
2110
  {
1225
- Vsource = convert_encoding(StringValue(Vsource));
1226
- StringValue(Vsource);
2111
+ VALUE Vsource = convert_encoding(src);
2112
+
2113
+ // Ensure the string isn't mutated under us.
2114
+ // The classic API to use is `rb_str_locktmp`, but then we'd
2115
+ // need to use `rb_protect` to make sure we always unlock.
2116
+ if (Vsource == src) {
2117
+ Vsource = rb_str_new_frozen(Vsource);
2118
+ }
1227
2119
 
1228
2120
  VALUE rvalue_stack_buffer[RVALUE_STACK_INITIAL_CAPA];
1229
- rvalue_stack stack = {
2121
+ rvalue_stack value_stack = {
1230
2122
  .type = RVALUE_STACK_STACK_ALLOCATED,
1231
2123
  .ptr = rvalue_stack_buffer,
1232
2124
  .capa = RVALUE_STACK_INITIAL_CAPA,
1233
2125
  };
1234
2126
 
2127
+ // Seed the frame stack with the root frame, establishing the invariant that
2128
+ // json_parse_any always has a top frame to dispatch on (so the stack is never
2129
+ // empty mid-parse).
2130
+ json_frame frame_stack_buffer[JSON_FRAME_STACK_INITIAL_CAPA];
2131
+ frame_stack_buffer[0] = (json_frame){
2132
+ .type = JSON_FRAME_ROOT,
2133
+ .phase = JSON_PHASE_VALUE,
2134
+ };
2135
+ json_frame_stack frames = {
2136
+ .type = RVALUE_STACK_STACK_ALLOCATED,
2137
+ .ptr = frame_stack_buffer,
2138
+ .capa = JSON_FRAME_STACK_INITIAL_CAPA,
2139
+ .head = 1,
2140
+ };
2141
+
2142
+ long len;
2143
+ const char *start;
2144
+
2145
+ RSTRING_GETMEM(Vsource, start, len);
2146
+
2147
+ VALUE value_stack_handle = 0;
2148
+ VALUE frame_stack_handle = 0;
1235
2149
  JSON_ParserState _state = {
1236
- .cursor = RSTRING_PTR(Vsource),
1237
- .end = RSTRING_END(Vsource),
1238
- .stack = &stack,
2150
+ .start = start,
2151
+ .cursor = start,
2152
+ .end = start + len,
2153
+ .value_stack = &value_stack,
2154
+ .value_stack_handle = &value_stack_handle,
2155
+ .frames = &frames,
2156
+ .frame_stack_handle = &frame_stack_handle,
1239
2157
  };
1240
2158
  JSON_ParserState *state = &_state;
1241
2159
 
1242
- VALUE result = json_parse_any(state, config);
2160
+ bool complete = json_parse_any(state, config, false);
2161
+
2162
+ // The root document value is parsed; it is the lone survivor on
2163
+ // the rvalue stack.
2164
+ VALUE result = complete ? *rvalue_stack_peek(state->value_stack, 1) : Qundef;
1243
2165
 
1244
2166
  // This may be skipped in case of exception, but
1245
2167
  // it won't cause a leak.
1246
- rvalue_stack_eagerly_release(state->stack_handle);
1247
-
1248
- json_ensure_eof(state);
2168
+ rvalue_stack_eagerly_release(value_stack_handle);
2169
+ json_frame_stack_eagerly_release(frame_stack_handle);
2170
+ RB_GC_GUARD(value_stack_handle);
2171
+ RB_GC_GUARD(frame_stack_handle);
2172
+ RB_GC_GUARD(Vsource);
2173
+
2174
+ if (complete) {
2175
+ json_ensure_eof(state, config);
2176
+ } else {
2177
+ raise_eos_error("unexpected end of input", state);
2178
+ }
1249
2179
 
1250
2180
  return result;
1251
2181
  }
@@ -1265,12 +2195,9 @@ static VALUE cParserConfig_parse(VALUE self, VALUE Vsource)
1265
2195
 
1266
2196
  static VALUE cParser_m_parse(VALUE klass, VALUE Vsource, VALUE opts)
1267
2197
  {
1268
- Vsource = convert_encoding(StringValue(Vsource));
1269
- StringValue(Vsource);
1270
-
1271
2198
  JSON_ParserConfig _config = {0};
1272
2199
  JSON_ParserConfig *config = &_config;
1273
- parser_config_init(config, opts);
2200
+ parser_config_init(config, opts, Qfalse, false);
1274
2201
 
1275
2202
  return cParser_parse(config, Vsource);
1276
2203
  }
@@ -1278,30 +2205,35 @@ static VALUE cParser_m_parse(VALUE klass, VALUE Vsource, VALUE opts)
1278
2205
  static void JSON_ParserConfig_mark(void *ptr)
1279
2206
  {
1280
2207
  JSON_ParserConfig *config = ptr;
1281
- rb_gc_mark(config->on_load_proc);
1282
- rb_gc_mark(config->decimal_class);
2208
+ rb_gc_mark_movable(config->on_load_proc);
2209
+ rb_gc_mark_movable(config->decimal_class);
1283
2210
  }
1284
2211
 
1285
- static void JSON_ParserConfig_free(void *ptr)
2212
+ static size_t JSON_ParserConfig_memsize(const void *ptr)
1286
2213
  {
1287
- JSON_ParserConfig *config = ptr;
1288
- ruby_xfree(config);
2214
+ #ifdef HAVE_RUBY_TYPED_EMBEDDABLE
2215
+ return 0;
2216
+ #else
2217
+ return sizeof(JSON_ParserConfig);
2218
+ #endif
1289
2219
  }
1290
2220
 
1291
- static size_t JSON_ParserConfig_memsize(const void *ptr)
2221
+ static void JSON_ParserConfig_compact(void *ptr)
1292
2222
  {
1293
- return sizeof(JSON_ParserConfig);
2223
+ JSON_ParserConfig *config = ptr;
2224
+ config->on_load_proc = rb_gc_location(config->on_load_proc);
2225
+ config->decimal_class = rb_gc_location(config->decimal_class);
1294
2226
  }
1295
2227
 
1296
2228
  static const rb_data_type_t JSON_ParserConfig_type = {
1297
- "JSON::Ext::Parser/ParserConfig",
1298
- {
1299
- JSON_ParserConfig_mark,
1300
- JSON_ParserConfig_free,
1301
- JSON_ParserConfig_memsize,
2229
+ .wrap_struct_name = "JSON::Ext::Parser/ParserConfig",
2230
+ .function = {
2231
+ .dmark = JSON_ParserConfig_mark,
2232
+ .dfree = RUBY_DEFAULT_FREE,
2233
+ .dsize = JSON_ParserConfig_memsize,
2234
+ .dcompact = JSON_ParserConfig_compact,
1302
2235
  },
1303
- 0, 0,
1304
- RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED,
2236
+ .flags = RUBY_TYPED_THREAD_SAFE_FREE | RUBY_TYPED_WB_PROTECTED | RUBY_TYPED_FROZEN_SHAREABLE | RUBY_TYPED_EMBEDDABLE,
1305
2237
  };
1306
2238
 
1307
2239
  static VALUE cJSON_parser_s_allocate(VALUE klass)
@@ -1310,6 +2242,603 @@ static VALUE cJSON_parser_s_allocate(VALUE klass)
1310
2242
  return TypedData_Make_Struct(klass, JSON_ParserConfig, &JSON_ParserConfig_type, config);
1311
2243
  }
1312
2244
 
2245
+ static void json_str_clear(VALUE str)
2246
+ {
2247
+ if (RB_OBJ_FROZEN_RAW(str)) {
2248
+ return;
2249
+ }
2250
+ rb_str_replace(str, JSON_empty_string);
2251
+ }
2252
+
2253
+ typedef struct JSON_ResumableParserStruct {
2254
+ JSON_ParserConfig config;
2255
+ JSON_ParserState state;
2256
+ rvalue_stack value_stack;
2257
+ json_frame_stack frames;
2258
+ VALUE buffer;
2259
+ size_t parsed_bytes;
2260
+ size_t incomplete_bytes;
2261
+ bool complete;
2262
+ bool in_use;
2263
+ } JSON_ResumableParser;
2264
+
2265
+ static void JSON_ResumableParser_mark(void *ptr)
2266
+ {
2267
+ JSON_ResumableParser *parser = (JSON_ResumableParser *)ptr;
2268
+ JSON_ParserConfig_mark(&parser->config);
2269
+ rvalue_stack_mark(&parser->value_stack);
2270
+ rvalue_cache_mark(&parser->state.name_cache);
2271
+ rb_gc_mark(parser->buffer); // pin the buffer
2272
+ rb_gc_mark_movable(parser->state.parser);
2273
+ }
2274
+
2275
+ static void JSON_ResumableParser_free(void *ptr)
2276
+ {
2277
+ JSON_ResumableParser *parser = (JSON_ResumableParser *)ptr;
2278
+ rvalue_stack_free_buffer(&parser->value_stack);
2279
+ json_frame_stack_free_buffer(&parser->frames);
2280
+ }
2281
+
2282
+ static size_t JSON_ResumableParser_memsize(const void *ptr)
2283
+ {
2284
+ const JSON_ResumableParser *parser = (const JSON_ResumableParser *)ptr;
2285
+ size_t memsize = JSON_ParserConfig_memsize(&parser->config);
2286
+ memsize += rvalue_stack_memsize(&parser->value_stack);
2287
+ memsize += json_frame_stack_memsize(&parser->frames);
2288
+ #ifndef HAVE_RUBY_TYPED_EMBEDDABLE
2289
+ memsize += (
2290
+ sizeof(JSON_ResumableParser)
2291
+ - sizeof(JSON_ParserState)
2292
+ - sizeof(JSON_ParserConfig)
2293
+ - sizeof(rvalue_stack)
2294
+ - sizeof(json_frame_stack)
2295
+ );
2296
+ #endif
2297
+ return memsize;
2298
+ }
2299
+
2300
+ static void JSON_ResumableParser_compact(void *ptr)
2301
+ {
2302
+ JSON_ResumableParser *parser = (JSON_ResumableParser *)ptr;
2303
+ JSON_ParserConfig_compact(&parser->config);
2304
+ rvalue_stack_compact(&parser->value_stack);
2305
+ rvalue_cache_compact(&parser->state.name_cache);
2306
+ parser->buffer = rb_gc_location(parser->buffer);
2307
+ parser->state.parser = rb_gc_location(parser->state.parser);
2308
+ }
2309
+
2310
+ static const rb_data_type_t JSON_ResumableParser_type = {
2311
+ .wrap_struct_name = "JSON::Ext::ResumableParser",
2312
+ .function = {
2313
+ JSON_ResumableParser_mark,
2314
+ JSON_ResumableParser_free,
2315
+ JSON_ResumableParser_memsize,
2316
+ JSON_ResumableParser_compact,
2317
+ },
2318
+ // RUBY_TYPED_WB_PROTECTED is deliberately not declared because
2319
+ // this is a superset of JSON_Parser_rvalue_stack_type, so we'd need
2320
+ // to trigger a lot of write barriers.
2321
+ .flags = RUBY_TYPED_THREAD_SAFE_FREE | RUBY_TYPED_EMBEDDABLE,
2322
+ };
2323
+
2324
+ static VALUE cResumableParser_allocate(VALUE klass)
2325
+ {
2326
+ JSON_ResumableParser *parser;
2327
+ VALUE obj = TypedData_Make_Struct(klass, JSON_ResumableParser, &JSON_ResumableParser_type, parser);
2328
+ parser->state.in_array++;
2329
+ parser->state.parser = obj;
2330
+ return obj;
2331
+ }
2332
+
2333
+ static inline JSON_ResumableParser *cResumableParser_get(VALUE self)
2334
+ {
2335
+ JSON_ResumableParser *parser;
2336
+ TypedData_Get_Struct(self, JSON_ResumableParser, &JSON_ResumableParser_type, parser);
2337
+ return parser;
2338
+ }
2339
+
2340
+ /*
2341
+ * call-seq: new(opts => {})
2342
+ *
2343
+ * Creates a new JSON::ResumableParser instance.
2344
+ *
2345
+ * Argument +opts+, if given, contains a \Hash of options for the parsing.
2346
+ * See {Parsing Options}[#module-JSON-label-Parsing+Options].
2347
+ *
2348
+ * A ResumableParser is able to parse partial documents and resume parsing later
2349
+ * when more of the document is provided:
2350
+ *
2351
+ * parser = JSON::ResumableParser.new
2352
+ * parser << '{"user": "george", "role": "ad'
2353
+ * parser.parse # => false
2354
+ * parser.eos? # => true
2355
+ * parser.partial_value # => { "user" => "george", "role" => nil }
2356
+ * parser.rest # => '"ad'
2357
+ *
2358
+ * parser << 'min" }[1, 2, 3]'
2359
+ * parser.parse # => true
2360
+ * parser.value # => { "user" => "george", "role" => "admin" }
2361
+ *
2362
+ * parser.parse # => true
2363
+ * parser.value # => [1, 2, 3]
2364
+ *
2365
+ * === Limitations
2366
+ *
2367
+ * While ResumableParser is able to parse streams of documents without any
2368
+ * explicit separators between them, it is highly recommended to separate documents
2369
+ * by either spaces or newlines, as otherwise the \JSON syntax for numbers may be ambiguous.
2370
+ * When parsing a number, ResumableParser will not consider the number complete until something follows:
2371
+ *
2372
+ * parser << '123'
2373
+ * parser.parse # => false
2374
+ * parser << ' '
2375
+ * parser.parse # => true
2376
+ * parser.value # => 123
2377
+ *
2378
+ * === Security
2379
+ *
2380
+ * An incomplete document is buffered in full and there is no size limit, so when reading
2381
+ * from an untrusted source the caller is responsible for bounding how much data is fed.
2382
+ * For example:
2383
+ *
2384
+ * loop do
2385
+ * if parser.parsed_bytes > DOCUMENT_MAX_SIZE
2386
+ * raise "document too large"
2387
+ * end
2388
+ *
2389
+ * parser << read_chunk
2390
+ * while parser.parse
2391
+ * process(parser.value)
2392
+ * end
2393
+ * end
2394
+ */
2395
+ static VALUE cResumableParser_initialize(int argc, VALUE *argv, VALUE self)
2396
+ {
2397
+ rb_check_frozen(self);
2398
+
2399
+ VALUE opts = Qfalse;
2400
+ rb_scan_args_kw(RB_SCAN_ARGS_LAST_HASH_KEYWORDS, argc, argv, "0:", &opts);
2401
+ JSON_ResumableParser *parser = cResumableParser_get(self);
2402
+
2403
+ opts = argc > 0 ? argv[0] : Qnil;
2404
+ parser_config_init(&parser->config, opts, self, true);
2405
+
2406
+ return self;
2407
+ }
2408
+
2409
+ static JSON_ResumableParser *ResumableParser_acquire(VALUE self, bool lock);
2410
+
2411
+ /*
2412
+ * call-seq: self << string -> self
2413
+ *
2414
+ * Appends the given string to the parser's buffer.
2415
+ */
2416
+ static VALUE cResumableParser_feed(VALUE self, VALUE str)
2417
+ {
2418
+ rb_check_frozen(self);
2419
+
2420
+ JSON_ResumableParser *parser = ResumableParser_acquire(self, false);
2421
+
2422
+ str = convert_encoding(str);
2423
+ if (!RSTRING_LEN(str)) {
2424
+ return self;
2425
+ }
2426
+
2427
+ size_t offset = parser->state.cursor - parser->state.start;
2428
+ const size_t remaining = parser->state.end - parser->state.cursor;
2429
+
2430
+ if (!remaining) {
2431
+ if (parser->buffer) {
2432
+ json_str_clear(parser->buffer);
2433
+ }
2434
+ parser->buffer = RB_OBJ_FROZEN_RAW(str) ? str : rb_obj_hide(rb_str_new_shared(str));
2435
+ offset = 0;
2436
+ } else {
2437
+ JSON_ASSERT(parser->buffer);
2438
+
2439
+ const size_t size = parser->state.end - parser->state.start;
2440
+ const size_t consumed = size - remaining;
2441
+
2442
+ if (RB_OBJ_FROZEN_RAW(parser->buffer)) {
2443
+ VALUE new_buffer = rb_obj_hide(rb_str_buf_new(remaining + RSTRING_LEN(str)));
2444
+ rb_enc_associate_index(new_buffer, utf8_encindex);
2445
+
2446
+ char *old_ptr = RSTRING_PTR(parser->buffer);
2447
+ memcpy(RSTRING_PTR(new_buffer), old_ptr + consumed, remaining);
2448
+ rb_str_set_len(new_buffer, remaining);
2449
+ offset = 0;
2450
+ parser->buffer = new_buffer;
2451
+ } else if (consumed > (size / 2) && size >= 512) {
2452
+ rb_str_modify(parser->buffer);
2453
+ char *old_ptr = RSTRING_PTR(parser->buffer);
2454
+ memmove(old_ptr, old_ptr + consumed, remaining);
2455
+ rb_str_set_len(parser->buffer, remaining);
2456
+ offset = 0;
2457
+ }
2458
+ rb_str_append(parser->buffer, str);
2459
+ }
2460
+
2461
+ long len;
2462
+ const char *start;
2463
+ RSTRING_GETMEM(parser->buffer, start, len);
2464
+ parser->state.start = start;
2465
+ parser->state.end = start + len;
2466
+ parser->state.cursor = parser->state.start + offset;
2467
+
2468
+ return self;
2469
+ }
2470
+
2471
+ struct json_parse_any_args {
2472
+ JSON_ParserState *state;
2473
+ JSON_ParserConfig *config;
2474
+ VALUE parser;
2475
+ };
2476
+
2477
+ static VALUE json_parse_any_resumable_safe0(RB_BLOCK_CALL_FUNC_ARGLIST(yielded_arg, _args))
2478
+ {
2479
+ struct json_parse_any_args *args = (struct json_parse_any_args *)_args;
2480
+ return (VALUE)json_parse_any(args->state, args->config, true);
2481
+ }
2482
+
2483
+ static VALUE json_parse_any_resumable_safe(VALUE _args)
2484
+ {
2485
+ struct json_parse_any_args *args = (struct json_parse_any_args *)_args;
2486
+ VALUE result = rb_catch_obj(args->parser, json_parse_any_resumable_safe0, _args);
2487
+ return result == args->parser ? Qfalse : result;
2488
+ }
2489
+
2490
+ static JSON_ResumableParser *ResumableParser_acquire(VALUE self, bool lock)
2491
+ {
2492
+ JSON_ResumableParser *parser = cResumableParser_get(self);
2493
+
2494
+ if (parser->in_use) {
2495
+ rb_raise(rb_eArgError, "ResumableParser can't be used recursively");
2496
+ }
2497
+
2498
+ if (lock) {
2499
+ parser->in_use = true;
2500
+ }
2501
+
2502
+ // self may have moved, so we need to update all pointers
2503
+ // Investigate: We might be better off keeping JSON_ParserState on the stack
2504
+ // and only persist what we need.
2505
+ parser->state.value_stack = &parser->value_stack;
2506
+ parser->state.frames = &parser->frames;
2507
+
2508
+ return parser;
2509
+ }
2510
+
2511
+ /*
2512
+ * call-seq: parse -> true or false
2513
+ *
2514
+ * Attemps to parse a JSON document from the internal buffer.
2515
+ * Returns whether a complete document could be parsed.
2516
+ *
2517
+ * It does raise +JSON::ParserError+ when encountering invalid \JSON syntax.
2518
+ *
2519
+ * The parsed object can be retrieved by calling #value
2520
+ */
2521
+ static VALUE cResumableParser_parse(VALUE self)
2522
+ {
2523
+ JSON_ResumableParser *parser = ResumableParser_acquire(self, true);
2524
+
2525
+ if (parser->complete) {
2526
+ parser->parsed_bytes = 0;
2527
+ parser->incomplete_bytes = 0;
2528
+ parser->complete = false;
2529
+ }
2530
+
2531
+ if (!parser->buffer) {
2532
+ parser->in_use = false;
2533
+ return Qfalse;
2534
+ }
2535
+
2536
+ if (parser->frames.head == 0) {
2537
+ json_frame_stack_push(&parser->state, (json_frame){
2538
+ .type = JSON_FRAME_ROOT,
2539
+ .phase = JSON_PHASE_VALUE,
2540
+ });
2541
+ }
2542
+
2543
+ VALUE Vsource = parser->buffer; // Prevent compaction
2544
+
2545
+ json_frame *frame = json_frame_stack_peek(&parser->frames);
2546
+
2547
+ if (frame->phase == JSON_PHASE_DONE) {
2548
+ JSON_ASSERT(parser->value_stack.head == 1);
2549
+ JSON_ASSERT(parser->frames.head == 1);
2550
+
2551
+ frame->phase = JSON_PHASE_VALUE;
2552
+ rvalue_stack_pop(parser->state.value_stack, 1);
2553
+ }
2554
+
2555
+ struct json_parse_any_args args = {
2556
+ .state = &parser->state,
2557
+ .config = &parser->config,
2558
+ .parser = self,
2559
+ };
2560
+ int status;
2561
+ const char *initial_cursor = parser->state.cursor;
2562
+ parser->complete = rb_protect(json_parse_any_resumable_safe, (VALUE)&args, &status);
2563
+
2564
+ if (status) {
2565
+ parser->complete = true; // a parse error is considered complete
2566
+ }
2567
+
2568
+ parser->parsed_bytes += parser->state.cursor - initial_cursor;
2569
+ parser->incomplete_bytes = parser->complete ? 0 : parser->state.end - parser->state.cursor;
2570
+
2571
+ json_eat_whitespace(&parser->state, &parser->config, false);
2572
+ if (eos(&parser->state)) {
2573
+ json_str_clear(parser->buffer);
2574
+ parser->buffer = Qfalse;
2575
+ parser->state.start = parser->state.cursor = parser->state.end = 0;
2576
+ }
2577
+ parser->in_use = false;
2578
+
2579
+ if (status) {
2580
+ rb_jump_tag(status); // reraise
2581
+ }
2582
+ RB_GC_GUARD(Vsource);
2583
+ return parser->complete ? Qtrue : Qfalse;
2584
+ }
2585
+
2586
+ /*
2587
+ * call-seq: value? -> true or false
2588
+ *
2589
+ * Returns whether a parsed value is available.
2590
+ */
2591
+ static VALUE cResumableParser_value_p(VALUE self)
2592
+ {
2593
+ JSON_ResumableParser *parser = ResumableParser_acquire(self, false);
2594
+
2595
+ if (parser->value_stack.head > 0) {
2596
+ json_frame *frame = json_frame_stack_peek(&parser->frames);
2597
+ if (frame->phase == JSON_PHASE_DONE) {
2598
+ return Qtrue;
2599
+ }
2600
+ }
2601
+ return Qfalse;
2602
+ }
2603
+
2604
+ /*
2605
+ * call-seq: value -> object
2606
+ *
2607
+ * Returns and consume the last parsed value.
2608
+ * Raises ArgumentError if there is no parsed value or if it was already retrieved:
2609
+ * parser << '[1][2]'
2610
+ * parser.value # ArgumentError no ready value
2611
+ * parser.parse # => true
2612
+ * parser.value # => [1]
2613
+ * parser.value # ArgumentError no ready value
2614
+ */
2615
+ static VALUE cResumableParser_value(VALUE self)
2616
+ {
2617
+ JSON_ResumableParser *parser = ResumableParser_acquire(self, false);
2618
+
2619
+ if (parser->frames.head > 0) {
2620
+ json_frame *frame = json_frame_stack_peek(&parser->frames);
2621
+
2622
+ if (frame->phase == JSON_PHASE_DONE) {
2623
+ VALUE result = *rvalue_stack_peek(parser->state.value_stack, 1);
2624
+ rvalue_stack_pop(parser->state.value_stack, 1);
2625
+ json_frame_stack_pop(parser->state.frames);
2626
+ return result;
2627
+ }
2628
+ }
2629
+ rb_raise(rb_eArgError, "no ready value");
2630
+ }
2631
+
2632
+ /*
2633
+ * call-seq: clear -> self
2634
+ *
2635
+ * Entirely reset the parser state and buffer.
2636
+ */
2637
+ static VALUE cResumableParser_clear(VALUE self)
2638
+ {
2639
+ JSON_ResumableParser *parser = ResumableParser_acquire(self, false);
2640
+ parser->buffer = 0;
2641
+ parser->complete = true;
2642
+ parser->parsed_bytes = 0;
2643
+ parser->incomplete_bytes = 0;
2644
+ parser->frames.head = 0;
2645
+ parser->value_stack.head = 0;
2646
+ parser->state.name_cache.length = 0;
2647
+ parser->state.current_nesting = 0;
2648
+ parser->state.in_array = 1;
2649
+ parser->state.emitted_deprecations = 0;
2650
+ parser->state.start = parser->state.cursor = parser->state.end = NULL;
2651
+ return self;
2652
+ }
2653
+
2654
+ static VALUE cResumableParser_partial_value_body(VALUE self)
2655
+ {
2656
+ JSON_ResumableParser *original_parser = cResumableParser_get(self);
2657
+ JSON_ResumableParser parser = *original_parser;
2658
+
2659
+ parser.state.frames = &parser.frames;
2660
+ parser.state.value_stack = &parser.value_stack;
2661
+
2662
+ if (parser.value_stack.head == 0) {
2663
+ return Qnil;
2664
+ }
2665
+
2666
+ json_frame *frame = json_frame_stack_peek(parser.state.frames);
2667
+ long missing_object_value = 0;
2668
+ if (frame->type == JSON_FRAME_OBJECT && (frame->phase == JSON_PHASE_VALUE || frame->phase == JSON_PHASE_OBJECT_COLON)) {
2669
+ missing_object_value = 1;
2670
+ }
2671
+
2672
+ // Copy the value stack as we need to mutate it. The collapse loop folds each
2673
+ // open container by popping its entries and pushing the single result, so a
2674
+ // parent always reclaims its child's slot; head exceeds its live size by at
2675
+ // most one, either for the missing-value placeholder pushed below or for the
2676
+ // result of folding an empty innermost container. That one spare slot keeps
2677
+ // rvalue_stack_push from growing (reallocating) this ALLOCV buffer.
2678
+ long capa = parser.value_stack.head;
2679
+ parser.value_stack.capa = capa + 1;
2680
+ VALUE tmpbuf, *value_stack_buffer = ALLOCV_N(VALUE, tmpbuf, parser.value_stack.capa);
2681
+ MEMCPY(value_stack_buffer, parser.value_stack.ptr, VALUE, capa);
2682
+ parser.value_stack.ptr = value_stack_buffer;
2683
+
2684
+ JSON_ParserState *state = &parser.state;
2685
+ JSON_ParserConfig *config = &parser.config;
2686
+
2687
+ if (missing_object_value) {
2688
+ rvalue_stack_push(state->value_stack, Qnil, NULL, &state->value_stack);
2689
+ }
2690
+
2691
+ VALUE partial_result = Qundef;
2692
+
2693
+ while (UNDEF_P(partial_result)) {
2694
+ frame = json_frame_stack_peek(state->frames);
2695
+
2696
+ switch (frame->type) {
2697
+ case JSON_FRAME_ROOT: {
2698
+ partial_result = *rvalue_stack_peek(state->value_stack, 1);
2699
+ break;
2700
+ }
2701
+
2702
+ case JSON_FRAME_ARRAY: {
2703
+ long count = json_frame_entry_count(frame, state->value_stack);
2704
+ json_push_value(state, config, json_decode_array(state, config, count));
2705
+ json_frame_stack_pop(state->frames);
2706
+
2707
+ break;
2708
+ }
2709
+
2710
+ case JSON_FRAME_OBJECT: {
2711
+ long count = json_frame_entry_count(frame, state->value_stack);
2712
+ json_push_value(state, config, json_decode_object(state, config, count));
2713
+ json_frame_stack_pop(state->frames);
2714
+ break;
2715
+ }
2716
+
2717
+ default: {
2718
+ JSON_UNREACHABLE_RETURN(Qundef);
2719
+ break;
2720
+ }
2721
+ }
2722
+ }
2723
+
2724
+ ALLOCV_END(tmpbuf);
2725
+ return partial_result;
2726
+ }
2727
+
2728
+ /*
2729
+ * call-seq: partial_value -> object
2730
+ *
2731
+ * Returns the Ruby objects parsed up to this point:
2732
+ * parser << '[1, [2, 3,'
2733
+ * parser.parse # => false
2734
+ * parser.value # ArgumentError no ready value
2735
+ * parser.partial_value # => [1, [2, 3]]
2736
+ */
2737
+ static VALUE cResumableParser_partial_value(VALUE self)
2738
+ {
2739
+ JSON_ResumableParser *parser = ResumableParser_acquire(self, true);
2740
+
2741
+ int status;
2742
+ VALUE result = rb_protect(cResumableParser_partial_value_body, self, &status);
2743
+ parser->in_use = false;
2744
+ if (status) {
2745
+ rb_jump_tag(status);
2746
+ }
2747
+ return result;
2748
+ }
2749
+
2750
+ /*
2751
+ * call-seq: rest -> string
2752
+ *
2753
+ * Returns a string containing what remains to be parsed in the buffer
2754
+ * parser << '{ "message": "unterminated message'
2755
+ * parser.parse # => false
2756
+ * parser.rest # => '"unterminated message"'
2757
+ */
2758
+ static VALUE cResumableParser_rest(VALUE self)
2759
+ {
2760
+ JSON_ResumableParser *parser = cResumableParser_get(self);
2761
+
2762
+ if (!parser->buffer) {
2763
+ return rb_utf8_str_new("", 0);
2764
+ }
2765
+
2766
+ size_t offset = parser->state.cursor - parser->state.start;
2767
+ const char *ptr;
2768
+ long len;
2769
+ RSTRING_GETMEM(parser->buffer, ptr, len);
2770
+ return rb_utf8_str_new(ptr + offset, len - offset);
2771
+ }
2772
+
2773
+ /*
2774
+ * call-seq: eos? -> true or false
2775
+ *
2776
+ * Returns whether the internal buffer has been entirely consumed.
2777
+ */
2778
+ static VALUE cResumableParser_eos_p(VALUE self)
2779
+ {
2780
+ JSON_ResumableParser *parser = cResumableParser_get(self);
2781
+ return eos(&parser->state) ? Qtrue : Qfalse;
2782
+ }
2783
+
2784
+ /*
2785
+ * call-seq: partial_value? -> true or false
2786
+ *
2787
+ * Returns whether a document is currently under construction: an unclosed
2788
+ * container, a key awaiting its value, etc.
2789
+ *
2790
+ * It answers the same question as <tt>!partial_value.nil?</tt>, but as a
2791
+ * cheap predicate on the parser's internal state, without materializing the
2792
+ * partially parsed Ruby objects:
2793
+ * parser << '{"a":1,'
2794
+ * parser.parse # => false
2795
+ * parser.partial_value? # => true
2796
+ *
2797
+ * A fully parsed document whose value hasn't been retrieved yet is not under
2798
+ * construction: #value? returns true and #partial_value? returns false.
2799
+ */
2800
+ static VALUE cResumableParser_partial_value_p(VALUE self)
2801
+ {
2802
+ JSON_ResumableParser *parser = cResumableParser_get(self);
2803
+
2804
+ // Mirror of #value?: values on the stack while the document isn't DONE
2805
+ // belong to a partially built document. A container whose first key or
2806
+ // element hasn't been parsed yet has no frame nor value registered (the
2807
+ // tokenizer rewinds to the container start on EOS), so that state is
2808
+ // observable through the buffer (#eos?/#rest) instead, keeping this
2809
+ // predicate consistent with #partial_value returning nil.
2810
+ if (parser->value_stack.head > 0) {
2811
+ json_frame *frame = json_frame_stack_peek(&parser->frames);
2812
+ if (frame->phase != JSON_PHASE_DONE) {
2813
+ return Qtrue;
2814
+ }
2815
+ }
2816
+ return Qfalse;
2817
+ }
2818
+
2819
+ /*
2820
+ * call-seq: parsed_bytes -> integer
2821
+ *
2822
+ * Returns the number of bytes parsed since the start of the current partial value.
2823
+ * This is intended to be used for securing against untrusted input:
2824
+ *
2825
+ * loop do
2826
+ * if parser.parsed_bytes > DOCUMENT_MAX_SIZE
2827
+ * raise "document too large"
2828
+ * end
2829
+ *
2830
+ * parser << read_chunk
2831
+ * while parser.parse
2832
+ * process(parser.value)
2833
+ * end
2834
+ * end
2835
+ */
2836
+ static VALUE cResumableParser_parsed_bytes(VALUE self)
2837
+ {
2838
+ JSON_ResumableParser *parser = cResumableParser_get(self);
2839
+ return ULL2NUM(parser->parsed_bytes + parser->incomplete_bytes);
2840
+ }
2841
+
1313
2842
  void Init_parser(void)
1314
2843
  {
1315
2844
  #ifdef HAVE_RB_EXT_RACTOR_SAFE
@@ -1321,45 +2850,75 @@ void Init_parser(void)
1321
2850
  mJSON = rb_define_module("JSON");
1322
2851
  VALUE mExt = rb_define_module_under(mJSON, "Ext");
1323
2852
  VALUE cParserConfig = rb_define_class_under(mExt, "ParserConfig", rb_cObject);
2853
+
2854
+ rb_global_variable(&eParserError);
2855
+ eParserError = rb_path2class("JSON::ParserError");
2856
+
2857
+ rb_global_variable(&eNestingError);
1324
2858
  eNestingError = rb_path2class("JSON::NestingError");
1325
- rb_gc_register_mark_object(eNestingError);
2859
+
1326
2860
  rb_define_alloc_func(cParserConfig, cJSON_parser_s_allocate);
1327
- rb_define_method(cParserConfig, "initialize", cParserConfig_initialize, 1);
2861
+ rb_define_private_method(cParserConfig, "initialize", cParserConfig_initialize, 1);
1328
2862
  rb_define_method(cParserConfig, "parse", cParserConfig_parse, 1);
1329
2863
 
1330
2864
  VALUE cParser = rb_define_class_under(mExt, "Parser", rb_cObject);
1331
2865
  rb_define_singleton_method(cParser, "parse", cParser_m_parse, 2);
1332
2866
 
2867
+ VALUE cResumableParser = rb_define_class_under(mJSON, "ResumableParser", rb_cObject);
2868
+ rb_define_alloc_func(cResumableParser, cResumableParser_allocate);
2869
+ rb_define_private_method(cResumableParser, "initialize", cResumableParser_initialize, -1);
2870
+ rb_define_method(cResumableParser, "<<", cResumableParser_feed, 1);
2871
+ rb_define_method(cResumableParser, "parse", cResumableParser_parse, 0);
2872
+ rb_define_method(cResumableParser, "value", cResumableParser_value, 0);
2873
+ rb_define_method(cResumableParser, "value?", cResumableParser_value_p, 0);
2874
+ rb_define_method(cResumableParser, "partial_value", cResumableParser_partial_value, 0);
2875
+ rb_define_method(cResumableParser, "partial_value?", cResumableParser_partial_value_p, 0);
2876
+ rb_define_method(cResumableParser, "clear", cResumableParser_clear, 0);
2877
+ rb_define_method(cResumableParser, "rest", cResumableParser_rest, 0);
2878
+ rb_define_method(cResumableParser, "eos?", cResumableParser_eos_p, 0);
2879
+ rb_define_method(cResumableParser, "parsed_bytes", cResumableParser_parsed_bytes, 0);
2880
+
2881
+ rb_global_variable(&CNaN);
1333
2882
  CNaN = rb_const_get(mJSON, rb_intern("NaN"));
1334
- rb_gc_register_mark_object(CNaN);
1335
2883
 
2884
+ rb_global_variable(&CInfinity);
1336
2885
  CInfinity = rb_const_get(mJSON, rb_intern("Infinity"));
1337
- rb_gc_register_mark_object(CInfinity);
1338
2886
 
2887
+ rb_global_variable(&CMinusInfinity);
1339
2888
  CMinusInfinity = rb_const_get(mJSON, rb_intern("MinusInfinity"));
1340
- rb_gc_register_mark_object(CMinusInfinity);
1341
2889
 
1342
2890
  rb_global_variable(&Encoding_UTF_8);
1343
2891
  Encoding_UTF_8 = rb_const_get(rb_path2class("Encoding"), rb_intern("UTF_8"));
1344
2892
 
2893
+ rb_global_variable(&JSON_empty_string);
2894
+ JSON_empty_string = rb_obj_hide(rb_utf8_str_new("", 0));
2895
+
1345
2896
  sym_max_nesting = ID2SYM(rb_intern("max_nesting"));
1346
2897
  sym_allow_nan = ID2SYM(rb_intern("allow_nan"));
1347
2898
  sym_allow_trailing_comma = ID2SYM(rb_intern("allow_trailing_comma"));
2899
+ sym_allow_comments = ID2SYM(rb_intern("allow_comments"));
2900
+ sym_allow_control_characters = ID2SYM(rb_intern("allow_control_characters"));
2901
+ sym_allow_invalid_escape = ID2SYM(rb_intern("allow_invalid_escape"));
1348
2902
  sym_symbolize_names = ID2SYM(rb_intern("symbolize_names"));
1349
2903
  sym_freeze = ID2SYM(rb_intern("freeze"));
1350
2904
  sym_on_load = ID2SYM(rb_intern("on_load"));
1351
2905
  sym_decimal_class = ID2SYM(rb_intern("decimal_class"));
2906
+ sym_allow_duplicate_key = ID2SYM(rb_intern("allow_duplicate_key"));
1352
2907
 
1353
- i_chr = rb_intern("chr");
1354
- i_aset = rb_intern("[]=");
1355
- i_aref = rb_intern("[]");
1356
- i_leftshift = rb_intern("<<");
1357
2908
  i_new = rb_intern("new");
1358
2909
  i_try_convert = rb_intern("try_convert");
2910
+ #ifndef HAVE_RB_STR_TO_INTERNED_STR
1359
2911
  i_uminus = rb_intern("-@");
2912
+ #endif
1360
2913
  i_encode = rb_intern("encode");
2914
+ i_at_line = rb_intern("@line");
2915
+ i_at_column = rb_intern("@column");
1361
2916
 
1362
2917
  binary_encindex = rb_ascii8bit_encindex();
1363
2918
  utf8_encindex = rb_utf8_encindex();
1364
2919
  enc_utf8 = rb_utf8_encoding();
2920
+
2921
+ #ifdef HAVE_SIMD
2922
+ simd_impl = find_simd_implementation();
2923
+ #endif
1365
2924
  }