You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1891 lines
59 KiB

12 years ago
  1. #include "Python.h"
  2. #include "structmember.h"
  3. #include "accu.h"
  4. #ifdef __GNUC__
  5. #define UNUSED __attribute__((__unused__))
  6. #else
  7. #define UNUSED
  8. #endif
  9. #define PyScanner_Check(op) PyObject_TypeCheck(op, &PyScannerType)
  10. #define PyScanner_CheckExact(op) (Py_TYPE(op) == &PyScannerType)
  11. #define PyEncoder_Check(op) PyObject_TypeCheck(op, &PyEncoderType)
  12. #define PyEncoder_CheckExact(op) (Py_TYPE(op) == &PyEncoderType)
  13. static PyTypeObject PyScannerType;
  14. static PyTypeObject PyEncoderType;
  15. typedef struct _PyScannerObject {
  16. PyObject_HEAD
  17. PyObject *strict;
  18. PyObject *object_hook;
  19. PyObject *object_pairs_hook;
  20. PyObject *parse_float;
  21. PyObject *parse_int;
  22. PyObject *parse_constant;
  23. PyObject *memo;
  24. } PyScannerObject;
  25. static PyMemberDef scanner_members[] = {
  26. {"strict", T_OBJECT, offsetof(PyScannerObject, strict), READONLY, "strict"},
  27. {"object_hook", T_OBJECT, offsetof(PyScannerObject, object_hook), READONLY, "object_hook"},
  28. {"object_pairs_hook", T_OBJECT, offsetof(PyScannerObject, object_pairs_hook), READONLY},
  29. {"parse_float", T_OBJECT, offsetof(PyScannerObject, parse_float), READONLY, "parse_float"},
  30. {"parse_int", T_OBJECT, offsetof(PyScannerObject, parse_int), READONLY, "parse_int"},
  31. {"parse_constant", T_OBJECT, offsetof(PyScannerObject, parse_constant), READONLY, "parse_constant"},
  32. {NULL}
  33. };
  34. typedef struct _PyEncoderObject {
  35. PyObject_HEAD
  36. PyObject *markers;
  37. PyObject *defaultfn;
  38. PyObject *encoder;
  39. PyObject *indent;
  40. PyObject *key_separator;
  41. PyObject *item_separator;
  42. PyObject *sort_keys;
  43. PyObject *skipkeys;
  44. int fast_encode;
  45. int allow_nan;
  46. } PyEncoderObject;
  47. static PyMemberDef encoder_members[] = {
  48. {"markers", T_OBJECT, offsetof(PyEncoderObject, markers), READONLY, "markers"},
  49. {"default", T_OBJECT, offsetof(PyEncoderObject, defaultfn), READONLY, "default"},
  50. {"encoder", T_OBJECT, offsetof(PyEncoderObject, encoder), READONLY, "encoder"},
  51. {"indent", T_OBJECT, offsetof(PyEncoderObject, indent), READONLY, "indent"},
  52. {"key_separator", T_OBJECT, offsetof(PyEncoderObject, key_separator), READONLY, "key_separator"},
  53. {"item_separator", T_OBJECT, offsetof(PyEncoderObject, item_separator), READONLY, "item_separator"},
  54. {"sort_keys", T_OBJECT, offsetof(PyEncoderObject, sort_keys), READONLY, "sort_keys"},
  55. {"skipkeys", T_OBJECT, offsetof(PyEncoderObject, skipkeys), READONLY, "skipkeys"},
  56. {NULL}
  57. };
  58. static PyObject *
  59. join_list_unicode(PyObject *lst)
  60. {
  61. /* return u''.join(lst) */
  62. static PyObject *sep = NULL;
  63. if (sep == NULL) {
  64. sep = PyUnicode_FromStringAndSize("", 0);
  65. if (sep == NULL)
  66. return NULL;
  67. }
  68. return PyUnicode_Join(sep, lst);
  69. }
  70. /* Forward decls */
  71. static PyObject *
  72. ascii_escape_unicode(PyObject *pystr);
  73. static PyObject *
  74. py_encode_basestring_ascii(PyObject* self UNUSED, PyObject *pystr);
  75. void init_json(void);
  76. static PyObject *
  77. scan_once_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr);
  78. static PyObject *
  79. _build_rval_index_tuple(PyObject *rval, Py_ssize_t idx);
  80. static PyObject *
  81. scanner_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
  82. static int
  83. scanner_init(PyObject *self, PyObject *args, PyObject *kwds);
  84. static void
  85. scanner_dealloc(PyObject *self);
  86. static int
  87. scanner_clear(PyObject *self);
  88. static PyObject *
  89. encoder_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
  90. static int
  91. encoder_init(PyObject *self, PyObject *args, PyObject *kwds);
  92. static void
  93. encoder_dealloc(PyObject *self);
  94. static int
  95. encoder_clear(PyObject *self);
  96. static int
  97. encoder_listencode_list(PyEncoderObject *s, _PyAccu *acc, PyObject *seq, Py_ssize_t indent_level);
  98. static int
  99. encoder_listencode_obj(PyEncoderObject *s, _PyAccu *acc, PyObject *obj, Py_ssize_t indent_level);
  100. static int
  101. encoder_listencode_dict(PyEncoderObject *s, _PyAccu *acc, PyObject *dct, Py_ssize_t indent_level);
  102. static PyObject *
  103. _encoded_const(PyObject *obj);
  104. static void
  105. raise_errmsg(char *msg, PyObject *s, Py_ssize_t end);
  106. static PyObject *
  107. encoder_encode_string(PyEncoderObject *s, PyObject *obj);
  108. static PyObject *
  109. encoder_encode_long(PyEncoderObject* s UNUSED, PyObject *obj);
  110. static PyObject *
  111. encoder_encode_float(PyEncoderObject *s, PyObject *obj);
  112. #define S_CHAR(c) (c >= ' ' && c <= '~' && c != '\\' && c != '"')
  113. #define IS_WHITESPACE(c) (((c) == ' ') || ((c) == '\t') || ((c) == '\n') || ((c) == '\r'))
  114. static Py_ssize_t
  115. ascii_escape_unichar(Py_UCS4 c, unsigned char *output, Py_ssize_t chars)
  116. {
  117. /* Escape unicode code point c to ASCII escape sequences
  118. in char *output. output must have at least 12 bytes unused to
  119. accommodate an escaped surrogate pair "\uXXXX\uXXXX" */
  120. output[chars++] = '\\';
  121. switch (c) {
  122. case '\\': output[chars++] = c; break;
  123. case '"': output[chars++] = c; break;
  124. case '\b': output[chars++] = 'b'; break;
  125. case '\f': output[chars++] = 'f'; break;
  126. case '\n': output[chars++] = 'n'; break;
  127. case '\r': output[chars++] = 'r'; break;
  128. case '\t': output[chars++] = 't'; break;
  129. default:
  130. if (c >= 0x10000) {
  131. /* UTF-16 surrogate pair */
  132. Py_UCS4 v = Py_UNICODE_HIGH_SURROGATE(c);
  133. output[chars++] = 'u';
  134. output[chars++] = Py_hexdigits[(v >> 12) & 0xf];
  135. output[chars++] = Py_hexdigits[(v >> 8) & 0xf];
  136. output[chars++] = Py_hexdigits[(v >> 4) & 0xf];
  137. output[chars++] = Py_hexdigits[(v ) & 0xf];
  138. c = Py_UNICODE_LOW_SURROGATE(c);
  139. output[chars++] = '\\';
  140. }
  141. output[chars++] = 'u';
  142. output[chars++] = Py_hexdigits[(c >> 12) & 0xf];
  143. output[chars++] = Py_hexdigits[(c >> 8) & 0xf];
  144. output[chars++] = Py_hexdigits[(c >> 4) & 0xf];
  145. output[chars++] = Py_hexdigits[(c ) & 0xf];
  146. }
  147. return chars;
  148. }
  149. static PyObject *
  150. ascii_escape_unicode(PyObject *pystr)
  151. {
  152. /* Take a PyUnicode pystr and return a new ASCII-only escaped PyUnicode */
  153. Py_ssize_t i;
  154. Py_ssize_t input_chars;
  155. Py_ssize_t output_size;
  156. Py_ssize_t chars;
  157. PyObject *rval;
  158. void *input;
  159. unsigned char *output;
  160. int kind;
  161. if (PyUnicode_READY(pystr) == -1)
  162. return NULL;
  163. input_chars = PyUnicode_GET_LENGTH(pystr);
  164. input = PyUnicode_DATA(pystr);
  165. kind = PyUnicode_KIND(pystr);
  166. /* Compute the output size */
  167. for (i = 0, output_size = 2; i < input_chars; i++) {
  168. Py_UCS4 c = PyUnicode_READ(kind, input, i);
  169. if (S_CHAR(c))
  170. output_size++;
  171. else {
  172. switch(c) {
  173. case '\\': case '"': case '\b': case '\f':
  174. case '\n': case '\r': case '\t':
  175. output_size += 2; break;
  176. default:
  177. output_size += c >= 0x10000 ? 12 : 6;
  178. }
  179. }
  180. }
  181. rval = PyUnicode_New(output_size, 127);
  182. if (rval == NULL) {
  183. return NULL;
  184. }
  185. output = PyUnicode_1BYTE_DATA(rval);
  186. chars = 0;
  187. output[chars++] = '"';
  188. for (i = 0; i < input_chars; i++) {
  189. Py_UCS4 c = PyUnicode_READ(kind, input, i);
  190. if (S_CHAR(c)) {
  191. output[chars++] = c;
  192. }
  193. else {
  194. chars = ascii_escape_unichar(c, output, chars);
  195. }
  196. }
  197. output[chars++] = '"';
  198. #ifdef Py_DEBUG
  199. assert(_PyUnicode_CheckConsistency(rval, 1));
  200. #endif
  201. return rval;
  202. }
  203. static void
  204. raise_errmsg(char *msg, PyObject *s, Py_ssize_t end)
  205. {
  206. /* Use the Python function json.decoder.errmsg to raise a nice
  207. looking ValueError exception */
  208. static PyObject *errmsg_fn = NULL;
  209. PyObject *pymsg;
  210. if (errmsg_fn == NULL) {
  211. PyObject *decoder = PyImport_ImportModule("json.decoder");
  212. if (decoder == NULL)
  213. return;
  214. errmsg_fn = PyObject_GetAttrString(decoder, "errmsg");
  215. Py_DECREF(decoder);
  216. if (errmsg_fn == NULL)
  217. return;
  218. }
  219. pymsg = PyObject_CallFunction(errmsg_fn, "(zOn)", msg, s, end);
  220. if (pymsg) {
  221. PyErr_SetObject(PyExc_ValueError, pymsg);
  222. Py_DECREF(pymsg);
  223. }
  224. }
  225. static void
  226. raise_stop_iteration(Py_ssize_t idx)
  227. {
  228. PyObject *value = PyLong_FromSsize_t(idx);
  229. if (value != NULL) {
  230. PyErr_SetObject(PyExc_StopIteration, value);
  231. Py_DECREF(value);
  232. }
  233. }
  234. static PyObject *
  235. _build_rval_index_tuple(PyObject *rval, Py_ssize_t idx) {
  236. /* return (rval, idx) tuple, stealing reference to rval */
  237. PyObject *tpl;
  238. PyObject *pyidx;
  239. /*
  240. steal a reference to rval, returns (rval, idx)
  241. */
  242. if (rval == NULL) {
  243. return NULL;
  244. }
  245. pyidx = PyLong_FromSsize_t(idx);
  246. if (pyidx == NULL) {
  247. Py_DECREF(rval);
  248. return NULL;
  249. }
  250. tpl = PyTuple_New(2);
  251. if (tpl == NULL) {
  252. Py_DECREF(pyidx);
  253. Py_DECREF(rval);
  254. return NULL;
  255. }
  256. PyTuple_SET_ITEM(tpl, 0, rval);
  257. PyTuple_SET_ITEM(tpl, 1, pyidx);
  258. return tpl;
  259. }
  260. #define APPEND_OLD_CHUNK \
  261. if (chunk != NULL) { \
  262. if (chunks == NULL) { \
  263. chunks = PyList_New(0); \
  264. if (chunks == NULL) { \
  265. goto bail; \
  266. } \
  267. } \
  268. if (PyList_Append(chunks, chunk)) { \
  269. Py_CLEAR(chunk); \
  270. goto bail; \
  271. } \
  272. Py_CLEAR(chunk); \
  273. }
  274. static PyObject *
  275. scanstring_unicode(PyObject *pystr, Py_ssize_t end, int strict, Py_ssize_t *next_end_ptr)
  276. {
  277. /* Read the JSON string from PyUnicode pystr.
  278. end is the index of the first character after the quote.
  279. if strict is zero then literal control characters are allowed
  280. *next_end_ptr is a return-by-reference index of the character
  281. after the end quote
  282. Return value is a new PyUnicode
  283. */
  284. PyObject *rval = NULL;
  285. Py_ssize_t len;
  286. Py_ssize_t begin = end - 1;
  287. Py_ssize_t next /* = begin */;
  288. const void *buf;
  289. int kind;
  290. PyObject *chunks = NULL;
  291. PyObject *chunk = NULL;
  292. if (PyUnicode_READY(pystr) == -1)
  293. return 0;
  294. len = PyUnicode_GET_LENGTH(pystr);
  295. buf = PyUnicode_DATA(pystr);
  296. kind = PyUnicode_KIND(pystr);
  297. if (end < 0 || len < end) {
  298. PyErr_SetString(PyExc_ValueError, "end is out of bounds");
  299. goto bail;
  300. }
  301. while (1) {
  302. /* Find the end of the string or the next escape */
  303. Py_UCS4 c = 0;
  304. for (next = end; next < len; next++) {
  305. c = PyUnicode_READ(kind, buf, next);
  306. if (c == '"' || c == '\\') {
  307. break;
  308. }
  309. else if (strict && c <= 0x1f) {
  310. raise_errmsg("Invalid control character at", pystr, next);
  311. goto bail;
  312. }
  313. }
  314. if (!(c == '"' || c == '\\')) {
  315. raise_errmsg("Unterminated string starting at", pystr, begin);
  316. goto bail;
  317. }
  318. /* Pick up this chunk if it's not zero length */
  319. if (next != end) {
  320. APPEND_OLD_CHUNK
  321. chunk = PyUnicode_FromKindAndData(
  322. kind,
  323. (char*)buf + kind * end,
  324. next - end);
  325. if (chunk == NULL) {
  326. goto bail;
  327. }
  328. }
  329. next++;
  330. if (c == '"') {
  331. end = next;
  332. break;
  333. }
  334. if (next == len) {
  335. raise_errmsg("Unterminated string starting at", pystr, begin);
  336. goto bail;
  337. }
  338. c = PyUnicode_READ(kind, buf, next);
  339. if (c != 'u') {
  340. /* Non-unicode backslash escapes */
  341. end = next + 1;
  342. switch (c) {
  343. case '"': break;
  344. case '\\': break;
  345. case '/': break;
  346. case 'b': c = '\b'; break;
  347. case 'f': c = '\f'; break;
  348. case 'n': c = '\n'; break;
  349. case 'r': c = '\r'; break;
  350. case 't': c = '\t'; break;
  351. default: c = 0;
  352. }
  353. if (c == 0) {
  354. raise_errmsg("Invalid \\escape", pystr, end - 2);
  355. goto bail;
  356. }
  357. }
  358. else {
  359. c = 0;
  360. next++;
  361. end = next + 4;
  362. if (end >= len) {
  363. raise_errmsg("Invalid \\uXXXX escape", pystr, next - 1);
  364. goto bail;
  365. }
  366. /* Decode 4 hex digits */
  367. for (; next < end; next++) {
  368. Py_UCS4 digit = PyUnicode_READ(kind, buf, next);
  369. c <<= 4;
  370. switch (digit) {
  371. case '0': case '1': case '2': case '3': case '4':
  372. case '5': case '6': case '7': case '8': case '9':
  373. c |= (digit - '0'); break;
  374. case 'a': case 'b': case 'c': case 'd': case 'e':
  375. case 'f':
  376. c |= (digit - 'a' + 10); break;
  377. case 'A': case 'B': case 'C': case 'D': case 'E':
  378. case 'F':
  379. c |= (digit - 'A' + 10); break;
  380. default:
  381. raise_errmsg("Invalid \\uXXXX escape", pystr, end - 5);
  382. goto bail;
  383. }
  384. }
  385. /* Surrogate pair */
  386. if (Py_UNICODE_IS_HIGH_SURROGATE(c) && end + 6 < len &&
  387. PyUnicode_READ(kind, buf, next++) == '\\' &&
  388. PyUnicode_READ(kind, buf, next++) == 'u') {
  389. Py_UCS4 c2 = 0;
  390. end += 6;
  391. /* Decode 4 hex digits */
  392. for (; next < end; next++) {
  393. Py_UCS4 digit = PyUnicode_READ(kind, buf, next);
  394. c2 <<= 4;
  395. switch (digit) {
  396. case '0': case '1': case '2': case '3': case '4':
  397. case '5': case '6': case '7': case '8': case '9':
  398. c2 |= (digit - '0'); break;
  399. case 'a': case 'b': case 'c': case 'd': case 'e':
  400. case 'f':
  401. c2 |= (digit - 'a' + 10); break;
  402. case 'A': case 'B': case 'C': case 'D': case 'E':
  403. case 'F':
  404. c2 |= (digit - 'A' + 10); break;
  405. default:
  406. raise_errmsg("Invalid \\uXXXX escape", pystr, end - 5);
  407. goto bail;
  408. }
  409. }
  410. if (Py_UNICODE_IS_LOW_SURROGATE(c2))
  411. c = Py_UNICODE_JOIN_SURROGATES(c, c2);
  412. else
  413. end -= 6;
  414. }
  415. }
  416. APPEND_OLD_CHUNK
  417. chunk = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, &c, 1);
  418. if (chunk == NULL) {
  419. goto bail;
  420. }
  421. }
  422. if (chunks == NULL) {
  423. if (chunk != NULL)
  424. rval = chunk;
  425. else
  426. rval = PyUnicode_FromStringAndSize("", 0);
  427. }
  428. else {
  429. APPEND_OLD_CHUNK
  430. rval = join_list_unicode(chunks);
  431. if (rval == NULL) {
  432. goto bail;
  433. }
  434. Py_CLEAR(chunks);
  435. }
  436. *next_end_ptr = end;
  437. return rval;
  438. bail:
  439. *next_end_ptr = -1;
  440. Py_XDECREF(chunks);
  441. Py_XDECREF(chunk);
  442. return NULL;
  443. }
  444. PyDoc_STRVAR(pydoc_scanstring,
  445. "scanstring(string, end, strict=True) -> (string, end)\n"
  446. "\n"
  447. "Scan the string s for a JSON string. End is the index of the\n"
  448. "character in s after the quote that started the JSON string.\n"
  449. "Unescapes all valid JSON string escape sequences and raises ValueError\n"
  450. "on attempt to decode an invalid string. If strict is False then literal\n"
  451. "control characters are allowed in the string.\n"
  452. "\n"
  453. "Returns a tuple of the decoded string and the index of the character in s\n"
  454. "after the end quote."
  455. );
  456. static PyObject *
  457. py_scanstring(PyObject* self UNUSED, PyObject *args)
  458. {
  459. PyObject *pystr;
  460. PyObject *rval;
  461. Py_ssize_t end;
  462. Py_ssize_t next_end = -1;
  463. int strict = 1;
  464. if (!PyArg_ParseTuple(args, "On|i:scanstring", &pystr, &end, &strict)) {
  465. return NULL;
  466. }
  467. if (PyUnicode_Check(pystr)) {
  468. rval = scanstring_unicode(pystr, end, strict, &next_end);
  469. }
  470. else {
  471. PyErr_Format(PyExc_TypeError,
  472. "first argument must be a string, not %.80s",
  473. Py_TYPE(pystr)->tp_name);
  474. return NULL;
  475. }
  476. return _build_rval_index_tuple(rval, next_end);
  477. }
  478. PyDoc_STRVAR(pydoc_encode_basestring_ascii,
  479. "encode_basestring_ascii(string) -> string\n"
  480. "\n"
  481. "Return an ASCII-only JSON representation of a Python string"
  482. );
  483. static PyObject *
  484. py_encode_basestring_ascii(PyObject* self UNUSED, PyObject *pystr)
  485. {
  486. PyObject *rval;
  487. /* Return an ASCII-only JSON representation of a Python string */
  488. /* METH_O */
  489. if (PyUnicode_Check(pystr)) {
  490. rval = ascii_escape_unicode(pystr);
  491. }
  492. else {
  493. PyErr_Format(PyExc_TypeError,
  494. "first argument must be a string, not %.80s",
  495. Py_TYPE(pystr)->tp_name);
  496. return NULL;
  497. }
  498. return rval;
  499. }
  500. static void
  501. scanner_dealloc(PyObject *self)
  502. {
  503. /* Deallocate scanner object */
  504. scanner_clear(self);
  505. Py_TYPE(self)->tp_free(self);
  506. }
  507. static int
  508. scanner_traverse(PyObject *self, visitproc visit, void *arg)
  509. {
  510. PyScannerObject *s;
  511. assert(PyScanner_Check(self));
  512. s = (PyScannerObject *)self;
  513. Py_VISIT(s->strict);
  514. Py_VISIT(s->object_hook);
  515. Py_VISIT(s->object_pairs_hook);
  516. Py_VISIT(s->parse_float);
  517. Py_VISIT(s->parse_int);
  518. Py_VISIT(s->parse_constant);
  519. return 0;
  520. }
  521. static int
  522. scanner_clear(PyObject *self)
  523. {
  524. PyScannerObject *s;
  525. assert(PyScanner_Check(self));
  526. s = (PyScannerObject *)self;
  527. Py_CLEAR(s->strict);
  528. Py_CLEAR(s->object_hook);
  529. Py_CLEAR(s->object_pairs_hook);
  530. Py_CLEAR(s->parse_float);
  531. Py_CLEAR(s->parse_int);
  532. Py_CLEAR(s->parse_constant);
  533. Py_CLEAR(s->memo);
  534. return 0;
  535. }
  536. static PyObject *
  537. _parse_object_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) {
  538. /* Read a JSON object from PyUnicode pystr.
  539. idx is the index of the first character after the opening curly brace.
  540. *next_idx_ptr is a return-by-reference index to the first character after
  541. the closing curly brace.
  542. Returns a new PyObject (usually a dict, but object_hook can change that)
  543. */
  544. void *str;
  545. int kind;
  546. Py_ssize_t end_idx;
  547. PyObject *val = NULL;
  548. PyObject *rval = NULL;
  549. PyObject *key = NULL;
  550. int strict = PyObject_IsTrue(s->strict);
  551. int has_pairs_hook = (s->object_pairs_hook != Py_None);
  552. Py_ssize_t next_idx;
  553. if (PyUnicode_READY(pystr) == -1)
  554. return NULL;
  555. str = PyUnicode_DATA(pystr);
  556. kind = PyUnicode_KIND(pystr);
  557. end_idx = PyUnicode_GET_LENGTH(pystr) - 1;
  558. if (has_pairs_hook)
  559. rval = PyList_New(0);
  560. else
  561. rval = PyDict_New();
  562. if (rval == NULL)
  563. return NULL;
  564. /* skip whitespace after { */
  565. while (idx <= end_idx && IS_WHITESPACE(PyUnicode_READ(kind,str, idx))) idx++;
  566. /* only loop if the object is non-empty */
  567. if (idx > end_idx || PyUnicode_READ(kind, str, idx) != '}') {
  568. while (1) {
  569. PyObject *memokey;
  570. /* read key */
  571. if (idx > end_idx || PyUnicode_READ(kind, str, idx) != '"') {
  572. raise_errmsg("Expecting property name enclosed in double quotes", pystr, idx);
  573. goto bail;
  574. }
  575. key = scanstring_unicode(pystr, idx + 1, strict, &next_idx);
  576. if (key == NULL)
  577. goto bail;
  578. memokey = PyDict_GetItem(s->memo, key);
  579. if (memokey != NULL) {
  580. Py_INCREF(memokey);
  581. Py_DECREF(key);
  582. key = memokey;
  583. }
  584. else {
  585. if (PyDict_SetItem(s->memo, key, key) < 0)
  586. goto bail;
  587. }
  588. idx = next_idx;
  589. /* skip whitespace between key and : delimiter, read :, skip whitespace */
  590. while (idx <= end_idx && IS_WHITESPACE(PyUnicode_READ(kind, str, idx))) idx++;
  591. if (idx > end_idx || PyUnicode_READ(kind, str, idx) != ':') {
  592. raise_errmsg("Expecting ':' delimiter", pystr, idx);
  593. goto bail;
  594. }
  595. idx++;
  596. while (idx <= end_idx && IS_WHITESPACE(PyUnicode_READ(kind, str, idx))) idx++;
  597. /* read any JSON term */
  598. val = scan_once_unicode(s, pystr, idx, &next_idx);
  599. if (val == NULL)
  600. goto bail;
  601. if (has_pairs_hook) {
  602. PyObject *item = PyTuple_Pack(2, key, val);
  603. if (item == NULL)
  604. goto bail;
  605. Py_CLEAR(key);
  606. Py_CLEAR(val);
  607. if (PyList_Append(rval, item) == -1) {
  608. Py_DECREF(item);
  609. goto bail;
  610. }
  611. Py_DECREF(item);
  612. }
  613. else {
  614. if (PyDict_SetItem(rval, key, val) < 0)
  615. goto bail;
  616. Py_CLEAR(key);
  617. Py_CLEAR(val);
  618. }
  619. idx = next_idx;
  620. /* skip whitespace before } or , */
  621. while (idx <= end_idx && IS_WHITESPACE(PyUnicode_READ(kind, str, idx))) idx++;
  622. /* bail if the object is closed or we didn't get the , delimiter */
  623. if (idx <= end_idx && PyUnicode_READ(kind, str, idx) == '}')
  624. break;
  625. if (idx > end_idx || PyUnicode_READ(kind, str, idx) != ',') {
  626. raise_errmsg("Expecting ',' delimiter", pystr, idx);
  627. goto bail;
  628. }
  629. idx++;
  630. /* skip whitespace after , delimiter */
  631. while (idx <= end_idx && IS_WHITESPACE(PyUnicode_READ(kind, str, idx))) idx++;
  632. }
  633. }
  634. *next_idx_ptr = idx + 1;
  635. if (has_pairs_hook) {
  636. val = PyObject_CallFunctionObjArgs(s->object_pairs_hook, rval, NULL);
  637. Py_DECREF(rval);
  638. return val;
  639. }
  640. /* if object_hook is not None: rval = object_hook(rval) */
  641. if (s->object_hook != Py_None) {
  642. val = PyObject_CallFunctionObjArgs(s->object_hook, rval, NULL);
  643. Py_DECREF(rval);
  644. return val;
  645. }
  646. return rval;
  647. bail:
  648. Py_XDECREF(key);
  649. Py_XDECREF(val);
  650. Py_XDECREF(rval);
  651. return NULL;
  652. }
  653. static PyObject *
  654. _parse_array_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) {
  655. /* Read a JSON array from PyString pystr.
  656. idx is the index of the first character after the opening brace.
  657. *next_idx_ptr is a return-by-reference index to the first character after
  658. the closing brace.
  659. Returns a new PyList
  660. */
  661. void *str;
  662. int kind;
  663. Py_ssize_t end_idx;
  664. PyObject *val = NULL;
  665. PyObject *rval = PyList_New(0);
  666. Py_ssize_t next_idx;
  667. if (rval == NULL)
  668. return NULL;
  669. if (PyUnicode_READY(pystr) == -1)
  670. return NULL;
  671. str = PyUnicode_DATA(pystr);
  672. kind = PyUnicode_KIND(pystr);
  673. end_idx = PyUnicode_GET_LENGTH(pystr) - 1;
  674. /* skip whitespace after [ */
  675. while (idx <= end_idx && IS_WHITESPACE(PyUnicode_READ(kind, str, idx))) idx++;
  676. /* only loop if the array is non-empty */
  677. if (idx > end_idx || PyUnicode_READ(kind, str, idx) != ']') {
  678. while (1) {
  679. /* read any JSON term */
  680. val = scan_once_unicode(s, pystr, idx, &next_idx);
  681. if (val == NULL)
  682. goto bail;
  683. if (PyList_Append(rval, val) == -1)
  684. goto bail;
  685. Py_CLEAR(val);
  686. idx = next_idx;
  687. /* skip whitespace between term and , */
  688. while (idx <= end_idx && IS_WHITESPACE(PyUnicode_READ(kind, str, idx))) idx++;
  689. /* bail if the array is closed or we didn't get the , delimiter */
  690. if (idx <= end_idx && PyUnicode_READ(kind, str, idx) == ']')
  691. break;
  692. if (idx > end_idx || PyUnicode_READ(kind, str, idx) != ',') {
  693. raise_errmsg("Expecting ',' delimiter", pystr, idx);
  694. goto bail;
  695. }
  696. idx++;
  697. /* skip whitespace after , */
  698. while (idx <= end_idx && IS_WHITESPACE(PyUnicode_READ(kind, str, idx))) idx++;
  699. }
  700. }
  701. /* verify that idx < end_idx, PyUnicode_READ(kind, str, idx) should be ']' */
  702. if (idx > end_idx || PyUnicode_READ(kind, str, idx) != ']') {
  703. raise_errmsg("Expecting value", pystr, end_idx);
  704. goto bail;
  705. }
  706. *next_idx_ptr = idx + 1;
  707. return rval;
  708. bail:
  709. Py_XDECREF(val);
  710. Py_DECREF(rval);
  711. return NULL;
  712. }
  713. static PyObject *
  714. _parse_constant(PyScannerObject *s, char *constant, Py_ssize_t idx, Py_ssize_t *next_idx_ptr) {
  715. /* Read a JSON constant from PyString pystr.
  716. constant is the constant string that was found
  717. ("NaN", "Infinity", "-Infinity").
  718. idx is the index of the first character of the constant
  719. *next_idx_ptr is a return-by-reference index to the first character after
  720. the constant.
  721. Returns the result of parse_constant
  722. */
  723. PyObject *cstr;
  724. PyObject *rval;
  725. /* constant is "NaN", "Infinity", or "-Infinity" */
  726. cstr = PyUnicode_InternFromString(constant);
  727. if (cstr == NULL)
  728. return NULL;
  729. /* rval = parse_constant(constant) */
  730. rval = PyObject_CallFunctionObjArgs(s->parse_constant, cstr, NULL);
  731. idx += PyUnicode_GET_LENGTH(cstr);
  732. Py_DECREF(cstr);
  733. *next_idx_ptr = idx;
  734. return rval;
  735. }
  736. static PyObject *
  737. _match_number_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t start, Py_ssize_t *next_idx_ptr) {
  738. /* Read a JSON number from PyUnicode pystr.
  739. idx is the index of the first character of the number
  740. *next_idx_ptr is a return-by-reference index to the first character after
  741. the number.
  742. Returns a new PyObject representation of that number:
  743. PyInt, PyLong, or PyFloat.
  744. May return other types if parse_int or parse_float are set
  745. */
  746. void *str;
  747. int kind;
  748. Py_ssize_t end_idx;
  749. Py_ssize_t idx = start;
  750. int is_float = 0;
  751. PyObject *rval;
  752. PyObject *numstr = NULL;
  753. PyObject *custom_func;
  754. if (PyUnicode_READY(pystr) == -1)
  755. return NULL;
  756. str = PyUnicode_DATA(pystr);
  757. kind = PyUnicode_KIND(pystr);
  758. end_idx = PyUnicode_GET_LENGTH(pystr) - 1;
  759. /* read a sign if it's there, make sure it's not the end of the string */
  760. if (PyUnicode_READ(kind, str, idx) == '-') {
  761. idx++;
  762. if (idx > end_idx) {
  763. raise_stop_iteration(start);
  764. return NULL;
  765. }
  766. }
  767. /* read as many integer digits as we find as long as it doesn't start with 0 */
  768. if (PyUnicode_READ(kind, str, idx) >= '1' && PyUnicode_READ(kind, str, idx) <= '9') {
  769. idx++;
  770. while (idx <= end_idx && PyUnicode_READ(kind, str, idx) >= '0' && PyUnicode_READ(kind, str, idx) <= '9') idx++;
  771. }
  772. /* if it starts with 0 we only expect one integer digit */
  773. else if (PyUnicode_READ(kind, str, idx) == '0') {
  774. idx++;
  775. }
  776. /* no integer digits, error */
  777. else {
  778. raise_stop_iteration(start);
  779. return NULL;
  780. }
  781. /* if the next char is '.' followed by a digit then read all float digits */
  782. if (idx < end_idx && PyUnicode_READ(kind, str, idx) == '.' && PyUnicode_READ(kind, str, idx + 1) >= '0' && PyUnicode_READ(kind, str, idx + 1) <= '9') {
  783. is_float = 1;
  784. idx += 2;
  785. while (idx <= end_idx && PyUnicode_READ(kind, str, idx) >= '0' && PyUnicode_READ(kind, str, idx) <= '9') idx++;
  786. }
  787. /* if the next char is 'e' or 'E' then maybe read the exponent (or backtrack) */
  788. if (idx < end_idx && (PyUnicode_READ(kind, str, idx) == 'e' || PyUnicode_READ(kind, str, idx) == 'E')) {
  789. Py_ssize_t e_start = idx;
  790. idx++;
  791. /* read an exponent sign if present */
  792. if (idx < end_idx && (PyUnicode_READ(kind, str, idx) == '-' || PyUnicode_READ(kind, str, idx) == '+')) idx++;
  793. /* read all digits */
  794. while (idx <= end_idx && PyUnicode_READ(kind, str, idx) >= '0' && PyUnicode_READ(kind, str, idx) <= '9') idx++;
  795. /* if we got a digit, then parse as float. if not, backtrack */
  796. if (PyUnicode_READ(kind, str, idx - 1) >= '0' && PyUnicode_READ(kind, str, idx - 1) <= '9') {
  797. is_float = 1;
  798. }
  799. else {
  800. idx = e_start;
  801. }
  802. }
  803. if (is_float && s->parse_float != (PyObject *)&PyFloat_Type)
  804. custom_func = s->parse_float;
  805. else if (!is_float && s->parse_int != (PyObject *) &PyLong_Type)
  806. custom_func = s->parse_int;
  807. else
  808. custom_func = NULL;
  809. if (custom_func) {
  810. /* copy the section we determined to be a number */
  811. numstr = PyUnicode_FromKindAndData(kind,
  812. (char*)str + kind * start,
  813. idx - start);
  814. if (numstr == NULL)
  815. return NULL;
  816. rval = PyObject_CallFunctionObjArgs(custom_func, numstr, NULL);
  817. }
  818. else {
  819. Py_ssize_t i, n;
  820. char *buf;
  821. /* Straight conversion to ASCII, to avoid costly conversion of
  822. decimal unicode digits (which cannot appear here) */
  823. n = idx - start;
  824. numstr = PyBytes_FromStringAndSize(NULL, n);
  825. if (numstr == NULL)
  826. return NULL;
  827. buf = PyBytes_AS_STRING(numstr);
  828. for (i = 0; i < n; i++) {
  829. buf[i] = (char) PyUnicode_READ(kind, str, i + start);
  830. }
  831. if (is_float)
  832. rval = PyFloat_FromString(numstr);
  833. else
  834. rval = PyLong_FromString(buf, NULL, 10);
  835. }
  836. Py_DECREF(numstr);
  837. *next_idx_ptr = idx;
  838. return rval;
  839. }
  840. static PyObject *
  841. scan_once_unicode(PyScannerObject *s, PyObject *pystr, Py_ssize_t idx, Py_ssize_t *next_idx_ptr)
  842. {
  843. /* Read one JSON term (of any kind) from PyUnicode pystr.
  844. idx is the index of the first character of the term
  845. *next_idx_ptr is a return-by-reference index to the first character after
  846. the number.
  847. Returns a new PyObject representation of the term.
  848. */
  849. PyObject *res;
  850. void *str;
  851. int kind;
  852. Py_ssize_t length;
  853. if (PyUnicode_READY(pystr) == -1)
  854. return NULL;
  855. str = PyUnicode_DATA(pystr);
  856. kind = PyUnicode_KIND(pystr);
  857. length = PyUnicode_GET_LENGTH(pystr);
  858. if (idx < 0) {
  859. PyErr_SetString(PyExc_ValueError, "idx cannot be negative");
  860. return NULL;
  861. }
  862. if (idx >= length) {
  863. raise_stop_iteration(idx);
  864. return NULL;
  865. }
  866. switch (PyUnicode_READ(kind, str, idx)) {
  867. case '"':
  868. /* string */
  869. return scanstring_unicode(pystr, idx + 1,
  870. PyObject_IsTrue(s->strict),
  871. next_idx_ptr);
  872. case '{':
  873. /* object */
  874. if (Py_EnterRecursiveCall(" while decoding a JSON object "
  875. "from a unicode string"))
  876. return NULL;
  877. res = _parse_object_unicode(s, pystr, idx + 1, next_idx_ptr);
  878. Py_LeaveRecursiveCall();
  879. return res;
  880. case '[':
  881. /* array */
  882. if (Py_EnterRecursiveCall(" while decoding a JSON array "
  883. "from a unicode string"))
  884. return NULL;
  885. res = _parse_array_unicode(s, pystr, idx + 1, next_idx_ptr);
  886. Py_LeaveRecursiveCall();
  887. return res;
  888. case 'n':
  889. /* null */
  890. if ((idx + 3 < length) && PyUnicode_READ(kind, str, idx + 1) == 'u' && PyUnicode_READ(kind, str, idx + 2) == 'l' && PyUnicode_READ(kind, str, idx + 3) == 'l') {
  891. Py_INCREF(Py_None);
  892. *next_idx_ptr = idx + 4;
  893. return Py_None;
  894. }
  895. break;
  896. case 't':
  897. /* true */
  898. if ((idx + 3 < length) && PyUnicode_READ(kind, str, idx + 1) == 'r' && PyUnicode_READ(kind, str, idx + 2) == 'u' && PyUnicode_READ(kind, str, idx + 3) == 'e') {
  899. Py_INCREF(Py_True);
  900. *next_idx_ptr = idx + 4;
  901. return Py_True;
  902. }
  903. break;
  904. case 'f':
  905. /* false */
  906. if ((idx + 4 < length) && PyUnicode_READ(kind, str, idx + 1) == 'a' &&
  907. PyUnicode_READ(kind, str, idx + 2) == 'l' &&
  908. PyUnicode_READ(kind, str, idx + 3) == 's' &&
  909. PyUnicode_READ(kind, str, idx + 4) == 'e') {
  910. Py_INCREF(Py_False);
  911. *next_idx_ptr = idx + 5;
  912. return Py_False;
  913. }
  914. break;
  915. case 'N':
  916. /* NaN */
  917. if ((idx + 2 < length) && PyUnicode_READ(kind, str, idx + 1) == 'a' &&
  918. PyUnicode_READ(kind, str, idx + 2) == 'N') {
  919. return _parse_constant(s, "NaN", idx, next_idx_ptr);
  920. }
  921. break;
  922. case 'I':
  923. /* Infinity */
  924. if ((idx + 7 < length) && PyUnicode_READ(kind, str, idx + 1) == 'n' &&
  925. PyUnicode_READ(kind, str, idx + 2) == 'f' &&
  926. PyUnicode_READ(kind, str, idx + 3) == 'i' &&
  927. PyUnicode_READ(kind, str, idx + 4) == 'n' &&
  928. PyUnicode_READ(kind, str, idx + 5) == 'i' &&
  929. PyUnicode_READ(kind, str, idx + 6) == 't' &&
  930. PyUnicode_READ(kind, str, idx + 7) == 'y') {
  931. return _parse_constant(s, "Infinity", idx, next_idx_ptr);
  932. }
  933. break;
  934. case '-':
  935. /* -Infinity */
  936. if ((idx + 8 < length) && PyUnicode_READ(kind, str, idx + 1) == 'I' &&
  937. PyUnicode_READ(kind, str, idx + 2) == 'n' &&
  938. PyUnicode_READ(kind, str, idx + 3) == 'f' &&
  939. PyUnicode_READ(kind, str, idx + 4) == 'i' &&
  940. PyUnicode_READ(kind, str, idx + 5) == 'n' &&
  941. PyUnicode_READ(kind, str, idx + 6) == 'i' &&
  942. PyUnicode_READ(kind, str, idx + 7) == 't' &&
  943. PyUnicode_READ(kind, str, idx + 8) == 'y') {
  944. return _parse_constant(s, "-Infinity", idx, next_idx_ptr);
  945. }
  946. break;
  947. }
  948. /* Didn't find a string, object, array, or named constant. Look for a number. */
  949. return _match_number_unicode(s, pystr, idx, next_idx_ptr);
  950. }
  951. static PyObject *
  952. scanner_call(PyObject *self, PyObject *args, PyObject *kwds)
  953. {
  954. /* Python callable interface to scan_once_{str,unicode} */
  955. PyObject *pystr;
  956. PyObject *rval;
  957. Py_ssize_t idx;
  958. Py_ssize_t next_idx = -1;
  959. static char *kwlist[] = {"string", "idx", NULL};
  960. PyScannerObject *s;
  961. assert(PyScanner_Check(self));
  962. s = (PyScannerObject *)self;
  963. if (!PyArg_ParseTupleAndKeywords(args, kwds, "On:scan_once", kwlist, &pystr, &idx))
  964. return NULL;
  965. if (PyUnicode_Check(pystr)) {
  966. rval = scan_once_unicode(s, pystr, idx, &next_idx);
  967. }
  968. else {
  969. PyErr_Format(PyExc_TypeError,
  970. "first argument must be a string, not %.80s",
  971. Py_TYPE(pystr)->tp_name);
  972. return NULL;
  973. }
  974. PyDict_Clear(s->memo);
  975. if (rval == NULL)
  976. return NULL;
  977. return _build_rval_index_tuple(rval, next_idx);
  978. }
  979. static PyObject *
  980. scanner_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  981. {
  982. PyScannerObject *s;
  983. s = (PyScannerObject *)type->tp_alloc(type, 0);
  984. if (s != NULL) {
  985. s->strict = NULL;
  986. s->object_hook = NULL;
  987. s->object_pairs_hook = NULL;
  988. s->parse_float = NULL;
  989. s->parse_int = NULL;
  990. s->parse_constant = NULL;
  991. }
  992. return (PyObject *)s;
  993. }
  994. static int
  995. scanner_init(PyObject *self, PyObject *args, PyObject *kwds)
  996. {
  997. /* Initialize Scanner object */
  998. PyObject *ctx;
  999. static char *kwlist[] = {"context", NULL};
  1000. PyScannerObject *s;
  1001. assert(PyScanner_Check(self));
  1002. s = (PyScannerObject *)self;
  1003. if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:make_scanner", kwlist, &ctx))
  1004. return -1;
  1005. if (s->memo == NULL) {
  1006. s->memo = PyDict_New();
  1007. if (s->memo == NULL)
  1008. goto bail;
  1009. }
  1010. /* All of these will fail "gracefully" so we don't need to verify them */
  1011. s->strict = PyObject_GetAttrString(ctx, "strict");
  1012. if (s->strict == NULL)
  1013. goto bail;
  1014. s->object_hook = PyObject_GetAttrString(ctx, "object_hook");
  1015. if (s->object_hook == NULL)
  1016. goto bail;
  1017. s->object_pairs_hook = PyObject_GetAttrString(ctx, "object_pairs_hook");
  1018. if (s->object_pairs_hook == NULL)
  1019. goto bail;
  1020. s->parse_float = PyObject_GetAttrString(ctx, "parse_float");
  1021. if (s->parse_float == NULL)
  1022. goto bail;
  1023. s->parse_int = PyObject_GetAttrString(ctx, "parse_int");
  1024. if (s->parse_int == NULL)
  1025. goto bail;
  1026. s->parse_constant = PyObject_GetAttrString(ctx, "parse_constant");
  1027. if (s->parse_constant == NULL)
  1028. goto bail;
  1029. return 0;
  1030. bail:
  1031. Py_CLEAR(s->strict);
  1032. Py_CLEAR(s->object_hook);
  1033. Py_CLEAR(s->object_pairs_hook);
  1034. Py_CLEAR(s->parse_float);
  1035. Py_CLEAR(s->parse_int);
  1036. Py_CLEAR(s->parse_constant);
  1037. return -1;
  1038. }
  1039. PyDoc_STRVAR(scanner_doc, "JSON scanner object");
  1040. static
  1041. PyTypeObject PyScannerType = {
  1042. PyVarObject_HEAD_INIT(NULL, 0)
  1043. "_json.Scanner", /* tp_name */
  1044. sizeof(PyScannerObject), /* tp_basicsize */
  1045. 0, /* tp_itemsize */
  1046. scanner_dealloc, /* tp_dealloc */
  1047. 0, /* tp_print */
  1048. 0, /* tp_getattr */
  1049. 0, /* tp_setattr */
  1050. 0, /* tp_compare */
  1051. 0, /* tp_repr */
  1052. 0, /* tp_as_number */
  1053. 0, /* tp_as_sequence */
  1054. 0, /* tp_as_mapping */
  1055. 0, /* tp_hash */
  1056. scanner_call, /* tp_call */
  1057. 0, /* tp_str */
  1058. 0,/* PyObject_GenericGetAttr, */ /* tp_getattro */
  1059. 0,/* PyObject_GenericSetAttr, */ /* tp_setattro */
  1060. 0, /* tp_as_buffer */
  1061. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
  1062. scanner_doc, /* tp_doc */
  1063. scanner_traverse, /* tp_traverse */
  1064. scanner_clear, /* tp_clear */
  1065. 0, /* tp_richcompare */
  1066. 0, /* tp_weaklistoffset */
  1067. 0, /* tp_iter */
  1068. 0, /* tp_iternext */
  1069. 0, /* tp_methods */
  1070. scanner_members, /* tp_members */
  1071. 0, /* tp_getset */
  1072. 0, /* tp_base */
  1073. 0, /* tp_dict */
  1074. 0, /* tp_descr_get */
  1075. 0, /* tp_descr_set */
  1076. 0, /* tp_dictoffset */
  1077. scanner_init, /* tp_init */
  1078. 0,/* PyType_GenericAlloc, */ /* tp_alloc */
  1079. scanner_new, /* tp_new */
  1080. 0,/* PyObject_GC_Del, */ /* tp_free */
  1081. };
  1082. static PyObject *
  1083. encoder_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  1084. {
  1085. PyEncoderObject *s;
  1086. s = (PyEncoderObject *)type->tp_alloc(type, 0);
  1087. if (s != NULL) {
  1088. s->markers = NULL;
  1089. s->defaultfn = NULL;
  1090. s->encoder = NULL;
  1091. s->indent = NULL;
  1092. s->key_separator = NULL;
  1093. s->item_separator = NULL;
  1094. s->sort_keys = NULL;
  1095. s->skipkeys = NULL;
  1096. }
  1097. return (PyObject *)s;
  1098. }
  1099. static int
  1100. encoder_init(PyObject *self, PyObject *args, PyObject *kwds)
  1101. {
  1102. /* initialize Encoder object */
  1103. static char *kwlist[] = {"markers", "default", "encoder", "indent", "key_separator", "item_separator", "sort_keys", "skipkeys", "allow_nan", NULL};
  1104. PyEncoderObject *s;
  1105. PyObject *markers, *defaultfn, *encoder, *indent, *key_separator;
  1106. PyObject *item_separator, *sort_keys, *skipkeys, *allow_nan;
  1107. assert(PyEncoder_Check(self));
  1108. s = (PyEncoderObject *)self;
  1109. if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOOOOOOOO:make_encoder", kwlist,
  1110. &markers, &defaultfn, &encoder, &indent, &key_separator, &item_separator,
  1111. &sort_keys, &skipkeys, &allow_nan))
  1112. return -1;
  1113. s->markers = markers;
  1114. s->defaultfn = defaultfn;
  1115. s->encoder = encoder;
  1116. s->indent = indent;
  1117. s->key_separator = key_separator;
  1118. s->item_separator = item_separator;
  1119. s->sort_keys = sort_keys;
  1120. s->skipkeys = skipkeys;
  1121. s->fast_encode = (PyCFunction_Check(s->encoder) && PyCFunction_GetFunction(s->encoder) == (PyCFunction)py_encode_basestring_ascii);
  1122. s->allow_nan = PyObject_IsTrue(allow_nan);
  1123. Py_INCREF(s->markers);
  1124. Py_INCREF(s->defaultfn);
  1125. Py_INCREF(s->encoder);
  1126. Py_INCREF(s->indent);
  1127. Py_INCREF(s->key_separator);
  1128. Py_INCREF(s->item_separator);
  1129. Py_INCREF(s->sort_keys);
  1130. Py_INCREF(s->skipkeys);
  1131. return 0;
  1132. }
  1133. static PyObject *
  1134. encoder_call(PyObject *self, PyObject *args, PyObject *kwds)
  1135. {
  1136. /* Python callable interface to encode_listencode_obj */
  1137. static char *kwlist[] = {"obj", "_current_indent_level", NULL};
  1138. PyObject *obj;
  1139. Py_ssize_t indent_level;
  1140. PyEncoderObject *s;
  1141. _PyAccu acc;
  1142. assert(PyEncoder_Check(self));
  1143. s = (PyEncoderObject *)self;
  1144. if (!PyArg_ParseTupleAndKeywords(args, kwds, "On:_iterencode", kwlist,
  1145. &obj, &indent_level))
  1146. return NULL;
  1147. if (_PyAccu_Init(&acc))
  1148. return NULL;
  1149. if (encoder_listencode_obj(s, &acc, obj, indent_level)) {
  1150. _PyAccu_Destroy(&acc);
  1151. return NULL;
  1152. }
  1153. return _PyAccu_FinishAsList(&acc);
  1154. }
  1155. static PyObject *
  1156. _encoded_const(PyObject *obj)
  1157. {
  1158. /* Return the JSON string representation of None, True, False */
  1159. if (obj == Py_None) {
  1160. static PyObject *s_null = NULL;
  1161. if (s_null == NULL) {
  1162. s_null = PyUnicode_InternFromString("null");
  1163. }
  1164. Py_INCREF(s_null);
  1165. return s_null;
  1166. }
  1167. else if (obj == Py_True) {
  1168. static PyObject *s_true = NULL;
  1169. if (s_true == NULL) {
  1170. s_true = PyUnicode_InternFromString("true");
  1171. }
  1172. Py_INCREF(s_true);
  1173. return s_true;
  1174. }
  1175. else if (obj == Py_False) {
  1176. static PyObject *s_false = NULL;
  1177. if (s_false == NULL) {
  1178. s_false = PyUnicode_InternFromString("false");
  1179. }
  1180. Py_INCREF(s_false);
  1181. return s_false;
  1182. }
  1183. else {
  1184. PyErr_SetString(PyExc_ValueError, "not a const");
  1185. return NULL;
  1186. }
  1187. }
  1188. static PyObject *
  1189. encoder_encode_long(PyEncoderObject* s UNUSED, PyObject *obj)
  1190. {
  1191. /* Return the JSON representation of a PyLong and PyLong subclasses.
  1192. Calls int() on PyLong subclasses in case the str() was changed.
  1193. Added specifically to deal with IntEnum. See Issue18264. */
  1194. PyObject *encoded, *longobj;
  1195. if (PyLong_CheckExact(obj)) {
  1196. encoded = PyObject_Str(obj);
  1197. }
  1198. else {
  1199. longobj = PyNumber_Long(obj);
  1200. if (longobj == NULL) {
  1201. PyErr_SetString(
  1202. PyExc_ValueError,
  1203. "Unable to coerce int subclass to int"
  1204. );
  1205. return NULL;
  1206. }
  1207. encoded = PyObject_Str(longobj);
  1208. Py_DECREF(longobj);
  1209. }
  1210. return encoded;
  1211. }
  1212. static PyObject *
  1213. encoder_encode_float(PyEncoderObject *s, PyObject *obj)
  1214. {
  1215. /* Return the JSON representation of a PyFloat.
  1216. Modified to call float() on float subclasses in case the subclass
  1217. changes the repr. See Issue18264. */
  1218. PyObject *encoded, *floatobj;
  1219. double i = PyFloat_AS_DOUBLE(obj);
  1220. if (!Py_IS_FINITE(i)) {
  1221. if (!s->allow_nan) {
  1222. PyErr_SetString(
  1223. PyExc_ValueError,
  1224. "Out of range float values are not JSON compliant"
  1225. );
  1226. return NULL;
  1227. }
  1228. if (i > 0) {
  1229. return PyUnicode_FromString("Infinity");
  1230. }
  1231. else if (i < 0) {
  1232. return PyUnicode_FromString("-Infinity");
  1233. }
  1234. else {
  1235. return PyUnicode_FromString("NaN");
  1236. }
  1237. }
  1238. /* coerce float subclasses to float (primarily for Enum) */
  1239. if (PyFloat_CheckExact(obj)) {
  1240. /* Use a better float format here? */
  1241. encoded = PyObject_Repr(obj);
  1242. }
  1243. else {
  1244. floatobj = PyNumber_Float(obj);
  1245. if (floatobj == NULL) {
  1246. PyErr_SetString(
  1247. PyExc_ValueError,
  1248. "Unable to coerce float subclass to float"
  1249. );
  1250. return NULL;
  1251. }
  1252. encoded = PyObject_Repr(floatobj);
  1253. Py_DECREF(floatobj);
  1254. }
  1255. return encoded;
  1256. }
  1257. static PyObject *
  1258. encoder_encode_string(PyEncoderObject *s, PyObject *obj)
  1259. {
  1260. /* Return the JSON representation of a string */
  1261. if (s->fast_encode)
  1262. return py_encode_basestring_ascii(NULL, obj);
  1263. else
  1264. return PyObject_CallFunctionObjArgs(s->encoder, obj, NULL);
  1265. }
  1266. static int
  1267. _steal_accumulate(_PyAccu *acc, PyObject *stolen)
  1268. {
  1269. /* Append stolen and then decrement its reference count */
  1270. int rval = _PyAccu_Accumulate(acc, stolen);
  1271. Py_DECREF(stolen);
  1272. return rval;
  1273. }
  1274. static int
  1275. encoder_listencode_obj(PyEncoderObject *s, _PyAccu *acc,
  1276. PyObject *obj, Py_ssize_t indent_level)
  1277. {
  1278. /* Encode Python object obj to a JSON term */
  1279. PyObject *newobj;
  1280. int rv;
  1281. if (obj == Py_None || obj == Py_True || obj == Py_False) {
  1282. PyObject *cstr = _encoded_const(obj);
  1283. if (cstr == NULL)
  1284. return -1;
  1285. return _steal_accumulate(acc, cstr);
  1286. }
  1287. else if (PyUnicode_Check(obj))
  1288. {
  1289. PyObject *encoded = encoder_encode_string(s, obj);
  1290. if (encoded == NULL)
  1291. return -1;
  1292. return _steal_accumulate(acc, encoded);
  1293. }
  1294. else if (PyLong_Check(obj)) {
  1295. PyObject *encoded = encoder_encode_long(s, obj);
  1296. if (encoded == NULL)
  1297. return -1;
  1298. return _steal_accumulate(acc, encoded);
  1299. }
  1300. else if (PyFloat_Check(obj)) {
  1301. PyObject *encoded = encoder_encode_float(s, obj);
  1302. if (encoded == NULL)
  1303. return -1;
  1304. return _steal_accumulate(acc, encoded);
  1305. }
  1306. else if (PyList_Check(obj) || PyTuple_Check(obj)) {
  1307. if (Py_EnterRecursiveCall(" while encoding a JSON object"))
  1308. return -1;
  1309. rv = encoder_listencode_list(s, acc, obj, indent_level);
  1310. Py_LeaveRecursiveCall();
  1311. return rv;
  1312. }
  1313. else if (PyDict_Check(obj)) {
  1314. if (Py_EnterRecursiveCall(" while encoding a JSON object"))
  1315. return -1;
  1316. rv = encoder_listencode_dict(s, acc, obj, indent_level);
  1317. Py_LeaveRecursiveCall();
  1318. return rv;
  1319. }
  1320. else {
  1321. PyObject *ident = NULL;
  1322. if (s->markers != Py_None) {
  1323. int has_key;
  1324. ident = PyLong_FromVoidPtr(obj);
  1325. if (ident == NULL)
  1326. return -1;
  1327. has_key = PyDict_Contains(s->markers, ident);
  1328. if (has_key) {
  1329. if (has_key != -1)
  1330. PyErr_SetString(PyExc_ValueError, "Circular reference detected");
  1331. Py_DECREF(ident);
  1332. return -1;
  1333. }
  1334. if (PyDict_SetItem(s->markers, ident, obj)) {
  1335. Py_DECREF(ident);
  1336. return -1;
  1337. }
  1338. }
  1339. newobj = PyObject_CallFunctionObjArgs(s->defaultfn, obj, NULL);
  1340. if (newobj == NULL) {
  1341. Py_XDECREF(ident);
  1342. return -1;
  1343. }
  1344. if (Py_EnterRecursiveCall(" while encoding a JSON object"))
  1345. return -1;
  1346. rv = encoder_listencode_obj(s, acc, newobj, indent_level);
  1347. Py_LeaveRecursiveCall();
  1348. Py_DECREF(newobj);
  1349. if (rv) {
  1350. Py_XDECREF(ident);
  1351. return -1;
  1352. }
  1353. if (ident != NULL) {
  1354. if (PyDict_DelItem(s->markers, ident)) {
  1355. Py_XDECREF(ident);
  1356. return -1;
  1357. }
  1358. Py_XDECREF(ident);
  1359. }
  1360. return rv;
  1361. }
  1362. }
  1363. static int
  1364. encoder_listencode_dict(PyEncoderObject *s, _PyAccu *acc,
  1365. PyObject *dct, Py_ssize_t indent_level)
  1366. {
  1367. /* Encode Python dict dct a JSON term */
  1368. static PyObject *open_dict = NULL;
  1369. static PyObject *close_dict = NULL;
  1370. static PyObject *empty_dict = NULL;
  1371. PyObject *kstr = NULL;
  1372. PyObject *ident = NULL;
  1373. PyObject *it = NULL;
  1374. PyObject *items;
  1375. PyObject *item = NULL;
  1376. int skipkeys;
  1377. Py_ssize_t idx;
  1378. if (open_dict == NULL || close_dict == NULL || empty_dict == NULL) {
  1379. open_dict = PyUnicode_InternFromString("{");
  1380. close_dict = PyUnicode_InternFromString("}");
  1381. empty_dict = PyUnicode_InternFromString("{}");
  1382. if (open_dict == NULL || close_dict == NULL || empty_dict == NULL)
  1383. return -1;
  1384. }
  1385. if (Py_SIZE(dct) == 0)
  1386. return _PyAccu_Accumulate(acc, empty_dict);
  1387. if (s->markers != Py_None) {
  1388. int has_key;
  1389. ident = PyLong_FromVoidPtr(dct);
  1390. if (ident == NULL)
  1391. goto bail;
  1392. has_key = PyDict_Contains(s->markers, ident);
  1393. if (has_key) {
  1394. if (has_key != -1)
  1395. PyErr_SetString(PyExc_ValueError, "Circular reference detected");
  1396. goto bail;
  1397. }
  1398. if (PyDict_SetItem(s->markers, ident, dct)) {
  1399. goto bail;
  1400. }
  1401. }
  1402. if (_PyAccu_Accumulate(acc, open_dict))
  1403. goto bail;
  1404. if (s->indent != Py_None) {
  1405. /* TODO: DOES NOT RUN */
  1406. indent_level += 1;
  1407. /*
  1408. newline_indent = '\n' + (' ' * (_indent * _current_indent_level))
  1409. separator = _item_separator + newline_indent
  1410. buf += newline_indent
  1411. */
  1412. }
  1413. if (PyObject_IsTrue(s->sort_keys)) {
  1414. /* First sort the keys then replace them with (key, value) tuples. */
  1415. Py_ssize_t i, nitems;
  1416. items = PyMapping_Keys(dct);
  1417. if (items == NULL)
  1418. goto bail;
  1419. if (!PyList_Check(items)) {
  1420. PyErr_SetString(PyExc_ValueError, "keys must return list");
  1421. goto bail;
  1422. }
  1423. if (PyList_Sort(items) < 0)
  1424. goto bail;
  1425. nitems = PyList_GET_SIZE(items);
  1426. for (i = 0; i < nitems; i++) {
  1427. PyObject *key, *value;
  1428. key = PyList_GET_ITEM(items, i);
  1429. value = PyDict_GetItem(dct, key);
  1430. item = PyTuple_Pack(2, key, value);
  1431. if (item == NULL)
  1432. goto bail;
  1433. PyList_SET_ITEM(items, i, item);
  1434. item = NULL;
  1435. Py_DECREF(key);
  1436. }
  1437. }
  1438. else {
  1439. items = PyMapping_Items(dct);
  1440. }
  1441. if (items == NULL)
  1442. goto bail;
  1443. it = PyObject_GetIter(items);
  1444. Py_DECREF(items);
  1445. if (it == NULL)
  1446. goto bail;
  1447. skipkeys = PyObject_IsTrue(s->skipkeys);
  1448. idx = 0;
  1449. while ((item = PyIter_Next(it)) != NULL) {
  1450. PyObject *encoded, *key, *value;
  1451. if (!PyTuple_Check(item) || Py_SIZE(item) != 2) {
  1452. PyErr_SetString(PyExc_ValueError, "items must return 2-tuples");
  1453. goto bail;
  1454. }
  1455. key = PyTuple_GET_ITEM(item, 0);
  1456. if (PyUnicode_Check(key)) {
  1457. Py_INCREF(key);
  1458. kstr = key;
  1459. }
  1460. else if (PyFloat_Check(key)) {
  1461. kstr = encoder_encode_float(s, key);
  1462. if (kstr == NULL)
  1463. goto bail;
  1464. }
  1465. else if (key == Py_True || key == Py_False || key == Py_None) {
  1466. /* This must come before the PyLong_Check because
  1467. True and False are also 1 and 0.*/
  1468. kstr = _encoded_const(key);
  1469. if (kstr == NULL)
  1470. goto bail;
  1471. }
  1472. else if (PyLong_Check(key)) {
  1473. kstr = encoder_encode_long(s, key);
  1474. if (kstr == NULL) {
  1475. goto bail;
  1476. }
  1477. }
  1478. else if (skipkeys) {
  1479. Py_DECREF(item);
  1480. continue;
  1481. }
  1482. else {
  1483. /* TODO: include repr of key */
  1484. PyErr_SetString(PyExc_TypeError, "keys must be a string");
  1485. goto bail;
  1486. }
  1487. if (idx) {
  1488. if (_PyAccu_Accumulate(acc, s->item_separator))
  1489. goto bail;
  1490. }
  1491. encoded = encoder_encode_string(s, kstr);
  1492. Py_CLEAR(kstr);
  1493. if (encoded == NULL)
  1494. goto bail;
  1495. if (_PyAccu_Accumulate(acc, encoded)) {
  1496. Py_DECREF(encoded);
  1497. goto bail;
  1498. }
  1499. Py_DECREF(encoded);
  1500. if (_PyAccu_Accumulate(acc, s->key_separator))
  1501. goto bail;
  1502. value = PyTuple_GET_ITEM(item, 1);
  1503. if (encoder_listencode_obj(s, acc, value, indent_level))
  1504. goto bail;
  1505. idx += 1;
  1506. Py_DECREF(item);
  1507. }
  1508. if (PyErr_Occurred())
  1509. goto bail;
  1510. Py_CLEAR(it);
  1511. if (ident != NULL) {
  1512. if (PyDict_DelItem(s->markers, ident))
  1513. goto bail;
  1514. Py_CLEAR(ident);
  1515. }
  1516. /* TODO DOES NOT RUN; dead code
  1517. if (s->indent != Py_None) {
  1518. indent_level -= 1;
  1519. yield '\n' + (' ' * (_indent * _current_indent_level))
  1520. }*/
  1521. if (_PyAccu_Accumulate(acc, close_dict))
  1522. goto bail;
  1523. return 0;
  1524. bail:
  1525. Py_XDECREF(it);
  1526. Py_XDECREF(item);
  1527. Py_XDECREF(kstr);
  1528. Py_XDECREF(ident);
  1529. return -1;
  1530. }
  1531. static int
  1532. encoder_listencode_list(PyEncoderObject *s, _PyAccu *acc,
  1533. PyObject *seq, Py_ssize_t indent_level)
  1534. {
  1535. /* Encode Python list seq to a JSON term */
  1536. static PyObject *open_array = NULL;
  1537. static PyObject *close_array = NULL;
  1538. static PyObject *empty_array = NULL;
  1539. PyObject *ident = NULL;
  1540. PyObject *s_fast = NULL;
  1541. Py_ssize_t i;
  1542. if (open_array == NULL || close_array == NULL || empty_array == NULL) {
  1543. open_array = PyUnicode_InternFromString("[");
  1544. close_array = PyUnicode_InternFromString("]");
  1545. empty_array = PyUnicode_InternFromString("[]");
  1546. if (open_array == NULL || close_array == NULL || empty_array == NULL)
  1547. return -1;
  1548. }
  1549. ident = NULL;
  1550. s_fast = PySequence_Fast(seq, "_iterencode_list needs a sequence");
  1551. if (s_fast == NULL)
  1552. return -1;
  1553. if (PySequence_Fast_GET_SIZE(s_fast) == 0) {
  1554. Py_DECREF(s_fast);
  1555. return _PyAccu_Accumulate(acc, empty_array);
  1556. }
  1557. if (s->markers != Py_None) {
  1558. int has_key;
  1559. ident = PyLong_FromVoidPtr(seq);
  1560. if (ident == NULL)
  1561. goto bail;
  1562. has_key = PyDict_Contains(s->markers, ident);
  1563. if (has_key) {
  1564. if (has_key != -1)
  1565. PyErr_SetString(PyExc_ValueError, "Circular reference detected");
  1566. goto bail;
  1567. }
  1568. if (PyDict_SetItem(s->markers, ident, seq)) {
  1569. goto bail;
  1570. }
  1571. }
  1572. if (_PyAccu_Accumulate(acc, open_array))
  1573. goto bail;
  1574. if (s->indent != Py_None) {
  1575. /* TODO: DOES NOT RUN */
  1576. indent_level += 1;
  1577. /*
  1578. newline_indent = '\n' + (' ' * (_indent * _current_indent_level))
  1579. separator = _item_separator + newline_indent
  1580. buf += newline_indent
  1581. */
  1582. }
  1583. for (i = 0; i < PySequence_Fast_GET_SIZE(s_fast); i++) {
  1584. PyObject *obj = PySequence_Fast_GET_ITEM(s_fast, i);
  1585. if (i) {
  1586. if (_PyAccu_Accumulate(acc, s->item_separator))
  1587. goto bail;
  1588. }
  1589. if (encoder_listencode_obj(s, acc, obj, indent_level))
  1590. goto bail;
  1591. }
  1592. if (ident != NULL) {
  1593. if (PyDict_DelItem(s->markers, ident))
  1594. goto bail;
  1595. Py_CLEAR(ident);
  1596. }
  1597. /* TODO: DOES NOT RUN
  1598. if (s->indent != Py_None) {
  1599. indent_level -= 1;
  1600. yield '\n' + (' ' * (_indent * _current_indent_level))
  1601. }*/
  1602. if (_PyAccu_Accumulate(acc, close_array))
  1603. goto bail;
  1604. Py_DECREF(s_fast);
  1605. return 0;
  1606. bail:
  1607. Py_XDECREF(ident);
  1608. Py_DECREF(s_fast);
  1609. return -1;
  1610. }
  1611. static void
  1612. encoder_dealloc(PyObject *self)
  1613. {
  1614. /* Deallocate Encoder */
  1615. encoder_clear(self);
  1616. Py_TYPE(self)->tp_free(self);
  1617. }
  1618. static int
  1619. encoder_traverse(PyObject *self, visitproc visit, void *arg)
  1620. {
  1621. PyEncoderObject *s;
  1622. assert(PyEncoder_Check(self));
  1623. s = (PyEncoderObject *)self;
  1624. Py_VISIT(s->markers);
  1625. Py_VISIT(s->defaultfn);
  1626. Py_VISIT(s->encoder);
  1627. Py_VISIT(s->indent);
  1628. Py_VISIT(s->key_separator);
  1629. Py_VISIT(s->item_separator);
  1630. Py_VISIT(s->sort_keys);
  1631. Py_VISIT(s->skipkeys);
  1632. return 0;
  1633. }
  1634. static int
  1635. encoder_clear(PyObject *self)
  1636. {
  1637. /* Deallocate Encoder */
  1638. PyEncoderObject *s;
  1639. assert(PyEncoder_Check(self));
  1640. s = (PyEncoderObject *)self;
  1641. Py_CLEAR(s->markers);
  1642. Py_CLEAR(s->defaultfn);
  1643. Py_CLEAR(s->encoder);
  1644. Py_CLEAR(s->indent);
  1645. Py_CLEAR(s->key_separator);
  1646. Py_CLEAR(s->item_separator);
  1647. Py_CLEAR(s->sort_keys);
  1648. Py_CLEAR(s->skipkeys);
  1649. return 0;
  1650. }
  1651. PyDoc_STRVAR(encoder_doc, "_iterencode(obj, _current_indent_level) -> iterable");
  1652. static
  1653. PyTypeObject PyEncoderType = {
  1654. PyVarObject_HEAD_INIT(NULL, 0)
  1655. "_json.Encoder", /* tp_name */
  1656. sizeof(PyEncoderObject), /* tp_basicsize */
  1657. 0, /* tp_itemsize */
  1658. encoder_dealloc, /* tp_dealloc */
  1659. 0, /* tp_print */
  1660. 0, /* tp_getattr */
  1661. 0, /* tp_setattr */
  1662. 0, /* tp_compare */
  1663. 0, /* tp_repr */
  1664. 0, /* tp_as_number */
  1665. 0, /* tp_as_sequence */
  1666. 0, /* tp_as_mapping */
  1667. 0, /* tp_hash */
  1668. encoder_call, /* tp_call */
  1669. 0, /* tp_str */
  1670. 0, /* tp_getattro */
  1671. 0, /* tp_setattro */
  1672. 0, /* tp_as_buffer */
  1673. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
  1674. encoder_doc, /* tp_doc */
  1675. encoder_traverse, /* tp_traverse */
  1676. encoder_clear, /* tp_clear */
  1677. 0, /* tp_richcompare */
  1678. 0, /* tp_weaklistoffset */
  1679. 0, /* tp_iter */
  1680. 0, /* tp_iternext */
  1681. 0, /* tp_methods */
  1682. encoder_members, /* tp_members */
  1683. 0, /* tp_getset */
  1684. 0, /* tp_base */
  1685. 0, /* tp_dict */
  1686. 0, /* tp_descr_get */
  1687. 0, /* tp_descr_set */
  1688. 0, /* tp_dictoffset */
  1689. encoder_init, /* tp_init */
  1690. 0, /* tp_alloc */
  1691. encoder_new, /* tp_new */
  1692. 0, /* tp_free */
  1693. };
  1694. static PyMethodDef speedups_methods[] = {
  1695. {"encode_basestring_ascii",
  1696. (PyCFunction)py_encode_basestring_ascii,
  1697. METH_O,
  1698. pydoc_encode_basestring_ascii},
  1699. {"scanstring",
  1700. (PyCFunction)py_scanstring,
  1701. METH_VARARGS,
  1702. pydoc_scanstring},
  1703. {NULL, NULL, 0, NULL}
  1704. };
  1705. PyDoc_STRVAR(module_doc,
  1706. "json speedups\n");
  1707. static struct PyModuleDef jsonmodule = {
  1708. PyModuleDef_HEAD_INIT,
  1709. "_json",
  1710. module_doc,
  1711. -1,
  1712. speedups_methods,
  1713. NULL,
  1714. NULL,
  1715. NULL,
  1716. NULL
  1717. };
  1718. PyObject*
  1719. PyInit__json(void)
  1720. {
  1721. PyObject *m = PyModule_Create(&jsonmodule);
  1722. if (!m)
  1723. return NULL;
  1724. PyScannerType.tp_new = PyType_GenericNew;
  1725. if (PyType_Ready(&PyScannerType) < 0)
  1726. goto fail;
  1727. PyEncoderType.tp_new = PyType_GenericNew;
  1728. if (PyType_Ready(&PyEncoderType) < 0)
  1729. goto fail;
  1730. Py_INCREF((PyObject*)&PyScannerType);
  1731. if (PyModule_AddObject(m, "make_scanner", (PyObject*)&PyScannerType) < 0) {
  1732. Py_DECREF((PyObject*)&PyScannerType);
  1733. goto fail;
  1734. }
  1735. Py_INCREF((PyObject*)&PyEncoderType);
  1736. if (PyModule_AddObject(m, "make_encoder", (PyObject*)&PyEncoderType) < 0) {
  1737. Py_DECREF((PyObject*)&PyEncoderType);
  1738. goto fail;
  1739. }
  1740. return m;
  1741. fail:
  1742. Py_DECREF(m);
  1743. return NULL;
  1744. }