8000 py/emitnative: Initialise locals as Python object type for native code. · micropython/micropython@910f579 · GitHub
[go: up one dir, main page]

Skip to content

Commit 910f579

Browse files
committed
py/emitnative: Initialise locals as Python object type for native code.
In @micropython.native code the types of variables and expressions are always Python objects, so they can be initialised as such. This prevents problems with compiling optimised code like while-loops where a local may be referenced before it is assigned to. Signed-off-by: Damien George <damien@micropython.org>
1 parent ed58d6e commit 910f579

File tree

3 files changed

+14
-1
lines changed

3 files changed

+14
-1
lines changed

py/emitnative.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -401,7 +401,7 @@ STATIC void emit_native_start_pass(emit_t *emit, pass_kind_t pass, scope_t *scop
401401

402402
// local variables begin unbound, and have unknown type
403403
for (mp_uint_t i = num_args; i < emit->local_vtype_alloc; i++) {
404-
emit->local_vtype[i] = VTYPE_UNBOUND;
404+
emit->local_vtype[i] = emit->do_viper_types ? VTYPE_UNBOUND : VTYPE_PYOBJ;
405405
}
406406

407407
// values on stack begin unbound

tests/basics/assign_expr.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,17 @@
1212
print(x, x := 5, x)
1313
print(x)
1414

15+
# Test "while" with assignment expression as conditional, assigning to a new local.
16+
# The while conditional is compiled after the while body, so this tests how the
17+
# compiler handles the case of an unbound local being compiled before it is assigned.
18+
def f():
19+
l = [0, 1]
20+
while local := len(l):
21+
print(local, l.pop())
22+
23+
24+
f()
25+
1526

1627
def foo():
1728
print("any", any((hit := i) % 5 == 3 and (hit % 2) == 0 for i in range(10)))

tests/basics/assign_expr.py.exp

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ True
55
5
66
1 5 5
77
5
8+
2 1
9+
1 0
810
any True
911
8
1012
123

0 commit comments

Comments
 (0)
0