blob: da52e357c3eeee649c0239c105e5cbbf9ec377e2 [file] [log] [blame]
Christian Heimes33fe8092008-04-13 13:53:33 +00001#include "Python.h"
2#include "frameobject.h"
3
4#define MODULE_NAME "_warnings"
Christian Heimes33fe8092008-04-13 13:53:33 +00005
6PyDoc_STRVAR(warnings__doc__,
7MODULE_NAME " provides basic warning filtering support.\n"
8"It is a helper module to speed up interpreter start-up.");
9
10/* Both 'filters' and 'onceregistry' can be set in warnings.py;
11 get_warnings_attr() will reset these variables accordingly. */
12static PyObject *_filters; /* List */
13static PyObject *_once_registry; /* Dict */
Brett Cannon0759dd62009-04-01 18:13:07 +000014static PyObject *_default_action; /* String */
Christian Heimes33fe8092008-04-13 13:53:33 +000015
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
Brett Cannon0759dd62009-04-01 18:13:07 +000081static PyObject *
82get_default_action(void)
83{
84 PyObject *default_action;
85
86 default_action = get_warnings_attr("defaultaction");
87 if (default_action == NULL) {
88 if (PyErr_Occurred()) {
89 return NULL;
90 }
91 return _default_action;
92 }
93
94 Py_DECREF(_default_action);
95 _default_action = default_action;
96 return default_action;
97}
98
99
Christian Heimes33fe8092008-04-13 13:53:33 +0000100/* The item is a borrowed reference. */
101static const char *
102get_filter(PyObject *category, PyObject *text, Py_ssize_t lineno,
103 PyObject *module, PyObject **item)
104{
Brett Cannon0759dd62009-04-01 18:13:07 +0000105 PyObject *action;
Christian Heimes33fe8092008-04-13 13:53:33 +0000106 Py_ssize_t i;
107 PyObject *warnings_filters;
108
109 warnings_filters = get_warnings_attr("filters");
110 if (warnings_filters == NULL) {
111 if (PyErr_Occurred())
112 return NULL;
113 }
114 else {
115 Py_DECREF(_filters);
116 _filters = warnings_filters;
117 }
118
119 if (!PyList_Check(_filters)) {
120 PyErr_SetString(PyExc_ValueError,
121 MODULE_NAME ".filters must be a list");
122 return NULL;
123 }
124
125 /* _filters could change while we are iterating over it. */
126 for (i = 0; i < PyList_GET_SIZE(_filters); i++) {
127 PyObject *tmp_item, *action, *msg, *cat, *mod, *ln_obj;
128 Py_ssize_t ln;
129 int is_subclass, good_msg, good_mod;
130
131 tmp_item = *item = PyList_GET_ITEM(_filters, i);
132 if (PyTuple_Size(tmp_item) != 5) {
133 PyErr_Format(PyExc_ValueError,
134 MODULE_NAME ".filters item %zd isn't a 5-tuple", i);
135 return NULL;
136 }
137
138 /* Python code: action, msg, cat, mod, ln = item */
139 action = PyTuple_GET_ITEM(tmp_item, 0);
140 msg = PyTuple_GET_ITEM(tmp_item, 1);
141 cat = PyTuple_GET_ITEM(tmp_item, 2);
142 mod = PyTuple_GET_ITEM(tmp_item, 3);
143 ln_obj = PyTuple_GET_ITEM(tmp_item, 4);
144
145 good_msg = check_matched(msg, text);
146 good_mod = check_matched(mod, module);
147 is_subclass = PyObject_IsSubclass(category, cat);
148 ln = PyLong_AsSsize_t(ln_obj);
149 if (good_msg == -1 || good_mod == -1 || is_subclass == -1 ||
150 (ln == -1 && PyErr_Occurred()))
151 return NULL;
152
153 if (good_msg && is_subclass && good_mod && (ln == 0 || lineno == ln))
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +0000154 return _PyUnicode_AsString(action);
Christian Heimes33fe8092008-04-13 13:53:33 +0000155 }
156
Brett Cannon0759dd62009-04-01 18:13:07 +0000157 action = get_default_action();
158 if (action != NULL) {
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +0000159 return _PyUnicode_AsString(action);
Brett Cannon0759dd62009-04-01 18:13:07 +0000160 }
Christian Heimes33fe8092008-04-13 13:53:33 +0000161
162 PyErr_SetString(PyExc_ValueError,
Brett Cannon0759dd62009-04-01 18:13:07 +0000163 MODULE_NAME ".defaultaction not found");
Christian Heimes33fe8092008-04-13 13:53:33 +0000164 return NULL;
165}
166
Brett Cannon0759dd62009-04-01 18:13:07 +0000167
Christian Heimes33fe8092008-04-13 13:53:33 +0000168static int
169already_warned(PyObject *registry, PyObject *key, int should_set)
170{
171 PyObject *already_warned;
172
173 if (key == NULL)
174 return -1;
175
176 already_warned = PyDict_GetItem(registry, key);
177 if (already_warned != NULL) {
178 int rc = PyObject_IsTrue(already_warned);
179 if (rc != 0)
180 return rc;
181 }
182
183 /* This warning wasn't found in the registry, set it. */
184 if (should_set)
185 return PyDict_SetItem(registry, key, Py_True);
186 return 0;
187}
188
189/* New reference. */
190static PyObject *
191normalize_module(PyObject *filename)
192{
193 PyObject *module;
194 const char *mod_str;
195 Py_ssize_t len;
196
197 int rc = PyObject_IsTrue(filename);
198 if (rc == -1)
199 return NULL;
200 else if (rc == 0)
201 return PyUnicode_FromString("<unknown>");
202
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +0000203 mod_str = _PyUnicode_AsString(filename);
Christian Heimes33fe8092008-04-13 13:53:33 +0000204 if (mod_str == NULL)
205 return NULL;
206 len = PyUnicode_GetSize(filename);
207 if (len < 0)
208 return NULL;
209 if (len >= 3 &&
210 strncmp(mod_str + (len - 3), ".py", 3) == 0) {
211 module = PyUnicode_FromStringAndSize(mod_str, len-3);
212 }
213 else {
214 module = filename;
215 Py_INCREF(module);
216 }
217 return module;
218}
219
220static int
221update_registry(PyObject *registry, PyObject *text, PyObject *category,
222 int add_zero)
223{
224 PyObject *altkey, *zero = NULL;
225 int rc;
226
227 if (add_zero) {
228 zero = PyLong_FromLong(0);
229 if (zero == NULL)
230 return -1;
231 altkey = PyTuple_Pack(3, text, category, zero);
232 }
233 else
234 altkey = PyTuple_Pack(2, text, category);
235
236 rc = already_warned(registry, altkey, 1);
237 Py_XDECREF(zero);
238 Py_XDECREF(altkey);
239 return rc;
240}
241
242static void
243show_warning(PyObject *filename, int lineno, PyObject *text, PyObject
244 *category, PyObject *sourceline)
245{
246 PyObject *f_stderr;
247 PyObject *name;
248 char lineno_str[128];
249
250 PyOS_snprintf(lineno_str, sizeof(lineno_str), ":%d: ", lineno);
251
252 name = PyObject_GetAttrString(category, "__name__");
253 if (name == NULL) /* XXX Can an object lack a '__name__' attribute? */
254 return;
255
256 f_stderr = PySys_GetObject("stderr");
257 if (f_stderr == NULL) {
258 fprintf(stderr, "lost sys.stderr\n");
259 Py_DECREF(name);
260 return;
261 }
262
263 /* Print "filename:lineno: category: text\n" */
264 PyFile_WriteObject(filename, f_stderr, Py_PRINT_RAW);
265 PyFile_WriteString(lineno_str, f_stderr);
266 PyFile_WriteObject(name, f_stderr, Py_PRINT_RAW);
267 PyFile_WriteString(": ", f_stderr);
268 PyFile_WriteObject(text, f_stderr, Py_PRINT_RAW);
269 PyFile_WriteString("\n", f_stderr);
270 Py_XDECREF(name);
271
272 /* Print " source_line\n" */
Christian Heimes33fe8092008-04-13 13:53:33 +0000273 if (sourceline) {
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +0000274 char *source_line_str = _PyUnicode_AsString(sourceline);
Brett Cannon54bd41d2008-09-02 04:01:42 +0000275 if (source_line_str == NULL)
276 return;
Christian Heimes33fe8092008-04-13 13:53:33 +0000277 while (*source_line_str == ' ' || *source_line_str == '\t' ||
278 *source_line_str == '\014')
279 source_line_str++;
280
281 PyFile_WriteString(source_line_str, f_stderr);
282 PyFile_WriteString("\n", f_stderr);
283 }
284 else
Brett Cannon54bd41d2008-09-02 04:01:42 +0000285 if (_Py_DisplaySourceLine(f_stderr, _PyUnicode_AsString(filename),
286 lineno, 2) < 0)
287 return;
Christian Heimes33fe8092008-04-13 13:53:33 +0000288 PyErr_Clear();
289}
290
291static PyObject *
292warn_explicit(PyObject *category, PyObject *message,
293 PyObject *filename, int lineno,
294 PyObject *module, PyObject *registry, PyObject *sourceline)
295{
296 PyObject *key = NULL, *text = NULL, *result = NULL, *lineno_obj = NULL;
297 PyObject *item = Py_None;
298 const char *action;
299 int rc;
Brett Cannondb734912008-06-27 00:52:15 +0000300
301 if (registry && !PyDict_Check(registry) && (registry != Py_None)) {
302 PyErr_SetString(PyExc_TypeError, "'registry' must be a dict");
303 return NULL;
304 }
Christian Heimes33fe8092008-04-13 13:53:33 +0000305
306 /* Normalize module. */
307 if (module == NULL) {
308 module = normalize_module(filename);
309 if (module == NULL)
310 return NULL;
311 }
312 else
313 Py_INCREF(module);
314
315 /* Normalize message. */
316 Py_INCREF(message); /* DECREF'ed in cleanup. */
317 rc = PyObject_IsInstance(message, PyExc_Warning);
318 if (rc == -1) {
319 goto cleanup;
320 }
321 if (rc == 1) {
322 text = PyObject_Str(message);
323 category = (PyObject*)message->ob_type;
324 }
325 else {
326 text = message;
327 message = PyObject_CallFunction(category, "O", message);
Brett Cannondb734912008-06-27 00:52:15 +0000328 if (message == NULL)
329 goto cleanup;
Christian Heimes33fe8092008-04-13 13:53:33 +0000330 }
331
332 lineno_obj = PyLong_FromLong(lineno);
333 if (lineno_obj == NULL)
334 goto cleanup;
335
336 /* Create key. */
337 key = PyTuple_Pack(3, text, category, lineno_obj);
338 if (key == NULL)
339 goto cleanup;
340
Brett Cannondb734912008-06-27 00:52:15 +0000341 if ((registry != NULL) && (registry != Py_None)) {
Christian Heimes33fe8092008-04-13 13:53:33 +0000342 rc = already_warned(registry, key, 0);
343 if (rc == -1)
344 goto cleanup;
345 else if (rc == 1)
346 goto return_none;
347 /* Else this warning hasn't been generated before. */
348 }
349
350 action = get_filter(category, text, lineno, module, &item);
351 if (action == NULL)
352 goto cleanup;
353
354 if (strcmp(action, "error") == 0) {
355 PyErr_SetObject(category, message);
356 goto cleanup;
357 }
358
359 /* Store in the registry that we've been here, *except* when the action
360 is "always". */
361 rc = 0;
362 if (strcmp(action, "always") != 0) {
Brett Cannondb734912008-06-27 00:52:15 +0000363 if (registry != NULL && registry != Py_None &&
364 PyDict_SetItem(registry, key, Py_True) < 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000365 goto cleanup;
366 else if (strcmp(action, "ignore") == 0)
367 goto return_none;
368 else if (strcmp(action, "once") == 0) {
Brett Cannondb734912008-06-27 00:52:15 +0000369 if (registry == NULL || registry == Py_None) {
Christian Heimes33fe8092008-04-13 13:53:33 +0000370 registry = get_once_registry();
371 if (registry == NULL)
372 goto cleanup;
373 }
374 /* _once_registry[(text, category)] = 1 */
375 rc = update_registry(registry, text, category, 0);
376 }
377 else if (strcmp(action, "module") == 0) {
378 /* registry[(text, category, 0)] = 1 */
Brett Cannondb734912008-06-27 00:52:15 +0000379 if (registry != NULL && registry != Py_None)
Christian Heimes33fe8092008-04-13 13:53:33 +0000380 rc = update_registry(registry, text, category, 0);
381 }
382 else if (strcmp(action, "default") != 0) {
383 PyObject *to_str = PyObject_Str(item);
384 const char *err_str = "???";
385
Brett Cannon54bd41d2008-09-02 04:01:42 +0000386 if (to_str != NULL) {
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +0000387 err_str = _PyUnicode_AsString(to_str);
Brett Cannon54bd41d2008-09-02 04:01:42 +0000388 if (err_str == NULL)
389 goto cleanup;
390 }
Christian Heimes33fe8092008-04-13 13:53:33 +0000391 PyErr_Format(PyExc_RuntimeError,
392 "Unrecognized action (%s) in warnings.filters:\n %s",
393 action, err_str);
394 Py_XDECREF(to_str);
395 goto cleanup;
396 }
397 }
398
Christian Heimes1a8501c2008-10-02 19:56:01 +0000399 if (rc == 1) /* Already warned for this module. */
Christian Heimes33fe8092008-04-13 13:53:33 +0000400 goto return_none;
401 if (rc == 0) {
402 PyObject *show_fxn = get_warnings_attr("showwarning");
403 if (show_fxn == NULL) {
404 if (PyErr_Occurred())
405 goto cleanup;
406 show_warning(filename, lineno, text, category, sourceline);
407 }
408 else {
Brett Cannonec92e182008-09-02 02:46:59 +0000409 PyObject *res;
Christian Heimes8dc226f2008-05-06 23:45:46 +0000410
Brett Cannonec92e182008-09-02 02:46:59 +0000411 if (!PyMethod_Check(show_fxn) && !PyFunction_Check(show_fxn)) {
412 PyErr_SetString(PyExc_TypeError,
413 "warnings.showwarning() must be set to a "
414 "function or method");
Christian Heimes8dc226f2008-05-06 23:45:46 +0000415 Py_DECREF(show_fxn);
Brett Cannonec92e182008-09-02 02:46:59 +0000416 goto cleanup;
Christian Heimes8dc226f2008-05-06 23:45:46 +0000417 }
Brett Cannonec92e182008-09-02 02:46:59 +0000418
419 res = PyObject_CallFunctionObjArgs(show_fxn, message, category,
420 filename, lineno_obj,
421 NULL);
422 Py_DECREF(show_fxn);
423 Py_XDECREF(res);
424 if (res == NULL)
425 goto cleanup;
Christian Heimes33fe8092008-04-13 13:53:33 +0000426 }
427 }
428 else /* if (rc == -1) */
429 goto cleanup;
430
431 return_none:
432 result = Py_None;
433 Py_INCREF(result);
434
435 cleanup:
436 Py_XDECREF(key);
437 Py_XDECREF(text);
438 Py_XDECREF(lineno_obj);
439 Py_DECREF(module);
Brett Cannondb734912008-06-27 00:52:15 +0000440 Py_XDECREF(message);
Christian Heimes33fe8092008-04-13 13:53:33 +0000441 return result; /* Py_None or NULL. */
442}
443
444/* filename, module, and registry are new refs, globals is borrowed */
445/* Returns 0 on error (no new refs), 1 on success */
446static int
447setup_context(Py_ssize_t stack_level, PyObject **filename, int *lineno,
448 PyObject **module, PyObject **registry)
449{
450 PyObject *globals;
451
452 /* Setup globals and lineno. */
453 PyFrameObject *f = PyThreadState_GET()->frame;
Christian Heimes5d8da202008-05-06 13:58:24 +0000454 while (--stack_level > 0 && f != NULL)
Christian Heimes33fe8092008-04-13 13:53:33 +0000455 f = f->f_back;
Christian Heimes33fe8092008-04-13 13:53:33 +0000456
457 if (f == NULL) {
458 globals = PyThreadState_Get()->interp->sysdict;
459 *lineno = 1;
460 }
461 else {
462 globals = f->f_globals;
463 *lineno = PyCode_Addr2Line(f->f_code, f->f_lasti);
464 }
465
466 *module = NULL;
467
468 /* Setup registry. */
469 assert(globals != NULL);
470 assert(PyDict_Check(globals));
471 *registry = PyDict_GetItemString(globals, "__warningregistry__");
472 if (*registry == NULL) {
473 int rc;
474
475 *registry = PyDict_New();
476 if (*registry == NULL)
477 return 0;
478
479 rc = PyDict_SetItemString(globals, "__warningregistry__", *registry);
480 if (rc < 0)
481 goto handle_error;
482 }
483 else
484 Py_INCREF(*registry);
485
486 /* Setup module. */
487 *module = PyDict_GetItemString(globals, "__name__");
488 if (*module == NULL) {
489 *module = PyUnicode_FromString("<string>");
490 if (*module == NULL)
491 goto handle_error;
492 }
493 else
494 Py_INCREF(*module);
495
496 /* Setup filename. */
497 *filename = PyDict_GetItemString(globals, "__file__");
498 if (*filename != NULL) {
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000499 Py_ssize_t len = PyUnicode_GetSize(*filename);
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +0000500 const char *file_str = _PyUnicode_AsString(*filename);
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000501 if (file_str == NULL || (len < 0 && PyErr_Occurred()))
Christian Heimes33fe8092008-04-13 13:53:33 +0000502 goto handle_error;
503
504 /* if filename.lower().endswith((".pyc", ".pyo")): */
505 if (len >= 4 &&
506 file_str[len-4] == '.' &&
507 tolower(file_str[len-3]) == 'p' &&
508 tolower(file_str[len-2]) == 'y' &&
509 (tolower(file_str[len-1]) == 'c' ||
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000510 tolower(file_str[len-1]) == 'o'))
511 {
Christian Heimes33fe8092008-04-13 13:53:33 +0000512 *filename = PyUnicode_FromStringAndSize(file_str, len-1);
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000513 if (*filename == NULL)
514 goto handle_error;
515 }
516 else
Christian Heimes33fe8092008-04-13 13:53:33 +0000517 Py_INCREF(*filename);
518 }
519 else {
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +0000520 const char *module_str = _PyUnicode_AsString(*module);
Brett Cannon54bd41d2008-09-02 04:01:42 +0000521 if (module_str == NULL)
522 goto handle_error;
523 if (strcmp(module_str, "__main__") == 0) {
Christian Heimes33fe8092008-04-13 13:53:33 +0000524 PyObject *argv = PySys_GetObject("argv");
525 if (argv != NULL && PyList_Size(argv) > 0) {
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000526 int is_true;
Christian Heimes33fe8092008-04-13 13:53:33 +0000527 *filename = PyList_GetItem(argv, 0);
528 Py_INCREF(*filename);
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000529 /* If sys.argv[0] is false, then use '__main__'. */
530 is_true = PyObject_IsTrue(*filename);
531 if (is_true < 0) {
532 Py_DECREF(*filename);
533 goto handle_error;
534 }
535 else if (!is_true) {
536 Py_DECREF(*filename);
Benjamin Peterson9f4bf1d2008-05-04 23:22:13 +0000537 *filename = PyUnicode_FromString("__main__");
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000538 if (*filename == NULL)
539 goto handle_error;
540 }
Christian Heimes33fe8092008-04-13 13:53:33 +0000541 }
542 else {
543 /* embedded interpreters don't have sys.argv, see bug #839151 */
544 *filename = PyUnicode_FromString("__main__");
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000545 if (*filename == NULL)
546 goto handle_error;
Christian Heimes33fe8092008-04-13 13:53:33 +0000547 }
548 }
549 if (*filename == NULL) {
550 *filename = *module;
551 Py_INCREF(*filename);
552 }
553 }
554
555 return 1;
556
557 handle_error:
558 /* filename not XDECREF'ed here as there is no way to jump here with a
559 dangling reference. */
560 Py_XDECREF(*registry);
561 Py_XDECREF(*module);
562 return 0;
563}
564
565static PyObject *
566get_category(PyObject *message, PyObject *category)
567{
568 int rc;
569
570 /* Get category. */
571 rc = PyObject_IsInstance(message, PyExc_Warning);
572 if (rc == -1)
573 return NULL;
574
575 if (rc == 1)
576 category = (PyObject*)message->ob_type;
577 else if (category == NULL)
578 category = PyExc_UserWarning;
579
580 /* Validate category. */
581 rc = PyObject_IsSubclass(category, PyExc_Warning);
582 if (rc == -1)
583 return NULL;
584 if (rc == 0) {
585 PyErr_SetString(PyExc_ValueError,
586 "category is not a subclass of Warning");
587 return NULL;
588 }
589
590 return category;
591}
592
593static PyObject *
594do_warn(PyObject *message, PyObject *category, Py_ssize_t stack_level)
595{
596 PyObject *filename, *module, *registry, *res;
597 int lineno;
598
599 if (!setup_context(stack_level, &filename, &lineno, &module, &registry))
600 return NULL;
601
602 res = warn_explicit(category, message, filename, lineno, module, registry,
603 NULL);
604 Py_DECREF(filename);
605 Py_DECREF(registry);
606 Py_DECREF(module);
607 return res;
608}
609
610static PyObject *
611warnings_warn(PyObject *self, PyObject *args, PyObject *kwds)
612{
613 static char *kw_list[] = { "message", "category", "stacklevel", 0 };
614 PyObject *message, *category = NULL;
615 Py_ssize_t stack_level = 1;
616
617 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|On:warn", kw_list,
618 &message, &category, &stack_level))
619 return NULL;
620
621 category = get_category(message, category);
622 if (category == NULL)
623 return NULL;
624 return do_warn(message, category, stack_level);
625}
626
627static PyObject *
628warnings_warn_explicit(PyObject *self, PyObject *args, PyObject *kwds)
629{
630 static char *kwd_list[] = {"message", "category", "filename", "lineno",
631 "module", "registry", "module_globals", 0};
632 PyObject *message;
633 PyObject *category;
634 PyObject *filename;
635 int lineno;
636 PyObject *module = NULL;
637 PyObject *registry = NULL;
638 PyObject *module_globals = NULL;
639
640 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOOi|OOO:warn_explicit",
641 kwd_list, &message, &category, &filename, &lineno, &module,
642 &registry, &module_globals))
643 return NULL;
644
645 if (module_globals) {
646 static PyObject *get_source_name = NULL;
647 static PyObject *splitlines_name = NULL;
648 PyObject *loader;
649 PyObject *module_name;
650 PyObject *source;
651 PyObject *source_list;
652 PyObject *source_line;
653 PyObject *returned;
654
655 if (get_source_name == NULL) {
656 get_source_name = PyUnicode_InternFromString("get_source");
657 if (!get_source_name)
658 return NULL;
659 }
660 if (splitlines_name == NULL) {
661 splitlines_name = PyUnicode_InternFromString("splitlines");
662 if (!splitlines_name)
663 return NULL;
664 }
665
666 /* Check/get the requisite pieces needed for the loader. */
667 loader = PyDict_GetItemString(module_globals, "__loader__");
668 module_name = PyDict_GetItemString(module_globals, "__name__");
669
670 if (loader == NULL || module_name == NULL)
671 goto standard_call;
672
673 /* Make sure the loader implements the optional get_source() method. */
674 if (!PyObject_HasAttrString(loader, "get_source"))
675 goto standard_call;
676 /* Call get_source() to get the source code. */
677 source = PyObject_CallMethodObjArgs(loader, get_source_name,
678 module_name, NULL);
679 if (!source)
680 return NULL;
681 else if (source == Py_None) {
682 Py_DECREF(Py_None);
683 goto standard_call;
684 }
685
686 /* Split the source into lines. */
687 source_list = PyObject_CallMethodObjArgs(source, splitlines_name,
688 NULL);
689 Py_DECREF(source);
690 if (!source_list)
691 return NULL;
692
693 /* Get the source line. */
694 source_line = PyList_GetItem(source_list, lineno-1);
695 if (!source_line) {
696 Py_DECREF(source_list);
697 return NULL;
698 }
699
700 /* Handle the warning. */
701 returned = warn_explicit(category, message, filename, lineno, module,
702 registry, source_line);
703 Py_DECREF(source_list);
704 return returned;
705 }
706
707 standard_call:
708 return warn_explicit(category, message, filename, lineno, module,
709 registry, NULL);
710}
711
712
713/* Function to issue a warning message; may raise an exception. */
714int
715PyErr_WarnEx(PyObject *category, const char *text, Py_ssize_t stack_level)
716{
717 PyObject *res;
718 PyObject *message = PyUnicode_FromString(text);
719 if (message == NULL)
720 return -1;
721
722 if (category == NULL)
723 category = PyExc_RuntimeWarning;
724
725 res = do_warn(message, category, stack_level);
726 Py_DECREF(message);
727 if (res == NULL)
728 return -1;
729 Py_DECREF(res);
730
731 return 0;
732}
733
734/* PyErr_Warn is only for backwards compatability and will be removed.
735 Use PyErr_WarnEx instead. */
736
737#undef PyErr_Warn
738
739PyAPI_FUNC(int)
740PyErr_Warn(PyObject *category, char *text)
741{
742 return PyErr_WarnEx(category, text, 1);
743}
744
745/* Warning with explicit origin */
746int
747PyErr_WarnExplicit(PyObject *category, const char *text,
748 const char *filename_str, int lineno,
749 const char *module_str, PyObject *registry)
750{
751 PyObject *res;
752 PyObject *message = PyUnicode_FromString(text);
753 PyObject *filename = PyUnicode_FromString(filename_str);
754 PyObject *module = NULL;
755 int ret = -1;
756
757 if (message == NULL || filename == NULL)
758 goto exit;
759 if (module_str != NULL) {
760 module = PyUnicode_FromString(module_str);
761 if (module == NULL)
762 goto exit;
763 }
764
765 if (category == NULL)
766 category = PyExc_RuntimeWarning;
767 res = warn_explicit(category, message, filename, lineno, module, registry,
768 NULL);
769 if (res == NULL)
770 goto exit;
771 Py_DECREF(res);
772 ret = 0;
773
774 exit:
775 Py_XDECREF(message);
776 Py_XDECREF(module);
777 Py_XDECREF(filename);
778 return ret;
779}
780
781
782PyDoc_STRVAR(warn_doc,
783"Issue a warning, or maybe ignore it or raise an exception.");
784
785PyDoc_STRVAR(warn_explicit_doc,
786"Low-level inferface to warnings functionality.");
787
788static PyMethodDef warnings_functions[] = {
789 {"warn", (PyCFunction)warnings_warn, METH_VARARGS | METH_KEYWORDS,
790 warn_doc},
791 {"warn_explicit", (PyCFunction)warnings_warn_explicit,
792 METH_VARARGS | METH_KEYWORDS, warn_explicit_doc},
Christian Heimes1a8501c2008-10-02 19:56:01 +0000793 /* XXX(brett.cannon): add showwarning? */
794 /* XXX(brett.cannon): Reasonable to add formatwarning? */
Christian Heimes33fe8092008-04-13 13:53:33 +0000795 {NULL, NULL} /* sentinel */
796};
797
798
799static PyObject *
800create_filter(PyObject *category, const char *action)
801{
802 static PyObject *ignore_str = NULL;
803 static PyObject *error_str = NULL;
804 static PyObject *default_str = NULL;
805 PyObject *action_obj = NULL;
806 PyObject *lineno, *result;
807
808 if (!strcmp(action, "ignore")) {
809 if (ignore_str == NULL) {
810 ignore_str = PyUnicode_InternFromString("ignore");
811 if (ignore_str == NULL)
812 return NULL;
813 }
814 action_obj = ignore_str;
815 }
816 else if (!strcmp(action, "error")) {
817 if (error_str == NULL) {
818 error_str = PyUnicode_InternFromString("error");
819 if (error_str == NULL)
820 return NULL;
821 }
822 action_obj = error_str;
823 }
824 else if (!strcmp(action, "default")) {
825 if (default_str == NULL) {
826 default_str = PyUnicode_InternFromString("default");
827 if (default_str == NULL)
828 return NULL;
829 }
830 action_obj = default_str;
831 }
832 else {
833 Py_FatalError("unknown action");
834 }
835
836 /* This assumes the line number is zero for now. */
837 lineno = PyLong_FromLong(0);
838 if (lineno == NULL)
839 return NULL;
840 result = PyTuple_Pack(5, action_obj, Py_None, category, Py_None, lineno);
841 Py_DECREF(lineno);
842 return result;
843}
844
845static PyObject *
846init_filters(void)
847{
848 PyObject *filters = PyList_New(3);
849 const char *bytes_action;
850 if (filters == NULL)
851 return NULL;
852
853 PyList_SET_ITEM(filters, 0,
854 create_filter(PyExc_PendingDeprecationWarning, "ignore"));
855 PyList_SET_ITEM(filters, 1, create_filter(PyExc_ImportWarning, "ignore"));
856 if (Py_BytesWarningFlag > 1)
857 bytes_action = "error";
858 else if (Py_BytesWarningFlag)
859 bytes_action = "default";
860 else
861 bytes_action = "ignore";
862 PyList_SET_ITEM(filters, 2, create_filter(PyExc_BytesWarning,
863 bytes_action));
864
865 if (PyList_GET_ITEM(filters, 0) == NULL ||
866 PyList_GET_ITEM(filters, 1) == NULL ||
867 PyList_GET_ITEM(filters, 2) == NULL) {
868 Py_DECREF(filters);
869 return NULL;
870 }
871
872 return filters;
873}
874
Martin v. Löwis1a214512008-06-11 05:26:20 +0000875static struct PyModuleDef warningsmodule = {
876 PyModuleDef_HEAD_INIT,
877 MODULE_NAME,
878 warnings__doc__,
879 0,
880 warnings_functions,
881 NULL,
882 NULL,
883 NULL,
884 NULL
885};
886
Christian Heimes33fe8092008-04-13 13:53:33 +0000887
888PyMODINIT_FUNC
889_PyWarnings_Init(void)
890{
Brett Cannon0759dd62009-04-01 18:13:07 +0000891 PyObject *m;
Christian Heimes33fe8092008-04-13 13:53:33 +0000892
Martin v. Löwis1a214512008-06-11 05:26:20 +0000893 m = PyModule_Create(&warningsmodule);
Christian Heimes33fe8092008-04-13 13:53:33 +0000894 if (m == NULL)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000895 return NULL;
Christian Heimes33fe8092008-04-13 13:53:33 +0000896
897 _filters = init_filters();
898 if (_filters == NULL)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000899 return NULL;
Christian Heimes33fe8092008-04-13 13:53:33 +0000900 Py_INCREF(_filters);
901 if (PyModule_AddObject(m, "filters", _filters) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000902 return NULL;
Christian Heimes33fe8092008-04-13 13:53:33 +0000903
904 _once_registry = PyDict_New();
905 if (_once_registry == NULL)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000906 return NULL;
Christian Heimes33fe8092008-04-13 13:53:33 +0000907 Py_INCREF(_once_registry);
908 if (PyModule_AddObject(m, "once_registry", _once_registry) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000909 return NULL;
Christian Heimes33fe8092008-04-13 13:53:33 +0000910
Brett Cannon0759dd62009-04-01 18:13:07 +0000911 _default_action = PyUnicode_FromString("default");
912 if (_default_action == NULL)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000913 return NULL;
Brett Cannon0759dd62009-04-01 18:13:07 +0000914 if (PyModule_AddObject(m, "default_action", _default_action) < 0)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000915 return NULL;
916 return m;
Christian Heimes33fe8092008-04-13 13:53:33 +0000917}