diff --git a/drivers/bus/softqspi.c b/drivers/bus/softqspi.c index 10c5992466..f08fdbaf88 100644 --- a/drivers/bus/softqspi.c +++ b/drivers/bus/softqspi.c @@ -57,7 +57,7 @@ STATIC void nibble_write(mp_soft_qspi_obj_t *self, uint8_t v) { } STATIC int mp_soft_qspi_ioctl(void *self_in, uint32_t cmd) { - mp_soft_qspi_obj_t *self = (mp_soft_qspi_obj_t*)self_in; + mp_soft_qspi_obj_t *self = (mp_soft_qspi_obj_t *)self_in; switch (cmd) { case MP_QSPI_IOCTL_INIT: @@ -67,7 +67,7 @@ STATIC int mp_soft_qspi_ioctl(void *self_in, uint32_t cmd) { // Configure pins mp_hal_pin_write(self->clk, 0); mp_hal_pin_output(self->clk); - //mp_hal_pin_write(self->clk, 1); + // mp_hal_pin_write(self->clk, 1); mp_hal_pin_output(self->io0); mp_hal_pin_input(self->io1); mp_hal_pin_write(self->io2, 1); @@ -155,19 +155,19 @@ STATIC void mp_soft_qspi_qwrite(mp_soft_qspi_obj_t *self, size_t len, const uint SCK_LOW(self); } - //mp_hal_pin_input(self->io1); + // mp_hal_pin_input(self->io1); } STATIC void mp_soft_qspi_write_cmd_data(void *self_in, uint8_t cmd, size_t len, uint32_t data) { - mp_soft_qspi_obj_t *self = (mp_soft_qspi_obj_t*)self_in; + mp_soft_qspi_obj_t *self = (mp_soft_qspi_obj_t *)self_in; uint32_t cmd_buf = cmd | data << 8; CS_LOW(self); - mp_soft_qspi_transfer(self, 1 + len, (uint8_t*)&cmd_buf, NULL); + mp_soft_qspi_transfer(self, 1 + len, (uint8_t *)&cmd_buf, NULL); CS_HIGH(self); } STATIC void mp_soft_qspi_write_cmd_addr_data(void *self_in, uint8_t cmd, uint32_t addr, size_t len, const uint8_t *src) { - mp_soft_qspi_obj_t *self = (mp_soft_qspi_obj_t*)self_in; + mp_soft_qspi_obj_t *self = (mp_soft_qspi_obj_t *)self_in; uint8_t cmd_buf[4] = {cmd, addr >> 16, addr >> 8, addr}; CS_LOW(self); mp_soft_qspi_transfer(self, 4, cmd_buf, NULL); @@ -176,16 +176,16 @@ STATIC void mp_soft_qspi_write_cmd_addr_data(void *self_in, uint8_t cmd, uint32_ } STATIC uint32_t mp_soft_qspi_read_cmd(void *self_in, uint8_t cmd, size_t len) { - mp_soft_qspi_obj_t *self = (mp_soft_qspi_obj_t*)self_in; + mp_soft_qspi_obj_t *self = (mp_soft_qspi_obj_t *)self_in; uint32_t cmd_buf = cmd; CS_LOW(self); - mp_soft_qspi_transfer(self, 1 + len, (uint8_t*)&cmd_buf, (uint8_t*)&cmd_buf); + mp_soft_qspi_transfer(self, 1 + len, (uint8_t *)&cmd_buf, (uint8_t *)&cmd_buf); CS_HIGH(self); return cmd_buf >> 8; } STATIC void mp_soft_qspi_read_cmd_qaddr_qdata(void *self_in, uint8_t cmd, uint32_t addr, size_t len, uint8_t *dest) { - mp_soft_qspi_obj_t *self = (mp_soft_qspi_obj_t*)self_in; + mp_soft_qspi_obj_t *self = (mp_soft_qspi_obj_t *)self_in; uint8_t cmd_buf[7] = {cmd, addr >> 16, addr >> 8, addr}; CS_LOW(self); mp_soft_qspi_transfer(self, 1, cmd_buf, NULL); diff --git a/drivers/bus/softspi.c b/drivers/bus/softspi.c index bc12d89d3b..71eb8911cd 100644 --- a/drivers/bus/softspi.c +++ b/drivers/bus/softspi.c @@ -27,7 +27,7 @@ #include "drivers/bus/spi.h" int mp_soft_spi_ioctl(void *self_in, uint32_t cmd) { - mp_soft_spi_obj_t *self = (mp_soft_spi_obj_t*)self_in; + mp_soft_spi_obj_t *self = (mp_soft_spi_obj_t *)self_in; switch (cmd) { case MP_SPI_IOCTL_INIT: @@ -45,7 +45,7 @@ int mp_soft_spi_ioctl(void *self_in, uint32_t cmd) { } void mp_soft_spi_transfer(void *self_in, size_t len, const uint8_t *src, uint8_t *dest) { - mp_soft_spi_obj_t *self = (mp_soft_spi_obj_t*)self_in; + mp_soft_spi_obj_t *self = (mp_soft_spi_obj_t *)self_in; uint32_t delay_half = self->delay_half; // only MSB transfer is implemented diff --git a/extmod/machine_i2c.c b/extmod/machine_i2c.c index c1a93ab041..82e67d0ba0 100644 --- a/extmod/machine_i2c.c +++ b/extmod/machine_i2c.c @@ -183,7 +183,7 @@ STATIC int mp_hal_i2c_read_byte(machine_i2c_obj_t *self, uint8_t *val, int nack) // >=0 - number of acks received // <0 - error, with errno being the negative of the return value int mp_machine_soft_i2c_writeto(mp_obj_base_t *self_in, uint16_t addr, const uint8_t *src, size_t len, bool stop) { - machine_i2c_obj_t *self = (machine_i2c_obj_t*)self_in; + machine_i2c_obj_t *self = (machine_i2c_obj_t *)self_in; // start the I2C transaction int ret = mp_hal_i2c_start(self); @@ -229,7 +229,7 @@ int mp_machine_soft_i2c_writeto(mp_obj_base_t *self_in, uint16_t addr, const uin // 0 - success // <0 - error, with errno being the negative of the return value int mp_machine_soft_i2c_readfrom(mp_obj_base_t *self_in, uint16_t addr, uint8_t *dest, size_t len, bool stop) { - machine_i2c_obj_t *self = (machine_i2c_obj_t*)self_in; + machine_i2c_obj_t *self = (machine_i2c_obj_t *)self_in; // start the I2C transaction int ret = mp_hal_i2c_start(self); @@ -318,7 +318,7 @@ MP_DEFINE_CONST_FUN_OBJ_KW(machine_i2c_init_obj, 1, machine_i2c_obj_init); STATIC mp_obj_t machine_i2c_scan(mp_obj_t self_in) { mp_obj_base_t *self = MP_OBJ_TO_PTR(self_in); - mp_machine_i2c_p_t *i2c_p = (mp_machine_i2c_p_t*)self->type->protocol; + mp_machine_i2c_p_t *i2c_p = (mp_machine_i2c_p_t *)self->type->protocol; mp_obj_t list = mp_obj_new_list(0, NULL); // 7-bit addresses 0b0000xxx and 0b1111xxx are reserved for (int addr = 0x08; addr < 0x78; ++addr) { @@ -332,8 +332,8 @@ STATIC mp_obj_t machine_i2c_scan(mp_obj_t self_in) { MP_DEFINE_CONST_FUN_OBJ_1(machine_i2c_scan_obj, machine_i2c_scan); STATIC mp_obj_t machine_i2c_start(mp_obj_t self_in) { - mp_obj_base_t *self = (mp_obj_base_t*)MP_OBJ_TO_PTR(self_in); - mp_machine_i2c_p_t *i2c_p = (mp_machine_i2c_p_t*)self->type->protocol; + mp_obj_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(self_in); + mp_machine_i2c_p_t *i2c_p = (mp_machine_i2c_p_t *)self->type->protocol; if (i2c_p->start == NULL) { mp_raise_msg(&mp_type_OSError, "I2C operation not supported"); } @@ -346,8 +346,8 @@ STATIC mp_obj_t machine_i2c_start(mp_obj_t self_in) { MP_DEFINE_CONST_FUN_OBJ_1(machine_i2c_start_obj, machine_i2c_start); STATIC mp_obj_t machine_i2c_stop(mp_obj_t self_in) { - mp_obj_base_t *self = (mp_obj_base_t*)MP_OBJ_TO_PTR(self_in); - mp_machine_i2c_p_t *i2c_p = (mp_machine_i2c_p_t*)self->type->protocol; + mp_obj_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(self_in); + mp_machine_i2c_p_t *i2c_p = (mp_machine_i2c_p_t *)self->type->protocol; if (i2c_p->stop == NULL) { mp_raise_msg(&mp_type_OSError, "I2C operation not supported"); } @@ -360,8 +360,8 @@ STATIC mp_obj_t machine_i2c_stop(mp_obj_t self_in) { MP_DEFINE_CONST_FUN_OBJ_1(machine_i2c_stop_obj, machine_i2c_stop); STATIC mp_obj_t machine_i2c_readinto(size_t n_args, const mp_obj_t *args) { - mp_obj_base_t *self = (mp_obj_base_t*)MP_OBJ_TO_PTR(args[0]); - mp_machine_i2c_p_t *i2c_p = (mp_machine_i2c_p_t*)self->type->protocol; + mp_obj_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(args[0]); + mp_machine_i2c_p_t *i2c_p = (mp_machine_i2c_p_t *)self->type->protocol; if (i2c_p->read == NULL) { mp_raise_msg(&mp_type_OSError, "I2C operation not supported"); } @@ -384,8 +384,8 @@ STATIC mp_obj_t machine_i2c_readinto(size_t n_args, const mp_obj_t *args) { MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(machine_i2c_readinto_obj, 2, 3, machine_i2c_readinto); STATIC mp_obj_t machine_i2c_write(mp_obj_t self_in, mp_obj_t buf_in) { - mp_obj_base_t *self = (mp_obj_base_t*)MP_OBJ_TO_PTR(self_in); - mp_machine_i2c_p_t *i2c_p = (mp_machine_i2c_p_t*)self->type->protocol; + mp_obj_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(self_in); + mp_machine_i2c_p_t *i2c_p = (mp_machine_i2c_p_t *)self->type->protocol; if (i2c_p->write == NULL) { mp_raise_msg(&mp_type_OSError, "I2C operation not supported"); } @@ -406,13 +406,13 @@ STATIC mp_obj_t machine_i2c_write(mp_obj_t self_in, mp_obj_t buf_in) { MP_DEFINE_CONST_FUN_OBJ_2(machine_i2c_write_obj, machine_i2c_write); STATIC mp_obj_t machine_i2c_readfrom(size_t n_args, const mp_obj_t *args) { - mp_obj_base_t *self = (mp_obj_base_t*)MP_OBJ_TO_PTR(args[0]); - mp_machine_i2c_p_t *i2c_p = (mp_machine_i2c_p_t*)self->type->protocol; + mp_obj_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(args[0]); + mp_machine_i2c_p_t *i2c_p = (mp_machine_i2c_p_t *)self->type->protocol; mp_int_t addr = mp_obj_get_int(args[1]); vstr_t vstr; vstr_init_len(&vstr, mp_obj_get_int(args[2])); bool stop = (n_args == 3) ? true : mp_obj_is_true(args[3]); - int ret = i2c_p->readfrom(self, addr, (uint8_t*)vstr.buf, vstr.len, stop); + int ret = i2c_p->readfrom(self, addr, (uint8_t *)vstr.buf, vstr.len, stop); if (ret < 0) { mp_raise_OSError(-ret); } @@ -421,8 +421,8 @@ STATIC mp_obj_t machine_i2c_readfrom(size_t n_args, const mp_obj_t *args) { MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(machine_i2c_readfrom_obj, 3, 4, machine_i2c_readfrom); STATIC mp_obj_t machine_i2c_readfrom_into(size_t n_args, const mp_obj_t *args) { - mp_obj_base_t *self = (mp_obj_base_t*)MP_OBJ_TO_PTR(args[0]); - mp_machine_i2c_p_t *i2c_p = (mp_machine_i2c_p_t*)self->type->protocol; + mp_obj_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(args[0]); + mp_machine_i2c_p_t *i2c_p = (mp_machine_i2c_p_t *)self->type->protocol; mp_int_t addr = mp_obj_get_int(args[1]); mp_buffer_info_t bufinfo; mp_get_buffer_raise(args[2], &bufinfo, MP_BUFFER_WRITE); @@ -436,8 +436,8 @@ STATIC mp_obj_t machine_i2c_readfrom_into(size_t n_args, const mp_obj_t *args) { MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(machine_i2c_readfrom_into_obj, 3, 4, machine_i2c_readfrom_into); STATIC mp_obj_t machine_i2c_writeto(size_t n_args, const mp_obj_t *args) { - mp_obj_base_t *self = (mp_obj_base_t*)MP_OBJ_TO_PTR(args[0]); - mp_machine_i2c_p_t *i2c_p = (mp_machine_i2c_p_t*)self->type->protocol; + mp_obj_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(args[0]); + mp_machine_i2c_p_t *i2c_p = (mp_machine_i2c_p_t *)self->type->protocol; mp_int_t addr = mp_obj_get_int(args[1]); mp_buffer_info_t bufinfo; mp_get_buffer_raise(args[2], &bufinfo, MP_BUFFER_READ); @@ -452,8 +452,8 @@ STATIC mp_obj_t machine_i2c_writeto(size_t n_args, const mp_obj_t *args) { STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(machine_i2c_writeto_obj, 3, 4, machine_i2c_writeto); STATIC int read_mem(mp_obj_t self_in, uint16_t addr, uint32_t memaddr, uint8_t addrsize, uint8_t *buf, size_t len) { - mp_obj_base_t *self = (mp_obj_base_t*)MP_OBJ_TO_PTR(self_in); - mp_machine_i2c_p_t *i2c_p = (mp_machine_i2c_p_t*)self->type->protocol; + mp_obj_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(self_in); + mp_machine_i2c_p_t *i2c_p = (mp_machine_i2c_p_t *)self->type->protocol; uint8_t memaddr_buf[4]; size_t memaddr_len = 0; for (int16_t i = addrsize - 8; i >= 0; i -= 8) { @@ -472,8 +472,8 @@ STATIC int read_mem(mp_obj_t self_in, uint16_t addr, uint32_t memaddr, uint8_t a #define BUF_STACK_SIZE (12) STATIC int write_mem(mp_obj_t self_in, uint16_t addr, uint32_t memaddr, uint8_t addrsize, const uint8_t *buf, size_t len) { - mp_obj_base_t *self = (mp_obj_base_t*)MP_OBJ_TO_PTR(self_in); - mp_machine_i2c_p_t *i2c_p = (mp_machine_i2c_p_t*)self->type->protocol; + mp_obj_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(self_in); + mp_machine_i2c_p_t *i2c_p = (mp_machine_i2c_p_t *)self->type->protocol; // need some memory to create the buffer to send; try to use stack if possible uint8_t buf2_stack[MAX_MEMADDR_SIZE + BUF_STACK_SIZE]; @@ -519,7 +519,7 @@ STATIC mp_obj_t machine_i2c_readfrom_mem(size_t n_args, const mp_obj_t *pos_args // do the transfer int ret = read_mem(pos_args[0], args[ARG_addr].u_int, args[ARG_memaddr].u_int, - args[ARG_addrsize].u_int, (uint8_t*)vstr.buf, vstr.len); + args[ARG_addrsize].u_int, (uint8_t *)vstr.buf, vstr.len); if (ret < 0) { mp_raise_OSError(-ret); } @@ -594,7 +594,7 @@ STATIC const mp_rom_map_elem_t machine_i2c_locals_dict_table[] = { MP_DEFINE_CONST_DICT(mp_machine_soft_i2c_locals_dict, machine_i2c_locals_dict_table); int mp_machine_soft_i2c_read(mp_obj_base_t *self_in, uint8_t *dest, size_t len, bool nack) { - machine_i2c_obj_t *self = (machine_i2c_obj_t*)self_in; + machine_i2c_obj_t *self = (machine_i2c_obj_t *)self_in; while (len--) { int ret = mp_hal_i2c_read_byte(self, dest++, nack && (len == 0)); if (ret != 0) { @@ -605,7 +605,7 @@ int mp_machine_soft_i2c_read(mp_obj_base_t *self_in, uint8_t *dest, size_t len, } int mp_machine_soft_i2c_write(mp_obj_base_t *self_in, const uint8_t *src, size_t len) { - machine_i2c_obj_t *self = (machine_i2c_obj_t*)self_in; + machine_i2c_obj_t *self = (machine_i2c_obj_t *)self_in; int num_acks = 0; while (len--) { int ret = mp_hal_i2c_write_byte(self, *src++); @@ -621,8 +621,8 @@ int mp_machine_soft_i2c_write(mp_obj_base_t *self_in, const uint8_t *src, size_t } STATIC const mp_machine_i2c_p_t mp_machine_soft_i2c_p = { - .start = (int(*)(mp_obj_base_t*))mp_hal_i2c_start, - .stop = (int(*)(mp_obj_base_t*))mp_hal_i2c_stop, + .start = (int (*)(mp_obj_base_t *))mp_hal_i2c_start, + .stop = (int (*)(mp_obj_base_t *))mp_hal_i2c_stop, .read = mp_machine_soft_i2c_read, .write = mp_machine_soft_i2c_write, .readfrom = mp_machine_soft_i2c_readfrom, @@ -634,7 +634,7 @@ const mp_obj_type_t machine_i2c_type = { .name = MP_QSTR_I2C, .make_new = machine_i2c_make_new, .protocol = &mp_machine_soft_i2c_p, - .locals_dict = (mp_obj_dict_t*)&mp_machine_soft_i2c_locals_dict, + .locals_dict = (mp_obj_dict_t *)&mp_machine_soft_i2c_locals_dict, }; #endif // MICROPY_PY_MACHINE_I2C diff --git a/extmod/machine_mem.c b/extmod/machine_mem.c index b9f16507c4..76be3afa03 100644 --- a/extmod/machine_mem.c +++ b/extmod/machine_mem.c @@ -71,9 +71,15 @@ STATIC mp_obj_t machine_mem_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t va uintptr_t addr = MICROPY_MACHINE_MEM_GET_READ_ADDR(index, self->elem_size); uint32_t val; switch (self->elem_size) { - case 1: val = (*(uint8_t*)addr); break; - case 2: val = (*(uint16_t*)addr); break; - default: val = (*(uint32_t*)addr); break; + case 1: + val = (*(uint8_t *)addr); + break; + case 2: + val = (*(uint16_t *)addr); + break; + default: + val = (*(uint32_t *)addr); + break; } return mp_obj_new_int(val); } else { @@ -81,9 +87,15 @@ STATIC mp_obj_t machine_mem_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t va uintptr_t addr = MICROPY_MACHINE_MEM_GET_WRITE_ADDR(index, self->elem_size); uint32_t val = mp_obj_get_int_truncated(value); switch (self->elem_size) { - case 1: (*(uint8_t*)addr) = val; break; - case 2: (*(uint16_t*)addr) = val; break; - default: (*(uint32_t*)addr) = val; break; + case 1: + (*(uint8_t *)addr) = val; + break; + case 2: + (*(uint16_t *)addr) = val; + break; + default: + (*(uint32_t *)addr) = val; + break; } return mp_const_none; } diff --git a/extmod/machine_signal.c b/extmod/machine_signal.c index 3f9f5af947..cdb2c01d2c 100644 --- a/extmod/machine_signal.c +++ b/extmod/machine_signal.c @@ -50,8 +50,8 @@ STATIC mp_obj_t signal_make_new(const mp_obj_type_t *type, size_t n_args, size_t mp_pin_p_t *pin_p = NULL; if (MP_OBJ_IS_OBJ(pin)) { - mp_obj_base_t *pin_base = (mp_obj_base_t*)MP_OBJ_TO_PTR(args[0]); - pin_p = (mp_pin_p_t*)pin_base->type->protocol; + mp_obj_base_t *pin_base = (mp_obj_base_t *)MP_OBJ_TO_PTR(args[0]); + pin_p = (mp_pin_p_t *)pin_base->type->protocol; } if (pin_p == NULL) { @@ -90,8 +90,7 @@ STATIC mp_obj_t signal_make_new(const mp_obj_type_t *type, size_t n_args, size_t pin = MICROPY_PY_MACHINE_PIN_MAKE_NEW(NULL, n_args, n_kw, pin_args); mp_local_free(pin_args); - } - else + } else #endif // Otherwise there should be 1 or 2 args { @@ -179,7 +178,7 @@ const mp_obj_type_t machine_signal_type = { .make_new = signal_make_new, .call = signal_call, .protocol = &signal_pin_p, - .locals_dict = (void*)&signal_locals_dict, + .locals_dict = (void *)&signal_locals_dict, }; #endif // MICROPY_PY_MACHINE diff --git a/extmod/machine_spi.c b/extmod/machine_spi.c index f0c4896c2e..f16ec269e3 100644 --- a/extmod/machine_spi.c +++ b/extmod/machine_spi.c @@ -64,16 +64,16 @@ mp_obj_t mp_machine_spi_make_new(const mp_obj_type_t *type, size_t n_args, size_ } STATIC mp_obj_t machine_spi_init(size_t n_args, const mp_obj_t *args, mp_map_t *kw_args) { - mp_obj_base_t *s = (mp_obj_base_t*)MP_OBJ_TO_PTR(args[0]); - mp_machine_spi_p_t *spi_p = (mp_machine_spi_p_t*)s->type->protocol; + mp_obj_base_t *s = (mp_obj_base_t *)MP_OBJ_TO_PTR(args[0]); + mp_machine_spi_p_t *spi_p = (mp_machine_spi_p_t *)s->type->protocol; spi_p->init(s, n_args - 1, args + 1, kw_args); return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_KW(machine_spi_init_obj, 1, machine_spi_init); STATIC mp_obj_t machine_spi_deinit(mp_obj_t self) { - mp_obj_base_t *s = (mp_obj_base_t*)MP_OBJ_TO_PTR(self); - mp_machine_spi_p_t *spi_p = (mp_machine_spi_p_t*)s->type->protocol; + mp_obj_base_t *s = (mp_obj_base_t *)MP_OBJ_TO_PTR(self); + mp_machine_spi_p_t *spi_p = (mp_machine_spi_p_t *)s->type->protocol; if (spi_p->deinit != NULL) { spi_p->deinit(s); } @@ -82,8 +82,8 @@ STATIC mp_obj_t machine_spi_deinit(mp_obj_t self) { STATIC MP_DEFINE_CONST_FUN_OBJ_1(machine_spi_deinit_obj, machine_spi_deinit); STATIC void mp_machine_spi_transfer(mp_obj_t self, size_t len, const void *src, void *dest) { - mp_obj_base_t *s = (mp_obj_base_t*)MP_OBJ_TO_PTR(self); - mp_machine_spi_p_t *spi_p = (mp_machine_spi_p_t*)s->type->protocol; + mp_obj_base_t *s = (mp_obj_base_t *)MP_OBJ_TO_PTR(self); + mp_machine_spi_p_t *spi_p = (mp_machine_spi_p_t *)s->type->protocol; spi_p->transfer(s, len, src, dest); } @@ -108,7 +108,7 @@ MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_machine_spi_readinto_obj, 2, 3, mp_machin STATIC mp_obj_t mp_machine_spi_write(mp_obj_t self, mp_obj_t wr_buf) { mp_buffer_info_t src; mp_get_buffer_raise(wr_buf, &src, MP_BUFFER_READ); - mp_machine_spi_transfer(self, src.len, (const uint8_t*)src.buf, NULL); + mp_machine_spi_transfer(self, src.len, (const uint8_t *)src.buf, NULL); return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_2(mp_machine_spi_write_obj, mp_machine_spi_write); @@ -223,7 +223,7 @@ STATIC mp_obj_t mp_machine_soft_spi_make_new(const mp_obj_type_t *type, size_t n } STATIC void mp_machine_soft_spi_init(mp_obj_base_t *self_in, size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { - mp_machine_soft_spi_obj_t *self = (mp_machine_soft_spi_obj_t*)self_in; + mp_machine_soft_spi_obj_t *self = (mp_machine_soft_spi_obj_t *)self_in; enum { ARG_baudrate, ARG_polarity, ARG_phase, ARG_sck, ARG_mosi, ARG_miso }; static const mp_arg_t allowed_args[] = { @@ -261,7 +261,7 @@ STATIC void mp_machine_soft_spi_init(mp_obj_base_t *self_in, size_t n_args, cons } STATIC void mp_machine_soft_spi_transfer(mp_obj_base_t *self_in, size_t len, const uint8_t *src, uint8_t *dest) { - mp_machine_soft_spi_obj_t *self = (mp_machine_soft_spi_obj_t*)self_in; + mp_machine_soft_spi_obj_t *self = (mp_machine_soft_spi_obj_t *)self_in; mp_soft_spi_transfer(&self->spi, len, src, dest); } @@ -277,7 +277,7 @@ const mp_obj_type_t mp_machine_soft_spi_type = { .print = mp_machine_soft_spi_print, .make_new = mp_machine_spi_make_new, // delegate to master constructor .protocol = &mp_machine_soft_spi_p, - .locals_dict = (mp_obj_dict_t*)&mp_machine_spi_locals_dict, + .locals_dict = (mp_obj_dict_t *)&mp_machine_spi_locals_dict, }; #endif // MICROPY_PY_MACHINE_SPI diff --git a/extmod/modbtree.c b/extmod/modbtree.c index a2bff06d44..7c8d0ab3a7 100644 --- a/extmod/modbtree.c +++ b/extmod/modbtree.c @@ -55,9 +55,9 @@ typedef struct _mp_obj_btree_t { STATIC const mp_obj_type_t btree_type; #define CHECK_ERROR(res) \ - if (res == RET_ERROR) { \ - mp_raise_OSError(errno); \ - } + if (res == RET_ERROR) { \ + mp_raise_OSError(errno); \ + } void __dbpanic(DB *db) { printf("__dbpanic(%p)\n", db); @@ -95,8 +95,8 @@ STATIC mp_obj_t btree_put(size_t n_args, const mp_obj_t *args) { (void)n_args; mp_obj_btree_t *self = MP_OBJ_TO_PTR(args[0]); DBT key, val; - key.data = (void*)mp_obj_str_get_data(args[1], &key.size); - val.data = (void*)mp_obj_str_get_data(args[2], &val.size); + key.data = (void *)mp_obj_str_get_data(args[1], &key.size); + val.data = (void *)mp_obj_str_get_data(args[2], &val.size); return MP_OBJ_NEW_SMALL_INT(__bt_put(self->db, &key, &val, 0)); } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(btree_put_obj, 3, 4, btree_put); @@ -104,7 +104,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(btree_put_obj, 3, 4, btree_put); STATIC mp_obj_t btree_get(size_t n_args, const mp_obj_t *args) { mp_obj_btree_t *self = MP_OBJ_TO_PTR(args[0]); DBT key, val; - key.data = (void*)mp_obj_str_get_data(args[1], &key.size); + key.data = (void *)mp_obj_str_get_data(args[1], &key.size); int res = __bt_get(self->db, &key, &val, 0); if (res == RET_SPECIAL) { if (n_args > 2) { @@ -123,7 +123,7 @@ STATIC mp_obj_t btree_seq(size_t n_args, const mp_obj_t *args) { int flags = MP_OBJ_SMALL_INT_VALUE(args[1]); DBT key, val; if (n_args > 2) { - key.data = (void*)mp_obj_str_get_data(args[2], &key.size); + key.data = (void *)mp_obj_str_get_data(args[2], &key.size); } int res = __bt_seq(self->db, &key, &val, flags); @@ -198,7 +198,7 @@ STATIC mp_obj_t btree_iternext(mp_obj_t self_in) { if (self->start_key != MP_OBJ_NULL) { int flags = R_FIRST; if (self->start_key != mp_const_none) { - key.data = (void*)mp_obj_str_get_data(self->start_key, &key.size); + key.data = (void *)mp_obj_str_get_data(self->start_key, &key.size); flags = R_CURSOR; } else if (desc) { flags = R_LAST; @@ -216,7 +216,7 @@ STATIC mp_obj_t btree_iternext(mp_obj_t self_in) { if (self->end_key != mp_const_none) { DBT end_key; - end_key.data = (void*)mp_obj_str_get_data(self->end_key, &end_key.size); + end_key.data = (void *)mp_obj_str_get_data(self->end_key, &end_key.size); BTREE *t = self->db->internal; int cmp = t->bt_cmp(&key, &end_key); if (desc) { @@ -251,7 +251,7 @@ STATIC mp_obj_t btree_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) { if (value == MP_OBJ_NULL) { // delete DBT key; - key.data = (void*)mp_obj_str_get_data(index, &key.size); + key.data = (void *)mp_obj_str_get_data(index, &key.size); int res = __bt_delete(self->db, &key, 0); if (res == RET_SPECIAL) { nlr_raise(mp_obj_new_exception(&mp_type_KeyError)); @@ -261,7 +261,7 @@ STATIC mp_obj_t btree_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) { } else if (value == MP_OBJ_SENTINEL) { // load DBT key, val; - key.data = (void*)mp_obj_str_get_data(index, &key.size); + key.data = (void *)mp_obj_str_get_data(index, &key.size); int res = __bt_get(self->db, &key, &val, 0); if (res == RET_SPECIAL) { nlr_raise(mp_obj_new_exception(&mp_type_KeyError)); @@ -271,8 +271,8 @@ STATIC mp_obj_t btree_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) { } else { // store DBT key, val; - key.data = (void*)mp_obj_str_get_data(index, &key.size); - val.data = (void*)mp_obj_str_get_data(value, &val.size); + key.data = (void *)mp_obj_str_get_data(index, &key.size); + val.data = (void *)mp_obj_str_get_data(value, &val.size); int res = __bt_put(self->db, &key, &val, 0); CHECK_ERROR(res); return mp_const_none; @@ -284,7 +284,7 @@ STATIC mp_obj_t btree_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs switch (op) { case MP_BINARY_OP_CONTAINS: { DBT key, val; - key.data = (void*)mp_obj_str_get_data(rhs_in, &key.size); + key.data = (void *)mp_obj_str_get_data(rhs_in, &key.size); int res = __bt_get(self->db, &key, &val, 0); CHECK_ERROR(res); return mp_obj_new_bool(res != RET_SPECIAL); @@ -317,7 +317,7 @@ STATIC const mp_obj_type_t btree_type = { .iternext = btree_iternext, .binary_op = btree_binary_op, .subscr = btree_subscr, - .locals_dict = (void*)&btree_locals_dict, + .locals_dict = (void *)&btree_locals_dict, }; STATIC FILEVTABLE btree_stream_fvtable = { @@ -345,14 +345,14 @@ STATIC mp_obj_t mod_btree_open(size_t n_args, const mp_obj_t *pos_args, mp_map_t mp_arg_val_t minkeypage; } 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_ARRAY_SIZE(allowed_args), allowed_args, (mp_arg_val_t *)&args); BTREEINFO openinfo = {0}; openinfo.flags = args.flags.u_int; openinfo.cachesize = args.cachesize.u_int; openinfo.psize = args.pagesize.u_int; openinfo.minkeypage = args.minkeypage.u_int; - DB *db = __bt_open(MP_OBJ_TO_PTR(pos_args[0]), &btree_stream_fvtable, &openinfo, /*dflags*/0); + DB *db = __bt_open(MP_OBJ_TO_PTR(pos_args[0]), &btree_stream_fvtable, &openinfo, /*dflags*/ 0); if (db == NULL) { mp_raise_OSError(errno); } @@ -371,7 +371,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_btree_globals, mp_module_btree_globals_tab const mp_obj_module_t mp_module_btree = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_btree_globals, + .globals = (mp_obj_dict_t *)&mp_module_btree_globals, }; #endif // MICROPY_PY_BTREE diff --git a/extmod/modframebuf.c b/extmod/modframebuf.c index a7f6ba905f..b7c02fdbab 100644 --- a/extmod/modframebuf.c +++ b/extmod/modframebuf.c @@ -41,8 +41,8 @@ typedef struct _mp_obj_framebuf_t { uint8_t format; } mp_obj_framebuf_t; -typedef void (*setpixel_t)(const mp_obj_framebuf_t*, int, int, uint32_t); -typedef uint32_t (*getpixel_t)(const mp_obj_framebuf_t*, int, int); +typedef void (*setpixel_t)(const mp_obj_framebuf_t *, int, int, uint32_t); +typedef uint32_t (*getpixel_t)(const mp_obj_framebuf_t *, int, int); typedef void (*fill_rect_t)(const mp_obj_framebuf_t *, int, int, int, int, uint32_t); typedef struct _mp_framebuf_p_t { @@ -65,20 +65,20 @@ typedef struct _mp_framebuf_p_t { STATIC void mono_horiz_setpixel(const mp_obj_framebuf_t *fb, int x, int y, uint32_t col) { size_t index = (x + y * fb->stride) >> 3; int offset = fb->format == FRAMEBUF_MHMSB ? x & 0x07 : 7 - (x & 0x07); - ((uint8_t*)fb->buf)[index] = (((uint8_t*)fb->buf)[index] & ~(0x01 << offset)) | ((col != 0) << offset); + ((uint8_t *)fb->buf)[index] = (((uint8_t *)fb->buf)[index] & ~(0x01 << offset)) | ((col != 0) << offset); } STATIC uint32_t mono_horiz_getpixel(const mp_obj_framebuf_t *fb, int x, int y) { size_t index = (x + y * fb->stride) >> 3; int offset = fb->format == FRAMEBUF_MHMSB ? x & 0x07 : 7 - (x & 0x07); - return (((uint8_t*)fb->buf)[index] >> (offset)) & 0x01; + return (((uint8_t *)fb->buf)[index] >> (offset)) & 0x01; } STATIC void mono_horiz_fill_rect(const mp_obj_framebuf_t *fb, int x, int y, int w, int h, uint32_t col) { int reverse = fb->format == FRAMEBUF_MHMSB; int advance = fb->stride >> 3; while (w--) { - uint8_t *b = &((uint8_t*)fb->buf)[(x >> 3) + y * advance]; + uint8_t *b = &((uint8_t *)fb->buf)[(x >> 3) + y * advance]; int offset = reverse ? x & 7 : 7 - (x & 7); for (int hh = h; hh; --hh) { *b = (*b & ~(0x01 << offset)) | ((col != 0) << offset); @@ -93,16 +93,16 @@ STATIC void mono_horiz_fill_rect(const mp_obj_framebuf_t *fb, int x, int y, int STATIC void mvlsb_setpixel(const mp_obj_framebuf_t *fb, int x, int y, uint32_t col) { size_t index = (y >> 3) * fb->stride + x; uint8_t offset = y & 0x07; - ((uint8_t*)fb->buf)[index] = (((uint8_t*)fb->buf)[index] & ~(0x01 << offset)) | ((col != 0) << offset); + ((uint8_t *)fb->buf)[index] = (((uint8_t *)fb->buf)[index] & ~(0x01 << offset)) | ((col != 0) << offset); } STATIC uint32_t mvlsb_getpixel(const mp_obj_framebuf_t *fb, int x, int y) { - return (((uint8_t*)fb->buf)[(y >> 3) * fb->stride + x] >> (y & 0x07)) & 0x01; + return (((uint8_t *)fb->buf)[(y >> 3) * fb->stride + x] >> (y & 0x07)) & 0x01; } STATIC void mvlsb_fill_rect(const mp_obj_framebuf_t *fb, int x, int y, int w, int h, uint32_t col) { while (h--) { - uint8_t *b = &((uint8_t*)fb->buf)[(y >> 3) * fb->stride + x]; + uint8_t *b = &((uint8_t *)fb->buf)[(y >> 3) * fb->stride + x]; uint8_t offset = y & 0x07; for (int ww = w; ww; --ww) { *b = (*b & ~(0x01 << offset)) | ((col != 0) << offset); @@ -115,15 +115,15 @@ STATIC void mvlsb_fill_rect(const mp_obj_framebuf_t *fb, int x, int y, int w, in // Functions for RGB565 format STATIC void rgb565_setpixel(const mp_obj_framebuf_t *fb, int x, int y, uint32_t col) { - ((uint16_t*)fb->buf)[x + y * fb->stride] = col; + ((uint16_t *)fb->buf)[x + y * fb->stride] = col; } STATIC uint32_t rgb565_getpixel(const mp_obj_framebuf_t *fb, int x, int y) { - return ((uint16_t*)fb->buf)[x + y * fb->stride]; + return ((uint16_t *)fb->buf)[x + y * fb->stride]; } STATIC void rgb565_fill_rect(const mp_obj_framebuf_t *fb, int x, int y, int w, int h, uint32_t col) { - uint16_t *b = &((uint16_t*)fb->buf)[x + y * fb->stride]; + uint16_t *b = &((uint16_t *)fb->buf)[x + y * fb->stride]; while (h--) { for (int ww = w; ww; --ww) { *b++ = col; @@ -135,7 +135,7 @@ STATIC void rgb565_fill_rect(const mp_obj_framebuf_t *fb, int x, int y, int w, i // Functions for GS2_HMSB format STATIC void gs2_hmsb_setpixel(const mp_obj_framebuf_t *fb, int x, int y, uint32_t col) { - uint8_t *pixel = &((uint8_t*)fb->buf)[(x + y * fb->stride) >> 2]; + uint8_t *pixel = &((uint8_t *)fb->buf)[(x + y * fb->stride) >> 2]; uint8_t shift = (x & 0x3) << 1; uint8_t mask = 0x3 << shift; uint8_t color = (col & 0x3) << shift; @@ -143,14 +143,14 @@ STATIC void gs2_hmsb_setpixel(const mp_obj_framebuf_t *fb, int x, int y, uint32_ } STATIC uint32_t gs2_hmsb_getpixel(const mp_obj_framebuf_t *fb, int x, int y) { - uint8_t pixel = ((uint8_t*)fb->buf)[(x + y * fb->stride) >> 2]; + uint8_t pixel = ((uint8_t *)fb->buf)[(x + y * fb->stride) >> 2]; uint8_t shift = (x & 0x3) << 1; return (pixel >> shift) & 0x3; } STATIC void gs2_hmsb_fill_rect(const mp_obj_framebuf_t *fb, int x, int y, int w, int h, uint32_t col) { - for (int xx=x; xx < x+w; xx++) { - for (int yy=y; yy < y+h; yy++) { + for (int xx = x; xx < x + w; xx++) { + for (int yy = y; yy < y + h; yy++) { gs2_hmsb_setpixel(fb, xx, yy, col); } } @@ -159,7 +159,7 @@ STATIC void gs2_hmsb_fill_rect(const mp_obj_framebuf_t *fb, int x, int y, int w, // Functions for GS4_HMSB format STATIC void gs4_hmsb_setpixel(const mp_obj_framebuf_t *fb, int x, int y, uint32_t col) { - uint8_t *pixel = &((uint8_t*)fb->buf)[(x + y * fb->stride) >> 1]; + uint8_t *pixel = &((uint8_t *)fb->buf)[(x + y * fb->stride) >> 1]; if (x % 2) { *pixel = ((uint8_t)col & 0x0f) | (*pixel & 0xf0); @@ -170,15 +170,15 @@ STATIC void gs4_hmsb_setpixel(const mp_obj_framebuf_t *fb, int x, int y, uint32_ STATIC uint32_t gs4_hmsb_getpixel(const mp_obj_framebuf_t *fb, int x, int y) { if (x % 2) { - return ((uint8_t*)fb->buf)[(x + y * fb->stride) >> 1] & 0x0f; + return ((uint8_t *)fb->buf)[(x + y * fb->stride) >> 1] & 0x0f; } - return ((uint8_t*)fb->buf)[(x + y * fb->stride) >> 1] >> 4; + return ((uint8_t *)fb->buf)[(x + y * fb->stride) >> 1] >> 4; } STATIC void gs4_hmsb_fill_rect(const mp_obj_framebuf_t *fb, int x, int y, int w, int h, uint32_t col) { col &= 0x0f; - uint8_t *pixel_pair = &((uint8_t*)fb->buf)[(x + y * fb->stride) >> 1]; + uint8_t *pixel_pair = &((uint8_t *)fb->buf)[(x + y * fb->stride) >> 1]; uint8_t col_shifted_left = col << 4; uint8_t col_pixel_pair = col_shifted_left | col; int pixel_count_till_next_line = (fb->stride - w) >> 1; @@ -210,16 +210,16 @@ STATIC void gs4_hmsb_fill_rect(const mp_obj_framebuf_t *fb, int x, int y, int w, // Functions for GS8 format STATIC void gs8_setpixel(const mp_obj_framebuf_t *fb, int x, int y, uint32_t col) { - uint8_t *pixel = &((uint8_t*)fb->buf)[(x + y * fb->stride)]; + uint8_t *pixel = &((uint8_t *)fb->buf)[(x + y * fb->stride)]; *pixel = col & 0xff; } STATIC uint32_t gs8_getpixel(const mp_obj_framebuf_t *fb, int x, int y) { - return ((uint8_t*)fb->buf)[(x + y * fb->stride)]; + return ((uint8_t *)fb->buf)[(x + y * fb->stride)]; } STATIC void gs8_fill_rect(const mp_obj_framebuf_t *fb, int x, int y, int w, int h, uint32_t col) { - uint8_t *pixel = &((uint8_t*)fb->buf)[(x + y * fb->stride)]; + uint8_t *pixel = &((uint8_t *)fb->buf)[(x + y * fb->stride)]; while (h--) { memset(pixel, col, w); pixel += fb->stride; @@ -393,9 +393,9 @@ STATIC mp_obj_t framebuf_rect(size_t n_args, const mp_obj_t *args) { mp_int_t col = mp_obj_get_int(args[5]); fill_rect(self, x, y, w, 1, col); - fill_rect(self, x, y + h- 1, w, 1, col); + fill_rect(self, x, y + h - 1, w, 1, col); fill_rect(self, x, y, 1, h, col); - fill_rect(self, x + w- 1, y, 1, h, col); + fill_rect(self, x + w - 1, y, 1, h, col); return mp_const_none; } @@ -432,9 +432,15 @@ STATIC mp_obj_t framebuf_line(size_t n_args, const mp_obj_t *args) { bool steep; if (dy > dx) { mp_int_t temp; - temp = x1; x1 = y1; y1 = temp; - temp = dx; dx = dy; dy = temp; - temp = sx; sx = sy; sy = temp; + temp = x1; + x1 = y1; + y1 = temp; + temp = dx; + dx = dy; + dy = temp; + temp = sx; + sx = sy; + sy = temp; steep = true; } else { steep = false; @@ -482,7 +488,7 @@ STATIC mp_obj_t framebuf_blit(size_t n_args, const mp_obj_t *args) { (y >= self->height) || (-x >= source->width) || (-y >= source->height) - ) { + ) { // Out of bounds, no-op. return mp_const_none; } @@ -556,7 +562,7 @@ STATIC mp_obj_t framebuf_text(size_t n_args, const mp_obj_t *args) { // loop over chars for (; *str; ++str) { // get char and make sure its in range of font - int chr = *(uint8_t*)str; + int chr = *(uint8_t *)str; if (chr < 32 || chr > 127) { chr = 127; } @@ -599,7 +605,7 @@ STATIC const mp_obj_type_t mp_type_framebuf = { .name = MP_QSTR_FrameBuffer, .make_new = framebuf_make_new, .buffer_p = { .get_buffer = framebuf_get_buffer }, - .locals_dict = (mp_obj_dict_t*)&framebuf_locals_dict, + .locals_dict = (mp_obj_dict_t *)&framebuf_locals_dict, }; // this factory function is provided for backwards compatibility with old FrameBuffer1 class @@ -642,7 +648,7 @@ STATIC MP_DEFINE_CONST_DICT(framebuf_module_globals, framebuf_module_globals_tab const mp_obj_module_t mp_module_framebuf = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&framebuf_module_globals, + .globals = (mp_obj_dict_t *)&framebuf_module_globals, }; #endif // MICROPY_PY_FRAMEBUF diff --git a/extmod/modlwip.c b/extmod/modlwip.c index 73f1679552..a13ec3e315 100644 --- a/extmod/modlwip.c +++ b/extmod/modlwip.c @@ -40,7 +40,7 @@ #include "lwip/init.h" #include "lwip/tcp.h" #include "lwip/udp.h" -//#include "lwip/raw.h" +// #include "lwip/raw.h" #include "lwip/dns.h" #include "lwip/igmp.h" #if LWIP_VERSION_MAJOR < 2 @@ -92,7 +92,7 @@ void mod_lwip_register_poll(void (*poll)(void *arg), void *poll_arg); void mod_lwip_deregister_poll(void (*poll)(void *arg), void *poll_arg); STATIC void slip_lwip_poll(void *netif) { - slipif_poll((struct netif*)netif); + slipif_poll((struct netif *)netif); } STATIC const mp_obj_type_t lwip_slip_type; @@ -141,7 +141,7 @@ STATIC mp_obj_t lwip_slip_make_new(mp_obj_t type_in, size_t n_args, size_t n_kw, struct netif *n = &lwip_slip_obj.lwip_netif; if (netif_add(n, &iplocal, IP_ADDR_BROADCAST, &ipremote, NULL, slipif_init, ip_input) == NULL) { - mp_raise_ValueError("out of memory"); + mp_raise_ValueError("out of memory"); } netif_set_up(n); netif_set_default(n); @@ -167,7 +167,7 @@ STATIC const mp_obj_type_t lwip_slip_type = { { &mp_type_type }, .name = MP_QSTR_slip, .make_new = lwip_slip_make_new, - .locals_dict = (mp_obj_dict_t*)&lwip_slip_locals_dict, + .locals_dict = (mp_obj_dict_t *)&lwip_slip_locals_dict, }; #endif // MICROPY_PY_LWIP_SLIP @@ -179,7 +179,7 @@ STATIC const mp_obj_type_t lwip_slip_type = { // lwIP 2 changed LWIP_VERSION and it can no longer be used in macros, // so we define our own equivalent version that can. #define LWIP_VERSION_MACRO (LWIP_VERSION_MAJOR << 24 | LWIP_VERSION_MINOR << 16 \ - | LWIP_VERSION_REVISION << 8 | LWIP_VERSION_RC) + | LWIP_VERSION_REVISION << 8 | LWIP_VERSION_RC) // Extension to lwIP error codes #define _ERR_BADF -16 @@ -301,11 +301,11 @@ typedef struct _lwip_socket_obj_t { } lwip_socket_obj_t; static inline void poll_sockets(void) { -#ifdef MICROPY_EVENT_POLL_HOOK + #ifdef MICROPY_EVENT_POLL_HOOK MICROPY_EVENT_POLL_HOOK; -#else + #else mp_hal_delay_ms(1); -#endif + #endif } /*******************************************************************************/ @@ -325,7 +325,7 @@ STATIC void _lwip_udp_incoming(void *arg, struct udp_pcb *upcb, struct pbuf *p, STATIC void _lwip_udp_incoming(void *arg, struct udp_pcb *upcb, struct pbuf *p, const ip_addr_t *addr, u16_t port) #endif { - lwip_socket_obj_t *socket = (lwip_socket_obj_t*)arg; + lwip_socket_obj_t *socket = (lwip_socket_obj_t *)arg; if (socket->incoming.pbuf != NULL) { // That's why they call it "unreliable". No room in the inn, drop the packet. @@ -339,7 +339,7 @@ STATIC void _lwip_udp_incoming(void *arg, struct udp_pcb *upcb, struct pbuf *p, // Callback for general tcp errors. STATIC void _lwip_tcp_error(void *arg, err_t err) { - lwip_socket_obj_t *socket = (lwip_socket_obj_t*)arg; + lwip_socket_obj_t *socket = (lwip_socket_obj_t *)arg; // Pass the error code back via the connection variable. socket->state = err; @@ -349,7 +349,7 @@ STATIC void _lwip_tcp_error(void *arg, err_t err) { // Callback for tcp connection requests. Error code err is unused. (See tcp.h) STATIC err_t _lwip_tcp_connected(void *arg, struct tcp_pcb *tpcb, err_t err) { - lwip_socket_obj_t *socket = (lwip_socket_obj_t*)arg; + lwip_socket_obj_t *socket = (lwip_socket_obj_t *)arg; socket->state = STATE_CONNECTED; return ERR_OK; @@ -367,9 +367,8 @@ STATIC err_t _lwip_tcp_recv_unaccepted(void *arg, struct tcp_pcb *pcb, struct pb // "Poll" (idle) callback to be called ASAP after accept callback // to execute Python callback function, as it can't be executed // from accept callback itself. -STATIC err_t _lwip_tcp_accept_finished(void *arg, struct tcp_pcb *pcb) -{ - lwip_socket_obj_t *socket = (lwip_socket_obj_t*)arg; +STATIC err_t _lwip_tcp_accept_finished(void *arg, struct tcp_pcb *pcb) { + lwip_socket_obj_t *socket = (lwip_socket_obj_t *)arg; tcp_poll(pcb, NULL, 0); exec_user_callback(socket); return ERR_OK; @@ -377,7 +376,7 @@ STATIC err_t _lwip_tcp_accept_finished(void *arg, struct tcp_pcb *pcb) // Callback for incoming tcp connections. STATIC err_t _lwip_tcp_accept(void *arg, struct tcp_pcb *newpcb, err_t err) { - lwip_socket_obj_t *socket = (lwip_socket_obj_t*)arg; + lwip_socket_obj_t *socket = (lwip_socket_obj_t *)arg; tcp_recv(newpcb, _lwip_tcp_recv_unaccepted); // Search for an empty slot to store the new connection @@ -408,7 +407,7 @@ STATIC err_t _lwip_tcp_accept(void *arg, struct tcp_pcb *newpcb, err_t err) { // Callback for inbound tcp packets. STATIC err_t _lwip_tcp_recv(void *arg, struct tcp_pcb *tcpb, struct pbuf *p, err_t err) { - lwip_socket_obj_t *socket = (lwip_socket_obj_t*)arg; + lwip_socket_obj_t *socket = (lwip_socket_obj_t *)arg; if (p == NULL) { // Other side has closed connection. @@ -482,7 +481,9 @@ STATIC mp_uint_t lwip_udp_receive(lwip_socket_obj_t *socket, byte *buf, mp_uint_ if (socket->timeout != -1) { for (mp_uint_t retries = socket->timeout / 100; retries--;) { mp_hal_delay_ms(100); - if (socket->incoming.pbuf != NULL) break; + if (socket->incoming.pbuf != NULL) { + break; + } } if (socket->incoming.pbuf == NULL) { *_errno = MP_ETIMEDOUT; @@ -506,16 +507,16 @@ STATIC mp_uint_t lwip_udp_receive(lwip_socket_obj_t *socket, byte *buf, mp_uint_ pbuf_free(p); socket->incoming.pbuf = NULL; - return (mp_uint_t) result; + return (mp_uint_t)result; } // For use in stream virtual methods #define STREAM_ERROR_CHECK(socket) \ - if (socket->state < 0) { \ - *_errno = error_lookup_table[-socket->state]; \ - return MP_STREAM_ERROR; \ - } \ - assert(socket->pcb.tcp); + if (socket->state < 0) { \ + *_errno = error_lookup_table[-socket->state]; \ + return MP_STREAM_ERROR; \ + } \ + assert(socket->pcb.tcp); // Helper function for send/sendto to handle TCP packets @@ -614,7 +615,7 @@ STATIC mp_uint_t lwip_tcp_receive(lwip_socket_obj_t *socket, byte *buf, mp_uint_ len = remaining; } - memcpy(buf, (byte*)p->payload + socket->recv_offset, len); + memcpy(buf, (byte *)p->payload + socket->recv_offset, len); remaining -= len; if (remaining == 0) { @@ -670,8 +671,9 @@ STATIC mp_obj_t lwip_socket_make_new(const mp_obj_type_t *type, size_t n_args, s socket->pcb.udp = udp_new(); socket->incoming.pbuf = NULL; break; - //case MOD_NETWORK_SOCK_RAW: socket->pcb.raw = raw_new(); break; - default: mp_raise_OSError(MP_EINVAL); + // case MOD_NETWORK_SOCK_RAW: socket->pcb.raw = raw_new(); break; + default: + mp_raise_OSError(MP_EINVAL); } if (socket->pcb.tcp == NULL) { @@ -681,7 +683,7 @@ STATIC mp_obj_t lwip_socket_make_new(const mp_obj_type_t *type, size_t n_args, s switch (socket->type) { case MOD_NETWORK_SOCK_STREAM: { // Register the socket object as our callback argument. - tcp_arg(socket->pcb.tcp, (void*)socket); + tcp_arg(socket->pcb.tcp, (void *)socket); // Register our error callback. tcp_err(socket->pcb.tcp, _lwip_tcp_error); break; @@ -689,7 +691,7 @@ STATIC mp_obj_t lwip_socket_make_new(const mp_obj_type_t *type, size_t n_args, s case MOD_NETWORK_SOCK_DGRAM: { // Register our receive callback now. Since UDP sockets don't require binding or connection // before use, there's no other good time to do it. - udp_recv(socket->pcb.udp, _lwip_udp_incoming, (void*)socket); + udp_recv(socket->pcb.udp, _lwip_udp_incoming, (void *)socket); break; } } @@ -752,7 +754,7 @@ STATIC mp_obj_t lwip_socket_listen(mp_obj_t self_in, mp_obj_t backlog_in) { socket->incoming.connection.tcp.item = NULL; } else { socket->incoming.connection.alloc = backlog; - socket->incoming.connection.tcp.array = m_new0(struct tcp_pcb*, backlog); + socket->incoming.connection.tcp.array = m_new0(struct tcp_pcb *, backlog); } socket->incoming.connection.iget = 0; socket->incoming.connection.iput = 0; @@ -794,7 +796,9 @@ STATIC mp_obj_t lwip_socket_accept(mp_obj_t self_in) { } else if (socket->timeout != -1) { for (mp_uint_t retries = socket->timeout / 100; retries--;) { mp_hal_delay_ms(100); - if (*incoming_connection != NULL) break; + if (*incoming_connection != NULL) { + break; + } } if (*incoming_connection == NULL) { mp_raise_OSError(MP_ETIMEDOUT); @@ -825,7 +829,7 @@ STATIC mp_obj_t lwip_socket_accept(mp_obj_t self_in) { socket2->state = STATE_CONNECTED; socket2->recv_offset = 0; socket2->callback = MP_OBJ_NULL; - tcp_arg(socket2->pcb.tcp, (void*)socket2); + tcp_arg(socket2->pcb.tcp, (void *)socket2); tcp_err(socket2->pcb.tcp, _lwip_tcp_error); tcp_recv(socket2->pcb.tcp, _lwip_tcp_recv); @@ -881,7 +885,9 @@ STATIC mp_obj_t lwip_socket_connect(mp_obj_t self_in, mp_obj_t addr_in) { if (socket->timeout != -1) { for (mp_uint_t retries = socket->timeout / 100; retries--;) { mp_hal_delay_ms(100); - if (socket->state != STATE_CONNECTING) break; + if (socket->state != STATE_CONNECTING) { + break; + } } if (socket->state == STATE_CONNECTING) { mp_raise_OSError(MP_EINPROGRESS); @@ -892,9 +898,9 @@ STATIC mp_obj_t lwip_socket_connect(mp_obj_t self_in, mp_obj_t addr_in) { } } if (socket->state == STATE_CONNECTED) { - err = ERR_OK; + err = ERR_OK; } else { - err = socket->state; + err = socket->state; } break; } @@ -962,11 +968,11 @@ STATIC mp_obj_t lwip_socket_recv(mp_obj_t self_in, mp_obj_t len_in) { mp_uint_t ret = 0; switch (socket->type) { case MOD_NETWORK_SOCK_STREAM: { - ret = lwip_tcp_receive(socket, (byte*)vstr.buf, len, &_errno); + ret = lwip_tcp_receive(socket, (byte *)vstr.buf, len, &_errno); break; } case MOD_NETWORK_SOCK_DGRAM: { - ret = lwip_udp_receive(socket, (byte*)vstr.buf, len, NULL, NULL, &_errno); + ret = lwip_udp_receive(socket, (byte *)vstr.buf, len, NULL, NULL, &_errno); break; } } @@ -1029,12 +1035,12 @@ STATIC mp_obj_t lwip_socket_recvfrom(mp_obj_t self_in, mp_obj_t len_in) { switch (socket->type) { case MOD_NETWORK_SOCK_STREAM: { memcpy(ip, &socket->peer, sizeof(socket->peer)); - port = (mp_uint_t) socket->peer_port; - ret = lwip_tcp_receive(socket, (byte*)vstr.buf, len, &_errno); + port = (mp_uint_t)socket->peer_port; + ret = lwip_tcp_receive(socket, (byte *)vstr.buf, len, &_errno); break; } case MOD_NETWORK_SOCK_DGRAM: { - ret = lwip_udp_receive(socket, (byte*)vstr.buf, len, ip, &port, &_errno); + ret = lwip_udp_receive(socket, (byte *)vstr.buf, len, ip, &port, &_errno); break; } } @@ -1083,7 +1089,7 @@ STATIC mp_obj_t lwip_socket_sendall(mp_obj_t self_in, mp_obj_t buf_in) { mp_raise_OSError(_errno); } bufinfo.len -= ret; - bufinfo.buf = (char*)bufinfo.buf + ret; + bufinfo.buf = (char *)bufinfo.buf + ret; } break; } @@ -1161,7 +1167,7 @@ STATIC mp_obj_t lwip_socket_setsockopt(size_t n_args, const mp_obj_t *args) { } // POSIX setsockopt has order: group addr, if addr, lwIP has it vice-versa - err_t err = igmp_joingroup((ip_addr_t*)bufinfo.buf + 1, bufinfo.buf); + err_t err = igmp_joingroup((ip_addr_t *)bufinfo.buf + 1, bufinfo.buf); if (err != ERR_OK) { mp_raise_OSError(error_lookup_table[-err]); } @@ -1219,9 +1225,9 @@ STATIC mp_uint_t lwip_socket_ioctl(mp_obj_t self_in, mp_uint_t request, uintptr_ if (socket->state == STATE_LISTENING) { // Listening TCP socket may have one or multiple connections waiting if ((socket->incoming.connection.alloc == 0 - && socket->incoming.connection.tcp.item != NULL) + && socket->incoming.connection.tcp.item != NULL) || socket->incoming.connection.tcp.array[socket->incoming.connection.iget] != NULL) { - ret |= MP_STREAM_POLL_RD; + ret |= MP_STREAM_POLL_RD; } } else { // Otherwise there is just one slot for incoming data @@ -1274,8 +1280,10 @@ STATIC mp_uint_t lwip_socket_ioctl(mp_obj_t self_in, mp_uint_t request, uintptr_ } break; } - case MOD_NETWORK_SOCK_DGRAM: udp_remove(socket->pcb.udp); break; - //case MOD_NETWORK_SOCK_RAW: raw_remove(socket->pcb.raw); break; + case MOD_NETWORK_SOCK_DGRAM: + udp_remove(socket->pcb.udp); + break; + // case MOD_NETWORK_SOCK_RAW: raw_remove(socket->pcb.raw); break; } socket->pcb.tcp = NULL; socket->state = _ERR_BADF; @@ -1347,7 +1355,7 @@ STATIC const mp_obj_type_t lwip_socket_type = { .print = lwip_socket_print, .make_new = lwip_socket_make_new, .protocol = &lwip_socket_stream_p, - .locals_dict = (mp_obj_dict_t*)&lwip_socket_locals_dict, + .locals_dict = (mp_obj_dict_t *)&lwip_socket_locals_dict, }; /******************************************************************************/ @@ -1367,18 +1375,18 @@ void sys_arch_unprotect(sys_prot_t state) { // itself a "list" but isn't; we only support a single interface. typedef struct nic_poll { - void (* poll)(void *arg); + void (*poll)(void *arg); void *poll_arg; } nic_poll_t; STATIC nic_poll_t lwip_poll_list; -void mod_lwip_register_poll(void (* poll)(void *arg), void *poll_arg) { +void mod_lwip_register_poll(void (*poll)(void *arg), void *poll_arg) { lwip_poll_list.poll = poll; lwip_poll_list.poll_arg = poll_arg; } -void mod_lwip_deregister_poll(void (* poll)(void *arg), void *poll_arg) { +void mod_lwip_deregister_poll(void (*poll)(void *arg), void *poll_arg) { lwip_poll_list.poll = NULL; } @@ -1445,9 +1453,9 @@ STATIC mp_obj_t lwip_getaddrinfo(size_t n_args, const mp_obj_t *args) { } } if (!((family == 0 || family == MOD_NETWORK_AF_INET) - && (type == 0 || type == MOD_NETWORK_SOCK_STREAM) - && proto == 0 - && flags == 0)) { + && (type == 0 || type == MOD_NETWORK_SOCK_STREAM) + && proto == 0 + && flags == 0)) { mp_warning("unsupported getaddrinfo constraints"); } } @@ -1455,7 +1463,7 @@ STATIC mp_obj_t lwip_getaddrinfo(size_t n_args, const mp_obj_t *args) { getaddrinfo_state_t state; state.status = 0; - err_t ret = dns_gethostbyname(host, (ip_addr_t*)&state.ipaddr, lwip_getaddrinfo_cb, &state); + err_t ret = dns_gethostbyname(host, (ip_addr_t *)&state.ipaddr, lwip_getaddrinfo_cb, &state); switch (ret) { case ERR_OK: // cached @@ -1481,8 +1489,8 @@ STATIC mp_obj_t lwip_getaddrinfo(size_t n_args, const mp_obj_t *args) { tuple->items[1] = MP_OBJ_NEW_SMALL_INT(MOD_NETWORK_SOCK_STREAM); tuple->items[2] = MP_OBJ_NEW_SMALL_INT(0); tuple->items[3] = MP_OBJ_NEW_QSTR(MP_QSTR_); - tuple->items[4] = netutils_format_inet_addr((uint8_t*)&state.ipaddr, port, NETUTILS_BIG); - return mp_obj_new_list(1, (mp_obj_t*)&tuple); + tuple->items[4] = netutils_format_inet_addr((uint8_t *)&state.ipaddr, port, NETUTILS_BIG); + return mp_obj_new_list(1, (mp_obj_t *)&tuple); } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(lwip_getaddrinfo_obj, 2, 6, lwip_getaddrinfo); @@ -1504,9 +1512,9 @@ STATIC const mp_rom_map_elem_t mp_module_lwip_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_print_pcbs), MP_ROM_PTR(&lwip_print_pcbs_obj) }, // objects { MP_ROM_QSTR(MP_QSTR_socket), MP_ROM_PTR(&lwip_socket_type) }, -#ifdef MICROPY_PY_LWIP_SLIP + #ifdef MICROPY_PY_LWIP_SLIP { MP_ROM_QSTR(MP_QSTR_slip), MP_ROM_PTR(&lwip_slip_type) }, -#endif + #endif // class constants { MP_ROM_QSTR(MP_QSTR_AF_INET), MP_ROM_INT(MOD_NETWORK_AF_INET) }, { MP_ROM_QSTR(MP_QSTR_AF_INET6), MP_ROM_INT(MOD_NETWORK_AF_INET6) }, @@ -1526,7 +1534,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_lwip_globals, mp_module_lwip_globals_table const mp_obj_module_t mp_module_lwip = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_lwip_globals, + .globals = (mp_obj_dict_t *)&mp_module_lwip_globals, }; #endif // MICROPY_PY_LWIP diff --git a/extmod/modonewire.c b/extmod/modonewire.c index 7ef4c3bce8..210bee366e 100644 --- a/extmod/modonewire.c +++ b/extmod/modonewire.c @@ -126,7 +126,7 @@ STATIC mp_obj_t onewire_crc8(mp_obj_t data) { mp_get_buffer_raise(data, &bufinfo, MP_BUFFER_READ); uint8_t crc = 0; for (size_t i = 0; i < bufinfo.len; ++i) { - uint8_t byte = ((uint8_t*)bufinfo.buf)[i]; + uint8_t byte = ((uint8_t *)bufinfo.buf)[i]; for (int b = 0; b < 8; ++b) { uint8_t fb_bit = (crc ^ byte) & 0x01; if (fb_bit == 0x01) { @@ -158,5 +158,5 @@ STATIC MP_DEFINE_CONST_DICT(onewire_module_globals, onewire_module_globals_table const mp_obj_module_t mp_module_onewire = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&onewire_module_globals, + .globals = (mp_obj_dict_t *)&onewire_module_globals, }; diff --git a/extmod/modubinascii.c b/extmod/modubinascii.c index 8256a50cf2..438b5e1100 100644 --- a/extmod/modubinascii.c +++ b/extmod/modubinascii.c @@ -53,7 +53,7 @@ mp_obj_t mod_binascii_hexlify(size_t n_args, const mp_obj_t *args) { sep = mp_obj_str_get_str(args[1]); } vstr_init_len(&vstr, out_len); - byte *in = bufinfo.buf, *out = (byte*)vstr.buf; + byte *in = bufinfo.buf, *out = (byte *)vstr.buf; for (mp_uint_t i = bufinfo.len; i--;) { byte d = (*in >> 4); if (d > 9) { @@ -82,7 +82,7 @@ mp_obj_t mod_binascii_unhexlify(mp_obj_t data) { } vstr_t vstr; vstr_init_len(&vstr, bufinfo.len / 2); - byte *in = bufinfo.buf, *out = (byte*)vstr.buf; + byte *in = bufinfo.buf, *out = (byte *)vstr.buf; byte hex_byte = 0; for (mp_uint_t i = bufinfo.len; i--;) { byte hex_ch = *in++; @@ -172,7 +172,7 @@ mp_obj_t mod_binascii_b2a_base64(mp_obj_t data) { vstr_init_len(&vstr, ((bufinfo.len != 0) ? (((bufinfo.len - 1) / 3) + 1) * 4 : 0) + 1); // First pass, we convert input buffer to numeric base 64 values - byte *in = bufinfo.buf, *out = (byte*)vstr.buf; + byte *in = bufinfo.buf, *out = (byte *)vstr.buf; mp_uint_t i; for (i = bufinfo.len; i >= 3; i -= 3) { *out++ = (in[0] & 0xFC) >> 2; @@ -186,8 +186,7 @@ mp_obj_t mod_binascii_b2a_base64(mp_obj_t data) { if (i == 2) { *out++ = (in[0] & 0x03) << 4 | (in[1] & 0xF0) >> 4; *out++ = (in[1] & 0x0F) << 2; - } - else { + } else { *out++ = (in[0] & 0x03) << 4; *out++ = 64; } @@ -195,7 +194,7 @@ mp_obj_t mod_binascii_b2a_base64(mp_obj_t data) { } // Second pass, we convert number base 64 values to actual base64 ascii encoding - out = (byte*)vstr.buf; + out = (byte *)vstr.buf; for (mp_uint_t j = vstr.len - 1; j--;) { if (*out < 26) { *out += 'A'; @@ -204,7 +203,7 @@ mp_obj_t mod_binascii_b2a_base64(mp_obj_t data) { } else if (*out < 62) { *out += '0' - 52; } else if (*out == 62) { - *out ='+'; + *out = '+'; } else if (*out == 63) { *out = '/'; } else { @@ -247,7 +246,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_binascii_globals, mp_module_binascii_globa const mp_obj_module_t mp_module_ubinascii = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_binascii_globals, + .globals = (mp_obj_dict_t *)&mp_module_binascii_globals, }; -#endif //MICROPY_PY_UBINASCII +#endif // MICROPY_PY_UBINASCII diff --git a/extmod/moducryptolib.c b/extmod/moducryptolib.c index af9eec624e..6352c13330 100644 --- a/extmod/moducryptolib.c +++ b/extmod/moducryptolib.c @@ -75,11 +75,11 @@ struct mbedtls_aes_ctx_with_key { typedef struct _mp_obj_aes_t { mp_obj_base_t base; AES_CTX_IMPL ctx; - uint8_t block_mode: 6; + uint8_t block_mode : 6; #define AES_KEYTYPE_NONE 0 #define AES_KEYTYPE_ENC 1 #define AES_KEYTYPE_DEC 2 - uint8_t key_type: 2; + uint8_t key_type : 2; } mp_obj_aes_t; #if MICROPY_SSL_AXTLS @@ -97,7 +97,7 @@ STATIC void aes_final_set_key_impl(AES_CTX_IMPL *ctx, bool encrypt) { STATIC void aes_process_ecb_impl(AES_CTX_IMPL *ctx, const uint8_t in[16], uint8_t out[16], bool encrypt) { memcpy(out, in, 16); // We assume that out (vstr.buf or given output buffer) is uint32_t aligned - uint32_t *p = (uint32_t*)out; + uint32_t *p = (uint32_t *)out; // axTLS likes it weird and complicated with byteswaps for (int i = 0; i < 4; i++) { p[i] = MP_HTOBE32(p[i]); @@ -220,7 +220,7 @@ STATIC mp_obj_t aes_process(size_t n_args, const mp_obj_t *args, bool encrypt) { out_buf_ptr = out_bufinfo.buf; } else { vstr_init_len(&vstr, in_bufinfo.len); - out_buf_ptr = (uint8_t*)vstr.buf; + out_buf_ptr = (uint8_t *)vstr.buf; } if (AES_KEYTYPE_NONE == self->key_type) { @@ -270,23 +270,23 @@ STATIC const mp_obj_type_t ucryptolib_aes_type = { { &mp_type_type }, .name = MP_QSTR_aes, .make_new = ucryptolib_aes_make_new, - .locals_dict = (void*)&ucryptolib_aes_locals_dict, + .locals_dict = (void *)&ucryptolib_aes_locals_dict, }; STATIC const mp_rom_map_elem_t mp_module_ucryptolib_globals_table[] = { { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_ucryptolib) }, { MP_ROM_QSTR(MP_QSTR_aes), MP_ROM_PTR(&ucryptolib_aes_type) }, -#if MICROPY_PY_UCRYPTOLIB_CONSTS + #if MICROPY_PY_UCRYPTOLIB_CONSTS { MP_ROM_QSTR(MP_QSTR_MODE_ECB), MP_ROM_INT(UCRYPTOLIB_MODE_ECB) }, { MP_ROM_QSTR(MP_QSTR_MODE_CBC), MP_ROM_INT(UCRYPTOLIB_MODE_CBC) }, -#endif + #endif }; STATIC MP_DEFINE_CONST_DICT(mp_module_ucryptolib_globals, mp_module_ucryptolib_globals_table); const mp_obj_module_t mp_module_ucryptolib = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_ucryptolib_globals, + .globals = (mp_obj_dict_t *)&mp_module_ucryptolib_globals, }; -#endif //MICROPY_PY_UCRYPTOLIB +#endif // MICROPY_PY_UCRYPTOLIB diff --git a/extmod/moductypes.c b/extmod/moductypes.c index 68cd5fca9e..9eb492059d 100644 --- a/extmod/moductypes.c +++ b/extmod/moductypes.c @@ -124,7 +124,7 @@ STATIC mp_obj_t uctypes_struct_make_new(const mp_obj_type_t *type, size_t n_args mp_arg_check_num(n_args, n_kw, 2, 3, false); mp_obj_uctypes_struct_t *o = m_new_obj(mp_obj_uctypes_struct_t); o->base.type = type; - o->addr = (void*)(uintptr_t)mp_obj_int_get_truncated(args[0]); + o->addr = (void *)(uintptr_t)mp_obj_int_get_truncated(args[0]); o->desc = args[1]; o->flags = LAYOUT_NATIVE; if (n_args == 3) { @@ -138,18 +138,22 @@ STATIC void uctypes_struct_print(const mp_print_t *print, mp_obj_t self_in, mp_p mp_obj_uctypes_struct_t *self = MP_OBJ_TO_PTR(self_in); const char *typen = "unk"; if (MP_OBJ_IS_TYPE(self->desc, &mp_type_dict) - #if MICROPY_PY_COLLECTIONS_ORDEREDDICT + #if MICROPY_PY_COLLECTIONS_ORDEREDDICT || MP_OBJ_IS_TYPE(self->desc, &mp_type_ordereddict) - #endif - ) { + #endif + ) { typen = "STRUCT"; } else if (MP_OBJ_IS_TYPE(self->desc, &mp_type_tuple)) { mp_obj_tuple_t *t = MP_OBJ_TO_PTR(self->desc); mp_int_t offset = MP_OBJ_SMALL_INT_VALUE(t->items[0]); uint agg_type = GET_TYPE(offset, AGG_TYPE_BITS); switch (agg_type) { - case PTR: typen = "PTR"; break; - case ARRAY: typen = "ARRAY"; break; + case PTR: + typen = "PTR"; + break; + case ARRAY: + typen = "ARRAY"; + break; } } else { typen = "ERROR"; @@ -180,10 +184,10 @@ STATIC mp_uint_t uctypes_struct_agg_size(mp_obj_tuple_t *t, int layout_type, mp_ case STRUCT: return uctypes_struct_size(t->items[1], layout_type, max_field_size); case PTR: - if (sizeof(void*) > *max_field_size) { - *max_field_size = sizeof(void*); + if (sizeof(void *) > *max_field_size) { + *max_field_size = sizeof(void *); } - return sizeof(void*); + return sizeof(void *); case ARRAY: { mp_int_t arr_sz = MP_OBJ_SMALL_INT_VALUE(t->items[1]); uint val_type = GET_TYPE(arr_sz, VAL_TYPE_BITS); @@ -211,12 +215,12 @@ STATIC mp_uint_t uctypes_struct_agg_size(mp_obj_tuple_t *t, int layout_type, mp_ STATIC mp_uint_t uctypes_struct_size(mp_obj_t desc_in, int layout_type, mp_uint_t *max_field_size) { if (!MP_OBJ_IS_TYPE(desc_in, &mp_type_dict) - #if MICROPY_PY_COLLECTIONS_ORDEREDDICT + #if MICROPY_PY_COLLECTIONS_ORDEREDDICT && !MP_OBJ_IS_TYPE(desc_in, &mp_type_ordereddict) - #endif - ) { + #endif + ) { if (MP_OBJ_IS_TYPE(desc_in, &mp_type_tuple)) { - return uctypes_struct_agg_size((mp_obj_tuple_t*)MP_OBJ_TO_PTR(desc_in), layout_type, max_field_size); + return uctypes_struct_agg_size((mp_obj_tuple_t *)MP_OBJ_TO_PTR(desc_in), layout_type, max_field_size); } else if (MP_OBJ_IS_SMALL_INT(desc_in)) { // We allow sizeof on both type definitions and structures/structure fields, // but scalar structure field is lowered into native Python int, so all @@ -311,11 +315,11 @@ static inline void set_unaligned(uint val_type, byte *p, int big_endian, mp_obj_ static inline mp_uint_t get_aligned_basic(uint val_type, void *p) { switch (val_type) { case UINT8: - return *(uint8_t*)p; + return *(uint8_t *)p; case UINT16: - return *(uint16_t*)p; + return *(uint16_t *)p; case UINT32: - return *(uint32_t*)p; + return *(uint32_t *)p; } assert(0); return 0; @@ -324,11 +328,14 @@ static inline mp_uint_t get_aligned_basic(uint val_type, void *p) { static inline void set_aligned_basic(uint val_type, void *p, mp_uint_t v) { switch (val_type) { case UINT8: - *(uint8_t*)p = (uint8_t)v; return; + *(uint8_t *)p = (uint8_t)v; + return; case UINT16: - *(uint16_t*)p = (uint16_t)v; return; + *(uint16_t *)p = (uint16_t)v; + return; case UINT32: - *(uint32_t*)p = (uint32_t)v; return; + *(uint32_t *)p = (uint32_t)v; + return; } assert(0); } @@ -336,26 +343,26 @@ static inline void set_aligned_basic(uint val_type, void *p, mp_uint_t v) { STATIC mp_obj_t get_aligned(uint val_type, void *p, mp_int_t index) { switch (val_type) { case UINT8: - return MP_OBJ_NEW_SMALL_INT(((uint8_t*)p)[index]); + return MP_OBJ_NEW_SMALL_INT(((uint8_t *)p)[index]); case INT8: - return MP_OBJ_NEW_SMALL_INT(((int8_t*)p)[index]); + return MP_OBJ_NEW_SMALL_INT(((int8_t *)p)[index]); case UINT16: - return MP_OBJ_NEW_SMALL_INT(((uint16_t*)p)[index]); + return MP_OBJ_NEW_SMALL_INT(((uint16_t *)p)[index]); case INT16: - return MP_OBJ_NEW_SMALL_INT(((int16_t*)p)[index]); + return MP_OBJ_NEW_SMALL_INT(((int16_t *)p)[index]); case UINT32: - return mp_obj_new_int_from_uint(((uint32_t*)p)[index]); + return mp_obj_new_int_from_uint(((uint32_t *)p)[index]); case INT32: - return mp_obj_new_int(((int32_t*)p)[index]); + return mp_obj_new_int(((int32_t *)p)[index]); case UINT64: - return mp_obj_new_int_from_ull(((uint64_t*)p)[index]); + return mp_obj_new_int_from_ull(((uint64_t *)p)[index]); case INT64: - return mp_obj_new_int_from_ll(((int64_t*)p)[index]); + return mp_obj_new_int_from_ll(((int64_t *)p)[index]); #if MICROPY_PY_BUILTINS_FLOAT case FLOAT32: - return mp_obj_new_float(((float*)p)[index]); + return mp_obj_new_float(((float *)p)[index]); case FLOAT64: - return mp_obj_new_float(((double*)p)[index]); + return mp_obj_new_float(((double *)p)[index]); #endif default: assert(0); @@ -368,9 +375,9 @@ STATIC void set_aligned(uint val_type, void *p, mp_int_t index, mp_obj_t val) { if (val_type == FLOAT32 || val_type == FLOAT64) { mp_float_t v = mp_obj_get_float(val); if (val_type == FLOAT32) { - ((float*)p)[index] = v; + ((float *)p)[index] = v; } else { - ((double*)p)[index] = v; + ((double *)p)[index] = v; } return; } @@ -378,21 +385,27 @@ STATIC void set_aligned(uint val_type, void *p, mp_int_t index, mp_obj_t val) { mp_int_t v = mp_obj_get_int_truncated(val); switch (val_type) { case UINT8: - ((uint8_t*)p)[index] = (uint8_t)v; return; + ((uint8_t *)p)[index] = (uint8_t)v; + return; case INT8: - ((int8_t*)p)[index] = (int8_t)v; return; + ((int8_t *)p)[index] = (int8_t)v; + return; case UINT16: - ((uint16_t*)p)[index] = (uint16_t)v; return; + ((uint16_t *)p)[index] = (uint16_t)v; + return; case INT16: - ((int16_t*)p)[index] = (int16_t)v; return; + ((int16_t *)p)[index] = (int16_t)v; + return; case UINT32: - ((uint32_t*)p)[index] = (uint32_t)v; return; + ((uint32_t *)p)[index] = (uint32_t)v; + return; case INT32: - ((int32_t*)p)[index] = (int32_t)v; return; + ((int32_t *)p)[index] = (int32_t)v; + return; case INT64: case UINT64: if (sizeof(mp_int_t) == 8) { - ((uint64_t*)p)[index] = (uint64_t)v; + ((uint64_t *)p)[index] = (uint64_t)v; } else { // TODO: Doesn't offer atomic store semantics, but should at least try set_unaligned(val_type, p, MP_ENDIANNESS_BIG, val); @@ -407,11 +420,11 @@ STATIC mp_obj_t uctypes_struct_attr_op(mp_obj_t self_in, qstr attr, mp_obj_t set mp_obj_uctypes_struct_t *self = MP_OBJ_TO_PTR(self_in); if (!MP_OBJ_IS_TYPE(self->desc, &mp_type_dict) - #if MICROPY_PY_COLLECTIONS_ORDEREDDICT + #if MICROPY_PY_COLLECTIONS_ORDEREDDICT && !MP_OBJ_IS_TYPE(self->desc, &mp_type_ordereddict) - #endif - ) { - mp_raise_TypeError("struct: no fields"); + #endif + ) { + mp_raise_TypeError("struct: no fields"); } mp_obj_t deref = mp_obj_dict_get(self->desc, MP_OBJ_NEW_QSTR(attr)); @@ -419,7 +432,7 @@ STATIC mp_obj_t uctypes_struct_attr_op(mp_obj_t self_in, qstr attr, mp_obj_t set mp_int_t offset = MP_OBJ_SMALL_INT_VALUE(deref); mp_uint_t val_type = GET_TYPE(offset, VAL_TYPE_BITS); offset &= VALUE_MASK(VAL_TYPE_BITS); -//printf("scalar type=%d offset=%x\n", val_type, offset); +// printf("scalar type=%d offset=%x\n", val_type, offset); if (val_type <= INT64 || val_type == FLOAT32 || val_type == FLOAT64) { // printf("size=%d\n", GET_SCALAR_SIZE(val_type)); @@ -489,7 +502,7 @@ STATIC mp_obj_t uctypes_struct_attr_op(mp_obj_t self_in, qstr attr, mp_obj_t set mp_int_t offset = MP_OBJ_SMALL_INT_VALUE(sub->items[0]); mp_uint_t agg_type = GET_TYPE(offset, AGG_TYPE_BITS); offset &= VALUE_MASK(AGG_TYPE_BITS); -//printf("agg type=%d offset=%x\n", agg_type, offset); +// printf("agg type=%d offset=%x\n", agg_type, offset); switch (agg_type) { case STRUCT: { @@ -513,7 +526,7 @@ STATIC mp_obj_t uctypes_struct_attr_op(mp_obj_t self_in, qstr attr, mp_obj_t set o->desc = MP_OBJ_FROM_PTR(sub); o->addr = self->addr + offset; o->flags = self->flags; -//printf("PTR/ARR base addr=%p\n", o->addr); +// printf("PTR/ARR base addr=%p\n", o->addr); return MP_OBJ_FROM_PTR(o); } } @@ -593,7 +606,7 @@ STATIC mp_obj_t uctypes_struct_subscr(mp_obj_t self_in, mp_obj_t index_in, mp_ob } } else if (agg_type == PTR) { - byte *p = *(void**)self->addr; + byte *p = *(void **)self->addr; if (MP_OBJ_IS_SMALL_INT(t->items[1])) { uint val_type = GET_TYPE(MP_OBJ_SMALL_INT_VALUE(t->items[1]), VAL_TYPE_BITS); return get_aligned(val_type, p, index); @@ -623,13 +636,14 @@ STATIC mp_obj_t uctypes_struct_unary_op(mp_unary_op_t op, mp_obj_t self_in) { mp_int_t offset = MP_OBJ_SMALL_INT_VALUE(t->items[0]); uint agg_type = GET_TYPE(offset, AGG_TYPE_BITS); if (agg_type == PTR) { - byte *p = *(void**)self->addr; + byte *p = *(void **)self->addr; return mp_obj_new_int((mp_int_t)(uintptr_t)p); } } - /* fallthru */ + /* fallthru */ - default: return MP_OBJ_NULL; // op not supported + default: + return MP_OBJ_NULL; // op not supported } } @@ -660,7 +674,7 @@ MP_DEFINE_CONST_FUN_OBJ_1(uctypes_struct_addressof_obj, uctypes_struct_addressof /// captured by reference (and thus memory pointed by bytearray may change /// or become invalid at later time). Use bytes_at() to capture by value. STATIC mp_obj_t uctypes_struct_bytearray_at(mp_obj_t ptr, mp_obj_t size) { - return mp_obj_new_bytearray_by_ref(mp_obj_int_get_truncated(size), (void*)(uintptr_t)mp_obj_int_get_truncated(ptr)); + return mp_obj_new_bytearray_by_ref(mp_obj_int_get_truncated(size), (void *)(uintptr_t)mp_obj_int_get_truncated(ptr)); } MP_DEFINE_CONST_FUN_OBJ_2(uctypes_struct_bytearray_at_obj, uctypes_struct_bytearray_at); @@ -669,7 +683,7 @@ MP_DEFINE_CONST_FUN_OBJ_2(uctypes_struct_bytearray_at_obj, uctypes_struct_bytear /// captured by value, i.e. copied. Use bytearray_at() to capture by reference /// ("zero copy"). STATIC mp_obj_t uctypes_struct_bytes_at(mp_obj_t ptr, mp_obj_t size) { - return mp_obj_new_bytes((void*)(uintptr_t)mp_obj_int_get_truncated(ptr), mp_obj_int_get_truncated(size)); + return mp_obj_new_bytes((void *)(uintptr_t)mp_obj_int_get_truncated(ptr), mp_obj_int_get_truncated(size)); } MP_DEFINE_CONST_FUN_OBJ_2(uctypes_struct_bytes_at_obj, uctypes_struct_bytes_at); @@ -772,7 +786,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_uctypes_globals, mp_module_uctypes_globals const mp_obj_module_t mp_module_uctypes = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_uctypes_globals, + .globals = (mp_obj_dict_t *)&mp_module_uctypes_globals, }; #endif diff --git a/extmod/moduhashlib.c b/extmod/moduhashlib.c index 50df7ca889..d675d65305 100644 --- a/extmod/moduhashlib.c +++ b/extmod/moduhashlib.c @@ -78,8 +78,8 @@ STATIC mp_obj_t uhashlib_sha256_make_new(const mp_obj_type_t *type, size_t n_arg mp_arg_check_num(n_args, n_kw, 0, 1, false); mp_obj_hash_t *o = m_new_obj_var(mp_obj_hash_t, char, sizeof(mbedtls_sha256_context)); o->base.type = type; - mbedtls_sha256_init((mbedtls_sha256_context*)&o->state); - mbedtls_sha256_starts_ret((mbedtls_sha256_context*)&o->state, 0); + mbedtls_sha256_init((mbedtls_sha256_context *)&o->state); + mbedtls_sha256_starts_ret((mbedtls_sha256_context *)&o->state, 0); if (n_args == 1) { uhashlib_sha256_update(MP_OBJ_FROM_PTR(o), args[0]); } @@ -90,7 +90,7 @@ STATIC mp_obj_t uhashlib_sha256_update(mp_obj_t self_in, mp_obj_t arg) { mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in); mp_buffer_info_t bufinfo; mp_get_buffer_raise(arg, &bufinfo, MP_BUFFER_READ); - mbedtls_sha256_update_ret((mbedtls_sha256_context*)&self->state, bufinfo.buf, bufinfo.len); + mbedtls_sha256_update_ret((mbedtls_sha256_context *)&self->state, bufinfo.buf, bufinfo.len); return mp_const_none; } @@ -98,7 +98,7 @@ STATIC mp_obj_t uhashlib_sha256_digest(mp_obj_t self_in) { mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in); vstr_t vstr; vstr_init_len(&vstr, 32); - mbedtls_sha256_finish_ret((mbedtls_sha256_context*)&self->state, (unsigned char *)vstr.buf); + mbedtls_sha256_finish_ret((mbedtls_sha256_context *)&self->state, (unsigned char *)vstr.buf); return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr); } @@ -108,7 +108,7 @@ STATIC mp_obj_t uhashlib_sha256_make_new(const mp_obj_type_t *type, size_t n_arg mp_arg_check_num(n_args, n_kw, 0, 1, false); mp_obj_hash_t *o = m_new_obj_var(mp_obj_hash_t, char, sizeof(CRYAL_SHA256_CTX)); o->base.type = type; - sha256_init((CRYAL_SHA256_CTX*)o->state); + sha256_init((CRYAL_SHA256_CTX *)o->state); if (n_args == 1) { uhashlib_sha256_update(MP_OBJ_FROM_PTR(o), args[0]); } @@ -119,7 +119,7 @@ STATIC mp_obj_t uhashlib_sha256_update(mp_obj_t self_in, mp_obj_t arg) { mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in); mp_buffer_info_t bufinfo; mp_get_buffer_raise(arg, &bufinfo, MP_BUFFER_READ); - sha256_update((CRYAL_SHA256_CTX*)self->state, bufinfo.buf, bufinfo.len); + sha256_update((CRYAL_SHA256_CTX *)self->state, bufinfo.buf, bufinfo.len); return mp_const_none; } @@ -127,7 +127,7 @@ STATIC mp_obj_t uhashlib_sha256_digest(mp_obj_t self_in) { mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in); vstr_t vstr; vstr_init_len(&vstr, SHA256_BLOCK_SIZE); - sha256_final((CRYAL_SHA256_CTX*)self->state, (byte*)vstr.buf); + sha256_final((CRYAL_SHA256_CTX *)self->state, (byte *)vstr.buf); return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr); } #endif @@ -146,7 +146,7 @@ STATIC const mp_obj_type_t uhashlib_sha256_type = { { &mp_type_type }, .name = MP_QSTR_sha256, .make_new = uhashlib_sha256_make_new, - .locals_dict = (void*)&uhashlib_sha256_locals_dict, + .locals_dict = (void *)&uhashlib_sha256_locals_dict, }; #endif @@ -158,7 +158,7 @@ STATIC mp_obj_t uhashlib_sha1_make_new(const mp_obj_type_t *type, size_t n_args, mp_arg_check_num(n_args, n_kw, 0, 1, false); mp_obj_hash_t *o = m_new_obj_var(mp_obj_hash_t, char, sizeof(SHA1_CTX)); o->base.type = type; - SHA1_Init((SHA1_CTX*)o->state); + SHA1_Init((SHA1_CTX *)o->state); if (n_args == 1) { uhashlib_sha1_update(MP_OBJ_FROM_PTR(o), args[0]); } @@ -169,7 +169,7 @@ STATIC mp_obj_t uhashlib_sha1_update(mp_obj_t self_in, mp_obj_t arg) { mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in); mp_buffer_info_t bufinfo; mp_get_buffer_raise(arg, &bufinfo, MP_BUFFER_READ); - SHA1_Update((SHA1_CTX*)self->state, bufinfo.buf, bufinfo.len); + SHA1_Update((SHA1_CTX *)self->state, bufinfo.buf, bufinfo.len); return mp_const_none; } @@ -177,7 +177,7 @@ STATIC mp_obj_t uhashlib_sha1_digest(mp_obj_t self_in) { mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in); vstr_t vstr; vstr_init_len(&vstr, SHA1_SIZE); - SHA1_Final((byte*)vstr.buf, (SHA1_CTX*)self->state); + SHA1_Final((byte *)vstr.buf, (SHA1_CTX *)self->state); return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr); } #endif @@ -194,8 +194,8 @@ STATIC mp_obj_t uhashlib_sha1_make_new(const mp_obj_type_t *type, size_t n_args, mp_arg_check_num(n_args, n_kw, 0, 1, false); mp_obj_hash_t *o = m_new_obj_var(mp_obj_hash_t, char, sizeof(mbedtls_sha1_context)); o->base.type = type; - mbedtls_sha1_init((mbedtls_sha1_context*)o->state); - mbedtls_sha1_starts_ret((mbedtls_sha1_context*)o->state); + mbedtls_sha1_init((mbedtls_sha1_context *)o->state); + mbedtls_sha1_starts_ret((mbedtls_sha1_context *)o->state); if (n_args == 1) { uhashlib_sha1_update(MP_OBJ_FROM_PTR(o), args[0]); } @@ -206,7 +206,7 @@ STATIC mp_obj_t uhashlib_sha1_update(mp_obj_t self_in, mp_obj_t arg) { mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in); mp_buffer_info_t bufinfo; mp_get_buffer_raise(arg, &bufinfo, MP_BUFFER_READ); - mbedtls_sha1_update_ret((mbedtls_sha1_context*)self->state, bufinfo.buf, bufinfo.len); + mbedtls_sha1_update_ret((mbedtls_sha1_context *)self->state, bufinfo.buf, bufinfo.len); return mp_const_none; } @@ -214,8 +214,8 @@ STATIC mp_obj_t uhashlib_sha1_digest(mp_obj_t self_in) { mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in); vstr_t vstr; vstr_init_len(&vstr, 20); - mbedtls_sha1_finish_ret((mbedtls_sha1_context*)self->state, (byte*)vstr.buf); - mbedtls_sha1_free((mbedtls_sha1_context*)self->state); + mbedtls_sha1_finish_ret((mbedtls_sha1_context *)self->state, (byte *)vstr.buf); + mbedtls_sha1_free((mbedtls_sha1_context *)self->state); return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr); } #endif @@ -233,7 +233,7 @@ STATIC const mp_obj_type_t uhashlib_sha1_type = { { &mp_type_type }, .name = MP_QSTR_sha1, .make_new = uhashlib_sha1_make_new, - .locals_dict = (void*)&uhashlib_sha1_locals_dict, + .locals_dict = (void *)&uhashlib_sha1_locals_dict, }; #endif @@ -245,7 +245,7 @@ STATIC mp_obj_t uhashlib_md5_make_new(const mp_obj_type_t *type, size_t n_args, mp_arg_check_num(n_args, n_kw, 0, 1, false); mp_obj_hash_t *o = m_new_obj_var(mp_obj_hash_t, char, sizeof(MD5_CTX)); o->base.type = type; - MD5_Init((MD5_CTX*)o->state); + MD5_Init((MD5_CTX *)o->state); if (n_args == 1) { uhashlib_md5_update(MP_OBJ_FROM_PTR(o), args[0]); } @@ -256,7 +256,7 @@ STATIC mp_obj_t uhashlib_md5_update(mp_obj_t self_in, mp_obj_t arg) { mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in); mp_buffer_info_t bufinfo; mp_get_buffer_raise(arg, &bufinfo, MP_BUFFER_READ); - MD5_Update((MD5_CTX*)self->state, bufinfo.buf, bufinfo.len); + MD5_Update((MD5_CTX *)self->state, bufinfo.buf, bufinfo.len); return mp_const_none; } @@ -264,7 +264,7 @@ STATIC mp_obj_t uhashlib_md5_digest(mp_obj_t self_in) { mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in); vstr_t vstr; vstr_init_len(&vstr, MD5_SIZE); - MD5_Final((byte*)vstr.buf, (MD5_CTX*)self->state); + MD5_Final((byte *)vstr.buf, (MD5_CTX *)self->state); return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr); } #endif // MICROPY_SSL_AXTLS @@ -281,8 +281,8 @@ STATIC mp_obj_t uhashlib_md5_make_new(const mp_obj_type_t *type, size_t n_args, mp_arg_check_num(n_args, n_kw, 0, 1, false); mp_obj_hash_t *o = m_new_obj_var(mp_obj_hash_t, char, sizeof(mbedtls_md5_context)); o->base.type = type; - mbedtls_md5_init((mbedtls_md5_context*)o->state); - mbedtls_md5_starts_ret((mbedtls_md5_context*)o->state); + mbedtls_md5_init((mbedtls_md5_context *)o->state); + mbedtls_md5_starts_ret((mbedtls_md5_context *)o->state); if (n_args == 1) { uhashlib_md5_update(MP_OBJ_FROM_PTR(o), args[0]); } @@ -293,7 +293,7 @@ STATIC mp_obj_t uhashlib_md5_update(mp_obj_t self_in, mp_obj_t arg) { mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in); mp_buffer_info_t bufinfo; mp_get_buffer_raise(arg, &bufinfo, MP_BUFFER_READ); - mbedtls_md5_update_ret((mbedtls_md5_context*)self->state, bufinfo.buf, bufinfo.len); + mbedtls_md5_update_ret((mbedtls_md5_context *)self->state, bufinfo.buf, bufinfo.len); return mp_const_none; } @@ -301,8 +301,8 @@ STATIC mp_obj_t uhashlib_md5_digest(mp_obj_t self_in) { mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in); vstr_t vstr; vstr_init_len(&vstr, 16); - mbedtls_md5_finish_ret((mbedtls_md5_context*)self->state, (byte*)vstr.buf); - mbedtls_md5_free((mbedtls_md5_context*)self->state); + mbedtls_md5_finish_ret((mbedtls_md5_context *)self->state, (byte *)vstr.buf); + mbedtls_md5_free((mbedtls_md5_context *)self->state); return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr); } #endif // MICROPY_SSL_MBEDTLS @@ -320,7 +320,7 @@ STATIC const mp_obj_type_t uhashlib_md5_type = { { &mp_type_type }, .name = MP_QSTR_md5, .make_new = uhashlib_md5_make_new, - .locals_dict = (void*)&uhashlib_md5_locals_dict, + .locals_dict = (void *)&uhashlib_md5_locals_dict, }; #endif // MICROPY_PY_UHASHLIB_MD5 @@ -341,11 +341,11 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_uhashlib_globals, mp_module_uhashlib_globa const mp_obj_module_t mp_module_uhashlib = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_uhashlib_globals, + .globals = (mp_obj_dict_t *)&mp_module_uhashlib_globals, }; #if MICROPY_PY_UHASHLIB_SHA256 #include "crypto-algorithms/sha256.c" #endif -#endif //MICROPY_PY_UHASHLIB +#endif // MICROPY_PY_UHASHLIB diff --git a/extmod/moduheapq.c b/extmod/moduheapq.c index 71c15368bf..6b41e85adb 100644 --- a/extmod/moduheapq.c +++ b/extmod/moduheapq.c @@ -114,7 +114,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_uheapq_globals, mp_module_uheapq_globals_t const mp_obj_module_t mp_module_uheapq = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_uheapq_globals, + .globals = (mp_obj_dict_t *)&mp_module_uheapq_globals, }; -#endif //MICROPY_PY_UHEAPQ +#endif // MICROPY_PY_UHEAPQ diff --git a/extmod/modujson.c b/extmod/modujson.c index 830b588fdc..35e763cdbe 100644 --- a/extmod/modujson.c +++ b/extmod/modujson.c @@ -100,7 +100,7 @@ STATIC mp_obj_t mod_ujson_load(mp_obj_t stream_obj) { mp_obj_t stack_key = MP_OBJ_NULL; S_NEXT(s); for (;;) { - cont: + cont: if (S_END(s)) { break; } @@ -147,11 +147,21 @@ STATIC mp_obj_t mod_ujson_load(mp_obj_t stream_obj) { if (c == '\\') { c = S_NEXT(s); switch (c) { - case 'b': c = 0x08; break; - case 'f': c = 0x0c; break; - case 'n': c = 0x0a; break; - case 'r': c = 0x0d; break; - case 't': c = 0x09; break; + case 'b': + c = 0x08; + break; + case 'f': + c = 0x0c; + break; + case 'n': + c = 0x0a; + break; + case 'r': + c = 0x0d; + break; + case 't': + c = 0x09; + break; case 'u': { mp_uint_t num = 0; for (int i = 0; i < 4; i++) { @@ -177,7 +187,16 @@ STATIC mp_obj_t mod_ujson_load(mp_obj_t stream_obj) { next = mp_obj_new_str(vstr.buf, vstr.len); break; case '-': - case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': { bool flt = false; vstr_reset(&vstr); for (;;) { @@ -259,7 +278,7 @@ STATIC mp_obj_t mod_ujson_load(mp_obj_t stream_obj) { } } } - success: +success: // eat trailing whitespace while (unichar_isspace(S_CUR(s))) { S_NEXT(s); @@ -275,7 +294,7 @@ STATIC mp_obj_t mod_ujson_load(mp_obj_t stream_obj) { vstr_clear(&vstr); return stack_top; - fail: +fail: mp_raise_ValueError("syntax error in JSON"); } STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_ujson_load_obj, mod_ujson_load); @@ -283,7 +302,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_ujson_load_obj, mod_ujson_load); STATIC mp_obj_t mod_ujson_loads(mp_obj_t obj) { size_t len; const char *buf = mp_obj_str_get_data(obj, &len); - vstr_t vstr = {len, len, (char*)buf, true}; + vstr_t vstr = {len, len, (char *)buf, true}; mp_obj_stringio_t sio = {{&mp_type_stringio}, &vstr, 0, MP_OBJ_NULL}; return mod_ujson_load(MP_OBJ_FROM_PTR(&sio)); } @@ -301,7 +320,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_ujson_globals, mp_module_ujson_globals_tab const mp_obj_module_t mp_module_ujson = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_ujson_globals, + .globals = (mp_obj_dict_t *)&mp_module_ujson_globals, }; -#endif //MICROPY_PY_UJSON +#endif // MICROPY_PY_UJSON diff --git a/extmod/modurandom.c b/extmod/modurandom.c index 1512a3fd4a..fca9daa9d3 100644 --- a/extmod/modurandom.c +++ b/extmod/modurandom.c @@ -39,15 +39,14 @@ STATIC uint32_t yasmarang_pad = 0xeda4baba, yasmarang_n = 69, yasmarang_d = 233; STATIC uint8_t yasmarang_dat = 0; -STATIC uint32_t yasmarang(void) -{ - yasmarang_pad += yasmarang_dat + yasmarang_d * yasmarang_n; - yasmarang_pad = (yasmarang_pad<<3) + (yasmarang_pad>>29); - yasmarang_n = yasmarang_pad | 2; - yasmarang_d ^= (yasmarang_pad<<31) + (yasmarang_pad>>1); - yasmarang_dat ^= (char) yasmarang_pad ^ (yasmarang_d>>8) ^ 1; +STATIC uint32_t yasmarang(void) { + yasmarang_pad += yasmarang_dat + yasmarang_d * yasmarang_n; + yasmarang_pad = (yasmarang_pad << 3) + (yasmarang_pad >> 29); + yasmarang_n = yasmarang_pad | 2; + yasmarang_d ^= (yasmarang_pad << 31) + (yasmarang_pad >> 1); + yasmarang_dat ^= (char)yasmarang_pad ^ (yasmarang_d >> 8) ^ 1; - return (yasmarang_pad^(yasmarang_d<<5)^(yasmarang_pad>>18)^(yasmarang_dat<<1)); + return yasmarang_pad ^ (yasmarang_d << 5) ^ (yasmarang_pad >> 18) ^ (yasmarang_dat << 1); } /* yasmarang */ // End of Yasmarang @@ -169,9 +168,11 @@ STATIC mp_float_t yasmarang_float(void) { union { mp_float_t f; #if MP_ENDIANNESS_LITTLE - struct { mp_float_int_t frc:MP_FLOAT_FRAC_BITS, exp:MP_FLOAT_EXP_BITS, sgn:1; } p; + struct { mp_float_int_t frc : MP_FLOAT_FRAC_BITS, exp : MP_FLOAT_EXP_BITS, sgn : 1; + } p; #else - struct { mp_float_int_t sgn:1, exp:MP_FLOAT_EXP_BITS, frc:MP_FLOAT_FRAC_BITS; } p; + struct { mp_float_int_t sgn : 1, exp : MP_FLOAT_EXP_BITS, frc : MP_FLOAT_FRAC_BITS; + } p; #endif } u; u.p.sgn = 0; @@ -219,7 +220,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_urandom_globals, mp_module_urandom_globals const mp_obj_module_t mp_module_urandom = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_urandom_globals, + .globals = (mp_obj_dict_t *)&mp_module_urandom_globals, }; -#endif //MICROPY_PY_URANDOM +#endif // MICROPY_PY_URANDOM diff --git a/extmod/modure.c b/extmod/modure.c index 0d5330cb54..c004dd81b7 100644 --- a/extmod/modure.c +++ b/extmod/modure.c @@ -73,7 +73,7 @@ STATIC mp_obj_t match_group(mp_obj_t self_in, mp_obj_t no_in) { return mp_const_none; } return mp_obj_new_str_of_type(mp_obj_get_type(self->str), - (const byte*)start, self->caps[no * 2 + 1] - start); + (const byte *)start, self->caps[no * 2 + 1] - start); } MP_DEFINE_CONST_FUN_OBJ_2(match_group_obj, match_group); @@ -162,7 +162,7 @@ STATIC const mp_obj_type_t match_type = { { &mp_type_type }, .name = MP_QSTR_match, .print = match_print, - .locals_dict = (void*)&match_locals_dict, + .locals_dict = (void *)&match_locals_dict, }; STATIC void re_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { @@ -179,12 +179,12 @@ STATIC mp_obj_t ure_exec(bool is_anchored, uint n_args, const mp_obj_t *args) { subj.begin = mp_obj_str_get_data(args[1], &len); subj.end = subj.begin + len; int caps_num = (self->re.sub + 1) * 2; - mp_obj_match_t *match = m_new_obj_var(mp_obj_match_t, char*, caps_num); + mp_obj_match_t *match = m_new_obj_var(mp_obj_match_t, char *, caps_num); // cast is a workaround for a bug in msvc: it treats const char** as a const pointer instead of a pointer to pointer to const char - memset((char*)match->caps, 0, caps_num * sizeof(char*)); + memset((char *)match->caps, 0, caps_num * sizeof(char *)); int res = re1_5_recursiveloopprog(&self->re, &subj, match->caps, caps_num, is_anchored); if (res == 0) { - m_del_var(mp_obj_match_t, char*, caps_num, match); + m_del_var(mp_obj_match_t, char *, caps_num, match); return mp_const_none; } @@ -219,10 +219,10 @@ STATIC mp_obj_t re_split(size_t n_args, const mp_obj_t *args) { } mp_obj_t retval = mp_obj_new_list(0, NULL); - const char **caps = mp_local_alloc(caps_num * sizeof(char*)); + const char **caps = mp_local_alloc(caps_num * sizeof(char *)); while (true) { // cast is a workaround for a bug in msvc: it treats const char** as a const pointer instead of a pointer to pointer to const char - memset((char**)caps, 0, caps_num * sizeof(char*)); + memset((char **)caps, 0, caps_num * sizeof(char *)); int res = re1_5_recursiveloopprog(&self->re, &subj, caps, caps_num, false); // if we didn't have a match, or had an empty match, it's time to stop @@ -230,7 +230,7 @@ STATIC mp_obj_t re_split(size_t n_args, const mp_obj_t *args) { break; } - mp_obj_t s = mp_obj_new_str_of_type(str_type, (const byte*)subj.begin, caps[0] - subj.begin); + mp_obj_t s = mp_obj_new_str_of_type(str_type, (const byte *)subj.begin, caps[0] - subj.begin); mp_obj_list_append(retval, s); if (self->re.sub > 0) { mp_raise_NotImplementedError("Splitting with sub-captures"); @@ -241,9 +241,9 @@ STATIC mp_obj_t re_split(size_t n_args, const mp_obj_t *args) { } } // cast is a workaround for a bug in msvc (see above) - mp_local_free((char**)caps); + mp_local_free((char **)caps); - mp_obj_t s = mp_obj_new_str_of_type(str_type, (const byte*)subj.begin, subj.end - subj.begin); + mp_obj_t s = mp_obj_new_str_of_type(str_type, (const byte *)subj.begin, subj.end - subj.begin); mp_obj_list_append(retval, s); return retval; } @@ -270,14 +270,14 @@ STATIC mp_obj_t re_sub_helper(mp_obj_t self_in, size_t n_args, const mp_obj_t *a vstr_t vstr_return; vstr_return.buf = NULL; // We'll init the vstr after the first match - mp_obj_match_t *match = mp_local_alloc(sizeof(mp_obj_match_t) + caps_num * sizeof(char*)); + mp_obj_match_t *match = mp_local_alloc(sizeof(mp_obj_match_t) + caps_num * sizeof(char *)); match->base.type = &match_type; match->num_matches = caps_num / 2; // caps_num counts start and end pointers match->str = where; for (;;) { // cast is a workaround for a bug in msvc: it treats const char** as a const pointer instead of a pointer to pointer to const char - memset((char*)match->caps, 0, caps_num * sizeof(char*)); + memset((char *)match->caps, 0, caps_num * sizeof(char *)); int res = re1_5_recursiveloopprog(&self->re, &subj, match->caps, caps_num, false); // If we didn't have a match, or had an empty match, it's time to stop @@ -294,7 +294,7 @@ STATIC mp_obj_t re_sub_helper(mp_obj_t self_in, size_t n_args, const mp_obj_t *a vstr_add_strn(&vstr_return, subj.begin, match->caps[0] - subj.begin); // Get replacement string - const char* repl = mp_obj_str_get_str((mp_obj_is_callable(replace) ? mp_call_function_1(replace, MP_OBJ_FROM_PTR(match)) : replace)); + const char *repl = mp_obj_str_get_str((mp_obj_is_callable(replace) ? mp_call_function_1(replace, MP_OBJ_FROM_PTR(match)) : replace)); // Append replacement string to result, substituting any regex groups while (*repl != '\0') { @@ -378,7 +378,7 @@ STATIC const mp_obj_type_t re_type = { { &mp_type_type }, .name = MP_QSTR_ure, .print = re_print, - .locals_dict = (void*)&re_locals_dict, + .locals_dict = (void *)&re_locals_dict, }; STATIC mp_obj_t mod_re_compile(size_t n_args, const mp_obj_t *args) { @@ -395,7 +395,7 @@ STATIC mp_obj_t mod_re_compile(size_t n_args, const mp_obj_t *args) { } int error = re1_5_compilecode(&o->re, re_str); if (error != 0) { -error: + error: mp_raise_ValueError("Error in regex"); } if (flags & FLAG_DEBUG) { @@ -447,7 +447,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_re_globals, mp_module_re_globals_table); const mp_obj_module_t mp_module_ure = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_re_globals, + .globals = (mp_obj_dict_t *)&mp_module_re_globals, }; // Source files #include'd here to make sure they're compiled in @@ -459,4 +459,4 @@ const mp_obj_module_t mp_module_ure = { #include "re1.5/recursiveloop.c" #include "re1.5/charclass.c" -#endif //MICROPY_PY_URE +#endif // MICROPY_PY_URE diff --git a/extmod/moduselect.c b/extmod/moduselect.c index 582814b0b6..ca48803567 100644 --- a/extmod/moduselect.c +++ b/extmod/moduselect.c @@ -65,9 +65,9 @@ STATIC void poll_map_add(mp_map_t *poll_map, const mp_obj_t *obj, mp_uint_t obj_ } else { // object exists; update its flags if (or_flags) { - ((poll_obj_t*)MP_OBJ_TO_PTR(elem->value))->flags |= flags; + ((poll_obj_t *)MP_OBJ_TO_PTR(elem->value))->flags |= flags; } else { - ((poll_obj_t*)MP_OBJ_TO_PTR(elem->value))->flags = flags; + ((poll_obj_t *)MP_OBJ_TO_PTR(elem->value))->flags = flags; } } } @@ -160,13 +160,13 @@ STATIC mp_obj_t select_select(uint n_args, const mp_obj_t *args) { } poll_obj_t *poll_obj = MP_OBJ_TO_PTR(poll_map.table[i].value); if (poll_obj->flags_ret & MP_STREAM_POLL_RD) { - ((mp_obj_list_t*)MP_OBJ_TO_PTR(list_array[0]))->items[rwx_len[0]++] = poll_obj->obj; + ((mp_obj_list_t *)MP_OBJ_TO_PTR(list_array[0]))->items[rwx_len[0]++] = poll_obj->obj; } if (poll_obj->flags_ret & MP_STREAM_POLL_WR) { - ((mp_obj_list_t*)MP_OBJ_TO_PTR(list_array[1]))->items[rwx_len[1]++] = poll_obj->obj; + ((mp_obj_list_t *)MP_OBJ_TO_PTR(list_array[1]))->items[rwx_len[1]++] = poll_obj->obj; } if ((poll_obj->flags_ret & ~(MP_STREAM_POLL_RD | MP_STREAM_POLL_WR)) != 0) { - ((mp_obj_list_t*)MP_OBJ_TO_PTR(list_array[2]))->items[rwx_len[2]++] = poll_obj->obj; + ((mp_obj_list_t *)MP_OBJ_TO_PTR(list_array[2]))->items[rwx_len[2]++] = poll_obj->obj; } } mp_map_deinit(&poll_map); @@ -219,7 +219,7 @@ STATIC mp_obj_t poll_modify(mp_obj_t self_in, mp_obj_t obj_in, mp_obj_t eventmas if (elem == NULL) { mp_raise_OSError(MP_ENOENT); } - ((poll_obj_t*)MP_OBJ_TO_PTR(elem->value))->flags = mp_obj_get_int(eventmask_in); + ((poll_obj_t *)MP_OBJ_TO_PTR(elem->value))->flags = mp_obj_get_int(eventmask_in); return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_3(poll_modify_obj, poll_modify); @@ -344,7 +344,7 @@ STATIC const mp_obj_type_t mp_type_poll = { .name = MP_QSTR_poll, .getiter = mp_identity_getiter, .iternext = poll_iternext, - .locals_dict = (void*)&poll_locals_dict, + .locals_dict = (void *)&poll_locals_dict, }; /// \function poll() @@ -372,7 +372,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_select_globals, mp_module_select_globals_t const mp_obj_module_t mp_module_uselect = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_select_globals, + .globals = (mp_obj_dict_t *)&mp_module_select_globals, }; #endif // MICROPY_PY_USELECT diff --git a/extmod/modussl_axtls.c b/extmod/modussl_axtls.c index 2dab6ff491..0e026fa4e7 100644 --- a/extmod/modussl_axtls.c +++ b/extmod/modussl_axtls.c @@ -53,11 +53,11 @@ struct ssl_args { STATIC const mp_obj_type_t ussl_socket_type; STATIC mp_obj_ssl_socket_t *socket_new(mp_obj_t sock, struct ssl_args *args) { -#if MICROPY_PY_USSL_FINALISER + #if MICROPY_PY_USSL_FINALISER mp_obj_ssl_socket_t *o = m_new_obj_with_finaliser(mp_obj_ssl_socket_t); -#else + #else mp_obj_ssl_socket_t *o = m_new_obj(mp_obj_ssl_socket_t); -#endif + #endif o->base.type = &ussl_socket_type; o->buf = NULL; o->bytes_left = 0; @@ -73,13 +73,13 @@ STATIC mp_obj_ssl_socket_t *socket_new(mp_obj_t sock, struct ssl_args *args) { if (args->key.u_obj != mp_const_none) { size_t len; - const byte *data = (const byte*)mp_obj_str_get_data(args->key.u_obj, &len); + const byte *data = (const byte *)mp_obj_str_get_data(args->key.u_obj, &len); int res = ssl_obj_memory_load(o->ssl_ctx, SSL_OBJ_RSA_KEY, data, len, NULL); if (res != SSL_OK) { mp_raise_ValueError("invalid key"); } - data = (const byte*)mp_obj_str_get_data(args->cert.u_obj, &len); + data = (const byte *)mp_obj_str_get_data(args->cert.u_obj, &len); res = ssl_obj_memory_load(o->ssl_ctx, SSL_OBJ_X509_CERT, data, len, NULL); if (res != SSL_OK) { mp_raise_ValueError("invalid cert"); @@ -92,7 +92,7 @@ STATIC mp_obj_ssl_socket_t *socket_new(mp_obj_t sock, struct ssl_args *args) { SSL_EXTENSIONS *ext = ssl_ext_new(); if (args->server_hostname.u_obj != mp_const_none) { - ext->host_name = (char*)mp_obj_str_get_str(args->server_hostname.u_obj); + ext->host_name = (char *)mp_obj_str_get_str(args->server_hostname.u_obj); } o->ssl_sock = ssl_client_new(o->ssl_ctx, (long)sock, NULL, 0, ext); @@ -203,9 +203,9 @@ STATIC const mp_rom_map_elem_t ussl_socket_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_write), MP_ROM_PTR(&mp_stream_write_obj) }, { MP_ROM_QSTR(MP_QSTR_setblocking), MP_ROM_PTR(&socket_setblocking_obj) }, { MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&mp_stream_close_obj) }, -#if MICROPY_PY_USSL_FINALISER + #if MICROPY_PY_USSL_FINALISER { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&mp_stream_close_obj) }, -#endif + #endif }; STATIC MP_DEFINE_CONST_DICT(ussl_socket_locals_dict, ussl_socket_locals_dict_table); @@ -224,7 +224,7 @@ STATIC const mp_obj_type_t ussl_socket_type = { .getiter = NULL, .iternext = NULL, .protocol = &ussl_socket_stream_p, - .locals_dict = (void*)&ussl_socket_locals_dict, + .locals_dict = (void *)&ussl_socket_locals_dict, }; STATIC mp_obj_t mod_ssl_wrap_socket(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { @@ -241,7 +241,7 @@ STATIC mp_obj_t mod_ssl_wrap_socket(size_t n_args, const mp_obj_t *pos_args, mp_ struct ssl_args 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_ARRAY_SIZE(allowed_args), allowed_args, (mp_arg_val_t *)&args); return MP_OBJ_FROM_PTR(socket_new(sock, &args)); } @@ -256,7 +256,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_ssl_globals, mp_module_ssl_globals_table); const mp_obj_module_t mp_module_ussl = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_ssl_globals, + .globals = (mp_obj_dict_t *)&mp_module_ssl_globals, }; #endif // MICROPY_PY_USSL diff --git a/extmod/modussl_mbedtls.c b/extmod/modussl_mbedtls.c index ce3db0fd92..9242f53f0c 100644 --- a/extmod/modussl_mbedtls.c +++ b/extmod/modussl_mbedtls.c @@ -74,7 +74,7 @@ STATIC void mbedtls_debug(void *ctx, int level, const char *file, int line, cons #endif STATIC int _mbedtls_ssl_send(void *ctx, const byte *buf, size_t len) { - mp_obj_t sock = *(mp_obj_t*)ctx; + mp_obj_t sock = *(mp_obj_t *)ctx; const mp_stream_p_t *sock_stream = mp_get_stream(sock); int err; @@ -91,7 +91,7 @@ STATIC int _mbedtls_ssl_send(void *ctx, const byte *buf, size_t len) { } STATIC int _mbedtls_ssl_recv(void *ctx, byte *buf, size_t len) { - mp_obj_t sock = *(mp_obj_t*)ctx; + mp_obj_t sock = *(mp_obj_t *)ctx; const mp_stream_p_t *sock_stream = mp_get_stream(sock); int err; @@ -112,11 +112,11 @@ STATIC mp_obj_ssl_socket_t *socket_new(mp_obj_t sock, struct ssl_args *args) { // Verify the socket object has the full stream protocol mp_get_stream_raise(sock, MP_STREAM_OP_READ | MP_STREAM_OP_WRITE | MP_STREAM_OP_IOCTL); -#if MICROPY_PY_USSL_FINALISER + #if MICROPY_PY_USSL_FINALISER mp_obj_ssl_socket_t *o = m_new_obj_with_finaliser(mp_obj_ssl_socket_t); -#else + #else mp_obj_ssl_socket_t *o = m_new_obj(mp_obj_ssl_socket_t); -#endif + #endif o->base.type = &ussl_socket_type; o->sock = sock; @@ -140,9 +140,9 @@ STATIC mp_obj_ssl_socket_t *socket_new(mp_obj_t sock, struct ssl_args *args) { } ret = mbedtls_ssl_config_defaults(&o->conf, - args->server_side.u_bool ? MBEDTLS_SSL_IS_SERVER : MBEDTLS_SSL_IS_CLIENT, - MBEDTLS_SSL_TRANSPORT_STREAM, - MBEDTLS_SSL_PRESET_DEFAULT); + args->server_side.u_bool ? MBEDTLS_SSL_IS_SERVER : MBEDTLS_SSL_IS_CLIENT, + MBEDTLS_SSL_TRANSPORT_STREAM, + MBEDTLS_SSL_PRESET_DEFAULT); if (ret != 0) { goto cleanup; } @@ -170,13 +170,13 @@ STATIC mp_obj_ssl_socket_t *socket_new(mp_obj_t sock, struct ssl_args *args) { if (args->key.u_obj != MP_OBJ_NULL) { size_t key_len; - const byte *key = (const byte*)mp_obj_str_get_data(args->key.u_obj, &key_len); + const byte *key = (const byte *)mp_obj_str_get_data(args->key.u_obj, &key_len); // len should include terminating null ret = mbedtls_pk_parse_key(&o->pkey, key, key_len + 1, NULL, 0); assert(ret == 0); size_t cert_len; - const byte *cert = (const byte*)mp_obj_str_get_data(args->cert.u_obj, &cert_len); + const byte *cert = (const byte *)mp_obj_str_get_data(args->cert.u_obj, &cert_len); // len should include terminating null ret = mbedtls_x509_crt_parse(&o->cert, cert, cert_len + 1); assert(ret == 0); @@ -215,7 +215,7 @@ STATIC mp_obj_t mod_ssl_getpeercert(mp_obj_t o_in, mp_obj_t binary_form) { if (!mp_obj_is_true(binary_form)) { mp_raise_NotImplementedError(NULL); } - const mbedtls_x509_crt* peer_cert = mbedtls_ssl_get_peer_cert(&o->ssl); + const mbedtls_x509_crt *peer_cert = mbedtls_ssl_get_peer_cert(&o->ssl); return mp_obj_new_bytes(peer_cert->raw.p, peer_cert->raw.len); } STATIC MP_DEFINE_CONST_FUN_OBJ_2(mod_ssl_getpeercert_obj, mod_ssl_getpeercert); @@ -290,9 +290,9 @@ STATIC const mp_rom_map_elem_t ussl_socket_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_write), MP_ROM_PTR(&mp_stream_write_obj) }, { MP_ROM_QSTR(MP_QSTR_setblocking), MP_ROM_PTR(&socket_setblocking_obj) }, { MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&mp_stream_close_obj) }, -#if MICROPY_PY_USSL_FINALISER + #if MICROPY_PY_USSL_FINALISER { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&mp_stream_close_obj) }, -#endif + #endif { MP_ROM_QSTR(MP_QSTR_getpeercert), MP_ROM_PTR(&mod_ssl_getpeercert_obj) }, }; @@ -312,7 +312,7 @@ STATIC const mp_obj_type_t ussl_socket_type = { .getiter = NULL, .iternext = NULL, .protocol = &ussl_socket_stream_p, - .locals_dict = (void*)&ussl_socket_locals_dict, + .locals_dict = (void *)&ussl_socket_locals_dict, }; STATIC mp_obj_t mod_ssl_wrap_socket(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { @@ -329,7 +329,7 @@ STATIC mp_obj_t mod_ssl_wrap_socket(size_t n_args, const mp_obj_t *pos_args, mp_ struct ssl_args 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_ARRAY_SIZE(allowed_args), allowed_args, (mp_arg_val_t *)&args); return MP_OBJ_FROM_PTR(socket_new(sock, &args)); } @@ -344,7 +344,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_ssl_globals, mp_module_ssl_globals_table); const mp_obj_module_t mp_module_ussl = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_ssl_globals, + .globals = (mp_obj_dict_t *)&mp_module_ssl_globals, }; #endif // MICROPY_PY_USSL diff --git a/extmod/modutimeq.c b/extmod/modutimeq.c index 620e7484b9..6384e5b073 100644 --- a/extmod/modutimeq.c +++ b/extmod/modutimeq.c @@ -190,9 +190,12 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_utimeq_dump_obj, mod_utimeq_dump); STATIC mp_obj_t utimeq_unary_op(mp_unary_op_t op, mp_obj_t self_in) { mp_obj_utimeq_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); - default: return MP_OBJ_NULL; // op not supported + 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); + default: + return MP_OBJ_NULL; // op not supported } } @@ -212,7 +215,7 @@ STATIC const mp_obj_type_t utimeq_type = { .name = MP_QSTR_utimeq, .make_new = utimeq_make_new, .unary_op = utimeq_unary_op, - .locals_dict = (void*)&utimeq_locals_dict, + .locals_dict = (void *)&utimeq_locals_dict, }; STATIC const mp_rom_map_elem_t mp_module_utimeq_globals_table[] = { @@ -224,7 +227,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_utimeq_globals, mp_module_utimeq_globals_t const mp_obj_module_t mp_module_utimeq = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_utimeq_globals, + .globals = (mp_obj_dict_t *)&mp_module_utimeq_globals, }; -#endif //MICROPY_PY_UTIMEQ +#endif // MICROPY_PY_UTIMEQ diff --git a/extmod/moduzlib.c b/extmod/moduzlib.c index 940b72805d..9ccdd007ac 100644 --- a/extmod/moduzlib.c +++ b/extmod/moduzlib.c @@ -49,9 +49,9 @@ typedef struct _mp_obj_decompio_t { } mp_obj_decompio_t; STATIC unsigned char read_src_stream(TINF_DATA *data) { - byte *p = (void*)data; + byte *p = (void *)data; p -= offsetof(mp_obj_decompio_t, decomp); - mp_obj_decompio_t *self = (mp_obj_decompio_t*)p; + mp_obj_decompio_t *self = (mp_obj_decompio_t *)p; const mp_stream_p_t *stream = mp_get_stream(self->src_stream); int err; @@ -91,7 +91,7 @@ STATIC mp_obj_t decompio_make_new(const mp_obj_type_t *type, size_t n_args, size } else if (dict_opt >= 0) { dict_opt = uzlib_zlib_parse_header(&o->decomp); if (dict_opt < 0) { -header_error: + header_error: mp_raise_ValueError("compression header"); } dict_sz = 1 << dict_opt; @@ -119,7 +119,7 @@ STATIC mp_uint_t decompio_read(mp_obj_t o_in, void *buf, mp_uint_t size, int *er *errcode = MP_EINVAL; return MP_STREAM_ERROR; } - return o->decomp.dest - (byte*)buf; + return o->decomp.dest - (byte *)buf; } STATIC const mp_rom_map_elem_t decompio_locals_dict_table[] = { @@ -139,7 +139,7 @@ STATIC const mp_obj_type_t decompio_type = { .name = MP_QSTR_DecompIO, .make_new = decompio_make_new, .protocol = &decompio_stream_p, - .locals_dict = (void*)&decompio_locals_dict, + .locals_dict = (void *)&decompio_locals_dict, }; STATIC mp_obj_t mod_uzlib_decompress(size_t n_args, const mp_obj_t *args) { @@ -190,13 +190,13 @@ STATIC mp_obj_t mod_uzlib_decompress(size_t n_args, const mp_obj_t *args) { mp_uint_t final_sz = decomp->dest - dest_buf; DEBUG_printf("uzlib: Resizing from " UINT_FMT " to final size: " UINT_FMT " bytes\n", dest_buf_size, final_sz); - dest_buf = (byte*)m_renew(byte, dest_buf, dest_buf_size, final_sz); + dest_buf = (byte *)m_renew(byte, dest_buf, dest_buf_size, final_sz); mp_obj_t res = mp_obj_new_bytearray_by_ref(final_sz, dest_buf); m_del_obj(TINF_DATA, decomp); return res; error: - nlr_raise(mp_obj_new_exception_arg1(&mp_type_ValueError, MP_OBJ_NEW_SMALL_INT(st))); + nlr_raise(mp_obj_new_exception_arg1(&mp_type_ValueError, MP_OBJ_NEW_SMALL_INT(st))); } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_uzlib_decompress_obj, 1, 3, mod_uzlib_decompress); @@ -210,7 +210,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_uzlib_globals, mp_module_uzlib_globals_tab const mp_obj_module_t mp_module_uzlib = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_uzlib_globals, + .globals = (mp_obj_dict_t *)&mp_module_uzlib_globals, }; // Source files #include'd here to make sure they're compiled in diff --git a/extmod/modwebrepl.c b/extmod/modwebrepl.c index 3c33ee1502..5201ffdccf 100644 --- a/extmod/modwebrepl.c +++ b/extmod/modwebrepl.c @@ -147,7 +147,7 @@ STATIC void handle_op(mp_obj_webrepl_t *self) { open_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_wb); } - self->cur_file = mp_builtin_open(2, open_args, (mp_map_t*)&mp_const_empty_map); + self->cur_file = mp_builtin_open(2, open_args, (mp_map_t *)&mp_const_empty_map); #if 0 struct mp_stream_seek_t seek = { .offset = self->hdr.offset, .whence = 0 }; @@ -181,13 +181,13 @@ STATIC mp_uint_t _webrepl_read(mp_obj_t self_in, void *buf, mp_uint_t size, int mp_obj_webrepl_t *self = self_in; const mp_stream_p_t *sock_stream = mp_get_stream(self->sock); mp_uint_t out_sz = sock_stream->read(self->sock, buf, size, errcode); - //DEBUG_printf("webrepl: Read %d initial bytes from websocket\n", out_sz); + // DEBUG_printf("webrepl: Read %d initial bytes from websocket\n", out_sz); if (out_sz == 0 || out_sz == MP_STREAM_ERROR) { return out_sz; } if (self->state == STATE_PASSWD) { - char c = *(char*)buf; + char c = *(char *)buf; if (c == '\r' || c == '\n') { self->hdr.fname[self->data_to_recv] = 0; DEBUG_printf("webrepl: entered password: %s\n", self->hdr.fname); @@ -215,8 +215,8 @@ STATIC mp_uint_t _webrepl_read(mp_obj_t self_in, void *buf, mp_uint_t size, int DEBUG_printf("webrepl: received bin data, hdr_to_recv: %d, data_to_recv=%d\n", self->hdr_to_recv, self->data_to_recv); if (self->hdr_to_recv != 0) { - char *p = (char*)&self->hdr + sizeof(self->hdr) - self->hdr_to_recv; - *p++ = *(char*)buf; + char *p = (char *)&self->hdr + sizeof(self->hdr) - self->hdr_to_recv; + *p++ = *(char *)buf; if (--self->hdr_to_recv != 0) { mp_uint_t hdr_sz = sock_stream->read(self->sock, p, self->hdr_to_recv, errcode); if (hdr_sz == MP_STREAM_ERROR) { @@ -237,7 +237,7 @@ STATIC mp_uint_t _webrepl_read(mp_obj_t self_in, void *buf, mp_uint_t size, int if (self->data_to_recv != 0) { static byte filebuf[512]; - filebuf[0] = *(byte*)buf; + filebuf[0] = *(byte *)buf; mp_uint_t buf_sz = 1; if (--self->data_to_recv != 0) { size_t to_read = MIN(sizeof(filebuf) - 1, self->data_to_recv); @@ -340,7 +340,7 @@ STATIC const mp_obj_type_t webrepl_type = { .name = MP_QSTR__webrepl, .make_new = webrepl_make_new, .protocol = &webrepl_stream_p, - .locals_dict = (mp_obj_dict_t*)&webrepl_locals_dict, + .locals_dict = (mp_obj_dict_t *)&webrepl_locals_dict, }; STATIC const mp_rom_map_elem_t webrepl_module_globals_table[] = { @@ -353,7 +353,7 @@ STATIC MP_DEFINE_CONST_DICT(webrepl_module_globals, webrepl_module_globals_table const mp_obj_module_t mp_module_webrepl = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&webrepl_module_globals, + .globals = (mp_obj_dict_t *)&webrepl_module_globals, }; #endif // MICROPY_PY_WEBREPL diff --git a/extmod/modwebsocket.c b/extmod/modwebsocket.c index c556f2b770..4dbff7e065 100644 --- a/extmod/modwebsocket.c +++ b/extmod/modwebsocket.c @@ -71,11 +71,11 @@ STATIC mp_obj_t websocket_make_new(const mp_obj_type_t *type, size_t n_args, siz if (n_args > 1 && args[1] == mp_const_true) { o->opts |= BLOCKING_WRITE; } - return MP_OBJ_FROM_PTR(o); + return MP_OBJ_FROM_PTR(o); } STATIC mp_uint_t websocket_read(mp_obj_t self_in, void *buf, mp_uint_t size, int *errcode) { - mp_obj_websocket_t *self = MP_OBJ_TO_PTR(self_in); + mp_obj_websocket_t *self = MP_OBJ_TO_PTR(self_in); const mp_stream_p_t *stream_p = mp_get_stream(self->sock); while (1) { if (self->to_recv != 0) { @@ -183,7 +183,7 @@ STATIC mp_uint_t websocket_read(mp_obj_t self_in, void *buf, mp_uint_t size, int self->msg_sz -= out_sz; if (self->msg_sz == 0) { byte last_state; -no_payload: + no_payload: last_state = self->state; self->state = FRAME_HEADER; self->to_recv = 2; @@ -200,7 +200,7 @@ no_payload: return 0; } - //DEBUG_printf("Finished receiving ctrl message %x, ignoring\n", self->last_flags); + // DEBUG_printf("Finished receiving ctrl message %x, ignoring\n", self->last_flags); continue; } } @@ -217,7 +217,7 @@ no_payload: } STATIC mp_uint_t websocket_write(mp_obj_t self_in, const void *buf, mp_uint_t size, int *errcode) { - mp_obj_websocket_t *self = MP_OBJ_TO_PTR(self_in); + mp_obj_websocket_t *self = MP_OBJ_TO_PTR(self_in); assert(size < 0x10000); byte header[4] = {0x80 | (self->opts & FRAME_OPCODE_MASK)}; int hdr_sz; @@ -296,7 +296,7 @@ STATIC const mp_obj_type_t websocket_type = { .name = MP_QSTR_websocket, .make_new = websocket_make_new, .protocol = &websocket_stream_p, - .locals_dict = (void*)&websocket_locals_dict, + .locals_dict = (void *)&websocket_locals_dict, }; STATIC const mp_rom_map_elem_t websocket_module_globals_table[] = { @@ -308,7 +308,7 @@ STATIC MP_DEFINE_CONST_DICT(websocket_module_globals, websocket_module_globals_t const mp_obj_module_t mp_module_websocket = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&websocket_module_globals, + .globals = (mp_obj_dict_t *)&websocket_module_globals, }; #endif // MICROPY_PY_WEBSOCKET diff --git a/extmod/utime_mphal.c b/extmod/utime_mphal.c index 0fe3a3ba1d..6aff2cac72 100644 --- a/extmod/utime_mphal.c +++ b/extmod/utime_mphal.c @@ -86,7 +86,7 @@ STATIC mp_obj_t time_ticks_diff(mp_obj_t end_in, mp_obj_t start_in) { // Optimized formula avoiding if conditions. We adjust difference "forward", // wrap it around and adjust back. mp_int_t diff = ((end - start + MICROPY_PY_UTIME_TICKS_PERIOD / 2) & (MICROPY_PY_UTIME_TICKS_PERIOD - 1)) - - MICROPY_PY_UTIME_TICKS_PERIOD / 2; + - MICROPY_PY_UTIME_TICKS_PERIOD / 2; return MP_OBJ_NEW_SMALL_INT(diff); } MP_DEFINE_CONST_FUN_OBJ_2(mp_utime_ticks_diff_obj, time_ticks_diff); diff --git a/extmod/vfs.c b/extmod/vfs.c index fd7f2a4feb..2a96bf629c 100644 --- a/extmod/vfs.c +++ b/extmod/vfs.c @@ -99,7 +99,7 @@ STATIC mp_vfs_mount_t *lookup_path(mp_obj_t path_in, mp_obj_t *path_out) { mp_vfs_mount_t *vfs = mp_vfs_lookup_path(path, &p_out); if (vfs != MP_VFS_NONE && vfs != MP_VFS_ROOT) { *path_out = mp_obj_new_str_of_type(mp_obj_get_type(path_in), - (const byte*)p_out, strlen(p_out)); + (const byte *)p_out, strlen(p_out)); } return vfs; } @@ -192,7 +192,7 @@ mp_obj_t mp_vfs_mount(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args vfs->next = NULL; // call the underlying object to do any mounting operation - mp_vfs_proxy_call(vfs, MP_QSTR_mount, 2, (mp_obj_t*)&args); + mp_vfs_proxy_call(vfs, MP_QSTR_mount, 2, (mp_obj_t *)&args); // check that the destination mount point is unused const char *path_out; @@ -276,7 +276,7 @@ mp_obj_t mp_vfs_open(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) #endif mp_vfs_mount_t *vfs = lookup_path(args[ARG_file].u_obj, &args[ARG_file].u_obj); - return mp_vfs_proxy_call(vfs, MP_QSTR_open, 2, (mp_obj_t*)&args); + return mp_vfs_proxy_call(vfs, MP_QSTR_open, 2, (mp_obj_t *)&args); } MP_DEFINE_CONST_FUN_OBJ_KW(mp_vfs_open_obj, 0, mp_vfs_open); @@ -356,7 +356,7 @@ STATIC mp_obj_t mp_vfs_ilistdir_it_iternext(mp_obj_t self_in) { mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(3, NULL)); t->items[0] = mp_obj_new_str_of_type( self->is_str ? &mp_type_str : &mp_type_bytes, - (const byte*)vfs->str + 1, vfs->len - 1); + (const byte *)vfs->str + 1, vfs->len - 1); t->items[1] = MP_OBJ_NEW_SMALL_INT(MP_S_IFDIR); t->items[2] = MP_OBJ_NEW_SMALL_INT(0); // no inode number return MP_OBJ_FROM_PTR(t); diff --git a/extmod/vfs.h b/extmod/vfs.h index 730dea0431..32557baccf 100644 --- a/extmod/vfs.h +++ b/extmod/vfs.h @@ -31,8 +31,8 @@ // return values of mp_vfs_lookup_path // ROOT is 0 so that the default current directory is the root directory -#define MP_VFS_NONE ((mp_vfs_mount_t*)1) -#define MP_VFS_ROOT ((mp_vfs_mount_t*)0) +#define MP_VFS_NONE ((mp_vfs_mount_t *)1) +#define MP_VFS_ROOT ((mp_vfs_mount_t *)0) // MicroPython's port-standardized versions of stat constants #define MP_S_IFDIR (0x4000) diff --git a/extmod/vfs_fat.c b/extmod/vfs_fat.c index 4af836b2d0..99fe7bfcac 100644 --- a/extmod/vfs_fat.c +++ b/extmod/vfs_fat.c @@ -148,7 +148,7 @@ STATIC mp_obj_t mp_vfs_fat_ilistdir_it_iternext(mp_obj_t self_in) { if (self->is_str) { t->items[0] = mp_obj_new_str(fn, strlen(fn)); } else { - t->items[0] = mp_obj_new_bytes((const byte*)fn, strlen(fn)); + t->items[0] = mp_obj_new_bytes((const byte *)fn, strlen(fn)); } if (fno.fattrib & AM_DIR) { // dir @@ -324,7 +324,7 @@ STATIC mp_obj_t fat_vfs_stat(mp_obj_t vfs_in, mp_obj_t path_in) { (fno.ftime >> 11) & 0x1f, (fno.ftime >> 5) & 0x3f, 2 * (fno.ftime & 0x1f) - ); + ); t->items[0] = MP_OBJ_NEW_SMALL_INT(mode); // st_mode t->items[1] = MP_OBJ_NEW_SMALL_INT(0); // st_ino t->items[2] = MP_OBJ_NEW_SMALL_INT(0); // st_dev @@ -431,7 +431,7 @@ const mp_obj_type_t mp_fat_vfs_type = { .name = MP_QSTR_VfsFat, .make_new = fat_vfs_make_new, .protocol = &fat_vfs_proto, - .locals_dict = (mp_obj_dict_t*)&fat_vfs_locals_dict, + .locals_dict = (mp_obj_dict_t *)&fat_vfs_locals_dict, }; diff --git a/extmod/vfs_fat_diskio.c b/extmod/vfs_fat_diskio.c index fa013d2786..507513f927 100644 --- a/extmod/vfs_fat_diskio.c +++ b/extmod/vfs_fat_diskio.c @@ -50,32 +50,31 @@ typedef void *bdev_t; STATIC fs_user_mount_t *disk_get_device(void *bdev) { - return (fs_user_mount_t*)bdev; + return (fs_user_mount_t *)bdev; } /*-----------------------------------------------------------------------*/ /* Read Sector(s) */ /*-----------------------------------------------------------------------*/ -DRESULT disk_read ( +DRESULT disk_read( bdev_t pdrv, /* Physical drive nmuber (0..) */ BYTE *buff, /* Data buffer to store read data */ DWORD sector, /* Sector address (LBA) */ UINT count /* Number of sectors to read (1..128) */ -) -{ + ) { fs_user_mount_t *vfs = disk_get_device(pdrv); if (vfs == NULL) { return RES_PARERR; } if (vfs->flags & FSUSER_NATIVE) { - mp_uint_t (*f)(uint8_t*, uint32_t, uint32_t) = (void*)(uintptr_t)vfs->readblocks[2]; + mp_uint_t (*f)(uint8_t *, uint32_t, uint32_t) = (void *)(uintptr_t)vfs->readblocks[2]; if (f(buff, sector, count) != 0) { return RES_ERROR; } } else { - mp_obj_array_t ar = {{&mp_type_bytearray}, BYTEARRAY_TYPECODE, 0, count * SECSIZE(&vfs->fatfs), buff}; + mp_obj_array_t ar = {{&mp_type_bytearray}, BYTEARRAY_TYPECODE, 0, count *SECSIZE(&vfs->fatfs), buff}; vfs->readblocks[2] = MP_OBJ_NEW_SMALL_INT(sector); vfs->readblocks[3] = MP_OBJ_FROM_PTR(&ar); mp_call_method_n_kw(2, 0, vfs->readblocks); @@ -89,13 +88,12 @@ DRESULT disk_read ( /* Write Sector(s) */ /*-----------------------------------------------------------------------*/ -DRESULT disk_write ( +DRESULT disk_write( bdev_t pdrv, /* Physical drive nmuber (0..) */ const BYTE *buff, /* Data to be written */ DWORD sector, /* Sector address (LBA) */ UINT count /* Number of sectors to write (1..128) */ -) -{ + ) { fs_user_mount_t *vfs = disk_get_device(pdrv); if (vfs == NULL) { return RES_PARERR; @@ -107,12 +105,12 @@ DRESULT disk_write ( } if (vfs->flags & FSUSER_NATIVE) { - mp_uint_t (*f)(const uint8_t*, uint32_t, uint32_t) = (void*)(uintptr_t)vfs->writeblocks[2]; + mp_uint_t (*f)(const uint8_t *, uint32_t, uint32_t) = (void *)(uintptr_t)vfs->writeblocks[2]; if (f(buff, sector, count) != 0) { return RES_ERROR; } } else { - mp_obj_array_t ar = {{&mp_type_bytearray}, BYTEARRAY_TYPECODE, 0, count * SECSIZE(&vfs->fatfs), (void*)buff}; + mp_obj_array_t ar = {{&mp_type_bytearray}, BYTEARRAY_TYPECODE, 0, count *SECSIZE(&vfs->fatfs), (void *)buff}; vfs->writeblocks[2] = MP_OBJ_NEW_SMALL_INT(sector); vfs->writeblocks[3] = MP_OBJ_FROM_PTR(&ar); mp_call_method_n_kw(2, 0, vfs->writeblocks); @@ -127,12 +125,11 @@ DRESULT disk_write ( /* Miscellaneous Functions */ /*-----------------------------------------------------------------------*/ -DRESULT disk_ioctl ( +DRESULT disk_ioctl( bdev_t pdrv, /* Physical drive nmuber (0..) */ BYTE cmd, /* Control code */ void *buff /* Buffer to send/receive control data */ -) -{ + ) { fs_user_mount_t *vfs = disk_get_device(pdrv); if (vfs == NULL) { return RES_PARERR; @@ -183,26 +180,26 @@ DRESULT disk_ioctl ( return RES_OK; case GET_SECTOR_COUNT: { - *((DWORD*)buff) = mp_obj_get_int(ret); + *((DWORD *)buff) = mp_obj_get_int(ret); return RES_OK; } case GET_SECTOR_SIZE: { if (ret == mp_const_none) { // Default sector size - *((WORD*)buff) = 512; + *((WORD *)buff) = 512; } else { - *((WORD*)buff) = mp_obj_get_int(ret); + *((WORD *)buff) = mp_obj_get_int(ret); } #if _MAX_SS != _MIN_SS // need to store ssize because we use it in disk_read/disk_write - vfs->fatfs.ssize = *((WORD*)buff); + vfs->fatfs.ssize = *((WORD *)buff); #endif return RES_OK; } case GET_BLOCK_SIZE: - *((DWORD*)buff) = 1; // erase block size in units of sector size + *((DWORD *)buff) = 1; // erase block size in units of sector size return RES_OK; case IOCTL_INIT: @@ -216,7 +213,7 @@ DRESULT disk_ioctl ( } else { stat = 0; } - *((DSTATUS*)buff) = stat; + *((DSTATUS *)buff) = stat; return RES_OK; } diff --git a/extmod/vfs_fat_file.c b/extmod/vfs_fat_file.c index f7b9331b82..bab1b5932d 100644 --- a/extmod/vfs_fat_file.c +++ b/extmod/vfs_fat_file.c @@ -107,7 +107,7 @@ STATIC mp_uint_t file_obj_ioctl(mp_obj_t o_in, mp_uint_t request, uintptr_t arg, pyb_file_obj_t *self = MP_OBJ_TO_PTR(o_in); if (request == MP_STREAM_SEEK) { - struct mp_stream_seek_t *s = (struct mp_stream_seek_t*)(uintptr_t)arg; + struct mp_stream_seek_t *s = (struct mp_stream_seek_t *)(uintptr_t)arg; switch (s->whence) { case 0: // SEEK_SET @@ -251,7 +251,7 @@ const mp_obj_type_t mp_type_vfs_fat_fileio = { .getiter = mp_identity_getiter, .iternext = mp_stream_unbuffered_iter, .protocol = &fileio_stream_p, - .locals_dict = (mp_obj_dict_t*)&rawfile_locals_dict, + .locals_dict = (mp_obj_dict_t *)&rawfile_locals_dict, }; #endif @@ -270,7 +270,7 @@ const mp_obj_type_t mp_type_vfs_fat_textio = { .getiter = mp_identity_getiter, .iternext = mp_stream_unbuffered_iter, .protocol = &textio_stream_p, - .locals_dict = (mp_obj_dict_t*)&rawfile_locals_dict, + .locals_dict = (mp_obj_dict_t *)&rawfile_locals_dict, }; // Factory function for I/O stream classes diff --git a/extmod/vfs_posix.c b/extmod/vfs_posix.c index 4ca7f9b908..c48f622680 100644 --- a/extmod/vfs_posix.c +++ b/extmod/vfs_posix.c @@ -62,7 +62,7 @@ STATIC mp_obj_t vfs_posix_get_path_obj(mp_obj_vfs_posix_t *self, mp_obj_t path) } } -STATIC mp_obj_t vfs_posix_fun1_helper(mp_obj_t self_in, mp_obj_t path_in, int (*f)(const char*)) { +STATIC mp_obj_t vfs_posix_fun1_helper(mp_obj_t self_in, mp_obj_t path_in, int (*f)(const char *)) { mp_obj_vfs_posix_t *self = MP_OBJ_TO_PTR(self_in); int ret = f(vfs_posix_get_path_str(self, path_in)); if (ret != 0) { @@ -188,7 +188,7 @@ STATIC mp_obj_t vfs_posix_ilistdir_it_iternext(mp_obj_t self_in) { if (self->is_str) { t->items[0] = mp_obj_new_str(fn, strlen(fn)); } else { - t->items[0] = mp_obj_new_bytes((const byte*)fn, strlen(fn)); + t->items[0] = mp_obj_new_bytes((const byte *)fn, strlen(fn)); } #ifdef _DIRENT_HAVE_D_TYPE @@ -365,7 +365,7 @@ const mp_obj_type_t mp_type_vfs_posix = { .name = MP_QSTR_VfsPosix, .make_new = vfs_posix_make_new, .protocol = &vfs_posix_proto, - .locals_dict = (mp_obj_dict_t*)&vfs_posix_locals_dict, + .locals_dict = (mp_obj_dict_t *)&vfs_posix_locals_dict, }; #endif // MICROPY_VFS_POSIX diff --git a/extmod/vfs_posix_file.c b/extmod/vfs_posix_file.c index 435ac65cd4..d23093eae9 100644 --- a/extmod/vfs_posix_file.c +++ b/extmod/vfs_posix_file.c @@ -78,7 +78,7 @@ mp_obj_t mp_vfs_posix_file_open(const mp_obj_type_t *type, mp_obj_t file_in, mp_ case '+': mode_rw = O_RDWR; break; - #if MICROPY_PY_IO_FILEIO + #if MICROPY_PY_IO_FILEIO // If we don't have io.FileIO, then files are in text mode implicitly case 'b': type = &mp_type_vfs_posix_fileio; @@ -86,7 +86,7 @@ mp_obj_t mp_vfs_posix_file_open(const mp_obj_type_t *type, mp_obj_t file_in, mp_ case 't': type = &mp_type_vfs_posix_textio; break; - #endif + #endif } } @@ -179,7 +179,7 @@ STATIC mp_uint_t vfs_posix_file_ioctl(mp_obj_t o_in, mp_uint_t request, uintptr_ } return 0; case MP_STREAM_SEEK: { - struct mp_stream_seek_t *s = (struct mp_stream_seek_t*)arg; + struct mp_stream_seek_t *s = (struct mp_stream_seek_t *)arg; off_t off = lseek(o->fd, s->offset, s->whence); if (off == (off_t)-1) { *errcode = errno; @@ -232,7 +232,7 @@ const mp_obj_type_t mp_type_vfs_posix_fileio = { .getiter = mp_identity_getiter, .iternext = mp_stream_unbuffered_iter, .protocol = &fileio_stream_p, - .locals_dict = (mp_obj_dict_t*)&rawfile_locals_dict, + .locals_dict = (mp_obj_dict_t *)&rawfile_locals_dict, }; #endif @@ -251,10 +251,10 @@ const mp_obj_type_t mp_type_vfs_posix_textio = { .getiter = mp_identity_getiter, .iternext = mp_stream_unbuffered_iter, .protocol = &textio_stream_p, - .locals_dict = (mp_obj_dict_t*)&rawfile_locals_dict, + .locals_dict = (mp_obj_dict_t *)&rawfile_locals_dict, }; -const mp_obj_vfs_posix_file_t mp_sys_stdin_obj = {{&mp_type_textio}, STDIN_FILENO}; +const mp_obj_vfs_posix_file_t mp_sys_stdin_obj = {{&mp_type_textio}, STDIN_FILENO}; const mp_obj_vfs_posix_file_t mp_sys_stdout_obj = {{&mp_type_textio}, STDOUT_FILENO}; const mp_obj_vfs_posix_file_t mp_sys_stderr_obj = {{&mp_type_textio}, STDERR_FILENO}; diff --git a/extmod/vfs_reader.c b/extmod/vfs_reader.c index e1ee45a3c7..db13ce3c33 100644 --- a/extmod/vfs_reader.c +++ b/extmod/vfs_reader.c @@ -42,7 +42,7 @@ typedef struct _mp_reader_vfs_t { } mp_reader_vfs_t; STATIC mp_uint_t mp_reader_vfs_readbyte(void *data) { - mp_reader_vfs_t *reader = (mp_reader_vfs_t*)data; + mp_reader_vfs_t *reader = (mp_reader_vfs_t *)data; if (reader->pos >= reader->len) { if (reader->len < sizeof(reader->buf)) { return MP_READER_EOF; @@ -64,7 +64,7 @@ STATIC mp_uint_t mp_reader_vfs_readbyte(void *data) { } STATIC void mp_reader_vfs_close(void *data) { - mp_reader_vfs_t *reader = (mp_reader_vfs_t*)data; + mp_reader_vfs_t *reader = (mp_reader_vfs_t *)data; mp_stream_close(reader->file); m_del_obj(mp_reader_vfs_t, reader); } @@ -72,7 +72,7 @@ STATIC void mp_reader_vfs_close(void *data) { void mp_reader_new_file(mp_reader_t *reader, const char *filename) { mp_reader_vfs_t *rf = m_new_obj(mp_reader_vfs_t); mp_obj_t arg = mp_obj_new_str(filename, strlen(filename)); - rf->file = mp_vfs_open(1, &arg, (mp_map_t*)&mp_const_empty_map); + rf->file = mp_vfs_open(1, &arg, (mp_map_t *)&mp_const_empty_map); int errcode; rf->len = mp_stream_rw(rf->file, rf->buf, sizeof(rf->buf), &errcode, MP_STREAM_RW_READ | MP_STREAM_RW_ONCE); if (errcode != 0) { diff --git a/extmod/virtpin.c b/extmod/virtpin.c index dbfa21d669..71a11232d4 100644 --- a/extmod/virtpin.c +++ b/extmod/virtpin.c @@ -27,13 +27,13 @@ #include "extmod/virtpin.h" int mp_virtual_pin_read(mp_obj_t pin) { - mp_obj_base_t* s = (mp_obj_base_t*)MP_OBJ_TO_PTR(pin); - mp_pin_p_t *pin_p = (mp_pin_p_t*)s->type->protocol; + mp_obj_base_t *s = (mp_obj_base_t *)MP_OBJ_TO_PTR(pin); + mp_pin_p_t *pin_p = (mp_pin_p_t *)s->type->protocol; return pin_p->ioctl(pin, MP_PIN_READ, 0, NULL); } void mp_virtual_pin_write(mp_obj_t pin, int value) { - mp_obj_base_t* s = (mp_obj_base_t*)MP_OBJ_TO_PTR(pin); - mp_pin_p_t *pin_p = (mp_pin_p_t*)s->type->protocol; + mp_obj_base_t *s = (mp_obj_base_t *)MP_OBJ_TO_PTR(pin); + mp_pin_p_t *pin_p = (mp_pin_p_t *)s->type->protocol; pin_p->ioctl(pin, MP_PIN_WRITE, value, NULL); } diff --git a/lib/netutils/netutils.c b/lib/netutils/netutils.c index 073f46b199..917cd83310 100644 --- a/lib/netutils/netutils.c +++ b/lib/netutils/netutils.c @@ -64,7 +64,7 @@ void netutils_parse_ipv4_addr(mp_obj_t addr_in, uint8_t *out_ip, netutils_endian } const char *s = addr_str; const char *s_top = addr_str + addr_len; - for (mp_uint_t i = 3 ; ; i--) { + for (mp_uint_t i = 3; ; i--) { mp_uint_t val = 0; for (; s < s_top && *s != '.'; s++) { val = val * 10 + *s - '0'; diff --git a/lib/timeutils/timeutils.c b/lib/timeutils/timeutils.c index eb3dc80d4b..fc8b5e7fc8 100644 --- a/lib/timeutils/timeutils.c +++ b/lib/timeutils/timeutils.c @@ -36,11 +36,11 @@ #define LEAPOCH ((31 + 29) * 86400) -#define DAYS_PER_400Y (365*400 + 97) -#define DAYS_PER_100Y (365*100 + 24) -#define DAYS_PER_4Y (365*4 + 1) +#define DAYS_PER_400Y (365 * 400 + 97) +#define DAYS_PER_100Y (365 * 100 + 24) +#define DAYS_PER_4Y (365 * 4 + 1) -STATIC const uint16_t days_since_jan1[]= { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 }; +STATIC const uint16_t days_since_jan1[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 }; bool timeutils_is_leap_year(mp_uint_t year) { return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0; diff --git a/lib/timeutils/timeutils.h b/lib/timeutils/timeutils.h index 9b1abeb8f3..cb7a72123a 100644 --- a/lib/timeutils/timeutils.h +++ b/lib/timeutils/timeutils.h @@ -28,14 +28,14 @@ #define MICROPY_INCLUDED_LIB_TIMEUTILS_TIMEUTILS_H typedef struct _timeutils_struct_time_t { - uint16_t tm_year; // i.e. 2014 - uint8_t tm_mon; // 1..12 - uint8_t tm_mday; // 1..31 - uint8_t tm_hour; // 0..23 - uint8_t tm_min; // 0..59 - uint8_t tm_sec; // 0..59 - uint8_t tm_wday; // 0..6 0 = Monday - uint16_t tm_yday; // 1..366 + uint16_t tm_year; // i.e. 2014 + uint8_t tm_mon; // 1..12 + uint8_t tm_mday; // 1..31 + uint8_t tm_hour; // 0..23 + uint8_t tm_min; // 0..59 + uint8_t tm_sec; // 0..59 + uint8_t tm_wday; // 0..6 0 = Monday + uint16_t tm_yday; // 1..366 } timeutils_struct_time_t; bool timeutils_is_leap_year(mp_uint_t year); diff --git a/lib/utils/mpirq.c b/lib/utils/mpirq.c index d54c15482f..dd0c220059 100644 --- a/lib/utils/mpirq.c +++ b/lib/utils/mpirq.c @@ -52,7 +52,7 @@ const mp_arg_t mp_irq_init_args[] = { mp_irq_obj_t *mp_irq_new(const mp_irq_methods_t *methods, mp_obj_t parent) { mp_irq_obj_t *self = m_new0(mp_irq_obj_t, 1); self->base.type = &mp_irq_type; - self->methods = (mp_irq_methods_t*)methods; + self->methods = (mp_irq_methods_t *)methods; self->parent = parent; self->handler = mp_const_none; self->ishard = false; @@ -120,5 +120,5 @@ const mp_obj_type_t mp_irq_type = { { &mp_type_type }, .name = MP_QSTR_irq, .call = mp_irq_call, - .locals_dict = (mp_obj_dict_t*)&mp_irq_locals_dict, + .locals_dict = (mp_obj_dict_t *)&mp_irq_locals_dict, }; diff --git a/lib/utils/printf.c b/lib/utils/printf.c index 1ceeea39ff..d67189e937 100644 --- a/lib/utils/printf.c +++ b/lib/utils/printf.c @@ -102,7 +102,7 @@ STATIC void strn_print_strn(void *data, const char *str, size_t len) { #if defined(__GNUC__) && !defined(__clang__) // uClibc requires this alias to be defined, or there may be link errors // when linkings against it statically. -int __GI_vsnprintf(char *str, size_t size, const char *fmt, va_list ap) __attribute__((weak, alias ("vsnprintf"))); +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) { @@ -128,4 +128,4 @@ int snprintf(char *str, size_t size, const char *fmt, ...) { return ret; } -#endif //MICROPY_USE_INTERNAL_PRINTF +#endif // MICROPY_USE_INTERNAL_PRINTF diff --git a/lib/utils/pyexec.c b/lib/utils/pyexec.c index d8dc60bfe5..a0ae556a72 100644 --- a/lib/utils/pyexec.c +++ b/lib/utils/pyexec.c @@ -84,7 +84,7 @@ STATIC int parse_compile_execute(const void *source, mp_parse_input_kind_t input } else if (exec_flags & EXEC_FLAG_SOURCE_IS_FILENAME) { lex = mp_lexer_new_from_file(source); } else { - lex = (mp_lexer_t*)source; + lex = (mp_lexer_t *)source; } // source is a lexer, parse and compile the script qstr source_name = lex->source_name; @@ -114,7 +114,7 @@ STATIC int parse_compile_execute(const void *source, mp_parse_input_kind_t input mp_hal_stdout_tx_strn("\x04", 1); } // check for SystemExit - if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(((mp_obj_base_t*)nlr.ret_val)->type), MP_OBJ_FROM_PTR(&mp_type_SystemExit))) { + if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(((mp_obj_base_t *)nlr.ret_val)->type), MP_OBJ_FROM_PTR(&mp_type_SystemExit))) { // at the moment, the value of SystemExit is unused ret = pyexec_system_exit; } else { @@ -132,8 +132,8 @@ STATIC int parse_compile_execute(const void *source, mp_parse_input_kind_t input size_t n_pool, n_qstr, n_str_data_bytes, n_total_bytes; qstr_pool_info(&n_pool, &n_qstr, &n_str_data_bytes, &n_total_bytes); printf("qstr:\n n_pool=%u\n n_qstr=%u\n " - "n_str_data_bytes=%u\n n_total_bytes=%u\n", - (unsigned)n_pool, (unsigned)n_qstr, (unsigned)n_str_data_bytes, (unsigned)n_total_bytes); + "n_str_data_bytes=%u\n n_total_bytes=%u\n", + (unsigned)n_pool, (unsigned)n_qstr, (unsigned)n_str_data_bytes, (unsigned)n_total_bytes); } #if MICROPY_ENABLE_GC @@ -158,7 +158,7 @@ typedef struct _repl_t { // but it was moved to MP_STATE_VM(repl_line) as containing // root pointer. Still keep structure in case more state // will be added later. - //vstr_t line; + // vstr_t line; bool cont_line; } repl_t; @@ -271,10 +271,10 @@ STATIC int pyexec_friendly_repl_process_char(int c) { } else { if (ret == CHAR_CTRL_C) { - // cancel everything - mp_hal_stdout_tx_str("\r\n"); - repl.cont_line = false; - goto input_restart; + // cancel everything + mp_hal_stdout_tx_str("\r\n"); + repl.cont_line = false; + goto input_restart; } else if (ret == CHAR_CTRL_D) { // stop entering compound statement goto exec; @@ -290,13 +290,13 @@ STATIC int pyexec_friendly_repl_process_char(int c) { return 0; } -exec: ; + exec:; int ret = parse_compile_execute(MP_STATE_VM(repl_line), MP_PARSE_SINGLE_INPUT, EXEC_FLAG_ALLOW_DEBUGGING | EXEC_FLAG_IS_REPL | EXEC_FLAG_SOURCE_IS_VSTR); if (ret & PYEXEC_FORCED_EXIT) { return ret; } -input_restart: + input_restart: vstr_reset(MP_STATE_VM(repl_line)); repl.cont_line = false; readline_init(MP_STATE_VM(repl_line), ">>> "); @@ -373,11 +373,11 @@ int pyexec_friendly_repl(void) { vstr_t line; vstr_init(&line, 32); -#if defined(USE_HOST_MODE) && MICROPY_HW_HAS_LCD + #if defined(USE_HOST_MODE) && MICROPY_HW_HAS_LCD // in host mode, we enable the LCD for the repl mp_obj_t lcd_o = mp_call_function_0(mp_load_name(qstr_from_str("LCD"))); mp_call_function_1(mp_load_attr(lcd_o, qstr_from_str("light")), mp_const_true); -#endif + #endif friendly_repl_reset: mp_hal_stdout_tx_str("MicroPython " MICROPY_GIT_TAG " on " MICROPY_BUILD_DATE "; " MICROPY_HW_BOARD_NAME " with " MICROPY_HW_MCU_NAME "\r\n"); diff --git a/lib/utils/sys_stdio_mphal.c b/lib/utils/sys_stdio_mphal.c index 234db0829b..0b92ec3e38 100644 --- a/lib/utils/sys_stdio_mphal.c +++ b/lib/utils/sys_stdio_mphal.c @@ -65,7 +65,7 @@ STATIC mp_uint_t stdio_read(mp_obj_t self_in, void *buf, mp_uint_t size, int *er if (c == '\r') { c = '\n'; } - ((byte*)buf)[i] = c; + ((byte *)buf)[i] = c; } return size; } else { @@ -93,9 +93,9 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(stdio_obj___exit___obj, 4, 4, stdio_o // TODO gc hook to close the file if not already closed STATIC const mp_rom_map_elem_t stdio_locals_dict_table[] = { -#if MICROPY_PY_SYS_STDIO_BUFFER + #if MICROPY_PY_SYS_STDIO_BUFFER { MP_ROM_QSTR(MP_QSTR_buffer), MP_ROM_PTR(&stdio_buffer_obj) }, -#endif + #endif { 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)}, @@ -123,7 +123,7 @@ STATIC const mp_obj_type_t stdio_obj_type = { .getiter = mp_identity_getiter, .iternext = mp_stream_unbuffered_iter, .protocol = &stdio_obj_stream_p, - .locals_dict = (mp_obj_dict_t*)&stdio_locals_dict, + .locals_dict = (mp_obj_dict_t *)&stdio_locals_dict, }; const sys_stdio_obj_t mp_sys_stdin_obj = {{&stdio_obj_type}, .fd = STDIO_FD_IN}; @@ -133,7 +133,7 @@ const sys_stdio_obj_t mp_sys_stderr_obj = {{&stdio_obj_type}, .fd = STDIO_FD_ERR #if MICROPY_PY_SYS_STDIO_BUFFER STATIC mp_uint_t stdio_buffer_read(mp_obj_t self_in, void *buf, mp_uint_t size, int *errcode) { for (uint i = 0; i < size; i++) { - ((byte*)buf)[i] = mp_hal_stdin_rx_chr(); + ((byte *)buf)[i] = mp_hal_stdin_rx_chr(); } return size; } @@ -156,7 +156,7 @@ STATIC const mp_obj_type_t stdio_buffer_obj_type = { .getiter = mp_identity_getiter, .iternext = mp_stream_unbuffered_iter, .protocol = &stdio_buffer_obj_stream_p, - .locals_dict = (mp_obj_dict_t*)&stdio_locals_dict, + .locals_dict = (mp_obj_dict_t *)&stdio_locals_dict, }; STATIC const sys_stdio_obj_t stdio_buffer_obj = {{&stdio_buffer_obj_type}, .fd = 0}; // fd unused diff --git a/ports/bare-arm/main.c b/ports/bare-arm/main.c index b96fb47ace..6cbba0d752 100644 --- a/ports/bare-arm/main.c +++ b/ports/bare-arm/main.c @@ -44,11 +44,15 @@ mp_obj_t mp_builtin_open(size_t n_args, const mp_obj_t *args, mp_map_t *kwargs) MP_DEFINE_CONST_FUN_OBJ_KW(mp_builtin_open_obj, 1, mp_builtin_open); void nlr_jump_fail(void *val) { - while (1); + while (1) { + ; + } } void NORETURN __fatal_error(const char *msg) { - while (1); + while (1) { + ; + } } #ifndef NDEBUG @@ -71,26 +75,63 @@ int _fstat() {return 0;} int _isatty() {return 0;} */ -void *malloc(size_t n) {return NULL;} -void *calloc(size_t nmemb, size_t size) {return NULL;} -void *realloc(void *ptr, size_t size) {return NULL;} -void free(void *p) {} -int printf(const char *m, ...) {return 0;} -void *memcpy(void *dest, const void *src, size_t n) {return NULL;} -int memcmp(const void *s1, const void *s2, size_t n) {return 0;} -void *memmove(void *dest, const void *src, size_t n) {return NULL;} -void *memset(void *s, int c, size_t n) {return NULL;} -int strcmp(const char *s1, const char* s2) {return 0;} -int strncmp(const char *s1, const char* s2, size_t n) {return 0;} -size_t strlen(const char *s) {return 0;} -char *strcat(char *dest, const char *src) {return NULL;} -char *strchr(const char *dest, int c) {return NULL;} +void *malloc(size_t n) { + return NULL; +} +void *calloc(size_t nmemb, size_t size) { + return NULL; +} +void *realloc(void *ptr, size_t size) { + return NULL; +} +void free(void *p) { +} +int printf(const char *m, ...) { + return 0; +} +void *memcpy(void *dest, const void *src, size_t n) { + return NULL; +} +int memcmp(const void *s1, const void *s2, size_t n) { + return 0; +} +void *memmove(void *dest, const void *src, size_t n) { + return NULL; +} +void *memset(void *s, int c, size_t n) { + return NULL; +} +int strcmp(const char *s1, const char *s2) { + return 0; +} +int strncmp(const char *s1, const char *s2, size_t n) { + return 0; +} +size_t strlen(const char *s) { + return 0; +} +char *strcat(char *dest, const char *src) { + return NULL; +} +char *strchr(const char *dest, int c) { + return NULL; +} #include -int vprintf(const char *format, va_list ap) {return 0;} -int vsnprintf(char *str, size_t size, const char *format, va_list ap) {return 0;} +int vprintf(const char *format, va_list ap) { + return 0; +} +int vsnprintf(char *str, size_t size, const char *format, va_list ap) { + return 0; +} #undef putchar -int putchar(int c) {return 0;} -int puts(const char *s) {return 0;} +int putchar(int c) { + return 0; +} +int puts(const char *s) { + return 0; +} -void _start(void) {main(0, NULL);} +void _start(void) { + main(0, NULL); +} diff --git a/ports/bare-arm/mpconfigport.h b/ports/bare-arm/mpconfigport.h index 395659a8bd..273e21451b 100644 --- a/ports/bare-arm/mpconfigport.h +++ b/ports/bare-arm/mpconfigport.h @@ -49,7 +49,7 @@ // type definitions for the specific machine -#define MICROPY_MAKE_POINTER_CALLABLE(p) ((void*)((mp_uint_t)(p) | 1)) +#define MICROPY_MAKE_POINTER_CALLABLE(p) ((void *)((mp_uint_t)(p) | 1)) #define UINT_FMT "%lu" #define INT_FMT "%ld" diff --git a/ports/cc3200/fatfs_port.c b/ports/cc3200/fatfs_port.c index 658c94e886..a991aa8c46 100644 --- a/ports/cc3200/fatfs_port.c +++ b/ports/cc3200/fatfs_port.c @@ -68,7 +68,7 @@ DWORD get_fattime(void) { timeutils_struct_time_t tm; timeutils_seconds_since_2000_to_struct_time(pyb_rtc_get_seconds(), &tm); - return ((tm.tm_year - 1980) << 25) | ((tm.tm_mon) << 21) | - ((tm.tm_mday) << 16) | ((tm.tm_hour) << 11) | - ((tm.tm_min) << 5) | (tm.tm_sec >> 1); + return ((tm.tm_year - 1980) << 25) | ((tm.tm_mon) << 21) | + ((tm.tm_mday) << 16) | ((tm.tm_hour) << 11) | + ((tm.tm_min) << 5) | (tm.tm_sec >> 1); } diff --git a/ports/cc3200/main.c b/ports/cc3200/main.c index e2299e1460..bdd73e7bf9 100644 --- a/ports/cc3200/main.c +++ b/ports/cc3200/main.c @@ -51,57 +51,58 @@ ******************************************************************************/ // This is the static memory (TCB and stack) for the idle task -static StaticTask_t xIdleTaskTCB __attribute__ ((section (".rtos_heap"))); -static StackType_t uxIdleTaskStack[configMINIMAL_STACK_SIZE] __attribute__ ((section (".rtos_heap"))) __attribute__((aligned (8))); +static StaticTask_t xIdleTaskTCB __attribute__ ((section(".rtos_heap"))); +static StackType_t uxIdleTaskStack[configMINIMAL_STACK_SIZE] __attribute__ ((section(".rtos_heap"))) __attribute__((aligned(8))); /****************************************************************************** DECLARE PUBLIC DATA ******************************************************************************/ #ifdef DEBUG -OsiTaskHandle mpTaskHandle; +OsiTaskHandle mpTaskHandle; #endif // This is the FreeRTOS heap, defined here so we can put it in a special segment -uint8_t ucHeap[ configTOTAL_HEAP_SIZE ] __attribute__ ((section (".rtos_heap"))) __attribute__((aligned (8))); +uint8_t ucHeap[ configTOTAL_HEAP_SIZE ] __attribute__ ((section(".rtos_heap"))) __attribute__((aligned(8))); // This is the static memory (TCB and stack) for the main MicroPython task -StaticTask_t mpTaskTCB __attribute__ ((section (".rtos_heap"))); -StackType_t mpTaskStack[MICROPY_TASK_STACK_LEN] __attribute__ ((section (".rtos_heap"))) __attribute__((aligned (8))); +StaticTask_t mpTaskTCB __attribute__ ((section(".rtos_heap"))); +StackType_t mpTaskStack[MICROPY_TASK_STACK_LEN] __attribute__ ((section(".rtos_heap"))) __attribute__((aligned(8))); /****************************************************************************** DEFINE PUBLIC FUNCTIONS ******************************************************************************/ -__attribute__ ((section (".boot"))) -int main (void) { +__attribute__ ((section(".boot"))) +int main(void) { // Initialize the clocks and the interrupt system HAL_SystemInit(); -#if MICROPY_HW_ANTENNA_DIVERSITY + #if MICROPY_HW_ANTENNA_DIVERSITY // configure the antenna selection pins antenna_init0(); -#endif + #endif // Init the watchdog pybwdt_init0(); -#ifndef DEBUG + #ifndef DEBUG OsiTaskHandle mpTaskHandle; -#endif + #endif mpTaskHandle = xTaskCreateStatic(TASK_MicroPython, "MicroPy", MICROPY_TASK_STACK_LEN, NULL, MICROPY_TASK_PRIORITY, mpTaskStack, &mpTaskTCB); ASSERT(mpTaskHandle != NULL); osi_start(); - for ( ; ; ); + for ( ; ;) {; + } } // We need this when configSUPPORT_STATIC_ALLOCATION is enabled -void vApplicationGetIdleTaskMemory( StaticTask_t **ppxIdleTaskTCBBuffer, - StackType_t **ppxIdleTaskStackBuffer, - uint32_t *pulIdleTaskStackSize ) { +void vApplicationGetIdleTaskMemory(StaticTask_t **ppxIdleTaskTCBBuffer, + StackType_t **ppxIdleTaskStackBuffer, + uint32_t *pulIdleTaskStackSize) { *ppxIdleTaskTCBBuffer = &xIdleTaskTCB; *ppxIdleTaskStackBuffer = uxIdleTaskStack; *pulIdleTaskStackSize = configMINIMAL_STACK_SIZE; diff --git a/ports/cc3200/mpconfigport.h b/ports/cc3200/mpconfigport.h index b1c68a2dc3..3c539e9922 100644 --- a/ports/cc3200/mpconfigport.h +++ b/ports/cc3200/mpconfigport.h @@ -199,15 +199,15 @@ extern const struct _mp_obj_module_t mp_module_ussl; // type definitions for the specific machine -#define MICROPY_MAKE_POINTER_CALLABLE(p) ((void*)((mp_uint_t)(p) | 1)) +#define MICROPY_MAKE_POINTER_CALLABLE(p) ((void *)((mp_uint_t)(p) | 1)) #define MP_SSIZE_MAX (0x7FFFFFFF) #define UINT_FMT "%u" #define INT_FMT "%d" -typedef int32_t mp_int_t; // must be pointer size -typedef unsigned int mp_uint_t; // must be pointer size -typedef long mp_off_t; +typedef int32_t mp_int_t; // must be pointer size +typedef unsigned int mp_uint_t; // must be pointer size +typedef long mp_off_t; #define MP_PLAT_PRINT_STRN(str, len) mp_hal_stdout_tx_strn_cooked(str, len) diff --git a/ports/cc3200/mptask.c b/ports/cc3200/mptask.c index 6143f72a7a..fdea6e6df1 100644 --- a/ports/cc3200/mptask.c +++ b/ports/cc3200/mptask.c @@ -81,16 +81,16 @@ /****************************************************************************** DECLARE PRIVATE FUNCTIONS ******************************************************************************/ -STATIC void mptask_pre_init (void); -STATIC void mptask_init_sflash_filesystem (void); -STATIC void mptask_enter_ap_mode (void); -STATIC void mptask_create_main_py (void); +STATIC void mptask_pre_init(void); +STATIC void mptask_init_sflash_filesystem(void); +STATIC void mptask_enter_ap_mode(void); +STATIC void mptask_create_main_py(void); /****************************************************************************** DECLARE PUBLIC DATA ******************************************************************************/ #ifdef DEBUG -OsiTaskHandle svTaskHandle; +OsiTaskHandle svTaskHandle; #endif /****************************************************************************** @@ -100,27 +100,27 @@ static fs_user_mount_t *sflash_vfs_fat; static const char fresh_main_py[] = "# main.py -- put your code here!\r\n"; static const char fresh_boot_py[] = "# boot.py -- run on boot-up\r\n" - "# can run arbitrary Python, but best to keep it minimal\r\n" + "# can run arbitrary Python, but best to keep it minimal\r\n" #if MICROPY_STDIO_UART - "import os, machine\r\n" - "os.dupterm(machine.UART(0, " MP_STRINGIFY(MICROPY_STDIO_UART_BAUD) "))\r\n" + "import os, machine\r\n" + "os.dupterm(machine.UART(0, " MP_STRINGIFY(MICROPY_STDIO_UART_BAUD) "))\r\n" #endif - ; +; /****************************************************************************** DECLARE PUBLIC FUNCTIONS ******************************************************************************/ -void TASK_MicroPython (void *pvParameters) { +void TASK_MicroPython(void *pvParameters) { // get the top of the stack to initialize the garbage collector uint32_t sp = gc_helper_get_sp(); bool safeboot = false; mptask_pre_init(); -#ifndef DEBUG + #ifndef DEBUG safeboot = PRCMGetSpecialBit(PRCM_SAFE_BOOT_BIT); -#endif + #endif soft_reset: @@ -130,7 +130,7 @@ soft_reset: #endif // initialise the stack pointer for the main thread (must be done after mp_thread_init) - mp_stack_set_top((void*)sp); + mp_stack_set_top((void *)sp); // GC init gc_init(&_boot, &_eheap); @@ -158,8 +158,7 @@ soft_reset: // when waking up from hibernate we just want // to enable simplelink and leave it as is wlan_first_start(); - } - else { + } else { // only if not comming out of hibernate or a soft reset mptask_enter_ap_mode(); } @@ -218,7 +217,7 @@ soft_reset: // main script is finished, so now go into REPL mode. // the REPL mode can change, or it can request a soft reset. - for ( ; ; ) { + for ( ; ;) { if (pyexec_mode_kind == PYEXEC_MODE_RAW_REPL) { if (pyexec_raw_repl() != 0) { break; @@ -261,16 +260,16 @@ soft_reset_exit: /****************************************************************************** DEFINE PRIVATE FUNCTIONS ******************************************************************************/ -__attribute__ ((section (".boot"))) -STATIC void mptask_pre_init (void) { +__attribute__ ((section(".boot"))) +STATIC void mptask_pre_init(void) { // this one only makes sense after a poweron reset pyb_rtc_pre_init(); // Create the simple link spawn task - ASSERT (OSI_OK == VStartSimpleLinkSpawnTask(SIMPLELINK_SPAWN_TASK_PRIORITY)); + ASSERT(OSI_OK == VStartSimpleLinkSpawnTask(SIMPLELINK_SPAWN_TASK_PRIORITY)); // Allocate memory for the flash file system - ASSERT ((sflash_vfs_fat = mem_Malloc(sizeof(*sflash_vfs_fat))) != NULL); + ASSERT((sflash_vfs_fat = mem_Malloc(sizeof(*sflash_vfs_fat))) != NULL); // this one allocates memory for the nvic vault pyb_sleep_pre_init(); @@ -284,17 +283,17 @@ STATIC void mptask_pre_init (void) { // this one allocates memory for the socket semaphore modusocket_pre_init(); - //CRYPTOHASH_Init(); + // CRYPTOHASH_Init(); -#ifndef DEBUG + #ifndef DEBUG OsiTaskHandle svTaskHandle; -#endif + #endif svTaskHandle = xTaskCreateStatic(TASK_Servers, "Servers", SERVERS_STACK_LEN, NULL, SERVERS_PRIORITY, svTaskStack, &svTaskTCB); ASSERT(svTaskHandle != NULL); } -STATIC void mptask_init_sflash_filesystem (void) { +STATIC void mptask_init_sflash_filesystem(void) { FILINFO fno; // Initialise the local flash filesystem. @@ -377,16 +376,16 @@ STATIC void mptask_init_sflash_filesystem (void) { } } -STATIC void mptask_enter_ap_mode (void) { +STATIC void mptask_enter_ap_mode(void) { // append the mac only if it's not the first boot bool add_mac = !PRCMGetSpecialBit(PRCM_FIRST_BOOT_BIT); // enable simplelink in ap mode (use the MAC address to make the ssid unique) - wlan_sl_init (ROLE_AP, MICROPY_PORT_WLAN_AP_SSID, strlen(MICROPY_PORT_WLAN_AP_SSID), - MICROPY_PORT_WLAN_AP_SECURITY, MICROPY_PORT_WLAN_AP_KEY, strlen(MICROPY_PORT_WLAN_AP_KEY), - MICROPY_PORT_WLAN_AP_CHANNEL, ANTENNA_TYPE_INTERNAL, add_mac); + wlan_sl_init(ROLE_AP, MICROPY_PORT_WLAN_AP_SSID, strlen(MICROPY_PORT_WLAN_AP_SSID), + MICROPY_PORT_WLAN_AP_SECURITY, MICROPY_PORT_WLAN_AP_KEY, strlen(MICROPY_PORT_WLAN_AP_KEY), + MICROPY_PORT_WLAN_AP_CHANNEL, ANTENNA_TYPE_INTERNAL, add_mac); } -STATIC void mptask_create_main_py (void) { +STATIC void mptask_create_main_py(void) { // create empty main.py FIL fp; f_open(&sflash_vfs_fat->fatfs, &fp, "/main.py", FA_WRITE | FA_CREATE_ALWAYS); diff --git a/ports/cc3200/mptask.h b/ports/cc3200/mptask.h index a1c3eb2cbf..2c9d6c4cf2 100644 --- a/ports/cc3200/mptask.h +++ b/ports/cc3200/mptask.h @@ -41,6 +41,6 @@ extern StackType_t mpTaskStack[]; /****************************************************************************** DECLARE PUBLIC FUNCTIONS ******************************************************************************/ -extern void TASK_MicroPython (void *pvParameters); +extern void TASK_MicroPython(void *pvParameters); #endif // MICROPY_INCLUDED_CC3200_MPTASK_H diff --git a/ports/cc3200/mpthreadport.c b/ports/cc3200/mpthreadport.c index 9dbc518e06..62c4e076ae 100644 --- a/ports/cc3200/mpthreadport.c +++ b/ports/cc3200/mpthreadport.c @@ -68,7 +68,7 @@ void mp_thread_init(void) { void mp_thread_gc_others(void) { mp_thread_mutex_lock(&thread_mutex, 1); for (thread_t *th = thread; th != NULL; th = th->next) { - gc_collect_root((void**)&th, 1); + gc_collect_root((void **)&th, 1); gc_collect_root(&th->arg, 1); // probably not needed if (th->id == xTaskGetCurrentTaskHandle()) { continue; @@ -100,7 +100,7 @@ void mp_thread_start(void) { mp_thread_mutex_unlock(&thread_mutex); } -STATIC void *(*ext_thread_entry)(void*) = NULL; +STATIC void *(*ext_thread_entry)(void *) = NULL; STATIC void freertos_entry(void *arg) { if (ext_thread_entry) { @@ -111,7 +111,7 @@ STATIC void freertos_entry(void *arg) { } } -void mp_thread_create(void *(*entry)(void*), void *arg, size_t *stack_size) { +void mp_thread_create(void *(*entry)(void *), void *arg, size_t *stack_size) { // store thread entry function into a global variable so we can access it ext_thread_entry = entry; @@ -129,7 +129,7 @@ void mp_thread_create(void *(*entry)(void*), void *arg, size_t *stack_size) { mp_thread_mutex_lock(&thread_mutex, 1); // create thread - TaskHandle_t id = xTaskCreateStatic(freertos_entry, "Thread", *stack_size / sizeof(void*), arg, 2, stack, tcb); + TaskHandle_t id = xTaskCreateStatic(freertos_entry, "Thread", *stack_size / sizeof(void *), arg, 2, stack, tcb); if (id == NULL) { mp_thread_mutex_unlock(&thread_mutex); mp_raise_msg(&mp_type_OSError, "can't create thread"); diff --git a/ports/cc3200/qstrdefsport.h b/ports/cc3200/qstrdefsport.h index d5f22d70a8..36f8c07ec0 100644 --- a/ports/cc3200/qstrdefsport.h +++ b/ports/cc3200/qstrdefsport.h @@ -28,5 +28,5 @@ // for machine module Q(/) // entries for sys.path -Q(/flash) -Q(/flash/lib) +Q(/ flash) +Q(/ flash / lib) diff --git a/ports/cc3200/serverstask.c b/ports/cc3200/serverstask.c index 100b8d33b0..06c8194c9d 100644 --- a/ports/cc3200/serverstask.c +++ b/ports/cc3200/serverstask.c @@ -69,8 +69,8 @@ static volatile bool sleep_sockets = false; ******************************************************************************/ // This is the static memory (TCB and stack) for the servers task -StaticTask_t svTaskTCB __attribute__ ((section (".rtos_heap"))); -StackType_t svTaskStack[SERVERS_STACK_LEN] __attribute__ ((section (".rtos_heap"))) __attribute__((aligned (8))); +StaticTask_t svTaskTCB __attribute__ ((section(".rtos_heap"))); +StackType_t svTaskStack[SERVERS_STACK_LEN] __attribute__ ((section(".rtos_heap"))) __attribute__((aligned(8))); char servers_user[SERVERS_USER_PASS_LEN_MAX + 1]; char servers_pass[SERVERS_USER_PASS_LEN_MAX + 1]; @@ -78,17 +78,17 @@ char servers_pass[SERVERS_USER_PASS_LEN_MAX + 1]; /****************************************************************************** DECLARE PUBLIC FUNCTIONS ******************************************************************************/ -void TASK_Servers (void *pvParameters) { +void TASK_Servers(void *pvParameters) { bool cycle = false; - strcpy (servers_user, SERVERS_DEF_USER); - strcpy (servers_pass, SERVERS_DEF_PASS); + strcpy(servers_user, SERVERS_DEF_USER); + strcpy(servers_pass, SERVERS_DEF_PASS); telnet_init(); ftp_init(); - for ( ;; ) { + for ( ;;) { if (servers_data.do_enable) { // enable network services @@ -97,16 +97,14 @@ void TASK_Servers (void *pvParameters) { // now set/clear the flags servers_data.enabled = true; servers_data.do_enable = false; - } - else if (servers_data.do_disable) { + } else if (servers_data.do_disable) { // disable network services telnet_disable(); ftp_disable(); // now clear the flags servers_data.do_disable = false; servers_data.enabled = false; - } - else if (servers_data.do_reset) { + } else if (servers_data.do_reset) { // resetting the servers is needed to prevent half-open sockets servers_data.do_reset = false; if (servers_data.enabled) { @@ -120,8 +118,7 @@ void TASK_Servers (void *pvParameters) { if (cycle) { telnet_run(); - } - else { + } else { ftp_run(); } @@ -147,12 +144,12 @@ void TASK_Servers (void *pvParameters) { } } -void servers_start (void) { +void servers_start(void) { servers_data.do_enable = true; mp_hal_delay_ms(SERVERS_CYCLE_TIME_MS * 3); } -void servers_stop (void) { +void servers_stop(void) { servers_data.do_disable = true; do { mp_hal_delay_ms(SERVERS_CYCLE_TIME_MS); @@ -160,24 +157,24 @@ void servers_stop (void) { mp_hal_delay_ms(SERVERS_CYCLE_TIME_MS * 3); } -void servers_reset (void) { +void servers_reset(void) { servers_data.do_reset = true; } -void servers_wlan_cycle_power (void) { +void servers_wlan_cycle_power(void) { servers_data.do_wlan_cycle_power = true; } -bool servers_are_enabled (void) { +bool servers_are_enabled(void) { return servers_data.enabled; } -void server_sleep_sockets (void) { +void server_sleep_sockets(void) { sleep_sockets = true; mp_hal_delay_ms(SERVERS_CYCLE_TIME_MS + 1); } -void servers_close_socket (int16_t *sd) { +void servers_close_socket(int16_t *sd) { if (*sd > 0) { modusocket_socket_delete(*sd); sl_Close(*sd); @@ -185,7 +182,7 @@ void servers_close_socket (int16_t *sd) { } } -void servers_set_login (char *user, char *pass) { +void servers_set_login(char *user, char *pass) { if (strlen(user) > SERVERS_USER_PASS_LEN_MAX || strlen(pass) > SERVERS_USER_PASS_LEN_MAX) { mp_raise_ValueError(mpexception_value_invalid_arguments); } @@ -193,7 +190,7 @@ void servers_set_login (char *user, char *pass) { memcpy(servers_pass, pass, SERVERS_USER_PASS_LEN_MAX); } -void servers_set_timeout (uint32_t timeout) { +void servers_set_timeout(uint32_t timeout) { if (timeout < SERVERS_MIN_TIMEOUT_MS) { // timeout is too low mp_raise_ValueError(mpexception_value_invalid_arguments); @@ -201,7 +198,7 @@ void servers_set_timeout (uint32_t timeout) { servers_data.timeout = timeout; } -uint32_t servers_get_timeout (void) { +uint32_t servers_get_timeout(void) { return servers_data.timeout; } diff --git a/ports/cc3200/serverstask.h b/ports/cc3200/serverstask.h index c4533d7174..612899d7f1 100644 --- a/ports/cc3200/serverstask.h +++ b/ports/cc3200/serverstask.h @@ -60,16 +60,16 @@ extern char servers_pass[]; /****************************************************************************** DECLARE PUBLIC FUNCTIONS ******************************************************************************/ -extern void TASK_Servers (void *pvParameters); -extern void servers_start (void); -extern void servers_stop (void); -extern void servers_reset (void); -extern void servers_wlan_cycle_power (void); -extern bool servers_are_enabled (void); -extern void servers_close_socket (int16_t *sd); -extern void servers_set_login (char *user, char *pass); -extern void server_sleep_sockets (void); -extern void servers_set_timeout (uint32_t timeout); -extern uint32_t servers_get_timeout (void); +extern void TASK_Servers(void *pvParameters); +extern void servers_start(void); +extern void servers_stop(void); +extern void servers_reset(void); +extern void servers_wlan_cycle_power(void); +extern bool servers_are_enabled(void); +extern void servers_close_socket(int16_t *sd); +extern void servers_set_login(char *user, char *pass); +extern void server_sleep_sockets(void); +extern void servers_set_timeout(uint32_t timeout); +extern uint32_t servers_get_timeout(void); #endif // MICROPY_INCLUDED_CC3200_SERVERSTASK_H diff --git a/ports/cc3200/tools/smoke.py b/ports/cc3200/tools/smoke.py index 3ade11cf87..4ccc700c6c 100644 --- a/ports/cc3200/tools/smoke.py +++ b/ports/cc3200/tools/smoke.py @@ -12,55 +12,58 @@ python3 run-tests --target wipy --device 192.168.1.1 ../cc3200/tools/smoke.py pin_map = [23, 24, 11, 12, 13, 14, 15, 16, 17, 22, 28, 10, 9, 8, 7, 6, 30, 31, 3, 0, 4, 5] test_bytes = os.urandom(1024) -def test_pin_read (pull): + +def test_pin_read(pull): # enable the pull resistor on all pins, then read the value for p in pin_map: - pin = Pin('GP' + str(p), mode=Pin.IN, pull=pull) + pin = Pin("GP" + str(p), mode=Pin.IN, pull=pull) # read the pin value print(pin()) -def test_pin_shorts (pull): + +def test_pin_shorts(pull): if pull == Pin.PULL_UP: pull_inverted = Pin.PULL_DOWN else: pull_inverted = Pin.PULL_UP # enable all pulls of the specified type for p in pin_map: - pin = Pin('GP' + str(p), mode=Pin.IN, pull=pull_inverted) + pin = Pin("GP" + str(p), mode=Pin.IN, pull=pull_inverted) # then change the pull one pin at a time and read its value i = 0 while i < len(pin_map): - pin = Pin('GP' + str(pin_map[i]), mode=Pin.IN, pull=pull) - Pin('GP' + str(pin_map[i - 1]), mode=Pin.IN, pull=pull_inverted) + pin = Pin("GP" + str(pin_map[i]), mode=Pin.IN, pull=pull) + Pin("GP" + str(pin_map[i - 1]), mode=Pin.IN, pull=pull_inverted) i += 1 # read the pin value print(pin()) + test_pin_read(Pin.PULL_UP) test_pin_read(Pin.PULL_DOWN) test_pin_shorts(Pin.PULL_UP) test_pin_shorts(Pin.PULL_DOWN) # create a test directory -os.mkdir('/flash/test') -os.chdir('/flash/test') +os.mkdir("/flash/test") +os.chdir("/flash/test") print(os.getcwd()) # create a new file -f = open('test.txt', 'w') +f = open("test.txt", "w") n_w = f.write(test_bytes) print(n_w == len(test_bytes)) f.close() -f = open('test.txt', 'r') -r = bytes(f.read(), 'ascii') +f = open("test.txt", "r") +r = bytes(f.read(), "ascii") # check that we can write and read it correctly print(r == test_bytes) f.close() -os.remove('test.txt') -os.chdir('..') -os.rmdir('test') +os.remove("test.txt") +os.chdir("..") +os.rmdir("test") ls = os.listdir() -print('test' not in ls) +print("test" not in ls) print(ls) # test the real time clock @@ -72,5 +75,4 @@ time1 = rtc.now() time.sleep_ms(1000) time2 = rtc.now() print(time2[5] - time1[5] == 1) -print(time2[6] - time1[6] < 5000) # microseconds - +print(time2[6] - time1[6] < 5000) # microseconds diff --git a/ports/cc3200/tools/uniflash.py b/ports/cc3200/tools/uniflash.py index 21da46a56f..0ce9d0703a 100644 --- a/ports/cc3200/tools/uniflash.py +++ b/ports/cc3200/tools/uniflash.py @@ -19,7 +19,7 @@ import subprocess def print_exception(e): - print ('Exception: {}, on line {}'.format(e, sys.exc_info()[-1].tb_lineno)) + print("Exception: {}, on line {}".format(e, sys.exc_info()[-1].tb_lineno)) def execute(command): @@ -29,7 +29,7 @@ def execute(command): # Poll process for new output until finished while True: nextline = process.stdout.readline() - if nextline == '' and process.poll() != None: + if nextline == "" and process.poll() != None: break sys.stdout.write(nextline) sys.stdout.flush() @@ -43,25 +43,58 @@ def execute(command): else: raise ProcessException(command, exitCode, output) + def main(): - cmd_parser = argparse.ArgumentParser(description='Flash the WiPy and optionally run a small test on it.') - cmd_parser.add_argument('-u', '--uniflash', default=None, help='the path to the uniflash cli executable') - cmd_parser.add_argument('-c', '--config', default=None, help='the path to the uniflash config file') - cmd_parser.add_argument('-p', '--port', default=8, help='the com serial port') - cmd_parser.add_argument('-s', '--servicepack', default=None, help='the path to the servicepack file') + cmd_parser = argparse.ArgumentParser( + description="Flash the WiPy and optionally run a small test on it." + ) + cmd_parser.add_argument( + "-u", "--uniflash", default=None, help="the path to the uniflash cli executable" + ) + cmd_parser.add_argument( + "-c", "--config", default=None, help="the path to the uniflash config file" + ) + cmd_parser.add_argument("-p", "--port", default=8, help="the com serial port") + cmd_parser.add_argument( + "-s", "--servicepack", default=None, help="the path to the servicepack file" + ) args = cmd_parser.parse_args() output = "" - com_port = 'com=' + str(args.port) - servicepack_path = 'spPath=' + args.servicepack + com_port = "com=" + str(args.port) + servicepack_path = "spPath=" + args.servicepack try: if args.uniflash == None or args.config == None: - raise ValueError('uniflash path and config path are mandatory') + raise ValueError("uniflash path and config path are mandatory") if args.servicepack == None: - output += execute([args.uniflash, '-config', args.config, '-setOptions', com_port, '-operations', 'format', 'program']) + output += execute( + [ + args.uniflash, + "-config", + args.config, + "-setOptions", + com_port, + "-operations", + "format", + "program", + ] + ) else: - output += execute([args.uniflash, '-config', args.config, '-setOptions', com_port, servicepack_path, '-operations', 'format', 'servicePackUpdate', 'program']) + output += execute( + [ + args.uniflash, + "-config", + args.config, + "-setOptions", + com_port, + servicepack_path, + "-operations", + "format", + "servicePackUpdate", + "program", + ] + ) except Exception as e: print_exception(e) output = "" @@ -77,5 +110,6 @@ def main(): print("======================================") sys.exit(1) + if __name__ == "__main__": main() diff --git a/ports/cc3200/tools/update-wipy.py b/ports/cc3200/tools/update-wipy.py index 2d5fe57c2f..e0e1266f7a 100644 --- a/ports/cc3200/tools/update-wipy.py +++ b/ports/cc3200/tools/update-wipy.py @@ -23,12 +23,12 @@ from telnetlib import Telnet def print_exception(e): - print ('Exception: {}, on line {}'.format(e, sys.exc_info()[-1].tb_lineno)) + print("Exception: {}, on line {}".format(e, sys.exc_info()[-1].tb_lineno)) def ftp_directory_exists(ftpobj, directory_name): filelist = [] - ftpobj.retrlines('LIST',filelist.append) + ftpobj.retrlines("LIST", filelist.append) for f in filelist: if f.split()[-1] == directory_name: return True @@ -37,34 +37,34 @@ def ftp_directory_exists(ftpobj, directory_name): def transfer_file(args): with FTP(args.ip, timeout=20) as ftp: - print ('FTP connection established') + print("FTP connection established") - if '230' in ftp.login(args.user, args.password): - print ('Login successful') + if "230" in ftp.login(args.user, args.password): + print("Login successful") - if '250' in ftp.cwd('/flash'): - if not ftp_directory_exists(ftp, 'sys'): - print ('/flash/sys directory does not exist') - if not '550' in ftp.mkd('sys'): - print ('/flash/sys directory created') + if "250" in ftp.cwd("/flash"): + if not ftp_directory_exists(ftp, "sys"): + print("/flash/sys directory does not exist") + if not "550" in ftp.mkd("sys"): + print("/flash/sys directory created") else: - print ('Error: cannot create /flash/sys directory') + print("Error: cannot create /flash/sys directory") return False - if '250' in ftp.cwd('sys'): - print ("Entered '/flash/sys' directory") + if "250" in ftp.cwd("sys"): + print("Entered '/flash/sys' directory") with open(args.file, "rb") as fwfile: - print ('Firmware image found, initiating transfer...') - if '226' in ftp.storbinary("STOR " + 'mcuimg.bin', fwfile, 512): - print ('File transfer complete') + print("Firmware image found, initiating transfer...") + if "226" in ftp.storbinary("STOR " + "mcuimg.bin", fwfile, 512): + print("File transfer complete") return True else: - print ('Error: file transfer failed') + print("Error: file transfer failed") else: - print ('Error: cannot enter /flash/sys directory') + print("Error: cannot enter /flash/sys directory") else: - print ('Error: cannot enter /flash directory') + print("Error: cannot enter /flash directory") else: - print ('Error: ftp login failed') + print("Error: ftp login failed") return False @@ -76,20 +76,24 @@ def reset_board(args): tn = Telnet(args.ip, timeout=5) print("Connected via Telnet, trying to login now") - if b'Login as:' in tn.read_until(b"Login as:", timeout=5): - tn.write(bytes(args.user, 'ascii') + b"\r\n") + if b"Login as:" in tn.read_until(b"Login as:", timeout=5): + tn.write(bytes(args.user, "ascii") + b"\r\n") - if b'Password:' in tn.read_until(b"Password:", timeout=5): + if b"Password:" in tn.read_until(b"Password:", timeout=5): # needed because of internal implementation details of the WiPy's telnet server time.sleep(0.2) - tn.write(bytes(args.password, 'ascii') + b"\r\n") + tn.write(bytes(args.password, "ascii") + b"\r\n") - if b'Type "help()" for more information.' in tn.read_until(b'Type "help()" for more information.', timeout=5): + if b'Type "help()" for more information.' in tn.read_until( + b'Type "help()" for more information.', timeout=5 + ): print("Telnet login succeeded") - tn.write(b'\r\x03\x03') # ctrl-C twice: interrupt any running program + tn.write(b"\r\x03\x03") # ctrl-C twice: interrupt any running program time.sleep(1) - tn.write(b'\r\x02') # ctrl-B: enter friendly REPL - if b'Type "help()" for more information.' in tn.read_until(b'Type "help()" for more information.', timeout=5): + tn.write(b"\r\x02") # ctrl-B: enter friendly REPL + if b'Type "help()" for more information.' in tn.read_until( + b'Type "help()" for more information.', timeout=5 + ): tn.write(b"import machine\r\n") tn.write(b"machine.reset()\r\n") time.sleep(2) @@ -112,9 +116,9 @@ def reset_board(args): def verify_update(args): success = False - firmware_tag = '' + firmware_tag = "" - def find_tag (tag): + def find_tag(tag): if tag in firmware_tag: print("Verification passed") return True @@ -135,21 +139,26 @@ def verify_update(args): print("Timeout while connecting via telnet, retrying...") retries += 1 else: - print('Error: Telnet connection timed out!') + print("Error: Telnet connection timed out!") return False try: - firmware_tag = tn.read_until (b'with CC3200') - tag_file_path = args.file.rstrip('mcuimg.bin') + 'genhdr/mpversion.h' - + firmware_tag = tn.read_until(b"with CC3200") + tag_file_path = args.file.rstrip("mcuimg.bin") + "genhdr/mpversion.h" + if args.tag is not None: - success = find_tag(bytes(args.tag, 'ascii')) + success = find_tag(bytes(args.tag, "ascii")) else: with open(tag_file_path) as tag_file: for line in tag_file: - bline = bytes(line, 'ascii') - if b'MICROPY_GIT_HASH' in bline: - bline = bline.lstrip(b'#define MICROPY_GIT_HASH ').replace(b'"', b'').replace(b'\r', b'').replace(b'\n', b'') + bline = bytes(line, "ascii") + if b"MICROPY_GIT_HASH" in bline: + bline = ( + bline.lstrip(b"#define MICROPY_GIT_HASH ") + .replace(b'"', b"") + .replace(b"\r", b"") + .replace(b"\n", b"") + ) success = find_tag(bline) break @@ -164,24 +173,28 @@ def verify_update(args): def main(): - cmd_parser = argparse.ArgumentParser(description='Update the WiPy firmware with the specified image file') - cmd_parser.add_argument('-f', '--file', default=None, help='the path of the firmware file') - cmd_parser.add_argument('-u', '--user', default='micro', help='the username') - cmd_parser.add_argument('-p', '--password', default='python', help='the login password') - cmd_parser.add_argument('--ip', default='192.168.1.1', help='the ip address of the WiPy') - cmd_parser.add_argument('--verify', action='store_true', help='verify that the update succeeded') - cmd_parser.add_argument('-t', '--tag', default=None, help='git tag of the firmware image') + cmd_parser = argparse.ArgumentParser( + description="Update the WiPy firmware with the specified image file" + ) + cmd_parser.add_argument("-f", "--file", default=None, help="the path of the firmware file") + cmd_parser.add_argument("-u", "--user", default="micro", help="the username") + cmd_parser.add_argument("-p", "--password", default="python", help="the login password") + cmd_parser.add_argument("--ip", default="192.168.1.1", help="the ip address of the WiPy") + cmd_parser.add_argument( + "--verify", action="store_true", help="verify that the update succeeded" + ) + cmd_parser.add_argument("-t", "--tag", default=None, help="git tag of the firmware image") args = cmd_parser.parse_args() result = 1 try: if args.file is None: - raise ValueError('the image file path must be specified') + raise ValueError("the image file path must be specified") if transfer_file(args): if reset_board(args): if args.verify: - print ('Waiting for the WiFi connection to come up again...') + print("Waiting for the WiFi connection to come up again...") # this time is to allow the system's wireless network card to # connect to the WiPy again. time.sleep(5) diff --git a/ports/cc3200/version.h b/ports/cc3200/version.h index fccb95c521..81a69999ec 100644 --- a/ports/cc3200/version.h +++ b/ports/cc3200/version.h @@ -1,31 +1,31 @@ -/* - * This file is part of the MicroPython project, http://micropython.org/ - * - * The MIT License (MIT) - * - * 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_CC3200_VERSION_H -#define MICROPY_INCLUDED_CC3200_VERSION_H - -#define WIPY_SW_VERSION_NUMBER "1.2.0" - -#endif // MICROPY_INCLUDED_CC3200_VERSION_H +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * 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_CC3200_VERSION_H +#define MICROPY_INCLUDED_CC3200_VERSION_H + +#define WIPY_SW_VERSION_NUMBER "1.2.0" + +#endif // MICROPY_INCLUDED_CC3200_VERSION_H diff --git a/ports/esp32/esp32_ulp.c b/ports/esp32/esp32_ulp.c index 3772639f44..d54e4eb012 100644 --- a/ports/esp32/esp32_ulp.c +++ b/ports/esp32/esp32_ulp.c @@ -51,7 +51,7 @@ STATIC mp_obj_t esp32_ulp_set_wakeup_period(mp_obj_t self_in, mp_obj_t period_in mp_uint_t period_us = mp_obj_get_int(period_us_in); int _errno = ulp_set_wakeup_period(period_index, period_us); if (_errno != ESP_OK) { - mp_raise_OSError(_errno); + mp_raise_OSError(_errno); } return mp_const_none; } @@ -63,9 +63,9 @@ STATIC mp_obj_t esp32_ulp_load_binary(mp_obj_t self_in, mp_obj_t load_addr_in, m mp_buffer_info_t bufinfo; mp_get_buffer_raise(program_binary_in, &bufinfo, MP_BUFFER_READ); - int _errno = ulp_load_binary(load_addr, bufinfo.buf, bufinfo.len/sizeof(uint32_t)); + int _errno = ulp_load_binary(load_addr, bufinfo.buf, bufinfo.len / sizeof(uint32_t)); if (_errno != ESP_OK) { - mp_raise_OSError(_errno); + mp_raise_OSError(_errno); } return mp_const_none; } @@ -73,9 +73,9 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_3(esp32_ulp_load_binary_obj, esp32_ulp_load_binar STATIC mp_obj_t esp32_ulp_run(mp_obj_t self_in, mp_obj_t entry_point_in) { mp_uint_t entry_point = mp_obj_get_int(entry_point_in); - int _errno = ulp_run(entry_point/sizeof(uint32_t)); + int _errno = ulp_run(entry_point / sizeof(uint32_t)); if (_errno != ESP_OK) { - mp_raise_OSError(_errno); + mp_raise_OSError(_errno); } return mp_const_none; } diff --git a/ports/esp32/espneopixel.c b/ports/esp32/espneopixel.c index 829c8b1c80..1736e2a46a 100644 --- a/ports/esp32/espneopixel.c +++ b/ports/esp32/espneopixel.c @@ -13,11 +13,11 @@ void IRAM_ATTR esp_neopixel_write(uint8_t pin, uint8_t *pixels, uint32_t numByte uint8_t *p, *end, pix, mask; uint32_t t, time0, time1, period, c, startTime, pinMask; - pinMask = 1 << pin; - p = pixels; - end = p + numBytes; - pix = *p++; - mask = 0x80; + pinMask = 1 << pin; + p = pixels; + end = p + numBytes; + pix = *p++; + mask = 0x80; startTime = 0; uint32_t fcpu = ets_get_cpu_frequency() * 1000000; @@ -36,18 +36,28 @@ void IRAM_ATTR esp_neopixel_write(uint8_t pin, uint8_t *pixels, uint32_t numByte uint32_t irq_state = mp_hal_quiet_timing_enter(); for (t = time0;; t = time0) { - if (pix & mask) t = time1; // Bit high duration - while (((c = mp_hal_ticks_cpu()) - startTime) < period); // Wait for bit start + if (pix & mask) { + t = time1; // Bit high duration + } + while (((c = mp_hal_ticks_cpu()) - startTime) < period) { + ; // Wait for bit start + } GPIO_REG_WRITE(GPIO_OUT_W1TS_REG, pinMask); // Set high startTime = c; // Save start time - while (((c = mp_hal_ticks_cpu()) - startTime) < t); // Wait high duration + while (((c = mp_hal_ticks_cpu()) - startTime) < t) { + ; // Wait high duration + } GPIO_REG_WRITE(GPIO_OUT_W1TC_REG, pinMask); // Set low if (!(mask >>= 1)) { // Next bit/byte - if(p >= end) break; - pix = *p++; + if (p >= end) { + break; + } + pix = *p++; mask = 0x80; } } - while ((mp_hal_ticks_cpu() - startTime) < period); // Wait for last bit + while ((mp_hal_ticks_cpu() - startTime) < period) { + ; // Wait for last bit + } mp_hal_quiet_timing_exit(irq_state); } diff --git a/ports/esp32/fatfs_port.c b/ports/esp32/fatfs_port.c index 880324ed82..779ba1c88a 100644 --- a/ports/esp32/fatfs_port.c +++ b/ports/esp32/fatfs_port.c @@ -36,6 +36,6 @@ DWORD get_fattime(void) { timeutils_struct_time_t tm; timeutils_seconds_since_2000_to_struct_time(tv.tv_sec, &tm); - return (((DWORD)(tm.tm_year - 1980) << 25) | ((DWORD)tm.tm_mon << 21) | ((DWORD)tm.tm_mday << 16) | - ((DWORD)tm.tm_hour << 11) | ((DWORD)tm.tm_min << 5) | ((DWORD)tm.tm_sec >> 1)); + return ((DWORD)(tm.tm_year - 1980) << 25) | ((DWORD)tm.tm_mon << 21) | ((DWORD)tm.tm_mday << 16) | + ((DWORD)tm.tm_hour << 11) | ((DWORD)tm.tm_min << 5) | ((DWORD)tm.tm_sec >> 1); } diff --git a/ports/esp32/gccollect.c b/ports/esp32/gccollect.c index 9843cef008..7d5da57e76 100644 --- a/ports/esp32/gccollect.c +++ b/ports/esp32/gccollect.c @@ -49,7 +49,7 @@ static void gc_collect_inner(int level) { if (level == XCHAL_NUM_AREGS / 8) { // get the sp volatile uint32_t sp = (uint32_t)get_sp(); - gc_collect_root((void**)sp, ((mp_uint_t)MP_STATE_THREAD(stack_top) - sp) / sizeof(uint32_t)); + gc_collect_root((void **)sp, ((mp_uint_t)MP_STATE_THREAD(stack_top) - sp) / sizeof(uint32_t)); return; } diff --git a/ports/esp32/help.c b/ports/esp32/help.c index 95d115c563..2336d97f84 100644 --- a/ports/esp32/help.c +++ b/ports/esp32/help.c @@ -29,37 +29,37 @@ #include "py/builtin.h" const char esp32_help_text[] = -"Welcome to MicroPython on the ESP32!\n" -"\n" -"For generic online docs please visit http://docs.micropython.org/\n" -"\n" -"For access to the hardware use the 'machine' module:\n" -"\n" -"import machine\n" -"pin12 = machine.Pin(12, machine.Pin.OUT)\n" -"pin12.value(1)\n" -"pin13 = machine.Pin(13, machine.Pin.IN, machine.Pin.PULL_UP)\n" -"print(pin13.value())\n" -"i2c = machine.I2C(scl=machine.Pin(21), sda=machine.Pin(22))\n" -"i2c.scan()\n" -"i2c.writeto(addr, b'1234')\n" -"i2c.readfrom(addr, 4)\n" -"\n" -"Basic WiFi configuration:\n" -"\n" -"import network\n" -"sta_if = network.WLAN(network.STA_IF); sta_if.active(True)\n" -"sta_if.scan() # Scan for available access points\n" -"sta_if.connect(\"\", \"\") # Connect to an AP\n" -"sta_if.isconnected() # Check for successful connection\n" -"\n" -"Control commands:\n" -" CTRL-A -- on a blank line, enter raw REPL mode\n" -" CTRL-B -- on a blank line, enter normal REPL mode\n" -" CTRL-C -- interrupt a running program\n" -" CTRL-D -- on a blank line, do a soft reset of the board\n" -" CTRL-E -- on a blank line, enter paste mode\n" -"\n" -"For further help on a specific object, type help(obj)\n" -"For a list of available modules, type help('modules')\n" + "Welcome to MicroPython on the ESP32!\n" + "\n" + "For generic online docs please visit http://docs.micropython.org/\n" + "\n" + "For access to the hardware use the 'machine' module:\n" + "\n" + "import machine\n" + "pin12 = machine.Pin(12, machine.Pin.OUT)\n" + "pin12.value(1)\n" + "pin13 = machine.Pin(13, machine.Pin.IN, machine.Pin.PULL_UP)\n" + "print(pin13.value())\n" + "i2c = machine.I2C(scl=machine.Pin(21), sda=machine.Pin(22))\n" + "i2c.scan()\n" + "i2c.writeto(addr, b'1234')\n" + "i2c.readfrom(addr, 4)\n" + "\n" + "Basic WiFi configuration:\n" + "\n" + "import network\n" + "sta_if = network.WLAN(network.STA_IF); sta_if.active(True)\n" + "sta_if.scan() # Scan for available access points\n" + "sta_if.connect(\"\", \"\") # Connect to an AP\n" + "sta_if.isconnected() # Check for successful connection\n" + "\n" + "Control commands:\n" + " CTRL-A -- on a blank line, enter raw REPL mode\n" + " CTRL-B -- on a blank line, enter normal REPL mode\n" + " CTRL-C -- interrupt a running program\n" + " CTRL-D -- on a blank line, do a soft reset of the board\n" + " CTRL-E -- on a blank line, enter paste mode\n" + "\n" + "For further help on a specific object, type help(obj)\n" + "For a list of available modules, type help('modules')\n" ; diff --git a/ports/esp32/machine_adc.c b/ports/esp32/machine_adc.c index d62f362e96..67252ac1e7 100644 --- a/ports/esp32/machine_adc.c +++ b/ports/esp32/machine_adc.c @@ -54,7 +54,7 @@ STATIC const madc_obj_t madc_obj[] = { }; STATIC mp_obj_t madc_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, - const mp_obj_t *args) { + const mp_obj_t *args) { static int initialized = 0; if (!initialized) { @@ -66,11 +66,18 @@ STATIC mp_obj_t madc_make_new(const mp_obj_type_t *type, size_t n_args, size_t n gpio_num_t pin_id = machine_pin_get_id(args[0]); const madc_obj_t *self = NULL; for (int i = 0; i < MP_ARRAY_SIZE(madc_obj); i++) { - if (pin_id == madc_obj[i].gpio_id) { self = &madc_obj[i]; break; } + if (pin_id == madc_obj[i].gpio_id) { + self = &madc_obj[i]; + break; + } + } + if (!self) { + mp_raise_ValueError("invalid Pin for ADC"); } - if (!self) mp_raise_ValueError("invalid Pin for ADC"); esp_err_t err = adc1_config_channel_atten(self->adc1_id, ADC_ATTEN_0db); - if (err == ESP_OK) return MP_OBJ_FROM_PTR(self); + if (err == ESP_OK) { + return MP_OBJ_FROM_PTR(self); + } mp_raise_ValueError("Parameter Error"); } @@ -82,7 +89,9 @@ STATIC void madc_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_ STATIC mp_obj_t madc_read(mp_obj_t self_in) { madc_obj_t *self = self_in; int val = adc1_get_raw(self->adc1_id); - if (val == -1) mp_raise_ValueError("Parameter Error"); + if (val == -1) { + mp_raise_ValueError("Parameter Error"); + } return MP_OBJ_NEW_SMALL_INT(val); } MP_DEFINE_CONST_FUN_OBJ_1(madc_read_obj, madc_read); @@ -91,7 +100,9 @@ STATIC mp_obj_t madc_atten(mp_obj_t self_in, mp_obj_t atten_in) { madc_obj_t *self = self_in; adc_atten_t atten = mp_obj_get_int(atten_in); esp_err_t err = adc1_config_channel_atten(self->adc1_id, atten); - if (err == ESP_OK) return mp_const_none; + if (err == ESP_OK) { + return mp_const_none; + } mp_raise_ValueError("Parameter Error"); } MP_DEFINE_CONST_FUN_OBJ_2(madc_atten_obj, madc_atten); @@ -99,7 +110,9 @@ MP_DEFINE_CONST_FUN_OBJ_2(madc_atten_obj, madc_atten); STATIC mp_obj_t madc_width(mp_obj_t cls_in, mp_obj_t width_in) { adc_bits_width_t width = mp_obj_get_int(width_in); esp_err_t err = adc1_config_width(width); - if (err == ESP_OK) return mp_const_none; + if (err == ESP_OK) { + return mp_const_none; + } mp_raise_ValueError("Parameter Error"); } MP_DEFINE_CONST_FUN_OBJ_2(madc_width_fun_obj, madc_width); diff --git a/ports/esp32/machine_dac.c b/ports/esp32/machine_dac.c index bd0804ec41..bb441c7da9 100644 --- a/ports/esp32/machine_dac.c +++ b/ports/esp32/machine_dac.c @@ -48,21 +48,28 @@ STATIC const mdac_obj_t mdac_obj[] = { }; STATIC mp_obj_t mdac_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, - const mp_obj_t *args) { + const mp_obj_t *args) { mp_arg_check_num(n_args, n_kw, 1, 1, true); gpio_num_t pin_id = machine_pin_get_id(args[0]); const mdac_obj_t *self = NULL; for (int i = 0; i < MP_ARRAY_SIZE(mdac_obj); i++) { - if (pin_id == mdac_obj[i].gpio_id) { self = &mdac_obj[i]; break; } + if (pin_id == mdac_obj[i].gpio_id) { + self = &mdac_obj[i]; + break; + } + } + if (!self) { + mp_raise_ValueError("invalid Pin for DAC"); } - if (!self) mp_raise_ValueError("invalid Pin for DAC"); esp_err_t err = dac_output_enable(self->dac_id); if (err == ESP_OK) { err = dac_output_voltage(self->dac_id, 0); } - if (err == ESP_OK) return MP_OBJ_FROM_PTR(self); + if (err == ESP_OK) { + return MP_OBJ_FROM_PTR(self); + } mp_raise_ValueError("Parameter Error"); } @@ -74,10 +81,14 @@ STATIC void mdac_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_ STATIC mp_obj_t mdac_write(mp_obj_t self_in, mp_obj_t value_in) { mdac_obj_t *self = self_in; int value = mp_obj_get_int(value_in); - if (value < 0 || value > 255) mp_raise_ValueError("Value out of range"); + if (value < 0 || value > 255) { + mp_raise_ValueError("Value out of range"); + } esp_err_t err = dac_output_voltage(self->dac_id, value); - if (err == ESP_OK) return mp_const_none; + if (err == ESP_OK) { + return mp_const_none; + } mp_raise_ValueError("Parameter Error"); } MP_DEFINE_CONST_FUN_OBJ_2(mdac_write_obj, mdac_write); diff --git a/ports/esp32/machine_hw_spi.c b/ports/esp32/machine_hw_spi.c index 2f63a32d4a..a63045031b 100644 --- a/ports/esp32/machine_hw_spi.c +++ b/ports/esp32/machine_hw_spi.c @@ -94,16 +94,16 @@ STATIC void machine_hw_spi_deinit_internal(machine_hw_spi_obj_t *self) { } STATIC void machine_hw_spi_init_internal( - machine_hw_spi_obj_t *self, - int8_t host, - int32_t baudrate, - int8_t polarity, - int8_t phase, - int8_t bits, - int8_t firstbit, - int8_t sck, - int8_t mosi, - int8_t miso) { + machine_hw_spi_obj_t *self, + int8_t host, + int32_t baudrate, + int8_t polarity, + int8_t phase, + int8_t bits, + int8_t firstbit, + int8_t sck, + int8_t mosi, + int8_t miso) { // if we're not initialized, then we're // implicitly 'changed', since this is the init routine @@ -129,7 +129,7 @@ STATIC void machine_hw_spi_init_internal( } if (phase != -1 && phase != self->phase) { - self->phase = phase; + self->phase = phase; changed = true; } @@ -188,7 +188,7 @@ STATIC void machine_hw_spi_init_internal( .pre_cb = NULL }; - //Initialize the SPI bus + // Initialize the SPI bus // Select DMA channel based on the hardware SPI host int dma_chan = 0; @@ -230,7 +230,7 @@ STATIC void machine_hw_spi_init_internal( } STATIC void machine_hw_spi_deinit(mp_obj_base_t *self_in) { - machine_hw_spi_obj_t *self = (machine_hw_spi_obj_t *) self_in; + machine_hw_spi_obj_t *self = (machine_hw_spi_obj_t *)self_in; if (self->state == MACHINE_HW_SPI_STATE_INIT) { self->state = MACHINE_HW_SPI_STATE_DEINIT; machine_hw_spi_deinit_internal(self); @@ -295,13 +295,13 @@ STATIC void machine_hw_spi_transfer(mp_obj_base_t *self_in, size_t len, const ui STATIC void machine_hw_spi_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { machine_hw_spi_obj_t *self = MP_OBJ_TO_PTR(self_in); mp_printf(print, "SPI(id=%u, baudrate=%u, polarity=%u, phase=%u, bits=%u, firstbit=%u, sck=%d, mosi=%d, miso=%d)", - self->host, self->baudrate, self->polarity, - self->phase, self->bits, self->firstbit, - self->sck, self->mosi, self->miso); + self->host, self->baudrate, self->polarity, + self->phase, self->bits, self->firstbit, + self->sck, self->mosi, self->miso); } STATIC void machine_hw_spi_init(mp_obj_base_t *self_in, size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { - machine_hw_spi_obj_t *self = (machine_hw_spi_obj_t *) self_in; + machine_hw_spi_obj_t *self = (machine_hw_spi_obj_t *)self_in; enum { ARG_id, ARG_baudrate, ARG_polarity, ARG_phase, ARG_bits, ARG_firstbit, ARG_sck, ARG_mosi, ARG_miso }; static const mp_arg_t allowed_args[] = { @@ -318,7 +318,7 @@ STATIC void machine_hw_spi_init(mp_obj_base_t *self_in, size_t n_args, const mp_ mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), - allowed_args, args); + allowed_args, args); int8_t sck, mosi, miso; if (args[ARG_sck].u_obj == MP_OBJ_NULL) { @@ -346,8 +346,8 @@ STATIC void machine_hw_spi_init(mp_obj_base_t *self_in, size_t n_args, const mp_ } machine_hw_spi_init_internal(self, args[ARG_id].u_int, args[ARG_baudrate].u_int, - args[ARG_polarity].u_int, args[ARG_phase].u_int, args[ARG_bits].u_int, - args[ARG_firstbit].u_int, sck, mosi, miso); + args[ARG_polarity].u_int, args[ARG_phase].u_int, args[ARG_bits].u_int, + args[ARG_firstbit].u_int, sck, mosi, miso); } mp_obj_t machine_hw_spi_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { @@ -401,5 +401,5 @@ const mp_obj_type_t machine_hw_spi_type = { .print = machine_hw_spi_print, .make_new = machine_hw_spi_make_new, .protocol = &machine_hw_spi_p, - .locals_dict = (mp_obj_dict_t *) &mp_machine_spi_locals_dict, + .locals_dict = (mp_obj_dict_t *)&mp_machine_spi_locals_dict, }; diff --git a/ports/esp32/machine_pin.c b/ports/esp32/machine_pin.c index 1f4226474b..e49d0a9f6d 100644 --- a/ports/esp32/machine_pin.c +++ b/ports/esp32/machine_pin.c @@ -179,7 +179,7 @@ mp_obj_t mp_pin_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, int wanted_pin = mp_obj_get_int(args[0]); const machine_pin_obj_t *self = NULL; if (0 <= wanted_pin && wanted_pin < MP_ARRAY_SIZE(machine_pin_obj)) { - self = (machine_pin_obj_t*)&machine_pin_obj[wanted_pin]; + self = (machine_pin_obj_t *)&machine_pin_obj[wanted_pin]; } if (self == NULL || self->base.type == NULL) { mp_raise_ValueError("invalid pin"); @@ -293,7 +293,7 @@ STATIC mp_obj_t machine_pin_irq(size_t n_args, const mp_obj_t *pos_args, mp_map_ gpio_isr_handler_remove(self->id); MP_STATE_PORT(machine_pin_irq_handler)[self->id] = handler; gpio_set_intr_type(self->id, trigger); - gpio_isr_handler_add(self->id, machine_pin_isr_handler, (void*)self); + gpio_isr_handler_add(self->id, machine_pin_isr_handler, (void *)self); } } @@ -341,7 +341,7 @@ STATIC mp_uint_t pin_ioctl(mp_obj_t self_in, mp_uint_t request, uintptr_t arg, i STATIC MP_DEFINE_CONST_DICT(machine_pin_locals_dict, machine_pin_locals_dict_table); STATIC const mp_pin_p_t pin_pin_p = { - .ioctl = pin_ioctl, + .ioctl = pin_ioctl, }; const mp_obj_type_t machine_pin_type = { @@ -405,7 +405,7 @@ STATIC const machine_pin_irq_obj_t machine_pin_irq_object[] = { STATIC mp_obj_t machine_pin_irq_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp_obj_t *args) { machine_pin_irq_obj_t *self = self_in; mp_arg_check_num(n_args, n_kw, 0, 0, false); - machine_pin_isr_handler((void*)&machine_pin_obj[self->id]); + machine_pin_isr_handler((void *)&machine_pin_obj[self->id]); return mp_const_none; } @@ -430,5 +430,5 @@ STATIC const mp_obj_type_t machine_pin_irq_type = { { &mp_type_type }, .name = MP_QSTR_IRQ, .call = machine_pin_irq_call, - .locals_dict = (mp_obj_dict_t*)&machine_pin_irq_locals_dict, + .locals_dict = (mp_obj_dict_t *)&machine_pin_irq_locals_dict, }; diff --git a/ports/esp32/machine_pwm.c b/ports/esp32/machine_pwm.c index 7376470dcc..24385c49eb 100644 --- a/ports/esp32/machine_pwm.c +++ b/ports/esp32/machine_pwm.c @@ -120,7 +120,7 @@ STATIC void esp32_pwm_print(const mp_print_t *print, mp_obj_t self_in, mp_print_ } STATIC void esp32_pwm_init_helper(esp32_pwm_obj_t *self, - size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { enum { ARG_freq, ARG_duty }; static const mp_arg_t allowed_args[] = { { MP_QSTR_freq, MP_ARG_INT, {.u_int = -1} }, @@ -183,7 +183,7 @@ STATIC void esp32_pwm_init_helper(esp32_pwm_obj_t *self, // Set duty cycle? int dval = args[ARG_duty].u_int; if (dval != -1) { - dval &= ((1 << PWRES)-1); + dval &= ((1 << PWRES) - 1); dval >>= PWRES - timer_cfg.duty_resolution; ledc_set_duty(PWMODE, channel, dval); ledc_update_duty(PWMODE, channel); @@ -191,7 +191,7 @@ STATIC void esp32_pwm_init_helper(esp32_pwm_obj_t *self, } STATIC mp_obj_t esp32_pwm_make_new(const mp_obj_type_t *type, - size_t n_args, size_t n_kw, const mp_obj_t *args) { + size_t n_args, size_t n_kw, const mp_obj_t *args) { mp_arg_check_num(n_args, n_kw, 1, MP_OBJ_FUN_ARGS_MAX, true); gpio_num_t pin_id = machine_pin_get_id(args[0]); @@ -217,7 +217,7 @@ STATIC mp_obj_t esp32_pwm_make_new(const mp_obj_type_t *type, } STATIC mp_obj_t esp32_pwm_init(size_t n_args, - const mp_obj_t *args, mp_map_t *kw_args) { + const mp_obj_t *args, mp_map_t *kw_args) { esp32_pwm_init_helper(args[0], n_args - 1, args + 1, kw_args); return mp_const_none; } @@ -270,7 +270,7 @@ STATIC mp_obj_t esp32_pwm_duty(size_t n_args, const mp_obj_t *args) { // set duty = mp_obj_get_int(args[1]); - duty &= ((1 << PWRES)-1); + duty &= ((1 << PWRES) - 1); duty >>= PWRES - timer_cfg.duty_resolution; ledc_set_duty(PWMODE, self->channel, duty); ledc_update_duty(PWMODE, self->channel); @@ -295,5 +295,5 @@ const mp_obj_type_t machine_pwm_type = { .name = MP_QSTR_PWM, .print = esp32_pwm_print, .make_new = esp32_pwm_make_new, - .locals_dict = (mp_obj_dict_t*)&esp32_pwm_locals_dict, + .locals_dict = (mp_obj_dict_t *)&esp32_pwm_locals_dict, }; diff --git a/ports/esp32/machine_rtc.c b/ports/esp32/machine_rtc.c index 08c7b02bfd..ea38ce35b6 100644 --- a/ports/esp32/machine_rtc.c +++ b/ports/esp32/machine_rtc.c @@ -62,7 +62,7 @@ STATIC const machine_rtc_obj_t machine_rtc_obj = {{&machine_rtc_type}}; machine_rtc_config_t machine_rtc_config = { .ext1_pins = 0, .ext0_pin = -1 - }; +}; STATIC mp_obj_t machine_rtc_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { // check arguments @@ -130,7 +130,7 @@ STATIC mp_obj_t machine_rtc_memory(mp_uint_t n_args, const mp_obj_t *args) { // read RTC memory uint32_t len = rtc_user_mem_len; uint8_t rtcram[MEM_USER_MAXLEN]; - memcpy( (char *) rtcram, (char *) rtc_user_mem_data, len); + memcpy((char *)rtcram, (char *)rtc_user_mem_data, len); return mp_obj_new_bytes(rtcram, len); } else { // write RTC memory @@ -140,7 +140,7 @@ STATIC mp_obj_t machine_rtc_memory(mp_uint_t n_args, const mp_obj_t *args) { if (bufinfo.len > MEM_USER_MAXLEN) { mp_raise_ValueError("buffer too long"); } - memcpy( (char *) rtc_user_mem_data, (char *) bufinfo.buf, bufinfo.len); + memcpy((char *)rtc_user_mem_data, (char *)bufinfo.buf, bufinfo.len); rtc_user_mem_len = bufinfo.len; return mp_const_none; } diff --git a/ports/esp32/machine_rtc.h b/ports/esp32/machine_rtc.h index e34deb9be6..6e70f74385 100644 --- a/ports/esp32/machine_rtc.h +++ b/ports/esp32/machine_rtc.h @@ -4,7 +4,7 @@ * The MIT License (MIT) * * Copyright (c) 2017 "Eric Poulsen" - * Copyright (c) 2017 "Tom Manning" + * Copyright (c) 2017 "Tom Manning" * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal diff --git a/ports/esp32/machine_timer.c b/ports/esp32/machine_timer.c index 7dca9e0143..231641d3e2 100644 --- a/ports/esp32/machine_timer.c +++ b/ports/esp32/machine_timer.c @@ -129,7 +129,7 @@ STATIC void machine_timer_enable(machine_timer_obj_t *self) { check_esp_err(timer_set_counter_value(self->group, self->index, 0x00000000)); check_esp_err(timer_set_alarm_value(self->group, self->index, self->period)); check_esp_err(timer_enable_intr(self->group, self->index)); - check_esp_err(timer_isr_register(self->group, self->index, machine_timer_isr, (void*)self, TIMER_FLAGS, &self->handle)); + check_esp_err(timer_isr_register(self->group, self->index, machine_timer_isr, (void *)self, TIMER_FLAGS, &self->handle)); check_esp_err(timer_start(self->group, self->index)); } @@ -146,11 +146,11 @@ STATIC mp_obj_t machine_timer_init_helper(machine_timer_obj_t *self, mp_uint_t n { MP_QSTR_callback, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, { MP_QSTR_period, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0xffffffff} }, { MP_QSTR_tick_hz, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 1000} }, -#if MICROPY_PY_BUILTINS_FLOAT + #if MICROPY_PY_BUILTINS_FLOAT { MP_QSTR_freq, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, -#else + #else { MP_QSTR_freq, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0xffffffff} }, -#endif + #endif }; machine_timer_disable(self); @@ -158,15 +158,15 @@ STATIC mp_obj_t machine_timer_init_helper(machine_timer_obj_t *self, mp_uint_t n mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); -#if MICROPY_PY_BUILTINS_FLOAT + #if MICROPY_PY_BUILTINS_FLOAT if (args[ARG_freq].u_obj != mp_const_none) { self->period = (uint64_t)(TIMER_SCALE / mp_obj_get_float(args[ARG_freq].u_obj)); } -#else + #else if (args[ARG_freq].u_int != 0xffffffff) { self->period = TIMER_SCALE / ((uint64_t)args[ARG_freq].u_int); } -#endif + #endif else { self->period = (((uint64_t)args[ARG_period].u_int) * TIMER_SCALE) / args[ARG_tick_hz].u_int; } diff --git a/ports/esp32/machine_touchpad.c b/ports/esp32/machine_touchpad.c index 96de1a2a1d..a7037655c3 100644 --- a/ports/esp32/machine_touchpad.c +++ b/ports/esp32/machine_touchpad.c @@ -56,15 +56,20 @@ STATIC const mtp_obj_t touchpad_obj[] = { }; STATIC mp_obj_t mtp_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, - const mp_obj_t *args) { + const mp_obj_t *args) { mp_arg_check_num(n_args, n_kw, 1, 1, true); gpio_num_t pin_id = machine_pin_get_id(args[0]); const mtp_obj_t *self = NULL; for (int i = 0; i < MP_ARRAY_SIZE(touchpad_obj); i++) { - if (pin_id == touchpad_obj[i].gpio_id) { self = &touchpad_obj[i]; break; } + if (pin_id == touchpad_obj[i].gpio_id) { + self = &touchpad_obj[i]; + break; + } + } + if (!self) { + mp_raise_ValueError("invalid pin for touchpad"); } - if (!self) mp_raise_ValueError("invalid pin for touchpad"); static int initialized = 0; if (!initialized) { @@ -72,7 +77,9 @@ STATIC mp_obj_t mtp_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_ initialized = 1; } esp_err_t err = touch_pad_config(self->touchpad_id, 0); - if (err == ESP_OK) return MP_OBJ_FROM_PTR(self); + if (err == ESP_OK) { + return MP_OBJ_FROM_PTR(self); + } mp_raise_ValueError("Touch pad error"); } @@ -80,7 +87,9 @@ STATIC mp_obj_t mtp_config(mp_obj_t self_in, mp_obj_t value_in) { mtp_obj_t *self = self_in; uint16_t value = mp_obj_get_int(value_in); esp_err_t err = touch_pad_config(self->touchpad_id, value); - if (err == ESP_OK) return mp_const_none; + if (err == ESP_OK) { + return mp_const_none; + } mp_raise_ValueError("Touch pad error"); } MP_DEFINE_CONST_FUN_OBJ_2(mtp_config_obj, mtp_config); @@ -89,7 +98,9 @@ STATIC mp_obj_t mtp_read(mp_obj_t self_in) { mtp_obj_t *self = self_in; uint16_t value; esp_err_t err = touch_pad_read(self->touchpad_id, &value); - if (err == ESP_OK) return MP_OBJ_NEW_SMALL_INT(value); + if (err == ESP_OK) { + return MP_OBJ_NEW_SMALL_INT(value); + } mp_raise_ValueError("Touch pad error"); } MP_DEFINE_CONST_FUN_OBJ_1(mtp_read_obj, mtp_read); diff --git a/ports/esp32/machine_uart.c b/ports/esp32/machine_uart.c index b3c70de1e7..01bb4719a8 100644 --- a/ports/esp32/machine_uart.c +++ b/ports/esp32/machine_uart.c @@ -222,7 +222,7 @@ STATIC mp_obj_t machine_uart_make_new(const mp_obj_type_t *type, size_t n_args, nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "UART(%d) is disabled (dedicated to REPL)", uart_num)); } - // Defaults + // Defaults uart_config_t uartcfg = { .baud_rate = 115200, .data_bits = UART_DATA_8_BITS, @@ -413,5 +413,5 @@ const mp_obj_type_t machine_uart_type = { .getiter = mp_identity_getiter, .iternext = mp_stream_unbuffered_iter, .protocol = &uart_stream_p, - .locals_dict = (mp_obj_dict_t*)&machine_uart_locals_dict, + .locals_dict = (mp_obj_dict_t *)&machine_uart_locals_dict, }; diff --git a/ports/esp32/makeimg.py b/ports/esp32/makeimg.py index aeedbff7ef..9f27ed6ef8 100644 --- a/ports/esp32/makeimg.py +++ b/ports/esp32/makeimg.py @@ -5,21 +5,21 @@ OFFSET_PARTITIONS = 0x8000 OFFSET_APPLICATION = 0x10000 files_in = [ - ('bootloader', OFFSET_BOOTLOADER, sys.argv[1]), - ('partitions', OFFSET_PARTITIONS, sys.argv[2]), - ('application', OFFSET_APPLICATION, sys.argv[3]), + ("bootloader", OFFSET_BOOTLOADER, sys.argv[1]), + ("partitions", OFFSET_PARTITIONS, sys.argv[2]), + ("application", OFFSET_APPLICATION, sys.argv[3]), ] file_out = sys.argv[4] cur_offset = OFFSET_BOOTLOADER -with open(file_out, 'wb') as fout: +with open(file_out, "wb") as fout: for name, offset, file_in in files_in: assert offset >= cur_offset - fout.write(b'\xff' * (offset - cur_offset)) + fout.write(b"\xff" * (offset - cur_offset)) cur_offset = offset - with open(file_in, 'rb') as fin: + with open(file_in, "rb") as fin: data = fin.read() fout.write(data) cur_offset += len(data) - print('%-12s% 8d' % (name, len(data))) - print('%-12s% 8d' % ('total', cur_offset)) + print("%-12s% 8d" % (name, len(data))) + print("%-12s% 8d" % ("total", cur_offset)) diff --git a/ports/esp32/modesp.c b/ports/esp32/modesp.c index e614f77a6a..b40a780cb9 100644 --- a/ports/esp32/modesp.c +++ b/ports/esp32/modesp.c @@ -117,7 +117,7 @@ STATIC mp_obj_t esp_neopixel_write_(mp_obj_t pin, mp_obj_t buf, mp_obj_t timing) mp_buffer_info_t bufinfo; mp_get_buffer_raise(buf, &bufinfo, MP_BUFFER_READ); esp_neopixel_write(mp_hal_get_pin_obj(pin), - (uint8_t*)bufinfo.buf, bufinfo.len, mp_obj_get_int(timing)); + (uint8_t *)bufinfo.buf, bufinfo.len, mp_obj_get_int(timing)); return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_3(esp_neopixel_write_obj, esp_neopixel_write_); @@ -152,6 +152,6 @@ STATIC MP_DEFINE_CONST_DICT(esp_module_globals, esp_module_globals_table); const mp_obj_module_t esp_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&esp_module_globals, + .globals = (mp_obj_dict_t *)&esp_module_globals, }; diff --git a/ports/esp32/modesp32.c b/ports/esp32/modesp32.c index 2e2d8236cf..5cc95b86de 100644 --- a/ports/esp32/modesp32.c +++ b/ports/esp32/modesp32.c @@ -48,7 +48,7 @@ STATIC mp_obj_t esp32_wake_on_touch(const mp_obj_t wake) { if (machine_rtc_config.ext0_pin != -1) { mp_raise_ValueError("no resources"); } - //nlr_raise(mp_obj_new_exception_msg(&mp_type_RuntimeError, "touchpad wakeup not available for this version of ESP-IDF")); + // nlr_raise(mp_obj_new_exception_msg(&mp_type_RuntimeError, "touchpad wakeup not available for this version of ESP-IDF")); machine_rtc_config.wake_on_touch = mp_obj_is_true(wake); return mp_const_none; @@ -164,5 +164,5 @@ STATIC MP_DEFINE_CONST_DICT(esp32_module_globals, esp32_module_globals_table); const mp_obj_module_t esp32_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&esp32_module_globals, + .globals = (mp_obj_dict_t *)&esp32_module_globals, }; diff --git a/ports/esp32/modesp32.h b/ports/esp32/modesp32.h index 1d18cb41fb..a9d59b4b71 100644 --- a/ports/esp32/modesp32.h +++ b/ports/esp32/modesp32.h @@ -2,10 +2,10 @@ #define MICROPY_INCLUDED_ESP32_MODESP32_H #define RTC_VALID_EXT_PINS \ -( \ - (1ll << 0) | \ - (1ll << 2) | \ - (1ll << 4) | \ + ( \ + (1ll << 0) | \ + (1ll << 2) | \ + (1ll << 4) | \ (1ll << 12) | \ (1ll << 13) | \ (1ll << 14) | \ @@ -21,7 +21,7 @@ (1ll << 37) | \ (1ll << 38) | \ (1ll << 39) \ -) + ) #define RTC_LAST_EXT_PIN 39 #define RTC_IS_VALID_EXT_PIN(pin_id) ((1ll << (pin_id)) & RTC_VALID_EXT_PINS) diff --git a/ports/esp32/modmachine.c b/ports/esp32/modmachine.c index ea733effff..b8b68fdf8a 100644 --- a/ports/esp32/modmachine.c +++ b/ports/esp32/modmachine.c @@ -108,7 +108,7 @@ STATIC mp_obj_t machine_sleep_helper(wake_type_t wake_type, size_t n_args, const } } - switch(wake_type) { + switch (wake_type) { case MACHINE_WAKE_SLEEP: esp_light_sleep_start(); break; @@ -130,7 +130,7 @@ STATIC mp_obj_t machine_deepsleep(size_t n_args, const mp_obj_t *pos_args, mp_ma STATIC MP_DEFINE_CONST_FUN_OBJ_KW(machine_deepsleep_obj, 0, machine_deepsleep); STATIC mp_obj_t machine_reset_cause(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { - switch(rtc_get_reset_reason(0)) { + switch (rtc_get_reset_reason(0)) { case POWERON_RESET: return MP_OBJ_NEW_SMALL_INT(MP_PWRON_RESET); break; @@ -262,7 +262,7 @@ STATIC MP_DEFINE_CONST_DICT(machine_module_globals, machine_module_globals_table const mp_obj_module_t mp_module_machine = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&machine_module_globals, + .globals = (mp_obj_dict_t *)&machine_module_globals, }; #endif // MICROPY_PY_MACHINE diff --git a/ports/esp32/modmachine.h b/ports/esp32/modmachine.h index c8513a4711..b3e50c80d5 100644 --- a/ports/esp32/modmachine.h +++ b/ports/esp32/modmachine.h @@ -4,7 +4,7 @@ #include "py/obj.h" typedef enum { - //MACHINE_WAKE_IDLE=0x01, + // MACHINE_WAKE_IDLE=0x01, MACHINE_WAKE_SLEEP=0x02, MACHINE_WAKE_DEEPSLEEP=0x04 } wake_type_t; diff --git a/ports/esp32/modnetwork.c b/ports/esp32/modnetwork.c index e2e1560c1a..dd2633b30f 100644 --- a/ports/esp32/modnetwork.c +++ b/ports/esp32/modnetwork.c @@ -54,54 +54,56 @@ #define MODNETWORK_INCLUDE_CONSTANTS (1) NORETURN void _esp_exceptions(esp_err_t e) { - switch (e) { - case ESP_ERR_WIFI_NOT_INIT: - mp_raise_msg(&mp_type_OSError, "Wifi Not Initialized"); - case ESP_ERR_WIFI_NOT_STARTED: - mp_raise_msg(&mp_type_OSError, "Wifi Not Started"); - case ESP_ERR_WIFI_NOT_STOPPED: - mp_raise_msg(&mp_type_OSError, "Wifi Not Stopped"); - case ESP_ERR_WIFI_IF: - mp_raise_msg(&mp_type_OSError, "Wifi Invalid Interface"); - case ESP_ERR_WIFI_MODE: - mp_raise_msg(&mp_type_OSError, "Wifi Invalid Mode"); - case ESP_ERR_WIFI_STATE: - mp_raise_msg(&mp_type_OSError, "Wifi Internal State Error"); - case ESP_ERR_WIFI_CONN: - mp_raise_msg(&mp_type_OSError, "Wifi Internal Error"); - case ESP_ERR_WIFI_NVS: - mp_raise_msg(&mp_type_OSError, "Wifi Internal NVS Error"); - case ESP_ERR_WIFI_MAC: - mp_raise_msg(&mp_type_OSError, "Wifi Invalid MAC Address"); - case ESP_ERR_WIFI_SSID: - mp_raise_msg(&mp_type_OSError, "Wifi SSID Invalid"); - case ESP_ERR_WIFI_PASSWORD: - mp_raise_msg(&mp_type_OSError, "Wifi Invalid Password"); - case ESP_ERR_WIFI_TIMEOUT: - mp_raise_OSError(MP_ETIMEDOUT); - case ESP_ERR_WIFI_WAKE_FAIL: - mp_raise_msg(&mp_type_OSError, "Wifi Wakeup Failure"); - case ESP_ERR_WIFI_WOULD_BLOCK: - mp_raise_msg(&mp_type_OSError, "Wifi Would Block"); - case ESP_ERR_WIFI_NOT_CONNECT: - mp_raise_msg(&mp_type_OSError, "Wifi Not Connected"); - case ESP_ERR_TCPIP_ADAPTER_INVALID_PARAMS: - mp_raise_msg(&mp_type_OSError, "TCP/IP Invalid Parameters"); - case ESP_ERR_TCPIP_ADAPTER_IF_NOT_READY: - mp_raise_msg(&mp_type_OSError, "TCP/IP IF Not Ready"); - case ESP_ERR_TCPIP_ADAPTER_DHCPC_START_FAILED: - mp_raise_msg(&mp_type_OSError, "TCP/IP DHCP Client Start Failed"); - case ESP_ERR_TCPIP_ADAPTER_NO_MEM: - mp_raise_OSError(MP_ENOMEM); - default: - nlr_raise(mp_obj_new_exception_msg_varg( - &mp_type_RuntimeError, "Wifi Unknown Error 0x%04x", e - )); - } + switch (e) { + case ESP_ERR_WIFI_NOT_INIT: + mp_raise_msg(&mp_type_OSError, "Wifi Not Initialized"); + case ESP_ERR_WIFI_NOT_STARTED: + mp_raise_msg(&mp_type_OSError, "Wifi Not Started"); + case ESP_ERR_WIFI_NOT_STOPPED: + mp_raise_msg(&mp_type_OSError, "Wifi Not Stopped"); + case ESP_ERR_WIFI_IF: + mp_raise_msg(&mp_type_OSError, "Wifi Invalid Interface"); + case ESP_ERR_WIFI_MODE: + mp_raise_msg(&mp_type_OSError, "Wifi Invalid Mode"); + case ESP_ERR_WIFI_STATE: + mp_raise_msg(&mp_type_OSError, "Wifi Internal State Error"); + case ESP_ERR_WIFI_CONN: + mp_raise_msg(&mp_type_OSError, "Wifi Internal Error"); + case ESP_ERR_WIFI_NVS: + mp_raise_msg(&mp_type_OSError, "Wifi Internal NVS Error"); + case ESP_ERR_WIFI_MAC: + mp_raise_msg(&mp_type_OSError, "Wifi Invalid MAC Address"); + case ESP_ERR_WIFI_SSID: + mp_raise_msg(&mp_type_OSError, "Wifi SSID Invalid"); + case ESP_ERR_WIFI_PASSWORD: + mp_raise_msg(&mp_type_OSError, "Wifi Invalid Password"); + case ESP_ERR_WIFI_TIMEOUT: + mp_raise_OSError(MP_ETIMEDOUT); + case ESP_ERR_WIFI_WAKE_FAIL: + mp_raise_msg(&mp_type_OSError, "Wifi Wakeup Failure"); + case ESP_ERR_WIFI_WOULD_BLOCK: + mp_raise_msg(&mp_type_OSError, "Wifi Would Block"); + case ESP_ERR_WIFI_NOT_CONNECT: + mp_raise_msg(&mp_type_OSError, "Wifi Not Connected"); + case ESP_ERR_TCPIP_ADAPTER_INVALID_PARAMS: + mp_raise_msg(&mp_type_OSError, "TCP/IP Invalid Parameters"); + case ESP_ERR_TCPIP_ADAPTER_IF_NOT_READY: + mp_raise_msg(&mp_type_OSError, "TCP/IP IF Not Ready"); + case ESP_ERR_TCPIP_ADAPTER_DHCPC_START_FAILED: + mp_raise_msg(&mp_type_OSError, "TCP/IP DHCP Client Start Failed"); + case ESP_ERR_TCPIP_ADAPTER_NO_MEM: + mp_raise_OSError(MP_ENOMEM); + default: + nlr_raise(mp_obj_new_exception_msg_varg( + &mp_type_RuntimeError, "Wifi Unknown Error 0x%04x", e + )); + } } static inline void esp_exceptions(esp_err_t e) { - if (e != ESP_OK) _esp_exceptions(e); + if (e != ESP_OK) { + _esp_exceptions(e); + } } #define ESP_EXCEPTIONS(x) do { esp_exceptions(x); } while (0); @@ -131,67 +133,67 @@ static uint8_t wifi_sta_disconn_reason = 0; // This function is called by the system-event task and so runs in a different // thread to the main MicroPython task. It must not raise any Python exceptions. static esp_err_t event_handler(void *ctx, system_event_t *event) { - switch(event->event_id) { - case SYSTEM_EVENT_STA_START: - ESP_LOGI("wifi", "STA_START"); - break; - case SYSTEM_EVENT_STA_CONNECTED: - ESP_LOGI("network", "CONNECTED"); - break; - case SYSTEM_EVENT_STA_GOT_IP: - ESP_LOGI("network", "GOT_IP"); - wifi_sta_connected = true; - wifi_sta_disconn_reason = 0; // Success so clear error. (in case of new error will be replaced anyway) - break; - case SYSTEM_EVENT_STA_DISCONNECTED: { - // This is a workaround as ESP32 WiFi libs don't currently - // auto-reassociate. - system_event_sta_disconnected_t *disconn = &event->event_info.disconnected; - char *message = ""; - wifi_sta_disconn_reason = disconn->reason; - switch (disconn->reason) { - case WIFI_REASON_BEACON_TIMEOUT: - // AP has dropped out; try to reconnect. - message = "\nbeacon timeout"; - break; - case WIFI_REASON_NO_AP_FOUND: - // AP may not exist, or it may have momentarily dropped out; try to reconnect. - message = "\nno AP found"; - break; - case WIFI_REASON_AUTH_FAIL: - message = "\nauthentication failed"; - wifi_sta_connect_requested = false; - break; - default: - // Let other errors through and try to reconnect. - break; - } - ESP_LOGI("wifi", "STA_DISCONNECTED, reason:%d%s", disconn->reason, message); + switch (event->event_id) { + case SYSTEM_EVENT_STA_START: + ESP_LOGI("wifi", "STA_START"); + break; + case SYSTEM_EVENT_STA_CONNECTED: + ESP_LOGI("network", "CONNECTED"); + break; + case SYSTEM_EVENT_STA_GOT_IP: + ESP_LOGI("network", "GOT_IP"); + wifi_sta_connected = true; + wifi_sta_disconn_reason = 0; // Success so clear error. (in case of new error will be replaced anyway) + break; + case SYSTEM_EVENT_STA_DISCONNECTED: { + // This is a workaround as ESP32 WiFi libs don't currently + // auto-reassociate. + system_event_sta_disconnected_t *disconn = &event->event_info.disconnected; + char *message = ""; + wifi_sta_disconn_reason = disconn->reason; + switch (disconn->reason) { + case WIFI_REASON_BEACON_TIMEOUT: + // AP has dropped out; try to reconnect. + message = "\nbeacon timeout"; + break; + case WIFI_REASON_NO_AP_FOUND: + // AP may not exist, or it may have momentarily dropped out; try to reconnect. + message = "\nno AP found"; + break; + case WIFI_REASON_AUTH_FAIL: + message = "\nauthentication failed"; + wifi_sta_connect_requested = false; + break; + default: + // Let other errors through and try to reconnect. + break; + } + ESP_LOGI("wifi", "STA_DISCONNECTED, reason:%d%s", disconn->reason, message); - bool reconnected = false; - if (wifi_sta_connect_requested) { - wifi_mode_t mode; - if (esp_wifi_get_mode(&mode) == ESP_OK) { - if (mode & WIFI_MODE_STA) { - // STA is active so attempt to reconnect. - esp_err_t e = esp_wifi_connect(); - if (e != ESP_OK) { - ESP_LOGI("wifi", "error attempting to reconnect: 0x%04x", e); - } else { - reconnected = true; + bool reconnected = false; + if (wifi_sta_connect_requested) { + wifi_mode_t mode; + if (esp_wifi_get_mode(&mode) == ESP_OK) { + if (mode & WIFI_MODE_STA) { + // STA is active so attempt to reconnect. + esp_err_t e = esp_wifi_connect(); + if (e != ESP_OK) { + ESP_LOGI("wifi", "error attempting to reconnect: 0x%04x", e); + } else { + reconnected = true; + } } } } + if (wifi_sta_connected && !reconnected) { + // If already connected and we fail to reconnect + wifi_sta_connected = false; + } + break; } - if (wifi_sta_connected && !reconnected) { - // If already connected and we fail to reconnect - wifi_sta_connected = false; - } - break; - } - default: - ESP_LOGI("network", "event %d", event->event_id); - break; + default: + ESP_LOGI("network", "event %d", event->event_id); + break; } return ESP_OK; } @@ -215,8 +217,8 @@ STATIC mp_obj_t get_wlan(size_t n_args, const mp_obj_t *args) { if (!initialized) { wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT(); ESP_LOGD("modnetwork", "Initializing WiFi"); - ESP_EXCEPTIONS( esp_wifi_init(&cfg) ); - ESP_EXCEPTIONS( esp_wifi_set_storage(WIFI_STORAGE_RAM) ); + ESP_EXCEPTIONS(esp_wifi_init(&cfg)); + ESP_EXCEPTIONS(esp_wifi_set_storage(WIFI_STORAGE_RAM)); ESP_LOGD("modnetwork", "Initialized"); initialized = 1; } @@ -238,7 +240,7 @@ STATIC mp_obj_t esp_initialize() { ESP_LOGD("modnetwork", "Initializing TCP/IP"); tcpip_adapter_init(); ESP_LOGD("modnetwork", "Initializing Event Loop"); - ESP_EXCEPTIONS( esp_event_loop_init(event_handler, NULL) ); + ESP_EXCEPTIONS(esp_event_loop_init(event_handler, NULL)); ESP_LOGD("modnetwork", "esp_event_loop_init done"); initialized = 1; } @@ -318,12 +320,12 @@ STATIC mp_obj_t esp_connect(size_t n_args, const mp_obj_t *pos_args, mp_map_t *k wifi_sta_config.sta.bssid_set = 1; memcpy(wifi_sta_config.sta.bssid, p, sizeof(wifi_sta_config.sta.bssid)); } - ESP_EXCEPTIONS( esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_sta_config) ); + ESP_EXCEPTIONS(esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_sta_config)); } // connect to the WiFi AP MP_THREAD_GIL_EXIT(); - ESP_EXCEPTIONS( esp_wifi_connect() ); + ESP_EXCEPTIONS(esp_wifi_connect()); MP_THREAD_GIL_ENTER(); wifi_sta_connect_requested = true; @@ -333,7 +335,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_KW(esp_connect_obj, 1, esp_connect); STATIC mp_obj_t esp_disconnect(mp_obj_t self_in) { wifi_sta_connect_requested = false; - ESP_EXCEPTIONS( esp_wifi_disconnect() ); + ESP_EXCEPTIONS(esp_wifi_disconnect()); return mp_const_none; } @@ -376,7 +378,7 @@ STATIC mp_obj_t esp_status(size_t n_args, const mp_obj_t *args) { require_if(args[0], WIFI_IF_AP); wifi_sta_list_t station_list; ESP_EXCEPTIONS(esp_wifi_ap_get_sta_list(&station_list)); - wifi_sta_info_t *stations = (wifi_sta_info_t*)station_list.sta; + wifi_sta_info_t *stations = (wifi_sta_info_t *)station_list.sta; mp_obj_t list = mp_obj_new_list(0, NULL); for (int i = 0; i < station_list.num; ++i) { mp_obj_tuple_t *t = mp_obj_new_tuple(1, NULL); @@ -410,9 +412,9 @@ STATIC mp_obj_t esp_scan(mp_obj_t self_in) { MP_THREAD_GIL_ENTER(); if (status == 0) { uint16_t count = 0; - ESP_EXCEPTIONS( esp_wifi_scan_get_ap_num(&count) ); + ESP_EXCEPTIONS(esp_wifi_scan_get_ap_num(&count)); wifi_ap_record_t *wifi_ap_records = calloc(count, sizeof(wifi_ap_record_t)); - ESP_EXCEPTIONS( esp_wifi_scan_get_ap_records(&count, wifi_ap_records) ); + ESP_EXCEPTIONS(esp_wifi_scan_get_ap_records(&count, wifi_ap_records)); for (uint16_t i = 0; i < count; i++) { mp_obj_tuple_t *t = mp_obj_new_tuple(6, NULL); uint8_t *x = memchr(wifi_ap_records[i].ssid, 0, sizeof(wifi_ap_records[i].ssid)); @@ -453,10 +455,10 @@ STATIC mp_obj_t esp_ifconfig(size_t n_args, const mp_obj_t *args) { if (n_args == 1) { // get mp_obj_t tuple[4] = { - netutils_format_ipv4_addr((uint8_t*)&info.ip, NETUTILS_BIG), - netutils_format_ipv4_addr((uint8_t*)&info.netmask, NETUTILS_BIG), - netutils_format_ipv4_addr((uint8_t*)&info.gw, NETUTILS_BIG), - netutils_format_ipv4_addr((uint8_t*)&dns_info.ip, NETUTILS_BIG), + netutils_format_ipv4_addr((uint8_t *)&info.ip, NETUTILS_BIG), + netutils_format_ipv4_addr((uint8_t *)&info.netmask, NETUTILS_BIG), + netutils_format_ipv4_addr((uint8_t *)&info.gw, NETUTILS_BIG), + netutils_format_ipv4_addr((uint8_t *)&dns_info.ip, NETUTILS_BIG), }; return mp_obj_new_tuple(4, tuple); } else { @@ -464,28 +466,32 @@ STATIC mp_obj_t esp_ifconfig(size_t n_args, const mp_obj_t *args) { if (MP_OBJ_IS_TYPE(args[1], &mp_type_tuple) || MP_OBJ_IS_TYPE(args[1], &mp_type_list)) { mp_obj_t *items; mp_obj_get_array_fixed_n(args[1], 4, &items); - netutils_parse_ipv4_addr(items[0], (void*)&info.ip, NETUTILS_BIG); + netutils_parse_ipv4_addr(items[0], (void *)&info.ip, NETUTILS_BIG); if (mp_obj_is_integer(items[1])) { // allow numeric netmask, i.e.: // 24 -> 255.255.255.0 // 16 -> 255.255.0.0 // etc... - uint32_t* m = (uint32_t*)&info.netmask; + uint32_t *m = (uint32_t *)&info.netmask; *m = htonl(0xffffffff << (32 - mp_obj_get_int(items[1]))); } else { - netutils_parse_ipv4_addr(items[1], (void*)&info.netmask, NETUTILS_BIG); + netutils_parse_ipv4_addr(items[1], (void *)&info.netmask, NETUTILS_BIG); } - netutils_parse_ipv4_addr(items[2], (void*)&info.gw, NETUTILS_BIG); - netutils_parse_ipv4_addr(items[3], (void*)&dns_info.ip, NETUTILS_BIG); + netutils_parse_ipv4_addr(items[2], (void *)&info.gw, NETUTILS_BIG); + netutils_parse_ipv4_addr(items[3], (void *)&dns_info.ip, NETUTILS_BIG); // To set a static IP we have to disable DHCP first if (self->if_id == WIFI_IF_STA || self->if_id == ESP_IF_ETH) { esp_err_t e = tcpip_adapter_dhcpc_stop(self->if_id); - if (e != ESP_OK && e != ESP_ERR_TCPIP_ADAPTER_DHCP_ALREADY_STOPPED) _esp_exceptions(e); + if (e != ESP_OK && e != ESP_ERR_TCPIP_ADAPTER_DHCP_ALREADY_STOPPED) { + _esp_exceptions(e); + } ESP_EXCEPTIONS(tcpip_adapter_set_ip_info(self->if_id, &info)); ESP_EXCEPTIONS(tcpip_adapter_set_dns_info(self->if_id, TCPIP_ADAPTER_DNS_MAIN, &dns_info)); } else if (self->if_id == WIFI_IF_AP) { esp_err_t e = tcpip_adapter_dhcps_stop(WIFI_IF_AP); - if (e != ESP_OK && e != ESP_ERR_TCPIP_ADAPTER_DHCP_ALREADY_STOPPED) _esp_exceptions(e); + if (e != ESP_OK && e != ESP_ERR_TCPIP_ADAPTER_DHCP_ALREADY_STOPPED) { + _esp_exceptions(e); + } ESP_EXCEPTIONS(tcpip_adapter_set_ip_info(WIFI_IF_AP, &info)); ESP_EXCEPTIONS(tcpip_adapter_set_dns_info(WIFI_IF_AP, TCPIP_ADAPTER_DNS_MAIN, &dns_info)); ESP_EXCEPTIONS(tcpip_adapter_dhcps_start(WIFI_IF_AP)); @@ -573,7 +579,7 @@ STATIC mp_obj_t esp_config(size_t n_args, const mp_obj_t *args, mp_map_t *kwargs default: goto unknown; } - #undef QS +#undef QS // We post-check interface requirements to save on code size if (req_if >= 0) { @@ -605,9 +611,9 @@ STATIC mp_obj_t esp_config(size_t n_args, const mp_obj_t *args, mp_map_t *kwargs } case QS(MP_QSTR_essid): if (self->if_id == WIFI_IF_STA) { - val = mp_obj_new_str((char*)cfg.sta.ssid, strlen((char*)cfg.sta.ssid)); + val = mp_obj_new_str((char *)cfg.sta.ssid, strlen((char *)cfg.sta.ssid)); } else { - val = mp_obj_new_str((char*)cfg.ap.ssid, cfg.ap.ssid_len); + val = mp_obj_new_str((char *)cfg.ap.ssid, cfg.ap.ssid_len); } break; case QS(MP_QSTR_hidden): @@ -631,7 +637,7 @@ STATIC mp_obj_t esp_config(size_t n_args, const mp_obj_t *args, mp_map_t *kwargs default: goto unknown; } - #undef QS +#undef QS // We post-check interface requirements to save on code size if (req_if >= 0) { @@ -679,7 +685,7 @@ STATIC const mp_rom_map_elem_t mp_module_network_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_PPP), MP_ROM_PTR(&ppp_make_new_obj) }, { MP_ROM_QSTR(MP_QSTR_phy_mode), MP_ROM_PTR(&esp_phy_mode_obj) }, -#if MODNETWORK_INCLUDE_CONSTANTS + #if MODNETWORK_INCLUDE_CONSTANTS { MP_ROM_QSTR(MP_QSTR_STA_IF), MP_ROM_INT(WIFI_IF_STA)}, { MP_ROM_QSTR(MP_QSTR_AP_IF), MP_ROM_INT(WIFI_IF_AP)}, @@ -706,12 +712,12 @@ STATIC const mp_rom_map_elem_t mp_module_network_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_STAT_BEACON_TIMEOUT), MP_ROM_INT(WIFI_REASON_BEACON_TIMEOUT)}, { MP_ROM_QSTR(MP_QSTR_STAT_ASSOC_FAIL), MP_ROM_INT(WIFI_REASON_ASSOC_FAIL)}, { MP_ROM_QSTR(MP_QSTR_STAT_HANDSHAKE_TIMEOUT), MP_ROM_INT(WIFI_REASON_HANDSHAKE_TIMEOUT)}, -#endif + #endif }; STATIC MP_DEFINE_CONST_DICT(mp_module_network_globals, mp_module_network_globals_table); const mp_obj_module_t mp_module_network = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_network_globals, + .globals = (mp_obj_dict_t *)&mp_module_network_globals, }; diff --git a/ports/esp32/modsocket.c b/ports/esp32/modsocket.c index 92f9a35b56..99eb272647 100644 --- a/ports/esp32/modsocket.c +++ b/ports/esp32/modsocket.c @@ -182,7 +182,9 @@ int _socket_getaddrinfo(const mp_obj_t addrtuple, struct addrinfo **resp) { mp_uint_t len = 0; mp_obj_t *elem; mp_obj_get_array(addrtuple, &len, &elem); - if (len != 2) return -1; + if (len != 2) { + return -1; + } return _socket_getaddrinfo2(elem[0], elem[1], resp); } @@ -192,16 +194,20 @@ STATIC mp_obj_t socket_bind(const mp_obj_t arg0, const mp_obj_t arg1) { _socket_getaddrinfo(arg1, &res); int r = lwip_bind_r(self->fd, res->ai_addr, res->ai_addrlen); lwip_freeaddrinfo(res); - if (r < 0) exception_from_errno(errno); + if (r < 0) { + exception_from_errno(errno); + } return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_bind_obj, socket_bind); - + STATIC mp_obj_t socket_listen(const mp_obj_t arg0, const mp_obj_t arg1) { socket_obj_t *self = MP_OBJ_TO_PTR(arg0); int backlog = mp_obj_get_int(arg1); int r = lwip_listen_r(self->fd, backlog); - if (r < 0) exception_from_errno(errno); + if (r < 0) { + exception_from_errno(errno); + } return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_listen_obj, socket_listen); @@ -213,15 +219,21 @@ STATIC mp_obj_t socket_accept(const mp_obj_t arg0) { socklen_t addr_len = sizeof(addr); int new_fd = -1; - for (int i=0; i<=self->retries; i++) { + for (int i = 0; i <= self->retries; i++) { MP_THREAD_GIL_EXIT(); new_fd = lwip_accept_r(self->fd, &addr, &addr_len); MP_THREAD_GIL_ENTER(); - if (new_fd >= 0) break; - if (errno != EAGAIN) exception_from_errno(errno); + if (new_fd >= 0) { + break; + } + if (errno != EAGAIN) { + exception_from_errno(errno); + } check_for_exceptions(); } - if (new_fd < 0) mp_raise_OSError(MP_ETIMEDOUT); + if (new_fd < 0) { + mp_raise_OSError(MP_ETIMEDOUT); + } // create new socket object socket_obj_t *sock = m_new_obj_with_finaliser(socket_obj_t); @@ -234,8 +246,8 @@ STATIC mp_obj_t socket_accept(const mp_obj_t arg0) { _socket_settimeout(sock, UINT64_MAX); // make the return value - uint8_t *ip = (uint8_t*)&((struct sockaddr_in*)&addr)->sin_addr; - mp_uint_t port = lwip_ntohs(((struct sockaddr_in*)&addr)->sin_port); + uint8_t *ip = (uint8_t *)&((struct sockaddr_in *)&addr)->sin_addr; + mp_uint_t port = lwip_ntohs(((struct sockaddr_in *)&addr)->sin_port); mp_obj_tuple_t *client = mp_obj_new_tuple(2, NULL); client->items[0] = sock; client->items[1] = netutils_format_inet_addr(ip, port, NETUTILS_BIG); @@ -277,7 +289,7 @@ STATIC mp_obj_t socket_setsockopt(size_t n_args, const mp_obj_t *args) { break; } - #if MICROPY_PY_USOCKET_EVENTS + #if MICROPY_PY_USOCKET_EVENTS // level: SOL_SOCKET // special "register callback" option case 20: { @@ -294,7 +306,7 @@ STATIC mp_obj_t socket_setsockopt(size_t n_args, const mp_obj_t *args) { } break; } - #endif + #endif // level: IPPROTO_IP case IP_ADD_MEMBERSHIP: { @@ -305,7 +317,7 @@ STATIC mp_obj_t socket_setsockopt(size_t n_args, const mp_obj_t *args) { } // POSIX setsockopt has order: group addr, if addr, lwIP has it vice-versa - err_t err = igmp_joingroup((const ip4_addr_t*)bufinfo.buf + 1, bufinfo.buf); + err_t err = igmp_joingroup((const ip4_addr_t *)bufinfo.buf + 1, bufinfo.buf); if (err != ERR_OK) { mp_raise_OSError(-err); } @@ -338,8 +350,9 @@ void _socket_settimeout(socket_obj_t *sock, uint64_t timeout_ms) { STATIC mp_obj_t socket_settimeout(const mp_obj_t arg0, const mp_obj_t arg1) { socket_obj_t *self = MP_OBJ_TO_PTR(arg0); - if (arg1 == mp_const_none) _socket_settimeout(self, UINT64_MAX); - else { + if (arg1 == mp_const_none) { + _socket_settimeout(self, UINT64_MAX); + } else { #if MICROPY_PY_BUILTINS_FLOAT _socket_settimeout(self, mp_obj_get_float(arg1) * 1000L); #else @@ -352,8 +365,11 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_settimeout_obj, socket_settimeout); STATIC mp_obj_t socket_setblocking(const mp_obj_t arg0, const mp_obj_t arg1) { socket_obj_t *self = MP_OBJ_TO_PTR(arg0); - if (mp_obj_is_true(arg1)) _socket_settimeout(self, UINT64_MAX); - else _socket_settimeout(self, 0); + if (mp_obj_is_true(arg1)) { + _socket_settimeout(self, UINT64_MAX); + } else { + _socket_settimeout(self, 0); + } return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_setblocking_obj, socket_setblocking); @@ -411,7 +427,7 @@ STATIC mp_uint_t _socket_read_data(mp_obj_t self_in, void *buf, size_t size, } mp_obj_t _socket_recvfrom(mp_obj_t self_in, mp_obj_t len_in, - struct sockaddr *from, socklen_t *from_len) { + struct sockaddr *from, socklen_t *from_len) { size_t len = mp_obj_get_int(len_in); vstr_t vstr; vstr_init_len(&vstr, len); @@ -438,8 +454,8 @@ STATIC mp_obj_t socket_recvfrom(mp_obj_t self_in, mp_obj_t len_in) { mp_obj_t tuple[2]; tuple[0] = _socket_recvfrom(self_in, len_in, &from, &fromlen); - uint8_t *ip = (uint8_t*)&((struct sockaddr_in*)&from)->sin_addr; - mp_uint_t port = lwip_ntohs(((struct sockaddr_in*)&from)->sin_port); + uint8_t *ip = (uint8_t *)&((struct sockaddr_in *)&from)->sin_addr; + mp_uint_t port = lwip_ntohs(((struct sockaddr_in *)&from)->sin_port); tuple[1] = netutils_format_inet_addr(ip, port, NETUTILS_BIG); return mp_obj_new_tuple(2, tuple); @@ -448,15 +464,21 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_recvfrom_obj, socket_recvfrom); int _socket_send(socket_obj_t *sock, const char *data, size_t datalen) { int sentlen = 0; - for (int i=0; i<=sock->retries && sentlen < datalen; i++) { + for (int i = 0; i <= sock->retries && sentlen < datalen; i++) { MP_THREAD_GIL_EXIT(); - int r = lwip_write_r(sock->fd, data+sentlen, datalen-sentlen); + int r = lwip_write_r(sock->fd, data + sentlen, datalen - sentlen); MP_THREAD_GIL_ENTER(); - if (r < 0 && errno != EWOULDBLOCK) exception_from_errno(errno); - if (r > 0) sentlen += r; + if (r < 0 && errno != EWOULDBLOCK) { + exception_from_errno(errno); + } + if (r > 0) { + sentlen += r; + } check_for_exceptions(); } - if (sentlen == 0) mp_raise_OSError(MP_ETIMEDOUT); + if (sentlen == 0) { + mp_raise_OSError(MP_ETIMEDOUT); + } return sentlen; } @@ -476,7 +498,9 @@ STATIC mp_obj_t socket_sendall(const mp_obj_t arg0, const mp_obj_t arg1) { mp_buffer_info_t bufinfo; mp_get_buffer_raise(arg1, &bufinfo, MP_BUFFER_READ); int r = _socket_send(sock, bufinfo.buf, bufinfo.len); - if (r < bufinfo.len) mp_raise_OSError(MP_ETIMEDOUT); + if (r < bufinfo.len) { + mp_raise_OSError(MP_ETIMEDOUT); + } return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_sendall_obj, socket_sendall); @@ -492,20 +516,22 @@ STATIC mp_obj_t socket_sendto(mp_obj_t self_in, mp_obj_t data_in, mp_obj_t addr_ struct sockaddr_in to; to.sin_len = sizeof(to); to.sin_family = AF_INET; - to.sin_port = lwip_htons(netutils_parse_inet_addr(addr_in, (uint8_t*)&to.sin_addr, NETUTILS_BIG)); + to.sin_port = lwip_htons(netutils_parse_inet_addr(addr_in, (uint8_t *)&to.sin_addr, NETUTILS_BIG)); // send the data - for (int i=0; i<=self->retries; i++) { + for (int i = 0; i <= self->retries; i++) { MP_THREAD_GIL_EXIT(); - int ret = lwip_sendto_r(self->fd, bufinfo.buf, bufinfo.len, 0, (struct sockaddr*)&to, sizeof(to)); + int ret = lwip_sendto_r(self->fd, bufinfo.buf, bufinfo.len, 0, (struct sockaddr *)&to, sizeof(to)); MP_THREAD_GIL_ENTER(); - if (ret > 0) return mp_obj_new_int_from_uint(ret); + if (ret > 0) { + return mp_obj_new_int_from_uint(ret); + } if (ret == -1 && errno != EWOULDBLOCK) { exception_from_errno(errno); } check_for_exceptions(); } - mp_raise_OSError(MP_ETIMEDOUT); + mp_raise_OSError(MP_ETIMEDOUT); } STATIC MP_DEFINE_CONST_FUN_OBJ_3(socket_sendto_obj, socket_sendto); @@ -527,12 +553,17 @@ STATIC mp_uint_t socket_stream_read(mp_obj_t self_in, void *buf, mp_uint_t size, STATIC mp_uint_t socket_stream_write(mp_obj_t self_in, const void *buf, mp_uint_t size, int *errcode) { socket_obj_t *sock = self_in; - for (int i=0; i<=sock->retries; i++) { + for (int i = 0; i <= sock->retries; i++) { MP_THREAD_GIL_EXIT(); int r = lwip_write_r(sock->fd, buf, size); MP_THREAD_GIL_ENTER(); - if (r > 0) return r; - if (r < 0 && errno != EWOULDBLOCK) { *errcode = errno; return MP_STREAM_ERROR; } + if (r > 0) { + return r; + } + if (r < 0 && errno != EWOULDBLOCK) { + *errcode = errno; + return MP_STREAM_ERROR; + } check_for_exceptions(); } *errcode = sock->retries == 0 ? MP_EWOULDBLOCK : MP_ETIMEDOUT; @@ -540,27 +571,42 @@ STATIC mp_uint_t socket_stream_write(mp_obj_t self_in, const void *buf, mp_uint_ } STATIC mp_uint_t socket_stream_ioctl(mp_obj_t self_in, mp_uint_t request, uintptr_t arg, int *errcode) { - socket_obj_t * socket = self_in; + socket_obj_t *socket = self_in; if (request == MP_STREAM_POLL) { - fd_set rfds; FD_ZERO(&rfds); - fd_set wfds; FD_ZERO(&wfds); - fd_set efds; FD_ZERO(&efds); + fd_set rfds; + FD_ZERO(&rfds); + fd_set wfds; + FD_ZERO(&wfds); + fd_set efds; + FD_ZERO(&efds); struct timeval timeout = { .tv_sec = 0, .tv_usec = 0 }; - if (arg & MP_STREAM_POLL_RD) FD_SET(socket->fd, &rfds); - if (arg & MP_STREAM_POLL_WR) FD_SET(socket->fd, &wfds); - if (arg & MP_STREAM_POLL_HUP) FD_SET(socket->fd, &efds); + if (arg & MP_STREAM_POLL_RD) { + FD_SET(socket->fd, &rfds); + } + if (arg & MP_STREAM_POLL_WR) { + FD_SET(socket->fd, &wfds); + } + if (arg & MP_STREAM_POLL_HUP) { + FD_SET(socket->fd, &efds); + } - int r = select((socket->fd)+1, &rfds, &wfds, &efds, &timeout); + int r = select((socket->fd) + 1, &rfds, &wfds, &efds, &timeout); if (r < 0) { *errcode = MP_EIO; return MP_STREAM_ERROR; } mp_uint_t ret = 0; - if (FD_ISSET(socket->fd, &rfds)) ret |= MP_STREAM_POLL_RD; - if (FD_ISSET(socket->fd, &wfds)) ret |= MP_STREAM_POLL_WR; - if (FD_ISSET(socket->fd, &efds)) ret |= MP_STREAM_POLL_HUP; + if (FD_ISSET(socket->fd, &rfds)) { + ret |= MP_STREAM_POLL_RD; + } + if (FD_ISSET(socket->fd, &wfds)) { + ret |= MP_STREAM_POLL_WR; + } + if (FD_ISSET(socket->fd, &efds)) { + ret |= MP_STREAM_POLL_HUP; + } return ret; } else if (request == MP_STREAM_CLOSE) { if (socket->fd >= 0) { @@ -664,7 +710,7 @@ STATIC mp_obj_t esp_socket_getaddrinfo(size_t n_args, const mp_obj_t *args) { mp_obj_new_str(resi->ai_canonname, strlen(resi->ai_canonname)), mp_const_none }; - + if (resi->ai_family == AF_INET) { struct sockaddr_in *addr = (struct sockaddr_in *)resi->ai_addr; // This looks odd, but it's really just a u32_t @@ -680,7 +726,9 @@ STATIC mp_obj_t esp_socket_getaddrinfo(size_t n_args, const mp_obj_t *args) { mp_obj_list_append(ret_list, mp_obj_new_tuple(5, addrinfo_objs)); } - if (res) lwip_freeaddrinfo(res); + if (res) { + lwip_freeaddrinfo(res); + } return ret_list; } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(esp_socket_getaddrinfo_obj, 2, 6, esp_socket_getaddrinfo); @@ -719,5 +767,5 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_socket_globals, mp_module_socket_globals_t const mp_obj_module_t mp_module_usocket = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_socket_globals, + .globals = (mp_obj_dict_t *)&mp_module_socket_globals, }; diff --git a/ports/esp32/moduos.c b/ports/esp32/moduos.c index dc85136f3d..1548e4c7eb 100644 --- a/ports/esp32/moduos.c +++ b/ports/esp32/moduos.c @@ -61,7 +61,7 @@ STATIC MP_DEFINE_ATTRTUPLE( (mp_obj_t)&os_uname_info_release_obj, (mp_obj_t)&os_uname_info_version_obj, (mp_obj_t)&os_uname_info_machine_obj -); + ); STATIC mp_obj_t os_uname(void) { return (mp_obj_t)&os_uname_info_obj; @@ -130,5 +130,5 @@ STATIC MP_DEFINE_CONST_DICT(os_module_globals, os_module_globals_table); const mp_obj_module_t uos_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&os_module_globals, + .globals = (mp_obj_dict_t *)&os_module_globals, }; diff --git a/ports/esp32/modutime.c b/ports/esp32/modutime.c index 002854298b..ec075a11b2 100644 --- a/ports/esp32/modutime.c +++ b/ports/esp32/modutime.c @@ -70,8 +70,8 @@ STATIC mp_obj_t time_mktime(mp_obj_t tuple) { } return mp_obj_new_int_from_uint(timeutils_mktime(mp_obj_get_int(elem[0]), - mp_obj_get_int(elem[1]), mp_obj_get_int(elem[2]), mp_obj_get_int(elem[3]), - mp_obj_get_int(elem[4]), mp_obj_get_int(elem[5]))); + mp_obj_get_int(elem[1]), mp_obj_get_int(elem[2]), mp_obj_get_int(elem[3]), + mp_obj_get_int(elem[4]), mp_obj_get_int(elem[5]))); } STATIC MP_DEFINE_CONST_FUN_OBJ_1(time_mktime_obj, time_mktime); @@ -102,5 +102,5 @@ STATIC MP_DEFINE_CONST_DICT(time_module_globals, time_module_globals_table); const mp_obj_module_t utime_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&time_module_globals, + .globals = (mp_obj_dict_t *)&time_module_globals, }; diff --git a/ports/esp32/mpconfigport.h b/ports/esp32/mpconfigport.h index 0f8deb11c3..4cde0cf0db 100644 --- a/ports/esp32/mpconfigport.h +++ b/ports/esp32/mpconfigport.h @@ -217,7 +217,7 @@ extern const struct _mp_obj_module_t mp_module_onewire; // type definitions for the specific machine #define BYTES_PER_WORD (4) -#define MICROPY_MAKE_POINTER_CALLABLE(p) ((void*)((mp_uint_t)(p))) +#define MICROPY_MAKE_POINTER_CALLABLE(p) ((void *)((mp_uint_t)(p))) #define MP_PLAT_PRINT_STRN(str, len) mp_hal_stdout_tx_strn_cooked(str, len) #define MP_SSIZE_MAX (0x7fffffff) @@ -249,7 +249,7 @@ extern const struct _mp_obj_module_t mp_module_onewire; extern void mp_handle_pending(void); \ mp_handle_pending(); \ MICROPY_PY_USOCKET_EVENTS_HANDLER \ - asm("waiti 0"); \ + asm ("waiti 0"); \ } while (0); #endif diff --git a/ports/esp32/mphalport.h b/ports/esp32/mphalport.h index b829627792..e0adc0d57f 100644 --- a/ports/esp32/mphalport.h +++ b/ports/esp32/mphalport.h @@ -41,9 +41,9 @@ extern ringbuf_t stdin_ringbuf; uint32_t mp_hal_ticks_us(void); __attribute__((always_inline)) static inline uint32_t mp_hal_ticks_cpu(void) { - uint32_t ccount; - __asm__ __volatile__("rsr %0,ccount":"=a" (ccount)); - return ccount; + uint32_t ccount; + __asm__ __volatile__ ("rsr %0,ccount" : "=a" (ccount)); + return ccount; } void mp_hal_delay_us(uint32_t); diff --git a/ports/esp32/mpthreadport.c b/ports/esp32/mpthreadport.c index 52d4d7ff4d..33296133f4 100644 --- a/ports/esp32/mpthreadport.c +++ b/ports/esp32/mpthreadport.c @@ -72,7 +72,7 @@ void mp_thread_init(void *stack, uint32_t stack_len) { void mp_thread_gc_others(void) { mp_thread_mutex_lock(&thread_mutex, 1); for (thread_t *th = thread; th != NULL; th = th->next) { - gc_collect_root((void**)&th, 1); + gc_collect_root((void **)&th, 1); gc_collect_root(&th->arg, 1); // probably not needed if (th->id == xTaskGetCurrentTaskHandle()) { continue; @@ -104,17 +104,18 @@ void mp_thread_start(void) { mp_thread_mutex_unlock(&thread_mutex); } -STATIC void *(*ext_thread_entry)(void*) = NULL; +STATIC void *(*ext_thread_entry)(void *) = NULL; STATIC void freertos_entry(void *arg) { if (ext_thread_entry) { ext_thread_entry(arg); } vTaskDelete(NULL); - for (;;); + for (;;) {; + } } -void mp_thread_create_ex(void *(*entry)(void*), void *arg, size_t *stack_size, int priority, char *name) { +void mp_thread_create_ex(void *(*entry)(void *), void *arg, size_t *stack_size, int priority, char *name) { // store thread entry function into a global variable so we can access it ext_thread_entry = entry; @@ -150,7 +151,7 @@ void mp_thread_create_ex(void *(*entry)(void*), void *arg, size_t *stack_size, i mp_thread_mutex_unlock(&thread_mutex); } -void mp_thread_create(void *(*entry)(void*), void *arg, size_t *stack_size) { +void mp_thread_create(void *(*entry)(void *), void *arg, size_t *stack_size) { mp_thread_create_ex(entry, arg, stack_size, MP_THREAD_PRIORITY, "mp_thread"); } @@ -170,7 +171,7 @@ void vPortCleanUpTCB(void *tcb) { mp_thread_mutex_lock(&thread_mutex, 1); for (thread_t *th = thread; th != NULL; prev = th, th = th->next) { // unlink the node from the list - if ((void*)th->id == tcb) { + if ((void *)th->id == tcb) { if (prev != NULL) { prev->next = th->next; } else { @@ -190,7 +191,7 @@ void mp_thread_mutex_init(mp_thread_mutex_t *mutex) { } int mp_thread_mutex_lock(mp_thread_mutex_t *mutex, int wait) { - return (pdTRUE == xSemaphoreTake(mutex->handle, wait ? portMAX_DELAY : 0)); + return pdTRUE == xSemaphoreTake(mutex->handle, wait ? portMAX_DELAY : 0); } void mp_thread_mutex_unlock(mp_thread_mutex_t *mutex) { diff --git a/ports/esp32/network_lan.c b/ports/esp32/network_lan.c index fba4de73ab..6ba716d76d 100644 --- a/ports/esp32/network_lan.c +++ b/ports/esp32/network_lan.c @@ -54,7 +54,7 @@ const mp_obj_type_t lan_if_type; STATIC lan_if_obj_t lan_obj = {{&lan_if_type}, ESP_IF_ETH, false, false}; STATIC void phy_power_enable(bool enable) { - lan_if_obj_t* self = &lan_obj; + lan_if_obj_t *self = &lan_obj; if (self->phy_power_pin != -1) { @@ -82,13 +82,13 @@ STATIC void phy_power_enable(bool enable) { } STATIC void init_lan_rmii() { - lan_if_obj_t* self = &lan_obj; + lan_if_obj_t *self = &lan_obj; phy_rmii_configure_data_interface_pins(); phy_rmii_smi_configure_pins(self->mdc_pin, self->mdio_pin); } STATIC mp_obj_t get_lan(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { - lan_if_obj_t* self = &lan_obj; + lan_if_obj_t *self = &lan_obj; if (self->initialized) { return MP_OBJ_FROM_PTR(&lan_obj); @@ -199,5 +199,5 @@ STATIC MP_DEFINE_CONST_DICT(lan_if_locals_dict, lan_if_locals_dict_table); const mp_obj_type_t lan_if_type = { { &mp_type_type }, .name = MP_QSTR_LAN, - .locals_dict = (mp_obj_dict_t*)&lan_if_locals_dict, + .locals_dict = (mp_obj_dict_t *)&lan_if_locals_dict, }; diff --git a/ports/esp32/network_ppp.c b/ports/esp32/network_ppp.c index 27dd5e0437..3b807cf898 100644 --- a/ports/esp32/network_ppp.c +++ b/ports/esp32/network_ppp.c @@ -56,7 +56,7 @@ typedef struct _ppp_if_obj_t { const mp_obj_type_t ppp_if_type; static void ppp_status_cb(ppp_pcb *pcb, int err_code, void *ctx) { - ppp_if_obj_t* self = ctx; + ppp_if_obj_t *self = ctx; struct netif *pppif = ppp_netif(self->pcb); switch (err_code) { @@ -98,14 +98,14 @@ static u32_t ppp_output_callback(ppp_pcb *pcb, u8_t *data, u32_t len, void *ctx) } static void pppos_client_task(void *self_in) { - ppp_if_obj_t *self = (ppp_if_obj_t*)self_in; + ppp_if_obj_t *self = (ppp_if_obj_t *)self_in; uint8_t buf[256]; while (ulTaskNotifyTake(pdTRUE, 0) == 0) { int err; int len = mp_stream_rw(self->stream, buf, sizeof(buf), &err, 0); if (len > 0) { - pppos_input_tcpip(self->pcb, (u8_t*)buf, len); + pppos_input_tcpip(self->pcb, (u8_t *)buf, len); } } vTaskDelete(NULL); @@ -158,7 +158,7 @@ STATIC mp_obj_t ppp_active(size_t n_args, const mp_obj_t *args) { STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(ppp_active_obj, 1, 2, ppp_active); STATIC mp_obj_t ppp_delete(mp_obj_t self_in) { - ppp_if_obj_t* self = MP_OBJ_TO_PTR(self_in); + ppp_if_obj_t *self = MP_OBJ_TO_PTR(self_in); mp_obj_t args[] = {self, mp_const_false}; ppp_active(2, args); return mp_const_none; @@ -174,10 +174,10 @@ STATIC mp_obj_t ppp_ifconfig(size_t n_args, const mp_obj_t *args) { dns = dns_getserver(0); struct netif *pppif = ppp_netif(self->pcb); mp_obj_t tuple[4] = { - netutils_format_ipv4_addr((uint8_t*)&pppif->ip_addr, NETUTILS_BIG), - netutils_format_ipv4_addr((uint8_t*)&pppif->gw, NETUTILS_BIG), - netutils_format_ipv4_addr((uint8_t*)&pppif->netmask, NETUTILS_BIG), - netutils_format_ipv4_addr((uint8_t*)&dns, NETUTILS_BIG), + netutils_format_ipv4_addr((uint8_t *)&pppif->ip_addr, NETUTILS_BIG), + netutils_format_ipv4_addr((uint8_t *)&pppif->gw, NETUTILS_BIG), + netutils_format_ipv4_addr((uint8_t *)&pppif->netmask, NETUTILS_BIG), + netutils_format_ipv4_addr((uint8_t *)&dns, NETUTILS_BIG), }; return mp_obj_new_tuple(4, tuple); } else { @@ -187,7 +187,7 @@ STATIC mp_obj_t ppp_ifconfig(size_t n_args, const mp_obj_t *args) { } else { mp_obj_t *items; mp_obj_get_array_fixed_n(args[1], 4, &items); - netutils_parse_ipv4_addr(items[3], (uint8_t*)&dns.u_addr.ip4, NETUTILS_BIG); + netutils_parse_ipv4_addr(items[3], (uint8_t *)&dns.u_addr.ip4, NETUTILS_BIG); dns_setserver(0, &dns); return mp_const_none; } @@ -217,5 +217,5 @@ STATIC MP_DEFINE_CONST_DICT(ppp_if_locals_dict, ppp_if_locals_dict_table); const mp_obj_type_t ppp_if_type = { { &mp_type_type }, .name = MP_QSTR_PPP, - .locals_dict = (mp_obj_dict_t*)&ppp_if_locals_dict, + .locals_dict = (mp_obj_dict_t *)&ppp_if_locals_dict, }; diff --git a/ports/esp32/qstrdefsport.h b/ports/esp32/qstrdefsport.h index ff6c2cc426..06a40c4f6e 100644 --- a/ports/esp32/qstrdefsport.h +++ b/ports/esp32/qstrdefsport.h @@ -27,4 +27,4 @@ // qstrs specific to this port, only needed if they aren't auto-generated // Entries for sys.path -Q(/lib) +Q(/ lib) diff --git a/ports/esp8266/esp_init_data.c b/ports/esp8266/esp_init_data.c index b14de573a7..eb4d99ebda 100644 --- a/ports/esp8266/esp_init_data.c +++ b/ports/esp8266/esp_init_data.c @@ -36,20 +36,20 @@ void ets_printf(const char *fmt, ...); extern char flashchip; static const uint8_t default_init_data[] __attribute__((aligned(4))) = { -0x05, 0x00, 0x04, 0x02, 0x05, 0x05, 0x05, 0x02, 0x05, 0x00, 0x04, 0x05, 0x05, 0x04, 0x05, 0x05, -0x04, 0xfe, 0xfd, 0xff, 0xf0, 0xf0, 0xf0, 0xe0, 0xe0, 0xe0, 0xe1, 0x0a, 0xff, 0xff, 0xf8, 0x00, -0xf8, 0xf8, 0x52, 0x4e, 0x4a, 0x44, 0x40, 0x38, 0x00, 0x00, 0x01, 0x01, 0x02, 0x03, 0x04, 0x05, -0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0xe1, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x93, 0x43, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, -0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 + 0x05, 0x00, 0x04, 0x02, 0x05, 0x05, 0x05, 0x02, 0x05, 0x00, 0x04, 0x05, 0x05, 0x04, 0x05, 0x05, + 0x04, 0xfe, 0xfd, 0xff, 0xf0, 0xf0, 0xf0, 0xe0, 0xe0, 0xe0, 0xe1, 0x0a, 0xff, 0xff, 0xf8, 0x00, + 0xf8, 0xf8, 0x52, 0x4e, 0x4a, 0x44, 0x40, 0x38, 0x00, 0x00, 0x01, 0x01, 0x02, 0x03, 0x04, 0x05, + 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0xe1, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x93, 0x43, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; void firmware_start(void) { // For SDK 1.5.2, either address has shifted and not mirrored in // eagle.rom.addr.v6.ld, or extra initial member was added. - SpiFlashChip *flash = (SpiFlashChip*)(&flashchip + 4); + SpiFlashChip *flash = (SpiFlashChip *)(&flashchip + 4); char buf[128]; SPIRead(flash->chip_size - 4 * 0x1000, buf, sizeof(buf)); @@ -73,5 +73,5 @@ void firmware_start(void) { SPIWrite(flash->chip_size - 4 * 0x1000, buf, sizeof(buf)); } - asm("j call_user_start"); + asm ("j call_user_start"); } diff --git a/ports/esp8266/esp_mphal.c b/ports/esp8266/esp_mphal.c index df97a73430..2ff8e19017 100644 --- a/ports/esp8266/esp_mphal.c +++ b/ports/esp8266/esp_mphal.c @@ -43,7 +43,7 @@ const mp_print_t mp_debug_print = {NULL, mp_hal_debug_tx_strn_cooked}; int uart_attached_to_dupterm; void mp_hal_init(void) { - //ets_wdt_disable(); // it's a pain while developing + // ets_wdt_disable(); // it's a pain while developing mp_hal_rtc_init(); uart_init(UART_BIT_RATE_115200, UART_BIT_RATE_115200); uart_attached_to_dupterm = 0; @@ -65,7 +65,7 @@ int mp_hal_stdin_rx_chr(void) { #if 0 // Idles CPU but need more testing before enabling if (!ets_loop_iter()) { - asm("waiti 0"); + asm ("waiti 0"); } #else mp_hal_delay_us(1); @@ -179,7 +179,7 @@ void mp_hal_signal_dupterm_input(void) { void *ets_get_esf_buf_ctlblk(void) { // Get literal ptr before start of esf_rx_buf_alloc func extern void *esf_rx_buf_alloc(); - return ((void**)esf_rx_buf_alloc)[-1]; + return ((void **)esf_rx_buf_alloc)[-1]; } // Get number of esf_buf free buffers of given type, as encoded by index @@ -188,10 +188,10 @@ void *ets_get_esf_buf_ctlblk(void) { // 1 - tx buffer, 5 - management frame tx buffer; 8 - rx buffer int ets_esf_free_bufs(int idx) { uint32_t *p = ets_get_esf_buf_ctlblk(); - uint32_t *b = (uint32_t*)p[idx]; + uint32_t *b = (uint32_t *)p[idx]; int cnt = 0; while (b) { - b = (uint32_t*)b[0x20 / 4]; + b = (uint32_t *)b[0x20 / 4]; cnt++; } return cnt; diff --git a/ports/esp8266/esp_mphal.h b/ports/esp8266/esp_mphal.h index 8712a2a33b..eaae18f6fe 100644 --- a/ports/esp8266/esp_mphal.h +++ b/ports/esp8266/esp_mphal.h @@ -48,9 +48,9 @@ void mp_hal_rtc_init(void); uint32_t mp_hal_ticks_us(void); __attribute__((always_inline)) static inline uint32_t mp_hal_ticks_cpu(void) { - uint32_t ccount; - __asm__ __volatile__("rsr %0,ccount":"=a" (ccount)); - return ccount; + uint32_t ccount; + __asm__ __volatile__ ("rsr %0,ccount" : "=a" (ccount)); + return ccount; } void mp_hal_delay_us(uint32_t); @@ -86,16 +86,16 @@ void mp_hal_pin_open_drain(mp_hal_pin_obj_t pin); #define mp_hal_pin_od_low(p) do { \ if ((p) == 16) { WRITE_PERI_REG(RTC_GPIO_ENABLE, (READ_PERI_REG(RTC_GPIO_ENABLE) & ~1) | 1); } \ else { gpio_output_set(0, 1 << (p), 1 << (p), 0); } \ - } while (0) +} while (0) #define mp_hal_pin_od_high(p) do { \ if ((p) == 16) { WRITE_PERI_REG(RTC_GPIO_ENABLE, (READ_PERI_REG(RTC_GPIO_ENABLE) & ~1)); } \ else { gpio_output_set(0, 0, 0, 1 << (p)); /* set as input to avoid glitches */ } \ - } while (0) +} while (0) // The DHT driver requires using the open-drain feature of the GPIO to get it to work reliably #define mp_hal_pin_od_high_dht(p) do { \ if ((p) == 16) { WRITE_PERI_REG(RTC_GPIO_ENABLE, (READ_PERI_REG(RTC_GPIO_ENABLE) & ~1)); } \ else { gpio_output_set(1 << (p), 0, 1 << (p), 0); } \ - } while (0) +} while (0) #define mp_hal_pin_read(p) pin_get(p) #define mp_hal_pin_write(p, v) pin_set((p), (v)) diff --git a/ports/esp8266/espapa102.c b/ports/esp8266/espapa102.c index 4295fe42d8..2bea26609a 100644 --- a/ports/esp8266/espapa102.c +++ b/ports/esp8266/espapa102.c @@ -33,7 +33,7 @@ #include "user_interface.h" #include "espapa102.h" -#define NOP asm volatile(" nop \n\t") +#define NOP asm volatile (" nop \n\t") static inline void _esp_apa102_send_byte(uint32_t clockPinMask, uint32_t dataPinMask, uint8_t byte) { for (uint32_t i = 0; i < 8; i++) { diff --git a/ports/esp8266/espneopixel.c b/ports/esp8266/espneopixel.c index 6c76591865..d2166a8b06 100644 --- a/ports/esp8266/espneopixel.c +++ b/ports/esp8266/espneopixel.c @@ -18,48 +18,58 @@ void /*ICACHE_RAM_ATTR*/ esp_neopixel_write(uint8_t pin, uint8_t *pixels, uint32_t numBytes, bool is800KHz) { - uint8_t *p, *end, pix, mask; - uint32_t t, time0, time1, period, c, startTime, pinMask; + uint8_t *p, *end, pix, mask; + uint32_t t, time0, time1, period, c, startTime, pinMask; - pinMask = 1 << pin; - p = pixels; - end = p + numBytes; - pix = *p++; - mask = 0x80; - startTime = 0; + pinMask = 1 << pin; + p = pixels; + end = p + numBytes; + pix = *p++; + mask = 0x80; + startTime = 0; - uint32_t fcpu = system_get_cpu_freq() * 1000000; + uint32_t fcpu = system_get_cpu_freq() * 1000000; -#ifdef NEO_KHZ400 - if(is800KHz) { -#endif - time0 = fcpu / 2857143; // 0.35us - time1 = fcpu / 1250000; // 0.8us - period = fcpu / 800000; // 1.25us per bit -#ifdef NEO_KHZ400 - } else { // 400 KHz bitstream - time0 = fcpu / 2000000; // 0.5uS - time1 = fcpu / 833333; // 1.2us - period = fcpu / 400000; // 2.5us per bit - } -#endif + #ifdef NEO_KHZ400 + if (is800KHz) { + #endif + time0 = fcpu / 2857143; // 0.35us + time1 = fcpu / 1250000; // 0.8us + period = fcpu / 800000; // 1.25us per bit + #ifdef NEO_KHZ400 +} else { // 400 KHz bitstream + time0 = fcpu / 2000000; // 0.5uS + time1 = fcpu / 833333; // 1.2us + period = fcpu / 400000; // 2.5us per bit +} + #endif - uint32_t irq_state = mp_hal_quiet_timing_enter(); - for(t = time0;; t = time0) { - if(pix & mask) t = time1; // Bit high duration - while(((c = mp_hal_ticks_cpu()) - startTime) < period); // Wait for bit start - GPIO_REG_WRITE(GPIO_OUT_W1TS_ADDRESS, pinMask); // Set high - startTime = c; // Save start time - while(((c = mp_hal_ticks_cpu()) - startTime) < t); // Wait high duration - GPIO_REG_WRITE(GPIO_OUT_W1TC_ADDRESS, pinMask); // Set low - if(!(mask >>= 1)) { // Next bit/byte - if(p >= end) break; - pix = *p++; - mask = 0x80; + uint32_t irq_state = mp_hal_quiet_timing_enter(); + for (t = time0;; t = time0) { + if (pix & mask) { + t = time1; // Bit high duration + } + while (((c = mp_hal_ticks_cpu()) - startTime) < period) { + ; // Wait for bit start + } + GPIO_REG_WRITE(GPIO_OUT_W1TS_ADDRESS, pinMask); // Set high + startTime = c; // Save start time + while (((c = mp_hal_ticks_cpu()) - startTime) < t) { + ; // Wait high duration + } + GPIO_REG_WRITE(GPIO_OUT_W1TC_ADDRESS, pinMask); // Set low + if (!(mask >>= 1)) { // Next bit/byte + if (p >= end) { + break; + } + pix = *p++; + mask = 0x80; + } } - } - while((mp_hal_ticks_cpu() - startTime) < period); // Wait for last bit - mp_hal_quiet_timing_exit(irq_state); + while ((mp_hal_ticks_cpu() - startTime) < period) { + ; // Wait for last bit + } + mp_hal_quiet_timing_exit(irq_state); } #endif // MICROPY_ESP8266_NEOPIXEL diff --git a/ports/esp8266/esppwm.c b/ports/esp8266/esppwm.c index 33eaf3b9a1..6116a46895 100644 --- a/ports/esp8266/esppwm.c +++ b/ports/esp8266/esppwm.c @@ -20,7 +20,7 @@ #include "py/mpprint.h" #define PWM_DBG(...) -//#define PWM_DBG(...) mp_printf(&mp_plat_print, __VA_ARGS__) +// #define PWM_DBG(...) mp_printf(&mp_plat_print, __VA_ARGS__) #define ICACHE_RAM_ATTR // __attribute__((section(".text"))) @@ -58,15 +58,15 @@ STATIC uint8_t pwm_current_channel = 0; STATIC uint16_t pwm_gpio = 0; STATIC uint8_t pwm_channel_num = 0; -//XXX: 0xffffffff/(80000000/16)=35A +// XXX: 0xffffffff/(80000000/16)=35A #define US_TO_RTC_TIMER_TICKS(t) \ ((t) ? \ - (((t) > 0x35A) ? \ - (((t)>>2) * ((APB_CLK_FREQ>>4)/250000) + ((t)&0x3) * ((APB_CLK_FREQ>>4)/1000000)) : \ - (((t) *(APB_CLK_FREQ>>4)) / 1000000)) : \ - 0) + (((t) > 0x35A) ? \ + (((t) >> 2) * ((APB_CLK_FREQ >> 4) / 250000) + ((t) & 0x3) * ((APB_CLK_FREQ >> 4) / 1000000)) : \ + (((t) * (APB_CLK_FREQ >> 4)) / 1000000)) : \ + 0) -//FRC1 +// FRC1 #define FRC1_ENABLE_TIMER BIT7 typedef enum { @@ -81,8 +81,7 @@ typedef enum { } TIMER_INT_MODE; STATIC void ICACHE_FLASH_ATTR -pwm_insert_sort(struct pwm_single_param pwm[], uint8 n) -{ +pwm_insert_sort(struct pwm_single_param pwm[], uint8 n) { uint8 i; for (i = 1; i < n; i++) { @@ -109,17 +108,16 @@ pwm_insert_sort(struct pwm_single_param pwm[], uint8 n) STATIC volatile uint8 critical = 0; #define LOCK_PWM(c) do { \ - while( (c)==1 ); \ - (c) = 1; \ + while ((c) == 1); \ + (c) = 1; \ } while (0) #define UNLOCK_PWM(c) do { \ - (c) = 0; \ + (c) = 0; \ } while (0) void ICACHE_FLASH_ATTR -pwm_start(void) -{ +pwm_start(void) { uint8 i, j; PWM_DBG("--Function pwm_start() is called\n"); PWM_DBG("pwm_gpio:%x,pwm_channel_num:%d\n",pwm_gpio,pwm_channel_num); @@ -169,7 +167,7 @@ pwm_start(void) } // step 5: last channel needs to clean - local_single[*local_channel-1].gpio_clear = 0; + local_single[*local_channel - 1].gpio_clear = 0; // step 6: if first channel duty is 0, remove it if (local_single[0].h_time == 0) { @@ -212,17 +210,17 @@ pwm_start(void) * Returns : NONE *******************************************************************************/ void ICACHE_FLASH_ATTR -pwm_set_duty(int16_t duty, uint8 channel) -{ +pwm_set_duty(int16_t duty, uint8 channel) { uint8 i; - for(i=0;i PWM_FREQ_MAX) { pwm.freq = PWM_FREQ_MAX; @@ -264,17 +261,17 @@ pwm_set_freq(uint16 freq, uint8 channel) * Returns : NONE *******************************************************************************/ uint16 ICACHE_FLASH_ATTR -pwm_get_duty(uint8 channel) -{ +pwm_get_duty(uint8 channel) { uint8 i; - for(i=0;i= 010500 -# define FIRST_PRIO 0 +#define FIRST_PRIO 0 #else -# define FIRST_PRIO 0x14 +#define FIRST_PRIO 0x14 #endif #define LAST_PRIO 0x20 #define PRIO2ID(prio) ((prio) - FIRST_PRIO) @@ -38,7 +38,9 @@ static inline int prio2id(uint8_t prio) { int id = PRIO2ID(prio); if (id < 0 || id >= MP_ARRAY_SIZE(emu_tasks)) { printf("task prio out of range: %d\n", prio); - while (1); + while (1) { + ; + } } return id; } @@ -62,9 +64,9 @@ void dump_tasks(void) { bool ets_task(os_task_t task, uint8 prio, os_event_t *queue, uint8 qlen) { static unsigned cnt; printf("#%d ets_task(%p, %d, %p, %d)\n", cnt++, task, prio, queue, qlen); -#if USE_ETS_TASK + #if USE_ETS_TASK return _ets_task(task, prio, queue, qlen); -#else + #else int id = prio2id(prio); emu_tasks[id].task = task; emu_tasks[id].queue = queue; @@ -72,14 +74,14 @@ bool ets_task(os_task_t task, uint8 prio, os_event_t *queue, uint8 qlen) { emu_tasks[id].i_get = 0; emu_tasks[id].i_put = 0; return true; -#endif + #endif } bool ets_post(uint8 prio, os_signal_t sig, os_param_t param) { // static unsigned cnt; printf("#%d ets_post(%d, %x, %x)\n", cnt++, prio, sig, param); -#if USE_ETS_TASK + #if USE_ETS_TASK return _ets_post(prio, sig, param); -#else + #else ets_intr_lock(); const int id = prio2id(prio); @@ -99,13 +101,13 @@ bool ets_post(uint8 prio, os_signal_t sig, os_param_t param) { // queue got full emu_tasks[id].i_put = -1; } - //printf("after ets_post: "); dump_task(prio, &emu_tasks[id]); - //dump_tasks(); + // printf("after ets_post: "); dump_task(prio, &emu_tasks[id]); + // dump_tasks(); ets_intr_unlock(); return 0; -#endif + #endif } int ets_loop_iter_disable = 0; @@ -135,17 +137,17 @@ bool ets_loop_iter(void) { extern uint32_t pend_flag_noise_check; uint32_t *sw_wdt = &pend_flag_noise_check - 6; - //static unsigned cnt; + // static unsigned cnt; bool progress = false; for (volatile struct task_entry *t = emu_tasks; t < &emu_tasks[MP_ARRAY_SIZE(emu_tasks)]; t++) { if (!ets_loop_dont_feed_sw_wdt) { system_soft_wdt_feed(); } ets_intr_lock(); - //printf("etc_loop_iter: "); dump_task(t - emu_tasks + FIRST_PRIO, t); + // printf("etc_loop_iter: "); dump_task(t - emu_tasks + FIRST_PRIO, t); if (t->i_get != t->i_put) { progress = true; - //printf("#%d Calling task %d(%p) (%x, %x)\n", cnt++, + // printf("#%d Calling task %d(%p) (%x, %x)\n", cnt++, // t - emu_tasks + FIRST_PRIO, t->task, t->queue[t->i_get].sig, t->queue[t->i_get].par); int idx = t->i_get; if (t->i_put == -1) { @@ -154,15 +156,15 @@ bool ets_loop_iter(void) { if (++t->i_get == t->qlen) { t->i_get = 0; } - //ets_intr_unlock(); + // ets_intr_unlock(); uint32_t old_sw_wdt = *sw_wdt; t->task(&t->queue[idx]); if (ets_loop_dont_feed_sw_wdt) { // Restore previous SW WDT counter, in case task fed/cleared it *sw_wdt = old_sw_wdt; } - //ets_intr_lock(); - //printf("Done calling task %d\n", t - emu_tasks + FIRST_PRIO); + // ets_intr_lock(); + // printf("Done calling task %d\n", t - emu_tasks + FIRST_PRIO); } ets_intr_unlock(); } @@ -188,7 +190,7 @@ void ets_timer_init() { ets_isr_attach(10, my_timer_isr, NULL); SET_PERI_REG_MASK(0x3FF00004, 4); ETS_INTR_ENABLE(10); - ets_task((os_task_t)0x40002E3C, 0x1f, (os_event_t*)0x3FFFDDC0, 4); + ets_task((os_task_t)0x40002E3C, 0x1f, (os_event_t *)0x3FFFDDC0, 4); WRITE_PERI_REG(PERIPHS_TIMER_BASEDDR + 0x30, 0); WRITE_PERI_REG(PERIPHS_TIMER_BASEDDR + 0x28, 0x88); @@ -198,36 +200,36 @@ void ets_timer_init() { #endif bool ets_run(void) { -#if USE_ETS_TASK + #if USE_ETS_TASK #if SDK_BELOW_1_1_1 ets_isr_attach(10, my_timer_isr, NULL); #endif _ets_run(); -#else + #else // ets_timer_init(); - *(char*)0x3FFFC6FC = 0; + *(char *)0x3FFFC6FC = 0; ets_intr_lock(); printf("ets_alt_task: ets_run\n"); -#if DEBUG + #if DEBUG dump_tasks(); -#endif + #endif ets_intr_unlock(); while (1) { if (!ets_loop_iter()) { - //printf("idle\n"); + // printf("idle\n"); ets_intr_lock(); if (idle_cb) { idle_cb(idle_arg); } - asm("waiti 0"); + asm ("waiti 0"); ets_intr_unlock(); } } -#endif + #endif } void ets_set_idle_cb(void (*handler)(void *), void *arg) { - //printf("ets_set_idle_cb(%p, %p)\n", handler, arg); + // printf("ets_set_idle_cb(%p, %p)\n", handler, arg); idle_cb = handler; idle_arg = arg; } diff --git a/ports/esp8266/etshal.h b/ports/esp8266/etshal.h index 8d64573119..f7b34b8356 100644 --- a/ports/esp8266/etshal.h +++ b/ports/esp8266/etshal.h @@ -4,7 +4,7 @@ #include // see http://esp8266-re.foogod.com/wiki/Random_Number_Generator -#define WDEV_HWRNG ((volatile uint32_t*)0x3ff20e44) +#define WDEV_HWRNG ((volatile uint32_t *)0x3ff20e44) void ets_delay_us(uint16_t us); void ets_intr_lock(void); diff --git a/ports/esp8266/fatfs_port.c b/ports/esp8266/fatfs_port.c index a8865c817e..8cef0acec3 100644 --- a/ports/esp8266/fatfs_port.c +++ b/ports/esp8266/fatfs_port.c @@ -38,6 +38,6 @@ DWORD get_fattime(void) { timeutils_struct_time_t tm; timeutils_seconds_since_2000_to_struct_time(secs, &tm); - return (((DWORD)(tm.tm_year - 1980) << 25) | ((DWORD)tm.tm_mon << 21) | ((DWORD)tm.tm_mday << 16) | - ((DWORD)tm.tm_hour << 11) | ((DWORD)tm.tm_min << 5) | ((DWORD)tm.tm_sec >> 1)); + return ((DWORD)(tm.tm_year - 1980) << 25) | ((DWORD)tm.tm_mon << 21) | ((DWORD)tm.tm_mday << 16) | + ((DWORD)tm.tm_hour << 11) | ((DWORD)tm.tm_min << 5) | ((DWORD)tm.tm_sec >> 1); } diff --git a/ports/esp8266/gccollect.c b/ports/esp8266/gccollect.c index dbe7bc186c..3618a56644 100644 --- a/ports/esp8266/gccollect.c +++ b/ports/esp8266/gccollect.c @@ -44,7 +44,7 @@ void gc_collect(void) { mp_uint_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, (STACK_END - sp) / sizeof(uint32_t)); + gc_collect_root((void **)sp, (STACK_END - sp) / sizeof(uint32_t)); // end the GC gc_collect_end(); diff --git a/ports/esp8266/help.c b/ports/esp8266/help.c index 0a851f4c48..4dd586c1a8 100644 --- a/ports/esp8266/help.c +++ b/ports/esp8266/help.c @@ -27,28 +27,28 @@ #include "py/builtin.h" const char esp_help_text[] = -"Welcome to MicroPython!\n" -"\n" -"For online docs please visit http://docs.micropython.org/en/latest/esp8266/ .\n" -"For diagnostic information to include in bug reports execute 'import port_diag'.\n" -"\n" -"Basic WiFi configuration:\n" -"\n" -"import network\n" -"sta_if = network.WLAN(network.STA_IF); sta_if.active(True)\n" -"sta_if.scan() # Scan for available access points\n" -"sta_if.connect(\"\", \"\") # Connect to an AP\n" -"sta_if.isconnected() # Check for successful connection\n" -"# Change name/password of ESP8266's AP:\n" -"ap_if = network.WLAN(network.AP_IF)\n" -"ap_if.config(essid=\"\", authmode=network.AUTH_WPA_WPA2_PSK, password=\"\")\n" -"\n" -"Control commands:\n" -" CTRL-A -- on a blank line, enter raw REPL mode\n" -" CTRL-B -- on a blank line, enter normal REPL mode\n" -" CTRL-C -- interrupt a running program\n" -" CTRL-D -- on a blank line, do a soft reset of the board\n" -" CTRL-E -- on a blank line, enter paste mode\n" -"\n" -"For further help on a specific object, type help(obj)\n" + "Welcome to MicroPython!\n" + "\n" + "For online docs please visit http://docs.micropython.org/en/latest/esp8266/ .\n" + "For diagnostic information to include in bug reports execute 'import port_diag'.\n" + "\n" + "Basic WiFi configuration:\n" + "\n" + "import network\n" + "sta_if = network.WLAN(network.STA_IF); sta_if.active(True)\n" + "sta_if.scan() # Scan for available access points\n" + "sta_if.connect(\"\", \"\") # Connect to an AP\n" + "sta_if.isconnected() # Check for successful connection\n" + "# Change name/password of ESP8266's AP:\n" + "ap_if = network.WLAN(network.AP_IF)\n" + "ap_if.config(essid=\"\", authmode=network.AUTH_WPA_WPA2_PSK, password=\"\")\n" + "\n" + "Control commands:\n" + " CTRL-A -- on a blank line, enter raw REPL mode\n" + " CTRL-B -- on a blank line, enter normal REPL mode\n" + " CTRL-C -- interrupt a running program\n" + " CTRL-D -- on a blank line, do a soft reset of the board\n" + " CTRL-E -- on a blank line, enter paste mode\n" + "\n" + "For further help on a specific object, type help(obj)\n" ; diff --git a/ports/esp8266/hspi.c b/ports/esp8266/hspi.c index 554a50460f..cecf0b755c 100644 --- a/ports/esp8266/hspi.c +++ b/ports/esp8266/hspi.c @@ -36,7 +36,7 @@ void spi_init(uint8_t spi_no) { spi_tx_byte_order(spi_no, SPI_BYTE_ORDER_HIGH_TO_LOW); spi_rx_byte_order(spi_no, SPI_BYTE_ORDER_HIGH_TO_LOW); - SET_PERI_REG_MASK(SPI_USER(spi_no), SPI_CS_SETUP|SPI_CS_HOLD); + SET_PERI_REG_MASK(SPI_USER(spi_no), SPI_CS_SETUP | SPI_CS_HOLD); CLEAR_PERI_REG_MASK(SPI_USER(spi_no), SPI_FLASH_MODE); } @@ -84,14 +84,14 @@ void spi_init_gpio(uint8_t spi_no, uint8_t sysclk_as_spiclk) { } if (spi_no == SPI) { // Set bit 8 if 80MHz sysclock required - WRITE_PERI_REG(PERIPHS_IO_MUX, 0x005 | (clock_div_flag<<8)); + WRITE_PERI_REG(PERIPHS_IO_MUX, 0x005 | (clock_div_flag << 8)); PIN_FUNC_SELECT(PERIPHS_IO_MUX_SD_CLK_U, 1); PIN_FUNC_SELECT(PERIPHS_IO_MUX_SD_CMD_U, 1); PIN_FUNC_SELECT(PERIPHS_IO_MUX_SD_DATA0_U, 1); PIN_FUNC_SELECT(PERIPHS_IO_MUX_SD_DATA1_U, 1); } else if (spi_no == HSPI) { // Set bit 9 if 80MHz sysclock required - WRITE_PERI_REG(PERIPHS_IO_MUX, 0x105 | (clock_div_flag<<9)); + WRITE_PERI_REG(PERIPHS_IO_MUX, 0x105 | (clock_div_flag << 9)); // GPIO12 is HSPI MISO pin (Master Data In) PIN_FUNC_SELECT(PERIPHS_IO_MUX_MTDI_U, 2); // GPIO13 is HSPI MOSI pin (Master Data Out) @@ -117,11 +117,11 @@ void spi_clock(uint8_t spi_no, uint16_t prediv, uint8_t cntdiv) { WRITE_PERI_REG(SPI_CLOCK(spi_no), SPI_CLK_EQU_SYSCLK); } else { WRITE_PERI_REG(SPI_CLOCK(spi_no), - (((prediv - 1) & SPI_CLKDIV_PRE) << SPI_CLKDIV_PRE_S) | - (((cntdiv - 1) & SPI_CLKCNT_N) << SPI_CLKCNT_N_S) | - (((cntdiv >> 1) & SPI_CLKCNT_H) << SPI_CLKCNT_H_S) | - ((0 & SPI_CLKCNT_L) << SPI_CLKCNT_L_S) - ); + (((prediv - 1) & SPI_CLKDIV_PRE) << SPI_CLKDIV_PRE_S) | + (((cntdiv - 1) & SPI_CLKCNT_N) << SPI_CLKCNT_N_S) | + (((cntdiv >> 1) & SPI_CLKCNT_H) << SPI_CLKCNT_H_S) | + ((0 & SPI_CLKCNT_L) << SPI_CLKCNT_L_S) + ); } } @@ -185,15 +185,17 @@ Note: all data is assumed to be stored in the lower bits of the data variables (for anything <32 bits). */ uint32_t spi_transaction(uint8_t spi_no, uint8_t cmd_bits, uint16_t cmd_data, - uint32_t addr_bits, uint32_t addr_data, - uint32_t dout_bits, uint32_t dout_data, - uint32_t din_bits, uint32_t dummy_bits) { - while (spi_busy(spi_no)) {}; // Wait for SPI to be ready + uint32_t addr_bits, uint32_t addr_data, + uint32_t dout_bits, uint32_t dout_data, + uint32_t din_bits, uint32_t dummy_bits) { + while (spi_busy(spi_no)) { + } + ; // Wait for SPI to be ready // Enable SPI Functions // Disable MOSI, MISO, ADDR, COMMAND, DUMMY in case previously set. CLEAR_PERI_REG_MASK(SPI_USER(spi_no), SPI_USR_MOSI | SPI_USR_MISO | - SPI_USR_COMMAND | SPI_USR_ADDR | SPI_USR_DUMMY); + SPI_USR_COMMAND | SPI_USR_ADDR | SPI_USR_DUMMY); // Enable functions based on number of bits. 0 bits = disabled. // This is rather inefficient but allows for a very generic function. @@ -213,25 +215,25 @@ uint32_t spi_transaction(uint8_t spi_no, uint8_t cmd_bits, uint16_t cmd_data, WRITE_PERI_REG(SPI_USER1(spi_no), // Number of bits in Address ((addr_bits - 1) & SPI_USR_ADDR_BITLEN) << SPI_USR_ADDR_BITLEN_S | - // Number of bits to Send - ((dout_bits - 1) & SPI_USR_MOSI_BITLEN) << SPI_USR_MOSI_BITLEN_S | - // Number of bits to receive - ((din_bits - 1) & SPI_USR_MISO_BITLEN) << SPI_USR_MISO_BITLEN_S | - // Number of Dummy bits to insert - ((dummy_bits - 1) & SPI_USR_DUMMY_CYCLELEN) << SPI_USR_DUMMY_CYCLELEN_S); + // Number of bits to Send + ((dout_bits - 1) & SPI_USR_MOSI_BITLEN) << SPI_USR_MOSI_BITLEN_S | + // Number of bits to receive + ((din_bits - 1) & SPI_USR_MISO_BITLEN) << SPI_USR_MISO_BITLEN_S | + // Number of Dummy bits to insert + ((dummy_bits - 1) & SPI_USR_DUMMY_CYCLELEN) << SPI_USR_DUMMY_CYCLELEN_S); // Setup Command Data if (cmd_bits) { // Enable COMMAND function in SPI module SET_PERI_REG_MASK(SPI_USER(spi_no), SPI_USR_COMMAND); // Align command data to high bits - uint16_t command = cmd_data << (16-cmd_bits); + uint16_t command = cmd_data << (16 - cmd_bits); // Swap byte order - command = ((command>>8)&0xff) | ((command<<8)&0xff00); + command = ((command >> 8) & 0xff) | ((command << 8) & 0xff00); WRITE_PERI_REG(SPI_USER2(spi_no), ( (((cmd_bits - 1) & SPI_USR_COMMAND_BITLEN) << SPI_USR_COMMAND_BITLEN_S) | (command & SPI_USR_COMMAND_VALUE) - )); + )); } // Setup Address Data @@ -246,42 +248,44 @@ uint32_t spi_transaction(uint8_t spi_no, uint8_t cmd_bits, uint16_t cmd_data, if (dout_bits) { // Enable MOSI function in SPI module SET_PERI_REG_MASK(SPI_USER(spi_no), SPI_USR_MOSI); - // Copy data to W0 - if (READ_PERI_REG(SPI_USER(spi_no))&SPI_WR_BYTE_ORDER) { - WRITE_PERI_REG(SPI_W0(spi_no), dout_data << (32 - dout_bits)); - } else { - uint8_t dout_extra_bits = dout_bits%8; - - if (dout_extra_bits) { - // If your data isn't a byte multiple (8/16/24/32 bits) and you - // don't have SPI_WR_BYTE_ORDER set, you need this to move the - // non-8bit remainder to the MSBs. Not sure if there's even a use - // case for this, but it's here if you need it... For example, - // 0xDA4 12 bits without SPI_WR_BYTE_ORDER would usually be output - // as if it were 0x0DA4, of which 0xA4, and then 0x0 would be - // shifted out (first 8 bits of low byte, then 4 MSB bits of high - // byte - ie reverse byte order). - // The code below shifts it out as 0xA4 followed by 0xD as you - // might require. - WRITE_PERI_REG(SPI_W0(spi_no), ( - (0xFFFFFFFF << (dout_bits - dout_extra_bits) & dout_data) - << (8-dout_extra_bits) | - ((0xFFFFFFFF >> (32 - (dout_bits - dout_extra_bits))) - & dout_data) - )); + // Copy data to W0 + if (READ_PERI_REG(SPI_USER(spi_no)) & SPI_WR_BYTE_ORDER) { + WRITE_PERI_REG(SPI_W0(spi_no), dout_data << (32 - dout_bits)); } else { - WRITE_PERI_REG(SPI_W0(spi_no), dout_data); + uint8_t dout_extra_bits = dout_bits % 8; + + if (dout_extra_bits) { + // If your data isn't a byte multiple (8/16/24/32 bits) and you + // don't have SPI_WR_BYTE_ORDER set, you need this to move the + // non-8bit remainder to the MSBs. Not sure if there's even a use + // case for this, but it's here if you need it... For example, + // 0xDA4 12 bits without SPI_WR_BYTE_ORDER would usually be output + // as if it were 0x0DA4, of which 0xA4, and then 0x0 would be + // shifted out (first 8 bits of low byte, then 4 MSB bits of high + // byte - ie reverse byte order). + // The code below shifts it out as 0xA4 followed by 0xD as you + // might require. + WRITE_PERI_REG(SPI_W0(spi_no), ( + (0xFFFFFFFF << (dout_bits - dout_extra_bits) & dout_data) + << (8 - dout_extra_bits) | + ((0xFFFFFFFF >> (32 - (dout_bits - dout_extra_bits))) + & dout_data) + )); + } else { + WRITE_PERI_REG(SPI_W0(spi_no), dout_data); + } } } -} // Begin SPI Transaction SET_PERI_REG_MASK(SPI_CMD(spi_no), SPI_USR); // Return DIN data if (din_bits) { - while (spi_busy(spi_no)) {}; // Wait for SPI transaction to complete - if (READ_PERI_REG(SPI_USER(spi_no))&SPI_RD_BYTE_ORDER) { + while (spi_busy(spi_no)) { + } + ; // Wait for SPI transaction to complete + if (READ_PERI_REG(SPI_USER(spi_no)) & SPI_RD_BYTE_ORDER) { // Assuming data in is written to MSB. TBC return READ_PERI_REG(SPI_W0(spi_no)) >> (32 - din_bits); } else { @@ -301,19 +305,21 @@ uint32_t spi_transaction(uint8_t spi_no, uint8_t cmd_bits, uint16_t cmd_data, Just do minimal work needed to send 8 bits. */ inline void spi_tx8fast(uint8_t spi_no, uint8_t dout_data) { - while (spi_busy(spi_no)) {}; // Wait for SPI to be ready + while (spi_busy(spi_no)) { + } + ; // Wait for SPI to be ready // Enable SPI Functions // Disable MOSI, MISO, ADDR, COMMAND, DUMMY in case previously set. CLEAR_PERI_REG_MASK(SPI_USER(spi_no), SPI_USR_MOSI | SPI_USR_MISO | - SPI_USR_COMMAND | SPI_USR_ADDR | SPI_USR_DUMMY); + SPI_USR_COMMAND | SPI_USR_ADDR | SPI_USR_DUMMY); // Setup Bitlengths WRITE_PERI_REG(SPI_USER1(spi_no), // Number of bits to Send ((8 - 1) & SPI_USR_MOSI_BITLEN) << SPI_USR_MOSI_BITLEN_S | - // Number of bits to receive - ((8 - 1) & SPI_USR_MISO_BITLEN) << SPI_USR_MISO_BITLEN_S); + // Number of bits to receive + ((8 - 1) & SPI_USR_MISO_BITLEN) << SPI_USR_MISO_BITLEN_S); // Setup DOUT data diff --git a/ports/esp8266/hspi.h b/ports/esp8266/hspi.h index c68366ef44..f92a13994d 100644 --- a/ports/esp8266/hspi.h +++ b/ports/esp8266/hspi.h @@ -41,7 +41,7 @@ #define SPI_BYTE_ORDER_HIGH_TO_LOW 1 #define SPI_BYTE_ORDER_LOW_TO_HIGH 0 -#ifndef CPU_CLK_FREQ //Should already be defined in eagle_soc.h +#ifndef CPU_CLK_FREQ // Should already be defined in eagle_soc.h #define CPU_CLK_FREQ (80 * 1000000) #endif @@ -58,18 +58,18 @@ void spi_clock(uint8_t spi_no, uint16_t prediv, uint8_t cntdiv); void spi_tx_byte_order(uint8_t spi_no, uint8_t byte_order); void spi_rx_byte_order(uint8_t spi_no, uint8_t byte_order); uint32_t spi_transaction(uint8_t spi_no, uint8_t cmd_bits, uint16_t cmd_data, - uint32_t addr_bits, uint32_t addr_data, - uint32_t dout_bits, uint32_t dout_data, - uint32_t din_bits, uint32_t dummy_bits); + uint32_t addr_bits, uint32_t addr_data, + uint32_t dout_bits, uint32_t dout_data, + uint32_t din_bits, uint32_t dummy_bits); void spi_tx8fast(uint8_t spi_no, uint8_t dout_data); // Expansion Macros -#define spi_busy(spi_no) READ_PERI_REG(SPI_CMD(spi_no))&SPI_USR +#define spi_busy(spi_no) READ_PERI_REG(SPI_CMD(spi_no)) & SPI_USR -#define spi_txd(spi_no, bits, data) spi_transaction(spi_no, 0, 0, 0, 0, bits, (uint32_t) data, 0, 0) -#define spi_tx8(spi_no, data) spi_transaction(spi_no, 0, 0, 0, 0, 8, (uint32_t) data, 0, 0) -#define spi_tx16(spi_no, data) spi_transaction(spi_no, 0, 0, 0, 0, 16, (uint32_t) data, 0, 0) -#define spi_tx32(spi_no, data) spi_transaction(spi_no, 0, 0, 0, 0, 32, (uint32_t) data, 0, 0) +#define spi_txd(spi_no, bits, data) spi_transaction(spi_no, 0, 0, 0, 0, bits, (uint32_t)data, 0, 0) +#define spi_tx8(spi_no, data) spi_transaction(spi_no, 0, 0, 0, 0, 8, (uint32_t)data, 0, 0) +#define spi_tx16(spi_no, data) spi_transaction(spi_no, 0, 0, 0, 0, 16, (uint32_t)data, 0, 0) +#define spi_tx32(spi_no, data) spi_transaction(spi_no, 0, 0, 0, 0, 32, (uint32_t)data, 0, 0) #define spi_rxd(spi_no, bits) spi_transaction(spi_no, 0, 0, 0, 0, 0, 0, bits, 0) #define spi_rx8(spi_no) spi_transaction(spi_no, 0, 0, 0, 0, 0, 0, 8, 0) diff --git a/ports/esp8266/hspi_register.h b/ports/esp8266/hspi_register.h index 4dd335b400..0a068b7477 100644 --- a/ports/esp8266/hspi_register.h +++ b/ports/esp8266/hspi_register.h @@ -11,74 +11,74 @@ #ifndef SPI_REGISTER_H_INCLUDED #define SPI_REGISTER_H_INCLUDED -#define REG_SPI_BASE(i) (0x60000200-i*0x100) +#define REG_SPI_BASE(i) (0x60000200 - i * 0x100) -#define SPI_CMD(i) (REG_SPI_BASE(i) + 0x0) -#define SPI_FLASH_READ (BIT(31)) //From previous SDK -#define SPI_FLASH_WREN (BIT(30)) //From previous SDK -#define SPI_FLASH_WRDI (BIT(29)) //From previous SDK -#define SPI_FLASH_RDID (BIT(28)) //From previous SDK -#define SPI_FLASH_RDSR (BIT(27)) //From previous SDK -#define SPI_FLASH_WRSR (BIT(26)) //From previous SDK -#define SPI_FLASH_PP (BIT(25)) //From previous SDK -#define SPI_FLASH_SE (BIT(24)) //From previous SDK -#define SPI_FLASH_BE (BIT(23)) //From previous SDK -#define SPI_FLASH_CE (BIT(22)) //From previous SDK -#define SPI_FLASH_DP (BIT(21)) //From previous SDK -#define SPI_FLASH_RES (BIT(20)) //From previous SDK -#define SPI_FLASH_HPM (BIT(19)) //From previous SDK +#define SPI_CMD(i) (REG_SPI_BASE(i) + 0x0) +#define SPI_FLASH_READ (BIT(31)) // From previous SDK +#define SPI_FLASH_WREN (BIT(30)) // From previous SDK +#define SPI_FLASH_WRDI (BIT(29)) // From previous SDK +#define SPI_FLASH_RDID (BIT(28)) // From previous SDK +#define SPI_FLASH_RDSR (BIT(27)) // From previous SDK +#define SPI_FLASH_WRSR (BIT(26)) // From previous SDK +#define SPI_FLASH_PP (BIT(25)) // From previous SDK +#define SPI_FLASH_SE (BIT(24)) // From previous SDK +#define SPI_FLASH_BE (BIT(23)) // From previous SDK +#define SPI_FLASH_CE (BIT(22)) // From previous SDK +#define SPI_FLASH_DP (BIT(21)) // From previous SDK +#define SPI_FLASH_RES (BIT(20)) // From previous SDK +#define SPI_FLASH_HPM (BIT(19)) // From previous SDK #define SPI_USR (BIT(18)) -#define SPI_ADDR(i) (REG_SPI_BASE(i) + 0x4) +#define SPI_ADDR(i) (REG_SPI_BASE(i) + 0x4) -#define SPI_CTRL(i) (REG_SPI_BASE(i) + 0x8) +#define SPI_CTRL(i) (REG_SPI_BASE(i) + 0x8) #define SPI_WR_BIT_ORDER (BIT(26)) #define SPI_RD_BIT_ORDER (BIT(25)) #define SPI_QIO_MODE (BIT(24)) #define SPI_DIO_MODE (BIT(23)) -#define SPI_TWO_BYTE_STATUS_EN (BIT(22)) //From previous SDK -#define SPI_WP_REG (BIT(21)) //From previous SDK +#define SPI_TWO_BYTE_STATUS_EN (BIT(22)) // From previous SDK +#define SPI_WP_REG (BIT(21)) // From previous SDK #define SPI_QOUT_MODE (BIT(20)) -#define SPI_SHARE_BUS (BIT(19)) //From previous SDK -#define SPI_HOLD_MODE (BIT(18)) //From previous SDK -#define SPI_ENABLE_AHB (BIT(17)) //From previous SDK -#define SPI_SST_AAI (BIT(16)) //From previous SDK -#define SPI_RESANDRES (BIT(15)) //From previous SDK +#define SPI_SHARE_BUS (BIT(19)) // From previous SDK +#define SPI_HOLD_MODE (BIT(18)) // From previous SDK +#define SPI_ENABLE_AHB (BIT(17)) // From previous SDK +#define SPI_SST_AAI (BIT(16)) // From previous SDK +#define SPI_RESANDRES (BIT(15)) // From previous SDK #define SPI_DOUT_MODE (BIT(14)) #define SPI_FASTRD_MODE (BIT(13)) -#define SPI_CTRL1(i) (REG_SPI_BASE (i) + 0xC) //From previous SDK. Removed _FLASH_ from name to match other registers. -#define SPI_CS_HOLD_DELAY 0x0000000F //Espressif BBS -#define SPI_CS_HOLD_DELAY_S 28 //Espressif BBS -#define SPI_CS_HOLD_DELAY_RES 0x00000FFF //Espressif BBS -#define SPI_CS_HOLD_DELAY_RES_S 16 //Espressif BBS -#define SPI_BUS_TIMER_LIMIT 0x0000FFFF //From previous SDK -#define SPI_BUS_TIMER_LIMIT_S 0 //From previous SDK +#define SPI_CTRL1(i) (REG_SPI_BASE(i) + 0xC) // From previous SDK. Removed _FLASH_ from name to match other registers. +#define SPI_CS_HOLD_DELAY 0x0000000F // Espressif BBS +#define SPI_CS_HOLD_DELAY_S 28 // Espressif BBS +#define SPI_CS_HOLD_DELAY_RES 0x00000FFF // Espressif BBS +#define SPI_CS_HOLD_DELAY_RES_S 16 // Espressif BBS +#define SPI_BUS_TIMER_LIMIT 0x0000FFFF // From previous SDK +#define SPI_BUS_TIMER_LIMIT_S 0 // From previous SDK -#define SPI_RD_STATUS(i) (REG_SPI_BASE(i) + 0x10) -#define SPI_STATUS_EXT 0x000000FF //From previous SDK -#define SPI_STATUS_EXT_S 24 //From previous SDK -#define SPI_WB_MODE 0x000000FF //From previous SDK -#define SPI_WB_MODE_S 16 //From previous SDK -#define SPI_FLASH_STATUS_PRO_FLAG (BIT(7)) //From previous SDK -#define SPI_FLASH_TOP_BOT_PRO_FLAG (BIT(5)) //From previous SDK -#define SPI_FLASH_BP2 (BIT(4)) //From previous SDK -#define SPI_FLASH_BP1 (BIT(3)) //From previous SDK -#define SPI_FLASH_BP0 (BIT(2)) //From previous SDK -#define SPI_FLASH_WRENABLE_FLAG (BIT(1)) //From previous SDK -#define SPI_FLASH_BUSY_FLAG (BIT(0)) //From previous SDK +#define SPI_RD_STATUS(i) (REG_SPI_BASE(i) + 0x10) +#define SPI_STATUS_EXT 0x000000FF // From previous SDK +#define SPI_STATUS_EXT_S 24 // From previous SDK +#define SPI_WB_MODE 0x000000FF // From previous SDK +#define SPI_WB_MODE_S 16 // From previous SDK +#define SPI_FLASH_STATUS_PRO_FLAG (BIT(7)) // From previous SDK +#define SPI_FLASH_TOP_BOT_PRO_FLAG (BIT(5)) // From previous SDK +#define SPI_FLASH_BP2 (BIT(4)) // From previous SDK +#define SPI_FLASH_BP1 (BIT(3)) // From previous SDK +#define SPI_FLASH_BP0 (BIT(2)) // From previous SDK +#define SPI_FLASH_WRENABLE_FLAG (BIT(1)) // From previous SDK +#define SPI_FLASH_BUSY_FLAG (BIT(0)) // From previous SDK -#define SPI_CTRL2(i) (REG_SPI_BASE(i) + 0x14) +#define SPI_CTRL2(i) (REG_SPI_BASE(i) + 0x14) #define SPI_CS_DELAY_NUM 0x0000000F #define SPI_CS_DELAY_NUM_S 28 #define SPI_CS_DELAY_MODE 0x00000003 #define SPI_CS_DELAY_MODE_S 26 #define SPI_MOSI_DELAY_NUM 0x00000007 #define SPI_MOSI_DELAY_NUM_S 23 -#define SPI_MOSI_DELAY_MODE 0x00000003 //mode 0 : posedge; data set at positive edge of clk - //mode 1 : negedge + 1 cycle delay, only if freq<10MHz ; data set at negitive edge of clk - //mode 2 : Do not use this mode. +#define SPI_MOSI_DELAY_MODE 0x00000003 // mode 0 : posedge; data set at positive edge of clk +// mode 1 : negedge + 1 cycle delay, only if freq<10MHz ; data set at negitive edge of clk +// mode 2 : Do not use this mode. #define SPI_MOSI_DELAY_MODE_S 21 #define SPI_MISO_DELAY_NUM 0x00000007 #define SPI_MISO_DELAY_NUM_S 18 @@ -93,7 +93,7 @@ #define SPI_SETUP_TIME 0x0000000F #define SPI_SETUP_TIME_S 0 -#define SPI_CLOCK(i) (REG_SPI_BASE(i) + 0x18) +#define SPI_CLOCK(i) (REG_SPI_BASE(i) + 0x18) #define SPI_CLK_EQU_SYSCLK (BIT(31)) #define SPI_CLKDIV_PRE 0x00001FFF #define SPI_CLKDIV_PRE_S 18 @@ -104,22 +104,22 @@ #define SPI_CLKCNT_L 0x0000003F #define SPI_CLKCNT_L_S 0 -#define SPI_USER(i) (REG_SPI_BASE(i) + 0x1C) +#define SPI_USER(i) (REG_SPI_BASE(i) + 0x1C) #define SPI_USR_COMMAND (BIT(31)) #define SPI_USR_ADDR (BIT(30)) #define SPI_USR_DUMMY (BIT(29)) #define SPI_USR_MISO (BIT(28)) #define SPI_USR_MOSI (BIT(27)) -#define SPI_USR_DUMMY_IDLE (BIT(26)) //From previous SDK +#define SPI_USR_DUMMY_IDLE (BIT(26)) // From previous SDK #define SPI_USR_MOSI_HIGHPART (BIT(25)) #define SPI_USR_MISO_HIGHPART (BIT(24)) -#define SPI_USR_PREP_HOLD (BIT(23)) //From previous SDK -#define SPI_USR_CMD_HOLD (BIT(22)) //From previous SDK -#define SPI_USR_ADDR_HOLD (BIT(21)) //From previous SDK -#define SPI_USR_DUMMY_HOLD (BIT(20)) //From previous SDK -#define SPI_USR_DIN_HOLD (BIT(19)) //From previous SDK -#define SPI_USR_DOUT_HOLD (BIT(18)) //From previous SDK -#define SPI_USR_HOLD_POL (BIT(17)) //From previous SDK +#define SPI_USR_PREP_HOLD (BIT(23)) // From previous SDK +#define SPI_USR_CMD_HOLD (BIT(22)) // From previous SDK +#define SPI_USR_ADDR_HOLD (BIT(21)) // From previous SDK +#define SPI_USR_DUMMY_HOLD (BIT(20)) // From previous SDK +#define SPI_USR_DIN_HOLD (BIT(19)) // From previous SDK +#define SPI_USR_DOUT_HOLD (BIT(18)) // From previous SDK +#define SPI_USR_HOLD_POL (BIT(17)) // From previous SDK #define SPI_SIO (BIT(16)) #define SPI_FWRITE_QIO (BIT(15)) #define SPI_FWRITE_DIO (BIT(14)) @@ -127,18 +127,18 @@ #define SPI_FWRITE_DUAL (BIT(12)) #define SPI_WR_BYTE_ORDER (BIT(11)) #define SPI_RD_BYTE_ORDER (BIT(10)) -#define SPI_AHB_ENDIAN_MODE 0x00000003 //From previous SDK -#define SPI_AHB_ENDIAN_MODE_S 8 //From previous SDK +#define SPI_AHB_ENDIAN_MODE 0x00000003 // From previous SDK +#define SPI_AHB_ENDIAN_MODE_S 8 // From previous SDK #define SPI_CK_OUT_EDGE (BIT(7)) #define SPI_CK_I_EDGE (BIT(6)) #define SPI_CS_SETUP (BIT(5)) #define SPI_CS_HOLD (BIT(4)) -#define SPI_AHB_USR_COMMAND (BIT(3)) //From previous SDK +#define SPI_AHB_USR_COMMAND (BIT(3)) // From previous SDK #define SPI_FLASH_MODE (BIT(2)) -#define SPI_AHB_USR_COMMAND_4BYTE (BIT(1)) //From previous SDK -#define SPI_DOUTDIN (BIT(0)) //From previous SDK +#define SPI_AHB_USR_COMMAND_4BYTE (BIT(1)) // From previous SDK +#define SPI_DOUTDIN (BIT(0)) // From previous SDK -//AHB = http://en.wikipedia.org/wiki/Advanced_Microcontroller_Bus_Architecture ? +// AHB = http://en.wikipedia.org/wiki/Advanced_Microcontroller_Bus_Architecture ? #define SPI_USER1(i) (REG_SPI_BASE(i) + 0x20) @@ -151,22 +151,22 @@ #define SPI_USR_DUMMY_CYCLELEN 0x000000FF #define SPI_USR_DUMMY_CYCLELEN_S 0 -#define SPI_USER2(i) (REG_SPI_BASE(i) + 0x24) +#define SPI_USER2(i) (REG_SPI_BASE(i) + 0x24) #define SPI_USR_COMMAND_BITLEN 0x0000000F #define SPI_USR_COMMAND_BITLEN_S 28 #define SPI_USR_COMMAND_VALUE 0x0000FFFF #define SPI_USR_COMMAND_VALUE_S 0 -#define SPI_WR_STATUS(i) (REG_SPI_BASE(i) + 0x28) - //previously defined as SPI_FLASH_USER3. No further info available. +#define SPI_WR_STATUS(i) (REG_SPI_BASE(i) + 0x28) +// previously defined as SPI_FLASH_USER3. No further info available. -#define SPI_PIN(i) (REG_SPI_BASE(i) + 0x2C) +#define SPI_PIN(i) (REG_SPI_BASE(i) + 0x2C) #define SPI_IDLE_EDGE (BIT(29)) #define SPI_CS2_DIS (BIT(2)) #define SPI_CS1_DIS (BIT(1)) #define SPI_CS0_DIS (BIT(0)) -#define SPI_SLAVE(i) (REG_SPI_BASE(i) + 0x30) +#define SPI_SLAVE(i) (REG_SPI_BASE(i) + 0x30) #define SPI_SYNC_RESET (BIT(31)) #define SPI_SLAVE_MODE (BIT(30)) #define SPI_SLV_WR_RD_BUF_EN (BIT(29)) @@ -174,12 +174,12 @@ #define SPI_SLV_CMD_DEFINE (BIT(27)) #define SPI_TRANS_CNT 0x0000000F #define SPI_TRANS_CNT_S 23 -#define SPI_SLV_LAST_STATE 0x00000007 //From previous SDK -#define SPI_SLV_LAST_STATE_S 20 //From previous SDK -#define SPI_SLV_LAST_COMMAND 0x00000007 //From previous SDK -#define SPI_SLV_LAST_COMMAND_S 17 //From previous SDK -#define SPI_CS_I_MODE 0x00000003 //From previous SDK -#define SPI_CS_I_MODE_S 10 //From previous SDK +#define SPI_SLV_LAST_STATE 0x00000007 // From previous SDK +#define SPI_SLV_LAST_STATE_S 20 // From previous SDK +#define SPI_SLV_LAST_COMMAND 0x00000007 // From previous SDK +#define SPI_SLV_LAST_COMMAND_S 17 // From previous SDK +#define SPI_CS_I_MODE 0x00000003 // From previous SDK +#define SPI_CS_I_MODE_S 10 // From previous SDK #define SPI_TRANS_DONE_EN (BIT(9)) #define SPI_SLV_WR_STA_DONE_EN (BIT(8)) #define SPI_SLV_RD_STA_DONE_EN (BIT(7)) @@ -193,11 +193,11 @@ #define SPI_SLV_WR_BUF_DONE (BIT(1)) #define SPI_SLV_RD_BUF_DONE (BIT(0)) -#define SPI_SLAVE1(i) (REG_SPI_BASE(i) + 0x34) +#define SPI_SLAVE1(i) (REG_SPI_BASE(i) + 0x34) #define SPI_SLV_STATUS_BITLEN 0x0000001F #define SPI_SLV_STATUS_BITLEN_S 27 -#define SPI_SLV_STATUS_FAST_EN (BIT(26)) //From previous SDK -#define SPI_SLV_STATUS_READBACK (BIT(25)) //From previous SDK +#define SPI_SLV_STATUS_FAST_EN (BIT(26)) // From previous SDK +#define SPI_SLV_STATUS_READBACK (BIT(25)) // From previous SDK #define SPI_SLV_BUF_BITLEN 0x000001FF #define SPI_SLV_BUF_BITLEN_S 16 #define SPI_SLV_RD_ADDR_BITLEN 0x0000003F @@ -211,7 +211,7 @@ -#define SPI_SLAVE2(i) (REG_SPI_BASE(i) + 0x38) +#define SPI_SLAVE2(i) (REG_SPI_BASE(i) + 0x38) #define SPI_SLV_WRBUF_DUMMY_CYCLELEN 0X000000FF #define SPI_SLV_WRBUF_DUMMY_CYCLELEN_S 24 #define SPI_SLV_RDBUF_DUMMY_CYCLELEN 0X000000FF @@ -221,7 +221,7 @@ #define SPI_SLV_RDSTR_DUMMY_CYCLELEN 0x000000FF #define SPI_SLV_RDSTR_DUMMY_CYCLELEN_S 0 -#define SPI_SLAVE3(i) (REG_SPI_BASE(i) + 0x3C) +#define SPI_SLAVE3(i) (REG_SPI_BASE(i) + 0x3C) #define SPI_SLV_WRSTA_CMD_VALUE 0x000000FF #define SPI_SLV_WRSTA_CMD_VALUE_S 24 #define SPI_SLV_RDSTA_CMD_VALUE 0x000000FF @@ -231,48 +231,48 @@ #define SPI_SLV_RDBUF_CMD_VALUE 0x000000FF #define SPI_SLV_RDBUF_CMD_VALUE_S 0 -//Previous SDKs referred to these following registers as SPI_C0 etc. +// Previous SDKs referred to these following registers as SPI_C0 etc. -#define SPI_W0(i) (REG_SPI_BASE(i) +0x40) -#define SPI_W1(i) (REG_SPI_BASE(i) +0x44) -#define SPI_W2(i) (REG_SPI_BASE(i) +0x48) -#define SPI_W3(i) (REG_SPI_BASE(i) +0x4C) -#define SPI_W4(i) (REG_SPI_BASE(i) +0x50) -#define SPI_W5(i) (REG_SPI_BASE(i) +0x54) -#define SPI_W6(i) (REG_SPI_BASE(i) +0x58) -#define SPI_W7(i) (REG_SPI_BASE(i) +0x5C) -#define SPI_W8(i) (REG_SPI_BASE(i) +0x60) -#define SPI_W9(i) (REG_SPI_BASE(i) +0x64) -#define SPI_W10(i) (REG_SPI_BASE(i) +0x68) -#define SPI_W11(i) (REG_SPI_BASE(i) +0x6C) -#define SPI_W12(i) (REG_SPI_BASE(i) +0x70) -#define SPI_W13(i) (REG_SPI_BASE(i) +0x74) -#define SPI_W14(i) (REG_SPI_BASE(i) +0x78) -#define SPI_W15(i) (REG_SPI_BASE(i) +0x7C) +#define SPI_W0(i) (REG_SPI_BASE(i) + 0x40) +#define SPI_W1(i) (REG_SPI_BASE(i) + 0x44) +#define SPI_W2(i) (REG_SPI_BASE(i) + 0x48) +#define SPI_W3(i) (REG_SPI_BASE(i) + 0x4C) +#define SPI_W4(i) (REG_SPI_BASE(i) + 0x50) +#define SPI_W5(i) (REG_SPI_BASE(i) + 0x54) +#define SPI_W6(i) (REG_SPI_BASE(i) + 0x58) +#define SPI_W7(i) (REG_SPI_BASE(i) + 0x5C) +#define SPI_W8(i) (REG_SPI_BASE(i) + 0x60) +#define SPI_W9(i) (REG_SPI_BASE(i) + 0x64) +#define SPI_W10(i) (REG_SPI_BASE(i) + 0x68) +#define SPI_W11(i) (REG_SPI_BASE(i) + 0x6C) +#define SPI_W12(i) (REG_SPI_BASE(i) + 0x70) +#define SPI_W13(i) (REG_SPI_BASE(i) + 0x74) +#define SPI_W14(i) (REG_SPI_BASE(i) + 0x78) +#define SPI_W15(i) (REG_SPI_BASE(i) + 0x7C) - // +0x80 to +0xBC could be SPI_W16 through SPI_W31? +// +0x80 to +0xBC could be SPI_W16 through SPI_W31? - // +0xC0 to +0xEC not currently defined. +// +0xC0 to +0xEC not currently defined. -#define SPI_EXT0(i) (REG_SPI_BASE(i) + 0xF0) //From previous SDK. Removed _FLASH_ from name to match other registers. -#define SPI_T_PP_ENA (BIT(31)) //From previous SDK -#define SPI_T_PP_SHIFT 0x0000000F //From previous SDK -#define SPI_T_PP_SHIFT_S 16 //From previous SDK -#define SPI_T_PP_TIME 0x00000FFF //From previous SDK -#define SPI_T_PP_TIME_S 0 //From previous SDK +#define SPI_EXT0(i) (REG_SPI_BASE(i) + 0xF0) // From previous SDK. Removed _FLASH_ from name to match other registers. +#define SPI_T_PP_ENA (BIT(31)) // From previous SDK +#define SPI_T_PP_SHIFT 0x0000000F // From previous SDK +#define SPI_T_PP_SHIFT_S 16 // From previous SDK +#define SPI_T_PP_TIME 0x00000FFF // From previous SDK +#define SPI_T_PP_TIME_S 0 // From previous SDK -#define SPI_EXT1(i) (REG_SPI_BASE(i) + 0xF4) //From previous SDK. Removed _FLASH_ from name to match other registers. -#define SPI_T_ERASE_ENA (BIT(31)) //From previous SDK -#define SPI_T_ERASE_SHIFT 0x0000000F //From previous SDK -#define SPI_T_ERASE_SHIFT_S 16 //From previous SDK -#define SPI_T_ERASE_TIME 0x00000FFF //From previous SDK -#define SPI_T_ERASE_TIME_S 0 //From previous SDK +#define SPI_EXT1(i) (REG_SPI_BASE(i) + 0xF4) // From previous SDK. Removed _FLASH_ from name to match other registers. +#define SPI_T_ERASE_ENA (BIT(31)) // From previous SDK +#define SPI_T_ERASE_SHIFT 0x0000000F // From previous SDK +#define SPI_T_ERASE_SHIFT_S 16 // From previous SDK +#define SPI_T_ERASE_TIME 0x00000FFF // From previous SDK +#define SPI_T_ERASE_TIME_S 0 // From previous SDK -#define SPI_EXT2(i) (REG_SPI_BASE(i) + 0xF8) //From previous SDK. Removed _FLASH_ from name to match other registers. -#define SPI_ST 0x00000007 //From previous SDK -#define SPI_ST_S 0 //From previous SDK +#define SPI_EXT2(i) (REG_SPI_BASE(i) + 0xF8) // From previous SDK. Removed _FLASH_ from name to match other registers. +#define SPI_ST 0x00000007 // From previous SDK +#define SPI_ST_S 0 // From previous SDK -#define SPI_EXT3(i) (REG_SPI_BASE(i) + 0xFC) +#define SPI_EXT3(i) (REG_SPI_BASE(i) + 0xFC) #define SPI_INT_HOLD_ENA 0x00000003 #define SPI_INT_HOLD_ENA_S 0 #endif // SPI_REGISTER_H_INCLUDED diff --git a/ports/esp8266/lexerstr32.c b/ports/esp8266/lexerstr32.c index 6fb84bb74e..a921efbbdc 100644 --- a/ports/esp8266/lexerstr32.c +++ b/ports/esp8266/lexerstr32.c @@ -36,7 +36,7 @@ typedef struct _mp_lexer_str32_buf_t { } mp_lexer_str32_buf_t; STATIC mp_uint_t str32_buf_next_byte(void *sb_in) { - mp_lexer_str32_buf_t *sb = (mp_lexer_str32_buf_t*)sb_in; + mp_lexer_str32_buf_t *sb = (mp_lexer_str32_buf_t *)sb_in; byte c = sb->val & 0xff; if (c == 0) { return MP_READER_EOF; @@ -53,14 +53,14 @@ STATIC mp_uint_t str32_buf_next_byte(void *sb_in) { } STATIC void str32_buf_free(void *sb_in) { - mp_lexer_str32_buf_t *sb = (mp_lexer_str32_buf_t*)sb_in; + mp_lexer_str32_buf_t *sb = (mp_lexer_str32_buf_t *)sb_in; m_del_obj(mp_lexer_str32_buf_t, sb); } mp_lexer_t *mp_lexer_new_from_str32(qstr src_name, const char *str, mp_uint_t len, mp_uint_t free_len) { mp_lexer_str32_buf_t *sb = m_new_obj(mp_lexer_str32_buf_t); sb->byte_off = (uint32_t)str & 3; - sb->src_cur = (uint32_t*)(str - sb->byte_off); + sb->src_cur = (uint32_t *)(str - sb->byte_off); sb->val = *sb->src_cur++ >> sb->byte_off * 8; mp_reader_t reader = {sb, str32_buf_next_byte, str32_buf_free}; return mp_lexer_new(src_name, reader); diff --git a/ports/esp8266/machine_adc.c b/ports/esp8266/machine_adc.c index b422f0f9ec..22c0ebc419 100644 --- a/ports/esp8266/machine_adc.c +++ b/ports/esp8266/machine_adc.c @@ -47,13 +47,13 @@ STATIC mp_obj_t pyb_adc_make_new(const mp_obj_type_t *type_in, size_t n_args, si mp_int_t chn = mp_obj_get_int(args[0]); switch (chn) { - case 0: - return &pyb_adc_adc; - case 1: - return &pyb_adc_vdd3; - default: - nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, - "not a valid ADC Channel: %d", chn)); + case 0: + return &pyb_adc_adc; + case 1: + return &pyb_adc_vdd3; + default: + nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, + "not a valid ADC Channel: %d", chn)); } } @@ -77,5 +77,5 @@ const mp_obj_type_t pyb_adc_type = { { &mp_type_type }, .name = MP_QSTR_ADC, .make_new = pyb_adc_make_new, - .locals_dict = (mp_obj_dict_t*)&pyb_adc_locals_dict, + .locals_dict = (mp_obj_dict_t *)&pyb_adc_locals_dict, }; diff --git a/ports/esp8266/machine_hspi.c b/ports/esp8266/machine_hspi.c index 07770c8c89..11c95a3e8a 100644 --- a/ports/esp8266/machine_hspi.c +++ b/ports/esp8266/machine_hspi.c @@ -101,7 +101,7 @@ STATIC void machine_hspi_print(const mp_print_t *print, mp_obj_t self_in, mp_pri } STATIC void machine_hspi_init(mp_obj_base_t *self_in, size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { - machine_hspi_obj_t *self = (machine_hspi_obj_t*)self_in; + machine_hspi_obj_t *self = (machine_hspi_obj_t *)self_in; enum { ARG_baudrate, ARG_polarity, ARG_phase }; static const mp_arg_t allowed_args[] = { @@ -111,7 +111,7 @@ STATIC void machine_hspi_init(mp_obj_base_t *self_in, size_t n_args, const mp_ob }; mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), - allowed_args, args); + allowed_args, args); if (args[ARG_baudrate].u_int != -1) { self->baudrate = args[ARG_baudrate].u_int; @@ -143,10 +143,10 @@ STATIC void machine_hspi_init(mp_obj_base_t *self_in, size_t n_args, const mp_ob spi_tx_byte_order(HSPI, SPI_BYTE_ORDER_HIGH_TO_LOW); spi_rx_byte_order(HSPI, SPI_BYTE_ORDER_HIGH_TO_LOW); CLEAR_PERI_REG_MASK(SPI_USER(HSPI), SPI_FLASH_MODE | SPI_USR_MISO | - SPI_USR_ADDR | SPI_USR_COMMAND | SPI_USR_DUMMY); + SPI_USR_ADDR | SPI_USR_COMMAND | SPI_USR_DUMMY); // Clear Dual or Quad lines transmission mode CLEAR_PERI_REG_MASK(SPI_CTRL(HSPI), SPI_QIO_MODE | SPI_DIO_MODE | - SPI_DOUT_MODE | SPI_QOUT_MODE); + SPI_DOUT_MODE | SPI_QOUT_MODE); spi_mode(HSPI, self->phase, self->polarity); } @@ -165,7 +165,7 @@ mp_obj_t machine_hspi_make_new(const mp_obj_type_t *type, size_t n_args, size_t self->phase = 0; mp_map_t kw_args; mp_map_init_fixed_table(&kw_args, n_kw, args + n_args); - machine_hspi_init((mp_obj_base_t*)self, n_args - 1, args + 1, &kw_args); + machine_hspi_init((mp_obj_base_t *)self, n_args - 1, args + 1, &kw_args); return MP_OBJ_FROM_PTR(self); } @@ -180,7 +180,7 @@ const mp_obj_type_t machine_hspi_type = { .print = machine_hspi_print, .make_new = mp_machine_spi_make_new, // delegate to master constructor .protocol = &machine_hspi_p, - .locals_dict = (mp_obj_dict_t*)&mp_machine_spi_locals_dict, + .locals_dict = (mp_obj_dict_t *)&mp_machine_spi_locals_dict, }; #endif // MICROPY_PY_MACHINE_SPI diff --git a/ports/esp8266/machine_pin.c b/ports/esp8266/machine_pin.c index 14505c8f02..55d006b541 100644 --- a/ports/esp8266/machine_pin.c +++ b/ports/esp8266/machine_pin.c @@ -43,8 +43,8 @@ GPIO_PIN_INT_TYPE_GET(GPIO_REG_READ(GPIO_PIN_ADDR(phys_port))) #define SET_TRIGGER(phys_port, trig) \ (GPIO_REG_WRITE(GPIO_PIN_ADDR(phys_port), \ - (GPIO_REG_READ(GPIO_PIN_ADDR(phys_port)) & ~GPIO_PIN_INT_TYPE_MASK) \ - | GPIO_PIN_INT_TYPE_SET(trig))) \ + (GPIO_REG_READ(GPIO_PIN_ADDR(phys_port)) & ~GPIO_PIN_INT_TYPE_MASK) \ + | GPIO_PIN_INT_TYPE_SET(trig))) \ #define GPIO_MODE_INPUT (0) #define GPIO_MODE_OUTPUT (1) @@ -52,7 +52,7 @@ #define GPIO_PULL_NONE (0) #define GPIO_PULL_UP (1) // Removed in SDK 1.1.0 -//#define GPIO_PULL_DOWN (2) +// #define GPIO_PULL_DOWN (2) typedef struct _pin_irq_obj_t { mp_obj_base_t base; @@ -315,7 +315,7 @@ mp_obj_t mp_pin_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, int wanted_pin = mp_obj_get_int(args[0]); pyb_pin_obj_t *pin = NULL; if (0 <= wanted_pin && wanted_pin < MP_ARRAY_SIZE(pyb_pin_obj)) { - pin = (pyb_pin_obj_t*)&pyb_pin_obj[wanted_pin]; + pin = (pyb_pin_obj_t *)&pyb_pin_obj[wanted_pin]; } if (pin == NULL || pin->base.type == NULL) { mp_raise_ValueError("invalid pin"); @@ -438,7 +438,7 @@ STATIC const mp_rom_map_elem_t pyb_pin_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_OUT), MP_ROM_INT(GPIO_MODE_OUTPUT) }, { MP_ROM_QSTR(MP_QSTR_OPEN_DRAIN), MP_ROM_INT(GPIO_MODE_OPEN_DRAIN) }, { MP_ROM_QSTR(MP_QSTR_PULL_UP), MP_ROM_INT(GPIO_PULL_UP) }, - //{ MP_ROM_QSTR(MP_QSTR_PULL_DOWN), MP_ROM_INT(GPIO_PULL_DOWN) }, + // { MP_ROM_QSTR(MP_QSTR_PULL_DOWN), MP_ROM_INT(GPIO_PULL_DOWN) }, // IRQ triggers, can be or'd together { MP_ROM_QSTR(MP_QSTR_IRQ_RISING), MP_ROM_INT(GPIO_PIN_INTR_POSEDGE) }, @@ -458,7 +458,7 @@ const mp_obj_type_t pyb_pin_type = { .make_new = mp_pin_make_new, .call = pyb_pin_call, .protocol = &pin_pin_p, - .locals_dict = (mp_obj_dict_t*)&pyb_pin_locals_dict, + .locals_dict = (mp_obj_dict_t *)&pyb_pin_locals_dict, }; /******************************************************************************/ @@ -514,5 +514,5 @@ STATIC const mp_obj_type_t pin_irq_type = { { &mp_type_type }, .name = MP_QSTR_IRQ, .call = pin_irq_call, - .locals_dict = (mp_obj_dict_t*)&pin_irq_locals_dict, + .locals_dict = (mp_obj_dict_t *)&pin_irq_locals_dict, }; diff --git a/ports/esp8266/machine_pwm.c b/ports/esp8266/machine_pwm.c index 4c5cb87277..8dedf2d334 100644 --- a/ports/esp8266/machine_pwm.c +++ b/ports/esp8266/machine_pwm.c @@ -122,7 +122,7 @@ STATIC mp_obj_t pyb_pwm_deinit(mp_obj_t self_in) { STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_pwm_deinit_obj, pyb_pwm_deinit); STATIC mp_obj_t pyb_pwm_freq(size_t n_args, const mp_obj_t *args) { - //pyb_pwm_obj_t *self = MP_OBJ_TO_PTR(args[0]); + // pyb_pwm_obj_t *self = MP_OBJ_TO_PTR(args[0]); if (n_args == 1) { // get return MP_OBJ_NEW_SMALL_INT(pwm_get_freq(0)); @@ -167,5 +167,5 @@ const mp_obj_type_t pyb_pwm_type = { .name = MP_QSTR_PWM, .print = pyb_pwm_print, .make_new = pyb_pwm_make_new, - .locals_dict = (mp_obj_dict_t*)&pyb_pwm_locals_dict, + .locals_dict = (mp_obj_dict_t *)&pyb_pwm_locals_dict, }; diff --git a/ports/esp8266/machine_rtc.c b/ports/esp8266/machine_rtc.c index bbfc172cd8..3df2dfcaaf 100644 --- a/ports/esp8266/machine_rtc.c +++ b/ports/esp8266/machine_rtc.c @@ -266,5 +266,5 @@ const mp_obj_type_t pyb_rtc_type = { { &mp_type_type }, .name = MP_QSTR_RTC, .make_new = pyb_rtc_make_new, - .locals_dict = (mp_obj_dict_t*)&pyb_rtc_locals_dict, + .locals_dict = (mp_obj_dict_t *)&pyb_rtc_locals_dict, }; diff --git a/ports/esp8266/machine_uart.c b/ports/esp8266/machine_uart.c index 21336c7fd4..a99a485e82 100644 --- a/ports/esp8266/machine_uart.c +++ b/ports/esp8266/machine_uart.c @@ -69,8 +69,8 @@ STATIC void pyb_uart_init_helper(pyb_uart_obj_t *self, size_t n_args, const mp_o { MP_QSTR_bits, MP_ARG_INT, {.u_int = 0} }, { MP_QSTR_parity, MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, { MP_QSTR_stop, MP_ARG_INT, {.u_int = 0} }, - //{ MP_QSTR_tx, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, - //{ MP_QSTR_rx, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, + // { MP_QSTR_tx, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, + // { MP_QSTR_rx, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, { MP_QSTR_rxbuf, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} }, { MP_QSTR_timeout, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} }, { MP_QSTR_timeout_char, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} }, @@ -250,7 +250,7 @@ STATIC mp_uint_t pyb_uart_read(mp_obj_t self_in, void *buf_in, mp_uint_t size, i *buf++ = uart_rx_char(); if (--size == 0 || !uart_rx_wait(self->timeout_char * 1000)) { // return number of bytes read - return buf - (uint8_t*)buf_in; + return buf - (uint8_t *)buf_in; } } } @@ -310,5 +310,5 @@ const mp_obj_type_t pyb_uart_type = { .getiter = mp_identity_getiter, .iternext = mp_stream_unbuffered_iter, .protocol = &uart_stream_p, - .locals_dict = (mp_obj_dict_t*)&pyb_uart_locals_dict, + .locals_dict = (mp_obj_dict_t *)&pyb_uart_locals_dict, }; diff --git a/ports/esp8266/machine_wdt.c b/ports/esp8266/machine_wdt.c index fad0b2e4de..391575ada4 100644 --- a/ports/esp8266/machine_wdt.c +++ b/ports/esp8266/machine_wdt.c @@ -24,7 +24,7 @@ * THE SOFTWARE. */ -//#include +// #include #include #include "py/runtime.h" @@ -49,12 +49,12 @@ STATIC mp_obj_t machine_wdt_make_new(const mp_obj_type_t *type_in, size_t n_args } switch (id) { - case 0: - ets_loop_dont_feed_sw_wdt = 1; - system_soft_wdt_feed(); - return &wdt_default; - default: - mp_raise_ValueError(NULL); + case 0: + ets_loop_dont_feed_sw_wdt = 1; + system_soft_wdt_feed(); + return &wdt_default; + default: + mp_raise_ValueError(NULL); } } @@ -82,5 +82,5 @@ const mp_obj_type_t esp_wdt_type = { { &mp_type_type }, .name = MP_QSTR_WDT, .make_new = machine_wdt_make_new, - .locals_dict = (mp_obj_dict_t*)&machine_wdt_locals_dict, + .locals_dict = (mp_obj_dict_t *)&machine_wdt_locals_dict, }; diff --git a/ports/esp8266/main.c b/ports/esp8266/main.c index 923e4530fc..eca55729b0 100644 --- a/ports/esp8266/main.c +++ b/ports/esp8266/main.c @@ -46,7 +46,7 @@ STATIC char heap[38 * 1024]; STATIC void mp_reset(void) { - mp_stack_set_top((void*)0x40000000); + mp_stack_set_top((void *)0x40000000); mp_stack_set_limit(8192); mp_hal_init(); gc_init(heap, heap + sizeof(heap)); @@ -157,7 +157,7 @@ void MP_FASTCODE(nlr_jump_fail)(void *val) { } } -//void __assert(const char *file, int line, const char *func, const char *expr) { +// void __assert(const char *file, int line, const char *func, const char *expr) { void __assert(const char *file, int line, const char *expr) { printf("Assertion '%s' failed, at file %s:%d\n", expr, file, line); for (;;) { diff --git a/ports/esp8266/makeimg.py b/ports/esp8266/makeimg.py index 091854fa4d..a81b2d0c27 100644 --- a/ports/esp8266/makeimg.py +++ b/ports/esp8266/makeimg.py @@ -8,33 +8,33 @@ assert len(sys.argv) == 4 md5 = hashlib.md5() -with open(sys.argv[3], 'wb') as fout: +with open(sys.argv[3], "wb") as fout: - with open(sys.argv[1], 'rb') as f: + with open(sys.argv[1], "rb") as f: data_flash = f.read() fout.write(data_flash) # First 4 bytes include flash size, etc. which may be changed # by esptool.py, etc. md5.update(data_flash[4:]) - print('flash ', len(data_flash)) + print("flash ", len(data_flash)) - with open(sys.argv[2], 'rb') as f: + with open(sys.argv[2], "rb") as f: data_rom = f.read() - pad = b'\xff' * (SEGS_MAX_SIZE - len(data_flash)) + pad = b"\xff" * (SEGS_MAX_SIZE - len(data_flash)) assert len(pad) >= 4 fout.write(pad[:-4]) md5.update(pad[:-4]) len_data = struct.pack("I", SEGS_MAX_SIZE + len(data_rom)) fout.write(len_data) md5.update(len_data) - print('padding ', len(pad)) + print("padding ", len(pad)) fout.write(data_rom) md5.update(data_rom) - print('irom0text', len(data_rom)) + print("irom0text", len(data_rom)) fout.write(md5.digest()) - print('total ', SEGS_MAX_SIZE + len(data_rom)) - print('md5 ', md5.hexdigest()) + print("total ", SEGS_MAX_SIZE + len(data_rom)) + print("md5 ", md5.hexdigest()) diff --git a/ports/esp8266/modesp.c b/ports/esp8266/modesp.c index 46cd24c030..c4d8c21cca 100644 --- a/ports/esp8266/modesp.c +++ b/ports/esp8266/modesp.c @@ -100,7 +100,7 @@ STATIC mp_obj_t esp_flash_read(mp_obj_t offset_in, mp_obj_t len_or_buf_in) { } // We know that allocation will be 4-byte aligned for sure - SpiFlashOpResult res = spi_flash_read(offset, (uint32_t*)buf, len); + SpiFlashOpResult res = spi_flash_read(offset, (uint32_t *)buf, len); if (res == SPI_FLASH_RESULT_OK) { if (alloc_buf) { return mp_obj_new_bytes(buf, len); @@ -147,7 +147,7 @@ STATIC mp_obj_t esp_flash_size(void) { extern char flashchip; // For SDK 1.5.2, either address has shifted and not mirrored in // eagle.rom.addr.v6.ld, or extra initial member was added. - SpiFlashChip *flash = (SpiFlashChip*)(&flashchip + 4); + SpiFlashChip *flash = (SpiFlashChip *)(&flashchip + 4); #if 0 printf("deviceId: %x\n", flash->deviceId); printf("chip_size: %u\n", flash->chip_size); @@ -162,7 +162,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_0(esp_flash_size_obj, esp_flash_size); // If there's just 1 loadable segment at the start of flash, // we assume there's a yaota8266 bootloader. -#define IS_OTA_FIRMWARE() ((*(uint32_t*)0x40200000 & 0xff00) == 0x100) +#define IS_OTA_FIRMWARE() ((*(uint32_t *)0x40200000 & 0xff00) == 0x100) extern byte _firmware_size[]; @@ -173,13 +173,13 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_0(esp_flash_user_start_obj, esp_flash_user_start) STATIC mp_obj_t esp_check_fw(void) { MD5_CTX ctx; - char *fw_start = (char*)0x40200000; + char *fw_start = (char *)0x40200000; if (IS_OTA_FIRMWARE()) { // Skip yaota8266 bootloader fw_start += 0x3c000; } - uint32_t size = *(uint32_t*)(fw_start + 0x8ffc); + uint32_t size = *(uint32_t *)(fw_start + 0x8ffc); printf("size: %d\n", size); if (size > 1024 * 1024) { printf("Invalid size\n"); @@ -203,7 +203,7 @@ STATIC mp_obj_t esp_neopixel_write_(mp_obj_t pin, mp_obj_t buf, mp_obj_t is800k) mp_buffer_info_t bufinfo; mp_get_buffer_raise(buf, &bufinfo, MP_BUFFER_READ); esp_neopixel_write(mp_obj_get_pin_obj(pin)->phys_port, - (uint8_t*)bufinfo.buf, bufinfo.len, mp_obj_is_true(is800k)); + (uint8_t *)bufinfo.buf, bufinfo.len, mp_obj_is_true(is800k)); return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_3(esp_neopixel_write_obj, esp_neopixel_write_); @@ -214,7 +214,7 @@ STATIC mp_obj_t esp_apa102_write_(mp_obj_t clockPin, mp_obj_t dataPin, mp_obj_t mp_get_buffer_raise(buf, &bufinfo, MP_BUFFER_READ); esp_apa102_write(mp_obj_get_pin_obj(clockPin)->phys_port, mp_obj_get_pin_obj(dataPin)->phys_port, - (uint8_t*)bufinfo.buf, bufinfo.len); + (uint8_t *)bufinfo.buf, bufinfo.len); return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_3(esp_apa102_write_obj, esp_apa102_write_); @@ -237,7 +237,7 @@ STATIC mp_obj_t esp_malloc(mp_obj_t size_in) { STATIC MP_DEFINE_CONST_FUN_OBJ_1(esp_malloc_obj, esp_malloc); STATIC mp_obj_t esp_free(mp_obj_t addr_in) { - os_free((void*)mp_obj_get_int(addr_in)); + os_free((void *)mp_obj_get_int(addr_in)); return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_1(esp_free_obj, esp_free); @@ -283,7 +283,7 @@ void esp_native_code_init(void) { } void *esp_native_code_commit(void *buf, size_t len) { - //printf("COMMIT(buf=%p, len=%u, start=%08x, cur=%08x, end=%08x, erased=%08x)\n", buf, len, esp_native_code_start, esp_native_code_cur, esp_native_code_end, esp_native_code_erased); + // printf("COMMIT(buf=%p, len=%u, start=%08x, cur=%08x, end=%08x, erased=%08x)\n", buf, len, esp_native_code_start, esp_native_code_cur, esp_native_code_end, esp_native_code_erased); len = (len + 3) & ~3; if (esp_native_code_cur + len > esp_native_code_end) { @@ -293,7 +293,7 @@ void *esp_native_code_commit(void *buf, size_t len) { void *dest; if (esp_native_code_location == ESP_NATIVE_CODE_IRAM1) { - dest = (void*)esp_native_code_cur; + dest = (void *)esp_native_code_cur; memcpy(dest, buf, len); } else { SpiFlashOpResult res; @@ -313,7 +313,7 @@ void *esp_native_code_commit(void *buf, size_t len) { if (res != SPI_FLASH_RESULT_OK) { mp_raise_OSError(res == SPI_FLASH_RESULT_TIMEOUT ? MP_ETIMEDOUT : MP_EIO); } - dest = (void*)(FLASH_START + esp_native_code_cur); + dest = (void *)(FLASH_START + esp_native_code_cur); } esp_native_code_cur += len; @@ -373,16 +373,16 @@ STATIC const mp_rom_map_elem_t esp_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_set_native_code_location), MP_ROM_PTR(&esp_set_native_code_location_obj) }, #endif -#if MODESP_INCLUDE_CONSTANTS + #if MODESP_INCLUDE_CONSTANTS { MP_ROM_QSTR(MP_QSTR_SLEEP_NONE), MP_ROM_INT(NONE_SLEEP_T) }, { MP_ROM_QSTR(MP_QSTR_SLEEP_LIGHT), MP_ROM_INT(LIGHT_SLEEP_T) }, { MP_ROM_QSTR(MP_QSTR_SLEEP_MODEM), MP_ROM_INT(MODEM_SLEEP_T) }, -#endif + #endif }; STATIC MP_DEFINE_CONST_DICT(esp_module_globals, esp_module_globals_table); const mp_obj_module_t esp_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&esp_module_globals, + .globals = (mp_obj_dict_t *)&esp_module_globals, }; diff --git a/ports/esp8266/modmachine.c b/ports/esp8266/modmachine.c index 1c1d902e5e..e8a6bf1eda 100644 --- a/ports/esp8266/modmachine.c +++ b/ports/esp8266/modmachine.c @@ -49,8 +49,8 @@ #if MICROPY_PY_MACHINE -//#define MACHINE_WAKE_IDLE (0x01) -//#define MACHINE_WAKE_SLEEP (0x02) +// #define MACHINE_WAKE_IDLE (0x01) +// #define MACHINE_WAKE_SLEEP (0x02) #define MACHINE_WAKE_DEEPSLEEP (0x04) extern const mp_obj_type_t esp_wdt_type; @@ -84,13 +84,13 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_0(machine_reset_cause_obj, machine_reset_cause); STATIC mp_obj_t machine_unique_id(void) { uint32_t id = system_get_chip_id(); - return mp_obj_new_bytes((byte*)&id, sizeof(id)); + return mp_obj_new_bytes((byte *)&id, sizeof(id)); } STATIC MP_DEFINE_CONST_FUN_OBJ_0(machine_unique_id_obj, machine_unique_id); STATIC mp_obj_t machine_idle(void) { uint32_t t = mp_hal_ticks_cpu(); - asm("waiti 0"); + asm ("waiti 0"); t = mp_hal_ticks_cpu() - t; return MP_OBJ_NEW_SMALL_INT(t); } @@ -176,11 +176,11 @@ STATIC mp_obj_t esp_timer_init_helper(esp_timer_obj_t *self, size_t n_args, cons { MP_QSTR_callback, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, { MP_QSTR_period, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0xffffffff} }, { MP_QSTR_tick_hz, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 1000} }, -#if MICROPY_PY_BUILTINS_FLOAT + #if MICROPY_PY_BUILTINS_FLOAT { MP_QSTR_freq, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, -#else + #else { MP_QSTR_freq, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0xffffffff} }, -#endif + #endif }; // parse args @@ -192,7 +192,7 @@ STATIC mp_obj_t esp_timer_init_helper(esp_timer_obj_t *self, size_t n_args, cons os_timer_disarm(&self->timer); os_timer_setfn(&self->timer, esp_timer_cb, self); -#if MICROPY_PY_BUILTINS_FLOAT + #if MICROPY_PY_BUILTINS_FLOAT if (args[ARG_freq].u_obj != mp_const_none) { mp_float_t freq = mp_obj_get_float(args[ARG_freq].u_obj); if (freq < 0.001) { @@ -201,11 +201,11 @@ STATIC mp_obj_t esp_timer_init_helper(esp_timer_obj_t *self, size_t n_args, cons os_timer_arm_us(&self->timer, (mp_int_t)(1000000 / freq), args[ARG_mode].u_int); } } -#else + #else if (args[ARG_freq].u_int != 0xffffffff) { os_timer_arm_us(&self->timer, 1000000 / args[ARG_freq].u_int, args[ARG_mode].u_int); } -#endif + #endif else { mp_int_t period = args[ARG_period].u_int; mp_int_t hz = args[ARG_tick_hz].u_int; @@ -253,7 +253,7 @@ const mp_obj_type_t esp_timer_type = { .name = MP_QSTR_Timer, .print = esp_timer_print, .make_new = esp_timer_make_new, - .locals_dict = (mp_obj_dict_t*)&esp_timer_locals_dict, + .locals_dict = (mp_obj_dict_t *)&esp_timer_locals_dict, }; // this bit is unused in the Xtensa PS register @@ -324,7 +324,7 @@ STATIC MP_DEFINE_CONST_DICT(machine_module_globals, machine_module_globals_table const mp_obj_module_t mp_module_machine = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&machine_module_globals, + .globals = (mp_obj_dict_t *)&machine_module_globals, }; #endif // MICROPY_PY_MACHINE diff --git a/ports/esp8266/modnetwork.c b/ports/esp8266/modnetwork.c index 6ef2d315d6..38f29941ff 100644 --- a/ports/esp8266/modnetwork.c +++ b/ports/esp8266/modnetwork.c @@ -204,7 +204,7 @@ STATIC void esp_scan_cb(void *result, STATUS status) { // but is present in SDK headers since 1.4.0 t->items[0] = mp_obj_new_bytes(bs->ssid, bs->ssid_len); #else - t->items[0] = mp_obj_new_bytes(bs->ssid, strlen((char*)bs->ssid)); + t->items[0] = mp_obj_new_bytes(bs->ssid, strlen((char *)bs->ssid)); #endif t->items[1] = mp_obj_new_bytes(bs->bssid, sizeof(bs->bssid)); t->items[2] = MP_OBJ_NEW_SMALL_INT(bs->channel); @@ -281,10 +281,10 @@ STATIC mp_obj_t esp_ifconfig(size_t n_args, const mp_obj_t *args) { // get dns_addr = dns_getserver(0); mp_obj_t tuple[4] = { - netutils_format_ipv4_addr((uint8_t*)&info.ip, NETUTILS_BIG), - netutils_format_ipv4_addr((uint8_t*)&info.netmask, NETUTILS_BIG), - netutils_format_ipv4_addr((uint8_t*)&info.gw, NETUTILS_BIG), - netutils_format_ipv4_addr((uint8_t*)&dns_addr, NETUTILS_BIG), + netutils_format_ipv4_addr((uint8_t *)&info.ip, NETUTILS_BIG), + netutils_format_ipv4_addr((uint8_t *)&info.netmask, NETUTILS_BIG), + netutils_format_ipv4_addr((uint8_t *)&info.gw, NETUTILS_BIG), + netutils_format_ipv4_addr((uint8_t *)&dns_addr, NETUTILS_BIG), }; return mp_obj_new_tuple(4, tuple); } else { @@ -292,19 +292,19 @@ STATIC mp_obj_t esp_ifconfig(size_t n_args, const mp_obj_t *args) { mp_obj_t *items; bool restart_dhcp_server = false; mp_obj_get_array_fixed_n(args[1], 4, &items); - netutils_parse_ipv4_addr(items[0], (void*)&info.ip, NETUTILS_BIG); + netutils_parse_ipv4_addr(items[0], (void *)&info.ip, NETUTILS_BIG); if (mp_obj_is_integer(items[1])) { // allow numeric netmask, i.e.: // 24 -> 255.255.255.0 // 16 -> 255.255.0.0 // etc... - uint32_t* m = (uint32_t*)&info.netmask; + uint32_t *m = (uint32_t *)&info.netmask; *m = htonl(0xffffffff << (32 - mp_obj_get_int(items[1]))); } else { - netutils_parse_ipv4_addr(items[1], (void*)&info.netmask, NETUTILS_BIG); + netutils_parse_ipv4_addr(items[1], (void *)&info.netmask, NETUTILS_BIG); } - netutils_parse_ipv4_addr(items[2], (void*)&info.gw, NETUTILS_BIG); - netutils_parse_ipv4_addr(items[3], (void*)&dns_addr, NETUTILS_BIG); + netutils_parse_ipv4_addr(items[2], (void *)&info.gw, NETUTILS_BIG); + netutils_parse_ipv4_addr(items[3], (void *)&dns_addr, NETUTILS_BIG); // To set a static IP we have to disable DHCP first if (self->if_id == STATION_IF) { wifi_station_dhcpc_stop(); @@ -313,8 +313,8 @@ STATIC mp_obj_t esp_ifconfig(size_t n_args, const mp_obj_t *args) { wifi_softap_dhcps_stop(); } if (!wifi_set_ip_info(self->if_id, &info)) { - nlr_raise(mp_obj_new_exception_msg(&mp_type_OSError, - "wifi_set_ip_info() failed")); + nlr_raise(mp_obj_new_exception_msg(&mp_type_OSError, + "wifi_set_ip_info() failed")); } dns_setserver(0, &dns_addr); if (restart_dhcp_server) { @@ -396,14 +396,14 @@ STATIC mp_obj_t esp_config(size_t n_args, const mp_obj_t *args, mp_map_t *kwargs req_if = STATION_IF; if (self->if_id == STATION_IF) { const char *s = mp_obj_str_get_str(kwargs->table[i].value); - wifi_station_set_hostname((char*)s); + wifi_station_set_hostname((char *)s); } break; } default: goto unknown; } - #undef QS +#undef QS } } @@ -438,9 +438,9 @@ STATIC mp_obj_t esp_config(size_t n_args, const mp_obj_t *args, mp_map_t *kwargs } case MP_QSTR_essid: if (self->if_id == STATION_IF) { - val = mp_obj_new_str((char*)cfg.sta.ssid, strlen((char*)cfg.sta.ssid)); + val = mp_obj_new_str((char *)cfg.sta.ssid, strlen((char *)cfg.sta.ssid)); } else { - val = mp_obj_new_str((char*)cfg.ap.ssid, cfg.ap.ssid_len); + val = mp_obj_new_str((char *)cfg.ap.ssid, cfg.ap.ssid_len); } break; case MP_QSTR_hidden: @@ -457,7 +457,7 @@ STATIC mp_obj_t esp_config(size_t n_args, const mp_obj_t *args, mp_map_t *kwargs break; case MP_QSTR_dhcp_hostname: { req_if = STATION_IF; - char* s = wifi_station_get_hostname(); + char *s = wifi_station_get_hostname(); if (s == NULL) { val = MP_OBJ_NEW_QSTR(MP_QSTR_); } else { @@ -497,7 +497,7 @@ STATIC MP_DEFINE_CONST_DICT(wlan_if_locals_dict, wlan_if_locals_dict_table); const mp_obj_type_t wlan_if_type = { { &mp_type_type }, .name = MP_QSTR_WLAN, - .locals_dict = (mp_obj_dict_t*)&wlan_if_locals_dict, + .locals_dict = (mp_obj_dict_t *)&wlan_if_locals_dict, }; STATIC mp_obj_t esp_phy_mode(size_t n_args, const mp_obj_t *args) { @@ -515,7 +515,7 @@ STATIC const mp_rom_map_elem_t mp_module_network_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_WLAN), MP_ROM_PTR(&get_wlan_obj) }, { MP_ROM_QSTR(MP_QSTR_phy_mode), MP_ROM_PTR(&esp_phy_mode_obj) }, -#if MODNETWORK_INCLUDE_CONSTANTS + #if MODNETWORK_INCLUDE_CONSTANTS { MP_ROM_QSTR(MP_QSTR_STA_IF), MP_ROM_INT(STATION_IF)}, { MP_ROM_QSTR(MP_QSTR_AP_IF), MP_ROM_INT(SOFTAP_IF)}, @@ -535,12 +535,12 @@ STATIC const mp_rom_map_elem_t mp_module_network_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_AUTH_WPA_PSK), MP_ROM_INT(AUTH_WPA_PSK) }, { MP_ROM_QSTR(MP_QSTR_AUTH_WPA2_PSK), MP_ROM_INT(AUTH_WPA2_PSK) }, { MP_ROM_QSTR(MP_QSTR_AUTH_WPA_WPA2_PSK), MP_ROM_INT(AUTH_WPA_WPA2_PSK) }, -#endif + #endif }; STATIC MP_DEFINE_CONST_DICT(mp_module_network_globals, mp_module_network_globals_table); const mp_obj_module_t network_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_network_globals, + .globals = (mp_obj_dict_t *)&mp_module_network_globals, }; diff --git a/ports/esp8266/moduos.c b/ports/esp8266/moduos.c index 7a32c11c07..377e7fd730 100644 --- a/ports/esp8266/moduos.c +++ b/ports/esp8266/moduos.c @@ -125,5 +125,5 @@ STATIC MP_DEFINE_CONST_DICT(os_module_globals, os_module_globals_table); const mp_obj_module_t uos_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&os_module_globals, + .globals = (mp_obj_dict_t *)&os_module_globals, }; diff --git a/ports/esp8266/modutime.c b/ports/esp8266/modutime.c index ab9cb7dc23..ccd6b40c48 100644 --- a/ports/esp8266/modutime.c +++ b/ports/esp8266/modutime.c @@ -92,8 +92,8 @@ STATIC mp_obj_t time_mktime(mp_obj_t tuple) { } return mp_obj_new_int_from_uint(timeutils_mktime(mp_obj_get_int(elem[0]), - mp_obj_get_int(elem[1]), mp_obj_get_int(elem[2]), mp_obj_get_int(elem[3]), - mp_obj_get_int(elem[4]), mp_obj_get_int(elem[5]))); + mp_obj_get_int(elem[1]), mp_obj_get_int(elem[2]), mp_obj_get_int(elem[3]), + mp_obj_get_int(elem[4]), mp_obj_get_int(elem[5]))); } MP_DEFINE_CONST_FUN_OBJ_1(time_mktime_obj, time_mktime); @@ -125,5 +125,5 @@ STATIC MP_DEFINE_CONST_DICT(time_module_globals, time_module_globals_table); const mp_obj_module_t utime_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&time_module_globals, + .globals = (mp_obj_dict_t *)&time_module_globals, }; diff --git a/ports/esp8266/mpconfigport.h b/ports/esp8266/mpconfigport.h index b2a05e6791..c523f6155f 100644 --- a/ports/esp8266/mpconfigport.h +++ b/ports/esp8266/mpconfigport.h @@ -122,13 +122,13 @@ vm_hook_divisor = MICROPY_VM_HOOK_COUNT; \ extern void ets_loop_iter(void); \ ets_loop_iter(); \ - } +} #define MICROPY_VM_HOOK_LOOP MICROPY_VM_HOOK_POLL #define MICROPY_VM_HOOK_RETURN MICROPY_VM_HOOK_POLL // type definitions for the specific machine -#define MICROPY_MAKE_POINTER_CALLABLE(p) ((void*)((mp_uint_t)(p))) +#define MICROPY_MAKE_POINTER_CALLABLE(p) ((void *)((mp_uint_t)(p))) #define MP_SSIZE_MAX (0x7fffffff) @@ -143,7 +143,7 @@ typedef uint32_t sys_prot_t; // for modlwip #include #define MP_PLAT_PRINT_STRN(str, len) mp_hal_stdout_tx_strn_cooked(str, len) -void *esp_native_code_commit(void*, size_t); +void *esp_native_code_commit(void *, size_t); #define MP_PLAT_COMMIT_EXEC(buf, len) esp_native_code_commit(buf, len) // printer for debugging output, goes to UART only diff --git a/ports/esp8266/qstrdefsport.h b/ports/esp8266/qstrdefsport.h index 8f301a69c5..bad5aa5797 100644 --- a/ports/esp8266/qstrdefsport.h +++ b/ports/esp8266/qstrdefsport.h @@ -28,4 +28,4 @@ // Entries for sys.path Q(/) -Q(/lib) +Q(/ lib) diff --git a/ports/esp8266/strtoll.c b/ports/esp8266/strtoll.c index 4e8a4d0566..f095f7606d 100644 --- a/ports/esp8266/strtoll.c +++ b/ports/esp8266/strtoll.c @@ -23,7 +23,7 @@ long long int strtoll(const char *nptr, char **endptr, int base) { val = val * base + v; } - *endptr = (char*)nptr; + *endptr = (char *)nptr; return val; } diff --git a/ports/esp8266/uart.c b/ports/esp8266/uart.c index cf9e8f61b2..784994fcc6 100644 --- a/ports/esp8266/uart.c +++ b/ports/esp8266/uart.c @@ -65,9 +65,9 @@ static void ICACHE_FLASH_ATTR uart_config(uint8 uart_no) { uart_div_modify(uart_no, UART_CLK_FREQ / (UartDev.baut_rate)); WRITE_PERI_REG(UART_CONF0(uart_no), UartDev.exist_parity - | UartDev.parity - | (UartDev.stop_bits << UART_STOP_BIT_NUM_S) - | (UartDev.data_bits << UART_BIT_NUM_S)); + | UartDev.parity + | (UartDev.stop_bits << UART_STOP_BIT_NUM_S) + | (UartDev.data_bits << UART_BIT_NUM_S)); // clear rx and tx fifo,not ready SET_PERI_REG_MASK(UART_CONF0(uart_no), UART_RXFIFO_RST | UART_TXFIFO_RST); @@ -76,16 +76,16 @@ static void ICACHE_FLASH_ATTR uart_config(uint8 uart_no) { if (uart_no == UART0) { // set rx fifo trigger WRITE_PERI_REG(UART_CONF1(uart_no), - ((0x10 & UART_RXFIFO_FULL_THRHD) << UART_RXFIFO_FULL_THRHD_S) | - ((0x10 & UART_RX_FLOW_THRHD) << UART_RX_FLOW_THRHD_S) | - UART_RX_FLOW_EN | - (0x02 & UART_RX_TOUT_THRHD) << UART_RX_TOUT_THRHD_S | - UART_RX_TOUT_EN); + ((0x10 & UART_RXFIFO_FULL_THRHD) << UART_RXFIFO_FULL_THRHD_S) | + ((0x10 & UART_RX_FLOW_THRHD) << UART_RX_FLOW_THRHD_S) | + UART_RX_FLOW_EN | + (0x02 & UART_RX_TOUT_THRHD) << UART_RX_TOUT_THRHD_S | + UART_RX_TOUT_EN); SET_PERI_REG_MASK(UART_INT_ENA(uart_no), UART_RXFIFO_TOUT_INT_ENA | - UART_FRM_ERR_INT_ENA); + UART_FRM_ERR_INT_ENA); } else { WRITE_PERI_REG(UART_CONF1(uart_no), - ((UartDev.rcv_buff.TrigLvl & UART_RXFIFO_FULL_THRHD) << UART_RXFIFO_FULL_THRHD_S)); + ((UartDev.rcv_buff.TrigLvl & UART_RXFIFO_FULL_THRHD) << UART_RXFIFO_FULL_THRHD_S)); } // clear all interrupt @@ -103,7 +103,7 @@ static void ICACHE_FLASH_ATTR uart_config(uint8 uart_no) { *******************************************************************************/ void uart_tx_one_char(uint8 uart, uint8 TxChar) { while (true) { - uint32 fifo_cnt = READ_PERI_REG(UART_STATUS(uart)) & (UART_TXFIFO_CNT<> UART_TXFIFO_CNT_S & UART_TXFIFO_CNT) < 126) { break; } @@ -113,7 +113,7 @@ void uart_tx_one_char(uint8 uart, uint8 TxChar) { void uart_flush(uint8 uart) { while (true) { - uint32 fifo_cnt = READ_PERI_REG(UART_STATUS(uart)) & (UART_TXFIFO_CNT<> UART_TXFIFO_CNT_S & UART_TXFIFO_CNT) == 0) { break; } @@ -155,9 +155,9 @@ uart_os_config(int uart) { *******************************************************************************/ static void uart0_rx_intr_handler(void *para) { - /* uart0 and uart1 intr combine togther, when interrupt occur, see reg 0x3ff20020, bit2, bit0 represents - * uart1 and uart0 respectively - */ + /* uart0 and uart1 intr combine togther, when interrupt occur, see reg 0x3ff20020, bit2, bit0 represents + * uart1 and uart0 respectively + */ uint8 uart_no = UART_REPL; @@ -170,7 +170,7 @@ static void uart0_rx_intr_handler(void *para) { // fifo full goto read_chars; } else if (UART_RXFIFO_TOUT_INT_ST == (READ_PERI_REG(UART_INT_ST(uart_no)) & UART_RXFIFO_TOUT_INT_ST)) { - read_chars: + read_chars: ETS_UART_INTR_DISABLE(); while (READ_PERI_REG(UART_STATUS(uart_no)) & (UART_RXFIFO_CNT << UART_RXFIFO_CNT_S)) { diff --git a/ports/esp8266/uart.h b/ports/esp8266/uart.h index 0e67783cd8..de0919bde0 100644 --- a/ports/esp8266/uart.h +++ b/ports/esp8266/uart.h @@ -58,17 +58,17 @@ typedef enum { } RcvMsgBuffState; typedef struct { - uint32 RcvBuffSize; - uint8 *pRcvMsgBuff; - uint8 *pWritePos; - uint8 *pReadPos; - uint8 TrigLvl; //JLU: may need to pad - RcvMsgBuffState BuffState; + uint32 RcvBuffSize; + uint8 *pRcvMsgBuff; + uint8 *pWritePos; + uint8 *pReadPos; + uint8 TrigLvl; // JLU: may need to pad + RcvMsgBuffState BuffState; } RcvMsgBuff; typedef struct { - uint32 TrxBuffSize; - uint8 *pTrxBuff; + uint32 TrxBuffSize; + uint8 *pTrxBuff; } TrxMsgBuff; typedef enum { @@ -80,17 +80,17 @@ typedef enum { } RcvMsgState; typedef struct { - UartBautRate baut_rate; - UartBitsNum4Char data_bits; - UartExistParity exist_parity; - UartParityMode parity; // chip size in byte - UartStopBitsNum stop_bits; - UartFlowCtrl flow_ctrl; - RcvMsgBuff rcv_buff; - TrxMsgBuff trx_buff; - RcvMsgState rcv_state; - int received; - int buff_uart_no; //indicate which uart use tx/rx buffer + UartBautRate baut_rate; + UartBitsNum4Char data_bits; + UartExistParity exist_parity; + UartParityMode parity; // chip size in byte + UartStopBitsNum stop_bits; + UartFlowCtrl flow_ctrl; + RcvMsgBuff rcv_buff; + TrxMsgBuff trx_buff; + RcvMsgState rcv_state; + int received; + int buff_uart_no; // indicate which uart use tx/rx buffer } UartDevice; extern uint8 uart_ringbuf_array[UART0_STATIC_RXBUF_LEN]; diff --git a/ports/esp8266/uart_register.h b/ports/esp8266/uart_register.h index 6398879ee2..f0d646a525 100644 --- a/ports/esp8266/uart_register.h +++ b/ports/esp8266/uart_register.h @@ -1,4 +1,4 @@ -//Generated at 2012-07-03 18:44:06 +// Generated at 2012-07-03 18:44:06 /* * Copyright (c) 2010 - 2011 Espressif System * @@ -6,14 +6,14 @@ #ifndef UART_REGISTER_H_INCLUDED #define UART_REGISTER_H_INCLUDED -#define REG_UART_BASE( i ) (0x60000000+(i)*0xf00) -//version value:32'h062000 +#define REG_UART_BASE(i) (0x60000000 + (i) * 0xf00) +// version value:32'h062000 -#define UART_FIFO( i ) (REG_UART_BASE( i ) + 0x0) +#define UART_FIFO(i) (REG_UART_BASE(i) + 0x0) #define UART_RXFIFO_RD_BYTE 0x000000FF #define UART_RXFIFO_RD_BYTE_S 0 -#define UART_INT_RAW( i ) (REG_UART_BASE( i ) + 0x4) +#define UART_INT_RAW(i) (REG_UART_BASE(i) + 0x4) #define UART_RXFIFO_TOUT_INT_RAW (BIT(8)) #define UART_BRK_DET_INT_RAW (BIT(7)) #define UART_CTS_CHG_INT_RAW (BIT(6)) @@ -24,7 +24,7 @@ #define UART_TXFIFO_EMPTY_INT_RAW (BIT(1)) #define UART_RXFIFO_FULL_INT_RAW (BIT(0)) -#define UART_INT_ST( i ) (REG_UART_BASE( i ) + 0x8) +#define UART_INT_ST(i) (REG_UART_BASE(i) + 0x8) #define UART_RXFIFO_TOUT_INT_ST (BIT(8)) #define UART_BRK_DET_INT_ST (BIT(7)) #define UART_CTS_CHG_INT_ST (BIT(6)) @@ -35,7 +35,7 @@ #define UART_TXFIFO_EMPTY_INT_ST (BIT(1)) #define UART_RXFIFO_FULL_INT_ST (BIT(0)) -#define UART_INT_ENA( i ) (REG_UART_BASE( i ) + 0xC) +#define UART_INT_ENA(i) (REG_UART_BASE(i) + 0xC) #define UART_RXFIFO_TOUT_INT_ENA (BIT(8)) #define UART_BRK_DET_INT_ENA (BIT(7)) #define UART_CTS_CHG_INT_ENA (BIT(6)) @@ -46,7 +46,7 @@ #define UART_TXFIFO_EMPTY_INT_ENA (BIT(1)) #define UART_RXFIFO_FULL_INT_ENA (BIT(0)) -#define UART_INT_CLR( i ) (REG_UART_BASE( i ) + 0x10) +#define UART_INT_CLR(i) (REG_UART_BASE(i) + 0x10) #define UART_RXFIFO_TOUT_INT_CLR (BIT(8)) #define UART_BRK_DET_INT_CLR (BIT(7)) #define UART_CTS_CHG_INT_CLR (BIT(6)) @@ -57,16 +57,16 @@ #define UART_TXFIFO_EMPTY_INT_CLR (BIT(1)) #define UART_RXFIFO_FULL_INT_CLR (BIT(0)) -#define UART_CLKDIV( i ) (REG_UART_BASE( i ) + 0x14) +#define UART_CLKDIV(i) (REG_UART_BASE(i) + 0x14) #define UART_CLKDIV_CNT 0x000FFFFF #define UART_CLKDIV_S 0 -#define UART_AUTOBAUD( i ) (REG_UART_BASE( i ) + 0x18) +#define UART_AUTOBAUD(i) (REG_UART_BASE(i) + 0x18) #define UART_GLITCH_FILT 0x000000FF #define UART_GLITCH_FILT_S 8 #define UART_AUTOBAUD_EN (BIT(0)) -#define UART_STATUS( i ) (REG_UART_BASE( i ) + 0x1C) +#define UART_STATUS(i) (REG_UART_BASE(i) + 0x1C) #define UART_TXD (BIT(31)) #define UART_RTSN (BIT(30)) #define UART_DTRN (BIT(29)) @@ -78,7 +78,7 @@ #define UART_RXFIFO_CNT 0x000000FF #define UART_RXFIFO_CNT_S 0 -#define UART_CONF0( i ) (REG_UART_BASE( i ) + 0x20) +#define UART_CONF0(i) (REG_UART_BASE(i) + 0x20) #define UART_TXFIFO_RST (BIT(18)) #define UART_RXFIFO_RST (BIT(17)) #define UART_IRDA_EN (BIT(16)) @@ -99,7 +99,7 @@ #define UART_PARITY_EN (BIT(1)) #define UART_PARITY (BIT(0)) -#define UART_CONF1( i ) (REG_UART_BASE( i ) + 0x24) +#define UART_CONF1(i) (REG_UART_BASE(i) + 0x24) #define UART_RX_TOUT_EN (BIT(31)) #define UART_RX_TOUT_THRHD 0x0000007F #define UART_RX_TOUT_THRHD_S 24 @@ -111,18 +111,18 @@ #define UART_RXFIFO_FULL_THRHD 0x0000007F #define UART_RXFIFO_FULL_THRHD_S 0 -#define UART_LOWPULSE( i ) (REG_UART_BASE( i ) + 0x28) +#define UART_LOWPULSE(i) (REG_UART_BASE(i) + 0x28) #define UART_LOWPULSE_MIN_CNT 0x000FFFFF #define UART_LOWPULSE_MIN_CNT_S 0 -#define UART_HIGHPULSE( i ) (REG_UART_BASE( i ) + 0x2C) +#define UART_HIGHPULSE(i) (REG_UART_BASE(i) + 0x2C) #define UART_HIGHPULSE_MIN_CNT 0x000FFFFF #define UART_HIGHPULSE_MIN_CNT_S 0 -#define UART_PULSE_NUM( i ) (REG_UART_BASE( i ) + 0x30) +#define UART_PULSE_NUM(i) (REG_UART_BASE(i) + 0x30) #define UART_PULSE_NUM_CNT 0x0003FF #define UART_PULSE_NUM_CNT_S 0 -#define UART_DATE( i ) (REG_UART_BASE( i ) + 0x78) -#define UART_ID( i ) (REG_UART_BASE( i ) + 0x7C) +#define UART_DATE(i) (REG_UART_BASE(i) + 0x78) +#define UART_ID(i) (REG_UART_BASE(i) + 0x7C) #endif // UART_REGISTER_H_INCLUDED diff --git a/ports/esp8266/xtirq.h b/ports/esp8266/xtirq.h index 595052fc73..835f06bcae 100644 --- a/ports/esp8266/xtirq.h +++ b/ports/esp8266/xtirq.h @@ -31,7 +31,7 @@ // returns the value of "intlevel" from the PS register static inline uint32_t query_irq(void) { uint32_t ps; - __asm__ volatile("rsr %0, ps" : "=a" (ps)); + __asm__ volatile ("rsr %0, ps" : "=a" (ps)); return ps & 0xf; } @@ -45,7 +45,7 @@ static inline uint32_t raise_irq_pri(uint32_t intlevel) { // "ps" should be the value returned from raise_irq_pri static inline void restore_irq_pri(uint32_t ps) { - __asm__ volatile ("wsr %0, ps; rsync" :: "a" (ps)); + __asm__ volatile ("wsr %0, ps; rsync" : : "a" (ps)); } static inline uint32_t disable_irq(void) { diff --git a/ports/minimal/frozentest.py b/ports/minimal/frozentest.py index 0f99b74297..78cdd60bf0 100644 --- a/ports/minimal/frozentest.py +++ b/ports/minimal/frozentest.py @@ -1,7 +1,7 @@ -print('uPy') -print('a long string that is not interned') -print('a string that has unicode αβγ chars') -print(b'bytes 1234\x01') +print("uPy") +print("a long string that is not interned") +print("a string that has unicode αβγ chars") +print(b"bytes 1234\x01") print(123456789) for i in range(4): print(i) diff --git a/ports/minimal/main.c b/ports/minimal/main.c index 5e145dc829..0de4fd9bf7 100644 --- a/ports/minimal/main.c +++ b/ports/minimal/main.c @@ -33,7 +33,7 @@ static char heap[2048]; int main(int argc, char **argv) { int stack_dummy; - stack_top = (char*)&stack_dummy; + stack_top = (char *)&stack_dummy; #if MICROPY_ENABLE_GC gc_init(heap, heap + sizeof(heap)); @@ -51,8 +51,8 @@ int main(int argc, char **argv) { #else pyexec_friendly_repl(); #endif - //do_str("print('hello world!', list(x+1 for x in range(10)), end='eol\\n')", MP_PARSE_SINGLE_INPUT); - //do_str("for i in range(10):\r\n print(i)", MP_PARSE_FILE_INPUT); + // do_str("print('hello world!', list(x+1 for x in range(10)), end='eol\\n')", MP_PARSE_SINGLE_INPUT); + // do_str("for i in range(10):\r\n print(i)", MP_PARSE_FILE_INPUT); #else pyexec_frozen_module("frozentest.py"); #endif @@ -84,11 +84,15 @@ mp_obj_t mp_builtin_open(size_t n_args, const mp_obj_t *args, mp_map_t *kwargs) MP_DEFINE_CONST_FUN_OBJ_KW(mp_builtin_open_obj, 1, mp_builtin_open); void nlr_jump_fail(void *val) { - while (1); + while (1) { + ; + } } void NORETURN __fatal_error(const char *msg) { - while (1); + while (1) { + ; + } } #ifndef NDEBUG @@ -149,7 +153,7 @@ void _start(void) { // when we get here: stack is initialised, bss is clear, data is copied // SCB->CCR: enable 8-byte stack alignment for IRQ handlers, in accord with EABI - *((volatile uint32_t*)0xe000ed14) |= 1 << 9; + *((volatile uint32_t *)0xe000ed14) |= 1 << 9; // initialise the cpu and peripherals #if MICROPY_MIN_USE_STM32_MCU @@ -205,10 +209,10 @@ typedef struct { volatile uint32_t CR1; } periph_uart_t; -#define USART1 ((periph_uart_t*) 0x40011000) -#define GPIOA ((periph_gpio_t*) 0x40020000) -#define GPIOB ((periph_gpio_t*) 0x40020400) -#define RCC ((periph_rcc_t*) 0x40023800) +#define USART1 ((periph_uart_t *)0x40011000) +#define GPIOA ((periph_gpio_t *)0x40020000) +#define GPIOB ((periph_gpio_t *)0x40020400) +#define RCC ((periph_rcc_t *)0x40023800) // simple GPIO interface #define GPIO_MODE_IN (0) diff --git a/ports/minimal/mpconfigport.h b/ports/minimal/mpconfigport.h index f2a43523d5..41e22cd010 100644 --- a/ports/minimal/mpconfigport.h +++ b/ports/minimal/mpconfigport.h @@ -60,7 +60,7 @@ // type definitions for the specific machine -#define MICROPY_MAKE_POINTER_CALLABLE(p) ((void*)((mp_uint_t)(p) | 1)) +#define MICROPY_MAKE_POINTER_CALLABLE(p) ((void *)((mp_uint_t)(p) | 1)) // This port is intended to be 32-bit, but unfortunately, int32_t for // different targets may be defined in different ways - either as int diff --git a/ports/minimal/mphalport.h b/ports/minimal/mphalport.h index 60d68bd2d6..5130d19a24 100644 --- a/ports/minimal/mphalport.h +++ b/ports/minimal/mphalport.h @@ -1,2 +1,5 @@ -static inline mp_uint_t mp_hal_ticks_ms(void) { return 0; } -static inline void mp_hal_set_interrupt_char(char c) {} +static inline mp_uint_t mp_hal_ticks_ms(void) { + return 0; +} +static inline void mp_hal_set_interrupt_char(char c) { +} diff --git a/ports/minimal/uart_core.c b/ports/minimal/uart_core.c index d2d17b4d14..5b3797d2eb 100644 --- a/ports/minimal/uart_core.c +++ b/ports/minimal/uart_core.c @@ -10,35 +10,35 @@ typedef struct { volatile uint32_t SR; volatile uint32_t DR; } periph_uart_t; -#define USART1 ((periph_uart_t*)0x40011000) +#define USART1 ((periph_uart_t *)0x40011000) #endif // Receive single character int mp_hal_stdin_rx_chr(void) { unsigned char c = 0; -#if MICROPY_MIN_USE_STDOUT + #if MICROPY_MIN_USE_STDOUT int r = read(0, &c, 1); (void)r; -#elif MICROPY_MIN_USE_STM32_MCU + #elif MICROPY_MIN_USE_STM32_MCU // wait for RXNE while ((USART1->SR & (1 << 5)) == 0) { } c = USART1->DR; -#endif + #endif return c; } // Send string of given length void mp_hal_stdout_tx_strn(const char *str, mp_uint_t len) { -#if MICROPY_MIN_USE_STDOUT + #if MICROPY_MIN_USE_STDOUT int r = write(1, str, len); (void)r; -#elif MICROPY_MIN_USE_STM32_MCU + #elif MICROPY_MIN_USE_STM32_MCU while (len--) { // wait for TXE while ((USART1->SR & (1 << 7)) == 0) { } USART1->DR = *str++; } -#endif + #endif } diff --git a/ports/nrf/fatfs_port.c b/ports/nrf/fatfs_port.c index 13ac21fb1b..6a17f627bd 100644 --- a/ports/nrf/fatfs_port.c +++ b/ports/nrf/fatfs_port.c @@ -28,6 +28,6 @@ #include "lib/oofatfs/ff.h" DWORD get_fattime(void) { - // TODO: Implement this function. For now, fake it. + // TODO: Implement this function. For now, fake it. return ((2016 - 1980) << 25) | ((12) << 21) | ((4) << 16) | ((00) << 11) | ((18) << 5) | (23 / 2); } diff --git a/ports/nrf/gccollect.c b/ports/nrf/gccollect.c index 68b8188532..740561242f 100644 --- a/ports/nrf/gccollect.c +++ b/ports/nrf/gccollect.c @@ -33,7 +33,7 @@ static inline uintptr_t get_sp(void) { uintptr_t result; - __asm__ ("mov %0, sp\n" : "=r" (result) ); + __asm__ ("mov %0, sp\n" : "=r" (result)); return result; } @@ -45,7 +45,7 @@ void gc_collect(void) { uintptr_t sp = get_sp(); // trace the stack, including the registers (since they live on the stack in this function) - gc_collect_root((void**)sp, ((uint32_t)&_ram_end - sp) / sizeof(uint32_t)); + gc_collect_root((void **)sp, ((uint32_t)&_ram_end - sp) / sizeof(uint32_t)); // end the GC gc_collect_end(); diff --git a/ports/nrf/help.c b/ports/nrf/help.c index 5856ef6e37..afc979130f 100644 --- a/ports/nrf/help.c +++ b/ports/nrf/help.c @@ -32,23 +32,23 @@ #endif const char nrf5_help_text[] = -"Welcome to MicroPython!\n" -"\n" -"For online help please visit http://micropython.org/help/.\n" -"\n" -"Quick overview of commands for the board:\n" + "Welcome to MicroPython!\n" + "\n" + "For online help please visit http://micropython.org/help/.\n" + "\n" + "Quick overview of commands for the board:\n" #if MICROPY_HW_HAS_LED -" board.LED(n) -- create an LED object for LED n (n=" HELP_TEXT_BOARD_LED ")\n" -"\n" + " board.LED(n) -- create an LED object for LED n (n=" HELP_TEXT_BOARD_LED ")\n" + "\n" #endif #if BLUETOOTH_SD -HELP_TEXT_SD + HELP_TEXT_SD #endif -"Control commands:\n" -" CTRL-A -- on a blank line, enter raw REPL mode\n" -" CTRL-B -- on a blank line, enter normal REPL mode\n" -" CTRL-D -- on a blank line, do a soft reset of the board\n" -" CTRL-E -- on a blank line, enter paste mode\n" -"\n" -"For further help on a specific object, type help(obj)\n" + "Control commands:\n" + " CTRL-A -- on a blank line, enter raw REPL mode\n" + " CTRL-B -- on a blank line, enter normal REPL mode\n" + " CTRL-D -- on a blank line, do a soft reset of the board\n" + " CTRL-E -- on a blank line, enter paste mode\n" + "\n" + "For further help on a specific object, type help(obj)\n" ; diff --git a/ports/nrf/main.c b/ports/nrf/main.c index b9c29e7538..9fba04e9c5 100644 --- a/ports/nrf/main.c +++ b/ports/nrf/main.c @@ -94,13 +94,13 @@ extern uint32_t _heap_start; extern uint32_t _heap_end; int main(int argc, char **argv) { - + soft_reset: mp_stack_set_top(&_ram_end); // Stack limit should be less than real stack size, so we have a chance // to recover from limit hit. (Limit is measured in bytes.) - mp_stack_set_limit((char*)&_ram_end - (char*)&_heap_end - 400); + mp_stack_set_limit((char *)&_ram_end - (char *)&_heap_end - 400); machine_init(); @@ -115,35 +115,35 @@ soft_reset: readline_init0(); -#if MICROPY_PY_MACHINE_HW_SPI + #if MICROPY_PY_MACHINE_HW_SPI spi_init0(); -#endif + #endif -#if MICROPY_PY_MACHINE_I2C + #if MICROPY_PY_MACHINE_I2C i2c_init0(); -#endif + #endif -#if MICROPY_PY_MACHINE_ADC + #if MICROPY_PY_MACHINE_ADC adc_init0(); -#endif + #endif -#if MICROPY_PY_MACHINE_HW_PWM + #if MICROPY_PY_MACHINE_HW_PWM pwm_init0(); -#endif + #endif -#if MICROPY_PY_MACHINE_RTCOUNTER + #if MICROPY_PY_MACHINE_RTCOUNTER rtc_init0(); -#endif + #endif -#if MICROPY_PY_MACHINE_TIMER + #if MICROPY_PY_MACHINE_TIMER timer_init0(); -#endif + #endif -#if MICROPY_PY_MACHINE_UART + #if MICROPY_PY_MACHINE_UART uart_init0(); -#endif + #endif -#if (MICROPY_PY_BLE_NUS == 0) + #if (MICROPY_PY_BLE_NUS == 0) { mp_obj_t args[2] = { MP_OBJ_NEW_SMALL_INT(0), @@ -151,15 +151,15 @@ soft_reset: }; MP_STATE_PORT(board_stdio_uart) = machine_hard_uart_type.make_new((mp_obj_t)&machine_hard_uart_type, MP_ARRAY_SIZE(args), 0, args); } -#endif + #endif -pin_init0(); + pin_init0(); -#if MICROPY_MBFS + #if MICROPY_MBFS microbit_filesystem_init(); -#endif + #endif -#if MICROPY_HW_HAS_SDCARD + #if MICROPY_HW_HAS_SDCARD // if an SD card is present then mount it on /sd/ if (sdcard_is_present()) { // create vfs object @@ -185,47 +185,47 @@ pin_init0(); mp_obj_list_append(mp_sys_path, MP_OBJ_NEW_QSTR(MP_QSTR__slash_sd)); mp_obj_list_append(mp_sys_path, MP_OBJ_NEW_QSTR(MP_QSTR__slash_sd_slash_lib)); - // use SD card as current directory - f_chdrive("/sd"); + // use SD card as current directory + f_chdrive("/sd"); } - no_mem_for_sd:; + no_mem_for_sd:; } -#endif + #endif -#if (MICROPY_HW_HAS_LED) + #if (MICROPY_HW_HAS_LED) led_init(); do_str("import board\r\n" \ - "board.LED(1).on()", - MP_PARSE_FILE_INPUT); -#endif + "board.LED(1).on()", + MP_PARSE_FILE_INPUT); + #endif // Main script is finished, so now go into REPL mode. // The REPL mode can change, or it can request a soft reset. int ret_code = 0; -#if MICROPY_PY_BLE_NUS + #if MICROPY_PY_BLE_NUS ble_uart_init0(); -#endif + #endif -#if MICROPY_PY_MACHINE_SOFT_PWM + #if MICROPY_PY_MACHINE_SOFT_PWM ticker_init0(); softpwm_init0(); -#endif + #endif -#if MICROPY_PY_MUSIC + #if MICROPY_PY_MUSIC microbit_music_init0(); -#endif -#if BOARD_SPECIFIC_MODULES + #endif + #if BOARD_SPECIFIC_MODULES board_modules_init0(); -#endif + #endif -#if MICROPY_PY_MACHINE_SOFT_PWM + #if MICROPY_PY_MACHINE_SOFT_PWM ticker_start(); pwm_start(); -#endif + #endif -#if MICROPY_VFS || MICROPY_MBFS + #if MICROPY_VFS || MICROPY_MBFS // run boot.py and main.py if they exist. if (mp_import_stat("boot.py") == MP_IMPORT_STAT_FILE) { pyexec_file("boot.py"); @@ -233,7 +233,7 @@ pin_init0(); if (mp_import_stat("main.py") == MP_IMPORT_STAT_FILE) { pyexec_file("main.py"); } -#endif + #endif for (;;) { if (pyexec_mode_kind == PYEXEC_MODE_RAW_REPL) { @@ -252,9 +252,9 @@ pin_init0(); printf("MPY: soft reboot\n"); -#if BLUETOOTH_SD + #if BLUETOOTH_SD sd_softdevice_disable(); -#endif + #endif goto soft_reset; @@ -294,26 +294,27 @@ MP_DEFINE_CONST_FUN_OBJ_KW(mp_builtin_open_obj, 1, mp_builtin_open); #endif #endif -void HardFault_Handler(void) -{ -#if defined(NRF52_SERIES) - static volatile uint32_t reg; - static volatile uint32_t reg2; - static volatile uint32_t bfar; - reg = SCB->HFSR; - reg2 = SCB->CFSR; - bfar = SCB->BFAR; - for (int i = 0; i < 0; i++) - { - (void)reg; - (void)reg2; - (void)bfar; - } -#endif +void HardFault_Handler(void) { + #if defined(NRF52_SERIES) + static volatile uint32_t reg; + static volatile uint32_t reg2; + static volatile uint32_t bfar; + reg = SCB->HFSR; + reg2 = SCB->CFSR; + bfar = SCB->BFAR; + for (int i = 0; i < 0; i++) + { + (void)reg; + (void)reg2; + (void)bfar; + } + #endif } void NORETURN __fatal_error(const char *msg) { - while (1); + while (1) { + ; + } } void nlr_jump_fail(void *val) { @@ -327,4 +328,6 @@ void MP_WEAK __assert_func(const char *file, int line, const char *func, const c __fatal_error("Assertion failed"); } -void _start(void) {main(0, NULL);} +void _start(void) { + main(0, NULL); +} diff --git a/ports/nrf/mpconfigport.h b/ports/nrf/mpconfigport.h index a5e16421cc..5103de4441 100644 --- a/ports/nrf/mpconfigport.h +++ b/ports/nrf/mpconfigport.h @@ -199,7 +199,7 @@ #define BYTES_PER_WORD (4) -#define MICROPY_MAKE_POINTER_CALLABLE(p) ((void*)((mp_uint_t)(p) | 1)) +#define MICROPY_MAKE_POINTER_CALLABLE(p) ((void *)((mp_uint_t)(p) | 1)) #define MP_SSIZE_MAX (0x7fffffff) diff --git a/ports/nrf/mphalport.c b/ports/nrf/mphalport.c index 9ce904514e..5f6fc23ea5 100644 --- a/ports/nrf/mphalport.c +++ b/ports/nrf/mphalport.c @@ -80,17 +80,16 @@ void mp_hal_stdout_tx_str(const char *str) { mp_hal_stdout_tx_strn(str, strlen(str)); } -void mp_hal_delay_us(mp_uint_t us) -{ +void mp_hal_delay_us(mp_uint_t us) { if (us == 0) { return; } - register uint32_t delay __ASM ("r0") = us; + register uint32_t delay __ASM("r0") = us; __ASM volatile ( -#ifdef NRF51 - ".syntax unified\n" -#endif + #ifdef NRF51 + ".syntax unified\n" + #endif "1:\n" " SUBS %0, %0, #1\n" " NOP\n" @@ -105,7 +104,7 @@ void mp_hal_delay_us(mp_uint_t us) " NOP\n" " NOP\n" " NOP\n" -#ifdef NRF52 + #ifdef NRF52 " NOP\n" " NOP\n" " NOP\n" @@ -152,13 +151,12 @@ void mp_hal_delay_us(mp_uint_t us) " NOP\n" " NOP\n" " NOP\n" -#endif + #endif " BNE 1b\n" : "+r" (delay)); } -void mp_hal_delay_ms(mp_uint_t ms) -{ +void mp_hal_delay_ms(mp_uint_t ms) { for (mp_uint_t i = 0; i < ms; i++) { mp_hal_delay_us(999); @@ -169,21 +167,21 @@ void mp_hal_delay_ms(mp_uint_t ms) static const char nrfx_error_unknown[1] = ""; -static const char nrfx_error_success[] = "NRFX_SUCCESS"; -static const char nrfx_error_internal[] = "NRFX_ERROR_INTERNAL"; -static const char nrfx_error_no_mem[] = "NRFX_ERROR_NO_MEM"; -static const char nrfx_error_not_supported[] = "NRFX_ERROR_NOT_SUPPORTED"; -static const char nrfx_error_invalid_param[] = "NRFX_ERROR_INVALID_PARAM"; -static const char nrfx_error_invalid_state[] = "NRFX_ERROR_INVALID_STATE"; -static const char nrfx_error_invalid_length[] = "NRFX_ERROR_INVALID_LENGTH"; -static const char nrfx_error_timeout[] = "NRFX_ERROR_TIMEOUT"; -static const char nrfx_error_forbidden[] = "NRFX_ERROR_FORBIDDEN"; -static const char nrfx_error_null[] = "NRFX_ERROR_NULL"; -static const char nrfx_error_invalid_addr[] = "NRFX_ERROR_INVALID_ADDR"; -static const char nrfx_error_busy[] = "NRFX_ERROR_BUSY"; +static const char nrfx_error_success[] = "NRFX_SUCCESS"; +static const char nrfx_error_internal[] = "NRFX_ERROR_INTERNAL"; +static const char nrfx_error_no_mem[] = "NRFX_ERROR_NO_MEM"; +static const char nrfx_error_not_supported[] = "NRFX_ERROR_NOT_SUPPORTED"; +static const char nrfx_error_invalid_param[] = "NRFX_ERROR_INVALID_PARAM"; +static const char nrfx_error_invalid_state[] = "NRFX_ERROR_INVALID_STATE"; +static const char nrfx_error_invalid_length[] = "NRFX_ERROR_INVALID_LENGTH"; +static const char nrfx_error_timeout[] = "NRFX_ERROR_TIMEOUT"; +static const char nrfx_error_forbidden[] = "NRFX_ERROR_FORBIDDEN"; +static const char nrfx_error_null[] = "NRFX_ERROR_NULL"; +static const char nrfx_error_invalid_addr[] = "NRFX_ERROR_INVALID_ADDR"; +static const char nrfx_error_busy[] = "NRFX_ERROR_BUSY"; static const char nrfx_error_already_initalized[] = "NRFX_ERROR_ALREADY_INITIALIZED"; -static const char * nrfx_error_strings[13] = { +static const char *nrfx_error_strings[13] = { nrfx_error_success, nrfx_error_internal, nrfx_error_no_mem, @@ -200,16 +198,16 @@ static const char * nrfx_error_strings[13] = { }; static const char nrfx_drv_error_twi_err_overrun[] = "NRFX_ERROR_DRV_TWI_ERR_OVERRUN"; -static const char nrfx_drv_error_twi_err_anack[] = "NRFX_ERROR_DRV_TWI_ERR_ANACK"; -static const char nrfx_drv_error_twi_err_dnack[] = "NRFX_ERROR_DRV_TWI_ERR_DNACK"; +static const char nrfx_drv_error_twi_err_anack[] = "NRFX_ERROR_DRV_TWI_ERR_ANACK"; +static const char nrfx_drv_error_twi_err_dnack[] = "NRFX_ERROR_DRV_TWI_ERR_DNACK"; -static const char * nrfx_drv_error_strings[3] = { +static const char *nrfx_drv_error_strings[3] = { nrfx_drv_error_twi_err_overrun, nrfx_drv_error_twi_err_anack, nrfx_drv_error_twi_err_dnack }; -const char * nrfx_error_code_lookup(uint32_t err_code) { +const char *nrfx_error_code_lookup(uint32_t err_code) { if (err_code >= NRFX_ERROR_BASE_NUM && err_code <= NRFX_ERROR_BASE_NUM + 13) { return nrfx_error_strings[err_code - NRFX_ERROR_BASE_NUM]; } else if (err_code >= NRFX_ERROR_DRIVERS_BASE_NUM && err_code <= NRFX_ERROR_DRIVERS_BASE_NUM + 3) { diff --git a/ports/nrf/mphalport.h b/ports/nrf/mphalport.h index 18ff454fe6..ee1212b32c 100644 --- a/ports/nrf/mphalport.h +++ b/ports/nrf/mphalport.h @@ -35,14 +35,14 @@ typedef enum { - HAL_OK = 0x00, - HAL_ERROR = 0x01, - HAL_BUSY = 0x02, - HAL_TIMEOUT = 0x03 + HAL_OK = 0x00, + HAL_ERROR = 0x01, + HAL_BUSY = 0x02, + HAL_TIMEOUT = 0x03 } HAL_StatusTypeDef; static inline uint32_t hal_tick_fake(void) { - return 0; + return 0; } #define mp_hal_ticks_ms hal_tick_fake // TODO: implement. Right now, return 0 always @@ -58,9 +58,9 @@ void mp_hal_stdout_tx_str(const char *str); void mp_hal_delay_ms(mp_uint_t ms); void mp_hal_delay_us(mp_uint_t us); -const char * nrfx_error_code_lookup(uint32_t err_code); +const char *nrfx_error_code_lookup(uint32_t err_code); -#define mp_hal_pin_obj_t const pin_obj_t* +#define mp_hal_pin_obj_t const pin_obj_t * #define mp_hal_get_pin_obj(o) pin_find(o) #define mp_hal_pin_high(p) nrf_gpio_pin_set(p->pin) #define mp_hal_pin_low(p) nrf_gpio_pin_clear(p->pin) diff --git a/ports/nrf/nrfx_glue.h b/ports/nrf/nrfx_glue.h index 0108e3242f..7ded49e1e9 100644 --- a/ports/nrf/nrfx_glue.h +++ b/ports/nrf/nrfx_glue.h @@ -51,7 +51,7 @@ } else { \ NVIC_EnableIRQ(irq_number); \ } \ - } while(0) + } while (0) #else #define NRFX_IRQ_ENABLE(irq_number) sd_nvic_EnableIRQ(irq_number) #endif @@ -65,7 +65,7 @@ } else { \ NVIC_DisableIRQ(irq_number); \ } \ - } while(0) + } while (0) #else #define NRFX_IRQ_DISABLE(irq_number) sd_nvic_DisableIRQ(irq_number) #endif @@ -79,7 +79,7 @@ } else { \ NVIC_SetPriority(irq_number, priority); \ } \ - } while(0) + } while (0) #else #define NRFX_IRQ_PRIORITY_SET(irq_number, priority) sd_nvic_SetPriority(irq_number, priority) #endif @@ -93,7 +93,7 @@ } else { \ NVIC_SetPendingIRQ(irq_number); \ } \ - } while(0) + } while (0) #else #define NRFX_IRQ_PENDING_SET(irq_number) sd_nvic_SetPendingIRQ(irq_number) #endif @@ -107,7 +107,7 @@ } else { \ NVIC_ClearPendingIRQ(irq_number)(irq_number); \ } \ - } while(0) + } while (0) #else #define NRFX_IRQ_PENDING_CLEAR(irq_number) sd_nvic_ClearPendingIRQ(irq_number) #endif @@ -118,8 +118,8 @@ sd_nvic_critical_region_enter(&_is_nested_critical_region); #define NRFX_CRITICAL_SECTION_EXIT() \ - sd_nvic_critical_region_exit(_is_nested_critical_region); \ - } + sd_nvic_critical_region_exit(_is_nested_critical_region); \ +} #else // BLUETOOTH_SD diff --git a/ports/nrf/nrfx_log.h b/ports/nrf/nrfx_log.h index ca2fd588ac..8710d3fc22 100644 --- a/ports/nrf/nrfx_log.h +++ b/ports/nrf/nrfx_log.h @@ -33,7 +33,7 @@ #define LOG_TEST_UART 1 -#define TEST_MODULE_IMPL(x, y) LOG_TEST_ ## x == LOG_TEST_ ## y +#define TEST_MODULE_IMPL(x, y) LOG_TEST_##x == LOG_TEST_##y #define TEST_MODULE(x, y) TEST_MODULE_IMPL(x, y) #if (!defined(NRFX_LOG_ENABLED) || (NRFX_LOG_ENABLED == 0)) || \ @@ -56,11 +56,11 @@ #define VALUE(x) VALUE_TO_STR(x) #define LOG_PRINTF(fmt, ...) \ - do { \ - printf("%s: ", VALUE(NRFX_LOG_MODULE)); \ - printf(fmt, ##__VA_ARGS__); \ - printf("\n"); \ - } while (0) + do { \ + printf("%s: ", VALUE(NRFX_LOG_MODULE)); \ + printf(fmt,##__VA_ARGS__); \ + printf("\n"); \ + } while (0) #define NRFX_LOG_DEBUG LOG_PRINTF #define NRFX_LOG_ERROR LOG_PRINTF @@ -77,7 +77,7 @@ #define NRFX_LOG_HEXDUMP_DEBUG(p_memory, length) #define NRFX_LOG_ERROR_STRING_GET(error_code) \ - nrfx_error_code_lookup(error_code) + nrfx_error_code_lookup(error_code) #endif // NRFX_LOG_ENABLED diff --git a/ports/nrf/pin_defs_nrf5.h b/ports/nrf/pin_defs_nrf5.h index c84d048a42..95dec1eefb 100644 --- a/ports/nrf/pin_defs_nrf5.h +++ b/ports/nrf/pin_defs_nrf5.h @@ -31,29 +31,29 @@ #include "nrf_gpio.h" enum { - PORT_A, - PORT_B, + PORT_A, + PORT_B, }; enum { - AF_FN_UART, - AF_FN_SPI, + AF_FN_UART, + AF_FN_SPI, }; enum { - AF_PIN_TYPE_UART_TX = 0, - AF_PIN_TYPE_UART_RX, - AF_PIN_TYPE_UART_CTS, - AF_PIN_TYPE_UART_RTS, + AF_PIN_TYPE_UART_TX = 0, + AF_PIN_TYPE_UART_RX, + AF_PIN_TYPE_UART_CTS, + AF_PIN_TYPE_UART_RTS, - AF_PIN_TYPE_SPI_MOSI = 0, - AF_PIN_TYPE_SPI_MISO, - AF_PIN_TYPE_SPI_SCK, - AF_PIN_TYPE_SPI_NSS, + AF_PIN_TYPE_SPI_MOSI = 0, + AF_PIN_TYPE_SPI_MISO, + AF_PIN_TYPE_SPI_SCK, + AF_PIN_TYPE_SPI_NSS, }; #define PIN_DEFS_PORT_AF_UNION \ - NRF_UART_Type *UART; + NRF_UART_Type *UART; // NRF_SPI_Type *SPIM; // NRF_SPIS_Type *SPIS; diff --git a/ports/nrf/qstrdefsport.h b/ports/nrf/qstrdefsport.h index ef398a4c0a..8bf9032cbc 100644 --- a/ports/nrf/qstrdefsport.h +++ b/ports/nrf/qstrdefsport.h @@ -26,114 +26,114 @@ // qstrs specific to this port Q(a) -Q(a#) -Q(a#:1) -Q(a#:3) +Q(a #) +Q(a #: 1) +Q(a #: 3) Q(a2) Q(a4) -Q(a4:1) -Q(a4:3) -Q(a:1) -Q(a:2) -Q(a:4) -Q(a:5) +Q(a4: 1) +Q(a4: 3) +Q(a: 1) +Q(a: 2) +Q(a: 4) +Q(a: 5) Q(b) -Q(b2:1) +Q(b2: 1) Q(b3) Q(b4) -Q(b4:1) -Q(b4:2) +Q(b4: 1) +Q(b4: 2) Q(b5) -Q(b5:1) -Q(b:1) -Q(b:2) +Q(b5: 1) +Q(b: 1) +Q(b: 2) Q(c) -Q(c#) -Q(c#5) -Q(c#5:1) -Q(c#5:2) -Q(c#:1) -Q(c#:8) -Q(c2:2) +Q(c #) +Q(c #5) +Q(c #5 : 1) +Q(c #5 : 2) +Q(c #: 1) +Q(c #: 8) +Q(c2: 2) Q(c3) -Q(c3:3) -Q(c3:4) +Q(c3: 3) +Q(c3: 4) Q(c4) -Q(c4:1) -Q(c4:3) -Q(c4:4) +Q(c4: 1) +Q(c4: 3) +Q(c4: 4) Q(c5) -Q(c5:1) -Q(c5:2) -Q(c5:3) -Q(c5:4) -Q(c:1) -Q(c:2) -Q(c:3) -Q(c:4) -Q(c:8) +Q(c5: 1) +Q(c5: 2) +Q(c5: 3) +Q(c5: 4) +Q(c: 1) +Q(c: 2) +Q(c: 3) +Q(c: 4) +Q(c: 8) Q(d) -Q(d#) -Q(d#5:2) -Q(d#:2) -Q(d#:3) +Q(d #) +Q(d #5 : 2) +Q(d #: 2) +Q(d #: 3) Q(d3) Q(d4) -Q(d4:1) +Q(d4: 1) Q(d5) -Q(d5:1) -Q(d5:2) -Q(d:1) -Q(d:2) -Q(d:3) -Q(d:4) -Q(d:5) -Q(d:6) -Q(d:8) +Q(d5: 1) +Q(d5: 2) +Q(d: 1) +Q(d: 2) +Q(d: 3) +Q(d: 4) +Q(d: 5) +Q(d: 6) +Q(d: 8) Q(e) -Q(e3:3) +Q(e3: 3) Q(e4) -Q(e4:1) +Q(e4: 1) Q(e5) -Q(e6:3) -Q(e:1) -Q(e:2) -Q(e:3) -Q(e:4) -Q(e:5) -Q(e:6) -Q(e:8) -Q(eb:8) +Q(e6: 3) +Q(e: 1) +Q(e: 2) +Q(e: 3) +Q(e: 4) +Q(e: 5) +Q(e: 6) +Q(e: 8) +Q(eb: 8) Q(f) -Q(f#) -Q(f#5) -Q(f#5:2) -Q(f#:1) -Q(f#:2) -Q(f#:8) +Q(f #) +Q(f #5) +Q(f #5 : 2) +Q(f #: 1) +Q(f #: 2) +Q(f #: 8) Q(f2) -Q(f:1) -Q(f:2) -Q(f:3) -Q(f:4) -Q(f:8) +Q(f: 1) +Q(f: 2) +Q(f: 3) +Q(f: 4) +Q(f: 8) Q(g) -Q(g#) -Q(g#:1) -Q(g#:3) -Q(g3:1) +Q(g #) +Q(g #: 1) +Q(g #: 3) +Q(g3: 1) Q(g4) -Q(g4:1) -Q(g4:2) +Q(g4: 1) +Q(g4: 2) Q(g5) -Q(g5:1) -Q(g:1) -Q(g:2) -Q(g:3) -Q(g:8) +Q(g5: 1) +Q(g: 1) +Q(g: 2) +Q(g: 3) +Q(g: 8) Q(r) -Q(r4:2) -Q(r:1) -Q(r:2) -Q(r:3) +Q(r4: 2) +Q(r: 1) +Q(r: 2) +Q(r: 3) diff --git a/ports/pic16bit/board.c b/ports/pic16bit/board.c index 0321b0ee22..977dd2cfa8 100644 --- a/ports/pic16bit/board.c +++ b/ports/pic16bit/board.c @@ -79,17 +79,29 @@ void led_init(void) { void led_state(int led, int state) { int val = state ? LED_ON : LED_OFF; switch (led) { - case 1: RED_LED = val; break; - case 2: YELLOW_LED = val; break; - case 3: GREEN_LED = val; break; + case 1: + RED_LED = val; + break; + case 2: + YELLOW_LED = val; + break; + case 3: + GREEN_LED = val; + break; } } void led_toggle(int led) { switch (led) { - case 1: RED_LED ^= 1; break; - case 2: YELLOW_LED ^= 1; break; - case 3: GREEN_LED ^= 1; break; + case 1: + RED_LED ^= 1; + break; + case 2: + YELLOW_LED ^= 1; + break; + case 3: + GREEN_LED ^= 1; + break; } } @@ -111,8 +123,12 @@ void switch_init(void) { int switch_get(int sw) { int val = 1; switch (sw) { - case 1: val = SWITCH_S1; break; - case 2: val = SWITCH_S2; break; + case 1: + val = SWITCH_S1; + break; + case 2: + val = SWITCH_S2; + break; } return val == 0; } diff --git a/ports/pic16bit/main.c b/ports/pic16bit/main.c index 47ba00f48f..326a1ccb97 100644 --- a/ports/pic16bit/main.c +++ b/ports/pic16bit/main.c @@ -68,7 +68,7 @@ soft_reset: // init MicroPython runtime int stack_dummy; - MP_STATE_THREAD(stack_top) = (char*)&stack_dummy; + MP_STATE_THREAD(stack_top) = (char *)&stack_dummy; gc_init(heap, heap + sizeof(heap)); mp_init(); mp_hal_init(); @@ -115,11 +115,15 @@ mp_obj_t mp_builtin_open(size_t n_args, const mp_obj_t *args, mp_map_t *kwargs) MP_DEFINE_CONST_FUN_OBJ_KW(mp_builtin_open_obj, 1, mp_builtin_open); void nlr_jump_fail(void *val) { - while (1); + while (1) { + ; + } } void NORETURN __fatal_error(const char *msg) { - while (1); + while (1) { + ; + } } #ifndef NDEBUG diff --git a/ports/pic16bit/modpyb.c b/ports/pic16bit/modpyb.c index 6299146336..a18b37700c 100644 --- a/ports/pic16bit/modpyb.c +++ b/ports/pic16bit/modpyb.c @@ -66,5 +66,5 @@ STATIC MP_DEFINE_CONST_DICT(pyb_module_globals, pyb_module_globals_table); const mp_obj_module_t pyb_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&pyb_module_globals, + .globals = (mp_obj_dict_t *)&pyb_module_globals, }; diff --git a/ports/pic16bit/mpconfigport.h b/ports/pic16bit/mpconfigport.h index 59880dc599..f121081e6f 100644 --- a/ports/pic16bit/mpconfigport.h +++ b/ports/pic16bit/mpconfigport.h @@ -73,9 +73,9 @@ // The xc16 compiler doesn't seem to respect alignment (!!) so we // need to use instead an object representation that allows for // 2-byte aligned pointers (see config setting above). -//#define MICROPY_OBJ_BASE_ALIGNMENT __attribute__((aligned(4))) +// #define MICROPY_OBJ_BASE_ALIGNMENT __attribute__((aligned(4))) -#define MICROPY_MAKE_POINTER_CALLABLE(p) ((void*)((mp_uint_t)(p))) +#define MICROPY_MAKE_POINTER_CALLABLE(p) ((void *)((mp_uint_t)(p))) #define UINT_FMT "%u" #define INT_FMT "%d" diff --git a/ports/qemu-arm/main.c b/ports/qemu-arm/main.c index d23ef576f9..c950777458 100644 --- a/ports/qemu-arm/main.c +++ b/ports/qemu-arm/main.c @@ -31,7 +31,7 @@ int main(int argc, char **argv) { mp_stack_ctrl_init(); mp_stack_set_limit(10240); void *heap = malloc(16 * 1024); - gc_init(heap, (char*)heap + 16 * 1024); + gc_init(heap, (char *)heap + 16 * 1024); mp_init(); do_str("print('hello world!')", MP_PARSE_SINGLE_INPUT); mp_deinit(); diff --git a/ports/qemu-arm/modmachine.c b/ports/qemu-arm/modmachine.c index 0f66349a8b..728fd4fa31 100644 --- a/ports/qemu-arm/modmachine.c +++ b/ports/qemu-arm/modmachine.c @@ -43,5 +43,5 @@ STATIC MP_DEFINE_CONST_DICT(machine_module_globals, machine_module_globals_table const mp_obj_module_t mp_module_machine = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&machine_module_globals, + .globals = (mp_obj_dict_t *)&machine_module_globals, }; diff --git a/ports/qemu-arm/moduos.c b/ports/qemu-arm/moduos.c index a48b51db01..23a1241869 100644 --- a/ports/qemu-arm/moduos.c +++ b/ports/qemu-arm/moduos.c @@ -49,5 +49,5 @@ STATIC MP_DEFINE_CONST_DICT(os_module_globals, os_module_globals_table); const mp_obj_module_t mp_module_uos = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&os_module_globals, + .globals = (mp_obj_dict_t *)&os_module_globals, }; diff --git a/ports/qemu-arm/mpconfigport.h b/ports/qemu-arm/mpconfigport.h index 5d86191988..59eb86745f 100644 --- a/ports/qemu-arm/mpconfigport.h +++ b/ports/qemu-arm/mpconfigport.h @@ -43,7 +43,7 @@ // type definitions for the specific machine -#define MICROPY_MAKE_POINTER_CALLABLE(p) ((void*)((mp_uint_t)(p) | 1)) +#define MICROPY_MAKE_POINTER_CALLABLE(p) ((void *)((mp_uint_t)(p) | 1)) #define MP_SSIZE_MAX (0x7fffffff) diff --git a/ports/qemu-arm/test_main.c b/ports/qemu-arm/test_main.c index adbdf04e18..8cc83d67be 100644 --- a/ports/qemu-arm/test_main.c +++ b/ports/qemu-arm/test_main.c @@ -24,7 +24,7 @@ int main() { mp_stack_ctrl_init(); mp_stack_set_limit(10240); heap = malloc(HEAP_SIZE); - upytest_set_heap(heap, (char*)heap + HEAP_SIZE); + upytest_set_heap(heap, (char *)heap + HEAP_SIZE); int r = tinytest_main(0, NULL, groups); printf("status: %d\n", r); return r; @@ -37,10 +37,10 @@ void gc_collect(void) { jmp_buf env; setjmp(env); volatile mp_uint_t dummy; - void *sp = (void*)&dummy; + void *sp = (void *)&dummy; // 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) - (uint32_t)sp) / sizeof(uint32_t)); + gc_collect_root((void **)sp, ((uint32_t)MP_STATE_THREAD(stack_top) - (uint32_t)sp) / sizeof(uint32_t)); gc_collect_end(); } diff --git a/ports/stm32/accel.c b/ports/stm32/accel.c index 0d7708c093..de0f9d2742 100644 --- a/ports/stm32/accel.c +++ b/ports/stm32/accel.c @@ -220,7 +220,7 @@ const mp_obj_type_t pyb_accel_type = { { &mp_type_type }, .name = MP_QSTR_Accel, .make_new = pyb_accel_make_new, - .locals_dict = (mp_obj_dict_t*)&pyb_accel_locals_dict, + .locals_dict = (mp_obj_dict_t *)&pyb_accel_locals_dict, }; #endif // MICROPY_HW_HAS_MMA7660 diff --git a/ports/stm32/adc.c b/ports/stm32/adc.c index 35a8ff7883..637f12c5c5 100644 --- a/ports/stm32/adc.c +++ b/ports/stm32/adc.c @@ -65,8 +65,8 @@ #define ADC_LAST_GPIO_CHANNEL (15) #define ADC_SCALE_V (3.3f) #define ADC_CAL_ADDRESS (0x1ffff7ba) -#define ADC_CAL1 ((uint16_t*)0x1ffff7b8) -#define ADC_CAL2 ((uint16_t*)0x1ffff7c2) +#define ADC_CAL1 ((uint16_t *)0x1ffff7b8) +#define ADC_CAL2 ((uint16_t *)0x1ffff7c2) #define ADC_CAL_BITS (12) #elif defined(STM32F4) @@ -75,8 +75,8 @@ #define ADC_LAST_GPIO_CHANNEL (15) #define ADC_SCALE_V (3.3f) #define ADC_CAL_ADDRESS (0x1fff7a2a) -#define ADC_CAL1 ((uint16_t*)(ADC_CAL_ADDRESS + 2)) -#define ADC_CAL2 ((uint16_t*)(ADC_CAL_ADDRESS + 4)) +#define ADC_CAL1 ((uint16_t *)(ADC_CAL_ADDRESS + 2)) +#define ADC_CAL2 ((uint16_t *)(ADC_CAL_ADDRESS + 4)) #define ADC_CAL_BITS (12) #elif defined(STM32F7) @@ -91,8 +91,8 @@ #define ADC_CAL_ADDRESS (0x1ff0f44a) #endif -#define ADC_CAL1 ((uint16_t*)(ADC_CAL_ADDRESS + 2)) -#define ADC_CAL2 ((uint16_t*)(ADC_CAL_ADDRESS + 4)) +#define ADC_CAL1 ((uint16_t *)(ADC_CAL_ADDRESS + 2)) +#define ADC_CAL2 ((uint16_t *)(ADC_CAL_ADDRESS + 4)) #define ADC_CAL_BITS (12) #elif defined(STM32H7) @@ -101,8 +101,8 @@ #define ADC_LAST_GPIO_CHANNEL (16) #define ADC_SCALE_V (3.3f) #define ADC_CAL_ADDRESS (0x1FF1E860) -#define ADC_CAL1 ((uint16_t*)(0x1FF1E820)) -#define ADC_CAL2 ((uint16_t*)(0x1FF1E840)) +#define ADC_CAL1 ((uint16_t *)(0x1FF1E820)) +#define ADC_CAL2 ((uint16_t *)(0x1FF1E840)) #define ADC_CAL_BITS (16) #define ADC_CHANNEL_VBAT ADC_CHANNEL_VBAT_DIV4 @@ -112,8 +112,8 @@ #define ADC_LAST_GPIO_CHANNEL (16) #define ADC_SCALE_V (3.0f) #define ADC_CAL_ADDRESS (0x1fff75aa) -#define ADC_CAL1 ((uint16_t*)(ADC_CAL_ADDRESS - 2)) -#define ADC_CAL2 ((uint16_t*)(ADC_CAL_ADDRESS + 0x20)) +#define ADC_CAL1 ((uint16_t *)(ADC_CAL_ADDRESS - 2)) +#define ADC_CAL2 ((uint16_t *)(ADC_CAL_ADDRESS + 0x20)) #define ADC_CAL_BITS (12) #else @@ -130,17 +130,17 @@ defined(STM32F411xE) #define VBAT_DIV (2) #elif defined(STM32F427xx) || defined(STM32F429xx) || \ - defined(STM32F437xx) || defined(STM32F439xx) || \ - defined(STM32F446xx) || \ - defined(STM32F722xx) || defined(STM32F723xx) || \ - defined(STM32F732xx) || defined(STM32F733xx) || \ - defined(STM32F746xx) || defined(STM32F765xx) || \ - defined(STM32F767xx) || defined(STM32F769xx) + defined(STM32F437xx) || defined(STM32F439xx) || \ + defined(STM32F446xx) || \ + defined(STM32F722xx) || defined(STM32F723xx) || \ + defined(STM32F732xx) || defined(STM32F733xx) || \ + defined(STM32F746xx) || defined(STM32F765xx) || \ + defined(STM32F767xx) || defined(STM32F769xx) #define VBAT_DIV (4) #elif defined(STM32H743xx) #define VBAT_DIV (4) #elif defined(STM32L432xx) || defined(STM32L475xx) || \ - defined(STM32L476xx) || defined(STM32L496xx) + defined(STM32L476xx) || defined(STM32L496xx) #define VBAT_DIV (3) #else #error Unsupported processor @@ -177,83 +177,83 @@ static inline uint32_t adc_get_internal_channel(uint32_t channel) { } STATIC bool is_adcx_channel(int channel) { -#if defined(STM32F411xE) + #if defined(STM32F411xE) // The HAL has an incorrect IS_ADC_CHANNEL macro for the F411 so we check for temp return IS_ADC_CHANNEL(channel) || channel == ADC_CHANNEL_TEMPSENSOR; -#elif defined(STM32F0) || defined(STM32F4) || defined(STM32F7) || defined(STM32H7) + #elif defined(STM32F0) || defined(STM32F4) || defined(STM32F7) || defined(STM32H7) return IS_ADC_CHANNEL(channel); -#elif defined(STM32L4) + #elif defined(STM32L4) ADC_HandleTypeDef handle; handle.Instance = ADCx; return IS_ADC_CHANNEL(&handle, channel); -#else + #else #error Unsupported processor -#endif + #endif } STATIC void adc_wait_for_eoc_or_timeout(int32_t timeout) { uint32_t tickstart = HAL_GetTick(); -#if defined(STM32F4) || defined(STM32F7) + #if defined(STM32F4) || defined(STM32F7) while ((ADCx->SR & ADC_FLAG_EOC) != ADC_FLAG_EOC) { -#elif defined(STM32F0) || defined(STM32H7) || defined(STM32L4) + #elif defined(STM32F0) || defined(STM32H7) || defined(STM32L4) while (READ_BIT(ADCx->ISR, ADC_FLAG_EOC) != ADC_FLAG_EOC) { -#else + #else #error Unsupported processor -#endif - if (((HAL_GetTick() - tickstart ) > timeout)) { + #endif + if (((HAL_GetTick() - tickstart) > timeout)) { break; // timeout } } } STATIC void adcx_clock_enable(void) { -#if defined(STM32F0) || defined(STM32F4) || defined(STM32F7) + #if defined(STM32F0) || defined(STM32F4) || defined(STM32F7) ADCx_CLK_ENABLE(); -#elif defined(STM32H7) + #elif defined(STM32H7) __HAL_RCC_ADC3_CLK_ENABLE(); __HAL_RCC_ADC_CONFIG(RCC_ADCCLKSOURCE_CLKP); -#elif defined(STM32L4) + #elif defined(STM32L4) __HAL_RCC_ADC_CLK_ENABLE(); -#else + #else #error Unsupported processor -#endif + #endif } STATIC void adcx_init_periph(ADC_HandleTypeDef *adch, uint32_t resolution) { adcx_clock_enable(); - adch->Instance = ADCx; - adch->Init.Resolution = resolution; - adch->Init.ContinuousConvMode = DISABLE; + adch->Instance = ADCx; + adch->Init.Resolution = resolution; + adch->Init.ContinuousConvMode = DISABLE; adch->Init.DiscontinuousConvMode = DISABLE; #if !defined(STM32F0) - adch->Init.NbrOfDiscConversion = 0; - adch->Init.NbrOfConversion = 1; + adch->Init.NbrOfDiscConversion = 0; + adch->Init.NbrOfConversion = 1; #endif - adch->Init.EOCSelection = ADC_EOC_SINGLE_CONV; - adch->Init.ExternalTrigConv = ADC_SOFTWARE_START; - adch->Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE; + adch->Init.EOCSelection = ADC_EOC_SINGLE_CONV; + adch->Init.ExternalTrigConv = ADC_SOFTWARE_START; + adch->Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE; #if defined(STM32F0) || defined(STM32F4) || defined(STM32F7) - adch->Init.ClockPrescaler = ADC_CLOCK_SYNC_PCLK_DIV2; - adch->Init.ScanConvMode = DISABLE; - adch->Init.DataAlign = ADC_DATAALIGN_RIGHT; + adch->Init.ClockPrescaler = ADC_CLOCK_SYNC_PCLK_DIV2; + adch->Init.ScanConvMode = DISABLE; + adch->Init.DataAlign = ADC_DATAALIGN_RIGHT; adch->Init.DMAContinuousRequests = DISABLE; #elif defined(STM32H7) - adch->Init.ClockPrescaler = ADC_CLOCK_SYNC_PCLK_DIV4; - adch->Init.BoostMode = ENABLE; - adch->Init.ScanConvMode = DISABLE; - adch->Init.LowPowerAutoWait = DISABLE; - adch->Init.Overrun = ADC_OVR_DATA_OVERWRITTEN; - adch->Init.OversamplingMode = DISABLE; - adch->Init.LeftBitShift = ADC_LEFTBITSHIFT_NONE; + adch->Init.ClockPrescaler = ADC_CLOCK_SYNC_PCLK_DIV4; + adch->Init.BoostMode = ENABLE; + adch->Init.ScanConvMode = DISABLE; + adch->Init.LowPowerAutoWait = DISABLE; + adch->Init.Overrun = ADC_OVR_DATA_OVERWRITTEN; + adch->Init.OversamplingMode = DISABLE; + adch->Init.LeftBitShift = ADC_LEFTBITSHIFT_NONE; adch->Init.ConversionDataManagement = ADC_CONVERSIONDATA_DR; #elif defined(STM32L4) - adch->Init.ClockPrescaler = ADC_CLOCK_ASYNC_DIV1; - adch->Init.ScanConvMode = ADC_SCAN_DISABLE; - adch->Init.LowPowerAutoWait = DISABLE; - adch->Init.Overrun = ADC_OVR_DATA_PRESERVED; - adch->Init.OversamplingMode = DISABLE; - adch->Init.DataAlign = ADC_DATAALIGN_RIGHT; + adch->Init.ClockPrescaler = ADC_CLOCK_ASYNC_DIV1; + adch->Init.ScanConvMode = ADC_SCAN_DISABLE; + adch->Init.LowPowerAutoWait = DISABLE; + adch->Init.Overrun = ADC_OVR_DATA_PRESERVED; + adch->Init.OversamplingMode = DISABLE; + adch->Init.DataAlign = ADC_DATAALIGN_RIGHT; adch->Init.DMAContinuousRequests = DISABLE; #else #error Unsupported processor @@ -286,14 +286,13 @@ STATIC void adc_init_single(pyb_obj_adc_t *adc_obj) { adcx_init_periph(&adc_obj->handle, ADC_RESOLUTION_12B); -#if defined(STM32L4) && defined(ADC_DUALMODE_REGSIMULT_INJECSIMULT) + #if defined(STM32L4) && defined(ADC_DUALMODE_REGSIMULT_INJECSIMULT) ADC_MultiModeTypeDef multimode; multimode.Mode = ADC_MODE_INDEPENDENT; - if (HAL_ADCEx_MultiModeConfigChannel(&adc_obj->handle, &multimode) != HAL_OK) - { + if (HAL_ADCEx_MultiModeConfigChannel(&adc_obj->handle, &multimode) != HAL_OK) { nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Can not set multimode on ADC1 channel: %d", adc_obj->channel)); } -#endif + #endif } STATIC void adc_config_channel(ADC_HandleTypeDef *adc_handle, uint32_t channel) { @@ -301,11 +300,11 @@ STATIC void adc_config_channel(ADC_HandleTypeDef *adc_handle, uint32_t channel) sConfig.Channel = channel; sConfig.Rank = 1; -#if defined(STM32F0) + #if defined(STM32F0) sConfig.SamplingTime = ADC_SAMPLETIME_71CYCLES_5; -#elif defined(STM32F4) || defined(STM32F7) + #elif defined(STM32F4) || defined(STM32F7) sConfig.SamplingTime = ADC_SAMPLETIME_15CYCLES; -#elif defined(STM32H7) + #elif defined(STM32H7) if (channel == ADC_CHANNEL_VREFINT || channel == ADC_CHANNEL_TEMPSENSOR || channel == ADC_CHANNEL_VBAT) { @@ -317,7 +316,7 @@ STATIC void adc_config_channel(ADC_HandleTypeDef *adc_handle, uint32_t channel) sConfig.OffsetNumber = ADC_OFFSET_NONE; sConfig.OffsetRightShift = DISABLE; sConfig.OffsetSignedSaturation = DISABLE; -#elif defined(STM32L4) + #elif defined(STM32L4) if (channel == ADC_CHANNEL_VREFINT || channel == ADC_CHANNEL_TEMPSENSOR || channel == ADC_CHANNEL_VBAT) { @@ -328,9 +327,9 @@ STATIC void adc_config_channel(ADC_HandleTypeDef *adc_handle, uint32_t channel) sConfig.SingleDiff = ADC_SINGLE_ENDED; sConfig.OffsetNumber = ADC_OFFSET_NONE; sConfig.Offset = 0; -#else + #else #error Unsupported processor -#endif + #endif #if defined(STM32F0) // On the STM32F0 we must select only one channel at a time to sample, so clear all @@ -504,13 +503,13 @@ STATIC mp_obj_t adc_read_timed(mp_obj_t self_in, mp_obj_t buf_in, mp_obj_t freq_ HAL_ADC_Start(&self->handle); } else { // for subsequent samples we can just set the "start sample" bit -#if defined(STM32F4) || defined(STM32F7) + #if defined(STM32F4) || defined(STM32F7) ADCx->CR2 |= (uint32_t)ADC_CR2_SWSTART; -#elif defined(STM32F0) || defined(STM32H7) || defined(STM32L4) + #elif defined(STM32F0) || defined(STM32H7) || defined(STM32L4) SET_BIT(ADCx->CR, ADC_CR_ADSTART); -#else + #else #error Unsupported processor -#endif + #endif } // wait for sample to complete @@ -657,7 +656,7 @@ const mp_obj_type_t pyb_adc_type = { .name = MP_QSTR_ADC, .print = adc_print, .make_new = adc_make_new, - .locals_dict = (mp_obj_dict_t*)&adc_locals_dict, + .locals_dict = (mp_obj_dict_t *)&adc_locals_dict, }; /******************************************************************************/ @@ -672,13 +671,23 @@ void adc_init_all(pyb_adc_all_obj_t *adc_all, uint32_t resolution, uint32_t en_m switch (resolution) { #if !defined(STM32H7) - case 6: resolution = ADC_RESOLUTION_6B; break; + case 6: + resolution = ADC_RESOLUTION_6B; + break; #endif - case 8: resolution = ADC_RESOLUTION_8B; break; - case 10: resolution = ADC_RESOLUTION_10B; break; - case 12: resolution = ADC_RESOLUTION_12B; break; + case 8: + resolution = ADC_RESOLUTION_8B; + break; + case 10: + resolution = ADC_RESOLUTION_10B; + break; + case 12: + resolution = ADC_RESOLUTION_12B; + break; #if defined(STM32H7) - case 16: resolution = ADC_RESOLUTION_16B; break; + case 16: + resolution = ADC_RESOLUTION_16B; + break; #endif default: nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, @@ -704,13 +713,17 @@ int adc_get_resolution(ADC_HandleTypeDef *adcHandle) { uint32_t res_reg = ADC_GET_RESOLUTION(adcHandle); switch (res_reg) { - #if !defined(STM32H7) - case ADC_RESOLUTION_6B: return 6; + #if !defined(STM32H7) + case ADC_RESOLUTION_6B: + return 6; #endif - case ADC_RESOLUTION_8B: return 8; - case ADC_RESOLUTION_10B: return 10; + case ADC_RESOLUTION_8B: + return 8; + case ADC_RESOLUTION_10B: + return 10; #if defined(STM32H7) - case ADC_RESOLUTION_16B: return 16; + case ADC_RESOLUTION_16B: + return 16; #endif } return 12; @@ -765,7 +778,7 @@ STATIC mp_obj_t adc_all_make_new(const mp_obj_type_t *type, size_t n_args, size_ mp_int_t res = mp_obj_get_int(args[0]); uint32_t en_mask = 0xffffffff; if (n_args > 1) { - en_mask = mp_obj_get_int(args[1]); + en_mask = mp_obj_get_int(args[1]); } adc_init_all(o, res, en_mask); @@ -786,7 +799,7 @@ STATIC mp_obj_t adc_all_read_core_temp(mp_obj_t self_in) { float data = adc_read_core_temp_float(&self->handle); return mp_obj_new_float(data); #else - int data = adc_read_core_temp(&self->handle); + int data = adc_read_core_temp(&self->handle); return mp_obj_new_int(data); #endif } @@ -802,7 +815,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_1(adc_all_read_core_vbat_obj, adc_all_read_core_v STATIC mp_obj_t adc_all_read_core_vref(mp_obj_t self_in) { pyb_adc_all_obj_t *self = MP_OBJ_TO_PTR(self_in); - float data = adc_read_core_vref(&self->handle); + float data = adc_read_core_vref(&self->handle); return mp_obj_new_float(data); } STATIC MP_DEFINE_CONST_FUN_OBJ_1(adc_all_read_core_vref_obj, adc_all_read_core_vref); @@ -818,11 +831,11 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_1(adc_all_read_vref_obj, adc_all_read_vref); STATIC const mp_rom_map_elem_t adc_all_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_read_channel), MP_ROM_PTR(&adc_all_read_channel_obj) }, { MP_ROM_QSTR(MP_QSTR_read_core_temp), MP_ROM_PTR(&adc_all_read_core_temp_obj) }, -#if MICROPY_PY_BUILTINS_FLOAT + #if MICROPY_PY_BUILTINS_FLOAT { MP_ROM_QSTR(MP_QSTR_read_core_vbat), MP_ROM_PTR(&adc_all_read_core_vbat_obj) }, { MP_ROM_QSTR(MP_QSTR_read_core_vref), MP_ROM_PTR(&adc_all_read_core_vref_obj) }, { MP_ROM_QSTR(MP_QSTR_read_vref), MP_ROM_PTR(&adc_all_read_vref_obj) }, -#endif + #endif }; STATIC MP_DEFINE_CONST_DICT(adc_all_locals_dict, adc_all_locals_dict_table); @@ -831,7 +844,7 @@ const mp_obj_type_t pyb_adc_all_type = { { &mp_type_type }, .name = MP_QSTR_ADCAll, .make_new = adc_all_make_new, - .locals_dict = (mp_obj_dict_t*)&adc_all_locals_dict, + .locals_dict = (mp_obj_dict_t *)&adc_all_locals_dict, }; #endif // MICROPY_HW_ENABLE_ADC diff --git a/ports/stm32/can.c b/ports/stm32/can.c index b92389aaf0..5d1f0e0989 100644 --- a/ports/stm32/can.c +++ b/ports/stm32/can.c @@ -177,16 +177,16 @@ void can_deinit(void) { STATIC void can_clearfilter(uint32_t f) { CAN_FilterConfTypeDef filter; - filter.FilterIdHigh = 0; - filter.FilterIdLow = 0; - filter.FilterMaskIdHigh = 0; - filter.FilterMaskIdLow = 0; + filter.FilterIdHigh = 0; + filter.FilterIdLow = 0; + filter.FilterMaskIdHigh = 0; + filter.FilterMaskIdLow = 0; filter.FilterFIFOAssignment = CAN_FILTER_FIFO0; - filter.FilterNumber = f; - filter.FilterMode = CAN_FILTERMODE_IDMASK; - filter.FilterScale = CAN_FILTERSCALE_16BIT; - filter.FilterActivation = DISABLE; - filter.BankNumber = can2_start_bank; + filter.FilterNumber = f; + filter.FilterMode = CAN_FILTERMODE_IDMASK; + filter.FilterScale = CAN_FILTERSCALE_16BIT; + filter.FilterActivation = DISABLE; + filter.BankNumber = can2_start_bank; HAL_CAN_ConfigFilter(NULL, &filter); } @@ -249,15 +249,15 @@ STATIC HAL_StatusTypeDef CAN_Transmit(CAN_HandleTypeDef *hcan, uint32_t Timeout) assert_param(IS_CAN_DLC(hcan->pTxMsg->DLC)); // Select one empty transmit mailbox - if ((hcan->Instance->TSR&CAN_TSR_TME0) == CAN_TSR_TME0) { + if ((hcan->Instance->TSR & CAN_TSR_TME0) == CAN_TSR_TME0) { transmitmailbox = CAN_TXMAILBOX_0; rqcpflag = CAN_FLAG_RQCP0; txokflag = CAN_FLAG_TXOK0; - } else if ((hcan->Instance->TSR&CAN_TSR_TME1) == CAN_TSR_TME1) { + } else if ((hcan->Instance->TSR & CAN_TSR_TME1) == CAN_TSR_TME1) { transmitmailbox = CAN_TXMAILBOX_1; rqcpflag = CAN_FLAG_RQCP1; txokflag = CAN_FLAG_TXOK1; - } else if ((hcan->Instance->TSR&CAN_TSR_TME2) == CAN_TSR_TME2) { + } else if ((hcan->Instance->TSR & CAN_TSR_TME2) == CAN_TSR_TME2) { transmitmailbox = CAN_TXMAILBOX_2; rqcpflag = CAN_FLAG_RQCP2; txokflag = CAN_FLAG_TXOK2; @@ -271,12 +271,12 @@ STATIC HAL_StatusTypeDef CAN_Transmit(CAN_HandleTypeDef *hcan, uint32_t Timeout) if (hcan->pTxMsg->IDE == CAN_ID_STD) { assert_param(IS_CAN_STDID(hcan->pTxMsg->StdId)); hcan->Instance->sTxMailBox[transmitmailbox].TIR |= ((hcan->pTxMsg->StdId << 21) | \ - hcan->pTxMsg->RTR); + hcan->pTxMsg->RTR); } else { assert_param(IS_CAN_EXTID(hcan->pTxMsg->ExtId)); hcan->Instance->sTxMailBox[transmitmailbox].TIR |= ((hcan->pTxMsg->ExtId << 3) | \ - hcan->pTxMsg->IDE | \ - hcan->pTxMsg->RTR); + hcan->pTxMsg->IDE | \ + hcan->pTxMsg->RTR); } // Set up the DLC @@ -286,13 +286,13 @@ STATIC HAL_StatusTypeDef CAN_Transmit(CAN_HandleTypeDef *hcan, uint32_t Timeout) // Set up the data field hcan->Instance->sTxMailBox[transmitmailbox].TDLR = (((uint32_t)hcan->pTxMsg->Data[3] << 24) | - ((uint32_t)hcan->pTxMsg->Data[2] << 16) | - ((uint32_t)hcan->pTxMsg->Data[1] << 8) | - ((uint32_t)hcan->pTxMsg->Data[0])); + ((uint32_t)hcan->pTxMsg->Data[2] << 16) | + ((uint32_t)hcan->pTxMsg->Data[1] << 8) | + ((uint32_t)hcan->pTxMsg->Data[0])); hcan->Instance->sTxMailBox[transmitmailbox].TDHR = (((uint32_t)hcan->pTxMsg->Data[7] << 24) | - ((uint32_t)hcan->pTxMsg->Data[6] << 16) | - ((uint32_t)hcan->pTxMsg->Data[5] << 8) | - ((uint32_t)hcan->pTxMsg->Data[4])); + ((uint32_t)hcan->pTxMsg->Data[6] << 16) | + ((uint32_t)hcan->pTxMsg->Data[5] << 8) | + ((uint32_t)hcan->pTxMsg->Data[4])); // Request transmission hcan->Instance->sTxMailBox[transmitmailbox].TIR |= CAN_TI0R_TXRQ; @@ -336,10 +336,19 @@ STATIC void pyb_can_print(const mp_print_t *print, mp_obj_t self_in, mp_print_ki } else { qstr mode; switch (self->can.Init.Mode) { - case CAN_MODE_NORMAL: mode = MP_QSTR_NORMAL; break; - case CAN_MODE_LOOPBACK: mode = MP_QSTR_LOOPBACK; break; - case CAN_MODE_SILENT: mode = MP_QSTR_SILENT; break; - case CAN_MODE_SILENT_LOOPBACK: default: mode = MP_QSTR_SILENT_LOOPBACK; break; + case CAN_MODE_NORMAL: + mode = MP_QSTR_NORMAL; + break; + case CAN_MODE_LOOPBACK: + mode = MP_QSTR_LOOPBACK; + break; + case CAN_MODE_SILENT: + mode = MP_QSTR_SILENT; + break; + case CAN_MODE_SILENT_LOOPBACK: + default: + mode = MP_QSTR_SILENT_LOOPBACK; + break; } mp_printf(print, "CAN(%u, CAN.%q, extframe=%q, auto_restart=%q)", self->can_id, @@ -353,9 +362,9 @@ STATIC void pyb_can_print(const mp_print_t *print, mp_obj_t self_in, mp_print_ki STATIC mp_obj_t pyb_can_init_helper(pyb_can_obj_t *self, size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { enum { ARG_mode, ARG_extframe, ARG_prescaler, ARG_sjw, ARG_bs1, ARG_bs2, ARG_auto_restart }; static const mp_arg_t allowed_args[] = { - { MP_QSTR_mode, MP_ARG_REQUIRED | MP_ARG_INT, {.u_int = CAN_MODE_NORMAL} }, + { MP_QSTR_mode, MP_ARG_REQUIRED | MP_ARG_INT, {.u_int = CAN_MODE_NORMAL} }, { MP_QSTR_extframe, MP_ARG_BOOL, {.u_bool = false} }, - { MP_QSTR_prescaler, MP_ARG_INT, {.u_int = 100} }, + { MP_QSTR_prescaler, MP_ARG_INT, {.u_int = 100} }, { MP_QSTR_sjw, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 1} }, { MP_QSTR_bs1, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 6} }, { MP_QSTR_bs2, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 8} }, @@ -623,12 +632,12 @@ STATIC mp_obj_t pyb_can_send(size_t n_args, const mp_obj_t *pos_args, mp_map_t * } if (args[ARG_rtr].u_bool == false) { tx_msg.RTR = CAN_RTR_DATA; - } else { + } else { tx_msg.RTR = CAN_RTR_REMOTE; } tx_msg.DLC = bufinfo.len; for (mp_uint_t i = 0; i < bufinfo.len; i++) { - tx_msg.Data[i] = ((byte*)bufinfo.buf)[i]; // Data is uint32_t but holds only 1 byte + tx_msg.Data[i] = ((byte *)bufinfo.buf)[i]; // Data is uint32_t but holds only 1 byte } self->can.pTxMsg = &tx_msg; @@ -678,24 +687,24 @@ STATIC mp_obj_t pyb_can_recv(size_t n_args, const mp_obj_t *pos_args, mp_map_t * byte *state = (fifo == CAN_FIFO0) ? &self->rx_state0 : &self->rx_state1; switch (*state) { - case RX_STATE_FIFO_EMPTY: - break; - case RX_STATE_MESSAGE_PENDING: - if (__HAL_CAN_MSG_PENDING(&self->can, fifo) == 0) { - // Fifo is empty - __HAL_CAN_ENABLE_IT(&self->can, (fifo == CAN_FIFO0) ? CAN_IT_FMP0 : CAN_IT_FMP1); - *state = RX_STATE_FIFO_EMPTY; - } - break; - case RX_STATE_FIFO_FULL: - __HAL_CAN_ENABLE_IT(&self->can, (fifo == CAN_FIFO0) ? CAN_IT_FF0 : CAN_IT_FF1); - *state = RX_STATE_MESSAGE_PENDING; - break; - case RX_STATE_FIFO_OVERFLOW: - __HAL_CAN_ENABLE_IT(&self->can, (fifo == CAN_FIFO0) ? CAN_IT_FOV0 : CAN_IT_FOV1); - __HAL_CAN_ENABLE_IT(&self->can, (fifo == CAN_FIFO0) ? CAN_IT_FF0 : CAN_IT_FF1); - *state = RX_STATE_MESSAGE_PENDING; - break; + case RX_STATE_FIFO_EMPTY: + break; + case RX_STATE_MESSAGE_PENDING: + if (__HAL_CAN_MSG_PENDING(&self->can, fifo) == 0) { + // Fifo is empty + __HAL_CAN_ENABLE_IT(&self->can, (fifo == CAN_FIFO0) ? CAN_IT_FMP0 : CAN_IT_FMP1); + *state = RX_STATE_FIFO_EMPTY; + } + break; + case RX_STATE_FIFO_FULL: + __HAL_CAN_ENABLE_IT(&self->can, (fifo == CAN_FIFO0) ? CAN_IT_FF0 : CAN_IT_FF1); + *state = RX_STATE_MESSAGE_PENDING; + break; + case RX_STATE_FIFO_OVERFLOW: + __HAL_CAN_ENABLE_IT(&self->can, (fifo == CAN_FIFO0) ? CAN_IT_FOV0 : CAN_IT_FOV1); + __HAL_CAN_ENABLE_IT(&self->can, (fifo == CAN_FIFO0) ? CAN_IT_FF0 : CAN_IT_FF1); + *state = RX_STATE_MESSAGE_PENDING; + break; } } @@ -705,7 +714,7 @@ STATIC mp_obj_t pyb_can_recv(size_t n_args, const mp_obj_t *pos_args, mp_map_t * mp_obj_t *items; if (ret_obj == mp_const_none) { ret_obj = mp_obj_new_tuple(4, NULL); - items = ((mp_obj_tuple_t*)MP_OBJ_TO_PTR(ret_obj))->items; + items = ((mp_obj_tuple_t *)MP_OBJ_TO_PTR(ret_obj))->items; items[3] = mp_obj_new_bytes(&rx_msg.Data[0], rx_msg.DLC); } else { // User should provide a list of length at least 4 to hold the values @@ -724,7 +733,7 @@ STATIC mp_obj_t pyb_can_recv(size_t n_args, const mp_obj_t *pos_args, mp_map_t * } mp_obj_array_t *mv = MP_OBJ_TO_PTR(items[3]); if (!(mv->typecode == (MP_OBJ_ARRAY_TYPECODE_FLAG_RW | BYTEARRAY_TYPECODE) - || (mv->typecode | 0x20) == (MP_OBJ_ARRAY_TYPECODE_FLAG_RW | 'b'))) { + || (mv->typecode | 0x20) == (MP_OBJ_ARRAY_TYPECODE_FLAG_RW | 'b'))) { mp_raise_ValueError(NULL); } mv->len = rx_msg.DLC; @@ -788,7 +797,7 @@ STATIC mp_obj_t pyb_can_setfilter(size_t n_args, const mp_obj_t *pos_args, mp_ma { MP_QSTR_mode, MP_ARG_REQUIRED | MP_ARG_INT, {.u_int = 0} }, { MP_QSTR_fifo, MP_ARG_REQUIRED | MP_ARG_INT, {.u_int = CAN_FILTER_FIFO0} }, { MP_QSTR_params, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, - { MP_QSTR_rtr, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, + { MP_QSTR_rtr, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, }; // parse args @@ -802,7 +811,7 @@ STATIC mp_obj_t pyb_can_setfilter(size_t n_args, const mp_obj_t *pos_args, mp_ma mp_obj_t *rtr_flags; mp_obj_t *params; mp_obj_get_array(args[ARG_params].u_obj, &len, ¶ms); - if (args[ARG_rtr].u_obj != MP_OBJ_NULL){ + if (args[ARG_rtr].u_obj != MP_OBJ_NULL) { mp_obj_get_array(args[ARG_rtr].u_obj, &rtr_len, &rtr_flags); } @@ -826,9 +835,9 @@ STATIC mp_obj_t pyb_can_setfilter(size_t n_args, const mp_obj_t *pos_args, mp_ma rtr_masks[3] = mp_obj_get_int(rtr_flags[3]) ? 0x02 : 0; } } - filter.FilterIdLow = EXTENDED_ID_TO_16BIT_FILTER(mp_obj_get_int(params[0])) | rtr_masks[0]; // id1 - filter.FilterMaskIdLow = EXTENDED_ID_TO_16BIT_FILTER(mp_obj_get_int(params[1])) | rtr_masks[1]; // mask1 - filter.FilterIdHigh = EXTENDED_ID_TO_16BIT_FILTER(mp_obj_get_int(params[2])) | rtr_masks[2]; // id2 + filter.FilterIdLow = EXTENDED_ID_TO_16BIT_FILTER(mp_obj_get_int(params[0])) | rtr_masks[0]; // id1 + filter.FilterMaskIdLow = EXTENDED_ID_TO_16BIT_FILTER(mp_obj_get_int(params[1])) | rtr_masks[1]; // mask1 + filter.FilterIdHigh = EXTENDED_ID_TO_16BIT_FILTER(mp_obj_get_int(params[2])) | rtr_masks[2]; // id2 filter.FilterMaskIdHigh = EXTENDED_ID_TO_16BIT_FILTER(mp_obj_get_int(params[3])) | rtr_masks[3]; // mask2 } else { // Basic frames if (args[ARG_rtr].u_obj != MP_OBJ_NULL) { @@ -844,19 +853,18 @@ STATIC mp_obj_t pyb_can_setfilter(size_t n_args, const mp_obj_t *pos_args, mp_ma rtr_masks[3] = mp_obj_get_int(rtr_flags[3]) ? 0x10 : 0; } } - filter.FilterIdLow = (mp_obj_get_int(params[0]) << 5) | rtr_masks[0]; // id1 - filter.FilterMaskIdLow = (mp_obj_get_int(params[1]) << 5) | rtr_masks[1]; // mask1 - filter.FilterIdHigh = (mp_obj_get_int(params[2]) << 5) | rtr_masks[2]; // id2 + filter.FilterIdLow = (mp_obj_get_int(params[0]) << 5) | rtr_masks[0]; // id1 + filter.FilterMaskIdLow = (mp_obj_get_int(params[1]) << 5) | rtr_masks[1]; // mask1 + filter.FilterIdHigh = (mp_obj_get_int(params[2]) << 5) | rtr_masks[2]; // id2 filter.FilterMaskIdHigh = (mp_obj_get_int(params[3]) << 5) | rtr_masks[3]; // mask2 } if (args[ARG_mode].u_int == MASK16) { - filter.FilterMode = CAN_FILTERMODE_IDMASK; + filter.FilterMode = CAN_FILTERMODE_IDMASK; } if (args[ARG_mode].u_int == LIST16) { - filter.FilterMode = CAN_FILTERMODE_IDLIST; + filter.FilterMode = CAN_FILTERMODE_IDLIST; } - } - else if (args[ARG_mode].u_int == MASK32 || args[ARG_mode].u_int == LIST32) { + } else if (args[ARG_mode].u_int == MASK32 || args[ARG_mode].u_int == LIST32) { if (len != 2) { goto error; } @@ -870,15 +878,15 @@ STATIC mp_obj_t pyb_can_setfilter(size_t n_args, const mp_obj_t *pos_args, mp_ma rtr_masks[1] = mp_obj_get_int(rtr_flags[1]) ? 0x02 : 0; } } - filter.FilterIdHigh = (mp_obj_get_int(params[0]) & 0x1FFFE000) >> 13; - filter.FilterIdLow = (((mp_obj_get_int(params[0]) & 0x00001FFF) << 3) | 4) | rtr_masks[0]; - filter.FilterMaskIdHigh = (mp_obj_get_int(params[1]) & 0x1FFFE000 ) >> 13; - filter.FilterMaskIdLow = (((mp_obj_get_int(params[1]) & 0x00001FFF) << 3) | 4) | rtr_masks[1]; + filter.FilterIdHigh = (mp_obj_get_int(params[0]) & 0x1FFFE000) >> 13; + filter.FilterIdLow = (((mp_obj_get_int(params[0]) & 0x00001FFF) << 3) | 4) | rtr_masks[0]; + filter.FilterMaskIdHigh = (mp_obj_get_int(params[1]) & 0x1FFFE000) >> 13; + filter.FilterMaskIdLow = (((mp_obj_get_int(params[1]) & 0x00001FFF) << 3) | 4) | rtr_masks[1]; if (args[ARG_mode].u_int == MASK32) { - filter.FilterMode = CAN_FILTERMODE_IDMASK; + filter.FilterMode = CAN_FILTERMODE_IDMASK; } if (args[ARG_mode].u_int == LIST32) { - filter.FilterMode = CAN_FILTERMODE_IDLIST; + filter.FilterMode = CAN_FILTERMODE_IDLIST; } } else { goto error; @@ -1075,8 +1083,8 @@ void can_sce_irq_handler(uint can_id) { } STATIC const mp_stream_p_t can_stream_p = { - //.read = can_read, // is read sensible for CAN? - //.write = can_write, // is write sensible for CAN? + // .read = can_read, // is read sensible for CAN? + // .write = can_write, // is write sensible for CAN? .ioctl = can_ioctl, .is_text = false, }; @@ -1087,7 +1095,7 @@ const mp_obj_type_t pyb_can_type = { .print = pyb_can_print, .make_new = pyb_can_make_new, .protocol = &can_stream_p, - .locals_dict = (mp_obj_dict_t*)&pyb_can_locals_dict, + .locals_dict = (mp_obj_dict_t *)&pyb_can_locals_dict, }; #endif // MICROPY_HW_ENABLE_CAN diff --git a/ports/stm32/dac.c b/ports/stm32/dac.c index 808e4d1bd1..242e8d0915 100644 --- a/ports/stm32/dac.c +++ b/ports/stm32/dac.c @@ -187,14 +187,14 @@ STATIC mp_obj_t pyb_dac_init_helper(pyb_dac_obj_t *self, size_t n_args, const mp __HAL_RCC_DMA1_CLK_ENABLE(); DMA_HandleTypeDef DMA_Handle; /* Get currently configured dma */ - dma_init_handle(&DMA_Handle, self->tx_dma_descr, DMA_MEMORY_TO_PERIPH, (void*)NULL); + dma_init_handle(&DMA_Handle, self->tx_dma_descr, DMA_MEMORY_TO_PERIPH, (void *)NULL); // Need to deinit DMA first DMA_Handle.State = HAL_DMA_STATE_READY; HAL_DMA_DeInit(&DMA_Handle); HAL_DAC_Stop(&DAC_Handle, self->dac_channel); if ((self->dac_channel == DAC_CHANNEL_1 && DAC_Handle.DMA_Handle1 != NULL) - || (self->dac_channel == DAC_CHANNEL_2 && DAC_Handle.DMA_Handle2 != NULL)) { + || (self->dac_channel == DAC_CHANNEL_2 && DAC_Handle.DMA_Handle2 != NULL)) { HAL_DAC_Stop_DMA(&DAC_Handle, self->dac_channel); } @@ -436,7 +436,7 @@ mp_obj_t pyb_dac_write_timed(size_t n_args, const mp_obj_t *pos_args, mp_map_t * DMA_HandleTypeDef DMA_Handle; /* Get currently configured dma */ - dma_init_handle(&DMA_Handle, self->tx_dma_descr, DMA_MEMORY_TO_PERIPH, (void*)NULL); + dma_init_handle(&DMA_Handle, self->tx_dma_descr, DMA_MEMORY_TO_PERIPH, (void *)NULL); /* DMA_Cmd(DMA_Handle->Instance, DISABLE); while (DMA_GetCmdStatus(DMA_Handle->Instance) != DISABLE) { @@ -489,10 +489,10 @@ mp_obj_t pyb_dac_write_timed(size_t n_args, const mp_obj_t *pos_args, mp_map_t * if (self->bits == 8) { HAL_DAC_Start_DMA(&DAC_Handle, self->dac_channel, - (uint32_t*)bufinfo.buf, bufinfo.len, DAC_ALIGN_8B_R); + (uint32_t *)bufinfo.buf, bufinfo.len, DAC_ALIGN_8B_R); } else { HAL_DAC_Start_DMA(&DAC_Handle, self->dac_channel, - (uint32_t*)bufinfo.buf, bufinfo.len / 2, DAC_ALIGN_12B_R); + (uint32_t *)bufinfo.buf, bufinfo.len / 2, DAC_ALIGN_12B_R); } /* @@ -508,7 +508,7 @@ mp_obj_t pyb_dac_write_timed(size_t n_args, const mp_obj_t *pos_args, mp_map_t * DAC_DMACmd(self->dac_channel, ENABLE); */ - //printf("DMA: %p %lu\n", bufinfo.buf, bufinfo.len); + // printf("DMA: %p %lu\n", bufinfo.buf, bufinfo.len); return mp_const_none; } @@ -538,7 +538,7 @@ const mp_obj_type_t pyb_dac_type = { .name = MP_QSTR_DAC, .print = pyb_dac_print, .make_new = pyb_dac_make_new, - .locals_dict = (mp_obj_dict_t*)&pyb_dac_locals_dict, + .locals_dict = (mp_obj_dict_t *)&pyb_dac_locals_dict, }; #endif // MICROPY_HW_ENABLE_DAC diff --git a/ports/stm32/dma.c b/ports/stm32/dma.c index 9817bf6c15..521df88f6f 100644 --- a/ports/stm32/dma.c +++ b/ports/stm32/dma.c @@ -69,22 +69,22 @@ struct _dma_descr_t { // vary depending on the peripheral instance so they get passed separately static const DMA_InitTypeDef dma_init_struct_spi_i2c = { #if defined(STM32F4) || defined(STM32F7) - .Channel = 0, + .Channel = 0, #elif defined(STM32L4) - .Request = 0, + .Request = 0, #endif - .Direction = 0, - .PeriphInc = DMA_PINC_DISABLE, - .MemInc = DMA_MINC_ENABLE, + .Direction = 0, + .PeriphInc = DMA_PINC_DISABLE, + .MemInc = DMA_MINC_ENABLE, .PeriphDataAlignment = DMA_PDATAALIGN_BYTE, - .MemDataAlignment = DMA_MDATAALIGN_BYTE, - .Mode = DMA_NORMAL, - .Priority = DMA_PRIORITY_LOW, + .MemDataAlignment = DMA_MDATAALIGN_BYTE, + .Mode = DMA_NORMAL, + .Priority = DMA_PRIORITY_LOW, #if defined(STM32F4) || defined(STM32F7) - .FIFOMode = DMA_FIFOMODE_DISABLE, - .FIFOThreshold = DMA_FIFO_THRESHOLD_FULL, - .MemBurst = DMA_MBURST_INC4, - .PeriphBurst = DMA_PBURST_INC4 + .FIFOMode = DMA_FIFOMODE_DISABLE, + .FIFOThreshold = DMA_FIFO_THRESHOLD_FULL, + .MemBurst = DMA_MBURST_INC4, + .PeriphBurst = DMA_PBURST_INC4 #endif }; @@ -92,26 +92,26 @@ static const DMA_InitTypeDef dma_init_struct_spi_i2c = { // Parameters to dma_init() for SDIO tx and rx. static const DMA_InitTypeDef dma_init_struct_sdio = { #if defined(STM32F4) || defined(STM32F7) - .Channel = 0, + .Channel = 0, #elif defined(STM32L4) - .Request = 0, + .Request = 0, #endif - .Direction = 0, - .PeriphInc = DMA_PINC_DISABLE, - .MemInc = DMA_MINC_ENABLE, + .Direction = 0, + .PeriphInc = DMA_PINC_DISABLE, + .MemInc = DMA_MINC_ENABLE, .PeriphDataAlignment = DMA_PDATAALIGN_WORD, - .MemDataAlignment = DMA_MDATAALIGN_WORD, + .MemDataAlignment = DMA_MDATAALIGN_WORD, #if defined(STM32F4) || defined(STM32F7) - .Mode = DMA_PFCTRL, + .Mode = DMA_PFCTRL, #elif defined(STM32L4) - .Mode = DMA_NORMAL, + .Mode = DMA_NORMAL, #endif - .Priority = DMA_PRIORITY_VERY_HIGH, + .Priority = DMA_PRIORITY_VERY_HIGH, #if defined(STM32F4) || defined(STM32F7) - .FIFOMode = DMA_FIFOMODE_ENABLE, - .FIFOThreshold = DMA_FIFO_THRESHOLD_FULL, - .MemBurst = DMA_MBURST_INC4, - .PeriphBurst = DMA_PBURST_INC4, + .FIFOMode = DMA_FIFOMODE_ENABLE, + .FIFOThreshold = DMA_FIFO_THRESHOLD_FULL, + .MemBurst = DMA_MBURST_INC4, + .PeriphBurst = DMA_PBURST_INC4, #endif }; #endif @@ -120,22 +120,22 @@ static const DMA_InitTypeDef dma_init_struct_sdio = { // Default parameters to dma_init() for DAC tx static const DMA_InitTypeDef dma_init_struct_dac = { #if defined(STM32F4) || defined(STM32F7) - .Channel = 0, + .Channel = 0, #elif defined(STM32L4) - .Request = 0, + .Request = 0, #endif - .Direction = 0, - .PeriphInc = DMA_PINC_DISABLE, - .MemInc = DMA_MINC_ENABLE, + .Direction = 0, + .PeriphInc = DMA_PINC_DISABLE, + .MemInc = DMA_MINC_ENABLE, .PeriphDataAlignment = DMA_PDATAALIGN_BYTE, - .MemDataAlignment = DMA_MDATAALIGN_BYTE, - .Mode = DMA_NORMAL, - .Priority = DMA_PRIORITY_HIGH, + .MemDataAlignment = DMA_MDATAALIGN_BYTE, + .Mode = DMA_NORMAL, + .Priority = DMA_PRIORITY_HIGH, #if defined(STM32F4) || defined(STM32F7) - .FIFOMode = DMA_FIFOMODE_DISABLE, - .FIFOThreshold = DMA_FIFO_THRESHOLD_HALFFULL, - .MemBurst = DMA_MBURST_SINGLE, - .PeriphBurst = DMA_PBURST_SINGLE, + .FIFOMode = DMA_FIFOMODE_DISABLE, + .FIFOThreshold = DMA_FIFO_THRESHOLD_HALFFULL, + .MemBurst = DMA_MBURST_SINGLE, + .PeriphBurst = DMA_PBURST_SINGLE, #endif }; #endif @@ -143,21 +143,21 @@ static const DMA_InitTypeDef dma_init_struct_dac = { #if MICROPY_HW_ENABLE_DCMI static const DMA_InitTypeDef dma_init_struct_dcmi = { #if defined(STM32H7) - .Request = DMA_REQUEST_DCMI, + .Request = DMA_REQUEST_DCMI, #else - .Channel = DMA_CHANNEL_1, + .Channel = DMA_CHANNEL_1, #endif - .Direction = DMA_PERIPH_TO_MEMORY, - .PeriphInc = DMA_PINC_DISABLE, - .MemInc = DMA_MINC_ENABLE, + .Direction = DMA_PERIPH_TO_MEMORY, + .PeriphInc = DMA_PINC_DISABLE, + .MemInc = DMA_MINC_ENABLE, .PeriphDataAlignment = DMA_PDATAALIGN_WORD, - .MemDataAlignment = DMA_MDATAALIGN_WORD, - .Mode = DMA_NORMAL, - .Priority = DMA_PRIORITY_HIGH, - .FIFOMode = DMA_FIFOMODE_ENABLE, - .FIFOThreshold = DMA_FIFO_THRESHOLD_FULL, - .MemBurst = DMA_MBURST_INC4, - .PeriphBurst = DMA_PBURST_SINGLE + .MemDataAlignment = DMA_MDATAALIGN_WORD, + .Mode = DMA_NORMAL, + .Priority = DMA_PRIORITY_HIGH, + .FIFOMode = DMA_FIFOMODE_ENABLE, + .FIFOThreshold = DMA_FIFO_THRESHOLD_FULL, + .MemBurst = DMA_MBURST_INC4, + .PeriphBurst = DMA_PBURST_SINGLE }; #endif @@ -260,13 +260,13 @@ const dma_descr_t dma_SPI_5_TX = { DMA2_Stream4, DMA_CHANNEL_2, dma_id_12, &dma const dma_descr_t dma_SPI_4_TX = { DMA2_Stream4, DMA_CHANNEL_5, dma_id_12, &dma_init_struct_spi_i2c }; const dma_descr_t dma_SPI_6_TX = { DMA2_Stream5, DMA_CHANNEL_1, dma_id_13, &dma_init_struct_spi_i2c }; const dma_descr_t dma_SPI_1_TX = { DMA2_Stream5, DMA_CHANNEL_3, dma_id_13, &dma_init_struct_spi_i2c }; -//#if defined(STM32F7) && defined(SDMMC2) && MICROPY_HW_HAS_SDCARD -//const dma_descr_t dma_SDMMC_2 = { DMA2_Stream5, DMA_CHANNEL_11, dma_id_13, &dma_init_struct_sdio }; -//#endif +// #if defined(STM32F7) && defined(SDMMC2) && MICROPY_HW_HAS_SDCARD +// const dma_descr_t dma_SDMMC_2 = { DMA2_Stream5, DMA_CHANNEL_11, dma_id_13, &dma_init_struct_sdio }; +// #endif const dma_descr_t dma_SPI_6_RX = { DMA2_Stream6, DMA_CHANNEL_1, dma_id_14, &dma_init_struct_spi_i2c }; -//#if defined(MICROPY_HW_HAS_SDCARD) && MICROPY_HW_HAS_SDCARD -//const dma_descr_t dma_SDIO_0 = { DMA2_Stream6, DMA_CHANNEL_4, dma_id_14, &dma_init_struct_sdio }; -//#endif +// #if defined(MICROPY_HW_HAS_SDCARD) && MICROPY_HW_HAS_SDCARD +// const dma_descr_t dma_SDIO_0 = { DMA2_Stream6, DMA_CHANNEL_4, dma_id_14, &dma_init_struct_sdio }; +// #endif /* not preferred streams const dma_descr_t dma_SPI_1_TX = { DMA2_Stream3, DMA_CHANNEL_3, dma_id_11, &dma_init_struct_spi_i2c }; const dma_descr_t dma_SPI_1_RX = { DMA2_Stream0, DMA_CHANNEL_3, dma_id_8, &dma_init_struct_spi_i2c }; @@ -310,11 +310,11 @@ static const uint8_t dma_irqn[NSTREAM] = { // number. The duplicate streams are ok as long as they aren't used at the same time. // DMA1 streams -//const dma_descr_t dma_ADC_1_RX = { DMA1_Channel1, DMA_REQUEST_0, dma_id_0, NULL }; // unused -//const dma_descr_t dma_ADC_2_RX = { DMA1_Channel2, DMA_REQUEST_0, dma_id_1, NULL }; // unused +// const dma_descr_t dma_ADC_1_RX = { DMA1_Channel1, DMA_REQUEST_0, dma_id_0, NULL }; // unused +// const dma_descr_t dma_ADC_2_RX = { DMA1_Channel2, DMA_REQUEST_0, dma_id_1, NULL }; // unused const dma_descr_t dma_SPI_1_RX = { DMA1_Channel2, DMA_REQUEST_1, dma_id_1, &dma_init_struct_spi_i2c }; const dma_descr_t dma_I2C_3_TX = { DMA1_Channel2, DMA_REQUEST_3, dma_id_1, &dma_init_struct_spi_i2c }; -//const dma_descr_t dma_ADC_3_RX = { DMA1_Channel3, DMA_REQUEST_0, dma_id_2, NULL }; // unused +// const dma_descr_t dma_ADC_3_RX = { DMA1_Channel3, DMA_REQUEST_0, dma_id_2, NULL }; // unused const dma_descr_t dma_SPI_1_TX = { DMA1_Channel3, DMA_REQUEST_1, dma_id_2, &dma_init_struct_spi_i2c }; const dma_descr_t dma_I2C_3_RX = { DMA1_Channel3, DMA_REQUEST_3, dma_id_2, &dma_init_struct_spi_i2c }; #if MICROPY_HW_ENABLE_DAC @@ -494,39 +494,219 @@ void DMA1_Ch4_7_DMA2_Ch3_5_IRQHandler(void) { #elif defined(STM32F4) || defined(STM32F7) || defined(STM32H7) -void DMA1_Stream0_IRQHandler(void) { IRQ_ENTER(DMA1_Stream0_IRQn); if (dma_handle[dma_id_0] != NULL) { HAL_DMA_IRQHandler(dma_handle[dma_id_0]); } IRQ_EXIT(DMA1_Stream0_IRQn); } -void DMA1_Stream1_IRQHandler(void) { IRQ_ENTER(DMA1_Stream1_IRQn); if (dma_handle[dma_id_1] != NULL) { HAL_DMA_IRQHandler(dma_handle[dma_id_1]); } IRQ_EXIT(DMA1_Stream1_IRQn); } -void DMA1_Stream2_IRQHandler(void) { IRQ_ENTER(DMA1_Stream2_IRQn); if (dma_handle[dma_id_2] != NULL) { HAL_DMA_IRQHandler(dma_handle[dma_id_2]); } IRQ_EXIT(DMA1_Stream2_IRQn); } -void DMA1_Stream3_IRQHandler(void) { IRQ_ENTER(DMA1_Stream3_IRQn); if (dma_handle[dma_id_3] != NULL) { HAL_DMA_IRQHandler(dma_handle[dma_id_3]); } IRQ_EXIT(DMA1_Stream3_IRQn); } -void DMA1_Stream4_IRQHandler(void) { IRQ_ENTER(DMA1_Stream4_IRQn); if (dma_handle[dma_id_4] != NULL) { HAL_DMA_IRQHandler(dma_handle[dma_id_4]); } IRQ_EXIT(DMA1_Stream4_IRQn); } -void DMA1_Stream5_IRQHandler(void) { IRQ_ENTER(DMA1_Stream5_IRQn); if (dma_handle[dma_id_5] != NULL) { HAL_DMA_IRQHandler(dma_handle[dma_id_5]); } IRQ_EXIT(DMA1_Stream5_IRQn); } -void DMA1_Stream6_IRQHandler(void) { IRQ_ENTER(DMA1_Stream6_IRQn); if (dma_handle[dma_id_6] != NULL) { HAL_DMA_IRQHandler(dma_handle[dma_id_6]); } IRQ_EXIT(DMA1_Stream6_IRQn); } -void DMA1_Stream7_IRQHandler(void) { IRQ_ENTER(DMA1_Stream7_IRQn); if (dma_handle[dma_id_7] != NULL) { HAL_DMA_IRQHandler(dma_handle[dma_id_7]); } IRQ_EXIT(DMA1_Stream7_IRQn); } -void DMA2_Stream0_IRQHandler(void) { IRQ_ENTER(DMA2_Stream0_IRQn); if (dma_handle[dma_id_8] != NULL) { HAL_DMA_IRQHandler(dma_handle[dma_id_8]); } IRQ_EXIT(DMA2_Stream0_IRQn); } -void DMA2_Stream1_IRQHandler(void) { IRQ_ENTER(DMA2_Stream1_IRQn); if (dma_handle[dma_id_9] != NULL) { HAL_DMA_IRQHandler(dma_handle[dma_id_9]); } IRQ_EXIT(DMA2_Stream1_IRQn); } -void DMA2_Stream2_IRQHandler(void) { IRQ_ENTER(DMA2_Stream2_IRQn); if (dma_handle[dma_id_10] != NULL) { HAL_DMA_IRQHandler(dma_handle[dma_id_10]); } IRQ_EXIT(DMA2_Stream2_IRQn); } -void DMA2_Stream3_IRQHandler(void) { IRQ_ENTER(DMA2_Stream3_IRQn); if (dma_handle[dma_id_11] != NULL) { HAL_DMA_IRQHandler(dma_handle[dma_id_11]); } IRQ_EXIT(DMA2_Stream3_IRQn); } -void DMA2_Stream4_IRQHandler(void) { IRQ_ENTER(DMA2_Stream4_IRQn); if (dma_handle[dma_id_12] != NULL) { HAL_DMA_IRQHandler(dma_handle[dma_id_12]); } IRQ_EXIT(DMA2_Stream4_IRQn); } -void DMA2_Stream5_IRQHandler(void) { IRQ_ENTER(DMA2_Stream5_IRQn); if (dma_handle[dma_id_13] != NULL) { HAL_DMA_IRQHandler(dma_handle[dma_id_13]); } IRQ_EXIT(DMA2_Stream5_IRQn); } -void DMA2_Stream6_IRQHandler(void) { IRQ_ENTER(DMA2_Stream6_IRQn); if (dma_handle[dma_id_14] != NULL) { HAL_DMA_IRQHandler(dma_handle[dma_id_14]); } IRQ_EXIT(DMA2_Stream6_IRQn); } -void DMA2_Stream7_IRQHandler(void) { IRQ_ENTER(DMA2_Stream7_IRQn); if (dma_handle[dma_id_15] != NULL) { HAL_DMA_IRQHandler(dma_handle[dma_id_15]); } IRQ_EXIT(DMA2_Stream7_IRQn); } +void DMA1_Stream0_IRQHandler(void) { + IRQ_ENTER(DMA1_Stream0_IRQn); + if (dma_handle[dma_id_0] != NULL) { + HAL_DMA_IRQHandler(dma_handle[dma_id_0]); + } + IRQ_EXIT(DMA1_Stream0_IRQn); +} +void DMA1_Stream1_IRQHandler(void) { + IRQ_ENTER(DMA1_Stream1_IRQn); + if (dma_handle[dma_id_1] != NULL) { + HAL_DMA_IRQHandler(dma_handle[dma_id_1]); + } + IRQ_EXIT(DMA1_Stream1_IRQn); +} +void DMA1_Stream2_IRQHandler(void) { + IRQ_ENTER(DMA1_Stream2_IRQn); + if (dma_handle[dma_id_2] != NULL) { + HAL_DMA_IRQHandler(dma_handle[dma_id_2]); + } + IRQ_EXIT(DMA1_Stream2_IRQn); +} +void DMA1_Stream3_IRQHandler(void) { + IRQ_ENTER(DMA1_Stream3_IRQn); + if (dma_handle[dma_id_3] != NULL) { + HAL_DMA_IRQHandler(dma_handle[dma_id_3]); + } + IRQ_EXIT(DMA1_Stream3_IRQn); +} +void DMA1_Stream4_IRQHandler(void) { + IRQ_ENTER(DMA1_Stream4_IRQn); + if (dma_handle[dma_id_4] != NULL) { + HAL_DMA_IRQHandler(dma_handle[dma_id_4]); + } + IRQ_EXIT(DMA1_Stream4_IRQn); +} +void DMA1_Stream5_IRQHandler(void) { + IRQ_ENTER(DMA1_Stream5_IRQn); + if (dma_handle[dma_id_5] != NULL) { + HAL_DMA_IRQHandler(dma_handle[dma_id_5]); + } + IRQ_EXIT(DMA1_Stream5_IRQn); +} +void DMA1_Stream6_IRQHandler(void) { + IRQ_ENTER(DMA1_Stream6_IRQn); + if (dma_handle[dma_id_6] != NULL) { + HAL_DMA_IRQHandler(dma_handle[dma_id_6]); + } + IRQ_EXIT(DMA1_Stream6_IRQn); +} +void DMA1_Stream7_IRQHandler(void) { + IRQ_ENTER(DMA1_Stream7_IRQn); + if (dma_handle[dma_id_7] != NULL) { + HAL_DMA_IRQHandler(dma_handle[dma_id_7]); + } + IRQ_EXIT(DMA1_Stream7_IRQn); +} +void DMA2_Stream0_IRQHandler(void) { + IRQ_ENTER(DMA2_Stream0_IRQn); + if (dma_handle[dma_id_8] != NULL) { + HAL_DMA_IRQHandler(dma_handle[dma_id_8]); + } + IRQ_EXIT(DMA2_Stream0_IRQn); +} +void DMA2_Stream1_IRQHandler(void) { + IRQ_ENTER(DMA2_Stream1_IRQn); + if (dma_handle[dma_id_9] != NULL) { + HAL_DMA_IRQHandler(dma_handle[dma_id_9]); + } + IRQ_EXIT(DMA2_Stream1_IRQn); +} +void DMA2_Stream2_IRQHandler(void) { + IRQ_ENTER(DMA2_Stream2_IRQn); + if (dma_handle[dma_id_10] != NULL) { + HAL_DMA_IRQHandler(dma_handle[dma_id_10]); + } + IRQ_EXIT(DMA2_Stream2_IRQn); +} +void DMA2_Stream3_IRQHandler(void) { + IRQ_ENTER(DMA2_Stream3_IRQn); + if (dma_handle[dma_id_11] != NULL) { + HAL_DMA_IRQHandler(dma_handle[dma_id_11]); + } + IRQ_EXIT(DMA2_Stream3_IRQn); +} +void DMA2_Stream4_IRQHandler(void) { + IRQ_ENTER(DMA2_Stream4_IRQn); + if (dma_handle[dma_id_12] != NULL) { + HAL_DMA_IRQHandler(dma_handle[dma_id_12]); + } + IRQ_EXIT(DMA2_Stream4_IRQn); +} +void DMA2_Stream5_IRQHandler(void) { + IRQ_ENTER(DMA2_Stream5_IRQn); + if (dma_handle[dma_id_13] != NULL) { + HAL_DMA_IRQHandler(dma_handle[dma_id_13]); + } + IRQ_EXIT(DMA2_Stream5_IRQn); +} +void DMA2_Stream6_IRQHandler(void) { + IRQ_ENTER(DMA2_Stream6_IRQn); + if (dma_handle[dma_id_14] != NULL) { + HAL_DMA_IRQHandler(dma_handle[dma_id_14]); + } + IRQ_EXIT(DMA2_Stream6_IRQn); +} +void DMA2_Stream7_IRQHandler(void) { + IRQ_ENTER(DMA2_Stream7_IRQn); + if (dma_handle[dma_id_15] != NULL) { + HAL_DMA_IRQHandler(dma_handle[dma_id_15]); + } + IRQ_EXIT(DMA2_Stream7_IRQn); +} #elif defined(STM32L4) -void DMA1_Channel1_IRQHandler(void) { IRQ_ENTER(DMA1_Channel1_IRQn); if (dma_handle[dma_id_0] != NULL) { HAL_DMA_IRQHandler(dma_handle[dma_id_0]); } IRQ_EXIT(DMA1_Channel1_IRQn); } -void DMA1_Channel2_IRQHandler(void) { IRQ_ENTER(DMA1_Channel2_IRQn); if (dma_handle[dma_id_1] != NULL) { HAL_DMA_IRQHandler(dma_handle[dma_id_1]); } IRQ_EXIT(DMA1_Channel2_IRQn); } -void DMA1_Channel3_IRQHandler(void) { IRQ_ENTER(DMA1_Channel3_IRQn); if (dma_handle[dma_id_2] != NULL) { HAL_DMA_IRQHandler(dma_handle[dma_id_2]); } IRQ_EXIT(DMA1_Channel3_IRQn); } -void DMA1_Channel4_IRQHandler(void) { IRQ_ENTER(DMA1_Channel4_IRQn); if (dma_handle[dma_id_3] != NULL) { HAL_DMA_IRQHandler(dma_handle[dma_id_3]); } IRQ_EXIT(DMA1_Channel4_IRQn); } -void DMA1_Channel5_IRQHandler(void) { IRQ_ENTER(DMA1_Channel5_IRQn); if (dma_handle[dma_id_4] != NULL) { HAL_DMA_IRQHandler(dma_handle[dma_id_4]); } IRQ_EXIT(DMA1_Channel5_IRQn); } -void DMA1_Channel6_IRQHandler(void) { IRQ_ENTER(DMA1_Channel6_IRQn); if (dma_handle[dma_id_5] != NULL) { HAL_DMA_IRQHandler(dma_handle[dma_id_5]); } IRQ_EXIT(DMA1_Channel6_IRQn); } -void DMA1_Channel7_IRQHandler(void) { IRQ_ENTER(DMA1_Channel7_IRQn); if (dma_handle[dma_id_6] != NULL) { HAL_DMA_IRQHandler(dma_handle[dma_id_6]); } IRQ_EXIT(DMA1_Channel7_IRQn); } -void DMA2_Channel1_IRQHandler(void) { IRQ_ENTER(DMA2_Channel1_IRQn); if (dma_handle[dma_id_7] != NULL) { HAL_DMA_IRQHandler(dma_handle[dma_id_7]); } IRQ_EXIT(DMA2_Channel1_IRQn); } -void DMA2_Channel2_IRQHandler(void) { IRQ_ENTER(DMA2_Channel2_IRQn); if (dma_handle[dma_id_8] != NULL) { HAL_DMA_IRQHandler(dma_handle[dma_id_8]); } IRQ_EXIT(DMA2_Channel2_IRQn); } -void DMA2_Channel3_IRQHandler(void) { IRQ_ENTER(DMA2_Channel3_IRQn); if (dma_handle[dma_id_9] != NULL) { HAL_DMA_IRQHandler(dma_handle[dma_id_9]); } IRQ_EXIT(DMA2_Channel3_IRQn); } -void DMA2_Channel4_IRQHandler(void) { IRQ_ENTER(DMA2_Channel4_IRQn); if (dma_handle[dma_id_10] != NULL) { HAL_DMA_IRQHandler(dma_handle[dma_id_10]);} IRQ_EXIT(DMA2_Channel4_IRQn); } -void DMA2_Channel5_IRQHandler(void) { IRQ_ENTER(DMA2_Channel5_IRQn); if (dma_handle[dma_id_11] != NULL) { HAL_DMA_IRQHandler(dma_handle[dma_id_11]);} IRQ_EXIT(DMA2_Channel5_IRQn); } -void DMA2_Channel6_IRQHandler(void) { IRQ_ENTER(DMA2_Channel6_IRQn); if (dma_handle[dma_id_12] != NULL) { HAL_DMA_IRQHandler(dma_handle[dma_id_12]);} IRQ_EXIT(DMA2_Channel6_IRQn); } -void DMA2_Channel7_IRQHandler(void) { IRQ_ENTER(DMA2_Channel7_IRQn); if (dma_handle[dma_id_13] != NULL) { HAL_DMA_IRQHandler(dma_handle[dma_id_13]);} IRQ_EXIT(DMA2_Channel7_IRQn); } +void DMA1_Channel1_IRQHandler(void) { + IRQ_ENTER(DMA1_Channel1_IRQn); + if (dma_handle[dma_id_0] != NULL) { + HAL_DMA_IRQHandler(dma_handle[dma_id_0]); + } + IRQ_EXIT(DMA1_Channel1_IRQn); +} +void DMA1_Channel2_IRQHandler(void) { + IRQ_ENTER(DMA1_Channel2_IRQn); + if (dma_handle[dma_id_1] != NULL) { + HAL_DMA_IRQHandler(dma_handle[dma_id_1]); + } + IRQ_EXIT(DMA1_Channel2_IRQn); +} +void DMA1_Channel3_IRQHandler(void) { + IRQ_ENTER(DMA1_Channel3_IRQn); + if (dma_handle[dma_id_2] != NULL) { + HAL_DMA_IRQHandler(dma_handle[dma_id_2]); + } + IRQ_EXIT(DMA1_Channel3_IRQn); +} +void DMA1_Channel4_IRQHandler(void) { + IRQ_ENTER(DMA1_Channel4_IRQn); + if (dma_handle[dma_id_3] != NULL) { + HAL_DMA_IRQHandler(dma_handle[dma_id_3]); + } + IRQ_EXIT(DMA1_Channel4_IRQn); +} +void DMA1_Channel5_IRQHandler(void) { + IRQ_ENTER(DMA1_Channel5_IRQn); + if (dma_handle[dma_id_4] != NULL) { + HAL_DMA_IRQHandler(dma_handle[dma_id_4]); + } + IRQ_EXIT(DMA1_Channel5_IRQn); +} +void DMA1_Channel6_IRQHandler(void) { + IRQ_ENTER(DMA1_Channel6_IRQn); + if (dma_handle[dma_id_5] != NULL) { + HAL_DMA_IRQHandler(dma_handle[dma_id_5]); + } + IRQ_EXIT(DMA1_Channel6_IRQn); +} +void DMA1_Channel7_IRQHandler(void) { + IRQ_ENTER(DMA1_Channel7_IRQn); + if (dma_handle[dma_id_6] != NULL) { + HAL_DMA_IRQHandler(dma_handle[dma_id_6]); + } + IRQ_EXIT(DMA1_Channel7_IRQn); +} +void DMA2_Channel1_IRQHandler(void) { + IRQ_ENTER(DMA2_Channel1_IRQn); + if (dma_handle[dma_id_7] != NULL) { + HAL_DMA_IRQHandler(dma_handle[dma_id_7]); + } + IRQ_EXIT(DMA2_Channel1_IRQn); +} +void DMA2_Channel2_IRQHandler(void) { + IRQ_ENTER(DMA2_Channel2_IRQn); + if (dma_handle[dma_id_8] != NULL) { + HAL_DMA_IRQHandler(dma_handle[dma_id_8]); + } + IRQ_EXIT(DMA2_Channel2_IRQn); +} +void DMA2_Channel3_IRQHandler(void) { + IRQ_ENTER(DMA2_Channel3_IRQn); + if (dma_handle[dma_id_9] != NULL) { + HAL_DMA_IRQHandler(dma_handle[dma_id_9]); + } + IRQ_EXIT(DMA2_Channel3_IRQn); +} +void DMA2_Channel4_IRQHandler(void) { + IRQ_ENTER(DMA2_Channel4_IRQn); + if (dma_handle[dma_id_10] != NULL) { + HAL_DMA_IRQHandler(dma_handle[dma_id_10]); + } + IRQ_EXIT(DMA2_Channel4_IRQn); +} +void DMA2_Channel5_IRQHandler(void) { + IRQ_ENTER(DMA2_Channel5_IRQn); + if (dma_handle[dma_id_11] != NULL) { + HAL_DMA_IRQHandler(dma_handle[dma_id_11]); + } + IRQ_EXIT(DMA2_Channel5_IRQn); +} +void DMA2_Channel6_IRQHandler(void) { + IRQ_ENTER(DMA2_Channel6_IRQn); + if (dma_handle[dma_id_12] != NULL) { + HAL_DMA_IRQHandler(dma_handle[dma_id_12]); + } + IRQ_EXIT(DMA2_Channel6_IRQn); +} +void DMA2_Channel7_IRQHandler(void) { + IRQ_ENTER(DMA2_Channel7_IRQn); + if (dma_handle[dma_id_13] != NULL) { + HAL_DMA_IRQHandler(dma_handle[dma_id_13]); + } + IRQ_EXIT(DMA2_Channel7_IRQn); +} #endif @@ -593,14 +773,14 @@ void dma_init_handle(DMA_HandleTypeDef *dma, const dma_descr_t *dma_descr, uint3 dma->Parent = data; } -void dma_init(DMA_HandleTypeDef *dma, const dma_descr_t *dma_descr, uint32_t dir, void *data){ +void dma_init(DMA_HandleTypeDef *dma, const dma_descr_t *dma_descr, uint32_t dir, void *data) { // Some drivers allocate the DMA_HandleTypeDef from the stack // (i.e. dac, i2c, spi) and for those cases we need to clear the // structure so we don't get random values from the stack) memset(dma, 0, sizeof(*dma)); if (dma_descr != NULL) { - dma_id_t dma_id = dma_descr->id; + dma_id_t dma_id = dma_descr->id; dma_init_handle(dma, dma_descr, dir, data); // set global pointer for IRQ handler @@ -673,7 +853,7 @@ void dma_invalidate_channel(const dma_descr_t *dma_descr) { if (dma_descr != NULL) { dma_id_t dma_id = dma_descr->id; // Only compare the sub-instance, not the direction bit (MSB) - if ((dma_last_sub_instance[dma_id] & 0x7f) == DMA_SUB_INSTANCE_AS_UINT8(dma_descr->sub_instance) ) { + if ((dma_last_sub_instance[dma_id] & 0x7f) == DMA_SUB_INSTANCE_AS_UINT8(dma_descr->sub_instance)) { dma_last_sub_instance[dma_id] = DMA_INVALID_CHANNEL; } } @@ -682,7 +862,7 @@ void dma_invalidate_channel(const dma_descr_t *dma_descr) { // Called from the SysTick handler // We use LSB of tick to select which controller to process void dma_idle_handler(int tick) { - static const uint32_t controller_mask[] = { + static const uint32_t controller_mask[] = { DMA1_ENABLE_MASK, DMA2_ENABLE_MASK }; { diff --git a/ports/stm32/dma.h b/ports/stm32/dma.h index 84875374b2..f6b9f2d780 100644 --- a/ports/stm32/dma.h +++ b/ports/stm32/dma.h @@ -82,8 +82,8 @@ extern const dma_descr_t dma_SDIO_0; #endif typedef union { - uint16_t enabled; // Used to test if both counters are == 0 - uint8_t counter[2]; + uint16_t enabled; // Used to test if both counters are == 0 + uint8_t counter[2]; } dma_idle_count_t; extern volatile dma_idle_count_t dma_idle; #define DMA_IDLE_ENABLED() (dma_idle.enabled != 0) diff --git a/ports/stm32/extint.c b/ports/stm32/extint.c index b6e980101a..62fe5e4653 100644 --- a/ports/stm32/extint.c +++ b/ports/stm32/extint.c @@ -344,13 +344,13 @@ void extint_swint(uint line) { return; } // we need 0 to 1 transition to trigger the interrupt -#if defined(STM32L4) || defined(STM32H7) + #if defined(STM32L4) || defined(STM32H7) EXTI->SWIER1 &= ~(1 << line); EXTI->SWIER1 |= (1 << line); -#else + #else EXTI->SWIER &= ~(1 << line); EXTI->SWIER |= (1 << line); -#endif + #endif } /// \method line() @@ -506,14 +506,14 @@ const mp_obj_type_t extint_type = { .name = MP_QSTR_ExtInt, .print = extint_obj_print, .make_new = extint_make_new, - .locals_dict = (mp_obj_dict_t*)&extint_locals_dict, + .locals_dict = (mp_obj_dict_t *)&extint_locals_dict, }; void extint_init0(void) { for (int i = 0; i < PYB_EXTI_NUM_VECTORS; i++) { MP_STATE_PORT(pyb_extint_callback)[i] = mp_const_none; pyb_extint_mode[i] = EXTI_Mode_Interrupt; - } + } } // Interrupt handler diff --git a/ports/stm32/flash.c b/ports/stm32/flash.c index e1cf707d34..0a61c0d3bf 100644 --- a/ports/stm32/flash.c +++ b/ports/stm32/flash.c @@ -92,7 +92,7 @@ static uint32_t get_bank(uint32_t addr) { if (READ_BIT(FLASH->OPTCR, FLASH_OPTCR_SWAP_BANK) == 0) { #else if (READ_BIT(SYSCFG->MEMRMP, SYSCFG_MEMRMP_FB_MODE) == 0) { - #endif + #endif // no bank swap if (addr < (FLASH_BASE + FLASH_BANK_SIZE)) { return FLASH_BANK_1; @@ -161,31 +161,32 @@ void flash_erase(uint32_t flash_dest, uint32_t num_word32) { #if defined(STM32F0) __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_WRPERR | FLASH_FLAG_PGERR); - EraseInitStruct.TypeErase = FLASH_TYPEERASE_PAGES; + EraseInitStruct.TypeErase = FLASH_TYPEERASE_PAGES; EraseInitStruct.PageAddress = flash_dest; - EraseInitStruct.NbPages = (4 * num_word32 + FLASH_PAGE_SIZE - 4) / FLASH_PAGE_SIZE; + EraseInitStruct.NbPages = (4 * num_word32 + FLASH_PAGE_SIZE - 4) / FLASH_PAGE_SIZE; #elif (defined(STM32L4) && !defined(SYSCFG_MEMRMP_FB_MODE)) __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_ALL_ERRORS); - EraseInitStruct.TypeErase = FLASH_TYPEERASE_PAGES; - EraseInitStruct.Page = flash_dest; - EraseInitStruct.NbPages = (4 * num_word32 + FLASH_PAGE_SIZE - 4) / FLASH_PAGE_SIZE; + EraseInitStruct.TypeErase = FLASH_TYPEERASE_PAGES; + EraseInitStruct.Page = flash_dest; + EraseInitStruct.NbPages = (4 * num_word32 + FLASH_PAGE_SIZE - 4) / FLASH_PAGE_SIZE; #elif defined(STM32L4) __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_ALL_ERRORS); // erase the sector(s) // The sector returned by flash_get_sector_info can not be used // as the flash has on each bank 0/1 pages 0..255 - EraseInitStruct.TypeErase = FLASH_TYPEERASE_PAGES; - EraseInitStruct.Banks = get_bank(flash_dest); - EraseInitStruct.Page = get_page(flash_dest); - EraseInitStruct.NbPages = get_page(flash_dest + 4 * num_word32 - 1) - EraseInitStruct.Page + 1;; + EraseInitStruct.TypeErase = FLASH_TYPEERASE_PAGES; + EraseInitStruct.Banks = get_bank(flash_dest); + EraseInitStruct.Page = get_page(flash_dest); + EraseInitStruct.NbPages = get_page(flash_dest + 4 * num_word32 - 1) - EraseInitStruct.Page + 1; + ; #else // Clear pending flags (if any) #if defined(STM32H7) __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_ALL_ERRORS_BANK1 | FLASH_FLAG_ALL_ERRORS_BANK2); #else __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR | - FLASH_FLAG_PGAERR | FLASH_FLAG_PGPERR | FLASH_FLAG_PGSERR); + FLASH_FLAG_PGAERR | FLASH_FLAG_PGPERR | FLASH_FLAG_PGSERR); #endif // erase the sector(s) @@ -240,7 +241,7 @@ void flash_write(uint32_t flash_dest, const uint32_t *src, uint32_t num_word32) // program the flash uint64 by uint64 for (int i = 0; i < num_word32 / 2; i++) { - uint64_t val = *(uint64_t*)src; + uint64_t val = *(uint64_t *)src; if (HAL_FLASH_Program(FLASH_TYPEPROGRAM_DOUBLEWORD, flash_dest, val) != HAL_OK) { // error occurred during flash write HAL_FLASH_Lock(); // lock the flash @@ -250,7 +251,7 @@ void flash_write(uint32_t flash_dest, const uint32_t *src, uint32_t num_word32) src += 2; } if ((num_word32 & 0x01) == 1) { - uint64_t val = *(uint64_t*)flash_dest; + uint64_t val = *(uint64_t *)flash_dest; val = (val & 0xffffffff00000000uL) | (*src); if (HAL_FLASH_Program(FLASH_TYPEPROGRAM_DOUBLEWORD, flash_dest, val) != HAL_OK) { // error occurred during flash write diff --git a/ports/stm32/flashbdev.c b/ports/stm32/flashbdev.c index 0b95dcc4ff..8fc964bf55 100644 --- a/ports/stm32/flashbdev.c +++ b/ports/stm32/flashbdev.c @@ -168,7 +168,7 @@ static uint8_t *flash_cache_get_addr_for_write(uint32_t flash_addr) { } if (flash_cache_sector_id != flash_sector_id) { flash_bdev_ioctl(BDEV_IOCTL_SYNC, 0); - memcpy((void*)CACHE_MEM_START_ADDR, (const void*)flash_sector_start, flash_sector_size); + memcpy((void *)CACHE_MEM_START_ADDR, (const void *)flash_sector_start, flash_sector_size); flash_cache_sector_id = flash_sector_id; flash_cache_sector_start = flash_sector_start; flash_cache_sector_size = flash_sector_size; @@ -176,7 +176,7 @@ static uint8_t *flash_cache_get_addr_for_write(uint32_t flash_addr) { flash_flags |= FLASH_FLAG_DIRTY; led_state(PYB_LED_RED, 1); // indicate a dirty cache with LED on flash_tick_counter_last_write = HAL_GetTick(); - return (uint8_t*)CACHE_MEM_START_ADDR + flash_addr - flash_sector_start; + return (uint8_t *)CACHE_MEM_START_ADDR + flash_addr - flash_sector_start; } static uint8_t *flash_cache_get_addr_for_read(uint32_t flash_addr) { @@ -185,10 +185,10 @@ static uint8_t *flash_cache_get_addr_for_read(uint32_t flash_addr) { uint32_t flash_sector_id = flash_get_sector_info(flash_addr, &flash_sector_start, &flash_sector_size); if (flash_cache_sector_id == flash_sector_id) { // in cache, copy from there - return (uint8_t*)CACHE_MEM_START_ADDR + flash_addr - flash_sector_start; + return (uint8_t *)CACHE_MEM_START_ADDR + flash_addr - flash_sector_start; } // not in cache, copy straight from flash - return (uint8_t*)flash_addr; + return (uint8_t *)flash_addr; } static uint32_t convert_block_to_flash_addr(uint32_t block) { @@ -239,7 +239,7 @@ static void flash_bdev_irq_handler(void) { // On file close and flash unmount we get a forced write, so we can afford to wait a while if ((flash_flags & FLASH_FLAG_FORCE_WRITE) || HAL_GetTick() - flash_tick_counter_last_write >= 5000) { // sync the cache RAM buffer by writing it to the flash page - flash_write(flash_cache_sector_start, (const uint32_t*)CACHE_MEM_START_ADDR, flash_cache_sector_size / 4); + flash_write(flash_cache_sector_start, (const uint32_t *)CACHE_MEM_START_ADDR, flash_cache_sector_size / 4); // clear the flash flags now that we have a clean cache flash_flags = 0; // indicate a clean cache with LED off diff --git a/ports/stm32/font_petme128_8x8.h b/ports/stm32/font_petme128_8x8.h index cdc4e73a79..9963698b17 100644 --- a/ports/stm32/font_petme128_8x8.h +++ b/ports/stm32/font_petme128_8x8.h @@ -27,7 +27,7 @@ #define MICROPY_INCLUDED_STM32_FONT_PETME128_8X8_H static const uint8_t font_petme128_8x8[] = { - 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, // 32= + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, // 32= 0x00,0x00,0x00,0x4f,0x4f,0x00,0x00,0x00, // 33=! 0x00,0x07,0x07,0x00,0x00,0x07,0x07,0x00, // 34=" 0x14,0x7f,0x7f,0x14,0x14,0x7f,0x7f,0x14, // 35=# diff --git a/ports/stm32/gccollect.c b/ports/stm32/gccollect.c index 50880e2891..e235eba5b8 100644 --- a/ports/stm32/gccollect.c +++ b/ports/stm32/gccollect.c @@ -50,9 +50,9 @@ void gc_collect(void) { // trace the stack, including the registers (since they live on the stack in this function) #if MICROPY_PY_THREAD - gc_collect_root((void**)sp, ((uint32_t)MP_STATE_THREAD(stack_top) - sp) / sizeof(uint32_t)); + gc_collect_root((void **)sp, ((uint32_t)MP_STATE_THREAD(stack_top) - sp) / sizeof(uint32_t)); #else - gc_collect_root((void**)sp, ((uint32_t)&_ram_end - sp) / sizeof(uint32_t)); + gc_collect_root((void **)sp, ((uint32_t)&_ram_end - sp) / sizeof(uint32_t)); #endif // trace root pointers from any threads diff --git a/ports/stm32/help.c b/ports/stm32/help.c index f9d97b70d6..fba0a6937f 100644 --- a/ports/stm32/help.c +++ b/ports/stm32/help.c @@ -27,45 +27,45 @@ #include "py/builtin.h" const char stm32_help_text[] = -"Welcome to MicroPython!\n" -"\n" -"For online help please visit http://micropython.org/help/.\n" -"\n" -"Quick overview of commands for the board:\n" -" pyb.info() -- print some general information\n" -" pyb.delay(n) -- wait for n milliseconds\n" -" pyb.millis() -- get number of milliseconds since hard reset\n" -" pyb.Switch() -- create a switch object\n" -" Switch methods: (), callback(f)\n" -" pyb.LED(n) -- create an LED object for LED n (n=1,2,3,4)\n" -" LED methods: on(), off(), toggle(), intensity()\n" -" pyb.Pin(pin) -- get a pin, eg pyb.Pin('X1')\n" -" pyb.Pin(pin, m, [p]) -- get a pin and configure it for IO mode m, pull mode p\n" -" Pin methods: init(..), value([v]), high(), low()\n" -" pyb.ExtInt(pin, m, p, callback) -- create an external interrupt object\n" -" pyb.ADC(pin) -- make an analog object from a pin\n" -" ADC methods: read(), read_timed(buf, freq)\n" -" pyb.DAC(port) -- make a DAC object\n" -" DAC methods: triangle(freq), write(n), write_timed(buf, freq)\n" -" pyb.RTC() -- make an RTC object; methods: datetime([val])\n" -" pyb.rng() -- get a 30-bit hardware random number\n" -" pyb.Servo(n) -- create Servo object for servo n (n=1,2,3,4)\n" -" Servo methods: calibration(..), angle([x, [t]]), speed([x, [t]])\n" -" pyb.Accel() -- create an Accelerometer object\n" -" Accelerometer methods: x(), y(), z(), tilt(), filtered_xyz()\n" -"\n" -"Pins are numbered X1-X12, X17-X22, Y1-Y12, or by their MCU name\n" -"Pin IO modes are: pyb.Pin.IN, pyb.Pin.OUT_PP, pyb.Pin.OUT_OD\n" -"Pin pull modes are: pyb.Pin.PULL_NONE, pyb.Pin.PULL_UP, pyb.Pin.PULL_DOWN\n" -"Additional serial bus objects: pyb.I2C(n), pyb.SPI(n), pyb.UART(n)\n" -"\n" -"Control commands:\n" -" CTRL-A -- on a blank line, enter raw REPL mode\n" -" CTRL-B -- on a blank line, enter normal REPL mode\n" -" CTRL-C -- interrupt a running program\n" -" CTRL-D -- on a blank line, do a soft reset of the board\n" -" CTRL-E -- on a blank line, enter paste mode\n" -"\n" -"For further help on a specific object, type help(obj)\n" -"For a list of available modules, type help('modules')\n" + "Welcome to MicroPython!\n" + "\n" + "For online help please visit http://micropython.org/help/.\n" + "\n" + "Quick overview of commands for the board:\n" + " pyb.info() -- print some general information\n" + " pyb.delay(n) -- wait for n milliseconds\n" + " pyb.millis() -- get number of milliseconds since hard reset\n" + " pyb.Switch() -- create a switch object\n" + " Switch methods: (), callback(f)\n" + " pyb.LED(n) -- create an LED object for LED n (n=1,2,3,4)\n" + " LED methods: on(), off(), toggle(), intensity()\n" + " pyb.Pin(pin) -- get a pin, eg pyb.Pin('X1')\n" + " pyb.Pin(pin, m, [p]) -- get a pin and configure it for IO mode m, pull mode p\n" + " Pin methods: init(..), value([v]), high(), low()\n" + " pyb.ExtInt(pin, m, p, callback) -- create an external interrupt object\n" + " pyb.ADC(pin) -- make an analog object from a pin\n" + " ADC methods: read(), read_timed(buf, freq)\n" + " pyb.DAC(port) -- make a DAC object\n" + " DAC methods: triangle(freq), write(n), write_timed(buf, freq)\n" + " pyb.RTC() -- make an RTC object; methods: datetime([val])\n" + " pyb.rng() -- get a 30-bit hardware random number\n" + " pyb.Servo(n) -- create Servo object for servo n (n=1,2,3,4)\n" + " Servo methods: calibration(..), angle([x, [t]]), speed([x, [t]])\n" + " pyb.Accel() -- create an Accelerometer object\n" + " Accelerometer methods: x(), y(), z(), tilt(), filtered_xyz()\n" + "\n" + "Pins are numbered X1-X12, X17-X22, Y1-Y12, or by their MCU name\n" + "Pin IO modes are: pyb.Pin.IN, pyb.Pin.OUT_PP, pyb.Pin.OUT_OD\n" + "Pin pull modes are: pyb.Pin.PULL_NONE, pyb.Pin.PULL_UP, pyb.Pin.PULL_DOWN\n" + "Additional serial bus objects: pyb.I2C(n), pyb.SPI(n), pyb.UART(n)\n" + "\n" + "Control commands:\n" + " CTRL-A -- on a blank line, enter raw REPL mode\n" + " CTRL-B -- on a blank line, enter normal REPL mode\n" + " CTRL-C -- interrupt a running program\n" + " CTRL-D -- on a blank line, do a soft reset of the board\n" + " CTRL-E -- on a blank line, enter paste mode\n" + "\n" + "For further help on a specific object, type help(obj)\n" + "For a list of available modules, type help('modules')\n" ; diff --git a/ports/stm32/i2cslave.c b/ports/stm32/i2cslave.c index 473f0c8c55..bf8f62dc4a 100644 --- a/ports/stm32/i2cslave.c +++ b/ports/stm32/i2cslave.c @@ -90,7 +90,7 @@ void i2c_slave_ev_irq_handler(i2c_slave_t *i2c) { i2c->ICR = I2C_ICR_STOPCF; i2c->OAR1 &= ~I2C_OAR1_OA1EN; if (i2c->ISR & I2C_ISR_DIR) { - //i2c_slave_process_tx_end(); + // i2c_slave_process_tx_end(); } else { i2c_slave_process_rx_end(); } diff --git a/ports/stm32/irq.h b/ports/stm32/irq.h index 9919013f89..11f4e25f48 100644 --- a/ports/stm32/irq.h +++ b/ports/stm32/irq.h @@ -104,7 +104,7 @@ MP_DECLARE_CONST_FUN_OBJ_0(pyb_irq_stats_obj); #if __CORTEX_M == 0 -//#def IRQ_PRI_SYSTICK 0 +// #def IRQ_PRI_SYSTICK 0 #define IRQ_PRI_UART 1 #define IRQ_PRI_SDIO 1 #define IRQ_PRI_DMA 1 @@ -120,7 +120,7 @@ MP_DECLARE_CONST_FUN_OBJ_0(pyb_irq_stats_obj); #else -//#def IRQ_PRI_SYSTICK NVIC_EncodePriority(NVIC_PRIORITYGROUP_4, 0, 0) +// #def IRQ_PRI_SYSTICK NVIC_EncodePriority(NVIC_PRIORITYGROUP_4, 0, 0) // The UARTs have no FIFOs, so if they don't get serviced quickly then characters // get dropped. The handling for each character only consumes about 0.5 usec diff --git a/ports/stm32/lcd.c b/ports/stm32/lcd.c index b35bd3bbdb..331c50dd95 100644 --- a/ports/stm32/lcd.c +++ b/ports/stm32/lcd.c @@ -236,14 +236,23 @@ STATIC mp_obj_t pyb_lcd_make_new(const mp_obj_type_t *type, size_t n_args, size_ spi_clock = HAL_RCC_GetPCLK1Freq(); } uint br_prescale = spi_clock / 16000000; // datasheet says LCD can run at 20MHz, but we go for 16MHz - if (br_prescale <= 2) { init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_2; } - else if (br_prescale <= 4) { init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_4; } - else if (br_prescale <= 8) { init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_8; } - else if (br_prescale <= 16) { init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_16; } - else if (br_prescale <= 32) { init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_32; } - else if (br_prescale <= 64) { init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_64; } - else if (br_prescale <= 128) { init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_128; } - else { init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_256; } + if (br_prescale <= 2) { + init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_2; + } else if (br_prescale <= 4) { + init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_4; + } else if (br_prescale <= 8) { + init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_8; + } else if (br_prescale <= 16) { + init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_16; + } else if (br_prescale <= 32) { + init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_32; + } else if (br_prescale <= 64) { + init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_64; + } else if (br_prescale <= 128) { + init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_128; + } else { + init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_256; + } // data is sent bigendian, latches on rising clock init->CLKPolarity = SPI_POLARITY_HIGH; @@ -328,7 +337,7 @@ STATIC mp_obj_t pyb_lcd_command(mp_obj_t self_in, mp_obj_t instr_data_in, mp_obj // send the data for (uint i = 0; i < bufinfo.len; i++) { - lcd_out(self, instr_data, ((byte*)bufinfo.buf)[i]); + lcd_out(self, instr_data, ((byte *)bufinfo.buf)[i]); } return mp_const_none; @@ -452,7 +461,7 @@ STATIC mp_obj_t pyb_lcd_text(size_t n_args, const mp_obj_t *args) { // loop over chars for (const char *top = data + len; data < top; data++) { // get char and make sure its in range of font - uint chr = *(byte*)data; + uint chr = *(byte *)data; if (chr < 32 || chr > 127) { chr = 127; } @@ -521,7 +530,7 @@ const mp_obj_type_t pyb_lcd_type = { { &mp_type_type }, .name = MP_QSTR_LCD, .make_new = pyb_lcd_make_new, - .locals_dict = (mp_obj_dict_t*)&pyb_lcd_locals_dict, + .locals_dict = (mp_obj_dict_t *)&pyb_lcd_locals_dict, }; #endif // MICROPY_HW_HAS_LCD diff --git a/ports/stm32/led.c b/ports/stm32/led.c index be7d196cfd..b1d5cb354d 100644 --- a/ports/stm32/led.c +++ b/ports/stm32/led.c @@ -52,15 +52,15 @@ typedef struct _pyb_led_obj_t { STATIC const pyb_led_obj_t pyb_led_obj[] = { {{&pyb_led_type}, 1, MICROPY_HW_LED1}, -#if defined(MICROPY_HW_LED2) + #if defined(MICROPY_HW_LED2) {{&pyb_led_type}, 2, MICROPY_HW_LED2}, -#if defined(MICROPY_HW_LED3) + #if defined(MICROPY_HW_LED3) {{&pyb_led_type}, 3, MICROPY_HW_LED3}, -#if defined(MICROPY_HW_LED4) + #if defined(MICROPY_HW_LED4) {{&pyb_led_type}, 4, MICROPY_HW_LED4}, -#endif -#endif -#endif + #endif + #endif + #endif }; #define NUM_LEDS MP_ARRAY_SIZE(pyb_led_obj) @@ -102,7 +102,7 @@ void led_init(void) { #define LED_PWM_TIM_PERIOD (10000) // TIM runs at 1MHz and fires every 10ms // this gives the address of the CCR register for channels 1-4 -#define LED_PWM_CCR(pwm_cfg) ((volatile uint32_t*)&(pwm_cfg)->tim->CCR1 + ((pwm_cfg)->tim_channel >> 2)) +#define LED_PWM_CCR(pwm_cfg) ((volatile uint32_t *)&(pwm_cfg)->tim->CCR1 + ((pwm_cfg)->tim_channel >> 2)) typedef struct _led_pwm_config_t { TIM_TypeDef *tim; @@ -135,10 +135,17 @@ STATIC void led_pwm_init(int led) { // TIM configuration switch (pwm_cfg->tim_id) { - case 1: __TIM1_CLK_ENABLE(); break; - case 2: __TIM2_CLK_ENABLE(); break; - case 3: __TIM3_CLK_ENABLE(); break; - default: assert(0); + case 1: + __TIM1_CLK_ENABLE(); + break; + case 2: + __TIM2_CLK_ENABLE(); + break; + case 3: + __TIM3_CLK_ENABLE(); + break; + default: + assert(0); } TIM_HandleTypeDef tim = {0}; tim.Instance = pwm_cfg->tim; @@ -187,7 +194,7 @@ void led_state(pyb_led_t led, int state) { } const pin_obj_t *led_pin = pyb_led_obj[led - 1].led_pin; - //printf("led_state(%d,%d)\n", led, state); + // printf("led_state(%d,%d)\n", led, state); if (state == 0) { // turn LED off MICROPY_HW_LED_OFF(led_pin); @@ -361,7 +368,7 @@ const mp_obj_type_t pyb_led_type = { .name = MP_QSTR_LED, .print = led_obj_print, .make_new = led_obj_make_new, - .locals_dict = (mp_obj_dict_t*)&led_locals_dict, + .locals_dict = (mp_obj_dict_t *)&led_locals_dict, }; #else diff --git a/ports/stm32/machine_i2c.c b/ports/stm32/machine_i2c.c index b7a9ea69bf..3836162a86 100644 --- a/ports/stm32/machine_i2c.c +++ b/ports/stm32/machine_i2c.c @@ -226,7 +226,7 @@ mp_obj_t machine_hard_i2c_make_new(const mp_obj_type_t *type, size_t n_args, siz } // get static peripheral object - machine_hard_i2c_obj_t *self = (machine_hard_i2c_obj_t*)&machine_hard_i2c_obj[i2c_id - 1]; + machine_hard_i2c_obj_t *self = (machine_hard_i2c_obj_t *)&machine_hard_i2c_obj[i2c_id - 1]; // here we would check the scl/sda pins and configure them, but it's not implemented if (args[ARG_scl].u_obj != MP_OBJ_NULL || args[ARG_sda].u_obj != MP_OBJ_NULL) { @@ -250,7 +250,7 @@ STATIC const mp_obj_type_t machine_hard_i2c_type = { .print = machine_hard_i2c_print, .make_new = machine_hard_i2c_make_new, .protocol = &machine_hard_i2c_p, - .locals_dict = (mp_obj_dict_t*)&mp_machine_soft_i2c_locals_dict, + .locals_dict = (mp_obj_dict_t *)&mp_machine_soft_i2c_locals_dict, }; #endif // MICROPY_HW_ENABLE_HW_I2C diff --git a/ports/stm32/machine_spi.c b/ports/stm32/machine_spi.c index dedcafc8bf..d012d70a08 100644 --- a/ports/stm32/machine_spi.c +++ b/ports/stm32/machine_spi.c @@ -95,7 +95,7 @@ mp_obj_t machine_hard_spi_make_new(const mp_obj_type_t *type, size_t n_args, siz } STATIC void machine_hard_spi_init(mp_obj_base_t *self_in, size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { - machine_hard_spi_obj_t *self = (machine_hard_spi_obj_t*)self_in; + machine_hard_spi_obj_t *self = (machine_hard_spi_obj_t *)self_in; enum { ARG_baudrate, ARG_polarity, ARG_phase, ARG_bits, ARG_firstbit }; static const mp_arg_t allowed_args[] = { @@ -118,12 +118,12 @@ STATIC void machine_hard_spi_init(mp_obj_base_t *self_in, size_t n_args, const m } STATIC void machine_hard_spi_deinit(mp_obj_base_t *self_in) { - machine_hard_spi_obj_t *self = (machine_hard_spi_obj_t*)self_in; + machine_hard_spi_obj_t *self = (machine_hard_spi_obj_t *)self_in; spi_deinit(self->spi); } STATIC void machine_hard_spi_transfer(mp_obj_base_t *self_in, size_t len, const uint8_t *src, uint8_t *dest) { - machine_hard_spi_obj_t *self = (machine_hard_spi_obj_t*)self_in; + machine_hard_spi_obj_t *self = (machine_hard_spi_obj_t *)self_in; spi_transfer(self->spi, len, src, dest, SPI_TRANSFER_TIMEOUT(len)); } @@ -139,5 +139,5 @@ const mp_obj_type_t machine_hard_spi_type = { .print = machine_hard_spi_print, .make_new = mp_machine_spi_make_new, // delegate to master constructor .protocol = &machine_hard_spi_p, - .locals_dict = (mp_obj_dict_t*)&mp_machine_spi_locals_dict, + .locals_dict = (mp_obj_dict_t *)&mp_machine_spi_locals_dict, }; diff --git a/ports/stm32/machine_uart.c b/ports/stm32/machine_uart.c index c453960467..1aea9f67f6 100644 --- a/ports/stm32/machine_uart.c +++ b/ports/stm32/machine_uart.c @@ -188,7 +188,7 @@ STATIC void pyb_uart_print(const mp_print_t *print, mp_obj_t self_in, mp_print_k if (cr3 & USART_CR3_RTSE) { mp_print_str(print, "RTS"); if (cr3 & USART_CR3_CTSE) { - mp_print_str(print, "|"); + mp_print_str(print, "|"); } } if (cr3 & USART_CR3_CTSE) { @@ -235,7 +235,7 @@ STATIC mp_obj_t pyb_uart_init_helper(pyb_uart_obj_t *self, size_t n_args, const mp_arg_val_t baudrate, bits, parity, stop, flow, timeout, timeout_char, rxbuf, read_buf_len; } args; mp_arg_parse_all(n_args, pos_args, kw_args, - MP_ARRAY_SIZE(allowed_args), allowed_args, (mp_arg_val_t*)&args); + MP_ARRAY_SIZE(allowed_args), allowed_args, (mp_arg_val_t *)&args); // static UARTs are used for internal purposes and shouldn't be reconfigured if (self->is_static) { @@ -272,8 +272,12 @@ STATIC mp_obj_t pyb_uart_init_helper(pyb_uart_obj_t *self, size_t n_args, const // stop bits uint32_t stop; switch (args.stop.u_int) { - case 1: stop = UART_STOPBITS_1; break; - default: stop = UART_STOPBITS_2; break; + case 1: + stop = UART_STOPBITS_1; + break; + default: + stop = UART_STOPBITS_2; + break; } // flow control @@ -588,7 +592,7 @@ STATIC mp_uint_t pyb_uart_read(mp_obj_t self_in, void *buf_in, mp_uint_t size, i for (;;) { int data = uart_rx_char(self); if (self->char_width == CHAR_WIDTH_9BIT) { - *(uint16_t*)buf = data; + *(uint16_t *)buf = data; buf += 2; } else { *buf++ = data; @@ -661,5 +665,5 @@ const mp_obj_type_t pyb_uart_type = { .getiter = mp_identity_getiter, .iternext = mp_stream_unbuffered_iter, .protocol = &uart_stream_p, - .locals_dict = (mp_obj_dict_t*)&pyb_uart_locals_dict, + .locals_dict = (mp_obj_dict_t *)&pyb_uart_locals_dict, }; diff --git a/ports/stm32/main.c b/ports/stm32/main.c index 5d6cbf236e..f9f4349a53 100644 --- a/ports/stm32/main.c +++ b/ports/stm32/main.c @@ -138,20 +138,20 @@ MP_DEFINE_CONST_FUN_OBJ_KW(pyb_main_obj, 1, pyb_main); #if MICROPY_HW_ENABLE_STORAGE static const char fresh_boot_py[] = -"# boot.py -- run on boot-up\r\n" -"# can run arbitrary Python, but best to keep it minimal\r\n" -"\r\n" -"import machine\r\n" -"import pyb\r\n" -"#pyb.main('main.py') # main script to run after this one\r\n" + "# boot.py -- run on boot-up\r\n" + "# can run arbitrary Python, but best to keep it minimal\r\n" + "\r\n" + "import machine\r\n" + "import pyb\r\n" + "#pyb.main('main.py') # main script to run after this one\r\n" #if MICROPY_HW_ENABLE_USB -"#pyb.usb_mode('VCP+MSC') # act as a serial and a storage device\r\n" -"#pyb.usb_mode('VCP+HID') # act as a serial device and a mouse\r\n" + "#pyb.usb_mode('VCP+MSC') # act as a serial and a storage device\r\n" + "#pyb.usb_mode('VCP+HID') # act as a serial device and a mouse\r\n" #endif ; static const char fresh_main_py[] = -"# main.py -- put your code here!\r\n" + "# main.py -- put your code here!\r\n" ; static const char fresh_pybcdc_inf[] = @@ -159,18 +159,18 @@ static const char fresh_pybcdc_inf[] = ; static const char fresh_readme_txt[] = -"This is a MicroPython board\r\n" -"\r\n" -"You can get started right away by writing your Python code in 'main.py'.\r\n" -"\r\n" -"For a serial prompt:\r\n" -" - Windows: you need to go to 'Device manager', right click on the unknown device,\r\n" -" then update the driver software, using the 'pybcdc.inf' file found on this drive.\r\n" -" Then use a terminal program like Hyperterminal or putty.\r\n" -" - Mac OS X: use the command: screen /dev/tty.usbmodem*\r\n" -" - Linux: use the command: screen /dev/ttyACM0\r\n" -"\r\n" -"Please visit http://micropython.org/help/ for further help.\r\n" + "This is a MicroPython board\r\n" + "\r\n" + "You can get started right away by writing your Python code in 'main.py'.\r\n" + "\r\n" + "For a serial prompt:\r\n" + " - Windows: you need to go to 'Device manager', right click on the unknown device,\r\n" + " then update the driver software, using the 'pybcdc.inf' file found on this drive.\r\n" + " Then use a terminal program like Hyperterminal or putty.\r\n" + " - Mac OS X: use the command: screen /dev/tty.usbmodem*\r\n" + " - Linux: use the command: screen /dev/ttyACM0\r\n" + "\r\n" + "Please visit http://micropython.org/help/ for further help.\r\n" ; // avoid inlining to avoid stack usage within main() @@ -483,20 +483,20 @@ void stm32_main(uint32_t reset_mode) { __HAL_RCC_GPIOD_CLK_ENABLE(); #endif - #if defined(STM32F4) || defined(STM32F7) - #if defined(__HAL_RCC_DTCMRAMEN_CLK_ENABLE) - // The STM32F746 doesn't really have CCM memory, but it does have DTCM, - // which behaves more or less like normal SRAM. - __HAL_RCC_DTCMRAMEN_CLK_ENABLE(); - #elif defined(CCMDATARAM_BASE) - // enable the CCM RAM - __HAL_RCC_CCMDATARAMEN_CLK_ENABLE(); - #endif + #if defined(STM32F4) || defined(STM32F7) + #if defined(__HAL_RCC_DTCMRAMEN_CLK_ENABLE) + // The STM32F746 doesn't really have CCM memory, but it does have DTCM, + // which behaves more or less like normal SRAM. + __HAL_RCC_DTCMRAMEN_CLK_ENABLE(); + #elif defined(CCMDATARAM_BASE) + // enable the CCM RAM + __HAL_RCC_CCMDATARAMEN_CLK_ENABLE(); + #endif #elif defined(STM32H7) - // Enable D2 SRAM1/2/3 clocks. - __HAL_RCC_D2SRAM1_CLK_ENABLE(); - __HAL_RCC_D2SRAM2_CLK_ENABLE(); - __HAL_RCC_D2SRAM3_CLK_ENABLE(); + // Enable D2 SRAM1/2/3 clocks. + __HAL_RCC_D2SRAM1_CLK_ENABLE(); + __HAL_RCC_D2SRAM2_CLK_ENABLE(); + __HAL_RCC_D2SRAM3_CLK_ENABLE(); #endif @@ -567,7 +567,7 @@ soft_reset: // to recover from limit hit. (Limit is measured in bytes.) // Note: stack control relies on main thread being initialised above mp_stack_set_top(&_estack); - mp_stack_set_limit((char*)&_estack - (char*)&_heap_end - 1024); + mp_stack_set_limit((char *)&_estack - (char *)&_heap_end - 1024); // GC init gc_init(MICROPY_HEAP_START, MICROPY_HEAP_END); diff --git a/ports/stm32/make-stmconst.py b/ports/stm32/make-stmconst.py index d509d00c1c..4b209f4b36 100644 --- a/ports/stm32/make-stmconst.py +++ b/ports/stm32/make-stmconst.py @@ -11,16 +11,23 @@ import re # Python 2/3 compatibility import platform -if platform.python_version_tuple()[0] == '2': + +if platform.python_version_tuple()[0] == "2": + def convert_bytes_to_str(b): return b -elif platform.python_version_tuple()[0] == '3': + + +elif platform.python_version_tuple()[0] == "3": + def convert_bytes_to_str(b): try: - return str(b, 'utf8') + return str(b, "utf8") except ValueError: # some files have invalid utf8 bytes, so filter them out - return ''.join(chr(l) for l in b if l <= 126) + return "".join(chr(l) for l in b if l <= 126) + + # end compatibility code # given a list of (name,regex) pairs, find the first one that matches the given line @@ -31,29 +38,62 @@ def re_match_first(regexs, line): return name, match return None, None + class LexerError(Exception): def __init__(self, line): self.line = line + class Lexer: - re_io_reg = r'__IO uint(?P8|16|32)_t +(?P[A-Z0-9]+)' - re_comment = r'(?P[A-Za-z0-9 \-/_()&]+)' - re_addr_offset = r'Address offset: (?P0x[0-9A-Z]{2,3})' + re_io_reg = r"__IO uint(?P8|16|32)_t +(?P[A-Z0-9]+)" + re_comment = r"(?P[A-Za-z0-9 \-/_()&]+)" + re_addr_offset = r"Address offset: (?P0x[0-9A-Z]{2,3})" regexs = ( - ('#define hex', re.compile(r'#define +(?P[A-Z0-9_]+) +(?:\(\(uint32_t\))?(?P0x[0-9A-F]+)U?(?:\))?($| +/\*)')), - ('#define X', re.compile(r'#define +(?P[A-Z0-9_]+) +(?P[A-Z0-9_]+)($| +/\*)')), - ('#define X+hex', re.compile(r'#define +(?P[A-Za-z0-9_]+) +\((?P[A-Z0-9_]+) \+ (?P0x[0-9A-F]+)U?\)($| +/\*)')), - ('#define typedef', re.compile(r'#define +(?P[A-Z0-9_]+(ext)?) +\(\([A-Za-z0-9_]+_TypeDef \*\) (?P[A-Za-z0-9_]+)\)($| +/\*)')), - ('typedef struct', re.compile(r'typedef struct$')), - ('{', re.compile(r'{$')), - ('}', re.compile(r'}$')), - ('} TypeDef', re.compile(r'} *(?P[A-Z][A-Za-z0-9_]+)_(?P([A-Za-z0-9_]+)?)TypeDef;$')), - ('IO reg', re.compile(re_io_reg + r'; +/\*!< ' + re_comment + r', +' + re_addr_offset + r' *\*/')), - ('IO reg array', re.compile(re_io_reg + r'\[(?P[2-8])\]; +/\*!< ' + re_comment + r', +' + re_addr_offset + r'-(0x[0-9A-Z]{2,3}) *\*/')), + ( + "#define hex", + re.compile( + r"#define +(?P[A-Z0-9_]+) +(?:\(\(uint32_t\))?(?P0x[0-9A-F]+)U?(?:\))?($| +/\*)" + ), + ), + ("#define X", re.compile(r"#define +(?P[A-Z0-9_]+) +(?P[A-Z0-9_]+)($| +/\*)")), + ( + "#define X+hex", + re.compile( + r"#define +(?P[A-Za-z0-9_]+) +\((?P[A-Z0-9_]+) \+ (?P0x[0-9A-F]+)U?\)($| +/\*)" + ), + ), + ( + "#define typedef", + re.compile( + r"#define +(?P[A-Z0-9_]+(ext)?) +\(\([A-Za-z0-9_]+_TypeDef \*\) (?P[A-Za-z0-9_]+)\)($| +/\*)" + ), + ), + ("typedef struct", re.compile(r"typedef struct$")), + ("{", re.compile(r"{$")), + ("}", re.compile(r"}$")), + ( + "} TypeDef", + re.compile(r"} *(?P[A-Z][A-Za-z0-9_]+)_(?P([A-Za-z0-9_]+)?)TypeDef;$"), + ), + ( + "IO reg", + re.compile(re_io_reg + r"; +/\*!< " + re_comment + r", +" + re_addr_offset + r" *\*/"), + ), + ( + "IO reg array", + re.compile( + re_io_reg + + r"\[(?P[2-8])\]; +/\*!< " + + re_comment + + r", +" + + re_addr_offset + + r"-(0x[0-9A-Z]{2,3}) *\*/" + ), + ), ) def __init__(self, filename): - self.file = open(filename, 'rb') + self.file = open(filename, "rb") self.line_number = 0 def next_match(self, strictly_next=False): @@ -62,7 +102,7 @@ class Lexer: line = convert_bytes_to_str(line) self.line_number += 1 if len(line) == 0: - return ('EOF', None) + return ("EOF", None) match = re_match_first(Lexer.regexs, line.strip()) if strictly_next or match[0] is not None: return match @@ -73,6 +113,7 @@ class Lexer: raise LexerError(self.line_number) return match + def parse_file(filename): lexer = Lexer(filename) @@ -81,71 +122,75 @@ def parse_file(filename): periphs = [] while True: m = lexer.next_match() - if m[0] == 'EOF': + if m[0] == "EOF": break - elif m[0] == '#define hex': + elif m[0] == "#define hex": d = m[1].groupdict() - consts[d['id']] = int(d['hex'], base=16) - elif m[0] == '#define X': + consts[d["id"]] = int(d["hex"], base=16) + elif m[0] == "#define X": d = m[1].groupdict() - if d['id2'] in consts: - consts[d['id']] = consts[d['id2']] - elif m[0] == '#define X+hex': + if d["id2"] in consts: + consts[d["id"]] = consts[d["id2"]] + elif m[0] == "#define X+hex": d = m[1].groupdict() - if d['id2'] in consts: - consts[d['id']] = consts[d['id2']] + int(d['hex'], base=16) - elif m[0] == '#define typedef': + if d["id2"] in consts: + consts[d["id"]] = consts[d["id2"]] + int(d["hex"], base=16) + elif m[0] == "#define typedef": d = m[1].groupdict() - if d['id2'] in consts: - periphs.append((d['id'], consts[d['id2']])) - elif m[0] == 'typedef struct': - lexer.must_match('{') + if d["id2"] in consts: + periphs.append((d["id"], consts[d["id2"]])) + elif m[0] == "typedef struct": + lexer.must_match("{") m = lexer.next_match() regs = [] - while m[0] in ('IO reg', 'IO reg array'): + while m[0] in ("IO reg", "IO reg array"): d = m[1].groupdict() - reg = d['reg'] - offset = int(d['offset'], base=16) - bits = int(d['bits']) - comment = d['comment'] - if m[0] == 'IO reg': + reg = d["reg"] + offset = int(d["offset"], base=16) + bits = int(d["bits"]) + comment = d["comment"] + if m[0] == "IO reg": regs.append((reg, offset, bits, comment)) else: - for i in range(int(d['array'])): + for i in range(int(d["array"])): regs.append((reg + str(i), offset + i * bits // 8, bits, comment)) m = lexer.next_match() - if m[0] == '}': + if m[0] == "}": pass - elif m[0] == '} TypeDef': - reg_defs[m[1].groupdict()['id']] = regs + elif m[0] == "} TypeDef": + reg_defs[m[1].groupdict()["id"]] = regs else: raise LexerError(lexer.line_number) return periphs, reg_defs + def print_int_obj(val, needed_mpzs): if -0x40000000 <= val < 0x40000000: - print('MP_ROM_INT(%#x)' % val, end='') + print("MP_ROM_INT(%#x)" % val, end="") else: - print('MP_ROM_PTR(&mpz_%08x)' % val, end='') + print("MP_ROM_PTR(&mpz_%08x)" % val, end="") needed_mpzs.add(val) + def print_periph(periph_name, periph_val, needed_qstrs, needed_mpzs): qstr = periph_name.upper() - print('{ MP_ROM_QSTR(MP_QSTR_%s), ' % qstr, end='') + print("{ MP_ROM_QSTR(MP_QSTR_%s), " % qstr, end="") print_int_obj(periph_val, needed_mpzs) - print(' },') + print(" },") needed_qstrs.add(qstr) + def print_regs(reg_name, reg_defs, needed_qstrs, needed_mpzs): reg_name = reg_name.upper() for r in reg_defs: - qstr = reg_name + '_' + r[0] - print('{ MP_ROM_QSTR(MP_QSTR_%s), ' % qstr, end='') + qstr = reg_name + "_" + r[0] + print("{ MP_ROM_QSTR(MP_QSTR_%s), " % qstr, end="") print_int_obj(r[1], needed_mpzs) - print(' }, // %s-bits, %s' % (r[2], r[3])) + print(" }, // %s-bits, %s" % (r[2], r[3])) needed_qstrs.add(qstr) + # This version of print regs groups registers together into submodules (eg GPIO submodule). # This makes the qstrs shorter, and makes the list of constants more manageable (since # they are not all in one big module) but it is then harder to compile the constants, and @@ -154,21 +199,28 @@ def print_regs(reg_name, reg_defs, needed_qstrs, needed_mpzs): # And for the number of constants we have, this function seems to use about the same amount # of ROM as print_regs. def print_regs_as_submodules(reg_name, reg_defs, modules, needed_qstrs): - mod_name_lower = reg_name.lower() + '_' + mod_name_lower = reg_name.lower() + "_" mod_name_upper = mod_name_lower.upper() modules.append((mod_name_lower, mod_name_upper)) - print(""" + print( + """ STATIC const mp_rom_map_elem_t stm_%s_globals_table[] = { { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_%s) }, -""" % (mod_name_lower, mod_name_upper)) +""" + % (mod_name_lower, mod_name_upper) + ) needed_qstrs.add(mod_name_upper) for r in reg_defs: - print(' { MP_ROM_QSTR(MP_QSTR_%s), MP_ROM_INT(%#x) }, // %s-bits, %s' % (r[0], r[1], r[2], r[3])) + print( + " { MP_ROM_QSTR(MP_QSTR_%s), MP_ROM_INT(%#x) }, // %s-bits, %s" + % (r[0], r[1], r[2], r[3]) + ) needed_qstrs.add(r[0]) - print("""}; + print( + """}; STATIC MP_DEFINE_CONST_DICT(stm_%s_globals, stm_%s_globals_table); @@ -177,23 +229,35 @@ const mp_obj_module_t stm_%s_obj = { .name = MP_QSTR_%s, .globals = (mp_obj_dict_t*)&stm_%s_globals, }; -""" % (mod_name_lower, mod_name_lower, mod_name_lower, mod_name_upper, mod_name_lower)) +""" + % (mod_name_lower, mod_name_lower, mod_name_lower, mod_name_upper, mod_name_lower) + ) + def main(): - cmd_parser = argparse.ArgumentParser(description='Extract ST constants from a C header file.') - cmd_parser.add_argument('file', nargs=1, help='input file') - cmd_parser.add_argument('-q', '--qstr', dest='qstr_filename', default='build/stmconst_qstr.h', - help='Specified the name of the generated qstr header file') - cmd_parser.add_argument('--mpz', dest='mpz_filename', default='build/stmconst_mpz.h', - help='the destination file of the generated mpz header') + cmd_parser = argparse.ArgumentParser(description="Extract ST constants from a C header file.") + cmd_parser.add_argument("file", nargs=1, help="input file") + cmd_parser.add_argument( + "-q", + "--qstr", + dest="qstr_filename", + default="build/stmconst_qstr.h", + help="Specified the name of the generated qstr header file", + ) + cmd_parser.add_argument( + "--mpz", + dest="mpz_filename", + default="build/stmconst_mpz.h", + help="the destination file of the generated mpz header", + ) args = cmd_parser.parse_args() periphs, reg_defs = parse_file(args.file[0]) # add legacy GPIO constants that were removed when upgrading CMSIS - if 'GPIO' in reg_defs and 'stm32f4' in args.file[0]: - reg_defs['GPIO'].append(['BSRRL', 0x18, 16, 'legacy register']) - reg_defs['GPIO'].append(['BSRRH', 0x1a, 16, 'legacy register']) + if "GPIO" in reg_defs and "stm32f4" in args.file[0]: + reg_defs["GPIO"].append(["BSRRL", 0x18, 16, "legacy register"]) + reg_defs["GPIO"].append(["BSRRH", 0x1A, 16, "legacy register"]) modules = [] needed_qstrs = set() @@ -206,55 +270,60 @@ def main(): print_periph(periph_name, periph_val, needed_qstrs, needed_mpzs) for reg in ( - 'ADC', + "ADC", #'ADC_Common', #'CAN_TxMailBox', #'CAN_FIFOMailBox', #'CAN_FilterRegister', #'CAN', - 'CRC', - 'DAC', - 'DBGMCU', - 'DMA_Stream', - 'DMA', - 'EXTI', - 'FLASH', - 'GPIO', - 'SYSCFG', - 'I2C', - 'IWDG', - 'PWR', - 'RCC', - 'RTC', + "CRC", + "DAC", + "DBGMCU", + "DMA_Stream", + "DMA", + "EXTI", + "FLASH", + "GPIO", + "SYSCFG", + "I2C", + "IWDG", + "PWR", + "RCC", + "RTC", #'SDIO', - 'SPI', - 'TIM', - 'USART', - 'WWDG', - 'RNG', - ): + "SPI", + "TIM", + "USART", + "WWDG", + "RNG", + ): if reg in reg_defs: print_regs(reg, reg_defs[reg], needed_qstrs, needed_mpzs) - #print_regs_as_submodules(reg, reg_defs[reg], modules, needed_qstrs) + # print_regs_as_submodules(reg, reg_defs[reg], modules, needed_qstrs) - #print("#define MOD_STM_CONST_MODULES \\") - #for mod_lower, mod_upper in modules: + # print("#define MOD_STM_CONST_MODULES \\") + # for mod_lower, mod_upper in modules: # print(" { MP_ROM_QSTR(MP_QSTR_%s), MP_ROM_PTR(&stm_%s_obj) }, \\" % (mod_upper, mod_lower)) print("") - with open(args.qstr_filename, 'wt') as qstr_file: - print('#if MICROPY_PY_STM', file=qstr_file) + with open(args.qstr_filename, "wt") as qstr_file: + print("#if MICROPY_PY_STM", file=qstr_file) for qstr in sorted(needed_qstrs): - print('Q({})'.format(qstr), file=qstr_file) - print('#endif // MICROPY_PY_STM', file=qstr_file) + print("Q({})".format(qstr), file=qstr_file) + print("#endif // MICROPY_PY_STM", file=qstr_file) - with open(args.mpz_filename, 'wt') as mpz_file: + with open(args.mpz_filename, "wt") as mpz_file: for mpz in sorted(needed_mpzs): - assert 0 <= mpz <= 0xffffffff - print('STATIC const mp_obj_int_t mpz_%08x = {{&mp_type_int}, ' - '{.neg=0, .fixed_dig=1, .alloc=2, .len=2, ' '.dig=(uint16_t*)(const uint16_t[]){%#x, %#x}}};' - % (mpz, mpz & 0xffff, (mpz >> 16) & 0xffff), file=mpz_file) + assert 0 <= mpz <= 0xFFFFFFFF + print( + "STATIC const mp_obj_int_t mpz_%08x = {{&mp_type_int}, " + "{.neg=0, .fixed_dig=1, .alloc=2, .len=2, " + ".dig=(uint16_t*)(const uint16_t[]){%#x, %#x}}};" + % (mpz, mpz & 0xFFFF, (mpz >> 16) & 0xFFFF), + file=mpz_file, + ) + if __name__ == "__main__": main() diff --git a/ports/stm32/modmachine.c b/ports/stm32/modmachine.c index 06c07812c0..6c9f22f98b 100644 --- a/ports/stm32/modmachine.c +++ b/ports/stm32/modmachine.c @@ -118,10 +118,10 @@ void machine_init(void) { if (state & RCC_SR_IWDGRSTF || state & RCC_SR_WWDGRSTF) { reset_cause = PYB_RESET_WDT; } else if (state & RCC_SR_PORRSTF - #if !defined(STM32F0) - || state & RCC_SR_BORRSTF - #endif - ) { + #if !defined(STM32F0) + || state & RCC_SR_BORRSTF + #endif + ) { reset_cause = PYB_RESET_POWER_ON; } else if (state & RCC_SR_PINRSTF) { reset_cause = PYB_RESET_HARD; @@ -144,7 +144,7 @@ void machine_deinit(void) { STATIC mp_obj_t machine_info(size_t n_args, const mp_obj_t *args) { // get and print unique id; 96 bits { - byte *id = (byte*)MP_HAL_UNIQUE_ID_ADDRESS; + byte *id = (byte *)MP_HAL_UNIQUE_ID_ADDRESS; printf("ID=%02x%02x%02x%02x:%02x%02x%02x%02x:%02x%02x%02x%02x\n", id[0], id[1], id[2], id[3], id[4], id[5], id[6], id[7], id[8], id[9], id[10], id[11]); } @@ -153,15 +153,15 @@ STATIC mp_obj_t machine_info(size_t n_args, const mp_obj_t *args) { { #if defined(STM32F0) printf("S=%u\nH=%u\nP1=%u\n", - (unsigned int)HAL_RCC_GetSysClockFreq(), - (unsigned int)HAL_RCC_GetHCLKFreq(), - (unsigned int)HAL_RCC_GetPCLK1Freq()); + (unsigned int)HAL_RCC_GetSysClockFreq(), + (unsigned int)HAL_RCC_GetHCLKFreq(), + (unsigned int)HAL_RCC_GetPCLK1Freq()); #else printf("S=%u\nH=%u\nP1=%u\nP2=%u\n", - (unsigned int)HAL_RCC_GetSysClockFreq(), - (unsigned int)HAL_RCC_GetHCLKFreq(), - (unsigned int)HAL_RCC_GetPCLK1Freq(), - (unsigned int)HAL_RCC_GetPCLK2Freq()); + (unsigned int)HAL_RCC_GetSysClockFreq(), + (unsigned int)HAL_RCC_GetHCLKFreq(), + (unsigned int)HAL_RCC_GetPCLK1Freq(), + (unsigned int)HAL_RCC_GetPCLK2Freq()); #endif } @@ -228,7 +228,7 @@ MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(machine_info_obj, 0, 1, machine_info); // Returns a string of 12 bytes (96 bits), which is the unique ID for the MCU. STATIC mp_obj_t machine_unique_id(void) { - byte *id = (byte*)MP_HAL_UNIQUE_ID_ADDRESS; + byte *id = (byte *)MP_HAL_UNIQUE_ID_ADDRESS; return mp_obj_new_bytes(id, 12); } MP_DEFINE_CONST_FUN_OBJ_0(machine_unique_id_obj, machine_unique_id); @@ -263,25 +263,27 @@ STATIC NORETURN mp_obj_t machine_bootloader(void) { HAL_MPU_Disable(); #endif -#if defined(STM32F7) || defined(STM32H7) + #if defined(STM32F7) || defined(STM32H7) // arm-none-eabi-gcc 4.9.0 does not correctly inline this // MSP function, so we write it out explicitly here. - //__set_MSP(*((uint32_t*) 0x1FF00000)); + // __set_MSP(*((uint32_t*) 0x1FF00000)); __ASM volatile ("movw r3, #0x0000\nmovt r3, #0x1FF0\nldr r3, [r3, #0]\nMSR msp, r3\n" : : : "r3", "sp"); - ((void (*)(void)) *((uint32_t*) 0x1FF00004))(); -#else + ((void (*)(void)) * ((uint32_t *)0x1FF00004))(); + #else __HAL_SYSCFG_REMAPMEMORY_SYSTEMFLASH(); // arm-none-eabi-gcc 4.9.0 does not correctly inline this // MSP function, so we write it out explicitly here. - //__set_MSP(*((uint32_t*) 0x00000000)); + // __set_MSP(*((uint32_t*) 0x00000000)); __ASM volatile ("movs r3, #0\nldr r3, [r3, #0]\nMSR msp, r3\n" : : : "r3", "sp"); - ((void (*)(void)) *((uint32_t*) 0x00000004))(); -#endif + ((void (*)(void)) * ((uint32_t *)0x00000004))(); + #endif - while (1); + while (1) { + ; + } } MP_DEFINE_CONST_FUN_OBJ_0(machine_bootloader_obj, machine_bootloader); @@ -290,12 +292,12 @@ STATIC mp_obj_t machine_freq(size_t n_args, const mp_obj_t *args) { if (n_args == 0) { // get mp_obj_t tuple[] = { - mp_obj_new_int(HAL_RCC_GetSysClockFreq()), - mp_obj_new_int(HAL_RCC_GetHCLKFreq()), - mp_obj_new_int(HAL_RCC_GetPCLK1Freq()), - #if !defined(STM32F0) - mp_obj_new_int(HAL_RCC_GetPCLK2Freq()), - #endif + mp_obj_new_int(HAL_RCC_GetSysClockFreq()), + mp_obj_new_int(HAL_RCC_GetHCLKFreq()), + mp_obj_new_int(HAL_RCC_GetPCLK1Freq()), + #if !defined(STM32F0) + mp_obj_new_int(HAL_RCC_GetPCLK2Freq()), + #endif }; return mp_obj_new_tuple(MP_ARRAY_SIZE(tuple), tuple); } else { @@ -354,16 +356,16 @@ STATIC const mp_rom_map_elem_t machine_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_soft_reset), MP_ROM_PTR(&machine_soft_reset_obj) }, { MP_ROM_QSTR(MP_QSTR_bootloader), MP_ROM_PTR(&machine_bootloader_obj) }, { MP_ROM_QSTR(MP_QSTR_freq), MP_ROM_PTR(&machine_freq_obj) }, -#if MICROPY_HW_ENABLE_RNG + #if MICROPY_HW_ENABLE_RNG { MP_ROM_QSTR(MP_QSTR_rng), MP_ROM_PTR(&pyb_rng_get_obj) }, -#endif + #endif { MP_ROM_QSTR(MP_QSTR_idle), MP_ROM_PTR(&pyb_wfi_obj) }, { MP_ROM_QSTR(MP_QSTR_sleep), MP_ROM_PTR(&machine_sleep_obj) }, { MP_ROM_QSTR(MP_QSTR_deepsleep), MP_ROM_PTR(&machine_deepsleep_obj) }, { MP_ROM_QSTR(MP_QSTR_reset_cause), MP_ROM_PTR(&machine_reset_cause_obj) }, -#if 0 + #if 0 { MP_ROM_QSTR(MP_QSTR_wake_reason), MP_ROM_PTR(&machine_wake_reason_obj) }, -#endif + #endif { MP_ROM_QSTR(MP_QSTR_disable_irq), MP_ROM_PTR(&pyb_disable_irq_obj) }, { MP_ROM_QSTR(MP_QSTR_enable_irq), MP_ROM_PTR(&pyb_enable_irq_obj) }, @@ -377,17 +379,17 @@ STATIC const mp_rom_map_elem_t machine_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_Pin), MP_ROM_PTR(&pin_type) }, { MP_ROM_QSTR(MP_QSTR_Signal), MP_ROM_PTR(&machine_signal_type) }, -#if 0 + #if 0 { MP_ROM_QSTR(MP_QSTR_RTC), MP_ROM_PTR(&pyb_rtc_type) }, { MP_ROM_QSTR(MP_QSTR_ADC), MP_ROM_PTR(&pyb_adc_type) }, -#endif -#if MICROPY_PY_MACHINE_I2C + #endif + #if MICROPY_PY_MACHINE_I2C { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&machine_i2c_type) }, -#endif + #endif { MP_ROM_QSTR(MP_QSTR_SPI), MP_ROM_PTR(&machine_hard_spi_type) }, { MP_ROM_QSTR(MP_QSTR_UART), MP_ROM_PTR(&pyb_uart_type) }, { MP_ROM_QSTR(MP_QSTR_WDT), MP_ROM_PTR(&pyb_wdt_type) }, -#if 0 + #if 0 { MP_ROM_QSTR(MP_QSTR_Timer), MP_ROM_PTR(&pyb_timer_type) }, { MP_ROM_QSTR(MP_QSTR_HeartBeat), MP_ROM_PTR(&pyb_heartbeat_type) }, { MP_ROM_QSTR(MP_QSTR_SD), MP_ROM_PTR(&pyb_sd_type) }, @@ -396,23 +398,23 @@ STATIC const mp_rom_map_elem_t machine_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_IDLE), MP_ROM_INT(PYB_PWR_MODE_ACTIVE) }, { MP_ROM_QSTR(MP_QSTR_SLEEP), MP_ROM_INT(PYB_PWR_MODE_LPDS) }, { MP_ROM_QSTR(MP_QSTR_DEEPSLEEP), MP_ROM_INT(PYB_PWR_MODE_HIBERNATE) }, -#endif + #endif { MP_ROM_QSTR(MP_QSTR_PWRON_RESET), MP_ROM_INT(PYB_RESET_POWER_ON) }, { MP_ROM_QSTR(MP_QSTR_HARD_RESET), MP_ROM_INT(PYB_RESET_HARD) }, { MP_ROM_QSTR(MP_QSTR_WDT_RESET), MP_ROM_INT(PYB_RESET_WDT) }, { MP_ROM_QSTR(MP_QSTR_DEEPSLEEP_RESET), MP_ROM_INT(PYB_RESET_DEEPSLEEP) }, { MP_ROM_QSTR(MP_QSTR_SOFT_RESET), MP_ROM_INT(PYB_RESET_SOFT) }, -#if 0 + #if 0 { MP_ROM_QSTR(MP_QSTR_WLAN_WAKE), MP_ROM_INT(PYB_SLP_WAKED_BY_WLAN) }, { MP_ROM_QSTR(MP_QSTR_PIN_WAKE), MP_ROM_INT(PYB_SLP_WAKED_BY_GPIO) }, { MP_ROM_QSTR(MP_QSTR_RTC_WAKE), MP_ROM_INT(PYB_SLP_WAKED_BY_RTC) }, -#endif + #endif }; STATIC MP_DEFINE_CONST_DICT(machine_module_globals, machine_module_globals_table); const mp_obj_module_t machine_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&machine_module_globals, + .globals = (mp_obj_dict_t *)&machine_module_globals, }; diff --git a/ports/stm32/modnetwork.c b/ports/stm32/modnetwork.c index dea23b4051..cd89240ebb 100644 --- a/ports/stm32/modnetwork.c +++ b/ports/stm32/modnetwork.c @@ -88,7 +88,7 @@ mp_obj_t mod_network_find_nic(const uint8_t *ip) { for (mp_uint_t i = 0; i < MP_STATE_PORT(mod_network_nic_list).len; i++) { mp_obj_t nic = MP_STATE_PORT(mod_network_nic_list).items[i]; // TODO check IP suitability here - //mod_network_nic_type_t *nic_type = (mod_network_nic_type_t*)mp_obj_get_type(nic); + // mod_network_nic_type_t *nic_type = (mod_network_nic_type_t*)mp_obj_get_type(nic); return nic; } @@ -117,7 +117,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_network_globals, mp_module_network_globals const mp_obj_module_t mp_module_network = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_network_globals, + .globals = (mp_obj_dict_t *)&mp_module_network_globals, }; /*******************************************************************************/ @@ -130,10 +130,10 @@ mp_obj_t mod_network_nic_ifconfig(struct netif *netif, size_t n_args, const mp_o // Get IP addresses const ip_addr_t *dns = dns_getserver(0); mp_obj_t tuple[4] = { - netutils_format_ipv4_addr((uint8_t*)&netif->ip_addr, NETUTILS_BIG), - netutils_format_ipv4_addr((uint8_t*)&netif->netmask, NETUTILS_BIG), - netutils_format_ipv4_addr((uint8_t*)&netif->gw, NETUTILS_BIG), - netutils_format_ipv4_addr((uint8_t*)dns, NETUTILS_BIG), + netutils_format_ipv4_addr((uint8_t *)&netif->ip_addr, NETUTILS_BIG), + netutils_format_ipv4_addr((uint8_t *)&netif->netmask, NETUTILS_BIG), + netutils_format_ipv4_addr((uint8_t *)&netif->gw, NETUTILS_BIG), + netutils_format_ipv4_addr((uint8_t *)dns, NETUTILS_BIG), }; return mp_obj_new_tuple(4, tuple); } else if (args[0] == MP_OBJ_NEW_QSTR(MP_QSTR_dhcp)) { @@ -162,11 +162,11 @@ mp_obj_t mod_network_nic_ifconfig(struct netif *netif, size_t n_args, const mp_o // Set static IP addresses mp_obj_t *items; mp_obj_get_array_fixed_n(args[0], 4, &items); - netutils_parse_ipv4_addr(items[0], (uint8_t*)&netif->ip_addr, NETUTILS_BIG); - netutils_parse_ipv4_addr(items[1], (uint8_t*)&netif->netmask, NETUTILS_BIG); - netutils_parse_ipv4_addr(items[2], (uint8_t*)&netif->gw, NETUTILS_BIG); + netutils_parse_ipv4_addr(items[0], (uint8_t *)&netif->ip_addr, NETUTILS_BIG); + netutils_parse_ipv4_addr(items[1], (uint8_t *)&netif->netmask, NETUTILS_BIG); + netutils_parse_ipv4_addr(items[2], (uint8_t *)&netif->gw, NETUTILS_BIG); ip_addr_t dns; - netutils_parse_ipv4_addr(items[3], (uint8_t*)&dns, NETUTILS_BIG); + netutils_parse_ipv4_addr(items[3], (uint8_t *)&dns, NETUTILS_BIG); dns_setserver(0, &dns); return mp_const_none; } diff --git a/ports/stm32/modnwcc3k.c b/ports/stm32/modnwcc3k.c index 8723994f45..d7923ca537 100644 --- a/ports/stm32/modnwcc3k.c +++ b/ports/stm32/modnwcc3k.c @@ -52,8 +52,8 @@ #include "patch_prog.h" #define MAX_ADDRSTRLEN (128) -#define MAX_RX_PACKET (CC3000_RX_BUFFER_SIZE-CC3000_MINIMAL_RX_SIZE-1) -#define MAX_TX_PACKET (CC3000_TX_BUFFER_SIZE-CC3000_MINIMAL_TX_SIZE-1) +#define MAX_RX_PACKET (CC3000_RX_BUFFER_SIZE - CC3000_MINIMAL_RX_SIZE - 1) +#define MAX_TX_PACKET (CC3000_TX_BUFFER_SIZE - CC3000_MINIMAL_TX_SIZE - 1) #define MAKE_SOCKADDR(addr, ip, port) \ sockaddr addr; \ @@ -115,7 +115,7 @@ STATIC void cc3k_callback(long event_type, char *data, unsigned char length) { STATIC int cc3k_gethostbyname(mp_obj_t nic, const char *name, mp_uint_t len, uint8_t *out_ip) { uint32_t ip; // CC3000 gethostbyname is unreliable and usually returns -95 on first call - for (int retry = 5; CC3000_EXPORT(gethostbyname)((char*)name, len, &ip) < 0; retry--) { + for (int retry = 5; CC3000_EXPORT(gethostbyname)((char *)name, len, &ip) < 0; retry--) { if (retry == 0 || CC3000_EXPORT(errno) != -95) { return CC3000_EXPORT(errno); } @@ -143,10 +143,18 @@ STATIC int cc3k_socket_socket(mod_network_socket_obj_t *socket, int *_errno) { mp_uint_t type; switch (socket->u_param.type) { - case MOD_NETWORK_SOCK_STREAM: type = SOCK_STREAM; break; - case MOD_NETWORK_SOCK_DGRAM: type = SOCK_DGRAM; break; - case MOD_NETWORK_SOCK_RAW: type = SOCK_RAW; break; - default: *_errno = MP_EINVAL; return -1; + case MOD_NETWORK_SOCK_STREAM: + type = SOCK_STREAM; + break; + case MOD_NETWORK_SOCK_DGRAM: + type = SOCK_DGRAM; + break; + case MOD_NETWORK_SOCK_RAW: + type = SOCK_RAW; + break; + default: + *_errno = MP_EINVAL; + return -1; } // open socket @@ -215,7 +223,7 @@ STATIC int cc3k_socket_accept(mod_network_socket_obj_t *socket, mod_network_sock // return ip and port // it seems CC3000 returns little endian for accept?? - //UNPACK_SOCKADDR(addr, ip, *port); + // UNPACK_SOCKADDR(addr, ip, *port); *port = (addr.sa_data[1] << 8) | addr.sa_data[0]; ip[3] = addr.sa_data[2]; ip[2] = addr.sa_data[3]; @@ -247,7 +255,7 @@ STATIC mp_uint_t cc3k_socket_send(mod_network_socket_obj_t *socket, const byte * mp_int_t bytes = 0; while (bytes < len) { int n = MIN((len - bytes), MAX_TX_PACKET); - n = CC3000_EXPORT(send)(socket->u_state, (uint8_t*)buf + bytes, n, 0); + n = CC3000_EXPORT(send)(socket->u_state, (uint8_t *)buf + bytes, n, 0); if (n <= 0) { *_errno = CC3000_EXPORT(errno); return -1; @@ -291,7 +299,7 @@ STATIC mp_uint_t cc3k_socket_recv(mod_network_socket_obj_t *socket, byte *buf, m STATIC mp_uint_t cc3k_socket_sendto(mod_network_socket_obj_t *socket, const byte *buf, mp_uint_t len, byte *ip, mp_uint_t port, int *_errno) { MAKE_SOCKADDR(addr, ip, port) - int ret = CC3000_EXPORT(sendto)(socket->u_state, (byte*)buf, len, 0, (sockaddr*)&addr, sizeof(addr)); + int ret = CC3000_EXPORT(sendto)(socket->u_state, (byte *)buf, len, 0, (sockaddr *)&addr, sizeof(addr)); if (ret < 0) { *_errno = CC3000_EXPORT(errno); return -1; @@ -416,7 +424,7 @@ typedef struct _cc3k_obj_t { mp_obj_base_t base; } cc3k_obj_t; -STATIC const cc3k_obj_t cc3k_obj = {{(mp_obj_type_t*)&mod_network_nic_type_cc3k}}; +STATIC const cc3k_obj_t cc3k_obj = {{(mp_obj_type_t *)&mod_network_nic_type_cc3k}}; // \classmethod \constructor(spi, pin_cs, pin_en, pin_irq) // Initialise the CC3000 using the given SPI bus and pins and return a CC3K object. @@ -436,11 +444,11 @@ STATIC mp_obj_t cc3k_make_new(const mp_obj_type_t *type, size_t n_args, size_t n pin_find(args[1]), pin_find(args[2]), pin_find(args[3]) - ); + ); // initialize and start the module wlan_init(cc3k_callback, NULL, NULL, NULL, - ReadWlanInterruptPin, SpiResumeSpi, SpiPauseSpi, WriteWlanPin); + ReadWlanInterruptPin, SpiResumeSpi, SpiPauseSpi, WriteWlanPin); if (wlan_start(0) != 0) { nlr_raise(mp_obj_new_exception_msg(&mp_type_OSError, "failed to init CC3000 module")); @@ -450,10 +458,10 @@ STATIC mp_obj_t cc3k_make_new(const mp_obj_type_t *type, size_t n_args, size_t n // wlan_ioctl_set_connection_policy(0, 0, 0); // Mask out all non-required events from the CC3000 - wlan_set_event_mask(HCI_EVNT_WLAN_KEEPALIVE| - HCI_EVNT_WLAN_UNSOL_INIT| - HCI_EVNT_WLAN_ASYNC_PING_REPORT| - HCI_EVNT_WLAN_ASYNC_SIMPLE_CONFIG_DONE); + wlan_set_event_mask(HCI_EVNT_WLAN_KEEPALIVE | + HCI_EVNT_WLAN_UNSOL_INIT | + HCI_EVNT_WLAN_ASYNC_PING_REPORT | + HCI_EVNT_WLAN_ASYNC_SIMPLE_CONFIG_DONE); // register with network module mod_network_register_nic((mp_obj_t)&cc3k_obj); @@ -494,7 +502,7 @@ STATIC mp_obj_t cc3k_connect(size_t n_args, const mp_obj_t *pos_args, mp_map_t * } // connect to AP - if (wlan_connect(sec, (char*)ssid, ssid_len, (uint8_t*)bssid, (uint8_t*)key, key_len) != 0) { + if (wlan_connect(sec, (char *)ssid, ssid_len, (uint8_t *)bssid, (uint8_t *)key, key_len) != 0) { nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_OSError, "could not connect to ssid=%s, sec=%d, key=%s\n", ssid, sec, key)); } @@ -531,7 +539,7 @@ STATIC mp_obj_t cc3k_ifconfig(mp_obj_t self_in) { netutils_format_ipv4_addr(ipconfig.aucDNSServer, NETUTILS_LITTLE), netutils_format_ipv4_addr(ipconfig.aucDHCPServer, NETUTILS_LITTLE), mp_obj_new_str(mac_vstr.buf, mac_vstr.len), - mp_obj_new_str((const char*)ipconfig.uaSSID, strlen((const char*)ipconfig.uaSSID)), + mp_obj_new_str((const char *)ipconfig.uaSSID, strlen((const char *)ipconfig.uaSSID)), }; return mp_obj_new_tuple(MP_ARRAY_SIZE(tuple), tuple); } @@ -581,7 +589,7 @@ const mod_network_nic_type_t mod_network_nic_type_cc3k = { { &mp_type_type }, .name = MP_QSTR_CC3K, .make_new = cc3k_make_new, - .locals_dict = (mp_obj_dict_t*)&cc3k_locals_dict, + .locals_dict = (mp_obj_dict_t *)&cc3k_locals_dict, }, .gethostbyname = cc3k_gethostbyname, .socket = cc3k_socket_socket, diff --git a/ports/stm32/modnwwiznet5k.c b/ports/stm32/modnwwiznet5k.c index bf4b72ff21..204b9fcc3f 100644 --- a/ports/stm32/modnwwiznet5k.c +++ b/ports/stm32/modnwwiznet5k.c @@ -79,7 +79,7 @@ STATIC void wiz_spi_read(uint8_t *buf, uint32_t len) { } STATIC void wiz_spi_write(const uint8_t *buf, uint32_t len) { - HAL_StatusTypeDef status = HAL_SPI_Transmit(wiznet5k_obj.spi->spi, (uint8_t*)buf, len, 5000); + HAL_StatusTypeDef status = HAL_SPI_Transmit(wiznet5k_obj.spi->spi, (uint8_t *)buf, len, 5000); (void)status; } @@ -87,7 +87,7 @@ STATIC int wiznet5k_gethostbyname(mp_obj_t nic, const char *name, mp_uint_t len, uint8_t dns_ip[MOD_NETWORK_IPADDR_BUF_SIZE] = {8, 8, 8, 8}; uint8_t *buf = m_new(uint8_t, MAX_DNS_BUF_SIZE); DNS_init(0, buf); - mp_int_t ret = DNS_run(dns_ip, (uint8_t*)name, out_ip); + mp_int_t ret = DNS_run(dns_ip, (uint8_t *)name, out_ip); m_del(uint8_t, buf, MAX_DNS_BUF_SIZE); if (ret == 1) { // success @@ -105,9 +105,15 @@ STATIC int wiznet5k_socket_socket(mod_network_socket_obj_t *socket, int *_errno) } switch (socket->u_param.type) { - case MOD_NETWORK_SOCK_STREAM: socket->u_param.type = Sn_MR_TCP; break; - case MOD_NETWORK_SOCK_DGRAM: socket->u_param.type = Sn_MR_UDP; break; - default: *_errno = MP_EINVAL; return -1; + case MOD_NETWORK_SOCK_STREAM: + socket->u_param.type = Sn_MR_TCP; + break; + case MOD_NETWORK_SOCK_DGRAM: + socket->u_param.type = Sn_MR_UDP; + break; + default: + *_errno = MP_EINVAL; + return -1; } if (socket->u_param.fileno == -1) { @@ -185,11 +191,11 @@ STATIC int wiznet5k_socket_accept(mod_network_socket_obj_t *socket, mod_network_ socket->u_param.fileno = -1; int _errno2; if (wiznet5k_socket_socket(socket, &_errno2) != 0) { - //printf("(bad resocket %d)\n", _errno2); + // printf("(bad resocket %d)\n", _errno2); } else if (wiznet5k_socket_bind(socket, NULL, *port, &_errno2) != 0) { - //printf("(bad rebind %d)\n", _errno2); + // printf("(bad rebind %d)\n", _errno2); } else if (wiznet5k_socket_listen(socket, 0, &_errno2) != 0) { - //printf("(bad relisten %d)\n", _errno2); + // printf("(bad relisten %d)\n", _errno2); } return 0; @@ -226,7 +232,7 @@ STATIC int wiznet5k_socket_connect(mod_network_socket_obj_t *socket, byte *ip, m STATIC mp_uint_t wiznet5k_socket_send(mod_network_socket_obj_t *socket, const byte *buf, mp_uint_t len, int *_errno) { MP_THREAD_GIL_EXIT(); - mp_int_t ret = WIZCHIP_EXPORT(send)(socket->u_param.fileno, (byte*)buf, len); + mp_int_t ret = WIZCHIP_EXPORT(send)(socket->u_param.fileno, (byte *)buf, len); MP_THREAD_GIL_ENTER(); // TODO convert Wiz errno's to POSIX ones @@ -261,7 +267,7 @@ STATIC mp_uint_t wiznet5k_socket_sendto(mod_network_socket_obj_t *socket, const } MP_THREAD_GIL_EXIT(); - mp_int_t ret = WIZCHIP_EXPORT(sendto)(socket->u_param.fileno, (byte*)buf, len, ip, port); + mp_int_t ret = WIZCHIP_EXPORT(sendto)(socket->u_param.fileno, (byte *)buf, len, ip, port); MP_THREAD_GIL_ENTER(); if (ret < 0) { @@ -344,7 +350,7 @@ STATIC mp_obj_t wiznet5k_make_new(const mp_obj_type_t *type, size_t n_args, size mp_arg_check_num(n_args, n_kw, 3, 3, false); // init the wiznet5k object - wiznet5k_obj.base.type = (mp_obj_type_t*)&mod_network_nic_type_wiznet5k; + wiznet5k_obj.base.type = (mp_obj_type_t *)&mod_network_nic_type_wiznet5k; wiznet5k_obj.cris_state = 0; wiznet5k_obj.spi = spi_from_mp_obj(args[0]); wiznet5k_obj.cs = pin_find(args[1]); @@ -390,7 +396,7 @@ STATIC mp_obj_t wiznet5k_make_new(const mp_obj_type_t *type, size_t n_args, size .dns = {8, 8, 8, 8}, // Google public DNS .dhcp = NETINFO_STATIC, }; - ctlnetwork(CN_SET_NETINFO, (void*)&netinfo); + ctlnetwork(CN_SET_NETINFO, (void *)&netinfo); // seems we need a small delay after init mp_hal_delay_ms(250); @@ -405,7 +411,7 @@ STATIC mp_obj_t wiznet5k_make_new(const mp_obj_type_t *type, size_t n_args, size /// \method regs() /// Dump WIZNET5K registers. STATIC mp_obj_t wiznet5k_regs(mp_obj_t self_in) { - //wiznet5k_obj_t *self = self_in; + // wiznet5k_obj_t *self = self_in; printf("Wiz CREG:"); for (int i = 0; i < 0x50; ++i) { if (i % 16 == 0) { @@ -484,7 +490,7 @@ const mod_network_nic_type_t mod_network_nic_type_wiznet5k = { { &mp_type_type }, .name = MP_QSTR_WIZNET5K, .make_new = wiznet5k_make_new, - .locals_dict = (mp_obj_dict_t*)&wiznet5k_locals_dict, + .locals_dict = (mp_obj_dict_t *)&wiznet5k_locals_dict, }, .gethostbyname = wiznet5k_gethostbyname, .socket = wiznet5k_socket_socket, diff --git a/ports/stm32/modpyb.c b/ports/stm32/modpyb.c index 0e8313d101..4abc18d7f8 100644 --- a/ports/stm32/modpyb.c +++ b/ports/stm32/modpyb.c @@ -169,71 +169,71 @@ STATIC const mp_rom_map_elem_t pyb_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_Timer), MP_ROM_PTR(&pyb_timer_type) }, -#if MICROPY_HW_ENABLE_RNG + #if MICROPY_HW_ENABLE_RNG { MP_ROM_QSTR(MP_QSTR_rng), MP_ROM_PTR(&pyb_rng_get_obj) }, -#endif + #endif -#if MICROPY_HW_ENABLE_RTC + #if MICROPY_HW_ENABLE_RTC { MP_ROM_QSTR(MP_QSTR_RTC), MP_ROM_PTR(&pyb_rtc_type) }, -#endif + #endif { MP_ROM_QSTR(MP_QSTR_Pin), MP_ROM_PTR(&pin_type) }, { MP_ROM_QSTR(MP_QSTR_ExtInt), MP_ROM_PTR(&extint_type) }, -#if MICROPY_HW_ENABLE_SERVO + #if MICROPY_HW_ENABLE_SERVO { MP_ROM_QSTR(MP_QSTR_pwm), MP_ROM_PTR(&pyb_pwm_set_obj) }, { MP_ROM_QSTR(MP_QSTR_servo), MP_ROM_PTR(&pyb_servo_set_obj) }, { MP_ROM_QSTR(MP_QSTR_Servo), MP_ROM_PTR(&pyb_servo_type) }, -#endif + #endif -#if MICROPY_HW_HAS_SWITCH + #if MICROPY_HW_HAS_SWITCH { MP_ROM_QSTR(MP_QSTR_Switch), MP_ROM_PTR(&pyb_switch_type) }, -#endif + #endif -#if MICROPY_HW_HAS_FLASH + #if MICROPY_HW_HAS_FLASH { MP_ROM_QSTR(MP_QSTR_Flash), MP_ROM_PTR(&pyb_flash_type) }, -#endif + #endif -#if MICROPY_HW_HAS_SDCARD + #if MICROPY_HW_HAS_SDCARD #if MICROPY_PY_PYB_LEGACY { MP_ROM_QSTR(MP_QSTR_SD), MP_ROM_PTR(&pyb_sdcard_obj) }, // now obsolete #endif { MP_ROM_QSTR(MP_QSTR_SDCard), MP_ROM_PTR(&pyb_sdcard_type) }, -#endif + #endif -#if defined(MICROPY_HW_LED1) + #if defined(MICROPY_HW_LED1) { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pyb_led_type) }, -#endif + #endif #if MICROPY_PY_PYB_LEGACY && MICROPY_HW_ENABLE_HW_I2C { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&pyb_i2c_type) }, #endif { MP_ROM_QSTR(MP_QSTR_SPI), MP_ROM_PTR(&pyb_spi_type) }, { MP_ROM_QSTR(MP_QSTR_UART), MP_ROM_PTR(&pyb_uart_type) }, -#if MICROPY_HW_ENABLE_CAN + #if MICROPY_HW_ENABLE_CAN { MP_ROM_QSTR(MP_QSTR_CAN), MP_ROM_PTR(&pyb_can_type) }, -#endif + #endif #if MICROPY_HW_ENABLE_ADC { MP_ROM_QSTR(MP_QSTR_ADC), MP_ROM_PTR(&pyb_adc_type) }, { MP_ROM_QSTR(MP_QSTR_ADCAll), MP_ROM_PTR(&pyb_adc_all_type) }, #endif -#if MICROPY_HW_ENABLE_DAC + #if MICROPY_HW_ENABLE_DAC { MP_ROM_QSTR(MP_QSTR_DAC), MP_ROM_PTR(&pyb_dac_type) }, -#endif + #endif -#if MICROPY_HW_HAS_MMA7660 + #if MICROPY_HW_HAS_MMA7660 { MP_ROM_QSTR(MP_QSTR_Accel), MP_ROM_PTR(&pyb_accel_type) }, -#endif + #endif -#if MICROPY_HW_HAS_LCD + #if MICROPY_HW_HAS_LCD { MP_ROM_QSTR(MP_QSTR_LCD), MP_ROM_PTR(&pyb_lcd_type) }, -#endif + #endif }; STATIC MP_DEFINE_CONST_DICT(pyb_module_globals, pyb_module_globals_table); const mp_obj_module_t pyb_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&pyb_module_globals, + .globals = (mp_obj_dict_t *)&pyb_module_globals, }; diff --git a/ports/stm32/modstm.c b/ports/stm32/modstm.c index 3fae3a57c4..418b8bde2a 100644 --- a/ports/stm32/modstm.c +++ b/ports/stm32/modstm.c @@ -43,14 +43,14 @@ STATIC const mp_rom_map_elem_t stm_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_mem16), MP_ROM_PTR(&machine_mem16_obj) }, { MP_ROM_QSTR(MP_QSTR_mem32), MP_ROM_PTR(&machine_mem32_obj) }, -#include "genhdr/modstm_const.h" + #include "genhdr/modstm_const.h" }; STATIC MP_DEFINE_CONST_DICT(stm_module_globals, stm_module_globals_table); const mp_obj_module_t stm_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&stm_module_globals, + .globals = (mp_obj_dict_t *)&stm_module_globals, }; #endif // MICROPY_PY_STM diff --git a/ports/stm32/moduos.c b/ports/stm32/moduos.c index f492b0b752..9f8729827a 100644 --- a/ports/stm32/moduos.c +++ b/ports/stm32/moduos.c @@ -72,7 +72,7 @@ STATIC MP_DEFINE_ATTRTUPLE( MP_ROM_PTR(&os_uname_info_release_obj), MP_ROM_PTR(&os_uname_info_version_obj), MP_ROM_PTR(&os_uname_info_machine_obj) -); + ); STATIC mp_obj_t os_uname(void) { return MP_OBJ_FROM_PTR(&os_uname_info_obj); @@ -142,9 +142,9 @@ STATIC const mp_rom_map_elem_t os_module_globals_table[] = { /// \constant sep - separation character used in paths { MP_ROM_QSTR(MP_QSTR_sep), MP_ROM_QSTR(MP_QSTR__slash_) }, -#if MICROPY_HW_ENABLE_RNG + #if MICROPY_HW_ENABLE_RNG { MP_ROM_QSTR(MP_QSTR_urandom), MP_ROM_PTR(&os_urandom_obj) }, -#endif + #endif // these are MicroPython extensions { MP_ROM_QSTR(MP_QSTR_dupterm), MP_ROM_PTR(&uos_dupterm_obj) }, @@ -159,5 +159,5 @@ STATIC MP_DEFINE_CONST_DICT(os_module_globals, os_module_globals_table); const mp_obj_module_t mp_module_uos = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&os_module_globals, + .globals = (mp_obj_dict_t *)&os_module_globals, }; diff --git a/ports/stm32/modusocket.c b/ports/stm32/modusocket.c index 7503ecbd68..d630850ee2 100644 --- a/ports/stm32/modusocket.c +++ b/ports/stm32/modusocket.c @@ -71,7 +71,7 @@ STATIC void socket_select_nic(mod_network_socket_obj_t *self, const byte *ip) { if (self->nic == MP_OBJ_NULL) { // select NIC based on IP self->nic = mod_network_find_nic(ip); - self->nic_type = (mod_network_nic_type_t*)mp_obj_get_type(self->nic); + self->nic_type = (mod_network_nic_type_t *)mp_obj_get_type(self->nic); // call the NIC to open the socket int _errno; @@ -203,7 +203,7 @@ STATIC mp_obj_t socket_recv(mp_obj_t self_in, mp_obj_t len_in) { vstr_t vstr; vstr_init_len(&vstr, len); int _errno; - mp_uint_t ret = self->nic_type->recv(self, (byte*)vstr.buf, len, &_errno); + mp_uint_t ret = self->nic_type->recv(self, (byte *)vstr.buf, len, &_errno); if (ret == -1) { mp_raise_OSError(_errno); } @@ -253,7 +253,7 @@ STATIC mp_obj_t socket_recvfrom(mp_obj_t self_in, mp_obj_t len_in) { byte ip[4]; mp_uint_t port; int _errno; - mp_int_t ret = self->nic_type->recvfrom(self, (byte*)vstr.buf, vstr.len, ip, &port, &_errno); + mp_int_t ret = self->nic_type->recvfrom(self, (byte *)vstr.buf, vstr.len, ip, &port, &_errno); if (ret == -1) { mp_raise_OSError(_errno); } @@ -377,7 +377,7 @@ STATIC const mp_obj_type_t socket_type = { .name = MP_QSTR_socket, .make_new = socket_make_new, .protocol = &socket_stream_p, - .locals_dict = (mp_obj_dict_t*)&socket_locals_dict, + .locals_dict = (mp_obj_dict_t *)&socket_locals_dict, }; /******************************************************************************/ @@ -407,7 +407,7 @@ STATIC mp_obj_t mod_usocket_getaddrinfo(mp_obj_t host_in, mp_obj_t port_in) { // find a NIC that can do a name lookup for (mp_uint_t i = 0; i < MP_STATE_PORT(mod_network_nic_list).len; i++) { mp_obj_t nic = MP_STATE_PORT(mod_network_nic_list).items[i]; - mod_network_nic_type_t *nic_type = (mod_network_nic_type_t*)mp_obj_get_type(nic); + mod_network_nic_type_t *nic_type = (mod_network_nic_type_t *)mp_obj_get_type(nic); if (nic_type->gethostbyname != NULL) { int ret = nic_type->gethostbyname(nic, host, hlen, out_ip); if (ret != 0) { @@ -429,7 +429,7 @@ STATIC mp_obj_t mod_usocket_getaddrinfo(mp_obj_t host_in, mp_obj_t port_in) { tuple->items[2] = MP_OBJ_NEW_SMALL_INT(0); tuple->items[3] = MP_OBJ_NEW_QSTR(MP_QSTR_); tuple->items[4] = netutils_format_inet_addr(out_ip, port, NETUTILS_BIG); - return mp_obj_new_list(1, (mp_obj_t*)&tuple); + return mp_obj_new_list(1, (mp_obj_t *)&tuple); } STATIC MP_DEFINE_CONST_FUN_OBJ_2(mod_usocket_getaddrinfo_obj, mod_usocket_getaddrinfo); @@ -462,7 +462,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_usocket_globals, mp_module_usocket_globals const mp_obj_module_t mp_module_usocket = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_usocket_globals, + .globals = (mp_obj_dict_t *)&mp_module_usocket_globals, }; #endif // MICROPY_PY_USOCKET && !MICROPY_PY_LWIP diff --git a/ports/stm32/modutime.c b/ports/stm32/modutime.c index 6b5c841151..428aa7911c 100644 --- a/ports/stm32/modutime.c +++ b/ports/stm32/modutime.c @@ -110,8 +110,8 @@ STATIC mp_obj_t time_mktime(mp_obj_t tuple) { } return mp_obj_new_int_from_uint(timeutils_mktime(mp_obj_get_int(elem[0]), - mp_obj_get_int(elem[1]), mp_obj_get_int(elem[2]), mp_obj_get_int(elem[3]), - mp_obj_get_int(elem[4]), mp_obj_get_int(elem[5]))); + mp_obj_get_int(elem[1]), mp_obj_get_int(elem[2]), mp_obj_get_int(elem[3]), + mp_obj_get_int(elem[4]), mp_obj_get_int(elem[5]))); } MP_DEFINE_CONST_FUN_OBJ_1(time_mktime_obj, time_mktime); @@ -149,5 +149,5 @@ STATIC MP_DEFINE_CONST_DICT(time_module_globals, time_module_globals_table); const mp_obj_module_t mp_module_utime = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&time_module_globals, + .globals = (mp_obj_dict_t *)&time_module_globals, }; diff --git a/ports/stm32/mpconfigboard_common.h b/ports/stm32/mpconfigboard_common.h index d4e7c20145..9e0c212ded 100644 --- a/ports/stm32/mpconfigboard_common.h +++ b/ports/stm32/mpconfigboard_common.h @@ -223,11 +223,11 @@ // D-cache clean/invalidate helpers #if __DCACHE_PRESENT == 1 #define MP_HAL_CLEANINVALIDATE_DCACHE(addr, size) \ - (SCB_CleanInvalidateDCache_by_Addr((uint32_t*)((uint32_t)addr & ~0x1f), \ - ((uint32_t)((uint8_t*)addr + size + 0x1f) & ~0x1f) - ((uint32_t)addr & ~0x1f))) + (SCB_CleanInvalidateDCache_by_Addr((uint32_t *)((uint32_t)addr & ~0x1f), \ + ((uint32_t)((uint8_t *)addr + size + 0x1f) & ~0x1f) - ((uint32_t)addr & ~0x1f))) #define MP_HAL_CLEAN_DCACHE(addr, size) \ - (SCB_CleanDCache_by_Addr((uint32_t*)((uint32_t)addr & ~0x1f), \ - ((uint32_t)((uint8_t*)addr + size + 0x1f) & ~0x1f) - ((uint32_t)addr & ~0x1f))) + (SCB_CleanDCache_by_Addr((uint32_t *)((uint32_t)addr & ~0x1f), \ + ((uint32_t)((uint8_t *)addr + size + 0x1f) & ~0x1f) - ((uint32_t)addr & ~0x1f))) #else #define MP_HAL_CLEANINVALIDATE_DCACHE(addr, size) #define MP_HAL_CLEAN_DCACHE(addr, size) diff --git a/ports/stm32/mpconfigport.h b/ports/stm32/mpconfigport.h index 42e0bf3f13..a71d420276 100644 --- a/ports/stm32/mpconfigport.h +++ b/ports/stm32/mpconfigport.h @@ -300,7 +300,7 @@ extern const struct _mp_obj_module_t mp_module_onewire; // type definitions for the specific machine -#define MICROPY_MAKE_POINTER_CALLABLE(p) ((void*)((mp_uint_t)(p) | 1)) +#define MICROPY_MAKE_POINTER_CALLABLE(p) ((void *)((mp_uint_t)(p) | 1)) #define MP_SSIZE_MAX (0x7fffffff) diff --git a/ports/stm32/mphalport.c b/ports/stm32/mphalport.c index 206221721b..eab648e568 100644 --- a/ports/stm32/mphalport.c +++ b/ports/stm32/mphalport.c @@ -21,15 +21,15 @@ NORETURN void mp_hal_raise(HAL_StatusTypeDef status) { MP_WEAK int mp_hal_stdin_rx_chr(void) { for (;;) { -#if 0 -#ifdef USE_HOST_MODE + #if 0 + #ifdef USE_HOST_MODE pyb_usb_host_process(); int c = pyb_usb_host_get_keyboard(); if (c != 0) { return c; } -#endif -#endif + #endif + #endif #if MICROPY_HW_ENABLE_USB byte c; @@ -56,9 +56,9 @@ MP_WEAK void mp_hal_stdout_tx_strn(const char *str, size_t len) { if (MP_STATE_PORT(pyb_stdio_uart) != NULL) { uart_tx_strn(MP_STATE_PORT(pyb_stdio_uart), str, len); } -#if 0 && defined(USE_HOST_MODE) && MICROPY_HW_HAS_LCD + #if 0 && defined(USE_HOST_MODE) && MICROPY_HW_HAS_LCD lcd_print_strn(str, len); -#endif + #endif #if MICROPY_HW_ENABLE_USB if (usb_vcp_is_enabled()) { usb_vcp_send_strn(str, len); diff --git a/ports/stm32/mphalport.h b/ports/stm32/mphalport.h index 72413c04c7..67e5f6aba8 100644 --- a/ports/stm32/mphalport.h +++ b/ports/stm32/mphalport.h @@ -53,7 +53,7 @@ static inline mp_uint_t mp_hal_ticks_cpu(void) { #define MP_HAL_PIN_PULL_UP (GPIO_PULLUP) #define MP_HAL_PIN_PULL_DOWN (GPIO_PULLDOWN) -#define mp_hal_pin_obj_t const pin_obj_t* +#define mp_hal_pin_obj_t const pin_obj_t * #define mp_hal_get_pin_obj(o) pin_find(o) #define mp_hal_pin_name(p) ((p)->name) #define mp_hal_pin_input(p) mp_hal_pin_config((p), MP_HAL_PIN_MODE_INPUT, MP_HAL_PIN_PULL_NONE, 0) diff --git a/ports/stm32/mpthreadport.c b/ports/stm32/mpthreadport.c index 11653b24cf..2f03052233 100644 --- a/ports/stm32/mpthreadport.c +++ b/ports/stm32/mpthreadport.c @@ -43,7 +43,7 @@ void mp_thread_init(void) { void mp_thread_gc_others(void) { mp_thread_mutex_lock(&thread_mutex, 1); for (pyb_thread_t *th = pyb_thread_all; th != NULL; th = th->all_next) { - gc_collect_root((void**)&th, 1); + gc_collect_root((void **)&th, 1); gc_collect_root(&th->arg, 1); gc_collect_root(&th->stack, 1); if (th != pyb_thread_cur) { @@ -53,7 +53,7 @@ void mp_thread_gc_others(void) { mp_thread_mutex_unlock(&thread_mutex); } -void mp_thread_create(void *(*entry)(void*), void *arg, size_t *stack_size) { +void mp_thread_create(void *(*entry)(void *), void *arg, size_t *stack_size) { if (*stack_size == 0) { *stack_size = 4096; // default stack size } else if (*stack_size < 2048) { diff --git a/ports/stm32/network_wiznet5k.c b/ports/stm32/network_wiznet5k.c index 9db42b7874..ad4b84d1df 100644 --- a/ports/stm32/network_wiznet5k.c +++ b/ports/stm32/network_wiznet5k.c @@ -80,7 +80,7 @@ STATIC void wiz_spi_read(uint8_t *buf, uint32_t len) { } STATIC void wiz_spi_write(const uint8_t *buf, uint32_t len) { - HAL_StatusTypeDef status = HAL_SPI_Transmit(wiznet5k_obj.spi->spi, (uint8_t*)buf, len, 5000); + HAL_StatusTypeDef status = HAL_SPI_Transmit(wiznet5k_obj.spi->spi, (uint8_t *)buf, len, 5000); (void)status; } @@ -142,7 +142,7 @@ STATIC void wiznet5k_get_mac_address(wiznet5k_obj_t *self, uint8_t mac[6]) { STATIC void wiznet5k_send_ethernet(wiznet5k_obj_t *self, size_t len, const uint8_t *buf) { uint8_t ip[4] = {1, 1, 1, 1}; // dummy - int ret = WIZCHIP_EXPORT(sendto)(0, (byte*)buf, len, ip, 11); // dummy port + int ret = WIZCHIP_EXPORT(sendto)(0, (byte *)buf, len, ip, 11); // dummy port if (ret != len) { printf("wiznet5k_send_ethernet: fatal error %d\n", ret); netif_set_link_down(&self->netif); @@ -248,7 +248,7 @@ STATIC mp_obj_t wiznet5k_make_new(const mp_obj_type_t *type, size_t n_args, size // Access the existing object, if it has been constructed with the same hardware interface if (wiznet5k_obj.base.base.type == &mod_network_nic_type_wiznet5k) { if (!(wiznet5k_obj.spi == spi && wiznet5k_obj.cs == cs && wiznet5k_obj.rst == rst - && wiznet5k_obj.netif.flags != 0)) { + && wiznet5k_obj.netif.flags != 0)) { wiznet5k_deinit(); } } @@ -304,7 +304,7 @@ STATIC mp_obj_t wiznet5k_isconnected(mp_obj_t self_in) { wizphy_getphylink() == PHY_LINK_ON && (self->netif.flags & NETIF_FLAG_UP) && self->netif.ip_addr.addr != 0 - ); + ); } STATIC MP_DEFINE_CONST_FUN_OBJ_1(wiznet5k_isconnected_obj, wiznet5k_isconnected); @@ -411,7 +411,7 @@ const mp_obj_type_t mod_network_nic_type_wiznet5k = { { &mp_type_type }, .name = MP_QSTR_WIZNET5K, .make_new = wiznet5k_make_new, - .locals_dict = (mp_obj_dict_t*)&wiznet5k_locals_dict, + .locals_dict = (mp_obj_dict_t *)&wiznet5k_locals_dict, }; #endif // MICROPY_PY_WIZNET5K && MICROPY_PY_LWIP diff --git a/ports/stm32/pendsv.c b/ports/stm32/pendsv.c index b5fe42f70d..c924ddbfcc 100644 --- a/ports/stm32/pendsv.c +++ b/ports/stm32/pendsv.c @@ -88,7 +88,7 @@ void pendsv_isr_handler(void) { // sp[1]: 0xfffffff9 // sp[0]: ? -#if MICROPY_PY_THREAD + #if MICROPY_PY_THREAD __asm volatile ( "ldr r1, pendsv_object_ptr\n" "ldr r0, [r1]\n" @@ -118,28 +118,28 @@ void pendsv_isr_handler(void) { ".align 2\n" "pendsv_object_ptr: .word pendsv_object\n" "nlr_jump_ptr: .word nlr_jump\n" - ); -#else + ); + #else __asm volatile ( "ldr r0, pendsv_object_ptr\n" "ldr r0, [r0]\n" -#if defined(PENDSV_DEBUG) + #if defined(PENDSV_DEBUG) "str r0, [sp, #8]\n" -#else + #else "str r0, [sp, #0]\n" -#endif + #endif "ldr r0, nlr_jump_ptr\n" -#if defined(PENDSV_DEBUG) + #if defined(PENDSV_DEBUG) "str r0, [sp, #32]\n" -#else + #else "str r0, [sp, #24]\n" -#endif + #endif "bx lr\n" ".align 2\n" "pendsv_object_ptr: .word pendsv_object\n" "nlr_jump_ptr: .word nlr_jump\n" - ); -#endif + ); + #endif /* uint32_t x[2] = {0x424242, 0xdeaddead}; diff --git a/ports/stm32/pin.c b/ports/stm32/pin.c index 58c01e22cf..f99a6921da 100644 --- a/ports/stm32/pin.c +++ b/ports/stm32/pin.c @@ -564,7 +564,7 @@ STATIC const mp_rom_map_elem_t pin_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_AF_OD), MP_ROM_INT(GPIO_MODE_AF_OD) }, { MP_ROM_QSTR(MP_QSTR_PULL_NONE), MP_ROM_INT(GPIO_NOPULL) }, -#include "genhdr/pins_af_const.h" + #include "genhdr/pins_af_const.h" }; STATIC MP_DEFINE_CONST_DICT(pin_locals_dict, pin_locals_dict_table); @@ -596,7 +596,7 @@ const mp_obj_type_t pin_type = { .make_new = mp_pin_make_new, .call = pin_call, .protocol = &pin_pin_p, - .locals_dict = (mp_obj_dict_t*)&pin_locals_dict, + .locals_dict = (mp_obj_dict_t *)&pin_locals_dict, }; /// \moduleref pyb @@ -670,5 +670,5 @@ const mp_obj_type_t pin_af_type = { { &mp_type_type }, .name = MP_QSTR_PinAF, .print = pin_af_obj_print, - .locals_dict = (mp_obj_dict_t*)&pin_af_locals_dict, + .locals_dict = (mp_obj_dict_t *)&pin_af_locals_dict, }; diff --git a/ports/stm32/pin.h b/ports/stm32/pin.h index ea57b0a274..2397a9d48e 100644 --- a/ports/stm32/pin.h +++ b/ports/stm32/pin.h @@ -33,26 +33,26 @@ #include "py/obj.h" typedef struct { - mp_obj_base_t base; - qstr name; - uint8_t idx; - uint8_t fn; - uint8_t unit; - uint8_t type; - void *reg; // The peripheral associated with this AF + mp_obj_base_t base; + qstr name; + uint8_t idx; + uint8_t fn; + uint8_t unit; + uint8_t type; + void *reg; // The peripheral associated with this AF } pin_af_obj_t; typedef struct { - mp_obj_base_t base; - qstr name; - uint32_t port : 4; - uint32_t pin : 5; // Some ARM processors use 32 bits/PORT - uint32_t num_af : 4; - uint32_t adc_channel : 5; // Some ARM processors use 32 bits/PORT - uint32_t adc_num : 3; // 1 bit per ADC - uint32_t pin_mask; - pin_gpio_t *gpio; - const pin_af_obj_t *af; + mp_obj_base_t base; + qstr name; + uint32_t port : 4; + uint32_t pin : 5; // Some ARM processors use 32 bits/PORT + uint32_t num_af : 4; + uint32_t adc_channel : 5; // Some ARM processors use 32 bits/PORT + uint32_t adc_num : 3; // 1 bit per ADC + uint32_t pin_mask; + pin_gpio_t *gpio; + const pin_af_obj_t *af; } pin_obj_t; extern const mp_obj_type_t pin_type; @@ -62,14 +62,14 @@ extern const mp_obj_type_t pin_af_type; #include "genhdr/pins.h" typedef struct { - const char *name; - const pin_obj_t *pin; + const char *name; + const pin_obj_t *pin; } pin_named_pin_t; extern const pin_named_pin_t pin_board_pins[]; extern const pin_named_pin_t pin_cpu_pins[]; -//extern pin_map_obj_t pin_map_obj; +// extern pin_map_obj_t pin_map_obj; typedef struct { mp_obj_base_t base; diff --git a/ports/stm32/pin_defs_stm32.h b/ports/stm32/pin_defs_stm32.h index 89b659de5d..6995741e65 100644 --- a/ports/stm32/pin_defs_stm32.h +++ b/ports/stm32/pin_defs_stm32.h @@ -28,76 +28,76 @@ // This file should only ever be #included by pin.h and not directly. enum { - PORT_A, - PORT_B, - PORT_C, - PORT_D, - PORT_E, - PORT_F, - PORT_G, - PORT_H, - PORT_I, - PORT_J, - PORT_K, + PORT_A, + PORT_B, + PORT_C, + PORT_D, + PORT_E, + PORT_F, + PORT_G, + PORT_H, + PORT_I, + PORT_J, + PORT_K, }; // Must have matching entries in SUPPORTED_FN in boards/make-pins.py enum { - AF_FN_TIM, - AF_FN_I2C, - AF_FN_USART, - AF_FN_UART = AF_FN_USART, - AF_FN_SPI, - AF_FN_I2S, - AF_FN_SDMMC, - AF_FN_CAN, + AF_FN_TIM, + AF_FN_I2C, + AF_FN_USART, + AF_FN_UART = AF_FN_USART, + AF_FN_SPI, + AF_FN_I2S, + AF_FN_SDMMC, + AF_FN_CAN, }; enum { - AF_PIN_TYPE_TIM_CH1 = 0, - AF_PIN_TYPE_TIM_CH2, - AF_PIN_TYPE_TIM_CH3, - AF_PIN_TYPE_TIM_CH4, - AF_PIN_TYPE_TIM_CH1N, - AF_PIN_TYPE_TIM_CH2N, - AF_PIN_TYPE_TIM_CH3N, - AF_PIN_TYPE_TIM_CH1_ETR, - AF_PIN_TYPE_TIM_ETR, - AF_PIN_TYPE_TIM_BKIN, + AF_PIN_TYPE_TIM_CH1 = 0, + AF_PIN_TYPE_TIM_CH2, + AF_PIN_TYPE_TIM_CH3, + AF_PIN_TYPE_TIM_CH4, + AF_PIN_TYPE_TIM_CH1N, + AF_PIN_TYPE_TIM_CH2N, + AF_PIN_TYPE_TIM_CH3N, + AF_PIN_TYPE_TIM_CH1_ETR, + AF_PIN_TYPE_TIM_ETR, + AF_PIN_TYPE_TIM_BKIN, - AF_PIN_TYPE_I2C_SDA = 0, - AF_PIN_TYPE_I2C_SCL, + AF_PIN_TYPE_I2C_SDA = 0, + AF_PIN_TYPE_I2C_SCL, - AF_PIN_TYPE_USART_TX = 0, - AF_PIN_TYPE_USART_RX, - AF_PIN_TYPE_USART_CTS, - AF_PIN_TYPE_USART_RTS, - AF_PIN_TYPE_USART_CK, - AF_PIN_TYPE_UART_TX = AF_PIN_TYPE_USART_TX, - AF_PIN_TYPE_UART_RX = AF_PIN_TYPE_USART_RX, - AF_PIN_TYPE_UART_CTS = AF_PIN_TYPE_USART_CTS, - AF_PIN_TYPE_UART_RTS = AF_PIN_TYPE_USART_RTS, + AF_PIN_TYPE_USART_TX = 0, + AF_PIN_TYPE_USART_RX, + AF_PIN_TYPE_USART_CTS, + AF_PIN_TYPE_USART_RTS, + AF_PIN_TYPE_USART_CK, + AF_PIN_TYPE_UART_TX = AF_PIN_TYPE_USART_TX, + AF_PIN_TYPE_UART_RX = AF_PIN_TYPE_USART_RX, + AF_PIN_TYPE_UART_CTS = AF_PIN_TYPE_USART_CTS, + AF_PIN_TYPE_UART_RTS = AF_PIN_TYPE_USART_RTS, - AF_PIN_TYPE_SPI_MOSI = 0, - AF_PIN_TYPE_SPI_MISO, - AF_PIN_TYPE_SPI_SCK, - AF_PIN_TYPE_SPI_NSS, + AF_PIN_TYPE_SPI_MOSI = 0, + AF_PIN_TYPE_SPI_MISO, + AF_PIN_TYPE_SPI_SCK, + AF_PIN_TYPE_SPI_NSS, - AF_PIN_TYPE_I2S_CK = 0, - AF_PIN_TYPE_I2S_MCK, - AF_PIN_TYPE_I2S_SD, - AF_PIN_TYPE_I2S_WS, - AF_PIN_TYPE_I2S_EXTSD, + AF_PIN_TYPE_I2S_CK = 0, + AF_PIN_TYPE_I2S_MCK, + AF_PIN_TYPE_I2S_SD, + AF_PIN_TYPE_I2S_WS, + AF_PIN_TYPE_I2S_EXTSD, - AF_PIN_TYPE_SDMMC_CK = 0, - AF_PIN_TYPE_SDMMC_CMD, - AF_PIN_TYPE_SDMMC_D0, - AF_PIN_TYPE_SDMMC_D1, - AF_PIN_TYPE_SDMMC_D2, - AF_PIN_TYPE_SDMMC_D3, + AF_PIN_TYPE_SDMMC_CK = 0, + AF_PIN_TYPE_SDMMC_CMD, + AF_PIN_TYPE_SDMMC_D0, + AF_PIN_TYPE_SDMMC_D1, + AF_PIN_TYPE_SDMMC_D2, + AF_PIN_TYPE_SDMMC_D3, - AF_PIN_TYPE_CAN_TX = 0, - AF_PIN_TYPE_CAN_RX, + AF_PIN_TYPE_CAN_TX = 0, + AF_PIN_TYPE_CAN_RX, }; // The HAL uses a slightly different naming than we chose, so we provide @@ -115,9 +115,9 @@ enum { #define I2S3 SPI3 enum { - PIN_ADC1 = (1 << 0), - PIN_ADC2 = (1 << 1), - PIN_ADC3 = (1 << 2), + PIN_ADC1 = (1 << 0), + PIN_ADC2 = (1 << 1), + PIN_ADC3 = (1 << 2), }; typedef GPIO_TypeDef pin_gpio_t; diff --git a/ports/stm32/pin_named_pins.c b/ports/stm32/pin_named_pins.c index 1c7e643422..3a8e0f9fce 100644 --- a/ports/stm32/pin_named_pins.c +++ b/ports/stm32/pin_named_pins.c @@ -34,18 +34,18 @@ const mp_obj_type_t pin_cpu_pins_obj_type = { { &mp_type_type }, .name = MP_QSTR_cpu, - .locals_dict = (mp_obj_dict_t*)&pin_cpu_pins_locals_dict, + .locals_dict = (mp_obj_dict_t *)&pin_cpu_pins_locals_dict, }; const mp_obj_type_t pin_board_pins_obj_type = { { &mp_type_type }, .name = MP_QSTR_board, - .locals_dict = (mp_obj_dict_t*)&pin_board_pins_locals_dict, + .locals_dict = (mp_obj_dict_t *)&pin_board_pins_locals_dict, }; const pin_obj_t *pin_find_named_pin(const mp_obj_dict_t *named_pins, mp_obj_t name) { const mp_map_t *named_map = &named_pins->map; - mp_map_elem_t *named_elem = mp_map_lookup((mp_map_t*)named_map, name, MP_MAP_LOOKUP); + mp_map_elem_t *named_elem = mp_map_lookup((mp_map_t *)named_map, name, MP_MAP_LOOKUP); if (named_elem != NULL && named_elem->value != MP_OBJ_NULL) { return MP_OBJ_TO_PTR(named_elem->value); } diff --git a/ports/stm32/pin_static_af.h b/ports/stm32/pin_static_af.h index b73944d6f8..4beb65208d 100644 --- a/ports/stm32/pin_static_af.h +++ b/ports/stm32/pin_static_af.h @@ -32,14 +32,14 @@ #if 0 // Enable to test if AF's are statically compiled #define mp_hal_pin_config_alt_static(pin_obj, mode, pull, fn_type) \ - mp_hal_pin_config(pin_obj, mode, pull, fn_type(pin_obj)); \ - _Static_assert(fn_type(pin_obj) != -1, ""); \ - _Static_assert(__builtin_constant_p(fn_type(pin_obj)) == 1, "") + mp_hal_pin_config(pin_obj, mode, pull, fn_type(pin_obj)); \ + _Static_assert(fn_type(pin_obj) != -1, ""); \ + _Static_assert(__builtin_constant_p(fn_type(pin_obj)) == 1, "") #else #define mp_hal_pin_config_alt_static(pin_obj, mode, pull, fn_type) \ - mp_hal_pin_config(pin_obj, mode, pull, fn_type(pin_obj)) /* Overflow Error => alt func not found */ + mp_hal_pin_config(pin_obj, mode, pull, fn_type(pin_obj)) /* Overflow Error => alt func not found */ #endif diff --git a/ports/stm32/powerctrl.c b/ports/stm32/powerctrl.c index fe4d580017..6f704f6de9 100644 --- a/ports/stm32/powerctrl.c +++ b/ports/stm32/powerctrl.c @@ -109,23 +109,39 @@ int powerctrl_rcc_clock_config_pll(RCC_ClkInitTypeDef *rcc_init, uint32_t sysclk #if !(defined(STM32F0) || defined(STM32L4)) STATIC uint32_t calc_ahb_div(uint32_t wanted_div) { - if (wanted_div <= 1) { return RCC_SYSCLK_DIV1; } - else if (wanted_div <= 2) { return RCC_SYSCLK_DIV2; } - else if (wanted_div <= 4) { return RCC_SYSCLK_DIV4; } - else if (wanted_div <= 8) { return RCC_SYSCLK_DIV8; } - else if (wanted_div <= 16) { return RCC_SYSCLK_DIV16; } - else if (wanted_div <= 64) { return RCC_SYSCLK_DIV64; } - else if (wanted_div <= 128) { return RCC_SYSCLK_DIV128; } - else if (wanted_div <= 256) { return RCC_SYSCLK_DIV256; } - else { return RCC_SYSCLK_DIV512; } + if (wanted_div <= 1) { + return RCC_SYSCLK_DIV1; + } else if (wanted_div <= 2) { + return RCC_SYSCLK_DIV2; + } else if (wanted_div <= 4) { + return RCC_SYSCLK_DIV4; + } else if (wanted_div <= 8) { + return RCC_SYSCLK_DIV8; + } else if (wanted_div <= 16) { + return RCC_SYSCLK_DIV16; + } else if (wanted_div <= 64) { + return RCC_SYSCLK_DIV64; + } else if (wanted_div <= 128) { + return RCC_SYSCLK_DIV128; + } else if (wanted_div <= 256) { + return RCC_SYSCLK_DIV256; + } else { + return RCC_SYSCLK_DIV512; + } } STATIC uint32_t calc_apb_div(uint32_t wanted_div) { - if (wanted_div <= 1) { return RCC_HCLK_DIV1; } - else if (wanted_div <= 2) { return RCC_HCLK_DIV2; } - else if (wanted_div <= 4) { return RCC_HCLK_DIV4; } - else if (wanted_div <= 8) { return RCC_HCLK_DIV8; } - else { return RCC_SYSCLK_DIV16; } + if (wanted_div <= 1) { + return RCC_HCLK_DIV1; + } else if (wanted_div <= 2) { + return RCC_HCLK_DIV2; + } else if (wanted_div <= 4) { + return RCC_HCLK_DIV4; + } else if (wanted_div <= 8) { + return RCC_HCLK_DIV8; + } else { + return RCC_SYSCLK_DIV16; + } } int powerctrl_set_sysclk(uint32_t sysclk, uint32_t ahb, uint32_t apb1, uint32_t apb2) { @@ -274,9 +290,9 @@ void powerctrl_enter_stop_mode(void) { HAL_PWREx_EnableFlashPowerDown(); #endif - # if defined(STM32F7) + #if defined(STM32F7) HAL_PWR_EnterSTOPMode((PWR_CR1_LPDS | PWR_CR1_LPUDS | PWR_CR1_FPDS | PWR_CR1_UDEN), PWR_STOPENTRY_WFI); - # else + #else HAL_PWR_EnterSTOPMode(PWR_LOWPOWERREGULATOR_ON, PWR_STOPENTRY_WFI); #endif diff --git a/ports/stm32/pyb_i2c.c b/ports/stm32/pyb_i2c.c index d6b9ec6cc1..00363622b2 100644 --- a/ports/stm32/pyb_i2c.c +++ b/ports/stm32/pyb_i2c.c @@ -143,7 +143,7 @@ const pyb_i2c_obj_t pyb_i2c_obj[] = { {PYB_I2C_SPEED_STANDARD, 0x40912732}, \ {PYB_I2C_SPEED_FULL, 0x10911823}, \ {PYB_I2C_SPEED_FAST, 0x00611116}, \ - } +} #define MICROPY_HW_I2C_BAUDRATE_DEFAULT (PYB_I2C_SPEED_FULL) #define MICROPY_HW_I2C_BAUDRATE_MAX (PYB_I2C_SPEED_FAST) @@ -157,7 +157,7 @@ const pyb_i2c_obj_t pyb_i2c_obj[] = { {PYB_I2C_SPEED_STANDARD, 0xb0420f13}, \ {PYB_I2C_SPEED_FULL, 0x70330309}, \ {PYB_I2C_SPEED_FAST, 0x50100103}, \ - } +} #define MICROPY_HW_I2C_BAUDRATE_DEFAULT (PYB_I2C_SPEED_FULL) #define MICROPY_HW_I2C_BAUDRATE_MAX (PYB_I2C_SPEED_FAST) @@ -168,7 +168,7 @@ const pyb_i2c_obj_t pyb_i2c_obj[] = { {PYB_I2C_SPEED_STANDARD, 0x40604E73}, \ {PYB_I2C_SPEED_FULL, 0x00901954}, \ {PYB_I2C_SPEED_FAST, 0x10810915}, \ - } +} #define MICROPY_HW_I2C_BAUDRATE_DEFAULT (PYB_I2C_SPEED_FULL) #define MICROPY_HW_I2C_BAUDRATE_MAX (PYB_I2C_SPEED_FAST) @@ -185,8 +185,8 @@ const pyb_i2c_obj_t pyb_i2c_obj[] = { #endif STATIC const struct { - uint32_t baudrate; - uint32_t timing; + uint32_t baudrate; + uint32_t timing; } pyb_i2c_baudrate_timing[] = MICROPY_HW_I2C_BAUDRATE_TIMING; #define NUM_BAUDRATE_TIMINGS MP_ARRAY_SIZE(pyb_i2c_baudrate_timing) @@ -199,7 +199,7 @@ STATIC void i2c_set_baudrate(I2C_InitTypeDef *init, uint32_t baudrate) { } } nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, - "Unsupported I2C baudrate: %u", baudrate)); + "Unsupported I2C baudrate: %u", baudrate)); } uint32_t pyb_i2c_get_baudrate(I2C_HandleTypeDef *i2c) { @@ -376,12 +376,12 @@ void i2c_deinit(I2C_HandleTypeDef *i2c) { void pyb_i2c_init_freq(const pyb_i2c_obj_t *self, mp_int_t freq) { I2C_InitTypeDef *init = &self->i2c->Init; - init->AddressingMode = I2C_ADDRESSINGMODE_7BIT; - init->DualAddressMode = I2C_DUALADDRESS_DISABLED; - init->GeneralCallMode = I2C_GENERALCALL_DISABLED; - init->NoStretchMode = I2C_NOSTRETCH_DISABLE; - init->OwnAddress1 = PYB_I2C_MASTER_ADDRESS; - init->OwnAddress2 = 0; // unused + init->AddressingMode = I2C_ADDRESSINGMODE_7BIT; + init->DualAddressMode = I2C_DUALADDRESS_DISABLED; + init->GeneralCallMode = I2C_GENERALCALL_DISABLED; + init->NoStretchMode = I2C_NOSTRETCH_DISABLE; + init->OwnAddress1 = PYB_I2C_MASTER_ADDRESS; + init->OwnAddress2 = 0; // unused if (freq != -1) { i2c_set_baudrate(init, MIN(freq, MICROPY_HW_I2C_BAUDRATE_MAX)); } @@ -540,24 +540,35 @@ STATIC HAL_StatusTypeDef i2c_wait_dma_finished(I2C_HandleTypeDef *i2c, uint32_t /******************************************************************************/ /* MicroPython bindings */ -static inline bool in_master_mode(pyb_i2c_obj_t *self) { return self->i2c->Init.OwnAddress1 == PYB_I2C_MASTER_ADDRESS; } +static inline bool in_master_mode(pyb_i2c_obj_t *self) { + return self->i2c->Init.OwnAddress1 == PYB_I2C_MASTER_ADDRESS; +} STATIC void pyb_i2c_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { pyb_i2c_obj_t *self = MP_OBJ_TO_PTR(self_in); uint i2c_num = 0; - if (0) { } + if (0) { + } #if defined(MICROPY_HW_I2C1_SCL) - else if (self->i2c->Instance == I2C1) { i2c_num = 1; } + else if (self->i2c->Instance == I2C1) { + i2c_num = 1; + } #endif #if defined(MICROPY_HW_I2C2_SCL) - else if (self->i2c->Instance == I2C2) { i2c_num = 2; } + else if (self->i2c->Instance == I2C2) { + i2c_num = 2; + } #endif #if defined(MICROPY_HW_I2C3_SCL) - else if (self->i2c->Instance == I2C3) { i2c_num = 3; } + else if (self->i2c->Instance == I2C3) { + i2c_num = 3; + } #endif #if defined(MICROPY_HW_I2C4_SCL) - else if (self->i2c->Instance == I2C4) { i2c_num = 4; } + else if (self->i2c->Instance == I2C4) { + i2c_num = 4; + } #endif if (self->i2c->State == HAL_I2C_STATE_RESET) { @@ -603,11 +614,11 @@ STATIC mp_obj_t pyb_i2c_init_helper(const pyb_i2c_obj_t *self, size_t n_args, co } i2c_set_baudrate(init, MIN(args[2].u_int, MICROPY_HW_I2C_BAUDRATE_MAX)); - init->AddressingMode = I2C_ADDRESSINGMODE_7BIT; + init->AddressingMode = I2C_ADDRESSINGMODE_7BIT; init->DualAddressMode = I2C_DUALADDRESS_DISABLED; init->GeneralCallMode = args[3].u_bool ? I2C_GENERALCALL_ENABLED : I2C_GENERALCALL_DISABLED; - init->OwnAddress2 = 0; // unused - init->NoStretchMode = I2C_NOSTRETCH_DISABLE; + init->OwnAddress2 = 0; // unused + init->NoStretchMode = I2C_NOSTRETCH_DISABLE; *self->use_dma = args[4].u_bool; @@ -862,17 +873,17 @@ STATIC mp_obj_t pyb_i2c_recv(size_t n_args, const mp_obj_t *pos_args, mp_map_t * } mp_uint_t i2c_addr = args[1].u_int << 1; if (!use_dma) { - status = HAL_I2C_Master_Receive(self->i2c, i2c_addr, (uint8_t*)vstr.buf, vstr.len, args[2].u_int); + status = HAL_I2C_Master_Receive(self->i2c, i2c_addr, (uint8_t *)vstr.buf, vstr.len, args[2].u_int); } else { MP_HAL_CLEANINVALIDATE_DCACHE(vstr.buf, vstr.len); - status = HAL_I2C_Master_Receive_DMA(self->i2c, i2c_addr, (uint8_t*)vstr.buf, vstr.len); + status = HAL_I2C_Master_Receive_DMA(self->i2c, i2c_addr, (uint8_t *)vstr.buf, vstr.len); } } else { if (!use_dma) { - status = HAL_I2C_Slave_Receive(self->i2c, (uint8_t*)vstr.buf, vstr.len, args[2].u_int); + status = HAL_I2C_Slave_Receive(self->i2c, (uint8_t *)vstr.buf, vstr.len, args[2].u_int); } else { MP_HAL_CLEANINVALIDATE_DCACHE(vstr.buf, vstr.len); - status = HAL_I2C_Slave_Receive_DMA(self->i2c, (uint8_t*)vstr.buf, vstr.len); + status = HAL_I2C_Slave_Receive_DMA(self->i2c, (uint8_t *)vstr.buf, vstr.len); } } @@ -946,14 +957,14 @@ STATIC mp_obj_t pyb_i2c_mem_read(size_t n_args, const mp_obj_t *pos_args, mp_map HAL_StatusTypeDef status; if (!use_dma) { - status = HAL_I2C_Mem_Read(self->i2c, i2c_addr, mem_addr, mem_addr_size, (uint8_t*)vstr.buf, vstr.len, args[3].u_int); + status = HAL_I2C_Mem_Read(self->i2c, i2c_addr, mem_addr, mem_addr_size, (uint8_t *)vstr.buf, vstr.len, args[3].u_int); } else { DMA_HandleTypeDef rx_dma; dma_init(&rx_dma, self->rx_dma_descr, DMA_PERIPH_TO_MEMORY, self->i2c); self->i2c->hdmatx = NULL; self->i2c->hdmarx = &rx_dma; MP_HAL_CLEANINVALIDATE_DCACHE(vstr.buf, vstr.len); - status = HAL_I2C_Mem_Read_DMA(self->i2c, i2c_addr, mem_addr, mem_addr_size, (uint8_t*)vstr.buf, vstr.len); + status = HAL_I2C_Mem_Read_DMA(self->i2c, i2c_addr, mem_addr, mem_addr_size, (uint8_t *)vstr.buf, vstr.len); if (status == HAL_OK) { status = i2c_wait_dma_finished(self->i2c, args[3].u_int); } @@ -1063,7 +1074,7 @@ const mp_obj_type_t pyb_i2c_type = { .name = MP_QSTR_I2C, .print = pyb_i2c_print, .make_new = pyb_i2c_make_new, - .locals_dict = (mp_obj_dict_t*)&pyb_i2c_locals_dict, + .locals_dict = (mp_obj_dict_t *)&pyb_i2c_locals_dict, }; #endif // MICROPY_PY_PYB_LEGACY && MICROPY_HW_ENABLE_HW_I2C diff --git a/ports/stm32/pyb_spi.c b/ports/stm32/pyb_spi.c index e76369973c..fb1d455725 100644 --- a/ports/stm32/pyb_spi.c +++ b/ports/stm32/pyb_spi.c @@ -223,7 +223,7 @@ STATIC mp_obj_t pyb_spi_recv(size_t n_args, const mp_obj_t *pos_args, mp_map_t * mp_obj_t o_ret = pyb_buf_get_for_recv(args[0].u_obj, &vstr); // receive the data - spi_transfer(self->spi, vstr.len, NULL, (uint8_t*)vstr.buf, args[1].u_int); + spi_transfer(self->spi, vstr.len, NULL, (uint8_t *)vstr.buf, args[1].u_int); // return the received data if (o_ret != MP_OBJ_NULL) { @@ -339,7 +339,7 @@ STATIC const mp_rom_map_elem_t pyb_spi_locals_dict_table[] = { STATIC MP_DEFINE_CONST_DICT(pyb_spi_locals_dict, pyb_spi_locals_dict_table); STATIC void spi_transfer_machine(mp_obj_base_t *self_in, size_t len, const uint8_t *src, uint8_t *dest) { - pyb_spi_obj_t *self = (pyb_spi_obj_t*)self_in; + pyb_spi_obj_t *self = (pyb_spi_obj_t *)self_in; spi_transfer(self->spi, len, src, dest, SPI_TRANSFER_TIMEOUT(len)); } @@ -353,5 +353,5 @@ const mp_obj_type_t pyb_spi_type = { .print = pyb_spi_print, .make_new = pyb_spi_make_new, .protocol = &pyb_spi_p, - .locals_dict = (mp_obj_dict_t*)&pyb_spi_locals_dict, + .locals_dict = (mp_obj_dict_t *)&pyb_spi_locals_dict, }; diff --git a/ports/stm32/pybthread.c b/ports/stm32/pybthread.c index 6baf88f66b..8e8e5c0406 100644 --- a/ports/stm32/pybthread.c +++ b/ports/stm32/pybthread.c @@ -34,15 +34,15 @@ #if MICROPY_PY_THREAD -#define PYB_MUTEX_UNLOCKED ((void*)0) -#define PYB_MUTEX_LOCKED ((void*)1) +#define PYB_MUTEX_UNLOCKED ((void *)0) +#define PYB_MUTEX_LOCKED ((void *)1) // These macros are used when we only need to protect against a thread // switch; other interrupts are still allowed to proceed. #define RAISE_IRQ_PRI() raise_irq_pri(IRQ_PRI_PENDSV) #define RESTORE_IRQ_PRI(state) restore_irq_pri(state) -extern void __fatal_error(const char*); +extern void __fatal_error(const char *); volatile int pyb_thread_enabled; pyb_thread_t *volatile pyb_thread_all; @@ -94,7 +94,7 @@ STATIC void pyb_thread_terminate(void) { // take current thread off the run list pyb_thread_remove_from_runable(thread); // take current thread off the list of all threads - for (pyb_thread_t **n = (pyb_thread_t**)&pyb_thread_all;; n = &(*n)->all_next) { + for (pyb_thread_t **n = (pyb_thread_t **)&pyb_thread_all;; n = &(*n)->all_next) { if (*n == thread) { *n = thread->all_next; break; @@ -116,7 +116,7 @@ STATIC void pyb_thread_terminate(void) { } uint32_t pyb_thread_new(pyb_thread_t *thread, void *stack, size_t stack_len, void *entry, void *arg) { - uint32_t *stack_top = (uint32_t*)stack + stack_len; // stack is full descending + uint32_t *stack_top = (uint32_t *)stack + stack_len; // stack is full descending *--stack_top = 0x01000000; // xPSR (thumb bit set) *--stack_top = (uint32_t)entry & 0xfffffffe; // pc (must have bit 0 cleared, even for thumb code) *--stack_top = (uint32_t)pyb_thread_terminate; // lr diff --git a/ports/stm32/pybthread.h b/ports/stm32/pybthread.h index 42300508c9..8e5ce2570c 100644 --- a/ports/stm32/pybthread.h +++ b/ports/stm32/pybthread.h @@ -59,7 +59,7 @@ static inline void pyb_thread_set_local(void *value) { } static inline void *pyb_thread_get_local(void) { - return (void*)pyb_thread_cur->local_state; + return (void *)pyb_thread_cur->local_state; } static inline void pyb_thread_yield(void) { diff --git a/ports/stm32/qspi.c b/ports/stm32/qspi.c index a7cbbde014..c656c4fbec 100644 --- a/ports/stm32/qspi.c +++ b/ports/stm32/qspi.c @@ -47,7 +47,7 @@ void qspi_init(void) { QUADSPI->CR = 2 << QUADSPI_CR_PRESCALER_Pos // F_CLK = F_AHB/3 (72MHz when CPU is 216MHz) - | 3 << QUADSPI_CR_FTHRES_Pos // 4 bytes must be available to read/write + | 3 << QUADSPI_CR_FTHRES_Pos // 4 bytes must be available to read/write #if defined(QUADSPI_CR_FSEL_Pos) | 0 << QUADSPI_CR_FSEL_Pos // FLASH 1 selected #endif @@ -55,15 +55,15 @@ void qspi_init(void) { | 0 << QUADSPI_CR_DFM_Pos // dual-flash mode disabled #endif | 0 << QUADSPI_CR_SSHIFT_Pos // no sample shift - | 1 << QUADSPI_CR_TCEN_Pos // timeout counter enabled - | 1 << QUADSPI_CR_EN_Pos // enable the peripheral - ; + | 1 << QUADSPI_CR_TCEN_Pos // timeout counter enabled + | 1 << QUADSPI_CR_EN_Pos // enable the peripheral + ; QUADSPI->DCR = (MICROPY_HW_QSPIFLASH_SIZE_BITS_LOG2 - 3 - 1) << QUADSPI_DCR_FSIZE_Pos - | 1 << QUADSPI_DCR_CSHT_Pos // nCS stays high for 2 cycles - | 0 << QUADSPI_DCR_CKMODE_Pos // CLK idles at low state - ; + | 1 << QUADSPI_DCR_CSHT_Pos // nCS stays high for 2 cycles + | 0 << QUADSPI_DCR_CKMODE_Pos // CLK idles at low state + ; } void qspi_memory_map(void) { @@ -73,17 +73,17 @@ void qspi_memory_map(void) { QUADSPI->LPTR = 100; // to tune QUADSPI->CCR = 0 << QUADSPI_CCR_DDRM_Pos // DDR mode disabled - | 0 << QUADSPI_CCR_SIOO_Pos // send instruction every transaction - | 3 << QUADSPI_CCR_FMODE_Pos // memory-mapped mode - | 3 << QUADSPI_CCR_DMODE_Pos // data on 4 lines - | 4 << QUADSPI_CCR_DCYC_Pos // 4 dummy cycles - | 0 << QUADSPI_CCR_ABSIZE_Pos // 8-bit alternate byte - | 3 << QUADSPI_CCR_ABMODE_Pos // alternate byte on 4 lines - | 2 << QUADSPI_CCR_ADSIZE_Pos // 24-bit address size - | 3 << QUADSPI_CCR_ADMODE_Pos // address on 4 lines - | 1 << QUADSPI_CCR_IMODE_Pos // instruction on 1 line - | 0xeb << QUADSPI_CCR_INSTRUCTION_Pos // quad read opcode - ; + | 0 << QUADSPI_CCR_SIOO_Pos // send instruction every transaction + | 3 << QUADSPI_CCR_FMODE_Pos // memory-mapped mode + | 3 << QUADSPI_CCR_DMODE_Pos // data on 4 lines + | 4 << QUADSPI_CCR_DCYC_Pos // 4 dummy cycles + | 0 << QUADSPI_CCR_ABSIZE_Pos // 8-bit alternate byte + | 3 << QUADSPI_CCR_ABMODE_Pos // alternate byte on 4 lines + | 2 << QUADSPI_CCR_ADSIZE_Pos // 24-bit address size + | 3 << QUADSPI_CCR_ADMODE_Pos // address on 4 lines + | 1 << QUADSPI_CCR_IMODE_Pos // instruction on 1 line + | 0xeb << QUADSPI_CCR_INSTRUCTION_Pos // quad read opcode + ; } STATIC int qspi_ioctl(void *self_in, uint32_t cmd) { @@ -108,32 +108,32 @@ STATIC void qspi_write_cmd_data(void *self_in, uint8_t cmd, size_t len, uint32_t if (len == 0) { QUADSPI->CCR = 0 << QUADSPI_CCR_DDRM_Pos // DDR mode disabled - | 0 << QUADSPI_CCR_SIOO_Pos // send instruction every transaction - | 0 << QUADSPI_CCR_FMODE_Pos // indirect write mode - | 0 << QUADSPI_CCR_DMODE_Pos // no data - | 0 << QUADSPI_CCR_DCYC_Pos // 0 dummy cycles - | 0 << QUADSPI_CCR_ABMODE_Pos // no alternate byte - | 0 << QUADSPI_CCR_ADMODE_Pos // no address - | 1 << QUADSPI_CCR_IMODE_Pos // instruction on 1 line - | cmd << QUADSPI_CCR_INSTRUCTION_Pos // write opcode - ; + | 0 << QUADSPI_CCR_SIOO_Pos // send instruction every transaction + | 0 << QUADSPI_CCR_FMODE_Pos // indirect write mode + | 0 << QUADSPI_CCR_DMODE_Pos // no data + | 0 << QUADSPI_CCR_DCYC_Pos // 0 dummy cycles + | 0 << QUADSPI_CCR_ABMODE_Pos // no alternate byte + | 0 << QUADSPI_CCR_ADMODE_Pos // no address + | 1 << QUADSPI_CCR_IMODE_Pos // instruction on 1 line + | cmd << QUADSPI_CCR_INSTRUCTION_Pos // write opcode + ; } else { QUADSPI->DLR = len - 1; QUADSPI->CCR = 0 << QUADSPI_CCR_DDRM_Pos // DDR mode disabled - | 0 << QUADSPI_CCR_SIOO_Pos // send instruction every transaction - | 0 << QUADSPI_CCR_FMODE_Pos // indirect write mode - | 1 << QUADSPI_CCR_DMODE_Pos // data on 1 line - | 0 << QUADSPI_CCR_DCYC_Pos // 0 dummy cycles - | 0 << QUADSPI_CCR_ABMODE_Pos // no alternate byte - | 0 << QUADSPI_CCR_ADMODE_Pos // no address - | 1 << QUADSPI_CCR_IMODE_Pos // instruction on 1 line - | cmd << QUADSPI_CCR_INSTRUCTION_Pos // write opcode - ; + | 0 << QUADSPI_CCR_SIOO_Pos // send instruction every transaction + | 0 << QUADSPI_CCR_FMODE_Pos // indirect write mode + | 1 << QUADSPI_CCR_DMODE_Pos // data on 1 line + | 0 << QUADSPI_CCR_DCYC_Pos // 0 dummy cycles + | 0 << QUADSPI_CCR_ABMODE_Pos // no alternate byte + | 0 << QUADSPI_CCR_ADMODE_Pos // no address + | 1 << QUADSPI_CCR_IMODE_Pos // instruction on 1 line + | cmd << QUADSPI_CCR_INSTRUCTION_Pos // write opcode + ; // This assumes len==2 - *(uint16_t*)&QUADSPI->DR = data; + *(uint16_t *)&QUADSPI->DR = data; } // Wait for write to finish @@ -151,16 +151,16 @@ STATIC void qspi_write_cmd_addr_data(void *self_in, uint8_t cmd, uint32_t addr, if (len == 0) { QUADSPI->CCR = 0 << QUADSPI_CCR_DDRM_Pos // DDR mode disabled - | 0 << QUADSPI_CCR_SIOO_Pos // send instruction every transaction - | 0 << QUADSPI_CCR_FMODE_Pos // indirect write mode - | 0 << QUADSPI_CCR_DMODE_Pos // no data - | 0 << QUADSPI_CCR_DCYC_Pos // 0 dummy cycles - | 0 << QUADSPI_CCR_ABMODE_Pos // no alternate byte - | 2 << QUADSPI_CCR_ADSIZE_Pos // 24-bit address size - | 1 << QUADSPI_CCR_ADMODE_Pos // address on 1 line - | 1 << QUADSPI_CCR_IMODE_Pos // instruction on 1 line - | cmd << QUADSPI_CCR_INSTRUCTION_Pos // write opcode - ; + | 0 << QUADSPI_CCR_SIOO_Pos // send instruction every transaction + | 0 << QUADSPI_CCR_FMODE_Pos // indirect write mode + | 0 << QUADSPI_CCR_DMODE_Pos // no data + | 0 << QUADSPI_CCR_DCYC_Pos // 0 dummy cycles + | 0 << QUADSPI_CCR_ABMODE_Pos // no alternate byte + | 2 << QUADSPI_CCR_ADSIZE_Pos // 24-bit address size + | 1 << QUADSPI_CCR_ADMODE_Pos // address on 1 line + | 1 << QUADSPI_CCR_IMODE_Pos // instruction on 1 line + | cmd << QUADSPI_CCR_INSTRUCTION_Pos // write opcode + ; QUADSPI->AR = addr; } else { @@ -168,16 +168,16 @@ STATIC void qspi_write_cmd_addr_data(void *self_in, uint8_t cmd, uint32_t addr, QUADSPI->CCR = 0 << QUADSPI_CCR_DDRM_Pos // DDR mode disabled - | 0 << QUADSPI_CCR_SIOO_Pos // send instruction every transaction - | 0 << QUADSPI_CCR_FMODE_Pos // indirect write mode - | 1 << QUADSPI_CCR_DMODE_Pos // data on 1 line - | 0 << QUADSPI_CCR_DCYC_Pos // 0 dummy cycles - | 0 << QUADSPI_CCR_ABMODE_Pos // no alternate byte - | 2 << QUADSPI_CCR_ADSIZE_Pos // 24-bit address size - | 1 << QUADSPI_CCR_ADMODE_Pos // address on 1 line - | 1 << QUADSPI_CCR_IMODE_Pos // instruction on 1 line - | cmd << QUADSPI_CCR_INSTRUCTION_Pos // write opcode - ; + | 0 << QUADSPI_CCR_SIOO_Pos // send instruction every transaction + | 0 << QUADSPI_CCR_FMODE_Pos // indirect write mode + | 1 << QUADSPI_CCR_DMODE_Pos // data on 1 line + | 0 << QUADSPI_CCR_DCYC_Pos // 0 dummy cycles + | 0 << QUADSPI_CCR_ABMODE_Pos // no alternate byte + | 2 << QUADSPI_CCR_ADSIZE_Pos // 24-bit address size + | 1 << QUADSPI_CCR_ADMODE_Pos // address on 1 line + | 1 << QUADSPI_CCR_IMODE_Pos // instruction on 1 line + | cmd << QUADSPI_CCR_INSTRUCTION_Pos // write opcode + ; QUADSPI->AR = addr; @@ -185,7 +185,7 @@ STATIC void qspi_write_cmd_addr_data(void *self_in, uint8_t cmd, uint32_t addr, while (len) { while (!(QUADSPI->SR & QUADSPI_SR_FTF)) { } - *(volatile uint8_t*)&QUADSPI->DR = *src++; + *(volatile uint8_t *)&QUADSPI->DR = *src++; --len; } } @@ -206,15 +206,15 @@ STATIC uint32_t qspi_read_cmd(void *self_in, uint8_t cmd, size_t len) { QUADSPI->CCR = 0 << QUADSPI_CCR_DDRM_Pos // DDR mode disabled - | 0 << QUADSPI_CCR_SIOO_Pos // send instruction every transaction - | 1 << QUADSPI_CCR_FMODE_Pos // indirect read mode - | 1 << QUADSPI_CCR_DMODE_Pos // data on 1 line - | 0 << QUADSPI_CCR_DCYC_Pos // 0 dummy cycles - | 0 << QUADSPI_CCR_ABMODE_Pos // no alternate byte - | 0 << QUADSPI_CCR_ADMODE_Pos // no address - | 1 << QUADSPI_CCR_IMODE_Pos // instruction on 1 line - | cmd << QUADSPI_CCR_INSTRUCTION_Pos // read opcode - ; + | 0 << QUADSPI_CCR_SIOO_Pos // send instruction every transaction + | 1 << QUADSPI_CCR_FMODE_Pos // indirect read mode + | 1 << QUADSPI_CCR_DMODE_Pos // data on 1 line + | 0 << QUADSPI_CCR_DCYC_Pos // 0 dummy cycles + | 0 << QUADSPI_CCR_ABMODE_Pos // no alternate byte + | 0 << QUADSPI_CCR_ADMODE_Pos // no address + | 1 << QUADSPI_CCR_IMODE_Pos // instruction on 1 line + | cmd << QUADSPI_CCR_INSTRUCTION_Pos // read opcode + ; // Wait for read to finish while (!(QUADSPI->SR & QUADSPI_SR_TCF)) { @@ -234,17 +234,17 @@ STATIC void qspi_read_cmd_qaddr_qdata(void *self_in, uint8_t cmd, uint32_t addr, QUADSPI->CCR = 0 << QUADSPI_CCR_DDRM_Pos // DDR mode disabled - | 0 << QUADSPI_CCR_SIOO_Pos // send instruction every transaction - | 1 << QUADSPI_CCR_FMODE_Pos // indirect read mode - | 3 << QUADSPI_CCR_DMODE_Pos // data on 4 lines - | 4 << QUADSPI_CCR_DCYC_Pos // 4 dummy cycles - | 0 << QUADSPI_CCR_ABSIZE_Pos // 8-bit alternate byte - | 3 << QUADSPI_CCR_ABMODE_Pos // alternate byte on 4 lines - | 2 << QUADSPI_CCR_ADSIZE_Pos // 24-bit address size - | 3 << QUADSPI_CCR_ADMODE_Pos // address on 4 lines - | 1 << QUADSPI_CCR_IMODE_Pos // instruction on 1 line - | cmd << QUADSPI_CCR_INSTRUCTION_Pos // quad read opcode - ; + | 0 << QUADSPI_CCR_SIOO_Pos // send instruction every transaction + | 1 << QUADSPI_CCR_FMODE_Pos // indirect read mode + | 3 << QUADSPI_CCR_DMODE_Pos // data on 4 lines + | 4 << QUADSPI_CCR_DCYC_Pos // 4 dummy cycles + | 0 << QUADSPI_CCR_ABSIZE_Pos // 8-bit alternate byte + | 3 << QUADSPI_CCR_ABMODE_Pos // alternate byte on 4 lines + | 2 << QUADSPI_CCR_ADSIZE_Pos // 24-bit address size + | 3 << QUADSPI_CCR_ADMODE_Pos // address on 4 lines + | 1 << QUADSPI_CCR_IMODE_Pos // instruction on 1 line + | cmd << QUADSPI_CCR_INSTRUCTION_Pos // quad read opcode + ; QUADSPI->ABR = 0; // alternate byte: disable continuous read mode QUADSPI->AR = addr; // addres to read from @@ -254,7 +254,7 @@ STATIC void qspi_read_cmd_qaddr_qdata(void *self_in, uint8_t cmd, uint32_t addr, while (len >= 4) { while (!(QUADSPI->SR & QUADSPI_SR_FTF)) { } - *(uint32_t*)dest = QUADSPI->DR; + *(uint32_t *)dest = QUADSPI->DR; dest += 4; len -= 4; } @@ -264,7 +264,7 @@ STATIC void qspi_read_cmd_qaddr_qdata(void *self_in, uint8_t cmd, uint32_t addr, while (len) { while (!((QUADSPI->SR >> QUADSPI_SR_FLEVEL_Pos) & 0x3f)) { } - *dest++ = *(volatile uint8_t*)&QUADSPI->DR; + *dest++ = *(volatile uint8_t *)&QUADSPI->DR; --len; } diff --git a/ports/stm32/qstrdefsport.h b/ports/stm32/qstrdefsport.h index 31220c5a42..8f6364327b 100644 --- a/ports/stm32/qstrdefsport.h +++ b/ports/stm32/qstrdefsport.h @@ -29,16 +29,16 @@ Q(boot.py) Q(main.py) // Entries for sys.path -Q(/flash) -Q(/flash/lib) -Q(/sd) -Q(/sd/lib) +Q(/ flash) +Q(/ flash / lib) +Q(/ sd) +Q(/ sd / lib) // for usb modes -Q(MSC+HID) -Q(VCP+MSC) -Q(VCP+HID) -Q(CDC+MSC) -Q(CDC+HID) +Q(MSC + HID) +Q(VCP + MSC) +Q(VCP + HID) +Q(CDC + MSC) +Q(CDC + HID) Q(/) diff --git a/ports/stm32/rtc.c b/ports/stm32/rtc.c index 1999dfb384..350b8b4194 100644 --- a/ports/stm32/rtc.c +++ b/ports/stm32/rtc.c @@ -76,7 +76,7 @@ STATIC bool rtc_need_init_finalise = false; // check if LSE exists // not well tested, should probably be removed STATIC bool lse_magic(void) { -#if 0 + #if 0 uint32_t mode_in = GPIOC->MODER & 0x3fffffff; uint32_t mode_out = mode_in | 0x40000000; GPIOC->MODER = mode_out; @@ -91,16 +91,17 @@ STATIC bool lse_magic(void) { while (i) { GPIOC->MODER = mode_out; GPIOC->MODER = mode_in; - for (j = 0; j < d; j++) ; + for (j = 0; j < d; j++) {; + } i--; if ((GPIOC->IDR & 0x8000) == 0) { tc++; } } return (tc < 0xff0)?true:false; -#else + #else return false; -#endif + #endif } void rtc_init_start(bool force_init) { @@ -193,14 +194,14 @@ void rtc_init_finalise() { // fresh reset; configure RTC Calendar RTC_CalendarConfig(); #if defined(STM32L4) - if(__HAL_RCC_GET_FLAG(RCC_FLAG_BORRST) != RESET) { + if (__HAL_RCC_GET_FLAG(RCC_FLAG_BORRST) != RESET) { #else - if(__HAL_RCC_GET_FLAG(RCC_FLAG_PORRST) != RESET) { - #endif + if (__HAL_RCC_GET_FLAG(RCC_FLAG_PORRST) != RESET) { + #endif // power on reset occurred rtc_info |= 0x10000; } - if(__HAL_RCC_GET_FLAG(RCC_FLAG_PINRST) != RESET) { + if (__HAL_RCC_GET_FLAG(RCC_FLAG_PINRST) != RESET) { // external reset occurred rtc_info |= 0x20000; } @@ -209,7 +210,7 @@ void rtc_init_finalise() { rtc_need_init_finalise = false; } -STATIC HAL_StatusTypeDef PYB_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) { +STATIC HAL_StatusTypeDef PYB_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) { /*------------------------------ LSI Configuration -------------------------*/ if ((RCC_OscInitStruct->OscillatorType & RCC_OSCILLATORTYPE_LSI) == RCC_OSCILLATORTYPE_LSI) { // Check the LSI State @@ -234,9 +235,9 @@ STATIC HAL_StatusTypeDef PYB_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruc uint32_t tickstart = HAL_GetTick(); #if defined(STM32F7) || defined(STM32L4) || defined(STM32H7) - //__HAL_RCC_PWR_CLK_ENABLE(); + // __HAL_RCC_PWR_CLK_ENABLE(); // Enable write access to Backup domain - //PWR->CR1 |= PWR_CR1_DBP; + // PWR->CR1 |= PWR_CR1_DBP; // Wait for Backup domain Write protection disable while ((PWR->CR1 & PWR_CR1_DBP) == RESET) { if (HAL_GetTick() - tickstart > RCC_DBP_TIMEOUT_VALUE) { @@ -245,7 +246,7 @@ STATIC HAL_StatusTypeDef PYB_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruc } #else // Enable write access to Backup domain - //PWR->CR |= PWR_CR_DBP; + // PWR->CR |= PWR_CR_DBP; // Wait for Backup domain Write protection disable while ((PWR->CR & PWR_CR_DBP) == RESET) { if (HAL_GetTick() - tickstart > RCC_DBP_TIMEOUT_VALUE) { @@ -292,7 +293,7 @@ STATIC HAL_StatusTypeDef PYB_RTC_Init(RTC_HandleTypeDef *hrtc) { return HAL_ERROR; } else { // Clear RTC_CR FMT, OSEL and POL Bits - hrtc->Instance->CR &= ((uint32_t)~(RTC_CR_FMT | RTC_CR_OSEL | RTC_CR_POL)); + hrtc->Instance->CR &= ((uint32_t) ~(RTC_CR_FMT | RTC_CR_OSEL | RTC_CR_POL)); // Set RTC_CR register hrtc->Instance->CR |= (uint32_t)(hrtc->Init.HourFormat | hrtc->Init.OutPut | hrtc->Init.OutPutPolarity); @@ -301,16 +302,16 @@ STATIC HAL_StatusTypeDef PYB_RTC_Init(RTC_HandleTypeDef *hrtc) { hrtc->Instance->PRER |= (uint32_t)(hrtc->Init.AsynchPrediv << 16); // Exit Initialization mode - hrtc->Instance->ISR &= (uint32_t)~RTC_ISR_INIT; + hrtc->Instance->ISR &= (uint32_t) ~RTC_ISR_INIT; #if defined(STM32L4) || defined(STM32H7) - hrtc->Instance->OR &= (uint32_t)~RTC_OR_ALARMOUTTYPE; + hrtc->Instance->OR &= (uint32_t) ~RTC_OR_ALARMOUTTYPE; hrtc->Instance->OR |= (uint32_t)(hrtc->Init.OutPutType); #elif defined(STM32F7) - hrtc->Instance->OR &= (uint32_t)~RTC_OR_ALARMTYPE; + hrtc->Instance->OR &= (uint32_t) ~RTC_OR_ALARMTYPE; hrtc->Instance->OR |= (uint32_t)(hrtc->Init.OutPutType); #else - hrtc->Instance->TAFCR &= (uint32_t)~RTC_TAFCR_ALARMOUTTYPE; + hrtc->Instance->TAFCR &= (uint32_t) ~RTC_TAFCR_ALARMOUTTYPE; hrtc->Instance->TAFCR |= (uint32_t)(hrtc->Init.OutPutType); #endif @@ -337,7 +338,7 @@ STATIC void PYB_RTC_MspInit_Kick(RTC_HandleTypeDef *hrtc, bool rtc_use_lse) { // configuration variable is set. Otherwise it uses LSI (internal osc). RCC_OscInitTypeDef RCC_OscInitStruct; - RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSI | RCC_OSCILLATORTYPE_LSE; + RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSI | RCC_OSCILLATORTYPE_LSE; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE; if (rtc_use_lse) { #if MICROPY_HW_RTC_USE_BYPASS @@ -365,7 +366,7 @@ STATIC HAL_StatusTypeDef PYB_RTC_MspInit_Finalise(RTC_HandleTypeDef *hrtc) { // we now have to wait for LSE ready or timeout uint32_t tickstart = rtc_startup_tick; while (__HAL_RCC_GET_FLAG(RCC_FLAG_LSERDY) == RESET) { - if ((HAL_GetTick() - tickstart ) > PYB_LSE_TIMEOUT_VALUE) { + if ((HAL_GetTick() - tickstart) > PYB_LSE_TIMEOUT_VALUE) { return HAL_TIMEOUT; } } @@ -373,7 +374,7 @@ STATIC HAL_StatusTypeDef PYB_RTC_MspInit_Finalise(RTC_HandleTypeDef *hrtc) { // we now have to wait for LSI ready or timeout uint32_t tickstart = rtc_startup_tick; while (__HAL_RCC_GET_FLAG(RCC_FLAG_LSIRDY) == RESET) { - if ((HAL_GetTick() - tickstart ) > PYB_LSI_TIMEOUT_VALUE) { + if ((HAL_GetTick() - tickstart) > PYB_LSI_TIMEOUT_VALUE) { return HAL_TIMEOUT; } } @@ -387,7 +388,7 @@ STATIC HAL_StatusTypeDef PYB_RTC_MspInit_Finalise(RTC_HandleTypeDef *hrtc) { PeriphClkInitStruct.RTCClockSelection = RCC_RTCCLKSOURCE_LSI; } if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct) != HAL_OK) { - //Error_Handler(); + // Error_Handler(); return HAL_ERROR; } @@ -404,7 +405,7 @@ STATIC void RTC_CalendarConfig(void) { date.Date = 1; date.WeekDay = RTC_WEEKDAY_THURSDAY; - if(HAL_RTC_SetDate(&RTCHandle, &date, RTC_FORMAT_BIN) != HAL_OK) { + if (HAL_RTC_SetDate(&RTCHandle, &date, RTC_FORMAT_BIN) != HAL_OK) { // init error return; } @@ -663,7 +664,7 @@ mp_obj_t pyb_rtc_wakeup(size_t n_args, const mp_obj_t *args) { NVIC_SetPriority(RTC_WKUP_IRQn, IRQ_PRI_RTC_WKUP); HAL_NVIC_EnableIRQ(RTC_WKUP_IRQn); - //printf("wut=%d wucksel=%d\n", wut, wucksel); + // printf("wut=%d wucksel=%d\n", wut, wucksel); } else { // clear WUTIE to disable interrupts RTC->CR &= ~RTC_CR_WUTIE; @@ -696,7 +697,7 @@ mp_obj_t pyb_rtc_calibration(size_t n_args, const mp_obj_t *args) { cal = mp_obj_get_int(args[1]); mp_uint_t cal_p, cal_m; if (cal < -511 || cal > 512) { -#if defined(MICROPY_HW_RTC_USE_CALOUT) && MICROPY_HW_RTC_USE_CALOUT + #if defined(MICROPY_HW_RTC_USE_CALOUT) && MICROPY_HW_RTC_USE_CALOUT if ((cal & 0xfffe) == 0x0ffe) { // turn on/off X18 (PC13) 512Hz output // Note: @@ -710,9 +711,9 @@ mp_obj_t pyb_rtc_calibration(size_t n_args, const mp_obj_t *args) { } else { mp_raise_ValueError("calibration value out of range"); } -#else + #else mp_raise_ValueError("calibration value out of range"); -#endif + #endif } if (cal > 0) { cal_p = RTC_SMOOTHCALIB_PLUSPULSES_SET; @@ -749,5 +750,5 @@ const mp_obj_type_t pyb_rtc_type = { { &mp_type_type }, .name = MP_QSTR_RTC, .make_new = pyb_rtc_make_new, - .locals_dict = (mp_obj_dict_t*)&pyb_rtc_locals_dict, + .locals_dict = (mp_obj_dict_t *)&pyb_rtc_locals_dict, }; diff --git a/ports/stm32/sdcard.c b/ports/stm32/sdcard.c index 1d49016e7d..de59c3f7e9 100644 --- a/ports/stm32/sdcard.c +++ b/ports/stm32/sdcard.c @@ -204,14 +204,14 @@ bool sdcard_power_on(void) { // SD device interface configuration sd_handle.Instance = SDIO; - sd_handle.Init.ClockEdge = SDIO_CLOCK_EDGE_RISING; + sd_handle.Init.ClockEdge = SDIO_CLOCK_EDGE_RISING; #ifndef STM32H7 - sd_handle.Init.ClockBypass = SDIO_CLOCK_BYPASS_DISABLE; + sd_handle.Init.ClockBypass = SDIO_CLOCK_BYPASS_DISABLE; #endif - sd_handle.Init.ClockPowerSave = SDIO_CLOCK_POWER_SAVE_ENABLE; - sd_handle.Init.BusWide = SDIO_BUS_WIDE_1B; + sd_handle.Init.ClockPowerSave = SDIO_CLOCK_POWER_SAVE_ENABLE; + sd_handle.Init.BusWide = SDIO_BUS_WIDE_1B; sd_handle.Init.HardwareFlowControl = SDIO_HARDWARE_FLOW_CONTROL_DISABLE; - sd_handle.Init.ClockDiv = SDIO_TRANSFER_CLK_DIV; + sd_handle.Init.ClockDiv = SDIO_TRANSFER_CLK_DIV; // init the SD interface, with retry if it's not ready yet for (int retry = 10; HAL_SD_Init(&sd_handle) != HAL_OK; retry--) { @@ -337,8 +337,8 @@ mp_uint_t sdcard_read_blocks(uint8_t *dest, uint32_t block_num, uint32_t num_blo // bytes at the aligned location should be able to be changed for the // duration of this function call. orig_dest = dest; - dest = (uint8_t*)((uint32_t)dest & ~3); - saved_word = *(uint32_t*)dest; + dest = (uint8_t *)((uint32_t)dest & ~3); + saved_word = *(uint32_t *)dest; } if (query_irq() == IRQ_STATE_ENABLED) { @@ -423,7 +423,7 @@ mp_uint_t sdcard_write_blocks(const uint8_t *src, uint32_t block_num, uint32_t n MP_HAL_CLEAN_DCACHE(src, num_blocks * SDCARD_BLOCK_SIZE); sdcard_reset_periph(); - err = HAL_SD_WriteBlocks_DMA(&sd_handle, (uint8_t*)src, block_num, num_blocks); + err = HAL_SD_WriteBlocks_DMA(&sd_handle, (uint8_t *)src, block_num, num_blocks); if (err == HAL_OK) { err = sdcard_wait_finished(&sd_handle, 60000); } @@ -435,7 +435,7 @@ mp_uint_t sdcard_write_blocks(const uint8_t *src, uint32_t block_num, uint32_t n restore_irq_pri(basepri); } else { - err = HAL_SD_WriteBlocks(&sd_handle, (uint8_t*)src, block_num, num_blocks, 60000); + err = HAL_SD_WriteBlocks(&sd_handle, (uint8_t *)src, block_num, num_blocks, 60000); if (err == HAL_OK) { err = sdcard_wait_finished(&sd_handle, 60000); } @@ -588,7 +588,7 @@ const mp_obj_type_t pyb_sdcard_type = { { &mp_type_type }, .name = MP_QSTR_SDCard, .make_new = pyb_sdcard_make_new, - .locals_dict = (mp_obj_dict_t*)&pyb_sdcard_locals_dict, + .locals_dict = (mp_obj_dict_t *)&pyb_sdcard_locals_dict, }; void sdcard_init_vfs(fs_user_mount_t *vfs, int part) { diff --git a/ports/stm32/sdram.c b/ports/stm32/sdram.c index 6350b1d954..901d085df1 100644 --- a/ports/stm32/sdram.c +++ b/ports/stm32/sdram.c @@ -42,7 +42,7 @@ #ifdef FMC_SDRAM_BANK static void sdram_init_seq(SDRAM_HandleTypeDef - *hsdram, FMC_SDRAM_CommandTypeDef *command); + *hsdram, FMC_SDRAM_CommandTypeDef *command); extern void __fatal_error(const char *msg); bool sdram_init(void) { @@ -127,36 +127,36 @@ bool sdram_init(void) { hsdram.Instance = FMC_SDRAM_DEVICE; /* Timing configuration for 90 Mhz of SD clock frequency (180Mhz/2) */ /* TMRD: 2 Clock cycles */ - SDRAM_Timing.LoadToActiveDelay = MICROPY_HW_SDRAM_TIMING_TMRD; + SDRAM_Timing.LoadToActiveDelay = MICROPY_HW_SDRAM_TIMING_TMRD; /* TXSR: min=70ns (6x11.90ns) */ SDRAM_Timing.ExitSelfRefreshDelay = MICROPY_HW_SDRAM_TIMING_TXSR; /* TRAS */ - SDRAM_Timing.SelfRefreshTime = MICROPY_HW_SDRAM_TIMING_TRAS; + SDRAM_Timing.SelfRefreshTime = MICROPY_HW_SDRAM_TIMING_TRAS; /* TRC */ - SDRAM_Timing.RowCycleDelay = MICROPY_HW_SDRAM_TIMING_TRC; + SDRAM_Timing.RowCycleDelay = MICROPY_HW_SDRAM_TIMING_TRC; /* TWR */ - SDRAM_Timing.WriteRecoveryTime = MICROPY_HW_SDRAM_TIMING_TWR; + SDRAM_Timing.WriteRecoveryTime = MICROPY_HW_SDRAM_TIMING_TWR; /* TRP */ - SDRAM_Timing.RPDelay = MICROPY_HW_SDRAM_TIMING_TRP; + SDRAM_Timing.RPDelay = MICROPY_HW_SDRAM_TIMING_TRP; /* TRCD */ - SDRAM_Timing.RCDDelay = MICROPY_HW_SDRAM_TIMING_TRCD; + SDRAM_Timing.RCDDelay = MICROPY_HW_SDRAM_TIMING_TRCD; - #define _FMC_INIT(x, n) x ## _ ## n + #define _FMC_INIT(x, n) x##_##n #define FMC_INIT(x, n) _FMC_INIT(x, n) - hsdram.Init.SDBank = FMC_SDRAM_BANK; - hsdram.Init.ColumnBitsNumber = FMC_INIT(FMC_SDRAM_COLUMN_BITS_NUM, MICROPY_HW_SDRAM_COLUMN_BITS_NUM); - hsdram.Init.RowBitsNumber = FMC_INIT(FMC_SDRAM_ROW_BITS_NUM, MICROPY_HW_SDRAM_ROW_BITS_NUM); - hsdram.Init.MemoryDataWidth = FMC_INIT(FMC_SDRAM_MEM_BUS_WIDTH, MICROPY_HW_SDRAM_MEM_BUS_WIDTH); + hsdram.Init.SDBank = FMC_SDRAM_BANK; + hsdram.Init.ColumnBitsNumber = FMC_INIT(FMC_SDRAM_COLUMN_BITS_NUM, MICROPY_HW_SDRAM_COLUMN_BITS_NUM); + hsdram.Init.RowBitsNumber = FMC_INIT(FMC_SDRAM_ROW_BITS_NUM, MICROPY_HW_SDRAM_ROW_BITS_NUM); + hsdram.Init.MemoryDataWidth = FMC_INIT(FMC_SDRAM_MEM_BUS_WIDTH, MICROPY_HW_SDRAM_MEM_BUS_WIDTH); hsdram.Init.InternalBankNumber = FMC_INIT(FMC_SDRAM_INTERN_BANKS_NUM, MICROPY_HW_SDRAM_INTERN_BANKS_NUM); - hsdram.Init.CASLatency = FMC_INIT(FMC_SDRAM_CAS_LATENCY, MICROPY_HW_SDRAM_CAS_LATENCY); - hsdram.Init.SDClockPeriod = FMC_INIT(FMC_SDRAM_CLOCK_PERIOD, MICROPY_HW_SDRAM_CLOCK_PERIOD); - hsdram.Init.ReadPipeDelay = FMC_INIT(FMC_SDRAM_RPIPE_DELAY, MICROPY_HW_SDRAM_RPIPE_DELAY); - hsdram.Init.ReadBurst = (MICROPY_HW_SDRAM_RBURST) ? FMC_SDRAM_RBURST_ENABLE : FMC_SDRAM_RBURST_DISABLE; - hsdram.Init.WriteProtection = (MICROPY_HW_SDRAM_WRITE_PROTECTION) ? FMC_SDRAM_WRITE_PROTECTION_ENABLE : FMC_SDRAM_WRITE_PROTECTION_DISABLE; + hsdram.Init.CASLatency = FMC_INIT(FMC_SDRAM_CAS_LATENCY, MICROPY_HW_SDRAM_CAS_LATENCY); + hsdram.Init.SDClockPeriod = FMC_INIT(FMC_SDRAM_CLOCK_PERIOD, MICROPY_HW_SDRAM_CLOCK_PERIOD); + hsdram.Init.ReadPipeDelay = FMC_INIT(FMC_SDRAM_RPIPE_DELAY, MICROPY_HW_SDRAM_RPIPE_DELAY); + hsdram.Init.ReadBurst = (MICROPY_HW_SDRAM_RBURST) ? FMC_SDRAM_RBURST_ENABLE : FMC_SDRAM_RBURST_DISABLE; + hsdram.Init.WriteProtection = (MICROPY_HW_SDRAM_WRITE_PROTECTION) ? FMC_SDRAM_WRITE_PROTECTION_ENABLE : FMC_SDRAM_WRITE_PROTECTION_DISABLE; /* Initialize the SDRAM controller */ - if(HAL_SDRAM_Init(&hsdram, &SDRAM_Timing) != HAL_OK) { + if (HAL_SDRAM_Init(&hsdram, &SDRAM_Timing) != HAL_OK) { return false; } @@ -165,23 +165,22 @@ bool sdram_init(void) { } void *sdram_start(void) { - return (void*)SDRAM_START_ADDRESS; + return (void *)SDRAM_START_ADDRESS; } void *sdram_end(void) { - return (void*)(SDRAM_START_ADDRESS + MICROPY_HW_SDRAM_SIZE); + return (void *)(SDRAM_START_ADDRESS + MICROPY_HW_SDRAM_SIZE); } static void sdram_init_seq(SDRAM_HandleTypeDef - *hsdram, FMC_SDRAM_CommandTypeDef *command) -{ + *hsdram, FMC_SDRAM_CommandTypeDef *command) { /* Program the SDRAM external device */ - __IO uint32_t tmpmrd =0; + __IO uint32_t tmpmrd = 0; /* Step 3: Configure a clock configuration enable command */ - command->CommandMode = FMC_SDRAM_CMD_CLK_ENABLE; - command->CommandTarget = FMC_SDRAM_CMD_TARGET_BANK; - command->AutoRefreshNumber = 1; + command->CommandMode = FMC_SDRAM_CMD_CLK_ENABLE; + command->CommandTarget = FMC_SDRAM_CMD_TARGET_BANK; + command->AutoRefreshNumber = 1; command->ModeRegisterDefinition = 0; /* Send the command */ @@ -191,18 +190,18 @@ static void sdram_init_seq(SDRAM_HandleTypeDef HAL_Delay(100); /* Step 5: Configure a PALL (precharge all) command */ - command->CommandMode = FMC_SDRAM_CMD_PALL; - command->CommandTarget = FMC_SDRAM_CMD_TARGET_BANK; - command->AutoRefreshNumber = 1; + command->CommandMode = FMC_SDRAM_CMD_PALL; + command->CommandTarget = FMC_SDRAM_CMD_TARGET_BANK; + command->AutoRefreshNumber = 1; command->ModeRegisterDefinition = 0; /* Send the command */ HAL_SDRAM_SendCommand(hsdram, command, 0x1000); /* Step 6 : Configure a Auto-Refresh command */ - command->CommandMode = FMC_SDRAM_CMD_AUTOREFRESH_MODE; - command->CommandTarget = FMC_SDRAM_CMD_TARGET_BANK; - command->AutoRefreshNumber = MICROPY_HW_SDRAM_AUTOREFRESH_NUM; + command->CommandMode = FMC_SDRAM_CMD_AUTOREFRESH_MODE; + command->CommandTarget = FMC_SDRAM_CMD_TARGET_BANK; + command->AutoRefreshNumber = MICROPY_HW_SDRAM_AUTOREFRESH_NUM; command->ModeRegisterDefinition = 0; /* Send the command */ @@ -210,14 +209,14 @@ static void sdram_init_seq(SDRAM_HandleTypeDef /* Step 7: Program the external memory mode register */ tmpmrd = (uint32_t)FMC_INIT(SDRAM_MODEREG_BURST_LENGTH, MICROPY_HW_SDRAM_BURST_LENGTH) | - SDRAM_MODEREG_BURST_TYPE_SEQUENTIAL | + SDRAM_MODEREG_BURST_TYPE_SEQUENTIAL | FMC_INIT(SDRAM_MODEREG_CAS_LATENCY, MICROPY_HW_SDRAM_CAS_LATENCY) | SDRAM_MODEREG_OPERATING_MODE_STANDARD | SDRAM_MODEREG_WRITEBURST_MODE_SINGLE; - command->CommandMode = FMC_SDRAM_CMD_LOAD_MODE; - command->CommandTarget = FMC_SDRAM_CMD_TARGET_BANK; - command->AutoRefreshNumber = 1; + command->CommandMode = FMC_SDRAM_CMD_LOAD_MODE; + command->CommandTarget = FMC_SDRAM_CMD_TARGET_BANK; + command->AutoRefreshNumber = 1; command->ModeRegisterDefinition = tmpmrd; /* Send the command */ @@ -266,7 +265,7 @@ static void sdram_init_seq(SDRAM_HandleTypeDef bool __attribute__((optimize("O0"))) sdram_test(bool fast) { uint8_t const pattern = 0xaa; uint8_t const antipattern = 0x55; - uint8_t *const mem_base = (uint8_t*)sdram_start(); + uint8_t *const mem_base = (uint8_t *)sdram_start(); /* test data bus */ for (uint8_t i = 1; i; i <<= 1) { diff --git a/ports/stm32/servo.c b/ports/stm32/servo.c index 691c8037f5..c353874de1 100644 --- a/ports/stm32/servo.c +++ b/ports/stm32/servo.c @@ -125,7 +125,7 @@ void servo_timer_irq_callback(void) { STATIC void servo_init_channel(pyb_servo_obj_t *s) { static const uint8_t channel_table[4] = - {TIM_CHANNEL_1, TIM_CHANNEL_2, TIM_CHANNEL_3, TIM_CHANNEL_4}; + {TIM_CHANNEL_1, TIM_CHANNEL_2, TIM_CHANNEL_3, TIM_CHANNEL_4}; uint32_t channel = channel_table[s->pin->pin]; // GPIO configuration @@ -153,13 +153,25 @@ STATIC void servo_init_channel(pyb_servo_obj_t *s) { STATIC mp_obj_t pyb_servo_set(mp_obj_t port, mp_obj_t value) { int p = mp_obj_get_int(port); int v = mp_obj_get_int(value); - if (v < 50) { v = 50; } - if (v > 250) { v = 250; } + if (v < 50) { + v = 50; + } + if (v > 250) { + v = 250; + } switch (p) { - case 1: TIM5->CCR1 = v; break; - case 2: TIM5->CCR2 = v; break; - case 3: TIM5->CCR3 = v; break; - case 4: TIM5->CCR4 = v; break; + case 1: + TIM5->CCR1 = v; + break; + case 2: + TIM5->CCR2 = v; + break; + case 3: + TIM5->CCR3 = v; + break; + case 4: + TIM5->CCR4 = v; + break; } return mp_const_none; } @@ -265,11 +277,11 @@ STATIC mp_obj_t pyb_servo_angle(size_t n_args, const mp_obj_t *args) { // get angle return mp_obj_new_int((self->pulse_cur - self->pulse_centre) * 90 / self->pulse_angle_90); } else { -#if MICROPY_PY_BUILTINS_FLOAT + #if MICROPY_PY_BUILTINS_FLOAT self->pulse_dest = self->pulse_centre + self->pulse_angle_90 * mp_obj_get_float(args[1]) / 90.0; -#else + #else self->pulse_dest = self->pulse_centre + self->pulse_angle_90 * mp_obj_get_int(args[1]) / 90; -#endif + #endif if (n_args == 2) { // set angle immediately self->time_left = 0; @@ -295,11 +307,11 @@ STATIC mp_obj_t pyb_servo_speed(size_t n_args, const mp_obj_t *args) { // get speed return mp_obj_new_int((self->pulse_cur - self->pulse_centre) * 100 / self->pulse_speed_100); } else { -#if MICROPY_PY_BUILTINS_FLOAT + #if MICROPY_PY_BUILTINS_FLOAT self->pulse_dest = self->pulse_centre + self->pulse_speed_100 * mp_obj_get_float(args[1]) / 100.0; -#else + #else self->pulse_dest = self->pulse_centre + self->pulse_speed_100 * mp_obj_get_int(args[1]) / 100; -#endif + #endif if (n_args == 2) { // set speed immediately self->time_left = 0; @@ -329,7 +341,7 @@ const mp_obj_type_t pyb_servo_type = { .name = MP_QSTR_Servo, .print = pyb_servo_print, .make_new = pyb_servo_make_new, - .locals_dict = (mp_obj_dict_t*)&pyb_servo_locals_dict, + .locals_dict = (mp_obj_dict_t *)&pyb_servo_locals_dict, }; #endif // MICROPY_HW_ENABLE_SERVO diff --git a/ports/stm32/spi.c b/ports/stm32/spi.c index ae97d9ab40..e576c81ad3 100644 --- a/ports/stm32/spi.c +++ b/ports/stm32/spi.c @@ -201,14 +201,23 @@ void spi_set_params(const spi_t *spi_obj, uint32_t prescale, int32_t baudrate, #endif prescale = (spi_clock + baudrate - 1) / baudrate; } - if (prescale <= 2) { init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_2; } - else if (prescale <= 4) { init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_4; } - else if (prescale <= 8) { init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_8; } - else if (prescale <= 16) { init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_16; } - else if (prescale <= 32) { init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_32; } - else if (prescale <= 64) { init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_64; } - else if (prescale <= 128) { init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_128; } - else { init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_256; } + if (prescale <= 2) { + init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_2; + } else if (prescale <= 4) { + init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_4; + } else if (prescale <= 8) { + init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_8; + } else if (prescale <= 16) { + init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_16; + } else if (prescale <= 32) { + init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_32; + } else if (prescale <= 64) { + init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_64; + } else if (prescale <= 128) { + init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_128; + } else { + init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_256; + } } if (polarity != -1) { @@ -416,7 +425,7 @@ void spi_transfer(const spi_t *self, size_t len, const uint8_t *src, uint8_t *de if (dest == NULL) { // send only if (len == 1 || query_irq() == IRQ_STATE_DISABLED) { - status = HAL_SPI_Transmit(self->spi, (uint8_t*)src, len, timeout); + status = HAL_SPI_Transmit(self->spi, (uint8_t *)src, len, timeout); } else { DMA_HandleTypeDef tx_dma; dma_init(&tx_dma, self->tx_dma_descr, DMA_MEMORY_TO_PERIPH, self->spi); @@ -426,7 +435,7 @@ void spi_transfer(const spi_t *self, size_t len, const uint8_t *src, uint8_t *de uint32_t t_start = HAL_GetTick(); do { uint32_t l = MIN(len, 65535); - status = HAL_SPI_Transmit_DMA(self->spi, (uint8_t*)src, l); + status = HAL_SPI_Transmit_DMA(self->spi, (uint8_t *)src, l); if (status != HAL_OK) { break; } @@ -477,7 +486,7 @@ void spi_transfer(const spi_t *self, size_t len, const uint8_t *src, uint8_t *de } else { // send and receive if (len == 1 || query_irq() == IRQ_STATE_DISABLED) { - status = HAL_SPI_TransmitReceive(self->spi, (uint8_t*)src, dest, len, timeout); + status = HAL_SPI_TransmitReceive(self->spi, (uint8_t *)src, dest, len, timeout); } else { DMA_HandleTypeDef tx_dma, rx_dma; dma_init(&tx_dma, self->tx_dma_descr, DMA_MEMORY_TO_PERIPH, self->spi); @@ -489,7 +498,7 @@ void spi_transfer(const spi_t *self, size_t len, const uint8_t *src, uint8_t *de uint32_t t_start = HAL_GetTick(); do { uint32_t l = MIN(len, 65535); - status = HAL_SPI_TransmitReceive_DMA(self->spi, (uint8_t*)src, dest, l); + status = HAL_SPI_TransmitReceive_DMA(self->spi, (uint8_t *)src, dest, l); if (status != HAL_OK) { break; } @@ -515,21 +524,32 @@ void spi_print(const mp_print_t *print, const spi_t *spi_obj, bool legacy) { SPI_HandleTypeDef *spi = spi_obj->spi; uint spi_num = 1; // default to SPI1 - if (0) { } + if (0) { + } #if defined(SPI2) - else if (spi->Instance == SPI2) { spi_num = 2; } + else if (spi->Instance == SPI2) { + spi_num = 2; + } #endif #if defined(SPI3) - else if (spi->Instance == SPI3) { spi_num = 3; } + else if (spi->Instance == SPI3) { + spi_num = 3; + } #endif #if defined(SPI4) - else if (spi->Instance == SPI4) { spi_num = 4; } + else if (spi->Instance == SPI4) { + spi_num = 4; + } #endif #if defined(SPI5) - else if (spi->Instance == SPI5) { spi_num = 5; } + else if (spi->Instance == SPI5) { + spi_num = 5; + } #endif #if defined(SPI6) - else if (spi->Instance == SPI6) { spi_num = 6; } + else if (spi->Instance == SPI6) { + spi_num = 6; + } #endif mp_printf(print, "SPI(%u", spi_num); @@ -598,7 +618,7 @@ const spi_t *spi_from_mp_obj(mp_obj_t o) { // Implementation of low-level SPI C protocol STATIC int spi_proto_ioctl(void *self_in, uint32_t cmd) { - spi_proto_cfg_t *self = (spi_proto_cfg_t*)self_in; + spi_proto_cfg_t *self = (spi_proto_cfg_t *)self_in; switch (cmd) { case MP_SPI_IOCTL_INIT: @@ -621,7 +641,7 @@ STATIC int spi_proto_ioctl(void *self_in, uint32_t cmd) { } STATIC void spi_proto_transfer(void *self_in, size_t len, const uint8_t *src, uint8_t *dest) { - spi_proto_cfg_t *self = (spi_proto_cfg_t*)self_in; + spi_proto_cfg_t *self = (spi_proto_cfg_t *)self_in; spi_transfer(self->spi, len, src, dest, SPI_TRANSFER_TIMEOUT(len)); } diff --git a/ports/stm32/spibdev.c b/ports/stm32/spibdev.c index 9b5a10b400..a7250b5d7d 100644 --- a/ports/stm32/spibdev.c +++ b/ports/stm32/spibdev.c @@ -35,7 +35,7 @@ int32_t spi_bdev_ioctl(spi_bdev_t *bdev, uint32_t op, uint32_t arg) { switch (op) { case BDEV_IOCTL_INIT: - bdev->spiflash.config = (const mp_spiflash_config_t*)arg; + bdev->spiflash.config = (const mp_spiflash_config_t *)arg; mp_spiflash_init(&bdev->spiflash); bdev->flash_tick_counter_last_write = 0; return 0; diff --git a/ports/stm32/stm32_it.c b/ports/stm32/stm32_it.c index 026082eb98..d5eac3b7d8 100644 --- a/ports/stm32/stm32_it.c +++ b/ports/stm32/stm32_it.c @@ -83,7 +83,7 @@ #include "i2c.h" #include "usb.h" -extern void __fatal_error(const char*); +extern void __fatal_error(const char *); #if defined(MICROPY_HW_USB_FS) extern PCD_HandleTypeDef pcd_fs_handle; #endif @@ -107,9 +107,9 @@ STATIC char *fmt_hex(uint32_t val, char *buf) { buf[2] = hexDig[(val >> 20) & 0x0f]; buf[3] = hexDig[(val >> 16) & 0x0f]; buf[4] = hexDig[(val >> 12) & 0x0f]; - buf[5] = hexDig[(val >> 8) & 0x0f]; - buf[6] = hexDig[(val >> 4) & 0x0f]; - buf[7] = hexDig[(val >> 0) & 0x0f]; + buf[5] = hexDig[(val >> 8) & 0x0f]; + buf[6] = hexDig[(val >> 4) & 0x0f]; + buf[7] = hexDig[(val >> 0) & 0x0f]; buf[8] = '\0'; return buf; @@ -137,7 +137,7 @@ STATIC void print_hex_hex(const char *label, uint32_t val1, uint32_t val2) { // // stack: R0, R1, R2, R3, R12, LR, PC, XPSR typedef struct { - uint32_t r0, r1, r2, r3, r12, lr, pc, xpsr; + uint32_t r0, r1, r2, r3, r12, lr, pc, xpsr; } ExceptionRegisters_t; int pyb_hard_fault_debug = 0; @@ -178,14 +178,14 @@ void HardFault_C_Handler(ExceptionRegisters_t *regs) { } #endif - if ((void*)&_ram_start <= (void*)regs && (void*)regs < (void*)&_ram_end) { + if ((void *)&_ram_start <= (void *)regs && (void *)regs < (void *)&_ram_end) { mp_hal_stdout_tx_str("Stack:\r\n"); uint32_t *stack_top = &_estack; - if ((void*)regs < (void*)&_heap_end) { + if ((void *)regs < (void *)&_heap_end) { // stack not in static stack area so limit the amount we print - stack_top = (uint32_t*)regs + 32; + stack_top = (uint32_t *)regs + 32; } - for (uint32_t *sp = (uint32_t*)regs; sp < stack_top; ++sp) { + for (uint32_t *sp = (uint32_t *)regs; sp < stack_top; ++sp) { print_hex_hex(" ", (uint32_t)sp, *sp); } } @@ -210,23 +210,23 @@ void HardFault_Handler(void) { // was stacked up using the process stack pointer (aka PSP). #if __CORTEX_M == 0 - __asm volatile( - " mov r0, lr \n" - " lsr r0, r0, #3 \n" // Shift Bit 3 into carry to see which stack pointer we should use. - " mrs r0, msp \n" // Make R0 point to main stack pointer - " bcc .use_msp \n" // Keep MSP in R0 if SPSEL (carry) is 0 - " mrs r0, psp \n" // Make R0 point to process stack pointer - " .use_msp: \n" - " b HardFault_C_Handler \n" // Off to C land - ); + __asm volatile ( + " mov r0, lr \n" + " lsr r0, r0, #3 \n" // Shift Bit 3 into carry to see which stack pointer we should use. + " mrs r0, msp \n" // Make R0 point to main stack pointer + " bcc .use_msp \n" // Keep MSP in R0 if SPSEL (carry) is 0 + " mrs r0, psp \n" // Make R0 point to process stack pointer + " .use_msp: \n" + " b HardFault_C_Handler \n" // Off to C land + ); #else - __asm volatile( - " tst lr, #4 \n" // Test Bit 3 to see which stack pointer we should use. - " ite eq \n" // Tell the assembler that the nest 2 instructions are if-then-else - " mrseq r0, msp \n" // Make R0 point to main stack pointer - " mrsne r0, psp \n" // Make R0 point to process stack pointer - " b HardFault_C_Handler \n" // Off to C land - ); + __asm volatile ( + " tst lr, #4 \n" // Test Bit 3 to see which stack pointer we should use. + " ite eq \n" // Tell the assembler that the nest 2 instructions are if-then-else + " mrseq r0, msp \n" // Make R0 point to main stack pointer + " mrsne r0, psp \n" // Make R0 point to process stack pointer + " b HardFault_C_Handler \n" // Off to C land + ); #endif } @@ -382,40 +382,40 @@ void OTG_HS_IRQHandler(void) { */ STATIC void OTG_CMD_WKUP_Handler(PCD_HandleTypeDef *pcd_handle) { - if (pcd_handle->Init.low_power_enable) { - /* Reset SLEEPDEEP bit of Cortex System Control Register */ - SCB->SCR &= (uint32_t)~((uint32_t)(SCB_SCR_SLEEPDEEP_Msk | SCB_SCR_SLEEPONEXIT_Msk)); + if (pcd_handle->Init.low_power_enable) { + /* Reset SLEEPDEEP bit of Cortex System Control Register */ + SCB->SCR &= (uint32_t) ~((uint32_t)(SCB_SCR_SLEEPDEEP_Msk | SCB_SCR_SLEEPONEXIT_Msk)); - /* Configures system clock after wake-up from STOP: enable HSE, PLL and select - PLL as system clock source (HSE and PLL are disabled in STOP mode) */ + /* Configures system clock after wake-up from STOP: enable HSE, PLL and select + PLL as system clock source (HSE and PLL are disabled in STOP mode) */ - __HAL_RCC_HSE_CONFIG(MICROPY_HW_CLK_HSE_STATE); + __HAL_RCC_HSE_CONFIG(MICROPY_HW_CLK_HSE_STATE); - /* Wait till HSE is ready */ - while(__HAL_RCC_GET_FLAG(RCC_FLAG_HSERDY) == RESET) - {} + /* Wait till HSE is ready */ + while (__HAL_RCC_GET_FLAG(RCC_FLAG_HSERDY) == RESET) { + } - /* Enable the main PLL. */ - __HAL_RCC_PLL_ENABLE(); + /* Enable the main PLL. */ + __HAL_RCC_PLL_ENABLE(); - /* Wait till PLL is ready */ - while(__HAL_RCC_GET_FLAG(RCC_FLAG_PLLRDY) == RESET) - {} + /* Wait till PLL is ready */ + while (__HAL_RCC_GET_FLAG(RCC_FLAG_PLLRDY) == RESET) { + } - /* Select PLL as SYSCLK */ - MODIFY_REG(RCC->CFGR, RCC_CFGR_SW, RCC_SYSCLKSOURCE_PLLCLK); + /* Select PLL as SYSCLK */ + MODIFY_REG(RCC->CFGR, RCC_CFGR_SW, RCC_SYSCLKSOURCE_PLLCLK); - #if defined(STM32H7) - while (__HAL_RCC_GET_SYSCLK_SOURCE() != RCC_CFGR_SWS_PLL1) - {} - #else - while (__HAL_RCC_GET_SYSCLK_SOURCE() != RCC_CFGR_SWS_PLL) - {} - #endif + #if defined(STM32H7) + while (__HAL_RCC_GET_SYSCLK_SOURCE() != RCC_CFGR_SWS_PLL1) { + } + #else + while (__HAL_RCC_GET_SYSCLK_SOURCE() != RCC_CFGR_SWS_PLL) { + } + #endif - /* ungate PHY clock */ - __HAL_PCD_UNGATE_PHYCLOCK(pcd_handle); - } + /* ungate PHY clock */ + __HAL_PCD_UNGATE_PHYCLOCK(pcd_handle); + } } #endif @@ -429,10 +429,10 @@ STATIC void OTG_CMD_WKUP_Handler(PCD_HandleTypeDef *pcd_handle) { void OTG_FS_WKUP_IRQHandler(void) { IRQ_ENTER(OTG_FS_WKUP_IRQn); - OTG_CMD_WKUP_Handler(&pcd_fs_handle); + OTG_CMD_WKUP_Handler(&pcd_fs_handle); - /* Clear EXTI pending Bit*/ - __HAL_USB_FS_EXTI_CLEAR_FLAG(); + /* Clear EXTI pending Bit*/ + __HAL_USB_FS_EXTI_CLEAR_FLAG(); IRQ_EXIT(OTG_FS_WKUP_IRQn); } @@ -447,10 +447,10 @@ void OTG_FS_WKUP_IRQHandler(void) { void OTG_HS_WKUP_IRQHandler(void) { IRQ_ENTER(OTG_HS_WKUP_IRQn); - OTG_CMD_WKUP_Handler(&pcd_hs_handle); + OTG_CMD_WKUP_Handler(&pcd_hs_handle); - /* Clear EXTI pending Bit*/ - __HAL_USB_HS_EXTI_CLEAR_FLAG(); + /* Clear EXTI pending Bit*/ + __HAL_USB_HS_EXTI_CLEAR_FLAG(); IRQ_EXIT(OTG_HS_WKUP_IRQn); } @@ -559,7 +559,7 @@ void RTC_Alarm_IRQHandler(void) { } #if defined(ETH) // The 407 has ETH, the 405 doesn't -void ETH_WKUP_IRQHandler(void) { +void ETH_WKUP_IRQHandler(void) { IRQ_ENTER(ETH_WKUP_IRQn); Handle_EXTI_Irq(EXTI_ETH_WAKEUP); IRQ_EXIT(ETH_WKUP_IRQn); diff --git a/ports/stm32/storage.c b/ports/stm32/storage.c index 7724ae0f42..c863d71959 100644 --- a/ports/stm32/storage.c +++ b/ports/stm32/storage.c @@ -124,7 +124,7 @@ static void build_partition(uint8_t *buf, int boot, int type, uint32_t start_blo } bool storage_read_block(uint8_t *dest, uint32_t block) { - //printf("RD %u\n", block); + // printf("RD %u\n", block); if (block == 0) { // fake the MBR so we can decide on our own partition table @@ -156,7 +156,7 @@ bool storage_read_block(uint8_t *dest, uint32_t block) { } bool storage_write_block(const uint8_t *src, uint32_t block) { - //printf("WR %u\n", block); + // printf("WR %u\n", block); if (block == 0) { // can't write MBR, but pretend we did return true; @@ -246,12 +246,21 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_3(pyb_flash_writeblocks_obj, pyb_flash_writeblock STATIC mp_obj_t pyb_flash_ioctl(mp_obj_t self, mp_obj_t cmd_in, mp_obj_t arg_in) { mp_int_t cmd = mp_obj_get_int(cmd_in); switch (cmd) { - case BP_IOCTL_INIT: storage_init(); return MP_OBJ_NEW_SMALL_INT(0); - case BP_IOCTL_DEINIT: storage_flush(); return MP_OBJ_NEW_SMALL_INT(0); // TODO properly - case BP_IOCTL_SYNC: storage_flush(); return MP_OBJ_NEW_SMALL_INT(0); - case BP_IOCTL_SEC_COUNT: return MP_OBJ_NEW_SMALL_INT(storage_get_block_count()); - case BP_IOCTL_SEC_SIZE: return MP_OBJ_NEW_SMALL_INT(storage_get_block_size()); - default: return mp_const_none; + case BP_IOCTL_INIT: + storage_init(); + return MP_OBJ_NEW_SMALL_INT(0); + case BP_IOCTL_DEINIT: + storage_flush(); + return MP_OBJ_NEW_SMALL_INT(0); // TODO properly + case BP_IOCTL_SYNC: + storage_flush(); + return MP_OBJ_NEW_SMALL_INT(0); + case BP_IOCTL_SEC_COUNT: + return MP_OBJ_NEW_SMALL_INT(storage_get_block_count()); + case BP_IOCTL_SEC_SIZE: + return MP_OBJ_NEW_SMALL_INT(storage_get_block_size()); + default: + return mp_const_none; } } STATIC MP_DEFINE_CONST_FUN_OBJ_3(pyb_flash_ioctl_obj, pyb_flash_ioctl); @@ -268,7 +277,7 @@ const mp_obj_type_t pyb_flash_type = { { &mp_type_type }, .name = MP_QSTR_Flash, .make_new = pyb_flash_make_new, - .locals_dict = (mp_obj_dict_t*)&pyb_flash_locals_dict, + .locals_dict = (mp_obj_dict_t *)&pyb_flash_locals_dict, }; void pyb_flash_init_vfs(fs_user_mount_t *vfs) { diff --git a/ports/stm32/system_stm32.c b/ports/stm32/system_stm32.c index e0e27cef09..5db04d9718 100644 --- a/ports/stm32/system_stm32.c +++ b/ports/stm32/system_stm32.c @@ -132,10 +132,10 @@ const uint8_t APBPrescTable[8] = {0, 0, 0, 0, 1, 2, 3, 4}; * hal_rcc-file!! * */ -const uint8_t AHBPrescTable[16] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 7, 8, 9}; -const uint8_t APBPrescTable[8] = {0, 0, 0, 0, 1, 2, 3, 4}; +const uint8_t AHBPrescTable[16] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 7, 8, 9}; +const uint8_t APBPrescTable[8] = {0, 0, 0, 0, 1, 2, 3, 4}; const uint32_t MSIRangeTable[12] = {100000, 200000, 400000, 800000, 1000000, 2000000, \ - 4000000, 8000000, 16000000, 24000000, 32000000, 48000000}; + 4000000, 8000000, 16000000, 24000000, 32000000, 48000000}; #elif defined(STM32H7) #define CONFIG_RCC_CR_1ST (RCC_CR_HSION) @@ -175,7 +175,7 @@ const uint8_t D1CorePrescTable[16] = {0, 0, 0, 0, 1, 2, 3, 4, 1, 2, 3, 4, 6, 7, /** @addtogroup STM32Fxxx_System_Private_Variables * @{ */ - /* This variable is updated in three ways: +/* This variable is updated in three ways: 1) by calling CMSIS function SystemCoreClockUpdate() 2) by calling HAL API function HAL_RCC_GetHCLKFreq() 3) each time HAL_RCC_ClockConfig() is called to configure the system clock frequency @@ -183,7 +183,7 @@ const uint8_t D1CorePrescTable[16] = {0, 0, 0, 0, 1, 2, 3, 4, 1, 2, 3, 4, 6, 7, is no need to call the 2 first functions listed above, since SystemCoreClock variable is updated automatically. */ - uint32_t SystemCoreClock = 16000000; +uint32_t SystemCoreClock = 16000000; /** * @} @@ -208,86 +208,85 @@ const uint8_t D1CorePrescTable[16] = {0, 0, 0, 0, 1, 2, 3, 4, 1, 2, 3, 4, 6, 7, * @param None * @retval None */ -void SystemInit(void) -{ - /* FPU settings ------------------------------------------------------------*/ - #if (__FPU_PRESENT == 1) && (__FPU_USED == 1) - SCB->CPACR |= ((3UL << 10*2)|(3UL << 11*2)); /* set CP10 and CP11 Full Access */ - #endif - /* Reset the RCC clock configuration to the default reset state ------------*/ +void SystemInit(void) { + /* FPU settings ------------------------------------------------------------*/ + #if (__FPU_PRESENT == 1) && (__FPU_USED == 1) + SCB->CPACR |= ((3UL << 10 * 2) | (3UL << 11 * 2)); /* set CP10 and CP11 Full Access */ + #endif + /* Reset the RCC clock configuration to the default reset state ------------*/ - /* Set configured startup clk source */ - RCC->CR |= CONFIG_RCC_CR_1ST; + /* Set configured startup clk source */ + RCC->CR |= CONFIG_RCC_CR_1ST; - /* Reset CFGR register */ - RCC->CFGR = 0x00000000; + /* Reset CFGR register */ + RCC->CFGR = 0x00000000; - /* Reset HSEON, CSSON and PLLON bits */ - RCC->CR &= ~ CONFIG_RCC_CR_2ND; + /* Reset HSEON, CSSON and PLLON bits */ + RCC->CR &= ~CONFIG_RCC_CR_2ND; - /* Reset PLLCFGR register */ - RCC->PLLCFGR = CONFIG_RCC_PLLCFGR; + /* Reset PLLCFGR register */ + RCC->PLLCFGR = CONFIG_RCC_PLLCFGR; - #if defined(STM32H7) - /* Reset D1CFGR register */ - RCC->D1CFGR = 0x00000000; + #if defined(STM32H7) + /* Reset D1CFGR register */ + RCC->D1CFGR = 0x00000000; - /* Reset D2CFGR register */ - RCC->D2CFGR = 0x00000000; + /* Reset D2CFGR register */ + RCC->D2CFGR = 0x00000000; - /* Reset D3CFGR register */ - RCC->D3CFGR = 0x00000000; + /* Reset D3CFGR register */ + RCC->D3CFGR = 0x00000000; - /* Reset PLLCKSELR register */ - RCC->PLLCKSELR = 0x00000000; + /* Reset PLLCKSELR register */ + RCC->PLLCKSELR = 0x00000000; - /* Reset PLL1DIVR register */ - RCC->PLL1DIVR = 0x00000000; + /* Reset PLL1DIVR register */ + RCC->PLL1DIVR = 0x00000000; - /* Reset PLL1FRACR register */ - RCC->PLL1FRACR = 0x00000000; + /* Reset PLL1FRACR register */ + RCC->PLL1FRACR = 0x00000000; - /* Reset PLL2DIVR register */ - RCC->PLL2DIVR = 0x00000000; + /* Reset PLL2DIVR register */ + RCC->PLL2DIVR = 0x00000000; - /* Reset PLL2FRACR register */ - RCC->PLL2FRACR = 0x00000000; + /* Reset PLL2FRACR register */ + RCC->PLL2FRACR = 0x00000000; - /* Reset PLL3DIVR register */ - RCC->PLL3DIVR = 0x00000000; + /* Reset PLL3DIVR register */ + RCC->PLL3DIVR = 0x00000000; - /* Reset PLL3FRACR register */ - RCC->PLL3FRACR = 0x00000000; - #endif + /* Reset PLL3FRACR register */ + RCC->PLL3FRACR = 0x00000000; + #endif - /* Reset HSEBYP bit */ - RCC->CR &= (uint32_t)0xFFFBFFFF; + /* Reset HSEBYP bit */ + RCC->CR &= (uint32_t)0xFFFBFFFF; - /* Disable all interrupts */ - #if defined(STM32F4) || defined(STM32F7) - RCC->CIR = 0x00000000; - #elif defined(STM32L4) || defined(STM32H7) - RCC->CIER = 0x00000000; - #endif + /* Disable all interrupts */ + #if defined(STM32F4) || defined(STM32F7) + RCC->CIR = 0x00000000; + #elif defined(STM32L4) || defined(STM32H7) + RCC->CIER = 0x00000000; + #endif - #if defined(STM32H7) - /* Change the switch matrix read issuing capability to 1 for the AXI SRAM target (Target 7) */ - *((__IO uint32_t*)0x51008108) = 0x00000001; - #endif + #if defined(STM32H7) + /* Change the switch matrix read issuing capability to 1 for the AXI SRAM target (Target 7) */ + *((__IO uint32_t *)0x51008108) = 0x00000001; + #endif - /* Configure the Vector Table location add offset address ------------------*/ -#ifdef MICROPY_HW_VTOR - SCB->VTOR = MICROPY_HW_VTOR; -#else -#ifdef VECT_TAB_SRAM - SCB->VTOR = SRAM1_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal SRAM */ -#else - SCB->VTOR = FLASH_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal FLASH */ -#endif -#endif + /* Configure the Vector Table location add offset address ------------------*/ + #ifdef MICROPY_HW_VTOR + SCB->VTOR = MICROPY_HW_VTOR; + #else + #ifdef VECT_TAB_SRAM + SCB->VTOR = SRAM1_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal SRAM */ + #else + SCB->VTOR = FLASH_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal FLASH */ + #endif + #endif - /* dpgeorge: enable 8-byte stack alignment for IRQ handlers, in accord with EABI */ - SCB->CCR |= SCB_CCR_STKALIGN_Msk; + /* dpgeorge: enable 8-byte stack alignment for IRQ handlers, in accord with EABI */ + SCB->CCR |= SCB_CCR_STKALIGN_Msk; } @@ -370,8 +369,7 @@ void SystemInit(void) * * Timers run from APBx if APBx_PRESC=1, else 2x APBx */ -void SystemClock_Config(void) -{ +void SystemClock_Config(void) { #if defined(STM32F7) // The DFU bootloader changes the clocksource register from its default power // on reset value, so we set it back here, so the clocksources are the same @@ -419,7 +417,7 @@ void SystemClock_Config(void) #endif RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE; #elif defined(STM32L4) - RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSE|RCC_OSCILLATORTYPE_MSI; + RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSE | RCC_OSCILLATORTYPE_MSI; RCC_OscInitStruct.LSEState = RCC_LSE_ON; RCC_OscInitStruct.MSIState = RCC_MSI_ON; RCC_OscInitStruct.MSICalibrationValue = RCC_MSICALIBRATION_DEFAULT; @@ -434,7 +432,7 @@ void SystemClock_Config(void) RCC_ClkInitStruct.ClockType |= (RCC_CLOCKTYPE_D3PCLK1 | RCC_CLOCKTYPE_D1PCLK1); #endif -#if defined(MICROPY_HW_CLK_LAST_FREQ) && MICROPY_HW_CLK_LAST_FREQ + #if defined(MICROPY_HW_CLK_LAST_FREQ) && MICROPY_HW_CLK_LAST_FREQ #if defined(STM32F7) #define FREQ_BKP BKP31R #elif defined(STM32L4) @@ -452,7 +450,7 @@ void SystemClock_Config(void) uint32_t b1 = (m >> 26) & 0x7; uint32_t b2 = (m >> 29) & 0x7; q = (m >> 18) & 0xf; - p = (((m >> 16) & 0x03)+1)*2; + p = (((m >> 16) & 0x03) + 1) * 2; n = (m >> 6) & 0x3ff; m &= 0x3f; if ((q < 2) || (q > 15) || (p > 8) || (p < 2) || (n < 192) || (n >= 433) || (m < 2)) { @@ -468,15 +466,15 @@ void SystemClock_Config(void) b1 <<= 10; b2 <<= 10; } - RCC_OscInitStruct.PLL.PLLM = m; //MICROPY_HW_CLK_PLLM; - RCC_OscInitStruct.PLL.PLLN = n; //MICROPY_HW_CLK_PLLN; - RCC_OscInitStruct.PLL.PLLP = p; //MICROPY_HW_CLK_PLLP; - RCC_OscInitStruct.PLL.PLLQ = q; //MICROPY_HW_CLK_PLLQ; + RCC_OscInitStruct.PLL.PLLM = m; // MICROPY_HW_CLK_PLLM; + RCC_OscInitStruct.PLL.PLLN = n; // MICROPY_HW_CLK_PLLN; + RCC_OscInitStruct.PLL.PLLP = p; // MICROPY_HW_CLK_PLLP; + RCC_OscInitStruct.PLL.PLLQ = q; // MICROPY_HW_CLK_PLLQ; - RCC_ClkInitStruct.AHBCLKDivider = h; //RCC_SYSCLK_DIV1; - RCC_ClkInitStruct.APB1CLKDivider = b1; //RCC_HCLK_DIV4; - RCC_ClkInitStruct.APB2CLKDivider = b2; //RCC_HCLK_DIV2; -#else // defined(MICROPY_HW_CLK_LAST_FREQ) && MICROPY_HW_CLK_LAST_FREQ + RCC_ClkInitStruct.AHBCLKDivider = h; // RCC_SYSCLK_DIV1; + RCC_ClkInitStruct.APB1CLKDivider = b1; // RCC_HCLK_DIV4; + RCC_ClkInitStruct.APB2CLKDivider = b2; // RCC_HCLK_DIV2; + #else // defined(MICROPY_HW_CLK_LAST_FREQ) && MICROPY_HW_CLK_LAST_FREQ RCC_OscInitStruct.PLL.PLLM = MICROPY_HW_CLK_PLLM; RCC_OscInitStruct.PLL.PLLN = MICROPY_HW_CLK_PLLN; RCC_OscInitStruct.PLL.PLLP = MICROPY_HW_CLK_PLLP; @@ -492,28 +490,28 @@ void SystemClock_Config(void) #endif #if defined(STM32F4) || defined(STM32F7) - RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; + RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4; RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2; #elif defined(STM32L4) - RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; + RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1; RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; #elif defined(STM32H7) - RCC_ClkInitStruct.SYSCLKDivider = RCC_SYSCLK_DIV1; - RCC_ClkInitStruct.AHBCLKDivider = RCC_HCLK_DIV2; + RCC_ClkInitStruct.SYSCLKDivider = RCC_SYSCLK_DIV1; + RCC_ClkInitStruct.AHBCLKDivider = RCC_HCLK_DIV2; RCC_ClkInitStruct.APB3CLKDivider = RCC_APB3_DIV2; RCC_ClkInitStruct.APB1CLKDivider = RCC_APB1_DIV2; RCC_ClkInitStruct.APB2CLKDivider = RCC_APB2_DIV2; RCC_ClkInitStruct.APB4CLKDivider = RCC_APB4_DIV2; #endif -#endif + #endif - if(HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { - __fatal_error("HAL_RCC_OscConfig"); + if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { + __fatal_error("HAL_RCC_OscConfig"); } -#if defined(STM32H7) + #if defined(STM32H7) /* PLL3 for USB Clock */ PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_USB; PeriphClkInitStruct.UsbClockSelection = RCC_USBCLKSOURCE_PLL3; @@ -528,15 +526,14 @@ void SystemClock_Config(void) if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct) != HAL_OK) { __fatal_error("HAL_RCCEx_PeriphCLKConfig"); } -#endif + #endif -#if defined(STM32F7) - /* Activate the OverDrive to reach the 200 MHz Frequency */ - if (HAL_PWREx_EnableOverDrive() != HAL_OK) - { - __fatal_error("HAL_PWREx_EnableOverDrive"); - } -#endif + #if defined(STM32F7) + /* Activate the OverDrive to reach the 200 MHz Frequency */ + if (HAL_PWREx_EnableOverDrive() != HAL_OK) { + __fatal_error("HAL_PWREx_EnableOverDrive"); + } + #endif uint32_t vco_out = RCC_OscInitStruct.PLL.PLLN * (HSE_VALUE / 1000000) / RCC_OscInitStruct.PLL.PLLM; uint32_t sysclk_mhz = vco_out / RCC_OscInitStruct.PLL.PLLP; @@ -545,28 +542,28 @@ void SystemClock_Config(void) __fatal_error("HAL_RCC_ClockConfig"); } -#if defined(STM32H7) - /* Activate CSI clock mandatory for I/O Compensation Cell*/ - __HAL_RCC_CSI_ENABLE() ; + #if defined(STM32H7) + /* Activate CSI clock mandatory for I/O Compensation Cell*/ + __HAL_RCC_CSI_ENABLE(); - /* Enable SYSCFG clock mandatory for I/O Compensation Cell */ - __HAL_RCC_SYSCFG_CLK_ENABLE() ; + /* Enable SYSCFG clock mandatory for I/O Compensation Cell */ + __HAL_RCC_SYSCFG_CLK_ENABLE(); - /* Enable the I/O Compensation Cell */ - HAL_EnableCompensationCell(); + /* Enable the I/O Compensation Cell */ + HAL_EnableCompensationCell(); - /* Enable the USB voltage level detector */ - HAL_PWREx_EnableUSBVoltageDetector(); -#endif + /* Enable the USB voltage level detector */ + HAL_PWREx_EnableUSBVoltageDetector(); + #endif -#if defined(STM32L4) + #if defined(STM32L4) // Enable MSI-Hardware auto calibration mode with LSE HAL_RCCEx_EnableMSIPLLMode(); RCC_PeriphCLKInitTypeDef PeriphClkInitStruct; - PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_SAI1|RCC_PERIPHCLK_I2C1 - |RCC_PERIPHCLK_USB |RCC_PERIPHCLK_ADC - |RCC_PERIPHCLK_RNG |RCC_PERIPHCLK_RTC; + PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_SAI1 | RCC_PERIPHCLK_I2C1 + | RCC_PERIPHCLK_USB | RCC_PERIPHCLK_ADC + | RCC_PERIPHCLK_RNG | RCC_PERIPHCLK_RTC; PeriphClkInitStruct.I2c1ClockSelection = RCC_I2C1CLKSOURCE_PCLK1; /* PLLSAI is used to clock USB, ADC, I2C1 and RNG. The frequency is MSI(4MHz)/PLLM(1)*PLLSAI1N(24)/PLLSAIQ(2) = 48MHz. See the STM32CubeMx @@ -583,11 +580,10 @@ void SystemClock_Config(void) PeriphClkInitStruct.PLLSAI1.PLLSAI1Q = RCC_PLLQ_DIV2; PeriphClkInitStruct.PLLSAI1.PLLSAI1R = RCC_PLLR_DIV2; PeriphClkInitStruct.PLLSAI1.PLLSAI1ClockOut = RCC_PLLSAI1_SAI1CLK - |RCC_PLLSAI1_48M2CLK - |RCC_PLLSAI1_ADC1CLK; + | RCC_PLLSAI1_48M2CLK + | RCC_PLLSAI1_ADC1CLK; - if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct) != HAL_OK) - { + if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct) != HAL_OK) { __fatal_error("HAL_RCCEx_PeriphCLKConfig"); } @@ -595,8 +591,8 @@ void SystemClock_Config(void) HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1); - HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq()/1000); + HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq() / 1000); HAL_SYSTICK_CLKSourceConfig(SYSTICK_CLKSOURCE_HCLK); NVIC_SetPriority(SysTick_IRQn, NVIC_EncodePriority(NVIC_PRIORITYGROUP_4, TICK_INT_PRIORITY, 0)); -#endif + #endif } diff --git a/ports/stm32/system_stm32f0.c b/ports/stm32/system_stm32f0.c index 9d4b06e568..2e54a490a2 100644 --- a/ports/stm32/system_stm32f0.c +++ b/ports/stm32/system_stm32f0.c @@ -65,7 +65,7 @@ uint32_t SystemCoreClock = 8000000; const uint8_t AHBPrescTable[16] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 7, 8, 9}; -const uint8_t APBPrescTable[8] = {0, 0, 0, 0, 1, 2, 3, 4}; +const uint8_t APBPrescTable[8] = {0, 0, 0, 0, 1, 2, 3, 4}; void SystemInit(void) { // Set HSION bit @@ -167,17 +167,17 @@ void SystemCoreClockUpdate(void) { if (pllsource == RCC_CFGR_PLLSRC_HSE_PREDIV) { /* HSE used as PLL clock source : SystemCoreClock = HSE/PREDIV * PLLMUL */ - SystemCoreClock = (HSE_VALUE/predivfactor) * pllmull; - #if defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F072xB) \ + SystemCoreClock = (HSE_VALUE / predivfactor) * pllmull; + #if defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F072xB) \ || defined(STM32F078xx) || defined(STM32F091xC) || defined(STM32F098xx) } else if (pllsource == RCC_CFGR_PLLSRC_HSI48_PREDIV) { /* HSI48 used as PLL clock source : SystemCoreClock = HSI48/PREDIV * PLLMUL */ - SystemCoreClock = (HSI48_VALUE/predivfactor) * pllmull; - #endif + SystemCoreClock = (HSI48_VALUE / predivfactor) * pllmull; + #endif } else { - #if defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F070x6) \ - || defined(STM32F078xx) || defined(STM32F071xB) || defined(STM32F072xB) \ - || defined(STM32F070xB) || defined(STM32F091xC) || defined(STM32F098xx) || defined(STM32F030xC) + #if defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F070x6) \ + || defined(STM32F078xx) || defined(STM32F071xB) || defined(STM32F072xB) \ + || defined(STM32F070xB) || defined(STM32F091xC) || defined(STM32F098xx) || defined(STM32F030xC) /* HSI used as PLL clock source : SystemCoreClock = HSI/PREDIV * PLLMUL */ SystemCoreClock = (HSI_VALUE / predivfactor) * pllmull; #else diff --git a/ports/stm32/systick.c b/ports/stm32/systick.c index c07d0fabce..077ca2ad2e 100644 --- a/ports/stm32/systick.c +++ b/ports/stm32/systick.c @@ -115,7 +115,7 @@ mp_uint_t mp_hal_ticks_us(void) { mp_uint_t irq_state = disable_irq(); uint32_t counter = SysTick->VAL; uint32_t milliseconds = HAL_GetTick(); - uint32_t status = SysTick->CTRL; + uint32_t status = SysTick->CTRL; enable_irq(irq_state); // It's still possible for the countflag bit to get set if the counter was diff --git a/ports/stm32/timer.c b/ports/stm32/timer.c index 983f7cbc6f..524afed036 100644 --- a/ports/stm32/timer.c +++ b/ports/stm32/timer.c @@ -95,8 +95,8 @@ typedef enum { } pyb_channel_mode; STATIC const struct { - qstr name; - uint32_t oc_mode; + qstr name; + uint32_t oc_mode; } channel_mode_info[] = { { MP_QSTR_PWM, TIM_OCMODE_PWM1 }, { MP_QSTR_PWM_INVERTED, TIM_OCMODE_PWM2 }, @@ -290,7 +290,7 @@ STATIC uint32_t compute_prescaler_period_from_freq(pyb_timer_obj_t *self, mp_obj mp_int_t freq = mp_obj_get_int(freq_in); if (freq <= 0) { goto bad_freq; - bad_freq: + bad_freq: mp_raise_ValueError("must have positive freq"); } period = source_freq / freq; @@ -464,13 +464,13 @@ STATIC mp_int_t compute_ticks_from_dtg(uint32_t dtg) { STATIC void config_deadtime(pyb_timer_obj_t *self, mp_int_t ticks) { TIM_BreakDeadTimeConfigTypeDef deadTimeConfig; - deadTimeConfig.OffStateRunMode = TIM_OSSR_DISABLE; + deadTimeConfig.OffStateRunMode = TIM_OSSR_DISABLE; deadTimeConfig.OffStateIDLEMode = TIM_OSSI_DISABLE; - deadTimeConfig.LockLevel = TIM_LOCKLEVEL_OFF; - deadTimeConfig.DeadTime = compute_dtg_from_ticks(ticks); - deadTimeConfig.BreakState = TIM_BREAK_DISABLE; - deadTimeConfig.BreakPolarity = TIM_BREAKPOLARITY_LOW; - deadTimeConfig.AutomaticOutput = TIM_AUTOMATICOUTPUT_DISABLE; + deadTimeConfig.LockLevel = TIM_LOCKLEVEL_OFF; + deadTimeConfig.DeadTime = compute_dtg_from_ticks(ticks); + deadTimeConfig.BreakState = TIM_BREAK_DISABLE; + deadTimeConfig.BreakPolarity = TIM_BREAKPOLARITY_LOW; + deadTimeConfig.AutomaticOutput = TIM_AUTOMATICOUTPUT_DISABLE; HAL_TIMEx_ConfigBreakDeadTime(&self->tim, &deadTimeConfig); } @@ -602,59 +602,93 @@ STATIC mp_obj_t pyb_timer_init_helper(pyb_timer_obj_t *self, size_t n_args, cons } init->ClockDivision = args[ARG_div].u_int == 2 ? TIM_CLOCKDIVISION_DIV2 : - args[ARG_div].u_int == 4 ? TIM_CLOCKDIVISION_DIV4 : - TIM_CLOCKDIVISION_DIV1; + args[ARG_div].u_int == 4 ? TIM_CLOCKDIVISION_DIV4 : + TIM_CLOCKDIVISION_DIV1; init->RepetitionCounter = 0; // enable TIM clock switch (self->tim_id) { - case 1: __HAL_RCC_TIM1_CLK_ENABLE(); break; - case 2: __HAL_RCC_TIM2_CLK_ENABLE(); break; + case 1: + __HAL_RCC_TIM1_CLK_ENABLE(); + break; + case 2: + __HAL_RCC_TIM2_CLK_ENABLE(); + break; #if defined(TIM3) - case 3: __HAL_RCC_TIM3_CLK_ENABLE(); break; + case 3: + __HAL_RCC_TIM3_CLK_ENABLE(); + break; #endif #if defined(TIM4) - case 4: __HAL_RCC_TIM4_CLK_ENABLE(); break; + case 4: + __HAL_RCC_TIM4_CLK_ENABLE(); + break; #endif #if defined(TIM5) - case 5: __HAL_RCC_TIM5_CLK_ENABLE(); break; + case 5: + __HAL_RCC_TIM5_CLK_ENABLE(); + break; #endif #if defined(TIM6) - case 6: __HAL_RCC_TIM6_CLK_ENABLE(); break; + case 6: + __HAL_RCC_TIM6_CLK_ENABLE(); + break; #endif #if defined(TIM7) - case 7: __HAL_RCC_TIM7_CLK_ENABLE(); break; + case 7: + __HAL_RCC_TIM7_CLK_ENABLE(); + break; #endif #if defined(TIM8) - case 8: __HAL_RCC_TIM8_CLK_ENABLE(); break; + case 8: + __HAL_RCC_TIM8_CLK_ENABLE(); + break; #endif #if defined(TIM9) - case 9: __HAL_RCC_TIM9_CLK_ENABLE(); break; + case 9: + __HAL_RCC_TIM9_CLK_ENABLE(); + break; #endif #if defined(TIM10) - case 10: __HAL_RCC_TIM10_CLK_ENABLE(); break; + case 10: + __HAL_RCC_TIM10_CLK_ENABLE(); + break; #endif #if defined(TIM11) - case 11: __HAL_RCC_TIM11_CLK_ENABLE(); break; + case 11: + __HAL_RCC_TIM11_CLK_ENABLE(); + break; #endif #if defined(TIM12) - case 12: __HAL_RCC_TIM12_CLK_ENABLE(); break; + case 12: + __HAL_RCC_TIM12_CLK_ENABLE(); + break; #endif #if defined(TIM13) - case 13: __HAL_RCC_TIM13_CLK_ENABLE(); break; + case 13: + __HAL_RCC_TIM13_CLK_ENABLE(); + break; #endif #if defined(TIM14) - case 14: __HAL_RCC_TIM14_CLK_ENABLE(); break; + case 14: + __HAL_RCC_TIM14_CLK_ENABLE(); + break; #endif #if defined(TIM15) - case 15: __HAL_RCC_TIM15_CLK_ENABLE(); break; + case 15: + __HAL_RCC_TIM15_CLK_ENABLE(); + break; #endif #if defined(TIM16) - case 16: __HAL_RCC_TIM16_CLK_ENABLE(); break; + case 16: + __HAL_RCC_TIM16_CLK_ENABLE(); + break; #endif #if defined(TIM17) - case 17: __HAL_RCC_TIM17_CLK_ENABLE(); break; + case 17: + __HAL_RCC_TIM17_CLK_ENABLE(); + break; #endif } @@ -678,7 +712,7 @@ STATIC mp_obj_t pyb_timer_init_helper(pyb_timer_obj_t *self, size_t n_args, cons if (IS_TIM_BREAK_INSTANCE(self->tim.Instance)) { #else if (0) { - #endif + #endif config_deadtime(self, args[ARG_deadtime].u_int); } @@ -800,7 +834,7 @@ STATIC mp_obj_t pyb_timer_make_new(const mp_obj_type_t *type, size_t n_args, siz tim->is_32bit = tim_id == 2 || tim_id == 5; tim->callback = mp_const_none; uint32_t ti = tim_instance_table[tim_id - 1]; - tim->tim.Instance = (TIM_TypeDef*)(ti & 0xffffff00); + tim->tim.Instance = (TIM_TypeDef *)(ti & 0xffffff00); tim->irqn = ti & 0xff; MP_STATE_PORT(pyb_timer_obj_all)[tim_id - 1] = tim; } else { @@ -1027,10 +1061,10 @@ STATIC mp_obj_t pyb_timer_channel(size_t n_args, const mp_obj_t *pos_args, mp_ma // use absolute pulse width value (defaults to 0 if nothing given) oc_config.Pulse = args[3].u_int; } - oc_config.OCPolarity = TIM_OCPOLARITY_HIGH; - oc_config.OCNPolarity = TIM_OCNPOLARITY_HIGH; - oc_config.OCFastMode = TIM_OCFAST_DISABLE; - oc_config.OCIdleState = TIM_OCIDLESTATE_SET; + oc_config.OCPolarity = TIM_OCPOLARITY_HIGH; + oc_config.OCNPolarity = TIM_OCNPOLARITY_HIGH; + oc_config.OCFastMode = TIM_OCFAST_DISABLE; + oc_config.OCIdleState = TIM_OCIDLESTATE_SET; oc_config.OCNIdleState = TIM_OCNIDLESTATE_SET; HAL_TIM_PWM_ConfigChannel(&self->tim, &oc_config, TIMER_CHANNEL(chan)); @@ -1053,19 +1087,19 @@ STATIC mp_obj_t pyb_timer_channel(size_t n_args, const mp_obj_t *pos_args, mp_ma case CHANNEL_MODE_OC_FORCED_ACTIVE: case CHANNEL_MODE_OC_FORCED_INACTIVE: { TIM_OC_InitTypeDef oc_config; - oc_config.OCMode = channel_mode_info[chan->mode].oc_mode; - oc_config.Pulse = args[5].u_int; - oc_config.OCPolarity = args[6].u_int; + oc_config.OCMode = channel_mode_info[chan->mode].oc_mode; + oc_config.Pulse = args[5].u_int; + oc_config.OCPolarity = args[6].u_int; if (oc_config.OCPolarity == 0xffffffff) { oc_config.OCPolarity = TIM_OCPOLARITY_HIGH; } if (oc_config.OCPolarity == TIM_OCPOLARITY_HIGH) { - oc_config.OCNPolarity = TIM_OCNPOLARITY_HIGH; + oc_config.OCNPolarity = TIM_OCNPOLARITY_HIGH; } else { - oc_config.OCNPolarity = TIM_OCNPOLARITY_LOW; + oc_config.OCNPolarity = TIM_OCNPOLARITY_LOW; } - oc_config.OCFastMode = TIM_OCFAST_DISABLE; - oc_config.OCIdleState = TIM_OCIDLESTATE_SET; + oc_config.OCFastMode = TIM_OCFAST_DISABLE; + oc_config.OCIdleState = TIM_OCIDLESTATE_SET; oc_config.OCNIdleState = TIM_OCNIDLESTATE_SET; if (!IS_TIM_OC_POLARITY(oc_config.OCPolarity)) { @@ -1087,13 +1121,13 @@ STATIC mp_obj_t pyb_timer_channel(size_t n_args, const mp_obj_t *pos_args, mp_ma case CHANNEL_MODE_IC: { TIM_IC_InitTypeDef ic_config; - ic_config.ICPolarity = args[6].u_int; + ic_config.ICPolarity = args[6].u_int; if (ic_config.ICPolarity == 0xffffffff) { ic_config.ICPolarity = TIM_ICPOLARITY_RISING; } ic_config.ICSelection = TIM_ICSELECTION_DIRECTTI; ic_config.ICPrescaler = TIM_ICPSC_DIV1; - ic_config.ICFilter = 0; + ic_config.ICFilter = 0; if (!IS_TIM_IC_POLARITY(ic_config.ICPolarity)) { nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "invalid polarity (%d)", ic_config.ICPolarity)); @@ -1113,37 +1147,37 @@ STATIC mp_obj_t pyb_timer_channel(size_t n_args, const mp_obj_t *pos_args, mp_ma TIM_Encoder_InitTypeDef enc_config; enc_config.EncoderMode = channel_mode_info[chan->mode].oc_mode; - enc_config.IC1Polarity = args[6].u_int; + enc_config.IC1Polarity = args[6].u_int; if (enc_config.IC1Polarity == 0xffffffff) { enc_config.IC1Polarity = TIM_ICPOLARITY_RISING; } - enc_config.IC2Polarity = enc_config.IC1Polarity; + enc_config.IC2Polarity = enc_config.IC1Polarity; enc_config.IC1Selection = TIM_ICSELECTION_DIRECTTI; enc_config.IC2Selection = TIM_ICSELECTION_DIRECTTI; enc_config.IC1Prescaler = TIM_ICPSC_DIV1; enc_config.IC2Prescaler = TIM_ICPSC_DIV1; - enc_config.IC1Filter = 0; - enc_config.IC2Filter = 0; + enc_config.IC1Filter = 0; + enc_config.IC2Filter = 0; if (!IS_TIM_IC_POLARITY(enc_config.IC1Polarity)) { nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "invalid polarity (%d)", enc_config.IC1Polarity)); } // Only Timers 1, 2, 3, 4, 5, and 8 support encoder mode if (self->tim.Instance != TIM1 - && self->tim.Instance != TIM2 - #if defined(TIM3) - && self->tim.Instance != TIM3 - #endif - #if defined(TIM4) - && self->tim.Instance != TIM4 - #endif - #if defined(TIM5) - && self->tim.Instance != TIM5 - #endif - #if defined(TIM8) - && self->tim.Instance != TIM8 - #endif - ) { + && self->tim.Instance != TIM2 + #if defined(TIM3) + && self->tim.Instance != TIM3 + #endif + #if defined(TIM4) + && self->tim.Instance != TIM4 + #endif + #if defined(TIM5) + && self->tim.Instance != TIM5 + #endif + #if defined(TIM8) + && self->tim.Instance != TIM8 + #endif + ) { nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "encoder not supported on timer %d", self->tim_id)); } @@ -1315,7 +1349,7 @@ const mp_obj_type_t pyb_timer_type = { .name = MP_QSTR_Timer, .print = pyb_timer_print, .make_new = pyb_timer_make_new, - .locals_dict = (mp_obj_dict_t*)&pyb_timer_locals_dict, + .locals_dict = (mp_obj_dict_t *)&pyb_timer_locals_dict, }; /// \moduleref pyb @@ -1328,9 +1362,9 @@ STATIC void pyb_timer_channel_print(const mp_print_t *print, mp_obj_t self_in, m pyb_timer_channel_obj_t *self = MP_OBJ_TO_PTR(self_in); mp_printf(print, "TimerChannel(timer=%u, channel=%u, mode=%s)", - self->timer->tim_id, - self->channel, - qstr_str(channel_mode_info[self->mode].name)); + self->timer->tim_id, + self->channel, + qstr_str(channel_mode_info[self->mode].name)); } /// \method capture([value]) @@ -1447,7 +1481,7 @@ STATIC const mp_obj_type_t pyb_timer_channel_type = { { &mp_type_type }, .name = MP_QSTR_TimerChannel, .print = pyb_timer_channel_print, - .locals_dict = (mp_obj_dict_t*)&pyb_timer_channel_locals_dict, + .locals_dict = (mp_obj_dict_t *)&pyb_timer_channel_locals_dict, }; STATIC void timer_handle_irq_channel(pyb_timer_obj_t *tim, uint8_t channel, mp_obj_t callback) { diff --git a/ports/stm32/uart.c b/ports/stm32/uart.c index e514709b72..f6a57307f3 100644 --- a/ports/stm32/uart.c +++ b/ports/stm32/uart.c @@ -123,38 +123,47 @@ bool uart_exists(int uart_id) { } switch (uart_id) { #if defined(MICROPY_HW_UART1_TX) && defined(MICROPY_HW_UART1_RX) - case PYB_UART_1: return true; + case PYB_UART_1: + return true; #endif #if defined(MICROPY_HW_UART2_TX) && defined(MICROPY_HW_UART2_RX) - case PYB_UART_2: return true; + case PYB_UART_2: + return true; #endif #if defined(MICROPY_HW_UART3_TX) && defined(MICROPY_HW_UART3_RX) - case PYB_UART_3: return true; + case PYB_UART_3: + return true; #endif #if defined(MICROPY_HW_UART4_TX) && defined(MICROPY_HW_UART4_RX) - case PYB_UART_4: return true; + case PYB_UART_4: + return true; #endif #if defined(MICROPY_HW_UART5_TX) && defined(MICROPY_HW_UART5_RX) - case PYB_UART_5: return true; + case PYB_UART_5: + return true; #endif #if defined(MICROPY_HW_UART6_TX) && defined(MICROPY_HW_UART6_RX) - case PYB_UART_6: return true; + case PYB_UART_6: + return true; #endif #if defined(MICROPY_HW_UART7_TX) && defined(MICROPY_HW_UART7_RX) - case PYB_UART_7: return true; + case PYB_UART_7: + return true; #endif #if defined(MICROPY_HW_UART8_TX) && defined(MICROPY_HW_UART8_RX) - case PYB_UART_8: return true; + case PYB_UART_8: + return true; #endif - default: return false; + default: + return false; } } @@ -584,7 +593,7 @@ int uart_rx_char(pyb_uart_obj_t *self) { // buffering via IRQ int data; if (self->char_width == CHAR_WIDTH_9BIT) { - data = ((uint16_t*)self->read_buf)[self->read_buf_tail]; + data = ((uint16_t *)self->read_buf)[self->read_buf_tail]; } else { data = self->read_buf[self->read_buf_tail]; } @@ -667,7 +676,7 @@ size_t uart_tx_data(pyb_uart_obj_t *self, const void *src_in, size_t num_chars, timeout = 2 * self->timeout_char; } - const uint8_t *src = (const uint8_t*)src_in; + const uint8_t *src = (const uint8_t *)src_in; size_t num_tx = 0; USART_TypeDef *uart = self->uartx; @@ -678,7 +687,7 @@ size_t uart_tx_data(pyb_uart_obj_t *self, const void *src_in, size_t num_chars, } uint32_t data; if (self->char_width == CHAR_WIDTH_9BIT) { - data = *((uint16_t*)src) & 0x1ff; + data = *((uint16_t *)src) & 0x1ff; src += 2; } else { data = *src++; @@ -734,7 +743,7 @@ void uart_irq_handler(mp_uint_t uart_id) { pendsv_kbd_intr(); } else { if (self->char_width == CHAR_WIDTH_9BIT) { - ((uint16_t*)self->read_buf)[self->read_buf_head] = data; + ((uint16_t *)self->read_buf)[self->read_buf_head] = data; } else { self->read_buf[self->read_buf_head] = data; } diff --git a/ports/stm32/usb.c b/ports/stm32/usb.c index b73bfdc311..07f42fdf62 100644 --- a/ports/stm32/usb.c +++ b/ports/stm32/usb.c @@ -125,8 +125,8 @@ bool pyb_usb_dev_init(uint16_t vid, uint16_t pid, usb_device_mode_t mode, USBD_H // set up the USBD state USBD_HandleTypeDef *usbd = &usb_dev->hUSBDDevice; usbd->id = MICROPY_HW_USB_MAIN_DEV; - usbd->dev_state = USBD_STATE_DEFAULT; - usbd->pDesc = (USBD_DescriptorsTypeDef*)&USBD_Descriptors; + usbd->dev_state = USBD_STATE_DEFAULT; + usbd->pDesc = (USBD_DescriptorsTypeDef *)&USBD_Descriptors; usbd->pClass = &USBD_CDC_MSC_HID; usb_dev->usbd_cdc_msc_hid_state.pdev = usbd; usb_dev->usbd_cdc_msc_hid_state.cdc = &usb_dev->usbd_cdc_itf.base; @@ -143,13 +143,13 @@ bool pyb_usb_dev_init(uint16_t vid, uint16_t pid, usb_device_mode_t mode, USBD_H } switch (pyb_usb_storage_medium) { -#if MICROPY_HW_HAS_SDCARD + #if MICROPY_HW_HAS_SDCARD case PYB_USB_STORAGE_MEDIUM_SDCARD: - USBD_MSC_RegisterStorage(&usb_dev->usbd_cdc_msc_hid_state, (USBD_StorageTypeDef*)&USBD_SDCARD_STORAGE_fops); + USBD_MSC_RegisterStorage(&usb_dev->usbd_cdc_msc_hid_state, (USBD_StorageTypeDef *)&USBD_SDCARD_STORAGE_fops); break; -#endif + #endif default: - USBD_MSC_RegisterStorage(&usb_dev->usbd_cdc_msc_hid_state, (USBD_StorageTypeDef*)&USBD_FLASH_STORAGE_fops); + USBD_MSC_RegisterStorage(&usb_dev->usbd_cdc_msc_hid_state, (USBD_StorageTypeDef *)&USBD_FLASH_STORAGE_fops); break; } @@ -181,7 +181,7 @@ int usb_vcp_recv_byte(uint8_t *c) { void usb_vcp_send_strn(const char *str, int len) { if (usb_device.enabled) { - usbd_cdc_tx_always(&usb_device.usbd_cdc_itf, (const uint8_t*)str, len); + usbd_cdc_tx_always(&usb_device.usbd_cdc_itf, (const uint8_t *)str, len); } } @@ -236,9 +236,9 @@ STATIC mp_obj_t pyb_usb_mode(size_t n_args, const mp_obj_t *pos_args, mp_map_t * // fetch the current usb mode -> pyb.usb_mode() if (n_args == 0) { - #if defined(USE_HOST_MODE) + #if defined(USE_HOST_MODE) return MP_OBJ_NEW_QSTR(MP_QSTR_host); - #else + #else uint8_t mode = USBD_GetMode(&usb_device.usbd_cdc_msc_hid_state); switch (mode) { case USBD_MODE_CDC: @@ -256,7 +256,7 @@ STATIC mp_obj_t pyb_usb_mode(size_t n_args, const mp_obj_t *pos_args, mp_map_t * default: return mp_const_none; } - #endif + #endif } // parse args @@ -276,7 +276,7 @@ STATIC mp_obj_t pyb_usb_mode(size_t n_args, const mp_obj_t *pos_args, mp_map_t * // get mode string const char *mode_str = mp_obj_str_get_str(args[0].u_obj); -#if defined(USE_HOST_MODE) + #if defined(USE_HOST_MODE) // hardware configured for USB host mode @@ -286,7 +286,7 @@ STATIC mp_obj_t pyb_usb_mode(size_t n_args, const mp_obj_t *pos_args, mp_map_t * goto bad_mode; } -#else + #else // hardware configured for USB device mode @@ -356,7 +356,7 @@ STATIC mp_obj_t pyb_usb_mode(size_t n_args, const mp_obj_t *pos_args, mp_map_t * goto bad_mode; } -#endif + #endif return mp_const_none; @@ -386,7 +386,7 @@ STATIC const pyb_usb_vcp_obj_t pyb_usb_vcp2_obj = {{&pyb_usb_vcp_type}, &usb_dev #endif STATIC void pyb_usb_vcp_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { - int id = ((pyb_usb_vcp_obj_t*)MP_OBJ_TO_PTR(self_in))->cdc_itf - &usb_device.usbd_cdc_itf; + int id = ((pyb_usb_vcp_obj_t *)MP_OBJ_TO_PTR(self_in))->cdc_itf - &usb_device.usbd_cdc_itf; mp_printf(print, "USB_VCP(%u)", id); } @@ -492,7 +492,7 @@ STATIC mp_obj_t pyb_usb_vcp_recv(size_t n_args, const mp_obj_t *args, mp_map_t * mp_obj_t o_ret = pyb_buf_get_for_recv(vals[0].u_obj, &vstr); // receive the data - int ret = usbd_cdc_rx(self->cdc_itf, (uint8_t*)vstr.buf, vstr.len, vals[1].u_int); + int ret = usbd_cdc_rx(self->cdc_itf, (uint8_t *)vstr.buf, vstr.len, vals[1].u_int); // return the received data if (o_ret != MP_OBJ_NULL) { @@ -530,7 +530,7 @@ STATIC MP_DEFINE_CONST_DICT(pyb_usb_vcp_locals_dict, pyb_usb_vcp_locals_dict_tab STATIC mp_uint_t pyb_usb_vcp_read(mp_obj_t self_in, void *buf, mp_uint_t size, int *errcode) { pyb_usb_vcp_obj_t *self = MP_OBJ_TO_PTR(self_in); - int ret = usbd_cdc_rx(self->cdc_itf, (byte*)buf, size, 0); + int ret = usbd_cdc_rx(self->cdc_itf, (byte *)buf, size, 0); if (ret == 0) { // return EAGAIN error to indicate non-blocking *errcode = MP_EAGAIN; @@ -541,7 +541,7 @@ STATIC mp_uint_t pyb_usb_vcp_read(mp_obj_t self_in, void *buf, mp_uint_t size, i STATIC mp_uint_t pyb_usb_vcp_write(mp_obj_t self_in, const void *buf, mp_uint_t size, int *errcode) { pyb_usb_vcp_obj_t *self = MP_OBJ_TO_PTR(self_in); - int ret = usbd_cdc_tx(self->cdc_itf, (const byte*)buf, size, 0); + int ret = usbd_cdc_tx(self->cdc_itf, (const byte *)buf, size, 0); if (ret == 0) { // return EAGAIN error to indicate non-blocking *errcode = MP_EAGAIN; @@ -583,7 +583,7 @@ const mp_obj_type_t pyb_usb_vcp_type = { .getiter = mp_identity_getiter, .iternext = mp_stream_unbuffered_iter, .protocol = &pyb_usb_vcp_stream_p, - .locals_dict = (mp_obj_dict_t*)&pyb_usb_vcp_locals_dict, + .locals_dict = (mp_obj_dict_t *)&pyb_usb_vcp_locals_dict, }; /******************************************************************************/ @@ -632,7 +632,7 @@ STATIC mp_obj_t pyb_usb_hid_recv(size_t n_args, const mp_obj_t *args, mp_map_t * mp_obj_t o_ret = pyb_buf_get_for_recv(vals[0].u_obj, &vstr); // receive the data - int ret = usbd_hid_rx(&self->usb_dev->usbd_hid_itf, vstr.len, (uint8_t*)vstr.buf, vals[1].u_int); + int ret = usbd_hid_rx(&self->usb_dev->usbd_hid_itf, vstr.len, (uint8_t *)vstr.buf, vals[1].u_int); // return the received data if (o_ret != MP_OBJ_NULL) { @@ -714,7 +714,7 @@ const mp_obj_type_t pyb_usb_hid_type = { .name = MP_QSTR_USB_HID, .make_new = pyb_usb_hid_make_new, .protocol = &pyb_usb_hid_stream_p, - .locals_dict = (mp_obj_dict_t*)&pyb_usb_hid_locals_dict, + .locals_dict = (mp_obj_dict_t *)&pyb_usb_hid_locals_dict, }; /******************************************************************************/ @@ -729,7 +729,7 @@ const mp_obj_type_t pyb_usb_hid_type = { #include "usbh_hid_keybd.h" #include "usbh_hid_mouse.h" -__ALIGN_BEGIN USBH_HOST USB_Host __ALIGN_END ; +__ALIGN_BEGIN USBH_HOST USB_Host __ALIGN_END; static int host_is_enabled = 0; diff --git a/ports/stm32/usb.h b/ports/stm32/usb.h index 45a05882a9..1c1f6b8a02 100644 --- a/ports/stm32/usb.h +++ b/ports/stm32/usb.h @@ -64,7 +64,7 @@ bool pyb_usb_dev_init(uint16_t vid, uint16_t pid, usb_device_mode_t mode, USBD_H void pyb_usb_dev_deinit(void); bool usb_vcp_is_enabled(void); int usb_vcp_recv_byte(uint8_t *c); // if a byte is available, return 1 and put the byte in *c, else return 0 -void usb_vcp_send_strn(const char* str, int len); +void usb_vcp_send_strn(const char *str, int len); void pyb_usb_host_init(void); void pyb_usb_host_process(void); diff --git a/ports/stm32/usbd_cdc_interface.c b/ports/stm32/usbd_cdc_interface.c index 149971bfb5..d6eaf19c8c 100644 --- a/ports/stm32/usbd_cdc_interface.c +++ b/ports/stm32/usbd_cdc_interface.c @@ -62,7 +62,7 @@ static uint8_t usbd_cdc_connect_tx_timer; uint8_t *usbd_cdc_init(usbd_cdc_state_t *cdc_in) { - usbd_cdc_itf_t *cdc = (usbd_cdc_itf_t*)cdc_in; + usbd_cdc_itf_t *cdc = (usbd_cdc_itf_t *)cdc_in; // Reset all the CDC state // Note: we don't reset tx_buf_ptr_in in order to allow the output buffer to @@ -84,7 +84,7 @@ uint8_t *usbd_cdc_init(usbd_cdc_state_t *cdc_in) { } void usbd_cdc_deinit(usbd_cdc_state_t *cdc_in) { - usbd_cdc_itf_t *cdc = (usbd_cdc_itf_t*)cdc_in; + usbd_cdc_itf_t *cdc = (usbd_cdc_itf_t *)cdc_in; cdc->connect_state = USBD_CDC_CONNECT_STATE_DISCONNECTED; } @@ -93,8 +93,8 @@ void usbd_cdc_deinit(usbd_cdc_state_t *cdc_in) { // pbuf: buffer containing command data (request parameters) // length: number of data to be sent (in bytes) // Returns USBD_OK if all operations are OK else USBD_FAIL -int8_t usbd_cdc_control(usbd_cdc_state_t *cdc_in, uint8_t cmd, uint8_t* pbuf, uint16_t length) { - usbd_cdc_itf_t *cdc = (usbd_cdc_itf_t*)cdc_in; +int8_t usbd_cdc_control(usbd_cdc_state_t *cdc_in, uint8_t cmd, uint8_t *pbuf, uint16_t length) { + usbd_cdc_itf_t *cdc = (usbd_cdc_itf_t *)cdc_in; switch (cmd) { case CDC_SEND_ENCAPSULATED_COMMAND: @@ -119,11 +119,11 @@ int8_t usbd_cdc_control(usbd_cdc_state_t *cdc_in, uint8_t cmd, uint8_t* pbuf, ui case CDC_SET_LINE_CODING: #if 0 - LineCoding.bitrate = (uint32_t)(pbuf[0] | (pbuf[1] << 8) |\ - (pbuf[2] << 16) | (pbuf[3] << 24)); - LineCoding.format = pbuf[4]; + LineCoding.bitrate = (uint32_t)(pbuf[0] | (pbuf[1] << 8) | \ + (pbuf[2] << 16) | (pbuf[3] << 24)); + LineCoding.format = pbuf[4]; LineCoding.paritytype = pbuf[5]; - LineCoding.datatype = pbuf[6]; + LineCoding.datatype = pbuf[6]; /* Set the new configuration */ #endif break; @@ -170,7 +170,7 @@ int8_t usbd_cdc_control(usbd_cdc_state_t *cdc_in, uint8_t cmd, uint8_t* pbuf, ui // (cdc.base.tx_in_progress must be 0) void usbd_cdc_tx_ready(usbd_cdc_state_t *cdc_in) { - usbd_cdc_itf_t *cdc = (usbd_cdc_itf_t*)cdc_in; + usbd_cdc_itf_t *cdc = (usbd_cdc_itf_t *)cdc_in; cdc->tx_buf_ptr_out = cdc->tx_buf_ptr_out_shadow; if (cdc->tx_buf_ptr_out == cdc->tx_buf_ptr_in && !cdc->tx_need_empty_packet) { @@ -219,15 +219,15 @@ void HAL_PCD_SOFCallback(PCD_HandleTypeDef *hpcd) { if (usbd_cdc_connect_tx_timer > 0) { --usbd_cdc_connect_tx_timer; } else { - usbd_cdc_msc_hid_state_t *usbd = ((USBD_HandleTypeDef*)hpcd->pData)->pClassData; + usbd_cdc_msc_hid_state_t *usbd = ((USBD_HandleTypeDef *)hpcd->pData)->pClassData; hpcd->Instance->GINTMSK &= ~USB_OTG_GINTMSK_SOFM; - usbd_cdc_itf_t *cdc = (usbd_cdc_itf_t*)usbd->cdc; + usbd_cdc_itf_t *cdc = (usbd_cdc_itf_t *)usbd->cdc; if (cdc->connect_state == USBD_CDC_CONNECT_STATE_CONNECTING) { cdc->connect_state = USBD_CDC_CONNECT_STATE_CONNECTED; usbd_cdc_try_tx(cdc); } #if MICROPY_HW_USB_ENABLE_CDC2 - cdc = (usbd_cdc_itf_t*)usbd->cdc2; + cdc = (usbd_cdc_itf_t *)usbd->cdc2; if (cdc->connect_state == USBD_CDC_CONNECT_STATE_CONNECTING) { cdc->connect_state = USBD_CDC_CONNECT_STATE_CONNECTED; usbd_cdc_try_tx(cdc); @@ -240,7 +240,7 @@ void HAL_PCD_SOFCallback(PCD_HandleTypeDef *hpcd) { // len: number of bytes received into the buffer we passed to USBD_CDC_ReceivePacket // Returns USBD_OK if all operations are OK else USBD_FAIL int8_t usbd_cdc_receive(usbd_cdc_state_t *cdc_in, size_t len) { - usbd_cdc_itf_t *cdc = (usbd_cdc_itf_t*)cdc_in; + usbd_cdc_itf_t *cdc = (usbd_cdc_itf_t *)cdc_in; // copy the incoming data into the circular buffer for (const uint8_t *src = cdc->rx_packet_buf, *top = cdc->rx_packet_buf + len; src < top; ++src) { @@ -278,7 +278,7 @@ int usbd_cdc_tx(usbd_cdc_itf_t *cdc, const uint8_t *buf, uint32_t len, uint32_t // Wait until the device is connected and the buffer has space, with a given timeout uint32_t start = HAL_GetTick(); while (cdc->connect_state == USBD_CDC_CONNECT_STATE_DISCONNECTED - || ((cdc->tx_buf_ptr_in + 1) & (USBD_CDC_TX_DATA_SIZE - 1)) == cdc->tx_buf_ptr_out) { + || ((cdc->tx_buf_ptr_in + 1) & (USBD_CDC_TX_DATA_SIZE - 1)) == cdc->tx_buf_ptr_out) { usbd_cdc_try_tx(cdc); // Wraparound of tick is taken care of by 2's complement arithmetic. if (HAL_GetTick() - start >= timeout) { diff --git a/ports/stm32/usbd_conf.c b/ports/stm32/usbd_conf.c index 3068a822e3..d1421b4edf 100644 --- a/ports/stm32/usbd_conf.c +++ b/ports/stm32/usbd_conf.c @@ -163,7 +163,7 @@ void HAL_PCD_MspInit(PCD_HandleTypeDef *hpcd) { HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); // D1 D2 D3 D4 D5 D6 D7 - GPIO_InitStruct.Pin = GPIO_PIN_0 | GPIO_PIN_1 | GPIO_PIN_5 |\ + GPIO_InitStruct.Pin = GPIO_PIN_0 | GPIO_PIN_1 | GPIO_PIN_5 | \ GPIO_PIN_10 | GPIO_PIN_11 | GPIO_PIN_12 | GPIO_PIN_13; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; @@ -367,7 +367,7 @@ void HAL_PCD_DisconnectCallback(PCD_HandleTypeDef *hpcd) { */ USBD_StatusTypeDef USBD_LL_Init(USBD_HandleTypeDef *pdev, int high_speed) { #if MICROPY_HW_USB_FS - if (pdev->id == USB_PHY_FS_ID) { + if (pdev->id == USB_PHY_FS_ID) { // Set LL Driver parameters pcd_fs_handle.Instance = USB_OTG_FS; #if MICROPY_HW_USB_ENABLE_CDC2 @@ -652,7 +652,7 @@ USBD_StatusTypeDef USBD_LL_PrepareReceive(USBD_HandleTypeDef *pdev, * @param ep_addr: Endpoint Number * @retval Recived Data Size */ -uint32_t USBD_LL_GetRxDataSize(USBD_HandleTypeDef *pdev, uint8_t ep_addr) { +uint32_t USBD_LL_GetRxDataSize(USBD_HandleTypeDef *pdev, uint8_t ep_addr) { return HAL_PCD_EP_GetRxCount(pdev->pData, ep_addr); } diff --git a/ports/stm32/usbd_desc.c b/ports/stm32/usbd_desc.c index 4babebf640..4859ebed62 100644 --- a/ports/stm32/usbd_desc.c +++ b/ports/stm32/usbd_desc.c @@ -97,7 +97,7 @@ void USBD_SetVIDPIDRelease(usbd_cdc_msc_hid_state_t *usbd, uint16_t vid, uint16_ * @retval Pointer to descriptor buffer */ STATIC uint8_t *USBD_DeviceDescriptor(USBD_HandleTypeDef *pdev, uint16_t *length) { - uint8_t *dev_desc = ((usbd_cdc_msc_hid_state_t*)pdev->pClassData)->usbd_device_desc; + uint8_t *dev_desc = ((usbd_cdc_msc_hid_state_t *)pdev->pClassData)->usbd_device_desc; *length = USB_LEN_DEV_DESC; return dev_desc; } @@ -115,7 +115,7 @@ STATIC uint8_t *USBD_StrDescriptor(USBD_HandleTypeDef *pdev, uint8_t idx, uint16 switch (idx) { case USBD_IDX_LANGID_STR: *length = sizeof(USBD_LangIDDesc); - return (uint8_t*)USBD_LangIDDesc; // the data should only be read from this buf + return (uint8_t *)USBD_LangIDDesc; // the data should only be read from this buf case USBD_IDX_MFC_STR: str = USBD_MANUFACTURER_STRING; @@ -171,8 +171,8 @@ STATIC uint8_t *USBD_StrDescriptor(USBD_HandleTypeDef *pdev, uint8_t idx, uint16 return NULL; } - uint8_t *str_desc = ((usbd_cdc_msc_hid_state_t*)pdev->pClassData)->usbd_str_desc; - USBD_GetString((uint8_t*)str, str_desc, length); + uint8_t *str_desc = ((usbd_cdc_msc_hid_state_t *)pdev->pClassData)->usbd_str_desc; + USBD_GetString((uint8_t *)str, str_desc, length); return str_desc; } diff --git a/ports/stm32/usbd_hid_interface.c b/ports/stm32/usbd_hid_interface.c index 3ffc0b425d..c33fb7ce84 100644 --- a/ports/stm32/usbd_hid_interface.c +++ b/ports/stm32/usbd_hid_interface.c @@ -43,7 +43,7 @@ #include "usb.h" uint8_t *usbd_hid_init(usbd_hid_state_t *hid_in) { - usbd_hid_itf_t *hid = (usbd_hid_itf_t*)hid_in; + usbd_hid_itf_t *hid = (usbd_hid_itf_t *)hid_in; hid->current_read_buffer = 0; hid->last_read_len = 0; @@ -57,7 +57,7 @@ uint8_t *usbd_hid_init(usbd_hid_state_t *hid_in) { // len: number of bytes received into the buffer we passed to USBD_HID_ReceivePacket // Returns USBD_OK if all operations are OK else USBD_FAIL int8_t usbd_hid_receive(usbd_hid_state_t *hid_in, size_t len) { - usbd_hid_itf_t *hid = (usbd_hid_itf_t*)hid_in; + usbd_hid_itf_t *hid = (usbd_hid_itf_t *)hid_in; hid->current_write_buffer = !hid->current_write_buffer; hid->last_read_len = len; diff --git a/ports/stm32/usbd_msc_storage.c b/ports/stm32/usbd_msc_storage.c index 7d6c19e9fe..0bb12003ff 100644 --- a/ports/stm32/usbd_msc_storage.c +++ b/ports/stm32/usbd_msc_storage.c @@ -64,7 +64,7 @@ static const int8_t FLASH_STORAGE_Inquirydata[] = { // 36 bytes 'u', 'P', 'y', ' ', ' ', ' ', ' ', ' ', // Manufacturer : 8 bytes 'm', 'i', 'c', 'r', 'o', 'S', 'D', ' ', // Product : 16 Bytes 'F', 'l', 'a', 's', 'h', ' ', ' ', ' ', - '1', '.', '0' ,'0', // Version : 4 Bytes + '1', '.', '0','0', // Version : 4 Bytes }; /** @@ -109,7 +109,7 @@ int8_t FLASH_STORAGE_IsReady(uint8_t lun) { * @retval Status */ int8_t FLASH_STORAGE_IsWriteProtected(uint8_t lun) { - return 0; + return 0; } // Remove the lun @@ -145,7 +145,7 @@ int8_t FLASH_STORAGE_Read(uint8_t lun, uint8_t *buf, uint32_t blk_addr, uint16_t * @param blk_len : nmber of blocks to be read * @retval Status */ -int8_t FLASH_STORAGE_Write (uint8_t lun, uint8_t *buf, uint32_t blk_addr, uint16_t blk_len) { +int8_t FLASH_STORAGE_Write(uint8_t lun, uint8_t *buf, uint32_t blk_addr, uint16_t blk_len) { storage_write_blocks(buf, blk_addr, blk_len); return 0; } @@ -190,7 +190,7 @@ static const int8_t SDCARD_STORAGE_Inquirydata[] = { // 36 bytes 'u', 'P', 'y', ' ', ' ', ' ', ' ', ' ', // Manufacturer : 8 bytes 'm', 'i', 'c', 'r', 'o', 'S', 'D', ' ', // Product : 16 Bytes 'S', 'D', ' ', 'c', 'a', 'r', 'd', ' ', - '1', '.', '0' ,'0', // Version : 4 Bytes + '1', '.', '0','0', // Version : 4 Bytes }; /** @@ -216,7 +216,7 @@ int8_t SDCARD_STORAGE_Init(uint8_t lun) { */ int8_t SDCARD_STORAGE_GetCapacity(uint8_t lun, uint32_t *block_num, uint16_t *block_size) { *block_size = SDCARD_BLOCK_SIZE; - *block_num = sdcard_get_capacity_in_bytes() / SDCARD_BLOCK_SIZE; + *block_num = sdcard_get_capacity_in_bytes() / SDCARD_BLOCK_SIZE; return 0; } diff --git a/ports/stm32/usrsw.c b/ports/stm32/usrsw.c index 4519f8018e..596efba053 100644 --- a/ports/stm32/usrsw.c +++ b/ports/stm32/usrsw.c @@ -119,10 +119,10 @@ mp_obj_t pyb_switch_callback(mp_obj_t self_in, mp_obj_t callback) { // may have been disabled by an exception in the interrupt, or the // user disabling the line explicitly. extint_register(MP_OBJ_FROM_PTR(MICROPY_HW_USRSW_PIN), - MICROPY_HW_USRSW_EXTI_MODE, - MICROPY_HW_USRSW_PULL, - callback == mp_const_none ? mp_const_none : MP_OBJ_FROM_PTR(&switch_callback_obj), - true); + MICROPY_HW_USRSW_EXTI_MODE, + MICROPY_HW_USRSW_PULL, + callback == mp_const_none ? mp_const_none : MP_OBJ_FROM_PTR(&switch_callback_obj), + true); return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_2(pyb_switch_callback_obj, pyb_switch_callback); @@ -140,7 +140,7 @@ const mp_obj_type_t pyb_switch_type = { .print = pyb_switch_print, .make_new = pyb_switch_make_new, .call = pyb_switch_call, - .locals_dict = (mp_obj_dict_t*)&pyb_switch_locals_dict, + .locals_dict = (mp_obj_dict_t *)&pyb_switch_locals_dict, }; #endif // MICROPY_HW_HAS_SWITCH diff --git a/ports/stm32/wdt.c b/ports/stm32/wdt.c index 3cfbd7f2ed..7beff0dea4 100644 --- a/ports/stm32/wdt.c +++ b/ports/stm32/wdt.c @@ -106,5 +106,5 @@ const mp_obj_type_t pyb_wdt_type = { { &mp_type_type }, .name = MP_QSTR_WDT, .make_new = pyb_wdt_make_new, - .locals_dict = (mp_obj_dict_t*)&pyb_wdt_locals_dict, + .locals_dict = (mp_obj_dict_t *)&pyb_wdt_locals_dict, }; diff --git a/ports/teensy/hal_ftm.c b/ports/teensy/hal_ftm.c index 3c031bf6dd..7ae70b2bbb 100644 --- a/ports/teensy/hal_ftm.c +++ b/ports/teensy/hal_ftm.c @@ -43,7 +43,7 @@ void HAL_FTM_Base_Init(FTM_HandleTypeDef *hftm) { FTMx->MOD = hftm->Init.Period; uint32_t sc = FTM_SC_PS(hftm->Init.PrescalerShift); if (hftm->Init.CounterMode == FTM_COUNTERMODE_CENTER) { - sc |= FTM_SC_CPWMS; + sc |= FTM_SC_CPWMS; } FTMx->SC = sc; @@ -89,7 +89,7 @@ void HAL_FTM_OC_Init(FTM_HandleTypeDef *hftm) { HAL_FTM_Base_Init(hftm); } -void HAL_FTM_OC_ConfigChannel(FTM_HandleTypeDef *hftm, FTM_OC_InitTypeDef* sConfig, uint32_t channel) { +void HAL_FTM_OC_ConfigChannel(FTM_HandleTypeDef *hftm, FTM_OC_InitTypeDef *sConfig, uint32_t channel) { FTM_TypeDef *FTMx = hftm->Instance; assert_param(IS_FTM_INSTANCE(FTMx)); assert_param(IS_FTM_CHANNEL(channel)); @@ -100,11 +100,11 @@ void HAL_FTM_OC_ConfigChannel(FTM_HandleTypeDef *hftm, FTM_OC_InitTypeDef* sConf hftm->State = HAL_FTM_STATE_BUSY; FTMx->channel[channel].CSC = sConfig->OCMode; - FTMx->channel[channel].CV = sConfig->Pulse; + FTMx->channel[channel].CV = sConfig->Pulse; if (sConfig->OCPolarity & 1) { - FTMx->POL |= (1 << channel); + FTMx->POL |= (1 << channel); } else { - FTMx->POL &= ~(1 << channel); + FTMx->POL &= ~(1 << channel); } hftm->State = HAL_FTM_STATE_READY; @@ -129,7 +129,7 @@ void HAL_FTM_PWM_Init(FTM_HandleTypeDef *hftm) { HAL_FTM_Base_Init(hftm); } -void HAL_FTM_PWM_ConfigChannel(FTM_HandleTypeDef *hftm, FTM_OC_InitTypeDef* sConfig, uint32_t channel) { +void HAL_FTM_PWM_ConfigChannel(FTM_HandleTypeDef *hftm, FTM_OC_InitTypeDef *sConfig, uint32_t channel) { FTM_TypeDef *FTMx = hftm->Instance; assert_param(IS_FTM_INSTANCE(FTMx)); assert_param(IS_FTM_CHANNEL(channel)); @@ -140,11 +140,11 @@ void HAL_FTM_PWM_ConfigChannel(FTM_HandleTypeDef *hftm, FTM_OC_InitTypeDef* sCon hftm->State = HAL_FTM_STATE_BUSY; FTMx->channel[channel].CSC = sConfig->OCMode; - FTMx->channel[channel].CV = sConfig->Pulse; + FTMx->channel[channel].CV = sConfig->Pulse; if (sConfig->OCPolarity & 1) { - FTMx->POL |= (1 << channel); + FTMx->POL |= (1 << channel); } else { - FTMx->POL &= ~(1 << channel); + FTMx->POL &= ~(1 << channel); } hftm->State = HAL_FTM_STATE_READY; @@ -169,7 +169,7 @@ void HAL_FTM_IC_Init(FTM_HandleTypeDef *hftm) { HAL_FTM_Base_Init(hftm); } -void HAL_FTM_IC_ConfigChannel(FTM_HandleTypeDef *hftm, FTM_IC_InitTypeDef* sConfig, uint32_t channel) { +void HAL_FTM_IC_ConfigChannel(FTM_HandleTypeDef *hftm, FTM_IC_InitTypeDef *sConfig, uint32_t channel) { FTM_TypeDef *FTMx = hftm->Instance; assert_param(IS_FTM_INSTANCE(FTMx)); assert_param(IS_FTM_CHANNEL(channel)); @@ -183,8 +183,8 @@ void HAL_FTM_IC_ConfigChannel(FTM_HandleTypeDef *hftm, FTM_IC_InitTypeDef* sConf } void HAL_FTM_IC_Start(FTM_HandleTypeDef *hftm, uint32_t channel) { - //FTM_TypeDef *FTMx = hftm->Instance; - //assert_param(IS_FTM_INSTANCE(FTMx)); + // FTM_TypeDef *FTMx = hftm->Instance; + // assert_param(IS_FTM_INSTANCE(FTMx)); // Nothing else to do } diff --git a/ports/teensy/hal_ftm.h b/ports/teensy/hal_ftm.h index 84fae8312b..17503c8f2d 100644 --- a/ports/teensy/hal_ftm.h +++ b/ports/teensy/hal_ftm.h @@ -31,64 +31,64 @@ #define FTM2 ((FTM_TypeDef *)&FTM2_SC) typedef struct { - volatile uint32_t CSC; // Channel x Status And Control - volatile uint32_t CV; // Channel x Value + volatile uint32_t CSC; // Channel x Status And Control + volatile uint32_t CV; // Channel x Value } FTM_ChannelTypeDef; typedef struct { - volatile uint32_t SC; // Status And Control - volatile uint32_t CNT; // Counter - volatile uint32_t MOD; // Modulo + volatile uint32_t SC; // Status And Control + volatile uint32_t CNT; // Counter + volatile uint32_t MOD; // Modulo FTM_ChannelTypeDef channel[8]; - volatile uint32_t CNTIN; // Counter Initial Value - volatile uint32_t STATUS; // Capture And Compare Status - volatile uint32_t MODE; // Features Mode Selection - volatile uint32_t SYNC; // Synchronization + volatile uint32_t CNTIN; // Counter Initial Value + volatile uint32_t STATUS; // Capture And Compare Status + volatile uint32_t MODE; // Features Mode Selection + volatile uint32_t SYNC; // Synchronization volatile uint32_t OUTINIT; // Initial State For Channels Output - volatile uint32_t OUTMASK; // Output Mask - volatile uint32_t COMBINE; // Function For Linked Channels + volatile uint32_t OUTMASK; // Output Mask + volatile uint32_t COMBINE; // Function For Linked Channels volatile uint32_t DEADTIME; // Deadtime Insertion Control - volatile uint32_t EXTTRIG; // FTM External Trigger - volatile uint32_t POL; // Channels Polarity - volatile uint32_t FMS; // Fault Mode Status - volatile uint32_t FILTER; // Input Capture Filter Control - volatile uint32_t FLTCTRL; // Fault Control - volatile uint32_t QDCTRL; // Quadrature Decoder Control And Status - volatile uint32_t CONF; // Configuration - volatile uint32_t FLTPOL; // FTM Fault Input Polarity - volatile uint32_t SYNCONF; // Synchronization Configuration - volatile uint32_t INVCTRL; // FTM Inverting Control - volatile uint32_t SWOCTRL; // FTM Software Output Control + volatile uint32_t EXTTRIG; // FTM External Trigger + volatile uint32_t POL; // Channels Polarity + volatile uint32_t FMS; // Fault Mode Status + volatile uint32_t FILTER; // Input Capture Filter Control + volatile uint32_t FLTCTRL; // Fault Control + volatile uint32_t QDCTRL; // Quadrature Decoder Control And Status + volatile uint32_t CONF; // Configuration + volatile uint32_t FLTPOL; // FTM Fault Input Polarity + volatile uint32_t SYNCONF; // Synchronization Configuration + volatile uint32_t INVCTRL; // FTM Inverting Control + volatile uint32_t SWOCTRL; // FTM Software Output Control volatile uint32_t PWMLOAD; // FTM PWM Load } FTM_TypeDef; typedef struct { - uint32_t PrescalerShift; // Sets the prescaler to 1 << PrescalerShift - uint32_t CounterMode; // One of FTM_COUNTERMODE_xxx - uint32_t Period; // Specifies the Period for determining timer overflow + uint32_t PrescalerShift; // Sets the prescaler to 1 << PrescalerShift + uint32_t CounterMode; // One of FTM_COUNTERMODE_xxx + uint32_t Period; // Specifies the Period for determining timer overflow } FTM_Base_InitTypeDef; typedef struct { - uint32_t OCMode; // One of FTM_OCMODE_xxx - uint32_t Pulse; // Specifies initial pulse width (0-0xffff) - uint32_t OCPolarity; // One of FTM_OCPOLRITY_xxx + uint32_t OCMode; // One of FTM_OCMODE_xxx + uint32_t Pulse; // Specifies initial pulse width (0-0xffff) + uint32_t OCPolarity; // One of FTM_OCPOLRITY_xxx } FTM_OC_InitTypeDef; typedef struct { - uint32_t ICPolarity; // Specifies Rising/Falling/Both + uint32_t ICPolarity; // Specifies Rising/Falling/Both } FTM_IC_InitTypeDef; -#define IS_FTM_INSTANCE(INSTANCE) (((INSTANCE) == FTM0) || \ - ((INSTANCE) == FTM1) || \ - ((INSTANCE) == FTM2)) +#define IS_FTM_INSTANCE(INSTANCE) (((INSTANCE) == FTM0) || \ + ((INSTANCE) == FTM1) || \ + ((INSTANCE) == FTM2)) -#define IS_FTM_PRESCALERSHIFT(PRESCALERSHIFT) (((PRESCALERSHIFT) & ~7) == 0) +#define IS_FTM_PRESCALERSHIFT(PRESCALERSHIFT) (((PRESCALERSHIFT)&~7) == 0) #define FTM_COUNTERMODE_UP (0) #define FTM_COUNTERMODE_CENTER (FTM_SC_CPWMS) -#define IS_FTM_COUNTERMODE(MODE) (((MODE) == FTM_COUNTERMODE_UP) ||\ - ((MODE) == FTM_COUNTERMODE_CENTER)) +#define IS_FTM_COUNTERMODE(MODE) (((MODE) == FTM_COUNTERMODE_UP) || \ + ((MODE) == FTM_COUNTERMODE_CENTER)) #define IS_FTM_PERIOD(PERIOD) (((PERIOD) & 0xFFFF0000) == 0) @@ -108,12 +108,12 @@ typedef struct { #define FTM_OCMODE_PWM2 (FTM_CSC_MSB | FTM_CSC_ELSA) #define IS_FTM_OC_MODE(mode) ((mode) == FTM_OCMODE_TIMING || \ - (mode) == FTM_OCMODE_ACTIVE || \ - (mode) == FTM_OCMODE_INACTIVE || \ - (mode) == FTM_OCMODE_TOGGLE ) + (mode) == FTM_OCMODE_ACTIVE || \ + (mode) == FTM_OCMODE_INACTIVE || \ + (mode) == FTM_OCMODE_TOGGLE) #define IS_FTM_PWM_MODE(mode) ((mode) == FTM_OCMODE_PWM1 || \ - (mode) == FTM_OCMODE_PWM2) + (mode) == FTM_OCMODE_PWM2) #define IS_FTM_CHANNEL(channel) (((channel) & ~7) == 0) @@ -122,16 +122,16 @@ typedef struct { #define FTM_OCPOLARITY_HIGH (0) #define FTM_OCPOLARITY_LOW (1) -#define IS_FTM_OC_POLARITY(polarity) ((polarity) == FTM_OCPOLARITY_HIGH || \ - (polarity) == FTM_OCPOLARITY_LOW) +#define IS_FTM_OC_POLARITY(polarity) ((polarity) == FTM_OCPOLARITY_HIGH || \ + (polarity) == FTM_OCPOLARITY_LOW) #define FTM_ICPOLARITY_RISING (FTM_CSC_ELSA) #define FTM_ICPOLARITY_FALLING (FTM_CSC_ELSB) #define FTM_ICPOLARITY_BOTH (FTM_CSC_ELSA | FTM_CSC_ELSB) -#define IS_FTM_IC_POLARITY(polarity) ((polarity) == FTM_ICPOLARITY_RISING || \ - (polarity) == FTM_ICPOLARITY_FALLING || \ - (polarity) == FTM_ICPOLARITY_BOTH) +#define IS_FTM_IC_POLARITY(polarity) ((polarity) == FTM_ICPOLARITY_RISING || \ + (polarity) == FTM_ICPOLARITY_FALLING || \ + (polarity) == FTM_ICPOLARITY_BOTH) typedef enum { HAL_FTM_STATE_RESET = 0x00, @@ -140,9 +140,9 @@ typedef enum { } HAL_FTM_State; typedef struct { - FTM_TypeDef *Instance; - FTM_Base_InitTypeDef Init; - HAL_FTM_State State; + FTM_TypeDef *Instance; + FTM_Base_InitTypeDef Init; + HAL_FTM_State State; } FTM_HandleTypeDef; @@ -166,19 +166,19 @@ void HAL_FTM_Base_Start_IT(FTM_HandleTypeDef *hftm); void HAL_FTM_Base_DeInit(FTM_HandleTypeDef *hftm); void HAL_FTM_OC_Init(FTM_HandleTypeDef *hftm); -void HAL_FTM_OC_ConfigChannel(FTM_HandleTypeDef *hftm, FTM_OC_InitTypeDef* sConfig, uint32_t channel); +void HAL_FTM_OC_ConfigChannel(FTM_HandleTypeDef *hftm, FTM_OC_InitTypeDef *sConfig, uint32_t channel); void HAL_FTM_OC_Start(FTM_HandleTypeDef *hftm, uint32_t channel); void HAL_FTM_OC_Start_IT(FTM_HandleTypeDef *hftm, uint32_t channel); void HAL_FTM_OC_DeInit(FTM_HandleTypeDef *hftm); void HAL_FTM_PWM_Init(FTM_HandleTypeDef *hftm); -void HAL_FTM_PWM_ConfigChannel(FTM_HandleTypeDef *hftm, FTM_OC_InitTypeDef* sConfig, uint32_t channel); +void HAL_FTM_PWM_ConfigChannel(FTM_HandleTypeDef *hftm, FTM_OC_InitTypeDef *sConfig, uint32_t channel); void HAL_FTM_PWM_Start(FTM_HandleTypeDef *hftm, uint32_t channel); void HAL_FTM_PWM_Start_IT(FTM_HandleTypeDef *hftm, uint32_t channel); void HAL_FTM_PWM_DeInit(FTM_HandleTypeDef *hftm); void HAL_FTM_IC_Init(FTM_HandleTypeDef *hftm); -void HAL_FTM_IC_ConfigChannel(FTM_HandleTypeDef *hftm, FTM_IC_InitTypeDef* sConfig, uint32_t channel); +void HAL_FTM_IC_ConfigChannel(FTM_HandleTypeDef *hftm, FTM_IC_InitTypeDef *sConfig, uint32_t channel); void HAL_FTM_IC_Start(FTM_HandleTypeDef *hftm, uint32_t channel); void HAL_FTM_IC_Start_IT(FTM_HandleTypeDef *hftm, uint32_t channel); void HAL_FTM_IC_DeInit(FTM_HandleTypeDef *hftm); diff --git a/ports/teensy/hal_gpio.c b/ports/teensy/hal_gpio.c index f9e137602c..e8bc1eb5ce 100644 --- a/ports/teensy/hal_gpio.c +++ b/ports/teensy/hal_gpio.c @@ -4,8 +4,7 @@ #define GPIO_NUMBER 32 -void HAL_GPIO_Init(GPIO_TypeDef *GPIOx, GPIO_InitTypeDef *GPIO_Init) -{ +void HAL_GPIO_Init(GPIO_TypeDef *GPIOx, GPIO_InitTypeDef *GPIO_Init) { /* Check the parameters */ assert_param(IS_GPIO_PIN(GPIO_Init->Pin)); assert_param(IS_GPIO_MODE(GPIO_Init->Mode)); @@ -24,11 +23,9 @@ void HAL_GPIO_Init(GPIO_TypeDef *GPIOx, GPIO_InitTypeDef *GPIO_Init) if ((GPIO_Init->Mode == GPIO_MODE_AF_PP) || (GPIO_Init->Mode == GPIO_MODE_AF_OD)) { /* Check the Alternate function parameter */ assert_param(IS_GPIO_AF(GPIO_Init->Alternate)); - } - else if (GPIO_Init->Mode == GPIO_MODE_ANALOG) { + } else if (GPIO_Init->Mode == GPIO_MODE_ANALOG) { GPIO_Init->Alternate = 0; - } - else { + } else { GPIO_Init->Alternate = 1; } @@ -80,44 +77,39 @@ void HAL_GPIO_Init(GPIO_TypeDef *GPIOx, GPIO_InitTypeDef *GPIO_Init) } } -#if 0 + #if 0 /*--------------------- EXTI Mode Configuration ------------------------*/ /* Configure the External Interrupt or event for the current IO */ - if((GPIO_Init->Mode & EXTI_MODE) == EXTI_MODE) - { - /* Enable SYSCFG Clock */ - __SYSCFG_CLK_ENABLE(); + if ((GPIO_Init->Mode & EXTI_MODE) == EXTI_MODE) { + /* Enable SYSCFG Clock */ + __SYSCFG_CLK_ENABLE(); - temp = ((uint32_t)0x0F) << (4 * (position & 0x03)); - SYSCFG->EXTICR[position >> 2] &= ~temp; - SYSCFG->EXTICR[position >> 2] |= ((uint32_t)(__HAL_GET_GPIO_SOURCE(GPIOx)) << (4 * (position & 0x03))); + temp = ((uint32_t)0x0F) << (4 * (position & 0x03)); + SYSCFG->EXTICR[position >> 2] &= ~temp; + SYSCFG->EXTICR[position >> 2] |= ((uint32_t)(__HAL_GET_GPIO_SOURCE(GPIOx)) << (4 * (position & 0x03))); - /* Clear EXTI line configuration */ - EXTI->IMR &= ~((uint32_t)iocurrent); - EXTI->EMR &= ~((uint32_t)iocurrent); + /* Clear EXTI line configuration */ + EXTI->IMR &= ~((uint32_t)iocurrent); + EXTI->EMR &= ~((uint32_t)iocurrent); - if((GPIO_Init->Mode & GPIO_MODE_IT) == GPIO_MODE_IT) - { - EXTI->IMR |= iocurrent; - } - if((GPIO_Init->Mode & GPIO_MODE_EVT) == GPIO_MODE_EVT) - { - EXTI->EMR |= iocurrent; - } + if ((GPIO_Init->Mode & GPIO_MODE_IT) == GPIO_MODE_IT) { + EXTI->IMR |= iocurrent; + } + if ((GPIO_Init->Mode & GPIO_MODE_EVT) == GPIO_MODE_EVT) { + EXTI->EMR |= iocurrent; + } - /* Clear Rising Falling edge configuration */ - EXTI->RTSR &= ~((uint32_t)iocurrent); - EXTI->FTSR &= ~((uint32_t)iocurrent); + /* Clear Rising Falling edge configuration */ + EXTI->RTSR &= ~((uint32_t)iocurrent); + EXTI->FTSR &= ~((uint32_t)iocurrent); - if((GPIO_Init->Mode & RISING_EDGE) == RISING_EDGE) - { - EXTI->RTSR |= iocurrent; - } - if((GPIO_Init->Mode & FALLING_EDGE) == FALLING_EDGE) - { - EXTI->FTSR |= iocurrent; - } + if ((GPIO_Init->Mode & RISING_EDGE) == RISING_EDGE) { + EXTI->RTSR |= iocurrent; + } + if ((GPIO_Init->Mode & FALLING_EDGE) == FALLING_EDGE) { + EXTI->FTSR |= iocurrent; + } } -#endif + #endif } } diff --git a/ports/teensy/help.c b/ports/teensy/help.c index a2370c04d2..11625afc5a 100644 --- a/ports/teensy/help.c +++ b/ports/teensy/help.c @@ -27,43 +27,43 @@ #include "py/builtin.h" const char teensy_help_text[] = -"Welcome to MicroPython!\n" -"\n" -"For online help please visit http://micropython.org/help/.\n" -"\n" -"Quick overview of commands for the board:\n" -" pyb.info() -- print some general information\n" -" pyb.gc() -- run the garbage collector\n" -" pyb.delay(n) -- wait for n milliseconds\n" -" pyb.Switch() -- create a switch object\n" -" Switch methods: (), callback(f)\n" -" pyb.LED(n) -- create an LED object for LED n (n=1,2,3,4)\n" -" LED methods: on(), off(), toggle(), intensity()\n" -" pyb.Pin(pin) -- get a pin, eg pyb.Pin('X1')\n" -" pyb.Pin(pin, m, [p]) -- get a pin and configure it for IO mode m, pull mode p\n" -" Pin methods: init(..), value([v]), high(), low()\n" -" pyb.ExtInt(pin, m, p, callback) -- create an external interrupt object\n" -" pyb.ADC(pin) -- make an analog object from a pin\n" -" ADC methods: read(), read_timed(buf, freq)\n" -" pyb.DAC(port) -- make a DAC object\n" -" DAC methods: triangle(freq), write(n), write_timed(buf, freq)\n" -" pyb.RTC() -- make an RTC object; methods: datetime([val])\n" -" pyb.rng() -- get a 30-bit hardware random number\n" -" pyb.Servo(n) -- create Servo object for servo n (n=1,2,3,4)\n" -" Servo methods: calibration(..), angle([x, [t]]), speed([x, [t]])\n" -" pyb.Accel() -- create an Accelerometer object\n" -" Accelerometer methods: x(), y(), z(), tilt(), filtered_xyz()\n" -"\n" -"Pins are numbered X1-X12, X17-X22, Y1-Y12, or by their MCU name\n" -"Pin IO modes are: pyb.Pin.IN, pyb.Pin.OUT_PP, pyb.Pin.OUT_OD\n" -"Pin pull modes are: pyb.Pin.PULL_NONE, pyb.Pin.PULL_UP, pyb.Pin.PULL_DOWN\n" -"Additional serial bus objects: pyb.I2C(n), pyb.SPI(n), pyb.UART(n)\n" -"\n" -"Control commands:\n" -" CTRL-A -- on a blank line, enter raw REPL mode\n" -" CTRL-B -- on a blank line, enter normal REPL mode\n" -" CTRL-C -- interrupt a running program\n" -" CTRL-D -- on a blank line, do a soft reset of the board\n" -"\n" -"For further help on a specific object, type help(obj)\n" + "Welcome to MicroPython!\n" + "\n" + "For online help please visit http://micropython.org/help/.\n" + "\n" + "Quick overview of commands for the board:\n" + " pyb.info() -- print some general information\n" + " pyb.gc() -- run the garbage collector\n" + " pyb.delay(n) -- wait for n milliseconds\n" + " pyb.Switch() -- create a switch object\n" + " Switch methods: (), callback(f)\n" + " pyb.LED(n) -- create an LED object for LED n (n=1,2,3,4)\n" + " LED methods: on(), off(), toggle(), intensity()\n" + " pyb.Pin(pin) -- get a pin, eg pyb.Pin('X1')\n" + " pyb.Pin(pin, m, [p]) -- get a pin and configure it for IO mode m, pull mode p\n" + " Pin methods: init(..), value([v]), high(), low()\n" + " pyb.ExtInt(pin, m, p, callback) -- create an external interrupt object\n" + " pyb.ADC(pin) -- make an analog object from a pin\n" + " ADC methods: read(), read_timed(buf, freq)\n" + " pyb.DAC(port) -- make a DAC object\n" + " DAC methods: triangle(freq), write(n), write_timed(buf, freq)\n" + " pyb.RTC() -- make an RTC object; methods: datetime([val])\n" + " pyb.rng() -- get a 30-bit hardware random number\n" + " pyb.Servo(n) -- create Servo object for servo n (n=1,2,3,4)\n" + " Servo methods: calibration(..), angle([x, [t]]), speed([x, [t]])\n" + " pyb.Accel() -- create an Accelerometer object\n" + " Accelerometer methods: x(), y(), z(), tilt(), filtered_xyz()\n" + "\n" + "Pins are numbered X1-X12, X17-X22, Y1-Y12, or by their MCU name\n" + "Pin IO modes are: pyb.Pin.IN, pyb.Pin.OUT_PP, pyb.Pin.OUT_OD\n" + "Pin pull modes are: pyb.Pin.PULL_NONE, pyb.Pin.PULL_UP, pyb.Pin.PULL_DOWN\n" + "Additional serial bus objects: pyb.I2C(n), pyb.SPI(n), pyb.UART(n)\n" + "\n" + "Control commands:\n" + " CTRL-A -- on a blank line, enter raw REPL mode\n" + " CTRL-B -- on a blank line, enter normal REPL mode\n" + " CTRL-C -- interrupt a running program\n" + " CTRL-D -- on a blank line, do a soft reset of the board\n" + "\n" + "For further help on a specific object, type help(obj)\n" ; diff --git a/ports/teensy/led.c b/ports/teensy/led.c index cf59dbd0a3..6e0b511134 100644 --- a/ports/teensy/led.c +++ b/ports/teensy/led.c @@ -16,15 +16,15 @@ typedef struct _pyb_led_obj_t { STATIC const pyb_led_obj_t pyb_led_obj[] = { {{&pyb_led_type}, 1, &MICROPY_HW_LED1}, -#if defined(MICROPY_HW_LED2) + #if defined(MICROPY_HW_LED2) {{&pyb_led_type}, 2, &MICROPY_HW_LED2}, -#if defined(MICROPY_HW_LED3) + #if defined(MICROPY_HW_LED3) {{&pyb_led_type}, 3, &MICROPY_HW_LED3}, -#if defined(MICROPY_HW_LED4) + #if defined(MICROPY_HW_LED4) {{&pyb_led_type}, 4, &MICROPY_HW_LED4}, -#endif -#endif -#endif + #endif + #endif + #endif }; #define NUM_LEDS MP_ARRAY_SIZE(pyb_led_obj) @@ -51,7 +51,7 @@ void led_state(pyb_led_t led, int state) { return; } const pin_obj_t *led_pin = pyb_led_obj[led - 1].led_pin; - //printf("led_state(%d,%d)\n", led, state); + // printf("led_state(%d,%d)\n", led, state); if (state == 0) { // turn LED off MICROPY_HW_LED_OFF(led_pin); diff --git a/ports/teensy/main.c b/ports/teensy/main.c index 3edaa28a06..5df730a99a 100644 --- a/ports/teensy/main.c +++ b/ports/teensy/main.c @@ -93,7 +93,7 @@ mp_obj_t pyb_analog_write_frequency(mp_obj_t pin_obj, mp_obj_t freq_obj) { static mp_obj_t pyb_info(void) { // get and print unique id; 96 bits { - byte *id = (byte*)0x40048058; + byte *id = (byte *)0x40048058; printf("ID=%02x%02x%02x%02x:%02x%02x%02x%02x:%02x%02x%02x%02x\n", id[0], id[1], id[2], id[3], id[4], id[5], id[6], id[7], id[8], id[9], id[10], id[11]); } @@ -121,7 +121,7 @@ static mp_obj_t pyb_info(void) { printf(" 1=%u 2=%u m=%u\n", info.num_1block, info.num_2block, info.max_block); } -#if 0 + #if 0 // free space on flash { DWORD nclst; @@ -129,7 +129,7 @@ static mp_obj_t pyb_info(void) { f_getfree("0:", &nclst, &fatfs); printf("LFS free: %u bytes\n", (uint)(nclst * fatfs->csize * 512)); } -#endif + #endif return mp_const_none; } @@ -150,7 +150,7 @@ mp_obj_t pyb_gc(void) { } mp_obj_t pyb_gpio(int n_args, mp_obj_t *args) { - //assert(1 <= n_args && n_args <= 2); + // assert(1 <= n_args && n_args <= 2); uint pin = mp_obj_get_int(args[0]); if (pin > CORE_NUM_DIGITAL) { @@ -162,7 +162,7 @@ mp_obj_t pyb_gpio(int n_args, mp_obj_t *args) { pinMode(pin, INPUT); return MP_OBJ_NEW_SMALL_INT(digitalRead(pin)); } - + // set pin pinMode(pin, OUTPUT); digitalWrite(pin, mp_obj_is_true(args[1])); @@ -264,7 +264,7 @@ soft_reset: led_state(PYB_LED_BUILTIN, 1); // GC init - gc_init(&_heap_start, (void*)HEAP_END); + gc_init(&_heap_start, (void *)HEAP_END); // MicroPython init mp_init(); @@ -276,7 +276,7 @@ soft_reset: pin_init0(); -#if 0 + #if 0 // add some functions to the python namespace { mp_store_name(MP_QSTR_help, mp_make_function_n(0, pyb_help)); @@ -297,23 +297,23 @@ soft_reset: mp_store_attr(m, MP_QSTR_Servo, mp_make_function_n(0, pyb_Servo)); mp_store_name(MP_QSTR_pyb, m); } -#endif + #endif -#if MICROPY_MODULE_FROZEN + #if MICROPY_MODULE_FROZEN pyexec_frozen_module("boot.py"); -#else + #else if (!pyexec_file("/boot.py")) { flash_error(4); } -#endif + #endif // Turn bootup LED off led_state(PYB_LED_BUILTIN, 0); // run main script -#if MICROPY_MODULE_FROZEN + #if MICROPY_MODULE_FROZEN pyexec_frozen_module("main.py"); -#else + #else { vstr_t *vstr = vstr_new(16); vstr_add_str(vstr, "/"); @@ -327,7 +327,7 @@ soft_reset: } vstr_free(vstr); } -#endif + #endif // enter REPL // REPL mode can change, or it can request a soft reset @@ -358,24 +358,25 @@ void __libc_init_array(void) { // ultoa is used by usb_init_serialnumber. Normally ultoa would be provided // by nonstd.c from the teensy core, but it conflicts with some of the // MicroPython functions in string0.c, so we provide ultoa here. -char * ultoa(unsigned long val, char *buf, int radix) -{ - unsigned digit; - int i=0, j; - char t; +char *ultoa(unsigned long val, char *buf, int radix) { + unsigned digit; + int i = 0, j; + char t; - while (1) { - digit = val % radix; - buf[i] = ((digit < 10) ? '0' + digit : 'A' + digit - 10); - val /= radix; - if (val == 0) break; - i++; - } - buf[i + 1] = 0; - for (j=0; j < i; j++, i--) { - t = buf[j]; - buf[j] = buf[i]; - buf[i] = t; - } - return buf; + while (1) { + digit = val % radix; + buf[i] = ((digit < 10) ? '0' + digit : 'A' + digit - 10); + val /= radix; + if (val == 0) { + break; + } + i++; + } + buf[i + 1] = 0; + for (j = 0; j < i; j++, i--) { + t = buf[j]; + buf[j] = buf[i]; + buf[i] = t; + } + return buf; } diff --git a/ports/teensy/make-pins.py b/ports/teensy/make-pins.py index 0f6c5f28d4..4e46a8c244 100755 --- a/ports/teensy/make-pins.py +++ b/ports/teensy/make-pins.py @@ -8,33 +8,34 @@ import sys import csv SUPPORTED_FN = { - 'FTM' : ['CH0', 'CH1', 'CH2', 'CH3', 'CH4', 'CH5', 'CH6', 'CH7', - 'QD_PHA', 'QD_PHB'], - 'I2C' : ['SDA', 'SCL'], - 'UART' : ['RX', 'TX', 'CTS', 'RTS'], - 'SPI' : ['NSS', 'SCK', 'MISO', 'MOSI'] + "FTM": ["CH0", "CH1", "CH2", "CH3", "CH4", "CH5", "CH6", "CH7", "QD_PHA", "QD_PHB"], + "I2C": ["SDA", "SCL"], + "UART": ["RX", "TX", "CTS", "RTS"], + "SPI": ["NSS", "SCK", "MISO", "MOSI"], } + def parse_port_pin(name_str): """Parses a string and returns a (port-num, pin-num) tuple.""" if len(name_str) < 4: raise ValueError("Expecting pin name to be at least 4 charcters.") - if name_str[0:2] != 'PT': + if name_str[0:2] != "PT": raise ValueError("Expecting pin name to start with PT") - if name_str[2] not in ('A', 'B', 'C', 'D', 'E', 'Z'): + if name_str[2] not in ("A", "B", "C", "D", "E", "Z"): raise ValueError("Expecting pin port to be between A and E or Z") - port = ord(name_str[2]) - ord('A') - pin_str = name_str[3:].split('/')[0] + port = ord(name_str[2]) - ord("A") + pin_str = name_str[3:].split("/")[0] if not pin_str.isdigit(): raise ValueError("Expecting numeric pin number.") return (port, int(pin_str)) + def split_name_num(name_num): num = None for num_idx in range(len(name_num) - 1, -1, -1): if not name_num[num_idx].isdigit(): - name = name_num[0:num_idx + 1] - num_str = name_num[num_idx + 1:] + name = name_num[0 : num_idx + 1] + num_str = name_num[num_idx + 1 :] if len(num_str) > 0: num = int(num_str) break @@ -48,12 +49,12 @@ class AlternateFunction(object): self.idx = idx self.af_str = af_str - self.func = '' + self.func = "" self.fn_num = None - self.pin_type = '' + self.pin_type = "" self.supported = False - af_words = af_str.split('_', 1) + af_words = af_str.split("_", 1) self.func, self.fn_num = split_name_num(af_words[0]) if len(af_words) > 1: self.pin_type = af_words[1] @@ -69,22 +70,25 @@ class AlternateFunction(object): """Returns the numbered function (i.e. USART6) for this AF.""" if self.fn_num is None: return self.func - return '{:s}{:d}'.format(self.func, self.fn_num) + return "{:s}{:d}".format(self.func, self.fn_num) def mux_name(self): - return 'AF{:d}_{:s}'.format(self.idx, self.ptr()) + return "AF{:d}_{:s}".format(self.idx, self.ptr()) def print(self): """Prints the C representation of this AF.""" if self.supported: - print(' AF', end='') + print(" AF", end="") else: - print(' //', end='') + print(" //", end="") fn_num = self.fn_num if fn_num is None: fn_num = 0 - print('({:2d}, {:8s}, {:2d}, {:10s}, {:8s}), // {:s}'.format(self.idx, - self.func, fn_num, self.pin_type, self.ptr(), self.af_str)) + print( + "({:2d}, {:8s}, {:2d}, {:10s}, {:8s}), // {:s}".format( + self.idx, self.func, fn_num, self.pin_type, self.ptr(), self.af_str + ) + ) def qstr_list(self): return [self.mux_name()] @@ -103,10 +107,10 @@ class Pin(object): self.board_pin = False def port_letter(self): - return chr(self.port + ord('A')) + return chr(self.port + ord("A")) def cpu_pin_name(self): - return '{:s}{:d}'.format(self.port_letter(), self.pin) + return "{:s}{:d}".format(self.port_letter(), self.pin) def is_board_pin(self): return self.board_pin @@ -115,12 +119,12 @@ class Pin(object): self.board_pin = True def parse_adc(self, adc_str): - if (adc_str[:3] != 'ADC'): + if adc_str[:3] != "ADC": return - (adc,channel) = adc_str.split('_') + (adc, channel) = adc_str.split("_") for idx in range(3, len(adc)): - adc_num = int(adc[idx]) # 1, 2, or 3 - self.adc_num |= (1 << (adc_num - 1)) + adc_num = int(adc[idx]) # 1, 2, or 3 + self.adc_num |= 1 << (adc_num - 1) self.adc_channel = int(channel[2:]) def parse_af(self, af_idx, af_strs_in): @@ -128,7 +132,7 @@ class Pin(object): return # If there is a slash, then the slash separates 2 aliases for the # same alternate function. - af_strs = af_strs_in.split('/') + af_strs = af_strs_in.split("/") for af_str in af_strs: alt_fn = AlternateFunction(af_idx, af_str) self.alt_fn.append(alt_fn) @@ -137,43 +141,50 @@ class Pin(object): def alt_fn_name(self, null_if_0=False): if null_if_0 and self.alt_fn_count == 0: - return 'NULL' - return 'pin_{:s}_af'.format(self.cpu_pin_name()) + return "NULL" + return "pin_{:s}_af".format(self.cpu_pin_name()) def adc_num_str(self): - str = '' - for adc_num in range(1,4): + str = "" + for adc_num in range(1, 4): if self.adc_num & (1 << (adc_num - 1)): if len(str) > 0: - str += ' | ' - str += 'PIN_ADC' - str += chr(ord('0') + adc_num) + str += " | " + str += "PIN_ADC" + str += chr(ord("0") + adc_num) if len(str) == 0: - str = '0' + str = "0" return str def print(self): if self.alt_fn_count == 0: - print("// ", end='') - print('const pin_af_obj_t {:s}[] = {{'.format(self.alt_fn_name())) + print("// ", end="") + print("const pin_af_obj_t {:s}[] = {{".format(self.alt_fn_name())) for alt_fn in self.alt_fn: alt_fn.print() if self.alt_fn_count == 0: - print("// ", end='') - print('};') - print('') - print('const pin_obj_t pin_{:s} = PIN({:s}, {:d}, {:d}, {:s}, {:s}, {:d});'.format( - self.cpu_pin_name(), self.port_letter(), self.pin, - self.alt_fn_count, self.alt_fn_name(null_if_0=True), - self.adc_num_str(), self.adc_channel)) - print('') + print("// ", end="") + print("};") + print("") + print( + "const pin_obj_t pin_{:s} = PIN({:s}, {:d}, {:d}, {:s}, {:s}, {:d});".format( + self.cpu_pin_name(), + self.port_letter(), + self.pin, + self.alt_fn_count, + self.alt_fn_name(null_if_0=True), + self.adc_num_str(), + self.adc_channel, + ) + ) + print("") def print_header(self, hdr_file): - hdr_file.write('extern const pin_obj_t pin_{:s};\n'. - format(self.cpu_pin_name())) + hdr_file.write("extern const pin_obj_t pin_{:s};\n".format(self.cpu_pin_name())) if self.alt_fn_count > 0: - hdr_file.write('extern const pin_af_obj_t pin_{:s}_af[];\n'. - format(self.cpu_pin_name())) + hdr_file.write( + "extern const pin_af_obj_t pin_{:s}_af[];\n".format(self.cpu_pin_name()) + ) def qstr_list(self): result = [] @@ -184,7 +195,6 @@ class Pin(object): class NamedPin(object): - def __init__(self, name, pin): self._name = name self._pin = pin @@ -197,10 +207,9 @@ class NamedPin(object): class Pins(object): - def __init__(self): - self.cpu_pins = [] # list of NamedPin objects - self.board_pins = [] # list of NamedPin objects + self.cpu_pins = [] # list of NamedPin objects + self.board_pins = [] # list of NamedPin objects def find_pin(self, port_num, pin_num): for named_pin in self.cpu_pins: @@ -209,7 +218,7 @@ class Pins(object): return pin def parse_af_file(self, filename, pinname_col, af_col): - with open(filename, 'r') as csvfile: + with open(filename, "r") as csvfile: rows = csv.reader(csvfile) for row in rows: try: @@ -223,7 +232,7 @@ class Pins(object): self.cpu_pins.append(NamedPin(pin.cpu_pin_name(), pin)) def parse_board_file(self, filename): - with open(filename, 'r') as csvfile: + with open(filename, "r") as csvfile: rows = csv.reader(csvfile) for row in rows: try: @@ -236,52 +245,64 @@ class Pins(object): self.board_pins.append(NamedPin(row[0], pin)) def print_named(self, label, named_pins): - print('STATIC const mp_rom_map_elem_t pin_{:s}_pins_locals_dict_table[] = {{'.format(label)) + print( + "STATIC const mp_rom_map_elem_t pin_{:s}_pins_locals_dict_table[] = {{".format(label) + ) for named_pin in named_pins: pin = named_pin.pin() if pin.is_board_pin(): - print(' {{ MP_ROM_QSTR(MP_QSTR_{:s}), MP_ROM_PTR(&pin_{:s}) }},'.format(named_pin.name(), pin.cpu_pin_name())) - print('};') - print('MP_DEFINE_CONST_DICT(pin_{:s}_pins_locals_dict, pin_{:s}_pins_locals_dict_table);'.format(label, label)); + print( + " {{ MP_ROM_QSTR(MP_QSTR_{:s}), MP_ROM_PTR(&pin_{:s}) }},".format( + named_pin.name(), pin.cpu_pin_name() + ) + ) + print("};") + print( + "MP_DEFINE_CONST_DICT(pin_{:s}_pins_locals_dict, pin_{:s}_pins_locals_dict_table);".format( + label, label + ) + ) def print(self): for named_pin in self.cpu_pins: pin = named_pin.pin() if pin.is_board_pin(): pin.print() - self.print_named('cpu', self.cpu_pins) - print('') - self.print_named('board', self.board_pins) + self.print_named("cpu", self.cpu_pins) + print("") + self.print_named("board", self.board_pins) def print_adc(self, adc_num): - print(''); - print('const pin_obj_t * const pin_adc{:d}[] = {{'.format(adc_num)) + print("") + print("const pin_obj_t * const pin_adc{:d}[] = {{".format(adc_num)) for channel in range(16): adc_found = False for named_pin in self.cpu_pins: pin = named_pin.pin() - if (pin.is_board_pin() and - (pin.adc_num & (1 << (adc_num - 1))) and (pin.adc_channel == channel)): - print(' &pin_{:s}, // {:d}'.format(pin.cpu_pin_name(), channel)) + if ( + pin.is_board_pin() + and (pin.adc_num & (1 << (adc_num - 1))) + and (pin.adc_channel == channel) + ): + print(" &pin_{:s}, // {:d}".format(pin.cpu_pin_name(), channel)) adc_found = True break if not adc_found: - print(' NULL, // {:d}'.format(channel)) - print('};') - + print(" NULL, // {:d}".format(channel)) + print("};") def print_header(self, hdr_filename): - with open(hdr_filename, 'wt') as hdr_file: + with open(hdr_filename, "wt") as hdr_file: for named_pin in self.cpu_pins: pin = named_pin.pin() if pin.is_board_pin(): pin.print_header(hdr_file) - hdr_file.write('extern const pin_obj_t * const pin_adc1[];\n') - hdr_file.write('extern const pin_obj_t * const pin_adc2[];\n') - hdr_file.write('extern const pin_obj_t * const pin_adc3[];\n') + hdr_file.write("extern const pin_obj_t * const pin_adc1[];\n") + hdr_file.write("extern const pin_obj_t * const pin_adc2[];\n") + hdr_file.write("extern const pin_obj_t * const pin_adc3[];\n") def print_qstr(self, qstr_filename): - with open(qstr_filename, 'wt') as qstr_file: + with open(qstr_filename, "wt") as qstr_file: qstr_set = set([]) for named_pin in self.cpu_pins: pin = named_pin.pin() @@ -291,11 +312,10 @@ class Pins(object): for named_pin in self.board_pins: qstr_set |= set([named_pin.name()]) for qstr in sorted(qstr_set): - print('Q({})'.format(qstr), file=qstr_file) - + print("Q({})".format(qstr), file=qstr_file) def print_af_hdr(self, af_const_filename): - with open(af_const_filename, 'wt') as af_const_file: + with open(af_const_filename, "wt") as af_const_file: af_hdr_set = set([]) mux_name_width = 0 for named_pin in self.cpu_pins: @@ -308,88 +328,92 @@ class Pins(object): if len(mux_name) > mux_name_width: mux_name_width = len(mux_name) for mux_name in sorted(af_hdr_set): - key = 'MP_OBJ_NEW_QSTR(MP_QSTR_{}),'.format(mux_name) - val = 'MP_OBJ_NEW_SMALL_INT(GPIO_{})'.format(mux_name) - print(' { %-*s %s },' % (mux_name_width + 26, key, val), - file=af_const_file) + key = "MP_OBJ_NEW_QSTR(MP_QSTR_{}),".format(mux_name) + val = "MP_OBJ_NEW_SMALL_INT(GPIO_{})".format(mux_name) + print(" { %-*s %s }," % (mux_name_width + 26, key, val), file=af_const_file) def print_af_py(self, af_py_filename): - with open(af_py_filename, 'wt') as af_py_file: - print('PINS_AF = (', file=af_py_file); + with open(af_py_filename, "wt") as af_py_file: + print("PINS_AF = (", file=af_py_file) for named_pin in self.board_pins: - print(" ('%s', " % named_pin.name(), end='', file=af_py_file) + print(" ('%s', " % named_pin.name(), end="", file=af_py_file) for af in named_pin.pin().alt_fn: if af.is_supported(): - print("(%d, '%s'), " % (af.idx, af.af_str), end='', file=af_py_file) - print('),', file=af_py_file) - print(')', file=af_py_file) + print("(%d, '%s'), " % (af.idx, af.af_str), end="", file=af_py_file) + print("),", file=af_py_file) + print(")", file=af_py_file) def main(): parser = argparse.ArgumentParser( prog="make-pins.py", usage="%(prog)s [options] [command]", - description="Generate board specific pin file" + description="Generate board specific pin file", ) parser.add_argument( - "-a", "--af", + "-a", + "--af", dest="af_filename", help="Specifies the alternate function file for the chip", - default="mk20dx256_af.csv" + default="mk20dx256_af.csv", ) parser.add_argument( "--af-const", dest="af_const_filename", help="Specifies header file for alternate function constants.", - default="build/pins_af_const.h" + default="build/pins_af_const.h", ) parser.add_argument( "--af-py", dest="af_py_filename", help="Specifies the filename for the python alternate function mappings.", - default="build/pins_af.py" + default="build/pins_af.py", ) parser.add_argument( - "-b", "--board", + "-b", + "--board", dest="board_filename", help="Specifies the board file", ) parser.add_argument( - "-p", "--prefix", + "-p", + "--prefix", dest="prefix_filename", help="Specifies beginning portion of generated pins file", - default="mk20dx256_prefix.c" + default="mk20dx256_prefix.c", ) parser.add_argument( - "-q", "--qstr", + "-q", + "--qstr", dest="qstr_filename", help="Specifies name of generated qstr header file", - default="build/pins_qstr.h" + default="build/pins_qstr.h", ) parser.add_argument( - "-r", "--hdr", + "-r", + "--hdr", dest="hdr_filename", help="Specifies name of generated pin header file", - default="build/pins.h" + default="build/pins.h", ) args = parser.parse_args(sys.argv[1:]) pins = Pins() - print('// This file was automatically generated by make-pins.py') - print('//') + print("// This file was automatically generated by make-pins.py") + print("//") if args.af_filename: - print('// --af {:s}'.format(args.af_filename)) + print("// --af {:s}".format(args.af_filename)) pins.parse_af_file(args.af_filename, 4, 3) if args.board_filename: - print('// --board {:s}'.format(args.board_filename)) + print("// --board {:s}".format(args.board_filename)) pins.parse_board_file(args.board_filename) if args.prefix_filename: - print('// --prefix {:s}'.format(args.prefix_filename)) - print('') - with open(args.prefix_filename, 'r') as prefix_file: + print("// --prefix {:s}".format(args.prefix_filename)) + print("") + with open(args.prefix_filename, "r") as prefix_file: print(prefix_file.read()) pins.print() pins.print_adc(1) diff --git a/ports/teensy/mk20dx256_prefix.c b/ports/teensy/mk20dx256_prefix.c index 58ab07d6ec..4790bb83ca 100644 --- a/ports/teensy/mk20dx256_prefix.c +++ b/ports/teensy/mk20dx256_prefix.c @@ -8,26 +8,26 @@ #include "pin.h" #define AF(af_idx, af_fn, af_unit, af_type, af_ptr) \ -{ \ - { &pin_af_type }, \ - .name = MP_QSTR_AF ## af_idx ## _ ## af_fn ## af_unit, \ - .idx = (af_idx), \ - .fn = AF_FN_ ## af_fn, \ - .unit = (af_unit), \ - .type = AF_PIN_TYPE_ ## af_fn ## _ ## af_type, \ - .reg = (af_ptr) \ -} + { \ + { &pin_af_type }, \ + .name = MP_QSTR_AF##af_idx##_##af_fn##af_unit, \ + .idx = (af_idx), \ + .fn = AF_FN_##af_fn, \ + .unit = (af_unit), \ + .type = AF_PIN_TYPE_##af_fn##_##af_type, \ + .reg = (af_ptr) \ + } #define PIN(p_port, p_pin, p_num_af, p_af, p_adc_num, p_adc_channel) \ -{ \ - { &pin_type }, \ - .name = MP_QSTR_ ## p_port ## p_pin, \ - .port = PORT_ ## p_port, \ - .pin = (p_pin), \ - .num_af = (p_num_af), \ - .pin_mask = (1 << (p_pin)), \ - .gpio = GPIO ## p_port, \ - .af = p_af, \ - .adc_num = p_adc_num, \ - .adc_channel = p_adc_channel, \ -} + { \ + { &pin_type }, \ + .name = MP_QSTR_##p_port##p_pin, \ + .port = PORT_##p_port, \ + .pin = (p_pin), \ + .num_af = (p_num_af), \ + .pin_mask = (1 << (p_pin)), \ + .gpio = GPIO##p_port, \ + .af = p_af, \ + .adc_num = p_adc_num, \ + .adc_channel = p_adc_channel, \ + } diff --git a/ports/teensy/modpyb.c b/ports/teensy/modpyb.c index e4c399fc84..af1f83cc52 100644 --- a/ports/teensy/modpyb.c +++ b/ports/teensy/modpyb.c @@ -44,9 +44,9 @@ #include "extint.h" #include "usrsw.h" #include "rng.h" -//#include "rtc.h" -//#include "i2c.h" -//#include "spi.h" +// #include "rtc.h" +// #include "i2c.h" +// #include "spi.h" #include "uart.h" #include "adc.h" #include "storage.h" @@ -74,7 +74,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_0(pyb_bootloader_obj, pyb_bootloader); STATIC mp_obj_t pyb_info(uint n_args, const mp_obj_t *args) { // get and print unique id; 96 bits { - byte *id = (byte*)0x40048058; + byte *id = (byte *)0x40048058; printf("ID=%02x%02x%02x%02x:%02x%02x%02x%02x:%02x%02x%02x%02x\n", id[0], id[1], id[2], id[3], id[4], id[5], id[6], id[7], id[8], id[9], id[10], id[11]); } @@ -125,7 +125,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_info_obj, 0, 1, pyb_info); /// \function unique_id() /// Returns a string of 12 bytes (96 bits), which is the unique ID for the MCU. STATIC mp_obj_t pyb_unique_id(void) { - byte *id = (byte*)0x40048058; + byte *id = (byte *)0x40048058; return mp_obj_new_bytes(id, 12); } STATIC MP_DEFINE_CONST_FUN_OBJ_0(pyb_unique_id_obj, pyb_unique_id); @@ -135,9 +135,9 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_0(pyb_unique_id_obj, pyb_unique_id); // TODO should also be able to set frequency via this function STATIC mp_obj_t pyb_freq(void) { mp_obj_t tuple[3] = { - mp_obj_new_int(F_CPU), - mp_obj_new_int(F_BUS), - mp_obj_new_int(F_MEM), + mp_obj_new_int(F_CPU), + mp_obj_new_int(F_BUS), + mp_obj_new_int(F_MEM), }; return mp_obj_new_tuple(3, tuple); } @@ -247,7 +247,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_0(pyb_standby_obj, pyb_standby); /// \function have_cdc() /// Return True if USB is connected as a serial device, False otherwise. -STATIC mp_obj_t pyb_have_cdc(void ) { +STATIC mp_obj_t pyb_have_cdc(void) { return mp_obj_new_bool(usb_vcp_is_connected()); } STATIC MP_DEFINE_CONST_FUN_OBJ_0(pyb_have_cdc_obj, pyb_have_cdc); @@ -256,9 +256,9 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_0(pyb_have_cdc_obj, pyb_have_cdc); /// Takes a 4-tuple (or list) and sends it to the USB host (the PC) to /// signal a HID mouse-motion event. STATIC mp_obj_t pyb_hid_send_report(mp_obj_t arg) { -#if 1 + #if 1 printf("hid_send_report not currently implemented\n"); -#else + #else mp_obj_t *items; mp_obj_get_array_fixed_n(arg, 4, &items); uint8_t data[4]; @@ -267,7 +267,7 @@ STATIC mp_obj_t pyb_hid_send_report(mp_obj_t arg) { data[2] = mp_obj_get_int(items[2]); data[3] = mp_obj_get_int(items[3]); usb_hid_send_report(data); -#endif + #endif return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_hid_send_report_obj, pyb_hid_send_report); @@ -308,30 +308,30 @@ STATIC const mp_rom_map_elem_t pyb_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_Timer), MP_ROM_PTR(&pyb_timer_type) }, -//#if MICROPY_HW_ENABLE_RNG +// #if MICROPY_HW_ENABLE_RNG // { MP_ROM_QSTR(MP_QSTR_rng), MP_ROM_PTR(&pyb_rng_get_obj) }, -//#endif +// #endif -//#if MICROPY_HW_ENABLE_RTC +// #if MICROPY_HW_ENABLE_RTC // { MP_ROM_QSTR(MP_QSTR_RTC), MP_ROM_PTR(&pyb_rtc_type) }, -//#endif +// #endif { MP_ROM_QSTR(MP_QSTR_Pin), MP_ROM_PTR(&pin_type) }, // { MP_ROM_QSTR(MP_QSTR_ExtInt), MP_ROM_PTR(&extint_type) }, -#if MICROPY_HW_ENABLE_SERVO + #if MICROPY_HW_ENABLE_SERVO { MP_ROM_QSTR(MP_QSTR_pwm), MP_ROM_PTR(&pyb_pwm_set_obj) }, { MP_ROM_QSTR(MP_QSTR_servo), MP_ROM_PTR(&pyb_servo_set_obj) }, { MP_ROM_QSTR(MP_QSTR_Servo), MP_ROM_PTR(&pyb_servo_type) }, -#endif + #endif -#if MICROPY_HW_HAS_SWITCH + #if MICROPY_HW_HAS_SWITCH { MP_ROM_QSTR(MP_QSTR_Switch), MP_ROM_PTR(&pyb_switch_type) }, -#endif + #endif -//#if MICROPY_HW_HAS_SDCARD +// #if MICROPY_HW_HAS_SDCARD // { MP_ROM_QSTR(MP_QSTR_SD), MP_ROM_PTR(&pyb_sdcard_obj) }, -//#endif +// #endif { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pyb_led_type) }, // { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&pyb_i2c_type) }, @@ -341,18 +341,18 @@ STATIC const mp_rom_map_elem_t pyb_module_globals_table[] = { // { MP_ROM_QSTR(MP_QSTR_ADC), MP_ROM_PTR(&pyb_adc_type) }, // { MP_ROM_QSTR(MP_QSTR_ADCAll), MP_ROM_PTR(&pyb_adc_all_type) }, -//#if MICROPY_HW_ENABLE_DAC +// #if MICROPY_HW_ENABLE_DAC // { MP_ROM_QSTR(MP_QSTR_DAC), MP_ROM_PTR(&pyb_dac_type) }, -//#endif +// #endif -//#if MICROPY_HW_HAS_MMA7660 +// #if MICROPY_HW_HAS_MMA7660 // { MP_ROM_QSTR(MP_QSTR_Accel), MP_ROM_PTR(&pyb_accel_type) }, -//#endif +// #endif }; STATIC MP_DEFINE_CONST_DICT(pyb_module_globals, pyb_module_globals_table); const mp_obj_module_t pyb_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&pyb_module_globals, + .globals = (mp_obj_dict_t *)&pyb_module_globals, }; diff --git a/ports/teensy/mpconfigport.h b/ports/teensy/mpconfigport.h index b45b5ad4e3..4c3782fa8a 100644 --- a/ports/teensy/mpconfigport.h +++ b/ports/teensy/mpconfigport.h @@ -72,24 +72,24 @@ typedef long mp_off_t; // to know the machine-specific values, see irq.h. #ifndef __disable_irq -#define __disable_irq() __asm__ volatile("CPSID i"); +#define __disable_irq() __asm__ volatile ("CPSID i"); #endif -__attribute__(( always_inline )) static inline uint32_t __get_PRIMASK(void) { +__attribute__((always_inline)) static inline uint32_t __get_PRIMASK(void) { uint32_t result; __asm volatile ("MRS %0, primask" : "=r" (result)); - return(result); + return result; } -__attribute__(( always_inline )) static inline void __set_PRIMASK(uint32_t priMask) { +__attribute__((always_inline)) static inline void __set_PRIMASK(uint32_t priMask) { __asm volatile ("MSR primask, %0" : : "r" (priMask) : "memory"); } -__attribute__(( always_inline )) static inline void enable_irq(mp_uint_t state) { +__attribute__((always_inline)) static inline void enable_irq(mp_uint_t state) { __set_PRIMASK(state); } -__attribute__(( always_inline )) static inline mp_uint_t disable_irq(void) { +__attribute__((always_inline)) static inline mp_uint_t disable_irq(void) { mp_uint_t state = __get_PRIMASK(); __disable_irq(); return state; diff --git a/ports/teensy/pin_defs_teensy.c b/ports/teensy/pin_defs_teensy.c index e7af1e9697..9041a379e1 100644 --- a/ports/teensy/pin_defs_teensy.c +++ b/ports/teensy/pin_defs_teensy.c @@ -43,7 +43,7 @@ uint32_t pin_get_pull(const pin_obj_t *pin) { // Analog only pin return GPIO_NOPULL; } - volatile uint32_t *port_pcr = GPIO_PIN_TO_PORT_PCR(pin->gpio, pin->pin); + volatile uint32_t *port_pcr = GPIO_PIN_TO_PORT_PCR(pin->gpio, pin->pin); uint32_t pcr = *port_pcr; uint32_t af = (pcr & PORT_PCR_MUX_MASK) >> 8; diff --git a/ports/teensy/pin_defs_teensy.h b/ports/teensy/pin_defs_teensy.h index d3a700be21..fa248483e9 100644 --- a/ports/teensy/pin_defs_teensy.h +++ b/ports/teensy/pin_defs_teensy.h @@ -1,10 +1,10 @@ enum { - PORT_A, - PORT_B, - PORT_C, - PORT_D, - PORT_E, - PORT_Z, + PORT_A, + PORT_B, + PORT_C, + PORT_D, + PORT_E, + PORT_Z, }; enum { diff --git a/ports/teensy/reg.c b/ports/teensy/reg.c index cbc427d876..9bad1918e5 100644 --- a/ports/teensy/reg.c +++ b/ports/teensy/reg.c @@ -11,7 +11,7 @@ mp_obj_t reg_cmd(void *base, reg_t *reg, mp_uint_t num_regs, uint n_args, const for (mp_uint_t reg_idx = 0; reg_idx < num_regs; reg_idx++, reg++) { printf(" %-8s @0x%08x = 0x%08lx\n", - reg->name, (mp_uint_t)base + reg->offset, *(uint32_t *)((uint8_t *)base + reg->offset)); + reg->name, (mp_uint_t)base + reg->offset, *(uint32_t *)((uint8_t *)base + reg->offset)); } return mp_const_none; } diff --git a/ports/teensy/reg.h b/ports/teensy/reg.h index 0da6378ee7..8202b537b1 100644 --- a/ports/teensy/reg.h +++ b/ports/teensy/reg.h @@ -3,7 +3,7 @@ typedef struct { const char *name; - mp_uint_t offset; + mp_uint_t offset; } reg_t; #define REG_ENTRY(st, name) { #name, offsetof(st, name) } diff --git a/ports/teensy/servo.c b/ports/teensy/servo.c index 262daaeb66..099a73a40a 100644 --- a/ports/teensy/servo.c +++ b/ports/teensy/servo.c @@ -17,7 +17,7 @@ #define REFRESH_INTERVAL 20000 // minumim time to refresh servos in microseconds #define PDB_CONFIG (PDB_SC_TRGSEL(15) | PDB_SC_PDBEN | PDB_SC_PDBIE \ - | PDB_SC_CONT | PDB_SC_PRESCALER(2) | PDB_SC_MULT(0)) + | PDB_SC_CONT | PDB_SC_PRESCALER(2) | PDB_SC_MULT(0)) #define PDB_PRESCALE 4 #define usToTicks(us) ((us) * (F_BUS / 1000) / PDB_PRESCALE / 1000) #define ticksToUs(ticks) ((ticks) * PDB_PRESCALE * 1000 / (F_BUS / 1000)) @@ -36,14 +36,12 @@ typedef struct _pyb_servo_obj_t { #define clamp(v, min_val, max_val) ((v) < (min_val) ? (min_val) : (v) > (max_val) ? (max_val) : (v)) -static float map_uint_to_float(uint x, uint in_min, uint in_max, float out_min, float out_max) -{ - return (float)(x - in_min) * (out_max - out_min) / (float)(in_max - in_min) + (float)out_min; +static float map_uint_to_float(uint x, uint in_min, uint in_max, float out_min, float out_max) { + return (float)(x - in_min) * (out_max - out_min) / (float)(in_max - in_min) + (float)out_min; } -static uint map_float_to_uint(float x, float in_min, float in_max, uint out_min, uint out_max) -{ - return (int)((x - in_min) * (float)(out_max - out_min) / (in_max - in_min) + (float)out_min); +static uint map_float_to_uint(float x, float in_min, float in_max, uint out_min, uint out_max) { + return (int)((x - in_min) * (float)(out_max - out_min) / (in_max - in_min) + (float)out_min); } static mp_obj_t servo_obj_attach(mp_obj_t self_in, mp_obj_t pin_obj) { @@ -74,7 +72,7 @@ pin_error: } static mp_obj_t servo_obj_detach(mp_obj_t self_in) { - //pyb_servo_obj_t *self = self_in; + // pyb_servo_obj_t *self = self_in; return mp_const_none; } @@ -110,9 +108,9 @@ static mp_obj_t servo_obj_angle(int n_args, const mp_obj_t *args) { if (n_args == 1) { // get float angle = map_uint_to_float(servo_ticks[self->servo_id], - usToTicks(self->min_usecs), - usToTicks(self->max_usecs), - 0.0, 180.0); + usToTicks(self->min_usecs), + usToTicks(self->max_usecs), + 0.0, 180.0); return mp_obj_new_float(angle); } // Set @@ -124,9 +122,9 @@ static mp_obj_t servo_obj_angle(int n_args, const mp_obj_t *args) { angle = 180.0F; } servo_ticks[self->servo_id] = map_float_to_uint(angle, - 0.0F, 180.0F, - usToTicks(self->min_usecs), - usToTicks(self->max_usecs)); + 0.0F, 180.0F, + usToTicks(self->min_usecs), + usToTicks(self->max_usecs)); return mp_const_none; } @@ -207,7 +205,7 @@ mp_obj_t pyb_Servo(void) { /* Find an unallocated servo id */ self->servo_id = 0; - for (mask=1; mask < (1< 60000) wait_ticks = 60000; - tick_accum += wait_ticks; - PDB0_IDLY += wait_ticks; - PDB0_SC = PDB_CONFIG | PDB_SC_LDOK; - // if this wait is enough to satisfy the refresh - // interval, next time begin again at channel zero - if (tick_accum >= usToTicks(REFRESH_INTERVAL)) { - tick_accum = 0; - channel = 0; - } + // first, if any channel was left high from the previous + // run, now is the time to shut it off + if (servo_active_mask & (1 << channel_high)) { + digitalWrite(servo_pin[channel_high], LOW); + channel_high = MAX_SERVOS; + } + // search for the next channel to turn on + while (channel < MAX_SERVOS) { + if (servo_active_mask & (1 << channel)) { + digitalWrite(servo_pin[channel], HIGH); + channel_high = channel; + ticks = servo_ticks[channel]; + tick_accum += ticks; + PDB0_IDLY += ticks; + PDB0_SC = PDB_CONFIG | PDB_SC_LDOK; + channel++; + return; + } + channel++; + } + // when all channels have output, wait for the + // minimum refresh interval + wait_ticks = usToTicks(REFRESH_INTERVAL) - tick_accum; + if (wait_ticks < usToTicks(100)) { + wait_ticks = usToTicks(100); + } else if (wait_ticks > 60000) { + wait_ticks = 60000; + } + tick_accum += wait_ticks; + PDB0_IDLY += wait_ticks; + PDB0_SC = PDB_CONFIG | PDB_SC_LDOK; + // if this wait is enough to satisfy the refresh + // interval, next time begin again at channel zero + if (tick_accum >= usToTicks(REFRESH_INTERVAL)) { + tick_accum = 0; + channel = 0; + } } diff --git a/ports/teensy/teensy_hal.c b/ports/teensy/teensy_hal.c index 7ce82f1d2a..ec324d0dea 100644 --- a/ports/teensy/teensy_hal.c +++ b/ports/teensy/teensy_hal.c @@ -8,17 +8,17 @@ #include "Arduino.h" mp_uint_t mp_hal_ticks_ms(void) { - return millis(); + return millis(); } void mp_hal_delay_ms(mp_uint_t ms) { - delay(ms); + delay(ms); } void mp_hal_set_interrupt_char(int c) { - // The teensy 3.1 usb stack doesn't currently have the notion of generating - // an exception when a certain character is received. That just means that - // you can't press Control-C and get your python script to stop. + // The teensy 3.1 usb stack doesn't currently have the notion of generating + // an exception when a certain character is received. That just means that + // you can't press Control-C and get your python script to stop. } int mp_hal_stdin_rx_chr(void) { diff --git a/ports/teensy/teensy_hal.h b/ports/teensy/teensy_hal.h index aef38a2ad9..3c9b1ddbc7 100644 --- a/ports/teensy/teensy_hal.h +++ b/ports/teensy/teensy_hal.h @@ -3,7 +3,7 @@ #ifdef USE_FULL_ASSERT #define assert_param(expr) ((expr) ? (void)0 : assert_failed((uint8_t *)__FILE__, __LINE__)) - void assert_failed(uint8_t* file, uint32_t line); +void assert_failed(uint8_t *file, uint32_t line); #else #define assert_param(expr) ((void)0) #endif /* USE_FULL_ASSERT */ @@ -41,12 +41,12 @@ typedef struct { } SPI_TypeDef; typedef struct { - volatile uint32_t PDOR; // Output register - volatile uint32_t PSOR; // Set output register - volatile uint32_t PCOR; // Clear output register - volatile uint32_t PTOR; // Toggle output register - volatile uint32_t PDIR; // Data Input register - volatile uint32_t PDDR; // Data Direction register + volatile uint32_t PDOR; // Output register + volatile uint32_t PSOR; // Set output register + volatile uint32_t PCOR; // Clear output register + volatile uint32_t PTOR; // Toggle output register + volatile uint32_t PDIR; // Data Input register + volatile uint32_t PDDR; // Data Direction register } GPIO_TypeDef; #define GPIO_OUTPUT_TYPE ((uint32_t)0x00000010) // Indicates OD @@ -60,19 +60,19 @@ typedef struct { #define GPIO_MODE_IT_RISING ((uint32_t)1) #define GPIO_MODE_IT_FALLING ((uint32_t)2) -#define IS_GPIO_MODE(MODE) (((MODE) == GPIO_MODE_INPUT) ||\ - ((MODE) == GPIO_MODE_OUTPUT_PP) ||\ - ((MODE) == GPIO_MODE_OUTPUT_OD) ||\ - ((MODE) == GPIO_MODE_AF_PP) ||\ - ((MODE) == GPIO_MODE_AF_OD) ||\ - ((MODE) == GPIO_MODE_ANALOG)) +#define IS_GPIO_MODE(MODE) (((MODE) == GPIO_MODE_INPUT) || \ + ((MODE) == GPIO_MODE_OUTPUT_PP) || \ + ((MODE) == GPIO_MODE_OUTPUT_OD) || \ + ((MODE) == GPIO_MODE_AF_PP) || \ + ((MODE) == GPIO_MODE_AF_OD) || \ + ((MODE) == GPIO_MODE_ANALOG)) #define GPIO_NOPULL ((uint32_t)0) #define GPIO_PULLUP ((uint32_t)1) #define GPIO_PULLDOWN ((uint32_t)2) #define IS_GPIO_PULL(PULL) (((PULL) == GPIO_NOPULL) || ((PULL) == GPIO_PULLUP) || \ - ((PULL) == GPIO_PULLDOWN)) + ((PULL) == GPIO_PULLDOWN)) #define GPIO_SPEED_FREQ_LOW ((uint32_t)0) #define GPIO_SPEED_FREQ_MEDIUM ((uint32_t)1) @@ -82,11 +82,11 @@ typedef struct { #define IS_GPIO_AF(af) ((af) >= 0 && (af) <= 7) typedef struct { - uint32_t Pin; - uint32_t Mode; - uint32_t Pull; - uint32_t Speed; - uint32_t Alternate; + uint32_t Pin; + uint32_t Mode; + uint32_t Pull; + uint32_t Speed; + uint32_t Alternate; } GPIO_InitTypeDef; #define GPIO_PORT_TO_PORT_NUM(GPIOx) \ @@ -110,8 +110,8 @@ typedef struct { #define GPIO_AF6_I2C1 6 #define GPIO_AF7_FTM1 7 -__attribute__(( always_inline )) static inline void __WFI(void) { - __asm volatile ("wfi"); +__attribute__((always_inline)) static inline void __WFI(void) { + __asm volatile ("wfi"); } void mp_hal_set_interrupt_char(int c); @@ -121,7 +121,7 @@ void mp_hal_gpio_clock_enable(GPIO_TypeDef *gpio); void HAL_GPIO_Init(GPIO_TypeDef *GPIOx, GPIO_InitTypeDef *init); struct _pin_obj_t; -#define mp_hal_pin_obj_t const struct _pin_obj_t* +#define mp_hal_pin_obj_t const struct _pin_obj_t * #define mp_hal_pin_high(p) (((p)->gpio->PSOR) = (p)->pin_mask) #define mp_hal_pin_low(p) (((p)->gpio->PCOR) = (p)->pin_mask) #define mp_hal_pin_read(p) (((p)->gpio->PDIR >> (p)->pin) & 1) diff --git a/ports/teensy/timer.c b/ports/teensy/timer.c index b823e6c3b9..a26c1d5851 100644 --- a/ports/teensy/timer.c +++ b/ports/teensy/timer.c @@ -49,8 +49,8 @@ typedef enum { } pyb_channel_mode; STATIC const struct { - qstr name; - uint32_t oc_mode; + qstr name; + uint32_t oc_mode; } channel_mode_info[] = { { MP_QSTR_PWM, FTM_OCMODE_PWM1 }, { MP_QSTR_PWM_INVERTED, FTM_OCMODE_PWM2 }, @@ -195,8 +195,8 @@ STATIC void pyb_timer_print(const mp_print_t *print, mp_obj_t self_in, mp_print_ mp_printf(print, "Timer(%u, prescaler=%u, period=%u, mode=%s)", self->tim_id, 1 << (self->ftm.Instance->SC & 7), - self->ftm.Instance->MOD & 0xffff, - self->ftm.Init.CounterMode == FTM_COUNTERMODE_UP ? "UP" : "CENTER"); + self->ftm.Instance->MOD & 0xffff, + self->ftm.Init.CounterMode == FTM_COUNTERMODE_UP ? "UP" : "CENTER"); } } @@ -319,10 +319,20 @@ STATIC mp_obj_t pyb_timer_make_new(const mp_obj_type_t *type, size_t n_args, siz tim->tim_id = mp_obj_get_int(args[0]); switch (tim->tim_id) { - case 0: tim->ftm.Instance = FTM0; tim->irqn = IRQ_FTM0; break; - case 1: tim->ftm.Instance = FTM1; tim->irqn = IRQ_FTM1; break; - case 2: tim->ftm.Instance = FTM2; tim->irqn = IRQ_FTM2; break; - default: nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Timer %d does not exist", tim->tim_id)); + case 0: + tim->ftm.Instance = FTM0; + tim->irqn = IRQ_FTM0; + break; + case 1: + tim->ftm.Instance = FTM1; + tim->irqn = IRQ_FTM1; + break; + case 2: + tim->ftm.Instance = FTM2; + tim->irqn = IRQ_FTM2; + break; + default: + nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Timer %d does not exist", tim->tim_id)); } if (n_args > 1 || n_kw > 0) { @@ -551,9 +561,9 @@ STATIC mp_obj_t pyb_timer_channel(size_t n_args, const mp_obj_t *args, mp_map_t case CHANNEL_MODE_OC_INACTIVE: case CHANNEL_MODE_OC_TOGGLE: { FTM_OC_InitTypeDef oc_config; - oc_config.OCMode = channel_mode_info[chan->mode].oc_mode; - oc_config.Pulse = vals[4].u_int; - oc_config.OCPolarity = vals[5].u_int; + oc_config.OCMode = channel_mode_info[chan->mode].oc_mode; + oc_config.Pulse = vals[4].u_int; + oc_config.OCPolarity = vals[5].u_int; if (oc_config.OCPolarity == 0xffffffff) { oc_config.OCPolarity = FTM_OCPOLARITY_HIGH; } @@ -573,7 +583,7 @@ STATIC mp_obj_t pyb_timer_channel(size_t n_args, const mp_obj_t *args, mp_map_t case CHANNEL_MODE_IC: { FTM_IC_InitTypeDef ic_config; - ic_config.ICPolarity = vals[5].u_int; + ic_config.ICPolarity = vals[5].u_int; if (ic_config.ICPolarity == 0xffffffff) { ic_config.ICPolarity = FTM_ICPOLARITY_RISING; } @@ -716,9 +726,9 @@ STATIC const mp_rom_map_elem_t pyb_timer_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_prescaler), MP_ROM_PTR(&pyb_timer_prescaler_obj) }, { MP_ROM_QSTR(MP_QSTR_period), MP_ROM_PTR(&pyb_timer_period_obj) }, { MP_ROM_QSTR(MP_QSTR_callback), MP_ROM_PTR(&pyb_timer_callback_obj) }, -#if MICROPY_TIMER_REG + #if MICROPY_TIMER_REG { MP_ROM_QSTR(MP_QSTR_reg), MP_ROM_PTR(&pyb_timer_reg_obj) }, -#endif + #endif { MP_ROM_QSTR(MP_QSTR_UP), MP_ROM_INT(FTM_COUNTERMODE_UP) }, { MP_ROM_QSTR(MP_QSTR_CENTER), MP_ROM_INT(FTM_COUNTERMODE_CENTER) }, { MP_ROM_QSTR(MP_QSTR_PWM), MP_ROM_INT(CHANNEL_MODE_PWM_NORMAL) }, @@ -754,9 +764,9 @@ STATIC void pyb_timer_channel_print(const mp_print_t *print, mp_obj_t self_in, m pyb_timer_channel_obj_t *self = self_in; mp_printf(print, "TimerChannel(timer=%u, channel=%u, mode=%s)", - self->timer->tim_id, - self->channel, - qstr_str(channel_mode_info[self->mode].name)); + self->timer->tim_id, + self->channel, + qstr_str(channel_mode_info[self->mode].name)); } /// \method capture([value]) @@ -773,7 +783,7 @@ STATIC void pyb_timer_channel_print(const mp_print_t *print, mp_obj_t self_in, m /// Get or set the pulse width value associated with a channel. /// capture, compare, and pulse_width are all aliases for the same function. /// pulse_width is the logical name to use when the channel is in PWM mode. -/// +/// /// In edge aligned mode, a pulse_width of `period + 1` corresponds to a duty cycle of 100% /// In center aligned mode, a pulse width of `period` corresponds to a duty cycle of 100% STATIC mp_obj_t pyb_timer_channel_capture_compare(size_t n_args, const mp_obj_t *args) { @@ -860,8 +870,8 @@ reg_t timer_channel_reg[] = { mp_obj_t pyb_timer_channel_reg(uint n_args, const mp_obj_t *args) { pyb_timer_channel_obj_t *self = args[0]; return reg_cmd(&self->timer->ftm.Instance->channel[self->channel], - timer_channel_reg, MP_ARRAY_SIZE(timer_channel_reg), - n_args - 1, args + 1); + timer_channel_reg, MP_ARRAY_SIZE(timer_channel_reg), + n_args - 1, args + 1); } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_timer_channel_reg_obj, 1, 3, pyb_timer_channel_reg); #endif @@ -873,9 +883,9 @@ STATIC const mp_rom_map_elem_t pyb_timer_channel_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_pulse_width_percent), MP_ROM_PTR(&pyb_timer_channel_pulse_width_percent_obj) }, { MP_ROM_QSTR(MP_QSTR_capture), MP_ROM_PTR(&pyb_timer_channel_capture_compare_obj) }, { MP_ROM_QSTR(MP_QSTR_compare), MP_ROM_PTR(&pyb_timer_channel_capture_compare_obj) }, -#if MICROPY_TIMER_REG + #if MICROPY_TIMER_REG { MP_ROM_QSTR(MP_QSTR_reg), MP_ROM_PTR(&pyb_timer_channel_reg_obj) }, -#endif + #endif }; STATIC MP_DEFINE_CONST_DICT(pyb_timer_channel_locals_dict, pyb_timer_channel_locals_dict_table); @@ -906,10 +916,10 @@ STATIC bool ftm_handle_irq_callback(pyb_timer_obj_t *self, mp_uint_t channel, mp self->callback = mp_const_none; if (channel == 0xffffffff) { printf("Uncaught exception in Timer(" UINT_FMT - ") interrupt handler\n", self->tim_id); + ") interrupt handler\n", self->tim_id); } else { printf("Uncaught exception in Timer(" UINT_FMT ") channel " - UINT_FMT " interrupt handler\n", self->tim_id, channel); + UINT_FMT " interrupt handler\n", self->tim_id, channel); } mp_obj_print_exception(&mp_plat_print, (mp_obj_t)nlr.ret_val); } @@ -956,7 +966,7 @@ STATIC void ftm_irq_handler(uint tim_id) { } else { __HAL_FTM_DISABLE_CH_IT(&self->ftm, chan->channel); printf("No callback for Timer %d channel %u (now disabled)\n", - self->tim_id, chan->channel); + self->tim_id, chan->channel); } } chan = chan->next; @@ -971,7 +981,7 @@ STATIC void ftm_irq_handler(uint tim_id) { __HAL_FTM_CLEAR_CH_FLAG(&self->ftm, channel); __HAL_FTM_DISABLE_CH_IT(&self->ftm, channel); printf("Unhandled interrupt Timer %d channel %u (now disabled)\n", - tim_id, channel); + tim_id, channel); } } } diff --git a/ports/teensy/uart.c b/ports/teensy/uart.c index a8cfd63eac..f780cb0ccc 100644 --- a/ports/teensy/uart.c +++ b/ports/teensy/uart.c @@ -62,12 +62,12 @@ pyb_uart_obj_t *pyb_uart_global_debug = NULL; // assumes Init parameters have been set up correctly bool uart_init2(pyb_uart_obj_t *uart_obj) { -#if 0 + #if 0 USART_TypeDef *UARTx = NULL; uint32_t GPIO_Pin = 0; - uint8_t GPIO_AF_UARTx = 0; - GPIO_TypeDef* GPIO_Port = NULL; + uint8_t GPIO_AF_UARTx = 0; + GPIO_TypeDef *GPIO_Port = NULL; switch (uart_obj->uart_id) { // USART1 is on PA9/PA10 (CK on PA8), PB6/PB7 @@ -75,13 +75,13 @@ bool uart_init2(pyb_uart_obj_t *uart_obj) { UARTx = USART1; GPIO_AF_UARTx = GPIO_AF7_USART1; -#if defined (PYBV4) || defined(PYBV10) + #if defined(PYBV4) || defined(PYBV10) GPIO_Port = GPIOB; GPIO_Pin = GPIO_PIN_6 | GPIO_PIN_7; -#else + #else GPIO_Port = GPIOA; GPIO_Pin = GPIO_PIN_9 | GPIO_PIN_10; -#endif + #endif __USART1_CLK_ENABLE(); break; @@ -102,13 +102,13 @@ bool uart_init2(pyb_uart_obj_t *uart_obj) { UARTx = USART3; GPIO_AF_UARTx = GPIO_AF7_USART3; -#if defined(PYBV3) || defined(PYBV4) | defined(PYBV10) + #if defined(PYBV3) || defined(PYBV4) | defined(PYBV10) GPIO_Port = GPIOB; GPIO_Pin = GPIO_PIN_10 | GPIO_PIN_11; -#else + #else GPIO_Port = GPIOD; GPIO_Pin = GPIO_PIN_8 | GPIO_PIN_9; -#endif + #endif __USART3_CLK_ENABLE(); break; @@ -152,12 +152,12 @@ bool uart_init2(pyb_uart_obj_t *uart_obj) { HAL_UART_Init(&uart_obj->uart); uart_obj->is_enabled = true; -#endif + #endif return true; } bool uart_init(pyb_uart_obj_t *uart_obj, uint32_t baudrate) { -#if 0 + #if 0 UART_HandleTypeDef *uh = &uart_obj->uart; memset(uh, 0, sizeof(*uh)); uh->Init.BaudRate = baudrate; @@ -167,47 +167,47 @@ bool uart_init(pyb_uart_obj_t *uart_obj, uint32_t baudrate) { uh->Init.Mode = UART_MODE_TX_RX; uh->Init.HwFlowCtl = UART_HWCONTROL_NONE; uh->Init.OverSampling = UART_OVERSAMPLING_16; -#endif + #endif return uart_init2(uart_obj); } mp_uint_t uart_rx_any(pyb_uart_obj_t *uart_obj) { -#if 0 + #if 0 return __HAL_UART_GET_FLAG(&uart_obj->uart, UART_FLAG_RXNE); -#else + #else return 0; -#endif + #endif } int uart_rx_char(pyb_uart_obj_t *uart_obj) { uint8_t ch; -#if 0 + #if 0 if (HAL_UART_Receive(&uart_obj->uart, &ch, 1, 0) != HAL_OK) { ch = 0; } -#else + #else ch = 'A'; -#endif + #endif return ch; } void uart_tx_char(pyb_uart_obj_t *uart_obj, int c) { -#if 0 + #if 0 uint8_t ch = c; HAL_UART_Transmit(&uart_obj->uart, &ch, 1, 100000); -#endif + #endif } void uart_tx_str(pyb_uart_obj_t *uart_obj, const char *str) { -#if 0 - HAL_UART_Transmit(&uart_obj->uart, (uint8_t*)str, strlen(str), 100000); -#endif + #if 0 + HAL_UART_Transmit(&uart_obj->uart, (uint8_t *)str, strlen(str), 100000); + #endif } void uart_tx_strn(pyb_uart_obj_t *uart_obj, const char *str, uint len) { -#if 0 - HAL_UART_Transmit(&uart_obj->uart, (uint8_t*)str, len, 100000); -#endif + #if 0 + HAL_UART_Transmit(&uart_obj->uart, (uint8_t *)str, len, 100000); + #endif } void uart_tx_strn_cooked(pyb_uart_obj_t *uart_obj, const char *str, uint len) { @@ -227,7 +227,7 @@ STATIC void pyb_uart_print(const mp_print_t *print, mp_obj_t self_in, mp_print_k if (!self->is_enabled) { mp_printf(print, "UART(%lu)", self->uart_id); } else { -#if 0 + #if 0 mp_printf(print, "UART(%lu, baudrate=%u, bits=%u, stop=%u", self->uart_id, self->uart.Init.BaudRate, self->uart.Init.WordLength == UART_WORDLENGTH_8B ? 8 : 9, @@ -237,7 +237,7 @@ STATIC void pyb_uart_print(const mp_print_t *print, mp_obj_t self_in, mp_print_k } else { mp_printf(print, ", parity=%u)", self->uart.Init.Parity == UART_PARITY_EVEN ? 0 : 1); } -#endif + #endif } } @@ -261,15 +261,19 @@ STATIC mp_obj_t pyb_uart_init_helper(pyb_uart_obj_t *self, uint n_args, const mp // parse args mp_arg_val_t vals[PYB_UART_INIT_NUM_ARGS]; mp_arg_parse_all(n_args, args, kw_args, PYB_UART_INIT_NUM_ARGS, pyb_uart_init_args, vals); -#if 0 + #if 0 // set the UART configuration values memset(&self->uart, 0, sizeof(self->uart)); UART_InitTypeDef *init = &self->uart.Init; init->BaudRate = vals[0].u_int; init->WordLength = vals[1].u_int == 8 ? UART_WORDLENGTH_8B : UART_WORDLENGTH_9B; switch (vals[2].u_int) { - case 1: init->StopBits = UART_STOPBITS_1; break; - default: init->StopBits = UART_STOPBITS_2; break; + case 1: + init->StopBits = UART_STOPBITS_1; + break; + default: + init->StopBits = UART_STOPBITS_2; + break; } if (vals[3].u_obj == mp_const_none) { init->Parity = UART_PARITY_NONE; @@ -285,7 +289,7 @@ STATIC mp_obj_t pyb_uart_init_helper(pyb_uart_obj_t *self, uint n_args, const mp if (!uart_init2(self)) { nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "UART port %d does not exist", self->uart_id)); } -#endif + #endif return mp_const_none; } @@ -315,11 +319,11 @@ STATIC mp_obj_t pyb_uart_make_new(const mp_obj_type_t *type, uint n_args, uint n // work out port o->uart_id = 0; -#if 0 + #if 0 if (MP_OBJ_IS_STR(args[0])) { const char *port = mp_obj_str_get_str(args[0]); if (0) { -#if defined(PYBV10) + #if defined(PYBV10) } else if (strcmp(port, "XA") == 0) { o->uart_id = PYB_UART_XA; } else if (strcmp(port, "XB") == 0) { @@ -328,14 +332,14 @@ STATIC mp_obj_t pyb_uart_make_new(const mp_obj_type_t *type, uint n_args, uint n o->uart_id = PYB_UART_YA; } else if (strcmp(port, "YB") == 0) { o->uart_id = PYB_UART_YB; -#endif + #endif } else { nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "UART port %s does not exist", port)); } } else { o->uart_id = mp_obj_get_int(args[0]); } -#endif + #endif if (n_args > 1 || n_kw > 0) { // start the peripheral @@ -355,7 +359,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_uart_init_obj, 1, pyb_uart_init); /// \method deinit() /// Turn off the UART bus. STATIC mp_obj_t pyb_uart_deinit(mp_obj_t self_in) { - //pyb_uart_obj_t *self = self_in; + // pyb_uart_obj_t *self = self_in; // TODO return mp_const_none; } @@ -395,7 +399,7 @@ STATIC mp_obj_t pyb_uart_send(uint n_args, const mp_obj_t *args, mp_map_t *kw_ar mp_arg_val_t vals[PYB_UART_SEND_NUM_ARGS]; mp_arg_parse_all(n_args - 1, args + 1, kw_args, PYB_UART_SEND_NUM_ARGS, pyb_uart_send_args, vals); -#if 0 + #if 0 // get the buffer to send from mp_buffer_info_t bufinfo; uint8_t data[1]; @@ -408,9 +412,9 @@ STATIC mp_obj_t pyb_uart_send(uint n_args, const mp_obj_t *args, mp_map_t *kw_ar // TODO really need a HardwareError object, or something nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_Exception, "HAL_UART_Transmit failed with code %d", status)); } -#else + #else (void)self; -#endif + #endif return mp_const_none; } @@ -439,7 +443,7 @@ STATIC mp_obj_t pyb_uart_recv(uint n_args, const mp_obj_t *args, mp_map_t *kw_ar pyb_uart_obj_t *self = args[0]; -#if 0 + #if 0 // parse args mp_arg_val_t vals[PYB_UART_RECV_NUM_ARGS]; mp_arg_parse_all(n_args - 1, args + 1, kw_args, PYB_UART_RECV_NUM_ARGS, pyb_uart_recv_args, vals); @@ -462,10 +466,10 @@ STATIC mp_obj_t pyb_uart_recv(uint n_args, const mp_obj_t *args, mp_map_t *kw_ar } else { return mp_obj_str_builder_end(o_ret); } -#else + #else (void)self; return mp_const_none; -#endif + #endif } STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_uart_recv_obj, 1, pyb_uart_recv); diff --git a/ports/teensy/usb.c b/ports/teensy/usb.c index ed96826b35..a906f91288 100644 --- a/ports/teensy/usb.c +++ b/ports/teensy/usb.c @@ -7,46 +7,40 @@ #include "usb.h" #include "usb_serial.h" -bool usb_vcp_is_connected(void) -{ - return usb_configuration && (usb_cdc_line_rtsdtr & (USB_SERIAL_DTR | USB_SERIAL_RTS)); +bool usb_vcp_is_connected(void) { + return usb_configuration && (usb_cdc_line_rtsdtr & (USB_SERIAL_DTR | USB_SERIAL_RTS)); } -bool usb_vcp_is_enabled(void) -{ - return true; +bool usb_vcp_is_enabled(void) { + return true; } int usb_vcp_rx_num(void) { - return usb_serial_available(); + return usb_serial_available(); } -int usb_vcp_recv_byte(uint8_t *ptr) -{ - int ch = usb_serial_getchar(); - if (ch < 0) { - return 0; - } - *ptr = ch; - return 1; -} - -void usb_vcp_send_str(const char* str) -{ - usb_vcp_send_strn(str, strlen(str)); -} - -void usb_vcp_send_strn(const char* str, int len) -{ - usb_serial_write(str, len); -} - -void usb_vcp_send_strn_cooked(const char *str, int len) -{ - for (const char *top = str + len; str < top; str++) { - if (*str == '\n') { - usb_serial_putchar('\r'); +int usb_vcp_recv_byte(uint8_t *ptr) { + int ch = usb_serial_getchar(); + if (ch < 0) { + return 0; + } + *ptr = ch; + return 1; +} + +void usb_vcp_send_str(const char *str) { + usb_vcp_send_strn(str, strlen(str)); +} + +void usb_vcp_send_strn(const char *str, int len) { + usb_serial_write(str, len); +} + +void usb_vcp_send_strn_cooked(const char *str, int len) { + for (const char *top = str + len; str < top; str++) { + if (*str == '\n') { + usb_serial_putchar('\r'); + } + usb_serial_putchar(*str); } - usb_serial_putchar(*str); - } } diff --git a/ports/teensy/usb.h b/ports/teensy/usb.h index 50fb3ff90d..7ca0eacb9b 100644 --- a/ports/teensy/usb.h +++ b/ports/teensy/usb.h @@ -5,8 +5,8 @@ bool usb_vcp_is_connected(void); bool usb_vcp_is_enabled(void); int usb_vcp_rx_num(void); int usb_vcp_recv_byte(uint8_t *ptr); -void usb_vcp_send_str(const char* str); -void usb_vcp_send_strn(const char* str, int len); +void usb_vcp_send_str(const char *str); +void usb_vcp_send_strn(const char *str, int len); void usb_vcp_send_strn_cooked(const char *str, int len); #endif // MICROPY_INCLUDED_TEENSY_USB_H diff --git a/ports/unix/alloc.c b/ports/unix/alloc.c index ca12d025b6..7fe7b4dba4 100644 --- a/ports/unix/alloc.c +++ b/ports/unix/alloc.c @@ -69,7 +69,7 @@ void mp_unix_free_exec(void *ptr, size_t size) { munmap(ptr, size); // unlink the mmap'd region from the list - for (mmap_region_t **rg = (mmap_region_t**)&MP_STATE_VM(mmap_region_head); *rg != NULL; *rg = (*rg)->next) { + for (mmap_region_t **rg = (mmap_region_t **)&MP_STATE_VM(mmap_region_head); *rg != NULL; *rg = (*rg)->next) { if ((*rg)->ptr == ptr) { mmap_region_t *next = (*rg)->next; m_del_obj(mmap_region_t, *rg); diff --git a/ports/unix/coverage.c b/ports/unix/coverage.c index 7820f6d736..bd5296e4f5 100644 --- a/ports/unix/coverage.c +++ b/ports/unix/coverage.c @@ -104,7 +104,7 @@ STATIC const mp_stream_p_t fileio_stream_p = { STATIC const mp_obj_type_t mp_type_stest_fileio = { { &mp_type_type }, .protocol = &fileio_stream_p, - .locals_dict = (mp_obj_dict_t*)&rawfile_locals_dict, + .locals_dict = (mp_obj_dict_t *)&rawfile_locals_dict, }; // stream read returns non-blocking error @@ -131,12 +131,12 @@ STATIC const mp_stream_p_t textio_stream_p2 = { STATIC const mp_obj_type_t mp_type_stest_textio2 = { { &mp_type_type }, .protocol = &textio_stream_p2, - .locals_dict = (mp_obj_dict_t*)&rawfile_locals_dict2, + .locals_dict = (mp_obj_dict_t *)&rawfile_locals_dict2, }; // str/bytes objects without a valid hash -STATIC const mp_obj_str_t str_no_hash_obj = {{&mp_type_str}, 0, 10, (const byte*)"0123456789"}; -STATIC const mp_obj_str_t bytes_no_hash_obj = {{&mp_type_bytes}, 0, 10, (const byte*)"0123456789"}; +STATIC const mp_obj_str_t str_no_hash_obj = {{&mp_type_str}, 0, 10, (const byte *)"0123456789"}; +STATIC const mp_obj_str_t bytes_no_hash_obj = {{&mp_type_bytes}, 0, 10, (const byte *)"0123456789"}; // function to run extra tests for things that can't be checked by scripts STATIC mp_obj_t extra_coverage(void) { @@ -378,10 +378,10 @@ STATIC mp_obj_t extra_coverage(void) { // call mp_execute_bytecode with invalide bytecode (should raise NotImplementedError) mp_obj_fun_bc_t fun_bc; - fun_bc.bytecode = (const byte*)"\x01"; // just needed for n_state + fun_bc.bytecode = (const byte *)"\x01"; // just needed for n_state mp_code_state_t *code_state = m_new_obj_var(mp_code_state_t, mp_obj_t, 1); code_state->fun_bc = &fun_bc; - code_state->ip = (const byte*)"\x00"; // just needed for an invalid opcode + code_state->ip = (const byte *)"\x00"; // just needed for an invalid opcode code_state->sp = &code_state->state[0]; code_state->exc_sp = NULL; code_state->old_globals = NULL; diff --git a/ports/unix/file.c b/ports/unix/file.c index a54d1d03df..bcffdd41e7 100644 --- a/ports/unix/file.c +++ b/ports/unix/file.c @@ -103,7 +103,7 @@ STATIC mp_uint_t fdfile_ioctl(mp_obj_t o_in, mp_uint_t request, uintptr_t arg, i check_fd_is_open(o); switch (request) { case MP_STREAM_SEEK: { - struct mp_stream_seek_t *s = (struct mp_stream_seek_t*)arg; + struct mp_stream_seek_t *s = (struct mp_stream_seek_t *)arg; off_t off = lseek(o->fd, s->offset, s->whence); if (off == (off_t)-1) { *errcode = errno; @@ -176,7 +176,7 @@ STATIC mp_obj_t fdfile_open(const mp_obj_type_t *type, mp_arg_val_t *args) { case '+': mode_rw = O_RDWR; break; - #if MICROPY_PY_IO_FILEIO + #if MICROPY_PY_IO_FILEIO // If we don't have io.FileIO, then files are in text mode implicitly case 'b': type = &mp_type_fileio; @@ -184,7 +184,7 @@ STATIC mp_obj_t fdfile_open(const mp_obj_type_t *type, mp_arg_val_t *args) { case 't': type = &mp_type_textio; break; - #endif + #endif } } @@ -244,7 +244,7 @@ const mp_obj_type_t mp_type_fileio = { .getiter = mp_identity_getiter, .iternext = mp_stream_unbuffered_iter, .protocol = &fileio_stream_p, - .locals_dict = (mp_obj_dict_t*)&rawfile_locals_dict, + .locals_dict = (mp_obj_dict_t *)&rawfile_locals_dict, }; #endif @@ -263,7 +263,7 @@ const mp_obj_type_t mp_type_textio = { .getiter = mp_identity_getiter, .iternext = mp_stream_unbuffered_iter, .protocol = &textio_stream_p, - .locals_dict = (mp_obj_dict_t*)&rawfile_locals_dict, + .locals_dict = (mp_obj_dict_t *)&rawfile_locals_dict, }; // Factory function for I/O stream classes @@ -275,7 +275,7 @@ mp_obj_t mp_builtin_open(size_t n_args, const mp_obj_t *args, mp_map_t *kwargs) } MP_DEFINE_CONST_FUN_OBJ_KW(mp_builtin_open_obj, 1, mp_builtin_open); -const mp_obj_fdfile_t mp_sys_stdin_obj = { .base = {&mp_type_textio}, .fd = STDIN_FILENO }; +const mp_obj_fdfile_t mp_sys_stdin_obj = { .base = {&mp_type_textio}, .fd = STDIN_FILENO }; const mp_obj_fdfile_t mp_sys_stdout_obj = { .base = {&mp_type_textio}, .fd = STDOUT_FILENO }; const mp_obj_fdfile_t mp_sys_stderr_obj = { .base = {&mp_type_textio}, .fd = STDERR_FILENO }; diff --git a/ports/unix/gccollect.c b/ports/unix/gccollect.c index 02f6fc91a8..b2386d336a 100644 --- a/ports/unix/gccollect.c +++ b/ports/unix/gccollect.c @@ -49,20 +49,20 @@ STATIC void gc_helper_get_regs(regs_t arr) { register long r13 asm ("r13"); register long r14 asm ("r14"); register long r15 asm ("r15"); -#ifdef __clang__ + #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 + 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; @@ -80,18 +80,18 @@ STATIC void gc_helper_get_regs(regs_t arr) { register long esi asm ("esi"); register long edi asm ("edi"); register long ebp asm ("ebp"); -#ifdef __clang__ + #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 + asm ("" : "=r" (ebx)); + asm ("" : "=r" (esi)); + asm ("" : "=r" (edi)); + asm ("" : "=r" (ebp)); + #endif arr[0] = ebx; arr[1] = esi; arr[2] = edi; @@ -155,12 +155,12 @@ void gc_collect_regs_and_stack(void) { regs_t regs; gc_helper_get_regs(regs); // GC stack (and regs because we captured them) - void **regs_ptr = (void**)(void*)®s; + void **regs_ptr = (void **)(void *)®s; gc_collect_root(regs_ptr, ((uintptr_t)MP_STATE_THREAD(stack_top) - (uintptr_t)®s) / sizeof(uintptr_t)); } void gc_collect(void) { - //gc_dump_info(); + // gc_dump_info(); gc_collect_start(); gc_collect_regs_and_stack(); @@ -172,8 +172,8 @@ void gc_collect(void) { #endif gc_collect_end(); - //printf("-----\n"); - //gc_dump_info(); + // printf("-----\n"); + // gc_dump_info(); } -#endif //MICROPY_ENABLE_GC +#endif // MICROPY_ENABLE_GC diff --git a/ports/unix/input.c b/ports/unix/input.c index 7d60b46cc7..a33c020cec 100644 --- a/ports/unix/input.c +++ b/ports/unix/input.c @@ -59,7 +59,7 @@ char *prompt(char *p) { #endif void prompt_read_history(void) { -#if MICROPY_USE_READLINE_HISTORY + #if MICROPY_USE_READLINE_HISTORY #if MICROPY_USE_READLINE == 1 readline_init0(); // will clear history pointers char *home = getenv("HOME"); @@ -91,11 +91,11 @@ void prompt_read_history(void) { vstr_clear(&vstr); } #endif -#endif + #endif } void prompt_write_history(void) { -#if MICROPY_USE_READLINE_HISTORY + #if MICROPY_USE_READLINE_HISTORY #if MICROPY_USE_READLINE == 1 char *home = getenv("HOME"); if (home != NULL) { @@ -117,5 +117,5 @@ void prompt_write_history(void) { } } #endif -#endif + #endif } diff --git a/ports/unix/main.c b/ports/unix/main.c index 1cf237a2b2..a24891058e 100644 --- a/ports/unix/main.c +++ b/ports/unix/main.c @@ -58,7 +58,7 @@ STATIC uint emit_opt = MP_EMIT_OPT_NONE; #if MICROPY_ENABLE_GC // Heap size of GC heap (if enabled) // Make it larger on a 64 bit machine, because pointers are larger. -long heap_size = 1024*1024 * (sizeof(mp_uint_t) / 4); +long heap_size = 1024 * 1024 * (sizeof(mp_uint_t) / 4); #endif STATIC void stderr_print_strn(void *env, const char *str, size_t len) { @@ -113,7 +113,7 @@ STATIC int execute_from_lexer(int source_kind, const void *source, mp_parse_inpu const vstr_t *vstr = source; lex = mp_lexer_new_from_str_len(MP_QSTR__lt_stdin_gt_, vstr->buf, vstr->len, false); } else if (source_kind == LEX_SRC_FILENAME) { - lex = mp_lexer_new_from_file((const char*)source); + lex = mp_lexer_new_from_file((const char *)source); } else { // LEX_SRC_STDIN lex = mp_lexer_new_from_fd(MP_QSTR__lt_stdin_gt_, 0, false); } @@ -302,25 +302,25 @@ STATIC int do_str(const char *str) { STATIC int usage(char **argv) { printf( -"usage: %s [] [-X ] [-c ] []\n" -"Options:\n" -"-v : verbose (trace various operations); can be multiple\n" -"-O[N] : apply bytecode optimizations of level N\n" -"\n" -"Implementation specific options (-X):\n", argv[0] -); + "usage: %s [] [-X ] [-c ] []\n" + "Options:\n" + "-v : verbose (trace various operations); can be multiple\n" + "-O[N] : apply bytecode optimizations of level N\n" + "\n" + "Implementation specific options (-X):\n", argv[0] + ); int impl_opts_cnt = 0; printf( -" compile-only -- parse and compile only\n" -" emit={bytecode,native,viper} -- set the default code emitter\n" -); + " compile-only -- parse and compile only\n" + " emit={bytecode,native,viper} -- set the default code emitter\n" + ); impl_opts_cnt++; -#if MICROPY_ENABLE_GC + #if MICROPY_ENABLE_GC printf( -" heapsize=[w][K|M] -- set the heap size for the GC (default %ld)\n" -, heap_size); + " heapsize=[w][K|M] -- set the heap size for the GC (default %ld)\n" + , heap_size); impl_opts_cnt++; -#endif + #endif if (impl_opts_cnt == 0) { printf(" (none)\n"); @@ -346,7 +346,7 @@ STATIC void pre_process_options(int argc, char **argv) { emit_opt = MP_EMIT_OPT_NATIVE_PYTHON; } else if (strcmp(argv[a + 1], "emit=viper") == 0) { emit_opt = MP_EMIT_OPT_VIPER; -#if MICROPY_ENABLE_GC + #if MICROPY_ENABLE_GC } else if (strncmp(argv[a + 1], "heapsize=", sizeof("heapsize=") - 1) == 0) { char *end; heap_size = strtol(argv[a + 1] + sizeof("heapsize=") - 1, &end, 0); @@ -379,9 +379,9 @@ STATIC void pre_process_options(int argc, char **argv) { if (heap_size < 700) { goto invalid_arg; } -#endif + #endif } else { -invalid_arg: + invalid_arg: printf("Invalid option\n"); exit(usage(argv)); } @@ -437,10 +437,10 @@ MP_NOINLINE int main_(int argc, char **argv) { pre_process_options(argc, argv); -#if MICROPY_ENABLE_GC + #if MICROPY_ENABLE_GC char *heap = malloc(heap_size); gc_init(heap, heap + heap_size); -#endif + #endif #if MICROPY_ENABLE_PYSTACK static mp_obj_t pystack[1024]; @@ -456,7 +456,7 @@ MP_NOINLINE int main_(int argc, char **argv) { mp_type_vfs_posix.make_new(&mp_type_vfs_posix, 0, 0, NULL), MP_OBJ_NEW_QSTR(MP_QSTR__slash_), }; - mp_vfs_mount(2, args, (mp_map_t*)&mp_const_empty_map); + mp_vfs_mount(2, args, (mp_map_t *)&mp_const_empty_map); MP_STATE_VM(vfs_cur) = MP_STATE_VM(vfs_mount_table); } #endif @@ -485,25 +485,25 @@ MP_NOINLINE int main_(int argc, char **argv) { mp_obj_list_get(mp_sys_path, &path_num, &path_items); path_items[0] = MP_OBJ_NEW_QSTR(MP_QSTR_); { - char *p = path; - for (mp_uint_t i = 1; i < path_num; i++) { - char *p1 = strchr(p, PATHLIST_SEP_CHAR); - if (p1 == NULL) { - p1 = p + strlen(p); + char *p = path; + for (mp_uint_t i = 1; i < path_num; i++) { + char *p1 = strchr(p, PATHLIST_SEP_CHAR); + if (p1 == NULL) { + p1 = p + strlen(p); + } + if (p[0] == '~' && p[1] == '/' && home != NULL) { + // Expand standalone ~ to $HOME + int home_l = strlen(home); + vstr_t vstr; + vstr_init(&vstr, home_l + (p1 - p - 1) + 1); + vstr_add_strn(&vstr, home, home_l); + vstr_add_strn(&vstr, p + 1, p1 - p - 1); + path_items[i] = mp_obj_new_str_from_vstr(&mp_type_str, &vstr); + } else { + path_items[i] = mp_obj_new_str_via_qstr(p, p1 - p); + } + p = p1 + 1; } - if (p[0] == '~' && p[1] == '/' && home != NULL) { - // Expand standalone ~ to $HOME - int home_l = strlen(home); - vstr_t vstr; - vstr_init(&vstr, home_l + (p1 - p - 1) + 1); - vstr_add_strn(&vstr, home, home_l); - vstr_add_strn(&vstr, p + 1, p1 - p - 1); - path_items[i] = mp_obj_new_str_from_vstr(&mp_type_str, &vstr); - } else { - path_items[i] = mp_obj_new_str_via_qstr(p, p1 - p); - } - p = p1 + 1; - } } mp_obj_list_init(MP_OBJ_TO_PTR(mp_sys_argv), 0); @@ -605,7 +605,8 @@ MP_NOINLINE int main_(int argc, char **argv) { MP_STATE_VM(mp_optimise_value) = argv[a][2] & 0xf; } else { MP_STATE_VM(mp_optimise_value) = 0; - for (char *p = argv[a] + 1; *p && *p == 'O'; p++, MP_STATE_VM(mp_optimise_value)++); + for (char *p = argv[a] + 1; *p && *p == 'O'; p++, MP_STATE_VM(mp_optimise_value)++) {; + } } } else { return usage(argv); @@ -653,13 +654,13 @@ MP_NOINLINE int main_(int argc, char **argv) { mp_deinit(); -#if MICROPY_ENABLE_GC && !defined(NDEBUG) + #if MICROPY_ENABLE_GC && !defined(NDEBUG) // We don't really need to free memory since we are about to exit the // process, but doing so helps to find memory leaks. free(heap); -#endif + #endif - //printf("total bytes = %d\n", m_get_total_bytes_allocated()); + // printf("total bytes = %d\n", m_get_total_bytes_allocated()); return ret & 0xff; } diff --git a/ports/unix/modffi.c b/ports/unix/modffi.c index c262721ebb..eb17ba3f75 100644 --- a/ports/unix/modffi.c +++ b/ports/unix/modffi.c @@ -91,41 +91,54 @@ typedef struct _mp_obj_fficallback_t { ffi_type *params[]; } mp_obj_fficallback_t; -//STATIC const mp_obj_type_t opaque_type; +// STATIC const mp_obj_type_t opaque_type; STATIC const mp_obj_type_t ffimod_type; STATIC const mp_obj_type_t ffifunc_type; STATIC const mp_obj_type_t fficallback_type; STATIC const mp_obj_type_t ffivar_type; -STATIC ffi_type *char2ffi_type(char c) -{ +STATIC ffi_type *char2ffi_type(char c) { switch (c) { - case 'b': return &ffi_type_schar; - case 'B': return &ffi_type_uchar; - case 'h': return &ffi_type_sshort; - case 'H': return &ffi_type_ushort; - case 'i': return &ffi_type_sint; - case 'I': return &ffi_type_uint; - case 'l': return &ffi_type_slong; - case 'L': return &ffi_type_ulong; - case 'q': return &ffi_type_sint64; - case 'Q': return &ffi_type_uint64; + case 'b': + return &ffi_type_schar; + case 'B': + return &ffi_type_uchar; + case 'h': + return &ffi_type_sshort; + case 'H': + return &ffi_type_ushort; + case 'i': + return &ffi_type_sint; + case 'I': + return &ffi_type_uint; + case 'l': + return &ffi_type_slong; + case 'L': + return &ffi_type_ulong; + case 'q': + return &ffi_type_sint64; + case 'Q': + return &ffi_type_uint64; #if MICROPY_PY_BUILTINS_FLOAT - case 'f': return &ffi_type_float; - case 'd': return &ffi_type_double; + case 'f': + return &ffi_type_float; + case 'd': + return &ffi_type_double; #endif case 'O': // mp_obj_t case 'C': // (*)() case 'P': // const void* case 'p': // void* - case 's': return &ffi_type_pointer; - case 'v': return &ffi_type_void; - default: return NULL; + case 's': + return &ffi_type_pointer; + case 'v': + return &ffi_type_void; + default: + return NULL; } } -STATIC ffi_type *get_ffi_type(mp_obj_t o_in) -{ +STATIC ffi_type *get_ffi_type(mp_obj_t o_in) { if (MP_OBJ_IS_STR(o_in)) { const char *s = mp_obj_str_get_str(o_in); ffi_type *t = char2ffi_type(*s); @@ -138,8 +151,7 @@ STATIC ffi_type *get_ffi_type(mp_obj_t o_in) mp_raise_TypeError("Unknown type"); } -STATIC mp_obj_t return_ffi_value(ffi_arg val, char type) -{ +STATIC mp_obj_t return_ffi_value(ffi_arg val, char type) { switch (type) { case 's': { const char *s = (const char *)(intptr_t)val; @@ -152,11 +164,13 @@ STATIC mp_obj_t return_ffi_value(ffi_arg val, char type) return mp_const_none; #if MICROPY_PY_BUILTINS_FLOAT case 'f': { - union { ffi_arg ffi; float flt; } val_union = { .ffi = val }; + union { ffi_arg ffi; + float flt; + } val_union = { .ffi = val }; return mp_obj_new_float(val_union.flt); } case 'd': { - double *p = (double*)&val; + double *p = (double *)&val; return mp_obj_new_float(*p); } #endif @@ -187,7 +201,7 @@ STATIC mp_obj_t make_func(mp_obj_t rettype_in, void *func, mp_obj_t argtypes_in) const char *argtypes = mp_obj_str_get_str(argtypes_in); mp_int_t nparams = MP_OBJ_SMALL_INT_VALUE(mp_obj_len_maybe(argtypes_in)); - mp_obj_ffifunc_t *o = m_new_obj_var(mp_obj_ffifunc_t, ffi_type*, nparams); + mp_obj_ffifunc_t *o = m_new_obj_var(mp_obj_ffifunc_t, ffi_type *, nparams); o->base.type = &ffifunc_type; o->func = func; @@ -224,20 +238,20 @@ STATIC mp_obj_t ffimod_func(size_t n_args, const mp_obj_t *args) { MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(ffimod_func_obj, 4, 4, ffimod_func); STATIC mp_obj_t mod_ffi_func(mp_obj_t rettype, mp_obj_t addr_in, mp_obj_t argtypes) { - void *addr = (void*)MP_OBJ_TO_PTR(mp_obj_int_get_truncated(addr_in)); + void *addr = (void *)MP_OBJ_TO_PTR(mp_obj_int_get_truncated(addr_in)); return make_func(rettype, addr, argtypes); } MP_DEFINE_CONST_FUN_OBJ_3(mod_ffi_func_obj, mod_ffi_func); -STATIC void call_py_func(ffi_cif *cif, void *ret, void** args, void *func) { +STATIC void call_py_func(ffi_cif *cif, void *ret, void **args, void *func) { mp_obj_t pyargs[cif->nargs]; for (uint i = 0; i < cif->nargs; i++) { - pyargs[i] = mp_obj_new_int(*(mp_int_t*)args[i]); + pyargs[i] = mp_obj_new_int(*(mp_int_t *)args[i]); } mp_obj_t res = mp_call_function_n_kw(MP_OBJ_FROM_PTR(func), cif->nargs, 0, pyargs); if (res != mp_const_none) { - *(ffi_arg*)ret = mp_obj_int_get_truncated(res); + *(ffi_arg *)ret = mp_obj_int_get_truncated(res); } } @@ -245,7 +259,7 @@ STATIC mp_obj_t mod_ffi_callback(mp_obj_t rettype_in, mp_obj_t func_in, mp_obj_t const char *rettype = mp_obj_str_get_str(rettype_in); mp_int_t nparams = MP_OBJ_SMALL_INT_VALUE(mp_obj_len_maybe(paramtypes_in)); - mp_obj_fficallback_t *o = m_new_obj_var(mp_obj_fficallback_t, ffi_type*, nparams); + mp_obj_fficallback_t *o = m_new_obj_var(mp_obj_fficallback_t, ffi_type *, nparams); o->base.type = &fficallback_type; o->clo = ffi_closure_alloc(sizeof(ffi_closure), &o->func); @@ -337,7 +351,7 @@ STATIC const mp_obj_type_t ffimod_type = { .name = MP_QSTR_ffimod, .print = ffimod_print, .make_new = ffimod_make_new, - .locals_dict = (mp_obj_dict_t*)&ffimod_locals_dict, + .locals_dict = (mp_obj_dict_t *)&ffimod_locals_dict, }; // FFI function @@ -362,10 +376,10 @@ STATIC mp_obj_t ffifunc_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const values[i] = (ffi_arg)(intptr_t)a; #if MICROPY_PY_BUILTINS_FLOAT } else if (*argtype == 'f') { - float *p = (float*)&values[i]; + float *p = (float *)&values[i]; *p = mp_obj_get_float(a); } else if (*argtype == 'd') { - double *p = (double*)&values[i]; + double *p = (double *)&values[i]; *p = mp_obj_get_float(a); #endif } else if (a == mp_const_none) { @@ -375,8 +389,8 @@ STATIC mp_obj_t ffifunc_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const } else if (MP_OBJ_IS_STR(a)) { const char *s = mp_obj_str_get_str(a); values[i] = (ffi_arg)(intptr_t)s; - } else if (((mp_obj_base_t*)MP_OBJ_TO_PTR(a))->type->buffer_p.get_buffer != NULL) { - mp_obj_base_t *o = (mp_obj_base_t*)MP_OBJ_TO_PTR(a); + } else if (((mp_obj_base_t *)MP_OBJ_TO_PTR(a))->type->buffer_p.get_buffer != NULL) { + mp_obj_base_t *o = (mp_obj_base_t *)MP_OBJ_TO_PTR(a); mp_buffer_info_t bufinfo; int ret = o->type->buffer_p.get_buffer(MP_OBJ_FROM_PTR(o), &bufinfo, MP_BUFFER_READ); // TODO: MP_BUFFER_READ? if (ret != 0) { @@ -440,7 +454,7 @@ STATIC void ffivar_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kin (void)kind; mp_obj_ffivar_t *self = MP_OBJ_TO_PTR(self_in); // Variable value printed as cast to int - mp_printf(print, "", self->var, *(int*)self->var); + mp_printf(print, "", self->var, *(int *)self->var); } STATIC mp_obj_t ffivar_get(mp_obj_t self_in) { @@ -467,7 +481,7 @@ STATIC const mp_obj_type_t ffivar_type = { { &mp_type_type }, .name = MP_QSTR_ffivar, .print = ffivar_print, - .locals_dict = (mp_obj_dict_t*)&ffivar_locals_dict, + .locals_dict = (mp_obj_dict_t *)&ffivar_locals_dict, }; // Generic opaque storage object (unused) @@ -486,7 +500,7 @@ STATIC mp_obj_t mod_ffi_open(size_t n_args, const mp_obj_t *args) { MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_ffi_open_obj, 1, 2, mod_ffi_open); STATIC mp_obj_t mod_ffi_as_bytearray(mp_obj_t ptr, mp_obj_t size) { - return mp_obj_new_bytearray_by_ref(mp_obj_int_get_truncated(size), (void*)(uintptr_t)mp_obj_int_get_truncated(ptr)); + return mp_obj_new_bytearray_by_ref(mp_obj_int_get_truncated(size), (void *)(uintptr_t)mp_obj_int_get_truncated(ptr)); } MP_DEFINE_CONST_FUN_OBJ_2(mod_ffi_as_bytearray_obj, mod_ffi_as_bytearray); @@ -502,5 +516,5 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_ffi_globals, mp_module_ffi_globals_table); const mp_obj_module_t mp_module_ffi = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_ffi_globals, + .globals = (mp_obj_dict_t *)&mp_module_ffi_globals, }; diff --git a/ports/unix/modjni.c b/ports/unix/modjni.c index 9e8c232094..8bf4f11bf2 100644 --- a/ports/unix/modjni.c +++ b/ports/unix/modjni.c @@ -98,7 +98,7 @@ STATIC bool is_object_type(const char *jtypesig) { STATIC void check_exception(void) { jobject exc = JJ1(ExceptionOccurred); if (exc) { - //JJ1(ExceptionDescribe); + // JJ1(ExceptionDescribe); mp_obj_t py_e = new_jobject(exc); JJ1(ExceptionClear); if (JJ(IsInstanceOf, exc, IndexException_class)) { @@ -142,7 +142,7 @@ STATIC void jclass_attr(mp_obj_t self_in, qstr attr_in, mp_obj_t *dest) { dest[0] = new_jobject(obj); return; } - //JJ1(ExceptionDescribe); + // JJ1(ExceptionDescribe); JJ1(ExceptionClear); mp_obj_jmethod_t *o = m_new_obj(mp_obj_jmethod_t); @@ -179,7 +179,7 @@ STATIC const mp_obj_type_t jclass_type = { .print = jclass_print, .attr = jclass_attr, .call = jclass_call, - .locals_dict = (mp_obj_dict_t*)&jclass_locals_dict, + .locals_dict = (mp_obj_dict_t *)&jclass_locals_dict, }; STATIC mp_obj_t new_jclass(jclass jc) { @@ -220,7 +220,7 @@ STATIC void jobject_attr(mp_obj_t self_in, qstr attr_in, mp_obj_t *dest) { dest[0] = new_jobject(obj); return; } - //JJ1(ExceptionDescribe); + // JJ1(ExceptionDescribe); JJ1(ExceptionClear); mp_obj_jmethod_t *o = m_new_obj(mp_obj_jmethod_t); @@ -246,7 +246,7 @@ STATIC mp_obj_t jobject_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) mp_uint_t idx = mp_obj_get_int(index); char class_name[64]; get_jclass_name(self->obj, class_name); - //printf("class: %s\n", class_name); + // printf("class: %s\n", class_name); if (class_name[0] == '[') { if (class_name[1] == 'L' || class_name[1] == '[') { @@ -288,7 +288,7 @@ STATIC mp_obj_t jobject_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) } -return MP_OBJ_NULL; + return MP_OBJ_NULL; } STATIC mp_obj_t jobject_unary_op(mp_unary_op_t op, mp_obj_t self_in) { @@ -364,10 +364,10 @@ STATIC void jmethod_print(const mp_print_t *print, mp_obj_t self_in, mp_print_ki #define IMATCH(s, static) ((!strncmp(s, static, sizeof(static) - 1)) && (s += sizeof(static) - 1)) #define CHECK_TYPE(java_type_name) \ - if (strncmp(arg_type, java_type_name, sizeof(java_type_name) - 1) != 0) { \ - return false; \ - } \ - arg_type += sizeof(java_type_name) - 1; + if (strncmp(arg_type, java_type_name, sizeof(java_type_name) - 1) != 0) { \ + return false; \ + } \ + arg_type += sizeof(java_type_name) - 1; STATIC const char *strprev(const char *s, char c) { while (*s != c) { @@ -412,7 +412,7 @@ STATIC bool py2jvalue(const char **jtypesig, mp_obj_t arg, jvalue *out) { if (!MATCH(expected_type, "java.lang.Object")) { char class_name[64]; get_jclass_name(jo->obj, class_name); - //printf("Arg class: %s\n", class_name); + // printf("Arg class: %s\n", class_name); if (strcmp(class_name, expected_type) != 0) { return false; } @@ -425,7 +425,7 @@ STATIC bool py2jvalue(const char **jtypesig, mp_obj_t arg, jvalue *out) { return false; } } else if (arg == mp_const_none) { - //printf("TODO: Check java arg type!!\n"); + // printf("TODO: Check java arg type!!\n"); while (isalpha(*arg_type) || *arg_type == '.') { arg_type++; } @@ -470,7 +470,7 @@ STATIC mp_obj_t call_method(jobject obj, const char *name, jarray methods, bool jobject name_o = JJ(CallObjectMethod, meth, Object_toString_mid); const char *decl = JJ(GetStringUTFChars, name_o, NULL); const char *arg_types = strchr(decl, '(') + 1; - //const char *arg_types_end = strchr(arg_types, ')'); + // const char *arg_types_end = strchr(arg_types, ')'); // printf("method[%d]=%p %s\n", i, meth, decl); const char *meth_name = NULL; @@ -481,7 +481,7 @@ STATIC mp_obj_t call_method(jobject obj, const char *name, jarray methods, bool ret_type = strprev(ret_type, ' ') + 1; int name_len = strlen(name); - if (strncmp(name, meth_name, name_len/*arg_types - meth_name - 1*/) || meth_name[name_len] != '('/*(*/) { + if (strncmp(name, meth_name, name_len /*arg_types - meth_name - 1*/) || meth_name[name_len] != '(' /*(*/) { goto next_method; } } @@ -541,7 +541,7 @@ STATIC mp_obj_t call_method(jobject obj, const char *name, jarray methods, bool } } -next_method: + next_method: JJ(ReleaseStringUTFChars, name_o, decl); JJ(DeleteLocalRef, name_o); JJ(DeleteLocalRef, meth); @@ -601,9 +601,9 @@ STATIC void create_jvm(void) { if (!libjvm) { mp_raise_msg(&mp_type_OSError, "unable to load libjvm.so, use LD_LIBRARY_PATH"); } - int (*_JNI_CreateJavaVM)(void*, void**, void*) = dlsym(libjvm, "JNI_CreateJavaVM"); + int (*_JNI_CreateJavaVM)(void *, void **, void *) = dlsym(libjvm, "JNI_CreateJavaVM"); - int st = _JNI_CreateJavaVM(&jvm, (void**)&env, &args); + int st = _JNI_CreateJavaVM(&jvm, (void **)&env, &args); if (st < 0 || !env) { mp_raise_msg(&mp_type_OSError, "unable to create JVM"); } @@ -614,26 +614,26 @@ STATIC void create_jvm(void) { jclass Object_class = JJ(FindClass, "java/lang/Object"); Object_toString_mid = JJ(GetMethodID, Object_class, "toString", - "()Ljava/lang/String;"); + "()Ljava/lang/String;"); Class_getName_mid = (*env)->GetMethodID(env, Class_class, "getName", - "()Ljava/lang/String;"); + "()Ljava/lang/String;"); Class_getField_mid = (*env)->GetMethodID(env, Class_class, "getField", - "(Ljava/lang/String;)Ljava/lang/reflect/Field;"); + "(Ljava/lang/String;)Ljava/lang/reflect/Field;"); Class_getMethods_mid = (*env)->GetMethodID(env, Class_class, "getMethods", - "()[Ljava/lang/reflect/Method;"); + "()[Ljava/lang/reflect/Method;"); Class_getConstructors_mid = (*env)->GetMethodID(env, Class_class, "getConstructors", - "()[Ljava/lang/reflect/Constructor;"); + "()[Ljava/lang/reflect/Constructor;"); Method_getName_mid = (*env)->GetMethodID(env, method_class, "getName", - "()Ljava/lang/String;"); + "()Ljava/lang/String;"); List_class = JJ(FindClass, "java/util/List"); List_get_mid = JJ(GetMethodID, List_class, "get", - "(I)Ljava/lang/Object;"); + "(I)Ljava/lang/Object;"); List_set_mid = JJ(GetMethodID, List_class, "set", - "(ILjava/lang/Object;)Ljava/lang/Object;"); + "(ILjava/lang/Object;)Ljava/lang/Object;"); List_size_mid = JJ(GetMethodID, List_class, "size", - "()I"); + "()I"); IndexException_class = JJ(FindClass, "java/lang/IndexOutOfBoundsException"); } @@ -715,5 +715,5 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_jni_globals, mp_module_jni_globals_table); const mp_obj_module_t mp_module_jni = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_jni_globals, + .globals = (mp_obj_dict_t *)&mp_module_jni_globals, }; diff --git a/ports/unix/modmachine.c b/ports/unix/modmachine.c index 48dddec0ae..9b08cfc0c0 100644 --- a/ports/unix/modmachine.c +++ b/ports/unix/modmachine.c @@ -93,7 +93,7 @@ STATIC MP_DEFINE_CONST_DICT(machine_module_globals, machine_module_globals_table const mp_obj_module_t mp_module_machine = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&machine_module_globals, + .globals = (mp_obj_dict_t *)&machine_module_globals, }; #endif // MICROPY_PY_MACHINE diff --git a/ports/unix/modos.c b/ports/unix/modos.c index d7ba1cfa1e..c400550ef2 100644 --- a/ports/unix/modos.c +++ b/ports/unix/modos.c @@ -248,5 +248,5 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_os_globals, mp_module_os_globals_table); const mp_obj_module_t mp_module_os = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_os_globals, + .globals = (mp_obj_dict_t *)&mp_module_os_globals, }; diff --git a/ports/unix/modtermios.c b/ports/unix/modtermios.c index fe19aac83c..bd723085de 100644 --- a/ports/unix/modtermios.c +++ b/ports/unix/modtermios.c @@ -58,7 +58,7 @@ STATIC mp_obj_t mod_termios_tcgetattr(mp_obj_t fd_in) { // but no way unicode chars could be there, if c_cc is defined to be a // a "char". But it's type is actually cc_t, which can be anything. // TODO: For now, we still deal with it like that. - cc->items[i] = mp_obj_new_bytes((byte*)&term.c_cc[i], 1); + cc->items[i] = mp_obj_new_bytes((byte *)&term.c_cc[i], 1); } } return MP_OBJ_FROM_PTR(r); @@ -129,7 +129,7 @@ STATIC const mp_rom_map_elem_t mp_module_termios_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_tcsetattr), MP_ROM_PTR(&mod_termios_tcsetattr_obj) }, { MP_ROM_QSTR(MP_QSTR_setraw), MP_ROM_PTR(&mod_termios_setraw_obj) }, -#define C(name) { MP_ROM_QSTR(MP_QSTR_ ## name), MP_ROM_INT(name) } +#define C(name) { MP_ROM_QSTR(MP_QSTR_##name), MP_ROM_INT(name) } C(TCSANOW), C(B9600), @@ -146,5 +146,5 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_termios_globals, mp_module_termios_globals const mp_obj_module_t mp_module_termios = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_termios_globals, + .globals = (mp_obj_dict_t *)&mp_module_termios_globals, }; diff --git a/ports/unix/modtime.c b/ports/unix/modtime.c index a74b81f374..66d1db4291 100644 --- a/ports/unix/modtime.c +++ b/ports/unix/modtime.c @@ -66,32 +66,32 @@ static inline int msec_sleep_tv(struct timeval *tv) { #endif STATIC mp_obj_t mod_time_time(void) { -#if MICROPY_PY_BUILTINS_FLOAT + #if MICROPY_PY_BUILTINS_FLOAT struct timeval tv; gettimeofday(&tv, NULL); mp_float_t val = tv.tv_sec + (mp_float_t)tv.tv_usec / 1000000; return mp_obj_new_float(val); -#else + #else return mp_obj_new_int((mp_int_t)time(NULL)); -#endif + #endif } STATIC MP_DEFINE_CONST_FUN_OBJ_0(mod_time_time_obj, mod_time_time); // Note: this is deprecated since CPy3.3, but pystone still uses it. STATIC mp_obj_t mod_time_clock(void) { -#if MICROPY_PY_BUILTINS_FLOAT + #if MICROPY_PY_BUILTINS_FLOAT // float cannot represent full range of int32 precisely, so we pre-divide // int to reduce resolution, and then actually do float division hoping // to preserve integer part resolution. return mp_obj_new_float((float)(clock() / 1000) / CLOCK_DIV); -#else + #else return mp_obj_new_int((mp_int_t)clock()); -#endif + #endif } STATIC MP_DEFINE_CONST_FUN_OBJ_0(mod_time_clock_obj, mod_time_clock); STATIC mp_obj_t mod_time_sleep(mp_obj_t arg) { -#if MICROPY_PY_BUILTINS_FLOAT + #if MICROPY_PY_BUILTINS_FLOAT struct timeval tv; mp_float_t val = mp_obj_get_float(arg); double ipart; @@ -109,18 +109,18 @@ STATIC mp_obj_t mod_time_sleep(mp_obj_t arg) { break; } mp_handle_pending(); - //printf("select: EINTR: %ld:%ld\n", tv.tv_sec, tv.tv_usec); + // printf("select: EINTR: %ld:%ld\n", tv.tv_sec, tv.tv_usec); #else break; #endif } RAISE_ERRNO(res, errno); -#else + #else // TODO: Handle EINTR MP_THREAD_GIL_EXIT(); sleep(mp_obj_get_int(arg)); MP_THREAD_GIL_ENTER(); -#endif + #endif return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_time_sleep_obj, mod_time_sleep); @@ -179,7 +179,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_time_globals, mp_module_time_globals_table const mp_obj_module_t mp_module_time = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_time_globals, + .globals = (mp_obj_dict_t *)&mp_module_time_globals, }; #endif // MICROPY_PY_UTIME diff --git a/ports/unix/moduos_vfs.c b/ports/unix/moduos_vfs.c index e9ac8e1f88..1406672fcd 100644 --- a/ports/unix/moduos_vfs.c +++ b/ports/unix/moduos_vfs.c @@ -77,7 +77,7 @@ STATIC MP_DEFINE_CONST_DICT(uos_vfs_module_globals, uos_vfs_module_globals_table const mp_obj_module_t mp_module_uos_vfs = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&uos_vfs_module_globals, + .globals = (mp_obj_dict_t *)&uos_vfs_module_globals, }; #endif // MICROPY_VFS diff --git a/ports/unix/moduselect.c b/ports/unix/moduselect.c index a95663e31f..2eb719b15f 100644 --- a/ports/unix/moduselect.c +++ b/ports/unix/moduselect.c @@ -312,7 +312,7 @@ STATIC const mp_obj_type_t mp_type_poll = { .name = MP_QSTR_poll, .getiter = mp_identity_getiter, .iternext = poll_iternext, - .locals_dict = (void*)&poll_locals_dict, + .locals_dict = (void *)&poll_locals_dict, }; STATIC mp_obj_t select_poll(size_t n_args, const mp_obj_t *args) { @@ -345,7 +345,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_select_globals, mp_module_select_globals_t const mp_obj_module_t mp_module_uselect = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_select_globals, + .globals = (mp_obj_dict_t *)&mp_module_select_globals, }; #endif // MICROPY_PY_USELECT_POSIX diff --git a/ports/unix/modusocket.c b/ports/unix/modusocket.c index 61402e001d..794022ebdc 100644 --- a/ports/unix/modusocket.c +++ b/ports/unix/modusocket.c @@ -186,10 +186,10 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_listen_obj, socket_listen); STATIC mp_obj_t socket_accept(mp_obj_t self_in) { mp_obj_socket_t *self = MP_OBJ_TO_PTR(self_in); // sockaddr_storage isn't stack-friendly (129 bytes or so) - //struct sockaddr_storage addr; + // struct sockaddr_storage addr; byte addr[32]; socklen_t addr_len = sizeof(addr); - int fd = accept(self->fd, (struct sockaddr*)&addr, &addr_len); + int fd = accept(self->fd, (struct sockaddr *)&addr, &addr_len); RAISE_ERRNO(fd, errno); mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(2, NULL)); @@ -235,7 +235,7 @@ STATIC mp_obj_t socket_recvfrom(size_t n_args, const mp_obj_t *args) { socklen_t addr_len = sizeof(addr); byte *buf = m_new(byte, sz); - int out_sz = recvfrom(self->fd, buf, sz, flags, (struct sockaddr*)&addr, &addr_len); + int out_sz = recvfrom(self->fd, buf, sz, flags, (struct sockaddr *)&addr, &addr_len); RAISE_ERRNO(out_sz, errno); mp_obj_t buf_o = mp_obj_new_str_of_type(&mp_type_bytes, buf, out_sz); @@ -243,7 +243,7 @@ STATIC mp_obj_t socket_recvfrom(size_t n_args, const mp_obj_t *args) { mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(2, NULL)); t->items[0] = buf_o; - t->items[1] = mp_obj_from_sockaddr((struct sockaddr*)&addr, addr_len); + t->items[1] = mp_obj_from_sockaddr((struct sockaddr *)&addr, addr_len); return MP_OBJ_FROM_PTR(t); } @@ -283,7 +283,7 @@ STATIC mp_obj_t socket_sendto(size_t n_args, const mp_obj_t *args) { mp_get_buffer_raise(args[1], &bufinfo, MP_BUFFER_READ); mp_get_buffer_raise(dst_addr, &addr_bi, MP_BUFFER_READ); int out_sz = sendto(self->fd, bufinfo.buf, bufinfo.len, flags, - (struct sockaddr *)addr_bi.buf, addr_bi.len); + (struct sockaddr *)addr_bi.buf, addr_bi.len); RAISE_ERRNO(out_sz, errno); return MP_OBJ_NEW_SMALL_INT(out_sz); @@ -356,9 +356,9 @@ STATIC mp_obj_t socket_settimeout(mp_obj_t self_in, mp_obj_t timeout_in) { new_blocking = false; } else { setsockopt(self->fd, SOL_SOCKET, SO_RCVTIMEO, - &tv, sizeof(struct timeval)); + &tv, sizeof(struct timeval)); setsockopt(self->fd, SOL_SOCKET, SO_SNDTIMEO, - &tv, sizeof(struct timeval)); + &tv, sizeof(struct timeval)); } } @@ -378,7 +378,7 @@ STATIC mp_obj_t socket_makefile(size_t n_args, const mp_obj_t *args) { mp_obj_t *new_args = alloca(n_args * sizeof(mp_obj_t)); memcpy(new_args + 1, args + 1, (n_args - 1) * sizeof(mp_obj_t)); new_args[0] = MP_OBJ_NEW_SMALL_INT(self->fd); - return mp_builtin_open(n_args, new_args, (mp_map_t*)&mp_const_empty_map); + return mp_builtin_open(n_args, new_args, (mp_map_t *)&mp_const_empty_map); } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(socket_makefile_obj, 1, 3, socket_makefile); @@ -445,7 +445,7 @@ const mp_obj_type_t mp_type_socket = { .getiter = NULL, .iternext = NULL, .protocol = &usocket_stream_p, - .locals_dict = (mp_obj_dict_t*)&usocket_locals_dict, + .locals_dict = (mp_obj_dict_t *)&usocket_locals_dict, }; #define BINADDR_MAX_LEN sizeof(struct in6_addr) @@ -499,10 +499,10 @@ STATIC mp_obj_t mod_socket_getaddrinfo(size_t n_args, const mp_obj_t *args) { snprintf(buf, sizeof(buf), "%u", port); serv = buf; hints.ai_flags = AI_NUMERICSERV; -#ifdef __UCLIBC_MAJOR__ -#if __UCLIBC_MAJOR__ == 0 && (__UCLIBC_MINOR__ < 9 || (__UCLIBC_MINOR__ == 9 && __UCLIBC_SUBLEVEL__ <= 32)) + #ifdef __UCLIBC_MAJOR__ + #if __UCLIBC_MAJOR__ == 0 && (__UCLIBC_MINOR__ < 9 || (__UCLIBC_MINOR__ == 9 && __UCLIBC_SUBLEVEL__ <= 32)) // "warning" requires -Wno-cpp which is a relatively new gcc option, so we choose not to use it. -//#warning Working around uClibc bug with numeric service name +// #warning Working around uClibc bug with numeric service name // Older versions og uClibc have bugs when numeric ports in service // arg require also hints.ai_socktype (or hints.ai_protocol) != 0 // This actually was fixed in 0.9.32.1, but uClibc doesn't allow to @@ -511,8 +511,8 @@ STATIC mp_obj_t mod_socket_getaddrinfo(size_t n_args, const mp_obj_t *args) { // Note that this is crude workaround, precluding UDP socket addresses // to be returned. TODO: set only if not set by Python args. hints.ai_socktype = SOCK_STREAM; -#endif -#endif + #endif + #endif } else { serv = mp_obj_str_get_str(args[1]); } @@ -557,30 +557,30 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_socket_getaddrinfo_obj, 2, 4, mod STATIC mp_obj_t mod_socket_sockaddr(mp_obj_t sockaddr_in) { mp_buffer_info_t bufinfo; mp_get_buffer_raise(sockaddr_in, &bufinfo, MP_BUFFER_READ); - switch (((struct sockaddr*)bufinfo.buf)->sa_family) { + switch (((struct sockaddr *)bufinfo.buf)->sa_family) { case AF_INET: { - struct sockaddr_in *sa = (struct sockaddr_in*)bufinfo.buf; + struct sockaddr_in *sa = (struct sockaddr_in *)bufinfo.buf; mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(3, NULL)); t->items[0] = MP_OBJ_NEW_SMALL_INT(AF_INET); - t->items[1] = mp_obj_new_bytes((byte*)&sa->sin_addr, sizeof(sa->sin_addr)); + t->items[1] = mp_obj_new_bytes((byte *)&sa->sin_addr, sizeof(sa->sin_addr)); t->items[2] = MP_OBJ_NEW_SMALL_INT(ntohs(sa->sin_port)); return MP_OBJ_FROM_PTR(t); } case AF_INET6: { - struct sockaddr_in6 *sa = (struct sockaddr_in6*)bufinfo.buf; + struct sockaddr_in6 *sa = (struct sockaddr_in6 *)bufinfo.buf; mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(5, NULL)); t->items[0] = MP_OBJ_NEW_SMALL_INT(AF_INET6); - t->items[1] = mp_obj_new_bytes((byte*)&sa->sin6_addr, sizeof(sa->sin6_addr)); + t->items[1] = mp_obj_new_bytes((byte *)&sa->sin6_addr, sizeof(sa->sin6_addr)); t->items[2] = MP_OBJ_NEW_SMALL_INT(ntohs(sa->sin6_port)); t->items[3] = MP_OBJ_NEW_SMALL_INT(ntohl(sa->sin6_flowinfo)); t->items[4] = MP_OBJ_NEW_SMALL_INT(ntohl(sa->sin6_scope_id)); return MP_OBJ_FROM_PTR(t); } default: { - struct sockaddr *sa = (struct sockaddr*)bufinfo.buf; + struct sockaddr *sa = (struct sockaddr *)bufinfo.buf; mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(2, NULL)); t->items[0] = MP_OBJ_NEW_SMALL_INT(sa->sa_family); - t->items[1] = mp_obj_new_bytes((byte*)sa->sa_data, bufinfo.len - offsetof(struct sockaddr, sa_data)); + t->items[1] = mp_obj_new_bytes((byte *)sa->sa_data, bufinfo.len - offsetof(struct sockaddr, sa_data)); return MP_OBJ_FROM_PTR(t); } } @@ -596,7 +596,7 @@ STATIC const mp_rom_map_elem_t mp_module_socket_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_inet_ntop), MP_ROM_PTR(&mod_socket_inet_ntop_obj) }, { MP_ROM_QSTR(MP_QSTR_sockaddr), MP_ROM_PTR(&mod_socket_sockaddr_obj) }, -#define C(name) { MP_ROM_QSTR(MP_QSTR_ ## name), MP_ROM_INT(name) } +#define C(name) { MP_ROM_QSTR(MP_QSTR_##name), MP_ROM_INT(name) } C(AF_UNIX), C(AF_INET), C(AF_INET6), @@ -620,5 +620,5 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_socket_globals, mp_module_socket_globals_t const mp_obj_module_t mp_module_socket = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_socket_globals, + .globals = (mp_obj_dict_t *)&mp_module_socket_globals, }; diff --git a/ports/unix/mpconfigport.h b/ports/unix/mpconfigport.h index d0cc9e396e..a812383d95 100644 --- a/ports/unix/mpconfigport.h +++ b/ports/unix/mpconfigport.h @@ -36,7 +36,7 @@ #endif #if !defined(MICROPY_EMIT_THUMB) && defined(__thumb2__) #define MICROPY_EMIT_THUMB (1) - #define MICROPY_MAKE_POINTER_CALLABLE(p) ((void*)((mp_uint_t)(p) | 1)) + #define MICROPY_MAKE_POINTER_CALLABLE(p) ((void *)((mp_uint_t)(p) | 1)) #endif // Some compilers define __thumb2__ and __arm__ at the same time, let // autodetected thumb2 emitter have priority. @@ -253,7 +253,7 @@ typedef long long mp_off_t; typedef long mp_off_t; #endif -void mp_unix_alloc_exec(size_t min_size, void** ptr, size_t *size); +void mp_unix_alloc_exec(size_t min_size, void **ptr, size_t *size); void mp_unix_free_exec(void *ptr, size_t size); void mp_unix_mark_exec(void); #define MP_PLAT_ALLOC_EXEC(min_size, ptr, size) mp_unix_alloc_exec(min_size, ptr, size) diff --git a/ports/unix/mphalport.h b/ports/unix/mphalport.h index ff7a51567c..48754d4d18 100644 --- a/ports/unix/mphalport.h +++ b/ports/unix/mphalport.h @@ -49,10 +49,14 @@ static inline int mp_hal_readline(vstr_t *vstr, const char *p) { // TODO: POSIX et al. define usleep() as guaranteedly capable only of 1s sleep: // "The useconds argument shall be less than one million." -static inline void mp_hal_delay_ms(mp_uint_t ms) { usleep((ms) * 1000); } -static inline void mp_hal_delay_us(mp_uint_t us) { usleep(us); } +static inline void mp_hal_delay_ms(mp_uint_t ms) { + usleep((ms) * 1000); +} +static inline void mp_hal_delay_us(mp_uint_t us) { + usleep(us); +} #define mp_hal_ticks_cpu() 0 #define RAISE_ERRNO(err_flag, error_val) \ { if (err_flag == -1) \ - { mp_raise_OSError(error_val); } } + { mp_raise_OSError(error_val); } } diff --git a/ports/unix/mpthreadport.c b/ports/unix/mpthreadport.c index baca0a2b1e..8309e2c13e 100644 --- a/ports/unix/mpthreadport.c +++ b/ports/unix/mpthreadport.c @@ -65,10 +65,10 @@ STATIC void mp_thread_gc(int signo, siginfo_t *info, void *context) { // We have access to the context (regs, stack) of the thread but it seems // that we don't need the extra information, enough is captured by the // gc_collect_regs_and_stack function above - //gc_collect_root((void**)context, sizeof(ucontext_t) / sizeof(uintptr_t)); + // gc_collect_root((void**)context, sizeof(ucontext_t) / sizeof(uintptr_t)); #if MICROPY_ENABLE_PYSTACK - void **ptrs = (void**)(void*)MP_STATE_THREAD(pystack_start); - gc_collect_root(ptrs, (MP_STATE_THREAD(pystack_cur) - MP_STATE_THREAD(pystack_start)) / sizeof(void*)); + void **ptrs = (void **)(void *)MP_STATE_THREAD(pystack_start); + gc_collect_root(ptrs, (MP_STATE_THREAD(pystack_cur) - MP_STATE_THREAD(pystack_start)) / sizeof(void *)); #endif thread_signal_done = 1; } @@ -119,7 +119,7 @@ void mp_thread_gc_others(void) { } mp_state_thread_t *mp_thread_get_state(void) { - return (mp_state_thread_t*)pthread_getspecific(tls_key); + return (mp_state_thread_t *)pthread_getspecific(tls_key); } void mp_thread_set_state(void *state) { @@ -137,7 +137,7 @@ void mp_thread_start(void) { pthread_mutex_unlock(&thread_mutex); } -void mp_thread_create(void *(*entry)(void*), void *arg, size_t *stack_size) { +void mp_thread_create(void *(*entry)(void *), void *arg, size_t *stack_size) { // default stack size is 8k machine-words if (*stack_size == 0) { *stack_size = 8192 * BYTES_PER_WORD; diff --git a/ports/unix/unix_mphal.c b/ports/unix/unix_mphal.c index f27c62fd1d..b6030a92e1 100644 --- a/ports/unix/unix_mphal.c +++ b/ports/unix/unix_mphal.c @@ -126,7 +126,7 @@ static int call_dupterm_read(size_t idx) { return -1; } nlr_pop(); - return *(byte*)bufinfo.buf; + return *(byte *)bufinfo.buf; } else { // Temporarily disable dupterm to avoid infinite recursion mp_obj_t save_term = MP_STATE_VM(dupterm_objs[idx]); @@ -142,12 +142,12 @@ static int call_dupterm_read(size_t idx) { int mp_hal_stdin_rx_chr(void) { unsigned char c; -#if MICROPY_PY_OS_DUPTERM + #if MICROPY_PY_OS_DUPTERM // TODO only support dupterm one slot at the moment if (MP_STATE_VM(dupterm_objs[0]) != MP_OBJ_NULL) { int c; do { - c = call_dupterm_read(0); + c = call_dupterm_read(0); } while (c == -2); if (c == -1) { goto main_term; @@ -157,18 +157,18 @@ int mp_hal_stdin_rx_chr(void) { } return c; } else { - main_term:; -#endif - int ret = read(0, &c, 1); - if (ret == 0) { - c = 4; // EOF, ctrl-D - } else if (c == '\n') { - c = '\r'; - } - return c; -#if MICROPY_PY_OS_DUPTERM + main_term:; + #endif + int ret = read(0, &c, 1); + if (ret == 0) { + c = 4; // EOF, ctrl-D + } else if (c == '\n') { + c = '\r'; } -#endif + return c; + #if MICROPY_PY_OS_DUPTERM +} + #endif } void mp_hal_stdout_tx_strn(const char *str, size_t len) { diff --git a/ports/windows/fmode.c b/ports/windows/fmode.c index 33ba24ed1f..a7976b87e3 100644 --- a/ports/windows/fmode.c +++ b/ports/windows/fmode.c @@ -32,12 +32,12 @@ // Workaround for setting file translation mode: we must distinguish toolsets // since mingw has no _set_fmode, and altering msvc's _fmode directly has no effect STATIC int set_fmode_impl(int mode) { -#ifndef _MSC_VER + #ifndef _MSC_VER _fmode = mode; return 0; -#else + #else return _set_fmode(mode); -#endif + #endif } void set_fmode_binary(void) { diff --git a/ports/windows/init.c b/ports/windows/init.c index 09fa10417b..91a58730c5 100644 --- a/ports/windows/init.c +++ b/ports/windows/init.c @@ -40,7 +40,7 @@ void invalid_param_handler(const wchar_t *expr, const wchar_t *fun, const wchar_ #endif void init() { -#ifdef _MSC_VER + #ifdef _MSC_VER // Disable the 'Debug Error!' dialog for assertions failures and the likes, // instead write messages to the debugger output and terminate. _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG); @@ -51,16 +51,16 @@ void init() { // passing invalid file descriptors to functions like lseek() and make the // functions called behave properly by setting errno to EBADF/EINVAL/.. _set_invalid_parameter_handler(invalid_param_handler); -#endif + #endif SetConsoleCtrlHandler(console_sighandler, TRUE); init_sleep(); -#ifdef __MINGW32__ + #ifdef __MINGW32__ putenv("PRINTF_EXPONENT_DIGITS=2"); -#elif _MSC_VER < 1900 + #elif _MSC_VER < 1900 // This is only necessary for Visual Studio versions 2013 and below: // https://msdn.microsoft.com/en-us/library/bb531344(v=vs.140).aspx _set_output_format(_TWO_DIGIT_EXPONENT); -#endif + #endif } void deinit() { diff --git a/ports/windows/mpconfigport.h b/ports/windows/mpconfigport.h index 81464d72a7..356428f770 100644 --- a/ports/windows/mpconfigport.h +++ b/ports/windows/mpconfigport.h @@ -31,7 +31,7 @@ #define MICROPY_USE_READLINE (1) #endif -#define MICROPY_ALLOC_PATH_MAX (260) //see minwindef.h for msvc or limits.h for mingw +#define MICROPY_ALLOC_PATH_MAX (260) // see minwindef.h for msvc or limits.h for mingw #define MICROPY_PERSISTENT_CODE_LOAD (1) #define MICROPY_EMIT_X64 (0) #define MICROPY_EMIT_THUMB (0) @@ -133,15 +133,15 @@ extern const struct _mp_print_t mp_stderr_print; // type definitions for the specific machine -#if defined( __MINGW32__ ) && defined( __LP64__ ) +#if defined(__MINGW32__) && defined(__LP64__) typedef long mp_int_t; // must be pointer size typedef unsigned long mp_uint_t; // must be pointer size -#elif defined ( __MINGW32__ ) && defined( _WIN64 ) +#elif defined(__MINGW32__) && defined(_WIN64) #include typedef __int64 mp_int_t; typedef unsigned __int64 mp_uint_t; #define MP_SSIZE_MAX __INT64_MAX__ -#elif defined ( _MSC_VER ) && defined( _WIN64 ) +#elif defined(_MSC_VER) && defined(_WIN64) typedef __int64 mp_int_t; typedef unsigned __int64 mp_uint_t; #else @@ -206,7 +206,7 @@ extern const struct _mp_obj_module_t mp_module_time; // Sanity check -#if ( _MSC_VER < 1800 ) +#if (_MSC_VER < 1800) #error Can only build with Visual Studio 2013 toolset #endif @@ -217,7 +217,7 @@ extern const struct _mp_obj_module_t mp_module_time; #define MP_NOINLINE __declspec(noinline) #define MP_LIKELY(x) (x) #define MP_UNLIKELY(x) (x) -#define MICROPY_PORT_CONSTANTS { "dummy", 0 } //can't have zero-sized array +#define MICROPY_PORT_CONSTANTS { "dummy", 0 } // can't have zero-sized array #ifdef _WIN64 #define MP_SSIZE_MAX _I64_MAX #else @@ -235,12 +235,12 @@ extern const struct _mp_obj_module_t mp_module_time; #define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR) #ifdef _WIN64 #define SSIZE_MAX _I64_MAX -typedef __int64 ssize_t; +typedef __int64 ssize_t; #else #define SSIZE_MAX _I32_MAX -typedef int ssize_t; +typedef int ssize_t; #endif -typedef mp_off_t off_t; +typedef mp_off_t off_t; // Put static/global variables in sections with a known name @@ -254,7 +254,7 @@ typedef mp_off_t off_t; // System headers (needed e.g. for nlr.h) -#include //for NULL -#include //for assert +#include // for NULL +#include // for assert #endif diff --git a/ports/windows/realpath.c b/ports/windows/realpath.c index ac9adf8125..5e429ef6a0 100644 --- a/ports/windows/realpath.c +++ b/ports/windows/realpath.c @@ -33,8 +33,9 @@ char *to_unix_path(char *p) { if (p != NULL) { char *pp = p; while (*pp != 0) { - if (*pp == '\\') + if (*pp == '\\') { *pp = '/'; + } ++pp; } } @@ -50,14 +51,16 @@ char *realpath(const char *path, char *resolved_path) { errno = EINVAL; } else if (access(path, R_OK) == 0) { ret = resolved_path; - if (ret == NULL) + if (ret == NULL) { ret = malloc(_MAX_PATH); + } if (ret == NULL) { errno = ENOMEM; } else { ret = _fullpath(ret, path, _MAX_PATH); - if (ret == NULL) + if (ret == NULL) { errno = EIO; + } } } return to_unix_path(ret); diff --git a/ports/windows/windows_mphal.c b/ports/windows/windows_mphal.c index 153b044235..60e8801874 100644 --- a/ports/windows/windows_mphal.c +++ b/ports/windows/windows_mphal.c @@ -46,8 +46,8 @@ STATIC void assure_stdin_handle() { STATIC void assure_conout_handle() { if (!con_out) { con_out = CreateFile("CONOUT$", GENERIC_READ | GENERIC_WRITE, - FILE_SHARE_READ | FILE_SHARE_WRITE, - NULL, OPEN_EXISTING, 0, 0); + FILE_SHARE_READ | FILE_SHARE_WRITE, + NULL, OPEN_EXISTING, 0, 0); assert(con_out != INVALID_HANDLE_VALUE); } } @@ -139,7 +139,7 @@ STATIC item_t keyCodeMap[] = { {VK_HOME, "[H"}, {VK_END, "[F"}, {VK_DELETE, "[3~"}, - {0, ""} //sentinel + {0, ""} // sentinel }; STATIC const char *cur_esc_seq = NULL; @@ -177,20 +177,20 @@ int mp_hal_stdin_rx_chr(void) { DWORD num_read; INPUT_RECORD rec; for (;;) { - if (!ReadConsoleInput(std_in, &rec, 1, &num_read) || !num_read) { - return CHAR_CTRL_C; // EOF, ctrl-D - } - if (rec.EventType != KEY_EVENT || !rec.Event.KeyEvent.bKeyDown) { // only want key down events - continue; - } - const char c = rec.Event.KeyEvent.uChar.AsciiChar; - if (c) { // plain ascii char, return it - return c; - } - const int ret = esc_seq_process_vk(rec.Event.KeyEvent.wVirtualKeyCode); - if (ret) { - return ret; - } + if (!ReadConsoleInput(std_in, &rec, 1, &num_read) || !num_read) { + return CHAR_CTRL_C; // EOF, ctrl-D + } + if (rec.EventType != KEY_EVENT || !rec.Event.KeyEvent.bKeyDown) { // only want key down events + continue; + } + const char c = rec.Event.KeyEvent.uChar.AsciiChar; + if (c) { // plain ascii char, return it + return c; + } + const int ret = esc_seq_process_vk(rec.Event.KeyEvent.wVirtualKeyCode); + if (ret) { + return ret; + } } } @@ -221,9 +221,9 @@ mp_uint_t mp_hal_ticks_us(void) { mp_uint_t mp_hal_ticks_cpu(void) { LARGE_INTEGER value; QueryPerformanceCounter(&value); -#ifdef _WIN64 + #ifdef _WIN64 return value.QuadPart; -#else + #else return value.LowPart; -#endif + #endif } diff --git a/ports/zephyr/help.c b/ports/zephyr/help.c index becc203f6f..4ee674b9d2 100644 --- a/ports/zephyr/help.c +++ b/ports/zephyr/help.c @@ -27,14 +27,14 @@ #include "py/builtin.h" const char zephyr_help_text[] = -"Welcome to MicroPython!\n" -"\n" -"Control commands:\n" -" CTRL-A -- on a blank line, enter raw REPL mode\n" -" CTRL-B -- on a blank line, enter normal REPL mode\n" -" CTRL-C -- interrupt a running program\n" -" CTRL-D -- on a blank line, do a soft reset of the board\n" -" CTRL-E -- on a blank line, enter paste mode\n" -"\n" -"For further help on a specific object, type help(obj)\n" + "Welcome to MicroPython!\n" + "\n" + "Control commands:\n" + " CTRL-A -- on a blank line, enter raw REPL mode\n" + " CTRL-B -- on a blank line, enter normal REPL mode\n" + " CTRL-C -- interrupt a running program\n" + " CTRL-D -- on a blank line, do a soft reset of the board\n" + " CTRL-E -- on a blank line, enter paste mode\n" + "\n" + "For further help on a specific object, type help(obj)\n" ; diff --git a/ports/zephyr/main.c b/ports/zephyr/main.c index a28fb37923..ec65110454 100644 --- a/ports/zephyr/main.c +++ b/ports/zephyr/main.c @@ -54,7 +54,7 @@ static char heap[MICROPY_HEAP_SIZE]; void init_zephyr(void) { // We now rely on CONFIG_NET_APP_SETTINGS to set up bootstrap // network addresses. -#if 0 + #if 0 #ifdef CONFIG_NETWORKING if (net_if_get_default() == NULL) { // If there's no default networking interface, @@ -75,12 +75,12 @@ void init_zephyr(void) { static struct in6_addr in6addr_my = {{{0x20, 0x01, 0x0d, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}}}; net_if_ipv6_addr_add(net_if_get_default(), &in6addr_my, NET_ADDR_MANUAL, 0); #endif -#endif + #endif } int real_main(void) { int stack_dummy; - stack_top = (char*)&stack_dummy; + stack_top = (char *)&stack_dummy; mp_stack_set_top(stack_top); // Make MicroPython's stack limit somewhat smaller than full stack available mp_stack_set_limit(CONFIG_MAIN_STACK_SIZE - 512); @@ -132,7 +132,7 @@ void gc_collect(void) { gc_collect_start(); gc_collect_root(&dummy, ((mp_uint_t)stack_top - (mp_uint_t)&dummy) / sizeof(mp_uint_t)); gc_collect_end(); - //gc_dump_info(); + // gc_dump_info(); } mp_lexer_t *mp_lexer_new_from_file(const char *filename) { @@ -149,7 +149,9 @@ mp_obj_t mp_builtin_open(size_t n_args, const mp_obj_t *args, mp_map_t *kwargs) MP_DEFINE_CONST_FUN_OBJ_KW(mp_builtin_open_obj, 1, mp_builtin_open); NORETURN void nlr_jump_fail(void *val) { - while (1); + while (1) { + ; + } } #ifndef NDEBUG diff --git a/ports/zephyr/modmachine.c b/ports/zephyr/modmachine.c index 5909c37d6f..2ea654932f 100644 --- a/ports/zephyr/modmachine.c +++ b/ports/zephyr/modmachine.c @@ -71,7 +71,7 @@ STATIC MP_DEFINE_CONST_DICT(machine_module_globals, machine_module_globals_table const mp_obj_module_t mp_module_machine = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&machine_module_globals, + .globals = (mp_obj_dict_t *)&machine_module_globals, }; #endif // MICROPY_PY_MACHINE diff --git a/ports/zephyr/modusocket.c b/ports/zephyr/modusocket.c index 84d6fa7297..384a06c96c 100644 --- a/ports/zephyr/modusocket.c +++ b/ports/zephyr/modusocket.c @@ -75,18 +75,18 @@ STATIC void socket_check_closed(socket_obj_t *socket) { STATIC void parse_inet_addr(socket_obj_t *socket, mp_obj_t addr_in, struct sockaddr *sockaddr) { // We employ the fact that port and address offsets are the same for IPv4 & IPv6 - struct sockaddr_in *sockaddr_in = (struct sockaddr_in*)sockaddr; + struct sockaddr_in *sockaddr_in = (struct sockaddr_in *)sockaddr; mp_obj_t *addr_items; mp_obj_get_array_fixed_n(addr_in, 2, &addr_items); - sockaddr_in->sin_family = net_context_get_family((void*)socket->ctx); + sockaddr_in->sin_family = net_context_get_family((void *)socket->ctx); RAISE_ERRNO(net_addr_pton(sockaddr_in->sin_family, mp_obj_str_get_str(addr_items[0]), &sockaddr_in->sin_addr)); sockaddr_in->sin_port = htons(mp_obj_get_int(addr_items[1])); } STATIC mp_obj_t format_inet_addr(struct sockaddr *addr, mp_obj_t port) { // We employ the fact that port and address offsets are the same for IPv4 & IPv6 - struct sockaddr_in6 *sockaddr_in6 = (struct sockaddr_in6*)addr; + struct sockaddr_in6 *sockaddr_in6 = (struct sockaddr_in6 *)addr; char buf[40]; net_addr_ntop(addr->sa_family, &sockaddr_in6->sin6_addr, buf, sizeof(buf)); mp_obj_tuple_t *tuple = mp_obj_new_tuple(addr->sa_family == AF_INET ? 2 : 4, NULL); @@ -94,7 +94,7 @@ STATIC mp_obj_t format_inet_addr(struct sockaddr *addr, mp_obj_t port) { tuple->items[0] = mp_obj_new_str(buf, strlen(buf)); // We employ the fact that port offset is the same for IPv4 & IPv6 // not filled in - //tuple->items[1] = mp_obj_new_int(ntohs(((struct sockaddr_in*)addr)->sin_port)); + // tuple->items[1] = mp_obj_new_int(ntohs(((struct sockaddr_in*)addr)->sin_port)); tuple->items[1] = port; if (addr->sa_family == AF_INET6) { @@ -119,7 +119,7 @@ STATIC void socket_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kin if (self->ctx == -1) { mp_printf(print, ""); } else { - struct net_context *ctx = (void*)self->ctx; + struct net_context *ctx = (void *)self->ctx; mp_printf(print, "", ctx, net_context_get_type(ctx)); } } @@ -462,7 +462,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_usocket_globals, mp_module_usocket_globals const mp_obj_module_t mp_module_usocket = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_usocket_globals, + .globals = (mp_obj_dict_t *)&mp_module_usocket_globals, }; #endif // MICROPY_PY_USOCKET diff --git a/ports/zephyr/modutime.c b/ports/zephyr/modutime.c index a5d32fe665..ba9e1d8f1f 100644 --- a/ports/zephyr/modutime.c +++ b/ports/zephyr/modutime.c @@ -61,7 +61,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_time_globals, mp_module_time_globals_table const mp_obj_module_t mp_module_time = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_time_globals, + .globals = (mp_obj_dict_t *)&mp_module_time_globals, }; #endif // MICROPY_PY_UTIME diff --git a/ports/zephyr/modzephyr.c b/ports/zephyr/modzephyr.c index 265fc882dc..9f5642dbb7 100644 --- a/ports/zephyr/modzephyr.c +++ b/ports/zephyr/modzephyr.c @@ -50,7 +50,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_0(mod_stacks_analyze_obj, mod_stacks_analyze); #ifdef CONFIG_NET_SHELL -//int net_shell_cmd_iface(int argc, char *argv[]); +// int net_shell_cmd_iface(int argc, char *argv[]); STATIC mp_obj_t mod_shell_net_iface(void) { net_shell_cmd_iface(0, NULL); @@ -75,7 +75,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_time_globals, mp_module_time_globals_table const mp_obj_module_t mp_module_zephyr = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_time_globals, + .globals = (mp_obj_dict_t *)&mp_module_time_globals, }; #endif // MICROPY_PY_ZEPHYR diff --git a/ports/zephyr/modzsensor.c b/ports/zephyr/modzsensor.c index 74c909d167..1152d0273a 100644 --- a/ports/zephyr/modzsensor.c +++ b/ports/zephyr/modzsensor.c @@ -110,14 +110,14 @@ STATIC const mp_obj_type_t sensor_type = { { &mp_type_type }, .name = MP_QSTR_Sensor, .make_new = sensor_make_new, - .locals_dict = (void*)&sensor_locals_dict, + .locals_dict = (void *)&sensor_locals_dict, }; STATIC const mp_rom_map_elem_t mp_module_zsensor_globals_table[] = { { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_zsensor) }, { MP_ROM_QSTR(MP_QSTR_Sensor), MP_ROM_PTR(&sensor_type) }, -#define C(name) { MP_ROM_QSTR(MP_QSTR_ ## name), MP_ROM_INT(SENSOR_CHAN_ ## name) } +#define C(name) { MP_ROM_QSTR(MP_QSTR_##name), MP_ROM_INT(SENSOR_CHAN_##name) } C(ACCEL_X), C(ACCEL_Y), C(ACCEL_Z), @@ -140,7 +140,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_zsensor_globals, mp_module_zsensor_globals const mp_obj_module_t mp_module_zsensor = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_zsensor_globals, + .globals = (mp_obj_dict_t *)&mp_module_zsensor_globals, }; -#endif //MICROPY_PY_UHASHLIB +#endif // MICROPY_PY_UHASHLIB diff --git a/ports/zephyr/uart_core.c b/ports/zephyr/uart_core.c index 325e437434..8900977041 100644 --- a/ports/zephyr/uart_core.c +++ b/ports/zephyr/uart_core.c @@ -36,23 +36,23 @@ // Receive single character int mp_hal_stdin_rx_chr(void) { -#ifdef CONFIG_CONSOLE_SUBSYS + #ifdef CONFIG_CONSOLE_SUBSYS return console_getchar(); -#else + #else return zephyr_getchar(); -#endif + #endif } // Send string of given length void mp_hal_stdout_tx_strn(const char *str, mp_uint_t len) { -#ifdef CONFIG_CONSOLE_SUBSYS + #ifdef CONFIG_CONSOLE_SUBSYS while (len--) { char c = *str++; while (console_putchar(c) == -1) { k_sleep(1); } } -#else + #else static struct device *uart_console_dev; if (uart_console_dev == NULL) { uart_console_dev = device_get_binding(CONFIG_UART_CONSOLE_ON_DEV_NAME); @@ -61,5 +61,5 @@ void mp_hal_stdout_tx_strn(const char *str, mp_uint_t len) { while (len--) { uart_poll_out(uart_console_dev, *str++); } -#endif + #endif } diff --git a/py/argcheck.c b/py/argcheck.c index c2b1b6c079..33d39d31f8 100644 --- a/py/argcheck.c +++ b/py/argcheck.c @@ -114,7 +114,7 @@ void mp_arg_parse_all(size_t n_pos, const mp_obj_t *pos, mp_map_t *kws, size_t n } } if (pos_found < n_pos) { - extra_positional: + extra_positional: if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) { mp_arg_error_terse_mismatch(); } else { diff --git a/py/asmarm.c b/py/asmarm.c index 3610f838e6..8f43758fec 100644 --- a/py/asmarm.c +++ b/py/asmarm.c @@ -40,16 +40,16 @@ void asm_arm_end_pass(asm_arm_t *as) { if (as->base.pass == MP_ASM_PASS_EMIT) { -#ifdef __arm__ + #ifdef __arm__ // flush I- and D-cache - asm volatile( - "0:" - "mrc p15, 0, r15, c7, c10, 3\n" - "bne 0b\n" - "mov r0, #0\n" - "mcr p15, 0, r0, c7, c7, 0\n" - : : : "r0", "cc"); -#endif + asm volatile ( + "0:" + "mrc p15, 0, r15, c7, c10, 3\n" + "bne 0b\n" + "mov r0, #0\n" + "mcr p15, 0, r0, c7, c7, 0\n" + : : : "r0", "cc"); + #endif } } @@ -57,7 +57,7 @@ void asm_arm_end_pass(asm_arm_t *as) { STATIC void emit(asm_arm_t *as, uint op) { uint8_t *c = mp_asm_base_get_cur_to_write_bytes(&as->base, 4); if (c != NULL) { - *(uint32_t*)c = op; + *(uint32_t *)c = op; } } @@ -205,7 +205,7 @@ void asm_arm_mov_reg_i32(asm_arm_t *as, uint rd, int imm) { // mvn is "move not", not "move negative" emit_al(as, asm_arm_op_mvn_imm(rd, ~imm)); } else { - //Insert immediate into code and jump over it + // Insert immediate into code and jump over it emit_al(as, 0x59f0000 | (rd << 12)); // ldr rd, [pc] emit_al(as, 0xa000000); // b pc emit(as, imm); diff --git a/py/asmbase.c b/py/asmbase.c index 4c84c3b255..8f40fe7e06 100644 --- a/py/asmbase.c +++ b/py/asmbase.c @@ -51,7 +51,7 @@ void mp_asm_base_start_pass(mp_asm_base_t *as, int pass) { memset(as->label_offsets, -1, as->max_num_labels * sizeof(size_t)); } else { // allocating executable RAM is platform specific - MP_PLAT_ALLOC_EXEC(as->code_offset, (void**)&as->code_base, &as->code_size); + MP_PLAT_ALLOC_EXEC(as->code_offset, (void **)&as->code_base, &as->code_size); assert(as->code_base != NULL); } as->pass = pass; @@ -84,12 +84,12 @@ void mp_asm_base_label_assign(mp_asm_base_t *as, size_t label) { } // align must be a multiple of 2 -void mp_asm_base_align(mp_asm_base_t* as, unsigned int align) { +void mp_asm_base_align(mp_asm_base_t *as, unsigned int align) { as->code_offset = (as->code_offset + align - 1) & (~(align - 1)); } // this function assumes a little endian machine -void mp_asm_base_data(mp_asm_base_t* as, unsigned int bytesize, uintptr_t val) { +void mp_asm_base_data(mp_asm_base_t *as, unsigned int bytesize, uintptr_t val) { uint8_t *c = mp_asm_base_get_cur_to_write_bytes(as, bytesize); if (c != NULL) { for (unsigned int i = 0; i < bytesize; i++) { diff --git a/py/asmbase.h b/py/asmbase.h index d2b4038931..ba26a757ff 100644 --- a/py/asmbase.h +++ b/py/asmbase.h @@ -47,8 +47,8 @@ void mp_asm_base_deinit(mp_asm_base_t *as, bool free_code); void mp_asm_base_start_pass(mp_asm_base_t *as, int pass); uint8_t *mp_asm_base_get_cur_to_write_bytes(mp_asm_base_t *as, size_t num_bytes_to_write); void mp_asm_base_label_assign(mp_asm_base_t *as, size_t label); -void mp_asm_base_align(mp_asm_base_t* as, unsigned int align); -void mp_asm_base_data(mp_asm_base_t* as, unsigned int bytesize, uintptr_t val); +void mp_asm_base_align(mp_asm_base_t *as, unsigned int align); +void mp_asm_base_data(mp_asm_base_t *as, unsigned int bytesize, uintptr_t val); static inline size_t mp_asm_base_get_code_pos(mp_asm_base_t *as) { return as->code_offset; diff --git a/py/asmthumb.c b/py/asmthumb.c index 46102395dc..eb64009b6e 100644 --- a/py/asmthumb.c +++ b/py/asmthumb.c @@ -354,7 +354,7 @@ void asm_thumb_b_label(asm_thumb_t *as, uint label) { } } else { // is a forwards jump, so need to assume it's large - large_jump: + large_jump: asm_thumb_op32(as, OP_BW_HI(rel), OP_BW_LO(rel)); } } @@ -373,7 +373,7 @@ void asm_thumb_bcc_label(asm_thumb_t *as, int cond, uint label) { } } else { // is a forwards jump, so need to assume it's large - large_jump: + large_jump: asm_thumb_op32(as, OP_BCC_W_HI(cond, rel), OP_BCC_W_LO(rel)); } } diff --git a/py/asmthumb.h b/py/asmthumb.h index 9a44a78cae..19f48206f7 100644 --- a/py/asmthumb.h +++ b/py/asmthumb.h @@ -95,8 +95,9 @@ void asm_thumb_exit(asm_thumb_t *as); void asm_thumb_op16(asm_thumb_t *as, uint op); void asm_thumb_op32(asm_thumb_t *as, uint op1, uint op2); -static inline void asm_thumb_it_cc(asm_thumb_t *as, uint cc, uint mask) - { asm_thumb_op16(as, ASM_THUMB_OP_IT | (cc << 4) | mask); } +static inline void asm_thumb_it_cc(asm_thumb_t *as, uint cc, uint mask) { + asm_thumb_op16(as, ASM_THUMB_OP_IT | (cc << 4) | mask); +} // FORMAT 1: move shifted register @@ -129,14 +130,18 @@ static inline void asm_thumb_format_2(asm_thumb_t *as, uint op, uint rlo_dest, u asm_thumb_op16(as, ASM_THUMB_FORMAT_2_ENCODE(op, rlo_dest, rlo_src, src_b)); } -static inline void asm_thumb_add_rlo_rlo_rlo(asm_thumb_t *as, uint rlo_dest, uint rlo_src_a, uint rlo_src_b) - { asm_thumb_format_2(as, ASM_THUMB_FORMAT_2_ADD | ASM_THUMB_FORMAT_2_REG_OPERAND, rlo_dest, rlo_src_a, rlo_src_b); } -static inline void asm_thumb_add_rlo_rlo_i3(asm_thumb_t *as, uint rlo_dest, uint rlo_src_a, int i3_src) - { asm_thumb_format_2(as, ASM_THUMB_FORMAT_2_ADD | ASM_THUMB_FORMAT_2_IMM_OPERAND, rlo_dest, rlo_src_a, i3_src); } -static inline void asm_thumb_sub_rlo_rlo_rlo(asm_thumb_t *as, uint rlo_dest, uint rlo_src_a, uint rlo_src_b) - { asm_thumb_format_2(as, ASM_THUMB_FORMAT_2_SUB | ASM_THUMB_FORMAT_2_REG_OPERAND, rlo_dest, rlo_src_a, rlo_src_b); } -static inline void asm_thumb_sub_rlo_rlo_i3(asm_thumb_t *as, uint rlo_dest, uint rlo_src_a, int i3_src) - { asm_thumb_format_2(as, ASM_THUMB_FORMAT_2_SUB | ASM_THUMB_FORMAT_2_IMM_OPERAND, rlo_dest, rlo_src_a, i3_src); } +static inline void asm_thumb_add_rlo_rlo_rlo(asm_thumb_t *as, uint rlo_dest, uint rlo_src_a, uint rlo_src_b) { + asm_thumb_format_2(as, ASM_THUMB_FORMAT_2_ADD | ASM_THUMB_FORMAT_2_REG_OPERAND, rlo_dest, rlo_src_a, rlo_src_b); +} +static inline void asm_thumb_add_rlo_rlo_i3(asm_thumb_t *as, uint rlo_dest, uint rlo_src_a, int i3_src) { + asm_thumb_format_2(as, ASM_THUMB_FORMAT_2_ADD | ASM_THUMB_FORMAT_2_IMM_OPERAND, rlo_dest, rlo_src_a, i3_src); +} +static inline void asm_thumb_sub_rlo_rlo_rlo(asm_thumb_t *as, uint rlo_dest, uint rlo_src_a, uint rlo_src_b) { + asm_thumb_format_2(as, ASM_THUMB_FORMAT_2_SUB | ASM_THUMB_FORMAT_2_REG_OPERAND, rlo_dest, rlo_src_a, rlo_src_b); +} +static inline void asm_thumb_sub_rlo_rlo_i3(asm_thumb_t *as, uint rlo_dest, uint rlo_src_a, int i3_src) { + asm_thumb_format_2(as, ASM_THUMB_FORMAT_2_SUB | ASM_THUMB_FORMAT_2_IMM_OPERAND, rlo_dest, rlo_src_a, i3_src); +} // FORMAT 3: move/compare/add/subtract immediate // These instructions all do zero extension of the i8 value @@ -153,10 +158,18 @@ static inline void asm_thumb_format_3(asm_thumb_t *as, uint op, uint rlo, int i8 asm_thumb_op16(as, ASM_THUMB_FORMAT_3_ENCODE(op, rlo, i8)); } -static inline void asm_thumb_mov_rlo_i8(asm_thumb_t *as, uint rlo, int i8) { asm_thumb_format_3(as, ASM_THUMB_FORMAT_3_MOV, rlo, i8); } -static inline void asm_thumb_cmp_rlo_i8(asm_thumb_t *as, uint rlo, int i8) { asm_thumb_format_3(as, ASM_THUMB_FORMAT_3_CMP, rlo, i8); } -static inline void asm_thumb_add_rlo_i8(asm_thumb_t *as, uint rlo, int i8) { asm_thumb_format_3(as, ASM_THUMB_FORMAT_3_ADD, rlo, i8); } -static inline void asm_thumb_sub_rlo_i8(asm_thumb_t *as, uint rlo, int i8) { asm_thumb_format_3(as, ASM_THUMB_FORMAT_3_SUB, rlo, i8); } +static inline void asm_thumb_mov_rlo_i8(asm_thumb_t *as, uint rlo, int i8) { + asm_thumb_format_3(as, ASM_THUMB_FORMAT_3_MOV, rlo, i8); +} +static inline void asm_thumb_cmp_rlo_i8(asm_thumb_t *as, uint rlo, int i8) { + asm_thumb_format_3(as, ASM_THUMB_FORMAT_3_CMP, rlo, i8); +} +static inline void asm_thumb_add_rlo_i8(asm_thumb_t *as, uint rlo, int i8) { + asm_thumb_format_3(as, ASM_THUMB_FORMAT_3_ADD, rlo, i8); +} +static inline void asm_thumb_sub_rlo_i8(asm_thumb_t *as, uint rlo, int i8) { + asm_thumb_format_3(as, ASM_THUMB_FORMAT_3_SUB, rlo, i8); +} // FORMAT 4: ALU operations @@ -179,7 +192,9 @@ static inline void asm_thumb_sub_rlo_i8(asm_thumb_t *as, uint rlo, int i8) { asm void asm_thumb_format_4(asm_thumb_t *as, uint op, uint rlo_dest, uint rlo_src); -static inline void asm_thumb_cmp_rlo_rlo(asm_thumb_t *as, uint rlo_dest, uint rlo_src) { asm_thumb_format_4(as, ASM_THUMB_FORMAT_4_CMP, rlo_dest, rlo_src); } +static inline void asm_thumb_cmp_rlo_rlo(asm_thumb_t *as, uint rlo_dest, uint rlo_src) { + asm_thumb_format_4(as, ASM_THUMB_FORMAT_4_CMP, rlo_dest, rlo_src); +} // FORMAT 5: hi register operations (add, cmp, mov, bx) // For add/cmp/mov, at least one of the args must be a high register @@ -219,21 +234,28 @@ static inline void asm_thumb_bx_reg(asm_thumb_t *as, uint r_src) { #define ASM_THUMB_FORMAT_9_10_ENCODE(op, rlo_dest, rlo_base, offset) \ ((op) | (((offset) << 6) & 0x07c0) | ((rlo_base) << 3) | (rlo_dest)) -static inline void asm_thumb_format_9_10(asm_thumb_t *as, uint op, uint rlo_dest, uint rlo_base, uint offset) - { asm_thumb_op16(as, ASM_THUMB_FORMAT_9_10_ENCODE(op, rlo_dest, rlo_base, offset)); } +static inline void asm_thumb_format_9_10(asm_thumb_t *as, uint op, uint rlo_dest, uint rlo_base, uint offset) { + asm_thumb_op16(as, ASM_THUMB_FORMAT_9_10_ENCODE(op, rlo_dest, rlo_base, offset)); +} -static inline void asm_thumb_str_rlo_rlo_i5(asm_thumb_t *as, uint rlo_src, uint rlo_base, uint word_offset) - { asm_thumb_format_9_10(as, ASM_THUMB_FORMAT_9_STR | ASM_THUMB_FORMAT_9_WORD_TRANSFER, rlo_src, rlo_base, word_offset); } -static inline void asm_thumb_strb_rlo_rlo_i5(asm_thumb_t *as, uint rlo_src, uint rlo_base, uint byte_offset) - { asm_thumb_format_9_10(as, ASM_THUMB_FORMAT_9_STR | ASM_THUMB_FORMAT_9_BYTE_TRANSFER, rlo_src, rlo_base, byte_offset); } -static inline void asm_thumb_strh_rlo_rlo_i5(asm_thumb_t *as, uint rlo_src, uint rlo_base, uint byte_offset) - { asm_thumb_format_9_10(as, ASM_THUMB_FORMAT_10_STRH, rlo_src, rlo_base, byte_offset); } -static inline void asm_thumb_ldr_rlo_rlo_i5(asm_thumb_t *as, uint rlo_dest, uint rlo_base, uint word_offset) - { asm_thumb_format_9_10(as, ASM_THUMB_FORMAT_9_LDR | ASM_THUMB_FORMAT_9_WORD_TRANSFER, rlo_dest, rlo_base, word_offset); } -static inline void asm_thumb_ldrb_rlo_rlo_i5(asm_thumb_t *as, uint rlo_dest, uint rlo_base, uint byte_offset) - { asm_thumb_format_9_10(as, ASM_THUMB_FORMAT_9_LDR | ASM_THUMB_FORMAT_9_BYTE_TRANSFER , rlo_dest, rlo_base, byte_offset); } -static inline void asm_thumb_ldrh_rlo_rlo_i5(asm_thumb_t *as, uint rlo_dest, uint rlo_base, uint byte_offset) - { asm_thumb_format_9_10(as, ASM_THUMB_FORMAT_10_LDRH, rlo_dest, rlo_base, byte_offset); } +static inline void asm_thumb_str_rlo_rlo_i5(asm_thumb_t *as, uint rlo_src, uint rlo_base, uint word_offset) { + asm_thumb_format_9_10(as, ASM_THUMB_FORMAT_9_STR | ASM_THUMB_FORMAT_9_WORD_TRANSFER, rlo_src, rlo_base, word_offset); +} +static inline void asm_thumb_strb_rlo_rlo_i5(asm_thumb_t *as, uint rlo_src, uint rlo_base, uint byte_offset) { + asm_thumb_format_9_10(as, ASM_THUMB_FORMAT_9_STR | ASM_THUMB_FORMAT_9_BYTE_TRANSFER, rlo_src, rlo_base, byte_offset); +} +static inline void asm_thumb_strh_rlo_rlo_i5(asm_thumb_t *as, uint rlo_src, uint rlo_base, uint byte_offset) { + asm_thumb_format_9_10(as, ASM_THUMB_FORMAT_10_STRH, rlo_src, rlo_base, byte_offset); +} +static inline void asm_thumb_ldr_rlo_rlo_i5(asm_thumb_t *as, uint rlo_dest, uint rlo_base, uint word_offset) { + asm_thumb_format_9_10(as, ASM_THUMB_FORMAT_9_LDR | ASM_THUMB_FORMAT_9_WORD_TRANSFER, rlo_dest, rlo_base, word_offset); +} +static inline void asm_thumb_ldrb_rlo_rlo_i5(asm_thumb_t *as, uint rlo_dest, uint rlo_base, uint byte_offset) { + asm_thumb_format_9_10(as, ASM_THUMB_FORMAT_9_LDR | ASM_THUMB_FORMAT_9_BYTE_TRANSFER, rlo_dest, rlo_base, byte_offset); +} +static inline void asm_thumb_ldrh_rlo_rlo_i5(asm_thumb_t *as, uint rlo_dest, uint rlo_base, uint byte_offset) { + asm_thumb_format_9_10(as, ASM_THUMB_FORMAT_10_LDRH, rlo_dest, rlo_base, byte_offset); +} // TODO convert these to above format style diff --git a/py/asmx64.c b/py/asmx64.c index 3609f49d30..b881491121 100644 --- a/py/asmx64.c +++ b/py/asmx64.c @@ -63,15 +63,15 @@ #define OPCODE_SUB_R64_FROM_RM64 (0x29) #define OPCODE_SUB_I32_FROM_RM64 (0x81) /* /5 */ #define OPCODE_SUB_I8_FROM_RM64 (0x83) /* /5 */ -//#define OPCODE_SHL_RM32_BY_I8 (0xc1) /* /4 */ -//#define OPCODE_SHR_RM32_BY_I8 (0xc1) /* /5 */ -//#define OPCODE_SAR_RM32_BY_I8 (0xc1) /* /7 */ +// #define OPCODE_SHL_RM32_BY_I8 (0xc1) /* /4 */ +// #define OPCODE_SHR_RM32_BY_I8 (0xc1) /* /5 */ +// #define OPCODE_SAR_RM32_BY_I8 (0xc1) /* /7 */ #define OPCODE_SHL_RM64_CL (0xd3) /* /4 */ #define OPCODE_SAR_RM64_CL (0xd3) /* /7 */ -//#define OPCODE_CMP_I32_WITH_RM32 (0x81) /* /7 */ -//#define OPCODE_CMP_I8_WITH_RM32 (0x83) /* /7 */ +// #define OPCODE_CMP_I32_WITH_RM32 (0x81) /* /7 */ +// #define OPCODE_CMP_I8_WITH_RM32 (0x83) /* /7 */ #define OPCODE_CMP_R64_WITH_RM64 (0x39) /* /r */ -//#define OPCODE_CMP_RM32_WITH_R32 (0x3b) +// #define OPCODE_CMP_RM32_WITH_R32 (0x3b) #define OPCODE_TEST_R8_WITH_RM8 (0x84) /* /r */ #define OPCODE_TEST_R64_WITH_RM64 (0x85) /* /r */ #define OPCODE_JMP_REL8 (0xeb) @@ -123,14 +123,14 @@ static inline byte *asm_x64_get_cur_to_write_bytes(asm_x64_t *as, int n) { } STATIC void asm_x64_write_byte_1(asm_x64_t *as, byte b1) { - byte* c = asm_x64_get_cur_to_write_bytes(as, 1); + byte *c = asm_x64_get_cur_to_write_bytes(as, 1); if (c != NULL) { c[0] = b1; } } STATIC void asm_x64_write_byte_2(asm_x64_t *as, byte b1, byte b2) { - byte* c = asm_x64_get_cur_to_write_bytes(as, 2); + byte *c = asm_x64_get_cur_to_write_bytes(as, 2); if (c != NULL) { c[0] = b1; c[1] = b2; @@ -138,7 +138,7 @@ STATIC void asm_x64_write_byte_2(asm_x64_t *as, byte b1, byte b2) { } STATIC void asm_x64_write_byte_3(asm_x64_t *as, byte b1, byte b2, byte b3) { - byte* c = asm_x64_get_cur_to_write_bytes(as, 3); + byte *c = asm_x64_get_cur_to_write_bytes(as, 3); if (c != NULL) { c[0] = b1; c[1] = b2; @@ -147,7 +147,7 @@ STATIC void asm_x64_write_byte_3(asm_x64_t *as, byte b1, byte b2, byte b3) { } STATIC void asm_x64_write_word32(asm_x64_t *as, int w32) { - byte* c = asm_x64_get_cur_to_write_bytes(as, 4); + byte *c = asm_x64_get_cur_to_write_bytes(as, 4); if (c != NULL) { c[0] = IMM32_L0(w32); c[1] = IMM32_L1(w32); @@ -157,7 +157,7 @@ STATIC void asm_x64_write_word32(asm_x64_t *as, int w32) { } STATIC void asm_x64_write_word64(asm_x64_t *as, int64_t w64) { - byte* c = asm_x64_get_cur_to_write_bytes(as, 8); + byte *c = asm_x64_get_cur_to_write_bytes(as, 8); if (c != NULL) { c[0] = IMM32_L0(w64); c[1] = IMM32_L1(w64); @@ -376,11 +376,11 @@ void asm_x64_xor_r64_r64(asm_x64_t *as, int dest_r64, int src_r64) { asm_x64_generic_r64_r64(as, dest_r64, src_r64, OPCODE_XOR_R64_TO_RM64); } -void asm_x64_shl_r64_cl(asm_x64_t* as, int dest_r64) { +void asm_x64_shl_r64_cl(asm_x64_t *as, int dest_r64) { asm_x64_generic_r64_r64(as, dest_r64, 4, OPCODE_SHL_RM64_CL); } -void asm_x64_sar_r64_cl(asm_x64_t* as, int dest_r64) { +void asm_x64_sar_r64_cl(asm_x64_t *as, int dest_r64) { asm_x64_generic_r64_r64(as, dest_r64, 7, OPCODE_SAR_RM64_CL); } @@ -498,7 +498,7 @@ void asm_x64_jmp_label(asm_x64_t *as, mp_uint_t label) { } } else { // is a forwards jump, so need to assume it's large - large_jump: + large_jump: rel -= 5; asm_x64_write_byte_1(as, OPCODE_JMP_REL32); asm_x64_write_word32(as, rel); @@ -520,7 +520,7 @@ void asm_x64_jcc_label(asm_x64_t *as, int jcc_type, mp_uint_t label) { } } else { // is a forwards jump, so need to assume it's large - large_jump: + large_jump: rel -= 6; asm_x64_write_byte_2(as, OPCODE_JCC_REL32_A, OPCODE_JCC_REL32_B | jcc_type); asm_x64_write_word32(as, rel); diff --git a/py/asmx64.h b/py/asmx64.h index 1c8755a84c..e2f20f2e1b 100644 --- a/py/asmx64.h +++ b/py/asmx64.h @@ -79,11 +79,11 @@ static inline void asm_x64_end_pass(asm_x64_t *as) { (void)as; } -void asm_x64_nop(asm_x64_t* as); -void asm_x64_push_r64(asm_x64_t* as, int src_r64); -void asm_x64_pop_r64(asm_x64_t* as, int dest_r64); -void asm_x64_mov_r64_r64(asm_x64_t* as, int dest_r64, int src_r64); -void asm_x64_mov_i64_to_r64(asm_x64_t* as, int64_t src_i64, int dest_r64); +void asm_x64_nop(asm_x64_t *as); +void asm_x64_push_r64(asm_x64_t *as, int src_r64); +void asm_x64_pop_r64(asm_x64_t *as, int dest_r64); +void asm_x64_mov_r64_r64(asm_x64_t *as, int dest_r64, int src_r64); +void asm_x64_mov_i64_to_r64(asm_x64_t *as, int64_t src_i64, int dest_r64); void asm_x64_mov_i64_to_r64_optimised(asm_x64_t *as, int64_t src_i64, int dest_r64); void asm_x64_mov_r8_to_mem8(asm_x64_t *as, int src_r64, int dest_r64, int dest_disp); void asm_x64_mov_r16_to_mem16(asm_x64_t *as, int src_r64, int dest_r64, int dest_disp); @@ -96,25 +96,25 @@ void asm_x64_mov_mem64_to_r64(asm_x64_t *as, int src_r64, int src_disp, int dest void asm_x64_and_r64_r64(asm_x64_t *as, int dest_r64, int src_r64); void asm_x64_or_r64_r64(asm_x64_t *as, int dest_r64, int src_r64); void asm_x64_xor_r64_r64(asm_x64_t *as, int dest_r64, int src_r64); -void asm_x64_shl_r64_cl(asm_x64_t* as, int dest_r64); -void asm_x64_sar_r64_cl(asm_x64_t* as, int dest_r64); -void asm_x64_add_r64_r64(asm_x64_t* as, int dest_r64, int src_r64); -void asm_x64_sub_r64_r64(asm_x64_t* as, int dest_r64, int src_r64); -void asm_x64_mul_r64_r64(asm_x64_t* as, int dest_r64, int src_r64); -void asm_x64_cmp_r64_with_r64(asm_x64_t* as, int src_r64_a, int src_r64_b); -void asm_x64_test_r8_with_r8(asm_x64_t* as, int src_r64_a, int src_r64_b); +void asm_x64_shl_r64_cl(asm_x64_t *as, int dest_r64); +void asm_x64_sar_r64_cl(asm_x64_t *as, int dest_r64); +void asm_x64_add_r64_r64(asm_x64_t *as, int dest_r64, int src_r64); +void asm_x64_sub_r64_r64(asm_x64_t *as, int dest_r64, int src_r64); +void asm_x64_mul_r64_r64(asm_x64_t *as, int dest_r64, int src_r64); +void asm_x64_cmp_r64_with_r64(asm_x64_t *as, int src_r64_a, int src_r64_b); +void asm_x64_test_r8_with_r8(asm_x64_t *as, int src_r64_a, int src_r64_b); void asm_x64_test_r64_with_r64(asm_x64_t *as, int src_r64_a, int src_r64_b); -void asm_x64_setcc_r8(asm_x64_t* as, int jcc_type, int dest_r8); +void asm_x64_setcc_r8(asm_x64_t *as, int jcc_type, int dest_r8); void asm_x64_jmp_reg(asm_x64_t *as, int src_r64); -void asm_x64_jmp_label(asm_x64_t* as, mp_uint_t label); -void asm_x64_jcc_label(asm_x64_t* as, int jcc_type, mp_uint_t label); -void asm_x64_entry(asm_x64_t* as, int num_locals); -void asm_x64_exit(asm_x64_t* as); -void asm_x64_mov_local_to_r64(asm_x64_t* as, int src_local_num, int dest_r64); -void asm_x64_mov_r64_to_local(asm_x64_t* as, int src_r64, int dest_local_num); -void asm_x64_mov_local_addr_to_r64(asm_x64_t* as, int local_num, int dest_r64); +void asm_x64_jmp_label(asm_x64_t *as, mp_uint_t label); +void asm_x64_jcc_label(asm_x64_t *as, int jcc_type, mp_uint_t label); +void asm_x64_entry(asm_x64_t *as, int num_locals); +void asm_x64_exit(asm_x64_t *as); +void asm_x64_mov_local_to_r64(asm_x64_t *as, int src_local_num, int dest_r64); +void asm_x64_mov_r64_to_local(asm_x64_t *as, int src_r64, int dest_local_num); +void asm_x64_mov_local_addr_to_r64(asm_x64_t *as, int local_num, int dest_r64); void asm_x64_mov_reg_pcrel(asm_x64_t *as, int dest_r64, mp_uint_t label); -void asm_x64_call_ind(asm_x64_t* as, size_t fun_id, int temp_r32); +void asm_x64_call_ind(asm_x64_t *as, size_t fun_id, int temp_r32); // Holds a pointer to mp_fun_table #define ASM_X64_REG_FUN_TABLE ASM_X64_REG_RBP diff --git a/py/asmx86.c b/py/asmx86.c index 8ce576ac89..4577ea28ec 100644 --- a/py/asmx86.c +++ b/py/asmx86.c @@ -41,13 +41,13 @@ #define OPCODE_NOP (0x90) #define OPCODE_PUSH_R32 (0x50) -//#define OPCODE_PUSH_I32 (0x68) -//#define OPCODE_PUSH_M32 (0xff) /* /6 */ +// #define OPCODE_PUSH_I32 (0x68) +// #define OPCODE_PUSH_M32 (0xff) /* /6 */ #define OPCODE_POP_R32 (0x58) #define OPCODE_RET (0xc3) -//#define OPCODE_MOV_I8_TO_R8 (0xb0) /* +rb */ +// #define OPCODE_MOV_I8_TO_R8 (0xb0) /* +rb */ #define OPCODE_MOV_I32_TO_R32 (0xb8) -//#define OPCODE_MOV_I32_TO_RM32 (0xc7) +// #define OPCODE_MOV_I32_TO_RM32 (0xc7) #define OPCODE_MOV_R8_TO_RM8 (0x88) /* /r */ #define OPCODE_MOV_R32_TO_RM32 (0x89) /* /r */ #define OPCODE_MOV_RM32_TO_R32 (0x8b) /* /r */ @@ -63,15 +63,15 @@ #define OPCODE_SUB_R32_FROM_RM32 (0x29) #define OPCODE_SUB_I32_FROM_RM32 (0x81) /* /5 */ #define OPCODE_SUB_I8_FROM_RM32 (0x83) /* /5 */ -//#define OPCODE_SHL_RM32_BY_I8 (0xc1) /* /4 */ -//#define OPCODE_SHR_RM32_BY_I8 (0xc1) /* /5 */ -//#define OPCODE_SAR_RM32_BY_I8 (0xc1) /* /7 */ +// #define OPCODE_SHL_RM32_BY_I8 (0xc1) /* /4 */ +// #define OPCODE_SHR_RM32_BY_I8 (0xc1) /* /5 */ +// #define OPCODE_SAR_RM32_BY_I8 (0xc1) /* /7 */ #define OPCODE_SHL_RM32_CL (0xd3) /* /4 */ #define OPCODE_SAR_RM32_CL (0xd3) /* /7 */ -//#define OPCODE_CMP_I32_WITH_RM32 (0x81) /* /7 */ -//#define OPCODE_CMP_I8_WITH_RM32 (0x83) /* /7 */ +// #define OPCODE_CMP_I32_WITH_RM32 (0x81) /* /7 */ +// #define OPCODE_CMP_I8_WITH_RM32 (0x83) /* /7 */ #define OPCODE_CMP_R32_WITH_RM32 (0x39) -//#define OPCODE_CMP_RM32_WITH_R32 (0x3b) +// #define OPCODE_CMP_RM32_WITH_R32 (0x3b) #define OPCODE_TEST_R8_WITH_RM8 (0x84) /* /r */ #define OPCODE_TEST_R32_WITH_RM32 (0x85) /* /r */ #define OPCODE_JMP_REL8 (0xeb) @@ -103,14 +103,14 @@ #define SIGNED_FIT8(x) (((x) & 0xffffff80) == 0) || (((x) & 0xffffff80) == 0xffffff80) STATIC void asm_x86_write_byte_1(asm_x86_t *as, byte b1) { - byte* c = mp_asm_base_get_cur_to_write_bytes(&as->base, 1); + byte *c = mp_asm_base_get_cur_to_write_bytes(&as->base, 1); if (c != NULL) { c[0] = b1; } } STATIC void asm_x86_write_byte_2(asm_x86_t *as, byte b1, byte b2) { - byte* c = mp_asm_base_get_cur_to_write_bytes(&as->base, 2); + byte *c = mp_asm_base_get_cur_to_write_bytes(&as->base, 2); if (c != NULL) { c[0] = b1; c[1] = b2; @@ -118,7 +118,7 @@ STATIC void asm_x86_write_byte_2(asm_x86_t *as, byte b1, byte b2) { } STATIC void asm_x86_write_byte_3(asm_x86_t *as, byte b1, byte b2, byte b3) { - byte* c = mp_asm_base_get_cur_to_write_bytes(&as->base, 3); + byte *c = mp_asm_base_get_cur_to_write_bytes(&as->base, 3); if (c != NULL) { c[0] = b1; c[1] = b2; @@ -127,7 +127,7 @@ STATIC void asm_x86_write_byte_3(asm_x86_t *as, byte b1, byte b2, byte b3) { } STATIC void asm_x86_write_word32(asm_x86_t *as, int w32) { - byte* c = mp_asm_base_get_cur_to_write_bytes(&as->base, 4); + byte *c = mp_asm_base_get_cur_to_write_bytes(&as->base, 4); if (c != NULL) { c[0] = IMM32_L0(w32); c[1] = IMM32_L1(w32); @@ -253,11 +253,11 @@ void asm_x86_xor_r32_r32(asm_x86_t *as, int dest_r32, int src_r32) { asm_x86_generic_r32_r32(as, dest_r32, src_r32, OPCODE_XOR_R32_TO_RM32); } -void asm_x86_shl_r32_cl(asm_x86_t* as, int dest_r32) { +void asm_x86_shl_r32_cl(asm_x86_t *as, int dest_r32) { asm_x86_generic_r32_r32(as, dest_r32, 4, OPCODE_SHL_RM32_CL); } -void asm_x86_sar_r32_cl(asm_x86_t* as, int dest_r32) { +void asm_x86_sar_r32_cl(asm_x86_t *as, int dest_r32) { asm_x86_generic_r32_r32(as, dest_r32, 7, OPCODE_SAR_RM32_CL); } @@ -366,7 +366,7 @@ void asm_x86_jmp_label(asm_x86_t *as, mp_uint_t label) { } } else { // is a forwards jump, so need to assume it's large - large_jump: + large_jump: rel -= 5; asm_x86_write_byte_1(as, OPCODE_JMP_REL32); asm_x86_write_word32(as, rel); @@ -388,7 +388,7 @@ void asm_x86_jcc_label(asm_x86_t *as, mp_uint_t jcc_type, mp_uint_t label) { } } else { // is a forwards jump, so need to assume it's large - large_jump: + large_jump: rel -= 6; asm_x86_write_byte_2(as, OPCODE_JCC_REL32_A, OPCODE_JCC_REL32_B | jcc_type); asm_x86_write_word32(as, rel); @@ -486,8 +486,7 @@ void asm_x86_push_local(asm_x86_t *as, int local_num) { asm_x86_push_disp(as, ASM_X86_REG_ESP, asm_x86_local_offset_from_esp(as, local_num)); } -void asm_x86_push_local_addr(asm_x86_t *as, int local_num, int temp_r32) -{ +void asm_x86_push_local_addr(asm_x86_t *as, int local_num, int temp_r32) { asm_x86_mov_r32_r32(as, temp_r32, ASM_X86_REG_ESP); asm_x86_add_i32_to_r32(as, asm_x86_local_offset_from_esp(as, local_num), temp_r32); asm_x86_push_r32(as, temp_r32); diff --git a/py/asmx86.h b/py/asmx86.h index 82a8629ddf..63cb85e5fd 100644 --- a/py/asmx86.h +++ b/py/asmx86.h @@ -82,7 +82,7 @@ static inline void asm_x86_end_pass(asm_x86_t *as) { (void)as; } -void asm_x86_mov_r32_r32(asm_x86_t* as, int dest_r32, int src_r32); +void asm_x86_mov_r32_r32(asm_x86_t *as, int dest_r32, int src_r32); void asm_x86_mov_i32_to_r32(asm_x86_t *as, int32_t src_i32, int dest_r32); void asm_x86_mov_r8_to_mem8(asm_x86_t *as, int src_r32, int dest_r32, int dest_disp); void asm_x86_mov_r16_to_mem16(asm_x86_t *as, int src_r32, int dest_r32, int dest_disp); @@ -93,26 +93,26 @@ void asm_x86_mov_mem32_to_r32(asm_x86_t *as, int src_r32, int src_disp, int dest void asm_x86_and_r32_r32(asm_x86_t *as, int dest_r32, int src_r32); void asm_x86_or_r32_r32(asm_x86_t *as, int dest_r32, int src_r32); void asm_x86_xor_r32_r32(asm_x86_t *as, int dest_r32, int src_r32); -void asm_x86_shl_r32_cl(asm_x86_t* as, int dest_r32); -void asm_x86_sar_r32_cl(asm_x86_t* as, int dest_r32); -void asm_x86_add_r32_r32(asm_x86_t* as, int dest_r32, int src_r32); -void asm_x86_sub_r32_r32(asm_x86_t* as, int dest_r32, int src_r32); -void asm_x86_mul_r32_r32(asm_x86_t* as, int dest_r32, int src_r32); -void asm_x86_cmp_r32_with_r32(asm_x86_t* as, int src_r32_a, int src_r32_b); -void asm_x86_test_r8_with_r8(asm_x86_t* as, int src_r32_a, int src_r32_b); -void asm_x86_test_r32_with_r32(asm_x86_t* as, int src_r32_a, int src_r32_b); -void asm_x86_setcc_r8(asm_x86_t* as, mp_uint_t jcc_type, int dest_r8); +void asm_x86_shl_r32_cl(asm_x86_t *as, int dest_r32); +void asm_x86_sar_r32_cl(asm_x86_t *as, int dest_r32); +void asm_x86_add_r32_r32(asm_x86_t *as, int dest_r32, int src_r32); +void asm_x86_sub_r32_r32(asm_x86_t *as, int dest_r32, int src_r32); +void asm_x86_mul_r32_r32(asm_x86_t *as, int dest_r32, int src_r32); +void asm_x86_cmp_r32_with_r32(asm_x86_t *as, int src_r32_a, int src_r32_b); +void asm_x86_test_r8_with_r8(asm_x86_t *as, int src_r32_a, int src_r32_b); +void asm_x86_test_r32_with_r32(asm_x86_t *as, int src_r32_a, int src_r32_b); +void asm_x86_setcc_r8(asm_x86_t *as, mp_uint_t jcc_type, int dest_r8); void asm_x86_jmp_reg(asm_x86_t *as, int src_r86); -void asm_x86_jmp_label(asm_x86_t* as, mp_uint_t label); -void asm_x86_jcc_label(asm_x86_t* as, mp_uint_t jcc_type, mp_uint_t label); -void asm_x86_entry(asm_x86_t* as, int num_locals); -void asm_x86_exit(asm_x86_t* as); +void asm_x86_jmp_label(asm_x86_t *as, mp_uint_t label); +void asm_x86_jcc_label(asm_x86_t *as, mp_uint_t jcc_type, mp_uint_t label); +void asm_x86_entry(asm_x86_t *as, int num_locals); +void asm_x86_exit(asm_x86_t *as); void asm_x86_mov_arg_to_r32(asm_x86_t *as, int src_arg_num, int dest_r32); -void asm_x86_mov_local_to_r32(asm_x86_t* as, int src_local_num, int dest_r32); -void asm_x86_mov_r32_to_local(asm_x86_t* as, int src_r32, int dest_local_num); -void asm_x86_mov_local_addr_to_r32(asm_x86_t* as, int local_num, int dest_r32); +void asm_x86_mov_local_to_r32(asm_x86_t *as, int src_local_num, int dest_r32); +void asm_x86_mov_r32_to_local(asm_x86_t *as, int src_r32, int dest_local_num); +void asm_x86_mov_local_addr_to_r32(asm_x86_t *as, int local_num, int dest_r32); void asm_x86_mov_reg_pcrel(asm_x86_t *as, int dest_r64, mp_uint_t label); -void asm_x86_call_ind(asm_x86_t* as, size_t fun_id, mp_uint_t n_args, int temp_r32); +void asm_x86_call_ind(asm_x86_t *as, size_t fun_id, mp_uint_t n_args, int temp_r32); // Holds a pointer to mp_fun_table #define ASM_X86_REG_FUN_TABLE ASM_X86_REG_EBP diff --git a/py/asmxtensa.c b/py/asmxtensa.c index 8da56ffe30..00ba9248f8 100644 --- a/py/asmxtensa.c +++ b/py/asmxtensa.c @@ -66,7 +66,7 @@ void asm_xtensa_entry(asm_xtensa_t *as, int num_locals) { // jump over the constants asm_xtensa_op_j(as, as->num_const * WORD_SIZE + 4 - 4); mp_asm_base_get_cur_to_write_bytes(&as->base, 1); // padding/alignment byte - as->const_table = (uint32_t*)mp_asm_base_get_cur_to_write_bytes(&as->base, as->num_const * 4); + as->const_table = (uint32_t *)mp_asm_base_get_cur_to_write_bytes(&as->base, as->num_const * 4); // adjust the stack-pointer to store a0, a12, a13, a14, a15 and locals, 16-byte aligned as->stack_adjust = (((NUM_REGS_SAVED + num_locals) * WORD_SIZE) + 15) & ~15; @@ -161,7 +161,7 @@ void asm_xtensa_mov_reg_i32(asm_xtensa_t *as, uint reg_dest, uint32_t i32) { asm_xtensa_op_movi(as, reg_dest, i32); } else { // load the constant - uint32_t const_table_offset = (uint8_t*)as->const_table - as->base.code_base; + uint32_t const_table_offset = (uint8_t *)as->const_table - as->base.code_base; asm_xtensa_op_l32r(as, reg_dest, as->base.code_offset, const_table_offset + as->cur_const * WORD_SIZE); // store the constant in the table if (as->const_table != NULL) { diff --git a/py/bc.c b/py/bc.c index 1d6e4322b2..8d0398705a 100644 --- a/py/bc.c +++ b/py/bc.c @@ -71,21 +71,21 @@ const byte *mp_decode_uint_skip(const byte *ptr) { } STATIC NORETURN void fun_pos_args_mismatch(mp_obj_fun_bc_t *f, size_t expected, size_t given) { -#if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE + #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE // generic message, used also for other argument issues (void)f; (void)expected; (void)given; mp_arg_error_terse_mismatch(); -#elif MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_NORMAL + #elif MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_NORMAL (void)f; nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, "function takes %d positional arguments but %d were given", expected, given)); -#elif MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_DETAILED + #elif MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_DETAILED nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, "%q() takes %d positional arguments but %d were given", mp_obj_fun_get_name(MP_OBJ_FROM_PTR(f)), expected, given)); -#endif + #endif } #if DEBUG_PRINT @@ -128,7 +128,7 @@ void mp_setup_code_state(mp_code_state_t *code_state, size_t n_args, size_t n_kw size_t n_def_pos_args = *code_state->ip++; code_state->sp = &code_state->state[0] - 1; - code_state->exc_sp = (mp_exc_stack_t*)(code_state->state + n_state) - 1; + code_state->exc_sp = (mp_exc_stack_t *)(code_state->state + n_state) - 1; // zero out the local stack to begin with memset(code_state->state, 0, n_state * sizeof(*code_state->state)); @@ -185,7 +185,7 @@ void mp_setup_code_state(mp_code_state_t *code_state, size_t n_args, size_t n_kw } // get pointer to arg_names array - const mp_obj_t *arg_names = (const mp_obj_t*)self->const_table; + const mp_obj_t *arg_names = (const mp_obj_t *)self->const_table; for (size_t i = 0; i < n_kw; i++) { // the keys in kwargs are expected to be qstr objects @@ -210,7 +210,7 @@ void mp_setup_code_state(mp_code_state_t *code_state, size_t n_args, size_t n_kw } } mp_obj_dict_store(dict, kwargs[2 * i], kwargs[2 * i + 1]); -continue2:; + continue2:; } DEBUG_printf("Args with kws flattened: "); @@ -242,7 +242,7 @@ continue2:; if (code_state->state[n_state - 1 - n_pos_args - i] == MP_OBJ_NULL) { mp_map_elem_t *elem = NULL; if ((scope_flags & MP_SCOPE_FLAG_DEFKWARGS) != 0) { - elem = mp_map_lookup(&((mp_obj_dict_t*)MP_OBJ_TO_PTR(self->extra_args[n_def_pos_args]))->map, arg_names[n_pos_args + i], MP_MAP_LOOKUP); + elem = mp_map_lookup(&((mp_obj_dict_t *)MP_OBJ_TO_PTR(self->extra_args[n_def_pos_args]))->map, arg_names[n_pos_args + i], MP_MAP_LOOKUP); } if (elem != NULL) { code_state->state[n_state - 1 - n_pos_args - i] = elem->value; @@ -400,7 +400,7 @@ uint mp_opcode_format(const byte *ip, size_t *opcode_size) { *ip == MP_BC_RAISE_VARARGS || *ip == MP_BC_MAKE_CLOSURE || *ip == MP_BC_MAKE_CLOSURE_DEFARGS - ); + ); ip += 1; if (f == MP_OPCODE_VAR_UINT) { while ((*ip++ & 0x80) != 0) { diff --git a/py/bc.h b/py/bc.h index ebfdeaac1d..fb01d65ff1 100644 --- a/py/bc.h +++ b/py/bc.h @@ -86,7 +86,7 @@ typedef struct _mp_code_state_t { // Variable-length mp_obj_t state[0]; // Variable-length, never accessed by name, only as (void*)(state + n_state) - //mp_exc_stack_t exc_state[0]; + // mp_exc_stack_t exc_state[0]; } mp_code_state_t; mp_uint_t mp_decode_uint(const byte **ptr); @@ -102,10 +102,10 @@ const byte *mp_bytecode_print_str(const byte *ip); #define mp_bytecode_print_inst(code, const_table) mp_bytecode_print2(code, 1, const_table) // Helper macros to access pointer with least significant bits holding flags -#define MP_TAGPTR_PTR(x) ((void*)((uintptr_t)(x) & ~((uintptr_t)3))) +#define MP_TAGPTR_PTR(x) ((void *)((uintptr_t)(x) & ~((uintptr_t)3))) #define MP_TAGPTR_TAG0(x) ((uintptr_t)(x) & 1) #define MP_TAGPTR_TAG1(x) ((uintptr_t)(x) & 2) -#define MP_TAGPTR_MAKE(ptr, tag) ((void*)((uintptr_t)(ptr) | (tag))) +#define MP_TAGPTR_MAKE(ptr, tag) ((void *)((uintptr_t)(ptr) | (tag))) #if MICROPY_PERSISTENT_CODE_LOAD || MICROPY_PERSISTENT_CODE_SAVE diff --git a/py/binary.c b/py/binary.c index f509ff0108..5f0ae77bc8 100644 --- a/py/binary.c +++ b/py/binary.c @@ -45,24 +45,40 @@ size_t mp_binary_get_size(char struct_type, char val_type, mp_uint_t *palign) { size_t size = 0; int align = 1; switch (struct_type) { - case '<': case '>': + case '<': + case '>': switch (val_type) { - case 'b': case 'B': - size = 1; break; - case 'h': case 'H': - size = 2; break; - case 'i': case 'I': - size = 4; break; - case 'l': case 'L': - size = 4; break; - case 'q': case 'Q': - size = 8; break; - case 'P': case 'O': case 'S': - size = sizeof(void*); break; + case 'b': + case 'B': + size = 1; + break; + case 'h': + case 'H': + size = 2; + break; + case 'i': + case 'I': + size = 4; + break; + case 'l': + case 'L': + size = 4; + break; + case 'q': + case 'Q': + size = 8; + break; + case 'P': + case 'O': + case 'S': + size = sizeof(void *); + break; case 'f': - size = sizeof(float); break; + size = sizeof(float); + break; case 'd': - size = sizeof(double); break; + size = sizeof(double); + break; } break; case '@': { @@ -75,29 +91,44 @@ size_t mp_binary_get_size(char struct_type, char val_type, mp_uint_t *palign) { // particular (or any) ABI. switch (val_type) { case BYTEARRAY_TYPECODE: - case 'b': case 'B': - align = size = 1; break; - case 'h': case 'H': + case 'b': + case 'B': + align = size = 1; + break; + case 'h': + case 'H': align = alignof(short); - size = sizeof(short); break; - case 'i': case 'I': + size = sizeof(short); + break; + case 'i': + case 'I': align = alignof(int); - size = sizeof(int); break; - case 'l': case 'L': + size = sizeof(int); + break; + case 'l': + case 'L': align = alignof(long); - size = sizeof(long); break; - case 'q': case 'Q': + size = sizeof(long); + break; + case 'q': + case 'Q': align = alignof(long long); - size = sizeof(long long); break; - case 'P': case 'O': case 'S': - align = alignof(void*); - size = sizeof(void*); break; + size = sizeof(long long); + break; + case 'P': + case 'O': + case 'S': + align = alignof(void *); + size = sizeof(void *); + break; case 'f': align = alignof(float); - size = sizeof(float); break; + size = sizeof(float); + break; case 'd': align = alignof(double); - size = sizeof(double); break; + size = sizeof(double); + break; } } } @@ -116,44 +147,44 @@ mp_obj_t mp_binary_get_val_array(char typecode, void *p, mp_uint_t index) { mp_int_t val = 0; switch (typecode) { case 'b': - val = ((signed char*)p)[index]; + val = ((signed char *)p)[index]; break; case BYTEARRAY_TYPECODE: case 'B': - val = ((unsigned char*)p)[index]; + val = ((unsigned char *)p)[index]; break; case 'h': - val = ((short*)p)[index]; + val = ((short *)p)[index]; break; case 'H': - val = ((unsigned short*)p)[index]; + val = ((unsigned short *)p)[index]; break; case 'i': - return mp_obj_new_int(((int*)p)[index]); + return mp_obj_new_int(((int *)p)[index]); case 'I': - return mp_obj_new_int_from_uint(((unsigned int*)p)[index]); + return mp_obj_new_int_from_uint(((unsigned int *)p)[index]); case 'l': - return mp_obj_new_int(((long*)p)[index]); + return mp_obj_new_int(((long *)p)[index]); case 'L': - return mp_obj_new_int_from_uint(((unsigned long*)p)[index]); + return mp_obj_new_int_from_uint(((unsigned long *)p)[index]); #if MICROPY_LONGINT_IMPL != MICROPY_LONGINT_IMPL_NONE case 'q': - return mp_obj_new_int_from_ll(((long long*)p)[index]); + return mp_obj_new_int_from_ll(((long long *)p)[index]); case 'Q': - return mp_obj_new_int_from_ull(((unsigned long long*)p)[index]); + return mp_obj_new_int_from_ull(((unsigned long long *)p)[index]); #endif -#if MICROPY_PY_BUILTINS_FLOAT + #if MICROPY_PY_BUILTINS_FLOAT case 'f': - return mp_obj_new_float(((float*)p)[index]); + return mp_obj_new_float(((float *)p)[index]); case 'd': - return mp_obj_new_float(((double*)p)[index]); -#endif + return mp_obj_new_float(((double *)p)[index]); + #endif // Extension to CPython: array of objects case 'O': - return ((mp_obj_t*)p)[index]; + return ((mp_obj_t *)p)[index]; // Extension to CPython: array of pointers case 'P': - return mp_obj_new_int((mp_int_t)(uintptr_t)((void**)p)[index]); + return mp_obj_new_int((mp_int_t)(uintptr_t)((void **)p)[index]); } return MP_OBJ_NEW_SMALL_INT(val); } @@ -191,7 +222,7 @@ mp_obj_t mp_binary_get_val(char struct_type, char val_type, byte **ptr) { size_t size = mp_binary_get_size(struct_type, val_type, &align); if (struct_type == '@') { // Make pointer aligned - p = (byte*)MP_ALIGN(p, (size_t)align); + p = (byte *)MP_ALIGN(p, (size_t)align); #if MP_ENDIANNESS_LITTLE struct_type = '<'; #else @@ -205,16 +236,20 @@ mp_obj_t mp_binary_get_val(char struct_type, char val_type, byte **ptr) { if (val_type == 'O') { return (mp_obj_t)(mp_uint_t)val; } else if (val_type == 'S') { - const char *s_val = (const char*)(uintptr_t)(mp_uint_t)val; + const char *s_val = (const char *)(uintptr_t)(mp_uint_t)val; return mp_obj_new_str(s_val, strlen(s_val)); -#if MICROPY_PY_BUILTINS_FLOAT + #if MICROPY_PY_BUILTINS_FLOAT } else if (val_type == 'f') { - union { uint32_t i; float f; } fpu = {val}; + union { uint32_t i; + float f; + } fpu = {val}; return mp_obj_new_float(fpu.f); } else if (val_type == 'd') { - union { uint64_t i; double f; } fpu = {val}; + union { uint64_t i; + double f; + } fpu = {val}; return mp_obj_new_float(fpu.f); -#endif + #endif } else if (is_signed(val_type)) { if ((long long)MP_SMALL_INT_MIN <= val && val <= (long long)MP_SMALL_INT_MAX) { return mp_obj_new_int((mp_int_t)val); @@ -235,13 +270,13 @@ void mp_binary_set_int(mp_uint_t val_sz, bool big_endian, byte *dest, mp_uint_t memcpy(dest, &val, val_sz); } else if (MP_ENDIANNESS_BIG && big_endian) { // only copy the least-significant val_sz bytes - memcpy(dest, (byte*)&val + sizeof(mp_uint_t) - val_sz, val_sz); + memcpy(dest, (byte *)&val + sizeof(mp_uint_t) - val_sz, val_sz); } else { const byte *src; if (MP_ENDIANNESS_LITTLE) { - src = (const byte*)&val + val_sz; + src = (const byte *)&val + val_sz; } else { - src = (const byte*)&val + sizeof(mp_uint_t); + src = (const byte *)&val + sizeof(mp_uint_t); } while (val_sz--) { *dest++ = *--src; @@ -256,7 +291,7 @@ void mp_binary_set_val(char struct_type, char val_type, mp_obj_t val_in, byte ** size_t size = mp_binary_get_size(struct_type, val_type, &align); if (struct_type == '@') { // Make pointer aligned - p = (byte*)MP_ALIGN(p, (size_t)align); + p = (byte *)MP_ALIGN(p, (size_t)align); if (MP_ENDIANNESS_LITTLE) { struct_type = '<'; } else { @@ -270,15 +305,20 @@ void mp_binary_set_val(char struct_type, char val_type, mp_obj_t val_in, byte ** case 'O': val = (mp_uint_t)val_in; break; -#if MICROPY_PY_BUILTINS_FLOAT + #if MICROPY_PY_BUILTINS_FLOAT case 'f': { - union { uint32_t i; float f; } fp_sp; + union { uint32_t i; + float f; + } fp_sp; fp_sp.f = mp_obj_get_float(val_in); val = fp_sp.i; break; } case 'd': { - union { uint64_t i64; uint32_t i32[2]; double f; } fp_dp; + union { uint64_t i64; + uint32_t i32[2]; + double f; + } fp_dp; fp_dp.f = mp_obj_get_float(val_in); if (BYTES_PER_WORD == 8) { val = fp_dp.i64; @@ -290,7 +330,7 @@ void mp_binary_set_val(char struct_type, char val_type, mp_obj_t val_in, byte ** } break; } -#endif + #endif default: #if MICROPY_LONGINT_IMPL != MICROPY_LONGINT_IMPL_NONE if (MP_OBJ_IS_TYPE(val_in, &mp_type_int)) { @@ -316,24 +356,24 @@ void mp_binary_set_val(char struct_type, char val_type, mp_obj_t val_in, byte ** void mp_binary_set_val_array(char typecode, void *p, mp_uint_t index, mp_obj_t val_in) { switch (typecode) { -#if MICROPY_PY_BUILTINS_FLOAT + #if MICROPY_PY_BUILTINS_FLOAT case 'f': - ((float*)p)[index] = mp_obj_get_float(val_in); + ((float *)p)[index] = mp_obj_get_float(val_in); break; case 'd': - ((double*)p)[index] = mp_obj_get_float(val_in); + ((double *)p)[index] = mp_obj_get_float(val_in); break; -#endif + #endif // Extension to CPython: array of objects case 'O': - ((mp_obj_t*)p)[index] = val_in; + ((mp_obj_t *)p)[index] = val_in; break; default: #if MICROPY_LONGINT_IMPL != MICROPY_LONGINT_IMPL_NONE if (MP_OBJ_IS_TYPE(val_in, &mp_type_int)) { size_t size = mp_binary_get_size('@', typecode, NULL); mp_obj_int_to_bytes_impl(val_in, MP_ENDIANNESS_BIG, - size, (uint8_t*)p + index * size); + size, (uint8_t *)p + index * size); return; } #endif @@ -344,49 +384,49 @@ void mp_binary_set_val_array(char typecode, void *p, mp_uint_t index, mp_obj_t v void mp_binary_set_val_array_from_int(char typecode, void *p, mp_uint_t index, mp_int_t val) { switch (typecode) { case 'b': - ((signed char*)p)[index] = val; + ((signed char *)p)[index] = val; break; case BYTEARRAY_TYPECODE: case 'B': - ((unsigned char*)p)[index] = val; + ((unsigned char *)p)[index] = val; break; case 'h': - ((short*)p)[index] = val; + ((short *)p)[index] = val; break; case 'H': - ((unsigned short*)p)[index] = val; + ((unsigned short *)p)[index] = val; break; case 'i': - ((int*)p)[index] = val; + ((int *)p)[index] = val; break; case 'I': - ((unsigned int*)p)[index] = val; + ((unsigned int *)p)[index] = val; break; case 'l': - ((long*)p)[index] = val; + ((long *)p)[index] = val; break; case 'L': - ((unsigned long*)p)[index] = val; + ((unsigned long *)p)[index] = val; break; #if MICROPY_LONGINT_IMPL != MICROPY_LONGINT_IMPL_NONE case 'q': - ((long long*)p)[index] = val; + ((long long *)p)[index] = val; break; case 'Q': - ((unsigned long long*)p)[index] = val; + ((unsigned long long *)p)[index] = val; break; #endif -#if MICROPY_PY_BUILTINS_FLOAT + #if MICROPY_PY_BUILTINS_FLOAT case 'f': - ((float*)p)[index] = val; + ((float *)p)[index] = val; break; case 'd': - ((double*)p)[index] = val; + ((double *)p)[index] = val; break; -#endif + #endif // Extension to CPython: array of pointers case 'P': - ((void**)p)[index] = (void*)(uintptr_t)val; + ((void **)p)[index] = (void *)(uintptr_t)val; break; } } diff --git a/py/builtinevex.c b/py/builtinevex.c index 846603f46b..159d97ee8a 100644 --- a/py/builtinevex.c +++ b/py/builtinevex.c @@ -90,9 +90,15 @@ STATIC mp_obj_t mp_builtin_compile(size_t n_args, const mp_obj_t *args) { qstr mode = mp_obj_str_get_qstr(args[2]); mp_parse_input_kind_t parse_input_kind; switch (mode) { - case MP_QSTR_single: parse_input_kind = MP_PARSE_SINGLE_INPUT; break; - case MP_QSTR_exec: parse_input_kind = MP_PARSE_FILE_INPUT; break; - case MP_QSTR_eval: parse_input_kind = MP_PARSE_EVAL_INPUT; break; + case MP_QSTR_single: + parse_input_kind = MP_PARSE_SINGLE_INPUT; + break; + case MP_QSTR_exec: + parse_input_kind = MP_PARSE_FILE_INPUT; + break; + case MP_QSTR_eval: + parse_input_kind = MP_PARSE_EVAL_INPUT; + break; default: mp_raise_ValueError("bad compile mode"); } diff --git a/py/builtinhelp.c b/py/builtinhelp.c index b36f4c9d33..4e5636a484 100644 --- a/py/builtinhelp.c +++ b/py/builtinhelp.c @@ -33,18 +33,18 @@ #if MICROPY_PY_BUILTINS_HELP const char mp_help_default_text[] = -"Welcome to MicroPython!\n" -"\n" -"For online docs please visit http://docs.micropython.org/\n" -"\n" -"Control commands:\n" -" CTRL-A -- on a blank line, enter raw REPL mode\n" -" CTRL-B -- on a blank line, enter normal REPL mode\n" -" CTRL-C -- interrupt a running program\n" -" CTRL-D -- on a blank line, exit or do a soft reset\n" -" CTRL-E -- on a blank line, enter paste mode\n" -"\n" -"For further help on a specific object, type help(obj)\n" + "Welcome to MicroPython!\n" + "\n" + "For online docs please visit http://docs.micropython.org/\n" + "\n" + "Control commands:\n" + " CTRL-A -- on a blank line, enter raw REPL mode\n" + " CTRL-B -- on a blank line, enter normal REPL mode\n" + " CTRL-C -- interrupt a running program\n" + " CTRL-D -- on a blank line, exit or do a soft reset\n" + " CTRL-E -- on a blank line, enter paste mode\n" + "\n" + "For further help on a specific object, type help(obj)\n" ; STATIC void mp_help_print_info_about_object(mp_obj_t name_o, mp_obj_t value) { @@ -95,7 +95,7 @@ STATIC void mp_help_print_modules(void) { #endif // sort the list so it's printed in alphabetical order - mp_obj_list_sort(1, &list, (mp_map_t*)&mp_const_empty_map); + mp_obj_list_sort(1, &list, (mp_map_t *)&mp_const_empty_map); // print the list of modules in a column-first order #define NUM_COLUMNS (4) diff --git a/py/builtinimport.c b/py/builtinimport.c index b8ed096caf..1cba6c3d6d 100644 --- a/py/builtinimport.c +++ b/py/builtinimport.c @@ -96,39 +96,39 @@ STATIC mp_import_stat_t stat_dir_or_file(vstr_t *path) { } STATIC mp_import_stat_t find_file(const char *file_str, uint file_len, vstr_t *dest) { -#if MICROPY_PY_SYS + #if MICROPY_PY_SYS // extract the list of paths size_t path_num; mp_obj_t *path_items; mp_obj_list_get(mp_sys_path, &path_num, &path_items); if (path_num == 0) { -#endif - // mp_sys_path is empty, so just use the given file name - vstr_add_strn(dest, file_str, file_len); - return stat_dir_or_file(dest); -#if MICROPY_PY_SYS - } else { - // go through each path looking for a directory or file - for (size_t i = 0; i < path_num; i++) { - vstr_reset(dest); - size_t p_len; - const char *p = mp_obj_str_get_data(path_items[i], &p_len); - if (p_len > 0) { - vstr_add_strn(dest, p, p_len); - vstr_add_char(dest, PATH_SEP_CHAR); - } - vstr_add_strn(dest, file_str, file_len); - mp_import_stat_t stat = stat_dir_or_file(dest); - if (stat != MP_IMPORT_STAT_NO_EXIST) { - return stat; - } + #endif + // mp_sys_path is empty, so just use the given file name + vstr_add_strn(dest, file_str, file_len); + return stat_dir_or_file(dest); + #if MICROPY_PY_SYS +} else { + // go through each path looking for a directory or file + for (size_t i = 0; i < path_num; i++) { + vstr_reset(dest); + size_t p_len; + const char *p = mp_obj_str_get_data(path_items[i], &p_len); + if (p_len > 0) { + vstr_add_strn(dest, p, p_len); + vstr_add_char(dest, PATH_SEP_CHAR); + } + vstr_add_strn(dest, file_str, file_len); + mp_import_stat_t stat = stat_dir_or_file(dest); + if (stat != MP_IMPORT_STAT_NO_EXIST) { + return stat; } - - // could not find a directory or file - return MP_IMPORT_STAT_NO_EXIST; } -#endif + + // could not find a directory or file + return MP_IMPORT_STAT_NO_EXIST; +} + #endif } #if MICROPY_ENABLE_COMPILER @@ -148,8 +148,8 @@ STATIC void do_load_from_lexer(mp_obj_t module_obj, mp_lexer_t *lex) { STATIC void do_execute_raw_code(mp_obj_t module_obj, mp_raw_code_t *raw_code) { #if MICROPY_PY___FILE__ // TODO - //qstr source_name = lex->source_name; - //mp_store_attr(module_obj, MP_QSTR___file__, MP_OBJ_NEW_QSTR(source_name)); + // qstr source_name = lex->source_name; + // mp_store_attr(module_obj, MP_QSTR___file__, MP_OBJ_NEW_QSTR(source_name)); #endif // execute the module in its context @@ -247,14 +247,14 @@ STATIC void chop_component(const char *start, const char **end) { } mp_obj_t mp_builtin___import__(size_t n_args, const mp_obj_t *args) { -#if DEBUG_PRINT + #if DEBUG_PRINT DEBUG_printf("__import__:\n"); for (size_t i = 0; i < n_args; i++) { DEBUG_printf(" "); mp_obj_print(args[i], PRINT_REPR); DEBUG_printf("\n"); } -#endif + #endif mp_obj_t module_name = args[0]; mp_obj_t fromtuple = mp_const_none; @@ -293,12 +293,12 @@ mp_obj_t mp_builtin___import__(size_t n_args, const mp_obj_t *args) { mp_map_elem_t *elem = mp_map_lookup(globals_map, MP_OBJ_NEW_QSTR(MP_QSTR___path__), MP_MAP_LOOKUP); bool is_pkg = (elem != NULL); -#if DEBUG_PRINT + #if DEBUG_PRINT DEBUG_printf("Current module/package: "); mp_obj_print(this_name_q, PRINT_REPR); DEBUG_printf(", is_package: %d", is_pkg); DEBUG_printf("\n"); -#endif + #endif size_t this_name_l; const char *this_name = mp_obj_str_get_data(this_name_q, &this_name_l); @@ -385,7 +385,7 @@ mp_obj_t mp_builtin___import__(size_t n_args, const mp_obj_t *args) { #if MICROPY_MODULE_WEAK_LINKS // check if there is a weak link to this module if (i == mod_len) { - mp_map_elem_t *el = mp_map_lookup((mp_map_t*)&mp_builtin_module_weak_links_map, MP_OBJ_NEW_QSTR(mod_name), MP_MAP_LOOKUP); + mp_map_elem_t *el = mp_map_lookup((mp_map_t *)&mp_builtin_module_weak_links_map, MP_OBJ_NEW_QSTR(mod_name), MP_MAP_LOOKUP); if (el == NULL) { goto no_exist; } @@ -393,10 +393,10 @@ mp_obj_t mp_builtin___import__(size_t n_args, const mp_obj_t *args) { module_obj = el->value; mp_module_call_init(mod_name, module_obj); } else { - no_exist: + no_exist: #else { - #endif + #endif // couldn't find the file, so fail if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) { mp_raise_msg(&mp_type_ImportError, "module not found"); @@ -443,7 +443,7 @@ mp_obj_t mp_builtin___import__(size_t n_args, const mp_obj_t *args) { vstr_add_char(&path, PATH_SEP_CHAR); vstr_add_str(&path, "__init__.py"); if (stat_file_py_or_mpy(&path) != MP_IMPORT_STAT_FILE) { - //mp_warning("%s is imported as namespace package", vstr_str(&path)); + // mp_warning("%s is imported as namespace package", vstr_str(&path)); } else { do_load(module_obj, &path); } @@ -493,7 +493,7 @@ mp_obj_t mp_builtin___import__(size_t n_args, const mp_obj_t *args) { #if MICROPY_MODULE_WEAK_LINKS // Check if there is a weak link to this module - mp_map_elem_t *el = mp_map_lookup((mp_map_t*)&mp_builtin_module_weak_links_map, MP_OBJ_NEW_QSTR(module_name_qstr), MP_MAP_LOOKUP); + mp_map_elem_t *el = mp_map_lookup((mp_map_t *)&mp_builtin_module_weak_links_map, MP_OBJ_NEW_QSTR(module_name_qstr), MP_MAP_LOOKUP); if (el != NULL) { // Found weak-linked module mp_module_call_init(module_name_qstr, el->value); diff --git a/py/compile.c b/py/compile.c index 6db108a599..36b2aab7ce 100644 --- a/py/compile.c +++ b/py/compile.c @@ -46,14 +46,14 @@ typedef enum { // define rules with a compile function #define DEF_RULE(rule, comp, kind, ...) PN_##rule, #define DEF_RULE_NC(rule, kind, ...) -#include "py/grammar.h" + #include "py/grammar.h" #undef DEF_RULE #undef DEF_RULE_NC PN_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, ...) PN_##rule, -#include "py/grammar.h" + #include "py/grammar.h" #undef DEF_RULE #undef DEF_RULE_NC } pn_kind_t; @@ -150,7 +150,7 @@ typedef struct _compiler_t { STATIC void compile_error_set_line(compiler_t *comp, mp_parse_node_t pn) { // if the line of the error is unknown then try to update it from the pn if (comp->compile_error_line == 0 && MP_PARSE_NODE_IS_STRUCT(pn)) { - comp->compile_error_line = ((mp_parse_node_struct_t*)pn)->source_line; + comp->compile_error_line = ((mp_parse_node_struct_t *)pn)->source_line; } } @@ -215,7 +215,7 @@ typedef void (*apply_list_fun_t)(compiler_t *comp, mp_parse_node_t pn); STATIC void apply_to_single_or_list(compiler_t *comp, mp_parse_node_t pn, pn_kind_t pn_list_kind, apply_list_fun_t f) { if (MP_PARSE_NODE_IS_STRUCT_KIND(pn, pn_list_kind)) { - mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)pn; + mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn; int num_nodes = MP_PARSE_NODE_STRUCT_NUM_NODES(pns); for (int i = 0; i < num_nodes; i++) { f(comp, pns->nodes[i]); @@ -306,7 +306,7 @@ STATIC void c_if_cond(compiler_t *comp, mp_parse_node_t pn, bool jump_if, int la } return; } else if (MP_PARSE_NODE_IS_STRUCT(pn)) { - mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)pn; + mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn; int n = MP_PARSE_NODE_STRUCT_NUM_NODES(pns); if (MP_PARSE_NODE_STRUCT_KIND(pns) == PN_or_test) { if (jump_if == false) { @@ -365,7 +365,7 @@ STATIC void c_assign_atom_expr(compiler_t *comp, mp_parse_node_struct_t *pns, as } if (MP_PARSE_NODE_IS_STRUCT(pns->nodes[1])) { - mp_parse_node_struct_t *pns1 = (mp_parse_node_struct_t*)pns->nodes[1]; + mp_parse_node_struct_t *pns1 = (mp_parse_node_struct_t *)pns->nodes[1]; if (MP_PARSE_NODE_STRUCT_KIND(pns1) == PN_atom_expr_trailers) { int n = MP_PARSE_NODE_STRUCT_NUM_NODES(pns1); if (assign_kind != ASSIGN_AUG_STORE) { @@ -374,7 +374,7 @@ STATIC void c_assign_atom_expr(compiler_t *comp, mp_parse_node_struct_t *pns, as } } assert(MP_PARSE_NODE_IS_STRUCT(pns1->nodes[n - 1])); - pns1 = (mp_parse_node_struct_t*)pns1->nodes[n - 1]; + pns1 = (mp_parse_node_struct_t *)pns1->nodes[n - 1]; } if (MP_PARSE_NODE_STRUCT_KIND(pns1) == PN_trailer_bracket) { if (assign_kind == ASSIGN_AUG_STORE) { @@ -434,14 +434,14 @@ STATIC void c_assign_tuple(compiler_t *comp, mp_parse_node_t node_head, uint num } if (num_head != 0) { if (0 == have_star_index) { - c_assign(comp, ((mp_parse_node_struct_t*)node_head)->nodes[0], ASSIGN_STORE); + c_assign(comp, ((mp_parse_node_struct_t *)node_head)->nodes[0], ASSIGN_STORE); } else { c_assign(comp, node_head, ASSIGN_STORE); } } for (uint i = 0; i < num_tail; i++) { if (num_head + i == have_star_index) { - c_assign(comp, ((mp_parse_node_struct_t*)nodes_tail[i])->nodes[0], ASSIGN_STORE); + c_assign(comp, ((mp_parse_node_struct_t *)nodes_tail[i])->nodes[0], ASSIGN_STORE); } else { c_assign(comp, nodes_tail[i], ASSIGN_STORE); } @@ -469,7 +469,7 @@ STATIC void c_assign(compiler_t *comp, mp_parse_node_t pn, assign_kind_t assign_ } } else { // pn must be a struct - mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)pn; + mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn; switch (MP_PARSE_NODE_STRUCT_KIND(pns)) { case PN_atom_expr_normal: // lhs is an index or attribute @@ -495,7 +495,7 @@ STATIC void c_assign(compiler_t *comp, mp_parse_node_t pn, assign_kind_t assign_ if (assign_kind != ASSIGN_STORE) { goto cannot_assign; } - pns = (mp_parse_node_struct_t*)pns->nodes[0]; + pns = (mp_parse_node_struct_t *)pns->nodes[0]; goto testlist_comp; } break; @@ -509,7 +509,7 @@ STATIC void c_assign(compiler_t *comp, mp_parse_node_t pn, assign_kind_t assign_ // empty list, assignment allowed c_assign_tuple(comp, MP_PARSE_NODE_NULL, 0, NULL); } else if (MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[0], PN_testlist_comp)) { - pns = (mp_parse_node_struct_t*)pns->nodes[0]; + pns = (mp_parse_node_struct_t *)pns->nodes[0]; goto testlist_comp; } else { // brackets around 1 item @@ -522,10 +522,10 @@ STATIC void c_assign(compiler_t *comp, mp_parse_node_t pn, assign_kind_t assign_ } return; - testlist_comp: + testlist_comp: // lhs is a sequence if (MP_PARSE_NODE_IS_STRUCT(pns->nodes[1])) { - mp_parse_node_struct_t *pns2 = (mp_parse_node_struct_t*)pns->nodes[1]; + mp_parse_node_struct_t *pns2 = (mp_parse_node_struct_t *)pns->nodes[1]; if (MP_PARSE_NODE_STRUCT_KIND(pns2) == PN_testlist_comp_3b) { // sequence of one item, with trailing comma assert(MP_PARSE_NODE_IS_NULL(pns2->nodes[0])); @@ -542,14 +542,14 @@ STATIC void c_assign(compiler_t *comp, mp_parse_node_t pn, assign_kind_t assign_ } } else { // sequence with 2 items - sequence_with_2_items: + sequence_with_2_items: c_assign_tuple(comp, MP_PARSE_NODE_NULL, 2, pns->nodes); } return; } return; - cannot_assign: +cannot_assign: compile_syntax_error(comp, pn, "can't assign to expression"); } @@ -606,7 +606,7 @@ STATIC void compile_funcdef_lambdef_param(compiler_t *comp, mp_parse_node_t pn) pn_kind = -1; } else { assert(MP_PARSE_NODE_IS_STRUCT(pn)); - pn_kind = MP_PARSE_NODE_STRUCT_KIND((mp_parse_node_struct_t*)pn); + pn_kind = MP_PARSE_NODE_STRUCT_KIND((mp_parse_node_struct_t *)pn); } if (pn_kind == PN_typedargslist_star || pn_kind == PN_varargslist_star) { @@ -636,16 +636,16 @@ STATIC void compile_funcdef_lambdef_param(compiler_t *comp, mp_parse_node_t pn) } else if (pn_kind == PN_typedargslist_name) { // this parameter has a colon and/or equal specifier - mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)pn; + mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn; pn_id = pns->nodes[0]; - //pn_colon = pns->nodes[1]; // unused + // pn_colon = pns->nodes[1]; // unused pn_equal = pns->nodes[2]; } else { assert(pn_kind == PN_varargslist_name); // should be // this parameter has an equal specifier - mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)pn; + mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn; pn_id = pns->nodes[0]; pn_equal = pns->nodes[1]; } @@ -735,7 +735,7 @@ STATIC qstr compile_funcdef_helper(compiler_t *comp, mp_parse_node_struct_t *pns } // get the scope for this function - scope_t *fscope = (scope_t*)pns->nodes[4]; + scope_t *fscope = (scope_t *)pns->nodes[4]; // compile the function definition compile_funcdef_lambdef(comp, fscope, pns->nodes[1], PN_typedargslist); @@ -757,7 +757,7 @@ STATIC qstr compile_classdef_helper(compiler_t *comp, mp_parse_node_struct_t *pn EMIT(load_build_class); // scope for this class - scope_t *cscope = (scope_t*)pns->nodes[3]; + scope_t *cscope = (scope_t *)pns->nodes[3]; // compile the class close_over_variables_etc(comp, cscope, 0, 0); @@ -791,12 +791,12 @@ STATIC bool compile_built_in_decorator(compiler_t *comp, int name_len, mp_parse_ qstr attr = MP_PARSE_NODE_LEAF_ARG(name_nodes[1]); if (attr == MP_QSTR_bytecode) { *emit_options = MP_EMIT_OPT_BYTECODE; -#if MICROPY_EMIT_NATIVE + #if MICROPY_EMIT_NATIVE } else if (attr == MP_QSTR_native) { *emit_options = MP_EMIT_OPT_NATIVE_PYTHON; } else if (attr == MP_QSTR_viper) { *emit_options = MP_EMIT_OPT_VIPER; -#endif + #endif #if MICROPY_EMIT_INLINE_ASM } else if (attr == ASM_DECORATOR_QSTR) { *emit_options = MP_EMIT_OPT_ASM; @@ -820,7 +820,7 @@ STATIC void compile_decorated(compiler_t *comp, mp_parse_node_struct_t *pns) { int num_built_in_decorators = 0; for (int i = 0; i < n; i++) { assert(MP_PARSE_NODE_IS_STRUCT_KIND(nodes[i], PN_decorator)); // should be - mp_parse_node_struct_t *pns_decorator = (mp_parse_node_struct_t*)nodes[i]; + mp_parse_node_struct_t *pns_decorator = (mp_parse_node_struct_t *)nodes[i]; // nodes[0] contains the decorator function, which is a dotted name mp_parse_node_t *name_nodes; @@ -850,16 +850,16 @@ STATIC void compile_decorated(compiler_t *comp, mp_parse_node_struct_t *pns) { } // compile the body (funcdef, async funcdef or classdef) and get its name - mp_parse_node_struct_t *pns_body = (mp_parse_node_struct_t*)pns->nodes[1]; + mp_parse_node_struct_t *pns_body = (mp_parse_node_struct_t *)pns->nodes[1]; qstr body_name = 0; if (MP_PARSE_NODE_STRUCT_KIND(pns_body) == PN_funcdef) { body_name = compile_funcdef_helper(comp, pns_body, emit_options); #if MICROPY_PY_ASYNC_AWAIT } else if (MP_PARSE_NODE_STRUCT_KIND(pns_body) == PN_async_funcdef) { assert(MP_PARSE_NODE_IS_STRUCT(pns_body->nodes[0])); - mp_parse_node_struct_t *pns0 = (mp_parse_node_struct_t*)pns_body->nodes[0]; + mp_parse_node_struct_t *pns0 = (mp_parse_node_struct_t *)pns_body->nodes[0]; body_name = compile_funcdef_helper(comp, pns0, emit_options); - scope_t *fscope = (scope_t*)pns0->nodes[4]; + scope_t *fscope = (scope_t *)pns0->nodes[4]; fscope->scope_flags |= MP_SCOPE_FLAG_GENERATOR; #endif } else { @@ -886,19 +886,19 @@ STATIC void c_del_stmt(compiler_t *comp, mp_parse_node_t pn) { if (MP_PARSE_NODE_IS_ID(pn)) { compile_delete_id(comp, MP_PARSE_NODE_LEAF_ARG(pn)); } else if (MP_PARSE_NODE_IS_STRUCT_KIND(pn, PN_atom_expr_normal)) { - mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)pn; + mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn; compile_node(comp, pns->nodes[0]); // base of the atom_expr_normal node if (MP_PARSE_NODE_IS_STRUCT(pns->nodes[1])) { - mp_parse_node_struct_t *pns1 = (mp_parse_node_struct_t*)pns->nodes[1]; + mp_parse_node_struct_t *pns1 = (mp_parse_node_struct_t *)pns->nodes[1]; if (MP_PARSE_NODE_STRUCT_KIND(pns1) == PN_atom_expr_trailers) { int n = MP_PARSE_NODE_STRUCT_NUM_NODES(pns1); for (int i = 0; i < n - 1; i++) { compile_node(comp, pns1->nodes[i]); } assert(MP_PARSE_NODE_IS_STRUCT(pns1->nodes[n - 1])); - pns1 = (mp_parse_node_struct_t*)pns1->nodes[n - 1]; + pns1 = (mp_parse_node_struct_t *)pns1->nodes[n - 1]; } if (MP_PARSE_NODE_STRUCT_KIND(pns1) == PN_trailer_bracket) { compile_node(comp, pns1->nodes[0]); @@ -914,16 +914,16 @@ STATIC void c_del_stmt(compiler_t *comp, mp_parse_node_t pn) { } } else if (MP_PARSE_NODE_IS_STRUCT_KIND(pn, PN_atom_paren)) { - pn = ((mp_parse_node_struct_t*)pn)->nodes[0]; + pn = ((mp_parse_node_struct_t *)pn)->nodes[0]; if (MP_PARSE_NODE_IS_NULL(pn)) { goto cannot_delete; } else { assert(MP_PARSE_NODE_IS_STRUCT_KIND(pn, PN_testlist_comp)); - mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)pn; + mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn; // TODO perhaps factorise testlist_comp code with other uses of PN_testlist_comp if (MP_PARSE_NODE_IS_STRUCT(pns->nodes[1])) { - mp_parse_node_struct_t *pns1 = (mp_parse_node_struct_t*)pns->nodes[1]; + mp_parse_node_struct_t *pns1 = (mp_parse_node_struct_t *)pns->nodes[1]; if (MP_PARSE_NODE_STRUCT_KIND(pns1) == PN_testlist_comp_3b) { // sequence of one item, with trailing comma assert(MP_PARSE_NODE_IS_NULL(pns1->nodes[0])); @@ -943,7 +943,7 @@ STATIC void c_del_stmt(compiler_t *comp, mp_parse_node_t pn) { } } else { // sequence with 2 items - sequence_with_2_items: + sequence_with_2_items: c_del_stmt(comp, pns->nodes[0]); c_del_stmt(comp, pns->nodes[1]); } @@ -989,10 +989,10 @@ STATIC void compile_return_stmt(compiler_t *comp, mp_parse_node_struct_t *pns) { // no argument to 'return', so return None EMIT_ARG(load_const_tok, MP_TOKEN_KW_NONE); } else if (MICROPY_COMP_RETURN_IF_EXPR - && MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[0], PN_test_if_expr)) { + && MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[0], PN_test_if_expr)) { // special case when returning an if-expression; to match CPython optimisation - mp_parse_node_struct_t *pns_test_if_expr = (mp_parse_node_struct_t*)pns->nodes[0]; - mp_parse_node_struct_t *pns_test_if_else = (mp_parse_node_struct_t*)pns_test_if_expr->nodes[1]; + mp_parse_node_struct_t *pns_test_if_expr = (mp_parse_node_struct_t *)pns->nodes[0]; + mp_parse_node_struct_t *pns_test_if_else = (mp_parse_node_struct_t *)pns_test_if_expr->nodes[1]; uint l_fail = comp_next_label(comp); c_if_cond(comp, pns_test_if_else->nodes[0], false, l_fail); // condition @@ -1017,7 +1017,7 @@ STATIC void compile_raise_stmt(compiler_t *comp, mp_parse_node_struct_t *pns) { EMIT_ARG(raise_varargs, 0); } else if (MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[0], PN_raise_stmt_arg)) { // raise x from y - pns = (mp_parse_node_struct_t*)pns->nodes[0]; + pns = (mp_parse_node_struct_t *)pns->nodes[0]; compile_node(comp, pns->nodes[0]); compile_node(comp, pns->nodes[1]); EMIT_ARG(raise_varargs, 2); @@ -1034,7 +1034,7 @@ STATIC void compile_raise_stmt(compiler_t *comp, mp_parse_node_struct_t *pns) { STATIC void do_import_name(compiler_t *comp, mp_parse_node_t pn, qstr *q_base) { bool is_as = false; if (MP_PARSE_NODE_IS_STRUCT_KIND(pn, PN_dotted_as_name)) { - mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)pn; + mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn; // a name of the form x as y; unwrap it *q_base = MP_PARSE_NODE_LEAF_ARG(pns->nodes[1]); pn = pns->nodes[0]; @@ -1053,7 +1053,7 @@ STATIC void do_import_name(compiler_t *comp, mp_parse_node_t pn, qstr *q_base) { EMIT_ARG(import, q_full, MP_EMIT_IMPORT_NAME); } else { assert(MP_PARSE_NODE_IS_STRUCT_KIND(pn, PN_dotted_name)); // should be - mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)pn; + mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn; { // a name of the form a.b.c if (!is_as) { @@ -1112,7 +1112,7 @@ STATIC void compile_import_from(compiler_t *comp, mp_parse_node_struct_t *pns) { pn_import_source = MP_PARSE_NODE_NULL; } else if (MP_PARSE_NODE_IS_STRUCT_KIND(pn_import_source, PN_import_from_2b)) { // This covers relative imports starting with dot(s) like "from .foo import" - mp_parse_node_struct_t *pns_2b = (mp_parse_node_struct_t*)pn_import_source; + mp_parse_node_struct_t *pns_2b = (mp_parse_node_struct_t *)pn_import_source; pn_rel = pns_2b->nodes[0]; pn_import_source = pns_2b->nodes[1]; assert(!MP_PARSE_NODE_IS_NULL(pn_import_source)); // should not be @@ -1156,7 +1156,7 @@ STATIC void compile_import_from(compiler_t *comp, mp_parse_node_struct_t *pns) { int n = mp_parse_node_extract_list(&pns->nodes[1], PN_import_as_names, &pn_nodes); for (int i = 0; i < n; i++) { assert(MP_PARSE_NODE_IS_STRUCT_KIND(pn_nodes[i], PN_import_as_name)); - mp_parse_node_struct_t *pns3 = (mp_parse_node_struct_t*)pn_nodes[i]; + mp_parse_node_struct_t *pns3 = (mp_parse_node_struct_t *)pn_nodes[i]; qstr id2 = MP_PARSE_NODE_LEAF_ARG(pns3->nodes[0]); // should be id EMIT_ARG(load_const_str, id2); } @@ -1167,7 +1167,7 @@ STATIC void compile_import_from(compiler_t *comp, mp_parse_node_struct_t *pns) { do_import_name(comp, pn_import_source, &dummy_q); for (int i = 0; i < n; i++) { assert(MP_PARSE_NODE_IS_STRUCT_KIND(pn_nodes[i], PN_import_as_name)); - mp_parse_node_struct_t *pns3 = (mp_parse_node_struct_t*)pn_nodes[i]; + mp_parse_node_struct_t *pns3 = (mp_parse_node_struct_t *)pn_nodes[i]; qstr id2 = MP_PARSE_NODE_LEAF_ARG(pns3->nodes[0]); // should be id EMIT_ARG(import, id2, MP_EMIT_IMPORT_FROM); if (MP_PARSE_NODE_IS_NULL(pns3->nodes[1])) { @@ -1280,7 +1280,7 @@ STATIC void compile_if_stmt(compiler_t *comp, mp_parse_node_struct_t *pns) { int n_elif = mp_parse_node_extract_list(&pns->nodes[2], PN_if_stmt_elif_list, &pn_elif); for (int i = 0; i < n_elif; i++) { assert(MP_PARSE_NODE_IS_STRUCT_KIND(pn_elif[i], PN_if_stmt_elif)); // should be - mp_parse_node_struct_t *pns_elif = (mp_parse_node_struct_t*)pn_elif[i]; + mp_parse_node_struct_t *pns_elif = (mp_parse_node_struct_t *)pn_elif[i]; // optimisation: don't emit anything when "if False" if (!mp_parse_node_is_const_false(pns_elif->nodes[0])) { @@ -1449,11 +1449,11 @@ STATIC void compile_for_stmt(compiler_t *comp, mp_parse_node_struct_t *pns) { // this is actually slower, but uses no heap memory // for viper it will be much, much faster if (/*comp->scope_cur->emit_options == MP_EMIT_OPT_VIPER &&*/ MP_PARSE_NODE_IS_ID(pns->nodes[0]) && MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[1], PN_atom_expr_normal)) { - mp_parse_node_struct_t *pns_it = (mp_parse_node_struct_t*)pns->nodes[1]; + mp_parse_node_struct_t *pns_it = (mp_parse_node_struct_t *)pns->nodes[1]; if (MP_PARSE_NODE_IS_ID(pns_it->nodes[0]) && MP_PARSE_NODE_LEAF_ARG(pns_it->nodes[0]) == MP_QSTR_range - && MP_PARSE_NODE_STRUCT_KIND((mp_parse_node_struct_t*)pns_it->nodes[1]) == PN_trailer_paren) { - mp_parse_node_t pn_range_args = ((mp_parse_node_struct_t*)pns_it->nodes[1])->nodes[0]; + && MP_PARSE_NODE_STRUCT_KIND((mp_parse_node_struct_t *)pns_it->nodes[1]) == PN_trailer_paren) { + mp_parse_node_t pn_range_args = ((mp_parse_node_struct_t *)pns_it->nodes[1])->nodes[0]; mp_parse_node_t *args; int n_args = mp_parse_node_extract_list(&pn_range_args, PN_arglist, &args); mp_parse_node_t pn_range_start; @@ -1482,13 +1482,13 @@ STATIC void compile_for_stmt(compiler_t *comp, mp_parse_node_struct_t *pns) { } // arguments must be able to be compiled as standard expressions if (optimize && MP_PARSE_NODE_IS_STRUCT(pn_range_start)) { - int k = MP_PARSE_NODE_STRUCT_KIND((mp_parse_node_struct_t*)pn_range_start); + int k = MP_PARSE_NODE_STRUCT_KIND((mp_parse_node_struct_t *)pn_range_start); if (k == PN_arglist_star || k == PN_arglist_dbl_star || k == PN_argument) { optimize = false; } } if (optimize && MP_PARSE_NODE_IS_STRUCT(pn_range_end)) { - int k = MP_PARSE_NODE_STRUCT_KIND((mp_parse_node_struct_t*)pn_range_end); + int k = MP_PARSE_NODE_STRUCT_KIND((mp_parse_node_struct_t *)pn_range_end); if (k == PN_arglist_star || k == PN_arglist_dbl_star || k == PN_argument) { optimize = false; } @@ -1546,7 +1546,7 @@ STATIC void compile_try_except(compiler_t *comp, mp_parse_node_t pn_body, int n_ for (int i = 0; i < n_except; i++) { assert(MP_PARSE_NODE_IS_STRUCT_KIND(pn_excepts[i], PN_try_stmt_except)); // should be - mp_parse_node_struct_t *pns_except = (mp_parse_node_struct_t*)pn_excepts[i]; + mp_parse_node_struct_t *pns_except = (mp_parse_node_struct_t *)pn_excepts[i]; qstr qstr_exception_local = 0; uint end_finally_label = comp_next_label(comp); @@ -1562,7 +1562,7 @@ STATIC void compile_try_except(compiler_t *comp, mp_parse_node_t pn_body, int n_ // this exception handler requires a match to a certain type of exception mp_parse_node_t pns_exception_expr = pns_except->nodes[0]; if (MP_PARSE_NODE_IS_STRUCT(pns_exception_expr)) { - mp_parse_node_struct_t *pns3 = (mp_parse_node_struct_t*)pns_exception_expr; + mp_parse_node_struct_t *pns3 = (mp_parse_node_struct_t *)pns_exception_expr; if (MP_PARSE_NODE_STRUCT_KIND(pns3) == PN_try_stmt_as_name) { // handler binds the exception to a local pns_exception_expr = pns3->nodes[0]; @@ -1638,7 +1638,7 @@ STATIC void compile_try_finally(compiler_t *comp, mp_parse_node_t pn_body, int n STATIC void compile_try_stmt(compiler_t *comp, mp_parse_node_struct_t *pns) { assert(MP_PARSE_NODE_IS_STRUCT(pns->nodes[1])); // should be { - mp_parse_node_struct_t *pns2 = (mp_parse_node_struct_t*)pns->nodes[1]; + mp_parse_node_struct_t *pns2 = (mp_parse_node_struct_t *)pns->nodes[1]; if (MP_PARSE_NODE_STRUCT_KIND(pns2) == PN_try_stmt_finally) { // just try-finally compile_try_finally(comp, pns->nodes[0], 0, NULL, MP_PARSE_NODE_NULL, pns2->nodes[0]); @@ -1651,7 +1651,7 @@ STATIC void compile_try_stmt(compiler_t *comp, mp_parse_node_struct_t *pns) { compile_try_except(comp, pns->nodes[0], n_except, pn_excepts, pns2->nodes[1]); } else { // have finally - compile_try_finally(comp, pns->nodes[0], n_except, pn_excepts, pns2->nodes[1], ((mp_parse_node_struct_t*)pns2->nodes[2])->nodes[0]); + compile_try_finally(comp, pns->nodes[0], n_except, pn_excepts, pns2->nodes[1], ((mp_parse_node_struct_t *)pns2->nodes[2])->nodes[0]); } } else { // just try-except @@ -1670,7 +1670,7 @@ STATIC void compile_with_stmt_helper(compiler_t *comp, int n, mp_parse_node_t *n uint l_end = comp_next_label(comp); if (MP_PARSE_NODE_IS_STRUCT_KIND(nodes[0], PN_with_item)) { // this pre-bit is of the form "a as b" - mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)nodes[0]; + mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)nodes[0]; compile_node(comp, pns->nodes[0]); compile_increase_except_level(comp, l_end, MP_EMIT_SETUP_BLOCK_WITH); c_assign(comp, pns->nodes[1], ASSIGN_STORE); @@ -1778,7 +1778,7 @@ STATIC void compile_async_with_stmt_helper(compiler_t *comp, int n, mp_parse_nod if (MP_PARSE_NODE_IS_STRUCT_KIND(nodes[0], PN_with_item)) { // this pre-bit is of the form "a as b" - mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)nodes[0]; + mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)nodes[0]; compile_node(comp, pns->nodes[0]); EMIT(dup_top); compile_await_object_method(comp, MP_QSTR___aenter__); @@ -1891,11 +1891,11 @@ STATIC void compile_async_with_stmt(compiler_t *comp, mp_parse_node_struct_t *pn STATIC void compile_async_stmt(compiler_t *comp, mp_parse_node_struct_t *pns) { assert(MP_PARSE_NODE_IS_STRUCT(pns->nodes[0])); - mp_parse_node_struct_t *pns0 = (mp_parse_node_struct_t*)pns->nodes[0]; + mp_parse_node_struct_t *pns0 = (mp_parse_node_struct_t *)pns->nodes[0]; if (MP_PARSE_NODE_STRUCT_KIND(pns0) == PN_funcdef) { // async def compile_funcdef(comp, pns0); - scope_t *fscope = (scope_t*)pns0->nodes[4]; + scope_t *fscope = (scope_t *)pns0->nodes[4]; fscope->scope_flags |= MP_SCOPE_FLAG_GENERATOR; } else if (MP_PARSE_NODE_STRUCT_KIND(pns0) == PN_for_stmt) { // async for @@ -1928,7 +1928,7 @@ STATIC void compile_expr_stmt(compiler_t *comp, mp_parse_node_struct_t *pns) { } } } else if (MP_PARSE_NODE_IS_STRUCT(pns->nodes[1])) { - mp_parse_node_struct_t *pns1 = (mp_parse_node_struct_t*)pns->nodes[1]; + mp_parse_node_struct_t *pns1 = (mp_parse_node_struct_t *)pns->nodes[1]; int kind = MP_PARSE_NODE_STRUCT_KIND(pns1); if (kind == PN_expr_stmt_augassign) { c_assign(comp, pns->nodes[0], ASSIGN_AUG_LOAD); // lhs load for aug assign @@ -1936,18 +1936,43 @@ STATIC void compile_expr_stmt(compiler_t *comp, mp_parse_node_struct_t *pns) { assert(MP_PARSE_NODE_IS_TOKEN(pns1->nodes[0])); mp_binary_op_t op; switch (MP_PARSE_NODE_LEAF_ARG(pns1->nodes[0])) { - case MP_TOKEN_DEL_PIPE_EQUAL: op = MP_BINARY_OP_INPLACE_OR; break; - case MP_TOKEN_DEL_CARET_EQUAL: op = MP_BINARY_OP_INPLACE_XOR; break; - case MP_TOKEN_DEL_AMPERSAND_EQUAL: op = MP_BINARY_OP_INPLACE_AND; break; - case MP_TOKEN_DEL_DBL_LESS_EQUAL: op = MP_BINARY_OP_INPLACE_LSHIFT; break; - case MP_TOKEN_DEL_DBL_MORE_EQUAL: op = MP_BINARY_OP_INPLACE_RSHIFT; break; - case MP_TOKEN_DEL_PLUS_EQUAL: op = MP_BINARY_OP_INPLACE_ADD; break; - case MP_TOKEN_DEL_MINUS_EQUAL: op = MP_BINARY_OP_INPLACE_SUBTRACT; break; - case MP_TOKEN_DEL_STAR_EQUAL: op = MP_BINARY_OP_INPLACE_MULTIPLY; break; - case MP_TOKEN_DEL_DBL_SLASH_EQUAL: op = MP_BINARY_OP_INPLACE_FLOOR_DIVIDE; break; - case MP_TOKEN_DEL_SLASH_EQUAL: op = MP_BINARY_OP_INPLACE_TRUE_DIVIDE; break; - case MP_TOKEN_DEL_PERCENT_EQUAL: op = MP_BINARY_OP_INPLACE_MODULO; break; - case MP_TOKEN_DEL_DBL_STAR_EQUAL: default: op = MP_BINARY_OP_INPLACE_POWER; break; + case MP_TOKEN_DEL_PIPE_EQUAL: + op = MP_BINARY_OP_INPLACE_OR; + break; + case MP_TOKEN_DEL_CARET_EQUAL: + op = MP_BINARY_OP_INPLACE_XOR; + break; + case MP_TOKEN_DEL_AMPERSAND_EQUAL: + op = MP_BINARY_OP_INPLACE_AND; + break; + case MP_TOKEN_DEL_DBL_LESS_EQUAL: + op = MP_BINARY_OP_INPLACE_LSHIFT; + break; + case MP_TOKEN_DEL_DBL_MORE_EQUAL: + op = MP_BINARY_OP_INPLACE_RSHIFT; + break; + case MP_TOKEN_DEL_PLUS_EQUAL: + op = MP_BINARY_OP_INPLACE_ADD; + break; + case MP_TOKEN_DEL_MINUS_EQUAL: + op = MP_BINARY_OP_INPLACE_SUBTRACT; + break; + case MP_TOKEN_DEL_STAR_EQUAL: + op = MP_BINARY_OP_INPLACE_MULTIPLY; + break; + case MP_TOKEN_DEL_DBL_SLASH_EQUAL: + op = MP_BINARY_OP_INPLACE_FLOOR_DIVIDE; + break; + case MP_TOKEN_DEL_SLASH_EQUAL: + op = MP_BINARY_OP_INPLACE_TRUE_DIVIDE; + break; + case MP_TOKEN_DEL_PERCENT_EQUAL: + op = MP_BINARY_OP_INPLACE_MODULO; + break; + case MP_TOKEN_DEL_DBL_STAR_EQUAL: + default: + op = MP_BINARY_OP_INPLACE_POWER; + break; } EMIT_ARG(binary_op, op); c_assign(comp, pns->nodes[0], ASSIGN_AUG_STORE); // lhs store for aug assign @@ -1970,8 +1995,8 @@ STATIC void compile_expr_stmt(compiler_t *comp, mp_parse_node_struct_t *pns) { #if MICROPY_COMP_DOUBLE_TUPLE_ASSIGN if (MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[1], PN_testlist_star_expr) && MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[0], PN_testlist_star_expr)) { - mp_parse_node_struct_t *pns0 = (mp_parse_node_struct_t*)pns->nodes[0]; - pns1 = (mp_parse_node_struct_t*)pns->nodes[1]; + mp_parse_node_struct_t *pns0 = (mp_parse_node_struct_t *)pns->nodes[0]; + pns1 = (mp_parse_node_struct_t *)pns->nodes[1]; uint32_t n_pns0 = MP_PARSE_NODE_STRUCT_NUM_NODES(pns0); // Can only optimise a tuple-to-tuple assignment when all of the following hold: // - equal number of items in LHS and RHS tuples @@ -2021,7 +2046,7 @@ STATIC void compile_expr_stmt(compiler_t *comp, mp_parse_node_struct_t *pns) { STATIC void compile_test_if_expr(compiler_t *comp, mp_parse_node_struct_t *pns) { assert(MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[1], PN_test_if_else)); - mp_parse_node_struct_t *pns_test_if_else = (mp_parse_node_struct_t*)pns->nodes[1]; + mp_parse_node_struct_t *pns_test_if_else = (mp_parse_node_struct_t *)pns->nodes[1]; uint l_fail = comp_next_label(comp); uint l_end = comp_next_label(comp); @@ -2043,7 +2068,7 @@ STATIC void compile_lambdef(compiler_t *comp, mp_parse_node_struct_t *pns) { } // get the scope for this lambda - scope_t *this_scope = (scope_t*)pns->nodes[2]; + scope_t *this_scope = (scope_t *)pns->nodes[2]; // compile the lambda definition compile_funcdef_lambdef(comp, this_scope, pns->nodes[0], PN_varargslist); @@ -2084,18 +2109,33 @@ STATIC void compile_comparison(compiler_t *comp, mp_parse_node_struct_t *pns) { if (MP_PARSE_NODE_IS_TOKEN(pns->nodes[i])) { mp_binary_op_t op; switch (MP_PARSE_NODE_LEAF_ARG(pns->nodes[i])) { - case MP_TOKEN_OP_LESS: op = MP_BINARY_OP_LESS; break; - case MP_TOKEN_OP_MORE: op = MP_BINARY_OP_MORE; break; - case MP_TOKEN_OP_DBL_EQUAL: op = MP_BINARY_OP_EQUAL; break; - case MP_TOKEN_OP_LESS_EQUAL: op = MP_BINARY_OP_LESS_EQUAL; break; - case MP_TOKEN_OP_MORE_EQUAL: op = MP_BINARY_OP_MORE_EQUAL; break; - case MP_TOKEN_OP_NOT_EQUAL: op = MP_BINARY_OP_NOT_EQUAL; break; - case MP_TOKEN_KW_IN: default: op = MP_BINARY_OP_IN; break; + case MP_TOKEN_OP_LESS: + op = MP_BINARY_OP_LESS; + break; + case MP_TOKEN_OP_MORE: + op = MP_BINARY_OP_MORE; + break; + case MP_TOKEN_OP_DBL_EQUAL: + op = MP_BINARY_OP_EQUAL; + break; + case MP_TOKEN_OP_LESS_EQUAL: + op = MP_BINARY_OP_LESS_EQUAL; + break; + case MP_TOKEN_OP_MORE_EQUAL: + op = MP_BINARY_OP_MORE_EQUAL; + break; + case MP_TOKEN_OP_NOT_EQUAL: + op = MP_BINARY_OP_NOT_EQUAL; + break; + case MP_TOKEN_KW_IN: + default: + op = MP_BINARY_OP_IN; + break; } EMIT_ARG(binary_op, op); } else { assert(MP_PARSE_NODE_IS_STRUCT(pns->nodes[i])); // should be - mp_parse_node_struct_t *pns2 = (mp_parse_node_struct_t*)pns->nodes[i]; + mp_parse_node_struct_t *pns2 = (mp_parse_node_struct_t *)pns->nodes[i]; int kind = MP_PARSE_NODE_STRUCT_KIND(pns2); if (kind == PN_comp_op_not_in) { EMIT_ARG(binary_op, MP_BINARY_OP_NOT_IN); @@ -2147,13 +2187,27 @@ STATIC void compile_term(compiler_t *comp, mp_parse_node_struct_t *pns) { mp_binary_op_t op; mp_token_kind_t tok = MP_PARSE_NODE_LEAF_ARG(pns->nodes[i]); switch (tok) { - case MP_TOKEN_OP_PLUS: op = MP_BINARY_OP_ADD; break; - case MP_TOKEN_OP_MINUS: op = MP_BINARY_OP_SUBTRACT; break; - case MP_TOKEN_OP_STAR: op = MP_BINARY_OP_MULTIPLY; break; - case MP_TOKEN_OP_DBL_SLASH: op = MP_BINARY_OP_FLOOR_DIVIDE; break; - case MP_TOKEN_OP_SLASH: op = MP_BINARY_OP_TRUE_DIVIDE; break; - case MP_TOKEN_OP_PERCENT: op = MP_BINARY_OP_MODULO; break; - case MP_TOKEN_OP_DBL_LESS: op = MP_BINARY_OP_LSHIFT; break; + case MP_TOKEN_OP_PLUS: + op = MP_BINARY_OP_ADD; + break; + case MP_TOKEN_OP_MINUS: + op = MP_BINARY_OP_SUBTRACT; + break; + case MP_TOKEN_OP_STAR: + op = MP_BINARY_OP_MULTIPLY; + break; + case MP_TOKEN_OP_DBL_SLASH: + op = MP_BINARY_OP_FLOOR_DIVIDE; + break; + case MP_TOKEN_OP_SLASH: + op = MP_BINARY_OP_TRUE_DIVIDE; + break; + case MP_TOKEN_OP_PERCENT: + op = MP_BINARY_OP_MODULO; + break; + case MP_TOKEN_OP_DBL_LESS: + op = MP_BINARY_OP_LSHIFT; + break; default: assert(tok == MP_TOKEN_OP_DBL_MORE); op = MP_BINARY_OP_RSHIFT; @@ -2168,8 +2222,12 @@ STATIC void compile_factor_2(compiler_t *comp, mp_parse_node_struct_t *pns) { mp_unary_op_t op; mp_token_kind_t tok = MP_PARSE_NODE_LEAF_ARG(pns->nodes[0]); switch (tok) { - case MP_TOKEN_OP_PLUS: op = MP_UNARY_OP_POSITIVE; break; - case MP_TOKEN_OP_MINUS: op = MP_UNARY_OP_NEGATIVE; break; + case MP_TOKEN_OP_PLUS: + op = MP_UNARY_OP_POSITIVE; + break; + case MP_TOKEN_OP_MINUS: + op = MP_UNARY_OP_NEGATIVE; + break; default: assert(tok == MP_TOKEN_OP_TILDE); op = MP_UNARY_OP_INVERT; @@ -2189,10 +2247,10 @@ STATIC void compile_atom_expr_normal(compiler_t *comp, mp_parse_node_struct_t *p // get the array of trailers (known to be an array of PARSE_NODE_STRUCT) size_t num_trail = 1; - mp_parse_node_struct_t **pns_trail = (mp_parse_node_struct_t**)&pns->nodes[1]; + mp_parse_node_struct_t **pns_trail = (mp_parse_node_struct_t **)&pns->nodes[1]; if (MP_PARSE_NODE_STRUCT_KIND(pns_trail[0]) == PN_atom_expr_trailers) { num_trail = MP_PARSE_NODE_STRUCT_NUM_NODES(pns_trail[0]); - pns_trail = (mp_parse_node_struct_t**)&pns_trail[0]->nodes[0]; + pns_trail = (mp_parse_node_struct_t **)&pns_trail[0]->nodes[0]; } // the current index into the array of trailers @@ -2282,7 +2340,7 @@ STATIC void compile_trailer_paren_helper(compiler_t *comp, mp_parse_node_t pn_ar mp_parse_node_struct_t *star_args_node = NULL, *dblstar_args_node = NULL; for (int i = 0; i < n_args; i++) { if (MP_PARSE_NODE_IS_STRUCT(args[i])) { - mp_parse_node_struct_t *pns_arg = (mp_parse_node_struct_t*)args[i]; + mp_parse_node_struct_t *pns_arg = (mp_parse_node_struct_t *)args[i]; if (MP_PARSE_NODE_STRUCT_KIND(pns_arg) == PN_arglist_star) { if (star_flags & MP_EMIT_STAR_FLAG_SINGLE) { compile_syntax_error(comp, (mp_parse_node_t)pns_arg, "can't have multiple *x"); @@ -2314,7 +2372,7 @@ STATIC void compile_trailer_paren_helper(compiler_t *comp, mp_parse_node_t pn_ar goto normal_argument; } } else { - normal_argument: + normal_argument: if (star_flags) { compile_syntax_error(comp, args[i], "non-keyword arg after */**"); return; @@ -2355,7 +2413,7 @@ STATIC void compile_trailer_paren_helper(compiler_t *comp, mp_parse_node_t pn_ar STATIC void compile_comprehension(compiler_t *comp, mp_parse_node_struct_t *pns, scope_kind_t kind) { assert(MP_PARSE_NODE_STRUCT_NUM_NODES(pns) == 2); assert(MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[1], PN_comp_for)); - mp_parse_node_struct_t *pns_comp_for = (mp_parse_node_struct_t*)pns->nodes[1]; + mp_parse_node_struct_t *pns_comp_for = (mp_parse_node_struct_t *)pns->nodes[1]; if (comp->pass == MP_PASS_SCOPE) { // create a new scope for this comprehension @@ -2365,7 +2423,7 @@ STATIC void compile_comprehension(compiler_t *comp, mp_parse_node_struct_t *pns, } // get the scope for this comprehension - scope_t *this_scope = (scope_t*)pns_comp_for->nodes[3]; + scope_t *this_scope = (scope_t *)pns_comp_for->nodes[3]; // compile the comprehension close_over_variables_etc(comp, this_scope, 0, 0); @@ -2383,10 +2441,10 @@ STATIC void compile_atom_paren(compiler_t *comp, mp_parse_node_struct_t *pns) { c_tuple(comp, MP_PARSE_NODE_NULL, NULL); } else { assert(MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[0], PN_testlist_comp)); - pns = (mp_parse_node_struct_t*)pns->nodes[0]; + pns = (mp_parse_node_struct_t *)pns->nodes[0]; assert(!MP_PARSE_NODE_IS_NULL(pns->nodes[1])); if (MP_PARSE_NODE_IS_STRUCT(pns->nodes[1])) { - mp_parse_node_struct_t *pns2 = (mp_parse_node_struct_t*)pns->nodes[1]; + mp_parse_node_struct_t *pns2 = (mp_parse_node_struct_t *)pns->nodes[1]; if (MP_PARSE_NODE_STRUCT_KIND(pns2) == PN_testlist_comp_3b) { // tuple of one item, with trailing comma assert(MP_PARSE_NODE_IS_NULL(pns2->nodes[0])); @@ -2403,7 +2461,7 @@ STATIC void compile_atom_paren(compiler_t *comp, mp_parse_node_struct_t *pns) { } } else { // tuple with 2 items - tuple_with_2_items: + tuple_with_2_items: c_tuple(comp, MP_PARSE_NODE_NULL, pns); } } @@ -2414,9 +2472,9 @@ STATIC void compile_atom_bracket(compiler_t *comp, mp_parse_node_struct_t *pns) // empty list EMIT_ARG(build, 0, MP_EMIT_BUILD_LIST); } else if (MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[0], PN_testlist_comp)) { - mp_parse_node_struct_t *pns2 = (mp_parse_node_struct_t*)pns->nodes[0]; + mp_parse_node_struct_t *pns2 = (mp_parse_node_struct_t *)pns->nodes[0]; if (MP_PARSE_NODE_IS_STRUCT(pns2->nodes[1])) { - mp_parse_node_struct_t *pns3 = (mp_parse_node_struct_t*)pns2->nodes[1]; + mp_parse_node_struct_t *pns3 = (mp_parse_node_struct_t *)pns2->nodes[1]; if (MP_PARSE_NODE_STRUCT_KIND(pns3) == PN_testlist_comp_3b) { // list of one item, with trailing comma assert(MP_PARSE_NODE_IS_NULL(pns3->nodes[0])); @@ -2436,7 +2494,7 @@ STATIC void compile_atom_bracket(compiler_t *comp, mp_parse_node_struct_t *pns) } } else { // list with 2 items - list_with_2_items: + list_with_2_items: compile_node(comp, pns2->nodes[0]); compile_node(comp, pns2->nodes[1]); EMIT_ARG(build, 2, MP_EMIT_BUILD_LIST); @@ -2454,7 +2512,7 @@ STATIC void compile_atom_brace(compiler_t *comp, mp_parse_node_struct_t *pns) { // empty dict EMIT_ARG(build, 0, MP_EMIT_BUILD_MAP); } else if (MP_PARSE_NODE_IS_STRUCT(pn)) { - pns = (mp_parse_node_struct_t*)pn; + pns = (mp_parse_node_struct_t *)pn; if (MP_PARSE_NODE_STRUCT_KIND(pns) == PN_dictorsetmaker_item) { // dict with one element EMIT_ARG(build, 1, MP_EMIT_BUILD_MAP); @@ -2462,7 +2520,7 @@ STATIC void compile_atom_brace(compiler_t *comp, mp_parse_node_struct_t *pns) { EMIT(store_map); } else if (MP_PARSE_NODE_STRUCT_KIND(pns) == PN_dictorsetmaker) { assert(MP_PARSE_NODE_IS_STRUCT(pns->nodes[1])); // should succeed - mp_parse_node_struct_t *pns1 = (mp_parse_node_struct_t*)pns->nodes[1]; + mp_parse_node_struct_t *pns1 = (mp_parse_node_struct_t *)pns->nodes[1]; if (MP_PARSE_NODE_STRUCT_KIND(pns1) == PN_dictorsetmaker_list) { // dict/set with multiple elements @@ -2534,7 +2592,7 @@ STATIC void compile_atom_brace(compiler_t *comp, mp_parse_node_struct_t *pns) { } } else { // set with one element - set_with_one_element: + set_with_one_element: #if MICROPY_PY_BUILTINS_SET compile_node(comp, pn); EMIT_ARG(build, 1, MP_EMIT_BUILD_SET); @@ -2564,7 +2622,7 @@ STATIC void compile_subscript(compiler_t *comp, mp_parse_node_struct_t *pns) { if (MP_PARSE_NODE_STRUCT_KIND(pns) == PN_subscript_2) { compile_node(comp, pns->nodes[0]); // start of slice assert(MP_PARSE_NODE_IS_STRUCT(pns->nodes[1])); // should always be - pns = (mp_parse_node_struct_t*)pns->nodes[1]; + pns = (mp_parse_node_struct_t *)pns->nodes[1]; } else { // pns is a PN_subscript_3, load None for start of slice EMIT_ARG(load_const_tok, MP_TOKEN_KW_NONE); @@ -2577,7 +2635,7 @@ STATIC void compile_subscript(compiler_t *comp, mp_parse_node_struct_t *pns) { EMIT_ARG(load_const_tok, MP_TOKEN_KW_NONE); EMIT_ARG(build, 2, MP_EMIT_BUILD_SLICE); } else if (MP_PARSE_NODE_IS_STRUCT(pn)) { - pns = (mp_parse_node_struct_t*)pn; + pns = (mp_parse_node_struct_t *)pn; if (MP_PARSE_NODE_STRUCT_KIND(pns) == PN_subscript_3c) { EMIT_ARG(load_const_tok, MP_TOKEN_KW_NONE); pn = pns->nodes[0]; @@ -2592,7 +2650,7 @@ STATIC void compile_subscript(compiler_t *comp, mp_parse_node_struct_t *pns) { } else if (MP_PARSE_NODE_STRUCT_KIND(pns) == PN_subscript_3d) { compile_node(comp, pns->nodes[0]); assert(MP_PARSE_NODE_IS_STRUCT(pns->nodes[1])); // should always be - pns = (mp_parse_node_struct_t*)pns->nodes[1]; + pns = (mp_parse_node_struct_t *)pns->nodes[1]; assert(MP_PARSE_NODE_STRUCT_KIND(pns) == PN_sliceop); // should always be if (MP_PARSE_NODE_IS_NULL(pns->nodes[0])) { // [?:x:] @@ -2637,7 +2695,7 @@ STATIC void compile_yield_expr(compiler_t *comp, mp_parse_node_struct_t *pns) { EMIT_ARG(yield, MP_EMIT_YIELD_VALUE); reserve_labels_for_native(comp, 1); } else if (MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[0], PN_yield_arg_from)) { - pns = (mp_parse_node_struct_t*)pns->nodes[0]; + pns = (mp_parse_node_struct_t *)pns->nodes[0]; compile_node(comp, pns->nodes[0]); compile_yield_from(comp); } else { @@ -2674,13 +2732,13 @@ STATIC void compile_const_object(compiler_t *comp, mp_parse_node_struct_t *pns) EMIT_ARG(load_const_obj, get_const_object(pns)); } -typedef void (*compile_function_t)(compiler_t*, mp_parse_node_struct_t*); +typedef void (*compile_function_t)(compiler_t *, mp_parse_node_struct_t *); STATIC const compile_function_t compile_function[] = { // only define rules with a compile function #define c(f) compile_##f #define DEF_RULE(rule, comp, kind, ...) comp, #define DEF_RULE_NC(rule, kind, ...) -#include "py/grammar.h" + #include "py/grammar.h" #undef c #undef DEF_RULE #undef DEF_RULE_NC @@ -2715,8 +2773,12 @@ STATIC void compile_node(compiler_t *comp, mp_parse_node_t pn) { } 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: compile_load_id(comp, arg); break; - case MP_PARSE_NODE_STRING: EMIT_ARG(load_const_str, arg); break; + case MP_PARSE_NODE_ID: + compile_load_id(comp, arg); + break; + case MP_PARSE_NODE_STRING: + EMIT_ARG(load_const_str, arg); + break; case MP_PARSE_NODE_BYTES: // only create and load the actual bytes object on the last pass if (comp->pass != MP_PASS_EMIT) { @@ -2730,18 +2792,19 @@ STATIC void compile_node(compiler_t *comp, mp_parse_node_t pn) { comp->scope_cur->scope_flags |= MP_SCOPE_FLAG_HASCONSTS; #endif break; - case MP_PARSE_NODE_TOKEN: default: + case MP_PARSE_NODE_TOKEN: + default: if (arg == MP_TOKEN_NEWLINE) { // this can occur when file_input lets through a NEWLINE (eg if file starts with a newline) // or when single_input lets through a NEWLINE (user enters a blank line) // do nothing } else { - EMIT_ARG(load_const_tok, arg); + EMIT_ARG(load_const_tok, arg); } break; } } else { - mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)pn; + mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn; EMIT_ARG(set_source_line, pns->source_line); assert(MP_PARSE_NODE_STRUCT_KIND(pns) <= PN_const_object); compile_function_t f = compile_function[MP_PARSE_NODE_STRUCT_KIND(pns)]; @@ -2789,7 +2852,7 @@ STATIC void compile_scope_func_lambda_param(compiler_t *comp, mp_parse_node_t pn } } else { assert(MP_PARSE_NODE_IS_STRUCT(pn)); - pns = (mp_parse_node_struct_t*)pn; + pns = (mp_parse_node_struct_t *)pn; if (MP_PARSE_NODE_STRUCT_KIND(pns) == pn_name) { // named parameter with possible annotation param_name = MP_PARSE_NODE_LEAF_ARG(pns->nodes[0]); @@ -2811,7 +2874,7 @@ STATIC void compile_scope_func_lambda_param(compiler_t *comp, mp_parse_node_t pn if (MP_PARSE_NODE_IS_NULL(pns->nodes[0])) { // bare star // TODO see http://www.python.org/dev/peps/pep-3102/ - //assert(comp->scope_cur->num_dict_params == 0); + // assert(comp->scope_cur->num_dict_params == 0); pns = NULL; } else if (MP_PARSE_NODE_IS_ID(pns->nodes[0])) { // named star @@ -2822,7 +2885,7 @@ STATIC void compile_scope_func_lambda_param(compiler_t *comp, mp_parse_node_t pn assert(MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[0], PN_tfpdef)); // should be // named star with possible annotation comp->scope_cur->scope_flags |= MP_SCOPE_FLAG_VARARGS; - pns = (mp_parse_node_struct_t*)pns->nodes[0]; + pns = (mp_parse_node_struct_t *)pns->nodes[0]; param_name = MP_PARSE_NODE_LEAF_ARG(pns->nodes[0]); } } else { @@ -2869,7 +2932,7 @@ STATIC void compile_scope_comp_iter(compiler_t *comp, mp_parse_node_struct_t *pn c_assign(comp, pns_comp_for->nodes[0], ASSIGN_STORE); mp_parse_node_t pn_iter = pns_comp_for->nodes[2]; - tail_recursion: +tail_recursion: if (MP_PARSE_NODE_IS_NULL(pn_iter)) { // no more nested if/for; compile inner expression compile_node(comp, pn_inner_expr); @@ -2880,16 +2943,16 @@ STATIC void compile_scope_comp_iter(compiler_t *comp, mp_parse_node_struct_t *pn } else { EMIT_ARG(store_comp, comp->scope_cur->kind, 4 * for_depth + 5); } - } else if (MP_PARSE_NODE_STRUCT_KIND((mp_parse_node_struct_t*)pn_iter) == PN_comp_if) { + } else if (MP_PARSE_NODE_STRUCT_KIND((mp_parse_node_struct_t *)pn_iter) == PN_comp_if) { // if condition - mp_parse_node_struct_t *pns_comp_if = (mp_parse_node_struct_t*)pn_iter; + mp_parse_node_struct_t *pns_comp_if = (mp_parse_node_struct_t *)pn_iter; c_if_cond(comp, pns_comp_if->nodes[0], false, l_top); pn_iter = pns_comp_if->nodes[1]; goto tail_recursion; } else { - assert(MP_PARSE_NODE_STRUCT_KIND((mp_parse_node_struct_t*)pn_iter) == PN_comp_for); // should be + assert(MP_PARSE_NODE_STRUCT_KIND((mp_parse_node_struct_t *)pn_iter) == PN_comp_for); // should be // for loop - mp_parse_node_struct_t *pns_comp_for2 = (mp_parse_node_struct_t*)pn_iter; + mp_parse_node_struct_t *pns_comp_for2 = (mp_parse_node_struct_t *)pn_iter; compile_node(comp, pns_comp_for2->nodes[1]); EMIT_ARG(get_iter, true); compile_scope_comp_iter(comp, pns_comp_for2, pn_inner_expr, for_depth + 1); @@ -2901,7 +2964,7 @@ STATIC void compile_scope_comp_iter(compiler_t *comp, mp_parse_node_struct_t *pn } STATIC void check_for_doc_string(compiler_t *comp, mp_parse_node_t pn) { -#if MICROPY_ENABLE_DOC_STRING + #if MICROPY_ENABLE_DOC_STRING // see http://www.python.org/dev/peps/pep-0257/ // look for the first statement @@ -2909,7 +2972,7 @@ STATIC void check_for_doc_string(compiler_t *comp, mp_parse_node_t pn) { // a statement; fall through } else if (MP_PARSE_NODE_IS_STRUCT_KIND(pn, PN_file_input_2)) { // file input; find the first non-newline node - mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)pn; + mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn; int num_nodes = MP_PARSE_NODE_STRUCT_NUM_NODES(pns); for (int i = 0; i < num_nodes; i++) { pn = pns->nodes[i]; @@ -2921,28 +2984,28 @@ STATIC void check_for_doc_string(compiler_t *comp, mp_parse_node_t pn) { // if we didn't find a non-newline then it's okay to fall through; pn will be a newline and so doc-string test below will fail gracefully } else if (MP_PARSE_NODE_IS_STRUCT_KIND(pn, PN_suite_block_stmts)) { // a list of statements; get the first one - pn = ((mp_parse_node_struct_t*)pn)->nodes[0]; + pn = ((mp_parse_node_struct_t *)pn)->nodes[0]; } else { return; } // check the first statement for a doc string if (MP_PARSE_NODE_IS_STRUCT_KIND(pn, PN_expr_stmt)) { - mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)pn; + mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn; if ((MP_PARSE_NODE_IS_LEAF(pns->nodes[0]) - && MP_PARSE_NODE_LEAF_KIND(pns->nodes[0]) == MP_PARSE_NODE_STRING) + && MP_PARSE_NODE_LEAF_KIND(pns->nodes[0]) == MP_PARSE_NODE_STRING) || (MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[0], PN_const_object) - && MP_OBJ_IS_STR(get_const_object((mp_parse_node_struct_t*)pns->nodes[0])))) { - // compile the doc string - compile_node(comp, pns->nodes[0]); - // store the doc string - compile_store_id(comp, MP_QSTR___doc__); + && MP_OBJ_IS_STR(get_const_object((mp_parse_node_struct_t *)pns->nodes[0])))) { + // compile the doc string + compile_node(comp, pns->nodes[0]); + // store the doc string + compile_store_id(comp, MP_QSTR___doc__); } } -#else + #else (void)comp; (void)pn; -#endif + #endif } STATIC void compile_scope(compiler_t *comp, scope_t *scope, pass_kind_t pass) { @@ -2962,7 +3025,7 @@ STATIC void compile_scope(compiler_t *comp, scope_t *scope, pass_kind_t pass) { // compile if (MP_PARSE_NODE_IS_STRUCT_KIND(scope->pn, PN_eval_input)) { assert(scope->kind == SCOPE_MODULE); - mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)scope->pn; + mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)scope->pn; compile_node(comp, pns->nodes[0]); // compile the expression EMIT(return_value); } else if (scope->kind == SCOPE_MODULE) { @@ -2974,7 +3037,7 @@ STATIC void compile_scope(compiler_t *comp, scope_t *scope, pass_kind_t pass) { EMIT(return_value); } else if (scope->kind == SCOPE_FUNCTION) { assert(MP_PARSE_NODE_IS_STRUCT(scope->pn)); - mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)scope->pn; + mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)scope->pn; assert(MP_PARSE_NODE_STRUCT_KIND(pns) == PN_funcdef); // work out number of parameters, keywords and default parameters, and add them to the id_info array @@ -2999,7 +3062,7 @@ STATIC void compile_scope(compiler_t *comp, scope_t *scope, pass_kind_t pass) { } } else if (scope->kind == SCOPE_LAMBDA) { assert(MP_PARSE_NODE_IS_STRUCT(scope->pn)); - mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)scope->pn; + mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)scope->pn; assert(MP_PARSE_NODE_STRUCT_NUM_NODES(pns) == 3); // work out number of parameters, keywords and default parameters, and add them to the id_info array @@ -3021,10 +3084,10 @@ STATIC void compile_scope(compiler_t *comp, scope_t *scope, pass_kind_t pass) { // a bit of a hack at the moment assert(MP_PARSE_NODE_IS_STRUCT(scope->pn)); - mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)scope->pn; + mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)scope->pn; assert(MP_PARSE_NODE_STRUCT_NUM_NODES(pns) == 2); assert(MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[1], PN_comp_for)); - mp_parse_node_struct_t *pns_comp_for = (mp_parse_node_struct_t*)pns->nodes[1]; + mp_parse_node_struct_t *pns_comp_for = (mp_parse_node_struct_t *)pns->nodes[1]; // We need a unique name for the comprehension argument (the iterator). // CPython uses .0, but we should be able to use anything that won't @@ -3068,7 +3131,7 @@ STATIC void compile_scope(compiler_t *comp, scope_t *scope, pass_kind_t pass) { } else { assert(scope->kind == SCOPE_CLASS); assert(MP_PARSE_NODE_IS_STRUCT(scope->pn)); - mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)scope->pn; + mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)scope->pn; assert(MP_PARSE_NODE_STRUCT_KIND(pns) == PN_classdef); if (comp->pass == MP_PASS_SCOPE) { @@ -3117,10 +3180,10 @@ STATIC void compile_scope_inline_asm(compiler_t *comp, scope_t *scope, pass_kind // get the function definition parse node assert(MP_PARSE_NODE_IS_STRUCT(scope->pn)); - mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)scope->pn; + mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)scope->pn; assert(MP_PARSE_NODE_STRUCT_KIND(pns) == PN_funcdef); - //qstr f_id = MP_PARSE_NODE_LEAF_ARG(pns->nodes[0]); // function name + // qstr f_id = MP_PARSE_NODE_LEAF_ARG(pns->nodes[0]); // function name // parameters are in pns->nodes[1] if (comp->pass == MP_PASS_CODE_SIZE) { @@ -3140,11 +3203,21 @@ STATIC void compile_scope_inline_asm(compiler_t *comp, scope_t *scope, pass_kind if (MP_PARSE_NODE_IS_ID(pn_annotation)) { qstr ret_type = MP_PARSE_NODE_LEAF_ARG(pn_annotation); switch (ret_type) { - case MP_QSTR_object: type_sig = MP_NATIVE_TYPE_OBJ; break; - case MP_QSTR_bool: type_sig = MP_NATIVE_TYPE_BOOL; break; - case MP_QSTR_int: type_sig = MP_NATIVE_TYPE_INT; break; - case MP_QSTR_uint: type_sig = MP_NATIVE_TYPE_UINT; break; - default: compile_syntax_error(comp, pn_annotation, "unknown type"); return; + case MP_QSTR_object: + type_sig = MP_NATIVE_TYPE_OBJ; + break; + case MP_QSTR_bool: + type_sig = MP_NATIVE_TYPE_BOOL; + break; + case MP_QSTR_int: + type_sig = MP_NATIVE_TYPE_INT; + break; + case MP_QSTR_uint: + type_sig = MP_NATIVE_TYPE_UINT; + break; + default: + compile_syntax_error(comp, pn_annotation, "unknown type"); + return; } } else { compile_syntax_error(comp, pn_annotation, "return annotation must be an identifier"); @@ -3157,7 +3230,7 @@ STATIC void compile_scope_inline_asm(compiler_t *comp, scope_t *scope, pass_kind for (int i = 0; i < num; i++) { assert(MP_PARSE_NODE_IS_STRUCT(nodes[i])); - mp_parse_node_struct_t *pns2 = (mp_parse_node_struct_t*)nodes[i]; + mp_parse_node_struct_t *pns2 = (mp_parse_node_struct_t *)nodes[i]; if (MP_PARSE_NODE_STRUCT_KIND(pns2) == PN_pass_stmt) { // no instructions continue; @@ -3173,7 +3246,7 @@ STATIC void compile_scope_inline_asm(compiler_t *comp, scope_t *scope, pass_kind if (!MP_PARSE_NODE_IS_NULL(pns2->nodes[1])) { goto not_an_instruction; } - pns2 = (mp_parse_node_struct_t*)pns2->nodes[0]; + pns2 = (mp_parse_node_struct_t *)pns2->nodes[0]; if (MP_PARSE_NODE_STRUCT_KIND(pns2) != PN_atom_expr_normal) { goto not_an_instruction; } @@ -3187,7 +3260,7 @@ STATIC void compile_scope_inline_asm(compiler_t *comp, scope_t *scope, pass_kind // parse node looks like an instruction // get instruction name and args qstr op = MP_PARSE_NODE_LEAF_ARG(pns2->nodes[0]); - pns2 = (mp_parse_node_struct_t*)pns2->nodes[1]; // PN_trailer_paren + pns2 = (mp_parse_node_struct_t *)pns2->nodes[1]; // PN_trailer_paren mp_parse_node_t *pn_arg; int n_args = mp_parse_node_extract_list(&pns2->nodes[0], PN_arglist, &pn_arg); @@ -3210,7 +3283,7 @@ STATIC void compile_scope_inline_asm(compiler_t *comp, scope_t *scope, pass_kind return; } if (pass > MP_PASS_SCOPE) { - mp_asm_base_align((mp_asm_base_t*)comp->emit_inline_asm, + mp_asm_base_align((mp_asm_base_t *)comp->emit_inline_asm, MP_PARSE_NODE_LEAF_SMALL_INT(pn_arg[0])); } } else if (op == MP_QSTR_data) { @@ -3225,7 +3298,7 @@ STATIC void compile_scope_inline_asm(compiler_t *comp, scope_t *scope, pass_kind compile_syntax_error(comp, nodes[i], "'data' requires integer arguments"); return; } - mp_asm_base_data((mp_asm_base_t*)comp->emit_inline_asm, + mp_asm_base_data((mp_asm_base_t *)comp->emit_inline_asm, bytesize, MP_PARSE_NODE_LEAF_SMALL_INT(pn_arg[j])); } } @@ -3245,9 +3318,9 @@ STATIC void compile_scope_inline_asm(compiler_t *comp, scope_t *scope, pass_kind EMIT_INLINE_ASM_ARG(end_pass, type_sig); if (comp->pass == MP_PASS_EMIT) { - void *f = mp_asm_base_get_code((mp_asm_base_t*)comp->emit_inline_asm); + void *f = mp_asm_base_get_code((mp_asm_base_t *)comp->emit_inline_asm); mp_emit_glue_assign_native(comp->scope_cur->raw_code, MP_CODE_NATIVE_ASM, - f, mp_asm_base_get_code_size((mp_asm_base_t*)comp->emit_inline_asm), + f, mp_asm_base_get_code_size((mp_asm_base_t *)comp->emit_inline_asm), NULL, comp->scope_cur->num_pos_args, 0, type_sig); } } @@ -3269,7 +3342,9 @@ STATIC void scope_compute_things(scope_t *scope) { if (id->flags & ID_FLAG_IS_STAR_PARAM) { if (id_param != NULL) { // swap star param with last param - id_info_t temp = *id_param; *id_param = *id; *id = temp; + id_info_t temp = *id_param; + *id_param = *id; + *id = temp; } break; } else if (id_param == NULL && id->flags == ID_FLAG_IS_PARAM) { @@ -3409,9 +3484,9 @@ mp_raw_code_t *mp_compile_to_raw_code(mp_parse_tree_t *parse_tree, qstr source_f emit_bc_set_max_num_labels(emit_bc, max_num_labels); // compile pass 2 and 3 -#if MICROPY_EMIT_NATIVE + #if MICROPY_EMIT_NATIVE emit_t *emit_native = NULL; -#endif + #endif for (scope_t *s = comp->scope_head; s != NULL && comp->compile_error == MP_OBJ_NULL; s = s->next) { if (false) { // dummy @@ -3442,7 +3517,7 @@ mp_raw_code_t *mp_compile_to_raw_code(mp_parse_tree_t *parse_tree, qstr source_f switch (s->emit_options) { -#if MICROPY_EMIT_NATIVE + #if MICROPY_EMIT_NATIVE case MP_EMIT_OPT_NATIVE_PYTHON: case MP_EMIT_OPT_VIPER: if (emit_native == NULL) { @@ -3451,7 +3526,7 @@ mp_raw_code_t *mp_compile_to_raw_code(mp_parse_tree_t *parse_tree, qstr source_f comp->emit_method_table = &NATIVE_EMITTER(method_table); comp->emit = emit_native; break; -#endif // MICROPY_EMIT_NATIVE + #endif // MICROPY_EMIT_NATIVE default: comp->emit = emit_bc; @@ -3488,11 +3563,11 @@ mp_raw_code_t *mp_compile_to_raw_code(mp_parse_tree_t *parse_tree, qstr source_f // free the emitters emit_bc_free(emit_bc); -#if MICROPY_EMIT_NATIVE + #if MICROPY_EMIT_NATIVE if (emit_native != NULL) { NATIVE_EMITTER(free)(emit_native); } -#endif + #endif #if MICROPY_EMIT_INLINE_ASM if (comp->emit_inline_asm != NULL) { ASM_EMITTER(free)(comp->emit_inline_asm); diff --git a/py/emit.h b/py/emit.h index 3c42bdf143..170f0aa3c4 100644 --- a/py/emit.h +++ b/py/emit.h @@ -184,7 +184,7 @@ emit_t *emit_native_thumb_new(mp_obj_t *error_slot, uint *label_slot, mp_uint_t emit_t *emit_native_arm_new(mp_obj_t *error_slot, uint *label_slot, mp_uint_t max_num_labels); emit_t *emit_native_xtensa_new(mp_obj_t *error_slot, uint *label_slot, mp_uint_t max_num_labels); -void emit_bc_set_max_num_labels(emit_t* emit, mp_uint_t max_num_labels); +void emit_bc_set_max_num_labels(emit_t *emit, mp_uint_t max_num_labels); void emit_bc_free(emit_t *emit); void emit_native_x64_free(emit_t *emit); diff --git a/py/emitbc.c b/py/emitbc.c index 6a46cfb593..ba09029f99 100644 --- a/py/emitbc.c +++ b/py/emitbc.c @@ -107,7 +107,7 @@ STATIC void emit_write_uint(emit_t *emit, emit_allocator_t allocator, mp_uint_t // all functions must go through this one to emit code info STATIC byte *emit_get_cur_to_write_code_info(emit_t *emit, int num_bytes_to_write) { - //printf("emit %d\n", num_bytes_to_write); + // printf("emit %d\n", num_bytes_to_write); if (emit->pass < MP_PASS_EMIT) { emit->code_info_offset += num_bytes_to_write; return emit->dummy_data; @@ -119,11 +119,11 @@ STATIC byte *emit_get_cur_to_write_code_info(emit_t *emit, int num_bytes_to_writ } } -STATIC void emit_write_code_info_byte(emit_t* emit, byte val) { +STATIC void emit_write_code_info_byte(emit_t *emit, byte val) { *emit_get_cur_to_write_code_info(emit, 1) = val; } -STATIC void emit_write_code_info_uint(emit_t* emit, mp_uint_t val) { +STATIC void emit_write_code_info_uint(emit_t *emit, mp_uint_t val) { emit_write_uint(emit, emit_get_cur_to_write_code_info, val); } @@ -141,7 +141,7 @@ STATIC void emit_write_code_info_qstr(emit_t *emit, qstr qst) { #if MICROPY_ENABLE_SOURCE_LINE STATIC void emit_write_code_info_bytes_lines(emit_t *emit, mp_uint_t bytes_to_skip, mp_uint_t lines_to_skip) { assert(bytes_to_skip > 0 || lines_to_skip > 0); - //printf(" %d %d\n", bytes_to_skip, lines_to_skip); + // printf(" %d %d\n", bytes_to_skip, lines_to_skip); while (bytes_to_skip > 0 || lines_to_skip > 0) { mp_uint_t b, l; if (lines_to_skip <= 6 || bytes_to_skip > 0xf) { @@ -170,7 +170,7 @@ STATIC void emit_write_code_info_bytes_lines(emit_t *emit, mp_uint_t bytes_to_sk // all functions must go through this one to emit byte code STATIC byte *emit_get_cur_to_write_bytecode(emit_t *emit, int num_bytes_to_write) { - //printf("emit %d\n", num_bytes_to_write); + // printf("emit %d\n", num_bytes_to_write); if (emit->pass < MP_PASS_EMIT) { emit->bytecode_offset += num_bytes_to_write; return emit->dummy_data; @@ -187,7 +187,7 @@ STATIC void emit_write_bytecode_byte(emit_t *emit, byte b1) { c[0] = b1; } -STATIC void emit_write_bytecode_byte_byte(emit_t* emit, byte b1, byte b2) { +STATIC void emit_write_bytecode_byte_byte(emit_t *emit, byte b1, byte b2) { byte *c = emit_get_cur_to_write_bytecode(emit, 2); c[0] = b1; c[1] = b2; @@ -234,7 +234,7 @@ STATIC void emit_write_bytecode_byte_const(emit_t *emit, byte b, mp_uint_t n, mp } #endif -STATIC void emit_write_bytecode_byte_qstr(emit_t* emit, byte b, qstr qst) { +STATIC void emit_write_bytecode_byte_qstr(emit_t *emit, byte b, qstr qst) { #if MICROPY_PERSISTENT_CODE assert((qst >> 16) == 0); byte *c = emit_get_cur_to_write_bytecode(emit, 3); @@ -255,7 +255,7 @@ STATIC void emit_write_bytecode_byte_obj(emit_t *emit, byte b, mp_obj_t obj) { // aligns the pointer so it is friendly to GC emit_write_bytecode_byte(emit, b); emit->bytecode_offset = (size_t)MP_ALIGN(emit->bytecode_offset, sizeof(mp_obj_t)); - mp_obj_t *c = (mp_obj_t*)emit_get_cur_to_write_bytecode(emit, sizeof(mp_obj_t)); + mp_obj_t *c = (mp_obj_t *)emit_get_cur_to_write_bytecode(emit, sizeof(mp_obj_t)); // Verify thar c is already uint-aligned assert(c == MP_ALIGN(c, sizeof(mp_obj_t))); *c = obj; @@ -270,10 +270,10 @@ STATIC void emit_write_bytecode_byte_raw_code(emit_t *emit, byte b, mp_raw_code_ #else // aligns the pointer so it is friendly to GC emit_write_bytecode_byte(emit, b); - emit->bytecode_offset = (size_t)MP_ALIGN(emit->bytecode_offset, sizeof(void*)); - void **c = (void**)emit_get_cur_to_write_bytecode(emit, sizeof(void*)); + emit->bytecode_offset = (size_t)MP_ALIGN(emit->bytecode_offset, sizeof(void *)); + void **c = (void **)emit_get_cur_to_write_bytecode(emit, sizeof(void *)); // Verify thar c is already uint-aligned - assert(c == MP_ALIGN(c, sizeof(void*))); + assert(c == MP_ALIGN(c, sizeof(void *))); *c = rc; #endif } @@ -351,7 +351,7 @@ void mp_emit_bc_start_pass(emit_t *emit, pass_kind_t pass, scope_t *scope) { // for it and hope that is enough! TODO assert this or something. if (pass == MP_PASS_EMIT) { emit_write_code_info_uint(emit, emit->code_info_size - emit->code_info_offset); - } else { + } else { emit_get_cur_to_write_code_info(emit, 2); } @@ -473,8 +473,8 @@ static inline void emit_bc_pre(emit_t *emit, mp_int_t stack_size_delta) { } void mp_emit_bc_set_source_line(emit_t *emit, mp_uint_t source_line) { - //printf("source: line %d -> %d offset %d -> %d\n", emit->last_source_line, source_line, emit->last_source_line_offset, emit->bytecode_offset); -#if MICROPY_ENABLE_SOURCE_LINE + // printf("source: line %d -> %d offset %d -> %d\n", emit->last_source_line, source_line, emit->last_source_line_offset, emit->bytecode_offset); + #if MICROPY_ENABLE_SOURCE_LINE if (MP_STATE_VM(mp_optimise_value) >= 3) { // If we compile with -O3, don't store line numbers. return; @@ -486,10 +486,10 @@ void mp_emit_bc_set_source_line(emit_t *emit, mp_uint_t source_line) { emit->last_source_line_offset = emit->bytecode_offset; emit->last_source_line = source_line; } -#else + #else (void)emit; (void)source_line; -#endif + #endif } void mp_emit_bc_label_assign(emit_t *emit, mp_uint_t l) { @@ -526,9 +526,15 @@ void mp_emit_bc_import(emit_t *emit, qstr qst, int kind) { void mp_emit_bc_load_const_tok(emit_t *emit, mp_token_kind_t tok) { emit_bc_pre(emit, 1); switch (tok) { - case MP_TOKEN_KW_FALSE: emit_write_bytecode_byte(emit, MP_BC_LOAD_CONST_FALSE); break; - case MP_TOKEN_KW_NONE: emit_write_bytecode_byte(emit, MP_BC_LOAD_CONST_NONE); break; - case MP_TOKEN_KW_TRUE: emit_write_bytecode_byte(emit, MP_BC_LOAD_CONST_TRUE); break; + case MP_TOKEN_KW_FALSE: + emit_write_bytecode_byte(emit, MP_BC_LOAD_CONST_FALSE); + break; + case MP_TOKEN_KW_NONE: + emit_write_bytecode_byte(emit, MP_BC_LOAD_CONST_NONE); + break; + case MP_TOKEN_KW_TRUE: + emit_write_bytecode_byte(emit, MP_BC_LOAD_CONST_TRUE); + break; default: assert(tok == MP_TOKEN_ELLIPSIS); emit_write_bytecode_byte_obj(emit, MP_BC_LOAD_CONST_OBJ, MP_OBJ_FROM_PTR(&mp_const_ellipsis_obj)); @@ -728,8 +734,8 @@ void mp_emit_bc_setup_block(emit_t *emit, mp_uint_t label, int kind) { MP_STATIC_ASSERT(MP_BC_SETUP_WITH + MP_EMIT_SETUP_BLOCK_EXCEPT == MP_BC_SETUP_EXCEPT); MP_STATIC_ASSERT(MP_BC_SETUP_WITH + MP_EMIT_SETUP_BLOCK_FINALLY == MP_BC_SETUP_FINALLY); if (kind == MP_EMIT_SETUP_BLOCK_WITH) { - // The SETUP_WITH opcode pops ctx_mgr from the top of the stack - // and then pushes 3 entries: __exit__, ctx_mgr, as_value. + // The SETUP_WITH opcode pops ctx_mgr from the top of the stack + // and then pushes 3 entries: __exit__, ctx_mgr, as_value. emit_bc_pre(emit, 2); } else { emit_bc_pre(emit, 0); @@ -996,4 +1002,4 @@ const mp_emit_method_table_id_ops_t mp_emit_bc_method_table_delete_id_ops = { }; #endif -#endif //MICROPY_ENABLE_COMPILER +#endif // MICROPY_ENABLE_COMPILER diff --git a/py/emitglue.c b/py/emitglue.c index 064a838007..f62fa39b46 100644 --- a/py/emitglue.c +++ b/py/emitglue.c @@ -75,17 +75,17 @@ void mp_emit_glue_assign_bytecode(mp_raw_code_t *rc, const byte *code, rc->data.u_byte.n_raw_code = n_raw_code; #endif -#ifdef DEBUG_PRINT + #ifdef DEBUG_PRINT #if !MICROPY_DEBUG_PRINTERS const size_t len = 0; #endif DEBUG_printf("assign byte code: code=%p len=" UINT_FMT " flags=%x\n", code, len, (uint)scope_flags); -#endif -#if MICROPY_DEBUG_PRINTERS + #endif + #if MICROPY_DEBUG_PRINTERS if (mp_verbose_flag >= 2) { mp_bytecode_print(rc, code, len, const_table); } -#endif + #endif } #if MICROPY_EMIT_NATIVE || MICROPY_EMIT_INLINE_ASM @@ -98,24 +98,24 @@ void mp_emit_glue_assign_native(mp_raw_code_t *rc, mp_raw_code_kind_t kind, void rc->data.u_native.const_table = const_table; rc->data.u_native.type_sig = type_sig; -#ifdef DEBUG_PRINT + #ifdef DEBUG_PRINT DEBUG_printf("assign native: kind=%d fun=%p len=" UINT_FMT " n_pos_args=" UINT_FMT " flags=%x\n", kind, fun_data, fun_len, n_pos_args, (uint)scope_flags); for (mp_uint_t i = 0; i < fun_len; i++) { if (i > 0 && i % 16 == 0) { DEBUG_printf("\n"); } - DEBUG_printf(" %02x", ((byte*)fun_data)[i]); + DEBUG_printf(" %02x", ((byte *)fun_data)[i]); } DEBUG_printf("\n"); -#ifdef WRITE_CODE + #ifdef WRITE_CODE FILE *fp_write_code = fopen("out-code", "wb"); fwrite(fun_data, fun_len, 1, fp_write_code); fclose(fp_write_code); -#endif -#else + #endif + #else (void)fun_len; -#endif + #endif } #endif @@ -138,7 +138,7 @@ mp_obj_t mp_make_function_from_raw_code(const mp_raw_code_t *rc, mp_obj_t def_ar fun = mp_obj_new_fun_native(def_args, def_kw_args, rc->data.u_native.fun_data, rc->data.u_native.const_table); // Check for a generator function, and if so change the type of the object if ((rc->scope_flags & MP_SCOPE_FLAG_GENERATOR) != 0) { - ((mp_obj_base_t*)MP_OBJ_TO_PTR(fun))->type = &mp_type_native_gen_wrap; + ((mp_obj_base_t *)MP_OBJ_TO_PTR(fun))->type = &mp_type_native_gen_wrap; } break; #endif @@ -153,7 +153,7 @@ mp_obj_t mp_make_function_from_raw_code(const mp_raw_code_t *rc, mp_obj_t def_ar fun = mp_obj_new_fun_bc(def_args, def_kw_args, rc->data.u_byte.bytecode, rc->data.u_byte.const_table); // check for generator functions and if so change the type of the object if ((rc->scope_flags & MP_SCOPE_FLAG_GENERATOR) != 0) { - ((mp_obj_base_t*)MP_OBJ_TO_PTR(fun))->type = &mp_type_gen_wrap; + ((mp_obj_base_t *)MP_OBJ_TO_PTR(fun))->type = &mp_type_gen_wrap; } break; } diff --git a/py/emitinlinethumb.c b/py/emitinlinethumb.c index 0649c59edd..8e3975960f 100644 --- a/py/emitinlinethumb.c +++ b/py/emitinlinethumb.c @@ -39,14 +39,14 @@ typedef enum { // define rules with a compile function #define DEF_RULE(rule, comp, kind, ...) PN_##rule, #define DEF_RULE_NC(rule, kind, ...) -#include "py/grammar.h" + #include "py/grammar.h" #undef DEF_RULE #undef DEF_RULE_NC PN_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, ...) PN_##rule, -#include "py/grammar.h" + #include "py/grammar.h" #undef DEF_RULE #undef DEF_RULE_NC } pn_kind_t; @@ -131,7 +131,9 @@ STATIC bool emit_inline_thumb_label(emit_inline_asm_t *emit, mp_uint_t label_num return true; } -typedef struct _reg_name_t { byte reg; byte name[3]; } reg_name_t; +typedef struct _reg_name_t { byte reg; + byte name[3]; +} reg_name_t; STATIC const reg_name_t reg_name_table[] = { {0, "r0\0"}, {1, "r1\0"}, @@ -157,7 +159,9 @@ STATIC const reg_name_t reg_name_table[] = { }; #define MAX_SPECIAL_REGISTER_NAME_LENGTH 7 -typedef struct _special_reg_name_t { byte reg; char name[MAX_SPECIAL_REGISTER_NAME_LENGTH + 1]; } special_reg_name_t; +typedef struct _special_reg_name_t { byte reg; + char name[MAX_SPECIAL_REGISTER_NAME_LENGTH + 1]; +} special_reg_name_t; STATIC const special_reg_name_t special_reg_name_table[] = { {5, "IPSR"}, {17, "BASEPRI"}, @@ -226,8 +230,8 @@ STATIC mp_uint_t get_arg_vfpreg(emit_inline_asm_t *emit, const char *op, mp_pars } if (regno > 31) { emit_inline_thumb_error_exc(emit, - mp_obj_new_exception_msg_varg(&mp_type_SyntaxError, - "'%s' expects at most r%d", op, 31)); + mp_obj_new_exception_msg_varg(&mp_type_SyntaxError, + "'%s' expects at most r%d", op, 31)); return 0; } else { return regno; @@ -235,7 +239,7 @@ STATIC mp_uint_t get_arg_vfpreg(emit_inline_asm_t *emit, const char *op, mp_pars } malformed: emit_inline_thumb_error_exc(emit, - mp_obj_new_exception_msg_varg(&mp_type_SyntaxError, + mp_obj_new_exception_msg_varg(&mp_type_SyntaxError, "'%s' expects an FPU register", op)); return 0; } @@ -248,7 +252,7 @@ STATIC mp_uint_t get_arg_reglist(emit_inline_asm_t *emit, const char *op, mp_par goto bad_arg; } - mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)pn; + mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn; assert(MP_PARSE_NODE_STRUCT_NUM_NODES(pns) == 1); // should always be pn = pns->nodes[0]; @@ -258,10 +262,10 @@ STATIC mp_uint_t get_arg_reglist(emit_inline_asm_t *emit, const char *op, mp_par // set with one element reglist |= 1 << get_arg_reg(emit, op, pn, 15); } else if (MP_PARSE_NODE_IS_STRUCT(pn)) { - pns = (mp_parse_node_struct_t*)pn; + pns = (mp_parse_node_struct_t *)pn; if (MP_PARSE_NODE_STRUCT_KIND(pns) == PN_dictorsetmaker) { assert(MP_PARSE_NODE_IS_STRUCT(pns->nodes[1])); // should succeed - mp_parse_node_struct_t *pns1 = (mp_parse_node_struct_t*)pns->nodes[1]; + mp_parse_node_struct_t *pns1 = (mp_parse_node_struct_t *)pns->nodes[1]; if (MP_PARSE_NODE_STRUCT_KIND(pns1) == PN_dictorsetmaker_list) { // set with multiple elements @@ -311,11 +315,11 @@ STATIC bool get_arg_addr(emit_inline_asm_t *emit, const char *op, mp_parse_node_ if (!MP_PARSE_NODE_IS_STRUCT_KIND(pn, PN_atom_bracket)) { goto bad_arg; } - mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)pn; + mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn; if (!MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[0], PN_testlist_comp)) { goto bad_arg; } - pns = (mp_parse_node_struct_t*)pns->nodes[0]; + pns = (mp_parse_node_struct_t *)pns->nodes[0]; if (MP_PARSE_NODE_STRUCT_NUM_NODES(pns) != 2) { goto bad_arg; } @@ -347,7 +351,9 @@ STATIC int get_arg_label(emit_inline_asm_t *emit, const char *op, mp_parse_node_ return 0; } -typedef struct _cc_name_t { byte cc; byte name[2]; } cc_name_t; +typedef struct _cc_name_t { byte cc; + byte name[2]; +} cc_name_t; STATIC const cc_name_t cc_name_table[] = { { ASM_THUMB_CC_EQ, "eq" }, { ASM_THUMB_CC_NE, "ne" }, @@ -365,7 +371,9 @@ STATIC const cc_name_t cc_name_table[] = { { ASM_THUMB_CC_LE, "le" }, }; -typedef struct _format_4_op_t { byte op; char name[3]; } format_4_op_t; +typedef struct _format_4_op_t { byte op; + char name[3]; +} format_4_op_t; #define X(x) (((x) >> 4) & 0xff) // only need 1 byte to distinguish these ops STATIC const format_4_op_t format_4_op_table[] = { { X(ASM_THUMB_FORMAT_4_EOR), "eor" }, @@ -387,7 +395,9 @@ STATIC const format_4_op_t format_4_op_table[] = { #undef X // name is actually a qstr, which should fit in 16 bits -typedef struct _format_9_10_op_t { uint16_t op; uint16_t name; } format_9_10_op_t; +typedef struct _format_9_10_op_t { uint16_t op; + uint16_t name; +} format_9_10_op_t; #define X(x) (x) STATIC const format_9_10_op_t format_9_10_op_table[] = { { X(ASM_THUMB_FORMAT_9_LDR | ASM_THUMB_FORMAT_9_WORD_TRANSFER), MP_QSTR_ldr }, @@ -401,7 +411,9 @@ STATIC const format_9_10_op_t format_9_10_op_table[] = { #if MICROPY_EMIT_INLINE_THUMB_FLOAT // actual opcodes are: 0xee00 | op.hi_nibble, 0x0a00 | op.lo_nibble -typedef struct _format_vfp_op_t { byte op; char name[3]; } format_vfp_op_t; +typedef struct _format_vfp_op_t { byte op; + char name[3]; +} format_vfp_op_t; STATIC const format_vfp_op_t format_vfp_op_table[] = { { 0x30, "add" }, { 0x34, "sub" }, @@ -425,7 +437,7 @@ STATIC void emit_inline_thumb_op(emit_inline_asm_t *emit, qstr op, mp_uint_t n_a // "subs", RLO, RLO, I3, asm_thumb_subs_reg_reg_i3 size_t op_len; - const char *op_str = (const char*)qstr_data(op, &op_len); + const char *op_str = (const char *)qstr_data(op, &op_len); #if MICROPY_EMIT_INLINE_THUMB_FLOAT if (op_str[0] == 'v') { @@ -434,7 +446,7 @@ STATIC void emit_inline_thumb_op(emit_inline_asm_t *emit, qstr op, mp_uint_t n_a mp_uint_t op_code = 0x0ac0, op_code_hi; if (op == MP_QSTR_vcmp) { op_code_hi = 0xeeb4; - op_vfp_twoargs:; + op_vfp_twoargs:; mp_uint_t vd = get_arg_vfpreg(emit, op_str, pn_args[0]); mp_uint_t vm = get_arg_vfpreg(emit, op_str, pn_args[1]); asm_thumb_op32(&emit->as, @@ -485,7 +497,7 @@ STATIC void emit_inline_thumb_op(emit_inline_asm_t *emit, qstr op, mp_uint_t n_a 0x0a10 | (r_arm << 12) | ((vm & 1) << 7)); } else if (op == MP_QSTR_vldr) { op_code_hi = 0xed90; - op_vldr_vstr:; + op_vldr_vstr:; mp_uint_t vd = get_arg_vfpreg(emit, op_str, pn_args[0]); mp_parse_node_t pn_base, pn_offset; if (get_arg_addr(emit, op_str, pn_args[1], &pn_base, &pn_offset)) { @@ -547,8 +559,8 @@ STATIC void emit_inline_thumb_op(emit_inline_asm_t *emit, qstr op, mp_uint_t n_a mp_uint_t r = get_arg_reg(emit, op_str, pn_args[0], 15); asm_thumb_op16(&emit->as, 0x4700 | (r << 3)); } else if (op_str[0] == 'b' && (op_len == 3 - || (op_len == 5 && op_str[3] == '_' - && (op_str[4] == 'n' || (ARMV7M && op_str[4] == 'w'))))) { + || (op_len == 5 && op_str[3] == '_' + && (op_str[4] == 'n' || (ARMV7M && op_str[4] == 'w'))))) { mp_uint_t cc = -1; for (mp_uint_t i = 0; i < MP_ARRAY_SIZE(cc_name_table); i++) { if (op_str[1] == cc_name_table[i].name[0] && op_str[2] == cc_name_table[i].name[1]) { @@ -637,7 +649,7 @@ STATIC void emit_inline_thumb_op(emit_inline_asm_t *emit, qstr op, mp_uint_t n_a op_code_hi = 0xfab0; op_code = 0xf080; mp_uint_t rd, rm; - op_clz_rbit: + op_clz_rbit: rd = get_arg_reg(emit, op_str, pn_args[0], 15); rm = get_arg_reg(emit, op_str, pn_args[1], 15); asm_thumb_op32(&emit->as, op_code_hi | rm, op_code | (rd << 8) | rm); @@ -645,7 +657,7 @@ STATIC void emit_inline_thumb_op(emit_inline_asm_t *emit, qstr op, mp_uint_t n_a op_code_hi = 0xfa90; op_code = 0xf0a0; goto op_clz_rbit; - } else if (ARMV7M && op == MP_QSTR_mrs){ + } else if (ARMV7M && op == MP_QSTR_mrs) { mp_uint_t reg_dest = get_arg_reg(emit, op_str, pn_args[0], 12); mp_uint_t reg_src = get_arg_special_reg(emit, op_str, pn_args[1]); asm_thumb_op32(&emit->as, 0xf3ef, 0x8000 | (reg_dest << 8) | reg_src); @@ -653,7 +665,7 @@ STATIC void emit_inline_thumb_op(emit_inline_asm_t *emit, qstr op, mp_uint_t n_a if (op == MP_QSTR_and_) { op_code = ASM_THUMB_FORMAT_4_AND; mp_uint_t reg_dest, reg_src; - op_format_4: + op_format_4: reg_dest = get_arg_reg(emit, op_str, pn_args[0], 7); reg_src = get_arg_reg(emit, op_str, pn_args[1], 7); asm_thumb_format_4(&emit->as, op_code, reg_dest, reg_src); @@ -674,7 +686,7 @@ STATIC void emit_inline_thumb_op(emit_inline_asm_t *emit, qstr op, mp_uint_t n_a if (op == MP_QSTR_mov) { op_code = ASM_THUMB_FORMAT_3_MOV; mp_uint_t rlo_dest, i8_src; - op_format_3: + op_format_3: rlo_dest = get_arg_reg(emit, op_str, pn_args[0], 7); i8_src = get_arg_i(emit, op_str, pn_args[1], 0xff); asm_thumb_format_3(&emit->as, op_code, rlo_dest, i8_src); @@ -690,7 +702,7 @@ STATIC void emit_inline_thumb_op(emit_inline_asm_t *emit, qstr op, mp_uint_t n_a } else if (ARMV7M && op == MP_QSTR_movw) { op_code = ASM_THUMB_OP_MOVW; mp_uint_t reg_dest; - op_movw_movt: + op_movw_movt: reg_dest = get_arg_reg(emit, op_str, pn_args[0], 15); int i_src = get_arg_i(emit, op_str, pn_args[1], 0xffff); asm_thumb_mov_reg_i16(&emit->as, op_code, reg_dest, i_src); @@ -743,7 +755,7 @@ STATIC void emit_inline_thumb_op(emit_inline_asm_t *emit, qstr op, mp_uint_t n_a if (op == MP_QSTR_lsl) { op_code = ASM_THUMB_FORMAT_1_LSL; mp_uint_t rlo_dest, rlo_src, i5; - op_format_1: + op_format_1: rlo_dest = get_arg_reg(emit, op_str, pn_args[0], 7); rlo_src = get_arg_reg(emit, op_str, pn_args[1], 7); i5 = get_arg_i(emit, op_str, pn_args[2], 0x1f); @@ -757,7 +769,7 @@ STATIC void emit_inline_thumb_op(emit_inline_asm_t *emit, qstr op, mp_uint_t n_a } else if (op == MP_QSTR_add) { op_code = ASM_THUMB_FORMAT_2_ADD; mp_uint_t rlo_dest, rlo_src; - op_format_2: + op_format_2: rlo_dest = get_arg_reg(emit, op_str, pn_args[0], 7); rlo_src = get_arg_reg(emit, op_str, pn_args[1], 7); int src_b; @@ -772,7 +784,7 @@ STATIC void emit_inline_thumb_op(emit_inline_asm_t *emit, qstr op, mp_uint_t n_a } else if (ARMV7M && op == MP_QSTR_sdiv) { op_code = 0xfb90; // sdiv high part mp_uint_t rd, rn, rm; - op_sdiv_udiv: + op_sdiv_udiv: rd = get_arg_reg(emit, op_str, pn_args[0], 15); rn = get_arg_reg(emit, op_str, pn_args[1], 15); rm = get_arg_reg(emit, op_str, pn_args[2], 15); diff --git a/py/emitinlinextensa.c b/py/emitinlinextensa.c index b5f9189d4b..b8f871c71c 100644 --- a/py/emitinlinextensa.c +++ b/py/emitinlinextensa.c @@ -115,7 +115,9 @@ STATIC bool emit_inline_xtensa_label(emit_inline_asm_t *emit, mp_uint_t label_nu return true; } -typedef struct _reg_name_t { byte reg; byte name[3]; } reg_name_t; +typedef struct _reg_name_t { byte reg; + byte name[3]; +} reg_name_t; STATIC const reg_name_t reg_name_table[] = { {0, "a0\0"}, {1, "a1\0"}, @@ -242,7 +244,7 @@ STATIC const opcode_table_3arg_t opcode_table_3arg[] = { STATIC void emit_inline_xtensa_op(emit_inline_asm_t *emit, qstr op, mp_uint_t n_args, mp_parse_node_t *pn_args) { size_t op_len; - const char *op_str = (const char*)qstr_data(op, &op_len); + const char *op_str = (const char *)qstr_data(op, &op_len); if (n_args == 0) { if (op == MP_QSTR_ret_n) { diff --git a/py/emitnative.c b/py/emitnative.c index a198ffb085..df4e50d2e8 100644 --- a/py/emitnative.c +++ b/py/emitnative.c @@ -110,7 +110,7 @@ #define EMIT_NATIVE_VIPER_TYPE_ERROR(emit, ...) do { \ *emit->error_slot = mp_obj_new_exception_msg_varg(&mp_type_ViperTypeError, __VA_ARGS__); \ - } while (0) +} while (0) typedef enum { STACK_VALUE, @@ -138,29 +138,48 @@ typedef enum { int mp_native_type_from_qstr(qstr qst) { switch (qst) { - case MP_QSTR_object: return MP_NATIVE_TYPE_OBJ; - case MP_QSTR_bool: return MP_NATIVE_TYPE_BOOL; - case MP_QSTR_int: return MP_NATIVE_TYPE_INT; - case MP_QSTR_uint: return MP_NATIVE_TYPE_UINT; - case MP_QSTR_ptr: return MP_NATIVE_TYPE_PTR; - case MP_QSTR_ptr8: return MP_NATIVE_TYPE_PTR8; - case MP_QSTR_ptr16: return MP_NATIVE_TYPE_PTR16; - case MP_QSTR_ptr32: return MP_NATIVE_TYPE_PTR32; - default: return -1; + case MP_QSTR_object: + return MP_NATIVE_TYPE_OBJ; + case MP_QSTR_bool: + return MP_NATIVE_TYPE_BOOL; + case MP_QSTR_int: + return MP_NATIVE_TYPE_INT; + case MP_QSTR_uint: + return MP_NATIVE_TYPE_UINT; + case MP_QSTR_ptr: + return MP_NATIVE_TYPE_PTR; + case MP_QSTR_ptr8: + return MP_NATIVE_TYPE_PTR8; + case MP_QSTR_ptr16: + return MP_NATIVE_TYPE_PTR16; + case MP_QSTR_ptr32: + return MP_NATIVE_TYPE_PTR32; + default: + return -1; } } STATIC qstr vtype_to_qstr(vtype_kind_t vtype) { switch (vtype) { - case VTYPE_PYOBJ: return MP_QSTR_object; - case VTYPE_BOOL: return MP_QSTR_bool; - case VTYPE_INT: return MP_QSTR_int; - case VTYPE_UINT: return MP_QSTR_uint; - case VTYPE_PTR: return MP_QSTR_ptr; - case VTYPE_PTR8: return MP_QSTR_ptr8; - case VTYPE_PTR16: return MP_QSTR_ptr16; - case VTYPE_PTR32: return MP_QSTR_ptr32; - case VTYPE_PTR_NONE: default: return MP_QSTR_None; + case VTYPE_PYOBJ: + return MP_QSTR_object; + case VTYPE_BOOL: + return MP_QSTR_bool; + case VTYPE_INT: + return MP_QSTR_int; + case VTYPE_UINT: + return MP_QSTR_uint; + case VTYPE_PTR: + return MP_QSTR_ptr; + case VTYPE_PTR8: + return MP_QSTR_ptr8; + case VTYPE_PTR16: + return MP_QSTR_ptr16; + case VTYPE_PTR32: + return MP_QSTR_ptr32; + case VTYPE_PTR_NONE: + default: + return MP_QSTR_None; } } @@ -226,7 +245,7 @@ STATIC const uint8_t reg_local_table[REG_LOCAL_NUM] = {REG_LOCAL_1, REG_LOCAL_2, STATIC void emit_native_global_exc_entry(emit_t *emit); STATIC void emit_native_global_exc_exit(emit_t *emit); -emit_t *EXPORT_FUN(new)(mp_obj_t *error_slot, uint *label_slot, mp_uint_t max_num_labels) { +emit_t *EXPORT_FUN(new)(mp_obj_t * error_slot, uint *label_slot, mp_uint_t max_num_labels) { emit_t *emit = m_new0(emit_t, 1); emit->error_slot = error_slot; emit->label_slot = label_slot; @@ -239,7 +258,7 @@ emit_t *EXPORT_FUN(new)(mp_obj_t *error_slot, uint *label_slot, mp_uint_t max_nu return emit; } -void EXPORT_FUN(free)(emit_t *emit) { +void EXPORT_FUN(free)(emit_t * emit) { mp_asm_base_deinit(&emit->as->base, false); m_del_obj(ASM_T, emit->as); m_del(exc_stack_entry_t, emit->exc_stack, emit->exc_stack_alloc); @@ -622,14 +641,14 @@ STATIC void adjust_stack(emit_t *emit, mp_int_t stack_size_delta) { if (emit->pass > MP_PASS_SCOPE && emit->stack_size > emit->scope->stack_size) { emit->scope->stack_size = emit->stack_size; } -#ifdef DEBUG_PRINT + #ifdef DEBUG_PRINT DEBUG_printf(" adjust_stack; stack_size=%d+%d; stack now:", emit->stack_size - stack_size_delta, stack_size_delta); for (int i = 0; i < emit->stack_size; i++) { stack_info_t *si = &emit->stack_info[i]; DEBUG_printf(" (v=%d k=%d %d)", si->vtype, si->kind, si->data.u_reg); } DEBUG_printf("\n"); -#endif + #endif } STATIC void emit_native_adjust_stack_size(emit_t *emit, mp_int_t delta) { @@ -1013,8 +1032,8 @@ STATIC void emit_native_label_assign(emit_t *emit, mp_uint_t l) { bool is_finally = false; if (emit->exc_stack_size > 0) { - exc_stack_entry_t *e = &emit->exc_stack[emit->exc_stack_size - 1]; - is_finally = e->is_finally && e->label == l; + exc_stack_entry_t *e = &emit->exc_stack[emit->exc_stack_size - 1]; + is_finally = e->is_finally && e->label == l; } if (is_finally) { @@ -2283,7 +2302,7 @@ STATIC void emit_native_binary_op(emit_t *emit, mp_binary_op_t op) { asm_xtensa_setcc_reg_reg_reg(emit->as, cc & ~0x80, REG_RET, reg_rhs, REG_ARG_2); } #else - #error not implemented + #error not implemented #endif emit_post_push_reg(emit, VTYPE_BOOL, REG_RET); } else { diff --git a/py/formatfloat.c b/py/formatfloat.c index dc7fc1d1fd..50fc0da4b4 100644 --- a/py/formatfloat.c +++ b/py/formatfloat.c @@ -68,11 +68,20 @@ union floatbits { float f; uint32_t u; }; -static inline int fp_signbit(float x) { union floatbits fb = {x}; return fb.u & FLT_SIGN_MASK; } +static inline int fp_signbit(float x) { + union floatbits fb = {x}; + return fb.u & FLT_SIGN_MASK; +} #define fp_isnan(x) isnan(x) #define fp_isinf(x) isinf(x) -static inline int fp_iszero(float x) { union floatbits fb = {x}; return fb.u == 0; } -static inline int fp_isless1(float x) { union floatbits fb = {x}; return fb.u < 0x3f800000; } +static inline int fp_iszero(float x) { + union floatbits fb = {x}; + return fb.u == 0; +} +static inline int fp_isless1(float x) { + union floatbits fb = {x}; + return fb.u < 0x3f800000; +} #elif MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE @@ -282,7 +291,7 @@ int mp_format_float(FPTYPE f, char *buf, size_t buf_size, char fmt, int prec, ch if (fmt == 'e' && prec > (buf_remaining - FPMIN_BUF_SIZE)) { prec = buf_remaining - FPMIN_BUF_SIZE; } - if (fmt == 'g'){ + if (fmt == 'g') { // Truncate precision to prevent buffer overflow if (prec + (FPMIN_BUF_SIZE - 1) > buf_remaining) { prec = buf_remaining - (FPMIN_BUF_SIZE - 1); diff --git a/py/frozenmod.c b/py/frozenmod.c index 06d4f84c8e..a250c02151 100644 --- a/py/frozenmod.c +++ b/py/frozenmod.c @@ -146,7 +146,7 @@ int mp_find_frozen_module(const char *str, size_t len, void **data) { #if MICROPY_MODULE_FROZEN_MPY const mp_raw_code_t *rc = mp_find_frozen_mpy(str, len); if (rc != NULL) { - *data = (void*)rc; + *data = (void *)rc; return MP_FROZEN_MPY; } #endif diff --git a/py/gc.c b/py/gc.c index 2965059a1a..df7154fff8 100644 --- a/py/gc.c +++ b/py/gc.c @@ -81,7 +81,7 @@ #define ATB_HEAD_TO_MARK(block) do { MP_STATE_MEM(gc_alloc_table_start)[(block) / BLOCKS_PER_ATB] |= (AT_MARK << BLOCK_SHIFT(block)); } while (0) #define ATB_MARK_TO_HEAD(block) do { MP_STATE_MEM(gc_alloc_table_start)[(block) / BLOCKS_PER_ATB] &= (~(AT_TAIL << BLOCK_SHIFT(block))); } while (0) -#define BLOCK_FROM_PTR(ptr) (((byte*)(ptr) - MP_STATE_MEM(gc_pool_start)) / BYTES_PER_BLOCK) +#define BLOCK_FROM_PTR(ptr) (((byte *)(ptr) - MP_STATE_MEM(gc_pool_start)) / BYTES_PER_BLOCK) #define PTR_FROM_BLOCK(block) (((block) * BYTES_PER_BLOCK + (uintptr_t)MP_STATE_MEM(gc_pool_start))) #define ATB_FROM_BLOCK(bl) ((bl) / BLOCKS_PER_ATB) @@ -107,43 +107,43 @@ // TODO waste less memory; currently requires that all entries in alloc_table have a corresponding block in pool void gc_init(void *start, void *end) { // align end pointer on block boundary - end = (void*)((uintptr_t)end & (~(BYTES_PER_BLOCK - 1))); - DEBUG_printf("Initializing GC heap: %p..%p = " UINT_FMT " bytes\n", start, end, (byte*)end - (byte*)start); + end = (void *)((uintptr_t)end & (~(BYTES_PER_BLOCK - 1))); + DEBUG_printf("Initializing GC heap: %p..%p = " UINT_FMT " bytes\n", start, end, (byte *)end - (byte *)start); // calculate parameters for GC (T=total, A=alloc table, F=finaliser table, P=pool; all in bytes): // T = A + F + P // F = A * BLOCKS_PER_ATB / BLOCKS_PER_FTB // P = A * BLOCKS_PER_ATB * BYTES_PER_BLOCK // => T = A * (1 + BLOCKS_PER_ATB / BLOCKS_PER_FTB + BLOCKS_PER_ATB * BYTES_PER_BLOCK) - size_t total_byte_len = (byte*)end - (byte*)start; -#if MICROPY_ENABLE_FINALISER + size_t total_byte_len = (byte *)end - (byte *)start; + #if MICROPY_ENABLE_FINALISER MP_STATE_MEM(gc_alloc_table_byte_len) = total_byte_len * BITS_PER_BYTE / (BITS_PER_BYTE + BITS_PER_BYTE * BLOCKS_PER_ATB / BLOCKS_PER_FTB + BITS_PER_BYTE * BLOCKS_PER_ATB * BYTES_PER_BLOCK); -#else + #else MP_STATE_MEM(gc_alloc_table_byte_len) = total_byte_len / (1 + BITS_PER_BYTE / 2 * BYTES_PER_BLOCK); -#endif + #endif - MP_STATE_MEM(gc_alloc_table_start) = (byte*)start; + MP_STATE_MEM(gc_alloc_table_start) = (byte *)start; -#if MICROPY_ENABLE_FINALISER + #if MICROPY_ENABLE_FINALISER size_t gc_finaliser_table_byte_len = (MP_STATE_MEM(gc_alloc_table_byte_len) * BLOCKS_PER_ATB + BLOCKS_PER_FTB - 1) / BLOCKS_PER_FTB; MP_STATE_MEM(gc_finaliser_table_start) = MP_STATE_MEM(gc_alloc_table_start) + MP_STATE_MEM(gc_alloc_table_byte_len); -#endif + #endif size_t gc_pool_block_len = MP_STATE_MEM(gc_alloc_table_byte_len) * BLOCKS_PER_ATB; - MP_STATE_MEM(gc_pool_start) = (byte*)end - gc_pool_block_len * BYTES_PER_BLOCK; + MP_STATE_MEM(gc_pool_start) = (byte *)end - gc_pool_block_len * BYTES_PER_BLOCK; MP_STATE_MEM(gc_pool_end) = end; -#if MICROPY_ENABLE_FINALISER + #if MICROPY_ENABLE_FINALISER assert(MP_STATE_MEM(gc_pool_start) >= MP_STATE_MEM(gc_finaliser_table_start) + gc_finaliser_table_byte_len); -#endif + #endif // clear ATBs memset(MP_STATE_MEM(gc_alloc_table_start), 0, MP_STATE_MEM(gc_alloc_table_byte_len)); -#if MICROPY_ENABLE_FINALISER + #if MICROPY_ENABLE_FINALISER // clear FTBs memset(MP_STATE_MEM(gc_finaliser_table_start), 0, gc_finaliser_table_byte_len); -#endif + #endif // set last free ATB index to start of heap MP_STATE_MEM(gc_last_free_atb_index) = 0; @@ -166,9 +166,9 @@ void gc_init(void *start, void *end) { DEBUG_printf("GC layout:\n"); DEBUG_printf(" alloc table at %p, length " UINT_FMT " bytes, " UINT_FMT " blocks\n", MP_STATE_MEM(gc_alloc_table_start), MP_STATE_MEM(gc_alloc_table_byte_len), MP_STATE_MEM(gc_alloc_table_byte_len) * BLOCKS_PER_ATB); -#if MICROPY_ENABLE_FINALISER + #if MICROPY_ENABLE_FINALISER DEBUG_printf(" finaliser table at %p, length " UINT_FMT " bytes, " UINT_FMT " blocks\n", MP_STATE_MEM(gc_finaliser_table_start), gc_finaliser_table_byte_len, gc_finaliser_table_byte_len * BLOCKS_PER_FTB); -#endif + #endif DEBUG_printf(" pool at %p, length " UINT_FMT " bytes, " UINT_FMT " blocks\n", MP_STATE_MEM(gc_pool_start), gc_pool_block_len * BYTES_PER_BLOCK, gc_pool_block_len); } @@ -190,9 +190,9 @@ bool gc_is_locked(void) { // ptr should be of type void* #define VERIFY_PTR(ptr) ( \ - ((uintptr_t)(ptr) & (BYTES_PER_BLOCK - 1)) == 0 /* must be aligned on a block */ \ - && ptr >= (void*)MP_STATE_MEM(gc_pool_start) /* must be above start of pool */ \ - && ptr < (void*)MP_STATE_MEM(gc_pool_end) /* must be below end of pool */ \ + ((uintptr_t)(ptr) & (BYTES_PER_BLOCK - 1)) == 0 /* must be aligned on a block */ \ + && ptr >= (void *)MP_STATE_MEM(gc_pool_start) /* must be above start of pool */ \ + && ptr < (void *)MP_STATE_MEM(gc_pool_end) /* must be below end of pool */ \ ) #ifndef TRACE_MARK @@ -218,8 +218,8 @@ STATIC void gc_mark_subtree(size_t block) { } while (ATB_GET_KIND(block + n_blocks) == AT_TAIL); // check this block's children - void **ptrs = (void**)PTR_FROM_BLOCK(block); - for (size_t i = n_blocks * BYTES_PER_BLOCK / sizeof(void*); i > 0; i--, ptrs++) { + void **ptrs = (void **)PTR_FROM_BLOCK(block); + for (size_t i = n_blocks * BYTES_PER_BLOCK / sizeof(void *); i > 0; i--, ptrs++) { void *ptr = *ptrs; if (VERIFY_PTR(ptr)) { // Mark and push this pointer @@ -270,9 +270,9 @@ STATIC void gc_sweep(void) { for (size_t block = 0; block < MP_STATE_MEM(gc_alloc_table_byte_len) * BLOCKS_PER_ATB; block++) { switch (ATB_GET_KIND(block)) { case AT_HEAD: -#if MICROPY_ENABLE_FINALISER + #if MICROPY_ENABLE_FINALISER if (FTB_GET(block)) { - mp_obj_base_t *obj = (mp_obj_base_t*)PTR_FROM_BLOCK(block); + mp_obj_base_t *obj = (mp_obj_base_t *)PTR_FROM_BLOCK(block); if (obj->type != NULL) { // if the object has a type then see if it has a __del__ method mp_obj_t dest[2]; @@ -291,19 +291,19 @@ STATIC void gc_sweep(void) { // clear finaliser flag FTB_CLEAR(block); } -#endif + #endif free_tail = 1; DEBUG_printf("gc_sweep(%p)\n", PTR_FROM_BLOCK(block)); #if MICROPY_PY_GC_COLLECT_RETVAL MP_STATE_MEM(gc_collected)++; #endif - // fall through to free the head + // fall through to free the head case AT_TAIL: if (free_tail) { ATB_ANY_TO_FREE(block); #if CLEAR_ON_SWEEP - memset((void*)PTR_FROM_BLOCK(block), 0, BYTES_PER_BLOCK); + memset((void *)PTR_FROM_BLOCK(block), 0, BYTES_PER_BLOCK); #endif } break; @@ -327,15 +327,15 @@ void gc_collect_start(void) { // Trace root pointers. This relies on the root pointers being organised // correctly in the mp_state_ctx structure. We scan nlr_top, dict_locals, // dict_globals, then the root pointer section of mp_state_vm. - void **ptrs = (void**)(void*)&mp_state_ctx; + void **ptrs = (void **)(void *)&mp_state_ctx; size_t root_start = offsetof(mp_state_ctx_t, thread.dict_locals); size_t root_end = offsetof(mp_state_ctx_t, vm.qstr_last_chunk); - gc_collect_root(ptrs + root_start / sizeof(void*), (root_end - root_start) / sizeof(void*)); + gc_collect_root(ptrs + root_start / sizeof(void *), (root_end - root_start) / sizeof(void *)); #if MICROPY_ENABLE_PYSTACK // Trace root pointers from the Python stack. - ptrs = (void**)(void*)MP_STATE_THREAD(pystack_start); - gc_collect_root(ptrs, (MP_STATE_THREAD(pystack_cur) - MP_STATE_THREAD(pystack_start)) / sizeof(void*)); + ptrs = (void **)(void *)MP_STATE_THREAD(pystack_start); + gc_collect_root(ptrs, (MP_STATE_THREAD(pystack_cur) - MP_STATE_THREAD(pystack_start)) / sizeof(void *)); #endif } @@ -472,10 +472,38 @@ void *gc_alloc(size_t n_bytes, unsigned int alloc_flags) { n_free = 0; for (i = MP_STATE_MEM(gc_last_free_atb_index); i < MP_STATE_MEM(gc_alloc_table_byte_len); i++) { byte a = MP_STATE_MEM(gc_alloc_table_start)[i]; - if (ATB_0_IS_FREE(a)) { if (++n_free >= n_blocks) { i = i * BLOCKS_PER_ATB + 0; goto found; } } else { n_free = 0; } - if (ATB_1_IS_FREE(a)) { if (++n_free >= n_blocks) { i = i * BLOCKS_PER_ATB + 1; goto found; } } else { n_free = 0; } - if (ATB_2_IS_FREE(a)) { if (++n_free >= n_blocks) { i = i * BLOCKS_PER_ATB + 2; goto found; } } else { n_free = 0; } - if (ATB_3_IS_FREE(a)) { if (++n_free >= n_blocks) { i = i * BLOCKS_PER_ATB + 3; goto found; } } else { n_free = 0; } + if (ATB_0_IS_FREE(a)) { + if (++n_free >= n_blocks) { + i = i * BLOCKS_PER_ATB + 0; + goto found; + } + } else { + n_free = 0; + } + if (ATB_1_IS_FREE(a)) { + if (++n_free >= n_blocks) { + i = i * BLOCKS_PER_ATB + 1; + goto found; + } + } else { + n_free = 0; + } + if (ATB_2_IS_FREE(a)) { + if (++n_free >= n_blocks) { + i = i * BLOCKS_PER_ATB + 2; + goto found; + } + } else { + n_free = 0; + } + if (ATB_3_IS_FREE(a)) { + if (++n_free >= n_blocks) { + i = i * BLOCKS_PER_ATB + 3; + goto found; + } + } else { + n_free = 0; + } } GC_EXIT(); @@ -515,7 +543,7 @@ found: // get pointer to first block // we must create this pointer before unlocking the GC so a collection can find it - void *ret_ptr = (void*)(MP_STATE_MEM(gc_pool_start) + start_block * BYTES_PER_BLOCK); + void *ret_ptr = (void *)(MP_STATE_MEM(gc_pool_start) + start_block * BYTES_PER_BLOCK); DEBUG_printf("gc_alloc(%p)\n", ret_ptr); #if MICROPY_GC_ALLOC_THRESHOLD @@ -526,20 +554,20 @@ found: #if MICROPY_GC_CONSERVATIVE_CLEAR // be conservative and zero out all the newly allocated blocks - memset((byte*)ret_ptr, 0, (end_block - start_block + 1) * BYTES_PER_BLOCK); + memset((byte *)ret_ptr, 0, (end_block - start_block + 1) * BYTES_PER_BLOCK); #else // zero out the additional bytes of the newly allocated blocks // This is needed because the blocks may have previously held pointers // to the heap and will not be set to something else if the caller // doesn't actually use the entire block. As such they will continue // to point to the heap and may prevent other blocks from being reclaimed. - memset((byte*)ret_ptr + n_bytes, 0, (end_block - start_block + 1) * BYTES_PER_BLOCK - n_bytes); + memset((byte *)ret_ptr + n_bytes, 0, (end_block - start_block + 1) * BYTES_PER_BLOCK - n_bytes); #endif #if MICROPY_ENABLE_FINALISER if (has_finaliser) { // clear type pointer in case it is never set - ((mp_obj_base_t*)ret_ptr)->type = NULL; + ((mp_obj_base_t *)ret_ptr)->type = NULL; // set mp_obj flag only if it has a finaliser GC_ENTER(); FTB_SET(start_block); @@ -640,11 +668,11 @@ void *gc_realloc(void *ptr, mp_uint_t n_bytes) { if (ptr == NULL) { has_finaliser = false; } else { -#if MICROPY_ENABLE_FINALISER + #if MICROPY_ENABLE_FINALISER has_finaliser = FTB_GET(BLOCK_FROM_PTR((mp_uint_t)ptr)); -#else + #else has_finaliser = false; -#endif + #endif } void *ptr2 = gc_alloc(n_bytes, has_finaliser); if (ptr2 == NULL) { @@ -693,7 +721,7 @@ void *gc_realloc(void *ptr_in, size_t n_bytes, bool allow_move) { // free blocks to satisfy the realloc. Note that we need to compute the // total size of the existing memory chunk so we can correctly and // efficiently shrink it (see below for shrinking code). - size_t n_free = 0; + size_t n_free = 0; size_t n_blocks = 1; // counting HEAD block size_t max_block = MP_STATE_MEM(gc_alloc_table_byte_len) * BLOCKS_PER_ATB; for (size_t bl = block + n_blocks; bl < max_block; bl++) { @@ -752,10 +780,10 @@ void *gc_realloc(void *ptr_in, size_t n_bytes, bool allow_move) { #if MICROPY_GC_CONSERVATIVE_CLEAR // be conservative and zero out all the newly allocated blocks - memset((byte*)ptr_in + n_blocks * BYTES_PER_BLOCK, 0, (new_blocks - n_blocks) * BYTES_PER_BLOCK); + memset((byte *)ptr_in + n_blocks * BYTES_PER_BLOCK, 0, (new_blocks - n_blocks) * BYTES_PER_BLOCK); #else // zero out the additional bytes of the newly allocated blocks (see comment above in gc_alloc) - memset((byte*)ptr_in + n_bytes, 0, new_blocks * BYTES_PER_BLOCK - n_bytes); + memset((byte *)ptr_in + n_bytes, 0, new_blocks * BYTES_PER_BLOCK - n_bytes); #endif #if EXTENSIVE_HEAP_PROFILING @@ -799,7 +827,7 @@ void gc_dump_info(void) { mp_printf(&mp_plat_print, "GC: total: %u, used: %u, free: %u\n", (uint)info.total, (uint)info.used, (uint)info.free); mp_printf(&mp_plat_print, " No. of 1-blocks: %u, 2-blocks: %u, max blk sz: %u, max free sz: %u\n", - (uint)info.num_1block, (uint)info.num_2block, (uint)info.max_block, (uint)info.max_free); + (uint)info.num_1block, (uint)info.num_2block, (uint)info.max_block, (uint)info.max_free); } void gc_dump_alloc_table(void) { @@ -831,12 +859,14 @@ void gc_dump_alloc_table(void) { } // print header for new line of blocks // (the cast to uint32_t is for 16-bit ports) - //mp_printf(&mp_plat_print, "\n%05x: ", (uint)(PTR_FROM_BLOCK(bl) & (uint32_t)0xfffff)); + // mp_printf(&mp_plat_print, "\n%05x: ", (uint)(PTR_FROM_BLOCK(bl) & (uint32_t)0xfffff)); mp_printf(&mp_plat_print, "\n%05x: ", (uint)((bl * BYTES_PER_BLOCK) & (uint32_t)0xfffff)); } int c = ' '; switch (ATB_GET_KIND(bl)) { - case AT_FREE: c = '.'; break; + case AT_FREE: + c = '.'; + break; /* this prints out if the object is reachable from BSS or STACK (for unix only) case AT_HEAD: { c = 'h'; @@ -865,35 +895,48 @@ void gc_dump_alloc_table(void) { */ /* this prints the uPy object type of the head block */ case AT_HEAD: { - void **ptr = (void**)(MP_STATE_MEM(gc_pool_start) + bl * BYTES_PER_BLOCK); - if (*ptr == &mp_type_tuple) { c = 'T'; } - else if (*ptr == &mp_type_list) { c = 'L'; } - else if (*ptr == &mp_type_dict) { c = 'D'; } - else if (*ptr == &mp_type_str || *ptr == &mp_type_bytes) { c = 'S'; } + void **ptr = (void **)(MP_STATE_MEM(gc_pool_start) + bl * BYTES_PER_BLOCK); + if (*ptr == &mp_type_tuple) { + c = 'T'; + } else if (*ptr == &mp_type_list) { + c = 'L'; + } else if (*ptr == &mp_type_dict) { + c = 'D'; + } else if (*ptr == &mp_type_str || *ptr == &mp_type_bytes) { + c = 'S'; + } #if MICROPY_PY_BUILTINS_BYTEARRAY - else if (*ptr == &mp_type_bytearray) { c = 'A'; } + else if (*ptr == &mp_type_bytearray) { + c = 'A'; + } #endif #if MICROPY_PY_ARRAY - else if (*ptr == &mp_type_array) { c = 'A'; } + else if (*ptr == &mp_type_array) { + c = 'A'; + } #endif #if MICROPY_PY_BUILTINS_FLOAT - else if (*ptr == &mp_type_float) { c = 'F'; } + else if (*ptr == &mp_type_float) { + c = 'F'; + } #endif - else if (*ptr == &mp_type_fun_bc) { c = 'B'; } - else if (*ptr == &mp_type_module) { c = 'M'; } - else { + else if (*ptr == &mp_type_fun_bc) { + c = 'B'; + } else if (*ptr == &mp_type_module) { + c = 'M'; + } else { c = 'h'; #if 0 // This code prints "Q" for qstr-pool data, and "q" for qstr-str // data. It can be useful to see how qstrs are being allocated, // but is disabled by default because it is very slow. for (qstr_pool_t *pool = MP_STATE_VM(last_pool); c == 'h' && pool != NULL; pool = pool->prev) { - if ((qstr_pool_t*)ptr == pool) { + if ((qstr_pool_t *)ptr == pool) { c = 'Q'; break; } for (const byte **q = pool->qstrs, **q_top = pool->qstrs + pool->len; q < q_top; q++) { - if ((const byte*)ptr == *q) { + if ((const byte *)ptr == *q) { c = 'q'; break; } @@ -903,8 +946,12 @@ void gc_dump_alloc_table(void) { } break; } - case AT_TAIL: c = '='; break; - case AT_MARK: c = 'm'; break; + case AT_TAIL: + c = '='; + break; + case AT_MARK: + c = 'm'; + break; } mp_printf(&mp_plat_print, "%c", c); } @@ -930,11 +977,11 @@ void gc_test(void) { p2[1] = p; ptrs[0] = p2; } - for (int i = 0; i < 25; i+=2) { + for (int i = 0; i < 25; i += 2) { mp_uint_t *p = gc_alloc(i, false); printf("p=%p\n", p); if (i & 3) { - //ptrs[i] = p; + // ptrs[i] = p; } } @@ -942,7 +989,7 @@ void gc_test(void) { gc_dump_alloc_table(); printf("Starting GC...\n"); gc_collect_start(); - gc_collect_root(ptrs, sizeof(ptrs) / sizeof(void*)); + gc_collect_root(ptrs, sizeof(ptrs) / sizeof(void *)); gc_collect_end(); printf("After GC:\n"); gc_dump_alloc_table(); diff --git a/py/lexer.c b/py/lexer.c index e161700b16..d08bd27546 100644 --- a/py/lexer.c +++ b/py/lexer.c @@ -105,9 +105,9 @@ STATIC bool is_following_odigit(mp_lexer_t *lex) { STATIC bool is_string_or_bytes(mp_lexer_t *lex) { return is_char_or(lex, '\'', '\"') - || (is_char_or3(lex, 'r', 'u', 'b') && is_char_following_or(lex, '\'', '\"')) - || ((is_char_and(lex, 'r', 'b') || is_char_and(lex, 'b', 'r')) - && is_char_following_following_or(lex, '\'', '\"')); + || (is_char_or3(lex, 'r', 'u', 'b') && is_char_following_or(lex, '\'', '\"')) + || ((is_char_and(lex, 'r', 'b') || is_char_and(lex, 'b', 'r')) + && is_char_following_following_or(lex, '\'', '\"')); } // to easily parse utf-8 identifiers we allow any raw byte with high bit set @@ -305,17 +305,36 @@ STATIC void parse_string_literal(mp_lexer_t *lex, bool is_raw) { switch (c) { // note: "c" can never be MP_LEXER_EOF because next_char // always inserts a newline at the end of the input stream - case '\n': c = MP_LEXER_EOF; break; // backslash escape the newline, just ignore it - case '\\': break; - case '\'': break; - case '"': break; - case 'a': c = 0x07; break; - case 'b': c = 0x08; break; - case 't': c = 0x09; break; - case 'n': c = 0x0a; break; - case 'v': c = 0x0b; break; - case 'f': c = 0x0c; break; - case 'r': c = 0x0d; break; + case '\n': + c = MP_LEXER_EOF; + break; // backslash escape the newline, just ignore it + case '\\': + break; + case '\'': + break; + case '"': + break; + case 'a': + c = 0x07; + break; + case 'b': + c = 0x08; + break; + case 't': + c = 0x09; + break; + case 'n': + c = 0x0a; + break; + case 'v': + c = 0x0b; + break; + case 'f': + c = 0x0c; + break; + case 'r': + c = 0x0d; + break; case 'u': case 'U': if (lex->tok_kind == MP_TOKEN_BYTES) { @@ -323,9 +342,8 @@ STATIC void parse_string_literal(mp_lexer_t *lex, bool is_raw) { vstr_add_char(&lex->vstr, '\\'); break; } - // Otherwise fall through. - case 'x': - { + // Otherwise fall through. + case 'x': { mp_uint_t num = 0; if (!get_hex(lex, (c == 'x' ? 2 : c == 'u' ? 4 : 8), &num)) { // not enough hex chars for escape sequence @@ -705,7 +723,7 @@ mp_lexer_t *mp_lexer_new(qstr src_name, mp_reader_t reader) { mp_lexer_t *mp_lexer_new_from_str_len(qstr src_name, const char *str, size_t len, size_t free_len) { mp_reader_t reader; - mp_reader_new_mem(&reader, (const byte*)str, len, free_len); + mp_reader_new_mem(&reader, (const byte *)str, len, free_len); return mp_lexer_new(src_name, reader); } diff --git a/py/lexer.h b/py/lexer.h index a29709107d..cfa9059d3a 100644 --- a/py/lexer.h +++ b/py/lexer.h @@ -177,7 +177,7 @@ void mp_lexer_to_next(mp_lexer_t *lex); // platform specific import function; must be implemented for a specific port // TODO tidy up, rename, or put elsewhere -//mp_lexer_t *mp_import_open_file(qstr mod_name); +// mp_lexer_t *mp_import_open_file(qstr mod_name); typedef enum { MP_IMPORT_STAT_NO_EXIST, diff --git a/py/makeqstrdata.py b/py/makeqstrdata.py index 3c0a609092..d797963f41 100644 --- a/py/makeqstrdata.py +++ b/py/makeqstrdata.py @@ -13,43 +13,44 @@ import sys # - iterating through bytes is different # - codepoint2name lives in a different module import platform -if platform.python_version_tuple()[0] == '2': + +if platform.python_version_tuple()[0] == "2": bytes_cons = lambda val, enc=None: bytearray(val) from htmlentitydefs import codepoint2name -elif platform.python_version_tuple()[0] == '3': +elif platform.python_version_tuple()[0] == "3": bytes_cons = bytes from html.entities import codepoint2name # end compatibility code -codepoint2name[ord('-')] = 'hyphen'; +codepoint2name[ord("-")] = "hyphen" # add some custom names to map characters that aren't in HTML -codepoint2name[ord(' ')] = 'space' -codepoint2name[ord('\'')] = 'squot' -codepoint2name[ord(',')] = 'comma' -codepoint2name[ord('.')] = 'dot' -codepoint2name[ord(':')] = 'colon' -codepoint2name[ord(';')] = 'semicolon' -codepoint2name[ord('/')] = 'slash' -codepoint2name[ord('%')] = 'percent' -codepoint2name[ord('#')] = 'hash' -codepoint2name[ord('(')] = 'paren_open' -codepoint2name[ord(')')] = 'paren_close' -codepoint2name[ord('[')] = 'bracket_open' -codepoint2name[ord(']')] = 'bracket_close' -codepoint2name[ord('{')] = 'brace_open' -codepoint2name[ord('}')] = 'brace_close' -codepoint2name[ord('*')] = 'star' -codepoint2name[ord('!')] = 'bang' -codepoint2name[ord('\\')] = 'backslash' -codepoint2name[ord('+')] = 'plus' -codepoint2name[ord('$')] = 'dollar' -codepoint2name[ord('=')] = 'equals' -codepoint2name[ord('?')] = 'question' -codepoint2name[ord('@')] = 'at_sign' -codepoint2name[ord('^')] = 'caret' -codepoint2name[ord('|')] = 'pipe' -codepoint2name[ord('~')] = 'tilde' +codepoint2name[ord(" ")] = "space" +codepoint2name[ord("'")] = "squot" +codepoint2name[ord(",")] = "comma" +codepoint2name[ord(".")] = "dot" +codepoint2name[ord(":")] = "colon" +codepoint2name[ord(";")] = "semicolon" +codepoint2name[ord("/")] = "slash" +codepoint2name[ord("%")] = "percent" +codepoint2name[ord("#")] = "hash" +codepoint2name[ord("(")] = "paren_open" +codepoint2name[ord(")")] = "paren_close" +codepoint2name[ord("[")] = "bracket_open" +codepoint2name[ord("]")] = "bracket_close" +codepoint2name[ord("{")] = "brace_open" +codepoint2name[ord("}")] = "brace_close" +codepoint2name[ord("*")] = "star" +codepoint2name[ord("!")] = "bang" +codepoint2name[ord("\\")] = "backslash" +codepoint2name[ord("+")] = "plus" +codepoint2name[ord("$")] = "dollar" +codepoint2name[ord("=")] = "equals" +codepoint2name[ord("?")] = "question" +codepoint2name[ord("@")] = "at_sign" +codepoint2name[ord("^")] = "caret" +codepoint2name[ord("|")] = "pipe" +codepoint2name[ord("~")] = "tilde" # this must match the equivalent function in qstr.c def compute_hash(qstr, bytes_hash): @@ -59,37 +60,40 @@ def compute_hash(qstr, bytes_hash): # Make sure that valid hash is never zero, zero means "hash not computed" return (hash & ((1 << (8 * bytes_hash)) - 1)) or 1 + def qstr_escape(qst): def esc_char(m): c = ord(m.group(0)) try: name = codepoint2name[c] except KeyError: - name = '0x%02x' % c - return "_" + name + '_' - return re.sub(r'[^A-Za-z0-9_]', esc_char, qst) + name = "0x%02x" % c + return "_" + name + "_" + + return re.sub(r"[^A-Za-z0-9_]", esc_char, qst) + def parse_input_headers(infiles): # read the qstrs in from the input files qcfgs = {} qstrs = {} for infile in infiles: - with open(infile, 'rt') as f: + with open(infile, "rt") as f: for line in f: line = line.strip() # is this a config line? - match = re.match(r'^QCFG\((.+), (.+)\)', line) + match = re.match(r"^QCFG\((.+), (.+)\)", line) if match: value = match.group(2) - if value[0] == '(' and value[-1] == ')': + if value[0] == "(" and value[-1] == ")": # strip parenthesis from config value value = value[1:-1] qcfgs[match.group(1)] = value continue # is this a QSTR line? - match = re.match(r'^Q\((.*)\)$', line) + match = re.match(r"^Q\((.*)\)$", line) if not match: continue @@ -97,8 +101,8 @@ def parse_input_headers(infiles): qstr = match.group(1) # special case to specify control characters - if qstr == '\\n': - qstr = '\n' + if qstr == "\\n": + qstr = "\n" # work out the corresponding qstr name ident = qstr_escape(qstr) @@ -127,43 +131,54 @@ def parse_input_headers(infiles): return qcfgs, qstrs + def make_bytes(cfg_bytes_len, cfg_bytes_hash, qstr): - qbytes = bytes_cons(qstr, 'utf8') + qbytes = bytes_cons(qstr, "utf8") qlen = len(qbytes) qhash = compute_hash(qbytes, cfg_bytes_hash) - if all(32 <= ord(c) <= 126 and c != '\\' and c != '"' for c in qstr): + if all(32 <= ord(c) <= 126 and c != "\\" and c != '"' for c in qstr): # qstr is all printable ASCII so render it as-is (for easier debugging) qdata = qstr else: # qstr contains non-printable codes so render entire thing as hex pairs - qdata = ''.join(('\\x%02x' % b) for b in qbytes) + qdata = "".join(("\\x%02x" % b) for b in qbytes) if qlen >= (1 << (8 * cfg_bytes_len)): - print('qstr is too long:', qstr) + print("qstr is too long:", qstr) assert False - qlen_str = ('\\x%02x' * cfg_bytes_len) % tuple(((qlen >> (8 * i)) & 0xff) for i in range(cfg_bytes_len)) - qhash_str = ('\\x%02x' * cfg_bytes_hash) % tuple(((qhash >> (8 * i)) & 0xff) for i in range(cfg_bytes_hash)) + qlen_str = ("\\x%02x" * cfg_bytes_len) % tuple( + ((qlen >> (8 * i)) & 0xFF) for i in range(cfg_bytes_len) + ) + qhash_str = ("\\x%02x" * cfg_bytes_hash) % tuple( + ((qhash >> (8 * i)) & 0xFF) for i in range(cfg_bytes_hash) + ) return '(const byte*)"%s%s" "%s"' % (qhash_str, qlen_str, qdata) + def print_qstr_data(qcfgs, qstrs): # get config variables - cfg_bytes_len = int(qcfgs['BYTES_IN_LEN']) - cfg_bytes_hash = int(qcfgs['BYTES_IN_HASH']) + cfg_bytes_len = int(qcfgs["BYTES_IN_LEN"]) + cfg_bytes_hash = int(qcfgs["BYTES_IN_HASH"]) # print out the starter of the generated C header file - print('// This file was automatically generated by makeqstrdata.py') - print('') + print("// This file was automatically generated by makeqstrdata.py") + print("") # add NULL qstr with no hash or data - print('QDEF(MP_QSTR_NULL, (const byte*)"%s%s" "")' % ('\\x00' * cfg_bytes_hash, '\\x00' * cfg_bytes_len)) + print( + 'QDEF(MP_QSTR_NULL, (const byte*)"%s%s" "")' + % ("\\x00" * cfg_bytes_hash, "\\x00" * cfg_bytes_len) + ) # go through each qstr and print it out for order, ident, qstr in sorted(qstrs.values(), key=lambda x: x[0]): qbytes = make_bytes(cfg_bytes_len, cfg_bytes_hash, qstr) - print('QDEF(MP_QSTR_%s, %s)' % (ident, qbytes)) + print("QDEF(MP_QSTR_%s, %s)" % (ident, qbytes)) + def do_work(infiles): qcfgs, qstrs = parse_input_headers(infiles) print_qstr_data(qcfgs, qstrs) + if __name__ == "__main__": do_work(sys.argv[1:]) diff --git a/py/makeqstrdefs.py b/py/makeqstrdefs.py index 176440136d..ada71a0aa8 100644 --- a/py/makeqstrdefs.py +++ b/py/makeqstrdefs.py @@ -13,7 +13,7 @@ import os # Blacklist of qstrings that are specially handled in further # processing and should be ignored -QSTRING_BLACK_LIST = set(['NULL', 'number_of']) +QSTRING_BLACK_LIST = set(["NULL", "number_of"]) def write_out(fname, output): @@ -23,16 +23,17 @@ def write_out(fname, output): with open(args.output_dir + "/" + fname + ".qstr", "w") as f: f.write("\n".join(output) + "\n") + def process_file(f): re_line = re.compile(r"#[line]*\s\d+\s\"([^\"]+)\"") - re_qstr = re.compile(r'MP_QSTR_[_a-zA-Z0-9]+') + re_qstr = re.compile(r"MP_QSTR_[_a-zA-Z0-9]+") output = [] last_fname = None for line in f: if line.isspace(): continue # match gcc-like output (# n "file") and msvc-like output (#line n "file") - if line.startswith(('# ', '#line')): + if line.startswith(("# ", "#line")): m = re_line.match(line) assert m is not None fname = m.group(1) @@ -44,9 +45,9 @@ def process_file(f): last_fname = fname continue for match in re_qstr.findall(line): - name = match.replace('MP_QSTR_', '') + name = match.replace("MP_QSTR_", "") if name not in QSTRING_BLACK_LIST: - output.append('Q(' + name + ')') + output.append("Q(" + name + ")") write_out(last_fname, output) return "" @@ -55,6 +56,7 @@ def process_file(f): def cat_together(): import glob import hashlib + hasher = hashlib.md5() all_lines = [] outf = open(args.output_dir + "/out", "wb") @@ -68,7 +70,7 @@ def cat_together(): outf.close() hasher.update(all_lines) new_hash = hasher.hexdigest() - #print(new_hash) + # print(new_hash) old_hash = None try: with open(args.output_file + ".hash") as f: @@ -91,11 +93,12 @@ def cat_together(): if __name__ == "__main__": if len(sys.argv) != 5: - print('usage: %s command input_filename output_dir output_file' % sys.argv[0]) + print("usage: %s command input_filename output_dir output_file" % sys.argv[0]) sys.exit(2) class Args: pass + args = Args() args.command = sys.argv[1] args.input_filename = sys.argv[2] diff --git a/py/makeversionhdr.py b/py/makeversionhdr.py index 2ab99d89b4..567b3b8322 100644 --- a/py/makeversionhdr.py +++ b/py/makeversionhdr.py @@ -11,6 +11,7 @@ import os import datetime import subprocess + def get_version_info_from_git(): # Python 2.6 doesn't have check_output, so check for that try: @@ -21,7 +22,11 @@ def get_version_info_from_git(): # Note: git describe doesn't work if no tag is available try: - git_tag = subprocess.check_output(["git", "describe", "--dirty", "--always"], stderr=subprocess.STDOUT, universal_newlines=True).strip() + git_tag = subprocess.check_output( + ["git", "describe", "--dirty", "--always"], + stderr=subprocess.STDOUT, + universal_newlines=True, + ).strip() except subprocess.CalledProcessError as er: if er.returncode == 128: # git exit code of 128 means no repository found @@ -30,7 +35,11 @@ def get_version_info_from_git(): except OSError: return None try: - git_hash = subprocess.check_output(["git", "rev-parse", "--short", "HEAD"], stderr=subprocess.STDOUT, universal_newlines=True).strip() + git_hash = subprocess.check_output( + ["git", "rev-parse", "--short", "HEAD"], + stderr=subprocess.STDOUT, + universal_newlines=True, + ).strip() except subprocess.CalledProcessError: git_hash = "unknown" except OSError: @@ -38,9 +47,13 @@ def get_version_info_from_git(): try: # Check if there are any modified files. - subprocess.check_call(["git", "diff", "--no-ext-diff", "--quiet", "--exit-code"], stderr=subprocess.STDOUT) + subprocess.check_call( + ["git", "diff", "--no-ext-diff", "--quiet", "--exit-code"], stderr=subprocess.STDOUT + ) # Check if there are any staged files. - subprocess.check_call(["git", "diff-index", "--cached", "--quiet", "HEAD", "--"], stderr=subprocess.STDOUT) + subprocess.check_call( + ["git", "diff-index", "--cached", "--quiet", "HEAD", "--"], stderr=subprocess.STDOUT + ) except subprocess.CalledProcessError: git_hash += "-dirty" except OSError: @@ -48,6 +61,7 @@ def get_version_info_from_git(): return git_tag, git_hash + def get_version_info_from_docs_conf(): with open(os.path.join(os.path.dirname(sys.argv[0]), "..", "docs", "conf.py")) as f: for line in f: @@ -57,6 +71,7 @@ def get_version_info_from_docs_conf(): return git_tag, "" return None + def make_version_header(filename): # Get version info using git, with fallback to docs/conf.py info = get_version_info_from_git() @@ -71,12 +86,16 @@ def make_version_header(filename): #define MICROPY_GIT_TAG "%s" #define MICROPY_GIT_HASH "%s" #define MICROPY_BUILD_DATE "%s" -""" % (git_tag, git_hash, datetime.date.today().strftime("%Y-%m-%d")) +""" % ( + git_tag, + git_hash, + datetime.date.today().strftime("%Y-%m-%d"), + ) # Check if the file contents changed from last time write_file = True if os.path.isfile(filename): - with open(filename, 'r') as f: + with open(filename, "r") as f: existing_data = f.read() if existing_data == file_data: write_file = False @@ -84,8 +103,9 @@ def make_version_header(filename): # Only write the file if we need to if write_file: print("GEN %s" % filename) - with open(filename, 'w') as f: + with open(filename, "w") as f: f.write(file_data) + if __name__ == "__main__": make_version_header(sys.argv[1]) diff --git a/py/malloc.c b/py/malloc.c index f8ed1487a5..44be347953 100644 --- a/py/malloc.c +++ b/py/malloc.c @@ -87,22 +87,22 @@ void *m_malloc(size_t num_bytes) { if (ptr == NULL && num_bytes != 0) { m_malloc_fail(num_bytes); } -#if MICROPY_MEM_STATS + #if MICROPY_MEM_STATS MP_STATE_MEM(total_bytes_allocated) += num_bytes; MP_STATE_MEM(current_bytes_allocated) += num_bytes; UPDATE_PEAK(); -#endif + #endif DEBUG_printf("malloc %d : %p\n", num_bytes, ptr); return ptr; } void *m_malloc_maybe(size_t num_bytes) { void *ptr = malloc(num_bytes); -#if MICROPY_MEM_STATS + #if MICROPY_MEM_STATS MP_STATE_MEM(total_bytes_allocated) += num_bytes; MP_STATE_MEM(current_bytes_allocated) += num_bytes; UPDATE_PEAK(); -#endif + #endif DEBUG_printf("malloc %d : %p\n", num_bytes, ptr); return ptr; } @@ -113,11 +113,11 @@ void *m_malloc_with_finaliser(size_t num_bytes) { if (ptr == NULL && num_bytes != 0) { m_malloc_fail(num_bytes); } -#if MICROPY_MEM_STATS + #if MICROPY_MEM_STATS MP_STATE_MEM(total_bytes_allocated) += num_bytes; MP_STATE_MEM(current_bytes_allocated) += num_bytes; UPDATE_PEAK(); -#endif + #endif DEBUG_printf("malloc %d : %p\n", num_bytes, ptr); return ptr; } @@ -136,12 +136,12 @@ void *m_malloc0(size_t num_bytes) { void *m_realloc(void *ptr, size_t old_num_bytes, size_t new_num_bytes) { #else void *m_realloc(void *ptr, size_t new_num_bytes) { -#endif + #endif void *new_ptr = realloc(ptr, new_num_bytes); if (new_ptr == NULL && new_num_bytes != 0) { m_malloc_fail(new_num_bytes); } -#if MICROPY_MEM_STATS + #if MICROPY_MEM_STATS // At first thought, "Total bytes allocated" should only grow, // after all, it's *total*. But consider for example 2K block // shrunk to 1K and then grown to 2K again. It's still 2K @@ -151,7 +151,7 @@ void *m_realloc(void *ptr, size_t new_num_bytes) { MP_STATE_MEM(total_bytes_allocated) += diff; MP_STATE_MEM(current_bytes_allocated) += diff; UPDATE_PEAK(); -#endif + #endif #if MICROPY_MALLOC_USES_ALLOCATED_SIZE DEBUG_printf("realloc %p, %d, %d : %p\n", ptr, old_num_bytes, new_num_bytes, new_ptr); #else @@ -164,9 +164,9 @@ void *m_realloc(void *ptr, size_t new_num_bytes) { void *m_realloc_maybe(void *ptr, size_t old_num_bytes, size_t new_num_bytes, bool allow_move) { #else void *m_realloc_maybe(void *ptr, size_t new_num_bytes, bool allow_move) { -#endif + #endif void *new_ptr = realloc_ext(ptr, new_num_bytes, allow_move); -#if MICROPY_MEM_STATS + #if MICROPY_MEM_STATS // At first thought, "Total bytes allocated" should only grow, // after all, it's *total*. But consider for example 2K block // shrunk to 1K and then grown to 2K again. It's still 2K @@ -179,7 +179,7 @@ void *m_realloc_maybe(void *ptr, size_t new_num_bytes, bool allow_move) { MP_STATE_MEM(current_bytes_allocated) += diff; UPDATE_PEAK(); } -#endif + #endif #if MICROPY_MALLOC_USES_ALLOCATED_SIZE DEBUG_printf("realloc %p, %d, %d : %p\n", ptr, old_num_bytes, new_num_bytes, new_ptr); #else @@ -192,11 +192,11 @@ void *m_realloc_maybe(void *ptr, size_t new_num_bytes, bool allow_move) { void m_free(void *ptr, size_t num_bytes) { #else void m_free(void *ptr) { -#endif + #endif free(ptr); -#if MICROPY_MEM_STATS + #if MICROPY_MEM_STATS MP_STATE_MEM(current_bytes_allocated) -= num_bytes; -#endif + #endif #if MICROPY_MALLOC_USES_ALLOCATED_SIZE DEBUG_printf("free %p, %d\n", ptr, num_bytes); #else diff --git a/py/map.c b/py/map.c index fc5e1b1b75..74807ec996 100644 --- a/py/map.c +++ b/py/map.c @@ -96,7 +96,7 @@ void mp_map_init_fixed_table(mp_map_t *map, size_t n, const mp_obj_t *table) { map->all_keys_are_qstrs = 1; map->is_fixed = 1; map->is_ordered = 1; - map->table = (mp_map_elem_t*)table; + map->table = (mp_map_elem_t *)table; } // Differentiate from mp_map_clear() - semantics is different diff --git a/py/misc.h b/py/misc.h index e6d25b8509..71e7bbfd75 100644 --- a/py/misc.h +++ b/py/misc.h @@ -57,28 +57,28 @@ typedef unsigned int uint; // TODO make a lazy m_renew that can increase by a smaller amount than requested (but by at least 1 more element) -#define m_new(type, num) ((type*)(m_malloc(sizeof(type) * (num)))) -#define m_new_maybe(type, num) ((type*)(m_malloc_maybe(sizeof(type) * (num)))) -#define m_new0(type, num) ((type*)(m_malloc0(sizeof(type) * (num)))) +#define m_new(type, num) ((type *)(m_malloc(sizeof(type) * (num)))) +#define m_new_maybe(type, num) ((type *)(m_malloc_maybe(sizeof(type) * (num)))) +#define m_new0(type, num) ((type *)(m_malloc0(sizeof(type) * (num)))) #define m_new_obj(type) (m_new(type, 1)) #define m_new_obj_maybe(type) (m_new_maybe(type, 1)) -#define m_new_obj_var(obj_type, var_type, var_num) ((obj_type*)m_malloc(sizeof(obj_type) + sizeof(var_type) * (var_num))) -#define m_new_obj_var_maybe(obj_type, var_type, var_num) ((obj_type*)m_malloc_maybe(sizeof(obj_type) + sizeof(var_type) * (var_num))) +#define m_new_obj_var(obj_type, var_type, var_num) ((obj_type *)m_malloc(sizeof(obj_type) + sizeof(var_type) * (var_num))) +#define m_new_obj_var_maybe(obj_type, var_type, var_num) ((obj_type *)m_malloc_maybe(sizeof(obj_type) + sizeof(var_type) * (var_num))) #if MICROPY_ENABLE_FINALISER -#define m_new_obj_with_finaliser(type) ((type*)(m_malloc_with_finaliser(sizeof(type)))) -#define m_new_obj_var_with_finaliser(type, var_type, var_num) ((type*)m_malloc_with_finaliser(sizeof(type) + sizeof(var_type) * (var_num))) +#define m_new_obj_with_finaliser(type) ((type *)(m_malloc_with_finaliser(sizeof(type)))) +#define m_new_obj_var_with_finaliser(type, var_type, var_num) ((type *)m_malloc_with_finaliser(sizeof(type) + sizeof(var_type) * (var_num))) #else #define m_new_obj_with_finaliser(type) m_new_obj(type) #define m_new_obj_var_with_finaliser(type, var_type, var_num) m_new_obj_var(type, var_type, var_num) #endif #if MICROPY_MALLOC_USES_ALLOCATED_SIZE -#define m_renew(type, ptr, old_num, new_num) ((type*)(m_realloc((ptr), sizeof(type) * (old_num), sizeof(type) * (new_num)))) -#define m_renew_maybe(type, ptr, old_num, new_num, allow_move) ((type*)(m_realloc_maybe((ptr), sizeof(type) * (old_num), sizeof(type) * (new_num), (allow_move)))) +#define m_renew(type, ptr, old_num, new_num) ((type *)(m_realloc((ptr), sizeof(type) * (old_num), sizeof(type) * (new_num)))) +#define m_renew_maybe(type, ptr, old_num, new_num, allow_move) ((type *)(m_realloc_maybe((ptr), sizeof(type) * (old_num), sizeof(type) * (new_num), (allow_move)))) #define m_del(type, ptr, num) m_free(ptr, sizeof(type) * (num)) #define m_del_var(obj_type, var_type, var_num, ptr) (m_free(ptr, sizeof(obj_type) + sizeof(var_type) * (var_num))) #else -#define m_renew(type, ptr, old_num, new_num) ((type*)(m_realloc((ptr), sizeof(type) * (new_num)))) -#define m_renew_maybe(type, ptr, old_num, new_num, allow_move) ((type*)(m_realloc_maybe((ptr), sizeof(type) * (new_num), (allow_move)))) +#define m_renew(type, ptr, old_num, new_num) ((type *)(m_realloc((ptr), sizeof(type) * (new_num)))) +#define m_renew_maybe(type, ptr, old_num, new_num, allow_move) ((type *)(m_realloc_maybe((ptr), sizeof(type) * (new_num), (allow_move)))) #define m_del(type, ptr, num) ((void)(num), m_free(ptr)) #define m_del_var(obj_type, var_type, var_num, ptr) ((void)(var_num), m_free(ptr)) #endif @@ -111,7 +111,7 @@ size_t m_get_peak_bytes_allocated(void); #define MP_ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) // align ptr to the nearest multiple of "alignment" -#define MP_ALIGN(ptr, alignment) (void*)(((uintptr_t)(ptr) + ((alignment) - 1)) & ~((alignment) - 1)) +#define MP_ALIGN(ptr, alignment) (void *)(((uintptr_t)(ptr) + ((alignment) - 1)) & ~((alignment) - 1)) /** unichar / UTF-8 *********************************************/ @@ -129,9 +129,16 @@ unichar utf8_get_char(const byte *s); const byte *utf8_next_char(const byte *s); size_t utf8_charlen(const byte *str, size_t len); #else -static inline unichar utf8_get_char(const byte *s) { return *s; } -static inline const byte *utf8_next_char(const byte *s) { return s + 1; } -static inline size_t utf8_charlen(const byte *str, size_t len) { (void)str; return len; } +static inline unichar utf8_get_char(const byte *s) { + return *s; +} +static inline const byte *utf8_next_char(const byte *s) { + return s + 1; +} +static inline size_t utf8_charlen(const byte *str, size_t len) { + (void)str; + return len; +} #endif bool unichar_isspace(unichar c); @@ -168,9 +175,15 @@ void vstr_init_print(vstr_t *vstr, size_t alloc, struct _mp_print_t *print); void vstr_clear(vstr_t *vstr); vstr_t *vstr_new(size_t alloc); void vstr_free(vstr_t *vstr); -static inline void vstr_reset(vstr_t *vstr) { vstr->len = 0; } -static inline char *vstr_str(vstr_t *vstr) { return vstr->buf; } -static inline size_t vstr_len(vstr_t *vstr) { return vstr->len; } +static inline void vstr_reset(vstr_t *vstr) { + vstr->len = 0; +} +static inline char *vstr_str(vstr_t *vstr) { + return vstr->buf; +} +static inline size_t vstr_len(vstr_t *vstr) { + return vstr->len; +} void vstr_hint_size(vstr_t *vstr, size_t size); char *vstr_extend(vstr_t *vstr, size_t size); char *vstr_add_len(vstr_t *vstr, size_t len); @@ -191,10 +204,10 @@ void vstr_printf(vstr_t *vstr, const char *fmt, ...); #define CHECKBUF(buf, max_size) char buf[max_size + 1]; size_t buf##_len = max_size; char *buf##_p = buf; #define CHECKBUF_RESET(buf, max_size) buf##_len = max_size; buf##_p = buf; #define CHECKBUF_APPEND(buf, src, src_len) \ - { size_t l = MIN(src_len, buf##_len); \ - memcpy(buf##_p, src, l); \ - buf##_len -= l; \ - buf##_p += l; } + { size_t l = MIN(src_len, buf##_len); \ + memcpy(buf##_p, src, l); \ + buf##_len -= l; \ + buf##_p += l; } #define CHECKBUF_APPEND_0(buf) { *buf##_p = 0; } #define CHECKBUF_LEN(buf) (buf##_p - buf) diff --git a/py/modarray.c b/py/modarray.c index c0cdca9286..e7134a59ea 100644 --- a/py/modarray.c +++ b/py/modarray.c @@ -37,7 +37,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_array_globals, mp_module_array_globals_tab const mp_obj_module_t mp_module_array = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_array_globals, + .globals = (mp_obj_dict_t *)&mp_module_array_globals, }; #endif diff --git a/py/modbuiltins.c b/py/modbuiltins.c index c4de325c14..402138f296 100644 --- a/py/modbuiltins.c +++ b/py/modbuiltins.c @@ -140,7 +140,8 @@ STATIC mp_obj_t mp_builtin_chr(mp_obj_t o_in) { uint8_t str[4]; int len = 0; if (c < 0x80) { - *str = c; len = 1; + *str = c; + len = 1; } else if (c < 0x800) { str[0] = (c >> 6) | 0xC0; str[1] = (c & 0x3F) | 0x80; @@ -159,12 +160,12 @@ STATIC mp_obj_t mp_builtin_chr(mp_obj_t o_in) { } else { mp_raise_ValueError("chr() arg not in range(0x110000)"); } - return mp_obj_new_str_via_qstr((char*)str, len); + return mp_obj_new_str_via_qstr((char *)str, len); #else mp_int_t ord = mp_obj_get_int(o_in); if (0 <= ord && ord <= 0xff) { uint8_t str[1] = {ord}; - return mp_obj_new_str_via_qstr((char*)str, 1); + return mp_obj_new_str_via_qstr((char *)str, 1); } else { mp_raise_ValueError("chr() arg not in range(256)"); } @@ -338,7 +339,7 @@ MP_DEFINE_CONST_FUN_OBJ_1(mp_builtin_oct_obj, mp_builtin_oct); STATIC mp_obj_t mp_builtin_ord(mp_obj_t o_in) { size_t len; - const byte *str = (const byte*)mp_obj_str_get_data(o_in, &len); + const byte *str = (const byte *)mp_obj_str_get_data(o_in, &len); #if MICROPY_PY_BUILTINS_STR_UNICODE if (MP_OBJ_IS_STR(o_in)) { len = utf8_charlen(str, len); @@ -365,15 +366,16 @@ MP_DEFINE_CONST_FUN_OBJ_1(mp_builtin_ord_obj, mp_builtin_ord); STATIC mp_obj_t mp_builtin_pow(size_t n_args, const mp_obj_t *args) { switch (n_args) { - case 2: return mp_binary_op(MP_BINARY_OP_POWER, args[0], args[1]); + case 2: + return mp_binary_op(MP_BINARY_OP_POWER, args[0], args[1]); default: -#if !MICROPY_PY_BUILTINS_POW3 + #if !MICROPY_PY_BUILTINS_POW3 mp_raise_msg(&mp_type_NotImplementedError, "3-arg pow() not supported"); -#elif MICROPY_LONGINT_IMPL != MICROPY_LONGINT_IMPL_MPZ + #elif MICROPY_LONGINT_IMPL != MICROPY_LONGINT_IMPL_MPZ return mp_binary_op(MP_BINARY_OP_MODULO, mp_binary_op(MP_BINARY_OP_POWER, args[0], args[1]), args[2]); -#else + #else return mp_obj_int_pow3(args[0], args[1], args[2]); -#endif + #endif } } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_builtin_pow_obj, 2, 3, mp_builtin_pow); @@ -468,7 +470,7 @@ STATIC mp_obj_t mp_builtin_round(size_t n_args, const mp_obj_t *args) { } mp_obj_t mult = mp_binary_op(MP_BINARY_OP_POWER, MP_OBJ_NEW_SMALL_INT(10), MP_OBJ_NEW_SMALL_INT(-num_dig)); - mp_obj_t half_mult = mp_binary_op(MP_BINARY_OP_FLOOR_DIVIDE, mult, MP_OBJ_NEW_SMALL_INT(2)); + mp_obj_t half_mult = mp_binary_op(MP_BINARY_OP_FLOOR_DIVIDE, mult, MP_OBJ_NEW_SMALL_INT(2)); mp_obj_t modulo = mp_binary_op(MP_BINARY_OP_MODULO, o_in, mult); mp_obj_t rounded = mp_binary_op(MP_BINARY_OP_SUBTRACT, o_in, modulo); if (mp_obj_is_true(mp_binary_op(MP_BINARY_OP_MORE, half_mult, modulo))) { @@ -486,7 +488,7 @@ STATIC mp_obj_t mp_builtin_round(size_t n_args, const mp_obj_t *args) { } #endif } -#if MICROPY_PY_BUILTINS_FLOAT + #if MICROPY_PY_BUILTINS_FLOAT mp_float_t val = mp_obj_get_float(o_in); if (n_args > 1) { mp_int_t num_dig = mp_obj_get_int(args[1]); @@ -497,18 +499,22 @@ STATIC mp_obj_t mp_builtin_round(size_t n_args, const mp_obj_t *args) { } mp_float_t rounded = MICROPY_FLOAT_C_FUN(nearbyint)(val); return mp_obj_new_int_from_float(rounded); -#else + #else mp_int_t r = mp_obj_get_int(o_in); return mp_obj_new_int(r); -#endif + #endif } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_builtin_round_obj, 1, 2, mp_builtin_round); STATIC mp_obj_t mp_builtin_sum(size_t n_args, const mp_obj_t *args) { mp_obj_t value; switch (n_args) { - case 1: value = MP_OBJ_NEW_SMALL_INT(0); break; - default: value = args[1]; break; + case 1: + value = MP_OBJ_NEW_SMALL_INT(0); + break; + default: + value = args[1]; + break; } mp_obj_iter_buf_t iter_buf; mp_obj_t iterable = mp_getiter(args[0], &iter_buf); @@ -756,5 +762,5 @@ MP_DEFINE_CONST_DICT(mp_module_builtins_globals, mp_module_builtins_globals_tabl const mp_obj_module_t mp_module_builtins = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_builtins_globals, + .globals = (mp_obj_dict_t *)&mp_module_builtins_globals, }; diff --git a/py/modcmath.c b/py/modcmath.c index 70fd542af9..0bda512092 100644 --- a/py/modcmath.c +++ b/py/modcmath.c @@ -43,7 +43,7 @@ STATIC mp_obj_t mp_cmath_polar(mp_obj_t z_obj) { mp_float_t real, imag; mp_obj_get_complex(z_obj, &real, &imag); mp_obj_t tuple[2] = { - mp_obj_new_float(MICROPY_FLOAT_C_FUN(sqrt)(real*real + imag*imag)), + mp_obj_new_float(MICROPY_FLOAT_C_FUN(sqrt)(real * real + imag * imag)), mp_obj_new_float(MICROPY_FLOAT_C_FUN(atan2)(imag, real)), }; return mp_obj_new_tuple(2, tuple); @@ -72,7 +72,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_cmath_exp_obj, mp_cmath_exp); STATIC mp_obj_t mp_cmath_log(mp_obj_t z_obj) { mp_float_t real, imag; mp_obj_get_complex(z_obj, &real, &imag); - return mp_obj_new_complex(0.5 * MICROPY_FLOAT_C_FUN(log)(real*real + imag*imag), MICROPY_FLOAT_C_FUN(atan2)(imag, real)); + return mp_obj_new_complex(0.5 * MICROPY_FLOAT_C_FUN(log)(real * real + imag * imag), MICROPY_FLOAT_C_FUN(atan2)(imag, real)); } STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_cmath_log_obj, mp_cmath_log); @@ -81,7 +81,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_cmath_log_obj, mp_cmath_log); STATIC mp_obj_t mp_cmath_log10(mp_obj_t z_obj) { mp_float_t real, imag; mp_obj_get_complex(z_obj, &real, &imag); - return mp_obj_new_complex(0.5 * MICROPY_FLOAT_C_FUN(log10)(real*real + imag*imag), 0.4342944819032518 * MICROPY_FLOAT_C_FUN(atan2)(imag, real)); + return mp_obj_new_complex(0.5 * MICROPY_FLOAT_C_FUN(log10)(real * real + imag * imag), 0.4342944819032518 * MICROPY_FLOAT_C_FUN(atan2)(imag, real)); } STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_cmath_log10_obj, mp_cmath_log10); #endif @@ -90,7 +90,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_cmath_log10_obj, mp_cmath_log10); STATIC mp_obj_t mp_cmath_sqrt(mp_obj_t z_obj) { mp_float_t real, imag; mp_obj_get_complex(z_obj, &real, &imag); - mp_float_t sqrt_abs = MICROPY_FLOAT_C_FUN(pow)(real*real + imag*imag, 0.25); + mp_float_t sqrt_abs = MICROPY_FLOAT_C_FUN(pow)(real * real + imag * imag, 0.25); mp_float_t theta = 0.5 * MICROPY_FLOAT_C_FUN(atan2)(imag, real); return mp_obj_new_complex(sqrt_abs * MICROPY_FLOAT_C_FUN(cos)(theta), sqrt_abs * MICROPY_FLOAT_C_FUN(sin)(theta)); } @@ -125,28 +125,28 @@ STATIC const mp_rom_map_elem_t mp_module_cmath_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_log10), MP_ROM_PTR(&mp_cmath_log10_obj) }, #endif { MP_ROM_QSTR(MP_QSTR_sqrt), MP_ROM_PTR(&mp_cmath_sqrt_obj) }, - //{ MP_ROM_QSTR(MP_QSTR_acos), MP_ROM_PTR(&mp_cmath_acos_obj) }, - //{ MP_ROM_QSTR(MP_QSTR_asin), MP_ROM_PTR(&mp_cmath_asin_obj) }, - //{ MP_ROM_QSTR(MP_QSTR_atan), MP_ROM_PTR(&mp_cmath_atan_obj) }, + // { MP_ROM_QSTR(MP_QSTR_acos), MP_ROM_PTR(&mp_cmath_acos_obj) }, + // { MP_ROM_QSTR(MP_QSTR_asin), MP_ROM_PTR(&mp_cmath_asin_obj) }, + // { MP_ROM_QSTR(MP_QSTR_atan), MP_ROM_PTR(&mp_cmath_atan_obj) }, { MP_ROM_QSTR(MP_QSTR_cos), MP_ROM_PTR(&mp_cmath_cos_obj) }, { MP_ROM_QSTR(MP_QSTR_sin), MP_ROM_PTR(&mp_cmath_sin_obj) }, - //{ MP_ROM_QSTR(MP_QSTR_tan), MP_ROM_PTR(&mp_cmath_tan_obj) }, - //{ MP_ROM_QSTR(MP_QSTR_acosh), MP_ROM_PTR(&mp_cmath_acosh_obj) }, - //{ MP_ROM_QSTR(MP_QSTR_asinh), MP_ROM_PTR(&mp_cmath_asinh_obj) }, - //{ MP_ROM_QSTR(MP_QSTR_atanh), MP_ROM_PTR(&mp_cmath_atanh_obj) }, - //{ MP_ROM_QSTR(MP_QSTR_cosh), MP_ROM_PTR(&mp_cmath_cosh_obj) }, - //{ MP_ROM_QSTR(MP_QSTR_sinh), MP_ROM_PTR(&mp_cmath_sinh_obj) }, - //{ MP_ROM_QSTR(MP_QSTR_tanh), MP_ROM_PTR(&mp_cmath_tanh_obj) }, - //{ MP_ROM_QSTR(MP_QSTR_isfinite), MP_ROM_PTR(&mp_cmath_isfinite_obj) }, - //{ MP_ROM_QSTR(MP_QSTR_isinf), MP_ROM_PTR(&mp_cmath_isinf_obj) }, - //{ MP_ROM_QSTR(MP_QSTR_isnan), MP_ROM_PTR(&mp_cmath_isnan_obj) }, + // { MP_ROM_QSTR(MP_QSTR_tan), MP_ROM_PTR(&mp_cmath_tan_obj) }, + // { MP_ROM_QSTR(MP_QSTR_acosh), MP_ROM_PTR(&mp_cmath_acosh_obj) }, + // { MP_ROM_QSTR(MP_QSTR_asinh), MP_ROM_PTR(&mp_cmath_asinh_obj) }, + // { MP_ROM_QSTR(MP_QSTR_atanh), MP_ROM_PTR(&mp_cmath_atanh_obj) }, + // { MP_ROM_QSTR(MP_QSTR_cosh), MP_ROM_PTR(&mp_cmath_cosh_obj) }, + // { MP_ROM_QSTR(MP_QSTR_sinh), MP_ROM_PTR(&mp_cmath_sinh_obj) }, + // { MP_ROM_QSTR(MP_QSTR_tanh), MP_ROM_PTR(&mp_cmath_tanh_obj) }, + // { MP_ROM_QSTR(MP_QSTR_isfinite), MP_ROM_PTR(&mp_cmath_isfinite_obj) }, + // { MP_ROM_QSTR(MP_QSTR_isinf), MP_ROM_PTR(&mp_cmath_isinf_obj) }, + // { MP_ROM_QSTR(MP_QSTR_isnan), MP_ROM_PTR(&mp_cmath_isnan_obj) }, }; STATIC MP_DEFINE_CONST_DICT(mp_module_cmath_globals, mp_module_cmath_globals_table); const mp_obj_module_t mp_module_cmath = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_cmath_globals, + .globals = (mp_obj_dict_t *)&mp_module_cmath_globals, }; #endif // MICROPY_PY_BUILTINS_FLOAT && MICROPY_PY_CMATH diff --git a/py/modcollections.c b/py/modcollections.c index bb6488471c..c145f12cc6 100644 --- a/py/modcollections.c +++ b/py/modcollections.c @@ -43,7 +43,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_collections_globals, mp_module_collections const mp_obj_module_t mp_module_collections = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_collections_globals, + .globals = (mp_obj_dict_t *)&mp_module_collections_globals, }; #endif // MICROPY_PY_COLLECTIONS diff --git a/py/modgc.c b/py/modgc.c index 55e73defce..534a711c16 100644 --- a/py/modgc.c +++ b/py/modgc.c @@ -33,11 +33,11 @@ // collect(): run a garbage collection STATIC mp_obj_t py_gc_collect(void) { gc_collect(); -#if MICROPY_PY_GC_COLLECT_RETVAL + #if MICROPY_PY_GC_COLLECT_RETVAL return MP_OBJ_NEW_SMALL_INT(MP_STATE_MEM(gc_collected)); -#else + #else return mp_const_none; -#endif + #endif } MP_DEFINE_CONST_FUN_OBJ_0(gc_collect_obj, py_gc_collect); @@ -112,7 +112,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_gc_globals, mp_module_gc_globals_table); const mp_obj_module_t mp_module_gc = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_gc_globals, + .globals = (mp_obj_dict_t *)&mp_module_gc_globals, }; #endif diff --git a/py/modio.c b/py/modio.c index b4d033238f..f56150c324 100644 --- a/py/modio.c +++ b/py/modio.c @@ -72,7 +72,7 @@ STATIC mp_uint_t iobase_read(mp_obj_t obj, void *buf, mp_uint_t size, int *errco } STATIC mp_uint_t iobase_write(mp_obj_t obj, const void *buf, mp_uint_t size, int *errcode) { - return iobase_read_write(obj, (void*)buf, size, errcode, MP_QSTR_write); + return iobase_read_write(obj, (void *)buf, size, errcode, MP_QSTR_write); } STATIC mp_uint_t iobase_ioctl(mp_obj_t obj, mp_uint_t request, uintptr_t arg, int *errcode) { @@ -144,7 +144,7 @@ STATIC mp_uint_t bufwriter_write(mp_obj_t self_in, const void *buf, mp_uint_t si // is word-aligned, to guard against obscure cases when it matters, e.g. // https://github.com/micropython/micropython/issues/1863 memcpy(self->buf + self->len, buf, rem); - buf = (byte*)buf + rem; + buf = (byte *)buf + rem; size -= rem; mp_uint_t out_sz = mp_stream_write_exactly(self->stream, self->buf, self->alloc, errcode); if (*errcode != 0) { @@ -193,7 +193,7 @@ STATIC const mp_obj_type_t bufwriter_type = { .name = MP_QSTR_BufferedWriter, .make_new = bufwriter_make_new, .protocol = &bufwriter_stream_p, - .locals_dict = (mp_obj_dict_t*)&bufwriter_locals_dict, + .locals_dict = (mp_obj_dict_t *)&bufwriter_locals_dict, }; #endif // MICROPY_PY_IO_BUFFEREDWRITER @@ -236,14 +236,14 @@ STATIC mp_obj_t resource_stream(mp_obj_t package_in, mp_obj_t path_in) { mp_obj_stringio_t *o = m_new_obj(mp_obj_stringio_t); o->base.type = &mp_type_bytesio; o->vstr = m_new_obj(vstr_t); - vstr_init_fixed_buf(o->vstr, len + 1, (char*)data); + vstr_init_fixed_buf(o->vstr, len + 1, (char *)data); o->vstr->len = len; o->pos = 0; return MP_OBJ_FROM_PTR(o); } mp_obj_t path_out = mp_obj_new_str(path_buf.buf, path_buf.len); - return mp_builtin_open(1, &path_out, (mp_map_t*)&mp_const_empty_map); + return mp_builtin_open(1, &path_out, (mp_map_t *)&mp_const_empty_map); } STATIC MP_DEFINE_CONST_FUN_OBJ_2(resource_stream_obj, resource_stream); #endif @@ -278,7 +278,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_io_globals, mp_module_io_globals_table); const mp_obj_module_t mp_module_io = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_io_globals, + .globals = (mp_obj_dict_t *)&mp_module_io_globals, }; #endif diff --git a/py/modmath.c b/py/modmath.c index d106f240c8..2e2b676541 100644 --- a/py/modmath.c +++ b/py/modmath.c @@ -59,30 +59,30 @@ STATIC mp_obj_t math_generic_2(mp_obj_t x_obj, mp_obj_t y_obj, mp_float_t (*f)(m } #define MATH_FUN_1(py_name, c_name) \ - STATIC mp_obj_t mp_math_ ## py_name(mp_obj_t x_obj) { \ + STATIC mp_obj_t mp_math_##py_name(mp_obj_t x_obj) { \ return math_generic_1(x_obj, MICROPY_FLOAT_C_FUN(c_name)); \ } \ - STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_math_## py_name ## _obj, mp_math_ ## py_name); + STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_math_##py_name##_obj, mp_math_##py_name); #define MATH_FUN_1_TO_BOOL(py_name, c_name) \ - STATIC mp_obj_t mp_math_ ## py_name(mp_obj_t x_obj) { return mp_obj_new_bool(c_name(mp_obj_get_float(x_obj))); } \ - STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_math_## py_name ## _obj, mp_math_ ## py_name); + STATIC mp_obj_t mp_math_##py_name(mp_obj_t x_obj) { return mp_obj_new_bool(c_name(mp_obj_get_float(x_obj))); } \ + STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_math_##py_name##_obj, mp_math_##py_name); #define MATH_FUN_1_TO_INT(py_name, c_name) \ - STATIC mp_obj_t mp_math_ ## py_name(mp_obj_t x_obj) { return mp_obj_new_int_from_float(MICROPY_FLOAT_C_FUN(c_name)(mp_obj_get_float(x_obj))); } \ - STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_math_## py_name ## _obj, mp_math_ ## py_name); + STATIC mp_obj_t mp_math_##py_name(mp_obj_t x_obj) { return mp_obj_new_int_from_float(MICROPY_FLOAT_C_FUN(c_name)(mp_obj_get_float(x_obj))); } \ + STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_math_##py_name##_obj, mp_math_##py_name); #define MATH_FUN_2(py_name, c_name) \ - STATIC mp_obj_t mp_math_ ## py_name(mp_obj_t x_obj, mp_obj_t y_obj) { \ + STATIC mp_obj_t mp_math_##py_name(mp_obj_t x_obj, mp_obj_t y_obj) { \ return math_generic_2(x_obj, y_obj, MICROPY_FLOAT_C_FUN(c_name)); \ } \ - STATIC MP_DEFINE_CONST_FUN_OBJ_2(mp_math_## py_name ## _obj, mp_math_ ## py_name); + STATIC MP_DEFINE_CONST_FUN_OBJ_2(mp_math_##py_name##_obj, mp_math_##py_name); #define MATH_FUN_2_FLT_INT(py_name, c_name) \ - STATIC mp_obj_t mp_math_ ## py_name(mp_obj_t x_obj, mp_obj_t y_obj) { \ + STATIC mp_obj_t mp_math_##py_name(mp_obj_t x_obj, mp_obj_t y_obj) { \ return mp_obj_new_float(MICROPY_FLOAT_C_FUN(c_name)(mp_obj_get_float(x_obj), mp_obj_get_int(y_obj))); \ } \ - STATIC MP_DEFINE_CONST_FUN_OBJ_2(mp_math_## py_name ## _obj, mp_math_ ## py_name); + STATIC MP_DEFINE_CONST_FUN_OBJ_2(mp_math_##py_name##_obj, mp_math_##py_name); #if MP_NEED_LOG2 #undef log2 @@ -146,7 +146,7 @@ STATIC mp_float_t MICROPY_FLOAT_C_FUN(fabs_func)(mp_float_t x) { } MATH_FUN_1(fabs, fabs_func) // floor(x) -MATH_FUN_1_TO_INT(floor, floor) //TODO: delegate to x.__floor__() if x is not a float +MATH_FUN_1_TO_INT(floor, floor) // TODO: delegate to x.__floor__() if x is not a float // fmod(x, y) MATH_FUN_2(fmod, fmod) // isfinite(x) @@ -169,7 +169,7 @@ MATH_FUN_1(gamma, tgamma) // lgamma(x): return the natural logarithm of the gamma function of x MATH_FUN_1(lgamma, lgamma) #endif -//TODO: fsum +// TODO: fsum // Function that takes a variable number of arguments @@ -353,7 +353,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_math_globals, mp_module_math_globals_table const mp_obj_module_t mp_module_math = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_math_globals, + .globals = (mp_obj_dict_t *)&mp_module_math_globals, }; #endif // MICROPY_PY_BUILTINS_FLOAT && MICROPY_PY_MATH diff --git a/py/modmicropython.c b/py/modmicropython.c index 864d1a5c5b..6902e69e7a 100644 --- a/py/modmicropython.c +++ b/py/modmicropython.c @@ -68,25 +68,25 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_0(mp_micropython_mem_peak_obj, mp_micropython_mem mp_obj_t mp_micropython_mem_info(size_t n_args, const mp_obj_t *args) { (void)args; -#if MICROPY_MEM_STATS + #if MICROPY_MEM_STATS mp_printf(&mp_plat_print, "mem: total=" UINT_FMT ", current=" UINT_FMT ", peak=" UINT_FMT "\n", (mp_uint_t)m_get_total_bytes_allocated(), (mp_uint_t)m_get_current_bytes_allocated(), (mp_uint_t)m_get_peak_bytes_allocated()); -#endif -#if MICROPY_STACK_CHECK + #endif + #if MICROPY_STACK_CHECK mp_printf(&mp_plat_print, "stack: " UINT_FMT " out of " UINT_FMT "\n", mp_stack_usage(), (mp_uint_t)MP_STATE_THREAD(stack_limit)); -#else + #else mp_printf(&mp_plat_print, "stack: " UINT_FMT "\n", mp_stack_usage()); -#endif -#if MICROPY_ENABLE_GC + #endif + #if MICROPY_ENABLE_GC gc_dump_info(); if (n_args == 1) { // arg given means dump gc allocation table gc_dump_alloc_table(); } -#else + #else (void)n_args; -#endif + #endif return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_micropython_mem_info_obj, 0, 1, mp_micropython_mem_info); @@ -163,21 +163,21 @@ STATIC const mp_rom_map_elem_t mp_module_micropython_globals_table[] = { #if MICROPY_ENABLE_COMPILER { MP_ROM_QSTR(MP_QSTR_opt_level), MP_ROM_PTR(&mp_micropython_opt_level_obj) }, #endif -#if MICROPY_PY_MICROPYTHON_MEM_INFO -#if MICROPY_MEM_STATS + #if MICROPY_PY_MICROPYTHON_MEM_INFO + #if MICROPY_MEM_STATS { MP_ROM_QSTR(MP_QSTR_mem_total), MP_ROM_PTR(&mp_micropython_mem_total_obj) }, { MP_ROM_QSTR(MP_QSTR_mem_current), MP_ROM_PTR(&mp_micropython_mem_current_obj) }, { MP_ROM_QSTR(MP_QSTR_mem_peak), MP_ROM_PTR(&mp_micropython_mem_peak_obj) }, -#endif + #endif { MP_ROM_QSTR(MP_QSTR_mem_info), MP_ROM_PTR(&mp_micropython_mem_info_obj) }, { MP_ROM_QSTR(MP_QSTR_qstr_info), MP_ROM_PTR(&mp_micropython_qstr_info_obj) }, -#endif + #endif #if MICROPY_PY_MICROPYTHON_STACK_USE { MP_ROM_QSTR(MP_QSTR_stack_use), MP_ROM_PTR(&mp_micropython_stack_use_obj) }, #endif -#if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF && (MICROPY_EMERGENCY_EXCEPTION_BUF_SIZE == 0) + #if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF && (MICROPY_EMERGENCY_EXCEPTION_BUF_SIZE == 0) { MP_ROM_QSTR(MP_QSTR_alloc_emergency_exception_buf), MP_ROM_PTR(&mp_alloc_emergency_exception_buf_obj) }, -#endif + #endif #if MICROPY_ENABLE_PYSTACK { MP_ROM_QSTR(MP_QSTR_pystack_use), MP_ROM_PTR(&mp_micropython_pystack_use_obj) }, #endif @@ -197,5 +197,5 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_micropython_globals, mp_module_micropython const mp_obj_module_t mp_module_micropython = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_micropython_globals, + .globals = (mp_obj_dict_t *)&mp_module_micropython_globals, }; diff --git a/py/modstruct.c b/py/modstruct.c index 8617a8e0d3..35233ade1c 100644 --- a/py/modstruct.c +++ b/py/modstruct.c @@ -215,7 +215,7 @@ STATIC mp_obj_t struct_pack(size_t n_args, const mp_obj_t *args) { mp_int_t size = MP_OBJ_SMALL_INT_VALUE(struct_calcsize(args[0])); vstr_t vstr; vstr_init_len(&vstr, size); - byte *p = (byte*)vstr.buf; + byte *p = (byte *)vstr.buf; memset(p, 0, size); struct_pack_into_internal(args[0], p, n_args - 1, &args[1]); return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr); @@ -261,7 +261,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_struct_globals, mp_module_struct_globals_t const mp_obj_module_t mp_module_ustruct = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_struct_globals, + .globals = (mp_obj_dict_t *)&mp_module_struct_globals, }; #endif diff --git a/py/modsys.c b/py/modsys.c index 3434517328..4f3aeccd13 100644 --- a/py/modsys.c +++ b/py/modsys.c @@ -67,9 +67,9 @@ STATIC MP_DEFINE_ATTRTUPLE( mp_sys_implementation_obj, impl_fields, 2, - MP_ROM_QSTR(MP_QSTR_micropython), - MP_ROM_PTR(&mp_sys_implementation_version_info_obj) -); + MP_ROM_QSTR(MP_QSTR_micropython), + MP_ROM_PTR(&mp_sys_implementation_version_info_obj) + ); #else STATIC const mp_rom_obj_tuple_t mp_sys_implementation_obj = { {&mp_type_tuple}, @@ -207,7 +207,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_sys_globals, mp_module_sys_globals_table); const mp_obj_module_t mp_module_sys = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_sys_globals, + .globals = (mp_obj_dict_t *)&mp_module_sys_globals, }; #endif diff --git a/py/modthread.c b/py/modthread.c index 61ada50351..828b3efa51 100644 --- a/py/modthread.c +++ b/py/modthread.c @@ -120,7 +120,7 @@ STATIC MP_DEFINE_CONST_DICT(thread_lock_locals_dict, thread_lock_locals_dict_tab STATIC const mp_obj_type_t mp_type_thread_lock = { { &mp_type_type }, .name = MP_QSTR_lock, - .locals_dict = (mp_obj_dict_t*)&thread_lock_locals_dict, + .locals_dict = (mp_obj_dict_t *)&thread_lock_locals_dict, }; /****************************************************************/ @@ -157,7 +157,7 @@ typedef struct _thread_entry_args_t { STATIC void *thread_entry(void *args_in) { // Execution begins here for a new thread. We do not have the GIL. - thread_entry_args_t *args = (thread_entry_args_t*)args_in; + thread_entry_args_t *args = (thread_entry_args_t *)args_in; mp_state_thread_t ts; mp_thread_set_state(&ts); @@ -193,7 +193,7 @@ STATIC void *thread_entry(void *args_in) { } else { // uncaught exception // check for SystemExit - mp_obj_base_t *exc = (mp_obj_base_t*)nlr.ret_val; + mp_obj_base_t *exc = (mp_obj_base_t *)nlr.ret_val; if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(exc->type), MP_OBJ_FROM_PTR(&mp_type_SystemExit))) { // swallow exception silently } else { @@ -237,7 +237,7 @@ STATIC mp_obj_t mod_thread_start_new_thread(size_t n_args, const mp_obj_t *args) if (mp_obj_get_type(args[2]) != &mp_type_dict) { mp_raise_TypeError("expecting a dict for keyword args"); } - mp_map_t *map = &((mp_obj_dict_t*)MP_OBJ_TO_PTR(args[2]))->map; + mp_map_t *map = &((mp_obj_dict_t *)MP_OBJ_TO_PTR(args[2]))->map; th_args = m_new_obj_var(thread_entry_args_t, mp_obj_t, pos_args_len + 2 * map->used); th_args->n_kw = map->used; // copy across the keyword arguments @@ -294,7 +294,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_thread_globals, mp_module_thread_globals_t const mp_obj_module_t mp_module_thread = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_thread_globals, + .globals = (mp_obj_dict_t *)&mp_module_thread_globals, }; #endif // MICROPY_PY_THREAD diff --git a/py/moduerrno.c b/py/moduerrno.c index de66c941b0..02821693f1 100644 --- a/py/moduerrno.c +++ b/py/moduerrno.c @@ -63,9 +63,9 @@ #if MICROPY_PY_UERRNO_ERRORCODE STATIC const mp_rom_map_elem_t errorcode_table[] = { - #define X(e) { MP_ROM_INT(MP_ ## e), MP_ROM_QSTR(MP_QSTR_## e) }, + #define X(e) { MP_ROM_INT(MP_##e), MP_ROM_QSTR(MP_QSTR_##e) }, MICROPY_PY_UERRNO_LIST - #undef X +#undef X }; STATIC const mp_obj_dict_t errorcode_dict = { @@ -76,7 +76,7 @@ STATIC const mp_obj_dict_t errorcode_dict = { .is_ordered = 1, .used = MP_ARRAY_SIZE(errorcode_table), .alloc = MP_ARRAY_SIZE(errorcode_table), - .table = (mp_map_elem_t*)(mp_rom_map_elem_t*)errorcode_table, + .table = (mp_map_elem_t *)(mp_rom_map_elem_t *)errorcode_table, }, }; #endif @@ -87,22 +87,22 @@ STATIC const mp_rom_map_elem_t mp_module_uerrno_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_errorcode), MP_ROM_PTR(&errorcode_dict) }, #endif - #define X(e) { MP_ROM_QSTR(MP_QSTR_## e), MP_ROM_INT(MP_ ## e) }, + #define X(e) { MP_ROM_QSTR(MP_QSTR_##e), MP_ROM_INT(MP_##e) }, MICROPY_PY_UERRNO_LIST - #undef X +#undef X }; STATIC MP_DEFINE_CONST_DICT(mp_module_uerrno_globals, mp_module_uerrno_globals_table); const mp_obj_module_t mp_module_uerrno = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_uerrno_globals, + .globals = (mp_obj_dict_t *)&mp_module_uerrno_globals, }; qstr mp_errno_to_str(mp_obj_t errno_val) { #if MICROPY_PY_UERRNO_ERRORCODE // We have the errorcode dict so can do a lookup using the hash map - mp_map_elem_t *elem = mp_map_lookup((mp_map_t*)&errorcode_dict.map, errno_val, MP_MAP_LOOKUP); + mp_map_elem_t *elem = mp_map_lookup((mp_map_t *)&errorcode_dict.map, errno_val, MP_MAP_LOOKUP); if (elem == NULL) { return MP_QSTR_NULL; } else { @@ -119,4 +119,4 @@ qstr mp_errno_to_str(mp_obj_t errno_val) { #endif } -#endif //MICROPY_PY_UERRNO +#endif // MICROPY_PY_UERRNO diff --git a/py/mpconfig.h b/py/mpconfig.h index ce1a8cbfc2..75cd327d01 100644 --- a/py/mpconfig.h +++ b/py/mpconfig.h @@ -34,8 +34,8 @@ // Combined version as a 32-bit number for convenience #define MICROPY_VERSION ( \ MICROPY_VERSION_MAJOR << 16 \ - | MICROPY_VERSION_MINOR << 8 \ - | MICROPY_VERSION_MICRO) + | MICROPY_VERSION_MINOR << 8 \ + | MICROPY_VERSION_MICRO) // String version #define MICROPY_VERSION_STRING \ @@ -512,9 +512,9 @@ #define MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF (0) #endif #if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF -# ifndef MICROPY_EMERGENCY_EXCEPTION_BUF_SIZE -# define MICROPY_EMERGENCY_EXCEPTION_BUF_SIZE (0) // 0 - implies dynamic allocation -# endif +#ifndef MICROPY_EMERGENCY_EXCEPTION_BUF_SIZE +#define MICROPY_EMERGENCY_EXCEPTION_BUF_SIZE (0) // 0 - implies dynamic allocation +#endif #endif // Whether to provide the mp_kbd_exception object, and micropython.kbd_intr function @@ -1383,7 +1383,7 @@ typedef double mp_float_t; #elif defined(MP_ENDIANNESS_BIG) #define MP_ENDIANNESS_LITTLE (!MP_ENDIANNESS_BIG) #else - // Endianness not defined by port so try to autodetect it. +// Endianness not defined by port so try to autodetect it. #if defined(__BYTE_ORDER__) #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ #define MP_ENDIANNESS_LITTLE (1) @@ -1446,7 +1446,7 @@ typedef double mp_float_t; #define UINT_FMT "%u" #define INT_FMT "%d" #endif -#endif //INT_FMT +#endif // INT_FMT // Modifier for function which doesn't return #ifndef NORETURN @@ -1480,21 +1480,21 @@ typedef double mp_float_t; #ifndef MP_HTOBE16 #if MP_ENDIANNESS_LITTLE -# define MP_HTOBE16(x) ((uint16_t)( (((x) & 0xff) << 8) | (((x) >> 8) & 0xff) )) -# define MP_BE16TOH(x) MP_HTOBE16(x) +#define MP_HTOBE16(x) ((uint16_t)((((x) & 0xff) << 8) | (((x) >> 8) & 0xff))) +#define MP_BE16TOH(x) MP_HTOBE16(x) #else -# define MP_HTOBE16(x) (x) -# define MP_BE16TOH(x) (x) +#define MP_HTOBE16(x) (x) +#define MP_BE16TOH(x) (x) #endif #endif #ifndef MP_HTOBE32 #if MP_ENDIANNESS_LITTLE -# define MP_HTOBE32(x) ((uint32_t)( (((x) & 0xff) << 24) | (((x) & 0xff00) << 8) | (((x) >> 8) & 0xff00) | (((x) >> 24) & 0xff) )) -# define MP_BE32TOH(x) MP_HTOBE32(x) +#define MP_HTOBE32(x) ((uint32_t)((((x) & 0xff) << 24) | (((x) & 0xff00) << 8) | (((x) >> 8) & 0xff00) | (((x) >> 24) & 0xff))) +#define MP_BE32TOH(x) MP_HTOBE32(x) #else -# define MP_HTOBE32(x) (x) -# define MP_BE32TOH(x) (x) +#define MP_HTOBE32(x) (x) +#define MP_BE32TOH(x) (x) #endif #endif diff --git a/py/mpprint.c b/py/mpprint.c index c2e65301c9..c1763394cc 100644 --- a/py/mpprint.c +++ b/py/mpprint.c @@ -269,14 +269,14 @@ int mp_print_mp_int(const mp_print_t *print, mp_obj_t x, int base, int base_char // We add the pad in this function, so since the pad goes after // the sign & prefix, we format without a prefix str = mp_obj_int_formatted(&buf, &buf_size, &fmt_size, - x, base, NULL, base_char, comma); + x, base, NULL, base_char, comma); if (*str == '-') { sign = *str++; fmt_size--; } } else { str = mp_obj_int_formatted(&buf, &buf_size, &fmt_size, - x, base, prefix, base_char, comma); + x, base, prefix, base_char, comma); } int spaces_before = 0; @@ -347,8 +347,7 @@ int mp_print_float(const mp_print_t *print, mp_float_t f, char fmt, int flags, c if (flags & PF_FLAG_SHOW_SIGN) { sign = '+'; - } - else + } else if (flags & PF_FLAG_SPACE_SIGN) { sign = ' '; } @@ -411,14 +410,20 @@ int mp_vprintf(const mp_print_t *print, const char *fmt, va_list args) { int flags = 0; char fill = ' '; while (*fmt != '\0') { - if (*fmt == '-') flags |= PF_FLAG_LEFT_ADJUST; - else if (*fmt == '+') flags |= PF_FLAG_SHOW_SIGN; - else if (*fmt == ' ') flags |= PF_FLAG_SPACE_SIGN; - else if (*fmt == '!') flags |= PF_FLAG_NO_TRAILZ; - else if (*fmt == '0') { + if (*fmt == '-') { + flags |= PF_FLAG_LEFT_ADJUST; + } else if (*fmt == '+') { + flags |= PF_FLAG_SHOW_SIGN; + } else if (*fmt == ' ') { + flags |= PF_FLAG_SPACE_SIGN; + } else if (*fmt == '!') { + flags |= PF_FLAG_NO_TRAILZ; + } else if (*fmt == '0') { flags |= PF_FLAG_PAD_AFTER_SIGN; fill = '0'; - } else break; + } else { + break; + } ++fmt; } @@ -470,26 +475,23 @@ int mp_vprintf(const mp_print_t *print, const char *fmt, va_list args) { chrs += mp_print_strn(print, "false", 5, flags, fill, width); } break; - case 'c': - { + case 'c': { char str = va_arg(args, int); chrs += mp_print_strn(print, &str, 1, flags, fill, width); break; } - case 'q': - { + case 'q': { qstr qst = va_arg(args, qstr); size_t len; - const char *str = (const char*)qstr_data(qst, &len); + const char *str = (const char *)qstr_data(qst, &len); if (prec < 0) { prec = len; } chrs += mp_print_strn(print, str, prec, flags, fill, width); break; } - case 's': - { - const char *str = va_arg(args, const char*); + case 's': { + const char *str = va_arg(args, const char *); #ifndef NDEBUG // With debugging enabled, catch printing of null string pointers if (prec != 0 && str == NULL) { @@ -526,26 +528,25 @@ int mp_vprintf(const mp_print_t *print, const char *fmt, va_list args) { // Use unsigned long int to work on both ILP32 and LP64 systems chrs += mp_print_int(print, va_arg(args, unsigned long int), 0, 16, 'a', flags, fill, width); break; -#if MICROPY_PY_BUILTINS_FLOAT + #if MICROPY_PY_BUILTINS_FLOAT case 'e': case 'E': case 'f': case 'F': case 'g': - case 'G': - { -#if ((MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT) || (MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE)) + case 'G': { + #if ((MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT) || (MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE)) mp_float_t f = va_arg(args, double); chrs += mp_print_float(print, f, *fmt, flags, fill, width, prec); -#else -#error Unknown MICROPY FLOAT IMPL -#endif + #else + #error Unknown MICROPY FLOAT IMPL + #endif break; } -#endif - // Because 'l' is eaten above, another 'l' means %ll. We need to support - // this length specifier for OBJ_REPR_D (64-bit NaN boxing). - // TODO Either enable this unconditionally, or provide a specific config var. + #endif + // Because 'l' is eaten above, another 'l' means %ll. We need to support + // this length specifier for OBJ_REPR_D (64-bit NaN boxing). + // TODO Either enable this unconditionally, or provide a specific config var. #if (MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_D) || defined(_WIN64) case 'l': { unsigned long long int arg_value = va_arg(args, unsigned long long int); diff --git a/py/mpprint.h b/py/mpprint.h index 07462bddcc..aef9015deb 100644 --- a/py/mpprint.h +++ b/py/mpprint.h @@ -40,9 +40,9 @@ #define PF_FLAG_SHOW_OCTAL_LETTER (0x200) #if MICROPY_PY_IO && MICROPY_PY_SYS_STDFILES -# define MP_PYTHON_PRINTER &mp_sys_stdout_print +#define MP_PYTHON_PRINTER &mp_sys_stdout_print #else -# define MP_PYTHON_PRINTER &mp_plat_print +#define MP_PYTHON_PRINTER &mp_plat_print #endif typedef void (*mp_print_strn_t)(void *data, const char *str, size_t len); diff --git a/py/mpthread.h b/py/mpthread.h index 602df830c4..25a9dd3c36 100644 --- a/py/mpthread.h +++ b/py/mpthread.h @@ -40,7 +40,7 @@ struct _mp_state_thread_t; struct _mp_state_thread_t *mp_thread_get_state(void); void mp_thread_set_state(void *state); -void mp_thread_create(void *(*entry)(void*), void *arg, size_t *stack_size); +void mp_thread_create(void *(*entry)(void *), void *arg, size_t *stack_size); void mp_thread_start(void); void mp_thread_finish(void); void mp_thread_mutex_init(mp_thread_mutex_t *mutex); diff --git a/py/mpz.c b/py/mpz.c index 8687092d02..b0aef984f7 100644 --- a/py/mpz.c +++ b/py/mpz.c @@ -60,13 +60,21 @@ STATIC size_t mpn_remove_trailing_zeros(mpz_dig_t *oidig, mpz_dig_t *idig) { assumes i, j are normalised */ STATIC int mpn_cmp(const mpz_dig_t *idig, size_t ilen, const mpz_dig_t *jdig, size_t jlen) { - if (ilen < jlen) { return -1; } - if (ilen > jlen) { return 1; } + if (ilen < jlen) { + return -1; + } + if (ilen > jlen) { + return 1; + } for (idig += ilen, jdig += ilen; ilen > 0; --ilen) { mpz_dbl_dig_signed_t cmp = (mpz_dbl_dig_t)*(--idig) - (mpz_dbl_dig_t)*(--jdig); - if (cmp < 0) { return -1; } - if (cmp > 0) { return 1; } + if (cmp < 0) { + return -1; + } + if (cmp > 0) { + return 1; + } } return 0; @@ -228,7 +236,7 @@ STATIC size_t mpn_and(mpz_dig_t *idig, const mpz_dig_t *jdig, const mpz_dig_t *k can have i, j, k pointing to same memory */ STATIC size_t mpn_and_neg(mpz_dig_t *idig, const mpz_dig_t *jdig, size_t jlen, const mpz_dig_t *kdig, size_t klen, - mpz_dbl_dig_t carryi, mpz_dbl_dig_t carryj, mpz_dbl_dig_t carryk) { + mpz_dbl_dig_t carryi, mpz_dbl_dig_t carryj, mpz_dbl_dig_t carryk) { mpz_dig_t *oidig = idig; mpz_dig_t imask = (0 == carryi) ? 0 : DIG_MASK; mpz_dig_t jmask = (0 == carryj) ? 0 : DIG_MASK; @@ -289,7 +297,7 @@ STATIC size_t mpn_or(mpz_dig_t *idig, const mpz_dig_t *jdig, size_t jlen, const #if MICROPY_OPT_MPZ_BITWISE STATIC size_t mpn_or_neg(mpz_dig_t *idig, const mpz_dig_t *jdig, size_t jlen, const mpz_dig_t *kdig, size_t klen, - mpz_dbl_dig_t carryj, mpz_dbl_dig_t carryk) { + mpz_dbl_dig_t carryj, mpz_dbl_dig_t carryk) { mpz_dig_t *oidig = idig; mpz_dbl_dig_t carryi = 1; mpz_dig_t jmask = (0 == carryj) ? 0 : DIG_MASK; @@ -319,7 +327,7 @@ STATIC size_t mpn_or_neg(mpz_dig_t *idig, const mpz_dig_t *jdig, size_t jlen, co #else STATIC size_t mpn_or_neg(mpz_dig_t *idig, const mpz_dig_t *jdig, size_t jlen, const mpz_dig_t *kdig, size_t klen, - mpz_dbl_dig_t carryi, mpz_dbl_dig_t carryj, mpz_dbl_dig_t carryk) { + mpz_dbl_dig_t carryi, mpz_dbl_dig_t carryj, mpz_dbl_dig_t carryk) { mpz_dig_t *oidig = idig; mpz_dig_t imask = (0 == carryi) ? 0 : DIG_MASK; mpz_dig_t jmask = (0 == carryj) ? 0 : DIG_MASK; @@ -378,7 +386,7 @@ STATIC size_t mpn_xor(mpz_dig_t *idig, const mpz_dig_t *jdig, size_t jlen, const can have i, j, k pointing to same memory */ STATIC size_t mpn_xor_neg(mpz_dig_t *idig, const mpz_dig_t *jdig, size_t jlen, const mpz_dig_t *kdig, size_t klen, - mpz_dbl_dig_t carryi, mpz_dbl_dig_t carryj, mpz_dbl_dig_t carryk) { + mpz_dbl_dig_t carryi, mpz_dbl_dig_t carryj, mpz_dbl_dig_t carryk) { mpz_dig_t *oidig = idig; for (; jlen > 0; ++idig, ++jdig) { @@ -771,17 +779,19 @@ void mpz_set_from_ll(mpz_t *z, long long val, bool is_signed) { #if MICROPY_PY_BUILTINS_FLOAT void mpz_set_from_float(mpz_t *z, mp_float_t src) { -#if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE -typedef uint64_t mp_float_int_t; -#elif MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT -typedef uint32_t mp_float_int_t; -#endif + #if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE + typedef uint64_t mp_float_int_t; + #elif MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT + typedef uint32_t mp_float_int_t; + #endif union { mp_float_t f; #if MP_ENDIANNESS_LITTLE - struct { mp_float_int_t frc:MP_FLOAT_FRAC_BITS, exp:MP_FLOAT_EXP_BITS, sgn:1; } p; + struct { mp_float_int_t frc : MP_FLOAT_FRAC_BITS, exp : MP_FLOAT_EXP_BITS, sgn : 1; + } p; #else - struct { mp_float_int_t sgn:1, exp:MP_FLOAT_EXP_BITS, frc:MP_FLOAT_FRAC_BITS; } p; + struct { mp_float_int_t sgn : 1, exp : MP_FLOAT_EXP_BITS, frc : MP_FLOAT_FRAC_BITS; + } p; #endif } u = {src}; @@ -825,16 +835,16 @@ typedef uint32_t mp_float_int_t; z->dig[dig_ind++] = (frc << shft) & DIG_MASK; frc >>= DIG_SIZE - shft; } -#if DIG_SIZE < (MP_FLOAT_FRAC_BITS + 1) + #if DIG_SIZE < (MP_FLOAT_FRAC_BITS + 1) while (dig_ind != dig_cnt) { z->dig[dig_ind++] = frc & DIG_MASK; frc >>= DIG_SIZE; } -#else + #else if (dig_ind != dig_cnt) { z->dig[dig_ind] = frc; } -#endif + #endif } } } @@ -857,7 +867,7 @@ size_t mpz_set_from_str(mpz_t *z, const char *str, size_t len, bool neg, unsigne z->len = 0; for (; cur < top; ++cur) { // XXX UTF8 next char - //mp_uint_t v = char_to_numeric(cur#); // XXX UTF8 get char + // mp_uint_t v = char_to_numeric(cur#); // XXX UTF8 get char mp_uint_t v = *cur; if ('0' <= v && v <= '9') { v -= '0'; @@ -948,28 +958,48 @@ int mpz_cmp(const mpz_t *z1, const mpz_t *z2) { mp_int_t mpz_cmp_sml_int(const mpz_t *z, mp_int_t sml_int) { mp_int_t cmp; if (z->neg == 0) { - if (sml_int < 0) return 1; - if (sml_int == 0) { - if (z->len == 0) return 0; + if (sml_int < 0) { return 1; } - if (z->len == 0) return -1; - assert(sml_int < (1 << DIG_SIZE)); - if (z->len != 1) return 1; - cmp = z->dig[0] - sml_int; - } else { - if (sml_int > 0) return -1; if (sml_int == 0) { - if (z->len == 0) return 0; + if (z->len == 0) { + return 0; + } + return 1; + } + if (z->len == 0) { return -1; } - if (z->len == 0) return 1; + assert(sml_int < (1 << DIG_SIZE)); + if (z->len != 1) { + return 1; + } + cmp = z->dig[0] - sml_int; + } else { + if (sml_int > 0) { + return -1; + } + if (sml_int == 0) { + if (z->len == 0) { + return 0; + } + return -1; + } + if (z->len == 0) { + return 1; + } assert(sml_int > -(1 << DIG_SIZE)); - if (z->len != 1) return -1; + if (z->len != 1) { + return -1; + } cmp = -z->dig[0] - sml_int; } - if (cmp < 0) return -1; - if (cmp > 0) return 1; + if (cmp < 0) { + return -1; + } + if (cmp > 0) { + return 1; + } return 0; } #endif @@ -1207,7 +1237,7 @@ void mpz_and_inpl(mpz_t *dest, const mpz_t *lhs, const mpz_t *rhs) { } else { mpz_need_dig(dest, lhs->len + 1); dest->len = mpn_and_neg(dest->dig, lhs->dig, lhs->len, rhs->dig, rhs->len, - lhs->neg == rhs->neg, 0 != lhs->neg, 0 != rhs->neg); + lhs->neg == rhs->neg, 0 != lhs->neg, 0 != rhs->neg); dest->neg = lhs->neg & rhs->neg; } @@ -1215,7 +1245,7 @@ void mpz_and_inpl(mpz_t *dest, const mpz_t *lhs, const mpz_t *rhs) { mpz_need_dig(dest, lhs->len + (lhs->neg || rhs->neg)); dest->len = mpn_and_neg(dest->dig, lhs->dig, lhs->len, rhs->dig, rhs->len, - (lhs->neg == rhs->neg) ? lhs->neg : 0, lhs->neg, rhs->neg); + (lhs->neg == rhs->neg) ? lhs->neg : 0, lhs->neg, rhs->neg); dest->neg = lhs->neg & rhs->neg; #endif @@ -1241,7 +1271,7 @@ void mpz_or_inpl(mpz_t *dest, const mpz_t *lhs, const mpz_t *rhs) { } else { mpz_need_dig(dest, lhs->len + 1); dest->len = mpn_or_neg(dest->dig, lhs->dig, lhs->len, rhs->dig, rhs->len, - 0 != lhs->neg, 0 != rhs->neg); + 0 != lhs->neg, 0 != rhs->neg); dest->neg = 1; } @@ -1249,7 +1279,7 @@ void mpz_or_inpl(mpz_t *dest, const mpz_t *lhs, const mpz_t *rhs) { mpz_need_dig(dest, lhs->len + (lhs->neg || rhs->neg)); dest->len = mpn_or_neg(dest->dig, lhs->dig, lhs->len, rhs->dig, rhs->len, - (lhs->neg || rhs->neg), lhs->neg, rhs->neg); + (lhs->neg || rhs->neg), lhs->neg, rhs->neg); dest->neg = lhs->neg | rhs->neg; #endif @@ -1279,7 +1309,7 @@ void mpz_xor_inpl(mpz_t *dest, const mpz_t *lhs, const mpz_t *rhs) { } else { mpz_need_dig(dest, lhs->len + 1); dest->len = mpn_xor_neg(dest->dig, lhs->dig, lhs->len, rhs->dig, rhs->len, 1, - 0 == lhs->neg, 0 == rhs->neg); + 0 == lhs->neg, 0 == rhs->neg); dest->neg = 1; } @@ -1287,7 +1317,7 @@ void mpz_xor_inpl(mpz_t *dest, const mpz_t *lhs, const mpz_t *rhs) { mpz_need_dig(dest, lhs->len + (lhs->neg || rhs->neg)); dest->len = mpn_xor_neg(dest->dig, lhs->dig, lhs->len, rhs->dig, rhs->len, - (lhs->neg != rhs->neg), 0 == lhs->neg, 0 == rhs->neg); + (lhs->neg != rhs->neg), 0 == lhs->neg, 0 == rhs->neg); dest->neg = lhs->neg ^ rhs->neg; #endif @@ -1376,7 +1406,8 @@ void mpz_pow3_inpl(mpz_t *dest, const mpz_t *lhs, const mpz_t *rhs, const mpz_t mpz_t *x = mpz_clone(lhs); mpz_t *n = mpz_clone(rhs); - mpz_t quo; mpz_init_zero(&quo); + mpz_t quo; + mpz_init_zero(&quo); while (n->len > 0) { if ((n->dig[0] & 1) != 0) { @@ -1419,7 +1450,8 @@ mpz_t *mpz_gcd(const mpz_t *z1, const mpz_t *z2) { mpz_t *a = mpz_clone(z1); mpz_t *b = mpz_clone(z2); - mpz_t c; mpz_init_zero(&c); + mpz_t c; + mpz_init_zero(&c); a->neg = 0; b->neg = 0; @@ -1430,7 +1462,9 @@ mpz_t *mpz_gcd(const mpz_t *z1, const mpz_t *z2) { mpz_deinit(&c); return b; } - mpz_t *t = a; a = b; b = t; + mpz_t *t = a; + a = b; + b = t; } if (!(b->len >= 2 || (b->len == 1 && b->dig[0] > 1))) { // compute b > 0; could be mpz_cmp_small_int(b, 1) > 0 break; @@ -1497,7 +1531,8 @@ void mpz_divmod_inpl(mpz_t *dest_quo, mpz_t *dest_rem, const mpz_t *lhs, const m if (lhs->neg != rhs->neg) { dest_quo->neg = 1; if (!mpz_is_zero(dest_rem)) { - mpz_t mpzone; mpz_init_from_int(&mpzone, -1); + mpz_t mpzone; + mpz_init_from_int(&mpzone, -1); mpz_add_inpl(dest_quo, dest_quo, &mpzone); mpz_add_inpl(dest_rem, dest_rem, rhs); } @@ -1512,7 +1547,8 @@ these functions are unused */ mpz_t *mpz_div(const mpz_t *lhs, const mpz_t *rhs) { mpz_t *quo = mpz_zero(); - mpz_t rem; mpz_init_zero(&rem); + mpz_t rem; + mpz_init_zero(&rem); mpz_divmod_inpl(quo, &rem, lhs, rhs); mpz_deinit(&rem); return quo; @@ -1522,7 +1558,8 @@ mpz_t *mpz_div(const mpz_t *lhs, const mpz_t *rhs) { can have lhs, rhs the same */ mpz_t *mpz_mod(const mpz_t *lhs, const mpz_t *rhs) { - mpz_t quo; mpz_init_zero(&quo); + mpz_t quo; + mpz_init_zero(&quo); mpz_t *rem = mpz_zero(); mpz_divmod_inpl(&quo, rem, lhs, rhs); mpz_deinit(&quo); @@ -1659,8 +1696,9 @@ size_t mpz_as_str_inpl(const mpz_t *i, unsigned int base, const char *prefix, ch char *s = str; if (ilen == 0) { if (prefix) { - while (*prefix) + while (*prefix) { *s++ = *prefix++; + } } *s++ = '0'; *s = '\0'; diff --git a/py/mpz.h b/py/mpz.h index 3c36cac66b..cc1504955f 100644 --- a/py/mpz.h +++ b/py/mpz.h @@ -46,10 +46,10 @@ #ifndef MPZ_DIG_SIZE #if defined(__x86_64__) || defined(_WIN64) - // 64-bit machine, using 32-bit storage for digits +// 64-bit machine, using 32-bit storage for digits #define MPZ_DIG_SIZE (32) #else - // default: 32-bit machine, using 16-bit storage for digits +// default: 32-bit machine, using 16-bit storage for digits #define MPZ_DIG_SIZE (16) #endif #endif @@ -99,7 +99,7 @@ typedef struct _mpz_t { } mpz_t; // convenience macro to declare an mpz with a digit array from the stack, initialised by an integer -#define MPZ_CONST_INT(z, val) mpz_t z; mpz_dig_t z ## _digits[MPZ_NUM_DIG_FOR_INT]; mpz_init_fixed_from_int(&z, z_digits, MPZ_NUM_DIG_FOR_INT, val); +#define MPZ_CONST_INT(z, val) mpz_t z; mpz_dig_t z##_digits[MPZ_NUM_DIG_FOR_INT]; mpz_init_fixed_from_int(&z, z_digits, MPZ_NUM_DIG_FOR_INT, val); void mpz_init_zero(mpz_t *z); void mpz_init_from_int(mpz_t *z, mp_int_t val); @@ -115,8 +115,12 @@ void mpz_set_from_float(mpz_t *z, mp_float_t src); size_t mpz_set_from_str(mpz_t *z, const char *str, size_t len, bool neg, unsigned int base); void mpz_set_from_bytes(mpz_t *z, bool big_endian, size_t len, const byte *buf); -static inline bool mpz_is_zero(const mpz_t *z) { return z->len == 0; } -static inline bool mpz_is_neg(const mpz_t *z) { return z->len != 0 && z->neg != 0; } +static inline bool mpz_is_zero(const mpz_t *z) { + return z->len == 0; +} +static inline bool mpz_is_neg(const mpz_t *z) { + return z->len != 0 && z->neg != 0; +} int mpz_cmp(const mpz_t *lhs, const mpz_t *rhs); void mpz_abs_inpl(mpz_t *dest, const mpz_t *z); @@ -134,7 +138,9 @@ void mpz_or_inpl(mpz_t *dest, const mpz_t *lhs, const mpz_t *rhs); void mpz_xor_inpl(mpz_t *dest, const mpz_t *lhs, const mpz_t *rhs); void mpz_divmod_inpl(mpz_t *dest_quo, mpz_t *dest_rem, const mpz_t *lhs, const mpz_t *rhs); -static inline size_t mpz_max_num_bits(const mpz_t *z) { return z->len * MPZ_DIG_SIZE; } +static inline size_t mpz_max_num_bits(const mpz_t *z) { + return z->len * MPZ_DIG_SIZE; +} mp_int_t mpz_hash(const mpz_t *z); bool mpz_as_int_checked(const mpz_t *z, mp_int_t *value); bool mpz_as_uint_checked(const mpz_t *z, mp_uint_t *value); diff --git a/py/nativeglue.c b/py/nativeglue.c index b7031a5d27..e6918a9aa2 100644 --- a/py/nativeglue.c +++ b/py/nativeglue.c @@ -45,10 +45,12 @@ mp_uint_t mp_convert_obj_to_native(mp_obj_t obj, mp_uint_t type) { DEBUG_printf("mp_convert_obj_to_native(%p, " UINT_FMT ")\n", obj, type); switch (type & 0xf) { - case MP_NATIVE_TYPE_OBJ: return (mp_uint_t)obj; + case MP_NATIVE_TYPE_OBJ: + return (mp_uint_t)obj; case MP_NATIVE_TYPE_BOOL: case MP_NATIVE_TYPE_INT: - case MP_NATIVE_TYPE_UINT: return mp_obj_get_int_truncated(obj); + case MP_NATIVE_TYPE_UINT: + return mp_obj_get_int_truncated(obj); default: { // cast obj to a pointer mp_buffer_info_t bufinfo; if (mp_get_buffer(obj, &bufinfo, MP_BUFFER_RW)) { @@ -69,10 +71,14 @@ mp_uint_t mp_convert_obj_to_native(mp_obj_t obj, mp_uint_t type) { mp_obj_t mp_convert_native_to_obj(mp_uint_t val, mp_uint_t type) { DEBUG_printf("mp_convert_native_to_obj(" UINT_FMT ", " UINT_FMT ")\n", val, type); switch (type & 0xf) { - case MP_NATIVE_TYPE_OBJ: return (mp_obj_t)val; - case MP_NATIVE_TYPE_BOOL: return mp_obj_new_bool(val); - case MP_NATIVE_TYPE_INT: return mp_obj_new_int(val); - case MP_NATIVE_TYPE_UINT: return mp_obj_new_int_from_uint(val); + case MP_NATIVE_TYPE_OBJ: + return (mp_obj_t)val; + case MP_NATIVE_TYPE_BOOL: + return mp_obj_new_bool(val); + case MP_NATIVE_TYPE_INT: + return mp_obj_new_int(val); + case MP_NATIVE_TYPE_UINT: + return mp_obj_new_int_from_uint(val); default: // a pointer // we return just the value of the pointer as an integer return mp_obj_new_int_from_uint(val); @@ -199,10 +205,10 @@ const void *const mp_fun_table[MP_F_NUMBER_OF] = { mp_obj_list_append, mp_obj_new_dict, mp_obj_dict_store, -#if MICROPY_PY_BUILTINS_SET + #if MICROPY_PY_BUILTINS_SET mp_obj_set_store, mp_obj_new_set, -#endif + #endif mp_make_function_from_raw_code, mp_native_call_function_n_kw, mp_call_method_n_kw, @@ -215,9 +221,9 @@ const void *const mp_fun_table[MP_F_NUMBER_OF] = { mp_import_name, mp_import_from, mp_import_all, -#if MICROPY_PY_BUILTINS_SLICE + #if MICROPY_PY_BUILTINS_SLICE mp_obj_new_slice, -#endif + #endif mp_unpack_sequence, mp_unpack_ex, mp_delete_name, diff --git a/py/nlr.c b/py/nlr.c index 03d01577e1..a35e7d229c 100644 --- a/py/nlr.c +++ b/py/nlr.c @@ -30,7 +30,7 @@ // When not using setjmp, nlr_push_tail is called from inline asm so needs special care #if MICROPY_NLR_X86 && MICROPY_NLR_OS_WINDOWS // On these 32-bit platforms make sure nlr_push_tail doesn't have a leading underscore -unsigned int nlr_push_tail(nlr_buf_t *nlr) asm("nlr_push_tail"); +unsigned int nlr_push_tail(nlr_buf_t *nlr) asm ("nlr_push_tail"); #else // LTO can't see inside inline asm functions so explicitly mark nlr_push_tail as used __attribute__((used)) unsigned int nlr_push_tail(nlr_buf_t *nlr); diff --git a/py/nlr.h b/py/nlr.h index 90595a12d3..2d82049656 100644 --- a/py/nlr.h +++ b/py/nlr.h @@ -60,7 +60,7 @@ #define MICROPY_NLR_NUM_REGS (10) #else #define MICROPY_NLR_SETJMP (1) - //#warning "No native NLR support for this arch, using setjmp implementation" +// #warning "No native NLR support for this arch, using setjmp implementation" #endif #endif diff --git a/py/nlrthumb.c b/py/nlrthumb.c index c283023551..074b82bfe2 100644 --- a/py/nlrthumb.c +++ b/py/nlrthumb.c @@ -39,42 +39,42 @@ __attribute__((naked)) unsigned int nlr_push(nlr_buf_t *nlr) { __asm volatile ( - "str r4, [r0, #12] \n" // store r4 into nlr_buf - "str r5, [r0, #16] \n" // store r5 into nlr_buf - "str r6, [r0, #20] \n" // store r6 into nlr_buf - "str r7, [r0, #24] \n" // store r7 into nlr_buf + "str r4, [r0, #12] \n" // store r4 into nlr_buf + "str r5, [r0, #16] \n" // store r5 into nlr_buf + "str r6, [r0, #20] \n" // store r6 into nlr_buf + "str r7, [r0, #24] \n" // store r7 into nlr_buf -#if defined(__ARM_ARCH_6M__) - "mov r1, r8 \n" - "str r1, [r0, #28] \n" // store r8 into nlr_buf - "mov r1, r9 \n" - "str r1, [r0, #32] \n" // store r9 into nlr_buf - "mov r1, r10 \n" - "str r1, [r0, #36] \n" // store r10 into nlr_buf - "mov r1, r11 \n" - "str r1, [r0, #40] \n" // store r11 into nlr_buf - "mov r1, r13 \n" - "str r1, [r0, #44] \n" // store r13=sp into nlr_buf - "mov r1, lr \n" - "str r1, [r0, #8] \n" // store lr into nlr_buf -#else - "str r8, [r0, #28] \n" // store r8 into nlr_buf - "str r9, [r0, #32] \n" // store r9 into nlr_buf - "str r10, [r0, #36] \n" // store r10 into nlr_buf - "str r11, [r0, #40] \n" // store r11 into nlr_buf - "str r13, [r0, #44] \n" // store r13=sp into nlr_buf - "str lr, [r0, #8] \n" // store lr into nlr_buf -#endif + #if defined(__ARM_ARCH_6M__) + "mov r1, r8 \n" + "str r1, [r0, #28] \n" // store r8 into nlr_buf + "mov r1, r9 \n" + "str r1, [r0, #32] \n" // store r9 into nlr_buf + "mov r1, r10 \n" + "str r1, [r0, #36] \n" // store r10 into nlr_buf + "mov r1, r11 \n" + "str r1, [r0, #40] \n" // store r11 into nlr_buf + "mov r1, r13 \n" + "str r1, [r0, #44] \n" // store r13=sp into nlr_buf + "mov r1, lr \n" + "str r1, [r0, #8] \n" // store lr into nlr_buf + #else + "str r8, [r0, #28] \n" // store r8 into nlr_buf + "str r9, [r0, #32] \n" // store r9 into nlr_buf + "str r10, [r0, #36] \n" // store r10 into nlr_buf + "str r11, [r0, #40] \n" // store r11 into nlr_buf + "str r13, [r0, #44] \n" // store r13=sp into nlr_buf + "str lr, [r0, #8] \n" // store lr into nlr_buf + #endif -#if defined(__ARM_ARCH_6M__) - "ldr r1, nlr_push_tail_var \n" - "bx r1 \n" // do the rest in C - ".align 2 \n" - "nlr_push_tail_var: .word nlr_push_tail \n" -#else - "b nlr_push_tail \n" // do the rest in C -#endif - ); + #if defined(__ARM_ARCH_6M__) + "ldr r1, nlr_push_tail_var \n" + "bx r1 \n" // do the rest in C + ".align 2 \n" + "nlr_push_tail_var: .word nlr_push_tail \n" + #else + "b nlr_push_tail \n" // do the rest in C + #endif + ); #if !defined(__clang__) && defined(__GNUC__) && (__GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 8)) // Older versions of gcc give an error when naked functions don't return a value @@ -87,44 +87,45 @@ NORETURN void nlr_jump(void *val) { MP_NLR_JUMP_HEAD(val, top) __asm volatile ( - "mov r0, %0 \n" // r0 points to nlr_buf - "ldr r4, [r0, #12] \n" // load r4 from nlr_buf - "ldr r5, [r0, #16] \n" // load r5 from nlr_buf - "ldr r6, [r0, #20] \n" // load r6 from nlr_buf - "ldr r7, [r0, #24] \n" // load r7 from nlr_buf + "mov r0, %0 \n" // r0 points to nlr_buf + "ldr r4, [r0, #12] \n" // load r4 from nlr_buf + "ldr r5, [r0, #16] \n" // load r5 from nlr_buf + "ldr r6, [r0, #20] \n" // load r6 from nlr_buf + "ldr r7, [r0, #24] \n" // load r7 from nlr_buf -#if defined(__ARM_ARCH_6M__) - "ldr r1, [r0, #28] \n" // load r8 from nlr_buf - "mov r8, r1 \n" - "ldr r1, [r0, #32] \n" // load r9 from nlr_buf - "mov r9, r1 \n" - "ldr r1, [r0, #36] \n" // load r10 from nlr_buf - "mov r10, r1 \n" - "ldr r1, [r0, #40] \n" // load r11 from nlr_buf - "mov r11, r1 \n" - "ldr r1, [r0, #44] \n" // load r13=sp from nlr_buf - "mov r13, r1 \n" - "ldr r1, [r0, #8] \n" // load lr from nlr_buf - "mov lr, r1 \n" -#else - "ldr r8, [r0, #28] \n" // load r8 from nlr_buf - "ldr r9, [r0, #32] \n" // load r9 from nlr_buf - "ldr r10, [r0, #36] \n" // load r10 from nlr_buf - "ldr r11, [r0, #40] \n" // load r11 from nlr_buf - "ldr r13, [r0, #44] \n" // load r13=sp from nlr_buf - "ldr lr, [r0, #8] \n" // load lr from nlr_buf -#endif - "movs r0, #1 \n" // return 1, non-local return - "bx lr \n" // return - : // output operands - : "r"(top) // input operands - : // clobbered registers - ); + #if defined(__ARM_ARCH_6M__) + "ldr r1, [r0, #28] \n" // load r8 from nlr_buf + "mov r8, r1 \n" + "ldr r1, [r0, #32] \n" // load r9 from nlr_buf + "mov r9, r1 \n" + "ldr r1, [r0, #36] \n" // load r10 from nlr_buf + "mov r10, r1 \n" + "ldr r1, [r0, #40] \n" // load r11 from nlr_buf + "mov r11, r1 \n" + "ldr r1, [r0, #44] \n" // load r13=sp from nlr_buf + "mov r13, r1 \n" + "ldr r1, [r0, #8] \n" // load lr from nlr_buf + "mov lr, r1 \n" + #else + "ldr r8, [r0, #28] \n" // load r8 from nlr_buf + "ldr r9, [r0, #32] \n" // load r9 from nlr_buf + "ldr r10, [r0, #36] \n" // load r10 from nlr_buf + "ldr r11, [r0, #40] \n" // load r11 from nlr_buf + "ldr r13, [r0, #44] \n" // load r13=sp from nlr_buf + "ldr lr, [r0, #8] \n" // load lr from nlr_buf + #endif + "movs r0, #1 \n" // return 1, non-local return + "bx lr \n" // return + : // output operands + : "r" (top) // input operands + : // clobbered registers + ); #if defined(__GNUC__) __builtin_unreachable(); #else - for (;;); // needed to silence compiler warning + for (;;) {; // needed to silence compiler warning + } #endif } diff --git a/py/nlrx64.c b/py/nlrx64.c index a3a1cf341b..1cbb04e425 100644 --- a/py/nlrx64.c +++ b/py/nlrx64.c @@ -41,41 +41,41 @@ unsigned int nlr_push(nlr_buf_t *nlr) { #if MICROPY_NLR_OS_WINDOWS __asm volatile ( - "movq (%rsp), %rax \n" // load return %rip - "movq %rax, 16(%rcx) \n" // store %rip into nlr_buf - "movq %rbp, 24(%rcx) \n" // store %rbp into nlr_buf - "movq %rsp, 32(%rcx) \n" // store %rsp into nlr_buf - "movq %rbx, 40(%rcx) \n" // store %rbx into nlr_buf - "movq %r12, 48(%rcx) \n" // store %r12 into nlr_buf - "movq %r13, 56(%rcx) \n" // store %r13 into nlr_buf - "movq %r14, 64(%rcx) \n" // store %r14 into nlr_buf - "movq %r15, 72(%rcx) \n" // store %r15 into nlr_buf - "movq %rdi, 80(%rcx) \n" // store %rdr into nlr_buf - "movq %rsi, 88(%rcx) \n" // store %rsi into nlr_buf - "jmp nlr_push_tail \n" // do the rest in C - ); + "movq (%rsp), %rax \n" // load return %rip + "movq %rax, 16(%rcx) \n" // store %rip into nlr_buf + "movq %rbp, 24(%rcx) \n" // store %rbp into nlr_buf + "movq %rsp, 32(%rcx) \n" // store %rsp into nlr_buf + "movq %rbx, 40(%rcx) \n" // store %rbx into nlr_buf + "movq %r12, 48(%rcx) \n" // store %r12 into nlr_buf + "movq %r13, 56(%rcx) \n" // store %r13 into nlr_buf + "movq %r14, 64(%rcx) \n" // store %r14 into nlr_buf + "movq %r15, 72(%rcx) \n" // store %r15 into nlr_buf + "movq %rdi, 80(%rcx) \n" // store %rdr into nlr_buf + "movq %rsi, 88(%rcx) \n" // store %rsi into nlr_buf + "jmp nlr_push_tail \n" // do the rest in C + ); #else __asm volatile ( - #if defined(__APPLE__) || defined(__MACH__) - "pop %rbp \n" // undo function's prelude - #endif - "movq (%rsp), %rax \n" // load return %rip - "movq %rax, 16(%rdi) \n" // store %rip into nlr_buf - "movq %rbp, 24(%rdi) \n" // store %rbp into nlr_buf - "movq %rsp, 32(%rdi) \n" // store %rsp into nlr_buf - "movq %rbx, 40(%rdi) \n" // store %rbx into nlr_buf - "movq %r12, 48(%rdi) \n" // store %r12 into nlr_buf - "movq %r13, 56(%rdi) \n" // store %r13 into nlr_buf - "movq %r14, 64(%rdi) \n" // store %r14 into nlr_buf - "movq %r15, 72(%rdi) \n" // store %r15 into nlr_buf - #if defined(__APPLE__) || defined(__MACH__) - "jmp _nlr_push_tail \n" // do the rest in C - #else - "jmp nlr_push_tail \n" // do the rest in C - #endif - ); + #if defined(__APPLE__) || defined(__MACH__) + "pop %rbp \n" // undo function's prelude + #endif + "movq (%rsp), %rax \n" // load return %rip + "movq %rax, 16(%rdi) \n" // store %rip into nlr_buf + "movq %rbp, 24(%rdi) \n" // store %rbp into nlr_buf + "movq %rsp, 32(%rdi) \n" // store %rsp into nlr_buf + "movq %rbx, 40(%rdi) \n" // store %rbx into nlr_buf + "movq %r12, 48(%rdi) \n" // store %r12 into nlr_buf + "movq %r13, 56(%rdi) \n" // store %r13 into nlr_buf + "movq %r14, 64(%rdi) \n" // store %r14 into nlr_buf + "movq %r15, 72(%rdi) \n" // store %r15 into nlr_buf + #if defined(__APPLE__) || defined(__MACH__) + "jmp _nlr_push_tail \n" // do the rest in C + #else + "jmp nlr_push_tail \n" // do the rest in C + #endif + ); #endif @@ -86,29 +86,30 @@ NORETURN void nlr_jump(void *val) { MP_NLR_JUMP_HEAD(val, top) __asm volatile ( - "movq %0, %%rcx \n" // %rcx points to nlr_buf - #if MICROPY_NLR_OS_WINDOWS - "movq 88(%%rcx), %%rsi \n" // load saved %rsi - "movq 80(%%rcx), %%rdi \n" // load saved %rdr - #endif - "movq 72(%%rcx), %%r15 \n" // load saved %r15 - "movq 64(%%rcx), %%r14 \n" // load saved %r14 - "movq 56(%%rcx), %%r13 \n" // load saved %r13 - "movq 48(%%rcx), %%r12 \n" // load saved %r12 - "movq 40(%%rcx), %%rbx \n" // load saved %rbx - "movq 32(%%rcx), %%rsp \n" // load saved %rsp - "movq 24(%%rcx), %%rbp \n" // load saved %rbp - "movq 16(%%rcx), %%rax \n" // load saved %rip - "movq %%rax, (%%rsp) \n" // store saved %rip to stack - "xorq %%rax, %%rax \n" // clear return register - "inc %%al \n" // increase to make 1, non-local return - "ret \n" // return - : // output operands - : "r"(top) // input operands - : // clobbered registers - ); + "movq %0, %%rcx \n" // %rcx points to nlr_buf + #if MICROPY_NLR_OS_WINDOWS + "movq 88(%%rcx), %%rsi \n" // load saved %rsi + "movq 80(%%rcx), %%rdi \n" // load saved %rdr + #endif + "movq 72(%%rcx), %%r15 \n" // load saved %r15 + "movq 64(%%rcx), %%r14 \n" // load saved %r14 + "movq 56(%%rcx), %%r13 \n" // load saved %r13 + "movq 48(%%rcx), %%r12 \n" // load saved %r12 + "movq 40(%%rcx), %%rbx \n" // load saved %rbx + "movq 32(%%rcx), %%rsp \n" // load saved %rsp + "movq 24(%%rcx), %%rbp \n" // load saved %rbp + "movq 16(%%rcx), %%rax \n" // load saved %rip + "movq %%rax, (%%rsp) \n" // store saved %rip to stack + "xorq %%rax, %%rax \n" // clear return register + "inc %%al \n" // increase to make 1, non-local return + "ret \n" // return + : // output operands + : "r" (top) // input operands + : // clobbered registers + ); - for (;;); // needed to silence compiler warning + for (;;) {; // needed to silence compiler warning + } } #endif // MICROPY_NLR_X64 diff --git a/py/nlrx86.c b/py/nlrx86.c index 59b97d8ee6..94c8210eeb 100644 --- a/py/nlrx86.c +++ b/py/nlrx86.c @@ -34,7 +34,7 @@ // ebx, esi, edi, ebp, esp, eip #if MICROPY_NLR_OS_WINDOWS -unsigned int nlr_push_tail(nlr_buf_t *nlr) asm("nlr_push_tail"); +unsigned int nlr_push_tail(nlr_buf_t *nlr) asm ("nlr_push_tail"); #else __attribute__((used)) unsigned int nlr_push_tail(nlr_buf_t *nlr); #endif @@ -61,19 +61,19 @@ unsigned int nlr_push(nlr_buf_t *nlr) { #endif __asm volatile ( - #if UNDO_PRELUDE - "pop %ebp \n" // undo function's prelude - #endif - "mov 4(%esp), %edx \n" // load nlr_buf - "mov (%esp), %eax \n" // load return %eip - "mov %eax, 8(%edx) \n" // store %eip into nlr_buf - "mov %ebp, 12(%edx) \n" // store %ebp into nlr_buf - "mov %esp, 16(%edx) \n" // store %esp into nlr_buf - "mov %ebx, 20(%edx) \n" // store %ebx into nlr_buf - "mov %edi, 24(%edx) \n" // store %edi into nlr_buf - "mov %esi, 28(%edx) \n" // store %esi into nlr_buf - "jmp nlr_push_tail \n" // do the rest in C - ); + #if UNDO_PRELUDE + "pop %ebp \n" // undo function's prelude + #endif + "mov 4(%esp), %edx \n" // load nlr_buf + "mov (%esp), %eax \n" // load return %eip + "mov %eax, 8(%edx) \n" // store %eip into nlr_buf + "mov %ebp, 12(%edx) \n" // store %ebp into nlr_buf + "mov %esp, 16(%edx) \n" // store %esp into nlr_buf + "mov %ebx, 20(%edx) \n" // store %ebx into nlr_buf + "mov %edi, 24(%edx) \n" // store %edi into nlr_buf + "mov %esi, 28(%edx) \n" // store %esi into nlr_buf + "jmp nlr_push_tail \n" // do the rest in C + ); #if !USE_NAKED return 0; // needed to silence compiler warning @@ -84,23 +84,24 @@ NORETURN void nlr_jump(void *val) { MP_NLR_JUMP_HEAD(val, top) __asm volatile ( - "mov %0, %%edx \n" // %edx points to nlr_buf - "mov 28(%%edx), %%esi \n" // load saved %esi - "mov 24(%%edx), %%edi \n" // load saved %edi - "mov 20(%%edx), %%ebx \n" // load saved %ebx - "mov 16(%%edx), %%esp \n" // load saved %esp - "mov 12(%%edx), %%ebp \n" // load saved %ebp - "mov 8(%%edx), %%eax \n" // load saved %eip - "mov %%eax, (%%esp) \n" // store saved %eip to stack - "xor %%eax, %%eax \n" // clear return register - "inc %%al \n" // increase to make 1, non-local return - "ret \n" // return - : // output operands - : "r"(top) // input operands - : // clobbered registers - ); + "mov %0, %%edx \n" // %edx points to nlr_buf + "mov 28(%%edx), %%esi \n" // load saved %esi + "mov 24(%%edx), %%edi \n" // load saved %edi + "mov 20(%%edx), %%ebx \n" // load saved %ebx + "mov 16(%%edx), %%esp \n" // load saved %esp + "mov 12(%%edx), %%ebp \n" // load saved %ebp + "mov 8(%%edx), %%eax \n" // load saved %eip + "mov %%eax, (%%esp) \n" // store saved %eip to stack + "xor %%eax, %%eax \n" // clear return register + "inc %%al \n" // increase to make 1, non-local return + "ret \n" // return + : // output operands + : "r" (top) // input operands + : // clobbered registers + ); - for (;;); // needed to silence compiler warning + for (;;) {; // needed to silence compiler warning + } } #endif // MICROPY_NLR_X86 diff --git a/py/nlrxtensa.c b/py/nlrxtensa.c index cd3dee364c..4abaad7208 100644 --- a/py/nlrxtensa.c +++ b/py/nlrxtensa.c @@ -39,18 +39,18 @@ unsigned int nlr_push(nlr_buf_t *nlr) { __asm volatile ( - "s32i.n a0, a2, 8 \n" // save regs... - "s32i.n a1, a2, 12 \n" - "s32i.n a8, a2, 16 \n" - "s32i.n a9, a2, 20 \n" - "s32i.n a10, a2, 24 \n" - "s32i.n a11, a2, 28 \n" - "s32i.n a12, a2, 32 \n" - "s32i.n a13, a2, 36 \n" - "s32i.n a14, a2, 40 \n" - "s32i.n a15, a2, 44 \n" - "j nlr_push_tail \n" // do the rest in C - ); + "s32i.n a0, a2, 8 \n" // save regs... + "s32i.n a1, a2, 12 \n" + "s32i.n a8, a2, 16 \n" + "s32i.n a9, a2, 20 \n" + "s32i.n a10, a2, 24 \n" + "s32i.n a11, a2, 28 \n" + "s32i.n a12, a2, 32 \n" + "s32i.n a13, a2, 36 \n" + "s32i.n a14, a2, 40 \n" + "s32i.n a15, a2, 44 \n" + "j nlr_push_tail \n" // do the rest in C + ); return 0; // needed to silence compiler warning } @@ -59,25 +59,26 @@ NORETURN void nlr_jump(void *val) { MP_NLR_JUMP_HEAD(val, top) __asm volatile ( - "mov.n a2, %0 \n" // a2 points to nlr_buf - "l32i.n a0, a2, 8 \n" // restore regs... - "l32i.n a1, a2, 12 \n" - "l32i.n a8, a2, 16 \n" - "l32i.n a9, a2, 20 \n" - "l32i.n a10, a2, 24 \n" - "l32i.n a11, a2, 28 \n" - "l32i.n a12, a2, 32 \n" - "l32i.n a13, a2, 36 \n" - "l32i.n a14, a2, 40 \n" - "l32i.n a15, a2, 44 \n" - "movi.n a2, 1 \n" // return 1, non-local return - "ret.n \n" // return - : // output operands - : "r"(top) // input operands - : // clobbered registers - ); + "mov.n a2, %0 \n" // a2 points to nlr_buf + "l32i.n a0, a2, 8 \n" // restore regs... + "l32i.n a1, a2, 12 \n" + "l32i.n a8, a2, 16 \n" + "l32i.n a9, a2, 20 \n" + "l32i.n a10, a2, 24 \n" + "l32i.n a11, a2, 28 \n" + "l32i.n a12, a2, 32 \n" + "l32i.n a13, a2, 36 \n" + "l32i.n a14, a2, 40 \n" + "l32i.n a15, a2, 44 \n" + "movi.n a2, 1 \n" // return 1, non-local return + "ret.n \n" // return + : // output operands + : "r" (top) // input operands + : // clobbered registers + ); - for (;;); // needed to silence compiler warning + for (;;) {; // needed to silence compiler warning + } } #endif // MICROPY_NLR_XTENSA diff --git a/py/obj.c b/py/obj.c index 47b7d15ae0..054124b16c 100644 --- a/py/obj.c +++ b/py/obj.c @@ -39,16 +39,16 @@ mp_obj_type_t *mp_obj_get_type(mp_const_obj_t o_in) { if (MP_OBJ_IS_SMALL_INT(o_in)) { - return (mp_obj_type_t*)&mp_type_int; + return (mp_obj_type_t *)&mp_type_int; } else if (MP_OBJ_IS_QSTR(o_in)) { - return (mp_obj_type_t*)&mp_type_str; + return (mp_obj_type_t *)&mp_type_str; #if MICROPY_PY_BUILTINS_FLOAT } else if (mp_obj_is_float(o_in)) { - return (mp_obj_type_t*)&mp_type_float; + return (mp_obj_type_t *)&mp_type_float; #endif } else { const mp_obj_base_t *o = MP_OBJ_TO_PTR(o_in); - return (mp_obj_type_t*)o->type; + return (mp_obj_type_t *)o->type; } } @@ -59,15 +59,15 @@ const char *mp_obj_get_type_str(mp_const_obj_t o_in) { void mp_obj_print_helper(const mp_print_t *print, mp_obj_t o_in, mp_print_kind_t kind) { // There can be data structures nested too deep, or just recursive MP_STACK_CHECK(); -#ifndef NDEBUG + #ifndef NDEBUG if (o_in == MP_OBJ_NULL) { mp_print_str(print, "(nil)"); return; } -#endif + #endif mp_obj_type_t *type = mp_obj_get_type(o_in); if (type->print != NULL) { - type->print((mp_print_t*)print, o_in, kind); + type->print((mp_print_t *)print, o_in, kind); } else { mp_printf(print, "<%q>", type->name); } @@ -86,11 +86,11 @@ void mp_obj_print_exception(const mp_print_t *print, mp_obj_t exc) { assert(n % 3 == 0); mp_print_str(print, "Traceback (most recent call last):\n"); for (int i = n - 3; i >= 0; i -= 3) { -#if MICROPY_ENABLE_SOURCE_LINE + #if MICROPY_ENABLE_SOURCE_LINE mp_printf(print, " File \"%q\", line %d", values[i], (int)values[i + 1]); -#else + #else mp_printf(print, " File \"%q\"", values[i]); -#endif + #endif // the block name can be NULL if it's unknown qstr block = values[i + 2]; if (block == MP_QSTR_NULL) { @@ -182,7 +182,9 @@ bool mp_obj_equal(mp_obj_t o1, mp_obj_t o2) { // both SMALL_INT, and not equal if we get here return false; } else { - mp_obj_t temp = o2; o2 = o1; o1 = temp; + mp_obj_t temp = o2; + o2 = o1; + o1 = temp; // o2 is now the SMALL_INT, o1 is not // fall through to generic op } @@ -443,10 +445,10 @@ mp_obj_t mp_obj_len(mp_obj_t o_in) { // may return MP_OBJ_NULL mp_obj_t mp_obj_len_maybe(mp_obj_t o_in) { if ( -#if !MICROPY_PY_BUILTINS_STR_UNICODE + #if !MICROPY_PY_BUILTINS_STR_UNICODE // It's simple - unicode is slow, non-unicode is fast MP_OBJ_IS_STR(o_in) || -#endif + #endif MP_OBJ_IS_TYPE(o_in, &mp_type_bytes)) { GET_STR_LEN(o_in, l); return MP_OBJ_NEW_SMALL_INT(l); @@ -525,7 +527,9 @@ void mp_get_buffer_raise(mp_obj_t obj, mp_buffer_info_t *bufinfo, mp_uint_t flag mp_obj_t mp_generic_unary_op(mp_unary_op_t op, mp_obj_t o_in) { switch (op) { - case MP_UNARY_OP_HASH: return MP_OBJ_NEW_SMALL_INT((mp_uint_t)o_in); - default: return MP_OBJ_NULL; // op not supported + case MP_UNARY_OP_HASH: + return MP_OBJ_NEW_SMALL_INT((mp_uint_t)o_in); + default: + return MP_OBJ_NULL; // op not supported } } diff --git a/py/obj.h b/py/obj.h index 5eed90b0ab..0f758f1334 100644 --- a/py/obj.h +++ b/py/obj.h @@ -66,13 +66,13 @@ typedef struct _mp_obj_base_t mp_obj_base_t; // as many as we can to MP_OBJ_NULL because it's cheaper to load/compare 0. #ifdef NDEBUG -#define MP_OBJ_NULL (MP_OBJ_FROM_PTR((void*)0)) -#define MP_OBJ_STOP_ITERATION (MP_OBJ_FROM_PTR((void*)0)) -#define MP_OBJ_SENTINEL (MP_OBJ_FROM_PTR((void*)4)) +#define MP_OBJ_NULL (MP_OBJ_FROM_PTR((void *)0)) +#define MP_OBJ_STOP_ITERATION (MP_OBJ_FROM_PTR((void *)0)) +#define MP_OBJ_SENTINEL (MP_OBJ_FROM_PTR((void *)4)) #else -#define MP_OBJ_NULL (MP_OBJ_FROM_PTR((void*)0)) -#define MP_OBJ_STOP_ITERATION (MP_OBJ_FROM_PTR((void*)4)) -#define MP_OBJ_SENTINEL (MP_OBJ_FROM_PTR((void*)8)) +#define MP_OBJ_NULL (MP_OBJ_FROM_PTR((void *)0)) +#define MP_OBJ_STOP_ITERATION (MP_OBJ_FROM_PTR((void *)4)) +#define MP_OBJ_SENTINEL (MP_OBJ_FROM_PTR((void *)8)) #endif // These macros/inline functions operate on objects and depend on the @@ -81,13 +81,15 @@ typedef struct _mp_obj_base_t mp_obj_base_t; #if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_A -static inline bool MP_OBJ_IS_SMALL_INT(mp_const_obj_t o) - { return ((((mp_int_t)(o)) & 1) != 0); } +static inline bool MP_OBJ_IS_SMALL_INT(mp_const_obj_t o) { + return (((mp_int_t)(o)) & 1) != 0; +} #define MP_OBJ_SMALL_INT_VALUE(o) (((mp_int_t)(o)) >> 1) #define MP_OBJ_NEW_SMALL_INT(small_int) ((mp_obj_t)((((mp_uint_t)(small_int)) << 1) | 1)) -static inline bool MP_OBJ_IS_QSTR(mp_const_obj_t o) - { return ((((mp_int_t)(o)) & 3) == 2); } +static inline bool MP_OBJ_IS_QSTR(mp_const_obj_t o) { + return (((mp_int_t)(o)) & 3) == 2; +} #define MP_OBJ_QSTR_VALUE(o) (((mp_uint_t)(o)) >> 2) #define MP_OBJ_NEW_QSTR(qst) ((mp_obj_t)((((mp_uint_t)(qst)) << 2) | 2)) @@ -102,18 +104,21 @@ mp_float_t mp_obj_float_get(mp_obj_t self_in); mp_obj_t mp_obj_new_float(mp_float_t value); #endif -static inline bool MP_OBJ_IS_OBJ(mp_const_obj_t o) - { return ((((mp_int_t)(o)) & 3) == 0); } +static inline bool MP_OBJ_IS_OBJ(mp_const_obj_t o) { + return (((mp_int_t)(o)) & 3) == 0; +} #elif MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_B -static inline bool MP_OBJ_IS_SMALL_INT(mp_const_obj_t o) - { return ((((mp_int_t)(o)) & 3) == 1); } +static inline bool MP_OBJ_IS_SMALL_INT(mp_const_obj_t o) { + return (((mp_int_t)(o)) & 3) == 1; +} #define MP_OBJ_SMALL_INT_VALUE(o) (((mp_int_t)(o)) >> 2) #define MP_OBJ_NEW_SMALL_INT(small_int) ((mp_obj_t)((((mp_uint_t)(small_int)) << 2) | 1)) -static inline bool MP_OBJ_IS_QSTR(mp_const_obj_t o) - { return ((((mp_int_t)(o)) & 3) == 3); } +static inline bool MP_OBJ_IS_QSTR(mp_const_obj_t o) { + return (((mp_int_t)(o)) & 3) == 3; +} #define MP_OBJ_QSTR_VALUE(o) (((mp_uint_t)(o)) >> 2) #define MP_OBJ_NEW_QSTR(qst) ((mp_obj_t)((((mp_uint_t)(qst)) << 2) | 3)) @@ -128,13 +133,15 @@ mp_float_t mp_obj_float_get(mp_obj_t self_in); mp_obj_t mp_obj_new_float(mp_float_t value); #endif -static inline bool MP_OBJ_IS_OBJ(mp_const_obj_t o) - { return ((((mp_int_t)(o)) & 1) == 0); } +static inline bool MP_OBJ_IS_OBJ(mp_const_obj_t o) { + return (((mp_int_t)(o)) & 1) == 0; +} #elif MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_C -static inline bool MP_OBJ_IS_SMALL_INT(mp_const_obj_t o) - { return ((((mp_int_t)(o)) & 1) != 0); } +static inline bool MP_OBJ_IS_SMALL_INT(mp_const_obj_t o) { + return (((mp_int_t)(o)) & 1) != 0; +} #define MP_OBJ_SMALL_INT_VALUE(o) (((mp_int_t)(o)) >> 1) #define MP_OBJ_NEW_SMALL_INT(small_int) ((mp_obj_t)((((mp_uint_t)(small_int)) << 1) | 1)) @@ -142,8 +149,9 @@ static inline bool MP_OBJ_IS_SMALL_INT(mp_const_obj_t o) #define mp_const_float_e MP_ROM_PTR((mp_obj_t)(((0x402df854 & ~3) | 2) + 0x80800000)) #define mp_const_float_pi MP_ROM_PTR((mp_obj_t)(((0x40490fdb & ~3) | 2) + 0x80800000)) -static inline bool mp_obj_is_float(mp_const_obj_t o) - { return (((mp_uint_t)(o)) & 3) == 2 && (((mp_uint_t)(o)) & 0xff800007) != 0x00000006; } +static inline bool mp_obj_is_float(mp_const_obj_t o) { + return (((mp_uint_t)(o)) & 3) == 2 && (((mp_uint_t)(o)) & 0xff800007) != 0x00000006; +} static inline mp_float_t mp_obj_float_get(mp_const_obj_t o) { union { mp_float_t f; @@ -160,23 +168,27 @@ static inline mp_obj_t mp_obj_new_float(mp_float_t f) { } #endif -static inline bool MP_OBJ_IS_QSTR(mp_const_obj_t o) - { return (((mp_uint_t)(o)) & 0xff800007) == 0x00000006; } +static inline bool MP_OBJ_IS_QSTR(mp_const_obj_t o) { + return (((mp_uint_t)(o)) & 0xff800007) == 0x00000006; +} #define MP_OBJ_QSTR_VALUE(o) (((mp_uint_t)(o)) >> 3) #define MP_OBJ_NEW_QSTR(qst) ((mp_obj_t)((((mp_uint_t)(qst)) << 3) | 0x00000006)) -static inline bool MP_OBJ_IS_OBJ(mp_const_obj_t o) - { return ((((mp_int_t)(o)) & 3) == 0); } +static inline bool MP_OBJ_IS_OBJ(mp_const_obj_t o) { + return (((mp_int_t)(o)) & 3) == 0; +} #elif MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_D -static inline bool MP_OBJ_IS_SMALL_INT(mp_const_obj_t o) - { return ((((uint64_t)(o)) & 0xffff000000000000) == 0x0001000000000000); } +static inline bool MP_OBJ_IS_SMALL_INT(mp_const_obj_t o) { + return (((uint64_t)(o)) & 0xffff000000000000) == 0x0001000000000000; +} #define MP_OBJ_SMALL_INT_VALUE(o) (((mp_int_t)((o) << 16)) >> 17) #define MP_OBJ_NEW_SMALL_INT(small_int) (((((uint64_t)(small_int)) & 0x7fffffffffff) << 1) | 0x0001000000000001) -static inline bool MP_OBJ_IS_QSTR(mp_const_obj_t o) - { return ((((uint64_t)(o)) & 0xffff000000000000) == 0x0002000000000000); } +static inline bool MP_OBJ_IS_QSTR(mp_const_obj_t o) { + return (((uint64_t)(o)) & 0xffff000000000000) == 0x0002000000000000; +} #define MP_OBJ_QSTR_VALUE(o) ((((uint32_t)(o)) >> 1) & 0xffffffff) #define MP_OBJ_NEW_QSTR(qst) ((mp_obj_t)((((mp_uint_t)(qst)) << 1) | 0x0002000000000001)) @@ -208,13 +220,17 @@ static inline mp_obj_t mp_obj_new_float(mp_float_t f) { } #endif -static inline bool MP_OBJ_IS_OBJ(mp_const_obj_t o) - { return ((((uint64_t)(o)) & 0xffff000000000000) == 0x0000000000000000); } -#define MP_OBJ_TO_PTR(o) ((void*)(uintptr_t)(o)) +static inline bool MP_OBJ_IS_OBJ(mp_const_obj_t o) { + return (((uint64_t)(o)) & 0xffff000000000000) == 0x0000000000000000; +} +#define MP_OBJ_TO_PTR(o) ((void *)(uintptr_t)(o)) #define MP_OBJ_FROM_PTR(p) ((mp_obj_t)((uintptr_t)(p))) // rom object storage needs special handling to widen 32-bit pointer to 64-bits -typedef union _mp_rom_obj_t { uint64_t u64; struct { const void *lo, *hi; } u32; } mp_rom_obj_t; +typedef union _mp_rom_obj_t { uint64_t u64; + struct { const void *lo, *hi; + } u32; +} mp_rom_obj_t; #define MP_ROM_INT(i) {MP_OBJ_NEW_SMALL_INT(i)} #define MP_ROM_QSTR(q) {MP_OBJ_NEW_QSTR(q)} #if MP_ENDIANNESS_LITTLE @@ -232,7 +248,7 @@ typedef union _mp_rom_obj_t { uint64_t u64; struct { const void *lo, *hi; } u32; // Cast mp_obj_t to object pointer #ifndef MP_OBJ_TO_PTR -#define MP_OBJ_TO_PTR(o) ((void*)o) +#define MP_OBJ_TO_PTR(o) ((void *)o) #endif // Cast object pointer to mp_obj_t @@ -260,11 +276,11 @@ typedef struct _mp_rom_obj_t { mp_const_obj_t o; } mp_rom_obj_t; // Note: these are kept as macros because inline functions sometimes use much // more code space than the equivalent macros, depending on the compiler. -#define MP_OBJ_IS_TYPE(o, t) (MP_OBJ_IS_OBJ(o) && (((mp_obj_base_t*)MP_OBJ_TO_PTR(o))->type == (t))) // this does not work for checking int, str or fun; use below macros for that +#define MP_OBJ_IS_TYPE(o, t) (MP_OBJ_IS_OBJ(o) && (((mp_obj_base_t *)MP_OBJ_TO_PTR(o))->type == (t))) // this does not work for checking int, str or fun; use below macros for that #define MP_OBJ_IS_INT(o) (MP_OBJ_IS_SMALL_INT(o) || MP_OBJ_IS_TYPE(o, &mp_type_int)) #define MP_OBJ_IS_STR(o) (MP_OBJ_IS_QSTR(o) || MP_OBJ_IS_TYPE(o, &mp_type_str)) -#define MP_OBJ_IS_STR_OR_BYTES(o) (MP_OBJ_IS_QSTR(o) || (MP_OBJ_IS_OBJ(o) && ((mp_obj_base_t*)MP_OBJ_TO_PTR(o))->type->binary_op == mp_obj_str_binary_op)) -#define MP_OBJ_IS_FUN(o) (MP_OBJ_IS_OBJ(o) && (((mp_obj_base_t*)MP_OBJ_TO_PTR(o))->type->name == MP_QSTR_function)) +#define MP_OBJ_IS_STR_OR_BYTES(o) (MP_OBJ_IS_QSTR(o) || (MP_OBJ_IS_OBJ(o) && ((mp_obj_base_t *)MP_OBJ_TO_PTR(o))->type->binary_op == mp_obj_str_binary_op)) +#define MP_OBJ_IS_FUN(o) (MP_OBJ_IS_OBJ(o) && (((mp_obj_base_t *)MP_OBJ_TO_PTR(o))->type->name == MP_QSTR_function)) // These macros are used to declare and define constant function objects // You can put "static" in front of the definitions to make them local @@ -282,25 +298,25 @@ typedef struct _mp_rom_obj_t { mp_const_obj_t o; } mp_rom_obj_t; #define MP_DEFINE_CONST_FUN_OBJ_0(obj_name, fun_name) \ const mp_obj_fun_builtin_fixed_t obj_name = \ - {{&mp_type_fun_builtin_0}, .fun._0 = fun_name} + {{&mp_type_fun_builtin_0}, .fun._0 = fun_name} #define MP_DEFINE_CONST_FUN_OBJ_1(obj_name, fun_name) \ const mp_obj_fun_builtin_fixed_t obj_name = \ - {{&mp_type_fun_builtin_1}, .fun._1 = fun_name} + {{&mp_type_fun_builtin_1}, .fun._1 = fun_name} #define MP_DEFINE_CONST_FUN_OBJ_2(obj_name, fun_name) \ const mp_obj_fun_builtin_fixed_t obj_name = \ - {{&mp_type_fun_builtin_2}, .fun._2 = fun_name} + {{&mp_type_fun_builtin_2}, .fun._2 = fun_name} #define MP_DEFINE_CONST_FUN_OBJ_3(obj_name, fun_name) \ const mp_obj_fun_builtin_fixed_t obj_name = \ - {{&mp_type_fun_builtin_3}, .fun._3 = fun_name} + {{&mp_type_fun_builtin_3}, .fun._3 = fun_name} #define MP_DEFINE_CONST_FUN_OBJ_VAR(obj_name, n_args_min, fun_name) \ const mp_obj_fun_builtin_var_t obj_name = \ - {{&mp_type_fun_builtin_var}, MP_OBJ_FUN_MAKE_SIG(n_args_min, MP_OBJ_FUN_ARGS_MAX, false), .fun.var = fun_name} + {{&mp_type_fun_builtin_var}, MP_OBJ_FUN_MAKE_SIG(n_args_min, MP_OBJ_FUN_ARGS_MAX, false), .fun.var = fun_name} #define MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(obj_name, n_args_min, n_args_max, fun_name) \ const mp_obj_fun_builtin_var_t obj_name = \ - {{&mp_type_fun_builtin_var}, MP_OBJ_FUN_MAKE_SIG(n_args_min, n_args_max, false), .fun.var = fun_name} + {{&mp_type_fun_builtin_var}, MP_OBJ_FUN_MAKE_SIG(n_args_min, n_args_max, false), .fun.var = fun_name} #define MP_DEFINE_CONST_FUN_OBJ_KW(obj_name, n_args_min, fun_name) \ const mp_obj_fun_builtin_var_t obj_name = \ - {{&mp_type_fun_builtin_var}, MP_OBJ_FUN_MAKE_SIG(n_args_min, MP_OBJ_FUN_ARGS_MAX, true), .fun.kw = fun_name} + {{&mp_type_fun_builtin_var}, MP_OBJ_FUN_MAKE_SIG(n_args_min, MP_OBJ_FUN_ARGS_MAX, true), .fun.kw = fun_name} // These macros are used to define constant map/dict objects // You can put "static" in front of the definition to make it local @@ -312,7 +328,7 @@ typedef struct _mp_rom_obj_t { mp_const_obj_t o; } mp_rom_obj_t; .is_ordered = 1, \ .used = MP_ARRAY_SIZE(table_name), \ .alloc = MP_ARRAY_SIZE(table_name), \ - .table = (mp_map_elem_t*)(mp_rom_map_elem_t*)table_name, \ + .table = (mp_map_elem_t *)(mp_rom_map_elem_t *)table_name, \ } #define MP_DEFINE_CONST_DICT(dict_name, table_name) \ @@ -324,7 +340,7 @@ typedef struct _mp_rom_obj_t { mp_const_obj_t o; } mp_rom_obj_t; .is_ordered = 1, \ .used = MP_ARRAY_SIZE(table_name), \ .alloc = MP_ARRAY_SIZE(table_name), \ - .table = (mp_map_elem_t*)(mp_rom_map_elem_t*)table_name, \ + .table = (mp_map_elem_t *)(mp_rom_map_elem_t *)table_name, \ }, \ } @@ -373,7 +389,9 @@ typedef enum _mp_map_lookup_kind_t { extern const mp_map_t mp_const_empty_map; -static inline bool MP_MAP_SLOT_IS_FILLED(const mp_map_t *map, size_t pos) { return ((map)->table[pos].key != MP_OBJ_NULL && (map)->table[pos].key != MP_OBJ_SENTINEL); } +static inline bool MP_MAP_SLOT_IS_FILLED(const mp_map_t *map, size_t pos) { + return (map)->table[pos].key != MP_OBJ_NULL && (map)->table[pos].key != MP_OBJ_SENTINEL; +} void mp_map_init(mp_map_t *map, size_t n); void mp_map_init_fixed_table(mp_map_t *map, size_t n, const mp_obj_t *table); @@ -392,7 +410,9 @@ typedef struct _mp_set_t { mp_obj_t *table; } mp_set_t; -static inline bool MP_SET_SLOT_IS_FILLED(const mp_set_t *set, size_t pos) { return ((set)->table[pos] != MP_OBJ_NULL && (set)->table[pos] != MP_OBJ_SENTINEL); } +static inline bool MP_SET_SLOT_IS_FILLED(const mp_set_t *set, size_t pos) { + return (set)->table[pos] != MP_OBJ_NULL && (set)->table[pos] != MP_OBJ_SENTINEL; +} void mp_set_init(mp_set_t *set, size_t n); mp_obj_t mp_set_lookup(mp_set_t *set, mp_obj_t index, mp_map_lookup_kind_t lookup_kind); @@ -442,7 +462,7 @@ typedef struct _mp_buffer_info_t { // if we'd bother to support various versions of structure // (with different number of fields), we can distinguish // them with ver = sizeof(struct). Cons: overkill for *micro*? - //int ver; // ? + // int ver; // ? void *buf; // can be NULL if len == 0 size_t len; // in bytes @@ -626,17 +646,19 @@ extern const struct _mp_obj_exception_t mp_const_GeneratorExit_obj; // General API for objects mp_obj_t mp_obj_new_type(qstr name, mp_obj_t bases_tuple, mp_obj_t locals_dict); -static inline mp_obj_t mp_obj_new_bool(mp_int_t x) { return x ? mp_const_true : mp_const_false; } +static inline mp_obj_t mp_obj_new_bool(mp_int_t x) { + return x ? mp_const_true : mp_const_false; +} mp_obj_t mp_obj_new_cell(mp_obj_t obj); mp_obj_t mp_obj_new_int(mp_int_t value); mp_obj_t mp_obj_new_int_from_uint(mp_uint_t value); mp_obj_t mp_obj_new_int_from_str_len(const char **str, size_t len, bool neg, unsigned int base); mp_obj_t mp_obj_new_int_from_ll(long long val); // this must return a multi-precision integer object (or raise an overflow exception) mp_obj_t mp_obj_new_int_from_ull(unsigned long long val); // this must return a multi-precision integer object (or raise an overflow exception) -mp_obj_t mp_obj_new_str(const char* data, size_t len); -mp_obj_t mp_obj_new_str_via_qstr(const char* data, size_t len); +mp_obj_t mp_obj_new_str(const char *data, size_t len); +mp_obj_t mp_obj_new_str_via_qstr(const char *data, size_t len); mp_obj_t mp_obj_new_str_from_vstr(const mp_obj_type_t *type, vstr_t *vstr); -mp_obj_t mp_obj_new_bytes(const byte* data, size_t len); +mp_obj_t mp_obj_new_bytes(const byte *data, size_t len); mp_obj_t mp_obj_new_bytearray(size_t n, void *items); mp_obj_t mp_obj_new_bytearray_by_ref(size_t n, void *items); #if MICROPY_PY_BUILTINS_FLOAT @@ -677,7 +699,9 @@ bool mp_obj_is_true(mp_obj_t arg); bool mp_obj_is_callable(mp_obj_t o_in); bool mp_obj_equal(mp_obj_t o1, mp_obj_t o2); -static inline bool mp_obj_is_integer(mp_const_obj_t o) { return MP_OBJ_IS_INT(o) || MP_OBJ_IS_TYPE(o, &mp_type_bool); } // returns true if o is bool, small int or long int +static inline bool mp_obj_is_integer(mp_const_obj_t o) { + return MP_OBJ_IS_INT(o) || MP_OBJ_IS_TYPE(o, &mp_type_bool); +} // returns true if o is bool, small int or long int mp_int_t mp_obj_get_int(mp_const_obj_t arg); mp_int_t mp_obj_get_int_truncated(mp_const_obj_t arg); bool mp_obj_get_int_maybe(mp_const_obj_t arg, mp_int_t *value); @@ -686,7 +710,7 @@ mp_float_t mp_obj_get_float(mp_obj_t self_in); bool mp_obj_get_float_maybe(mp_obj_t arg, mp_float_t *value); void mp_obj_get_complex(mp_obj_t self_in, mp_float_t *real, mp_float_t *imag); #endif -//qstr mp_obj_get_qstr(mp_obj_t arg); +// qstr mp_obj_get_qstr(mp_obj_t arg); void mp_obj_get_array(mp_obj_t o, size_t *len, mp_obj_t **items); // *items may point inside a GC block void mp_obj_get_array_fixed_n(mp_obj_t o, size_t len, mp_obj_t **items); // *items may point inside a GC block size_t mp_get_index(const mp_obj_type_t *type, size_t len, mp_obj_t index, bool is_slice); @@ -733,7 +757,9 @@ void mp_str_print_quoted(const mp_print_t *print, const byte *str_data, size_t s #if MICROPY_FLOAT_HIGH_QUALITY_HASH mp_int_t mp_float_hash(mp_float_t val); #else -static inline mp_int_t mp_float_hash(mp_float_t val) { return (mp_int_t)val; } +static inline mp_int_t mp_float_hash(mp_float_t val) { + return (mp_int_t)val; +} #endif mp_obj_t mp_obj_float_binary_op(mp_binary_op_t op, mp_float_t lhs_val, mp_obj_t rhs); // can return MP_OBJ_NULL if op not supported @@ -768,7 +794,7 @@ mp_obj_t mp_obj_dict_get(mp_obj_t self_in, mp_obj_t index); mp_obj_t mp_obj_dict_store(mp_obj_t self_in, mp_obj_t key, mp_obj_t value); mp_obj_t mp_obj_dict_delete(mp_obj_t self_in, mp_obj_t key); static inline mp_map_t *mp_obj_dict_get_map(mp_obj_t dict) { - return &((mp_obj_dict_t*)MP_OBJ_TO_PTR(dict))->map; + return &((mp_obj_dict_t *)MP_OBJ_TO_PTR(dict))->map; } // set @@ -811,7 +837,7 @@ typedef struct _mp_obj_module_t { mp_obj_dict_t *globals; } mp_obj_module_t; static inline mp_obj_dict_t *mp_obj_module_get_globals(mp_obj_t module) { - return ((mp_obj_module_t*)MP_OBJ_TO_PTR(module))->globals; + return ((mp_obj_module_t *)MP_OBJ_TO_PTR(module))->globals; } // check if given module object is a package bool mp_obj_is_package(mp_obj_t module); @@ -851,17 +877,17 @@ mp_obj_t mp_seq_index_obj(const mp_obj_t *items, size_t len, size_t n_args, cons mp_obj_t mp_seq_count_obj(const mp_obj_t *items, size_t len, mp_obj_t value); mp_obj_t mp_seq_extract_slice(size_t len, const mp_obj_t *seq, mp_bound_slice_t *indexes); // Helper to clear stale pointers from allocated, but unused memory, to preclude GC problems -#define mp_seq_clear(start, len, alloc_len, item_sz) memset((byte*)(start) + (len) * (item_sz), 0, ((alloc_len) - (len)) * (item_sz)) +#define mp_seq_clear(start, len, alloc_len, item_sz) memset((byte *)(start) + (len) * (item_sz), 0, ((alloc_len) - (len)) * (item_sz)) #define mp_seq_replace_slice_no_grow(dest, dest_len, beg, end, slice, slice_len, item_sz) \ /*printf("memcpy(%p, %p, %d)\n", dest + beg, slice, slice_len * (item_sz));*/ \ - memcpy(((char*)dest) + (beg) * (item_sz), slice, slice_len * (item_sz)); \ + memcpy(((char *)dest) + (beg) * (item_sz), slice, slice_len * (item_sz)); \ /*printf("memmove(%p, %p, %d)\n", dest + (beg + slice_len), dest + end, (dest_len - end) * (item_sz));*/ \ - memmove(((char*)dest) + (beg + slice_len) * (item_sz), ((char*)dest) + (end) * (item_sz), (dest_len - end) * (item_sz)); + memmove(((char *)dest) + (beg + slice_len) * (item_sz), ((char *)dest) + (end) * (item_sz), (dest_len - end) * (item_sz)); // Note: dest and slice regions may overlap #define mp_seq_replace_slice_grow_inplace(dest, dest_len, beg, end, slice, slice_len, len_adj, item_sz) \ /*printf("memmove(%p, %p, %d)\n", dest + beg + len_adj, dest + beg, (dest_len - beg) * (item_sz));*/ \ - memmove(((char*)dest) + (beg + slice_len) * (item_sz), ((char*)dest) + (end) * (item_sz), ((dest_len) + (len_adj) - ((beg) + (slice_len))) * (item_sz)); \ - memmove(((char*)dest) + (beg) * (item_sz), slice, slice_len * (item_sz)); + memmove(((char *)dest) + (beg + slice_len) * (item_sz), ((char *)dest) + (end) * (item_sz), ((dest_len) + (len_adj) - ((beg) + (slice_len))) * (item_sz)); \ + memmove(((char *)dest) + (beg) * (item_sz), slice, slice_len * (item_sz)); #endif // MICROPY_INCLUDED_PY_OBJ_H diff --git a/py/objarray.c b/py/objarray.c index 6f857a9eda..9a6cea6c79 100644 --- a/py/objarray.c +++ b/py/objarray.c @@ -117,10 +117,10 @@ STATIC mp_obj_t array_construct(char typecode, mp_obj_t initializer) { // other arrays can only be raw-initialised from bytes and bytearray objects mp_buffer_info_t bufinfo; if (((MICROPY_PY_BUILTINS_BYTEARRAY - && typecode == BYTEARRAY_TYPECODE) - || (MICROPY_PY_ARRAY - && (MP_OBJ_IS_TYPE(initializer, &mp_type_bytes) - || (MICROPY_PY_BUILTINS_BYTEARRAY && MP_OBJ_IS_TYPE(initializer, &mp_type_bytearray))))) + && typecode == BYTEARRAY_TYPECODE) + || (MICROPY_PY_ARRAY + && (MP_OBJ_IS_TYPE(initializer, &mp_type_bytes) + || (MICROPY_PY_BUILTINS_BYTEARRAY && MP_OBJ_IS_TYPE(initializer, &mp_type_bytearray))))) && mp_get_buffer(initializer, &bufinfo, MP_BUFFER_READ)) { // construct array from raw bytes // we round-down the len to make it a multiple of sz (CPython raises error) @@ -236,9 +236,12 @@ STATIC mp_obj_t memoryview_make_new(const mp_obj_type_t *type_in, size_t n_args, STATIC mp_obj_t array_unary_op(mp_unary_op_t op, mp_obj_t o_in) { mp_obj_array_t *o = MP_OBJ_TO_PTR(o_in); switch (op) { - case MP_UNARY_OP_BOOL: return mp_obj_new_bool(o->len != 0); - case MP_UNARY_OP_LEN: return MP_OBJ_NEW_SMALL_INT(o->len); - default: return MP_OBJ_NULL; // op not supported + case MP_UNARY_OP_BOOL: + return mp_obj_new_bool(o->len != 0); + case MP_UNARY_OP_LEN: + return MP_OBJ_NEW_SMALL_INT(o->len); + default: + return MP_OBJ_NULL; // op not supported } } @@ -259,7 +262,7 @@ STATIC mp_obj_t array_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs // note: lhs->len is element count of lhs, lhs_bufinfo.len is byte count mp_obj_array_t *res = array_new(lhs_bufinfo.typecode, lhs->len + rhs_len); - mp_seq_cat((byte*)res->items, lhs_bufinfo.buf, lhs_bufinfo.len, rhs_bufinfo.buf, rhs_len * sz, byte); + mp_seq_cat((byte *)res->items, lhs_bufinfo.buf, lhs_bufinfo.len, rhs_bufinfo.buf, rhs_len * sz, byte); return MP_OBJ_FROM_PTR(res); } @@ -358,7 +361,7 @@ STATIC mp_obj_t array_extend(mp_obj_t self_in, mp_obj_t arg_in) { } // extend - mp_seq_copy((byte*)self->items + self->len * sz, arg_bufinfo.buf, len * sz, byte); + mp_seq_copy((byte *)self->items + self->len * sz, arg_bufinfo.buf, len * sz, byte); self->len += len; return mp_const_none; @@ -376,7 +379,7 @@ STATIC mp_obj_t array_subscr(mp_obj_t self_in, mp_obj_t index_in, mp_obj_t value } else { mp_obj_array_t *o = MP_OBJ_TO_PTR(self_in); if (0) { -#if MICROPY_PY_BUILTINS_SLICE + #if MICROPY_PY_BUILTINS_SLICE } else if (MP_OBJ_IS_TYPE(index_in, &mp_type_slice)) { mp_bound_slice_t slice; if (!mp_seq_get_fast_slice_indexes(o->len, index_in, &slice)) { @@ -388,7 +391,7 @@ STATIC mp_obj_t array_subscr(mp_obj_t self_in, mp_obj_t index_in, mp_obj_t value size_t src_len; void *src_items; size_t item_sz = mp_binary_get_size('@', o->typecode & TYPECODE_MASK, NULL); - if (MP_OBJ_IS_OBJ(value) && ((mp_obj_base_t*)MP_OBJ_TO_PTR(value))->type->subscr == array_subscr) { + if (MP_OBJ_IS_OBJ(value) && ((mp_obj_base_t *)MP_OBJ_TO_PTR(value))->type->subscr == array_subscr) { // value is array, bytearray or memoryview mp_obj_array_t *src_slice = MP_OBJ_TO_PTR(value); if (item_sz != mp_binary_get_size('@', src_slice->typecode & TYPECODE_MASK, NULL)) { @@ -399,7 +402,7 @@ STATIC mp_obj_t array_subscr(mp_obj_t self_in, mp_obj_t index_in, mp_obj_t value src_items = src_slice->items; #if MICROPY_PY_BUILTINS_MEMORYVIEW if (MP_OBJ_IS_TYPE(value, &mp_type_memoryview)) { - src_items = (uint8_t*)src_items + (src_slice->memview_offset * item_sz); + src_items = (uint8_t *)src_items + (src_slice->memview_offset * item_sz); } #endif } else if (MP_OBJ_IS_TYPE(value, &mp_type_bytes)) { @@ -416,7 +419,7 @@ STATIC mp_obj_t array_subscr(mp_obj_t self_in, mp_obj_t index_in, mp_obj_t value // TODO: check src/dst compat mp_int_t len_adj = src_len - (slice.stop - slice.start); - uint8_t* dest_items = o->items; + uint8_t *dest_items = o->items; #if MICROPY_PY_BUILTINS_MEMORYVIEW if (o->base.type == &mp_type_memoryview) { if (!(o->typecode & MP_OBJ_ARRAY_TYPECODE_FLAG_RW)) { @@ -467,10 +470,10 @@ STATIC mp_obj_t array_subscr(mp_obj_t self_in, mp_obj_t index_in, mp_obj_t value #endif } else { res = array_new(o->typecode, slice.stop - slice.start); - memcpy(res->items, (uint8_t*)o->items + slice.start * sz, (slice.stop - slice.start) * sz); + memcpy(res->items, (uint8_t *)o->items + slice.start * sz, (slice.stop - slice.start) * sz); } return MP_OBJ_FROM_PTR(res); -#endif + #endif } else { size_t index = mp_get_index(o->base.type, o->len, index_in, false); #if MICROPY_PY_BUILTINS_MEMORYVIEW @@ -506,7 +509,7 @@ STATIC mp_int_t array_get_buffer(mp_obj_t o_in, mp_buffer_info_t *bufinfo, mp_ui // read-only memoryview return 1; } - bufinfo->buf = (uint8_t*)bufinfo->buf + (size_t)o->memview_offset * sz; + bufinfo->buf = (uint8_t *)bufinfo->buf + (size_t)o->memview_offset * sz; } #else (void)flags; @@ -534,7 +537,7 @@ const mp_obj_type_t mp_type_array = { .binary_op = array_binary_op, .subscr = array_subscr, .buffer_p = { .get_buffer = array_get_buffer }, - .locals_dict = (mp_obj_dict_t*)&array_locals_dict, + .locals_dict = (mp_obj_dict_t *)&array_locals_dict, }; #endif @@ -549,7 +552,7 @@ const mp_obj_type_t mp_type_bytearray = { .binary_op = array_binary_op, .subscr = array_subscr, .buffer_p = { .get_buffer = array_get_buffer }, - .locals_dict = (mp_obj_dict_t*)&array_locals_dict, + .locals_dict = (mp_obj_dict_t *)&array_locals_dict, }; #endif @@ -620,7 +623,7 @@ STATIC const mp_obj_type_t array_it_type = { STATIC mp_obj_t array_iterator_new(mp_obj_t array_in, mp_obj_iter_buf_t *iter_buf) { assert(sizeof(mp_obj_array_t) <= sizeof(mp_obj_iter_buf_t)); mp_obj_array_t *array = MP_OBJ_TO_PTR(array_in); - mp_obj_array_it_t *o = (mp_obj_array_it_t*)iter_buf; + mp_obj_array_it_t *o = (mp_obj_array_it_t *)iter_buf; o->base.type = &array_it_type; o->array = array; o->offset = 0; diff --git a/py/objattrtuple.c b/py/objattrtuple.c index 3cc298d4e9..3422d0146a 100644 --- a/py/objattrtuple.c +++ b/py/objattrtuple.c @@ -51,7 +51,7 @@ void mp_obj_attrtuple_print_helper(const mp_print_t *print, const qstr *fields, STATIC void mp_obj_attrtuple_print(const mp_print_t *print, mp_obj_t o_in, mp_print_kind_t kind) { (void)kind; mp_obj_tuple_t *o = MP_OBJ_TO_PTR(o_in); - const qstr *fields = (const qstr*)MP_OBJ_TO_PTR(o->items[o->len]); + const qstr *fields = (const qstr *)MP_OBJ_TO_PTR(o->items[o->len]); mp_obj_attrtuple_print_helper(print, fields, o); } @@ -60,7 +60,7 @@ STATIC void mp_obj_attrtuple_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) { // load attribute mp_obj_tuple_t *self = MP_OBJ_TO_PTR(self_in); size_t len = self->len; - const qstr *fields = (const qstr*)MP_OBJ_TO_PTR(self->items[len]); + const qstr *fields = (const qstr *)MP_OBJ_TO_PTR(self->items[len]); for (size_t i = 0; i < len; i++) { if (fields[i] == attr) { dest[0] = self->items[i]; diff --git a/py/objboundmeth.c b/py/objboundmeth.c index 8fc44f1637..a3e1d302d9 100644 --- a/py/objboundmeth.c +++ b/py/objboundmeth.c @@ -98,13 +98,13 @@ STATIC void bound_meth_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) { STATIC const mp_obj_type_t mp_type_bound_meth = { { &mp_type_type }, .name = MP_QSTR_bound_method, -#if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_DETAILED + #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_DETAILED .print = bound_meth_print, -#endif + #endif .call = bound_meth_call, -#if MICROPY_PY_FUNCTION_ATTRS + #if MICROPY_PY_FUNCTION_ATTRS .attr = bound_meth_attr, -#endif + #endif }; mp_obj_t mp_obj_new_bound_meth(mp_obj_t meth, mp_obj_t self) { diff --git a/py/objcell.c b/py/objcell.c index 111906412e..be2ae8cd9c 100644 --- a/py/objcell.c +++ b/py/objcell.c @@ -58,9 +58,9 @@ STATIC void cell_print(const mp_print_t *print, mp_obj_t o_in, mp_print_kind_t k STATIC const mp_obj_type_t mp_type_cell = { { &mp_type_type }, .name = MP_QSTR_, // cell representation is just value in < > -#if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_DETAILED + #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_DETAILED .print = cell_print, -#endif + #endif }; mp_obj_t mp_obj_new_cell(mp_obj_t obj) { diff --git a/py/objclosure.c b/py/objclosure.c index 4eb9eb8b84..f5038ffc46 100644 --- a/py/objclosure.c +++ b/py/objclosure.c @@ -81,9 +81,9 @@ STATIC void closure_print(const mp_print_t *print, mp_obj_t o_in, mp_print_kind_ const mp_obj_type_t closure_type = { { &mp_type_type }, .name = MP_QSTR_closure, -#if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_DETAILED + #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_DETAILED .print = closure_print, -#endif + #endif .call = closure_call, }; diff --git a/py/objcomplex.c b/py/objcomplex.c index 42b396da34..cc37e2fd1f 100644 --- a/py/objcomplex.c +++ b/py/objcomplex.c @@ -45,17 +45,17 @@ typedef struct _mp_obj_complex_t { STATIC void complex_print(const mp_print_t *print, mp_obj_t o_in, mp_print_kind_t kind) { (void)kind; mp_obj_complex_t *o = MP_OBJ_TO_PTR(o_in); -#if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT + #if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT char buf[16]; #if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_C const int precision = 6; #else const int precision = 7; #endif -#else + #else char buf[32]; const int precision = 16; -#endif + #endif if (o->real == 0) { mp_format_float(o->imag, buf, sizeof(buf), 'g', precision, '\0'); mp_printf(print, "%sj", buf); @@ -117,13 +117,18 @@ STATIC mp_obj_t complex_make_new(const mp_obj_type_t *type_in, size_t n_args, si STATIC mp_obj_t complex_unary_op(mp_unary_op_t op, mp_obj_t o_in) { mp_obj_complex_t *o = MP_OBJ_TO_PTR(o_in); switch (op) { - case MP_UNARY_OP_BOOL: return mp_obj_new_bool(o->real != 0 || o->imag != 0); - case MP_UNARY_OP_HASH: return MP_OBJ_NEW_SMALL_INT(mp_float_hash(o->real) ^ mp_float_hash(o->imag)); - case MP_UNARY_OP_POSITIVE: return o_in; - case MP_UNARY_OP_NEGATIVE: return mp_obj_new_complex(-o->real, -o->imag); + case MP_UNARY_OP_BOOL: + return mp_obj_new_bool(o->real != 0 || o->imag != 0); + case MP_UNARY_OP_HASH: + return MP_OBJ_NEW_SMALL_INT(mp_float_hash(o->real) ^ mp_float_hash(o->imag)); + case MP_UNARY_OP_POSITIVE: + return o_in; + case MP_UNARY_OP_NEGATIVE: + return mp_obj_new_complex(-o->real, -o->imag); case MP_UNARY_OP_ABS: - return mp_obj_new_float(MICROPY_FLOAT_C_FUN(sqrt)(o->real*o->real + o->imag*o->imag)); - default: return MP_OBJ_NULL; // op not supported + return mp_obj_new_float(MICROPY_FLOAT_C_FUN(sqrt)(o->real * o->real + o->imag * o->imag)); + default: + return MP_OBJ_NULL; // op not supported } } @@ -187,7 +192,7 @@ mp_obj_t mp_obj_complex_binary_op(mp_binary_op_t op, mp_float_t lhs_real, mp_flo case MP_BINARY_OP_MULTIPLY: case MP_BINARY_OP_INPLACE_MULTIPLY: { mp_float_t real; - multiply: + multiply: real = lhs_real * rhs_real - lhs_imag * rhs_imag; lhs_imag = lhs_real * rhs_imag + lhs_imag * rhs_real; lhs_real = real; @@ -210,7 +215,7 @@ mp_obj_t mp_obj_complex_binary_op(mp_binary_op_t op, mp_float_t lhs_real, mp_flo lhs_imag = -lhs_real / rhs_imag; lhs_real = real; } else { - mp_float_t rhs_len_sq = rhs_real*rhs_real + rhs_imag*rhs_imag; + mp_float_t rhs_len_sq = rhs_real * rhs_real + rhs_imag * rhs_imag; rhs_real /= rhs_len_sq; rhs_imag /= -rhs_len_sq; goto multiply; @@ -224,7 +229,7 @@ mp_obj_t mp_obj_complex_binary_op(mp_binary_op_t op, mp_float_t lhs_real, mp_flo // = exp( (x2*ln1 - y2*arg1) + i*(y2*ln1 + x2*arg1) ) // = exp(x3 + i*y3) // = exp(x3)*(cos(y3) + i*sin(y3)) - mp_float_t abs1 = MICROPY_FLOAT_C_FUN(sqrt)(lhs_real*lhs_real + lhs_imag*lhs_imag); + mp_float_t abs1 = MICROPY_FLOAT_C_FUN(sqrt)(lhs_real * lhs_real + lhs_imag * lhs_imag); if (abs1 == 0) { if (rhs_imag == 0 && rhs_real >= 0) { lhs_real = (rhs_real == 0); @@ -243,7 +248,8 @@ mp_obj_t mp_obj_complex_binary_op(mp_binary_op_t op, mp_float_t lhs_real, mp_flo break; } - case MP_BINARY_OP_EQUAL: return mp_obj_new_bool(lhs_real == rhs_real && lhs_imag == rhs_imag); + case MP_BINARY_OP_EQUAL: + return mp_obj_new_bool(lhs_real == rhs_real && lhs_imag == rhs_imag); default: return MP_OBJ_NULL; // op not supported diff --git a/py/objdeque.c b/py/objdeque.c index 1cff1f8d3b..0eb666591e 100644 --- a/py/objdeque.c +++ b/py/objdeque.c @@ -161,7 +161,7 @@ const mp_obj_type_t mp_type_deque = { .name = MP_QSTR_deque, .make_new = deque_make_new, .unary_op = deque_unary_op, - .locals_dict = (mp_obj_dict_t*)&deque_locals_dict, + .locals_dict = (mp_obj_dict_t *)&deque_locals_dict, }; #endif // MICROPY_PY_COLLECTIONS_DEQUE diff --git a/py/objdict.c b/py/objdict.c index 92e837a881..59366b8c46 100644 --- a/py/objdict.c +++ b/py/objdict.c @@ -31,7 +31,7 @@ #include "py/builtin.h" #include "py/objtype.h" -#define MP_OBJ_IS_DICT_TYPE(o) (MP_OBJ_IS_OBJ(o) && ((mp_obj_base_t*)MP_OBJ_TO_PTR(o))->type->make_new == dict_make_new) +#define MP_OBJ_IS_DICT_TYPE(o) (MP_OBJ_IS_OBJ(o) && ((mp_obj_base_t *)MP_OBJ_TO_PTR(o))->type->make_new == dict_make_new) STATIC mp_obj_t dict_update(size_t n_args, const mp_obj_t *args, mp_map_t *kwargs); @@ -100,15 +100,18 @@ STATIC mp_obj_t dict_make_new(const mp_obj_type_t *type, size_t n_args, size_t n STATIC mp_obj_t dict_unary_op(mp_unary_op_t op, mp_obj_t self_in) { mp_obj_dict_t *self = MP_OBJ_TO_PTR(self_in); switch (op) { - case MP_UNARY_OP_BOOL: return mp_obj_new_bool(self->map.used != 0); - case MP_UNARY_OP_LEN: return MP_OBJ_NEW_SMALL_INT(self->map.used); + case MP_UNARY_OP_BOOL: + return mp_obj_new_bool(self->map.used != 0); + case MP_UNARY_OP_LEN: + return MP_OBJ_NEW_SMALL_INT(self->map.used); #if MICROPY_PY_SYS_GETSIZEOF case MP_UNARY_OP_SIZEOF: { size_t sz = sizeof(*self) + sizeof(*self->map.table) * self->map.alloc; return MP_OBJ_NEW_SMALL_INT(sz); } #endif - default: return MP_OBJ_NULL; // op not supported + default: + return MP_OBJ_NULL; // op not supported } } @@ -338,7 +341,7 @@ STATIC mp_obj_t dict_update(size_t n_args, const mp_obj_t *args, mp_map_t *kwarg if (args[1] != args[0]) { size_t cur = 0; mp_map_elem_t *elem = NULL; - while ((elem = dict_iter_next((mp_obj_dict_t*)MP_OBJ_TO_PTR(args[1]), &cur)) != NULL) { + while ((elem = dict_iter_next((mp_obj_dict_t *)MP_OBJ_TO_PTR(args[1]), &cur)) != NULL) { mp_map_lookup(&self->map, elem->key, MP_MAP_LOOKUP_ADD_IF_NOT_FOUND)->value = elem->value; } } @@ -434,7 +437,7 @@ STATIC mp_obj_t dict_view_getiter(mp_obj_t view_in, mp_obj_iter_buf_t *iter_buf) assert(sizeof(mp_obj_dict_view_it_t) <= sizeof(mp_obj_iter_buf_t)); mp_check_self(MP_OBJ_IS_TYPE(view_in, &dict_view_type)); mp_obj_dict_view_t *view = MP_OBJ_TO_PTR(view_in); - mp_obj_dict_view_it_t *o = (mp_obj_dict_view_it_t*)iter_buf; + mp_obj_dict_view_it_t *o = (mp_obj_dict_view_it_t *)iter_buf; o->base.type = &dict_view_it_type; o->kind = view->kind; o->dict = view->dict; @@ -516,7 +519,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_1(dict_values_obj, dict_values); STATIC mp_obj_t dict_getiter(mp_obj_t self_in, mp_obj_iter_buf_t *iter_buf) { assert(sizeof(mp_obj_dict_view_it_t) <= sizeof(mp_obj_iter_buf_t)); mp_check_self(MP_OBJ_IS_DICT_TYPE(self_in)); - mp_obj_dict_view_it_t *o = (mp_obj_dict_view_it_t*)iter_buf; + mp_obj_dict_view_it_t *o = (mp_obj_dict_view_it_t *)iter_buf; o->base.type = &dict_view_it_type; o->kind = MP_DICT_VIEW_KEYS; o->dict = self_in; @@ -557,7 +560,7 @@ const mp_obj_type_t mp_type_dict = { .binary_op = dict_binary_op, .subscr = dict_subscr, .getiter = dict_getiter, - .locals_dict = (mp_obj_dict_t*)&dict_locals_dict, + .locals_dict = (mp_obj_dict_t *)&dict_locals_dict, }; #if MICROPY_PY_COLLECTIONS_ORDEREDDICT @@ -571,7 +574,7 @@ const mp_obj_type_t mp_type_ordereddict = { .subscr = dict_subscr, .getiter = dict_getiter, .parent = &mp_type_dict, - .locals_dict = (mp_obj_dict_t*)&dict_locals_dict, + .locals_dict = (mp_obj_dict_t *)&dict_locals_dict, }; #endif diff --git a/py/objenumerate.c b/py/objenumerate.c index 1a9d30f836..4bb5e17b90 100644 --- a/py/objenumerate.c +++ b/py/objenumerate.c @@ -40,7 +40,7 @@ typedef struct _mp_obj_enumerate_t { STATIC mp_obj_t enumerate_iternext(mp_obj_t self_in); STATIC mp_obj_t enumerate_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 MICROPY_CPYTHON_COMPAT static const mp_arg_t allowed_args[] = { { MP_QSTR_iterable, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, { MP_QSTR_start, MP_ARG_INT, {.u_int = 0} }, @@ -51,20 +51,20 @@ STATIC mp_obj_t enumerate_make_new(const mp_obj_type_t *type, size_t n_args, siz mp_arg_val_t iterable, start; } arg_vals; mp_arg_parse_all_kw_array(n_args, n_kw, args, - MP_ARRAY_SIZE(allowed_args), allowed_args, (mp_arg_val_t*)&arg_vals); + MP_ARRAY_SIZE(allowed_args), allowed_args, (mp_arg_val_t *)&arg_vals); // create enumerate object mp_obj_enumerate_t *o = m_new_obj(mp_obj_enumerate_t); o->base.type = type; o->iter = mp_getiter(arg_vals.iterable.u_obj, NULL); o->cur = arg_vals.start.u_int; -#else + #else (void)n_kw; mp_obj_enumerate_t *o = m_new_obj(mp_obj_enumerate_t); o->base.type = type; o->iter = mp_getiter(args[0], NULL); o->cur = n_args > 1 ? mp_obj_get_int(args[1]) : 0; -#endif + #endif return MP_OBJ_FROM_PTR(o); } diff --git a/py/objexcept.c b/py/objexcept.c index 2a10aa99a4..6a86cdbad6 100644 --- a/py/objexcept.c +++ b/py/objexcept.c @@ -57,7 +57,7 @@ #define EMG_BUF_TUPLE_SIZE(n_args) (sizeof(mp_obj_tuple_t) + n_args * sizeof(mp_obj_t)) #define EMG_BUF_STR_OFFSET (EMG_BUF_TUPLE_OFFSET + EMG_BUF_TUPLE_SIZE(1)) -# if MICROPY_EMERGENCY_EXCEPTION_BUF_SIZE > 0 +#if MICROPY_EMERGENCY_EXCEPTION_BUF_SIZE > 0 #define mp_emergency_exception_buf_size MICROPY_EMERGENCY_EXCEPTION_BUF_SIZE void mp_init_emergency_exception_buf(void) { @@ -102,7 +102,7 @@ mp_obj_t mp_alloc_emergency_exception_buf(mp_obj_t size_in) { // Instance of GeneratorExit exception - needed by generator.close() // This would belong to objgenerator.c, but to keep mp_obj_exception_t // definition module-private so far, have it here. -const mp_obj_exception_t mp_const_GeneratorExit_obj = {{&mp_type_GeneratorExit}, 0, 0, NULL, (mp_obj_tuple_t*)&mp_const_empty_tuple_obj}; +const mp_obj_exception_t mp_const_GeneratorExit_obj = {{&mp_type_GeneratorExit}, 0, 0, NULL, (mp_obj_tuple_t *)&mp_const_empty_tuple_obj}; void mp_obj_exception_print(const mp_print_t *print, mp_obj_t o_in, mp_print_kind_t kind) { mp_obj_exception_t *o = MP_OBJ_TO_PTR(o_in); @@ -154,7 +154,7 @@ mp_obj_t mp_obj_exception_make_new(const mp_obj_type_t *type, size_t n_args, siz mp_obj_tuple_t *o_tuple; if (n_args == 0) { // No args, can use the empty tuple straightaway - o_tuple = (mp_obj_tuple_t*)&mp_const_empty_tuple_obj; + o_tuple = (mp_obj_tuple_t *)&mp_const_empty_tuple_obj; } else { // Try to allocate memory for the tuple containing the args o_tuple = m_new_obj_var_maybe(mp_obj_tuple_t, mp_obj_t, n_args); @@ -165,14 +165,14 @@ mp_obj_t mp_obj_exception_make_new(const mp_obj_type_t *type, size_t n_args, siz // Otherwise we are free to use the whole buffer after the traceback data. if (o_tuple == NULL && mp_emergency_exception_buf_size >= EMG_BUF_TUPLE_OFFSET + EMG_BUF_TUPLE_SIZE(n_args)) { - o_tuple = (mp_obj_tuple_t*) - ((uint8_t*)MP_STATE_VM(mp_emergency_exception_buf) + EMG_BUF_TUPLE_OFFSET); + o_tuple = (mp_obj_tuple_t *) + ((uint8_t *)MP_STATE_VM(mp_emergency_exception_buf) + EMG_BUF_TUPLE_OFFSET); } #endif if (o_tuple == NULL) { // No memory for a tuple, fallback to an empty tuple - o_tuple = (mp_obj_tuple_t*)&mp_const_empty_tuple_obj; + o_tuple = (mp_obj_tuple_t *)&mp_const_empty_tuple_obj; } else { // Have memory for a tuple so populate it o_tuple->base.type = &mp_type_tuple; @@ -235,33 +235,33 @@ MP_DEFINE_EXCEPTION(KeyboardInterrupt, BaseException) MP_DEFINE_EXCEPTION(GeneratorExit, BaseException) MP_DEFINE_EXCEPTION(Exception, BaseException) #if MICROPY_PY_ASYNC_AWAIT - MP_DEFINE_EXCEPTION(StopAsyncIteration, Exception) +MP_DEFINE_EXCEPTION(StopAsyncIteration, Exception) #endif - MP_DEFINE_EXCEPTION(StopIteration, Exception) - MP_DEFINE_EXCEPTION(ArithmeticError, Exception) - //MP_DEFINE_EXCEPTION(FloatingPointError, ArithmeticError) - MP_DEFINE_EXCEPTION(OverflowError, ArithmeticError) - MP_DEFINE_EXCEPTION(ZeroDivisionError, ArithmeticError) - MP_DEFINE_EXCEPTION(AssertionError, Exception) - MP_DEFINE_EXCEPTION(AttributeError, Exception) - //MP_DEFINE_EXCEPTION(BufferError, Exception) - //MP_DEFINE_EXCEPTION(EnvironmentError, Exception) use OSError instead - MP_DEFINE_EXCEPTION(EOFError, Exception) - MP_DEFINE_EXCEPTION(ImportError, Exception) - //MP_DEFINE_EXCEPTION(IOError, Exception) use OSError instead - MP_DEFINE_EXCEPTION(LookupError, Exception) - MP_DEFINE_EXCEPTION(IndexError, LookupError) - MP_DEFINE_EXCEPTION(KeyError, LookupError) - MP_DEFINE_EXCEPTION(MemoryError, Exception) - MP_DEFINE_EXCEPTION(NameError, Exception) - /* +MP_DEFINE_EXCEPTION(StopIteration, Exception) +MP_DEFINE_EXCEPTION(ArithmeticError, Exception) +// MP_DEFINE_EXCEPTION(FloatingPointError, ArithmeticError) +MP_DEFINE_EXCEPTION(OverflowError, ArithmeticError) +MP_DEFINE_EXCEPTION(ZeroDivisionError, ArithmeticError) +MP_DEFINE_EXCEPTION(AssertionError, Exception) +MP_DEFINE_EXCEPTION(AttributeError, Exception) +// MP_DEFINE_EXCEPTION(BufferError, Exception) +// MP_DEFINE_EXCEPTION(EnvironmentError, Exception) use OSError instead +MP_DEFINE_EXCEPTION(EOFError, Exception) +MP_DEFINE_EXCEPTION(ImportError, Exception) +// MP_DEFINE_EXCEPTION(IOError, Exception) use OSError instead +MP_DEFINE_EXCEPTION(LookupError, Exception) +MP_DEFINE_EXCEPTION(IndexError, LookupError) +MP_DEFINE_EXCEPTION(KeyError, LookupError) +MP_DEFINE_EXCEPTION(MemoryError, Exception) +MP_DEFINE_EXCEPTION(NameError, Exception) +/* MP_DEFINE_EXCEPTION(UnboundLocalError, NameError) */ - MP_DEFINE_EXCEPTION(OSError, Exception) +MP_DEFINE_EXCEPTION(OSError, Exception) #if MICROPY_PY_BUILTINS_TIMEOUTERROR - MP_DEFINE_EXCEPTION(TimeoutError, OSError) +MP_DEFINE_EXCEPTION(TimeoutError, OSError) #endif - /* +/* MP_DEFINE_EXCEPTION(BlockingIOError, OSError) MP_DEFINE_EXCEPTION(ChildProcessError, OSError) MP_DEFINE_EXCEPTION(ConnectionError, OSError) @@ -278,24 +278,24 @@ MP_DEFINE_EXCEPTION(Exception, BaseException) MP_DEFINE_EXCEPTION(FileNotFoundError, OSError) MP_DEFINE_EXCEPTION(ReferenceError, Exception) */ - MP_DEFINE_EXCEPTION(RuntimeError, Exception) - MP_DEFINE_EXCEPTION(NotImplementedError, RuntimeError) - MP_DEFINE_EXCEPTION(SyntaxError, Exception) - MP_DEFINE_EXCEPTION(IndentationError, SyntaxError) - /* +MP_DEFINE_EXCEPTION(RuntimeError, Exception) +MP_DEFINE_EXCEPTION(NotImplementedError, RuntimeError) +MP_DEFINE_EXCEPTION(SyntaxError, Exception) +MP_DEFINE_EXCEPTION(IndentationError, SyntaxError) +/* MP_DEFINE_EXCEPTION(TabError, IndentationError) */ - //MP_DEFINE_EXCEPTION(SystemError, Exception) - MP_DEFINE_EXCEPTION(TypeError, Exception) +// MP_DEFINE_EXCEPTION(SystemError, Exception) +MP_DEFINE_EXCEPTION(TypeError, Exception) #if MICROPY_EMIT_NATIVE - MP_DEFINE_EXCEPTION(ViperTypeError, TypeError) +MP_DEFINE_EXCEPTION(ViperTypeError, TypeError) #endif - MP_DEFINE_EXCEPTION(ValueError, Exception) +MP_DEFINE_EXCEPTION(ValueError, Exception) #if MICROPY_PY_BUILTINS_STR_UNICODE - MP_DEFINE_EXCEPTION(UnicodeError, ValueError) - //TODO: Implement more UnicodeError subclasses which take arguments +MP_DEFINE_EXCEPTION(UnicodeError, ValueError) +// TODO: Implement more UnicodeError subclasses which take arguments #endif - /* +/* MP_DEFINE_EXCEPTION(Warning, Exception) MP_DEFINE_EXCEPTION(DeprecationWarning, Warning) MP_DEFINE_EXCEPTION(PendingDeprecationWarning, Warning) @@ -336,7 +336,7 @@ mp_obj_t mp_obj_new_exception_msg(const mp_obj_type_t *exc_type, const char *msg // traceback and 1-tuple. if (o_str == NULL && mp_emergency_exception_buf_size >= EMG_BUF_STR_OFFSET + sizeof(mp_obj_str_t)) { - o_str = (mp_obj_str_t*)((uint8_t*)MP_STATE_VM(mp_emergency_exception_buf) + o_str = (mp_obj_str_t *)((uint8_t *)MP_STATE_VM(mp_emergency_exception_buf) + EMG_BUF_STR_OFFSET); } #endif @@ -350,7 +350,7 @@ mp_obj_t mp_obj_new_exception_msg(const mp_obj_type_t *exc_type, const char *msg o_str->base.type = &mp_type_str; o_str->hash = qstr_compute_hash(o_str->data, o_str->len); o_str->len = strlen(msg); - o_str->data = (const byte*)msg; + o_str->data = (const byte *)msg; mp_obj_t arg = MP_OBJ_FROM_PTR(o_str); return mp_obj_exception_make_new(exc_type, 1, 0, &arg); } @@ -407,10 +407,10 @@ mp_obj_t mp_obj_new_exception_msg_varg(const mp_obj_type_t *exc_type, const char if ((o_str == NULL || o_str_buf == NULL) && mp_emergency_exception_buf_size >= EMG_BUF_STR_OFFSET + sizeof(mp_obj_str_t) + 16) { used_emg_buf = true; - o_str = (mp_obj_str_t*)((uint8_t*)MP_STATE_VM(mp_emergency_exception_buf) + o_str = (mp_obj_str_t *)((uint8_t *)MP_STATE_VM(mp_emergency_exception_buf) + EMG_BUF_STR_OFFSET); - o_str_buf = (byte*)&o_str[1]; - o_str_alloc = (uint8_t*)MP_STATE_VM(mp_emergency_exception_buf) + o_str_buf = (byte *)&o_str[1]; + o_str_alloc = (uint8_t *)MP_STATE_VM(mp_emergency_exception_buf) + mp_emergency_exception_buf_size - o_str_buf; } #endif @@ -424,7 +424,7 @@ mp_obj_t mp_obj_new_exception_msg_varg(const mp_obj_type_t *exc_type, const char // No memory for the string buffer: assume that the fmt string is in ROM // and use that data as the data of the string o_str->len = o_str_alloc - 1; // will be equal to strlen(fmt) - o_str->data = (const byte*)fmt; + o_str->data = (const byte *)fmt; } else { // We have some memory to format the string struct _exc_printer_t exc_pr = {!used_emg_buf, o_str_alloc, 0, o_str_buf}; @@ -482,7 +482,7 @@ bool mp_obj_exception_match(mp_obj_t exc, mp_const_obj_t exc_type) { if (mp_obj_is_native_exception_instance(self_in)) { \ self = MP_OBJ_TO_PTR(self_in); \ } else { \ - self = MP_OBJ_TO_PTR(((mp_obj_instance_t*)MP_OBJ_TO_PTR(self_in))->subobj[0]); \ + self = MP_OBJ_TO_PTR(((mp_obj_instance_t *)MP_OBJ_TO_PTR(self_in))->subobj[0]); \ } void mp_obj_exception_clear_traceback(mp_obj_t self_in) { @@ -504,7 +504,7 @@ void mp_obj_exception_add_traceback(mp_obj_t self_in, qstr file, size_t line, qs #if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF if (mp_emergency_exception_buf_size >= EMG_BUF_TRACEBACK_OFFSET + EMG_BUF_TRACEBACK_SIZE) { // There is room in the emergency buffer for traceback data - size_t *tb = (size_t*)((uint8_t*)MP_STATE_VM(mp_emergency_exception_buf) + size_t *tb = (size_t *)((uint8_t *)MP_STATE_VM(mp_emergency_exception_buf) + EMG_BUF_TRACEBACK_OFFSET); self->traceback_data = tb; self->traceback_alloc = EMG_BUF_TRACEBACK_SIZE / sizeof(size_t); @@ -523,7 +523,7 @@ void mp_obj_exception_add_traceback(mp_obj_t self_in, qstr file, size_t line, qs self->traceback_len = 0; } else if (self->traceback_len + TRACEBACK_ENTRY_LEN > self->traceback_alloc) { #if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF - if (self->traceback_data == (size_t*)MP_STATE_VM(mp_emergency_exception_buf)) { + if (self->traceback_data == (size_t *)MP_STATE_VM(mp_emergency_exception_buf)) { // Can't resize the emergency buffer return; } diff --git a/py/objexcept.h b/py/objexcept.h index 7c30762248..384456bb51 100644 --- a/py/objexcept.h +++ b/py/objexcept.h @@ -41,13 +41,13 @@ void mp_obj_exception_print(const mp_print_t *print, mp_obj_t o_in, mp_print_kin void mp_obj_exception_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest); #define MP_DEFINE_EXCEPTION(exc_name, base_name) \ -const mp_obj_type_t mp_type_ ## exc_name = { \ - { &mp_type_type }, \ - .name = MP_QSTR_ ## exc_name, \ - .print = mp_obj_exception_print, \ - .make_new = mp_obj_exception_make_new, \ - .attr = mp_obj_exception_attr, \ - .parent = &mp_type_ ## base_name, \ -}; + const mp_obj_type_t mp_type_##exc_name = { \ + { &mp_type_type }, \ + .name = MP_QSTR_##exc_name, \ + .print = mp_obj_exception_print, \ + .make_new = mp_obj_exception_make_new, \ + .attr = mp_obj_exception_attr, \ + .parent = &mp_type_##base_name, \ + }; #endif // MICROPY_INCLUDED_PY_OBJEXCEPT_H diff --git a/py/objfloat.c b/py/objfloat.c index 4db1bb89e9..3df54788f7 100644 --- a/py/objfloat.c +++ b/py/objfloat.c @@ -60,17 +60,19 @@ const mp_obj_float_t mp_const_float_pi_obj = {{&mp_type_float}, M_PI}; #if MICROPY_FLOAT_HIGH_QUALITY_HASH // must return actual integer value if it fits in mp_int_t mp_int_t mp_float_hash(mp_float_t src) { -#if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE -typedef uint64_t mp_float_uint_t; -#elif MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT -typedef uint32_t mp_float_uint_t; -#endif + #if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE + typedef uint64_t mp_float_uint_t; + #elif MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT + typedef uint32_t mp_float_uint_t; + #endif union { mp_float_t f; #if MP_ENDIANNESS_LITTLE - struct { mp_float_uint_t frc:MP_FLOAT_FRAC_BITS, exp:MP_FLOAT_EXP_BITS, sgn:1; } p; + struct { mp_float_uint_t frc : MP_FLOAT_FRAC_BITS, exp : MP_FLOAT_EXP_BITS, sgn : 1; + } p; #else - struct { mp_float_uint_t sgn:1, exp:MP_FLOAT_EXP_BITS, frc:MP_FLOAT_FRAC_BITS; } p; + struct { mp_float_uint_t sgn : 1, exp : MP_FLOAT_EXP_BITS, frc : MP_FLOAT_FRAC_BITS; + } p; #endif mp_float_uint_t i; } u = {.f = src}; @@ -109,17 +111,17 @@ typedef uint32_t mp_float_uint_t; STATIC void float_print(const mp_print_t *print, mp_obj_t o_in, mp_print_kind_t kind) { (void)kind; mp_float_t o_val = mp_obj_float_get(o_in); -#if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT + #if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT char buf[16]; #if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_C const int precision = 6; #else const int precision = 7; #endif -#else + #else char buf[32]; const int precision = 16; -#endif + #endif mp_format_float(o_val, buf, sizeof(buf), 'g', precision, '\0'); mp_print_str(print, buf); if (strchr(buf, '.') == NULL && strchr(buf, 'e') == NULL && strchr(buf, 'n') == NULL) { @@ -156,10 +158,14 @@ STATIC mp_obj_t float_make_new(const mp_obj_type_t *type_in, size_t n_args, size STATIC mp_obj_t float_unary_op(mp_unary_op_t op, mp_obj_t o_in) { mp_float_t val = mp_obj_float_get(o_in); switch (op) { - case MP_UNARY_OP_BOOL: return mp_obj_new_bool(val != 0); - case MP_UNARY_OP_HASH: return MP_OBJ_NEW_SMALL_INT(mp_float_hash(val)); - case MP_UNARY_OP_POSITIVE: return o_in; - case MP_UNARY_OP_NEGATIVE: return mp_obj_new_float(-val); + case MP_UNARY_OP_BOOL: + return mp_obj_new_bool(val != 0); + case MP_UNARY_OP_HASH: + return MP_OBJ_NEW_SMALL_INT(mp_float_hash(val)); + case MP_UNARY_OP_POSITIVE: + return o_in; + case MP_UNARY_OP_NEGATIVE: + return mp_obj_new_float(-val); case MP_UNARY_OP_ABS: { if (signbit(val)) { return mp_obj_new_float(-val); @@ -167,17 +173,18 @@ STATIC mp_obj_t float_unary_op(mp_unary_op_t op, mp_obj_t o_in) { return o_in; } } - default: return MP_OBJ_NULL; // op not supported + default: + return MP_OBJ_NULL; // op not supported } } STATIC mp_obj_t float_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_in) { mp_float_t lhs_val = mp_obj_float_get(lhs_in); -#if MICROPY_PY_BUILTINS_COMPLEX + #if MICROPY_PY_BUILTINS_COMPLEX if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_complex)) { return mp_obj_complex_binary_op(op, lhs_val, 0, rhs_in); } else -#endif + #endif { return mp_obj_float_binary_op(op, lhs_val, rhs_in); } @@ -252,15 +259,21 @@ mp_obj_t mp_obj_float_binary_op(mp_binary_op_t op, mp_float_t lhs_val, mp_obj_t switch (op) { case MP_BINARY_OP_ADD: - case MP_BINARY_OP_INPLACE_ADD: lhs_val += rhs_val; break; + 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_INPLACE_SUBTRACT: + lhs_val -= rhs_val; + break; case MP_BINARY_OP_MULTIPLY: - case MP_BINARY_OP_INPLACE_MULTIPLY: lhs_val *= rhs_val; break; + case MP_BINARY_OP_INPLACE_MULTIPLY: + lhs_val *= rhs_val; + break; case MP_BINARY_OP_FLOOR_DIVIDE: case MP_BINARY_OP_INPLACE_FLOOR_DIVIDE: if (rhs_val == 0) { - zero_division_error: + zero_division_error: mp_raise_msg(&mp_type_ZeroDivisionError, "divide by zero"); } // Python specs require that x == (x//y)*y + (x%y) so we must @@ -315,11 +328,16 @@ mp_obj_t mp_obj_float_binary_op(mp_binary_op_t op, mp_float_t lhs_val, mp_obj_t }; return mp_obj_new_tuple(2, 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_EQUAL: 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_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_EQUAL: + 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: return MP_OBJ_NULL; // op not supported diff --git a/py/objfun.c b/py/objfun.c index a05d446328..4c82d8b7b2 100644 --- a/py/objfun.c +++ b/py/objfun.c @@ -203,7 +203,7 @@ STATIC void dump_args(const mp_obj_t *a, size_t sz) { \ /* state size in bytes */ \ state_size_out_var = n_state_out_var * sizeof(mp_obj_t) \ - + n_exc_stack * sizeof(mp_exc_stack_t); \ + + n_exc_stack * sizeof(mp_exc_stack_t); \ } #define INIT_CODESTATE(code_state, _fun_bc, n_args, n_kw, args) \ @@ -358,14 +358,14 @@ void mp_obj_fun_bc_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) { const mp_obj_type_t mp_type_fun_bc = { { &mp_type_type }, .name = MP_QSTR_function, -#if MICROPY_CPYTHON_COMPAT + #if MICROPY_CPYTHON_COMPAT .print = fun_bc_print, -#endif + #endif .call = fun_bc_call, .unary_op = mp_generic_unary_op, -#if MICROPY_PY_FUNCTION_ATTRS + #if MICROPY_PY_FUNCTION_ATTRS .attr = mp_obj_fun_bc_attr, -#endif + #endif }; mp_obj_t mp_obj_new_fun_bc(mp_obj_t def_args_in, mp_obj_t def_kw_args, const byte *code, const mp_uint_t *const_table) { @@ -402,7 +402,7 @@ mp_obj_t mp_obj_new_fun_bc(mp_obj_t def_args_in, mp_obj_t def_kw_args, const byt STATIC mp_obj_t fun_native_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp_obj_t *args) { MP_STACK_CHECK(); mp_obj_fun_bc_t *self = self_in; - mp_call_fun_t fun = MICROPY_MAKE_POINTER_CALLABLE((void*)self->bytecode); + mp_call_fun_t fun = MICROPY_MAKE_POINTER_CALLABLE((void *)self->bytecode); return fun(self_in, n_args, n_kw, args); } @@ -414,7 +414,7 @@ STATIC const mp_obj_type_t mp_type_fun_native = { }; mp_obj_t mp_obj_new_fun_native(mp_obj_t def_args_in, mp_obj_t def_kw_args, const void *fun_data, const mp_uint_t *const_table) { - mp_obj_fun_bc_t *o = mp_obj_new_fun_bc(def_args_in, def_kw_args, (const byte*)fun_data, const_table); + mp_obj_fun_bc_t *o = mp_obj_new_fun_bc(def_args_in, def_kw_args, (const byte *)fun_data, const_table); o->base.type = &mp_type_fun_native; return o; } @@ -459,11 +459,11 @@ STATIC mp_uint_t convert_obj_for_inline_asm(mp_obj_t obj) { } else { mp_obj_type_t *type = mp_obj_get_type(obj); if (0) { -#if MICROPY_PY_BUILTINS_FLOAT + #if MICROPY_PY_BUILTINS_FLOAT } else if (type == &mp_type_float) { // convert float to int (could also pass in float registers) return (mp_int_t)mp_obj_float_get(obj); -#endif + #endif } else if (type == &mp_type_tuple || type == &mp_type_list) { // pointer to start of tuple (could pass length, but then could use len(x) for that) size_t len; @@ -507,7 +507,7 @@ STATIC mp_obj_t fun_asm_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const convert_obj_for_inline_asm(args[1]), convert_obj_for_inline_asm(args[2]), convert_obj_for_inline_asm(args[3]) - ); + ); } return mp_convert_native_to_obj(ret, self->type_sig); diff --git a/py/objgenerator.c b/py/objgenerator.c index 348d2d79df..db90d4915c 100644 --- a/py/objgenerator.c +++ b/py/objgenerator.c @@ -83,7 +83,7 @@ STATIC mp_obj_t native_gen_wrap_call(mp_obj_t self_in, size_t n_args, size_t n_k mp_obj_fun_bc_t *self_fun = MP_OBJ_TO_PTR(self_in); // Determine start of prelude, and extract n_state from it - uintptr_t prelude_offset = ((uintptr_t*)self_fun->bytecode)[0]; + uintptr_t prelude_offset = ((uintptr_t *)self_fun->bytecode)[0]; size_t n_state = mp_decode_uint_value(self_fun->bytecode + prelude_offset); size_t n_exc_stack = 0; @@ -95,15 +95,15 @@ STATIC mp_obj_t native_gen_wrap_call(mp_obj_t self_in, size_t n_args, size_t n_k // Parse the input arguments and set up the code state o->globals = self_fun->globals; o->code_state.fun_bc = self_fun; - o->code_state.ip = (const byte*)prelude_offset; + o->code_state.ip = (const byte *)prelude_offset; mp_setup_code_state(&o->code_state, n_args, n_kw, args); // Indicate we are a native function, which doesn't use this variable o->code_state.exc_sp = NULL; // Prepare the generator instance for execution - uintptr_t start_offset = ((uintptr_t*)self_fun->bytecode)[1]; - o->code_state.ip = MICROPY_MAKE_POINTER_CALLABLE((void*)(self_fun->bytecode + start_offset)); + uintptr_t start_offset = ((uintptr_t *)self_fun->bytecode)[1]; + o->code_state.ip = MICROPY_MAKE_POINTER_CALLABLE((void *)(self_fun->bytecode + start_offset)); return MP_OBJ_FROM_PTR(o); } @@ -171,9 +171,9 @@ mp_vm_return_kind_t mp_obj_gen_resume(mp_obj_t self_in, mp_obj_t send_value, mp_ #if MICROPY_EMIT_NATIVE if (self->code_state.exc_sp == NULL) { // A native generator, with entry point 2 words into the "bytecode" pointer - typedef uintptr_t (*mp_fun_native_gen_t)(void*, mp_obj_t); - mp_fun_native_gen_t fun = MICROPY_MAKE_POINTER_CALLABLE((const void*)(self->code_state.fun_bc->bytecode + 2 * sizeof(uintptr_t))); - ret_kind = fun((void*)&self->code_state, throw_value); + typedef uintptr_t (*mp_fun_native_gen_t)(void *, mp_obj_t); + mp_fun_native_gen_t fun = MICROPY_MAKE_POINTER_CALLABLE((const void *)(self->code_state.fun_bc->bytecode + 2 * sizeof(uintptr_t))); + ret_kind = fun((void *)&self->code_state, throw_value); } else #endif { @@ -315,5 +315,5 @@ const mp_obj_type_t mp_type_gen_instance = { .unary_op = mp_generic_unary_op, .getiter = mp_identity_getiter, .iternext = gen_instance_iternext, - .locals_dict = (mp_obj_dict_t*)&gen_instance_locals_dict, + .locals_dict = (mp_obj_dict_t *)&gen_instance_locals_dict, }; diff --git a/py/objgetitemiter.c b/py/objgetitemiter.c index ec41c2c5b1..54e27b8f11 100644 --- a/py/objgetitemiter.c +++ b/py/objgetitemiter.c @@ -46,7 +46,7 @@ STATIC mp_obj_t it_iternext(mp_obj_t self_in) { return value; } else { // an exception was raised - mp_obj_type_t *t = (mp_obj_type_t*)((mp_obj_base_t*)nlr.ret_val)->type; + 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 instead of raising return MP_OBJ_STOP_ITERATION; @@ -67,7 +67,7 @@ STATIC const mp_obj_type_t it_type = { // 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; + mp_obj_getitem_iter_t *o = (mp_obj_getitem_iter_t *)iter_buf; o->base.type = &it_type; o->args[0] = args[0]; o->args[1] = args[1]; diff --git a/py/objint.c b/py/objint.c index d5d74dd558..d83803572c 100644 --- a/py/objint.c +++ b/py/objint.c @@ -57,10 +57,10 @@ STATIC mp_obj_t mp_obj_int_make_new(const mp_obj_type_t *type_in, size_t n_args, 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 + #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 + #endif } else { return mp_unary_op(MP_UNARY_OP_INT, args[0]); } @@ -86,26 +86,26 @@ typedef enum { 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 + #if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT uint32_t i; -#elif MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE + #elif MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE uint32_t i[2]; -#endif + #endif } u = {val}; uint32_t e; -#if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT + #if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT e = u.i; -#elif MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE + #elif MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE e = u.i[MP_ENDIANNESS_LITTLE]; -#endif + #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 + #if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE e |= u.i[MP_ENDIANNESS_BIG] != 0; -#endif + #endif if ((e & ~(1 << MP_FLOAT_SIGN_SHIFT_I32)) == 0) { // handle case of -0 (when sign is set but rest of bits are zero) e = 0; @@ -120,16 +120,16 @@ STATIC mp_fp_as_int_class_t mp_classify_fp_as_int(mp_float_t val) { 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 MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_LONGLONG if (e <= (((sizeof(long long) * 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 + #endif + #if MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_MPZ return MP_FP_CLASS_FIT_LONGINT; -#else + #else return MP_FP_CLASS_OVERFLOW; -#endif + #endif } #undef MP_FLOAT_SIGN_SHIFT_I32 #undef MP_FLOAT_EXP_SHIFT_I32 @@ -218,7 +218,7 @@ size_t mp_int_format_size(size_t num_bits, int base, const char *prefix, char co // 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) { + 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. @@ -392,7 +392,7 @@ STATIC mp_obj_t int_from_bytes(size_t n_args, const mp_obj_t *args) { mp_buffer_info_t bufinfo; mp_get_buffer_raise(args[1], &bufinfo, MP_BUFFER_READ); - const byte* buf = (const byte*)bufinfo.buf; + const byte *buf = (const byte *)bufinfo.buf; int delta = 1; if (args[2] == MP_OBJ_NEW_QSTR(MP_QSTR_little)) { buf += bufinfo.len - 1; @@ -428,7 +428,7 @@ STATIC mp_obj_t int_to_bytes(size_t n_args, const mp_obj_t *args) { vstr_t vstr; vstr_init_len(&vstr, len); - byte *data = (byte*)vstr.buf; + byte *data = (byte *)vstr.buf; memset(data, 0, len); #if MICROPY_LONGINT_IMPL != MICROPY_LONGINT_IMPL_NONE @@ -460,5 +460,5 @@ const mp_obj_type_t mp_type_int = { .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, + .locals_dict = (mp_obj_dict_t *)&int_locals_dict, }; diff --git a/py/objint.h b/py/objint.h index 4b95acde9f..c4752384e0 100644 --- a/py/objint.h +++ b/py/objint.h @@ -31,11 +31,11 @@ typedef struct _mp_obj_int_t { mp_obj_base_t base; -#if MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_LONGLONG + #if MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_LONGLONG mp_longint_impl_t val; -#elif MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_MPZ + #elif MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_MPZ mpz_t mpz; -#endif + #endif } mp_obj_int_t; extern const mp_obj_int_t mp_maxsize_obj; @@ -50,9 +50,9 @@ 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); + 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); + 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); diff --git a/py/objint_longlong.c b/py/objint_longlong.c index 485803cfc5..fc61a0c8c0 100644 --- a/py/objint_longlong.c +++ b/py/objint_longlong.c @@ -95,15 +95,20 @@ 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_int_t *o = o_in; switch (op) { - case MP_UNARY_OP_BOOL: return mp_obj_new_bool(o->val != 0); + 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_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_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) { @@ -114,7 +119,8 @@ mp_obj_t mp_obj_int_unary_op(mp_unary_op_t op, mp_obj_t o_in) { self->val = -self->val; return MP_OBJ_FROM_PTR(self); } - default: return MP_OBJ_NULL; // op not supported + default: + return MP_OBJ_NULL; // op not supported } } @@ -126,13 +132,13 @@ mp_obj_t mp_obj_int_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_i 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; + 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; + 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); diff --git a/py/objint_mpz.c b/py/objint_mpz.c index e59c123ed0..f3bfc29b1c 100644 --- a/py/objint_mpz.c +++ b/py/objint_mpz.c @@ -46,27 +46,27 @@ 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 +#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 + (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 + (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 + (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 }; const mp_obj_int_t mp_maxsize_obj = { {&mp_type_int}, - {.fixed_dig = 1, .len = NUM_DIG, .alloc = NUM_DIG, .dig = (mpz_dig_t*)maxsize_dig} + {.fixed_dig = 1, .len = NUM_DIG, .alloc = NUM_DIG, .dig = (mpz_dig_t *)maxsize_dig} }; #undef DIG_MASK #undef NUM_DIG @@ -89,7 +89,7 @@ mp_obj_int_t *mp_obj_int_new_mpz(void) { // // 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) { + 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); @@ -142,11 +142,20 @@ 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_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_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) { @@ -156,7 +165,8 @@ mp_obj_t mp_obj_int_unary_op(mp_unary_op_t op, mp_obj_t o_in) { mpz_abs_inpl(&self2->mpz, &self->mpz); return MP_OBJ_FROM_PTR(self2); } - default: return MP_OBJ_NULL; // op not supported + default: + return MP_OBJ_NULL; // op not supported } } @@ -172,7 +182,7 @@ mp_obj_t mp_obj_int_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_i 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; + 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) @@ -180,22 +190,22 @@ mp_obj_t mp_obj_int_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_i 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 + 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); -#if MICROPY_PY_BUILTINS_COMPLEX + #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 -#endif + #endif + #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 (0) { -#if MICROPY_PY_BUILTINS_FLOAT + #if MICROPY_PY_BUILTINS_FLOAT } else if (op == MP_BINARY_OP_TRUE_DIVIDE || op == MP_BINARY_OP_INPLACE_TRUE_DIVIDE) { if (mpz_is_zero(zrhs)) { goto zero_division_error; @@ -203,7 +213,7 @@ mp_obj_t mp_obj_int_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_i mp_float_t flhs = mpz_as_float(zlhs); mp_float_t frhs = mpz_as_float(zrhs); return mp_obj_new_float(flhs / frhs); -#endif + #endif } else if (op >= MP_BINARY_OP_INPLACE_OR && op < MP_BINARY_OP_CONTAINS) { mp_obj_int_t *res = mp_obj_int_new_mpz(); @@ -224,10 +234,11 @@ mp_obj_t mp_obj_int_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_i case MP_BINARY_OP_FLOOR_DIVIDE: case MP_BINARY_OP_INPLACE_FLOOR_DIVIDE: { if (mpz_is_zero(zrhs)) { - zero_division_error: + zero_division_error: mp_raise_msg(&mp_type_ZeroDivisionError, "divide by zero"); } - mpz_t rem; mpz_init_zero(&rem); + mpz_t rem; + mpz_init_zero(&rem); mpz_divmod_inpl(&res->mpz, &rem, zlhs, zrhs); mpz_deinit(&rem); break; @@ -237,7 +248,8 @@ mp_obj_t mp_obj_int_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_i if (mpz_is_zero(zrhs)) { goto zero_division_error; } - mpz_t quo; mpz_init_zero(&quo); + mpz_t quo; + mpz_init_zero(&quo); mpz_divmod_inpl(&quo, &res->mpz, zlhs, zrhs); mpz_deinit(&quo); break; @@ -334,7 +346,7 @@ mp_obj_t mp_obj_int_pow3(mp_obj_t base, mp_obj_t exponent, mp_obj_t modulus) { mp_raise_TypeError("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); + 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); @@ -343,9 +355,15 @@ mp_obj_t mp_obj_int_pow3(mp_obj_t base, mp_obj_t exponent, mp_obj_t modulus) { 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); } + if (lhs == &l_temp) { + mpz_deinit(lhs); + } + if (rhs == &r_temp) { + mpz_deinit(rhs); + } + if (mod == &m_temp) { + mpz_deinit(mod); + } return result; } } diff --git a/py/objlist.c b/py/objlist.c index 1a18f937d6..c0af02d102 100644 --- a/py/objlist.c +++ b/py/objlist.c @@ -88,15 +88,18 @@ STATIC mp_obj_t list_make_new(const mp_obj_type_t *type_in, size_t n_args, size_ 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); + 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 + default: + return MP_OBJ_NULL; // op not supported } } @@ -153,7 +156,7 @@ STATIC mp_obj_t list_binary_op(mp_binary_op_t op, mp_obj_t lhs, mp_obj_t rhs) { 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 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; @@ -162,22 +165,22 @@ STATIC mp_obj_t list_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) { } mp_int_t len_adj = slice.start - slice.stop; - //printf("Len adj: %d\n", len_adj); + // printf("Len adj: %d\n", len_adj); 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)); + 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 + #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 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)) { @@ -187,21 +190,22 @@ STATIC mp_obj_t list_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) { mp_seq_copy(res->items, self->items + slice.start, res->len, mp_obj_t); return MP_OBJ_FROM_PTR(res); } -#endif + #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 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; + 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); - //printf("Len adj: %d\n", len_adj); + // printf("Len adj: %d\n", len_adj); if (len_adj > 0) { if (self->len + len_adj > self->alloc) { // TODO: Might optimize memory copies here by checking if block can @@ -221,7 +225,7 @@ STATIC mp_obj_t list_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) { self->len += len_adj; return mp_const_none; } -#endif + #endif mp_obj_list_store(self_in, index, value); return mp_const_none; } @@ -277,7 +281,7 @@ STATIC mp_obj_t list_pop(size_t n_args, const mp_obj_t *args) { // 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->items = m_renew(mp_obj_t, self->items, self->alloc, self->alloc / 2); self->alloc /= 2; } return ret; @@ -290,9 +294,13 @@ STATIC void mp_quicksort(mp_obj_t *head, mp_obj_t *tail, mp_obj_t key_fn, mp_obj 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; + 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; @@ -323,15 +331,15 @@ mp_obj_t mp_obj_list_sort(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_ 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_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); + 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; @@ -371,19 +379,19 @@ STATIC mp_obj_t list_insert(mp_obj_t self_in, mp_obj_t idx, mp_obj_t obj) { // insert has its own strange index logic mp_int_t index = MP_OBJ_SMALL_INT_VALUE(idx); if (index < 0) { - index += self->len; + index += self->len; } if (index < 0) { - index = 0; + index = 0; } if ((size_t)index > self->len) { - 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]; + for (mp_int_t i = self->len - 1; i > index; i--) { + self->items[i] = self->items[i - 1]; } self->items[index] = obj; @@ -404,10 +412,10 @@ STATIC mp_obj_t list_reverse(mp_obj_t self_in) { 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; + 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; @@ -450,7 +458,7 @@ const mp_obj_type_t mp_type_list = { .binary_op = list_binary_op, .subscr = list_subscr, .getiter = list_getiter, - .locals_dict = (mp_obj_dict_t*)&list_locals_dict, + .locals_dict = (mp_obj_dict_t *)&list_locals_dict, }; void mp_obj_list_init(mp_obj_list_t *o, size_t n) { @@ -520,7 +528,7 @@ STATIC mp_obj_t list_it_iternext(mp_obj_t self_in) { 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; + 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; diff --git a/py/objmodule.c b/py/objmodule.c index 3a00b7ddc1..69fb1a16d3 100644 --- a/py/objmodule.c +++ b/py/objmodule.c @@ -41,7 +41,7 @@ STATIC void module_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kin module_name = mp_obj_str_get_str(elem->value); } -#if MICROPY_PY___FILE__ + #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); @@ -49,7 +49,7 @@ STATIC void module_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kin mp_printf(print, "", module_name, mp_obj_str_get_str(elem->value)); return; } -#endif + #endif mp_printf(print, "", module_name); } @@ -136,93 +136,93 @@ STATIC const mp_rom_map_elem_t mp_builtin_module_table[] = { { 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_ARRAY + #if MICROPY_PY_ARRAY { MP_ROM_QSTR(MP_QSTR_array), MP_ROM_PTR(&mp_module_array) }, -#endif -#if MICROPY_PY_IO + #endif + #if MICROPY_PY_IO { MP_ROM_QSTR(MP_QSTR_uio), MP_ROM_PTR(&mp_module_io) }, -#endif -#if MICROPY_PY_COLLECTIONS + #endif + #if MICROPY_PY_COLLECTIONS { MP_ROM_QSTR(MP_QSTR_ucollections), MP_ROM_PTR(&mp_module_collections) }, -#endif -#if MICROPY_PY_STRUCT + #endif + #if MICROPY_PY_STRUCT { MP_ROM_QSTR(MP_QSTR_ustruct), MP_ROM_PTR(&mp_module_ustruct) }, -#endif + #endif -#if MICROPY_PY_BUILTINS_FLOAT -#if MICROPY_PY_MATH + #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 + #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 + #endif + #endif + #if MICROPY_PY_SYS { MP_ROM_QSTR(MP_QSTR_sys), MP_ROM_PTR(&mp_module_sys) }, -#endif -#if MICROPY_PY_GC && MICROPY_ENABLE_GC + #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 + #endif + #if MICROPY_PY_THREAD { MP_ROM_QSTR(MP_QSTR__thread), MP_ROM_PTR(&mp_module_thread) }, -#endif + #endif // extmod modules -#if MICROPY_PY_UERRNO + #if MICROPY_PY_UERRNO { MP_ROM_QSTR(MP_QSTR_uerrno), MP_ROM_PTR(&mp_module_uerrno) }, -#endif -#if MICROPY_PY_UCTYPES + #endif + #if MICROPY_PY_UCTYPES { MP_ROM_QSTR(MP_QSTR_uctypes), MP_ROM_PTR(&mp_module_uctypes) }, -#endif -#if MICROPY_PY_UZLIB + #endif + #if MICROPY_PY_UZLIB { MP_ROM_QSTR(MP_QSTR_uzlib), MP_ROM_PTR(&mp_module_uzlib) }, -#endif -#if MICROPY_PY_UJSON + #endif + #if MICROPY_PY_UJSON { MP_ROM_QSTR(MP_QSTR_ujson), MP_ROM_PTR(&mp_module_ujson) }, -#endif -#if MICROPY_PY_URE + #endif + #if MICROPY_PY_URE { MP_ROM_QSTR(MP_QSTR_ure), MP_ROM_PTR(&mp_module_ure) }, -#endif -#if MICROPY_PY_UHEAPQ + #endif + #if MICROPY_PY_UHEAPQ { MP_ROM_QSTR(MP_QSTR_uheapq), MP_ROM_PTR(&mp_module_uheapq) }, -#endif -#if MICROPY_PY_UTIMEQ + #endif + #if MICROPY_PY_UTIMEQ { MP_ROM_QSTR(MP_QSTR_utimeq), MP_ROM_PTR(&mp_module_utimeq) }, -#endif -#if MICROPY_PY_UHASHLIB + #endif + #if MICROPY_PY_UHASHLIB { MP_ROM_QSTR(MP_QSTR_uhashlib), MP_ROM_PTR(&mp_module_uhashlib) }, -#endif -#if MICROPY_PY_UCRYPTOLIB + #endif + #if MICROPY_PY_UCRYPTOLIB { MP_ROM_QSTR(MP_QSTR_ucryptolib), MP_ROM_PTR(&mp_module_ucryptolib) }, -#endif -#if MICROPY_PY_UBINASCII + #endif + #if MICROPY_PY_UBINASCII { MP_ROM_QSTR(MP_QSTR_ubinascii), MP_ROM_PTR(&mp_module_ubinascii) }, -#endif -#if MICROPY_PY_URANDOM + #endif + #if MICROPY_PY_URANDOM { MP_ROM_QSTR(MP_QSTR_urandom), MP_ROM_PTR(&mp_module_urandom) }, -#endif -#if MICROPY_PY_USELECT + #endif + #if MICROPY_PY_USELECT { MP_ROM_QSTR(MP_QSTR_uselect), MP_ROM_PTR(&mp_module_uselect) }, -#endif -#if MICROPY_PY_USSL + #endif + #if MICROPY_PY_USSL { MP_ROM_QSTR(MP_QSTR_ussl), MP_ROM_PTR(&mp_module_ussl) }, -#endif -#if MICROPY_PY_LWIP + #endif + #if MICROPY_PY_LWIP { MP_ROM_QSTR(MP_QSTR_lwip), MP_ROM_PTR(&mp_module_lwip) }, -#endif -#if MICROPY_PY_WEBSOCKET + #endif + #if MICROPY_PY_WEBSOCKET { MP_ROM_QSTR(MP_QSTR_websocket), MP_ROM_PTR(&mp_module_websocket) }, -#endif -#if MICROPY_PY_WEBREPL + #endif + #if MICROPY_PY_WEBREPL { MP_ROM_QSTR(MP_QSTR__webrepl), MP_ROM_PTR(&mp_module_webrepl) }, -#endif -#if MICROPY_PY_FRAMEBUF + #endif + #if MICROPY_PY_FRAMEBUF { MP_ROM_QSTR(MP_QSTR_framebuf), MP_ROM_PTR(&mp_module_framebuf) }, -#endif -#if MICROPY_PY_BTREE + #endif + #if MICROPY_PY_BTREE { MP_ROM_QSTR(MP_QSTR_btree), MP_ROM_PTR(&mp_module_btree) }, -#endif + #endif // extra builtin modules as defined by a port MICROPY_PORT_BUILTIN_MODULES @@ -246,7 +246,7 @@ mp_obj_t mp_module_get(qstr module_name) { 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); + 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; } diff --git a/py/objnamedtuple.c b/py/objnamedtuple.c index e7de899cf9..0d79a7c887 100644 --- a/py/objnamedtuple.c +++ b/py/objnamedtuple.c @@ -46,9 +46,9 @@ size_t mp_obj_namedtuple_find_field(const mp_obj_namedtuple_type_t *type, qstr n #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; + 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 + // 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; @@ -64,7 +64,7 @@ STATIC void namedtuple_print(const mp_print_t *print, mp_obj_t o_in, mp_print_ki (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; + const qstr *fields = ((mp_obj_namedtuple_type_t *)o->tuple.base.type)->fields; mp_obj_attrtuple_print_helper(print, fields, &o->tuple); } @@ -79,7 +79,7 @@ STATIC void namedtuple_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) { return; } #endif - size_t id = mp_obj_namedtuple_find_field((mp_obj_namedtuple_type_t*)self->tuple.base.type, attr); + size_t id = mp_obj_namedtuple_find_field((mp_obj_namedtuple_type_t *)self->tuple.base.type, attr); if (id == (size_t)-1) { return; } @@ -92,7 +92,7 @@ STATIC void namedtuple_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) { } 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; + 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) { diff --git a/py/objobject.c b/py/objobject.c index 265fcfbf2b..7b5c5962bd 100644 --- a/py/objobject.c +++ b/py/objobject.c @@ -49,7 +49,7 @@ STATIC mp_obj_t object___init__(mp_obj_t self) { 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))) { + 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("__new__ arg must be a user-type"); } // This executes only "__new__" part of instance creation. @@ -79,6 +79,6 @@ const mp_obj_type_t mp_type_object = { .name = MP_QSTR_object, .make_new = object_make_new, #if MICROPY_CPYTHON_COMPAT - .locals_dict = (mp_obj_dict_t*)&object_locals_dict, + .locals_dict = (mp_obj_dict_t *)&object_locals_dict, #endif }; diff --git a/py/objproperty.c b/py/objproperty.c index b66d24a119..097f98a2fe 100644 --- a/py/objproperty.c +++ b/py/objproperty.c @@ -58,7 +58,7 @@ STATIC mp_obj_t property_make_new(const mp_obj_type_t *type, size_t n_args, size 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 = *(mp_obj_property_t *)MP_OBJ_TO_PTR(self_in); p2->proxy[0] = getter; return MP_OBJ_FROM_PTR(p2); } @@ -67,7 +67,7 @@ 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 = *(mp_obj_property_t *)MP_OBJ_TO_PTR(self_in); p2->proxy[1] = setter; return MP_OBJ_FROM_PTR(p2); } @@ -76,7 +76,7 @@ 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 = *(mp_obj_property_t *)MP_OBJ_TO_PTR(self_in); p2->proxy[2] = deleter; return MP_OBJ_FROM_PTR(p2); } @@ -95,7 +95,7 @@ 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, + .locals_dict = (mp_obj_dict_t *)&property_locals_dict, }; const mp_obj_t *mp_obj_property_get(mp_obj_t self_in) { diff --git a/py/objrange.c b/py/objrange.c index 86aa0ccfe6..da8a1e6ec8 100644 --- a/py/objrange.c +++ b/py/objrange.c @@ -59,7 +59,7 @@ STATIC const mp_obj_type_t range_it_type = { 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; + mp_obj_range_it_t *o = (mp_obj_range_it_t *)iter_buf; o->base.type = &range_it_type; o->cur = cur; o->stop = stop; @@ -132,9 +132,12 @@ 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 + 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 } } @@ -152,7 +155,7 @@ STATIC mp_obj_t range_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs && (lhs_len == 0 || (lhs->start == rhs->start && (lhs_len == 1 || lhs->step == rhs->step))) - ); + ); } #endif @@ -161,7 +164,7 @@ STATIC mp_obj_t range_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) { // 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 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); @@ -176,7 +179,7 @@ STATIC mp_obj_t range_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) { } return MP_OBJ_FROM_PTR(o); } -#endif + #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 { @@ -218,7 +221,7 @@ const mp_obj_type_t mp_type_range = { #endif .subscr = range_subscr, .getiter = range_getiter, -#if MICROPY_PY_BUILTINS_RANGE_ATTRS + #if MICROPY_PY_BUILTINS_RANGE_ATTRS .attr = range_attr, -#endif + #endif }; diff --git a/py/objset.c b/py/objset.c index 799ba9df04..568be7bc11 100644 --- a/py/objset.c +++ b/py/objset.c @@ -49,9 +49,9 @@ STATIC mp_obj_t set_it_iternext(mp_obj_t self_in); 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 + #if MICROPY_PY_BUILTINS_FROZENSET + || MP_OBJ_IS_TYPE(o, &mp_type_frozenset) + #endif ; } @@ -123,7 +123,7 @@ STATIC mp_obj_t set_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_ mp_obj_set_store(set, item); } // Set actual set/frozenset type - ((mp_obj_set_t*)MP_OBJ_TO_PTR(set))->base.type = type; + ((mp_obj_set_t *)MP_OBJ_TO_PTR(set))->base.type = type; return set; } } @@ -146,7 +146,7 @@ STATIC mp_obj_t set_it_iternext(mp_obj_t self_in) { 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; + 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); @@ -210,7 +210,7 @@ STATIC mp_obj_t set_diff_int(size_t n_args, const mp_obj_t *args, bool update) { if (self == other) { set_clear(self); } else { - mp_set_t *self_set = &((mp_obj_set_t*)MP_OBJ_TO_PTR(self))->set; + 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) { @@ -430,9 +430,11 @@ 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_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 @@ -447,8 +449,9 @@ STATIC mp_obj_t set_unary_op(mp_unary_op_t op, mp_obj_t self_in) { } return MP_OBJ_NEW_SMALL_INT(hash); } -#endif - default: return MP_OBJ_NULL; // op not supported + #endif + default: + return MP_OBJ_NULL; // op not supported } } @@ -550,7 +553,7 @@ const mp_obj_type_t mp_type_set = { .unary_op = set_unary_op, .binary_op = set_binary_op, .getiter = set_getiter, - .locals_dict = (mp_obj_dict_t*)&set_locals_dict, + .locals_dict = (mp_obj_dict_t *)&set_locals_dict, }; #if MICROPY_PY_BUILTINS_FROZENSET @@ -575,7 +578,7 @@ const mp_obj_type_t mp_type_frozenset = { .unary_op = set_unary_op, .binary_op = set_binary_op, .getiter = set_getiter, - .locals_dict = (mp_obj_dict_t*)&frozenset_locals_dict, + .locals_dict = (mp_obj_dict_t *)&frozenset_locals_dict, }; #endif diff --git a/py/objslice.c b/py/objslice.c index e50aa07897..0a6bb401b2 100644 --- a/py/objslice.c +++ b/py/objslice.c @@ -74,9 +74,9 @@ const mp_obj_type_t mp_type_slice = { { &mp_type_type }, .name = MP_QSTR_slice, .print = slice_print, -#if MICROPY_PY_BUILTINS_SLICE_ATTRS + #if MICROPY_PY_BUILTINS_SLICE_ATTRS .attr = slice_attr, -#endif + #endif }; mp_obj_t mp_obj_new_slice(mp_obj_t ostart, mp_obj_t ostop, mp_obj_t ostep) { diff --git a/py/objstr.c b/py/objstr.c index 1b12147fdd..66f8e8463a 100644 --- a/py/objstr.c +++ b/py/objstr.c @@ -133,11 +133,11 @@ STATIC void str_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t } 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 MICROPY_CPYTHON_COMPAT if (n_kw != 0) { mp_arg_error_unimpl_kw(); } -#endif + #endif mp_arg_check_num(n_args, n_kw, 0, 3, false); @@ -168,7 +168,7 @@ mp_obj_t mp_obj_str_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_ #endif // Check if a qstr with this data already exists - qstr q = qstr_find_strn((const char*)str_data, str_len); + qstr q = qstr_find_strn((const char *)str_data, str_len); if (q != MP_QSTR_NULL) { return MP_OBJ_NEW_QSTR(q); } @@ -284,11 +284,11 @@ const byte *find_subbytes(const byte *haystack, size_t hlen, const byte *needle, } for (;;) { if (memcmp(&haystack[str_index], needle, nlen) == 0) { - //found + // found return haystack + str_index; } if (str_index == str_index_end) { - //not found + // not found break; } str_index += direction; @@ -396,7 +396,7 @@ mp_obj_t mp_obj_str_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_i 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_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: @@ -412,7 +412,7 @@ mp_obj_t mp_obj_str_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_i #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) { + 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; } @@ -424,7 +424,7 @@ STATIC mp_obj_t bytes_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) { GET_STR_DATA_LEN(self_in, self_data, self_len); if (value == MP_OBJ_SENTINEL) { // load -#if MICROPY_PY_BUILTINS_SLICE + #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)) { @@ -432,13 +432,13 @@ STATIC mp_obj_t bytes_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) { } return mp_obj_new_str_of_type(type, self_data + slice.start, slice.stop - slice.start); } -#endif + #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); + return mp_obj_new_str_via_qstr((char *)&self_data[index_val], 1); } } else { return MP_OBJ_NULL; // op not supported @@ -480,7 +480,7 @@ STATIC mp_obj_t str_join(mp_obj_t self_in, mp_obj_t arg) { // make joined string vstr_t vstr; vstr_init_len(&vstr, required_len); - byte *data = (byte*)vstr.buf; + byte *data = (byte *)vstr.buf; for (size_t i = 0; i < seq_len; i++) { if (i > 0) { memcpy(data, sep_str, sep_len); @@ -515,15 +515,21 @@ mp_obj_t mp_obj_str_split(size_t n_args, const mp_obj_t *args) { // 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 && unichar_isspace(*s)) { + s++; + } while (s < top && splits != 0) { const byte *start = s; - while (s < top && !unichar_isspace(*s)) 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++; + while (s < top && unichar_isspace(*s)) { + s++; + } if (splits > 0) { splits--; } @@ -843,7 +849,7 @@ STATIC mp_obj_t str_uni_strip(int type, size_t n_args, const mp_obj_t *args) { } assert(last_good_char_pos >= first_good_char_pos); - //+1 to accommodate the last character + // +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 @@ -915,19 +921,19 @@ STATIC bool arg_looks_integer(mp_obj_t 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_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 MICROPY_PY_BUILTINS_FLOAT if (mp_obj_is_float(arg)) { return mp_obj_new_int_from_float(mp_obj_float_get(arg)); } -#endif + #endif return arg; } #endif @@ -1065,7 +1071,8 @@ STATIC vstr_t mp_obj_str_format_helper(const char *str, const char *top, int *ar *arg_i = -1; } else { const char *lookup; - for (lookup = field_name; lookup < field_name_top && *lookup != '.' && *lookup != '['; 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); @@ -1210,9 +1217,15 @@ STATIC vstr_t mp_obj_str_format_helper(const char *str, const char *top, int *ar } switch (align) { - case '<': flags |= PF_FLAG_LEFT_ADJUST; break; - case '=': flags |= PF_FLAG_PAD_AFTER_SIGN; break; - case '^': flags |= PF_FLAG_CENTER_ADJUST; break; + 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)) { @@ -1221,8 +1234,7 @@ STATIC vstr_t mp_obj_str_format_helper(const char *str, const char *top, int *ar mp_print_mp_int(&print, arg, 2, 'a', flags, fill, width, 0); continue; - case 'c': - { + case 'c': { char ch = mp_obj_get_int(arg); mp_print_strn(&print, &ch, 1, flags, fill, width); continue; @@ -1308,7 +1320,7 @@ STATIC vstr_t mp_obj_str_format_helper(const char *str, const char *top, int *ar } switch (type) { -#if MICROPY_PY_BUILTINS_FLOAT + #if MICROPY_PY_BUILTINS_FLOAT case 'e': case 'E': case 'f': @@ -1326,9 +1338,9 @@ STATIC vstr_t mp_obj_str_format_helper(const char *str, const char *top, int *ar #define F100 100.0 #endif mp_print_float(&print, mp_obj_get_float(arg) * F100, 'f', flags, fill, width, precision); - #undef F100 +#undef F100 break; -#endif + #endif default: if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) { @@ -1386,7 +1398,7 @@ mp_obj_t mp_obj_str_format(size_t n_args, const mp_obj_t *args, mp_map_t *kwargs 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); + 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); @@ -1434,7 +1446,7 @@ STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, size_t n_args, const mp_obj_ } ++str; } - mp_obj_t k_obj = mp_obj_new_str_via_qstr((const char*)key, str - key); + 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++; } @@ -1443,14 +1455,20 @@ STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, size_t n_args, const mp_obj_ 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') { + 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; + } else { + break; + } str++; } // parse width, if it exists @@ -1463,7 +1481,7 @@ STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, size_t n_args, const mp_obj_ width = mp_obj_get_int(args[arg_i++]); str++; } else { - str = (const byte*)str_to_int((const char*)str, (const char*)top, &width); + str = (const byte *)str_to_int((const char *)str, (const char *)top, &width); } } int prec = -1; @@ -1477,13 +1495,13 @@ STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, size_t n_args, const mp_obj_ str++; } else { prec = 0; - str = (const byte*)str_to_int((const char*)str, (const char*)top, &prec); + str = (const byte *)str_to_int((const char *)str, (const char *)top, &prec); } } } if (str >= top) { -incomplete_format: + incomplete_format: if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) { terse_str_format_value_error(); } else { @@ -1494,7 +1512,7 @@ incomplete_format: // Tuple value lookup if (arg == MP_OBJ_NULL) { if (arg_i >= n_args) { -not_enough_args: + not_enough_args: mp_raise_TypeError("format string needs more arguments"); } arg = args[arg_i++]; @@ -1522,7 +1540,7 @@ not_enough_args: mp_print_mp_int(&print, arg_as_int(arg), 10, 'a', flags, fill, width, prec); break; -#if MICROPY_PY_BUILTINS_FLOAT + #if MICROPY_PY_BUILTINS_FLOAT case 'e': case 'E': case 'f': @@ -1531,7 +1549,7 @@ not_enough_args: case 'G': mp_print_float(&print, mp_obj_get_float(arg), *str, flags, fill, width, prec); break; -#endif + #endif case 'o': if (alt) { @@ -1541,8 +1559,7 @@ not_enough_args: break; case 'r': - case 's': - { + case 's': { vstr_t arg_vstr; mp_print_t arg_print; vstr_init_print(&arg_vstr, 16, &arg_print); @@ -1684,7 +1701,7 @@ STATIC mp_obj_t str_replace(size_t n_args, const mp_obj_t *args) { } else { // substr found, allocate new string vstr_init_len(&vstr, replaced_str_index); - data = (byte*)vstr.buf; + data = (byte *)vstr.buf; assert(data != NULL); } } else { @@ -1799,7 +1816,7 @@ 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; + byte *data = (byte *)vstr.buf; for (size_t i = 0; i < self_len; i++) { *data++ = op(*self_data++); } @@ -1907,7 +1924,7 @@ MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_encode_obj, 1, 3, str_encode); 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->buf = (void *)str_data; bufinfo->len = str_len; bufinfo->typecode = 'B'; // bytes should be unsigned, so should unicode byte-access return 0; @@ -1921,7 +1938,7 @@ mp_int_t mp_obj_str_get_buffer(mp_obj_t self_in, mp_buffer_info_t *bufinfo, mp_u } STATIC const mp_rom_map_elem_t str8_locals_dict_table[] = { -#if MICROPY_CPYTHON_COMPAT + #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 @@ -1931,7 +1948,7 @@ STATIC const mp_rom_map_elem_t str8_locals_dict_table[] = { // methods (which should do type checking at runtime). { MP_ROM_QSTR(MP_QSTR_encode), MP_ROM_PTR(&str_encode_obj) }, #endif -#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) }, @@ -1982,7 +1999,7 @@ const mp_obj_type_t mp_type_str = { .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, + .locals_dict = (mp_obj_dict_t *)&str8_locals_dict, }; #endif @@ -1996,16 +2013,16 @@ const mp_obj_type_t mp_type_bytes = { .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, + .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*)""}; +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_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; @@ -2022,16 +2039,16 @@ mp_obj_t mp_obj_new_str_copy(const mp_obj_type_t *type, const byte* data, size_t // 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) { +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); + 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) { +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)); } @@ -2053,41 +2070,41 @@ mp_obj_t mp_obj_new_str_from_vstr(const mp_obj_type_t *type, vstr_t *vstr) { 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); + o->hash = qstr_compute_hash((byte *)vstr->buf, vstr->len); if (vstr->len + 1 == vstr->alloc) { - o->data = (byte*)vstr->buf; + o->data = (byte *)vstr->buf; } else { - o->data = (byte*)m_renew(char, vstr->buf, vstr->alloc, vstr->len + 1); + o->data = (byte *)m_renew(char, vstr->buf, vstr->alloc, vstr->len + 1); } - ((byte*)o->data)[o->len] = '\0'; // add null byte + ((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) { +mp_obj_t mp_obj_new_str(const char *data, size_t len) { qstr q = qstr_find_strn(data, len); if (q != MP_QSTR_NULL) { // 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); + 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); + 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); + return mp_obj_new_str_via_qstr((const char *)data, len); } -mp_obj_t mp_obj_new_bytes(const byte* data, size_t 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); } @@ -2128,7 +2145,7 @@ qstr mp_obj_str_get_qstr(mp_obj_t 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); + return qstr_from_strn((char *)self->data, self->len); } else { bad_implicit_conversion(self_in); } @@ -2140,7 +2157,7 @@ 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; + return (const char *)s; } else { bad_implicit_conversion(self_in); } @@ -2150,7 +2167,7 @@ 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; + return (const char *)s; } else { bad_implicit_conversion(self_in); } @@ -2161,8 +2178,8 @@ 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*)self_in)->len; - return ((mp_obj_str_t*)self_in)->data; + *len = ((mp_obj_str_t *)self_in)->len; + return ((mp_obj_str_t *)self_in)->data; } } #endif @@ -2182,7 +2199,7 @@ 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); + mp_obj_t o_out = mp_obj_new_str_via_qstr((const char *)str + self->cur, 1); self->cur += 1; return o_out; } else { @@ -2192,7 +2209,7 @@ STATIC mp_obj_t str_it_iternext(mp_obj_t self_in) { 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; + 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; @@ -2215,7 +2232,7 @@ STATIC mp_obj_t bytes_it_iternext(mp_obj_t self_in) { 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; + 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; diff --git a/py/objstr.h b/py/objstr.h index 4e55cad091..eecca52da9 100644 --- a/py/objstr.h +++ b/py/objstr.h @@ -36,18 +36,18 @@ typedef struct _mp_obj_str_t { 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} +#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; } + { 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; } + { 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 @@ -58,21 +58,21 @@ 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) \ 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; } + 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_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); + 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); diff --git a/py/objstringio.c b/py/objstringio.c index b405ee21e3..597f9eb8cd 100644 --- a/py/objstringio.c +++ b/py/objstringio.c @@ -114,7 +114,7 @@ STATIC mp_uint_t stringio_ioctl(mp_obj_t o_in, mp_uint_t request, uintptr_t arg, 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; + struct mp_stream_seek_t *s = (struct mp_stream_seek_t *)arg; mp_uint_t ref = 0; switch (s->whence) { case MP_SEEK_CUR: @@ -166,7 +166,7 @@ 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); + 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); @@ -258,7 +258,7 @@ const mp_obj_type_t mp_type_stringio = { .getiter = mp_identity_getiter, .iternext = mp_stream_unbuffered_iter, .protocol = &stringio_stream_p, - .locals_dict = (mp_obj_dict_t*)&stringio_locals_dict, + .locals_dict = (mp_obj_dict_t *)&stringio_locals_dict, }; #if MICROPY_PY_IO_BYTESIO @@ -270,7 +270,7 @@ const mp_obj_type_t mp_type_bytesio = { .getiter = mp_identity_getiter, .iternext = mp_stream_unbuffered_iter, .protocol = &bytesio_stream_p, - .locals_dict = (mp_obj_dict_t*)&stringio_locals_dict, + .locals_dict = (mp_obj_dict_t *)&stringio_locals_dict, }; #endif diff --git a/py/objstrunicode.c b/py/objstrunicode.c index 13da922a80..63501b5c62 100644 --- a/py/objstrunicode.c +++ b/py/objstrunicode.c @@ -113,7 +113,7 @@ STATIC mp_obj_t uni_unary_op(mp_unary_op_t op, mp_obj_t self_in) { // 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) { + 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) { @@ -132,8 +132,7 @@ const byte *str_index_to_ptr(const mp_obj_type_t *type, const byte *self_data, s nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, "string indices must be integers, not %s", mp_obj_get_type_str(index))); } const byte *s, *top = self_data + self_len; - if (i < 0) - { + 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) { @@ -181,7 +180,7 @@ STATIC mp_obj_t str_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) { GET_STR_DATA_LEN(self_in, self_data, self_len); if (value == MP_OBJ_SENTINEL) { // load -#if MICROPY_PY_BUILTINS_SLICE + #if MICROPY_PY_BUILTINS_SLICE if (MP_OBJ_IS_TYPE(index, &mp_type_slice)) { mp_obj_t ostart, ostop, ostep; mp_obj_slice_get(index, &ostart, &ostop, &ostep); @@ -207,7 +206,7 @@ STATIC mp_obj_t str_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) { } return mp_obj_new_str_of_type(type, (const byte *)pstart, pstop - pstart); } -#endif + #endif const byte *s = str_index_to_ptr(type, self_data, self_len, index, false); int len = 1; if (UTF8_IS_NONASCII(*s)) { @@ -216,16 +215,16 @@ STATIC mp_obj_t str_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) { ++len; } } - return mp_obj_new_str_via_qstr((const char*)s, len); // This will create a one-character string + 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 + #if MICROPY_CPYTHON_COMPAT { 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) }, @@ -274,7 +273,7 @@ const mp_obj_type_t mp_type_str = { .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, + .locals_dict = (mp_obj_dict_t *)&struni_locals_dict, }; /******************************************************************************/ @@ -293,7 +292,7 @@ STATIC mp_obj_t str_it_iternext(mp_obj_t self_in) { 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); + mp_obj_t o_out = mp_obj_new_str_via_qstr((const char *)cur, end - cur); self->cur += end - cur; return o_out; } else { @@ -303,7 +302,7 @@ STATIC mp_obj_t str_it_iternext(mp_obj_t self_in) { 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; + 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; diff --git a/py/objtuple.c b/py/objtuple.c index 34b7664ebb..81b4784994 100644 --- a/py/objtuple.c +++ b/py/objtuple.c @@ -122,7 +122,8 @@ STATIC mp_obj_t tuple_cmp_helper(mp_uint_t op, mp_obj_t self_in, mp_obj_t anothe 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_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; @@ -131,8 +132,10 @@ mp_obj_t mp_obj_tuple_unary_op(mp_unary_op_t op, mp_obj_t self_in) { } 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 + case MP_UNARY_OP_LEN: + return MP_OBJ_NEW_SMALL_INT(self->len); + default: + return MP_OBJ_NULL; // op not supported } } @@ -178,7 +181,7 @@ 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 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)) { @@ -188,7 +191,7 @@ mp_obj_t mp_obj_tuple_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) { mp_seq_copy(res->items, self->items + slice.start, res->len, mp_obj_t); return MP_OBJ_FROM_PTR(res); } -#endif + #endif size_t index_value = mp_get_index(self->base.type, self->len, index, false); return self->items[index_value]; } else { @@ -226,7 +229,7 @@ const mp_obj_type_t mp_type_tuple = { .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, + .locals_dict = (mp_obj_dict_t *)&tuple_locals_dict, }; // the zero-length tuple @@ -283,7 +286,7 @@ STATIC mp_obj_t tuple_it_iternext(mp_obj_t self_in) { 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; + 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); diff --git a/py/objtuple.h b/py/objtuple.h index 74cde88d3d..cc42aa6df3 100644 --- a/py/objtuple.h +++ b/py/objtuple.h @@ -52,7 +52,7 @@ extern const mp_obj_type_t mp_type_attrtuple; const mp_rom_obj_tuple_t tuple_obj_name = { \ .base = {&mp_type_attrtuple}, \ .len = nitems, \ - .items = { __VA_ARGS__ , MP_ROM_PTR((void*)fields) } \ + .items = { __VA_ARGS__, MP_ROM_PTR((void *)fields) } \ } #if MICROPY_PY_COLLECTIONS diff --git a/py/objtype.c b/py/objtype.c index fec73f16ee..190c0a28b0 100644 --- a/py/objtype.c +++ b/py/objtype.c @@ -42,7 +42,7 @@ #endif #define ENABLE_SPECIAL_ACCESSORS \ - (MICROPY_PY_DESCRIPTORS || MICROPY_PY_DELATTR_SETATTR || MICROPY_PY_BUILTINS_PROPERTY) + (MICROPY_PY_DESCRIPTORS || MICROPY_PY_DELATTR_SETATTR || MICROPY_PY_BUILTINS_PROPERTY) #define TYPE_FLAG_IS_SUBCLASSED (0x0001) #define TYPE_FLAG_HAS_SPECIAL_ACCESSORS (0x0002) @@ -66,7 +66,7 @@ STATIC int instance_count_native_bases(const mp_obj_type_t *type, const mp_obj_t // No parents so end search here. return count; #if MICROPY_MULTIPLE_INHERITANCE - } else if (((mp_obj_base_t*)type->parent)->type == &mp_type_tuple) { + } 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; @@ -136,7 +136,7 @@ struct class_lookup_data { bool is_type; }; -STATIC void mp_obj_class_lookup(struct class_lookup_data *lookup, const mp_obj_type_t *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 (;;) { @@ -146,7 +146,7 @@ STATIC void mp_obj_class_lookup(struct class_lookup_data *lookup, const mp_obj_ // 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) { + 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; @@ -163,7 +163,7 @@ STATIC void mp_obj_class_lookup(struct class_lookup_data *lookup, const mp_obj_ 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; + 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; @@ -176,7 +176,7 @@ STATIC void mp_obj_class_lookup(struct class_lookup_data *lookup, const mp_obj_ } mp_convert_member_lookup(obj_obj, type, elem->value, lookup->dest); } -#if DEBUG_PRINT + #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) { @@ -184,7 +184,7 @@ STATIC void mp_obj_class_lookup(struct class_lookup_data *lookup, const mp_obj_ DEBUG_printf(" <%s @%p>", mp_obj_get_type_str(lookup->dest[1]), MP_OBJ_TO_PTR(lookup->dest[1])); } DEBUG_printf("\n"); -#endif + #endif return; } } @@ -205,13 +205,13 @@ STATIC void mp_obj_class_lookup(struct class_lookup_data *lookup, const mp_obj_ 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) { + } 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); + mp_obj_type_t *bt = (mp_obj_type_t *)MP_OBJ_TO_PTR(*item); if (bt == &mp_type_object) { // Not a "real" type continue; @@ -224,7 +224,7 @@ STATIC void mp_obj_class_lookup(struct class_lookup_data *lookup, const mp_obj_ // 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); + type = (mp_obj_type_t *)MP_OBJ_TO_PTR(*item); #endif } else { type = type->parent; @@ -586,7 +586,7 @@ STATIC void mp_obj_instance_load_attr(mp_obj_t self_in, qstr attr, mp_obj_t *des dest[0] = elem->value; return; } -#if MICROPY_CPYTHON_COMPAT + #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__: modifying @@ -601,7 +601,7 @@ STATIC void mp_obj_instance_load_attr(mp_obj_t self_in, qstr attr, mp_obj_t *des dest[0] = attr_dict; return; } -#endif + #endif struct class_lookup_data lookup = { .obj = self, .attr = attr, @@ -1013,7 +1013,7 @@ STATIC void type_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) { } #endif struct class_lookup_data lookup = { - .obj = (mp_obj_instance_t*)self, + .obj = (mp_obj_instance_t *)self, .attr = attr, .meth_offset = 0, .dest = dest, @@ -1119,7 +1119,7 @@ mp_obj_t mp_obj_new_type(qstr name, mp_obj_t bases_tuple, mp_obj_t locals_dict) o->attr = mp_obj_instance_attr; o->subscr = instance_subscr; o->getiter = instance_getiter; - //o->iternext = ; not implemented + // o->iternext = ; not implemented o->buffer_p.get_buffer = instance_get_buffer; if (bases_len > 0) { @@ -1127,7 +1127,7 @@ mp_obj_t mp_obj_new_type(qstr name, mp_obj_t bases_tuple, mp_obj_t locals_dict) // 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; + o->protocol = ((mp_obj_type_t *)MP_OBJ_TO_PTR(bases_items[0]))->protocol; if (bases_len >= 2) { #if MICROPY_MULTIPLE_INHERITANCE @@ -1204,7 +1204,7 @@ STATIC mp_obj_t super_make_new(const mp_obj_type_t *type_in, size_t n_args, size 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]}; + *o = (mp_obj_super_t) {{type_in}, args[0], args[1]}; return MP_OBJ_FROM_PTR(o); } @@ -1237,7 +1237,7 @@ STATIC void super_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) { if (type->parent == NULL) { // no parents, do nothing #if MICROPY_MULTIPLE_INHERITANCE - } else if (((mp_obj_base_t*)type->parent)->type == &mp_type_tuple) { + } 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; @@ -1248,7 +1248,7 @@ STATIC void super_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) { // 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])); + mp_obj_class_lookup(&lookup, (mp_obj_type_t *)MP_OBJ_TO_PTR(items[i])); if (dest[0] != MP_OBJ_NULL) { break; } @@ -1311,7 +1311,7 @@ bool mp_obj_is_subclass_fast(mp_const_obj_t object, mp_const_obj_t classinfo) { // type has no parents return false; #if MICROPY_MULTIPLE_INHERITANCE - } else if (((mp_obj_base_t*)self->parent)->type == &mp_type_tuple) { + } 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; @@ -1375,7 +1375,7 @@ mp_obj_t mp_instance_cast_to_native_base(mp_const_obj_t self_in, mp_const_obj_t if (!mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(self_type), native_type)) { return MP_OBJ_NULL; } - mp_obj_instance_t *self = (mp_obj_instance_t*)MP_OBJ_TO_PTR(self_in); + mp_obj_instance_t *self = (mp_obj_instance_t *)MP_OBJ_TO_PTR(self_in); return self->subobj[0]; } @@ -1388,7 +1388,7 @@ STATIC mp_obj_t static_class_method_make_new(const mp_obj_type_t *self, size_t n 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]}; + *o = (mp_obj_static_class_method_t) {{self}, args[0]}; return MP_OBJ_FROM_PTR(o); } diff --git a/py/parse.c b/py/parse.c index 6c5ebbeaf9..811d195edb 100644 --- a/py/parse.c +++ b/py/parse.c @@ -56,13 +56,13 @@ #define RULE_ARG_OPT_RULE (0x3000) // (un)comment to use rule names; for debugging -//#define USE_RULE_NAME (1) +// #define USE_RULE_NAME (1) 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" + #include "py/grammar.h" #undef DEF_RULE #undef DEF_RULE_NC RULE_const_object, // special node for a constant, generic Python object @@ -70,7 +70,7 @@ enum { // define rules without a compile function #define DEF_RULE(rule, comp, kind, ...) #define DEF_RULE_NC(rule, kind, ...) RULE_##rule, -#include "py/grammar.h" + #include "py/grammar.h" #undef DEF_RULE #undef DEF_RULE_NC }; @@ -87,7 +87,7 @@ STATIC const uint8_t rule_act_table[] = { #define DEF_RULE(rule, comp, kind, ...) kind, #define DEF_RULE_NC(rule, kind, ...) -#include "py/grammar.h" + #include "py/grammar.h" #undef DEF_RULE #undef DEF_RULE_NC @@ -95,7 +95,7 @@ STATIC const uint8_t rule_act_table[] = { #define DEF_RULE(rule, comp, kind, ...) #define DEF_RULE_NC(rule, kind, ...) kind, -#include "py/grammar.h" + #include "py/grammar.h" #undef DEF_RULE #undef DEF_RULE_NC @@ -116,13 +116,13 @@ STATIC const uint16_t rule_arg_combined_table[] = { #define DEF_RULE(rule, comp, kind, ...) __VA_ARGS__, #define DEF_RULE_NC(rule, kind, ...) -#include "py/grammar.h" + #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" + #include "py/grammar.h" #undef DEF_RULE #undef DEF_RULE_NC @@ -142,12 +142,12 @@ STATIC const uint16_t 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" + #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" + #include "py/grammar.h" #undef DEF_RULE #undef DEF_RULE_NC }; @@ -165,13 +165,13 @@ enum { 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" + #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" + #include "py/grammar.h" #undef DEF_RULE #undef DEF_RULE_NC }; @@ -188,20 +188,20 @@ static const size_t FIRST_RULE_WITH_OFFSET_ABOVE_255 = #include "py/grammar.h" #undef DEF_RULE #undef DEF_RULE_NC -0; + 0; #if USE_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" + #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" + #include "py/grammar.h" #undef DEF_RULE #undef DEF_RULE_NC }; @@ -256,7 +256,7 @@ STATIC void *parser_alloc(parser_t *parser, size_t num_bytes) { 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, + 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) { @@ -279,7 +279,7 @@ STATIC void *parser_alloc(parser_t *parser, size_t num_bytes) { if (alloc < num_bytes) { alloc = num_bytes; } - chunk = (mp_parse_chunk_t*)m_new(byte, sizeof(mp_parse_chunk_t) + alloc); + 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; @@ -318,12 +318,12 @@ STATIC uint8_t pop_rule(parser_t *parser, size_t *arg_i, size_t *src_line) { 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); + || (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); + || (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) { @@ -331,7 +331,7 @@ bool mp_parse_node_get_int_maybe(mp_parse_node_t pn, mp_obj_t *o) { *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; + 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); @@ -352,7 +352,7 @@ int mp_parse_node_extract_list(mp_parse_node_t *pn, size_t pn_kind, mp_parse_nod *nodes = pn; return 1; } else { - mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)(*pn); + 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; @@ -366,7 +366,7 @@ int mp_parse_node_extract_list(mp_parse_node_t *pn, size_t pn_kind, mp_parse_nod #if MICROPY_DEBUG_PRINTERS void mp_parse_node_print(mp_parse_node_t pn, size_t indent) { if (MP_PARSE_NODE_IS_STRUCT(pn)) { - printf("[% 4d] ", (int)((mp_parse_node_struct_t*)pn)->source_line); + printf("[% 4d] ", (int)((mp_parse_node_struct_t *)pn)->source_line); } else { printf(" "); } @@ -381,16 +381,23 @@ void mp_parse_node_print(mp_parse_node_t pn, size_t indent) { } 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: printf("id(%s)\n", qstr_str(arg)); break; - case MP_PARSE_NODE_STRING: printf("str(%s)\n", qstr_str(arg)); break; - case MP_PARSE_NODE_BYTES: printf("bytes(%s)\n", qstr_str(arg)); break; + case MP_PARSE_NODE_ID: + printf("id(%s)\n", qstr_str(arg)); + break; + case MP_PARSE_NODE_STRING: + printf("str(%s)\n", qstr_str(arg)); + break; + case MP_PARSE_NODE_BYTES: + printf("bytes(%s)\n", qstr_str(arg)); + break; default: assert(MP_PARSE_NODE_LEAF_KIND(pn) == MP_PARSE_NODE_TOKEN); - printf("tok(%u)\n", (uint)arg); break; + printf("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; + 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 printf("literal const(%016llx)\n", (uint64_t)pns->nodes[0] | ((uint64_t)pns->nodes[1] << 32)); @@ -517,7 +524,7 @@ STATIC void push_result_token(parser_t *parser, uint8_t rule_id) { // 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); + (const byte *)lex->vstr.buf, lex->vstr.len); pn = make_node_const_object(parser, lex->tok_line, o); } } else { @@ -630,8 +637,8 @@ STATIC bool fold_constants(parser_t *parser, uint8_t rule_id, size_t num_args) { arg0 = mp_binary_op(op, arg0, arg1); } } else if (rule_id == RULE_shift_expr - || rule_id == RULE_arith_expr - || rule_id == RULE_term) { + || 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)) { @@ -648,13 +655,13 @@ STATIC bool fold_constants(parser_t *parser, uint8_t rule_id, size_t num_args) { MP_BINARY_OP_ADD, MP_BINARY_OP_SUBTRACT, MP_BINARY_OP_MULTIPLY, - 255,//MP_BINARY_OP_POWER, - 255,//MP_BINARY_OP_TRUE_DIVIDE, + 255,// MP_BINARY_OP_POWER, + 255,// MP_BINARY_OP_TRUE_DIVIDE, MP_BINARY_OP_FLOOR_DIVIDE, MP_BINARY_OP_MODULO, - 255,//MP_BINARY_OP_LESS + 255,// MP_BINARY_OP_LESS MP_BINARY_OP_LSHIFT, - 255,//MP_BINARY_OP_MORE + 255,// MP_BINARY_OP_MORE MP_BINARY_OP_RSHIFT, }; mp_binary_op_t op = token_to_op[tok - MP_TOKEN_OP_PLUS]; @@ -698,14 +705,14 @@ STATIC bool fold_constants(parser_t *parser, uint8_t rule_id, size_t num_args) { 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))) { + || MP_PARSE_NODE_IS_STRUCT_KIND(pn1, RULE_expr_stmt_assign_list))) { // this node is of the form = 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) + && 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) @@ -713,13 +720,13 @@ STATIC bool fold_constants(parser_t *parser, uint8_t rule_id, size_t num_args) { 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_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, "constant must be an integer"); mp_obj_exception_add_traceback(exc, parser->lexer->source_name, - ((mp_parse_node_struct_t*)pn1)->source_line, MP_QSTR_NULL); + ((mp_parse_node_struct_t *)pn1)->source_line, MP_QSTR_NULL); nlr_raise(exc); } @@ -753,16 +760,16 @@ STATIC bool fold_constants(parser_t *parser, uint8_t rule_id, size_t num_args) { 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))) { + && 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; + 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); + 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; } @@ -855,9 +862,14 @@ mp_parse_tree_t mp_parse(mp_lexer_t *lex, mp_parse_input_kind_t input_kind) { // 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; + 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); @@ -866,7 +878,7 @@ mp_parse_tree_t mp_parse(mp_lexer_t *lex, mp_parse_input_kind_t input_kind) { bool backtrack = false; for (;;) { - next_rule: + next_rule: if (parser.rule_stack_top == 0) { break; } @@ -1038,7 +1050,7 @@ mp_parse_tree_t mp_parse(mp_lexer_t *lex, mp_parse_input_kind_t input_kind) { // n=3 is: item (sep item)* [sep] bool had_trailing_sep; if (backtrack) { - list_backtrack: + list_backtrack: had_trailing_sep = false; if (n == 2) { if (i == 1) { diff --git a/py/parse.h b/py/parse.h index 9a1a2b4dd4..0963862385 100644 --- a/py/parse.h +++ b/py/parse.h @@ -63,7 +63,7 @@ typedef struct _mp_parse_node_struct_t { #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_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) diff --git a/py/parsenum.c b/py/parsenum.c index ae9b834192..f6fcf87226 100644 --- a/py/parsenum.c +++ b/py/parsenum.c @@ -40,7 +40,7 @@ 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_base_t *)MP_OBJ_TO_PTR(exc))->type = &mp_type_SyntaxError; mp_obj_exception_add_traceback(exc, lex->source_name, lex->tok_line, MP_QSTR_NULL); } nlr_raise(exc); @@ -73,7 +73,7 @@ mp_obj_t mp_parse_num_integer(const char *restrict str_, size_t len, int base, m } // parse optional base prefix - str += mp_parse_num_base((const char*)str, top - str, &base); + str += mp_parse_num_base((const char *)str, top - str, &base); // string should be an integer number mp_int_t int_val = 0; @@ -137,9 +137,9 @@ have_ret_val: overflow: // reparse using long int { - const char *s2 = (const char*)str_val_start; + 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; + str = (const byte *)s2; goto have_ret_val; } @@ -171,7 +171,7 @@ typedef enum { } 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 + #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 @@ -179,17 +179,17 @@ mp_obj_t mp_parse_num_decimal(const char *str, size_t len, bool allow_imag, bool // 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 + #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 + #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 + #endif const char *top = str + len; mp_float_t dec_val = 0; @@ -334,17 +334,17 @@ mp_obj_t mp_parse_num_decimal(const char *str, size_t len, bool allow_imag, bool } // return the object -#if MICROPY_PY_BUILTINS_COMPLEX + #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 + #else if (imag || force_complex) { raise_exc(mp_obj_new_exception_msg(&mp_type_ValueError, "complex values not supported"), lex); } -#endif + #endif else { return mp_obj_new_float(dec_val); } @@ -352,7 +352,7 @@ mp_obj_t mp_parse_num_decimal(const char *str, size_t len, bool allow_imag, bool value_error: raise_exc(mp_obj_new_exception_msg(&mp_type_ValueError, "invalid syntax for number"), lex); -#else + #else raise_exc(mp_obj_new_exception_msg(&mp_type_ValueError, "decimal numbers not supported"), lex); -#endif + #endif } diff --git a/py/parsenumbase.c b/py/parsenumbase.c index ba10591226..94523a666d 100644 --- a/py/parsenumbase.c +++ b/py/parsenumbase.c @@ -31,7 +31,7 @@ // 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; + const byte *p = (const byte *)str; if (len <= 1) { goto no_prefix; } @@ -67,5 +67,5 @@ size_t mp_parse_num_base(const char *str, size_t len, int *base) { *base = 10; } } - return p - (const byte*)str; + return p - (const byte *)str; } diff --git a/py/persistentcode.c b/py/persistentcode.c index 7113b0dc2e..47a2c38f81 100644 --- a/py/persistentcode.c +++ b/py/persistentcode.c @@ -125,7 +125,7 @@ STATIC size_t read_uint(mp_reader_t *reader) { STATIC qstr load_qstr(mp_reader_t *reader) { size_t len = read_uint(reader); char *str = m_new(char, len); - read_bytes(reader, (byte*)str, len); + read_bytes(reader, (byte *)str, len); qstr qst = qstr_from_strn(str, len); m_del(char, str, len); return qst; @@ -139,7 +139,7 @@ STATIC mp_obj_t load_obj(mp_reader_t *reader) { size_t len = read_uint(reader); vstr_t vstr; vstr_init_len(&vstr, len); - read_bytes(reader, (byte*)vstr.buf, 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') { @@ -179,9 +179,11 @@ STATIC mp_raw_code_t *load_raw_code(mp_reader_t *reader) { // load qstrs and link global qstr ids into bytecode qstr simple_name = load_qstr(reader); qstr source_file = load_qstr(reader); - ((byte*)ip2)[0] = simple_name; ((byte*)ip2)[1] = simple_name >> 8; - ((byte*)ip2)[2] = source_file; ((byte*)ip2)[3] = source_file >> 8; - load_bytecode_qstrs(reader, (byte*)ip, bytecode + bc_len); + ((byte *)ip2)[0] = simple_name; + ((byte *)ip2)[1] = simple_name >> 8; + ((byte *)ip2)[2] = source_file; + ((byte *)ip2)[3] = source_file >> 8; + load_bytecode_qstrs(reader, (byte *)ip, bytecode + bc_len); // load constant table size_t n_obj = read_uint(reader); @@ -245,7 +247,7 @@ mp_raw_code_t *mp_raw_code_load_file(const char *filename) { #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); + print->print_strn(print->data, (const char *)data, len); } #define BYTES_FOR_INT ((BYTES_PER_WORD * 8 + 6) / 7) @@ -257,7 +259,7 @@ STATIC void mp_print_uint(mp_print_t *print, size_t n) { for (; n != 0; n >>= 7) { *--p = 0x80 | (n & 0x7f); } - print->print_strn(print->data, (char*)p, buf + sizeof(buf) - p); + print->print_strn(print->data, (char *)p, buf + sizeof(buf) - p); } STATIC void save_qstr(mp_print_t *print, qstr qst) { @@ -279,7 +281,7 @@ STATIC void save_obj(mp_print_t *print, mp_obj_t o) { 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); + 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); @@ -303,7 +305,7 @@ STATIC void save_obj(mp_print_t *print, mp_obj_t o) { 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); + mp_print_bytes(print, (const byte *)vstr.buf, vstr.len); vstr_clear(&vstr); } } @@ -352,7 +354,7 @@ STATIC void save_raw_code(mp_print_t *print, mp_raw_code_t *rc) { save_obj(print, (mp_obj_t)*const_table++); } for (uint i = 0; i < rc->data.u_byte.n_raw_code; ++i) { - save_raw_code(print, (mp_raw_code_t*)(uintptr_t)*const_table++); + save_raw_code(print, (mp_raw_code_t *)(uintptr_t)*const_table++); } } @@ -363,11 +365,11 @@ void mp_raw_code_save(mp_raw_code_t *rc, mp_print_t *print) { // byte feature flags // byte number of bits in a small int byte header[4] = {'M', MPY_VERSION, MPY_FEATURE_FLAGS_DYNAMIC, - #if MICROPY_DYNAMIC_COMPILER - mp_dynamic_compiler.small_int_bits, - #else - mp_small_int_bits(), - #endif + #if MICROPY_DYNAMIC_COMPILER + mp_dynamic_compiler.small_int_bits, + #else + mp_small_int_bits(), + #endif }; mp_print_bytes(print, header, sizeof(header)); @@ -391,7 +393,7 @@ STATIC void fd_print_strn(void *env, const char *str, size_t len) { void mp_raw_code_save_file(mp_raw_code_t *rc, const char *filename) { int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0644); - mp_print_t fd_print = {(void*)(intptr_t)fd, fd_print_strn}; + mp_print_t fd_print = {(void *)(intptr_t)fd, fd_print_strn}; mp_raw_code_save(rc, &fd_print); close(fd); } diff --git a/py/pystack.c b/py/pystack.c index 552e59d537..f7323fd740 100644 --- a/py/pystack.c +++ b/py/pystack.c @@ -49,7 +49,7 @@ void *mp_pystack_alloc(size_t n_bytes) { 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; + *(size_t *)(MP_STATE_THREAD(pystack_cur) - MICROPY_PYSTACK_ALIGN) = n_bytes; #endif return ptr; } diff --git a/py/pystack.h b/py/pystack.h index 82ac3743d1..ea8fddcf2f 100644 --- a/py/pystack.h +++ b/py/pystack.h @@ -41,21 +41,21 @@ void *mp_pystack_alloc(size_t n_bytes); // 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)); + 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); + 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); + 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)); + (uint)*(size_t *)(MP_STATE_THREAD(pystack_cur) - MICROPY_PYSTACK_ALIGN)); assert(0); } #endif - MP_STATE_THREAD(pystack_cur) = (uint8_t*)ptr; + MP_STATE_THREAD(pystack_cur) = (uint8_t *)ptr; } static inline void mp_pystack_realloc(void *ptr, size_t n_bytes) { diff --git a/py/qstr.c b/py/qstr.c index a06b84f153..a429c6c475 100644 --- a/py/qstr.c +++ b/py/qstr.c @@ -105,11 +105,11 @@ const qstr_pool_t mp_qstr_const_pool = { MICROPY_ALLOC_QSTR_ENTRIES_INIT, MP_QSTRnumber_of, // corresponds to number of strings in array just below { -#ifndef NO_QSTR + #ifndef NO_QSTR #define QDEF(id, str) str, -#include "genhdr/qstrdefs.generated.h" + #include "genhdr/qstrdefs.generated.h" #undef QDEF -#endif + #endif }, }; @@ -121,7 +121,7 @@ extern const qstr_pool_t MICROPY_QSTR_EXTRA_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(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 @@ -150,7 +150,7 @@ STATIC qstr qstr_add(const byte *q_ptr) { // 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); + 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); @@ -172,7 +172,7 @@ STATIC qstr qstr_add(const byte *q_ptr) { qstr qstr_find_strn(const char *str, size_t str_len) { // work out hash of str - mp_uint_t str_hash = qstr_compute_hash((const byte*)str, 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) { @@ -239,7 +239,7 @@ qstr qstr_from_strn(const char *str, size_t len) { MP_STATE_VM(qstr_last_used) += n_bytes; // store the interned strings' data - mp_uint_t hash = qstr_compute_hash((const byte*)str, len); + 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); @@ -261,7 +261,7 @@ size_t qstr_len(qstr q) { const char *qstr_str(qstr q) { const byte *qd = find_qstr(q); - return (const char*)Q_GET_DATA(qd); + return (const char *)Q_GET_DATA(qd); } const byte *qstr_data(qstr q, size_t *len) { diff --git a/py/qstr.h b/py/qstr.h index f4375ee0e9..46c0fa3946 100644 --- a/py/qstr.h +++ b/py/qstr.h @@ -37,11 +37,11 @@ // first entry in enum will be MP_QSTR_NULL=0, which indicates invalid/no qstr enum { -#ifndef NO_QSTR + #ifndef NO_QSTR #define QDEF(id, str) id, -#include "genhdr/qstrdefs.generated.h" + #include "genhdr/qstrdefs.generated.h" #undef QDEF -#endif + #endif MP_QSTRnumber_of, // no underscore so it can't clash with any of the above }; diff --git a/py/qstrdefs.h b/py/qstrdefs.h index 5c8b13b47e..b951f3d574 100644 --- a/py/qstrdefs.h +++ b/py/qstrdefs.h @@ -38,25 +38,25 @@ Q(*) Q(_) Q(/) #if MICROPY_PY_BUILTINS_STR_OP_MODULO -Q(%#o) -Q(%#x) +Q(% #o) +Q(% #x) #else -Q({:#o}) -Q({:#x}) +Q({: #o}) +Q({: #x}) #endif -Q({:#b}) -Q( ) -Q(\n) +Q({: #b}) +Q() +Q(\ n) Q(maximum recursion depth exceeded) -Q() -Q() -Q() -Q() -Q() -Q() -Q() -Q() -Q(utf-8) +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) diff --git a/py/reader.c b/py/reader.c index 80364104bb..d1b7e7f3a5 100644 --- a/py/reader.c +++ b/py/reader.c @@ -39,7 +39,7 @@ typedef struct _mp_reader_mem_t { } mp_reader_mem_t; STATIC mp_uint_t mp_reader_mem_readbyte(void *data) { - mp_reader_mem_t *reader = (mp_reader_mem_t*)data; + mp_reader_mem_t *reader = (mp_reader_mem_t *)data; if (reader->cur < reader->end) { return *reader->cur++; } else { @@ -48,9 +48,9 @@ STATIC mp_uint_t mp_reader_mem_readbyte(void *data) { } STATIC void mp_reader_mem_close(void *data) { - mp_reader_mem_t *reader = (mp_reader_mem_t*)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(char, (char *)reader->beg, reader->free_len); } m_del_obj(mp_reader_mem_t, reader); } @@ -81,7 +81,7 @@ typedef struct _mp_reader_posix_t { } mp_reader_posix_t; STATIC mp_uint_t mp_reader_posix_readbyte(void *data) { - mp_reader_posix_t *reader = (mp_reader_posix_t*)data; + mp_reader_posix_t *reader = (mp_reader_posix_t *)data; if (reader->pos >= reader->len) { if (reader->len == 0) { return MP_READER_EOF; @@ -99,7 +99,7 @@ STATIC mp_uint_t mp_reader_posix_readbyte(void *data) { } STATIC void mp_reader_posix_close(void *data) { - mp_reader_posix_t *reader = (mp_reader_posix_t*)data; + mp_reader_posix_t *reader = (mp_reader_posix_t *)data; if (reader->close_fd) { close(reader->fd); } diff --git a/py/repl.c b/py/repl.c index da0fefb3a9..2337ce1aed 100644 --- a/py/repl.c +++ b/py/repl.c @@ -50,7 +50,7 @@ bool mp_repl_continue_with_input(const char *input) { // check if input starts with a certain keyword bool starts_with_compound_keyword = - input[0] == '@' + input[0] == '@' || str_startswith_word(input, "if") || str_startswith_word(input, "while") || str_startswith_word(input, "for") @@ -61,7 +61,7 @@ bool mp_repl_continue_with_input(const char *input) { #if MICROPY_PY_ASYNC_AWAIT || str_startswith_word(input, "async") #endif - ; + ; // check for unmatched open bracket, quote or escape quote #define Q_NONE (0) @@ -95,13 +95,26 @@ bool mp_repl_continue_with_input(const char *input) { } } 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; + 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; } } } @@ -183,7 +196,7 @@ size_t mp_repl_autocomplete(const char *str, size_t len, const mp_print_t *print qstr q_first = 0, q_last = 0; for (qstr q = MP_QSTR_ + 1; q < nqstr; ++q) { size_t d_len; - const char *d_str = (const char*)qstr_data(q, &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) { mp_load_method_protected(obj, q, dest, true); if (dest[0] != MP_OBJ_NULL) { @@ -237,7 +250,7 @@ size_t mp_repl_autocomplete(const char *str, size_t len, const mp_print_t *print 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); + const char *d_str = (const char *)qstr_data(q, &d_len); if (s_len <= d_len && strncmp(s_start, d_str, s_len) == 0) { mp_load_method_protected(obj, q, dest, true); if (dest[0] != MP_OBJ_NULL) { diff --git a/py/ringbuf.h b/py/ringbuf.h index b416927060..8ff7e43d67 100644 --- a/py/ringbuf.h +++ b/py/ringbuf.h @@ -39,11 +39,11 @@ typedef struct _ringbuf_t { // Dynamic initialization. This creates root pointer! #define ringbuf_alloc(r, sz) \ -{ \ - (r)->buf = m_new(uint8_t, sz); \ - (r)->size = sz; \ - (r)->iget = (r)->iput = 0; \ -} + { \ + (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) { diff --git a/py/runtime.c b/py/runtime.c index c1e0478135..ae49d87de5 100644 --- a/py/runtime.c +++ b/py/runtime.c @@ -52,7 +52,7 @@ const mp_obj_module_t mp_module___main__ = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&MP_STATE_VM(dict_main), + .globals = (mp_obj_dict_t *)&MP_STATE_VM(dict_main), }; void mp_init(void) { @@ -65,9 +65,9 @@ void mp_init(void) { MP_STATE_VM(sched_sp) = 0; #endif -#if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF + #if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF mp_init_emergency_exception_buf(); -#endif + #endif #if MICROPY_KBD_EXCEPTION // initialise the exception object for raising KeyboardInterrupt @@ -75,13 +75,13 @@ void mp_init(void) { 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; + MP_STATE_VM(mp_kbd_exception).args = (mp_obj_tuple_t *)&mp_const_empty_tuple_obj; #endif // call port specific initialization if any -#ifdef MICROPY_PORT_INIT_FUNC + #ifdef MICROPY_PORT_INIT_FUNC MICROPY_PORT_INIT_FUNC; -#endif + #endif #if MICROPY_ENABLE_COMPILER // optimization disabled by default @@ -131,13 +131,13 @@ void mp_init(void) { void mp_deinit(void) { MP_THREAD_GIL_EXIT(); - //mp_obj_dict_free(&dict_main); - //mp_map_deinit(&MP_STATE_VM(mp_loaded_modules_map)); + // mp_obj_dict_free(&dict_main); + // mp_map_deinit(&MP_STATE_VM(mp_loaded_modules_map)); // call port specific deinitialization if any -#ifdef MICROPY_PORT_DEINIT_FUNC + #ifdef MICROPY_PORT_DEINIT_FUNC MICROPY_PORT_DEINIT_FUNC; -#endif + #endif } mp_obj_t mp_load_name(qstr qst) { @@ -167,7 +167,7 @@ mp_obj_t mp_load_global(qstr qst) { } } #endif - elem = mp_map_lookup((mp_map_t*)&mp_module_builtins_globals.map, MP_OBJ_NEW_QSTR(qst), MP_MAP_LOOKUP); + 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, "name not defined"); @@ -363,11 +363,17 @@ mp_obj_t mp_binary_op(mp_binary_op_t op, mp_obj_t lhs, mp_obj_t rhs) { // << checked explicitly switch (op) { case MP_BINARY_OP_OR: - case MP_BINARY_OP_INPLACE_OR: lhs_val |= rhs_val; break; + 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_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_INPLACE_AND: + lhs_val &= rhs_val; + break; case MP_BINARY_OP_LSHIFT: case MP_BINARY_OP_INPLACE_LSHIFT: { if (rhs_val < 0) { @@ -399,9 +405,13 @@ mp_obj_t mp_binary_op(mp_binary_op_t op, mp_obj_t lhs, mp_obj_t rhs) { } break; case MP_BINARY_OP_ADD: - case MP_BINARY_OP_INPLACE_ADD: lhs_val += rhs_val; break; + 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_INPLACE_SUBTRACT: + lhs_val -= rhs_val; + break; case MP_BINARY_OP_MULTIPLY: case MP_BINARY_OP_INPLACE_MULTIPLY: { @@ -502,10 +512,14 @@ mp_obj_t mp_binary_op(mp_binary_op_t op, mp_obj_t lhs, mp_obj_t rhs) { 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); + 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; @@ -516,7 +530,7 @@ mp_obj_t mp_binary_op(mp_binary_op_t op, mp_obj_t lhs, mp_obj_t rhs) { } else { return mp_obj_new_int_from_ll(lhs_val); } -#if MICROPY_PY_BUILTINS_FLOAT + #if MICROPY_PY_BUILTINS_FLOAT } else if (mp_obj_is_float(rhs)) { mp_obj_t res = mp_obj_float_binary_op(op, lhs_val, rhs); if (res == MP_OBJ_NULL) { @@ -524,7 +538,7 @@ mp_obj_t mp_binary_op(mp_binary_op_t op, mp_obj_t lhs, mp_obj_t rhs) { } else { return res; } -#if MICROPY_PY_BUILTINS_COMPLEX + #if MICROPY_PY_BUILTINS_COMPLEX } else if (MP_OBJ_IS_TYPE(rhs, &mp_type_complex)) { mp_obj_t res = mp_obj_complex_binary_op(op, lhs_val, 0, rhs); if (res == MP_OBJ_NULL) { @@ -532,8 +546,8 @@ mp_obj_t mp_binary_op(mp_binary_op_t op, mp_obj_t lhs, mp_obj_t rhs) { } else { return res; } -#endif -#endif + #endif + #endif } } @@ -556,7 +570,7 @@ generic_binary_op: } } -#if MICROPY_PY_REVERSE_SPECIAL_METHODS + #if MICROPY_PY_REVERSE_SPECIAL_METHODS if (op >= MP_BINARY_OP_OR && op <= MP_BINARY_OP_REVERSE_POWER) { mp_obj_t t = rhs; rhs = lhs; @@ -569,7 +583,7 @@ generic_binary_op: // Convert __rop__ back to __op__ for error message op -= MP_BINARY_OP_REVERSE_OR - MP_BINARY_OP_OR; } -#endif + #endif if (op == MP_BINARY_OP_CONTAINS) { // If type didn't support containment then explicitly walk the iterator. @@ -994,7 +1008,7 @@ STATIC mp_obj_t mp_obj_new_checked_fun(const mp_obj_type_t *type, mp_obj_t fun) 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_TYPE(member, &mp_type_staticmethod)) { // return just the function - dest[0] = ((mp_obj_static_class_method_t*)MP_OBJ_TO_PTR(member))->fun; + dest[0] = ((mp_obj_static_class_method_t *)MP_OBJ_TO_PTR(member))->fun; } else if (MP_OBJ_IS_TYPE(member, &mp_type_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 @@ -1002,18 +1016,18 @@ void mp_convert_member_lookup(mp_obj_t self, const mp_obj_type_t *type, mp_obj_t 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[0] = ((mp_obj_static_class_method_t *)MP_OBJ_TO_PTR(member))->fun; dest[1] = MP_OBJ_FROM_PTR(type); } else if (MP_OBJ_IS_TYPE(member, &mp_type_type)) { // Don't try to bind types (even though they're callable) dest[0] = member; } else if (MP_OBJ_IS_FUN(member) - || (MP_OBJ_IS_OBJ(member) - && (((mp_obj_base_t*)MP_OBJ_TO_PTR(member))->type->name == MP_QSTR_closure - || ((mp_obj_base_t*)MP_OBJ_TO_PTR(member))->type->name == MP_QSTR_generator))) { + || (MP_OBJ_IS_OBJ(member) + && (((mp_obj_base_t *)MP_OBJ_TO_PTR(member))->type->name == MP_QSTR_closure + || ((mp_obj_base_t *)MP_OBJ_TO_PTR(member))->type->name == MP_QSTR_generator))) { // only functions, closures and generators objects can be bound to self #if MICROPY_BUILTIN_METHOD_CHECK_SELF_ARG - const mp_obj_type_t *m_type = ((mp_obj_base_t*)MP_OBJ_TO_PTR(member))->type; + const mp_obj_type_t *m_type = ((mp_obj_base_t *)MP_OBJ_TO_PTR(member))->type; if (self == MP_OBJ_NULL && (m_type == &mp_type_fun_builtin_0 || m_type == &mp_type_fun_builtin_1 @@ -1049,11 +1063,11 @@ void mp_load_method_maybe(mp_obj_t obj, qstr attr, mp_obj_t *dest) { // look for built-in names if (0) { -#if MICROPY_CPYTHON_COMPAT + #if MICROPY_CPYTHON_COMPAT } else if (attr == MP_QSTR___class__) { // a.__class__ is equivalent to type(a) dest[0] = MP_OBJ_FROM_PTR(type); -#endif + #endif } else if (attr == MP_QSTR___next__ && type->iternext != NULL) { dest[0] = MP_OBJ_FROM_PTR(&mp_builtin_next_obj); @@ -1089,7 +1103,7 @@ void mp_load_method(mp_obj_t base, qstr attr, mp_obj_t *dest) { if (MP_OBJ_IS_TYPE(base, &mp_type_type)) { nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_AttributeError, "type object '%q' has no attribute '%q'", - ((mp_obj_type_t*)MP_OBJ_TO_PTR(base))->name, attr)); + ((mp_obj_type_t *)MP_OBJ_TO_PTR(base))->name, attr)); } else { nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_AttributeError, "'%s' object has no attribute '%q'", @@ -1107,7 +1121,7 @@ void mp_load_method_protected(mp_obj_t obj, qstr attr, mp_obj_t *dest, bool catc 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_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)); @@ -1218,7 +1232,7 @@ mp_obj_t mp_iternext(mp_obj_t o_in) { 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))) { + 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_OBJ_STOP_ITERATION; } else { nlr_jump(nlr.ret_val); @@ -1348,7 +1362,7 @@ mp_obj_t mp_import_from(mp_obj_t module, qstr name) { if (dest[1] != MP_OBJ_NULL) { // Hopefully we can't import bound method from an object -import_error: + import_error: nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ImportError, "cannot import name %q", name)); } diff --git a/py/runtime.h b/py/runtime.h index dd4c9a984e..c961d81809 100644 --- a/py/runtime.h +++ b/py/runtime.h @@ -70,7 +70,9 @@ void mp_handle_pending_tail(mp_uint_t atomic_state); #if MICROPY_ENABLE_SCHEDULER void mp_sched_lock(void); void mp_sched_unlock(void); -static inline unsigned int mp_sched_num_pending(void) { return MP_STATE_VM(sched_sp); } +static inline unsigned int mp_sched_num_pending(void) { + return MP_STATE_VM(sched_sp); +} bool mp_sched_schedule(mp_obj_t function, mp_obj_t arg); #endif @@ -86,10 +88,18 @@ void mp_arg_parse_all_kw_array(size_t n_pos, size_t n_kw, const mp_obj_t *args, 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; } +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); @@ -151,7 +161,7 @@ mp_obj_t mp_import_from(mp_obj_t module, qstr name); void mp_import_all(mp_obj_t module); NORETURN void mp_raise_msg(const mp_obj_type_t *exc_type, const char *msg); -//NORETURN void nlr_raise_msg_varg(const mp_obj_type_t *exc_type, const char *fmt, ...); +// NORETURN void nlr_raise_msg_varg(const mp_obj_type_t *exc_type, const char *fmt, ...); NORETURN void mp_raise_ValueError(const char *msg); NORETURN void mp_raise_TypeError(const char *msg); NORETURN void mp_raise_NotImplementedError(const char *msg); diff --git a/py/runtime0.h b/py/runtime0.h index efd439196c..6f8892a16f 100644 --- a/py/runtime0.h +++ b/py/runtime0.h @@ -114,7 +114,7 @@ typedef enum { MP_BINARY_OP_NUM_BYTECODE, // MP_BINARY_OP_REVERSE_* must follow immediately after MP_BINARY_OP_* -#if MICROPY_PY_REVERSE_SPECIAL_METHODS + #if MICROPY_PY_REVERSE_SPECIAL_METHODS MP_BINARY_OP_REVERSE_OR = MP_BINARY_OP_NUM_BYTECODE, MP_BINARY_OP_REVERSE_XOR, MP_BINARY_OP_REVERSE_AND, @@ -127,13 +127,13 @@ typedef enum { MP_BINARY_OP_REVERSE_TRUE_DIVIDE, MP_BINARY_OP_REVERSE_MODULO, MP_BINARY_OP_REVERSE_POWER, -#endif + #endif // This is not emitted by the compiler but is supported by the runtime MP_BINARY_OP_DIVMOD - #if !MICROPY_PY_REVERSE_SPECIAL_METHODS + #if !MICROPY_PY_REVERSE_SPECIAL_METHODS = MP_BINARY_OP_NUM_BYTECODE - #endif + #endif , // The runtime will convert MP_BINARY_OP_IN to this operator with swapped args. @@ -172,10 +172,10 @@ typedef enum { MP_F_LIST_APPEND, MP_F_BUILD_MAP, MP_F_STORE_MAP, -#if MICROPY_PY_BUILTINS_SET + #if MICROPY_PY_BUILTINS_SET MP_F_STORE_SET, MP_F_BUILD_SET, -#endif + #endif MP_F_MAKE_FUNCTION_FROM_RAW_CODE, MP_F_NATIVE_CALL_FUNCTION_N_KW, MP_F_CALL_METHOD_N_KW, @@ -188,9 +188,9 @@ typedef enum { MP_F_IMPORT_NAME, MP_F_IMPORT_FROM, MP_F_IMPORT_ALL, -#if MICROPY_PY_BUILTINS_SLICE + #if MICROPY_PY_BUILTINS_SLICE MP_F_NEW_SLICE, -#endif + #endif MP_F_UNPACK_SEQUENCE, MP_F_UNPACK_EX, MP_F_DELETE_NAME, diff --git a/py/scope.c b/py/scope.c index d996731f85..1e45139b08 100644 --- a/py/scope.c +++ b/py/scope.c @@ -47,7 +47,7 @@ scope_t *scope_new(scope_kind_t kind, mp_parse_node_t pn, qstr source_file, mp_u 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]); + 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]; } diff --git a/py/sequence.c b/py/sequence.c index c66fde98f6..bb53631bf8 100644 --- a/py/sequence.c +++ b/py/sequence.c @@ -39,7 +39,7 @@ void mp_seq_multiply(const void *items, size_t item_sz, size_t len, size_t times 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; + dest = (char *)dest + copy_sz; } } @@ -154,7 +154,7 @@ bool mp_seq_cmp_bytes(mp_uint_t op, const byte *data1, size_t len1, const byte * // Let's deal only with > & >= if (op == MP_BINARY_OP_LESS || op == MP_BINARY_OP_LESS_EQUAL) { - SWAP(const byte*, data1, data2); + SWAP(const byte *, data1, data2); SWAP(size_t, len1, len2); if (op == MP_BINARY_OP_LESS) { op = MP_BINARY_OP_MORE; @@ -221,7 +221,7 @@ bool mp_seq_cmp_objs(mp_uint_t op, const mp_obj_t *items1, size_t len1, const mp } // Otherwise, application of relation op gives the answer - return (mp_binary_op(op, items1[i], items2[i]) == mp_const_true); + return mp_binary_op(op, items1[i], items2[i]) == mp_const_true; } // If we had tie in the last element... @@ -266,9 +266,9 @@ mp_obj_t mp_seq_index_obj(const mp_obj_t *items, size_t len, size_t n_args, cons 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++; - } + if (mp_obj_equal(items[i], value)) { + count++; + } } // Common sense says this cannot overflow small int diff --git a/py/showbc.c b/py/showbc.c index 3deb18cd31..516e48570d 100644 --- a/py/showbc.c +++ b/py/showbc.c @@ -36,10 +36,10 @@ #define printf(...) mp_printf(&mp_plat_print, __VA_ARGS__) #define DECODE_UINT { \ - unum = 0; \ - do { \ - unum = (unum << 7) + (*ip & 0x7f); \ - } while ((*ip++ & 0x80) != 0); \ + 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) @@ -59,20 +59,20 @@ #else #define DECODE_QSTR { \ - qst = 0; \ - do { \ - qst = (qst << 7) + (*ip & 0x7f); \ - } while ((*ip++ & 0x80) != 0); \ + 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*); \ + 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); \ + 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 @@ -143,7 +143,7 @@ void mp_bytecode_print(const void *descr, const byte *ip, mp_uint_t len, const m mp_int_t bc = bytecode_start - ip; mp_uint_t source_line = 1; printf(" bc=" INT_FMT " line=" UINT_FMT "\n", bc, source_line); - for (const byte* ci = code_info; *ci;) { + for (const byte *ci = code_info; *ci;) { if ((ci[0] & 0x80) == 0) { // 0b0LLBBBBB encoding bc += ci[0] & 0x1f; @@ -435,12 +435,12 @@ const byte *mp_bytecode_print_str(const byte *ip) { printf("BUILD_SET " UINT_FMT, unum); break; -#if MICROPY_PY_BUILTINS_SLICE + #if MICROPY_PY_BUILTINS_SLICE case MP_BC_BUILD_SLICE: DECODE_UINT; printf("BUILD_SLICE " UINT_FMT, unum); break; -#endif + #endif case MP_BC_STORE_COMP: DECODE_UINT; @@ -459,25 +459,25 @@ const byte *mp_bytecode_print_str(const byte *ip) { case MP_BC_MAKE_FUNCTION: DECODE_PTR; - printf("MAKE_FUNCTION %p", (void*)(uintptr_t)unum); + printf("MAKE_FUNCTION %p", (void *)(uintptr_t)unum); break; case MP_BC_MAKE_FUNCTION_DEFARGS: DECODE_PTR; - printf("MAKE_FUNCTION_DEFARGS %p", (void*)(uintptr_t)unum); + printf("MAKE_FUNCTION_DEFARGS %p", (void *)(uintptr_t)unum); break; case MP_BC_MAKE_CLOSURE: { DECODE_PTR; mp_uint_t n_closed_over = *ip++; - printf("MAKE_CLOSURE %p " UINT_FMT, (void*)(uintptr_t)unum, n_closed_over); + printf("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++; - printf("MAKE_CLOSURE_DEFARGS %p " UINT_FMT, (void*)(uintptr_t)unum, n_closed_over); + printf("MAKE_CLOSURE_DEFARGS %p " UINT_FMT, (void *)(uintptr_t)unum, n_closed_over); break; } diff --git a/py/stackctrl.c b/py/stackctrl.c index 5c07796bde..c2f3adb5ee 100644 --- a/py/stackctrl.c +++ b/py/stackctrl.c @@ -29,7 +29,7 @@ void mp_stack_ctrl_init(void) { volatile int stack_dummy; - MP_STATE_THREAD(stack_top) = (char*)&stack_dummy; + MP_STATE_THREAD(stack_top) = (char *)&stack_dummy; } void mp_stack_set_top(void *top) { @@ -39,7 +39,7 @@ void mp_stack_set_top(void *top) { mp_uint_t mp_stack_usage(void) { // Assumes descending stack volatile int stack_dummy; - return MP_STATE_THREAD(stack_top) - (char*)&stack_dummy; + return MP_STATE_THREAD(stack_top) - (char *)&stack_dummy; } #if MICROPY_STACK_CHECK diff --git a/py/stream.c b/py/stream.c index 2a9acdea77..d5b4eb67de 100644 --- a/py/stream.c +++ b/py/stream.c @@ -227,7 +227,7 @@ 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); + 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 @@ -261,7 +261,7 @@ STATIC mp_obj_t stream_write_method(size_t n_args, const mp_obj_t *args) { } } bufinfo.len -= off; - return mp_stream_write(args[0], (byte*)bufinfo.buf + off, MIN(bufinfo.len, max_len), MP_STREAM_RW_WRITE); + 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); @@ -378,7 +378,7 @@ STATIC mp_obj_t stream_unbuffered_readline(size_t n_args, const mp_obj_t *args) mp_raise_OSError(error); } if (out_sz == 0) { -done: + 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. @@ -508,7 +508,7 @@ MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_stream_ioctl_obj, 2, 3, stream_ioctl); int mp_stream_errno; ssize_t mp_stream_posix_write(void *stream, const void *buf, size_t len) { - mp_obj_base_t* o = stream; + 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, &mp_stream_errno); if (out_sz == MP_STREAM_ERROR) { @@ -519,7 +519,7 @@ 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) { - mp_obj_base_t* o = stream; + 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, &mp_stream_errno); if (out_sz == MP_STREAM_ERROR) { @@ -530,7 +530,7 @@ 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) { - const mp_obj_base_t* o = stream; + 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; @@ -543,7 +543,7 @@ off_t mp_stream_posix_lseek(void *stream, off_t offset, int whence) { } int mp_stream_posix_fsync(void *stream) { - mp_obj_base_t* o = 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, &mp_stream_errno); if (res == MP_STREAM_ERROR) { diff --git a/py/stream.h b/py/stream.h index f4c6d30bdc..cd6b8c89e0 100644 --- a/py/stream.h +++ b/py/stream.h @@ -93,7 +93,7 @@ MP_DECLARE_CONST_FUN_OBJ_VAR_BETWEEN(mp_stream_ioctl_obj); // 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; + 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); @@ -109,7 +109,7 @@ mp_obj_t mp_stream_write(mp_obj_t self_in, const void *buf, size_t len, byte fla #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_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); diff --git a/py/unicode.c b/py/unicode.c index d69b6f56f0..078ac29b45 100644 --- a/py/unicode.c +++ b/py/unicode.c @@ -71,7 +71,9 @@ STATIC const uint8_t attr[] = { unichar utf8_get_char(const byte *s) { unichar ord = *s++; - if (!UTF8_IS_NONASCII(ord)) return ord; + if (!UTF8_IS_NONASCII(ord)) { + return ord; + } ord &= 0x7F; for (unichar mask = 0x40; ord & mask; mask >>= 1) { ord &= ~mask; diff --git a/py/vm.c b/py/vm.c index f9f9a3d6ac..929c1020ab 100644 --- a/py/vm.c +++ b/py/vm.c @@ -63,7 +63,7 @@ ip += 2; #define DECODE_PTR \ DECODE_UINT; \ - void *ptr = (void*)(uintptr_t)code_state->fun_bc->const_table[unum] + 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] @@ -75,12 +75,12 @@ 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*) + 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 = (byte *)MP_ALIGN(ip, sizeof(mp_obj_t)); \ + mp_obj_t obj = *(mp_obj_t *)ip; \ ip += sizeof(mp_obj_t) #endif @@ -97,12 +97,12 @@ #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) | currently_in_except_block); \ - exc_sp->prev_exc = NULL; \ - currently_in_except_block = 0; /* in a try block now */ \ + 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) | currently_in_except_block); \ + exc_sp->prev_exc = NULL; \ + currently_in_except_block = 0; /* in a try block now */ \ } while (0) #define POP_EXC_BLOCK() \ @@ -118,29 +118,29 @@ // 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 + #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 + #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 + #endif + #if MICROPY_OPT_COMPUTED_GOTO #include "py/vmentrytable.h" #define DISPATCH() do { \ TRACE(ip); \ MARK_EXC_IP_GLOBAL(); \ goto *entry_table[*ip++]; \ - } while (0) +} while (0) #define DISPATCH_WITH_PEND_EXC_CHECK() goto pending_exception_check #define ENTRY(op) entry_##op #define ENTRY_DEFAULT entry_default -#else + #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 + #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 @@ -148,16 +148,17 @@ mp_vm_return_kind_t mp_execute_bytecode(mp_code_state_t *code_state, volatile mp // 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 + #if MICROPY_STACKLESS + run_code_state: + ; + #endif // 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 = mp_decode_uint_value(code_state->fun_bc->bytecode); fastn = &code_state->state[n_state - 1]; - exc_stack = (mp_exc_stack_t*)(code_state->state + n_state); + exc_stack = (mp_exc_stack_t *)(code_state->state + n_state); } // variables that are visible to the exception handler (declared volatile) @@ -173,7 +174,7 @@ run_code_state: ; // outer exception handling loop for (;;) { nlr_buf_t nlr; -outer_dispatch_loop: + outer_dispatch_loop: if (nlr_push(&nlr) == 0) { // local variables that are not visible to the exception handler const byte *ip = code_state->ip; @@ -195,28 +196,28 @@ outer_dispatch_loop: // loop to execute byte code for (;;) { -dispatch_loop: -#if MICROPY_OPT_COMPUTED_GOTO + dispatch_loop: + #if MICROPY_OPT_COMPUTED_GOTO DISPATCH(); -#else + #else TRACE(ip); MARK_EXC_IP_GLOBAL(); switch (*ip++) { -#endif + #endif - ENTRY(MP_BC_LOAD_CONST_FALSE): + ENTRY(MP_BC_LOAD_CONST_FALSE) : PUSH(mp_const_false); - DISPATCH(); + DISPATCH(); - ENTRY(MP_BC_LOAD_CONST_NONE): + ENTRY(MP_BC_LOAD_CONST_NONE) : PUSH(mp_const_none); - DISPATCH(); + DISPATCH(); - ENTRY(MP_BC_LOAD_CONST_TRUE): + ENTRY(MP_BC_LOAD_CONST_TRUE) : PUSH(mp_const_true); - DISPATCH(); + DISPATCH(); - ENTRY(MP_BC_LOAD_CONST_SMALL_INT): { + ENTRY(MP_BC_LOAD_CONST_SMALL_INT) : { mp_int_t num = 0; if ((ip[0] & 0x40) != 0) { // Number is negative @@ -229,28 +230,28 @@ dispatch_loop: DISPATCH(); } - ENTRY(MP_BC_LOAD_CONST_STRING): { + ENTRY(MP_BC_LOAD_CONST_STRING) : { DECODE_QSTR; PUSH(MP_OBJ_NEW_QSTR(qst)); DISPATCH(); } - ENTRY(MP_BC_LOAD_CONST_OBJ): { + ENTRY(MP_BC_LOAD_CONST_OBJ) : { DECODE_OBJ; PUSH(obj); DISPATCH(); } - ENTRY(MP_BC_LOAD_NULL): + ENTRY(MP_BC_LOAD_NULL) : PUSH(MP_OBJ_NULL); - DISPATCH(); + DISPATCH(); - ENTRY(MP_BC_LOAD_FAST_N): { + ENTRY(MP_BC_LOAD_FAST_N) : { DECODE_UINT; obj_shared = fastn[-unum]; - load_check: + load_check: if (obj_shared == MP_OBJ_NULL) { - local_name_error: { + local_name_error: { MARK_EXC_IP_SELECTIVE(); mp_obj_t obj = mp_obj_new_exception_msg(&mp_type_NameError, "local variable referenced before assignment"); RAISE(obj); @@ -260,21 +261,21 @@ dispatch_loop: DISPATCH(); } - ENTRY(MP_BC_LOAD_DEREF): { + 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): { + ENTRY(MP_BC_LOAD_NAME) : { MARK_EXC_IP_SELECTIVE(); DECODE_QSTR; PUSH(mp_load_name(qst)); DISPATCH(); } #else - ENTRY(MP_BC_LOAD_NAME): { + ENTRY(MP_BC_LOAD_NAME) : { MARK_EXC_IP_SELECTIVE(); DECODE_QSTR; mp_obj_t key = MP_OBJ_NEW_QSTR(qst); @@ -284,7 +285,7 @@ dispatch_loop: } else { mp_map_elem_t *elem = mp_map_lookup(&mp_locals_get()->map, MP_OBJ_NEW_QSTR(qst), MP_MAP_LOOKUP); if (elem != NULL) { - *(byte*)ip = (elem - &mp_locals_get()->map.table[0]) & 0xff; + *(byte *)ip = (elem - &mp_locals_get()->map.table[0]) & 0xff; PUSH(elem->value); } else { PUSH(mp_load_name(MP_OBJ_QSTR_VALUE(key))); @@ -296,14 +297,14 @@ dispatch_loop: #endif #if !MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE - ENTRY(MP_BC_LOAD_GLOBAL): { + ENTRY(MP_BC_LOAD_GLOBAL) : { MARK_EXC_IP_SELECTIVE(); DECODE_QSTR; PUSH(mp_load_global(qst)); DISPATCH(); } #else - ENTRY(MP_BC_LOAD_GLOBAL): { + ENTRY(MP_BC_LOAD_GLOBAL) : { MARK_EXC_IP_SELECTIVE(); DECODE_QSTR; mp_obj_t key = MP_OBJ_NEW_QSTR(qst); @@ -313,7 +314,7 @@ dispatch_loop: } else { mp_map_elem_t *elem = mp_map_lookup(&mp_globals_get()->map, MP_OBJ_NEW_QSTR(qst), MP_MAP_LOOKUP); if (elem != NULL) { - *(byte*)ip = (elem - &mp_globals_get()->map.table[0]) & 0xff; + *(byte *)ip = (elem - &mp_globals_get()->map.table[0]) & 0xff; PUSH(elem->value); } else { PUSH(mp_load_global(MP_OBJ_QSTR_VALUE(key))); @@ -325,14 +326,14 @@ dispatch_loop: #endif #if !MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE - ENTRY(MP_BC_LOAD_ATTR): { + ENTRY(MP_BC_LOAD_ATTR) : { MARK_EXC_IP_SELECTIVE(); DECODE_QSTR; SET_TOP(mp_load_attr(TOP(), qst)); DISPATCH(); } #else - ENTRY(MP_BC_LOAD_ATTR): { + ENTRY(MP_BC_LOAD_ATTR) : { MARK_EXC_IP_SELECTIVE(); DECODE_QSTR; mp_obj_t top = TOP(); @@ -346,7 +347,7 @@ dispatch_loop: } else { elem = mp_map_lookup(&self->members, key, MP_MAP_LOOKUP); if (elem != NULL) { - *(byte*)ip = elem - &self->members.table[0]; + *(byte *)ip = elem - &self->members.table[0]; } else { goto load_attr_cache_fail; } @@ -362,7 +363,7 @@ dispatch_loop: } #endif - ENTRY(MP_BC_LOAD_METHOD): { + ENTRY(MP_BC_LOAD_METHOD) : { MARK_EXC_IP_SELECTIVE(); DECODE_QSTR; mp_load_method(*sp, qst, sp); @@ -370,7 +371,7 @@ dispatch_loop: DISPATCH(); } - ENTRY(MP_BC_LOAD_SUPER_METHOD): { + ENTRY(MP_BC_LOAD_SUPER_METHOD) : { MARK_EXC_IP_SELECTIVE(); DECODE_QSTR; sp -= 1; @@ -378,38 +379,38 @@ dispatch_loop: DISPATCH(); } - ENTRY(MP_BC_LOAD_BUILD_CLASS): + ENTRY(MP_BC_LOAD_BUILD_CLASS) : MARK_EXC_IP_SELECTIVE(); - PUSH(mp_load_build_class()); - DISPATCH(); + PUSH(mp_load_build_class()); + DISPATCH(); - ENTRY(MP_BC_LOAD_SUBSCR): { + 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): { + ENTRY(MP_BC_STORE_FAST_N) : { DECODE_UINT; fastn[-unum] = POP(); DISPATCH(); } - ENTRY(MP_BC_STORE_DEREF): { + ENTRY(MP_BC_STORE_DEREF) : { DECODE_UINT; mp_obj_cell_set(fastn[-unum], POP()); DISPATCH(); } - ENTRY(MP_BC_STORE_NAME): { + ENTRY(MP_BC_STORE_NAME) : { MARK_EXC_IP_SELECTIVE(); DECODE_QSTR; mp_store_name(qst, POP()); DISPATCH(); } - ENTRY(MP_BC_STORE_GLOBAL): { + ENTRY(MP_BC_STORE_GLOBAL) : { MARK_EXC_IP_SELECTIVE(); DECODE_QSTR; mp_store_global(qst, POP()); @@ -417,7 +418,7 @@ dispatch_loop: } #if !MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE - ENTRY(MP_BC_STORE_ATTR): { + ENTRY(MP_BC_STORE_ATTR) : { MARK_EXC_IP_SELECTIVE(); DECODE_QSTR; mp_store_attr(sp[0], qst, sp[-1]); @@ -430,7 +431,7 @@ dispatch_loop: // 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): { + ENTRY(MP_BC_STORE_ATTR) : { MARK_EXC_IP_SELECTIVE(); DECODE_QSTR; mp_obj_t top = TOP(); @@ -444,7 +445,7 @@ dispatch_loop: } else { elem = mp_map_lookup(&self->members, key, MP_MAP_LOOKUP); if (elem != NULL) { - *(byte*)ip = elem - &self->members.table[0]; + *(byte *)ip = elem - &self->members.table[0]; } else { goto store_attr_cache_fail; } @@ -462,13 +463,13 @@ dispatch_loop: } #endif - ENTRY(MP_BC_STORE_SUBSCR): + ENTRY(MP_BC_STORE_SUBSCR) : MARK_EXC_IP_SELECTIVE(); - mp_obj_subscr(sp[-1], sp[0], sp[-2]); - sp -= 3; - DISPATCH(); + mp_obj_subscr(sp[-1], sp[0], sp[-2]); + sp -= 3; + DISPATCH(); - ENTRY(MP_BC_DELETE_FAST): { + ENTRY(MP_BC_DELETE_FAST) : { MARK_EXC_IP_SELECTIVE(); DECODE_UINT; if (fastn[-unum] == MP_OBJ_NULL) { @@ -478,7 +479,7 @@ dispatch_loop: DISPATCH(); } - ENTRY(MP_BC_DELETE_DEREF): { + ENTRY(MP_BC_DELETE_DEREF) : { MARK_EXC_IP_SELECTIVE(); DECODE_UINT; if (mp_obj_cell_get(fastn[-unum]) == MP_OBJ_NULL) { @@ -488,44 +489,44 @@ dispatch_loop: DISPATCH(); } - ENTRY(MP_BC_DELETE_NAME): { + ENTRY(MP_BC_DELETE_NAME) : { MARK_EXC_IP_SELECTIVE(); DECODE_QSTR; mp_delete_name(qst); DISPATCH(); } - ENTRY(MP_BC_DELETE_GLOBAL): { + ENTRY(MP_BC_DELETE_GLOBAL) : { MARK_EXC_IP_SELECTIVE(); DECODE_QSTR; mp_delete_global(qst); DISPATCH(); } - ENTRY(MP_BC_DUP_TOP): { + ENTRY(MP_BC_DUP_TOP) : { mp_obj_t top = TOP(); PUSH(top); DISPATCH(); } - ENTRY(MP_BC_DUP_TOP_TWO): + ENTRY(MP_BC_DUP_TOP_TWO) : sp += 2; - sp[0] = sp[-2]; - sp[-1] = sp[-3]; - DISPATCH(); + sp[0] = sp[-2]; + sp[-1] = sp[-3]; + DISPATCH(); - ENTRY(MP_BC_POP_TOP): + ENTRY(MP_BC_POP_TOP) : sp -= 1; - DISPATCH(); + DISPATCH(); - ENTRY(MP_BC_ROT_TWO): { + ENTRY(MP_BC_ROT_TWO) : { mp_obj_t top = sp[0]; sp[0] = sp[-1]; sp[-1] = top; DISPATCH(); } - ENTRY(MP_BC_ROT_THREE): { + ENTRY(MP_BC_ROT_THREE) : { mp_obj_t top = sp[0]; sp[0] = sp[-1]; sp[-1] = sp[-2]; @@ -533,13 +534,13 @@ dispatch_loop: DISPATCH(); } - ENTRY(MP_BC_JUMP): { + ENTRY(MP_BC_JUMP) : { DECODE_SLABEL; ip += slab; DISPATCH_WITH_PEND_EXC_CHECK(); } - ENTRY(MP_BC_POP_JUMP_IF_TRUE): { + ENTRY(MP_BC_POP_JUMP_IF_TRUE) : { DECODE_SLABEL; if (mp_obj_is_true(POP())) { ip += slab; @@ -547,7 +548,7 @@ dispatch_loop: DISPATCH_WITH_PEND_EXC_CHECK(); } - ENTRY(MP_BC_POP_JUMP_IF_FALSE): { + ENTRY(MP_BC_POP_JUMP_IF_FALSE) : { DECODE_SLABEL; if (!mp_obj_is_true(POP())) { ip += slab; @@ -555,7 +556,7 @@ dispatch_loop: DISPATCH_WITH_PEND_EXC_CHECK(); } - ENTRY(MP_BC_JUMP_IF_TRUE_OR_POP): { + ENTRY(MP_BC_JUMP_IF_TRUE_OR_POP) : { DECODE_SLABEL; if (mp_obj_is_true(TOP())) { ip += slab; @@ -565,7 +566,7 @@ dispatch_loop: DISPATCH_WITH_PEND_EXC_CHECK(); } - ENTRY(MP_BC_JUMP_IF_FALSE_OR_POP): { + ENTRY(MP_BC_JUMP_IF_FALSE_OR_POP) : { DECODE_SLABEL; if (mp_obj_is_true(TOP())) { sp--; @@ -575,7 +576,7 @@ dispatch_loop: DISPATCH_WITH_PEND_EXC_CHECK(); } - ENTRY(MP_BC_SETUP_WITH): { + ENTRY(MP_BC_SETUP_WITH) : { MARK_EXC_IP_SELECTIVE(); // stack: (..., ctx_mgr) mp_obj_t obj = TOP(); @@ -589,7 +590,7 @@ dispatch_loop: DISPATCH(); } - ENTRY(MP_BC_WITH_CLEANUP): { + 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__, @@ -644,12 +645,12 @@ dispatch_loop: DISPATCH(); } - ENTRY(MP_BC_UNWIND_JUMP): { + 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:; + unwind_jump:; mp_uint_t unum = (mp_uint_t)POP(); // get number of exception handlers to unwind while ((unum & 0x7f) > 0) { unum -= 1; @@ -672,7 +673,7 @@ unwind_jump:; } POP_EXC_BLOCK(); } - ip = (const byte*)MP_OBJ_TO_PTR(POP()); // pop destination ip for jump + 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; @@ -681,8 +682,8 @@ unwind_jump:; } // matched against: POP_BLOCK or POP_EXCEPT (anything else?) - ENTRY(MP_BC_SETUP_EXCEPT): - ENTRY(MP_BC_SETUP_FINALLY): { + 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); @@ -692,45 +693,45 @@ unwind_jump:; DISPATCH(); } - ENTRY(MP_BC_END_FINALLY): + 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 - 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; - } + // 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 + 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 { - assert(mp_obj_is_exception_instance(TOP())); - RAISE(TOP()); + // 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; } - DISPATCH(); + } else { + assert(mp_obj_is_exception_instance(TOP())); + RAISE(TOP()); + } + DISPATCH(); - ENTRY(MP_BC_GET_ITER): + ENTRY(MP_BC_GET_ITER) : MARK_EXC_IP_SELECTIVE(); - SET_TOP(mp_getiter(TOP(), NULL)); - DISPATCH(); + 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): { + 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; + 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)) { @@ -741,7 +742,7 @@ unwind_jump:; DISPATCH(); } - ENTRY(MP_BC_FOR_ITER): { + ENTRY(MP_BC_FOR_ITER) : { MARK_EXC_IP_SELECTIVE(); DECODE_ULABEL; // the jump offset if iteration finishes; for labels are always forward code_state->sp = sp; @@ -762,20 +763,20 @@ unwind_jump:; } // matched against: SETUP_EXCEPT, SETUP_FINALLY, SETUP_WITH - ENTRY(MP_BC_POP_BLOCK): + ENTRY(MP_BC_POP_BLOCK) : // we are exiting an exception handler, so pop the last one of the exception-stack assert(exc_sp >= exc_stack); - POP_EXC_BLOCK(); - DISPATCH(); + POP_EXC_BLOCK(); + DISPATCH(); // matched against: SETUP_EXCEPT - ENTRY(MP_BC_POP_EXCEPT): + ENTRY(MP_BC_POP_EXCEPT) : assert(exc_sp >= exc_stack); - assert(currently_in_except_block); - POP_EXC_BLOCK(); - DISPATCH(); + assert(currently_in_except_block); + POP_EXC_BLOCK(); + DISPATCH(); - ENTRY(MP_BC_BUILD_TUPLE): { + ENTRY(MP_BC_BUILD_TUPLE) : { MARK_EXC_IP_SELECTIVE(); DECODE_UINT; sp -= unum - 1; @@ -783,7 +784,7 @@ unwind_jump:; DISPATCH(); } - ENTRY(MP_BC_BUILD_LIST): { + ENTRY(MP_BC_BUILD_LIST) : { MARK_EXC_IP_SELECTIVE(); DECODE_UINT; sp -= unum - 1; @@ -791,31 +792,31 @@ unwind_jump:; DISPATCH(); } - ENTRY(MP_BC_BUILD_MAP): { + ENTRY(MP_BC_BUILD_MAP) : { MARK_EXC_IP_SELECTIVE(); DECODE_UINT; PUSH(mp_obj_new_dict(unum)); DISPATCH(); } - ENTRY(MP_BC_STORE_MAP): + ENTRY(MP_BC_STORE_MAP) : MARK_EXC_IP_SELECTIVE(); - sp -= 2; - mp_obj_dict_store(sp[0], sp[2], sp[1]); - DISPATCH(); + sp -= 2; + mp_obj_dict_store(sp[0], sp[2], sp[1]); + DISPATCH(); -#if MICROPY_PY_BUILTINS_SET - ENTRY(MP_BC_BUILD_SET): { + #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 + #endif -#if MICROPY_PY_BUILTINS_SLICE - ENTRY(MP_BC_BUILD_SLICE): { + #if MICROPY_PY_BUILTINS_SLICE + ENTRY(MP_BC_BUILD_SLICE) : { MARK_EXC_IP_SELECTIVE(); mp_obj_t step = mp_const_none; if (*ip++ == 3) { @@ -827,9 +828,9 @@ unwind_jump:; SET_TOP(mp_obj_new_slice(start, stop, step)); DISPATCH(); } -#endif + #endif - ENTRY(MP_BC_STORE_COMP): { + ENTRY(MP_BC_STORE_COMP) : { MARK_EXC_IP_SELECTIVE(); DECODE_UINT; mp_obj_t obj = sp[-(unum >> 2)]; @@ -848,7 +849,7 @@ unwind_jump:; DISPATCH(); } - ENTRY(MP_BC_UNPACK_SEQUENCE): { + ENTRY(MP_BC_UNPACK_SEQUENCE) : { MARK_EXC_IP_SELECTIVE(); DECODE_UINT; mp_unpack_sequence(sp[0], unum, sp); @@ -856,7 +857,7 @@ unwind_jump:; DISPATCH(); } - ENTRY(MP_BC_UNPACK_EX): { + ENTRY(MP_BC_UNPACK_EX) : { MARK_EXC_IP_SELECTIVE(); DECODE_UINT; mp_unpack_ex(sp[0], unum, sp); @@ -864,13 +865,13 @@ unwind_jump:; DISPATCH(); } - ENTRY(MP_BC_MAKE_FUNCTION): { + 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): { + ENTRY(MP_BC_MAKE_FUNCTION_DEFARGS) : { DECODE_PTR; // Stack layout: def_tuple def_dict <- TOS mp_obj_t def_dict = POP(); @@ -878,7 +879,7 @@ unwind_jump:; DISPATCH(); } - ENTRY(MP_BC_MAKE_CLOSURE): { + ENTRY(MP_BC_MAKE_CLOSURE) : { DECODE_PTR; size_t n_closed_over = *ip++; // Stack layout: closed_overs <- TOS @@ -887,7 +888,7 @@ unwind_jump:; DISPATCH(); } - ENTRY(MP_BC_MAKE_CLOSURE_DEFARGS): { + ENTRY(MP_BC_MAKE_CLOSURE_DEFARGS) : { DECODE_PTR; size_t n_closed_over = *ip++; // Stack layout: def_tuple def_dict closed_overs <- TOS @@ -896,7 +897,7 @@ unwind_jump:; DISPATCH(); } - ENTRY(MP_BC_CALL_FUNCTION): { + ENTRY(MP_BC_CALL_FUNCTION) : { MARK_EXC_IP_SELECTIVE(); DECODE_UINT; // unum & 0xff == n_positional @@ -930,7 +931,7 @@ unwind_jump:; DISPATCH(); } - ENTRY(MP_BC_CALL_FUNCTION_VAR_KW): { + ENTRY(MP_BC_CALL_FUNCTION_VAR_KW) : { MARK_EXC_IP_SELECTIVE(); DECODE_UINT; // unum & 0xff == n_positional @@ -975,7 +976,7 @@ unwind_jump:; DISPATCH(); } - ENTRY(MP_BC_CALL_METHOD): { + ENTRY(MP_BC_CALL_METHOD) : { MARK_EXC_IP_SELECTIVE(); DECODE_UINT; // unum & 0xff == n_positional @@ -1013,7 +1014,7 @@ unwind_jump:; DISPATCH(); } - ENTRY(MP_BC_CALL_METHOD_VAR_KW): { + ENTRY(MP_BC_CALL_METHOD_VAR_KW) : { MARK_EXC_IP_SELECTIVE(); DECODE_UINT; // unum & 0xff == n_positional @@ -1058,60 +1059,60 @@ unwind_jump:; DISPATCH(); } - ENTRY(MP_BC_RETURN_VALUE): + 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 (!currently_in_except_block && MP_TAGPTR_TAG1(exc_sp->val_sp)) { - // Found a finally handler that isn't active. - // 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; - POP_EXC_BLOCK(); - goto dispatch_loop; - } + unwind_return: + // Search for and execute finally handlers that aren't already active + while (exc_sp >= exc_stack) { + if (!currently_in_except_block && MP_TAGPTR_TAG1(exc_sp->val_sp)) { + // Found a finally handler that isn't active. + // 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; POP_EXC_BLOCK(); + goto dispatch_loop; } - 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; - } + 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 - return MP_VM_RETURN_NORMAL; + code_state = new_code_state; + *code_state->sp = res; + goto run_code_state; + } + #endif + return MP_VM_RETURN_NORMAL; - ENTRY(MP_BC_RAISE_VARARGS): { + ENTRY(MP_BC_RAISE_VARARGS) : { MARK_EXC_IP_SELECTIVE(); mp_uint_t unum = *ip; mp_obj_t obj; @@ -1140,19 +1141,20 @@ unwind_return: RAISE(obj); } - ENTRY(MP_BC_YIELD_VALUE): -yield: + ENTRY(MP_BC_YIELD_VALUE) : + yield: nlr_pop(); - code_state->ip = ip; - code_state->sp = sp; - code_state->exc_sp = MP_TAGPTR_MAKE(exc_sp, currently_in_except_block); - return MP_VM_RETURN_YIELD; + code_state->ip = ip; + code_state->sp = sp; + code_state->exc_sp = MP_TAGPTR_MAKE(exc_sp, currently_in_except_block); + return MP_VM_RETURN_YIELD; - ENTRY(MP_BC_YIELD_FROM): { + 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_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); } +#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; @@ -1201,7 +1203,7 @@ yield: } } - ENTRY(MP_BC_IMPORT_NAME): { + ENTRY(MP_BC_IMPORT_NAME) : { MARK_EXC_IP_SELECTIVE(); DECODE_QSTR; mp_obj_t obj = POP(); @@ -1209,7 +1211,7 @@ yield: DISPATCH(); } - ENTRY(MP_BC_IMPORT_FROM): { + ENTRY(MP_BC_IMPORT_FROM) : { MARK_EXC_IP_SELECTIVE(); DECODE_QSTR; mp_obj_t obj = mp_import_from(TOP(), qst); @@ -1217,30 +1219,30 @@ yield: DISPATCH(); } - ENTRY(MP_BC_IMPORT_STAR): + ENTRY(MP_BC_IMPORT_STAR) : MARK_EXC_IP_SELECTIVE(); - mp_import_all(POP()); - DISPATCH(); + mp_import_all(POP()); + DISPATCH(); -#if MICROPY_OPT_COMPUTED_GOTO - ENTRY(MP_BC_LOAD_CONST_SMALL_INT_MULTI): + #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 - 16)); - DISPATCH(); + DISPATCH(); - ENTRY(MP_BC_LOAD_FAST_MULTI): + ENTRY(MP_BC_LOAD_FAST_MULTI) : obj_shared = fastn[MP_BC_LOAD_FAST_MULTI - (mp_int_t)ip[-1]]; - goto load_check; + goto load_check; - ENTRY(MP_BC_STORE_FAST_MULTI): + ENTRY(MP_BC_STORE_FAST_MULTI) : fastn[MP_BC_STORE_FAST_MULTI - (mp_int_t)ip[-1]] = POP(); - DISPATCH(); + DISPATCH(); - ENTRY(MP_BC_UNARY_OP_MULTI): + ENTRY(MP_BC_UNARY_OP_MULTI) : MARK_EXC_IP_SELECTIVE(); - SET_TOP(mp_unary_op(ip[-1] - MP_BC_UNARY_OP_MULTI, TOP())); - DISPATCH(); + SET_TOP(mp_unary_op(ip[-1] - MP_BC_UNARY_OP_MULTI, TOP())); + DISPATCH(); - ENTRY(MP_BC_BINARY_OP_MULTI): { + ENTRY(MP_BC_BINARY_OP_MULTI) : { MARK_EXC_IP_SELECTIVE(); mp_obj_t rhs = POP(); mp_obj_t lhs = TOP(); @@ -1248,29 +1250,29 @@ yield: DISPATCH(); } - ENTRY_DEFAULT: - MARK_EXC_IP_SELECTIVE(); -#else - ENTRY_DEFAULT: - if (ip[-1] < MP_BC_LOAD_CONST_SMALL_INT_MULTI + 64) { - PUSH(MP_OBJ_NEW_SMALL_INT((mp_int_t)ip[-1] - MP_BC_LOAD_CONST_SMALL_INT_MULTI - 16)); - DISPATCH(); - } else if (ip[-1] < MP_BC_LOAD_FAST_MULTI + 16) { - 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 + 16) { - fastn[MP_BC_STORE_FAST_MULTI - (mp_int_t)ip[-1]] = POP(); - DISPATCH(); - } else if (ip[-1] < MP_BC_UNARY_OP_MULTI + MP_UNARY_OP_NUM_BYTECODE) { - SET_TOP(mp_unary_op(ip[-1] - MP_BC_UNARY_OP_MULTI, TOP())); - DISPATCH(); - } else if (ip[-1] < MP_BC_BINARY_OP_MULTI + MP_BINARY_OP_NUM_BYTECODE) { - 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 + ENTRY_DEFAULT: + MARK_EXC_IP_SELECTIVE(); + #else + ENTRY_DEFAULT: + if (ip[-1] < MP_BC_LOAD_CONST_SMALL_INT_MULTI + 64) { + PUSH(MP_OBJ_NEW_SMALL_INT((mp_int_t)ip[-1] - MP_BC_LOAD_CONST_SMALL_INT_MULTI - 16)); + DISPATCH(); + } else if (ip[-1] < MP_BC_LOAD_FAST_MULTI + 16) { + 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 + 16) { + fastn[MP_BC_STORE_FAST_MULTI - (mp_int_t)ip[-1]] = POP(); + DISPATCH(); + } else if (ip[-1] < MP_BC_UNARY_OP_MULTI + MP_UNARY_OP_NUM_BYTECODE) { + SET_TOP(mp_unary_op(ip[-1] - MP_BC_UNARY_OP_MULTI, TOP())); + DISPATCH(); + } else if (ip[-1] < MP_BC_BINARY_OP_MULTI + MP_BINARY_OP_NUM_BYTECODE) { + 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, "byte code not implemented"); nlr_pop(); @@ -1278,11 +1280,11 @@ yield: return MP_VM_RETURN_EXCEPTION; } -#if !MICROPY_OPT_COMPUTED_GOTO - } // switch -#endif + #if !MICROPY_OPT_COMPUTED_GOTO + } // switch + #endif -pending_exception_check: + pending_exception_check: MICROPY_VM_HOOK_LOOP #if MICROPY_ENABLE_SCHEDULER @@ -1324,8 +1326,8 @@ pending_exception_check: if (MP_STATE_VM(sched_state) == MP_SCHED_IDLE) #endif { - MP_THREAD_GIL_EXIT(); - MP_THREAD_GIL_ENTER(); + MP_THREAD_GIL_EXIT(); + MP_THREAD_GIL_ENTER(); } } #endif @@ -1333,7 +1335,7 @@ pending_exception_check: } // for loop } else { -exception_handler: + exception_handler: // exception occurred #if MICROPY_PY_SYS_EXC_INFO @@ -1345,7 +1347,7 @@ exception_handler: 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 (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) { @@ -1365,9 +1367,9 @@ exception_handler: } } -#if MICROPY_STACKLESS -unwind_loop: -#endif + #if MICROPY_STACKLESS + unwind_loop: + #endif // set file and line number that the exception occurred at // TODO: don't set traceback for exceptions re-raised by END_FINALLY. // But consider how to handle nested exceptions. @@ -1458,7 +1460,7 @@ unwind_loop: code_state = new_code_state; size_t n_state = mp_decode_uint_value(code_state->fun_bc->bytecode); fastn = &code_state->state[n_state - 1]; - exc_stack = (mp_exc_stack_t*)(code_state->state + n_state); + exc_stack = (mp_exc_stack_t *)(code_state->state + n_state); // variables that are visible to the exception handler (declared volatile) currently_in_except_block = MP_TAGPTR_TAG0(code_state->exc_sp); // 0 or 1, to detect nested exceptions exc_sp = MP_TAGPTR_PTR(code_state->exc_sp); // stack grows up, exc_sp points to top of stack diff --git a/py/vmentrytable.h b/py/vmentrytable.h index 615f4e2ce4..a98a052fca 100644 --- a/py/vmentrytable.h +++ b/py/vmentrytable.h @@ -30,87 +30,87 @@ #endif // __clang__ 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_BLOCK] = &&entry_MP_BC_POP_BLOCK, - [MP_BC_POP_EXCEPT] = &&entry_MP_BC_POP_EXCEPT, - [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, + [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_BLOCK] = && entry_MP_BC_POP_BLOCK, + [MP_BC_POP_EXCEPT] = && entry_MP_BC_POP_EXCEPT, + [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, + [MP_BC_BUILD_SET] = && entry_MP_BC_BUILD_SET, #endif #if MICROPY_PY_BUILTINS_SLICE - [MP_BC_BUILD_SLICE] = &&entry_MP_BC_BUILD_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_VARARGS] = &&entry_MP_BC_RAISE_VARARGS, - [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 + 63] = &&entry_MP_BC_LOAD_CONST_SMALL_INT_MULTI, - [MP_BC_LOAD_FAST_MULTI ... MP_BC_LOAD_FAST_MULTI + 15] = &&entry_MP_BC_LOAD_FAST_MULTI, - [MP_BC_STORE_FAST_MULTI ... MP_BC_STORE_FAST_MULTI + 15] = &&entry_MP_BC_STORE_FAST_MULTI, - [MP_BC_UNARY_OP_MULTI ... MP_BC_UNARY_OP_MULTI + MP_UNARY_OP_NUM_BYTECODE - 1] = &&entry_MP_BC_UNARY_OP_MULTI, - [MP_BC_BINARY_OP_MULTI ... MP_BC_BINARY_OP_MULTI + MP_BINARY_OP_NUM_BYTECODE - 1] = &&entry_MP_BC_BINARY_OP_MULTI, + [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_VARARGS] = && entry_MP_BC_RAISE_VARARGS, + [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 + 63] = && entry_MP_BC_LOAD_CONST_SMALL_INT_MULTI, + [MP_BC_LOAD_FAST_MULTI ... MP_BC_LOAD_FAST_MULTI + 15] = && entry_MP_BC_LOAD_FAST_MULTI, + [MP_BC_STORE_FAST_MULTI ... MP_BC_STORE_FAST_MULTI + 15] = && entry_MP_BC_STORE_FAST_MULTI, + [MP_BC_UNARY_OP_MULTI ... MP_BC_UNARY_OP_MULTI + MP_UNARY_OP_NUM_BYTECODE - 1] = && entry_MP_BC_UNARY_OP_MULTI, + [MP_BC_BINARY_OP_MULTI ... MP_BC_BINARY_OP_MULTI + MP_BINARY_OP_NUM_BYTECODE - 1] = && entry_MP_BC_BINARY_OP_MULTI, }; #if __clang__ diff --git a/py/vstr.c b/py/vstr.c index 869b278057..168763bfba 100644 --- a/py/vstr.c +++ b/py/vstr.c @@ -139,37 +139,37 @@ char *vstr_null_terminated_str(vstr_t *vstr) { } void vstr_add_byte(vstr_t *vstr, byte b) { - byte *buf = (byte*)vstr_add_len(vstr, 1); + 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 + #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); + byte *buf = (byte *)vstr_add_len(vstr, 1); *buf = (byte)c; } else if (c < 0x800) { - byte *buf = (byte*)vstr_add_len(vstr, 2); + 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); + 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); + 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 + #else vstr_add_byte(vstr, c); -#endif + #endif } void vstr_add_str(vstr_t *vstr, const char *str) { diff --git a/tests/bench/arrayop-1-list_inplace.py b/tests/bench/arrayop-1-list_inplace.py index 0ee1ef2eca..b29593c1a1 100644 --- a/tests/bench/arrayop-1-list_inplace.py +++ b/tests/bench/arrayop-1-list_inplace.py @@ -3,10 +3,12 @@ # method is that it doesn't require any extra memory allocation. import bench + def test(num): - for i in iter(range(num//10000)): + for i in iter(range(num // 10000)): arr = [0] * 1000 for i in range(len(arr)): arr[i] += 1 + bench.run(test) diff --git a/tests/bench/arrayop-2-list_map.py b/tests/bench/arrayop-2-list_map.py index 9d5095c53a..5959d3f469 100644 --- a/tests/bench/arrayop-2-list_map.py +++ b/tests/bench/arrayop-2-list_map.py @@ -4,9 +4,11 @@ # array). On the other hand, input array stays intact. import bench + def test(num): - for i in iter(range(num//10000)): + for i in iter(range(num // 10000)): arr = [0] * 1000 arr2 = list(map(lambda x: x + 1, arr)) + bench.run(test) diff --git a/tests/bench/arrayop-3-bytearray_inplace.py b/tests/bench/arrayop-3-bytearray_inplace.py index a6d6280705..fbbade2cac 100644 --- a/tests/bench/arrayop-3-bytearray_inplace.py +++ b/tests/bench/arrayop-3-bytearray_inplace.py @@ -3,10 +3,12 @@ # method is that it doesn't require any extra memory allocation. import bench + def test(num): - for i in iter(range(num//10000)): + for i in iter(range(num // 10000)): arr = bytearray(b"\0" * 1000) for i in range(len(arr)): arr[i] += 1 + bench.run(test) diff --git a/tests/bench/arrayop-4-bytearray_map.py b/tests/bench/arrayop-4-bytearray_map.py index 1b92a40961..8fa9879705 100644 --- a/tests/bench/arrayop-4-bytearray_map.py +++ b/tests/bench/arrayop-4-bytearray_map.py @@ -4,9 +4,11 @@ # array). On the other hand, input array stays intact. import bench + def test(num): - for i in iter(range(num//10000)): + for i in iter(range(num // 10000)): arr = bytearray(b"\0" * 1000) arr2 = bytearray(map(lambda x: x + 1, arr)) + bench.run(test) diff --git a/tests/bench/bench.py b/tests/bench/bench.py index 0cd40a93fc..d7087e0e09 100644 --- a/tests/bench/bench.py +++ b/tests/bench/bench.py @@ -3,6 +3,7 @@ import time ITERS = 20000000 + def run(f): t = time.time() f(ITERS) diff --git a/tests/bench/bytealloc-1-bytes_n.py b/tests/bench/bytealloc-1-bytes_n.py index 4a4bbc6fae..8b8120a530 100644 --- a/tests/bench/bytealloc-1-bytes_n.py +++ b/tests/bench/bytealloc-1-bytes_n.py @@ -1,7 +1,9 @@ import bench + def test(num): for i in iter(range(num // 1000)): bytes(10000) + bench.run(test) diff --git a/tests/bench/bytealloc-2-repeat.py b/tests/bench/bytealloc-2-repeat.py index 786a804622..8d6b5d5289 100644 --- a/tests/bench/bytealloc-2-repeat.py +++ b/tests/bench/bytealloc-2-repeat.py @@ -1,7 +1,9 @@ import bench + def test(num): for i in iter(range(num // 1000)): b"\0" * 10000 + bench.run(test) diff --git a/tests/bench/bytebuf-1-inplace.py b/tests/bench/bytebuf-1-inplace.py index 7e7d9391cc..e1b6016a57 100644 --- a/tests/bench/bytebuf-1-inplace.py +++ b/tests/bench/bytebuf-1-inplace.py @@ -2,10 +2,12 @@ # Inplace - the most memory efficient way import bench + def test(num): - for i in iter(range(num//10000)): + for i in iter(range(num // 10000)): ba = bytearray(b"\0" * 1000) for i in range(len(ba)): ba[i] += 1 + bench.run(test) diff --git a/tests/bench/bytebuf-2-join_map_bytes.py b/tests/bench/bytebuf-2-join_map_bytes.py index daa622991f..9ecee47978 100644 --- a/tests/bench/bytebuf-2-join_map_bytes.py +++ b/tests/bench/bytebuf-2-join_map_bytes.py @@ -4,9 +4,11 @@ # this is slowest way to do it. import bench + def test(num): - for i in iter(range(num//10000)): + for i in iter(range(num // 10000)): ba = bytearray(b"\0" * 1000) - ba2 = b''.join(map(lambda x:bytes([x + 1]), ba)) + ba2 = b"".join(map(lambda x: bytes([x + 1]), ba)) + bench.run(test) diff --git a/tests/bench/bytebuf-3-bytarray_map.py b/tests/bench/bytebuf-3-bytarray_map.py index 078d08e99b..2752d4e784 100644 --- a/tests/bench/bytebuf-3-bytarray_map.py +++ b/tests/bench/bytebuf-3-bytarray_map.py @@ -2,9 +2,11 @@ # No joins, but still map(). import bench + def test(num): - for i in iter(range(num//10000)): + for i in iter(range(num // 10000)): ba = bytearray(b"\0" * 1000) ba2 = bytearray(map(lambda x: x + 1, ba)) + bench.run(test) diff --git a/tests/bench/from_iter-1-list_bound.py b/tests/bench/from_iter-1-list_bound.py index d209daecc5..384d52903f 100644 --- a/tests/bench/from_iter-1-list_bound.py +++ b/tests/bench/from_iter-1-list_bound.py @@ -1,8 +1,10 @@ import bench + def test(num): - for i in iter(range(num//10000)): + for i in iter(range(num // 10000)): l = [0] * 1000 l2 = list(l) + bench.run(test) diff --git a/tests/bench/from_iter-2-list_unbound.py b/tests/bench/from_iter-2-list_unbound.py index be019c52fe..98e22d6813 100644 --- a/tests/bench/from_iter-2-list_unbound.py +++ b/tests/bench/from_iter-2-list_unbound.py @@ -1,8 +1,10 @@ import bench + def test(num): - for i in iter(range(num//10000)): + for i in iter(range(num // 10000)): l = [0] * 1000 l2 = list(map(lambda x: x, l)) + bench.run(test) diff --git a/tests/bench/from_iter-3-tuple_bound.py b/tests/bench/from_iter-3-tuple_bound.py index 7b7fa36c6e..f052f6deea 100644 --- a/tests/bench/from_iter-3-tuple_bound.py +++ b/tests/bench/from_iter-3-tuple_bound.py @@ -1,8 +1,10 @@ import bench + def test(num): - for i in iter(range(num//10000)): + for i in iter(range(num // 10000)): l = [0] * 1000 l2 = tuple(l) + bench.run(test) diff --git a/tests/bench/from_iter-4-tuple_unbound.py b/tests/bench/from_iter-4-tuple_unbound.py index 7c7f134c85..ff9d1b4df5 100644 --- a/tests/bench/from_iter-4-tuple_unbound.py +++ b/tests/bench/from_iter-4-tuple_unbound.py @@ -1,8 +1,10 @@ import bench + def test(num): - for i in iter(range(num//10000)): + for i in iter(range(num // 10000)): l = [0] * 1000 l2 = tuple(map(lambda x: x, l)) + bench.run(test) diff --git a/tests/bench/from_iter-5-bytes_bound.py b/tests/bench/from_iter-5-bytes_bound.py index b793a3207e..967cb99eea 100644 --- a/tests/bench/from_iter-5-bytes_bound.py +++ b/tests/bench/from_iter-5-bytes_bound.py @@ -1,8 +1,10 @@ import bench + def test(num): - for i in iter(range(num//10000)): + for i in iter(range(num // 10000)): l = [0] * 1000 l2 = bytes(l) + bench.run(test) diff --git a/tests/bench/from_iter-6-bytes_unbound.py b/tests/bench/from_iter-6-bytes_unbound.py index 20aa556277..b855019160 100644 --- a/tests/bench/from_iter-6-bytes_unbound.py +++ b/tests/bench/from_iter-6-bytes_unbound.py @@ -1,8 +1,10 @@ import bench + def test(num): - for i in iter(range(num//10000)): + for i in iter(range(num // 10000)): l = [0] * 1000 l2 = bytes(map(lambda x: x, l)) + bench.run(test) diff --git a/tests/bench/from_iter-7-bytearray_bound.py b/tests/bench/from_iter-7-bytearray_bound.py index 72001a05c7..d0c4c65a74 100644 --- a/tests/bench/from_iter-7-bytearray_bound.py +++ b/tests/bench/from_iter-7-bytearray_bound.py @@ -1,8 +1,10 @@ import bench + def test(num): - for i in iter(range(num//10000)): + for i in iter(range(num // 10000)): l = [0] * 1000 l2 = bytearray(l) + bench.run(test) diff --git a/tests/bench/from_iter-8-bytearray_unbound.py b/tests/bench/from_iter-8-bytearray_unbound.py index e2263b8ef9..aec2e65adf 100644 --- a/tests/bench/from_iter-8-bytearray_unbound.py +++ b/tests/bench/from_iter-8-bytearray_unbound.py @@ -1,8 +1,10 @@ import bench + def test(num): - for i in iter(range(num//10000)): + for i in iter(range(num // 10000)): l = [0] * 1000 l2 = bytearray(map(lambda x: x, l)) + bench.run(test) diff --git a/tests/bench/func_args-1.1-pos_1.py b/tests/bench/func_args-1.1-pos_1.py index eee0ea8289..cadb17768c 100644 --- a/tests/bench/func_args-1.1-pos_1.py +++ b/tests/bench/func_args-1.1-pos_1.py @@ -1,10 +1,13 @@ import bench + def func(a): pass + def test(num): for i in iter(range(num)): func(i) + bench.run(test) diff --git a/tests/bench/func_args-1.2-pos_3.py b/tests/bench/func_args-1.2-pos_3.py index 7e03ee2f85..12010d0150 100644 --- a/tests/bench/func_args-1.2-pos_3.py +++ b/tests/bench/func_args-1.2-pos_3.py @@ -1,10 +1,13 @@ import bench + def func(a, b, c): pass + def test(num): for i in iter(range(num)): func(i, i, i) + bench.run(test) diff --git a/tests/bench/func_args-2-pos_default_2_of_3.py b/tests/bench/func_args-2-pos_default_2_of_3.py index 1fa0fbda59..4dc5650902 100644 --- a/tests/bench/func_args-2-pos_default_2_of_3.py +++ b/tests/bench/func_args-2-pos_default_2_of_3.py @@ -1,10 +1,13 @@ import bench + def func(a, b=1, c=2): pass + def test(num): for i in iter(range(num)): func(i) + bench.run(test) diff --git a/tests/bench/func_args-3.1-kw_1.py b/tests/bench/func_args-3.1-kw_1.py index 7bc81e5bea..18252570c1 100644 --- a/tests/bench/func_args-3.1-kw_1.py +++ b/tests/bench/func_args-3.1-kw_1.py @@ -1,10 +1,13 @@ import bench + def func(a): pass + def test(num): for i in iter(range(num)): func(a=i) + bench.run(test) diff --git a/tests/bench/func_args-3.2-kw_3.py b/tests/bench/func_args-3.2-kw_3.py index 7f95106841..deac15cb41 100644 --- a/tests/bench/func_args-3.2-kw_3.py +++ b/tests/bench/func_args-3.2-kw_3.py @@ -1,10 +1,13 @@ import bench + def func(a, b, c): pass + def test(num): for i in iter(range(num)): func(c=i, b=i, a=i) + bench.run(test) diff --git a/tests/bench/func_builtin-1-enum_pos.py b/tests/bench/func_builtin-1-enum_pos.py index 20935164e8..c7c148df10 100644 --- a/tests/bench/func_builtin-1-enum_pos.py +++ b/tests/bench/func_builtin-1-enum_pos.py @@ -1,7 +1,9 @@ import bench + def test(num): - for i in iter(range(num//20)): + for i in iter(range(num // 20)): enumerate([1, 2], 1) + bench.run(test) diff --git a/tests/bench/func_builtin-2-enum_kw.py b/tests/bench/func_builtin-2-enum_kw.py index 6c5e44419c..a25ab241c6 100644 --- a/tests/bench/func_builtin-2-enum_kw.py +++ b/tests/bench/func_builtin-2-enum_kw.py @@ -1,7 +1,9 @@ import bench + def test(num): - for i in iter(range(num//20)): + for i in iter(range(num // 20)): enumerate(iterable=[1, 2], start=1) + bench.run(test) diff --git a/tests/bench/funcall-1-inline.py b/tests/bench/funcall-1-inline.py index fbeb79630d..8c3f0ccd59 100644 --- a/tests/bench/funcall-1-inline.py +++ b/tests/bench/funcall-1-inline.py @@ -2,8 +2,10 @@ # Establish a baseline for performing a trivial operation inline import bench + def test(num): for i in iter(range(num)): a = i + 1 + bench.run(test) diff --git a/tests/bench/funcall-2-funcall.py b/tests/bench/funcall-2-funcall.py index d5c36c60aa..a245258040 100644 --- a/tests/bench/funcall-2-funcall.py +++ b/tests/bench/funcall-2-funcall.py @@ -2,11 +2,14 @@ # Perform the same trivial operation as global function call import bench + def f(x): return x + 1 + def test(num): for i in iter(range(num)): a = f(i) + bench.run(test) diff --git a/tests/bench/funcall-3-funcall-local.py b/tests/bench/funcall-3-funcall-local.py index 1a6d728c63..d922888685 100644 --- a/tests/bench/funcall-3-funcall-local.py +++ b/tests/bench/funcall-3-funcall-local.py @@ -5,12 +5,15 @@ # variables are accessed by offset, not by name) import bench + def f(x): return x + 1 + def test(num): f_ = f for i in iter(range(num)): a = f_(i) + bench.run(test) diff --git a/tests/bench/loop_count-1-range.py b/tests/bench/loop_count-1-range.py index e22adf6cbe..fdb11eaac6 100644 --- a/tests/bench/loop_count-1-range.py +++ b/tests/bench/loop_count-1-range.py @@ -1,7 +1,9 @@ import bench + def test(num): for i in range(num): pass + bench.run(test) diff --git a/tests/bench/loop_count-2-range_iter.py b/tests/bench/loop_count-2-range_iter.py index fe4a3857e1..4189bf329d 100644 --- a/tests/bench/loop_count-2-range_iter.py +++ b/tests/bench/loop_count-2-range_iter.py @@ -1,7 +1,9 @@ import bench + def test(num): for i in iter(range(num)): pass + bench.run(test) diff --git a/tests/bench/loop_count-3-while_up.py b/tests/bench/loop_count-3-while_up.py index 1ab8054a0f..22c64403bf 100644 --- a/tests/bench/loop_count-3-while_up.py +++ b/tests/bench/loop_count-3-while_up.py @@ -1,8 +1,10 @@ import bench + def test(num): i = 0 while i < num: i += 1 + bench.run(test) diff --git a/tests/bench/loop_count-4-while_down_gt.py b/tests/bench/loop_count-4-while_down_gt.py index de8dee2ca9..47b004c2bd 100644 --- a/tests/bench/loop_count-4-while_down_gt.py +++ b/tests/bench/loop_count-4-while_down_gt.py @@ -1,7 +1,9 @@ import bench + def test(num): while num > 0: num -= 1 + bench.run(test) diff --git a/tests/bench/loop_count-5-while_down_ne.py b/tests/bench/loop_count-5-while_down_ne.py index b9a1af414b..419c817c8f 100644 --- a/tests/bench/loop_count-5-while_down_ne.py +++ b/tests/bench/loop_count-5-while_down_ne.py @@ -1,7 +1,9 @@ import bench + def test(num): while num != 0: num -= 1 + bench.run(test) diff --git a/tests/bench/loop_count-5.1-while_down_ne_localvar.py b/tests/bench/loop_count-5.1-while_down_ne_localvar.py index 96bdb9129f..d25102a630 100644 --- a/tests/bench/loop_count-5.1-while_down_ne_localvar.py +++ b/tests/bench/loop_count-5.1-while_down_ne_localvar.py @@ -1,8 +1,10 @@ import bench + def test(num): zero = 0 while num != zero: num -= 1 + bench.run(test) diff --git a/tests/bench/var-1-constant.py b/tests/bench/var-1-constant.py index eec977909c..4a24194725 100644 --- a/tests/bench/var-1-constant.py +++ b/tests/bench/var-1-constant.py @@ -1,8 +1,10 @@ import bench + def test(num): i = 0 while i < 20000000: i += 1 + bench.run(test) diff --git a/tests/bench/var-2-global.py b/tests/bench/var-2-global.py index 5758ad61aa..a47240d646 100644 --- a/tests/bench/var-2-global.py +++ b/tests/bench/var-2-global.py @@ -2,9 +2,11 @@ import bench ITERS = 20000000 + def test(num): i = 0 while i < ITERS: i += 1 + bench.run(test) diff --git a/tests/bench/var-3-local.py b/tests/bench/var-3-local.py index 124b484295..182bb95f6f 100644 --- a/tests/bench/var-3-local.py +++ b/tests/bench/var-3-local.py @@ -7,4 +7,5 @@ def test(num): while i < ITERS: i += 1 + bench.run(test) diff --git a/tests/bench/var-4-arg.py b/tests/bench/var-4-arg.py index cf050c58fd..b9734357c8 100644 --- a/tests/bench/var-4-arg.py +++ b/tests/bench/var-4-arg.py @@ -6,4 +6,5 @@ def test(num): while i < num: i += 1 -bench.run(lambda n:test(20000000)) + +bench.run(lambda n: test(20000000)) diff --git a/tests/bench/var-5-class-attr.py b/tests/bench/var-5-class-attr.py index 02ae874ac2..e10770ee5b 100644 --- a/tests/bench/var-5-class-attr.py +++ b/tests/bench/var-5-class-attr.py @@ -1,11 +1,14 @@ import bench + class Foo: num = 20000000 + def test(num): i = 0 while i < Foo.num: i += 1 + bench.run(test) diff --git a/tests/bench/var-6-instance-attr.py b/tests/bench/var-6-instance-attr.py index 787ed870fb..0124ef51b3 100644 --- a/tests/bench/var-6-instance-attr.py +++ b/tests/bench/var-6-instance-attr.py @@ -1,14 +1,16 @@ import bench -class Foo: +class Foo: def __init__(self): self.num = 20000000 + def test(num): o = Foo() i = 0 while i < o.num: i += 1 + bench.run(test) diff --git a/tests/bench/var-6.1-instance-attr-5.py b/tests/bench/var-6.1-instance-attr-5.py index e8d3383605..692cef20df 100644 --- a/tests/bench/var-6.1-instance-attr-5.py +++ b/tests/bench/var-6.1-instance-attr-5.py @@ -1,7 +1,7 @@ import bench -class Foo: +class Foo: def __init__(self): self.num1 = 0 self.num2 = 0 @@ -9,10 +9,12 @@ class Foo: self.num4 = 0 self.num = 20000000 + def test(num): o = Foo() i = 0 while i < o.num: i += 1 + bench.run(test) diff --git a/tests/bench/var-7-instance-meth.py b/tests/bench/var-7-instance-meth.py index f9d463f40a..2ed7800be5 100644 --- a/tests/bench/var-7-instance-meth.py +++ b/tests/bench/var-7-instance-meth.py @@ -1,17 +1,19 @@ import bench -class Foo: +class Foo: def __init__(self): self._num = 20000000 def num(self): return self._num + def test(num): o = Foo() i = 0 while i < o.num(): i += 1 + bench.run(test) diff --git a/tests/bench/var-8-namedtuple-1st.py b/tests/bench/var-8-namedtuple-1st.py index d862480a51..1a6daa6cdd 100644 --- a/tests/bench/var-8-namedtuple-1st.py +++ b/tests/bench/var-8-namedtuple-1st.py @@ -3,10 +3,12 @@ from ucollections import namedtuple T = namedtuple("Tup", ["num", "bar"]) + def test(num): t = T(20000000, 0) i = 0 while i < t.num: i += 1 + bench.run(test) diff --git a/tests/bench/var-8.1-namedtuple-5th.py b/tests/bench/var-8.1-namedtuple-5th.py index 0bcf661803..568ece8067 100644 --- a/tests/bench/var-8.1-namedtuple-5th.py +++ b/tests/bench/var-8.1-namedtuple-5th.py @@ -3,10 +3,12 @@ from ucollections import namedtuple T = namedtuple("Tup", ["foo1", "foo2", "foo3", "foo4", "num"]) + def test(num): t = T(0, 0, 0, 0, 20000000) i = 0 while i < t.num: i += 1 + bench.run(test) diff --git a/tests/cmdline/cmd_parsetree.py b/tests/cmdline/cmd_parsetree.py index da36c80703..50da369543 100644 --- a/tests/cmdline/cmd_parsetree.py +++ b/tests/cmdline/cmd_parsetree.py @@ -4,9 +4,9 @@ for i in (): pass a = None -b = 'str' -c = 'a very long str that will not be interned' -d = b'bytes' -e = b'a very long bytes that will not be interned' +b = "str" +c = "a very long str that will not be interned" +d = b"bytes" +e = b"a very long bytes that will not be interned" f = 123456789012345678901234567890 g = 123 diff --git a/tests/cmdline/cmd_showbc.py b/tests/cmdline/cmd_showbc.py index 916228356f..23691a4757 100644 --- a/tests/cmdline/cmd_showbc.py +++ b/tests/cmdline/cmd_showbc.py @@ -1,6 +1,7 @@ # cmdline: -v -v # test printing of all bytecodes + def f(): # constants a = None + False + True @@ -14,9 +15,9 @@ def f(): c = [1, 2] d = {1, 2} e = {} - f = {1:2} - g = 'a' - h = b'a' + f = {1: 2} + g = "a" + h = b"a" # unary/binary ops i = 1 @@ -58,7 +59,7 @@ def f(): # comprehensions a = (b for c in d if e) a = [b for c in d if e] - a = {b:b for c in d if e} + a = {b: b for c in d if e} # function calls a() @@ -107,8 +108,10 @@ def f(): # closed over variables x = 1 + def closure(): - nonlocal x; a = x + 1 + nonlocal x + a = x + 1 x = 1 del x @@ -125,12 +128,14 @@ def f(): return return 1 + # function with lots of locals def f(): l1 = l2 = l3 = l4 = l5 = l6 = l7 = l8 = l9 = l10 = 1 m1 = m2 = m3 = m4 = m5 = m6 = m7 = m8 = m9 = m10 = 2 l10 + m10 + # functions with default args def f(a=1): pass @@ -138,16 +143,19 @@ def f(a=1): def f(b=2): return b + a + # function which yields def f(): yield yield 1 yield from 1 + # class class Class: pass + # delete name del Class diff --git a/tests/cpydiff/core_class_delnotimpl.py b/tests/cpydiff/core_class_delnotimpl.py index c51c3d536f..18c176e9bb 100644 --- a/tests/cpydiff/core_class_delnotimpl.py +++ b/tests/cpydiff/core_class_delnotimpl.py @@ -6,9 +6,11 @@ workaround: Unknown """ import gc -class Foo(): + +class Foo: def __del__(self): - print('__del__') + print("__del__") + f = Foo() del f diff --git a/tests/cpydiff/core_class_mro.py b/tests/cpydiff/core_class_mro.py index 99713e790c..bdd6dd5df6 100644 --- a/tests/cpydiff/core_class_mro.py +++ b/tests/cpydiff/core_class_mro.py @@ -4,12 +4,16 @@ description: Method Resolution Order (MRO) is not compliant with CPython cause: Depth first non-exhaustive method resolution order workaround: Avoid complex class hierarchies with multiple inheritance and complex method overrides. Keep in mind that many languages don't support multiple inheritance at all. """ + + class Foo: def __str__(self): return "Foo" + class C(tuple, Foo): pass + t = C((1, 2, 3)) print(t) diff --git a/tests/cpydiff/core_class_supermultiple.py b/tests/cpydiff/core_class_supermultiple.py index f0823ee11d..9a87b85a87 100644 --- a/tests/cpydiff/core_class_supermultiple.py +++ b/tests/cpydiff/core_class_supermultiple.py @@ -4,24 +4,29 @@ description: When inheriting from multiple classes super() only calls one class cause: See :ref:`cpydiff_core_class_mro` workaround: See :ref:`cpydiff_core_class_mro` """ + + class A: def __init__(self): print("A.__init__") + class B(A): def __init__(self): print("B.__init__") super().__init__() + class C(A): def __init__(self): print("C.__init__") super().__init__() -class D(B,C): +class D(B, C): def __init__(self): print("D.__init__") super().__init__() + D() diff --git a/tests/cpydiff/core_class_superproperty.py b/tests/cpydiff/core_class_superproperty.py index 1ec210550e..2d7775a902 100644 --- a/tests/cpydiff/core_class_superproperty.py +++ b/tests/cpydiff/core_class_superproperty.py @@ -4,15 +4,19 @@ description: Calling super() getter property in subclass will return a property cause: Unknown workaround: Unknown """ + + class A: @property def p(self): - return {"a":10} + return {"a": 10} + class AA(A): @property def p(self): return super().p + a = AA() print(a.p) diff --git a/tests/cpydiff/core_function_userattr.py b/tests/cpydiff/core_function_userattr.py index 2972939084..a8380c690a 100644 --- a/tests/cpydiff/core_function_userattr.py +++ b/tests/cpydiff/core_function_userattr.py @@ -4,8 +4,11 @@ description: User-defined attributes for functions are not supported cause: MicroPython is highly optimized for memory usage. workaround: Use external dictionary, e.g. ``FUNC_X[f] = 0``. """ + + def f(): pass + f.x = 0 print(f.x) diff --git a/tests/cpydiff/core_generator_noexit.py b/tests/cpydiff/core_generator_noexit.py index c25fbe75a2..149e9a0a90 100644 --- a/tests/cpydiff/core_generator_noexit.py +++ b/tests/cpydiff/core_generator_noexit.py @@ -4,11 +4,15 @@ description: Context manager __exit__() not called in a generator which does not cause: Unknown workaround: Unknown """ + + class foo(object): def __enter__(self): - print('Enter') + print("Enter") + def __exit__(self, *args): - print('Exit') + print("Exit") + def bar(x): with foo(): @@ -16,9 +20,11 @@ def bar(x): x += 1 yield x + def func(): g = bar(0) for _ in range(3): print(next(g)) + func() diff --git a/tests/cpydiff/core_import_prereg.py b/tests/cpydiff/core_import_prereg.py index 4a71217821..3ce2340c68 100644 --- a/tests/cpydiff/core_import_prereg.py +++ b/tests/cpydiff/core_import_prereg.py @@ -12,6 +12,7 @@ except NameError as e: print(e) try: from modules import foo - print('Should not get here') + + print("Should not get here") except NameError as e: print(e) diff --git a/tests/cpydiff/core_import_split_ns_pkgs.py b/tests/cpydiff/core_import_split_ns_pkgs.py index 700620c470..62bf337a22 100644 --- a/tests/cpydiff/core_import_split_ns_pkgs.py +++ b/tests/cpydiff/core_import_split_ns_pkgs.py @@ -5,6 +5,7 @@ cause: MicroPython's import system is highly optimized for simplicity, minimal m workaround: Don't install modules belonging to the same namespace package in different directories. For MicroPython, it's recommended to have at most 3-component module search paths: for your current application, per-user (writable), system-wide (non-writable). """ import sys + sys.path.append(sys.path[1] + "/modules") sys.path.append(sys.path[1] + "/modules2") diff --git a/tests/cpydiff/core_locals.py b/tests/cpydiff/core_locals.py index 0240e5a1a9..af3280c6d7 100644 --- a/tests/cpydiff/core_locals.py +++ b/tests/cpydiff/core_locals.py @@ -4,8 +4,11 @@ description: Local variables aren't included in locals() result cause: MicroPython doesn't maintain symbolic local environment, it is optimized to an array of slots. Thus, local variables can't be accessed by a name. workaround: Unknown """ + + def test(): val = 2 print(locals()) + test() diff --git a/tests/cpydiff/core_locals_eval.py b/tests/cpydiff/core_locals_eval.py index 8416e3b069..025d226372 100644 --- a/tests/cpydiff/core_locals_eval.py +++ b/tests/cpydiff/core_locals_eval.py @@ -6,9 +6,11 @@ workaround: Unknown """ val = 1 + def test(): val = 2 print(val) eval("print(val)") + test() diff --git a/tests/cpydiff/modules_array_containment.py b/tests/cpydiff/modules_array_containment.py index 190a3c2760..8f25b0d491 100644 --- a/tests/cpydiff/modules_array_containment.py +++ b/tests/cpydiff/modules_array_containment.py @@ -5,4 +5,5 @@ cause: Unknown workaround: Unknown """ import array -print(1 in array.array('B', b'12')) + +print(1 in array.array("B", b"12")) diff --git a/tests/cpydiff/modules_array_deletion.py b/tests/cpydiff/modules_array_deletion.py index 97f988da23..3376527373 100644 --- a/tests/cpydiff/modules_array_deletion.py +++ b/tests/cpydiff/modules_array_deletion.py @@ -5,6 +5,7 @@ cause: Unknown workaround: Unknown """ import array -a = array.array('b', (1, 2, 3)) + +a = array.array("b", (1, 2, 3)) del a[1] print(a) diff --git a/tests/cpydiff/modules_array_subscrstep.py b/tests/cpydiff/modules_array_subscrstep.py index 1103f18269..24308bd904 100644 --- a/tests/cpydiff/modules_array_subscrstep.py +++ b/tests/cpydiff/modules_array_subscrstep.py @@ -5,5 +5,6 @@ cause: Unknown workaround: Unknown """ import array -a = array.array('b', (1, 2, 3)) + +a = array.array("b", (1, 2, 3)) print(a[3:2:2]) diff --git a/tests/cpydiff/modules_deque.py b/tests/cpydiff/modules_deque.py index a503ea4f55..4d2746d1f8 100644 --- a/tests/cpydiff/modules_deque.py +++ b/tests/cpydiff/modules_deque.py @@ -5,5 +5,6 @@ cause: Unknown workaround: Use regular lists. micropython-lib has implementation of collections.deque. """ import collections + D = collections.deque() print(D) diff --git a/tests/cpydiff/modules_json_nonserializable.py b/tests/cpydiff/modules_json_nonserializable.py index 913b734e8b..ffe523786f 100644 --- a/tests/cpydiff/modules_json_nonserializable.py +++ b/tests/cpydiff/modules_json_nonserializable.py @@ -5,10 +5,11 @@ cause: Unknown workaround: Unknown """ import json + a = bytes(x for x in range(256)) try: z = json.dumps(a) x = json.loads(z) - print('Should not get here') + print("Should not get here") except TypeError: - print('TypeError') + print("TypeError") diff --git a/tests/cpydiff/modules_struct_fewargs.py b/tests/cpydiff/modules_struct_fewargs.py index 08d32ca672..cb6b0fd874 100644 --- a/tests/cpydiff/modules_struct_fewargs.py +++ b/tests/cpydiff/modules_struct_fewargs.py @@ -5,8 +5,9 @@ cause: Unknown workaround: Unknown """ import struct + try: - print(struct.pack('bb', 1)) - print('Should not get here') + print(struct.pack("bb", 1)) + print("Should not get here") except: - print('struct.error') + print("struct.error") diff --git a/tests/cpydiff/modules_struct_manyargs.py b/tests/cpydiff/modules_struct_manyargs.py index cdbb5c672c..03395baad3 100644 --- a/tests/cpydiff/modules_struct_manyargs.py +++ b/tests/cpydiff/modules_struct_manyargs.py @@ -5,8 +5,9 @@ cause: Unknown workaround: Unknown """ import struct + try: - print(struct.pack('bb', 1, 2, 3)) - print('Should not get here') + print(struct.pack("bb", 1, 2, 3)) + print("Should not get here") except: - print('struct.error') + print("struct.error") diff --git a/tests/cpydiff/modules_sys_stdassign.py b/tests/cpydiff/modules_sys_stdassign.py index 1bf2a598a0..7d086078a9 100644 --- a/tests/cpydiff/modules_sys_stdassign.py +++ b/tests/cpydiff/modules_sys_stdassign.py @@ -5,5 +5,6 @@ cause: They are stored in read-only memory. workaround: Unknown """ import sys + sys.stdin = None print(sys.stdin) diff --git a/tests/cpydiff/syntax_spaces.py b/tests/cpydiff/syntax_spaces.py index 8578a51e28..c308240a78 100644 --- a/tests/cpydiff/syntax_spaces.py +++ b/tests/cpydiff/syntax_spaces.py @@ -5,14 +5,14 @@ cause: Unknown workaround: Unknown """ try: - print(eval('1and 0')) + print(eval("1and 0")) except SyntaxError: - print('Should have worked') + print("Should have worked") try: - print(eval('1or 0')) + print(eval("1or 0")) except SyntaxError: - print('Should have worked') + print("Should have worked") try: - print(eval('1if 1else 0')) + print(eval("1if 1else 0")) except SyntaxError: - print('Should have worked') + print("Should have worked") diff --git a/tests/cpydiff/types_bytes_format.py b/tests/cpydiff/types_bytes_format.py index 697ee52698..ad04987711 100644 --- a/tests/cpydiff/types_bytes_format.py +++ b/tests/cpydiff/types_bytes_format.py @@ -4,4 +4,4 @@ description: bytes objects support .format() method cause: MicroPython strives to be a more regular implementation, so if both `str` and `bytes` support ``__mod__()`` (the % operator), it makes sense to support ``format()`` for both too. Support for ``__mod__`` can also be compiled out, which leaves only ``format()`` for bytes formatting. workaround: If you are interested in CPython compatibility, don't use ``.format()`` on bytes objects. """ -print(b'{}'.format(1)) +print(b"{}".format(1)) diff --git a/tests/cpydiff/types_bytes_keywords.py b/tests/cpydiff/types_bytes_keywords.py index 4dc383f262..550ce12bbd 100644 --- a/tests/cpydiff/types_bytes_keywords.py +++ b/tests/cpydiff/types_bytes_keywords.py @@ -4,4 +4,4 @@ description: bytes() with keywords not implemented cause: Unknown workaround: Pass the encoding as a positional paramter, e.g. ``print(bytes('abc', 'utf-8'))`` """ -print(bytes('abc', encoding='utf8')) +print(bytes("abc", encoding="utf8")) diff --git a/tests/cpydiff/types_bytes_subscrstep.py b/tests/cpydiff/types_bytes_subscrstep.py index 2871bda6c1..51b94cb710 100644 --- a/tests/cpydiff/types_bytes_subscrstep.py +++ b/tests/cpydiff/types_bytes_subscrstep.py @@ -4,4 +4,4 @@ description: Bytes subscription with step != 1 not implemented cause: MicroPython is highly optimized for memory usage. workaround: Use explicit loop for this very rare operation. """ -print(b'123'[0:3:2]) +print(b"123"[0:3:2]) diff --git a/tests/cpydiff/types_exception_subclassinit.py b/tests/cpydiff/types_exception_subclassinit.py index 39cdaf45b8..ade9ebc7ab 100644 --- a/tests/cpydiff/types_exception_subclassinit.py +++ b/tests/cpydiff/types_exception_subclassinit.py @@ -8,8 +8,11 @@ workaround: Call using ``super()`` instead:: def __init__(self): super().__init__() """ + + class A(Exception): def __init__(self): Exception.__init__(self) + a = A() diff --git a/tests/cpydiff/types_float_rounding.py b/tests/cpydiff/types_float_rounding.py index c8d3cfbe88..a5b591966b 100644 --- a/tests/cpydiff/types_float_rounding.py +++ b/tests/cpydiff/types_float_rounding.py @@ -4,4 +4,4 @@ description: uPy and CPython outputs formats may differ cause: Unknown workaround: Unknown """ -print('%.1g' % -9.9) +print("%.1g" % -9.9) diff --git a/tests/cpydiff/types_int_subclassconv.py b/tests/cpydiff/types_int_subclassconv.py index 260b060ed6..5d337412c7 100644 --- a/tests/cpydiff/types_int_subclassconv.py +++ b/tests/cpydiff/types_int_subclassconv.py @@ -4,8 +4,11 @@ description: No int conversion for int-derived types available cause: Unknown workaround: Avoid subclassing builtin types unless really needed. Prefer https://en.wikipedia.org/wiki/Composition_over_inheritance . """ + + class A(int): __add__ = lambda self, other: A(int(self) + other) + a = A(42) -print(a+a) +print(a + a) diff --git a/tests/cpydiff/types_str_endswith.py b/tests/cpydiff/types_str_endswith.py index ac2600bd25..f222ac1cd3 100644 --- a/tests/cpydiff/types_str_endswith.py +++ b/tests/cpydiff/types_str_endswith.py @@ -4,4 +4,4 @@ description: Start/end indices such as str.endswith(s, start) not implemented cause: Unknown workaround: Unknown """ -print('abc'.endswith('c', 1)) +print("abc".endswith("c", 1)) diff --git a/tests/cpydiff/types_str_formatsubscr.py b/tests/cpydiff/types_str_formatsubscr.py index dd1d8d33d7..1b83cfff6c 100644 --- a/tests/cpydiff/types_str_formatsubscr.py +++ b/tests/cpydiff/types_str_formatsubscr.py @@ -4,4 +4,4 @@ description: Attributes/subscr not implemented cause: Unknown workaround: Unknown """ -print('{a[0]}'.format(a=[1, 2])) +print("{a[0]}".format(a=[1, 2])) diff --git a/tests/cpydiff/types_str_keywords.py b/tests/cpydiff/types_str_keywords.py index b336b1a73e..77a4eac1c1 100644 --- a/tests/cpydiff/types_str_keywords.py +++ b/tests/cpydiff/types_str_keywords.py @@ -4,4 +4,4 @@ description: str(...) with keywords not implemented cause: Unknown workaround: Input the encoding format directly. eg ``print(bytes('abc', 'utf-8'))`` """ -print(str(b'abc', encoding='utf8')) +print(str(b"abc", encoding="utf8")) diff --git a/tests/cpydiff/types_str_ljust_rjust.py b/tests/cpydiff/types_str_ljust_rjust.py index fa3f594c1f..72e5105e02 100644 --- a/tests/cpydiff/types_str_ljust_rjust.py +++ b/tests/cpydiff/types_str_ljust_rjust.py @@ -4,4 +4,4 @@ description: str.ljust() and str.rjust() not implemented cause: MicroPython is highly optimized for memory usage. Easy workarounds available. workaround: Instead of ``s.ljust(10)`` use ``"%-10s" % s``, instead of ``s.rjust(10)`` use ``"% 10s" % s``. Alternatively, ``"{:<10}".format(s)`` or ``"{:>10}".format(s)``. """ -print('abc'.ljust(10)) +print("abc".ljust(10)) diff --git a/tests/cpydiff/types_str_rsplitnone.py b/tests/cpydiff/types_str_rsplitnone.py index cadf869877..5d334fea2f 100644 --- a/tests/cpydiff/types_str_rsplitnone.py +++ b/tests/cpydiff/types_str_rsplitnone.py @@ -4,4 +4,4 @@ description: None as first argument for rsplit such as str.rsplit(None, n) not i cause: Unknown workaround: Unknown """ -print('a a a'.rsplit(None, 1)) +print("a a a".rsplit(None, 1)) diff --git a/tests/cpydiff/types_str_subclassequality.py b/tests/cpydiff/types_str_subclassequality.py index 8aec1ea78f..e44198fccf 100644 --- a/tests/cpydiff/types_str_subclassequality.py +++ b/tests/cpydiff/types_str_subclassequality.py @@ -4,8 +4,11 @@ description: Instance of a subclass of str cannot be compared for equality with cause: Unknown workaround: Unknown """ + + class S(str): pass -s = S('hello') -print(s == 'hello') + +s = S("hello") +print(s == "hello") diff --git a/tests/cpydiff/types_str_subscrstep.py b/tests/cpydiff/types_str_subscrstep.py index 0c2fce1b11..2d3245e558 100644 --- a/tests/cpydiff/types_str_subscrstep.py +++ b/tests/cpydiff/types_str_subscrstep.py @@ -4,4 +4,4 @@ description: Subscript with step != 1 is not yet implemented cause: Unknown workaround: Unknown """ -print('abcdefghi'[0:9:2]) +print("abcdefghi"[0:9:2]) diff --git a/tests/extmod/btree1.py b/tests/extmod/btree1.py index 59638ef0a4..4890d92b42 100644 --- a/tests/extmod/btree1.py +++ b/tests/extmod/btree1.py @@ -6,7 +6,7 @@ except ImportError: print("SKIP") raise SystemExit -#f = open("_test.db", "w+b") +# f = open("_test.db", "w+b") f = uio.BytesIO() db = btree.open(f, pagesize=512) diff --git a/tests/extmod/framebuf1.py b/tests/extmod/framebuf1.py index 2c13665228..c8e0132265 100644 --- a/tests/extmod/framebuf1.py +++ b/tests/extmod/framebuf1.py @@ -8,9 +8,11 @@ w = 5 h = 16 size = w * h // 8 buf = bytearray(size) -maps = {framebuf.MONO_VLSB : 'MONO_VLSB', - framebuf.MONO_HLSB : 'MONO_HLSB', - framebuf.MONO_HMSB : 'MONO_HMSB'} +maps = { + framebuf.MONO_VLSB: "MONO_VLSB", + framebuf.MONO_HLSB: "MONO_HLSB", + framebuf.MONO_HMSB: "MONO_HMSB", +} for mapping in maps.keys(): for x in range(size): @@ -43,33 +45,33 @@ for mapping in maps.keys(): # hline fbuf.fill(0) fbuf.hline(0, 1, w, 1) - print('hline', buf) + print("hline", buf) # vline fbuf.fill(0) fbuf.vline(1, 0, h, 1) - print('vline', buf) + print("vline", buf) # rect fbuf.fill(0) fbuf.rect(1, 1, 3, 3, 1) - print('rect', buf) + print("rect", buf) - #fill rect + # fill rect fbuf.fill(0) - fbuf.fill_rect(0, 0, 0, 3, 1) # zero width, no-operation + fbuf.fill_rect(0, 0, 0, 3, 1) # zero width, no-operation fbuf.fill_rect(1, 1, 3, 3, 1) - print('fill_rect', buf) + print("fill_rect", buf) # line fbuf.fill(0) fbuf.line(1, 1, 3, 3, 1) - print('line', buf) + print("line", buf) # line steep negative gradient fbuf.fill(0) fbuf.line(3, 3, 2, 1, 1) - print('line', buf) + print("line", buf) # scroll fbuf.fill(0) @@ -89,7 +91,7 @@ for mapping in maps.keys(): fbuf.fill(0) fbuf.text("hello", 0, 0, 1) print(buf) - fbuf.text("hello", 0, 0, 0) # clear + fbuf.text("hello", 0, 0, 0) # clear print(buf) # char out of font range set to chr(127) diff --git a/tests/extmod/framebuf16.py b/tests/extmod/framebuf16.py index fe81f7f93f..e658f1345a 100644 --- a/tests/extmod/framebuf16.py +++ b/tests/extmod/framebuf16.py @@ -4,28 +4,30 @@ except ImportError: print("SKIP") raise SystemExit + def printbuf(): print("--8<--") for y in range(h): - print(buf[y * w * 2:(y + 1) * w * 2]) + print(buf[y * w * 2 : (y + 1) * w * 2]) print("-->8--") + w = 4 h = 5 buf = bytearray(w * h * 2) fbuf = framebuf.FrameBuffer(buf, w, h, framebuf.RGB565) # fill -fbuf.fill(0xffff) +fbuf.fill(0xFFFF) printbuf() fbuf.fill(0x0000) printbuf() # put pixel -fbuf.pixel(0, 0, 0xeeee) -fbuf.pixel(3, 0, 0xee00) -fbuf.pixel(0, 4, 0x00ee) -fbuf.pixel(3, 4, 0x0ee0) +fbuf.pixel(0, 0, 0xEEEE) +fbuf.pixel(3, 0, 0xEE00) +fbuf.pixel(0, 4, 0x00EE) +fbuf.pixel(3, 4, 0x0EE0) printbuf() # get pixel @@ -33,7 +35,7 @@ print(fbuf.pixel(0, 4), fbuf.pixel(1, 1)) # scroll fbuf.fill(0x0000) -fbuf.pixel(2, 2, 0xffff) +fbuf.pixel(2, 2, 0xFFFF) printbuf() fbuf.scroll(0, 1) printbuf() @@ -48,11 +50,11 @@ buf2 = bytearray(w2 * h2 * 2) fbuf2 = framebuf.FrameBuffer(buf2, w2, h2, framebuf.RGB565) fbuf2.fill(0x0000) -fbuf2.pixel(0, 0, 0x0ee0) -fbuf2.pixel(0, 2, 0xee00) -fbuf2.pixel(1, 0, 0x00ee) -fbuf2.pixel(1, 2, 0xe00e) -fbuf.fill(0xffff) +fbuf2.pixel(0, 0, 0x0EE0) +fbuf2.pixel(0, 2, 0xEE00) +fbuf2.pixel(1, 0, 0x00EE) +fbuf2.pixel(1, 2, 0xE00E) +fbuf.fill(0xFFFF) fbuf.blit(fbuf2, 3, 3, 0x0000) fbuf.blit(fbuf2, -1, -1, 0x0000) fbuf.blit(fbuf2, 16, 16, 0x0000) diff --git a/tests/extmod/framebuf2.py b/tests/extmod/framebuf2.py index a313170eb5..097057fe96 100644 --- a/tests/extmod/framebuf2.py +++ b/tests/extmod/framebuf2.py @@ -4,14 +4,16 @@ except ImportError: print("SKIP") raise SystemExit + def printbuf(): print("--8<--") for y in range(h): for x in range(w): - print('%u' % ((buf[(x + y * w) // 4] >> ((x & 3) << 1)) & 3), end='') + print("%u" % ((buf[(x + y * w) // 4] >> ((x & 3) << 1)) & 3), end="") print() print("-->8--") + w = 8 h = 5 buf = bytearray(w * h // 4) diff --git a/tests/extmod/framebuf4.py b/tests/extmod/framebuf4.py index 8358fa55b9..56593ee155 100644 --- a/tests/extmod/framebuf4.py +++ b/tests/extmod/framebuf4.py @@ -4,50 +4,52 @@ except ImportError: print("SKIP") raise SystemExit + def printbuf(): print("--8<--") for y in range(h): - print(buf[y * w // 2:(y + 1) * w // 2]) + print(buf[y * w // 2 : (y + 1) * w // 2]) print("-->8--") + w = 16 h = 8 buf = bytearray(w * h // 2) fbuf = framebuf.FrameBuffer(buf, w, h, framebuf.GS4_HMSB) # fill -fbuf.fill(0x0f) +fbuf.fill(0x0F) printbuf() -fbuf.fill(0xa0) +fbuf.fill(0xA0) printbuf() # put pixel fbuf.pixel(0, 0, 0x01) printbuf() -fbuf.pixel(w-1, 0, 0x02) +fbuf.pixel(w - 1, 0, 0x02) printbuf() -fbuf.pixel(w-1, h-1, 0x03) +fbuf.pixel(w - 1, h - 1, 0x03) printbuf() -fbuf.pixel(0, h-1, 0x04) +fbuf.pixel(0, h - 1, 0x04) printbuf() # get pixel -print(fbuf.pixel(0, 0), fbuf.pixel(w-1, 0), fbuf.pixel(w-1, h-1), fbuf.pixel(0, h-1)) -print(fbuf.pixel(1, 0), fbuf.pixel(w-2, 0), fbuf.pixel(w-2, h-1), fbuf.pixel(1, h-1)) +print(fbuf.pixel(0, 0), fbuf.pixel(w - 1, 0), fbuf.pixel(w - 1, h - 1), fbuf.pixel(0, h - 1)) +print(fbuf.pixel(1, 0), fbuf.pixel(w - 2, 0), fbuf.pixel(w - 2, h - 1), fbuf.pixel(1, h - 1)) # fill rect -fbuf.fill_rect(0, 0, w, h, 0x0f) +fbuf.fill_rect(0, 0, w, h, 0x0F) printbuf() -fbuf.fill_rect(0, 0, w, h, 0xf0) -fbuf.fill_rect(1, 0, w//2+1, 1, 0xf1) +fbuf.fill_rect(0, 0, w, h, 0xF0) +fbuf.fill_rect(1, 0, w // 2 + 1, 1, 0xF1) printbuf() -fbuf.fill_rect(1, 0, w//2+1, 1, 0x10) -fbuf.fill_rect(1, 0, w//2, 1, 0xf1) +fbuf.fill_rect(1, 0, w // 2 + 1, 1, 0x10) +fbuf.fill_rect(1, 0, w // 2, 1, 0xF1) printbuf() -fbuf.fill_rect(1, 0, w//2, 1, 0x10) -fbuf.fill_rect(0, h-4, w//2+1, 4, 0xaf) +fbuf.fill_rect(1, 0, w // 2, 1, 0x10) +fbuf.fill_rect(0, h - 4, w // 2 + 1, 4, 0xAF) printbuf() -fbuf.fill_rect(0, h-4, w//2+1, 4, 0xb0) -fbuf.fill_rect(0, h-4, w//2, 4, 0xaf) +fbuf.fill_rect(0, h - 4, w // 2 + 1, 4, 0xB0) +fbuf.fill_rect(0, h - 4, w // 2, 4, 0xAF) printbuf() -fbuf.fill_rect(0, h-4, w//2, 4, 0xb0) +fbuf.fill_rect(0, h - 4, w // 2, 4, 0xB0) diff --git a/tests/extmod/framebuf8.py b/tests/extmod/framebuf8.py index b6899aae91..a3ca6fcd4f 100644 --- a/tests/extmod/framebuf8.py +++ b/tests/extmod/framebuf8.py @@ -4,14 +4,16 @@ except ImportError: print("SKIP") raise SystemExit + def printbuf(): print("--8<--") for y in range(h): for x in range(w): - print('%02x' % buf[(x + y * w)], end='') + print("%02x" % buf[(x + y * w)], end="") print() print("-->8--") + w = 8 h = 5 buf = bytearray(w * h) @@ -25,7 +27,7 @@ printbuf() fbuf.pixel(0, 0, 0x11) fbuf.pixel(w - 1, 0, 0x22) fbuf.pixel(0, h - 1, 0x33) -fbuf.pixel(w - 1, h - 1, 0xff) +fbuf.pixel(w - 1, h - 1, 0xFF) printbuf() # get pixel diff --git a/tests/extmod/framebuf_subclass.py b/tests/extmod/framebuf_subclass.py index 6363c224fb..b429776bc2 100644 --- a/tests/extmod/framebuf_subclass.py +++ b/tests/extmod/framebuf_subclass.py @@ -3,9 +3,10 @@ try: import framebuf except ImportError: - print('SKIP') + print("SKIP") raise SystemExit + class FB(framebuf.FrameBuffer): def __init__(self, n): self.n = n @@ -14,6 +15,7 @@ class FB(framebuf.FrameBuffer): def foo(self): self.hline(0, 2, self.n, 0x0304) + fb = FB(n=3) fb.pixel(0, 0, 0x0102) fb.foo() diff --git a/tests/extmod/machine_pinbase.py b/tests/extmod/machine_pinbase.py index e91775504d..f6b27d1d1d 100644 --- a/tests/extmod/machine_pinbase.py +++ b/tests/extmod/machine_pinbase.py @@ -10,7 +10,6 @@ except AttributeError: class MyPin(machine.PinBase): - def __init__(self): print("__init__") self.v = False @@ -21,6 +20,7 @@ class MyPin(machine.PinBase): self.v = not self.v return int(self.v) + p = MyPin() print(p.value()) diff --git a/tests/extmod/machine_pulse.py b/tests/extmod/machine_pulse.py index d525974e0c..7a8fe14d06 100644 --- a/tests/extmod/machine_pulse.py +++ b/tests/extmod/machine_pulse.py @@ -11,7 +11,6 @@ except AttributeError: class ConstPin(machine.PinBase): - def __init__(self, value): self.v = value @@ -23,7 +22,6 @@ class ConstPin(machine.PinBase): class TogglePin(machine.PinBase): - def __init__(self): self.v = 0 diff --git a/tests/extmod/machine_signal.py b/tests/extmod/machine_signal.py index 53f4f5890c..c453098402 100644 --- a/tests/extmod/machine_signal.py +++ b/tests/extmod/machine_signal.py @@ -11,6 +11,7 @@ except AttributeError: print("SKIP") raise SystemExit + class Pin(machine.PinBase): def __init__(self): self.v = 0 diff --git a/tests/extmod/time_ms_us.py b/tests/extmod/time_ms_us.py index 135cf1e096..0e4749b898 100644 --- a/tests/extmod/time_ms_us.py +++ b/tests/extmod/time_ms_us.py @@ -1,4 +1,5 @@ import utime + try: utime.sleep_ms except AttributeError: diff --git a/tests/extmod/ubinascii_a2b_base64.py b/tests/extmod/ubinascii_a2b_base64.py index 05a3169f3a..2630965e6a 100644 --- a/tests/extmod/ubinascii_a2b_base64.py +++ b/tests/extmod/ubinascii_a2b_base64.py @@ -7,40 +7,40 @@ except ImportError: print("SKIP") raise SystemExit -print(binascii.a2b_base64(b'')) -print(binascii.a2b_base64(b'Zg==')) -print(binascii.a2b_base64(b'Zm8=')) -print(binascii.a2b_base64(b'Zm9v')) -print(binascii.a2b_base64(b'Zm9vYg==')) -print(binascii.a2b_base64(b'Zm9vYmE=')) -print(binascii.a2b_base64(b'Zm9vYmFy')) +print(binascii.a2b_base64(b"")) +print(binascii.a2b_base64(b"Zg==")) +print(binascii.a2b_base64(b"Zm8=")) +print(binascii.a2b_base64(b"Zm9v")) +print(binascii.a2b_base64(b"Zm9vYg==")) +print(binascii.a2b_base64(b"Zm9vYmE=")) +print(binascii.a2b_base64(b"Zm9vYmFy")) -print(binascii.a2b_base64(b'AAECAwQFBgc=')) -print(binascii.a2b_base64(b'CAkKCwwNDg8=')) -print(binascii.a2b_base64(b'f4D/')) -print(binascii.a2b_base64(b'f4D+')) # convert '+' -print(binascii.a2b_base64(b'MTIzNEFCQ0RhYmNk')) +print(binascii.a2b_base64(b"AAECAwQFBgc=")) +print(binascii.a2b_base64(b"CAkKCwwNDg8=")) +print(binascii.a2b_base64(b"f4D/")) +print(binascii.a2b_base64(b"f4D+")) # convert '+' +print(binascii.a2b_base64(b"MTIzNEFCQ0RhYmNk")) # Ignore invalid characters and pad sequences -print(binascii.a2b_base64(b'Zm9v\n')) -print(binascii.a2b_base64(b'Zm\x009v\n')) -print(binascii.a2b_base64(b'Zm9v==')) -print(binascii.a2b_base64(b'Zm9v===')) -print(binascii.a2b_base64(b'Zm9v===YmFy')) +print(binascii.a2b_base64(b"Zm9v\n")) +print(binascii.a2b_base64(b"Zm\x009v\n")) +print(binascii.a2b_base64(b"Zm9v==")) +print(binascii.a2b_base64(b"Zm9v===")) +print(binascii.a2b_base64(b"Zm9v===YmFy")) try: - print(binascii.a2b_base64(b'abc')) + print(binascii.a2b_base64(b"abc")) except ValueError: print("ValueError") try: - print(binascii.a2b_base64(b'abcde=')) + print(binascii.a2b_base64(b"abcde=")) except ValueError: print("ValueError") try: - print(binascii.a2b_base64(b'ab*d')) + print(binascii.a2b_base64(b"ab*d")) except ValueError: print("ValueError") try: - print(binascii.a2b_base64(b'ab=cdef=')) + print(binascii.a2b_base64(b"ab=cdef=")) except ValueError: print("ValueError") diff --git a/tests/extmod/ubinascii_b2a_base64.py b/tests/extmod/ubinascii_b2a_base64.py index f4bb69fe0c..9c100f972b 100644 --- a/tests/extmod/ubinascii_b2a_base64.py +++ b/tests/extmod/ubinascii_b2a_base64.py @@ -7,16 +7,16 @@ except ImportError: print("SKIP") raise SystemExit -print(binascii.b2a_base64(b'')) -print(binascii.b2a_base64(b'f')) -print(binascii.b2a_base64(b'fo')) -print(binascii.b2a_base64(b'foo')) -print(binascii.b2a_base64(b'foob')) -print(binascii.b2a_base64(b'fooba')) -print(binascii.b2a_base64(b'foobar')) +print(binascii.b2a_base64(b"")) +print(binascii.b2a_base64(b"f")) +print(binascii.b2a_base64(b"fo")) +print(binascii.b2a_base64(b"foo")) +print(binascii.b2a_base64(b"foob")) +print(binascii.b2a_base64(b"fooba")) +print(binascii.b2a_base64(b"foobar")) -print(binascii.b2a_base64(b'\x00\x01\x02\x03\x04\x05\x06\x07')) -print(binascii.b2a_base64(b'\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f')) -print(binascii.b2a_base64(b'\x7f\x80\xff')) -print(binascii.b2a_base64(b'1234ABCDabcd')) -print(binascii.b2a_base64(b'\x00\x00>')) # convert into '+' +print(binascii.b2a_base64(b"\x00\x01\x02\x03\x04\x05\x06\x07")) +print(binascii.b2a_base64(b"\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f")) +print(binascii.b2a_base64(b"\x7f\x80\xff")) +print(binascii.b2a_base64(b"1234ABCDabcd")) +print(binascii.b2a_base64(b"\x00\x00>")) # convert into '+' diff --git a/tests/extmod/ubinascii_crc32.py b/tests/extmod/ubinascii_crc32.py index 89664a9b36..8f5f4d9ba5 100644 --- a/tests/extmod/ubinascii_crc32.py +++ b/tests/extmod/ubinascii_crc32.py @@ -13,12 +13,12 @@ except AttributeError: print("SKIP") raise SystemExit -print(hex(binascii.crc32(b'The quick brown fox jumps over the lazy dog'))) -print(hex(binascii.crc32(b'\x00' * 32))) -print(hex(binascii.crc32(b'\xff' * 32))) +print(hex(binascii.crc32(b"The quick brown fox jumps over the lazy dog"))) +print(hex(binascii.crc32(b"\x00" * 32))) +print(hex(binascii.crc32(b"\xff" * 32))) print(hex(binascii.crc32(bytes(range(32))))) -print(hex(binascii.crc32(b' over the lazy dog', binascii.crc32(b'The quick brown fox jumps')))) -print(hex(binascii.crc32(b'\x00' * 16, binascii.crc32(b'\x00' * 16)))) -print(hex(binascii.crc32(b'\xff' * 16, binascii.crc32(b'\xff' * 16)))) +print(hex(binascii.crc32(b" over the lazy dog", binascii.crc32(b"The quick brown fox jumps")))) +print(hex(binascii.crc32(b"\x00" * 16, binascii.crc32(b"\x00" * 16)))) +print(hex(binascii.crc32(b"\xff" * 16, binascii.crc32(b"\xff" * 16)))) print(hex(binascii.crc32(bytes(range(16, 32)), binascii.crc32(bytes(range(16)))))) diff --git a/tests/extmod/ubinascii_hexlify.py b/tests/extmod/ubinascii_hexlify.py index bc99287476..2329f53edd 100644 --- a/tests/extmod/ubinascii_hexlify.py +++ b/tests/extmod/ubinascii_hexlify.py @@ -7,7 +7,7 @@ except ImportError: print("SKIP") raise SystemExit -print(binascii.hexlify(b'\x00\x01\x02\x03\x04\x05\x06\x07')) -print(binascii.hexlify(b'\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f')) -print(binascii.hexlify(b'\x7f\x80\xff')) -print(binascii.hexlify(b'1234ABCDabcd')) +print(binascii.hexlify(b"\x00\x01\x02\x03\x04\x05\x06\x07")) +print(binascii.hexlify(b"\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f")) +print(binascii.hexlify(b"\x7f\x80\xff")) +print(binascii.hexlify(b"1234ABCDabcd")) diff --git a/tests/extmod/ubinascii_micropython.py b/tests/extmod/ubinascii_micropython.py index 77084ec9ee..94e8daa557 100644 --- a/tests/extmod/ubinascii_micropython.py +++ b/tests/extmod/ubinascii_micropython.py @@ -8,8 +8,8 @@ except ImportError: raise SystemExit # two arguments supported in uPy but not CPython -a = binascii.hexlify(b'123', ':') +a = binascii.hexlify(b"123", ":") print(a) # zero length buffer -print(binascii.hexlify(b'', b':')) +print(binascii.hexlify(b"", b":")) diff --git a/tests/extmod/ubinascii_unhexlify.py b/tests/extmod/ubinascii_unhexlify.py index 865abfe3a8..413eaf1b6f 100644 --- a/tests/extmod/ubinascii_unhexlify.py +++ b/tests/extmod/ubinascii_unhexlify.py @@ -7,17 +7,17 @@ except ImportError: print("SKIP") raise SystemExit -print(binascii.unhexlify(b'0001020304050607')) -print(binascii.unhexlify(b'08090a0b0c0d0e0f')) -print(binascii.unhexlify(b'7f80ff')) -print(binascii.unhexlify(b'313233344142434461626364')) +print(binascii.unhexlify(b"0001020304050607")) +print(binascii.unhexlify(b"08090a0b0c0d0e0f")) +print(binascii.unhexlify(b"7f80ff")) +print(binascii.unhexlify(b"313233344142434461626364")) try: - a = binascii.unhexlify(b'0') # odd buffer length + a = binascii.unhexlify(b"0") # odd buffer length except ValueError: - print('ValueError') + print("ValueError") try: - a = binascii.unhexlify(b'gg') # digit not hex + a = binascii.unhexlify(b"gg") # digit not hex except ValueError: - print('ValueError') + print("ValueError") diff --git a/tests/extmod/ucryptolib_aes128_cbc.py b/tests/extmod/ucryptolib_aes128_cbc.py index 4c5ea6acb2..d861d2c6bf 100644 --- a/tests/extmod/ucryptolib_aes128_cbc.py +++ b/tests/extmod/ucryptolib_aes128_cbc.py @@ -1,5 +1,6 @@ try: from Crypto.Cipher import AES + aes = AES.new except ImportError: try: diff --git a/tests/extmod/ucryptolib_aes128_ecb.py b/tests/extmod/ucryptolib_aes128_ecb.py index 89451b282c..5c0e179986 100644 --- a/tests/extmod/ucryptolib_aes128_ecb.py +++ b/tests/extmod/ucryptolib_aes128_ecb.py @@ -1,5 +1,6 @@ try: from Crypto.Cipher import AES + aes = AES.new except ImportError: try: diff --git a/tests/extmod/ucryptolib_aes128_ecb_enc.py b/tests/extmod/ucryptolib_aes128_ecb_enc.py index 55b676d361..1d4484b0bc 100644 --- a/tests/extmod/ucryptolib_aes128_ecb_enc.py +++ b/tests/extmod/ucryptolib_aes128_ecb_enc.py @@ -3,6 +3,7 @@ # is optional). try: from Crypto.Cipher import AES + aes = AES.new except ImportError: try: diff --git a/tests/extmod/ucryptolib_aes256_cbc.py b/tests/extmod/ucryptolib_aes256_cbc.py index a907f26e26..c01846f199 100644 --- a/tests/extmod/ucryptolib_aes256_cbc.py +++ b/tests/extmod/ucryptolib_aes256_cbc.py @@ -1,5 +1,6 @@ try: from Crypto.Cipher import AES + aes = AES.new except ImportError: try: diff --git a/tests/extmod/ucryptolib_aes256_ecb.py b/tests/extmod/ucryptolib_aes256_ecb.py index 326383a454..0760063c14 100644 --- a/tests/extmod/ucryptolib_aes256_ecb.py +++ b/tests/extmod/ucryptolib_aes256_ecb.py @@ -1,5 +1,6 @@ try: from Crypto.Cipher import AES + aes = AES.new except ImportError: try: diff --git a/tests/extmod/uctypes_32bit_intbig.py b/tests/extmod/uctypes_32bit_intbig.py index 6b4d3d76cd..eed36e8774 100644 --- a/tests/extmod/uctypes_32bit_intbig.py +++ b/tests/extmod/uctypes_32bit_intbig.py @@ -10,16 +10,16 @@ buf = b"12345678abcd" struct = uctypes.struct( uctypes.addressof(buf), {"f32": uctypes.UINT32 | 0, "f64": uctypes.UINT64 | 4}, - uctypes.LITTLE_ENDIAN + uctypes.LITTLE_ENDIAN, ) -struct.f32 = 0x7fffffff +struct.f32 = 0x7FFFFFFF print(buf) struct.f32 = 0x80000000 print(buf) -struct.f32 = 0xff010203 +struct.f32 = 0xFF010203 print(buf) struct.f64 = 0x80000000 @@ -34,16 +34,16 @@ buf = b"12345678abcd" struct = uctypes.struct( uctypes.addressof(buf), {"f32": uctypes.UINT32 | 0, "f64": uctypes.UINT64 | 4}, - uctypes.BIG_ENDIAN + uctypes.BIG_ENDIAN, ) -struct.f32 = 0x7fffffff +struct.f32 = 0x7FFFFFFF print(buf) struct.f32 = 0x80000000 print(buf) -struct.f32 = 0xff010203 +struct.f32 = 0xFF010203 print(buf) struct.f64 = 0x80000000 diff --git a/tests/extmod/uctypes_array_assign_le.py b/tests/extmod/uctypes_array_assign_le.py index 6afa7e0a24..d822faf7e8 100644 --- a/tests/extmod/uctypes_array_assign_le.py +++ b/tests/extmod/uctypes_array_assign_le.py @@ -10,19 +10,17 @@ desc = { # arr2 is array at offset 0, size 2, of structures defined recursively "arr2": (uctypes.ARRAY | 0, 2, {"b": uctypes.UINT8 | 0}), "arr3": (uctypes.ARRAY | 2, uctypes.UINT16 | 2), - # aligned "arr5": (uctypes.ARRAY | 0, uctypes.UINT32 | 1), # unaligned "arr6": (uctypes.ARRAY | 1, uctypes.UINT32 | 1), - "arr7": (uctypes.ARRAY | 0, 1, {"l": uctypes.UINT32 | 0}), - "arr8": (uctypes.ARRAY | 1, 1, {"l": uctypes.UINT32 | 0}) + "arr8": (uctypes.ARRAY | 1, 1, {"l": uctypes.UINT32 | 0}), } data = bytearray(5) -S = uctypes.struct(uctypes.addressof(data), desc, uctypes.LITTLE_ENDIAN) +S = uctypes.struct(uctypes.addressof(data), desc, uctypes.LITTLE_ENDIAN) # assign byte S.arr[0] = 0x11 @@ -55,4 +53,3 @@ assert hex(S.arr6[0]) == "0xaabbccdd" print(S.arr6[0] == S.arr8[0].l) assert S.arr6[0] == S.arr8[0].l - diff --git a/tests/extmod/uctypes_array_assign_native_le.py b/tests/extmod/uctypes_array_assign_native_le.py index a538bf9add..d4c27fc4b3 100644 --- a/tests/extmod/uctypes_array_assign_native_le.py +++ b/tests/extmod/uctypes_array_assign_native_le.py @@ -1,4 +1,5 @@ import sys + try: import uctypes except ImportError: @@ -15,16 +16,14 @@ desc = { # arr2 is array at offset 0, size 2, of structures defined recursively "arr2": (uctypes.ARRAY | 0, 2, {"b": uctypes.UINT8 | 0}), "arr3": (uctypes.ARRAY | 2, uctypes.UINT16 | 2), - # aligned "arr5": (uctypes.ARRAY | 0, uctypes.UINT32 | 1), "arr7": (uctypes.ARRAY | 0, 1, {"l": uctypes.UINT32 | 0}), - "arr8": (uctypes.ARRAY | 0, uctypes.INT8 | 1), "arr9": (uctypes.ARRAY | 0, uctypes.INT16 | 1), "arr10": (uctypes.ARRAY | 0, uctypes.INT32 | 1), "arr11": (uctypes.ARRAY | 0, uctypes.INT64 | 1), - "arr12": (uctypes.ARRAY | 0, uctypes.UINT64| 1), + "arr12": (uctypes.ARRAY | 0, uctypes.UINT64 | 1), "arr13": (uctypes.ARRAY | 1, 1, {"l": {}}), } diff --git a/tests/extmod/uctypes_array_assign_native_le_intbig.py b/tests/extmod/uctypes_array_assign_native_le_intbig.py index 84dfba0e29..f33c63b4ef 100644 --- a/tests/extmod/uctypes_array_assign_native_le_intbig.py +++ b/tests/extmod/uctypes_array_assign_native_le_intbig.py @@ -1,4 +1,5 @@ import sys + try: import uctypes except ImportError: @@ -15,16 +16,14 @@ desc = { # arr2 is array at offset 0, size 2, of structures defined recursively "arr2": (uctypes.ARRAY | 0, 2, {"b": uctypes.UINT8 | 0}), "arr3": (uctypes.ARRAY | 2, uctypes.UINT16 | 2), - # aligned "arr5": (uctypes.ARRAY | 0, uctypes.UINT32 | 1), "arr7": (uctypes.ARRAY | 0, 1, {"l": uctypes.UINT32 | 0}), - "arr8": (uctypes.ARRAY | 0, uctypes.INT8 | 1), "arr9": (uctypes.ARRAY | 0, uctypes.INT16 | 1), "arr10": (uctypes.ARRAY | 0, uctypes.INT32 | 1), "arr11": (uctypes.ARRAY | 0, uctypes.INT64 | 1), - "arr12": (uctypes.ARRAY | 0, uctypes.UINT64| 1), + "arr12": (uctypes.ARRAY | 0, uctypes.UINT64 | 1), "arr13": (uctypes.ARRAY | 1, 1, {"l": {}}), } diff --git a/tests/extmod/uctypes_byteat.py b/tests/extmod/uctypes_byteat.py index ab2535db8f..0619d31dc9 100644 --- a/tests/extmod/uctypes_byteat.py +++ b/tests/extmod/uctypes_byteat.py @@ -4,7 +4,7 @@ except ImportError: print("SKIP") raise SystemExit -data = bytearray(b'01234567') +data = bytearray(b"01234567") -print(uctypes.bytes_at(uctypes.addressof(data), 4)) -print(uctypes.bytearray_at(uctypes.addressof(data), 4)) +print(uctypes.bytes_at(uctypes.addressof(data), 4)) +print(uctypes.bytearray_at(uctypes.addressof(data), 4)) diff --git a/tests/extmod/uctypes_error.py b/tests/extmod/uctypes_error.py index 68106ac782..d429562615 100644 --- a/tests/extmod/uctypes_error.py +++ b/tests/extmod/uctypes_error.py @@ -9,35 +9,35 @@ except ImportError: data = bytearray(b"01234567") # del subscr not supported -S = uctypes.struct(uctypes.addressof(data), {}) +S = uctypes.struct(uctypes.addressof(data), {}) try: del S[0] except TypeError: - print('TypeError') + print("TypeError") # list is an invalid descriptor -S = uctypes.struct(uctypes.addressof(data), []) +S = uctypes.struct(uctypes.addressof(data), []) try: - S.x + S.x except TypeError: - print('TypeError') + print("TypeError") # can't access attribute with invalid descriptor -S = uctypes.struct(uctypes.addressof(data), {'x':[]}) +S = uctypes.struct(uctypes.addressof(data), {"x": []}) try: - S.x + S.x except TypeError: - print('TypeError') + print("TypeError") # can't assign to aggregate -S = uctypes.struct(uctypes.addressof(data), {'x':(uctypes.ARRAY | 0, uctypes.INT8 | 2)}) +S = uctypes.struct(uctypes.addressof(data), {"x": (uctypes.ARRAY | 0, uctypes.INT8 | 2)}) try: - S.x = 1 + S.x = 1 except TypeError: - print('TypeError') + print("TypeError") # unsupported unary op try: hash(S) except TypeError: - print('TypeError') + print("TypeError") diff --git a/tests/extmod/uctypes_le.py b/tests/extmod/uctypes_le.py index 7df5ac0909..466191c27a 100644 --- a/tests/extmod/uctypes_le.py +++ b/tests/extmod/uctypes_le.py @@ -6,20 +6,21 @@ except ImportError: desc = { "s0": uctypes.UINT16 | 0, - "sub": (0, { - "b0": uctypes.UINT8 | 0, - "b1": uctypes.UINT8 | 1, - }), + "sub": ( + 0, + { + "b0": uctypes.UINT8 | 0, + "b1": uctypes.UINT8 | 1, + }, + ), "arr": (uctypes.ARRAY | 0, uctypes.UINT8 | 2), "arr2": (uctypes.ARRAY | 0, 2, {"b": uctypes.UINT8 | 0}), "bitf0": uctypes.BFUINT16 | 0 | 0 << uctypes.BF_POS | 8 << uctypes.BF_LEN, "bitf1": uctypes.BFUINT16 | 0 | 8 << uctypes.BF_POS | 8 << uctypes.BF_LEN, - - "bf0": uctypes.BFUINT16 | 0 | 0 << uctypes.BF_POS | 4 << uctypes.BF_LEN, - "bf1": uctypes.BFUINT16 | 0 | 4 << uctypes.BF_POS | 4 << uctypes.BF_LEN, - "bf2": uctypes.BFUINT16 | 0 | 8 << uctypes.BF_POS | 4 << uctypes.BF_LEN, + "bf0": uctypes.BFUINT16 | 0 | 0 << uctypes.BF_POS | 4 << uctypes.BF_LEN, + "bf1": uctypes.BFUINT16 | 0 | 4 << uctypes.BF_POS | 4 << uctypes.BF_LEN, + "bf2": uctypes.BFUINT16 | 0 | 8 << uctypes.BF_POS | 4 << uctypes.BF_LEN, "bf3": uctypes.BFUINT16 | 0 | 12 << uctypes.BF_POS | 4 << uctypes.BF_LEN, - "ptr": (uctypes.PTR | 0, uctypes.UINT8), "ptr2": (uctypes.PTR | 0, {"b": uctypes.UINT8 | 0}), } @@ -28,10 +29,10 @@ data = bytearray(b"01") S = uctypes.struct(uctypes.addressof(data), desc, uctypes.LITTLE_ENDIAN) -#print(S) +# print(S) print(hex(S.s0)) assert hex(S.s0) == "0x3130" -#print(S.sub.b0) +# print(S.sub.b0) print(S.sub.b0, S.sub.b1) assert S.sub.b0, S.sub.b1 == (0x30, 0x31) @@ -73,7 +74,7 @@ assert bytes(data) == b"2Q" desc2 = { "bf8": uctypes.BFUINT8 | 0 | 0 << uctypes.BF_POS | 4 << uctypes.BF_LEN, - "bf32": uctypes.BFUINT32 | 0 | 20 << uctypes.BF_POS | 4 << uctypes.BF_LEN + "bf32": uctypes.BFUINT32 | 0 | 20 << uctypes.BF_POS | 4 << uctypes.BF_LEN, } data2 = bytearray(b"0123") diff --git a/tests/extmod/uctypes_le_float.py b/tests/extmod/uctypes_le_float.py index 84ff2b84cf..89e9a9e0ab 100644 --- a/tests/extmod/uctypes_le_float.py +++ b/tests/extmod/uctypes_le_float.py @@ -7,7 +7,7 @@ except ImportError: desc = { "f32": uctypes.FLOAT32 | 0, "f64": uctypes.FLOAT64 | 0, - "uf64": uctypes.FLOAT64 | 2, # unaligned + "uf64": uctypes.FLOAT64 | 2, # unaligned } data = bytearray(10) @@ -15,10 +15,10 @@ data = bytearray(10) S = uctypes.struct(uctypes.addressof(data), desc, uctypes.LITTLE_ENDIAN) S.f32 = 12.34 -print('%.4f' % S.f32) +print("%.4f" % S.f32) S.f64 = 12.34 -print('%.4f' % S.f64) +print("%.4f" % S.f64) S.uf64 = 12.34 -print('%.4f' % S.uf64) +print("%.4f" % S.uf64) diff --git a/tests/extmod/uctypes_native_float.py b/tests/extmod/uctypes_native_float.py index acef47036d..e7d3ddabd9 100644 --- a/tests/extmod/uctypes_native_float.py +++ b/tests/extmod/uctypes_native_float.py @@ -14,7 +14,7 @@ data = bytearray(8) S = uctypes.struct(uctypes.addressof(data), desc, uctypes.NATIVE) S.f32 = 12.34 -print('%.4f' % S.f32) +print("%.4f" % S.f32) S.f64 = 12.34 -print('%.4f' % S.f64) +print("%.4f" % S.f64) diff --git a/tests/extmod/uctypes_native_le.py b/tests/extmod/uctypes_native_le.py index 8bba03b38c..10477e6694 100644 --- a/tests/extmod/uctypes_native_le.py +++ b/tests/extmod/uctypes_native_le.py @@ -2,6 +2,7 @@ # Codepaths for packed vs native structures are different. This test only works # on little-endian machine (no matter if 32 or 64 bit). import sys + try: import uctypes except ImportError: @@ -15,20 +16,21 @@ if sys.byteorder != "little": desc = { "s0": uctypes.UINT16 | 0, - "sub": (0, { - "b0": uctypes.UINT8 | 0, - "b1": uctypes.UINT8 | 1, - }), + "sub": ( + 0, + { + "b0": uctypes.UINT8 | 0, + "b1": uctypes.UINT8 | 1, + }, + ), "arr": (uctypes.ARRAY | 0, uctypes.UINT8 | 2), "arr2": (uctypes.ARRAY | 0, 2, {"b": uctypes.UINT8 | 0}), "bitf0": uctypes.BFUINT16 | 0 | 0 << uctypes.BF_POS | 8 << uctypes.BF_LEN, "bitf1": uctypes.BFUINT16 | 0 | 8 << uctypes.BF_POS | 8 << uctypes.BF_LEN, - - "bf0": uctypes.BFUINT16 | 0 | 0 << uctypes.BF_POS | 4 << uctypes.BF_LEN, - "bf1": uctypes.BFUINT16 | 0 | 4 << uctypes.BF_POS | 4 << uctypes.BF_LEN, - "bf2": uctypes.BFUINT16 | 0 | 8 << uctypes.BF_POS | 4 << uctypes.BF_LEN, + "bf0": uctypes.BFUINT16 | 0 | 0 << uctypes.BF_POS | 4 << uctypes.BF_LEN, + "bf1": uctypes.BFUINT16 | 0 | 4 << uctypes.BF_POS | 4 << uctypes.BF_LEN, + "bf2": uctypes.BFUINT16 | 0 | 8 << uctypes.BF_POS | 4 << uctypes.BF_LEN, "bf3": uctypes.BFUINT16 | 0 | 12 << uctypes.BF_POS | 4 << uctypes.BF_LEN, - "ptr": (uctypes.PTR | 0, uctypes.UINT8), "ptr2": (uctypes.PTR | 0, {"b": uctypes.UINT8 | 0}), } @@ -37,10 +39,10 @@ data = bytearray(b"01") S = uctypes.struct(uctypes.addressof(data), desc, uctypes.NATIVE) -#print(S) +# print(S) print(hex(S.s0)) assert hex(S.s0) == "0x3130" -#print(S.sub.b0) +# print(S.sub.b0) print(S.sub.b0, S.sub.b1) assert S.sub.b0, S.sub.b1 == (0x30, 0x31) @@ -81,7 +83,7 @@ assert bytes(data) == b"2Q" desc2 = { "bf8": uctypes.BFUINT8 | 0 | 0 << uctypes.BF_POS | 4 << uctypes.BF_LEN, - "bf32": uctypes.BFUINT32 | 0 | 20 << uctypes.BF_POS | 4 << uctypes.BF_LEN + "bf32": uctypes.BFUINT32 | 0 | 20 << uctypes.BF_POS | 4 << uctypes.BF_LEN, } data2 = bytearray(b"0123") diff --git a/tests/extmod/uctypes_print.py b/tests/extmod/uctypes_print.py index c310238e54..6e0018abc7 100644 --- a/tests/extmod/uctypes_print.py +++ b/tests/extmod/uctypes_print.py @@ -16,10 +16,10 @@ desc2 = [(uctypes.ARRAY | 0, uctypes.UINT8 | 1)] S2 = uctypes.struct(0, desc2) print(S2) -desc3 = ((uctypes.ARRAY | 0, uctypes.UINT8 | 1)) +desc3 = (uctypes.ARRAY | 0, uctypes.UINT8 | 1) S3 = uctypes.struct(0, desc3) print(S3) -desc4 = ((uctypes.PTR | 0, uctypes.UINT8 | 1)) +desc4 = (uctypes.PTR | 0, uctypes.UINT8 | 1) S4 = uctypes.struct(0, desc4) print(S4) diff --git a/tests/extmod/uctypes_ptr_le.py b/tests/extmod/uctypes_ptr_le.py index fc625f4227..5d8094ee48 100644 --- a/tests/extmod/uctypes_ptr_le.py +++ b/tests/extmod/uctypes_ptr_le.py @@ -1,4 +1,5 @@ import sys + try: import uctypes except ImportError: @@ -32,6 +33,6 @@ assert S.ptr[1] == ord("1") print(hex(S.ptr16[0])) assert hex(S.ptr16[0]) == "0x3130" print(S.ptr2[0].b, S.ptr2[1].b) -print (S.ptr2[0].b, S.ptr2[1].b) +print(S.ptr2[0].b, S.ptr2[1].b) print(hex(S.ptr16[0])) assert (S.ptr2[0].b, S.ptr2[1].b) == (48, 49) diff --git a/tests/extmod/uctypes_ptr_native_le.py b/tests/extmod/uctypes_ptr_native_le.py index 24508b1cb4..8ca4d2c55c 100644 --- a/tests/extmod/uctypes_ptr_native_le.py +++ b/tests/extmod/uctypes_ptr_native_le.py @@ -1,4 +1,5 @@ import sys + try: import uctypes except ImportError: @@ -30,6 +31,6 @@ assert S.ptr[1] == ord("1") print(hex(S.ptr16[0])) assert hex(S.ptr16[0]) == "0x3130" print(S.ptr2[0].b, S.ptr2[1].b) -print (S.ptr2[0].b, S.ptr2[1].b) +print(S.ptr2[0].b, S.ptr2[1].b) print(hex(S.ptr16[0])) assert (S.ptr2[0].b, S.ptr2[1].b) == (48, 49) diff --git a/tests/extmod/uctypes_sizeof.py b/tests/extmod/uctypes_sizeof.py index e42e06c924..6e52232e39 100644 --- a/tests/extmod/uctypes_sizeof.py +++ b/tests/extmod/uctypes_sizeof.py @@ -11,10 +11,13 @@ desc = { "arr2": (uctypes.ARRAY | 0, 2, {"b": uctypes.UINT8 | 0}), "arr3": (uctypes.ARRAY | 2, uctypes.UINT16 | 2), "arr4": (uctypes.ARRAY | 0, 2, {"b": uctypes.UINT8 | 0, "w": uctypes.UINT16 | 1}), - "sub": (0, { - 'b1': uctypes.BFUINT8 | 0 | 4 << uctypes.BF_POS | 4 << uctypes.BF_LEN, - 'b2': uctypes.BFUINT8 | 0 | 0 << uctypes.BF_POS | 4 << uctypes.BF_LEN, - }), + "sub": ( + 0, + { + "b1": uctypes.BFUINT8 | 0 | 4 << uctypes.BF_POS | 4 << uctypes.BF_LEN, + "b2": uctypes.BFUINT8 | 0 | 0 << uctypes.BF_POS | 4 << uctypes.BF_LEN, + }, + ), } data = bytearray(b"01234567") diff --git a/tests/extmod/uctypes_sizeof_float.py b/tests/extmod/uctypes_sizeof_float.py index 1ba8871bdc..351632d76b 100644 --- a/tests/extmod/uctypes_sizeof_float.py +++ b/tests/extmod/uctypes_sizeof_float.py @@ -4,5 +4,5 @@ except ImportError: print("SKIP") raise SystemExit -print(uctypes.sizeof({'f':uctypes.FLOAT32})) -print(uctypes.sizeof({'f':uctypes.FLOAT64})) +print(uctypes.sizeof({"f": uctypes.FLOAT32})) +print(uctypes.sizeof({"f": uctypes.FLOAT64})) diff --git a/tests/extmod/uctypes_sizeof_native.py b/tests/extmod/uctypes_sizeof_native.py index 32c740e773..991cd25f52 100644 --- a/tests/extmod/uctypes_sizeof_native.py +++ b/tests/extmod/uctypes_sizeof_native.py @@ -28,10 +28,13 @@ S5 = { "b": uctypes.UINT32 | 4, "c": uctypes.UINT8 | 8, "d": uctypes.UINT32 | 0, - "sub": (4, { - "b0": uctypes.UINT8 | 0, - "b1": uctypes.UINT8 | 1, - }), + "sub": ( + 4, + { + "b0": uctypes.UINT8 | 0, + "b1": uctypes.UINT8 | 1, + }, + ), } assert uctypes.sizeof(S5) == 12 diff --git a/tests/extmod/uctypes_sizeof_od.py b/tests/extmod/uctypes_sizeof_od.py index 192ee91528..2f070095b5 100644 --- a/tests/extmod/uctypes_sizeof_od.py +++ b/tests/extmod/uctypes_sizeof_od.py @@ -5,18 +5,23 @@ except ImportError: print("SKIP") raise SystemExit -desc = OrderedDict({ - # arr is array at offset 0, of UINT8 elements, array size is 2 - "arr": (uctypes.ARRAY | 0, uctypes.UINT8 | 2), - # arr2 is array at offset 0, size 2, of structures defined recursively - "arr2": (uctypes.ARRAY | 0, 2, {"b": uctypes.UINT8 | 0}), - "arr3": (uctypes.ARRAY | 2, uctypes.UINT16 | 2), - "arr4": (uctypes.ARRAY | 0, 2, {"b": uctypes.UINT8 | 0, "w": uctypes.UINT16 | 1}), - "sub": (0, { - 'b1': uctypes.BFUINT8 | 0 | 4 << uctypes.BF_POS | 4 << uctypes.BF_LEN, - 'b2': uctypes.BFUINT8 | 0 | 0 << uctypes.BF_POS | 4 << uctypes.BF_LEN, - }), -}) +desc = OrderedDict( + { + # arr is array at offset 0, of UINT8 elements, array size is 2 + "arr": (uctypes.ARRAY | 0, uctypes.UINT8 | 2), + # arr2 is array at offset 0, size 2, of structures defined recursively + "arr2": (uctypes.ARRAY | 0, 2, {"b": uctypes.UINT8 | 0}), + "arr3": (uctypes.ARRAY | 2, uctypes.UINT16 | 2), + "arr4": (uctypes.ARRAY | 0, 2, {"b": uctypes.UINT8 | 0, "w": uctypes.UINT16 | 1}), + "sub": ( + 0, + { + "b1": uctypes.BFUINT8 | 0 | 4 << uctypes.BF_POS | 4 << uctypes.BF_LEN, + "b2": uctypes.BFUINT8 | 0 | 0 << uctypes.BF_POS | 4 << uctypes.BF_LEN, + }, + ), + } +) data = bytearray(b"01234567") diff --git a/tests/extmod/uhashlib_md5.py b/tests/extmod/uhashlib_md5.py index 10b6d054e7..07d5f31692 100644 --- a/tests/extmod/uhashlib_md5.py +++ b/tests/extmod/uhashlib_md5.py @@ -16,6 +16,6 @@ except AttributeError: print("SKIP") raise SystemExit -md5 = hashlib.md5(b'hello') -md5.update(b'world') +md5 = hashlib.md5(b"hello") +md5.update(b"world") print(md5.digest()) diff --git a/tests/extmod/uhashlib_sha1.py b/tests/extmod/uhashlib_sha1.py index 4f7066899a..a573121316 100644 --- a/tests/extmod/uhashlib_sha1.py +++ b/tests/extmod/uhashlib_sha1.py @@ -16,6 +16,6 @@ except AttributeError: print("SKIP") raise SystemExit -sha1 = hashlib.sha1(b'hello') -sha1.update(b'world') +sha1 = hashlib.sha1(b"hello") +sha1.update(b"world") print(sha1.digest()) diff --git a/tests/extmod/uhashlib_sha256.py b/tests/extmod/uhashlib_sha256.py index 676d479794..2e6df7df13 100644 --- a/tests/extmod/uhashlib_sha256.py +++ b/tests/extmod/uhashlib_sha256.py @@ -27,12 +27,12 @@ print(hashlib.sha256(b"\xff" * 64).digest()) print(hashlib.sha256(b"\xff" * 56).digest()) # TODO: running .digest() several times in row is not supported() -#h = hashlib.sha256(b'123') -#print(h.digest()) -#print(h.digest()) +# h = hashlib.sha256(b'123') +# print(h.digest()) +# print(h.digest()) # TODO: partial digests are not supported -#h = hashlib.sha256(b'123') -#print(h.digest()) -#h.update(b'456') -#print(h.digest()) +# h = hashlib.sha256(b'123') +# print(h.digest()) +# h.update(b'456') +# print(h.digest()) diff --git a/tests/extmod/uheapq1.py b/tests/extmod/uheapq1.py index 7c1fe4e1ec..a470bb6f71 100644 --- a/tests/extmod/uheapq1.py +++ b/tests/extmod/uheapq1.py @@ -17,11 +17,13 @@ try: except TypeError: print("TypeError") + def pop_and_print(h): l = [] while h: l.append(str(heapq.heappop(h))) - print(' '.join(l)) + print(" ".join(l)) + h = [] heapq.heappush(h, 3) diff --git a/tests/extmod/ujson_dump.py b/tests/extmod/ujson_dump.py index b1cb4a9cbc..feda8a47dd 100644 --- a/tests/extmod/ujson_dump.py +++ b/tests/extmod/ujson_dump.py @@ -20,11 +20,11 @@ print(s.getvalue()) # dump to a small-int not allowed try: json.dump(123, 1) -except (AttributeError, OSError): # CPython and uPy have different errors - print('Exception') +except (AttributeError, OSError): # CPython and uPy have different errors + print("Exception") # dump to an object not allowed try: json.dump(123, {}) -except (AttributeError, OSError): # CPython and uPy have different errors - print('Exception') +except (AttributeError, OSError): # CPython and uPy have different errors + print("Exception") diff --git a/tests/extmod/ujson_dump_iobase.py b/tests/extmod/ujson_dump_iobase.py index 51d507cd1a..7ecf23afb6 100644 --- a/tests/extmod/ujson_dump_iobase.py +++ b/tests/extmod/ujson_dump_iobase.py @@ -7,27 +7,28 @@ except ImportError: try: import io, json except ImportError: - print('SKIP') + print("SKIP") raise SystemExit -if not hasattr(io, 'IOBase'): - print('SKIP') +if not hasattr(io, "IOBase"): + print("SKIP") raise SystemExit # a user stream that only has the write method class S(io.IOBase): def __init__(self): - self.buf = '' + self.buf = "" + def write(self, buf): if type(buf) == bytearray: # uPy passes a bytearray, CPython passes a str - buf = str(buf, 'ascii') + buf = str(buf, "ascii") self.buf += buf return len(buf) # dump to the user stream s = S() -json.dump([123, {}], s) +json.dump([123, {}], s) print(s.buf) diff --git a/tests/extmod/ujson_dumps.py b/tests/extmod/ujson_dumps.py index d732718019..bfdae62643 100644 --- a/tests/extmod/ujson_dumps.py +++ b/tests/extmod/ujson_dumps.py @@ -11,8 +11,8 @@ print(json.dumps(False)) print(json.dumps(True)) print(json.dumps(None)) print(json.dumps(1)) -print(json.dumps('abc')) -print(json.dumps('\x00\x01\x7e')) +print(json.dumps("abc")) +print(json.dumps("\x00\x01\x7e")) print(json.dumps([])) print(json.dumps([1])) print(json.dumps([1, 2])) @@ -22,7 +22,7 @@ print(json.dumps((1,))) print(json.dumps((1, 2))) print(json.dumps((1, (2, 3)))) print(json.dumps({})) -print(json.dumps({"a":1})) -print(json.dumps({"a":(2,[3,None])})) +print(json.dumps({"a": 1})) +print(json.dumps({"a": (2, [3, None])})) print(json.dumps('"quoted"')) -print(json.dumps('space\n\r\tspace')) +print(json.dumps("space\n\r\tspace")) diff --git a/tests/extmod/ujson_dumps_extra.py b/tests/extmod/ujson_dumps_extra.py index 21a388c32d..f2aa7f249f 100644 --- a/tests/extmod/ujson_dumps_extra.py +++ b/tests/extmod/ujson_dumps_extra.py @@ -6,4 +6,4 @@ except ImportError: print("SKIP") raise SystemExit -print(ujson.dumps(b'1234')) +print(ujson.dumps(b"1234")) diff --git a/tests/extmod/ujson_load.py b/tests/extmod/ujson_load.py index 9725ab2ddc..7cec9246b8 100644 --- a/tests/extmod/ujson_load.py +++ b/tests/extmod/ujson_load.py @@ -9,7 +9,7 @@ except: print("SKIP") raise SystemExit -print(json.load(StringIO('null'))) +print(json.load(StringIO("null"))) print(json.load(StringIO('"abc\\u0064e"'))) -print(json.load(StringIO('[false, true, 1, -2]'))) +print(json.load(StringIO("[false, true, 1, -2]"))) print(json.load(StringIO('{"a":true}'))) diff --git a/tests/extmod/ujson_loads.py b/tests/extmod/ujson_loads.py index adba3c068d..2de9cdcbc1 100644 --- a/tests/extmod/ujson_loads.py +++ b/tests/extmod/ujson_loads.py @@ -7,23 +7,25 @@ except ImportError: print("SKIP") raise SystemExit + def my_print(o): if isinstance(o, dict): - print('sorted dict', sorted(o.items())) + print("sorted dict", sorted(o.items())) else: print(o) -my_print(json.loads('null')) -my_print(json.loads('false')) -my_print(json.loads('true')) -my_print(json.loads('1')) -my_print(json.loads('-2')) + +my_print(json.loads("null")) +my_print(json.loads("false")) +my_print(json.loads("true")) +my_print(json.loads("1")) +my_print(json.loads("-2")) my_print(json.loads('"abc\\u0064e"')) -my_print(json.loads('[]')) -my_print(json.loads('[null]')) -my_print(json.loads('[null,false,true]')) -my_print(json.loads(' [ null , false , true ] ')) -my_print(json.loads('{}')) +my_print(json.loads("[]")) +my_print(json.loads("[null]")) +my_print(json.loads("[null,false,true]")) +my_print(json.loads(" [ null , false , true ] ")) +my_print(json.loads("{}")) my_print(json.loads('{"a":true}')) my_print(json.loads('{"a":null, "b":false, "c":true}')) my_print(json.loads('{"a":[], "b":[1], "c":{"3":4}}')) @@ -39,36 +41,36 @@ my_print(json.loads('{\n\t"a":[]\r\n, "b":[1], "c":{"3":4} \n\r\t\r\r\r\n}') # loading nothing should raise exception try: - json.loads('') + json.loads("") except ValueError: - print('ValueError') + print("ValueError") # string which is not closed try: my_print(json.loads('"abc')) except ValueError: - print('ValueError') + print("ValueError") # unaccompanied closing brace try: - my_print(json.loads(']')) + my_print(json.loads("]")) except ValueError: - print('ValueError') + print("ValueError") # unspecified object type try: - my_print(json.loads('a')) + my_print(json.loads("a")) except ValueError: - print('ValueError') + print("ValueError") # bad property name try: my_print(json.loads('{{}:"abc"}')) except ValueError: - print('ValueError') + print("ValueError") # unexpected characters after white space try: - my_print(json.loads('[null] a')) + my_print(json.loads("[null] a")) except ValueError: - print('ValueError') + print("ValueError") diff --git a/tests/extmod/ujson_loads_float.py b/tests/extmod/ujson_loads_float.py index f1b8cc364c..e368ca42e7 100644 --- a/tests/extmod/ujson_loads_float.py +++ b/tests/extmod/ujson_loads_float.py @@ -7,11 +7,13 @@ except ImportError: print("SKIP") raise SystemExit -def my_print(o): - print('%.3f' % o) -my_print(json.loads('1.2')) -my_print(json.loads('1e2')) -my_print(json.loads('-2.3')) -my_print(json.loads('-2e3')) -my_print(json.loads('-2e-3')) +def my_print(o): + print("%.3f" % o) + + +my_print(json.loads("1.2")) +my_print(json.loads("1e2")) +my_print(json.loads("-2.3")) +my_print(json.loads("-2e3")) +my_print(json.loads("-2e-3")) diff --git a/tests/extmod/urandom_basic.py b/tests/extmod/urandom_basic.py index 57e6b26cba..180197398f 100644 --- a/tests/extmod/urandom_basic.py +++ b/tests/extmod/urandom_basic.py @@ -26,4 +26,4 @@ print(random.getrandbits(16) == r) try: random.getrandbits(0) except ValueError: - print('ValueError') + print("ValueError") diff --git a/tests/extmod/urandom_extra.py b/tests/extmod/urandom_extra.py index 0cfd9280b5..78e17379dc 100644 --- a/tests/extmod/urandom_extra.py +++ b/tests/extmod/urandom_extra.py @@ -10,10 +10,10 @@ except ImportError: try: random.randint except AttributeError: - print('SKIP') + print("SKIP") raise SystemExit -print('randrange') +print("randrange") for i in range(50): assert 0 <= random.randrange(4) < 4 assert 2 <= random.randrange(2, 6) < 6 @@ -25,27 +25,27 @@ for i in range(50): try: random.randrange(0) except ValueError: - print('ValueError') + print("ValueError") # empty range try: random.randrange(2, 1) except ValueError: - print('ValueError') + print("ValueError") # zero step try: random.randrange(2, 1, 0) except ValueError: - print('ValueError') + print("ValueError") # empty range try: random.randrange(2, 1, 1) except ValueError: - print('ValueError') + print("ValueError") -print('randint') +print("randint") for i in range(50): assert 0 <= random.randint(0, 4) <= 4 assert 2 <= random.randint(2, 6) <= 6 @@ -55,9 +55,9 @@ for i in range(50): try: random.randint(2, 1) except ValueError: - print('ValueError') + print("ValueError") -print('choice') +print("choice") lst = [1, 2, 5, 6] for i in range(50): assert random.choice(lst) in lst @@ -66,4 +66,4 @@ for i in range(50): try: random.choice([]) except IndexError: - print('IndexError') + print("IndexError") diff --git a/tests/extmod/urandom_extra_float.py b/tests/extmod/urandom_extra_float.py index f665fd18ad..65918da136 100644 --- a/tests/extmod/urandom_extra_float.py +++ b/tests/extmod/urandom_extra_float.py @@ -10,14 +10,14 @@ except ImportError: try: random.randint except AttributeError: - print('SKIP') + print("SKIP") raise SystemExit -print('random') +print("random") for i in range(50): assert 0 <= random.random() < 1 -print('uniform') +print("uniform") for i in range(50): assert 0 <= random.uniform(0, 4) <= 4 assert 2 <= random.uniform(2, 6) <= 6 diff --git a/tests/extmod/ure1.py b/tests/extmod/ure1.py index 54471ed4f9..ed7ad95653 100644 --- a/tests/extmod/ure1.py +++ b/tests/extmod/ure1.py @@ -70,11 +70,16 @@ print(m.group(0)) m = re.search("w.r", "hello world") print(m.group(0)) -m = re.match('a+?', 'ab'); print(m.group(0)) -m = re.match('a*?', 'ab'); print(m.group(0)) -m = re.match('^ab$', 'ab'); print(m.group(0)) -m = re.match('a|b', 'b'); print(m.group(0)) -m = re.match('a|b|c', 'c'); print(m.group(0)) +m = re.match("a+?", "ab") +print(m.group(0)) +m = re.match("a*?", "ab") +print(m.group(0)) +m = re.match("^ab$", "ab") +print(m.group(0)) +m = re.match("a|b", "b") +print(m.group(0)) +m = re.match("a|b|c", "c") +print(m.group(0)) # Case where anchors fail to match r = re.compile("^b|b$") @@ -87,4 +92,5 @@ except: print("Caught invalid regex") # bytes objects -m = re.match(rb'a+?', b'ab'); print(m.group(0)) +m = re.match(rb"a+?", b"ab") +print(m.group(0)) diff --git a/tests/extmod/ure_debug.py b/tests/extmod/ure_debug.py index cfb264bb6d..4cef4c98ae 100644 --- a/tests/extmod/ure_debug.py +++ b/tests/extmod/ure_debug.py @@ -5,4 +5,4 @@ except ImportError: print("SKIP") raise SystemExit -ure.compile('^a|b[0-9]\w$', ure.DEBUG) +ure.compile("^a|b[0-9]\w$", ure.DEBUG) diff --git a/tests/extmod/ure_error.py b/tests/extmod/ure_error.py index f52f735c7f..a99a47f97e 100644 --- a/tests/extmod/ure_error.py +++ b/tests/extmod/ure_error.py @@ -9,17 +9,19 @@ except ImportError: print("SKIP") raise SystemExit + def test_re(r): try: re.compile(r) print("OK") - except: # uPy and CPy use different errors, so just ignore the type + except: # uPy and CPy use different errors, so just ignore the type print("Error") -test_re(r'?') -test_re(r'*') -test_re(r'+') -test_re(r')') -test_re(r'[') -test_re(r'([') -test_re(r'([)') + +test_re(r"?") +test_re(r"*") +test_re(r"+") +test_re(r")") +test_re(r"[") +test_re(r"([") +test_re(r"([)") diff --git a/tests/extmod/ure_group.py b/tests/extmod/ure_group.py index 4e39468c5b..41425dd623 100644 --- a/tests/extmod/ure_group.py +++ b/tests/extmod/ure_group.py @@ -9,8 +9,9 @@ except ImportError: print("SKIP") raise SystemExit + def print_groups(match): - print('----') + print("----") try: i = 0 while True: @@ -19,14 +20,15 @@ def print_groups(match): except IndexError: pass -m = re.match(r'(([0-9]*)([a-z]*)[0-9]*)','1234hello567') + +m = re.match(r"(([0-9]*)([a-z]*)[0-9]*)", "1234hello567") print_groups(m) -m = re.match(r'([0-9]*)(([a-z]*)([0-9]*))','1234hello567') +m = re.match(r"([0-9]*)(([a-z]*)([0-9]*))", "1234hello567") print_groups(m) # optional group that matches -print_groups(re.match(r'(a)?b(c)', 'abc')) +print_groups(re.match(r"(a)?b(c)", "abc")) # optional group that doesn't match -print_groups(re.match(r'(a)?b(c)', 'bc')) +print_groups(re.match(r"(a)?b(c)", "bc")) diff --git a/tests/extmod/ure_groups.py b/tests/extmod/ure_groups.py index 4fac896d7f..7da072a920 100644 --- a/tests/extmod/ure_groups.py +++ b/tests/extmod/ure_groups.py @@ -13,21 +13,21 @@ try: m = re.match(".", "a") m.groups except AttributeError: - print('SKIP') + print("SKIP") raise SystemExit -m = re.match(r'(([0-9]*)([a-z]*)[0-9]*)','1234hello567') +m = re.match(r"(([0-9]*)([a-z]*)[0-9]*)", "1234hello567") print(m.groups()) -m = re.match(r'([0-9]*)(([a-z]*)([0-9]*))','1234hello567') +m = re.match(r"([0-9]*)(([a-z]*)([0-9]*))", "1234hello567") print(m.groups()) # optional group that matches -print(re.match(r'(a)?b(c)', 'abc').groups()) +print(re.match(r"(a)?b(c)", "abc").groups()) # optional group that doesn't match -print(re.match(r'(a)?b(c)', 'bc').groups()) +print(re.match(r"(a)?b(c)", "bc").groups()) # only a single match -print(re.match(r'abc', 'abc').groups()) +print(re.match(r"abc", "abc").groups()) diff --git a/tests/extmod/ure_namedclass.py b/tests/extmod/ure_namedclass.py index 215d09613f..00d58ad98a 100644 --- a/tests/extmod/ure_namedclass.py +++ b/tests/extmod/ure_namedclass.py @@ -9,8 +9,9 @@ except ImportError: print("SKIP") raise SystemExit + def print_groups(match): - print('----') + print("----") try: i = 0 while True: @@ -19,14 +20,15 @@ def print_groups(match): except IndexError: pass -m = re.match(r'\w+','1234hello567 abc') + +m = re.match(r"\w+", "1234hello567 abc") print_groups(m) -m = re.match(r'(\w+)\s+(\w+)','ABC \t1234hello567 abc') +m = re.match(r"(\w+)\s+(\w+)", "ABC \t1234hello567 abc") print_groups(m) -m = re.match(r'(\S+)\s+(\D+)','ABC \thello abc567 abc') +m = re.match(r"(\S+)\s+(\D+)", "ABC \thello abc567 abc") print_groups(m) -m = re.match(r'(([0-9]*)([a-z]*)\d*)','1234hello567') +m = re.match(r"(([0-9]*)([a-z]*)\d*)", "1234hello567") print_groups(m) diff --git a/tests/extmod/ure_span.py b/tests/extmod/ure_span.py index 50f44399ce..03a3fef9f3 100644 --- a/tests/extmod/ure_span.py +++ b/tests/extmod/ure_span.py @@ -13,12 +13,12 @@ try: m = re.match(".", "a") m.span except AttributeError: - print('SKIP') + print("SKIP") raise SystemExit def print_spans(match): - print('----') + print("----") try: i = 0 while True: @@ -27,14 +27,15 @@ def print_spans(match): except IndexError: pass -m = re.match(r'(([0-9]*)([a-z]*)[0-9]*)','1234hello567') + +m = re.match(r"(([0-9]*)([a-z]*)[0-9]*)", "1234hello567") print_spans(m) -m = re.match(r'([0-9]*)(([a-z]*)([0-9]*))','1234hello567') +m = re.match(r"([0-9]*)(([a-z]*)([0-9]*))", "1234hello567") print_spans(m) # optional span that matches -print_spans(re.match(r'(a)?b(c)', 'abc')) +print_spans(re.match(r"(a)?b(c)", "abc")) # optional span that doesn't match -print_spans(re.match(r'(a)?b(c)', 'bc')) +print_spans(re.match(r"(a)?b(c)", "bc")) diff --git a/tests/extmod/ure_split_notimpl.py b/tests/extmod/ure_split_notimpl.py index da6e9652d0..51bad791ef 100644 --- a/tests/extmod/ure_split_notimpl.py +++ b/tests/extmod/ure_split_notimpl.py @@ -4,8 +4,8 @@ except ImportError: print("SKIP") raise SystemExit -r = re.compile('( )') +r = re.compile("( )") try: s = r.split("a b c foobar") except NotImplementedError: - print('NotImplementedError') + print("NotImplementedError") diff --git a/tests/extmod/ure_sub.py b/tests/extmod/ure_sub.py index 4aeb8650a1..6bb332077d 100644 --- a/tests/extmod/ure_sub.py +++ b/tests/extmod/ure_sub.py @@ -4,58 +4,59 @@ except ImportError: try: import re except ImportError: - print('SKIP') + print("SKIP") raise SystemExit try: re.sub except AttributeError: - print('SKIP') + print("SKIP") raise SystemExit def multiply(m): return str(int(m.group(0)) * 2) + print(re.sub("\d+", multiply, "10 20 30 40 50")) print(re.sub("\d+", lambda m: str(int(m.group(0)) // 2), "10 20 30 40 50")) + def A(): return "A" -print(re.sub('a', A(), 'aBCBABCDabcda.')) + + +print(re.sub("a", A(), "aBCBABCDabcda.")) print( re.sub( - r'def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(\s*\):', - 'static PyObject*\npy_\\1(void){\n return;\n}\n', - '\n\ndef myfunc():\n\ndef myfunc1():\n\ndef myfunc2():' + r"def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(\s*\):", + "static PyObject*\npy_\\1(void){\n return;\n}\n", + "\n\ndef myfunc():\n\ndef myfunc1():\n\ndef myfunc2():", ) -) +) print( - re.compile( - '(calzino) (blu|bianco|verde) e (scarpa) (blu|bianco|verde)' - ).sub( - r'\g<1> colore \2 con \g<3> colore \4? ...', - 'calzino blu e scarpa verde' + re.compile("(calzino) (blu|bianco|verde) e (scarpa) (blu|bianco|verde)").sub( + r"\g<1> colore \2 con \g<3> colore \4? ...", "calzino blu e scarpa verde" ) ) # no matches at all -print(re.sub('a', 'b', 'c')) +print(re.sub("a", "b", "c")) # with maximum substitution count specified -print(re.sub('a', 'b', '1a2a3a', 2)) +print(re.sub("a", "b", "1a2a3a", 2)) # invalid group try: - re.sub('(a)', 'b\\2', 'a') + re.sub("(a)", "b\\2", "a") except: - print('invalid group') + print("invalid group") # invalid group with very large number (to test overflow in uPy) try: - re.sub('(a)', 'b\\199999999999999999999999999999999999999', 'a') + re.sub("(a)", "b\\199999999999999999999999999999999999999", "a") except: - print('invalid group') + print("invalid group") diff --git a/tests/extmod/ure_sub_unmatched.py b/tests/extmod/ure_sub_unmatched.py index 4795b3196f..d6312bfc2c 100644 --- a/tests/extmod/ure_sub_unmatched.py +++ b/tests/extmod/ure_sub_unmatched.py @@ -6,14 +6,14 @@ except ImportError: try: import re except ImportError: - print('SKIP') + print("SKIP") raise SystemExit try: re.sub except AttributeError: - print('SKIP') + print("SKIP") raise SystemExit # first group matches, second optional group doesn't so is replaced with a blank -print(re.sub(r'(a)(b)?', r'\2-\1', '1a2')) +print(re.sub(r"(a)(b)?", r"\2-\1", "1a2")) diff --git a/tests/extmod/uselect_poll_basic.py b/tests/extmod/uselect_poll_basic.py index df52471ac3..ab750078d3 100644 --- a/tests/extmod/uselect_poll_basic.py +++ b/tests/extmod/uselect_poll_basic.py @@ -3,6 +3,7 @@ try: except ImportError: try: import socket, select, errno + select.poll # Raises AttributeError for CPython implementations without poll() except (ImportError, AttributeError): print("SKIP") diff --git a/tests/extmod/ussl_basic.py b/tests/extmod/ussl_basic.py index e8710ed51a..c8bdc81a48 100644 --- a/tests/extmod/ussl_basic.py +++ b/tests/extmod/ussl_basic.py @@ -11,7 +11,7 @@ except ImportError: try: ss = ssl.wrap_socket(io.BytesIO()) except OSError as er: - print('wrap_socket:', repr(er)) + print("wrap_socket:", repr(er)) # create in server mode (can use this object for further tests) socket = io.BytesIO() @@ -24,22 +24,22 @@ print(repr(ss)[:12]) try: ss.setblocking(False) except NotImplementedError: - print('setblocking: NotImplementedError') + print("setblocking: NotImplementedError") ss.setblocking(True) # write -print(ss.write(b'aaaa')) +print(ss.write(b"aaaa")) # read (underlying socket has no data) print(ss.read(8)) # read (underlying socket has data, but it's bad data) -socket.write(b'aaaaaaaaaaaaaaaa') +socket.write(b"aaaaaaaaaaaaaaaa") socket.seek(0) try: ss.read(8) except OSError as er: - print('read:', repr(er)) + print("read:", repr(er)) # close ss.close() @@ -50,10 +50,10 @@ ss.close() try: ss.read(10) except OSError as er: - print('read:', repr(er)) + print("read:", repr(er)) # write on closed socket try: - ss.write(b'aaaa') + ss.write(b"aaaa") except OSError as er: - print('write:', repr(er)) + print("write:", repr(er)) diff --git a/tests/extmod/utimeq1.py b/tests/extmod/utimeq1.py index dc7f3b6600..234d7a31dd 100644 --- a/tests/extmod/utimeq1.py +++ b/tests/extmod/utimeq1.py @@ -13,12 +13,17 @@ MAX = ticks_add(0, -1) MODULO_HALF = MAX // 2 + 1 if DEBUG: + def dprint(*v): print(*v) + + else: + def dprint(*v): pass + # Try not to crash on invalid data h = utimeq(10) try: @@ -69,22 +74,25 @@ try: except IndexError: pass + def pop_all(h): l = [] while h: item = [0, 0, 0] h.pop(item) - #print("!", item) + # print("!", item) l.append(tuple(item)) dprint(l) return l + def add(h, v): h.push(v, 0, 0) dprint("-----") - #h.dump() + # h.dump() dprint("-----") + h = utimeq(10) add(h, 0) add(h, MAX) @@ -98,6 +106,7 @@ for i in range(len(l) - 1): diff = ticks_diff(l[i + 1][0], l[i][0]) assert diff > 0 + def edge_case(edge, offset): h = utimeq(10) add(h, ticks_add(0, offset)) @@ -108,6 +117,7 @@ def edge_case(edge, offset): dprint(diff, diff > 0) return diff + dprint("===") diff = edge_case(MODULO_HALF - 1, 0) assert diff == MODULO_HALF - 1 diff --git a/tests/extmod/uzlib_decompio.py b/tests/extmod/uzlib_decompio.py index 112a825976..6a0aae8bcd 100644 --- a/tests/extmod/uzlib_decompio.py +++ b/tests/extmod/uzlib_decompio.py @@ -7,7 +7,7 @@ except ImportError: # Raw DEFLATE bitstream -buf = io.BytesIO(b'\xcbH\xcd\xc9\xc9\x07\x00') +buf = io.BytesIO(b"\xcbH\xcd\xc9\xc9\x07\x00") inp = zlib.DecompIO(buf, -8) print(buf.seek(0, 1)) print(inp.read(1)) @@ -21,12 +21,12 @@ print(buf.seek(0, 1)) # zlib bitstream -inp = zlib.DecompIO(io.BytesIO(b'x\x9c30\xa0=\x00\x00\xb3q\x12\xc1')) +inp = zlib.DecompIO(io.BytesIO(b"x\x9c30\xa0=\x00\x00\xb3q\x12\xc1")) print(inp.read(10)) print(inp.read()) # zlib bitstream, wrong checksum -inp = zlib.DecompIO(io.BytesIO(b'x\x9c30\xa0=\x00\x00\xb3q\x12\xc0')) +inp = zlib.DecompIO(io.BytesIO(b"x\x9c30\xa0=\x00\x00\xb3q\x12\xc0")) try: print(inp.read()) except OSError as e: diff --git a/tests/extmod/uzlib_decompio_gz.py b/tests/extmod/uzlib_decompio_gz.py index 02087f7639..1bc8ba885b 100644 --- a/tests/extmod/uzlib_decompio_gz.py +++ b/tests/extmod/uzlib_decompio_gz.py @@ -7,7 +7,9 @@ except ImportError: # gzip bitstream -buf = io.BytesIO(b'\x1f\x8b\x08\x08\x99\x0c\xe5W\x00\x03hello\x00\xcbH\xcd\xc9\xc9\x07\x00\x86\xa6\x106\x05\x00\x00\x00') +buf = io.BytesIO( + b"\x1f\x8b\x08\x08\x99\x0c\xe5W\x00\x03hello\x00\xcbH\xcd\xc9\xc9\x07\x00\x86\xa6\x106\x05\x00\x00\x00" +) inp = zlib.DecompIO(buf, 16 + 8) print(buf.seek(0, 1)) print(inp.read(1)) @@ -20,24 +22,32 @@ print(inp.read()) print(buf.seek(0, 1)) # Check FHCRC field -buf = io.BytesIO(b'\x1f\x8b\x08\x02\x99\x0c\xe5W\x00\x03\x00\x00\xcbH\xcd\xc9\xc9\x07\x00\x86\xa6\x106\x05\x00\x00\x00') +buf = io.BytesIO( + b"\x1f\x8b\x08\x02\x99\x0c\xe5W\x00\x03\x00\x00\xcbH\xcd\xc9\xc9\x07\x00\x86\xa6\x106\x05\x00\x00\x00" +) inp = zlib.DecompIO(buf, 16 + 8) print(inp.read()) # Check FEXTRA field -buf = io.BytesIO(b'\x1f\x8b\x08\x04\x99\x0c\xe5W\x00\x03\x01\x00X\xcbH\xcd\xc9\xc9\x07\x00\x86\xa6\x106\x05\x00\x00\x00') +buf = io.BytesIO( + b"\x1f\x8b\x08\x04\x99\x0c\xe5W\x00\x03\x01\x00X\xcbH\xcd\xc9\xc9\x07\x00\x86\xa6\x106\x05\x00\x00\x00" +) inp = zlib.DecompIO(buf, 16 + 8) print(inp.read()) # broken header -buf = io.BytesIO(b'\x1f\x8c\x08\x08\x99\x0c\xe5W\x00\x03hello\x00\xcbH\xcd\xc9\xc9\x07\x00\x86\xa6\x106\x05\x00\x00\x00') +buf = io.BytesIO( + b"\x1f\x8c\x08\x08\x99\x0c\xe5W\x00\x03hello\x00\xcbH\xcd\xc9\xc9\x07\x00\x86\xa6\x106\x05\x00\x00\x00" +) try: inp = zlib.DecompIO(buf, 16 + 8) except ValueError: print("ValueError") # broken crc32 -buf = io.BytesIO(b'\x1f\x8b\x08\x08\x99\x0c\xe5W\x00\x03hello\x00\xcbH\xcd\xc9\xc9\x07\x00\x86\xa7\x106\x05\x00\x00\x00') +buf = io.BytesIO( + b"\x1f\x8b\x08\x08\x99\x0c\xe5W\x00\x03hello\x00\xcbH\xcd\xc9\xc9\x07\x00\x86\xa7\x106\x05\x00\x00\x00" +) inp = zlib.DecompIO(buf, 16 + 8) try: inp.read(6) @@ -45,6 +55,6 @@ except OSError as e: print(repr(e)) # broken uncompressed size - not checked so far -#buf = io.BytesIO(b'\x1f\x8b\x08\x08\x99\x0c\xe5W\x00\x03hello\x00\xcbH\xcd\xc9\xc9\x07\x00\x86\xa6\x106\x06\x00\x00\x00') -#inp = zlib.DecompIO(buf, 16 + 8) -#inp.read(6) +# buf = io.BytesIO(b'\x1f\x8b\x08\x08\x99\x0c\xe5W\x00\x03hello\x00\xcbH\xcd\xc9\xc9\x07\x00\x86\xa6\x106\x06\x00\x00\x00') +# inp = zlib.DecompIO(buf, 16 + 8) +# inp.read(6) diff --git a/tests/extmod/uzlib_decompress.py b/tests/extmod/uzlib_decompress.py index dd6e4876fa..8d4a9640b4 100644 --- a/tests/extmod/uzlib_decompress.py +++ b/tests/extmod/uzlib_decompress.py @@ -9,15 +9,24 @@ except ImportError: PATTERNS = [ # Packed results produced by CPy's zlib.compress() - (b'0', b'x\x9c3\x00\x00\x001\x001'), - (b'a', b'x\x9cK\x04\x00\x00b\x00b'), - (b'0' * 100, b'x\x9c30\xa0=\x00\x00\xb3q\x12\xc1'), - (bytes(range(64)), b'x\x9cc`dbfaec\xe7\xe0\xe4\xe2\xe6\xe1\xe5\xe3\x17\x10\x14\x12\x16\x11\x15\x13\x97\x90\x94\x92\x96\x91\x95\x93WPTRVQUS\xd7\xd0\xd4\xd2\xd6\xd1\xd5\xd370426153\xb7\xb0\xb4\xb2\xb6\xb1\xb5\xb3\x07\x00\xaa\xe0\x07\xe1'), - (b'hello', b'x\x01\x01\x05\x00\xfa\xffhello\x06,\x02\x15'), # compression level 0 + (b"0", b"x\x9c3\x00\x00\x001\x001"), + (b"a", b"x\x9cK\x04\x00\x00b\x00b"), + (b"0" * 100, b"x\x9c30\xa0=\x00\x00\xb3q\x12\xc1"), + ( + bytes(range(64)), + b"x\x9cc`dbfaec\xe7\xe0\xe4\xe2\xe6\xe1\xe5\xe3\x17\x10\x14\x12\x16\x11\x15\x13\x97\x90\x94\x92\x96\x91\x95\x93WPTRVQUS\xd7\xd0\xd4\xd2\xd6\xd1\xd5\xd370426153\xb7\xb0\xb4\xb2\xb6\xb1\xb5\xb3\x07\x00\xaa\xe0\x07\xe1", + ), + (b"hello", b"x\x01\x01\x05\x00\xfa\xffhello\x06,\x02\x15"), # compression level 0 # adaptive/dynamic huffman tree - (b'13371813150|13764518736|12345678901', b'x\x9c\x05\xc1\x81\x01\x000\x04\x04\xb1\x95\\\x1f\xcfn\x86o\x82d\x06Qq\xc8\x9d\xc5X}I}\x00\x951D>I}\x00\x951D>I}\x00\x951D>I}\x00\x951D', b'x\x9c\x05\xc11\x01\x00\x00\x00\x010\x95\x14py\x84\x12C_\x9bR\x8cV\x8a\xd1J1Z)F\x1fw`\x089'), + ( + b">I}\x00\x951D>I}\x00\x951D>I}\x00\x951D>I}\x00\x951D", + b"x\x9c\x05\xc11\x01\x00\x00\x00\x010\x95\x14py\x84\x12C_\x9bR\x8cV\x8a\xd1J1Z)F\x1fw`\x089", + ), ] for unpacked, packed in PATTERNS: @@ -26,26 +35,26 @@ for unpacked, packed in PATTERNS: # Raw DEFLATE bitstream -v = b'\xcbH\xcd\xc9\xc9\x07\x00' +v = b"\xcbH\xcd\xc9\xc9\x07\x00" exp = b"hello" out = zlib.decompress(v, -15) -assert(out == exp) +assert out == exp print(exp) # Even when you ask CPython zlib.compress to produce Raw DEFLATE stream, # it returns it with adler2 and oriignal size appended, as if it was a # zlib stream. Make sure there're no random issues decompressing such. -v = b'\xcbH\xcd\xc9\xc9\x07\x00\x86\xa6\x106\x05\x00\x00\x00' +v = b"\xcbH\xcd\xc9\xc9\x07\x00\x86\xa6\x106\x05\x00\x00\x00" out = zlib.decompress(v, -15) -assert(out == exp) +assert out == exp # this should error try: - zlib.decompress(b'abc') + zlib.decompress(b"abc") except Exception: print("Exception") # invalid block type try: - zlib.decompress(b'\x07', -15) # final-block, block-type=3 (invalid) + zlib.decompress(b"\x07", -15) # final-block, block-type=3 (invalid) except Exception as er: - print('Exception') + print("Exception") diff --git a/tests/extmod/vfs_basic.py b/tests/extmod/vfs_basic.py index fbcc92bade..c8e203b3df 100644 --- a/tests/extmod/vfs_basic.py +++ b/tests/extmod/vfs_basic.py @@ -2,6 +2,7 @@ try: import uos + uos.mount except (ImportError, AttributeError): print("SKIP") @@ -11,55 +12,67 @@ except (ImportError, AttributeError): class Filesystem: def __init__(self, id): self.id = id + def mount(self, readonly, mkfs): - print(self.id, 'mount', readonly, mkfs) + print(self.id, "mount", readonly, mkfs) + def umount(self): - print(self.id, 'umount') + print(self.id, "umount") + def ilistdir(self, dir): - print(self.id, 'ilistdir', dir) - return iter([('a%d' % self.id, 0, 0)]) + print(self.id, "ilistdir", dir) + return iter([("a%d" % self.id, 0, 0)]) + def chdir(self, dir): - print(self.id, 'chdir', dir) + print(self.id, "chdir", dir) + def getcwd(self): - print(self.id, 'getcwd') - return 'dir%d' % self.id + print(self.id, "getcwd") + return "dir%d" % self.id + def mkdir(self, path): - print(self.id, 'mkdir', path) + print(self.id, "mkdir", path) + def remove(self, path): - print(self.id, 'remove', path) + print(self.id, "remove", path) + def rename(self, old_path, new_path): - print(self.id, 'rename', old_path, new_path) + print(self.id, "rename", old_path, new_path) + def rmdir(self, path): - print(self.id, 'rmdir', path) + print(self.id, "rmdir", path) + def stat(self, path): - print(self.id, 'stat', path) + print(self.id, "stat", path) return (self.id,) + def statvfs(self, path): - print(self.id, 'statvfs', path) + print(self.id, "statvfs", path) return (self.id,) + def open(self, file, mode): - print(self.id, 'open', file, mode) + print(self.id, "open", file, mode) # first we umount any existing mount points the target may have try: - uos.umount('/') + uos.umount("/") except OSError: pass -for path in uos.listdir('/'): - uos.umount('/' + path) +for path in uos.listdir("/"): + uos.umount("/" + path) # stat root dir -print(uos.stat('/')) +print(uos.stat("/")) # statvfs root dir; verify that f_namemax has a sensible size -print(uos.statvfs('/')[9] >= 32) +print(uos.statvfs("/")[9] >= 32) # getcwd when in root dir print(uos.getcwd()) # basic mounting and listdir -uos.mount(Filesystem(1), '/test_mnt') +uos.mount(Filesystem(1), "/test_mnt") print(uos.listdir()) # ilistdir @@ -68,80 +81,80 @@ print(next(i)) try: next(i) except StopIteration: - print('StopIteration') + print("StopIteration") try: next(i) except StopIteration: - print('StopIteration') + print("StopIteration") # referencing the mount point in different ways -print(uos.listdir('test_mnt')) -print(uos.listdir('/test_mnt')) +print(uos.listdir("test_mnt")) +print(uos.listdir("/test_mnt")) # mounting another filesystem -uos.mount(Filesystem(2), '/test_mnt2', readonly=True) +uos.mount(Filesystem(2), "/test_mnt2", readonly=True) print(uos.listdir()) -print(uos.listdir('/test_mnt2')) +print(uos.listdir("/test_mnt2")) # mounting over an existing mount point try: - uos.mount(Filesystem(3), '/test_mnt2') + uos.mount(Filesystem(3), "/test_mnt2") except OSError: - print('OSError') + print("OSError") # mkdir of a mount point try: - uos.mkdir('/test_mnt') + uos.mkdir("/test_mnt") except OSError: - print('OSError') + print("OSError") # rename across a filesystem try: - uos.rename('/test_mnt/a', '/test_mnt2/b') + uos.rename("/test_mnt/a", "/test_mnt2/b") except OSError: - print('OSError') + print("OSError") # delegating to mounted filesystem -uos.chdir('test_mnt') +uos.chdir("test_mnt") print(uos.listdir()) print(uos.getcwd()) -uos.mkdir('test_dir') -uos.remove('test_file') -uos.rename('test_file', 'test_file2') -uos.rmdir('test_dir') -print(uos.stat('test_file')) -print(uos.statvfs('/test_mnt')) -open('test_file') -open('test_file', 'wb') +uos.mkdir("test_dir") +uos.remove("test_file") +uos.rename("test_file", "test_file2") +uos.rmdir("test_dir") +print(uos.stat("test_file")) +print(uos.statvfs("/test_mnt")) +open("test_file") +open("test_file", "wb") # umount -uos.umount('/test_mnt') -uos.umount('/test_mnt2') +uos.umount("/test_mnt") +uos.umount("/test_mnt2") # umount a non-existent mount point try: - uos.umount('/test_mnt') + uos.umount("/test_mnt") except OSError: - print('OSError') + print("OSError") # root dir -uos.mount(Filesystem(3), '/') -print(uos.stat('/')) -print(uos.statvfs('/')) +uos.mount(Filesystem(3), "/") +print(uos.stat("/")) +print(uos.statvfs("/")) print(uos.listdir()) -open('test') +open("test") -uos.mount(Filesystem(4), '/mnt') +uos.mount(Filesystem(4), "/mnt") print(uos.listdir()) -print(uos.listdir('/mnt')) -uos.chdir('/mnt') +print(uos.listdir("/mnt")) +uos.chdir("/mnt") print(uos.listdir()) # chdir to a subdir within root-mounted vfs, and then listdir -uos.chdir('/subdir') +uos.chdir("/subdir") print(uos.listdir()) -uos.chdir('/') +uos.chdir("/") -uos.umount('/') -print(uos.listdir('/')) -uos.umount('/mnt') +uos.umount("/") +print(uos.listdir("/")) +uos.umount("/mnt") diff --git a/tests/extmod/vfs_fat_fileio1.py b/tests/extmod/vfs_fat_fileio1.py index 51cd765222..a41a5b0fbd 100644 --- a/tests/extmod/vfs_fat_fileio1.py +++ b/tests/extmod/vfs_fat_fileio1.py @@ -20,17 +20,17 @@ class RAMFS: self.data = bytearray(blocks * self.SEC_SIZE) def readblocks(self, n, buf): - #print("readblocks(%s, %x(%d))" % (n, id(buf), len(buf))) + # print("readblocks(%s, %x(%d))" % (n, id(buf), len(buf))) for i in range(len(buf)): buf[i] = self.data[n * self.SEC_SIZE + i] def writeblocks(self, n, buf): - #print("writeblocks(%s, %x)" % (n, id(buf))) + # print("writeblocks(%s, %x)" % (n, id(buf))) for i in range(len(buf)): self.data[n * self.SEC_SIZE + i] = buf[i] def ioctl(self, op, arg): - #print("ioctl(%d, %r)" % (op, arg)) + # print("ioctl(%d, %r)" % (op, arg)) if op == 4: # BP_IOCTL_SEC_COUNT return len(self.data) // self.SEC_SIZE if op == 5: # BP_IOCTL_SEC_SIZE @@ -45,8 +45,8 @@ except MemoryError: uos.VfsFat.mkfs(bdev) vfs = uos.VfsFat(bdev) -uos.mount(vfs, '/ramdisk') -uos.chdir('/ramdisk') +uos.mount(vfs, "/ramdisk") +uos.chdir("/ramdisk") # file IO f = open("foo_file.txt", "w") @@ -54,7 +54,7 @@ print(str(f)[:17], str(f)[-1:]) f.write("hello!") f.flush() f.close() -f.close() # allowed +f.close() # allowed try: f.write("world!") except OSError as e: @@ -82,21 +82,21 @@ with open("foo_file.txt") as f2: print(f2.read()) print(f2.tell()) - f2.seek(0, 0) # SEEK_SET + f2.seek(0, 0) # SEEK_SET print(f2.read(1)) - f2.seek(0, 1) # SEEK_CUR + f2.seek(0, 1) # SEEK_CUR print(f2.read(1)) - f2.seek(2, 1) # SEEK_CUR + f2.seek(2, 1) # SEEK_CUR print(f2.read(1)) - f2.seek(-2, 2) # SEEK_END + f2.seek(-2, 2) # SEEK_END print(f2.read(1)) # using constructor of FileIO type to open a file # no longer working with new VFS sub-system -#FileIO = type(f) -#with FileIO("/ramdisk/foo_file.txt") as f: +# FileIO = type(f) +# with FileIO("/ramdisk/foo_file.txt") as f: # print(f.read()) # dirs @@ -105,7 +105,7 @@ vfs.mkdir("foo_dir") try: vfs.rmdir("foo_file.txt") except OSError as e: - print(e.args[0] == 20) # uerrno.ENOTDIR + print(e.args[0] == 20) # uerrno.ENOTDIR vfs.remove("foo_file.txt") print(list(vfs.ilistdir())) @@ -115,23 +115,25 @@ print(list(vfs.ilistdir())) # finaliser is a different path to normal allocation. It would be better to # test this in the core tests but there are no core objects that use finaliser. import micropython + micropython.heap_lock() try: - vfs.open('x', 'r') + vfs.open("x", "r") except MemoryError: - print('MemoryError') + print("MemoryError") micropython.heap_unlock() # Here we test that the finaliser is actually called during a garbage collection. import gc + N = 4 for i in range(N): - n = 'x%d' % i - f = vfs.open(n, 'w') + n = "x%d" % i + f = vfs.open(n, "w") f.write(n) - f = None # release f without closing - [0, 1, 2, 3] # use up Python stack so f is really gone -gc.collect() # should finalise all N files by closing them + f = None # release f without closing + [0, 1, 2, 3] # use up Python stack so f is really gone +gc.collect() # should finalise all N files by closing them for i in range(N): - with vfs.open('x%d' % i, 'r') as f: + with vfs.open("x%d" % i, "r") as f: print(f.read()) diff --git a/tests/extmod/vfs_fat_fileio2.py b/tests/extmod/vfs_fat_fileio2.py index 9b9a11e435..5dd641cfc0 100644 --- a/tests/extmod/vfs_fat_fileio2.py +++ b/tests/extmod/vfs_fat_fileio2.py @@ -20,17 +20,17 @@ class RAMFS: self.data = bytearray(blocks * self.SEC_SIZE) def readblocks(self, n, buf): - #print("readblocks(%s, %x(%d))" % (n, id(buf), len(buf))) + # print("readblocks(%s, %x(%d))" % (n, id(buf), len(buf))) for i in range(len(buf)): buf[i] = self.data[n * self.SEC_SIZE + i] def writeblocks(self, n, buf): - #print("writeblocks(%s, %x)" % (n, id(buf))) + # print("writeblocks(%s, %x)" % (n, id(buf))) for i in range(len(buf)): self.data[n * self.SEC_SIZE + i] = buf[i] def ioctl(self, op, arg): - #print("ioctl(%d, %r)" % (op, arg)) + # print("ioctl(%d, %r)" % (op, arg)) if op == 4: # BP_IOCTL_SEC_COUNT return len(self.data) // self.SEC_SIZE if op == 5: # BP_IOCTL_SEC_SIZE @@ -45,8 +45,8 @@ except MemoryError: uos.VfsFat.mkfs(bdev) vfs = uos.VfsFat(bdev) -uos.mount(vfs, '/ramdisk') -uos.chdir('/ramdisk') +uos.mount(vfs, "/ramdisk") +uos.chdir("/ramdisk") try: vfs.mkdir("foo_dir") @@ -111,4 +111,4 @@ try: f = open("large_file.txt", "wb") f.write(bytearray(bsize * free)) except OSError as e: - print("ENOSPC:", e.args[0] == 28) # uerrno.ENOSPC + print("ENOSPC:", e.args[0] == 28) # uerrno.ENOSPC diff --git a/tests/extmod/vfs_fat_more.py b/tests/extmod/vfs_fat_more.py index 488697fa85..17106de446 100644 --- a/tests/extmod/vfs_fat_more.py +++ b/tests/extmod/vfs_fat_more.py @@ -19,17 +19,17 @@ class RAMFS: self.data = bytearray(blocks * self.SEC_SIZE) def readblocks(self, n, buf): - #print("readblocks(%s, %x(%d))" % (n, id(buf), len(buf))) + # print("readblocks(%s, %x(%d))" % (n, id(buf), len(buf))) for i in range(len(buf)): buf[i] = self.data[n * self.SEC_SIZE + i] def writeblocks(self, n, buf): - #print("writeblocks(%s, %x)" % (n, id(buf))) + # print("writeblocks(%s, %x)" % (n, id(buf))) for i in range(len(buf)): self.data[n * self.SEC_SIZE + i] = buf[i] def ioctl(self, op, arg): - #print("ioctl(%d, %r)" % (op, arg)) + # print("ioctl(%d, %r)" % (op, arg)) if op == 4: # BP_IOCTL_SEC_COUNT return len(self.data) // self.SEC_SIZE if op == 5: # BP_IOCTL_SEC_SIZE @@ -45,75 +45,76 @@ except MemoryError: # first we umount any existing mount points the target may have try: - uos.umount('/') + uos.umount("/") except OSError: pass -for path in uos.listdir('/'): - uos.umount('/' + path) +for path in uos.listdir("/"): + uos.umount("/" + path) uos.VfsFat.mkfs(bdev) -uos.mount(bdev, '/') +uos.mount(bdev, "/") print(uos.getcwd()) -f = open('test.txt', 'w') -f.write('hello') +f = open("test.txt", "w") +f.write("hello") f.close() print(uos.listdir()) -print(uos.listdir('/')) -print(uos.stat('')[:-3]) -print(uos.stat('/')[:-3]) -print(uos.stat('test.txt')[:-3]) -print(uos.stat('/test.txt')[:-3]) +print(uos.listdir("/")) +print(uos.stat("")[:-3]) +print(uos.stat("/")[:-3]) +print(uos.stat("test.txt")[:-3]) +print(uos.stat("/test.txt")[:-3]) -f = open('/test.txt') +f = open("/test.txt") print(f.read()) f.close() -uos.rename('test.txt', 'test2.txt') +uos.rename("test.txt", "test2.txt") print(uos.listdir()) -uos.rename('test2.txt', '/test3.txt') +uos.rename("test2.txt", "/test3.txt") print(uos.listdir()) -uos.rename('/test3.txt', 'test4.txt') +uos.rename("/test3.txt", "test4.txt") print(uos.listdir()) -uos.rename('/test4.txt', '/test5.txt') +uos.rename("/test4.txt", "/test5.txt") print(uos.listdir()) -uos.mkdir('dir') +uos.mkdir("dir") print(uos.listdir()) -uos.mkdir('/dir2') +uos.mkdir("/dir2") print(uos.listdir()) -uos.mkdir('dir/subdir') -print(uos.listdir('dir')) -for exist in ('', '/', 'dir', '/dir', 'dir/subdir'): +uos.mkdir("dir/subdir") +print(uos.listdir("dir")) +for exist in ("", "/", "dir", "/dir", "dir/subdir"): try: uos.mkdir(exist) except OSError as er: - print('mkdir OSError', er.args[0] == 17) # EEXIST + print("mkdir OSError", er.args[0] == 17) # EEXIST -uos.chdir('/') -print(uos.stat('test5.txt')[:-3]) +uos.chdir("/") +print(uos.stat("test5.txt")[:-3]) uos.VfsFat.mkfs(bdev2) -uos.mount(bdev2, '/sys') +uos.mount(bdev2, "/sys") print(uos.listdir()) -print(uos.listdir('sys')) -print(uos.listdir('/sys')) +print(uos.listdir("sys")) +print(uos.listdir("/sys")) -uos.rmdir('dir2') -uos.remove('test5.txt') +uos.rmdir("dir2") +uos.remove("test5.txt") print(uos.listdir()) -uos.umount('/') +uos.umount("/") print(uos.getcwd()) print(uos.listdir()) -print(uos.listdir('sys')) +print(uos.listdir("sys")) # test importing a file from a mounted FS import sys + sys.path.clear() -sys.path.append('/sys') -with open('sys/test_module.py', 'w') as f: +sys.path.append("/sys") +with open("sys/test_module.py", "w") as f: f.write('print("test_module!")') import test_module diff --git a/tests/extmod/vfs_fat_oldproto.py b/tests/extmod/vfs_fat_oldproto.py index 3caaa368db..93d00f9ce4 100644 --- a/tests/extmod/vfs_fat_oldproto.py +++ b/tests/extmod/vfs_fat_oldproto.py @@ -11,6 +11,7 @@ except AttributeError: print("SKIP") raise SystemExit + class RAMFS_OLD: SEC_SIZE = 512 @@ -19,12 +20,12 @@ class RAMFS_OLD: self.data = bytearray(blocks * self.SEC_SIZE) def readblocks(self, n, buf): - #print("readblocks(%s, %x(%d))" % (n, id(buf), len(buf))) + # print("readblocks(%s, %x(%d))" % (n, id(buf), len(buf))) for i in range(len(buf)): buf[i] = self.data[n * self.SEC_SIZE + i] def writeblocks(self, n, buf): - #print("writeblocks(%s, %x)" % (n, id(buf))) + # print("writeblocks(%s, %x)" % (n, id(buf))) for i in range(len(buf)): self.data[n * self.SEC_SIZE + i] = buf[i] diff --git a/tests/extmod/vfs_fat_ramdisk.py b/tests/extmod/vfs_fat_ramdisk.py index f6e5c64df0..ac7963297e 100644 --- a/tests/extmod/vfs_fat_ramdisk.py +++ b/tests/extmod/vfs_fat_ramdisk.py @@ -20,17 +20,17 @@ class RAMFS: self.data = bytearray(blocks * self.SEC_SIZE) def readblocks(self, n, buf): - #print("readblocks(%s, %x(%d))" % (n, id(buf), len(buf))) + # print("readblocks(%s, %x(%d))" % (n, id(buf), len(buf))) for i in range(len(buf)): buf[i] = self.data[n * self.SEC_SIZE + i] def writeblocks(self, n, buf): - #print("writeblocks(%s, %x)" % (n, id(buf))) + # print("writeblocks(%s, %x)" % (n, id(buf))) for i in range(len(buf)): self.data[n * self.SEC_SIZE + i] = buf[i] def ioctl(self, op, arg): - #print("ioctl(%d, %r)" % (op, arg)) + # print("ioctl(%d, %r)" % (op, arg)) if op == 4: # BP_IOCTL_SEC_COUNT return len(self.data) // self.SEC_SIZE if op == 5: # BP_IOCTL_SEC_SIZE @@ -64,7 +64,7 @@ with vfs.open("foo_file.txt", "w") as f: print(list(vfs.ilistdir())) print("stat root:", vfs.stat("/")) -print("stat file:", vfs.stat("foo_file.txt")[:-3]) # timestamps differ across runs +print("stat file:", vfs.stat("foo_file.txt")[:-3]) # timestamps differ across runs print(b"FOO_FILETXT" in bdev.data) print(b"hello!" in bdev.data) @@ -94,4 +94,4 @@ print(list(vfs.ilistdir(b""))) try: vfs.ilistdir(b"no_exist") except OSError as e: - print('ENOENT:', e.args[0] == uerrno.ENOENT) + print("ENOENT:", e.args[0] == uerrno.ENOENT) diff --git a/tests/extmod/vfs_userfs.py b/tests/extmod/vfs_userfs.py index 7f6e48cb1e..06e546b081 100644 --- a/tests/extmod/vfs_userfs.py +++ b/tests/extmod/vfs_userfs.py @@ -5,8 +5,10 @@ import sys try: import uio + uio.IOBase import uos + uos.mount except (ImportError, AttributeError): print("SKIP") @@ -17,8 +19,10 @@ class UserFile(uio.IOBase): def __init__(self, data): self.data = data self.pos = 0 + def read(self): return self.data + def readinto(self, buf): n = 0 while n < len(buf) and self.pos < len(self.data): @@ -26,44 +30,49 @@ class UserFile(uio.IOBase): n += 1 self.pos += 1 return n + def ioctl(self, req, arg): - print('ioctl', req, arg) + print("ioctl", req, arg) return 0 class UserFS: def __init__(self, files): self.files = files + def mount(self, readonly, mksfs): pass + def umount(self): pass + def stat(self, path): - print('stat', path) + print("stat", path) if path in self.files: return (32768, 0, 0, 0, 0, 0, 0, 0, 0, 0) raise OSError + def open(self, path, mode): - print('open', path, mode) + print("open", path, mode) return UserFile(self.files[path]) # create and mount a user filesystem user_files = { - '/data.txt': b"some data in a text file\n", - '/usermod1.py': b"print('in usermod1')\nimport usermod2", - '/usermod2.py': b"print('in usermod2')", + "/data.txt": b"some data in a text file\n", + "/usermod1.py": b"print('in usermod1')\nimport usermod2", + "/usermod2.py": b"print('in usermod2')", } -uos.mount(UserFS(user_files), '/userfs') +uos.mount(UserFS(user_files), "/userfs") # open and read a file -f = open('/userfs/data.txt') +f = open("/userfs/data.txt") print(f.read()) # import files from the user filesystem -sys.path.append('/userfs') +sys.path.append("/userfs") import usermod1 # unmount and undo path addition -uos.umount('/userfs') +uos.umount("/userfs") sys.path.pop() diff --git a/tests/extmod/websocket_basic.py b/tests/extmod/websocket_basic.py index 9a80503a03..8c5cf58257 100644 --- a/tests/extmod/websocket_basic.py +++ b/tests/extmod/websocket_basic.py @@ -11,6 +11,7 @@ def ws_read(msg, sz): ws = websocket.websocket(uio.BytesIO(msg)) return ws.read(sz) + # do a websocket write and then return the raw data from the stream def ws_write(msg, sz): s = uio.BytesIO() @@ -19,31 +20,32 @@ def ws_write(msg, sz): s.seek(0) return s.read(sz) + # basic frame print(ws_read(b"\x81\x04ping", 4)) -print(ws_read(b"\x80\x04ping", 4)) # FRAME_CONT +print(ws_read(b"\x80\x04ping", 4)) # FRAME_CONT print(ws_write(b"pong", 6)) # split frames are not supported # print(ws_read(b"\x01\x04ping", 4)) # extended payloads -print(ws_read(b'\x81~\x00\x80' + b'ping' * 32, 128)) +print(ws_read(b"\x81~\x00\x80" + b"ping" * 32, 128)) print(ws_write(b"pong" * 32, 132)) # mask (returned data will be 'mask' ^ 'mask') print(ws_read(b"\x81\x84maskmask", 4)) # close control frame -s = uio.BytesIO(b'\x88\x00') # FRAME_CLOSE +s = uio.BytesIO(b"\x88\x00") # FRAME_CLOSE ws = websocket.websocket(s) print(ws.read(1)) s.seek(2) print(s.read(4)) # misc control frames -print(ws_read(b"\x89\x00\x81\x04ping", 4)) # FRAME_PING -print(ws_read(b"\x8a\x00\x81\x04pong", 4)) # FRAME_PONG +print(ws_read(b"\x89\x00\x81\x04ping", 4)) # FRAME_PING +print(ws_read(b"\x8a\x00\x81\x04pong", 4)) # FRAME_PONG # close method ws = websocket.websocket(uio.BytesIO()) @@ -51,8 +53,8 @@ ws.close() # ioctl ws = websocket.websocket(uio.BytesIO()) -print(ws.ioctl(8)) # GET_DATA_OPTS -print(ws.ioctl(9, 2)) # SET_DATA_OPTS +print(ws.ioctl(8)) # GET_DATA_OPTS +print(ws.ioctl(9, 2)) # SET_DATA_OPTS print(ws.ioctl(9)) try: ws.ioctl(-1) diff --git a/tests/feature_check/byteorder.py b/tests/feature_check/byteorder.py index d60f939568..c82a41a24b 100644 --- a/tests/feature_check/byteorder.py +++ b/tests/feature_check/byteorder.py @@ -1,2 +1,3 @@ import sys + print(sys.byteorder) diff --git a/tests/feature_check/complex.py b/tests/feature_check/complex.py index a22eb52ce3..7576dcb953 100644 --- a/tests/feature_check/complex.py +++ b/tests/feature_check/complex.py @@ -3,4 +3,3 @@ try: print("complex") except NameError: print("no") - diff --git a/tests/feature_check/coverage.py b/tests/feature_check/coverage.py index dcda53eae2..82647ee314 100644 --- a/tests/feature_check/coverage.py +++ b/tests/feature_check/coverage.py @@ -1,5 +1,5 @@ try: extra_coverage - print('coverage') + print("coverage") except NameError: - print('no') + print("no") diff --git a/tests/feature_check/float.py b/tests/feature_check/float.py index af93f59763..d6d2a99d24 100644 --- a/tests/feature_check/float.py +++ b/tests/feature_check/float.py @@ -5,9 +5,9 @@ try: except NameError: print(0) else: - if float('1.0000001') == float('1.0'): + if float("1.0000001") == float("1.0"): print(30) - elif float('1e300') == float('inf'): + elif float("1e300") == float("inf"): print(32) else: print(64) diff --git a/tests/feature_check/reverse_ops.py b/tests/feature_check/reverse_ops.py index 668748bc57..68eb91b44e 100644 --- a/tests/feature_check/reverse_ops.py +++ b/tests/feature_check/reverse_ops.py @@ -1,8 +1,8 @@ class Foo: - def __radd__(self, other): pass + try: 5 + Foo() except TypeError: diff --git a/tests/float/array_construct.py b/tests/float/array_construct.py index 938675835b..6b5c996312 100644 --- a/tests/float/array_construct.py +++ b/tests/float/array_construct.py @@ -6,5 +6,5 @@ except ImportError: print("SKIP") raise SystemExit -print(array('f', array('h', [1, 2]))) -print(array('d', array('f', [1, 2]))) +print(array("f", array("h", [1, 2]))) +print(array("d", array("f", [1, 2]))) diff --git a/tests/float/builtin_float_abs.py b/tests/float/builtin_float_abs.py index c0935c6eec..f7ce9e156f 100644 --- a/tests/float/builtin_float_abs.py +++ b/tests/float/builtin_float_abs.py @@ -1,13 +1,13 @@ # test builtin abs function with float args for val in ( - '1.0', - '-1.0', - '0.0', - '-0.0', - 'nan', - '-nan', - 'inf', - '-inf', - ): + "1.0", + "-1.0", + "0.0", + "-0.0", + "nan", + "-nan", + "inf", + "-inf", +): print(val, abs(float(val))) diff --git a/tests/float/builtin_float_hash.py b/tests/float/builtin_float_hash.py index 7a7e374010..1388bb0e83 100644 --- a/tests/float/builtin_float_hash.py +++ b/tests/float/builtin_float_hash.py @@ -2,24 +2,24 @@ # these should hash to an integer with a specific value for val in ( - '0.0', - '-0.0', - '1.0', - '2.0', - '-12.0', - '12345.0', - ): + "0.0", + "-0.0", + "1.0", + "2.0", + "-12.0", + "12345.0", +): print(val, hash(float(val))) # just check that these values are hashable for val in ( - '0.1', - '-0.1', - '10.3', - '0.4e3', - '1e16', - 'inf', - '-inf', - 'nan', - ): + "0.1", + "-0.1", + "10.3", + "0.4e3", + "1e16", + "inf", + "-inf", + "nan", +): print(val, type(hash(float(val)))) diff --git a/tests/float/builtin_float_minmax.py b/tests/float/builtin_float_minmax.py index 266ed133d5..8a53746e5d 100644 --- a/tests/float/builtin_float_minmax.py +++ b/tests/float/builtin_float_minmax.py @@ -29,4 +29,3 @@ print(min([1, 2.9, 4, 6.5, -1, 2])) print(max([1, 2.9, 4, 6.5, -1, 2])) print(min([1, 2.9, 4, -6.5, -1, 2])) print(max([1, 2.9, 4, -6.5, -1, 2])) - diff --git a/tests/float/builtin_float_pow.py b/tests/float/builtin_float_pow.py index 2de1b48176..98998bdc7c 100644 --- a/tests/float/builtin_float_pow.py +++ b/tests/float/builtin_float_pow.py @@ -6,6 +6,6 @@ print(pow(1.0, 1)) print(pow(2.0, 3.0)) print(pow(2.0, -4.0)) -print(pow(0.0, float('inf'))) -print(pow(0.0, float('-inf'))) -print(pow(0.0, float('nan'))) +print(pow(0.0, float("inf"))) +print(pow(0.0, float("-inf"))) +print(pow(0.0, float("nan"))) diff --git a/tests/float/builtin_float_round.py b/tests/float/builtin_float_round.py index 63cb39aa35..1153b8a2bf 100644 --- a/tests/float/builtin_float_round.py +++ b/tests/float/builtin_float_round.py @@ -2,8 +2,18 @@ # check basic cases tests = [ - [0.0], [1.0], [0.1], [-0.1], [123.4], [123.6], [-123.4], [-123.6], - [1.234567, 5], [1.23456, 1], [1.23456, 0], [1234.56, -2] + [0.0], + [1.0], + [0.1], + [-0.1], + [123.4], + [123.6], + [-123.4], + [-123.6], + [1.234567, 5], + [1.23456, 1], + [1.23456, 0], + [1234.56, -2], ] for t in tests: print(round(*t)) @@ -17,7 +27,7 @@ for i in range(-1, 3): print(round(1.47, i)) # test inf and nan -for val in (float('inf'), float('nan')): +for val in (float("inf"), float("nan")): try: round(val) except (ValueError, OverflowError) as e: diff --git a/tests/float/builtin_float_round_intbig.py b/tests/float/builtin_float_round_intbig.py index 2083e3ea3a..c8a338eefd 100644 --- a/tests/float/builtin_float_round_intbig.py +++ b/tests/float/builtin_float_round_intbig.py @@ -1,4 +1,4 @@ # test round() with floats that return large integers for x in (-1e25, 1e25): - print('%.3g' % round(x)) + print("%.3g" % round(x)) diff --git a/tests/float/bytearray_construct.py b/tests/float/bytearray_construct.py index e960d624ec..f84fa7be58 100644 --- a/tests/float/bytearray_construct.py +++ b/tests/float/bytearray_construct.py @@ -6,4 +6,4 @@ except ImportError: print("SKIP") raise SystemExit -print(bytearray(array('f', [1, 2.3]))) +print(bytearray(array("f", [1, 2.3]))) diff --git a/tests/float/bytes_construct.py b/tests/float/bytes_construct.py index 0e4482e436..c24263758e 100644 --- a/tests/float/bytes_construct.py +++ b/tests/float/bytes_construct.py @@ -6,4 +6,4 @@ except ImportError: print("SKIP") raise SystemExit -print(bytes(array('f', [1, 2.3]))) +print(bytes(array("f", [1, 2.3]))) diff --git a/tests/float/cmath_fun.py b/tests/float/cmath_fun.py index d3df25e111..5622918282 100644 --- a/tests/float/cmath_fun.py +++ b/tests/float/cmath_fun.py @@ -11,29 +11,35 @@ print("%.5g" % e) print("%.5g" % pi) test_values_non_zero = [] -base_values = (0.0, 0.5, 1.2345, 10.) +base_values = (0.0, 0.5, 1.2345, 10.0) for r in base_values: for i in base_values: - if r != 0. or i != 0.: + if r != 0.0 or i != 0.0: test_values_non_zero.append(complex(r, i)) - if r != 0.: + if r != 0.0: test_values_non_zero.append(complex(-r, i)) - if i != 0.: + if i != 0.0: test_values_non_zero.append(complex(r, -i)) - if r != 0. and i != 0.: + if r != 0.0 and i != 0.0: test_values_non_zero.append(complex(-r, -i)) -test_values = [complex(0., 0.),] + test_values_non_zero +test_values = [ + complex(0.0, 0.0), +] + test_values_non_zero print(test_values) functions = [ - ('phase', phase, test_values), - ('polar', polar, test_values), - ('rect', rect, ((0, 0), (0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (-1, 1), (1, -1), (123., -456.))), - ('exp', exp, test_values), - ('log', log, test_values_non_zero), - ('sqrt', sqrt, test_values), - ('cos', cos, test_values), - ('sin', sin, test_values), + ("phase", phase, test_values), + ("polar", polar, test_values), + ( + "rect", + rect, + ((0, 0), (0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (-1, 1), (1, -1), (123.0, -456.0)), + ), + ("exp", exp, test_values), + ("log", log, test_values_non_zero), + ("sqrt", sqrt, test_values), + ("cos", cos, test_values), + ("sin", sin, test_values), ] for f_name, f, test_vals in functions: @@ -51,5 +57,5 @@ for f_name, f, test_vals in functions: # some test (eg cmath.sqrt(-0.5)) disagree with CPython with tiny real part real = ret.real if abs(real) < 1e-6: - real = 0. + real = 0.0 print("complex(%.5g, %.5g)" % (real, ret.imag)) diff --git a/tests/float/cmath_fun_special.py b/tests/float/cmath_fun_special.py index 471fda8c0d..33b94d04db 100644 --- a/tests/float/cmath_fun_special.py +++ b/tests/float/cmath_fun_special.py @@ -2,26 +2,27 @@ try: from cmath import * + log10 except (ImportError, NameError): print("SKIP") raise SystemExit test_values_non_zero = [] -base_values = (0.0, 0.5, 1.2345, 10.) +base_values = (0.0, 0.5, 1.2345, 10.0) for r in base_values: for i in base_values: - if r != 0. or i != 0.: + if r != 0.0 or i != 0.0: test_values_non_zero.append(complex(r, i)) - if r != 0.: + if r != 0.0: test_values_non_zero.append(complex(-r, i)) - if i != 0.: + if i != 0.0: test_values_non_zero.append(complex(r, -i)) - if r != 0. and i != 0.: + if r != 0.0 and i != 0.0: test_values_non_zero.append(complex(-r, -i)) functions = [ - ('log10', log10, test_values_non_zero), + ("log10", log10, test_values_non_zero), ] for f_name, f, test_vals in functions: diff --git a/tests/float/complex1.py b/tests/float/complex1.py index 479b4b3485..e6338551c5 100644 --- a/tests/float/complex1.py +++ b/tests/float/complex1.py @@ -27,18 +27,23 @@ print(1j * 2j) print(1j / 2) print((1j / 2j).real) print(1j / (1 + 2j)) -ans = 0j ** 0; print("%.5g %.5g" % (ans.real, ans.imag)) -ans = 0j ** 1; print("%.5g %.5g" % (ans.real, ans.imag)) -ans = 0j ** 0j; print("%.5g %.5g" % (ans.real, ans.imag)) -ans = 1j ** 2.5; print("%.5g %.5g" % (ans.real, ans.imag)) -ans = 1j ** 2.5j; print("%.5g %.5g" % (ans.real, ans.imag)) +ans = 0j ** 0 +print("%.5g %.5g" % (ans.real, ans.imag)) +ans = 0j ** 1 +print("%.5g %.5g" % (ans.real, ans.imag)) +ans = 0j ** 0j +print("%.5g %.5g" % (ans.real, ans.imag)) +ans = 1j ** 2.5 +print("%.5g %.5g" % (ans.real, ans.imag)) +ans = 1j ** 2.5j +print("%.5g %.5g" % (ans.real, ans.imag)) # comparison print(1j == 1) print(1j == 1j) # comparison of nan is special -nan = float('nan') * 1j +nan = float("nan") * 1j print(nan == 1j) print(nan == nan) @@ -54,20 +59,22 @@ print(type(hash(1j))) print(1.2 + 3j) # negative base and fractional power should create a complex -ans = (-1) ** 2.3; print("%.5g %.5g" % (ans.real, ans.imag)) -ans = (-1.2) ** -3.4; print("%.5g %.5g" % (ans.real, ans.imag)) +ans = (-1) ** 2.3 +print("%.5g %.5g" % (ans.real, ans.imag)) +ans = (-1.2) ** -3.4 +print("%.5g %.5g" % (ans.real, ans.imag)) # check printing of inf/nan -print(float('nan') * 1j) -print(float('-nan') * 1j) -print(float('inf') * (1 + 1j)) -print(float('-inf') * (1 + 1j)) +print(float("nan") * 1j) +print(float("-nan") * 1j) +print(float("inf") * (1 + 1j)) +print(float("-inf") * (1 + 1j)) # can't assign to attributes try: (1j).imag = 0 except AttributeError: - print('AttributeError') + print("AttributeError") # can't convert rhs to complex try: @@ -93,11 +100,11 @@ try: except TypeError: print("TypeError") -#small int on LHS, complex on RHS, unsupported op +# small int on LHS, complex on RHS, unsupported op try: print(1 | 1j) except TypeError: - print('TypeError') + print("TypeError") # zero division try: diff --git a/tests/float/complex1_intbig.py b/tests/float/complex1_intbig.py index ed2390bbaf..864036b991 100644 --- a/tests/float/complex1_intbig.py +++ b/tests/float/complex1_intbig.py @@ -1,4 +1,5 @@ # test basic complex number functionality # convert bignum to complex on rhs -ans = 1j + (1 << 70); print("%.5g %.5g" % (ans.real, ans.imag)) +ans = 1j + (1 << 70) +print("%.5g %.5g" % (ans.real, ans.imag)) diff --git a/tests/float/float1.py b/tests/float/float1.py index 54807e5ac9..e51e96fd99 100644 --- a/tests/float/float1.py +++ b/tests/float/float1.py @@ -1,11 +1,11 @@ # test basic float capabilities # literals -print(.12) -print(1.) +print(0.12) +print(1.0) print(1.2) print(0e0) -print(0e+0) +print(0e0) print(0e-0) # float construction @@ -66,7 +66,7 @@ print(1.2 >= 3.4) print(1.2 >= -3.4) # comparison of nan is special -nan = float('nan') +nan = float("nan") print(nan == 1.2) print(nan == nan) @@ -106,7 +106,7 @@ except TypeError: try: print(1 | 1.0) except TypeError: - print('TypeError') + print("TypeError") # can't convert list to float try: diff --git a/tests/float/float2int_doubleprec_intbig.py b/tests/float/float2int_doubleprec_intbig.py index de2137d66c..24d30fe691 100644 --- a/tests/float/float2int_doubleprec_intbig.py +++ b/tests/float/float2int_doubleprec_intbig.py @@ -6,6 +6,7 @@ except: import struct import sys + maxsize_bits = 0 maxsize = sys.maxsize while maxsize: @@ -31,32 +32,33 @@ if ll_type is None: # This case occurs with time.time() values if ll_type != 0: - print(int(1418774543.)) - print("%d" % 1418774543.) + print(int(1418774543.0)) + print("%d" % 1418774543.0) if ll_type == 3: - print(int(2.**100)) - print("%d" % 2.**100) + print(int(2.0 ** 100)) + print("%d" % 2.0 ** 100) else: - print(int(1073741823.)) - print("%d" % 1073741823.) + print(int(1073741823.0)) + print("%d" % 1073741823.0) testpass = True -p2_rng = ((30,63,1024),(62,63,1024))[is_64bit][ll_type] -for i in range(0,p2_rng): - bitcnt = len(bin(int(2.**i))) - 3; +p2_rng = ((30, 63, 1024), (62, 63, 1024))[is_64bit][ll_type] +for i in range(0, p2_rng): + bitcnt = len(bin(int(2.0 ** i))) - 3 if i != bitcnt: - print('fail: 2**%u was %u bits long' % (i, bitcnt)); + print("fail: 2**%u was %u bits long" % (i, bitcnt)) testpass = False -print("power of 2 test: %s" % (testpass and 'passed' or 'failed')) +print("power of 2 test: %s" % (testpass and "passed" or "failed")) testpass = True -p10_rng = ((9,18,23),(18,18,23))[is_64bit][ll_type] -for i in range(0,p10_rng): - digcnt = len(str(int(10.**i))) - 1; +p10_rng = ((9, 18, 23), (18, 18, 23))[is_64bit][ll_type] +for i in range(0, p10_rng): + digcnt = len(str(int(10.0 ** i))) - 1 if i != digcnt: - print('fail: 10**%u was %u digits long' % (i, digcnt)); + print("fail: 10**%u was %u digits long" % (i, digcnt)) testpass = False -print("power of 10 test: %s" % (testpass and 'passed' or 'failed')) +print("power of 10 test: %s" % (testpass and "passed" or "failed")) + def fp2int_test(num, name, should_fail): try: @@ -64,37 +66,38 @@ def fp2int_test(num, name, should_fail): passed = ~should_fail except: passed = should_fail - print('%s: %s' % (name, passed and 'passed' or 'failed')) + print("%s: %s" % (name, passed and "passed" or "failed")) + if ll_type != 2: if ll_type == 0: if is_64bit: - neg_bad_fp = -1.00000005*2.**62. - pos_bad_fp = 2.**62. - neg_good_fp = -2.**62. - pos_good_fp = 0.99999993*2.**62. + neg_bad_fp = -1.00000005 * 2.0 ** 62.0 + pos_bad_fp = 2.0 ** 62.0 + neg_good_fp = -(2.0 ** 62.0) + pos_good_fp = 0.99999993 * 2.0 ** 62.0 else: - neg_bad_fp = -1.00000005*2.**30. - pos_bad_fp = 2.**30. - neg_good_fp = -2.**30. - pos_good_fp = 0.9999999499*2.**30. + neg_bad_fp = -1.00000005 * 2.0 ** 30.0 + pos_bad_fp = 2.0 ** 30.0 + neg_good_fp = -(2.0 ** 30.0) + pos_good_fp = 0.9999999499 * 2.0 ** 30.0 else: - neg_bad_fp = -0.51*2.**64. - pos_bad_fp = 2.**63. - neg_good_fp = -2.**63. - pos_good_fp = 1.9999998*2.**62. + neg_bad_fp = -0.51 * 2.0 ** 64.0 + pos_bad_fp = 2.0 ** 63.0 + neg_good_fp = -(2.0 ** 63.0) + pos_good_fp = 1.9999998 * 2.0 ** 62.0 - fp2int_test(neg_bad_fp, 'neg bad', True) - fp2int_test(pos_bad_fp, 'pos bad', True) - fp2int_test(neg_good_fp, 'neg good', False) - fp2int_test(pos_good_fp, 'pos good', False) + fp2int_test(neg_bad_fp, "neg bad", True) + fp2int_test(pos_bad_fp, "pos bad", True) + fp2int_test(neg_good_fp, "neg good", False) + fp2int_test(pos_good_fp, "pos good", False) else: - fp2int_test(-1.9999999999999981*2.**1023., 'large neg', False) - fp2int_test(1.9999999999999981*2.**1023., 'large pos', False) + fp2int_test(-1.9999999999999981 * 2.0 ** 1023.0, "large neg", False) + fp2int_test(1.9999999999999981 * 2.0 ** 1023.0, "large pos", False) -fp2int_test(float('inf'), 'inf test', True) -fp2int_test(float('nan'), 'NaN test', True) +fp2int_test(float("inf"), "inf test", True) +fp2int_test(float("nan"), "NaN test", True) # test numbers < 1 (this used to fail; see issue #1044) -fp2int_test(0.0001, 'small num', False) -struct.pack('I', int(1/2)) +fp2int_test(0.0001, "small num", False) +struct.pack("I", int(1 / 2)) diff --git a/tests/float/float2int_fp30_intbig.py b/tests/float/float2int_fp30_intbig.py index fbb94a4ccc..da39800401 100644 --- a/tests/float/float2int_fp30_intbig.py +++ b/tests/float/float2int_fp30_intbig.py @@ -6,6 +6,7 @@ except: import struct import sys + maxsize_bits = 0 maxsize = sys.maxsize while maxsize: @@ -30,30 +31,31 @@ if ll_type is None: ll_type = 2 # basic conversion -print(int(14187744.)) -print("%d" % 14187744.) +print(int(14187744.0)) +print("%d" % 14187744.0) if ll_type == 2: - print(int(2.**100)) - print("%d" % 2.**100) + print(int(2.0 ** 100)) + print("%d" % 2.0 ** 100) testpass = True -p2_rng = ((30,63,127),(62,63,127))[is_64bit][ll_type] -for i in range(0,p2_rng): - bitcnt = len(bin(int(2.**i))) - 3; +p2_rng = ((30, 63, 127), (62, 63, 127))[is_64bit][ll_type] +for i in range(0, p2_rng): + bitcnt = len(bin(int(2.0 ** i))) - 3 if i != bitcnt: - print('fail: 2.**%u was %u bits long' % (i, bitcnt)); + print("fail: 2.**%u was %u bits long" % (i, bitcnt)) testpass = False -print("power of 2 test: %s" % (testpass and 'passed' or 'failed')) +print("power of 2 test: %s" % (testpass and "passed" or "failed")) # TODO why does 10**12 fail this test for single precision float? testpass = True p10_rng = 9 -for i in range(0,p10_rng): - digcnt = len(str(int(10.**i))) - 1; +for i in range(0, p10_rng): + digcnt = len(str(int(10.0 ** i))) - 1 if i != digcnt: - print('fail: 10.**%u was %u digits long' % (i, digcnt)); + print("fail: 10.**%u was %u digits long" % (i, digcnt)) testpass = False -print("power of 10 test: %s" % (testpass and 'passed' or 'failed')) +print("power of 10 test: %s" % (testpass and "passed" or "failed")) + def fp2int_test(num, name, should_fail): try: @@ -61,37 +63,38 @@ def fp2int_test(num, name, should_fail): passed = ~should_fail except: passed = should_fail - print('%s: %s' % (name, passed and 'passed' or 'failed')) + print("%s: %s" % (name, passed and "passed" or "failed")) + if ll_type != 2: if ll_type == 0: if is_64bit: - neg_bad_fp = -1.00000005*2.**62. - pos_bad_fp = 2.**62. - neg_good_fp = -2.**62. - pos_good_fp = 0.99999993*2.**62. + neg_bad_fp = -1.00000005 * 2.0 ** 62.0 + pos_bad_fp = 2.0 ** 62.0 + neg_good_fp = -(2.0 ** 62.0) + pos_good_fp = 0.99999993 * 2.0 ** 62.0 else: - neg_bad_fp = -1.00000005*2.**30. - pos_bad_fp = 2.**30. - neg_good_fp = -2.**30. - pos_good_fp = 0.9999999499*2.**30. + neg_bad_fp = -1.00000005 * 2.0 ** 30.0 + pos_bad_fp = 2.0 ** 30.0 + neg_good_fp = -(2.0 ** 30.0) + pos_good_fp = 0.9999999499 * 2.0 ** 30.0 else: - neg_bad_fp = -0.51*2.**64. - pos_bad_fp = 2.**63. - neg_good_fp = -2.**63. - pos_good_fp = 1.9999998*2.**62. + neg_bad_fp = -0.51 * 2.0 ** 64.0 + pos_bad_fp = 2.0 ** 63.0 + neg_good_fp = -(2.0 ** 63.0) + pos_good_fp = 1.9999998 * 2.0 ** 62.0 - fp2int_test(neg_bad_fp, 'neg bad', True) - fp2int_test(pos_bad_fp, 'pos bad', True) - fp2int_test(neg_good_fp, 'neg good', False) - fp2int_test(pos_good_fp, 'pos good', False) + fp2int_test(neg_bad_fp, "neg bad", True) + fp2int_test(pos_bad_fp, "pos bad", True) + fp2int_test(neg_good_fp, "neg good", False) + fp2int_test(pos_good_fp, "pos good", False) else: - fp2int_test(-1.999999879*2.**126., 'large neg', False) - fp2int_test(1.999999879*2.**126., 'large pos', False) + fp2int_test(-1.999999879 * 2.0 ** 126.0, "large neg", False) + fp2int_test(1.999999879 * 2.0 ** 126.0, "large pos", False) -fp2int_test(float('inf'), 'inf test', True) -fp2int_test(float('nan'), 'NaN test', True) +fp2int_test(float("inf"), "inf test", True) +fp2int_test(float("nan"), "NaN test", True) # test numbers < 1 (this used to fail; see issue #1044) -fp2int_test(0.0001, 'small num', False) -struct.pack('I', int(1/2)) +fp2int_test(0.0001, "small num", False) +struct.pack("I", int(1 / 2)) diff --git a/tests/float/float2int_intbig.py b/tests/float/float2int_intbig.py index 3596d2f73d..30522d44ff 100644 --- a/tests/float/float2int_intbig.py +++ b/tests/float/float2int_intbig.py @@ -32,30 +32,31 @@ if ll_type is None: # basic conversion -print(int(14187745.)) -print("%d" % 14187745.) +print(int(14187745.0)) +print("%d" % 14187745.0) if ll_type == 2: - print(int(2.**100)) - print("%d" % 2.**100) + print(int(2.0 ** 100)) + print("%d" % 2.0 ** 100) testpass = True -p2_rng = ((30,63,127),(62,63,127))[is_64bit][ll_type] -for i in range(0,p2_rng): - bitcnt = len(bin(int(2.**i))) - 3; +p2_rng = ((30, 63, 127), (62, 63, 127))[is_64bit][ll_type] +for i in range(0, p2_rng): + bitcnt = len(bin(int(2.0 ** i))) - 3 if i != bitcnt: - print('fail: 2.**%u was %u bits long' % (i, bitcnt)); + print("fail: 2.**%u was %u bits long" % (i, bitcnt)) testpass = False -print("power of 2 test: %s" % (testpass and 'passed' or 'failed')) +print("power of 2 test: %s" % (testpass and "passed" or "failed")) # TODO why does 10**12 fail this test for single precision float? testpass = True p10_rng = 9 if (ll_type == 0 and ~is_64bit) else 11 -for i in range(0,p10_rng): - digcnt = len(str(int(10.**i))) - 1; +for i in range(0, p10_rng): + digcnt = len(str(int(10.0 ** i))) - 1 if i != digcnt: - print('fail: 10.**%u was %u digits long' % (i, digcnt)); + print("fail: 10.**%u was %u digits long" % (i, digcnt)) testpass = False -print("power of 10 test: %s" % (testpass and 'passed' or 'failed')) +print("power of 10 test: %s" % (testpass and "passed" or "failed")) + def fp2int_test(num, name, should_fail): try: @@ -63,37 +64,38 @@ def fp2int_test(num, name, should_fail): passed = ~should_fail except: passed = should_fail - print('%s: %s' % (name, passed and 'passed' or 'failed')) + print("%s: %s" % (name, passed and "passed" or "failed")) + if ll_type != 2: if ll_type == 0: if is_64bit: - neg_bad_fp = -1.00000005*2.**62. - pos_bad_fp = 2.**62. - neg_good_fp = -2.**62. - pos_good_fp = 0.99999993*2.**62. + neg_bad_fp = -1.00000005 * 2.0 ** 62.0 + pos_bad_fp = 2.0 ** 62.0 + neg_good_fp = -(2.0 ** 62.0) + pos_good_fp = 0.99999993 * 2.0 ** 62.0 else: - neg_bad_fp = -1.00000005*2.**30. - pos_bad_fp = 2.**30. - neg_good_fp = -2.**30. - pos_good_fp = 0.9999999499*2.**30. + neg_bad_fp = -1.00000005 * 2.0 ** 30.0 + pos_bad_fp = 2.0 ** 30.0 + neg_good_fp = -(2.0 ** 30.0) + pos_good_fp = 0.9999999499 * 2.0 ** 30.0 else: - neg_bad_fp = -0.51*2.**64. - pos_bad_fp = 2.**63. - neg_good_fp = -2.**63. - pos_good_fp = 1.9999998*2.**62. + neg_bad_fp = -0.51 * 2.0 ** 64.0 + pos_bad_fp = 2.0 ** 63.0 + neg_good_fp = -(2.0 ** 63.0) + pos_good_fp = 1.9999998 * 2.0 ** 62.0 - fp2int_test(neg_bad_fp, 'neg bad', True) - fp2int_test(pos_bad_fp, 'pos bad', True) - fp2int_test(neg_good_fp, 'neg good', False) - fp2int_test(pos_good_fp, 'pos good', False) + fp2int_test(neg_bad_fp, "neg bad", True) + fp2int_test(pos_bad_fp, "pos bad", True) + fp2int_test(neg_good_fp, "neg good", False) + fp2int_test(pos_good_fp, "pos good", False) else: - fp2int_test(-1.999999879*2.**127., 'large neg', False) - fp2int_test(1.999999879*2.**127., 'large pos', False) + fp2int_test(-1.999999879 * 2.0 ** 127.0, "large neg", False) + fp2int_test(1.999999879 * 2.0 ** 127.0, "large pos", False) -fp2int_test(float('inf'), 'inf test', True) -fp2int_test(float('nan'), 'NaN test', True) +fp2int_test(float("inf"), "inf test", True) +fp2int_test(float("nan"), "NaN test", True) # test numbers < 1 (this used to fail; see issue #1044) -fp2int_test(0.0001, 'small num', False) -struct.pack('I', int(1/2)) +fp2int_test(0.0001, "small num", False) +struct.pack("I", int(1 / 2)) diff --git a/tests/float/float_array.py b/tests/float/float_array.py index 8c8edcff7c..04212c44f4 100644 --- a/tests/float/float_array.py +++ b/tests/float/float_array.py @@ -4,17 +4,19 @@ except ImportError: print("SKIP") raise SystemExit + def test(a): print(a) a.append(1.2) - print(len(a), '%.3f' % a[0]) + print(len(a), "%.3f" % a[0]) a.append(1) a.append(False) - print(len(a), '%.3f %.3f' % (a[1], a[2])) + print(len(a), "%.3f %.3f" % (a[1], a[2])) a[-1] = 3.45 - print('%.3f' % a[-1]) + print("%.3f" % a[-1]) -test(array('f')) -test(array('d')) -print('{:.4f}'.format(array('f', b'\xcc\xcc\xcc=')[0])) +test(array("f")) +test(array("d")) + +print("{:.4f}".format(array("f", b"\xcc\xcc\xcc=")[0])) diff --git a/tests/float/float_compare.py b/tests/float/float_compare.py index 105923ac73..c177aa7e81 100644 --- a/tests/float/float_compare.py +++ b/tests/float/float_compare.py @@ -1,8 +1,10 @@ # Extended float comparisons + class Foo: pass + foo = Foo() print(foo == 1.0) diff --git a/tests/float/float_divmod.py b/tests/float/float_divmod.py index 8e7cd435a5..ec83ce2d19 100644 --- a/tests/float/float_divmod.py +++ b/tests/float/float_divmod.py @@ -1,11 +1,13 @@ # test floating point floor divide and modulus # it has some tricky corner cases + def test(x, y): div, mod = divmod(x, y) - print('%.8f %.8f %.8f %.8f' % (x // y, x % y, div, mod)) + print("%.8f %.8f %.8f %.8f" % (x // y, x % y, div, mod)) print(div == x // y, mod == x % y, abs(div * y + mod - x) < 1e-15) + test(1.23456, 0.7) test(-1.23456, 0.7) test(1.23456, -0.7) diff --git a/tests/float/float_divmod_relaxed.py b/tests/float/float_divmod_relaxed.py index a9450fa2c4..ef5a6ad2e8 100644 --- a/tests/float/float_divmod_relaxed.py +++ b/tests/float/float_divmod_relaxed.py @@ -4,10 +4,12 @@ # pyboard has 32-bit floating point and gives different (but still # correct) answers for certain combinations of divmod arguments. + def test(x, y): div, mod = divmod(x, y) print(div == x // y, mod == x % y, abs(div * y + mod - x) < 1e-6) + test(1.23456, 0.7) test(-1.23456, 0.7) test(1.23456, -0.7) @@ -30,4 +32,4 @@ for i in range(25): try: divmod(1.0, 0) except ZeroDivisionError: - print('ZeroDivisionError') + print("ZeroDivisionError") diff --git a/tests/float/float_format.py b/tests/float/float_format.py index d43535cf2f..4c8a217567 100644 --- a/tests/float/float_format.py +++ b/tests/float/float_format.py @@ -2,18 +2,18 @@ # general rounding for val in (116, 1111, 1234, 5010, 11111): - print('%.0f' % val) - print('%.1f' % val) - print('%.3f' % val) + print("%.0f" % val) + print("%.1f" % val) + print("%.3f" % val) # make sure rounding is done at the correct precision for prec in range(8): - print(('%%.%df' % prec) % 6e-5) + print(("%%.%df" % prec) % 6e-5) # check certain cases that had a digit value of 10 render as a ":" character -print('%.2e' % float('9' * 51 + 'e-39')) -print('%.2e' % float('9' * 40 + 'e-21')) +print("%.2e" % float("9" * 51 + "e-39")) +print("%.2e" % float("9" * 40 + "e-21")) # check a case that would render negative digit values, eg ")" characters # the string is converted back to a float to check for no illegal characters -float('%.23e' % 1e-80) +float("%.23e" % 1e-80) diff --git a/tests/float/float_parse.py b/tests/float/float_parse.py index 4b5fc613d3..de27c33e7b 100644 --- a/tests/float/float_parse.py +++ b/tests/float/float_parse.py @@ -1,36 +1,36 @@ # test parsing of floats -inf = float('inf') +inf = float("inf") # it shouldn't matter where the decimal point is if the exponent balances the value -print(float('1234') - float('0.1234e4')) -print(float('1.015625') - float('1015625e-6')) +print(float("1234") - float("0.1234e4")) +print(float("1.015625") - float("1015625e-6")) # very large integer part with a very negative exponent should cancel out -print('%.4e' % float('9' * 60 + 'e-60')) -print('%.4e' % float('9' * 60 + 'e-40')) +print("%.4e" % float("9" * 60 + "e-60")) +print("%.4e" % float("9" * 60 + "e-40")) # many fractional digits -print(float('.' + '9' * 70)) -print(float('.' + '9' * 70 + 'e20')) -print(float('.' + '9' * 70 + 'e-50') == float('1e-50')) +print(float("." + "9" * 70)) +print(float("." + "9" * 70 + "e20")) +print(float("." + "9" * 70 + "e-50") == float("1e-50")) # tiny fraction with large exponent -print(float('.' + '0' * 60 + '1e10') == float('1e-51')) -print(float('.' + '0' * 60 + '9e25') == float('9e-36')) -print(float('.' + '0' * 60 + '9e40') == float('9e-21')) +print(float("." + "0" * 60 + "1e10") == float("1e-51")) +print(float("." + "0" * 60 + "9e25") == float("9e-36")) +print(float("." + "0" * 60 + "9e40") == float("9e-21")) # ensure that accuracy is retained when value is close to a subnormal -print(float('1.00000000000000000000e-37')) -print(float('10.0000000000000000000e-38')) -print(float('100.000000000000000000e-39')) +print(float("1.00000000000000000000e-37")) +print(float("10.0000000000000000000e-38")) +print(float("100.000000000000000000e-39")) # very large exponent literal -print(float('1e4294967301')) -print(float('1e-4294967301')) -print(float('1e18446744073709551621')) -print(float('1e-18446744073709551621')) +print(float("1e4294967301")) +print(float("1e-4294967301")) +print(float("1e18446744073709551621")) +print(float("1e-18446744073709551621")) # check small decimals are as close to their true value as possible for n in range(1, 10): - print(float('0.%u' % n) == n / 10) + print(float("0.%u" % n) == n / 10) diff --git a/tests/float/float_parse_doubleprec.py b/tests/float/float_parse_doubleprec.py index dcc0dd5921..81fcadcee8 100644 --- a/tests/float/float_parse_doubleprec.py +++ b/tests/float/float_parse_doubleprec.py @@ -1,21 +1,21 @@ # test parsing of floats, requiring double-precision # very large integer part with a very negative exponent should cancel out -print(float('9' * 400 + 'e-100')) -print(float('9' * 400 + 'e-200')) -print(float('9' * 400 + 'e-400')) +print(float("9" * 400 + "e-100")) +print(float("9" * 400 + "e-200")) +print(float("9" * 400 + "e-400")) # many fractional digits -print(float('.' + '9' * 400)) -print(float('.' + '9' * 400 + 'e100')) -print(float('.' + '9' * 400 + 'e-100')) +print(float("." + "9" * 400)) +print(float("." + "9" * 400 + "e100")) +print(float("." + "9" * 400 + "e-100")) # tiny fraction with large exponent -print('%.14e' % float('.' + '0' * 400 + '9e100')) -print('%.14e' % float('.' + '0' * 400 + '9e200')) -print('%.14e' % float('.' + '0' * 400 + '9e400')) +print("%.14e" % float("." + "0" * 400 + "9e100")) +print("%.14e" % float("." + "0" * 400 + "9e200")) +print("%.14e" % float("." + "0" * 400 + "9e400")) # ensure that accuracy is retained when value is close to a subnormal -print(float('1.00000000000000000000e-307')) -print(float('10.0000000000000000000e-308')) -print(float('100.000000000000000000e-309')) +print(float("1.00000000000000000000e-307")) +print(float("10.0000000000000000000e-308")) +print(float("100.000000000000000000e-309")) diff --git a/tests/float/float_struct.py b/tests/float/float_struct.py index c4c186b89e..18893af0e0 100644 --- a/tests/float/float_struct.py +++ b/tests/float/float_struct.py @@ -8,11 +8,10 @@ except ImportError: print("SKIP") raise SystemExit -i = 1. + 1/2 +i = 1.0 + 1 / 2 # TODO: it looks like '=' format modifier is not yet supported # for fmt in ('f', 'd', '>f', '>d', 'f', '>d', 'f", ">d", "' + fmt.format(*args) + '<') + print("{:8s}".format(fmt) + ">" + fmt.format(*args) + "<") + test("{:10.4}", 123.456) test("{:10.4e}", 123.456) @@ -25,17 +26,17 @@ test("{:06e}", float("-inf")) test("{:06e}", float("nan")) # The following fails right now -#test("{:10.1}", 0.0) +# test("{:10.1}", 0.0) print("%.0f" % (1.750000 % 0.08333333333)) # Below isn't compatible with single-precision float -#print("%.1f" % (1.750000 % 0.08333333333)) -#print("%.2f" % (1.750000 % 0.08333333333)) -#print("%.12f" % (1.750000 % 0.08333333333)) +# print("%.1f" % (1.750000 % 0.08333333333)) +# print("%.2f" % (1.750000 % 0.08333333333)) +# print("%.12f" % (1.750000 % 0.08333333333)) # tests for errors in format string try: - '{:10.1b}'.format(0.0) + "{:10.1b}".format(0.0) except ValueError: - print('ValueError') + print("ValueError") diff --git a/tests/float/string_format2.py b/tests/float/string_format2.py index 269023e7ff..7a36f4d2f9 100644 --- a/tests/float/string_format2.py +++ b/tests/float/string_format2.py @@ -3,15 +3,17 @@ full_tests = False + def test(fmt, *args): - print('{:8s}'.format(fmt) + '>' + fmt.format(*args) + '<') + print("{:8s}".format(fmt) + ">" + fmt.format(*args) + "<") + def test_fmt(conv, fill, alignment, sign, prefix, width, precision, type, arg): - fmt = '{' + fmt = "{" if conv: - fmt += '!' + fmt += "!" fmt += conv - fmt += ':' + fmt += ":" if alignment: fmt += fill fmt += alignment @@ -19,88 +21,162 @@ def test_fmt(conv, fill, alignment, sign, prefix, width, precision, type, arg): fmt += prefix fmt += width if precision: - fmt += '.' + fmt += "." fmt += precision fmt += type - fmt += '}' - test(fmt, arg) - if fill == '0' and alignment == '=': - fmt = '{:' + fmt += "}" + test(fmt, arg) + if fill == "0" and alignment == "=": + fmt = "{:" fmt += sign fmt += prefix fmt += width if precision: - fmt += '.' + fmt += "." fmt += precision fmt += type - fmt += '}' + fmt += "}" test(fmt, arg) -eg_nums = (0.0, -0.0, 0.1, 1.234, 12.3459, 1.23456789, 123456789.0, -0.0, - -0.1, -1.234, -12.3459, 1e4, 1e-4, 1e5, 1e-5, 1e6, 1e-6, 1e10, - 1e37, -1e37, 1e-37, -1e-37, - 1.23456e8, 1.23456e7, 1.23456e6, 1.23456e5, 1.23456e4, 1.23456e3, 1.23456e2, 1.23456e1, 1.23456e0, - 1.23456e-1, 1.23456e-2, 1.23456e-3, 1.23456e-4, 1.23456e-5, 1.23456e-6, 1.23456e-7, 1.23456e-8, - -1.23456e8, -1.23456e7, -1.23456e6, -1.23456e5, -1.23456e4, -1.23456e3, -1.23456e2, -1.23456e1, -1.23456e0, - -1.23456e-1, -1.23456e-2, -1.23456e-3, -1.23456e-4, -1.23456e-5, -1.23456e-6, -1.23456e-7, -1.23456e-8) + +eg_nums = ( + 0.0, + -0.0, + 0.1, + 1.234, + 12.3459, + 1.23456789, + 123456789.0, + -0.0, + -0.1, + -1.234, + -12.3459, + 1e4, + 1e-4, + 1e5, + 1e-5, + 1e6, + 1e-6, + 1e10, + 1e37, + -1e37, + 1e-37, + -1e-37, + 1.23456e8, + 1.23456e7, + 1.23456e6, + 1.23456e5, + 1.23456e4, + 1.23456e3, + 1.23456e2, + 1.23456e1, + 1.23456e0, + 1.23456e-1, + 1.23456e-2, + 1.23456e-3, + 1.23456e-4, + 1.23456e-5, + 1.23456e-6, + 1.23456e-7, + 1.23456e-8, + -1.23456e8, + -1.23456e7, + -1.23456e6, + -1.23456e5, + -1.23456e4, + -1.23456e3, + -1.23456e2, + -1.23456e1, + -1.23456e0, + -1.23456e-1, + -1.23456e-2, + -1.23456e-3, + -1.23456e-4, + -1.23456e-5, + -1.23456e-6, + -1.23456e-7, + -1.23456e-8, +) if full_tests: - for type in ('e', 'E', 'g', 'G', 'n'): - for width in ('', '4', '6', '8', '10'): - for alignment in ('', '<', '>', '=', '^'): - for fill in ('', '@', '0', ' '): - for sign in ('', '+', '-', ' '): - for prec in ('', '1', '3', '6'): + for type in ("e", "E", "g", "G", "n"): + for width in ("", "4", "6", "8", "10"): + for alignment in ("", "<", ">", "=", "^"): + for fill in ("", "@", "0", " "): + for sign in ("", "+", "-", " "): + for prec in ("", "1", "3", "6"): for num in eg_nums: - test_fmt('', fill, alignment, sign, '', width, prec, type, num) + test_fmt("", fill, alignment, sign, "", width, prec, type, num) # Note: We use 1.23459 rather than 1.2345 because '{:3f}'.format(1.2345) # rounds differently than print("%.3f", 1.2345); -f_nums = (0.0, -0.0, 0.0001, 0.001, 0.01, 0.1, 1.0, 10.0, - 0.0012, 0.0123, 0.1234, 1.23459, 12.3456, - -0.0001, -0.001, -0.01, -0.1, -1.0, -10.0, - -0.0012, -0.0123, -0.1234, -1.23459, -12.3456) +f_nums = ( + 0.0, + -0.0, + 0.0001, + 0.001, + 0.01, + 0.1, + 1.0, + 10.0, + 0.0012, + 0.0123, + 0.1234, + 1.23459, + 12.3456, + -0.0001, + -0.001, + -0.01, + -0.1, + -1.0, + -10.0, + -0.0012, + -0.0123, + -0.1234, + -1.23459, + -12.3456, +) if full_tests: - for type in ('f', 'F'): - for width in ('', '4', '6', '8', '10'): - for alignment in ('', '<', '>', '=', '^'): - for fill in ('', ' ', '0', '@'): - for sign in ('', '+', '-', ' '): + for type in ("f", "F"): + for width in ("", "4", "6", "8", "10"): + for alignment in ("", "<", ">", "=", "^"): + for fill in ("", " ", "0", "@"): + for sign in ("", "+", "-", " "): # An empty precision defaults to 6, but when uPy is # configured to use a float, we can only use a # precision of 6 with numbers less than 10 and still # get results that compare to CPython (which uses # long doubles). - for prec in ('1', '2', '3'): + for prec in ("1", "2", "3"): for num in f_nums: - test_fmt('', fill, alignment, sign, '', width, prec, type, num) + test_fmt("", fill, alignment, sign, "", width, prec, type, num) for num in int_nums2: - test_fmt('', fill, alignment, sign, '', width, '', type, num) + test_fmt("", fill, alignment, sign, "", width, "", type, num) pct_nums1 = (0.1, 0.58, 0.99, -0.1, -0.58, -0.99) pct_nums2 = (True, False, 1, 0, -1) if full_tests: - type = '%' - for width in ('', '4', '6', '8', '10'): - for alignment in ('', '<', '>', '=', '^'): - for fill in ('', ' ', '0', '@'): - for sign in ('', '+', '-', ' '): + type = "%" + for width in ("", "4", "6", "8", "10"): + for alignment in ("", "<", ">", "=", "^"): + for fill in ("", " ", "0", "@"): + for sign in ("", "+", "-", " "): # An empty precision defaults to 6, but when uPy is # configured to use a float, we can only use a # precision of 6 with numbers less than 10 and still # get results that compare to CPython (which uses # long doubles). - for prec in ('1', '2', '3'): + for prec in ("1", "2", "3"): for num in pct_nums1: - test_fmt('', fill, alignment, sign, '', width, prec, type, num) + test_fmt("", fill, alignment, sign, "", width, prec, type, num) for num in pct_nums2: - test_fmt('', fill, alignment, sign, '', width, '', type, num) + test_fmt("", fill, alignment, sign, "", width, "", type, num) else: for num in pct_nums1: - test_fmt('', '', '', '', '', '', '1', '%', num) + test_fmt("", "", "", "", "", "", "1", "%", num) # We don't currently test a type of '' with floats (see the detailed comment # in objstr.c) diff --git a/tests/float/string_format_fp30.py b/tests/float/string_format_fp30.py index 77b2a52885..5f0b213daa 100644 --- a/tests/float/string_format_fp30.py +++ b/tests/float/string_format_fp30.py @@ -1,11 +1,12 @@ def test(fmt, *args): - print('{:8s}'.format(fmt) + '>' + fmt.format(*args) + '<') + print("{:8s}".format(fmt) + ">" + fmt.format(*args) + "<") + test("{:10.4}", 123.456) test("{:10.4e}", 123.456) test("{:10.4e}", -123.456) -#test("{:10.4f}", 123.456) -#test("{:10.4f}", -123.456) +# test("{:10.4f}", 123.456) +# test("{:10.4f}", -123.456) test("{:10.4g}", 123.456) test("{:10.4g}", -123.456) test("{:10.4n}", 123.456) @@ -15,8 +16,8 @@ test("{:g}", 300) test("{:10.4E}", 123.456) test("{:10.4E}", -123.456) -#test("{:10.4F}", 123.456) -#test("{:10.4F}", -123.456) +# test("{:10.4F}", 123.456) +# test("{:10.4F}", -123.456) test("{:10.4G}", 123.456) test("{:10.4G}", -123.456) @@ -25,17 +26,17 @@ test("{:06e}", float("-inf")) test("{:06e}", float("nan")) # The following fails right now -#test("{:10.1}", 0.0) +# test("{:10.1}", 0.0) print("%.0f" % (1.750000 % 0.08333333333)) # Below isn't compatible with single-precision float -#print("%.1f" % (1.750000 % 0.08333333333)) -#print("%.2f" % (1.750000 % 0.08333333333)) -#print("%.12f" % (1.750000 % 0.08333333333)) +# print("%.1f" % (1.750000 % 0.08333333333)) +# print("%.2f" % (1.750000 % 0.08333333333)) +# print("%.12f" % (1.750000 % 0.08333333333)) # tests for errors in format string try: - '{:10.1b}'.format(0.0) + "{:10.1b}".format(0.0) except ValueError: - print('ValueError') + print("ValueError") diff --git a/tests/float/string_format_modulo.py b/tests/float/string_format_modulo.py index aea534247c..0944615381 100644 --- a/tests/float/string_format_modulo.py +++ b/tests/float/string_format_modulo.py @@ -7,9 +7,9 @@ print("%u" % 1.0) # these 3 have different behaviour in Python 3.x versions # uPy raises a TypeError, following Python 3.5 (earlier versions don't) -#print("%x" % 18.0) -#print("%o" % 18.0) -#print("%X" % 18.0) +# print("%x" % 18.0) +# print("%o" % 18.0) +# print("%X" % 18.0) print("%e" % 1.23456) print("%E" % 1.23456) @@ -22,28 +22,28 @@ print("%06e" % float("inf")) print("%06e" % float("-inf")) print("%06e" % float("nan")) -print("%02.3d" % 123) # prec > width -print("%+f %+f" % (1.23, -1.23)) # float sign -print("% f % f" % (1.23, -1.23)) # float space sign -print("%0f" % -1.23) # negative number with 0 padding +print("%02.3d" % 123) # prec > width +print("%+f %+f" % (1.23, -1.23)) # float sign +print("% f % f" % (1.23, -1.23)) # float space sign +print("%0f" % -1.23) # negative number with 0 padding # numbers with large negative exponents -print('%f' % 1e-10) -print('%f' % 1e-20) -print('%f' % 1e-50) -print('%f' % 1e-100) -print('%f' % 1e-300) +print("%f" % 1e-10) +print("%f" % 1e-20) +print("%f" % 1e-50) +print("%f" % 1e-100) +print("%f" % 1e-300) # large decimal precision should be truncated and not overflow buffer # the output depends on the FP calculation so only first 2 digits are printed # (the 'g' with small e are printed using 'f' style, so need to be checked) -print(('%.40f' % 1e-300)[:2]) -print(('%.40g' % 1e-1)[:2]) -print(('%.40g' % 1e-2)[:2]) -print(('%.40g' % 1e-3)[:2]) -print(('%.40g' % 1e-4)[:2]) +print(("%.40f" % 1e-300)[:2]) +print(("%.40g" % 1e-1)[:2]) +print(("%.40g" % 1e-2)[:2]) +print(("%.40g" % 1e-3)[:2]) +print(("%.40g" % 1e-4)[:2]) -print("%.0g" % 1) # 0 precision 'g' +print("%.0g" % 1) # 0 precision 'g' -print('%.1e' % 9.99) # round up with positive exponent -print('%.1e' % 0.999) # round up with negative exponent +print("%.1e" % 9.99) # round up with positive exponent +print("%.1e" % 0.999) # round up with negative exponent diff --git a/tests/float/string_format_modulo2.py b/tests/float/string_format_modulo2.py index f6b1ae537d..b22021c5d0 100644 --- a/tests/float/string_format_modulo2.py +++ b/tests/float/string_format_modulo2.py @@ -1,24 +1,26 @@ # test formatting floats with large precision, that it doesn't overflow the buffer + def test(num, num_str): - if num == float('inf') or num == 0.0 and num_str != '0.0': + if num == float("inf") or num == 0.0 and num_str != "0.0": # skip numbers that overflow or underflow the FP precision return - for kind in ('e', 'f', 'g'): + for kind in ("e", "f", "g"): # check precision either side of the size of the buffer (32 bytes) for prec in range(23, 36, 2): - fmt = '%.' + '%d' % prec + kind + fmt = "%." + "%d" % prec + kind s = fmt % num check = abs(float(s) - num) if num > 1: check /= num if check > 1e-6: - print('FAIL', num_str, fmt, s, len(s), check) + print("FAIL", num_str, fmt, s, len(s), check) + # check pure zero -test(0.0, '0.0') +test(0.0, "0.0") # check some powers of 10, making sure to include exponents with 3 digits for e in range(-8, 8): num = pow(10, e) - test(num, '1e%d' % e) + test(num, "1e%d" % e) diff --git a/tests/float/string_format_modulo2_intbig.py b/tests/float/string_format_modulo2_intbig.py index 9992ba65d9..8110bc7f62 100644 --- a/tests/float/string_format_modulo2_intbig.py +++ b/tests/float/string_format_modulo2_intbig.py @@ -1,21 +1,23 @@ # test formatting floats with large precision, that it doesn't overflow the buffer + def test(num, num_str): - if num == float('inf') or num == 0.0 and num_str != '0.0': + if num == float("inf") or num == 0.0 and num_str != "0.0": # skip numbers that overflow or underflow the FP precision return - for kind in ('e', 'f', 'g'): + for kind in ("e", "f", "g"): # check precision either side of the size of the buffer (32 bytes) for prec in range(23, 36, 2): - fmt = '%.' + '%d' % prec + kind + fmt = "%." + "%d" % prec + kind s = fmt % num check = abs(float(s) - num) if num > 1: check /= num if check > 1e-6: - print('FAIL', num_str, fmt, s, len(s), check) + print("FAIL", num_str, fmt, s, len(s), check) + # check most powers of 10, making sure to include exponents with 3 digits for e in range(-101, 102): num = pow(10, e) - test(num, '1e%d' % e) + test(num, "1e%d" % e) diff --git a/tests/float/string_format_modulo3.py b/tests/float/string_format_modulo3.py index 5d26f25751..f9d9c43cdf 100644 --- a/tests/float/string_format_modulo3.py +++ b/tests/float/string_format_modulo3.py @@ -1,3 +1,3 @@ # uPy and CPython outputs differ for the following -print("%.1g" % -9.9) # round up 'g' with '-' sign -print("%.2g" % 99.9) # round up +print("%.1g" % -9.9) # round up 'g' with '-' sign +print("%.2g" % 99.9) # round up diff --git a/tests/float/true_value.py b/tests/float/true_value.py index df415f0031..4c8d2e5c82 100644 --- a/tests/float/true_value.py +++ b/tests/float/true_value.py @@ -3,5 +3,5 @@ if not 0.0: print("float 0") -if not 0+0j: +if not 0 + 0j: print("complex 0") diff --git a/tests/import/builtin_import.py b/tests/import/builtin_import.py index 088f631fcd..5258da8916 100644 --- a/tests/import/builtin_import.py +++ b/tests/import/builtin_import.py @@ -1,16 +1,16 @@ # test calling builtin import function # basic test -__import__('builtins') +__import__("builtins") # first arg should be a string try: __import__(1) except TypeError: - print('TypeError') + print("TypeError") # level argument should be non-negative try: - __import__('xyz', None, None, None, -1) + __import__("xyz", None, None, None, -1) except ValueError: - print('ValueError') + print("ValueError") diff --git a/tests/import/gen_context.py b/tests/import/gen_context.py index 02f1531467..b7567cf02d 100644 --- a/tests/import/gen_context.py +++ b/tests/import/gen_context.py @@ -2,8 +2,10 @@ import gen_context2 GLOBAL = "GLOBAL" + def gen(): print(GLOBAL) yield 1 + gen_context2.call(gen()) diff --git a/tests/import/import1a.py b/tests/import/import1a.py index 16b2d4d30f..9d7d72ff77 100644 --- a/tests/import/import1a.py +++ b/tests/import/import1a.py @@ -1,2 +1,3 @@ import import1b + print(import1b.var) diff --git a/tests/import/import1b.py b/tests/import/import1b.py index be74eca094..8c9d15a71f 100644 --- a/tests/import/import1b.py +++ b/tests/import/import1b.py @@ -1,4 +1,5 @@ var = 123 + def throw(): raise ValueError diff --git a/tests/import/import2a.py b/tests/import/import2a.py index def6aeb6aa..8fb4905250 100644 --- a/tests/import/import2a.py +++ b/tests/import/import2a.py @@ -1,5 +1,7 @@ from import1b import var + print(var) from import1b import var as var2 + print(var2) diff --git a/tests/import/import3a.py b/tests/import/import3a.py index 2e9d41f71d..2fadd8a52b 100644 --- a/tests/import/import3a.py +++ b/tests/import/import3a.py @@ -1,2 +1,3 @@ from import1b import * + print(var) diff --git a/tests/import/import_file.py b/tests/import/import_file.py index cb9a88a706..90ec4e41e7 100644 --- a/tests/import/import_file.py +++ b/tests/import/import_file.py @@ -1,2 +1,3 @@ import import1b + print(import1b.__file__) diff --git a/tests/import/import_pkg1.py b/tests/import/import_pkg1.py index fe6e4473e3..5c1b2ef4c7 100644 --- a/tests/import/import_pkg1.py +++ b/tests/import/import_pkg1.py @@ -12,5 +12,6 @@ print(pkg_.mod is pkg.mod) # import using "as" import pkg.mod as mm + print(mm is pkg.mod) print(mm.foo()) diff --git a/tests/import/import_pkg3.py b/tests/import/import_pkg3.py index 0ee885b220..ec46979062 100644 --- a/tests/import/import_pkg3.py +++ b/tests/import/import_pkg3.py @@ -3,4 +3,5 @@ from pkg import mod print(mod.foo()) import pkg.mod + print(mod is pkg.mod) diff --git a/tests/import/module_getattr.py b/tests/import/module_getattr.py index 4a18f414dd..df7a621815 100644 --- a/tests/import/module_getattr.py +++ b/tests/import/module_getattr.py @@ -10,13 +10,14 @@ except AttributeError: # define __getattr__ def __getattr__(attr): - if attr == 'does_not_exist': + if attr == "does_not_exist": return False raise AttributeError + # do feature test (will also test functionality if the feature exists) -if not hasattr(this, 'does_not_exist'): - print('SKIP') +if not hasattr(this, "does_not_exist"): + print("SKIP") raise SystemExit # check that __getattr__ works as expected diff --git a/tests/import/mpy_invalid.py b/tests/import/mpy_invalid.py index 6a4e116e78..250b011981 100644 --- a/tests/import/mpy_invalid.py +++ b/tests/import/mpy_invalid.py @@ -5,6 +5,7 @@ import sys, uio try: uio.IOBase import uos + uos.mount except (ImportError, AttributeError): print("SKIP") @@ -15,8 +16,10 @@ class UserFile(uio.IOBase): def __init__(self, data): self.data = data self.pos = 0 + def read(self): return self.data + def readinto(self, buf): n = 0 while n < len(buf) and self.pos < len(self.data): @@ -24,6 +27,7 @@ class UserFile(uio.IOBase): n += 1 self.pos += 1 return n + def ioctl(self, req, arg): return 0 @@ -31,37 +35,41 @@ class UserFile(uio.IOBase): class UserFS: def __init__(self, files): self.files = files + def mount(self, readonly, mksfs): pass + def umount(self): pass + def stat(self, path): if path in self.files: return (32768, 0, 0, 0, 0, 0, 0, 0, 0, 0) raise OSError + def open(self, path, mode): return UserFile(self.files[path]) # these are the test .mpy files user_files = { - '/mod0.mpy': b'', # empty file - '/mod1.mpy': b'M', # too short header - '/mod2.mpy': b'M\x00\x00\x00', # bad version + "/mod0.mpy": b"", # empty file + "/mod1.mpy": b"M", # too short header + "/mod2.mpy": b"M\x00\x00\x00", # bad version } # create and mount a user filesystem -uos.mount(UserFS(user_files), '/userfs') -sys.path.append('/userfs') +uos.mount(UserFS(user_files), "/userfs") +sys.path.append("/userfs") # import .mpy files from the user filesystem for i in range(len(user_files)): - mod = 'mod%u' % i + mod = "mod%u" % i try: __import__(mod) except ValueError as er: - print(mod, 'ValueError', er) + print(mod, "ValueError", er) # unmount and undo path addition -uos.umount('/userfs') +uos.umount("/userfs") sys.path.pop() diff --git a/tests/import/try_module.py b/tests/import/try_module.py index 03a9db15b5..7c97df28b3 100644 --- a/tests/import/try_module.py +++ b/tests/import/try_module.py @@ -2,8 +2,10 @@ # its namespace stick and namespace of current module not coming back. import import1b + def func1(): - print('func1') + print("func1") + def func2(): try: @@ -12,4 +14,5 @@ def func2(): pass func1() + func2() diff --git a/tests/inlineasm/asmargs.py b/tests/inlineasm/asmargs.py index 047d9ed420..3b03f15103 100644 --- a/tests/inlineasm/asmargs.py +++ b/tests/inlineasm/asmargs.py @@ -1,29 +1,44 @@ # test passing arguments + @micropython.asm_thumb def arg0(): mov(r0, 1) + + print(arg0()) + @micropython.asm_thumb def arg1(r0): add(r0, r0, 1) + + print(arg1(1)) + @micropython.asm_thumb def arg2(r0, r1): add(r0, r0, r1) + + print(arg2(1, 2)) + @micropython.asm_thumb def arg3(r0, r1, r2): add(r0, r0, r1) add(r0, r0, r2) + + print(arg3(1, 2, 3)) + @micropython.asm_thumb def arg4(r0, r1, r2, r3): add(r0, r0, r1) add(r0, r0, r2) add(r0, r0, r3) + + print(arg4(1, 2, 3, 4)) diff --git a/tests/inlineasm/asmbcc.py b/tests/inlineasm/asmbcc.py index 540fa6591f..08967d48c7 100644 --- a/tests/inlineasm/asmbcc.py +++ b/tests/inlineasm/asmbcc.py @@ -1,6 +1,7 @@ # test bcc instructions # at the moment only tests beq, narrow and wide versions + @micropython.asm_thumb def f(r0): mov(r1, r0) @@ -21,6 +22,7 @@ def f(r0): label(end) + print(f(0)) print(f(1)) print(f(2)) diff --git a/tests/inlineasm/asmbitops.py b/tests/inlineasm/asmbitops.py index 8cf92b301f..d1c8a98235 100644 --- a/tests/inlineasm/asmbitops.py +++ b/tests/inlineasm/asmbitops.py @@ -2,12 +2,15 @@ def clz(r0): clz(r0, r0) -print(clz(0xf0)) + +print(clz(0xF0)) print(clz(0x8000)) + @micropython.asm_thumb def rbit(r0): rbit(r0, r0) -print(hex(rbit(0xf0))) + +print(hex(rbit(0xF0))) print(hex(rbit(0x8000))) diff --git a/tests/inlineasm/asmblbx.py b/tests/inlineasm/asmblbx.py index d08c0ed6b3..43585dddcc 100644 --- a/tests/inlineasm/asmblbx.py +++ b/tests/inlineasm/asmblbx.py @@ -1,5 +1,6 @@ # test bl and bx instructions + @micropython.asm_thumb def f(r0): # jump over the internal functions @@ -17,5 +18,6 @@ def f(r0): bl(func1) bl(func2) + print(f(0)) print(f(1)) diff --git a/tests/inlineasm/asmconst.py b/tests/inlineasm/asmconst.py index 299a25093c..8412dd2c72 100644 --- a/tests/inlineasm/asmconst.py +++ b/tests/inlineasm/asmconst.py @@ -1,8 +1,11 @@ # test constants in assembler + @micropython.asm_thumb def c1(): - movwt(r0, 0xffffffff) - movwt(r1, 0xf0000000) + movwt(r0, 0xFFFFFFFF) + movwt(r1, 0xF0000000) sub(r0, r0, r1) + + print(hex(c1())) diff --git a/tests/inlineasm/asmdiv.py b/tests/inlineasm/asmdiv.py index b97d566eb5..c278463846 100644 --- a/tests/inlineasm/asmdiv.py +++ b/tests/inlineasm/asmdiv.py @@ -2,15 +2,17 @@ def sdiv(r0, r1): sdiv(r0, r0, r1) + @micropython.asm_thumb def udiv(r0, r1): udiv(r0, r0, r1) + print(sdiv(1234, 3)) print(sdiv(-1234, 3)) print(sdiv(1234, -3)) print(sdiv(-1234, -3)) print(udiv(1234, 3)) -print(udiv(0xffffffff, 0x7fffffff)) -print(udiv(0xffffffff, 0xffffffff)) +print(udiv(0xFFFFFFFF, 0x7FFFFFFF)) +print(udiv(0xFFFFFFFF, 0xFFFFFFFF)) diff --git a/tests/inlineasm/asmfpaddsub.py b/tests/inlineasm/asmfpaddsub.py index b5fcecb6ce..f69c89cdc6 100644 --- a/tests/inlineasm/asmfpaddsub.py +++ b/tests/inlineasm/asmfpaddsub.py @@ -1,4 +1,4 @@ -@micropython.asm_thumb # r0 = r0+r1-r2 +@micropython.asm_thumb # r0 = r0+r1-r2 def add_sub(r0, r1, r2): vmov(s0, r0) vcvt_f32_s32(s0, s0) @@ -11,5 +11,5 @@ def add_sub(r0, r1, r2): vcvt_s32_f32(s31, s0) vmov(r0, s31) -print(add_sub(100, 20, 30)) +print(add_sub(100, 20, 30)) diff --git a/tests/inlineasm/asmfpcmp.py b/tests/inlineasm/asmfpcmp.py index d4fa1f2410..47fd99a347 100644 --- a/tests/inlineasm/asmfpcmp.py +++ b/tests/inlineasm/asmfpcmp.py @@ -1,4 +1,4 @@ -@micropython.asm_thumb # test vcmp, vmrs +@micropython.asm_thumb # test vcmp, vmrs def f(r0, r1): vmov(s0, r0) vcvt_f32_s32(s0, s0) @@ -9,6 +9,7 @@ def f(r0, r1): mov(r1, 28) lsr(r0, r1) -print(f(0,1)) -print(f(1,1)) -print(f(1,0)) + +print(f(0, 1)) +print(f(1, 1)) +print(f(1, 0)) diff --git a/tests/inlineasm/asmfpldrstr.py b/tests/inlineasm/asmfpldrstr.py index 8fa9af6369..c65f8a798b 100644 --- a/tests/inlineasm/asmfpldrstr.py +++ b/tests/inlineasm/asmfpldrstr.py @@ -1,12 +1,14 @@ import array -@micropython.asm_thumb # test vldr, vstr + + +@micropython.asm_thumb # test vldr, vstr def arrayadd(r0): vldr(s0, [r0, 0]) vldr(s1, [r0, 4]) vadd(s2, s0, s1) vstr(s2, [r0, 8]) + z = array.array("f", [2, 4, 10]) arrayadd(z) print(z[2]) - diff --git a/tests/inlineasm/asmfpmuldiv.py b/tests/inlineasm/asmfpmuldiv.py index edf9511bcd..930ddd053c 100644 --- a/tests/inlineasm/asmfpmuldiv.py +++ b/tests/inlineasm/asmfpmuldiv.py @@ -1,4 +1,4 @@ -@micropython.asm_thumb # r0 = (int)(r0*r1/r2) +@micropython.asm_thumb # r0 = (int)(r0*r1/r2) def muldiv(r0, r1, r2): vmov(s0, r0) vcvt_f32_s32(s0, s0) @@ -11,5 +11,5 @@ def muldiv(r0, r1, r2): vcvt_s32_f32(s31, s8) vmov(r0, s31) -print(muldiv(100, 10, 50)) +print(muldiv(100, 10, 50)) diff --git a/tests/inlineasm/asmfpsqrt.py b/tests/inlineasm/asmfpsqrt.py index f2c2d3a954..519fde4fcc 100644 --- a/tests/inlineasm/asmfpsqrt.py +++ b/tests/inlineasm/asmfpsqrt.py @@ -1,5 +1,5 @@ # test vsqrt, vneg -@micropython.asm_thumb # r0 = -(int)(sqrt(r0)*r1) +@micropython.asm_thumb # r0 = -(int)(sqrt(r0)*r1) def sqrt_test(r0, r1): vmov(s1, r0) vcvt_f32_s32(s1, s1) @@ -11,5 +11,5 @@ def sqrt_test(r0, r1): vcvt_s32_f32(s31, s7) vmov(r0, s31) -print(sqrt_test(256, 10)) +print(sqrt_test(256, 10)) diff --git a/tests/inlineasm/asmit.py b/tests/inlineasm/asmit.py index 57bfcc7f9a..640258e7c8 100644 --- a/tests/inlineasm/asmit.py +++ b/tests/inlineasm/asmit.py @@ -1,16 +1,22 @@ # test it instruction + @micropython.asm_thumb def f(r0, r1): cmp(r0, r1) it(eq) mov(r0, 100) + + print(f(0, 0), f(1, 2)) + @micropython.asm_thumb def g(r0, r1): cmp(r0, r1) ite(eq) mov(r0, 100) mov(r0, 200) + + print(g(0, 0), g(0, 1)) diff --git a/tests/inlineasm/asmpushpop.py b/tests/inlineasm/asmpushpop.py index c9005434ba..74e729dfa2 100644 --- a/tests/inlineasm/asmpushpop.py +++ b/tests/inlineasm/asmpushpop.py @@ -5,4 +5,5 @@ def f(r0, r1, r2): pop({r0}) pop({r1, r2}) + print(f(0, 1, 2)) diff --git a/tests/inlineasm/asmrettype.py b/tests/inlineasm/asmrettype.py index f1918696ee..95068795df 100644 --- a/tests/inlineasm/asmrettype.py +++ b/tests/inlineasm/asmrettype.py @@ -1,21 +1,33 @@ # test return type of inline asm + @micropython.asm_thumb def ret_obj(r0) -> object: pass + + ret_obj(print)(1) + @micropython.asm_thumb def ret_bool(r0) -> bool: pass + + print(ret_bool(0), ret_bool(1)) + @micropython.asm_thumb def ret_int(r0) -> int: lsl(r0, r0, 29) + + print(ret_int(0), hex(ret_int(1)), hex(ret_int(2)), hex(ret_int(4))) + @micropython.asm_thumb def ret_uint(r0) -> uint: lsl(r0, r0, 29) + + print(ret_uint(0), hex(ret_uint(1)), hex(ret_uint(2)), hex(ret_uint(4))) diff --git a/tests/inlineasm/asmshift.py b/tests/inlineasm/asmshift.py index 0df2187347..ba4c21b3f2 100644 --- a/tests/inlineasm/asmshift.py +++ b/tests/inlineasm/asmshift.py @@ -1,29 +1,46 @@ @micropython.asm_thumb def lsl1(r0): lsl(r0, r0, 1) + + print(hex(lsl1(0x123))) + @micropython.asm_thumb def lsl23(r0): lsl(r0, r0, 23) + + print(hex(lsl23(1))) + @micropython.asm_thumb def lsr1(r0): lsr(r0, r0, 1) + + print(hex(lsr1(0x123))) + @micropython.asm_thumb def lsr31(r0): lsr(r0, r0, 31) + + print(hex(lsr31(0x80000000))) + @micropython.asm_thumb def asr1(r0): asr(r0, r0, 1) + + print(hex(asr1(0x123))) + @micropython.asm_thumb def asr31(r0): asr(r0, r0, 31) + + print(hex(asr31(0x80000000))) diff --git a/tests/inlineasm/asmspecialregs.py b/tests/inlineasm/asmspecialregs.py index edfe4c2bd7..053ae29a4d 100644 --- a/tests/inlineasm/asmspecialregs.py +++ b/tests/inlineasm/asmspecialregs.py @@ -2,10 +2,11 @@ def getIPSR(): mrs(r0, IPSR) + @micropython.asm_thumb def getBASEPRI(): mrs(r0, BASEPRI) + print(getBASEPRI()) print(getIPSR()) - diff --git a/tests/inlineasm/asmsum.py b/tests/inlineasm/asmsum.py index 07e71c7384..f465b25afd 100644 --- a/tests/inlineasm/asmsum.py +++ b/tests/inlineasm/asmsum.py @@ -22,6 +22,7 @@ def asm_sum_words(r0, r1): mov(r0, r2) + @micropython.asm_thumb def asm_sum_bytes(r0, r1): @@ -46,12 +47,13 @@ def asm_sum_bytes(r0, r1): mov(r0, r2) + import array -b = array.array('l', (100, 200, 300, 400)) +b = array.array("l", (100, 200, 300, 400)) n = asm_sum_words(len(b), b) print(b, n) -b = array.array('b', (10, 20, 30, 40, 50, 60, 70, 80)) +b = array.array("b", (10, 20, 30, 40, 50, 60, 70, 80)) n = asm_sum_bytes(len(b), b) print(b, n) diff --git a/tests/io/argv.py b/tests/io/argv.py index a13f2cad21..53254da119 100644 --- a/tests/io/argv.py +++ b/tests/io/argv.py @@ -1,2 +1,3 @@ import sys + print(sys.argv) diff --git a/tests/io/builtin_print_file.py b/tests/io/builtin_print_file.py index d9b8e2a960..822356a6cc 100644 --- a/tests/io/builtin_print_file.py +++ b/tests/io/builtin_print_file.py @@ -5,13 +5,13 @@ import sys try: sys.stdout except AttributeError: - print('SKIP') + print("SKIP") raise SystemExit print(file=sys.stdout) -print('test', file=sys.stdout) +print("test", file=sys.stdout) try: print(file=1) -except (AttributeError, OSError): # CPython and uPy differ in error message - print('Error') +except (AttributeError, OSError): # CPython and uPy differ in error message + print("Error") diff --git a/tests/io/file1.py b/tests/io/file1.py index af4176b64e..2a46c9c63e 100644 --- a/tests/io/file1.py +++ b/tests/io/file1.py @@ -4,43 +4,43 @@ print(f.readline()) print(f.read()) f = open("io/data/file1") print(f.readlines()) -f = open("io/data/file1","r") +f = open("io/data/file1", "r") print(f.readlines()) -f = open("io/data/file1","rb") +f = open("io/data/file1", "rb") print(f.readlines()) -f = open("io/data/file1",mode="r") +f = open("io/data/file1", mode="r") print(f.readlines()) -f = open("io/data/file1",mode="rb") +f = open("io/data/file1", mode="rb") print(f.readlines()) # write() error -f = open('io/data/file1', 'r') +f = open("io/data/file1", "r") try: - f.write('x') + f.write("x") except OSError: - print('OSError') + print("OSError") f.close() # read(n) error on binary file -f = open('io/data/file1', 'ab') +f = open("io/data/file1", "ab") try: f.read(1) except OSError: - print('OSError') + print("OSError") f.close() # read(n) error on text file -f = open('io/data/file1', 'at') +f = open("io/data/file1", "at") try: f.read(1) except OSError: - print('OSError') + print("OSError") f.close() # read() w/o args error -f = open('io/data/file1', 'ab') +f = open("io/data/file1", "ab") try: f.read() except OSError: - print('OSError') + print("OSError") f.close() diff --git a/tests/io/file_readinto.py b/tests/io/file_readinto.py index cbefc6e040..1f3702a217 100644 --- a/tests/io/file_readinto.py +++ b/tests/io/file_readinto.py @@ -7,8 +7,8 @@ print(f.readinto(b)) print(b) # readinto() on writable file -f = open('io/data/file1', 'ab') +f = open("io/data/file1", "ab") try: f.readinto(bytearray(4)) except OSError: - print('OSError') + print("OSError") diff --git a/tests/io/file_readline.py b/tests/io/file_readline.py index 25e76597b1..86d010eaf6 100644 --- a/tests/io/file_readline.py +++ b/tests/io/file_readline.py @@ -6,9 +6,9 @@ print(f.readline(5)) print(f.readline()) # readline() on writable file -f = open('io/data/file1', 'ab') +f = open("io/data/file1", "ab") try: f.readline() except OSError: - print('OSError') + print("OSError") f.close() diff --git a/tests/io/file_seek.py b/tests/io/file_seek.py index 10fb1fd06f..2fe57692c6 100644 --- a/tests/io/file_seek.py +++ b/tests/io/file_seek.py @@ -25,10 +25,10 @@ print(f.tell()) f.close() # seek closed file -f = open('io/data/file1', 'r') +f = open("io/data/file1", "r") f.close() try: f.seek(1) except (OSError, ValueError): # CPy raises ValueError, uPy raises OSError - print('OSError or ValueError') + print("OSError or ValueError") diff --git a/tests/io/file_with.py b/tests/io/file_with.py index ee1e702422..899c0f9287 100644 --- a/tests/io/file_with.py +++ b/tests/io/file_with.py @@ -15,7 +15,7 @@ except: # Regression test: test that exception in with initialization properly # thrown and doesn't crash. try: - with open('__non_existent', 'r'): + with open("__non_existent", "r"): pass except OSError: print("OSError") diff --git a/tests/io/resource_stream.py b/tests/io/resource_stream.py index 37d985bf16..5656205b69 100644 --- a/tests/io/resource_stream.py +++ b/tests/io/resource_stream.py @@ -4,7 +4,7 @@ import sys try: uio.resource_stream except AttributeError: - print('SKIP') + print("SKIP") raise SystemExit buf = uio.resource_stream("data", "file2") diff --git a/tests/jni/list.py b/tests/jni/list.py index d58181d0ba..7630a48e89 100644 --- a/tests/jni/list.py +++ b/tests/jni/list.py @@ -1,4 +1,5 @@ import jni + try: ArrayList = jni.cls("java/util/ArrayList") except: diff --git a/tests/jni/object.py b/tests/jni/object.py index aa67615ec8..8fbdb39d39 100644 --- a/tests/jni/object.py +++ b/tests/jni/object.py @@ -1,4 +1,5 @@ import jni + try: Integer = jni.cls("java/lang/Integer") except: diff --git a/tests/jni/system_out.py b/tests/jni/system_out.py index 86c4b9e112..c34d7011f7 100644 --- a/tests/jni/system_out.py +++ b/tests/jni/system_out.py @@ -1,5 +1,6 @@ try: import jni + System = jni.cls("java/lang/System") except: print("SKIP") diff --git a/tests/micropython/const.py b/tests/micropython/const.py index 660a095f2c..1faf22be9a 100644 --- a/tests/micropython/const.py +++ b/tests/micropython/const.py @@ -7,9 +7,11 @@ Y = const(X + 456) print(X, Y + 1) + def f(): print(X, Y + 1) + f() _X = const(12) @@ -17,9 +19,11 @@ _Y = const(_X + 34) print(_X, _Y) + class A: Z = const(1) _Z = const(2) print(Z, _Z) -print(hasattr(A, 'Z'), hasattr(A, '_Z')) + +print(hasattr(A, "Z"), hasattr(A, "_Z")) diff --git a/tests/micropython/const2.py b/tests/micropython/const2.py index 60085a1e04..ed4720122e 100644 --- a/tests/micropython/const2.py +++ b/tests/micropython/const2.py @@ -8,27 +8,37 @@ Z = const(3) # import that uses a constant import micropython as X -print(globals()['X']) + +print(globals()["X"]) # function name that matches a constant def X(): - print('function X', X) -globals()['X']() + print("function X", X) + + +globals()["X"]() # arguments that match a constant def f(X, *Y, **Z): pass + + f(1) # class name that matches a constant class X: def f(self): - print('class X', X) -globals()['X']().f() + print("class X", X) + + +globals()["X"]().f() # constant within a class class A: C1 = const(4) + def X(self): - print('method X', Y, C1, self.C1) + print("method X", Y, C1, self.C1) + + A().X() diff --git a/tests/micropython/const_error.py b/tests/micropython/const_error.py index 6d3d135b56..311cfb4d5e 100644 --- a/tests/micropython/const_error.py +++ b/tests/micropython/const_error.py @@ -2,12 +2,14 @@ from micropython import const + def test_syntax(code): try: exec(code) except SyntaxError: print("SyntaxError") + # argument not a constant test_syntax("a = const(x)") diff --git a/tests/micropython/const_intbig.py b/tests/micropython/const_intbig.py index e749026526..27990c8c20 100644 --- a/tests/micropython/const_intbig.py +++ b/tests/micropython/const_intbig.py @@ -3,8 +3,8 @@ from micropython import const # check we can make consts from bignums -Z1 = const(0xffffffff) -Z2 = const(0xffffffffffffffff) +Z1 = const(0xFFFFFFFF) +Z2 = const(0xFFFFFFFFFFFFFFFF) print(hex(Z1), hex(Z2)) # check arithmetic with bignum diff --git a/tests/micropython/decorator.py b/tests/micropython/decorator.py index bf688968a0..2e7cf17776 100644 --- a/tests/micropython/decorator.py +++ b/tests/micropython/decorator.py @@ -1,7 +1,9 @@ # test micropython-specific decorators + @micropython.bytecode def f(): - return 'bytecode' + return "bytecode" + print(f()) diff --git a/tests/micropython/decorator_error.py b/tests/micropython/decorator_error.py index c7da3119f4..94772ac1e5 100644 --- a/tests/micropython/decorator_error.py +++ b/tests/micropython/decorator_error.py @@ -1,11 +1,13 @@ # test syntax errors for uPy-specific decorators + def test_syntax(code): try: exec(code) except SyntaxError: print("SyntaxError") + # invalid micropython decorators test_syntax("@micropython.a\ndef f(): pass") test_syntax("@micropython.a.b\ndef f(): pass") diff --git a/tests/micropython/emg_exc.py b/tests/micropython/emg_exc.py index 4a9fa18bc1..bca4d2d9fb 100644 --- a/tests/micropython/emg_exc.py +++ b/tests/micropython/emg_exc.py @@ -2,6 +2,7 @@ import micropython import sys + try: import uio except ImportError: @@ -14,6 +15,7 @@ try: except AttributeError: pass + def f(): micropython.heap_lock() try: @@ -31,4 +33,5 @@ def f(): else: print(l) + f() diff --git a/tests/micropython/extreme_exc.py b/tests/micropython/extreme_exc.py index b9db964068..dae5b15186 100644 --- a/tests/micropython/extreme_exc.py +++ b/tests/micropython/extreme_exc.py @@ -5,8 +5,13 @@ import micropython # Check for stackless build, which can't call functions without # allocating a frame on the heap. try: - def stackless(): pass - micropython.heap_lock(); stackless(); micropython.heap_unlock() + + def stackless(): + pass + + micropython.heap_lock() + stackless() + micropython.heap_unlock() except RuntimeError: print("SKIP") raise SystemExit @@ -17,11 +22,78 @@ try: except AttributeError: pass + def main(): # create an exception with many args while heap is locked # should revert to empty tuple for args micropython.heap_lock() - e = Exception(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) + e = Exception( + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ) micropython.heap_unlock() print(repr(e)) @@ -29,9 +101,12 @@ def main(): # should use emergency exception buffer and truncate the message def f(): pass + micropython.heap_lock() try: - f(abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz=1) + f( + abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz=1 + ) except Exception as er: e = er micropython.heap_unlock() @@ -46,7 +121,9 @@ def main(): except MemoryError: break try: - f(abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz=1) + f( + abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz=1 + ) except Exception as er: e = er lst[0] = None @@ -57,6 +134,7 @@ def main(): # should use emergency exception and be unable to resize traceback array def g(): g() + micropython.heap_lock() try: g() @@ -67,13 +145,15 @@ def main(): # create an exception on the heap with some traceback on the heap, but then # raise it with the heap locked so it can't allocate any more traceback - exc = Exception('my exception') + exc = Exception("my exception") try: raise exc except: pass + def h(e): raise e + micropython.heap_lock() try: h(exc) @@ -82,4 +162,5 @@ def main(): micropython.heap_unlock() print(repr(e)) + main() diff --git a/tests/micropython/heap_lock.py b/tests/micropython/heap_lock.py index ca3f5806a8..8558935374 100644 --- a/tests/micropython/heap_lock.py +++ b/tests/micropython/heap_lock.py @@ -11,13 +11,13 @@ micropython.heap_lock() try: print([]) except MemoryError: - print('MemoryError') + print("MemoryError") # expansion of a heap block try: l.extend(l2) except MemoryError: - print('MemoryError') + print("MemoryError") micropython.heap_unlock() diff --git a/tests/micropython/heapalloc.py b/tests/micropython/heapalloc.py index f74bb92c85..99f157105d 100644 --- a/tests/micropython/heapalloc.py +++ b/tests/micropython/heapalloc.py @@ -5,18 +5,26 @@ import micropython # Check for stackless build, which can't call functions without # allocating a frame on heap. try: - def stackless(): pass - micropython.heap_lock(); stackless(); micropython.heap_unlock() + + def stackless(): + pass + + micropython.heap_lock() + stackless() + micropython.heap_unlock() except RuntimeError: print("SKIP") raise SystemExit + def f1(a): print(a) + def f2(a, b=2): print(a, b) + def f3(a, b, c, d): x1 = x2 = a x3 = x4 = b @@ -24,19 +32,22 @@ def f3(a, b, c, d): x7 = x8 = d print(x1, x3, x5, x7, x2 + x4 + x6 + x8) + global_var = 1 + def test(): global global_var, global_exc - global_var = 2 # set an existing global variable + global_var = 2 # set an existing global variable for i in range(2): # for loop - f1(i) # function call - f1(i * 2 + 1) # binary operation with small ints - f1(a=i) # keyword arguments - f2(i) # default arg (second one) - f2(i, i) # 2 args + f1(i) # function call + f1(i * 2 + 1) # binary operation with small ints + f1(a=i) # keyword arguments + f2(i) # default arg (second one) + f2(i, i) # 2 args f3(1, 2, 3, 4) # function with lots of local state + # call test() with heap allocation disabled micropython.heap_lock() test() diff --git a/tests/micropython/heapalloc_bytesio2.py b/tests/micropython/heapalloc_bytesio2.py index cd76f58077..3b9f141270 100644 --- a/tests/micropython/heapalloc_bytesio2.py +++ b/tests/micropython/heapalloc_bytesio2.py @@ -3,6 +3,7 @@ try: import uio import micropython + micropython.mem_total except (ImportError, AttributeError): print("SKIP") diff --git a/tests/micropython/heapalloc_exc_raise.py b/tests/micropython/heapalloc_exc_raise.py index fb63a84bf3..99810e0075 100644 --- a/tests/micropython/heapalloc_exc_raise.py +++ b/tests/micropython/heapalloc_exc_raise.py @@ -4,6 +4,7 @@ import micropython e = ValueError("error") + def func(): micropython.heap_lock() try: @@ -19,5 +20,6 @@ def func(): print(e2) micropython.heap_unlock() + func() print("ok") diff --git a/tests/micropython/heapalloc_inst_call.py b/tests/micropython/heapalloc_inst_call.py index 3cc497b73a..14d8826bf0 100644 --- a/tests/micropython/heapalloc_inst_call.py +++ b/tests/micropython/heapalloc_inst_call.py @@ -2,22 +2,27 @@ # doesn't require heap allocation. import micropython + class Foo0: def __call__(self): print("__call__") + class Foo1: def __call__(self, a): print("__call__", a) + class Foo2: def __call__(self, a, b): print("__call__", a, b) + class Foo3: def __call__(self, a, b, c): print("__call__", a, b, c) + f0 = Foo0() f1 = Foo1() f2 = Foo2() diff --git a/tests/micropython/heapalloc_iter.py b/tests/micropython/heapalloc_iter.py index 163e172111..f80a099e94 100644 --- a/tests/micropython/heapalloc_iter.py +++ b/tests/micropython/heapalloc_iter.py @@ -9,7 +9,8 @@ except (NameError, ImportError): try: from micropython import heap_lock, heap_unlock except (ImportError, AttributeError): - heap_lock = heap_unlock = lambda:0 + heap_lock = heap_unlock = lambda: 0 + def do_iter(l): heap_lock() @@ -17,16 +18,18 @@ def do_iter(l): print(i) heap_unlock() + def gen_func(): yield 1 yield 2 + # pre-create collections to iterate over -ba = bytearray(b'123') -ar = array.array('H', (123, 456)) +ba = bytearray(b"123") +ar = array.array("H", (123, 456)) t = (1, 2, 3) l = [1, 2] -d = {1:2} +d = {1: 2} s = set((1,)) fs = frozenset((1,)) g1 = (100 + x for x in range(2)) @@ -34,7 +37,7 @@ g2 = gen_func() # test containment (both success and failure) with the heap locked heap_lock() -print(49 in b'123', 255 in b'123') +print(49 in b"123", 255 in b"123") print(1 in t, -1 in t) print(1 in l, -1 in l) print(1 in d, -1 in d) @@ -42,7 +45,7 @@ print(1 in s, -1 in s) heap_unlock() # test unpacking with the heap locked -unp0 = unp1 = unp2 = None # preallocate slots for globals +unp0 = unp1 = unp2 = None # preallocate slots for globals heap_lock() unp0, unp1, unp2 = t print(unp0, unp1, unp2) @@ -58,7 +61,7 @@ print(sum(t)) heap_unlock() # test iterating over collections with the heap locked -do_iter(b'123') +do_iter(b"123") do_iter(ba) do_iter(ar) do_iter(t) diff --git a/tests/micropython/heapalloc_super.py b/tests/micropython/heapalloc_super.py index a8c23393e4..51afae3d83 100644 --- a/tests/micropython/heapalloc_super.py +++ b/tests/micropython/heapalloc_super.py @@ -4,21 +4,30 @@ import micropython # Check for stackless build, which can't call functions without # allocating a frame on heap. try: - def stackless(): pass - micropython.heap_lock(); stackless(); micropython.heap_unlock() + + def stackless(): + pass + + micropython.heap_lock() + stackless() + micropython.heap_unlock() except RuntimeError: print("SKIP") raise SystemExit + class A: def foo(self): - print('A foo') + print("A foo") return 42 + + class B(A): def foo(self): - print('B foo') + print("B foo") print(super().foo()) + b = B() micropython.heap_lock() diff --git a/tests/micropython/heapalloc_traceback.py b/tests/micropython/heapalloc_traceback.py index 813dea4b21..eabd09388b 100644 --- a/tests/micropython/heapalloc_traceback.py +++ b/tests/micropython/heapalloc_traceback.py @@ -2,6 +2,7 @@ import micropython import sys + try: import uio except ImportError: @@ -15,6 +16,7 @@ try: except: pass + def test(): micropython.heap_lock() global global_exc @@ -22,9 +24,10 @@ def test(): try: raise global_exc except StopIteration: - print('StopIteration') + print("StopIteration") micropython.heap_unlock() + # call test() with heap allocation disabled test() diff --git a/tests/micropython/kbd_intr.py b/tests/micropython/kbd_intr.py index 879c9a229f..81977aaa52 100644 --- a/tests/micropython/kbd_intr.py +++ b/tests/micropython/kbd_intr.py @@ -5,7 +5,7 @@ import micropython try: micropython.kbd_intr except AttributeError: - print('SKIP') + print("SKIP") raise SystemExit # just check we can actually call it diff --git a/tests/micropython/meminfo.py b/tests/micropython/meminfo.py index 698bbbd21c..9df341fbb8 100644 --- a/tests/micropython/meminfo.py +++ b/tests/micropython/meminfo.py @@ -3,8 +3,8 @@ import micropython # these functions are not always available -if not hasattr(micropython, 'mem_info'): - print('SKIP') +if not hasattr(micropython, "mem_info"): + print("SKIP") else: micropython.mem_info() micropython.mem_info(1) diff --git a/tests/micropython/memstats.py b/tests/micropython/memstats.py index 78e4d24736..dee3a4ce2f 100644 --- a/tests/micropython/memstats.py +++ b/tests/micropython/memstats.py @@ -3,8 +3,8 @@ import micropython # these functions are not always available -if not hasattr(micropython, 'mem_total'): - print('SKIP') +if not hasattr(micropython, "mem_total"): + print("SKIP") else: t = micropython.mem_total() c = micropython.mem_current() diff --git a/tests/micropython/native_closure.py b/tests/micropython/native_closure.py index 6c0592e52d..07014e90da 100644 --- a/tests/micropython/native_closure.py +++ b/tests/micropython/native_closure.py @@ -4,11 +4,15 @@ @micropython.native def f(): x = 1 + @micropython.native def g(): nonlocal x return x + return g + + print(f()()) # closing over an argument @@ -18,15 +22,22 @@ def f(x): def g(): nonlocal x return x + return g + + print(f(2)()) # closing over an argument and a normal local @micropython.native def f(x): y = 2 * x + @micropython.native def g(z): return x + y + z + return g + + print(f(2)(3)) diff --git a/tests/micropython/native_const.py b/tests/micropython/native_const.py index 37b491cf4a..b48499550e 100644 --- a/tests/micropython/native_const.py +++ b/tests/micropython/native_const.py @@ -1,14 +1,21 @@ # test loading constants in native functions + @micropython.native def f(): - return b'bytes' + return b"bytes" + + print(f()) + @micropython.native def f(): @micropython.native def g(): return 123 + return g + + print(f()()) diff --git a/tests/micropython/native_const_intbig.py b/tests/micropython/native_const_intbig.py index 611b39d8fe..69bc1d2163 100644 --- a/tests/micropython/native_const_intbig.py +++ b/tests/micropython/native_const_intbig.py @@ -1,7 +1,9 @@ # check loading constants + @micropython.native def f(): return 123456789012345678901234567890 + print(f()) diff --git a/tests/micropython/native_misc.py b/tests/micropython/native_misc.py index 0cd521de6c..7c5415375e 100644 --- a/tests/micropython/native_misc.py +++ b/tests/micropython/native_misc.py @@ -4,10 +4,13 @@ @micropython.native def native_test(x): print(1, [], x) + + native_test(2) # check that GC doesn't collect the native function import gc + gc.collect() native_test(3) @@ -15,17 +18,23 @@ native_test(3) @micropython.native def f(a, b): print(a + b) + + f(1, 2) # native with 3 args @micropython.native def f(a, b, c): print(a + b + c) + + f(1, 2, 3) # check not operator @micropython.native def f(a): print(not a) + + f(False) f(True) diff --git a/tests/micropython/native_try.py b/tests/micropython/native_try.py index 2e41bf2ea1..492b59085c 100644 --- a/tests/micropython/native_try.py +++ b/tests/micropython/native_try.py @@ -6,11 +6,13 @@ def f(): try: fail finally: - print('finally') + print("finally") + + try: f() except NameError: - print('NameError') + print("NameError") # nested try-except with try-finally @micropython.native @@ -19,9 +21,11 @@ def f(): try: fail finally: - print('finally') + print("finally") except NameError: - print('NameError') + print("NameError") + + f() # check that locals written to in try blocks keep their values @@ -36,4 +40,6 @@ def f(): print(a) a = 300 print(a) + + f() diff --git a/tests/micropython/native_try_deep.py b/tests/micropython/native_try_deep.py index 7fac4f0f38..3d31248df0 100644 --- a/tests/micropython/native_try_deep.py +++ b/tests/micropython/native_try_deep.py @@ -30,5 +30,7 @@ def f(): finally: print(1) except ValueError: - print('ValueError') + print("ValueError") + + f() diff --git a/tests/micropython/native_with.py b/tests/micropython/native_with.py index 343f3e8d38..4e20b23856 100644 --- a/tests/micropython/native_with.py +++ b/tests/micropython/native_with.py @@ -1,18 +1,24 @@ # test with handling within a native function + class C: def __init__(self): - print('__init__') + print("__init__") + def __enter__(self): - print('__enter__') + print("__enter__") + def __exit__(self, a, b, c): - print('__exit__', a, b, c) + print("__exit__", a, b, c) + # basic with @micropython.native def f(): with C(): print(1) + + f() # nested with and try-except @@ -24,5 +30,7 @@ def f(): fail print(2) except NameError: - print('NameError') + print("NameError") + + f() diff --git a/tests/micropython/opt_level.py b/tests/micropython/opt_level.py index 5a10047f04..3213dc003d 100644 --- a/tests/micropython/opt_level.py +++ b/tests/micropython/opt_level.py @@ -8,12 +8,12 @@ print(micropython.opt_level()) # check that the optimisation levels actually differ micropython.opt_level(0) -exec('print(__debug__)') +exec("print(__debug__)") micropython.opt_level(1) -exec('print(__debug__)') -exec('assert 0') +exec("print(__debug__)") +exec("assert 0") # check that level 3 doesn't store line numbers # the expected output is that any line is printed as "line 1" micropython.opt_level(3) -exec('try:\n xyz\nexcept NameError as er:\n import sys\n sys.print_exception(er)') +exec("try:\n xyz\nexcept NameError as er:\n import sys\n sys.print_exception(er)") diff --git a/tests/micropython/schedule.py b/tests/micropython/schedule.py index 74f90cb2de..6a91459ea3 100644 --- a/tests/micropython/schedule.py +++ b/tests/micropython/schedule.py @@ -5,16 +5,18 @@ import micropython try: micropython.schedule except AttributeError: - print('SKIP') + print("SKIP") raise SystemExit # Basic test of scheduling a function. + def callback(arg): global done print(arg) done = True + done = False micropython.schedule(callback, 1) while not done: @@ -23,20 +25,23 @@ while not done: # Test that callbacks can be scheduled from within a callback, but # that they don't execute until the outer callback is finished. + def callback_inner(arg): global done - print('inner') + print("inner") done += 1 + def callback_outer(arg): global done micropython.schedule(callback_inner, 0) # need a loop so that the VM can check for pending events for i in range(2): pass - print('outer') + print("outer") done += 1 + done = 0 micropython.schedule(callback_outer, 0) while done != 2: @@ -45,15 +50,17 @@ while done != 2: # Test that scheduling too many callbacks leads to an exception. To do this we # must schedule from within a callback to guarantee that the scheduler is locked. + def callback(arg): global done try: for i in range(100): - micropython.schedule(lambda x:x, None) + micropython.schedule(lambda x: x, None) except RuntimeError: - print('RuntimeError') + print("RuntimeError") done = True + done = False micropython.schedule(callback, None) while not done: diff --git a/tests/micropython/stack_use.py b/tests/micropython/stack_use.py index bc714755a1..266885d9d1 100644 --- a/tests/micropython/stack_use.py +++ b/tests/micropython/stack_use.py @@ -1,7 +1,7 @@ # tests stack_use function in micropython module import micropython -if not hasattr(micropython, 'stack_use'): - print('SKIP') +if not hasattr(micropython, "stack_use"): + print("SKIP") else: - print(type(micropython.stack_use())) # output varies + print(type(micropython.stack_use())) # output varies diff --git a/tests/micropython/viper_addr.py b/tests/micropython/viper_addr.py index cd953ce07d..a696b06628 100644 --- a/tests/micropython/viper_addr.py +++ b/tests/micropython/viper_addr.py @@ -1,29 +1,32 @@ # test passing addresses to viper -@micropython.viper -def get_addr(x:ptr) -> ptr: - return x @micropython.viper -def memset(dest:ptr8, c:int, n:int): +def get_addr(x: ptr) -> ptr: + return x + + +@micropython.viper +def memset(dest: ptr8, c: int, n: int): for i in range(n): dest[i] = c + # create array and get its address -ar = bytearray('0000') +ar = bytearray("0000") addr = get_addr(ar) print(type(ar)) print(type(addr)) print(ar) # pass array as an object -memset(ar, ord('1'), len(ar)) +memset(ar, ord("1"), len(ar)) print(ar) # pass direct pointer to array buffer -memset(addr, ord('2'), len(ar)) +memset(addr, ord("2"), len(ar)) print(ar) # pass direct pointer to array buffer, with offset -memset(addr + 2, ord('3'), len(ar) - 2) +memset(addr + 2, ord("3"), len(ar) - 2) print(ar) diff --git a/tests/micropython/viper_args.py b/tests/micropython/viper_args.py index ee8e82321f..8e3225331a 100644 --- a/tests/micropython/viper_args.py +++ b/tests/micropython/viper_args.py @@ -1,44 +1,67 @@ # test calling viper functions with different number of args + @micropython.viper def f0(): print(0) + + f0() + @micropython.viper -def f1(x1:int): +def f1(x1: int): print(x1) + + f1(1) + @micropython.viper -def f2(x1:int, x2:int): +def f2(x1: int, x2: int): print(x1, x2) + + f2(1, 2) + @micropython.viper -def f3(x1:int, x2:int, x3:int): +def f3(x1: int, x2: int, x3: int): print(x1, x2, x3) + + f3(1, 2, 3) + @micropython.viper -def f4(x1:int, x2:int, x3:int, x4:int): +def f4(x1: int, x2: int, x3: int, x4: int): print(x1, x2, x3, x4) + + f4(1, 2, 3, 4) -@micropython.viper -def f5(x1:int, x2:int, x3:int, x4:int, x5:int): - print(x1, x2, x3, x4, x5) -f5(1, 2, 3, 4, 5) @micropython.viper -def f6(x1:int, x2:int, x3:int, x4:int, x5:int, x6:int): +def f5(x1: int, x2: int, x3: int, x4: int, x5: int): + print(x1, x2, x3, x4, x5) + + +f5(1, 2, 3, 4, 5) + + +@micropython.viper +def f6(x1: int, x2: int, x3: int, x4: int, x5: int, x6: int): print(x1, x2, x3, x4, x5, x6) + + f6(1, 2, 3, 4, 5, 6) # test compiling *x, **x, * args (currently unsupported at runtime) @micropython.viper def f(*x, **y): pass + + @micropython.viper def f(*): pass diff --git a/tests/micropython/viper_binop_arith.py b/tests/micropython/viper_binop_arith.py index 4d711f1a9f..2691404b7b 100644 --- a/tests/micropython/viper_binop_arith.py +++ b/tests/micropython/viper_binop_arith.py @@ -1,27 +1,36 @@ # test arithmetic operators + @micropython.viper -def add(x:int, y:int): +def add(x: int, y: int): print(x + y) print(y + x) + + add(1, 2) add(42, 3) add(-1, 2) add(-42, -3) + @micropython.viper -def sub(x:int, y:int): +def sub(x: int, y: int): print(x - y) print(y - x) + + sub(1, 2) sub(42, 3) sub(-1, 2) sub(-42, -3) + @micropython.viper -def mul(x:int, y:int): +def mul(x: int, y: int): print(x * y) print(y * x) + + mul(0, 1) mul(1, -1) mul(1, 2) @@ -29,41 +38,56 @@ mul(8, 3) mul(-3, 4) mul(-9, -6) + @micropython.viper -def shl(x:int, y:int): +def shl(x: int, y: int): print(x << y) + + shl(1, 0) shl(1, 3) shl(1, 30) shl(42, 10) shl(-42, 10) + @micropython.viper -def shr(x:int, y:int): +def shr(x: int, y: int): print(x >> y) + + shr(1, 0) shr(1, 3) shr(42, 2) shr(-42, 2) -@micropython.viper -def and_(x:int, y:int): - print(x & y, y & x) -and_(1, 0) -and_(1, 3) -and_(0xf0, 0x3f) -and_(-42, 6) @micropython.viper -def or_(x:int, y:int): +def and_(x: int, y: int): + print(x & y, y & x) + + +and_(1, 0) +and_(1, 3) +and_(0xF0, 0x3F) +and_(-42, 6) + + +@micropython.viper +def or_(x: int, y: int): print(x | y, y | x) + + or_(1, 0) or_(1, 2) or_(-42, 5) + @micropython.viper -def xor(x:int, y:int): +def xor(x: int, y: int): print(x ^ y, y ^ x) + + xor(1, 0) xor(1, 2) xor(-42, 5) diff --git a/tests/micropython/viper_binop_comp.py b/tests/micropython/viper_binop_comp.py index dcf91ed89d..a4c0809c85 100644 --- a/tests/micropython/viper_binop_comp.py +++ b/tests/micropython/viper_binop_comp.py @@ -1,6 +1,6 @@ # test comparison operators @micropython.viper -def f(x:int, y:int): +def f(x: int, y: int): if x < y: print(x, "<", y) if x > y: @@ -14,6 +14,7 @@ def f(x:int, y:int): if x != y: print(x, "!=", y) + f(1, 1) f(2, 1) f(1, 2) diff --git a/tests/micropython/viper_binop_comp_imm.py b/tests/micropython/viper_binop_comp_imm.py index c7c0408959..daab8fcfb5 100644 --- a/tests/micropython/viper_binop_comp_imm.py +++ b/tests/micropython/viper_binop_comp_imm.py @@ -3,6 +3,7 @@ def f(a: int): print(a == -1, a == -255, a == -256, a == -257) + f(-1) f(-255) f(-256) diff --git a/tests/micropython/viper_binop_divmod.py b/tests/micropython/viper_binop_divmod.py index 822424982a..4b74b527d3 100644 --- a/tests/micropython/viper_binop_divmod.py +++ b/tests/micropython/viper_binop_divmod.py @@ -1,16 +1,20 @@ # test floor-division and modulo operators -@micropython.viper -def div(x:int, y:int) -> int: - return x // y @micropython.viper -def mod(x:int, y:int) -> int: +def div(x: int, y: int) -> int: + return x // y + + +@micropython.viper +def mod(x: int, y: int) -> int: return x % y + def dm(x, y): print(div(x, y), mod(x, y)) + for x in (-6, 6): for y in range(-7, 8): if y == 0: diff --git a/tests/micropython/viper_binop_multi_comp.py b/tests/micropython/viper_binop_multi_comp.py index 8065db291b..997c397d4c 100644 --- a/tests/micropython/viper_binop_multi_comp.py +++ b/tests/micropython/viper_binop_multi_comp.py @@ -1,6 +1,6 @@ # test multi comparison operators @micropython.viper -def f(x:int, y:int): +def f(x: int, y: int): if 0 < x < y: print(x, "<", y) if 3 > x > y: @@ -14,6 +14,7 @@ def f(x:int, y:int): if 2 == x != y: print(x, "!=", y) + f(1, 1) f(2, 1) f(1, 2) diff --git a/tests/micropython/viper_cond.py b/tests/micropython/viper_cond.py index bbb3f69233..d5ebf837bd 100644 --- a/tests/micropython/viper_cond.py +++ b/tests/micropython/viper_cond.py @@ -6,6 +6,8 @@ def f(): pass else: print("not x", x) + + f() # using True as a conditional @@ -14,6 +16,8 @@ def f(): x = True if x: print("x", x) + + f() # using an int as a conditional @@ -22,6 +26,8 @@ def g(): y = 1 if y: print("y", y) + + g() # using an int as a conditional that has the lower 16-bits clear @@ -30,4 +36,6 @@ def h(): z = 0x10000 if z: print("z", z) + + h() diff --git a/tests/micropython/viper_const.py b/tests/micropython/viper_const.py index 5085ede90f..230b282f23 100644 --- a/tests/micropython/viper_const.py +++ b/tests/micropython/viper_const.py @@ -1,14 +1,21 @@ # test loading constants in viper functions + @micropython.viper def f(): - return b'bytes' + return b"bytes" + + print(f()) + @micropython.viper def f(): @micropython.viper def g() -> int: return 123 + return g + + print(f()()) diff --git a/tests/micropython/viper_const_intbig.py b/tests/micropython/viper_const_intbig.py index 6b44973880..42574820a3 100644 --- a/tests/micropython/viper_const_intbig.py +++ b/tests/micropython/viper_const_intbig.py @@ -1,7 +1,9 @@ # check loading constants + @micropython.viper def f(): return 123456789012345678901234567890 + print(f()) diff --git a/tests/micropython/viper_error.py b/tests/micropython/viper_error.py index ff32f54739..790f3d75c4 100644 --- a/tests/micropython/viper_error.py +++ b/tests/micropython/viper_error.py @@ -1,11 +1,13 @@ # test syntax and type errors specific to viper code generation + def test(code): try: exec(code) except (SyntaxError, ViperTypeError, NotImplementedError) as e: print(repr(e)) + # viper: annotations must be identifiers test("@micropython.viper\ndef f(a:1): pass") test("@micropython.viper\ndef f() -> 1: pass") @@ -14,30 +16,36 @@ test("@micropython.viper\ndef f() -> 1: pass") test("@micropython.viper\ndef f(x:unknown_type): pass") # local used before type known -test(""" +test( + """ @micropython.viper def f(): print(x) x = 1 -""") +""" +) # type mismatch storing to local -test(""" +test( + """ @micropython.viper def f(): x = 1 y = [] x = y -""") +""" +) # can't implicitly convert type to bool -test(""" +test( + """ @micropython.viper def f(): x = ptr(0) if x: pass -""") +""" +) # incorrect return type test("@micropython.viper\ndef f() -> int: return []") diff --git a/tests/micropython/viper_globals.py b/tests/micropython/viper_globals.py index 9c68dc3da8..9532dfd895 100644 --- a/tests/micropython/viper_globals.py +++ b/tests/micropython/viper_globals.py @@ -2,18 +2,21 @@ gl = {} -exec(""" +exec( + """ @micropython.viper def f(): return x -""", gl) +""", + gl, +) # x is not yet in the globals, f should not see it try: - print(gl['f']()) + print(gl["f"]()) except NameError: - print('NameError') + print("NameError") # x is in globals, f should now see it -gl['x'] = 123 -print(gl['f']()) +gl["x"] = 123 +print(gl["f"]()) diff --git a/tests/micropython/viper_import.py b/tests/micropython/viper_import.py index 9878007444..3df23e17a7 100644 --- a/tests/micropython/viper_import.py +++ b/tests/micropython/viper_import.py @@ -1,10 +1,15 @@ # test import within viper function + @micropython.viper def f(): import micropython + print(micropython.const(1)) from micropython import const + print(const(2)) + + f() diff --git a/tests/micropython/viper_misc.py b/tests/micropython/viper_misc.py index 021e03f2ca..41389c751d 100644 --- a/tests/micropython/viper_misc.py +++ b/tests/micropython/viper_misc.py @@ -2,61 +2,79 @@ import micropython # viper function taking and returning ints @micropython.viper -def viper_int(x:int, y:int) -> int: +def viper_int(x: int, y: int) -> int: return x + y + 3 + + print(viper_int(1, 2)) # viper function taking and returning objects @micropython.viper -def viper_object(x:object, y:object) -> object: +def viper_object(x: object, y: object) -> object: return x + y + + print(viper_object(1, 2)) # return None as non-object (should return 0) @micropython.viper def viper_ret_none() -> int: return None + + print(viper_ret_none()) # return Ellipsis as object @micropython.viper def viper_ret_ellipsis() -> object: return ... + + print(viper_ret_ellipsis()) # 3 args @micropython.viper -def viper_3args(a:int, b:int, c:int) -> int: +def viper_3args(a: int, b: int, c: int) -> int: return a + b + c + + print(viper_3args(1, 2, 3)) # 4 args @micropython.viper -def viper_4args(a:int, b:int, c:int, d:int) -> int: +def viper_4args(a: int, b: int, c: int, d: int) -> int: return a + b + c + d + + # viper call with 4 args not yet supported -#print(viper_4args(1, 2, 3, 4)) +# print(viper_4args(1, 2, 3, 4)) # a local (should have automatic type int) @micropython.viper -def viper_local(x:int) -> int: +def viper_local(x: int) -> int: y = 4 return x + y + + print(viper_local(3)) # without type annotation, types should default to object @micropython.viper def viper_no_annotation(x, y): return x * y + + print(viper_no_annotation(4, 5)) # a for loop @micropython.viper -def viper_for(a:int, b:int) -> int: +def viper_for(a: int, b: int) -> int: total = 0 for x in range(a, b): total += x return total + + print(viper_for(10, 10000)) # accessing a global @@ -65,42 +83,56 @@ def viper_access_global(): global gl gl = 1 return gl + + print(viper_access_global(), gl) # calling print with object and int types @micropython.viper -def viper_print(x, y:int): +def viper_print(x, y: int): print(x, y + 1) + + viper_print(1, 2) # convert constants to objects in tuple @micropython.viper def viper_tuple_consts(x): return (x, 1, False, True) + + print(viper_tuple_consts(0)) # making a tuple from an object and an int @micropython.viper -def viper_tuple(x, y:int): +def viper_tuple(x, y: int): return (x, y + 1) + + print(viper_tuple(1, 2)) # making a list from an object and an int @micropython.viper -def viper_list(x, y:int): +def viper_list(x, y: int): return [x, y + 1] + + print(viper_list(1, 2)) # making a set from an object and an int @micropython.viper -def viper_set(x, y:int): +def viper_set(x, y: int): return {x, y + 1} + + print(sorted(list(viper_set(1, 2)))) # raising an exception @micropython.viper -def viper_raise(x:int): +def viper_raise(x: int): raise OSError(x) + + try: viper_raise(1) except OSError as e: @@ -110,7 +142,10 @@ except OSError as e: @micropython.viper def viper_gc() -> int: return 1 + + print(viper_gc()) import gc + gc.collect() print(viper_gc()) diff --git a/tests/micropython/viper_misc_intbig.py b/tests/micropython/viper_misc_intbig.py index e036435c7a..055c08d8e5 100644 --- a/tests/micropython/viper_misc_intbig.py +++ b/tests/micropython/viper_misc_intbig.py @@ -4,5 +4,8 @@ import micropython @micropython.viper def viper_uint() -> uint: return uint(-1) + + import sys + print(viper_uint() == (sys.maxsize << 1 | 1)) diff --git a/tests/micropython/viper_ptr16_load.py b/tests/micropython/viper_ptr16_load.py index 0b865eb9e7..30c85d0669 100644 --- a/tests/micropython/viper_ptr16_load.py +++ b/tests/micropython/viper_ptr16_load.py @@ -1,21 +1,25 @@ # test loading from ptr16 type # only works on little endian machines + @micropython.viper -def get(src:ptr16) -> int: +def get(src: ptr16) -> int: return src[0] -@micropython.viper -def get1(src:ptr16) -> int: - return src[1] @micropython.viper -def memadd(src:ptr16, n:int) -> int: +def get1(src: ptr16) -> int: + return src[1] + + +@micropython.viper +def memadd(src: ptr16, n: int) -> int: sum = 0 for i in range(n): sum += src[i] return sum + @micropython.viper def memadd2(src_in) -> int: src = ptr16(src_in) @@ -25,7 +29,8 @@ def memadd2(src_in) -> int: sum += src[i] return sum -b = bytearray(b'1234') + +b = bytearray(b"1234") print(b) print(get(b), get1(b)) print(memadd(b, 2)) diff --git a/tests/micropython/viper_ptr16_store.py b/tests/micropython/viper_ptr16_store.py index 5a5f25d170..3ca5a027c0 100644 --- a/tests/micropython/viper_ptr16_store.py +++ b/tests/micropython/viper_ptr16_store.py @@ -1,25 +1,30 @@ # test ptr16 type + @micropython.viper -def set(dest:ptr16, val:int): +def set(dest: ptr16, val: int): dest[0] = val -@micropython.viper -def set1(dest:ptr16, val:int): - dest[1] = val @micropython.viper -def memset(dest:ptr16, val:int, n:int): +def set1(dest: ptr16, val: int): + dest[1] = val + + +@micropython.viper +def memset(dest: ptr16, val: int, n: int): for i in range(n): dest[i] = val + @micropython.viper -def memset2(dest_in, val:int): +def memset2(dest_in, val: int): dest = ptr16(dest_in) n = int(len(dest_in)) >> 1 for i in range(n): dest[i] = val + b = bytearray(4) print(b) diff --git a/tests/micropython/viper_ptr32_load.py b/tests/micropython/viper_ptr32_load.py index 4d8b3846de..b0b90bcaf5 100644 --- a/tests/micropython/viper_ptr32_load.py +++ b/tests/micropython/viper_ptr32_load.py @@ -1,20 +1,24 @@ # test loading from ptr32 type + @micropython.viper -def get(src:ptr32) -> int: +def get(src: ptr32) -> int: return src[0] -@micropython.viper -def get1(src:ptr32) -> int: - return src[1] @micropython.viper -def memadd(src:ptr32, n:int) -> int: +def get1(src: ptr32) -> int: + return src[1] + + +@micropython.viper +def memadd(src: ptr32, n: int) -> int: sum = 0 for i in range(n): sum += src[i] return sum + @micropython.viper def memadd2(src_in) -> int: src = ptr32(src_in) @@ -24,7 +28,8 @@ def memadd2(src_in) -> int: sum += src[i] return sum -b = bytearray(b'\x12\x12\x12\x12\x34\x34\x34\x34') + +b = bytearray(b"\x12\x12\x12\x12\x34\x34\x34\x34") print(b) print(hex(get(b)), hex(get1(b))) print(hex(memadd(b, 2))) diff --git a/tests/micropython/viper_ptr32_store.py b/tests/micropython/viper_ptr32_store.py index 973086e4ad..ff0c371ab8 100644 --- a/tests/micropython/viper_ptr32_store.py +++ b/tests/micropython/viper_ptr32_store.py @@ -1,25 +1,30 @@ # test store to ptr32 type + @micropython.viper -def set(dest:ptr32, val:int): +def set(dest: ptr32, val: int): dest[0] = val -@micropython.viper -def set1(dest:ptr32, val:int): - dest[1] = val @micropython.viper -def memset(dest:ptr32, val:int, n:int): +def set1(dest: ptr32, val: int): + dest[1] = val + + +@micropython.viper +def memset(dest: ptr32, val: int, n: int): for i in range(n): dest[i] = val + @micropython.viper -def memset2(dest_in, val:int): +def memset2(dest_in, val: int): dest = ptr32(dest_in) n = int(len(dest_in)) >> 2 for i in range(n): dest[i] = val + b = bytearray(8) print(b) diff --git a/tests/micropython/viper_ptr8_load.py b/tests/micropython/viper_ptr8_load.py index 0ccf8a1d76..d871bfb689 100644 --- a/tests/micropython/viper_ptr8_load.py +++ b/tests/micropython/viper_ptr8_load.py @@ -1,20 +1,24 @@ # test loading from ptr8 type + @micropython.viper -def get(src:ptr8) -> int: +def get(src: ptr8) -> int: return src[0] -@micropython.viper -def get1(src:ptr8) -> int: - return src[1] @micropython.viper -def memadd(src:ptr8, n:int) -> int: +def get1(src: ptr8) -> int: + return src[1] + + +@micropython.viper +def memadd(src: ptr8, n: int) -> int: sum = 0 for i in range(n): sum += src[i] return sum + @micropython.viper def memadd2(src_in) -> int: src = ptr8(src_in) @@ -24,7 +28,8 @@ def memadd2(src_in) -> int: sum += src[i] return sum -b = bytearray(b'1234') + +b = bytearray(b"1234") print(b) print(get(b), get1(b)) print(memadd(b, 4)) diff --git a/tests/micropython/viper_ptr8_store.py b/tests/micropython/viper_ptr8_store.py index 5a8622eb10..baa9e2c6d4 100644 --- a/tests/micropython/viper_ptr8_store.py +++ b/tests/micropython/viper_ptr8_store.py @@ -1,25 +1,30 @@ # test ptr8 type + @micropython.viper -def set(dest:ptr8, val:int): +def set(dest: ptr8, val: int): dest[0] = val -@micropython.viper -def set1(dest:ptr8, val:int): - dest[1] = val @micropython.viper -def memset(dest:ptr8, val:int, n:int): +def set1(dest: ptr8, val: int): + dest[1] = val + + +@micropython.viper +def memset(dest: ptr8, val: int, n: int): for i in range(n): dest[i] = val + @micropython.viper -def memset2(dest_in, val:int): +def memset2(dest_in, val: int): dest = ptr8(dest_in) n = int(len(dest_in)) for i in range(n): dest[i] = val + b = bytearray(4) print(b) diff --git a/tests/micropython/viper_subscr.py b/tests/micropython/viper_subscr.py index 2198ed7313..bcaabd3fb4 100644 --- a/tests/micropython/viper_subscr.py +++ b/tests/micropython/viper_subscr.py @@ -1,15 +1,18 @@ # test standard Python subscr using viper types + @micropython.viper -def get(dest, i:int): +def get(dest, i: int): i += 1 return dest[i] + @micropython.viper -def set(dest, i:int, val:int): +def set(dest, i: int, val: int): i += 1 dest[i] = val + 1 + ar = [i for i in range(3)] for i in range(len(ar)): diff --git a/tests/micropython/viper_try.py b/tests/micropython/viper_try.py index d75b3418e3..61335af221 100644 --- a/tests/micropython/viper_try.py +++ b/tests/micropython/viper_try.py @@ -6,11 +6,13 @@ def f(): try: fail finally: - print('finally') + print("finally") + + try: f() except NameError: - print('NameError') + print("NameError") # nested try-except with try-finally @micropython.viper @@ -19,9 +21,11 @@ def f(): try: fail finally: - print('finally') + print("finally") except NameError: - print('NameError') + print("NameError") + + f() # check that locals written to in try blocks keep their values @@ -36,5 +40,6 @@ def f(): print(a) a = 300 print(a) -f() + +f() diff --git a/tests/micropython/viper_with.py b/tests/micropython/viper_with.py index 2bc3c4f1b2..d640c8ae0f 100644 --- a/tests/micropython/viper_with.py +++ b/tests/micropython/viper_with.py @@ -1,18 +1,24 @@ # test with handling within a viper function + class C: def __init__(self): - print('__init__') + print("__init__") + def __enter__(self): - print('__enter__') + print("__enter__") + def __exit__(self, a, b, c): - print('__exit__', a, b, c) + print("__exit__", a, b, c) + # basic with @micropython.viper def f(): with C(): print(1) + + f() # nested with and try-except @@ -24,5 +30,7 @@ def f(): fail print(2) except NameError: - print('NameError') + print("NameError") + + f() diff --git a/tests/misc/features.py b/tests/misc/features.py index 874945bfcf..455b44fb1e 100644 --- a/tests/misc/features.py +++ b/tests/misc/features.py @@ -7,159 +7,199 @@ except AttributeError: # mad.py # Alf Clement 27-Mar-2014 # -zero=0 -three=3 +zero = 0 +three = 3 print("1") print("2") print(three) print("{}".format(4)) -five=25//5 +five = 25 // 5 print(int(five)) -j=0 +j = 0 for i in range(4): - j += i + j += i print(j) -print(3+4) +print(3 + 4) try: - a=4//zero + a = 4 // zero except: - print(8) + print(8) print("xxxxxxxxx".count("x")) + + def ten(): - return 10 + return 10 + + print(ten()) -a=[] +a = [] for i in range(13): - a.append(i) -print(a[11]) + a.append(i) +print(a[11]) print(a[-1]) -str="0123456789" -print(str[1]+str[3]) +str = "0123456789" +print(str[1] + str[3]) + + def p(s): - print(s) + print(s) + + p("14") p(15) + + class A: - def __init__(self): - self.a=16 - def print(self): - print(self.a) - def set(self,b): - self.a=b -a=A() + def __init__(self): + self.a = 16 + + def print(self): + print(self.a) + + def set(self, b): + self.a = b + + +a = A() a.print() a.set(17) a.print() -b=A() +b = A() b.set(a.a + 1) b.print() for i in range(20): - pass + pass print(i) if 20 > 30: - a="1" + a = "1" else: - a="2" + a = "2" if 0 < 4: - print(a+"0") + print(a + "0") else: - print(a+"1") -a=[20,21,22,23,24] + print(a + "1") +a = [20, 21, 22, 23, 24] for i in a: - if i < 21: - continue - if i > 21: - break - print(i) -b=[a,a,a] + if i < 21: + continue + if i > 21: + break + print(i) +b = [a, a, a] print(b[1][2]) -print(161//7) -a=24 +print(161 // 7) +a = 24 while True: - try: - def gcheck(): - global a - print(a) - gcheck() - class c25(): - x=25 - x=c25() - print(x.x) - raise - except: - print(26) - print(27+zero) - break + try: + + def gcheck(): + global a + print(a) + + gcheck() + + class c25: + x = 25 + + x = c25() + print(x.x) + raise + except: + print(26) + print(27 + zero) + break print(28) -k=29 +k = 29 + + def f(): - global k - k = yield k + global k + k = yield k + + print(next(f())) while True: - k+= 1 - if k < 30: - continue - break + k += 1 + if k < 30: + continue + break print(k) -for i in [1,2,3]: - class A(): - def __init__(self, c): - self.a = i+10*c - b = A(3) - print(b.a) +for i in [1, 2, 3]: + + class A: + def __init__(self, c): + self.a = i + 10 * c + + b = A(3) + print(b.a) print(34) -p=0 +p = 0 for i in range(35, -1, -1): - print(i) - p = p + 1 - if p > 0: - break -p=36 + print(i) + p = p + 1 + if p > 0: + break +p = 36 while p == 36: - print(p) - p=37 + print(p) + p = 37 print(p) for i in [38]: - print(i) -print(int(exec("def foo(): return 38") == None)+foo()) + print(i) +print(int(exec("def foo(): return 38") == None) + foo()) d = {} exec("def bar(): return 40", d) print(d["bar"]()) + + def fib2(n): - result = [] - a, b = 0, 1 - while a < n: - result.append(a) - a, b = b, a+b - return result -print(fib2(100)[-2]-14) -Answer={} -Answer["ForAll"]=42 + result = [] + a, b = 0, 1 + while a < n: + result.append(a) + a, b = b, a + b + return result + + +print(fib2(100)[-2] - 14) +Answer = {} +Answer["ForAll"] = 42 print(Answer["ForAll"]) i = 43 + + def f(i=i): print(i) + + i = 44 f() print(i) while True: - try: - if None != True: - print(45) - break - else: - print(0) - except: - print(0) + try: + if None != True: + print(45) + break + else: + print(0) + except: + print(0) print(46) -print(46+1) +print(46 + 1) + + def u(p): - if p > 3: - return 3*p - else: - return u(2*p)-3*u(p) + if p > 3: + return 3 * p + else: + return u(2 * p) - 3 * u(p) + + print(u(16)) + + def u49(): - return 49 + return 49 + + print(u49()) diff --git a/tests/misc/non_compliant.py b/tests/misc/non_compliant.py index 580583bf39..6aed3e0d1d 100644 --- a/tests/misc/non_compliant.py +++ b/tests/misc/non_compliant.py @@ -9,143 +9,153 @@ except ImportError: # when super can't find self try: - exec('def f(): super()') + exec("def f(): super()") except SyntaxError: - print('SyntaxError') + print("SyntaxError") # store to exception attribute is not allowed try: ValueError().x = 0 except AttributeError: - print('AttributeError') + print("AttributeError") # array deletion not implemented try: - a = array.array('b', (1, 2, 3)) + a = array.array("b", (1, 2, 3)) del a[1] except TypeError: - print('TypeError') + print("TypeError") # slice with step!=1 not implemented try: - a = array.array('b', (1, 2, 3)) + a = array.array("b", (1, 2, 3)) print(a[3:2:2]) except NotImplementedError: - print('NotImplementedError') + print("NotImplementedError") # containment, looking for integer not implemented try: - print(1 in array.array('B', b'12')) + print(1 in array.array("B", b"12")) except NotImplementedError: - print('NotImplementedError') + print("NotImplementedError") # uPy raises TypeError, shold be ValueError try: - '%c' % b'\x01\x02' + "%c" % b"\x01\x02" except (TypeError, ValueError): - print('TypeError, ValueError') + print("TypeError, ValueError") # attributes/subscr not implemented try: - print('{a[0]}'.format(a=[1, 2])) + print("{a[0]}".format(a=[1, 2])) except NotImplementedError: - print('NotImplementedError') + print("NotImplementedError") # str(...) with keywords not implemented try: - str(b'abc', encoding='utf8') + str(b"abc", encoding="utf8") except NotImplementedError: - print('NotImplementedError') + print("NotImplementedError") # str.rsplit(None, n) not implemented try: - 'a a a'.rsplit(None, 1) + "a a a".rsplit(None, 1) except NotImplementedError: - print('NotImplementedError') + print("NotImplementedError") # str.endswith(s, start) not implemented try: - 'abc'.endswith('c', 1) + "abc".endswith("c", 1) except NotImplementedError: - print('NotImplementedError') + print("NotImplementedError") # str subscr with step!=1 not implemented try: - print('abc'[1:2:3]) + print("abc"[1:2:3]) except NotImplementedError: - print('NotImplementedError') + print("NotImplementedError") # bytes(...) with keywords not implemented try: - bytes('abc', encoding='utf8') + bytes("abc", encoding="utf8") except NotImplementedError: - print('NotImplementedError') + print("NotImplementedError") # bytes subscr with step!=1 not implemented try: - b'123'[0:3:2] + b"123"[0:3:2] except NotImplementedError: - print('NotImplementedError') + print("NotImplementedError") # tuple load with step!=1 not implemented try: ()[2:3:4] except NotImplementedError: - print('NotImplementedError') + print("NotImplementedError") # list store with step!=1 not implemented try: [][2:3:4] = [] except NotImplementedError: - print('NotImplementedError') + print("NotImplementedError") # list delete with step!=1 not implemented try: del [][2:3:4] except NotImplementedError: - print('NotImplementedError') + print("NotImplementedError") # struct pack with too many args, not checked by uPy -print(ustruct.pack('bb', 1, 2, 3)) +print(ustruct.pack("bb", 1, 2, 3)) # struct pack with too few args, not checked by uPy -print(ustruct.pack('bb', 1)) +print(ustruct.pack("bb", 1)) # array slice assignment with unsupported RHS try: bytearray(4)[0:1] = [1, 2] except NotImplementedError: - print('NotImplementedError') + print("NotImplementedError") # can't assign attributes to a function def f(): pass + + try: f.x = 1 except AttributeError: - print('AttributeError') + print("AttributeError") # can't call a function type (ie make new instances of a function) try: type(f)() except TypeError: - print('TypeError') + print("TypeError") # test when object explicitly listed at not-last position in parent tuple # this is not compliant with CPython because of illegal MRO class A: def foo(self): - print('A.foo') + print("A.foo") + + class B(object, A): pass + + B().foo() # can't assign property (or other special accessors) to already-subclassed class class A: pass + + class B(A): pass + + try: A.bar = property() except AttributeError: - print('AttributeError') + print("AttributeError") diff --git a/tests/misc/non_compliant_lexer.py b/tests/misc/non_compliant_lexer.py index 7e50d2836c..e1c21f3d71 100644 --- a/tests/misc/non_compliant_lexer.py +++ b/tests/misc/non_compliant_lexer.py @@ -1,31 +1,33 @@ # lexer tests for things that are not implemented, or have non-compliant behaviour + def test(code): try: exec(code) - print('no Error') + print("no Error") except SyntaxError: - print('SyntaxError') + print("SyntaxError") except NotImplementedError: - print('NotImplementedError') + print("NotImplementedError") + # uPy requires spaces between literal numbers and keywords, CPy doesn't try: - eval('1and 0') + eval("1and 0") except SyntaxError: - print('SyntaxError') + print("SyntaxError") try: - eval('1or 0') + eval("1or 0") except SyntaxError: - print('SyntaxError') + print("SyntaxError") try: - eval('1if 1else 0') + eval("1if 1else 0") except SyntaxError: - print('SyntaxError') + print("SyntaxError") try: - eval('1if 0else 0') + eval("1if 0else 0") except SyntaxError: - print('SyntaxError') + print("SyntaxError") # unicode name escapes are not implemented test('"\\N{LATIN SMALL LETTER A}"') diff --git a/tests/misc/print_exception.py b/tests/misc/print_exception.py index 95431632f9..edb3045878 100644 --- a/tests/misc/print_exception.py +++ b/tests/misc/print_exception.py @@ -1,4 +1,5 @@ import sys + try: try: import uio as io @@ -8,12 +9,14 @@ except ImportError: print("SKIP") raise SystemExit -if hasattr(sys, 'print_exception'): +if hasattr(sys, "print_exception"): print_exception = sys.print_exception else: import traceback + print_exception = lambda e, f: traceback.print_exception(None, e, sys.exc_info()[2], file=f) + def print_exc(e): buf = io.StringIO() print_exception(e, buf) @@ -29,36 +32,43 @@ def print_exc(e): elif not l.startswith(" "): print(l) + # basic exception message try: - raise Exception('msg') + raise Exception("msg") except Exception as e: - print('caught') + print("caught") print_exc(e) # exception message with more than 1 source-code line def f(): g() + + def g(): - raise Exception('fail') + raise Exception("fail") + + try: f() except Exception as e: - print('caught') + print("caught") print_exc(e) # Here we have a function with lots of bytecode generated for a single source-line, and # there is an error right at the end of the bytecode. It should report the correct line. def f(): - f([1, 2], [1, 2], [1, 2], {1:1, 1:1, 1:1, 1:1, 1:1, 1:1, 1:f.X}) + f([1, 2], [1, 2], [1, 2], {1: 1, 1: 1, 1: 1, 1: 1, 1: 1, 1: 1, 1: f.X}) return 1 + + try: f() except Exception as e: print_exc(e) # Test non-stream object passed as output object, only valid for uPy -if hasattr(sys, 'print_exception'): +if hasattr(sys, "print_exception"): try: sys.print_exception(Exception, 1) had_exception = False diff --git a/tests/misc/rge_sm.py b/tests/misc/rge_sm.py index 5bbf9d48b5..f3bb4189f7 100644 --- a/tests/misc/rge_sm.py +++ b/tests/misc/rge_sm.py @@ -3,30 +3,31 @@ import math + class RungeKutta(object): def __init__(self, functions, initConditions, t0, dh, save=True): - self.Trajectory, self.save = [[t0] + initConditions], save - self.functions = [lambda *args: 1.0] + list(functions) - self.N, self.dh = len(self.functions), dh - self.coeff = [1.0/6.0, 2.0/6.0, 2.0/6.0, 1.0/6.0] - self.InArgCoeff = [0.0, 0.5, 0.5, 1.0] + self.Trajectory, self.save = [[t0] + initConditions], save + self.functions = [lambda *args: 1.0] + list(functions) + self.N, self.dh = len(self.functions), dh + self.coeff = [1.0 / 6.0, 2.0 / 6.0, 2.0 / 6.0, 1.0 / 6.0] + self.InArgCoeff = [0.0, 0.5, 0.5, 1.0] def iterate(self): - step = self.Trajectory[-1][:] - istep, iac = step[:], self.InArgCoeff + step = self.Trajectory[-1][:] + istep, iac = step[:], self.InArgCoeff k, ktmp = self.N * [0.0], self.N * [0.0] for ic, c in enumerate(self.coeff): for if_, f in enumerate(self.functions): - arguments = [ (x + k[i]*iac[ic]) for i, x in enumerate(istep)] + arguments = [(x + k[i] * iac[ic]) for i, x in enumerate(istep)] try: feval = f(*arguments) except OverflowError: return False - if abs(feval) > 1e2: # stop integrating + if abs(feval) > 1e2: # stop integrating return False - ktmp[if_] = self.dh * feval + ktmp[if_] = self.dh * feval k = ktmp[:] - step = [s + c*k[ik] for ik,s in enumerate(step)] + step = [s + c * k[ik] for ik, s in enumerate(step)] if self.save: self.Trajectory += [step] else: @@ -46,23 +47,45 @@ class RungeKutta(object): def series(self): return zip(*self.Trajectory) + # 1-loop RGES for the main parameters of the SM # couplings are: g1, g2, g3 of U(1), SU(2), SU(3); yt (top Yukawa), lambda (Higgs quartic) # see arxiv.org/abs/0812.4950, eqs 10-15 sysSM = ( - lambda *a: 41.0 / 96.0 / math.pi**2 * a[1]**3, # g1 - lambda *a: -19.0 / 96.0 / math.pi**2 * a[2]**3, # g2 - lambda *a: -42.0 / 96.0 / math.pi**2 * a[3]**3, # g3 - lambda *a: 1.0 / 16.0 / math.pi**2 * (9.0 / 2.0 * a[4]**3 - 8.0 * a[3]**2 * a[4] - 9.0 / 4.0 * a[2]**2 * a[4] - 17.0 / 12.0 * a[1]**2 * a[4]), # yt - lambda *a: 1.0 / 16.0 / math.pi**2 * (24.0 * a[5]**2 + 12.0 * a[4]**2 * a[5] - 9.0 * a[5] * (a[2]**2 + 1.0 / 3.0 * a[1]**2) - 6.0 * a[4]**4 + 9.0 / 8.0 * a[2]**4 + 3.0 / 8.0 * a[1]**4 + 3.0 / 4.0 * a[2]**2 * a[1]**2), # lambda + lambda *a: 41.0 / 96.0 / math.pi ** 2 * a[1] ** 3, # g1 + lambda *a: -19.0 / 96.0 / math.pi ** 2 * a[2] ** 3, # g2 + lambda *a: -42.0 / 96.0 / math.pi ** 2 * a[3] ** 3, # g3 + lambda *a: 1.0 + / 16.0 + / math.pi ** 2 + * ( + 9.0 / 2.0 * a[4] ** 3 + - 8.0 * a[3] ** 2 * a[4] + - 9.0 / 4.0 * a[2] ** 2 * a[4] + - 17.0 / 12.0 * a[1] ** 2 * a[4] + ), # yt + lambda *a: 1.0 + / 16.0 + / math.pi ** 2 + * ( + 24.0 * a[5] ** 2 + + 12.0 * a[4] ** 2 * a[5] + - 9.0 * a[5] * (a[2] ** 2 + 1.0 / 3.0 * a[1] ** 2) + - 6.0 * a[4] ** 4 + + 9.0 / 8.0 * a[2] ** 4 + + 3.0 / 8.0 * a[1] ** 4 + + 3.0 / 4.0 * a[2] ** 2 * a[1] ** 2 + ), # lambda ) + def drange(start, stop, step): r = start while r < stop: yield r r += step + def phaseDiagram(system, trajStart, trajPlot, h=0.1, tend=1.0, range=1.0): tstart = 0.0 for i in drange(0, range, 0.1 * range): @@ -82,10 +105,10 @@ def phaseDiagram(system, trajStart, trajPlot, h=0.1, tend=1.0, range=1.0): p2 = rk.Trajectory[2 * l] x1, y1 = trajPlot(p1) x2, y2 = trajPlot(p2) - dx = -0.5 * (y2 - y1) # orthogonal to line + dx = -0.5 * (y2 - y1) # orthogonal to line dy = 0.5 * (x2 - x1) # orthogonal to line - #l = math.sqrt(dx*dx + dy*dy) - #if abs(l) > 1e-3: + # l = math.sqrt(dx*dx + dy*dy) + # if abs(l) > 1e-3: # l = 0.1 / l # dx *= l # dy *= l @@ -94,6 +117,7 @@ def phaseDiagram(system, trajStart, trajPlot, h=0.1, tend=1.0, range=1.0): print(x1 - dx, y1 - dy) print() + def singleTraj(system, trajStart, h=0.02, tend=1.0): tstart = 0.0 @@ -106,9 +130,12 @@ def singleTraj(system, trajStart, h=0.02, tend=1.0): for i in range(len(rk.Trajectory)): tr = rk.Trajectory[i] - print(' '.join(["{:.4f}".format(t) for t in tr])) + print(" ".join(["{:.4f}".format(t) for t in tr])) -#phaseDiagram(sysSM, (lambda i, j: [0.354, 0.654, 1.278, 0.8 + 0.2 * i, 0.1 + 0.1 * j]), (lambda a: (a[4], a[5])), h=0.1, tend=math.log(10**17)) + +# phaseDiagram(sysSM, (lambda i, j: [0.354, 0.654, 1.278, 0.8 + 0.2 * i, 0.1 + 0.1 * j]), (lambda a: (a[4], a[5])), h=0.1, tend=math.log(10**17)) # initial conditions at M_Z -singleTraj(sysSM, [0.354, 0.654, 1.278, 0.983, 0.131], h=0.5, tend=math.log(10**17)) # true values +singleTraj( + sysSM, [0.354, 0.654, 1.278, 0.983, 0.131], h=0.5, tend=math.log(10 ** 17) +) # true values diff --git a/tests/misc/sys_exc_info.py b/tests/misc/sys_exc_info.py index bf9438e462..d7e8a2d943 100644 --- a/tests/misc/sys_exc_info.py +++ b/tests/misc/sys_exc_info.py @@ -1,15 +1,18 @@ import sys + try: sys.exc_info except: print("SKIP") raise SystemExit + def f(): print(sys.exc_info()[0:2]) + try: - raise ValueError('value', 123) + raise ValueError("value", 123) except: print(sys.exc_info()[0:2]) f() diff --git a/tests/net_hosted/accept_nonblock.py b/tests/net_hosted/accept_nonblock.py index 56f3288e28..941965e178 100644 --- a/tests/net_hosted/accept_nonblock.py +++ b/tests/net_hosted/accept_nonblock.py @@ -6,11 +6,11 @@ except: import socket s = socket.socket() -s.bind(socket.getaddrinfo('127.0.0.1', 8123)[0][-1]) +s.bind(socket.getaddrinfo("127.0.0.1", 8123)[0][-1]) s.setblocking(False) s.listen(1) try: s.accept() except OSError as er: - print(er.args[0] == 11) # 11 is EAGAIN + print(er.args[0] == 11) # 11 is EAGAIN s.close() diff --git a/tests/net_hosted/accept_timeout.py b/tests/net_hosted/accept_timeout.py index 44b3b8c7cd..ff989110ae 100644 --- a/tests/net_hosted/accept_timeout.py +++ b/tests/net_hosted/accept_timeout.py @@ -8,15 +8,15 @@ except: try: socket.socket.settimeout except AttributeError: - print('SKIP') + print("SKIP") raise SystemExit s = socket.socket() -s.bind(socket.getaddrinfo('127.0.0.1', 8123)[0][-1]) +s.bind(socket.getaddrinfo("127.0.0.1", 8123)[0][-1]) s.settimeout(1) s.listen(1) try: s.accept() except OSError as er: - print(er.args[0] in (110, 'timed out')) # 110 is ETIMEDOUT; CPython uses a string + print(er.args[0] in (110, "timed out")) # 110 is ETIMEDOUT; CPython uses a string s.close() diff --git a/tests/net_hosted/connect_nonblock.py b/tests/net_hosted/connect_nonblock.py index 6479978bea..3a3eaa2ba0 100644 --- a/tests/net_hosted/connect_nonblock.py +++ b/tests/net_hosted/connect_nonblock.py @@ -12,9 +12,9 @@ def test(peer_addr): try: s.connect(peer_addr) except OSError as er: - print(er.args[0] == 115) # 115 is EINPROGRESS + print(er.args[0] == 115) # 115 is EINPROGRESS s.close() if __name__ == "__main__": - test(socket.getaddrinfo('micropython.org', 80)[0][-1]) + test(socket.getaddrinfo("micropython.org", 80)[0][-1]) diff --git a/tests/net_hosted/connect_poll.py b/tests/net_hosted/connect_poll.py index ece6aa0da9..90f9b7138e 100644 --- a/tests/net_hosted/connect_poll.py +++ b/tests/net_hosted/connect_poll.py @@ -29,4 +29,4 @@ def test(peer_addr): if __name__ == "__main__": - test(socket.getaddrinfo('micropython.org', 80)[0][-1]) + test(socket.getaddrinfo("micropython.org", 80)[0][-1]) diff --git a/tests/net_hosted/ssl_getpeercert.py b/tests/net_hosted/ssl_getpeercert.py index e265c830d0..dee5fcfd89 100644 --- a/tests/net_hosted/ssl_getpeercert.py +++ b/tests/net_hosted/ssl_getpeercert.py @@ -18,4 +18,4 @@ def test(peer_addr): if __name__ == "__main__": - test(socket.getaddrinfo('micropython.org', 443)[0][-1]) + test(socket.getaddrinfo("micropython.org", 443)[0][-1]) diff --git a/tests/net_inet/test_tls_sites.py b/tests/net_inet/test_tls_sites.py index bf8071d087..7fdafab99a 100644 --- a/tests/net_inet/test_tls_sites.py +++ b/tests/net_inet/test_tls_sites.py @@ -6,6 +6,7 @@ try: import ussl as ssl except: import ssl + # CPython only supports server_hostname with SSLContext ssl = ssl.SSLContext() @@ -24,9 +25,9 @@ def test_one(site, opts): else: s = ssl.wrap_socket(s) - s.write(b"GET / HTTP/1.0\r\nHost: %s\r\n\r\n" % bytes(site, 'latin')) + s.write(b"GET / HTTP/1.0\r\nHost: %s\r\n\r\n" % bytes(site, "latin")) resp = s.read(4096) -# print(resp) + # print(resp) finally: s.close() @@ -37,7 +38,7 @@ SITES = [ "www.google.com", "api.telegram.org", {"host": "api.pushbullet.com", "sni": True}, -# "w9rybpfril.execute-api.ap-southeast-2.amazonaws.com", + # "w9rybpfril.execute-api.ap-southeast-2.amazonaws.com", {"host": "w9rybpfril.execute-api.ap-southeast-2.amazonaws.com", "sni": True}, ] diff --git a/tests/pyb/adc.py b/tests/pyb/adc.py index 0bd9b9d53a..fff5a3019e 100644 --- a/tests/pyb/adc.py +++ b/tests/pyb/adc.py @@ -1,8 +1,8 @@ from pyb import ADC, Timer -adct = ADC(16) # Temperature 930 -> 20C +adct = ADC(16) # Temperature 930 -> 20C print(adct) -adcv = ADC(17) # Voltage 1500 -> 3.3V +adcv = ADC(17) # Voltage 1500 -> 3.3V print(adcv) # read single sample; 2.5V-5V is pass range @@ -13,7 +13,7 @@ assert val > 1000 and val < 2000 tim = Timer(5, freq=500) # read into bytearray -buf = bytearray(b'\xff' * 50) +buf = bytearray(b"\xff" * 50) adcv.read_timed(buf, tim) print(len(buf)) for i in buf: @@ -21,21 +21,22 @@ for i in buf: # read into arrays with different element sizes import array -arv = array.array('h', 25 * [0x7fff]) + +arv = array.array("h", 25 * [0x7FFF]) adcv.read_timed(arv, tim) print(len(arv)) for i in arv: assert i > 1000 and i < 2000 -arv = array.array('i', 30 * [-1]) +arv = array.array("i", 30 * [-1]) adcv.read_timed(arv, tim) print(len(arv)) for i in arv: assert i > 1000 and i < 2000 # Test read_timed_multi -arv = bytearray(b'\xff'*50) -art = bytearray(b'\xff'*50) +arv = bytearray(b"\xff" * 50) +art = bytearray(b"\xff" * 50) ADC.read_timed_multi((adcv, adct), (arv, art), tim) for i in arv: assert i > 60 and i < 125 @@ -43,8 +44,8 @@ for i in arv: for i in art: assert i > 15 and i < 200 -arv = array.array('i', 25 * [-1]) -art = array.array('i', 25 * [-1]) +arv = array.array("i", 25 * [-1]) +art = array.array("i", 25 * [-1]) ADC.read_timed_multi((adcv, adct), (arv, art), tim) for i in arv: assert i > 1000 and i < 2000 @@ -52,8 +53,8 @@ for i in arv: for i in art: assert i > 50 and i < 2000 -arv = array.array('h', 25 * [0x7fff]) -art = array.array('h', 25 * [0x7fff]) +arv = array.array("h", 25 * [0x7FFF]) +art = array.array("h", 25 * [0x7FFF]) ADC.read_timed_multi((adcv, adct), (arv, art), tim) for i in arv: assert i > 1000 and i < 2000 diff --git a/tests/pyb/can.py b/tests/pyb/can.py index 8a08ea9a65..7d27318d86 100644 --- a/tests/pyb/can.py +++ b/tests/pyb/can.py @@ -1,7 +1,7 @@ try: from pyb import CAN except ImportError: - print('SKIP') + print("SKIP") raise SystemExit from array import array @@ -40,23 +40,23 @@ print(can.info()) # Catch all filter can.setfilter(0, CAN.MASK16, 0, (0, 0, 0, 0)) -can.send('abcd', 123, timeout=5000) +can.send("abcd", 123, timeout=5000) print(can.any(0), can.info()) print(can.recv(0)) -can.send('abcd', -1, timeout=5000) +can.send("abcd", -1, timeout=5000) print(can.recv(0)) -can.send('abcd', 0x7FF + 1, timeout=5000) +can.send("abcd", 0x7FF + 1, timeout=5000) print(can.recv(0)) # Test too long message try: - can.send('abcdefghi', 0x7FF, timeout=5000) + can.send("abcdefghi", 0x7FF, timeout=5000) except ValueError: - print('passed') + print("passed") else: - print('failed') + print("failed") # Test that recv can work without allocating memory on the heap @@ -66,22 +66,22 @@ l2 = None micropython.heap_lock() -can.send('', 42) +can.send("", 42) l2 = can.recv(0, l) assert l is l2 print(l, len(l[3]), buf) -can.send('1234', 42) +can.send("1234", 42) l2 = can.recv(0, l) assert l is l2 print(l, len(l[3]), buf) -can.send('01234567', 42) +can.send("01234567", 42) l2 = can.recv(0, l) assert l is l2 print(l, len(l[3]), buf) -can.send('abc', 42) +can.send("abc", 42) l2 = can.recv(0, l) assert l is l2 print(l, len(l[3]), buf) @@ -89,65 +89,65 @@ print(l, len(l[3]), buf) micropython.heap_unlock() # Test that recv can work with different arrays behind the memoryview -can.send('abc', 1) -print(bytes(can.recv(0, [0, 0, 0, memoryview(array('B', range(8)))])[3])) -can.send('def', 1) -print(bytes(can.recv(0, [0, 0, 0, memoryview(array('b', range(8)))])[3])) +can.send("abc", 1) +print(bytes(can.recv(0, [0, 0, 0, memoryview(array("B", range(8)))])[3])) +can.send("def", 1) +print(bytes(can.recv(0, [0, 0, 0, memoryview(array("b", range(8)))])[3])) # Test for non-list passed as second arg to recv -can.send('abc', 1) +can.send("abc", 1) try: can.recv(0, 1) except TypeError: - print('TypeError') + print("TypeError") # Test for too-short-list passed as second arg to recv -can.send('abc', 1) +can.send("abc", 1) try: can.recv(0, [0, 0, 0]) except ValueError: - print('ValueError') + print("ValueError") # Test for non-memoryview passed as 4th element to recv -can.send('abc', 1) +can.send("abc", 1) try: can.recv(0, [0, 0, 0, 0]) except TypeError: - print('TypeError') + print("TypeError") # Test for read-only-memoryview passed as 4th element to recv -can.send('abc', 1) +can.send("abc", 1) try: can.recv(0, [0, 0, 0, memoryview(bytes(8))]) except ValueError: - print('ValueError') + print("ValueError") # Test for bad-typecode-memoryview passed as 4th element to recv -can.send('abc', 1) +can.send("abc", 1) try: - can.recv(0, [0, 0, 0, memoryview(array('i', range(8)))]) + can.recv(0, [0, 0, 0, memoryview(array("i", range(8)))]) except ValueError: - print('ValueError') + print("ValueError") del can # Testing extended IDs -can = CAN(1, CAN.LOOPBACK, extframe = True) +can = CAN(1, CAN.LOOPBACK, extframe=True) # Catch all filter can.setfilter(0, CAN.MASK32, 0, (0, 0)) print(can) try: - can.send('abcde', 0x7FF + 1, timeout=5000) + can.send("abcde", 0x7FF + 1, timeout=5000) except ValueError: - print('failed') + print("failed") else: r = can.recv(0) - if r[0] == 0x7FF+1 and r[3] == b'abcde': - print('passed') + if r[0] == 0x7FF + 1 and r[3] == b"abcde": + print("passed") else: - print('failed, wrong data received') + print("failed, wrong data received") # Test filters for n in [0, 8, 16, 24]: @@ -159,7 +159,7 @@ for n in [0, 8, 16, 24]: can.clearfilter(0) can.setfilter(0, pyb.CAN.MASK32, 0, (filter_id, filter_mask)) - can.send('ok', id_ok, timeout=3) + can.send("ok", id_ok, timeout=3) if can.any(0): msg = can.recv(0) print((hex(filter_id), hex(filter_mask), hex(msg[0]), msg[3])) @@ -175,57 +175,62 @@ del can can = CAN(1, CAN.LOOPBACK) can.setfilter(0, CAN.LIST16, 0, (1, 2, 3, 4)) can.setfilter(1, CAN.LIST16, 1, (5, 6, 7, 8)) + + def cb0(bus, reason): - print('cb0') + print("cb0") if reason == 0: - print('pending') + print("pending") if reason == 1: - print('full') + print("full") if reason == 2: - print('overflow') + print("overflow") + def cb1(bus, reason): - print('cb1') + print("cb1") if reason == 0: - print('pending') + print("pending") if reason == 1: - print('full') + print("full") if reason == 2: - print('overflow') + print("overflow") + def cb0a(bus, reason): - print('cb0a') + print("cb0a") if reason == 0: - print('pending') + print("pending") if reason == 1: - print('full') + print("full") if reason == 2: - print('overflow') + print("overflow") + def cb1a(bus, reason): - print('cb1a') + print("cb1a") if reason == 0: - print('pending') + print("pending") if reason == 1: - print('full') + print("full") if reason == 2: - print('overflow') + print("overflow") can.rxcallback(0, cb0) can.rxcallback(1, cb1) -can.send('11111111',1, timeout=5000) -can.send('22222222',2, timeout=5000) -can.send('33333333',3, timeout=5000) +can.send("11111111", 1, timeout=5000) +can.send("22222222", 2, timeout=5000) +can.send("33333333", 3, timeout=5000) can.rxcallback(0, cb0a) -can.send('44444444',4, timeout=5000) +can.send("44444444", 4, timeout=5000) -can.send('55555555',5, timeout=5000) -can.send('66666666',6, timeout=5000) -can.send('77777777',7, timeout=5000) +can.send("55555555", 5, timeout=5000) +can.send("66666666", 6, timeout=5000) +can.send("77777777", 7, timeout=5000) can.rxcallback(1, cb1a) -can.send('88888888',8, timeout=5000) +can.send("88888888", 8, timeout=5000) print(can.recv(0)) print(can.recv(0)) @@ -234,8 +239,8 @@ print(can.recv(1)) print(can.recv(1)) print(can.recv(1)) -can.send('11111111',1, timeout=5000) -can.send('55555555',5, timeout=5000) +can.send("11111111", 1, timeout=5000) +can.send("55555555", 5, timeout=5000) print(can.recv(0)) print(can.recv(1)) @@ -249,7 +254,7 @@ can.setfilter(0, CAN.MASK16, 0, (0, 0, 0, 0)) while can.any(0): can.recv(0) -can.send('abcde', 1, timeout=0) +can.send("abcde", 1, timeout=0) print(can.any(0)) while not can.any(0): pass @@ -257,15 +262,15 @@ while not can.any(0): print(can.recv(0)) try: - can.send('abcde', 2, timeout=0) - can.send('abcde', 3, timeout=0) - can.send('abcde', 4, timeout=0) - can.send('abcde', 5, timeout=0) + can.send("abcde", 2, timeout=0) + can.send("abcde", 3, timeout=0) + can.send("abcde", 4, timeout=0) + can.send("abcde", 5, timeout=0) except OSError as e: - if str(e) == '16': - print('passed') + if str(e) == "16": + print("passed") else: - print('failed') + print("failed") pyb.delay(500) while can.any(0): @@ -273,7 +278,7 @@ while can.any(0): # Testing rtr messages bus1 = CAN(1, CAN.LOOPBACK) -bus2 = CAN(2, CAN.LOOPBACK, extframe = True) +bus2 = CAN(2, CAN.LOOPBACK, extframe=True) while bus1.any(0): bus1.recv(0) while bus2.any(0): @@ -286,24 +291,24 @@ bus2.setfilter(1, CAN.LIST32, 0, (3, 4), rtr=(True, False)) bus2.setfilter(2, CAN.MASK32, 0, (16, 16), rtr=(False,)) bus2.setfilter(2, CAN.MASK32, 0, (32, 32), rtr=(True,)) -bus1.send('',1,rtr=True) +bus1.send("", 1, rtr=True) print(bus1.any(0)) -bus1.send('',5,rtr=True) +bus1.send("", 5, rtr=True) print(bus1.recv(0)) -bus1.send('',6,rtr=True) +bus1.send("", 6, rtr=True) print(bus1.recv(0)) -bus1.send('',7,rtr=True) +bus1.send("", 7, rtr=True) print(bus1.recv(0)) -bus1.send('',16,rtr=True) +bus1.send("", 16, rtr=True) print(bus1.any(0)) -bus1.send('',32,rtr=True) +bus1.send("", 32, rtr=True) print(bus1.recv(0)) -bus2.send('',1,rtr=True) +bus2.send("", 1, rtr=True) print(bus2.recv(0)) -bus2.send('',2,rtr=True) +bus2.send("", 2, rtr=True) print(bus2.recv(0)) -bus2.send('',3,rtr=True) +bus2.send("", 3, rtr=True) print(bus2.recv(0)) -bus2.send('',4,rtr=True) +bus2.send("", 4, rtr=True) print(bus2.any(0)) diff --git a/tests/pyb/dac.py b/tests/pyb/dac.py index ca68ec7098..506cf272b3 100644 --- a/tests/pyb/dac.py +++ b/tests/pyb/dac.py @@ -1,7 +1,7 @@ import pyb -if not hasattr(pyb, 'DAC'): - print('SKIP') +if not hasattr(pyb, "DAC"): + print("SKIP") raise SystemExit dac = pyb.DAC(1) diff --git a/tests/pyb/extint.py b/tests/pyb/extint.py index ae98ccd5a0..927b2bceba 100644 --- a/tests/pyb/extint.py +++ b/tests/pyb/extint.py @@ -1,7 +1,7 @@ import pyb # test basic functionality -ext = pyb.ExtInt('Y1', pyb.ExtInt.IRQ_RISING, pyb.Pin.PULL_DOWN, lambda l:print('line:', l)) +ext = pyb.ExtInt("Y1", pyb.ExtInt.IRQ_RISING, pyb.Pin.PULL_DOWN, lambda l: print("line:", l)) ext.disable() ext.enable() print(ext.line()) diff --git a/tests/pyb/halerror.py b/tests/pyb/halerror.py index 1a6bce1a7e..97b1ca1acb 100644 --- a/tests/pyb/halerror.py +++ b/tests/pyb/halerror.py @@ -10,6 +10,6 @@ except OSError as e: can = pyb.CAN(1, pyb.CAN.NORMAL) try: - can.send('1', 1, timeout=50) + can.send("1", 1, timeout=50) except OSError as e: print(repr(e)) diff --git a/tests/pyb/i2c.py b/tests/pyb/i2c.py index 6875e5a5aa..8d35ae7f6d 100644 --- a/tests/pyb/i2c.py +++ b/tests/pyb/i2c.py @@ -19,7 +19,7 @@ i2c.deinit() accel_addr = 76 -pyb.Accel() # this will init the MMA for us +pyb.Accel() # this will init the MMA for us i2c.init(I2C.MASTER, baudrate=400000) print(i2c.scan()) diff --git a/tests/pyb/i2c_error.py b/tests/pyb/i2c_error.py index 3201d6367d..0c4d45e851 100644 --- a/tests/pyb/i2c_error.py +++ b/tests/pyb/i2c_error.py @@ -11,40 +11,40 @@ i2c = I2C(1, I2C.MASTER, dma=True) # test polling mem_read pyb.disable_irq() -i2c.mem_read(1, 76, 0x0a) # should succeed +i2c.mem_read(1, 76, 0x0A) # should succeed pyb.enable_irq() try: pyb.disable_irq() - i2c.mem_read(1, 77, 0x0a) # should fail + i2c.mem_read(1, 77, 0x0A) # should fail except OSError as e: pyb.enable_irq() print(repr(e)) -i2c.mem_read(1, 76, 0x0a) # should succeed +i2c.mem_read(1, 76, 0x0A) # should succeed # test polling mem_write pyb.disable_irq() -i2c.mem_write(1, 76, 0x0a) # should succeed +i2c.mem_write(1, 76, 0x0A) # should succeed pyb.enable_irq() try: pyb.disable_irq() - i2c.mem_write(1, 77, 0x0a) # should fail + i2c.mem_write(1, 77, 0x0A) # should fail except OSError as e: pyb.enable_irq() print(repr(e)) -i2c.mem_write(1, 76, 0x0a) # should succeed +i2c.mem_write(1, 76, 0x0A) # should succeed # test DMA mem_read -i2c.mem_read(1, 76, 0x0a) # should succeed +i2c.mem_read(1, 76, 0x0A) # should succeed try: - i2c.mem_read(1, 77, 0x0a) # should fail + i2c.mem_read(1, 77, 0x0A) # should fail except OSError as e: print(repr(e)) -i2c.mem_read(1, 76, 0x0a) # should succeed +i2c.mem_read(1, 76, 0x0A) # should succeed # test DMA mem_write -i2c.mem_write(1, 76, 0x0a) # should succeed +i2c.mem_write(1, 76, 0x0A) # should succeed try: - i2c.mem_write(1, 77, 0x0a) # should fail + i2c.mem_write(1, 77, 0x0A) # should fail except OSError as e: print(repr(e)) -i2c.mem_write(1, 76, 0x0a) # should succeed +i2c.mem_write(1, 76, 0x0A) # should succeed diff --git a/tests/pyb/irq.py b/tests/pyb/irq.py index 42d276568e..04e70a7b79 100644 --- a/tests/pyb/irq.py +++ b/tests/pyb/irq.py @@ -1,10 +1,11 @@ import pyb + def test_irq(): # test basic disable/enable i1 = pyb.disable_irq() print(i1) - pyb.enable_irq() # by default should enable IRQ + pyb.enable_irq() # by default should enable IRQ # check that interrupts are enabled by waiting for ticks pyb.delay(10) @@ -19,4 +20,5 @@ def test_irq(): # check that interrupts are enabled by waiting for ticks pyb.delay(10) + test_irq() diff --git a/tests/pyb/modtime.py b/tests/pyb/modtime.py index d45440a63c..1f5b5f32fe 100644 --- a/tests/pyb/modtime.py +++ b/tests/pyb/modtime.py @@ -2,12 +2,14 @@ import time DAYS_PER_MONTH = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] + def is_leap(year): return (year % 4) == 0 + def test(): seconds = 0 - wday = 5 # Jan 1, 2000 was a Saturday + wday = 5 # Jan 1, 2000 was a Saturday for year in range(2000, 2034): print("Testing %d" % year) yday = 1 @@ -19,41 +21,56 @@ def test(): for day in range(1, DAYS_PER_MONTH[month] + 1): secs = time.mktime((year, month, day, 0, 0, 0, 0, 0)) if secs != seconds: - print("mktime failed for %d-%02d-%02d got %d expected %d" % (year, month, day, secs, seconds)) + print( + "mktime failed for %d-%02d-%02d got %d expected %d" + % (year, month, day, secs, seconds) + ) tuple = time.localtime(seconds) secs = time.mktime(tuple) if secs != seconds: - print("localtime failed for %d-%02d-%02d got %d expected %d" % (year, month, day, secs, seconds)) + print( + "localtime failed for %d-%02d-%02d got %d expected %d" + % (year, month, day, secs, seconds) + ) return seconds += 86400 if yday != tuple[7]: - print("locatime for %d-%02d-%02d got yday %d, expecting %d" % (year, month, day, tuple[7], yday)) + print( + "locatime for %d-%02d-%02d got yday %d, expecting %d" + % (year, month, day, tuple[7], yday) + ) return if wday != tuple[6]: - print("locatime for %d-%02d-%02d got wday %d, expecting %d" % (year, month, day, tuple[6], wday)) + print( + "locatime for %d-%02d-%02d got wday %d, expecting %d" + % (year, month, day, tuple[6], wday) + ) return yday += 1 wday = (wday + 1) % 7 + def spot_test(seconds, expected_time): actual_time = time.localtime(seconds) for i in range(len(actual_time)): if actual_time[i] != expected_time[i]: - print("time.localtime(", seconds, ") returned", actual_time, "expecting", expected_time) + print( + "time.localtime(", seconds, ") returned", actual_time, "expecting", expected_time + ) return print("time.localtime(", seconds, ") returned", actual_time, "(pass)") test() -spot_test( 0, (2000, 1, 1, 0, 0, 0, 5, 1)) -spot_test( 1, (2000, 1, 1, 0, 0, 1, 5, 1)) -spot_test( 59, (2000, 1, 1, 0, 0, 59, 5, 1)) -spot_test( 60, (2000, 1, 1, 0, 1, 0, 5, 1)) -spot_test( 3599, (2000, 1, 1, 0, 59, 59, 5, 1)) -spot_test( 3600, (2000, 1, 1, 1, 0, 0, 5, 1)) -spot_test( -1, (1999, 12, 31, 23, 59, 59, 4, 365)) -spot_test( 447549467, (2014, 3, 7, 23, 17, 47, 4, 66)) -spot_test( -940984933, (1970, 3, 7, 23, 17, 47, 5, 66)) -spot_test(-1072915199, (1966, 1, 1, 0, 0, 1, 5, 1)) -spot_test(-1072915200, (1966, 1, 1, 0, 0, 0, 5, 1)) -spot_test(-1072915201, (1965, 12, 31, 23, 59, 59, 4, 365)) +spot_test(0, (2000, 1, 1, 0, 0, 0, 5, 1)) +spot_test(1, (2000, 1, 1, 0, 0, 1, 5, 1)) +spot_test(59, (2000, 1, 1, 0, 0, 59, 5, 1)) +spot_test(60, (2000, 1, 1, 0, 1, 0, 5, 1)) +spot_test(3599, (2000, 1, 1, 0, 59, 59, 5, 1)) +spot_test(3600, (2000, 1, 1, 1, 0, 0, 5, 1)) +spot_test(-1, (1999, 12, 31, 23, 59, 59, 4, 365)) +spot_test(447549467, (2014, 3, 7, 23, 17, 47, 4, 66)) +spot_test(-940984933, (1970, 3, 7, 23, 17, 47, 5, 66)) +spot_test(-1072915199, (1966, 1, 1, 0, 0, 1, 5, 1)) +spot_test(-1072915200, (1966, 1, 1, 0, 0, 0, 5, 1)) +spot_test(-1072915201, (1965, 12, 31, 23, 59, 59, 4, 365)) diff --git a/tests/pyb/pin.py b/tests/pyb/pin.py index 9b37883438..c5a4443321 100644 --- a/tests/pyb/pin.py +++ b/tests/pyb/pin.py @@ -1,14 +1,14 @@ from pyb import Pin -p = Pin('Y1', Pin.IN) +p = Pin("Y1", Pin.IN) print(p) print(p.name()) print(p.pin()) print(p.port()) -p = Pin('Y1', Pin.IN, Pin.PULL_UP) -p = Pin('Y1', Pin.IN, pull=Pin.PULL_UP) -p = Pin('Y1', mode=Pin.IN, pull=Pin.PULL_UP) +p = Pin("Y1", Pin.IN, Pin.PULL_UP) +p = Pin("Y1", Pin.IN, pull=Pin.PULL_UP) +p = Pin("Y1", mode=Pin.IN, pull=Pin.PULL_UP) print(p) print(p.value()) diff --git a/tests/pyb/pyb1.py b/tests/pyb/pyb1.py index 443722ca85..e9626ecf4e 100644 --- a/tests/pyb/pyb1.py +++ b/tests/pyb/pyb1.py @@ -10,7 +10,7 @@ pyb.delay(1) start = pyb.millis() pyb.delay(17) -print((pyb.millis() - start) // 5) # should print 3 +print((pyb.millis() - start) // 5) # should print 3 # test udelay @@ -20,7 +20,7 @@ pyb.udelay(1) start = pyb.millis() pyb.udelay(17000) -print((pyb.millis() - start) // 5) # should print 3 +print((pyb.millis() - start) // 5) # should print 3 # other diff --git a/tests/pyb/pyb_f405.py b/tests/pyb/pyb_f405.py index 2f161ae099..6ca943dcea 100644 --- a/tests/pyb/pyb_f405.py +++ b/tests/pyb/pyb_f405.py @@ -2,8 +2,8 @@ import os, pyb -if not 'STM32F405' in os.uname().machine: - print('SKIP') +if not "STM32F405" in os.uname().machine: + print("SKIP") raise SystemExit print(pyb.freq()) diff --git a/tests/pyb/pyb_f411.py b/tests/pyb/pyb_f411.py index 50de302823..58d5fa2d41 100644 --- a/tests/pyb/pyb_f411.py +++ b/tests/pyb/pyb_f411.py @@ -2,8 +2,8 @@ import os, pyb -if not 'STM32F411' in os.uname().machine: - print('SKIP') +if not "STM32F411" in os.uname().machine: + print("SKIP") raise SystemExit print(pyb.freq()) diff --git a/tests/pyb/rtc.py b/tests/pyb/rtc.py index 844526b4b9..41b52f260d 100644 --- a/tests/pyb/rtc.py +++ b/tests/pyb/rtc.py @@ -10,10 +10,12 @@ rtc.datetime((2014, 1, 1, 1, 0, 0, 0, 0)) pyb.delay(1002) print(rtc.datetime()[:7]) + def set_and_print(datetime): rtc.datetime(datetime) print(rtc.datetime()[:7]) + # make sure that setting works correctly set_and_print((2000, 1, 1, 1, 0, 0, 0, 0)) set_and_print((2000, 1, 31, 1, 0, 0, 0, 0)) @@ -34,10 +36,12 @@ set_and_print((2099, 12, 31, 7, 23, 59, 59, 0)) # save existing calibration value: cal_tmp = rtc.calibration() + def set_and_print_calib(cal): rtc.calibration(cal) print(rtc.calibration()) + set_and_print_calib(512) set_and_print_calib(511) set_and_print_calib(345) @@ -56,12 +60,13 @@ def set_and_print_wakeup(ms): try: rtc.wakeup(ms) wucksel = stm.mem32[stm.RTC + stm.RTC_CR] & 7 - wut = stm.mem32[stm.RTC + stm.RTC_WUTR] & 0xffff + wut = stm.mem32[stm.RTC + stm.RTC_WUTR] & 0xFFFF except ValueError: wucksel = -1 wut = -1 print((wucksel, wut)) + set_and_print_wakeup(0) set_and_print_wakeup(1) set_and_print_wakeup(4000) @@ -72,8 +77,8 @@ set_and_print_wakeup(16000) set_and_print_wakeup(16001) set_and_print_wakeup(32000) set_and_print_wakeup(32001) -set_and_print_wakeup(0x10000*1000) -set_and_print_wakeup(0x10001*1000) -set_and_print_wakeup(0x1ffff*1000) -set_and_print_wakeup(0x20000*1000) -set_and_print_wakeup(0x20001*1000) # exception +set_and_print_wakeup(0x10000 * 1000) +set_and_print_wakeup(0x10001 * 1000) +set_and_print_wakeup(0x1FFFF * 1000) +set_and_print_wakeup(0x20000 * 1000) +set_and_print_wakeup(0x20001 * 1000) # exception diff --git a/tests/pyb/timer_callback.py b/tests/pyb/timer_callback.py index 864dd479ed..51242fba4b 100644 --- a/tests/pyb/timer_callback.py +++ b/tests/pyb/timer_callback.py @@ -8,19 +8,24 @@ def cb1(t): print("cb1") t.callback(None) + # callback function that disables the timer when called def cb2(t): print("cb2") t.deinit() + # callback where cb4 closes over cb3.y def cb3(x): y = x + def cb4(t): print("cb4", y) t.callback(None) + return cb4 + # create a timer with a callback, using callback(None) to stop tim = Timer(1, freq=100, callback=cb1) pyb.delay(5) diff --git a/tests/pyb/uart.py b/tests/pyb/uart.py index 836b073a6d..320d0af0d9 100644 --- a/tests/pyb/uart.py +++ b/tests/pyb/uart.py @@ -17,8 +17,8 @@ uart.init(2400) print(uart) print(uart.any()) -print(uart.write('123')) -print(uart.write(b'abcd')) +print(uart.write("123")) +print(uart.write(b"abcd")) print(uart.writechar(1)) # make sure this method exists @@ -26,8 +26,8 @@ uart.sendbreak() # non-blocking mode uart = UART(1, 9600, timeout=0) -print(uart.write(b'1')) -print(uart.write(b'abcd')) +print(uart.write(b"1")) +print(uart.write(b"abcd")) print(uart.writechar(1)) print(uart.read(100)) diff --git a/tests/pybnative/for.py b/tests/pybnative/for.py index 309c6c14fd..50177a9ba4 100644 --- a/tests/pybnative/for.py +++ b/tests/pybnative/for.py @@ -1,15 +1,19 @@ import pyb + @micropython.native def f1(n): for i in range(n): print(i) + f1(4) + @micropython.native def f2(r): for i in r: print(i) + f2(range(4)) diff --git a/tests/pybnative/while.py b/tests/pybnative/while.py index 3ea7221ea7..0f397dd377 100644 --- a/tests/pybnative/while.py +++ b/tests/pybnative/while.py @@ -1,5 +1,6 @@ import pyb + @micropython.native def f(led, n, d): led.off() @@ -11,5 +12,6 @@ def f(led, n, d): i += 1 led.off() + f(pyb.LED(1), 2, 150) f(pyb.LED(2), 4, 50) diff --git a/tests/stress/dict_copy.py b/tests/stress/dict_copy.py index 36db9bb7e8..73d3a5b51d 100644 --- a/tests/stress/dict_copy.py +++ b/tests/stress/dict_copy.py @@ -1,6 +1,6 @@ # copying a large dictionary -a = {i:2*i for i in range(1000)} +a = {i: 2 * i for i in range(1000)} b = a.copy() for i in range(1000): print(i, b[i]) diff --git a/tests/stress/gc_trace.py b/tests/stress/gc_trace.py index 72dc7b6276..f952ad36a6 100644 --- a/tests/stress/gc_trace.py +++ b/tests/stress/gc_trace.py @@ -12,6 +12,8 @@ gc.collect() print(lst) # test a deep object -lst = [[[[[(i, j, k, l)] for i in range(3)] for j in range(3)] for k in range(3)] for l in range(3)] +lst = [ + [[[[(i, j, k, l)] for i in range(3)] for j in range(3)] for k in range(3)] for l in range(3) +] gc.collect() print(lst) diff --git a/tests/stress/recursion.py b/tests/stress/recursion.py index 227f48396a..c2d831bb82 100644 --- a/tests/stress/recursion.py +++ b/tests/stress/recursion.py @@ -1,6 +1,7 @@ def foo(): foo() + try: foo() except RuntimeError: diff --git a/tests/stress/recursive_gen.py b/tests/stress/recursive_gen.py index 0e0d3914ee..8c21397658 100644 --- a/tests/stress/recursive_gen.py +++ b/tests/stress/recursive_gen.py @@ -3,16 +3,20 @@ # simple "yield from" recursion def gen(): yield from gen() + + try: list(gen()) except RuntimeError: - print('RuntimeError') + print("RuntimeError") # recursion via an iterator over a generator def gen2(): for x in gen2(): yield x + + try: next(gen2()) except RuntimeError: - print('RuntimeError') + print("RuntimeError") diff --git a/tests/thread/mutate_bytearray.py b/tests/thread/mutate_bytearray.py index f3276f1b2d..67c01d91cf 100644 --- a/tests/thread/mutate_bytearray.py +++ b/tests/thread/mutate_bytearray.py @@ -23,10 +23,11 @@ def th(n, lo, hi): global n_finished n_finished += 1 + lock = _thread.allocate_lock() n_thread = 4 n_finished = 0 -n_repeat = 4 # use 40 for more stressful test (uses more heap) +n_repeat = 4 # use 40 for more stressful test (uses more heap) # spawn threads for i in range(n_thread): @@ -42,4 +43,3 @@ count = [0 for _ in range(256)] for b in ba: count[b] += 1 print(count) - diff --git a/tests/thread/mutate_dict.py b/tests/thread/mutate_dict.py index c57d332d51..89c93f4eee 100644 --- a/tests/thread/mutate_dict.py +++ b/tests/thread/mutate_dict.py @@ -5,7 +5,7 @@ import _thread # the shared dict -di = {'a':'A', 'b':'B', 'c':'C', 'd':'D'} +di = {"a": "A", "b": "B", "c": "C", "d": "D"} # main thread function def th(n, lo, hi): @@ -26,6 +26,7 @@ def th(n, lo, hi): global n_finished n_finished += 1 + lock = _thread.allocate_lock() n_thread = 4 n_finished = 0 diff --git a/tests/thread/mutate_instance.py b/tests/thread/mutate_instance.py index a1ae428b54..939a0b8acd 100644 --- a/tests/thread/mutate_instance.py +++ b/tests/thread/mutate_instance.py @@ -7,25 +7,28 @@ import _thread # the shared user class and instance class User: def __init__(self): - self.a = 'A' - self.b = 'B' - self.c = 'C' + self.a = "A" + self.b = "B" + self.c = "C" + + user = User() # main thread function def th(n, lo, hi): for repeat in range(n): for i in range(lo, hi): - setattr(user, 'attr_%u' % i, repeat + i) - assert getattr(user, 'attr_%u' % i) == repeat + i + setattr(user, "attr_%u" % i, repeat + i) + assert getattr(user, "attr_%u" % i) == repeat + i with lock: global n_finished n_finished += 1 + lock = _thread.allocate_lock() n_repeat = 30 -n_range = 50 # 300 for stressful test (uses more heap) +n_range = 50 # 300 for stressful test (uses more heap) n_thread = 4 n_finished = 0 @@ -40,4 +43,4 @@ while n_finished < n_thread: # check user instance has correct contents print(user.a, user.b, user.c) for i in range(n_thread * n_range): - assert getattr(user, 'attr_%u' % i) == n_repeat - 1 + i + assert getattr(user, "attr_%u" % i) == n_repeat - 1 + i diff --git a/tests/thread/mutate_list.py b/tests/thread/mutate_list.py index 764a9bd99e..c1849e6729 100644 --- a/tests/thread/mutate_list.py +++ b/tests/thread/mutate_list.py @@ -27,6 +27,7 @@ def th(n, lo, hi): global n_finished n_finished += 1 + lock = _thread.allocate_lock() n_thread = 4 n_finished = 0 diff --git a/tests/thread/mutate_set.py b/tests/thread/mutate_set.py index 5492d86313..924124611b 100644 --- a/tests/thread/mutate_set.py +++ b/tests/thread/mutate_set.py @@ -21,6 +21,7 @@ def th(n, lo, hi): global n_finished n_finished += 1 + lock = _thread.allocate_lock() n_thread = 4 n_finished = 0 diff --git a/tests/thread/stress_aes.py b/tests/thread/stress_aes.py index df75e616c6..f3abc06ecf 100644 --- a/tests/thread/stress_aes.py +++ b/tests/thread/stress_aes.py @@ -17,49 +17,295 @@ # discrete arithmetic routines, mostly from a precomputed table # non-linear, invertible, substitution box -aes_s_box_table = bytes(( - 0x63,0x7c,0x77,0x7b,0xf2,0x6b,0x6f,0xc5,0x30,0x01,0x67,0x2b,0xfe,0xd7,0xab,0x76, - 0xca,0x82,0xc9,0x7d,0xfa,0x59,0x47,0xf0,0xad,0xd4,0xa2,0xaf,0x9c,0xa4,0x72,0xc0, - 0xb7,0xfd,0x93,0x26,0x36,0x3f,0xf7,0xcc,0x34,0xa5,0xe5,0xf1,0x71,0xd8,0x31,0x15, - 0x04,0xc7,0x23,0xc3,0x18,0x96,0x05,0x9a,0x07,0x12,0x80,0xe2,0xeb,0x27,0xb2,0x75, - 0x09,0x83,0x2c,0x1a,0x1b,0x6e,0x5a,0xa0,0x52,0x3b,0xd6,0xb3,0x29,0xe3,0x2f,0x84, - 0x53,0xd1,0x00,0xed,0x20,0xfc,0xb1,0x5b,0x6a,0xcb,0xbe,0x39,0x4a,0x4c,0x58,0xcf, - 0xd0,0xef,0xaa,0xfb,0x43,0x4d,0x33,0x85,0x45,0xf9,0x02,0x7f,0x50,0x3c,0x9f,0xa8, - 0x51,0xa3,0x40,0x8f,0x92,0x9d,0x38,0xf5,0xbc,0xb6,0xda,0x21,0x10,0xff,0xf3,0xd2, - 0xcd,0x0c,0x13,0xec,0x5f,0x97,0x44,0x17,0xc4,0xa7,0x7e,0x3d,0x64,0x5d,0x19,0x73, - 0x60,0x81,0x4f,0xdc,0x22,0x2a,0x90,0x88,0x46,0xee,0xb8,0x14,0xde,0x5e,0x0b,0xdb, - 0xe0,0x32,0x3a,0x0a,0x49,0x06,0x24,0x5c,0xc2,0xd3,0xac,0x62,0x91,0x95,0xe4,0x79, - 0xe7,0xc8,0x37,0x6d,0x8d,0xd5,0x4e,0xa9,0x6c,0x56,0xf4,0xea,0x65,0x7a,0xae,0x08, - 0xba,0x78,0x25,0x2e,0x1c,0xa6,0xb4,0xc6,0xe8,0xdd,0x74,0x1f,0x4b,0xbd,0x8b,0x8a, - 0x70,0x3e,0xb5,0x66,0x48,0x03,0xf6,0x0e,0x61,0x35,0x57,0xb9,0x86,0xc1,0x1d,0x9e, - 0xe1,0xf8,0x98,0x11,0x69,0xd9,0x8e,0x94,0x9b,0x1e,0x87,0xe9,0xce,0x55,0x28,0xdf, - 0x8c,0xa1,0x89,0x0d,0xbf,0xe6,0x42,0x68,0x41,0x99,0x2d,0x0f,0xb0,0x54,0xbb,0x16, -)) +aes_s_box_table = bytes( + ( + 0x63, + 0x7C, + 0x77, + 0x7B, + 0xF2, + 0x6B, + 0x6F, + 0xC5, + 0x30, + 0x01, + 0x67, + 0x2B, + 0xFE, + 0xD7, + 0xAB, + 0x76, + 0xCA, + 0x82, + 0xC9, + 0x7D, + 0xFA, + 0x59, + 0x47, + 0xF0, + 0xAD, + 0xD4, + 0xA2, + 0xAF, + 0x9C, + 0xA4, + 0x72, + 0xC0, + 0xB7, + 0xFD, + 0x93, + 0x26, + 0x36, + 0x3F, + 0xF7, + 0xCC, + 0x34, + 0xA5, + 0xE5, + 0xF1, + 0x71, + 0xD8, + 0x31, + 0x15, + 0x04, + 0xC7, + 0x23, + 0xC3, + 0x18, + 0x96, + 0x05, + 0x9A, + 0x07, + 0x12, + 0x80, + 0xE2, + 0xEB, + 0x27, + 0xB2, + 0x75, + 0x09, + 0x83, + 0x2C, + 0x1A, + 0x1B, + 0x6E, + 0x5A, + 0xA0, + 0x52, + 0x3B, + 0xD6, + 0xB3, + 0x29, + 0xE3, + 0x2F, + 0x84, + 0x53, + 0xD1, + 0x00, + 0xED, + 0x20, + 0xFC, + 0xB1, + 0x5B, + 0x6A, + 0xCB, + 0xBE, + 0x39, + 0x4A, + 0x4C, + 0x58, + 0xCF, + 0xD0, + 0xEF, + 0xAA, + 0xFB, + 0x43, + 0x4D, + 0x33, + 0x85, + 0x45, + 0xF9, + 0x02, + 0x7F, + 0x50, + 0x3C, + 0x9F, + 0xA8, + 0x51, + 0xA3, + 0x40, + 0x8F, + 0x92, + 0x9D, + 0x38, + 0xF5, + 0xBC, + 0xB6, + 0xDA, + 0x21, + 0x10, + 0xFF, + 0xF3, + 0xD2, + 0xCD, + 0x0C, + 0x13, + 0xEC, + 0x5F, + 0x97, + 0x44, + 0x17, + 0xC4, + 0xA7, + 0x7E, + 0x3D, + 0x64, + 0x5D, + 0x19, + 0x73, + 0x60, + 0x81, + 0x4F, + 0xDC, + 0x22, + 0x2A, + 0x90, + 0x88, + 0x46, + 0xEE, + 0xB8, + 0x14, + 0xDE, + 0x5E, + 0x0B, + 0xDB, + 0xE0, + 0x32, + 0x3A, + 0x0A, + 0x49, + 0x06, + 0x24, + 0x5C, + 0xC2, + 0xD3, + 0xAC, + 0x62, + 0x91, + 0x95, + 0xE4, + 0x79, + 0xE7, + 0xC8, + 0x37, + 0x6D, + 0x8D, + 0xD5, + 0x4E, + 0xA9, + 0x6C, + 0x56, + 0xF4, + 0xEA, + 0x65, + 0x7A, + 0xAE, + 0x08, + 0xBA, + 0x78, + 0x25, + 0x2E, + 0x1C, + 0xA6, + 0xB4, + 0xC6, + 0xE8, + 0xDD, + 0x74, + 0x1F, + 0x4B, + 0xBD, + 0x8B, + 0x8A, + 0x70, + 0x3E, + 0xB5, + 0x66, + 0x48, + 0x03, + 0xF6, + 0x0E, + 0x61, + 0x35, + 0x57, + 0xB9, + 0x86, + 0xC1, + 0x1D, + 0x9E, + 0xE1, + 0xF8, + 0x98, + 0x11, + 0x69, + 0xD9, + 0x8E, + 0x94, + 0x9B, + 0x1E, + 0x87, + 0xE9, + 0xCE, + 0x55, + 0x28, + 0xDF, + 0x8C, + 0xA1, + 0x89, + 0x0D, + 0xBF, + 0xE6, + 0x42, + 0x68, + 0x41, + 0x99, + 0x2D, + 0x0F, + 0xB0, + 0x54, + 0xBB, + 0x16, + ) +) # multiplication of polynomials modulo x^8 + x^4 + x^3 + x + 1 = 0x11b def aes_gf8_mul_2(x): if x & 0x80: - return (x << 1) ^ 0x11b + return (x << 1) ^ 0x11B else: return x << 1 + def aes_gf8_mul_3(x): return x ^ aes_gf8_mul_2(x) + # non-linear, invertible, substitution box def aes_s_box(a): - return aes_s_box_table[a & 0xff] + return aes_s_box_table[a & 0xFF] + # return 0x02^(a-1) in GF(2^8) def aes_r_con(a): ans = 1 while a > 1: - ans <<= 1; + ans <<= 1 if ans & 0x100: - ans ^= 0x11b + ans ^= 0x11B a -= 1 return ans + ################################################################## # basic AES algorithm; see FIPS-197 # @@ -79,6 +325,7 @@ def aes_add_round_key(state, w): for i in range(16): state[i] ^= w[i] + # combined sub_bytes, shift_rows, mix_columns, add_round_key # all inputs must be size 16 def aes_sb_sr_mc_ark(state, w, w_idx, temp): @@ -88,7 +335,7 @@ def aes_sb_sr_mc_ark(state, w, w_idx, temp): x1 = aes_s_box_table[state[1 + ((i + 1) & 3) * 4]] x2 = aes_s_box_table[state[2 + ((i + 2) & 3) * 4]] x3 = aes_s_box_table[state[3 + ((i + 3) & 3) * 4]] - temp[temp_idx] = aes_gf8_mul_2(x0) ^ aes_gf8_mul_3(x1) ^ x2 ^ x3 ^ w[w_idx] + temp[temp_idx] = aes_gf8_mul_2(x0) ^ aes_gf8_mul_3(x1) ^ x2 ^ x3 ^ w[w_idx] temp[temp_idx + 1] = x0 ^ aes_gf8_mul_2(x1) ^ aes_gf8_mul_3(x2) ^ x3 ^ w[w_idx + 1] temp[temp_idx + 2] = x0 ^ x1 ^ aes_gf8_mul_2(x2) ^ aes_gf8_mul_3(x3) ^ w[w_idx + 2] temp[temp_idx + 3] = aes_gf8_mul_3(x0) ^ x1 ^ x2 ^ aes_gf8_mul_2(x3) ^ w[w_idx + 3] @@ -97,6 +344,7 @@ def aes_sb_sr_mc_ark(state, w, w_idx, temp): for i in range(16): state[i] = temp[i] + # combined sub_bytes, shift_rows, add_round_key # all inputs must be size 16 def aes_sb_sr_ark(state, w, w_idx, temp): @@ -106,7 +354,7 @@ def aes_sb_sr_ark(state, w, w_idx, temp): x1 = aes_s_box_table[state[1 + ((i + 1) & 3) * 4]] x2 = aes_s_box_table[state[2 + ((i + 2) & 3) * 4]] x3 = aes_s_box_table[state[3 + ((i + 3) & 3) * 4]] - temp[temp_idx] = x0 ^ w[w_idx] + temp[temp_idx] = x0 ^ w[w_idx] temp[temp_idx + 1] = x1 ^ w[w_idx + 1] temp[temp_idx + 2] = x2 ^ w[w_idx + 2] temp[temp_idx + 3] = x3 ^ w[w_idx + 3] @@ -115,6 +363,7 @@ def aes_sb_sr_ark(state, w, w_idx, temp): for i in range(16): state[i] = temp[i] + # take state as input and change it to the next state in the sequence # state and temp have size 16, w has size 16 * (Nr + 1), Nr >= 1 def aes_state(state, w, temp, nr): @@ -125,6 +374,7 @@ def aes_state(state, w, temp, nr): w_idx += 16 aes_sb_sr_ark(state, w, w_idx, temp) + # expand 'key' to 'w' for use with aes_state # key has size 4 * Nk, w has size 16 * (Nr + 1), temp has size 16 def aes_key_expansion(key, w, temp, nk, nr): @@ -148,9 +398,11 @@ def aes_key_expansion(key, w, temp, nk, nr): for j in range(4): w[w_idx + j] = w[w_idx + j - 4 * nk] ^ t[t_idx + j] + ################################################################## # simple use of AES algorithm, using output feedback (OFB) mode + class AES: def __init__(self, keysize): if keysize == 128: @@ -176,7 +428,7 @@ class AES: def set_iv(self, iv): for i in range(16): self.state[i] = iv[i] - self.state_pos = 16; + self.state_pos = 16 def get_some_state(self, n_needed): if self.state_pos >= 16: @@ -198,6 +450,7 @@ class AES: idx += ln self.state_pos += n + ################################################################## # test code @@ -207,6 +460,7 @@ except ImportError: import time import _thread + class LockedCounter: def __init__(self): self.lock = _thread.allocate_lock() @@ -217,8 +471,10 @@ class LockedCounter: self.value += val self.lock.release() + count = LockedCounter() + def thread_entry(): global count @@ -247,7 +503,8 @@ def thread_entry(): count.add(1) -if __name__ == '__main__': + +if __name__ == "__main__": n_thread = 20 for i in range(n_thread): _thread.start_new_thread(thread_entry, ()) diff --git a/tests/thread/stress_create.py b/tests/thread/stress_create.py index 2399746cca..eda768fa7b 100644 --- a/tests/thread/stress_create.py +++ b/tests/thread/stress_create.py @@ -6,9 +6,11 @@ except ImportError: import time import _thread + def thread_entry(n): pass + thread_num = 0 while thread_num < 500: try: @@ -19,4 +21,4 @@ while thread_num < 500: # wait for the last threads to terminate time.sleep(1) -print('done') +print("done") diff --git a/tests/thread/stress_heap.py b/tests/thread/stress_heap.py index 5482a9ac6f..2ad91ae147 100644 --- a/tests/thread/stress_heap.py +++ b/tests/thread/stress_heap.py @@ -9,9 +9,11 @@ except ImportError: import time import _thread + def last(l): return l[-1] + def thread_entry(n): # allocate a bytearray and fill it data = bytearray(i for i in range(256)) @@ -33,6 +35,7 @@ def thread_entry(n): global n_finished n_finished += 1 + lock = _thread.allocate_lock() n_thread = 10 n_finished = 0 diff --git a/tests/thread/stress_recurse.py b/tests/thread/stress_recurse.py index 68367c4dd7..73b3a40f33 100644 --- a/tests/thread/stress_recurse.py +++ b/tests/thread/stress_recurse.py @@ -4,17 +4,20 @@ import _thread + def foo(): foo() + def thread_entry(): try: foo() except RuntimeError: - print('RuntimeError') + print("RuntimeError") global finished finished = True + finished = False _thread.start_new_thread(thread_entry, ()) @@ -22,4 +25,4 @@ _thread.start_new_thread(thread_entry, ()) # busy wait for thread to finish while not finished: pass -print('done') +print("done") diff --git a/tests/thread/thread_exc1.py b/tests/thread/thread_exc1.py index 10fb94b4fb..16483d7778 100644 --- a/tests/thread/thread_exc1.py +++ b/tests/thread/thread_exc1.py @@ -4,9 +4,11 @@ import _thread + def foo(): raise ValueError + def thread_entry(): try: foo() @@ -16,6 +18,7 @@ def thread_entry(): global n_finished n_finished += 1 + lock = _thread.allocate_lock() n_thread = 4 n_finished = 0 @@ -27,4 +30,4 @@ for i in range(n_thread): # busy wait for threads to finish while n_finished < n_thread: pass -print('done') +print("done") diff --git a/tests/thread/thread_exc2.py b/tests/thread/thread_exc2.py index 35cb324412..2863e1dec1 100644 --- a/tests/thread/thread_exc2.py +++ b/tests/thread/thread_exc2.py @@ -2,9 +2,11 @@ import utime import _thread + def thread_entry(): raise ValueError + _thread.start_new_thread(thread_entry, ()) utime.sleep(1) -print('done') +print("done") diff --git a/tests/thread/thread_exit1.py b/tests/thread/thread_exit1.py index 88cdd165c7..c4a93c45a3 100644 --- a/tests/thread/thread_exit1.py +++ b/tests/thread/thread_exit1.py @@ -8,12 +8,14 @@ except ImportError: import time import _thread + def thread_entry(): _thread.exit() + _thread.start_new_thread(thread_entry, ()) _thread.start_new_thread(thread_entry, ()) # wait for threads to finish time.sleep(1) -print('done') +print("done") diff --git a/tests/thread/thread_exit2.py b/tests/thread/thread_exit2.py index 368a11bba4..0cd80e6909 100644 --- a/tests/thread/thread_exit2.py +++ b/tests/thread/thread_exit2.py @@ -8,12 +8,14 @@ except ImportError: import time import _thread + def thread_entry(): raise SystemExit + _thread.start_new_thread(thread_entry, ()) _thread.start_new_thread(thread_entry, ()) # wait for threads to finish time.sleep(1) -print('done') +print("done") diff --git a/tests/thread/thread_gc1.py b/tests/thread/thread_gc1.py index 8dcbf7e07a..dd1e64d894 100644 --- a/tests/thread/thread_gc1.py +++ b/tests/thread/thread_gc1.py @@ -5,6 +5,7 @@ import gc import _thread + def thread_entry(n): # allocate a bytearray and fill it data = bytearray(i for i in range(256)) @@ -21,6 +22,7 @@ def thread_entry(n): global n_finished n_finished += 1 + lock = _thread.allocate_lock() n_thread = 4 n_finished = 0 diff --git a/tests/thread/thread_ident1.py b/tests/thread/thread_ident1.py index 217fce73b1..390193accc 100644 --- a/tests/thread/thread_ident1.py +++ b/tests/thread/thread_ident1.py @@ -4,18 +4,20 @@ import _thread + def thread_entry(): tid = _thread.get_ident() - print('thread', type(tid) == int, tid != 0, tid != tid_main) + print("thread", type(tid) == int, tid != 0, tid != tid_main) global finished finished = True + tid_main = _thread.get_ident() -print('main', type(tid_main) == int, tid_main != 0) +print("main", type(tid_main) == int, tid_main != 0) finished = False _thread.start_new_thread(thread_entry, ()) while not finished: pass -print('done') +print("done") diff --git a/tests/thread/thread_lock1.py b/tests/thread/thread_lock1.py index ba5c7dff06..342c554f4a 100644 --- a/tests/thread/thread_lock1.py +++ b/tests/thread/thread_lock1.py @@ -36,11 +36,11 @@ try: print(lock.locked()) raise KeyError except KeyError: - print('KeyError') + print("KeyError") print(lock.locked()) # test that we can't release an unlocked lock try: lock.release() except RuntimeError: - print('RuntimeError') + print("RuntimeError") diff --git a/tests/thread/thread_lock2.py b/tests/thread/thread_lock2.py index 405f10b0b6..b842f69c93 100644 --- a/tests/thread/thread_lock2.py +++ b/tests/thread/thread_lock2.py @@ -10,15 +10,17 @@ import _thread lock = _thread.allocate_lock() + def thread_entry(): lock.acquire() - print('have it') + print("have it") lock.release() + # spawn the threads for i in range(4): _thread.start_new_thread(thread_entry, ()) # wait for threads to finish time.sleep(1) -print('done') +print("done") diff --git a/tests/thread/thread_lock3.py b/tests/thread/thread_lock3.py index 607898dad8..a927dc6829 100644 --- a/tests/thread/thread_lock3.py +++ b/tests/thread/thread_lock3.py @@ -8,16 +8,18 @@ lock = _thread.allocate_lock() n_thread = 10 n_finished = 0 + def thread_entry(idx): global n_finished while True: with lock: if n_finished == idx: break - print('my turn:', idx) + print("my turn:", idx) with lock: n_finished += 1 + # spawn threads for i in range(n_thread): _thread.start_new_thread(thread_entry, (i,)) diff --git a/tests/thread/thread_lock4.py b/tests/thread/thread_lock4.py index 2f9d42d6b5..bbf9043996 100644 --- a/tests/thread/thread_lock4.py +++ b/tests/thread/thread_lock4.py @@ -8,12 +8,14 @@ except ImportError: import time import _thread + def fac(n): x = 1 for i in range(1, n + 1): x *= i return x + def thread_entry(): while True: with jobs_lock: @@ -25,6 +27,7 @@ def thread_entry(): with output_lock: output.append((arg, ans)) + # create a list of jobs jobs = [(fac, i) for i in range(20, 80)] jobs_lock = _thread.allocate_lock() diff --git a/tests/thread/thread_qstr1.py b/tests/thread/thread_qstr1.py index f4136d9646..40ee2910cb 100644 --- a/tests/thread/thread_qstr1.py +++ b/tests/thread/thread_qstr1.py @@ -13,6 +13,7 @@ def check(s, val): assert type(s) == str assert int(s) == val + # main thread function def th(base, n): for i in range(n): @@ -23,10 +24,11 @@ def th(base, n): global n_finished n_finished += 1 + lock = _thread.allocate_lock() n_thread = 4 n_finished = 0 -n_qstr_per_thread = 100 # make 1000 for a more stressful test (uses more heap) +n_qstr_per_thread = 100 # make 1000 for a more stressful test (uses more heap) # spawn threads for i in range(n_thread): @@ -36,4 +38,4 @@ for i in range(n_thread): while n_finished < n_thread: time.sleep(1) -print('pass') +print("pass") diff --git a/tests/thread/thread_shared1.py b/tests/thread/thread_shared1.py index 13c6651cc4..582b01fc34 100644 --- a/tests/thread/thread_shared1.py +++ b/tests/thread/thread_shared1.py @@ -4,9 +4,11 @@ import _thread + def foo(i): pass + def thread_entry(n, tup): for i in tup: foo(i) @@ -14,6 +16,7 @@ def thread_entry(n, tup): global n_finished n_finished += 1 + lock = _thread.allocate_lock() n_thread = 2 n_finished = 0 diff --git a/tests/thread/thread_shared2.py b/tests/thread/thread_shared2.py index e4bfe78022..a1223c2b94 100644 --- a/tests/thread/thread_shared2.py +++ b/tests/thread/thread_shared2.py @@ -5,9 +5,11 @@ import _thread + def foo(lst, i): lst[i] += 1 + def thread_entry(n, lst, idx): for i in range(n): foo(lst, idx) @@ -15,6 +17,7 @@ def thread_entry(n, lst, idx): global n_finished n_finished += 1 + lock = _thread.allocate_lock() n_thread = 2 n_finished = 0 diff --git a/tests/thread/thread_sleep1.py b/tests/thread/thread_sleep1.py index 032ec17543..18fa4e05a1 100644 --- a/tests/thread/thread_sleep1.py +++ b/tests/thread/thread_sleep1.py @@ -4,9 +4,11 @@ try: import utime + sleep_ms = utime.sleep_ms except ImportError: import time + sleep_ms = lambda t: time.sleep(t / 1000) import _thread @@ -15,6 +17,7 @@ lock = _thread.allocate_lock() n_thread = 4 n_finished = 0 + def thread_entry(t): global n_finished sleep_ms(t) @@ -22,10 +25,11 @@ def thread_entry(t): with lock: n_finished += 1 + for i in range(n_thread): _thread.start_new_thread(thread_entry, (10 * i,)) # wait for threads to finish while n_finished < n_thread: sleep_ms(100) -print('done', n_thread) +print("done", n_thread) diff --git a/tests/thread/thread_stacksize1.py b/tests/thread/thread_stacksize1.py index 62b6e5e40d..39fe235b22 100644 --- a/tests/thread/thread_stacksize1.py +++ b/tests/thread/thread_stacksize1.py @@ -6,20 +6,23 @@ import sys import _thread # different implementations have different minimum sizes -if sys.implementation.name == 'micropython': +if sys.implementation.name == "micropython": sz = 2 * 1024 else: sz = 32 * 1024 + def foo(): pass + def thread_entry(): foo() with lock: global n_finished n_finished += 1 + # reset stack size to default _thread.stack_size() @@ -44,4 +47,4 @@ _thread.stack_size() # busy wait for threads to finish while n_finished < n_thread: pass -print('done') +print("done") diff --git a/tests/thread/thread_start1.py b/tests/thread/thread_start1.py index d23a74aa21..f0e696840e 100644 --- a/tests/thread/thread_start1.py +++ b/tests/thread/thread_start1.py @@ -8,16 +8,19 @@ except ImportError: import time import _thread + def foo(): pass + def thread_entry(n): for i in range(n): foo() + _thread.start_new_thread(thread_entry, (10,)) _thread.start_new_thread(thread_entry, (20,)) # wait for threads to finish time.sleep(1) -print('done') +print("done") diff --git a/tests/thread/thread_start2.py b/tests/thread/thread_start2.py index d0913e37cd..d68ea94329 100644 --- a/tests/thread/thread_start2.py +++ b/tests/thread/thread_start2.py @@ -8,11 +8,13 @@ except ImportError: import time import _thread + def thread_entry(a0, a1, a2, a3): - print('thread', a0, a1, a2, a3) + print("thread", a0, a1, a2, a3) + # spawn thread using kw args -_thread.start_new_thread(thread_entry, (10, 20), {'a2': 0, 'a3': 1}) +_thread.start_new_thread(thread_entry, (10, 20), {"a2": 0, "a3": 1}) # wait for thread to finish time.sleep(1) @@ -21,6 +23,6 @@ time.sleep(1) try: _thread.start_new_thread(thread_entry, (), ()) except TypeError: - print('TypeError') + print("TypeError") -print('done') +print("done") diff --git a/tests/unicode/file2.py b/tests/unicode/file2.py index 8c45f91faf..1a5b933c89 100644 --- a/tests/unicode/file2.py +++ b/tests/unicode/file2.py @@ -1,11 +1,12 @@ # test reading a given number of characters + def do(mode): - if mode == 'rb': + if mode == "rb": enc = None else: - enc = 'utf-8' - f = open('unicode/data/utf-8_2.txt', mode=mode, encoding=enc) + enc = "utf-8" + f = open("unicode/data/utf-8_2.txt", mode=mode, encoding=enc) print(f.read(1)) print(f.read(1)) print(f.read(2)) @@ -15,12 +16,13 @@ def do(mode): f.readline() # check 3-byte utf-8 char - print(f.read(1 if mode == 'rt' else 3)) + print(f.read(1 if mode == "rt" else 3)) # check 4-byte utf-8 char - print(f.read(1 if mode == 'rt' else 4)) + print(f.read(1 if mode == "rt" else 4)) f.close() -do('rb') -do('rt') + +do("rb") +do("rt") diff --git a/tests/unicode/unicode.py b/tests/unicode/unicode.py index b3d4b09eeb..072e049fde 100644 --- a/tests/unicode/unicode.py +++ b/tests/unicode/unicode.py @@ -1,17 +1,17 @@ # Test a UTF-8 encoded literal s = "asdf©qwer" for i in range(len(s)): - print("s[%d]: %s %X"%(i, s[i], ord(s[i]))) + print("s[%d]: %s %X" % (i, s[i], ord(s[i]))) # Test all three forms of Unicode escape, and # all blocks of UTF-8 byte patterns s = "a\xA9\xFF\u0123\u0800\uFFEE\U0001F44C" for i in range(-len(s), len(s)): - print("s[%d]: %s %X"%(i, s[i], ord(s[i]))) - print("s[:%d]: %d chars, '%s'"%(i, len(s[:i]), s[:i])) + print("s[%d]: %s %X" % (i, s[i], ord(s[i]))) + print("s[:%d]: %d chars, '%s'" % (i, len(s[:i]), s[:i])) for j in range(i, len(s)): - print("s[%d:%d]: %d chars, '%s'"%(i, j, len(s[i:j]), s[i:j])) - print("s[%d:]: %d chars, '%s'"%(i, len(s[i:]), s[i:])) + print("s[%d:%d]: %d chars, '%s'" % (i, j, len(s[i:j]), s[i:j])) + print("s[%d:]: %d chars, '%s'" % (i, len(s[i:]), s[i:])) # Test UTF-8 encode and decode enc = s.encode() @@ -19,35 +19,35 @@ print(enc, enc.decode() == s) # printing of unicode chars using repr # NOTE: for some characters (eg \u10ff) we differ to CPython -print(repr('a\uffff')) -print(repr('a\U0001ffff')) +print(repr("a\uffff")) +print(repr("a\U0001ffff")) # test invalid escape code try: eval('"\\U00110000"') except SyntaxError: - print('SyntaxError') + print("SyntaxError") # test unicode string given to int try: - int('\u0200') + int("\u0200") except ValueError: - print('ValueError') + print("ValueError") # test invalid UTF-8 string try: - str(b'ab\xa1', 'utf8') + str(b"ab\xa1", "utf8") except UnicodeError: - print('UnicodeError') + print("UnicodeError") try: - str(b'ab\xf8', 'utf8') + str(b"ab\xf8", "utf8") except UnicodeError: - print('UnicodeError') + print("UnicodeError") try: - str(bytearray(b'ab\xc0a'), 'utf8') + str(bytearray(b"ab\xc0a"), "utf8") except UnicodeError: - print('UnicodeError') + print("UnicodeError") try: - str(b'\xf0\xe0\xed\xe8', 'utf8') + str(b"\xf0\xe0\xed\xe8", "utf8") except UnicodeError: - print('UnicodeError') + print("UnicodeError") diff --git a/tests/unicode/unicode_id.py b/tests/unicode/unicode_id.py index 10f540c503..3a58e3f72b 100644 --- a/tests/unicode/unicode_id.py +++ b/tests/unicode/unicode_id.py @@ -14,14 +14,19 @@ print(α, αβγ, bβ, βb) def α(β, γ): δ = β + γ print(β, γ, δ) + + α(1, 2) # class, method identifiers class φ: def __init__(self): pass + def δ(self, ϵ): print(ϵ) + + zζzζz = φ() if hasattr(zζzζz, "δ"): zζzζz.δ(ϵ=123) diff --git a/tests/unicode/unicode_ord.py b/tests/unicode/unicode_ord.py index 47cfa1c2d7..73577050bf 100644 --- a/tests/unicode/unicode_ord.py +++ b/tests/unicode/unicode_ord.py @@ -1,3 +1,3 @@ # test builtin ord with unicode characters -print(ord('α')) +print(ord("α")) diff --git a/tests/unicode/unicode_str_format.py b/tests/unicode/unicode_str_format.py index bf8505a31a..1a60e7be4a 100644 --- a/tests/unicode/unicode_str_format.py +++ b/tests/unicode/unicode_str_format.py @@ -1,4 +1,4 @@ # test handling of unicode chars in format strings -print('α'.format()) -print('{α}'.format(α=1)) +print("α".format()) +print("{α}".format(α=1)) diff --git a/tests/unicode/unicode_str_modulo.py b/tests/unicode/unicode_str_modulo.py index e9b152473c..42211d0b05 100644 --- a/tests/unicode/unicode_str_modulo.py +++ b/tests/unicode/unicode_str_modulo.py @@ -1,3 +1,3 @@ # test handling of unicode chars in string % formatting -print('α' % ()) +print("α" % ()) diff --git a/tests/unicode/unicode_subscr.py b/tests/unicode/unicode_subscr.py index a2f434de58..5028910077 100644 --- a/tests/unicode/unicode_subscr.py +++ b/tests/unicode/unicode_subscr.py @@ -1,4 +1,4 @@ -a = '¢пр' +a = "¢пр" print(a[0], a[0:1]) print(a[1], a[1:2]) diff --git a/tests/unix/extra_coverage.py b/tests/unix/extra_coverage.py index 13721f1f47..e31eece774 100644 --- a/tests/unix/extra_coverage.py +++ b/tests/unix/extra_coverage.py @@ -13,33 +13,33 @@ data = extra_coverage() print(data[0], data[1]) print(hash(data[0])) print(hash(data[1])) -print(hash(bytes(data[0], 'utf8'))) -print(hash(str(data[1], 'utf8'))) +print(hash(bytes(data[0], "utf8"))) +print(hash(str(data[1], "utf8"))) # test streams -stream = data[2] # has set_error and set_buf. Write always returns error -stream.set_error(uerrno.EAGAIN) # non-blocking error -print(stream.read()) # read all encounters non-blocking error -print(stream.read(1)) # read 1 byte encounters non-blocking error -print(stream.readline()) # readline encounters non-blocking error -print(stream.readinto(bytearray(10))) # readinto encounters non-blocking error -print(stream.write(b'1')) # write encounters non-blocking error -print(stream.write1(b'1')) # write1 encounters non-blocking error -stream.set_buf(b'123') -print(stream.read(4)) # read encounters non-blocking error after successful reads -stream.set_buf(b'123') -print(stream.read1(4)) # read1 encounters non-blocking error after successful reads -stream.set_buf(b'123') -print(stream.readline(4)) # readline encounters non-blocking error after successful reads +stream = data[2] # has set_error and set_buf. Write always returns error +stream.set_error(uerrno.EAGAIN) # non-blocking error +print(stream.read()) # read all encounters non-blocking error +print(stream.read(1)) # read 1 byte encounters non-blocking error +print(stream.readline()) # readline encounters non-blocking error +print(stream.readinto(bytearray(10))) # readinto encounters non-blocking error +print(stream.write(b"1")) # write encounters non-blocking error +print(stream.write1(b"1")) # write1 encounters non-blocking error +stream.set_buf(b"123") +print(stream.read(4)) # read encounters non-blocking error after successful reads +stream.set_buf(b"123") +print(stream.read1(4)) # read1 encounters non-blocking error after successful reads +stream.set_buf(b"123") +print(stream.readline(4)) # readline encounters non-blocking error after successful reads try: - print(stream.ioctl(0, 0)) # ioctl encounters non-blocking error; raises OSError + print(stream.ioctl(0, 0)) # ioctl encounters non-blocking error; raises OSError except OSError: - print('OSError') + print("OSError") stream.set_error(0) -print(stream.ioctl(0, bytearray(10))) # successful ioctl call +print(stream.ioctl(0, bytearray(10))) # successful ioctl call -stream2 = data[3] # is textio -print(stream2.read(1)) # read 1 byte encounters non-blocking error with textio stream +stream2 = data[3] # is textio +print(stream2.read(1)) # read 1 byte encounters non-blocking error with textio stream # test BufferedWriter with stream errors stream.set_error(uerrno.EAGAIN) @@ -52,23 +52,28 @@ import frzmpy1 # test import of frozen packages with __init__.py import frzstr_pkg1 + print(frzstr_pkg1.x) import frzmpy_pkg1 + print(frzmpy_pkg1.x) # test import of frozen packages without __init__.py from frzstr_pkg2.mod import Foo + print(Foo.x) from frzmpy_pkg2.mod import Foo + print(Foo.x) # test raising exception in frozen script try: import frzmpy2 except ZeroDivisionError: - print('ZeroDivisionError') + print("ZeroDivisionError") # test loading a resource from a frozen string import uio -buf = uio.resource_stream('frzstr_pkg2', 'mod.py') + +buf = uio.resource_stream("frzstr_pkg2", "mod.py") print(buf.read(21)) diff --git a/tests/unix/ffi_callback.py b/tests/unix/ffi_callback.py index 23b058bcec..21bfccf251 100644 --- a/tests/unix/ffi_callback.py +++ b/tests/unix/ffi_callback.py @@ -15,16 +15,19 @@ def ffi_open(names): err = e raise err -libc = ffi_open(('libc.so', 'libc.so.0', 'libc.so.6', 'libc.dylib')) + +libc = ffi_open(("libc.so", "libc.so.0", "libc.so.6", "libc.dylib")) qsort = libc.func("v", "qsort", "piip") + def cmp(pa, pb): a = ffi.as_bytearray(pa, 1) b = ffi.as_bytearray(pb, 1) - #print("cmp:", a, b) + # print("cmp:", a, b) return a[0] - b[0] + cmp_c = ffi.callback("i", cmp, "pp") s = bytearray(b"foobar") diff --git a/tests/unix/ffi_float.py b/tests/unix/ffi_float.py index 317436855b..d039398965 100644 --- a/tests/unix/ffi_float.py +++ b/tests/unix/ffi_float.py @@ -16,7 +16,8 @@ def ffi_open(names): err = e raise err -libc = ffi_open(('libc.so', 'libc.so.0', 'libc.so.6', 'libc.dylib')) + +libc = ffi_open(("libc.so", "libc.so.0", "libc.so.6", "libc.dylib")) try: strtof = libc.func("f", "strtof", "sp") @@ -26,14 +27,14 @@ except OSError: print("SKIP") raise SystemExit -print('%.6f' % strtof('1.23', None)) +print("%.6f" % strtof("1.23", None)) strtod = libc.func("d", "strtod", "sp") -print('%.6f' % strtod('1.23', None)) +print("%.6f" % strtod("1.23", None)) # test passing double and float args -libm = ffi_open(('libm.so', 'libm.so.6', 'libc.so.0', 'libc.so.6', 'libc.dylib')) -tgamma = libm.func('d', 'tgamma', 'd') +libm = ffi_open(("libm.so", "libm.so.6", "libc.so.0", "libc.so.6", "libc.dylib")) +tgamma = libm.func("d", "tgamma", "d") for fun in (tgamma,): for val in (0.5, 1, 1.0, 1.5, 4, 4.0): - print('%.6f' % fun(val)) + print("%.6f" % fun(val)) diff --git a/tests/unix/ffi_float2.py b/tests/unix/ffi_float2.py index 721eb4d192..bbed696662 100644 --- a/tests/unix/ffi_float2.py +++ b/tests/unix/ffi_float2.py @@ -16,16 +16,17 @@ def ffi_open(names): err = e raise err -libm = ffi_open(('libm.so', 'libm.so.6', 'libc.so.0', 'libc.so.6', 'libc.dylib')) + +libm = ffi_open(("libm.so", "libm.so.6", "libc.so.0", "libc.so.6", "libc.dylib")) # Some libc's implement tgammaf as header macro with tgamma(), so don't assume # it'll be in library. try: - tgammaf = libm.func('f', 'tgammaf', 'f') + tgammaf = libm.func("f", "tgammaf", "f") except OSError: print("SKIP") raise SystemExit for fun in (tgammaf,): for val in (0.5, 1, 1.0, 1.5, 4, 4.0): - print('%.6f' % fun(val)) + print("%.6f" % fun(val)) diff --git a/tests/wipy/adc.py b/tests/wipy/adc.py index 6fd4373dbd..73264113f3 100644 --- a/tests/wipy/adc.py +++ b/tests/wipy/adc.py @@ -1,19 +1,19 @@ -''' +""" ADC test for the CC3200 based boards. -''' +""" from machine import ADC import os mch = os.uname().machine -if 'LaunchPad' in mch: - adc_pin = 'GP5' +if "LaunchPad" in mch: + adc_pin = "GP5" adc_channel = 3 -elif 'WiPy' in mch: - adc_pin = 'GP3' +elif "WiPy" in mch: + adc_pin = "GP3" adc_channel = 1 else: - raise Exception('Board not supported!') + raise Exception("Board not supported!") adc = ADC(0) print(adc) @@ -49,7 +49,7 @@ print(apin) print(apin() > 3000) # check for memory leaks... -for i in range (0, 1000): +for i in range(0, 1000): adc = ADC() apin = adc.channel(adc_channel) @@ -57,56 +57,56 @@ for i in range (0, 1000): try: adc = ADC(bits=17) except: - print('Exception') + print("Exception") try: adc = ADC(id=1) except: - print('Exception') + print("Exception") try: adc = ADC(0, 16) except: - print('Exception') + print("Exception") adc = ADC() try: apin = adc.channel(4) except: - print('Exception') + print("Exception") try: apin = adc.channel(-1) except: - print('Exception') + print("Exception") try: - apin = adc.channel(0, pin='GP3') + apin = adc.channel(0, pin="GP3") except: - print('Exception') + print("Exception") apin = adc.channel(1) apin.deinit() try: apin() except: - print('Exception') + print("Exception") try: apin.value() except: - print('Exception') + print("Exception") adc.deinit() try: apin.value() except: - print('Exception') + print("Exception") try: apin = adc.channel(1) except: - print('Exception') + print("Exception") # re-init must work adc.init() diff --git a/tests/wipy/i2c.py b/tests/wipy/i2c.py index 6931554191..c7d32f6639 100644 --- a/tests/wipy/i2c.py +++ b/tests/wipy/i2c.py @@ -1,19 +1,19 @@ -''' +""" I2C test for the CC3200 based boards. A MPU-9150 sensor must be connected to the I2C bus. -''' +""" from machine import I2C import os import time mch = os.uname().machine -if 'LaunchPad' in mch: - i2c_pins = ('GP11', 'GP10') -elif 'WiPy' in mch: - i2c_pins = ('GP15', 'GP10') +if "LaunchPad" in mch: + i2c_pins = ("GP11", "GP10") +elif "WiPy" in mch: + i2c_pins = ("GP15", "GP10") else: - raise Exception('Board not supported!') + raise Exception("Board not supported!") i2c = I2C(0, I2C.MASTER, baudrate=400000) # try initing without the peripheral id @@ -41,26 +41,26 @@ reg[0] |= 0x80 print(1 == i2c.writeto_mem(addr, 107, reg)) time.sleep_ms(100) # wait for the sensor to reset... -print(1 == i2c.readfrom_mem_into(addr, 107, reg)) # read the power management register 1 +print(1 == i2c.readfrom_mem_into(addr, 107, reg)) # read the power management register 1 print(0x40 == reg[0]) # now just read one byte -data = i2c.readfrom_mem(addr, 117, 1) # read the "who am I?" register +data = i2c.readfrom_mem(addr, 117, 1) # read the "who am I?" register print(0x68 == data[0]) print(len(data) == 1) -print(1 == i2c.readfrom_mem_into(addr, 117, reg)) # read the "who am I?" register again +print(1 == i2c.readfrom_mem_into(addr, 117, reg)) # read the "who am I?" register again print(0x68 == reg[0]) # now try reading two bytes -data = i2c.readfrom_mem(addr, 116, 2) # read the "who am I?" register +data = i2c.readfrom_mem(addr, 116, 2) # read the "who am I?" register print(0x68 == data[1]) -print(data == b'\x00\x68') +print(data == b"\x00\x68") print(len(data) == 2) -print(2 == i2c.readfrom_mem_into(addr, 116, reg2)) # read the "who am I?" register again +print(2 == i2c.readfrom_mem_into(addr, 116, reg2)) # read the "who am I?" register again print(0x68 == reg2[1]) -print(reg2 == b'\x00\x68') +print(reg2 == b"\x00\x68") -print(1 == i2c.readfrom_mem_into(addr, 107, reg)) # read the power management register 1 +print(1 == i2c.readfrom_mem_into(addr, 107, reg)) # read the power management register 1 print(0x40 == reg[0]) # clear the sleep bit reg[0] = 0 @@ -100,13 +100,13 @@ print(1 == i2c.writeto_mem(addr, 107, reg)) time.sleep_ms(100) # wait for the sensor to reset... # try some raw read and writes -reg[0] = 117 # register address -print(1 == i2c.writeto(addr, reg, stop=False)) # just write the register address +reg[0] = 117 # register address +print(1 == i2c.writeto(addr, reg, stop=False)) # just write the register address # now read print(1 == i2c.readfrom_into(addr, reg)) print(reg[0] == 0x68) -reg[0] = 117 # register address -print(1 == i2c.writeto(addr, reg, stop=False)) # just write the register address +reg[0] = 117 # register address +print(1 == i2c.writeto(addr, reg, stop=False)) # just write the register address # now read print(0x68 == i2c.readfrom(addr, 1)[0]) @@ -114,14 +114,14 @@ i2c.readfrom_mem_into(addr, 107, reg2) print(0x40 == reg2[0]) print(0x00 == reg2[1]) -reg2[0] = 107 # register address +reg2[0] = 107 # register address reg2[1] = 0 -print(2 == i2c.writeto(addr, reg2, stop=True)) # write the register address and the data -i2c.readfrom_mem_into(addr, 107, reg) # check it back +print(2 == i2c.writeto(addr, reg2, stop=True)) # write the register address and the data +i2c.readfrom_mem_into(addr, 107, reg) # check it back print(reg[0] == 0) # check for memory leaks... -for i in range (0, 1000): +for i in range(0, 1000): i2c = I2C(0, I2C.MASTER, baudrate=100000) # test deinit @@ -173,4 +173,3 @@ except Exception: # reinitialization must work i2c.init(baudrate=400000) print(i2c) - diff --git a/tests/wipy/modwipy.py b/tests/wipy/modwipy.py index 7571af0753..59df3ae90a 100644 --- a/tests/wipy/modwipy.py +++ b/tests/wipy/modwipy.py @@ -1,13 +1,13 @@ -''' +""" wipy module test for the CC3200 based boards -''' +""" import os import wipy mch = os.uname().machine -if not 'LaunchPad' in mch and not'WiPy' in mch: - raise Exception('Board not supported!') +if not "LaunchPad" in mch and not "WiPy" in mch: + raise Exception("Board not supported!") print(wipy.heartbeat() == True) wipy.heartbeat(False) @@ -18,4 +18,4 @@ print(wipy.heartbeat() == True) try: wipy.heartbeat(True, 1) except: - print('Exception') + print("Exception") diff --git a/tests/wipy/os.py b/tests/wipy/os.py index 0596a16b52..1f4debcade 100644 --- a/tests/wipy/os.py +++ b/tests/wipy/os.py @@ -1,164 +1,164 @@ -''' +""" os module test for the CC3200 based boards -''' +""" from machine import SD import os mch = os.uname().machine -if 'LaunchPad' in mch: - sd_pins = ('GP16', 'GP17', 'GP15') -elif 'WiPy' in mch: - sd_pins = ('GP10', 'GP11', 'GP15') +if "LaunchPad" in mch: + sd_pins = ("GP16", "GP17", "GP15") +elif "WiPy" in mch: + sd_pins = ("GP10", "GP11", "GP15") else: - raise Exception('Board not supported!') + raise Exception("Board not supported!") sd = SD(pins=sd_pins) -os.mount(sd, '/sd') -os.mkfs('/sd') -os.chdir('/flash') +os.mount(sd, "/sd") +os.mkfs("/sd") +os.chdir("/flash") print(os.listdir()) -os.chdir('/sd') +os.chdir("/sd") print(os.listdir()) # create a test directory in flash -os.mkdir('/flash/test') -os.chdir('/flash/test') +os.mkdir("/flash/test") +os.chdir("/flash/test") print(os.getcwd()) -os.chdir('..') +os.chdir("..") print(os.getcwd()) -os.chdir('test') +os.chdir("test") print(os.getcwd()) # create a new file -f = open('test.txt', 'w') +f = open("test.txt", "w") test_bytes = os.urandom(1024) n_w = f.write(test_bytes) print(n_w == len(test_bytes)) f.close() -f = open('test.txt', 'r') -r = bytes(f.read(), 'ascii') +f = open("test.txt", "r") +r = bytes(f.read(), "ascii") # check that we can write and read it correctly print(r == test_bytes) f.close() -os.rename('test.txt', 'newtest.txt') +os.rename("test.txt", "newtest.txt") print(os.listdir()) -os.rename('/flash/test', '/flash/newtest') -print(os.listdir('/flash')) -os.remove('newtest.txt') -os.chdir('..') -os.rmdir('newtest') +os.rename("/flash/test", "/flash/newtest") +print(os.listdir("/flash")) +os.remove("newtest.txt") +os.chdir("..") +os.rmdir("newtest") # create a test directory in the sd card -os.mkdir('/sd/test') -os.chdir('/sd/test') +os.mkdir("/sd/test") +os.chdir("/sd/test") print(os.getcwd()) -os.chdir('..') +os.chdir("..") print(os.getcwd()) -os.chdir('test') +os.chdir("test") print(os.getcwd()) # create a new file -f = open('test.txt', 'w') +f = open("test.txt", "w") test_bytes = os.urandom(1024) n_w = f.write(test_bytes) print(n_w == len(test_bytes)) f.close() -f = open('test.txt', 'r') -r = bytes(f.read(), 'ascii') +f = open("test.txt", "r") +r = bytes(f.read(), "ascii") # check that we can write and read it correctly print(r == test_bytes) f.close() -print('CC3200' in os.uname().machine) -print('WiPy' == os.uname().sysname) +print("CC3200" in os.uname().machine) +print("WiPy" == os.uname().sysname) os.sync() -os.stat('/flash') -os.stat('/flash/sys') -os.stat('/flash/boot.py') -os.stat('/sd') -os.stat('/') -os.chdir('/sd/test') -os.remove('test.txt') -os.chdir('/sd') -os.rmdir('test') -os.listdir('/sd') -print(os.listdir('/')) -os.unmount('/sd') -print(os.listdir('/')) +os.stat("/flash") +os.stat("/flash/sys") +os.stat("/flash/boot.py") +os.stat("/sd") +os.stat("/") +os.chdir("/sd/test") +os.remove("test.txt") +os.chdir("/sd") +os.rmdir("test") +os.listdir("/sd") +print(os.listdir("/")) +os.unmount("/sd") +print(os.listdir("/")) os.mkfs(sd) -os.mount(sd, '/sd') -print(os.listdir('/')) -os.chdir('/flash') +os.mount(sd, "/sd") +print(os.listdir("/")) +os.chdir("/flash") # next ones must raise sd.deinit() try: - os.listdir('/sd') + os.listdir("/sd") except: - print('Exception') + print("Exception") -#re-initialization must work +# re-initialization must work sd.init() -print(os.listdir('/sd')) +print(os.listdir("/sd")) try: - os.mount(sd, '/sd') + os.mount(sd, "/sd") except: - print('Exception') + print("Exception") try: - os.mount(sd, '/sd2') + os.mount(sd, "/sd2") except: - print('Exception') + print("Exception") -os.unmount('/sd') +os.unmount("/sd") try: - os.listdir('/sd') + os.listdir("/sd") except: - print('Exception') + print("Exception") try: - os.unmount('/flash') + os.unmount("/flash") except: - print('Exception') + print("Exception") try: - os.unmount('/something') + os.unmount("/something") except: - print('Exception') + print("Exception") try: - os.unmount('something') + os.unmount("something") except: - print('Exception') + print("Exception") try: - os.mkfs('flash') # incorrect path format + os.mkfs("flash") # incorrect path format except: - print('Exception') + print("Exception") try: - os.remove('/flash/nofile.txt') + os.remove("/flash/nofile.txt") except: - print('Exception') + print("Exception") try: - os.rename('/flash/nofile.txt', '/flash/nofile2.txt') + os.rename("/flash/nofile.txt", "/flash/nofile2.txt") except: - print('Exception') + print("Exception") try: - os.chdir('/flash/nodir') + os.chdir("/flash/nodir") except: - print('Exception') + print("Exception") try: - os.listdir('/flash/nodir') + os.listdir("/flash/nodir") except: - print('Exception') + print("Exception") -os.mount(sd, '/sd') -print(os.listdir('/')) -os.unmount('/sd') +os.mount(sd, "/sd") +print(os.listdir("/")) +os.unmount("/sd") diff --git a/tests/wipy/pin.py b/tests/wipy/pin.py index 22c7c6176c..9ffd152e93 100644 --- a/tests/wipy/pin.py +++ b/tests/wipy/pin.py @@ -7,27 +7,61 @@ from machine import Pin import os mch = os.uname().machine -if 'LaunchPad' in mch: - pin_map = ['GP24', 'GP12', 'GP14', 'GP15', 'GP16', 'GP17', 'GP28', 'GP8', 'GP6', 'GP30', 'GP31', 'GP3', 'GP0', 'GP4', 'GP5'] +if "LaunchPad" in mch: + pin_map = [ + "GP24", + "GP12", + "GP14", + "GP15", + "GP16", + "GP17", + "GP28", + "GP8", + "GP6", + "GP30", + "GP31", + "GP3", + "GP0", + "GP4", + "GP5", + ] max_af_idx = 15 -elif 'WiPy' in mch: - pin_map = ['GP23', 'GP24', 'GP12', 'GP13', 'GP14', 'GP9', 'GP17', 'GP28', 'GP22', 'GP8', 'GP30', 'GP31', 'GP0', 'GP4', 'GP5'] +elif "WiPy" in mch: + pin_map = [ + "GP23", + "GP24", + "GP12", + "GP13", + "GP14", + "GP9", + "GP17", + "GP28", + "GP22", + "GP8", + "GP30", + "GP31", + "GP0", + "GP4", + "GP5", + ] max_af_idx = 15 else: - raise Exception('Board not supported!') + raise Exception("Board not supported!") # test initial value -p = Pin('GP12', Pin.IN) -Pin('GP17', Pin.OUT, value=1) +p = Pin("GP12", Pin.IN) +Pin("GP17", Pin.OUT, value=1) print(p() == 1) -Pin('GP17', Pin.OUT, value=0) +Pin("GP17", Pin.OUT, value=0) print(p() == 0) + def test_noinit(): for p in pin_map: pin = Pin(p) pin.value() + def test_pin_read(pull): # enable the pull resistor on all pins, then read the value for p in pin_map: @@ -35,6 +69,7 @@ def test_pin_read(pull): for p in pin_map: print(pin()) + def test_pin_af(): for p in pin_map: for af in Pin(p).alt_list(): @@ -42,6 +77,7 @@ def test_pin_af(): Pin(p, mode=Pin.ALT, alt=af[1]) Pin(p, mode=Pin.ALT_OPEN_DRAIN, alt=af[1]) + # test un-initialized pins test_noinit() # test with pull-up and pull-down @@ -65,7 +101,7 @@ pin = Pin(pin_map[0], mode=Pin.OUT, drive=pin.LOW_POWER) pin = Pin(pin_map[0], Pin.OUT, Pin.PULL_DOWN) pin = Pin(pin_map[0], Pin.ALT, Pin.PULL_UP) pin = Pin(pin_map[0], Pin.ALT_OPEN_DRAIN, Pin.PULL_UP) -test_pin_af() # try the entire af range on all pins +test_pin_af() # try the entire af range on all pins # test pin init and printing pin = Pin(pin_map[0]) @@ -81,9 +117,9 @@ print(pin) # test value in OUT mode pin = Pin(pin_map[0], mode=Pin.OUT) pin.value(0) -pin.toggle() # test toggle +pin.toggle() # test toggle print(pin()) -pin.toggle() # test toggle again +pin.toggle() # test toggle again print(pin()) # test different value settings pin(1) @@ -116,67 +152,66 @@ print(pin.id() == pin_map[0]) # all the next ones MUST raise try: - pin = Pin(pin_map[0], mode=Pin.OUT, pull=Pin.PULL_UP, drive=pin.IN) # incorrect drive value + pin = Pin(pin_map[0], mode=Pin.OUT, pull=Pin.PULL_UP, drive=pin.IN) # incorrect drive value except Exception: - print('Exception') + print("Exception") try: - pin = Pin(pin_map[0], mode=Pin.LOW_POWER, pull=Pin.PULL_UP) # incorrect mode value + pin = Pin(pin_map[0], mode=Pin.LOW_POWER, pull=Pin.PULL_UP) # incorrect mode value except Exception: - print('Exception') + print("Exception") try: - pin = Pin(pin_map[0], mode=Pin.IN, pull=Pin.HIGH_POWER) # incorrect pull value + pin = Pin(pin_map[0], mode=Pin.IN, pull=Pin.HIGH_POWER) # incorrect pull value except Exception: - print('Exception') + print("Exception") try: - pin = Pin('A0', Pin.OUT, Pin.PULL_DOWN) # incorrect pin id + pin = Pin("A0", Pin.OUT, Pin.PULL_DOWN) # incorrect pin id except Exception: - print('Exception') + print("Exception") try: - pin = Pin(pin_map[0], Pin.IN, Pin.PULL_UP, alt=0) # af specified in GPIO mode + pin = Pin(pin_map[0], Pin.IN, Pin.PULL_UP, alt=0) # af specified in GPIO mode except Exception: - print('Exception') + print("Exception") try: - pin = Pin(pin_map[0], Pin.OUT, Pin.PULL_UP, alt=7) # af specified in GPIO mode + pin = Pin(pin_map[0], Pin.OUT, Pin.PULL_UP, alt=7) # af specified in GPIO mode except Exception: - print('Exception') + print("Exception") try: - pin = Pin(pin_map[0], Pin.ALT, Pin.PULL_UP, alt=0) # incorrect af + pin = Pin(pin_map[0], Pin.ALT, Pin.PULL_UP, alt=0) # incorrect af except Exception: - print('Exception') + print("Exception") try: - pin = Pin(pin_map[0], Pin.ALT_OPEN_DRAIN, Pin.PULL_UP, alt=-1) # incorrect af + pin = Pin(pin_map[0], Pin.ALT_OPEN_DRAIN, Pin.PULL_UP, alt=-1) # incorrect af except Exception: - print('Exception') + print("Exception") try: - pin = Pin(pin_map[0], Pin.ALT_OPEN_DRAIN, Pin.PULL_UP, alt=16) # incorrect af + pin = Pin(pin_map[0], Pin.ALT_OPEN_DRAIN, Pin.PULL_UP, alt=16) # incorrect af except Exception: - print('Exception') + print("Exception") try: - pin.mode(Pin.PULL_UP) # incorrect pin mode + pin.mode(Pin.PULL_UP) # incorrect pin mode except Exception: - print('Exception') + print("Exception") try: - pin.pull(Pin.OUT) # incorrect pull + pin.pull(Pin.OUT) # incorrect pull except Exception: - print('Exception') + print("Exception") try: - pin.drive(Pin.IN) # incorrect drive strength + pin.drive(Pin.IN) # incorrect drive strength except Exception: - print('Exception') + print("Exception") try: - pin.id('ABC') # id cannot be set + pin.id("ABC") # id cannot be set except Exception: - print('Exception') - + print("Exception") diff --git a/tests/wipy/pin_irq.py b/tests/wipy/pin_irq.py index 875f1f9397..be5e1f426c 100644 --- a/tests/wipy/pin_irq.py +++ b/tests/wipy/pin_irq.py @@ -1,6 +1,6 @@ -''' +""" Pin IRQ test for the CC3200 based boards. -''' +""" from machine import Pin import machine @@ -8,17 +8,18 @@ import os import time mch = os.uname().machine -if 'LaunchPad' in mch: - pins = ['GP16', 'GP13'] -elif 'WiPy' in mch: - pins = ['GP16', 'GP13'] +if "LaunchPad" in mch: + pins = ["GP16", "GP13"] +elif "WiPy" in mch: + pins = ["GP16", "GP13"] else: - raise Exception('Board not supported!') + raise Exception("Board not supported!") pin0 = Pin(pins[0], mode=Pin.OUT, value=1) pin1 = Pin(pins[1], mode=Pin.IN, pull=Pin.PULL_UP) -def pin_handler (pin_o): + +def pin_handler(pin_o): global pin_irq_count_trigger global pin_irq_count_total global _trigger @@ -26,11 +27,12 @@ def pin_handler (pin_o): pin_irq_count_trigger += 1 pin_irq_count_total += 1 + pin_irq_count_trigger = 0 pin_irq_count_total = 0 _trigger = Pin.IRQ_FALLING pin1_irq = pin1.irq(trigger=_trigger, handler=pin_handler) -for i in range (0, 10): +for i in range(0, 10): pin0.toggle() time.sleep_ms(5) print(pin_irq_count_trigger == 5) @@ -40,7 +42,7 @@ pin_irq_count_trigger = 0 pin_irq_count_total = 0 _trigger = Pin.IRQ_RISING pin1_irq = pin1.irq(trigger=_trigger, handler=pin_handler) -for i in range (0, 200): +for i in range(0, 200): pin0.toggle() time.sleep_ms(5) print(pin_irq_count_trigger == 100) @@ -69,7 +71,7 @@ print(pin_irq_count_total == 2) pin1_irq.disable() pin_irq_count_trigger = 0 pin_irq_count_total = 0 -for i in range (0, 10): +for i in range(0, 10): pin0.toggle() time.sleep_ms(5) print(pin_irq_count_trigger == 0) @@ -81,7 +83,7 @@ t0 = time.ticks_ms() pin1_irq.init(trigger=Pin.IRQ_LOW_LEVEL, wake=machine.SLEEP) machine.sleep() print(time.ticks_ms() - t0 < 10) -print('Awake') +print("Awake") # test waking up from suspended mode on high level pin0(1) @@ -89,7 +91,7 @@ t0 = time.ticks_ms() pin1_irq.init(trigger=Pin.IRQ_HIGH_LEVEL, wake=machine.SLEEP) machine.sleep() print(time.ticks_ms() - t0 < 10) -print('Awake') +print("Awake") # check for memory leaks for i in range(0, 1000): @@ -100,17 +102,19 @@ for i in range(0, 1000): try: pin1_irq.init(trigger=123456, handler=pin_handler) except: - print('Exception') + print("Exception") try: pin1_irq.init(trigger=Pin.IRQ_LOW_LEVEL, wake=1789456) except: - print('Exception') + print("Exception") try: - pin0_irq = pin0.irq(trigger=Pin.IRQ_RISING, wake=machine.SLEEP) # GP16 can't wake up from DEEPSLEEP + pin0_irq = pin0.irq( + trigger=Pin.IRQ_RISING, wake=machine.SLEEP + ) # GP16 can't wake up from DEEPSLEEP except: - print('Exception') + print("Exception") pin0_irq.disable() pin1_irq.disable() diff --git a/tests/wipy/rtc.py b/tests/wipy/rtc.py index 2737ebe73a..c62e400fe3 100644 --- a/tests/wipy/rtc.py +++ b/tests/wipy/rtc.py @@ -1,14 +1,14 @@ -''' +""" RTC test for the CC3200 based boards. -''' +""" from machine import RTC import os import time mch = os.uname().machine -if not 'LaunchPad' in mch and not 'WiPy' in mch: - raise Exception('Board not supported!') +if not "LaunchPad" in mch and not "WiPy" in mch: + raise Exception("Board not supported!") rtc = RTC() print(rtc) @@ -41,10 +41,12 @@ print(rtc.now()[4]) rtc.init((2015, 9, 19)) print(rtc.now()[3]) + def set_and_print(datetime): rtc.init(datetime) print(rtc.now()[:6]) + # make sure that setting works correctly set_and_print((2000, 1, 1, 0, 0, 0, 0, None)) set_and_print((2000, 1, 31, 0, 0, 0, 0, None)) @@ -66,7 +68,7 @@ rtc.alarm(0, 5000) rtc.alarm(time=2000) time.sleep_ms(1000) left = rtc.alarm_left() -print(abs(left-1000) <= 10) +print(abs(left - 1000) <= 10) time.sleep_ms(1000) print(rtc.alarm_left() == 0) time.sleep_ms(100) @@ -75,13 +77,13 @@ print(rtc.alarm_left(0) == 0) rtc.alarm(time=1000, repeat=True) time.sleep_ms(1500) left = rtc.alarm_left() -print(abs(left-500) <= 15) +print(abs(left - 500) <= 15) rtc.init((2015, 8, 29, 9, 0, 0, 0, None)) rtc.alarm(time=(2015, 8, 29, 9, 0, 45)) time.sleep_ms(1000) left = rtc.alarm_left() -print(abs(left-44000) <= 90) +print(abs(left - 44000) <= 90) rtc.alarm_cancel() rtc.deinit() @@ -89,29 +91,29 @@ rtc.deinit() try: rtc.alarm(5000) except: - print('Exception') + print("Exception") try: rtc.alarm_left(1) except: - print('Exception') + print("Exception") try: rtc.alarm_cancel(1) except: - print('Exception') + print("Exception") try: rtc.alarm(5000) except: - print('Exception') + print("Exception") try: rtc = RTC(200000000) except: - print('Exception') + print("Exception") try: rtc = RTC((2015, 8, 29, 9, 0, 0, 0, None)) except: - print('Exception') + print("Exception") diff --git a/tests/wipy/sd.py b/tests/wipy/sd.py index 92746e01ed..381d46f30a 100644 --- a/tests/wipy/sd.py +++ b/tests/wipy/sd.py @@ -1,17 +1,17 @@ -''' +""" SD card test for the CC3200 based boards. -''' +""" from machine import SD import os mch = os.uname().machine -if 'LaunchPad' in mch: - sd_pins = ('GP16', 'GP17', 'GP15') -elif 'WiPy' in mch: - sd_pins = ('GP10', 'GP11', 'GP15') +if "LaunchPad" in mch: + sd_pins = ("GP16", "GP17", "GP15") +elif "WiPy" in mch: + sd_pins = ("GP10", "GP11", "GP15") else: - raise Exception('Board not supported!') + raise Exception("Board not supported!") sd = SD(pins=sd_pins) print(sd) @@ -35,12 +35,11 @@ except Exception: print("Exception") try: - sd = SD(pins=('GP10', 'GP11', 'GP8')) + sd = SD(pins=("GP10", "GP11", "GP8")) except Exception: print("Exception") try: - sd = SD(pins=('GP10', 'GP11')) + sd = SD(pins=("GP10", "GP11")) except Exception: print("Exception") - diff --git a/tests/wipy/spi.py b/tests/wipy/spi.py index 6bd7aabce1..a3509d8542 100644 --- a/tests/wipy/spi.py +++ b/tests/wipy/spi.py @@ -1,17 +1,17 @@ -''' +""" SPI test for the CC3200 based boards. -''' +""" from machine import SPI import os mch = os.uname().machine -if 'LaunchPad' in mch: - spi_pins = ('GP14', 'GP16', 'GP30') -elif 'WiPy' in mch: - spi_pins = ('GP14', 'GP16', 'GP30') +if "LaunchPad" in mch: + spi_pins = ("GP14", "GP16", "GP30") +elif "WiPy" in mch: + spi_pins = ("GP14", "GP16", "GP30") else: - raise Exception('Board not supported!') + raise Exception("Board not supported!") spi = SPI(0, SPI.MASTER, baudrate=2000000, polarity=0, phase=0, firstbit=SPI.MSB, pins=spi_pins) print(spi) @@ -27,15 +27,15 @@ spi = SPI(0, SPI.MASTER, baudrate=10000000, polarity=1, phase=1) print(spi) spi.init(baudrate=20000000, polarity=0, phase=0) print(spi) -spi=SPI() +spi = SPI() print(spi) SPI(mode=SPI.MASTER) SPI(mode=SPI.MASTER, pins=spi_pins) -SPI(id=0, mode=SPI.MASTER, polarity=0, phase=0, pins=('GP14', 'GP16', 'GP15')) -SPI(0, SPI.MASTER, polarity=0, phase=0, pins=('GP31', 'GP16', 'GP15')) +SPI(id=0, mode=SPI.MASTER, polarity=0, phase=0, pins=("GP14", "GP16", "GP15")) +SPI(0, SPI.MASTER, polarity=0, phase=0, pins=("GP31", "GP16", "GP15")) spi = SPI(0, SPI.MASTER, baudrate=10000000, polarity=0, phase=0, pins=spi_pins) -print(spi.write('123456') == 6) +print(spi.write("123456") == 6) buffer_r = bytearray(10) print(spi.readinto(buffer_r) == 10) print(spi.readinto(buffer_r, write=0x55) == 10) @@ -76,7 +76,7 @@ print(spi.write_readinto(buffer_w, buffer_r) == 12) print(buffer_w == buffer_r) # check for memory leaks... -for i in range (0, 1000): +for i in range(0, 1000): spi = SPI(0, SPI.MASTER, baudrate=1000000) # test deinit @@ -112,7 +112,7 @@ except: print("Exception") try: - spi = SPI(0, mode=SPI.MASTER, baudrate=2000000, polarity=2, phase=0, pins=('GP1', 'GP2')) + spi = SPI(0, mode=SPI.MASTER, baudrate=2000000, polarity=2, phase=0, pins=("GP1", "GP2")) except: print("Exception") @@ -133,7 +133,7 @@ except Exception: print("Exception") try: - spi.spi.write('abc') + spi.spi.write("abc") except Exception: print("Exception") diff --git a/tests/wipy/time.py b/tests/wipy/time.py index e6237de356..c1d105d64d 100644 --- a/tests/wipy/time.py +++ b/tests/wipy/time.py @@ -2,12 +2,14 @@ import time DAYS_PER_MONTH = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] + def is_leap(year): return (year % 4) == 0 + def test(): seconds = 0 - wday = 5 # Jan 1, 2000 was a Saturday + wday = 5 # Jan 1, 2000 was a Saturday for year in range(2000, 2049): print("Testing %d" % year) yday = 1 @@ -19,53 +21,69 @@ def test(): for day in range(1, DAYS_PER_MONTH[month] + 1): secs = time.mktime((year, month, day, 0, 0, 0, 0, 0)) if secs != seconds: - print("mktime failed for %d-%02d-%02d got %d expected %d" % (year, month, day, secs, seconds)) + print( + "mktime failed for %d-%02d-%02d got %d expected %d" + % (year, month, day, secs, seconds) + ) tuple = time.localtime(seconds) secs = time.mktime(tuple) if secs != seconds: - print("localtime failed for %d-%02d-%02d got %d expected %d" % (year, month, day, secs, seconds)) + print( + "localtime failed for %d-%02d-%02d got %d expected %d" + % (year, month, day, secs, seconds) + ) return seconds += 86400 if yday != tuple[7]: - print("locatime for %d-%02d-%02d got yday %d, expecting %d" % (year, month, day, tuple[7], yday)) + print( + "locatime for %d-%02d-%02d got yday %d, expecting %d" + % (year, month, day, tuple[7], yday) + ) return if wday != tuple[6]: - print("locatime for %d-%02d-%02d got wday %d, expecting %d" % (year, month, day, tuple[6], wday)) + print( + "locatime for %d-%02d-%02d got wday %d, expecting %d" + % (year, month, day, tuple[6], wday) + ) return yday += 1 wday = (wday + 1) % 7 + def spot_test(seconds, expected_time): actual_time = time.localtime(seconds) for i in range(len(actual_time)): if actual_time[i] != expected_time[i]: - print("time.localtime(", seconds, ") returned", actual_time, "expecting", expected_time) + print( + "time.localtime(", seconds, ") returned", actual_time, "expecting", expected_time + ) return print("time.localtime(", seconds, ") returned", actual_time, "(pass)") + test() -spot_test( 0, (2000, 1, 1, 0, 0, 0, 5, 1)) -spot_test( 1, (2000, 1, 1, 0, 0, 1, 5, 1)) -spot_test( 59, (2000, 1, 1, 0, 0, 59, 5, 1)) -spot_test( 60, (2000, 1, 1, 0, 1, 0, 5, 1)) -spot_test( 3599, (2000, 1, 1, 0, 59, 59, 5, 1)) -spot_test( 3600, (2000, 1, 1, 1, 0, 0, 5, 1)) -spot_test( -1, (1999, 12, 31, 23, 59, 59, 4, 365)) -spot_test( 447549467, (2014, 3, 7, 23, 17, 47, 4, 66)) -spot_test( -940984933, (1970, 3, 7, 23, 17, 47, 5, 66)) -spot_test(-1072915199, (1966, 1, 1, 0, 0, 1, 5, 1)) -spot_test(-1072915200, (1966, 1, 1, 0, 0, 0, 5, 1)) -spot_test(-1072915201, (1965, 12, 31, 23, 59, 59, 4, 365)) +spot_test(0, (2000, 1, 1, 0, 0, 0, 5, 1)) +spot_test(1, (2000, 1, 1, 0, 0, 1, 5, 1)) +spot_test(59, (2000, 1, 1, 0, 0, 59, 5, 1)) +spot_test(60, (2000, 1, 1, 0, 1, 0, 5, 1)) +spot_test(3599, (2000, 1, 1, 0, 59, 59, 5, 1)) +spot_test(3600, (2000, 1, 1, 1, 0, 0, 5, 1)) +spot_test(-1, (1999, 12, 31, 23, 59, 59, 4, 365)) +spot_test(447549467, (2014, 3, 7, 23, 17, 47, 4, 66)) +spot_test(-940984933, (1970, 3, 7, 23, 17, 47, 5, 66)) +spot_test(-1072915199, (1966, 1, 1, 0, 0, 1, 5, 1)) +spot_test(-1072915200, (1966, 1, 1, 0, 0, 0, 5, 1)) +spot_test(-1072915201, (1965, 12, 31, 23, 59, 59, 4, 365)) t1 = time.time() time.sleep(2) t2 = time.time() -print(abs(time.ticks_diff(t1, t2) -2) <= 1) +print(abs(time.ticks_diff(t1, t2) - 2) <= 1) t1 = time.ticks_ms() time.sleep_ms(50) t2 = time.ticks_ms() -print(abs(time.ticks_diff(t1, t2)- 50) <= 1) +print(abs(time.ticks_diff(t1, t2) - 50) <= 1) t1 = time.ticks_us() time.sleep_us(1000) diff --git a/tests/wipy/timer.py b/tests/wipy/timer.py index f62899b472..db25870db0 100644 --- a/tests/wipy/timer.py +++ b/tests/wipy/timer.py @@ -1,18 +1,18 @@ -''' +""" Timer test for the CC3200 based boards. -''' +""" from machine import Timer import os import time mch = os.uname().machine -if 'LaunchPad' in mch: - pwm_pin = ('GP24') -elif 'WiPy' in mch: - pwm_pin = ('GP24') +if "LaunchPad" in mch: + pwm_pin = "GP24" +elif "WiPy" in mch: + pwm_pin = "GP24" else: - raise Exception('Board not supported!') + raise Exception("Board not supported!") for i in range(4): tim = Timer(i, mode=Timer.PERIODIC) @@ -49,6 +49,7 @@ class TimerTest: def timer_isr(self, tim_ch): self.int_count += 1 + timer_test = TimerTest() ch = timer_test.tim.channel(Timer.A, freq=5) print(ch.freq() == 5) @@ -92,26 +93,26 @@ for i in range(1000): try: tim = Timer(0, mode=12) except: - print('Exception') + print("Exception") try: tim = Timer(4, mode=Timer.ONE_SHOT) except: - print('Exception') + print("Exception") try: tim = Timer(0, mode=Timer.PWM, width=32) except: - print('Exception') + print("Exception") tim = Timer(0, mode=Timer.PWM) try: ch = tim.channel(TIMER_A | TIMER_B, freq=10) except: - print('Exception') + print("Exception") try: ch = tim.channel(TIMER_A, freq=4) except: - print('Exception') + print("Exception") diff --git a/tests/wipy/uart.py b/tests/wipy/uart.py index 8e794015de..9498d95545 100644 --- a/tests/wipy/uart.py +++ b/tests/wipy/uart.py @@ -1,7 +1,7 @@ -''' +""" UART test for the CC3200 based boards. UART0 and UART1 must be connected together for this test to pass. -''' +""" from machine import UART from machine import Pin @@ -9,14 +9,20 @@ import os import time mch = os.uname().machine -if 'LaunchPad' in mch: +if "LaunchPad" in mch: uart_id_range = range(0, 2) - uart_pins = [[('GP12', 'GP13'), ('GP12', 'GP13', 'GP7', 'GP6')], [('GP16', 'GP17'), ('GP16', 'GP17', 'GP7', 'GP6')]] -elif 'WiPy' in mch: + uart_pins = [ + [("GP12", "GP13"), ("GP12", "GP13", "GP7", "GP6")], + [("GP16", "GP17"), ("GP16", "GP17", "GP7", "GP6")], + ] +elif "WiPy" in mch: uart_id_range = range(0, 2) - uart_pins = [[('GP12', 'GP13'), ('GP12', 'GP13', 'GP7', 'GP6')], [('GP16', 'GP17'), ('GP16', 'GP17', 'GP7', 'GP6')]] + uart_pins = [ + [("GP12", "GP13"), ("GP12", "GP13", "GP7", "GP6")], + [("GP16", "GP17"), ("GP16", "GP17", "GP7", "GP6")], + ] else: - raise Exception('Board not supported!') + raise Exception("Board not supported!") # just in case we have the repl duplicated on any of the uarts os.dupterm(None) @@ -33,13 +39,13 @@ for uart_id in uart_id_range: uart = UART(baudrate=1000000) uart = UART() print(uart) -uart = UART(baudrate=38400, pins=('GP12', 'GP13')) +uart = UART(baudrate=38400, pins=("GP12", "GP13")) print(uart) -uart = UART(pins=('GP12', 'GP13')) +uart = UART(pins=("GP12", "GP13")) print(uart) -uart = UART(pins=(None, 'GP17')) +uart = UART(pins=(None, "GP17")) print(uart) -uart = UART(baudrate=57600, pins=('GP16', 'GP17')) +uart = UART(baudrate=57600, pins=("GP16", "GP17")) print(uart) # now it's time for some loopback tests between the uarts @@ -48,104 +54,104 @@ print(uart0) uart1 = UART(1, 1000000, pins=uart_pins[1][0]) print(uart1) -print(uart0.write(b'123456') == 6) -print(uart1.read() == b'123456') +print(uart0.write(b"123456") == 6) +print(uart1.read() == b"123456") -print(uart1.write(b'123') == 3) -print(uart0.read(1) == b'1') -print(uart0.read(2) == b'23') +print(uart1.write(b"123") == 3) +print(uart0.read(1) == b"1") +print(uart0.read(2) == b"23") print(uart0.read() == None) -uart0.write(b'123') +uart0.write(b"123") buf = bytearray(3) -print(uart1.readinto(buf, 1) == 1) +print(uart1.readinto(buf, 1) == 1) print(buf) print(uart1.readinto(buf) == 2) print(buf) # try initializing without the id uart0 = UART(baudrate=1000000, pins=uart_pins[0][0]) -uart0.write(b'1234567890') -time.sleep_ms(2) # because of the fifo interrupt levels +uart0.write(b"1234567890") +time.sleep_ms(2) # because of the fifo interrupt levels print(uart1.any() == 10) -print(uart1.readline() == b'1234567890') +print(uart1.readline() == b"1234567890") print(uart1.any() == 0) -uart0.write(b'1234567890') -print(uart1.read() == b'1234567890') +uart0.write(b"1234567890") +print(uart1.read() == b"1234567890") # tx only mode -uart0 = UART(0, 1000000, pins=('GP12', None)) -print(uart0.write(b'123456') == 6) -print(uart1.read() == b'123456') -print(uart1.write(b'123') == 3) +uart0 = UART(0, 1000000, pins=("GP12", None)) +print(uart0.write(b"123456") == 6) +print(uart1.read() == b"123456") +print(uart1.write(b"123") == 3) print(uart0.read() == None) # rx only mode -uart0 = UART(0, 1000000, pins=(None, 'GP13')) -print(uart0.write(b'123456') == 6) +uart0 = UART(0, 1000000, pins=(None, "GP13")) +print(uart0.write(b"123456") == 6) print(uart1.read() == None) -print(uart1.write(b'123') == 3) -print(uart0.read() == b'123') +print(uart1.write(b"123") == 3) +print(uart0.read() == b"123") # leave pins as they were (rx only mode) uart0 = UART(0, 1000000, pins=None) -print(uart0.write(b'123456') == 6) +print(uart0.write(b"123456") == 6) print(uart1.read() == None) -print(uart1.write(b'123') == 3) -print(uart0.read() == b'123') +print(uart1.write(b"123") == 3) +print(uart0.read() == b"123") # no pin assignment uart0 = UART(0, 1000000, pins=(None, None)) -print(uart0.write(b'123456789') == 9) +print(uart0.write(b"123456789") == 9) print(uart1.read() == None) -print(uart1.write(b'123456789') == 9) +print(uart1.write(b"123456789") == 9) print(uart0.read() == None) print(Pin.board.GP12) print(Pin.board.GP13) # check for memory leaks... -for i in range (0, 1000): +for i in range(0, 1000): uart0 = UART(0, 1000000) uart1 = UART(1, 1000000) # next ones must raise try: - UART(0, 9600, parity=None, pins=('GP12', 'GP13', 'GP7')) + UART(0, 9600, parity=None, pins=("GP12", "GP13", "GP7")) except Exception: - print('Exception') + print("Exception") try: - UART(0, 9600, parity=UART.ODD, pins=('GP12', 'GP7')) + UART(0, 9600, parity=UART.ODD, pins=("GP12", "GP7")) except Exception: - print('Exception') + print("Exception") uart0 = UART(0, 1000000) uart0.deinit() try: uart0.any() except Exception: - print('Exception') + print("Exception") try: uart0.read() except Exception: - print('Exception') + print("Exception") try: - uart0.write('abc') + uart0.write("abc") except Exception: - print('Exception') + print("Exception") try: - uart0.sendbreak('abc') + uart0.sendbreak("abc") except Exception: - print('Exception') + print("Exception") try: UART(2, 9600) except Exception: - print('Exception') + print("Exception") for uart_id in uart_id_range: uart = UART(uart_id, 1000000) diff --git a/tests/wipy/uart_irq.py b/tests/wipy/uart_irq.py index d4cd900585..e631e46a9c 100644 --- a/tests/wipy/uart_irq.py +++ b/tests/wipy/uart_irq.py @@ -1,18 +1,24 @@ -''' +""" UART IRQ test for the CC3200 based boards. -''' +""" from machine import UART import os import time mch = os.uname().machine -if 'LaunchPad' in mch: - uart_pins = [[('GP12', 'GP13'), ('GP12', 'GP13', 'GP7', 'GP6')], [('GP16', 'GP17'), ('GP16', 'GP17', 'GP7', 'GP6')]] -elif 'WiPy' in mch: - uart_pins = [[('GP12', 'GP13'), ('GP12', 'GP13', 'GP7', 'GP6')], [('GP16', 'GP17'), ('GP16', 'GP17', 'GP7', 'GP6')]] +if "LaunchPad" in mch: + uart_pins = [ + [("GP12", "GP13"), ("GP12", "GP13", "GP7", "GP6")], + [("GP16", "GP17"), ("GP16", "GP17", "GP7", "GP6")], + ] +elif "WiPy" in mch: + uart_pins = [ + [("GP12", "GP13"), ("GP12", "GP13", "GP7", "GP6")], + [("GP16", "GP17"), ("GP16", "GP17", "GP7", "GP6")], + ] else: - raise Exception('Board not supported!') + raise Exception("Board not supported!") # just in case we have stdio duplicated on any of the uarts os.dupterm(None) @@ -23,22 +29,25 @@ uart1 = UART(1, 1000000, pins=uart_pins[1][0]) uart0_int_count = 0 uart1_int_count = 0 -def uart0_handler (uart_o): + +def uart0_handler(uart_o): global uart0_irq global uart0_int_count - if (uart0_irq.flags() & UART.RX_ANY): + if uart0_irq.flags() & UART.RX_ANY: uart0_int_count += 1 -def uart1_handler (uart_o): + +def uart1_handler(uart_o): global uart1_irq global uart1_int_count - if (uart1_irq.flags() & UART.RX_ANY): + if uart1_irq.flags() & UART.RX_ANY: uart1_int_count += 1 + uart0_irq = uart0.irq(trigger=UART.RX_ANY, handler=uart0_handler) uart1_irq = uart1.irq(trigger=UART.RX_ANY, handler=uart1_handler) -uart0.write(b'123') +uart0.write(b"123") # wait for the characters to be received while not uart1.any(): pass @@ -48,9 +57,9 @@ print(uart1.any() == 3) print(uart1_int_count > 0) print(uart1_irq.flags() == 0) print(uart0_irq.flags() == 0) -print(uart1.read() == b'123') +print(uart1.read() == b"123") -uart1.write(b'12345') +uart1.write(b"12345") # wait for the characters to be received while not uart0.any(): pass @@ -60,11 +69,11 @@ print(uart0.any() == 5) print(uart0_int_count > 0) print(uart0_irq.flags() == 0) print(uart1_irq.flags() == 0) -print(uart0.read() == b'12345') +print(uart0.read() == b"12345") # do it again uart1_int_count = 0 -uart0.write(b'123') +uart0.write(b"123") # wait for the characters to be received while not uart1.any(): pass @@ -74,29 +83,29 @@ print(uart1.any() == 3) print(uart1_int_count > 0) print(uart1_irq.flags() == 0) print(uart0_irq.flags() == 0) -print(uart1.read() == b'123') +print(uart1.read() == b"123") # disable the interrupt uart1_irq.disable() # do it again uart1_int_count = 0 -uart0.write(b'123') +uart0.write(b"123") # wait for the characters to be received while not uart1.any(): pass time.sleep_us(100) print(uart1.any() == 3) -print(uart1_int_count == 0) # no interrupt triggered this time +print(uart1_int_count == 0) # no interrupt triggered this time print(uart1_irq.flags() == 0) print(uart0_irq.flags() == 0) -print(uart1.read() == b'123') +print(uart1.read() == b"123") # enable the interrupt uart1_irq.enable() # do it again uart1_int_count = 0 -uart0.write(b'123') +uart0.write(b"123") # wait for the characters to be received while not uart1.any(): pass @@ -106,22 +115,22 @@ print(uart1.any() == 3) print(uart1_int_count > 0) print(uart1_irq.flags() == 0) print(uart0_irq.flags() == 0) -print(uart1.read() == b'123') +print(uart1.read() == b"123") -uart1_irq.init(trigger=UART.RX_ANY, handler=None) # No handler +uart1_irq.init(trigger=UART.RX_ANY, handler=None) # No handler # do it again uart1_int_count = 0 -uart0.write(b'123') +uart0.write(b"123") # wait for the characters to be received while not uart1.any(): pass time.sleep_us(100) print(uart1.any() == 3) -print(uart1_int_count == 0) # no interrupt handler called +print(uart1_int_count == 0) # no interrupt handler called print(uart1_irq.flags() == 0) print(uart0_irq.flags() == 0) -print(uart1.read() == b'123') +print(uart1.read() == b"123") # check for memory leaks for i in range(0, 1000): @@ -132,17 +141,17 @@ for i in range(0, 1000): try: uart0_irq = uart0.irq(trigger=100, handler=uart0_handler) except: - print('Exception') + print("Exception") try: uart0_irq = uart0.irq(trigger=0) except: - print('Exception') + print("Exception") try: uart0_irq = uart0.irq(trigger=UART.RX_ANY, wake=Sleep.SUSPENDED) except: - print('Exception') + print("Exception") uart0_irq.disable() uart1_irq.disable() diff --git a/tests/wipy/wdt.py b/tests/wipy/wdt.py index a894b88fd8..56f6ea8d95 100644 --- a/tests/wipy/wdt.py +++ b/tests/wipy/wdt.py @@ -1,6 +1,6 @@ -''' +""" WDT test for the CC3200 based boards -''' +""" from machine import WDT import time diff --git a/tools/dfu.py b/tools/dfu.py index ee89c7541e..6591436e9e 100755 --- a/tools/dfu.py +++ b/tools/dfu.py @@ -4,122 +4,160 @@ # Distributed under Gnu LGPL 3.0 # see http://www.gnu.org/licenses/lgpl-3.0.txt -import sys,struct,zlib,os +import sys, struct, zlib, os from optparse import OptionParser -DEFAULT_DEVICE="0x0483:0xdf11" +DEFAULT_DEVICE = "0x0483:0xdf11" + + +def named(tuple, names): + return dict(zip(names.split(), tuple)) + + +def consume(fmt, data, names): + n = struct.calcsize(fmt) + return named(struct.unpack(fmt, data[:n]), names), data[n:] + -def named(tuple,names): - return dict(zip(names.split(),tuple)) -def consume(fmt,data,names): - n = struct.calcsize(fmt) - return named(struct.unpack(fmt,data[:n]),names),data[n:] def cstring(string): - return string.split('\0',1)[0] + return string.split("\0", 1)[0] + + def compute_crc(data): - return 0xFFFFFFFF & -zlib.crc32(data) -1 + return 0xFFFFFFFF & -zlib.crc32(data) - 1 -def parse(file,dump_images=False): - print ('File: "%s"' % file) - data = open(file,'rb').read() - crc = compute_crc(data[:-4]) - prefix, data = consume('<5sBIB',data,'signature version size targets') - print ('%(signature)s v%(version)d, image size: %(size)d, targets: %(targets)d' % prefix) - for t in range(prefix['targets']): - tprefix, data = consume('<6sBI255s2I',data,'signature altsetting named name size elements') - tprefix['num'] = t - if tprefix['named']: - tprefix['name'] = cstring(tprefix['name']) - else: - tprefix['name'] = '' - print ('%(signature)s %(num)d, alt setting: %(altsetting)s, name: "%(name)s", size: %(size)d, elements: %(elements)d' % tprefix) - tsize = tprefix['size'] - target, data = data[:tsize], data[tsize:] - for e in range(tprefix['elements']): - eprefix, target = consume('<2I',target,'address size') - eprefix['num'] = e - print (' %(num)d, address: 0x%(address)08x, size: %(size)d' % eprefix) - esize = eprefix['size'] - image, target = target[:esize], target[esize:] - if dump_images: - out = '%s.target%d.image%d.bin' % (file,t,e) - open(out,'wb').write(image) - print (' DUMPED IMAGE TO "%s"' % out) - if len(target): - print ("target %d: PARSE ERROR" % t) - suffix = named(struct.unpack('<4H3sBI',data[:16]),'device product vendor dfu ufd len crc') - print ('usb: %(vendor)04x:%(product)04x, device: 0x%(device)04x, dfu: 0x%(dfu)04x, %(ufd)s, %(len)d, 0x%(crc)08x' % suffix) - if crc != suffix['crc']: - print ("CRC ERROR: computed crc32 is 0x%08x" % crc) - data = data[16:] - if data: - print ("PARSE ERROR") -def build(file,targets,device=DEFAULT_DEVICE): - data = b'' - for t,target in enumerate(targets): - tdata = b'' - for image in target: - # pad image to 8 bytes (needed at least for L476) - pad = (8 - len(image['data']) % 8 ) % 8 - image['data'] = image['data'] + bytes(bytearray(8)[0:pad]) - # - tdata += struct.pack('<2I',image['address'],len(image['data']))+image['data'] - tdata = struct.pack('<6sBI255s2I',b'Target',0,1, b'ST...',len(tdata),len(target)) + tdata - data += tdata - data = struct.pack('<5sBIB',b'DfuSe',1,len(data)+11,len(targets)) + data - v,d=map(lambda x: int(x,0) & 0xFFFF, device.split(':',1)) - data += struct.pack('<4H3sB',0,d,v,0x011a,b'UFD',16) - crc = compute_crc(data) - data += struct.pack('= len(class_) or section[i] != class_[i]: if i == 0: - filename = section[i].replace(' ', '_').lower() - rst = open(DOCPATH + filename + '.rst', 'w') + filename = section[i].replace(" ", "_").lower() + rst = open(DOCPATH + filename + ".rst", "w") rst.write(HEADER) - rst.write(section[i] + '\n') + rst.write(section[i] + "\n") rst.write(RSTCHARS[0] * len(section[i])) rst.write(time.strftime("\nGenerated %a %d %b %Y %X UTC\n\n", time.gmtime())) toctree.append(filename) else: - rst.write(section[i] + '\n') - rst.write(RSTCHARS[min(i, len(RSTCHARS)-1)] * len(section[i])) - rst.write('\n\n') + rst.write(section[i] + "\n") + rst.write(RSTCHARS[min(i, len(RSTCHARS) - 1)] * len(section[i])) + rst.write("\n\n") class_ = section - rst.write('.. _cpydiff_%s:\n\n' % output.name.rsplit('.', 1)[0]) - rst.write(output.desc + '\n') - rst.write('~' * len(output.desc) + '\n\n') - if output.cause != 'Unknown': - rst.write('**Cause:** ' + output.cause + '\n\n') - if output.workaround != 'Unknown': - rst.write('**Workaround:** ' + output.workaround + '\n\n') + rst.write(".. _cpydiff_%s:\n\n" % output.name.rsplit(".", 1)[0]) + rst.write(output.desc + "\n") + rst.write("~" * len(output.desc) + "\n\n") + if output.cause != "Unknown": + rst.write("**Cause:** " + output.cause + "\n\n") + if output.workaround != "Unknown": + rst.write("**Workaround:** " + output.workaround + "\n\n") - rst.write('Sample code::\n\n' + indent(output.code, TAB) + '\n') - output_cpy = indent(''.join(output.output_cpy[0:2]), TAB).rstrip() - output_cpy = ('::\n\n' if output_cpy != '' else '') + output_cpy - output_upy = indent(''.join(output.output_upy[0:2]), TAB).rstrip() - output_upy = ('::\n\n' if output_upy != '' else '') + output_upy - table = gen_table([['CPy output:', output_cpy], ['uPy output:', output_upy]]) + rst.write("Sample code::\n\n" + indent(output.code, TAB) + "\n") + output_cpy = indent("".join(output.output_cpy[0:2]), TAB).rstrip() + output_cpy = ("::\n\n" if output_cpy != "" else "") + output_cpy + output_upy = indent("".join(output.output_upy[0:2]), TAB).rstrip() + output_upy = ("::\n\n" if output_upy != "" else "") + output_upy + table = gen_table([["CPy output:", output_cpy], ["uPy output:", output_upy]]) rst.write(table) - template = open(INDEXTEMPLATE, 'r') - index = open(DOCPATH + INDEX, 'w') + template = open(INDEXTEMPLATE, "r") + index = open(DOCPATH + INDEX, "w") index.write(HEADER) index.write(template.read()) for section in INDEXPRIORITY: if section in toctree: - index.write(indent(section + '.rst', TAB)) + index.write(indent(section + ".rst", TAB)) toctree.remove(section) for section in toctree: - index.write(indent(section + '.rst', TAB)) + index.write(indent(section + ".rst", TAB)) + def main(): """ Main function """ # set search path so that test scripts find the test modules (and no other ones) - os.environ['PYTHONPATH'] = TESTPATH - os.environ['MICROPYPATH'] = TESTPATH + os.environ["PYTHONPATH"] = TESTPATH + os.environ["MICROPYPATH"] = TESTPATH files = readfiles() results = run_tests(files) gen_rst(results) + main() diff --git a/tools/gendoc.py b/tools/gendoc.py index 61844d203f..0f13056995 100644 --- a/tools/gendoc.py +++ b/tools/gendoc.py @@ -15,10 +15,12 @@ def re_match_first(regexs, line): return name, match return None, None + def makedirs(d): if not os.path.isdir(d): os.makedirs(d) + class Lexer: class LexerError(Exception): pass @@ -31,15 +33,15 @@ class Lexer: def __init__(self, file): self.filename = file - with open(file, 'rt') as f: + with open(file, "rt") as f: line_num = 0 lines = [] for line in f: line_num += 1 line = line.strip() - if line == '///': - lines.append((line_num, '')) - elif line.startswith('/// '): + if line == "///": + lines.append((line_num, "")) + elif line.startswith("/// "): lines.append((line_num, line[4:])) elif len(lines) > 0 and lines[-1][1] is not None: lines.append((line_num, None)) @@ -64,9 +66,10 @@ class Lexer: return l[1] def error(self, msg): - print('({}:{}) {}'.format(self.filename, self.cur_line, msg)) + print("({}:{}) {}".format(self.filename, self.cur_line, msg)) raise Lexer.LexerError + class MarkdownWriter: def __init__(self): pass @@ -75,52 +78,53 @@ class MarkdownWriter: self.lines = [] def end(self): - return '\n'.join(self.lines) + return "\n".join(self.lines) def heading(self, level, text): if len(self.lines) > 0: - self.lines.append('') - self.lines.append(level * '#' + ' ' + text) - self.lines.append('') + self.lines.append("") + self.lines.append(level * "#" + " " + text) + self.lines.append("") def para(self, text): - if len(self.lines) > 0 and self.lines[-1] != '': - self.lines.append('') + if len(self.lines) > 0 and self.lines[-1] != "": + self.lines.append("") if isinstance(text, list): self.lines.extend(text) elif isinstance(text, str): self.lines.append(text) else: assert False - self.lines.append('') + self.lines.append("") def single_line(self, text): self.lines.append(text) def module(self, name, short_descr, descr): - self.heading(1, 'module {}'.format(name)) + self.heading(1, "module {}".format(name)) self.para(descr) def function(self, ctx, name, args, descr): - proto = '{}.{}{}'.format(ctx, self.name, self.args) - self.heading(3, '`' + proto + '`') + proto = "{}.{}{}".format(ctx, self.name, self.args) + self.heading(3, "`" + proto + "`") self.para(descr) def method(self, ctx, name, args, descr): - if name == '\\constructor': - proto = '{}{}'.format(ctx, args) - elif name == '\\call': - proto = '{}{}'.format(ctx, args) + if name == "\\constructor": + proto = "{}{}".format(ctx, args) + elif name == "\\call": + proto = "{}{}".format(ctx, args) else: - proto = '{}.{}{}'.format(ctx, name, args) - self.heading(3, '`' + proto + '`') + proto = "{}.{}{}".format(ctx, name, args) + self.heading(3, "`" + proto + "`") self.para(descr) def constant(self, ctx, name, descr): - self.single_line('`{}.{}` - {}'.format(ctx, name, descr)) + self.single_line("`{}.{}` - {}".format(ctx, name, descr)) + class ReStructuredTextWriter: - head_chars = {1:'=', 2:'-', 3:'.'} + head_chars = {1: "=", 2: "-", 3: "."} def __init__(self): pass @@ -129,23 +133,23 @@ class ReStructuredTextWriter: self.lines = [] def end(self): - return '\n'.join(self.lines) + return "\n".join(self.lines) def _convert(self, text): - return text.replace('`', '``').replace('*', '\\*') + return text.replace("`", "``").replace("*", "\\*") def heading(self, level, text, convert=True): if len(self.lines) > 0: - self.lines.append('') + self.lines.append("") if convert: text = self._convert(text) self.lines.append(text) self.lines.append(len(text) * self.head_chars[level]) - self.lines.append('') + self.lines.append("") - def para(self, text, indent=''): - if len(self.lines) > 0 and self.lines[-1] != '': - self.lines.append('') + def para(self, text, indent=""): + if len(self.lines) > 0 and self.lines[-1] != "": + self.lines.append("") if isinstance(text, list): for t in text: self.lines.append(indent + self._convert(t)) @@ -153,39 +157,41 @@ class ReStructuredTextWriter: self.lines.append(indent + self._convert(text)) else: assert False - self.lines.append('') + self.lines.append("") def single_line(self, text): self.lines.append(self._convert(text)) def module(self, name, short_descr, descr): - self.heading(1, ':mod:`{}` --- {}'.format(name, self._convert(short_descr)), convert=False) - self.lines.append('.. module:: {}'.format(name)) - self.lines.append(' :synopsis: {}'.format(short_descr)) + self.heading(1, ":mod:`{}` --- {}".format(name, self._convert(short_descr)), convert=False) + self.lines.append(".. module:: {}".format(name)) + self.lines.append(" :synopsis: {}".format(short_descr)) self.para(descr) def function(self, ctx, name, args, descr): args = self._convert(args) - self.lines.append('.. function:: ' + name + args) - self.para(descr, indent=' ') + self.lines.append(".. function:: " + name + args) + self.para(descr, indent=" ") def method(self, ctx, name, args, descr): args = self._convert(args) - if name == '\\constructor': - self.lines.append('.. class:: ' + ctx + args) - elif name == '\\call': - self.lines.append('.. method:: ' + ctx + args) + if name == "\\constructor": + self.lines.append(".. class:: " + ctx + args) + elif name == "\\call": + self.lines.append(".. method:: " + ctx + args) else: - self.lines.append('.. method:: ' + ctx + '.' + name + args) - self.para(descr, indent=' ') + self.lines.append(".. method:: " + ctx + "." + name + args) + self.para(descr, indent=" ") def constant(self, ctx, name, descr): - self.lines.append('.. data:: ' + name) - self.para(descr, indent=' ') + self.lines.append(".. data:: " + name) + self.para(descr, indent=" ") + class DocValidateError(Exception): pass + class DocItem: def __init__(self): self.doc = [] @@ -202,6 +208,7 @@ class DocItem: def dump(self, writer): writer.para(self.doc) + class DocConstant(DocItem): def __init__(self, name, descr): super().__init__() @@ -211,6 +218,7 @@ class DocConstant(DocItem): def dump(self, ctx, writer): writer.constant(ctx, self.name, self.descr) + class DocFunction(DocItem): def __init__(self, name, args): super().__init__() @@ -220,6 +228,7 @@ class DocFunction(DocItem): def dump(self, ctx, writer): writer.function(ctx, self.name, self.args, self.doc) + class DocMethod(DocItem): def __init__(self, name, args): super().__init__() @@ -229,6 +238,7 @@ class DocMethod(DocItem): def dump(self, ctx, writer): writer.method(ctx, self.name, self.args, self.doc) + class DocClass(DocItem): def __init__(self, name, descr): super().__init__() @@ -240,51 +250,52 @@ class DocClass(DocItem): self.constants = {} def process_classmethod(self, lex, d): - name = d['id'] - if name == '\\constructor': + name = d["id"] + if name == "\\constructor": dict_ = self.constructors else: dict_ = self.classmethods if name in dict_: lex.error("multiple definition of method '{}'".format(name)) - method = dict_[name] = DocMethod(name, d['args']) + method = dict_[name] = DocMethod(name, d["args"]) method.add_doc(lex) def process_method(self, lex, d): - name = d['id'] + name = d["id"] dict_ = self.methods if name in dict_: lex.error("multiple definition of method '{}'".format(name)) - method = dict_[name] = DocMethod(name, d['args']) + method = dict_[name] = DocMethod(name, d["args"]) method.add_doc(lex) def process_constant(self, lex, d): - name = d['id'] + name = d["id"] if name in self.constants: lex.error("multiple definition of constant '{}'".format(name)) - self.constants[name] = DocConstant(name, d['descr']) + self.constants[name] = DocConstant(name, d["descr"]) lex.opt_break() def dump(self, writer): - writer.heading(1, 'class {}'.format(self.name)) + writer.heading(1, "class {}".format(self.name)) super().dump(writer) if len(self.constructors) > 0: - writer.heading(2, 'Constructors') - for f in sorted(self.constructors.values(), key=lambda x:x.name): + writer.heading(2, "Constructors") + for f in sorted(self.constructors.values(), key=lambda x: x.name): f.dump(self.name, writer) if len(self.classmethods) > 0: - writer.heading(2, 'Class methods') - for f in sorted(self.classmethods.values(), key=lambda x:x.name): + writer.heading(2, "Class methods") + for f in sorted(self.classmethods.values(), key=lambda x: x.name): f.dump(self.name, writer) if len(self.methods) > 0: - writer.heading(2, 'Methods') - for f in sorted(self.methods.values(), key=lambda x:x.name): + writer.heading(2, "Methods") + for f in sorted(self.methods.values(), key=lambda x: x.name): f.dump(self.name.lower(), writer) if len(self.constants) > 0: - writer.heading(2, 'Constants') - for c in sorted(self.constants.values(), key=lambda x:x.name): + writer.heading(2, "Constants") + for c in sorted(self.constants.values(), key=lambda x: x.name): c.dump(self.name, writer) + class DocModule(DocItem): def __init__(self, name, descr): super().__init__() @@ -299,22 +310,22 @@ class DocModule(DocItem): self.cur_class = None def process_function(self, lex, d): - name = d['id'] + name = d["id"] if name in self.functions: lex.error("multiple definition of function '{}'".format(name)) - function = self.functions[name] = DocFunction(name, d['args']) + function = self.functions[name] = DocFunction(name, d["args"]) function.add_doc(lex) - #def process_classref(self, lex, d): + # def process_classref(self, lex, d): # name = d['id'] # self.classes[name] = name # lex.opt_break() def process_class(self, lex, d): - name = d['id'] + name = d["id"] if name in self.classes: lex.error("multiple definition of class '{}'".format(name)) - self.cur_class = self.classes[name] = DocClass(name, d['descr']) + self.cur_class = self.classes[name] = DocClass(name, d["descr"]) self.cur_class.add_doc(lex) def process_classmethod(self, lex, d): @@ -326,10 +337,10 @@ class DocModule(DocItem): def process_constant(self, lex, d): if self.cur_class is None: # a module-level constant - name = d['id'] + name = d["id"] if name in self.constants: lex.error("multiple definition of constant '{}'".format(name)) - self.constants[name] = DocConstant(name, d['descr']) + self.constants[name] = DocConstant(name, d["descr"]) lex.opt_break() else: # a class-level constant @@ -337,50 +348,51 @@ class DocModule(DocItem): def validate(self): if self.descr is None: - raise DocValidateError('module {} referenced but never defined'.format(self.name)) + raise DocValidateError("module {} referenced but never defined".format(self.name)) def dump(self, writer): writer.module(self.name, self.descr, self.doc) if self.functions: - writer.heading(2, 'Functions') - for f in sorted(self.functions.values(), key=lambda x:x.name): + writer.heading(2, "Functions") + for f in sorted(self.functions.values(), key=lambda x: x.name): f.dump(self.name, writer) if self.constants: - writer.heading(2, 'Constants') - for c in sorted(self.constants.values(), key=lambda x:x.name): + writer.heading(2, "Constants") + for c in sorted(self.constants.values(), key=lambda x: x.name): c.dump(self.name, writer) if self.classes: - writer.heading(2, 'Classes') - for c in sorted(self.classes.values(), key=lambda x:x.name): - writer.para('[`{}.{}`]({}) - {}'.format(self.name, c.name, c.name, c.descr)) + writer.heading(2, "Classes") + for c in sorted(self.classes.values(), key=lambda x: x.name): + writer.para("[`{}.{}`]({}) - {}".format(self.name, c.name, c.name, c.descr)) def write_html(self, dir): md_writer = MarkdownWriter() md_writer.start() self.dump(md_writer) - with open(os.path.join(dir, 'index.html'), 'wt') as f: + with open(os.path.join(dir, "index.html"), "wt") as f: f.write(markdown.markdown(md_writer.end())) for c in self.classes.values(): class_dir = os.path.join(dir, c.name) makedirs(class_dir) md_writer.start() - md_writer.para('part of the [{} module](./)'.format(self.name)) + md_writer.para("part of the [{} module](./)".format(self.name)) c.dump(md_writer) - with open(os.path.join(class_dir, 'index.html'), 'wt') as f: + with open(os.path.join(class_dir, "index.html"), "wt") as f: f.write(markdown.markdown(md_writer.end())) def write_rst(self, dir): rst_writer = ReStructuredTextWriter() rst_writer.start() self.dump(rst_writer) - with open(dir + '/' + self.name + '.rst', 'wt') as f: + with open(dir + "/" + self.name + ".rst", "wt") as f: f.write(rst_writer.end()) for c in self.classes.values(): rst_writer.start() c.dump(rst_writer) - with open(dir + '/' + self.name + '.' + c.name + '.rst', 'wt') as f: + with open(dir + "/" + self.name + "." + c.name + ".rst", "wt") as f: f.write(rst_writer.end()) + class Doc: def __init__(self): self.modules = {} @@ -393,20 +405,20 @@ class Doc: def check_module(self, lex): if self.cur_module is None: - lex.error('module not defined') + lex.error("module not defined") def process_module(self, lex, d): - name = d['id'] + name = d["id"] if name not in self.modules: self.modules[name] = DocModule(name, None) self.cur_module = self.modules[name] if self.cur_module.descr is not None: lex.error("multiple definition of module '{}'".format(name)) - self.cur_module.descr = d['descr'] + self.cur_module.descr = d["descr"] self.cur_module.add_doc(lex) def process_moduleref(self, lex, d): - name = d['id'] + name = d["id"] if name not in self.modules: self.modules[name] = DocModule(name, None) self.cur_module = self.modules[name] @@ -437,41 +449,46 @@ class Doc: m.validate() def dump(self, writer): - writer.heading(1, 'Modules') - writer.para('These are the Python modules that are implemented.') - for m in sorted(self.modules.values(), key=lambda x:x.name): - writer.para('[`{}`]({}/) - {}'.format(m.name, m.name, m.descr)) + writer.heading(1, "Modules") + writer.para("These are the Python modules that are implemented.") + for m in sorted(self.modules.values(), key=lambda x: x.name): + writer.para("[`{}`]({}/) - {}".format(m.name, m.name, m.descr)) def write_html(self, dir): md_writer = MarkdownWriter() - with open(os.path.join(dir, 'module', 'index.html'), 'wt') as f: + with open(os.path.join(dir, "module", "index.html"), "wt") as f: md_writer.start() self.dump(md_writer) f.write(markdown.markdown(md_writer.end())) for m in self.modules.values(): - mod_dir = os.path.join(dir, 'module', m.name) + mod_dir = os.path.join(dir, "module", m.name) makedirs(mod_dir) m.write_html(mod_dir) def write_rst(self, dir): - #with open(os.path.join(dir, 'module', 'index.html'), 'wt') as f: + # with open(os.path.join(dir, 'module', 'index.html'), 'wt') as f: # f.write(markdown.markdown(self.dump())) for m in self.modules.values(): m.write_rst(dir) -regex_descr = r'(?P.*)' + +regex_descr = r"(?P.*)" doc_regexs = ( - (Doc.process_module, re.compile(r'\\module (?P[a-z][a-z0-9]*) - ' + regex_descr + r'$')), - (Doc.process_moduleref, re.compile(r'\\moduleref (?P[a-z]+)$')), - (Doc.process_function, re.compile(r'\\function (?P[a-z0-9_]+)(?P\(.*\))$')), - (Doc.process_classmethod, re.compile(r'\\classmethod (?P\\?[a-z0-9_]+)(?P\(.*\))$')), - (Doc.process_method, re.compile(r'\\method (?P\\?[a-z0-9_]+)(?P\(.*\))$')), - (Doc.process_constant, re.compile(r'\\constant (?P[A-Za-z0-9_]+) - ' + regex_descr + r'$')), - #(Doc.process_classref, re.compile(r'\\classref (?P[A-Za-z0-9_]+)$')), - (Doc.process_class, re.compile(r'\\class (?P[A-Za-z0-9_]+) - ' + regex_descr + r'$')), + (Doc.process_module, re.compile(r"\\module (?P[a-z][a-z0-9]*) - " + regex_descr + r"$")), + (Doc.process_moduleref, re.compile(r"\\moduleref (?P[a-z]+)$")), + (Doc.process_function, re.compile(r"\\function (?P[a-z0-9_]+)(?P\(.*\))$")), + (Doc.process_classmethod, re.compile(r"\\classmethod (?P\\?[a-z0-9_]+)(?P\(.*\))$")), + (Doc.process_method, re.compile(r"\\method (?P\\?[a-z0-9_]+)(?P\(.*\))$")), + ( + Doc.process_constant, + re.compile(r"\\constant (?P[A-Za-z0-9_]+) - " + regex_descr + r"$"), + ), + # (Doc.process_classref, re.compile(r'\\classref (?P[A-Za-z0-9_]+)$')), + (Doc.process_class, re.compile(r"\\class (?P[A-Za-z0-9_]+) - " + regex_descr + r"$")), ) + def process_file(file, doc): lex = Lexer(file) doc.new_file() @@ -481,11 +498,11 @@ def process_file(file, doc): line = lex.next() fun, match = re_match_first(doc_regexs, line) if fun == None: - lex.error('unknown line format: {}'.format(line)) + lex.error("unknown line format: {}".format(line)) fun(doc, lex, match.groupdict()) except Lexer.Break: - lex.error('unexpected break') + lex.error("unexpected break") except Lexer.EOF: pass @@ -495,16 +512,21 @@ def process_file(file, doc): return True + def main(): - cmd_parser = argparse.ArgumentParser(description='Generate documentation for pyboard API from C files.') - cmd_parser.add_argument('--outdir', metavar='', default='gendoc-out', help='ouput directory') - cmd_parser.add_argument('--format', default='html', help='output format: html or rst') - cmd_parser.add_argument('files', nargs='+', help='input files') + cmd_parser = argparse.ArgumentParser( + description="Generate documentation for pyboard API from C files." + ) + cmd_parser.add_argument( + "--outdir", metavar="", default="gendoc-out", help="ouput directory" + ) + cmd_parser.add_argument("--format", default="html", help="output format: html or rst") + cmd_parser.add_argument("files", nargs="+", help="input files") args = cmd_parser.parse_args() doc = Doc() for file in args.files: - print('processing', file) + print("processing", file) if not process_file(file, doc): return try: @@ -514,15 +536,16 @@ def main(): makedirs(args.outdir) - if args.format == 'html': + if args.format == "html": doc.write_html(args.outdir) - elif args.format == 'rst': + elif args.format == "rst": doc.write_rst(args.outdir) else: - print('unknown format:', args.format) + print("unknown format:", args.format) return - print('written to', args.outdir) + print("written to", args.outdir) + if __name__ == "__main__": main() diff --git a/tools/insert-usb-ids.py b/tools/insert-usb-ids.py index cdccd3be97..b1d848ad4e 100644 --- a/tools/insert-usb-ids.py +++ b/tools/insert-usb-ids.py @@ -8,15 +8,16 @@ import sys import re import string -needed_keys = ('USB_PID_CDC_MSC', 'USB_PID_CDC_HID', 'USB_PID_CDC', 'USB_VID') +needed_keys = ("USB_PID_CDC_MSC", "USB_PID_CDC_HID", "USB_PID_CDC", "USB_VID") + def parse_usb_ids(filename): rv = dict() for line in open(filename).readlines(): - line = line.rstrip('\r\n') - match = re.match('^#define\s+(\w+)\s+\(0x([0-9A-Fa-f]+)\)$', line) - if match and match.group(1).startswith('USBD_'): - key = match.group(1).replace('USBD', 'USB') + line = line.rstrip("\r\n") + match = re.match("^#define\s+(\w+)\s+\(0x([0-9A-Fa-f]+)\)$", line) + if match and match.group(1).startswith("USBD_"): + key = match.group(1).replace("USBD", "USB") val = match.group(2) print("key =", key, "val =", val) if key in needed_keys: @@ -26,9 +27,10 @@ def parse_usb_ids(filename): raise Exception("Unable to parse %s from %s" % (k, filename)) return rv + if __name__ == "__main__": usb_ids_file = sys.argv[1] template_file = sys.argv[2] replacements = parse_usb_ids(usb_ids_file) - for line in open(template_file, 'r').readlines(): - print(string.Template(line).safe_substitute(replacements), end='') + for line in open(template_file, "r").readlines(): + print(string.Template(line).safe_substitute(replacements), end="") diff --git a/tools/make-frozen.py b/tools/make-frozen.py index 1051b520e4..41cd304098 100755 --- a/tools/make-frozen.py +++ b/tools/make-frozen.py @@ -25,6 +25,7 @@ import os def module_name(f): return f + modules = [] root = sys.argv[1].rstrip("/") @@ -34,7 +35,7 @@ for dirpath, dirnames, filenames in os.walk(root): for f in filenames: fullpath = dirpath + "/" + f st = os.stat(fullpath) - modules.append((fullpath[root_len + 1:], st)) + modules.append((fullpath[root_len + 1 :], st)) print("#include ") print("const char mp_frozen_str_names[] = {") @@ -61,8 +62,8 @@ for f, st in modules: # data. We could just encode all characters as hex digits but it's nice # to be able to read the resulting C code as ASCII when possible. - data = bytearray(data) # so Python2 extracts each byte as an integer - esc_dict = {ord('\n'): '\\n', ord('\r'): '\\r', ord('"'): '\\"', ord('\\'): '\\\\'} + data = bytearray(data) # so Python2 extracts each byte as an integer + esc_dict = {ord("\n"): "\\n", ord("\r"): "\\r", ord('"'): '\\"', ord("\\"): "\\\\"} chrs = ['"'] break_str = False for c in data: @@ -75,9 +76,9 @@ for f, st in modules: break_str = False chrs.append(chr(c)) else: - chrs.append('\\x%02x' % c) + chrs.append("\\x%02x" % c) break_str = True chrs.append('\\0"') - print(''.join(chrs)) + print("".join(chrs)) print("};") diff --git a/tools/mpy-tool.py b/tools/mpy-tool.py index 6fbb10a39d..d839aa5d3c 100755 --- a/tools/mpy-tool.py +++ b/tools/mpy-tool.py @@ -27,7 +27,8 @@ # Python 2/3 compatibility code from __future__ import print_function import platform -if platform.python_version_tuple()[0] == '2': + +if platform.python_version_tuple()[0] == "2": str_cons = lambda val, enc=None: val bytes_cons = lambda val, enc=None: bytearray(val) is_str_type = lambda o: type(o) is str @@ -45,22 +46,26 @@ import sys import struct from collections import namedtuple -sys.path.append(sys.path[0] + '/../py') +sys.path.append(sys.path[0] + "/../py") import makeqstrdata as qstrutil + class FreezeError(Exception): def __init__(self, rawcode, msg): self.rawcode = rawcode self.msg = msg def __str__(self): - return 'error while freezing %s: %s' % (self.rawcode.source_file, self.msg) + return "error while freezing %s: %s" % (self.rawcode.source_file, self.msg) + class Config: MPY_VERSION = 3 MICROPY_LONGINT_IMPL_NONE = 0 MICROPY_LONGINT_IMPL_LONGLONG = 1 MICROPY_LONGINT_IMPL_MPZ = 2 + + config = Config() MP_OPCODE_BYTE = 0 @@ -71,94 +76,93 @@ MP_OPCODE_OFFSET = 3 # extra bytes: MP_BC_MAKE_CLOSURE = 0x62 MP_BC_MAKE_CLOSURE_DEFARGS = 0x63 -MP_BC_RAISE_VARARGS = 0x5c +MP_BC_RAISE_VARARGS = 0x5C # extra byte if caching enabled: -MP_BC_LOAD_NAME = 0x1b -MP_BC_LOAD_GLOBAL = 0x1c -MP_BC_LOAD_ATTR = 0x1d +MP_BC_LOAD_NAME = 0x1B +MP_BC_LOAD_GLOBAL = 0x1C +MP_BC_LOAD_ATTR = 0x1D MP_BC_STORE_ATTR = 0x26 + def make_opcode_format(): def OC4(a, b, c, d): return a | (b << 2) | (c << 4) | (d << 6) + U = 0 B = 0 Q = 1 V = 2 O = 3 - return bytes_cons(( - # this table is taken verbatim from py/bc.c - OC4(U, U, U, U), # 0x00-0x03 - OC4(U, U, U, U), # 0x04-0x07 - OC4(U, U, U, U), # 0x08-0x0b - OC4(U, U, U, U), # 0x0c-0x0f - OC4(B, B, B, U), # 0x10-0x13 - OC4(V, U, Q, V), # 0x14-0x17 - OC4(B, V, V, Q), # 0x18-0x1b - OC4(Q, Q, Q, Q), # 0x1c-0x1f - OC4(B, B, V, V), # 0x20-0x23 - OC4(Q, Q, Q, B), # 0x24-0x27 - OC4(V, V, Q, Q), # 0x28-0x2b - OC4(U, U, U, U), # 0x2c-0x2f - OC4(B, B, B, B), # 0x30-0x33 - OC4(B, O, O, O), # 0x34-0x37 - OC4(O, O, U, U), # 0x38-0x3b - OC4(U, O, B, O), # 0x3c-0x3f - OC4(O, B, B, O), # 0x40-0x43 - OC4(B, B, O, B), # 0x44-0x47 - OC4(U, U, U, U), # 0x48-0x4b - OC4(U, U, U, U), # 0x4c-0x4f - OC4(V, V, U, V), # 0x50-0x53 - OC4(B, U, V, V), # 0x54-0x57 - OC4(V, V, V, B), # 0x58-0x5b - OC4(B, B, B, U), # 0x5c-0x5f - OC4(V, V, V, V), # 0x60-0x63 - OC4(V, V, V, V), # 0x64-0x67 - OC4(Q, Q, B, U), # 0x68-0x6b - OC4(U, U, U, U), # 0x6c-0x6f + return bytes_cons( + ( + # this table is taken verbatim from py/bc.c + OC4(U, U, U, U), # 0x00-0x03 + OC4(U, U, U, U), # 0x04-0x07 + OC4(U, U, U, U), # 0x08-0x0b + OC4(U, U, U, U), # 0x0c-0x0f + OC4(B, B, B, U), # 0x10-0x13 + OC4(V, U, Q, V), # 0x14-0x17 + OC4(B, V, V, Q), # 0x18-0x1b + OC4(Q, Q, Q, Q), # 0x1c-0x1f + OC4(B, B, V, V), # 0x20-0x23 + OC4(Q, Q, Q, B), # 0x24-0x27 + OC4(V, V, Q, Q), # 0x28-0x2b + OC4(U, U, U, U), # 0x2c-0x2f + OC4(B, B, B, B), # 0x30-0x33 + OC4(B, O, O, O), # 0x34-0x37 + OC4(O, O, U, U), # 0x38-0x3b + OC4(U, O, B, O), # 0x3c-0x3f + OC4(O, B, B, O), # 0x40-0x43 + OC4(B, B, O, B), # 0x44-0x47 + OC4(U, U, U, U), # 0x48-0x4b + OC4(U, U, U, U), # 0x4c-0x4f + OC4(V, V, U, V), # 0x50-0x53 + OC4(B, U, V, V), # 0x54-0x57 + OC4(V, V, V, B), # 0x58-0x5b + OC4(B, B, B, U), # 0x5c-0x5f + OC4(V, V, V, V), # 0x60-0x63 + OC4(V, V, V, V), # 0x64-0x67 + OC4(Q, Q, B, U), # 0x68-0x6b + OC4(U, U, U, U), # 0x6c-0x6f + OC4(B, B, B, B), # 0x70-0x73 + OC4(B, B, B, B), # 0x74-0x77 + OC4(B, B, B, B), # 0x78-0x7b + OC4(B, B, B, B), # 0x7c-0x7f + OC4(B, B, B, B), # 0x80-0x83 + OC4(B, B, B, B), # 0x84-0x87 + OC4(B, B, B, B), # 0x88-0x8b + OC4(B, B, B, B), # 0x8c-0x8f + OC4(B, B, B, B), # 0x90-0x93 + OC4(B, B, B, B), # 0x94-0x97 + OC4(B, B, B, B), # 0x98-0x9b + OC4(B, B, B, B), # 0x9c-0x9f + OC4(B, B, B, B), # 0xa0-0xa3 + OC4(B, B, B, B), # 0xa4-0xa7 + OC4(B, B, B, B), # 0xa8-0xab + OC4(B, B, B, B), # 0xac-0xaf + OC4(B, B, B, B), # 0xb0-0xb3 + OC4(B, B, B, B), # 0xb4-0xb7 + OC4(B, B, B, B), # 0xb8-0xbb + OC4(B, B, B, B), # 0xbc-0xbf + OC4(B, B, B, B), # 0xc0-0xc3 + OC4(B, B, B, B), # 0xc4-0xc7 + OC4(B, B, B, B), # 0xc8-0xcb + OC4(B, B, B, B), # 0xcc-0xcf + OC4(B, B, B, B), # 0xd0-0xd3 + OC4(U, U, U, B), # 0xd4-0xd7 + OC4(B, B, B, B), # 0xd8-0xdb + OC4(B, B, B, B), # 0xdc-0xdf + OC4(B, B, B, B), # 0xe0-0xe3 + OC4(B, B, B, B), # 0xe4-0xe7 + OC4(B, B, B, B), # 0xe8-0xeb + OC4(B, B, B, B), # 0xec-0xef + OC4(B, B, B, B), # 0xf0-0xf3 + OC4(B, B, B, B), # 0xf4-0xf7 + OC4(U, U, U, U), # 0xf8-0xfb + OC4(U, U, U, U), # 0xfc-0xff + ) + ) - OC4(B, B, B, B), # 0x70-0x73 - OC4(B, B, B, B), # 0x74-0x77 - OC4(B, B, B, B), # 0x78-0x7b - OC4(B, B, B, B), # 0x7c-0x7f - OC4(B, B, B, B), # 0x80-0x83 - OC4(B, B, B, B), # 0x84-0x87 - OC4(B, B, B, B), # 0x88-0x8b - OC4(B, B, B, B), # 0x8c-0x8f - OC4(B, B, B, B), # 0x90-0x93 - OC4(B, B, B, B), # 0x94-0x97 - OC4(B, B, B, B), # 0x98-0x9b - OC4(B, B, B, B), # 0x9c-0x9f - OC4(B, B, B, B), # 0xa0-0xa3 - OC4(B, B, B, B), # 0xa4-0xa7 - OC4(B, B, B, B), # 0xa8-0xab - OC4(B, B, B, B), # 0xac-0xaf - - OC4(B, B, B, B), # 0xb0-0xb3 - OC4(B, B, B, B), # 0xb4-0xb7 - OC4(B, B, B, B), # 0xb8-0xbb - OC4(B, B, B, B), # 0xbc-0xbf - - OC4(B, B, B, B), # 0xc0-0xc3 - OC4(B, B, B, B), # 0xc4-0xc7 - OC4(B, B, B, B), # 0xc8-0xcb - OC4(B, B, B, B), # 0xcc-0xcf - - OC4(B, B, B, B), # 0xd0-0xd3 - OC4(U, U, U, B), # 0xd4-0xd7 - OC4(B, B, B, B), # 0xd8-0xdb - OC4(B, B, B, B), # 0xdc-0xdf - - OC4(B, B, B, B), # 0xe0-0xe3 - OC4(B, B, B, B), # 0xe4-0xe7 - OC4(B, B, B, B), # 0xe8-0xeb - OC4(B, B, B, B), # 0xec-0xef - - OC4(B, B, B, B), # 0xf0-0xf3 - OC4(B, B, B, B), # 0xf4-0xf7 - OC4(U, U, U, U), # 0xf8-0xfb - OC4(U, U, U, U), # 0xfc-0xff - )) # this function mirrors that in py/bc.c def mp_opcode_format(bytecode, ip, opcode_format=make_opcode_format()): @@ -167,10 +171,12 @@ def mp_opcode_format(bytecode, ip, opcode_format=make_opcode_format()): f = (opcode_format[opcode >> 2] >> (2 * (opcode & 3))) & 3 if f == MP_OPCODE_QSTR: if config.MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE: - if (opcode == MP_BC_LOAD_NAME + if ( + opcode == MP_BC_LOAD_NAME or opcode == MP_BC_LOAD_GLOBAL or opcode == MP_BC_LOAD_ATTR - or opcode == MP_BC_STORE_ATTR): + or opcode == MP_BC_STORE_ATTR + ): ip += 1 ip += 3 else: @@ -189,32 +195,51 @@ def mp_opcode_format(bytecode, ip, opcode_format=make_opcode_format()): ip += extra_byte return f, ip - ip_start + def decode_uint(bytecode, ip): unum = 0 while True: val = bytecode[ip] ip += 1 - unum = (unum << 7) | (val & 0x7f) + unum = (unum << 7) | (val & 0x7F) if not (val & 0x80): break return ip, unum + def extract_prelude(bytecode): ip = 0 ip, n_state = decode_uint(bytecode, ip) ip, n_exc_stack = decode_uint(bytecode, ip) - scope_flags = bytecode[ip]; ip += 1 - n_pos_args = bytecode[ip]; ip += 1 - n_kwonly_args = bytecode[ip]; ip += 1 - n_def_pos_args = bytecode[ip]; ip += 1 + scope_flags = bytecode[ip] + ip += 1 + n_pos_args = bytecode[ip] + ip += 1 + n_kwonly_args = bytecode[ip] + ip += 1 + n_def_pos_args = bytecode[ip] + ip += 1 ip2, code_info_size = decode_uint(bytecode, ip) ip += code_info_size - while bytecode[ip] != 0xff: + while bytecode[ip] != 0xFF: ip += 1 ip += 1 # ip now points to first opcode # ip2 points to simple_name qstr - return ip, ip2, (n_state, n_exc_stack, scope_flags, n_pos_args, n_kwonly_args, n_def_pos_args, code_info_size) + return ( + ip, + ip2, + ( + n_state, + n_exc_stack, + scope_flags, + n_pos_args, + n_kwonly_args, + n_def_pos_args, + code_info_size, + ), + ) + class RawCode: # a set of all escaped names, to make sure they are unique @@ -239,7 +264,7 @@ class RawCode: def dump(self): # dump children first for rc in self.raw_codes: - rc.freeze('') + rc.freeze("") # TODO def freeze(self, parent_name): @@ -254,58 +279,68 @@ class RawCode: # emit children first for rc in self.raw_codes: - rc.freeze(self.escaped_name + '_') + rc.freeze(self.escaped_name + "_") # generate bytecode data print() - print('// frozen bytecode for file %s, scope %s%s' % (self.source_file.str, parent_name, self.simple_name.str)) - print('STATIC ', end='') + print( + "// frozen bytecode for file %s, scope %s%s" + % (self.source_file.str, parent_name, self.simple_name.str) + ) + print("STATIC ", end="") if not config.MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE: - print('const ', end='') - print('byte bytecode_data_%s[%u] = {' % (self.escaped_name, len(self.bytecode))) - print(' ', end='') + print("const ", end="") + print("byte bytecode_data_%s[%u] = {" % (self.escaped_name, len(self.bytecode))) + print(" ", end="") for i in range(self.ip2): - print(' 0x%02x,' % self.bytecode[i], end='') + print(" 0x%02x," % self.bytecode[i], end="") print() - print(' ', self.simple_name.qstr_id, '& 0xff,', self.simple_name.qstr_id, '>> 8,') - print(' ', self.source_file.qstr_id, '& 0xff,', self.source_file.qstr_id, '>> 8,') - print(' ', end='') + print(" ", self.simple_name.qstr_id, "& 0xff,", self.simple_name.qstr_id, ">> 8,") + print(" ", self.source_file.qstr_id, "& 0xff,", self.source_file.qstr_id, ">> 8,") + print(" ", end="") for i in range(self.ip2 + 4, self.ip): - print(' 0x%02x,' % self.bytecode[i], end='') + print(" 0x%02x," % self.bytecode[i], end="") print() ip = self.ip while ip < len(self.bytecode): f, sz = mp_opcode_format(self.bytecode, ip) if f == 1: qst = self._unpack_qstr(ip + 1).qstr_id - extra = '' if sz == 3 else ' 0x%02x,' % self.bytecode[ip + 3] - print(' ', '0x%02x,' % self.bytecode[ip], qst, '& 0xff,', qst, '>> 8,', extra) + extra = "" if sz == 3 else " 0x%02x," % self.bytecode[ip + 3] + print(" ", "0x%02x," % self.bytecode[ip], qst, "& 0xff,", qst, ">> 8,", extra) else: - print(' ', ''.join('0x%02x, ' % self.bytecode[ip + i] for i in range(sz))) + print(" ", "".join("0x%02x, " % self.bytecode[ip + i] for i in range(sz))) ip += sz - print('};') + print("};") # generate constant objects for i, obj in enumerate(self.objs): - obj_name = 'const_obj_%s_%u' % (self.escaped_name, i) + obj_name = "const_obj_%s_%u" % (self.escaped_name, i) if obj is Ellipsis: - print('#define %s mp_const_ellipsis_obj' % obj_name) + print("#define %s mp_const_ellipsis_obj" % obj_name) elif is_str_type(obj) or is_bytes_type(obj): if is_str_type(obj): - obj = bytes_cons(obj, 'utf8') - obj_type = 'mp_type_str' + obj = bytes_cons(obj, "utf8") + obj_type = "mp_type_str" else: - obj_type = 'mp_type_bytes' - print('STATIC const mp_obj_str_t %s = {{&%s}, %u, %u, (const byte*)"%s"};' - % (obj_name, obj_type, qstrutil.compute_hash(obj, config.MICROPY_QSTR_BYTES_IN_HASH), - len(obj), ''.join(('\\x%02x' % b) for b in obj))) + obj_type = "mp_type_bytes" + print( + 'STATIC const mp_obj_str_t %s = {{&%s}, %u, %u, (const byte*)"%s"};' + % ( + obj_name, + obj_type, + qstrutil.compute_hash(obj, config.MICROPY_QSTR_BYTES_IN_HASH), + len(obj), + "".join(("\\x%02x" % b) for b in obj), + ) + ) elif is_int_type(obj): if config.MICROPY_LONGINT_IMPL == config.MICROPY_LONGINT_IMPL_NONE: # TODO check if we can actually fit this long-int into a small-int - raise FreezeError(self, 'target does not support long int') + raise FreezeError(self, "target does not support long int") elif config.MICROPY_LONGINT_IMPL == config.MICROPY_LONGINT_IMPL_LONGLONG: # TODO - raise FreezeError(self, 'freezing int to long-long is not implemented') + raise FreezeError(self, "freezing int to long-long is not implemented") elif config.MICROPY_LONGINT_IMPL == config.MICROPY_LONGINT_IMPL_MPZ: neg = 0 if obj < 0: @@ -318,110 +353,128 @@ class RawCode: digs.append(z & ((1 << bits_per_dig) - 1)) z >>= bits_per_dig ndigs = len(digs) - digs = ','.join(('%#x' % d) for d in digs) - print('STATIC const mp_obj_int_t %s = {{&mp_type_int}, ' - '{.neg=%u, .fixed_dig=1, .alloc=%u, .len=%u, .dig=(uint%u_t*)(const uint%u_t[]){%s}}};' - % (obj_name, neg, ndigs, ndigs, bits_per_dig, bits_per_dig, digs)) + digs = ",".join(("%#x" % d) for d in digs) + print( + "STATIC const mp_obj_int_t %s = {{&mp_type_int}, " + "{.neg=%u, .fixed_dig=1, .alloc=%u, .len=%u, .dig=(uint%u_t*)(const uint%u_t[]){%s}}};" + % (obj_name, neg, ndigs, ndigs, bits_per_dig, bits_per_dig, digs) + ) elif type(obj) is float: - print('#if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_A || MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_B') - print('STATIC const mp_obj_float_t %s = {{&mp_type_float}, %.16g};' - % (obj_name, obj)) - print('#endif') + print( + "#if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_A || MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_B" + ) + print( + "STATIC const mp_obj_float_t %s = {{&mp_type_float}, %.16g};" % (obj_name, obj) + ) + print("#endif") elif type(obj) is complex: - print('STATIC const mp_obj_complex_t %s = {{&mp_type_complex}, %.16g, %.16g};' - % (obj_name, obj.real, obj.imag)) + print( + "STATIC const mp_obj_complex_t %s = {{&mp_type_complex}, %.16g, %.16g};" + % (obj_name, obj.real, obj.imag) + ) else: - raise FreezeError(self, 'freezing of object %r is not implemented' % (obj,)) + raise FreezeError(self, "freezing of object %r is not implemented" % (obj,)) # generate constant table, if it has any entries const_table_len = len(self.qstrs) + len(self.objs) + len(self.raw_codes) if const_table_len: - print('STATIC const mp_rom_obj_t const_table_data_%s[%u] = {' - % (self.escaped_name, const_table_len)) + print( + "STATIC const mp_rom_obj_t const_table_data_%s[%u] = {" + % (self.escaped_name, const_table_len) + ) for qst in self.qstrs: - print(' MP_ROM_QSTR(%s),' % global_qstrs[qst].qstr_id) + print(" MP_ROM_QSTR(%s)," % global_qstrs[qst].qstr_id) for i in range(len(self.objs)): if type(self.objs[i]) is float: - print('#if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_A || MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_B') - print(' MP_ROM_PTR(&const_obj_%s_%u),' % (self.escaped_name, i)) - print('#elif MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_C') - n = struct.unpack('> 8 + def read_bytecode_qstrs(file, bytecode, ip): while ip < len(bytecode): f, sz = mp_opcode_format(bytecode, ip) @@ -429,12 +482,13 @@ def read_bytecode_qstrs(file, bytecode, ip): read_qstr_and_pack(file, bytecode, ip + 1) ip += sz + def read_raw_code(f): bc_len = read_uint(f) bytecode = bytearray(f.read(bc_len)) ip, ip2, prelude = extract_prelude(bytecode) - read_qstr_and_pack(f, bytecode, ip2) # simple_name - read_qstr_and_pack(f, bytecode, ip2 + 2) # source_file + read_qstr_and_pack(f, bytecode, ip2) # simple_name + read_qstr_and_pack(f, bytecode, ip2 + 2) # source_file read_bytecode_qstrs(f, bytecode, ip) n_obj = read_uint(f) n_raw_code = read_uint(f) @@ -443,23 +497,26 @@ def read_raw_code(f): raw_codes = [read_raw_code(f) for _ in range(n_raw_code)] return RawCode(bytecode, qstrs, objs, raw_codes) + def read_mpy(filename): - with open(filename, 'rb') as f: + with open(filename, "rb") as f: header = bytes_cons(f.read(4)) - if header[0] != ord('M'): - raise Exception('not a valid .mpy file') + if header[0] != ord("M"): + raise Exception("not a valid .mpy file") if header[1] != config.MPY_VERSION: - raise Exception('incompatible .mpy version') + raise Exception("incompatible .mpy version") feature_flags = header[2] config.MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE = (feature_flags & 1) != 0 config.MICROPY_PY_BUILTINS_STR_UNICODE = (feature_flags & 2) != 0 config.mp_small_int_bits = header[3] return read_raw_code(f) + def dump_mpy(raw_codes): for rc in raw_codes: rc.dump() + def freeze_mpy(base_qstrs, raw_codes): # add to qstrs new = {} @@ -476,111 +533,124 @@ def freeze_mpy(base_qstrs, raw_codes): print('#include "py/emitglue.h"') print() - print('#if MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE != %u' % config.MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE) + print( + "#if MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE != %u" + % config.MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE + ) print('#error "incompatible MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE"') - print('#endif') + print("#endif") print() - print('#if MICROPY_LONGINT_IMPL != %u' % config.MICROPY_LONGINT_IMPL) + print("#if MICROPY_LONGINT_IMPL != %u" % config.MICROPY_LONGINT_IMPL) print('#error "incompatible MICROPY_LONGINT_IMPL"') - print('#endif') + print("#endif") print() if config.MICROPY_LONGINT_IMPL == config.MICROPY_LONGINT_IMPL_MPZ: - print('#if MPZ_DIG_SIZE != %u' % config.MPZ_DIG_SIZE) + print("#if MPZ_DIG_SIZE != %u" % config.MPZ_DIG_SIZE) print('#error "incompatible MPZ_DIG_SIZE"') - print('#endif') + print("#endif") print() - - print('#if MICROPY_PY_BUILTINS_FLOAT') - print('typedef struct _mp_obj_float_t {') - print(' mp_obj_base_t base;') - print(' mp_float_t value;') - print('} mp_obj_float_t;') - print('#endif') + print("#if MICROPY_PY_BUILTINS_FLOAT") + print("typedef struct _mp_obj_float_t {") + print(" mp_obj_base_t base;") + print(" mp_float_t value;") + print("} mp_obj_float_t;") + print("#endif") print() - print('#if MICROPY_PY_BUILTINS_COMPLEX') - print('typedef struct _mp_obj_complex_t {') - print(' mp_obj_base_t base;') - print(' mp_float_t real;') - print(' mp_float_t imag;') - print('} mp_obj_complex_t;') - print('#endif') + print("#if MICROPY_PY_BUILTINS_COMPLEX") + print("typedef struct _mp_obj_complex_t {") + print(" mp_obj_base_t base;") + print(" mp_float_t real;") + print(" mp_float_t imag;") + print("} mp_obj_complex_t;") + print("#endif") print() if len(new) > 0: - print('enum {') + print("enum {") for i in range(len(new)): if i == 0: - print(' MP_QSTR_%s = MP_QSTRnumber_of,' % new[i][1]) + print(" MP_QSTR_%s = MP_QSTRnumber_of," % new[i][1]) else: - print(' MP_QSTR_%s,' % new[i][1]) - print('};') + print(" MP_QSTR_%s," % new[i][1]) + print("};") # As in qstr.c, set so that the first dynamically allocated pool is twice this size; must be <= the len qstr_pool_alloc = min(len(new), 10) print() - print('extern const qstr_pool_t mp_qstr_const_pool;'); - print('const qstr_pool_t mp_qstr_frozen_const_pool = {') - print(' (qstr_pool_t*)&mp_qstr_const_pool, // previous pool') - print(' MP_QSTRnumber_of, // previous pool size') - print(' %u, // allocated entries' % qstr_pool_alloc) - print(' %u, // used entries' % len(new)) - print(' {') + print("extern const qstr_pool_t mp_qstr_const_pool;") + print("const qstr_pool_t mp_qstr_frozen_const_pool = {") + print(" (qstr_pool_t*)&mp_qstr_const_pool, // previous pool") + print(" MP_QSTRnumber_of, // previous pool size") + print(" %u, // allocated entries" % qstr_pool_alloc) + print(" %u, // used entries" % len(new)) + print(" {") for _, _, qstr in new: - print(' %s,' - % qstrutil.make_bytes(config.MICROPY_QSTR_BYTES_IN_LEN, config.MICROPY_QSTR_BYTES_IN_HASH, qstr)) - print(' },') - print('};') + print( + " %s," + % qstrutil.make_bytes( + config.MICROPY_QSTR_BYTES_IN_LEN, config.MICROPY_QSTR_BYTES_IN_HASH, qstr + ) + ) + print(" },") + print("};") for rc in raw_codes: - rc.freeze(rc.source_file.str.replace('/', '_')[:-3] + '_') + rc.freeze(rc.source_file.str.replace("/", "_")[:-3] + "_") print() - print('const char mp_frozen_mpy_names[] = {') + print("const char mp_frozen_mpy_names[] = {") for rc in raw_codes: module_name = rc.source_file.str print('"%s\\0"' % module_name) print('"\\0"};') - print('const mp_raw_code_t *const mp_frozen_mpy_content[] = {') + print("const mp_raw_code_t *const mp_frozen_mpy_content[] = {") for rc in raw_codes: - print(' &raw_code_%s,' % rc.escaped_name) - print('};') + print(" &raw_code_%s," % rc.escaped_name) + print("};") + def main(): import argparse - cmd_parser = argparse.ArgumentParser(description='A tool to work with MicroPython .mpy files.') - cmd_parser.add_argument('-d', '--dump', action='store_true', - help='dump contents of files') - cmd_parser.add_argument('-f', '--freeze', action='store_true', - help='freeze files') - cmd_parser.add_argument('-q', '--qstr-header', - help='qstr header file to freeze against') - cmd_parser.add_argument('-mlongint-impl', choices=['none', 'longlong', 'mpz'], default='mpz', - help='long-int implementation used by target (default mpz)') - cmd_parser.add_argument('-mmpz-dig-size', metavar='N', type=int, default=16, - help='mpz digit size used by target (default 16)') - cmd_parser.add_argument('files', nargs='+', - help='input .mpy files') + + cmd_parser = argparse.ArgumentParser(description="A tool to work with MicroPython .mpy files.") + cmd_parser.add_argument("-d", "--dump", action="store_true", help="dump contents of files") + cmd_parser.add_argument("-f", "--freeze", action="store_true", help="freeze files") + cmd_parser.add_argument("-q", "--qstr-header", help="qstr header file to freeze against") + cmd_parser.add_argument( + "-mlongint-impl", + choices=["none", "longlong", "mpz"], + default="mpz", + help="long-int implementation used by target (default mpz)", + ) + cmd_parser.add_argument( + "-mmpz-dig-size", + metavar="N", + type=int, + default=16, + help="mpz digit size used by target (default 16)", + ) + cmd_parser.add_argument("files", nargs="+", help="input .mpy files") args = cmd_parser.parse_args() # set config values relevant to target machine config.MICROPY_LONGINT_IMPL = { - 'none':config.MICROPY_LONGINT_IMPL_NONE, - 'longlong':config.MICROPY_LONGINT_IMPL_LONGLONG, - 'mpz':config.MICROPY_LONGINT_IMPL_MPZ, + "none": config.MICROPY_LONGINT_IMPL_NONE, + "longlong": config.MICROPY_LONGINT_IMPL_LONGLONG, + "mpz": config.MICROPY_LONGINT_IMPL_MPZ, }[args.mlongint_impl] config.MPZ_DIG_SIZE = args.mmpz_dig_size # set config values for qstrs, and get the existing base set of qstrs if args.qstr_header: qcfgs, base_qstrs = qstrutil.parse_input_headers([args.qstr_header]) - config.MICROPY_QSTR_BYTES_IN_LEN = int(qcfgs['BYTES_IN_LEN']) - config.MICROPY_QSTR_BYTES_IN_HASH = int(qcfgs['BYTES_IN_HASH']) + config.MICROPY_QSTR_BYTES_IN_LEN = int(qcfgs["BYTES_IN_LEN"]) + config.MICROPY_QSTR_BYTES_IN_HASH = int(qcfgs["BYTES_IN_HASH"]) else: config.MICROPY_QSTR_BYTES_IN_LEN = 1 config.MICROPY_QSTR_BYTES_IN_HASH = 1 @@ -597,5 +667,6 @@ def main(): print(er, file=sys.stderr) sys.exit(1) -if __name__ == '__main__': + +if __name__ == "__main__": main() diff --git a/tools/mpy_cross_all.py b/tools/mpy_cross_all.py index 2bda71e9bc..d542bde42e 100755 --- a/tools/mpy_cross_all.py +++ b/tools/mpy_cross_all.py @@ -6,7 +6,9 @@ import os.path argparser = argparse.ArgumentParser(description="Compile all .py files to .mpy recursively") argparser.add_argument("-o", "--out", help="output directory (default: input dir)") argparser.add_argument("--target", help="select MicroPython target config") -argparser.add_argument("-mcache-lookup-bc", action="store_true", help="cache map lookups in the bytecode") +argparser.add_argument( + "-mcache-lookup-bc", action="store_true", help="cache map lookups in the bytecode" +) argparser.add_argument("dir", help="input directory") args = argparser.parse_args() @@ -26,13 +28,17 @@ for path, subdirs, files in os.walk(args.dir): for f in files: if f.endswith(".py"): fpath = path + "/" + f - #print(fpath) + # print(fpath) out_fpath = args.out + "/" + fpath[path_prefix_len:-3] + ".mpy" out_dir = os.path.dirname(out_fpath) if not os.path.isdir(out_dir): os.makedirs(out_dir) - cmd = "mpy-cross -v -v %s -s %s %s -o %s" % (TARGET_OPTS.get(args.target, ""), - fpath[path_prefix_len:], fpath, out_fpath) - #print(cmd) + cmd = "mpy-cross -v -v %s -s %s %s -o %s" % ( + TARGET_OPTS.get(args.target, ""), + fpath[path_prefix_len:], + fpath, + out_fpath, + ) + # print(cmd) res = os.system(cmd) assert res == 0 diff --git a/tools/pyboard.py b/tools/pyboard.py index 86a07a151c..e74ebb52ae 100755 --- a/tools/pyboard.py +++ b/tools/pyboard.py @@ -76,35 +76,42 @@ except AttributeError: # Python2 doesn't have buffer attr stdout = sys.stdout + def stdout_write_bytes(b): b = b.replace(b"\x04", b"") stdout.write(b) stdout.flush() + class PyboardError(Exception): pass + class TelnetToSerial: def __init__(self, ip, user, password, read_timeout=None): self.tn = None import telnetlib + self.tn = telnetlib.Telnet(ip, timeout=15) self.read_timeout = read_timeout - if b'Login as:' in self.tn.read_until(b'Login as:', timeout=read_timeout): - self.tn.write(bytes(user, 'ascii') + b"\r\n") + if b"Login as:" in self.tn.read_until(b"Login as:", timeout=read_timeout): + self.tn.write(bytes(user, "ascii") + b"\r\n") - if b'Password:' in self.tn.read_until(b'Password:', timeout=read_timeout): + if b"Password:" in self.tn.read_until(b"Password:", timeout=read_timeout): # needed because of internal implementation details of the telnet server time.sleep(0.2) - self.tn.write(bytes(password, 'ascii') + b"\r\n") + self.tn.write(bytes(password, "ascii") + b"\r\n") - if b'for more information.' in self.tn.read_until(b'Type "help()" for more information.', timeout=read_timeout): + if b"for more information." in self.tn.read_until( + b'Type "help()" for more information.', timeout=read_timeout + ): # login successful from collections import deque + self.fifo = deque() return - raise PyboardError('Failed to establish a telnet connection with the board') + raise PyboardError("Failed to establish a telnet connection with the board") def __del__(self): self.close() @@ -126,7 +133,7 @@ class TelnetToSerial: break timeout_count += 1 - data = b'' + data = b"" while len(data) < size and len(self.fifo) > 0: data += bytes([self.fifo.popleft()]) return data @@ -150,24 +157,33 @@ class ProcessToSerial: def __init__(self, cmd): import subprocess - self.subp = subprocess.Popen(cmd, bufsize=0, shell=True, preexec_fn=os.setsid, - stdin=subprocess.PIPE, stdout=subprocess.PIPE) + + self.subp = subprocess.Popen( + cmd, + bufsize=0, + shell=True, + preexec_fn=os.setsid, + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + ) # Initially was implemented with selectors, but that adds Python3 # dependency. However, there can be race conditions communicating # with a particular child process (like QEMU), and selectors may # still work better in that case, so left inplace for now. # - #import selectors - #self.sel = selectors.DefaultSelector() - #self.sel.register(self.subp.stdout, selectors.EVENT_READ) + # import selectors + # self.sel = selectors.DefaultSelector() + # self.sel.register(self.subp.stdout, selectors.EVENT_READ) import select + self.poll = select.poll() self.poll.register(self.subp.stdout.fileno()) def close(self): import signal + os.killpg(os.getpgid(self.subp.pid), signal.SIGTERM) def read(self, size=1): @@ -181,7 +197,7 @@ class ProcessToSerial: return len(data) def inWaiting(self): - #res = self.sel.select(0) + # res = self.sel.select(0) res = self.poll.poll(0) if res: return 1 @@ -197,8 +213,16 @@ class ProcessPtyToTerminal: import subprocess import re import serial - self.subp = subprocess.Popen(cmd.split(), bufsize=0, shell=False, preexec_fn=os.setsid, - stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + + self.subp = subprocess.Popen( + cmd.split(), + bufsize=0, + shell=False, + preexec_fn=os.setsid, + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + ) pty_line = self.subp.stderr.readline().decode("utf-8") m = re.search(r"/dev/pts/[0-9]+", pty_line) if not m: @@ -212,6 +236,7 @@ class ProcessPtyToTerminal: def close(self): import signal + os.killpg(os.getpgid(self.subp.pid), signal.SIGTERM) def read(self, size=1): @@ -225,36 +250,37 @@ class ProcessPtyToTerminal: class Pyboard: - def __init__(self, device, baudrate=115200, user='micro', password='python', wait=0): + def __init__(self, device, baudrate=115200, user="micro", password="python", wait=0): if device.startswith("exec:"): - self.serial = ProcessToSerial(device[len("exec:"):]) + self.serial = ProcessToSerial(device[len("exec:") :]) elif device.startswith("execpty:"): - self.serial = ProcessPtyToTerminal(device[len("qemupty:"):]) - elif device and device[0].isdigit() and device[-1].isdigit() and device.count('.') == 3: + self.serial = ProcessPtyToTerminal(device[len("qemupty:") :]) + elif device and device[0].isdigit() and device[-1].isdigit() and device.count(".") == 3: # device looks like an IP address self.serial = TelnetToSerial(device, user, password, read_timeout=10) else: import serial + delayed = False for attempt in range(wait + 1): try: self.serial = serial.Serial(device, baudrate=baudrate, interCharTimeout=1) break - except (OSError, IOError): # Py2 and Py3 have different errors + except (OSError, IOError): # Py2 and Py3 have different errors if wait == 0: continue if attempt == 0: - sys.stdout.write('Waiting {} seconds for pyboard '.format(wait)) + sys.stdout.write("Waiting {} seconds for pyboard ".format(wait)) delayed = True time.sleep(1) - sys.stdout.write('.') + sys.stdout.write(".") sys.stdout.flush() else: if delayed: - print('') - raise PyboardError('failed to access ' + device) + print("") + raise PyboardError("failed to access " + device) if delayed: - print('') + print("") def close(self): self.serial.close() @@ -281,7 +307,7 @@ class Pyboard: return data def enter_raw_repl(self): - self.serial.write(b'\r\x03\x03') # ctrl-C twice: interrupt any running program + self.serial.write(b"\r\x03\x03") # ctrl-C twice: interrupt any running program # flush input (without relying on serial.flushInput()) n = self.serial.inWaiting() @@ -289,38 +315,38 @@ class Pyboard: self.serial.read(n) n = self.serial.inWaiting() - self.serial.write(b'\r\x01') # ctrl-A: enter raw REPL - data = self.read_until(1, b'raw REPL; CTRL-B to exit\r\n>') - if not data.endswith(b'raw REPL; CTRL-B to exit\r\n>'): + self.serial.write(b"\r\x01") # ctrl-A: enter raw REPL + data = self.read_until(1, b"raw REPL; CTRL-B to exit\r\n>") + if not data.endswith(b"raw REPL; CTRL-B to exit\r\n>"): print(data) - raise PyboardError('could not enter raw repl') + raise PyboardError("could not enter raw repl") - self.serial.write(b'\x04') # ctrl-D: soft reset - data = self.read_until(1, b'soft reboot\r\n') - if not data.endswith(b'soft reboot\r\n'): + self.serial.write(b"\x04") # ctrl-D: soft reset + data = self.read_until(1, b"soft reboot\r\n") + if not data.endswith(b"soft reboot\r\n"): print(data) - raise PyboardError('could not enter raw repl') + raise PyboardError("could not enter raw repl") # By splitting this into 2 reads, it allows boot.py to print stuff, # which will show up after the soft reboot and before the raw REPL. - data = self.read_until(1, b'raw REPL; CTRL-B to exit\r\n') - if not data.endswith(b'raw REPL; CTRL-B to exit\r\n'): + data = self.read_until(1, b"raw REPL; CTRL-B to exit\r\n") + if not data.endswith(b"raw REPL; CTRL-B to exit\r\n"): print(data) - raise PyboardError('could not enter raw repl') + raise PyboardError("could not enter raw repl") def exit_raw_repl(self): - self.serial.write(b'\r\x02') # ctrl-B: enter friendly REPL + self.serial.write(b"\r\x02") # ctrl-B: enter friendly REPL def follow(self, timeout, data_consumer=None): # wait for normal output - data = self.read_until(1, b'\x04', timeout=timeout, data_consumer=data_consumer) - if not data.endswith(b'\x04'): - raise PyboardError('timeout waiting for first EOF reception') + data = self.read_until(1, b"\x04", timeout=timeout, data_consumer=data_consumer) + if not data.endswith(b"\x04"): + raise PyboardError("timeout waiting for first EOF reception") data = data[:-1] # wait for error output - data_err = self.read_until(1, b'\x04', timeout=timeout) - if not data_err.endswith(b'\x04'): - raise PyboardError('timeout waiting for second EOF reception') + data_err = self.read_until(1, b"\x04", timeout=timeout) + if not data_err.endswith(b"\x04"): + raise PyboardError("timeout waiting for second EOF reception") data_err = data_err[:-1] # return normal and error output @@ -330,53 +356,55 @@ class Pyboard: if isinstance(command, bytes): command_bytes = command else: - command_bytes = bytes(command, encoding='utf8') + command_bytes = bytes(command, encoding="utf8") # check we have a prompt - data = self.read_until(1, b'>') - if not data.endswith(b'>'): - raise PyboardError('could not enter raw repl') + data = self.read_until(1, b">") + if not data.endswith(b">"): + raise PyboardError("could not enter raw repl") # write command for i in range(0, len(command_bytes), 256): - self.serial.write(command_bytes[i:min(i + 256, len(command_bytes))]) + self.serial.write(command_bytes[i : min(i + 256, len(command_bytes))]) time.sleep(0.01) - self.serial.write(b'\x04') + self.serial.write(b"\x04") # check if we could exec command data = self.serial.read(2) - if data != b'OK': - raise PyboardError('could not exec command (response: %r)' % data) + if data != b"OK": + raise PyboardError("could not exec command (response: %r)" % data) def exec_raw(self, command, timeout=10, data_consumer=None): - self.exec_raw_no_follow(command); + self.exec_raw_no_follow(command) return self.follow(timeout, data_consumer) def eval(self, expression): - ret = self.exec_('print({})'.format(expression)) + ret = self.exec_("print({})".format(expression)) ret = ret.strip() return ret def exec_(self, command): ret, ret_err = self.exec_raw(command) if ret_err: - raise PyboardError('exception', ret, ret_err) + raise PyboardError("exception", ret, ret_err) return ret def execfile(self, filename): - with open(filename, 'rb') as f: + with open(filename, "rb") as f: pyfile = f.read() return self.exec_(pyfile) def get_time(self): - t = str(self.eval('pyb.RTC().datetime()'), encoding='utf8')[1:-1].split(', ') + t = str(self.eval("pyb.RTC().datetime()"), encoding="utf8")[1:-1].split(", ") return int(t[4]) * 3600 + int(t[5]) * 60 + int(t[6]) + # in Python2 exec is a keyword so one must use "exec_" # but for Python3 we want to provide the nicer version "exec" setattr(Pyboard, "exec", Pyboard.exec_) -def execfile(filename, device='/dev/ttyACM0', baudrate=115200, user='micro', password='python'): + +def execfile(filename, device="/dev/ttyACM0", baudrate=115200, user="micro", password="python"): pyb = Pyboard(device, baudrate, user, password) pyb.enter_raw_repl() output = pyb.execfile(filename) @@ -384,17 +412,35 @@ def execfile(filename, device='/dev/ttyACM0', baudrate=115200, user='micro', pas pyb.exit_raw_repl() pyb.close() + def main(): import argparse - cmd_parser = argparse.ArgumentParser(description='Run scripts on the pyboard.') - cmd_parser.add_argument('--device', default='/dev/ttyACM0', help='the serial device or the IP address of the pyboard') - cmd_parser.add_argument('-b', '--baudrate', default=115200, help='the baud rate of the serial device') - cmd_parser.add_argument('-u', '--user', default='micro', help='the telnet login username') - cmd_parser.add_argument('-p', '--password', default='python', help='the telnet login password') - cmd_parser.add_argument('-c', '--command', help='program passed in as string') - cmd_parser.add_argument('-w', '--wait', default=0, type=int, help='seconds to wait for USB connected board to become available') - cmd_parser.add_argument('--follow', action='store_true', help='follow the output after running the scripts [default if no scripts given]') - cmd_parser.add_argument('files', nargs='*', help='input files') + + cmd_parser = argparse.ArgumentParser(description="Run scripts on the pyboard.") + cmd_parser.add_argument( + "--device", + default="/dev/ttyACM0", + help="the serial device or the IP address of the pyboard", + ) + cmd_parser.add_argument( + "-b", "--baudrate", default=115200, help="the baud rate of the serial device" + ) + cmd_parser.add_argument("-u", "--user", default="micro", help="the telnet login username") + cmd_parser.add_argument("-p", "--password", default="python", help="the telnet login password") + cmd_parser.add_argument("-c", "--command", help="program passed in as string") + cmd_parser.add_argument( + "-w", + "--wait", + default=0, + type=int, + help="seconds to wait for USB connected board to become available", + ) + cmd_parser.add_argument( + "--follow", + action="store_true", + help="follow the output after running the scripts [default if no scripts given]", + ) + cmd_parser.add_argument("files", nargs="*", help="input files") args = cmd_parser.parse_args() # open the connection to the pyboard @@ -432,11 +478,11 @@ def main(): # run the command, if given if args.command is not None: - execbuffer(args.command.encode('utf-8')) + execbuffer(args.command.encode("utf-8")) # run any files for filename in args.files: - with open(filename, 'rb') as f: + with open(filename, "rb") as f: pyfile = f.read() execbuffer(pyfile) @@ -460,5 +506,6 @@ def main(): # close the connection to the pyboard pyb.close() + if __name__ == "__main__": main() diff --git a/tools/pydfu.py b/tools/pydfu.py index 658ce59ae6..4532339fde 100755 --- a/tools/pydfu.py +++ b/tools/pydfu.py @@ -24,34 +24,34 @@ import zlib # VID/PID __VID = 0x0483 -__PID = 0xdf11 +__PID = 0xDF11 # USB request __TIMEOUT __TIMEOUT = 4000 # DFU commands -__DFU_DETACH = 0 -__DFU_DNLOAD = 1 -__DFU_UPLOAD = 2 +__DFU_DETACH = 0 +__DFU_DNLOAD = 1 +__DFU_UPLOAD = 2 __DFU_GETSTATUS = 3 __DFU_CLRSTATUS = 4 -__DFU_GETSTATE = 5 -__DFU_ABORT = 6 +__DFU_GETSTATE = 5 +__DFU_ABORT = 6 # DFU status -__DFU_STATE_APP_IDLE = 0x00 -__DFU_STATE_APP_DETACH = 0x01 -__DFU_STATE_DFU_IDLE = 0x02 -__DFU_STATE_DFU_DOWNLOAD_SYNC = 0x03 -__DFU_STATE_DFU_DOWNLOAD_BUSY = 0x04 -__DFU_STATE_DFU_DOWNLOAD_IDLE = 0x05 -__DFU_STATE_DFU_MANIFEST_SYNC = 0x06 -__DFU_STATE_DFU_MANIFEST = 0x07 -__DFU_STATE_DFU_MANIFEST_WAIT_RESET = 0x08 -__DFU_STATE_DFU_UPLOAD_IDLE = 0x09 -__DFU_STATE_DFU_ERROR = 0x0a +__DFU_STATE_APP_IDLE = 0x00 +__DFU_STATE_APP_DETACH = 0x01 +__DFU_STATE_DFU_IDLE = 0x02 +__DFU_STATE_DFU_DOWNLOAD_SYNC = 0x03 +__DFU_STATE_DFU_DOWNLOAD_BUSY = 0x04 +__DFU_STATE_DFU_DOWNLOAD_IDLE = 0x05 +__DFU_STATE_DFU_MANIFEST_SYNC = 0x06 +__DFU_STATE_DFU_MANIFEST = 0x07 +__DFU_STATE_DFU_MANIFEST_WAIT_RESET = 0x08 +__DFU_STATE_DFU_UPLOAD_IDLE = 0x09 +__DFU_STATE_DFU_ERROR = 0x0A -_DFU_DESCRIPTOR_TYPE = 0x21 +_DFU_DESCRIPTOR_TYPE = 0x21 # USB device handle @@ -68,12 +68,15 @@ __DFU_INTERFACE = 0 # Python 3 deprecated getargspec in favour of getfullargspec, but # Python 2 doesn't have the latter, so detect which one to use import inspect -getargspec = getattr(inspect, 'getfullargspec', inspect.getargspec) -if 'length' in getargspec(usb.util.get_string).args: +getargspec = getattr(inspect, "getfullargspec", inspect.getargspec) + +if "length" in getargspec(usb.util.get_string).args: # PyUSB 1.0.0.b1 has the length argument def get_string(dev, index): return usb.util.get_string(dev, 255, index) + + else: # PyUSB 1.0.0.b2 dropped the length argument def get_string(dev, index): @@ -82,10 +85,18 @@ else: def find_dfu_cfg_descr(descr): if len(descr) == 9 and descr[0] == 9 and descr[1] == _DFU_DESCRIPTOR_TYPE: - nt = collections.namedtuple('CfgDescr', - ['bLength', 'bDescriptorType', 'bmAttributes', - 'wDetachTimeOut', 'wTransferSize', 'bcdDFUVersion']) - return nt(*struct.unpack(' 1: raise ValueError("Multiple DFU devices found") __dev = devices[0] @@ -119,8 +130,7 @@ def init(): status = get_status() if status == __DFU_STATE_DFU_IDLE: break - elif (status == __DFU_STATE_DFU_DOWNLOAD_IDLE - or status == __DFU_STATE_DFU_UPLOAD_IDLE): + elif status == __DFU_STATE_DFU_DOWNLOAD_IDLE or status == __DFU_STATE_DFU_UPLOAD_IDLE: abort_request() else: clr_status() @@ -133,14 +143,12 @@ def abort_request(): def clr_status(): """Clears any error status (perhaps left over from a previous session).""" - __dev.ctrl_transfer(0x21, __DFU_CLRSTATUS, 0, __DFU_INTERFACE, - None, __TIMEOUT) + __dev.ctrl_transfer(0x21, __DFU_CLRSTATUS, 0, __DFU_INTERFACE, None, __TIMEOUT) def get_status(): """Get the status of the last operation.""" - stat = __dev.ctrl_transfer(0xA1, __DFU_GETSTATUS, 0, __DFU_INTERFACE, - 6, 20000) + stat = __dev.ctrl_transfer(0xA1, __DFU_GETSTATUS, 0, __DFU_INTERFACE, 6, 20000) # print (__DFU_STAT[stat[4]], stat) return stat[4] @@ -148,8 +156,7 @@ def get_status(): def mass_erase(): """Performs a MASS erase (i.e. erases the entire device.""" # Send DNLOAD with first byte=0x41 - __dev.ctrl_transfer(0x21, __DFU_DNLOAD, 0, __DFU_INTERFACE, - "\x41", __TIMEOUT) + __dev.ctrl_transfer(0x21, __DFU_DNLOAD, 0, __DFU_INTERFACE, "\x41", __TIMEOUT) # Execute last command if get_status() != __DFU_STATE_DFU_DOWNLOAD_BUSY: @@ -206,20 +213,21 @@ def write_memory(addr, buf, progress=None, progress_addr=0, progress_size=0): while xfer_bytes < xfer_total: if __verbose and xfer_count % 512 == 0: - print ("Addr 0x%x %dKBs/%dKBs..." % (xfer_base + xfer_bytes, - xfer_bytes // 1024, - xfer_total // 1024)) + print( + "Addr 0x%x %dKBs/%dKBs..." + % (xfer_base + xfer_bytes, xfer_bytes // 1024, xfer_total // 1024) + ) if progress and xfer_count % 2 == 0: - progress(progress_addr, xfer_base + xfer_bytes - progress_addr, - progress_size) + progress(progress_addr, xfer_base + xfer_bytes - progress_addr, progress_size) # Set mem write address - set_address(xfer_base+xfer_bytes) + set_address(xfer_base + xfer_bytes) # Send DNLOAD with fw data - chunk = min(__cfg_descr.wTransferSize, xfer_total-xfer_bytes) - __dev.ctrl_transfer(0x21, __DFU_DNLOAD, 2, __DFU_INTERFACE, - buf[xfer_bytes:xfer_bytes + chunk], __TIMEOUT) + chunk = min(__cfg_descr.wTransferSize, xfer_total - xfer_bytes) + __dev.ctrl_transfer( + 0x21, __DFU_DNLOAD, 2, __DFU_INTERFACE, buf[xfer_bytes : xfer_bytes + chunk], __TIMEOUT + ) # Execute last command if get_status() != __DFU_STATE_DFU_DOWNLOAD_BUSY: @@ -241,7 +249,7 @@ def write_page(buf, xfer_offset): xfer_base = 0x08000000 # Set mem write address - set_address(xfer_base+xfer_offset) + set_address(xfer_base + xfer_offset) # Send DNLOAD with fw data __dev.ctrl_transfer(0x21, __DFU_DNLOAD, 2, __DFU_INTERFACE, buf, __TIMEOUT) @@ -255,7 +263,7 @@ def write_page(buf, xfer_offset): raise Exception("DFU: write memory failed") if __verbose: - print ("Write: 0x%x " % (xfer_base + xfer_offset)) + print("Write: 0x%x " % (xfer_base + xfer_offset)) def exit_dfu(): @@ -265,8 +273,7 @@ def exit_dfu(): set_address(0x08000000) # Send DNLOAD with 0 length to exit DFU - __dev.ctrl_transfer(0x21, __DFU_DNLOAD, 0, __DFU_INTERFACE, - None, __TIMEOUT) + __dev.ctrl_transfer(0x21, __DFU_DNLOAD, 0, __DFU_INTERFACE, None, __TIMEOUT) try: # Execute last command @@ -294,7 +301,7 @@ def consume(fmt, data, names): def cstring(string): """Extracts a null-terminated string from a byte array.""" - return string.decode('utf-8').split('\0', 1)[0] + return string.decode("utf-8").split("\0", 1)[0] def compute_crc(data): @@ -314,7 +321,7 @@ def read_dfu_file(filename): """ print("File: {}".format(filename)) - with open(filename, 'rb') as fin: + with open(filename, "rb") as fin: data = fin.read() crc = compute_crc(data[:-4]) elements = [] @@ -327,11 +334,12 @@ def read_dfu_file(filename): # B uint8_t version 1 # I uint32_t size Size of the DFU file (not including suffix) # B uint8_t targets Number of targets - dfu_prefix, data = consume('<5sBIB', data, - 'signature version size targets') - print (" %(signature)s v%(version)d, image size: %(size)d, " - "targets: %(targets)d" % dfu_prefix) - for target_idx in range(dfu_prefix['targets']): + dfu_prefix, data = consume("<5sBIB", data, "signature version size targets") + print( + " %(signature)s v%(version)d, image size: %(size)d, " + "targets: %(targets)d" % dfu_prefix + ) + for target_idx in range(dfu_prefix["targets"]): # Decode the Image Prefix # # <6sBI255s2I @@ -342,33 +350,33 @@ def read_dfu_file(filename): # 255s char[255] name name of the target # I uint32_t size size of image (not incl prefix) # I uint32_t elements Number of elements in the image - img_prefix, data = consume('<6sBI255s2I', data, - 'signature altsetting named name ' - 'size elements') - img_prefix['num'] = target_idx - if img_prefix['named']: - img_prefix['name'] = cstring(img_prefix['name']) + img_prefix, data = consume( + "<6sBI255s2I", data, "signature altsetting named name " "size elements" + ) + img_prefix["num"] = target_idx + if img_prefix["named"]: + img_prefix["name"] = cstring(img_prefix["name"]) else: - img_prefix['name'] = '' - print(' %(signature)s %(num)d, alt setting: %(altsetting)s, ' - 'name: "%(name)s", size: %(size)d, elements: %(elements)d' - % img_prefix) + img_prefix["name"] = "" + print( + " %(signature)s %(num)d, alt setting: %(altsetting)s, " + 'name: "%(name)s", size: %(size)d, elements: %(elements)d' % img_prefix + ) - target_size = img_prefix['size'] + target_size = img_prefix["size"] target_data, data = data[:target_size], data[target_size:] - for elem_idx in range(img_prefix['elements']): + for elem_idx in range(img_prefix["elements"]): # Decode target prefix # < little endian # I uint32_t element address # I uint32_t element size - elem_prefix, target_data = consume('<2I', target_data, 'addr size') - elem_prefix['num'] = elem_idx - print(' %(num)d, address: 0x%(addr)08x, size: %(size)d' - % elem_prefix) - elem_size = elem_prefix['size'] + elem_prefix, target_data = consume("<2I", target_data, "addr size") + elem_prefix["num"] = elem_idx + print(" %(num)d, address: 0x%(addr)08x, size: %(size)d" % elem_prefix) + elem_size = elem_prefix["size"] elem_data = target_data[:elem_size] target_data = target_data[elem_size:] - elem_prefix['data'] = elem_data + elem_prefix["data"] = elem_data elements.append(elem_prefix) if len(target_data): @@ -383,11 +391,14 @@ def read_dfu_file(filename): # 3s char[3] ufd 'UFD' # B uint8_t len 16 # I uint32_t crc32 - dfu_suffix = named(struct.unpack('<4H3sBI', data[:16]), - 'device product vendor dfu ufd len crc') - print (' usb: %(vendor)04x:%(product)04x, device: 0x%(device)04x, ' - 'dfu: 0x%(dfu)04x, %(ufd)s, %(len)d, 0x%(crc)08x' % dfu_suffix) - if crc != dfu_suffix['crc']: + dfu_suffix = named( + struct.unpack("<4H3sBI", data[:16]), "device product vendor dfu ufd len crc" + ) + print( + " usb: %(vendor)04x:%(product)04x, device: 0x%(device)04x, " + "dfu: 0x%(dfu)04x, %(ufd)s, %(len)d, 0x%(crc)08x" % dfu_suffix + ) + if crc != dfu_suffix["crc"]: print("CRC ERROR: computed crc32 is 0x%08x" % crc) return data = data[16:] @@ -406,8 +417,7 @@ class FilterDFU(object): def __call__(self, device): for cfg in device: for intf in cfg: - return (intf.bInterfaceClass == 0xFE and - intf.bInterfaceSubClass == 1) + return intf.bInterfaceClass == 0xFE and intf.bInterfaceSubClass == 1 def get_dfu_devices(*args, **kwargs): @@ -416,8 +426,7 @@ def get_dfu_devices(*args, **kwargs): refine the search. """ # convert to list for compatibility with newer pyusb - return list(usb.core.find(*args, find_all=True, - custom_match=FilterDFU(), **kwargs)) + return list(usb.core.find(*args, find_all=True, custom_match=FilterDFU(), **kwargs)) def get_memory_layout(device): @@ -432,25 +441,29 @@ def get_memory_layout(device): cfg = device[0] intf = cfg[(0, 0)] mem_layout_str = get_string(device, intf.iInterface) - mem_layout = mem_layout_str.split('/') + mem_layout = mem_layout_str.split("/") result = [] for mem_layout_index in range(1, len(mem_layout), 2): addr = int(mem_layout[mem_layout_index], 0) - segments = mem_layout[mem_layout_index + 1].split(',') - seg_re = re.compile(r'(\d+)\*(\d+)(.)(.)') + segments = mem_layout[mem_layout_index + 1].split(",") + seg_re = re.compile(r"(\d+)\*(\d+)(.)(.)") for segment in segments: seg_match = seg_re.match(segment) num_pages = int(seg_match.groups()[0], 10) page_size = int(seg_match.groups()[1], 10) multiplier = seg_match.groups()[2] - if multiplier == 'K': + if multiplier == "K": page_size *= 1024 - if multiplier == 'M': + if multiplier == "M": page_size *= 1024 * 1024 size = num_pages * page_size last_addr = addr + size - 1 - result.append(named((addr, last_addr, size, num_pages, page_size), - "addr last_addr size num_pages page_size")) + result.append( + named( + (addr, last_addr, size, num_pages, page_size), + "addr last_addr size num_pages page_size", + ) + ) addr += size return result @@ -462,15 +475,19 @@ def list_dfu_devices(*args, **kwargs): print("No DFU capable devices found") return for device in devices: - print("Bus {} Device {:03d}: ID {:04x}:{:04x}" - .format(device.bus, device.address, - device.idVendor, device.idProduct)) + print( + "Bus {} Device {:03d}: ID {:04x}:{:04x}".format( + device.bus, device.address, device.idVendor, device.idProduct + ) + ) layout = get_memory_layout(device) print("Memory Layout") for entry in layout: - print(" 0x{:x} {:2d} pages of {:3d}K bytes" - .format(entry['addr'], entry['num_pages'], - entry['page_size'] // 1024)) + print( + " 0x{:x} {:2d} pages of {:3d}K bytes".format( + entry["addr"], entry["num_pages"], entry["page_size"] // 1024 + ) + ) def write_elements(elements, mass_erase_used, progress=None): @@ -480,9 +497,9 @@ def write_elements(elements, mass_erase_used, progress=None): mem_layout = get_memory_layout(__dev) for elem in elements: - addr = elem['addr'] - size = elem['size'] - data = elem['data'] + addr = elem["addr"] + size = elem["size"] + data = elem["data"] elem_size = size elem_addr = addr if progress: @@ -491,18 +508,16 @@ def write_elements(elements, mass_erase_used, progress=None): write_size = size if not mass_erase_used: for segment in mem_layout: - if addr >= segment['addr'] and \ - addr <= segment['last_addr']: + if addr >= segment["addr"] and addr <= segment["last_addr"]: # We found the page containing the address we want to # write, erase it - page_size = segment['page_size'] + page_size = segment["page_size"] page_addr = addr & ~(page_size - 1) if addr + write_size > page_addr + page_size: write_size = page_addr + page_size - addr page_erase(page_addr) break - write_memory(addr, data[:write_size], progress, - elem_addr, elem_size) + write_memory(addr, data[:write_size], progress, elem_addr, elem_size) data = data[write_size:] addr += write_size size -= write_size @@ -514,13 +529,16 @@ def cli_progress(addr, offset, size): """Prints a progress report suitable for use on the command line.""" width = 25 done = offset * width // size - print("\r0x{:08x} {:7d} [{}{}] {:3d}% " - .format(addr, size, '=' * done, ' ' * (width - done), - offset * 100 // size), end="") + print( + "\r0x{:08x} {:7d} [{}{}] {:3d}% ".format( + addr, size, "=" * done, " " * (width - done), offset * 100 // size + ), + end="", + ) try: sys.stdout.flush() except OSError: - pass # Ignore Windows CLI "WinError 87" on Python 3.6 + pass # Ignore Windows CLI "WinError 87" on Python 3.6 if offset == size: print("") @@ -529,31 +547,19 @@ def main(): """Test program for verifying this files functionality.""" global __verbose # Parse CMD args - parser = argparse.ArgumentParser(description='DFU Python Util') - #parser.add_argument("path", help="file path") + parser = argparse.ArgumentParser(description="DFU Python Util") + # parser.add_argument("path", help="file path") parser.add_argument( - "-l", "--list", - help="list available DFU devices", - action="store_true", - default=False + "-l", "--list", help="list available DFU devices", action="store_true", default=False ) parser.add_argument( - "-m", "--mass-erase", - help="mass erase device", - action="store_true", - default=False + "-m", "--mass-erase", help="mass erase device", action="store_true", default=False ) parser.add_argument( - "-u", "--upload", - help="read file from DFU device", - dest="path", - default=False + "-u", "--upload", help="read file from DFU device", dest="path", default=False ) parser.add_argument( - "-v", "--verbose", - help="increase output verbosity", - action="store_true", - default=False + "-v", "--verbose", help="increase output verbosity", action="store_true", default=False ) args = parser.parse_args() @@ -566,7 +572,7 @@ def main(): init() if args.mass_erase: - print ("Mass erase...") + print("Mass erase...") mass_erase() if args.path: @@ -582,5 +588,6 @@ def main(): print("No command specified") -if __name__ == '__main__': + +if __name__ == "__main__": main() diff --git a/tools/tinytest-codegen.py b/tools/tinytest-codegen.py index ad3b3bbec9..2d219c6f28 100755 --- a/tools/tinytest-codegen.py +++ b/tools/tinytest-codegen.py @@ -9,17 +9,19 @@ import argparse def escape(s): s = s.decode() lookup = { - '\0': '\\0', - '\t': '\\t', - '\n': '\\n\"\n\"', - '\r': '\\r', - '\\': '\\\\', - '\"': '\\\"', + "\0": "\\0", + "\t": "\\t", + "\n": '\\n"\n"', + "\r": "\\r", + "\\": "\\\\", + '"': '\\"', } - return "\"\"\n\"{}\"".format(''.join([lookup[x] if x in lookup else x for x in s])) + return '""\n"{}"'.format("".join([lookup[x] if x in lookup else x for x in s])) + def chew_filename(t): - return { 'func': "test_{}_fn".format(sub(r'/|\.|-', '_', t)), 'desc': t } + return {"func": "test_{}_fn".format(sub(r"/|\.|-", "_", t)), "desc": t} + def script_to_map(test_file): r = {"name": chew_filename(test_file)["func"]} @@ -29,6 +31,7 @@ def script_to_map(test_file): r["output"] = escape(f.read()) return r + test_function = ( "void {name}(void* data) {{\n" " static const char pystr[] = {script};\n" @@ -38,73 +41,72 @@ test_function = ( "}}" ) -testcase_struct = ( - "struct testcase_t {name}_tests[] = {{\n{body}\n END_OF_TESTCASES\n}};" -) -testcase_member = ( - " {{ \"{desc}\", {func}, TT_ENABLED_, 0, 0 }}," -) +testcase_struct = "struct testcase_t {name}_tests[] = {{\n{body}\n END_OF_TESTCASES\n}};" +testcase_member = ' {{ "{desc}", {func}, TT_ENABLED_, 0, 0 }},' -testgroup_struct = ( - "struct testgroup_t groups[] = {{\n{body}\n END_OF_GROUPS\n}};" -) -testgroup_member = ( - " {{ \"{name}\", {name}_tests }}," -) +testgroup_struct = "struct testgroup_t groups[] = {{\n{body}\n END_OF_GROUPS\n}};" +testgroup_member = ' {{ "{name}", {name}_tests }},' ## XXX: may be we could have `--without ` argument... # currently these tests are selected because they pass on qemu-arm -test_dirs = ('basics', 'micropython', 'float', 'extmod', 'inlineasm') # 'import', 'io', 'misc') +test_dirs = ("basics", "micropython", "float", "extmod", "inlineasm") # 'import', 'io', 'misc') exclude_tests = ( # pattern matching in .exp - 'basics/bytes_compare3.py', - 'extmod/ticks_diff.py', - 'extmod/time_ms_us.py', - 'extmod/uheapq_timeq.py', + "basics/bytes_compare3.py", + "extmod/ticks_diff.py", + "extmod/time_ms_us.py", + "extmod/uheapq_timeq.py", # unicode char issue - 'extmod/ujson_loads.py', + "extmod/ujson_loads.py", # doesn't output to python stdout - 'extmod/ure_debug.py', - 'extmod/vfs_basic.py', - 'extmod/vfs_fat_ramdisk.py', 'extmod/vfs_fat_fileio.py', - 'extmod/vfs_fat_fsusermount.py', 'extmod/vfs_fat_oldproto.py', + "extmod/ure_debug.py", + "extmod/vfs_basic.py", + "extmod/vfs_fat_ramdisk.py", + "extmod/vfs_fat_fileio.py", + "extmod/vfs_fat_fsusermount.py", + "extmod/vfs_fat_oldproto.py", # rounding issues - 'float/float_divmod.py', + "float/float_divmod.py", # requires double precision floating point to work - 'float/float2int_doubleprec_intbig.py', - 'float/float_parse_doubleprec.py', + "float/float2int_doubleprec_intbig.py", + "float/float_parse_doubleprec.py", # inline asm FP tests (require Cortex-M4) - 'inlineasm/asmfpaddsub.py', 'inlineasm/asmfpcmp.py', 'inlineasm/asmfpldrstr.py', - 'inlineasm/asmfpmuldiv.py','inlineasm/asmfpsqrt.py', + "inlineasm/asmfpaddsub.py", + "inlineasm/asmfpcmp.py", + "inlineasm/asmfpldrstr.py", + "inlineasm/asmfpmuldiv.py", + "inlineasm/asmfpsqrt.py", # different filename in output - 'micropython/emg_exc.py', - 'micropython/heapalloc_traceback.py', + "micropython/emg_exc.py", + "micropython/heapalloc_traceback.py", # pattern matching in .exp - 'micropython/meminfo.py', + "micropython/meminfo.py", ) output = [] tests = [] -argparser = argparse.ArgumentParser(description='Convert native MicroPython tests to tinytest/upytesthelper C code') -argparser.add_argument('--stdin', action="store_true", help='read list of tests from stdin') +argparser = argparse.ArgumentParser( + description="Convert native MicroPython tests to tinytest/upytesthelper C code" +) +argparser.add_argument("--stdin", action="store_true", help="read list of tests from stdin") args = argparser.parse_args() if not args.stdin: for group in test_dirs: - tests += [test for test in glob('{}/*.py'.format(group)) if test not in exclude_tests] + tests += [test for test in glob("{}/*.py".format(group)) if test not in exclude_tests] else: for l in sys.stdin: tests.append(l.rstrip()) output.extend([test_function.format(**script_to_map(test)) for test in tests]) testcase_members = [testcase_member.format(**chew_filename(test)) for test in tests] -output.append(testcase_struct.format(name="", body='\n'.join(testcase_members))) +output.append(testcase_struct.format(name="", body="\n".join(testcase_members))) testgroup_members = [testgroup_member.format(name=group) for group in [""]] -output.append(testgroup_struct.format(body='\n'.join(testgroup_members))) +output.append(testgroup_struct.format(body="\n".join(testgroup_members))) ## XXX: may be we could have `--output ` argument... # Don't depend on what system locale is set, use utf8 encoding. -sys.stdout.buffer.write('\n\n'.join(output).encode('utf8')) +sys.stdout.buffer.write("\n\n".join(output).encode("utf8")) diff --git a/tools/upip.py b/tools/upip.py index a400c31743..b28fdfbb2e 100644 --- a/tools/upip.py +++ b/tools/upip.py @@ -12,6 +12,7 @@ import uerrno as errno import ujson as json import uzlib import upip_utarfile as tarfile + gc.collect() @@ -22,9 +23,11 @@ gzdict_sz = 16 + 15 file_buf = bytearray(512) + class NotFoundError(Exception): pass + def op_split(path): if path == "": return ("", "") @@ -36,9 +39,11 @@ def op_split(path): head = "/" return (head, r[1]) + def op_basename(path): return op_split(path)[1] + # Expects *file* name def _makedirs(name, mode=0o777): ret = False @@ -69,26 +74,27 @@ def save_file(fname, subf): break outf.write(file_buf, sz) + def install_tar(f, prefix): meta = {} for info in f: - #print(info) + # print(info) fname = info.name try: - fname = fname[fname.index("/") + 1:] + fname = fname[fname.index("/") + 1 :] except ValueError: fname = "" save = True for p in ("setup.", "PKG-INFO", "README"): - #print(fname, p) - if fname.startswith(p) or ".egg-info" in fname: - if fname.endswith("/requires.txt"): - meta["deps"] = f.extractfile(info).read() - save = False - if debug: - print("Skipping", fname) - break + # print(fname, p) + if fname.startswith(p) or ".egg-info" in fname: + if fname.endswith("/requires.txt"): + meta["deps"] = f.extractfile(info).read() + save = False + if debug: + print("Skipping", fname) + break if save: outfname = prefix + fname @@ -100,32 +106,37 @@ def install_tar(f, prefix): save_file(outfname, subf) return meta + def expandhome(s): if "~/" in s: h = os.getenv("HOME") s = s.replace("~/", h + "/") return s + import ussl import usocket + warn_ussl = True + + def url_open(url): global warn_ussl if debug: print(url) - proto, _, host, urlpath = url.split('/', 3) + proto, _, host, urlpath = url.split("/", 3) try: ai = usocket.getaddrinfo(host, 443, 0, usocket.SOCK_STREAM) except OSError as e: fatal("Unable to resolve %s (no Internet?)" % host, e) - #print("Address infos:", ai) + # print("Address infos:", ai) ai = ai[0] s = usocket.socket(ai[0], ai[1], ai[2]) try: - #print("Connect address:", addr) + # print("Connect address:", addr) s.connect(ai[-1]) if proto == "https:": @@ -146,7 +157,7 @@ def url_open(url): l = s.readline() if not l: raise ValueError("Unexpected EOF in HTTP headers") - if l == b'\r\n': + if l == b"\r\n": break except Exception as e: s.close() @@ -169,6 +180,7 @@ def fatal(msg, exc=None): raise exc sys.exit(1) + def install_pkg(pkg_spec, install_path): data = get_pkg_metadata(pkg_spec) @@ -192,6 +204,7 @@ def install_pkg(pkg_spec, install_path): gc.collect() return meta + def install(to_install, install_path=None): # Calculate gzip dictionary size to use global gzdict_sz @@ -224,9 +237,11 @@ def install(to_install, install_path=None): deps = deps.decode("utf-8").split("\n") to_install.extend(deps) except Exception as e: - print("Error installing '{}': {}, packages may be partially installed".format( - pkg_spec, e), - file=sys.stderr) + print( + "Error installing '{}': {}, packages may be partially installed".format(pkg_spec, e), + file=sys.stderr, + ) + def get_install_path(): global install_path @@ -236,6 +251,7 @@ def get_install_path(): install_path = expandhome(install_path) return install_path + def cleanup(): for fname in cleanup_files: try: @@ -243,21 +259,27 @@ def cleanup(): except OSError: print("Warning: Cannot delete " + fname) + def help(): - print("""\ + print( + """\ upip - Simple PyPI package manager for MicroPython Usage: micropython -m upip install [-p ] ... | -r import upip; upip.install(package_or_list, []) If is not given, packages will be installed into sys.path[1] (can be set from MICROPYPATH environment variable, if current system -supports that).""") +supports that).""" + ) print("Current value of sys.path[1]:", sys.path[1]) - print("""\ + print( + """\ Note: only MicroPython packages (usually, named micropython-*) are supported for installation, upip does not support arbitrary code in setup.py. -""") +""" + ) + def main(): global debug diff --git a/tools/upip_utarfile.py b/tools/upip_utarfile.py index 460ca2cd44..21b899f020 100644 --- a/tools/upip_utarfile.py +++ b/tools/upip_utarfile.py @@ -9,11 +9,12 @@ TAR_HEADER = { DIRTYPE = "dir" REGTYPE = "file" + def roundup(val, align): return (val + align - 1) & ~(align - 1) -class FileSection: +class FileSection: def __init__(self, f, content_len, aligned_len): self.f = f self.content_len = content_len @@ -33,7 +34,7 @@ class FileSection: if self.content_len == 0: return 0 if len(buf) > self.content_len: - buf = memoryview(buf)[:self.content_len] + buf = memoryview(buf)[: self.content_len] sz = self.f.readinto(buf) self.content_len -= sz return sz @@ -47,13 +48,13 @@ class FileSection: self.f.readinto(buf, s) sz -= s -class TarInfo: +class TarInfo: def __str__(self): return "TarInfo(%r, %s, %d)" % (self.name, self.type, self.size) -class TarFile: +class TarFile: def __init__(self, name=None, fileobj=None): if fileobj: self.f = fileobj @@ -62,24 +63,24 @@ class TarFile: self.subf = None def next(self): - if self.subf: - self.subf.skip() - buf = self.f.read(512) - if not buf: - return None + if self.subf: + self.subf.skip() + buf = self.f.read(512) + if not buf: + return None - h = uctypes.struct(uctypes.addressof(buf), TAR_HEADER, uctypes.LITTLE_ENDIAN) + h = uctypes.struct(uctypes.addressof(buf), TAR_HEADER, uctypes.LITTLE_ENDIAN) - # Empty block means end of archive - if h.name[0] == 0: - return None + # Empty block means end of archive + if h.name[0] == 0: + return None - d = TarInfo() - d.name = str(h.name, "utf-8").rstrip("\0") - d.size = int(bytes(h.size), 8) - d.type = [REGTYPE, DIRTYPE][d.name[-1] == "/"] - self.subf = d.subf = FileSection(self.f, d.size, roundup(d.size, 512)) - return d + d = TarInfo() + d.name = str(h.name, "utf-8").rstrip("\0") + d.size = int(bytes(h.size), 8) + d.type = [REGTYPE, DIRTYPE][d.name[-1] == "/"] + self.subf = d.subf = FileSection(self.f, d.size, roundup(d.size, 512)) + return d def __iter__(self): return self