circuitpython/py/objlist.c
Jeff Epler 8d8f83bc05 Merge tag 'v1.17' into merge-1.17
F-strings, new machine.I2S class, ESP32-C3 support and LEGO_HUB_NO6 board

This release of MicroPython adds support for f-strings (PEP-498), with a
few limitations compared to normal Python.  F-strings are essentially
syntactic sugar for "".format() and make formatting strings a lot more
convenient.  Other improvements to the core runtime include pretty printing
OSError when it has two arguments (an errno code and a string), scheduling
of KeyboardInterrupt on the main thread, and support for a single argument
to the optimised form of StopIteration.

In the machine module a new I2S class has been added, with support for
esp32 and stm32 ports.  This provides a consistent API for transmit and
receive of audio data in blocking, non-blocking and asyncio-based
operation.  Also, the json module has support for the "separators" argument
in the dump and dumps functions, and framebuf now includes a way to blit
between frame buffers of different formats using a palette.  A new,
portable machine.bitstream function is also added which can output a stream
of bits with configurable timing, and is used as the basis for driving
WS2812 LEDs in a common way across ports.

There has been some restructuring of the repository directory layout, with
all third-party code now in the lib/ directory.  And a new top-level
directory shared/ has been added with first-party code that was previously
in lib/ moved there.

The docs have seen further improvement with enhancements and additions to
the rp2 parts, as well as a new quick reference for the zephyr port.
The terms master/slave have been replaced with controller/peripheral,
mainly relating to I2C and SPI usage.  And u-module references have been
replaced with just the module name without the u-prefix to help clear up
the intended usage of modules in MicroPython.

For the esp8266 and esp32 ports, hidden networks are now included in WLAN
scan results.  On the esp32 the RMT class is enhanced with idle_level and
write_pulses modes.  There is initial support for ESP32-C3 chips with
GENERIC_C3 and GENERIC_C3_USB boards.

The javascript port has had its Makefile and garbage collector
implementation reworked so it compiles and runs with latest the Emscripten
using asyncify.

The mimxrt port sees the addition of hardware I2C and SPI support, as well
as some additional methods to the machine module.  There is also support
for Hyperflash chips.

The nrf port now has full VFS storage support, enables source-line on
traceback, and has .mpy features consistent with other ports.

For the rp2 port there is now more configurability for boards, and more
boards added.

The stm32 port has a new LEGO_HUB_NO6 board definition with detailed
information how to get this LEGO Hub running stock MicroPython.  There is
also now support to change the CPU frequency on STM32WB MCUs.  And USBD_xxx
descriptor options have been renamed to MICROPY_HW_USB_xxx.

Thanks to everyone who contributed to this release: Amir Gonnen, Andrew
Scheller, Bryan Tong Minh, Chris Wilson, Damien George, Daniel Mizyrycki,
David Lechner, David P, Fernando, finefoot, Frank Pilhofer, Glenn Ruben
Bakke, iabdalkader, Jeff Epler, Jim Mussared, Jonathan Hogg, Josh Klar,
Josh Lloyd, Julia Hathaway, Krzysztof Adamski, Matúš Olekšák, Michael
Weiss, Michel Bouwmans, Mike Causer, Mike Teachman, Ned Konz, NitiKaur,
oclyke, Patrick Van Oosterwijck, Peter Hinch, Peter Züger, Philipp
Ebensberger, robert-hh, Roberto Colistete Jr, Sashkoiv, Seon Rozenblum,
Tobias Thyrrestrup, Tom McDermott, Will Sowerbutts, Yonatan Goldschmidt.

What follows is a detailed list of changes, generated from the git commit
history, and organised into sections.

Main components
===============

all:
- fix signed shifts and NULL access errors from -fsanitize=undefined
- update to point to files in new shared/ directory

py core:
- mpstate: make exceptions thread-local
- mpstate: schedule KeyboardInterrupt on main thread
- mperrno: add MP_ECANCELED error code
- makeqstrdefs.py: don't include .h files explicitly in preprocessing
- mark unused arguments from bytecode decoding macros
- objexcept: pretty print OSError also when it has 2 arguments
- makeversionhdr: add --tags arg to git describe
- vm: simplify handling of MP_OBJ_STOP_ITERATION in yield-from opcode
- objexcept: make mp_obj_exception_get_value support subclassed excs
- support single argument to optimised MP_OBJ_STOP_ITERATION
- introduce and use mp_raise_type_arg helper
- modsys: optimise sys.exit for code size by using exception helpers
- objexcept: make mp_obj_new_exception_arg1 inline
- obj: fix formatting of comment for mp_obj_is_integer
- emitnative: reuse need_reg_all func in need_stack_settled
- emitnative: ensure stack settling is safe mid-branch
- runtime: fix bool unary op for subclasses of native types
- builtinimport: fix condition for including do_execute_raw_code()
- mkrules: automatically build mpy-cross if it doesn't exist
- implement partial PEP-498 (f-string) support
- lexer: clear fstring_args vstr on lexer free
- mkrules.mk: do submodule sync in "make submodules"

