py: Fix bug with right-shifting small ints by large amounts.
Undefined behavior in C, needs explicit check.
diff --git a/py/compile.c b/py/compile.c
index 61b8278..3633503 100644
--- a/py/compile.c
+++ b/py/compile.c
@@ -233,6 +233,11 @@
}
} else if (MP_PARSE_NODE_IS_TOKEN_KIND(pns->nodes[1], MP_TOKEN_OP_DBL_MORE)) {
// int >> int
+ if (arg1 >= BITS_PER_WORD) {
+ // Shifting to big amounts is underfined behavior
+ // in C and is CPU-dependent; propagate sign bit.
+ arg1 = BITS_PER_WORD - 1;
+ }
pn = mp_parse_node_new_leaf(MP_PARSE_NODE_SMALL_INT, arg0 >> arg1);
} else {
// shouldn't happen
diff --git a/py/runtime.c b/py/runtime.c
index f6f34be..e225ba8 100644
--- a/py/runtime.c
+++ b/py/runtime.c
@@ -337,6 +337,11 @@
nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "negative shift count"));
} else {
// standard precision is enough for right-shift
+ if (rhs_val >= BITS_PER_WORD) {
+ // Shifting to big amounts is underfined behavior
+ // in C and is CPU-dependent; propagate sign bit.
+ rhs_val = BITS_PER_WORD - 1;
+ }
lhs_val >>= rhs_val;
}
break;