code stringlengths 1 1.05M | repo_name stringlengths 6 83 | path stringlengths 3 242 | language stringclasses 222 values | license stringclasses 20 values | size int64 1 1.05M |
|---|---|---|---|---|---|
/*
* 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 <stdlib.h>
#include "py/runtime.h"
// this is a wrapper object that turns something that has a __getitem__ method into an iterator
typedef struct _mp_obj_getitem_iter_t {
mp_obj_base_t base;
mp_obj_t args[3];
} mp_obj_getitem_iter_t;
STATIC mp_obj_t it_iternext(mp_obj_t self_in) {
mp_obj_getitem_iter_t *self = MP_OBJ_TO_PTR(self_in);
nlr_buf_t nlr;
if (nlr_push(&nlr) == 0) {
// try to get next item
mp_obj_t value = mp_call_method_n_kw(1, 0, self->args);
self->args[2] = MP_OBJ_NEW_SMALL_INT(MP_OBJ_SMALL_INT_VALUE(self->args[2]) + 1);
nlr_pop();
return value;
} else {
// an exception was raised
mp_obj_type_t *t = (mp_obj_type_t *)((mp_obj_base_t *)nlr.ret_val)->type;
if (t == &mp_type_StopIteration || t == &mp_type_IndexError) {
return MP_OBJ_STOP_ITERATION;
} else {
// re-raise exception
nlr_jump(nlr.ret_val);
}
}
}
STATIC const mp_obj_type_t mp_type_it = {
{ &mp_type_type },
.name = MP_QSTR_iterator,
.getiter = mp_identity_getiter,
.iternext = it_iternext,
};
// args are those returned from mp_load_method_maybe (ie either an attribute or a method)
mp_obj_t mp_obj_new_getitem_iter(mp_obj_t *args, mp_obj_iter_buf_t *iter_buf) {
assert(sizeof(mp_obj_getitem_iter_t) <= sizeof(mp_obj_iter_buf_t));
mp_obj_getitem_iter_t *o = (mp_obj_getitem_iter_t *)iter_buf;
o->base.type = &mp_type_it;
o->args[0] = args[0];
o->args[1] = args[1];
o->args[2] = MP_OBJ_NEW_SMALL_INT(0);
return MP_OBJ_FROM_PTR(o);
}
| YifuLiu/AliOS-Things | components/py_engine/engine/py/objgetitemiter.c | C | apache-2.0 | 2,848 |
/*
* 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 <stdlib.h>
#include <assert.h>
#include <string.h>
#include "py/parsenum.h"
#include "py/smallint.h"
#include "py/objint.h"
#include "py/objstr.h"
#include "py/runtime.h"
#include "py/binary.h"
#if MICROPY_PY_BUILTINS_FLOAT
#include <math.h>
#endif
// This dispatcher function is expected to be independent of the implementation of long int
STATIC mp_obj_t mp_obj_int_make_new(const mp_obj_type_t *type_in, size_t n_args, size_t n_kw, const mp_obj_t *args) {
(void)type_in;
mp_arg_check_num(n_args, n_kw, 0, 2, false);
switch (n_args) {
case 0:
return MP_OBJ_NEW_SMALL_INT(0);
case 1:
if (mp_obj_is_int(args[0])) {
// already an int (small or long), just return it
return args[0];
} else if (mp_obj_is_str_or_bytes(args[0])) {
// a string, parse it
size_t l;
const char *s = mp_obj_str_get_data(args[0], &l);
return mp_parse_num_integer(s, l, 0, NULL);
#if MICROPY_PY_BUILTINS_FLOAT
} else if (mp_obj_is_float(args[0])) {
return mp_obj_new_int_from_float(mp_obj_float_get(args[0]));
#endif
} else {
return mp_unary_op(MP_UNARY_OP_INT, args[0]);
}
case 2:
default: {
// should be a string, parse it
size_t l;
const char *s = mp_obj_str_get_data(args[0], &l);
return mp_parse_num_integer(s, l, mp_obj_get_int(args[1]), NULL);
}
}
}
#if MICROPY_PY_BUILTINS_FLOAT
typedef enum {
MP_FP_CLASS_FIT_SMALLINT,
MP_FP_CLASS_FIT_LONGINT,
MP_FP_CLASS_OVERFLOW
} mp_fp_as_int_class_t;
STATIC mp_fp_as_int_class_t mp_classify_fp_as_int(mp_float_t val) {
union {
mp_float_t f;
#if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT
uint32_t i;
#elif MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE
uint32_t i[2];
#endif
} u = {val};
uint32_t e;
#if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT
e = u.i;
#elif MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE
e = u.i[MP_ENDIANNESS_LITTLE];
#endif
#define MP_FLOAT_SIGN_SHIFT_I32 ((MP_FLOAT_FRAC_BITS + MP_FLOAT_EXP_BITS) % 32)
#define MP_FLOAT_EXP_SHIFT_I32 (MP_FLOAT_FRAC_BITS % 32)
if (e & (1U << MP_FLOAT_SIGN_SHIFT_I32)) {
#if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE
e |= u.i[MP_ENDIANNESS_BIG] != 0;
#endif
if ((e & ~(1U << MP_FLOAT_SIGN_SHIFT_I32)) == 0) {
// handle case of -0 (when sign is set but rest of bits are zero)
e = 0;
} else {
e += ((1U << MP_FLOAT_EXP_BITS) - 1) << MP_FLOAT_EXP_SHIFT_I32;
}
} else {
e &= ~((1U << MP_FLOAT_EXP_SHIFT_I32) - 1);
}
// 8 * sizeof(uintptr_t) counts the number of bits for a small int
// TODO provide a way to configure this properly
if (e <= ((8 * sizeof(uintptr_t) + MP_FLOAT_EXP_BIAS - 3) << MP_FLOAT_EXP_SHIFT_I32)) {
return MP_FP_CLASS_FIT_SMALLINT;
}
#if MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_LONGLONG
if (e <= (((sizeof(long long) * MP_BITS_PER_BYTE) + MP_FLOAT_EXP_BIAS - 2) << MP_FLOAT_EXP_SHIFT_I32)) {
return MP_FP_CLASS_FIT_LONGINT;
}
#endif
#if MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_MPZ
return MP_FP_CLASS_FIT_LONGINT;
#else
return MP_FP_CLASS_OVERFLOW;
#endif
}
#undef MP_FLOAT_SIGN_SHIFT_I32
#undef MP_FLOAT_EXP_SHIFT_I32
mp_obj_t mp_obj_new_int_from_float(mp_float_t val) {
mp_float_union_t u = {val};
// IEEE-754: if biased exponent is all 1 bits...
if (u.p.exp == ((1 << MP_FLOAT_EXP_BITS) - 1)) {
// ...then number is Inf (positive or negative) if fraction is 0, else NaN.
if (u.p.frc == 0) {
mp_raise_msg(&mp_type_OverflowError, MP_ERROR_TEXT("can't convert inf to int"));
} else {
mp_raise_ValueError(MP_ERROR_TEXT("can't convert NaN to int"));
}
} else {
mp_fp_as_int_class_t icl = mp_classify_fp_as_int(val);
if (icl == MP_FP_CLASS_FIT_SMALLINT) {
return MP_OBJ_NEW_SMALL_INT((mp_int_t)val);
#if MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_MPZ
} else {
mp_obj_int_t *o = mp_obj_int_new_mpz();
mpz_set_from_float(&o->mpz, val);
return MP_OBJ_FROM_PTR(o);
}
#else
#if MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_LONGLONG
} else if (icl == MP_FP_CLASS_FIT_LONGINT) {
return mp_obj_new_int_from_ll((long long)val);
#endif
} else {
mp_raise_ValueError(MP_ERROR_TEXT("float too big"));
}
#endif
}
}
#endif
#if MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_LONGLONG
typedef mp_longint_impl_t fmt_int_t;
typedef unsigned long long fmt_uint_t;
#else
typedef mp_int_t fmt_int_t;
typedef mp_uint_t fmt_uint_t;
#endif
void mp_obj_int_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
(void)kind;
// The size of this buffer is rather arbitrary. If it's not large
// enough, a dynamic one will be allocated.
char stack_buf[sizeof(fmt_int_t) * 4];
char *buf = stack_buf;
size_t buf_size = sizeof(stack_buf);
size_t fmt_size;
char *str = mp_obj_int_formatted(&buf, &buf_size, &fmt_size, self_in, 10, NULL, '\0', '\0');
mp_print_str(print, str);
if (buf != stack_buf) {
m_del(char, buf, buf_size);
}
}
STATIC const uint8_t log_base2_floor[] = {
0, 1, 1, 2,
2, 2, 2, 3,
3, 3, 3, 3,
3, 3, 3, 4,
/* if needed, these are the values for higher bases
4, 4, 4, 4,
4, 4, 4, 4,
4, 4, 4, 4,
4, 4, 4, 5
*/
};
size_t mp_int_format_size(size_t num_bits, int base, const char *prefix, char comma) {
assert(2 <= base && base <= 16);
size_t num_digits = num_bits / log_base2_floor[base - 1] + 1;
size_t num_commas = comma ? num_digits / 3 : 0;
size_t prefix_len = prefix ? strlen(prefix) : 0;
return num_digits + num_commas + prefix_len + 2; // +1 for sign, +1 for null byte
}
// This routine expects you to pass in a buffer and size (in *buf and *buf_size).
// If, for some reason, this buffer is too small, then it will allocate a
// buffer and return the allocated buffer and size in *buf and *buf_size. It
// is the callers responsibility to free this allocated buffer.
//
// The resulting formatted string will be returned from this function and the
// formatted size will be in *fmt_size.
char *mp_obj_int_formatted(char **buf, size_t *buf_size, size_t *fmt_size, mp_const_obj_t self_in,
int base, const char *prefix, char base_char, char comma) {
fmt_int_t num;
#if MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_NONE
// Only have small ints; get the integer value to format.
num = MP_OBJ_SMALL_INT_VALUE(self_in);
#else
if (mp_obj_is_small_int(self_in)) {
// A small int; get the integer value to format.
num = MP_OBJ_SMALL_INT_VALUE(self_in);
} else {
assert(mp_obj_is_type(self_in, &mp_type_int));
// Not a small int.
#if MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_LONGLONG
const mp_obj_int_t *self = self_in;
// Get the value to format; mp_obj_get_int truncates to mp_int_t.
num = self->val;
#else
// Delegate to the implementation for the long int.
return mp_obj_int_formatted_impl(buf, buf_size, fmt_size, self_in, base, prefix, base_char, comma);
#endif
}
#endif
char sign = '\0';
if (num < 0) {
num = -num;
sign = '-';
}
size_t needed_size = mp_int_format_size(sizeof(fmt_int_t) * 8, base, prefix, comma);
if (needed_size > *buf_size) {
*buf = m_new(char, needed_size);
*buf_size = needed_size;
}
char *str = *buf;
char *b = str + needed_size;
*(--b) = '\0';
char *last_comma = b;
if (num == 0) {
*(--b) = '0';
} else {
do {
// The cast to fmt_uint_t is because num is positive and we want unsigned arithmetic
int c = (fmt_uint_t)num % base;
num = (fmt_uint_t)num / base;
if (c >= 10) {
c += base_char - 10;
} else {
c += '0';
}
*(--b) = c;
if (comma && num != 0 && b > str && (last_comma - b) == 3) {
*(--b) = comma;
last_comma = b;
}
}
while (b > str && num != 0);
}
if (prefix) {
size_t prefix_len = strlen(prefix);
char *p = b - prefix_len;
if (p > str) {
b = p;
while (*prefix) {
*p++ = *prefix++;
}
}
}
if (sign && b > str) {
*(--b) = sign;
}
*fmt_size = *buf + needed_size - b - 1;
return b;
}
#if MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_NONE
int mp_obj_int_sign(mp_obj_t self_in) {
mp_int_t val = mp_obj_get_int(self_in);
if (val < 0) {
return -1;
} else if (val > 0) {
return 1;
} else {
return 0;
}
}
// This is called for operations on SMALL_INT that are not handled by mp_unary_op
mp_obj_t mp_obj_int_unary_op(mp_unary_op_t op, mp_obj_t o_in) {
return MP_OBJ_NULL; // op not supported
}
// This is called for operations on SMALL_INT that are not handled by mp_binary_op
mp_obj_t mp_obj_int_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_in) {
return mp_obj_int_binary_op_extra_cases(op, lhs_in, rhs_in);
}
// This is called only with strings whose value doesn't fit in SMALL_INT
mp_obj_t mp_obj_new_int_from_str_len(const char **str, size_t len, bool neg, unsigned int base) {
mp_raise_msg(&mp_type_OverflowError, MP_ERROR_TEXT("long int not supported in this build"));
return mp_const_none;
}
// This is called when an integer larger than a SMALL_INT is needed (although val might still fit in a SMALL_INT)
mp_obj_t mp_obj_new_int_from_ll(long long val) {
mp_raise_msg(&mp_type_OverflowError, MP_ERROR_TEXT("small int overflow"));
return mp_const_none;
}
// This is called when an integer larger than a SMALL_INT is needed (although val might still fit in a SMALL_INT)
mp_obj_t mp_obj_new_int_from_ull(unsigned long long val) {
mp_raise_msg(&mp_type_OverflowError, MP_ERROR_TEXT("small int overflow"));
return mp_const_none;
}
mp_obj_t mp_obj_new_int_from_uint(mp_uint_t value) {
// SMALL_INT accepts only signed numbers, so make sure the input
// value fits completely in the small-int positive range.
if ((value & ~MP_SMALL_INT_POSITIVE_MASK) == 0) {
return MP_OBJ_NEW_SMALL_INT(value);
}
mp_raise_msg(&mp_type_OverflowError, MP_ERROR_TEXT("small int overflow"));
return mp_const_none;
}
mp_obj_t mp_obj_new_int(mp_int_t value) {
if (MP_SMALL_INT_FITS(value)) {
return MP_OBJ_NEW_SMALL_INT(value);
}
mp_raise_msg(&mp_type_OverflowError, MP_ERROR_TEXT("small int overflow"));
return mp_const_none;
}
mp_int_t mp_obj_int_get_truncated(mp_const_obj_t self_in) {
return MP_OBJ_SMALL_INT_VALUE(self_in);
}
mp_int_t mp_obj_int_get_checked(mp_const_obj_t self_in) {
return MP_OBJ_SMALL_INT_VALUE(self_in);
}
#endif // MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_NONE
// This dispatcher function is expected to be independent of the implementation of long int
// It handles the extra cases for integer-like arithmetic
mp_obj_t mp_obj_int_binary_op_extra_cases(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_in) {
if (rhs_in == mp_const_false) {
// false acts as 0
return mp_binary_op(op, lhs_in, MP_OBJ_NEW_SMALL_INT(0));
} else if (rhs_in == mp_const_true) {
// true acts as 0
return mp_binary_op(op, lhs_in, MP_OBJ_NEW_SMALL_INT(1));
} else if (op == MP_BINARY_OP_MULTIPLY) {
if (mp_obj_is_str_or_bytes(rhs_in) || mp_obj_is_type(rhs_in, &mp_type_tuple) || mp_obj_is_type(rhs_in, &mp_type_list)) {
// multiply is commutative for these types, so delegate to them
return mp_binary_op(op, rhs_in, lhs_in);
}
}
return MP_OBJ_NULL; // op not supported
}
// this is a classmethod
STATIC mp_obj_t int_from_bytes(size_t n_args, const mp_obj_t *args) {
// TODO: Support signed param (assumes signed=False at the moment)
(void)n_args;
// get the buffer info
mp_buffer_info_t bufinfo;
mp_get_buffer_raise(args[1], &bufinfo, MP_BUFFER_READ);
const byte *buf = (const byte *)bufinfo.buf;
int delta = 1;
if (args[2] == MP_OBJ_NEW_QSTR(MP_QSTR_little)) {
buf += bufinfo.len - 1;
delta = -1;
}
mp_uint_t value = 0;
size_t len = bufinfo.len;
for (; len--; buf += delta) {
#if MICROPY_LONGINT_IMPL != MICROPY_LONGINT_IMPL_NONE
if (value > (MP_SMALL_INT_MAX >> 8)) {
// Result will overflow a small-int so construct a big-int
return mp_obj_int_from_bytes_impl(args[2] != MP_OBJ_NEW_QSTR(MP_QSTR_little), bufinfo.len, bufinfo.buf);
}
#endif
value = (value << 8) | *buf;
}
return mp_obj_new_int_from_uint(value);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(int_from_bytes_fun_obj, 3, 4, int_from_bytes);
STATIC MP_DEFINE_CONST_CLASSMETHOD_OBJ(int_from_bytes_obj, MP_ROM_PTR(&int_from_bytes_fun_obj));
STATIC mp_obj_t int_to_bytes(size_t n_args, const mp_obj_t *args) {
// TODO: Support signed param (assumes signed=False)
(void)n_args;
mp_int_t len = mp_obj_get_int(args[1]);
if (len < 0) {
mp_raise_ValueError(NULL);
}
bool big_endian = args[2] != MP_OBJ_NEW_QSTR(MP_QSTR_little);
vstr_t vstr;
vstr_init_len(&vstr, len);
byte *data = (byte *)vstr.buf;
memset(data, 0, len);
#if MICROPY_LONGINT_IMPL != MICROPY_LONGINT_IMPL_NONE
if (!mp_obj_is_small_int(args[0])) {
mp_obj_int_to_bytes_impl(args[0], big_endian, len, data);
} else
#endif
{
mp_int_t val = MP_OBJ_SMALL_INT_VALUE(args[0]);
size_t l = MIN((size_t)len, sizeof(val));
mp_binary_set_int(l, big_endian, data + (big_endian ? (len - l) : 0), val);
}
return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(int_to_bytes_obj, 3, 4, int_to_bytes);
STATIC const mp_rom_map_elem_t int_locals_dict_table[] = {
{ MP_ROM_QSTR(MP_QSTR_from_bytes), MP_ROM_PTR(&int_from_bytes_obj) },
{ MP_ROM_QSTR(MP_QSTR_to_bytes), MP_ROM_PTR(&int_to_bytes_obj) },
};
STATIC MP_DEFINE_CONST_DICT(int_locals_dict, int_locals_dict_table);
const mp_obj_type_t mp_type_int = {
{ &mp_type_type },
.name = MP_QSTR_int,
.print = mp_obj_int_print,
.make_new = mp_obj_int_make_new,
.unary_op = mp_obj_int_unary_op,
.binary_op = mp_obj_int_binary_op,
.locals_dict = (mp_obj_dict_t *)&int_locals_dict,
};
| YifuLiu/AliOS-Things | components/py_engine/engine/py/objint.c | C | apache-2.0 | 16,201 |
/*
* 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.
*/
#ifndef MICROPY_INCLUDED_PY_OBJINT_H
#define MICROPY_INCLUDED_PY_OBJINT_H
#include "py/mpz.h"
#include "py/obj.h"
typedef struct _mp_obj_int_t {
mp_obj_base_t base;
#if MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_LONGLONG
mp_longint_impl_t val;
#elif MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_MPZ
mpz_t mpz;
#endif
} mp_obj_int_t;
extern const mp_obj_int_t mp_sys_maxsize_obj;
#if MICROPY_PY_BUILTINS_FLOAT
mp_float_t mp_obj_int_as_float_impl(mp_obj_t self_in);
#endif
size_t mp_int_format_size(size_t num_bits, int base, const char *prefix, char comma);
mp_obj_int_t *mp_obj_int_new_mpz(void);
void mp_obj_int_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind);
char *mp_obj_int_formatted(char **buf, size_t *buf_size, size_t *fmt_size, mp_const_obj_t self_in,
int base, const char *prefix, char base_char, char comma);
char *mp_obj_int_formatted_impl(char **buf, size_t *buf_size, size_t *fmt_size, mp_const_obj_t self_in,
int base, const char *prefix, char base_char, char comma);
mp_int_t mp_obj_int_hash(mp_obj_t self_in);
mp_obj_t mp_obj_int_from_bytes_impl(bool big_endian, size_t len, const byte *buf);
void mp_obj_int_to_bytes_impl(mp_obj_t self_in, bool big_endian, size_t len, byte *buf);
int mp_obj_int_sign(mp_obj_t self_in);
mp_obj_t mp_obj_int_unary_op(mp_unary_op_t op, mp_obj_t o_in);
mp_obj_t mp_obj_int_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_in);
mp_obj_t mp_obj_int_binary_op_extra_cases(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_in);
mp_obj_t mp_obj_int_pow3(mp_obj_t base, mp_obj_t exponent, mp_obj_t modulus);
#endif // MICROPY_INCLUDED_PY_OBJINT_H
| YifuLiu/AliOS-Things | components/py_engine/engine/py/objint.h | C | apache-2.0 | 2,895 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2013, 2014 Damien P. George
* Copyright (c) 2014 Paul Sokolovsky
*
* 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 <stdlib.h>
#include <string.h>
#include "py/smallint.h"
#include "py/objint.h"
#include "py/runtime.h"
#if MICROPY_PY_BUILTINS_FLOAT
#include <math.h>
#endif
#if MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_LONGLONG
#if MICROPY_PY_SYS_MAXSIZE
// Export value for sys.maxsize
const mp_obj_int_t mp_sys_maxsize_obj = {{&mp_type_int}, MP_SSIZE_MAX};
#endif
mp_obj_t mp_obj_int_from_bytes_impl(bool big_endian, size_t len, const byte *buf) {
int delta = 1;
if (!big_endian) {
buf += len - 1;
delta = -1;
}
mp_longint_impl_t value = 0;
for (; len--; buf += delta) {
value = (value << 8) | *buf;
}
return mp_obj_new_int_from_ll(value);
}
void mp_obj_int_to_bytes_impl(mp_obj_t self_in, bool big_endian, size_t len, byte *buf) {
assert(mp_obj_is_type(self_in, &mp_type_int));
mp_obj_int_t *self = self_in;
long long val = self->val;
if (big_endian) {
byte *b = buf + len;
while (b > buf) {
*--b = val;
val >>= 8;
}
} else {
for (; len > 0; --len) {
*buf++ = val;
val >>= 8;
}
}
}
int mp_obj_int_sign(mp_obj_t self_in) {
mp_longint_impl_t val;
if (mp_obj_is_small_int(self_in)) {
val = MP_OBJ_SMALL_INT_VALUE(self_in);
} else {
mp_obj_int_t *self = self_in;
val = self->val;
}
if (val < 0) {
return -1;
} else if (val > 0) {
return 1;
} else {
return 0;
}
}
mp_obj_t mp_obj_int_unary_op(mp_unary_op_t op, mp_obj_t o_in) {
mp_obj_int_t *o = o_in;
switch (op) {
case MP_UNARY_OP_BOOL:
return mp_obj_new_bool(o->val != 0);
// truncate value to fit in mp_int_t, which gives the same hash as
// small int if the value fits without truncation
case MP_UNARY_OP_HASH:
return MP_OBJ_NEW_SMALL_INT((mp_int_t)o->val);
case MP_UNARY_OP_POSITIVE:
return o_in;
case MP_UNARY_OP_NEGATIVE:
return mp_obj_new_int_from_ll(-o->val);
case MP_UNARY_OP_INVERT:
return mp_obj_new_int_from_ll(~o->val);
case MP_UNARY_OP_ABS: {
mp_obj_int_t *self = MP_OBJ_TO_PTR(o_in);
if (self->val >= 0) {
return o_in;
}
self = mp_obj_new_int_from_ll(self->val);
// TODO could overflow long long
self->val = -self->val;
return MP_OBJ_FROM_PTR(self);
}
default:
return MP_OBJ_NULL; // op not supported
}
}
mp_obj_t mp_obj_int_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_in) {
long long lhs_val;
long long rhs_val;
if (mp_obj_is_small_int(lhs_in)) {
lhs_val = MP_OBJ_SMALL_INT_VALUE(lhs_in);
} else {
assert(mp_obj_is_type(lhs_in, &mp_type_int));
lhs_val = ((mp_obj_int_t *)lhs_in)->val;
}
if (mp_obj_is_small_int(rhs_in)) {
rhs_val = MP_OBJ_SMALL_INT_VALUE(rhs_in);
} else if (mp_obj_is_type(rhs_in, &mp_type_int)) {
rhs_val = ((mp_obj_int_t *)rhs_in)->val;
} else {
// delegate to generic function to check for extra cases
return mp_obj_int_binary_op_extra_cases(op, lhs_in, rhs_in);
}
switch (op) {
case MP_BINARY_OP_ADD:
case MP_BINARY_OP_INPLACE_ADD:
return mp_obj_new_int_from_ll(lhs_val + rhs_val);
case MP_BINARY_OP_SUBTRACT:
case MP_BINARY_OP_INPLACE_SUBTRACT:
return mp_obj_new_int_from_ll(lhs_val - rhs_val);
case MP_BINARY_OP_MULTIPLY:
case MP_BINARY_OP_INPLACE_MULTIPLY:
return mp_obj_new_int_from_ll(lhs_val * rhs_val);
case MP_BINARY_OP_FLOOR_DIVIDE:
case MP_BINARY_OP_INPLACE_FLOOR_DIVIDE:
if (rhs_val == 0) {
goto zero_division;
}
return mp_obj_new_int_from_ll(lhs_val / rhs_val);
case MP_BINARY_OP_MODULO:
case MP_BINARY_OP_INPLACE_MODULO:
if (rhs_val == 0) {
goto zero_division;
}
return mp_obj_new_int_from_ll(lhs_val % rhs_val);
case MP_BINARY_OP_AND:
case MP_BINARY_OP_INPLACE_AND:
return mp_obj_new_int_from_ll(lhs_val & rhs_val);
case MP_BINARY_OP_OR:
case MP_BINARY_OP_INPLACE_OR:
return mp_obj_new_int_from_ll(lhs_val | rhs_val);
case MP_BINARY_OP_XOR:
case MP_BINARY_OP_INPLACE_XOR:
return mp_obj_new_int_from_ll(lhs_val ^ rhs_val);
case MP_BINARY_OP_LSHIFT:
case MP_BINARY_OP_INPLACE_LSHIFT:
return mp_obj_new_int_from_ll(lhs_val << (int)rhs_val);
case MP_BINARY_OP_RSHIFT:
case MP_BINARY_OP_INPLACE_RSHIFT:
return mp_obj_new_int_from_ll(lhs_val >> (int)rhs_val);
case MP_BINARY_OP_POWER:
case MP_BINARY_OP_INPLACE_POWER: {
if (rhs_val < 0) {
#if MICROPY_PY_BUILTINS_FLOAT
return mp_obj_float_binary_op(op, lhs_val, rhs_in);
#else
mp_raise_ValueError(MP_ERROR_TEXT("negative power with no float support"));
#endif
}
long long ans = 1;
while (rhs_val > 0) {
if (rhs_val & 1) {
ans *= lhs_val;
}
if (rhs_val == 1) {
break;
}
rhs_val /= 2;
lhs_val *= lhs_val;
}
return mp_obj_new_int_from_ll(ans);
}
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);
case MP_BINARY_OP_EQUAL:
return mp_obj_new_bool(lhs_val == rhs_val);
default:
return MP_OBJ_NULL; // op not supported
}
zero_division:
mp_raise_msg(&mp_type_ZeroDivisionError, MP_ERROR_TEXT("divide by zero"));
}
mp_obj_t mp_obj_new_int(mp_int_t value) {
if (MP_SMALL_INT_FITS(value)) {
return MP_OBJ_NEW_SMALL_INT(value);
}
return mp_obj_new_int_from_ll(value);
}
mp_obj_t mp_obj_new_int_from_uint(mp_uint_t value) {
// SMALL_INT accepts only signed numbers, so make sure the input
// value fits completely in the small-int positive range.
if ((value & ~MP_SMALL_INT_POSITIVE_MASK) == 0) {
return MP_OBJ_NEW_SMALL_INT(value);
}
return mp_obj_new_int_from_ll(value);
}
mp_obj_t mp_obj_new_int_from_ll(long long val) {
mp_obj_int_t *o = m_new_obj(mp_obj_int_t);
o->base.type = &mp_type_int;
o->val = val;
return o;
}
mp_obj_t mp_obj_new_int_from_ull(unsigned long long val) {
// TODO raise an exception if the unsigned long long won't fit
if (val >> (sizeof(unsigned long long) * 8 - 1) != 0) {
mp_raise_msg(&mp_type_OverflowError, MP_ERROR_TEXT("ulonglong too large"));
}
mp_obj_int_t *o = m_new_obj(mp_obj_int_t);
o->base.type = &mp_type_int;
o->val = val;
return o;
}
mp_obj_t mp_obj_new_int_from_str_len(const char **str, size_t len, bool neg, unsigned int base) {
// TODO this does not honor the given length of the string, but it all cases it should anyway be null terminated
// TODO check overflow
mp_obj_int_t *o = m_new_obj(mp_obj_int_t);
o->base.type = &mp_type_int;
char *endptr;
o->val = strtoll(*str, &endptr, base);
*str = endptr;
return o;
}
mp_int_t mp_obj_int_get_truncated(mp_const_obj_t self_in) {
if (mp_obj_is_small_int(self_in)) {
return MP_OBJ_SMALL_INT_VALUE(self_in);
} else {
const mp_obj_int_t *self = self_in;
return self->val;
}
}
mp_int_t mp_obj_int_get_checked(mp_const_obj_t self_in) {
// TODO: Check overflow
return mp_obj_int_get_truncated(self_in);
}
#if MICROPY_PY_BUILTINS_FLOAT
mp_float_t mp_obj_int_as_float_impl(mp_obj_t self_in) {
assert(mp_obj_is_type(self_in, &mp_type_int));
mp_obj_int_t *self = self_in;
return self->val;
}
#endif
#endif
| YifuLiu/AliOS-Things | components/py_engine/engine/py/objint_longlong.c | C | apache-2.0 | 9,560 |
/*
* 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 <string.h>
#include <stdio.h>
#include <assert.h>
#include "py/parsenumbase.h"
#include "py/smallint.h"
#include "py/objint.h"
#include "py/runtime.h"
#if MICROPY_PY_BUILTINS_FLOAT
#include <math.h>
#endif
#if MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_MPZ
#if MICROPY_PY_SYS_MAXSIZE
// Export value for sys.maxsize
// *FORMAT-OFF*
#define DIG_MASK ((MPZ_LONG_1 << MPZ_DIG_SIZE) - 1)
STATIC const mpz_dig_t maxsize_dig[] = {
#define NUM_DIG 1
(MP_SSIZE_MAX >> MPZ_DIG_SIZE * 0) & DIG_MASK,
#if (MP_SSIZE_MAX >> MPZ_DIG_SIZE * 0) > DIG_MASK
#undef NUM_DIG
#define NUM_DIG 2
(MP_SSIZE_MAX >> MPZ_DIG_SIZE * 1) & DIG_MASK,
#if (MP_SSIZE_MAX >> MPZ_DIG_SIZE * 1) > DIG_MASK
#undef NUM_DIG
#define NUM_DIG 3
(MP_SSIZE_MAX >> MPZ_DIG_SIZE * 2) & DIG_MASK,
#if (MP_SSIZE_MAX >> MPZ_DIG_SIZE * 2) > DIG_MASK
#undef NUM_DIG
#define NUM_DIG 4
(MP_SSIZE_MAX >> MPZ_DIG_SIZE * 3) & DIG_MASK,
#if (MP_SSIZE_MAX >> MPZ_DIG_SIZE * 3) > DIG_MASK
#error cannot encode MP_SSIZE_MAX as mpz
#endif
#endif
#endif
#endif
};
// *FORMAT-ON*
const mp_obj_int_t mp_sys_maxsize_obj = {
{&mp_type_int},
{.fixed_dig = 1, .len = NUM_DIG, .alloc = NUM_DIG, .dig = (mpz_dig_t *)maxsize_dig}
};
#undef DIG_MASK
#undef NUM_DIG
#endif
mp_obj_int_t *mp_obj_int_new_mpz(void) {
mp_obj_int_t *o = m_new_obj(mp_obj_int_t);
o->base.type = &mp_type_int;
mpz_init_zero(&o->mpz);
return o;
}
// This routine expects you to pass in a buffer and size (in *buf and buf_size).
// If, for some reason, this buffer is too small, then it will allocate a
// buffer and return the allocated buffer and size in *buf and *buf_size. It
// is the callers responsibility to free this allocated buffer.
//
// The resulting formatted string will be returned from this function and the
// formatted size will be in *fmt_size.
//
// This particular routine should only be called for the mpz representation of the int.
char *mp_obj_int_formatted_impl(char **buf, size_t *buf_size, size_t *fmt_size, mp_const_obj_t self_in,
int base, const char *prefix, char base_char, char comma) {
assert(mp_obj_is_type(self_in, &mp_type_int));
const mp_obj_int_t *self = MP_OBJ_TO_PTR(self_in);
size_t needed_size = mp_int_format_size(mpz_max_num_bits(&self->mpz), base, prefix, comma);
if (needed_size > *buf_size) {
*buf = m_new(char, needed_size);
*buf_size = needed_size;
}
char *str = *buf;
*fmt_size = mpz_as_str_inpl(&self->mpz, base, prefix, base_char, comma, str);
return str;
}
mp_obj_t mp_obj_int_from_bytes_impl(bool big_endian, size_t len, const byte *buf) {
mp_obj_int_t *o = mp_obj_int_new_mpz();
mpz_set_from_bytes(&o->mpz, big_endian, len, buf);
return MP_OBJ_FROM_PTR(o);
}
void mp_obj_int_to_bytes_impl(mp_obj_t self_in, bool big_endian, size_t len, byte *buf) {
assert(mp_obj_is_type(self_in, &mp_type_int));
mp_obj_int_t *self = MP_OBJ_TO_PTR(self_in);
mpz_as_bytes(&self->mpz, big_endian, len, buf);
}
int mp_obj_int_sign(mp_obj_t self_in) {
if (mp_obj_is_small_int(self_in)) {
mp_int_t val = MP_OBJ_SMALL_INT_VALUE(self_in);
if (val < 0) {
return -1;
} else if (val > 0) {
return 1;
} else {
return 0;
}
}
mp_obj_int_t *self = MP_OBJ_TO_PTR(self_in);
if (self->mpz.len == 0) {
return 0;
} else if (self->mpz.neg == 0) {
return 1;
} else {
return -1;
}
}
mp_obj_t mp_obj_int_unary_op(mp_unary_op_t op, mp_obj_t o_in) {
mp_obj_int_t *o = MP_OBJ_TO_PTR(o_in);
switch (op) {
case MP_UNARY_OP_BOOL:
return mp_obj_new_bool(!mpz_is_zero(&o->mpz));
case MP_UNARY_OP_HASH:
return MP_OBJ_NEW_SMALL_INT(mpz_hash(&o->mpz));
case MP_UNARY_OP_POSITIVE:
return o_in;
case MP_UNARY_OP_NEGATIVE: { mp_obj_int_t *o2 = mp_obj_int_new_mpz();
mpz_neg_inpl(&o2->mpz, &o->mpz);
return MP_OBJ_FROM_PTR(o2);
}
case MP_UNARY_OP_INVERT: { mp_obj_int_t *o2 = mp_obj_int_new_mpz();
mpz_not_inpl(&o2->mpz, &o->mpz);
return MP_OBJ_FROM_PTR(o2);
}
case MP_UNARY_OP_ABS: {
mp_obj_int_t *self = MP_OBJ_TO_PTR(o_in);
if (self->mpz.neg == 0) {
return o_in;
}
mp_obj_int_t *self2 = mp_obj_int_new_mpz();
mpz_abs_inpl(&self2->mpz, &self->mpz);
return MP_OBJ_FROM_PTR(self2);
}
default:
return MP_OBJ_NULL; // op not supported
}
}
mp_obj_t mp_obj_int_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_in) {
const mpz_t *zlhs;
const mpz_t *zrhs;
mpz_t z_int;
mpz_dig_t z_int_dig[MPZ_NUM_DIG_FOR_INT];
// lhs could be a small int (eg small-int + mpz)
if (mp_obj_is_small_int(lhs_in)) {
mpz_init_fixed_from_int(&z_int, z_int_dig, MPZ_NUM_DIG_FOR_INT, MP_OBJ_SMALL_INT_VALUE(lhs_in));
zlhs = &z_int;
} else {
assert(mp_obj_is_type(lhs_in, &mp_type_int));
zlhs = &((mp_obj_int_t *)MP_OBJ_TO_PTR(lhs_in))->mpz;
}
// if rhs is small int, then lhs was not (otherwise mp_binary_op handles it)
if (mp_obj_is_small_int(rhs_in)) {
mpz_init_fixed_from_int(&z_int, z_int_dig, MPZ_NUM_DIG_FOR_INT, MP_OBJ_SMALL_INT_VALUE(rhs_in));
zrhs = &z_int;
} else if (mp_obj_is_type(rhs_in, &mp_type_int)) {
zrhs = &((mp_obj_int_t *)MP_OBJ_TO_PTR(rhs_in))->mpz;
#if MICROPY_PY_BUILTINS_FLOAT
} else if (mp_obj_is_float(rhs_in)) {
return mp_obj_float_binary_op(op, mpz_as_float(zlhs), rhs_in);
#endif
#if MICROPY_PY_BUILTINS_COMPLEX
} else if (mp_obj_is_type(rhs_in, &mp_type_complex)) {
return mp_obj_complex_binary_op(op, mpz_as_float(zlhs), 0, rhs_in);
#endif
} else {
// delegate to generic function to check for extra cases
return mp_obj_int_binary_op_extra_cases(op, lhs_in, rhs_in);
}
#if MICROPY_PY_BUILTINS_FLOAT
if (op == MP_BINARY_OP_TRUE_DIVIDE || op == MP_BINARY_OP_INPLACE_TRUE_DIVIDE) {
if (mpz_is_zero(zrhs)) {
goto zero_division_error;
}
mp_float_t flhs = mpz_as_float(zlhs);
mp_float_t frhs = mpz_as_float(zrhs);
return mp_obj_new_float(flhs / frhs);
}
#endif
if (op >= MP_BINARY_OP_INPLACE_OR && op < MP_BINARY_OP_CONTAINS) {
mp_obj_int_t *res = mp_obj_int_new_mpz();
switch (op) {
case MP_BINARY_OP_ADD:
case MP_BINARY_OP_INPLACE_ADD:
mpz_add_inpl(&res->mpz, zlhs, zrhs);
break;
case MP_BINARY_OP_SUBTRACT:
case MP_BINARY_OP_INPLACE_SUBTRACT:
mpz_sub_inpl(&res->mpz, zlhs, zrhs);
break;
case MP_BINARY_OP_MULTIPLY:
case MP_BINARY_OP_INPLACE_MULTIPLY:
mpz_mul_inpl(&res->mpz, zlhs, zrhs);
break;
case MP_BINARY_OP_FLOOR_DIVIDE:
case MP_BINARY_OP_INPLACE_FLOOR_DIVIDE: {
if (mpz_is_zero(zrhs)) {
zero_division_error:
mp_raise_msg(&mp_type_ZeroDivisionError, MP_ERROR_TEXT("divide by zero"));
}
mpz_t rem;
mpz_init_zero(&rem);
mpz_divmod_inpl(&res->mpz, &rem, zlhs, zrhs);
mpz_deinit(&rem);
break;
}
case MP_BINARY_OP_MODULO:
case MP_BINARY_OP_INPLACE_MODULO: {
if (mpz_is_zero(zrhs)) {
goto zero_division_error;
}
mpz_t quo;
mpz_init_zero(&quo);
mpz_divmod_inpl(&quo, &res->mpz, zlhs, zrhs);
mpz_deinit(&quo);
break;
}
case MP_BINARY_OP_AND:
case MP_BINARY_OP_INPLACE_AND:
mpz_and_inpl(&res->mpz, zlhs, zrhs);
break;
case MP_BINARY_OP_OR:
case MP_BINARY_OP_INPLACE_OR:
mpz_or_inpl(&res->mpz, zlhs, zrhs);
break;
case MP_BINARY_OP_XOR:
case MP_BINARY_OP_INPLACE_XOR:
mpz_xor_inpl(&res->mpz, zlhs, zrhs);
break;
case MP_BINARY_OP_LSHIFT:
case MP_BINARY_OP_INPLACE_LSHIFT:
case MP_BINARY_OP_RSHIFT:
case MP_BINARY_OP_INPLACE_RSHIFT: {
mp_int_t irhs = mp_obj_int_get_checked(rhs_in);
if (irhs < 0) {
mp_raise_ValueError(MP_ERROR_TEXT("negative shift count"));
}
if (op == MP_BINARY_OP_LSHIFT || op == MP_BINARY_OP_INPLACE_LSHIFT) {
mpz_shl_inpl(&res->mpz, zlhs, irhs);
} else {
mpz_shr_inpl(&res->mpz, zlhs, irhs);
}
break;
}
case MP_BINARY_OP_POWER:
case MP_BINARY_OP_INPLACE_POWER:
if (mpz_is_neg(zrhs)) {
#if MICROPY_PY_BUILTINS_FLOAT
return mp_obj_float_binary_op(op, mpz_as_float(zlhs), rhs_in);
#else
mp_raise_ValueError(MP_ERROR_TEXT("negative power with no float support"));
#endif
}
mpz_pow_inpl(&res->mpz, zlhs, zrhs);
break;
default: {
assert(op == MP_BINARY_OP_DIVMOD);
if (mpz_is_zero(zrhs)) {
goto zero_division_error;
}
mp_obj_int_t *quo = mp_obj_int_new_mpz();
mpz_divmod_inpl(&quo->mpz, &res->mpz, zlhs, zrhs);
mp_obj_t tuple[2] = {MP_OBJ_FROM_PTR(quo), MP_OBJ_FROM_PTR(res)};
return mp_obj_new_tuple(2, tuple);
}
}
return MP_OBJ_FROM_PTR(res);
} else {
int cmp = mpz_cmp(zlhs, zrhs);
switch (op) {
case MP_BINARY_OP_LESS:
return mp_obj_new_bool(cmp < 0);
case MP_BINARY_OP_MORE:
return mp_obj_new_bool(cmp > 0);
case MP_BINARY_OP_LESS_EQUAL:
return mp_obj_new_bool(cmp <= 0);
case MP_BINARY_OP_MORE_EQUAL:
return mp_obj_new_bool(cmp >= 0);
case MP_BINARY_OP_EQUAL:
return mp_obj_new_bool(cmp == 0);
default:
return MP_OBJ_NULL; // op not supported
}
}
}
#if MICROPY_PY_BUILTINS_POW3
STATIC mpz_t *mp_mpz_for_int(mp_obj_t arg, mpz_t *temp) {
if (mp_obj_is_small_int(arg)) {
mpz_init_from_int(temp, MP_OBJ_SMALL_INT_VALUE(arg));
return temp;
} else {
mp_obj_int_t *arp_p = MP_OBJ_TO_PTR(arg);
return &(arp_p->mpz);
}
}
mp_obj_t mp_obj_int_pow3(mp_obj_t base, mp_obj_t exponent, mp_obj_t modulus) {
if (!mp_obj_is_int(base) || !mp_obj_is_int(exponent) || !mp_obj_is_int(modulus)) {
mp_raise_TypeError(MP_ERROR_TEXT("pow() with 3 arguments requires integers"));
} else {
mp_obj_t result = mp_obj_new_int_from_ull(0); // Use the _from_ull version as this forces an mpz int
mp_obj_int_t *res_p = (mp_obj_int_t *)MP_OBJ_TO_PTR(result);
mpz_t l_temp, r_temp, m_temp;
mpz_t *lhs = mp_mpz_for_int(base, &l_temp);
mpz_t *rhs = mp_mpz_for_int(exponent, &r_temp);
mpz_t *mod = mp_mpz_for_int(modulus, &m_temp);
mpz_pow3_inpl(&(res_p->mpz), lhs, rhs, mod);
if (lhs == &l_temp) {
mpz_deinit(lhs);
}
if (rhs == &r_temp) {
mpz_deinit(rhs);
}
if (mod == &m_temp) {
mpz_deinit(mod);
}
return result;
}
}
#endif
mp_obj_t mp_obj_new_int(mp_int_t value) {
if (MP_SMALL_INT_FITS(value)) {
return MP_OBJ_NEW_SMALL_INT(value);
}
return mp_obj_new_int_from_ll(value);
}
mp_obj_t mp_obj_new_int_from_ll(long long val) {
mp_obj_int_t *o = mp_obj_int_new_mpz();
mpz_set_from_ll(&o->mpz, val, true);
return MP_OBJ_FROM_PTR(o);
}
mp_obj_t mp_obj_new_int_from_ull(unsigned long long val) {
mp_obj_int_t *o = mp_obj_int_new_mpz();
mpz_set_from_ll(&o->mpz, val, false);
return MP_OBJ_FROM_PTR(o);
}
mp_obj_t mp_obj_new_int_from_uint(mp_uint_t value) {
// SMALL_INT accepts only signed numbers, so make sure the input
// value fits completely in the small-int positive range.
if ((value & ~MP_SMALL_INT_POSITIVE_MASK) == 0) {
return MP_OBJ_NEW_SMALL_INT(value);
}
return mp_obj_new_int_from_ull(value);
}
mp_obj_t mp_obj_new_int_from_str_len(const char **str, size_t len, bool neg, unsigned int base) {
mp_obj_int_t *o = mp_obj_int_new_mpz();
size_t n = mpz_set_from_str(&o->mpz, *str, len, neg, base);
*str += n;
return MP_OBJ_FROM_PTR(o);
}
mp_int_t mp_obj_int_get_truncated(mp_const_obj_t self_in) {
if (mp_obj_is_small_int(self_in)) {
return MP_OBJ_SMALL_INT_VALUE(self_in);
} else {
const mp_obj_int_t *self = MP_OBJ_TO_PTR(self_in);
// hash returns actual int value if it fits in mp_int_t
return mpz_hash(&self->mpz);
}
}
mp_int_t mp_obj_int_get_checked(mp_const_obj_t self_in) {
if (mp_obj_is_small_int(self_in)) {
return MP_OBJ_SMALL_INT_VALUE(self_in);
} else {
const mp_obj_int_t *self = MP_OBJ_TO_PTR(self_in);
mp_int_t value;
if (mpz_as_int_checked(&self->mpz, &value)) {
return value;
} else {
// overflow
mp_raise_msg(&mp_type_OverflowError, MP_ERROR_TEXT("overflow converting long int to machine word"));
}
}
}
mp_uint_t mp_obj_int_get_uint_checked(mp_const_obj_t self_in) {
if (mp_obj_is_small_int(self_in)) {
if (MP_OBJ_SMALL_INT_VALUE(self_in) >= 0) {
return MP_OBJ_SMALL_INT_VALUE(self_in);
}
} else {
const mp_obj_int_t *self = MP_OBJ_TO_PTR(self_in);
mp_uint_t value;
if (mpz_as_uint_checked(&self->mpz, &value)) {
return value;
}
}
mp_raise_msg(&mp_type_OverflowError, MP_ERROR_TEXT("overflow converting long int to machine word"));
}
#if MICROPY_PY_BUILTINS_FLOAT
mp_float_t mp_obj_int_as_float_impl(mp_obj_t self_in) {
assert(mp_obj_is_type(self_in, &mp_type_int));
mp_obj_int_t *self = MP_OBJ_TO_PTR(self_in);
return mpz_as_float(&self->mpz);
}
#endif
#endif
| YifuLiu/AliOS-Things | components/py_engine/engine/py/objint_mpz.c | C | apache-2.0 | 15,953 |
/*
* 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 <string.h>
#include <assert.h>
#include "py/objlist.h"
#include "py/runtime.h"
#include "py/stackctrl.h"
STATIC mp_obj_t mp_obj_new_list_iterator(mp_obj_t list, size_t cur, mp_obj_iter_buf_t *iter_buf);
STATIC mp_obj_list_t *list_new(size_t n);
STATIC mp_obj_t list_extend(mp_obj_t self_in, mp_obj_t arg_in);
STATIC mp_obj_t list_pop(size_t n_args, const mp_obj_t *args);
// TODO: Move to mpconfig.h
#define LIST_MIN_ALLOC 4
/******************************************************************************/
/* list */
STATIC void list_print(const mp_print_t *print, mp_obj_t o_in, mp_print_kind_t kind) {
mp_obj_list_t *o = MP_OBJ_TO_PTR(o_in);
const char *item_separator = ", ";
if (!(MICROPY_PY_UJSON && kind == PRINT_JSON)) {
kind = PRINT_REPR;
} else {
#if MICROPY_PY_UJSON_SEPARATORS
item_separator = MP_PRINT_GET_EXT(print)->item_separator;
#endif
}
mp_print_str(print, "[");
for (size_t i = 0; i < o->len; i++) {
if (i > 0) {
mp_print_str(print, item_separator);
}
mp_obj_print_helper(print, o->items[i], kind);
}
mp_print_str(print, "]");
}
STATIC mp_obj_t list_extend_from_iter(mp_obj_t list, mp_obj_t iterable) {
mp_obj_t iter = mp_getiter(iterable, NULL);
mp_obj_t item;
while ((item = mp_iternext(iter)) != MP_OBJ_STOP_ITERATION) {
mp_obj_list_append(list, item);
}
return list;
}
STATIC mp_obj_t list_make_new(const mp_obj_type_t *type_in, size_t n_args, size_t n_kw, const mp_obj_t *args) {
(void)type_in;
mp_arg_check_num(n_args, n_kw, 0, 1, false);
switch (n_args) {
case 0:
// return a new, empty list
return mp_obj_new_list(0, NULL);
case 1:
default: {
// make list from iterable
// TODO: optimize list/tuple
mp_obj_t list = mp_obj_new_list(0, NULL);
return list_extend_from_iter(list, args[0]);
}
}
}
STATIC mp_obj_t list_unary_op(mp_unary_op_t op, mp_obj_t self_in) {
mp_obj_list_t *self = MP_OBJ_TO_PTR(self_in);
switch (op) {
case MP_UNARY_OP_BOOL:
return mp_obj_new_bool(self->len != 0);
case MP_UNARY_OP_LEN:
return MP_OBJ_NEW_SMALL_INT(self->len);
#if MICROPY_PY_SYS_GETSIZEOF
case MP_UNARY_OP_SIZEOF: {
size_t sz = sizeof(*self) + sizeof(mp_obj_t) * self->alloc;
return MP_OBJ_NEW_SMALL_INT(sz);
}
#endif
default:
return MP_OBJ_NULL; // op not supported
}
}
STATIC mp_obj_t list_binary_op(mp_binary_op_t op, mp_obj_t lhs, mp_obj_t rhs) {
mp_obj_list_t *o = MP_OBJ_TO_PTR(lhs);
switch (op) {
case MP_BINARY_OP_ADD: {
if (!mp_obj_is_type(rhs, &mp_type_list)) {
return MP_OBJ_NULL; // op not supported
}
mp_obj_list_t *p = MP_OBJ_TO_PTR(rhs);
mp_obj_list_t *s = list_new(o->len + p->len);
mp_seq_cat(s->items, o->items, o->len, p->items, p->len, mp_obj_t);
return MP_OBJ_FROM_PTR(s);
}
case MP_BINARY_OP_INPLACE_ADD: {
list_extend(lhs, rhs);
return lhs;
}
case MP_BINARY_OP_MULTIPLY: {
mp_int_t n;
if (!mp_obj_get_int_maybe(rhs, &n)) {
return MP_OBJ_NULL; // op not supported
}
if (n < 0) {
n = 0;
}
mp_obj_list_t *s = list_new(o->len * n);
mp_seq_multiply(o->items, sizeof(*o->items), o->len, n, s->items);
return MP_OBJ_FROM_PTR(s);
}
case MP_BINARY_OP_EQUAL:
case MP_BINARY_OP_LESS:
case MP_BINARY_OP_LESS_EQUAL:
case MP_BINARY_OP_MORE:
case MP_BINARY_OP_MORE_EQUAL: {
if (!mp_obj_is_type(rhs, &mp_type_list)) {
if (op == MP_BINARY_OP_EQUAL) {
return mp_const_false;
}
return MP_OBJ_NULL; // op not supported
}
mp_obj_list_t *another = MP_OBJ_TO_PTR(rhs);
bool res = mp_seq_cmp_objs(op, o->items, o->len, another->items, another->len);
return mp_obj_new_bool(res);
}
default:
return MP_OBJ_NULL; // op not supported
}
}
STATIC mp_obj_t list_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) {
if (value == MP_OBJ_NULL) {
// delete
#if MICROPY_PY_BUILTINS_SLICE
if (mp_obj_is_type(index, &mp_type_slice)) {
mp_obj_list_t *self = MP_OBJ_TO_PTR(self_in);
mp_bound_slice_t slice;
if (!mp_seq_get_fast_slice_indexes(self->len, index, &slice)) {
mp_raise_NotImplementedError(NULL);
}
mp_int_t len_adj = slice.start - slice.stop;
assert(len_adj <= 0);
mp_seq_replace_slice_no_grow(self->items, self->len, slice.start, slice.stop, self->items /*NULL*/, 0, sizeof(*self->items));
// Clear "freed" elements at the end of list
mp_seq_clear(self->items, self->len + len_adj, self->len, sizeof(*self->items));
self->len += len_adj;
return mp_const_none;
}
#endif
mp_obj_t args[2] = {self_in, index};
list_pop(2, args);
return mp_const_none;
} else if (value == MP_OBJ_SENTINEL) {
// load
mp_obj_list_t *self = MP_OBJ_TO_PTR(self_in);
#if MICROPY_PY_BUILTINS_SLICE
if (mp_obj_is_type(index, &mp_type_slice)) {
mp_bound_slice_t slice;
if (!mp_seq_get_fast_slice_indexes(self->len, index, &slice)) {
return mp_seq_extract_slice(self->len, self->items, &slice);
}
mp_obj_list_t *res = list_new(slice.stop - slice.start);
mp_seq_copy(res->items, self->items + slice.start, res->len, mp_obj_t);
return MP_OBJ_FROM_PTR(res);
}
#endif
size_t index_val = mp_get_index(self->base.type, self->len, index, false);
return self->items[index_val];
} else {
#if MICROPY_PY_BUILTINS_SLICE
if (mp_obj_is_type(index, &mp_type_slice)) {
mp_obj_list_t *self = MP_OBJ_TO_PTR(self_in);
size_t value_len;
mp_obj_t *value_items;
mp_obj_get_array(value, &value_len, &value_items);
mp_bound_slice_t slice_out;
if (!mp_seq_get_fast_slice_indexes(self->len, index, &slice_out)) {
mp_raise_NotImplementedError(NULL);
}
mp_int_t len_adj = value_len - (slice_out.stop - slice_out.start);
if (len_adj > 0) {
if (self->len + len_adj > self->alloc) {
// TODO: Might optimize memory copies here by checking if block can
// be grown inplace or not
self->items = m_renew(mp_obj_t, self->items, self->alloc, self->len + len_adj);
self->alloc = self->len + len_adj;
}
mp_seq_replace_slice_grow_inplace(self->items, self->len,
slice_out.start, slice_out.stop, value_items, value_len, len_adj, sizeof(*self->items));
} else {
mp_seq_replace_slice_no_grow(self->items, self->len,
slice_out.start, slice_out.stop, value_items, value_len, sizeof(*self->items));
// Clear "freed" elements at the end of list
mp_seq_clear(self->items, self->len + len_adj, self->len, sizeof(*self->items));
// TODO: apply allocation policy re: alloc_size
}
self->len += len_adj;
return mp_const_none;
}
#endif
mp_obj_list_store(self_in, index, value);
return mp_const_none;
}
}
STATIC mp_obj_t list_getiter(mp_obj_t o_in, mp_obj_iter_buf_t *iter_buf) {
return mp_obj_new_list_iterator(o_in, 0, iter_buf);
}
mp_obj_t mp_obj_list_append(mp_obj_t self_in, mp_obj_t arg) {
mp_check_self(mp_obj_is_type(self_in, &mp_type_list));
mp_obj_list_t *self = MP_OBJ_TO_PTR(self_in);
if (self->len >= self->alloc) {
self->items = m_renew(mp_obj_t, self->items, self->alloc, self->alloc * 2);
self->alloc *= 2;
mp_seq_clear(self->items, self->len + 1, self->alloc, sizeof(*self->items));
}
self->items[self->len++] = arg;
return mp_const_none; // return None, as per CPython
}
STATIC mp_obj_t list_extend(mp_obj_t self_in, mp_obj_t arg_in) {
mp_check_self(mp_obj_is_type(self_in, &mp_type_list));
if (mp_obj_is_type(arg_in, &mp_type_list)) {
mp_obj_list_t *self = MP_OBJ_TO_PTR(self_in);
mp_obj_list_t *arg = MP_OBJ_TO_PTR(arg_in);
if (self->len + arg->len > self->alloc) {
// TODO: use alloc policy for "4"
self->items = m_renew(mp_obj_t, self->items, self->alloc, self->len + arg->len + 4);
self->alloc = self->len + arg->len + 4;
mp_seq_clear(self->items, self->len + arg->len, self->alloc, sizeof(*self->items));
}
memcpy(self->items + self->len, arg->items, sizeof(mp_obj_t) * arg->len);
self->len += arg->len;
} else {
list_extend_from_iter(self_in, arg_in);
}
return mp_const_none; // return None, as per CPython
}
STATIC mp_obj_t list_pop(size_t n_args, const mp_obj_t *args) {
mp_check_self(mp_obj_is_type(args[0], &mp_type_list));
mp_obj_list_t *self = MP_OBJ_TO_PTR(args[0]);
if (self->len == 0) {
mp_raise_msg(&mp_type_IndexError, MP_ERROR_TEXT("pop from empty list"));
}
size_t index = mp_get_index(self->base.type, self->len, n_args == 1 ? MP_OBJ_NEW_SMALL_INT(-1) : args[1], false);
mp_obj_t ret = self->items[index];
self->len -= 1;
memmove(self->items + index, self->items + index + 1, (self->len - index) * sizeof(mp_obj_t));
// Clear stale pointer from slot which just got freed to prevent GC issues
self->items[self->len] = MP_OBJ_NULL;
if (self->alloc > LIST_MIN_ALLOC && self->alloc > 2 * self->len) {
self->items = m_renew(mp_obj_t, self->items, self->alloc, self->alloc / 2);
self->alloc /= 2;
}
return ret;
}
STATIC void mp_quicksort(mp_obj_t *head, mp_obj_t *tail, mp_obj_t key_fn, mp_obj_t binop_less_result) {
MP_STACK_CHECK();
while (head < tail) {
mp_obj_t *h = head - 1;
mp_obj_t *t = tail;
mp_obj_t v = key_fn == MP_OBJ_NULL ? tail[0] : mp_call_function_1(key_fn, tail[0]); // get pivot using key_fn
for (;;) {
do {++h;
} while (h < t && mp_binary_op(MP_BINARY_OP_LESS, key_fn == MP_OBJ_NULL ? h[0] : mp_call_function_1(key_fn, h[0]), v) == binop_less_result);
do {--t;
} while (h < t && mp_binary_op(MP_BINARY_OP_LESS, v, key_fn == MP_OBJ_NULL ? t[0] : mp_call_function_1(key_fn, t[0])) == binop_less_result);
if (h >= t) {
break;
}
mp_obj_t x = h[0];
h[0] = t[0];
t[0] = x;
}
mp_obj_t x = h[0];
h[0] = tail[0];
tail[0] = x;
// do the smaller recursive call first, to keep stack within O(log(N))
if (t - head < tail - h - 1) {
mp_quicksort(head, t, key_fn, binop_less_result);
head = h + 1;
} else {
mp_quicksort(h + 1, tail, key_fn, binop_less_result);
tail = t;
}
}
}
// TODO Python defines sort to be stable but ours is not
mp_obj_t mp_obj_list_sort(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
static const mp_arg_t allowed_args[] = {
{ MP_QSTR_key, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_rom_obj = MP_ROM_NONE} },
{ MP_QSTR_reverse, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = false} },
};
// parse args
struct {
mp_arg_val_t key, reverse;
} args;
mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args,
MP_ARRAY_SIZE(allowed_args), allowed_args, (mp_arg_val_t *)&args);
mp_check_self(mp_obj_is_type(pos_args[0], &mp_type_list));
mp_obj_list_t *self = MP_OBJ_TO_PTR(pos_args[0]);
if (self->len > 1) {
mp_quicksort(self->items, self->items + self->len - 1,
args.key.u_obj == mp_const_none ? MP_OBJ_NULL : args.key.u_obj,
args.reverse.u_bool ? mp_const_false : mp_const_true);
}
return mp_const_none;
}
STATIC mp_obj_t list_clear(mp_obj_t self_in) {
mp_check_self(mp_obj_is_type(self_in, &mp_type_list));
mp_obj_list_t *self = MP_OBJ_TO_PTR(self_in);
self->len = 0;
self->items = m_renew(mp_obj_t, self->items, self->alloc, LIST_MIN_ALLOC);
self->alloc = LIST_MIN_ALLOC;
mp_seq_clear(self->items, 0, self->alloc, sizeof(*self->items));
return mp_const_none;
}
STATIC mp_obj_t list_copy(mp_obj_t self_in) {
mp_check_self(mp_obj_is_type(self_in, &mp_type_list));
mp_obj_list_t *self = MP_OBJ_TO_PTR(self_in);
return mp_obj_new_list(self->len, self->items);
}
STATIC mp_obj_t list_count(mp_obj_t self_in, mp_obj_t value) {
mp_check_self(mp_obj_is_type(self_in, &mp_type_list));
mp_obj_list_t *self = MP_OBJ_TO_PTR(self_in);
return mp_seq_count_obj(self->items, self->len, value);
}
STATIC mp_obj_t list_index(size_t n_args, const mp_obj_t *args) {
mp_check_self(mp_obj_is_type(args[0], &mp_type_list));
mp_obj_list_t *self = MP_OBJ_TO_PTR(args[0]);
return mp_seq_index_obj(self->items, self->len, n_args, args);
}
STATIC mp_obj_t list_insert(mp_obj_t self_in, mp_obj_t idx, mp_obj_t obj) {
mp_check_self(mp_obj_is_type(self_in, &mp_type_list));
mp_obj_list_t *self = MP_OBJ_TO_PTR(self_in);
// insert has its own strange index logic
mp_int_t index = MP_OBJ_SMALL_INT_VALUE(idx);
if (index < 0) {
index += self->len;
}
if (index < 0) {
index = 0;
}
if ((size_t)index > self->len) {
index = self->len;
}
mp_obj_list_append(self_in, mp_const_none);
for (mp_int_t i = self->len - 1; i > index; i--) {
self->items[i] = self->items[i - 1];
}
self->items[index] = obj;
return mp_const_none;
}
mp_obj_t mp_obj_list_remove(mp_obj_t self_in, mp_obj_t value) {
mp_check_self(mp_obj_is_type(self_in, &mp_type_list));
mp_obj_t args[] = {self_in, value};
args[1] = list_index(2, args);
list_pop(2, args);
return mp_const_none;
}
STATIC mp_obj_t list_reverse(mp_obj_t self_in) {
mp_check_self(mp_obj_is_type(self_in, &mp_type_list));
mp_obj_list_t *self = MP_OBJ_TO_PTR(self_in);
mp_int_t len = self->len;
for (mp_int_t i = 0; i < len / 2; i++) {
mp_obj_t a = self->items[i];
self->items[i] = self->items[len - i - 1];
self->items[len - i - 1] = a;
}
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(list_append_obj, mp_obj_list_append);
STATIC MP_DEFINE_CONST_FUN_OBJ_2(list_extend_obj, list_extend);
STATIC MP_DEFINE_CONST_FUN_OBJ_1(list_clear_obj, list_clear);
STATIC MP_DEFINE_CONST_FUN_OBJ_1(list_copy_obj, list_copy);
STATIC MP_DEFINE_CONST_FUN_OBJ_2(list_count_obj, list_count);
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(list_index_obj, 2, 4, list_index);
STATIC MP_DEFINE_CONST_FUN_OBJ_3(list_insert_obj, list_insert);
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(list_pop_obj, 1, 2, list_pop);
STATIC MP_DEFINE_CONST_FUN_OBJ_2(list_remove_obj, mp_obj_list_remove);
STATIC MP_DEFINE_CONST_FUN_OBJ_1(list_reverse_obj, list_reverse);
STATIC MP_DEFINE_CONST_FUN_OBJ_KW(list_sort_obj, 1, mp_obj_list_sort);
STATIC const mp_rom_map_elem_t list_locals_dict_table[] = {
{ MP_ROM_QSTR(MP_QSTR_append), MP_ROM_PTR(&list_append_obj) },
{ MP_ROM_QSTR(MP_QSTR_clear), MP_ROM_PTR(&list_clear_obj) },
{ MP_ROM_QSTR(MP_QSTR_copy), MP_ROM_PTR(&list_copy_obj) },
{ MP_ROM_QSTR(MP_QSTR_count), MP_ROM_PTR(&list_count_obj) },
{ MP_ROM_QSTR(MP_QSTR_extend), MP_ROM_PTR(&list_extend_obj) },
{ MP_ROM_QSTR(MP_QSTR_index), MP_ROM_PTR(&list_index_obj) },
{ MP_ROM_QSTR(MP_QSTR_insert), MP_ROM_PTR(&list_insert_obj) },
{ MP_ROM_QSTR(MP_QSTR_pop), MP_ROM_PTR(&list_pop_obj) },
{ MP_ROM_QSTR(MP_QSTR_remove), MP_ROM_PTR(&list_remove_obj) },
{ MP_ROM_QSTR(MP_QSTR_reverse), MP_ROM_PTR(&list_reverse_obj) },
{ MP_ROM_QSTR(MP_QSTR_sort), MP_ROM_PTR(&list_sort_obj) },
};
STATIC MP_DEFINE_CONST_DICT(list_locals_dict, list_locals_dict_table);
const mp_obj_type_t mp_type_list = {
{ &mp_type_type },
.name = MP_QSTR_list,
.print = list_print,
.make_new = list_make_new,
.unary_op = list_unary_op,
.binary_op = list_binary_op,
.subscr = list_subscr,
.getiter = list_getiter,
.locals_dict = (mp_obj_dict_t *)&list_locals_dict,
};
void mp_obj_list_init(mp_obj_list_t *o, size_t n) {
o->base.type = &mp_type_list;
o->alloc = n < LIST_MIN_ALLOC ? LIST_MIN_ALLOC : n;
o->len = n;
o->items = m_new(mp_obj_t, o->alloc);
mp_seq_clear(o->items, n, o->alloc, sizeof(*o->items));
}
STATIC mp_obj_list_t *list_new(size_t n) {
mp_obj_list_t *o = m_new_obj(mp_obj_list_t);
mp_obj_list_init(o, n);
return o;
}
mp_obj_t mp_obj_new_list(size_t n, mp_obj_t *items) {
mp_obj_list_t *o = list_new(n);
if (items != NULL) {
for (size_t i = 0; i < n; i++) {
o->items[i] = items[i];
}
}
return MP_OBJ_FROM_PTR(o);
}
void mp_obj_list_get(mp_obj_t self_in, size_t *len, mp_obj_t **items) {
mp_obj_list_t *self = MP_OBJ_TO_PTR(self_in);
*len = self->len;
*items = self->items;
}
void mp_obj_list_set_len(mp_obj_t self_in, size_t len) {
// trust that the caller knows what it's doing
// TODO realloc if len got much smaller than alloc
mp_obj_list_t *self = MP_OBJ_TO_PTR(self_in);
self->len = len;
}
void mp_obj_list_store(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) {
mp_obj_list_t *self = MP_OBJ_TO_PTR(self_in);
size_t i = mp_get_index(self->base.type, self->len, index, false);
self->items[i] = value;
}
/******************************************************************************/
/* list iterator */
typedef struct _mp_obj_list_it_t {
mp_obj_base_t base;
mp_fun_1_t iternext;
mp_obj_t list;
size_t cur;
} mp_obj_list_it_t;
STATIC mp_obj_t list_it_iternext(mp_obj_t self_in) {
mp_obj_list_it_t *self = MP_OBJ_TO_PTR(self_in);
mp_obj_list_t *list = MP_OBJ_TO_PTR(self->list);
if (self->cur < list->len) {
mp_obj_t o_out = list->items[self->cur];
self->cur += 1;
return o_out;
} else {
return MP_OBJ_STOP_ITERATION;
}
}
mp_obj_t mp_obj_new_list_iterator(mp_obj_t list, size_t cur, mp_obj_iter_buf_t *iter_buf) {
assert(sizeof(mp_obj_list_it_t) <= sizeof(mp_obj_iter_buf_t));
mp_obj_list_it_t *o = (mp_obj_list_it_t *)iter_buf;
o->base.type = &mp_type_polymorph_iter;
o->iternext = list_it_iternext;
o->list = list;
o->cur = cur;
return MP_OBJ_FROM_PTR(o);
}
| YifuLiu/AliOS-Things | components/py_engine/engine/py/objlist.c | C | apache-2.0 | 20,381 |
/*
* 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.
*/
#ifndef MICROPY_INCLUDED_PY_OBJLIST_H
#define MICROPY_INCLUDED_PY_OBJLIST_H
#include "py/obj.h"
typedef struct _mp_obj_list_t {
mp_obj_base_t base;
size_t alloc;
size_t len;
mp_obj_t *items;
} mp_obj_list_t;
void mp_obj_list_init(mp_obj_list_t *o, size_t n);
#endif // MICROPY_INCLUDED_PY_OBJLIST_H
| YifuLiu/AliOS-Things | components/py_engine/engine/py/objlist.h | C | apache-2.0 | 1,550 |
/*
* 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 <stdlib.h>
#include <assert.h>
#include "py/runtime.h"
typedef struct _mp_obj_map_t {
mp_obj_base_t base;
size_t n_iters;
mp_obj_t fun;
mp_obj_t iters[];
} mp_obj_map_t;
STATIC mp_obj_t map_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
mp_arg_check_num(n_args, n_kw, 2, MP_OBJ_FUN_ARGS_MAX, false);
mp_obj_map_t *o = m_new_obj_var(mp_obj_map_t, mp_obj_t, n_args - 1);
o->base.type = type;
o->n_iters = n_args - 1;
o->fun = args[0];
for (size_t i = 0; i < n_args - 1; i++) {
o->iters[i] = mp_getiter(args[i + 1], NULL);
}
return MP_OBJ_FROM_PTR(o);
}
STATIC mp_obj_t map_iternext(mp_obj_t self_in) {
mp_check_self(mp_obj_is_type(self_in, &mp_type_map));
mp_obj_map_t *self = MP_OBJ_TO_PTR(self_in);
mp_obj_t *nextses = m_new(mp_obj_t, self->n_iters);
for (size_t i = 0; i < self->n_iters; i++) {
mp_obj_t next = mp_iternext(self->iters[i]);
if (next == MP_OBJ_STOP_ITERATION) {
m_del(mp_obj_t, nextses, self->n_iters);
return MP_OBJ_STOP_ITERATION;
}
nextses[i] = next;
}
return mp_call_function_n_kw(self->fun, self->n_iters, 0, nextses);
}
const mp_obj_type_t mp_type_map = {
{ &mp_type_type },
.name = MP_QSTR_map,
.make_new = map_make_new,
.getiter = mp_identity_getiter,
.iternext = map_iternext,
};
| YifuLiu/AliOS-Things | components/py_engine/engine/py/objmap.c | C | apache-2.0 | 2,649 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2013-2019 Damien P. George
* Copyright (c) 2014-2015 Paul Sokolovsky
*
* 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 <stdlib.h>
#include <string.h>
#include <assert.h>
#include "py/objmodule.h"
#include "py/runtime.h"
#include "py/builtin.h"
#include "genhdr/moduledefs.h"
STATIC void module_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
(void)kind;
mp_obj_module_t *self = MP_OBJ_TO_PTR(self_in);
const char *module_name = "";
mp_map_elem_t *elem = mp_map_lookup(&self->globals->map, MP_OBJ_NEW_QSTR(MP_QSTR___name__), MP_MAP_LOOKUP);
if (elem != NULL) {
module_name = mp_obj_str_get_str(elem->value);
}
#if MICROPY_PY___FILE__
// If we store __file__ to imported modules then try to lookup this
// symbol to give more information about the module.
elem = mp_map_lookup(&self->globals->map, MP_OBJ_NEW_QSTR(MP_QSTR___file__), MP_MAP_LOOKUP);
if (elem != NULL) {
mp_printf(print, "<module '%s' from '%s'>", module_name, mp_obj_str_get_str(elem->value));
return;
}
#endif
mp_printf(print, "<module '%s'>", module_name);
}
STATIC void module_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) {
mp_obj_module_t *self = MP_OBJ_TO_PTR(self_in);
if (dest[0] == MP_OBJ_NULL) {
// load attribute
mp_map_elem_t *elem = mp_map_lookup(&self->globals->map, MP_OBJ_NEW_QSTR(attr), MP_MAP_LOOKUP);
if (elem != NULL) {
dest[0] = elem->value;
#if MICROPY_MODULE_GETATTR
} else if (attr != MP_QSTR___getattr__) {
elem = mp_map_lookup(&self->globals->map, MP_OBJ_NEW_QSTR(MP_QSTR___getattr__), MP_MAP_LOOKUP);
if (elem != NULL) {
dest[0] = mp_call_function_1(elem->value, MP_OBJ_NEW_QSTR(attr));
}
#endif
}
} else {
// delete/store attribute
mp_obj_dict_t *dict = self->globals;
if (dict->map.is_fixed) {
#if MICROPY_CAN_OVERRIDE_BUILTINS
if (dict == &mp_module_builtins_globals) {
if (MP_STATE_VM(mp_module_builtins_override_dict) == NULL) {
MP_STATE_VM(mp_module_builtins_override_dict) = MP_OBJ_TO_PTR(mp_obj_new_dict(1));
}
dict = MP_STATE_VM(mp_module_builtins_override_dict);
} else
#endif
{
// can't delete or store to fixed map
return;
}
}
if (dest[1] == MP_OBJ_NULL) {
// delete attribute
mp_obj_dict_delete(MP_OBJ_FROM_PTR(dict), MP_OBJ_NEW_QSTR(attr));
} else {
// store attribute
mp_obj_dict_store(MP_OBJ_FROM_PTR(dict), MP_OBJ_NEW_QSTR(attr), dest[1]);
}
dest[0] = MP_OBJ_NULL; // indicate success
}
}
const mp_obj_type_t mp_type_module = {
{ &mp_type_type },
.name = MP_QSTR_module,
.print = module_print,
.attr = module_attr,
};
mp_obj_t mp_obj_new_module(qstr module_name) {
mp_map_t *mp_loaded_modules_map = &MP_STATE_VM(mp_loaded_modules_dict).map;
mp_map_elem_t *el = mp_map_lookup(mp_loaded_modules_map, MP_OBJ_NEW_QSTR(module_name), MP_MAP_LOOKUP_ADD_IF_NOT_FOUND);
// We could error out if module already exists, but let C extensions
// add new members to existing modules.
if (el->value != MP_OBJ_NULL) {
return el->value;
}
// create new module object
mp_obj_module_t *o = m_new_obj(mp_obj_module_t);
o->base.type = &mp_type_module;
o->globals = MP_OBJ_TO_PTR(mp_obj_new_dict(MICROPY_MODULE_DICT_SIZE));
// store __name__ entry in the module
mp_obj_dict_store(MP_OBJ_FROM_PTR(o->globals), MP_OBJ_NEW_QSTR(MP_QSTR___name__), MP_OBJ_NEW_QSTR(module_name));
// store the new module into the slot in the global dict holding all modules
el->value = MP_OBJ_FROM_PTR(o);
// return the new module
return MP_OBJ_FROM_PTR(o);
}
/******************************************************************************/
// Global module table and related functions
STATIC const mp_rom_map_elem_t mp_builtin_module_table[] = {
{ MP_ROM_QSTR(MP_QSTR___main__), MP_ROM_PTR(&mp_module___main__) },
{ MP_ROM_QSTR(MP_QSTR_builtins), MP_ROM_PTR(&mp_module_builtins) },
{ MP_ROM_QSTR(MP_QSTR_micropython), MP_ROM_PTR(&mp_module_micropython) },
#if MICROPY_PY_IO
{ MP_ROM_QSTR(MP_QSTR_uio), MP_ROM_PTR(&mp_module_io) },
#endif
#if MICROPY_PY_COLLECTIONS
{ MP_ROM_QSTR(MP_QSTR_ucollections), MP_ROM_PTR(&mp_module_collections) },
#endif
#if MICROPY_PY_STRUCT
{ MP_ROM_QSTR(MP_QSTR_ustruct), MP_ROM_PTR(&mp_module_ustruct) },
#endif
#if MICROPY_PY_BUILTINS_FLOAT
#if MICROPY_PY_MATH
{ MP_ROM_QSTR(MP_QSTR_math), MP_ROM_PTR(&mp_module_math) },
#endif
#if MICROPY_PY_BUILTINS_COMPLEX && MICROPY_PY_CMATH
{ MP_ROM_QSTR(MP_QSTR_cmath), MP_ROM_PTR(&mp_module_cmath) },
#endif
#endif
#if MICROPY_PY_SYS
{ MP_ROM_QSTR(MP_QSTR_usys), MP_ROM_PTR(&mp_module_sys) },
#endif
#if MICROPY_PY_GC && MICROPY_ENABLE_GC
{ MP_ROM_QSTR(MP_QSTR_gc), MP_ROM_PTR(&mp_module_gc) },
#endif
#if MICROPY_PY_THREAD
{ MP_ROM_QSTR(MP_QSTR__thread), MP_ROM_PTR(&mp_module_thread) },
#endif
// extmod modules
#if MICROPY_PY_UASYNCIO
{ MP_ROM_QSTR(MP_QSTR__uasyncio), MP_ROM_PTR(&mp_module_uasyncio) },
#endif
#if MICROPY_PY_UERRNO
{ MP_ROM_QSTR(MP_QSTR_uerrno), MP_ROM_PTR(&mp_module_uerrno) },
#endif
#if MICROPY_PY_UCTYPES
{ MP_ROM_QSTR(MP_QSTR_uctypes), MP_ROM_PTR(&mp_module_uctypes) },
#endif
#if MICROPY_PY_UZLIB
{ MP_ROM_QSTR(MP_QSTR_uzlib), MP_ROM_PTR(&mp_module_uzlib) },
#endif
#if MICROPY_PY_UJSON
{ MP_ROM_QSTR(MP_QSTR_ujson), MP_ROM_PTR(&mp_module_ujson) },
#endif
#if MICROPY_PY_URE
{ MP_ROM_QSTR(MP_QSTR_ure), MP_ROM_PTR(&mp_module_ure) },
#endif
#if MICROPY_PY_UHEAPQ
{ MP_ROM_QSTR(MP_QSTR_uheapq), MP_ROM_PTR(&mp_module_uheapq) },
#endif
#if MICROPY_PY_UTIMEQ
{ MP_ROM_QSTR(MP_QSTR_utimeq), MP_ROM_PTR(&mp_module_utimeq) },
#endif
#if MICROPY_PY_UHASHLIB
{ MP_ROM_QSTR(MP_QSTR_uhashlib), MP_ROM_PTR(&mp_module_uhashlib) },
#endif
#if MICROPY_PY_UCRYPTOLIB
{ MP_ROM_QSTR(MP_QSTR_ucryptolib), MP_ROM_PTR(&mp_module_ucryptolib) },
#endif
#if MICROPY_PY_UBINASCII
{ MP_ROM_QSTR(MP_QSTR_ubinascii), MP_ROM_PTR(&mp_module_ubinascii) },
#endif
#if MICROPY_PY_URANDOM
{ MP_ROM_QSTR(MP_QSTR_urandom), MP_ROM_PTR(&mp_module_urandom) },
#endif
#if MICROPY_PY_USELECT
{ MP_ROM_QSTR(MP_QSTR_uselect), MP_ROM_PTR(&mp_module_uselect) },
#endif
#if MICROPY_PY_USSL
{ MP_ROM_QSTR(MP_QSTR_ussl), MP_ROM_PTR(&mp_module_ussl) },
#endif
#if MICROPY_PY_LWIP
{ MP_ROM_QSTR(MP_QSTR_lwip), MP_ROM_PTR(&mp_module_lwip) },
#endif
#if MICROPY_PY_UWEBSOCKET
{ MP_ROM_QSTR(MP_QSTR_uwebsocket), MP_ROM_PTR(&mp_module_uwebsocket) },
#endif
#if MICROPY_PY_WEBREPL
{ MP_ROM_QSTR(MP_QSTR__webrepl), MP_ROM_PTR(&mp_module_webrepl) },
#endif
#if MICROPY_PY_FRAMEBUF
{ MP_ROM_QSTR(MP_QSTR_framebuf), MP_ROM_PTR(&mp_module_framebuf) },
#endif
#if MICROPY_PY_BTREE
{ MP_ROM_QSTR(MP_QSTR_btree), MP_ROM_PTR(&mp_module_btree) },
#endif
#if MICROPY_PY_BLUETOOTH
{ MP_ROM_QSTR(MP_QSTR_ubluetooth), MP_ROM_PTR(&mp_module_ubluetooth) },
#endif
// extra builtin modules as defined by a port
MICROPY_PORT_BUILTIN_MODULES
#ifdef MICROPY_REGISTERED_MODULES
// builtin modules declared with MP_REGISTER_MODULE()
MICROPY_REGISTERED_MODULES
#endif
};
MP_DEFINE_CONST_MAP(mp_builtin_module_map, mp_builtin_module_table);
// returns MP_OBJ_NULL if not found
mp_obj_t mp_module_get(qstr module_name) {
mp_map_t *mp_loaded_modules_map = &MP_STATE_VM(mp_loaded_modules_dict).map;
// lookup module
mp_map_elem_t *el = mp_map_lookup(mp_loaded_modules_map, MP_OBJ_NEW_QSTR(module_name), MP_MAP_LOOKUP);
if (el == NULL) {
// module not found, look for builtin module names
el = mp_map_lookup((mp_map_t *)&mp_builtin_module_map, MP_OBJ_NEW_QSTR(module_name), MP_MAP_LOOKUP);
if (el == NULL) {
return MP_OBJ_NULL;
}
mp_module_call_init(module_name, el->value);
}
// module found, return it
return el->value;
}
void mp_module_register(qstr qst, mp_obj_t module) {
mp_map_t *mp_loaded_modules_map = &MP_STATE_VM(mp_loaded_modules_dict).map;
mp_map_lookup(mp_loaded_modules_map, MP_OBJ_NEW_QSTR(qst), MP_MAP_LOOKUP_ADD_IF_NOT_FOUND)->value = module;
}
#if MICROPY_MODULE_WEAK_LINKS
// Search for u"foo" in built-in modules, return MP_OBJ_NULL if not found
mp_obj_t mp_module_search_umodule(const char *module_str) {
for (size_t i = 0; i < MP_ARRAY_SIZE(mp_builtin_module_table); ++i) {
const mp_map_elem_t *entry = (const mp_map_elem_t *)&mp_builtin_module_table[i];
const char *key = qstr_str(MP_OBJ_QSTR_VALUE(entry->key));
if (key[0] == 'u' && strcmp(&key[1], module_str) == 0) {
return (mp_obj_t)entry->value;
}
}
return MP_OBJ_NULL;
}
#endif
#if MICROPY_MODULE_BUILTIN_INIT
void mp_module_call_init(qstr module_name, mp_obj_t module_obj) {
// Look for __init__ and call it if it exists
mp_obj_t dest[2];
mp_load_method_maybe(module_obj, MP_QSTR___init__, dest);
if (dest[0] != MP_OBJ_NULL) {
mp_call_method_n_kw(0, 0, dest);
// Register module so __init__ is not called again.
// If a module can be referenced by more than one name (eg due to weak links)
// then __init__ will still be called for each distinct import, and it's then
// up to the particular module to make sure it's __init__ code only runs once.
mp_module_register(module_name, module_obj);
}
}
#endif
| YifuLiu/AliOS-Things | components/py_engine/engine/py/objmodule.c | C | apache-2.0 | 11,071 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2013-2019 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.
*/
#ifndef MICROPY_INCLUDED_PY_OBJMODULE_H
#define MICROPY_INCLUDED_PY_OBJMODULE_H
#include "py/obj.h"
extern const mp_map_t mp_builtin_module_map;
mp_obj_t mp_module_get(qstr module_name);
void mp_module_register(qstr qstr, mp_obj_t module);
mp_obj_t mp_module_search_umodule(const char *module_str);
#if MICROPY_MODULE_BUILTIN_INIT
void mp_module_call_init(qstr module_name, mp_obj_t module_obj);
#else
static inline void mp_module_call_init(qstr module_name, mp_obj_t module_obj) {
(void)module_name;
(void)module_obj;
}
#endif
#endif // MICROPY_INCLUDED_PY_OBJMODULE_H
| YifuLiu/AliOS-Things | components/py_engine/engine/py/objmodule.h | C | apache-2.0 | 1,814 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2013, 2014 Damien P. George
* Copyright (c) 2014 Paul Sokolovsky
*
* 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 <string.h>
#include "py/objtuple.h"
#include "py/runtime.h"
#include "py/objstr.h"
#include "py/objnamedtuple.h"
#if MICROPY_PY_COLLECTIONS
size_t mp_obj_namedtuple_find_field(const mp_obj_namedtuple_type_t *type, qstr name) {
for (size_t i = 0; i < type->n_fields; i++) {
if (type->fields[i] == name) {
return i;
}
}
return (size_t)-1;
}
#if MICROPY_PY_COLLECTIONS_NAMEDTUPLE__ASDICT
STATIC mp_obj_t namedtuple_asdict(mp_obj_t self_in) {
mp_obj_namedtuple_t *self = MP_OBJ_TO_PTR(self_in);
const qstr *fields = ((mp_obj_namedtuple_type_t *)self->tuple.base.type)->fields;
mp_obj_t dict = mp_obj_new_dict(self->tuple.len);
// make it an OrderedDict
mp_obj_dict_t *dictObj = MP_OBJ_TO_PTR(dict);
dictObj->base.type = &mp_type_ordereddict;
dictObj->map.is_ordered = 1;
for (size_t i = 0; i < self->tuple.len; ++i) {
mp_obj_dict_store(dict, MP_OBJ_NEW_QSTR(fields[i]), self->tuple.items[i]);
}
return dict;
}
MP_DEFINE_CONST_FUN_OBJ_1(namedtuple_asdict_obj, namedtuple_asdict);
#endif
STATIC void namedtuple_print(const mp_print_t *print, mp_obj_t o_in, mp_print_kind_t kind) {
(void)kind;
mp_obj_namedtuple_t *o = MP_OBJ_TO_PTR(o_in);
mp_printf(print, "%q", o->tuple.base.type->name);
const qstr *fields = ((mp_obj_namedtuple_type_t *)o->tuple.base.type)->fields;
mp_obj_attrtuple_print_helper(print, fields, &o->tuple);
}
STATIC void namedtuple_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) {
if (dest[0] == MP_OBJ_NULL) {
// load attribute
mp_obj_namedtuple_t *self = MP_OBJ_TO_PTR(self_in);
#if MICROPY_PY_COLLECTIONS_NAMEDTUPLE__ASDICT
if (attr == MP_QSTR__asdict) {
dest[0] = MP_OBJ_FROM_PTR(&namedtuple_asdict_obj);
dest[1] = self_in;
return;
}
#endif
size_t id = mp_obj_namedtuple_find_field((mp_obj_namedtuple_type_t *)self->tuple.base.type, attr);
if (id == (size_t)-1) {
return;
}
dest[0] = self->tuple.items[id];
} else {
// delete/store attribute
// provide more detailed error message than we'd get by just returning
mp_raise_msg(&mp_type_AttributeError, MP_ERROR_TEXT("can't set attribute"));
}
}
STATIC mp_obj_t namedtuple_make_new(const mp_obj_type_t *type_in, size_t n_args, size_t n_kw, const mp_obj_t *args) {
const mp_obj_namedtuple_type_t *type = (const mp_obj_namedtuple_type_t *)type_in;
size_t num_fields = type->n_fields;
if (n_args + n_kw != num_fields) {
#if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
mp_arg_error_terse_mismatch();
#elif MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_NORMAL
mp_raise_msg_varg(&mp_type_TypeError,
MP_ERROR_TEXT("function takes %d positional arguments but %d were given"),
num_fields, n_args + n_kw);
#elif MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_DETAILED
mp_raise_msg_varg(&mp_type_TypeError,
MP_ERROR_TEXT("%q() takes %d positional arguments but %d were given"),
type->base.name, num_fields, n_args + n_kw);
#endif
}
// Create a tuple and set the type to this namedtuple
mp_obj_tuple_t *tuple = MP_OBJ_TO_PTR(mp_obj_new_tuple(num_fields, NULL));
tuple->base.type = type_in;
// Copy the positional args into the first slots of the namedtuple
memcpy(&tuple->items[0], args, sizeof(mp_obj_t) * n_args);
// Fill in the remaining slots with the keyword args
memset(&tuple->items[n_args], 0, sizeof(mp_obj_t) * n_kw);
for (size_t i = n_args; i < n_args + 2 * n_kw; i += 2) {
qstr kw = mp_obj_str_get_qstr(args[i]);
size_t id = mp_obj_namedtuple_find_field(type, kw);
if (id == (size_t)-1) {
#if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
mp_arg_error_terse_mismatch();
#else
mp_raise_msg_varg(&mp_type_TypeError, MP_ERROR_TEXT("unexpected keyword argument '%q'"), kw);
#endif
}
if (tuple->items[id] != MP_OBJ_NULL) {
#if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
mp_arg_error_terse_mismatch();
#else
mp_raise_msg_varg(&mp_type_TypeError,
MP_ERROR_TEXT("function got multiple values for argument '%q'"), kw);
#endif
}
tuple->items[id] = args[i + 1];
}
return MP_OBJ_FROM_PTR(tuple);
}
mp_obj_namedtuple_type_t *mp_obj_new_namedtuple_base(size_t n_fields, mp_obj_t *fields) {
mp_obj_namedtuple_type_t *o = m_new_obj_var(mp_obj_namedtuple_type_t, qstr, n_fields);
memset(&o->base, 0, sizeof(o->base));
o->n_fields = n_fields;
for (size_t i = 0; i < n_fields; i++) {
o->fields[i] = mp_obj_str_get_qstr(fields[i]);
}
return o;
}
STATIC mp_obj_t mp_obj_new_namedtuple_type(qstr name, size_t n_fields, mp_obj_t *fields) {
mp_obj_namedtuple_type_t *o = mp_obj_new_namedtuple_base(n_fields, fields);
o->base.base.type = &mp_type_type;
o->base.flags = MP_TYPE_FLAG_EQ_CHECKS_OTHER_TYPE; // can match tuple
o->base.name = name;
o->base.print = namedtuple_print;
o->base.make_new = namedtuple_make_new;
o->base.unary_op = mp_obj_tuple_unary_op;
o->base.binary_op = mp_obj_tuple_binary_op;
o->base.attr = namedtuple_attr;
o->base.subscr = mp_obj_tuple_subscr;
o->base.getiter = mp_obj_tuple_getiter;
o->base.parent = &mp_type_tuple;
return MP_OBJ_FROM_PTR(o);
}
STATIC mp_obj_t new_namedtuple_type(mp_obj_t name_in, mp_obj_t fields_in) {
qstr name = mp_obj_str_get_qstr(name_in);
size_t n_fields;
mp_obj_t *fields;
#if MICROPY_CPYTHON_COMPAT
if (mp_obj_is_str(fields_in)) {
fields_in = mp_obj_str_split(1, &fields_in);
}
#endif
mp_obj_get_array(fields_in, &n_fields, &fields);
return mp_obj_new_namedtuple_type(name, n_fields, fields);
}
MP_DEFINE_CONST_FUN_OBJ_2(mp_namedtuple_obj, new_namedtuple_type);
#endif // MICROPY_PY_COLLECTIONS
| YifuLiu/AliOS-Things | components/py_engine/engine/py/objnamedtuple.c | C | apache-2.0 | 7,387 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2014-2017 Paul Sokolovsky
*
* 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.
*/
#ifndef MICROPY_INCLUDED_PY_OBJNAMEDTUPLE_H
#define MICROPY_INCLUDED_PY_OBJNAMEDTUPLE_H
#include "py/objtuple.h"
typedef struct _mp_obj_namedtuple_type_t {
mp_obj_type_t base;
size_t n_fields;
qstr fields[];
} mp_obj_namedtuple_type_t;
typedef struct _mp_obj_namedtuple_t {
mp_obj_tuple_t tuple;
} mp_obj_namedtuple_t;
size_t mp_obj_namedtuple_find_field(const mp_obj_namedtuple_type_t *type, qstr name);
mp_obj_namedtuple_type_t *mp_obj_new_namedtuple_base(size_t n_fields, mp_obj_t *fields);
#endif // MICROPY_INCLUDED_PY_OBJNAMEDTUPLE_H
| YifuLiu/AliOS-Things | components/py_engine/engine/py/objnamedtuple.h | C | apache-2.0 | 1,790 |
/*
* 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 <stdlib.h>
#include "py/obj.h"
#if !MICROPY_OBJ_IMMEDIATE_OBJS
typedef struct _mp_obj_none_t {
mp_obj_base_t base;
} mp_obj_none_t;
#endif
STATIC void none_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
(void)self_in;
if (MICROPY_PY_UJSON && kind == PRINT_JSON) {
mp_print_str(print, "null");
} else {
mp_print_str(print, "None");
}
}
const mp_obj_type_t mp_type_NoneType = {
{ &mp_type_type },
.name = MP_QSTR_NoneType,
.print = none_print,
.unary_op = mp_generic_unary_op,
};
#if !MICROPY_OBJ_IMMEDIATE_OBJS
const mp_obj_none_t mp_const_none_obj = {{&mp_type_NoneType}};
#endif
| YifuLiu/AliOS-Things | components/py_engine/engine/py/objnone.c | C | apache-2.0 | 1,904 |
/*
* 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 <stdlib.h>
#include "py/objtype.h"
#include "py/runtime.h"
typedef struct _mp_obj_object_t {
mp_obj_base_t base;
} mp_obj_object_t;
STATIC mp_obj_t object_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
(void)args;
mp_arg_check_num(n_args, n_kw, 0, 0, false);
mp_obj_object_t *o = m_new_obj(mp_obj_object_t);
o->base.type = type;
return MP_OBJ_FROM_PTR(o);
}
#if MICROPY_CPYTHON_COMPAT
STATIC mp_obj_t object___init__(mp_obj_t self) {
(void)self;
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(object___init___obj, object___init__);
STATIC mp_obj_t object___new__(mp_obj_t cls) {
if (!mp_obj_is_type(cls, &mp_type_type) || !mp_obj_is_instance_type((mp_obj_type_t *)MP_OBJ_TO_PTR(cls))) {
mp_raise_TypeError(MP_ERROR_TEXT("arg must be user-type"));
}
// This executes only "__new__" part of instance creation.
// TODO: This won't work well for classes with native bases.
// TODO: This is a hack, should be resolved along the lines of
// https://github.com/micropython/micropython/issues/606#issuecomment-43685883
const mp_obj_type_t *native_base;
return MP_OBJ_FROM_PTR(mp_obj_new_instance(MP_OBJ_TO_PTR(cls), &native_base));
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(object___new___fun_obj, object___new__);
STATIC MP_DEFINE_CONST_STATICMETHOD_OBJ(object___new___obj, MP_ROM_PTR(&object___new___fun_obj));
#if MICROPY_PY_DELATTR_SETATTR
STATIC mp_obj_t object___setattr__(mp_obj_t self_in, mp_obj_t attr, mp_obj_t value) {
if (!mp_obj_is_instance_type(mp_obj_get_type(self_in))) {
mp_raise_TypeError(MP_ERROR_TEXT("arg must be user-type"));
}
if (!mp_obj_is_str(attr)) {
mp_raise_TypeError(NULL);
}
mp_obj_instance_t *self = MP_OBJ_TO_PTR(self_in);
mp_map_lookup(&self->members, attr, MP_MAP_LOOKUP_ADD_IF_NOT_FOUND)->value = value;
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_3(object___setattr___obj, object___setattr__);
STATIC mp_obj_t object___delattr__(mp_obj_t self_in, mp_obj_t attr) {
if (!mp_obj_is_instance_type(mp_obj_get_type(self_in))) {
mp_raise_TypeError(MP_ERROR_TEXT("arg must be user-type"));
}
if (!mp_obj_is_str(attr)) {
mp_raise_TypeError(NULL);
}
mp_obj_instance_t *self = MP_OBJ_TO_PTR(self_in);
if (mp_map_lookup(&self->members, attr, MP_MAP_LOOKUP_REMOVE_IF_FOUND) == NULL) {
mp_raise_msg(&mp_type_AttributeError, MP_ERROR_TEXT("no such attribute"));
}
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(object___delattr___obj, object___delattr__);
#endif
STATIC const mp_rom_map_elem_t object_locals_dict_table[] = {
#if MICROPY_CPYTHON_COMPAT
{ MP_ROM_QSTR(MP_QSTR___init__), MP_ROM_PTR(&object___init___obj) },
#endif
#if MICROPY_CPYTHON_COMPAT
{ MP_ROM_QSTR(MP_QSTR___new__), MP_ROM_PTR(&object___new___obj) },
#endif
#if MICROPY_PY_DELATTR_SETATTR
{ MP_ROM_QSTR(MP_QSTR___setattr__), MP_ROM_PTR(&object___setattr___obj) },
{ MP_ROM_QSTR(MP_QSTR___delattr__), MP_ROM_PTR(&object___delattr___obj) },
#endif
};
STATIC MP_DEFINE_CONST_DICT(object_locals_dict, object_locals_dict_table);
#endif
const mp_obj_type_t mp_type_object = {
{ &mp_type_type },
.name = MP_QSTR_object,
.make_new = object_make_new,
#if MICROPY_CPYTHON_COMPAT
.locals_dict = (mp_obj_dict_t *)&object_locals_dict,
#endif
};
| YifuLiu/AliOS-Things | components/py_engine/engine/py/objobject.c | C | apache-2.0 | 4,673 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2015 Paul Sokolovsky
*
* 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 <stdlib.h>
#include "py/runtime.h"
// This is universal iterator type which calls "iternext" method stored in
// particular object instance. (So, each instance of this time can have its
// own iteration behavior.) Having this type saves to define type objects
// for various internal iterator objects.
// Any instance should have these 2 fields at the beginning
typedef struct _mp_obj_polymorph_iter_t {
mp_obj_base_t base;
mp_fun_1_t iternext;
} mp_obj_polymorph_iter_t;
STATIC mp_obj_t polymorph_it_iternext(mp_obj_t self_in) {
mp_obj_polymorph_iter_t *self = MP_OBJ_TO_PTR(self_in);
// Redirect call to object instance's iternext method
return self->iternext(self_in);
}
const mp_obj_type_t mp_type_polymorph_iter = {
{ &mp_type_type },
.name = MP_QSTR_iterator,
.getiter = mp_identity_getiter,
.iternext = polymorph_it_iternext,
};
| YifuLiu/AliOS-Things | components/py_engine/engine/py/objpolyiter.c | C | apache-2.0 | 2,111 |
/*
* 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 <stdlib.h>
#include <assert.h>
#include "py/runtime.h"
#if MICROPY_PY_BUILTINS_PROPERTY
typedef struct _mp_obj_property_t {
mp_obj_base_t base;
mp_obj_t proxy[3]; // getter, setter, deleter
} mp_obj_property_t;
STATIC mp_obj_t property_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
enum { ARG_fget, ARG_fset, ARG_fdel, ARG_doc };
static const mp_arg_t allowed_args[] = {
{ MP_QSTR_, MP_ARG_OBJ, {.u_rom_obj = MP_ROM_NONE} },
{ MP_QSTR_, MP_ARG_OBJ, {.u_rom_obj = MP_ROM_NONE} },
{ MP_QSTR_, MP_ARG_OBJ, {.u_rom_obj = MP_ROM_NONE} },
{ MP_QSTR_doc, MP_ARG_OBJ, {.u_rom_obj = MP_ROM_NONE} },
};
mp_arg_val_t vals[MP_ARRAY_SIZE(allowed_args)];
mp_arg_parse_all_kw_array(n_args, n_kw, args, MP_ARRAY_SIZE(allowed_args), allowed_args, vals);
mp_obj_property_t *o = m_new_obj(mp_obj_property_t);
o->base.type = type;
o->proxy[0] = vals[ARG_fget].u_obj;
o->proxy[1] = vals[ARG_fset].u_obj;
o->proxy[2] = vals[ARG_fdel].u_obj;
// vals[ARG_doc] is silently discarded
return MP_OBJ_FROM_PTR(o);
}
STATIC mp_obj_t property_getter(mp_obj_t self_in, mp_obj_t getter) {
mp_obj_property_t *p2 = m_new_obj(mp_obj_property_t);
*p2 = *(mp_obj_property_t *)MP_OBJ_TO_PTR(self_in);
p2->proxy[0] = getter;
return MP_OBJ_FROM_PTR(p2);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(property_getter_obj, property_getter);
STATIC mp_obj_t property_setter(mp_obj_t self_in, mp_obj_t setter) {
mp_obj_property_t *p2 = m_new_obj(mp_obj_property_t);
*p2 = *(mp_obj_property_t *)MP_OBJ_TO_PTR(self_in);
p2->proxy[1] = setter;
return MP_OBJ_FROM_PTR(p2);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(property_setter_obj, property_setter);
STATIC mp_obj_t property_deleter(mp_obj_t self_in, mp_obj_t deleter) {
mp_obj_property_t *p2 = m_new_obj(mp_obj_property_t);
*p2 = *(mp_obj_property_t *)MP_OBJ_TO_PTR(self_in);
p2->proxy[2] = deleter;
return MP_OBJ_FROM_PTR(p2);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(property_deleter_obj, property_deleter);
STATIC const mp_rom_map_elem_t property_locals_dict_table[] = {
{ MP_ROM_QSTR(MP_QSTR_getter), MP_ROM_PTR(&property_getter_obj) },
{ MP_ROM_QSTR(MP_QSTR_setter), MP_ROM_PTR(&property_setter_obj) },
{ MP_ROM_QSTR(MP_QSTR_deleter), MP_ROM_PTR(&property_deleter_obj) },
};
STATIC MP_DEFINE_CONST_DICT(property_locals_dict, property_locals_dict_table);
const mp_obj_type_t mp_type_property = {
{ &mp_type_type },
.name = MP_QSTR_property,
.make_new = property_make_new,
.locals_dict = (mp_obj_dict_t *)&property_locals_dict,
};
const mp_obj_t *mp_obj_property_get(mp_obj_t self_in) {
mp_check_self(mp_obj_is_type(self_in, &mp_type_property));
mp_obj_property_t *self = MP_OBJ_TO_PTR(self_in);
return self->proxy;
}
#endif // MICROPY_PY_BUILTINS_PROPERTY
| YifuLiu/AliOS-Things | components/py_engine/engine/py/objproperty.c | C | apache-2.0 | 4,117 |
/*
* 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 <stdlib.h>
#include "py/runtime.h"
/******************************************************************************/
/* range iterator */
typedef struct _mp_obj_range_it_t {
mp_obj_base_t base;
// TODO make these values generic objects or something
mp_int_t cur;
mp_int_t stop;
mp_int_t step;
} mp_obj_range_it_t;
STATIC mp_obj_t range_it_iternext(mp_obj_t o_in) {
mp_obj_range_it_t *o = MP_OBJ_TO_PTR(o_in);
if ((o->step > 0 && o->cur < o->stop) || (o->step < 0 && o->cur > o->stop)) {
mp_obj_t o_out = MP_OBJ_NEW_SMALL_INT(o->cur);
o->cur += o->step;
return o_out;
} else {
return MP_OBJ_STOP_ITERATION;
}
}
STATIC const mp_obj_type_t mp_type_range_it = {
{ &mp_type_type },
.name = MP_QSTR_iterator,
.getiter = mp_identity_getiter,
.iternext = range_it_iternext,
};
STATIC mp_obj_t mp_obj_new_range_iterator(mp_int_t cur, mp_int_t stop, mp_int_t step, mp_obj_iter_buf_t *iter_buf) {
assert(sizeof(mp_obj_range_it_t) <= sizeof(mp_obj_iter_buf_t));
mp_obj_range_it_t *o = (mp_obj_range_it_t *)iter_buf;
o->base.type = &mp_type_range_it;
o->cur = cur;
o->stop = stop;
o->step = step;
return MP_OBJ_FROM_PTR(o);
}
/******************************************************************************/
/* range */
typedef struct _mp_obj_range_t {
mp_obj_base_t base;
// TODO make these values generic objects or something
mp_int_t start;
mp_int_t stop;
mp_int_t step;
} mp_obj_range_t;
STATIC void range_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
(void)kind;
mp_obj_range_t *self = MP_OBJ_TO_PTR(self_in);
mp_printf(print, "range(" INT_FMT ", " INT_FMT "", self->start, self->stop);
if (self->step == 1) {
mp_print_str(print, ")");
} else {
mp_printf(print, ", " INT_FMT ")", self->step);
}
}
STATIC mp_obj_t range_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
mp_arg_check_num(n_args, n_kw, 1, 3, false);
mp_obj_range_t *o = m_new_obj(mp_obj_range_t);
o->base.type = type;
o->start = 0;
o->step = 1;
if (n_args == 1) {
o->stop = mp_obj_get_int(args[0]);
} else {
o->start = mp_obj_get_int(args[0]);
o->stop = mp_obj_get_int(args[1]);
if (n_args == 3) {
o->step = mp_obj_get_int(args[2]);
if (o->step == 0) {
mp_raise_ValueError(MP_ERROR_TEXT("zero step"));
}
}
}
return MP_OBJ_FROM_PTR(o);
}
STATIC mp_int_t range_len(mp_obj_range_t *self) {
// When computing length, need to take into account step!=1 and step<0.
mp_int_t len = self->stop - self->start + self->step;
if (self->step > 0) {
len -= 1;
} else {
len += 1;
}
len = len / self->step;
if (len < 0) {
len = 0;
}
return len;
}
STATIC mp_obj_t range_unary_op(mp_unary_op_t op, mp_obj_t self_in) {
mp_obj_range_t *self = MP_OBJ_TO_PTR(self_in);
mp_int_t len = range_len(self);
switch (op) {
case MP_UNARY_OP_BOOL:
return mp_obj_new_bool(len > 0);
case MP_UNARY_OP_LEN:
return MP_OBJ_NEW_SMALL_INT(len);
default:
return MP_OBJ_NULL; // op not supported
}
}
#if MICROPY_PY_BUILTINS_RANGE_BINOP
STATIC mp_obj_t range_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_in) {
if (!mp_obj_is_type(rhs_in, &mp_type_range) || op != MP_BINARY_OP_EQUAL) {
return MP_OBJ_NULL; // op not supported
}
mp_obj_range_t *lhs = MP_OBJ_TO_PTR(lhs_in);
mp_obj_range_t *rhs = MP_OBJ_TO_PTR(rhs_in);
mp_int_t lhs_len = range_len(lhs);
mp_int_t rhs_len = range_len(rhs);
return mp_obj_new_bool(
lhs_len == rhs_len
&& (lhs_len == 0
|| (lhs->start == rhs->start
&& (lhs_len == 1 || lhs->step == rhs->step)))
);
}
#endif
STATIC mp_obj_t range_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) {
if (value == MP_OBJ_SENTINEL) {
// load
mp_obj_range_t *self = MP_OBJ_TO_PTR(self_in);
mp_int_t len = range_len(self);
#if MICROPY_PY_BUILTINS_SLICE
if (mp_obj_is_type(index, &mp_type_slice)) {
mp_bound_slice_t slice;
mp_seq_get_fast_slice_indexes(len, index, &slice);
mp_obj_range_t *o = m_new_obj(mp_obj_range_t);
o->base.type = &mp_type_range;
o->start = self->start + slice.start * self->step;
o->stop = self->start + slice.stop * self->step;
o->step = slice.step * self->step;
if (slice.step < 0) {
// Negative slice steps have inclusive stop, so adjust for exclusive
o->stop -= self->step;
}
return MP_OBJ_FROM_PTR(o);
}
#endif
size_t index_val = mp_get_index(self->base.type, len, index, false);
return MP_OBJ_NEW_SMALL_INT(self->start + index_val * self->step);
} else {
return MP_OBJ_NULL; // op not supported
}
}
STATIC mp_obj_t range_getiter(mp_obj_t o_in, mp_obj_iter_buf_t *iter_buf) {
mp_obj_range_t *o = MP_OBJ_TO_PTR(o_in);
return mp_obj_new_range_iterator(o->start, o->stop, o->step, iter_buf);
}
#if MICROPY_PY_BUILTINS_RANGE_ATTRS
STATIC void range_attr(mp_obj_t o_in, qstr attr, mp_obj_t *dest) {
if (dest[0] != MP_OBJ_NULL) {
// not load attribute
return;
}
mp_obj_range_t *o = MP_OBJ_TO_PTR(o_in);
if (attr == MP_QSTR_start) {
dest[0] = mp_obj_new_int(o->start);
} else if (attr == MP_QSTR_stop) {
dest[0] = mp_obj_new_int(o->stop);
} else if (attr == MP_QSTR_step) {
dest[0] = mp_obj_new_int(o->step);
}
}
#endif
const mp_obj_type_t mp_type_range = {
{ &mp_type_type },
.name = MP_QSTR_range,
.print = range_print,
.make_new = range_make_new,
.unary_op = range_unary_op,
#if MICROPY_PY_BUILTINS_RANGE_BINOP
.binary_op = range_binary_op,
#endif
.subscr = range_subscr,
.getiter = range_getiter,
#if MICROPY_PY_BUILTINS_RANGE_ATTRS
.attr = range_attr,
#endif
};
| YifuLiu/AliOS-Things | components/py_engine/engine/py/objrange.c | C | apache-2.0 | 7,579 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 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 <stdlib.h>
#include <assert.h>
#include "py/runtime.h"
#if MICROPY_PY_BUILTINS_REVERSED
typedef struct _mp_obj_reversed_t {
mp_obj_base_t base;
mp_obj_t seq; // sequence object that we are reversing
mp_uint_t cur_index; // current index, plus 1; 0=no more, 1=last one (index 0)
} mp_obj_reversed_t;
STATIC mp_obj_t reversed_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
mp_arg_check_num(n_args, n_kw, 1, 1, false);
// check if __reversed__ exists, and if so delegate to it
mp_obj_t dest[2];
mp_load_method_maybe(args[0], MP_QSTR___reversed__, dest);
if (dest[0] != MP_OBJ_NULL) {
return mp_call_method_n_kw(0, 0, dest);
}
mp_obj_reversed_t *o = m_new_obj(mp_obj_reversed_t);
o->base.type = type;
o->seq = args[0];
o->cur_index = mp_obj_get_int(mp_obj_len(args[0])); // start at the end of the sequence
return MP_OBJ_FROM_PTR(o);
}
STATIC mp_obj_t reversed_iternext(mp_obj_t self_in) {
mp_check_self(mp_obj_is_type(self_in, &mp_type_reversed));
mp_obj_reversed_t *self = MP_OBJ_TO_PTR(self_in);
// "raise" stop iteration if we are at the end (the start) of the sequence
if (self->cur_index == 0) {
return MP_OBJ_STOP_ITERATION;
}
// pre-decrement and index sequence
self->cur_index -= 1;
return mp_obj_subscr(self->seq, MP_OBJ_NEW_SMALL_INT(self->cur_index), MP_OBJ_SENTINEL);
}
const mp_obj_type_t mp_type_reversed = {
{ &mp_type_type },
.name = MP_QSTR_reversed,
.make_new = reversed_make_new,
.getiter = mp_identity_getiter,
.iternext = reversed_iternext,
};
#endif // MICROPY_PY_BUILTINS_REVERSED
| YifuLiu/AliOS-Things | components/py_engine/engine/py/objreversed.c | C | apache-2.0 | 2,926 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2013-2017 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 <stdbool.h>
#include <string.h>
#include <assert.h>
#include "py/runtime.h"
#include "py/builtin.h"
#if MICROPY_PY_BUILTINS_SET
typedef struct _mp_obj_set_t {
mp_obj_base_t base;
mp_set_t set;
} mp_obj_set_t;
typedef struct _mp_obj_set_it_t {
mp_obj_base_t base;
mp_fun_1_t iternext;
mp_obj_set_t *set;
size_t cur;
} mp_obj_set_it_t;
STATIC bool is_set_or_frozenset(mp_obj_t o) {
return mp_obj_is_type(o, &mp_type_set)
#if MICROPY_PY_BUILTINS_FROZENSET
|| mp_obj_is_type(o, &mp_type_frozenset)
#endif
;
}
// This macro is shorthand for mp_check_self to verify the argument is a set.
#define check_set(o) mp_check_self(mp_obj_is_type(o, &mp_type_set))
// This macro is shorthand for mp_check_self to verify the argument is a
// set or frozenset for methods that operate on both of these types.
#define check_set_or_frozenset(o) mp_check_self(is_set_or_frozenset(o))
STATIC void set_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
(void)kind;
mp_obj_set_t *self = MP_OBJ_TO_PTR(self_in);
#if MICROPY_PY_BUILTINS_FROZENSET
bool is_frozen = mp_obj_is_type(self_in, &mp_type_frozenset);
#endif
if (self->set.used == 0) {
#if MICROPY_PY_BUILTINS_FROZENSET
if (is_frozen) {
mp_print_str(print, "frozen");
}
#endif
mp_print_str(print, "set()");
return;
}
bool first = true;
#if MICROPY_PY_BUILTINS_FROZENSET
if (is_frozen) {
mp_print_str(print, "frozenset(");
}
#endif
mp_print_str(print, "{");
for (size_t i = 0; i < self->set.alloc; i++) {
if (mp_set_slot_is_filled(&self->set, i)) {
if (!first) {
mp_print_str(print, ", ");
}
first = false;
mp_obj_print_helper(print, self->set.table[i], PRINT_REPR);
}
}
mp_print_str(print, "}");
#if MICROPY_PY_BUILTINS_FROZENSET
if (is_frozen) {
mp_print_str(print, ")");
}
#endif
}
STATIC mp_obj_t set_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
mp_arg_check_num(n_args, n_kw, 0, 1, false);
switch (n_args) {
case 0: {
// create a new, empty set
mp_obj_set_t *set = MP_OBJ_TO_PTR(mp_obj_new_set(0, NULL));
// set actual set/frozenset type
set->base.type = type;
return MP_OBJ_FROM_PTR(set);
}
case 1:
default: { // can only be 0 or 1 arg
// 1 argument, an iterable from which we make a new set
mp_obj_t set = mp_obj_new_set(0, NULL);
mp_obj_t iterable = mp_getiter(args[0], NULL);
mp_obj_t item;
while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
mp_obj_set_store(set, item);
}
// Set actual set/frozenset type
((mp_obj_set_t *)MP_OBJ_TO_PTR(set))->base.type = type;
return set;
}
}
}
STATIC mp_obj_t set_it_iternext(mp_obj_t self_in) {
mp_obj_set_it_t *self = MP_OBJ_TO_PTR(self_in);
size_t max = self->set->set.alloc;
mp_set_t *set = &self->set->set;
for (size_t i = self->cur; i < max; i++) {
if (mp_set_slot_is_filled(set, i)) {
self->cur = i + 1;
return set->table[i];
}
}
return MP_OBJ_STOP_ITERATION;
}
STATIC mp_obj_t set_getiter(mp_obj_t set_in, mp_obj_iter_buf_t *iter_buf) {
assert(sizeof(mp_obj_set_it_t) <= sizeof(mp_obj_iter_buf_t));
mp_obj_set_it_t *o = (mp_obj_set_it_t *)iter_buf;
o->base.type = &mp_type_polymorph_iter;
o->iternext = set_it_iternext;
o->set = (mp_obj_set_t *)MP_OBJ_TO_PTR(set_in);
o->cur = 0;
return MP_OBJ_FROM_PTR(o);
}
/******************************************************************************/
/* set methods */
STATIC mp_obj_t set_add(mp_obj_t self_in, mp_obj_t item) {
check_set(self_in);
mp_obj_set_t *self = MP_OBJ_TO_PTR(self_in);
mp_set_lookup(&self->set, item, MP_MAP_LOOKUP_ADD_IF_NOT_FOUND);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(set_add_obj, set_add);
STATIC mp_obj_t set_clear(mp_obj_t self_in) {
check_set(self_in);
mp_obj_set_t *self = MP_OBJ_TO_PTR(self_in);
mp_set_clear(&self->set);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(set_clear_obj, set_clear);
STATIC mp_obj_t set_copy(mp_obj_t self_in) {
check_set_or_frozenset(self_in);
mp_obj_set_t *self = MP_OBJ_TO_PTR(self_in);
mp_obj_set_t *other = m_new_obj(mp_obj_set_t);
other->base.type = self->base.type;
mp_set_init(&other->set, self->set.alloc);
other->set.used = self->set.used;
memcpy(other->set.table, self->set.table, self->set.alloc * sizeof(mp_obj_t));
return MP_OBJ_FROM_PTR(other);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(set_copy_obj, set_copy);
STATIC mp_obj_t set_discard(mp_obj_t self_in, mp_obj_t item) {
check_set(self_in);
mp_obj_set_t *self = MP_OBJ_TO_PTR(self_in);
mp_set_lookup(&self->set, item, MP_MAP_LOOKUP_REMOVE_IF_FOUND);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(set_discard_obj, set_discard);
STATIC mp_obj_t set_diff_int(size_t n_args, const mp_obj_t *args, bool update) {
mp_obj_t self;
if (update) {
check_set(args[0]);
self = args[0];
} else {
self = set_copy(args[0]);
}
for (size_t i = 1; i < n_args; i++) {
mp_obj_t other = args[i];
if (self == other) {
set_clear(self);
} else {
mp_set_t *self_set = &((mp_obj_set_t *)MP_OBJ_TO_PTR(self))->set;
mp_obj_t iter = mp_getiter(other, NULL);
mp_obj_t next;
while ((next = mp_iternext(iter)) != MP_OBJ_STOP_ITERATION) {
mp_set_lookup(self_set, next, MP_MAP_LOOKUP_REMOVE_IF_FOUND);
}
}
}
return self;
}
STATIC mp_obj_t set_diff(size_t n_args, const mp_obj_t *args) {
return set_diff_int(n_args, args, false);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(set_diff_obj, 1, set_diff);
STATIC mp_obj_t set_diff_update(size_t n_args, const mp_obj_t *args) {
set_diff_int(n_args, args, true);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(set_diff_update_obj, 1, set_diff_update);
STATIC mp_obj_t set_intersect_int(mp_obj_t self_in, mp_obj_t other, bool update) {
if (update) {
check_set(self_in);
} else {
check_set_or_frozenset(self_in);
}
if (self_in == other) {
return update ? mp_const_none : set_copy(self_in);
}
mp_obj_set_t *self = MP_OBJ_TO_PTR(self_in);
mp_obj_set_t *out = MP_OBJ_TO_PTR(mp_obj_new_set(0, NULL));
mp_obj_t iter = mp_getiter(other, NULL);
mp_obj_t next;
while ((next = mp_iternext(iter)) != MP_OBJ_STOP_ITERATION) {
if (mp_set_lookup(&self->set, next, MP_MAP_LOOKUP)) {
set_add(MP_OBJ_FROM_PTR(out), next);
}
}
if (update) {
m_del(mp_obj_t, self->set.table, self->set.alloc);
self->set.alloc = out->set.alloc;
self->set.used = out->set.used;
self->set.table = out->set.table;
}
return update ? mp_const_none : MP_OBJ_FROM_PTR(out);
}
STATIC mp_obj_t set_intersect(mp_obj_t self_in, mp_obj_t other) {
return set_intersect_int(self_in, other, false);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(set_intersect_obj, set_intersect);
STATIC mp_obj_t set_intersect_update(mp_obj_t self_in, mp_obj_t other) {
return set_intersect_int(self_in, other, true);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(set_intersect_update_obj, set_intersect_update);
STATIC mp_obj_t set_isdisjoint(mp_obj_t self_in, mp_obj_t other) {
check_set_or_frozenset(self_in);
mp_obj_set_t *self = MP_OBJ_TO_PTR(self_in);
mp_obj_iter_buf_t iter_buf;
mp_obj_t iter = mp_getiter(other, &iter_buf);
mp_obj_t next;
while ((next = mp_iternext(iter)) != MP_OBJ_STOP_ITERATION) {
if (mp_set_lookup(&self->set, next, MP_MAP_LOOKUP)) {
return mp_const_false;
}
}
return mp_const_true;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(set_isdisjoint_obj, set_isdisjoint);
STATIC mp_obj_t set_issubset_internal(mp_obj_t self_in, mp_obj_t other_in, bool proper) {
mp_obj_set_t *self;
bool cleanup_self = false;
if (is_set_or_frozenset(self_in)) {
self = MP_OBJ_TO_PTR(self_in);
} else {
self = MP_OBJ_TO_PTR(set_make_new(&mp_type_set, 1, 0, &self_in));
cleanup_self = true;
}
mp_obj_set_t *other;
bool cleanup_other = false;
if (is_set_or_frozenset(other_in)) {
other = MP_OBJ_TO_PTR(other_in);
} else {
other = MP_OBJ_TO_PTR(set_make_new(&mp_type_set, 1, 0, &other_in));
cleanup_other = true;
}
mp_obj_t out = mp_const_true;
if (proper && self->set.used == other->set.used) {
out = mp_const_false;
} else {
mp_obj_iter_buf_t iter_buf;
mp_obj_t iter = set_getiter(MP_OBJ_FROM_PTR(self), &iter_buf);
mp_obj_t next;
while ((next = set_it_iternext(iter)) != MP_OBJ_STOP_ITERATION) {
if (!mp_set_lookup(&other->set, next, MP_MAP_LOOKUP)) {
out = mp_const_false;
break;
}
}
}
// TODO: Should free objects altogether
if (cleanup_self) {
set_clear(MP_OBJ_FROM_PTR(self));
}
if (cleanup_other) {
set_clear(MP_OBJ_FROM_PTR(other));
}
return out;
}
STATIC mp_obj_t set_issubset(mp_obj_t self_in, mp_obj_t other_in) {
return set_issubset_internal(self_in, other_in, false);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(set_issubset_obj, set_issubset);
STATIC mp_obj_t set_issubset_proper(mp_obj_t self_in, mp_obj_t other_in) {
return set_issubset_internal(self_in, other_in, true);
}
STATIC mp_obj_t set_issuperset(mp_obj_t self_in, mp_obj_t other_in) {
return set_issubset_internal(other_in, self_in, false);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(set_issuperset_obj, set_issuperset);
STATIC mp_obj_t set_issuperset_proper(mp_obj_t self_in, mp_obj_t other_in) {
return set_issubset_internal(other_in, self_in, true);
}
STATIC mp_obj_t set_equal(mp_obj_t self_in, mp_obj_t other_in) {
assert(is_set_or_frozenset(other_in));
check_set_or_frozenset(self_in);
mp_obj_set_t *self = MP_OBJ_TO_PTR(self_in);
mp_obj_set_t *other = MP_OBJ_TO_PTR(other_in);
if (self->set.used != other->set.used) {
return mp_const_false;
}
return set_issubset(self_in, other_in);
}
STATIC mp_obj_t set_pop(mp_obj_t self_in) {
check_set(self_in);
mp_obj_set_t *self = MP_OBJ_TO_PTR(self_in);
mp_obj_t obj = mp_set_remove_first(&self->set);
if (obj == MP_OBJ_NULL) {
mp_raise_msg(&mp_type_KeyError, MP_ERROR_TEXT("pop from an empty set"));
}
return obj;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(set_pop_obj, set_pop);
STATIC mp_obj_t set_remove(mp_obj_t self_in, mp_obj_t item) {
check_set(self_in);
mp_obj_set_t *self = MP_OBJ_TO_PTR(self_in);
if (mp_set_lookup(&self->set, item, MP_MAP_LOOKUP_REMOVE_IF_FOUND) == MP_OBJ_NULL) {
mp_raise_type_arg(&mp_type_KeyError, item);
}
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(set_remove_obj, set_remove);
STATIC mp_obj_t set_symmetric_difference_update(mp_obj_t self_in, mp_obj_t other_in) {
check_set_or_frozenset(self_in); // can be frozenset due to call from set_symmetric_difference
mp_obj_set_t *self = MP_OBJ_TO_PTR(self_in);
mp_obj_t iter = mp_getiter(other_in, NULL);
mp_obj_t next;
while ((next = mp_iternext(iter)) != MP_OBJ_STOP_ITERATION) {
mp_set_lookup(&self->set, next, MP_MAP_LOOKUP_ADD_IF_NOT_FOUND_OR_REMOVE_IF_FOUND);
}
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(set_symmetric_difference_update_obj, set_symmetric_difference_update);
STATIC mp_obj_t set_symmetric_difference(mp_obj_t self_in, mp_obj_t other_in) {
mp_obj_t self_out = set_copy(self_in);
set_symmetric_difference_update(self_out, other_in);
return self_out;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(set_symmetric_difference_obj, set_symmetric_difference);
STATIC void set_update_int(mp_obj_set_t *self, mp_obj_t other_in) {
mp_obj_t iter = mp_getiter(other_in, NULL);
mp_obj_t next;
while ((next = mp_iternext(iter)) != MP_OBJ_STOP_ITERATION) {
mp_set_lookup(&self->set, next, MP_MAP_LOOKUP_ADD_IF_NOT_FOUND);
}
}
STATIC mp_obj_t set_update(size_t n_args, const mp_obj_t *args) {
check_set(args[0]);
for (size_t i = 1; i < n_args; i++) {
set_update_int(MP_OBJ_TO_PTR(args[0]), args[i]);
}
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(set_update_obj, 1, set_update);
STATIC mp_obj_t set_union(mp_obj_t self_in, mp_obj_t other_in) {
check_set_or_frozenset(self_in);
mp_obj_t self = set_copy(self_in);
set_update_int(MP_OBJ_TO_PTR(self), other_in);
return self;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(set_union_obj, set_union);
STATIC mp_obj_t set_unary_op(mp_unary_op_t op, mp_obj_t self_in) {
mp_obj_set_t *self = MP_OBJ_TO_PTR(self_in);
switch (op) {
case MP_UNARY_OP_BOOL:
return mp_obj_new_bool(self->set.used != 0);
case MP_UNARY_OP_LEN:
return MP_OBJ_NEW_SMALL_INT(self->set.used);
#if MICROPY_PY_BUILTINS_FROZENSET
case MP_UNARY_OP_HASH:
if (mp_obj_is_type(self_in, &mp_type_frozenset)) {
// start hash with unique value
mp_int_t hash = (mp_int_t)(uintptr_t)&mp_type_frozenset;
size_t max = self->set.alloc;
mp_set_t *set = &self->set;
for (size_t i = 0; i < max; i++) {
if (mp_set_slot_is_filled(set, i)) {
hash += MP_OBJ_SMALL_INT_VALUE(mp_unary_op(MP_UNARY_OP_HASH, set->table[i]));
}
}
return MP_OBJ_NEW_SMALL_INT(hash);
}
MP_FALLTHROUGH
#endif
default:
return MP_OBJ_NULL; // op not supported
}
}
STATIC mp_obj_t set_binary_op(mp_binary_op_t op, mp_obj_t lhs, mp_obj_t rhs) {
mp_obj_t args[] = {lhs, rhs};
#if MICROPY_PY_BUILTINS_FROZENSET
bool update = mp_obj_is_type(lhs, &mp_type_set);
#else
bool update = true;
#endif
if (op != MP_BINARY_OP_CONTAINS && !is_set_or_frozenset(rhs)) {
// For all ops except containment the RHS must be a set/frozenset
return MP_OBJ_NULL;
}
switch (op) {
case MP_BINARY_OP_OR:
return set_union(lhs, rhs);
case MP_BINARY_OP_XOR:
return set_symmetric_difference(lhs, rhs);
case MP_BINARY_OP_AND:
return set_intersect(lhs, rhs);
case MP_BINARY_OP_SUBTRACT:
return set_diff(2, args);
case MP_BINARY_OP_INPLACE_OR:
if (update) {
set_update(2, args);
return lhs;
} else {
return set_union(lhs, rhs);
}
case MP_BINARY_OP_INPLACE_XOR:
if (update) {
set_symmetric_difference_update(lhs, rhs);
return lhs;
} else {
return set_symmetric_difference(lhs, rhs);
}
case MP_BINARY_OP_INPLACE_AND:
rhs = set_intersect_int(lhs, rhs, update);
if (update) {
return lhs;
} else {
return rhs;
}
case MP_BINARY_OP_INPLACE_SUBTRACT:
return set_diff_int(2, args, update);
case MP_BINARY_OP_LESS:
return set_issubset_proper(lhs, rhs);
case MP_BINARY_OP_MORE:
return set_issuperset_proper(lhs, rhs);
case MP_BINARY_OP_EQUAL:
return set_equal(lhs, rhs);
case MP_BINARY_OP_LESS_EQUAL:
return set_issubset(lhs, rhs);
case MP_BINARY_OP_MORE_EQUAL:
return set_issuperset(lhs, rhs);
case MP_BINARY_OP_CONTAINS: {
mp_obj_set_t *o = MP_OBJ_TO_PTR(lhs);
mp_obj_t elem = mp_set_lookup(&o->set, rhs, MP_MAP_LOOKUP);
return mp_obj_new_bool(elem != MP_OBJ_NULL);
}
default:
return MP_OBJ_NULL; // op not supported
}
}
/******************************************************************************/
/* set constructors & public C API */
STATIC const mp_rom_map_elem_t set_locals_dict_table[] = {
{ MP_ROM_QSTR(MP_QSTR_add), MP_ROM_PTR(&set_add_obj) },
{ MP_ROM_QSTR(MP_QSTR_clear), MP_ROM_PTR(&set_clear_obj) },
{ MP_ROM_QSTR(MP_QSTR_copy), MP_ROM_PTR(&set_copy_obj) },
{ MP_ROM_QSTR(MP_QSTR_discard), MP_ROM_PTR(&set_discard_obj) },
{ MP_ROM_QSTR(MP_QSTR_difference), MP_ROM_PTR(&set_diff_obj) },
{ MP_ROM_QSTR(MP_QSTR_difference_update), MP_ROM_PTR(&set_diff_update_obj) },
{ MP_ROM_QSTR(MP_QSTR_intersection), MP_ROM_PTR(&set_intersect_obj) },
{ MP_ROM_QSTR(MP_QSTR_intersection_update), MP_ROM_PTR(&set_intersect_update_obj) },
{ MP_ROM_QSTR(MP_QSTR_isdisjoint), MP_ROM_PTR(&set_isdisjoint_obj) },
{ MP_ROM_QSTR(MP_QSTR_issubset), MP_ROM_PTR(&set_issubset_obj) },
{ MP_ROM_QSTR(MP_QSTR_issuperset), MP_ROM_PTR(&set_issuperset_obj) },
{ MP_ROM_QSTR(MP_QSTR_pop), MP_ROM_PTR(&set_pop_obj) },
{ MP_ROM_QSTR(MP_QSTR_remove), MP_ROM_PTR(&set_remove_obj) },
{ MP_ROM_QSTR(MP_QSTR_symmetric_difference), MP_ROM_PTR(&set_symmetric_difference_obj) },
{ MP_ROM_QSTR(MP_QSTR_symmetric_difference_update), MP_ROM_PTR(&set_symmetric_difference_update_obj) },
{ MP_ROM_QSTR(MP_QSTR_union), MP_ROM_PTR(&set_union_obj) },
{ MP_ROM_QSTR(MP_QSTR_update), MP_ROM_PTR(&set_update_obj) },
{ MP_ROM_QSTR(MP_QSTR___contains__), MP_ROM_PTR(&mp_op_contains_obj) },
};
STATIC MP_DEFINE_CONST_DICT(set_locals_dict, set_locals_dict_table);
const mp_obj_type_t mp_type_set = {
{ &mp_type_type },
.name = MP_QSTR_set,
.print = set_print,
.make_new = set_make_new,
.unary_op = set_unary_op,
.binary_op = set_binary_op,
.getiter = set_getiter,
.locals_dict = (mp_obj_dict_t *)&set_locals_dict,
};
#if MICROPY_PY_BUILTINS_FROZENSET
STATIC const mp_rom_map_elem_t frozenset_locals_dict_table[] = {
{ MP_ROM_QSTR(MP_QSTR_copy), MP_ROM_PTR(&set_copy_obj) },
{ MP_ROM_QSTR(MP_QSTR_difference), MP_ROM_PTR(&set_diff_obj) },
{ MP_ROM_QSTR(MP_QSTR_intersection), MP_ROM_PTR(&set_intersect_obj) },
{ MP_ROM_QSTR(MP_QSTR_isdisjoint), MP_ROM_PTR(&set_isdisjoint_obj) },
{ MP_ROM_QSTR(MP_QSTR_issubset), MP_ROM_PTR(&set_issubset_obj) },
{ MP_ROM_QSTR(MP_QSTR_issuperset), MP_ROM_PTR(&set_issuperset_obj) },
{ MP_ROM_QSTR(MP_QSTR_symmetric_difference), MP_ROM_PTR(&set_symmetric_difference_obj) },
{ MP_ROM_QSTR(MP_QSTR_union), MP_ROM_PTR(&set_union_obj) },
{ MP_ROM_QSTR(MP_QSTR___contains__), MP_ROM_PTR(&mp_op_contains_obj) },
};
STATIC MP_DEFINE_CONST_DICT(frozenset_locals_dict, frozenset_locals_dict_table);
const mp_obj_type_t mp_type_frozenset = {
{ &mp_type_type },
.flags = MP_TYPE_FLAG_EQ_CHECKS_OTHER_TYPE,
.name = MP_QSTR_frozenset,
.print = set_print,
.make_new = set_make_new,
.unary_op = set_unary_op,
.binary_op = set_binary_op,
.getiter = set_getiter,
.locals_dict = (mp_obj_dict_t *)&frozenset_locals_dict,
};
#endif
mp_obj_t mp_obj_new_set(size_t n_args, mp_obj_t *items) {
mp_obj_set_t *o = m_new_obj(mp_obj_set_t);
o->base.type = &mp_type_set;
mp_set_init(&o->set, n_args);
for (size_t i = 0; i < n_args; i++) {
mp_set_lookup(&o->set, items[i], MP_MAP_LOOKUP_ADD_IF_NOT_FOUND);
}
return MP_OBJ_FROM_PTR(o);
}
void mp_obj_set_store(mp_obj_t self_in, mp_obj_t item) {
mp_check_self(mp_obj_is_type(self_in, &mp_type_set));
mp_obj_set_t *self = MP_OBJ_TO_PTR(self_in);
mp_set_lookup(&self->set, item, MP_MAP_LOOKUP_ADD_IF_NOT_FOUND);
}
#endif // MICROPY_PY_BUILTINS_SET
| YifuLiu/AliOS-Things | components/py_engine/engine/py/objset.c | C | apache-2.0 | 21,364 |
/*
* 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 <stdlib.h>
#include <assert.h>
#include "py/obj.h"
/******************************************************************************/
/* singleton objects defined by Python */
typedef struct _mp_obj_singleton_t {
mp_obj_base_t base;
qstr name;
} mp_obj_singleton_t;
STATIC void singleton_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
(void)kind;
mp_obj_singleton_t *self = MP_OBJ_TO_PTR(self_in);
mp_printf(print, "%q", self->name);
}
const mp_obj_type_t mp_type_singleton = {
{ &mp_type_type },
.name = MP_QSTR_,
.print = singleton_print,
.unary_op = mp_generic_unary_op,
};
const mp_obj_singleton_t mp_const_ellipsis_obj = {{&mp_type_singleton}, MP_QSTR_Ellipsis};
#if MICROPY_PY_BUILTINS_NOTIMPLEMENTED
const mp_obj_singleton_t mp_const_notimplemented_obj = {{&mp_type_singleton}, MP_QSTR_NotImplemented};
#endif
| YifuLiu/AliOS-Things | components/py_engine/engine/py/objsingleton.c | C | apache-2.0 | 2,163 |
/*
* 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 <stdlib.h>
#include <assert.h>
#include "py/runtime.h"
/******************************************************************************/
/* slice object */
#if MICROPY_PY_BUILTINS_SLICE
STATIC void slice_print(const mp_print_t *print, mp_obj_t o_in, mp_print_kind_t kind) {
(void)kind;
mp_obj_slice_t *o = MP_OBJ_TO_PTR(o_in);
mp_print_str(print, "slice(");
mp_obj_print_helper(print, o->start, PRINT_REPR);
mp_print_str(print, ", ");
mp_obj_print_helper(print, o->stop, PRINT_REPR);
mp_print_str(print, ", ");
mp_obj_print_helper(print, o->step, PRINT_REPR);
mp_print_str(print, ")");
}
#if MICROPY_PY_BUILTINS_SLICE_INDICES
STATIC mp_obj_t slice_indices(mp_obj_t self_in, mp_obj_t length_obj) {
mp_int_t length = mp_obj_int_get_checked(length_obj);
mp_bound_slice_t bound_indices;
mp_obj_slice_indices(self_in, length, &bound_indices);
mp_obj_t results[3] = {
MP_OBJ_NEW_SMALL_INT(bound_indices.start),
MP_OBJ_NEW_SMALL_INT(bound_indices.stop),
MP_OBJ_NEW_SMALL_INT(bound_indices.step),
};
return mp_obj_new_tuple(3, results);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(slice_indices_obj, slice_indices);
#endif
#if MICROPY_PY_BUILTINS_SLICE_ATTRS
STATIC void slice_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) {
if (dest[0] != MP_OBJ_NULL) {
// not load attribute
return;
}
mp_obj_slice_t *self = MP_OBJ_TO_PTR(self_in);
if (attr == MP_QSTR_start) {
dest[0] = self->start;
} else if (attr == MP_QSTR_stop) {
dest[0] = self->stop;
} else if (attr == MP_QSTR_step) {
dest[0] = self->step;
#if MICROPY_PY_BUILTINS_SLICE_INDICES
} else if (attr == MP_QSTR_indices) {
dest[0] = MP_OBJ_FROM_PTR(&slice_indices_obj);
dest[1] = self_in;
#endif
}
}
#endif
#if MICROPY_PY_BUILTINS_SLICE_INDICES && !MICROPY_PY_BUILTINS_SLICE_ATTRS
STATIC const mp_rom_map_elem_t slice_locals_dict_table[] = {
{ MP_ROM_QSTR(MP_QSTR_indices), MP_ROM_PTR(&slice_indices_obj) },
};
STATIC MP_DEFINE_CONST_DICT(slice_locals_dict, slice_locals_dict_table);
#endif
const mp_obj_type_t mp_type_slice = {
{ &mp_type_type },
.name = MP_QSTR_slice,
.print = slice_print,
#if MICROPY_PY_BUILTINS_SLICE_ATTRS
.attr = slice_attr,
#elif MICROPY_PY_BUILTINS_SLICE_INDICES
.locals_dict = (mp_obj_dict_t *)&slice_locals_dict,
#endif
};
mp_obj_t mp_obj_new_slice(mp_obj_t ostart, mp_obj_t ostop, mp_obj_t ostep) {
mp_obj_slice_t *o = m_new_obj(mp_obj_slice_t);
o->base.type = &mp_type_slice;
o->start = ostart;
o->stop = ostop;
o->step = ostep;
return MP_OBJ_FROM_PTR(o);
}
// Return the real index and step values for a slice when applied to a sequence of
// the given length, resolving missing components, negative values and values off
// the end of the sequence.
void mp_obj_slice_indices(mp_obj_t self_in, mp_int_t length, mp_bound_slice_t *result) {
mp_obj_slice_t *self = MP_OBJ_TO_PTR(self_in);
mp_int_t start, stop, step;
if (self->step == mp_const_none) {
step = 1;
} else {
step = mp_obj_get_int(self->step);
if (step == 0) {
mp_raise_ValueError(MP_ERROR_TEXT("slice step can't be zero"));
}
}
if (step > 0) {
// Positive step
if (self->start == mp_const_none) {
start = 0;
} else {
start = mp_obj_get_int(self->start);
if (start < 0) {
start += length;
}
start = MIN(length, MAX(start, 0));
}
if (self->stop == mp_const_none) {
stop = length;
} else {
stop = mp_obj_get_int(self->stop);
if (stop < 0) {
stop += length;
}
stop = MIN(length, MAX(stop, 0));
}
} else {
// Negative step
if (self->start == mp_const_none) {
start = length - 1;
} else {
start = mp_obj_get_int(self->start);
if (start < 0) {
start += length;
}
start = MIN(length - 1, MAX(start, -1));
}
if (self->stop == mp_const_none) {
stop = -1;
} else {
stop = mp_obj_get_int(self->stop);
if (stop < 0) {
stop += length;
}
stop = MIN(length - 1, MAX(stop, -1));
}
}
result->start = start;
result->stop = stop;
result->step = step;
}
#endif
| YifuLiu/AliOS-Things | components/py_engine/engine/py/objslice.c | C | apache-2.0 | 5,835 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2013, 2014 Damien P. George
* Copyright (c) 2014-2018 Paul Sokolovsky
*
* 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 <string.h>
#include <assert.h>
#include "py/unicode.h"
#include "py/objstr.h"
#include "py/objlist.h"
#include "py/runtime.h"
#include "py/stackctrl.h"
#if MICROPY_PY_BUILTINS_STR_OP_MODULO
STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, size_t n_args, const mp_obj_t *args, mp_obj_t dict);
#endif
STATIC mp_obj_t mp_obj_new_bytes_iterator(mp_obj_t str, mp_obj_iter_buf_t *iter_buf);
STATIC NORETURN void bad_implicit_conversion(mp_obj_t self_in);
/******************************************************************************/
/* str */
void mp_str_print_quoted(const mp_print_t *print, const byte *str_data, size_t str_len, bool is_bytes) {
// this escapes characters, but it will be very slow to print (calling print many times)
bool has_single_quote = false;
bool has_double_quote = false;
for (const byte *s = str_data, *top = str_data + str_len; !has_double_quote && s < top; s++) {
if (*s == '\'') {
has_single_quote = true;
} else if (*s == '"') {
has_double_quote = true;
}
}
int quote_char = '\'';
if (has_single_quote && !has_double_quote) {
quote_char = '"';
}
mp_printf(print, "%c", quote_char);
for (const byte *s = str_data, *top = str_data + str_len; s < top; s++) {
if (*s == quote_char) {
mp_printf(print, "\\%c", quote_char);
} else if (*s == '\\') {
mp_print_str(print, "\\\\");
} else if (*s >= 0x20 && *s != 0x7f && (!is_bytes || *s < 0x80)) {
// In strings, anything which is not ascii control character
// is printed as is, this includes characters in range 0x80-0xff
// (which can be non-Latin letters, etc.)
mp_printf(print, "%c", *s);
} else if (*s == '\n') {
mp_print_str(print, "\\n");
} else if (*s == '\r') {
mp_print_str(print, "\\r");
} else if (*s == '\t') {
mp_print_str(print, "\\t");
} else {
mp_printf(print, "\\x%02x", *s);
}
}
mp_printf(print, "%c", quote_char);
}
#if MICROPY_PY_UJSON
void mp_str_print_json(const mp_print_t *print, const byte *str_data, size_t str_len) {
// for JSON spec, see http://www.ietf.org/rfc/rfc4627.txt
// if we are given a valid utf8-encoded string, we will print it in a JSON-conforming way
mp_print_str(print, "\"");
for (const byte *s = str_data, *top = str_data + str_len; s < top; s++) {
if (*s == '"' || *s == '\\') {
mp_printf(print, "\\%c", *s);
} else if (*s >= 32) {
// this will handle normal and utf-8 encoded chars
mp_printf(print, "%c", *s);
} else if (*s == '\n') {
mp_print_str(print, "\\n");
} else if (*s == '\r') {
mp_print_str(print, "\\r");
} else if (*s == '\t') {
mp_print_str(print, "\\t");
} else {
// this will handle control chars
mp_printf(print, "\\u%04x", *s);
}
}
mp_print_str(print, "\"");
}
#endif
STATIC void str_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
GET_STR_DATA_LEN(self_in, str_data, str_len);
#if MICROPY_PY_UJSON
if (kind == PRINT_JSON) {
mp_str_print_json(print, str_data, str_len);
return;
}
#endif
#if !MICROPY_PY_BUILTINS_STR_UNICODE
bool is_bytes = mp_obj_is_type(self_in, &mp_type_bytes);
#else
bool is_bytes = true;
#endif
if (kind == PRINT_RAW || (!MICROPY_PY_BUILTINS_STR_UNICODE && kind == PRINT_STR && !is_bytes)) {
print->print_strn(print->data, (const char *)str_data, str_len);
} else {
if (is_bytes) {
print->print_strn(print->data, "b", 1);
}
mp_str_print_quoted(print, str_data, str_len, is_bytes);
}
}
mp_obj_t mp_obj_str_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
#if MICROPY_CPYTHON_COMPAT
if (n_kw != 0) {
mp_arg_error_unimpl_kw();
}
#endif
mp_arg_check_num(n_args, n_kw, 0, 3, false);
switch (n_args) {
case 0:
return MP_OBJ_NEW_QSTR(MP_QSTR_);
case 1: {
vstr_t vstr;
mp_print_t print;
vstr_init_print(&vstr, 16, &print);
mp_obj_print_helper(&print, args[0], PRINT_STR);
return mp_obj_new_str_from_vstr(type, &vstr);
}
default: // 2 or 3 args
// TODO: validate 2nd/3rd args
if (mp_obj_is_type(args[0], &mp_type_bytes)) {
GET_STR_DATA_LEN(args[0], str_data, str_len);
GET_STR_HASH(args[0], str_hash);
if (str_hash == 0) {
str_hash = qstr_compute_hash(str_data, str_len);
}
#if MICROPY_PY_BUILTINS_STR_UNICODE_CHECK
if (!utf8_check(str_data, str_len)) {
mp_raise_msg(&mp_type_UnicodeError, NULL);
}
#endif
// Check if a qstr with this data already exists
qstr q = qstr_find_strn((const char *)str_data, str_len);
if (q != MP_QSTRnull) {
return MP_OBJ_NEW_QSTR(q);
}
mp_obj_str_t *o = MP_OBJ_TO_PTR(mp_obj_new_str_copy(type, NULL, str_len));
o->data = str_data;
o->hash = str_hash;
return MP_OBJ_FROM_PTR(o);
} else {
mp_buffer_info_t bufinfo;
mp_get_buffer_raise(args[0], &bufinfo, MP_BUFFER_READ);
#if MICROPY_PY_BUILTINS_STR_UNICODE_CHECK
if (!utf8_check(bufinfo.buf, bufinfo.len)) {
mp_raise_msg(&mp_type_UnicodeError, NULL);
}
#endif
return mp_obj_new_str(bufinfo.buf, bufinfo.len);
}
}
}
STATIC mp_obj_t bytes_make_new(const mp_obj_type_t *type_in, size_t n_args, size_t n_kw, const mp_obj_t *args) {
(void)type_in;
#if MICROPY_CPYTHON_COMPAT
if (n_kw != 0) {
mp_arg_error_unimpl_kw();
}
#else
(void)n_kw;
#endif
if (n_args == 0) {
return mp_const_empty_bytes;
}
if (mp_obj_is_type(args[0], &mp_type_bytes)) {
return args[0];
}
if (mp_obj_is_str(args[0])) {
if (n_args < 2 || n_args > 3) {
goto wrong_args;
}
GET_STR_DATA_LEN(args[0], str_data, str_len);
GET_STR_HASH(args[0], str_hash);
if (str_hash == 0) {
str_hash = qstr_compute_hash(str_data, str_len);
}
mp_obj_str_t *o = MP_OBJ_TO_PTR(mp_obj_new_str_copy(&mp_type_bytes, NULL, str_len));
o->data = str_data;
o->hash = str_hash;
return MP_OBJ_FROM_PTR(o);
}
if (n_args > 1) {
goto wrong_args;
}
if (mp_obj_is_small_int(args[0])) {
mp_int_t len = MP_OBJ_SMALL_INT_VALUE(args[0]);
if (len < 0) {
mp_raise_ValueError(NULL);
}
vstr_t vstr;
vstr_init_len(&vstr, len);
memset(vstr.buf, 0, len);
return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
}
// check if argument has the buffer protocol
mp_buffer_info_t bufinfo;
if (mp_get_buffer(args[0], &bufinfo, MP_BUFFER_READ)) {
return mp_obj_new_bytes(bufinfo.buf, bufinfo.len);
}
vstr_t vstr;
// Try to create array of exact len if initializer len is known
mp_obj_t len_in = mp_obj_len_maybe(args[0]);
if (len_in == MP_OBJ_NULL) {
vstr_init(&vstr, 16);
} else {
mp_int_t len = MP_OBJ_SMALL_INT_VALUE(len_in);
vstr_init(&vstr, len);
}
mp_obj_iter_buf_t iter_buf;
mp_obj_t iterable = mp_getiter(args[0], &iter_buf);
mp_obj_t item;
while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
mp_int_t val = mp_obj_get_int(item);
#if MICROPY_FULL_CHECKS
if (val < 0 || val > 255) {
mp_raise_ValueError(MP_ERROR_TEXT("bytes value out of range"));
}
#endif
vstr_add_byte(&vstr, val);
}
return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
wrong_args:
mp_raise_TypeError(MP_ERROR_TEXT("wrong number of arguments"));
}
// like strstr but with specified length and allows \0 bytes
// TODO replace with something more efficient/standard
const byte *find_subbytes(const byte *haystack, size_t hlen, const byte *needle, size_t nlen, int direction) {
if (hlen >= nlen) {
size_t str_index, str_index_end;
if (direction > 0) {
str_index = 0;
str_index_end = hlen - nlen;
} else {
str_index = hlen - nlen;
str_index_end = 0;
}
for (;;) {
if (memcmp(&haystack[str_index], needle, nlen) == 0) {
// found
return haystack + str_index;
}
if (str_index == str_index_end) {
// not found
break;
}
str_index += direction;
}
}
return NULL;
}
// Note: this function is used to check if an object is a str or bytes, which
// works because both those types use it as their binary_op method. Revisit
// mp_obj_is_str_or_bytes if this fact changes.
mp_obj_t mp_obj_str_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_in) {
// check for modulo
if (op == MP_BINARY_OP_MODULO) {
#if MICROPY_PY_BUILTINS_STR_OP_MODULO
mp_obj_t *args = &rhs_in;
size_t n_args = 1;
mp_obj_t dict = MP_OBJ_NULL;
if (mp_obj_is_type(rhs_in, &mp_type_tuple)) {
// TODO: Support tuple subclasses?
mp_obj_tuple_get(rhs_in, &n_args, &args);
} else if (mp_obj_is_type(rhs_in, &mp_type_dict)) {
dict = rhs_in;
}
return str_modulo_format(lhs_in, n_args, args, dict);
#else
return MP_OBJ_NULL;
#endif
}
// from now on we need lhs type and data, so extract them
const mp_obj_type_t *lhs_type = mp_obj_get_type(lhs_in);
GET_STR_DATA_LEN(lhs_in, lhs_data, lhs_len);
// check for multiply
if (op == MP_BINARY_OP_MULTIPLY) {
mp_int_t n;
if (!mp_obj_get_int_maybe(rhs_in, &n)) {
return MP_OBJ_NULL; // op not supported
}
if (n <= 0) {
if (lhs_type == &mp_type_str) {
return MP_OBJ_NEW_QSTR(MP_QSTR_); // empty str
} else {
return mp_const_empty_bytes;
}
}
vstr_t vstr;
vstr_init_len(&vstr, lhs_len * n);
mp_seq_multiply(lhs_data, sizeof(*lhs_data), lhs_len, n, vstr.buf);
return mp_obj_new_str_from_vstr(lhs_type, &vstr);
}
// From now on all operations allow:
// - str with str
// - bytes with bytes
// - bytes with bytearray
// - bytes with array.array
// To do this efficiently we use the buffer protocol to extract the raw
// data for the rhs, but only if the lhs is a bytes object.
//
// NOTE: CPython does not allow comparison between bytes ard array.array
// (even if the array is of type 'b'), even though it allows addition of
// such types. We are not compatible with this (we do allow comparison
// of bytes with anything that has the buffer protocol). It would be
// easy to "fix" this with a bit of extra logic below, but it costs code
// size and execution time so we don't.
const byte *rhs_data;
size_t rhs_len;
if (lhs_type == mp_obj_get_type(rhs_in)) {
GET_STR_DATA_LEN(rhs_in, rhs_data_, rhs_len_);
rhs_data = rhs_data_;
rhs_len = rhs_len_;
} else if (lhs_type == &mp_type_bytes) {
mp_buffer_info_t bufinfo;
if (!mp_get_buffer(rhs_in, &bufinfo, MP_BUFFER_READ)) {
return MP_OBJ_NULL; // op not supported
}
rhs_data = bufinfo.buf;
rhs_len = bufinfo.len;
} else {
// LHS is str and RHS has an incompatible type
// (except if operation is EQUAL, but that's handled by mp_obj_equal)
bad_implicit_conversion(rhs_in);
}
switch (op) {
case MP_BINARY_OP_ADD:
case MP_BINARY_OP_INPLACE_ADD: {
if (lhs_len == 0 && mp_obj_get_type(rhs_in) == lhs_type) {
return rhs_in;
}
if (rhs_len == 0) {
return lhs_in;
}
vstr_t vstr;
vstr_init_len(&vstr, lhs_len + rhs_len);
memcpy(vstr.buf, lhs_data, lhs_len);
memcpy(vstr.buf + lhs_len, rhs_data, rhs_len);
return mp_obj_new_str_from_vstr(lhs_type, &vstr);
}
case MP_BINARY_OP_CONTAINS:
return mp_obj_new_bool(find_subbytes(lhs_data, lhs_len, rhs_data, rhs_len, 1) != NULL);
// case MP_BINARY_OP_NOT_EQUAL: // This is never passed here
case MP_BINARY_OP_EQUAL: // This will be passed only for bytes, str is dealt with in mp_obj_equal()
case MP_BINARY_OP_LESS:
case MP_BINARY_OP_LESS_EQUAL:
case MP_BINARY_OP_MORE:
case MP_BINARY_OP_MORE_EQUAL:
return mp_obj_new_bool(mp_seq_cmp_bytes(op, lhs_data, lhs_len, rhs_data, rhs_len));
default:
return MP_OBJ_NULL; // op not supported
}
}
#if !MICROPY_PY_BUILTINS_STR_UNICODE
// objstrunicode defines own version
const byte *str_index_to_ptr(const mp_obj_type_t *type, const byte *self_data, size_t self_len,
mp_obj_t index, bool is_slice) {
size_t index_val = mp_get_index(type, self_len, index, is_slice);
return self_data + index_val;
}
#endif
// This is used for both bytes and 8-bit strings. This is not used for unicode strings.
STATIC mp_obj_t bytes_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) {
const mp_obj_type_t *type = mp_obj_get_type(self_in);
GET_STR_DATA_LEN(self_in, self_data, self_len);
if (value == MP_OBJ_SENTINEL) {
// load
#if MICROPY_PY_BUILTINS_SLICE
if (mp_obj_is_type(index, &mp_type_slice)) {
mp_bound_slice_t slice;
if (!mp_seq_get_fast_slice_indexes(self_len, index, &slice)) {
mp_raise_NotImplementedError(MP_ERROR_TEXT("only slices with step=1 (aka None) are supported"));
}
return mp_obj_new_str_of_type(type, self_data + slice.start, slice.stop - slice.start);
}
#endif
size_t index_val = mp_get_index(type, self_len, index, false);
// If we have unicode enabled the type will always be bytes, so take the short cut.
if (MICROPY_PY_BUILTINS_STR_UNICODE || type == &mp_type_bytes) {
return MP_OBJ_NEW_SMALL_INT(self_data[index_val]);
} else {
return mp_obj_new_str_via_qstr((char *)&self_data[index_val], 1);
}
} else {
return MP_OBJ_NULL; // op not supported
}
}
STATIC mp_obj_t str_join(mp_obj_t self_in, mp_obj_t arg) {
mp_check_self(mp_obj_is_str_or_bytes(self_in));
const mp_obj_type_t *self_type = mp_obj_get_type(self_in);
// get separation string
GET_STR_DATA_LEN(self_in, sep_str, sep_len);
// process args
size_t seq_len;
mp_obj_t *seq_items;
if (!mp_obj_is_type(arg, &mp_type_list) && !mp_obj_is_type(arg, &mp_type_tuple)) {
// arg is not a list nor a tuple, try to convert it to a list
// TODO: Try to optimize?
arg = mp_type_list.make_new(&mp_type_list, 1, 0, &arg);
}
mp_obj_get_array(arg, &seq_len, &seq_items);
// count required length
size_t required_len = 0;
for (size_t i = 0; i < seq_len; i++) {
if (mp_obj_get_type(seq_items[i]) != self_type) {
mp_raise_TypeError(
MP_ERROR_TEXT("join expects a list of str/bytes objects consistent with self object"));
}
if (i > 0) {
required_len += sep_len;
}
GET_STR_LEN(seq_items[i], l);
required_len += l;
}
// make joined string
vstr_t vstr;
vstr_init_len(&vstr, required_len);
byte *data = (byte *)vstr.buf;
for (size_t i = 0; i < seq_len; i++) {
if (i > 0) {
memcpy(data, sep_str, sep_len);
data += sep_len;
}
GET_STR_DATA_LEN(seq_items[i], s, l);
memcpy(data, s, l);
data += l;
}
// return joined string
return mp_obj_new_str_from_vstr(self_type, &vstr);
}
MP_DEFINE_CONST_FUN_OBJ_2(str_join_obj, str_join);
mp_obj_t mp_obj_str_split(size_t n_args, const mp_obj_t *args) {
const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
mp_int_t splits = -1;
mp_obj_t sep = mp_const_none;
if (n_args > 1) {
sep = args[1];
if (n_args > 2) {
splits = mp_obj_get_int(args[2]);
}
}
mp_obj_t res = mp_obj_new_list(0, NULL);
GET_STR_DATA_LEN(args[0], s, len);
const byte *top = s + len;
if (sep == mp_const_none) {
// sep not given, so separate on whitespace
// Initial whitespace is not counted as split, so we pre-do it
while (s < top && unichar_isspace(*s)) {
s++;
}
while (s < top && splits != 0) {
const byte *start = s;
while (s < top && !unichar_isspace(*s)) {
s++;
}
mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, s - start));
if (s >= top) {
break;
}
while (s < top && unichar_isspace(*s)) {
s++;
}
if (splits > 0) {
splits--;
}
}
if (s < top) {
mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, s, top - s));
}
} else {
// sep given
if (mp_obj_get_type(sep) != self_type) {
bad_implicit_conversion(sep);
}
size_t sep_len;
const char *sep_str = mp_obj_str_get_data(sep, &sep_len);
if (sep_len == 0) {
mp_raise_ValueError(MP_ERROR_TEXT("empty separator"));
}
for (;;) {
const byte *start = s;
for (;;) {
if (splits == 0 || s + sep_len > top) {
s = top;
break;
} else if (memcmp(s, sep_str, sep_len) == 0) {
break;
}
s++;
}
mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, s - start));
if (s >= top) {
break;
}
s += sep_len;
if (splits > 0) {
splits--;
}
}
}
return res;
}
MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_split_obj, 1, 3, mp_obj_str_split);
#if MICROPY_PY_BUILTINS_STR_SPLITLINES
STATIC mp_obj_t str_splitlines(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
enum { ARG_keepends };
static const mp_arg_t allowed_args[] = {
{ MP_QSTR_keepends, MP_ARG_BOOL, {.u_bool = false} },
};
// parse args
mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
const mp_obj_type_t *self_type = mp_obj_get_type(pos_args[0]);
mp_obj_t res = mp_obj_new_list(0, NULL);
GET_STR_DATA_LEN(pos_args[0], s, len);
const byte *top = s + len;
while (s < top) {
const byte *start = s;
size_t match = 0;
while (s < top) {
if (*s == '\n') {
match = 1;
break;
} else if (*s == '\r') {
if (s[1] == '\n') {
match = 2;
} else {
match = 1;
}
break;
}
s++;
}
size_t sub_len = s - start;
if (args[ARG_keepends].u_bool) {
sub_len += match;
}
mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, sub_len));
s += match;
}
return res;
}
MP_DEFINE_CONST_FUN_OBJ_KW(str_splitlines_obj, 1, str_splitlines);
#endif
STATIC mp_obj_t str_rsplit(size_t n_args, const mp_obj_t *args) {
if (n_args < 3) {
// If we don't have split limit, it doesn't matter from which side
// we split.
return mp_obj_str_split(n_args, args);
}
const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
mp_obj_t sep = args[1];
GET_STR_DATA_LEN(args[0], s, len);
mp_int_t splits = mp_obj_get_int(args[2]);
if (splits < 0) {
// Negative limit means no limit, so delegate to split().
return mp_obj_str_split(n_args, args);
}
mp_int_t org_splits = splits;
// Preallocate list to the max expected # of elements, as we
// will fill it from the end.
mp_obj_list_t *res = MP_OBJ_TO_PTR(mp_obj_new_list(splits + 1, NULL));
mp_int_t idx = splits;
if (sep == mp_const_none) {
mp_raise_NotImplementedError(MP_ERROR_TEXT("rsplit(None,n)"));
} else {
size_t sep_len;
const char *sep_str = mp_obj_str_get_data(sep, &sep_len);
if (sep_len == 0) {
mp_raise_ValueError(MP_ERROR_TEXT("empty separator"));
}
const byte *beg = s;
const byte *last = s + len;
for (;;) {
s = last - sep_len;
for (;;) {
if (splits == 0 || s < beg) {
break;
} else if (memcmp(s, sep_str, sep_len) == 0) {
break;
}
s--;
}
if (s < beg || splits == 0) {
res->items[idx] = mp_obj_new_str_of_type(self_type, beg, last - beg);
break;
}
res->items[idx--] = mp_obj_new_str_of_type(self_type, s + sep_len, last - s - sep_len);
last = s;
splits--;
}
if (idx != 0) {
// We split less parts than split limit, now go cleanup surplus
size_t used = org_splits + 1 - idx;
memmove(res->items, &res->items[idx], used * sizeof(mp_obj_t));
mp_seq_clear(res->items, used, res->alloc, sizeof(*res->items));
res->len = used;
}
}
return MP_OBJ_FROM_PTR(res);
}
MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rsplit_obj, 1, 3, str_rsplit);
STATIC mp_obj_t str_finder(size_t n_args, const mp_obj_t *args, int direction, bool is_index) {
const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
mp_check_self(mp_obj_is_str_or_bytes(args[0]));
// check argument type
if (mp_obj_get_type(args[1]) != self_type) {
bad_implicit_conversion(args[1]);
}
GET_STR_DATA_LEN(args[0], haystack, haystack_len);
GET_STR_DATA_LEN(args[1], needle, needle_len);
const byte *start = haystack;
const byte *end = haystack + haystack_len;
if (n_args >= 3 && args[2] != mp_const_none) {
start = str_index_to_ptr(self_type, haystack, haystack_len, args[2], true);
}
if (n_args >= 4 && args[3] != mp_const_none) {
end = str_index_to_ptr(self_type, haystack, haystack_len, args[3], true);
}
if (end < start) {
goto out_error;
}
const byte *p = find_subbytes(start, end - start, needle, needle_len, direction);
if (p == NULL) {
out_error:
// not found
if (is_index) {
mp_raise_ValueError(MP_ERROR_TEXT("substring not found"));
} else {
return MP_OBJ_NEW_SMALL_INT(-1);
}
} else {
// found
#if MICROPY_PY_BUILTINS_STR_UNICODE
if (self_type == &mp_type_str) {
return MP_OBJ_NEW_SMALL_INT(utf8_ptr_to_index(haystack, p));
}
#endif
return MP_OBJ_NEW_SMALL_INT(p - haystack);
}
}
STATIC mp_obj_t str_find(size_t n_args, const mp_obj_t *args) {
return str_finder(n_args, args, 1, false);
}
MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_find_obj, 2, 4, str_find);
STATIC mp_obj_t str_rfind(size_t n_args, const mp_obj_t *args) {
return str_finder(n_args, args, -1, false);
}
MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rfind_obj, 2, 4, str_rfind);
STATIC mp_obj_t str_index(size_t n_args, const mp_obj_t *args) {
return str_finder(n_args, args, 1, true);
}
MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_index_obj, 2, 4, str_index);
STATIC mp_obj_t str_rindex(size_t n_args, const mp_obj_t *args) {
return str_finder(n_args, args, -1, true);
}
MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rindex_obj, 2, 4, str_rindex);
// TODO: (Much) more variety in args
STATIC mp_obj_t str_startswith(size_t n_args, const mp_obj_t *args) {
const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
GET_STR_DATA_LEN(args[0], str, str_len);
size_t prefix_len;
const char *prefix = mp_obj_str_get_data(args[1], &prefix_len);
const byte *start = str;
if (n_args > 2) {
start = str_index_to_ptr(self_type, str, str_len, args[2], true);
}
if (prefix_len + (start - str) > str_len) {
return mp_const_false;
}
return mp_obj_new_bool(memcmp(start, prefix, prefix_len) == 0);
}
MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_startswith_obj, 2, 3, str_startswith);
STATIC mp_obj_t str_endswith(size_t n_args, const mp_obj_t *args) {
GET_STR_DATA_LEN(args[0], str, str_len);
size_t suffix_len;
const char *suffix = mp_obj_str_get_data(args[1], &suffix_len);
if (n_args > 2) {
mp_raise_NotImplementedError(MP_ERROR_TEXT("start/end indices"));
}
if (suffix_len > str_len) {
return mp_const_false;
}
return mp_obj_new_bool(memcmp(str + (str_len - suffix_len), suffix, suffix_len) == 0);
}
MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_endswith_obj, 2, 3, str_endswith);
enum { LSTRIP, RSTRIP, STRIP };
STATIC mp_obj_t str_uni_strip(int type, size_t n_args, const mp_obj_t *args) {
mp_check_self(mp_obj_is_str_or_bytes(args[0]));
const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
const byte *chars_to_del;
uint chars_to_del_len;
static const byte whitespace[] = " \t\n\r\v\f";
if (n_args == 1) {
chars_to_del = whitespace;
chars_to_del_len = sizeof(whitespace) - 1;
} else {
if (mp_obj_get_type(args[1]) != self_type) {
bad_implicit_conversion(args[1]);
}
GET_STR_DATA_LEN(args[1], s, l);
chars_to_del = s;
chars_to_del_len = l;
}
GET_STR_DATA_LEN(args[0], orig_str, orig_str_len);
size_t first_good_char_pos = 0;
bool first_good_char_pos_set = false;
size_t last_good_char_pos = 0;
size_t i = 0;
int delta = 1;
if (type == RSTRIP) {
i = orig_str_len - 1;
delta = -1;
}
for (size_t len = orig_str_len; len > 0; len--) {
if (find_subbytes(chars_to_del, chars_to_del_len, &orig_str[i], 1, 1) == NULL) {
if (!first_good_char_pos_set) {
first_good_char_pos_set = true;
first_good_char_pos = i;
if (type == LSTRIP) {
last_good_char_pos = orig_str_len - 1;
break;
} else if (type == RSTRIP) {
first_good_char_pos = 0;
last_good_char_pos = i;
break;
}
}
last_good_char_pos = i;
}
i += delta;
}
if (!first_good_char_pos_set) {
// string is all whitespace, return ''
if (self_type == &mp_type_str) {
return MP_OBJ_NEW_QSTR(MP_QSTR_);
} else {
return mp_const_empty_bytes;
}
}
assert(last_good_char_pos >= first_good_char_pos);
// +1 to accommodate the last character
size_t stripped_len = last_good_char_pos - first_good_char_pos + 1;
if (stripped_len == orig_str_len) {
// If nothing was stripped, don't bother to dup original string
// TODO: watch out for this case when we'll get to bytearray.strip()
assert(first_good_char_pos == 0);
return args[0];
}
return mp_obj_new_str_of_type(self_type, orig_str + first_good_char_pos, stripped_len);
}
STATIC mp_obj_t str_strip(size_t n_args, const mp_obj_t *args) {
return str_uni_strip(STRIP, n_args, args);
}
MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_strip_obj, 1, 2, str_strip);
STATIC mp_obj_t str_lstrip(size_t n_args, const mp_obj_t *args) {
return str_uni_strip(LSTRIP, n_args, args);
}
MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_lstrip_obj, 1, 2, str_lstrip);
STATIC mp_obj_t str_rstrip(size_t n_args, const mp_obj_t *args) {
return str_uni_strip(RSTRIP, n_args, args);
}
MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rstrip_obj, 1, 2, str_rstrip);
#if MICROPY_PY_BUILTINS_STR_CENTER
STATIC mp_obj_t str_center(mp_obj_t str_in, mp_obj_t width_in) {
GET_STR_DATA_LEN(str_in, str, str_len);
mp_uint_t width = mp_obj_get_int(width_in);
if (str_len >= width) {
return str_in;
}
vstr_t vstr;
vstr_init_len(&vstr, width);
memset(vstr.buf, ' ', width);
int left = (width - str_len) / 2;
memcpy(vstr.buf + left, str, str_len);
return mp_obj_new_str_from_vstr(mp_obj_get_type(str_in), &vstr);
}
MP_DEFINE_CONST_FUN_OBJ_2(str_center_obj, str_center);
#endif
// Takes an int arg, but only parses unsigned numbers, and only changes
// *num if at least one digit was parsed.
STATIC const char *str_to_int(const char *str, const char *top, int *num) {
if (str < top && '0' <= *str && *str <= '9') {
*num = 0;
do {
*num = *num * 10 + (*str - '0');
str++;
}
while (str < top && '0' <= *str && *str <= '9');
}
return str;
}
STATIC bool isalignment(char ch) {
return ch && strchr("<>=^", ch) != NULL;
}
STATIC bool istype(char ch) {
return ch && strchr("bcdeEfFgGnosxX%", ch) != NULL;
}
STATIC bool arg_looks_integer(mp_obj_t arg) {
return mp_obj_is_bool(arg) || mp_obj_is_int(arg);
}
STATIC bool arg_looks_numeric(mp_obj_t arg) {
return arg_looks_integer(arg)
#if MICROPY_PY_BUILTINS_FLOAT
|| mp_obj_is_float(arg)
#endif
;
}
#if MICROPY_PY_BUILTINS_STR_OP_MODULO
STATIC mp_obj_t arg_as_int(mp_obj_t arg) {
#if MICROPY_PY_BUILTINS_FLOAT
if (mp_obj_is_float(arg)) {
return mp_obj_new_int_from_float(mp_obj_float_get(arg));
}
#endif
return arg;
}
#endif
#if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
STATIC NORETURN void terse_str_format_value_error(void) {
mp_raise_ValueError(MP_ERROR_TEXT("bad format string"));
}
#else
// define to nothing to improve coverage
#define terse_str_format_value_error()
#endif
STATIC vstr_t mp_obj_str_format_helper(const char *str, const char *top, int *arg_i, size_t n_args, const mp_obj_t *args, mp_map_t *kwargs) {
vstr_t vstr;
mp_print_t print;
vstr_init_print(&vstr, 16, &print);
for (; str < top; str++) {
if (*str == '}') {
str++;
if (str < top && *str == '}') {
vstr_add_byte(&vstr, '}');
continue;
}
#if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
terse_str_format_value_error();
#else
mp_raise_ValueError(MP_ERROR_TEXT("single '}' encountered in format string"));
#endif
}
if (*str != '{') {
vstr_add_byte(&vstr, *str);
continue;
}
str++;
if (str < top && *str == '{') {
vstr_add_byte(&vstr, '{');
continue;
}
// replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"
const char *field_name = NULL;
const char *field_name_top = NULL;
char conversion = '\0';
const char *format_spec = NULL;
if (str < top && *str != '}' && *str != '!' && *str != ':') {
field_name = (const char *)str;
while (str < top && *str != '}' && *str != '!' && *str != ':') {
++str;
}
field_name_top = (const char *)str;
}
// conversion ::= "r" | "s"
if (str < top && *str == '!') {
str++;
if (str < top && (*str == 'r' || *str == 's')) {
conversion = *str++;
} else {
#if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
terse_str_format_value_error();
#elif MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_NORMAL
mp_raise_ValueError(MP_ERROR_TEXT("bad conversion specifier"));
#else
if (str >= top) {
mp_raise_ValueError(
MP_ERROR_TEXT("end of format while looking for conversion specifier"));
} else {
mp_raise_msg_varg(&mp_type_ValueError,
MP_ERROR_TEXT("unknown conversion specifier %c"), *str);
}
#endif
}
}
if (str < top && *str == ':') {
str++;
// {:} is the same as {}, which is the same as {!s}
// This makes a difference when passing in a True or False
// '{}'.format(True) returns 'True'
// '{:d}'.format(True) returns '1'
// So we treat {:} as {} and this later gets treated to be {!s}
if (*str != '}') {
format_spec = str;
for (int nest = 1; str < top;) {
if (*str == '{') {
++nest;
} else if (*str == '}') {
if (--nest == 0) {
break;
}
}
++str;
}
}
}
if (str >= top) {
#if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
terse_str_format_value_error();
#else
mp_raise_ValueError(MP_ERROR_TEXT("unmatched '{' in format"));
#endif
}
if (*str != '}') {
#if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
terse_str_format_value_error();
#else
mp_raise_ValueError(MP_ERROR_TEXT("expected ':' after format specifier"));
#endif
}
mp_obj_t arg = mp_const_none;
if (field_name) {
int index = 0;
if (MP_LIKELY(unichar_isdigit(*field_name))) {
if (*arg_i > 0) {
#if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
terse_str_format_value_error();
#else
mp_raise_ValueError(
MP_ERROR_TEXT("can't switch from automatic field numbering to manual field specification"));
#endif
}
field_name = str_to_int(field_name, field_name_top, &index);
if ((uint)index >= n_args - 1) {
mp_raise_msg(&mp_type_IndexError, MP_ERROR_TEXT("tuple index out of range"));
}
arg = args[index + 1];
*arg_i = -1;
} else {
const char *lookup;
for (lookup = field_name; lookup < field_name_top && *lookup != '.' && *lookup != '['; lookup++) {;
}
mp_obj_t field_q = mp_obj_new_str_via_qstr(field_name, lookup - field_name); // should it be via qstr?
field_name = lookup;
mp_map_elem_t *key_elem = mp_map_lookup(kwargs, field_q, MP_MAP_LOOKUP);
if (key_elem == NULL) {
mp_raise_type_arg(&mp_type_KeyError, field_q);
}
arg = key_elem->value;
}
if (field_name < field_name_top) {
mp_raise_NotImplementedError(MP_ERROR_TEXT("attributes not supported yet"));
}
} else {
if (*arg_i < 0) {
#if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
terse_str_format_value_error();
#else
mp_raise_ValueError(
MP_ERROR_TEXT("can't switch from manual field specification to automatic field numbering"));
#endif
}
if ((uint)*arg_i >= n_args - 1) {
mp_raise_msg(&mp_type_IndexError, MP_ERROR_TEXT("tuple index out of range"));
}
arg = args[(*arg_i) + 1];
(*arg_i)++;
}
if (!format_spec && !conversion) {
conversion = 's';
}
if (conversion) {
mp_print_kind_t print_kind;
if (conversion == 's') {
print_kind = PRINT_STR;
} else {
assert(conversion == 'r');
print_kind = PRINT_REPR;
}
vstr_t arg_vstr;
mp_print_t arg_print;
vstr_init_print(&arg_vstr, 16, &arg_print);
mp_obj_print_helper(&arg_print, arg, print_kind);
arg = mp_obj_new_str_from_vstr(&mp_type_str, &arg_vstr);
}
char fill = '\0';
char align = '\0';
int width = -1;
int precision = -1;
char type = '\0';
int flags = 0;
if (format_spec) {
// The format specifier (from http://docs.python.org/2/library/string.html#formatspec)
//
// [[fill]align][sign][#][0][width][,][.precision][type]
// fill ::= <any character>
// align ::= "<" | ">" | "=" | "^"
// sign ::= "+" | "-" | " "
// width ::= integer
// precision ::= integer
// type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
// recursively call the formatter to format any nested specifiers
MP_STACK_CHECK();
vstr_t format_spec_vstr = mp_obj_str_format_helper(format_spec, str, arg_i, n_args, args, kwargs);
const char *s = vstr_null_terminated_str(&format_spec_vstr);
const char *stop = s + format_spec_vstr.len;
if (isalignment(*s)) {
align = *s++;
} else if (*s && isalignment(s[1])) {
fill = *s++;
align = *s++;
}
if (*s == '+' || *s == '-' || *s == ' ') {
if (*s == '+') {
flags |= PF_FLAG_SHOW_SIGN;
} else if (*s == ' ') {
flags |= PF_FLAG_SPACE_SIGN;
}
s++;
}
if (*s == '#') {
flags |= PF_FLAG_SHOW_PREFIX;
s++;
}
if (*s == '0') {
if (!align) {
align = '=';
}
if (!fill) {
fill = '0';
}
}
s = str_to_int(s, stop, &width);
if (*s == ',') {
flags |= PF_FLAG_SHOW_COMMA;
s++;
}
if (*s == '.') {
s++;
s = str_to_int(s, stop, &precision);
}
if (istype(*s)) {
type = *s++;
}
if (*s) {
#if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
terse_str_format_value_error();
#else
mp_raise_ValueError(MP_ERROR_TEXT("invalid format specifier"));
#endif
}
vstr_clear(&format_spec_vstr);
}
if (!align) {
if (arg_looks_numeric(arg)) {
align = '>';
} else {
align = '<';
}
}
if (!fill) {
fill = ' ';
}
if (flags & (PF_FLAG_SHOW_SIGN | PF_FLAG_SPACE_SIGN)) {
if (type == 's') {
#if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
terse_str_format_value_error();
#else
mp_raise_ValueError(MP_ERROR_TEXT("sign not allowed in string format specifier"));
#endif
}
if (type == 'c') {
#if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
terse_str_format_value_error();
#else
mp_raise_ValueError(
MP_ERROR_TEXT("sign not allowed with integer format specifier 'c'"));
#endif
}
}
switch (align) {
case '<':
flags |= PF_FLAG_LEFT_ADJUST;
break;
case '=':
flags |= PF_FLAG_PAD_AFTER_SIGN;
break;
case '^':
flags |= PF_FLAG_CENTER_ADJUST;
break;
}
if (arg_looks_integer(arg)) {
switch (type) {
case 'b':
mp_print_mp_int(&print, arg, 2, 'a', flags, fill, width, 0);
continue;
case 'c': {
char ch = mp_obj_get_int(arg);
mp_print_strn(&print, &ch, 1, flags, fill, width);
continue;
}
case '\0': // No explicit format type implies 'd'
case 'n': // I don't think we support locales in uPy so use 'd'
case 'd':
mp_print_mp_int(&print, arg, 10, 'a', flags, fill, width, 0);
continue;
case 'o':
if (flags & PF_FLAG_SHOW_PREFIX) {
flags |= PF_FLAG_SHOW_OCTAL_LETTER;
}
mp_print_mp_int(&print, arg, 8, 'a', flags, fill, width, 0);
continue;
case 'X':
case 'x':
mp_print_mp_int(&print, arg, 16, type - ('X' - 'A'), flags, fill, width, 0);
continue;
case 'e':
case 'E':
case 'f':
case 'F':
case 'g':
case 'G':
case '%':
// The floating point formatters all work with anything that
// looks like an integer
break;
default:
#if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
terse_str_format_value_error();
#else
mp_raise_msg_varg(&mp_type_ValueError,
MP_ERROR_TEXT("unknown format code '%c' for object of type '%s'"),
type, mp_obj_get_type_str(arg));
#endif
}
}
// NOTE: no else here. We need the e, f, g etc formats for integer
// arguments (from above if) to take this if.
if (arg_looks_numeric(arg)) {
if (!type) {
// Even though the docs say that an unspecified type is the same
// as 'g', there is one subtle difference, when the exponent
// is one less than the precision.
//
// '{:10.1}'.format(0.0) ==> '0e+00'
// '{:10.1g}'.format(0.0) ==> '0'
//
// TODO: Figure out how to deal with this.
//
// A proper solution would involve adding a special flag
// or something to format_float, and create a format_double
// to deal with doubles. In order to fix this when using
// sprintf, we'd need to use the e format and tweak the
// returned result to strip trailing zeros like the g format
// does.
//
// {:10.3} and {:10.2e} with 1.23e2 both produce 1.23e+02
// but with 1.e2 you get 1e+02 and 1.00e+02
//
// Stripping the trailing 0's (like g) does would make the
// e format give us the right format.
//
// CPython sources say:
// Omitted type specifier. Behaves in the same way as repr(x)
// and str(x) if no precision is given, else like 'g', but with
// at least one digit after the decimal point. */
type = 'g';
}
if (type == 'n') {
type = 'g';
}
switch (type) {
#if MICROPY_PY_BUILTINS_FLOAT
case 'e':
case 'E':
case 'f':
case 'F':
case 'g':
case 'G':
mp_print_float(&print, mp_obj_get_float(arg), type, flags, fill, width, precision);
break;
case '%':
flags |= PF_FLAG_ADD_PERCENT;
#if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT
#define F100 100.0F
#else
#define F100 100.0
#endif
mp_print_float(&print, mp_obj_get_float(arg) * F100, 'f', flags, fill, width, precision);
#undef F100
break;
#endif
default:
#if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
terse_str_format_value_error();
#else
mp_raise_msg_varg(&mp_type_ValueError,
MP_ERROR_TEXT("unknown format code '%c' for object of type '%s'"),
type, mp_obj_get_type_str(arg));
#endif
}
} else {
// arg doesn't look like a number
if (align == '=') {
#if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
terse_str_format_value_error();
#else
mp_raise_ValueError(
MP_ERROR_TEXT("'=' alignment not allowed in string format specifier"));
#endif
}
switch (type) {
case '\0': // no explicit format type implies 's'
case 's': {
size_t slen;
const char *s = mp_obj_str_get_data(arg, &slen);
if (precision < 0) {
precision = slen;
}
if (slen > (size_t)precision) {
slen = precision;
}
mp_print_strn(&print, s, slen, flags, fill, width);
break;
}
default:
#if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
terse_str_format_value_error();
#else
mp_raise_msg_varg(&mp_type_ValueError,
MP_ERROR_TEXT("unknown format code '%c' for object of type '%s'"),
type, mp_obj_get_type_str(arg));
#endif
}
}
}
return vstr;
}
mp_obj_t mp_obj_str_format(size_t n_args, const mp_obj_t *args, mp_map_t *kwargs) {
mp_check_self(mp_obj_is_str_or_bytes(args[0]));
GET_STR_DATA_LEN(args[0], str, len);
int arg_i = 0;
vstr_t vstr = mp_obj_str_format_helper((const char *)str, (const char *)str + len, &arg_i, n_args, args, kwargs);
return mp_obj_new_str_from_vstr(mp_obj_get_type(args[0]), &vstr);
}
MP_DEFINE_CONST_FUN_OBJ_KW(str_format_obj, 1, mp_obj_str_format);
#if MICROPY_PY_BUILTINS_STR_OP_MODULO
STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, size_t n_args, const mp_obj_t *args, mp_obj_t dict) {
mp_check_self(mp_obj_is_str_or_bytes(pattern));
GET_STR_DATA_LEN(pattern, str, len);
#if MICROPY_ERROR_REPORTING > MICROPY_ERROR_REPORTING_TERSE
const byte *start_str = str;
#endif
bool is_bytes = mp_obj_is_type(pattern, &mp_type_bytes);
size_t arg_i = 0;
vstr_t vstr;
mp_print_t print;
vstr_init_print(&vstr, 16, &print);
for (const byte *top = str + len; str < top; str++) {
mp_obj_t arg = MP_OBJ_NULL;
if (*str != '%') {
vstr_add_byte(&vstr, *str);
continue;
}
if (++str >= top) {
goto incomplete_format;
}
if (*str == '%') {
vstr_add_byte(&vstr, '%');
continue;
}
// Dictionary value lookup
if (*str == '(') {
if (dict == MP_OBJ_NULL) {
mp_raise_TypeError(MP_ERROR_TEXT("format needs a dict"));
}
arg_i = 1; // we used up the single dict argument
const byte *key = ++str;
while (*str != ')') {
if (str >= top) {
#if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
terse_str_format_value_error();
#else
mp_raise_ValueError(MP_ERROR_TEXT("incomplete format key"));
#endif
}
++str;
}
mp_obj_t k_obj = mp_obj_new_str_via_qstr((const char *)key, str - key);
arg = mp_obj_dict_get(dict, k_obj);
str++;
}
int flags = 0;
char fill = ' ';
int alt = 0;
while (str < top) {
if (*str == '-') {
flags |= PF_FLAG_LEFT_ADJUST;
} else if (*str == '+') {
flags |= PF_FLAG_SHOW_SIGN;
} else if (*str == ' ') {
flags |= PF_FLAG_SPACE_SIGN;
} else if (*str == '#') {
alt = PF_FLAG_SHOW_PREFIX;
} else if (*str == '0') {
flags |= PF_FLAG_PAD_AFTER_SIGN;
fill = '0';
} else {
break;
}
str++;
}
// parse width, if it exists
int width = 0;
if (str < top) {
if (*str == '*') {
if (arg_i >= n_args) {
goto not_enough_args;
}
width = mp_obj_get_int(args[arg_i++]);
str++;
} else {
str = (const byte *)str_to_int((const char *)str, (const char *)top, &width);
}
}
int prec = -1;
if (str < top && *str == '.') {
if (++str < top) {
if (*str == '*') {
if (arg_i >= n_args) {
goto not_enough_args;
}
prec = mp_obj_get_int(args[arg_i++]);
str++;
} else {
prec = 0;
str = (const byte *)str_to_int((const char *)str, (const char *)top, &prec);
}
}
}
if (str >= top) {
incomplete_format:
#if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
terse_str_format_value_error();
#else
mp_raise_ValueError(MP_ERROR_TEXT("incomplete format"));
#endif
}
// Tuple value lookup
if (arg == MP_OBJ_NULL) {
if (arg_i >= n_args) {
not_enough_args:
mp_raise_TypeError(MP_ERROR_TEXT("format string needs more arguments"));
}
arg = args[arg_i++];
}
switch (*str) {
case 'c':
if (mp_obj_is_str(arg)) {
size_t slen;
const char *s = mp_obj_str_get_data(arg, &slen);
if (slen != 1) {
mp_raise_TypeError(MP_ERROR_TEXT("%c needs int or char"));
}
mp_print_strn(&print, s, 1, flags, ' ', width);
} else if (arg_looks_integer(arg)) {
char ch = mp_obj_get_int(arg);
mp_print_strn(&print, &ch, 1, flags, ' ', width);
} else {
mp_raise_TypeError(MP_ERROR_TEXT("integer needed"));
}
break;
case 'd':
case 'i':
case 'u':
mp_print_mp_int(&print, arg_as_int(arg), 10, 'a', flags, fill, width, prec);
break;
#if MICROPY_PY_BUILTINS_FLOAT
case 'e':
case 'E':
case 'f':
case 'F':
case 'g':
case 'G':
mp_print_float(&print, mp_obj_get_float(arg), *str, flags, fill, width, prec);
break;
#endif
case 'o':
if (alt) {
flags |= (PF_FLAG_SHOW_PREFIX | PF_FLAG_SHOW_OCTAL_LETTER);
}
mp_print_mp_int(&print, arg, 8, 'a', flags, fill, width, prec);
break;
case 'r':
case 's': {
vstr_t arg_vstr;
mp_print_t arg_print;
vstr_init_print(&arg_vstr, 16, &arg_print);
mp_print_kind_t print_kind = (*str == 'r' ? PRINT_REPR : PRINT_STR);
if (print_kind == PRINT_STR && is_bytes && mp_obj_is_type(arg, &mp_type_bytes)) {
// If we have something like b"%s" % b"1", bytes arg should be
// printed undecorated.
print_kind = PRINT_RAW;
}
mp_obj_print_helper(&arg_print, arg, print_kind);
uint vlen = arg_vstr.len;
if (prec < 0) {
prec = vlen;
}
if (vlen > (uint)prec) {
vlen = prec;
}
mp_print_strn(&print, arg_vstr.buf, vlen, flags, ' ', width);
vstr_clear(&arg_vstr);
break;
}
case 'X':
case 'x':
mp_print_mp_int(&print, arg, 16, *str - ('X' - 'A'), flags | alt, fill, width, prec);
break;
default:
#if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
terse_str_format_value_error();
#else
mp_raise_msg_varg(&mp_type_ValueError,
MP_ERROR_TEXT("unsupported format character '%c' (0x%x) at index %d"),
*str, *str, str - start_str);
#endif
}
}
if (arg_i != n_args) {
mp_raise_TypeError(MP_ERROR_TEXT("format string didn't convert all arguments"));
}
return mp_obj_new_str_from_vstr(is_bytes ? &mp_type_bytes : &mp_type_str, &vstr);
}
#endif
// The implementation is optimized, returning the original string if there's
// nothing to replace.
STATIC mp_obj_t str_replace(size_t n_args, const mp_obj_t *args) {
mp_check_self(mp_obj_is_str_or_bytes(args[0]));
mp_int_t max_rep = -1;
if (n_args == 4) {
max_rep = mp_obj_get_int(args[3]);
if (max_rep == 0) {
return args[0];
} else if (max_rep < 0) {
max_rep = -1;
}
}
// if max_rep is still -1 by this point we will need to do all possible replacements
// check argument types
const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
if (mp_obj_get_type(args[1]) != self_type) {
bad_implicit_conversion(args[1]);
}
if (mp_obj_get_type(args[2]) != self_type) {
bad_implicit_conversion(args[2]);
}
// extract string data
GET_STR_DATA_LEN(args[0], str, str_len);
GET_STR_DATA_LEN(args[1], old, old_len);
GET_STR_DATA_LEN(args[2], new, new_len);
// old won't exist in str if it's longer, so nothing to replace
if (old_len > str_len) {
return args[0];
}
// data for the replaced string
byte *data = NULL;
vstr_t vstr;
// do 2 passes over the string:
// first pass computes the required length of the replaced string
// second pass does the replacements
for (;;) {
size_t replaced_str_index = 0;
size_t num_replacements_done = 0;
const byte *old_occurrence;
const byte *offset_ptr = str;
size_t str_len_remain = str_len;
if (old_len == 0) {
// if old_str is empty, copy new_str to start of replaced string
// copy the replacement string
if (data != NULL) {
memcpy(data, new, new_len);
}
replaced_str_index += new_len;
num_replacements_done++;
}
while (num_replacements_done != (size_t)max_rep && str_len_remain > 0 && (old_occurrence = find_subbytes(offset_ptr, str_len_remain, old, old_len, 1)) != NULL) {
if (old_len == 0) {
old_occurrence += 1;
}
// copy from just after end of last occurrence of to-be-replaced string to right before start of next occurrence
if (data != NULL) {
memcpy(data + replaced_str_index, offset_ptr, old_occurrence - offset_ptr);
}
replaced_str_index += old_occurrence - offset_ptr;
// copy the replacement string
if (data != NULL) {
memcpy(data + replaced_str_index, new, new_len);
}
replaced_str_index += new_len;
offset_ptr = old_occurrence + old_len;
str_len_remain = str + str_len - offset_ptr;
num_replacements_done++;
}
// copy from just after end of last occurrence of to-be-replaced string to end of old string
if (data != NULL) {
memcpy(data + replaced_str_index, offset_ptr, str_len_remain);
}
replaced_str_index += str_len_remain;
if (data == NULL) {
// first pass
if (num_replacements_done == 0) {
// no substr found, return original string
return args[0];
} else {
// substr found, allocate new string
vstr_init_len(&vstr, replaced_str_index);
data = (byte *)vstr.buf;
assert(data != NULL);
}
} else {
// second pass, we are done
break;
}
}
return mp_obj_new_str_from_vstr(self_type, &vstr);
}
MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_replace_obj, 3, 4, str_replace);
#if MICROPY_PY_BUILTINS_STR_COUNT
STATIC mp_obj_t str_count(size_t n_args, const mp_obj_t *args) {
const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
mp_check_self(mp_obj_is_str_or_bytes(args[0]));
// check argument type
if (mp_obj_get_type(args[1]) != self_type) {
bad_implicit_conversion(args[1]);
}
GET_STR_DATA_LEN(args[0], haystack, haystack_len);
GET_STR_DATA_LEN(args[1], needle, needle_len);
const byte *start = haystack;
const byte *end = haystack + haystack_len;
if (n_args >= 3 && args[2] != mp_const_none) {
start = str_index_to_ptr(self_type, haystack, haystack_len, args[2], true);
}
if (n_args >= 4 && args[3] != mp_const_none) {
end = str_index_to_ptr(self_type, haystack, haystack_len, args[3], true);
}
// if needle_len is zero then we count each gap between characters as an occurrence
if (needle_len == 0) {
return MP_OBJ_NEW_SMALL_INT(utf8_charlen(start, end - start) + 1);
}
// count the occurrences
mp_int_t num_occurrences = 0;
for (const byte *haystack_ptr = start; haystack_ptr + needle_len <= end;) {
if (memcmp(haystack_ptr, needle, needle_len) == 0) {
num_occurrences++;
haystack_ptr += needle_len;
} else {
haystack_ptr = utf8_next_char(haystack_ptr);
}
}
return MP_OBJ_NEW_SMALL_INT(num_occurrences);
}
MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_count_obj, 2, 4, str_count);
#endif
#if MICROPY_PY_BUILTINS_STR_PARTITION
STATIC mp_obj_t str_partitioner(mp_obj_t self_in, mp_obj_t arg, int direction) {
mp_check_self(mp_obj_is_str_or_bytes(self_in));
const mp_obj_type_t *self_type = mp_obj_get_type(self_in);
if (self_type != mp_obj_get_type(arg)) {
bad_implicit_conversion(arg);
}
GET_STR_DATA_LEN(self_in, str, str_len);
GET_STR_DATA_LEN(arg, sep, sep_len);
if (sep_len == 0) {
mp_raise_ValueError(MP_ERROR_TEXT("empty separator"));
}
mp_obj_t result[3];
if (self_type == &mp_type_str) {
result[0] = MP_OBJ_NEW_QSTR(MP_QSTR_);
result[1] = MP_OBJ_NEW_QSTR(MP_QSTR_);
result[2] = MP_OBJ_NEW_QSTR(MP_QSTR_);
} else {
result[0] = mp_const_empty_bytes;
result[1] = mp_const_empty_bytes;
result[2] = mp_const_empty_bytes;
}
if (direction > 0) {
result[0] = self_in;
} else {
result[2] = self_in;
}
const byte *position_ptr = find_subbytes(str, str_len, sep, sep_len, direction);
if (position_ptr != NULL) {
size_t position = position_ptr - str;
result[0] = mp_obj_new_str_of_type(self_type, str, position);
result[1] = arg;
result[2] = mp_obj_new_str_of_type(self_type, str + position + sep_len, str_len - position - sep_len);
}
return mp_obj_new_tuple(3, result);
}
STATIC mp_obj_t str_partition(mp_obj_t self_in, mp_obj_t arg) {
return str_partitioner(self_in, arg, 1);
}
MP_DEFINE_CONST_FUN_OBJ_2(str_partition_obj, str_partition);
STATIC mp_obj_t str_rpartition(mp_obj_t self_in, mp_obj_t arg) {
return str_partitioner(self_in, arg, -1);
}
MP_DEFINE_CONST_FUN_OBJ_2(str_rpartition_obj, str_rpartition);
#endif
// Supposedly not too critical operations, so optimize for code size
STATIC mp_obj_t str_caseconv(unichar (*op)(unichar), mp_obj_t self_in) {
GET_STR_DATA_LEN(self_in, self_data, self_len);
vstr_t vstr;
vstr_init_len(&vstr, self_len);
byte *data = (byte *)vstr.buf;
for (size_t i = 0; i < self_len; i++) {
*data++ = op(*self_data++);
}
return mp_obj_new_str_from_vstr(mp_obj_get_type(self_in), &vstr);
}
STATIC mp_obj_t str_lower(mp_obj_t self_in) {
return str_caseconv(unichar_tolower, self_in);
}
MP_DEFINE_CONST_FUN_OBJ_1(str_lower_obj, str_lower);
STATIC mp_obj_t str_upper(mp_obj_t self_in) {
return str_caseconv(unichar_toupper, self_in);
}
MP_DEFINE_CONST_FUN_OBJ_1(str_upper_obj, str_upper);
STATIC mp_obj_t str_uni_istype(bool (*f)(unichar), mp_obj_t self_in) {
GET_STR_DATA_LEN(self_in, self_data, self_len);
if (self_len == 0) {
return mp_const_false; // default to False for empty str
}
if (f != unichar_isupper && f != unichar_islower) {
for (size_t i = 0; i < self_len; i++) {
if (!f(*self_data++)) {
return mp_const_false;
}
}
} else {
bool contains_alpha = false;
for (size_t i = 0; i < self_len; i++) { // only check alphanumeric characters
if (unichar_isalpha(*self_data++)) {
contains_alpha = true;
if (!f(*(self_data - 1))) { // -1 because we already incremented above
return mp_const_false;
}
}
}
if (!contains_alpha) {
return mp_const_false;
}
}
return mp_const_true;
}
STATIC mp_obj_t str_isspace(mp_obj_t self_in) {
return str_uni_istype(unichar_isspace, self_in);
}
MP_DEFINE_CONST_FUN_OBJ_1(str_isspace_obj, str_isspace);
STATIC mp_obj_t str_isalpha(mp_obj_t self_in) {
return str_uni_istype(unichar_isalpha, self_in);
}
MP_DEFINE_CONST_FUN_OBJ_1(str_isalpha_obj, str_isalpha);
STATIC mp_obj_t str_isdigit(mp_obj_t self_in) {
return str_uni_istype(unichar_isdigit, self_in);
}
MP_DEFINE_CONST_FUN_OBJ_1(str_isdigit_obj, str_isdigit);
STATIC mp_obj_t str_isupper(mp_obj_t self_in) {
return str_uni_istype(unichar_isupper, self_in);
}
MP_DEFINE_CONST_FUN_OBJ_1(str_isupper_obj, str_isupper);
STATIC mp_obj_t str_islower(mp_obj_t self_in) {
return str_uni_istype(unichar_islower, self_in);
}
MP_DEFINE_CONST_FUN_OBJ_1(str_islower_obj, str_islower);
#if MICROPY_CPYTHON_COMPAT
// These methods are superfluous in the presence of str() and bytes()
// constructors.
// TODO: should accept kwargs too
STATIC mp_obj_t bytes_decode(size_t n_args, const mp_obj_t *args) {
mp_obj_t new_args[2];
if (n_args == 1) {
new_args[0] = args[0];
new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
args = new_args;
n_args++;
}
return mp_obj_str_make_new(&mp_type_str, n_args, 0, args);
}
MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(bytes_decode_obj, 1, 3, bytes_decode);
// TODO: should accept kwargs too
STATIC mp_obj_t str_encode(size_t n_args, const mp_obj_t *args) {
mp_obj_t new_args[2];
if (n_args == 1) {
new_args[0] = args[0];
new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
args = new_args;
n_args++;
}
return bytes_make_new(NULL, n_args, 0, args);
}
MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_encode_obj, 1, 3, str_encode);
#endif
mp_int_t mp_obj_str_get_buffer(mp_obj_t self_in, mp_buffer_info_t *bufinfo, mp_uint_t flags) {
if (flags == MP_BUFFER_READ) {
GET_STR_DATA_LEN(self_in, str_data, str_len);
bufinfo->buf = (void *)str_data;
bufinfo->len = str_len;
bufinfo->typecode = 'B'; // bytes should be unsigned, so should unicode byte-access
return 0;
} else {
// can't write to a string
return 1;
}
}
STATIC const mp_rom_map_elem_t str8_locals_dict_table[] = {
#if MICROPY_CPYTHON_COMPAT
{ MP_ROM_QSTR(MP_QSTR_decode), MP_ROM_PTR(&bytes_decode_obj) },
#if !MICROPY_PY_BUILTINS_STR_UNICODE
// If we have separate unicode type, then here we have methods only
// for bytes type, and it should not have encode() methods. Otherwise,
// we have non-compliant-but-practical bytestring type, which shares
// method table with bytes, so they both have encode() and decode()
// methods (which should do type checking at runtime).
{ MP_ROM_QSTR(MP_QSTR_encode), MP_ROM_PTR(&str_encode_obj) },
#endif
#endif
{ MP_ROM_QSTR(MP_QSTR_find), MP_ROM_PTR(&str_find_obj) },
{ MP_ROM_QSTR(MP_QSTR_rfind), MP_ROM_PTR(&str_rfind_obj) },
{ MP_ROM_QSTR(MP_QSTR_index), MP_ROM_PTR(&str_index_obj) },
{ MP_ROM_QSTR(MP_QSTR_rindex), MP_ROM_PTR(&str_rindex_obj) },
{ MP_ROM_QSTR(MP_QSTR_join), MP_ROM_PTR(&str_join_obj) },
{ MP_ROM_QSTR(MP_QSTR_split), MP_ROM_PTR(&str_split_obj) },
#if MICROPY_PY_BUILTINS_STR_SPLITLINES
{ MP_ROM_QSTR(MP_QSTR_splitlines), MP_ROM_PTR(&str_splitlines_obj) },
#endif
{ MP_ROM_QSTR(MP_QSTR_rsplit), MP_ROM_PTR(&str_rsplit_obj) },
{ MP_ROM_QSTR(MP_QSTR_startswith), MP_ROM_PTR(&str_startswith_obj) },
{ MP_ROM_QSTR(MP_QSTR_endswith), MP_ROM_PTR(&str_endswith_obj) },
{ MP_ROM_QSTR(MP_QSTR_strip), MP_ROM_PTR(&str_strip_obj) },
{ MP_ROM_QSTR(MP_QSTR_lstrip), MP_ROM_PTR(&str_lstrip_obj) },
{ MP_ROM_QSTR(MP_QSTR_rstrip), MP_ROM_PTR(&str_rstrip_obj) },
{ MP_ROM_QSTR(MP_QSTR_format), MP_ROM_PTR(&str_format_obj) },
{ MP_ROM_QSTR(MP_QSTR_replace), MP_ROM_PTR(&str_replace_obj) },
#if MICROPY_PY_BUILTINS_STR_COUNT
{ MP_ROM_QSTR(MP_QSTR_count), MP_ROM_PTR(&str_count_obj) },
#endif
#if MICROPY_PY_BUILTINS_STR_PARTITION
{ MP_ROM_QSTR(MP_QSTR_partition), MP_ROM_PTR(&str_partition_obj) },
{ MP_ROM_QSTR(MP_QSTR_rpartition), MP_ROM_PTR(&str_rpartition_obj) },
#endif
#if MICROPY_PY_BUILTINS_STR_CENTER
{ MP_ROM_QSTR(MP_QSTR_center), MP_ROM_PTR(&str_center_obj) },
#endif
{ MP_ROM_QSTR(MP_QSTR_lower), MP_ROM_PTR(&str_lower_obj) },
{ MP_ROM_QSTR(MP_QSTR_upper), MP_ROM_PTR(&str_upper_obj) },
{ MP_ROM_QSTR(MP_QSTR_isspace), MP_ROM_PTR(&str_isspace_obj) },
{ MP_ROM_QSTR(MP_QSTR_isalpha), MP_ROM_PTR(&str_isalpha_obj) },
{ MP_ROM_QSTR(MP_QSTR_isdigit), MP_ROM_PTR(&str_isdigit_obj) },
{ MP_ROM_QSTR(MP_QSTR_isupper), MP_ROM_PTR(&str_isupper_obj) },
{ MP_ROM_QSTR(MP_QSTR_islower), MP_ROM_PTR(&str_islower_obj) },
};
STATIC MP_DEFINE_CONST_DICT(str8_locals_dict, str8_locals_dict_table);
#if !MICROPY_PY_BUILTINS_STR_UNICODE
STATIC mp_obj_t mp_obj_new_str_iterator(mp_obj_t str, mp_obj_iter_buf_t *iter_buf);
const mp_obj_type_t mp_type_str = {
{ &mp_type_type },
.name = MP_QSTR_str,
.print = str_print,
.make_new = mp_obj_str_make_new,
.binary_op = mp_obj_str_binary_op,
.subscr = bytes_subscr,
.getiter = mp_obj_new_str_iterator,
.buffer_p = { .get_buffer = mp_obj_str_get_buffer },
.locals_dict = (mp_obj_dict_t *)&str8_locals_dict,
};
#endif
// Reuses most of methods from str
const mp_obj_type_t mp_type_bytes = {
{ &mp_type_type },
.name = MP_QSTR_bytes,
.print = str_print,
.make_new = bytes_make_new,
.binary_op = mp_obj_str_binary_op,
.subscr = bytes_subscr,
.getiter = mp_obj_new_bytes_iterator,
.buffer_p = { .get_buffer = mp_obj_str_get_buffer },
.locals_dict = (mp_obj_dict_t *)&str8_locals_dict,
};
// The zero-length bytes object, with data that includes a null-terminating byte
const mp_obj_str_t mp_const_empty_bytes_obj = {{&mp_type_bytes}, 0, 0, (const byte *)""};
// Create a str/bytes object using the given data. New memory is allocated and
// the data is copied across. This function should only be used if the type is bytes,
// or if the type is str and the string data is known to be not interned.
mp_obj_t mp_obj_new_str_copy(const mp_obj_type_t *type, const byte *data, size_t len) {
mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
o->base.type = type;
o->len = len;
if (data) {
o->hash = qstr_compute_hash(data, len);
byte *p = m_new(byte, len + 1);
o->data = p;
memcpy(p, data, len * sizeof(byte));
p[len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
}
return MP_OBJ_FROM_PTR(o);
}
// Create a str/bytes object using the given data. If the type is str and the string
// data is already interned, then a qstr object is returned. Otherwise new memory is
// allocated for the object and the data is copied across.
mp_obj_t mp_obj_new_str_of_type(const mp_obj_type_t *type, const byte *data, size_t len) {
if (type == &mp_type_str) {
return mp_obj_new_str((const char *)data, len);
} else {
return mp_obj_new_bytes(data, len);
}
}
// Create a str using a qstr to store the data; may use existing or new qstr.
mp_obj_t mp_obj_new_str_via_qstr(const char *data, size_t len) {
return MP_OBJ_NEW_QSTR(qstr_from_strn(data, len));
}
// Create a str/bytes object from the given vstr. The vstr buffer is resized to
// the exact length required and then reused for the str/bytes object. The vstr
// is cleared and can safely be passed to vstr_free if it was heap allocated.
mp_obj_t mp_obj_new_str_from_vstr(const mp_obj_type_t *type, vstr_t *vstr) {
// if not a bytes object, look if a qstr with this data already exists
if (type == &mp_type_str) {
qstr q = qstr_find_strn(vstr->buf, vstr->len);
if (q != MP_QSTRnull) {
vstr_clear(vstr);
vstr->alloc = 0;
return MP_OBJ_NEW_QSTR(q);
}
}
// make a new str/bytes object
mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
o->base.type = type;
o->len = vstr->len;
o->hash = qstr_compute_hash((byte *)vstr->buf, vstr->len);
if (vstr->len + 1 == vstr->alloc) {
o->data = (byte *)vstr->buf;
} else {
o->data = (byte *)m_renew(char, vstr->buf, vstr->alloc, vstr->len + 1);
}
((byte *)o->data)[o->len] = '\0'; // add null byte
vstr->buf = NULL;
vstr->alloc = 0;
return MP_OBJ_FROM_PTR(o);
}
mp_obj_t mp_obj_new_str(const char *data, size_t len) {
qstr q = qstr_find_strn(data, len);
if (q != MP_QSTRnull) {
// qstr with this data already exists
return MP_OBJ_NEW_QSTR(q);
} else {
// no existing qstr, don't make one
return mp_obj_new_str_copy(&mp_type_str, (const byte *)data, len);
}
}
mp_obj_t mp_obj_str_intern(mp_obj_t str) {
GET_STR_DATA_LEN(str, data, len);
return mp_obj_new_str_via_qstr((const char *)data, len);
}
mp_obj_t mp_obj_str_intern_checked(mp_obj_t obj) {
size_t len;
const char *data = mp_obj_str_get_data(obj, &len);
return mp_obj_new_str_via_qstr((const char *)data, len);
}
mp_obj_t mp_obj_new_bytes(const byte *data, size_t len) {
return mp_obj_new_str_copy(&mp_type_bytes, data, len);
}
bool mp_obj_str_equal(mp_obj_t s1, mp_obj_t s2) {
if (mp_obj_is_qstr(s1) && mp_obj_is_qstr(s2)) {
return s1 == s2;
} else {
GET_STR_HASH(s1, h1);
GET_STR_HASH(s2, h2);
// If any of hashes is 0, it means it's not valid
if (h1 != 0 && h2 != 0 && h1 != h2) {
return false;
}
GET_STR_DATA_LEN(s1, d1, l1);
GET_STR_DATA_LEN(s2, d2, l2);
if (l1 != l2) {
return false;
}
return memcmp(d1, d2, l1) == 0;
}
}
STATIC NORETURN void bad_implicit_conversion(mp_obj_t self_in) {
#if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
mp_raise_TypeError(MP_ERROR_TEXT("can't convert to str implicitly"));
#else
const qstr src_name = mp_obj_get_type(self_in)->name;
mp_raise_msg_varg(&mp_type_TypeError,
MP_ERROR_TEXT("can't convert '%q' object to %q implicitly"),
src_name, src_name == MP_QSTR_str ? MP_QSTR_bytes : MP_QSTR_str);
#endif
}
// use this if you will anyway convert the string to a qstr
// will be more efficient for the case where it's already a qstr
qstr mp_obj_str_get_qstr(mp_obj_t self_in) {
if (mp_obj_is_qstr(self_in)) {
return MP_OBJ_QSTR_VALUE(self_in);
} else if (mp_obj_is_type(self_in, &mp_type_str)) {
mp_obj_str_t *self = MP_OBJ_TO_PTR(self_in);
return qstr_from_strn((char *)self->data, self->len);
} else {
bad_implicit_conversion(self_in);
}
}
// only use this function if you need the str data to be zero terminated
// at the moment all strings are zero terminated to help with C ASCIIZ compatibility
const char *mp_obj_str_get_str(mp_obj_t self_in) {
if (mp_obj_is_str_or_bytes(self_in)) {
GET_STR_DATA_LEN(self_in, s, l);
(void)l; // len unused
return (const char *)s;
} else {
bad_implicit_conversion(self_in);
}
}
const char *mp_obj_str_get_data(mp_obj_t self_in, size_t *len) {
if (mp_obj_is_str_or_bytes(self_in)) {
GET_STR_DATA_LEN(self_in, s, l);
*len = l;
return (const char *)s;
} else {
bad_implicit_conversion(self_in);
}
}
#if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_C || MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_D
const byte *mp_obj_str_get_data_no_check(mp_obj_t self_in, size_t *len) {
if (mp_obj_is_qstr(self_in)) {
return qstr_data(MP_OBJ_QSTR_VALUE(self_in), len);
} else {
*len = ((mp_obj_str_t *)MP_OBJ_TO_PTR(self_in))->len;
return ((mp_obj_str_t *)MP_OBJ_TO_PTR(self_in))->data;
}
}
#endif
/******************************************************************************/
/* str iterator */
typedef struct _mp_obj_str8_it_t {
mp_obj_base_t base;
mp_fun_1_t iternext;
mp_obj_t str;
size_t cur;
} mp_obj_str8_it_t;
#if !MICROPY_PY_BUILTINS_STR_UNICODE
STATIC mp_obj_t str_it_iternext(mp_obj_t self_in) {
mp_obj_str8_it_t *self = MP_OBJ_TO_PTR(self_in);
GET_STR_DATA_LEN(self->str, str, len);
if (self->cur < len) {
mp_obj_t o_out = mp_obj_new_str_via_qstr((const char *)str + self->cur, 1);
self->cur += 1;
return o_out;
} else {
return MP_OBJ_STOP_ITERATION;
}
}
STATIC mp_obj_t mp_obj_new_str_iterator(mp_obj_t str, mp_obj_iter_buf_t *iter_buf) {
assert(sizeof(mp_obj_str8_it_t) <= sizeof(mp_obj_iter_buf_t));
mp_obj_str8_it_t *o = (mp_obj_str8_it_t *)iter_buf;
o->base.type = &mp_type_polymorph_iter;
o->iternext = str_it_iternext;
o->str = str;
o->cur = 0;
return MP_OBJ_FROM_PTR(o);
}
#endif
STATIC mp_obj_t bytes_it_iternext(mp_obj_t self_in) {
mp_obj_str8_it_t *self = MP_OBJ_TO_PTR(self_in);
GET_STR_DATA_LEN(self->str, str, len);
if (self->cur < len) {
mp_obj_t o_out = MP_OBJ_NEW_SMALL_INT(str[self->cur]);
self->cur += 1;
return o_out;
} else {
return MP_OBJ_STOP_ITERATION;
}
}
mp_obj_t mp_obj_new_bytes_iterator(mp_obj_t str, mp_obj_iter_buf_t *iter_buf) {
assert(sizeof(mp_obj_str8_it_t) <= sizeof(mp_obj_iter_buf_t));
mp_obj_str8_it_t *o = (mp_obj_str8_it_t *)iter_buf;
o->base.type = &mp_type_polymorph_iter;
o->iternext = bytes_it_iternext;
o->str = str;
o->cur = 0;
return MP_OBJ_FROM_PTR(o);
}
| YifuLiu/AliOS-Things | components/py_engine/engine/py/objstr.c | C | apache-2.0 | 78,604 |
/*
* 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.
*/
#ifndef MICROPY_INCLUDED_PY_OBJSTR_H
#define MICROPY_INCLUDED_PY_OBJSTR_H
#include "py/obj.h"
typedef struct _mp_obj_str_t {
mp_obj_base_t base;
mp_uint_t hash;
// len == number of bytes used in data, alloc = len + 1 because (at the moment) we also append a null byte
size_t len;
const byte *data;
} mp_obj_str_t;
#define MP_DEFINE_STR_OBJ(obj_name, str) mp_obj_str_t obj_name = {{&mp_type_str}, 0, sizeof(str) - 1, (const byte *)str}
// use this macro to extract the string hash
// warning: the hash can be 0, meaning invalid, and must then be explicitly computed from the data
#define GET_STR_HASH(str_obj_in, str_hash) \
mp_uint_t str_hash; if (mp_obj_is_qstr(str_obj_in)) \
{ str_hash = qstr_hash(MP_OBJ_QSTR_VALUE(str_obj_in)); } else { str_hash = ((mp_obj_str_t *)MP_OBJ_TO_PTR(str_obj_in))->hash; }
// use this macro to extract the string length
#define GET_STR_LEN(str_obj_in, str_len) \
size_t str_len; if (mp_obj_is_qstr(str_obj_in)) \
{ str_len = qstr_len(MP_OBJ_QSTR_VALUE(str_obj_in)); } else { str_len = ((mp_obj_str_t *)MP_OBJ_TO_PTR(str_obj_in))->len; }
// use this macro to extract the string data and length
#if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_C || MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_D
const byte *mp_obj_str_get_data_no_check(mp_obj_t self_in, size_t *len);
#define GET_STR_DATA_LEN(str_obj_in, str_data, str_len) \
size_t str_len; const byte *str_data = mp_obj_str_get_data_no_check(str_obj_in, &str_len);
#else
#define GET_STR_DATA_LEN(str_obj_in, str_data, str_len) \
const byte *str_data; size_t str_len; if (mp_obj_is_qstr(str_obj_in)) \
{ str_data = qstr_data(MP_OBJ_QSTR_VALUE(str_obj_in), &str_len); } \
else { str_len = ((mp_obj_str_t *)MP_OBJ_TO_PTR(str_obj_in))->len; str_data = ((mp_obj_str_t *)MP_OBJ_TO_PTR(str_obj_in))->data; }
#endif
mp_obj_t mp_obj_str_make_new(const mp_obj_type_t *type_in, size_t n_args, size_t n_kw, const mp_obj_t *args);
void mp_str_print_json(const mp_print_t *print, const byte *str_data, size_t str_len);
mp_obj_t mp_obj_str_format(size_t n_args, const mp_obj_t *args, mp_map_t *kwargs);
mp_obj_t mp_obj_str_split(size_t n_args, const mp_obj_t *args);
mp_obj_t mp_obj_new_str_copy(const mp_obj_type_t *type, const byte *data, size_t len);
mp_obj_t mp_obj_new_str_of_type(const mp_obj_type_t *type, const byte *data, size_t len);
mp_obj_t mp_obj_str_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_in);
mp_int_t mp_obj_str_get_buffer(mp_obj_t self_in, mp_buffer_info_t *bufinfo, mp_uint_t flags);
const byte *str_index_to_ptr(const mp_obj_type_t *type, const byte *self_data, size_t self_len,
mp_obj_t index, bool is_slice);
const byte *find_subbytes(const byte *haystack, size_t hlen, const byte *needle, size_t nlen, int direction);
MP_DECLARE_CONST_FUN_OBJ_VAR_BETWEEN(str_encode_obj);
MP_DECLARE_CONST_FUN_OBJ_VAR_BETWEEN(str_find_obj);
MP_DECLARE_CONST_FUN_OBJ_VAR_BETWEEN(str_rfind_obj);
MP_DECLARE_CONST_FUN_OBJ_VAR_BETWEEN(str_index_obj);
MP_DECLARE_CONST_FUN_OBJ_VAR_BETWEEN(str_rindex_obj);
MP_DECLARE_CONST_FUN_OBJ_2(str_join_obj);
MP_DECLARE_CONST_FUN_OBJ_VAR_BETWEEN(str_split_obj);
MP_DECLARE_CONST_FUN_OBJ_KW(str_splitlines_obj);
MP_DECLARE_CONST_FUN_OBJ_VAR_BETWEEN(str_rsplit_obj);
MP_DECLARE_CONST_FUN_OBJ_VAR_BETWEEN(str_startswith_obj);
MP_DECLARE_CONST_FUN_OBJ_VAR_BETWEEN(str_endswith_obj);
MP_DECLARE_CONST_FUN_OBJ_VAR_BETWEEN(str_strip_obj);
MP_DECLARE_CONST_FUN_OBJ_VAR_BETWEEN(str_lstrip_obj);
MP_DECLARE_CONST_FUN_OBJ_VAR_BETWEEN(str_rstrip_obj);
MP_DECLARE_CONST_FUN_OBJ_KW(str_format_obj);
MP_DECLARE_CONST_FUN_OBJ_VAR_BETWEEN(str_replace_obj);
MP_DECLARE_CONST_FUN_OBJ_VAR_BETWEEN(str_count_obj);
MP_DECLARE_CONST_FUN_OBJ_2(str_partition_obj);
MP_DECLARE_CONST_FUN_OBJ_2(str_rpartition_obj);
MP_DECLARE_CONST_FUN_OBJ_2(str_center_obj);
MP_DECLARE_CONST_FUN_OBJ_1(str_lower_obj);
MP_DECLARE_CONST_FUN_OBJ_1(str_upper_obj);
MP_DECLARE_CONST_FUN_OBJ_1(str_isspace_obj);
MP_DECLARE_CONST_FUN_OBJ_1(str_isalpha_obj);
MP_DECLARE_CONST_FUN_OBJ_1(str_isdigit_obj);
MP_DECLARE_CONST_FUN_OBJ_1(str_isupper_obj);
MP_DECLARE_CONST_FUN_OBJ_1(str_islower_obj);
MP_DECLARE_CONST_FUN_OBJ_VAR_BETWEEN(bytes_decode_obj);
#endif // MICROPY_INCLUDED_PY_OBJSTR_H
| YifuLiu/AliOS-Things | components/py_engine/engine/py/objstr.h | C | apache-2.0 | 5,448 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2013, 2014 Damien P. George
* Copyright (c) 2014-2017 Paul Sokolovsky
*
* 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 <stdio.h>
#include <string.h>
#include "py/objstr.h"
#include "py/objstringio.h"
#include "py/runtime.h"
#include "py/stream.h"
#if MICROPY_PY_IO
#if MICROPY_CPYTHON_COMPAT
STATIC void check_stringio_is_open(const mp_obj_stringio_t *o) {
if (o->vstr == NULL) {
mp_raise_ValueError(MP_ERROR_TEXT("I/O operation on closed file"));
}
}
#else
#define check_stringio_is_open(o)
#endif
STATIC void stringio_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
(void)kind;
mp_obj_stringio_t *self = MP_OBJ_TO_PTR(self_in);
mp_printf(print, self->base.type == &mp_type_stringio ? "<io.StringIO 0x%x>" : "<io.BytesIO 0x%x>", self);
}
STATIC mp_uint_t stringio_read(mp_obj_t o_in, void *buf, mp_uint_t size, int *errcode) {
(void)errcode;
mp_obj_stringio_t *o = MP_OBJ_TO_PTR(o_in);
check_stringio_is_open(o);
if (o->vstr->len <= o->pos) { // read to EOF, or seeked to EOF or beyond
return 0;
}
mp_uint_t remaining = o->vstr->len - o->pos;
if (size > remaining) {
size = remaining;
}
memcpy(buf, o->vstr->buf + o->pos, size);
o->pos += size;
return size;
}
STATIC void stringio_copy_on_write(mp_obj_stringio_t *o) {
const void *buf = o->vstr->buf;
o->vstr->buf = m_new(char, o->vstr->len);
o->vstr->fixed_buf = false;
o->ref_obj = MP_OBJ_NULL;
memcpy(o->vstr->buf, buf, o->vstr->len);
}
STATIC mp_uint_t stringio_write(mp_obj_t o_in, const void *buf, mp_uint_t size, int *errcode) {
(void)errcode;
mp_obj_stringio_t *o = MP_OBJ_TO_PTR(o_in);
check_stringio_is_open(o);
if (o->vstr->fixed_buf) {
stringio_copy_on_write(o);
}
mp_uint_t new_pos = o->pos + size;
if (new_pos < size) {
// Writing <size> bytes will overflow o->pos beyond limit of mp_uint_t.
*errcode = MP_EFBIG;
return MP_STREAM_ERROR;
}
mp_uint_t org_len = o->vstr->len;
if (new_pos > o->vstr->alloc) {
// Take all what's already allocated...
o->vstr->len = o->vstr->alloc;
// ... and add more
vstr_add_len(o->vstr, new_pos - o->vstr->alloc);
}
// If there was a seek past EOF, clear the hole
if (o->pos > org_len) {
memset(o->vstr->buf + org_len, 0, o->pos - org_len);
}
memcpy(o->vstr->buf + o->pos, buf, size);
o->pos = new_pos;
if (new_pos > o->vstr->len) {
o->vstr->len = new_pos;
}
return size;
}
STATIC mp_uint_t stringio_ioctl(mp_obj_t o_in, mp_uint_t request, uintptr_t arg, int *errcode) {
(void)errcode;
mp_obj_stringio_t *o = MP_OBJ_TO_PTR(o_in);
switch (request) {
case MP_STREAM_SEEK: {
struct mp_stream_seek_t *s = (struct mp_stream_seek_t *)arg;
mp_uint_t ref = 0;
switch (s->whence) {
case MP_SEEK_CUR:
ref = o->pos;
break;
case MP_SEEK_END:
ref = o->vstr->len;
break;
}
mp_uint_t new_pos = ref + s->offset;
// For MP_SEEK_SET, offset is unsigned
if (s->whence != MP_SEEK_SET && s->offset < 0) {
if (new_pos > ref) {
// Negative offset from SEEK_CUR or SEEK_END went past 0.
// CPython sets position to 0, POSIX returns an EINVAL error
new_pos = 0;
}
} else if (new_pos < ref) {
// positive offset went beyond the limit of mp_uint_t
*errcode = MP_EINVAL; // replace with MP_EOVERFLOW when defined
return MP_STREAM_ERROR;
}
s->offset = o->pos = new_pos;
return 0;
}
case MP_STREAM_FLUSH:
return 0;
case MP_STREAM_CLOSE:
#if MICROPY_CPYTHON_COMPAT
vstr_free(o->vstr);
o->vstr = NULL;
#else
vstr_clear(o->vstr);
o->vstr->alloc = 0;
o->vstr->len = 0;
o->pos = 0;
#endif
return 0;
default:
*errcode = MP_EINVAL;
return MP_STREAM_ERROR;
}
}
#define STREAM_TO_CONTENT_TYPE(o) (((o)->base.type == &mp_type_stringio) ? &mp_type_str : &mp_type_bytes)
STATIC mp_obj_t stringio_getvalue(mp_obj_t self_in) {
mp_obj_stringio_t *self = MP_OBJ_TO_PTR(self_in);
check_stringio_is_open(self);
// TODO: Try to avoid copying string
return mp_obj_new_str_of_type(STREAM_TO_CONTENT_TYPE(self), (byte *)self->vstr->buf, self->vstr->len);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(stringio_getvalue_obj, stringio_getvalue);
STATIC mp_obj_t stringio___exit__(size_t n_args, const mp_obj_t *args) {
(void)n_args;
return mp_stream_close(args[0]);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(stringio___exit___obj, 4, 4, stringio___exit__);
STATIC mp_obj_stringio_t *stringio_new(const mp_obj_type_t *type) {
mp_obj_stringio_t *o = m_new_obj(mp_obj_stringio_t);
o->base.type = type;
o->pos = 0;
o->ref_obj = MP_OBJ_NULL;
return o;
}
STATIC mp_obj_t stringio_make_new(const mp_obj_type_t *type_in, size_t n_args, size_t n_kw, const mp_obj_t *args) {
(void)n_kw; // TODO check n_kw==0
mp_uint_t sz = 16;
bool initdata = false;
mp_buffer_info_t bufinfo;
mp_obj_stringio_t *o = stringio_new(type_in);
if (n_args > 0) {
if (mp_obj_is_int(args[0])) {
sz = mp_obj_get_int(args[0]);
} else {
mp_get_buffer_raise(args[0], &bufinfo, MP_BUFFER_READ);
if (mp_obj_is_str_or_bytes(args[0])) {
o->vstr = m_new_obj(vstr_t);
vstr_init_fixed_buf(o->vstr, bufinfo.len, bufinfo.buf);
o->vstr->len = bufinfo.len;
o->ref_obj = args[0];
return MP_OBJ_FROM_PTR(o);
}
sz = bufinfo.len;
initdata = true;
}
}
o->vstr = vstr_new(sz);
if (initdata) {
stringio_write(MP_OBJ_FROM_PTR(o), bufinfo.buf, bufinfo.len, NULL);
// Cur ptr is always at the beginning of buffer at the construction
o->pos = 0;
}
return MP_OBJ_FROM_PTR(o);
}
STATIC const mp_rom_map_elem_t stringio_locals_dict_table[] = {
{ MP_ROM_QSTR(MP_QSTR_read), MP_ROM_PTR(&mp_stream_read_obj) },
{ MP_ROM_QSTR(MP_QSTR_readinto), MP_ROM_PTR(&mp_stream_readinto_obj) },
{ MP_ROM_QSTR(MP_QSTR_readline), MP_ROM_PTR(&mp_stream_unbuffered_readline_obj) },
{ MP_ROM_QSTR(MP_QSTR_write), MP_ROM_PTR(&mp_stream_write_obj) },
{ MP_ROM_QSTR(MP_QSTR_seek), MP_ROM_PTR(&mp_stream_seek_obj) },
{ MP_ROM_QSTR(MP_QSTR_tell), MP_ROM_PTR(&mp_stream_tell_obj) },
{ MP_ROM_QSTR(MP_QSTR_flush), MP_ROM_PTR(&mp_stream_flush_obj) },
{ MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&mp_stream_close_obj) },
{ MP_ROM_QSTR(MP_QSTR_getvalue), MP_ROM_PTR(&stringio_getvalue_obj) },
{ MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&mp_identity_obj) },
{ MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&stringio___exit___obj) },
};
STATIC MP_DEFINE_CONST_DICT(stringio_locals_dict, stringio_locals_dict_table);
STATIC const mp_stream_p_t stringio_stream_p = {
.read = stringio_read,
.write = stringio_write,
.ioctl = stringio_ioctl,
.is_text = true,
};
const mp_obj_type_t mp_type_stringio = {
{ &mp_type_type },
.name = MP_QSTR_StringIO,
.print = stringio_print,
.make_new = stringio_make_new,
.getiter = mp_identity_getiter,
.iternext = mp_stream_unbuffered_iter,
.protocol = &stringio_stream_p,
.locals_dict = (mp_obj_dict_t *)&stringio_locals_dict,
};
#if MICROPY_PY_IO_BYTESIO
STATIC const mp_stream_p_t bytesio_stream_p = {
.read = stringio_read,
.write = stringio_write,
.ioctl = stringio_ioctl,
};
const mp_obj_type_t mp_type_bytesio = {
{ &mp_type_type },
.name = MP_QSTR_BytesIO,
.print = stringio_print,
.make_new = stringio_make_new,
.getiter = mp_identity_getiter,
.iternext = mp_stream_unbuffered_iter,
.protocol = &bytesio_stream_p,
.locals_dict = (mp_obj_dict_t *)&stringio_locals_dict,
};
#endif
#endif
| YifuLiu/AliOS-Things | components/py_engine/engine/py/objstringio.c | C | apache-2.0 | 9,465 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2016 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.
*/
#ifndef MICROPY_INCLUDED_PY_OBJSTRINGIO_H
#define MICROPY_INCLUDED_PY_OBJSTRINGIO_H
#include "py/obj.h"
typedef struct _mp_obj_stringio_t {
mp_obj_base_t base;
vstr_t *vstr;
// StringIO has single pointer used for both reading and writing
mp_uint_t pos;
// Underlying object buffered by this StringIO
mp_obj_t ref_obj;
} mp_obj_stringio_t;
#endif // MICROPY_INCLUDED_PY_OBJSTRINGIO_H
| YifuLiu/AliOS-Things | components/py_engine/engine/py/objstringio.h | C | apache-2.0 | 1,636 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2013, 2014 Damien P. George
* Copyright (c) 2014-2016 Paul Sokolovsky
*
* 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 <string.h>
#include <assert.h>
#include "py/objstr.h"
#include "py/objlist.h"
#include "py/runtime.h"
#if MICROPY_PY_BUILTINS_STR_UNICODE
STATIC mp_obj_t mp_obj_new_str_iterator(mp_obj_t str, mp_obj_iter_buf_t *iter_buf);
/******************************************************************************/
/* str */
STATIC void uni_print_quoted(const mp_print_t *print, const byte *str_data, uint str_len) {
// this escapes characters, but it will be very slow to print (calling print many times)
bool has_single_quote = false;
bool has_double_quote = false;
for (const byte *s = str_data, *top = str_data + str_len; !has_double_quote && s < top; s++) {
if (*s == '\'') {
has_single_quote = true;
} else if (*s == '"') {
has_double_quote = true;
}
}
unichar quote_char = '\'';
if (has_single_quote && !has_double_quote) {
quote_char = '"';
}
mp_printf(print, "%c", quote_char);
const byte *s = str_data, *top = str_data + str_len;
while (s < top) {
unichar ch;
ch = utf8_get_char(s);
s = utf8_next_char(s);
if (ch == quote_char) {
mp_printf(print, "\\%c", quote_char);
} else if (ch == '\\') {
mp_print_str(print, "\\\\");
} else if (32 <= ch && ch <= 126) {
mp_printf(print, "%c", ch);
} else if (ch == '\n') {
mp_print_str(print, "\\n");
} else if (ch == '\r') {
mp_print_str(print, "\\r");
} else if (ch == '\t') {
mp_print_str(print, "\\t");
} else if (ch < 0x100) {
mp_printf(print, "\\x%02x", ch);
} else if (ch < 0x10000) {
mp_printf(print, "\\u%04x", ch);
} else {
mp_printf(print, "\\U%08x", ch);
}
}
mp_printf(print, "%c", quote_char);
}
STATIC void uni_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
GET_STR_DATA_LEN(self_in, str_data, str_len);
#if MICROPY_PY_UJSON
if (kind == PRINT_JSON) {
mp_str_print_json(print, str_data, str_len);
return;
}
#endif
if (kind == PRINT_STR) {
print->print_strn(print->data, (const char *)str_data, str_len);
} else {
uni_print_quoted(print, str_data, str_len);
}
}
STATIC mp_obj_t uni_unary_op(mp_unary_op_t op, mp_obj_t self_in) {
GET_STR_DATA_LEN(self_in, str_data, str_len);
switch (op) {
case MP_UNARY_OP_BOOL:
return mp_obj_new_bool(str_len != 0);
case MP_UNARY_OP_LEN:
return MP_OBJ_NEW_SMALL_INT(utf8_charlen(str_data, str_len));
default:
return MP_OBJ_NULL; // op not supported
}
}
// Convert an index into a pointer to its lead byte. Out of bounds indexing will raise IndexError or
// be capped to the first/last character of the string, depending on is_slice.
const byte *str_index_to_ptr(const mp_obj_type_t *type, const byte *self_data, size_t self_len,
mp_obj_t index, bool is_slice) {
// All str functions also handle bytes objects, and they call str_index_to_ptr(),
// so it must handle bytes.
if (type == &mp_type_bytes) {
// Taken from objstr.c:str_index_to_ptr()
size_t index_val = mp_get_index(type, self_len, index, is_slice);
return self_data + index_val;
}
mp_int_t i;
// Copied from mp_get_index; I don't want bounds checking, just give me
// the integer as-is. (I can't bounds-check without scanning the whole
// string; an out-of-bounds index will be caught in the loops below.)
if (mp_obj_is_small_int(index)) {
i = MP_OBJ_SMALL_INT_VALUE(index);
} else if (!mp_obj_get_int_maybe(index, &i)) {
mp_raise_msg_varg(&mp_type_TypeError, MP_ERROR_TEXT("string indices must be integers, not %s"), mp_obj_get_type_str(index));
}
const byte *s, *top = self_data + self_len;
if (i < 0) {
// Negative indexing is performed by counting from the end of the string.
for (s = top - 1; i; --s) {
if (s < self_data) {
if (is_slice) {
return self_data;
}
mp_raise_msg(&mp_type_IndexError, MP_ERROR_TEXT("string index out of range"));
}
if (!UTF8_IS_CONT(*s)) {
++i;
}
}
++s;
} else {
// Positive indexing, correspondingly, counts from the start of the string.
// It's assumed that negative indexing will generally be used with small
// absolute values (eg str[-1], not str[-1000000]), which means it'll be
// more efficient this way.
s = self_data;
while (1) {
// First check out-of-bounds
if (s >= top) {
if (is_slice) {
return top;
}
mp_raise_msg(&mp_type_IndexError, MP_ERROR_TEXT("string index out of range"));
}
// Then check completion
if (i-- == 0) {
break;
}
// Then skip UTF-8 char
++s;
while (UTF8_IS_CONT(*s)) {
++s;
}
}
}
return s;
}
STATIC mp_obj_t str_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) {
const mp_obj_type_t *type = mp_obj_get_type(self_in);
assert(type == &mp_type_str);
GET_STR_DATA_LEN(self_in, self_data, self_len);
if (value == MP_OBJ_SENTINEL) {
// load
#if MICROPY_PY_BUILTINS_SLICE
if (mp_obj_is_type(index, &mp_type_slice)) {
mp_obj_t ostart, ostop, ostep;
mp_obj_slice_t *slice = MP_OBJ_TO_PTR(index);
ostart = slice->start;
ostop = slice->stop;
ostep = slice->step;
if (ostep != mp_const_none && ostep != MP_OBJ_NEW_SMALL_INT(1)) {
mp_raise_NotImplementedError(MP_ERROR_TEXT("only slices with step=1 (aka None) are supported"));
}
const byte *pstart, *pstop;
if (ostart != mp_const_none) {
pstart = str_index_to_ptr(type, self_data, self_len, ostart, true);
} else {
pstart = self_data;
}
if (ostop != mp_const_none) {
// pstop will point just after the stop character. This depends on
// the \0 at the end of the string.
pstop = str_index_to_ptr(type, self_data, self_len, ostop, true);
} else {
pstop = self_data + self_len;
}
if (pstop < pstart) {
return MP_OBJ_NEW_QSTR(MP_QSTR_);
}
return mp_obj_new_str_of_type(type, (const byte *)pstart, pstop - pstart);
}
#endif
const byte *s = str_index_to_ptr(type, self_data, self_len, index, false);
int len = 1;
if (UTF8_IS_NONASCII(*s)) {
// Count the number of 1 bits (after the first)
for (char mask = 0x40; *s & mask; mask >>= 1) {
++len;
}
}
return mp_obj_new_str_via_qstr((const char *)s, len); // This will create a one-character string
} else {
return MP_OBJ_NULL; // op not supported
}
}
STATIC const mp_rom_map_elem_t struni_locals_dict_table[] = {
#if MICROPY_CPYTHON_COMPAT
{ MP_ROM_QSTR(MP_QSTR_encode), MP_ROM_PTR(&str_encode_obj) },
#endif
{ MP_ROM_QSTR(MP_QSTR_find), MP_ROM_PTR(&str_find_obj) },
{ MP_ROM_QSTR(MP_QSTR_rfind), MP_ROM_PTR(&str_rfind_obj) },
{ MP_ROM_QSTR(MP_QSTR_index), MP_ROM_PTR(&str_index_obj) },
{ MP_ROM_QSTR(MP_QSTR_rindex), MP_ROM_PTR(&str_rindex_obj) },
{ MP_ROM_QSTR(MP_QSTR_join), MP_ROM_PTR(&str_join_obj) },
{ MP_ROM_QSTR(MP_QSTR_split), MP_ROM_PTR(&str_split_obj) },
#if MICROPY_PY_BUILTINS_STR_SPLITLINES
{ MP_ROM_QSTR(MP_QSTR_splitlines), MP_ROM_PTR(&str_splitlines_obj) },
#endif
{ MP_ROM_QSTR(MP_QSTR_rsplit), MP_ROM_PTR(&str_rsplit_obj) },
{ MP_ROM_QSTR(MP_QSTR_startswith), MP_ROM_PTR(&str_startswith_obj) },
{ MP_ROM_QSTR(MP_QSTR_endswith), MP_ROM_PTR(&str_endswith_obj) },
{ MP_ROM_QSTR(MP_QSTR_strip), MP_ROM_PTR(&str_strip_obj) },
{ MP_ROM_QSTR(MP_QSTR_lstrip), MP_ROM_PTR(&str_lstrip_obj) },
{ MP_ROM_QSTR(MP_QSTR_rstrip), MP_ROM_PTR(&str_rstrip_obj) },
{ MP_ROM_QSTR(MP_QSTR_format), MP_ROM_PTR(&str_format_obj) },
{ MP_ROM_QSTR(MP_QSTR_replace), MP_ROM_PTR(&str_replace_obj) },
#if MICROPY_PY_BUILTINS_STR_COUNT
{ MP_ROM_QSTR(MP_QSTR_count), MP_ROM_PTR(&str_count_obj) },
#endif
#if MICROPY_PY_BUILTINS_STR_PARTITION
{ MP_ROM_QSTR(MP_QSTR_partition), MP_ROM_PTR(&str_partition_obj) },
{ MP_ROM_QSTR(MP_QSTR_rpartition), MP_ROM_PTR(&str_rpartition_obj) },
#endif
#if MICROPY_PY_BUILTINS_STR_CENTER
{ MP_ROM_QSTR(MP_QSTR_center), MP_ROM_PTR(&str_center_obj) },
#endif
{ MP_ROM_QSTR(MP_QSTR_lower), MP_ROM_PTR(&str_lower_obj) },
{ MP_ROM_QSTR(MP_QSTR_upper), MP_ROM_PTR(&str_upper_obj) },
{ MP_ROM_QSTR(MP_QSTR_isspace), MP_ROM_PTR(&str_isspace_obj) },
{ MP_ROM_QSTR(MP_QSTR_isalpha), MP_ROM_PTR(&str_isalpha_obj) },
{ MP_ROM_QSTR(MP_QSTR_isdigit), MP_ROM_PTR(&str_isdigit_obj) },
{ MP_ROM_QSTR(MP_QSTR_isupper), MP_ROM_PTR(&str_isupper_obj) },
{ MP_ROM_QSTR(MP_QSTR_islower), MP_ROM_PTR(&str_islower_obj) },
};
STATIC MP_DEFINE_CONST_DICT(struni_locals_dict, struni_locals_dict_table);
const mp_obj_type_t mp_type_str = {
{ &mp_type_type },
.name = MP_QSTR_str,
.print = uni_print,
.make_new = mp_obj_str_make_new,
.unary_op = uni_unary_op,
.binary_op = mp_obj_str_binary_op,
.subscr = str_subscr,
.getiter = mp_obj_new_str_iterator,
.buffer_p = { .get_buffer = mp_obj_str_get_buffer },
.locals_dict = (mp_obj_dict_t *)&struni_locals_dict,
};
/******************************************************************************/
/* str iterator */
typedef struct _mp_obj_str_it_t {
mp_obj_base_t base;
mp_fun_1_t iternext;
mp_obj_t str;
size_t cur;
} mp_obj_str_it_t;
STATIC mp_obj_t str_it_iternext(mp_obj_t self_in) {
mp_obj_str_it_t *self = MP_OBJ_TO_PTR(self_in);
GET_STR_DATA_LEN(self->str, str, len);
if (self->cur < len) {
const byte *cur = str + self->cur;
const byte *end = utf8_next_char(str + self->cur);
mp_obj_t o_out = mp_obj_new_str_via_qstr((const char *)cur, end - cur);
self->cur += end - cur;
return o_out;
} else {
return MP_OBJ_STOP_ITERATION;
}
}
STATIC mp_obj_t mp_obj_new_str_iterator(mp_obj_t str, mp_obj_iter_buf_t *iter_buf) {
assert(sizeof(mp_obj_str_it_t) <= sizeof(mp_obj_iter_buf_t));
mp_obj_str_it_t *o = (mp_obj_str_it_t *)iter_buf;
o->base.type = &mp_type_polymorph_iter;
o->iternext = str_it_iternext;
o->str = str;
o->cur = 0;
return MP_OBJ_FROM_PTR(o);
}
#endif // MICROPY_PY_BUILTINS_STR_UNICODE
| YifuLiu/AliOS-Things | components/py_engine/engine/py/objstrunicode.c | C | apache-2.0 | 12,397 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2013, 2014 Damien P. George
* Copyright (c) 2014-2017 Paul Sokolovsky
*
* 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 <string.h>
#include <assert.h>
#include "py/objtuple.h"
#include "py/runtime.h"
// type check is done on getiter method to allow tuple, namedtuple, attrtuple
#define mp_obj_is_tuple_compatible(o) (mp_obj_get_type(o)->getiter == mp_obj_tuple_getiter)
/******************************************************************************/
/* tuple */
void mp_obj_tuple_print(const mp_print_t *print, mp_obj_t o_in, mp_print_kind_t kind) {
mp_obj_tuple_t *o = MP_OBJ_TO_PTR(o_in);
const char *item_separator = ", ";
if (MICROPY_PY_UJSON && kind == PRINT_JSON) {
mp_print_str(print, "[");
#if MICROPY_PY_UJSON_SEPARATORS
item_separator = MP_PRINT_GET_EXT(print)->item_separator;
#endif
} else {
mp_print_str(print, "(");
kind = PRINT_REPR;
}
for (size_t i = 0; i < o->len; i++) {
if (i > 0) {
mp_print_str(print, item_separator);
}
mp_obj_print_helper(print, o->items[i], kind);
}
if (MICROPY_PY_UJSON && kind == PRINT_JSON) {
mp_print_str(print, "]");
} else {
if (o->len == 1) {
mp_print_str(print, ",");
}
mp_print_str(print, ")");
}
}
STATIC mp_obj_t mp_obj_tuple_make_new(const mp_obj_type_t *type_in, size_t n_args, size_t n_kw, const mp_obj_t *args) {
(void)type_in;
mp_arg_check_num(n_args, n_kw, 0, 1, false);
switch (n_args) {
case 0:
// return a empty tuple
return mp_const_empty_tuple;
case 1:
default: {
// 1 argument, an iterable from which we make a new tuple
if (mp_obj_is_type(args[0], &mp_type_tuple)) {
return args[0];
}
// TODO optimise for cases where we know the length of the iterator
size_t alloc = 4;
size_t len = 0;
mp_obj_t *items = m_new(mp_obj_t, alloc);
mp_obj_t iterable = mp_getiter(args[0], NULL);
mp_obj_t item;
while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
if (len >= alloc) {
items = m_renew(mp_obj_t, items, alloc, alloc * 2);
alloc *= 2;
}
items[len++] = item;
}
mp_obj_t tuple = mp_obj_new_tuple(len, items);
m_del(mp_obj_t, items, alloc);
return tuple;
}
}
}
// Don't pass MP_BINARY_OP_NOT_EQUAL here
STATIC mp_obj_t tuple_cmp_helper(mp_uint_t op, mp_obj_t self_in, mp_obj_t another_in) {
mp_check_self(mp_obj_is_tuple_compatible(self_in));
const mp_obj_type_t *another_type = mp_obj_get_type(another_in);
mp_obj_tuple_t *self = MP_OBJ_TO_PTR(self_in);
if (another_type->getiter != mp_obj_tuple_getiter) {
// Slow path for user subclasses
another_in = mp_obj_cast_to_native_base(another_in, MP_OBJ_FROM_PTR(&mp_type_tuple));
if (another_in == MP_OBJ_NULL) {
return MP_OBJ_NULL;
}
}
mp_obj_tuple_t *another = MP_OBJ_TO_PTR(another_in);
return mp_obj_new_bool(mp_seq_cmp_objs(op, self->items, self->len, another->items, another->len));
}
mp_obj_t mp_obj_tuple_unary_op(mp_unary_op_t op, mp_obj_t self_in) {
mp_obj_tuple_t *self = MP_OBJ_TO_PTR(self_in);
switch (op) {
case MP_UNARY_OP_BOOL:
return mp_obj_new_bool(self->len != 0);
case MP_UNARY_OP_HASH: {
// start hash with pointer to empty tuple, to make it fairly unique
mp_int_t hash = (mp_int_t)mp_const_empty_tuple;
for (size_t i = 0; i < self->len; i++) {
hash += MP_OBJ_SMALL_INT_VALUE(mp_unary_op(MP_UNARY_OP_HASH, self->items[i]));
}
return MP_OBJ_NEW_SMALL_INT(hash);
}
case MP_UNARY_OP_LEN:
return MP_OBJ_NEW_SMALL_INT(self->len);
default:
return MP_OBJ_NULL; // op not supported
}
}
mp_obj_t mp_obj_tuple_binary_op(mp_binary_op_t op, mp_obj_t lhs, mp_obj_t rhs) {
mp_obj_tuple_t *o = MP_OBJ_TO_PTR(lhs);
switch (op) {
case MP_BINARY_OP_ADD:
case MP_BINARY_OP_INPLACE_ADD: {
if (!mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(mp_obj_get_type(rhs)), MP_OBJ_FROM_PTR(&mp_type_tuple))) {
return MP_OBJ_NULL; // op not supported
}
mp_obj_tuple_t *p = MP_OBJ_TO_PTR(rhs);
mp_obj_tuple_t *s = MP_OBJ_TO_PTR(mp_obj_new_tuple(o->len + p->len, NULL));
mp_seq_cat(s->items, o->items, o->len, p->items, p->len, mp_obj_t);
return MP_OBJ_FROM_PTR(s);
}
case MP_BINARY_OP_MULTIPLY:
case MP_BINARY_OP_INPLACE_MULTIPLY: {
mp_int_t n;
if (!mp_obj_get_int_maybe(rhs, &n)) {
return MP_OBJ_NULL; // op not supported
}
if (n <= 0) {
return mp_const_empty_tuple;
}
mp_obj_tuple_t *s = MP_OBJ_TO_PTR(mp_obj_new_tuple(o->len * n, NULL));
mp_seq_multiply(o->items, sizeof(*o->items), o->len, n, s->items);
return MP_OBJ_FROM_PTR(s);
}
case MP_BINARY_OP_EQUAL:
case MP_BINARY_OP_LESS:
case MP_BINARY_OP_LESS_EQUAL:
case MP_BINARY_OP_MORE:
case MP_BINARY_OP_MORE_EQUAL:
return tuple_cmp_helper(op, lhs, rhs);
default:
return MP_OBJ_NULL; // op not supported
}
}
mp_obj_t mp_obj_tuple_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) {
if (value == MP_OBJ_SENTINEL) {
// load
mp_obj_tuple_t *self = MP_OBJ_TO_PTR(self_in);
#if MICROPY_PY_BUILTINS_SLICE
if (mp_obj_is_type(index, &mp_type_slice)) {
mp_bound_slice_t slice;
if (!mp_seq_get_fast_slice_indexes(self->len, index, &slice)) {
mp_raise_NotImplementedError(MP_ERROR_TEXT("only slices with step=1 (aka None) are supported"));
}
mp_obj_tuple_t *res = MP_OBJ_TO_PTR(mp_obj_new_tuple(slice.stop - slice.start, NULL));
mp_seq_copy(res->items, self->items + slice.start, res->len, mp_obj_t);
return MP_OBJ_FROM_PTR(res);
}
#endif
size_t index_value = mp_get_index(self->base.type, self->len, index, false);
return self->items[index_value];
} else {
return MP_OBJ_NULL; // op not supported
}
}
STATIC mp_obj_t tuple_count(mp_obj_t self_in, mp_obj_t value) {
mp_check_self(mp_obj_is_type(self_in, &mp_type_tuple));
mp_obj_tuple_t *self = MP_OBJ_TO_PTR(self_in);
return mp_seq_count_obj(self->items, self->len, value);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(tuple_count_obj, tuple_count);
STATIC mp_obj_t tuple_index(size_t n_args, const mp_obj_t *args) {
mp_check_self(mp_obj_is_type(args[0], &mp_type_tuple));
mp_obj_tuple_t *self = MP_OBJ_TO_PTR(args[0]);
return mp_seq_index_obj(self->items, self->len, n_args, args);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(tuple_index_obj, 2, 4, tuple_index);
STATIC const mp_rom_map_elem_t tuple_locals_dict_table[] = {
{ MP_ROM_QSTR(MP_QSTR_count), MP_ROM_PTR(&tuple_count_obj) },
{ MP_ROM_QSTR(MP_QSTR_index), MP_ROM_PTR(&tuple_index_obj) },
};
STATIC MP_DEFINE_CONST_DICT(tuple_locals_dict, tuple_locals_dict_table);
const mp_obj_type_t mp_type_tuple = {
{ &mp_type_type },
.name = MP_QSTR_tuple,
.print = mp_obj_tuple_print,
.make_new = mp_obj_tuple_make_new,
.unary_op = mp_obj_tuple_unary_op,
.binary_op = mp_obj_tuple_binary_op,
.subscr = mp_obj_tuple_subscr,
.getiter = mp_obj_tuple_getiter,
.locals_dict = (mp_obj_dict_t *)&tuple_locals_dict,
};
// the zero-length tuple
const mp_obj_tuple_t mp_const_empty_tuple_obj = {{&mp_type_tuple}, 0};
mp_obj_t mp_obj_new_tuple(size_t n, const mp_obj_t *items) {
if (n == 0) {
return mp_const_empty_tuple;
}
mp_obj_tuple_t *o = m_new_obj_var(mp_obj_tuple_t, mp_obj_t, n);
o->base.type = &mp_type_tuple;
o->len = n;
if (items) {
for (size_t i = 0; i < n; i++) {
o->items[i] = items[i];
}
}
return MP_OBJ_FROM_PTR(o);
}
void mp_obj_tuple_get(mp_obj_t self_in, size_t *len, mp_obj_t **items) {
assert(mp_obj_is_tuple_compatible(self_in));
mp_obj_tuple_t *self = MP_OBJ_TO_PTR(self_in);
*len = self->len;
*items = &self->items[0];
}
void mp_obj_tuple_del(mp_obj_t self_in) {
assert(mp_obj_is_type(self_in, &mp_type_tuple));
mp_obj_tuple_t *self = MP_OBJ_TO_PTR(self_in);
m_del_var(mp_obj_tuple_t, mp_obj_t, self->len, self);
}
/******************************************************************************/
/* tuple iterator */
typedef struct _mp_obj_tuple_it_t {
mp_obj_base_t base;
mp_fun_1_t iternext;
mp_obj_tuple_t *tuple;
size_t cur;
} mp_obj_tuple_it_t;
STATIC mp_obj_t tuple_it_iternext(mp_obj_t self_in) {
mp_obj_tuple_it_t *self = MP_OBJ_TO_PTR(self_in);
if (self->cur < self->tuple->len) {
mp_obj_t o_out = self->tuple->items[self->cur];
self->cur += 1;
return o_out;
} else {
return MP_OBJ_STOP_ITERATION;
}
}
mp_obj_t mp_obj_tuple_getiter(mp_obj_t o_in, mp_obj_iter_buf_t *iter_buf) {
assert(sizeof(mp_obj_tuple_it_t) <= sizeof(mp_obj_iter_buf_t));
mp_obj_tuple_it_t *o = (mp_obj_tuple_it_t *)iter_buf;
o->base.type = &mp_type_polymorph_iter;
o->iternext = tuple_it_iternext;
o->tuple = MP_OBJ_TO_PTR(o_in);
o->cur = 0;
return MP_OBJ_FROM_PTR(o);
}
| YifuLiu/AliOS-Things | components/py_engine/engine/py/objtuple.c | C | apache-2.0 | 10,956 |
/*
* 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.
*/
#ifndef MICROPY_INCLUDED_PY_OBJTUPLE_H
#define MICROPY_INCLUDED_PY_OBJTUPLE_H
#include "py/obj.h"
typedef struct _mp_obj_tuple_t {
mp_obj_base_t base;
size_t len;
mp_obj_t items[];
} mp_obj_tuple_t;
typedef struct _mp_rom_obj_tuple_t {
mp_obj_base_t base;
size_t len;
mp_rom_obj_t items[];
} mp_rom_obj_tuple_t;
void mp_obj_tuple_print(const mp_print_t *print, mp_obj_t o_in, mp_print_kind_t kind);
mp_obj_t mp_obj_tuple_unary_op(mp_unary_op_t op, mp_obj_t self_in);
mp_obj_t mp_obj_tuple_binary_op(mp_binary_op_t op, mp_obj_t lhs, mp_obj_t rhs);
mp_obj_t mp_obj_tuple_subscr(mp_obj_t base, mp_obj_t index, mp_obj_t value);
mp_obj_t mp_obj_tuple_getiter(mp_obj_t o_in, mp_obj_iter_buf_t *iter_buf);
extern const mp_obj_type_t mp_type_attrtuple;
#define MP_DEFINE_ATTRTUPLE(tuple_obj_name, fields, nitems, ...) \
const mp_rom_obj_tuple_t tuple_obj_name = { \
.base = {&mp_type_attrtuple}, \
.len = nitems, \
.items = { __VA_ARGS__, MP_ROM_PTR((void *)fields) } \
}
#if MICROPY_PY_COLLECTIONS
void mp_obj_attrtuple_print_helper(const mp_print_t *print, const qstr *fields, mp_obj_tuple_t *o);
#endif
mp_obj_t mp_obj_new_attrtuple(const qstr *fields, size_t n, const mp_obj_t *items);
#endif // MICROPY_INCLUDED_PY_OBJTUPLE_H
| YifuLiu/AliOS-Things | components/py_engine/engine/py/objtuple.h | C | apache-2.0 | 2,519 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2013-2018 Damien P. George
* Copyright (c) 2014-2018 Paul Sokolovsky
*
* 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 <stdio.h>
#include <stddef.h>
#include <string.h>
#include <assert.h>
#include "py/objtype.h"
#include "py/runtime.h"
#if MICROPY_DEBUG_VERBOSE // print debugging info
#define DEBUG_PRINT (1)
#define DEBUG_printf DEBUG_printf
#else // don't print debugging info
#define DEBUG_PRINT (0)
#define DEBUG_printf(...) (void)0
#endif
#define ENABLE_SPECIAL_ACCESSORS \
(MICROPY_PY_DESCRIPTORS || MICROPY_PY_DELATTR_SETATTR || MICROPY_PY_BUILTINS_PROPERTY)
STATIC mp_obj_t static_class_method_make_new(const mp_obj_type_t *self_in, size_t n_args, size_t n_kw, const mp_obj_t *args);
/******************************************************************************/
// instance object
STATIC int instance_count_native_bases(const mp_obj_type_t *type, const mp_obj_type_t **last_native_base) {
int count = 0;
for (;;) {
if (type == &mp_type_object) {
// Not a "real" type, end search here.
return count;
} else if (mp_obj_is_native_type(type)) {
// Native types don't have parents (at least not from our perspective) so end.
*last_native_base = type;
return count + 1;
} else if (type->parent == NULL) {
// No parents so end search here.
return count;
#if MICROPY_MULTIPLE_INHERITANCE
} else if (((mp_obj_base_t *)type->parent)->type == &mp_type_tuple) {
// Multiple parents, search through them all recursively.
const mp_obj_tuple_t *parent_tuple = type->parent;
const mp_obj_t *item = parent_tuple->items;
const mp_obj_t *top = item + parent_tuple->len;
for (; item < top; ++item) {
assert(mp_obj_is_type(*item, &mp_type_type));
const mp_obj_type_t *bt = (const mp_obj_type_t *)MP_OBJ_TO_PTR(*item);
count += instance_count_native_bases(bt, last_native_base);
}
return count;
#endif
} else {
// A single parent, use iteration to continue the search.
type = type->parent;
}
}
}
// This wrapper function is allows a subclass of a native type to call the
// __init__() method (corresponding to type->make_new) of the native type.
STATIC mp_obj_t native_base_init_wrapper(size_t n_args, const mp_obj_t *args) {
mp_obj_instance_t *self = MP_OBJ_TO_PTR(args[0]);
const mp_obj_type_t *native_base = NULL;
instance_count_native_bases(self->base.type, &native_base);
self->subobj[0] = native_base->make_new(native_base, n_args - 1, 0, args + 1);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(native_base_init_wrapper_obj, 1, MP_OBJ_FUN_ARGS_MAX, native_base_init_wrapper);
#if !MICROPY_CPYTHON_COMPAT
STATIC
#endif
mp_obj_instance_t *mp_obj_new_instance(const mp_obj_type_t *class, const mp_obj_type_t **native_base) {
size_t num_native_bases = instance_count_native_bases(class, native_base);
assert(num_native_bases < 2);
mp_obj_instance_t *o = m_new_obj_var(mp_obj_instance_t, mp_obj_t, num_native_bases);
o->base.type = class;
mp_map_init(&o->members, 0);
// Initialise the native base-class slot (should be 1 at most) with a valid
// object. It doesn't matter which object, so long as it can be uniquely
// distinguished from a native class that is initialised.
if (num_native_bases != 0) {
o->subobj[0] = MP_OBJ_FROM_PTR(&native_base_init_wrapper_obj);
}
return o;
}
// TODO
// This implements depth-first left-to-right MRO, which is not compliant with Python3 MRO
// http://python-history.blogspot.com/2010/06/method-resolution-order.html
// https://www.python.org/download/releases/2.3/mro/
//
// will keep lookup->dest[0]'s value (should be MP_OBJ_NULL on invocation) if attribute
// is not found
// will set lookup->dest[0] to MP_OBJ_SENTINEL if special method was found in a native
// type base via slot id (as specified by lookup->meth_offset). As there can be only one
// native base, it's known that it applies to instance->subobj[0]. In most cases, we also
// don't need to know which type it was - because instance->subobj[0] is of that type.
// The only exception is when object is not yet constructed, then we need to know base
// native type to construct its instance->subobj[0] from. But this case is handled via
// instance_count_native_bases(), which returns a native base which it saw.
struct class_lookup_data {
mp_obj_instance_t *obj;
qstr attr;
size_t meth_offset;
mp_obj_t *dest;
bool is_type;
};
STATIC void mp_obj_class_lookup(struct class_lookup_data *lookup, const mp_obj_type_t *type) {
assert(lookup->dest[0] == MP_OBJ_NULL);
assert(lookup->dest[1] == MP_OBJ_NULL);
for (;;) {
DEBUG_printf("mp_obj_class_lookup: Looking up %s in %s\n", qstr_str(lookup->attr), qstr_str(type->name));
// Optimize special method lookup for native types
// This avoids extra method_name => slot lookup. On the other hand,
// this should not be applied to class types, as will result in extra
// lookup either.
if (lookup->meth_offset != 0 && mp_obj_is_native_type(type)) {
if (*(void **)((char *)type + lookup->meth_offset) != NULL) {
DEBUG_printf("mp_obj_class_lookup: Matched special meth slot (off=%d) for %s\n",
lookup->meth_offset, qstr_str(lookup->attr));
lookup->dest[0] = MP_OBJ_SENTINEL;
return;
}
}
if (type->locals_dict != NULL) {
// search locals_dict (the set of methods/attributes)
assert(mp_obj_is_dict_or_ordereddict(MP_OBJ_FROM_PTR(type->locals_dict))); // MicroPython restriction, for now
mp_map_t *locals_map = &type->locals_dict->map;
mp_map_elem_t *elem = mp_map_lookup(locals_map, MP_OBJ_NEW_QSTR(lookup->attr), MP_MAP_LOOKUP);
if (elem != NULL) {
if (lookup->is_type) {
// If we look up a class method, we need to return original type for which we
// do a lookup, not a (base) type in which we found the class method.
const mp_obj_type_t *org_type = (const mp_obj_type_t *)lookup->obj;
mp_convert_member_lookup(MP_OBJ_NULL, org_type, elem->value, lookup->dest);
} else {
mp_obj_instance_t *obj = lookup->obj;
mp_obj_t obj_obj;
if (obj != NULL && mp_obj_is_native_type(type) && type != &mp_type_object /* object is not a real type */) {
// If we're dealing with native base class, then it applies to native sub-object
obj_obj = obj->subobj[0];
} else {
obj_obj = MP_OBJ_FROM_PTR(obj);
}
mp_convert_member_lookup(obj_obj, type, elem->value, lookup->dest);
}
#if DEBUG_PRINT
DEBUG_printf("mp_obj_class_lookup: Returning: ");
mp_obj_print_helper(MICROPY_DEBUG_PRINTER, lookup->dest[0], PRINT_REPR);
if (lookup->dest[1] != MP_OBJ_NULL) {
// Don't try to repr() lookup->dest[1], as we can be called recursively
DEBUG_printf(" <%s @%p>", mp_obj_get_type_str(lookup->dest[1]), MP_OBJ_TO_PTR(lookup->dest[1]));
}
DEBUG_printf("\n");
#endif
return;
}
}
// Previous code block takes care about attributes defined in .locals_dict,
// but some attributes of native types may be handled using .load_attr method,
// so make sure we try to lookup those too.
if (lookup->obj != NULL && !lookup->is_type && mp_obj_is_native_type(type) && type != &mp_type_object /* object is not a real type */) {
mp_load_method_maybe(lookup->obj->subobj[0], lookup->attr, lookup->dest);
if (lookup->dest[0] != MP_OBJ_NULL) {
return;
}
}
// attribute not found, keep searching base classes
if (type->parent == NULL) {
DEBUG_printf("mp_obj_class_lookup: No more parents\n");
return;
#if MICROPY_MULTIPLE_INHERITANCE
} else if (((mp_obj_base_t *)type->parent)->type == &mp_type_tuple) {
const mp_obj_tuple_t *parent_tuple = type->parent;
const mp_obj_t *item = parent_tuple->items;
const mp_obj_t *top = item + parent_tuple->len - 1;
for (; item < top; ++item) {
assert(mp_obj_is_type(*item, &mp_type_type));
mp_obj_type_t *bt = (mp_obj_type_t *)MP_OBJ_TO_PTR(*item);
if (bt == &mp_type_object) {
// Not a "real" type
continue;
}
mp_obj_class_lookup(lookup, bt);
if (lookup->dest[0] != MP_OBJ_NULL) {
return;
}
}
// search last base (simple tail recursion elimination)
assert(mp_obj_is_type(*item, &mp_type_type));
type = (mp_obj_type_t *)MP_OBJ_TO_PTR(*item);
#endif
} else {
type = type->parent;
}
if (type == &mp_type_object) {
// Not a "real" type
return;
}
}
}
STATIC void instance_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
mp_obj_instance_t *self = MP_OBJ_TO_PTR(self_in);
qstr meth = (kind == PRINT_STR) ? MP_QSTR___str__ : MP_QSTR___repr__;
mp_obj_t member[2] = {MP_OBJ_NULL};
struct class_lookup_data lookup = {
.obj = self,
.attr = meth,
.meth_offset = offsetof(mp_obj_type_t, print),
.dest = member,
.is_type = false,
};
mp_obj_class_lookup(&lookup, self->base.type);
if (member[0] == MP_OBJ_NULL && kind == PRINT_STR) {
// If there's no __str__, fall back to __repr__
lookup.attr = MP_QSTR___repr__;
lookup.meth_offset = 0;
mp_obj_class_lookup(&lookup, self->base.type);
}
if (member[0] == MP_OBJ_SENTINEL) {
// Handle Exception subclasses specially
if (mp_obj_is_native_exception_instance(self->subobj[0])) {
if (kind != PRINT_STR) {
mp_print_str(print, qstr_str(self->base.type->name));
}
mp_obj_print_helper(print, self->subobj[0], kind | PRINT_EXC_SUBCLASS);
} else {
mp_obj_print_helper(print, self->subobj[0], kind);
}
return;
}
if (member[0] != MP_OBJ_NULL) {
mp_obj_t r = mp_call_function_1(member[0], self_in);
mp_obj_print_helper(print, r, PRINT_STR);
return;
}
// TODO: CPython prints fully-qualified type name
mp_printf(print, "<%s object at %p>", mp_obj_get_type_str(self_in), self);
}
mp_obj_t mp_obj_instance_make_new(const mp_obj_type_t *self, size_t n_args, size_t n_kw, const mp_obj_t *args) {
assert(mp_obj_is_instance_type(self));
// look for __new__ function
mp_obj_t init_fn[2] = {MP_OBJ_NULL};
struct class_lookup_data lookup = {
.obj = NULL,
.attr = MP_QSTR___new__,
.meth_offset = offsetof(mp_obj_type_t, make_new),
.dest = init_fn,
.is_type = false,
};
mp_obj_class_lookup(&lookup, self);
const mp_obj_type_t *native_base = NULL;
mp_obj_instance_t *o;
if (init_fn[0] == MP_OBJ_NULL || init_fn[0] == MP_OBJ_SENTINEL) {
// Either there is no __new__() method defined or there is a native
// constructor. In both cases create a blank instance.
o = mp_obj_new_instance(self, &native_base);
// Since type->make_new() implements both __new__() and __init__() in
// one go, of which the latter may be overridden by the Python subclass,
// we defer (see the end of this function) the call of the native
// constructor to give a chance for the Python __init__() method to call
// said native constructor.
} else {
// Call Python class __new__ function with all args to create an instance
mp_obj_t new_ret;
if (n_args == 0 && n_kw == 0) {
mp_obj_t args2[1] = {MP_OBJ_FROM_PTR(self)};
new_ret = mp_call_function_n_kw(init_fn[0], 1, 0, args2);
} else {
mp_obj_t *args2 = m_new(mp_obj_t, 1 + n_args + 2 * n_kw);
args2[0] = MP_OBJ_FROM_PTR(self);
memcpy(args2 + 1, args, (n_args + 2 * n_kw) * sizeof(mp_obj_t));
new_ret = mp_call_function_n_kw(init_fn[0], n_args + 1, n_kw, args2);
m_del(mp_obj_t, args2, 1 + n_args + 2 * n_kw);
}
// https://docs.python.org/3.4/reference/datamodel.html#object.__new__
// "If __new__() does not return an instance of cls, then the new
// instance's __init__() method will not be invoked."
if (mp_obj_get_type(new_ret) != self) {
return new_ret;
}
// The instance returned by __new__() becomes the new object
o = MP_OBJ_TO_PTR(new_ret);
}
// now call Python class __init__ function with all args
// This method has a chance to call super().__init__() to construct a
// possible native base class.
init_fn[0] = init_fn[1] = MP_OBJ_NULL;
lookup.obj = o;
lookup.attr = MP_QSTR___init__;
lookup.meth_offset = 0;
mp_obj_class_lookup(&lookup, self);
if (init_fn[0] != MP_OBJ_NULL) {
mp_obj_t init_ret;
if (n_args == 0 && n_kw == 0) {
init_ret = mp_call_method_n_kw(0, 0, init_fn);
} else {
mp_obj_t *args2 = m_new(mp_obj_t, 2 + n_args + 2 * n_kw);
args2[0] = init_fn[0];
args2[1] = init_fn[1];
memcpy(args2 + 2, args, (n_args + 2 * n_kw) * sizeof(mp_obj_t));
init_ret = mp_call_method_n_kw(n_args, n_kw, args2);
m_del(mp_obj_t, args2, 2 + n_args + 2 * n_kw);
}
if (init_ret != mp_const_none) {
#if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
mp_raise_TypeError(MP_ERROR_TEXT("__init__() should return None"));
#else
mp_raise_msg_varg(&mp_type_TypeError,
MP_ERROR_TEXT("__init__() should return None, not '%s'"), mp_obj_get_type_str(init_ret));
#endif
}
}
// If the type had a native base that was not explicitly initialised
// (constructed) by the Python __init__() method then construct it now.
if (native_base != NULL && o->subobj[0] == MP_OBJ_FROM_PTR(&native_base_init_wrapper_obj)) {
o->subobj[0] = native_base->make_new(native_base, n_args, n_kw, args);
}
return MP_OBJ_FROM_PTR(o);
}
// Qstrs for special methods are guaranteed to have a small value, so we use byte
// type to represent them.
const byte mp_unary_op_method_name[MP_UNARY_OP_NUM_RUNTIME] = {
[MP_UNARY_OP_BOOL] = MP_QSTR___bool__,
[MP_UNARY_OP_LEN] = MP_QSTR___len__,
[MP_UNARY_OP_HASH] = MP_QSTR___hash__,
[MP_UNARY_OP_INT] = MP_QSTR___int__,
#if MICROPY_PY_ALL_SPECIAL_METHODS
[MP_UNARY_OP_POSITIVE] = MP_QSTR___pos__,
[MP_UNARY_OP_NEGATIVE] = MP_QSTR___neg__,
[MP_UNARY_OP_INVERT] = MP_QSTR___invert__,
[MP_UNARY_OP_ABS] = MP_QSTR___abs__,
#endif
#if MICROPY_PY_SYS_GETSIZEOF
[MP_UNARY_OP_SIZEOF] = MP_QSTR___sizeof__,
#endif
};
STATIC mp_obj_t instance_unary_op(mp_unary_op_t op, mp_obj_t self_in) {
mp_obj_instance_t *self = MP_OBJ_TO_PTR(self_in);
#if MICROPY_PY_SYS_GETSIZEOF
if (MP_UNLIKELY(op == MP_UNARY_OP_SIZEOF)) {
// TODO: This doesn't count inherited objects (self->subobj)
const mp_obj_type_t *native_base;
size_t num_native_bases = instance_count_native_bases(mp_obj_get_type(self_in), &native_base);
size_t sz = sizeof(*self) + sizeof(*self->subobj) * num_native_bases
+ sizeof(*self->members.table) * self->members.alloc;
return MP_OBJ_NEW_SMALL_INT(sz);
}
#endif
qstr op_name = mp_unary_op_method_name[op];
/* Still try to lookup native slot
if (op_name == 0) {
return MP_OBJ_NULL;
}
*/
mp_obj_t member[2] = {MP_OBJ_NULL};
struct class_lookup_data lookup = {
.obj = self,
.attr = op_name,
.meth_offset = offsetof(mp_obj_type_t, unary_op),
.dest = member,
.is_type = false,
};
mp_obj_class_lookup(&lookup, self->base.type);
if (member[0] == MP_OBJ_SENTINEL) {
return mp_unary_op(op, self->subobj[0]);
} else if (member[0] != MP_OBJ_NULL) {
mp_obj_t val = mp_call_function_1(member[0], self_in);
switch (op) {
case MP_UNARY_OP_HASH:
// __hash__ must return a small int
val = MP_OBJ_NEW_SMALL_INT(mp_obj_get_int_truncated(val));
break;
case MP_UNARY_OP_INT:
// Must return int
if (!mp_obj_is_int(val)) {
mp_raise_TypeError(NULL);
}
break;
default:
// No need to do anything
;
}
return val;
} else {
if (op == MP_UNARY_OP_HASH) {
lookup.attr = MP_QSTR___eq__;
mp_obj_class_lookup(&lookup, self->base.type);
if (member[0] == MP_OBJ_NULL) {
// https://docs.python.org/3/reference/datamodel.html#object.__hash__
// "User-defined classes have __eq__() and __hash__() methods by default;
// with them, all objects compare unequal (except with themselves) and
// x.__hash__() returns an appropriate value such that x == y implies
// both that x is y and hash(x) == hash(y)."
return MP_OBJ_NEW_SMALL_INT((mp_uint_t)self_in);
}
// "A class that overrides __eq__() and does not define __hash__() will have its __hash__() implicitly set to None.
// When the __hash__() method of a class is None, instances of the class will raise an appropriate TypeError"
}
return MP_OBJ_NULL; // op not supported
}
}
// Binary-op enum values not listed here will have the default value of 0 in the
// table, corresponding to MP_QSTRnull, and are therefore unsupported (a lookup will
// fail). They can be added at the expense of code size for the qstr.
// Qstrs for special methods are guaranteed to have a small value, so we use byte
// type to represent them.
const byte mp_binary_op_method_name[MP_BINARY_OP_NUM_RUNTIME] = {
[MP_BINARY_OP_LESS] = MP_QSTR___lt__,
[MP_BINARY_OP_MORE] = MP_QSTR___gt__,
[MP_BINARY_OP_EQUAL] = MP_QSTR___eq__,
[MP_BINARY_OP_LESS_EQUAL] = MP_QSTR___le__,
[MP_BINARY_OP_MORE_EQUAL] = MP_QSTR___ge__,
[MP_BINARY_OP_NOT_EQUAL] = MP_QSTR___ne__,
[MP_BINARY_OP_CONTAINS] = MP_QSTR___contains__,
// If an inplace method is not found a normal method will be used as a fallback
[MP_BINARY_OP_INPLACE_ADD] = MP_QSTR___iadd__,
[MP_BINARY_OP_INPLACE_SUBTRACT] = MP_QSTR___isub__,
#if MICROPY_PY_ALL_INPLACE_SPECIAL_METHODS
[MP_BINARY_OP_INPLACE_MULTIPLY] = MP_QSTR___imul__,
[MP_BINARY_OP_INPLACE_MAT_MULTIPLY] = MP_QSTR___imatmul__,
[MP_BINARY_OP_INPLACE_FLOOR_DIVIDE] = MP_QSTR___ifloordiv__,
[MP_BINARY_OP_INPLACE_TRUE_DIVIDE] = MP_QSTR___itruediv__,
[MP_BINARY_OP_INPLACE_MODULO] = MP_QSTR___imod__,
[MP_BINARY_OP_INPLACE_POWER] = MP_QSTR___ipow__,
[MP_BINARY_OP_INPLACE_OR] = MP_QSTR___ior__,
[MP_BINARY_OP_INPLACE_XOR] = MP_QSTR___ixor__,
[MP_BINARY_OP_INPLACE_AND] = MP_QSTR___iand__,
[MP_BINARY_OP_INPLACE_LSHIFT] = MP_QSTR___ilshift__,
[MP_BINARY_OP_INPLACE_RSHIFT] = MP_QSTR___irshift__,
#endif
[MP_BINARY_OP_ADD] = MP_QSTR___add__,
[MP_BINARY_OP_SUBTRACT] = MP_QSTR___sub__,
#if MICROPY_PY_ALL_SPECIAL_METHODS
[MP_BINARY_OP_MULTIPLY] = MP_QSTR___mul__,
[MP_BINARY_OP_MAT_MULTIPLY] = MP_QSTR___matmul__,
[MP_BINARY_OP_FLOOR_DIVIDE] = MP_QSTR___floordiv__,
[MP_BINARY_OP_TRUE_DIVIDE] = MP_QSTR___truediv__,
[MP_BINARY_OP_MODULO] = MP_QSTR___mod__,
[MP_BINARY_OP_DIVMOD] = MP_QSTR___divmod__,
[MP_BINARY_OP_POWER] = MP_QSTR___pow__,
[MP_BINARY_OP_OR] = MP_QSTR___or__,
[MP_BINARY_OP_XOR] = MP_QSTR___xor__,
[MP_BINARY_OP_AND] = MP_QSTR___and__,
[MP_BINARY_OP_LSHIFT] = MP_QSTR___lshift__,
[MP_BINARY_OP_RSHIFT] = MP_QSTR___rshift__,
#endif
#if MICROPY_PY_REVERSE_SPECIAL_METHODS
[MP_BINARY_OP_REVERSE_ADD] = MP_QSTR___radd__,
[MP_BINARY_OP_REVERSE_SUBTRACT] = MP_QSTR___rsub__,
#if MICROPY_PY_ALL_SPECIAL_METHODS
[MP_BINARY_OP_REVERSE_MULTIPLY] = MP_QSTR___rmul__,
[MP_BINARY_OP_REVERSE_MAT_MULTIPLY] = MP_QSTR___rmatmul__,
[MP_BINARY_OP_REVERSE_FLOOR_DIVIDE] = MP_QSTR___rfloordiv__,
[MP_BINARY_OP_REVERSE_TRUE_DIVIDE] = MP_QSTR___rtruediv__,
[MP_BINARY_OP_REVERSE_MODULO] = MP_QSTR___rmod__,
[MP_BINARY_OP_REVERSE_POWER] = MP_QSTR___rpow__,
[MP_BINARY_OP_REVERSE_OR] = MP_QSTR___ror__,
[MP_BINARY_OP_REVERSE_XOR] = MP_QSTR___rxor__,
[MP_BINARY_OP_REVERSE_AND] = MP_QSTR___rand__,
[MP_BINARY_OP_REVERSE_LSHIFT] = MP_QSTR___rlshift__,
[MP_BINARY_OP_REVERSE_RSHIFT] = MP_QSTR___rrshift__,
#endif
#endif
};
STATIC mp_obj_t instance_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_in) {
// Note: For ducktyping, CPython does not look in the instance members or use
// __getattr__ or __getattribute__. It only looks in the class dictionary.
mp_obj_instance_t *lhs = MP_OBJ_TO_PTR(lhs_in);
retry:;
qstr op_name = mp_binary_op_method_name[op];
/* Still try to lookup native slot
if (op_name == 0) {
return MP_OBJ_NULL;
}
*/
mp_obj_t dest[3] = {MP_OBJ_NULL};
struct class_lookup_data lookup = {
.obj = lhs,
.attr = op_name,
.meth_offset = offsetof(mp_obj_type_t, binary_op),
.dest = dest,
.is_type = false,
};
mp_obj_class_lookup(&lookup, lhs->base.type);
mp_obj_t res;
if (dest[0] == MP_OBJ_SENTINEL) {
res = mp_binary_op(op, lhs->subobj[0], rhs_in);
} else if (dest[0] != MP_OBJ_NULL) {
dest[2] = rhs_in;
res = mp_call_method_n_kw(1, 0, dest);
} else {
// If this was an inplace method, fallback to normal method
// https://docs.python.org/3/reference/datamodel.html#object.__iadd__ :
// "If a specific method is not defined, the augmented assignment
// falls back to the normal methods."
if (op >= MP_BINARY_OP_INPLACE_OR && op <= MP_BINARY_OP_INPLACE_POWER) {
op -= MP_BINARY_OP_INPLACE_OR - MP_BINARY_OP_OR;
goto retry;
}
return MP_OBJ_NULL; // op not supported
}
#if MICROPY_PY_BUILTINS_NOTIMPLEMENTED
// NotImplemented means "try other fallbacks (like calling __rop__
// instead of __op__) and if nothing works, raise TypeError". As
// MicroPython doesn't implement any fallbacks, signal to raise
// TypeError right away.
if (res == mp_const_notimplemented) {
return MP_OBJ_NULL; // op not supported
}
#endif
return res;
}
STATIC void mp_obj_instance_load_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) {
// logic: look in instance members then class locals
assert(mp_obj_is_instance_type(mp_obj_get_type(self_in)));
mp_obj_instance_t *self = MP_OBJ_TO_PTR(self_in);
mp_map_elem_t *elem = mp_map_lookup(&self->members, MP_OBJ_NEW_QSTR(attr), MP_MAP_LOOKUP);
if (elem != NULL) {
// object member, always treated as a value
dest[0] = elem->value;
return;
}
#if MICROPY_CPYTHON_COMPAT
if (attr == MP_QSTR___dict__) {
// Create a new dict with a copy of the instance's map items.
// This creates, unlike CPython, a read-only __dict__ that can't be modified.
mp_obj_dict_t dict;
dict.base.type = &mp_type_dict;
dict.map = self->members;
dest[0] = mp_obj_dict_copy(MP_OBJ_FROM_PTR(&dict));
mp_obj_dict_t *dest_dict = MP_OBJ_TO_PTR(dest[0]);
dest_dict->map.is_fixed = 1;
return;
}
#endif
struct class_lookup_data lookup = {
.obj = self,
.attr = attr,
.meth_offset = 0,
.dest = dest,
.is_type = false,
};
mp_obj_class_lookup(&lookup, self->base.type);
mp_obj_t member = dest[0];
if (member != MP_OBJ_NULL) {
if (!(self->base.type->flags & MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS)) {
// Class doesn't have any special accessors to check so return straightaway
return;
}
#if MICROPY_PY_BUILTINS_PROPERTY
if (mp_obj_is_type(member, &mp_type_property)) {
// object member is a property; delegate the load to the property
// Note: This is an optimisation for code size and execution time.
// The proper way to do it is have the functionality just below
// in a __get__ method of the property object, and then it would
// be called by the descriptor code down below. But that way
// requires overhead for the nested mp_call's and overhead for
// the code.
const mp_obj_t *proxy = mp_obj_property_get(member);
if (proxy[0] == mp_const_none) {
mp_raise_msg(&mp_type_AttributeError, MP_ERROR_TEXT("unreadable attribute"));
} else {
dest[0] = mp_call_function_n_kw(proxy[0], 1, 0, &self_in);
}
return;
}
#endif
#if MICROPY_PY_DESCRIPTORS
// found a class attribute; if it has a __get__ method then call it with the
// class instance and class as arguments and return the result
// Note that this is functionally correct but very slow: each load_attr
// requires an extra mp_load_method_maybe to check for the __get__.
mp_obj_t attr_get_method[4];
mp_load_method_maybe(member, MP_QSTR___get__, attr_get_method);
if (attr_get_method[0] != MP_OBJ_NULL) {
attr_get_method[2] = self_in;
attr_get_method[3] = MP_OBJ_FROM_PTR(mp_obj_get_type(self_in));
dest[0] = mp_call_method_n_kw(2, 0, attr_get_method);
}
#endif
return;
}
// try __getattr__
if (attr != MP_QSTR___getattr__) {
#if MICROPY_PY_DELATTR_SETATTR
// If the requested attr is __setattr__/__delattr__ then don't delegate the lookup
// to __getattr__. If we followed CPython's behaviour then __setattr__/__delattr__
// would have already been found in the "object" base class.
if (attr == MP_QSTR___setattr__ || attr == MP_QSTR___delattr__) {
return;
}
#endif
mp_obj_t dest2[3];
mp_load_method_maybe(self_in, MP_QSTR___getattr__, dest2);
if (dest2[0] != MP_OBJ_NULL) {
// __getattr__ exists, call it and return its result
dest2[2] = MP_OBJ_NEW_QSTR(attr);
dest[0] = mp_call_method_n_kw(1, 0, dest2);
return;
}
}
}
STATIC bool mp_obj_instance_store_attr(mp_obj_t self_in, qstr attr, mp_obj_t value) {
mp_obj_instance_t *self = MP_OBJ_TO_PTR(self_in);
if (!(self->base.type->flags & MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS)) {
// Class doesn't have any special accessors so skip their checks
goto skip_special_accessors;
}
#if MICROPY_PY_BUILTINS_PROPERTY || MICROPY_PY_DESCRIPTORS
// With property and/or descriptors enabled we need to do a lookup
// first in the class dict for the attribute to see if the store should
// be delegated.
mp_obj_t member[2] = {MP_OBJ_NULL};
struct class_lookup_data lookup = {
.obj = self,
.attr = attr,
.meth_offset = 0,
.dest = member,
.is_type = false,
};
mp_obj_class_lookup(&lookup, self->base.type);
if (member[0] != MP_OBJ_NULL) {
#if MICROPY_PY_BUILTINS_PROPERTY
if (mp_obj_is_type(member[0], &mp_type_property)) {
// attribute exists and is a property; delegate the store/delete
// Note: This is an optimisation for code size and execution time.
// The proper way to do it is have the functionality just below in
// a __set__/__delete__ method of the property object, and then it
// would be called by the descriptor code down below. But that way
// requires overhead for the nested mp_call's and overhead for
// the code.
const mp_obj_t *proxy = mp_obj_property_get(member[0]);
mp_obj_t dest[2] = {self_in, value};
if (value == MP_OBJ_NULL) {
// delete attribute
if (proxy[2] == mp_const_none) {
// TODO better error message?
return false;
} else {
mp_call_function_n_kw(proxy[2], 1, 0, dest);
return true;
}
} else {
// store attribute
if (proxy[1] == mp_const_none) {
// TODO better error message?
return false;
} else {
mp_call_function_n_kw(proxy[1], 2, 0, dest);
return true;
}
}
}
#endif
#if MICROPY_PY_DESCRIPTORS
// found a class attribute; if it has a __set__/__delete__ method then
// call it with the class instance (and value) as arguments
if (value == MP_OBJ_NULL) {
// delete attribute
mp_obj_t attr_delete_method[3];
mp_load_method_maybe(member[0], MP_QSTR___delete__, attr_delete_method);
if (attr_delete_method[0] != MP_OBJ_NULL) {
attr_delete_method[2] = self_in;
mp_call_method_n_kw(1, 0, attr_delete_method);
return true;
}
} else {
// store attribute
mp_obj_t attr_set_method[4];
mp_load_method_maybe(member[0], MP_QSTR___set__, attr_set_method);
if (attr_set_method[0] != MP_OBJ_NULL) {
attr_set_method[2] = self_in;
attr_set_method[3] = value;
mp_call_method_n_kw(2, 0, attr_set_method);
return true;
}
}
#endif
}
#endif
#if MICROPY_PY_DELATTR_SETATTR
if (value == MP_OBJ_NULL) {
// delete attribute
// try __delattr__ first
mp_obj_t attr_delattr_method[3];
mp_load_method_maybe(self_in, MP_QSTR___delattr__, attr_delattr_method);
if (attr_delattr_method[0] != MP_OBJ_NULL) {
// __delattr__ exists, so call it
attr_delattr_method[2] = MP_OBJ_NEW_QSTR(attr);
mp_call_method_n_kw(1, 0, attr_delattr_method);
return true;
}
} else {
// store attribute
// try __setattr__ first
mp_obj_t attr_setattr_method[4];
mp_load_method_maybe(self_in, MP_QSTR___setattr__, attr_setattr_method);
if (attr_setattr_method[0] != MP_OBJ_NULL) {
// __setattr__ exists, so call it
attr_setattr_method[2] = MP_OBJ_NEW_QSTR(attr);
attr_setattr_method[3] = value;
mp_call_method_n_kw(2, 0, attr_setattr_method);
return true;
}
}
#endif
skip_special_accessors:
if (value == MP_OBJ_NULL) {
// delete attribute
mp_map_elem_t *elem = mp_map_lookup(&self->members, MP_OBJ_NEW_QSTR(attr), MP_MAP_LOOKUP_REMOVE_IF_FOUND);
return elem != NULL;
} else {
// store attribute
mp_map_lookup(&self->members, MP_OBJ_NEW_QSTR(attr), MP_MAP_LOOKUP_ADD_IF_NOT_FOUND)->value = value;
return true;
}
}
STATIC void mp_obj_instance_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) {
if (dest[0] == MP_OBJ_NULL) {
mp_obj_instance_load_attr(self_in, attr, dest);
} else {
if (mp_obj_instance_store_attr(self_in, attr, dest[1])) {
dest[0] = MP_OBJ_NULL; // indicate success
}
}
}
STATIC mp_obj_t instance_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) {
mp_obj_instance_t *self = MP_OBJ_TO_PTR(self_in);
mp_obj_t member[4] = {MP_OBJ_NULL, MP_OBJ_NULL, index, value};
struct class_lookup_data lookup = {
.obj = self,
.meth_offset = offsetof(mp_obj_type_t, subscr),
.dest = member,
.is_type = false,
};
if (value == MP_OBJ_NULL) {
// delete item
lookup.attr = MP_QSTR___delitem__;
} else if (value == MP_OBJ_SENTINEL) {
// load item
lookup.attr = MP_QSTR___getitem__;
} else {
// store item
lookup.attr = MP_QSTR___setitem__;
}
mp_obj_class_lookup(&lookup, self->base.type);
if (member[0] == MP_OBJ_SENTINEL) {
return mp_obj_subscr(self->subobj[0], index, value);
} else if (member[0] != MP_OBJ_NULL) {
size_t n_args = value == MP_OBJ_NULL || value == MP_OBJ_SENTINEL ? 1 : 2;
mp_obj_t ret = mp_call_method_n_kw(n_args, 0, member);
if (value == MP_OBJ_SENTINEL) {
return ret;
} else {
return mp_const_none;
}
} else {
return MP_OBJ_NULL; // op not supported
}
}
STATIC mp_obj_t mp_obj_instance_get_call(mp_obj_t self_in, mp_obj_t *member) {
mp_obj_instance_t *self = MP_OBJ_TO_PTR(self_in);
struct class_lookup_data lookup = {
.obj = self,
.attr = MP_QSTR___call__,
.meth_offset = offsetof(mp_obj_type_t, call),
.dest = member,
.is_type = false,
};
mp_obj_class_lookup(&lookup, self->base.type);
return member[0];
}
bool mp_obj_instance_is_callable(mp_obj_t self_in) {
mp_obj_t member[2] = {MP_OBJ_NULL, MP_OBJ_NULL};
return mp_obj_instance_get_call(self_in, member) != MP_OBJ_NULL;
}
mp_obj_t mp_obj_instance_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp_obj_t *args) {
mp_obj_t member[2] = {MP_OBJ_NULL, MP_OBJ_NULL};
mp_obj_t call = mp_obj_instance_get_call(self_in, member);
if (call == MP_OBJ_NULL) {
#if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
mp_raise_TypeError(MP_ERROR_TEXT("object not callable"));
#else
mp_raise_msg_varg(&mp_type_TypeError,
MP_ERROR_TEXT("'%s' object isn't callable"), mp_obj_get_type_str(self_in));
#endif
}
mp_obj_instance_t *self = MP_OBJ_TO_PTR(self_in);
if (call == MP_OBJ_SENTINEL) {
return mp_call_function_n_kw(self->subobj[0], n_args, n_kw, args);
}
return mp_call_method_self_n_kw(member[0], member[1], n_args, n_kw, args);
}
// Note that iter_buf may be NULL, and needs to be allocated if needed
mp_obj_t mp_obj_instance_getiter(mp_obj_t self_in, mp_obj_iter_buf_t *iter_buf) {
mp_obj_instance_t *self = MP_OBJ_TO_PTR(self_in);
mp_obj_t member[2] = {MP_OBJ_NULL};
struct class_lookup_data lookup = {
.obj = self,
.attr = MP_QSTR___iter__,
.meth_offset = offsetof(mp_obj_type_t, getiter),
.dest = member,
.is_type = false,
};
mp_obj_class_lookup(&lookup, self->base.type);
if (member[0] == MP_OBJ_NULL) {
return MP_OBJ_NULL;
} else if (member[0] == MP_OBJ_SENTINEL) {
const mp_obj_type_t *type = mp_obj_get_type(self->subobj[0]);
if (iter_buf == NULL) {
iter_buf = m_new_obj(mp_obj_iter_buf_t);
}
return type->getiter(self->subobj[0], iter_buf);
} else {
return mp_call_method_n_kw(0, 0, member);
}
}
STATIC mp_int_t instance_get_buffer(mp_obj_t self_in, mp_buffer_info_t *bufinfo, mp_uint_t flags) {
mp_obj_instance_t *self = MP_OBJ_TO_PTR(self_in);
mp_obj_t member[2] = {MP_OBJ_NULL};
struct class_lookup_data lookup = {
.obj = self,
.attr = MP_QSTR_, // don't actually look for a method
.meth_offset = offsetof(mp_obj_type_t, buffer_p.get_buffer),
.dest = member,
.is_type = false,
};
mp_obj_class_lookup(&lookup, self->base.type);
if (member[0] == MP_OBJ_SENTINEL) {
const mp_obj_type_t *type = mp_obj_get_type(self->subobj[0]);
return type->buffer_p.get_buffer(self->subobj[0], bufinfo, flags);
} else {
return 1; // object does not support buffer protocol
}
}
/******************************************************************************/
// type object
// - the struct is mp_obj_type_t and is defined in obj.h so const types can be made
// - there is a constant mp_obj_type_t (called mp_type_type) for the 'type' object
// - creating a new class (a new type) creates a new mp_obj_type_t
#if ENABLE_SPECIAL_ACCESSORS
STATIC bool check_for_special_accessors(mp_obj_t key, mp_obj_t value) {
#if MICROPY_PY_DELATTR_SETATTR
if (key == MP_OBJ_NEW_QSTR(MP_QSTR___setattr__) || key == MP_OBJ_NEW_QSTR(MP_QSTR___delattr__)) {
return true;
}
#endif
#if MICROPY_PY_BUILTINS_PROPERTY
if (mp_obj_is_type(value, &mp_type_property)) {
return true;
}
#endif
#if MICROPY_PY_DESCRIPTORS
static const uint8_t to_check[] = {
MP_QSTR___get__, MP_QSTR___set__, MP_QSTR___delete__,
};
for (size_t i = 0; i < MP_ARRAY_SIZE(to_check); ++i) {
mp_obj_t dest_temp[2];
mp_load_method_protected(value, to_check[i], dest_temp, true);
if (dest_temp[0] != MP_OBJ_NULL) {
return true;
}
}
#endif
return false;
}
#endif
STATIC void type_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
(void)kind;
mp_obj_type_t *self = MP_OBJ_TO_PTR(self_in);
mp_printf(print, "<class '%q'>", self->name);
}
STATIC mp_obj_t type_make_new(const mp_obj_type_t *type_in, size_t n_args, size_t n_kw, const mp_obj_t *args) {
(void)type_in;
mp_arg_check_num(n_args, n_kw, 1, 3, false);
switch (n_args) {
case 1:
return MP_OBJ_FROM_PTR(mp_obj_get_type(args[0]));
case 3:
// args[0] = name
// args[1] = bases tuple
// args[2] = locals dict
return mp_obj_new_type(mp_obj_str_get_qstr(args[0]), args[1], args[2]);
default:
mp_raise_TypeError(MP_ERROR_TEXT("type takes 1 or 3 arguments"));
}
}
STATIC mp_obj_t type_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp_obj_t *args) {
// instantiate an instance of a class
mp_obj_type_t *self = MP_OBJ_TO_PTR(self_in);
if (self->make_new == NULL) {
#if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
mp_raise_TypeError(MP_ERROR_TEXT("can't create instance"));
#else
mp_raise_msg_varg(&mp_type_TypeError, MP_ERROR_TEXT("can't create '%q' instances"), self->name);
#endif
}
// make new instance
mp_obj_t o = self->make_new(self, n_args, n_kw, args);
// return new instance
return o;
}
STATIC void type_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) {
assert(mp_obj_is_type(self_in, &mp_type_type));
mp_obj_type_t *self = MP_OBJ_TO_PTR(self_in);
if (dest[0] == MP_OBJ_NULL) {
// load attribute
#if MICROPY_CPYTHON_COMPAT
if (attr == MP_QSTR___name__) {
dest[0] = MP_OBJ_NEW_QSTR(self->name);
return;
}
#if MICROPY_CPYTHON_COMPAT
if (attr == MP_QSTR___dict__) {
// Returns a read-only dict of the class attributes.
// If the internal locals is not fixed, a copy will be created.
const mp_obj_dict_t *dict = self->locals_dict;
if (!dict) {
dict = &mp_const_empty_dict_obj;
}
if (dict->map.is_fixed) {
dest[0] = MP_OBJ_FROM_PTR(dict);
} else {
dest[0] = mp_obj_dict_copy(MP_OBJ_FROM_PTR(dict));
mp_obj_dict_t *dict_copy = MP_OBJ_TO_PTR(dest[0]);
dict_copy->map.is_fixed = 1;
}
return;
}
#endif
if (attr == MP_QSTR___bases__) {
if (self == &mp_type_object) {
dest[0] = mp_const_empty_tuple;
return;
}
mp_obj_t parent_obj = self->parent ? MP_OBJ_FROM_PTR(self->parent) : MP_OBJ_FROM_PTR(&mp_type_object);
#if MICROPY_MULTIPLE_INHERITANCE
if (mp_obj_is_type(parent_obj, &mp_type_tuple)) {
dest[0] = parent_obj;
return;
}
#endif
dest[0] = mp_obj_new_tuple(1, &parent_obj);
return;
}
#endif
struct class_lookup_data lookup = {
.obj = (mp_obj_instance_t *)self,
.attr = attr,
.meth_offset = 0,
.dest = dest,
.is_type = true,
};
mp_obj_class_lookup(&lookup, self);
} else {
// delete/store attribute
if (self->locals_dict != NULL) {
assert(mp_obj_is_dict_or_ordereddict(MP_OBJ_FROM_PTR(self->locals_dict))); // MicroPython restriction, for now
mp_map_t *locals_map = &self->locals_dict->map;
if (locals_map->is_fixed) {
// can't apply delete/store to a fixed map
return;
}
if (dest[1] == MP_OBJ_NULL) {
// delete attribute
mp_map_elem_t *elem = mp_map_lookup(locals_map, MP_OBJ_NEW_QSTR(attr), MP_MAP_LOOKUP_REMOVE_IF_FOUND);
if (elem != NULL) {
dest[0] = MP_OBJ_NULL; // indicate success
}
} else {
#if ENABLE_SPECIAL_ACCESSORS
// Check if we add any special accessor methods with this store
if (!(self->flags & MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS)) {
if (check_for_special_accessors(MP_OBJ_NEW_QSTR(attr), dest[1])) {
if (self->flags & MP_TYPE_FLAG_IS_SUBCLASSED) {
// This class is already subclassed so can't have special accessors added
mp_raise_msg(&mp_type_AttributeError, MP_ERROR_TEXT("can't add special method to already-subclassed class"));
}
self->flags |= MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS;
}
}
#endif
// store attribute
mp_map_elem_t *elem = mp_map_lookup(locals_map, MP_OBJ_NEW_QSTR(attr), MP_MAP_LOOKUP_ADD_IF_NOT_FOUND);
elem->value = dest[1];
dest[0] = MP_OBJ_NULL; // indicate success
}
}
}
}
const mp_obj_type_t mp_type_type = {
{ &mp_type_type },
.name = MP_QSTR_type,
.print = type_print,
.make_new = type_make_new,
.call = type_call,
.unary_op = mp_generic_unary_op,
.attr = type_attr,
};
mp_obj_t mp_obj_new_type(qstr name, mp_obj_t bases_tuple, mp_obj_t locals_dict) {
// Verify input objects have expected type
if (!mp_obj_is_type(bases_tuple, &mp_type_tuple)) {
mp_raise_TypeError(NULL);
}
if (!mp_obj_is_dict_or_ordereddict(locals_dict)) {
mp_raise_TypeError(NULL);
}
// TODO might need to make a copy of locals_dict; at least that's how CPython does it
// Basic validation of base classes
uint16_t base_flags = MP_TYPE_FLAG_EQ_NOT_REFLEXIVE
| MP_TYPE_FLAG_EQ_CHECKS_OTHER_TYPE | MP_TYPE_FLAG_EQ_HAS_NEQ_TEST;
size_t bases_len;
mp_obj_t *bases_items;
mp_obj_tuple_get(bases_tuple, &bases_len, &bases_items);
for (size_t i = 0; i < bases_len; i++) {
if (!mp_obj_is_type(bases_items[i], &mp_type_type)) {
mp_raise_TypeError(NULL);
}
mp_obj_type_t *t = MP_OBJ_TO_PTR(bases_items[i]);
// TODO: Verify with CPy, tested on function type
if (t->make_new == NULL) {
#if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
mp_raise_TypeError(MP_ERROR_TEXT("type isn't an acceptable base type"));
#else
mp_raise_msg_varg(&mp_type_TypeError,
MP_ERROR_TEXT("type '%q' isn't an acceptable base type"), t->name);
#endif
}
#if ENABLE_SPECIAL_ACCESSORS
if (mp_obj_is_instance_type(t)) {
t->flags |= MP_TYPE_FLAG_IS_SUBCLASSED;
base_flags |= t->flags & MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS;
}
#endif
}
mp_obj_type_t *o = m_new0(mp_obj_type_t, 1);
o->base.type = &mp_type_type;
o->flags = base_flags;
o->name = name;
o->print = instance_print;
o->make_new = mp_obj_instance_make_new;
o->call = mp_obj_instance_call;
o->unary_op = instance_unary_op;
o->binary_op = instance_binary_op;
o->attr = mp_obj_instance_attr;
o->subscr = instance_subscr;
o->getiter = mp_obj_instance_getiter;
// o->iternext = ; not implemented
o->buffer_p.get_buffer = instance_get_buffer;
if (bases_len > 0) {
// Inherit protocol from a base class. This allows to define an
// abstract base class which would translate C-level protocol to
// Python method calls, and any subclass inheriting from it will
// support this feature.
o->protocol = ((mp_obj_type_t *)MP_OBJ_TO_PTR(bases_items[0]))->protocol;
if (bases_len >= 2) {
#if MICROPY_MULTIPLE_INHERITANCE
o->parent = MP_OBJ_TO_PTR(bases_tuple);
#else
mp_raise_NotImplementedError(MP_ERROR_TEXT("multiple inheritance not supported"));
#endif
} else {
o->parent = MP_OBJ_TO_PTR(bases_items[0]);
}
}
o->locals_dict = MP_OBJ_TO_PTR(locals_dict);
#if ENABLE_SPECIAL_ACCESSORS
// Check if the class has any special accessor methods
if (!(o->flags & MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS)) {
for (size_t i = 0; i < o->locals_dict->map.alloc; i++) {
if (mp_map_slot_is_filled(&o->locals_dict->map, i)) {
const mp_map_elem_t *elem = &o->locals_dict->map.table[i];
if (check_for_special_accessors(elem->key, elem->value)) {
o->flags |= MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS;
break;
}
}
}
}
#endif
const mp_obj_type_t *native_base;
size_t num_native_bases = instance_count_native_bases(o, &native_base);
if (num_native_bases > 1) {
mp_raise_TypeError(MP_ERROR_TEXT("multiple bases have instance lay-out conflict"));
}
mp_map_t *locals_map = &o->locals_dict->map;
mp_map_elem_t *elem = mp_map_lookup(locals_map, MP_OBJ_NEW_QSTR(MP_QSTR___new__), MP_MAP_LOOKUP);
if (elem != NULL) {
// __new__ slot exists; check if it is a function
if (mp_obj_is_fun(elem->value)) {
// __new__ is a function, wrap it in a staticmethod decorator
elem->value = static_class_method_make_new(&mp_type_staticmethod, 1, 0, &elem->value);
}
}
return MP_OBJ_FROM_PTR(o);
}
/******************************************************************************/
// super object
typedef struct _mp_obj_super_t {
mp_obj_base_t base;
mp_obj_t type;
mp_obj_t obj;
} mp_obj_super_t;
STATIC void super_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
(void)kind;
mp_obj_super_t *self = MP_OBJ_TO_PTR(self_in);
mp_print_str(print, "<super: ");
mp_obj_print_helper(print, self->type, PRINT_STR);
mp_print_str(print, ", ");
mp_obj_print_helper(print, self->obj, PRINT_STR);
mp_print_str(print, ">");
}
STATIC mp_obj_t super_make_new(const mp_obj_type_t *type_in, size_t n_args, size_t n_kw, const mp_obj_t *args) {
(void)type_in;
// 0 arguments are turned into 2 in the compiler
// 1 argument is not yet implemented
mp_arg_check_num(n_args, n_kw, 2, 2, false);
if (!mp_obj_is_type(args[0], &mp_type_type)) {
mp_raise_TypeError(NULL);
}
mp_obj_super_t *o = m_new_obj(mp_obj_super_t);
*o = (mp_obj_super_t) {{type_in}, args[0], args[1]};
return MP_OBJ_FROM_PTR(o);
}
STATIC void super_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) {
if (dest[0] != MP_OBJ_NULL) {
// not load attribute
return;
}
assert(mp_obj_is_type(self_in, &mp_type_super));
mp_obj_super_t *self = MP_OBJ_TO_PTR(self_in);
assert(mp_obj_is_type(self->type, &mp_type_type));
mp_obj_type_t *type = MP_OBJ_TO_PTR(self->type);
struct class_lookup_data lookup = {
.obj = MP_OBJ_TO_PTR(self->obj),
.attr = attr,
.meth_offset = 0,
.dest = dest,
.is_type = false,
};
// Allow a call super().__init__() to reach any native base classes
if (attr == MP_QSTR___init__) {
lookup.meth_offset = offsetof(mp_obj_type_t, make_new);
}
if (type->parent == NULL) {
// no parents, do nothing
#if MICROPY_MULTIPLE_INHERITANCE
} else if (((mp_obj_base_t *)type->parent)->type == &mp_type_tuple) {
const mp_obj_tuple_t *parent_tuple = type->parent;
size_t len = parent_tuple->len;
const mp_obj_t *items = parent_tuple->items;
for (size_t i = 0; i < len; i++) {
assert(mp_obj_is_type(items[i], &mp_type_type));
if (MP_OBJ_TO_PTR(items[i]) == &mp_type_object) {
// The "object" type will be searched at the end of this function,
// and we don't want to lookup native methods in object.
continue;
}
mp_obj_class_lookup(&lookup, (mp_obj_type_t *)MP_OBJ_TO_PTR(items[i]));
if (dest[0] != MP_OBJ_NULL) {
break;
}
}
#endif
} else if (type->parent != &mp_type_object) {
mp_obj_class_lookup(&lookup, type->parent);
}
if (dest[0] != MP_OBJ_NULL) {
if (dest[0] == MP_OBJ_SENTINEL) {
// Looked up native __init__ so defer to it
dest[0] = MP_OBJ_FROM_PTR(&native_base_init_wrapper_obj);
dest[1] = self->obj;
}
return;
}
// Reset meth_offset so we don't look up any native methods in object,
// because object never takes up the native base-class slot.
lookup.meth_offset = 0;
mp_obj_class_lookup(&lookup, &mp_type_object);
}
const mp_obj_type_t mp_type_super = {
{ &mp_type_type },
.name = MP_QSTR_super,
.print = super_print,
.make_new = super_make_new,
.attr = super_attr,
};
void mp_load_super_method(qstr attr, mp_obj_t *dest) {
mp_obj_super_t super = {{&mp_type_super}, dest[1], dest[2]};
mp_load_method(MP_OBJ_FROM_PTR(&super), attr, dest);
}
/******************************************************************************/
// subclassing and built-ins specific to types
// object and classinfo should be type objects
// (but the function will fail gracefully if they are not)
bool mp_obj_is_subclass_fast(mp_const_obj_t object, mp_const_obj_t classinfo) {
for (;;) {
if (object == classinfo) {
return true;
}
// not equivalent classes, keep searching base classes
// object should always be a type object, but just return false if it's not
if (!mp_obj_is_type(object, &mp_type_type)) {
return false;
}
const mp_obj_type_t *self = MP_OBJ_TO_PTR(object);
if (self->parent == NULL) {
// type has no parents
return false;
#if MICROPY_MULTIPLE_INHERITANCE
} else if (((mp_obj_base_t *)self->parent)->type == &mp_type_tuple) {
// get the base objects (they should be type objects)
const mp_obj_tuple_t *parent_tuple = self->parent;
const mp_obj_t *item = parent_tuple->items;
const mp_obj_t *top = item + parent_tuple->len - 1;
// iterate through the base objects
for (; item < top; ++item) {
if (mp_obj_is_subclass_fast(*item, classinfo)) {
return true;
}
}
// search last base (simple tail recursion elimination)
object = *item;
#endif
} else {
// type has 1 parent
object = MP_OBJ_FROM_PTR(self->parent);
}
}
}
STATIC mp_obj_t mp_obj_is_subclass(mp_obj_t object, mp_obj_t classinfo) {
size_t len;
mp_obj_t *items;
if (mp_obj_is_type(classinfo, &mp_type_type)) {
len = 1;
items = &classinfo;
} else if (mp_obj_is_type(classinfo, &mp_type_tuple)) {
mp_obj_tuple_get(classinfo, &len, &items);
} else {
mp_raise_TypeError(MP_ERROR_TEXT("issubclass() arg 2 must be a class or a tuple of classes"));
}
for (size_t i = 0; i < len; i++) {
// We explicitly check for 'object' here since no-one explicitly derives from it
if (items[i] == MP_OBJ_FROM_PTR(&mp_type_object) || mp_obj_is_subclass_fast(object, items[i])) {
return mp_const_true;
}
}
return mp_const_false;
}
STATIC mp_obj_t mp_builtin_issubclass(mp_obj_t object, mp_obj_t classinfo) {
if (!mp_obj_is_type(object, &mp_type_type)) {
mp_raise_TypeError(MP_ERROR_TEXT("issubclass() arg 1 must be a class"));
}
return mp_obj_is_subclass(object, classinfo);
}
MP_DEFINE_CONST_FUN_OBJ_2(mp_builtin_issubclass_obj, mp_builtin_issubclass);
STATIC mp_obj_t mp_builtin_isinstance(mp_obj_t object, mp_obj_t classinfo) {
return mp_obj_is_subclass(MP_OBJ_FROM_PTR(mp_obj_get_type(object)), classinfo);
}
MP_DEFINE_CONST_FUN_OBJ_2(mp_builtin_isinstance_obj, mp_builtin_isinstance);
mp_obj_t mp_obj_cast_to_native_base(mp_obj_t self_in, mp_const_obj_t native_type) {
const mp_obj_type_t *self_type = mp_obj_get_type(self_in);
if (MP_OBJ_FROM_PTR(self_type) == native_type) {
return self_in;
} else if (!mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(self_type), native_type)) {
return MP_OBJ_NULL;
} else {
mp_obj_instance_t *self = (mp_obj_instance_t *)MP_OBJ_TO_PTR(self_in);
return self->subobj[0];
}
}
/******************************************************************************/
// staticmethod and classmethod types (probably should go in a different file)
STATIC mp_obj_t static_class_method_make_new(const mp_obj_type_t *self, size_t n_args, size_t n_kw, const mp_obj_t *args) {
assert(self == &mp_type_staticmethod || self == &mp_type_classmethod);
mp_arg_check_num(n_args, n_kw, 1, 1, false);
mp_obj_static_class_method_t *o = m_new_obj(mp_obj_static_class_method_t);
*o = (mp_obj_static_class_method_t) {{self}, args[0]};
return MP_OBJ_FROM_PTR(o);
}
const mp_obj_type_t mp_type_staticmethod = {
{ &mp_type_type },
.name = MP_QSTR_staticmethod,
.make_new = static_class_method_make_new,
};
const mp_obj_type_t mp_type_classmethod = {
{ &mp_type_type },
.name = MP_QSTR_classmethod,
.make_new = static_class_method_make_new,
};
| YifuLiu/AliOS-Things | components/py_engine/engine/py/objtype.c | C | apache-2.0 | 56,640 |
/*
* 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.
*/
#ifndef MICROPY_INCLUDED_PY_OBJTYPE_H
#define MICROPY_INCLUDED_PY_OBJTYPE_H
#include "py/obj.h"
// instance object
// creating an instance of a class makes one of these objects
typedef struct _mp_obj_instance_t {
mp_obj_base_t base;
mp_map_t members;
mp_obj_t subobj[];
// TODO maybe cache __getattr__ and __setattr__ for efficient lookup of them
} mp_obj_instance_t;
#if MICROPY_CPYTHON_COMPAT
// this is needed for object.__new__
mp_obj_instance_t *mp_obj_new_instance(const mp_obj_type_t *cls, const mp_obj_type_t **native_base);
#endif
// these need to be exposed so mp_obj_is_callable can work correctly
bool mp_obj_instance_is_callable(mp_obj_t self_in);
mp_obj_t mp_obj_instance_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp_obj_t *args);
#define mp_obj_is_instance_type(type) ((type)->make_new == mp_obj_instance_make_new)
#define mp_obj_is_native_type(type) ((type)->make_new != mp_obj_instance_make_new)
// this needs to be exposed for the above macros to work correctly
mp_obj_t mp_obj_instance_make_new(const mp_obj_type_t *self_in, size_t n_args, size_t n_kw, const mp_obj_t *args);
// this needs to be exposed for mp_getiter
mp_obj_t mp_obj_instance_getiter(mp_obj_t self_in, mp_obj_iter_buf_t *iter_buf);
#endif // MICROPY_INCLUDED_PY_OBJTYPE_H
| YifuLiu/AliOS-Things | components/py_engine/engine/py/objtype.h | C | apache-2.0 | 2,528 |
/*
* 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 <stdlib.h>
#include <assert.h>
#include "py/objtuple.h"
#include "py/runtime.h"
typedef struct _mp_obj_zip_t {
mp_obj_base_t base;
size_t n_iters;
mp_obj_t iters[];
} mp_obj_zip_t;
STATIC mp_obj_t zip_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
mp_arg_check_num(n_args, n_kw, 0, MP_OBJ_FUN_ARGS_MAX, false);
mp_obj_zip_t *o = m_new_obj_var(mp_obj_zip_t, mp_obj_t, n_args);
o->base.type = type;
o->n_iters = n_args;
for (size_t i = 0; i < n_args; i++) {
o->iters[i] = mp_getiter(args[i], NULL);
}
return MP_OBJ_FROM_PTR(o);
}
STATIC mp_obj_t zip_iternext(mp_obj_t self_in) {
mp_check_self(mp_obj_is_type(self_in, &mp_type_zip));
mp_obj_zip_t *self = MP_OBJ_TO_PTR(self_in);
if (self->n_iters == 0) {
return MP_OBJ_STOP_ITERATION;
}
mp_obj_tuple_t *tuple = MP_OBJ_TO_PTR(mp_obj_new_tuple(self->n_iters, NULL));
for (size_t i = 0; i < self->n_iters; i++) {
mp_obj_t next = mp_iternext(self->iters[i]);
if (next == MP_OBJ_STOP_ITERATION) {
mp_obj_tuple_del(MP_OBJ_FROM_PTR(tuple));
return MP_OBJ_STOP_ITERATION;
}
tuple->items[i] = next;
}
return MP_OBJ_FROM_PTR(tuple);
}
const mp_obj_type_t mp_type_zip = {
{ &mp_type_type },
.name = MP_QSTR_zip,
.make_new = zip_make_new,
.getiter = mp_identity_getiter,
.iternext = zip_iternext,
};
| YifuLiu/AliOS-Things | components/py_engine/engine/py/objzip.c | C | apache-2.0 | 2,688 |
/*
* 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 "py/obj.h"
#include "py/builtin.h"
STATIC mp_obj_t op_getitem(mp_obj_t self_in, mp_obj_t key_in) {
const mp_obj_type_t *type = mp_obj_get_type(self_in);
return type->subscr(self_in, key_in, MP_OBJ_SENTINEL);
}
MP_DEFINE_CONST_FUN_OBJ_2(mp_op_getitem_obj, op_getitem);
STATIC mp_obj_t op_setitem(mp_obj_t self_in, mp_obj_t key_in, mp_obj_t value_in) {
const mp_obj_type_t *type = mp_obj_get_type(self_in);
return type->subscr(self_in, key_in, value_in);
}
MP_DEFINE_CONST_FUN_OBJ_3(mp_op_setitem_obj, op_setitem);
STATIC mp_obj_t op_delitem(mp_obj_t self_in, mp_obj_t key_in) {
const mp_obj_type_t *type = mp_obj_get_type(self_in);
return type->subscr(self_in, key_in, MP_OBJ_NULL);
}
MP_DEFINE_CONST_FUN_OBJ_2(mp_op_delitem_obj, op_delitem);
STATIC mp_obj_t op_contains(mp_obj_t lhs_in, mp_obj_t rhs_in) {
const mp_obj_type_t *type = mp_obj_get_type(lhs_in);
return type->binary_op(MP_BINARY_OP_CONTAINS, lhs_in, rhs_in);
}
MP_DEFINE_CONST_FUN_OBJ_2(mp_op_contains_obj, op_contains);
| YifuLiu/AliOS-Things | components/py_engine/engine/py/opmethods.c | C | apache-2.0 | 2,261 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2020 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 "py/pairheap.h"
// The mp_pairheap_t.next pointer can take one of the following values:
// - NULL: the node is the top of the heap
// - LSB set: the node is the last of the children and points to its parent node
// - other: the node is a child and not the last child
// The macros below help manage this pointer.
#define NEXT_MAKE_RIGHTMOST_PARENT(parent) ((void *)((uintptr_t)(parent) | 1))
#define NEXT_IS_RIGHTMOST_PARENT(next) ((uintptr_t)(next) & 1)
#define NEXT_GET_RIGHTMOST_PARENT(next) ((void *)((uintptr_t)(next) & ~1))
// O(1), stable
mp_pairheap_t *mp_pairheap_meld(mp_pairheap_lt_t lt, mp_pairheap_t *heap1, mp_pairheap_t *heap2) {
if (heap1 == NULL) {
return heap2;
}
if (heap2 == NULL) {
return heap1;
}
if (lt(heap1, heap2)) {
if (heap1->child == NULL) {
heap1->child = heap2;
} else {
heap1->child_last->next = heap2;
}
heap1->child_last = heap2;
heap2->next = NEXT_MAKE_RIGHTMOST_PARENT(heap1);
return heap1;
} else {
heap1->next = heap2->child;
heap2->child = heap1;
if (heap1->next == NULL) {
heap2->child_last = heap1;
heap1->next = NEXT_MAKE_RIGHTMOST_PARENT(heap2);
}
return heap2;
}
}
// amortised O(log N), stable
mp_pairheap_t *mp_pairheap_pairing(mp_pairheap_lt_t lt, mp_pairheap_t *child) {
if (child == NULL) {
return NULL;
}
mp_pairheap_t *heap = NULL;
while (!NEXT_IS_RIGHTMOST_PARENT(child)) {
mp_pairheap_t *n1 = child;
child = child->next;
n1->next = NULL;
if (!NEXT_IS_RIGHTMOST_PARENT(child)) {
mp_pairheap_t *n2 = child;
child = child->next;
n2->next = NULL;
n1 = mp_pairheap_meld(lt, n1, n2);
}
heap = mp_pairheap_meld(lt, heap, n1);
}
heap->next = NULL;
return heap;
}
// amortised O(log N), stable
mp_pairheap_t *mp_pairheap_delete(mp_pairheap_lt_t lt, mp_pairheap_t *heap, mp_pairheap_t *node) {
// Simple case of the top being the node to delete
if (node == heap) {
mp_pairheap_t *child = heap->child;
node->child = NULL;
return mp_pairheap_pairing(lt, child);
}
// Case where node is not in the heap
if (node->next == NULL) {
return heap;
}
// Find parent of node
mp_pairheap_t *parent = node;
while (!NEXT_IS_RIGHTMOST_PARENT(parent->next)) {
parent = parent->next;
}
parent = NEXT_GET_RIGHTMOST_PARENT(parent->next);
// Replace node with pairing of its children
mp_pairheap_t *next;
if (node == parent->child && node->child == NULL) {
if (NEXT_IS_RIGHTMOST_PARENT(node->next)) {
parent->child = NULL;
} else {
parent->child = node->next;
}
node->next = NULL;
return heap;
} else if (node == parent->child) {
mp_pairheap_t *child = node->child;
next = node->next;
node->child = NULL;
node->next = NULL;
node = mp_pairheap_pairing(lt, child);
parent->child = node;
} else {
mp_pairheap_t *n = parent->child;
while (node != n->next) {
n = n->next;
}
mp_pairheap_t *child = node->child;
next = node->next;
node->child = NULL;
node->next = NULL;
node = mp_pairheap_pairing(lt, child);
if (node == NULL) {
node = n;
} else {
n->next = node;
}
}
node->next = next;
if (NEXT_IS_RIGHTMOST_PARENT(next)) {
parent->child_last = node;
}
return heap;
}
| YifuLiu/AliOS-Things | components/py_engine/engine/py/pairheap.c | C | apache-2.0 | 4,913 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2020 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.
*/
#ifndef MICROPY_INCLUDED_PY_PAIRHEAP_H
#define MICROPY_INCLUDED_PY_PAIRHEAP_H
// This is an implementation of a pairing heap. It is stable and has deletion
// support. Only the less-than operation needs to be defined on elements.
//
// See original paper for details:
// Michael L. Fredman, Robert Sedjewick, Daniel D. Sleator, and Robert E. Tarjan.
// The Pairing Heap: A New Form of Self-Adjusting Heap.
// Algorithmica 1:111-129, 1986.
// https://www.cs.cmu.edu/~sleator/papers/pairing-heaps.pdf
#include <assert.h>
#include "py/obj.h"
// This struct forms the nodes of the heap and is intended to be extended, by
// placing it first in another struct, to include additional information for the
// element stored in the heap. It includes "base" so it can be a MicroPython
// object allocated on the heap and the GC can automatically trace all nodes by
// following the tree structure.
typedef struct _mp_pairheap_t {
mp_obj_base_t base;
struct _mp_pairheap_t *child;
struct _mp_pairheap_t *child_last;
struct _mp_pairheap_t *next;
} mp_pairheap_t;
// This is the function for the less-than operation on nodes/elements.
typedef int (*mp_pairheap_lt_t)(mp_pairheap_t *, mp_pairheap_t *);
// Core functions.
mp_pairheap_t *mp_pairheap_meld(mp_pairheap_lt_t lt, mp_pairheap_t *heap1, mp_pairheap_t *heap2);
mp_pairheap_t *mp_pairheap_pairing(mp_pairheap_lt_t lt, mp_pairheap_t *child);
mp_pairheap_t *mp_pairheap_delete(mp_pairheap_lt_t lt, mp_pairheap_t *heap, mp_pairheap_t *node);
// Create a new heap.
static inline mp_pairheap_t *mp_pairheap_new(mp_pairheap_lt_t lt) {
(void)lt;
return NULL;
}
// Initialise a single pairing-heap node so it is ready to push on to a heap.
static inline void mp_pairheap_init_node(mp_pairheap_lt_t lt, mp_pairheap_t *node) {
(void)lt;
node->child = NULL;
node->next = NULL;
}
// Test if the heap is empty.
static inline bool mp_pairheap_is_empty(mp_pairheap_lt_t lt, mp_pairheap_t *heap) {
(void)lt;
return heap == NULL;
}
// Peek at the top of the heap. Will return NULL if empty.
static inline mp_pairheap_t *mp_pairheap_peek(mp_pairheap_lt_t lt, mp_pairheap_t *heap) {
(void)lt;
return heap;
}
// Push new node onto existing heap. Returns the new heap.
static inline mp_pairheap_t *mp_pairheap_push(mp_pairheap_lt_t lt, mp_pairheap_t *heap, mp_pairheap_t *node) {
assert(node->child == NULL && node->next == NULL);
return mp_pairheap_meld(lt, node, heap); // node is first to be stable
}
// Pop the top off the heap, which must not be empty. Returns the new heap.
static inline mp_pairheap_t *mp_pairheap_pop(mp_pairheap_lt_t lt, mp_pairheap_t *heap) {
assert(heap->next == NULL);
mp_pairheap_t *child = heap->child;
heap->child = NULL;
return mp_pairheap_pairing(lt, child);
}
#endif // MICROPY_INCLUDED_PY_PAIRHEAP_H
| YifuLiu/AliOS-Things | components/py_engine/engine/py/pairheap.h | C | apache-2.0 | 4,077 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2013-2017 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 <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <unistd.h> // for ssize_t
#include <assert.h>
#include <string.h>
#include "py/lexer.h"
#include "py/parse.h"
#include "py/parsenum.h"
#include "py/runtime.h"
#include "py/objint.h"
#include "py/objstr.h"
#include "py/builtin.h"
#if MICROPY_ENABLE_COMPILER
#define RULE_ACT_ARG_MASK (0x0f)
#define RULE_ACT_KIND_MASK (0x30)
#define RULE_ACT_ALLOW_IDENT (0x40)
#define RULE_ACT_ADD_BLANK (0x80)
#define RULE_ACT_OR (0x10)
#define RULE_ACT_AND (0x20)
#define RULE_ACT_LIST (0x30)
#define RULE_ARG_KIND_MASK (0xf000)
#define RULE_ARG_ARG_MASK (0x0fff)
#define RULE_ARG_TOK (0x1000)
#define RULE_ARG_RULE (0x2000)
#define RULE_ARG_OPT_RULE (0x3000)
// *FORMAT-OFF*
enum {
// define rules with a compile function
#define DEF_RULE(rule, comp, kind, ...) RULE_##rule,
#define DEF_RULE_NC(rule, kind, ...)
#include "py/grammar.h"
#undef DEF_RULE
#undef DEF_RULE_NC
RULE_const_object, // special node for a constant, generic Python object
// define rules without a compile function
#define DEF_RULE(rule, comp, kind, ...)
#define DEF_RULE_NC(rule, kind, ...) RULE_##rule,
#include "py/grammar.h"
#undef DEF_RULE
#undef DEF_RULE_NC
};
// Define an array of actions corresponding to each rule
STATIC const uint8_t rule_act_table[] = {
#define or(n) (RULE_ACT_OR | n)
#define and(n) (RULE_ACT_AND | n)
#define and_ident(n) (RULE_ACT_AND | n | RULE_ACT_ALLOW_IDENT)
#define and_blank(n) (RULE_ACT_AND | n | RULE_ACT_ADD_BLANK)
#define one_or_more (RULE_ACT_LIST | 2)
#define list (RULE_ACT_LIST | 1)
#define list_with_end (RULE_ACT_LIST | 3)
#define DEF_RULE(rule, comp, kind, ...) kind,
#define DEF_RULE_NC(rule, kind, ...)
#include "py/grammar.h"
#undef DEF_RULE
#undef DEF_RULE_NC
0, // RULE_const_object
#define DEF_RULE(rule, comp, kind, ...)
#define DEF_RULE_NC(rule, kind, ...) kind,
#include "py/grammar.h"
#undef DEF_RULE
#undef DEF_RULE_NC
#undef or
#undef and
#undef and_ident
#undef and_blank
#undef one_or_more
#undef list
#undef list_with_end
};
// Define the argument data for each rule, as a combined array
STATIC const uint16_t rule_arg_combined_table[] = {
#define tok(t) (RULE_ARG_TOK | MP_TOKEN_##t)
#define rule(r) (RULE_ARG_RULE | RULE_##r)
#define opt_rule(r) (RULE_ARG_OPT_RULE | RULE_##r)
#define DEF_RULE(rule, comp, kind, ...) __VA_ARGS__,
#define DEF_RULE_NC(rule, kind, ...)
#include "py/grammar.h"
#undef DEF_RULE
#undef DEF_RULE_NC
#define DEF_RULE(rule, comp, kind, ...)
#define DEF_RULE_NC(rule, kind, ...) __VA_ARGS__,
#include "py/grammar.h"
#undef DEF_RULE
#undef DEF_RULE_NC
#undef tok
#undef rule
#undef opt_rule
};
// Macro to create a list of N identifiers where N is the number of variable arguments to the macro
#define RULE_EXPAND(x) x
#define RULE_PADDING(rule, ...) RULE_PADDING2(rule, __VA_ARGS__, RULE_PADDING_IDS(rule))
#define RULE_PADDING2(rule, ...) RULE_EXPAND(RULE_PADDING3(rule, __VA_ARGS__))
#define RULE_PADDING3(rule, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, ...) __VA_ARGS__
#define RULE_PADDING_IDS(r) PAD13_##r, PAD12_##r, PAD11_##r, PAD10_##r, PAD9_##r, PAD8_##r, PAD7_##r, PAD6_##r, PAD5_##r, PAD4_##r, PAD3_##r, PAD2_##r, PAD1_##r,
// Use an enum to create constants specifying how much room a rule takes in rule_arg_combined_table
enum {
#define DEF_RULE(rule, comp, kind, ...) RULE_PADDING(rule, __VA_ARGS__)
#define DEF_RULE_NC(rule, kind, ...)
#include "py/grammar.h"
#undef DEF_RULE
#undef DEF_RULE_NC
#define DEF_RULE(rule, comp, kind, ...)
#define DEF_RULE_NC(rule, kind, ...) RULE_PADDING(rule, __VA_ARGS__)
#include "py/grammar.h"
#undef DEF_RULE
#undef DEF_RULE_NC
};
// Macro to compute the start of a rule in rule_arg_combined_table
#define RULE_ARG_OFFSET(rule, ...) RULE_ARG_OFFSET2(rule, __VA_ARGS__, RULE_ARG_OFFSET_IDS(rule))
#define RULE_ARG_OFFSET2(rule, ...) RULE_EXPAND(RULE_ARG_OFFSET3(rule, __VA_ARGS__))
#define RULE_ARG_OFFSET3(rule, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, ...) _14
#define RULE_ARG_OFFSET_IDS(r) PAD13_##r, PAD12_##r, PAD11_##r, PAD10_##r, PAD9_##r, PAD8_##r, PAD7_##r, PAD6_##r, PAD5_##r, PAD4_##r, PAD3_##r, PAD2_##r, PAD1_##r, PAD0_##r,
// Use the above enum values to create a table of offsets for each rule's arg
// data, which indexes rule_arg_combined_table. The offsets require 9 bits of
// storage but only the lower 8 bits are stored here. The 9th bit is computed
// in get_rule_arg using the FIRST_RULE_WITH_OFFSET_ABOVE_255 constant.
STATIC const uint8_t rule_arg_offset_table[] = {
#define DEF_RULE(rule, comp, kind, ...) RULE_ARG_OFFSET(rule, __VA_ARGS__) & 0xff,
#define DEF_RULE_NC(rule, kind, ...)
#include "py/grammar.h"
#undef DEF_RULE
#undef DEF_RULE_NC
0, // RULE_const_object
#define DEF_RULE(rule, comp, kind, ...)
#define DEF_RULE_NC(rule, kind, ...) RULE_ARG_OFFSET(rule, __VA_ARGS__) & 0xff,
#include "py/grammar.h"
#undef DEF_RULE
#undef DEF_RULE_NC
};
// Define a constant that's used to determine the 9th bit of the values in rule_arg_offset_table
static const size_t FIRST_RULE_WITH_OFFSET_ABOVE_255 =
#define DEF_RULE(rule, comp, kind, ...) RULE_ARG_OFFSET(rule, __VA_ARGS__) >= 0x100 ? RULE_##rule :
#define DEF_RULE_NC(rule, kind, ...)
#include "py/grammar.h"
#undef DEF_RULE
#undef DEF_RULE_NC
#define DEF_RULE(rule, comp, kind, ...)
#define DEF_RULE_NC(rule, kind, ...) RULE_ARG_OFFSET(rule, __VA_ARGS__) >= 0x100 ? RULE_##rule :
#include "py/grammar.h"
#undef DEF_RULE
#undef DEF_RULE_NC
0;
#if MICROPY_DEBUG_PARSE_RULE_NAME
// Define an array of rule names corresponding to each rule
STATIC const char *const rule_name_table[] = {
#define DEF_RULE(rule, comp, kind, ...) #rule,
#define DEF_RULE_NC(rule, kind, ...)
#include "py/grammar.h"
#undef DEF_RULE
#undef DEF_RULE_NC
"", // RULE_const_object
#define DEF_RULE(rule, comp, kind, ...)
#define DEF_RULE_NC(rule, kind, ...) #rule,
#include "py/grammar.h"
#undef DEF_RULE
#undef DEF_RULE_NC
};
#endif
// *FORMAT-ON*
typedef struct _rule_stack_t {
size_t src_line : (8 * sizeof(size_t) - 8); // maximum bits storing source line number
size_t rule_id : 8; // this must be large enough to fit largest rule number
size_t arg_i; // this dictates the maximum nodes in a "list" of things
} rule_stack_t;
typedef struct _mp_parse_chunk_t {
size_t alloc;
union {
size_t used;
struct _mp_parse_chunk_t *next;
} union_;
byte data[];
} mp_parse_chunk_t;
typedef struct _parser_t {
size_t rule_stack_alloc;
size_t rule_stack_top;
rule_stack_t *rule_stack;
size_t result_stack_alloc;
size_t result_stack_top;
mp_parse_node_t *result_stack;
mp_lexer_t *lexer;
mp_parse_tree_t tree;
mp_parse_chunk_t *cur_chunk;
#if MICROPY_COMP_CONST
mp_map_t consts;
#endif
} parser_t;
STATIC const uint16_t *get_rule_arg(uint8_t r_id) {
size_t off = rule_arg_offset_table[r_id];
if (r_id >= FIRST_RULE_WITH_OFFSET_ABOVE_255) {
off |= 0x100;
}
return &rule_arg_combined_table[off];
}
STATIC void *parser_alloc(parser_t *parser, size_t num_bytes) {
// use a custom memory allocator to store parse nodes sequentially in large chunks
mp_parse_chunk_t *chunk = parser->cur_chunk;
if (chunk != NULL && chunk->union_.used + num_bytes > chunk->alloc) {
// not enough room at end of previously allocated chunk so try to grow
mp_parse_chunk_t *new_data = (mp_parse_chunk_t *)m_renew_maybe(byte, chunk,
sizeof(mp_parse_chunk_t) + chunk->alloc,
sizeof(mp_parse_chunk_t) + chunk->alloc + num_bytes, false);
if (new_data == NULL) {
// could not grow existing memory; shrink it to fit previous
(void)m_renew_maybe(byte, chunk, sizeof(mp_parse_chunk_t) + chunk->alloc,
sizeof(mp_parse_chunk_t) + chunk->union_.used, false);
chunk->alloc = chunk->union_.used;
chunk->union_.next = parser->tree.chunk;
parser->tree.chunk = chunk;
chunk = NULL;
} else {
// could grow existing memory
chunk->alloc += num_bytes;
}
}
if (chunk == NULL) {
// no previous chunk, allocate a new chunk
size_t alloc = MICROPY_ALLOC_PARSE_CHUNK_INIT;
if (alloc < num_bytes) {
alloc = num_bytes;
}
chunk = (mp_parse_chunk_t *)m_new(byte, sizeof(mp_parse_chunk_t) + alloc);
chunk->alloc = alloc;
chunk->union_.used = 0;
parser->cur_chunk = chunk;
}
byte *ret = chunk->data + chunk->union_.used;
chunk->union_.used += num_bytes;
return ret;
}
STATIC void push_rule(parser_t *parser, size_t src_line, uint8_t rule_id, size_t arg_i) {
if (parser->rule_stack_top >= parser->rule_stack_alloc) {
rule_stack_t *rs = m_renew(rule_stack_t, parser->rule_stack, parser->rule_stack_alloc, parser->rule_stack_alloc + MICROPY_ALLOC_PARSE_RULE_INC);
parser->rule_stack = rs;
parser->rule_stack_alloc += MICROPY_ALLOC_PARSE_RULE_INC;
}
rule_stack_t *rs = &parser->rule_stack[parser->rule_stack_top++];
rs->src_line = src_line;
rs->rule_id = rule_id;
rs->arg_i = arg_i;
}
STATIC void push_rule_from_arg(parser_t *parser, size_t arg) {
assert((arg & RULE_ARG_KIND_MASK) == RULE_ARG_RULE || (arg & RULE_ARG_KIND_MASK) == RULE_ARG_OPT_RULE);
size_t rule_id = arg & RULE_ARG_ARG_MASK;
push_rule(parser, parser->lexer->tok_line, rule_id, 0);
}
STATIC uint8_t pop_rule(parser_t *parser, size_t *arg_i, size_t *src_line) {
parser->rule_stack_top -= 1;
uint8_t rule_id = parser->rule_stack[parser->rule_stack_top].rule_id;
*arg_i = parser->rule_stack[parser->rule_stack_top].arg_i;
*src_line = parser->rule_stack[parser->rule_stack_top].src_line;
return rule_id;
}
bool mp_parse_node_is_const_false(mp_parse_node_t pn) {
return MP_PARSE_NODE_IS_TOKEN_KIND(pn, MP_TOKEN_KW_FALSE)
|| (MP_PARSE_NODE_IS_SMALL_INT(pn) && MP_PARSE_NODE_LEAF_SMALL_INT(pn) == 0);
}
bool mp_parse_node_is_const_true(mp_parse_node_t pn) {
return MP_PARSE_NODE_IS_TOKEN_KIND(pn, MP_TOKEN_KW_TRUE)
|| (MP_PARSE_NODE_IS_SMALL_INT(pn) && MP_PARSE_NODE_LEAF_SMALL_INT(pn) != 0);
}
bool mp_parse_node_get_int_maybe(mp_parse_node_t pn, mp_obj_t *o) {
if (MP_PARSE_NODE_IS_SMALL_INT(pn)) {
*o = MP_OBJ_NEW_SMALL_INT(MP_PARSE_NODE_LEAF_SMALL_INT(pn));
return true;
} else if (MP_PARSE_NODE_IS_STRUCT_KIND(pn, RULE_const_object)) {
mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn;
#if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_D
// nodes are 32-bit pointers, but need to extract 64-bit object
*o = (uint64_t)pns->nodes[0] | ((uint64_t)pns->nodes[1] << 32);
#else
*o = (mp_obj_t)pns->nodes[0];
#endif
return mp_obj_is_int(*o);
} else {
return false;
}
}
size_t mp_parse_node_extract_list(mp_parse_node_t *pn, size_t pn_kind, mp_parse_node_t **nodes) {
if (MP_PARSE_NODE_IS_NULL(*pn)) {
*nodes = NULL;
return 0;
} else if (MP_PARSE_NODE_IS_LEAF(*pn)) {
*nodes = pn;
return 1;
} else {
mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)(*pn);
if (MP_PARSE_NODE_STRUCT_KIND(pns) != pn_kind) {
*nodes = pn;
return 1;
} else {
*nodes = pns->nodes;
return MP_PARSE_NODE_STRUCT_NUM_NODES(pns);
}
}
}
#if MICROPY_DEBUG_PRINTERS
void mp_parse_node_print(const mp_print_t *print, mp_parse_node_t pn, size_t indent) {
if (MP_PARSE_NODE_IS_STRUCT(pn)) {
mp_printf(print, "[% 4d] ", (int)((mp_parse_node_struct_t *)pn)->source_line);
} else {
mp_printf(print, " ");
}
for (size_t i = 0; i < indent; i++) {
mp_printf(print, " ");
}
if (MP_PARSE_NODE_IS_NULL(pn)) {
mp_printf(print, "NULL\n");
} else if (MP_PARSE_NODE_IS_SMALL_INT(pn)) {
mp_int_t arg = MP_PARSE_NODE_LEAF_SMALL_INT(pn);
mp_printf(print, "int(" INT_FMT ")\n", arg);
} else if (MP_PARSE_NODE_IS_LEAF(pn)) {
uintptr_t arg = MP_PARSE_NODE_LEAF_ARG(pn);
switch (MP_PARSE_NODE_LEAF_KIND(pn)) {
case MP_PARSE_NODE_ID:
mp_printf(print, "id(%s)\n", qstr_str(arg));
break;
case MP_PARSE_NODE_STRING:
mp_printf(print, "str(%s)\n", qstr_str(arg));
break;
case MP_PARSE_NODE_BYTES:
mp_printf(print, "bytes(%s)\n", qstr_str(arg));
break;
default:
assert(MP_PARSE_NODE_LEAF_KIND(pn) == MP_PARSE_NODE_TOKEN);
mp_printf(print, "tok(%u)\n", (uint)arg);
break;
}
} else {
// node must be a mp_parse_node_struct_t
mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn;
if (MP_PARSE_NODE_STRUCT_KIND(pns) == RULE_const_object) {
#if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_D
mp_printf(print, "literal const(%016llx)\n", (uint64_t)pns->nodes[0] | ((uint64_t)pns->nodes[1] << 32));
#else
mp_printf(print, "literal const(%p)\n", (mp_obj_t)pns->nodes[0]);
#endif
} else {
size_t n = MP_PARSE_NODE_STRUCT_NUM_NODES(pns);
#if MICROPY_DEBUG_PARSE_RULE_NAME
mp_printf(print, "%s(%u) (n=%u)\n", rule_name_table[MP_PARSE_NODE_STRUCT_KIND(pns)], (uint)MP_PARSE_NODE_STRUCT_KIND(pns), (uint)n);
#else
mp_printf(print, "rule(%u) (n=%u)\n", (uint)MP_PARSE_NODE_STRUCT_KIND(pns), (uint)n);
#endif
for (size_t i = 0; i < n; i++) {
mp_parse_node_print(print, pns->nodes[i], indent + 2);
}
}
}
}
#endif // MICROPY_DEBUG_PRINTERS
/*
STATIC void result_stack_show(const mp_print_t *print, parser_t *parser) {
mp_printf(print, "result stack, most recent first\n");
for (ssize_t i = parser->result_stack_top - 1; i >= 0; i--) {
mp_parse_node_print(print, parser->result_stack[i], 0);
}
}
*/
STATIC mp_parse_node_t pop_result(parser_t *parser) {
assert(parser->result_stack_top > 0);
return parser->result_stack[--parser->result_stack_top];
}
STATIC mp_parse_node_t peek_result(parser_t *parser, size_t pos) {
assert(parser->result_stack_top > pos);
return parser->result_stack[parser->result_stack_top - 1 - pos];
}
STATIC void push_result_node(parser_t *parser, mp_parse_node_t pn) {
if (parser->result_stack_top >= parser->result_stack_alloc) {
mp_parse_node_t *stack = m_renew(mp_parse_node_t, parser->result_stack, parser->result_stack_alloc, parser->result_stack_alloc + MICROPY_ALLOC_PARSE_RESULT_INC);
parser->result_stack = stack;
parser->result_stack_alloc += MICROPY_ALLOC_PARSE_RESULT_INC;
}
parser->result_stack[parser->result_stack_top++] = pn;
}
STATIC mp_parse_node_t make_node_const_object(parser_t *parser, size_t src_line, mp_obj_t obj) {
mp_parse_node_struct_t *pn = parser_alloc(parser, sizeof(mp_parse_node_struct_t) + sizeof(mp_obj_t));
pn->source_line = src_line;
#if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_D
// nodes are 32-bit pointers, but need to store 64-bit object
pn->kind_num_nodes = RULE_const_object | (2 << 8);
pn->nodes[0] = (uint64_t)obj;
pn->nodes[1] = (uint64_t)obj >> 32;
#else
pn->kind_num_nodes = RULE_const_object | (1 << 8);
pn->nodes[0] = (uintptr_t)obj;
#endif
return (mp_parse_node_t)pn;
}
STATIC mp_parse_node_t mp_parse_node_new_small_int_checked(parser_t *parser, mp_obj_t o_val) {
(void)parser;
mp_int_t val = MP_OBJ_SMALL_INT_VALUE(o_val);
#if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_D
// A parse node is only 32-bits and the small-int value must fit in 31-bits
if (((val ^ (val << 1)) & 0xffffffff80000000) != 0) {
return make_node_const_object(parser, 0, o_val);
}
#endif
return mp_parse_node_new_small_int(val);
}
STATIC void push_result_token(parser_t *parser, uint8_t rule_id) {
mp_parse_node_t pn;
mp_lexer_t *lex = parser->lexer;
if (lex->tok_kind == MP_TOKEN_NAME) {
qstr id = qstr_from_strn(lex->vstr.buf, lex->vstr.len);
#if MICROPY_COMP_CONST
// if name is a standalone identifier, look it up in the table of dynamic constants
mp_map_elem_t *elem;
if (rule_id == RULE_atom
&& (elem = mp_map_lookup(&parser->consts, MP_OBJ_NEW_QSTR(id), MP_MAP_LOOKUP)) != NULL) {
if (mp_obj_is_small_int(elem->value)) {
pn = mp_parse_node_new_small_int_checked(parser, elem->value);
} else {
pn = make_node_const_object(parser, lex->tok_line, elem->value);
}
} else {
pn = mp_parse_node_new_leaf(MP_PARSE_NODE_ID, id);
}
#else
(void)rule_id;
pn = mp_parse_node_new_leaf(MP_PARSE_NODE_ID, id);
#endif
} else if (lex->tok_kind == MP_TOKEN_INTEGER) {
mp_obj_t o = mp_parse_num_integer(lex->vstr.buf, lex->vstr.len, 0, lex);
if (mp_obj_is_small_int(o)) {
pn = mp_parse_node_new_small_int_checked(parser, o);
} else {
pn = make_node_const_object(parser, lex->tok_line, o);
}
} else if (lex->tok_kind == MP_TOKEN_FLOAT_OR_IMAG) {
mp_obj_t o = mp_parse_num_decimal(lex->vstr.buf, lex->vstr.len, true, false, lex);
pn = make_node_const_object(parser, lex->tok_line, o);
} else if (lex->tok_kind == MP_TOKEN_STRING || lex->tok_kind == MP_TOKEN_BYTES) {
// Don't automatically intern all strings/bytes. doc strings (which are usually large)
// will be discarded by the compiler, and so we shouldn't intern them.
qstr qst = MP_QSTRnull;
if (lex->vstr.len <= MICROPY_ALLOC_PARSE_INTERN_STRING_LEN) {
// intern short strings
qst = qstr_from_strn(lex->vstr.buf, lex->vstr.len);
} else {
// check if this string is already interned
qst = qstr_find_strn(lex->vstr.buf, lex->vstr.len);
}
if (qst != MP_QSTRnull) {
// qstr exists, make a leaf node
pn = mp_parse_node_new_leaf(lex->tok_kind == MP_TOKEN_STRING ? MP_PARSE_NODE_STRING : MP_PARSE_NODE_BYTES, qst);
} else {
// not interned, make a node holding a pointer to the string/bytes object
mp_obj_t o = mp_obj_new_str_copy(
lex->tok_kind == MP_TOKEN_STRING ? &mp_type_str : &mp_type_bytes,
(const byte *)lex->vstr.buf, lex->vstr.len);
pn = make_node_const_object(parser, lex->tok_line, o);
}
} else {
pn = mp_parse_node_new_leaf(MP_PARSE_NODE_TOKEN, lex->tok_kind);
}
push_result_node(parser, pn);
}
#if MICROPY_COMP_MODULE_CONST
STATIC const mp_rom_map_elem_t mp_constants_table[] = {
#if MICROPY_PY_UERRNO
{ MP_ROM_QSTR(MP_QSTR_errno), MP_ROM_PTR(&mp_module_uerrno) },
#endif
#if MICROPY_PY_UCTYPES
{ MP_ROM_QSTR(MP_QSTR_uctypes), MP_ROM_PTR(&mp_module_uctypes) },
#endif
// Extra constants as defined by a port
MICROPY_PORT_CONSTANTS
};
STATIC MP_DEFINE_CONST_MAP(mp_constants_map, mp_constants_table);
#endif
STATIC void push_result_rule(parser_t *parser, size_t src_line, uint8_t rule_id, size_t num_args);
#if MICROPY_COMP_CONST_FOLDING
STATIC bool fold_logical_constants(parser_t *parser, uint8_t rule_id, size_t *num_args) {
if (rule_id == RULE_or_test
|| rule_id == RULE_and_test) {
// folding for binary logical ops: or and
size_t copy_to = *num_args;
for (size_t i = copy_to; i > 0;) {
mp_parse_node_t pn = peek_result(parser, --i);
parser->result_stack[parser->result_stack_top - copy_to] = pn;
if (i == 0) {
// always need to keep the last value
break;
}
if (rule_id == RULE_or_test) {
if (mp_parse_node_is_const_true(pn)) {
//
break;
} else if (!mp_parse_node_is_const_false(pn)) {
copy_to -= 1;
}
} else {
// RULE_and_test
if (mp_parse_node_is_const_false(pn)) {
break;
} else if (!mp_parse_node_is_const_true(pn)) {
copy_to -= 1;
}
}
}
copy_to -= 1; // copy_to now contains number of args to pop
// pop and discard all the short-circuited expressions
for (size_t i = 0; i < copy_to; ++i) {
pop_result(parser);
}
*num_args -= copy_to;
// we did a complete folding if there's only 1 arg left
return *num_args == 1;
} else if (rule_id == RULE_not_test_2) {
// folding for unary logical op: not
mp_parse_node_t pn = peek_result(parser, 0);
if (mp_parse_node_is_const_false(pn)) {
pn = mp_parse_node_new_leaf(MP_PARSE_NODE_TOKEN, MP_TOKEN_KW_TRUE);
} else if (mp_parse_node_is_const_true(pn)) {
pn = mp_parse_node_new_leaf(MP_PARSE_NODE_TOKEN, MP_TOKEN_KW_FALSE);
} else {
return false;
}
pop_result(parser);
push_result_node(parser, pn);
return true;
}
return false;
}
STATIC bool fold_constants(parser_t *parser, uint8_t rule_id, size_t num_args) {
// this code does folding of arbitrary integer expressions, eg 1 + 2 * 3 + 4
// it does not do partial folding, eg 1 + 2 + x -> 3 + x
mp_obj_t arg0;
if (rule_id == RULE_expr
|| rule_id == RULE_xor_expr
|| rule_id == RULE_and_expr
|| rule_id == RULE_power) {
// folding for binary ops: | ^ & **
mp_parse_node_t pn = peek_result(parser, num_args - 1);
if (!mp_parse_node_get_int_maybe(pn, &arg0)) {
return false;
}
mp_binary_op_t op;
if (rule_id == RULE_expr) {
op = MP_BINARY_OP_OR;
} else if (rule_id == RULE_xor_expr) {
op = MP_BINARY_OP_XOR;
} else if (rule_id == RULE_and_expr) {
op = MP_BINARY_OP_AND;
} else {
op = MP_BINARY_OP_POWER;
}
for (ssize_t i = num_args - 2; i >= 0; --i) {
pn = peek_result(parser, i);
mp_obj_t arg1;
if (!mp_parse_node_get_int_maybe(pn, &arg1)) {
return false;
}
if (op == MP_BINARY_OP_POWER && mp_obj_int_sign(arg1) < 0) {
// ** can't have negative rhs
return false;
}
arg0 = mp_binary_op(op, arg0, arg1);
}
} else if (rule_id == RULE_shift_expr
|| rule_id == RULE_arith_expr
|| rule_id == RULE_term) {
// folding for binary ops: << >> + - * @ / % //
mp_parse_node_t pn = peek_result(parser, num_args - 1);
if (!mp_parse_node_get_int_maybe(pn, &arg0)) {
return false;
}
for (ssize_t i = num_args - 2; i >= 1; i -= 2) {
pn = peek_result(parser, i - 1);
mp_obj_t arg1;
if (!mp_parse_node_get_int_maybe(pn, &arg1)) {
return false;
}
mp_token_kind_t tok = MP_PARSE_NODE_LEAF_ARG(peek_result(parser, i));
if (tok == MP_TOKEN_OP_AT || tok == MP_TOKEN_OP_SLASH) {
// Can't fold @ or /
return false;
}
mp_binary_op_t op = MP_BINARY_OP_LSHIFT + (tok - MP_TOKEN_OP_DBL_LESS);
int rhs_sign = mp_obj_int_sign(arg1);
if (op <= MP_BINARY_OP_RSHIFT) {
// << and >> can't have negative rhs
if (rhs_sign < 0) {
return false;
}
} else if (op >= MP_BINARY_OP_FLOOR_DIVIDE) {
// % and // can't have zero rhs
if (rhs_sign == 0) {
return false;
}
}
arg0 = mp_binary_op(op, arg0, arg1);
}
} else if (rule_id == RULE_factor_2) {
// folding for unary ops: + - ~
mp_parse_node_t pn = peek_result(parser, 0);
if (!mp_parse_node_get_int_maybe(pn, &arg0)) {
return false;
}
mp_token_kind_t tok = MP_PARSE_NODE_LEAF_ARG(peek_result(parser, 1));
mp_unary_op_t op;
if (tok == MP_TOKEN_OP_TILDE) {
op = MP_UNARY_OP_INVERT;
} else {
assert(tok == MP_TOKEN_OP_PLUS || tok == MP_TOKEN_OP_MINUS); // should be
op = MP_UNARY_OP_POSITIVE + (tok - MP_TOKEN_OP_PLUS);
}
arg0 = mp_unary_op(op, arg0);
#if MICROPY_COMP_CONST
} else if (rule_id == RULE_expr_stmt) {
mp_parse_node_t pn1 = peek_result(parser, 0);
if (!MP_PARSE_NODE_IS_NULL(pn1)
&& !(MP_PARSE_NODE_IS_STRUCT_KIND(pn1, RULE_expr_stmt_augassign)
|| MP_PARSE_NODE_IS_STRUCT_KIND(pn1, RULE_expr_stmt_assign_list))) {
// this node is of the form <x> = <y>
mp_parse_node_t pn0 = peek_result(parser, 1);
if (MP_PARSE_NODE_IS_ID(pn0)
&& MP_PARSE_NODE_IS_STRUCT_KIND(pn1, RULE_atom_expr_normal)
&& MP_PARSE_NODE_IS_ID(((mp_parse_node_struct_t *)pn1)->nodes[0])
&& MP_PARSE_NODE_LEAF_ARG(((mp_parse_node_struct_t *)pn1)->nodes[0]) == MP_QSTR_const
&& MP_PARSE_NODE_IS_STRUCT_KIND(((mp_parse_node_struct_t *)pn1)->nodes[1], RULE_trailer_paren)
) {
// code to assign dynamic constants: id = const(value)
// get the id
qstr id = MP_PARSE_NODE_LEAF_ARG(pn0);
// get the value
mp_parse_node_t pn_value = ((mp_parse_node_struct_t *)((mp_parse_node_struct_t *)pn1)->nodes[1])->nodes[0];
mp_obj_t value;
if (!mp_parse_node_get_int_maybe(pn_value, &value)) {
mp_obj_t exc = mp_obj_new_exception_msg(&mp_type_SyntaxError,
MP_ERROR_TEXT("constant must be an integer"));
mp_obj_exception_add_traceback(exc, parser->lexer->source_name,
((mp_parse_node_struct_t *)pn1)->source_line, MP_QSTRnull);
nlr_raise(exc);
}
// store the value in the table of dynamic constants
mp_map_elem_t *elem = mp_map_lookup(&parser->consts, MP_OBJ_NEW_QSTR(id), MP_MAP_LOOKUP_ADD_IF_NOT_FOUND);
assert(elem->value == MP_OBJ_NULL);
elem->value = value;
// If the constant starts with an underscore then treat it as a private
// variable and don't emit any code to store the value to the id.
if (qstr_str(id)[0] == '_') {
pop_result(parser); // pop const(value)
pop_result(parser); // pop id
push_result_rule(parser, 0, RULE_pass_stmt, 0); // replace with "pass"
return true;
}
// replace const(value) with value
pop_result(parser);
push_result_node(parser, pn_value);
// finished folding this assignment, but we still want it to be part of the tree
return false;
}
}
return false;
#endif
#if MICROPY_COMP_MODULE_CONST
} else if (rule_id == RULE_atom_expr_normal) {
mp_parse_node_t pn0 = peek_result(parser, 1);
mp_parse_node_t pn1 = peek_result(parser, 0);
if (!(MP_PARSE_NODE_IS_ID(pn0)
&& MP_PARSE_NODE_IS_STRUCT_KIND(pn1, RULE_trailer_period))) {
return false;
}
// id1.id2
// look it up in constant table, see if it can be replaced with an integer
mp_parse_node_struct_t *pns1 = (mp_parse_node_struct_t *)pn1;
assert(MP_PARSE_NODE_IS_ID(pns1->nodes[0]));
qstr q_base = MP_PARSE_NODE_LEAF_ARG(pn0);
qstr q_attr = MP_PARSE_NODE_LEAF_ARG(pns1->nodes[0]);
mp_map_elem_t *elem = mp_map_lookup((mp_map_t *)&mp_constants_map, MP_OBJ_NEW_QSTR(q_base), MP_MAP_LOOKUP);
if (elem == NULL) {
return false;
}
mp_obj_t dest[2];
mp_load_method_maybe(elem->value, q_attr, dest);
if (!(dest[0] != MP_OBJ_NULL && mp_obj_is_int(dest[0]) && dest[1] == MP_OBJ_NULL)) {
return false;
}
arg0 = dest[0];
#endif
} else {
return false;
}
// success folding this rule
for (size_t i = num_args; i > 0; i--) {
pop_result(parser);
}
if (mp_obj_is_small_int(arg0)) {
push_result_node(parser, mp_parse_node_new_small_int_checked(parser, arg0));
} else {
// TODO reuse memory for parse node struct?
push_result_node(parser, make_node_const_object(parser, 0, arg0));
}
return true;
}
#endif
STATIC void push_result_rule(parser_t *parser, size_t src_line, uint8_t rule_id, size_t num_args) {
// optimise away parenthesis around an expression if possible
if (rule_id == RULE_atom_paren) {
// there should be just 1 arg for this rule
mp_parse_node_t pn = peek_result(parser, 0);
if (MP_PARSE_NODE_IS_NULL(pn)) {
// need to keep parenthesis for ()
} else if (MP_PARSE_NODE_IS_STRUCT_KIND(pn, RULE_testlist_comp)) {
// need to keep parenthesis for (a, b, ...)
} else {
// parenthesis around a single expression, so it's just the expression
return;
}
}
#if MICROPY_COMP_CONST_FOLDING
if (fold_logical_constants(parser, rule_id, &num_args)) {
// we folded this rule so return straight away
return;
}
if (fold_constants(parser, rule_id, num_args)) {
// we folded this rule so return straight away
return;
}
#endif
mp_parse_node_struct_t *pn = parser_alloc(parser, sizeof(mp_parse_node_struct_t) + sizeof(mp_parse_node_t) * num_args);
pn->source_line = src_line;
pn->kind_num_nodes = (rule_id & 0xff) | (num_args << 8);
for (size_t i = num_args; i > 0; i--) {
pn->nodes[i - 1] = pop_result(parser);
}
push_result_node(parser, (mp_parse_node_t)pn);
}
mp_parse_tree_t mp_parse(mp_lexer_t *lex, mp_parse_input_kind_t input_kind) {
// initialise parser and allocate memory for its stacks
parser_t parser;
parser.rule_stack_alloc = MICROPY_ALLOC_PARSE_RULE_INIT;
parser.rule_stack_top = 0;
parser.rule_stack = m_new(rule_stack_t, parser.rule_stack_alloc);
parser.result_stack_alloc = MICROPY_ALLOC_PARSE_RESULT_INIT;
parser.result_stack_top = 0;
parser.result_stack = m_new(mp_parse_node_t, parser.result_stack_alloc);
parser.lexer = lex;
parser.tree.chunk = NULL;
parser.cur_chunk = NULL;
#if MICROPY_COMP_CONST
mp_map_init(&parser.consts, 0);
#endif
// work out the top-level rule to use, and push it on the stack
size_t top_level_rule;
switch (input_kind) {
case MP_PARSE_SINGLE_INPUT:
top_level_rule = RULE_single_input;
break;
case MP_PARSE_EVAL_INPUT:
top_level_rule = RULE_eval_input;
break;
default:
top_level_rule = RULE_file_input;
}
push_rule(&parser, lex->tok_line, top_level_rule, 0);
// parse!
bool backtrack = false;
for (;;) {
next_rule:
if (parser.rule_stack_top == 0) {
break;
}
// Pop the next rule to process it
size_t i; // state for the current rule
size_t rule_src_line; // source line for the first token matched by the current rule
uint8_t rule_id = pop_rule(&parser, &i, &rule_src_line);
uint8_t rule_act = rule_act_table[rule_id];
const uint16_t *rule_arg = get_rule_arg(rule_id);
size_t n = rule_act & RULE_ACT_ARG_MASK;
#if 0
// debugging
printf("depth=" UINT_FMT " ", parser.rule_stack_top);
for (int j = 0; j < parser.rule_stack_top; ++j) {
printf(" ");
}
printf("%s n=" UINT_FMT " i=" UINT_FMT " bt=%d\n", rule_name_table[rule_id], n, i, backtrack);
#endif
switch (rule_act & RULE_ACT_KIND_MASK) {
case RULE_ACT_OR:
if (i > 0 && !backtrack) {
goto next_rule;
} else {
backtrack = false;
}
for (; i < n; ++i) {
uint16_t kind = rule_arg[i] & RULE_ARG_KIND_MASK;
if (kind == RULE_ARG_TOK) {
if (lex->tok_kind == (rule_arg[i] & RULE_ARG_ARG_MASK)) {
push_result_token(&parser, rule_id);
mp_lexer_to_next(lex);
goto next_rule;
}
} else {
assert(kind == RULE_ARG_RULE);
if (i + 1 < n) {
push_rule(&parser, rule_src_line, rule_id, i + 1); // save this or-rule
}
push_rule_from_arg(&parser, rule_arg[i]); // push child of or-rule
goto next_rule;
}
}
backtrack = true;
break;
case RULE_ACT_AND: {
// failed, backtrack if we can, else syntax error
if (backtrack) {
assert(i > 0);
if ((rule_arg[i - 1] & RULE_ARG_KIND_MASK) == RULE_ARG_OPT_RULE) {
// an optional rule that failed, so continue with next arg
push_result_node(&parser, MP_PARSE_NODE_NULL);
backtrack = false;
} else {
// a mandatory rule that failed, so propagate backtrack
if (i > 1) {
// already eaten tokens so can't backtrack
goto syntax_error;
} else {
goto next_rule;
}
}
}
// progress through the rule
for (; i < n; ++i) {
if ((rule_arg[i] & RULE_ARG_KIND_MASK) == RULE_ARG_TOK) {
// need to match a token
mp_token_kind_t tok_kind = rule_arg[i] & RULE_ARG_ARG_MASK;
if (lex->tok_kind == tok_kind) {
// matched token
if (tok_kind == MP_TOKEN_NAME) {
push_result_token(&parser, rule_id);
}
mp_lexer_to_next(lex);
} else {
// failed to match token
if (i > 0) {
// already eaten tokens so can't backtrack
goto syntax_error;
} else {
// this rule failed, so backtrack
backtrack = true;
goto next_rule;
}
}
} else {
push_rule(&parser, rule_src_line, rule_id, i + 1); // save this and-rule
push_rule_from_arg(&parser, rule_arg[i]); // push child of and-rule
goto next_rule;
}
}
assert(i == n);
// matched the rule, so now build the corresponding parse_node
#if !MICROPY_ENABLE_DOC_STRING
// this code discards lonely statements, such as doc strings
if (input_kind != MP_PARSE_SINGLE_INPUT && rule_id == RULE_expr_stmt && peek_result(&parser, 0) == MP_PARSE_NODE_NULL) {
mp_parse_node_t p = peek_result(&parser, 1);
if ((MP_PARSE_NODE_IS_LEAF(p) && !MP_PARSE_NODE_IS_ID(p))
|| MP_PARSE_NODE_IS_STRUCT_KIND(p, RULE_const_object)) {
pop_result(&parser); // MP_PARSE_NODE_NULL
pop_result(&parser); // const expression (leaf or RULE_const_object)
// Pushing the "pass" rule here will overwrite any RULE_const_object
// entry that was on the result stack, allowing the GC to reclaim
// the memory from the const object when needed.
push_result_rule(&parser, rule_src_line, RULE_pass_stmt, 0);
break;
}
}
#endif
// count number of arguments for the parse node
i = 0;
size_t num_not_nil = 0;
for (size_t x = n; x > 0;) {
--x;
if ((rule_arg[x] & RULE_ARG_KIND_MASK) == RULE_ARG_TOK) {
mp_token_kind_t tok_kind = rule_arg[x] & RULE_ARG_ARG_MASK;
if (tok_kind == MP_TOKEN_NAME) {
// only tokens which were names are pushed to stack
i += 1;
num_not_nil += 1;
}
} else {
// rules are always pushed
if (peek_result(&parser, i) != MP_PARSE_NODE_NULL) {
num_not_nil += 1;
}
i += 1;
}
}
if (num_not_nil == 1 && (rule_act & RULE_ACT_ALLOW_IDENT)) {
// this rule has only 1 argument and should not be emitted
mp_parse_node_t pn = MP_PARSE_NODE_NULL;
for (size_t x = 0; x < i; ++x) {
mp_parse_node_t pn2 = pop_result(&parser);
if (pn2 != MP_PARSE_NODE_NULL) {
pn = pn2;
}
}
push_result_node(&parser, pn);
} else {
// this rule must be emitted
if (rule_act & RULE_ACT_ADD_BLANK) {
// and add an extra blank node at the end (used by the compiler to store data)
push_result_node(&parser, MP_PARSE_NODE_NULL);
i += 1;
}
push_result_rule(&parser, rule_src_line, rule_id, i);
}
break;
}
default: {
assert((rule_act & RULE_ACT_KIND_MASK) == RULE_ACT_LIST);
// n=2 is: item item*
// n=1 is: item (sep item)*
// n=3 is: item (sep item)* [sep]
bool had_trailing_sep;
if (backtrack) {
list_backtrack:
had_trailing_sep = false;
if (n == 2) {
if (i == 1) {
// fail on item, first time round; propagate backtrack
goto next_rule;
} else {
// fail on item, in later rounds; finish with this rule
backtrack = false;
}
} else {
if (i == 1) {
// fail on item, first time round; propagate backtrack
goto next_rule;
} else if ((i & 1) == 1) {
// fail on item, in later rounds; have eaten tokens so can't backtrack
if (n == 3) {
// list allows trailing separator; finish parsing list
had_trailing_sep = true;
backtrack = false;
} else {
// list doesn't allowing trailing separator; fail
goto syntax_error;
}
} else {
// fail on separator; finish parsing list
backtrack = false;
}
}
} else {
for (;;) {
size_t arg = rule_arg[i & 1 & n];
if ((arg & RULE_ARG_KIND_MASK) == RULE_ARG_TOK) {
if (lex->tok_kind == (arg & RULE_ARG_ARG_MASK)) {
if (i & 1 & n) {
// separators which are tokens are not pushed to result stack
} else {
push_result_token(&parser, rule_id);
}
mp_lexer_to_next(lex);
// got element of list, so continue parsing list
i += 1;
} else {
// couldn't get element of list
i += 1;
backtrack = true;
goto list_backtrack;
}
} else {
assert((arg & RULE_ARG_KIND_MASK) == RULE_ARG_RULE);
push_rule(&parser, rule_src_line, rule_id, i + 1); // save this list-rule
push_rule_from_arg(&parser, arg); // push child of list-rule
goto next_rule;
}
}
}
assert(i >= 1);
// compute number of elements in list, result in i
i -= 1;
if ((n & 1) && (rule_arg[1] & RULE_ARG_KIND_MASK) == RULE_ARG_TOK) {
// don't count separators when they are tokens
i = (i + 1) / 2;
}
if (i == 1) {
// list matched single item
if (had_trailing_sep) {
// if there was a trailing separator, make a list of a single item
push_result_rule(&parser, rule_src_line, rule_id, i);
} else {
// just leave single item on stack (ie don't wrap in a list)
}
} else {
push_result_rule(&parser, rule_src_line, rule_id, i);
}
break;
}
}
}
#if MICROPY_COMP_CONST
mp_map_deinit(&parser.consts);
#endif
// truncate final chunk and link into chain of chunks
if (parser.cur_chunk != NULL) {
(void)m_renew_maybe(byte, parser.cur_chunk,
sizeof(mp_parse_chunk_t) + parser.cur_chunk->alloc,
sizeof(mp_parse_chunk_t) + parser.cur_chunk->union_.used,
false);
parser.cur_chunk->alloc = parser.cur_chunk->union_.used;
parser.cur_chunk->union_.next = parser.tree.chunk;
parser.tree.chunk = parser.cur_chunk;
}
if (
lex->tok_kind != MP_TOKEN_END // check we are at the end of the token stream
|| parser.result_stack_top == 0 // check that we got a node (can fail on empty input)
) {
syntax_error:;
mp_obj_t exc;
if (lex->tok_kind == MP_TOKEN_INDENT) {
exc = mp_obj_new_exception_msg(&mp_type_IndentationError,
MP_ERROR_TEXT("unexpected indent"));
} else if (lex->tok_kind == MP_TOKEN_DEDENT_MISMATCH) {
exc = mp_obj_new_exception_msg(&mp_type_IndentationError,
MP_ERROR_TEXT("unindent doesn't match any outer indent level"));
#if MICROPY_PY_FSTRINGS
} else if (lex->tok_kind == MP_TOKEN_MALFORMED_FSTRING) {
exc = mp_obj_new_exception_msg(&mp_type_SyntaxError,
MP_ERROR_TEXT("malformed f-string"));
} else if (lex->tok_kind == MP_TOKEN_FSTRING_RAW) {
exc = mp_obj_new_exception_msg(&mp_type_SyntaxError,
MP_ERROR_TEXT("raw f-strings are not supported"));
#endif
} else {
exc = mp_obj_new_exception_msg(&mp_type_SyntaxError,
MP_ERROR_TEXT("invalid syntax"));
}
// add traceback to give info about file name and location
// we don't have a 'block' name, so just pass the NULL qstr to indicate this
mp_obj_exception_add_traceback(exc, lex->source_name, lex->tok_line, MP_QSTRnull);
nlr_raise(exc);
}
// get the root parse node that we created
assert(parser.result_stack_top == 1);
parser.tree.root = parser.result_stack[0];
// free the memory that we don't need anymore
m_del(rule_stack_t, parser.rule_stack, parser.rule_stack_alloc);
m_del(mp_parse_node_t, parser.result_stack, parser.result_stack_alloc);
// we also free the lexer on behalf of the caller
mp_lexer_free(lex);
return parser.tree;
}
void mp_parse_tree_clear(mp_parse_tree_t *tree) {
mp_parse_chunk_t *chunk = tree->chunk;
while (chunk != NULL) {
mp_parse_chunk_t *next = chunk->union_.next;
m_del(byte, chunk, sizeof(mp_parse_chunk_t) + chunk->alloc);
chunk = next;
}
}
#endif // MICROPY_ENABLE_COMPILER
| YifuLiu/AliOS-Things | components/py_engine/engine/py/parse.c | C | apache-2.0 | 47,301 |
/*
* 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.
*/
#ifndef MICROPY_INCLUDED_PY_PARSE_H
#define MICROPY_INCLUDED_PY_PARSE_H
#include <stddef.h>
#include <stdint.h>
#include "py/obj.h"
struct _mp_lexer_t;
// a mp_parse_node_t is:
// - 0000...0000: no node
// - xxxx...xxx1: a small integer; bits 1 and above are the signed value, 2's complement
// - xxxx...xx00: pointer to mp_parse_node_struct_t
// - xx...xx0010: an identifier; bits 4 and above are the qstr
// - xx...xx0110: a string; bits 4 and above are the qstr holding the value
// - xx...xx1010: a string of bytes; bits 4 and above are the qstr holding the value
// - xx...xx1110: a token; bits 4 and above are mp_token_kind_t
#define MP_PARSE_NODE_NULL (0)
#define MP_PARSE_NODE_SMALL_INT (0x1)
#define MP_PARSE_NODE_ID (0x02)
#define MP_PARSE_NODE_STRING (0x06)
#define MP_PARSE_NODE_BYTES (0x0a)
#define MP_PARSE_NODE_TOKEN (0x0e)
typedef uintptr_t mp_parse_node_t; // must be pointer size
typedef struct _mp_parse_node_struct_t {
uint32_t source_line; // line number in source file
uint32_t kind_num_nodes; // parse node kind, and number of nodes
mp_parse_node_t nodes[]; // nodes
} mp_parse_node_struct_t;
// macros for mp_parse_node_t usage
// some of these evaluate their argument more than once
#define MP_PARSE_NODE_IS_NULL(pn) ((pn) == MP_PARSE_NODE_NULL)
#define MP_PARSE_NODE_IS_LEAF(pn) ((pn) & 3)
#define MP_PARSE_NODE_IS_STRUCT(pn) ((pn) != MP_PARSE_NODE_NULL && ((pn) & 3) == 0)
#define MP_PARSE_NODE_IS_STRUCT_KIND(pn, k) ((pn) != MP_PARSE_NODE_NULL && ((pn) & 3) == 0 && MP_PARSE_NODE_STRUCT_KIND((mp_parse_node_struct_t *)(pn)) == (k))
#define MP_PARSE_NODE_IS_SMALL_INT(pn) (((pn) & 0x1) == MP_PARSE_NODE_SMALL_INT)
#define MP_PARSE_NODE_IS_ID(pn) (((pn) & 0x0f) == MP_PARSE_NODE_ID)
#define MP_PARSE_NODE_IS_TOKEN(pn) (((pn) & 0x0f) == MP_PARSE_NODE_TOKEN)
#define MP_PARSE_NODE_IS_TOKEN_KIND(pn, k) ((pn) == (MP_PARSE_NODE_TOKEN | ((k) << 4)))
#define MP_PARSE_NODE_LEAF_KIND(pn) ((pn) & 0x0f)
#define MP_PARSE_NODE_LEAF_ARG(pn) (((uintptr_t)(pn)) >> 4)
#define MP_PARSE_NODE_LEAF_SMALL_INT(pn) (((mp_int_t)(intptr_t)(pn)) >> 1)
#define MP_PARSE_NODE_STRUCT_KIND(pns) ((pns)->kind_num_nodes & 0xff)
#define MP_PARSE_NODE_STRUCT_NUM_NODES(pns) ((pns)->kind_num_nodes >> 8)
static inline mp_parse_node_t mp_parse_node_new_small_int(mp_int_t val) {
return (mp_parse_node_t)(MP_PARSE_NODE_SMALL_INT | ((mp_uint_t)val << 1));
}
static inline mp_parse_node_t mp_parse_node_new_leaf(size_t kind, mp_int_t arg) {
return (mp_parse_node_t)(kind | ((mp_uint_t)arg << 4));
}
bool mp_parse_node_is_const_false(mp_parse_node_t pn);
bool mp_parse_node_is_const_true(mp_parse_node_t pn);
bool mp_parse_node_get_int_maybe(mp_parse_node_t pn, mp_obj_t *o);
size_t mp_parse_node_extract_list(mp_parse_node_t *pn, size_t pn_kind, mp_parse_node_t **nodes);
void mp_parse_node_print(const mp_print_t *print, mp_parse_node_t pn, size_t indent);
typedef enum {
MP_PARSE_SINGLE_INPUT,
MP_PARSE_FILE_INPUT,
MP_PARSE_EVAL_INPUT,
} mp_parse_input_kind_t;
typedef struct _mp_parse_t {
mp_parse_node_t root;
struct _mp_parse_chunk_t *chunk;
} mp_parse_tree_t;
// the parser will raise an exception if an error occurred
// the parser will free the lexer before it returns
mp_parse_tree_t mp_parse(struct _mp_lexer_t *lex, mp_parse_input_kind_t input_kind);
void mp_parse_tree_clear(mp_parse_tree_t *tree);
#endif // MICROPY_INCLUDED_PY_PARSE_H
| YifuLiu/AliOS-Things | components/py_engine/engine/py/parse.h | C | apache-2.0 | 4,669 |
/*
* 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 <stdbool.h>
#include <stdlib.h>
#include "py/runtime.h"
#include "py/parsenumbase.h"
#include "py/parsenum.h"
#include "py/smallint.h"
#if MICROPY_PY_BUILTINS_FLOAT
#include <math.h>
#endif
STATIC NORETURN void raise_exc(mp_obj_t exc, mp_lexer_t *lex) {
// if lex!=NULL then the parser called us and we need to convert the
// exception's type from ValueError to SyntaxError and add traceback info
if (lex != NULL) {
((mp_obj_base_t *)MP_OBJ_TO_PTR(exc))->type = &mp_type_SyntaxError;
mp_obj_exception_add_traceback(exc, lex->source_name, lex->tok_line, MP_QSTRnull);
}
nlr_raise(exc);
}
mp_obj_t mp_parse_num_integer(const char *restrict str_, size_t len, int base, mp_lexer_t *lex) {
const byte *restrict str = (const byte *)str_;
const byte *restrict top = str + len;
bool neg = false;
mp_obj_t ret_val;
// check radix base
if ((base != 0 && base < 2) || base > 36) {
// this won't be reached if lex!=NULL
mp_raise_ValueError(MP_ERROR_TEXT("int() arg 2 must be >= 2 and <= 36"));
}
// skip leading space
for (; str < top && unichar_isspace(*str); str++) {
}
// parse optional sign
if (str < top) {
if (*str == '+') {
str++;
} else if (*str == '-') {
str++;
neg = true;
}
}
// parse optional base prefix
str += mp_parse_num_base((const char *)str, top - str, &base);
// string should be an integer number
mp_int_t int_val = 0;
const byte *restrict str_val_start = str;
for (; str < top; str++) {
// get next digit as a value
mp_uint_t dig = *str;
if ('0' <= dig && dig <= '9') {
dig -= '0';
} else if (dig == '_') {
continue;
} else {
dig |= 0x20; // make digit lower-case
if ('a' <= dig && dig <= 'z') {
dig -= 'a' - 10;
} else {
// unknown character
break;
}
}
if (dig >= (mp_uint_t)base) {
break;
}
// add next digi and check for overflow
if (mp_small_int_mul_overflow(int_val, base)) {
goto overflow;
}
int_val = int_val * base + dig;
if (!MP_SMALL_INT_FITS(int_val)) {
goto overflow;
}
}
// negate value if needed
if (neg) {
int_val = -int_val;
}
// create the small int
ret_val = MP_OBJ_NEW_SMALL_INT(int_val);
have_ret_val:
// check we parsed something
if (str == str_val_start) {
goto value_error;
}
// skip trailing space
for (; str < top && unichar_isspace(*str); str++) {
}
// check we reached the end of the string
if (str != top) {
goto value_error;
}
// return the object
return ret_val;
overflow:
// reparse using long int
{
const char *s2 = (const char *)str_val_start;
ret_val = mp_obj_new_int_from_str_len(&s2, top - str_val_start, neg, base);
str = (const byte *)s2;
goto have_ret_val;
}
value_error:
{
#if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
mp_obj_t exc = mp_obj_new_exception_msg(&mp_type_ValueError,
MP_ERROR_TEXT("invalid syntax for integer"));
raise_exc(exc, lex);
#elif MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_NORMAL
mp_obj_t exc = mp_obj_new_exception_msg_varg(&mp_type_ValueError,
MP_ERROR_TEXT("invalid syntax for integer with base %d"), base);
raise_exc(exc, lex);
#else
vstr_t vstr;
mp_print_t print;
vstr_init_print(&vstr, 50, &print);
mp_printf(&print, "invalid syntax for integer with base %d: ", base);
mp_str_print_quoted(&print, str_val_start, top - str_val_start, true);
mp_obj_t exc = mp_obj_new_exception_arg1(&mp_type_ValueError,
mp_obj_new_str_from_vstr(&mp_type_str, &vstr));
raise_exc(exc, lex);
#endif
}
}
typedef enum {
PARSE_DEC_IN_INTG,
PARSE_DEC_IN_FRAC,
PARSE_DEC_IN_EXP,
} parse_dec_in_t;
mp_obj_t mp_parse_num_decimal(const char *str, size_t len, bool allow_imag, bool force_complex, mp_lexer_t *lex) {
#if MICROPY_PY_BUILTINS_FLOAT
// DEC_VAL_MAX only needs to be rough and is used to retain precision while not overflowing
// SMALL_NORMAL_VAL is the smallest power of 10 that is still a normal float
// EXACT_POWER_OF_10 is the largest value of x so that 10^x can be stored exactly in a float
// Note: EXACT_POWER_OF_10 is at least floor(log_5(2^mantissa_length)). Indeed, 10^n = 2^n * 5^n
// so we only have to store the 5^n part in the mantissa (the 2^n part will go into the float's
// exponent).
#if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT
#define DEC_VAL_MAX 1e20F
#define SMALL_NORMAL_VAL (1e-37F)
#define SMALL_NORMAL_EXP (-37)
#define EXACT_POWER_OF_10 (9)
#elif MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE
#define DEC_VAL_MAX 1e200
#define SMALL_NORMAL_VAL (1e-307)
#define SMALL_NORMAL_EXP (-307)
#define EXACT_POWER_OF_10 (22)
#endif
const char *top = str + len;
mp_float_t dec_val = 0;
bool dec_neg = false;
bool imag = false;
// skip leading space
for (; str < top && unichar_isspace(*str); str++) {
}
// parse optional sign
if (str < top) {
if (*str == '+') {
str++;
} else if (*str == '-') {
str++;
dec_neg = true;
}
}
const char *str_val_start = str;
// determine what the string is
if (str < top && (str[0] | 0x20) == 'i') {
// string starts with 'i', should be 'inf' or 'infinity' (case insensitive)
if (str + 2 < top && (str[1] | 0x20) == 'n' && (str[2] | 0x20) == 'f') {
// inf
str += 3;
dec_val = (mp_float_t)INFINITY;
if (str + 4 < top && (str[0] | 0x20) == 'i' && (str[1] | 0x20) == 'n' && (str[2] | 0x20) == 'i' && (str[3] | 0x20) == 't' && (str[4] | 0x20) == 'y') {
// infinity
str += 5;
}
}
} else if (str < top && (str[0] | 0x20) == 'n') {
// string starts with 'n', should be 'nan' (case insensitive)
if (str + 2 < top && (str[1] | 0x20) == 'a' && (str[2] | 0x20) == 'n') {
// NaN
str += 3;
dec_val = MICROPY_FLOAT_C_FUN(nan)("");
}
} else {
// string should be a decimal number
parse_dec_in_t in = PARSE_DEC_IN_INTG;
bool exp_neg = false;
int exp_val = 0;
int exp_extra = 0;
while (str < top) {
unsigned int dig = *str++;
if ('0' <= dig && dig <= '9') {
dig -= '0';
if (in == PARSE_DEC_IN_EXP) {
// don't overflow exp_val when adding next digit, instead just truncate
// it and the resulting float will still be correct, either inf or 0.0
// (use INT_MAX/2 to allow adding exp_extra at the end without overflow)
if (exp_val < (INT_MAX / 2 - 9) / 10) {
exp_val = 10 * exp_val + dig;
}
} else {
if (dec_val < DEC_VAL_MAX) {
// dec_val won't overflow so keep accumulating
dec_val = 10 * dec_val + dig;
if (in == PARSE_DEC_IN_FRAC) {
--exp_extra;
}
} else {
// dec_val might overflow and we anyway can't represent more digits
// of precision, so ignore the digit and just adjust the exponent
if (in == PARSE_DEC_IN_INTG) {
++exp_extra;
}
}
}
} else if (in == PARSE_DEC_IN_INTG && dig == '.') {
in = PARSE_DEC_IN_FRAC;
} else if (in != PARSE_DEC_IN_EXP && ((dig | 0x20) == 'e')) {
in = PARSE_DEC_IN_EXP;
if (str < top) {
if (str[0] == '+') {
str++;
} else if (str[0] == '-') {
str++;
exp_neg = true;
}
}
if (str == top) {
goto value_error;
}
} else if (allow_imag && (dig | 0x20) == 'j') {
imag = true;
break;
} else if (dig == '_') {
continue;
} else {
// unknown character
str--;
break;
}
}
// work out the exponent
if (exp_neg) {
exp_val = -exp_val;
}
// apply the exponent, making sure it's not a subnormal value
exp_val += exp_extra;
if (exp_val < SMALL_NORMAL_EXP) {
exp_val -= SMALL_NORMAL_EXP;
dec_val *= SMALL_NORMAL_VAL;
}
// At this point, we need to multiply the mantissa by its base 10 exponent. If possible,
// we would rather manipulate numbers that have an exact representation in IEEE754. It
// turns out small positive powers of 10 do, whereas small negative powers of 10 don't.
// So in that case, we'll yield a division of exact values rather than a multiplication
// of slightly erroneous values.
if (exp_val < 0 && exp_val >= -EXACT_POWER_OF_10) {
dec_val /= MICROPY_FLOAT_C_FUN(pow)(10, -exp_val);
} else {
dec_val *= MICROPY_FLOAT_C_FUN(pow)(10, exp_val);
}
}
// negate value if needed
if (dec_neg) {
dec_val = -dec_val;
}
// check we parsed something
if (str == str_val_start) {
goto value_error;
}
// skip trailing space
for (; str < top && unichar_isspace(*str); str++) {
}
// check we reached the end of the string
if (str != top) {
goto value_error;
}
// return the object
#if MICROPY_PY_BUILTINS_COMPLEX
if (imag) {
return mp_obj_new_complex(0, dec_val);
} else if (force_complex) {
return mp_obj_new_complex(dec_val, 0);
}
#else
if (imag || force_complex) {
raise_exc(mp_obj_new_exception_msg(&mp_type_ValueError, MP_ERROR_TEXT("complex values not supported")), lex);
}
#endif
else {
return mp_obj_new_float(dec_val);
}
value_error:
raise_exc(mp_obj_new_exception_msg(&mp_type_ValueError, MP_ERROR_TEXT("invalid syntax for number")), lex);
#else
raise_exc(mp_obj_new_exception_msg(&mp_type_ValueError, MP_ERROR_TEXT("decimal numbers not supported")), lex);
#endif
}
| YifuLiu/AliOS-Things | components/py_engine/engine/py/parsenum.c | C | apache-2.0 | 12,122 |
/*
* 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.
*/
#ifndef MICROPY_INCLUDED_PY_PARSENUM_H
#define MICROPY_INCLUDED_PY_PARSENUM_H
#include "py/mpconfig.h"
#include "py/lexer.h"
#include "py/obj.h"
// these functions raise a SyntaxError if lex!=NULL, else a ValueError
mp_obj_t mp_parse_num_integer(const char *restrict str, size_t len, int base, mp_lexer_t *lex);
mp_obj_t mp_parse_num_decimal(const char *str, size_t len, bool allow_imag, bool force_complex, mp_lexer_t *lex);
#endif // MICROPY_INCLUDED_PY_PARSENUM_H
| YifuLiu/AliOS-Things | components/py_engine/engine/py/parsenum.h | C | apache-2.0 | 1,701 |
/*
* 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 "py/mpconfig.h"
#include "py/misc.h"
#include "py/parsenumbase.h"
// find real radix base, and strip preceding '0x', '0o' and '0b'
// puts base in *base, and returns number of bytes to skip the prefix
size_t mp_parse_num_base(const char *str, size_t len, int *base) {
const byte *p = (const byte *)str;
if (len <= 1) {
goto no_prefix;
}
unichar c = *(p++);
if ((*base == 0 || *base == 16) && c == '0') {
c = *(p++);
if ((c | 32) == 'x') {
*base = 16;
} else if (*base == 0 && (c | 32) == 'o') {
*base = 8;
} else if (*base == 0 && (c | 32) == 'b') {
*base = 2;
} else {
if (*base == 0) {
*base = 10;
}
p -= 2;
}
} else if (*base == 8 && c == '0') {
c = *(p++);
if ((c | 32) != 'o') {
p -= 2;
}
} else if (*base == 2 && c == '0') {
c = *(p++);
if ((c | 32) != 'b') {
p -= 2;
}
} else {
p--;
no_prefix:
if (*base == 0) {
*base = 10;
}
}
return p - (const byte *)str;
}
| YifuLiu/AliOS-Things | components/py_engine/engine/py/parsenumbase.c | C | apache-2.0 | 2,405 |
/*
* 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.
*/
#ifndef MICROPY_INCLUDED_PY_PARSENUMBASE_H
#define MICROPY_INCLUDED_PY_PARSENUMBASE_H
#include "py/mpconfig.h"
size_t mp_parse_num_base(const char *str, size_t len, int *base);
#endif // MICROPY_INCLUDED_PY_PARSENUMBASE_H
| YifuLiu/AliOS-Things | components/py_engine/engine/py/parsenumbase.h | C | apache-2.0 | 1,456 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2013-2020 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 <stdint.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include "py/reader.h"
#include "py/nativeglue.h"
#include "py/persistentcode.h"
#include "py/bc0.h"
#include "py/objstr.h"
#include "py/mpthread.h"
#if MICROPY_PERSISTENT_CODE_LOAD || MICROPY_PERSISTENT_CODE_SAVE
#include "py/smallint.h"
#define QSTR_LAST_STATIC MP_QSTR_zip
#if MICROPY_DYNAMIC_COMPILER
#define MPY_FEATURE_ARCH_DYNAMIC mp_dynamic_compiler.native_arch
#else
#define MPY_FEATURE_ARCH_DYNAMIC MPY_FEATURE_ARCH
#endif
#if MICROPY_PERSISTENT_CODE_LOAD || (MICROPY_PERSISTENT_CODE_SAVE && !MICROPY_DYNAMIC_COMPILER)
// The bytecode will depend on the number of bits in a small-int, and
// this function computes that (could make it a fixed constant, but it
// would need to be defined in mpconfigport.h).
STATIC int mp_small_int_bits(void) {
mp_int_t i = MP_SMALL_INT_MAX;
int n = 1;
while (i != 0) {
i >>= 1;
++n;
}
return n;
}
#endif
#define QSTR_WINDOW_SIZE (32)
typedef struct _qstr_window_t {
uint16_t idx; // indexes the head of the window
uint16_t window[QSTR_WINDOW_SIZE];
} qstr_window_t;
// Push a qstr to the head of the window, and the tail qstr is overwritten
STATIC void qstr_window_push(qstr_window_t *qw, qstr qst) {
qw->idx = (qw->idx + 1) % QSTR_WINDOW_SIZE;
qw->window[qw->idx] = qst;
}
// Pull an existing qstr from within the window to the head of the window
STATIC qstr qstr_window_pull(qstr_window_t *qw, size_t idx) {
qstr qst = qw->window[idx];
if (idx > qw->idx) {
memmove(&qw->window[idx], &qw->window[idx + 1], (QSTR_WINDOW_SIZE - idx - 1) * sizeof(uint16_t));
qw->window[QSTR_WINDOW_SIZE - 1] = qw->window[0];
idx = 0;
}
memmove(&qw->window[idx], &qw->window[idx + 1], (qw->idx - idx) * sizeof(uint16_t));
qw->window[qw->idx] = qst;
return qst;
}
#if MICROPY_PERSISTENT_CODE_LOAD
// Access a qstr at the given index, relative to the head of the window (0=head)
STATIC qstr qstr_window_access(qstr_window_t *qw, size_t idx) {
return qstr_window_pull(qw, (qw->idx + QSTR_WINDOW_SIZE - idx) % QSTR_WINDOW_SIZE);
}
#endif
#if MICROPY_PERSISTENT_CODE_SAVE
// Insert a qstr at the head of the window, either by pulling an existing one or pushing a new one
STATIC size_t qstr_window_insert(qstr_window_t *qw, qstr qst) {
for (size_t idx = 0; idx < QSTR_WINDOW_SIZE; ++idx) {
if (qw->window[idx] == qst) {
qstr_window_pull(qw, idx);
return (qw->idx + QSTR_WINDOW_SIZE - idx) % QSTR_WINDOW_SIZE;
}
}
qstr_window_push(qw, qst);
return QSTR_WINDOW_SIZE;
}
#endif
typedef struct _bytecode_prelude_t {
uint n_state;
uint n_exc_stack;
uint scope_flags;
uint n_pos_args;
uint n_kwonly_args;
uint n_def_pos_args;
uint code_info_size;
} bytecode_prelude_t;
// ip will point to start of opcodes
// return value will point to simple_name, source_file qstrs
STATIC byte *extract_prelude(const byte **ip, bytecode_prelude_t *prelude) {
MP_BC_PRELUDE_SIG_DECODE(*ip);
prelude->n_state = n_state;
prelude->n_exc_stack = n_exc_stack;
prelude->scope_flags = scope_flags;
prelude->n_pos_args = n_pos_args;
prelude->n_kwonly_args = n_kwonly_args;
prelude->n_def_pos_args = n_def_pos_args;
MP_BC_PRELUDE_SIZE_DECODE(*ip);
byte *ip_info = (byte *)*ip;
*ip += n_info;
*ip += n_cell;
return ip_info;
}
#endif // MICROPY_PERSISTENT_CODE_LOAD || MICROPY_PERSISTENT_CODE_SAVE
#if MICROPY_PERSISTENT_CODE_LOAD
#include "py/parsenum.h"
STATIC int read_byte(mp_reader_t *reader);
STATIC size_t read_uint(mp_reader_t *reader, byte **out);
#if MICROPY_EMIT_MACHINE_CODE
typedef struct _reloc_info_t {
mp_reader_t *reader;
mp_uint_t *const_table;
} reloc_info_t;
#if MICROPY_EMIT_THUMB
STATIC void asm_thumb_rewrite_mov(uint8_t *pc, uint16_t val) {
// high part
*(uint16_t *)pc = (*(uint16_t *)pc & 0xfbf0) | (val >> 1 & 0x0400) | (val >> 12);
// low part
*(uint16_t *)(pc + 2) = (*(uint16_t *)(pc + 2) & 0x0f00) | (val << 4 & 0x7000) | (val & 0x00ff);
}
#endif
STATIC void arch_link_qstr(uint8_t *pc, bool is_obj, qstr qst) {
mp_uint_t val = qst;
if (is_obj) {
val = (mp_uint_t)MP_OBJ_NEW_QSTR(qst);
}
#if MICROPY_EMIT_X86 || MICROPY_EMIT_X64 || MICROPY_EMIT_ARM || MICROPY_EMIT_XTENSA || MICROPY_EMIT_XTENSAWIN
pc[0] = val & 0xff;
pc[1] = (val >> 8) & 0xff;
pc[2] = (val >> 16) & 0xff;
pc[3] = (val >> 24) & 0xff;
#elif MICROPY_EMIT_THUMB
if (is_obj) {
// qstr object, movw and movt
asm_thumb_rewrite_mov(pc, val); // movw
asm_thumb_rewrite_mov(pc + 4, val >> 16); // movt
} else {
// qstr number, movw instruction
asm_thumb_rewrite_mov(pc, val); // movw
}
#endif
}
void mp_native_relocate(void *ri_in, uint8_t *text, uintptr_t reloc_text) {
// Relocate native code
reloc_info_t *ri = ri_in;
uint8_t op;
uintptr_t *addr_to_adjust = NULL;
while ((op = read_byte(ri->reader)) != 0xff) {
if (op & 1) {
// Point to new location to make adjustments
size_t addr = read_uint(ri->reader, NULL);
if ((addr & 1) == 0) {
// Point to somewhere in text
addr_to_adjust = &((uintptr_t *)text)[addr >> 1];
} else {
// Point to somewhere in rodata
addr_to_adjust = &((uintptr_t *)ri->const_table[1])[addr >> 1];
}
}
op >>= 1;
uintptr_t dest;
size_t n = 1;
if (op <= 5) {
if (op & 1) {
// Read in number of adjustments to make
n = read_uint(ri->reader, NULL);
}
op >>= 1;
if (op == 0) {
// Destination is text
dest = reloc_text;
} else {
// Destination is rodata (op=1) or bss (op=1 if no rodata, else op=2)
dest = ri->const_table[op];
}
} else if (op == 6) {
// Destination is mp_fun_table itself
dest = (uintptr_t)&mp_fun_table;
} else {
// Destination is an entry in mp_fun_table
dest = ((uintptr_t *)&mp_fun_table)[op - 7];
}
while (n--) {
*addr_to_adjust++ += dest;
}
}
}
#endif
STATIC int read_byte(mp_reader_t *reader) {
return reader->readbyte(reader->data);
}
STATIC void read_bytes(mp_reader_t *reader, byte *buf, size_t len) {
while (len-- > 0) {
*buf++ = reader->readbyte(reader->data);
}
}
STATIC size_t read_uint(mp_reader_t *reader, byte **out) {
size_t unum = 0;
for (;;) {
byte b = reader->readbyte(reader->data);
if (out != NULL) {
**out = b;
++*out;
}
unum = (unum << 7) | (b & 0x7f);
if ((b & 0x80) == 0) {
break;
}
}
return unum;
}
STATIC qstr load_qstr(mp_reader_t *reader, qstr_window_t *qw) {
size_t len = read_uint(reader, NULL);
if (len == 0) {
// static qstr
return read_byte(reader);
}
if (len & 1) {
// qstr in window
return qstr_window_access(qw, len >> 1);
}
len >>= 1;
char *str = m_new(char, len);
read_bytes(reader, (byte *)str, len);
qstr qst = qstr_from_strn(str, len);
m_del(char, str, len);
qstr_window_push(qw, qst);
return qst;
}
STATIC mp_obj_t load_obj(mp_reader_t *reader) {
byte obj_type = read_byte(reader);
if (obj_type == 'e') {
return MP_OBJ_FROM_PTR(&mp_const_ellipsis_obj);
} else {
size_t len = read_uint(reader, NULL);
vstr_t vstr;
vstr_init_len(&vstr, len);
read_bytes(reader, (byte *)vstr.buf, len);
if (obj_type == 's' || obj_type == 'b') {
return mp_obj_new_str_from_vstr(obj_type == 's' ? &mp_type_str : &mp_type_bytes, &vstr);
} else if (obj_type == 'i') {
return mp_parse_num_integer(vstr.buf, vstr.len, 10, NULL);
} else {
assert(obj_type == 'f' || obj_type == 'c');
return mp_parse_num_decimal(vstr.buf, vstr.len, obj_type == 'c', false, NULL);
}
}
}
STATIC void load_prelude_qstrs(mp_reader_t *reader, qstr_window_t *qw, byte *ip) {
qstr simple_name = load_qstr(reader, qw);
ip[0] = simple_name;
ip[1] = simple_name >> 8;
qstr source_file = load_qstr(reader, qw);
ip[2] = source_file;
ip[3] = source_file >> 8;
}
STATIC void load_prelude(mp_reader_t *reader, qstr_window_t *qw, byte **ip, bytecode_prelude_t *prelude) {
// Read in the prelude header
byte *ip_read = *ip;
read_uint(reader, &ip_read); // read in n_state/etc (is effectively a var-uint)
read_uint(reader, &ip_read); // read in n_info/n_cell (is effectively a var-uint)
// Prelude header has been read into *ip, now decode and extract values from it
extract_prelude((const byte **)ip, prelude);
// Load qstrs in prelude
load_prelude_qstrs(reader, qw, ip_read);
ip_read += 4;
// Read remaining code info
read_bytes(reader, ip_read, *ip - ip_read);
}
STATIC void load_bytecode(mp_reader_t *reader, qstr_window_t *qw, byte *ip, byte *ip_top) {
while (ip < ip_top) {
*ip = read_byte(reader);
size_t sz;
uint f = mp_opcode_format(ip, &sz, false);
++ip;
--sz;
if (f == MP_BC_FORMAT_QSTR) {
qstr qst = load_qstr(reader, qw);
*ip++ = qst;
*ip++ = qst >> 8;
sz -= 2;
} else if (f == MP_BC_FORMAT_VAR_UINT) {
while ((*ip++ = read_byte(reader)) & 0x80) {
}
}
read_bytes(reader, ip, sz);
ip += sz;
}
}
STATIC mp_raw_code_t *load_raw_code(mp_reader_t *reader, qstr_window_t *qw) {
// Load function kind and data length
size_t kind_len = read_uint(reader, NULL);
int kind = (kind_len & 3) + MP_CODE_BYTECODE;
size_t fun_data_len = kind_len >> 2;
#if !MICROPY_EMIT_MACHINE_CODE
if (kind != MP_CODE_BYTECODE) {
mp_raise_ValueError(MP_ERROR_TEXT("incompatible .mpy file"));
}
#endif
uint8_t *fun_data = NULL;
bytecode_prelude_t prelude = {0};
#if MICROPY_EMIT_MACHINE_CODE
size_t prelude_offset = 0;
mp_uint_t type_sig = 0;
size_t n_qstr_link = 0;
#endif
if (kind == MP_CODE_BYTECODE) {
// Allocate memory for the bytecode
fun_data = m_new(uint8_t, fun_data_len);
// Load prelude
byte *ip = fun_data;
load_prelude(reader, qw, &ip, &prelude);
// Load bytecode
load_bytecode(reader, qw, ip, fun_data + fun_data_len);
#if MICROPY_EMIT_MACHINE_CODE
} else {
// Allocate memory for native data and load it
size_t fun_alloc;
MP_PLAT_ALLOC_EXEC(fun_data_len, (void **)&fun_data, &fun_alloc);
read_bytes(reader, fun_data, fun_data_len);
if (kind == MP_CODE_NATIVE_PY || kind == MP_CODE_NATIVE_VIPER) {
// Parse qstr link table and link native code
n_qstr_link = read_uint(reader, NULL);
for (size_t i = 0; i < n_qstr_link; ++i) {
size_t off = read_uint(reader, NULL);
qstr qst = load_qstr(reader, qw);
uint8_t *dest = fun_data + (off >> 2);
if ((off & 3) == 0) {
// Generic 16-bit link
dest[0] = qst & 0xff;
dest[1] = (qst >> 8) & 0xff;
} else if ((off & 3) == 3) {
// Generic, aligned qstr-object link
*(mp_obj_t *)dest = MP_OBJ_NEW_QSTR(qst);
} else {
// Architecture-specific link
arch_link_qstr(dest, (off & 3) == 2, qst);
}
}
}
if (kind == MP_CODE_NATIVE_PY) {
// Extract prelude for later use
prelude_offset = read_uint(reader, NULL);
const byte *ip = fun_data + prelude_offset;
byte *ip_info = extract_prelude(&ip, &prelude);
// Load qstrs in prelude
load_prelude_qstrs(reader, qw, ip_info);
} else {
// Load basic scope info for viper and asm
prelude.scope_flags = read_uint(reader, NULL);
prelude.n_pos_args = 0;
prelude.n_kwonly_args = 0;
if (kind == MP_CODE_NATIVE_ASM) {
prelude.n_pos_args = read_uint(reader, NULL);
type_sig = read_uint(reader, NULL);
}
}
#endif
}
size_t n_obj = 0;
size_t n_raw_code = 0;
mp_uint_t *const_table = NULL;
if (kind != MP_CODE_NATIVE_ASM) {
// Load constant table for bytecode, native and viper
// Number of entries in constant table
n_obj = read_uint(reader, NULL);
n_raw_code = read_uint(reader, NULL);
// Allocate constant table
size_t n_alloc = prelude.n_pos_args + prelude.n_kwonly_args + n_obj + n_raw_code;
#if MICROPY_EMIT_MACHINE_CODE
if (kind != MP_CODE_BYTECODE) {
++n_alloc; // additional entry for mp_fun_table
if (prelude.scope_flags & MP_SCOPE_FLAG_VIPERRODATA) {
++n_alloc; // additional entry for rodata
}
if (prelude.scope_flags & MP_SCOPE_FLAG_VIPERBSS) {
++n_alloc; // additional entry for BSS
}
}
#endif
const_table = m_new(mp_uint_t, n_alloc);
mp_uint_t *ct = const_table;
// Load function argument names (initial entries in const_table)
// (viper has n_pos_args=n_kwonly_args=0 so doesn't load any qstrs here)
for (size_t i = 0; i < prelude.n_pos_args + prelude.n_kwonly_args; ++i) {
*ct++ = (mp_uint_t)MP_OBJ_NEW_QSTR(load_qstr(reader, qw));
}
#if MICROPY_EMIT_MACHINE_CODE
if (kind != MP_CODE_BYTECODE) {
// Populate mp_fun_table entry
*ct++ = (mp_uint_t)(uintptr_t)&mp_fun_table;
// Allocate and load rodata if needed
if (prelude.scope_flags & MP_SCOPE_FLAG_VIPERRODATA) {
size_t size = read_uint(reader, NULL);
uint8_t *rodata = m_new(uint8_t, size);
read_bytes(reader, rodata, size);
*ct++ = (uintptr_t)rodata;
}
// Allocate BSS if needed
if (prelude.scope_flags & MP_SCOPE_FLAG_VIPERBSS) {
size_t size = read_uint(reader, NULL);
uint8_t *bss = m_new0(uint8_t, size);
*ct++ = (uintptr_t)bss;
}
}
#endif
// Load constant objects and raw code children
for (size_t i = 0; i < n_obj; ++i) {
*ct++ = (mp_uint_t)load_obj(reader);
}
for (size_t i = 0; i < n_raw_code; ++i) {
*ct++ = (mp_uint_t)(uintptr_t)load_raw_code(reader, qw);
}
}
// Create raw_code and return it
mp_raw_code_t *rc = mp_emit_glue_new_raw_code();
if (kind == MP_CODE_BYTECODE) {
// Assign bytecode to raw code object
mp_emit_glue_assign_bytecode(rc, fun_data,
#if MICROPY_PERSISTENT_CODE_SAVE || MICROPY_DEBUG_PRINTERS
fun_data_len,
#endif
const_table,
#if MICROPY_PERSISTENT_CODE_SAVE
n_obj, n_raw_code,
#endif
prelude.scope_flags);
#if MICROPY_EMIT_MACHINE_CODE
} else {
// Relocate and commit code to executable address space
reloc_info_t ri = {reader, const_table};
#if defined(MP_PLAT_COMMIT_EXEC)
void *opt_ri = (prelude.scope_flags & MP_SCOPE_FLAG_VIPERRELOC) ? &ri : NULL;
fun_data = MP_PLAT_COMMIT_EXEC(fun_data, fun_data_len, opt_ri);
#else
if (prelude.scope_flags & MP_SCOPE_FLAG_VIPERRELOC) {
#if MICROPY_PERSISTENT_CODE_TRACK_RELOC_CODE
// If native code needs relocations then it's not guaranteed that a pointer to
// the head of `buf` (containing the machine code) will be retained for the GC
// to trace. This is because native functions can start inside `buf` and so
// it's possible that the only GC-reachable pointers are pointers inside `buf`.
// So put this `buf` on a list of reachable root pointers.
if (MP_STATE_PORT(track_reloc_code_list) == MP_OBJ_NULL) {
MP_STATE_PORT(track_reloc_code_list) = mp_obj_new_list(0, NULL);
}
mp_obj_list_append(MP_STATE_PORT(track_reloc_code_list), MP_OBJ_FROM_PTR(fun_data));
#endif
// Do the relocations.
mp_native_relocate(&ri, fun_data, (uintptr_t)fun_data);
}
#endif
// Assign native code to raw code object
mp_emit_glue_assign_native(rc, kind,
fun_data, fun_data_len, const_table,
#if MICROPY_PERSISTENT_CODE_SAVE
prelude_offset,
n_obj, n_raw_code,
n_qstr_link, NULL,
#endif
prelude.n_pos_args, prelude.scope_flags, type_sig);
#endif
}
return rc;
}
mp_raw_code_t *mp_raw_code_load(mp_reader_t *reader) {
byte header[4];
read_bytes(reader, header, sizeof(header));
if (header[0] != 'M'
|| header[1] != MPY_VERSION
|| MPY_FEATURE_DECODE_FLAGS(header[2]) != MPY_FEATURE_FLAGS
|| header[3] > mp_small_int_bits()
|| read_uint(reader, NULL) > QSTR_WINDOW_SIZE) {
mp_raise_ValueError(MP_ERROR_TEXT("incompatible .mpy file"));
}
if (MPY_FEATURE_DECODE_ARCH(header[2]) != MP_NATIVE_ARCH_NONE) {
byte arch = MPY_FEATURE_DECODE_ARCH(header[2]);
if (!MPY_FEATURE_ARCH_TEST(arch)) {
mp_raise_ValueError(MP_ERROR_TEXT("incompatible .mpy arch"));
}
}
qstr_window_t qw;
qw.idx = 0;
mp_raw_code_t *rc = load_raw_code(reader, &qw);
reader->close(reader->data);
return rc;
}
mp_raw_code_t *mp_raw_code_load_mem(const byte *buf, size_t len) {
mp_reader_t reader;
mp_reader_new_mem(&reader, buf, len, 0);
return mp_raw_code_load(&reader);
}
#if MICROPY_HAS_FILE_READER
mp_raw_code_t *mp_raw_code_load_file(const char *filename) {
mp_reader_t reader;
mp_reader_new_file(&reader, filename);
return mp_raw_code_load(&reader);
}
#endif // MICROPY_HAS_FILE_READER
#endif // MICROPY_PERSISTENT_CODE_LOAD
#if MICROPY_PERSISTENT_CODE_SAVE
#include "py/objstr.h"
STATIC void mp_print_bytes(mp_print_t *print, const byte *data, size_t len) {
print->print_strn(print->data, (const char *)data, len);
}
#define BYTES_FOR_INT ((MP_BYTES_PER_OBJ_WORD * 8 + 6) / 7)
STATIC void mp_print_uint(mp_print_t *print, size_t n) {
byte buf[BYTES_FOR_INT];
byte *p = buf + sizeof(buf);
*--p = n & 0x7f;
n >>= 7;
for (; n != 0; n >>= 7) {
*--p = 0x80 | (n & 0x7f);
}
print->print_strn(print->data, (char *)p, buf + sizeof(buf) - p);
}
STATIC void save_qstr(mp_print_t *print, qstr_window_t *qw, qstr qst) {
if (qst <= QSTR_LAST_STATIC) {
// encode static qstr
byte buf[2] = {0, qst & 0xff};
mp_print_bytes(print, buf, 2);
return;
}
size_t idx = qstr_window_insert(qw, qst);
if (idx < QSTR_WINDOW_SIZE) {
// qstr found in window, encode index to it
mp_print_uint(print, idx << 1 | 1);
return;
}
size_t len;
const byte *str = qstr_data(qst, &len);
mp_print_uint(print, len << 1);
mp_print_bytes(print, str, len);
}
STATIC void save_obj(mp_print_t *print, mp_obj_t o) {
if (mp_obj_is_str_or_bytes(o)) {
byte obj_type;
if (mp_obj_is_str(o)) {
obj_type = 's';
} else {
obj_type = 'b';
}
size_t len;
const char *str = mp_obj_str_get_data(o, &len);
mp_print_bytes(print, &obj_type, 1);
mp_print_uint(print, len);
mp_print_bytes(print, (const byte *)str, len);
} else if (MP_OBJ_TO_PTR(o) == &mp_const_ellipsis_obj) {
byte obj_type = 'e';
mp_print_bytes(print, &obj_type, 1);
} else {
// we save numbers using a simplistic text representation
// TODO could be improved
byte obj_type;
if (mp_obj_is_type(o, &mp_type_int)) {
obj_type = 'i';
#if MICROPY_PY_BUILTINS_COMPLEX
} else if (mp_obj_is_type(o, &mp_type_complex)) {
obj_type = 'c';
#endif
} else {
assert(mp_obj_is_float(o));
obj_type = 'f';
}
vstr_t vstr;
mp_print_t pr;
vstr_init_print(&vstr, 10, &pr);
mp_obj_print_helper(&pr, o, PRINT_REPR);
mp_print_bytes(print, &obj_type, 1);
mp_print_uint(print, vstr.len);
mp_print_bytes(print, (const byte *)vstr.buf, vstr.len);
vstr_clear(&vstr);
}
}
STATIC void save_prelude_qstrs(mp_print_t *print, qstr_window_t *qw, const byte *ip) {
save_qstr(print, qw, ip[0] | (ip[1] << 8)); // simple_name
save_qstr(print, qw, ip[2] | (ip[3] << 8)); // source_file
}
STATIC void save_bytecode(mp_print_t *print, qstr_window_t *qw, const byte *ip, const byte *ip_top) {
while (ip < ip_top) {
size_t sz;
uint f = mp_opcode_format(ip, &sz, true);
if (f == MP_BC_FORMAT_QSTR) {
mp_print_bytes(print, ip, 1);
qstr qst = ip[1] | (ip[2] << 8);
save_qstr(print, qw, qst);
ip += 3;
sz -= 3;
}
mp_print_bytes(print, ip, sz);
ip += sz;
}
}
STATIC void save_raw_code(mp_print_t *print, mp_raw_code_t *rc, qstr_window_t *qstr_window) {
// Save function kind and data length
mp_print_uint(print, (rc->fun_data_len << 2) | (rc->kind - MP_CODE_BYTECODE));
bytecode_prelude_t prelude;
if (rc->kind == MP_CODE_BYTECODE) {
// Extract prelude
const byte *ip = rc->fun_data;
const byte *ip_info = extract_prelude(&ip, &prelude);
// Save prelude
mp_print_bytes(print, rc->fun_data, ip_info - (const byte *)rc->fun_data);
save_prelude_qstrs(print, qstr_window, ip_info);
ip_info += 4;
mp_print_bytes(print, ip_info, ip - ip_info);
// Save bytecode
const byte *ip_top = (const byte *)rc->fun_data + rc->fun_data_len;
save_bytecode(print, qstr_window, ip, ip_top);
#if MICROPY_EMIT_MACHINE_CODE
} else {
// Save native code
mp_print_bytes(print, rc->fun_data, rc->fun_data_len);
if (rc->kind == MP_CODE_NATIVE_PY || rc->kind == MP_CODE_NATIVE_VIPER) {
// Save qstr link table for native code
mp_print_uint(print, rc->n_qstr);
for (size_t i = 0; i < rc->n_qstr; ++i) {
mp_print_uint(print, rc->qstr_link[i].off);
save_qstr(print, qstr_window, rc->qstr_link[i].qst);
}
}
if (rc->kind == MP_CODE_NATIVE_PY) {
// Save prelude size
mp_print_uint(print, rc->prelude_offset);
// Extract prelude and save qstrs in prelude
const byte *ip = (const byte *)rc->fun_data + rc->prelude_offset;
const byte *ip_info = extract_prelude(&ip, &prelude);
save_prelude_qstrs(print, qstr_window, ip_info);
} else {
// Save basic scope info for viper and asm
mp_print_uint(print, rc->scope_flags & MP_SCOPE_FLAG_ALL_SIG);
prelude.n_pos_args = 0;
prelude.n_kwonly_args = 0;
if (rc->kind == MP_CODE_NATIVE_ASM) {
mp_print_uint(print, rc->n_pos_args);
mp_print_uint(print, rc->type_sig);
}
}
#endif
}
if (rc->kind != MP_CODE_NATIVE_ASM) {
// Save constant table for bytecode, native and viper
// Number of entries in constant table
mp_print_uint(print, rc->n_obj);
mp_print_uint(print, rc->n_raw_code);
const mp_uint_t *const_table = rc->const_table;
// Save function argument names (initial entries in const_table)
// (viper has n_pos_args=n_kwonly_args=0 so doesn't save any qstrs here)
for (size_t i = 0; i < prelude.n_pos_args + prelude.n_kwonly_args; ++i) {
mp_obj_t o = (mp_obj_t)*const_table++;
save_qstr(print, qstr_window, MP_OBJ_QSTR_VALUE(o));
}
if (rc->kind != MP_CODE_BYTECODE) {
// Skip saving mp_fun_table entry
++const_table;
}
// Save constant objects and raw code children
for (size_t i = 0; i < rc->n_obj; ++i) {
save_obj(print, (mp_obj_t)*const_table++);
}
for (size_t i = 0; i < rc->n_raw_code; ++i) {
save_raw_code(print, (mp_raw_code_t *)(uintptr_t)*const_table++, qstr_window);
}
}
}
STATIC bool mp_raw_code_has_native(mp_raw_code_t *rc) {
if (rc->kind != MP_CODE_BYTECODE) {
return true;
}
const byte *ip = rc->fun_data;
bytecode_prelude_t prelude;
extract_prelude(&ip, &prelude);
const mp_uint_t *const_table = rc->const_table
+ prelude.n_pos_args + prelude.n_kwonly_args
+ rc->n_obj;
for (size_t i = 0; i < rc->n_raw_code; ++i) {
if (mp_raw_code_has_native((mp_raw_code_t *)(uintptr_t)*const_table++)) {
return true;
}
}
return false;
}
void mp_raw_code_save(mp_raw_code_t *rc, mp_print_t *print) {
// header contains:
// byte 'M'
// byte version
// byte feature flags
// byte number of bits in a small int
// uint size of qstr window
byte header[4] = {
'M',
MPY_VERSION,
MPY_FEATURE_ENCODE_FLAGS(MPY_FEATURE_FLAGS_DYNAMIC),
#if MICROPY_DYNAMIC_COMPILER
mp_dynamic_compiler.small_int_bits,
#else
mp_small_int_bits(),
#endif
};
if (mp_raw_code_has_native(rc)) {
header[2] |= MPY_FEATURE_ENCODE_ARCH(MPY_FEATURE_ARCH_DYNAMIC);
}
mp_print_bytes(print, header, sizeof(header));
mp_print_uint(print, QSTR_WINDOW_SIZE);
qstr_window_t qw;
qw.idx = 0;
memset(qw.window, 0, sizeof(qw.window));
save_raw_code(print, rc, &qw);
}
#if MICROPY_PERSISTENT_CODE_SAVE_FILE
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
STATIC void fd_print_strn(void *env, const char *str, size_t len) {
int fd = (intptr_t)env;
MP_THREAD_GIL_EXIT();
ssize_t ret = write(fd, str, len);
MP_THREAD_GIL_ENTER();
(void)ret;
}
void mp_raw_code_save_file(mp_raw_code_t *rc, const char *filename) {
MP_THREAD_GIL_EXIT();
int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0644);
MP_THREAD_GIL_ENTER();
mp_print_t fd_print = {(void *)(intptr_t)fd, fd_print_strn};
mp_raw_code_save(rc, &fd_print);
MP_THREAD_GIL_EXIT();
close(fd);
MP_THREAD_GIL_ENTER();
}
#endif // MICROPY_PERSISTENT_CODE_SAVE_FILE
#endif // MICROPY_PERSISTENT_CODE_SAVE
| YifuLiu/AliOS-Things | components/py_engine/engine/py/persistentcode.c | C | apache-2.0 | 28,410 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2013-2016 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.
*/
#ifndef MICROPY_INCLUDED_PY_PERSISTENTCODE_H
#define MICROPY_INCLUDED_PY_PERSISTENTCODE_H
#include "py/mpprint.h"
#include "py/reader.h"
#include "py/emitglue.h"
// The current version of .mpy files
#define MPY_VERSION 5
// Macros to encode/decode flags to/from the feature byte
#define MPY_FEATURE_ENCODE_FLAGS(flags) (flags)
#define MPY_FEATURE_DECODE_FLAGS(feat) ((feat) & 3)
// Macros to encode/decode native architecture to/from the feature byte
#define MPY_FEATURE_ENCODE_ARCH(arch) ((arch) << 2)
#define MPY_FEATURE_DECODE_ARCH(feat) ((feat) >> 2)
// The feature flag bits encode the compile-time config options that
// affect the generate bytecode.
#define MPY_FEATURE_FLAGS ( \
((MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE) << 0) \
| ((MICROPY_PY_BUILTINS_STR_UNICODE) << 1) \
)
// This is a version of the flags that can be configured at runtime.
#define MPY_FEATURE_FLAGS_DYNAMIC ( \
((MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE_DYNAMIC) << 0) \
| ((MICROPY_PY_BUILTINS_STR_UNICODE_DYNAMIC) << 1) \
)
// Define the host architecture
#if MICROPY_EMIT_X86
#define MPY_FEATURE_ARCH (MP_NATIVE_ARCH_X86)
#elif MICROPY_EMIT_X64
#define MPY_FEATURE_ARCH (MP_NATIVE_ARCH_X64)
#elif MICROPY_EMIT_THUMB
#if defined(__thumb2__)
#if defined(__ARM_FP) && (__ARM_FP & 8) == 8
#define MPY_FEATURE_ARCH (MP_NATIVE_ARCH_ARMV7EMDP)
#elif defined(__ARM_FP) && (__ARM_FP & 4) == 4
#define MPY_FEATURE_ARCH (MP_NATIVE_ARCH_ARMV7EMSP)
#else
#define MPY_FEATURE_ARCH (MP_NATIVE_ARCH_ARMV7EM)
#endif
#else
#define MPY_FEATURE_ARCH (MP_NATIVE_ARCH_ARMV7M)
#endif
#define MPY_FEATURE_ARCH_TEST(x) (MP_NATIVE_ARCH_ARMV6M <= (x) && (x) <= MPY_FEATURE_ARCH)
#elif MICROPY_EMIT_ARM
#define MPY_FEATURE_ARCH (MP_NATIVE_ARCH_ARMV6)
#elif MICROPY_EMIT_XTENSA
#define MPY_FEATURE_ARCH (MP_NATIVE_ARCH_XTENSA)
#elif MICROPY_EMIT_XTENSAWIN
#define MPY_FEATURE_ARCH (MP_NATIVE_ARCH_XTENSAWIN)
#else
#define MPY_FEATURE_ARCH (MP_NATIVE_ARCH_NONE)
#endif
#ifndef MPY_FEATURE_ARCH_TEST
#define MPY_FEATURE_ARCH_TEST(x) ((x) == MPY_FEATURE_ARCH)
#endif
// 16-bit little-endian integer with the second and third bytes of supported .mpy files
#define MPY_FILE_HEADER_INT (MPY_VERSION \
| (MPY_FEATURE_ENCODE_FLAGS(MPY_FEATURE_FLAGS) | MPY_FEATURE_ENCODE_ARCH(MPY_FEATURE_ARCH)) << 8)
enum {
MP_NATIVE_ARCH_NONE = 0,
MP_NATIVE_ARCH_X86,
MP_NATIVE_ARCH_X64,
MP_NATIVE_ARCH_ARMV6,
MP_NATIVE_ARCH_ARMV6M,
MP_NATIVE_ARCH_ARMV7M,
MP_NATIVE_ARCH_ARMV7EM,
MP_NATIVE_ARCH_ARMV7EMSP,
MP_NATIVE_ARCH_ARMV7EMDP,
MP_NATIVE_ARCH_XTENSA,
MP_NATIVE_ARCH_XTENSAWIN,
};
mp_raw_code_t *mp_raw_code_load(mp_reader_t *reader);
mp_raw_code_t *mp_raw_code_load_mem(const byte *buf, size_t len);
mp_raw_code_t *mp_raw_code_load_file(const char *filename);
void mp_raw_code_save(mp_raw_code_t *rc, mp_print_t *print);
void mp_raw_code_save_file(mp_raw_code_t *rc, const char *filename);
void mp_native_relocate(void *reloc, uint8_t *text, uintptr_t reloc_text);
#endif // MICROPY_INCLUDED_PY_PERSISTENTCODE_H
| YifuLiu/AliOS-Things | components/py_engine/engine/py/persistentcode.h | C | apache-2.0 | 4,380 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) SatoshiLabs
*
* 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 "py/profile.h"
#include "py/bc0.h"
#include "py/gc.h"
#if MICROPY_PY_SYS_SETTRACE
#define prof_trace_cb MP_STATE_THREAD(prof_trace_callback)
STATIC uint mp_prof_bytecode_lineno(const mp_raw_code_t *rc, size_t bc) {
const mp_bytecode_prelude_t *prelude = &rc->prelude;
return mp_bytecode_get_source_line(prelude->line_info, bc);
}
void mp_prof_extract_prelude(const byte *bytecode, mp_bytecode_prelude_t *prelude) {
const byte *ip = bytecode;
MP_BC_PRELUDE_SIG_DECODE(ip);
prelude->n_state = n_state;
prelude->n_exc_stack = n_exc_stack;
prelude->scope_flags = scope_flags;
prelude->n_pos_args = n_pos_args;
prelude->n_kwonly_args = n_kwonly_args;
prelude->n_def_pos_args = n_def_pos_args;
MP_BC_PRELUDE_SIZE_DECODE(ip);
prelude->line_info = ip + 4;
prelude->opcodes = ip + n_info + n_cell;
qstr block_name = ip[0] | (ip[1] << 8);
qstr source_file = ip[2] | (ip[3] << 8);
prelude->qstr_block_name = block_name;
prelude->qstr_source_file = source_file;
}
/******************************************************************************/
// code object
STATIC void code_print(const mp_print_t *print, mp_obj_t o_in, mp_print_kind_t kind) {
(void)kind;
mp_obj_code_t *o = MP_OBJ_TO_PTR(o_in);
const mp_raw_code_t *rc = o->rc;
const mp_bytecode_prelude_t *prelude = &rc->prelude;
mp_printf(print,
"<code object %q at 0x%p, file \"%q\", line %d>",
prelude->qstr_block_name,
o,
prelude->qstr_source_file,
rc->line_of_definition
);
}
STATIC mp_obj_tuple_t *code_consts(const mp_raw_code_t *rc) {
const mp_bytecode_prelude_t *prelude = &rc->prelude;
int start = prelude->n_pos_args + prelude->n_kwonly_args + rc->n_obj;
int stop = prelude->n_pos_args + prelude->n_kwonly_args + rc->n_obj + rc->n_raw_code;
mp_obj_tuple_t *consts = MP_OBJ_TO_PTR(mp_obj_new_tuple(stop - start + 1, NULL));
size_t const_no = 0;
for (int i = start; i < stop; ++i) {
mp_obj_t code = mp_obj_new_code((const mp_raw_code_t *)MP_OBJ_TO_PTR(rc->const_table[i]));
if (code == MP_OBJ_NULL) {
m_malloc_fail(sizeof(mp_obj_code_t));
}
consts->items[const_no++] = code;
}
consts->items[const_no++] = mp_const_none;
return consts;
}
STATIC mp_obj_t raw_code_lnotab(const mp_raw_code_t *rc) {
// const mp_bytecode_prelude_t *prelude = &rc->prelude;
uint start = 0;
uint stop = rc->fun_data_len - start;
uint last_lineno = mp_prof_bytecode_lineno(rc, start);
uint lasti = 0;
const uint buffer_chunk_size = (stop - start) >> 2; // heuristic magic
uint buffer_size = buffer_chunk_size;
byte *buffer = m_new(byte, buffer_size);
uint buffer_index = 0;
for (uint i = start; i < stop; ++i) {
uint lineno = mp_prof_bytecode_lineno(rc, i);
size_t line_diff = lineno - last_lineno;
if (line_diff > 0) {
uint instr_diff = (i - start) - lasti;
assert(instr_diff < 256);
assert(line_diff < 256);
if (buffer_index + 2 > buffer_size) {
buffer = m_renew(byte, buffer, buffer_size, buffer_size + buffer_chunk_size);
buffer_size = buffer_size + buffer_chunk_size;
}
last_lineno = lineno;
lasti = i - start;
buffer[buffer_index++] = instr_diff;
buffer[buffer_index++] = line_diff;
}
}
mp_obj_t o = mp_obj_new_bytes(buffer, buffer_index);
m_del(byte, buffer, buffer_size);
return o;
}
STATIC void code_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) {
if (dest[0] != MP_OBJ_NULL) {
// not load attribute
return;
}
mp_obj_code_t *o = MP_OBJ_TO_PTR(self_in);
const mp_raw_code_t *rc = o->rc;
const mp_bytecode_prelude_t *prelude = &rc->prelude;
switch (attr) {
case MP_QSTR_co_code:
dest[0] = mp_obj_new_bytes(
(void *)prelude->opcodes,
rc->fun_data_len - (prelude->opcodes - (const byte *)rc->fun_data)
);
break;
case MP_QSTR_co_consts:
dest[0] = MP_OBJ_FROM_PTR(code_consts(rc));
break;
case MP_QSTR_co_filename:
dest[0] = MP_OBJ_NEW_QSTR(prelude->qstr_source_file);
break;
case MP_QSTR_co_firstlineno:
dest[0] = MP_OBJ_NEW_SMALL_INT(mp_prof_bytecode_lineno(rc, 0));
break;
case MP_QSTR_co_name:
dest[0] = MP_OBJ_NEW_QSTR(prelude->qstr_block_name);
break;
case MP_QSTR_co_names:
dest[0] = MP_OBJ_FROM_PTR(o->dict_locals);
break;
case MP_QSTR_co_lnotab:
if (!o->lnotab) {
o->lnotab = raw_code_lnotab(rc);
}
dest[0] = o->lnotab;
break;
}
}
const mp_obj_type_t mp_type_settrace_codeobj = {
{ &mp_type_type },
.name = MP_QSTR_code,
.print = code_print,
.unary_op = mp_generic_unary_op,
.attr = code_attr,
};
mp_obj_t mp_obj_new_code(const mp_raw_code_t *rc) {
mp_obj_code_t *o = m_new_obj_maybe(mp_obj_code_t);
if (o == NULL) {
return MP_OBJ_NULL;
}
o->base.type = &mp_type_settrace_codeobj;
o->rc = rc;
o->dict_locals = mp_locals_get(); // this is a wrong! how to do this properly?
o->lnotab = MP_OBJ_NULL;
return MP_OBJ_FROM_PTR(o);
}
/******************************************************************************/
// frame object
STATIC void frame_print(const mp_print_t *print, mp_obj_t o_in, mp_print_kind_t kind) {
(void)kind;
mp_obj_frame_t *frame = MP_OBJ_TO_PTR(o_in);
mp_obj_code_t *code = frame->code;
const mp_raw_code_t *rc = code->rc;
const mp_bytecode_prelude_t *prelude = &rc->prelude;
mp_printf(print,
"<frame at 0x%p, file '%q', line %d, code %q>",
frame,
prelude->qstr_source_file,
frame->lineno,
prelude->qstr_block_name
);
}
STATIC void frame_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) {
if (dest[0] != MP_OBJ_NULL) {
// not load attribute
return;
}
mp_obj_frame_t *o = MP_OBJ_TO_PTR(self_in);
switch (attr) {
case MP_QSTR_f_back:
dest[0] = mp_const_none;
if (o->code_state->prev_state) {
dest[0] = MP_OBJ_FROM_PTR(o->code_state->prev_state->frame);
}
break;
case MP_QSTR_f_code:
dest[0] = MP_OBJ_FROM_PTR(o->code);
break;
case MP_QSTR_f_globals:
dest[0] = MP_OBJ_FROM_PTR(o->code_state->fun_bc->globals);
break;
case MP_QSTR_f_lasti:
dest[0] = MP_OBJ_NEW_SMALL_INT(o->lasti);
break;
case MP_QSTR_f_lineno:
dest[0] = MP_OBJ_NEW_SMALL_INT(o->lineno);
break;
}
}
const mp_obj_type_t mp_type_frame = {
{ &mp_type_type },
.name = MP_QSTR_frame,
.print = frame_print,
.unary_op = mp_generic_unary_op,
.attr = frame_attr,
};
mp_obj_t mp_obj_new_frame(const mp_code_state_t *code_state) {
if (gc_is_locked()) {
return MP_OBJ_NULL;
}
mp_obj_frame_t *o = m_new_obj_maybe(mp_obj_frame_t);
if (o == NULL) {
return MP_OBJ_NULL;
}
mp_obj_code_t *code = o->code = MP_OBJ_TO_PTR(mp_obj_new_code(code_state->fun_bc->rc));
if (code == NULL) {
return MP_OBJ_NULL;
}
const mp_raw_code_t *rc = code->rc;
const mp_bytecode_prelude_t *prelude = &rc->prelude;
o->code_state = code_state;
o->base.type = &mp_type_frame;
o->back = NULL;
o->code = code;
o->lasti = code_state->ip - prelude->opcodes;
o->lineno = mp_prof_bytecode_lineno(rc, o->lasti);
o->trace_opcodes = false;
o->callback = MP_OBJ_NULL;
return MP_OBJ_FROM_PTR(o);
}
/******************************************************************************/
// Trace logic
typedef struct {
struct _mp_obj_frame_t *frame;
mp_obj_t event;
mp_obj_t arg;
} prof_callback_args_t;
STATIC mp_obj_t mp_prof_callback_invoke(mp_obj_t callback, prof_callback_args_t *args) {
assert(mp_obj_is_callable(callback));
mp_prof_is_executing = true;
mp_obj_t a[3] = {MP_OBJ_FROM_PTR(args->frame), args->event, args->arg};
mp_obj_t top = mp_call_function_n_kw(callback, 3, 0, a);
mp_prof_is_executing = false;
if (MP_STATE_THREAD(mp_pending_exception) != MP_OBJ_NULL) {
mp_handle_pending(true);
}
return top;
}
mp_obj_t mp_prof_settrace(mp_obj_t callback) {
if (mp_obj_is_callable(callback)) {
prof_trace_cb = callback;
} else {
prof_trace_cb = MP_OBJ_NULL;
}
return mp_const_none;
}
mp_obj_t mp_prof_frame_enter(mp_code_state_t *code_state) {
assert(!mp_prof_is_executing);
mp_obj_frame_t *frame = MP_OBJ_TO_PTR(mp_obj_new_frame(code_state));
if (frame == NULL) {
// Couldn't allocate a frame object
return MP_OBJ_NULL;
}
if (code_state->prev_state && code_state->frame == NULL) {
// We are entering not-yet-traced frame
// which means it's a CALL event (not a GENERATOR)
// so set the function definition line.
const mp_raw_code_t *rc = code_state->fun_bc->rc;
frame->lineno = rc->line_of_definition;
if (!rc->line_of_definition) {
frame->lineno = mp_prof_bytecode_lineno(rc, 0);
}
}
code_state->frame = frame;
if (!prof_trace_cb) {
return MP_OBJ_NULL;
}
mp_obj_t top;
prof_callback_args_t _args, *args = &_args;
args->frame = code_state->frame;
// SETTRACE event CALL
args->event = MP_OBJ_NEW_QSTR(MP_QSTR_call);
args->arg = mp_const_none;
top = mp_prof_callback_invoke(prof_trace_cb, args);
code_state->frame->callback = mp_obj_is_callable(top) ? top : MP_OBJ_NULL;
// Invalidate the last executed line number so the LINE trace can trigger after this CALL.
frame->lineno = 0;
return top;
}
mp_obj_t mp_prof_frame_update(const mp_code_state_t *code_state) {
mp_obj_frame_t *frame = code_state->frame;
if (frame == NULL) {
// Frame was not allocated (eg because there was no memory available)
return MP_OBJ_NULL;
}
mp_obj_frame_t *o = frame;
mp_obj_code_t *code = o->code;
const mp_raw_code_t *rc = code->rc;
const mp_bytecode_prelude_t *prelude = &rc->prelude;
assert(o->code_state == code_state);
o->lasti = code_state->ip - prelude->opcodes;
o->lineno = mp_prof_bytecode_lineno(rc, o->lasti);
return MP_OBJ_FROM_PTR(o);
}
mp_obj_t mp_prof_instr_tick(mp_code_state_t *code_state, bool is_exception) {
// Detect execution recursion
assert(!mp_prof_is_executing);
assert(code_state->frame);
assert(mp_obj_get_type(code_state->frame) == &mp_type_frame);
// Detect data recursion
assert(code_state != code_state->prev_state);
mp_obj_t top = mp_const_none;
mp_obj_t callback = code_state->frame->callback;
prof_callback_args_t _args, *args = &_args;
args->frame = code_state->frame;
args->event = mp_const_none;
args->arg = mp_const_none;
// Call event's are handled inside mp_prof_frame_enter
// SETTRACE event EXCEPTION
if (is_exception) {
args->event = MP_OBJ_NEW_QSTR(MP_QSTR_exception);
top = mp_prof_callback_invoke(callback, args);
return top;
}
// SETTRACE event LINE
const mp_raw_code_t *rc = code_state->fun_bc->rc;
const mp_bytecode_prelude_t *prelude = &rc->prelude;
size_t prev_line_no = args->frame->lineno;
size_t current_line_no = mp_prof_bytecode_lineno(rc, code_state->ip - prelude->opcodes);
if (prev_line_no != current_line_no) {
args->frame->lineno = current_line_no;
args->event = MP_OBJ_NEW_QSTR(MP_QSTR_line);
top = mp_prof_callback_invoke(callback, args);
}
// SETTRACE event RETURN
const byte *ip = code_state->ip;
if (*ip == MP_BC_RETURN_VALUE || *ip == MP_BC_YIELD_VALUE) {
args->event = MP_OBJ_NEW_QSTR(MP_QSTR_return);
top = mp_prof_callback_invoke(callback, args);
if (code_state->prev_state && *ip == MP_BC_RETURN_VALUE) {
code_state->frame->callback = MP_OBJ_NULL;
}
}
// SETTRACE event OPCODE
// TODO: frame.f_trace_opcodes=True
if (false) {
args->event = MP_OBJ_NEW_QSTR(MP_QSTR_opcode);
}
return top;
}
/******************************************************************************/
// DEBUG
// This section is for debugging the settrace feature itself, and is not intended
// to be included in production/release builds. The code structure for this block
// was taken from py/showbc.c and should not be used as a reference. To enable
// this debug feature enable MICROPY_PROF_INSTR_DEBUG_PRINT_ENABLE in py/profile.h.
#if MICROPY_PROF_INSTR_DEBUG_PRINT_ENABLE
#include "runtime0.h"
#define DECODE_UINT { \
unum = 0; \
do { \
unum = (unum << 7) + (*ip & 0x7f); \
} while ((*ip++ & 0x80) != 0); \
}
#define DECODE_ULABEL do { unum = (ip[0] | (ip[1] << 8)); ip += 2; } while (0)
#define DECODE_SLABEL do { unum = (ip[0] | (ip[1] << 8)) - 0x8000; ip += 2; } while (0)
#define DECODE_QSTR \
qst = ip[0] | ip[1] << 8; \
ip += 2;
#define DECODE_PTR \
DECODE_UINT; \
ptr = (const byte *)const_table[unum]
#define DECODE_OBJ \
DECODE_UINT; \
obj = (mp_obj_t)const_table[unum]
typedef struct _mp_dis_instruction_t {
mp_uint_t qstr_opname;
mp_uint_t arg;
mp_obj_t argobj;
mp_obj_t argobjex_cache;
} mp_dis_instruction_t;
STATIC const byte *mp_prof_opcode_decode(const byte *ip, const mp_uint_t *const_table, mp_dis_instruction_t *instruction) {
mp_uint_t unum;
const byte *ptr;
mp_obj_t obj;
qstr qst;
instruction->qstr_opname = MP_QSTR_;
instruction->arg = 0;
instruction->argobj = mp_const_none;
instruction->argobjex_cache = mp_const_none;
switch (*ip++) {
case MP_BC_LOAD_CONST_FALSE:
instruction->qstr_opname = MP_QSTR_LOAD_CONST_FALSE;
break;
case MP_BC_LOAD_CONST_NONE:
instruction->qstr_opname = MP_QSTR_LOAD_CONST_NONE;
break;
case MP_BC_LOAD_CONST_TRUE:
instruction->qstr_opname = MP_QSTR_LOAD_CONST_TRUE;
break;
case MP_BC_LOAD_CONST_SMALL_INT: {
mp_int_t num = 0;
if ((ip[0] & 0x40) != 0) {
// Number is negative
num--;
}
do {
num = (num << 7) | (*ip & 0x7f);
} while ((*ip++ & 0x80) != 0);
instruction->qstr_opname = MP_QSTR_LOAD_CONST_SMALL_INT;
instruction->arg = num;
break;
}
case MP_BC_LOAD_CONST_STRING:
DECODE_QSTR;
instruction->qstr_opname = MP_QSTR_LOAD_CONST_STRING;
instruction->arg = qst;
instruction->argobj = MP_OBJ_NEW_QSTR(qst);
break;
case MP_BC_LOAD_CONST_OBJ:
DECODE_OBJ;
instruction->qstr_opname = MP_QSTR_LOAD_CONST_OBJ;
instruction->arg = unum;
instruction->argobj = obj;
break;
case MP_BC_LOAD_NULL:
instruction->qstr_opname = MP_QSTR_LOAD_NULL;
break;
case MP_BC_LOAD_FAST_N:
DECODE_UINT;
instruction->qstr_opname = MP_QSTR_LOAD_FAST_N;
instruction->arg = unum;
break;
case MP_BC_LOAD_DEREF:
DECODE_UINT;
instruction->qstr_opname = MP_QSTR_LOAD_DEREF;
instruction->arg = unum;
break;
case MP_BC_LOAD_NAME:
DECODE_QSTR;
instruction->qstr_opname = MP_QSTR_LOAD_NAME;
instruction->arg = qst;
instruction->argobj = MP_OBJ_NEW_QSTR(qst);
if (MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE) {
instruction->argobjex_cache = MP_OBJ_NEW_SMALL_INT(*ip++);
}
break;
case MP_BC_LOAD_GLOBAL:
DECODE_QSTR;
instruction->qstr_opname = MP_QSTR_LOAD_GLOBAL;
instruction->arg = qst;
instruction->argobj = MP_OBJ_NEW_QSTR(qst);
if (MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE) {
instruction->argobjex_cache = MP_OBJ_NEW_SMALL_INT(*ip++);
}
break;
case MP_BC_LOAD_ATTR:
DECODE_QSTR;
instruction->qstr_opname = MP_QSTR_LOAD_ATTR;
instruction->arg = qst;
instruction->argobj = MP_OBJ_NEW_QSTR(qst);
if (MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE) {
instruction->argobjex_cache = MP_OBJ_NEW_SMALL_INT(*ip++);
}
break;
case MP_BC_LOAD_METHOD:
DECODE_QSTR;
instruction->qstr_opname = MP_QSTR_LOAD_METHOD;
instruction->arg = qst;
instruction->argobj = MP_OBJ_NEW_QSTR(qst);
break;
case MP_BC_LOAD_SUPER_METHOD:
DECODE_QSTR;
instruction->qstr_opname = MP_QSTR_LOAD_SUPER_METHOD;
instruction->arg = qst;
instruction->argobj = MP_OBJ_NEW_QSTR(qst);
break;
case MP_BC_LOAD_BUILD_CLASS:
instruction->qstr_opname = MP_QSTR_LOAD_BUILD_CLASS;
break;
case MP_BC_LOAD_SUBSCR:
instruction->qstr_opname = MP_QSTR_LOAD_SUBSCR;
break;
case MP_BC_STORE_FAST_N:
DECODE_UINT;
instruction->qstr_opname = MP_QSTR_STORE_FAST_N;
instruction->arg = unum;
break;
case MP_BC_STORE_DEREF:
DECODE_UINT;
instruction->qstr_opname = MP_QSTR_STORE_DEREF;
instruction->arg = unum;
break;
case MP_BC_STORE_NAME:
DECODE_QSTR;
instruction->qstr_opname = MP_QSTR_STORE_NAME;
instruction->arg = qst;
instruction->argobj = MP_OBJ_NEW_QSTR(qst);
break;
case MP_BC_STORE_GLOBAL:
DECODE_QSTR;
instruction->qstr_opname = MP_QSTR_STORE_GLOBAL;
instruction->arg = qst;
instruction->argobj = MP_OBJ_NEW_QSTR(qst);
break;
case MP_BC_STORE_ATTR:
DECODE_QSTR;
instruction->qstr_opname = MP_QSTR_STORE_ATTR;
instruction->arg = qst;
instruction->argobj = MP_OBJ_NEW_QSTR(qst);
if (MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE) {
instruction->argobjex_cache = MP_OBJ_NEW_SMALL_INT(*ip++);
}
break;
case MP_BC_STORE_SUBSCR:
instruction->qstr_opname = MP_QSTR_STORE_SUBSCR;
break;
case MP_BC_DELETE_FAST:
DECODE_UINT;
instruction->qstr_opname = MP_QSTR_DELETE_FAST;
instruction->arg = unum;
break;
case MP_BC_DELETE_DEREF:
DECODE_UINT;
instruction->qstr_opname = MP_QSTR_DELETE_DEREF;
instruction->arg = unum;
break;
case MP_BC_DELETE_NAME:
DECODE_QSTR;
instruction->qstr_opname = MP_QSTR_DELETE_NAME;
instruction->arg = qst;
instruction->argobj = MP_OBJ_NEW_QSTR(qst);
break;
case MP_BC_DELETE_GLOBAL:
DECODE_QSTR;
instruction->qstr_opname = MP_QSTR_DELETE_GLOBAL;
instruction->arg = qst;
instruction->argobj = MP_OBJ_NEW_QSTR(qst);
break;
case MP_BC_DUP_TOP:
instruction->qstr_opname = MP_QSTR_DUP_TOP;
break;
case MP_BC_DUP_TOP_TWO:
instruction->qstr_opname = MP_QSTR_DUP_TOP_TWO;
break;
case MP_BC_POP_TOP:
instruction->qstr_opname = MP_QSTR_POP_TOP;
break;
case MP_BC_ROT_TWO:
instruction->qstr_opname = MP_QSTR_ROT_TWO;
break;
case MP_BC_ROT_THREE:
instruction->qstr_opname = MP_QSTR_ROT_THREE;
break;
case MP_BC_JUMP:
DECODE_SLABEL;
instruction->qstr_opname = MP_QSTR_JUMP;
instruction->arg = unum;
break;
case MP_BC_POP_JUMP_IF_TRUE:
DECODE_SLABEL;
instruction->qstr_opname = MP_QSTR_POP_JUMP_IF_TRUE;
instruction->arg = unum;
break;
case MP_BC_POP_JUMP_IF_FALSE:
DECODE_SLABEL;
instruction->qstr_opname = MP_QSTR_POP_JUMP_IF_FALSE;
instruction->arg = unum;
break;
case MP_BC_JUMP_IF_TRUE_OR_POP:
DECODE_SLABEL;
instruction->qstr_opname = MP_QSTR_JUMP_IF_TRUE_OR_POP;
instruction->arg = unum;
break;
case MP_BC_JUMP_IF_FALSE_OR_POP:
DECODE_SLABEL;
instruction->qstr_opname = MP_QSTR_JUMP_IF_FALSE_OR_POP;
instruction->arg = unum;
break;
case MP_BC_SETUP_WITH:
DECODE_ULABEL; // loop-like labels are always forward
instruction->qstr_opname = MP_QSTR_SETUP_WITH;
instruction->arg = unum;
break;
case MP_BC_WITH_CLEANUP:
instruction->qstr_opname = MP_QSTR_WITH_CLEANUP;
break;
case MP_BC_UNWIND_JUMP:
DECODE_SLABEL;
instruction->qstr_opname = MP_QSTR_UNWIND_JUMP;
instruction->arg = unum;
break;
case MP_BC_SETUP_EXCEPT:
DECODE_ULABEL; // except labels are always forward
instruction->qstr_opname = MP_QSTR_SETUP_EXCEPT;
instruction->arg = unum;
break;
case MP_BC_SETUP_FINALLY:
DECODE_ULABEL; // except labels are always forward
instruction->qstr_opname = MP_QSTR_SETUP_FINALLY;
instruction->arg = unum;
break;
case MP_BC_END_FINALLY:
// if TOS is an exception, reraises the exception (3 values on TOS)
// if TOS is an integer, does something else
// if TOS is None, just pops it and continues
// else error
instruction->qstr_opname = MP_QSTR_END_FINALLY;
break;
case MP_BC_GET_ITER:
instruction->qstr_opname = MP_QSTR_GET_ITER;
break;
case MP_BC_GET_ITER_STACK:
instruction->qstr_opname = MP_QSTR_GET_ITER_STACK;
break;
case MP_BC_FOR_ITER:
DECODE_ULABEL; // the jump offset if iteration finishes; for labels are always forward
instruction->qstr_opname = MP_QSTR_FOR_ITER;
instruction->arg = unum;
break;
case MP_BC_BUILD_TUPLE:
DECODE_UINT;
instruction->qstr_opname = MP_QSTR_BUILD_TUPLE;
instruction->arg = unum;
break;
case MP_BC_BUILD_LIST:
DECODE_UINT;
instruction->qstr_opname = MP_QSTR_BUILD_LIST;
instruction->arg = unum;
break;
case MP_BC_BUILD_MAP:
DECODE_UINT;
instruction->qstr_opname = MP_QSTR_BUILD_MAP;
instruction->arg = unum;
break;
case MP_BC_STORE_MAP:
instruction->qstr_opname = MP_QSTR_STORE_MAP;
break;
case MP_BC_BUILD_SET:
DECODE_UINT;
instruction->qstr_opname = MP_QSTR_BUILD_SET;
instruction->arg = unum;
break;
#if MICROPY_PY_BUILTINS_SLICE
case MP_BC_BUILD_SLICE:
DECODE_UINT;
instruction->qstr_opname = MP_QSTR_BUILD_SLICE;
instruction->arg = unum;
break;
#endif
case MP_BC_STORE_COMP:
DECODE_UINT;
instruction->qstr_opname = MP_QSTR_STORE_COMP;
instruction->arg = unum;
break;
case MP_BC_UNPACK_SEQUENCE:
DECODE_UINT;
instruction->qstr_opname = MP_QSTR_UNPACK_SEQUENCE;
instruction->arg = unum;
break;
case MP_BC_UNPACK_EX:
DECODE_UINT;
instruction->qstr_opname = MP_QSTR_UNPACK_EX;
instruction->arg = unum;
break;
case MP_BC_MAKE_FUNCTION:
DECODE_PTR;
instruction->qstr_opname = MP_QSTR_MAKE_FUNCTION;
instruction->arg = unum;
instruction->argobj = mp_obj_new_int_from_ull((uint64_t)ptr);
break;
case MP_BC_MAKE_FUNCTION_DEFARGS:
DECODE_PTR;
instruction->qstr_opname = MP_QSTR_MAKE_FUNCTION_DEFARGS;
instruction->arg = unum;
instruction->argobj = mp_obj_new_int_from_ull((uint64_t)ptr);
break;
case MP_BC_MAKE_CLOSURE: {
DECODE_PTR;
mp_uint_t n_closed_over = *ip++;
instruction->qstr_opname = MP_QSTR_MAKE_CLOSURE;
instruction->arg = unum;
instruction->argobj = mp_obj_new_int_from_ull((uint64_t)ptr);
instruction->argobjex_cache = MP_OBJ_NEW_SMALL_INT(n_closed_over);
break;
}
case MP_BC_MAKE_CLOSURE_DEFARGS: {
DECODE_PTR;
mp_uint_t n_closed_over = *ip++;
instruction->qstr_opname = MP_QSTR_MAKE_CLOSURE_DEFARGS;
instruction->arg = unum;
instruction->argobj = mp_obj_new_int_from_ull((uint64_t)ptr);
instruction->argobjex_cache = MP_OBJ_NEW_SMALL_INT(n_closed_over);
break;
}
case MP_BC_CALL_FUNCTION:
DECODE_UINT;
instruction->qstr_opname = MP_QSTR_CALL_FUNCTION;
instruction->arg = unum & 0xff;
instruction->argobjex_cache = MP_OBJ_NEW_SMALL_INT((unum >> 8) & 0xff);
break;
case MP_BC_CALL_FUNCTION_VAR_KW:
DECODE_UINT;
instruction->qstr_opname = MP_QSTR_CALL_FUNCTION_VAR_KW;
instruction->arg = unum & 0xff;
instruction->argobjex_cache = MP_OBJ_NEW_SMALL_INT((unum >> 8) & 0xff);
break;
case MP_BC_CALL_METHOD:
DECODE_UINT;
instruction->qstr_opname = MP_QSTR_CALL_METHOD;
instruction->arg = unum & 0xff;
instruction->argobjex_cache = MP_OBJ_NEW_SMALL_INT((unum >> 8) & 0xff);
break;
case MP_BC_CALL_METHOD_VAR_KW:
DECODE_UINT;
instruction->qstr_opname = MP_QSTR_CALL_METHOD_VAR_KW;
instruction->arg = unum & 0xff;
instruction->argobjex_cache = MP_OBJ_NEW_SMALL_INT((unum >> 8) & 0xff);
break;
case MP_BC_RETURN_VALUE:
instruction->qstr_opname = MP_QSTR_RETURN_VALUE;
break;
case MP_BC_RAISE_LAST:
instruction->qstr_opname = MP_QSTR_RAISE_LAST;
break;
case MP_BC_RAISE_OBJ:
instruction->qstr_opname = MP_QSTR_RAISE_OBJ;
break;
case MP_BC_RAISE_FROM:
instruction->qstr_opname = MP_QSTR_RAISE_FROM;
break;
case MP_BC_YIELD_VALUE:
instruction->qstr_opname = MP_QSTR_YIELD_VALUE;
break;
case MP_BC_YIELD_FROM:
instruction->qstr_opname = MP_QSTR_YIELD_FROM;
break;
case MP_BC_IMPORT_NAME:
DECODE_QSTR;
instruction->qstr_opname = MP_QSTR_IMPORT_NAME;
instruction->arg = qst;
instruction->argobj = MP_OBJ_NEW_QSTR(qst);
break;
case MP_BC_IMPORT_FROM:
DECODE_QSTR;
instruction->qstr_opname = MP_QSTR_IMPORT_FROM;
instruction->arg = qst;
instruction->argobj = MP_OBJ_NEW_QSTR(qst);
break;
case MP_BC_IMPORT_STAR:
instruction->qstr_opname = MP_QSTR_IMPORT_STAR;
break;
default:
if (ip[-1] < MP_BC_LOAD_CONST_SMALL_INT_MULTI + 64) {
instruction->qstr_opname = MP_QSTR_LOAD_CONST_SMALL_INT;
instruction->arg = (mp_int_t)ip[-1] - MP_BC_LOAD_CONST_SMALL_INT_MULTI - 16;
} else if (ip[-1] < MP_BC_LOAD_FAST_MULTI + 16) {
instruction->qstr_opname = MP_QSTR_LOAD_FAST;
instruction->arg = (mp_uint_t)ip[-1] - MP_BC_LOAD_FAST_MULTI;
} else if (ip[-1] < MP_BC_STORE_FAST_MULTI + 16) {
instruction->qstr_opname = MP_QSTR_STORE_FAST;
instruction->arg = (mp_uint_t)ip[-1] - MP_BC_STORE_FAST_MULTI;
} else if (ip[-1] < MP_BC_UNARY_OP_MULTI + MP_UNARY_OP_NUM_BYTECODE) {
instruction->qstr_opname = MP_QSTR_UNARY_OP;
instruction->arg = (mp_uint_t)ip[-1] - MP_BC_UNARY_OP_MULTI;
} else if (ip[-1] < MP_BC_BINARY_OP_MULTI + MP_BINARY_OP_NUM_BYTECODE) {
mp_uint_t op = ip[-1] - MP_BC_BINARY_OP_MULTI;
instruction->qstr_opname = MP_QSTR_BINARY_OP;
instruction->arg = op;
} else {
mp_printf(&mp_plat_print, "code %p, opcode 0x%02x not implemented\n", ip - 1, ip[-1]);
assert(0);
return ip;
}
break;
}
return ip;
}
void mp_prof_print_instr(const byte *ip, mp_code_state_t *code_state) {
mp_dis_instruction_t _instruction, *instruction = &_instruction;
mp_prof_opcode_decode(ip, code_state->fun_bc->rc->const_table, instruction);
const mp_raw_code_t *rc = code_state->fun_bc->rc;
const mp_bytecode_prelude_t *prelude = &rc->prelude;
mp_uint_t offset = ip - prelude->opcodes;
mp_printf(&mp_plat_print, "instr");
/* long path */ if (1) {
mp_printf(&mp_plat_print,
"@0x%p:%q:%q+0x%04x:%d",
ip,
prelude->qstr_source_file,
prelude->qstr_block_name,
offset,
mp_prof_bytecode_lineno(rc, offset)
);
}
/* bytecode */ if (0) {
mp_printf(&mp_plat_print, " %02x %02x %02x %02x", ip[0], ip[1], ip[2], ip[3]);
}
mp_printf(&mp_plat_print, " 0x%02x %q [%d]", *ip, instruction->qstr_opname, instruction->arg);
if (instruction->argobj != mp_const_none) {
mp_printf(&mp_plat_print, " $");
mp_obj_print_helper(&mp_plat_print, instruction->argobj, PRINT_REPR);
}
if (instruction->argobjex_cache != mp_const_none) {
mp_printf(&mp_plat_print, " #");
mp_obj_print_helper(&mp_plat_print, instruction->argobjex_cache, PRINT_REPR);
}
mp_printf(&mp_plat_print, "\n");
}
#endif // MICROPY_PROF_INSTR_DEBUG_PRINT_ENABLE
#endif // MICROPY_PY_SYS_SETTRACE
| YifuLiu/AliOS-Things | components/py_engine/engine/py/profile.c | C | apache-2.0 | 32,090 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) SatoshiLabs
*
* 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.
*/
#ifndef MICROPY_INCLUDED_PY_PROFILING_H
#define MICROPY_INCLUDED_PY_PROFILING_H
#include "py/emitglue.h"
#if MICROPY_PY_SYS_SETTRACE
#define mp_prof_is_executing MP_STATE_THREAD(prof_callback_is_executing)
typedef struct _mp_obj_code_t {
mp_obj_base_t base;
const mp_raw_code_t *rc;
mp_obj_dict_t *dict_locals;
mp_obj_t lnotab;
} mp_obj_code_t;
typedef struct _mp_obj_frame_t {
mp_obj_base_t base;
const mp_code_state_t *code_state;
struct _mp_obj_frame_t *back;
mp_obj_t callback;
mp_obj_code_t *code;
mp_uint_t lasti;
mp_uint_t lineno;
bool trace_opcodes;
} mp_obj_frame_t;
void mp_prof_extract_prelude(const byte *bytecode, mp_bytecode_prelude_t *prelude);
mp_obj_t mp_obj_new_code(const mp_raw_code_t *rc);
mp_obj_t mp_obj_new_frame(const mp_code_state_t *code_state);
// This is the implementation for the sys.settrace
mp_obj_t mp_prof_settrace(mp_obj_t callback);
mp_obj_t mp_prof_frame_enter(mp_code_state_t *code_state);
mp_obj_t mp_prof_frame_update(const mp_code_state_t *code_state);
// For every VM instruction tick this function deduces events from the state
mp_obj_t mp_prof_instr_tick(mp_code_state_t *code_state, bool is_exception);
// This section is for debugging the settrace feature itself, and is not intended
// to be included in production/release builds.
#define MICROPY_PROF_INSTR_DEBUG_PRINT_ENABLE 0
#if MICROPY_PROF_INSTR_DEBUG_PRINT_ENABLE
void mp_prof_print_instr(const byte *ip, mp_code_state_t *code_state);
#define MP_PROF_INSTR_DEBUG_PRINT(current_ip) mp_prof_print_instr((current_ip), code_state)
#else
#define MP_PROF_INSTR_DEBUG_PRINT(current_ip)
#endif
#endif // MICROPY_PY_SYS_SETTRACE
#endif // MICROPY_INCLUDED_PY_PROFILING_H
| YifuLiu/AliOS-Things | components/py_engine/engine/py/profile.h | C | apache-2.0 | 2,943 |
# CMake fragment for MicroPython core py component
set(MICROPY_PY_DIR "${MICROPY_DIR}/py")
list(APPEND MICROPY_INC_CORE "${MICROPY_DIR}")
# All py/ source files
set(MICROPY_SOURCE_PY
${MICROPY_PY_DIR}/argcheck.c
${MICROPY_PY_DIR}/asmarm.c
${MICROPY_PY_DIR}/asmbase.c
${MICROPY_PY_DIR}/asmthumb.c
${MICROPY_PY_DIR}/asmx64.c
${MICROPY_PY_DIR}/asmx86.c
${MICROPY_PY_DIR}/asmxtensa.c
${MICROPY_PY_DIR}/bc.c
${MICROPY_PY_DIR}/binary.c
${MICROPY_PY_DIR}/builtinevex.c
${MICROPY_PY_DIR}/builtinhelp.c
${MICROPY_PY_DIR}/builtinimport.c
${MICROPY_PY_DIR}/compile.c
${MICROPY_PY_DIR}/emitbc.c
${MICROPY_PY_DIR}/emitcommon.c
${MICROPY_PY_DIR}/emitglue.c
${MICROPY_PY_DIR}/emitinlinethumb.c
${MICROPY_PY_DIR}/emitinlinextensa.c
${MICROPY_PY_DIR}/emitnarm.c
${MICROPY_PY_DIR}/emitnthumb.c
${MICROPY_PY_DIR}/emitnx64.c
${MICROPY_PY_DIR}/emitnx86.c
${MICROPY_PY_DIR}/emitnxtensa.c
${MICROPY_PY_DIR}/emitnxtensawin.c
${MICROPY_PY_DIR}/formatfloat.c
${MICROPY_PY_DIR}/frozenmod.c
${MICROPY_PY_DIR}/gc.c
${MICROPY_PY_DIR}/lexer.c
${MICROPY_PY_DIR}/malloc.c
${MICROPY_PY_DIR}/map.c
${MICROPY_PY_DIR}/modarray.c
${MICROPY_PY_DIR}/modbuiltins.c
${MICROPY_PY_DIR}/modcmath.c
${MICROPY_PY_DIR}/modcollections.c
${MICROPY_PY_DIR}/modgc.c
${MICROPY_PY_DIR}/modio.c
${MICROPY_PY_DIR}/modmath.c
${MICROPY_PY_DIR}/modmicropython.c
${MICROPY_PY_DIR}/modstruct.c
${MICROPY_PY_DIR}/modsys.c
${MICROPY_PY_DIR}/modthread.c
${MICROPY_PY_DIR}/moduerrno.c
${MICROPY_PY_DIR}/mpprint.c
${MICROPY_PY_DIR}/mpstate.c
${MICROPY_PY_DIR}/mpz.c
${MICROPY_PY_DIR}/nativeglue.c
${MICROPY_PY_DIR}/nlr.c
${MICROPY_PY_DIR}/nlrpowerpc.c
${MICROPY_PY_DIR}/nlrsetjmp.c
${MICROPY_PY_DIR}/nlrthumb.c
${MICROPY_PY_DIR}/nlrx64.c
${MICROPY_PY_DIR}/nlrx86.c
${MICROPY_PY_DIR}/nlrxtensa.c
${MICROPY_PY_DIR}/obj.c
${MICROPY_PY_DIR}/objarray.c
${MICROPY_PY_DIR}/objattrtuple.c
${MICROPY_PY_DIR}/objbool.c
${MICROPY_PY_DIR}/objboundmeth.c
${MICROPY_PY_DIR}/objcell.c
${MICROPY_PY_DIR}/objclosure.c
${MICROPY_PY_DIR}/objcomplex.c
${MICROPY_PY_DIR}/objdeque.c
${MICROPY_PY_DIR}/objdict.c
${MICROPY_PY_DIR}/objenumerate.c
${MICROPY_PY_DIR}/objexcept.c
${MICROPY_PY_DIR}/objfilter.c
${MICROPY_PY_DIR}/objfloat.c
${MICROPY_PY_DIR}/objfun.c
${MICROPY_PY_DIR}/objgenerator.c
${MICROPY_PY_DIR}/objgetitemiter.c
${MICROPY_PY_DIR}/objint.c
${MICROPY_PY_DIR}/objint_longlong.c
${MICROPY_PY_DIR}/objint_mpz.c
${MICROPY_PY_DIR}/objlist.c
${MICROPY_PY_DIR}/objmap.c
${MICROPY_PY_DIR}/objmodule.c
${MICROPY_PY_DIR}/objnamedtuple.c
${MICROPY_PY_DIR}/objnone.c
${MICROPY_PY_DIR}/objobject.c
${MICROPY_PY_DIR}/objpolyiter.c
${MICROPY_PY_DIR}/objproperty.c
${MICROPY_PY_DIR}/objrange.c
${MICROPY_PY_DIR}/objreversed.c
${MICROPY_PY_DIR}/objset.c
${MICROPY_PY_DIR}/objsingleton.c
${MICROPY_PY_DIR}/objslice.c
${MICROPY_PY_DIR}/objstr.c
${MICROPY_PY_DIR}/objstringio.c
${MICROPY_PY_DIR}/objstrunicode.c
${MICROPY_PY_DIR}/objtuple.c
${MICROPY_PY_DIR}/objtype.c
${MICROPY_PY_DIR}/objzip.c
${MICROPY_PY_DIR}/opmethods.c
${MICROPY_PY_DIR}/pairheap.c
${MICROPY_PY_DIR}/parse.c
${MICROPY_PY_DIR}/parsenum.c
${MICROPY_PY_DIR}/parsenumbase.c
${MICROPY_PY_DIR}/persistentcode.c
${MICROPY_PY_DIR}/profile.c
${MICROPY_PY_DIR}/pystack.c
${MICROPY_PY_DIR}/qstr.c
${MICROPY_PY_DIR}/reader.c
${MICROPY_PY_DIR}/repl.c
${MICROPY_PY_DIR}/ringbuf.c
${MICROPY_PY_DIR}/runtime.c
${MICROPY_PY_DIR}/runtime_utils.c
${MICROPY_PY_DIR}/scheduler.c
${MICROPY_PY_DIR}/scope.c
${MICROPY_PY_DIR}/sequence.c
${MICROPY_PY_DIR}/showbc.c
${MICROPY_PY_DIR}/smallint.c
${MICROPY_PY_DIR}/stackctrl.c
${MICROPY_PY_DIR}/stream.c
${MICROPY_PY_DIR}/unicode.c
${MICROPY_PY_DIR}/vm.c
${MICROPY_PY_DIR}/vstr.c
${MICROPY_PY_DIR}/warning.c
)
# Helper macro to collect include directories and compile definitions for qstr processing.
macro(micropy_gather_target_properties targ)
if(TARGET ${targ})
get_target_property(type ${targ} TYPE)
set(_inc OFF)
set(_def OFF)
if(${type} STREQUAL STATIC_LIBRARY)
get_target_property(_inc ${targ} INCLUDE_DIRECTORIES)
get_target_property(_def ${targ} COMPILE_DEFINITIONS)
elseif(${type} STREQUAL INTERFACE_LIBRARY)
get_target_property(_inc ${targ} INTERFACE_INCLUDE_DIRECTORIES)
get_target_property(_def ${targ} INTERFACE_COMPILE_DEFINITIONS)
endif()
if(_inc)
list(APPEND MICROPY_CPP_INC_EXTRA ${_inc})
endif()
if(_def)
list(APPEND MICROPY_CPP_DEF_EXTRA ${_def})
endif()
endif()
endmacro()
| YifuLiu/AliOS-Things | components/py_engine/engine/py/py.cmake | CMake | apache-2.0 | 4,927 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2017 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 <stdio.h>
#include "py/runtime.h"
#if MICROPY_ENABLE_PYSTACK
void mp_pystack_init(void *start, void *end) {
MP_STATE_THREAD(pystack_start) = start;
MP_STATE_THREAD(pystack_end) = end;
MP_STATE_THREAD(pystack_cur) = start;
}
void *mp_pystack_alloc(size_t n_bytes) {
n_bytes = (n_bytes + (MICROPY_PYSTACK_ALIGN - 1)) & ~(MICROPY_PYSTACK_ALIGN - 1);
#if MP_PYSTACK_DEBUG
n_bytes += MICROPY_PYSTACK_ALIGN;
#endif
if (MP_STATE_THREAD(pystack_cur) + n_bytes > MP_STATE_THREAD(pystack_end)) {
// out of memory in the pystack
mp_raise_type_arg(&mp_type_RuntimeError, MP_OBJ_NEW_QSTR(MP_QSTR_pystack_space_exhausted));
}
void *ptr = MP_STATE_THREAD(pystack_cur);
MP_STATE_THREAD(pystack_cur) += n_bytes;
#if MP_PYSTACK_DEBUG
*(size_t *)(MP_STATE_THREAD(pystack_cur) - MICROPY_PYSTACK_ALIGN) = n_bytes;
#endif
return ptr;
}
#endif
| YifuLiu/AliOS-Things | components/py_engine/engine/py/pystack.c | C | apache-2.0 | 2,137 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2017 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.
*/
#ifndef MICROPY_INCLUDED_PY_PYSTACK_H
#define MICROPY_INCLUDED_PY_PYSTACK_H
#include "py/mpstate.h"
// Enable this debugging option to check that the amount of memory freed is
// consistent with amounts that were previously allocated.
#define MP_PYSTACK_DEBUG (0)
#if MICROPY_ENABLE_PYSTACK
void mp_pystack_init(void *start, void *end);
void *mp_pystack_alloc(size_t n_bytes);
// This function can free multiple continuous blocks at once: just pass the
// pointer to the block that was allocated first and it and all subsequently
// allocated blocks will be freed.
static inline void mp_pystack_free(void *ptr) {
assert((uint8_t *)ptr >= MP_STATE_THREAD(pystack_start));
assert((uint8_t *)ptr <= MP_STATE_THREAD(pystack_cur));
#if MP_PYSTACK_DEBUG
size_t n_bytes_to_free = MP_STATE_THREAD(pystack_cur) - (uint8_t *)ptr;
size_t n_bytes = *(size_t *)(MP_STATE_THREAD(pystack_cur) - MICROPY_PYSTACK_ALIGN);
while (n_bytes < n_bytes_to_free) {
n_bytes += *(size_t *)(MP_STATE_THREAD(pystack_cur) - n_bytes - MICROPY_PYSTACK_ALIGN);
}
if (n_bytes != n_bytes_to_free) {
mp_printf(&mp_plat_print, "mp_pystack_free() failed: %u != %u\n", (uint)n_bytes_to_free,
(uint)*(size_t *)(MP_STATE_THREAD(pystack_cur) - MICROPY_PYSTACK_ALIGN));
assert(0);
}
#endif
MP_STATE_THREAD(pystack_cur) = (uint8_t *)ptr;
}
static inline void mp_pystack_realloc(void *ptr, size_t n_bytes) {
mp_pystack_free(ptr);
mp_pystack_alloc(n_bytes);
}
static inline size_t mp_pystack_usage(void) {
return MP_STATE_THREAD(pystack_cur) - MP_STATE_THREAD(pystack_start);
}
static inline size_t mp_pystack_limit(void) {
return MP_STATE_THREAD(pystack_end) - MP_STATE_THREAD(pystack_start);
}
#endif
#if !MICROPY_ENABLE_PYSTACK
#define mp_local_alloc(n_bytes) alloca(n_bytes)
static inline void mp_local_free(void *ptr) {
(void)ptr;
}
static inline void *mp_nonlocal_alloc(size_t n_bytes) {
return m_new(uint8_t, n_bytes);
}
static inline void *mp_nonlocal_realloc(void *ptr, size_t old_n_bytes, size_t new_n_bytes) {
return m_renew(uint8_t, ptr, old_n_bytes, new_n_bytes);
}
static inline void mp_nonlocal_free(void *ptr, size_t n_bytes) {
m_del(uint8_t, ptr, n_bytes);
}
#else
static inline void *mp_local_alloc(size_t n_bytes) {
return mp_pystack_alloc(n_bytes);
}
static inline void mp_local_free(void *ptr) {
mp_pystack_free(ptr);
}
static inline void *mp_nonlocal_alloc(size_t n_bytes) {
return mp_pystack_alloc(n_bytes);
}
static inline void *mp_nonlocal_realloc(void *ptr, size_t old_n_bytes, size_t new_n_bytes) {
(void)old_n_bytes;
mp_pystack_realloc(ptr, new_n_bytes);
return ptr;
}
static inline void mp_nonlocal_free(void *ptr, size_t n_bytes) {
(void)n_bytes;
mp_pystack_free(ptr);
}
#endif
#endif // MICROPY_INCLUDED_PY_PYSTACK_H
| YifuLiu/AliOS-Things | components/py_engine/engine/py/pystack.h | C | apache-2.0 | 4,094 |
/*
* 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 <assert.h>
#include <string.h>
#include <stdio.h>
#include "py/mpstate.h"
#include "py/qstr.h"
#include "py/gc.h"
#include "py/runtime.h"
// NOTE: we are using linear arrays to store and search for qstr's (unique strings, interned strings)
// ultimately we will replace this with a static hash table of some kind
// also probably need to include the length in the string data, to allow null bytes in the string
#if MICROPY_DEBUG_VERBOSE // print debugging info
#define DEBUG_printf DEBUG_printf
#else // don't print debugging info
#define DEBUG_printf(...) (void)0
#endif
// A qstr is an index into the qstr pool.
// The data for a qstr contains (hash, length, data):
// - hash (configurable number of bytes)
// - length (configurable number of bytes)
// - data ("length" number of bytes)
// - \0 terminated (so they can be printed using printf)
#if MICROPY_QSTR_BYTES_IN_HASH == 1
#define Q_HASH_MASK (0xff)
#define Q_GET_HASH(q) ((mp_uint_t)(q)[0])
#define Q_SET_HASH(q, hash) do { (q)[0] = (hash); } while (0)
#elif MICROPY_QSTR_BYTES_IN_HASH == 2
#define Q_HASH_MASK (0xffff)
#define Q_GET_HASH(q) ((mp_uint_t)(q)[0] | ((mp_uint_t)(q)[1] << 8))
#define Q_SET_HASH(q, hash) do { (q)[0] = (hash); (q)[1] = (hash) >> 8; } while (0)
#else
#error unimplemented qstr hash decoding
#endif
#define Q_GET_ALLOC(q) (MICROPY_QSTR_BYTES_IN_HASH + MICROPY_QSTR_BYTES_IN_LEN + Q_GET_LENGTH(q) + 1)
#define Q_GET_DATA(q) ((q) + MICROPY_QSTR_BYTES_IN_HASH + MICROPY_QSTR_BYTES_IN_LEN)
#if MICROPY_QSTR_BYTES_IN_LEN == 1
#define Q_GET_LENGTH(q) ((q)[MICROPY_QSTR_BYTES_IN_HASH])
#define Q_SET_LENGTH(q, len) do { (q)[MICROPY_QSTR_BYTES_IN_HASH] = (len); } while (0)
#elif MICROPY_QSTR_BYTES_IN_LEN == 2
#define Q_GET_LENGTH(q) ((q)[MICROPY_QSTR_BYTES_IN_HASH] | ((q)[MICROPY_QSTR_BYTES_IN_HASH + 1] << 8))
#define Q_SET_LENGTH(q, len) do { (q)[MICROPY_QSTR_BYTES_IN_HASH] = (len); (q)[MICROPY_QSTR_BYTES_IN_HASH + 1] = (len) >> 8; } while (0)
#else
#error unimplemented qstr length decoding
#endif
#if MICROPY_PY_THREAD && !MICROPY_PY_THREAD_GIL
#define QSTR_ENTER() mp_thread_mutex_lock(&MP_STATE_VM(qstr_mutex), 1)
#define QSTR_EXIT() mp_thread_mutex_unlock(&MP_STATE_VM(qstr_mutex))
#else
#define QSTR_ENTER()
#define QSTR_EXIT()
#endif
// Initial number of entries for qstr pool, set so that the first dynamically
// allocated pool is twice this size. The value here must be <= MP_QSTRnumber_of.
#define MICROPY_ALLOC_QSTR_ENTRIES_INIT (10)
// this must match the equivalent function in makeqstrdata.py
mp_uint_t qstr_compute_hash(const byte *data, size_t len) {
// djb2 algorithm; see http://www.cse.yorku.ca/~oz/hash.html
mp_uint_t hash = 5381;
for (const byte *top = data + len; data < top; data++) {
hash = ((hash << 5) + hash) ^ (*data); // hash * 33 ^ data
}
hash &= Q_HASH_MASK;
// Make sure that valid hash is never zero, zero means "hash not computed"
if (hash == 0) {
hash++;
}
return hash;
}
const qstr_pool_t mp_qstr_special_const_pool = {
NULL, // no previous pool
0, // no previous pool
MICROPY_ALLOC_QSTR_ENTRIES_INIT,
MP_QSTRspecial_const_number_of + 1, // corresponds to number of strings in array just below
false, // special constant qstrs are not sorted
{
#ifndef NO_QSTR
#define QDEF0(id, str) str,
#define QDEF1(id, str)
#include "genhdr/qstrdefs.generated.h"
#undef QDEF0
#undef QDEF1
#endif
(const byte *)"", // spacer for MP_QSTRspecial_const_number_of
},
};
const qstr_pool_t mp_qstr_const_pool = {
(qstr_pool_t *)&mp_qstr_special_const_pool,
MP_QSTRspecial_const_number_of + 1,
MICROPY_ALLOC_QSTR_ENTRIES_INIT,
MP_QSTRnumber_of -
(MP_QSTRspecial_const_number_of + 1), // corresponds to number of strings in array just below
true, // constant qstrs are sorted
{
#ifndef NO_QSTR
#define QDEF0(id, str)
#define QDEF1(id, str) str,
#include "genhdr/qstrdefs.generated.h"
#undef QDEF0
#undef QDEF1
#endif
},
};
#ifdef MICROPY_QSTR_EXTRA_POOL
extern const qstr_pool_t MICROPY_QSTR_EXTRA_POOL;
#define CONST_POOL MICROPY_QSTR_EXTRA_POOL
#else
#define CONST_POOL mp_qstr_const_pool
#endif
void qstr_init(void) {
MP_STATE_VM(last_pool) = (qstr_pool_t *)&CONST_POOL; // we won't modify the const_pool since it has no allocated room left
MP_STATE_VM(qstr_last_chunk) = NULL;
#if MICROPY_PY_THREAD && !MICROPY_PY_THREAD_GIL
mp_thread_mutex_init(&MP_STATE_VM(qstr_mutex));
#endif
}
STATIC const byte *find_qstr(qstr q) {
// search pool for this qstr
// total_prev_len==0 in the final pool, so the loop will always terminate
qstr_pool_t *pool = MP_STATE_VM(last_pool);
while (q < pool->total_prev_len) {
pool = pool->prev;
}
return pool->qstrs[q - pool->total_prev_len];
}
// qstr_mutex must be taken while in this function
STATIC qstr qstr_add(const byte *q_ptr) {
DEBUG_printf("QSTR: add hash=%d len=%d data=%.*s\n", Q_GET_HASH(q_ptr), Q_GET_LENGTH(q_ptr), Q_GET_LENGTH(q_ptr), Q_GET_DATA(q_ptr));
// make sure we have room in the pool for a new qstr
if (MP_STATE_VM(last_pool)->len >= MP_STATE_VM(last_pool)->alloc) {
size_t new_alloc = MP_STATE_VM(last_pool)->alloc * 2;
#ifdef MICROPY_QSTR_EXTRA_POOL
// Put a lower bound on the allocation size in case the extra qstr pool has few entries
new_alloc = MAX(MICROPY_ALLOC_QSTR_ENTRIES_INIT, new_alloc);
#endif
qstr_pool_t *pool = m_new_obj_var_maybe(qstr_pool_t, const char *, new_alloc);
if (pool == NULL) {
QSTR_EXIT();
m_malloc_fail(new_alloc);
}
pool->prev = MP_STATE_VM(last_pool);
pool->total_prev_len = MP_STATE_VM(last_pool)->total_prev_len + MP_STATE_VM(last_pool)->len;
pool->alloc = new_alloc;
pool->len = 0;
pool->sorted = false;
MP_STATE_VM(last_pool) = pool;
DEBUG_printf("QSTR: allocate new pool of size %d\n", MP_STATE_VM(last_pool)->alloc);
}
// add the new qstr
MP_STATE_VM(last_pool)->qstrs[MP_STATE_VM(last_pool)->len++] = q_ptr;
// return id for the newly-added qstr
return MP_STATE_VM(last_pool)->total_prev_len + MP_STATE_VM(last_pool)->len - 1;
}
#define MP_QSTR_SEARCH_THRESHOLD 10
qstr qstr_find_strn(const char *str, size_t str_len) {
mp_uint_t str_hash = qstr_compute_hash((const byte *)str, str_len);
// search pools for the data
for (qstr_pool_t *pool = MP_STATE_VM(last_pool); pool != NULL; pool = pool->prev) {
size_t low = 0;
size_t high = pool->len - 1;
// binary search inside the pool
if (pool->sorted) {
while (high - low > MP_QSTR_SEARCH_THRESHOLD) {
size_t mid = (low + high + 1) / 2;
const byte **q = pool->qstrs + mid;
size_t len = Q_GET_LENGTH(*q);
if (len > str_len) {
len = str_len;
}
int cmp = memcmp(Q_GET_DATA(*q), str, str_len);
if (cmp < 0) {
low = mid;
} else if (cmp > 0) {
high = mid;
} else {
if (Q_GET_LENGTH(*q) < str_len) {
low = mid;
} else if (Q_GET_LENGTH(*q) > str_len) {
high = mid;
} else {
return pool->total_prev_len + (q - pool->qstrs);
}
}
}
}
// sequential search for the remaining strings
for (const byte **q = pool->qstrs + low; q != pool->qstrs + high + 1; q++) {
if (*q &&
Q_GET_HASH(*q) == str_hash &&
Q_GET_LENGTH(*q) == str_len &&
memcmp(Q_GET_DATA(*q), str, str_len) == 0) {
return pool->total_prev_len + (q - pool->qstrs);
}
}
}
// not found; return null qstr
return 0;
}
qstr qstr_from_str(const char *str) {
return qstr_from_strn(str, strlen(str));
}
qstr qstr_from_strn(const char *str, size_t len) {
QSTR_ENTER();
qstr q = qstr_find_strn(str, len);
if (q == 0) {
// qstr does not exist in interned pool so need to add it
// check that len is not too big
if (len >= (1 << (8 * MICROPY_QSTR_BYTES_IN_LEN))) {
QSTR_EXIT();
mp_raise_msg(&mp_type_RuntimeError, MP_ERROR_TEXT("name too long"));
}
// compute number of bytes needed to intern this string
size_t n_bytes = MICROPY_QSTR_BYTES_IN_HASH + MICROPY_QSTR_BYTES_IN_LEN + len + 1;
if (MP_STATE_VM(qstr_last_chunk) != NULL && MP_STATE_VM(qstr_last_used) + n_bytes > MP_STATE_VM(qstr_last_alloc)) {
// not enough room at end of previously interned string so try to grow
byte *new_p = m_renew_maybe(byte, MP_STATE_VM(qstr_last_chunk), MP_STATE_VM(qstr_last_alloc), MP_STATE_VM(qstr_last_alloc) + n_bytes, false);
if (new_p == NULL) {
// could not grow existing memory; shrink it to fit previous
(void)m_renew_maybe(byte, MP_STATE_VM(qstr_last_chunk), MP_STATE_VM(qstr_last_alloc), MP_STATE_VM(qstr_last_used), false);
MP_STATE_VM(qstr_last_chunk) = NULL;
} else {
// could grow existing memory
MP_STATE_VM(qstr_last_alloc) += n_bytes;
}
}
if (MP_STATE_VM(qstr_last_chunk) == NULL) {
// no existing memory for the interned string so allocate a new chunk
size_t al = n_bytes;
if (al < MICROPY_ALLOC_QSTR_CHUNK_INIT) {
al = MICROPY_ALLOC_QSTR_CHUNK_INIT;
}
MP_STATE_VM(qstr_last_chunk) = m_new_maybe(byte, al);
if (MP_STATE_VM(qstr_last_chunk) == NULL) {
// failed to allocate a large chunk so try with exact size
MP_STATE_VM(qstr_last_chunk) = m_new_maybe(byte, n_bytes);
if (MP_STATE_VM(qstr_last_chunk) == NULL) {
QSTR_EXIT();
m_malloc_fail(n_bytes);
}
al = n_bytes;
}
MP_STATE_VM(qstr_last_alloc) = al;
MP_STATE_VM(qstr_last_used) = 0;
}
// allocate memory from the chunk for this new interned string's data
byte *q_ptr = MP_STATE_VM(qstr_last_chunk) + MP_STATE_VM(qstr_last_used);
MP_STATE_VM(qstr_last_used) += n_bytes;
// store the interned strings' data
mp_uint_t hash = qstr_compute_hash((const byte *)str, len);
Q_SET_HASH(q_ptr, hash);
Q_SET_LENGTH(q_ptr, len);
memcpy(q_ptr + MICROPY_QSTR_BYTES_IN_HASH + MICROPY_QSTR_BYTES_IN_LEN, str, len);
q_ptr[MICROPY_QSTR_BYTES_IN_HASH + MICROPY_QSTR_BYTES_IN_LEN + len] = '\0';
q = qstr_add(q_ptr);
}
QSTR_EXIT();
return q;
}
mp_uint_t qstr_hash(qstr q) {
const byte *qd = find_qstr(q);
return Q_GET_HASH(qd);
}
size_t qstr_len(qstr q) {
const byte *qd = find_qstr(q);
return Q_GET_LENGTH(qd);
}
const char *qstr_str(qstr q) {
const byte *qd = find_qstr(q);
return (const char *)Q_GET_DATA(qd);
}
const byte *qstr_data(qstr q, size_t *len) {
const byte *qd = find_qstr(q);
*len = Q_GET_LENGTH(qd);
return Q_GET_DATA(qd);
}
void qstr_pool_info(size_t *n_pool, size_t *n_qstr, size_t *n_str_data_bytes, size_t *n_total_bytes) {
QSTR_ENTER();
*n_pool = 0;
*n_qstr = 0;
*n_str_data_bytes = 0;
*n_total_bytes = 0;
for (qstr_pool_t *pool = MP_STATE_VM(last_pool); pool != NULL && pool != &CONST_POOL; pool = pool->prev) {
*n_pool += 1;
*n_qstr += pool->len;
for (const byte **q = pool->qstrs, **q_top = pool->qstrs + pool->len; q < q_top; q++) {
*n_str_data_bytes += Q_GET_ALLOC(*q);
}
#if MICROPY_ENABLE_GC
*n_total_bytes += gc_nbytes(pool); // this counts actual bytes used in heap
#else
*n_total_bytes += sizeof(qstr_pool_t) + sizeof(qstr) * pool->alloc;
#endif
}
*n_total_bytes += *n_str_data_bytes;
QSTR_EXIT();
}
#if MICROPY_PY_MICROPYTHON_MEM_INFO
void qstr_dump_data(void) {
QSTR_ENTER();
for (qstr_pool_t *pool = MP_STATE_VM(last_pool); pool != NULL && pool != &CONST_POOL; pool = pool->prev) {
for (const byte **q = pool->qstrs, **q_top = pool->qstrs + pool->len; q < q_top; q++) {
mp_printf(&mp_plat_print, "Q(%s)\n", Q_GET_DATA(*q));
}
}
QSTR_EXIT();
}
#endif
#if MICROPY_ROM_TEXT_COMPRESSION
#ifdef NO_QSTR
// If NO_QSTR is set, it means we're doing QSTR extraction.
// So we won't yet have "genhdr/compressed.data.h"
#else
// Emit the compressed_string_data string.
#define MP_COMPRESSED_DATA(x) STATIC const char *compressed_string_data = x;
#define MP_MATCH_COMPRESSED(a, b)
#include "genhdr/compressed.data.h"
#undef MP_COMPRESSED_DATA
#undef MP_MATCH_COMPRESSED
#endif // NO_QSTR
// This implements the "common word" compression scheme (see makecompresseddata.py) where the most
// common 128 words in error messages are replaced by their index into the list of common words.
// The compressed string data is delimited by setting high bit in the final char of each word.
// e.g. aaaa<0x80|a>bbbbbb<0x80|b>....
// This method finds the n'th string.
STATIC const byte *find_uncompressed_string(uint8_t n) {
const byte *c = (byte *)compressed_string_data;
while (n > 0) {
while ((*c & 0x80) == 0) {
++c;
}
++c;
--n;
}
return c;
}
// Given a compressed string in src, decompresses it into dst.
// dst must be large enough (use MP_MAX_UNCOMPRESSED_TEXT_LEN+1).
void mp_decompress_rom_string(byte *dst, const mp_rom_error_text_t src_chr) {
// Skip past the 0xff marker.
const byte *src = (byte *)src_chr + 1;
// Need to add spaces around compressed words, except for the first (i.e. transition from 1<->2).
// 0 = start, 1 = compressed, 2 = regular.
int state = 0;
while (*src) {
if ((byte) * src >= 128) {
if (state != 0) {
*dst++ = ' ';
}
state = 1;
// High bit set, replace with common word.
const byte *word = find_uncompressed_string(*src & 0x7f);
// The word is terminated by the final char having its high bit set.
while ((*word & 0x80) == 0) {
*dst++ = *word++;
}
*dst++ = (*word & 0x7f);
} else {
// Otherwise just copy one char.
if (state == 1) {
*dst++ = ' ';
}
state = 2;
*dst++ = *src;
}
++src;
}
// Add null-terminator.
*dst = 0;
}
#endif // MICROPY_ROM_TEXT_COMPRESSION
| YifuLiu/AliOS-Things | components/py_engine/engine/py/qstr.c | C | apache-2.0 | 16,290 |
/*
* 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.
*/
#ifndef MICROPY_INCLUDED_PY_QSTR_H
#define MICROPY_INCLUDED_PY_QSTR_H
#include "py/mpconfig.h"
#include "py/misc.h"
// See qstrdefs.h for a list of qstr's that are available as constants.
// Reference them as MP_QSTR_xxxx.
//
// Note: it would be possible to define MP_QSTR_xxx as qstr_from_str("xxx")
// for qstrs that are referenced this way, but you don't want to have them in ROM.
// first entry in enum will be MP_QSTRnull=0, which indicates invalid/no qstr
enum {
#ifndef NO_QSTR
#define QDEF0(id, str) id,
#define QDEF1(id, str)
#include "genhdr/qstrdefs.generated.h"
#undef QDEF0
#undef QDEF1
MP_QSTRspecial_const_number_of, // no underscore so it can't clash with any of the above
#define QDEF0(id, str)
#define QDEF1(id, str) id,
#include "genhdr/qstrdefs.generated.h"
#undef QDEF0
#undef QDEF1
#endif
MP_QSTRnumber_of, // no underscore so it can't clash with any of the above
};
typedef size_t qstr;
typedef struct _qstr_pool_t {
struct _qstr_pool_t *prev;
size_t total_prev_len;
size_t alloc;
size_t len;
bool sorted;
const byte *qstrs[];
} qstr_pool_t;
#define QSTR_TOTAL() (MP_STATE_VM(last_pool)->total_prev_len + MP_STATE_VM(last_pool)->len)
void qstr_init(void);
mp_uint_t qstr_compute_hash(const byte *data, size_t len);
qstr qstr_find_strn(const char *str, size_t str_len); // returns MP_QSTRnull if not found
qstr qstr_from_str(const char *str);
qstr qstr_from_strn(const char *str, size_t len);
mp_uint_t qstr_hash(qstr q);
const char *qstr_str(qstr q);
size_t qstr_len(qstr q);
const byte *qstr_data(qstr q, size_t *len);
void qstr_pool_info(size_t *n_pool, size_t *n_qstr, size_t *n_str_data_bytes, size_t *n_total_bytes);
void qstr_dump_data(void);
#if MICROPY_ROM_TEXT_COMPRESSION
void mp_decompress_rom_string(byte *dst, mp_rom_error_text_t src);
#define MP_IS_COMPRESSED_ROM_STRING(s) (*(byte *)(s) == 0xff)
#endif
#endif // MICROPY_INCLUDED_PY_QSTR_H
| YifuLiu/AliOS-Things | components/py_engine/engine/py/qstr.h | C | apache-2.0 | 3,175 |
/*
* 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.
*/
// *FORMAT-OFF*
#include "py/mpconfig.h"
// All the qstr definitions in this file are available as constants.
// That is, they are in ROM and you can reference them simply as MP_QSTR_xxxx.
// qstr configuration passed to makeqstrdata.py of the form QCFG(key, value)
QCFG(BYTES_IN_LEN, MICROPY_QSTR_BYTES_IN_LEN)
QCFG(BYTES_IN_HASH, MICROPY_QSTR_BYTES_IN_HASH)
Q()
Q(*)
Q(_)
Q(/)
#if MICROPY_PY_BUILTINS_STR_OP_MODULO
Q(%#o)
Q(%#x)
#else
Q({:#o})
Q({:#x})
#endif
Q({:#b})
Q( )
Q(\n)
Q(maximum recursion depth exceeded)
Q(<module>)
Q(<lambda>)
Q(<listcomp>)
Q(<dictcomp>)
Q(<setcomp>)
Q(<genexpr>)
Q(<string>)
Q(<stdin>)
Q(utf-8)
#if MICROPY_ENABLE_PYSTACK
Q(pystack exhausted)
#endif
| YifuLiu/AliOS-Things | components/py_engine/engine/py/qstrdefs.h | C | apache-2.0 | 1,920 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2013-2016 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 <stdio.h>
#include <assert.h>
#include "py/runtime.h"
#include "py/mperrno.h"
#include "py/mpthread.h"
#include "py/reader.h"
typedef struct _mp_reader_mem_t {
size_t free_len; // if >0 mem is freed on close by: m_free(beg, free_len)
const byte *beg;
const byte *cur;
const byte *end;
} mp_reader_mem_t;
STATIC mp_uint_t mp_reader_mem_readbyte(void *data) {
mp_reader_mem_t *reader = (mp_reader_mem_t *)data;
if (reader->cur < reader->end) {
return *reader->cur++;
} else {
return MP_READER_EOF;
}
}
STATIC void mp_reader_mem_close(void *data) {
mp_reader_mem_t *reader = (mp_reader_mem_t *)data;
if (reader->free_len > 0) {
m_del(char, (char *)reader->beg, reader->free_len);
}
m_del_obj(mp_reader_mem_t, reader);
}
void mp_reader_new_mem(mp_reader_t *reader, const byte *buf, size_t len, size_t free_len) {
mp_reader_mem_t *rm = m_new_obj(mp_reader_mem_t);
rm->free_len = free_len;
rm->beg = buf;
rm->cur = buf;
rm->end = buf + len;
reader->data = rm;
reader->readbyte = mp_reader_mem_readbyte;
reader->close = mp_reader_mem_close;
}
#if MICROPY_READER_POSIX
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
typedef struct _mp_reader_posix_t {
bool close_fd;
int fd;
size_t len;
size_t pos;
byte buf[20];
} mp_reader_posix_t;
STATIC mp_uint_t mp_reader_posix_readbyte(void *data) {
mp_reader_posix_t *reader = (mp_reader_posix_t *)data;
if (reader->pos >= reader->len) {
if (reader->len == 0) {
return MP_READER_EOF;
} else {
MP_THREAD_GIL_EXIT();
int n = read(reader->fd, reader->buf, sizeof(reader->buf));
MP_THREAD_GIL_ENTER();
if (n <= 0) {
reader->len = 0;
return MP_READER_EOF;
}
reader->len = n;
reader->pos = 0;
}
}
return reader->buf[reader->pos++];
}
STATIC void mp_reader_posix_close(void *data) {
mp_reader_posix_t *reader = (mp_reader_posix_t *)data;
if (reader->close_fd) {
MP_THREAD_GIL_EXIT();
close(reader->fd);
MP_THREAD_GIL_ENTER();
}
m_del_obj(mp_reader_posix_t, reader);
}
void mp_reader_new_file_from_fd(mp_reader_t *reader, int fd, bool close_fd) {
mp_reader_posix_t *rp = m_new_obj(mp_reader_posix_t);
rp->close_fd = close_fd;
rp->fd = fd;
MP_THREAD_GIL_EXIT();
int n = read(rp->fd, rp->buf, sizeof(rp->buf));
if (n == -1) {
if (close_fd) {
close(fd);
}
MP_THREAD_GIL_ENTER();
mp_raise_OSError(errno);
}
MP_THREAD_GIL_ENTER();
rp->len = n;
rp->pos = 0;
reader->data = rp;
reader->readbyte = mp_reader_posix_readbyte;
reader->close = mp_reader_posix_close;
}
#if !MICROPY_VFS_POSIX
// If MICROPY_VFS_POSIX is defined then this function is provided by the VFS layer
void mp_reader_new_file(mp_reader_t *reader, const char *filename) {
MP_THREAD_GIL_EXIT();
int fd = open(filename, O_RDONLY, 0644);
MP_THREAD_GIL_ENTER();
if (fd < 0) {
mp_raise_OSError(errno);
}
mp_reader_new_file_from_fd(reader, fd, true);
}
#endif
#endif
| YifuLiu/AliOS-Things | components/py_engine/engine/py/reader.c | C | apache-2.0 | 4,473 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2013-2016 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.
*/
#ifndef MICROPY_INCLUDED_PY_READER_H
#define MICROPY_INCLUDED_PY_READER_H
#include "py/obj.h"
// the readbyte function must return the next byte in the input stream
// it must return MP_READER_EOF if end of stream
// it can be called again after returning MP_READER_EOF, and in that case must return MP_READER_EOF
#define MP_READER_EOF ((mp_uint_t)(-1))
typedef struct _mp_reader_t {
void *data;
mp_uint_t (*readbyte)(void *data);
void (*close)(void *data);
} mp_reader_t;
void mp_reader_new_mem(mp_reader_t *reader, const byte *buf, size_t len, size_t free_len);
void mp_reader_new_file(mp_reader_t *reader, const char *filename);
void mp_reader_new_file_from_fd(mp_reader_t *reader, int fd, bool close_fd);
#endif // MICROPY_INCLUDED_PY_READER_H
| YifuLiu/AliOS-Things | components/py_engine/engine/py/reader.h | C | apache-2.0 | 1,995 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2013-2015 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 <string.h>
#include "py/obj.h"
#include "py/objmodule.h"
#include "py/runtime.h"
#include "py/builtin.h"
#include "py/repl.h"
#if MICROPY_HELPER_REPL
STATIC bool str_startswith_word(const char *str, const char *head) {
size_t i;
for (i = 0; str[i] && head[i]; i++) {
if (str[i] != head[i]) {
return false;
}
}
return head[i] == '\0' && (str[i] == '\0' || !unichar_isident(str[i]));
}
bool mp_repl_continue_with_input(const char *input) {
// check for blank input
if (input[0] == '\0') {
return false;
}
// check if input starts with a certain keyword
bool starts_with_compound_keyword =
input[0] == '@'
|| str_startswith_word(input, "if")
|| str_startswith_word(input, "while")
|| str_startswith_word(input, "for")
|| str_startswith_word(input, "try")
|| str_startswith_word(input, "with")
|| str_startswith_word(input, "def")
|| str_startswith_word(input, "class")
#if MICROPY_PY_ASYNC_AWAIT
|| str_startswith_word(input, "async")
#endif
;
// check for unmatched open bracket, quote or escape quote
#define Q_NONE (0)
#define Q_1_SINGLE (1)
#define Q_1_DOUBLE (2)
#define Q_3_SINGLE (3)
#define Q_3_DOUBLE (4)
int n_paren = 0;
int n_brack = 0;
int n_brace = 0;
int in_quote = Q_NONE;
const char *i;
for (i = input; *i; i++) {
if (*i == '\'') {
if ((in_quote == Q_NONE || in_quote == Q_3_SINGLE) && i[1] == '\'' && i[2] == '\'') {
i += 2;
in_quote = Q_3_SINGLE - in_quote;
} else if (in_quote == Q_NONE || in_quote == Q_1_SINGLE) {
in_quote = Q_1_SINGLE - in_quote;
}
} else if (*i == '"') {
if ((in_quote == Q_NONE || in_quote == Q_3_DOUBLE) && i[1] == '"' && i[2] == '"') {
i += 2;
in_quote = Q_3_DOUBLE - in_quote;
} else if (in_quote == Q_NONE || in_quote == Q_1_DOUBLE) {
in_quote = Q_1_DOUBLE - in_quote;
}
} else if (*i == '\\' && (i[1] == '\'' || i[1] == '"' || i[1] == '\\')) {
if (in_quote != Q_NONE) {
i++;
}
} else if (in_quote == Q_NONE) {
switch (*i) {
case '(':
n_paren += 1;
break;
case ')':
n_paren -= 1;
break;
case '[':
n_brack += 1;
break;
case ']':
n_brack -= 1;
break;
case '{':
n_brace += 1;
break;
case '}':
n_brace -= 1;
break;
default:
break;
}
}
}
// continue if unmatched 3-quotes
if (in_quote == Q_3_SINGLE || in_quote == Q_3_DOUBLE) {
return true;
}
// continue if unmatched brackets, but only if not in a 1-quote
if ((n_paren > 0 || n_brack > 0 || n_brace > 0) && in_quote == Q_NONE) {
return true;
}
// continue if last character was backslash (for line continuation)
if (i[-1] == '\\') {
return true;
}
// continue if compound keyword and last line was not empty
if (starts_with_compound_keyword && i[-1] != '\n') {
return true;
}
// otherwise, don't continue
return false;
}
STATIC bool test_qstr(mp_obj_t obj, qstr name) {
if (obj) {
// try object member
mp_obj_t dest[2];
mp_load_method_protected(obj, name, dest, true);
return dest[0] != MP_OBJ_NULL;
} else {
// try builtin module
return mp_map_lookup((mp_map_t *)&mp_builtin_module_map,
MP_OBJ_NEW_QSTR(name), MP_MAP_LOOKUP);
}
}
STATIC const char *find_completions(const char *s_start, size_t s_len,
mp_obj_t obj, size_t *match_len, qstr *q_first, qstr *q_last) {
const char *match_str = NULL;
*match_len = 0;
*q_first = *q_last = 0;
size_t nqstr = QSTR_TOTAL();
for (qstr q = MP_QSTR_ + 1; q < nqstr; ++q) {
size_t d_len;
const char *d_str = (const char *)qstr_data(q, &d_len);
// special case; filter out words that begin with underscore
// unless there's already a partial match
if (s_len == 0 && d_str[0] == '_') {
continue;
}
if (s_len <= d_len && strncmp(s_start, d_str, s_len) == 0) {
if (test_qstr(obj, q)) {
if (match_str == NULL) {
match_str = d_str;
*match_len = d_len;
} else {
// search for longest common prefix of match_str and d_str
// (assumes these strings are null-terminated)
for (size_t j = s_len; j <= *match_len && j <= d_len; ++j) {
if (match_str[j] != d_str[j]) {
*match_len = j;
break;
}
}
}
if (*q_first == 0) {
*q_first = q;
}
*q_last = q;
}
}
}
return match_str;
}
STATIC void print_completions(const mp_print_t *print,
const char *s_start, size_t s_len,
mp_obj_t obj, qstr q_first, qstr q_last) {
#define WORD_SLOT_LEN (16)
#define MAX_LINE_LEN (4 * WORD_SLOT_LEN)
int line_len = MAX_LINE_LEN; // force a newline for first word
for (qstr q = q_first; q <= q_last; ++q) {
size_t d_len;
const char *d_str = (const char *)qstr_data(q, &d_len);
if (s_len <= d_len && strncmp(s_start, d_str, s_len) == 0) {
if (test_qstr(obj, q)) {
int gap = (line_len + WORD_SLOT_LEN - 1) / WORD_SLOT_LEN * WORD_SLOT_LEN - line_len;
if (gap < 2) {
gap += WORD_SLOT_LEN;
}
if (line_len + gap + d_len <= MAX_LINE_LEN) {
// TODO optimise printing of gap?
for (int j = 0; j < gap; ++j) {
mp_print_str(print, " ");
}
mp_print_str(print, d_str);
line_len += gap + d_len;
} else {
mp_printf(print, "\n%s", d_str);
line_len = d_len;
}
}
}
}
mp_print_str(print, "\n");
}
size_t mp_repl_autocomplete(const char *str, size_t len, const mp_print_t *print, const char **compl_str) {
// scan backwards to find start of "a.b.c" chain
const char *org_str = str;
const char *top = str + len;
for (const char *s = top; --s >= str;) {
if (!(unichar_isalpha(*s) || unichar_isdigit(*s) || *s == '_' || *s == '.')) {
++s;
str = s;
break;
}
}
// begin search in outer global dict which is accessed from __main__
mp_obj_t obj = MP_OBJ_FROM_PTR(&mp_module___main__);
mp_obj_t dest[2];
const char *s_start;
size_t s_len;
for (;;) {
// get next word in string to complete
s_start = str;
while (str < top && *str != '.') {
++str;
}
s_len = str - s_start;
if (str == top) {
// end of string, do completion on this partial name
break;
}
// a complete word, lookup in current object
qstr q = qstr_find_strn(s_start, s_len);
if (q == MP_QSTRnull) {
// lookup will fail
return 0;
}
mp_load_method_protected(obj, q, dest, true);
obj = dest[0]; // attribute, method, or MP_OBJ_NULL if nothing found
if (obj == MP_OBJ_NULL) {
// lookup failed
return 0;
}
// skip '.' to move to next word
++str;
}
// after "import", suggest built-in modules
static const char import_str[] = "import ";
if (len >= 7 && !memcmp(org_str, import_str, 7)) {
obj = MP_OBJ_NULL;
}
// look for matches
size_t match_len;
qstr q_first, q_last;
const char *match_str =
find_completions(s_start, s_len, obj, &match_len, &q_first, &q_last);
// nothing found
if (q_first == 0) {
// If there're no better alternatives, and if it's first word
// in the line, try to complete "import".
if (s_start == org_str && s_len > 0 && s_len < sizeof(import_str) - 1) {
if (memcmp(s_start, import_str, s_len) == 0) {
*compl_str = import_str + s_len;
return sizeof(import_str) - 1 - s_len;
}
}
if (q_first == 0) {
*compl_str = " ";
return s_len ? 0 : 4;
}
}
// 1 match found, or multiple matches with a common prefix
if (q_first == q_last || match_len > s_len) {
*compl_str = match_str + s_len;
return match_len - s_len;
}
// multiple matches found, print them out
print_completions(print, s_start, s_len, obj, q_first, q_last);
return (size_t)(-1); // indicate many matches
}
#endif // MICROPY_HELPER_REPL
| YifuLiu/AliOS-Things | components/py_engine/engine/py/repl.c | C | apache-2.0 | 10,607 |
/*
* 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.
*/
#ifndef MICROPY_INCLUDED_PY_REPL_H
#define MICROPY_INCLUDED_PY_REPL_H
#include "py/mpconfig.h"
#include "py/misc.h"
#include "py/mpprint.h"
#if MICROPY_HELPER_REPL
bool mp_repl_continue_with_input(const char *input);
size_t mp_repl_autocomplete(const char *str, size_t len, const mp_print_t *print, const char **compl_str);
#endif
#endif // MICROPY_INCLUDED_PY_REPL_H
| YifuLiu/AliOS-Things | components/py_engine/engine/py/repl.h | C | apache-2.0 | 1,602 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2019 Jim Mussared
*
* 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 "ringbuf.h"
int ringbuf_get16(ringbuf_t *r) {
int v = ringbuf_peek16(r);
if (v == -1) {
return v;
}
r->iget += 2;
if (r->iget >= r->size) {
r->iget -= r->size;
}
return v;
}
int ringbuf_peek16(ringbuf_t *r) {
if (r->iget == r->iput) {
return -1;
}
uint32_t iget_a = r->iget + 1;
if (iget_a == r->size) {
iget_a = 0;
}
if (iget_a == r->iput) {
return -1;
}
return (r->buf[r->iget] << 8) | (r->buf[iget_a]);
}
int ringbuf_put16(ringbuf_t *r, uint16_t v) {
uint32_t iput_a = r->iput + 1;
if (iput_a == r->size) {
iput_a = 0;
}
if (iput_a == r->iget) {
return -1;
}
uint32_t iput_b = iput_a + 1;
if (iput_b == r->size) {
iput_b = 0;
}
if (iput_b == r->iget) {
return -1;
}
r->buf[r->iput] = (v >> 8) & 0xff;
r->buf[iput_a] = v & 0xff;
r->iput = iput_b;
return 0;
}
| YifuLiu/AliOS-Things | components/py_engine/engine/py/ringbuf.c | C | apache-2.0 | 2,182 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2016 Paul Sokolovsky
*
* 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.
*/
#ifndef MICROPY_INCLUDED_PY_RINGBUF_H
#define MICROPY_INCLUDED_PY_RINGBUF_H
#include <stddef.h>
#include <stdint.h>
#ifdef _MSC_VER
#include "py/mpconfig.h" // For inline.
#endif
typedef struct _ringbuf_t {
uint8_t *buf;
uint16_t size;
uint16_t iget;
uint16_t iput;
} ringbuf_t;
// Static initialization:
// byte buf_array[N];
// ringbuf_t buf = {buf_array, sizeof(buf_array)};
// Dynamic initialization. This needs to become findable as a root pointer!
#define ringbuf_alloc(r, sz) \
{ \
(r)->buf = m_new(uint8_t, sz); \
(r)->size = sz; \
(r)->iget = (r)->iput = 0; \
}
static inline int ringbuf_get(ringbuf_t *r) {
if (r->iget == r->iput) {
return -1;
}
uint8_t v = r->buf[r->iget++];
if (r->iget >= r->size) {
r->iget = 0;
}
return v;
}
static inline int ringbuf_peek(ringbuf_t *r) {
if (r->iget == r->iput) {
return -1;
}
return r->buf[r->iget];
}
static inline int ringbuf_put(ringbuf_t *r, uint8_t v) {
uint32_t iput_new = r->iput + 1;
if (iput_new >= r->size) {
iput_new = 0;
}
if (iput_new == r->iget) {
return -1;
}
r->buf[r->iput] = v;
r->iput = iput_new;
return 0;
}
static inline size_t ringbuf_free(ringbuf_t *r) {
return (r->size + r->iget - r->iput - 1) % r->size;
}
static inline size_t ringbuf_avail(ringbuf_t *r) {
return (r->size + r->iput - r->iget) % r->size;
}
// Note: big-endian. No-op if not enough room available for both bytes.
int ringbuf_get16(ringbuf_t *r);
int ringbuf_peek16(ringbuf_t *r);
int ringbuf_put16(ringbuf_t *r, uint16_t v);
#endif // MICROPY_INCLUDED_PY_RINGBUF_H
| YifuLiu/AliOS-Things | components/py_engine/engine/py/ringbuf.h | C | apache-2.0 | 2,907 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2013, 2014 Damien P. George
* Copyright (c) 2014-2018 Paul Sokolovsky
*
* 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>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include "py/parsenum.h"
#include "py/compile.h"
#include "py/objstr.h"
#include "py/objtuple.h"
#include "py/objlist.h"
#include "py/objtype.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"
#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
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_THREAD(mp_pending_exception) = MP_OBJ_NULL;
#if MICROPY_ENABLE_SCHEDULER
MP_STATE_VM(sched_state) = MP_SCHED_IDLE;
MP_STATE_VM(sched_idx) = 0;
MP_STATE_VM(sched_len) = 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
#if MICROPY_ENABLE_COMPILER
// optimization disabled by default
MP_STATE_VM(mp_optimise_value) = 0;
#if MICROPY_EMIT_NATIVE
MP_STATE_VM(default_emit_opt) = MP_EMIT_OPT_NONE;
#endif
#endif
// init global module dict
mp_obj_dict_init(&MP_STATE_VM(mp_loaded_modules_dict), MICROPY_LOADED_MODULES_DICT_SIZE);
// 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_PERSISTENT_CODE_TRACK_RELOC_CODE
MP_STATE_VM(track_reloc_code_list) = MP_OBJ_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;
}
#endif
#if MICROPY_VFS
// initialise the VFS sub-system
MP_STATE_VM(vfs_cur) = NULL;
MP_STATE_VM(vfs_mount_table) = NULL;
#endif
#if MICROPY_PY_SYS_ATEXIT
MP_STATE_VM(sys_exitfunc) = mp_const_none;
#endif
#if MICROPY_PY_SYS_SETTRACE
MP_STATE_THREAD(prof_trace_callback) = MP_OBJ_NULL;
MP_STATE_THREAD(prof_callback_is_executing) = false;
MP_STATE_THREAD(current_code_state) = NULL;
#endif
#if MICROPY_PY_BLUETOOTH
MP_STATE_VM(bluetooth) = MP_OBJ_NULL;
#endif
#if MICROPY_PY_THREAD_GIL
mp_thread_mutex_init(&MP_STATE_VM(gil_mutex));
#endif
// call port specific initialization if any
#ifdef MICROPY_PORT_INIT_FUNC
MICROPY_PORT_INIT_FUNC;
#endif
MP_THREAD_GIL_ENTER();
}
void mp_deinit(void) {
MP_THREAD_GIL_EXIT();
// call port specific deinitialization if any
#ifdef MICROPY_PORT_DEINIT_FUNC
MICROPY_PORT_DEINIT_FUNC;
#endif
}
mp_obj_t mp_load_name(qstr qst) {
// 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;
}
}
return mp_load_global(qst);
}
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, MP_ERROR_TEXT("name not defined"));
#else
mp_raise_msg_varg(&mp_type_NameError, MP_ERROR_TEXT("name '%q' isn't defined"), qst);
#endif
}
}
return elem->value;
}
mp_obj_t mp_load_build_class(void) {
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);
}
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);
}
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:
case MP_UNARY_OP_INT:
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 {
const 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 (op == MP_UNARY_OP_BOOL) {
// Type doesn't have unary_op (or didn't handle MP_UNARY_OP_BOOL),
// so is implicitly True as this code path is impossible to reach
// if arg==mp_const_none.
return mp_const_true;
}
// With MP_UNARY_OP_INT, mp_unary_op() becomes a fallback for mp_obj_get_int().
// In this case provide a more focused error message to not confuse, e.g. chr(1.0)
#if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
if (op == MP_UNARY_OP_INT) {
mp_raise_TypeError(MP_ERROR_TEXT("can't convert to int"));
} else {
mp_raise_TypeError(MP_ERROR_TEXT("unsupported type for operator"));
}
#else
if (op == MP_UNARY_OP_INT) {
mp_raise_msg_varg(&mp_type_TypeError,
MP_ERROR_TEXT("can't convert %s to int"), mp_obj_get_type_str(arg));
} else {
mp_raise_msg_varg(&mp_type_TypeError,
MP_ERROR_TEXT("unsupported type for %q: '%s'"),
mp_unary_op_method_name[op], mp_obj_get_type_str(arg));
}
#endif
}
}
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) {
// mp_obj_equal_not_equal supports a bunch of shortcuts
return mp_obj_equal_not_equal(op, lhs, rhs);
}
// 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(MP_ERROR_TEXT("negative shift count"));
} else if (rhs_val >= (mp_int_t)(sizeof(lhs_val) * MP_BITS_PER_BYTE)
|| 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 = (mp_uint_t)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(MP_ERROR_TEXT("negative shift count"));
} else {
// standard precision is enough for right-shift
if (rhs_val >= (mp_int_t)(sizeof(lhs_val) * MP_BITS_PER_BYTE)) {
// Shifting to big amounts is underfined behavior
// in C and is CPU-dependent; propagate sign bit.
rhs_val = sizeof(lhs_val) * MP_BITS_PER_BYTE - 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
return mp_obj_float_binary_op(op, (mp_float_t)lhs_val, rhs);
#else
mp_raise_ValueError(MP_ERROR_TEXT("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;
}
// This is an inlined version of mp_obj_new_int, for speed
if (MP_SMALL_INT_FITS(lhs_val)) {
return MP_OBJ_NEW_SMALL_INT(lhs_val);
} else {
return mp_obj_new_int_from_ll(lhs_val);
}
#if MICROPY_PY_BUILTINS_FLOAT
} else if (mp_obj_is_float(rhs)) {
mp_obj_t res = mp_obj_float_binary_op(op, (mp_float_t)lhs_val, rhs);
if (res == MP_OBJ_NULL) {
goto unsupported_op;
} else {
return res;
}
#endif
#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, (mp_float_t)lhs_val, 0, rhs);
if (res == MP_OBJ_NULL) {
goto unsupported_op;
} else {
return res;
}
#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
const 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;
}
}
#if MICROPY_PY_REVERSE_SPECIAL_METHODS
if (op >= MP_BINARY_OP_OR && op <= MP_BINARY_OP_POWER) {
mp_obj_t t = rhs;
rhs = lhs;
lhs = t;
op += MP_BINARY_OP_REVERSE_OR - MP_BINARY_OP_OR;
goto generic_binary_op;
} else if (op >= MP_BINARY_OP_REVERSE_OR) {
// Convert __rop__ back to __op__ for error message
mp_obj_t t = rhs;
rhs = lhs;
lhs = t;
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) {
if (mp_obj_equal(next, rhs)) {
return mp_const_true;
}
}
return mp_const_false;
}
unsupported_op:
#if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
mp_raise_TypeError(MP_ERROR_TEXT("unsupported type for operator"));
#else
mp_raise_msg_varg(&mp_type_TypeError,
MP_ERROR_TEXT("unsupported types for %q: '%s', '%s'"),
mp_binary_op_method_name[op], mp_obj_get_type_str(lhs), mp_obj_get_type_str(rhs));
#endif
zero_division:
mp_raise_msg(&mp_type_ZeroDivisionError, MP_ERROR_TEXT("divide by zero"));
}
mp_obj_t mp_call_function_0(mp_obj_t fun) {
return mp_call_function_n_kw(fun, 0, 0, NULL);
}
mp_obj_t mp_call_function_1(mp_obj_t fun, mp_obj_t arg) {
return mp_call_function_n_kw(fun, 1, 0, &arg);
}
mp_obj_t mp_call_function_2(mp_obj_t fun, mp_obj_t arg1, mp_obj_t arg2) {
mp_obj_t args[2];
args[0] = arg1;
args[1] = arg2;
return mp_call_function_n_kw(fun, 2, 0, args);
}
// args contains, eg: arg0 arg1 key0 value0 key1 value1
mp_obj_t mp_call_function_n_kw(mp_obj_t fun_in, size_t n_args, size_t n_kw, const mp_obj_t *args) {
// TODO improve this: fun object can specify its type and we parse here the arguments,
// passing to the function arrays of fixed and keyword arguments
DEBUG_OP_printf("calling function %p(n_args=" UINT_FMT ", n_kw=" UINT_FMT ", args=%p)\n", fun_in, n_args, n_kw, args);
// get the type
const mp_obj_type_t *type = mp_obj_get_type(fun_in);
// do the call
if (type->call != NULL) {
return type->call(fun_in, n_args, n_kw, args);
}
#if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
mp_raise_TypeError(MP_ERROR_TEXT("object not callable"));
#else
mp_raise_msg_varg(&mp_type_TypeError,
MP_ERROR_TEXT("'%s' object isn't callable"), mp_obj_get_type_str(fun_in));
#endif
}
// args contains: fun self/NULL arg(0) ... arg(n_args-2) arg(n_args-1) kw_key(0) kw_val(0) ... kw_key(n_kw-1) kw_val(n_kw-1)
// if n_args==0 and n_kw==0 then there are only fun and self/NULL
mp_obj_t mp_call_method_n_kw(size_t n_args, size_t n_kw, const mp_obj_t *args) {
DEBUG_OP_printf("call method (fun=%p, self=%p, n_args=" UINT_FMT ", n_kw=" UINT_FMT ", args=%p)\n", args[0], args[1], n_args, n_kw, args);
int adjust = (args[1] == MP_OBJ_NULL) ? 0 : 1;
return mp_call_function_n_kw(args[0], n_args + adjust, n_kw, args + 2 - adjust);
}
// This function only needs to be exposed externally when in stackless mode.
#if !MICROPY_STACKLESS
STATIC
#endif
void mp_call_prepare_args_n_kw_var(bool have_self, size_t n_args_n_kw, const mp_obj_t *args, mp_call_args_t *out_args) {
mp_obj_t fun = *args++;
mp_obj_t self = MP_OBJ_NULL;
if (have_self) {
self = *args++; // may be MP_OBJ_NULL
}
uint n_args = n_args_n_kw & 0xff;
uint n_kw = (n_args_n_kw >> 8) & 0xff;
mp_obj_t pos_seq = args[n_args + 2 * n_kw]; // may be MP_OBJ_NULL
mp_obj_t kw_dict = args[n_args + 2 * n_kw + 1]; // may be MP_OBJ_NULL
DEBUG_OP_printf("call method var (fun=%p, self=%p, n_args=%u, n_kw=%u, args=%p, seq=%p, dict=%p)\n", fun, self, n_args, n_kw, args, pos_seq, kw_dict);
// We need to create the following array of objects:
// args[0 .. n_args] unpacked(pos_seq) args[n_args .. n_args + 2 * n_kw] unpacked(kw_dict)
// TODO: optimize one day to avoid constructing new arg array? Will be hard.
// The new args array
mp_obj_t *args2;
uint args2_alloc;
uint args2_len = 0;
// Try to get a hint for the size of the kw_dict
uint kw_dict_len = 0;
if (kw_dict != MP_OBJ_NULL && mp_obj_is_type(kw_dict, &mp_type_dict)) {
kw_dict_len = mp_obj_dict_len(kw_dict);
}
// Extract the pos_seq sequence to the new args array.
// Note that it can be arbitrary iterator.
if (pos_seq == MP_OBJ_NULL) {
// no sequence
// allocate memory for the new array of args
args2_alloc = 1 + n_args + 2 * (n_kw + kw_dict_len);
args2 = mp_nonlocal_alloc(args2_alloc * sizeof(mp_obj_t));
// copy the self
if (self != MP_OBJ_NULL) {
args2[args2_len++] = self;
}
// copy the fixed pos args
mp_seq_copy(args2 + args2_len, args, n_args, mp_obj_t);
args2_len += n_args;
} else if (mp_obj_is_type(pos_seq, &mp_type_tuple) || mp_obj_is_type(pos_seq, &mp_type_list)) {
// optimise the case of a tuple and list
// get the items
size_t len;
mp_obj_t *items;
mp_obj_get_array(pos_seq, &len, &items);
// allocate memory for the new array of args
args2_alloc = 1 + n_args + len + 2 * (n_kw + kw_dict_len);
args2 = mp_nonlocal_alloc(args2_alloc * sizeof(mp_obj_t));
// copy the self
if (self != MP_OBJ_NULL) {
args2[args2_len++] = self;
}
// copy the fixed and variable position args
mp_seq_cat(args2 + args2_len, args, n_args, items, len, mp_obj_t);
args2_len += n_args + len;
} else {
// generic iterator
// allocate memory for the new array of args
args2_alloc = 1 + n_args + 2 * (n_kw + kw_dict_len) + 3;
args2 = mp_nonlocal_alloc(args2_alloc * sizeof(mp_obj_t));
// copy the self
if (self != MP_OBJ_NULL) {
args2[args2_len++] = self;
}
// copy the fixed position args
mp_seq_copy(args2 + args2_len, args, n_args, mp_obj_t);
args2_len += n_args;
// extract the variable position args from the iterator
mp_obj_iter_buf_t iter_buf;
mp_obj_t iterable = mp_getiter(pos_seq, &iter_buf);
mp_obj_t item;
while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
if (args2_len >= args2_alloc) {
args2 = mp_nonlocal_realloc(args2, args2_alloc * sizeof(mp_obj_t), args2_alloc * 2 * sizeof(mp_obj_t));
args2_alloc *= 2;
}
args2[args2_len++] = item;
}
}
// The size of the args2 array now is the number of positional args.
uint pos_args_len = args2_len;
// Copy the fixed kw args.
mp_seq_copy(args2 + args2_len, args + n_args, 2 * n_kw, mp_obj_t);
args2_len += 2 * n_kw;
// Extract (key,value) pairs from kw_dict dictionary and append to args2.
// Note that it can be arbitrary iterator.
if (kw_dict == MP_OBJ_NULL) {
// pass
} else if (mp_obj_is_type(kw_dict, &mp_type_dict)) {
// dictionary
mp_map_t *map = mp_obj_dict_get_map(kw_dict);
assert(args2_len + 2 * map->used <= args2_alloc); // should have enough, since kw_dict_len is in this case hinted correctly above
for (size_t i = 0; i < map->alloc; i++) {
if (mp_map_slot_is_filled(map, i)) {
// the key must be a qstr, so intern it if it's a string
mp_obj_t key = map->table[i].key;
if (!mp_obj_is_qstr(key)) {
key = mp_obj_str_intern_checked(key);
}
args2[args2_len++] = key;
args2[args2_len++] = map->table[i].value;
}
}
} else {
// generic mapping:
// - call keys() to get an iterable of all keys in the mapping
// - call __getitem__ for each key to get the corresponding value
// get the keys iterable
mp_obj_t dest[3];
mp_load_method(kw_dict, MP_QSTR_keys, dest);
mp_obj_t iterable = mp_getiter(mp_call_method_n_kw(0, 0, dest), NULL);
mp_obj_t key;
while ((key = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
// expand size of args array if needed
if (args2_len + 1 >= args2_alloc) {
uint new_alloc = args2_alloc * 2;
if (new_alloc < 4) {
new_alloc = 4;
}
args2 = mp_nonlocal_realloc(args2, args2_alloc * sizeof(mp_obj_t), new_alloc * sizeof(mp_obj_t));
args2_alloc = new_alloc;
}
// the key must be a qstr, so intern it if it's a string
if (!mp_obj_is_qstr(key)) {
key = mp_obj_str_intern_checked(key);
}
// get the value corresponding to the key
mp_load_method(kw_dict, MP_QSTR___getitem__, dest);
dest[2] = key;
mp_obj_t value = mp_call_method_n_kw(1, 0, dest);
// store the key/value pair in the argument array
args2[args2_len++] = key;
args2[args2_len++] = value;
}
}
out_args->fun = fun;
out_args->args = args2;
out_args->n_args = pos_args_len;
out_args->n_kw = (args2_len - pos_args_len) / 2;
out_args->n_alloc = args2_alloc;
}
mp_obj_t mp_call_method_n_kw_var(bool have_self, size_t n_args_n_kw, const mp_obj_t *args) {
mp_call_args_t out_args;
mp_call_prepare_args_n_kw_var(have_self, n_args_n_kw, args, &out_args);
mp_obj_t res = mp_call_function_n_kw(out_args.fun, out_args.n_args, out_args.n_kw, out_args.args);
mp_nonlocal_free(out_args.args, out_args.n_alloc * sizeof(mp_obj_t));
return res;
}
// unpacked items are stored in reverse order into the array pointed to by items
void mp_unpack_sequence(mp_obj_t seq_in, size_t num, mp_obj_t *items) {
size_t seq_len;
if (mp_obj_is_type(seq_in, &mp_type_tuple) || mp_obj_is_type(seq_in, &mp_type_list)) {
mp_obj_t *seq_items;
mp_obj_get_array(seq_in, &seq_len, &seq_items);
if (seq_len < num) {
goto too_short;
} else if (seq_len > num) {
goto too_long;
}
for (size_t i = 0; i < num; i++) {
items[i] = seq_items[num - 1 - i];
}
} else {
mp_obj_iter_buf_t iter_buf;
mp_obj_t iterable = mp_getiter(seq_in, &iter_buf);
for (seq_len = 0; seq_len < num; seq_len++) {
mp_obj_t el = mp_iternext(iterable);
if (el == MP_OBJ_STOP_ITERATION) {
goto too_short;
}
items[num - 1 - seq_len] = el;
}
if (mp_iternext(iterable) != MP_OBJ_STOP_ITERATION) {
goto too_long;
}
}
return;
too_short:
#if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
mp_raise_ValueError(MP_ERROR_TEXT("wrong number of values to unpack"));
#else
mp_raise_msg_varg(&mp_type_ValueError, MP_ERROR_TEXT("need more than %d values to unpack"), (int)seq_len);
#endif
too_long:
#if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
mp_raise_ValueError(MP_ERROR_TEXT("wrong number of values to unpack"));
#else
mp_raise_msg_varg(&mp_type_ValueError, MP_ERROR_TEXT("too many values to unpack (expected %d)"), (int)num);
#endif
}
// unpacked items are stored in reverse order into the array pointed to by items
void mp_unpack_ex(mp_obj_t seq_in, size_t num_in, mp_obj_t *items) {
size_t num_left = num_in & 0xff;
size_t num_right = (num_in >> 8) & 0xff;
DEBUG_OP_printf("unpack ex " UINT_FMT " " UINT_FMT "\n", num_left, num_right);
size_t seq_len;
if (mp_obj_is_type(seq_in, &mp_type_tuple) || mp_obj_is_type(seq_in, &mp_type_list)) {
// Make the seq variable volatile so the compiler keeps a reference to it,
// since if it's a tuple then seq_items points to the interior of the GC cell
// and mp_obj_new_list may trigger a GC which doesn't trace this and reclaims seq.
volatile mp_obj_t seq = seq_in;
mp_obj_t *seq_items;
mp_obj_get_array(seq, &seq_len, &seq_items);
if (seq_len < num_left + num_right) {
goto too_short;
}
for (size_t i = 0; i < num_right; i++) {
items[i] = seq_items[seq_len - 1 - i];
}
items[num_right] = mp_obj_new_list(seq_len - num_left - num_right, seq_items + num_left);
for (size_t i = 0; i < num_left; i++) {
items[num_right + 1 + i] = seq_items[num_left - 1 - i];
}
seq = MP_OBJ_NULL;
} else {
// Generic iterable; this gets a bit messy: we unpack known left length to the
// items destination array, then the rest to a dynamically created list. Once the
// iterable is exhausted, we take from this list for the right part of the items.
// TODO Improve to waste less memory in the dynamically created list.
mp_obj_t iterable = mp_getiter(seq_in, NULL);
mp_obj_t item;
for (seq_len = 0; seq_len < num_left; seq_len++) {
item = mp_iternext(iterable);
if (item == MP_OBJ_STOP_ITERATION) {
goto too_short;
}
items[num_left + num_right + 1 - 1 - seq_len] = item;
}
mp_obj_list_t *rest = MP_OBJ_TO_PTR(mp_obj_new_list(0, NULL));
while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
mp_obj_list_append(MP_OBJ_FROM_PTR(rest), item);
}
if (rest->len < num_right) {
goto too_short;
}
items[num_right] = MP_OBJ_FROM_PTR(rest);
for (size_t i = 0; i < num_right; i++) {
items[num_right - 1 - i] = rest->items[rest->len - num_right + i];
}
mp_obj_list_set_len(MP_OBJ_FROM_PTR(rest), rest->len - num_right);
}
return;
too_short:
#if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
mp_raise_ValueError(MP_ERROR_TEXT("wrong number of values to unpack"));
#else
mp_raise_msg_varg(&mp_type_ValueError, MP_ERROR_TEXT("need more than %d values to unpack"), (int)seq_len);
#endif
}
mp_obj_t mp_load_attr(mp_obj_t base, qstr attr) {
DEBUG_OP_printf("load attr %p.%s\n", base, qstr_str(attr));
// use load_method
mp_obj_t dest[2];
mp_load_method(base, attr, dest);
if (dest[1] == MP_OBJ_NULL) {
// load_method returned just a normal attribute
return dest[0];
} else {
// load_method returned a method, so build a bound method object
return mp_obj_new_bound_meth(dest[0], dest[1]);
}
}
#if MICROPY_BUILTIN_METHOD_CHECK_SELF_ARG
// The following "checked fun" type is local to the mp_convert_member_lookup
// function, and serves to check that the first argument to a builtin function
// has the correct type.
typedef struct _mp_obj_checked_fun_t {
mp_obj_base_t base;
const mp_obj_type_t *type;
mp_obj_t fun;
} mp_obj_checked_fun_t;
STATIC mp_obj_t checked_fun_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp_obj_t *args) {
mp_obj_checked_fun_t *self = MP_OBJ_TO_PTR(self_in);
if (n_args > 0) {
const mp_obj_type_t *arg0_type = mp_obj_get_type(args[0]);
if (arg0_type != self->type) {
#if MICROPY_ERROR_REPORTING != MICROPY_ERROR_REPORTING_DETAILED
mp_raise_TypeError(MP_ERROR_TEXT("argument has wrong type"));
#else
mp_raise_msg_varg(&mp_type_TypeError,
MP_ERROR_TEXT("argument should be a '%q' not a '%q'"), self->type->name, arg0_type->name);
#endif
}
}
return mp_call_function_n_kw(self->fun, n_args, n_kw, args);
}
STATIC const mp_obj_type_t mp_type_checked_fun = {
{ &mp_type_type },
.flags = MP_TYPE_FLAG_BINDS_SELF,
.name = MP_QSTR_function,
.call = checked_fun_call,
};
STATIC mp_obj_t mp_obj_new_checked_fun(const mp_obj_type_t *type, mp_obj_t fun) {
mp_obj_checked_fun_t *o = m_new_obj(mp_obj_checked_fun_t);
o->base.type = &mp_type_checked_fun;
o->type = type;
o->fun = fun;
return MP_OBJ_FROM_PTR(o);
}
#endif // MICROPY_BUILTIN_METHOD_CHECK_SELF_ARG
// Given a member that was extracted from an instance, convert it correctly
// and put the result in the dest[] array for a possible method call.
// Conversion means dealing with static/class methods, callables, and values.
// see http://docs.python.org/3/howto/descriptor.html
// and also https://mail.python.org/pipermail/python-dev/2015-March/138950.html
void mp_convert_member_lookup(mp_obj_t self, const mp_obj_type_t *type, mp_obj_t member, mp_obj_t *dest) {
if (mp_obj_is_obj(member)) {
const mp_obj_type_t *m_type = ((mp_obj_base_t *)MP_OBJ_TO_PTR(member))->type;
if (m_type->flags & MP_TYPE_FLAG_BINDS_SELF) {
// `member` is a function that binds self as its first argument.
if (m_type->flags & MP_TYPE_FLAG_BUILTIN_FUN) {
// `member` is a built-in function, which has special behaviour.
if (mp_obj_is_instance_type(type)) {
// Built-in functions on user types always behave like a staticmethod.
dest[0] = member;
}
#if MICROPY_BUILTIN_METHOD_CHECK_SELF_ARG
else if (self == MP_OBJ_NULL && type != &mp_type_object) {
// `member` is a built-in method without a first argument, so wrap
// it in a type checker that will check self when it's supplied.
// Note that object will do its own checking so shouldn't be wrapped.
dest[0] = mp_obj_new_checked_fun(type, member);
}
#endif
else {
// Return a (built-in) bound method, with self being this object.
dest[0] = member;
dest[1] = self;
}
} else {
// Return a bound method, with self being this object.
dest[0] = member;
dest[1] = self;
}
} else if (m_type == &mp_type_staticmethod) {
// `member` is a staticmethod, return the function that it wraps.
dest[0] = ((mp_obj_static_class_method_t *)MP_OBJ_TO_PTR(member))->fun;
} else if (m_type == &mp_type_classmethod) {
// `member` is a classmethod, return a bound method with self being the type of
// this object. This type should be the type of the original instance, not the
// base type (which is what is passed in the `type` argument to this function).
if (self != MP_OBJ_NULL) {
type = mp_obj_get_type(self);
}
dest[0] = ((mp_obj_static_class_method_t *)MP_OBJ_TO_PTR(member))->fun;
dest[1] = MP_OBJ_FROM_PTR(type);
} else {
// `member` is a value, so just return that value.
dest[0] = member;
}
} else {
// `member` is a value, so just return that value.
dest[0] = member;
}
}
// no attribute found, returns: dest[0] == MP_OBJ_NULL, dest[1] == MP_OBJ_NULL
// normal attribute found, returns: dest[0] == <attribute>, dest[1] == MP_OBJ_NULL
// method attribute found, returns: dest[0] == <method>, dest[1] == <self>
void mp_load_method_maybe(mp_obj_t obj, qstr attr, mp_obj_t *dest) {
// clear output to indicate no attribute/method found yet
dest[0] = MP_OBJ_NULL;
dest[1] = MP_OBJ_NULL;
// get the type
const mp_obj_type_t *type = mp_obj_get_type(obj);
// look for built-in names
#if MICROPY_CPYTHON_COMPAT
if (attr == MP_QSTR___class__) {
// a.__class__ is equivalent to type(a)
dest[0] = MP_OBJ_FROM_PTR(type);
return;
}
#endif
if (attr == MP_QSTR___next__ && type->iternext != NULL) {
dest[0] = MP_OBJ_FROM_PTR(&mp_builtin_next_obj);
dest[1] = obj;
} else if (type->attr != NULL) {
// this type can do its own load, so call it
type->attr(obj, attr, dest);
} else if (type->locals_dict != NULL) {
// generic method lookup
// this is a lookup in the object (ie not class or type)
assert(type->locals_dict->base.type == &mp_type_dict); // MicroPython restriction, for now
mp_map_t *locals_map = &type->locals_dict->map;
mp_map_elem_t *elem = mp_map_lookup(locals_map, MP_OBJ_NEW_QSTR(attr), MP_MAP_LOOKUP);
if (elem != NULL) {
mp_convert_member_lookup(obj, type, elem->value, dest);
}
}
}
void mp_load_method(mp_obj_t base, qstr attr, mp_obj_t *dest) {
DEBUG_OP_printf("load method %p.%s\n", base, qstr_str(attr));
mp_load_method_maybe(base, attr, dest);
if (dest[0] == MP_OBJ_NULL) {
// no attribute/method called attr
#if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
mp_raise_msg(&mp_type_AttributeError, MP_ERROR_TEXT("no such attribute"));
#else
// following CPython, we give a more detailed error message for type objects
if (mp_obj_is_type(base, &mp_type_type)) {
mp_raise_msg_varg(&mp_type_AttributeError,
MP_ERROR_TEXT("type object '%q' has no attribute '%q'"),
((mp_obj_type_t *)MP_OBJ_TO_PTR(base))->name, attr);
} else {
mp_raise_msg_varg(&mp_type_AttributeError,
MP_ERROR_TEXT("'%s' object has no attribute '%q'"),
mp_obj_get_type_str(base), attr);
}
#endif
}
}
// Acts like mp_load_method_maybe but catches AttributeError, and all other exceptions if requested
void mp_load_method_protected(mp_obj_t obj, qstr attr, mp_obj_t *dest, bool catch_all_exc) {
nlr_buf_t nlr;
if (nlr_push(&nlr) == 0) {
mp_load_method_maybe(obj, attr, dest);
nlr_pop();
} else {
if (!catch_all_exc
&& !mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(((mp_obj_base_t *)nlr.ret_val)->type),
MP_OBJ_FROM_PTR(&mp_type_AttributeError))) {
// Re-raise the exception
nlr_raise(MP_OBJ_FROM_PTR(nlr.ret_val));
}
}
}
void mp_store_attr(mp_obj_t base, qstr attr, mp_obj_t value) {
DEBUG_OP_printf("store attr %p.%s <- %p\n", base, qstr_str(attr), value);
const mp_obj_type_t *type = mp_obj_get_type(base);
if (type->attr != NULL) {
mp_obj_t dest[2] = {MP_OBJ_SENTINEL, value};
type->attr(base, attr, dest);
if (dest[0] == MP_OBJ_NULL) {
// success
return;
}
}
#if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
mp_raise_msg(&mp_type_AttributeError, MP_ERROR_TEXT("no such attribute"));
#else
mp_raise_msg_varg(&mp_type_AttributeError,
MP_ERROR_TEXT("'%s' object has no attribute '%q'"),
mp_obj_get_type_str(base), attr);
#endif
}
mp_obj_t mp_getiter(mp_obj_t o_in, mp_obj_iter_buf_t *iter_buf) {
assert(o_in);
const mp_obj_type_t *type = mp_obj_get_type(o_in);
// Check for native getiter which is the identity. We handle this case explicitly
// so we don't unnecessarily allocate any RAM for the iter_buf, which won't be used.
if (type->getiter == mp_identity_getiter) {
return o_in;
}
// check for native getiter (corresponds to __iter__)
if (type->getiter != NULL) {
if (iter_buf == NULL && type->getiter != mp_obj_instance_getiter) {
// if caller did not provide a buffer then allocate one on the heap
// mp_obj_instance_getiter is special, it will allocate only if needed
iter_buf = m_new_obj(mp_obj_iter_buf_t);
}
mp_obj_t iter = type->getiter(o_in, iter_buf);
if (iter != MP_OBJ_NULL) {
return iter;
}
}
// check for __getitem__
mp_obj_t dest[2];
mp_load_method_maybe(o_in, MP_QSTR___getitem__, dest);
if (dest[0] != MP_OBJ_NULL) {
// __getitem__ exists, create and return an iterator
if (iter_buf == NULL) {
// if caller did not provide a buffer then allocate one on the heap
iter_buf = m_new_obj(mp_obj_iter_buf_t);
}
return mp_obj_new_getitem_iter(dest, iter_buf);
}
// object not iterable
#if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
mp_raise_TypeError(MP_ERROR_TEXT("object not iterable"));
#else
mp_raise_msg_varg(&mp_type_TypeError,
MP_ERROR_TEXT("'%s' object isn't iterable"), mp_obj_get_type_str(o_in));
#endif
}
// may return MP_OBJ_STOP_ITERATION as an optimisation instead of raise StopIteration()
// may also raise StopIteration()
mp_obj_t mp_iternext_allow_raise(mp_obj_t o_in) {
const mp_obj_type_t *type = mp_obj_get_type(o_in);
if (type->iternext != NULL) {
MP_STATE_THREAD(stop_iteration_arg) = MP_OBJ_NULL;
return type->iternext(o_in);
} else {
// check for __next__ method
mp_obj_t dest[2];
mp_load_method_maybe(o_in, MP_QSTR___next__, dest);
if (dest[0] != MP_OBJ_NULL) {
// __next__ exists, call it and return its result
return mp_call_method_n_kw(0, 0, dest);
} else {
#if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
mp_raise_TypeError(MP_ERROR_TEXT("object not an iterator"));
#else
mp_raise_msg_varg(&mp_type_TypeError,
MP_ERROR_TEXT("'%s' object isn't an iterator"), mp_obj_get_type_str(o_in));
#endif
}
}
}
// will always return MP_OBJ_STOP_ITERATION instead of raising StopIteration() (or any subclass thereof)
// may raise other exceptions
mp_obj_t mp_iternext(mp_obj_t o_in) {
MP_STACK_CHECK(); // enumerate, filter, map and zip can recursively call mp_iternext
const mp_obj_type_t *type = mp_obj_get_type(o_in);
if (type->iternext != NULL) {
MP_STATE_THREAD(stop_iteration_arg) = MP_OBJ_NULL;
return type->iternext(o_in);
} else {
// check for __next__ method
mp_obj_t dest[2];
mp_load_method_maybe(o_in, MP_QSTR___next__, dest);
if (dest[0] != MP_OBJ_NULL) {
// __next__ exists, call it and return its result
nlr_buf_t nlr;
if (nlr_push(&nlr) == 0) {
mp_obj_t ret = mp_call_method_n_kw(0, 0, dest);
nlr_pop();
return ret;
} else {
if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(((mp_obj_base_t *)nlr.ret_val)->type), MP_OBJ_FROM_PTR(&mp_type_StopIteration))) {
return mp_make_stop_iteration(mp_obj_exception_get_value(MP_OBJ_FROM_PTR(nlr.ret_val)));
} else {
nlr_jump(nlr.ret_val);
}
}
} else {
#if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
mp_raise_TypeError(MP_ERROR_TEXT("object not an iterator"));
#else
mp_raise_msg_varg(&mp_type_TypeError,
MP_ERROR_TEXT("'%s' object isn't an iterator"), mp_obj_get_type_str(o_in));
#endif
}
}
}
mp_vm_return_kind_t mp_resume(mp_obj_t self_in, mp_obj_t send_value, mp_obj_t throw_value, mp_obj_t *ret_val) {
assert((send_value != MP_OBJ_NULL) ^ (throw_value != MP_OBJ_NULL));
const mp_obj_type_t *type = mp_obj_get_type(self_in);
if (type == &mp_type_gen_instance) {
return mp_obj_gen_resume(self_in, send_value, throw_value, ret_val);
}
if (type->iternext != NULL && send_value == mp_const_none) {
MP_STATE_THREAD(stop_iteration_arg) = MP_OBJ_NULL;
mp_obj_t ret = type->iternext(self_in);
*ret_val = ret;
if (ret != MP_OBJ_STOP_ITERATION) {
return MP_VM_RETURN_YIELD;
} else {
// The generator is finished.
// This is an optimised "raise StopIteration(*ret_val)".
*ret_val = MP_STATE_THREAD(stop_iteration_arg);
if (*ret_val == MP_OBJ_NULL) {
*ret_val = mp_const_none;
}
return MP_VM_RETURN_NORMAL;
}
}
mp_obj_t dest[3]; // Reserve slot for send() arg
// Python instance iterator protocol
if (send_value == mp_const_none) {
mp_load_method_maybe(self_in, MP_QSTR___next__, dest);
if (dest[0] != MP_OBJ_NULL) {
*ret_val = mp_call_method_n_kw(0, 0, dest);
return MP_VM_RETURN_YIELD;
}
}
// Either python instance generator protocol, or native object
// generator protocol.
if (send_value != MP_OBJ_NULL) {
mp_load_method(self_in, MP_QSTR_send, dest);
dest[2] = send_value;
*ret_val = mp_call_method_n_kw(1, 0, dest);
return MP_VM_RETURN_YIELD;
}
assert(throw_value != MP_OBJ_NULL);
{
if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(mp_obj_get_type(throw_value)), MP_OBJ_FROM_PTR(&mp_type_GeneratorExit))) {
mp_load_method_maybe(self_in, MP_QSTR_close, dest);
if (dest[0] != MP_OBJ_NULL) {
// TODO: Exceptions raised in close() are not propagated,
// printed to sys.stderr
*ret_val = mp_call_method_n_kw(0, 0, dest);
// We assume one can't "yield" from close()
return MP_VM_RETURN_NORMAL;
}
} else {
mp_load_method_maybe(self_in, MP_QSTR_throw, dest);
if (dest[0] != MP_OBJ_NULL) {
dest[2] = throw_value;
*ret_val = mp_call_method_n_kw(1, 0, dest);
// If .throw() method returned, we assume it's value to yield
// - any exception would be thrown with nlr_raise().
return MP_VM_RETURN_YIELD;
}
}
// If there's nowhere to throw exception into, then we assume that object
// is just incapable to handle it, so any exception thrown into it
// will be propagated up. This behavior is approved by test_pep380.py
// test_delegation_of_close_to_non_generator(),
// test_delegating_throw_to_non_generator()
if (mp_obj_exception_match(throw_value, MP_OBJ_FROM_PTR(&mp_type_StopIteration))) {
// PEP479: if StopIteration is raised inside a generator it is replaced with RuntimeError
*ret_val = mp_obj_new_exception_msg(&mp_type_RuntimeError, MP_ERROR_TEXT("generator raised StopIteration"));
} else {
*ret_val = mp_make_raise_obj(throw_value);
}
return MP_VM_RETURN_EXCEPTION;
}
}
mp_obj_t mp_make_raise_obj(mp_obj_t o) {
DEBUG_printf("raise %p\n", o);
if (mp_obj_is_exception_type(o)) {
// o is an exception type (it is derived from BaseException (or is BaseException))
// create and return a new exception instance by calling o
// TODO could have an option to disable traceback, then builtin exceptions (eg TypeError)
// could have const instances in ROM which we return here instead
return mp_call_function_n_kw(o, 0, 0, NULL);
} else if (mp_obj_is_exception_instance(o)) {
// o is an instance of an exception, so use it as the exception
return o;
} else {
// o cannot be used as an exception, so return a type error (which will be raised by the caller)
return mp_obj_new_exception_msg(&mp_type_TypeError, MP_ERROR_TEXT("exceptions must derive from BaseException"));
}
}
mp_obj_t mp_import_name(qstr name, mp_obj_t fromlist, mp_obj_t level) {
DEBUG_printf("import name '%s' level=%d\n", qstr_str(name), MP_OBJ_SMALL_INT_VALUE(level));
// build args array
mp_obj_t args[5];
args[0] = MP_OBJ_NEW_QSTR(name);
args[1] = mp_const_none; // TODO should be globals
args[2] = mp_const_none; // TODO should be locals
args[3] = fromlist;
args[4] = level;
#if MICROPY_CAN_OVERRIDE_BUILTINS
// Lookup __import__ and call that if it exists
mp_obj_dict_t *bo_dict = MP_STATE_VM(mp_module_builtins_override_dict);
if (bo_dict != NULL) {
mp_map_elem_t *import = mp_map_lookup(&bo_dict->map, MP_OBJ_NEW_QSTR(MP_QSTR___import__), MP_MAP_LOOKUP);
if (import != NULL) {
return mp_call_function_n_kw(import->value, 5, 0, args);
}
}
#endif
return mp_builtin___import__(5, args);
}
mp_obj_t mp_import_from(mp_obj_t module, qstr name) {
DEBUG_printf("import from %p %s\n", module, qstr_str(name));
mp_obj_t dest[2];
mp_load_method_maybe(module, name, dest);
if (dest[1] != MP_OBJ_NULL) {
// Hopefully we can't import bound method from an object
import_error:
mp_raise_msg_varg(&mp_type_ImportError, MP_ERROR_TEXT("can't import name %q"), name);
}
if (dest[0] != MP_OBJ_NULL) {
return dest[0];
}
#if MICROPY_ENABLE_EXTERNAL_IMPORT
// See if it's a package, then can try FS import
if (!mp_obj_is_package(module)) {
goto import_error;
}
mp_load_method_maybe(module, MP_QSTR___name__, dest);
size_t pkg_name_len;
const char *pkg_name = mp_obj_str_get_data(dest[0], &pkg_name_len);
const uint dot_name_len = pkg_name_len + 1 + qstr_len(name);
char *dot_name = mp_local_alloc(dot_name_len);
memcpy(dot_name, pkg_name, pkg_name_len);
dot_name[pkg_name_len] = '.';
memcpy(dot_name + pkg_name_len + 1, qstr_str(name), qstr_len(name));
qstr dot_name_q = qstr_from_strn(dot_name, dot_name_len);
mp_local_free(dot_name);
// For fromlist, pass sentinel "non empty" value to force returning of leaf module
return mp_import_name(dot_name_q, mp_const_true, MP_OBJ_NEW_SMALL_INT(0));
#else
// Package import not supported with external imports disabled
goto import_error;
#endif
}
void mp_import_all(mp_obj_t module) {
DEBUG_printf("import all %p\n", module);
// TODO: Support __all__
mp_map_t *map = &mp_obj_module_get_globals(module)->map;
for (size_t i = 0; i < map->alloc; i++) {
if (mp_map_slot_is_filled(map, i)) {
// Entry in module global scope may be generated programmatically
// (and thus be not a qstr for longer names). Avoid turning it in
// qstr if it has '_' and was used exactly to save memory.
const char *name = mp_obj_str_get_str(map->table[i].key);
if (*name != '_') {
qstr qname = mp_obj_str_get_qstr(map->table[i].key);
mp_store_name(qname, map->table[i].value);
}
}
}
}
#if MICROPY_ENABLE_COMPILER
mp_obj_t mp_parse_compile_execute(mp_lexer_t *lex, mp_parse_input_kind_t parse_input_kind, mp_obj_dict_t *globals, mp_obj_dict_t *locals) {
// save context
mp_obj_dict_t *volatile old_globals = mp_globals_get();
mp_obj_dict_t *volatile old_locals = mp_locals_get();
// set new context
mp_globals_set(globals);
mp_locals_set(locals);
nlr_buf_t nlr;
if (nlr_push(&nlr) == 0) {
qstr source_name = lex->source_name;
mp_parse_tree_t parse_tree = mp_parse(lex, parse_input_kind);
mp_obj_t module_fun = mp_compile(&parse_tree, source_name, parse_input_kind == MP_PARSE_SINGLE_INPUT);
mp_obj_t ret;
if (MICROPY_PY_BUILTINS_COMPILE && globals == NULL) {
// for compile only, return value is the module function
ret = module_fun;
} else {
// execute module function and get return value
ret = mp_call_function_0(module_fun);
}
// finish nlr block, restore context and return value
nlr_pop();
mp_globals_set(old_globals);
mp_locals_set(old_locals);
return ret;
} else {
// exception; restore context and re-raise same exception
mp_globals_set(old_globals);
mp_locals_set(old_locals);
nlr_jump(nlr.ret_val);
}
}
#endif // MICROPY_ENABLE_COMPILER
NORETURN void m_malloc_fail(size_t num_bytes) {
DEBUG_printf("memory allocation failed, allocating %u bytes\n", (uint)num_bytes);
#if MICROPY_ENABLE_GC
if (gc_is_locked()) {
mp_raise_msg(&mp_type_MemoryError, MP_ERROR_TEXT("memory allocation failed, heap is locked"));
}
#endif
mp_raise_msg_varg(&mp_type_MemoryError,
MP_ERROR_TEXT("memory allocation failed, allocating %u bytes"), (uint)num_bytes);
}
#if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_NONE
NORETURN void mp_raise_type(const mp_obj_type_t *exc_type) {
nlr_raise(mp_obj_new_exception(exc_type));
}
NORETURN void mp_raise_ValueError_no_msg(void) {
mp_raise_type(&mp_type_ValueError);
}
NORETURN void mp_raise_TypeError_no_msg(void) {
mp_raise_type(&mp_type_TypeError);
}
NORETURN void mp_raise_NotImplementedError_no_msg(void) {
mp_raise_type(&mp_type_NotImplementedError);
}
#else
NORETURN void mp_raise_msg(const mp_obj_type_t *exc_type, mp_rom_error_text_t msg) {
if (msg == NULL) {
nlr_raise(mp_obj_new_exception(exc_type));
} else {
nlr_raise(mp_obj_new_exception_msg(exc_type, msg));
}
}
NORETURN void mp_raise_msg_varg(const mp_obj_type_t *exc_type, mp_rom_error_text_t fmt, ...) {
va_list args;
va_start(args, fmt);
mp_obj_t exc = mp_obj_new_exception_msg_vlist(exc_type, fmt, args);
va_end(args);
nlr_raise(exc);
}
NORETURN void mp_raise_ValueError(mp_rom_error_text_t msg) {
mp_raise_msg(&mp_type_ValueError, msg);
}
NORETURN void mp_raise_TypeError(mp_rom_error_text_t msg) {
mp_raise_msg(&mp_type_TypeError, msg);
}
NORETURN void mp_raise_NotImplementedError(mp_rom_error_text_t msg) {
mp_raise_msg(&mp_type_NotImplementedError, msg);
}
#endif
NORETURN void mp_raise_type_arg(const mp_obj_type_t *exc_type, mp_obj_t arg) {
nlr_raise(mp_obj_new_exception_arg1(exc_type, arg));
}
NORETURN void mp_raise_StopIteration(mp_obj_t arg) {
if (arg == MP_OBJ_NULL) {
mp_raise_type(&mp_type_StopIteration);
} else {
mp_raise_type_arg(&mp_type_StopIteration, arg);
}
}
NORETURN void mp_raise_OSError(int errno_) {
mp_raise_type_arg(&mp_type_OSError, MP_OBJ_NEW_SMALL_INT(errno_));
}
#if MICROPY_STACK_CHECK || MICROPY_ENABLE_PYSTACK
NORETURN void mp_raise_recursion_depth(void) {
mp_raise_type_arg(&mp_type_RuntimeError, MP_OBJ_NEW_QSTR(MP_QSTR_maximum_space_recursion_space_depth_space_exceeded));
}
#endif
| YifuLiu/AliOS-Things | components/py_engine/engine/py/runtime.c | C | apache-2.0 | 61,759 |
/*
* 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.
*/
#ifndef MICROPY_INCLUDED_PY_RUNTIME_H
#define MICROPY_INCLUDED_PY_RUNTIME_H
#include "py/mpstate.h"
#include "py/pystack.h"
typedef enum {
MP_VM_RETURN_NORMAL,
MP_VM_RETURN_YIELD,
MP_VM_RETURN_EXCEPTION,
} mp_vm_return_kind_t;
typedef enum {
MP_ARG_BOOL = 0x001,
MP_ARG_INT = 0x002,
MP_ARG_OBJ = 0x003,
MP_ARG_KIND_MASK = 0x0ff,
MP_ARG_REQUIRED = 0x100,
MP_ARG_KW_ONLY = 0x200,
} mp_arg_flag_t;
typedef union _mp_arg_val_t {
bool u_bool;
mp_int_t u_int;
mp_obj_t u_obj;
mp_rom_obj_t u_rom_obj;
} mp_arg_val_t;
typedef struct _mp_arg_t {
uint16_t qst;
uint16_t flags;
mp_arg_val_t defval;
} mp_arg_t;
#if MP_SCHED_CALLBACK_ARGS_LoBo
#if MICROPY_ENABLE_SCHEDULER
#define MP_SCHED_CTYPE_MAX_ITEMS 8
#define MP_SCHED_CTYPE_NONE 0
#define MP_SCHED_CTYPE_SINGLE 1
#define MP_SCHED_CTYPE_TUPLE 2
#define MP_SCHED_CTYPE_DICT 3
#define MP_SCHED_ENTRY_TYPE_NONE 0
#define MP_SCHED_ENTRY_TYPE_INT 1
#define MP_SCHED_ENTRY_TYPE_BOOL 2
#define MP_SCHED_ENTRY_TYPE_FLOAT 3
#define MP_SCHED_ENTRY_TYPE_STR 4
#define MP_SCHED_ENTRY_TYPE_BYTES 5
#define MP_SCHED_ENTRY_TYPE_CARG 6
typedef struct _mp_sched_carg_t {
uint8_t type;
uint8_t n;
void *entry[MP_SCHED_CTYPE_MAX_ITEMS];
} mp_sched_carg_t;
typedef struct _mp_sched_carg_entry_t {
uint8_t type;
int ival;
float fval;
uint8_t *sval;
char key[16];
mp_sched_carg_t *carg;
} mp_sched_carg_entry_t;
#endif
#endif
// Tables mapping operator enums to qstrs, defined in objtype.c
extern const byte mp_unary_op_method_name[];
extern const byte mp_binary_op_method_name[];
void mp_init(void);
void mp_deinit(void);
void mp_sched_exception(mp_obj_t exc);
void mp_sched_keyboard_interrupt(void);
void mp_handle_pending(bool raise_exc);
void mp_handle_pending_tail(mp_uint_t atomic_state);
#if MICROPY_ENABLE_SCHEDULER
void mp_sched_lock(void);
void mp_sched_unlock(void);
#define mp_sched_num_pending() (MP_STATE_VM(sched_len))
bool mp_sched_schedule(mp_obj_t function, mp_obj_t arg);
bool mp_sched_schedule_LoBo(mp_obj_t function, mp_obj_t arg, void *carg);
void free_carg(mp_sched_carg_t *carg);
mp_sched_carg_t *make_carg_entry(mp_sched_carg_t *carg, int idx, uint8_t type, int val, const uint8_t *sval, const char *key);
mp_sched_carg_t *make_cargs(int type);
mp_sched_carg_t *make_carg_entry_carg(mp_sched_carg_t *carg, int idx, mp_sched_carg_t *darg);
#endif
// extra printing method specifically for mp_obj_t's which are integral type
int mp_print_mp_int(const mp_print_t *print, mp_obj_t x, int base, int base_char, int flags, char fill, int width, int prec);
void mp_arg_check_num_sig(size_t n_args, size_t n_kw, uint32_t sig);
static inline void mp_arg_check_num(size_t n_args, size_t n_kw, size_t n_args_min, size_t n_args_max, bool takes_kw) {
mp_arg_check_num_sig(n_args, n_kw, MP_OBJ_FUN_MAKE_SIG(n_args_min, n_args_max, takes_kw));
}
void mp_arg_parse_all(size_t n_pos, const mp_obj_t *pos, mp_map_t *kws, size_t n_allowed, const mp_arg_t *allowed, mp_arg_val_t *out_vals);
void mp_arg_parse_all_kw_array(size_t n_pos, size_t n_kw, const mp_obj_t *args, size_t n_allowed, const mp_arg_t *allowed, mp_arg_val_t *out_vals);
NORETURN void mp_arg_error_terse_mismatch(void);
NORETURN void mp_arg_error_unimpl_kw(void);
static inline mp_obj_dict_t *mp_locals_get(void) {
return MP_STATE_THREAD(dict_locals);
}
static inline void mp_locals_set(mp_obj_dict_t *d) {
MP_STATE_THREAD(dict_locals) = d;
}
static inline mp_obj_dict_t *mp_globals_get(void) {
return MP_STATE_THREAD(dict_globals);
}
static inline void mp_globals_set(mp_obj_dict_t *d) {
MP_STATE_THREAD(dict_globals) = d;
}
mp_obj_t mp_load_name(qstr qst);
mp_obj_t mp_load_global(qstr qst);
mp_obj_t mp_load_build_class(void);
void mp_store_name(qstr qst, mp_obj_t obj);
void mp_store_global(qstr qst, mp_obj_t obj);
void mp_delete_name(qstr qst);
void mp_delete_global(qstr qst);
mp_obj_t mp_unary_op(mp_unary_op_t op, mp_obj_t arg);
mp_obj_t mp_binary_op(mp_binary_op_t op, mp_obj_t lhs, mp_obj_t rhs);
mp_obj_t mp_call_function_0(mp_obj_t fun);
mp_obj_t mp_call_function_1(mp_obj_t fun, mp_obj_t arg);
mp_obj_t mp_call_function_2(mp_obj_t fun, mp_obj_t arg1, mp_obj_t arg2);
mp_obj_t mp_call_function_n_kw(mp_obj_t fun, size_t n_args, size_t n_kw, const mp_obj_t *args);
mp_obj_t mp_call_method_n_kw(size_t n_args, size_t n_kw, const mp_obj_t *args);
mp_obj_t mp_call_method_n_kw_var(bool have_self, size_t n_args_n_kw, const mp_obj_t *args);
mp_obj_t mp_call_method_self_n_kw(mp_obj_t meth, mp_obj_t self, size_t n_args, size_t n_kw, const mp_obj_t *args);
// Call function and catch/dump exception - for Python callbacks from C code
// (return MP_OBJ_NULL in case of exception).
mp_obj_t mp_call_function_1_protected(mp_obj_t fun, mp_obj_t arg);
mp_obj_t mp_call_function_2_protected(mp_obj_t fun, mp_obj_t arg1, mp_obj_t arg2);
typedef struct _mp_call_args_t {
mp_obj_t fun;
size_t n_args, n_kw, n_alloc;
mp_obj_t *args;
} mp_call_args_t;
#if MICROPY_STACKLESS
// Takes arguments which are the most general mix of Python arg types, and
// prepares argument array suitable for passing to ->call() method of a
// function object (and mp_call_function_n_kw()).
// (Only needed in stackless mode.)
void mp_call_prepare_args_n_kw_var(bool have_self, size_t n_args_n_kw, const mp_obj_t *args, mp_call_args_t *out_args);
#endif
void mp_unpack_sequence(mp_obj_t seq, size_t num, mp_obj_t *items);
void mp_unpack_ex(mp_obj_t seq, size_t num, mp_obj_t *items);
mp_obj_t mp_store_map(mp_obj_t map, mp_obj_t key, mp_obj_t value);
mp_obj_t mp_load_attr(mp_obj_t base, qstr attr);
void mp_convert_member_lookup(mp_obj_t obj, const mp_obj_type_t *type, mp_obj_t member, mp_obj_t *dest);
void mp_load_method(mp_obj_t base, qstr attr, mp_obj_t *dest);
void mp_load_method_maybe(mp_obj_t base, qstr attr, mp_obj_t *dest);
void mp_load_method_protected(mp_obj_t obj, qstr attr, mp_obj_t *dest, bool catch_all_exc);
void mp_load_super_method(qstr attr, mp_obj_t *dest);
void mp_store_attr(mp_obj_t base, qstr attr, mp_obj_t val);
mp_obj_t mp_getiter(mp_obj_t o, mp_obj_iter_buf_t *iter_buf);
mp_obj_t mp_iternext_allow_raise(mp_obj_t o); // may return MP_OBJ_STOP_ITERATION instead of raising StopIteration()
mp_obj_t mp_iternext(mp_obj_t o); // will always return MP_OBJ_STOP_ITERATION instead of raising StopIteration(...)
mp_vm_return_kind_t mp_resume(mp_obj_t self_in, mp_obj_t send_value, mp_obj_t throw_value, mp_obj_t *ret_val);
static inline mp_obj_t mp_make_stop_iteration(mp_obj_t o) {
MP_STATE_THREAD(stop_iteration_arg) = o;
return MP_OBJ_STOP_ITERATION;
}
mp_obj_t mp_make_raise_obj(mp_obj_t o);
mp_obj_t mp_import_name(qstr name, mp_obj_t fromlist, mp_obj_t level);
mp_obj_t mp_import_from(mp_obj_t module, qstr name);
void mp_import_all(mp_obj_t module);
#if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_NONE
NORETURN void mp_raise_type(const mp_obj_type_t *exc_type);
NORETURN void mp_raise_ValueError_no_msg(void);
NORETURN void mp_raise_TypeError_no_msg(void);
NORETURN void mp_raise_NotImplementedError_no_msg(void);
#define mp_raise_msg(exc_type, msg) mp_raise_type(exc_type)
#define mp_raise_msg_varg(exc_type, ...) mp_raise_type(exc_type)
#define mp_raise_ValueError(msg) mp_raise_ValueError_no_msg()
#define mp_raise_TypeError(msg) mp_raise_TypeError_no_msg()
#define mp_raise_NotImplementedError(msg) mp_raise_NotImplementedError_no_msg()
#else
#define mp_raise_type(exc_type) mp_raise_msg(exc_type, NULL)
NORETURN void mp_raise_msg(const mp_obj_type_t *exc_type, mp_rom_error_text_t msg);
NORETURN void mp_raise_msg_varg(const mp_obj_type_t *exc_type, mp_rom_error_text_t fmt, ...);
NORETURN void mp_raise_ValueError(mp_rom_error_text_t msg);
NORETURN void mp_raise_TypeError(mp_rom_error_text_t msg);
NORETURN void mp_raise_NotImplementedError(mp_rom_error_text_t msg);
#endif
NORETURN void mp_raise_type_arg(const mp_obj_type_t *exc_type, mp_obj_t arg);
NORETURN void mp_raise_StopIteration(mp_obj_t arg);
NORETURN void mp_raise_OSError(int errno_);
NORETURN void mp_raise_recursion_depth(void);
#if MICROPY_BUILTIN_METHOD_CHECK_SELF_ARG
#undef mp_check_self
#define mp_check_self(pred)
#else
// A port may define to raise TypeError for example
#ifndef mp_check_self
#define mp_check_self(pred) assert(pred)
#endif
#endif
// helper functions for native/viper code
int mp_native_type_from_qstr(qstr qst);
mp_uint_t mp_native_from_obj(mp_obj_t obj, mp_uint_t type);
mp_obj_t mp_native_to_obj(mp_uint_t val, mp_uint_t type);
#define mp_sys_path (MP_OBJ_FROM_PTR(&MP_STATE_VM(mp_sys_path_obj)))
#define mp_sys_argv (MP_OBJ_FROM_PTR(&MP_STATE_VM(mp_sys_argv_obj)))
#if MICROPY_WARNINGS
#ifndef mp_warning
void mp_warning(const char *category, const char *msg, ...);
#endif
#else
#define mp_warning(...)
#endif
#endif // MICROPY_INCLUDED_PY_RUNTIME_H
| YifuLiu/AliOS-Things | components/py_engine/engine/py/runtime.h | C | apache-2.0 | 10,118 |
/*
* 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.
*/
#ifndef MICROPY_INCLUDED_PY_RUNTIME0_H
#define MICROPY_INCLUDED_PY_RUNTIME0_H
// The first four must fit in 8 bits, see emitbc.c
// The remaining must fit in 16 bits, see scope.h
#define MP_SCOPE_FLAG_ALL_SIG (0x0f)
#define MP_SCOPE_FLAG_GENERATOR (0x01)
#define MP_SCOPE_FLAG_VARKEYWORDS (0x02)
#define MP_SCOPE_FLAG_VARARGS (0x04)
#define MP_SCOPE_FLAG_DEFKWARGS (0x08)
#define MP_SCOPE_FLAG_REFGLOBALS (0x10) // used only if native emitter enabled
#define MP_SCOPE_FLAG_HASCONSTS (0x20) // used only if native emitter enabled
#define MP_SCOPE_FLAG_VIPERRET_POS (6) // 3 bits used for viper return type, to pass from compiler to native emitter
#define MP_SCOPE_FLAG_VIPERRELOC (0x10) // used only when loading viper from .mpy
#define MP_SCOPE_FLAG_VIPERRODATA (0x20) // used only when loading viper from .mpy
#define MP_SCOPE_FLAG_VIPERBSS (0x40) // used only when loading viper from .mpy
// types for native (viper) function signature
#define MP_NATIVE_TYPE_OBJ (0x00)
#define MP_NATIVE_TYPE_BOOL (0x01)
#define MP_NATIVE_TYPE_INT (0x02)
#define MP_NATIVE_TYPE_UINT (0x03)
#define MP_NATIVE_TYPE_PTR (0x04)
#define MP_NATIVE_TYPE_PTR8 (0x05)
#define MP_NATIVE_TYPE_PTR16 (0x06)
#define MP_NATIVE_TYPE_PTR32 (0x07)
// Bytecode and runtime boundaries for unary ops
#define MP_UNARY_OP_NUM_BYTECODE (MP_UNARY_OP_NOT + 1)
#define MP_UNARY_OP_NUM_RUNTIME (MP_UNARY_OP_SIZEOF + 1)
// Bytecode and runtime boundaries for binary ops
#define MP_BINARY_OP_NUM_BYTECODE (MP_BINARY_OP_POWER + 1)
#if MICROPY_PY_REVERSE_SPECIAL_METHODS
#define MP_BINARY_OP_NUM_RUNTIME (MP_BINARY_OP_REVERSE_POWER + 1)
#else
#define MP_BINARY_OP_NUM_RUNTIME (MP_BINARY_OP_CONTAINS + 1)
#endif
typedef enum {
// These ops may appear in the bytecode. Changing this group
// in any way requires changing the bytecode version.
MP_UNARY_OP_POSITIVE,
MP_UNARY_OP_NEGATIVE,
MP_UNARY_OP_INVERT,
MP_UNARY_OP_NOT,
// Following ops cannot appear in the bytecode
MP_UNARY_OP_BOOL, // __bool__
MP_UNARY_OP_LEN, // __len__
MP_UNARY_OP_HASH, // __hash__; must return a small int
MP_UNARY_OP_ABS, // __abs__
MP_UNARY_OP_INT, // __int__
MP_UNARY_OP_SIZEOF, // for sys.getsizeof()
} mp_unary_op_t;
typedef enum {
// The following 9+13+13 ops are used in bytecode and changing
// them requires changing the bytecode version.
// 9 relational operations, should return a bool; order of first 6 matches corresponding mp_token_kind_t
MP_BINARY_OP_LESS,
MP_BINARY_OP_MORE,
MP_BINARY_OP_EQUAL,
MP_BINARY_OP_LESS_EQUAL,
MP_BINARY_OP_MORE_EQUAL,
MP_BINARY_OP_NOT_EQUAL,
MP_BINARY_OP_IN,
MP_BINARY_OP_IS,
MP_BINARY_OP_EXCEPTION_MATCH,
// 13 inplace arithmetic operations; order matches corresponding mp_token_kind_t
MP_BINARY_OP_INPLACE_OR,
MP_BINARY_OP_INPLACE_XOR,
MP_BINARY_OP_INPLACE_AND,
MP_BINARY_OP_INPLACE_LSHIFT,
MP_BINARY_OP_INPLACE_RSHIFT,
MP_BINARY_OP_INPLACE_ADD,
MP_BINARY_OP_INPLACE_SUBTRACT,
MP_BINARY_OP_INPLACE_MULTIPLY,
MP_BINARY_OP_INPLACE_MAT_MULTIPLY,
MP_BINARY_OP_INPLACE_FLOOR_DIVIDE,
MP_BINARY_OP_INPLACE_TRUE_DIVIDE,
MP_BINARY_OP_INPLACE_MODULO,
MP_BINARY_OP_INPLACE_POWER,
// 13 normal arithmetic operations; order matches corresponding mp_token_kind_t
MP_BINARY_OP_OR,
MP_BINARY_OP_XOR,
MP_BINARY_OP_AND,
MP_BINARY_OP_LSHIFT,
MP_BINARY_OP_RSHIFT,
MP_BINARY_OP_ADD,
MP_BINARY_OP_SUBTRACT,
MP_BINARY_OP_MULTIPLY,
MP_BINARY_OP_MAT_MULTIPLY,
MP_BINARY_OP_FLOOR_DIVIDE,
MP_BINARY_OP_TRUE_DIVIDE,
MP_BINARY_OP_MODULO,
MP_BINARY_OP_POWER,
// Operations below this line don't appear in bytecode, they
// just identify special methods.
// This is not emitted by the compiler but is supported by the runtime.
// It must follow immediately after MP_BINARY_OP_POWER.
MP_BINARY_OP_DIVMOD,
// The runtime will convert MP_BINARY_OP_IN to this operator with swapped args.
// A type should implement this containment operator instead of MP_BINARY_OP_IN.
MP_BINARY_OP_CONTAINS,
// 13 MP_BINARY_OP_REVERSE_* operations must be in the same order as MP_BINARY_OP_*,
// and be the last ones supported by the runtime.
MP_BINARY_OP_REVERSE_OR,
MP_BINARY_OP_REVERSE_XOR,
MP_BINARY_OP_REVERSE_AND,
MP_BINARY_OP_REVERSE_LSHIFT,
MP_BINARY_OP_REVERSE_RSHIFT,
MP_BINARY_OP_REVERSE_ADD,
MP_BINARY_OP_REVERSE_SUBTRACT,
MP_BINARY_OP_REVERSE_MULTIPLY,
MP_BINARY_OP_REVERSE_MAT_MULTIPLY,
MP_BINARY_OP_REVERSE_FLOOR_DIVIDE,
MP_BINARY_OP_REVERSE_TRUE_DIVIDE,
MP_BINARY_OP_REVERSE_MODULO,
MP_BINARY_OP_REVERSE_POWER,
// These 2 are not supported by the runtime and must be synthesised by the emitter
MP_BINARY_OP_NOT_IN,
MP_BINARY_OP_IS_NOT,
} mp_binary_op_t;
#endif // MICROPY_INCLUDED_PY_RUNTIME0_H
| YifuLiu/AliOS-Things | components/py_engine/engine/py/runtime0.h | C | apache-2.0 | 6,149 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2015 Josef Gajdusek
* Copyright (c) 2015 Paul Sokolovsky
*
* 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 "py/runtime.h"
mp_obj_t mp_call_function_1_protected(mp_obj_t fun, mp_obj_t arg) {
nlr_buf_t nlr;
if (nlr_push(&nlr) == 0) {
mp_obj_t ret = mp_call_function_1(fun, arg);
nlr_pop();
return ret;
} else {
mp_obj_print_exception(&mp_plat_print, MP_OBJ_FROM_PTR(nlr.ret_val));
return MP_OBJ_NULL;
}
}
mp_obj_t mp_call_function_2_protected(mp_obj_t fun, mp_obj_t arg1, mp_obj_t arg2) {
nlr_buf_t nlr;
if (nlr_push(&nlr) == 0) {
mp_obj_t ret = mp_call_function_2(fun, arg1, arg2);
nlr_pop();
return ret;
} else {
mp_obj_print_exception(&mp_plat_print, MP_OBJ_FROM_PTR(nlr.ret_val));
return MP_OBJ_NULL;
}
}
| YifuLiu/AliOS-Things | components/py_engine/engine/py/runtime_utils.c | C | apache-2.0 | 1,985 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2017 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 <stdio.h>
#include "py/runtime.h"
// Schedules an exception on the main thread (for exceptions "thrown" by async
// sources such as interrupts and UNIX signal handlers).
void MICROPY_WRAP_MP_SCHED_EXCEPTION(mp_sched_exception)(mp_obj_t exc) {
MP_STATE_MAIN_THREAD(mp_pending_exception) = exc;
#if MICROPY_ENABLE_SCHEDULER
if (MP_STATE_VM(sched_state) == MP_SCHED_IDLE) {
MP_STATE_VM(sched_state) = MP_SCHED_PENDING;
}
#endif
}
#if MICROPY_KBD_EXCEPTION
// This function may be called asynchronously at any time so only do the bare minimum.
void MICROPY_WRAP_MP_SCHED_KEYBOARD_INTERRUPT(mp_sched_keyboard_interrupt)(void) {
MP_STATE_VM(mp_kbd_exception).traceback_data = NULL;
mp_sched_exception(MP_OBJ_FROM_PTR(&MP_STATE_VM(mp_kbd_exception)));
}
#endif
#if MICROPY_ENABLE_SCHEDULER
#if MP_SCHED_CALLBACK_ARGS_LoBo
#define FREE_CBOBJECT_AFTER (0)
#define MAX_CB_OBJECTS (64)
#if FREE_CBOBJECT_AFTER
static mp_obj_t cb_objects[MAX_CB_OBJECTS];
#endif
#endif
#define IDX_MASK(i) ((i) & (MICROPY_SCHEDULER_DEPTH - 1))
// This is a macro so it is guaranteed to be inlined in functions like
// mp_sched_schedule that may be located in a special memory region.
#define mp_sched_full() (mp_sched_num_pending() == MICROPY_SCHEDULER_DEPTH)
static inline bool mp_sched_empty(void) {
MP_STATIC_ASSERT(MICROPY_SCHEDULER_DEPTH <= 255); // MICROPY_SCHEDULER_DEPTH must fit in 8 bits
MP_STATIC_ASSERT((IDX_MASK(MICROPY_SCHEDULER_DEPTH) == 0)); // MICROPY_SCHEDULER_DEPTH must be a power of 2
return mp_sched_num_pending() == 0;
}
// A variant of this is inlined in the VM at the pending exception check
void mp_handle_pending(bool raise_exc) {
if (MP_STATE_VM(sched_state) == MP_SCHED_PENDING) {
mp_uint_t atomic_state = MICROPY_BEGIN_ATOMIC_SECTION();
// Re-check state is still pending now that we're in the atomic section.
if (MP_STATE_VM(sched_state) == MP_SCHED_PENDING) {
mp_obj_t obj = MP_STATE_THREAD(mp_pending_exception);
if (obj != MP_OBJ_NULL) {
MP_STATE_THREAD(mp_pending_exception) = MP_OBJ_NULL;
if (!mp_sched_num_pending()) {
MP_STATE_VM(sched_state) = MP_SCHED_IDLE;
}
if (raise_exc) {
MICROPY_END_ATOMIC_SECTION(atomic_state);
nlr_raise(obj);
}
}
mp_handle_pending_tail(atomic_state);
} else {
MICROPY_END_ATOMIC_SECTION(atomic_state);
}
}
}
#if MP_SCHED_CALLBACK_ARGS_LoBo
void free_carg(mp_sched_carg_t *carg)
{
for (int i = 0; i < MP_SCHED_CTYPE_MAX_ITEMS; i++) {
if (carg->entry[i]) {
if (carg->type == MP_SCHED_ENTRY_TYPE_CARG) {
free_carg((mp_sched_carg_t *)carg->entry[i]);
} else {
mp_sched_carg_entry_t *entry = (mp_sched_carg_entry_t *)carg->entry[i];
if (entry->sval) {
free(entry->sval);
entry->sval = NULL;
}
}
free(carg->entry[i]);
carg->entry[i] = NULL;
}
}
free(carg);
carg = NULL;
}
mp_sched_carg_t *make_carg_entry(mp_sched_carg_t *carg, int idx, uint8_t type, int val, const uint8_t *sval,
const char *key)
{
if (idx >= MP_SCHED_CTYPE_MAX_ITEMS) {
free_carg(carg);
return NULL;
}
if (carg->entry[idx]) {
free_carg(carg);
return NULL;
}
carg->entry[idx] = calloc(sizeof(mp_sched_carg_entry_t), 1);
if (carg->entry[idx] == NULL) {
free_carg(carg);
return NULL;
}
mp_sched_carg_entry_t *entry = (mp_sched_carg_entry_t *)carg->entry[idx];
entry->type = type;
if (key)
sprintf(entry->key, key);
if (sval) {
entry->ival = val;
entry->sval = malloc(val);
if (entry->sval == NULL) {
free_carg(carg);
return NULL;
}
memcpy(entry->sval, sval, val);
} else {
entry->ival = val;
}
carg->n++;
return carg;
}
mp_sched_carg_t *make_carg_entry_carg(mp_sched_carg_t *carg, int idx, mp_sched_carg_t *darg)
{
carg->entry[idx] = calloc(sizeof(mp_sched_carg_entry_t), 1);
if (carg->entry[idx] == NULL) {
free_carg(carg);
return NULL;
}
mp_sched_carg_entry_t *entry = (mp_sched_carg_entry_t *)carg->entry[idx];
entry->type = MP_SCHED_ENTRY_TYPE_CARG;
entry->carg = darg;
carg->n++;
return carg;
}
mp_sched_carg_t *make_cargs(int type)
{
// Create scheduler function arguments
mp_sched_carg_t *carg = calloc(sizeof(mp_sched_carg_t), 1);
if (carg == NULL)
return NULL;
carg->type = type;
carg->n = 0;
return carg;
}
static mp_obj_t make_arg_from_carg(mp_sched_carg_t *carg, int level, int *n_cbitems)
{
mp_obj_t arg = mp_const_none;
if (carg->type == MP_SCHED_CTYPE_DICT) {
// dictionary
mp_obj_dict_t *dct = mp_obj_new_dict(0);
for (int i = 0; i < carg->n; i++) {
mp_obj_t val;
mp_sched_carg_entry_t *entry = (mp_sched_carg_entry_t *)carg->entry[i];
if (entry->type == MP_SCHED_ENTRY_TYPE_INT) {
mp_obj_dict_store(dct, mp_obj_new_str_copy(&mp_type_str, (const byte *)entry->key, strlen(entry->key)),
mp_obj_new_int(entry->ival));
} else if (entry->type == MP_SCHED_ENTRY_TYPE_BOOL) {
mp_obj_dict_store(dct, mp_obj_new_str_copy(&mp_type_str, (const byte *)entry->key, strlen(entry->key)),
mp_obj_new_bool(entry->ival));
} else if (entry->type == MP_SCHED_ENTRY_TYPE_FLOAT) {
val = mp_obj_new_float(entry->fval);
mp_obj_dict_store(dct, mp_obj_new_str_copy(&mp_type_str, (const byte *)entry->key, strlen(entry->key)),
val);
#if FREE_CBOBJECT_AFTER
if (*n_cbitems < (MAX_CB_OBJECTS - 1))
cb_objects[(*n_cbitems)++] = val;
#endif
} else if (entry->type == MP_SCHED_ENTRY_TYPE_STR) {
val = mp_obj_new_str_copy(&mp_type_str, (const byte *)entry->sval, entry->ival);
mp_obj_dict_store(dct, mp_obj_new_str_copy(&mp_type_str, (const byte *)entry->key, strlen(entry->key)),
val);
#if FREE_CBOBJECT_AFTER
if (*n_cbitems < (MAX_CB_OBJECTS - 1))
cb_objects[(*n_cbitems)++] = val;
#endif
} else if (entry->type == MP_SCHED_ENTRY_TYPE_BYTES) {
val = mp_obj_new_bytes((const byte *)entry->sval, entry->ival);
mp_obj_dict_store(dct, mp_obj_new_str_copy(&mp_type_str, (const byte *)entry->key, strlen(entry->key)),
val);
#if FREE_CBOBJECT_AFTER
if (*n_cbitems < (MAX_CB_OBJECTS - 1))
cb_objects[(*n_cbitems)++] = val;
#endif
} else if ((level == 0) && (entry->type == MP_SCHED_ENTRY_TYPE_CARG) && (strlen(entry->key) > 0) &&
(entry->carg)) {
mp_obj_t darg = make_arg_from_carg(entry->carg, 1, n_cbitems);
mp_obj_dict_store(dct, mp_obj_new_str_copy(&mp_type_str, (const byte *)entry->key, strlen(entry->key)),
darg);
#if FREE_CBOBJECT_AFTER
if (*n_cbitems < (MAX_CB_OBJECTS - 1))
cb_objects[(*n_cbitems)++] = darg;
#endif
}
}
arg = dct;
#if FREE_CBOBJECT_AFTER
cb_objects[(*n_cbitems)++] = arg;
#endif
} else if (carg->type == MP_SCHED_CTYPE_TUPLE) {
// tuple
mp_obj_t tuple[carg->n];
for (int i = 0; i < carg->n; i++) {
mp_sched_carg_entry_t *entry = (mp_sched_carg_entry_t *)carg->entry[i];
if (entry->type == MP_SCHED_ENTRY_TYPE_INT) {
tuple[i] = mp_obj_new_int(entry->ival);
} else if (entry->type == MP_SCHED_ENTRY_TYPE_BOOL) {
tuple[i] = mp_obj_new_bool(entry->ival);
} else if (entry->type == MP_SCHED_ENTRY_TYPE_FLOAT) {
tuple[i] = mp_obj_new_float(entry->fval);
#if FREE_CBOBJECT_AFTER
if (*n_cbitems < (MAX_CB_OBJECTS - 1))
cb_objects[(*n_cbitems)++] = tuple[i];
#endif
} else if (entry->type == MP_SCHED_ENTRY_TYPE_STR) {
tuple[i] = mp_obj_new_str_copy(&mp_type_str, (const byte *)entry->sval, entry->ival);
#if FREE_CBOBJECT_AFTER
if (*n_cbitems < (MAX_CB_OBJECTS - 1))
cb_objects[(*n_cbitems)++] = tuple[i];
#endif
} else if (entry->type == MP_SCHED_ENTRY_TYPE_BYTES) {
tuple[i] = mp_obj_new_bytes((const byte *)entry->sval, entry->ival);
#if FREE_CBOBJECT_AFTER
if (*n_cbitems < (MAX_CB_OBJECTS - 1))
cb_objects[(*n_cbitems)++] = tuple[i];
#endif
} else if ((level == 0) && (entry->type == MP_SCHED_ENTRY_TYPE_CARG) && (entry->carg)) {
mp_obj_t darg = make_arg_from_carg(entry->carg, 1, n_cbitems);
tuple[i] = darg;
#if FREE_CBOBJECT_AFTER
if (*n_cbitems < (MAX_CB_OBJECTS - 1))
cb_objects[(*n_cbitems)++] = tuple[i];
#endif
} else {
tuple[i] = mp_const_none;
}
}
arg = mp_obj_new_tuple(carg->n, tuple);
#if FREE_CBOBJECT_AFTER
cb_objects[(*n_cbitems)++] = arg;
#endif
} else {
// Simple type, single entry
mp_sched_carg_entry_t *entry = (mp_sched_carg_entry_t *)carg->entry[0];
if (entry->type == MP_SCHED_ENTRY_TYPE_INT) {
arg = mp_obj_new_int(entry->ival);
} else if (entry->type == MP_SCHED_ENTRY_TYPE_BOOL) {
arg = mp_obj_new_bool(entry->ival);
} else if (entry->type == MP_SCHED_ENTRY_TYPE_FLOAT) {
arg = mp_obj_new_float(entry->fval);
#if FREE_CBOBJECT_AFTER
cb_objects[(*n_cbitems)++] = arg;
#endif
} else if (entry->type == MP_SCHED_ENTRY_TYPE_STR) {
arg = mp_obj_new_str_copy(&mp_type_str, (const byte *)entry->sval, entry->ival);
#if FREE_CBOBJECT_AFTER
cb_objects[(*n_cbitems)++] = arg;
#endif
} else if (entry->type == MP_SCHED_ENTRY_TYPE_BYTES) {
arg = mp_obj_new_bytes((const byte *)entry->sval, entry->ival);
#if FREE_CBOBJECT_AFTER
cb_objects[(*n_cbitems)++] = arg;
#endif
}
}
// Free C-argument structure
free_carg(carg);
return arg;
}
#endif
// This function should only be called by mp_handle_pending,
// or by the VM's inlined version of that function.
void mp_handle_pending_tail(mp_uint_t atomic_state) {
MP_STATE_VM(sched_state) = MP_SCHED_LOCKED;
if (!mp_sched_empty()) {
mp_sched_item_t item = MP_STATE_VM(sched_queue)[MP_STATE_VM(sched_idx)];
MP_STATE_VM(sched_idx) = IDX_MASK(MP_STATE_VM(sched_idx) + 1);
--MP_STATE_VM(sched_len);
MICROPY_END_ATOMIC_SECTION(atomic_state);
#if MP_SCHED_CALLBACK_ARGS_LoBo
int n_cbitems = 0;
mp_obj_t arg = mp_const_none;
if (item.carg != NULL) {
// === C argument is present, create the MicroPython object argument from it ===
arg = make_arg_from_carg((mp_sched_carg_t *)item.carg, 0, &n_cbitems);
} else {
arg = item.arg;
}
mp_call_function_1_protected(item.func, arg);
#else
mp_call_function_1_protected(item.func, item.arg);
#endif
#if FREE_CBOBJECT_AFTER
if (n_cbitems) {
// Free all allocated objects
for (int i = 0; i < n_cbitems; i++) {
m_free(cb_objects[i]);
}
}
#endif
} else {
MICROPY_END_ATOMIC_SECTION(atomic_state);
}
mp_sched_unlock();
}
void mp_sched_lock(void) {
mp_uint_t atomic_state = MICROPY_BEGIN_ATOMIC_SECTION();
if (MP_STATE_VM(sched_state) < 0) {
--MP_STATE_VM(sched_state);
} else {
MP_STATE_VM(sched_state) = MP_SCHED_LOCKED;
}
MICROPY_END_ATOMIC_SECTION(atomic_state);
}
void mp_sched_unlock(void) {
mp_uint_t atomic_state = MICROPY_BEGIN_ATOMIC_SECTION();
assert(MP_STATE_VM(sched_state) < 0);
if (++MP_STATE_VM(sched_state) == 0) {
// vm became unlocked
if (MP_STATE_THREAD(mp_pending_exception) != MP_OBJ_NULL || mp_sched_num_pending()) {
MP_STATE_VM(sched_state) = MP_SCHED_PENDING;
} else {
MP_STATE_VM(sched_state) = MP_SCHED_IDLE;
}
}
MICROPY_END_ATOMIC_SECTION(atomic_state);
}
bool MICROPY_WRAP_MP_SCHED_SCHEDULE(mp_sched_schedule)(mp_obj_t function, mp_obj_t arg) {
mp_uint_t atomic_state = MICROPY_BEGIN_ATOMIC_SECTION();
bool ret;
if (!mp_sched_full()) {
if (MP_STATE_VM(sched_state) == MP_SCHED_IDLE) {
MP_STATE_VM(sched_state) = MP_SCHED_PENDING;
}
uint8_t iput = IDX_MASK(MP_STATE_VM(sched_idx) + MP_STATE_VM(sched_len)++);
MP_STATE_VM(sched_queue)[iput].func = function;
MP_STATE_VM(sched_queue)[iput].arg = arg;
MICROPY_SCHED_HOOK_SCHEDULED;
ret = true;
} else {
// schedule queue is full
ret = false;
}
MICROPY_END_ATOMIC_SECTION(atomic_state);
return ret;
}
#if MP_SCHED_CALLBACK_ARGS_LoBo
bool MICROPY_WRAP_MP_SCHED_SCHEDULE(mp_sched_schedule_LoBo)(mp_obj_t function, mp_obj_t arg, void *carg)
{
mp_uint_t atomic_state = MICROPY_BEGIN_ATOMIC_SECTION();
bool ret;
if (!mp_sched_full()) {
if (MP_STATE_VM(sched_state) == MP_SCHED_IDLE) {
MP_STATE_VM(sched_state) = MP_SCHED_PENDING;
}
uint8_t iput = IDX_MASK(MP_STATE_VM(sched_idx) + MP_STATE_VM(sched_len)++);
MP_STATE_VM(sched_queue)[iput].func = function;
MP_STATE_VM(sched_queue)[iput].arg = arg;
MP_STATE_VM(sched_queue)[iput].carg = carg;
MICROPY_SCHED_HOOK_SCHEDULED;
ret = true;
} else {
// schedule queue is full
ret = false;
}
MICROPY_END_ATOMIC_SECTION(atomic_state);
return ret;
}
#endif
#else // MICROPY_ENABLE_SCHEDULER
// A variant of this is inlined in the VM at the pending exception check
void mp_handle_pending(bool raise_exc) {
if (MP_STATE_THREAD(mp_pending_exception) != MP_OBJ_NULL) {
mp_obj_t obj = MP_STATE_THREAD(mp_pending_exception);
MP_STATE_THREAD(mp_pending_exception) = MP_OBJ_NULL;
if (raise_exc) {
nlr_raise(obj);
}
}
}
#endif // MICROPY_ENABLE_SCHEDULER
| YifuLiu/AliOS-Things | components/py_engine/engine/py/scheduler.c | C | apache-2.0 | 15,942 |
/*
* 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 <assert.h>
#include "py/scope.h"
#if MICROPY_ENABLE_COMPILER
// These low numbered qstrs should fit in 8 bits. See assertions below.
STATIC const uint8_t scope_simple_name_table[] = {
[SCOPE_MODULE] = MP_QSTR__lt_module_gt_,
[SCOPE_LAMBDA] = MP_QSTR__lt_lambda_gt_,
[SCOPE_LIST_COMP] = MP_QSTR__lt_listcomp_gt_,
[SCOPE_DICT_COMP] = MP_QSTR__lt_dictcomp_gt_,
[SCOPE_SET_COMP] = MP_QSTR__lt_setcomp_gt_,
[SCOPE_GEN_EXPR] = MP_QSTR__lt_genexpr_gt_,
};
scope_t *scope_new(scope_kind_t kind, mp_parse_node_t pn, qstr source_file, mp_uint_t emit_options) {
// Make sure those qstrs indeed fit in an uint8_t.
MP_STATIC_ASSERT(MP_QSTR__lt_module_gt_ <= UINT8_MAX);
MP_STATIC_ASSERT(MP_QSTR__lt_lambda_gt_ <= UINT8_MAX);
MP_STATIC_ASSERT(MP_QSTR__lt_listcomp_gt_ <= UINT8_MAX);
MP_STATIC_ASSERT(MP_QSTR__lt_dictcomp_gt_ <= UINT8_MAX);
MP_STATIC_ASSERT(MP_QSTR__lt_setcomp_gt_ <= UINT8_MAX);
MP_STATIC_ASSERT(MP_QSTR__lt_genexpr_gt_ <= UINT8_MAX);
scope_t *scope = m_new0(scope_t, 1);
scope->kind = kind;
scope->pn = pn;
scope->source_file = source_file;
if (kind == SCOPE_FUNCTION || kind == SCOPE_CLASS) {
assert(MP_PARSE_NODE_IS_STRUCT(pn));
scope->simple_name = MP_PARSE_NODE_LEAF_ARG(((mp_parse_node_struct_t *)pn)->nodes[0]);
} else {
scope->simple_name = scope_simple_name_table[kind];
}
scope->raw_code = mp_emit_glue_new_raw_code();
scope->emit_options = emit_options;
scope->id_info_alloc = MICROPY_ALLOC_SCOPE_ID_INIT;
scope->id_info = m_new(id_info_t, scope->id_info_alloc);
return scope;
}
void scope_free(scope_t *scope) {
m_del(id_info_t, scope->id_info, scope->id_info_alloc);
m_del(scope_t, scope, 1);
}
id_info_t *scope_find_or_add_id(scope_t *scope, qstr qst, id_info_kind_t kind) {
id_info_t *id_info = scope_find(scope, qst);
if (id_info != NULL) {
return id_info;
}
// make sure we have enough memory
if (scope->id_info_len >= scope->id_info_alloc) {
scope->id_info = m_renew(id_info_t, scope->id_info, scope->id_info_alloc, scope->id_info_alloc + MICROPY_ALLOC_SCOPE_ID_INC);
scope->id_info_alloc += MICROPY_ALLOC_SCOPE_ID_INC;
}
// add new id to end of array of all ids; this seems to match CPython
// important thing is that function arguments are first, but that is
// handled by the compiler because it adds arguments before compiling the body
id_info = &scope->id_info[scope->id_info_len++];
id_info->kind = kind;
id_info->flags = 0;
id_info->local_num = 0;
id_info->qst = qst;
return id_info;
}
id_info_t *scope_find(scope_t *scope, qstr qst) {
for (mp_uint_t i = 0; i < scope->id_info_len; i++) {
if (scope->id_info[i].qst == qst) {
return &scope->id_info[i];
}
}
return NULL;
}
id_info_t *scope_find_global(scope_t *scope, qstr qst) {
while (scope->parent != NULL) {
scope = scope->parent;
}
return scope_find(scope, qst);
}
STATIC void scope_close_over_in_parents(scope_t *scope, qstr qst) {
assert(scope->parent != NULL); // we should have at least 1 parent
for (scope_t *s = scope->parent;; s = s->parent) {
assert(s->parent != NULL); // we should not get to the outer scope
id_info_t *id = scope_find_or_add_id(s, qst, ID_INFO_KIND_UNDECIDED);
if (id->kind == ID_INFO_KIND_UNDECIDED) {
// variable not previously declared in this scope, so declare it as free and keep searching parents
id->kind = ID_INFO_KIND_FREE;
} else {
// variable is declared in this scope, so finish
if (id->kind == ID_INFO_KIND_LOCAL) {
// variable local to this scope, close it over
id->kind = ID_INFO_KIND_CELL;
} else {
// ID_INFO_KIND_FREE: variable already closed over in a parent scope
// ID_INFO_KIND_CELL: variable already closed over in this scope
assert(id->kind == ID_INFO_KIND_FREE || id->kind == ID_INFO_KIND_CELL);
}
return;
}
}
}
void scope_check_to_close_over(scope_t *scope, id_info_t *id) {
if (scope->parent != NULL) {
for (scope_t *s = scope->parent; s->parent != NULL; s = s->parent) {
id_info_t *id2 = scope_find(s, id->qst);
if (id2 != NULL) {
if (id2->kind == ID_INFO_KIND_LOCAL || id2->kind == ID_INFO_KIND_CELL || id2->kind == ID_INFO_KIND_FREE) {
id->kind = ID_INFO_KIND_FREE;
scope_close_over_in_parents(scope, id->qst);
}
break;
}
}
}
}
#endif // MICROPY_ENABLE_COMPILER
| YifuLiu/AliOS-Things | components/py_engine/engine/py/scope.c | C | apache-2.0 | 5,998 |
/*
* 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.
*/
#ifndef MICROPY_INCLUDED_PY_SCOPE_H
#define MICROPY_INCLUDED_PY_SCOPE_H
#include "py/parse.h"
#include "py/emitglue.h"
typedef enum {
ID_INFO_KIND_UNDECIDED,
ID_INFO_KIND_GLOBAL_IMPLICIT,
ID_INFO_KIND_GLOBAL_EXPLICIT,
ID_INFO_KIND_LOCAL, // in a function f, written and only referenced by f
ID_INFO_KIND_CELL, // in a function f, read/written by children of f
ID_INFO_KIND_FREE, // in a function f, belongs to the parent of f
} id_info_kind_t;
enum {
ID_FLAG_IS_PARAM = 0x01,
ID_FLAG_IS_STAR_PARAM = 0x02,
ID_FLAG_IS_DBL_STAR_PARAM = 0x04,
ID_FLAG_VIPER_TYPE_POS = 4,
};
typedef struct _id_info_t {
uint8_t kind;
uint8_t flags;
// when it's an ID_INFO_KIND_LOCAL this is the unique number of the local
// whet it's an ID_INFO_KIND_CELL/FREE this is the unique number of the closed over variable
uint16_t local_num;
qstr qst;
} id_info_t;
#define SCOPE_IS_FUNC_LIKE(s) ((s) >= SCOPE_LAMBDA)
#define SCOPE_IS_COMP_LIKE(s) (SCOPE_LIST_COMP <= (s) && (s) <= SCOPE_GEN_EXPR)
// scope is a "block" in Python parlance
typedef enum {
SCOPE_MODULE,
SCOPE_CLASS,
SCOPE_LAMBDA,
SCOPE_LIST_COMP,
SCOPE_DICT_COMP,
SCOPE_SET_COMP,
SCOPE_GEN_EXPR,
SCOPE_FUNCTION,
} scope_kind_t;
typedef struct _scope_t {
scope_kind_t kind;
struct _scope_t *parent;
struct _scope_t *next;
mp_parse_node_t pn;
mp_raw_code_t *raw_code;
uint16_t source_file; // a qstr
uint16_t simple_name; // a qstr
uint16_t scope_flags; // see runtime0.h
uint16_t emit_options; // see emitglue.h
uint16_t num_pos_args;
uint16_t num_kwonly_args;
uint16_t num_def_pos_args;
uint16_t num_locals;
uint16_t stack_size; // maximum size of the locals stack
uint16_t exc_stack_size; // maximum size of the exception stack
uint16_t id_info_alloc;
uint16_t id_info_len;
id_info_t *id_info;
} scope_t;
scope_t *scope_new(scope_kind_t kind, mp_parse_node_t pn, qstr source_file, mp_uint_t emit_options);
void scope_free(scope_t *scope);
id_info_t *scope_find_or_add_id(scope_t *scope, qstr qstr, id_info_kind_t kind);
id_info_t *scope_find(scope_t *scope, qstr qstr);
id_info_t *scope_find_global(scope_t *scope, qstr qstr);
void scope_check_to_close_over(scope_t *scope, id_info_t *id);
#endif // MICROPY_INCLUDED_PY_SCOPE_H
| YifuLiu/AliOS-Things | components/py_engine/engine/py/scope.h | C | apache-2.0 | 3,581 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2013, 2014 Damien P. George
* Copyright (c) 2014 Paul Sokolovsky
*
* 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 <string.h>
#include "py/runtime.h"
// Helpers for sequence types
#define SWAP(type, var1, var2) { type t = var2; var2 = var1; var1 = t; }
// Implements backend of sequence * integer operation. Assumes elements are
// memory-adjacent in sequence.
void mp_seq_multiply(const void *items, size_t item_sz, size_t len, size_t times, void *dest) {
for (size_t i = 0; i < times; i++) {
size_t copy_sz = item_sz * len;
memcpy(dest, items, copy_sz);
dest = (char *)dest + copy_sz;
}
}
#if MICROPY_PY_BUILTINS_SLICE
bool mp_seq_get_fast_slice_indexes(mp_uint_t len, mp_obj_t slice, mp_bound_slice_t *indexes) {
mp_obj_slice_indices(slice, len, indexes);
// If the index is negative then stop points to the last item, not after it
if (indexes->step < 0) {
indexes->stop++;
}
// CPython returns empty sequence in such case, or point for assignment is at start
if (indexes->step > 0 && indexes->start > indexes->stop) {
indexes->stop = indexes->start;
} else if (indexes->step < 0 && indexes->start < indexes->stop) {
indexes->stop = indexes->start + 1;
}
return indexes->step == 1;
}
#endif
mp_obj_t mp_seq_extract_slice(size_t len, const mp_obj_t *seq, mp_bound_slice_t *indexes) {
(void)len; // TODO can we remove len from the arg list?
mp_int_t start = indexes->start, stop = indexes->stop;
mp_int_t step = indexes->step;
mp_obj_t res = mp_obj_new_list(0, NULL);
if (step < 0) {
while (start >= stop) {
mp_obj_list_append(res, seq[start]);
start += step;
}
} else {
while (start < stop) {
mp_obj_list_append(res, seq[start]);
start += step;
}
}
return res;
}
// Special-case comparison function for sequences of bytes
// Don't pass MP_BINARY_OP_NOT_EQUAL here
bool mp_seq_cmp_bytes(mp_uint_t op, const byte *data1, size_t len1, const byte *data2, size_t len2) {
if (op == MP_BINARY_OP_EQUAL && len1 != len2) {
return false;
}
// Let's deal only with > & >=
if (op == MP_BINARY_OP_LESS || op == MP_BINARY_OP_LESS_EQUAL) {
SWAP(const byte *, data1, data2);
SWAP(size_t, len1, len2);
if (op == MP_BINARY_OP_LESS) {
op = MP_BINARY_OP_MORE;
} else {
op = MP_BINARY_OP_MORE_EQUAL;
}
}
size_t min_len = len1 < len2 ? len1 : len2;
int res = memcmp(data1, data2, min_len);
if (op == MP_BINARY_OP_EQUAL) {
// If we are checking for equality, here's the answer
return res == 0;
}
if (res < 0) {
return false;
}
if (res > 0) {
return true;
}
// If we had tie in the last element...
// ... and we have lists of different lengths...
if (len1 != len2) {
if (len1 < len2) {
// ... then longer list length wins (we deal only with >)
return false;
}
} else if (op == MP_BINARY_OP_MORE) {
// Otherwise, if we have strict relation, equality means failure
return false;
}
return true;
}
// Special-case comparison function for sequences of mp_obj_t
// Don't pass MP_BINARY_OP_NOT_EQUAL here
bool mp_seq_cmp_objs(mp_uint_t op, const mp_obj_t *items1, size_t len1, const mp_obj_t *items2, size_t len2) {
if (op == MP_BINARY_OP_EQUAL && len1 != len2) {
return false;
}
// Let's deal only with > & >=
if (op == MP_BINARY_OP_LESS || op == MP_BINARY_OP_LESS_EQUAL) {
SWAP(const mp_obj_t *, items1, items2);
SWAP(size_t, len1, len2);
if (op == MP_BINARY_OP_LESS) {
op = MP_BINARY_OP_MORE;
} else {
op = MP_BINARY_OP_MORE_EQUAL;
}
}
size_t len = len1 < len2 ? len1 : len2;
for (size_t i = 0; i < len; i++) {
// If current elements equal, can't decide anything - go on
if (mp_obj_equal(items1[i], items2[i])) {
continue;
}
// Othewise, if they are not equal, we can have final decision based on them
if (op == MP_BINARY_OP_EQUAL) {
// In particular, if we are checking for equality, here're the answer
return false;
}
// Otherwise, application of relation op gives the answer
return mp_binary_op(op, items1[i], items2[i]) == mp_const_true;
}
// If we had tie in the last element...
// ... and we have lists of different lengths...
if (len1 != len2) {
if (len1 < len2) {
// ... then longer list length wins (we deal only with >)
return false;
}
} else if (op == MP_BINARY_OP_MORE) {
// Otherwise, if we have strict relation, sequence equality means failure
return false;
}
return true;
}
// Special-case of index() which searches for mp_obj_t
mp_obj_t mp_seq_index_obj(const mp_obj_t *items, size_t len, size_t n_args, const mp_obj_t *args) {
const mp_obj_type_t *type = mp_obj_get_type(args[0]);
mp_obj_t value = args[1];
size_t start = 0;
size_t stop = len;
if (n_args >= 3) {
start = mp_get_index(type, len, args[2], true);
if (n_args >= 4) {
stop = mp_get_index(type, len, args[3], true);
}
}
for (size_t i = start; i < stop; i++) {
if (mp_obj_equal(items[i], value)) {
// Common sense says this cannot overflow small int
return MP_OBJ_NEW_SMALL_INT(i);
}
}
mp_raise_ValueError(MP_ERROR_TEXT("object not in sequence"));
}
mp_obj_t mp_seq_count_obj(const mp_obj_t *items, size_t len, mp_obj_t value) {
size_t count = 0;
for (size_t i = 0; i < len; i++) {
if (mp_obj_equal(items[i], value)) {
count++;
}
}
// Common sense says this cannot overflow small int
return MP_OBJ_NEW_SMALL_INT(count);
}
| YifuLiu/AliOS-Things | components/py_engine/engine/py/sequence.c | C | apache-2.0 | 7,151 |
/*
* 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 <stdio.h>
#include <assert.h>
#include "py/bc0.h"
#include "py/bc.h"
#if MICROPY_DEBUG_PRINTERS
#define DECODE_UINT { \
unum = 0; \
do { \
unum = (unum << 7) + (*ip & 0x7f); \
} while ((*ip++ & 0x80) != 0); \
}
#define DECODE_ULABEL do { unum = (ip[0] | (ip[1] << 8)); ip += 2; } while (0)
#define DECODE_SLABEL do { unum = (ip[0] | (ip[1] << 8)) - 0x8000; ip += 2; } while (0)
#if MICROPY_PERSISTENT_CODE
#define DECODE_QSTR \
qst = ip[0] | ip[1] << 8; \
ip += 2;
#define DECODE_PTR \
DECODE_UINT; \
unum = mp_showbc_const_table[unum]
#define DECODE_OBJ \
DECODE_UINT; \
unum = mp_showbc_const_table[unum]
#else
#define DECODE_QSTR { \
qst = 0; \
do { \
qst = (qst << 7) + (*ip & 0x7f); \
} while ((*ip++ & 0x80) != 0); \
}
#define DECODE_PTR do { \
ip = (byte *)MP_ALIGN(ip, sizeof(void *)); \
unum = (uintptr_t)*(void **)ip; \
ip += sizeof(void *); \
} while (0)
#define DECODE_OBJ do { \
ip = (byte *)MP_ALIGN(ip, sizeof(mp_obj_t)); \
unum = (mp_uint_t)*(mp_obj_t *)ip; \
ip += sizeof(mp_obj_t); \
} while (0)
#endif
const byte *mp_showbc_code_start;
const mp_uint_t *mp_showbc_const_table;
void mp_bytecode_print(const mp_print_t *print, const void *descr, const byte *ip, mp_uint_t len, const mp_uint_t *const_table) {
mp_showbc_code_start = ip;
// Decode prelude
MP_BC_PRELUDE_SIG_DECODE(ip);
MP_BC_PRELUDE_SIZE_DECODE(ip);
const byte *code_info = ip;
#if MICROPY_PERSISTENT_CODE
qstr block_name = code_info[0] | (code_info[1] << 8);
qstr source_file = code_info[2] | (code_info[3] << 8);
code_info += 4;
#else
qstr block_name = mp_decode_uint(&code_info);
qstr source_file = mp_decode_uint(&code_info);
#endif
mp_printf(print, "File %s, code block '%s' (descriptor: %p, bytecode @%p " UINT_FMT " bytes)\n",
qstr_str(source_file), qstr_str(block_name), descr, mp_showbc_code_start, len);
// raw bytecode dump
size_t prelude_size = ip - mp_showbc_code_start + n_info + n_cell;
mp_printf(print, "Raw bytecode (code_info_size=" UINT_FMT ", bytecode_size=" UINT_FMT "):\n",
prelude_size, len - prelude_size);
for (mp_uint_t i = 0; i < len; i++) {
if (i > 0 && i % 16 == 0) {
mp_printf(print, "\n");
}
mp_printf(print, " %02x", mp_showbc_code_start[i]);
}
mp_printf(print, "\n");
// bytecode prelude: arg names (as qstr objects)
mp_printf(print, "arg names:");
for (mp_uint_t i = 0; i < n_pos_args + n_kwonly_args; i++) {
mp_printf(print, " %s", qstr_str(MP_OBJ_QSTR_VALUE(const_table[i])));
}
mp_printf(print, "\n");
mp_printf(print, "(N_STATE %u)\n", (unsigned)n_state);
mp_printf(print, "(N_EXC_STACK %u)\n", (unsigned)n_exc_stack);
// skip over code_info
ip += n_info;
// bytecode prelude: initialise closed over variables
for (size_t i = 0; i < n_cell; ++i) {
uint local_num = *ip++;
mp_printf(print, "(INIT_CELL %u)\n", local_num);
}
// print out line number info
{
mp_int_t bc = 0;
mp_uint_t source_line = 1;
mp_printf(print, " bc=" INT_FMT " line=" UINT_FMT "\n", bc, source_line);
for (const byte *ci = code_info; *ci;) {
if ((ci[0] & 0x80) == 0) {
// 0b0LLBBBBB encoding
bc += ci[0] & 0x1f;
source_line += ci[0] >> 5;
ci += 1;
} else {
// 0b1LLLBBBB 0bLLLLLLLL encoding (l's LSB in second byte)
bc += ci[0] & 0xf;
source_line += ((ci[0] << 4) & 0x700) | ci[1];
ci += 2;
}
mp_printf(print, " bc=" INT_FMT " line=" UINT_FMT "\n", bc, source_line);
}
}
mp_bytecode_print2(print, ip, len - prelude_size, const_table);
}
const byte *mp_bytecode_print_str(const mp_print_t *print, const byte *ip) {
mp_uint_t unum;
qstr qst;
switch (*ip++) {
case MP_BC_LOAD_CONST_FALSE:
mp_printf(print, "LOAD_CONST_FALSE");
break;
case MP_BC_LOAD_CONST_NONE:
mp_printf(print, "LOAD_CONST_NONE");
break;
case MP_BC_LOAD_CONST_TRUE:
mp_printf(print, "LOAD_CONST_TRUE");
break;
case MP_BC_LOAD_CONST_SMALL_INT: {
mp_int_t num = 0;
if ((ip[0] & 0x40) != 0) {
// Number is negative
num--;
}
do {
num = ((mp_uint_t)num << 7) | (*ip & 0x7f);
} while ((*ip++ & 0x80) != 0);
mp_printf(print, "LOAD_CONST_SMALL_INT " INT_FMT, num);
break;
}
case MP_BC_LOAD_CONST_STRING:
DECODE_QSTR;
mp_printf(print, "LOAD_CONST_STRING '%s'", qstr_str(qst));
break;
case MP_BC_LOAD_CONST_OBJ:
DECODE_OBJ;
mp_printf(print, "LOAD_CONST_OBJ %p=", MP_OBJ_TO_PTR(unum));
mp_obj_print_helper(print, (mp_obj_t)unum, PRINT_REPR);
break;
case MP_BC_LOAD_NULL:
mp_printf(print, "LOAD_NULL");
break;
case MP_BC_LOAD_FAST_N:
DECODE_UINT;
mp_printf(print, "LOAD_FAST_N " UINT_FMT, unum);
break;
case MP_BC_LOAD_DEREF:
DECODE_UINT;
mp_printf(print, "LOAD_DEREF " UINT_FMT, unum);
break;
case MP_BC_LOAD_NAME:
DECODE_QSTR;
mp_printf(print, "LOAD_NAME %s", qstr_str(qst));
if (MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE) {
mp_printf(print, " (cache=%u)", *ip++);
}
break;
case MP_BC_LOAD_GLOBAL:
DECODE_QSTR;
mp_printf(print, "LOAD_GLOBAL %s", qstr_str(qst));
if (MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE) {
mp_printf(print, " (cache=%u)", *ip++);
}
break;
case MP_BC_LOAD_ATTR:
DECODE_QSTR;
mp_printf(print, "LOAD_ATTR %s", qstr_str(qst));
if (MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE) {
mp_printf(print, " (cache=%u)", *ip++);
}
break;
case MP_BC_LOAD_METHOD:
DECODE_QSTR;
mp_printf(print, "LOAD_METHOD %s", qstr_str(qst));
break;
case MP_BC_LOAD_SUPER_METHOD:
DECODE_QSTR;
mp_printf(print, "LOAD_SUPER_METHOD %s", qstr_str(qst));
break;
case MP_BC_LOAD_BUILD_CLASS:
mp_printf(print, "LOAD_BUILD_CLASS");
break;
case MP_BC_LOAD_SUBSCR:
mp_printf(print, "LOAD_SUBSCR");
break;
case MP_BC_STORE_FAST_N:
DECODE_UINT;
mp_printf(print, "STORE_FAST_N " UINT_FMT, unum);
break;
case MP_BC_STORE_DEREF:
DECODE_UINT;
mp_printf(print, "STORE_DEREF " UINT_FMT, unum);
break;
case MP_BC_STORE_NAME:
DECODE_QSTR;
mp_printf(print, "STORE_NAME %s", qstr_str(qst));
break;
case MP_BC_STORE_GLOBAL:
DECODE_QSTR;
mp_printf(print, "STORE_GLOBAL %s", qstr_str(qst));
break;
case MP_BC_STORE_ATTR:
DECODE_QSTR;
mp_printf(print, "STORE_ATTR %s", qstr_str(qst));
if (MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE) {
mp_printf(print, " (cache=%u)", *ip++);
}
break;
case MP_BC_STORE_SUBSCR:
mp_printf(print, "STORE_SUBSCR");
break;
case MP_BC_DELETE_FAST:
DECODE_UINT;
mp_printf(print, "DELETE_FAST " UINT_FMT, unum);
break;
case MP_BC_DELETE_DEREF:
DECODE_UINT;
mp_printf(print, "DELETE_DEREF " UINT_FMT, unum);
break;
case MP_BC_DELETE_NAME:
DECODE_QSTR;
mp_printf(print, "DELETE_NAME %s", qstr_str(qst));
break;
case MP_BC_DELETE_GLOBAL:
DECODE_QSTR;
mp_printf(print, "DELETE_GLOBAL %s", qstr_str(qst));
break;
case MP_BC_DUP_TOP:
mp_printf(print, "DUP_TOP");
break;
case MP_BC_DUP_TOP_TWO:
mp_printf(print, "DUP_TOP_TWO");
break;
case MP_BC_POP_TOP:
mp_printf(print, "POP_TOP");
break;
case MP_BC_ROT_TWO:
mp_printf(print, "ROT_TWO");
break;
case MP_BC_ROT_THREE:
mp_printf(print, "ROT_THREE");
break;
case MP_BC_JUMP:
DECODE_SLABEL;
mp_printf(print, "JUMP " UINT_FMT, (mp_uint_t)(ip + unum - mp_showbc_code_start));
break;
case MP_BC_POP_JUMP_IF_TRUE:
DECODE_SLABEL;
mp_printf(print, "POP_JUMP_IF_TRUE " UINT_FMT, (mp_uint_t)(ip + unum - mp_showbc_code_start));
break;
case MP_BC_POP_JUMP_IF_FALSE:
DECODE_SLABEL;
mp_printf(print, "POP_JUMP_IF_FALSE " UINT_FMT, (mp_uint_t)(ip + unum - mp_showbc_code_start));
break;
case MP_BC_JUMP_IF_TRUE_OR_POP:
DECODE_SLABEL;
mp_printf(print, "JUMP_IF_TRUE_OR_POP " UINT_FMT, (mp_uint_t)(ip + unum - mp_showbc_code_start));
break;
case MP_BC_JUMP_IF_FALSE_OR_POP:
DECODE_SLABEL;
mp_printf(print, "JUMP_IF_FALSE_OR_POP " UINT_FMT, (mp_uint_t)(ip + unum - mp_showbc_code_start));
break;
case MP_BC_SETUP_WITH:
DECODE_ULABEL; // loop-like labels are always forward
mp_printf(print, "SETUP_WITH " UINT_FMT, (mp_uint_t)(ip + unum - mp_showbc_code_start));
break;
case MP_BC_WITH_CLEANUP:
mp_printf(print, "WITH_CLEANUP");
break;
case MP_BC_UNWIND_JUMP:
DECODE_SLABEL;
mp_printf(print, "UNWIND_JUMP " UINT_FMT " %d", (mp_uint_t)(ip + unum - mp_showbc_code_start), *ip);
ip += 1;
break;
case MP_BC_SETUP_EXCEPT:
DECODE_ULABEL; // except labels are always forward
mp_printf(print, "SETUP_EXCEPT " UINT_FMT, (mp_uint_t)(ip + unum - mp_showbc_code_start));
break;
case MP_BC_SETUP_FINALLY:
DECODE_ULABEL; // except labels are always forward
mp_printf(print, "SETUP_FINALLY " UINT_FMT, (mp_uint_t)(ip + unum - mp_showbc_code_start));
break;
case MP_BC_END_FINALLY:
// if TOS is an exception, reraises the exception (3 values on TOS)
// if TOS is an integer, does something else
// if TOS is None, just pops it and continues
// else error
mp_printf(print, "END_FINALLY");
break;
case MP_BC_GET_ITER:
mp_printf(print, "GET_ITER");
break;
case MP_BC_GET_ITER_STACK:
mp_printf(print, "GET_ITER_STACK");
break;
case MP_BC_FOR_ITER:
DECODE_ULABEL; // the jump offset if iteration finishes; for labels are always forward
mp_printf(print, "FOR_ITER " UINT_FMT, (mp_uint_t)(ip + unum - mp_showbc_code_start));
break;
case MP_BC_POP_EXCEPT_JUMP:
DECODE_ULABEL; // these labels are always forward
mp_printf(print, "POP_EXCEPT_JUMP " UINT_FMT, (mp_uint_t)(ip + unum - mp_showbc_code_start));
break;
case MP_BC_BUILD_TUPLE:
DECODE_UINT;
mp_printf(print, "BUILD_TUPLE " UINT_FMT, unum);
break;
case MP_BC_BUILD_LIST:
DECODE_UINT;
mp_printf(print, "BUILD_LIST " UINT_FMT, unum);
break;
case MP_BC_BUILD_MAP:
DECODE_UINT;
mp_printf(print, "BUILD_MAP " UINT_FMT, unum);
break;
case MP_BC_STORE_MAP:
mp_printf(print, "STORE_MAP");
break;
case MP_BC_BUILD_SET:
DECODE_UINT;
mp_printf(print, "BUILD_SET " UINT_FMT, unum);
break;
#if MICROPY_PY_BUILTINS_SLICE
case MP_BC_BUILD_SLICE:
DECODE_UINT;
mp_printf(print, "BUILD_SLICE " UINT_FMT, unum);
break;
#endif
case MP_BC_STORE_COMP:
DECODE_UINT;
mp_printf(print, "STORE_COMP " UINT_FMT, unum);
break;
case MP_BC_UNPACK_SEQUENCE:
DECODE_UINT;
mp_printf(print, "UNPACK_SEQUENCE " UINT_FMT, unum);
break;
case MP_BC_UNPACK_EX:
DECODE_UINT;
mp_printf(print, "UNPACK_EX " UINT_FMT, unum);
break;
case MP_BC_MAKE_FUNCTION:
DECODE_PTR;
mp_printf(print, "MAKE_FUNCTION %p", (void *)(uintptr_t)unum);
break;
case MP_BC_MAKE_FUNCTION_DEFARGS:
DECODE_PTR;
mp_printf(print, "MAKE_FUNCTION_DEFARGS %p", (void *)(uintptr_t)unum);
break;
case MP_BC_MAKE_CLOSURE: {
DECODE_PTR;
mp_uint_t n_closed_over = *ip++;
mp_printf(print, "MAKE_CLOSURE %p " UINT_FMT, (void *)(uintptr_t)unum, n_closed_over);
break;
}
case MP_BC_MAKE_CLOSURE_DEFARGS: {
DECODE_PTR;
mp_uint_t n_closed_over = *ip++;
mp_printf(print, "MAKE_CLOSURE_DEFARGS %p " UINT_FMT, (void *)(uintptr_t)unum, n_closed_over);
break;
}
case MP_BC_CALL_FUNCTION:
DECODE_UINT;
mp_printf(print, "CALL_FUNCTION n=" UINT_FMT " nkw=" UINT_FMT, unum & 0xff, (unum >> 8) & 0xff);
break;
case MP_BC_CALL_FUNCTION_VAR_KW:
DECODE_UINT;
mp_printf(print, "CALL_FUNCTION_VAR_KW n=" UINT_FMT " nkw=" UINT_FMT, unum & 0xff, (unum >> 8) & 0xff);
break;
case MP_BC_CALL_METHOD:
DECODE_UINT;
mp_printf(print, "CALL_METHOD n=" UINT_FMT " nkw=" UINT_FMT, unum & 0xff, (unum >> 8) & 0xff);
break;
case MP_BC_CALL_METHOD_VAR_KW:
DECODE_UINT;
mp_printf(print, "CALL_METHOD_VAR_KW n=" UINT_FMT " nkw=" UINT_FMT, unum & 0xff, (unum >> 8) & 0xff);
break;
case MP_BC_RETURN_VALUE:
mp_printf(print, "RETURN_VALUE");
break;
case MP_BC_RAISE_LAST:
mp_printf(print, "RAISE_LAST");
break;
case MP_BC_RAISE_OBJ:
mp_printf(print, "RAISE_OBJ");
break;
case MP_BC_RAISE_FROM:
mp_printf(print, "RAISE_FROM");
break;
case MP_BC_YIELD_VALUE:
mp_printf(print, "YIELD_VALUE");
break;
case MP_BC_YIELD_FROM:
mp_printf(print, "YIELD_FROM");
break;
case MP_BC_IMPORT_NAME:
DECODE_QSTR;
mp_printf(print, "IMPORT_NAME '%s'", qstr_str(qst));
break;
case MP_BC_IMPORT_FROM:
DECODE_QSTR;
mp_printf(print, "IMPORT_FROM '%s'", qstr_str(qst));
break;
case MP_BC_IMPORT_STAR:
mp_printf(print, "IMPORT_STAR");
break;
default:
if (ip[-1] < MP_BC_LOAD_CONST_SMALL_INT_MULTI + 64) {
mp_printf(print, "LOAD_CONST_SMALL_INT " INT_FMT, (mp_int_t)ip[-1] - MP_BC_LOAD_CONST_SMALL_INT_MULTI - 16);
} else if (ip[-1] < MP_BC_LOAD_FAST_MULTI + 16) {
mp_printf(print, "LOAD_FAST " UINT_FMT, (mp_uint_t)ip[-1] - MP_BC_LOAD_FAST_MULTI);
} else if (ip[-1] < MP_BC_STORE_FAST_MULTI + 16) {
mp_printf(print, "STORE_FAST " UINT_FMT, (mp_uint_t)ip[-1] - MP_BC_STORE_FAST_MULTI);
} else if (ip[-1] < MP_BC_UNARY_OP_MULTI + MP_UNARY_OP_NUM_BYTECODE) {
mp_printf(print, "UNARY_OP " UINT_FMT, (mp_uint_t)ip[-1] - MP_BC_UNARY_OP_MULTI);
} else if (ip[-1] < MP_BC_BINARY_OP_MULTI + MP_BINARY_OP_NUM_BYTECODE) {
mp_uint_t op = ip[-1] - MP_BC_BINARY_OP_MULTI;
mp_printf(print, "BINARY_OP " UINT_FMT " %s", op, qstr_str(mp_binary_op_method_name[op]));
} else {
mp_printf(print, "code %p, byte code 0x%02x not implemented\n", ip - 1, ip[-1]);
assert(0);
return ip;
}
break;
}
return ip;
}
void mp_bytecode_print2(const mp_print_t *print, const byte *ip, size_t len, const mp_uint_t *const_table) {
mp_showbc_code_start = ip;
mp_showbc_const_table = const_table;
while (ip < len + mp_showbc_code_start) {
mp_printf(print, "%02u ", (uint)(ip - mp_showbc_code_start));
ip = mp_bytecode_print_str(print, ip);
mp_printf(print, "\n");
}
}
#endif // MICROPY_DEBUG_PRINTERS
| YifuLiu/AliOS-Things | components/py_engine/engine/py/showbc.c | C | apache-2.0 | 18,300 |
/*
* 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 "py/smallint.h"
bool mp_small_int_mul_overflow(mp_int_t x, mp_int_t y) {
// Check for multiply overflow; see CERT INT32-C
if (x > 0) { // x is positive
if (y > 0) { // x and y are positive
if (x > (MP_SMALL_INT_MAX / y)) {
return true;
}
} else { // x positive, y nonpositive
if (y < (MP_SMALL_INT_MIN / x)) {
return true;
}
} // x positive, y nonpositive
} else { // x is nonpositive
if (y > 0) { // x is nonpositive, y is positive
if (x < (MP_SMALL_INT_MIN / y)) {
return true;
}
} else { // x and y are nonpositive
if (x != 0 && y < (MP_SMALL_INT_MAX / x)) {
return true;
}
} // End if x and y are nonpositive
} // End if x is nonpositive
return false;
}
mp_int_t mp_small_int_modulo(mp_int_t dividend, mp_int_t divisor) {
// Python specs require that mod has same sign as second operand
dividend %= divisor;
if ((dividend < 0 && divisor > 0) || (dividend > 0 && divisor < 0)) {
dividend += divisor;
}
return dividend;
}
mp_int_t mp_small_int_floor_divide(mp_int_t num, mp_int_t denom) {
if (num >= 0) {
if (denom < 0) {
num += -denom - 1;
}
} else {
if (denom >= 0) {
num += -denom + 1;
}
}
return num / denom;
}
| YifuLiu/AliOS-Things | components/py_engine/engine/py/smallint.c | C | apache-2.0 | 2,689 |
/*
* 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.
*/
#ifndef MICROPY_INCLUDED_PY_SMALLINT_H
#define MICROPY_INCLUDED_PY_SMALLINT_H
#include "py/mpconfig.h"
#include "py/misc.h"
// Functions for small integer arithmetic
#ifndef MP_SMALL_INT_MIN
// In SMALL_INT, next-to-highest bits is used as sign, so both must match for value in range
#if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_A || MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_C
#define MP_SMALL_INT_MIN ((mp_int_t)(((mp_int_t)MP_OBJ_WORD_MSBIT_HIGH) >> 1))
#define MP_SMALL_INT_FITS(n) ((((n) ^ ((mp_uint_t)(n) << 1)) & MP_OBJ_WORD_MSBIT_HIGH) == 0)
// Mask to truncate mp_int_t to positive value
#define MP_SMALL_INT_POSITIVE_MASK ~(MP_OBJ_WORD_MSBIT_HIGH | (MP_OBJ_WORD_MSBIT_HIGH >> 1))
#elif MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_B
#define MP_SMALL_INT_MIN ((mp_int_t)(((mp_int_t)MP_OBJ_WORD_MSBIT_HIGH) >> 2))
#define MP_SMALL_INT_FITS(n) ((((n) & MP_SMALL_INT_MIN) == 0) || (((n) & MP_SMALL_INT_MIN) == MP_SMALL_INT_MIN))
// Mask to truncate mp_int_t to positive value
#define MP_SMALL_INT_POSITIVE_MASK ~(MP_OBJ_WORD_MSBIT_HIGH | (MP_OBJ_WORD_MSBIT_HIGH >> 1) | (MP_OBJ_WORD_MSBIT_HIGH >> 2))
#elif MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_D
#define MP_SMALL_INT_MIN ((mp_int_t)(((mp_int_t)0xffff800000000000) >> 1))
#define MP_SMALL_INT_FITS(n) ((((n) ^ ((n) << 1)) & 0xffff800000000000) == 0)
// Mask to truncate mp_int_t to positive value
#define MP_SMALL_INT_POSITIVE_MASK ~(0xffff800000000000 | (0xffff800000000000 >> 1))
#endif
#endif
#define MP_SMALL_INT_MAX ((mp_int_t)(~(MP_SMALL_INT_MIN)))
bool mp_small_int_mul_overflow(mp_int_t x, mp_int_t y);
mp_int_t mp_small_int_modulo(mp_int_t dividend, mp_int_t divisor);
mp_int_t mp_small_int_floor_divide(mp_int_t num, mp_int_t denom);
#endif // MICROPY_INCLUDED_PY_SMALLINT_H
| YifuLiu/AliOS-Things | components/py_engine/engine/py/smallint.h | C | apache-2.0 | 2,968 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2014 Paul Sokolovsky
*
* 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 "py/runtime.h"
#include "py/stackctrl.h"
void mp_stack_ctrl_init(void) {
volatile int stack_dummy;
MP_STATE_THREAD(stack_top) = (char *)&stack_dummy;
}
void mp_stack_set_top(void *top) {
MP_STATE_THREAD(stack_top) = top;
}
mp_uint_t mp_stack_usage(void) {
// Assumes descending stack
volatile int stack_dummy;
return MP_STATE_THREAD(stack_top) - (char *)&stack_dummy;
}
#if MICROPY_STACK_CHECK
void mp_stack_set_limit(mp_uint_t limit) {
MP_STATE_THREAD(stack_limit) = limit;
}
void mp_stack_check(void) {
if (mp_stack_usage() >= MP_STATE_THREAD(stack_limit)) {
mp_raise_recursion_depth();
}
}
#endif // MICROPY_STACK_CHECK
| YifuLiu/AliOS-Things | components/py_engine/engine/py/stackctrl.c | C | apache-2.0 | 1,908 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2014 Paul Sokolovsky
*
* 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.
*/
#ifndef MICROPY_INCLUDED_PY_STACKCTRL_H
#define MICROPY_INCLUDED_PY_STACKCTRL_H
#include "py/mpconfig.h"
void mp_stack_ctrl_init(void);
void mp_stack_set_top(void *top);
mp_uint_t mp_stack_usage(void);
#if MICROPY_STACK_CHECK
void mp_stack_set_limit(mp_uint_t limit);
void mp_stack_check(void);
#define MP_STACK_CHECK() mp_stack_check()
#else
#define mp_stack_set_limit(limit) (void)(limit)
#define MP_STACK_CHECK()
#endif
#endif // MICROPY_INCLUDED_PY_STACKCTRL_H
| YifuLiu/AliOS-Things | components/py_engine/engine/py/stackctrl.h | C | apache-2.0 | 1,697 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2014 Damien P. George
* Copyright (c) 2014-2016 Paul Sokolovsky
*
* 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 <string.h>
#include <unistd.h>
#include "py/objstr.h"
#include "py/stream.h"
#include "py/runtime.h"
// This file defines generic Python stream read/write methods which
// dispatch to the underlying stream interface of an object.
// TODO: should be in mpconfig.h
#define DEFAULT_BUFFER_SIZE 256
STATIC mp_obj_t stream_readall(mp_obj_t self_in);
#define STREAM_CONTENT_TYPE(stream) (((stream)->is_text) ? &mp_type_str : &mp_type_bytes)
// Returns error condition in *errcode, if non-zero, return value is number of bytes written
// before error condition occurred. If *errcode == 0, returns total bytes written (which will
// be equal to input size).
mp_uint_t mp_stream_rw(mp_obj_t stream, void *buf_, mp_uint_t size, int *errcode, byte flags) {
byte *buf = buf_;
typedef mp_uint_t (*io_func_t)(mp_obj_t obj, void *buf, mp_uint_t size, int *errcode);
io_func_t io_func;
const mp_stream_p_t *stream_p = mp_get_stream(stream);
if (flags & MP_STREAM_RW_WRITE) {
io_func = (io_func_t)stream_p->write;
} else {
io_func = stream_p->read;
}
*errcode = 0;
mp_uint_t done = 0;
while (size > 0) {
mp_uint_t out_sz = io_func(stream, buf, size, errcode);
// For read, out_sz == 0 means EOF. For write, it's unspecified
// what it means, but we don't make any progress, so returning
// is still the best option.
if (out_sz == 0) {
return done;
}
if (out_sz == MP_STREAM_ERROR) {
// If we read something before getting EAGAIN, don't leak it
if (mp_is_nonblocking_error(*errcode) && done != 0) {
*errcode = 0;
}
return done;
}
if (flags & MP_STREAM_RW_ONCE) {
return out_sz;
}
buf += out_sz;
size -= out_sz;
done += out_sz;
}
return done;
}
const mp_stream_p_t *mp_get_stream_raise(mp_obj_t self_in, int flags) {
const mp_obj_type_t *type = mp_obj_get_type(self_in);
const mp_stream_p_t *stream_p = type->protocol;
if (stream_p == NULL
|| ((flags & MP_STREAM_OP_READ) && stream_p->read == NULL)
|| ((flags & MP_STREAM_OP_WRITE) && stream_p->write == NULL)
|| ((flags & MP_STREAM_OP_IOCTL) && stream_p->ioctl == NULL)) {
// CPython: io.UnsupportedOperation, OSError subclass
mp_raise_msg(&mp_type_OSError, MP_ERROR_TEXT("stream operation not supported"));
}
return stream_p;
}
STATIC mp_obj_t stream_read_generic(size_t n_args, const mp_obj_t *args, byte flags) {
// What to do if sz < -1? Python docs don't specify this case.
// CPython does a readall, but here we silently let negatives through,
// and they will cause a MemoryError.
mp_int_t sz;
if (n_args == 1 || ((sz = mp_obj_get_int(args[1])) == -1)) {
return stream_readall(args[0]);
}
const mp_stream_p_t *stream_p = mp_get_stream(args[0]);
#if MICROPY_PY_BUILTINS_STR_UNICODE
if (stream_p->is_text) {
// We need to read sz number of unicode characters. Because we don't have any
// buffering, and because the stream API can only read bytes, we must read here
// in units of bytes and must never over read. If we want sz chars, then reading
// sz bytes will never over-read, so we follow this approach, in a loop to keep
// reading until we have exactly enough chars. This will be 1 read for text
// with ASCII-only chars, and about 2 reads for text with a couple of non-ASCII
// chars. For text with lots of non-ASCII chars, it'll be pretty inefficient
// in time and memory.
vstr_t vstr;
vstr_init(&vstr, sz);
mp_uint_t more_bytes = sz;
mp_uint_t last_buf_offset = 0;
while (more_bytes > 0) {
char *p = vstr_add_len(&vstr, more_bytes);
int error;
mp_uint_t out_sz = mp_stream_read_exactly(args[0], p, more_bytes, &error);
if (error != 0) {
vstr_cut_tail_bytes(&vstr, more_bytes);
if (mp_is_nonblocking_error(error)) {
// With non-blocking streams, we read as much as we can.
// If we read nothing, return None, just like read().
// Otherwise, return data read so far.
// TODO what if we have read only half a non-ASCII char?
if (vstr.len == 0) {
vstr_clear(&vstr);
return mp_const_none;
}
break;
}
mp_raise_OSError(error);
}
if (out_sz < more_bytes) {
// Finish reading.
// TODO what if we have read only half a non-ASCII char?
vstr_cut_tail_bytes(&vstr, more_bytes - out_sz);
if (out_sz == 0) {
break;
}
}
// count chars from bytes just read
for (mp_uint_t off = last_buf_offset;;) {
byte b = vstr.buf[off];
int n;
if (!UTF8_IS_NONASCII(b)) {
// 1-byte ASCII char
n = 1;
} else if ((b & 0xe0) == 0xc0) {
// 2-byte char
n = 2;
} else if ((b & 0xf0) == 0xe0) {
// 3-byte char
n = 3;
} else if ((b & 0xf8) == 0xf0) {
// 4-byte char
n = 4;
} else {
// TODO
n = 5;
}
if (off + n <= vstr.len) {
// got a whole char in n bytes
off += n;
sz -= 1;
last_buf_offset = off;
if (off >= vstr.len) {
more_bytes = sz;
break;
}
} else {
// didn't get a whole char, so work out how many extra bytes are needed for
// this partial char, plus bytes for additional chars that we want
more_bytes = (off + n - vstr.len) + (sz - 1);
break;
}
}
}
return mp_obj_new_str_from_vstr(&mp_type_str, &vstr);
}
#endif
vstr_t vstr;
vstr_init_len(&vstr, sz);
int error;
mp_uint_t out_sz = mp_stream_rw(args[0], vstr.buf, sz, &error, flags);
if (error != 0) {
vstr_clear(&vstr);
if (mp_is_nonblocking_error(error)) {
// https://docs.python.org/3.4/library/io.html#io.RawIOBase.read
// "If the object is in non-blocking mode and no bytes are available,
// None is returned."
// This is actually very weird, as naive truth check will treat
// this as EOF.
return mp_const_none;
}
mp_raise_OSError(error);
} else {
vstr.len = out_sz;
return mp_obj_new_str_from_vstr(STREAM_CONTENT_TYPE(stream_p), &vstr);
}
}
STATIC mp_obj_t stream_read(size_t n_args, const mp_obj_t *args) {
return stream_read_generic(n_args, args, MP_STREAM_RW_READ);
}
MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_stream_read_obj, 1, 2, stream_read);
STATIC mp_obj_t stream_read1(size_t n_args, const mp_obj_t *args) {
return stream_read_generic(n_args, args, MP_STREAM_RW_READ | MP_STREAM_RW_ONCE);
}
MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_stream_read1_obj, 1, 2, stream_read1);
mp_obj_t mp_stream_write(mp_obj_t self_in, const void *buf, size_t len, byte flags) {
int error;
mp_uint_t out_sz = mp_stream_rw(self_in, (void *)buf, len, &error, flags);
if (error != 0) {
if (mp_is_nonblocking_error(error)) {
// http://docs.python.org/3/library/io.html#io.RawIOBase.write
// "None is returned if the raw stream is set not to block and
// no single byte could be readily written to it."
return mp_const_none;
}
mp_raise_OSError(error);
} else {
return MP_OBJ_NEW_SMALL_INT(out_sz);
}
}
// This is used to adapt a stream object to an mp_print_t interface
void mp_stream_write_adaptor(void *self, const char *buf, size_t len) {
mp_stream_write(MP_OBJ_FROM_PTR(self), buf, len, MP_STREAM_RW_WRITE);
}
STATIC mp_obj_t stream_write_method(size_t n_args, const mp_obj_t *args) {
mp_buffer_info_t bufinfo;
mp_get_buffer_raise(args[1], &bufinfo, MP_BUFFER_READ);
size_t max_len = (size_t)-1;
size_t off = 0;
if (n_args == 3) {
max_len = mp_obj_get_int_truncated(args[2]);
} else if (n_args == 4) {
off = mp_obj_get_int_truncated(args[2]);
max_len = mp_obj_get_int_truncated(args[3]);
if (off > bufinfo.len) {
off = bufinfo.len;
}
}
bufinfo.len -= off;
return mp_stream_write(args[0], (byte *)bufinfo.buf + off, MIN(bufinfo.len, max_len), MP_STREAM_RW_WRITE);
}
MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_stream_write_obj, 2, 4, stream_write_method);
STATIC mp_obj_t stream_write1_method(mp_obj_t self_in, mp_obj_t arg) {
mp_buffer_info_t bufinfo;
mp_get_buffer_raise(arg, &bufinfo, MP_BUFFER_READ);
return mp_stream_write(self_in, bufinfo.buf, bufinfo.len, MP_STREAM_RW_WRITE | MP_STREAM_RW_ONCE);
}
MP_DEFINE_CONST_FUN_OBJ_2(mp_stream_write1_obj, stream_write1_method);
STATIC mp_obj_t stream_readinto(size_t n_args, const mp_obj_t *args) {
mp_buffer_info_t bufinfo;
mp_get_buffer_raise(args[1], &bufinfo, MP_BUFFER_WRITE);
// CPython extension: if 2nd arg is provided, that's max len to read,
// instead of full buffer. Similar to
// https://docs.python.org/3/library/socket.html#socket.socket.recv_into
mp_uint_t len = bufinfo.len;
if (n_args > 2) {
len = mp_obj_get_int(args[2]);
if (len > bufinfo.len) {
len = bufinfo.len;
}
}
int error;
mp_uint_t out_sz = mp_stream_read_exactly(args[0], bufinfo.buf, len, &error);
if (error != 0) {
if (mp_is_nonblocking_error(error)) {
return mp_const_none;
}
mp_raise_OSError(error);
} else {
return MP_OBJ_NEW_SMALL_INT(out_sz);
}
}
MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_stream_readinto_obj, 2, 3, stream_readinto);
STATIC mp_obj_t stream_readall(mp_obj_t self_in) {
const mp_stream_p_t *stream_p = mp_get_stream(self_in);
mp_uint_t total_size = 0;
vstr_t vstr;
vstr_init(&vstr, DEFAULT_BUFFER_SIZE);
char *p = vstr.buf;
mp_uint_t current_read = DEFAULT_BUFFER_SIZE;
while (true) {
int error;
mp_uint_t out_sz = stream_p->read(self_in, p, current_read, &error);
if (out_sz == MP_STREAM_ERROR) {
if (mp_is_nonblocking_error(error)) {
// With non-blocking streams, we read as much as we can.
// If we read nothing, return None, just like read().
// Otherwise, return data read so far.
if (total_size == 0) {
return mp_const_none;
}
break;
}
mp_raise_OSError(error);
}
if (out_sz == 0) {
break;
}
total_size += out_sz;
if (out_sz < current_read) {
current_read -= out_sz;
p += out_sz;
} else {
p = vstr_extend(&vstr, DEFAULT_BUFFER_SIZE);
current_read = DEFAULT_BUFFER_SIZE;
}
}
vstr.len = total_size;
return mp_obj_new_str_from_vstr(STREAM_CONTENT_TYPE(stream_p), &vstr);
}
// Unbuffered, inefficient implementation of readline() for raw I/O files.
STATIC mp_obj_t stream_unbuffered_readline(size_t n_args, const mp_obj_t *args) {
const mp_stream_p_t *stream_p = mp_get_stream(args[0]);
mp_int_t max_size = -1;
if (n_args > 1) {
max_size = MP_OBJ_SMALL_INT_VALUE(args[1]);
}
vstr_t vstr;
if (max_size != -1) {
vstr_init(&vstr, max_size);
} else {
vstr_init(&vstr, 16);
}
while (max_size == -1 || max_size-- != 0) {
char *p = vstr_add_len(&vstr, 1);
int error;
mp_uint_t out_sz = stream_p->read(args[0], p, 1, &error);
if (out_sz == MP_STREAM_ERROR) {
if (mp_is_nonblocking_error(error)) {
if (vstr.len == 1) {
// We just incremented it, but otherwise we read nothing
// and immediately got EAGAIN. This case is not well
// specified in
// https://docs.python.org/3/library/io.html#io.IOBase.readline
// unlike similar case for read(). But we follow the latter's
// behavior - return None.
vstr_clear(&vstr);
return mp_const_none;
} else {
goto done;
}
}
mp_raise_OSError(error);
}
if (out_sz == 0) {
done:
// Back out previously added byte
// Consider, what's better - read a char and get OutOfMemory (so read
// char is lost), or allocate first as we do.
vstr_cut_tail_bytes(&vstr, 1);
break;
}
if (*p == '\n') {
break;
}
}
return mp_obj_new_str_from_vstr(STREAM_CONTENT_TYPE(stream_p), &vstr);
}
MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_stream_unbuffered_readline_obj, 1, 2, stream_unbuffered_readline);
// TODO take an optional extra argument (what does it do exactly?)
STATIC mp_obj_t stream_unbuffered_readlines(mp_obj_t self) {
mp_obj_t lines = mp_obj_new_list(0, NULL);
for (;;) {
mp_obj_t line = stream_unbuffered_readline(1, &self);
if (!mp_obj_is_true(line)) {
break;
}
mp_obj_list_append(lines, line);
}
return lines;
}
MP_DEFINE_CONST_FUN_OBJ_1(mp_stream_unbuffered_readlines_obj, stream_unbuffered_readlines);
mp_obj_t mp_stream_unbuffered_iter(mp_obj_t self) {
mp_obj_t l_in = stream_unbuffered_readline(1, &self);
if (mp_obj_is_true(l_in)) {
return l_in;
}
return MP_OBJ_STOP_ITERATION;
}
mp_obj_t mp_stream_close(mp_obj_t stream) {
const mp_stream_p_t *stream_p = mp_get_stream(stream);
int error;
mp_uint_t res = stream_p->ioctl(stream, MP_STREAM_CLOSE, 0, &error);
if (res == MP_STREAM_ERROR) {
mp_raise_OSError(error);
}
return mp_const_none;
}
MP_DEFINE_CONST_FUN_OBJ_1(mp_stream_close_obj, mp_stream_close);
STATIC mp_obj_t stream_seek(size_t n_args, const mp_obj_t *args) {
struct mp_stream_seek_t seek_s;
// TODO: Could be uint64
seek_s.offset = mp_obj_get_int(args[1]);
seek_s.whence = SEEK_SET;
if (n_args == 3) {
seek_s.whence = mp_obj_get_int(args[2]);
}
// In POSIX, it's error to seek before end of stream, we enforce it here.
if (seek_s.whence == SEEK_SET && seek_s.offset < 0) {
mp_raise_OSError(MP_EINVAL);
}
const mp_stream_p_t *stream_p = mp_get_stream(args[0]);
int error;
mp_uint_t res = stream_p->ioctl(args[0], MP_STREAM_SEEK, (mp_uint_t)(uintptr_t)&seek_s, &error);
if (res == MP_STREAM_ERROR) {
mp_raise_OSError(error);
}
// TODO: Could be uint64
return mp_obj_new_int_from_uint(seek_s.offset);
}
MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_stream_seek_obj, 2, 3, stream_seek);
STATIC mp_obj_t stream_tell(mp_obj_t self) {
mp_obj_t offset = MP_OBJ_NEW_SMALL_INT(0);
mp_obj_t whence = MP_OBJ_NEW_SMALL_INT(SEEK_CUR);
const mp_obj_t args[3] = {self, offset, whence};
return stream_seek(3, args);
}
MP_DEFINE_CONST_FUN_OBJ_1(mp_stream_tell_obj, stream_tell);
STATIC mp_obj_t stream_flush(mp_obj_t self) {
const mp_stream_p_t *stream_p = mp_get_stream(self);
int error;
mp_uint_t res = stream_p->ioctl(self, MP_STREAM_FLUSH, 0, &error);
if (res == MP_STREAM_ERROR) {
mp_raise_OSError(error);
}
return mp_const_none;
}
MP_DEFINE_CONST_FUN_OBJ_1(mp_stream_flush_obj, stream_flush);
STATIC mp_obj_t stream_ioctl(size_t n_args, const mp_obj_t *args) {
mp_buffer_info_t bufinfo;
uintptr_t val = 0;
if (n_args > 2) {
if (mp_get_buffer(args[2], &bufinfo, MP_BUFFER_WRITE)) {
val = (uintptr_t)bufinfo.buf;
} else {
val = mp_obj_get_int_truncated(args[2]);
}
}
const mp_stream_p_t *stream_p = mp_get_stream(args[0]);
int error;
mp_uint_t res = stream_p->ioctl(args[0], mp_obj_get_int(args[1]), val, &error);
if (res == MP_STREAM_ERROR) {
mp_raise_OSError(error);
}
return mp_obj_new_int(res);
}
MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_stream_ioctl_obj, 2, 3, stream_ioctl);
#if MICROPY_STREAMS_POSIX_API
/*
* POSIX-like functions
*
* These functions have POSIX-compatible signature (except for "void *stream"
* first argument instead of "int fd"). They are useful to port existing
* POSIX-compatible software to work with MicroPython streams.
*/
#include <errno.h>
ssize_t mp_stream_posix_write(void *stream, const void *buf, size_t len) {
mp_obj_base_t *o = stream;
const mp_stream_p_t *stream_p = o->type->protocol;
mp_uint_t out_sz = stream_p->write(MP_OBJ_FROM_PTR(stream), buf, len, &errno);
if (out_sz == MP_STREAM_ERROR) {
return -1;
} else {
return out_sz;
}
}
ssize_t mp_stream_posix_read(void *stream, void *buf, size_t len) {
mp_obj_base_t *o = stream;
const mp_stream_p_t *stream_p = o->type->protocol;
mp_uint_t out_sz = stream_p->read(MP_OBJ_FROM_PTR(stream), buf, len, &errno);
if (out_sz == MP_STREAM_ERROR) {
return -1;
} else {
return out_sz;
}
}
off_t mp_stream_posix_lseek(void *stream, off_t offset, int whence) {
const mp_obj_base_t *o = stream;
const mp_stream_p_t *stream_p = o->type->protocol;
struct mp_stream_seek_t seek_s;
seek_s.offset = offset;
seek_s.whence = whence;
mp_uint_t res = stream_p->ioctl(MP_OBJ_FROM_PTR(stream), MP_STREAM_SEEK, (mp_uint_t)(uintptr_t)&seek_s, &errno);
if (res == MP_STREAM_ERROR) {
return -1;
}
return seek_s.offset;
}
int mp_stream_posix_fsync(void *stream) {
mp_obj_base_t *o = stream;
const mp_stream_p_t *stream_p = o->type->protocol;
mp_uint_t res = stream_p->ioctl(MP_OBJ_FROM_PTR(stream), MP_STREAM_FLUSH, 0, &errno);
if (res == MP_STREAM_ERROR) {
return -1;
}
return res;
}
#endif
| YifuLiu/AliOS-Things | components/py_engine/engine/py/stream.c | C | apache-2.0 | 19,905 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2013, 2014 Damien P. George
* Copyright (c) 2014-2016 Paul Sokolovsky
*
* 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.
*/
#ifndef MICROPY_INCLUDED_PY_STREAM_H
#define MICROPY_INCLUDED_PY_STREAM_H
#include "py/obj.h"
#include "py/mperrno.h"
#define MP_STREAM_ERROR ((mp_uint_t)-1)
// Stream ioctl request codes
#define MP_STREAM_FLUSH (1)
#define MP_STREAM_SEEK (2)
#define MP_STREAM_POLL (3)
#define MP_STREAM_CLOSE (4)
#define MP_STREAM_TIMEOUT (5) // Get/set timeout (single op)
#define MP_STREAM_GET_OPTS (6) // Get stream options
#define MP_STREAM_SET_OPTS (7) // Set stream options
#define MP_STREAM_GET_DATA_OPTS (8) // Get data/message options
#define MP_STREAM_SET_DATA_OPTS (9) // Set data/message options
#define MP_STREAM_GET_FILENO (10) // Get fileno of underlying file
// These poll ioctl values are compatible with Linux
#define MP_STREAM_POLL_RD (0x0001)
#define MP_STREAM_POLL_WR (0x0004)
#define MP_STREAM_POLL_ERR (0x0008)
#define MP_STREAM_POLL_HUP (0x0010)
#define MP_STREAM_POLL_NVAL (0x0020)
// Argument structure for MP_STREAM_SEEK
struct mp_stream_seek_t {
// If whence == MP_SEEK_SET, offset should be treated as unsigned.
// This allows dealing with full-width stream sizes (16, 32, 64,
// etc. bits). For other seek types, should be treated as signed.
mp_off_t offset;
int whence;
};
// seek ioctl "whence" values
#define MP_SEEK_SET (0)
#define MP_SEEK_CUR (1)
#define MP_SEEK_END (2)
// Stream protocol
typedef struct _mp_stream_p_t {
// On error, functions should return MP_STREAM_ERROR and fill in *errcode (values
// are implementation-dependent, but will be exposed to user, e.g. via exception).
mp_uint_t (*read)(mp_obj_t obj, void *buf, mp_uint_t size, int *errcode);
mp_uint_t (*write)(mp_obj_t obj, const void *buf, mp_uint_t size, int *errcode);
mp_uint_t (*ioctl)(mp_obj_t obj, mp_uint_t request, uintptr_t arg, int *errcode);
mp_uint_t is_text : 1; // default is bytes, set this for text stream
} mp_stream_p_t;
MP_DECLARE_CONST_FUN_OBJ_VAR_BETWEEN(mp_stream_read_obj);
MP_DECLARE_CONST_FUN_OBJ_VAR_BETWEEN(mp_stream_read1_obj);
MP_DECLARE_CONST_FUN_OBJ_VAR_BETWEEN(mp_stream_readinto_obj);
MP_DECLARE_CONST_FUN_OBJ_VAR_BETWEEN(mp_stream_unbuffered_readline_obj);
MP_DECLARE_CONST_FUN_OBJ_1(mp_stream_unbuffered_readlines_obj);
MP_DECLARE_CONST_FUN_OBJ_VAR_BETWEEN(mp_stream_write_obj);
MP_DECLARE_CONST_FUN_OBJ_2(mp_stream_write1_obj);
MP_DECLARE_CONST_FUN_OBJ_1(mp_stream_close_obj);
MP_DECLARE_CONST_FUN_OBJ_VAR_BETWEEN(mp_stream_seek_obj);
MP_DECLARE_CONST_FUN_OBJ_1(mp_stream_tell_obj);
MP_DECLARE_CONST_FUN_OBJ_1(mp_stream_flush_obj);
MP_DECLARE_CONST_FUN_OBJ_VAR_BETWEEN(mp_stream_ioctl_obj);
// these are for mp_get_stream_raise and can be or'd together
#define MP_STREAM_OP_READ (1)
#define MP_STREAM_OP_WRITE (2)
#define MP_STREAM_OP_IOCTL (4)
// Object is assumed to have a non-NULL stream protocol with valid r/w/ioctl methods
static inline const mp_stream_p_t *mp_get_stream(mp_const_obj_t self) {
return (const mp_stream_p_t *)((const mp_obj_base_t *)MP_OBJ_TO_PTR(self))->type->protocol;
}
const mp_stream_p_t *mp_get_stream_raise(mp_obj_t self_in, int flags);
mp_obj_t mp_stream_close(mp_obj_t stream);
// Iterator which uses mp_stream_unbuffered_readline_obj
mp_obj_t mp_stream_unbuffered_iter(mp_obj_t self);
mp_obj_t mp_stream_write(mp_obj_t self_in, const void *buf, size_t len, byte flags);
// C-level helper functions
#define MP_STREAM_RW_READ 0
#define MP_STREAM_RW_WRITE 2
#define MP_STREAM_RW_ONCE 1
mp_uint_t mp_stream_rw(mp_obj_t stream, void *buf, mp_uint_t size, int *errcode, byte flags);
#define mp_stream_write_exactly(stream, buf, size, err) mp_stream_rw(stream, (byte *)buf, size, err, MP_STREAM_RW_WRITE)
#define mp_stream_read_exactly(stream, buf, size, err) mp_stream_rw(stream, buf, size, err, MP_STREAM_RW_READ)
void mp_stream_write_adaptor(void *self, const char *buf, size_t len);
#if MICROPY_STREAMS_POSIX_API
#include <sys/types.h>
// Functions with POSIX-compatible signatures
// "stream" is assumed to be a pointer to a concrete object with the stream protocol
ssize_t mp_stream_posix_write(void *stream, const void *buf, size_t len);
ssize_t mp_stream_posix_read(void *stream, void *buf, size_t len);
off_t mp_stream_posix_lseek(void *stream, off_t offset, int whence);
int mp_stream_posix_fsync(void *stream);
#endif
#if MICROPY_STREAMS_NON_BLOCK
#define mp_is_nonblocking_error(errno) ((errno) == MP_EAGAIN || (errno) == MP_EWOULDBLOCK)
#else
#define mp_is_nonblocking_error(errno) (0)
#endif
#endif // MICROPY_INCLUDED_PY_STREAM_H
| YifuLiu/AliOS-Things | components/py_engine/engine/py/stream.h | C | apache-2.0 | 5,800 |
/*
* 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 <stdint.h>
#include "py/unicode.h"
// attribute flags
#define FL_PRINT (0x01)
#define FL_SPACE (0x02)
#define FL_DIGIT (0x04)
#define FL_ALPHA (0x08)
#define FL_UPPER (0x10)
#define FL_LOWER (0x20)
#define FL_XDIGIT (0x40)
// shorthand character attributes
#define AT_PR (FL_PRINT)
#define AT_SP (FL_SPACE | FL_PRINT)
#define AT_DI (FL_DIGIT | FL_PRINT | FL_XDIGIT)
#define AT_AL (FL_ALPHA | FL_PRINT)
#define AT_UP (FL_UPPER | FL_ALPHA | FL_PRINT)
#define AT_LO (FL_LOWER | FL_ALPHA | FL_PRINT)
#define AT_UX (FL_UPPER | FL_ALPHA | FL_PRINT | FL_XDIGIT)
#define AT_LX (FL_LOWER | FL_ALPHA | FL_PRINT | FL_XDIGIT)
// table of attributes for ascii characters
STATIC const uint8_t attr[] = {
0, 0, 0, 0, 0, 0, 0, 0,
0, AT_SP, AT_SP, AT_SP, AT_SP, AT_SP, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
AT_SP, AT_PR, AT_PR, AT_PR, AT_PR, AT_PR, AT_PR, AT_PR,
AT_PR, AT_PR, AT_PR, AT_PR, AT_PR, AT_PR, AT_PR, AT_PR,
AT_DI, AT_DI, AT_DI, AT_DI, AT_DI, AT_DI, AT_DI, AT_DI,
AT_DI, AT_DI, AT_PR, AT_PR, AT_PR, AT_PR, AT_PR, AT_PR,
AT_PR, AT_UX, AT_UX, AT_UX, AT_UX, AT_UX, AT_UX, AT_UP,
AT_UP, AT_UP, AT_UP, AT_UP, AT_UP, AT_UP, AT_UP, AT_UP,
AT_UP, AT_UP, AT_UP, AT_UP, AT_UP, AT_UP, AT_UP, AT_UP,
AT_UP, AT_UP, AT_UP, AT_PR, AT_PR, AT_PR, AT_PR, AT_PR,
AT_PR, AT_LX, AT_LX, AT_LX, AT_LX, AT_LX, AT_LX, AT_LO,
AT_LO, AT_LO, AT_LO, AT_LO, AT_LO, AT_LO, AT_LO, AT_LO,
AT_LO, AT_LO, AT_LO, AT_LO, AT_LO, AT_LO, AT_LO, AT_LO,
AT_LO, AT_LO, AT_LO, AT_PR, AT_PR, AT_PR, AT_PR, 0
};
#if MICROPY_PY_BUILTINS_STR_UNICODE
unichar utf8_get_char(const byte *s) {
unichar ord = *s++;
if (!UTF8_IS_NONASCII(ord)) {
return ord;
}
ord &= 0x7F;
for (unichar mask = 0x40; ord & mask; mask >>= 1) {
ord &= ~mask;
}
while (UTF8_IS_CONT(*s)) {
ord = (ord << 6) | (*s++ & 0x3F);
}
return ord;
}
const byte *utf8_next_char(const byte *s) {
++s;
while (UTF8_IS_CONT(*s)) {
++s;
}
return s;
}
mp_uint_t utf8_ptr_to_index(const byte *s, const byte *ptr) {
mp_uint_t i = 0;
while (ptr > s) {
if (!UTF8_IS_CONT(*--ptr)) {
i++;
}
}
return i;
}
size_t utf8_charlen(const byte *str, size_t len) {
size_t charlen = 0;
for (const byte *top = str + len; str < top; ++str) {
if (!UTF8_IS_CONT(*str)) {
++charlen;
}
}
return charlen;
}
#endif
// Be aware: These unichar_is* functions are actually ASCII-only!
bool unichar_isspace(unichar c) {
return c < 128 && (attr[c] & FL_SPACE) != 0;
}
bool unichar_isalpha(unichar c) {
return c < 128 && (attr[c] & FL_ALPHA) != 0;
}
/* unused
bool unichar_isprint(unichar c) {
return c < 128 && (attr[c] & FL_PRINT) != 0;
}
*/
bool unichar_isdigit(unichar c) {
return c < 128 && (attr[c] & FL_DIGIT) != 0;
}
bool unichar_isxdigit(unichar c) {
return c < 128 && (attr[c] & FL_XDIGIT) != 0;
}
bool unichar_isident(unichar c) {
return c < 128 && ((attr[c] & (FL_ALPHA | FL_DIGIT)) != 0 || c == '_');
}
bool unichar_isalnum(unichar c) {
return c < 128 && ((attr[c] & (FL_ALPHA | FL_DIGIT)) != 0);
}
bool unichar_isupper(unichar c) {
return c < 128 && (attr[c] & FL_UPPER) != 0;
}
bool unichar_islower(unichar c) {
return c < 128 && (attr[c] & FL_LOWER) != 0;
}
unichar unichar_tolower(unichar c) {
if (unichar_isupper(c)) {
return c + 0x20;
}
return c;
}
unichar unichar_toupper(unichar c) {
if (unichar_islower(c)) {
return c - 0x20;
}
return c;
}
mp_uint_t unichar_xdigit_value(unichar c) {
// c is assumed to be hex digit
mp_uint_t n = c - '0';
if (n > 9) {
n &= ~('a' - 'A');
n -= ('A' - ('9' + 1));
}
return n;
}
#if MICROPY_PY_BUILTINS_STR_UNICODE
bool utf8_check(const byte *p, size_t len) {
uint8_t need = 0;
const byte *end = p + len;
for (; p < end; p++) {
byte c = *p;
if (need) {
if (UTF8_IS_CONT(c)) {
need--;
} else {
// mismatch
return 0;
}
} else {
if (c >= 0xc0) {
if (c >= 0xf8) {
// mismatch
return 0;
}
need = (0xe5 >> ((c >> 3) & 0x6)) & 3;
} else if (c >= 0x80) {
// mismatch
return 0;
}
}
}
return need == 0; // no pending fragments allowed
}
#endif
| YifuLiu/AliOS-Things | components/py_engine/engine/py/unicode.c | C | apache-2.0 | 5,778 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 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.
*/
#ifndef MICROPY_INCLUDED_PY_UNICODE_H
#define MICROPY_INCLUDED_PY_UNICODE_H
#include "py/mpconfig.h"
#include "py/misc.h"
mp_uint_t utf8_ptr_to_index(const byte *s, const byte *ptr);
bool utf8_check(const byte *p, size_t len);
#endif // MICROPY_INCLUDED_PY_UNICODE_H
| YifuLiu/AliOS-Things | components/py_engine/engine/py/unicode.h | C | apache-2.0 | 1,495 |
# Create a target for all user modules to link against.
add_library(usermod INTERFACE)
function(usermod_gather_sources SOURCES_VARNAME INCLUDE_DIRECTORIES_VARNAME INCLUDED_VARNAME LIB)
if (NOT ${LIB} IN_LIST ${INCLUDED_VARNAME})
list(APPEND ${INCLUDED_VARNAME} ${LIB})
# Gather library sources
get_target_property(lib_sources ${LIB} INTERFACE_SOURCES)
if (lib_sources)
list(APPEND ${SOURCES_VARNAME} ${lib_sources})
endif()
# Gather library includes
get_target_property(lib_include_directories ${LIB} INTERFACE_INCLUDE_DIRECTORIES)
if (lib_include_directories)
list(APPEND ${INCLUDE_DIRECTORIES_VARNAME} ${lib_include_directories})
endif()
# Recurse linked libraries
get_target_property(trans_depend ${LIB} INTERFACE_LINK_LIBRARIES)
if (trans_depend)
foreach(SUB_LIB ${trans_depend})
usermod_gather_sources(
${SOURCES_VARNAME}
${INCLUDE_DIRECTORIES_VARNAME}
${INCLUDED_VARNAME}
${SUB_LIB})
endforeach()
endif()
set(${SOURCES_VARNAME} ${${SOURCES_VARNAME}} PARENT_SCOPE)
set(${INCLUDE_DIRECTORIES_VARNAME} ${${INCLUDE_DIRECTORIES_VARNAME}} PARENT_SCOPE)
set(${INCLUDED_VARNAME} ${${INCLUDED_VARNAME}} PARENT_SCOPE)
endif()
endfunction()
# Include CMake files for user modules.
if (USER_C_MODULES)
foreach(USER_C_MODULE_PATH ${USER_C_MODULES})
message("Including User C Module(s) from ${USER_C_MODULE_PATH}")
include(${USER_C_MODULE_PATH})
endforeach()
endif()
# Recursively gather sources for QSTR scanning - doesn't support generator expressions.
usermod_gather_sources(MICROPY_SOURCE_USERMOD MICROPY_INC_USERMOD found_modules usermod)
# Report found modules.
list(REMOVE_ITEM found_modules "usermod")
list(JOIN found_modules ", " found_modules)
message("Found User C Module(s): ${found_modules}")
| YifuLiu/AliOS-Things | components/py_engine/engine/py/usermod.cmake | CMake | apache-2.0 | 2,010 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2013-2019 Damien P. George
* Copyright (c) 2014-2015 Paul Sokolovsky
*
* 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 <stdio.h>
#include <string.h>
#include <assert.h>
#include "py/emitglue.h"
#include "py/objtype.h"
#include "py/runtime.h"
#include "py/bc0.h"
#include "py/bc.h"
#include "py/profile.h"
// *FORMAT-OFF*
#if 0
#if MICROPY_PY_THREAD
#define TRACE_PREFIX mp_printf(&mp_plat_print, "ts=%p sp=%d ", mp_thread_get_state(), (int)(sp - &code_state->state[0] + 1))
#else
#define TRACE_PREFIX mp_printf(&mp_plat_print, "sp=%d ", (int)(sp - &code_state->state[0] + 1))
#endif
#define TRACE(ip) TRACE_PREFIX; mp_bytecode_print2(&mp_plat_print, ip, 1, code_state->fun_bc->const_table);
#else
#define TRACE(ip)
#endif
// Value stack grows up (this makes it incompatible with native C stack, but
// makes sure that arguments to functions are in natural order arg1..argN
// (Python semantics mandates left-to-right evaluation order, including for
// function arguments). Stack pointer is pre-incremented and points at the
// top element.
// Exception stack also grows up, top element is also pointed at.
#define DECODE_UINT \
mp_uint_t unum = 0; \
do { \
unum = (unum << 7) + (*ip & 0x7f); \
} while ((*ip++ & 0x80) != 0)
#define DECODE_ULABEL size_t ulab = (ip[0] | (ip[1] << 8)); ip += 2
#define DECODE_SLABEL size_t slab = (ip[0] | (ip[1] << 8)) - 0x8000; ip += 2
#if MICROPY_PERSISTENT_CODE
#define DECODE_QSTR \
qstr qst = ip[0] | ip[1] << 8; \
ip += 2;
#define DECODE_PTR \
DECODE_UINT; \
void *ptr = (void*)(uintptr_t)code_state->fun_bc->const_table[unum]
#define DECODE_OBJ \
DECODE_UINT; \
mp_obj_t obj = (mp_obj_t)code_state->fun_bc->const_table[unum]
#else
#define DECODE_QSTR qstr qst = 0; \
do { \
qst = (qst << 7) + (*ip & 0x7f); \
} while ((*ip++ & 0x80) != 0)
#define DECODE_PTR \
ip = (byte*)MP_ALIGN(ip, sizeof(void*)); \
void *ptr = *(void**)ip; \
ip += sizeof(void*)
#define DECODE_OBJ \
ip = (byte*)MP_ALIGN(ip, sizeof(mp_obj_t)); \
mp_obj_t obj = *(mp_obj_t*)ip; \
ip += sizeof(mp_obj_t)
#endif
#define PUSH(val) *++sp = (val)
#define POP() (*sp--)
#define TOP() (*sp)
#define SET_TOP(val) *sp = (val)
#if MICROPY_PY_SYS_EXC_INFO
#define CLEAR_SYS_EXC_INFO() MP_STATE_VM(cur_exception) = NULL;
#else
#define CLEAR_SYS_EXC_INFO()
#endif
#define PUSH_EXC_BLOCK(with_or_finally) do { \
DECODE_ULABEL; /* except labels are always forward */ \
++exc_sp; \
exc_sp->handler = ip + ulab; \
exc_sp->val_sp = MP_TAGPTR_MAKE(sp, ((with_or_finally) << 1)); \
exc_sp->prev_exc = NULL; \
} while (0)
#define POP_EXC_BLOCK() \
exc_sp--; /* pop back to previous exception handler */ \
CLEAR_SYS_EXC_INFO() /* just clear sys.exc_info(), not compliant, but it shouldn't be used in 1st place */
#define CANCEL_ACTIVE_FINALLY(sp) do { \
if (mp_obj_is_small_int(sp[-1])) { \
/* Stack: (..., prev_dest_ip, prev_cause, dest_ip) */ \
/* Cancel the unwind through the previous finally, replace with current one */ \
sp[-2] = sp[0]; \
sp -= 2; \
} else { \
assert(sp[-1] == mp_const_none || mp_obj_is_exception_instance(sp[-1])); \
/* Stack: (..., None/exception, dest_ip) */ \
/* Silence the finally's exception value (may be None or an exception) */ \
sp[-1] = sp[0]; \
--sp; \
} \
} while (0)
#if MICROPY_PY_SYS_SETTRACE
#define FRAME_SETUP() do { \
assert(code_state != code_state->prev_state); \
MP_STATE_THREAD(current_code_state) = code_state; \
assert(code_state != code_state->prev_state); \
} while(0)
#define FRAME_ENTER() do { \
assert(code_state != code_state->prev_state); \
code_state->prev_state = MP_STATE_THREAD(current_code_state); \
assert(code_state != code_state->prev_state); \
if (!mp_prof_is_executing) { \
mp_prof_frame_enter(code_state); \
} \
} while(0)
#define FRAME_LEAVE() do { \
assert(code_state != code_state->prev_state); \
MP_STATE_THREAD(current_code_state) = code_state->prev_state; \
assert(code_state != code_state->prev_state); \
} while(0)
#define FRAME_UPDATE() do { \
assert(MP_STATE_THREAD(current_code_state) == code_state); \
if (!mp_prof_is_executing) { \
code_state->frame = MP_OBJ_TO_PTR(mp_prof_frame_update(code_state)); \
} \
} while(0)
#define TRACE_TICK(current_ip, current_sp, is_exception) do { \
assert(code_state != code_state->prev_state); \
assert(MP_STATE_THREAD(current_code_state) == code_state); \
if (!mp_prof_is_executing && code_state->frame && MP_STATE_THREAD(prof_trace_callback)) { \
MP_PROF_INSTR_DEBUG_PRINT(code_state->ip); \
} \
if (!mp_prof_is_executing && code_state->frame && code_state->frame->callback) { \
mp_prof_instr_tick(code_state, is_exception); \
} \
} while(0)
#else // MICROPY_PY_SYS_SETTRACE
#define FRAME_SETUP()
#define FRAME_ENTER()
#define FRAME_LEAVE()
#define FRAME_UPDATE()
#define TRACE_TICK(current_ip, current_sp, is_exception)
#endif // MICROPY_PY_SYS_SETTRACE
#if MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE
static inline mp_map_elem_t *mp_map_cached_lookup(mp_map_t *map, qstr qst, uint8_t *idx_cache) {
size_t idx = *idx_cache;
mp_obj_t key = MP_OBJ_NEW_QSTR(qst);
mp_map_elem_t *elem = NULL;
if (idx < map->alloc && map->table[idx].key == key) {
elem = &map->table[idx];
} else {
elem = mp_map_lookup(map, key, MP_MAP_LOOKUP);
if (elem != NULL) {
*idx_cache = (elem - &map->table[0]) & 0xff;
}
}
return elem;
}
#endif
// fastn has items in reverse order (fastn[0] is local[0], fastn[-1] is local[1], etc)
// sp points to bottom of stack which grows up
// returns:
// MP_VM_RETURN_NORMAL, sp valid, return value in *sp
// MP_VM_RETURN_YIELD, ip, sp valid, yielded value in *sp
// MP_VM_RETURN_EXCEPTION, exception in state[0]
mp_vm_return_kind_t mp_execute_bytecode(mp_code_state_t *code_state, volatile mp_obj_t inject_exc) {
#define SELECTIVE_EXC_IP (0)
#if SELECTIVE_EXC_IP
#define MARK_EXC_IP_SELECTIVE() { code_state->ip = ip; } /* stores ip 1 byte past last opcode */
#define MARK_EXC_IP_GLOBAL()
#else
#define MARK_EXC_IP_SELECTIVE()
#define MARK_EXC_IP_GLOBAL() { code_state->ip = ip; } /* stores ip pointing to last opcode */
#endif
#if MICROPY_OPT_COMPUTED_GOTO
#include "py/vmentrytable.h"
#define DISPATCH() do { \
TRACE(ip); \
MARK_EXC_IP_GLOBAL(); \
TRACE_TICK(ip, sp, false); \
goto *entry_table[*ip++]; \
} while (0)
#define DISPATCH_WITH_PEND_EXC_CHECK() goto pending_exception_check
#define ENTRY(op) entry_##op
#define ENTRY_DEFAULT entry_default
#else
#define DISPATCH() goto dispatch_loop
#define DISPATCH_WITH_PEND_EXC_CHECK() goto pending_exception_check
#define ENTRY(op) case op
#define ENTRY_DEFAULT default
#endif
// nlr_raise needs to be implemented as a goto, so that the C compiler's flow analyser
// sees that it's possible for us to jump from the dispatch loop to the exception
// handler. Without this, the code may have a different stack layout in the dispatch
// loop and the exception handler, leading to very obscure bugs.
#define RAISE(o) do { nlr_pop(); nlr.ret_val = MP_OBJ_TO_PTR(o); goto exception_handler; } while (0)
#if MICROPY_STACKLESS
run_code_state: ;
#endif
FRAME_ENTER();
#if MICROPY_STACKLESS
run_code_state_from_return: ;
#endif
FRAME_SETUP();
// Pointers which are constant for particular invocation of mp_execute_bytecode()
mp_obj_t * /*const*/ fastn;
mp_exc_stack_t * /*const*/ exc_stack;
{
size_t n_state = code_state->n_state;
fastn = &code_state->state[n_state - 1];
exc_stack = (mp_exc_stack_t*)(code_state->state + n_state);
}
// variables that are visible to the exception handler (declared volatile)
mp_exc_stack_t *volatile exc_sp = MP_CODE_STATE_EXC_SP_IDX_TO_PTR(exc_stack, code_state->exc_sp_idx); // stack grows up, exc_sp points to top of stack
#if MICROPY_PY_THREAD_GIL && MICROPY_PY_THREAD_GIL_VM_DIVISOR
// This needs to be volatile and outside the VM loop so it persists across handling
// of any exceptions. Otherwise it's possible that the VM never gives up the GIL.
volatile int gil_divisor = MICROPY_PY_THREAD_GIL_VM_DIVISOR;
#endif
// outer exception handling loop
for (;;) {
nlr_buf_t nlr;
outer_dispatch_loop:
if (nlr_push(&nlr) == 0) {
// local variables that are not visible to the exception handler
const byte *ip = code_state->ip;
mp_obj_t *sp = code_state->sp;
mp_obj_t obj_shared;
MICROPY_VM_HOOK_INIT
// If we have exception to inject, now that we finish setting up
// execution context, raise it. This works as if MP_BC_RAISE_OBJ
// bytecode was executed.
// Injecting exc into yield from generator is a special case,
// handled by MP_BC_YIELD_FROM itself
if (inject_exc != MP_OBJ_NULL && *ip != MP_BC_YIELD_FROM) {
mp_obj_t exc = inject_exc;
inject_exc = MP_OBJ_NULL;
exc = mp_make_raise_obj(exc);
RAISE(exc);
}
// loop to execute byte code
for (;;) {
dispatch_loop:
#if MICROPY_OPT_COMPUTED_GOTO
DISPATCH();
#else
TRACE(ip);
MARK_EXC_IP_GLOBAL();
TRACE_TICK(ip, sp, false);
switch (*ip++) {
#endif
ENTRY(MP_BC_LOAD_CONST_FALSE):
PUSH(mp_const_false);
DISPATCH();
ENTRY(MP_BC_LOAD_CONST_NONE):
PUSH(mp_const_none);
DISPATCH();
ENTRY(MP_BC_LOAD_CONST_TRUE):
PUSH(mp_const_true);
DISPATCH();
ENTRY(MP_BC_LOAD_CONST_SMALL_INT): {
mp_uint_t num = 0;
if ((ip[0] & 0x40) != 0) {
// Number is negative
num--;
}
do {
num = (num << 7) | (*ip & 0x7f);
} while ((*ip++ & 0x80) != 0);
PUSH(MP_OBJ_NEW_SMALL_INT(num));
DISPATCH();
}
ENTRY(MP_BC_LOAD_CONST_STRING): {
DECODE_QSTR;
PUSH(MP_OBJ_NEW_QSTR(qst));
DISPATCH();
}
ENTRY(MP_BC_LOAD_CONST_OBJ): {
DECODE_OBJ;
PUSH(obj);
DISPATCH();
}
ENTRY(MP_BC_LOAD_NULL):
PUSH(MP_OBJ_NULL);
DISPATCH();
ENTRY(MP_BC_LOAD_FAST_N): {
DECODE_UINT;
obj_shared = fastn[-unum];
load_check:
if (obj_shared == MP_OBJ_NULL) {
local_name_error: {
MARK_EXC_IP_SELECTIVE();
mp_obj_t obj = mp_obj_new_exception_msg(&mp_type_NameError, MP_ERROR_TEXT("local variable referenced before assignment"));
RAISE(obj);
}
}
PUSH(obj_shared);
DISPATCH();
}
ENTRY(MP_BC_LOAD_DEREF): {
DECODE_UINT;
obj_shared = mp_obj_cell_get(fastn[-unum]);
goto load_check;
}
#if !MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE
ENTRY(MP_BC_LOAD_NAME): {
MARK_EXC_IP_SELECTIVE();
DECODE_QSTR;
PUSH(mp_load_name(qst));
DISPATCH();
}
#else
ENTRY(MP_BC_LOAD_NAME): {
MARK_EXC_IP_SELECTIVE();
DECODE_QSTR;
mp_map_elem_t *elem = mp_map_cached_lookup(&mp_locals_get()->map, qst, (uint8_t*)ip);
mp_obj_t obj;
if (elem != NULL) {
obj = elem->value;
} else {
obj = mp_load_name(qst);
}
PUSH(obj);
ip++;
DISPATCH();
}
#endif
#if !MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE
ENTRY(MP_BC_LOAD_GLOBAL): {
MARK_EXC_IP_SELECTIVE();
DECODE_QSTR;
PUSH(mp_load_global(qst));
DISPATCH();
}
#else
ENTRY(MP_BC_LOAD_GLOBAL): {
MARK_EXC_IP_SELECTIVE();
DECODE_QSTR;
mp_map_elem_t *elem = mp_map_cached_lookup(&mp_globals_get()->map, qst, (uint8_t*)ip);
mp_obj_t obj;
if (elem != NULL) {
obj = elem->value;
} else {
obj = mp_load_global(qst);
}
PUSH(obj);
ip++;
DISPATCH();
}
#endif
#if !MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE
ENTRY(MP_BC_LOAD_ATTR): {
FRAME_UPDATE();
MARK_EXC_IP_SELECTIVE();
DECODE_QSTR;
SET_TOP(mp_load_attr(TOP(), qst));
DISPATCH();
}
#else
ENTRY(MP_BC_LOAD_ATTR): {
FRAME_UPDATE();
MARK_EXC_IP_SELECTIVE();
DECODE_QSTR;
mp_obj_t top = TOP();
mp_map_elem_t *elem = NULL;
if (mp_obj_is_instance_type(mp_obj_get_type(top))) {
mp_obj_instance_t *self = MP_OBJ_TO_PTR(top);
elem = mp_map_cached_lookup(&self->members, qst, (uint8_t*)ip);
}
mp_obj_t obj;
if (elem != NULL) {
obj = elem->value;
} else {
obj = mp_load_attr(top, qst);
}
SET_TOP(obj);
ip++;
DISPATCH();
}
#endif
ENTRY(MP_BC_LOAD_METHOD): {
MARK_EXC_IP_SELECTIVE();
DECODE_QSTR;
mp_load_method(*sp, qst, sp);
sp += 1;
DISPATCH();
}
ENTRY(MP_BC_LOAD_SUPER_METHOD): {
MARK_EXC_IP_SELECTIVE();
DECODE_QSTR;
sp -= 1;
mp_load_super_method(qst, sp - 1);
DISPATCH();
}
ENTRY(MP_BC_LOAD_BUILD_CLASS):
MARK_EXC_IP_SELECTIVE();
PUSH(mp_load_build_class());
DISPATCH();
ENTRY(MP_BC_LOAD_SUBSCR): {
MARK_EXC_IP_SELECTIVE();
mp_obj_t index = POP();
SET_TOP(mp_obj_subscr(TOP(), index, MP_OBJ_SENTINEL));
DISPATCH();
}
ENTRY(MP_BC_STORE_FAST_N): {
DECODE_UINT;
fastn[-unum] = POP();
DISPATCH();
}
ENTRY(MP_BC_STORE_DEREF): {
DECODE_UINT;
mp_obj_cell_set(fastn[-unum], POP());
DISPATCH();
}
ENTRY(MP_BC_STORE_NAME): {
MARK_EXC_IP_SELECTIVE();
DECODE_QSTR;
mp_store_name(qst, POP());
DISPATCH();
}
ENTRY(MP_BC_STORE_GLOBAL): {
MARK_EXC_IP_SELECTIVE();
DECODE_QSTR;
mp_store_global(qst, POP());
DISPATCH();
}
#if !MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE
ENTRY(MP_BC_STORE_ATTR): {
FRAME_UPDATE();
MARK_EXC_IP_SELECTIVE();
DECODE_QSTR;
mp_store_attr(sp[0], qst, sp[-1]);
sp -= 2;
DISPATCH();
}
#else
// This caching code works with MICROPY_PY_BUILTINS_PROPERTY and/or
// MICROPY_PY_DESCRIPTORS enabled because if the attr exists in
// self->members then it can't be a property or have descriptors. A
// consequence of this is that we can't use MP_MAP_LOOKUP_ADD_IF_NOT_FOUND
// in the fast-path below, because that store could override a property.
ENTRY(MP_BC_STORE_ATTR): {
FRAME_UPDATE();
MARK_EXC_IP_SELECTIVE();
DECODE_QSTR;
mp_map_elem_t *elem = NULL;
mp_obj_t top = TOP();
if (mp_obj_is_instance_type(mp_obj_get_type(top)) && sp[-1] != MP_OBJ_NULL) {
mp_obj_instance_t *self = MP_OBJ_TO_PTR(top);
elem = mp_map_cached_lookup(&self->members, qst, (uint8_t*)ip);
}
if (elem != NULL) {
elem->value = sp[-1];
} else {
mp_store_attr(sp[0], qst, sp[-1]);
}
sp -= 2;
ip++;
DISPATCH();
}
#endif
ENTRY(MP_BC_STORE_SUBSCR):
MARK_EXC_IP_SELECTIVE();
mp_obj_subscr(sp[-1], sp[0], sp[-2]);
sp -= 3;
DISPATCH();
ENTRY(MP_BC_DELETE_FAST): {
MARK_EXC_IP_SELECTIVE();
DECODE_UINT;
if (fastn[-unum] == MP_OBJ_NULL) {
goto local_name_error;
}
fastn[-unum] = MP_OBJ_NULL;
DISPATCH();
}
ENTRY(MP_BC_DELETE_DEREF): {
MARK_EXC_IP_SELECTIVE();
DECODE_UINT;
if (mp_obj_cell_get(fastn[-unum]) == MP_OBJ_NULL) {
goto local_name_error;
}
mp_obj_cell_set(fastn[-unum], MP_OBJ_NULL);
DISPATCH();
}
ENTRY(MP_BC_DELETE_NAME): {
MARK_EXC_IP_SELECTIVE();
DECODE_QSTR;
mp_delete_name(qst);
DISPATCH();
}
ENTRY(MP_BC_DELETE_GLOBAL): {
MARK_EXC_IP_SELECTIVE();
DECODE_QSTR;
mp_delete_global(qst);
DISPATCH();
}
ENTRY(MP_BC_DUP_TOP): {
mp_obj_t top = TOP();
PUSH(top);
DISPATCH();
}
ENTRY(MP_BC_DUP_TOP_TWO):
sp += 2;
sp[0] = sp[-2];
sp[-1] = sp[-3];
DISPATCH();
ENTRY(MP_BC_POP_TOP):
sp -= 1;
DISPATCH();
ENTRY(MP_BC_ROT_TWO): {
mp_obj_t top = sp[0];
sp[0] = sp[-1];
sp[-1] = top;
DISPATCH();
}
ENTRY(MP_BC_ROT_THREE): {
mp_obj_t top = sp[0];
sp[0] = sp[-1];
sp[-1] = sp[-2];
sp[-2] = top;
DISPATCH();
}
ENTRY(MP_BC_JUMP): {
DECODE_SLABEL;
ip += slab;
DISPATCH_WITH_PEND_EXC_CHECK();
}
ENTRY(MP_BC_POP_JUMP_IF_TRUE): {
DECODE_SLABEL;
if (mp_obj_is_true(POP())) {
ip += slab;
}
DISPATCH_WITH_PEND_EXC_CHECK();
}
ENTRY(MP_BC_POP_JUMP_IF_FALSE): {
DECODE_SLABEL;
if (!mp_obj_is_true(POP())) {
ip += slab;
}
DISPATCH_WITH_PEND_EXC_CHECK();
}
ENTRY(MP_BC_JUMP_IF_TRUE_OR_POP): {
DECODE_SLABEL;
if (mp_obj_is_true(TOP())) {
ip += slab;
} else {
sp--;
}
DISPATCH_WITH_PEND_EXC_CHECK();
}
ENTRY(MP_BC_JUMP_IF_FALSE_OR_POP): {
DECODE_SLABEL;
if (mp_obj_is_true(TOP())) {
sp--;
} else {
ip += slab;
}
DISPATCH_WITH_PEND_EXC_CHECK();
}
ENTRY(MP_BC_SETUP_WITH): {
MARK_EXC_IP_SELECTIVE();
// stack: (..., ctx_mgr)
mp_obj_t obj = TOP();
mp_load_method(obj, MP_QSTR___exit__, sp);
mp_load_method(obj, MP_QSTR___enter__, sp + 2);
mp_obj_t ret = mp_call_method_n_kw(0, 0, sp + 2);
sp += 1;
PUSH_EXC_BLOCK(1);
PUSH(ret);
// stack: (..., __exit__, ctx_mgr, as_value)
DISPATCH();
}
ENTRY(MP_BC_WITH_CLEANUP): {
MARK_EXC_IP_SELECTIVE();
// Arriving here, there's "exception control block" on top of stack,
// and __exit__ method (with self) underneath it. Bytecode calls __exit__,
// and "deletes" it off stack, shifting "exception control block"
// to its place.
// The bytecode emitter ensures that there is enough space on the Python
// value stack to hold the __exit__ method plus an additional 4 entries.
if (TOP() == mp_const_none) {
// stack: (..., __exit__, ctx_mgr, None)
sp[1] = mp_const_none;
sp[2] = mp_const_none;
sp -= 2;
mp_call_method_n_kw(3, 0, sp);
SET_TOP(mp_const_none);
} else if (mp_obj_is_small_int(TOP())) {
// Getting here there are two distinct cases:
// - unwind return, stack: (..., __exit__, ctx_mgr, ret_val, SMALL_INT(-1))
// - unwind jump, stack: (..., __exit__, ctx_mgr, dest_ip, SMALL_INT(num_exc))
// For both cases we do exactly the same thing.
mp_obj_t data = sp[-1];
mp_obj_t cause = sp[0];
sp[-1] = mp_const_none;
sp[0] = mp_const_none;
sp[1] = mp_const_none;
mp_call_method_n_kw(3, 0, sp - 3);
sp[-3] = data;
sp[-2] = cause;
sp -= 2; // we removed (__exit__, ctx_mgr)
} else {
assert(mp_obj_is_exception_instance(TOP()));
// stack: (..., __exit__, ctx_mgr, exc_instance)
// Need to pass (exc_type, exc_instance, None) as arguments to __exit__.
sp[1] = sp[0];
sp[0] = MP_OBJ_FROM_PTR(mp_obj_get_type(sp[0]));
sp[2] = mp_const_none;
sp -= 2;
mp_obj_t ret_value = mp_call_method_n_kw(3, 0, sp);
if (mp_obj_is_true(ret_value)) {
// We need to silence/swallow the exception. This is done
// by popping the exception and the __exit__ handler and
// replacing it with None, which signals END_FINALLY to just
// execute the finally handler normally.
SET_TOP(mp_const_none);
} else {
// We need to re-raise the exception. We pop __exit__ handler
// by copying the exception instance down to the new top-of-stack.
sp[0] = sp[3];
}
}
DISPATCH();
}
ENTRY(MP_BC_UNWIND_JUMP): {
MARK_EXC_IP_SELECTIVE();
DECODE_SLABEL;
PUSH((mp_obj_t)(mp_uint_t)(uintptr_t)(ip + slab)); // push destination ip for jump
PUSH((mp_obj_t)(mp_uint_t)(*ip)); // push number of exception handlers to unwind (0x80 bit set if we also need to pop stack)
unwind_jump:;
mp_uint_t unum = (mp_uint_t)POP(); // get number of exception handlers to unwind
while ((unum & 0x7f) > 0) {
unum -= 1;
assert(exc_sp >= exc_stack);
if (MP_TAGPTR_TAG1(exc_sp->val_sp)) {
if (exc_sp->handler > ip) {
// Found a finally handler that isn't active; run it.
// Getting here the stack looks like:
// (..., X, dest_ip)
// where X is pointed to by exc_sp->val_sp and in the case
// of a "with" block contains the context manager info.
assert(&sp[-1] == MP_TAGPTR_PTR(exc_sp->val_sp));
// We're going to run "finally" code as a coroutine
// (not calling it recursively). Set up a sentinel
// on the stack so it can return back to us when it is
// done (when WITH_CLEANUP or END_FINALLY reached).
// The sentinel is the number of exception handlers left to
// unwind, which is a non-negative integer.
PUSH(MP_OBJ_NEW_SMALL_INT(unum));
ip = exc_sp->handler;
goto dispatch_loop;
} else {
// Found a finally handler that is already active; cancel it.
CANCEL_ACTIVE_FINALLY(sp);
}
}
POP_EXC_BLOCK();
}
ip = (const byte*)MP_OBJ_TO_PTR(POP()); // pop destination ip for jump
if (unum != 0) {
// pop the exhausted iterator
sp -= MP_OBJ_ITER_BUF_NSLOTS;
}
DISPATCH_WITH_PEND_EXC_CHECK();
}
ENTRY(MP_BC_SETUP_EXCEPT):
ENTRY(MP_BC_SETUP_FINALLY): {
MARK_EXC_IP_SELECTIVE();
#if SELECTIVE_EXC_IP
PUSH_EXC_BLOCK((code_state->ip[-1] == MP_BC_SETUP_FINALLY) ? 1 : 0);
#else
PUSH_EXC_BLOCK((code_state->ip[0] == MP_BC_SETUP_FINALLY) ? 1 : 0);
#endif
DISPATCH();
}
ENTRY(MP_BC_END_FINALLY):
MARK_EXC_IP_SELECTIVE();
// if TOS is None, just pops it and continues
// if TOS is an integer, finishes coroutine and returns control to caller
// if TOS is an exception, reraises the exception
assert(exc_sp >= exc_stack);
POP_EXC_BLOCK();
if (TOP() == mp_const_none) {
sp--;
} else if (mp_obj_is_small_int(TOP())) {
// We finished "finally" coroutine and now dispatch back
// to our caller, based on TOS value
mp_int_t cause = MP_OBJ_SMALL_INT_VALUE(POP());
if (cause < 0) {
// A negative cause indicates unwind return
goto unwind_return;
} else {
// Otherwise it's an unwind jump and we must push as a raw
// number the number of exception handlers to unwind
PUSH((mp_obj_t)cause);
goto unwind_jump;
}
} else {
assert(mp_obj_is_exception_instance(TOP()));
RAISE(TOP());
}
DISPATCH();
ENTRY(MP_BC_GET_ITER):
MARK_EXC_IP_SELECTIVE();
SET_TOP(mp_getiter(TOP(), NULL));
DISPATCH();
// An iterator for a for-loop takes MP_OBJ_ITER_BUF_NSLOTS slots on
// the Python value stack. These slots are either used to store the
// iterator object itself, or the first slot is MP_OBJ_NULL and
// the second slot holds a reference to the iterator object.
ENTRY(MP_BC_GET_ITER_STACK): {
MARK_EXC_IP_SELECTIVE();
mp_obj_t obj = TOP();
mp_obj_iter_buf_t *iter_buf = (mp_obj_iter_buf_t*)sp;
sp += MP_OBJ_ITER_BUF_NSLOTS - 1;
obj = mp_getiter(obj, iter_buf);
if (obj != MP_OBJ_FROM_PTR(iter_buf)) {
// Iterator didn't use the stack so indicate that with MP_OBJ_NULL.
sp[-MP_OBJ_ITER_BUF_NSLOTS + 1] = MP_OBJ_NULL;
sp[-MP_OBJ_ITER_BUF_NSLOTS + 2] = obj;
}
DISPATCH();
}
ENTRY(MP_BC_FOR_ITER): {
FRAME_UPDATE();
MARK_EXC_IP_SELECTIVE();
DECODE_ULABEL; // the jump offset if iteration finishes; for labels are always forward
code_state->sp = sp;
mp_obj_t obj;
if (sp[-MP_OBJ_ITER_BUF_NSLOTS + 1] == MP_OBJ_NULL) {
obj = sp[-MP_OBJ_ITER_BUF_NSLOTS + 2];
} else {
obj = MP_OBJ_FROM_PTR(&sp[-MP_OBJ_ITER_BUF_NSLOTS + 1]);
}
mp_obj_t value = mp_iternext_allow_raise(obj);
if (value == MP_OBJ_STOP_ITERATION) {
sp -= MP_OBJ_ITER_BUF_NSLOTS; // pop the exhausted iterator
ip += ulab; // jump to after for-block
} else {
PUSH(value); // push the next iteration value
#if MICROPY_PY_SYS_SETTRACE
// LINE event should trigger for every iteration so invalidate last trigger
if (code_state->frame) {
code_state->frame->lineno = 0;
}
#endif
}
DISPATCH();
}
ENTRY(MP_BC_POP_EXCEPT_JUMP): {
assert(exc_sp >= exc_stack);
POP_EXC_BLOCK();
DECODE_ULABEL;
ip += ulab;
DISPATCH_WITH_PEND_EXC_CHECK();
}
ENTRY(MP_BC_BUILD_TUPLE): {
MARK_EXC_IP_SELECTIVE();
DECODE_UINT;
sp -= unum - 1;
SET_TOP(mp_obj_new_tuple(unum, sp));
DISPATCH();
}
ENTRY(MP_BC_BUILD_LIST): {
MARK_EXC_IP_SELECTIVE();
DECODE_UINT;
sp -= unum - 1;
SET_TOP(mp_obj_new_list(unum, sp));
DISPATCH();
}
ENTRY(MP_BC_BUILD_MAP): {
MARK_EXC_IP_SELECTIVE();
DECODE_UINT;
PUSH(mp_obj_new_dict(unum));
DISPATCH();
}
ENTRY(MP_BC_STORE_MAP):
MARK_EXC_IP_SELECTIVE();
sp -= 2;
mp_obj_dict_store(sp[0], sp[2], sp[1]);
DISPATCH();
#if MICROPY_PY_BUILTINS_SET
ENTRY(MP_BC_BUILD_SET): {
MARK_EXC_IP_SELECTIVE();
DECODE_UINT;
sp -= unum - 1;
SET_TOP(mp_obj_new_set(unum, sp));
DISPATCH();
}
#endif
#if MICROPY_PY_BUILTINS_SLICE
ENTRY(MP_BC_BUILD_SLICE): {
MARK_EXC_IP_SELECTIVE();
mp_obj_t step = mp_const_none;
if (*ip++ == 3) {
// 3-argument slice includes step
step = POP();
}
mp_obj_t stop = POP();
mp_obj_t start = TOP();
SET_TOP(mp_obj_new_slice(start, stop, step));
DISPATCH();
}
#endif
ENTRY(MP_BC_STORE_COMP): {
MARK_EXC_IP_SELECTIVE();
DECODE_UINT;
mp_obj_t obj = sp[-(unum >> 2)];
if ((unum & 3) == 0) {
mp_obj_list_append(obj, sp[0]);
sp--;
} else if (!MICROPY_PY_BUILTINS_SET || (unum & 3) == 1) {
mp_obj_dict_store(obj, sp[0], sp[-1]);
sp -= 2;
#if MICROPY_PY_BUILTINS_SET
} else {
mp_obj_set_store(obj, sp[0]);
sp--;
#endif
}
DISPATCH();
}
ENTRY(MP_BC_UNPACK_SEQUENCE): {
MARK_EXC_IP_SELECTIVE();
DECODE_UINT;
mp_unpack_sequence(sp[0], unum, sp);
sp += unum - 1;
DISPATCH();
}
ENTRY(MP_BC_UNPACK_EX): {
MARK_EXC_IP_SELECTIVE();
DECODE_UINT;
mp_unpack_ex(sp[0], unum, sp);
sp += (unum & 0xff) + ((unum >> 8) & 0xff);
DISPATCH();
}
ENTRY(MP_BC_MAKE_FUNCTION): {
DECODE_PTR;
PUSH(mp_make_function_from_raw_code(ptr, MP_OBJ_NULL, MP_OBJ_NULL));
DISPATCH();
}
ENTRY(MP_BC_MAKE_FUNCTION_DEFARGS): {
DECODE_PTR;
// Stack layout: def_tuple def_dict <- TOS
mp_obj_t def_dict = POP();
SET_TOP(mp_make_function_from_raw_code(ptr, TOP(), def_dict));
DISPATCH();
}
ENTRY(MP_BC_MAKE_CLOSURE): {
DECODE_PTR;
size_t n_closed_over = *ip++;
// Stack layout: closed_overs <- TOS
sp -= n_closed_over - 1;
SET_TOP(mp_make_closure_from_raw_code(ptr, n_closed_over, sp));
DISPATCH();
}
ENTRY(MP_BC_MAKE_CLOSURE_DEFARGS): {
DECODE_PTR;
size_t n_closed_over = *ip++;
// Stack layout: def_tuple def_dict closed_overs <- TOS
sp -= 2 + n_closed_over - 1;
SET_TOP(mp_make_closure_from_raw_code(ptr, 0x100 | n_closed_over, sp));
DISPATCH();
}
ENTRY(MP_BC_CALL_FUNCTION): {
FRAME_UPDATE();
MARK_EXC_IP_SELECTIVE();
DECODE_UINT;
// unum & 0xff == n_positional
// (unum >> 8) & 0xff == n_keyword
sp -= (unum & 0xff) + ((unum >> 7) & 0x1fe);
#if MICROPY_STACKLESS
if (mp_obj_get_type(*sp) == &mp_type_fun_bc) {
code_state->ip = ip;
code_state->sp = sp;
code_state->exc_sp_idx = MP_CODE_STATE_EXC_SP_IDX_FROM_PTR(exc_stack, exc_sp);
mp_code_state_t *new_state = mp_obj_fun_bc_prepare_codestate(*sp, unum & 0xff, (unum >> 8) & 0xff, sp + 1);
#if !MICROPY_ENABLE_PYSTACK
if (new_state == NULL) {
// Couldn't allocate codestate on heap: in the strict case raise
// an exception, otherwise just fall through to stack allocation.
#if MICROPY_STACKLESS_STRICT
deep_recursion_error:
mp_raise_recursion_depth();
#endif
} else
#endif
{
new_state->prev = code_state;
code_state = new_state;
nlr_pop();
goto run_code_state;
}
}
#endif
SET_TOP(mp_call_function_n_kw(*sp, unum & 0xff, (unum >> 8) & 0xff, sp + 1));
DISPATCH();
}
ENTRY(MP_BC_CALL_FUNCTION_VAR_KW): {
FRAME_UPDATE();
MARK_EXC_IP_SELECTIVE();
DECODE_UINT;
// unum & 0xff == n_positional
// (unum >> 8) & 0xff == n_keyword
// We have following stack layout here:
// fun arg0 arg1 ... kw0 val0 kw1 val1 ... seq dict <- TOS
sp -= (unum & 0xff) + ((unum >> 7) & 0x1fe) + 2;
#if MICROPY_STACKLESS
if (mp_obj_get_type(*sp) == &mp_type_fun_bc) {
code_state->ip = ip;
code_state->sp = sp;
code_state->exc_sp_idx = MP_CODE_STATE_EXC_SP_IDX_FROM_PTR(exc_stack, exc_sp);
mp_call_args_t out_args;
mp_call_prepare_args_n_kw_var(false, unum, sp, &out_args);
mp_code_state_t *new_state = mp_obj_fun_bc_prepare_codestate(out_args.fun,
out_args.n_args, out_args.n_kw, out_args.args);
#if !MICROPY_ENABLE_PYSTACK
// Freeing args at this point does not follow a LIFO order so only do it if
// pystack is not enabled. For pystack, they are freed when code_state is.
mp_nonlocal_free(out_args.args, out_args.n_alloc * sizeof(mp_obj_t));
#endif
#if !MICROPY_ENABLE_PYSTACK
if (new_state == NULL) {
// Couldn't allocate codestate on heap: in the strict case raise
// an exception, otherwise just fall through to stack allocation.
#if MICROPY_STACKLESS_STRICT
goto deep_recursion_error;
#endif
} else
#endif
{
new_state->prev = code_state;
code_state = new_state;
nlr_pop();
goto run_code_state;
}
}
#endif
SET_TOP(mp_call_method_n_kw_var(false, unum, sp));
DISPATCH();
}
ENTRY(MP_BC_CALL_METHOD): {
FRAME_UPDATE();
MARK_EXC_IP_SELECTIVE();
DECODE_UINT;
// unum & 0xff == n_positional
// (unum >> 8) & 0xff == n_keyword
sp -= (unum & 0xff) + ((unum >> 7) & 0x1fe) + 1;
#if MICROPY_STACKLESS
if (mp_obj_get_type(*sp) == &mp_type_fun_bc) {
code_state->ip = ip;
code_state->sp = sp;
code_state->exc_sp_idx = MP_CODE_STATE_EXC_SP_IDX_FROM_PTR(exc_stack, exc_sp);
size_t n_args = unum & 0xff;
size_t n_kw = (unum >> 8) & 0xff;
int adjust = (sp[1] == MP_OBJ_NULL) ? 0 : 1;
mp_code_state_t *new_state = mp_obj_fun_bc_prepare_codestate(*sp, n_args + adjust, n_kw, sp + 2 - adjust);
#if !MICROPY_ENABLE_PYSTACK
if (new_state == NULL) {
// Couldn't allocate codestate on heap: in the strict case raise
// an exception, otherwise just fall through to stack allocation.
#if MICROPY_STACKLESS_STRICT
goto deep_recursion_error;
#endif
} else
#endif
{
new_state->prev = code_state;
code_state = new_state;
nlr_pop();
goto run_code_state;
}
}
#endif
SET_TOP(mp_call_method_n_kw(unum & 0xff, (unum >> 8) & 0xff, sp));
DISPATCH();
}
ENTRY(MP_BC_CALL_METHOD_VAR_KW): {
FRAME_UPDATE();
MARK_EXC_IP_SELECTIVE();
DECODE_UINT;
// unum & 0xff == n_positional
// (unum >> 8) & 0xff == n_keyword
// We have following stack layout here:
// fun self arg0 arg1 ... kw0 val0 kw1 val1 ... seq dict <- TOS
sp -= (unum & 0xff) + ((unum >> 7) & 0x1fe) + 3;
#if MICROPY_STACKLESS
if (mp_obj_get_type(*sp) == &mp_type_fun_bc) {
code_state->ip = ip;
code_state->sp = sp;
code_state->exc_sp_idx = MP_CODE_STATE_EXC_SP_IDX_FROM_PTR(exc_stack, exc_sp);
mp_call_args_t out_args;
mp_call_prepare_args_n_kw_var(true, unum, sp, &out_args);
mp_code_state_t *new_state = mp_obj_fun_bc_prepare_codestate(out_args.fun,
out_args.n_args, out_args.n_kw, out_args.args);
#if !MICROPY_ENABLE_PYSTACK
// Freeing args at this point does not follow a LIFO order so only do it if
// pystack is not enabled. For pystack, they are freed when code_state is.
mp_nonlocal_free(out_args.args, out_args.n_alloc * sizeof(mp_obj_t));
#endif
#if !MICROPY_ENABLE_PYSTACK
if (new_state == NULL) {
// Couldn't allocate codestate on heap: in the strict case raise
// an exception, otherwise just fall through to stack allocation.
#if MICROPY_STACKLESS_STRICT
goto deep_recursion_error;
#endif
} else
#endif
{
new_state->prev = code_state;
code_state = new_state;
nlr_pop();
goto run_code_state;
}
}
#endif
SET_TOP(mp_call_method_n_kw_var(true, unum, sp));
DISPATCH();
}
ENTRY(MP_BC_RETURN_VALUE):
MARK_EXC_IP_SELECTIVE();
unwind_return:
// Search for and execute finally handlers that aren't already active
while (exc_sp >= exc_stack) {
if (MP_TAGPTR_TAG1(exc_sp->val_sp)) {
if (exc_sp->handler > ip) {
// Found a finally handler that isn't active; run it.
// Getting here the stack looks like:
// (..., X, [iter0, iter1, ...,] ret_val)
// where X is pointed to by exc_sp->val_sp and in the case
// of a "with" block contains the context manager info.
// There may be 0 or more for-iterators between X and the
// return value, and these must be removed before control can
// pass to the finally code. We simply copy the ret_value down
// over these iterators, if they exist. If they don't then the
// following is a null operation.
mp_obj_t *finally_sp = MP_TAGPTR_PTR(exc_sp->val_sp);
finally_sp[1] = sp[0];
sp = &finally_sp[1];
// We're going to run "finally" code as a coroutine
// (not calling it recursively). Set up a sentinel
// on a stack so it can return back to us when it is
// done (when WITH_CLEANUP or END_FINALLY reached).
PUSH(MP_OBJ_NEW_SMALL_INT(-1));
ip = exc_sp->handler;
goto dispatch_loop;
} else {
// Found a finally handler that is already active; cancel it.
CANCEL_ACTIVE_FINALLY(sp);
}
}
POP_EXC_BLOCK();
}
nlr_pop();
code_state->sp = sp;
assert(exc_sp == exc_stack - 1);
MICROPY_VM_HOOK_RETURN
#if MICROPY_STACKLESS
if (code_state->prev != NULL) {
mp_obj_t res = *sp;
mp_globals_set(code_state->old_globals);
mp_code_state_t *new_code_state = code_state->prev;
#if MICROPY_ENABLE_PYSTACK
// Free code_state, and args allocated by mp_call_prepare_args_n_kw_var
// (The latter is implicitly freed when using pystack due to its LIFO nature.)
// The sizeof in the following statement does not include the size of the variable
// part of the struct. This arg is anyway not used if pystack is enabled.
mp_nonlocal_free(code_state, sizeof(mp_code_state_t));
#endif
code_state = new_code_state;
*code_state->sp = res;
goto run_code_state_from_return;
}
#endif
FRAME_LEAVE();
return MP_VM_RETURN_NORMAL;
ENTRY(MP_BC_RAISE_LAST): {
MARK_EXC_IP_SELECTIVE();
// search for the inner-most previous exception, to reraise it
mp_obj_t obj = MP_OBJ_NULL;
for (mp_exc_stack_t *e = exc_sp; e >= exc_stack; --e) {
if (e->prev_exc != NULL) {
obj = MP_OBJ_FROM_PTR(e->prev_exc);
break;
}
}
if (obj == MP_OBJ_NULL) {
obj = mp_obj_new_exception_msg(&mp_type_RuntimeError, MP_ERROR_TEXT("no active exception to reraise"));
}
RAISE(obj);
}
ENTRY(MP_BC_RAISE_OBJ): {
MARK_EXC_IP_SELECTIVE();
mp_obj_t obj = mp_make_raise_obj(TOP());
RAISE(obj);
}
ENTRY(MP_BC_RAISE_FROM): {
MARK_EXC_IP_SELECTIVE();
mp_warning(NULL, "exception chaining not supported");
sp--; // ignore (pop) "from" argument
mp_obj_t obj = mp_make_raise_obj(TOP());
RAISE(obj);
}
ENTRY(MP_BC_YIELD_VALUE):
yield:
nlr_pop();
code_state->ip = ip;
code_state->sp = sp;
code_state->exc_sp_idx = MP_CODE_STATE_EXC_SP_IDX_FROM_PTR(exc_stack, exc_sp);
FRAME_LEAVE();
return MP_VM_RETURN_YIELD;
ENTRY(MP_BC_YIELD_FROM): {
MARK_EXC_IP_SELECTIVE();
//#define EXC_MATCH(exc, type) mp_obj_is_type(exc, type)
#define EXC_MATCH(exc, type) mp_obj_exception_match(exc, type)
#define GENERATOR_EXIT_IF_NEEDED(t) if (t != MP_OBJ_NULL && EXC_MATCH(t, MP_OBJ_FROM_PTR(&mp_type_GeneratorExit))) { mp_obj_t raise_t = mp_make_raise_obj(t); RAISE(raise_t); }
mp_vm_return_kind_t ret_kind;
mp_obj_t send_value = POP();
mp_obj_t t_exc = MP_OBJ_NULL;
mp_obj_t ret_value;
code_state->sp = sp; // Save sp because it's needed if mp_resume raises StopIteration
if (inject_exc != MP_OBJ_NULL) {
t_exc = inject_exc;
inject_exc = MP_OBJ_NULL;
ret_kind = mp_resume(TOP(), MP_OBJ_NULL, t_exc, &ret_value);
} else {
ret_kind = mp_resume(TOP(), send_value, MP_OBJ_NULL, &ret_value);
}
if (ret_kind == MP_VM_RETURN_YIELD) {
ip--;
PUSH(ret_value);
goto yield;
} else if (ret_kind == MP_VM_RETURN_NORMAL) {
// The generator has finished, and returned a value via StopIteration
// Replace exhausted generator with the returned value
SET_TOP(ret_value);
// If we injected GeneratorExit downstream, then even
// if it was swallowed, we re-raise GeneratorExit
GENERATOR_EXIT_IF_NEEDED(t_exc);
DISPATCH();
} else {
assert(ret_kind == MP_VM_RETURN_EXCEPTION);
assert(!EXC_MATCH(ret_value, MP_OBJ_FROM_PTR(&mp_type_StopIteration)));
// Pop exhausted gen
sp--;
RAISE(ret_value);
}
}
ENTRY(MP_BC_IMPORT_NAME): {
FRAME_UPDATE();
MARK_EXC_IP_SELECTIVE();
DECODE_QSTR;
mp_obj_t obj = POP();
SET_TOP(mp_import_name(qst, obj, TOP()));
DISPATCH();
}
ENTRY(MP_BC_IMPORT_FROM): {
FRAME_UPDATE();
MARK_EXC_IP_SELECTIVE();
DECODE_QSTR;
mp_obj_t obj = mp_import_from(TOP(), qst);
PUSH(obj);
DISPATCH();
}
ENTRY(MP_BC_IMPORT_STAR):
MARK_EXC_IP_SELECTIVE();
mp_import_all(POP());
DISPATCH();
#if MICROPY_OPT_COMPUTED_GOTO
ENTRY(MP_BC_LOAD_CONST_SMALL_INT_MULTI):
PUSH(MP_OBJ_NEW_SMALL_INT((mp_int_t)ip[-1] - MP_BC_LOAD_CONST_SMALL_INT_MULTI - MP_BC_LOAD_CONST_SMALL_INT_MULTI_EXCESS));
DISPATCH();
ENTRY(MP_BC_LOAD_FAST_MULTI):
obj_shared = fastn[MP_BC_LOAD_FAST_MULTI - (mp_int_t)ip[-1]];
goto load_check;
ENTRY(MP_BC_STORE_FAST_MULTI):
fastn[MP_BC_STORE_FAST_MULTI - (mp_int_t)ip[-1]] = POP();
DISPATCH();
ENTRY(MP_BC_UNARY_OP_MULTI):
MARK_EXC_IP_SELECTIVE();
SET_TOP(mp_unary_op(ip[-1] - MP_BC_UNARY_OP_MULTI, TOP()));
DISPATCH();
ENTRY(MP_BC_BINARY_OP_MULTI): {
MARK_EXC_IP_SELECTIVE();
mp_obj_t rhs = POP();
mp_obj_t lhs = TOP();
SET_TOP(mp_binary_op(ip[-1] - MP_BC_BINARY_OP_MULTI, lhs, rhs));
DISPATCH();
}
ENTRY_DEFAULT:
MARK_EXC_IP_SELECTIVE();
#else
ENTRY_DEFAULT:
if (ip[-1] < MP_BC_LOAD_CONST_SMALL_INT_MULTI + MP_BC_LOAD_CONST_SMALL_INT_MULTI_NUM) {
PUSH(MP_OBJ_NEW_SMALL_INT((mp_int_t)ip[-1] - MP_BC_LOAD_CONST_SMALL_INT_MULTI - MP_BC_LOAD_CONST_SMALL_INT_MULTI_EXCESS));
DISPATCH();
} else if (ip[-1] < MP_BC_LOAD_FAST_MULTI + MP_BC_LOAD_FAST_MULTI_NUM) {
obj_shared = fastn[MP_BC_LOAD_FAST_MULTI - (mp_int_t)ip[-1]];
goto load_check;
} else if (ip[-1] < MP_BC_STORE_FAST_MULTI + MP_BC_STORE_FAST_MULTI_NUM) {
fastn[MP_BC_STORE_FAST_MULTI - (mp_int_t)ip[-1]] = POP();
DISPATCH();
} else if (ip[-1] < MP_BC_UNARY_OP_MULTI + MP_BC_UNARY_OP_MULTI_NUM) {
SET_TOP(mp_unary_op(ip[-1] - MP_BC_UNARY_OP_MULTI, TOP()));
DISPATCH();
} else if (ip[-1] < MP_BC_BINARY_OP_MULTI + MP_BC_BINARY_OP_MULTI_NUM) {
mp_obj_t rhs = POP();
mp_obj_t lhs = TOP();
SET_TOP(mp_binary_op(ip[-1] - MP_BC_BINARY_OP_MULTI, lhs, rhs));
DISPATCH();
} else
#endif
{
mp_obj_t obj = mp_obj_new_exception_msg(&mp_type_NotImplementedError, MP_ERROR_TEXT("opcode"));
nlr_pop();
code_state->state[0] = obj;
FRAME_LEAVE();
return MP_VM_RETURN_EXCEPTION;
}
#if !MICROPY_OPT_COMPUTED_GOTO
} // switch
#endif
pending_exception_check:
MICROPY_VM_HOOK_LOOP
#if MICROPY_ENABLE_SCHEDULER
// This is an inlined variant of mp_handle_pending
if (MP_STATE_VM(sched_state) == MP_SCHED_PENDING) {
mp_uint_t atomic_state = MICROPY_BEGIN_ATOMIC_SECTION();
// Re-check state is still pending now that we're in the atomic section.
if (MP_STATE_VM(sched_state) == MP_SCHED_PENDING) {
MARK_EXC_IP_SELECTIVE();
mp_obj_t obj = MP_STATE_THREAD(mp_pending_exception);
if (obj != MP_OBJ_NULL) {
MP_STATE_THREAD(mp_pending_exception) = MP_OBJ_NULL;
if (!mp_sched_num_pending()) {
MP_STATE_VM(sched_state) = MP_SCHED_IDLE;
}
MICROPY_END_ATOMIC_SECTION(atomic_state);
RAISE(obj);
}
mp_handle_pending_tail(atomic_state);
} else {
MICROPY_END_ATOMIC_SECTION(atomic_state);
}
}
#else
// This is an inlined variant of mp_handle_pending
if (MP_STATE_THREAD(mp_pending_exception) != MP_OBJ_NULL) {
MARK_EXC_IP_SELECTIVE();
mp_obj_t obj = MP_STATE_THREAD(mp_pending_exception);
MP_STATE_THREAD(mp_pending_exception) = MP_OBJ_NULL;
RAISE(obj);
}
#endif
#if MICROPY_PY_THREAD_GIL
#if MICROPY_PY_THREAD_GIL_VM_DIVISOR
if (--gil_divisor == 0)
#endif
{
#if MICROPY_PY_THREAD_GIL_VM_DIVISOR
gil_divisor = MICROPY_PY_THREAD_GIL_VM_DIVISOR;
#endif
#if MICROPY_ENABLE_SCHEDULER
// can only switch threads if the scheduler is unlocked
if (MP_STATE_VM(sched_state) == MP_SCHED_IDLE)
#endif
{
MP_THREAD_GIL_EXIT();
MP_THREAD_GIL_ENTER();
}
}
#endif
} // for loop
} else {
exception_handler:
// exception occurred
#if MICROPY_PY_SYS_EXC_INFO
MP_STATE_VM(cur_exception) = nlr.ret_val;
#endif
#if SELECTIVE_EXC_IP
// with selective ip, we store the ip 1 byte past the opcode, so move ptr back
code_state->ip -= 1;
#endif
if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(((mp_obj_base_t*)nlr.ret_val)->type), MP_OBJ_FROM_PTR(&mp_type_StopIteration))) {
if (code_state->ip) {
// check if it's a StopIteration within a for block
if (*code_state->ip == MP_BC_FOR_ITER) {
const byte *ip = code_state->ip + 1;
DECODE_ULABEL; // the jump offset if iteration finishes; for labels are always forward
code_state->ip = ip + ulab; // jump to after for-block
code_state->sp -= MP_OBJ_ITER_BUF_NSLOTS; // pop the exhausted iterator
goto outer_dispatch_loop; // continue with dispatch loop
} else if (*code_state->ip == MP_BC_YIELD_FROM) {
// StopIteration inside yield from call means return a value of
// yield from, so inject exception's value as yield from's result
// (Instead of stack pop then push we just replace exhausted gen with value)
*code_state->sp = mp_obj_exception_get_value(MP_OBJ_FROM_PTR(nlr.ret_val));
code_state->ip++; // yield from is over, move to next instruction
goto outer_dispatch_loop; // continue with dispatch loop
}
}
}
#if MICROPY_PY_SYS_SETTRACE
// Exceptions are traced here
if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(((mp_obj_base_t*)nlr.ret_val)->type), MP_OBJ_FROM_PTR(&mp_type_Exception))) {
TRACE_TICK(code_state->ip, code_state->sp, true /* yes, it's an exception */);
}
#endif
#if MICROPY_STACKLESS
unwind_loop:
#endif
// Set traceback info (file and line number) where the exception occurred, but not for:
// - constant GeneratorExit object, because it's const
// - exceptions re-raised by END_FINALLY
// - exceptions re-raised explicitly by "raise"
if (nlr.ret_val != &mp_const_GeneratorExit_obj
&& *code_state->ip != MP_BC_END_FINALLY
&& *code_state->ip != MP_BC_RAISE_LAST) {
const byte *ip = code_state->fun_bc->bytecode;
MP_BC_PRELUDE_SIG_DECODE(ip);
MP_BC_PRELUDE_SIZE_DECODE(ip);
const byte *bytecode_start = ip + n_info + n_cell;
#if !MICROPY_PERSISTENT_CODE
// so bytecode is aligned
bytecode_start = MP_ALIGN(bytecode_start, sizeof(mp_uint_t));
#endif
size_t bc = code_state->ip - bytecode_start;
#if MICROPY_PERSISTENT_CODE
qstr block_name = ip[0] | (ip[1] << 8);
qstr source_file = ip[2] | (ip[3] << 8);
ip += 4;
#else
qstr block_name = mp_decode_uint_value(ip);
ip = mp_decode_uint_skip(ip);
qstr source_file = mp_decode_uint_value(ip);
ip = mp_decode_uint_skip(ip);
#endif
size_t source_line = mp_bytecode_get_source_line(ip, bc);
mp_obj_exception_add_traceback(MP_OBJ_FROM_PTR(nlr.ret_val), source_file, source_line, block_name);
}
while (exc_sp >= exc_stack && exc_sp->handler <= code_state->ip) {
// nested exception
assert(exc_sp >= exc_stack);
// TODO make a proper message for nested exception
// at the moment we are just raising the very last exception (the one that caused the nested exception)
// move up to previous exception handler
POP_EXC_BLOCK();
}
if (exc_sp >= exc_stack) {
// catch exception and pass to byte code
code_state->ip = exc_sp->handler;
mp_obj_t *sp = MP_TAGPTR_PTR(exc_sp->val_sp);
// save this exception in the stack so it can be used in a reraise, if needed
exc_sp->prev_exc = nlr.ret_val;
// push exception object so it can be handled by bytecode
PUSH(MP_OBJ_FROM_PTR(nlr.ret_val));
code_state->sp = sp;
#if MICROPY_STACKLESS
} else if (code_state->prev != NULL) {
mp_globals_set(code_state->old_globals);
mp_code_state_t *new_code_state = code_state->prev;
#if MICROPY_ENABLE_PYSTACK
// Free code_state, and args allocated by mp_call_prepare_args_n_kw_var
// (The latter is implicitly freed when using pystack due to its LIFO nature.)
// The sizeof in the following statement does not include the size of the variable
// part of the struct. This arg is anyway not used if pystack is enabled.
mp_nonlocal_free(code_state, sizeof(mp_code_state_t));
#endif
code_state = new_code_state;
size_t n_state = code_state->n_state;
fastn = &code_state->state[n_state - 1];
exc_stack = (mp_exc_stack_t*)(code_state->state + n_state);
// variables that are visible to the exception handler (declared volatile)
exc_sp = MP_CODE_STATE_EXC_SP_IDX_TO_PTR(exc_stack, code_state->exc_sp_idx); // stack grows up, exc_sp points to top of stack
goto unwind_loop;
#endif
} else {
// propagate exception to higher level
// Note: ip and sp don't have usable values at this point
code_state->state[0] = MP_OBJ_FROM_PTR(nlr.ret_val); // put exception here because sp is invalid
FRAME_LEAVE();
return MP_VM_RETURN_EXCEPTION;
}
}
}
}
| YifuLiu/AliOS-Things | components/py_engine/engine/py/vm.c | C | apache-2.0 | 66,197 |
/*
* 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.
*/
// *FORMAT-OFF*
#if __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winitializer-overrides"
#endif // __clang__
#if __GNUC__ >= 5
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Woverride-init"
#endif // __GNUC__ >= 5
static const void *const entry_table[256] = {
[0 ... 255] = &&entry_default,
[MP_BC_LOAD_CONST_FALSE] = &&entry_MP_BC_LOAD_CONST_FALSE,
[MP_BC_LOAD_CONST_NONE] = &&entry_MP_BC_LOAD_CONST_NONE,
[MP_BC_LOAD_CONST_TRUE] = &&entry_MP_BC_LOAD_CONST_TRUE,
[MP_BC_LOAD_CONST_SMALL_INT] = &&entry_MP_BC_LOAD_CONST_SMALL_INT,
[MP_BC_LOAD_CONST_STRING] = &&entry_MP_BC_LOAD_CONST_STRING,
[MP_BC_LOAD_CONST_OBJ] = &&entry_MP_BC_LOAD_CONST_OBJ,
[MP_BC_LOAD_NULL] = &&entry_MP_BC_LOAD_NULL,
[MP_BC_LOAD_FAST_N] = &&entry_MP_BC_LOAD_FAST_N,
[MP_BC_LOAD_DEREF] = &&entry_MP_BC_LOAD_DEREF,
[MP_BC_LOAD_NAME] = &&entry_MP_BC_LOAD_NAME,
[MP_BC_LOAD_GLOBAL] = &&entry_MP_BC_LOAD_GLOBAL,
[MP_BC_LOAD_ATTR] = &&entry_MP_BC_LOAD_ATTR,
[MP_BC_LOAD_METHOD] = &&entry_MP_BC_LOAD_METHOD,
[MP_BC_LOAD_SUPER_METHOD] = &&entry_MP_BC_LOAD_SUPER_METHOD,
[MP_BC_LOAD_BUILD_CLASS] = &&entry_MP_BC_LOAD_BUILD_CLASS,
[MP_BC_LOAD_SUBSCR] = &&entry_MP_BC_LOAD_SUBSCR,
[MP_BC_STORE_FAST_N] = &&entry_MP_BC_STORE_FAST_N,
[MP_BC_STORE_DEREF] = &&entry_MP_BC_STORE_DEREF,
[MP_BC_STORE_NAME] = &&entry_MP_BC_STORE_NAME,
[MP_BC_STORE_GLOBAL] = &&entry_MP_BC_STORE_GLOBAL,
[MP_BC_STORE_ATTR] = &&entry_MP_BC_STORE_ATTR,
[MP_BC_STORE_SUBSCR] = &&entry_MP_BC_STORE_SUBSCR,
[MP_BC_DELETE_FAST] = &&entry_MP_BC_DELETE_FAST,
[MP_BC_DELETE_DEREF] = &&entry_MP_BC_DELETE_DEREF,
[MP_BC_DELETE_NAME] = &&entry_MP_BC_DELETE_NAME,
[MP_BC_DELETE_GLOBAL] = &&entry_MP_BC_DELETE_GLOBAL,
[MP_BC_DUP_TOP] = &&entry_MP_BC_DUP_TOP,
[MP_BC_DUP_TOP_TWO] = &&entry_MP_BC_DUP_TOP_TWO,
[MP_BC_POP_TOP] = &&entry_MP_BC_POP_TOP,
[MP_BC_ROT_TWO] = &&entry_MP_BC_ROT_TWO,
[MP_BC_ROT_THREE] = &&entry_MP_BC_ROT_THREE,
[MP_BC_JUMP] = &&entry_MP_BC_JUMP,
[MP_BC_POP_JUMP_IF_TRUE] = &&entry_MP_BC_POP_JUMP_IF_TRUE,
[MP_BC_POP_JUMP_IF_FALSE] = &&entry_MP_BC_POP_JUMP_IF_FALSE,
[MP_BC_JUMP_IF_TRUE_OR_POP] = &&entry_MP_BC_JUMP_IF_TRUE_OR_POP,
[MP_BC_JUMP_IF_FALSE_OR_POP] = &&entry_MP_BC_JUMP_IF_FALSE_OR_POP,
[MP_BC_SETUP_WITH] = &&entry_MP_BC_SETUP_WITH,
[MP_BC_WITH_CLEANUP] = &&entry_MP_BC_WITH_CLEANUP,
[MP_BC_UNWIND_JUMP] = &&entry_MP_BC_UNWIND_JUMP,
[MP_BC_SETUP_EXCEPT] = &&entry_MP_BC_SETUP_EXCEPT,
[MP_BC_SETUP_FINALLY] = &&entry_MP_BC_SETUP_FINALLY,
[MP_BC_END_FINALLY] = &&entry_MP_BC_END_FINALLY,
[MP_BC_GET_ITER] = &&entry_MP_BC_GET_ITER,
[MP_BC_GET_ITER_STACK] = &&entry_MP_BC_GET_ITER_STACK,
[MP_BC_FOR_ITER] = &&entry_MP_BC_FOR_ITER,
[MP_BC_POP_EXCEPT_JUMP] = &&entry_MP_BC_POP_EXCEPT_JUMP,
[MP_BC_BUILD_TUPLE] = &&entry_MP_BC_BUILD_TUPLE,
[MP_BC_BUILD_LIST] = &&entry_MP_BC_BUILD_LIST,
[MP_BC_BUILD_MAP] = &&entry_MP_BC_BUILD_MAP,
[MP_BC_STORE_MAP] = &&entry_MP_BC_STORE_MAP,
#if MICROPY_PY_BUILTINS_SET
[MP_BC_BUILD_SET] = &&entry_MP_BC_BUILD_SET,
#endif
#if MICROPY_PY_BUILTINS_SLICE
[MP_BC_BUILD_SLICE] = &&entry_MP_BC_BUILD_SLICE,
#endif
[MP_BC_STORE_COMP] = &&entry_MP_BC_STORE_COMP,
[MP_BC_UNPACK_SEQUENCE] = &&entry_MP_BC_UNPACK_SEQUENCE,
[MP_BC_UNPACK_EX] = &&entry_MP_BC_UNPACK_EX,
[MP_BC_MAKE_FUNCTION] = &&entry_MP_BC_MAKE_FUNCTION,
[MP_BC_MAKE_FUNCTION_DEFARGS] = &&entry_MP_BC_MAKE_FUNCTION_DEFARGS,
[MP_BC_MAKE_CLOSURE] = &&entry_MP_BC_MAKE_CLOSURE,
[MP_BC_MAKE_CLOSURE_DEFARGS] = &&entry_MP_BC_MAKE_CLOSURE_DEFARGS,
[MP_BC_CALL_FUNCTION] = &&entry_MP_BC_CALL_FUNCTION,
[MP_BC_CALL_FUNCTION_VAR_KW] = &&entry_MP_BC_CALL_FUNCTION_VAR_KW,
[MP_BC_CALL_METHOD] = &&entry_MP_BC_CALL_METHOD,
[MP_BC_CALL_METHOD_VAR_KW] = &&entry_MP_BC_CALL_METHOD_VAR_KW,
[MP_BC_RETURN_VALUE] = &&entry_MP_BC_RETURN_VALUE,
[MP_BC_RAISE_LAST] = &&entry_MP_BC_RAISE_LAST,
[MP_BC_RAISE_OBJ] = &&entry_MP_BC_RAISE_OBJ,
[MP_BC_RAISE_FROM] = &&entry_MP_BC_RAISE_FROM,
[MP_BC_YIELD_VALUE] = &&entry_MP_BC_YIELD_VALUE,
[MP_BC_YIELD_FROM] = &&entry_MP_BC_YIELD_FROM,
[MP_BC_IMPORT_NAME] = &&entry_MP_BC_IMPORT_NAME,
[MP_BC_IMPORT_FROM] = &&entry_MP_BC_IMPORT_FROM,
[MP_BC_IMPORT_STAR] = &&entry_MP_BC_IMPORT_STAR,
[MP_BC_LOAD_CONST_SMALL_INT_MULTI ... MP_BC_LOAD_CONST_SMALL_INT_MULTI + MP_BC_LOAD_CONST_SMALL_INT_MULTI_NUM - 1] = &&entry_MP_BC_LOAD_CONST_SMALL_INT_MULTI,
[MP_BC_LOAD_FAST_MULTI ... MP_BC_LOAD_FAST_MULTI + MP_BC_LOAD_FAST_MULTI_NUM - 1] = &&entry_MP_BC_LOAD_FAST_MULTI,
[MP_BC_STORE_FAST_MULTI ... MP_BC_STORE_FAST_MULTI + MP_BC_STORE_FAST_MULTI_NUM - 1] = &&entry_MP_BC_STORE_FAST_MULTI,
[MP_BC_UNARY_OP_MULTI ... MP_BC_UNARY_OP_MULTI + MP_BC_UNARY_OP_MULTI_NUM - 1] = &&entry_MP_BC_UNARY_OP_MULTI,
[MP_BC_BINARY_OP_MULTI ... MP_BC_BINARY_OP_MULTI + MP_BC_BINARY_OP_MULTI_NUM - 1] = &&entry_MP_BC_BINARY_OP_MULTI,
};
#if __clang__
#pragma clang diagnostic pop
#endif // __clang__
#if __GNUC__ >= 5
#pragma GCC diagnostic pop
#endif // __GNUC__ >= 5
| YifuLiu/AliOS-Things | components/py_engine/engine/py/vmentrytable.h | C | apache-2.0 | 6,412 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2013, 2014 Damien P. George
* Copyright (c) 2014 Paul Sokolovsky
*
* 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 <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <assert.h>
#include "py/mpconfig.h"
#include "py/runtime.h"
#include "py/mpprint.h"
// returned value is always at least 1 greater than argument
#define ROUND_ALLOC(a) (((a) & ((~0U) - 7)) + 8)
// Init the vstr so it allocs exactly given number of bytes. Set length to zero.
void vstr_init(vstr_t *vstr, size_t alloc) {
if (alloc < 1) {
alloc = 1;
}
vstr->alloc = alloc;
vstr->len = 0;
vstr->buf = m_new(char, vstr->alloc);
vstr->fixed_buf = false;
}
// Init the vstr so it allocs exactly enough ram to hold a null-terminated
// string of the given length, and set the length.
void vstr_init_len(vstr_t *vstr, size_t len) {
vstr_init(vstr, len + 1);
vstr->len = len;
}
void vstr_init_fixed_buf(vstr_t *vstr, size_t alloc, char *buf) {
vstr->alloc = alloc;
vstr->len = 0;
vstr->buf = buf;
vstr->fixed_buf = true;
}
void vstr_init_print(vstr_t *vstr, size_t alloc, mp_print_t *print) {
vstr_init(vstr, alloc);
print->data = vstr;
print->print_strn = (mp_print_strn_t)vstr_add_strn;
}
void vstr_clear(vstr_t *vstr) {
if (!vstr->fixed_buf) {
m_del(char, vstr->buf, vstr->alloc);
}
vstr->buf = NULL;
}
vstr_t *vstr_new(size_t alloc) {
vstr_t *vstr = m_new_obj(vstr_t);
vstr_init(vstr, alloc);
return vstr;
}
void vstr_free(vstr_t *vstr) {
if (vstr != NULL) {
if (!vstr->fixed_buf) {
m_del(char, vstr->buf, vstr->alloc);
}
m_del_obj(vstr_t, vstr);
}
}
// Extend vstr strictly by requested size, return pointer to newly added chunk.
char *vstr_extend(vstr_t *vstr, size_t size) {
if (vstr->fixed_buf) {
// We can't reallocate, and the caller is expecting the space to
// be there, so the only safe option is to raise an exception.
mp_raise_msg(&mp_type_RuntimeError, NULL);
}
char *new_buf = m_renew(char, vstr->buf, vstr->alloc, vstr->alloc + size);
char *p = new_buf + vstr->alloc;
vstr->alloc += size;
vstr->buf = new_buf;
return p;
}
STATIC void vstr_ensure_extra(vstr_t *vstr, size_t size) {
if (vstr->len + size > vstr->alloc) {
if (vstr->fixed_buf) {
// We can't reallocate, and the caller is expecting the space to
// be there, so the only safe option is to raise an exception.
mp_raise_msg(&mp_type_RuntimeError, NULL);
}
size_t new_alloc = ROUND_ALLOC((vstr->len + size) + 16);
char *new_buf = m_renew(char, vstr->buf, vstr->alloc, new_alloc);
vstr->alloc = new_alloc;
vstr->buf = new_buf;
}
}
void vstr_hint_size(vstr_t *vstr, size_t size) {
vstr_ensure_extra(vstr, size);
}
char *vstr_add_len(vstr_t *vstr, size_t len) {
vstr_ensure_extra(vstr, len);
char *buf = vstr->buf + vstr->len;
vstr->len += len;
return buf;
}
// Doesn't increase len, just makes sure there is a null byte at the end
char *vstr_null_terminated_str(vstr_t *vstr) {
// If there's no more room, add single byte
if (vstr->alloc == vstr->len) {
vstr_extend(vstr, 1);
}
vstr->buf[vstr->len] = '\0';
return vstr->buf;
}
void vstr_add_byte(vstr_t *vstr, byte b) {
byte *buf = (byte *)vstr_add_len(vstr, 1);
buf[0] = b;
}
void vstr_add_char(vstr_t *vstr, unichar c) {
#if MICROPY_PY_BUILTINS_STR_UNICODE
// TODO: Can this be simplified and deduplicated?
// Is it worth just calling vstr_add_len(vstr, 4)?
if (c < 0x80) {
byte *buf = (byte *)vstr_add_len(vstr, 1);
*buf = (byte)c;
} else if (c < 0x800) {
byte *buf = (byte *)vstr_add_len(vstr, 2);
buf[0] = (c >> 6) | 0xC0;
buf[1] = (c & 0x3F) | 0x80;
} else if (c < 0x10000) {
byte *buf = (byte *)vstr_add_len(vstr, 3);
buf[0] = (c >> 12) | 0xE0;
buf[1] = ((c >> 6) & 0x3F) | 0x80;
buf[2] = (c & 0x3F) | 0x80;
} else {
assert(c < 0x110000);
byte *buf = (byte *)vstr_add_len(vstr, 4);
buf[0] = (c >> 18) | 0xF0;
buf[1] = ((c >> 12) & 0x3F) | 0x80;
buf[2] = ((c >> 6) & 0x3F) | 0x80;
buf[3] = (c & 0x3F) | 0x80;
}
#else
vstr_add_byte(vstr, c);
#endif
}
void vstr_add_str(vstr_t *vstr, const char *str) {
vstr_add_strn(vstr, str, strlen(str));
}
void vstr_add_strn(vstr_t *vstr, const char *str, size_t len) {
vstr_ensure_extra(vstr, len);
memmove(vstr->buf + vstr->len, str, len);
vstr->len += len;
}
STATIC char *vstr_ins_blank_bytes(vstr_t *vstr, size_t byte_pos, size_t byte_len) {
size_t l = vstr->len;
if (byte_pos > l) {
byte_pos = l;
}
if (byte_len > 0) {
// ensure room for the new bytes
vstr_ensure_extra(vstr, byte_len);
// copy up the string to make room for the new bytes
memmove(vstr->buf + byte_pos + byte_len, vstr->buf + byte_pos, l - byte_pos);
// increase the length
vstr->len += byte_len;
}
return vstr->buf + byte_pos;
}
void vstr_ins_byte(vstr_t *vstr, size_t byte_pos, byte b) {
char *s = vstr_ins_blank_bytes(vstr, byte_pos, 1);
*s = b;
}
void vstr_ins_char(vstr_t *vstr, size_t char_pos, unichar chr) {
// TODO UNICODE
char *s = vstr_ins_blank_bytes(vstr, char_pos, 1);
*s = chr;
}
void vstr_cut_head_bytes(vstr_t *vstr, size_t bytes_to_cut) {
vstr_cut_out_bytes(vstr, 0, bytes_to_cut);
}
void vstr_cut_tail_bytes(vstr_t *vstr, size_t len) {
if (len > vstr->len) {
vstr->len = 0;
} else {
vstr->len -= len;
}
}
void vstr_cut_out_bytes(vstr_t *vstr, size_t byte_pos, size_t bytes_to_cut) {
if (byte_pos >= vstr->len) {
return;
} else if (byte_pos + bytes_to_cut >= vstr->len) {
vstr->len = byte_pos;
} else {
memmove(vstr->buf + byte_pos, vstr->buf + byte_pos + bytes_to_cut, vstr->len - byte_pos - bytes_to_cut);
vstr->len -= bytes_to_cut;
}
}
void vstr_printf(vstr_t *vstr, const char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
vstr_vprintf(vstr, fmt, ap);
va_end(ap);
}
void vstr_vprintf(vstr_t *vstr, const char *fmt, va_list ap) {
mp_print_t print = {vstr, (mp_print_strn_t)vstr_add_strn};
mp_vprintf(&print, fmt, ap);
}
| YifuLiu/AliOS-Things | components/py_engine/engine/py/vstr.c | C | apache-2.0 | 7,561 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2014 Damien P. George
* Copyright (c) 2015-2018 Paul Sokolovsky
*
* 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>
#include <stdio.h>
#include "py/emit.h"
#include "py/runtime.h"
#if MICROPY_WARNINGS
void mp_warning(const char *category, const char *msg, ...) {
if (category == NULL) {
category = "Warning";
}
mp_print_str(MICROPY_ERROR_PRINTER, category);
mp_print_str(MICROPY_ERROR_PRINTER, ": ");
va_list args;
va_start(args, msg);
mp_vprintf(MICROPY_ERROR_PRINTER, msg, args);
mp_print_str(MICROPY_ERROR_PRINTER, "\n");
va_end(args);
}
void mp_emitter_warning(pass_kind_t pass, const char *msg) {
if (pass == MP_PASS_CODE_SIZE) {
mp_warning(NULL, msg);
}
}
#endif // MICROPY_WARNINGS
| YifuLiu/AliOS-Things | components/py_engine/engine/py/warning.c | C | apache-2.0 | 1,928 |
// This file provides a version of __errno() for embedded systems that do not have one.
// This function is needed for expressions of the form: &errno
static int embed_errno;
#if defined(__linux__)
int *__errno_location(void)
#else
int *__errno(void)
#endif
{
return &embed_errno;
}
| YifuLiu/AliOS-Things | components/py_engine/engine/shared/libc/__errno.c | C | apache-2.0 | 289 |
#include <py/runtime.h>
NORETURN void abort_(void);
NORETURN void abort_(void) {
mp_raise_msg(&mp_type_RuntimeError, MP_ERROR_TEXT("abort() called"));
}
| YifuLiu/AliOS-Things | components/py_engine/engine/shared/libc/abort_.c | C | apache-2.0 | 159 |
/*
* 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 "py/mpconfig.h"
#include <stdint.h>
#include <string.h>
#include <stdarg.h>
#include "py/obj.h"
#include "py/mphal.h"
#if MICROPY_PY_BUILTINS_FLOAT
#include "py/formatfloat.h"
#endif
#if MICROPY_DEBUG_PRINTERS
int DEBUG_printf(const char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
int ret = mp_vprintf(MICROPY_DEBUG_PRINTER, fmt, ap);
va_end(ap);
return ret;
}
#endif
#if MICROPY_USE_INTERNAL_PRINTF
#undef putchar // Some stdlibs have a #define for putchar
int printf(const char *fmt, ...);
int vprintf(const char *fmt, va_list ap);
int putchar(int c);
int puts(const char *s);
int vsnprintf(char *str, size_t size, const char *fmt, va_list ap);
int snprintf(char *str, size_t size, const char *fmt, ...);
int printf(const char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
int ret = mp_vprintf(&mp_plat_print, fmt, ap);
va_end(ap);
return ret;
}
int vprintf(const char *fmt, va_list ap) {
return mp_vprintf(&mp_plat_print, fmt, ap);
}
// need this because gcc optimises printf("%c", c) -> putchar(c), and printf("a") -> putchar('a')
int putchar(int c) {
char chr = c;
mp_hal_stdout_tx_strn_cooked(&chr, 1);
return chr;
}
// need this because gcc optimises printf("string\n") -> puts("string")
int puts(const char *s) {
mp_hal_stdout_tx_strn_cooked(s, strlen(s));
char chr = '\n';
mp_hal_stdout_tx_strn_cooked(&chr, 1);
return 1;
}
typedef struct _strn_print_env_t {
char *cur;
size_t remain;
} strn_print_env_t;
STATIC void strn_print_strn(void *data, const char *str, size_t len) {
strn_print_env_t *strn_print_env = data;
if (len > strn_print_env->remain) {
len = strn_print_env->remain;
}
memcpy(strn_print_env->cur, str, len);
strn_print_env->cur += len;
strn_print_env->remain -= len;
}
#if defined(__GNUC__) && !defined(__clang__) && __GNUC__ < 9
// uClibc requires this alias to be defined, or there may be link errors
// when linkings against it statically.
// GCC 9 gives a warning about missing attributes so it's excluded until
// uClibc+GCC9 support is needed.
int __GI_vsnprintf(char *str, size_t size, const char *fmt, va_list ap) __attribute__((weak, alias("vsnprintf")));
#endif
int vsnprintf(char *str, size_t size, const char *fmt, va_list ap) {
strn_print_env_t strn_print_env = {str, size};
mp_print_t print = {&strn_print_env, strn_print_strn};
int len = mp_vprintf(&print, fmt, ap);
// add terminating null byte
if (size > 0) {
if (strn_print_env.remain == 0) {
strn_print_env.cur[-1] = 0;
} else {
strn_print_env.cur[0] = 0;
}
}
return len;
}
int snprintf(char *str, size_t size, const char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
int ret = vsnprintf(str, size, fmt, ap);
va_end(ap);
return ret;
}
#endif // MICROPY_USE_INTERNAL_PRINTF
| YifuLiu/AliOS-Things | components/py_engine/engine/shared/libc/printf.c | C | apache-2.0 | 4,130 |
/*
* 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 <stdint.h>
#include <string.h>
#define likely(x) __builtin_expect((x), 1)
void *memcpy(void *dst, const void *src, size_t n) {
if (likely(!(((uintptr_t)dst) & 3) && !(((uintptr_t)src) & 3))) {
// pointers aligned
uint32_t *d = dst;
const uint32_t *s = src;
// copy words first
for (size_t i = (n >> 2); i; i--) {
*d++ = *s++;
}
if (n & 2) {
// copy half-word
*(uint16_t*)d = *(const uint16_t*)s;
d = (uint32_t*)((uint16_t*)d + 1);
s = (const uint32_t*)((const uint16_t*)s + 1);
}
if (n & 1) {
// copy byte
*((uint8_t*)d) = *((const uint8_t*)s);
}
} else {
// unaligned access, copy bytes
uint8_t *d = dst;
const uint8_t *s = src;
for (; n; n--) {
*d++ = *s++;
}
}
return dst;
}
void *memmove(void *dest, const void *src, size_t n) {
if (src < dest && (uint8_t*)dest < (const uint8_t*)src + n) {
// need to copy backwards
uint8_t *d = (uint8_t*)dest + n - 1;
const uint8_t *s = (const uint8_t*)src + n - 1;
for (; n > 0; n--) {
*d-- = *s--;
}
return dest;
} else {
// can use normal memcpy
return memcpy(dest, src, n);
}
}
void *memset(void *s, int c, size_t n) {
if (c == 0 && ((uintptr_t)s & 3) == 0) {
// aligned store of 0
uint32_t *s32 = s;
for (size_t i = n >> 2; i > 0; i--) {
*s32++ = 0;
}
if (n & 2) {
*((uint16_t*)s32) = 0;
s32 = (uint32_t*)((uint16_t*)s32 + 1);
}
if (n & 1) {
*((uint8_t*)s32) = 0;
}
} else {
uint8_t *s2 = s;
for (; n > 0; n--) {
*s2++ = c;
}
}
return s;
}
int memcmp(const void *s1, const void *s2, size_t n) {
const uint8_t *s1_8 = s1;
const uint8_t *s2_8 = s2;
while (n--) {
char c1 = *s1_8++;
char c2 = *s2_8++;
if (c1 < c2) return -1;
else if (c1 > c2) return 1;
}
return 0;
}
void *memchr(const void *s, int c, size_t n) {
if (n != 0) {
const unsigned char *p = s;
do {
if (*p++ == c)
return ((void *)(p - 1));
} while (--n != 0);
}
return 0;
}
size_t strlen(const char *str) {
int len = 0;
for (const char *s = str; *s; s++) {
len += 1;
}
return len;
}
int strcmp(const char *s1, const char *s2) {
while (*s1 && *s2) {
char c1 = *s1++; // XXX UTF8 get char, next char
char c2 = *s2++; // XXX UTF8 get char, next char
if (c1 < c2) return -1;
else if (c1 > c2) return 1;
}
if (*s2) return -1;
else if (*s1) return 1;
else return 0;
}
int strncmp(const char *s1, const char *s2, size_t n) {
while (*s1 && *s2 && n > 0) {
char c1 = *s1++; // XXX UTF8 get char, next char
char c2 = *s2++; // XXX UTF8 get char, next char
n--;
if (c1 < c2) return -1;
else if (c1 > c2) return 1;
}
if (n == 0) return 0;
else if (*s2) return -1;
else if (*s1) return 1;
else return 0;
}
char *strcpy(char *dest, const char *src) {
char *d = dest;
while (*src) {
*d++ = *src++;
}
*d = '\0';
return dest;
}
// Public Domain implementation of strncpy from:
// http://en.wikibooks.org/wiki/C_Programming/Strings#The_strncpy_function
char *strncpy(char *s1, const char *s2, size_t n) {
char *dst = s1;
const char *src = s2;
/* Copy bytes, one at a time. */
while (n > 0) {
n--;
if ((*dst++ = *src++) == '\0') {
/* If we get here, we found a null character at the end
of s2, so use memset to put null bytes at the end of
s1. */
memset(dst, '\0', n);
break;
}
}
return s1;
}
// needed because gcc optimises strcpy + strcat to this
char *stpcpy(char *dest, const char *src) {
while (*src) {
*dest++ = *src++;
}
*dest = '\0';
return dest;
}
char *strcat(char *dest, const char *src) {
char *d = dest;
while (*d) {
d++;
}
while (*src) {
*d++ = *src++;
}
*d = '\0';
return dest;
}
// Public Domain implementation of strchr from:
// http://en.wikibooks.org/wiki/C_Programming/Strings#The_strchr_function
char *strchr(const char *s, int c)
{
/* Scan s for the character. When this loop is finished,
s will either point to the end of the string or the
character we were looking for. */
while (*s != '\0' && *s != (char)c)
s++;
return ((*s == c) ? (char *) s : 0);
}
// Public Domain implementation of strstr from:
// http://en.wikibooks.org/wiki/C_Programming/Strings#The_strstr_function
char *strstr(const char *haystack, const char *needle)
{
size_t needlelen;
/* Check for the null needle case. */
if (*needle == '\0')
return (char *) haystack;
needlelen = strlen(needle);
for (; (haystack = strchr(haystack, *needle)) != 0; haystack++)
if (strncmp(haystack, needle, needlelen) == 0)
return (char *) haystack;
return 0;
}
size_t strspn(const char *s, const char *accept) {
const char *ss = s;
while (*s && strchr(accept, *s) != NULL) {
++s;
}
return s - ss;
}
size_t strcspn(const char *s, const char *reject) {
const char *ss = s;
while (*s && strchr(reject, *s) == NULL) {
++s;
}
return s - ss;
}
| YifuLiu/AliOS-Things | components/py_engine/engine/shared/libc/string0.c | C | apache-2.0 | 6,868 |
#include <stdio.h>
#include "py/lexer.h"
#include "memzip.h"
mp_import_stat_t mp_import_stat(const char *path) {
MEMZIP_FILE_INFO info;
if (memzip_stat(path, &info) != MZ_OK) {
return MP_IMPORT_STAT_NO_EXIST;
}
if (info.is_dir) {
return MP_IMPORT_STAT_DIR;
}
return MP_IMPORT_STAT_FILE;
}
| YifuLiu/AliOS-Things | components/py_engine/engine/shared/memzip/import.c | C | apache-2.0 | 333 |
#include <stdlib.h>
#include "py/lexer.h"
#include "py/runtime.h"
#include "py/mperrno.h"
#include "memzip.h"
mp_lexer_t *mp_lexer_new_from_file(const char *filename)
{
void *data;
size_t len;
if (memzip_locate(filename, &data, &len) != MZ_OK) {
mp_raise_OSError(MP_ENOENT);
}
return mp_lexer_new_from_str_len(qstr_from_str(filename), (const char *)data, (mp_uint_t)len, 0);
}
| YifuLiu/AliOS-Things | components/py_engine/engine/shared/memzip/lexermemzip.c | C | apache-2.0 | 410 |
#!/usr/bin/env python
#
# Takes a directory of files and zips them up (as uncompressed files).
# This then gets converted into a C data structure which can be read
# like a filesystem at runtime.
#
# This is somewhat like frozen modules in python, but allows arbitrary files
# to be used.
from __future__ import print_function
import argparse
import os
import subprocess
import sys
import types
def create_zip(zip_filename, zip_dir):
abs_zip_filename = os.path.abspath(zip_filename)
save_cwd = os.getcwd()
os.chdir(zip_dir)
if os.path.exists(abs_zip_filename):
os.remove(abs_zip_filename)
subprocess.check_call(['zip', '-0', '-r', '-D', abs_zip_filename, '.'])
os.chdir(save_cwd)
def create_c_from_file(c_filename, zip_filename):
with open(zip_filename, 'rb') as zip_file:
with open(c_filename, 'wb') as c_file:
print('#include <stdint.h>', file=c_file)
print('', file=c_file)
print('const uint8_t memzip_data[] = {', file=c_file)
while True:
buf = zip_file.read(16)
if not buf:
break
print(' ', end='', file=c_file)
for byte in buf:
if type(byte) is types.StringType:
print(' 0x{:02x},'.format(ord(byte)), end='', file=c_file)
else:
print(' 0x{:02x},'.format(byte), end='', file=c_file)
print('', file=c_file)
print('};', file=c_file)
def main():
parser = argparse.ArgumentParser(
prog='make-memzip.py',
usage='%(prog)s [options] [command]',
description='Generates a C source memzip file.'
)
parser.add_argument(
'-z', '--zip-file',
dest='zip_filename',
help='Specifies the name of the created zip file.',
default='memzip_files.zip'
)
parser.add_argument(
'-c', '--c-file',
dest='c_filename',
help='Specifies the name of the created C source file.',
default='memzip_files.c'
)
parser.add_argument(
dest='source_dir',
default='memzip_files'
)
args = parser.parse_args(sys.argv[1:])
print('args.zip_filename =', args.zip_filename)
print('args.c_filename =', args.c_filename)
print('args.source_dir =', args.source_dir)
create_zip(args.zip_filename, args.source_dir)
create_c_from_file(args.c_filename, args.zip_filename)
if __name__ == "__main__":
main()
| YifuLiu/AliOS-Things | components/py_engine/engine/shared/memzip/make-memzip.py | Python | apache-2.0 | 2,521 |
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include "py/mpconfig.h"
#include "py/misc.h"
#include "memzip.h"
extern uint8_t memzip_data[];
const MEMZIP_FILE_HDR *memzip_find_file_header(const char *filename) {
const MEMZIP_FILE_HDR *file_hdr = (const MEMZIP_FILE_HDR *)memzip_data;
uint8_t *mem_data;
/* Zip file filenames don't have a leading /, so we strip it off */
if (*filename == '/') {
filename++;
}
while (file_hdr->signature == MEMZIP_FILE_HEADER_SIGNATURE) {
const char *file_hdr_filename = (const char *)&file_hdr[1];
mem_data = (uint8_t *)file_hdr_filename;
mem_data += file_hdr->filename_len;
mem_data += file_hdr->extra_len;
if (!strncmp(file_hdr_filename, filename, file_hdr->filename_len)) {
/* We found a match */
return file_hdr;
}
mem_data += file_hdr->uncompressed_size;
file_hdr = (const MEMZIP_FILE_HDR *)mem_data;
}
return NULL;
}
bool memzip_is_dir(const char *filename) {
const MEMZIP_FILE_HDR *file_hdr = (const MEMZIP_FILE_HDR *)memzip_data;
uint8_t *mem_data;
if (strcmp(filename, "/") == 0) {
// The root directory is a directory.
return true;
}
// Zip filenames don't have a leading /, so we strip it off
if (*filename == '/') {
filename++;
}
size_t filename_len = strlen(filename);
while (file_hdr->signature == MEMZIP_FILE_HEADER_SIGNATURE) {
const char *file_hdr_filename = (const char *)&file_hdr[1];
if (filename_len < file_hdr->filename_len &&
strncmp(file_hdr_filename, filename, filename_len) == 0 &&
file_hdr_filename[filename_len] == '/') {
return true;
}
mem_data = (uint8_t *)file_hdr_filename;
mem_data += file_hdr->filename_len;
mem_data += file_hdr->extra_len;
mem_data += file_hdr->uncompressed_size;
file_hdr = (const MEMZIP_FILE_HDR *)mem_data;
}
return NULL;
}
MEMZIP_RESULT memzip_locate(const char *filename, void **data, size_t *len)
{
const MEMZIP_FILE_HDR *file_hdr = memzip_find_file_header(filename);
if (file_hdr == NULL) {
return MZ_NO_FILE;
}
if (file_hdr->compression_method != 0) {
return MZ_FILE_COMPRESSED;
}
uint8_t *mem_data;
mem_data = (uint8_t *)&file_hdr[1];
mem_data += file_hdr->filename_len;
mem_data += file_hdr->extra_len;
*data = mem_data;
*len = file_hdr->uncompressed_size;
return MZ_OK;
}
MEMZIP_RESULT memzip_stat(const char *path, MEMZIP_FILE_INFO *info) {
const MEMZIP_FILE_HDR *file_hdr = memzip_find_file_header(path);
if (file_hdr == NULL) {
if (memzip_is_dir(path)) {
info->file_size = 0;
info->last_mod_date = 0;
info->last_mod_time = 0;
info->is_dir = 1;
return MZ_OK;
}
return MZ_NO_FILE;
}
info->file_size = file_hdr->uncompressed_size;
info->last_mod_date = file_hdr->last_mod_date;
info->last_mod_time = file_hdr->last_mod_time;
info->is_dir = 0;
return MZ_OK;
}
| YifuLiu/AliOS-Things | components/py_engine/engine/shared/memzip/memzip.c | C | apache-2.0 | 3,162 |
#pragma pack(push, 1)
#define MEMZIP_FILE_HEADER_SIGNATURE 0x04034b50
typedef struct
{
uint32_t signature;
uint16_t version;
uint16_t flags;
uint16_t compression_method;
uint16_t last_mod_time;
uint16_t last_mod_date;
uint32_t crc32;
uint32_t compressed_size;
uint32_t uncompressed_size;
uint16_t filename_len;
uint16_t extra_len;
/* char filename[filename_len] */
/* uint8_t extra[extra_len] */
} MEMZIP_FILE_HDR;
#define MEMZIP_CENTRAL_DIRECTORY_SIGNATURE 0x02014b50
typedef struct
{
uint32_t signature;
uint16_t version_made_by;
uint16_t version_read_with;
uint16_t flags;
uint16_t compression_method;
uint16_t last_mod_time;
uint16_t last_mod_date;
uint32_t crc32;
uint32_t compressed_size;
uint32_t uncompressed_size;
uint16_t filename_len;
uint16_t extra_len;
uint16_t disk_num;
uint16_t internal_file_attributes;
uint32_t external_file_attributes;
uint32_t file_header_offset;
/* char filename[filename_len] */
/* uint8_t extra[extra_len] */
} MEMZIP_CENTRAL_DIRECTORY_HDR;
#define MEMZIP_END_OF_CENTRAL_DIRECTORY_SIGNATURE 0x06054b50
typedef struct
{
uint32_t signature;
uint16_t disk_num;
uint16_t central_directory_disk;
uint16_t num_central_directories_this_disk;
uint16_t total_central_directories;
uint32_t central_directory_size;
uint32_t central_directory_offset;
uint16_t comment_len;
/* char comment[comment_len] */
} MEMZIP_END_OF_CENTRAL_DIRECTORY;
#pragma pack(pop)
typedef enum {
MZ_OK = 0, /* (0) Succeeded */
MZ_NO_FILE, /* (1) Could not find the file. */
MZ_FILE_COMPRESSED, /* (2) File is compressed (expecting uncompressed) */
} MEMZIP_RESULT;
typedef struct {
uint32_t file_size;
uint16_t last_mod_date;
uint16_t last_mod_time;
uint8_t is_dir;
} MEMZIP_FILE_INFO;
MEMZIP_RESULT memzip_locate(const char *filename, void **data, size_t *len);
MEMZIP_RESULT memzip_stat(const char *path, MEMZIP_FILE_INFO *info);
| YifuLiu/AliOS-Things | components/py_engine/engine/shared/memzip/memzip.h | C | apache-2.0 | 2,209 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2018-2019 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.
*/
// For DHCP specs see:
// https://www.ietf.org/rfc/rfc2131.txt
// https://tools.ietf.org/html/rfc2132 -- DHCP Options and BOOTP Vendor Extensions
#include <stdio.h>
#include <string.h>
#include "py/mperrno.h"
#include "py/mphal.h"
#if MICROPY_PY_LWIP
#include "shared/netutils/dhcpserver.h"
#include "lwip/udp.h"
#define DHCPDISCOVER (1)
#define DHCPOFFER (2)
#define DHCPREQUEST (3)
#define DHCPDECLINE (4)
#define DHCPACK (5)
#define DHCPNACK (6)
#define DHCPRELEASE (7)
#define DHCPINFORM (8)
#define DHCP_OPT_PAD (0)
#define DHCP_OPT_SUBNET_MASK (1)
#define DHCP_OPT_ROUTER (3)
#define DHCP_OPT_DNS (6)
#define DHCP_OPT_HOST_NAME (12)
#define DHCP_OPT_REQUESTED_IP (50)
#define DHCP_OPT_IP_LEASE_TIME (51)
#define DHCP_OPT_MSG_TYPE (53)
#define DHCP_OPT_SERVER_ID (54)
#define DHCP_OPT_PARAM_REQUEST_LIST (55)
#define DHCP_OPT_MAX_MSG_SIZE (57)
#define DHCP_OPT_VENDOR_CLASS_ID (60)
#define DHCP_OPT_CLIENT_ID (61)
#define DHCP_OPT_END (255)
#define PORT_DHCP_SERVER (67)
#define PORT_DHCP_CLIENT (68)
#define DEFAULT_DNS MAKE_IP4(8, 8, 8, 8)
#define DEFAULT_LEASE_TIME_S (24 * 60 * 60) // in seconds
#define MAC_LEN (6)
#define MAKE_IP4(a, b, c, d) ((a) << 24 | (b) << 16 | (c) << 8 | (d))
typedef struct {
uint8_t op; // message opcode
uint8_t htype; // hardware address type
uint8_t hlen; // hardware address length
uint8_t hops;
uint32_t xid; // transaction id, chosen by client
uint16_t secs; // client seconds elapsed
uint16_t flags;
uint8_t ciaddr[4]; // client IP address
uint8_t yiaddr[4]; // your IP address
uint8_t siaddr[4]; // next server IP address
uint8_t giaddr[4]; // relay agent IP address
uint8_t chaddr[16]; // client hardware address
uint8_t sname[64]; // server host name
uint8_t file[128]; // boot file name
uint8_t options[312]; // optional parameters, variable, starts with magic
} dhcp_msg_t;
static int dhcp_socket_new_dgram(struct udp_pcb **udp, void *cb_data, udp_recv_fn cb_udp_recv) {
// family is AF_INET
// type is SOCK_DGRAM
*udp = udp_new();
if (*udp == NULL) {
return -MP_ENOMEM;
}
// Register callback
udp_recv(*udp, cb_udp_recv, (void *)cb_data);
return 0; // success
}
static void dhcp_socket_free(struct udp_pcb **udp) {
if (*udp != NULL) {
udp_remove(*udp);
*udp = NULL;
}
}
static int dhcp_socket_bind(struct udp_pcb **udp, uint32_t ip, uint16_t port) {
ip_addr_t addr;
IP4_ADDR(&addr, ip >> 24 & 0xff, ip >> 16 & 0xff, ip >> 8 & 0xff, ip & 0xff);
// TODO convert lwIP errors to errno
return udp_bind(*udp, &addr, port);
}
static int dhcp_socket_sendto(struct udp_pcb **udp, const void *buf, size_t len, uint32_t ip, uint16_t port) {
if (len > 0xffff) {
len = 0xffff;
}
struct pbuf *p = pbuf_alloc(PBUF_TRANSPORT, len, PBUF_RAM);
if (p == NULL) {
return -MP_ENOMEM;
}
memcpy(p->payload, buf, len);
ip_addr_t dest;
IP4_ADDR(&dest, ip >> 24 & 0xff, ip >> 16 & 0xff, ip >> 8 & 0xff, ip & 0xff);
err_t err = udp_sendto(*udp, p, &dest, port);
pbuf_free(p);
if (err != ERR_OK) {
return err;
}
return len;
}
static uint8_t *opt_find(uint8_t *opt, uint8_t cmd) {
for (int i = 0; i < 308 && opt[i] != DHCP_OPT_END;) {
if (opt[i] == cmd) {
return &opt[i];
}
i += 2 + opt[i + 1];
}
return NULL;
}
static void opt_write_n(uint8_t **opt, uint8_t cmd, size_t n, void *data) {
uint8_t *o = *opt;
*o++ = cmd;
*o++ = n;
memcpy(o, data, n);
*opt = o + n;
}
static void opt_write_u8(uint8_t **opt, uint8_t cmd, uint8_t val) {
uint8_t *o = *opt;
*o++ = cmd;
*o++ = 1;
*o++ = val;
*opt = o;
}
static void opt_write_u32(uint8_t **opt, uint8_t cmd, uint32_t val) {
uint8_t *o = *opt;
*o++ = cmd;
*o++ = 4;
*o++ = val >> 24;
*o++ = val >> 16;
*o++ = val >> 8;
*o++ = val;
*opt = o;
}
static void dhcp_server_process(void *arg, struct udp_pcb *upcb, struct pbuf *p, const ip_addr_t *src_addr, u16_t src_port) {
dhcp_server_t *d = arg;
(void)upcb;
(void)src_addr;
(void)src_port;
// This is around 548 bytes
dhcp_msg_t dhcp_msg;
#define DHCP_MIN_SIZE (240 + 3)
if (p->tot_len < DHCP_MIN_SIZE) {
goto ignore_request;
}
size_t len = pbuf_copy_partial(p, &dhcp_msg, sizeof(dhcp_msg), 0);
if (len < DHCP_MIN_SIZE) {
goto ignore_request;
}
dhcp_msg.op = DHCPOFFER;
memcpy(&dhcp_msg.yiaddr, &d->ip.addr, 4);
uint8_t *opt = (uint8_t *)&dhcp_msg.options;
opt += 4; // assume magic cookie: 99, 130, 83, 99
switch (opt[2]) {
case DHCPDISCOVER: {
int yi = DHCPS_MAX_IP;
for (int i = 0; i < DHCPS_MAX_IP; ++i) {
if (memcmp(d->lease[i].mac, dhcp_msg.chaddr, MAC_LEN) == 0) {
// MAC match, use this IP address
yi = i;
break;
}
if (yi == DHCPS_MAX_IP) {
// Look for a free IP address
if (memcmp(d->lease[i].mac, "\x00\x00\x00\x00\x00\x00", MAC_LEN) == 0) {
// IP available
yi = i;
}
uint32_t expiry = d->lease[i].expiry << 16 | 0xffff;
if ((int32_t)(expiry - mp_hal_ticks_ms()) < 0) {
// IP expired, reuse it
memset(d->lease[i].mac, 0, MAC_LEN);
yi = i;
}
}
}
if (yi == DHCPS_MAX_IP) {
// No more IP addresses left
goto ignore_request;
}
dhcp_msg.yiaddr[3] = DHCPS_BASE_IP + yi;
opt_write_u8(&opt, DHCP_OPT_MSG_TYPE, DHCPOFFER);
break;
}
case DHCPREQUEST: {
uint8_t *o = opt_find(opt, DHCP_OPT_REQUESTED_IP);
if (o == NULL) {
// Should be NACK
goto ignore_request;
}
if (memcmp(o + 2, &d->ip.addr, 3) != 0) {
// Should be NACK
goto ignore_request;
}
uint8_t yi = o[5] - DHCPS_BASE_IP;
if (yi >= DHCPS_MAX_IP) {
// Should be NACK
goto ignore_request;
}
if (memcmp(d->lease[yi].mac, dhcp_msg.chaddr, MAC_LEN) == 0) {
// MAC match, ok to use this IP address
} else if (memcmp(d->lease[yi].mac, "\x00\x00\x00\x00\x00\x00", MAC_LEN) == 0) {
// IP unused, ok to use this IP address
memcpy(d->lease[yi].mac, dhcp_msg.chaddr, MAC_LEN);
} else {
// IP already in use
// Should be NACK
goto ignore_request;
}
d->lease[yi].expiry = (mp_hal_ticks_ms() + DEFAULT_LEASE_TIME_S * 1000) >> 16;
dhcp_msg.yiaddr[3] = DHCPS_BASE_IP + yi;
opt_write_u8(&opt, DHCP_OPT_MSG_TYPE, DHCPACK);
printf("DHCPS: client connected: MAC=%02x:%02x:%02x:%02x:%02x:%02x IP=%u.%u.%u.%u\n",
dhcp_msg.chaddr[0], dhcp_msg.chaddr[1], dhcp_msg.chaddr[2], dhcp_msg.chaddr[3], dhcp_msg.chaddr[4], dhcp_msg.chaddr[5],
dhcp_msg.yiaddr[0], dhcp_msg.yiaddr[1], dhcp_msg.yiaddr[2], dhcp_msg.yiaddr[3]);
break;
}
default:
goto ignore_request;
}
opt_write_n(&opt, DHCP_OPT_SERVER_ID, 4, &d->ip.addr);
opt_write_n(&opt, DHCP_OPT_SUBNET_MASK, 4, &d->nm.addr);
opt_write_n(&opt, DHCP_OPT_ROUTER, 4, &d->ip.addr); // aka gateway; can have mulitple addresses
opt_write_u32(&opt, DHCP_OPT_DNS, DEFAULT_DNS); // can have mulitple addresses
opt_write_u32(&opt, DHCP_OPT_IP_LEASE_TIME, DEFAULT_LEASE_TIME_S);
*opt++ = DHCP_OPT_END;
dhcp_socket_sendto(&d->udp, &dhcp_msg, opt - (uint8_t *)&dhcp_msg, 0xffffffff, PORT_DHCP_CLIENT);
ignore_request:
pbuf_free(p);
}
void dhcp_server_init(dhcp_server_t *d, ip_addr_t *ip, ip_addr_t *nm) {
ip_addr_copy(d->ip, *ip);
ip_addr_copy(d->nm, *nm);
memset(d->lease, 0, sizeof(d->lease));
if (dhcp_socket_new_dgram(&d->udp, d, dhcp_server_process) != 0) {
return;
}
dhcp_socket_bind(&d->udp, 0, PORT_DHCP_SERVER);
}
void dhcp_server_deinit(dhcp_server_t *d) {
dhcp_socket_free(&d->udp);
}
#endif // MICROPY_PY_LWIP
| YifuLiu/AliOS-Things | components/py_engine/engine/shared/netutils/dhcpserver.c | C | apache-2.0 | 9,895 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2018-2019 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.
*/
#ifndef MICROPY_INCLUDED_LIB_NETUTILS_DHCPSERVER_H
#define MICROPY_INCLUDED_LIB_NETUTILS_DHCPSERVER_H
#include "lwip/ip_addr.h"
#define DHCPS_BASE_IP (16)
#define DHCPS_MAX_IP (8)
typedef struct _dhcp_server_lease_t {
uint8_t mac[6];
uint16_t expiry;
} dhcp_server_lease_t;
typedef struct _dhcp_server_t {
ip_addr_t ip;
ip_addr_t nm;
dhcp_server_lease_t lease[DHCPS_MAX_IP];
struct udp_pcb *udp;
} dhcp_server_t;
void dhcp_server_init(dhcp_server_t *d, ip_addr_t *ip, ip_addr_t *nm);
void dhcp_server_deinit(dhcp_server_t *d);
#endif // MICROPY_INCLUDED_LIB_NETUTILS_DHCPSERVER_H
| YifuLiu/AliOS-Things | components/py_engine/engine/shared/netutils/dhcpserver.h | C | apache-2.0 | 1,840 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2013, 2014 Damien P. George
* Copyright (c) 2015 Daniel Campora
*
* 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 <stdint.h>
#include <stdio.h>
#include <string.h>
#include "py/runtime.h"
#include "shared/netutils/netutils.h"
// Takes an array with a raw IPv4 address and returns something like '192.168.0.1'.
mp_obj_t netutils_format_ipv4_addr(uint8_t *ip, netutils_endian_t endian) {
char ip_str[16];
mp_uint_t ip_len;
if (endian == NETUTILS_LITTLE) {
ip_len = snprintf(ip_str, 16, "%u.%u.%u.%u", ip[3], ip[2], ip[1], ip[0]);
} else {
ip_len = snprintf(ip_str, 16, "%u.%u.%u.%u", ip[0], ip[1], ip[2], ip[3]);
}
return mp_obj_new_str(ip_str, ip_len);
}
// Takes an array with a raw IP address, and a port, and returns a net-address
// tuple such as ('192.168.0.1', 8080).
mp_obj_t netutils_format_inet_addr(uint8_t *ip, mp_uint_t port, netutils_endian_t endian) {
mp_obj_t tuple[2] = {
tuple[0] = netutils_format_ipv4_addr(ip, endian),
tuple[1] = mp_obj_new_int(port),
};
return mp_obj_new_tuple(2, tuple);
}
void netutils_parse_ipv4_addr(mp_obj_t addr_in, uint8_t *out_ip, netutils_endian_t endian) {
size_t addr_len;
const char *addr_str = mp_obj_str_get_data(addr_in, &addr_len);
if (addr_len == 0) {
// special case of no address given
memset(out_ip, 0, NETUTILS_IPV4ADDR_BUFSIZE);
return;
}
const char *s = addr_str;
const char *s_top = addr_str + addr_len;
for (mp_uint_t i = 3; ; i--) {
mp_uint_t val = 0;
for (; s < s_top && *s != '.'; s++) {
val = val * 10 + *s - '0';
}
if (endian == NETUTILS_LITTLE) {
out_ip[i] = val;
} else {
out_ip[NETUTILS_IPV4ADDR_BUFSIZE - 1 - i] = val;
}
if (i == 0 && s == s_top) {
return;
} else if (i > 0 && s < s_top && *s == '.') {
s++;
} else {
mp_raise_ValueError(MP_ERROR_TEXT("invalid arguments"));
}
}
}
// Takes an address of the form ('192.168.0.1', 8080), returns the port and
// puts IP in out_ip (which must take at least IPADDR_BUF_SIZE bytes).
mp_uint_t netutils_parse_inet_addr(mp_obj_t addr_in, uint8_t *out_ip, netutils_endian_t endian) {
mp_obj_t *addr_items;
mp_obj_get_array_fixed_n(addr_in, 2, &addr_items);
netutils_parse_ipv4_addr(addr_items[0], out_ip, endian);
return mp_obj_get_int(addr_items[1]);
}
| YifuLiu/AliOS-Things | components/py_engine/engine/shared/netutils/netutils.c | C | apache-2.0 | 3,626 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2013, 2014 Damien P. George
* Copyright (c) 2015 Daniel Campora
*
* 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.
*/
#ifndef MICROPY_INCLUDED_LIB_NETUTILS_NETUTILS_H
#define MICROPY_INCLUDED_LIB_NETUTILS_NETUTILS_H
#define NETUTILS_IPV4ADDR_BUFSIZE 4
#define NETUTILS_TRACE_IS_TX (0x0001)
#define NETUTILS_TRACE_PAYLOAD (0x0002)
#define NETUTILS_TRACE_NEWLINE (0x0004)
// Modified bt HaaS begin
#include "py/mpprint.h"
#include "py/obj.h"
// Modified bt HaaS end
typedef enum _netutils_endian_t {
NETUTILS_LITTLE,
NETUTILS_BIG,
} netutils_endian_t;
// Takes an array with a raw IPv4 address and returns something like '192.168.0.1'.
mp_obj_t netutils_format_ipv4_addr(uint8_t *ip, netutils_endian_t endian);
// Takes an array with a raw IP address, and a port, and returns a net-address
// tuple such as ('192.168.0.1', 8080).
mp_obj_t netutils_format_inet_addr(uint8_t *ip, mp_uint_t port, netutils_endian_t endian);
void netutils_parse_ipv4_addr(mp_obj_t addr_in, uint8_t *out_ip, netutils_endian_t endian);
// Takes an address of the form ('192.168.0.1', 8080), returns the port and
// puts IP in out_ip (which must take at least IPADDR_BUF_SIZE bytes).
mp_uint_t netutils_parse_inet_addr(mp_obj_t addr_in, uint8_t *out_ip, netutils_endian_t endian);
void netutils_ethernet_trace(const mp_print_t *print, size_t len, const uint8_t *buf, unsigned int flags);
#endif // MICROPY_INCLUDED_LIB_NETUTILS_NETUTILS_H
| YifuLiu/AliOS-Things | components/py_engine/engine/shared/netutils/netutils.h | C | apache-2.0 | 2,601 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2019 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 "py/mphal.h"
#include "shared/netutils/netutils.h"
static uint32_t get_be16(const uint8_t *buf) {
return buf[0] << 8 | buf[1];
}
static uint32_t get_be32(const uint8_t *buf) {
return buf[0] << 24 | buf[1] << 16 | buf[2] << 8 | buf[3];
}
static void dump_hex_bytes(const mp_print_t *print, size_t len, const uint8_t *buf) {
for (size_t i = 0; i < len; ++i) {
mp_printf(print, " %02x", buf[i]);
}
}
static const char *ethertype_str(uint16_t type) {
// A value between 0x0000 - 0x05dc (inclusive) indicates a length, not type
switch (type) {
case 0x0800:
return "IPv4";
case 0x0806:
return "ARP";
case 0x86dd:
return "IPv6";
default:
return NULL;
}
}
void netutils_ethernet_trace(const mp_print_t *print, size_t len, const uint8_t *buf, unsigned int flags) {
mp_printf(print, "[% 8d] ETH%cX len=%u", mp_hal_ticks_ms(), flags & NETUTILS_TRACE_IS_TX ? 'T' : 'R', len);
mp_printf(print, " dst=%02x:%02x:%02x:%02x:%02x:%02x", buf[0], buf[1], buf[2], buf[3], buf[4], buf[5]);
mp_printf(print, " src=%02x:%02x:%02x:%02x:%02x:%02x", buf[6], buf[7], buf[8], buf[9], buf[10], buf[11]);
const char *ethertype = ethertype_str(buf[12] << 8 | buf[13]);
if (ethertype) {
mp_printf(print, " type=%s", ethertype);
} else {
mp_printf(print, " type=0x%04x", buf[12] << 8 | buf[13]);
}
if (len > 14) {
len -= 14;
buf += 14;
if (buf[-2] == 0x08 && buf[-1] == 0x00 && buf[0] == 0x45) {
// IPv4 packet
len = get_be16(buf + 2);
mp_printf(print, " srcip=%u.%u.%u.%u dstip=%u.%u.%u.%u",
buf[12], buf[13], buf[14], buf[15],
buf[16], buf[17], buf[18], buf[19]);
uint8_t prot = buf[9];
buf += 20;
len -= 20;
if (prot == 6) {
// TCP packet
uint16_t srcport = get_be16(buf);
uint16_t dstport = get_be16(buf + 2);
uint32_t seqnum = get_be32(buf + 4);
uint32_t acknum = get_be32(buf + 8);
uint16_t dataoff_flags = get_be16(buf + 12);
uint16_t winsz = get_be16(buf + 14);
mp_printf(print, " TCP srcport=%u dstport=%u seqnum=%u acknum=%u dataoff=%u flags=%x winsz=%u",
srcport, dstport, (unsigned)seqnum, (unsigned)acknum, dataoff_flags >> 12, dataoff_flags & 0x1ff, winsz);
buf += 20;
len -= 20;
if (dataoff_flags >> 12 > 5) {
mp_printf(print, " opts=");
size_t opts_len = ((dataoff_flags >> 12) - 5) * 4;
dump_hex_bytes(print, opts_len, buf);
buf += opts_len;
len -= opts_len;
}
} else if (prot == 17) {
// UDP packet
uint16_t srcport = get_be16(buf);
uint16_t dstport = get_be16(buf + 2);
mp_printf(print, " UDP srcport=%u dstport=%u", srcport, dstport);
len = get_be16(buf + 4);
buf += 8;
if ((srcport == 67 && dstport == 68) || (srcport == 68 && dstport == 67)) {
// DHCP
if (srcport == 67) {
mp_printf(print, " DHCPS");
} else {
mp_printf(print, " DHCPC");
}
dump_hex_bytes(print, 12 + 16 + 16 + 64, buf);
size_t n = 12 + 16 + 16 + 64 + 128;
len -= n;
buf += n;
mp_printf(print, " opts:");
switch (buf[6]) {
case 1:
mp_printf(print, " DISCOVER");
break;
case 2:
mp_printf(print, " OFFER");
break;
case 3:
mp_printf(print, " REQUEST");
break;
case 4:
mp_printf(print, " DECLINE");
break;
case 5:
mp_printf(print, " ACK");
break;
case 6:
mp_printf(print, " NACK");
break;
case 7:
mp_printf(print, " RELEASE");
break;
case 8:
mp_printf(print, " INFORM");
break;
}
}
} else {
// Non-UDP packet
mp_printf(print, " prot=%u", prot);
}
} else if (buf[-2] == 0x86 && buf[-1] == 0xdd && (buf[0] >> 4) == 6) {
// IPv6 packet
uint32_t h = get_be32(buf);
uint16_t l = get_be16(buf + 4);
mp_printf(print, " tclass=%u flow=%u len=%u nexthdr=%u hoplimit=%u", (unsigned)((h >> 20) & 0xff), (unsigned)(h & 0xfffff), l, buf[6], buf[7]);
mp_printf(print, " srcip=");
dump_hex_bytes(print, 16, buf + 8);
mp_printf(print, " dstip=");
dump_hex_bytes(print, 16, buf + 24);
buf += 40;
len -= 40;
}
if (flags & NETUTILS_TRACE_PAYLOAD) {
mp_printf(print, " data=");
dump_hex_bytes(print, len, buf);
}
}
if (flags & NETUTILS_TRACE_NEWLINE) {
mp_printf(print, "\n");
}
}
| YifuLiu/AliOS-Things | components/py_engine/engine/shared/netutils/trace.c | C | apache-2.0 | 6,968 |
/*
* 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 <stdio.h>
#include <stdint.h>
#include <string.h>
#include "py/mpstate.h"
#include "py/repl.h"
#include "py/mphal.h"
#include "shared/readline/readline.h"
#if 0 // print debugging info
#define DEBUG_PRINT (1)
#define DEBUG_printf printf
#else // don't print debugging info
#define DEBUG_printf(...) (void)0
#endif
#define READLINE_HIST_SIZE (MP_ARRAY_SIZE(MP_STATE_PORT(readline_hist)))
enum { ESEQ_NONE, ESEQ_ESC, ESEQ_ESC_BRACKET, ESEQ_ESC_BRACKET_DIGIT, ESEQ_ESC_O };
void readline_init0(void) {
memset(MP_STATE_PORT(readline_hist), 0, READLINE_HIST_SIZE * sizeof(const char*));
}
STATIC char *str_dup_maybe(const char *str) {
uint32_t len = strlen(str);
char *s2 = m_new_maybe(char, len + 1);
if (s2 == NULL) {
return NULL;
}
memcpy(s2, str, len + 1);
return s2;
}
// By default assume terminal which implements VT100 commands...
#ifndef MICROPY_HAL_HAS_VT100
#define MICROPY_HAL_HAS_VT100 (1)
#endif
// ...and provide the implementation using them
#if MICROPY_HAL_HAS_VT100
STATIC void mp_hal_move_cursor_back(uint pos) {
if (pos <= 4) {
// fast path for most common case of 1 step back
mp_hal_stdout_tx_strn("\b\b\b\b", pos);
} else {
char vt100_command[6];
// snprintf needs space for the terminating null character
int n = snprintf(&vt100_command[0], sizeof(vt100_command), "\x1b[%u", pos);
if (n > 0) {
assert((unsigned)n < sizeof(vt100_command));
vt100_command[n] = 'D'; // replace null char
mp_hal_stdout_tx_strn(vt100_command, n + 1);
}
}
}
STATIC void mp_hal_erase_line_from_cursor(uint n_chars_to_erase) {
(void)n_chars_to_erase;
mp_hal_stdout_tx_strn("\x1b[K", 3);
}
#endif
typedef struct _readline_t {
vstr_t *line;
size_t orig_line_len;
int escape_seq;
int hist_cur;
size_t cursor_pos;
char escape_seq_buf[1];
const char *prompt;
} readline_t;
STATIC readline_t rl;
#if MICROPY_REPL_EMACS_WORDS_MOVE
STATIC size_t cursor_count_word(int forward) {
const char *line_buf = vstr_str(rl.line);
size_t pos = rl.cursor_pos;
bool in_word = false;
for (;;) {
// if moving backwards and we've reached 0... break
if (!forward && pos == 0) {
break;
}
// or if moving forwards and we've reached to the end of line... break
else if (forward && pos == vstr_len(rl.line)) {
break;
}
if (unichar_isalnum(line_buf[pos + (forward - 1)])) {
in_word = true;
} else if (in_word) {
break;
}
pos += forward ? forward : -1;
}
return forward ? pos - rl.cursor_pos : rl.cursor_pos - pos;
}
#endif
int readline_process_char(int c) {
size_t last_line_len = rl.line->len;
int redraw_step_back = 0;
bool redraw_from_cursor = false;
int redraw_step_forward = 0;
if (rl.escape_seq == ESEQ_NONE) {
if (CHAR_CTRL_A <= c && c <= CHAR_CTRL_E && vstr_len(rl.line) == rl.orig_line_len) {
// control character with empty line
return c;
#if MICROPY_PY_AOS_QUIT
} else if (c == CHAR_CTRL_X && vstr_len(rl.line) == rl.orig_line_len) {
// CTRL-Q with non-empty line is delete-at-cursor
return c;
#endif
} else if (c == CHAR_CTRL_A) {
// CTRL-A with non-empty line is go-to-start-of-line
goto home_key;
#if MICROPY_REPL_EMACS_KEYS
} else if (c == CHAR_CTRL_B) {
// CTRL-B with non-empty line is go-back-one-char
goto left_arrow_key;
#endif
} else if (c == CHAR_CTRL_C) {
// CTRL-C with non-empty line is cancel
return c;
#if MICROPY_REPL_EMACS_KEYS
} else if (c == CHAR_CTRL_D) {
// CTRL-D with non-empty line is delete-at-cursor
goto delete_key;
#endif
} else if (c == CHAR_CTRL_E) {
// CTRL-E is go-to-end-of-line
goto end_key;
#if MICROPY_REPL_EMACS_KEYS
} else if (c == CHAR_CTRL_F) {
// CTRL-F with non-empty line is go-forward-one-char
goto right_arrow_key;
} else if (c == CHAR_CTRL_K) {
// CTRL-K is kill from cursor to end-of-line, inclusive
vstr_cut_tail_bytes(rl.line, last_line_len - rl.cursor_pos);
// set redraw parameters
redraw_from_cursor = true;
} else if (c == CHAR_CTRL_N) {
// CTRL-N is go to next line in history
goto down_arrow_key;
} else if (c == CHAR_CTRL_P) {
// CTRL-P is go to previous line in history
goto up_arrow_key;
} else if (c == CHAR_CTRL_U) {
// CTRL-U is kill from beginning-of-line up to cursor
vstr_cut_out_bytes(rl.line, rl.orig_line_len, rl.cursor_pos - rl.orig_line_len);
// set redraw parameters
redraw_step_back = rl.cursor_pos - rl.orig_line_len;
redraw_from_cursor = true;
#endif
#if MICROPY_REPL_EMACS_EXTRA_WORDS_MOVE
} else if (c == CHAR_CTRL_W) {
goto backward_kill_word;
#endif
} else if (c == '\r') {
// newline
mp_hal_stdout_tx_str("\r\n");
readline_push_history(vstr_null_terminated_str(rl.line) + rl.orig_line_len);
return 0;
} else if (c == 27) {
// escape sequence
rl.escape_seq = ESEQ_ESC;
} else if (c == 8 || c == 127) {
// backspace/delete
if (rl.cursor_pos > rl.orig_line_len) {
// work out how many chars to backspace
#if MICROPY_REPL_AUTO_INDENT
int nspace = 0;
for (size_t i = rl.orig_line_len; i < rl.cursor_pos; i++) {
if (rl.line->buf[i] != ' ') {
nspace = 0;
break;
}
nspace += 1;
}
if (nspace < 4) {
nspace = 1;
} else {
nspace = 4;
}
#else
int nspace = 1;
#endif
// do the backspace
vstr_cut_out_bytes(rl.line, rl.cursor_pos - nspace, nspace);
// set redraw parameters
redraw_step_back = nspace;
redraw_from_cursor = true;
}
#if MICROPY_HELPER_REPL
} else if (c == 9) {
// tab magic
const char *compl_str;
size_t compl_len = mp_repl_autocomplete(rl.line->buf + rl.orig_line_len, rl.cursor_pos - rl.orig_line_len, &mp_plat_print, &compl_str);
if (compl_len == 0) {
// no match
} else if (compl_len == (size_t)(-1)) {
// many matches
mp_hal_stdout_tx_str(rl.prompt);
mp_hal_stdout_tx_strn(rl.line->buf + rl.orig_line_len, rl.cursor_pos - rl.orig_line_len);
redraw_from_cursor = true;
} else {
// one match
for (size_t i = 0; i < compl_len; ++i) {
vstr_ins_byte(rl.line, rl.cursor_pos + i, *compl_str++);
}
// set redraw parameters
redraw_from_cursor = true;
redraw_step_forward = compl_len;
}
#endif
} else if (32 <= c && c <= 126) {
// printable character
vstr_ins_char(rl.line, rl.cursor_pos, c);
// set redraw parameters
redraw_from_cursor = true;
redraw_step_forward = 1;
}
} else if (rl.escape_seq == ESEQ_ESC) {
switch (c) {
case '[':
rl.escape_seq = ESEQ_ESC_BRACKET;
break;
case 'O':
rl.escape_seq = ESEQ_ESC_O;
break;
#if MICROPY_REPL_EMACS_WORDS_MOVE
case 'b':
#if MICROPY_REPL_EMACS_EXTRA_WORDS_MOVE
backward_word:
#endif
redraw_step_back = cursor_count_word(0);
rl.escape_seq = ESEQ_NONE;
break;
case 'f':
#if MICROPY_REPL_EMACS_EXTRA_WORDS_MOVE
forward_word:
#endif
redraw_step_forward = cursor_count_word(1);
rl.escape_seq = ESEQ_NONE;
break;
case 'd':
vstr_cut_out_bytes(rl.line, rl.cursor_pos, cursor_count_word(1));
redraw_from_cursor = true;
rl.escape_seq = ESEQ_NONE;
break;
case 127:
#if MICROPY_REPL_EMACS_EXTRA_WORDS_MOVE
backward_kill_word:
#endif
redraw_step_back = cursor_count_word(0);
vstr_cut_out_bytes(rl.line, rl.cursor_pos - redraw_step_back, redraw_step_back);
redraw_from_cursor = true;
rl.escape_seq = ESEQ_NONE;
break;
#endif
default:
DEBUG_printf("(ESC %d)", c);
rl.escape_seq = ESEQ_NONE;
break;
}
} else if (rl.escape_seq == ESEQ_ESC_BRACKET) {
if ('0' <= c && c <= '9') {
rl.escape_seq = ESEQ_ESC_BRACKET_DIGIT;
rl.escape_seq_buf[0] = c;
} else {
rl.escape_seq = ESEQ_NONE;
if (c == 'A') {
#if MICROPY_REPL_EMACS_KEYS
up_arrow_key:
#endif
// up arrow
if (rl.hist_cur + 1 < (int)READLINE_HIST_SIZE && MP_STATE_PORT(readline_hist)[rl.hist_cur + 1] != NULL) {
// increase hist num
rl.hist_cur += 1;
// set line to history
rl.line->len = rl.orig_line_len;
vstr_add_str(rl.line, MP_STATE_PORT(readline_hist)[rl.hist_cur]);
// set redraw parameters
redraw_step_back = rl.cursor_pos - rl.orig_line_len;
redraw_from_cursor = true;
redraw_step_forward = rl.line->len - rl.orig_line_len;
}
} else if (c == 'B') {
#if MICROPY_REPL_EMACS_KEYS
down_arrow_key:
#endif
// down arrow
if (rl.hist_cur >= 0) {
// decrease hist num
rl.hist_cur -= 1;
// set line to history
vstr_cut_tail_bytes(rl.line, rl.line->len - rl.orig_line_len);
if (rl.hist_cur >= 0) {
vstr_add_str(rl.line, MP_STATE_PORT(readline_hist)[rl.hist_cur]);
}
// set redraw parameters
redraw_step_back = rl.cursor_pos - rl.orig_line_len;
redraw_from_cursor = true;
redraw_step_forward = rl.line->len - rl.orig_line_len;
}
} else if (c == 'C') {
#if MICROPY_REPL_EMACS_KEYS
right_arrow_key:
#endif
// right arrow
if (rl.cursor_pos < rl.line->len) {
redraw_step_forward = 1;
}
} else if (c == 'D') {
#if MICROPY_REPL_EMACS_KEYS
left_arrow_key:
#endif
// left arrow
if (rl.cursor_pos > rl.orig_line_len) {
redraw_step_back = 1;
}
} else if (c == 'H') {
// home
goto home_key;
} else if (c == 'F') {
// end
goto end_key;
} else {
DEBUG_printf("(ESC [ %d)", c);
}
}
} else if (rl.escape_seq == ESEQ_ESC_BRACKET_DIGIT) {
if (c == '~') {
if (rl.escape_seq_buf[0] == '1' || rl.escape_seq_buf[0] == '7') {
home_key:
redraw_step_back = rl.cursor_pos - rl.orig_line_len;
} else if (rl.escape_seq_buf[0] == '4' || rl.escape_seq_buf[0] == '8') {
end_key:
redraw_step_forward = rl.line->len - rl.cursor_pos;
} else if (rl.escape_seq_buf[0] == '3') {
// delete
#if MICROPY_REPL_EMACS_KEYS
delete_key:
#endif
if (rl.cursor_pos < rl.line->len) {
vstr_cut_out_bytes(rl.line, rl.cursor_pos, 1);
redraw_from_cursor = true;
}
} else {
DEBUG_printf("(ESC [ %c %d)", rl.escape_seq_buf[0], c);
}
#if MICROPY_REPL_EMACS_EXTRA_WORDS_MOVE
} else if (c == ';' && rl.escape_seq_buf[0] == '1') {
// ';' is used to separate parameters. so first parameter was '1',
// that's used for sequences like ctrl+left, which we will try to parse.
// escape_seq state is reset back to ESEQ_ESC_BRACKET, as if we've just received
// the opening bracket, because more parameters are to come.
// we don't track the parameters themselves to keep low on logic and code size. that
// might be required in the future if more complex sequences are added.
rl.escape_seq = ESEQ_ESC_BRACKET;
// goto away from the state-machine, as rl.escape_seq will be overridden.
goto redraw;
} else if (rl.escape_seq_buf[0] == '5' && c == 'C') {
// ctrl+right
goto forward_word;
} else if (rl.escape_seq_buf[0] == '5' && c == 'D') {
// ctrl+left
goto backward_word;
#endif
} else {
DEBUG_printf("(ESC [ %c %d)", rl.escape_seq_buf[0], c);
}
rl.escape_seq = ESEQ_NONE;
} else if (rl.escape_seq == ESEQ_ESC_O) {
switch (c) {
case 'H':
goto home_key;
case 'F':
goto end_key;
default:
DEBUG_printf("(ESC O %d)", c);
rl.escape_seq = ESEQ_NONE;
}
} else {
rl.escape_seq = ESEQ_NONE;
}
#if MICROPY_REPL_EMACS_EXTRA_WORDS_MOVE
redraw:
#endif
// redraw command prompt, efficiently
if (redraw_step_back > 0) {
mp_hal_move_cursor_back(redraw_step_back);
rl.cursor_pos -= redraw_step_back;
}
if (redraw_from_cursor) {
if (rl.line->len < last_line_len) {
// erase old chars
mp_hal_erase_line_from_cursor(last_line_len - rl.cursor_pos);
}
// draw new chars
mp_hal_stdout_tx_strn(rl.line->buf + rl.cursor_pos, rl.line->len - rl.cursor_pos);
// move cursor forward if needed (already moved forward by length of line, so move it back)
mp_hal_move_cursor_back(rl.line->len - (rl.cursor_pos + redraw_step_forward));
rl.cursor_pos += redraw_step_forward;
} else if (redraw_step_forward > 0) {
// draw over old chars to move cursor forwards
mp_hal_stdout_tx_strn(rl.line->buf + rl.cursor_pos, redraw_step_forward);
rl.cursor_pos += redraw_step_forward;
}
return -1;
}
#if MICROPY_REPL_AUTO_INDENT
STATIC void readline_auto_indent(void) {
vstr_t *line = rl.line;
if (line->len > 1 && line->buf[line->len - 1] == '\n') {
int i;
for (i = line->len - 1; i > 0; i--) {
if (line->buf[i - 1] == '\n') {
break;
}
}
size_t j;
for (j = i; j < line->len; j++) {
if (line->buf[j] != ' ') {
break;
}
}
// i=start of line; j=first non-space
if (i > 0 && j + 1 == line->len) {
// previous line is not first line and is all spaces
for (size_t k = i - 1; k > 0; --k) {
if (line->buf[k - 1] == '\n') {
// don't auto-indent if last 2 lines are all spaces
return;
} else if (line->buf[k - 1] != ' ') {
// 2nd previous line is not all spaces
break;
}
}
}
int n = (j - i) / 4;
if (line->buf[line->len - 2] == ':') {
n += 1;
}
while (n-- > 0) {
vstr_add_strn(line, " ", 4);
mp_hal_stdout_tx_strn(" ", 4);
rl.cursor_pos += 4;
}
}
}
#endif
void readline_note_newline(const char *prompt) {
rl.orig_line_len = rl.line->len;
rl.cursor_pos = rl.orig_line_len;
rl.prompt = prompt;
mp_hal_stdout_tx_str(prompt);
#if MICROPY_REPL_AUTO_INDENT
readline_auto_indent();
#endif
}
void readline_init(vstr_t *line, const char *prompt) {
rl.line = line;
rl.orig_line_len = line->len;
rl.escape_seq = ESEQ_NONE;
rl.escape_seq_buf[0] = 0;
rl.hist_cur = -1;
rl.cursor_pos = rl.orig_line_len;
rl.prompt = prompt;
mp_hal_stdout_tx_str(prompt);
#if MICROPY_REPL_AUTO_INDENT
readline_auto_indent();
#endif
}
int readline(vstr_t *line, const char *prompt) {
readline_init(line, prompt);
for (;;) {
int c = mp_hal_stdin_rx_chr();
int r = readline_process_char(c);
if (r >= 0) {
return r;
}
}
}
void readline_push_history(const char *line) {
if (line[0] != '\0'
&& (MP_STATE_PORT(readline_hist)[0] == NULL
|| strcmp(MP_STATE_PORT(readline_hist)[0], line) != 0)) {
// a line which is not empty and different from the last one
// so update the history
char *most_recent_hist = str_dup_maybe(line);
if (most_recent_hist != NULL) {
for (int i = READLINE_HIST_SIZE - 1; i > 0; i--) {
MP_STATE_PORT(readline_hist)[i] = MP_STATE_PORT(readline_hist)[i - 1];
}
MP_STATE_PORT(readline_hist)[0] = most_recent_hist;
}
}
}
| YifuLiu/AliOS-Things | components/py_engine/engine/shared/readline/readline.c | C | apache-2.0 | 19,028 |
/*
* 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.
*/
#ifndef MICROPY_INCLUDED_LIB_MP_READLINE_READLINE_H
#define MICROPY_INCLUDED_LIB_MP_READLINE_READLINE_H
#define CHAR_CTRL_A (1)
#define CHAR_CTRL_B (2)
#define CHAR_CTRL_C (3)
#define CHAR_CTRL_D (4)
#define CHAR_CTRL_E (5)
#define CHAR_CTRL_F (6)
#define CHAR_CTRL_K (11)
#define CHAR_CTRL_N (14)
#define CHAR_CTRL_P (16)
#define CHAR_CTRL_U (21)
#define CHAR_CTRL_W (23)
#if MICROPY_PY_AOS_QUIT
#define CHAR_CTRL_X (24)
#endif
void readline_init0(void);
int readline(vstr_t *line, const char *prompt);
void readline_push_history(const char *line);
void readline_init(vstr_t *line, const char *prompt);
void readline_note_newline(const char *prompt);
int readline_process_char(int c);
#endif // MICROPY_INCLUDED_LIB_MP_READLINE_READLINE_H
| YifuLiu/AliOS-Things | components/py_engine/engine/shared/readline/readline.h | C | apache-2.0 | 1,975 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2019 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.
*/
#ifndef MICROPY_INCLUDED_LIB_UTILS_GCHELPER_H
#define MICROPY_INCLUDED_LIB_UTILS_GCHELPER_H
#include <stdint.h>
#if MICROPY_GCREGS_SETJMP
#include <setjmp.h>
typedef jmp_buf gc_helper_regs_t;
#else
#if defined(__x86_64__)
typedef uintptr_t gc_helper_regs_t[6];
#elif defined(__i386__)
typedef uintptr_t gc_helper_regs_t[4];
#elif defined(__thumb2__) || defined(__thumb__) || defined(__arm__)
typedef uintptr_t gc_helper_regs_t[10];
#elif defined(__aarch64__)
typedef uintptr_t gc_helper_regs_t[11]; // x19-x29
#endif
#endif
void gc_helper_collect_regs_and_stack(void);
#endif // MICROPY_INCLUDED_LIB_UTILS_GCHELPER_H
| YifuLiu/AliOS-Things | components/py_engine/engine/shared/runtime/gchelper.h | C | apache-2.0 | 1,848 |
/*
* 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 <stdio.h>
#include "py/mpstate.h"
#include "py/gc.h"
#include "shared/runtime/gchelper.h"
#if MICROPY_ENABLE_GC
// Even if we have specific support for an architecture, it is
// possible to force use of setjmp-based implementation.
#if !MICROPY_GCREGS_SETJMP
// We capture here callee-save registers, i.e. ones which may contain
// interesting values held there by our callers. It doesn't make sense
// to capture caller-saved registers, because they, well, put on the
// stack already by the caller.
#if defined(__x86_64__)
STATIC void gc_helper_get_regs(gc_helper_regs_t arr) {
register long rbx asm ("rbx");
register long rbp asm ("rbp");
register long r12 asm ("r12");
register long r13 asm ("r13");
register long r14 asm ("r14");
register long r15 asm ("r15");
#ifdef __clang__
// TODO:
// This is dirty workaround for Clang. It tries to get around
// uncompliant (wrt to GCC) behavior of handling register variables.
// Application of this patch here is random, and done only to unbreak
// MacOS build. Better, cross-arch ways to deal with Clang issues should
// be found.
asm ("" : "=r" (rbx));
asm ("" : "=r" (rbp));
asm ("" : "=r" (r12));
asm ("" : "=r" (r13));
asm ("" : "=r" (r14));
asm ("" : "=r" (r15));
#endif
arr[0] = rbx;
arr[1] = rbp;
arr[2] = r12;
arr[3] = r13;
arr[4] = r14;
arr[5] = r15;
}
#elif defined(__i386__)
STATIC void gc_helper_get_regs(gc_helper_regs_t arr) {
register long ebx asm ("ebx");
register long esi asm ("esi");
register long edi asm ("edi");
register long ebp asm ("ebp");
#ifdef __clang__
// TODO:
// This is dirty workaround for Clang. It tries to get around
// uncompliant (wrt to GCC) behavior of handling register variables.
// Application of this patch here is random, and done only to unbreak
// MacOS build. Better, cross-arch ways to deal with Clang issues should
// be found.
asm ("" : "=r" (ebx));
asm ("" : "=r" (esi));
asm ("" : "=r" (edi));
asm ("" : "=r" (ebp));
#endif
arr[0] = ebx;
arr[1] = esi;
arr[2] = edi;
arr[3] = ebp;
}
#elif defined(__thumb2__) || defined(__thumb__) || defined(__arm__)
// Fallback implementation, prefer gchelper_m0.s or gchelper_m3.s
// Modified bt HaaS begin
#ifndef asm
#define asm __asm
#endif
// Modified bt HaaS end
STATIC void gc_helper_get_regs(gc_helper_regs_t arr) {
register long r4 asm ("r4");
register long r5 asm ("r5");
register long r6 asm ("r6");
register long r7 asm ("r7");
register long r8 asm ("r8");
register long r9 asm ("r9");
register long r10 asm ("r10");
register long r11 asm ("r11");
register long r12 asm ("r12");
register long r13 asm ("r13");
arr[0] = r4;
arr[1] = r5;
arr[2] = r6;
arr[3] = r7;
arr[4] = r8;
arr[5] = r9;
arr[6] = r10;
arr[7] = r11;
arr[8] = r12;
arr[9] = r13;
}
#elif defined(__aarch64__)
STATIC void gc_helper_get_regs(gc_helper_regs_t arr) {
const register long x19 asm ("x19");
const register long x20 asm ("x20");
const register long x21 asm ("x21");
const register long x22 asm ("x22");
const register long x23 asm ("x23");
const register long x24 asm ("x24");
const register long x25 asm ("x25");
const register long x26 asm ("x26");
const register long x27 asm ("x27");
const register long x28 asm ("x28");
const register long x29 asm ("x29");
arr[0] = x19;
arr[1] = x20;
arr[2] = x21;
arr[3] = x22;
arr[4] = x23;
arr[5] = x24;
arr[6] = x25;
arr[7] = x26;
arr[8] = x27;
arr[9] = x28;
arr[10] = x29;
}
#else
#error "Architecture not supported for gc_helper_get_regs. Set MICROPY_GCREGS_SETJMP to use the fallback implementation."
#endif
#else // !MICROPY_GCREGS_SETJMP
// Even if we have specific support for an architecture, it is
// possible to force use of setjmp-based implementation.
STATIC void gc_helper_get_regs(gc_helper_regs_t arr) {
setjmp(arr);
}
#endif // MICROPY_GCREGS_SETJMP
// Explicitly mark this as noinline to make sure the regs variable
// is effectively at the top of the stack: otherwise, in builds where
// LTO is enabled and a lot of inlining takes place we risk a stack
// layout where regs is lower on the stack than pointers which have
// just been allocated but not yet marked, and get incorrectly sweeped.
MP_NOINLINE void gc_helper_collect_regs_and_stack(void) {
gc_helper_regs_t regs;
gc_helper_get_regs(regs);
// GC stack (and regs because we captured them)
void **regs_ptr = (void **)(void *)®s;
gc_collect_root(regs_ptr, ((uintptr_t)MP_STATE_THREAD(stack_top) - (uintptr_t)®s) / sizeof(uintptr_t));
}
#endif // MICROPY_ENABLE_GC
| YifuLiu/AliOS-Things | components/py_engine/engine/shared/runtime/gchelper_generic.c | C | apache-2.0 | 6,046 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2018 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.
*/
.syntax unified
.cpu cortex-m0
.thumb
.section .text
.align 2
.global gc_helper_get_regs_and_sp
.type gc_helper_get_regs_and_sp, %function
@ uint gc_helper_get_regs_and_sp(r0=uint regs[10])
gc_helper_get_regs_and_sp:
@ store registers into given array
str r4, [r0, #0]
str r5, [r0, #4]
str r6, [r0, #8]
str r7, [r0, #12]
mov r1, r8
str r1, [r0, #16]
mov r1, r9
str r1, [r0, #20]
mov r1, r10
str r1, [r0, #24]
mov r1, r11
str r1, [r0, #28]
mov r1, r12
str r1, [r0, #32]
mov r1, r13
str r1, [r0, #36]
@ return the sp
mov r0, sp
bx lr
.size gc_helper_get_regs_and_sp, .-gc_helper_get_regs_and_sp
| YifuLiu/AliOS-Things | components/py_engine/engine/shared/runtime/gchelper_m0.s | Unix Assembly | apache-2.0 | 1,991 |
/*
* 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.
*/
.syntax unified
.cpu cortex-m3
.thumb
.section .text
.align 2
.global gc_helper_get_regs_and_sp
.type gc_helper_get_regs_and_sp, %function
@ uint gc_helper_get_regs_and_sp(r0=uint regs[10])
gc_helper_get_regs_and_sp:
@ store registers into given array
str r4, [r0], #4
str r5, [r0], #4
str r6, [r0], #4
str r7, [r0], #4
str r8, [r0], #4
str r9, [r0], #4
str r10, [r0], #4
str r11, [r0], #4
str r12, [r0], #4
str r13, [r0], #4
@ return the sp
mov r0, sp
bx lr
.size gc_helper_get_regs_and_sp, .-gc_helper_get_regs_and_sp
| YifuLiu/AliOS-Things | components/py_engine/engine/shared/runtime/gchelper_m3.s | Unix Assembly | apache-2.0 | 1,894 |
/*
* 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 <stdio.h>
#include "py/mpstate.h"
#include "py/gc.h"
#include "shared/runtime/gchelper.h"
#if MICROPY_ENABLE_GC
// provided by gchelper_*.s
uintptr_t gc_helper_get_regs_and_sp(uintptr_t *regs);
MP_NOINLINE void gc_helper_collect_regs_and_stack(void) {
// get the registers and the sp
gc_helper_regs_t regs;
uintptr_t sp = gc_helper_get_regs_and_sp(regs);
// trace the stack, including the registers (since they live on the stack in this function)
gc_collect_root((void **)sp, ((uint32_t)MP_STATE_THREAD(stack_top) - sp) / sizeof(uint32_t));
}
#endif
| YifuLiu/AliOS-Things | components/py_engine/engine/shared/runtime/gchelper_native.c | C | apache-2.0 | 1,817 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2013-2016 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 "py/obj.h"
#include "py/mpstate.h"
#if MICROPY_KBD_EXCEPTION
int mp_interrupt_char = -1;
void mp_hal_set_interrupt_char(int c) {
mp_interrupt_char = c;
}
#endif
| YifuLiu/AliOS-Things | components/py_engine/engine/shared/runtime/interrupt_char.c | C | apache-2.0 | 1,409 |