extmod:
- btstack: add missing call to mp_bluetooth_hci_uart_deinit
- btstack: check that BLE is active before performing operations
- uasyncio: get addr and bind server socket before creating task
- axtls-include: add axtls_os_port.h to customise axTLS
- update for move of crypto-algorithms, re1.5, uzlib to lib
- moduselect: conditionally compile select()
- nimble: fix leak in l2cap_send if send-while-stalled
- btstack/btstack.mk: use -Wno-implicit-fallthrough, not =0
- utime: always invoke mp_hal_delay_ms when >= to 0ms
- modbluetooth: clamp MTU values to 32->UINT16_MAX
- nimble: allow modbluetooth binding to hook "sent HCI packet"
- nimble: add "memory stalling" mechanism for l2cap_send
- uasyncio: in open_connection use address info in socket creation
- modujson: add support for dump/dumps separators keyword-argument
- modlwip: fix close and clean up of UDP and raw sockets
- modbluetooth: add send_update arg to gatts_write
- add machine.bitstream
- modframebuf: enable blit between different formats via a palette

lib:
- tinyusb: update to version 0.10.1
- pico-sdk: update to version 1.2.0
- utils/stdout_helpers: make mp_hal_stdout_tx_strn_cooked efficient
- axtls: switch to repo at micropython/axtls
- axtls: update to latest axtls 2.1.5 wih additional commits
- re1.5: move re1.5 code from extmod to lib
- uzlib: move uzlib code from extmod to lib
- crypto-algorithms: move crypto-algorithms code from extmod to lib
- update README's based on contents of these dirs

drivers:
- neopixel: add common machine.bitstream-based neopixel module
- neopixel: optimize fill() for speed
- neopixel: reduce code size of driver
- cyw43: fix cyw43_deinit so it can be called many times in a row
- cyw43: make wifi join fail if interface is not active

mpy-cross:
- disable stack check when building with Emscripten

Support components
==================

docs:
- library: document new esp32.RMT features and fix wait_done
- library: warn that ustruct doesn't handle spaces in format strings
- esp8266/tutorial: change flash mode from dio to dout
- replace master/slave with controller/peripheral in I2C and SPI
- rp2: enhance quickref and change image to Pico pinout
- rp2: update general section to give a brief technical overview
- library/utime.rst: clarify behaviour and precision of sleep ms/us
- library/uasyncio.rst: document stream readexactly() method
- library/machine.I2S.rst: fix use of sd pin in examples
- zephyr: add quick reference for the Zephyr port
- library/zephyr: add libraries specific to the Zephyr port
- templates: add unix and zephyr quickref links to top-index
- rename ufoo.rst to foo.rst
- replace ufoo with foo in all docs
- library/index.rst: clarify module naming and purpose
- library/builtins.rst: add module title
- library/network.rst: simplify socket import
- add docs for machine.bitstream and neopixel module
- library: fix usage of :term: for frozen module reference
- esp8266: use monospace for software tools
- reference: mention that slicing a memoryview causes allocation

examples: no changes specific to this component/port

tests:
- extmod: make uasyncio_heaplock test more deterministic
- cpydiff/modules_struct_whitespace_in_format: run black
- extmod/ujson: add tests for dump/dumps separators argument
- run-multitests.py: add broadcast and wait facility
- multi_bluetooth/ble_subscribe.py: add test for subscription
- extmod/vfs_fat_finaliser.py: ensure alloc at never-used GC blocks
- basics: split f-string debug printing to separate file with .exp
- pybnative: make while.py test run on boards without pyb.delay

tools:
- autobuild: add scripts to build release firmware
- remove obsolete build-stm-latest.sh script
- ci.sh: run apt-get update in ci_powerpc_setup
- makemanifest.py: allow passing flags to mpy-tool.py
- autobuild: add mimxrt port to build scripts for nightly builds
- pyboard.py: add cmd-line option to make soft reset configurable
- mpremote: swap order of PID and VID in connect-list output
- ci.sh: build unix dev variant as part of macOS CI
- ci.sh: build GENERIC_C3 board as part of esp32 CI
- autobuild: use separate IDF version to build newer esp32 SoCs
- autobuild: add FeatherS2 and TinyS2 to esp32 auto builds
- mpremote: add seek whence for mounted files
- mpremote: raise OSError on unsupported RemoteFile.seek
- autobuild: add the MIMXRT1050_EVKB board to the daily builds
- ci.sh: add mpy-cross build to nrf port
- codeformat.py: include ports/nrf/modules/nrf in code formatting
- gen-cpydiff.py: don't rename foo to ufoo in diff output
- autobuild: add auto build for Silicognition wESP32
- mpremote: fix connect-list in case VID/PID are None
- mpremote: add "devs" shortcut for "connect list"
- mpremote: remove support for pyb.USB_VCP in/out specialisation
- autobuild: don't use "-B" for make, it's already a fresh build
- pyboard.py: move --no-exclusive/--soft-reset out of mutex group
- pyboard.py: make --no-follow use same variable as --follow
- pyboard.py: add --exclusive to match --no-exclusive
- pyboard.py: make --no-soft-reset consistent with other args
- uncrustify: force 1 newline at end of file
- mpremote: bump version to 0.0.6

CI:
- workflows: add workflow to build and test javascript port
- workflows: switch from Coveralls to Codecov
- workflows: switch from lcov to gcov
- workflows: add workflow to build and test unix dev variant

The ports
=========

all ports:
- use common mp_hal_stdout_tx_strn_cooked instead of custom one
- update for move of crypto-algorithms, uzlib to lib
- rename USBD_VID/PID config macros to MICROPY_HW_USB_VID/PID

