Skip to content
Snippets Groups Projects
Commit de9b5369 authored by Damien George's avatar Damien George
Browse files

py: Raise a ValueError if range() step is zero.

Following CPython.  Otherwise one gets either an infinite loop (if code is
optimised by the uPy compiler) or possibly a divide-by-zero CPU exception.
parent 546ef301
Branches
No related tags found
No related merge requests found
...@@ -1444,8 +1444,9 @@ STATIC void compile_for_stmt(compiler_t *comp, mp_parse_node_struct_t *pns) { ...@@ -1444,8 +1444,9 @@ STATIC void compile_for_stmt(compiler_t *comp, mp_parse_node_struct_t *pns) {
pn_range_start = args[0]; pn_range_start = args[0];
pn_range_end = args[1]; pn_range_end = args[1];
pn_range_step = args[2]; pn_range_step = args[2];
// We need to know sign of step. This is possible only if it's constant // the step must be a non-zero constant integer to do the optimisation
if (!MP_PARSE_NODE_IS_SMALL_INT(pn_range_step)) { if (!MP_PARSE_NODE_IS_SMALL_INT(pn_range_step)
|| MP_PARSE_NODE_LEAF_SMALL_INT(pn_range_step) == 0) {
optimize = false; optimize = false;
} }
} }
......
...@@ -105,8 +105,10 @@ STATIC mp_obj_t range_make_new(const mp_obj_type_t *type, size_t n_args, size_t ...@@ -105,8 +105,10 @@ STATIC mp_obj_t range_make_new(const mp_obj_type_t *type, size_t n_args, size_t
o->start = mp_obj_get_int(args[0]); o->start = mp_obj_get_int(args[0]);
o->stop = mp_obj_get_int(args[1]); o->stop = mp_obj_get_int(args[1]);
if (n_args == 3) { if (n_args == 3) {
// TODO check step is non-zero
o->step = mp_obj_get_int(args[2]); o->step = mp_obj_get_int(args[2]);
if (o->step == 0) {
mp_raise_ValueError("zero step");
}
} }
} }
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment