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"
This commit is contained in:
Victor Stinner 2016-02-08 18:17:58 +01:00
parent 51d8c526d5
commit a2724095cd
5 changed files with 95 additions and 47 deletions

View file

@ -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;
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;
}
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;
}
default:
break;
}
VISIT(c, expr, value);