blob: 8ddfc8821a832e6ccfa89d0cc7abe7b5f652ddc2 [file] [log] [blame]
Brett Cannone9746892008-04-12 23:44:07 +00001#include "Python.h"
2#include "frameobject.h"
3
4#define MODULE_NAME "_warnings"
5#define DEFAULT_ACTION_NAME "default_action"
6
7PyDoc_STRVAR(warnings__doc__,
8MODULE_NAME " provides basic warning filtering support.\n"
9"It is a helper module to speed up interpreter start-up.");
10
11/* Both 'filters' and 'onceregistry' can be set in warnings.py;
12 get_warnings_attr() will reset these variables accordingly. */
13static PyObject *_filters; /* List */
14static PyObject *_once_registry; /* Dict */
15
16
17static int
18check_matched(PyObject *obj, PyObject *arg)
19{
20 PyObject *result;
21 int rc;
22
23 if (obj == Py_None)
24 return 1;
25 result = PyObject_CallMethod(obj, "match", "O", arg);
26 if (result == NULL)
27 return -1;
28
29 rc = PyObject_IsTrue(result);
30 Py_DECREF(result);
31 return rc;
32}
33
34/*
35 Returns a new reference.
36 A NULL return value can mean false or an error.
37*/
38static PyObject *
39get_warnings_attr(const char *attr)
40{
41 static PyObject *warnings_str = NULL;
42 PyObject *all_modules;
43 PyObject *warnings_module;
44 int result;
45
46 if (warnings_str == NULL) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +000047 warnings_str = PyString_InternFromString("warnings");
Brett Cannone9746892008-04-12 23:44:07 +000048 if (warnings_str == NULL)
49 return NULL;
50 }
51
52 all_modules = PyImport_GetModuleDict();
53 result = PyDict_Contains(all_modules, warnings_str);
54 if (result == -1 || result == 0)
55 return NULL;
56
57 warnings_module = PyDict_GetItem(all_modules, warnings_str);
58 if (!PyObject_HasAttrString(warnings_module, attr))
59 return NULL;
60 return PyObject_GetAttrString(warnings_module, attr);
61}
62
63
Amaury Forgeot d'Arcf9e7ebe2008-04-14 20:07:48 +000064static PyObject *
Brett Cannone9746892008-04-12 23:44:07 +000065get_once_registry(void)
66{
67 PyObject *registry;
68
69 registry = get_warnings_attr("onceregistry");
70 if (registry == NULL) {
71 if (PyErr_Occurred())
72 return NULL;
73 return _once_registry;
74 }
75 Py_DECREF(_once_registry);
76 _once_registry = registry;
77 return registry;
78}
79
80
81/* The item is a borrowed reference. */
82static const char *
83get_filter(PyObject *category, PyObject *text, Py_ssize_t lineno,
84 PyObject *module, PyObject **item)
85{
86 PyObject *action, *m, *d;
87 Py_ssize_t i;
88 PyObject *warnings_filters;
89
90 warnings_filters = get_warnings_attr("filters");
91 if (warnings_filters == NULL) {
92 if (PyErr_Occurred())
93 return NULL;
94 }
95 else {
96 Py_DECREF(_filters);
97 _filters = warnings_filters;
98 }
99
100 if (!PyList_Check(_filters)) {
101 PyErr_SetString(PyExc_ValueError,
102 MODULE_NAME ".filters must be a list");
103 return NULL;
104 }
105
106 /* _filters could change while we are iterating over it. */
107 for (i = 0; i < PyList_GET_SIZE(_filters); i++) {
108 PyObject *tmp_item, *action, *msg, *cat, *mod, *ln_obj;
109 Py_ssize_t ln;
110 int is_subclass, good_msg, good_mod;
111
112 tmp_item = *item = PyList_GET_ITEM(_filters, i);
113 if (PyTuple_Size(tmp_item) != 5) {
114 PyErr_Format(PyExc_ValueError,
115 MODULE_NAME ".filters item %zd isn't a 5-tuple", i);
116 return NULL;
117 }
118
119 /* Python code: action, msg, cat, mod, ln = item */
120 action = PyTuple_GET_ITEM(tmp_item, 0);
121 msg = PyTuple_GET_ITEM(tmp_item, 1);
122 cat = PyTuple_GET_ITEM(tmp_item, 2);
123 mod = PyTuple_GET_ITEM(tmp_item, 3);
124 ln_obj = PyTuple_GET_ITEM(tmp_item, 4);
125
126 good_msg = check_matched(msg, text);
127 good_mod = check_matched(mod, module);
128 is_subclass = PyObject_IsSubclass(category, cat);
129 ln = PyInt_AsSsize_t(ln_obj);
130 if (good_msg == -1 || good_mod == -1 || is_subclass == -1 ||
131 (ln == -1 && PyErr_Occurred()))
132 return NULL;
133
134 if (good_msg && is_subclass && good_mod && (ln == 0 || lineno == ln))
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000135 return PyString_AsString(action);
Brett Cannone9746892008-04-12 23:44:07 +0000136 }
137
138 m = PyImport_ImportModule(MODULE_NAME);
139 if (m == NULL)
140 return NULL;
141 d = PyModule_GetDict(m);
142 Py_DECREF(m);
143 if (d == NULL)
144 return NULL;
145 action = PyDict_GetItemString(d, DEFAULT_ACTION_NAME);
146 if (action != NULL)
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000147 return PyString_AsString(action);
Brett Cannone9746892008-04-12 23:44:07 +0000148
149 PyErr_SetString(PyExc_ValueError,
150 MODULE_NAME "." DEFAULT_ACTION_NAME " not found");
151 return NULL;
152}
153
154static int
155already_warned(PyObject *registry, PyObject *key, int should_set)
156{
157 PyObject *already_warned;
158
159 if (key == NULL)
160 return -1;
161
162 already_warned = PyDict_GetItem(registry, key);
163 if (already_warned != NULL) {
164 int rc = PyObject_IsTrue(already_warned);
165 if (rc != 0)
166 return rc;
167 }
168
169 /* This warning wasn't found in the registry, set it. */
170 if (should_set)
171 return PyDict_SetItem(registry, key, Py_True);
172 return 0;
173}
174
175/* New reference. */
176static PyObject *
177normalize_module(PyObject *filename)
178{
179 PyObject *module;
180 const char *mod_str;
181 Py_ssize_t len;
182
183 int rc = PyObject_IsTrue(filename);
184 if (rc == -1)
185 return NULL;
186 else if (rc == 0)
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000187 return PyString_FromString("<unknown>");
Brett Cannone9746892008-04-12 23:44:07 +0000188
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000189 mod_str = PyString_AsString(filename);
Brett Cannone9746892008-04-12 23:44:07 +0000190 if (mod_str == NULL)
191 return NULL;
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000192 len = PyString_Size(filename);
Brett Cannone9746892008-04-12 23:44:07 +0000193 if (len < 0)
194 return NULL;
195 if (len >= 3 &&
196 strncmp(mod_str + (len - 3), ".py", 3) == 0) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000197 module = PyString_FromStringAndSize(mod_str, len-3);
Brett Cannone9746892008-04-12 23:44:07 +0000198 }
199 else {
200 module = filename;
201 Py_INCREF(module);
202 }
203 return module;
204}
205
206static int
207update_registry(PyObject *registry, PyObject *text, PyObject *category,
208 int add_zero)
209{
210 PyObject *altkey, *zero = NULL;
211 int rc;
212
213 if (add_zero) {
214 zero = PyInt_FromLong(0);
215 if (zero == NULL)
216 return -1;
217 altkey = PyTuple_Pack(3, text, category, zero);
218 }
219 else
220 altkey = PyTuple_Pack(2, text, category);
221
222 rc = already_warned(registry, altkey, 1);
223 Py_XDECREF(zero);
224 Py_XDECREF(altkey);
225 return rc;
226}
227
228static void
229show_warning(PyObject *filename, int lineno, PyObject *text, PyObject
230 *category, PyObject *sourceline)
231{
Brett Cannon8a232cc2008-05-05 05:32:07 +0000232 PyObject *f_stderr;
233 PyObject *name;
Brett Cannone9746892008-04-12 23:44:07 +0000234 char lineno_str[128];
235
236 PyOS_snprintf(lineno_str, sizeof(lineno_str), ":%d: ", lineno);
237
238 name = PyObject_GetAttrString(category, "__name__");
239 if (name == NULL) /* XXX Can an object lack a '__name__' attribute? */
240 return;
241
242 f_stderr = PySys_GetObject("stderr");
243 if (f_stderr == NULL) {
244 fprintf(stderr, "lost sys.stderr\n");
245 Py_DECREF(name);
246 return;
247 }
248
249 /* Print "filename:lineno: category: text\n" */
250 PyFile_WriteObject(filename, f_stderr, Py_PRINT_RAW);
251 PyFile_WriteString(lineno_str, f_stderr);
252 PyFile_WriteObject(name, f_stderr, Py_PRINT_RAW);
253 PyFile_WriteString(": ", f_stderr);
254 PyFile_WriteObject(text, f_stderr, Py_PRINT_RAW);
255 PyFile_WriteString("\n", f_stderr);
256 Py_XDECREF(name);
257
258 /* Print " source_line\n" */
Brett Cannone9746892008-04-12 23:44:07 +0000259 if (sourceline) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000260 char *source_line_str = PyString_AS_STRING(sourceline);
Brett Cannone9746892008-04-12 23:44:07 +0000261 while (*source_line_str == ' ' || *source_line_str == '\t' ||
262 *source_line_str == '\014')
263 source_line_str++;
264
265 PyFile_WriteString(source_line_str, f_stderr);
266 PyFile_WriteString("\n", f_stderr);
267 }
268 else
Amaury Forgeot d'Arc2252d112008-07-11 21:45:06 +0000269 _Py_DisplaySourceLine(f_stderr, PyString_AS_STRING(filename),
270 lineno, 2);
Brett Cannone9746892008-04-12 23:44:07 +0000271 PyErr_Clear();
272}
273
274static PyObject *
Brett Cannon8a232cc2008-05-05 05:32:07 +0000275warn_explicit(PyObject *category, PyObject *message,
Brett Cannone9746892008-04-12 23:44:07 +0000276 PyObject *filename, int lineno,
277 PyObject *module, PyObject *registry, PyObject *sourceline)
278{
279 PyObject *key = NULL, *text = NULL, *result = NULL, *lineno_obj = NULL;
280 PyObject *item = Py_None;
281 const char *action;
282 int rc;
Brett Cannondea1b562008-06-27 00:31:13 +0000283
284 if (registry && !PyDict_Check(registry) && (registry != Py_None)) {
285 PyErr_SetString(PyExc_TypeError, "'registry' must be a dict");
286 return NULL;
287 }
Brett Cannone9746892008-04-12 23:44:07 +0000288
289 /* Normalize module. */
290 if (module == NULL) {
291 module = normalize_module(filename);
292 if (module == NULL)
293 return NULL;
294 }
295 else
296 Py_INCREF(module);
297
298 /* Normalize message. */
299 Py_INCREF(message); /* DECREF'ed in cleanup. */
300 rc = PyObject_IsInstance(message, PyExc_Warning);
301 if (rc == -1) {
302 goto cleanup;
303 }
304 if (rc == 1) {
305 text = PyObject_Str(message);
306 category = (PyObject*)message->ob_type;
307 }
308 else {
309 text = message;
310 message = PyObject_CallFunction(category, "O", message);
Brett Cannondea1b562008-06-27 00:31:13 +0000311 if (message == NULL)
312 goto cleanup;
Brett Cannone9746892008-04-12 23:44:07 +0000313 }
314
315 lineno_obj = PyInt_FromLong(lineno);
316 if (lineno_obj == NULL)
317 goto cleanup;
318
319 /* Create key. */
320 key = PyTuple_Pack(3, text, category, lineno_obj);
321 if (key == NULL)
322 goto cleanup;
323
Brett Cannondea1b562008-06-27 00:31:13 +0000324 if ((registry != NULL) && (registry != Py_None)) {
Brett Cannone9746892008-04-12 23:44:07 +0000325 rc = already_warned(registry, key, 0);
326 if (rc == -1)
327 goto cleanup;
328 else if (rc == 1)
329 goto return_none;
330 /* Else this warning hasn't been generated before. */
331 }
332
333 action = get_filter(category, text, lineno, module, &item);
334 if (action == NULL)
335 goto cleanup;
336
337 if (strcmp(action, "error") == 0) {
338 PyErr_SetObject(category, message);
339 goto cleanup;
340 }
341
342 /* Store in the registry that we've been here, *except* when the action
343 is "always". */
344 rc = 0;
345 if (strcmp(action, "always") != 0) {
Brett Cannondea1b562008-06-27 00:31:13 +0000346 if (registry != NULL && registry != Py_None &&
347 PyDict_SetItem(registry, key, Py_True) < 0)
Brett Cannone9746892008-04-12 23:44:07 +0000348 goto cleanup;
349 else if (strcmp(action, "ignore") == 0)
350 goto return_none;
351 else if (strcmp(action, "once") == 0) {
Brett Cannondea1b562008-06-27 00:31:13 +0000352 if (registry == NULL || registry == Py_None) {
Brett Cannone9746892008-04-12 23:44:07 +0000353 registry = get_once_registry();
354 if (registry == NULL)
355 goto cleanup;
356 }
357 /* _once_registry[(text, category)] = 1 */
Brett Cannon8a232cc2008-05-05 05:32:07 +0000358 rc = update_registry(registry, text, category, 0);
Brett Cannone9746892008-04-12 23:44:07 +0000359 }
360 else if (strcmp(action, "module") == 0) {
361 /* registry[(text, category, 0)] = 1 */
Brett Cannondea1b562008-06-27 00:31:13 +0000362 if (registry != NULL && registry != Py_None)
Brett Cannon8a232cc2008-05-05 05:32:07 +0000363 rc = update_registry(registry, text, category, 0);
Brett Cannone9746892008-04-12 23:44:07 +0000364 }
365 else if (strcmp(action, "default") != 0) {
366 PyObject *to_str = PyObject_Str(item);
367 const char *err_str = "???";
368
369 if (to_str != NULL)
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000370 err_str = PyString_AS_STRING(to_str);
Brett Cannone9746892008-04-12 23:44:07 +0000371 PyErr_Format(PyExc_RuntimeError,
372 "Unrecognized action (%s) in warnings.filters:\n %s",
373 action, err_str);
374 Py_XDECREF(to_str);
375 goto cleanup;
376 }
377 }
378
Christian Heimes32a66a02008-10-02 19:47:50 +0000379 if (rc == 1) /* Already warned for this module. */
Brett Cannone9746892008-04-12 23:44:07 +0000380 goto return_none;
381 if (rc == 0) {
382 PyObject *show_fxn = get_warnings_attr("showwarning");
383 if (show_fxn == NULL) {
384 if (PyErr_Occurred())
385 goto cleanup;
386 show_warning(filename, lineno, text, category, sourceline);
387 }
388 else {
Brett Cannon6c4cff02009-03-11 04:51:06 +0000389 PyObject *res;
Brett Cannon8a232cc2008-05-05 05:32:07 +0000390
Brett Cannon6c4cff02009-03-11 04:51:06 +0000391 if (!PyMethod_Check(show_fxn) && !PyFunction_Check(show_fxn)) {
392 PyErr_SetString(PyExc_TypeError,
393 "warnings.showwarning() must be set to a "
394 "function or method");
395 Py_DECREF(show_fxn);
396 goto cleanup;
397 }
Brett Cannon8a232cc2008-05-05 05:32:07 +0000398
Brett Cannon6c4cff02009-03-11 04:51:06 +0000399 res = PyObject_CallFunctionObjArgs(show_fxn, message, category,
400 filename, lineno_obj,
401 NULL);
402 Py_DECREF(show_fxn);
403 Py_XDECREF(res);
404 if (res == NULL)
405 goto cleanup;
Brett Cannone9746892008-04-12 23:44:07 +0000406 }
407 }
408 else /* if (rc == -1) */
409 goto cleanup;
410
411 return_none:
412 result = Py_None;
413 Py_INCREF(result);
414
415 cleanup:
416 Py_XDECREF(key);
417 Py_XDECREF(text);
418 Py_XDECREF(lineno_obj);
419 Py_DECREF(module);
Brett Cannondea1b562008-06-27 00:31:13 +0000420 Py_XDECREF(message);
Brett Cannone9746892008-04-12 23:44:07 +0000421 return result; /* Py_None or NULL. */
422}
423
424/* filename, module, and registry are new refs, globals is borrowed */
425/* Returns 0 on error (no new refs), 1 on success */
426static int
427setup_context(Py_ssize_t stack_level, PyObject **filename, int *lineno,
428 PyObject **module, PyObject **registry)
429{
430 PyObject *globals;
431
432 /* Setup globals and lineno. */
433 PyFrameObject *f = PyThreadState_GET()->frame;
Brett Cannone3dcb012008-05-06 04:37:31 +0000434 while (--stack_level > 0 && f != NULL)
Brett Cannone9746892008-04-12 23:44:07 +0000435 f = f->f_back;
Brett Cannone9746892008-04-12 23:44:07 +0000436
437 if (f == NULL) {
438 globals = PyThreadState_Get()->interp->sysdict;
439 *lineno = 1;
440 }
441 else {
442 globals = f->f_globals;
443 *lineno = PyCode_Addr2Line(f->f_code, f->f_lasti);
444 }
445
446 *module = NULL;
447
448 /* Setup registry. */
449 assert(globals != NULL);
450 assert(PyDict_Check(globals));
451 *registry = PyDict_GetItemString(globals, "__warningregistry__");
452 if (*registry == NULL) {
453 int rc;
454
455 *registry = PyDict_New();
456 if (*registry == NULL)
457 return 0;
458
459 rc = PyDict_SetItemString(globals, "__warningregistry__", *registry);
460 if (rc < 0)
461 goto handle_error;
462 }
463 else
464 Py_INCREF(*registry);
465
466 /* Setup module. */
467 *module = PyDict_GetItemString(globals, "__name__");
468 if (*module == NULL) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000469 *module = PyString_FromString("<string>");
Brett Cannone9746892008-04-12 23:44:07 +0000470 if (*module == NULL)
471 goto handle_error;
472 }
473 else
474 Py_INCREF(*module);
475
476 /* Setup filename. */
477 *filename = PyDict_GetItemString(globals, "__file__");
478 if (*filename != NULL) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000479 Py_ssize_t len = PyString_Size(*filename);
480 const char *file_str = PyString_AsString(*filename);
Brett Cannonab9cc1b2008-05-03 01:02:41 +0000481 if (file_str == NULL || (len < 0 && PyErr_Occurred()))
Brett Cannone9746892008-04-12 23:44:07 +0000482 goto handle_error;
483
484 /* if filename.lower().endswith((".pyc", ".pyo")): */
485 if (len >= 4 &&
486 file_str[len-4] == '.' &&
487 tolower(file_str[len-3]) == 'p' &&
488 tolower(file_str[len-2]) == 'y' &&
489 (tolower(file_str[len-1]) == 'c' ||
Brett Cannonab9cc1b2008-05-03 01:02:41 +0000490 tolower(file_str[len-1]) == 'o'))
491 {
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000492 *filename = PyString_FromStringAndSize(file_str, len-1);
Brett Cannonab9cc1b2008-05-03 01:02:41 +0000493 if (*filename == NULL)
494 goto handle_error;
495 }
496 else
Brett Cannone9746892008-04-12 23:44:07 +0000497 Py_INCREF(*filename);
498 }
499 else {
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000500 const char *module_str = PyString_AsString(*module);
Brett Cannone9746892008-04-12 23:44:07 +0000501 if (module_str && strcmp(module_str, "__main__") == 0) {
502 PyObject *argv = PySys_GetObject("argv");
503 if (argv != NULL && PyList_Size(argv) > 0) {
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000504 int is_true;
Brett Cannone9746892008-04-12 23:44:07 +0000505 *filename = PyList_GetItem(argv, 0);
506 Py_INCREF(*filename);
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000507 /* If sys.argv[0] is false, then use '__main__'. */
508 is_true = PyObject_IsTrue(*filename);
509 if (is_true < 0) {
510 Py_DECREF(*filename);
511 goto handle_error;
512 }
513 else if (!is_true) {
514 Py_DECREF(*filename);
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000515 *filename = PyString_FromString("__main__");
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000516 if (*filename == NULL)
517 goto handle_error;
518 }
Brett Cannone9746892008-04-12 23:44:07 +0000519 }
520 else {
521 /* embedded interpreters don't have sys.argv, see bug #839151 */
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000522 *filename = PyString_FromString("__main__");
Brett Cannonab9cc1b2008-05-03 01:02:41 +0000523 if (*filename == NULL)
524 goto handle_error;
Brett Cannone9746892008-04-12 23:44:07 +0000525 }
526 }
527 if (*filename == NULL) {
528 *filename = *module;
529 Py_INCREF(*filename);
530 }
531 }
532
533 return 1;
534
535 handle_error:
536 /* filename not XDECREF'ed here as there is no way to jump here with a
537 dangling reference. */
538 Py_XDECREF(*registry);
539 Py_XDECREF(*module);
540 return 0;
541}
542
543static PyObject *
544get_category(PyObject *message, PyObject *category)
545{
546 int rc;
547
548 /* Get category. */
549 rc = PyObject_IsInstance(message, PyExc_Warning);
550 if (rc == -1)
551 return NULL;
552
553 if (rc == 1)
554 category = (PyObject*)message->ob_type;
555 else if (category == NULL)
556 category = PyExc_UserWarning;
557
558 /* Validate category. */
559 rc = PyObject_IsSubclass(category, PyExc_Warning);
560 if (rc == -1)
561 return NULL;
562 if (rc == 0) {
563 PyErr_SetString(PyExc_ValueError,
564 "category is not a subclass of Warning");
565 return NULL;
566 }
567
568 return category;
569}
570
571static PyObject *
572do_warn(PyObject *message, PyObject *category, Py_ssize_t stack_level)
573{
574 PyObject *filename, *module, *registry, *res;
575 int lineno;
576
577 if (!setup_context(stack_level, &filename, &lineno, &module, &registry))
578 return NULL;
579
580 res = warn_explicit(category, message, filename, lineno, module, registry,
581 NULL);
582 Py_DECREF(filename);
583 Py_DECREF(registry);
584 Py_DECREF(module);
585 return res;
586}
587
588static PyObject *
589warnings_warn(PyObject *self, PyObject *args, PyObject *kwds)
590{
591 static char *kw_list[] = { "message", "category", "stacklevel", 0 };
592 PyObject *message, *category = NULL;
593 Py_ssize_t stack_level = 1;
594
Brett Cannon8a232cc2008-05-05 05:32:07 +0000595 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|On:warn", kw_list,
Brett Cannone9746892008-04-12 23:44:07 +0000596 &message, &category, &stack_level))
597 return NULL;
598
599 category = get_category(message, category);
600 if (category == NULL)
601 return NULL;
602 return do_warn(message, category, stack_level);
603}
604
605static PyObject *
606warnings_warn_explicit(PyObject *self, PyObject *args, PyObject *kwds)
607{
608 static char *kwd_list[] = {"message", "category", "filename", "lineno",
609 "module", "registry", "module_globals", 0};
610 PyObject *message;
611 PyObject *category;
612 PyObject *filename;
613 int lineno;
614 PyObject *module = NULL;
615 PyObject *registry = NULL;
616 PyObject *module_globals = NULL;
617
618 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOOi|OOO:warn_explicit",
619 kwd_list, &message, &category, &filename, &lineno, &module,
620 &registry, &module_globals))
621 return NULL;
622
623 if (module_globals) {
624 static PyObject *get_source_name = NULL;
625 static PyObject *splitlines_name = NULL;
626 PyObject *loader;
627 PyObject *module_name;
628 PyObject *source;
629 PyObject *source_list;
630 PyObject *source_line;
631 PyObject *returned;
632
633 if (get_source_name == NULL) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000634 get_source_name = PyString_InternFromString("get_source");
Brett Cannone9746892008-04-12 23:44:07 +0000635 if (!get_source_name)
636 return NULL;
637 }
638 if (splitlines_name == NULL) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000639 splitlines_name = PyString_InternFromString("splitlines");
Brett Cannone9746892008-04-12 23:44:07 +0000640 if (!splitlines_name)
641 return NULL;
642 }
643
644 /* Check/get the requisite pieces needed for the loader. */
645 loader = PyDict_GetItemString(module_globals, "__loader__");
646 module_name = PyDict_GetItemString(module_globals, "__name__");
647
648 if (loader == NULL || module_name == NULL)
649 goto standard_call;
650
651 /* Make sure the loader implements the optional get_source() method. */
652 if (!PyObject_HasAttrString(loader, "get_source"))
653 goto standard_call;
654 /* Call get_source() to get the source code. */
655 source = PyObject_CallMethodObjArgs(loader, get_source_name,
656 module_name, NULL);
657 if (!source)
658 return NULL;
659 else if (source == Py_None) {
660 Py_DECREF(Py_None);
661 goto standard_call;
662 }
663
664 /* Split the source into lines. */
665 source_list = PyObject_CallMethodObjArgs(source, splitlines_name,
666 NULL);
667 Py_DECREF(source);
668 if (!source_list)
669 return NULL;
670
671 /* Get the source line. */
672 source_line = PyList_GetItem(source_list, lineno-1);
673 if (!source_line) {
674 Py_DECREF(source_list);
675 return NULL;
676 }
677
678 /* Handle the warning. */
679 returned = warn_explicit(category, message, filename, lineno, module,
680 registry, source_line);
681 Py_DECREF(source_list);
682 return returned;
683 }
684
685 standard_call:
686 return warn_explicit(category, message, filename, lineno, module,
687 registry, NULL);
688}
689
690
691/* Function to issue a warning message; may raise an exception. */
692int
693PyErr_WarnEx(PyObject *category, const char *text, Py_ssize_t stack_level)
694{
695 PyObject *res;
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000696 PyObject *message = PyString_FromString(text);
Brett Cannone9746892008-04-12 23:44:07 +0000697 if (message == NULL)
698 return -1;
699
700 if (category == NULL)
701 category = PyExc_RuntimeWarning;
702
703 res = do_warn(message, category, stack_level);
704 Py_DECREF(message);
705 if (res == NULL)
706 return -1;
707 Py_DECREF(res);
708
709 return 0;
710}
711
712/* PyErr_Warn is only for backwards compatability and will be removed.
713 Use PyErr_WarnEx instead. */
714
715#undef PyErr_Warn
716
717PyAPI_FUNC(int)
718PyErr_Warn(PyObject *category, char *text)
719{
720 return PyErr_WarnEx(category, text, 1);
721}
722
723/* Warning with explicit origin */
724int
725PyErr_WarnExplicit(PyObject *category, const char *text,
726 const char *filename_str, int lineno,
727 const char *module_str, PyObject *registry)
728{
729 PyObject *res;
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000730 PyObject *message = PyString_FromString(text);
731 PyObject *filename = PyString_FromString(filename_str);
Brett Cannone9746892008-04-12 23:44:07 +0000732 PyObject *module = NULL;
733 int ret = -1;
734
735 if (message == NULL || filename == NULL)
736 goto exit;
737 if (module_str != NULL) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000738 module = PyString_FromString(module_str);
Brett Cannone9746892008-04-12 23:44:07 +0000739 if (module == NULL)
740 goto exit;
741 }
742
743 if (category == NULL)
744 category = PyExc_RuntimeWarning;
745 res = warn_explicit(category, message, filename, lineno, module, registry,
746 NULL);
747 if (res == NULL)
748 goto exit;
749 Py_DECREF(res);
750 ret = 0;
751
752 exit:
753 Py_XDECREF(message);
754 Py_XDECREF(module);
755 Py_XDECREF(filename);
756 return ret;
757}
758
759
Brett Cannone9746892008-04-12 23:44:07 +0000760PyDoc_STRVAR(warn_doc,
761"Issue a warning, or maybe ignore it or raise an exception.");
762
763PyDoc_STRVAR(warn_explicit_doc,
764"Low-level inferface to warnings functionality.");
765
766static PyMethodDef warnings_functions[] = {
767 {"warn", (PyCFunction)warnings_warn, METH_VARARGS | METH_KEYWORDS,
768 warn_doc},
769 {"warn_explicit", (PyCFunction)warnings_warn_explicit,
770 METH_VARARGS | METH_KEYWORDS, warn_explicit_doc},
Christian Heimes32a66a02008-10-02 19:47:50 +0000771 /* XXX(brett.cannon): add showwarning? */
772 /* XXX(brett.cannon): Reasonable to add formatwarning? */
Brett Cannone9746892008-04-12 23:44:07 +0000773 {NULL, NULL} /* sentinel */
774};
775
776
777static PyObject *
778create_filter(PyObject *category, const char *action)
779{
780 static PyObject *ignore_str = NULL;
781 static PyObject *error_str = NULL;
782 static PyObject *default_str = NULL;
783 PyObject *action_obj = NULL;
784 PyObject *lineno, *result;
785
786 if (!strcmp(action, "ignore")) {
787 if (ignore_str == NULL) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000788 ignore_str = PyString_InternFromString("ignore");
Brett Cannone9746892008-04-12 23:44:07 +0000789 if (ignore_str == NULL)
790 return NULL;
791 }
792 action_obj = ignore_str;
793 }
794 else if (!strcmp(action, "error")) {
795 if (error_str == NULL) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000796 error_str = PyString_InternFromString("error");
Brett Cannone9746892008-04-12 23:44:07 +0000797 if (error_str == NULL)
798 return NULL;
799 }
800 action_obj = error_str;
801 }
802 else if (!strcmp(action, "default")) {
803 if (default_str == NULL) {
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000804 default_str = PyString_InternFromString("default");
Brett Cannone9746892008-04-12 23:44:07 +0000805 if (default_str == NULL)
806 return NULL;
807 }
808 action_obj = default_str;
809 }
810 else {
811 Py_FatalError("unknown action");
812 }
813
814 /* This assumes the line number is zero for now. */
815 lineno = PyInt_FromLong(0);
816 if (lineno == NULL)
817 return NULL;
818 result = PyTuple_Pack(5, action_obj, Py_None, category, Py_None, lineno);
819 Py_DECREF(lineno);
820 return result;
821}
822
823static PyObject *
824init_filters(void)
825{
826 PyObject *filters = PyList_New(3);
827 const char *bytes_action;
828 if (filters == NULL)
829 return NULL;
830
831 PyList_SET_ITEM(filters, 0,
832 create_filter(PyExc_PendingDeprecationWarning, "ignore"));
833 PyList_SET_ITEM(filters, 1, create_filter(PyExc_ImportWarning, "ignore"));
834 if (Py_BytesWarningFlag > 1)
835 bytes_action = "error";
836 else if (Py_BytesWarningFlag)
837 bytes_action = "default";
838 else
839 bytes_action = "ignore";
840 PyList_SET_ITEM(filters, 2, create_filter(PyExc_BytesWarning,
841 bytes_action));
842
843 if (PyList_GET_ITEM(filters, 0) == NULL ||
844 PyList_GET_ITEM(filters, 1) == NULL ||
845 PyList_GET_ITEM(filters, 2) == NULL) {
846 Py_DECREF(filters);
847 return NULL;
848 }
849
850 return filters;
851}
852
853
854PyMODINIT_FUNC
855_PyWarnings_Init(void)
856{
857 PyObject *m, *default_action;
858
859 m = Py_InitModule3(MODULE_NAME, warnings_functions, warnings__doc__);
860 if (m == NULL)
861 return;
862
863 _filters = init_filters();
864 if (_filters == NULL)
865 return;
866 Py_INCREF(_filters);
867 if (PyModule_AddObject(m, "filters", _filters) < 0)
868 return;
869
870 _once_registry = PyDict_New();
871 if (_once_registry == NULL)
872 return;
873 Py_INCREF(_once_registry);
874 if (PyModule_AddObject(m, "once_registry", _once_registry) < 0)
875 return;
876
Gregory P. Smithdd96db62008-06-09 04:58:54 +0000877 default_action = PyString_InternFromString("default");
Brett Cannone9746892008-04-12 23:44:07 +0000878 if (default_action == NULL)
879 return;
880 if (PyModule_AddObject(m, DEFAULT_ACTION_NAME, default_action) < 0)
881 return;
882}