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.

1883 lines
59 KiB

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