py/native: Improve support for bool type in viper functions.
Variables with type bool now act more like an int, and there is proper casting to/from Python objects.
This commit is contained in:
parent
9a6f6fd68d
commit
5ea38e4d74
@ -1356,7 +1356,7 @@ STATIC void emit_native_load_global(emit_t *emit, qstr qst, int kind) {
|
||||
if (emit->do_viper_types) {
|
||||
// check for builtin casting operators
|
||||
int native_type = mp_native_type_from_qstr(qst);
|
||||
if (native_type >= MP_NATIVE_TYPE_INT) {
|
||||
if (native_type >= MP_NATIVE_TYPE_BOOL) {
|
||||
emit_post_push_imm(emit, VTYPE_BUILTIN_CAST, native_type);
|
||||
return;
|
||||
}
|
||||
|
@ -60,7 +60,7 @@ mp_uint_t mp_native_from_obj(mp_obj_t obj, mp_uint_t type) {
|
||||
DEBUG_printf("mp_native_from_obj(%p, " UINT_FMT ")\n", obj, type);
|
||||
switch (type & 0xf) {
|
||||
case MP_NATIVE_TYPE_OBJ: return (mp_uint_t)obj;
|
||||
case MP_NATIVE_TYPE_BOOL:
|
||||
case MP_NATIVE_TYPE_BOOL: return mp_obj_is_true(obj);
|
||||
case MP_NATIVE_TYPE_INT:
|
||||
case MP_NATIVE_TYPE_UINT: return mp_obj_get_int_truncated(obj);
|
||||
default: { // cast obj to a pointer
|
||||
|
26
tests/micropython/viper_types.py
Normal file
26
tests/micropython/viper_types.py
Normal file
@ -0,0 +1,26 @@
|
||||
# test various type conversions
|
||||
|
||||
import micropython
|
||||
|
||||
# converting incoming arg to bool
|
||||
@micropython.viper
|
||||
def f1(x:bool):
|
||||
print(x)
|
||||
f1(0)
|
||||
f1(1)
|
||||
f1([])
|
||||
f1([1])
|
||||
|
||||
# taking and returning a bool
|
||||
@micropython.viper
|
||||
def f2(x:bool) -> bool:
|
||||
return x
|
||||
print(f2([]))
|
||||
print(f2([1]))
|
||||
|
||||
# converting to bool within function
|
||||
@micropython.viper
|
||||
def f3(x) -> bool:
|
||||
return bool(x)
|
||||
print(f3([]))
|
||||
print(f3(-1))
|
8
tests/micropython/viper_types.py.exp
Normal file
8
tests/micropython/viper_types.py.exp
Normal file
@ -0,0 +1,8 @@
|
||||
False
|
||||
True
|
||||
False
|
||||
True
|
||||
False
|
||||
True
|
||||
False
|
||||
True
|
Loading…
Reference in New Issue
Block a user