Debian Codegraph @

cpython27/Modules/_json.c

raw symbols SCIP
1 #include "Python.h"
2 #include "structmember.h"
3 #if PY_VERSION_HEX < 0x02060000 && !defined(Py_TYPE)
4 #define Py_TYPE(ob) (((PyObject*)(ob))->ob_type)
5 #endif
6 #if PY_VERSION_HEX < 0x02050000 && !defined(PY_SSIZE_T_MIN)
7 typedef int Py_ssize_t;
8 #define PY_SSIZE_T_MAX INT_MAX
9 #define PY_SSIZE_T_MIN INT_MIN
10 #define PyInt_FromSsize_t PyInt_FromLong
11 #define PyInt_AsSsize_t PyInt_AsLong
12 #endif
13 #ifndef Py_IS_FINITE
14 #define Py_IS_FINITE(X) (!Py_IS_INFINITY(X) && !Py_IS_NAN(X))
15 #endif
16
17 #ifdef __GNUC__
18 #define UNUSED __attribute__((__unused__))
19 #else
20 #define UNUSED
21 #endif
22
23 #define DEFAULT_ENCODING "utf-8"
24
25 #define PyScanner_Check(op) PyObject_TypeCheck(op, &PyScannerType)
26 #define PyScanner_CheckExact(op) (Py_TYPE(op) == &PyScannerType)
27 #define PyEncoder_Check(op) PyObject_TypeCheck(op, &PyEncoderType)
28 #define PyEncoder_CheckExact(op) (Py_TYPE(op) == &PyEncoderType)
29
30 static PyTypeObject PyScannerType;
31 static PyTypeObject PyEncoderType;
32
33 typedef struct _PyScannerObject {
34 PyObject_HEAD
35 PyObject *encoding;
36 PyObject *strict;
37 PyObject *object_hook;
38 PyObject *pairs_hook;
39 PyObject *parse_float;
40 PyObject *parse_int;
41 PyObject *parse_constant;
42 } PyScannerObject;
43
44 static PyMemberDef scanner_members[] = {
45 {"encoding", T_OBJECT, offsetof(PyScannerObject, encoding), READONLY, "encoding"},
46 {"strict", T_OBJECT, offsetof(PyScannerObject, strict), READONLY, "strict"},
47 {"object_hook", T_OBJECT, offsetof(PyScannerObject, object_hook), READONLY, "object_hook"},
48 {"object_pairs_hook", T_OBJECT, offsetof(PyScannerObject, pairs_hook), READONLY, "object_pairs_hook"},
49 {"parse_float", T_OBJECT, offsetof(PyScannerObject, parse_float), READONLY, "parse_float"},
50 {"parse_int", T_OBJECT, offsetof(PyScannerObject, parse_int), READONLY, "parse_int"},
51 {"parse_constant", T_OBJECT, offsetof(PyScannerObject, parse_constant), READONLY, "parse_constant"},
52 {NULL}
53 };
54
55 typedef struct _PyEncoderObject {
56 PyObject_HEAD
57 PyObject *markers;
58 PyObject *defaultfn;
59 PyObject *encoder;
60 PyObject *indent;
61 PyObject *key_separator;
62 PyObject *item_separator;
63 PyObject *sort_keys;
64 PyObject *skipkeys;
65 int fast_encode;
66 int allow_nan;
67 } PyEncoderObject;
68
69 static PyMemberDef encoder_members[] = {
70 {"markers", T_OBJECT, offsetof(PyEncoderObject, markers), READONLY, "markers"},
71 {"default", T_OBJECT, offsetof(PyEncoderObject, defaultfn), READONLY, "default"},
72 {"encoder", T_OBJECT, offsetof(PyEncoderObject, encoder), READONLY, "encoder"},
73 {"indent", T_OBJECT, offsetof(PyEncoderObject, indent), READONLY, "indent"},
74 {"key_separator", T_OBJECT, offsetof(PyEncoderObject, key_separator), READONLY, "key_separator"},
75 {"item_separator", T_OBJECT, offsetof(PyEncoderObject, item_separator), READONLY, "item_separator"},
76 {"sort_keys", T_OBJECT, offsetof(PyEncoderObject, sort_keys), READONLY, "sort_keys"},
77 {"skipkeys", T_OBJECT, offsetof(PyEncoderObject, skipkeys), READONLY, "skipkeys"},
78 {NULL}
79 };
80
81 static Py_ssize_t
82 ascii_escape_char(Py_UNICODE c, char *output, Py_ssize_t chars);
83 static PyObject *
84 ascii_escape_unicode(PyObject *pystr);
85 static PyObject *
86 ascii_escape_str(PyObject *pystr);
87 static PyObject *
88 py_encode_basestring_ascii(PyObject* self UNUSED, PyObject *pystr);
89 void init_json(void);
90 static PyObject *
91 scan_once_str(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr);
92 static PyObject *
93 scan_once_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr);
94 static PyObject *
95 _build_rval_index_tuple(PyObject *rval, Py_ssize_t idx);
96 static PyObject *
97 scanner_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
98 static void
99 scanner_dealloc(PyObject *self);
100 static int
101 scanner_clear(PyObject *self);
102 static PyObject *
103 encoder_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
104 static void
105 encoder_dealloc(PyObject *self);
106 static int
107 encoder_clear(PyObject *self);
108 static int
109 encoder_listencode_list(PyEncoderObject *s, PyObject *rval, PyObject *seq, Py_ssize_t indent_level);
110 static int
111 encoder_listencode_obj(PyEncoderObject *s, PyObject *rval, PyObject *obj, Py_ssize_t indent_level);
112 static int
113 encoder_listencode_dict(PyEncoderObject *s, PyObject *rval, PyObject *dct, Py_ssize_t indent_level);
114 static PyObject *
115 _encoded_const(PyObject *obj);
116 static void
117 raise_errmsg(char *msg, PyObject *s, Py_ssize_t end);
118 static PyObject *
119 encoder_encode_string(PyEncoderObject *s, PyObject *obj);
120 static int
121 _convertPyInt_AsSsize_t(PyObject *o, Py_ssize_t *size_ptr);
122 static PyObject *
123 _convertPyInt_FromSsize_t(Py_ssize_t *size_ptr);
124 static PyObject *
125 encoder_encode_float(PyEncoderObject *s, PyObject *obj);
126
127 #define S_CHAR(c) (c >= ' ' && c <= '~' && c != '\\' && c != '"')
128 #define IS_WHITESPACE(c) (((c) == ' ') || ((c) == '\t') || ((c) == '\n') || ((c) == '\r'))
129
130 #define MIN_EXPANSION 6
131 #ifdef Py_UNICODE_WIDE
132 #define MAX_EXPANSION (2 * MIN_EXPANSION)
133 #else
134 #define MAX_EXPANSION MIN_EXPANSION
135 #endif
136
137 static int
138 _convertPyInt_AsSsize_t(PyObject *o, Py_ssize_t *size_ptr)
139 {
140 /* PyObject to Py_ssize_t converter */
141 *size_ptr = PyInt_AsSsize_t(o);
142 if (*size_ptr == -1 && PyErr_Occurred())
143 return 0;
144 return 1;
145 }
146
147 static PyObject *
148 _convertPyInt_FromSsize_t(Py_ssize_t *size_ptr)
149 {
150 /* Py_ssize_t to PyObject converter */
151 return PyInt_FromSsize_t(*size_ptr);
152 }
153
154 static Py_ssize_t
155 ascii_escape_char(Py_UNICODE c, char *output, Py_ssize_t chars)
156 {
157 /* Escape unicode code point c to ASCII escape sequences
158 in char *output. output must have at least 12 bytes unused to
159 accommodate an escaped surrogate pair "\uXXXX\uXXXX" */
160 output[chars++] = '\\';
161 switch (c) {
162 case '\\': output[chars++] = (char)c; break;
163 case '"': output[chars++] = (char)c; break;
164 case '\b': output[chars++] = 'b'; break;
165 case '\f': output[chars++] = 'f'; break;
166 case '\n': output[chars++] = 'n'; break;
167 case '\r': output[chars++] = 'r'; break;
168 case '\t': output[chars++] = 't'; break;
169 default:
170 #ifdef Py_UNICODE_WIDE
171 if (c >= 0x10000) {
172 /* UTF-16 surrogate pair */
173 Py_UNICODE v = c - 0x10000;
174 c = 0xd800 | ((v >> 10) & 0x3ff);
175 output[chars++] = 'u';
176 output[chars++] = "0123456789abcdef"[(c >> 12) & 0xf];
177 output[chars++] = "0123456789abcdef"[(c >> 8) & 0xf];
178 output[chars++] = "0123456789abcdef"[(c >> 4) & 0xf];
179 output[chars++] = "0123456789abcdef"[(c ) & 0xf];
180 c = 0xdc00 | (v & 0x3ff);
181 output[chars++] = '\\';
182 }
183 #endif
184 output[chars++] = 'u';
185 output[chars++] = "0123456789abcdef"[(c >> 12) & 0xf];
186 output[chars++] = "0123456789abcdef"[(c >> 8) & 0xf];
187 output[chars++] = "0123456789abcdef"[(c >> 4) & 0xf];
188 output[chars++] = "0123456789abcdef"[(c ) & 0xf];
189 }
190 return chars;
191 }
192
193 static PyObject *
194 ascii_escape_unicode(PyObject *pystr)
195 {
196 /* Take a PyUnicode pystr and return a new ASCII-only escaped PyString */
197 Py_ssize_t i;
198 Py_ssize_t input_chars;
199 Py_ssize_t output_size;
200 Py_ssize_t max_output_size;
201 Py_ssize_t chars;
202 Py_ssize_t incr;
203 PyObject *rval;
204 char *output;
205 Py_UNICODE *input_unicode;
206
207 input_chars = PyUnicode_GET_SIZE(pystr);
208 input_unicode = PyUnicode_AS_UNICODE(pystr);
209
210 output_size = input_chars;
211 incr = 2; /* for quotes */
212 /* One char input can be up to 6 chars output, estimate 4 of these */
213 incr += MIN_EXPANSION * 4;
214 if (PY_SSIZE_T_MAX - incr < output_size) {
215 PyErr_NoMemory();
216 return NULL;
217 }
218 output_size += incr;
219 if (PY_SSIZE_T_MAX / MAX_EXPANSION < input_chars ||
220 PY_SSIZE_T_MAX - 2 < input_chars * MAX_EXPANSION)
221 max_output_size = PY_SSIZE_T_MAX;
222 else
223 max_output_size = 2 + (input_chars * MAX_EXPANSION);
224 rval = PyString_FromStringAndSize(NULL, output_size);
225 if (rval == NULL) {
226 return NULL;
227 }
228 output = PyString_AS_STRING(rval);
229 chars = 0;
230 output[chars++] = '"';
231 for (i = 0; i < input_chars; i++) {
232 Py_UNICODE c = input_unicode[i];
233 if (S_CHAR(c)) {
234 output[chars++] = (char)c;
235 }
236 else {
237 chars = ascii_escape_char(c, output, chars);
238 }
239 if (output_size - chars < (1 + MAX_EXPANSION)) {
240 if (output_size == PY_SSIZE_T_MAX) {
241 Py_DECREF(rval);
242 PyErr_NoMemory();
243 return NULL;
244 }
245 /* There's more than four, so let's resize by a lot */
246 if (PY_SSIZE_T_MAX / 2 >= output_size && output_size * 2 < max_output_size)
247 output_size *= 2;
248 else
249 output_size = max_output_size;
250 if (_PyString_Resize(&rval, output_size) == -1) {
251 return NULL;
252 }
253 output = PyString_AS_STRING(rval);
254 }
255 }
256 output[chars++] = '"';
257 if (_PyString_Resize(&rval, chars) == -1) {
258 return NULL;
259 }
260 return rval;
261 }
262
263 static PyObject *
264 ascii_escape_str(PyObject *pystr)
265 {
266 /* Take a PyString pystr and return a new ASCII-only escaped PyString */
267 Py_ssize_t i;
268 Py_ssize_t input_chars;
269 Py_ssize_t output_size;
270 Py_ssize_t max_output_size;
271 Py_ssize_t chars;
272 Py_ssize_t incr;
273 PyObject *rval;
274 char *output;
275 char *input_str;
276
277 input_chars = PyString_GET_SIZE(pystr);
278 input_str = PyString_AS_STRING(pystr);
279
280 /* Fast path for a string that's already ASCII */
281 for (i = 0; i < input_chars; i++) {
282 Py_UNICODE c = (Py_UNICODE)(unsigned char)input_str[i];
283 if (!S_CHAR(c)) {
284 /* If we have to escape something, scan the string for unicode */
285 Py_ssize_t j;
286 for (j = i; j < input_chars; j++) {
287 c = (Py_UNICODE)(unsigned char)input_str[j];
288 if (c > 0x7f) {
289 /* We hit a non-ASCII character, bail to unicode mode */
290 PyObject *uni;
291 uni = PyUnicode_DecodeUTF8(input_str, input_chars, "strict");
292 if (uni == NULL) {
293 return NULL;
294 }
295 rval = ascii_escape_unicode(uni);
296 Py_DECREF(uni);
297 return rval;
298 }
299 }
300 break;
301 }
302 }
303
304 output_size = input_chars;
305 incr = 2; /* for quotes */
306 if (i != input_chars) {
307 /* One char input can be up to 6 chars output, estimate 4 of these */
308 incr += MIN_EXPANSION * 4;
309 }
310 if (PY_SSIZE_T_MAX - incr < output_size) {
311 PyErr_NoMemory();
312 return NULL;
313 }
314 output_size += incr;
315 if (PY_SSIZE_T_MAX / MIN_EXPANSION < input_chars ||
316 PY_SSIZE_T_MAX - 2 < input_chars * MIN_EXPANSION)
317 max_output_size = PY_SSIZE_T_MAX;
318 else
319 max_output_size = 2 + (input_chars * MIN_EXPANSION);
320 rval = PyString_FromStringAndSize(NULL, output_size);
321 if (rval == NULL) {
322 return NULL;
323 }
324 output = PyString_AS_STRING(rval);
325 output[0] = '"';
326
327 /* We know that everything up to i is ASCII already */
328 chars = i + 1;
329 memcpy(&output[1], input_str, i);
330
331 for (; i < input_chars; i++) {
332 Py_UNICODE c = (Py_UNICODE)(unsigned char)input_str[i];
333 if (S_CHAR(c)) {
334 output[chars++] = (char)c;
335 }
336 else {
337 chars = ascii_escape_char(c, output, chars);
338 }
339 /* An ASCII char can't possibly expand to a surrogate! */
340 if (output_size - chars < (1 + MIN_EXPANSION)) {
341 if (output_size == PY_SSIZE_T_MAX) {
342 Py_DECREF(rval);
343 PyErr_NoMemory();
344 return NULL;
345 }
346 /* There's more than four, so let's resize by a lot */
347 if (PY_SSIZE_T_MAX / 2 >= output_size && output_size * 2 < max_output_size)
348 output_size *= 2;
349 else
350 output_size = max_output_size;
351 if (_PyString_Resize(&rval, output_size) == -1) {
352 return NULL;
353 }
354 output = PyString_AS_STRING(rval);
355 }
356 }
357 output[chars++] = '"';
358 if (_PyString_Resize(&rval, chars) == -1) {
359 return NULL;
360 }
361 return rval;
362 }
363
364 static void
365 raise_errmsg(char *msg, PyObject *s, Py_ssize_t end)
366 {
367 /* Use the Python function json.decoder.errmsg to raise a nice
368 looking ValueError exception */
369 static PyObject *errmsg_fn = NULL;
370 PyObject *pymsg;
371 if (errmsg_fn == NULL) {
372 PyObject *decoder = PyImport_ImportModule("json.decoder");
373 if (decoder == NULL)
374 return;
375 errmsg_fn = PyObject_GetAttrString(decoder, "errmsg");
376 Py_DECREF(decoder);
377 if (errmsg_fn == NULL)
378 return;
379 }
380 pymsg = PyObject_CallFunction(errmsg_fn, "(zOO&)", msg, s, _convertPyInt_FromSsize_t, &end);
381 if (pymsg) {
382 PyErr_SetObject(PyExc_ValueError, pymsg);
383 Py_DECREF(pymsg);
384 }
385 }
386
387 static PyObject *
388 join_list_unicode(PyObject *lst)
389 {
390 /* return u''.join(lst) */
391 static PyObject *joinfn = NULL;
392 if (joinfn == NULL) {
393 PyObject *ustr = PyUnicode_FromUnicode(NULL, 0);
394 if (ustr == NULL)
395 return NULL;
396
397 joinfn = PyObject_GetAttrString(ustr, "join");
398 Py_DECREF(ustr);
399 if (joinfn == NULL)
400 return NULL;
401 }
402 return PyObject_CallFunctionObjArgs(joinfn, lst, NULL);
403 }
404
405 static PyObject *
406 _build_rval_index_tuple(PyObject *rval, Py_ssize_t idx) {
407 /* return (rval, idx) tuple, stealing reference to rval */
408 PyObject *tpl;
409 PyObject *pyidx;
410 /*
411 steal a reference to rval, returns (rval, idx)
412 */
413 if (rval == NULL) {
414 return NULL;
415 }
416 pyidx = PyInt_FromSsize_t(idx);
417 if (pyidx == NULL) {
418 Py_DECREF(rval);
419 return NULL;
420 }
421 tpl = PyTuple_New(2);
422 if (tpl == NULL) {
423 Py_DECREF(pyidx);
424 Py_DECREF(rval);
425 return NULL;
426 }
427 PyTuple_SET_ITEM(tpl, 0, rval);
428 PyTuple_SET_ITEM(tpl, 1, pyidx);
429 return tpl;
430 }
431
432 static PyObject *
433 scanstring_str(PyObject *pystr, Py_ssize_t end, char *encoding, int strict, Py_ssize_t *next_end_ptr)
434 {
435 /* Read the JSON string from PyString pystr.
436 end is the index of the first character after the quote.
437 encoding is the encoding of pystr (must be an ASCII superset)
438 if strict is zero then literal control characters are allowed
439 *next_end_ptr is a return-by-reference index of the character
440 after the end quote
441
442 Return value is a new PyString (if ASCII-only) or PyUnicode
443 */
444 PyObject *rval;
445 Py_ssize_t len = PyString_GET_SIZE(pystr);
446 Py_ssize_t begin = end - 1;
447 Py_ssize_t next;
448 char *buf = PyString_AS_STRING(pystr);
449 PyObject *chunks = PyList_New(0);
450 if (chunks == NULL) {
451 goto bail;
452 }
453 if (end < 0 || len <= end) {
454 PyErr_SetString(PyExc_ValueError, "end is out of bounds");
455 goto bail;
456 }
457 while (1) {
458 /* Find the end of the string or the next escape */
459 Py_UNICODE c = 0;
460 PyObject *chunk = NULL;
461 for (next = end; next < len; next++) {
462 c = (unsigned char)buf[next];
463 if (c == '"' || c == '\\') {
464 break;
465 }
466 else if (strict && c <= 0x1f) {
467 raise_errmsg("Invalid control character at", pystr, next);
468 goto bail;
469 }
470 }
471 if (!(c == '"' || c == '\\')) {
472 raise_errmsg("Unterminated string starting at", pystr, begin);
473 goto bail;
474 }
475 /* Pick up this chunk if it's not zero length */
476 if (next != end) {
477 PyObject *strchunk = PyString_FromStringAndSize(&buf[end], next - end);
478 if (strchunk == NULL) {
479 goto bail;
480 }
481 chunk = PyUnicode_FromEncodedObject(strchunk, encoding, NULL);
482 Py_DECREF(strchunk);
483 if (chunk == NULL) {
484 goto bail;
485 }
486 if (PyList_Append(chunks, chunk)) {
487 Py_DECREF(chunk);
488 goto bail;
489 }
490 Py_DECREF(chunk);
491 }
492 next++;
493 if (c == '"') {
494 end = next;
495 break;
496 }
497 if (next == len) {
498 raise_errmsg("Unterminated string starting at", pystr, begin);
499 goto bail;
500 }
501 c = buf[next];
502 if (c != 'u') {
503 /* Non-unicode backslash escapes */
504 end = next + 1;
505 switch (c) {
506 case '"': break;
507 case '\\': break;
508 case '/': break;
509 case 'b': c = '\b'; break;
510 case 'f': c = '\f'; break;
511 case 'n': c = '\n'; break;
512 case 'r': c = '\r'; break;
513 case 't': c = '\t'; break;
514 default: c = 0;
515 }
516 if (c == 0) {
517 raise_errmsg("Invalid \\escape", pystr, end - 2);
518 goto bail;
519 }
520 }
521 else {
522 c = 0;
523 next++;
524 end = next + 4;
525 if (end >= len) {
526 raise_errmsg("Invalid \\uXXXX escape", pystr, next - 1);
527 goto bail;
528 }
529 /* Decode 4 hex digits */
530 for (; next < end; next++) {
531 Py_UNICODE digit = buf[next];
532 c <<= 4;
533 switch (digit) {
534 case '0': case '1': case '2': case '3': case '4':
535 case '5': case '6': case '7': case '8': case '9':
536 c |= (digit - '0'); break;
537 case 'a': case 'b': case 'c': case 'd': case 'e':
538 case 'f':
539 c |= (digit - 'a' + 10); break;
540 case 'A': case 'B': case 'C': case 'D': case 'E':
541 case 'F':
542 c |= (digit - 'A' + 10); break;
543 default:
544 raise_errmsg("Invalid \\uXXXX escape", pystr, end - 5);
545 goto bail;
546 }
547 }
548 #ifdef Py_UNICODE_WIDE
549 /* Surrogate pair */
550 if ((c & 0xfc00) == 0xd800 && end + 6 < len &&
551 buf[next++] == '\\' &&
552 buf[next++] == 'u') {
553 Py_UNICODE c2 = 0;
554 end += 6;
555 /* Decode 4 hex digits */
556 for (; next < end; next++) {
557 Py_UNICODE digit = buf[next];
558 c2 <<= 4;
559 switch (digit) {
560 case '0': case '1': case '2': case '3': case '4':
561 case '5': case '6': case '7': case '8': case '9':
562 c2 |= (digit - '0'); break;
563 case 'a': case 'b': case 'c': case 'd': case 'e':
564 case 'f':
565 c2 |= (digit - 'a' + 10); break;
566 case 'A': case 'B': case 'C': case 'D': case 'E':
567 case 'F':
568 c2 |= (digit - 'A' + 10); break;
569 default:
570 raise_errmsg("Invalid \\uXXXX escape", pystr, end - 5);
571 goto bail;
572 }
573 }
574 if ((c2 & 0xfc00) == 0xdc00)
575 c = 0x10000 + (((c - 0xd800) << 10) | (c2 - 0xdc00));
576 else
577 end -= 6;
578 }
579 #endif
580 }
581 chunk = PyUnicode_FromUnicode(&c, 1);
582 if (chunk == NULL) {
583 goto bail;
584 }
585 if (PyList_Append(chunks, chunk)) {
586 Py_DECREF(chunk);
587 goto bail;
588 }
589 Py_DECREF(chunk);
590 }
591
592 rval = join_list_unicode(chunks);
593 if (rval == NULL) {
594 goto bail;
595 }
596 Py_CLEAR(chunks);
597 *next_end_ptr = end;
598 return rval;
599 bail:
600 *next_end_ptr = -1;
601 Py_XDECREF(chunks);
602 return NULL;
603 }
604
605
606 static PyObject *
607 scanstring_unicode(PyObject *pystr, Py_ssize_t end, int strict, Py_ssize_t *next_end_ptr)
608 {
609 /* Read the JSON string from PyUnicode pystr.
610 end is the index of the first character after the quote.
611 if strict is zero then literal control characters are allowed
612 *next_end_ptr is a return-by-reference index of the character
613 after the end quote
614
615 Return value is a new PyUnicode
616 */
617 PyObject *rval;
618 Py_ssize_t len = PyUnicode_GET_SIZE(pystr);
619 Py_ssize_t begin = end - 1;
620 Py_ssize_t next;
621 const Py_UNICODE *buf = PyUnicode_AS_UNICODE(pystr);
622 PyObject *chunks = PyList_New(0);
623 if (chunks == NULL) {
624 goto bail;
625 }
626 if (end < 0 || len <= end) {
627 PyErr_SetString(PyExc_ValueError, "end is out of bounds");
628 goto bail;
629 }
630 while (1) {
631 /* Find the end of the string or the next escape */
632 Py_UNICODE c = 0;
633 PyObject *chunk = NULL;
634 for (next = end; next < len; next++) {
635 c = buf[next];
636 if (c == '"' || c == '\\') {
637 break;
638 }
639 else if (strict && c <= 0x1f) {
640 raise_errmsg("Invalid control character at", pystr, next);
641 goto bail;
642 }
643 }
644 if (!(c == '"' || c == '\\')) {
645 raise_errmsg("Unterminated string starting at", pystr, begin);
646 goto bail;
647 }
648 /* Pick up this chunk if it's not zero length */
649 if (next != end) {
650 chunk = PyUnicode_FromUnicode(&buf[end], next - end);
651 if (chunk == NULL) {
652 goto bail;
653 }
654 if (PyList_Append(chunks, chunk)) {
655 Py_DECREF(chunk);
656 goto bail;
657 }
658 Py_DECREF(chunk);
659 }
660 next++;
661 if (c == '"') {
662 end = next;
663 break;
664 }
665 if (next == len) {
666 raise_errmsg("Unterminated string starting at", pystr, begin);
667 goto bail;
668 }
669 c = buf[next];
670 if (c != 'u') {
671 /* Non-unicode backslash escapes */
672 end = next + 1;
673 switch (c) {
674 case '"': break;
675 case '\\': break;
676 case '/': break;
677 case 'b': c = '\b'; break;
678 case 'f': c = '\f'; break;
679 case 'n': c = '\n'; break;
680 case 'r': c = '\r'; break;
681 case 't': c = '\t'; break;
682 default: c = 0;
683 }
684 if (c == 0) {
685 raise_errmsg("Invalid \\escape", pystr, end - 2);
686 goto bail;
687 }
688 }
689 else {
690 c = 0;
691 next++;
692 end = next + 4;
693 if (end >= len) {
694 raise_errmsg("Invalid \\uXXXX escape", pystr, next - 1);
695 goto bail;
696 }
697 /* Decode 4 hex digits */
698 for (; next < end; next++) {
699 Py_UNICODE digit = buf[next];
700 c <<= 4;
701 switch (digit) {
702 case '0': case '1': case '2': case '3': case '4':
703 case '5': case '6': case '7': case '8': case '9':
704 c |= (digit - '0'); break;
705 case 'a': case 'b': case 'c': case 'd': case 'e':
706 case 'f':
707 c |= (digit - 'a' + 10); break;
708 case 'A': case 'B': case 'C': case 'D': case 'E':
709 case 'F':
710 c |= (digit - 'A' + 10); break;
711 default:
712 raise_errmsg("Invalid \\uXXXX escape", pystr, end - 5);
713 goto bail;
714 }
715 }
716 #ifdef Py_UNICODE_WIDE
717 /* Surrogate pair */
718 if ((c & 0xfc00) == 0xd800 && end + 6 < len &&
719 buf[next++] == '\\' && buf[next++] == 'u') {
720 Py_UNICODE c2 = 0;
721 end += 6;
722 /* Decode 4 hex digits */
723 for (; next < end; next++) {
724 Py_UNICODE digit = buf[next];
725 c2 <<= 4;
726 switch (digit) {
727 case '0': case '1': case '2': case '3': case '4':
728 case '5': case '6': case '7': case '8': case '9':
729 c2 |= (digit - '0'); break;
730 case 'a': case 'b': case 'c': case 'd': case 'e':
731 case 'f':
732 c2 |= (digit - 'a' + 10); break;
733 case 'A': case 'B': case 'C': case 'D': case 'E':
734 case 'F':
735 c2 |= (digit - 'A' + 10); break;
736 default:
737 raise_errmsg("Invalid \\uXXXX escape", pystr, end - 5);
738 goto bail;
739 }
740 }
741 if ((c2 & 0xfc00) == 0xdc00)
742 c = 0x10000 + (((c - 0xd800) << 10) | (c2 - 0xdc00));
743 else
744 end -= 6;
745 }
746 #endif
747 }
748 chunk = PyUnicode_FromUnicode(&c, 1);
749 if (chunk == NULL) {
750 goto bail;
751 }
752 if (PyList_Append(chunks, chunk)) {
753 Py_DECREF(chunk);
754 goto bail;
755 }
756 Py_DECREF(chunk);
757 }
758
759 rval = join_list_unicode(chunks);
760 if (rval == NULL) {
761 goto bail;
762 }
763 Py_DECREF(chunks);
764 *next_end_ptr = end;
765 return rval;
766 bail:
767 *next_end_ptr = -1;
768 Py_XDECREF(chunks);
769 return NULL;
770 }
771
772 PyDoc_STRVAR(pydoc_scanstring,
773 "scanstring(basestring, end, encoding, strict=True) -> (str, end)\n"
774 "\n"
775 "Scan the string s for a JSON string. End is the index of the\n"
776 "character in s after the quote that started the JSON string.\n"
777 "Unescapes all valid JSON string escape sequences and raises ValueError\n"
778 "on attempt to decode an invalid string. If strict is False then literal\n"
779 "control characters are allowed in the string.\n"
780 "\n"
781 "Returns a tuple of the decoded string and the index of the character in s\n"
782 "after the end quote."
783 );
784
785 static PyObject *
786 py_scanstring(PyObject* self UNUSED, PyObject *args)
787 {
788 PyObject *pystr;
789 PyObject *rval;
790 Py_ssize_t end;
791 Py_ssize_t next_end = -1;
792 char *encoding = NULL;
793 int strict = 1;
794 if (!PyArg_ParseTuple(args, "OO&|zi:scanstring", &pystr, _convertPyInt_AsSsize_t, &end, &encoding, &strict)) {
795 return NULL;
796 }
797 if (encoding == NULL) {
798 encoding = DEFAULT_ENCODING;
799 }
800 if (PyString_Check(pystr)) {
801 rval = scanstring_str(pystr, end, encoding, strict, &next_end);
802 }
803 else if (PyUnicode_Check(pystr)) {
804 rval = scanstring_unicode(pystr, end, strict, &next_end);
805 }
806 else {
807 PyErr_Format(PyExc_TypeError,
808 "first argument must be a string, not %.80s",
809 Py_TYPE(pystr)->tp_name);
810 return NULL;
811 }
812 return _build_rval_index_tuple(rval, next_end);
813 }
814
815 PyDoc_STRVAR(pydoc_encode_basestring_ascii,
816 "encode_basestring_ascii(basestring) -> str\n"
817 "\n"
818 "Return an ASCII-only JSON representation of a Python string"
819 );
820
821 static PyObject *
822 py_encode_basestring_ascii(PyObject* self UNUSED, PyObject *pystr)
823 {
824 /* Return an ASCII-only JSON representation of a Python string */
825 /* METH_O */
826 if (PyString_Check(pystr)) {
827 return ascii_escape_str(pystr);
828 }
829 else if (PyUnicode_Check(pystr)) {
830 return ascii_escape_unicode(pystr);
831 }
832 else {
833 PyErr_Format(PyExc_TypeError,
834 "first argument must be a string, not %.80s",
835 Py_TYPE(pystr)->tp_name);
836 return NULL;
837 }
838 }
839
840 static void
841 scanner_dealloc(PyObject *self)
842 {
843 /* bpo-31095: UnTrack is needed before calling any callbacks */
844 PyObject_GC_UnTrack(self);
845 scanner_clear(self);
846 Py_TYPE(self)->tp_free(self);
847 }
848
849 static int
850 scanner_traverse(PyObject *self, visitproc visit, void *arg)
851 {
852 PyScannerObject *s;
853 assert(PyScanner_Check(self));
854 s = (PyScannerObject *)self;
855 Py_VISIT(s->encoding);
856 Py_VISIT(s->strict);
857 Py_VISIT(s->object_hook);
858 Py_VISIT(s->pairs_hook);
859 Py_VISIT(s->parse_float);
860 Py_VISIT(s->parse_int);
861 Py_VISIT(s->parse_constant);
862 return 0;
863 }
864
865 static int
866 scanner_clear(PyObject *self)
867 {
868 PyScannerObject *s;
869 assert(PyScanner_Check(self));
870 s = (PyScannerObject *)self;
871 Py_CLEAR(s->encoding);
872 Py_CLEAR(s->strict);
873 Py_CLEAR(s->object_hook);
874 Py_CLEAR(s->pairs_hook);
875 Py_CLEAR(s->parse_float);
876 Py_CLEAR(s->parse_int);
877 Py_CLEAR(s->parse_constant);
878 return 0;
879 }
880
881 static PyObject *
882 _parse_object_str(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) {
883 /* Read a JSON object from PyString pystr.
884 idx is the index of the first character after the opening curly brace.
885 *next_idx_ptr is a return-by-reference index to the first character after
886 the closing curly brace.
887
888 Returns a new PyObject (usually a dict, but object_hook can change that)
889 */
890 char *str = PyString_AS_STRING(pystr);
891 Py_ssize_t end_idx = PyString_GET_SIZE(pystr) - 1;
892 PyObject *rval;
893 PyObject *pairs;
894 PyObject *item;
895 PyObject *key = NULL;
896 PyObject *val = NULL;
897 char *encoding = PyString_AS_STRING(s->encoding);
898 int strict = PyObject_IsTrue(s->strict);
899 Py_ssize_t next_idx;
900
901 if (strict < 0)
902 return NULL;
903
904 pairs = PyList_New(0);
905 if (pairs == NULL)
906 return NULL;
907
908 /* skip whitespace after { */
909 while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
910
911 /* only loop if the object is non-empty */
912 if (idx <= end_idx && str[idx] != '}') {
913 while (idx <= end_idx) {
914 /* read key */
915 if (str[idx] != '"') {
916 raise_errmsg("Expecting property name", pystr, idx);
917 goto bail;
918 }
919 key = scanstring_str(pystr, idx + 1, encoding, strict, &next_idx);
920 if (key == NULL)
921 goto bail;
922 idx = next_idx;
923
924 /* skip whitespace between key and : delimiter, read :, skip whitespace */
925 while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
926 if (idx > end_idx || str[idx] != ':') {
927 raise_errmsg("Expecting : delimiter", pystr, idx);
928 goto bail;
929 }
930 idx++;
931 while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
932
933 /* read any JSON data type */
934 val = scan_once_str(s, pystr, idx, &next_idx);
935 if (val == NULL)
936 goto bail;
937
938 item = PyTuple_Pack(2, key, val);
939 if (item == NULL)
940 goto bail;
941 Py_CLEAR(key);
942 Py_CLEAR(val);
943 if (PyList_Append(pairs, item) == -1) {
944 Py_DECREF(item);
945 goto bail;
946 }
947 Py_DECREF(item);
948 idx = next_idx;
949
950 /* skip whitespace before } or , */
951 while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
952
953 /* bail if the object is closed or we didn't get the , delimiter */
954 if (idx > end_idx) break;
955 if (str[idx] == '}') {
956 break;
957 }
958 else if (str[idx] != ',') {
959 raise_errmsg("Expecting , delimiter", pystr, idx);
960 goto bail;
961 }
962 idx++;
963
964 /* skip whitespace after , delimiter */
965 while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
966 }
967 }
968 /* verify that idx < end_idx, str[idx] should be '}' */
969 if (idx > end_idx || str[idx] != '}') {
970 raise_errmsg("Expecting object", pystr, end_idx);
971 goto bail;
972 }
973
974 /* if pairs_hook is not None: rval = object_pairs_hook(pairs) */
975 if (s->pairs_hook != Py_None) {
976 val = PyObject_CallFunctionObjArgs(s->pairs_hook, pairs, NULL);
977 if (val == NULL)
978 goto bail;
979 Py_DECREF(pairs);
980 *next_idx_ptr = idx + 1;
981 return val;
982 }
983
984 rval = PyObject_CallFunctionObjArgs((PyObject *)(&PyDict_Type),
985 pairs, NULL);
986 if (rval == NULL)
987 goto bail;
988 Py_CLEAR(pairs);
989
990 /* if object_hook is not None: rval = object_hook(rval) */
991 if (s->object_hook != Py_None) {
992 val = PyObject_CallFunctionObjArgs(s->object_hook, rval, NULL);
993 if (val == NULL)
994 goto bail;
995 Py_DECREF(rval);
996 rval = val;
997 val = NULL;
998 }
999 *next_idx_ptr = idx + 1;
1000 return rval;
1001 bail:
1002 Py_XDECREF(key);
1003 Py_XDECREF(val);
1004 Py_XDECREF(pairs);
1005 return NULL;
1006 }
1007
1008 static PyObject *
1009 _parse_object_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) {
1010 /* Read a JSON object from PyUnicode pystr.
1011 idx is the index of the first character after the opening curly brace.
1012 *next_idx_ptr is a return-by-reference index to the first character after
1013 the closing curly brace.
1014
1015 Returns a new PyObject (usually a dict, but object_hook can change that)
1016 */
1017 Py_UNICODE *str = PyUnicode_AS_UNICODE(pystr);
1018 Py_ssize_t end_idx = PyUnicode_GET_SIZE(pystr) - 1;
1019 PyObject *rval;
1020 PyObject *pairs;
1021 PyObject *item;
1022 PyObject *key = NULL;
1023 PyObject *val = NULL;
1024 int strict = PyObject_IsTrue(s->strict);
1025 Py_ssize_t next_idx;
1026
1027 if (strict < 0)
1028 return NULL;
1029
1030 pairs = PyList_New(0);
1031 if (pairs == NULL)
1032 return NULL;
1033
1034 /* skip whitespace after { */
1035 while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
1036
1037 /* only loop if the object is non-empty */
1038 if (idx <= end_idx && str[idx] != '}') {
1039 while (idx <= end_idx) {
1040 /* read key */
1041 if (str[idx] != '"') {
1042 raise_errmsg("Expecting property name enclosed in double quotes", pystr, idx);
1043 goto bail;
1044 }
1045 key = scanstring_unicode(pystr, idx + 1, strict, &next_idx);
1046 if (key == NULL)
1047 goto bail;
1048 idx = next_idx;
1049
1050 /* skip whitespace between key and : delimiter, read :, skip whitespace */
1051 while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
1052 if (idx > end_idx || str[idx] != ':') {
1053 raise_errmsg("Expecting ':' delimiter", pystr, idx);
1054 goto bail;
1055 }
1056 idx++;
1057 while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
1058
1059 /* read any JSON term */
1060 val = scan_once_unicode(s, pystr, idx, &next_idx);
1061 if (val == NULL)
1062 goto bail;
1063
1064 item = PyTuple_Pack(2, key, val);
1065 if (item == NULL)
1066 goto bail;
1067 Py_CLEAR(key);
1068 Py_CLEAR(val);
1069 if (PyList_Append(pairs, item) == -1) {
1070 Py_DECREF(item);
1071 goto bail;
1072 }
1073 Py_DECREF(item);
1074 idx = next_idx;
1075
1076 /* skip whitespace before } or , */
1077 while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
1078
1079 /* bail if the object is closed or we didn't get the , delimiter */
1080 if (idx > end_idx) break;
1081 if (str[idx] == '}') {
1082 break;
1083 }
1084 else if (str[idx] != ',') {
1085 raise_errmsg("Expecting ',' delimiter", pystr, idx);
1086 goto bail;
1087 }
1088 idx++;
1089
1090 /* skip whitespace after , delimiter */
1091 while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
1092 }
1093 }
1094
1095 /* verify that idx < end_idx, str[idx] should be '}' */
1096 if (idx > end_idx || str[idx] != '}') {
1097 raise_errmsg("Expecting object", pystr, end_idx);
1098 goto bail;
1099 }
1100
1101 /* if pairs_hook is not None: rval = object_pairs_hook(pairs) */
1102 if (s->pairs_hook != Py_None) {
1103 val = PyObject_CallFunctionObjArgs(s->pairs_hook, pairs, NULL);
1104 if (val == NULL)
1105 goto bail;
1106 Py_DECREF(pairs);
1107 *next_idx_ptr = idx + 1;
1108 return val;
1109 }
1110
1111 rval = PyObject_CallFunctionObjArgs((PyObject *)(&PyDict_Type),
1112 pairs, NULL);
1113 if (rval == NULL)
1114 goto bail;
1115 Py_CLEAR(pairs);
1116
1117 /* if object_hook is not None: rval = object_hook(rval) */
1118 if (s->object_hook != Py_None) {
1119 val = PyObject_CallFunctionObjArgs(s->object_hook, rval, NULL);
1120 if (val == NULL)
1121 goto bail;
1122 Py_DECREF(rval);
1123 rval = val;
1124 val = NULL;
1125 }
1126 *next_idx_ptr = idx + 1;
1127 return rval;
1128 bail:
1129 Py_XDECREF(key);
1130 Py_XDECREF(val);
1131 Py_XDECREF(pairs);
1132 return NULL;
1133 }
1134
1135 static PyObject *
1136 _parse_array_str(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) {
1137 /* Read a JSON array from PyString pystr.
1138 idx is the index of the first character after the opening brace.
1139 *next_idx_ptr is a return-by-reference index to the first character after
1140 the closing brace.
1141
1142 Returns a new PyList
1143 */
1144 char *str = PyString_AS_STRING(pystr);
1145 Py_ssize_t end_idx = PyString_GET_SIZE(pystr) - 1;
1146 PyObject *val = NULL;
1147 PyObject *rval = PyList_New(0);
1148 Py_ssize_t next_idx;
1149 if (rval == NULL)
1150 return NULL;
1151
1152 /* skip whitespace after [ */
1153 while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
1154
1155 /* only loop if the array is non-empty */
1156 if (idx <= end_idx && str[idx] != ']') {
1157 while (idx <= end_idx) {
1158
1159 /* read any JSON term and de-tuplefy the (rval, idx) */
1160 val = scan_once_str(s, pystr, idx, &next_idx);
1161 if (val == NULL)
1162 goto bail;
1163
1164 if (PyList_Append(rval, val) == -1)
1165 goto bail;
1166
1167 Py_CLEAR(val);
1168 idx = next_idx;
1169
1170 /* skip whitespace between term and , */
1171 while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
1172
1173 /* bail if the array is closed or we didn't get the , delimiter */
1174 if (idx > end_idx) break;
1175 if (str[idx] == ']') {
1176 break;
1177 }
1178 else if (str[idx] != ',') {
1179 raise_errmsg("Expecting , delimiter", pystr, idx);
1180 goto bail;
1181 }
1182 idx++;
1183
1184 /* skip whitespace after , */
1185 while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
1186 }
1187 }
1188
1189 /* verify that idx < end_idx, str[idx] should be ']' */
1190 if (idx > end_idx || str[idx] != ']') {
1191 raise_errmsg("Expecting object", pystr, end_idx);
1192 goto bail;
1193 }
1194 *next_idx_ptr = idx + 1;
1195 return rval;
1196 bail:
1197 Py_XDECREF(val);
1198 Py_DECREF(rval);
1199 return NULL;
1200 }
1201
1202 static PyObject *
1203 _parse_array_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) {
1204 /* Read a JSON array from PyString pystr.
1205 idx is the index of the first character after the opening brace.
1206 *next_idx_ptr is a return-by-reference index to the first character after
1207 the closing brace.
1208
1209 Returns a new PyList
1210 */
1211 Py_UNICODE *str = PyUnicode_AS_UNICODE(pystr);
1212 Py_ssize_t end_idx = PyUnicode_GET_SIZE(pystr) - 1;
1213 PyObject *val = NULL;
1214 PyObject *rval = PyList_New(0);
1215 Py_ssize_t next_idx;
1216 if (rval == NULL)
1217 return NULL;
1218
1219 /* skip whitespace after [ */
1220 while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
1221
1222 /* only loop if the array is non-empty */
1223 if (idx <= end_idx && str[idx] != ']') {
1224 while (idx <= end_idx) {
1225
1226 /* read any JSON term */
1227 val = scan_once_unicode(s, pystr, idx, &next_idx);
1228 if (val == NULL)
1229 goto bail;
1230
1231 if (PyList_Append(rval, val) == -1)
1232 goto bail;
1233
1234 Py_CLEAR(val);
1235 idx = next_idx;
1236
1237 /* skip whitespace between term and , */
1238 while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
1239
1240 /* bail if the array is closed or we didn't get the , delimiter */
1241 if (idx > end_idx) break;
1242 if (str[idx] == ']') {
1243 break;
1244 }
1245 else if (str[idx] != ',') {
1246 raise_errmsg("Expecting ',' delimiter", pystr, idx);
1247 goto bail;
1248 }
1249 idx++;
1250
1251 /* skip whitespace after , */
1252 while (idx <= end_idx && IS_WHITESPACE(str[idx])) idx++;
1253 }
1254 }
1255
1256 /* verify that idx < end_idx, str[idx] should be ']' */
1257 if (idx > end_idx || str[idx] != ']') {
1258 raise_errmsg("Expecting object", pystr, end_idx);
1259 goto bail;
1260 }
1261 *next_idx_ptr = idx + 1;
1262 return rval;
1263 bail:
1264 Py_XDECREF(val);
1265 Py_DECREF(rval);
1266 return NULL;
1267 }
1268
1269 static PyObject *
1270 _parse_constant(PyScannerObject *s, char *constant, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) {
1271 /* Read a JSON constant from PyString pystr.
1272 constant is the constant string that was found
1273 ("NaN", "Infinity", "-Infinity").
1274 idx is the index of the first character of the constant
1275 *next_idx_ptr is a return-by-reference index to the first character after
1276 the constant.
1277
1278 Returns the result of parse_constant
1279 */
1280 PyObject *cstr;
1281 PyObject *rval;
1282 /* constant is "NaN", "Infinity", or "-Infinity" */
1283 cstr = PyString_InternFromString(constant);
1284 if (cstr == NULL)
1285 return NULL;
1286
1287 /* rval = parse_constant(constant) */
1288 rval = PyObject_CallFunctionObjArgs(s->parse_constant, cstr, NULL);
1289 idx += PyString_GET_SIZE(cstr);
1290 Py_DECREF(cstr);
1291 *next_idx_ptr = idx;
1292 return rval;
1293 }
1294
1295 static PyObject *
1296 _match_number_str(PyScannerObject *s, PyObject *pystr, Py_ssize_t start, Py_ssize_t *next_idx_ptr) {
1297 /* Read a JSON number from PyString pystr.
1298 idx is the index of the first character of the number
1299 *next_idx_ptr is a return-by-reference index to the first character after
1300 the number.
1301
1302 Returns a new PyObject representation of that number:
1303 PyInt, PyLong, or PyFloat.
1304 May return other types if parse_int or parse_float are set
1305 */
1306 char *str = PyString_AS_STRING(pystr);
1307 Py_ssize_t end_idx = PyString_GET_SIZE(pystr) - 1;
1308 Py_ssize_t idx = start;
1309 int is_float = 0;
1310 PyObject *rval;
1311 PyObject *numstr;
1312
1313 /* read a sign if it's there, make sure it's not the end of the string */
1314 if (str[idx] == '-') {
1315 idx++;
1316 if (idx > end_idx) {
1317 PyErr_SetNone(PyExc_StopIteration);
1318 return NULL;
1319 }
1320 }
1321
1322 /* read as many integer digits as we find as long as it doesn't start with 0 */
1323 if (str[idx] >= '1' && str[idx] <= '9') {
1324 idx++;
1325 while (idx <= end_idx && str[idx] >= '0' && str[idx] <= '9') idx++;
1326 }
1327 /* if it starts with 0 we only expect one integer digit */
1328 else if (str[idx] == '0') {
1329 idx++;
1330 }
1331 /* no integer digits, error */
1332 else {
1333 PyErr_SetNone(PyExc_StopIteration);
1334 return NULL;
1335 }
1336
1337 /* if the next char is '.' followed by a digit then read all float digits */
1338 if (idx < end_idx && str[idx] == '.' && str[idx + 1] >= '0' && str[idx + 1] <= '9') {
1339 is_float = 1;
1340 idx += 2;
1341 while (idx <= end_idx && str[idx] >= '0' && str[idx] <= '9') idx++;
1342 }
1343
1344 /* if the next char is 'e' or 'E' then maybe read the exponent (or backtrack) */
1345 if (idx < end_idx && (str[idx] == 'e' || str[idx] == 'E')) {
1346
1347 /* save the index of the 'e' or 'E' just in case we need to backtrack */
1348 Py_ssize_t e_start = idx;
1349 idx++;
1350
1351 /* read an exponent sign if present */
1352 if (idx < end_idx && (str[idx] == '-' || str[idx] == '+')) idx++;
1353
1354 /* read all digits */
1355 while (idx <= end_idx && str[idx] >= '0' && str[idx] <= '9') idx++;
1356
1357 /* if we got a digit, then parse as float. if not, backtrack */
1358 if (str[idx - 1] >= '0' && str[idx - 1] <= '9') {
1359 is_float = 1;
1360 }
1361 else {
1362 idx = e_start;
1363 }
1364 }
1365
1366 /* copy the section we determined to be a number */
1367 numstr = PyString_FromStringAndSize(&str[start], idx - start);
1368 if (numstr == NULL)
1369 return NULL;
1370 if (is_float) {
1371 /* parse as a float using a fast path if available, otherwise call user defined method */
1372 if (s->parse_float != (PyObject *)&PyFloat_Type) {
1373 rval = PyObject_CallFunctionObjArgs(s->parse_float, numstr, NULL);
1374 }
1375 else {
1376 double d = PyOS_string_to_double(PyString_AS_STRING(numstr),
1377 NULL, NULL);
1378 if (d == -1.0 && PyErr_Occurred()) {
1379 Py_DECREF(numstr);
1380 return NULL;
1381 }
1382 rval = PyFloat_FromDouble(d);
1383 }
1384 }
1385 else {
1386 /* parse as an int using a fast path if available, otherwise call user defined method */
1387 if (s->parse_int != (PyObject *)&PyInt_Type) {
1388 rval = PyObject_CallFunctionObjArgs(s->parse_int, numstr, NULL);
1389 }
1390 else {
1391 rval = PyInt_FromString(PyString_AS_STRING(numstr), NULL, 10);
1392 }
1393 }
1394 Py_DECREF(numstr);
1395 *next_idx_ptr = idx;
1396 return rval;
1397 }
1398
1399 static PyObject *
1400 _match_number_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t start, Py_ssize_t *next_idx_ptr) {
1401 /* Read a JSON number from PyUnicode pystr.
1402 idx is the index of the first character of the number
1403 *next_idx_ptr is a return-by-reference index to the first character after
1404 the number.
1405
1406 Returns a new PyObject representation of that number:
1407 PyInt, PyLong, or PyFloat.
1408 May return other types if parse_int or parse_float are set
1409 */
1410 Py_UNICODE *str = PyUnicode_AS_UNICODE(pystr);
1411 Py_ssize_t end_idx = PyUnicode_GET_SIZE(pystr) - 1;
1412 Py_ssize_t idx = start;
1413 int is_float = 0;
1414 PyObject *rval;
1415 PyObject *numstr;
1416
1417 /* read a sign if it's there, make sure it's not the end of the string */
1418 if (str[idx] == '-') {
1419 idx++;
1420 if (idx > end_idx) {
1421 PyErr_SetNone(PyExc_StopIteration);
1422 return NULL;
1423 }
1424 }
1425
1426 /* read as many integer digits as we find as long as it doesn't start with 0 */
1427 if (str[idx] >= '1' && str[idx] <= '9') {
1428 idx++;
1429 while (idx <= end_idx && str[idx] >= '0' && str[idx] <= '9') idx++;
1430 }
1431 /* if it starts with 0 we only expect one integer digit */
1432 else if (str[idx] == '0') {
1433 idx++;
1434 }
1435 /* no integer digits, error */
1436 else {
1437 PyErr_SetNone(PyExc_StopIteration);
1438 return NULL;
1439 }
1440
1441 /* if the next char is '.' followed by a digit then read all float digits */
1442 if (idx < end_idx && str[idx] == '.' && str[idx + 1] >= '0' && str[idx + 1] <= '9') {
1443 is_float = 1;
1444 idx += 2;
1445 while (idx <= end_idx && str[idx] >= '0' && str[idx] <= '9') idx++;
1446 }
1447
1448 /* if the next char is 'e' or 'E' then maybe read the exponent (or backtrack) */
1449 if (idx < end_idx && (str[idx] == 'e' || str[idx] == 'E')) {
1450 Py_ssize_t e_start = idx;
1451 idx++;
1452
1453 /* read an exponent sign if present */
1454 if (idx < end_idx && (str[idx] == '-' || str[idx] == '+')) idx++;
1455
1456 /* read all digits */
1457 while (idx <= end_idx && str[idx] >= '0' && str[idx] <= '9') idx++;
1458
1459 /* if we got a digit, then parse as float. if not, backtrack */
1460 if (str[idx - 1] >= '0' && str[idx - 1] <= '9') {
1461 is_float = 1;
1462 }
1463 else {
1464 idx = e_start;
1465 }
1466 }
1467
1468 /* copy the section we determined to be a number */
1469 numstr = PyUnicode_FromUnicode(&str[start], idx - start);
1470 if (numstr == NULL)
1471 return NULL;
1472 if (is_float) {
1473 /* parse as a float using a fast path if available, otherwise call user defined method */
1474 if (s->parse_float != (PyObject *)&PyFloat_Type) {
1475 rval = PyObject_CallFunctionObjArgs(s->parse_float, numstr, NULL);
1476 }
1477 else {
1478 rval = PyFloat_FromString(numstr, NULL);
1479 }
1480 }
1481 else {
1482 /* no fast path for unicode -> int, just call */
1483 rval = PyObject_CallFunctionObjArgs(s->parse_int, numstr, NULL);
1484 }
1485 Py_DECREF(numstr);
1486 *next_idx_ptr = idx;
1487 return rval;
1488 }
1489
1490 static PyObject *
1491 scan_once_str(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr)
1492 {
1493 /* Read one JSON term (of any kind) from PyString pystr.
1494 idx is the index of the first character of the term
1495 *next_idx_ptr is a return-by-reference index to the first character after
1496 the number.
1497
1498 Returns a new PyObject representation of the term.
1499 */
1500 PyObject *res;
1501 int strict;
1502 char *str = PyString_AS_STRING(pystr);
1503 Py_ssize_t length = PyString_GET_SIZE(pystr);
1504 if (idx < 0) {
1505 PyErr_SetString(PyExc_ValueError, "idx cannot be negative");
1506 return NULL;
1507 }
1508 if (idx >= length) {
1509 PyErr_SetNone(PyExc_StopIteration);
1510 return NULL;
1511 }
1512 switch (str[idx]) {
1513 case '"':
1514 /* string */
1515 strict = PyObject_IsTrue(s->strict);
1516 if (strict < 0)
1517 return NULL;
1518 return scanstring_str(pystr, idx + 1,
1519 PyString_AS_STRING(s->encoding), strict, next_idx_ptr);
1520 case '{':
1521 /* object */
1522 if (Py_EnterRecursiveCall(" while decoding a JSON object "
1523 "from a byte string"))
1524 return NULL;
1525 res = _parse_object_str(s, pystr, idx + 1, next_idx_ptr);
1526 Py_LeaveRecursiveCall();
1527 return res;
1528 case '[':
1529 /* array */
1530 if (Py_EnterRecursiveCall(" while decoding a JSON array "
1531 "from a byte string"))
1532 return NULL;
1533 res = _parse_array_str(s, pystr, idx + 1, next_idx_ptr);
1534 Py_LeaveRecursiveCall();
1535 return res;
1536 case 'n':
1537 /* null */
1538 if ((idx + 3 < length) && str[idx + 1] == 'u' && str[idx + 2] == 'l' && str[idx + 3] == 'l') {
1539 Py_INCREF(Py_None);
1540 *next_idx_ptr = idx + 4;
1541 return Py_None;
1542 }
1543 break;
1544 case 't':
1545 /* true */
1546 if ((idx + 3 < length) && str[idx + 1] == 'r' && str[idx + 2] == 'u' && str[idx + 3] == 'e') {
1547 Py_INCREF(Py_True);
1548 *next_idx_ptr = idx + 4;
1549 return Py_True;
1550 }
1551 break;
1552 case 'f':
1553 /* false */
1554 if ((idx + 4 < length) && str[idx + 1] == 'a' && str[idx + 2] == 'l' && str[idx + 3] == 's' && str[idx + 4] == 'e') {
1555 Py_INCREF(Py_False);
1556 *next_idx_ptr = idx + 5;
1557 return Py_False;
1558 }
1559 break;
1560 case 'N':
1561 /* NaN */
1562 if ((idx + 2 < length) && str[idx + 1] == 'a' && str[idx + 2] == 'N') {
1563 return _parse_constant(s, "NaN", idx, next_idx_ptr);
1564 }
1565 break;
1566 case 'I':
1567 /* Infinity */
1568 if ((idx + 7 < length) && str[idx + 1] == 'n' && str[idx + 2] == 'f' && str[idx + 3] == 'i' && str[idx + 4] == 'n' && str[idx + 5] == 'i' && str[idx + 6] == 't' && str[idx + 7] == 'y') {
1569 return _parse_constant(s, "Infinity", idx, next_idx_ptr);
1570 }
1571 break;
1572 case '-':
1573 /* -Infinity */
1574 if ((idx + 8 < length) && str[idx + 1] == 'I' && str[idx + 2] == 'n' && str[idx + 3] == 'f' && str[idx + 4] == 'i' && str[idx + 5] == 'n' && str[idx + 6] == 'i' && str[idx + 7] == 't' && str[idx + 8] == 'y') {
1575 return _parse_constant(s, "-Infinity", idx, next_idx_ptr);
1576 }
1577 break;
1578 }
1579 /* Didn't find a string, object, array, or named constant. Look for a number. */
1580 return _match_number_str(s, pystr, idx, next_idx_ptr);
1581 }
1582
1583 static PyObject *
1584 scan_once_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr)
1585 {
1586 /* Read one JSON term (of any kind) from PyUnicode pystr.
1587 idx is the index of the first character of the term
1588 *next_idx_ptr is a return-by-reference index to the first character after
1589 the number.
1590
1591 Returns a new PyObject representation of the term.
1592 */
1593 PyObject *res;
1594 int strict;
1595 Py_UNICODE *str = PyUnicode_AS_UNICODE(pystr);
1596 Py_ssize_t length = PyUnicode_GET_SIZE(pystr);
1597 if (idx < 0) {
1598 PyErr_SetString(PyExc_ValueError, "idx cannot be negative");
1599 return NULL;
1600 }
1601 if (idx >= length) {
1602 PyErr_SetNone(PyExc_StopIteration);
1603 return NULL;
1604 }
1605 switch (str[idx]) {
1606 case '"':
1607 /* string */
1608 strict = PyObject_IsTrue(s->strict);
1609 if (strict < 0)
1610 return NULL;
1611 return scanstring_unicode(pystr, idx + 1, strict, next_idx_ptr);
1612 case '{':
1613 /* object */
1614 if (Py_EnterRecursiveCall(" while decoding a JSON object "
1615 "from a unicode string"))
1616 return NULL;
1617 res = _parse_object_unicode(s, pystr, idx + 1, next_idx_ptr);
1618 Py_LeaveRecursiveCall();
1619 return res;
1620 case '[':
1621 /* array */
1622 if (Py_EnterRecursiveCall(" while decoding a JSON array "
1623 "from a unicode string"))
1624 return NULL;
1625 res = _parse_array_unicode(s, pystr, idx + 1, next_idx_ptr);
1626 Py_LeaveRecursiveCall();
1627 return res;
1628 case 'n':
1629 /* null */
1630 if ((idx + 3 < length) && str[idx + 1] == 'u' && str[idx + 2] == 'l' && str[idx + 3] == 'l') {
1631 Py_INCREF(Py_None);
1632 *next_idx_ptr = idx + 4;
1633 return Py_None;
1634 }
1635 break;
1636 case 't':
1637 /* true */
1638 if ((idx + 3 < length) && str[idx + 1] == 'r' && str[idx + 2] == 'u' && str[idx + 3] == 'e') {
1639 Py_INCREF(Py_True);
1640 *next_idx_ptr = idx + 4;
1641 return Py_True;
1642 }
1643 break;
1644 case 'f':
1645 /* false */
1646 if ((idx + 4 < length) && str[idx + 1] == 'a' && str[idx + 2] == 'l' && str[idx + 3] == 's' && str[idx + 4] == 'e') {
1647 Py_INCREF(Py_False);
1648 *next_idx_ptr = idx + 5;
1649 return Py_False;
1650 }
1651 break;
1652 case 'N':
1653 /* NaN */
1654 if ((idx + 2 < length) && str[idx + 1] == 'a' && str[idx + 2] == 'N') {
1655 return _parse_constant(s, "NaN", idx, next_idx_ptr);
1656 }
1657 break;
1658 case 'I':
1659 /* Infinity */
1660 if ((idx + 7 < length) && str[idx + 1] == 'n' && str[idx + 2] == 'f' && str[idx + 3] == 'i' && str[idx + 4] == 'n' && str[idx + 5] == 'i' && str[idx + 6] == 't' && str[idx + 7] == 'y') {
1661 return _parse_constant(s, "Infinity", idx, next_idx_ptr);
1662 }
1663 break;
1664 case '-':
1665 /* -Infinity */
1666 if ((idx + 8 < length) && str[idx + 1] == 'I' && str[idx + 2] == 'n' && str[idx + 3] == 'f' && str[idx + 4] == 'i' && str[idx + 5] == 'n' && str[idx + 6] == 'i' && str[idx + 7] == 't' && str[idx + 8] == 'y') {
1667 return _parse_constant(s, "-Infinity", idx, next_idx_ptr);
1668 }
1669 break;
1670 }
1671 /* Didn't find a string, object, array, or named constant. Look for a number. */
1672 return _match_number_unicode(s, pystr, idx, next_idx_ptr);
1673 }
1674
1675 static PyObject *
1676 scanner_call(PyObject *self, PyObject *args, PyObject *kwds)
1677 {
1678 /* Python callable interface to scan_once_{str,unicode} */
1679 PyObject *pystr;
1680 PyObject *rval;
1681 Py_ssize_t idx;
1682 Py_ssize_t next_idx = -1;
1683 static char *kwlist[] = {"string", "idx", NULL};
1684 PyScannerObject *s;
1685 assert(PyScanner_Check(self));
1686 s = (PyScannerObject *)self;
1687 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO&:scan_once", kwlist, &pystr, _convertPyInt_AsSsize_t, &idx))
1688 return NULL;
1689
1690 if (PyString_Check(pystr)) {
1691 rval = scan_once_str(s, pystr, idx, &next_idx);
1692 }
1693 else if (PyUnicode_Check(pystr)) {
1694 rval = scan_once_unicode(s, pystr, idx, &next_idx);
1695 }
1696 else {
1697 PyErr_Format(PyExc_TypeError,
1698 "first argument must be a string, not %.80s",
1699 Py_TYPE(pystr)->tp_name);
1700 return NULL;
1701 }
1702 return _build_rval_index_tuple(rval, next_idx);
1703 }
1704
1705 static PyObject *
1706 scanner_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1707 {
1708 PyScannerObject *s;
1709 PyObject *ctx;
1710 static char *kwlist[] = {"context", NULL};
1711
1712 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:make_scanner", kwlist, &ctx))
1713 return NULL;
1714
1715 s = (PyScannerObject *)type->tp_alloc(type, 0);
1716 if (s == NULL)
1717 return NULL;
1718
1719 /* PyString_AS_STRING is used on encoding */
1720 s->encoding = PyObject_GetAttrString(ctx, "encoding");
1721 if (s->encoding == NULL)
1722 goto bail;
1723 if (s->encoding == Py_None) {
1724 Py_DECREF(Py_None);
1725 s->encoding = PyString_InternFromString(DEFAULT_ENCODING);
1726 }
1727 else if (PyUnicode_Check(s->encoding)) {
1728 PyObject *tmp = PyUnicode_AsEncodedString(s->encoding, NULL, NULL);
1729 Py_SETREF(s->encoding, tmp);
1730 }
1731 if (s->encoding == NULL)
1732 goto bail;
1733 if (!PyString_Check(s->encoding)) {
1734 PyErr_Format(PyExc_TypeError,
1735 "encoding must be a string, not %.80s",
1736 Py_TYPE(s->encoding)->tp_name);
1737 goto bail;
1738 }
1739
1740
1741 /* All of these will fail "gracefully" so we don't need to verify them */
1742 s->strict = PyObject_GetAttrString(ctx, "strict");
1743 if (s->strict == NULL)
1744 goto bail;
1745 s->object_hook = PyObject_GetAttrString(ctx, "object_hook");
1746 if (s->object_hook == NULL)
1747 goto bail;
1748 s->pairs_hook = PyObject_GetAttrString(ctx, "object_pairs_hook");
1749 if (s->pairs_hook == NULL)
1750 goto bail;
1751 s->parse_float = PyObject_GetAttrString(ctx, "parse_float");
1752 if (s->parse_float == NULL)
1753 goto bail;
1754 s->parse_int = PyObject_GetAttrString(ctx, "parse_int");
1755 if (s->parse_int == NULL)
1756 goto bail;
1757 s->parse_constant = PyObject_GetAttrString(ctx, "parse_constant");
1758 if (s->parse_constant == NULL)
1759 goto bail;
1760
1761 return (PyObject *)s;
1762
1763 bail:
1764 Py_DECREF(s);
1765 return NULL;
1766 }
1767
1768 PyDoc_STRVAR(scanner_doc, "JSON scanner object");
1769
1770 static
1771 PyTypeObject PyScannerType = {
1772 PyVarObject_HEAD_INIT(NULL, 0)
1773 "_json.Scanner", /* tp_name */
1774 sizeof(PyScannerObject), /* tp_basicsize */
1775 0, /* tp_itemsize */
1776 scanner_dealloc, /* tp_dealloc */
1777 0, /* tp_print */
1778 0, /* tp_getattr */
1779 0, /* tp_setattr */
1780 0, /* tp_compare */
1781 0, /* tp_repr */
1782 0, /* tp_as_number */
1783 0, /* tp_as_sequence */
1784 0, /* tp_as_mapping */
1785 0, /* tp_hash */
1786 scanner_call, /* tp_call */
1787 0, /* tp_str */
1788 0,/* PyObject_GenericGetAttr, */ /* tp_getattro */
1789 0,/* PyObject_GenericSetAttr, */ /* tp_setattro */
1790 0, /* tp_as_buffer */
1791 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
1792 scanner_doc, /* tp_doc */
1793 scanner_traverse, /* tp_traverse */
1794 scanner_clear, /* tp_clear */
1795 0, /* tp_richcompare */
1796 0, /* tp_weaklistoffset */
1797 0, /* tp_iter */
1798 0, /* tp_iternext */
1799 0, /* tp_methods */
1800 scanner_members, /* tp_members */
1801 0, /* tp_getset */
1802 0, /* tp_base */
1803 0, /* tp_dict */
1804 0, /* tp_descr_get */
1805 0, /* tp_descr_set */
1806 0, /* tp_dictoffset */
1807 0, /* tp_init */
1808 0,/* PyType_GenericAlloc, */ /* tp_alloc */
1809 scanner_new, /* tp_new */
1810 0,/* PyObject_GC_Del, */ /* tp_free */
1811 };
1812
1813 static PyObject *
1814 encoder_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1815 {
1816 static char *kwlist[] = {"markers", "default", "encoder", "indent", "key_separator", "item_separator", "sort_keys", "skipkeys", "allow_nan", NULL};
1817
1818 PyEncoderObject *s;
1819 PyObject *markers, *defaultfn, *encoder, *indent, *key_separator;
1820 PyObject *item_separator, *sort_keys, *skipkeys, *allow_nan_obj;
1821 int allow_nan;
1822
1823 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOOOOOOOO:make_encoder", kwlist,
1824 &markers, &defaultfn, &encoder, &indent, &key_separator, &item_separator,
1825 &sort_keys, &skipkeys, &allow_nan_obj))
1826 return NULL;
1827
1828 allow_nan = PyObject_IsTrue(allow_nan_obj);
1829 if (allow_nan < 0)
1830 return NULL;
1831
1832 if (markers != Py_None && !PyDict_Check(markers)) {
1833 PyErr_Format(PyExc_TypeError,
1834 "make_encoder() argument 1 must be dict or None, "
1835 "not %.200s", Py_TYPE(markers)->tp_name);
1836 return NULL;
1837 }
1838
1839 s = (PyEncoderObject *)type->tp_alloc(type, 0);
1840 if (s == NULL)
1841 return NULL;
1842
1843 s->markers = markers;
1844 s->defaultfn = defaultfn;
1845 s->encoder = encoder;
1846 s->indent = indent;
1847 s->key_separator = key_separator;
1848 s->item_separator = item_separator;
1849 s->sort_keys = sort_keys;
1850 s->skipkeys = skipkeys;
1851 s->fast_encode = (PyCFunction_Check(s->encoder) && PyCFunction_GetFunction(s->encoder) == (PyCFunction)py_encode_basestring_ascii);
1852 s->allow_nan = allow_nan;
1853
1854 Py_INCREF(s->markers);
1855 Py_INCREF(s->defaultfn);
1856 Py_INCREF(s->encoder);
1857 Py_INCREF(s->indent);
1858 Py_INCREF(s->key_separator);
1859 Py_INCREF(s->item_separator);
1860 Py_INCREF(s->sort_keys);
1861 Py_INCREF(s->skipkeys);
1862 return (PyObject *)s;
1863 }
1864
1865 static PyObject *
1866 encoder_call(PyObject *self, PyObject *args, PyObject *kwds)
1867 {
1868 /* Python callable interface to encode_listencode_obj */
1869 static char *kwlist[] = {"obj", "_current_indent_level", NULL};
1870 PyObject *obj;
1871 PyObject *rval;
1872 Py_ssize_t indent_level;
1873 PyEncoderObject *s;
1874 assert(PyEncoder_Check(self));
1875 s = (PyEncoderObject *)self;
1876 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO&:_iterencode", kwlist,
1877 &obj, _convertPyInt_AsSsize_t, &indent_level))
1878 return NULL;
1879 rval = PyList_New(0);
1880 if (rval == NULL)
1881 return NULL;
1882 if (encoder_listencode_obj(s, rval, obj, indent_level)) {
1883 Py_DECREF(rval);
1884 return NULL;
1885 }
1886 return rval;
1887 }
1888
1889 static PyObject *
1890 _encoded_const(PyObject *obj)
1891 {
1892 /* Return the JSON string representation of None, True, False */
1893 if (obj == Py_None) {
1894 static PyObject *s_null = NULL;
1895 if (s_null == NULL) {
1896 s_null = PyString_InternFromString("null");
1897 }
1898 Py_XINCREF(s_null);
1899 return s_null;
1900 }
1901 else if (obj == Py_True) {
1902 static PyObject *s_true = NULL;
1903 if (s_true == NULL) {
1904 s_true = PyString_InternFromString("true");
1905 }
1906 Py_XINCREF(s_true);
1907 return s_true;
1908 }
1909 else if (obj == Py_False) {
1910 static PyObject *s_false = NULL;
1911 if (s_false == NULL) {
1912 s_false = PyString_InternFromString("false");
1913 }
1914 Py_XINCREF(s_false);
1915 return s_false;
1916 }
1917 else {
1918 PyErr_SetString(PyExc_ValueError, "not a const");
1919 return NULL;
1920 }
1921 }
1922
1923 static PyObject *
1924 encoder_encode_float(PyEncoderObject *s, PyObject *obj)
1925 {
1926 /* Return the JSON representation of a PyFloat */
1927 double i = PyFloat_AS_DOUBLE(obj);
1928 if (!Py_IS_FINITE(i)) {
1929 if (!s->allow_nan) {
1930 PyErr_SetString(PyExc_ValueError, "Out of range float values are not JSON compliant");
1931 return NULL;
1932 }
1933 if (i > 0) {
1934 return PyString_FromString("Infinity");
1935 }
1936 else if (i < 0) {
1937 return PyString_FromString("-Infinity");
1938 }
1939 else {
1940 return PyString_FromString("NaN");
1941 }
1942 }
1943 /* Make sure to use the base float class repr method */
1944 return PyFloat_Type.tp_repr(obj);
1945 }
1946
1947 static PyObject *
1948 encoder_encode_string(PyEncoderObject *s, PyObject *obj)
1949 {
1950 /* Return the JSON representation of a string */
1951 if (s->fast_encode)
1952 return py_encode_basestring_ascii(NULL, obj);
1953 else
1954 return PyObject_CallFunctionObjArgs(s->encoder, obj, NULL);
1955 }
1956
1957 static int
1958 _steal_list_append(PyObject *lst, PyObject *stolen)
1959 {
1960 /* Append stolen and then decrement its reference count */
1961 int rval = PyList_Append(lst, stolen);
1962 Py_DECREF(stolen);
1963 return rval;
1964 }
1965
1966 static int
1967 encoder_listencode_obj(PyEncoderObject *s, PyObject *rval, PyObject *obj, Py_ssize_t indent_level)
1968 {
1969 /* Encode Python object obj to a JSON term, rval is a PyList */
1970 PyObject *newobj;
1971 int rv;
1972
1973 if (obj == Py_None || obj == Py_True || obj == Py_False) {
1974 PyObject *cstr = _encoded_const(obj);
1975 if (cstr == NULL)
1976 return -1;
1977 return _steal_list_append(rval, cstr);
1978 }
1979 else if (PyString_Check(obj) || PyUnicode_Check(obj))
1980 {
1981 PyObject *encoded = encoder_encode_string(s, obj);
1982 if (encoded == NULL)
1983 return -1;
1984 return _steal_list_append(rval, encoded);
1985 }
1986 else if (_PyAnyInt_Check(obj)) {
1987 PyObject *encoded = PyObject_Str(obj);
1988 if (encoded == NULL)
1989 return -1;
1990 return _steal_list_append(rval, encoded);
1991 }
1992 else if (PyFloat_Check(obj)) {
1993 PyObject *encoded = encoder_encode_float(s, obj);
1994 if (encoded == NULL)
1995 return -1;
1996 return _steal_list_append(rval, encoded);
1997 }
1998 else if (PyList_Check(obj) || PyTuple_Check(obj)) {
1999 if (Py_EnterRecursiveCall(" while encoding a JSON object"))
2000 return -1;
2001 rv = encoder_listencode_list(s, rval, obj, indent_level);
2002 Py_LeaveRecursiveCall();
2003 return rv;
2004 }
2005 else if (PyDict_Check(obj)) {
2006 if (Py_EnterRecursiveCall(" while encoding a JSON object"))
2007 return -1;
2008 rv = encoder_listencode_dict(s, rval, obj, indent_level);
2009 Py_LeaveRecursiveCall();
2010 return rv;
2011 }
2012 else {
2013 PyObject *ident = NULL;
2014 if (s->markers != Py_None) {
2015 int has_key;
2016 ident = PyLong_FromVoidPtr(obj);
2017 if (ident == NULL)
2018 return -1;
2019 has_key = PyDict_Contains(s->markers, ident);
2020 if (has_key) {
2021 if (has_key != -1)
2022 PyErr_SetString(PyExc_ValueError, "Circular reference detected");
2023 Py_DECREF(ident);
2024 return -1;
2025 }
2026 if (PyDict_SetItem(s->markers, ident, obj)) {
2027 Py_DECREF(ident);
2028 return -1;
2029 }
2030 }
2031 newobj = PyObject_CallFunctionObjArgs(s->defaultfn, obj, NULL);
2032 if (newobj == NULL) {
2033 Py_XDECREF(ident);
2034 return -1;
2035 }
2036
2037 if (Py_EnterRecursiveCall(" while encoding a JSON object")) {
2038 Py_DECREF(newobj);
2039 Py_XDECREF(ident);
2040 return -1;
2041 }
2042 rv = encoder_listencode_obj(s, rval, newobj, indent_level);
2043 Py_LeaveRecursiveCall();
2044
2045 Py_DECREF(newobj);
2046 if (rv) {
2047 Py_XDECREF(ident);
2048 return -1;
2049 }
2050 if (ident != NULL) {
2051 if (PyDict_DelItem(s->markers, ident)) {
2052 Py_XDECREF(ident);
2053 return -1;
2054 }
2055 Py_XDECREF(ident);
2056 }
2057 return rv;
2058 }
2059 }
2060
2061 static int
2062 encoder_listencode_dict(PyEncoderObject *s, PyObject *rval, PyObject *dct, Py_ssize_t indent_level)
2063 {
2064 /* Encode Python dict dct a JSON term, rval is a PyList */
2065 static PyObject *open_dict = NULL;
2066 static PyObject *close_dict = NULL;
2067 static PyObject *empty_dict = NULL;
2068 PyObject *kstr = NULL;
2069 PyObject *ident = NULL;
2070 PyObject *key = NULL;
2071 PyObject *value = NULL;
2072 PyObject *it = NULL;
2073 int skipkeys;
2074 Py_ssize_t idx;
2075
2076 if (open_dict == NULL || close_dict == NULL || empty_dict == NULL) {
2077 open_dict = PyString_InternFromString("{");
2078 close_dict = PyString_InternFromString("}");
2079 empty_dict = PyString_InternFromString("{}");
2080 if (open_dict == NULL || close_dict == NULL || empty_dict == NULL)
2081 return -1;
2082 }
2083 if (Py_SIZE(dct) == 0)
2084 return PyList_Append(rval, empty_dict);
2085
2086 if (s->markers != Py_None) {
2087 int has_key;
2088 ident = PyLong_FromVoidPtr(dct);
2089 if (ident == NULL)
2090 goto bail;
2091 has_key = PyDict_Contains(s->markers, ident);
2092 if (has_key) {
2093 if (has_key != -1)
2094 PyErr_SetString(PyExc_ValueError, "Circular reference detected");
2095 goto bail;
2096 }
2097 if (PyDict_SetItem(s->markers, ident, dct)) {
2098 goto bail;
2099 }
2100 }
2101
2102 if (PyList_Append(rval, open_dict))
2103 goto bail;
2104
2105 if (s->indent != Py_None) {
2106 /* TODO: DOES NOT RUN */
2107 indent_level += 1;
2108 /*
2109 newline_indent = '\n' + (' ' * (_indent * _current_indent_level))
2110 separator = _item_separator + newline_indent
2111 buf += newline_indent
2112 */
2113 }
2114
2115 /* TODO: C speedup not implemented for sort_keys */
2116
2117 it = PyObject_GetIter(dct);
2118 if (it == NULL)
2119 goto bail;
2120 skipkeys = PyObject_IsTrue(s->skipkeys);
2121 if (skipkeys < 0)
2122 goto bail;
2123 idx = 0;
2124 while ((key = PyIter_Next(it)) != NULL) {
2125 PyObject *encoded;
2126
2127 if (PyString_Check(key) || PyUnicode_Check(key)) {
2128 Py_INCREF(key);
2129 kstr = key;
2130 }
2131 else if (PyFloat_Check(key)) {
2132 kstr = encoder_encode_float(s, key);
2133 if (kstr == NULL)
2134 goto bail;
2135 }
2136 else if (_PyAnyInt_Check(key)) {
2137 kstr = PyObject_Str(key);
2138 if (kstr == NULL)
2139 goto bail;
2140 }
2141 else if (key == Py_True || key == Py_False || key == Py_None) {
2142 kstr = _encoded_const(key);
2143 if (kstr == NULL)
2144 goto bail;
2145 }
2146 else if (skipkeys) {
2147 Py_DECREF(key);
2148 continue;
2149 }
2150 else {
2151 /* TODO: include repr of key */
2152 PyErr_SetString(PyExc_TypeError, "keys must be a string");
2153 goto bail;
2154 }
2155
2156 if (idx) {
2157 if (PyList_Append(rval, s->item_separator))
2158 goto bail;
2159 }
2160
2161 value = PyObject_GetItem(dct, key);
2162 if (value == NULL)
2163 goto bail;
2164
2165 encoded = encoder_encode_string(s, kstr);
2166 Py_CLEAR(kstr);
2167 if (encoded == NULL)
2168 goto bail;
2169 if (PyList_Append(rval, encoded)) {
2170 Py_DECREF(encoded);
2171 goto bail;
2172 }
2173 Py_DECREF(encoded);
2174 if (PyList_Append(rval, s->key_separator))
2175 goto bail;
2176 if (encoder_listencode_obj(s, rval, value, indent_level))
2177 goto bail;
2178 idx += 1;
2179 Py_CLEAR(value);
2180 Py_DECREF(key);
2181 }
2182 if (PyErr_Occurred())
2183 goto bail;
2184 Py_CLEAR(it);
2185
2186 if (ident != NULL) {
2187 if (PyDict_DelItem(s->markers, ident))
2188 goto bail;
2189 Py_CLEAR(ident);
2190 }
2191 if (s->indent != Py_None) {
2192 /* TODO: DOES NOT RUN */
2193 /*
2194 indent_level -= 1;
2195
2196 yield '\n' + (' ' * (_indent * _current_indent_level))
2197 */
2198 }
2199 if (PyList_Append(rval, close_dict))
2200 goto bail;
2201 return 0;
2202
2203 bail:
2204 Py_XDECREF(it);
2205 Py_XDECREF(key);
2206 Py_XDECREF(value);
2207 Py_XDECREF(kstr);
2208 Py_XDECREF(ident);
2209 return -1;
2210 }
2211
2212
2213 static int
2214 encoder_listencode_list(PyEncoderObject *s, PyObject *rval, PyObject *seq, Py_ssize_t indent_level)
2215 {
2216 /* Encode Python list seq to a JSON term, rval is a PyList */
2217 static PyObject *open_array = NULL;
2218 static PyObject *close_array = NULL;
2219 static PyObject *empty_array = NULL;
2220 PyObject *ident = NULL;
2221 PyObject *s_fast = NULL;
2222 Py_ssize_t i;
2223
2224 if (open_array == NULL || close_array == NULL || empty_array == NULL) {
2225 open_array = PyString_InternFromString("[");
2226 close_array = PyString_InternFromString("]");
2227 empty_array = PyString_InternFromString("[]");
2228 if (open_array == NULL || close_array == NULL || empty_array == NULL)
2229 return -1;
2230 }
2231 ident = NULL;
2232 s_fast = PySequence_Fast(seq, "_iterencode_list needs a sequence");
2233 if (s_fast == NULL)
2234 return -1;
2235 if (PySequence_Fast_GET_SIZE(s_fast) == 0) {
2236 Py_DECREF(s_fast);
2237 return PyList_Append(rval, empty_array);
2238 }
2239
2240 if (s->markers != Py_None) {
2241 int has_key;
2242 ident = PyLong_FromVoidPtr(seq);
2243 if (ident == NULL)
2244 goto bail;
2245 has_key = PyDict_Contains(s->markers, ident);
2246 if (has_key) {
2247 if (has_key != -1)
2248 PyErr_SetString(PyExc_ValueError, "Circular reference detected");
2249 goto bail;
2250 }
2251 if (PyDict_SetItem(s->markers, ident, seq)) {
2252 goto bail;
2253 }
2254 }
2255
2256 if (PyList_Append(rval, open_array))
2257 goto bail;
2258 if (s->indent != Py_None) {
2259 /* TODO: DOES NOT RUN */
2260 indent_level += 1;
2261 /*
2262 newline_indent = '\n' + (' ' * (_indent * _current_indent_level))
2263 separator = _item_separator + newline_indent
2264 buf += newline_indent
2265 */
2266 }
2267 for (i = 0; i < PySequence_Fast_GET_SIZE(s_fast); i++) {
2268 PyObject *obj = PySequence_Fast_GET_ITEM(s_fast, i);
2269 if (i) {
2270 if (PyList_Append(rval, s->item_separator))
2271 goto bail;
2272 }
2273 if (encoder_listencode_obj(s, rval, obj, indent_level))
2274 goto bail;
2275 }
2276 if (ident != NULL) {
2277 if (PyDict_DelItem(s->markers, ident))
2278 goto bail;
2279 Py_CLEAR(ident);
2280 }
2281 if (s->indent != Py_None) {
2282 /* TODO: DOES NOT RUN */
2283 /*
2284 indent_level -= 1;
2285
2286 yield '\n' + (' ' * (_indent * _current_indent_level))
2287 */
2288 }
2289 if (PyList_Append(rval, close_array))
2290 goto bail;
2291 Py_DECREF(s_fast);
2292 return 0;
2293
2294 bail:
2295 Py_XDECREF(ident);
2296 Py_DECREF(s_fast);
2297 return -1;
2298 }
2299
2300 static void
2301 encoder_dealloc(PyObject *self)
2302 {
2303 /* bpo-31095: UnTrack is needed before calling any callbacks */
2304 PyObject_GC_UnTrack(self);
2305 encoder_clear(self);
2306 Py_TYPE(self)->tp_free(self);
2307 }
2308
2309 static int
2310 encoder_traverse(PyObject *self, visitproc visit, void *arg)
2311 {
2312 PyEncoderObject *s;
2313 assert(PyEncoder_Check(self));
2314 s = (PyEncoderObject *)self;
2315 Py_VISIT(s->markers);
2316 Py_VISIT(s->defaultfn);
2317 Py_VISIT(s->encoder);
2318 Py_VISIT(s->indent);
2319 Py_VISIT(s->key_separator);
2320 Py_VISIT(s->item_separator);
2321 Py_VISIT(s->sort_keys);
2322 Py_VISIT(s->skipkeys);
2323 return 0;
2324 }
2325
2326 static int
2327 encoder_clear(PyObject *self)
2328 {
2329 /* Deallocate Encoder */
2330 PyEncoderObject *s;
2331 assert(PyEncoder_Check(self));
2332 s = (PyEncoderObject *)self;
2333 Py_CLEAR(s->markers);
2334 Py_CLEAR(s->defaultfn);
2335 Py_CLEAR(s->encoder);
2336 Py_CLEAR(s->indent);
2337 Py_CLEAR(s->key_separator);
2338 Py_CLEAR(s->item_separator);
2339 Py_CLEAR(s->sort_keys);
2340 Py_CLEAR(s->skipkeys);
2341 return 0;
2342 }
2343
2344 PyDoc_STRVAR(encoder_doc, "_iterencode(obj, _current_indent_level) -> iterable");
2345
2346 static
2347 PyTypeObject PyEncoderType = {
2348 PyVarObject_HEAD_INIT(NULL, 0)
2349 "_json.Encoder", /* tp_name */
2350 sizeof(PyEncoderObject), /* tp_basicsize */
2351 0, /* tp_itemsize */
2352 encoder_dealloc, /* tp_dealloc */
2353 0, /* tp_print */
2354 0, /* tp_getattr */
2355 0, /* tp_setattr */
2356 0, /* tp_compare */
2357 0, /* tp_repr */
2358 0, /* tp_as_number */
2359 0, /* tp_as_sequence */
2360 0, /* tp_as_mapping */
2361 0, /* tp_hash */
2362 encoder_call, /* tp_call */
2363 0, /* tp_str */
2364 0, /* tp_getattro */
2365 0, /* tp_setattro */
2366 0, /* tp_as_buffer */
2367 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
2368 encoder_doc, /* tp_doc */
2369 encoder_traverse, /* tp_traverse */
2370 encoder_clear, /* tp_clear */
2371 0, /* tp_richcompare */
2372 0, /* tp_weaklistoffset */
2373 0, /* tp_iter */
2374 0, /* tp_iternext */
2375 0, /* tp_methods */
2376 encoder_members, /* tp_members */
2377 0, /* tp_getset */
2378 0, /* tp_base */
2379 0, /* tp_dict */
2380 0, /* tp_descr_get */
2381 0, /* tp_descr_set */
2382 0, /* tp_dictoffset */
2383 0, /* tp_init */
2384 0, /* tp_alloc */
2385 encoder_new, /* tp_new */
2386 0, /* tp_free */
2387 };
2388
2389 static PyMethodDef speedups_methods[] = {
2390 {"encode_basestring_ascii",
2391 (PyCFunction)py_encode_basestring_ascii,
2392 METH_O,
2393 pydoc_encode_basestring_ascii},
2394 {"scanstring",
2395 (PyCFunction)py_scanstring,
2396 METH_VARARGS,
2397 pydoc_scanstring},
2398 {NULL, NULL, 0, NULL}
2399 };
2400
2401 PyDoc_STRVAR(module_doc,
2402 "json speedups\n");
2403
2404 void
2405 init_json(void)
2406 {
2407 PyObject *m;
2408 if (PyType_Ready(&PyScannerType) < 0)
2409 return;
2410 if (PyType_Ready(&PyEncoderType) < 0)
2411 return;
2412 m = Py_InitModule3("_json", speedups_methods, module_doc);
2413 if (m == NULL)
2414 return;
2415 Py_INCREF((PyObject*)&PyScannerType);
2416 PyModule_AddObject(m, "make_scanner", (PyObject*)&PyScannerType);
2417 Py_INCREF((PyObject*)&PyEncoderType);
2418 PyModule_AddObject(m, "make_encoder", (PyObject*)&PyEncoderType);
2419 }