blob: e9384ca1f9cf935665bf436d39154b2a4d0db8ea [file] [log] [blame]
Christian Heimes33fe8092008-04-13 13:53:33 +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) {
47 warnings_str = PyUnicode_InternFromString("warnings");
48 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
Neal Norwitz32dde222008-04-15 06:43:13 +000064static PyObject *
Christian Heimes33fe8092008-04-13 13:53:33 +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 = PyLong_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))
135 return PyUnicode_AsString(action);
136 }
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)
147 return PyUnicode_AsString(action);
148
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)
187 return PyUnicode_FromString("<unknown>");
188
189 mod_str = PyUnicode_AsString(filename);
190 if (mod_str == NULL)
191 return NULL;
192 len = PyUnicode_GetSize(filename);
193 if (len < 0)
194 return NULL;
195 if (len >= 3 &&
196 strncmp(mod_str + (len - 3), ".py", 3) == 0) {
197 module = PyUnicode_FromStringAndSize(mod_str, len-3);
198 }
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 = PyLong_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{
232 PyObject *f_stderr;
233 PyObject *name;
234 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" */
Christian Heimes33fe8092008-04-13 13:53:33 +0000259 if (sourceline) {
260 char *source_line_str = PyUnicode_AsString(sourceline);
261 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
Benjamin Petersone6528212008-07-15 15:32:09 +0000269 Py_DisplaySourceLine(f_stderr, PyUnicode_AsString(filename), lineno, 2);
Christian Heimes33fe8092008-04-13 13:53:33 +0000270 PyErr_Clear();
271}
272
273static PyObject *
274warn_explicit(PyObject *category, PyObject *message,
275 PyObject *filename, int lineno,
276 PyObject *module, PyObject *registry, PyObject *sourceline)
277{
278 PyObject *key = NULL, *text = NULL, *result = NULL, *lineno_obj = NULL;
279 PyObject *item = Py_None;
280 const char *action;
281 int rc;
Brett Cannondb734912008-06-27 00:52:15 +0000282
283 if (registry && !PyDict_Check(registry) && (registry != Py_None)) {
284 PyErr_SetString(PyExc_TypeError, "'registry' must be a dict");
285 return NULL;
286 }
Christian Heimes33fe8092008-04-13 13:53:33 +0000287
288 /* Normalize module. */
289 if (module == NULL) {
290 module = normalize_module(filename);
291 if (module == NULL)
292 return NULL;
293 }
294 else
295 Py_INCREF(module);
296
297 /* Normalize message. */
298 Py_INCREF(message); /* DECREF'ed in cleanup. */
299 rc = PyObject_IsInstance(message, PyExc_Warning);
300 if (rc == -1) {
301 goto cleanup;
302 }
303 if (rc == 1) {
304 text = PyObject_Str(message);
305 category = (PyObject*)message->ob_type;
306 }
307 else {
308 text = message;
309 message = PyObject_CallFunction(category, "O", message);
Brett Cannondb734912008-06-27 00:52:15 +0000310 if (message == NULL)
311 goto cleanup;
Christian Heimes33fe8092008-04-13 13:53:33 +0000312 }
313
314 lineno_obj = PyLong_FromLong(lineno);
315 if (lineno_obj == NULL)
316 goto cleanup;
317
318 /* Create key. */
319 key = PyTuple_Pack(3, text, category, lineno_obj);
320 if (key == NULL)
321 goto cleanup;
322
Brett Cannondb734912008-06-27 00:52:15 +0000323 if ((registry != NULL) && (registry != Py_None)) {
Christian Heimes33fe8092008-04-13 13:53:33 +0000324 rc = already_warned(registry, key, 0);
325 if (rc == -1)
326 goto cleanup;
327 else if (rc == 1)
328 goto return_none;
329 /* Else this warning hasn't been generated before. */
330 }
331
332 action = get_filter(category, text, lineno, module, &item);
333 if (action == NULL)
334 goto cleanup;
335
336 if (strcmp(action, "error") == 0) {
337 PyErr_SetObject(category, message);
338 goto cleanup;
339 }
340
341 /* Store in the registry that we've been here, *except* when the action
342 is "always". */
343 rc = 0;
344 if (strcmp(action, "always") != 0) {
Brett Cannondb734912008-06-27 00:52:15 +0000345 if (registry != NULL && registry != Py_None &&
346 PyDict_SetItem(registry, key, Py_True) < 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000347 goto cleanup;
348 else if (strcmp(action, "ignore") == 0)
349 goto return_none;
350 else if (strcmp(action, "once") == 0) {
Brett Cannondb734912008-06-27 00:52:15 +0000351 if (registry == NULL || registry == Py_None) {
Christian Heimes33fe8092008-04-13 13:53:33 +0000352 registry = get_once_registry();
353 if (registry == NULL)
354 goto cleanup;
355 }
356 /* _once_registry[(text, category)] = 1 */
357 rc = update_registry(registry, text, category, 0);
358 }
359 else if (strcmp(action, "module") == 0) {
360 /* registry[(text, category, 0)] = 1 */
Brett Cannondb734912008-06-27 00:52:15 +0000361 if (registry != NULL && registry != Py_None)
Christian Heimes33fe8092008-04-13 13:53:33 +0000362 rc = update_registry(registry, text, category, 0);
363 }
364 else if (strcmp(action, "default") != 0) {
365 PyObject *to_str = PyObject_Str(item);
366 const char *err_str = "???";
367
368 if (to_str != NULL)
369 err_str = PyUnicode_AsString(to_str);
370 PyErr_Format(PyExc_RuntimeError,
371 "Unrecognized action (%s) in warnings.filters:\n %s",
372 action, err_str);
373 Py_XDECREF(to_str);
374 goto cleanup;
375 }
376 }
377
378 if (rc == 1) // Already warned for this module. */
379 goto return_none;
380 if (rc == 0) {
381 PyObject *show_fxn = get_warnings_attr("showwarning");
382 if (show_fxn == NULL) {
383 if (PyErr_Occurred())
384 goto cleanup;
385 show_warning(filename, lineno, text, category, sourceline);
386 }
387 else {
Christian Heimes8dc226f2008-05-06 23:45:46 +0000388 const char *msg = "functions overriding warnings.showwarning() "
389 "must support the 'line' argument";
390 const char *text_char = PyUnicode_AsString(text);
391
392 if (strcmp(msg, text_char) == 0) {
393 /* Prevent infinite recursion by using built-in implementation
394 of showwarning(). */
395 show_warning(filename, lineno, text, category, sourceline);
396 }
397 else {
398 PyObject *check_fxn;
399 PyObject *defaults;
400 PyObject *res;
401
402 if (PyMethod_Check(show_fxn))
403 check_fxn = PyMethod_Function(show_fxn);
404 else if (PyFunction_Check(show_fxn))
405 check_fxn = show_fxn;
406 else {
407 PyErr_SetString(PyExc_TypeError,
408 "warnings.showwarning() must be set to a "
409 "function or method");
410 Py_DECREF(show_fxn);
411 goto cleanup;
412 }
413
414 defaults = PyFunction_GetDefaults(check_fxn);
415 /* A proper implementation of warnings.showwarning() should
416 have at least two default arguments. */
417 if ((defaults == NULL) || (PyTuple_Size(defaults) < 2)) {
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000418 if (PyErr_WarnEx(PyExc_DeprecationWarning, msg, 1) < 0) {
419 Py_DECREF(show_fxn);
Christian Heimes8dc226f2008-05-06 23:45:46 +0000420 goto cleanup;
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000421 }
Christian Heimes8dc226f2008-05-06 23:45:46 +0000422 }
423 res = PyObject_CallFunctionObjArgs(show_fxn, message, category,
Christian Heimes33fe8092008-04-13 13:53:33 +0000424 filename, lineno_obj,
Christian Heimes33fe8092008-04-13 13:53:33 +0000425 NULL);
Christian Heimes8dc226f2008-05-06 23:45:46 +0000426 Py_DECREF(show_fxn);
427 Py_XDECREF(res);
428 if (res == NULL)
429 goto cleanup;
430 }
Christian Heimes33fe8092008-04-13 13:53:33 +0000431 }
432 }
433 else /* if (rc == -1) */
434 goto cleanup;
435
436 return_none:
437 result = Py_None;
438 Py_INCREF(result);
439
440 cleanup:
441 Py_XDECREF(key);
442 Py_XDECREF(text);
443 Py_XDECREF(lineno_obj);
444 Py_DECREF(module);
Brett Cannondb734912008-06-27 00:52:15 +0000445 Py_XDECREF(message);
Christian Heimes33fe8092008-04-13 13:53:33 +0000446 return result; /* Py_None or NULL. */
447}
448
449/* filename, module, and registry are new refs, globals is borrowed */
450/* Returns 0 on error (no new refs), 1 on success */
451static int
452setup_context(Py_ssize_t stack_level, PyObject **filename, int *lineno,
453 PyObject **module, PyObject **registry)
454{
455 PyObject *globals;
456
457 /* Setup globals and lineno. */
458 PyFrameObject *f = PyThreadState_GET()->frame;
Christian Heimes5d8da202008-05-06 13:58:24 +0000459 while (--stack_level > 0 && f != NULL)
Christian Heimes33fe8092008-04-13 13:53:33 +0000460 f = f->f_back;
Christian Heimes33fe8092008-04-13 13:53:33 +0000461
462 if (f == NULL) {
463 globals = PyThreadState_Get()->interp->sysdict;
464 *lineno = 1;
465 }
466 else {
467 globals = f->f_globals;
468 *lineno = PyCode_Addr2Line(f->f_code, f->f_lasti);
469 }
470
471 *module = NULL;
472
473 /* Setup registry. */
474 assert(globals != NULL);
475 assert(PyDict_Check(globals));
476 *registry = PyDict_GetItemString(globals, "__warningregistry__");
477 if (*registry == NULL) {
478 int rc;
479
480 *registry = PyDict_New();
481 if (*registry == NULL)
482 return 0;
483
484 rc = PyDict_SetItemString(globals, "__warningregistry__", *registry);
485 if (rc < 0)
486 goto handle_error;
487 }
488 else
489 Py_INCREF(*registry);
490
491 /* Setup module. */
492 *module = PyDict_GetItemString(globals, "__name__");
493 if (*module == NULL) {
494 *module = PyUnicode_FromString("<string>");
495 if (*module == NULL)
496 goto handle_error;
497 }
498 else
499 Py_INCREF(*module);
500
501 /* Setup filename. */
502 *filename = PyDict_GetItemString(globals, "__file__");
503 if (*filename != NULL) {
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000504 Py_ssize_t len = PyUnicode_GetSize(*filename);
Christian Heimes33fe8092008-04-13 13:53:33 +0000505 const char *file_str = PyUnicode_AsString(*filename);
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000506 if (file_str == NULL || (len < 0 && PyErr_Occurred()))
Christian Heimes33fe8092008-04-13 13:53:33 +0000507 goto handle_error;
508
509 /* if filename.lower().endswith((".pyc", ".pyo")): */
510 if (len >= 4 &&
511 file_str[len-4] == '.' &&
512 tolower(file_str[len-3]) == 'p' &&
513 tolower(file_str[len-2]) == 'y' &&
514 (tolower(file_str[len-1]) == 'c' ||
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000515 tolower(file_str[len-1]) == 'o'))
516 {
Christian Heimes33fe8092008-04-13 13:53:33 +0000517 *filename = PyUnicode_FromStringAndSize(file_str, len-1);
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000518 if (*filename == NULL)
519 goto handle_error;
520 }
521 else
Christian Heimes33fe8092008-04-13 13:53:33 +0000522 Py_INCREF(*filename);
523 }
524 else {
525 const char *module_str = PyUnicode_AsString(*module);
526 if (module_str && strcmp(module_str, "__main__") == 0) {
527 PyObject *argv = PySys_GetObject("argv");
528 if (argv != NULL && PyList_Size(argv) > 0) {
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000529 int is_true;
Christian Heimes33fe8092008-04-13 13:53:33 +0000530 *filename = PyList_GetItem(argv, 0);
531 Py_INCREF(*filename);
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000532 /* If sys.argv[0] is false, then use '__main__'. */
533 is_true = PyObject_IsTrue(*filename);
534 if (is_true < 0) {
535 Py_DECREF(*filename);
536 goto handle_error;
537 }
538 else if (!is_true) {
539 Py_DECREF(*filename);
Benjamin Peterson9f4bf1d2008-05-04 23:22:13 +0000540 *filename = PyUnicode_FromString("__main__");
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000541 if (*filename == NULL)
542 goto handle_error;
543 }
Christian Heimes33fe8092008-04-13 13:53:33 +0000544 }
545 else {
546 /* embedded interpreters don't have sys.argv, see bug #839151 */
547 *filename = PyUnicode_FromString("__main__");
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000548 if (*filename == NULL)
549 goto handle_error;
Christian Heimes33fe8092008-04-13 13:53:33 +0000550 }
551 }
552 if (*filename == NULL) {
553 *filename = *module;
554 Py_INCREF(*filename);
555 }
556 }
557
558 return 1;
559
560 handle_error:
561 /* filename not XDECREF'ed here as there is no way to jump here with a
562 dangling reference. */
563 Py_XDECREF(*registry);
564 Py_XDECREF(*module);
565 return 0;
566}
567
568static PyObject *
569get_category(PyObject *message, PyObject *category)
570{
571 int rc;
572
573 /* Get category. */
574 rc = PyObject_IsInstance(message, PyExc_Warning);
575 if (rc == -1)
576 return NULL;
577
578 if (rc == 1)
579 category = (PyObject*)message->ob_type;
580 else if (category == NULL)
581 category = PyExc_UserWarning;
582
583 /* Validate category. */
584 rc = PyObject_IsSubclass(category, PyExc_Warning);
585 if (rc == -1)
586 return NULL;
587 if (rc == 0) {
588 PyErr_SetString(PyExc_ValueError,
589 "category is not a subclass of Warning");
590 return NULL;
591 }
592
593 return category;
594}
595
596static PyObject *
597do_warn(PyObject *message, PyObject *category, Py_ssize_t stack_level)
598{
599 PyObject *filename, *module, *registry, *res;
600 int lineno;
601
602 if (!setup_context(stack_level, &filename, &lineno, &module, &registry))
603 return NULL;
604
605 res = warn_explicit(category, message, filename, lineno, module, registry,
606 NULL);
607 Py_DECREF(filename);
608 Py_DECREF(registry);
609 Py_DECREF(module);
610 return res;
611}
612
613static PyObject *
614warnings_warn(PyObject *self, PyObject *args, PyObject *kwds)
615{
616 static char *kw_list[] = { "message", "category", "stacklevel", 0 };
617 PyObject *message, *category = NULL;
618 Py_ssize_t stack_level = 1;
619
620 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|On:warn", kw_list,
621 &message, &category, &stack_level))
622 return NULL;
623
624 category = get_category(message, category);
625 if (category == NULL)
626 return NULL;
627 return do_warn(message, category, stack_level);
628}
629
630static PyObject *
631warnings_warn_explicit(PyObject *self, PyObject *args, PyObject *kwds)
632{
633 static char *kwd_list[] = {"message", "category", "filename", "lineno",
634 "module", "registry", "module_globals", 0};
635 PyObject *message;
636 PyObject *category;
637 PyObject *filename;
638 int lineno;
639 PyObject *module = NULL;
640 PyObject *registry = NULL;
641 PyObject *module_globals = NULL;
642
643 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOOi|OOO:warn_explicit",
644 kwd_list, &message, &category, &filename, &lineno, &module,
645 &registry, &module_globals))
646 return NULL;
647
648 if (module_globals) {
649 static PyObject *get_source_name = NULL;
650 static PyObject *splitlines_name = NULL;
651 PyObject *loader;
652 PyObject *module_name;
653 PyObject *source;
654 PyObject *source_list;
655 PyObject *source_line;
656 PyObject *returned;
657
658 if (get_source_name == NULL) {
659 get_source_name = PyUnicode_InternFromString("get_source");
660 if (!get_source_name)
661 return NULL;
662 }
663 if (splitlines_name == NULL) {
664 splitlines_name = PyUnicode_InternFromString("splitlines");
665 if (!splitlines_name)
666 return NULL;
667 }
668
669 /* Check/get the requisite pieces needed for the loader. */
670 loader = PyDict_GetItemString(module_globals, "__loader__");
671 module_name = PyDict_GetItemString(module_globals, "__name__");
672
673 if (loader == NULL || module_name == NULL)
674 goto standard_call;
675
676 /* Make sure the loader implements the optional get_source() method. */
677 if (!PyObject_HasAttrString(loader, "get_source"))
678 goto standard_call;
679 /* Call get_source() to get the source code. */
680 source = PyObject_CallMethodObjArgs(loader, get_source_name,
681 module_name, NULL);
682 if (!source)
683 return NULL;
684 else if (source == Py_None) {
685 Py_DECREF(Py_None);
686 goto standard_call;
687 }
688
689 /* Split the source into lines. */
690 source_list = PyObject_CallMethodObjArgs(source, splitlines_name,
691 NULL);
692 Py_DECREF(source);
693 if (!source_list)
694 return NULL;
695
696 /* Get the source line. */
697 source_line = PyList_GetItem(source_list, lineno-1);
698 if (!source_line) {
699 Py_DECREF(source_list);
700 return NULL;
701 }
702
703 /* Handle the warning. */
704 returned = warn_explicit(category, message, filename, lineno, module,
705 registry, source_line);
706 Py_DECREF(source_list);
707 return returned;
708 }
709
710 standard_call:
711 return warn_explicit(category, message, filename, lineno, module,
712 registry, NULL);
713}
714
715
716/* Function to issue a warning message; may raise an exception. */
717int
718PyErr_WarnEx(PyObject *category, const char *text, Py_ssize_t stack_level)
719{
720 PyObject *res;
721 PyObject *message = PyUnicode_FromString(text);
722 if (message == NULL)
723 return -1;
724
725 if (category == NULL)
726 category = PyExc_RuntimeWarning;
727
728 res = do_warn(message, category, stack_level);
729 Py_DECREF(message);
730 if (res == NULL)
731 return -1;
732 Py_DECREF(res);
733
734 return 0;
735}
736
737/* PyErr_Warn is only for backwards compatability and will be removed.
738 Use PyErr_WarnEx instead. */
739
740#undef PyErr_Warn
741
742PyAPI_FUNC(int)
743PyErr_Warn(PyObject *category, char *text)
744{
745 return PyErr_WarnEx(category, text, 1);
746}
747
748/* Warning with explicit origin */
749int
750PyErr_WarnExplicit(PyObject *category, const char *text,
751 const char *filename_str, int lineno,
752 const char *module_str, PyObject *registry)
753{
754 PyObject *res;
755 PyObject *message = PyUnicode_FromString(text);
756 PyObject *filename = PyUnicode_FromString(filename_str);
757 PyObject *module = NULL;
758 int ret = -1;
759
760 if (message == NULL || filename == NULL)
761 goto exit;
762 if (module_str != NULL) {
763 module = PyUnicode_FromString(module_str);
764 if (module == NULL)
765 goto exit;
766 }
767
768 if (category == NULL)
769 category = PyExc_RuntimeWarning;
770 res = warn_explicit(category, message, filename, lineno, module, registry,
771 NULL);
772 if (res == NULL)
773 goto exit;
774 Py_DECREF(res);
775 ret = 0;
776
777 exit:
778 Py_XDECREF(message);
779 Py_XDECREF(module);
780 Py_XDECREF(filename);
781 return ret;
782}
783
784
785PyDoc_STRVAR(warn_doc,
786"Issue a warning, or maybe ignore it or raise an exception.");
787
788PyDoc_STRVAR(warn_explicit_doc,
789"Low-level inferface to warnings functionality.");
790
791static PyMethodDef warnings_functions[] = {
792 {"warn", (PyCFunction)warnings_warn, METH_VARARGS | METH_KEYWORDS,
793 warn_doc},
794 {"warn_explicit", (PyCFunction)warnings_warn_explicit,
795 METH_VARARGS | METH_KEYWORDS, warn_explicit_doc},
796 // XXX(brett.cannon): add showwarning?
797 // XXX(brett.cannon): Reasonable to add formatwarning?
798 {NULL, NULL} /* sentinel */
799};
800
801
802static PyObject *
803create_filter(PyObject *category, const char *action)
804{
805 static PyObject *ignore_str = NULL;
806 static PyObject *error_str = NULL;
807 static PyObject *default_str = NULL;
808 PyObject *action_obj = NULL;
809 PyObject *lineno, *result;
810
811 if (!strcmp(action, "ignore")) {
812 if (ignore_str == NULL) {
813 ignore_str = PyUnicode_InternFromString("ignore");
814 if (ignore_str == NULL)
815 return NULL;
816 }
817 action_obj = ignore_str;
818 }
819 else if (!strcmp(action, "error")) {
820 if (error_str == NULL) {
821 error_str = PyUnicode_InternFromString("error");
822 if (error_str == NULL)
823 return NULL;
824 }
825 action_obj = error_str;
826 }
827 else if (!strcmp(action, "default")) {
828 if (default_str == NULL) {
829 default_str = PyUnicode_InternFromString("default");
830 if (default_str == NULL)
831 return NULL;
832 }
833 action_obj = default_str;
834 }
835 else {
836 Py_FatalError("unknown action");
837 }
838
839 /* This assumes the line number is zero for now. */
840 lineno = PyLong_FromLong(0);
841 if (lineno == NULL)
842 return NULL;
843 result = PyTuple_Pack(5, action_obj, Py_None, category, Py_None, lineno);
844 Py_DECREF(lineno);
845 return result;
846}
847
848static PyObject *
849init_filters(void)
850{
851 PyObject *filters = PyList_New(3);
852 const char *bytes_action;
853 if (filters == NULL)
854 return NULL;
855
856 PyList_SET_ITEM(filters, 0,
857 create_filter(PyExc_PendingDeprecationWarning, "ignore"));
858 PyList_SET_ITEM(filters, 1, create_filter(PyExc_ImportWarning, "ignore"));
859 if (Py_BytesWarningFlag > 1)
860 bytes_action = "error";
861 else if (Py_BytesWarningFlag)
862 bytes_action = "default";
863 else
864 bytes_action = "ignore";
865 PyList_SET_ITEM(filters, 2, create_filter(PyExc_BytesWarning,
866 bytes_action));
867
868 if (PyList_GET_ITEM(filters, 0) == NULL ||
869 PyList_GET_ITEM(filters, 1) == NULL ||
870 PyList_GET_ITEM(filters, 2) == NULL) {
871 Py_DECREF(filters);
872 return NULL;
873 }
874
875 return filters;
876}
877
Martin v. Löwis1a214512008-06-11 05:26:20 +0000878static struct PyModuleDef warningsmodule = {
879 PyModuleDef_HEAD_INIT,
880 MODULE_NAME,
881 warnings__doc__,
882 0,
883 warnings_functions,
884 NULL,
885 NULL,
886 NULL,
887 NULL
888};
889
Christian Heimes33fe8092008-04-13 13:53:33 +0000890
891PyMODINIT_FUNC
892_PyWarnings_Init(void)
893{
894 PyObject *m, *default_action;
895
Martin v. Löwis1a214512008-06-11 05:26:20 +0000896 m = PyModule_Create(&warningsmodule);
Christian Heimes33fe8092008-04-13 13:53:33 +0000897 if (m == NULL)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000898 return NULL;
Christian Heimes33fe8092008-04-13 13:53:33 +0000899
900 _filters = init_filters();
901 if (_filters == NULL)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000902 return NULL;
Christian Heimes33fe8092008-04-13 13:53:33 +0000903 Py_INCREF(_filters);
904 if (PyModule_AddObject(m, "filters", _filters) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000905 return NULL;
Christian Heimes33fe8092008-04-13 13:53:33 +0000906
907 _once_registry = PyDict_New();
908 if (_once_registry == NULL)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000909 return NULL;
Christian Heimes33fe8092008-04-13 13:53:33 +0000910 Py_INCREF(_once_registry);
911 if (PyModule_AddObject(m, "once_registry", _once_registry) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000912 return NULL;
Christian Heimes33fe8092008-04-13 13:53:33 +0000913
914 default_action = PyUnicode_InternFromString("default");
915 if (default_action == NULL)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000916 return NULL;
Christian Heimes33fe8092008-04-13 13:53:33 +0000917 if (PyModule_AddObject(m, DEFAULT_ACTION_NAME, default_action) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000918 return NULL;
919 return m;
Christian Heimes33fe8092008-04-13 13:53:33 +0000920}