blob: 39d39cb05a05e7b51c6d2fd1a6278559d95da537 [file] [log] [blame]
Christian Heimes90540002008-05-08 14:29:10 +00001#include "Python.h"
2
3#define DEFAULT_ENCODING "utf-8"
4#define S_CHAR(c) (c >= ' ' && c <= '~' && c != '\\' && c != '"')
5#define MIN_EXPANSION 6
6
7#ifdef Py_UNICODE_WIDE
8#define MAX_EXPANSION (2 * MIN_EXPANSION)
9#else
10#define MAX_EXPANSION MIN_EXPANSION
11#endif
12
13static Py_ssize_t
14ascii_escape_char(Py_UNICODE c, char *output, Py_ssize_t chars)
15{
16 Py_UNICODE x;
17 output[chars++] = '\\';
18 switch (c) {
19 case '\\': output[chars++] = (char)c; break;
20 case '"': output[chars++] = (char)c; break;
21 case '\b': output[chars++] = 'b'; break;
22 case '\f': output[chars++] = 'f'; break;
23 case '\n': output[chars++] = 'n'; break;
24 case '\r': output[chars++] = 'r'; break;
25 case '\t': output[chars++] = 't'; break;
26 default:
27#ifdef Py_UNICODE_WIDE
28 if (c >= 0x10000) {
29 /* UTF-16 surrogate pair */
30 Py_UNICODE v = c - 0x10000;
31 c = 0xd800 | ((v >> 10) & 0x3ff);
32 output[chars++] = 'u';
33 x = (c & 0xf000) >> 12;
34 output[chars++] = (x < 10) ? '0' + x : 'a' + (x - 10);
35 x = (c & 0x0f00) >> 8;
36 output[chars++] = (x < 10) ? '0' + x : 'a' + (x - 10);
37 x = (c & 0x00f0) >> 4;
38 output[chars++] = (x < 10) ? '0' + x : 'a' + (x - 10);
39 x = (c & 0x000f);
40 output[chars++] = (x < 10) ? '0' + x : 'a' + (x - 10);
41 c = 0xdc00 | (v & 0x3ff);
42 output[chars++] = '\\';
43 }
44#endif
45 output[chars++] = 'u';
46 x = (c & 0xf000) >> 12;
47 output[chars++] = (x < 10) ? '0' + x : 'a' + (x - 10);
48 x = (c & 0x0f00) >> 8;
49 output[chars++] = (x < 10) ? '0' + x : 'a' + (x - 10);
50 x = (c & 0x00f0) >> 4;
51 output[chars++] = (x < 10) ? '0' + x : 'a' + (x - 10);
52 x = (c & 0x000f);
53 output[chars++] = (x < 10) ? '0' + x : 'a' + (x - 10);
54 }
55 return chars;
56}
57
58static PyObject *
59ascii_escape_unicode(PyObject *pystr)
60{
61 Py_ssize_t i;
62 Py_ssize_t input_chars;
63 Py_ssize_t output_size;
64 Py_ssize_t chars;
65 PyObject *rval;
66 char *output;
67 Py_UNICODE *input_unicode;
68
69 input_chars = PyUnicode_GET_SIZE(pystr);
70 input_unicode = PyUnicode_AS_UNICODE(pystr);
71 /* One char input can be up to 6 chars output, estimate 4 of these */
72 output_size = 2 + (MIN_EXPANSION * 4) + input_chars;
73 rval = PyString_FromStringAndSize(NULL, output_size);
74 if (rval == NULL) {
75 return NULL;
76 }
77 output = PyString_AS_STRING(rval);
78 chars = 0;
79 output[chars++] = '"';
80 for (i = 0; i < input_chars; i++) {
81 Py_UNICODE c = input_unicode[i];
82 if (S_CHAR(c)) {
83 output[chars++] = (char)c;
84 }
85 else {
86 chars = ascii_escape_char(c, output, chars);
87 }
88 if (output_size - chars < (1 + MAX_EXPANSION)) {
89 /* There's more than four, so let's resize by a lot */
90 output_size *= 2;
91 /* This is an upper bound */
92 if (output_size > 2 + (input_chars * MAX_EXPANSION)) {
93 output_size = 2 + (input_chars * MAX_EXPANSION);
94 }
95 if (_PyString_Resize(&rval, output_size) == -1) {
96 return NULL;
97 }
98 output = PyString_AS_STRING(rval);
99 }
100 }
101 output[chars++] = '"';
102 if (_PyString_Resize(&rval, chars) == -1) {
103 return NULL;
104 }
105 return rval;
106}
107
108static PyObject *
109ascii_escape_str(PyObject *pystr)
110{
111 Py_ssize_t i;
112 Py_ssize_t input_chars;
113 Py_ssize_t output_size;
114 Py_ssize_t chars;
115 PyObject *rval;
116 char *output;
117 char *input_str;
118
119 input_chars = PyString_GET_SIZE(pystr);
120 input_str = PyString_AS_STRING(pystr);
121 /* One char input can be up to 6 chars output, estimate 4 of these */
122 output_size = 2 + (MIN_EXPANSION * 4) + input_chars;
123 rval = PyString_FromStringAndSize(NULL, output_size);
124 if (rval == NULL) {
125 return NULL;
126 }
127 output = PyString_AS_STRING(rval);
128 chars = 0;
129 output[chars++] = '"';
130 for (i = 0; i < input_chars; i++) {
131 Py_UNICODE c = (Py_UNICODE)input_str[i];
132 if (S_CHAR(c)) {
133 output[chars++] = (char)c;
134 }
135 else if (c > 0x7F) {
136 /* We hit a non-ASCII character, bail to unicode mode */
137 PyObject *uni;
138 Py_DECREF(rval);
139 uni = PyUnicode_DecodeUTF8(input_str, input_chars, "strict");
140 if (uni == NULL) {
141 return NULL;
142 }
143 rval = ascii_escape_unicode(uni);
144 Py_DECREF(uni);
145 return rval;
146 }
147 else {
148 chars = ascii_escape_char(c, output, chars);
149 }
150 /* An ASCII char can't possibly expand to a surrogate! */
151 if (output_size - chars < (1 + MIN_EXPANSION)) {
152 /* There's more than four, so let's resize by a lot */
153 output_size *= 2;
154 if (output_size > 2 + (input_chars * MIN_EXPANSION)) {
155 output_size = 2 + (input_chars * MIN_EXPANSION);
156 }
157 if (_PyString_Resize(&rval, output_size) == -1) {
158 return NULL;
159 }
160 output = PyString_AS_STRING(rval);
161 }
162 }
163 output[chars++] = '"';
164 if (_PyString_Resize(&rval, chars) == -1) {
165 return NULL;
166 }
167 return rval;
168}
169
170void
171raise_errmsg(char *msg, PyObject *s, Py_ssize_t end)
172{
173 static PyObject *errmsg_fn = NULL;
174 PyObject *pymsg;
175 if (errmsg_fn == NULL) {
176 PyObject *decoder = PyImport_ImportModule("json.decoder");
177 if (decoder == NULL)
178 return;
179 errmsg_fn = PyObject_GetAttrString(decoder, "errmsg");
180 if (errmsg_fn == NULL)
181 return;
182 Py_XDECREF(decoder);
183 }
184 pymsg = PyObject_CallFunction(errmsg_fn, "(zOn)", msg, s, end);
185 PyErr_SetObject(PyExc_ValueError, pymsg);
186 Py_DECREF(pymsg);
187/*
188
189def linecol(doc, pos):
190 lineno = doc.count('\n', 0, pos) + 1
191 if lineno == 1:
192 colno = pos
193 else:
194 colno = pos - doc.rindex('\n', 0, pos)
195 return lineno, colno
196
197def errmsg(msg, doc, pos, end=None):
198 lineno, colno = linecol(doc, pos)
199 if end is None:
200 return '%s: line %d column %d (char %d)' % (msg, lineno, colno, pos)
201 endlineno, endcolno = linecol(doc, end)
202 return '%s: line %d column %d - line %d column %d (char %d - %d)' % (
203 msg, lineno, colno, endlineno, endcolno, pos, end)
204
205*/
206}
207
208static PyObject *
209join_list_unicode(PyObject *lst)
210{
211 static PyObject *ustr = NULL;
212 static PyObject *joinstr = NULL;
213 if (ustr == NULL) {
214 Py_UNICODE c = 0;
215 ustr = PyUnicode_FromUnicode(&c, 0);
216 }
217 if (joinstr == NULL) {
218 joinstr = PyUnicode_InternFromString("join");
219 }
220 if (joinstr == NULL || ustr == NULL) {
221 return NULL;
222 }
223 return PyObject_CallMethodObjArgs(ustr, joinstr, lst, NULL);
224}
225
226static PyObject *
227scanstring_str(PyObject *pystr, Py_ssize_t end, char *encoding, int strict)
228{
229 PyObject *rval;
230 Py_ssize_t len = PyString_GET_SIZE(pystr);
231 Py_ssize_t begin = end - 1;
232 Py_ssize_t next = begin;
233 char *buf = PyString_AS_STRING(pystr);
234 Py_buffer info;
235 PyObject *chunks = PyList_New(0);
236 if (chunks == NULL) {
237 goto bail;
238 }
239 while (1) {
240 /* Find the end of the string or the next escape */
241 Py_UNICODE c = 0;
242 PyObject *chunk = NULL;
243 for (next = end; next < len; next++) {
244 c = buf[next];
245 if (c == '"' || c == '\\') {
246 break;
247 }
248 else if (strict && c <= 0x1f) {
249 raise_errmsg("Invalid control character at", pystr, begin);
250 goto bail;
251 }
252 }
253 if (!(c == '"' || c == '\\')) {
254 raise_errmsg("Unterminated string starting at", pystr, begin);
255 goto bail;
256 }
257 /* Pick up this chunk if it's not zero length */
258 if (next != end) {
259 if (PyBuffer_FillInfo(&info, &buf[end], next - end, 1, 0) < 0) {
260 goto bail;
261 }
262 PyObject *strchunk = PyMemoryView_FromMemory(&info);
263 if (strchunk == NULL) {
264 goto bail;
265 }
266 chunk = PyUnicode_FromEncodedObject(strchunk, encoding, NULL);
267 Py_DECREF(strchunk);
268 if (chunk == NULL) {
269 goto bail;
270 }
271 if (PyList_Append(chunks, chunk)) {
272 goto bail;
273 }
274 Py_DECREF(chunk);
275 }
276 next++;
277 if (c == '"') {
278 end = next;
279 break;
280 }
281 if (next == len) {
282 raise_errmsg("Unterminated string starting at", pystr, begin);
283 goto bail;
284 }
285 c = buf[next];
286 if (c != 'u') {
287 /* Non-unicode backslash escapes */
288 end = next + 1;
289 switch (c) {
290 case '"': break;
291 case '\\': break;
292 case '/': break;
293 case 'b': c = '\b'; break;
294 case 'f': c = '\f'; break;
295 case 'n': c = '\n'; break;
296 case 'r': c = '\r'; break;
297 case 't': c = '\t'; break;
298 default: c = 0;
299 }
300 if (c == 0) {
301 raise_errmsg("Invalid \\escape", pystr, end - 2);
302 goto bail;
303 }
304 }
305 else {
306 c = 0;
307 next++;
308 end = next + 4;
309 if (end >= len) {
310 raise_errmsg("Invalid \\uXXXX escape", pystr, next - 1);
311 goto bail;
312 }
313 /* Decode 4 hex digits */
314 for (; next < end; next++) {
315 Py_ssize_t shl = (end - next - 1) << 2;
316 Py_UNICODE digit = buf[next];
317 switch (digit) {
318 case '0': case '1': case '2': case '3': case '4':
319 case '5': case '6': case '7': case '8': case '9':
320 c |= (digit - '0') << shl; break;
321 case 'a': case 'b': case 'c': case 'd': case 'e':
322 case 'f':
323 c |= (digit - 'a' + 10) << shl; break;
324 case 'A': case 'B': case 'C': case 'D': case 'E':
325 case 'F':
326 c |= (digit - 'A' + 10) << shl; break;
327 default:
328 raise_errmsg("Invalid \\uXXXX escape", pystr, end - 5);
329 goto bail;
330 }
331 }
332#ifdef Py_UNICODE_WIDE
333 /* Surrogate pair */
334 if (c >= 0xd800 && c <= 0xdbff) {
335 Py_UNICODE c2 = 0;
336 if (end + 6 >= len) {
337 raise_errmsg("Invalid \\uXXXX\\uXXXX surrogate pair", pystr,
338 end - 5);
339 }
340 if (buf[next++] != '\\' || buf[next++] != 'u') {
341 raise_errmsg("Invalid \\uXXXX\\uXXXX surrogate pair", pystr,
342 end - 5);
343 }
344 end += 6;
345 /* Decode 4 hex digits */
346 for (; next < end; next++) {
347 Py_ssize_t shl = (end - next - 1) << 2;
348 Py_UNICODE digit = buf[next];
349 switch (digit) {
350 case '0': case '1': case '2': case '3': case '4':
351 case '5': case '6': case '7': case '8': case '9':
352 c2 |= (digit - '0') << shl; break;
353 case 'a': case 'b': case 'c': case 'd': case 'e':
354 case 'f':
355 c2 |= (digit - 'a' + 10) << shl; break;
356 case 'A': case 'B': case 'C': case 'D': case 'E':
357 case 'F':
358 c2 |= (digit - 'A' + 10) << shl; break;
359 default:
360 raise_errmsg("Invalid \\uXXXX escape", pystr, end - 5);
361 goto bail;
362 }
363 }
364 c = 0x10000 + (((c - 0xd800) << 10) | (c2 - 0xdc00));
365 }
366#endif
367 }
368 chunk = PyUnicode_FromUnicode(&c, 1);
369 if (chunk == NULL) {
370 goto bail;
371 }
372 if (PyList_Append(chunks, chunk)) {
373 goto bail;
374 }
375 Py_DECREF(chunk);
376 }
377
378 rval = join_list_unicode(chunks);
379 if (rval == NULL) {
380 goto bail;
381 }
382 Py_DECREF(chunks);
383 chunks = NULL;
384 return Py_BuildValue("(Nn)", rval, end);
385bail:
386 Py_XDECREF(chunks);
387 return NULL;
388}
389
390
391static PyObject *
392scanstring_unicode(PyObject *pystr, Py_ssize_t end, int strict)
393{
394 PyObject *rval;
395 Py_ssize_t len = PyUnicode_GET_SIZE(pystr);
396 Py_ssize_t begin = end - 1;
397 Py_ssize_t next = begin;
398 const Py_UNICODE *buf = PyUnicode_AS_UNICODE(pystr);
399 PyObject *chunks = PyList_New(0);
400 if (chunks == NULL) {
401 goto bail;
402 }
403 while (1) {
404 /* Find the end of the string or the next escape */
405 Py_UNICODE c = 0;
406 PyObject *chunk = NULL;
407 for (next = end; next < len; next++) {
408 c = buf[next];
409 if (c == '"' || c == '\\') {
410 break;
411 }
412 else if (strict && c <= 0x1f) {
413 raise_errmsg("Invalid control character at", pystr, begin);
414 goto bail;
415 }
416 }
417 if (!(c == '"' || c == '\\')) {
418 raise_errmsg("Unterminated string starting at", pystr, begin);
419 goto bail;
420 }
421 /* Pick up this chunk if it's not zero length */
422 if (next != end) {
423 chunk = PyUnicode_FromUnicode(&buf[end], next - end);
424 if (chunk == NULL) {
425 goto bail;
426 }
427 if (PyList_Append(chunks, chunk)) {
428 goto bail;
429 }
430 Py_DECREF(chunk);
431 }
432 next++;
433 if (c == '"') {
434 end = next;
435 break;
436 }
437 if (next == len) {
438 raise_errmsg("Unterminated string starting at", pystr, begin);
439 goto bail;
440 }
441 c = buf[next];
442 if (c != 'u') {
443 /* Non-unicode backslash escapes */
444 end = next + 1;
445 switch (c) {
446 case '"': break;
447 case '\\': break;
448 case '/': break;
449 case 'b': c = '\b'; break;
450 case 'f': c = '\f'; break;
451 case 'n': c = '\n'; break;
452 case 'r': c = '\r'; break;
453 case 't': c = '\t'; break;
454 default: c = 0;
455 }
456 if (c == 0) {
457 raise_errmsg("Invalid \\escape", pystr, end - 2);
458 goto bail;
459 }
460 }
461 else {
462 c = 0;
463 next++;
464 end = next + 4;
465 if (end >= len) {
466 raise_errmsg("Invalid \\uXXXX escape", pystr, next - 1);
467 goto bail;
468 }
469 /* Decode 4 hex digits */
470 for (; next < end; next++) {
471 Py_ssize_t shl = (end - next - 1) << 2;
472 Py_UNICODE digit = buf[next];
473 switch (digit) {
474 case '0': case '1': case '2': case '3': case '4':
475 case '5': case '6': case '7': case '8': case '9':
476 c |= (digit - '0') << shl; break;
477 case 'a': case 'b': case 'c': case 'd': case 'e':
478 case 'f':
479 c |= (digit - 'a' + 10) << shl; break;
480 case 'A': case 'B': case 'C': case 'D': case 'E':
481 case 'F':
482 c |= (digit - 'A' + 10) << shl; break;
483 default:
484 raise_errmsg("Invalid \\uXXXX escape", pystr, end - 5);
485 goto bail;
486 }
487 }
488#ifdef Py_UNICODE_WIDE
489 /* Surrogate pair */
490 if (c >= 0xd800 && c <= 0xdbff) {
491 Py_UNICODE c2 = 0;
492 if (end + 6 >= len) {
493 raise_errmsg("Invalid \\uXXXX\\uXXXX surrogate pair", pystr,
494 end - 5);
495 }
496 if (buf[next++] != '\\' || buf[next++] != 'u') {
497 raise_errmsg("Invalid \\uXXXX\\uXXXX surrogate pair", pystr,
498 end - 5);
499 }
500 end += 6;
501 /* Decode 4 hex digits */
502 for (; next < end; next++) {
503 Py_ssize_t shl = (end - next - 1) << 2;
504 Py_UNICODE digit = buf[next];
505 switch (digit) {
506 case '0': case '1': case '2': case '3': case '4':
507 case '5': case '6': case '7': case '8': case '9':
508 c2 |= (digit - '0') << shl; break;
509 case 'a': case 'b': case 'c': case 'd': case 'e':
510 case 'f':
511 c2 |= (digit - 'a' + 10) << shl; break;
512 case 'A': case 'B': case 'C': case 'D': case 'E':
513 case 'F':
514 c2 |= (digit - 'A' + 10) << shl; break;
515 default:
516 raise_errmsg("Invalid \\uXXXX escape", pystr, end - 5);
517 goto bail;
518 }
519 }
520 c = 0x10000 + (((c - 0xd800) << 10) | (c2 - 0xdc00));
521 }
522#endif
523 }
524 chunk = PyUnicode_FromUnicode(&c, 1);
525 if (chunk == NULL) {
526 goto bail;
527 }
528 if (PyList_Append(chunks, chunk)) {
529 goto bail;
530 }
531 Py_DECREF(chunk);
532 }
533
534 rval = join_list_unicode(chunks);
535 if (rval == NULL) {
536 goto bail;
537 }
538 Py_DECREF(chunks);
539 chunks = NULL;
540 return Py_BuildValue("(Nn)", rval, end);
541bail:
542 Py_XDECREF(chunks);
543 return NULL;
544}
545
546PyDoc_STRVAR(pydoc_scanstring,
547"scanstring(str_or_bytes, end, encoding) -> (bytes, end)\n");
548
549static PyObject *
550py_scanstring(PyObject* self, PyObject *args)
551{
552 PyObject *pystr;
553 Py_ssize_t end;
554 char *encoding = NULL;
555 int strict = 0;
556 if (!PyArg_ParseTuple(args, "On|zi:scanstring", &pystr, &end, &encoding, &strict)) {
557 return NULL;
558 }
559 if (encoding == NULL) {
560 encoding = DEFAULT_ENCODING;
561 }
562 if (PyString_Check(pystr)) {
563 return scanstring_str(pystr, end, encoding, strict);
564 }
565 else if (PyUnicode_Check(pystr)) {
566 return scanstring_unicode(pystr, end, strict);
567 }
568 else {
569 PyErr_Format(PyExc_TypeError,
570 "first argument must be a string or bytes, not %.80s",
571 Py_TYPE(pystr)->tp_name);
572 return NULL;
573 }
574}
575
576PyDoc_STRVAR(pydoc_encode_basestring_ascii,
577"encode_basestring_ascii(str_or_bytes) -> bytes\n");
578
579static PyObject *
580py_encode_basestring_ascii(PyObject* self, PyObject *pystr)
581{
582 PyObject *rval;
583 /* METH_O */
584 if (PyString_Check(pystr)) {
585 rval = ascii_escape_str(pystr);
586 }
587 else if (PyUnicode_Check(pystr)) {
588 rval = ascii_escape_unicode(pystr);
589 }
590 else {
591 PyErr_Format(PyExc_TypeError,
592 "first argument must be a string or unicode, not %.80s",
593 Py_TYPE(pystr)->tp_name);
594 return NULL;
595 }
596 if (PyString_Check(rval)) {
597 PyObject *urval = PyUnicode_DecodeASCII(PyString_AS_STRING(rval), PyString_GET_SIZE(rval), NULL);
598 Py_DECREF(rval);
599 return urval;
600 }
601 return rval;
602}
603
604static PyMethodDef json_methods[] = {
605 {"encode_basestring_ascii", (PyCFunction)py_encode_basestring_ascii,
606 METH_O, pydoc_encode_basestring_ascii},
607 {"scanstring", (PyCFunction)py_scanstring, METH_VARARGS,
608 pydoc_scanstring},
609 {NULL, NULL, 0, NULL}
610};
611
612PyDoc_STRVAR(module_doc,
613"json speedups\n");
614
615void
616init_json(void)
617{
618 PyObject *m;
619 m = Py_InitModule3("_json", json_methods, module_doc);
620}