bare-arm port: no changes specific to this component/port

cc3200 port: no changes specific to this component/port

esp8266 port:
- add __len__ to NeoPixel driver to support iterating
- Makefile: add more libm files to build
- include hidden networks in WLAN.scan results
- replace esp.neopixel with machine.bitstream
- remove dead code for end_ticks in machine_bitstream

esp32 port:
- boards/sdkconfig.base: disable MEMPROT_FEATURE to alloc from IRAM
- add __len__ to NeoPixel driver to support iterating
- main: allow MICROPY_DIR to be overridden
- esp32_rmt: fix RMT looping in newer IDF versions
- esp32_rmt: enhance RMT with idle_level and write_pulses modes
- add new machine.I2S class for I2S protocol support
- machine_spi: calculate actual attained baudrate
- machine_hw_spi: use a 2 item SPI queue for long transfers
- machine_dac: add MICROPY_PY_MACHINE_DAC option, enable by default
- machine_i2s: add MICROPY_PY_MACHINE_I2S option, enable by default
- fix use of mp_int_t, size_t and uintptr_t
- add initial support for ESP32C3 SoCs
- boards/GENERIC_C3: add generic C3-based board
- modmachine: release the GIL in machine.idle()
- mphalport: always yield at least once in delay_ms
- machine_uart: add flow kw-arg to enable hardware flow control
- boards: add Silicognition wESP32 board configuration
- mpconfigport.h: enable reverse and inplace special methods
- include hidden networks in WLAN.scan results
- makeimg.py: get bootloader and partition offset from sdkconfig
- enable MICROPY_PY_FSTRINGS by default
- machine_hw_spi: release GIL during transfers
- machine_pin: make check for non-output pins respect chip variant
- replace esp.neopixel with machine.bitstream
- remove dead code for end_ticks in machine_bitstream
- boards: add GENERIC_C3_USB board with USB serial/JTAG support

javascript port:
- rework Makefile and GC so it works with latest Emscripten
- Makefile: suppress compiler errors from array bounds
- Makefile: change variable to EXPORTED_RUNTIME_METHODS

mimxrt port:
- move calc_weekday helper function to timeutils
- machine_spi: add the SPI class to the machine module
- moduos: seed the PRNG on boot using the TRNG
- boards: set vfs partition start to 1 MBbyte
- main: skip running main.py if boot.py failed
- main: extend the information returned by help()
- mimxrt_flash: remove commented-out code
- modmachine: add a few minor methods to the machine module
- machine_led: use mp_raise_msg_varg helper
- machine_i2c: add hardware-based machine.I2C to machine module
- add support for Hyperflash chips
- boards: add support for the MIMXRT1050_EVKB board
- machine_pin: implement ioctl for Pin

minimal port:
- Makefile: add support for building with user C modules

nrf port:
- modules: replace master/slave with controller/peripheral in SPI
- boards/common.ld: calculate unused flash region
- modules/nrf: add new nrf module with flash block device
- drivers: add support for using flash block device with SoftDevice
- mpconfigport.h: expose nrf module when MICROPY_PY_NRF is set
- README: update README.md to reflect internal file systems
- mpconfigport.h: tune FAT FS configuration
- Makefile: add _fs_size linker script override from make
- modules/uos: allow a board to configure MICROPY_VFS_FAT/LFS1/LFS2
- mpconfigport.h: enable MICROPY_PY_IO_FILEIO when an FS is enabled
- qstrdefsport.h: add entries for in-built FS mount points
- main: add auto mount and auto format hook for internal flash FS
- boards: enable needed features for FAT/LFS1/LFS2
- facilitate use of freeze manifest
- boards: set FROZEN_MANIFEST blank when SD present on nrf51 targets
- modules/scripts: add file system formatting script
- Makefile: set default manifest file for all targets
- mphalport: add dummy function for mp_hal_time_ns()
- boards: enable MICROPY_VFS_LFS2 for all target boards
- modules/uos: add ilistdir to uos module
- modules/nrf: add function to enable/disable DCDC
- enable source line on tracebacks
- set .mpy features consistent with documentation and other ports

pic16bit port: no changes specific to this component/port

powerpc port: no changes specific to this component/port

qemu-arm port: no changes specific to this component/port

rp2 port:
- use 0=Monday datetime convention in RTC
- machine_rtc: in RTC.datetime, compute weekday automatically
- CMakeLists.txt: suppress compiler errors for pico-sdk and tinyusb
- tusb_config.h: set CFG_TUD_CDC_EP_BUFSIZE to 256
- machine_uart: add hardware flow control support
- machine_uart: allow overriding default machine UART pins
- machine_i2c: allow boards to configure I2C pins using new macros
- machine_spi: allow boards to configure SPI pins using new macros
- machine_uart: fix poll ioctl to also check hardware FIFO
- machine_uart: fix read when FIFO has chars but ringbuf doesn't
- tusb_port: allow boards to configure USB VID and PID
- boards/ADAFRUIT_FEATHER_RP2040: configure custom VID/PID
- boards/ADAFRUIT_FEATHER_RP2040: configure I2C/SPI default pins
- boards/SPARKFUN_PROMICRO: configure UART/I2C/SPI default pins
- boards/SPARKFUN_THINGPLUS: configure I2C/SPI default pins
- boards: add Adafruit ItsyBitsy RP2040
- boards: add Adafruit QT Py RP2040
- boards: add Pimoroni Pico LiPo 4MB
- boards: add Pimoroni Pico LiPo 16MB
- boards: add Pimoroni Tiny 2040
- CMakeLists.txt: allow a board's cmake to set the manifest path
- enable MICROPY_PY_FSTRINGS by default
- Makefile: add "submodules" target, to match other ports
- rp2_flash: disable IRQs while calling flash_erase/program
- CMakeLists.txt: add option to enable double tap reset to bootrom
- mpconfigport.h: allow boards to add root pointers

