1 /* ------------------------------------------------------------------------
3 Python Codec Registry and support functions
5 Written by Marc-Andre Lemburg (mal@lemburg.com).
7 Copyright (c) Corporation for National Research Initiatives.
9 ------------------------------------------------------------------------ */
14 /* --- Codec Registry ----------------------------------------------------- */
16 /* Import the standard encodings package which will register the first
17 codec search function.
19 This is done in a lazy way so that the Unicode implementation does
20 not downgrade startup time of scripts not needing it.
22 ImportErrors are silently ignored by this function. Only one try is
27 static int _PyCodecRegistry_Init(void); /* Forward */
29 int PyCodec_Register(PyObject
*search_function
)
31 PyInterpreterState
*interp
= PyThreadState_Get()->interp
;
32 if (interp
->codec_search_path
== NULL
&& _PyCodecRegistry_Init())
34 if (search_function
== NULL
) {
38 if (!PyCallable_Check(search_function
)) {
39 PyErr_SetString(PyExc_TypeError
,
40 "argument must be callable");
43 return PyList_Append(interp
->codec_search_path
, search_function
);
49 /* Convert a string to a normalized Python string: all characters are
50 converted to lower case, spaces are replaced with underscores. */
53 PyObject
*normalizestring(const char *string
)
56 size_t len
= strlen(string
);
61 PyErr_SetString(PyExc_OverflowError
, "string is too large");
65 v
= PyString_FromStringAndSize(NULL
, (int)len
);
68 p
= PyString_AS_STRING(v
);
69 for (i
= 0; i
< len
; i
++) {
70 register char ch
= string
[i
];
80 /* Lookup the given encoding and return a tuple providing the codec
83 The encoding string is looked up converted to all lower-case
84 characters. This makes encodings looked up through this mechanism
85 effectively case-insensitive.
87 If no codec is found, a LookupError is set and NULL returned.
89 As side effect, this tries to load the encodings package, if not
90 yet done. This is part of the lazy load strategy for the encodings
95 PyObject
*_PyCodec_Lookup(const char *encoding
)
97 PyInterpreterState
*interp
;
98 PyObject
*result
, *args
= NULL
, *v
;
101 if (encoding
== NULL
) {
106 interp
= PyThreadState_Get()->interp
;
107 if (interp
->codec_search_path
== NULL
&& _PyCodecRegistry_Init())
110 /* Convert the encoding to a normalized Python string: all
111 characters are converted to lower case, spaces and hyphens are
112 replaced with underscores. */
113 v
= normalizestring(encoding
);
116 PyString_InternInPlace(&v
);
118 /* First, try to lookup the name in the registry dictionary */
119 result
= PyDict_GetItem(interp
->codec_search_cache
, v
);
120 if (result
!= NULL
) {
126 /* Next, scan the search functions in order of registration */
127 args
= PyTuple_New(1);
130 PyTuple_SET_ITEM(args
,0,v
);
132 len
= PyList_Size(interp
->codec_search_path
);
136 PyErr_SetString(PyExc_LookupError
,
137 "no codec search functions registered: "
138 "can't find encoding");
142 for (i
= 0; i
< len
; i
++) {
145 func
= PyList_GetItem(interp
->codec_search_path
, i
);
148 result
= PyEval_CallObject(func
, args
);
151 if (result
== Py_None
) {
155 if (!PyTuple_Check(result
) || PyTuple_GET_SIZE(result
) != 4) {
156 PyErr_SetString(PyExc_TypeError
,
157 "codec search functions must return 4-tuples");
164 /* XXX Perhaps we should cache misses too ? */
165 PyErr_Format(PyExc_LookupError
,
166 "unknown encoding: %s", encoding
);
170 /* Cache and return the result */
171 PyDict_SetItem(interp
->codec_search_cache
, v
, result
);
181 PyObject
*args_tuple(PyObject
*object
,
186 args
= PyTuple_New(1 + (errors
!= NULL
));
190 PyTuple_SET_ITEM(args
,0,object
);
194 v
= PyString_FromString(errors
);
199 PyTuple_SET_ITEM(args
, 1, v
);
204 /* Build a codec by calling factory(stream[,errors]) or just
205 factory(errors) depending on whether the given parameters are
209 PyObject
*build_stream_codec(PyObject
*factory
,
213 PyObject
*args
, *codec
;
215 args
= args_tuple(stream
, errors
);
219 codec
= PyEval_CallObject(factory
, args
);
224 /* Convenience APIs to query the Codec registry.
226 All APIs return a codec object with incremented refcount.
230 PyObject
*PyCodec_Encoder(const char *encoding
)
235 codecs
= _PyCodec_Lookup(encoding
);
238 v
= PyTuple_GET_ITEM(codecs
,0);
247 PyObject
*PyCodec_Decoder(const char *encoding
)
252 codecs
= _PyCodec_Lookup(encoding
);
255 v
= PyTuple_GET_ITEM(codecs
,1);
264 PyObject
*PyCodec_StreamReader(const char *encoding
,
268 PyObject
*codecs
, *ret
;
270 codecs
= _PyCodec_Lookup(encoding
);
273 ret
= build_stream_codec(PyTuple_GET_ITEM(codecs
,2),stream
,errors
);
281 PyObject
*PyCodec_StreamWriter(const char *encoding
,
285 PyObject
*codecs
, *ret
;
287 codecs
= _PyCodec_Lookup(encoding
);
290 ret
= build_stream_codec(PyTuple_GET_ITEM(codecs
,3),stream
,errors
);
298 /* Encode an object (e.g. an Unicode object) using the given encoding
299 and return the resulting encoded object (usually a Python string).
301 errors is passed to the encoder factory as argument if non-NULL. */
303 PyObject
*PyCodec_Encode(PyObject
*object
,
304 const char *encoding
,
307 PyObject
*encoder
= NULL
;
308 PyObject
*args
= NULL
, *result
;
311 encoder
= PyCodec_Encoder(encoding
);
315 args
= args_tuple(object
, errors
);
319 result
= PyEval_CallObject(encoder
,args
);
323 if (!PyTuple_Check(result
) ||
324 PyTuple_GET_SIZE(result
) != 2) {
325 PyErr_SetString(PyExc_TypeError
,
326 "encoder must return a tuple (object,integer)");
329 v
= PyTuple_GET_ITEM(result
,0);
331 /* We don't check or use the second (integer) entry. */
344 /* Decode an object (usually a Python string) using the given encoding
345 and return an equivalent object (e.g. an Unicode object).
347 errors is passed to the decoder factory as argument if non-NULL. */
349 PyObject
*PyCodec_Decode(PyObject
*object
,
350 const char *encoding
,
353 PyObject
*decoder
= NULL
;
354 PyObject
*args
= NULL
, *result
= NULL
;
357 decoder
= PyCodec_Decoder(encoding
);
361 args
= args_tuple(object
, errors
);
365 result
= PyEval_CallObject(decoder
,args
);
368 if (!PyTuple_Check(result
) ||
369 PyTuple_GET_SIZE(result
) != 2) {
370 PyErr_SetString(PyExc_TypeError
,
371 "decoder must return a tuple (object,integer)");
374 v
= PyTuple_GET_ITEM(result
,0);
376 /* We don't check or use the second (integer) entry. */
390 /* Register the error handling callback function error under the name
391 name. This function will be called by the codec when it encounters
392 an unencodable characters/undecodable bytes and doesn't know the
393 callback name, when name is specified as the error parameter
394 in the call to the encode/decode function.
395 Return 0 on success, -1 on error */
396 int PyCodec_RegisterError(const char *name
, PyObject
*error
)
398 PyInterpreterState
*interp
= PyThreadState_Get()->interp
;
399 if (interp
->codec_search_path
== NULL
&& _PyCodecRegistry_Init())
401 if (!PyCallable_Check(error
)) {
402 PyErr_SetString(PyExc_TypeError
, "handler must be callable");
405 return PyDict_SetItemString(interp
->codec_error_registry
,
406 (char *)name
, error
);
409 /* Lookup the error handling callback function registered under the
410 name error. As a special case NULL can be passed, in which case
411 the error handling callback for strict encoding will be returned. */
412 PyObject
*PyCodec_LookupError(const char *name
)
414 PyObject
*handler
= NULL
;
416 PyInterpreterState
*interp
= PyThreadState_Get()->interp
;
417 if (interp
->codec_search_path
== NULL
&& _PyCodecRegistry_Init())
422 handler
= PyDict_GetItemString(interp
->codec_error_registry
, (char *)name
);
424 PyErr_Format(PyExc_LookupError
, "unknown error handler name '%.400s'", name
);
430 static void wrong_exception_type(PyObject
*exc
)
432 PyObject
*type
= PyObject_GetAttrString(exc
, "__class__");
434 PyObject
*name
= PyObject_GetAttrString(type
, "__name__");
437 PyObject
*string
= PyObject_Str(name
);
439 if (string
!= NULL
) {
440 PyErr_Format(PyExc_TypeError
,
441 "don't know how to handle %.400s in error callback",
442 PyString_AS_STRING(string
));
449 PyObject
*PyCodec_StrictErrors(PyObject
*exc
)
451 if (PyInstance_Check(exc
))
452 PyErr_SetObject((PyObject
*)((PyInstanceObject
*)exc
)->in_class
,
455 PyErr_SetString(PyExc_TypeError
, "codec must pass exception instance");
460 #ifdef Py_USING_UNICODE
461 PyObject
*PyCodec_IgnoreErrors(PyObject
*exc
)
464 if (PyObject_IsInstance(exc
, PyExc_UnicodeEncodeError
)) {
465 if (PyUnicodeEncodeError_GetEnd(exc
, &end
))
468 else if (PyObject_IsInstance(exc
, PyExc_UnicodeDecodeError
)) {
469 if (PyUnicodeDecodeError_GetEnd(exc
, &end
))
472 else if (PyObject_IsInstance(exc
, PyExc_UnicodeTranslateError
)) {
473 if (PyUnicodeTranslateError_GetEnd(exc
, &end
))
477 wrong_exception_type(exc
);
480 /* ouch: passing NULL, 0, pos gives None instead of u'' */
481 return Py_BuildValue("(u#i)", &end
, 0, end
);
485 PyObject
*PyCodec_ReplaceErrors(PyObject
*exc
)
492 if (PyObject_IsInstance(exc
, PyExc_UnicodeEncodeError
)) {
495 if (PyUnicodeEncodeError_GetStart(exc
, &start
))
497 if (PyUnicodeEncodeError_GetEnd(exc
, &end
))
499 res
= PyUnicode_FromUnicode(NULL
, end
-start
);
502 for (p
= PyUnicode_AS_UNICODE(res
), i
= start
;
505 restuple
= Py_BuildValue("(Oi)", res
, end
);
509 else if (PyObject_IsInstance(exc
, PyExc_UnicodeDecodeError
)) {
510 Py_UNICODE res
= Py_UNICODE_REPLACEMENT_CHARACTER
;
511 if (PyUnicodeDecodeError_GetEnd(exc
, &end
))
513 return Py_BuildValue("(u#i)", &res
, 1, end
);
515 else if (PyObject_IsInstance(exc
, PyExc_UnicodeTranslateError
)) {
518 if (PyUnicodeTranslateError_GetStart(exc
, &start
))
520 if (PyUnicodeTranslateError_GetEnd(exc
, &end
))
522 res
= PyUnicode_FromUnicode(NULL
, end
-start
);
525 for (p
= PyUnicode_AS_UNICODE(res
), i
= start
;
527 *p
= Py_UNICODE_REPLACEMENT_CHARACTER
;
528 restuple
= Py_BuildValue("(Oi)", res
, end
);
533 wrong_exception_type(exc
);
538 PyObject
*PyCodec_XMLCharRefReplaceErrors(PyObject
*exc
)
540 if (PyObject_IsInstance(exc
, PyExc_UnicodeEncodeError
)) {
550 if (PyUnicodeEncodeError_GetStart(exc
, &start
))
552 if (PyUnicodeEncodeError_GetEnd(exc
, &end
))
554 if (!(object
= PyUnicodeEncodeError_GetObject(exc
)))
556 startp
= PyUnicode_AS_UNICODE(object
);
557 for (p
= startp
+start
, ressize
= 0; p
< startp
+end
; ++p
) {
573 /* allocate replacement */
574 res
= PyUnicode_FromUnicode(NULL
, ressize
);
579 /* generate replacement */
580 for (p
= startp
+start
, outp
= PyUnicode_AS_UNICODE(res
);
581 p
< startp
+end
; ++p
) {
603 else if (*p
<100000) {
607 else if (*p
<1000000) {
616 *outp
++ = '0' + c
/base
;
622 restuple
= Py_BuildValue("(Oi)", res
, end
);
628 wrong_exception_type(exc
);
633 static Py_UNICODE hexdigits
[] = {
634 '0', '1', '2', '3', '4', '5', '6', '7',
635 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
638 PyObject
*PyCodec_BackslashReplaceErrors(PyObject
*exc
)
640 if (PyObject_IsInstance(exc
, PyExc_UnicodeEncodeError
)) {
650 if (PyUnicodeEncodeError_GetStart(exc
, &start
))
652 if (PyUnicodeEncodeError_GetEnd(exc
, &end
))
654 if (!(object
= PyUnicodeEncodeError_GetObject(exc
)))
656 startp
= PyUnicode_AS_UNICODE(object
);
657 for (p
= startp
+start
, ressize
= 0; p
< startp
+end
; ++p
) {
658 if (*p
>= 0x00010000)
660 else if (*p
>= 0x100) {
666 res
= PyUnicode_FromUnicode(NULL
, ressize
);
669 for (p
= startp
+start
, outp
= PyUnicode_AS_UNICODE(res
);
670 p
< startp
+end
; ++p
) {
673 if (c
>= 0x00010000) {
675 *outp
++ = hexdigits
[(c
>>28)&0xf];
676 *outp
++ = hexdigits
[(c
>>24)&0xf];
677 *outp
++ = hexdigits
[(c
>>20)&0xf];
678 *outp
++ = hexdigits
[(c
>>16)&0xf];
679 *outp
++ = hexdigits
[(c
>>12)&0xf];
680 *outp
++ = hexdigits
[(c
>>8)&0xf];
682 else if (c
>= 0x100) {
684 *outp
++ = hexdigits
[(c
>>12)&0xf];
685 *outp
++ = hexdigits
[(c
>>8)&0xf];
689 *outp
++ = hexdigits
[(c
>>4)&0xf];
690 *outp
++ = hexdigits
[c
&0xf];
693 restuple
= Py_BuildValue("(Oi)", res
, end
);
699 wrong_exception_type(exc
);
705 static PyObject
*strict_errors(PyObject
*self
, PyObject
*exc
)
707 return PyCodec_StrictErrors(exc
);
711 #ifdef Py_USING_UNICODE
712 static PyObject
*ignore_errors(PyObject
*self
, PyObject
*exc
)
714 return PyCodec_IgnoreErrors(exc
);
718 static PyObject
*replace_errors(PyObject
*self
, PyObject
*exc
)
720 return PyCodec_ReplaceErrors(exc
);
724 static PyObject
*xmlcharrefreplace_errors(PyObject
*self
, PyObject
*exc
)
726 return PyCodec_XMLCharRefReplaceErrors(exc
);
730 static PyObject
*backslashreplace_errors(PyObject
*self
, PyObject
*exc
)
732 return PyCodec_BackslashReplaceErrors(exc
);
736 static int _PyCodecRegistry_Init(void)
751 #ifdef Py_USING_UNICODE
771 "xmlcharrefreplace_errors",
772 xmlcharrefreplace_errors
,
779 "backslashreplace_errors",
780 backslashreplace_errors
,
787 PyInterpreterState
*interp
= PyThreadState_Get()->interp
;
791 if (interp
->codec_search_path
!= NULL
)
794 interp
->codec_search_path
= PyList_New(0);
795 interp
->codec_search_cache
= PyDict_New();
796 interp
->codec_error_registry
= PyDict_New();
798 if (interp
->codec_error_registry
) {
799 for (i
= 0; i
< sizeof(methods
)/sizeof(methods
[0]); ++i
) {
800 PyObject
*func
= PyCFunction_New(&methods
[i
].def
, NULL
);
803 Py_FatalError("can't initialize codec error registry");
804 res
= PyCodec_RegisterError(methods
[i
].name
, func
);
807 Py_FatalError("can't initialize codec error registry");
811 if (interp
->codec_search_path
== NULL
||
812 interp
->codec_search_cache
== NULL
||
813 interp
->codec_error_registry
== NULL
)
814 Py_FatalError("can't initialize codec registry");
816 mod
= PyImport_ImportModuleEx("encodings", NULL
, NULL
, NULL
);
818 if (PyErr_ExceptionMatches(PyExc_ImportError
)) {
819 /* Ignore ImportErrors... this is done so that
820 distributions can disable the encodings package. Note
821 that other errors are not masked, e.g. SystemErrors
822 raised to inform the user of an error in the Python
823 configuration are still reported back to the user. */