From a2724095cd55d75497d9cd48d35911599f4dedda Mon Sep 17 00:00:00 2001 From: Victor Stinner Date: Mon, 8 Feb 2016 18:17:58 +0100 Subject: compiler now ignores constant statements The compile ignores constant statements and emit a SyntaxWarning warning. Don't emit the warning for string statement because triple quoted string is a common syntax for multiline comments. Don't emit the warning on ellipis neither: 'def f(): ...' is a legit syntax for abstract functions. Changes: * test_ast: ignore SyntaxWarning when compiling test statements. Modify test_load_const() to use assignment expressions rather than constant expression. * test_code: add more kinds of constant statements, ignore SyntaxWarning when testing that the compiler removes constant statements. * test_grammar: ignore SyntaxWarning on the statement "1" --- Python/compile.c | 41 ++++++++++++++++++++++++++++++----------- 1 file changed, 30 insertions(+), 11 deletions(-) (limited to 'Python/compile.c') diff --git a/Python/compile.c b/Python/compile.c index ccb05cf1ac8..84b79a2fffd 100644 --- a/Python/compile.c +++ b/Python/compile.c @@ -2616,20 +2616,39 @@ compiler_visit_stmt_expr(struct compiler *c, expr_ty value) return 1; } - if (value->kind == Str_kind || value->kind == Num_kind) { - /* ignore strings and numbers */ + switch (value->kind) + { + case Str_kind: + case Ellipsis_kind: + /* Issue #26204: ignore string statement, but don't emit a + * SyntaxWarning. Triple quoted strings is a common syntax for + * multiline comments. + * + * Don't emit warning on "def f(): ..." neither. It's a legit syntax + * for abstract function. */ return 1; - } - if (value->kind == Constant_kind) { - PyObject *cst = value->v.Constant.value; - if (PyUnicode_CheckExact(cst) - || PyLong_CheckExact(cst) - || PyFloat_CheckExact(cst) - || PyComplex_CheckExact(cst)) { - /* ignore strings and numbers */ - return 1; + case Bytes_kind: + case Num_kind: + case NameConstant_kind: + case Constant_kind: + { + PyObject *msg = PyUnicode_FromString("ignore constant statement"); + if (msg == NULL) + return 0; + if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, + msg, + c->c_filename, c->u->u_lineno, + NULL, NULL) == -1) { + Py_DECREF(msg); + return 0; } + Py_DECREF(msg); + return 1; + } + + default: + break; } VISIT(c, expr, value); -- cgit v1.2.3