samd port:
- add support for building with user C modules

stm32 port:
- softtimer: add soft_timer_reinsert() helper function
- mpbthciport: change from systick to soft-timer for BT scheduling
- provide a custom BTstack runloop that integrates with soft timer
- usb: make irq's default trigger enable all events
- boardctrl: skip running main.py if boot.py had an error
- sdio: fix undefined reference to DMA stream on H7
- dma: add DMAMUX configuration for H7 to fix dma_nohal_init
- main: call mp_deinit() at end of main
- adc: allow using ADC12 and ADC3 for H7
- adc: define the ADC instance used for internal channels
- adc: simplify and generalise how pin_adcX table is defined
- add new machine.I2S class for I2S protocol support
- boards/NUCLEO_F446RE: fix I2C1 pin assignment to match datasheet
- replace master/slave with controller/peripheral in I2C and SPI
- systick: always POLL_HOOK when delaying for milliseconds
- sdram: make SDRAM test cache aware, and optional failure with msg
- boards/NUCLEO_F446RE: enable CAN bus support
- boards: add support for SparkFun STM32 MicroMod Processor board
- uart: fix LPUART1 baudrate set/get
- uart: support low baudrates on LPUART1
- boards/STM32F429DISC: set correct UART2 pins and add UART3/6
- boards/NUCLEO_F439ZI: add board definition for NUCLEO_F439ZI
- boards/LEGO_HUB_NO6: add board definition for LEGO_HUB_NO6
- Makefile: update to only pull in used Bluetooth library
- README.md: update supported MCUs, and submodule and mboot use
- usbd_desc: rename USBD_xxx descriptor opts to MICROPY_HW_USB_xxx
- usbd_cdc_interface: rename USBD_CDC_xx opts to MICROPY_HW_USB_xx
- powerctrl: support changing frequency on WB MCUs
- boards/NUCLEO_H743ZI2: add modified version of NUCLEO_H743ZI
- mbedtls: fix compile warning about uninitialized val
- enable MICROPY_PY_FSTRINGS by default
- add implementation of machine.bitstream
- Makefile: allow GIT_SUBMODULES and LIBS to be extended
- stm32_it: support TIM17 IRQs on WB MCUs
- disable computed goto on constrained boards
- storage: make extended-block-device more configurable
- boards/LEGO_HUB_NO6: change SPI flash storage to use hardware SPI
- boards/LEGO_HUB_NO6: skip first 1MiB of SPI flash for storage
- boards/LEGO_HUB_NO6: add make commands to backup/restore firmware

teensy port: no changes specific to this component/port

unix port:
- modffi: add option to lock GC in callback, and cfun access
- Makefile: add back LIB_SRC_C to list of object files
- variants: enable help and help("modules") on standard and dev
- Makefile: disable error compression on arm-linux-gnueabi-gcc

windows port:
- Makefile: add .exe extension to executables name
- appveyor: update to VS 2017 and use Python 3.8 for build/test

zephyr port:
- machine_spi: add support for hardware SPI
2021-10-15 08:20:54 -05:00

556 lines
21 KiB
C

