You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
circuitpython/py/runtime.c

1612 lines
61 KiB

/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2013, 2014 Damien P. George
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <stdarg.h>
9 years ago
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include "extmod/vfs.h"
// #include "py/mpstate.h"
// #include "py/nlr.h"
#include "py/parsenum.h"
#include "py/compile.h"
#include "py/objstr.h"
#include "py/objtuple.h"
#include "py/objtype.h"
#include "py/objlist.h"
#include "py/objmodule.h"
#include "py/objgenerator.h"
#include "py/smallint.h"
#include "py/runtime.h"
#include "py/builtin.h"
#include "py/stackctrl.h"
#include "py/gc.h"
#include "supervisor/shared/translate.h"
#if MICROPY_DEBUG_VERBOSE // print debugging info
#define DEBUG_PRINT (1)
#define DEBUG_printf DEBUG_printf
#define DEBUG_OP_printf(...) DEBUG_printf(__VA_ARGS__)
#else // don't print debugging info
#define DEBUG_printf(...) (void)0
#define DEBUG_OP_printf(...) (void)0
#endif
9 years ago
const mp_obj_module_t mp_module___main__ = {
.base = { &mp_type_module },
.globals = (mp_obj_dict_t*)&MP_STATE_VM(dict_main),
};
void mp_init(void) {
qstr_init();
// no pending exceptions to start with
MP_STATE_VM(mp_pending_exception) = MP_OBJ_NULL;
#if MICROPY_ENABLE_SCHEDULER
MP_STATE_VM(sched_state) = MP_SCHED_IDLE;
MP_STATE_VM(sched_sp) = 0;
#endif
#if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF
mp_init_emergency_exception_buf();
#endif
#if MICROPY_KBD_EXCEPTION
// initialise the exception object for raising KeyboardInterrupt
MP_STATE_VM(mp_kbd_exception).base.type = &mp_type_KeyboardInterrupt;
MP_STATE_VM(mp_kbd_exception).traceback_alloc = 0;
MP_STATE_VM(mp_kbd_exception).traceback_len = 0;
MP_STATE_VM(mp_kbd_exception).traceback_data = NULL;
MP_STATE_VM(mp_kbd_exception).args = (mp_obj_tuple_t*)&mp_const_empty_tuple_obj;
#endif
MP_STATE_VM(mp_reload_exception).base.type = &mp_type_ReloadException;
MP_STATE_VM(mp_reload_exception).traceback_alloc = 0;
MP_STATE_VM(mp_reload_exception).traceback_len = 0;
MP_STATE_VM(mp_reload_exception).traceback_data = NULL;
MP_STATE_VM(mp_reload_exception).args = (mp_obj_tuple_t*)&mp_const_empty_tuple_obj;
// call port specific initialization if any
#ifdef MICROPY_PORT_INIT_FUNC
MICROPY_PORT_INIT_FUNC;
#endif
#if MICROPY_ENABLE_COMPILER
// optimization disabled by default
MP_STATE_VM(mp_optimise_value) = 0;
#endif
// init global module dict
mp_obj_dict_init(&MP_STATE_VM(mp_loaded_modules_dict), 3);
// initialise the __main__ module
mp_obj_dict_init(&MP_STATE_VM(dict_main), 1);
mp_obj_dict_store(MP_OBJ_FROM_PTR(&MP_STATE_VM(dict_main)), MP_OBJ_NEW_QSTR(MP_QSTR___name__), MP_OBJ_NEW_QSTR(MP_QSTR___main__));
// locals = globals for outer module (see Objects/frameobject.c/PyFrame_New())
mp_locals_set(&MP_STATE_VM(dict_main));
mp_globals_set(&MP_STATE_VM(dict_main));
#if MICROPY_CAN_OVERRIDE_BUILTINS
// start with no extensions to builtins
MP_STATE_VM(mp_module_builtins_override_dict) = NULL;
#endif
#if MICROPY_PY_OS_DUPTERM
for (size_t i = 0; i < MICROPY_PY_OS_DUPTERM; ++i) {
MP_STATE_VM(dupterm_objs[i]) = MP_OBJ_NULL;
}
MP_STATE_VM(dupterm_arr_obj) = MP_OBJ_NULL;
#endif
Merge tag 'v1.9.1' Fixes for stmhal USB mass storage, lwIP bindings and VFS regressions This release provides an important fix for the USB mass storage device in the stmhal port by implementing the SCSI SYNCHRONIZE_CACHE command, which is now require by some Operating Systems. There are also fixes for the lwIP bindings to improve non-blocking sockets and error codes. The VFS has some regressions fixed including the ability to statvfs the root. All changes are listed below. py core: - modbuiltins: add core-provided version of input() function - objstr: catch case of negative "maxsplit" arg to str.rsplit() - persistentcode: allow to compile with complex numbers disabled - objstr: allow to compile with obj-repr D, and unicode disabled - modsys: allow to compile with obj-repr D and PY_ATTRTUPLE disabled - provide mp_decode_uint_skip() to help reduce stack usage - makeqstrdefs.py: make script run correctly with Python 2.6 - objstringio: if created from immutable object, follow copy on write policy extmod: - modlwip: connect: for non-blocking mode, return EINPROGRESS - modlwip: fix error codes for duplicate calls to connect() - modlwip: accept: fix error code for non-blocking mode - vfs: allow to statvfs the root directory - vfs: allow "buffering" and "encoding" args to VFS's open() - modframebuf: fix signed/unsigned comparison pendantic warning lib: - libm: use isfinite instead of finitef, for C99 compatibility - utils/interrupt_char: remove support for KBD_EXCEPTION disabled tests: - basics/string_rsplit: add tests for negative "maxsplit" argument - float: convert "sys.exit()" to "raise SystemExit" - float/builtin_float_minmax: PEP8 fixes - basics: convert "sys.exit()" to "raise SystemExit" - convert remaining "sys.exit()" to "raise SystemExit" unix port: - convert to use core-provided version of built-in import() - Makefile: replace references to make with $(MAKE) windows port: - convert to use core-provided version of built-in import() qemu-arm port: - Makefile: adjust object-file lists to get correct dependencies - enable micropython.mem_*() functions to allow more tests stmhal port: - boards: enable DAC for NUCLEO_F767ZI board - add support for NUCLEO_F446RE board - pass USB handler as parameter to allow more than one USB handler - usb: use local USB handler variable in Start-of-Frame handler - usb: make state for USB device private to top-level USB driver - usbdev: for MSC implement SCSI SYNCHRONIZE_CACHE command - convert from using stmhal's input() to core provided version cc3200 port: - convert from using stmhal's input() to core provided version teensy port: - convert from using stmhal's input() to core provided version esp8266 port: - Makefile: replace references to make with $(MAKE) - Makefile: add clean-modules target - convert from using stmhal's input() to core provided version zephyr port: - modusocket: getaddrinfo: Fix mp_obj_len() usage - define MICROPY_PY_SYS_PLATFORM (to "zephyr") - machine_pin: use native Zephyr types for Zephyr API calls docs: - machine.Pin: remove out_value() method - machine.Pin: add on() and off() methods - esp8266: consistently replace Pin.high/low methods with .on/off - esp8266/quickref: polish Pin.on()/off() examples - network: move confusingly-named cc3200 Server class to its reference - uos: deconditionalize, remove minor port-specific details - uos: move cc3200 port legacy VFS mounting functions to its ref doc - machine: sort machine classes in logical order, not alphabetically - network: first step to describe standard network class interface examples: - embedding: use core-provided KeyboardInterrupt object
6 years ago
#ifdef MICROPY_FSUSERMOUNT
// zero out the pointers to the user-mounted devices
memset(MP_STATE_VM(fs_user_mount) + MICROPY_FATFS_NUM_PERSISTENT, 0,
sizeof(MP_STATE_VM(fs_user_mount)) - MICROPY_FATFS_NUM_PERSISTENT);
#endif
#if MICROPY_VFS
#if MICROPY_FATFS_NUM_PERSISTENT > 0
// We preserve the last MICROPY_FATFS_NUM_PERSISTENT mounts because newer
// mounts are put at the front of the list.
mp_vfs_mount_t *vfs = MP_STATE_VM(vfs_mount_table);
// Count how many mounts we have.
uint8_t count = 0;
while (vfs != NULL) {
vfs = vfs->next;
count++;
}
// Find the vfs MICROPY_FATFS_NUM_PERSISTENT mounts from the end.
vfs = MP_STATE_VM(vfs_mount_table);
for (uint8_t j = 0; j < count - MICROPY_FATFS_NUM_PERSISTENT; j++) {
vfs = vfs->next;
}
MP_STATE_VM(vfs_mount_table) = vfs;
MP_STATE_VM(vfs_cur) = vfs;
#else
// initialise the VFS sub-system
MP_STATE_VM(vfs_cur) = NULL;
MP_STATE_VM(vfs_mount_table) = NULL;
#endif
#endif
#if MICROPY_PY_THREAD_GIL
mp_thread_mutex_init(&MP_STATE_VM(gil_mutex));
#endif
MP_THREAD_GIL_ENTER();
9 years ago
}
void mp_deinit(void) {
//mp_obj_dict_free(&dict_main);
//mp_map_deinit(&MP_STATE_VM(mp_loaded_modules_map));
// call port specific deinitialization if any
#ifdef MICROPY_PORT_INIT_FUNC
MICROPY_PORT_DEINIT_FUNC;
#endif
9 years ago
}
mp_obj_t mp_load_name(qstr qst) {
9 years ago
// logic: search locals, globals, builtins
DEBUG_OP_printf("load name %s\n", qstr_str(qst));
// If we're at the outer scope (locals == globals), dispatch to load_global right away
if (mp_locals_get() != mp_globals_get()) {
mp_map_elem_t *elem = mp_map_lookup(&mp_locals_get()->map, MP_OBJ_NEW_QSTR(qst), MP_MAP_LOOKUP);
if (elem != NULL) {
return elem->value;
}
9 years ago
}
return mp_load_global(qst);
9 years ago
}
mp_obj_t mp_load_global(qstr qst) {
// logic: search globals, builtins
DEBUG_OP_printf("load global %s\n", qstr_str(qst));
mp_map_elem_t *elem = mp_map_lookup(&mp_globals_get()->map, MP_OBJ_NEW_QSTR(qst), MP_MAP_LOOKUP);
if (elem == NULL) {
#if MICROPY_CAN_OVERRIDE_BUILTINS
if (MP_STATE_VM(mp_module_builtins_override_dict) != NULL) {
// lookup in additional dynamic table of builtins first
elem = mp_map_lookup(&MP_STATE_VM(mp_module_builtins_override_dict)->map, MP_OBJ_NEW_QSTR(qst), MP_MAP_LOOKUP);
if (elem != NULL) {
return elem->value;
}
}
#endif
elem = mp_map_lookup((mp_map_t*)&mp_module_builtins_globals.map, MP_OBJ_NEW_QSTR(qst), MP_MAP_LOOKUP);
if (elem == NULL) {
if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
mp_raise_msg(&mp_type_NameError, translate("name not defined"));
} else {
nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_NameError,
translate("name '%q' is not defined"), qst));
}
}
}
return elem->value;
9 years ago
}
mp_obj_t mp_load_build_class(void) {
9 years ago
DEBUG_OP_printf("load_build_class\n");
#if MICROPY_CAN_OVERRIDE_BUILTINS
if (MP_STATE_VM(mp_module_builtins_override_dict) != NULL) {
// lookup in additional dynamic table of builtins first
mp_map_elem_t *elem = mp_map_lookup(&MP_STATE_VM(mp_module_builtins_override_dict)->map, MP_OBJ_NEW_QSTR(MP_QSTR___build_class__), MP_MAP_LOOKUP);
if (elem != NULL) {
return elem->value;
}
}
#endif
return MP_OBJ_FROM_PTR(&mp_builtin___build_class___obj);
9 years ago
}
void mp_store_name(qstr qst, mp_obj_t obj) {
DEBUG_OP_printf("store name %s <- %p\n", qstr_str(qst), obj);
mp_obj_dict_store(MP_OBJ_FROM_PTR(mp_locals_get()), MP_OBJ_NEW_QSTR(qst), obj);
}
void mp_delete_name(qstr qst) {
DEBUG_OP_printf("delete name %s\n", qstr_str(qst));
// TODO convert KeyError to NameError if qst not found
mp_obj_dict_delete(MP_OBJ_FROM_PTR(mp_locals_get()), MP_OBJ_NEW_QSTR(qst));
}
void mp_store_global(qstr qst, mp_obj_t obj) {
DEBUG_OP_printf("store global %s <- %p\n", qstr_str(qst), obj);
mp_obj_dict_store(MP_OBJ_FROM_PTR(mp_globals_get()), MP_OBJ_NEW_QSTR(qst), obj);
9 years ago
}
void mp_delete_global(qstr qst) {
DEBUG_OP_printf("delete global %s\n", qstr_str(qst));
// TODO convert KeyError to NameError if qst not found
mp_obj_dict_delete(MP_OBJ_FROM_PTR(mp_globals_get()), MP_OBJ_NEW_QSTR(qst));
}
mp_obj_t mp_unary_op(mp_unary_op_t op, mp_obj_t arg) {
DEBUG_OP_printf("unary " UINT_FMT " %q %p\n", op, mp_unary_op_method_name[op], arg);
if (op == MP_UNARY_OP_NOT) {
// "not x" is the negative of whether "x" is true per Python semantics
return mp_obj_new_bool(mp_obj_is_true(arg) == 0);
} else if (MP_OBJ_IS_SMALL_INT(arg)) {
mp_int_t val = MP_OBJ_SMALL_INT_VALUE(arg);
switch (op) {
case MP_UNARY_OP_BOOL:
return mp_obj_new_bool(val != 0);
case MP_UNARY_OP_HASH:
return arg;
case MP_UNARY_OP_POSITIVE:
return arg;
case MP_UNARY_OP_NEGATIVE:
// check for overflow
if (val == MP_SMALL_INT_MIN) {
return mp_obj_new_int(-val);
} else {
return MP_OBJ_NEW_SMALL_INT(-val);
}
case MP_UNARY_OP_ABS:
if (val >= 0) {
return arg;
} else if (val == MP_SMALL_INT_MIN) {
// check for overflow
return mp_obj_new_int(-val);
} else {
return MP_OBJ_NEW_SMALL_INT(-val);
}
default:
assert(op == MP_UNARY_OP_INVERT);
return MP_OBJ_NEW_SMALL_INT(~val);
}
} else if (op == MP_UNARY_OP_HASH && MP_OBJ_IS_STR_OR_BYTES(arg)) {
// fast path for hashing str/bytes
GET_STR_HASH(arg, h);
if (h == 0) {
GET_STR_DATA_LEN(arg, data, len);
h = qstr_compute_hash(data, len);
}
return MP_OBJ_NEW_SMALL_INT(h);
} else {
mp_obj_type_t *type = mp_obj_get_type(arg);
if (type->unary_op != NULL) {
mp_obj_t result = type->unary_op(op, arg);
if (result != MP_OBJ_NULL) {
return result;
}
}
if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
mp_raise_TypeError(translate("unsupported type for operator"));
} else {
mp_raise_TypeError_varg(
translate("unsupported type for %q: '%s'"),
mp_unary_op_method_name[op], mp_obj_get_type_str(arg));
}
}
9 years ago
}
mp_obj_t mp_binary_op(mp_binary_op_t op, mp_obj_t lhs, mp_obj_t rhs) {
DEBUG_OP_printf("binary " UINT_FMT " %q %p %p\n", op, mp_binary_op_method_name[op], lhs, rhs);
// TODO correctly distinguish inplace operators for mutable objects
// lookup logic that CPython uses for +=:
// check for implemented +=
// then check for implemented +
// then check for implemented seq.inplace_concat
// then check for implemented seq.concat
// then fail
// note that list does not implement + or +=, so that inplace_concat is reached first for +=
// deal with is
if (op == MP_BINARY_OP_IS) {
return mp_obj_new_bool(lhs == rhs);
}
// deal with == and != for all types
if (op == MP_BINARY_OP_EQUAL || op == MP_BINARY_OP_NOT_EQUAL) {
if (mp_obj_equal(lhs, rhs)) {
if (op == MP_BINARY_OP_EQUAL) {
return mp_const_true;
} else {
return mp_const_false;
}
} else {
if (op == MP_BINARY_OP_EQUAL) {
return mp_const_false;
} else {
return mp_const_true;
}
}
}
// deal with exception_match for all types
if (op == MP_BINARY_OP_EXCEPTION_MATCH) {
// rhs must be issubclass(rhs, BaseException)
if (mp_obj_is_exception_type(rhs)) {
if (mp_obj_exception_match(lhs, rhs)) {
return mp_const_true;
} else {
return mp_const_false;
}
} else if (MP_OBJ_IS_TYPE(rhs, &mp_type_tuple)) {
mp_obj_tuple_t *tuple = MP_OBJ_TO_PTR(rhs);
for (size_t i = 0; i < tuple->len; i++) {
rhs = tuple->items[i];
if (!mp_obj_is_exception_type(rhs)) {
goto unsupported_op;
}
if (mp_obj_exception_match(lhs, rhs)) {
return mp_const_true;
}
}
return mp_const_false;
}
goto unsupported_op;
}
if (MP_OBJ_IS_SMALL_INT(lhs)) {
mp_int_t lhs_val = MP_OBJ_SMALL_INT_VALUE(lhs);
if (MP_OBJ_IS_SMALL_INT(rhs)) {
mp_int_t rhs_val = MP_OBJ_SMALL_INT_VALUE(rhs);
// This is a binary operation: lhs_val op rhs_val
// We need to be careful to handle overflow; see CERT INT32-C
// Operations that can overflow:
// + result always fits in mp_int_t, then handled by SMALL_INT check
// - result always fits in mp_int_t, then handled by SMALL_INT check
// * checked explicitly
// / if lhs=MIN and rhs=-1; result always fits in mp_int_t, then handled by SMALL_INT check
// % if lhs=MIN and rhs=-1; result always fits in mp_int_t, then handled by SMALL_INT check
// << checked explicitly
switch (op) {
case MP_BINARY_OP_OR:
case MP_BINARY_OP_INPLACE_OR: lhs_val |= rhs_val; break;
case MP_BINARY_OP_XOR:
case MP_BINARY_OP_INPLACE_XOR: lhs_val ^= rhs_val; break;
case MP_BINARY_OP_AND:
case MP_BINARY_OP_INPLACE_AND: lhs_val &= rhs_val; break;
case MP_BINARY_OP_LSHIFT:
case MP_BINARY_OP_INPLACE_LSHIFT: {
if (rhs_val < 0) {
// negative shift not allowed
mp_raise_ValueError(translate("negative shift count"));
} else if (rhs_val >= (mp_int_t)BITS_PER_WORD || lhs_val > (MP_SMALL_INT_MAX >> rhs_val) || lhs_val < (MP_SMALL_INT_MIN >> rhs_val)) {
// left-shift will overflow, so use higher precision integer
lhs = mp_obj_new_int_from_ll(lhs_val);
goto generic_binary_op;
} else {
// use standard precision
lhs_val <<= rhs_val;
}
break;
}
case MP_BINARY_OP_RSHIFT:
case MP_BINARY_OP_INPLACE_RSHIFT:
if (rhs_val < 0) {
// negative shift not allowed
mp_raise_ValueError(translate("negative shift count"));
} else {
// standard precision is enough for right-shift
if (rhs_val >= (mp_int_t)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;
case MP_BINARY_OP_ADD:
case MP_BINARY_OP_INPLACE_ADD: lhs_val += rhs_val; break;
case MP_BINARY_OP_SUBTRACT:
case MP_BINARY_OP_INPLACE_SUBTRACT: lhs_val -= rhs_val; break;
case MP_BINARY_OP_MULTIPLY:
case MP_BINARY_OP_INPLACE_MULTIPLY: {
// If long long type exists and is larger than mp_int_t, then
// we can use the following code to perform overflow-checked multiplication.
// Otherwise (eg in x64 case) we must use mp_small_int_mul_overflow.
#if 0
// compute result using long long precision
long long res = (long long)lhs_val * (long long)rhs_val;
if (res > MP_SMALL_INT_MAX || res < MP_SMALL_INT_MIN) {
// result overflowed SMALL_INT, so return higher precision integer
return mp_obj_new_int_from_ll(res);
} else {
// use standard precision
lhs_val = (mp_int_t)res;
}
#endif
if (mp_small_int_mul_overflow(lhs_val, rhs_val)) {
// use higher precision
lhs = mp_obj_new_int_from_ll(lhs_val);
goto generic_binary_op;
} else {
// use standard precision
return MP_OBJ_NEW_SMALL_INT(lhs_val * rhs_val);
}
}
case MP_BINARY_OP_FLOOR_DIVIDE:
case MP_BINARY_OP_INPLACE_FLOOR_DIVIDE:
if (rhs_val == 0) {
goto zero_division;
}
lhs_val = mp_small_int_floor_divide(lhs_val, rhs_val);
break;
#if MICROPY_PY_BUILTINS_FLOAT
case MP_BINARY_OP_TRUE_DIVIDE:
case MP_BINARY_OP_INPLACE_TRUE_DIVIDE:
if (rhs_val == 0) {
goto zero_division;
}
return mp_obj_new_float((mp_float_t)lhs_val / (mp_float_t)rhs_val);
#endif
case MP_BINARY_OP_MODULO:
case MP_BINARY_OP_INPLACE_MODULO: {
if (rhs_val == 0) {
goto zero_division;
}
lhs_val = mp_small_int_modulo(lhs_val, rhs_val);
break;
}
case MP_BINARY_OP_POWER:
case MP_BINARY_OP_INPLACE_POWER:
if (rhs_val < 0) {
#if MICROPY_PY_BUILTINS_FLOAT
lhs = mp_obj_new_float(lhs_val);
goto generic_binary_op;
#else
mp_raise_ValueError(translate("negative power with no float support"));
#endif
} else {
mp_int_t ans = 1;
while (rhs_val > 0) {
if (rhs_val & 1) {
if (mp_small_int_mul_overflow(ans, lhs_val)) {
goto power_overflow;
}
ans *= lhs_val;
}
if (rhs_val == 1) {
break;
}
rhs_val /= 2;
if (mp_small_int_mul_overflow(lhs_val, lhs_val)) {
goto power_overflow;
}
lhs_val *= lhs_val;
}
lhs_val = ans;
}
break;
power_overflow:
// use higher precision
lhs = mp_obj_new_int_from_ll(MP_OBJ_SMALL_INT_VALUE(lhs));
goto generic_binary_op;
case MP_BINARY_OP_DIVMOD: {
if (rhs_val == 0) {
goto zero_division;
}
// to reduce stack usage we don't pass a temp array of the 2 items
mp_obj_tuple_t *tuple = MP_OBJ_TO_PTR(mp_obj_new_tuple(2, NULL));
tuple->items[0] = MP_OBJ_NEW_SMALL_INT(mp_small_int_floor_divide(lhs_val, rhs_val));
tuple->items[1] = MP_OBJ_NEW_SMALL_INT(mp_small_int_modulo(lhs_val, rhs_val));
return MP_OBJ_FROM_PTR(tuple);
}
case MP_BINARY_OP_LESS: return mp_obj_new_bool(lhs_val < rhs_val);
case MP_BINARY_OP_MORE: return mp_obj_new_bool(lhs_val > rhs_val);
case MP_BINARY_OP_LESS_EQUAL: return mp_obj_new_bool(lhs_val <= rhs_val);
case MP_BINARY_OP_MORE_EQUAL: return mp_obj_new_bool(lhs_val >= rhs_val);
default:
goto unsupported_op;
}
// TODO: We just should make mp_obj_new_int() inline and use that
if (MP_SMALL_INT_FITS(lhs_val)) {
return MP_OBJ_NEW_SMALL_INT(lhs_val);
} else {
return mp_obj_new_int(lhs_val);
}
#if MICROPY_PY_BUILTINS_FLOAT
} else if (mp_obj_is_float(rhs)) {
mp_obj_t res = mp_obj_float_binary_op(op, lhs_val, rhs);
if (res == MP_OBJ_NULL) {
goto unsupported_op;
} else {
return res;
}
#if MICROPY_PY_BUILTINS_COMPLEX
} else if (MP_OBJ_IS_TYPE(rhs, &mp_type_complex)) {
mp_obj_t res = mp_obj_complex_binary_op(op, lhs_val, 0, rhs);
if (res == MP_OBJ_NULL) {
goto unsupported_op;
} else {
return res;
}
#endif
#endif
}
}
// Convert MP_BINARY_OP_IN to MP_BINARY_OP_CONTAINS with swapped args.
if (op == MP_BINARY_OP_IN) {
op = MP_BINARY_OP_CONTAINS;
mp_obj_t temp = lhs;
lhs = rhs;
rhs = temp;
}
// generic binary_op supplied by type
mp_obj_type_t *type;
generic_binary_op:
type = mp_obj_get_type(lhs);
if (type->binary_op != NULL) {
mp_obj_t result = type->binary_op(op, lhs, rhs);
if (result != MP_OBJ_NULL) {
return result;
9 years ago
}
}
#if MICROPY_PY_REVERSE_SPECIAL_METHODS
if (op >= MP_BINARY_OP_OR && op <= MP_BINARY_OP_REVERSE_POWER) {
mp_obj_t t = rhs;
rhs = lhs;
lhs = t;
if (op <= MP_BINARY_OP_POWER) {
op += MP_BINARY_OP_REVERSE_OR - MP_BINARY_OP_OR;
goto generic_binary_op;
}
// Convert __rop__ back to __op__ for error message
op -= MP_BINARY_OP_REVERSE_OR - MP_BINARY_OP_OR;
}
#endif
if (op == MP_BINARY_OP_CONTAINS) {
// If type didn't support containment then explicitly walk the iterator.
// mp_getiter will raise the appropriate exception if lhs is not iterable.
mp_obj_iter_buf_t iter_buf;
mp_obj_t iter = mp_getiter(lhs, &iter_buf);
mp_obj_t next;
while ((next = mp_iternext(iter)) != MP_OBJ_STOP_ITERATION) {