Changes due to added test for fileConfig contributed by Shane Hathaway.
[python.git] / Python / modsupport.c
blob7241936fe92337d6c4e77bfa9109d6780a748113
2 /* Module support implementation */
4 #include "Python.h"
6 typedef double va_double;
8 /* Package context -- the full module name for package imports */
9 char *_Py_PackageContext = NULL;
11 /* Py_InitModule4() parameters:
12 - name is the module name
13 - methods is the list of top-level functions
14 - doc is the documentation string
15 - passthrough is passed as self to functions defined in the module
16 - api_version is the value of PYTHON_API_VERSION at the time the
17 module was compiled
19 Return value is a borrowed reference to the module object; or NULL
20 if an error occurred (in Python 1.4 and before, errors were fatal).
21 Errors may still leak memory.
24 static char api_version_warning[] =
25 "Python C API version mismatch for module %.100s:\
26 This Python has API version %d, module %.100s has version %d.";
28 PyObject *
29 Py_InitModule4(const char *name, PyMethodDef *methods, const char *doc,
30 PyObject *passthrough, int module_api_version)
32 PyObject *m, *d, *v, *n;
33 PyMethodDef *ml;
34 if (!Py_IsInitialized())
35 Py_FatalError("Interpreter not initialized (version mismatch?)");
36 if (module_api_version != PYTHON_API_VERSION) {
37 char message[512];
38 PyOS_snprintf(message, sizeof(message),
39 api_version_warning, name,
40 PYTHON_API_VERSION, name,
41 module_api_version);
42 if (PyErr_Warn(PyExc_RuntimeWarning, message))
43 return NULL;
45 /* Make sure name is fully qualified.
47 This is a bit of a hack: when the shared library is loaded,
48 the module name is "package.module", but the module calls
49 Py_InitModule*() with just "module" for the name. The shared
50 library loader squirrels away the true name of the module in
51 _Py_PackageContext, and Py_InitModule*() will substitute this
52 (if the name actually matches).
54 if (_Py_PackageContext != NULL) {
55 char *p = strrchr(_Py_PackageContext, '.');
56 if (p != NULL && strcmp(name, p+1) == 0) {
57 name = _Py_PackageContext;
58 _Py_PackageContext = NULL;
61 if ((m = PyImport_AddModule(name)) == NULL)
62 return NULL;
63 d = PyModule_GetDict(m);
64 if (methods != NULL) {
65 n = PyString_FromString(name);
66 if (n == NULL)
67 return NULL;
68 for (ml = methods; ml->ml_name != NULL; ml++) {
69 if ((ml->ml_flags & METH_CLASS) ||
70 (ml->ml_flags & METH_STATIC)) {
71 PyErr_SetString(PyExc_ValueError,
72 "module functions cannot set"
73 " METH_CLASS or METH_STATIC");
74 return NULL;
76 v = PyCFunction_NewEx(ml, passthrough, n);
77 if (v == NULL)
78 return NULL;
79 if (PyDict_SetItemString(d, ml->ml_name, v) != 0) {
80 Py_DECREF(v);
81 return NULL;
83 Py_DECREF(v);
85 Py_DECREF(n);
87 if (doc != NULL) {
88 v = PyString_FromString(doc);
89 if (v == NULL || PyDict_SetItemString(d, "__doc__", v) != 0) {
90 Py_XDECREF(v);
91 return NULL;
93 Py_DECREF(v);
95 return m;
99 /* Helper for mkvalue() to scan the length of a format */
101 static int
102 countformat(const char *format, int endchar)
104 int count = 0;
105 int level = 0;
106 while (level > 0 || *format != endchar) {
107 switch (*format) {
108 case '\0':
109 /* Premature end */
110 PyErr_SetString(PyExc_SystemError,
111 "unmatched paren in format");
112 return -1;
113 case '(':
114 case '[':
115 case '{':
116 if (level == 0)
117 count++;
118 level++;
119 break;
120 case ')':
121 case ']':
122 case '}':
123 level--;
124 break;
125 case '#':
126 case '&':
127 case ',':
128 case ':':
129 case ' ':
130 case '\t':
131 break;
132 default:
133 if (level == 0)
134 count++;
136 format++;
138 return count;
142 /* Generic function to create a value -- the inverse of getargs() */
143 /* After an original idea and first implementation by Steven Miale */
145 static PyObject *do_mktuple(const char**, va_list *, int, int);
146 static PyObject *do_mklist(const char**, va_list *, int, int);
147 static PyObject *do_mkdict(const char**, va_list *, int, int);
148 static PyObject *do_mkvalue(const char**, va_list *);
151 static PyObject *
152 do_mkdict(const char **p_format, va_list *p_va, int endchar, int n)
154 PyObject *d;
155 int i;
156 int itemfailed = 0;
157 if (n < 0)
158 return NULL;
159 if ((d = PyDict_New()) == NULL)
160 return NULL;
161 /* Note that we can't bail immediately on error as this will leak
162 refcounts on any 'N' arguments. */
163 for (i = 0; i < n; i+= 2) {
164 PyObject *k, *v;
165 int err;
166 k = do_mkvalue(p_format, p_va);
167 if (k == NULL) {
168 itemfailed = 1;
169 Py_INCREF(Py_None);
170 k = Py_None;
172 v = do_mkvalue(p_format, p_va);
173 if (v == NULL) {
174 itemfailed = 1;
175 Py_INCREF(Py_None);
176 v = Py_None;
178 err = PyDict_SetItem(d, k, v);
179 Py_DECREF(k);
180 Py_DECREF(v);
181 if (err < 0 || itemfailed) {
182 Py_DECREF(d);
183 return NULL;
186 if (d != NULL && **p_format != endchar) {
187 Py_DECREF(d);
188 d = NULL;
189 PyErr_SetString(PyExc_SystemError,
190 "Unmatched paren in format");
192 else if (endchar)
193 ++*p_format;
194 return d;
197 static PyObject *
198 do_mklist(const char **p_format, va_list *p_va, int endchar, int n)
200 PyObject *v;
201 int i;
202 int itemfailed = 0;
203 if (n < 0)
204 return NULL;
205 if ((v = PyList_New(n)) == NULL)
206 return NULL;
207 /* Note that we can't bail immediately on error as this will leak
208 refcounts on any 'N' arguments. */
209 for (i = 0; i < n; i++) {
210 PyObject *w = do_mkvalue(p_format, p_va);
211 if (w == NULL) {
212 itemfailed = 1;
213 Py_INCREF(Py_None);
214 w = Py_None;
216 PyList_SetItem(v, i, w);
218 if (v != NULL && **p_format != endchar) {
219 Py_DECREF(v);
220 v = NULL;
221 PyErr_SetString(PyExc_SystemError,
222 "Unmatched paren in format");
224 else if (endchar)
225 ++*p_format;
226 if (itemfailed) {
227 Py_DECREF(v);
228 v = NULL;
230 return v;
233 #ifdef Py_USING_UNICODE
234 static int
235 _ustrlen(Py_UNICODE *u)
237 int i = 0;
238 Py_UNICODE *v = u;
239 while (*v != 0) { i++; v++; }
240 return i;
242 #endif
244 static PyObject *
245 do_mktuple(const char **p_format, va_list *p_va, int endchar, int n)
247 PyObject *v;
248 int i;
249 int itemfailed = 0;
250 if (n < 0)
251 return NULL;
252 if ((v = PyTuple_New(n)) == NULL)
253 return NULL;
254 /* Note that we can't bail immediately on error as this will leak
255 refcounts on any 'N' arguments. */
256 for (i = 0; i < n; i++) {
257 PyObject *w = do_mkvalue(p_format, p_va);
258 if (w == NULL) {
259 itemfailed = 1;
260 Py_INCREF(Py_None);
261 w = Py_None;
263 PyTuple_SetItem(v, i, w);
265 if (v != NULL && **p_format != endchar) {
266 Py_DECREF(v);
267 v = NULL;
268 PyErr_SetString(PyExc_SystemError,
269 "Unmatched paren in format");
271 else if (endchar)
272 ++*p_format;
273 if (itemfailed) {
274 Py_DECREF(v);
275 v = NULL;
277 return v;
280 static PyObject *
281 do_mkvalue(const char **p_format, va_list *p_va)
283 for (;;) {
284 switch (*(*p_format)++) {
285 case '(':
286 return do_mktuple(p_format, p_va, ')',
287 countformat(*p_format, ')'));
289 case '[':
290 return do_mklist(p_format, p_va, ']',
291 countformat(*p_format, ']'));
293 case '{':
294 return do_mkdict(p_format, p_va, '}',
295 countformat(*p_format, '}'));
297 case 'b':
298 case 'B':
299 case 'h':
300 case 'i':
301 return PyInt_FromLong((long)va_arg(*p_va, int));
303 case 'H':
304 return PyInt_FromLong((long)va_arg(*p_va, unsigned int));
306 case 'I':
308 unsigned int n;
309 n = va_arg(*p_va, unsigned int);
310 if (n > (unsigned long)PyInt_GetMax())
311 return PyLong_FromUnsignedLong((unsigned long)n);
312 else
313 return PyInt_FromLong(n);
316 case 'l':
317 return PyInt_FromLong(va_arg(*p_va, long));
319 case 'k':
321 unsigned long n;
322 n = va_arg(*p_va, unsigned long);
323 if (n > (unsigned long)PyInt_GetMax())
324 return PyLong_FromUnsignedLong(n);
325 else
326 return PyInt_FromLong(n);
329 #ifdef HAVE_LONG_LONG
330 case 'L':
331 return PyLong_FromLongLong((PY_LONG_LONG)va_arg(*p_va, PY_LONG_LONG));
333 case 'K':
334 return PyLong_FromUnsignedLongLong((PY_LONG_LONG)va_arg(*p_va, unsigned PY_LONG_LONG));
335 #endif
336 #ifdef Py_USING_UNICODE
337 case 'u':
339 PyObject *v;
340 Py_UNICODE *u = va_arg(*p_va, Py_UNICODE *);
341 int n;
342 if (**p_format == '#') {
343 ++*p_format;
344 n = va_arg(*p_va, int);
346 else
347 n = -1;
348 if (u == NULL) {
349 v = Py_None;
350 Py_INCREF(v);
352 else {
353 if (n < 0)
354 n = _ustrlen(u);
355 v = PyUnicode_FromUnicode(u, n);
357 return v;
359 #endif
360 case 'f':
361 case 'd':
362 return PyFloat_FromDouble(
363 (double)va_arg(*p_va, va_double));
365 #ifndef WITHOUT_COMPLEX
366 case 'D':
367 return PyComplex_FromCComplex(
368 *((Py_complex *)va_arg(*p_va, Py_complex *)));
369 #endif /* WITHOUT_COMPLEX */
371 case 'c':
373 char p[1];
374 p[0] = va_arg(*p_va, int);
375 return PyString_FromStringAndSize(p, 1);
378 case 's':
379 case 'z':
381 PyObject *v;
382 char *str = va_arg(*p_va, char *);
383 int n;
384 if (**p_format == '#') {
385 ++*p_format;
386 n = va_arg(*p_va, int);
388 else
389 n = -1;
390 if (str == NULL) {
391 v = Py_None;
392 Py_INCREF(v);
394 else {
395 if (n < 0) {
396 size_t m = strlen(str);
397 if (m > INT_MAX) {
398 PyErr_SetString(PyExc_OverflowError,
399 "string too long for Python string");
400 return NULL;
402 n = (int)m;
404 v = PyString_FromStringAndSize(str, n);
406 return v;
409 case 'N':
410 case 'S':
411 case 'O':
412 if (**p_format == '&') {
413 typedef PyObject *(*converter)(void *);
414 converter func = va_arg(*p_va, converter);
415 void *arg = va_arg(*p_va, void *);
416 ++*p_format;
417 return (*func)(arg);
419 else {
420 PyObject *v;
421 v = va_arg(*p_va, PyObject *);
422 if (v != NULL) {
423 if (*(*p_format - 1) != 'N')
424 Py_INCREF(v);
426 else if (!PyErr_Occurred())
427 /* If a NULL was passed
428 * because a call that should
429 * have constructed a value
430 * failed, that's OK, and we
431 * pass the error on; but if
432 * no error occurred it's not
433 * clear that the caller knew
434 * what she was doing. */
435 PyErr_SetString(PyExc_SystemError,
436 "NULL object passed to Py_BuildValue");
437 return v;
440 case ':':
441 case ',':
442 case ' ':
443 case '\t':
444 break;
446 default:
447 PyErr_SetString(PyExc_SystemError,
448 "bad format char passed to Py_BuildValue");
449 return NULL;
456 PyObject *
457 Py_BuildValue(const char *format, ...)
459 va_list va;
460 PyObject* retval;
461 va_start(va, format);
462 retval = Py_VaBuildValue(format, va);
463 va_end(va);
464 return retval;
467 PyObject *
468 Py_VaBuildValue(const char *format, va_list va)
470 const char *f = format;
471 int n = countformat(f, '\0');
472 va_list lva;
474 #ifdef VA_LIST_IS_ARRAY
475 memcpy(lva, va, sizeof(va_list));
476 #else
477 #ifdef __va_copy
478 __va_copy(lva, va);
479 #else
480 lva = va;
481 #endif
482 #endif
484 if (n < 0)
485 return NULL;
486 if (n == 0) {
487 Py_INCREF(Py_None);
488 return Py_None;
490 if (n == 1)
491 return do_mkvalue(&f, &lva);
492 return do_mktuple(&f, &lva, '\0', n);
496 PyObject *
497 PyEval_CallFunction(PyObject *obj, const char *format, ...)
499 va_list vargs;
500 PyObject *args;
501 PyObject *res;
503 va_start(vargs, format);
505 args = Py_VaBuildValue(format, vargs);
506 va_end(vargs);
508 if (args == NULL)
509 return NULL;
511 res = PyEval_CallObject(obj, args);
512 Py_DECREF(args);
514 return res;
518 PyObject *
519 PyEval_CallMethod(PyObject *obj, const char *methodname, const char *format, ...)
521 va_list vargs;
522 PyObject *meth;
523 PyObject *args;
524 PyObject *res;
526 meth = PyObject_GetAttrString(obj, methodname);
527 if (meth == NULL)
528 return NULL;
530 va_start(vargs, format);
532 args = Py_VaBuildValue(format, vargs);
533 va_end(vargs);
535 if (args == NULL) {
536 Py_DECREF(meth);
537 return NULL;
540 res = PyEval_CallObject(meth, args);
541 Py_DECREF(meth);
542 Py_DECREF(args);
544 return res;
548 PyModule_AddObject(PyObject *m, const char *name, PyObject *o)
550 PyObject *dict;
551 if (!PyModule_Check(m)) {
552 PyErr_SetString(PyExc_TypeError,
553 "PyModule_AddObject() needs module as first arg");
554 return -1;
556 if (!o) {
557 if (!PyErr_Occurred())
558 PyErr_SetString(PyExc_TypeError,
559 "PyModule_AddObject() needs non-NULL value");
560 return -1;
563 dict = PyModule_GetDict(m);
564 if (dict == NULL) {
565 /* Internal error -- modules must have a dict! */
566 PyErr_Format(PyExc_SystemError, "module '%s' has no __dict__",
567 PyModule_GetName(m));
568 return -1;
570 if (PyDict_SetItemString(dict, name, o))
571 return -1;
572 Py_DECREF(o);
573 return 0;
576 int
577 PyModule_AddIntConstant(PyObject *m, const char *name, long value)
579 return PyModule_AddObject(m, name, PyInt_FromLong(value));
582 int
583 PyModule_AddStringConstant(PyObject *m, const char *name, const char *value)
585 return PyModule_AddObject(m, name, PyString_FromString(value));