/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* SPDX-FileCopyrightText: Copyright (c) 2013, 2014 Damien P. George
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <string.h>
#include <assert.h>
#include "py/objlist.h"
#include "py/runtime.h"
#include "py/stackctrl.h"
#include "supervisor/shared/translate.h"
STATIC mp_obj_t mp_obj_new_list_iterator(mp_obj_t list, size_t cur, mp_obj_iter_buf_t *iter_buf);
STATIC mp_obj_list_t *list_new(size_t n);
STATIC mp_obj_t list_extend(mp_obj_t self_in, mp_obj_t arg_in);
STATIC mp_obj_t list_pop(size_t n_args, const mp_obj_t *args);
// TODO: Move to mpconfig.h
#define LIST_MIN_ALLOC 4
/******************************************************************************/
/* list */
STATIC void list_print(const mp_print_t *print, mp_obj_t o_in, mp_print_kind_t kind) {
mp_obj_list_t *o = MP_OBJ_TO_PTR(o_in);
const char *item_separator = ", ";
if (!(MICROPY_PY_UJSON && kind == PRINT_JSON)) {
kind = PRINT_REPR;
} else {
#if MICROPY_PY_UJSON_SEPARATORS
item_separator = MP_PRINT_GET_EXT(print)->item_separator;
#endif
}
mp_print_str(print, "[");
for (size_t i = 0; i < o->len; i++) {
if (i > 0) {
mp_print_str(print, item_separator);
}
mp_obj_print_helper(print, o->items[i], kind);
}
mp_print_str(print, "]");
}
STATIC mp_obj_t list_extend_from_iter(mp_obj_t list, mp_obj_t iterable) {
mp_obj_t iter = mp_getiter(iterable, NULL);
mp_obj_t item;
while ((item = mp_iternext(iter)) != MP_OBJ_STOP_ITERATION) {
mp_obj_list_append(list, item);
}
return list;
}
mp_obj_t mp_obj_new_list_from_iter(mp_obj_t iterable) {
mp_obj_t list = mp_obj_new_list(0, NULL);
return list_extend_from_iter(list, iterable);
}
STATIC mp_obj_t list_make_new(const mp_obj_type_t *type_in, size_t n_args, size_t n_kw, const mp_obj_t *args) {
(void)type_in;
mp_arg_check_num(n_args, n_kw, 0, 1, false);
switch (n_args) {
case 0:
// return a new, empty list
return mp_obj_new_list(0, NULL);
case 1:
default: {
// make list from iterable
// TODO: optimize list/tuple
mp_obj_t list = mp_obj_new_list(0, NULL);
return list_extend_from_iter(list, args[0]);
}
}
}
STATIC mp_obj_t list_unary_op(mp_unary_op_t op, mp_obj_t self_in) {
mp_obj_list_t *self = mp_obj_cast_to_native_base(self_in, &mp_type_list);
switch (op) {
case MP_UNARY_OP_BOOL:
return mp_obj_new_bool(self->len != 0);
case MP_UNARY_OP_LEN:
return MP_OBJ_NEW_SMALL_INT(self->len);
#if MICROPY_PY_SYS_GETSIZEOF
case MP_UNARY_OP_SIZEOF: {
size_t sz = sizeof(*self) + sizeof(mp_obj_t) * self->alloc;
return MP_OBJ_NEW_SMALL_INT(sz);
}
#endif
default:
return MP_OBJ_NULL; // op not supported
}
}
STATIC mp_obj_t list_binary_op(mp_binary_op_t op, mp_obj_t lhs, mp_obj_t rhs) {
mp_obj_list_t *o = mp_obj_cast_to_native_base(lhs, &mp_type_list);
switch (op) {
case MP_BINARY_OP_ADD: {
if (!mp_obj_is_type(rhs, &mp_type_list)) {
return MP_OBJ_NULL; // op not supported
}
mp_obj_list_t *p = MP_OBJ_TO_PTR(rhs);
mp_obj_list_t *s = list_new(o->len + p->len);
mp_seq_cat(s->items, o->items, o->len, p->items, p->len, mp_obj_t);
return MP_OBJ_FROM_PTR(s);
}
case MP_BINARY_OP_INPLACE_ADD: {
list_extend(lhs, rhs);
return lhs;
}
case MP_BINARY_OP_MULTIPLY: {
mp_int_t n;
if (!mp_obj_get_int_maybe(rhs, &n)) {
return MP_OBJ_NULL; // op not supported
}
if (n < 0) {
n = 0;
}
size_t new_len = mp_seq_multiply_len(o->len, n);
mp_obj_list_t *s = list_new(new_len);
mp_seq_multiply(o->items, sizeof(*o->items), o->len, n, s->items);
return MP_OBJ_FROM_PTR(s);
}
case MP_BINARY_OP_EQUAL:
case MP_BINARY_OP_LESS:
case MP_BINARY_OP_LESS_EQUAL:
case MP_BINARY_OP_MORE:
case MP_BINARY_OP_MORE_EQUAL: {
if (!mp_obj_is_type(rhs, &mp_type_list)) {
if (op == MP_BINARY_OP_EQUAL) {
return mp_const_false;
}
return MP_OBJ_NULL; // op not supported
}
mp_obj_list_t *another = MP_OBJ_TO_PTR(rhs);
bool res = mp_seq_cmp_objs(op, o->items, o->len, another->items, another->len);
return mp_obj_new_bool(res);
}
default:
return MP_OBJ_NULL; // op not supported
}
}
STATIC mp_obj_t list_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) {
mp_obj_list_t *self = mp_obj_cast_to_native_base(self_in, &mp_type_list);
if (value == MP_OBJ_NULL) {
// delete
#if MICROPY_PY_BUILTINS_SLICE
if (mp_obj_is_type(index, &mp_type_slice)) {
mp_bound_slice_t slice;
if (!mp_seq_get_fast_slice_indexes(self->len, index, &slice)) {
mp_raise_NotImplementedError(NULL);
}
mp_int_t len_adj = slice.start - slice.stop;
assert(len_adj <= 0);
mp_seq_replace_slice_no_grow(self->items, self->len, slice.start, slice.stop, self->items /*NULL*/, 0, sizeof(*self->items));
// Clear "freed" elements at the end of list
mp_seq_clear(self->items, self->len + len_adj, self->len, sizeof(*self->items));
self->len += len_adj;
return mp_const_none;
}
#endif
mp_obj_t args[2] = {self, index};
list_pop(2, args);
return mp_const_none;
} else if (value == MP_OBJ_SENTINEL) {
// load
#if MICROPY_PY_BUILTINS_SLICE
if (mp_obj_is_type(index, &mp_type_slice)) {
mp_bound_slice_t slice;
if (!mp_seq_get_fast_slice_indexes(self->len, index, &slice)) {
return mp_seq_extract_slice(self->len, self->items, &slice);
}
mp_obj_list_t *res = list_new(slice.stop - slice.start);
mp_seq_copy(res->items, self->items + slice.start, res->len, mp_obj_t);
return MP_OBJ_FROM_PTR(res);
}
#endif
size_t index_val = mp_get_index(self->base.type, self->len, index, false);
return self->items[index_val];
} else {
#if MICROPY_PY_BUILTINS_SLICE
if (mp_obj_is_type(index, &mp_type_slice)) {
size_t value_len;
mp_obj_t *value_items;
mp_obj_get_array(value, &value_len, &value_items);
mp_bound_slice_t slice_out;
if (!mp_seq_get_fast_slice_indexes(self->len, index, &slice_out)) {
mp_raise_NotImplementedError(NULL);
}
mp_int_t len_adj = value_len - (slice_out.stop - slice_out.start);
if (len_adj > 0) {
if (self->len + len_adj > self->alloc) {
// TODO: Might optimize memory copies here by checking if block can
// be grown inplace or not
self->items = m_renew(mp_obj_t, self->items, self->alloc, self->len + len_adj);
self->alloc = self->len + len_adj;
}
mp_seq_replace_slice_grow_inplace(self->items, self->len,
slice_out.start, slice_out.stop, value_items, value_len, len_adj, sizeof(*self->items));
} else {
mp_seq_replace_slice_no_grow(self->items, self->len,
slice_out.start, slice_out.stop, value_items, value_len, sizeof(*self->items));
// Clear "freed" elements at the end of list
mp_seq_clear(self->items, self->len + len_adj, self->len, sizeof(*self->items));
// TODO: apply allocation policy re: alloc_size
}
self->len += len_adj;
return mp_const_none;
}
#endif
mp_obj_list_store(self, index, value);
return mp_const_none;
}
}
STATIC mp_obj_t list_getiter(mp_obj_t o_in, mp_obj_iter_buf_t *iter_buf) {
return mp_obj_new_list_iterator(o_in, 0, iter_buf);
}
mp_obj_t mp_obj_list_append(mp_obj_t self_in, mp_obj_t arg) {
mp_check_self(mp_obj_is_type(self_in, &mp_type_list));
mp_obj_list_t *self = mp_obj_cast_to_native_base(self_in, &mp_type_list);
if (self->len >= self->alloc) {
self->items = m_renew(mp_obj_t, self->items, self->alloc, self->alloc * 2);
self->alloc *= 2;
mp_seq_clear(self->items, self->len + 1, self->alloc, sizeof(*self->items));
}
self->items[self->len++] = arg;
return mp_const_none; // return None, as per CPython
}
STATIC mp_obj_t list_extend(mp_obj_t self_in, mp_obj_t arg_in) {
mp_check_self(mp_obj_is_type(self_in, &mp_type_list));
if (mp_obj_is_type(arg_in, &mp_type_list)) {
mp_obj_list_t *self = mp_obj_cast_to_native_base(self_in, &mp_type_list);
mp_obj_list_t *arg = mp_obj_cast_to_native_base(arg_in, &mp_type_list);
if (self->len + arg->len > self->alloc) {
// TODO: use alloc policy for "4"
self->items = m_renew(mp_obj_t, self->items, self->alloc, self->len + arg->len + 4);
self->alloc = self->len + arg->len + 4;
mp_seq_clear(self->items, self->len + arg->len, self->alloc, sizeof(*self->items));
}
memcpy(self->items + self->len, arg->items, sizeof(mp_obj_t) * arg->len);
self->len += arg->len;
} else {
list_extend_from_iter(self_in, arg_in);
}
return mp_const_none; // return None, as per CPython
}
inline mp_obj_t mp_obj_list_pop(mp_obj_list_t *self, size_t index) {
if (self->len == 0) {
mp_raise_IndexError_varg(MP_ERROR_TEXT("pop from empty %q"), MP_QSTR_list);
}
mp_obj_t ret = self->items[index];
self->len -= 1;
memmove(self->items + index, self->items + index + 1, (self->len - index) * sizeof(mp_obj_t));
// Clear stale pointer from slot which just got freed to prevent GC issues
self->items[self->len] = MP_OBJ_NULL;
if (self->alloc > LIST_MIN_ALLOC && self->alloc > 2 * self->len) {
self->items = m_renew(mp_obj_t, self->items, self->alloc, self->alloc / 2);
self->alloc /= 2;
}
return ret;
}
STATIC mp_obj_t list_pop(size_t n_args, const mp_obj_t *args) {
mp_check_self(mp_obj_is_type(args[0], &mp_type_list));
mp_obj_list_t *self = mp_obj_cast_to_native_base(args[0], &mp_type_list);
size_t index = mp_get_index(self->base.type, self->len, n_args == 1 ? MP_OBJ_NEW_SMALL_INT(-1) : args[1], false);
return mp_obj_list_pop(self, index);
}
STATIC void mp_quicksort(mp_obj_t *head, mp_obj_t *tail, mp_obj_t key_fn, mp_obj_t binop_less_result) {
MP_STACK_CHECK();
while (head < tail) {
mp_obj_t *h = head - 1;
mp_obj_t *t = tail;
mp_obj_t v = key_fn == MP_OBJ_NULL ? tail[0] : mp_call_function_1(key_fn, tail[0]); // get pivot using key_fn
for (;;) {
do {++h;
} while (h < t && mp_binary_op(MP_BINARY_OP_LESS, key_fn == MP_OBJ_NULL ? h[0] : mp_call_function_1(key_fn, h[0]), v) == binop_less_result);
do {--t;
} while (h < t && mp_binary_op(MP_BINARY_OP_LESS, v, key_fn == MP_OBJ_NULL ? t[0] : mp_call_function_1(key_fn, t[0])) == binop_less_result);
if (h >= t) {
break;
}
mp_obj_t x = h[0];
h[0] = t[0];
t[0] = x;
}
mp_obj_t x = h[0];
h[0] = tail[0];
tail[0] = x;
// do the smaller recursive call first, to keep stack within O(log(N))
if (t - head < tail - h - 1) {
mp_quicksort(head, t, key_fn, binop_less_result);
head = h + 1;
} else {
mp_quicksort(h + 1, tail, key_fn, binop_less_result);
tail = t;
}
}
}
// TODO Python defines sort to be stable but ours is not
mp_obj_t mp_obj_list_sort(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
static const mp_arg_t allowed_args[] = {
{ MP_QSTR_key, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_rom_obj = MP_ROM_NONE} },
{ MP_QSTR_reverse, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = false} },
};
// parse args
struct {
mp_arg_val_t key, reverse;
} args;
mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args,
MP_ARRAY_SIZE(allowed_args), allowed_args, (mp_arg_val_t *)&args);
mp_check_self(mp_obj_is_type(pos_args[0], &mp_type_list));
mp_obj_list_t *self = mp_obj_cast_to_native_base(pos_args[0], &mp_type_list);
if (self->len > 1) {
mp_quicksort(self->items, self->items + self->len - 1,
args.key.u_obj == mp_const_none ? MP_OBJ_NULL : args.key.u_obj,
args.reverse.u_bool ? mp_const_false : mp_const_true);
}
return mp_const_none;
}
mp_obj_t mp_obj_list_clear(mp_obj_t self_in) {
mp_check_self(mp_obj_is_type(self_in, &mp_type_list));
mp_obj_list_t *self = mp_obj_cast_to_native_base(self_in, &mp_type_list);
self->len = 0;
self->items = m_renew(mp_obj_t, self->items, self->alloc, LIST_MIN_ALLOC);
self->alloc = LIST_MIN_ALLOC;
mp_seq_clear(self->items, 0, self->alloc, sizeof(*self->items));
return mp_const_none;
}
STATIC mp_obj_t list_copy(mp_obj_t self_in) {
mp_check_self(mp_obj_is_type(self_in, &mp_type_list));
mp_obj_list_t *self = mp_obj_cast_to_native_base(self_in, &mp_type_list);
return mp_obj_new_list(self->len, self->items);
}
STATIC mp_obj_t list_count(mp_obj_t self_in, mp_obj_t value) {
mp_check_self(mp_obj_is_type(self_in, &mp_type_list));
mp_obj_list_t *self = mp_obj_cast_to_native_base(self_in, &mp_type_list);
return mp_seq_count_obj(self->items, self->len, value);
}
STATIC mp_obj_t list_index(size_t n_args, const mp_obj_t *args) {
mp_check_self(mp_obj_is_type(args[0], &mp_type_list));
mp_obj_list_t *self = mp_obj_cast_to_native_base(args[0], &mp_type_list);
return mp_seq_index_obj(self->items, self->len, n_args, args);
}
inline void mp_obj_list_insert(mp_obj_list_t *self, size_t index, mp_obj_t obj) {
mp_obj_list_append(MP_OBJ_FROM_PTR(self), mp_const_none);
for (size_t i = self->len - 1; i > index; --i) {
self->items[i] = self->items[i - 1];
}
self->items[index] = obj;
}
STATIC mp_obj_t list_insert(mp_obj_t self_in, mp_obj_t idx, mp_obj_t obj) {
mp_check_self(mp_obj_is_type(self_in, &mp_type_list));
mp_obj_list_t *self = mp_obj_cast_to_native_base(self_in, &mp_type_list);
// insert has its own strange index logic
mp_int_t index = MP_OBJ_SMALL_INT_VALUE(idx);
if (index < 0) {
index += self->len;
}
if (index < 0) {
index = 0;
}
if ((size_t)index > self->len) {
index = self->len;
}
mp_obj_list_insert(self, index, obj);
return mp_const_none;
}
mp_obj_t mp_obj_list_remove(mp_obj_t self_in, mp_obj_t value) {
mp_check_self(mp_obj_is_type(self_in, &mp_type_list));
mp_obj_t args[] = {self_in, value};
args[1] = list_index(2, args);
list_pop(2, args);
return mp_const_none;
}
STATIC mp_obj_t list_reverse(mp_obj_t self_in) {
mp_check_self(mp_obj_is_type(self_in, &mp_type_list));
mp_obj_list_t *self = mp_obj_cast_to_native_base(self_in, &mp_type_list);
mp_int_t len = self->len;
for (mp_int_t i = 0; i < len / 2; i++) {
mp_obj_t a = self->items[i];
self->items[i] = self->items[len - i - 1];
self->items[len - i - 1] = a;
}
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(list_append_obj, mp_obj_list_append);
STATIC MP_DEFINE_CONST_FUN_OBJ_2(list_extend_obj, list_extend);
STATIC MP_DEFINE_CONST_FUN_OBJ_1(list_clear_obj, mp_obj_list_clear);
STATIC MP_DEFINE_CONST_FUN_OBJ_1(list_copy_obj, list_copy);
STATIC MP_DEFINE_CONST_FUN_OBJ_2(list_count_obj, list_count);
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(list_index_obj, 2, 4, list_index);
STATIC MP_DEFINE_CONST_FUN_OBJ_3(list_insert_obj, list_insert);
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(list_pop_obj, 1, 2, list_pop);
STATIC MP_DEFINE_CONST_FUN_OBJ_2(list_remove_obj, mp_obj_list_remove);
STATIC MP_DEFINE_CONST_FUN_OBJ_1(list_reverse_obj, list_reverse);
STATIC MP_DEFINE_CONST_FUN_OBJ_KW(list_sort_obj, 1, mp_obj_list_sort);
STATIC const mp_rom_map_elem_t list_locals_dict_table[] = {
{ MP_ROM_QSTR(MP_QSTR_append), MP_ROM_PTR(&list_append_obj) },
{ MP_ROM_QSTR(MP_QSTR_clear), MP_ROM_PTR(&list_clear_obj) },
{ MP_ROM_QSTR(MP_QSTR_copy), MP_ROM_PTR(&list_copy_obj) },
{ MP_ROM_QSTR(MP_QSTR_count), MP_ROM_PTR(&list_count_obj) },
{ MP_ROM_QSTR(MP_QSTR_extend), MP_ROM_PTR(&list_extend_obj) },
{ MP_ROM_QSTR(MP_QSTR_index), MP_ROM_PTR(&list_index_obj) },
{ MP_ROM_QSTR(MP_QSTR_insert), MP_ROM_PTR(&list_insert_obj) },
{ MP_ROM_QSTR(MP_QSTR_pop), MP_ROM_PTR(&list_pop_obj) },
{ MP_ROM_QSTR(MP_QSTR_remove), MP_ROM_PTR(&list_remove_obj) },
{ MP_ROM_QSTR(MP_QSTR_reverse), MP_ROM_PTR(&list_reverse_obj) },
{ MP_ROM_QSTR(MP_QSTR_sort), MP_ROM_PTR(&list_sort_obj) },
};
STATIC MP_DEFINE_CONST_DICT(list_locals_dict, list_locals_dict_table);
const mp_obj_type_t mp_type_list = {
{ &mp_type_type },
.flags = MP_TYPE_FLAG_EXTENDED,
.name = MP_QSTR_list,
.print = list_print,
.make_new = list_make_new,
.locals_dict = (mp_obj_dict_t *)&list_locals_dict,
MP_TYPE_EXTENDED_FIELDS(
.unary_op = list_unary_op,
.binary_op = list_binary_op,
.subscr = list_subscr,
.getiter = list_getiter,
),
};
void mp_obj_list_init(mp_obj_list_t *o, size_t n) {
o->base.type = &mp_type_list;
o->alloc = n < LIST_MIN_ALLOC ? LIST_MIN_ALLOC : n;
o->len = n;
o->items = m_new(mp_obj_t, o->alloc);
mp_seq_clear(o->items, n, o->alloc, sizeof(*o->items));
}
STATIC mp_obj_list_t *list_new(size_t n) {
mp_obj_list_t *o = m_new_obj(mp_obj_list_t);
mp_obj_list_init(o, n);
return o;
}
mp_obj_t mp_obj_new_list(size_t n, mp_obj_t *items) {
mp_obj_list_t *o = list_new(n);
if (items != NULL) {
for (size_t i = 0; i < n; i++) {
o->items[i] = items[i];
}
}
return MP_OBJ_FROM_PTR(o);
}
void mp_obj_list_get(mp_obj_t self_in, size_t *len, mp_obj_t **items) {
mp_obj_list_t *self = mp_obj_cast_to_native_base(self_in, &mp_type_list);
*len = self->len;
*items = self->items;
}
void mp_obj_list_set_len(mp_obj_t self_in, size_t len) {
// trust that the caller knows what it's doing
// TODO realloc if len got much smaller than alloc
mp_obj_list_t *self = MP_OBJ_TO_PTR(self_in);
self->len = len;
}
void mp_obj_list_store(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) {
mp_obj_list_t *self = mp_obj_cast_to_native_base(self_in, &mp_type_list);
size_t i = mp_get_index(self->base.type, self->len, index, false);
self->items[i] = value;
}
/******************************************************************************/
/* list iterator */
typedef struct _mp_obj_list_it_t {
mp_obj_base_t base;
mp_fun_1_t iternext;
mp_obj_t list;
size_t cur;
} mp_obj_list_it_t;
STATIC mp_obj_t list_it_iternext(mp_obj_t self_in) {
mp_obj_list_it_t *self = MP_OBJ_TO_PTR(self_in);
mp_obj_list_t *list = MP_OBJ_TO_PTR(self->list);
if (self->cur < list->len) {
mp_obj_t o_out = list->items[self->cur];
self->cur += 1;
return o_out;
} else {
return MP_OBJ_STOP_ITERATION;
}
}
mp_obj_t mp_obj_new_list_iterator(mp_obj_t list, size_t cur, mp_obj_iter_buf_t *iter_buf) {
assert(sizeof(mp_obj_list_it_t) <= sizeof(mp_obj_iter_buf_t));
mp_obj_list_it_t *o = (mp_obj_list_it_t *)iter_buf;
o->base.type = &mp_type_polymorph_iter;
o->iternext = list_it_iternext;
o->list = list;
o->cur = cur;
return MP_OBJ_FROM_PTR(o);
}