2 #include "frameobject.h"
4 #define MODULE_NAME "_warnings"
5 #define DEFAULT_ACTION_NAME "default_action"
7 PyDoc_STRVAR(warnings__doc__
,
8 MODULE_NAME
" provides basic warning filtering support.\n"
9 "It is a helper module to speed up interpreter start-up.");
11 /* Both 'filters' and 'onceregistry' can be set in warnings.py;
12 get_warnings_attr() will reset these variables accordingly. */
13 static PyObject
*_filters
; /* List */
14 static PyObject
*_once_registry
; /* Dict */
18 check_matched(PyObject
*obj
, PyObject
*arg
)
25 result
= PyObject_CallMethod(obj
, "match", "O", arg
);
29 rc
= PyObject_IsTrue(result
);
35 Returns a new reference.
36 A NULL return value can mean false or an error.
39 get_warnings_attr(const char *attr
)
41 static PyObject
*warnings_str
= NULL
;
42 PyObject
*all_modules
;
43 PyObject
*warnings_module
;
46 if (warnings_str
== NULL
) {
47 warnings_str
= PyString_InternFromString("warnings");
48 if (warnings_str
== NULL
)
52 all_modules
= PyImport_GetModuleDict();
53 result
= PyDict_Contains(all_modules
, warnings_str
);
54 if (result
== -1 || result
== 0)
57 warnings_module
= PyDict_GetItem(all_modules
, warnings_str
);
58 if (!PyObject_HasAttrString(warnings_module
, attr
))
60 return PyObject_GetAttrString(warnings_module
, attr
);
65 get_once_registry(void)
69 registry
= get_warnings_attr("onceregistry");
70 if (registry
== NULL
) {
73 return _once_registry
;
75 Py_DECREF(_once_registry
);
76 _once_registry
= registry
;
81 /* The item is a borrowed reference. */
83 get_filter(PyObject
*category
, PyObject
*text
, Py_ssize_t lineno
,
84 PyObject
*module
, PyObject
**item
)
86 PyObject
*action
, *m
, *d
;
88 PyObject
*warnings_filters
;
90 warnings_filters
= get_warnings_attr("filters");
91 if (warnings_filters
== NULL
) {
97 _filters
= warnings_filters
;
100 if (!PyList_Check(_filters
)) {
101 PyErr_SetString(PyExc_ValueError
,
102 MODULE_NAME
".filters must be a list");
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
;
110 int is_subclass
, good_msg
, good_mod
;
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
);
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);
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()))
134 if (good_msg
&& is_subclass
&& good_mod
&& (ln
== 0 || lineno
== ln
))
135 return PyString_AsString(action
);
138 m
= PyImport_ImportModule(MODULE_NAME
);
141 d
= PyModule_GetDict(m
);
145 action
= PyDict_GetItemString(d
, DEFAULT_ACTION_NAME
);
147 return PyString_AsString(action
);
149 PyErr_SetString(PyExc_ValueError
,
150 MODULE_NAME
"." DEFAULT_ACTION_NAME
" not found");
155 already_warned(PyObject
*registry
, PyObject
*key
, int should_set
)
157 PyObject
*already_warned
;
162 already_warned
= PyDict_GetItem(registry
, key
);
163 if (already_warned
!= NULL
) {
164 int rc
= PyObject_IsTrue(already_warned
);
169 /* This warning wasn't found in the registry, set it. */
171 return PyDict_SetItem(registry
, key
, Py_True
);
177 normalize_module(PyObject
*filename
)
183 int rc
= PyObject_IsTrue(filename
);
187 return PyString_FromString("<unknown>");
189 mod_str
= PyString_AsString(filename
);
192 len
= PyString_Size(filename
);
196 strncmp(mod_str
+ (len
- 3), ".py", 3) == 0) {
197 module
= PyString_FromStringAndSize(mod_str
, len
-3);
207 update_registry(PyObject
*registry
, PyObject
*text
, PyObject
*category
,
210 PyObject
*altkey
, *zero
= NULL
;
214 zero
= PyInt_FromLong(0);
217 altkey
= PyTuple_Pack(3, text
, category
, zero
);
220 altkey
= PyTuple_Pack(2, text
, category
);
222 rc
= already_warned(registry
, altkey
, 1);
229 show_warning(PyObject
*filename
, int lineno
, PyObject
*text
, PyObject
230 *category
, PyObject
*sourceline
)
234 char lineno_str
[128];
236 PyOS_snprintf(lineno_str
, sizeof(lineno_str
), ":%d: ", lineno
);
238 name
= PyObject_GetAttrString(category
, "__name__");
239 if (name
== NULL
) /* XXX Can an object lack a '__name__' attribute? */
242 f_stderr
= PySys_GetObject("stderr");
243 if (f_stderr
== NULL
) {
244 fprintf(stderr
, "lost sys.stderr\n");
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
);
258 /* Print " source_line\n" */
259 PyFile_WriteString(" ", f_stderr
);
261 char *source_line_str
= PyString_AS_STRING(sourceline
);
262 while (*source_line_str
== ' ' || *source_line_str
== '\t' ||
263 *source_line_str
== '\014')
266 PyFile_WriteString(source_line_str
, f_stderr
);
267 PyFile_WriteString("\n", f_stderr
);
270 Py_DisplaySourceLine(f_stderr
, PyString_AS_STRING(filename
), lineno
);
275 warn_explicit(PyObject
*category
, PyObject
*message
,
276 PyObject
*filename
, int lineno
,
277 PyObject
*module
, PyObject
*registry
, PyObject
*sourceline
)
279 PyObject
*key
= NULL
, *text
= NULL
, *result
= NULL
, *lineno_obj
= NULL
;
280 PyObject
*item
= Py_None
;
284 if (registry
&& !PyDict_Check(registry
) && (registry
!= Py_None
)) {
285 PyErr_SetString(PyExc_TypeError
, "'registry' must be a dict");
289 /* Normalize module. */
290 if (module
== NULL
) {
291 module
= normalize_module(filename
);
298 /* Normalize message. */
299 Py_INCREF(message
); /* DECREF'ed in cleanup. */
300 rc
= PyObject_IsInstance(message
, PyExc_Warning
);
305 text
= PyObject_Str(message
);
306 category
= (PyObject
*)message
->ob_type
;
310 message
= PyObject_CallFunction(category
, "O", message
);
315 lineno_obj
= PyInt_FromLong(lineno
);
316 if (lineno_obj
== NULL
)
320 key
= PyTuple_Pack(3, text
, category
, lineno_obj
);
324 if ((registry
!= NULL
) && (registry
!= Py_None
)) {
325 rc
= already_warned(registry
, key
, 0);
330 /* Else this warning hasn't been generated before. */
333 action
= get_filter(category
, text
, lineno
, module
, &item
);
337 if (strcmp(action
, "error") == 0) {
338 PyErr_SetObject(category
, message
);
342 /* Store in the registry that we've been here, *except* when the action
345 if (strcmp(action
, "always") != 0) {
346 if (registry
!= NULL
&& registry
!= Py_None
&&
347 PyDict_SetItem(registry
, key
, Py_True
) < 0)
349 else if (strcmp(action
, "ignore") == 0)
351 else if (strcmp(action
, "once") == 0) {
352 if (registry
== NULL
|| registry
== Py_None
) {
353 registry
= get_once_registry();
354 if (registry
== NULL
)
357 /* _once_registry[(text, category)] = 1 */
358 rc
= update_registry(registry
, text
, category
, 0);
360 else if (strcmp(action
, "module") == 0) {
361 /* registry[(text, category, 0)] = 1 */
362 if (registry
!= NULL
&& registry
!= Py_None
)
363 rc
= update_registry(registry
, text
, category
, 0);
365 else if (strcmp(action
, "default") != 0) {
366 PyObject
*to_str
= PyObject_Str(item
);
367 const char *err_str
= "???";
370 err_str
= PyString_AS_STRING(to_str
);
371 PyErr_Format(PyExc_RuntimeError
,
372 "Unrecognized action (%s) in warnings.filters:\n %s",
379 if (rc
== 1) // Already warned for this module. */
382 PyObject
*show_fxn
= get_warnings_attr("showwarning");
383 if (show_fxn
== NULL
) {
384 if (PyErr_Occurred())
386 show_warning(filename
, lineno
, text
, category
, sourceline
);
389 const char *msg
= "functions overriding warnings.showwarning() "
390 "must support the 'line' argument";
391 const char *text_char
= PyString_AS_STRING(text
);
393 if (strcmp(msg
, text_char
) == 0) {
394 /* Prevent infinite recursion by using built-in implementation
396 show_warning(filename
, lineno
, text
, category
, sourceline
);
403 if (PyMethod_Check(show_fxn
))
404 check_fxn
= PyMethod_Function(show_fxn
);
405 else if (PyFunction_Check(show_fxn
))
406 check_fxn
= show_fxn
;
408 PyErr_SetString(PyExc_TypeError
,
409 "warnings.showwarning() must be set to a "
410 "function or method");
415 defaults
= PyFunction_GetDefaults(check_fxn
);
416 /* A proper implementation of warnings.showwarning() should
417 have at least two default arguments. */
418 if ((defaults
== NULL
) || (PyTuple_Size(defaults
) < 2)) {
419 if (PyErr_WarnEx(PyExc_DeprecationWarning
, msg
, 1) < 0) {
424 res
= PyObject_CallFunctionObjArgs(show_fxn
, message
, category
,
425 filename
, lineno_obj
,
434 else /* if (rc == -1) */
444 Py_XDECREF(lineno_obj
);
447 return result
; /* Py_None or NULL. */
450 /* filename, module, and registry are new refs, globals is borrowed */
451 /* Returns 0 on error (no new refs), 1 on success */
453 setup_context(Py_ssize_t stack_level
, PyObject
**filename
, int *lineno
,
454 PyObject
**module
, PyObject
**registry
)
458 /* Setup globals and lineno. */
459 PyFrameObject
*f
= PyThreadState_GET()->frame
;
460 while (--stack_level
> 0 && f
!= NULL
)
464 globals
= PyThreadState_Get()->interp
->sysdict
;
468 globals
= f
->f_globals
;
469 *lineno
= PyCode_Addr2Line(f
->f_code
, f
->f_lasti
);
474 /* Setup registry. */
475 assert(globals
!= NULL
);
476 assert(PyDict_Check(globals
));
477 *registry
= PyDict_GetItemString(globals
, "__warningregistry__");
478 if (*registry
== NULL
) {
481 *registry
= PyDict_New();
482 if (*registry
== NULL
)
485 rc
= PyDict_SetItemString(globals
, "__warningregistry__", *registry
);
490 Py_INCREF(*registry
);
493 *module
= PyDict_GetItemString(globals
, "__name__");
494 if (*module
== NULL
) {
495 *module
= PyString_FromString("<string>");
502 /* Setup filename. */
503 *filename
= PyDict_GetItemString(globals
, "__file__");
504 if (*filename
!= NULL
) {
505 Py_ssize_t len
= PyString_Size(*filename
);
506 const char *file_str
= PyString_AsString(*filename
);
507 if (file_str
== NULL
|| (len
< 0 && PyErr_Occurred()))
510 /* if filename.lower().endswith((".pyc", ".pyo")): */
512 file_str
[len
-4] == '.' &&
513 tolower(file_str
[len
-3]) == 'p' &&
514 tolower(file_str
[len
-2]) == 'y' &&
515 (tolower(file_str
[len
-1]) == 'c' ||
516 tolower(file_str
[len
-1]) == 'o'))
518 *filename
= PyString_FromStringAndSize(file_str
, len
-1);
519 if (*filename
== NULL
)
523 Py_INCREF(*filename
);
526 const char *module_str
= PyString_AsString(*module
);
527 if (module_str
&& strcmp(module_str
, "__main__") == 0) {
528 PyObject
*argv
= PySys_GetObject("argv");
529 if (argv
!= NULL
&& PyList_Size(argv
) > 0) {
531 *filename
= PyList_GetItem(argv
, 0);
532 Py_INCREF(*filename
);
533 /* If sys.argv[0] is false, then use '__main__'. */
534 is_true
= PyObject_IsTrue(*filename
);
536 Py_DECREF(*filename
);
540 Py_DECREF(*filename
);
541 *filename
= PyString_FromString("__main__");
542 if (*filename
== NULL
)
547 /* embedded interpreters don't have sys.argv, see bug #839151 */
548 *filename
= PyString_FromString("__main__");
549 if (*filename
== NULL
)
553 if (*filename
== NULL
) {
555 Py_INCREF(*filename
);
562 /* filename not XDECREF'ed here as there is no way to jump here with a
563 dangling reference. */
564 Py_XDECREF(*registry
);
570 get_category(PyObject
*message
, PyObject
*category
)
575 rc
= PyObject_IsInstance(message
, PyExc_Warning
);
580 category
= (PyObject
*)message
->ob_type
;
581 else if (category
== NULL
)
582 category
= PyExc_UserWarning
;
584 /* Validate category. */
585 rc
= PyObject_IsSubclass(category
, PyExc_Warning
);
589 PyErr_SetString(PyExc_ValueError
,
590 "category is not a subclass of Warning");
598 do_warn(PyObject
*message
, PyObject
*category
, Py_ssize_t stack_level
)
600 PyObject
*filename
, *module
, *registry
, *res
;
603 if (!setup_context(stack_level
, &filename
, &lineno
, &module
, ®istry
))
606 res
= warn_explicit(category
, message
, filename
, lineno
, module
, registry
,
615 warnings_warn(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
617 static char *kw_list
[] = { "message", "category", "stacklevel", 0 };
618 PyObject
*message
, *category
= NULL
;
619 Py_ssize_t stack_level
= 1;
621 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "O|On:warn", kw_list
,
622 &message
, &category
, &stack_level
))
625 category
= get_category(message
, category
);
626 if (category
== NULL
)
628 return do_warn(message
, category
, stack_level
);
632 warnings_warn_explicit(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
634 static char *kwd_list
[] = {"message", "category", "filename", "lineno",
635 "module", "registry", "module_globals", 0};
640 PyObject
*module
= NULL
;
641 PyObject
*registry
= NULL
;
642 PyObject
*module_globals
= NULL
;
644 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "OOOi|OOO:warn_explicit",
645 kwd_list
, &message
, &category
, &filename
, &lineno
, &module
,
646 ®istry
, &module_globals
))
649 if (module_globals
) {
650 static PyObject
*get_source_name
= NULL
;
651 static PyObject
*splitlines_name
= NULL
;
653 PyObject
*module_name
;
655 PyObject
*source_list
;
656 PyObject
*source_line
;
659 if (get_source_name
== NULL
) {
660 get_source_name
= PyString_InternFromString("get_source");
661 if (!get_source_name
)
664 if (splitlines_name
== NULL
) {
665 splitlines_name
= PyString_InternFromString("splitlines");
666 if (!splitlines_name
)
670 /* Check/get the requisite pieces needed for the loader. */
671 loader
= PyDict_GetItemString(module_globals
, "__loader__");
672 module_name
= PyDict_GetItemString(module_globals
, "__name__");
674 if (loader
== NULL
|| module_name
== NULL
)
677 /* Make sure the loader implements the optional get_source() method. */
678 if (!PyObject_HasAttrString(loader
, "get_source"))
680 /* Call get_source() to get the source code. */
681 source
= PyObject_CallMethodObjArgs(loader
, get_source_name
,
685 else if (source
== Py_None
) {
690 /* Split the source into lines. */
691 source_list
= PyObject_CallMethodObjArgs(source
, splitlines_name
,
697 /* Get the source line. */
698 source_line
= PyList_GetItem(source_list
, lineno
-1);
700 Py_DECREF(source_list
);
704 /* Handle the warning. */
705 returned
= warn_explicit(category
, message
, filename
, lineno
, module
,
706 registry
, source_line
);
707 Py_DECREF(source_list
);
712 return warn_explicit(category
, message
, filename
, lineno
, module
,
717 /* Function to issue a warning message; may raise an exception. */
719 PyErr_WarnEx(PyObject
*category
, const char *text
, Py_ssize_t stack_level
)
722 PyObject
*message
= PyString_FromString(text
);
726 if (category
== NULL
)
727 category
= PyExc_RuntimeWarning
;
729 res
= do_warn(message
, category
, stack_level
);
738 /* PyErr_Warn is only for backwards compatability and will be removed.
739 Use PyErr_WarnEx instead. */
744 PyErr_Warn(PyObject
*category
, char *text
)
746 return PyErr_WarnEx(category
, text
, 1);
749 /* Warning with explicit origin */
751 PyErr_WarnExplicit(PyObject
*category
, const char *text
,
752 const char *filename_str
, int lineno
,
753 const char *module_str
, PyObject
*registry
)
756 PyObject
*message
= PyString_FromString(text
);
757 PyObject
*filename
= PyString_FromString(filename_str
);
758 PyObject
*module
= NULL
;
761 if (message
== NULL
|| filename
== NULL
)
763 if (module_str
!= NULL
) {
764 module
= PyString_FromString(module_str
);
769 if (category
== NULL
)
770 category
= PyExc_RuntimeWarning
;
771 res
= warn_explicit(category
, message
, filename
, lineno
, module
, registry
,
781 Py_XDECREF(filename
);
786 PyDoc_STRVAR(warn_doc
,
787 "Issue a warning, or maybe ignore it or raise an exception.");
789 PyDoc_STRVAR(warn_explicit_doc
,
790 "Low-level inferface to warnings functionality.");
792 static PyMethodDef warnings_functions
[] = {
793 {"warn", (PyCFunction
)warnings_warn
, METH_VARARGS
| METH_KEYWORDS
,
795 {"warn_explicit", (PyCFunction
)warnings_warn_explicit
,
796 METH_VARARGS
| METH_KEYWORDS
, warn_explicit_doc
},
797 // XXX(brett.cannon): add showwarning?
798 // XXX(brett.cannon): Reasonable to add formatwarning?
799 {NULL
, NULL
} /* sentinel */
804 create_filter(PyObject
*category
, const char *action
)
806 static PyObject
*ignore_str
= NULL
;
807 static PyObject
*error_str
= NULL
;
808 static PyObject
*default_str
= NULL
;
809 PyObject
*action_obj
= NULL
;
810 PyObject
*lineno
, *result
;
812 if (!strcmp(action
, "ignore")) {
813 if (ignore_str
== NULL
) {
814 ignore_str
= PyString_InternFromString("ignore");
815 if (ignore_str
== NULL
)
818 action_obj
= ignore_str
;
820 else if (!strcmp(action
, "error")) {
821 if (error_str
== NULL
) {
822 error_str
= PyString_InternFromString("error");
823 if (error_str
== NULL
)
826 action_obj
= error_str
;
828 else if (!strcmp(action
, "default")) {
829 if (default_str
== NULL
) {
830 default_str
= PyString_InternFromString("default");
831 if (default_str
== NULL
)
834 action_obj
= default_str
;
837 Py_FatalError("unknown action");
840 /* This assumes the line number is zero for now. */
841 lineno
= PyInt_FromLong(0);
844 result
= PyTuple_Pack(5, action_obj
, Py_None
, category
, Py_None
, lineno
);
852 PyObject
*filters
= PyList_New(3);
853 const char *bytes_action
;
857 PyList_SET_ITEM(filters
, 0,
858 create_filter(PyExc_PendingDeprecationWarning
, "ignore"));
859 PyList_SET_ITEM(filters
, 1, create_filter(PyExc_ImportWarning
, "ignore"));
860 if (Py_BytesWarningFlag
> 1)
861 bytes_action
= "error";
862 else if (Py_BytesWarningFlag
)
863 bytes_action
= "default";
865 bytes_action
= "ignore";
866 PyList_SET_ITEM(filters
, 2, create_filter(PyExc_BytesWarning
,
869 if (PyList_GET_ITEM(filters
, 0) == NULL
||
870 PyList_GET_ITEM(filters
, 1) == NULL
||
871 PyList_GET_ITEM(filters
, 2) == NULL
) {
881 _PyWarnings_Init(void)
883 PyObject
*m
, *default_action
;
885 m
= Py_InitModule3(MODULE_NAME
, warnings_functions
, warnings__doc__
);
889 _filters
= init_filters();
890 if (_filters
== NULL
)
893 if (PyModule_AddObject(m
, "filters", _filters
) < 0)
896 _once_registry
= PyDict_New();
897 if (_once_registry
== NULL
)
899 Py_INCREF(_once_registry
);
900 if (PyModule_AddObject(m
, "once_registry", _once_registry
) < 0)
903 default_action
= PyString_InternFromString("default");
904 if (default_action
== NULL
)
906 if (PyModule_AddObject(m
, DEFAULT_ACTION_NAME
, default_action
) < 0)