diff --git a/.gitignore b/.gitignore index 280db388f5..5e841a89c0 100644 --- a/.gitignore +++ b/.gitignore @@ -9,7 +9,7 @@ *.dis *.exe -# Packages +# Packages ############ # Logs and Databases diff --git a/.travis.yml b/.travis.yml index 76aa965d2d..14d5df0a45 100644 --- a/.travis.yml +++ b/.travis.yml @@ -20,7 +20,8 @@ before_script: # For teensy build - sudo apt-get install realpath # For coverage testing - - sudo pip install cpp-coveralls + # cpp-coveralls 0.4 conflicts with urllib3 preinstalled in Travis VM + - sudo pip install cpp-coveralls==0.3.12 - gcc --version - arm-none-eabi-gcc --version - python3 --version @@ -40,7 +41,7 @@ script: - make -C qemu-arm test - make -C stmhal - make -C stmhal BOARD=PYBV11 MICROPY_PY_WIZNET5K=1 MICROPY_PY_CC3K=1 - - make -C stmhal BOARD=STM32F7DISC + - make -C stmhal BOARD=STM32F769DISC - make -C stmhal BOARD=STM32L476DISC - make -C teensy - make -C cc3200 BTARGET=application BTYPE=release diff --git a/CODECONVENTIONS.md b/CODECONVENTIONS.md index 7ab920806d..982b958313 100644 --- a/CODECONVENTIONS.md +++ b/CODECONVENTIONS.md @@ -26,6 +26,27 @@ require such detailed description. To get good practical examples of good commits and their messages, browse the `git log` of the project. +MicroPython doesn't require explicit sign-off for patches ("Signed-off-by" +lines and similar). Instead, the commit message, and your name and email +address on it construes your sign-off of the following: + +* That you wrote the change yourself, or took it from a project with + a compatible license (in the latter case the commit message, and possibly + source code should provide reference where the implementation was taken + from and give credit to the original author, as required by the license). +* That you are allowed to release these changes to an open-source project + (for example, changes done during paid work for a third party may require + explicit approval from that third party). +* That you (or your employer) agree to release the changes under + MicroPython's license, which is the MIT license. Note that you retain + copyright for your changes (for smaller changes, the commit message + conveys your copyright; if you make significant changes to a particular + source module, you're welcome to add your name to the file header). +* Your signature for all of the above, which is the 'Author' line in + the commit message, and which should include your full real name and + a valid and active email address by which you can be contacted in the + foreseeable future. + Python code conventions ======================= @@ -52,7 +73,7 @@ White space: keyword and the opening parenthesis. - Put 1 space after a comma, and 1 space around operators. -Braces: +Braces: - Use braces for all blocks, even no-line and single-line pieces of code. - Put opening braces on the end of the line it belongs to, not on @@ -114,3 +135,76 @@ Type declarations: int member; void *data; } my_struct_t; + +Documentation conventions +========================= + +MicroPython generally follows CPython in documentation process and +conventions. reStructuredText syntax is used for the documention. + +Specific conventions/suggestions: + +* Use `*` markup to refer to arguments of a function, e.g.: + +``` +.. method:: poll.unregister(obj) + + Unregister *obj* from polling. +``` + +* Use following syntax for cross-references/cross-links: + +``` +:func:`foo` - function foo in current module +:func:`module1.foo` - function foo in module "module1" + (similarly for other referent types) +:class:`Foo` - class Foo +:meth:`Class.method1` - method1 in Class +:meth:`~Class.method1` - method1 in Class, but rendered just as "method1()", + not "Class.method1()" +:meth:`title ` - reference method1, but render as "title" (use only + if really needed) +:mod:`module1` - module module1 + +`symbol` - generic xref syntax which can replace any of the above in case + the xref is unambiguous. If there's ambiguity, there will be a warning + during docs generation, which need to be fixed using one of the syntaxes + above +``` + +* Cross-referencing arbitrary locations +~~~ +.. _xref_target: + +Normal non-indented text. + +This is :ref:`reference `. + +(If xref target is followed by section title, can be just +:ref:`xref_target`). +~~~ + +* Linking to external URL: +``` +`link text `_ +``` + +* Referencing builtin singleton objects: +``` +``None``, ``True``, ``False`` +``` + +* Use following syntax to create common description for more than one element: +~~~ +.. function:: foo(x) + bar(y) + + Description common to foo() and bar(). +~~~ + + +More detailed guides and quickrefs: + +* http://www.sphinx-doc.org/en/stable/rest.html +* http://www.sphinx-doc.org/en/stable/markup/inline.html +* http://docutils.sourceforge.net/docs/user/rst/quickref.html diff --git a/README.md b/README.md index 26c6f6a01d..481cac4e42 100644 --- a/README.md +++ b/README.md @@ -22,12 +22,18 @@ Builtin modules include `sys`, `time`, and `struct`, etc. Select ports have support for `_thread` module (multithreading). Note that only a subset of Python 3 functionality is implemented for the data types and modules. -See the repository www.github.com/micropython/pyboard for the MicroPython +MicroPython can execute scripts in textual source form or from precompiled +bytecode, in both cases either from an on-device filesystem or "frozen" into +the MicroPython executable. + +See the repository http://github.com/micropython/pyboard for the MicroPython board (PyBoard), the officially supported reference electronic circuit board. Major components in this repository: - py/ -- the core Python implementation, including compiler, runtime, and core library. +- mpy-cross/ -- the MicroPython cross-compiler which is used to turn scripts + into precompiled bytecode. - unix/ -- a version of MicroPython that runs on Unix. - stmhal/ -- a version of MicroPython that runs on the PyBoard and similar STM32 boards (using ST's Cube HAL drivers). diff --git a/bare-arm/mpconfigport.h b/bare-arm/mpconfigport.h index 97e866bdb7..17f7945218 100644 --- a/bare-arm/mpconfigport.h +++ b/bare-arm/mpconfigport.h @@ -1,6 +1,6 @@ #include -// options to control how Micro Python is built +// options to control how MicroPython is built #define MICROPY_QSTR_BYTES_IN_HASH (1) #define MICROPY_ALLOC_PATH_MAX (512) diff --git a/bare-arm/stm32f405.ld b/bare-arm/stm32f405.ld index 345a92d3c1..dd688a0246 100644 --- a/bare-arm/stm32f405.ld +++ b/bare-arm/stm32f405.ld @@ -11,7 +11,7 @@ MEMORY CCMRAM (xrw) : ORIGIN = 0x10000000, LENGTH = 0x010000 /* 64 KiB */ RAM (xrw) : ORIGIN = 0x20000000, LENGTH = 0x020000 /* 128 KiB */ } - + /* top end of the stack */ _estack = ORIGIN(RAM) + LENGTH(RAM); @@ -30,7 +30,7 @@ SECTIONS . = ALIGN(4); } >FLASH_ISR - + /* The program code and other data goes into FLASH */ .text : { @@ -46,7 +46,7 @@ SECTIONS _etext = .; /* define a global symbol at end of code */ _sidata = _etext; /* This is used by the startup in order to initialize the .data secion */ } >FLASH_TEXT - + /* .ARM.extab : { @@ -60,7 +60,7 @@ SECTIONS __exidx_end = .; } >FLASH */ - + /* This is the initialized data section The program executes knowing that the data is in the RAM but the loader puts the initial values in the FLASH (inidata). @@ -76,7 +76,7 @@ SECTIONS . = ALIGN(4); _edata = .; /* define a global symbol at data end; used by startup code in order to initialise the .data section in RAM */ } >RAM - + /* Uninitialized data section */ .bss : { diff --git a/cc3200/application.lds b/cc3200/application.lds index 22ad1968d5..3f5e72f8bd 100644 --- a/cc3200/application.lds +++ b/cc3200/application.lds @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -37,7 +37,7 @@ ENTRY(ResetISR) SECTIONS { - /* place the FreeRTOS heap (the micropython stack will live here) */ + /* place the FreeRTOS heap (the MicroPython stack will live here) */ .rtos_heap (NOLOAD) : { . = ALIGN(8); @@ -83,7 +83,7 @@ SECTIONS } > SRAM /* place here functions that are only called during boot up, */ - /* that way, we can re-use this area for the micropython heap */ + /* that way, we can re-use this area for the MicroPython heap */ .boot : { . = ALIGN(8); @@ -93,7 +93,7 @@ SECTIONS _eboot = .; } > SRAM - /* allocate the micropython heap */ + /* allocate the MicroPython heap */ .heap : { . = ALIGN(8); diff --git a/cc3200/application.mk b/cc3200/application.mk index 1f54b764b9..c6b91ed0ed 100644 --- a/cc3200/application.mk +++ b/cc3200/application.mk @@ -147,12 +147,12 @@ APP_LIB_SRC_C = $(addprefix lib/,\ netutils/netutils.c \ timeutils/timeutils.c \ utils/pyexec.c \ + utils/sys_stdio_mphal.c \ ) APP_STM_SRC_C = $(addprefix stmhal/,\ bufhelper.c \ irq.c \ - pybstdio.c \ ) OBJ = $(PY_O) $(addprefix $(BUILD)/, $(APP_FATFS_SRC_C:.c=.o) $(APP_RTOS_SRC_C:.c=.o) $(APP_FTP_SRC_C:.c=.o) $(APP_HAL_SRC_C:.c=.o) $(APP_MISC_SRC_C:.c=.o)) diff --git a/cc3200/boards/LAUNCHXL/mpconfigboard.h b/cc3200/boards/LAUNCHXL/mpconfigboard.h index 32ef5290b4..b3d766d1e2 100644 --- a/cc3200/boards/LAUNCHXL/mpconfigboard.h +++ b/cc3200/boards/LAUNCHXL/mpconfigboard.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/cc3200/boards/WIPY/mpconfigboard.h b/cc3200/boards/WIPY/mpconfigboard.h index 9f04dbf237..af15cca350 100644 --- a/cc3200/boards/WIPY/mpconfigboard.h +++ b/cc3200/boards/WIPY/mpconfigboard.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/cc3200/boards/cc3200_prefix.c b/cc3200/boards/cc3200_prefix.c index 9712857453..d03efe0240 100644 --- a/cc3200/boards/cc3200_prefix.c +++ b/cc3200/boards/cc3200_prefix.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/cc3200/bootmgr/bootmgr.h b/cc3200/bootmgr/bootmgr.h index 4b314335c0..5a370f8c99 100644 --- a/cc3200/bootmgr/bootmgr.h +++ b/cc3200/bootmgr/bootmgr.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,9 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - -#ifndef __BOOTMGR_H__ -#define __BOOTMGR_H__ +#ifndef MICROPY_INCLUDED_CC3200_BOOTMGR_BOOTMGR_H +#define MICROPY_INCLUDED_CC3200_BOOTMGR_BOOTMGR_H //**************************************************************************** // @@ -66,4 +65,4 @@ extern void Run(unsigned long); } #endif -#endif //__BOOTMGR_H__ +#endif // MICROPY_INCLUDED_CC3200_BOOTMGR_BOOTMGR_H diff --git a/cc3200/bootmgr/bootmgr.lds b/cc3200/bootmgr/bootmgr.lds index e67fe23ae6..9c911a0d08 100644 --- a/cc3200/bootmgr/bootmgr.lds +++ b/cc3200/bootmgr/bootmgr.lds @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/cc3200/bootmgr/flc.h b/cc3200/bootmgr/flc.h index 4b2aca9ac5..8f05bb320e 100644 --- a/cc3200/bootmgr/flc.h +++ b/cc3200/bootmgr/flc.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,9 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - -#ifndef __FLC_H__ -#define __FLC_H__ +#ifndef MICROPY_INCLUDED_CC3200_BOOTMGR_FLC_H +#define MICROPY_INCLUDED_CC3200_BOOTMGR_FLC_H /****************************************************************************** @@ -93,4 +92,4 @@ typedef struct _sBootInfo_t } #endif -#endif /* __FLC_H__ */ +#endif // MICROPY_INCLUDED_CC3200_BOOTMGR_FLC_H diff --git a/cc3200/bootmgr/main.c b/cc3200/bootmgr/main.c index 0d9ab35f83..cfb8dec21d 100644 --- a/cc3200/bootmgr/main.c +++ b/cc3200/bootmgr/main.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/cc3200/ftp/ftp.c b/cc3200/ftp/ftp.c index 1febe291f9..5461f9180a 100644 --- a/cc3200/ftp/ftp.c +++ b/cc3200/ftp/ftp.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -335,7 +335,7 @@ void ftp_run (void) { ftp_data.loggin.uservalid = false; ftp_data.loggin.passvalid = false; strcpy (ftp_path, "/"); - ftp_send_reply (220, "Micropython FTP Server"); + ftp_send_reply (220, "MicroPython FTP Server"); break; } } diff --git a/cc3200/ftp/ftp.h b/cc3200/ftp/ftp.h index 13b044dcfa..af4c14fa3b 100644 --- a/cc3200/ftp/ftp.h +++ b/cc3200/ftp/ftp.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,9 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - -#ifndef FTP_H_ -#define FTP_H_ +#ifndef MICROPY_INCLUDED_CC3200_FTP_FTP_H +#define MICROPY_INCLUDED_CC3200_FTP_FTP_H /****************************************************************************** DECLARE EXPORTED FUNCTIONS @@ -36,4 +35,4 @@ extern void ftp_enable (void); extern void ftp_disable (void); extern void ftp_reset (void); -#endif /* FTP_H_ */ +#endif // MICROPY_INCLUDED_CC3200_FTP_FTP_H diff --git a/cc3200/ftp/updater.c b/cc3200/ftp/updater.c index fece70095b..5be2c6063c 100644 --- a/cc3200/ftp/updater.c +++ b/cc3200/ftp/updater.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/cc3200/ftp/updater.h b/cc3200/ftp/updater.h index b581d0fc8a..51248e4bf3 100644 --- a/cc3200/ftp/updater.h +++ b/cc3200/ftp/updater.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,10 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - - -#ifndef UPDATER_H_ -#define UPDATER_H_ +#ifndef MICROPY_INCLUDED_CC3200_FTP_UPDATER_H +#define MICROPY_INCLUDED_CC3200_FTP_UPDATER_H extern void updater_pre_init (void); extern bool updater_check_path (void *path); @@ -35,4 +33,4 @@ extern bool updater_write (uint8_t *buf, uint32_t len); extern void updater_finnish (void); extern bool updater_verify (uint8_t *rbuff, uint8_t *hasbuff); -#endif /* UPDATER_H_ */ +#endif // MICROPY_INCLUDED_CC3200_FTP_UPDATER_H diff --git a/cc3200/hal/cc3200_asm.h b/cc3200/hal/cc3200_asm.h index dcaaf57e1b..742c9a6f7f 100644 --- a/cc3200/hal/cc3200_asm.h +++ b/cc3200/hal/cc3200_asm.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/cc3200/hal/cc3200_hal.c b/cc3200/hal/cc3200_hal.c index 5c0e9c30fb..b4848e99e8 100644 --- a/cc3200/hal/cc3200_hal.c +++ b/cc3200/hal/cc3200_hal.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/cc3200/hal/cc3200_hal.h b/cc3200/hal/cc3200_hal.h index fcb85b2928..71e245eeb1 100644 --- a/cc3200/hal/cc3200_hal.h +++ b/cc3200/hal/cc3200_hal.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -24,9 +24,6 @@ * THE SOFTWARE. */ -#ifndef CC3200_LAUNCHXL_HAL_CC3200_HAL_H_ -#define CC3200_LAUNCHXL_HAL_CC3200_HAL_H_ - #include #include @@ -69,5 +66,3 @@ extern void mp_hal_set_interrupt_char (int c); #define mp_hal_delay_us(usec) UtilsDelay(UTILS_DELAY_US_TO_COUNT(usec)) #define mp_hal_ticks_cpu() (SysTickPeriodGet() - SysTickValueGet()) - -#endif /* CC3200_LAUNCHXL_HAL_CC3200_HAL_H_ */ diff --git a/cc3200/hal/fault_registers.h b/cc3200/hal/fault_registers.h index 739745e92a..ade516b9e4 100644 --- a/cc3200/hal/fault_registers.h +++ b/cc3200/hal/fault_registers.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/cc3200/main.c b/cc3200/main.c index 7c6c4b545d..e2299e1460 100644 --- a/cc3200/main.c +++ b/cc3200/main.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -89,7 +89,7 @@ int main (void) { #ifndef DEBUG OsiTaskHandle mpTaskHandle; #endif - mpTaskHandle = xTaskCreateStatic(TASK_Micropython, "MicroPy", + mpTaskHandle = xTaskCreateStatic(TASK_MicroPython, "MicroPy", MICROPY_TASK_STACK_LEN, NULL, MICROPY_TASK_PRIORITY, mpTaskStack, &mpTaskTCB); ASSERT(mpTaskHandle != NULL); diff --git a/cc3200/misc/FreeRTOSHooks.c b/cc3200/misc/FreeRTOSHooks.c index dac9a92826..c618279b7e 100644 --- a/cc3200/misc/FreeRTOSHooks.c +++ b/cc3200/misc/FreeRTOSHooks.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/cc3200/misc/antenna.c b/cc3200/misc/antenna.c index 0fbf79f0fc..afeed85e18 100644 --- a/cc3200/misc/antenna.c +++ b/cc3200/misc/antenna.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/cc3200/misc/antenna.h b/cc3200/misc/antenna.h index b3b1c61624..c9d845453e 100644 --- a/cc3200/misc/antenna.h +++ b/cc3200/misc/antenna.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,9 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - -#ifndef _ANTENNA_H_ -#define _ANTENNA_H_ +#ifndef MICROPY_INCLUDED_CC3200_MISC_ANTENNA_H +#define MICROPY_INCLUDED_CC3200_MISC_ANTENNA_H typedef enum { ANTENNA_TYPE_INTERNAL = 0, @@ -35,4 +34,4 @@ typedef enum { extern void antenna_init0 (void); extern void antenna_select (antenna_type_t antenna_type); -#endif /* _ANTENNA_H_ */ +#endif // MICROPY_INCLUDED_CC3200_MISC_ANTENNA_H diff --git a/cc3200/misc/help.c b/cc3200/misc/help.c index cce515898e..739303e193 100644 --- a/cc3200/misc/help.c +++ b/cc3200/misc/help.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/cc3200/misc/mperror.c b/cc3200/misc/mperror.c index 81b853b482..082d940e2f 100644 --- a/cc3200/misc/mperror.c +++ b/cc3200/misc/mperror.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/cc3200/misc/mperror.h b/cc3200/misc/mperror.h index e38d129db0..1c3eb62697 100644 --- a/cc3200/misc/mperror.h +++ b/cc3200/misc/mperror.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -24,9 +24,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - -#ifndef MPERROR_H_ -#define MPERROR_H_ +#ifndef MICROPY_INCLUDED_CC3200_MISC_MPERROR_H +#define MICROPY_INCLUDED_CC3200_MISC_MPERROR_H extern void NORETURN __fatal_error(const char *msg); @@ -39,4 +38,4 @@ void mperror_heartbeat_signal (void); void mperror_enable_heartbeat (bool enable); bool mperror_is_heartbeat_enabled (void); -#endif // MPERROR_H_ +#endif // MICROPY_INCLUDED_CC3200_MISC_MPERROR_H diff --git a/cc3200/misc/mpexception.c b/cc3200/misc/mpexception.c index 068adb70b0..72b203fae3 100644 --- a/cc3200/misc/mpexception.c +++ b/cc3200/misc/mpexception.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/cc3200/misc/mpexception.h b/cc3200/misc/mpexception.h index 2f9d1877c8..88134857c1 100644 --- a/cc3200/misc/mpexception.h +++ b/cc3200/misc/mpexception.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -24,9 +24,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - -#ifndef MPEXCEPTION_H_ -#define MPEXCEPTION_H_ +#ifndef MICROPY_INCLUDED_CC3200_MISC_MPEXCEPTION_H +#define MICROPY_INCLUDED_CC3200_MISC_MPEXCEPTION_H extern const char mpexception_value_invalid_arguments[]; extern const char mpexception_num_type_invalid_arguments[]; @@ -40,4 +39,4 @@ extern void mpexception_set_interrupt_char (int c); extern void mpexception_nlr_jump (void *o); extern void mpexception_keyboard_nlr_jump (void); -#endif /* MPEXCEPTION_H_ */ +#endif // MICROPY_INCLUDED_CC3200_MISC_MPEXCEPTION_H diff --git a/cc3200/misc/mpirq.c b/cc3200/misc/mpirq.c index 37149089f2..321663088d 100644 --- a/cc3200/misc/mpirq.c +++ b/cc3200/misc/mpirq.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -143,7 +143,7 @@ void mp_irq_handler (mp_obj_t self_in) { } /******************************************************************************/ -// Micro Python bindings +// MicroPython bindings STATIC mp_obj_t mp_irq_init (mp_uint_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { mp_irq_obj_t *self = pos_args[0]; diff --git a/cc3200/misc/mpirq.h b/cc3200/misc/mpirq.h index 3fd21ee094..35ce66e2da 100644 --- a/cc3200/misc/mpirq.h +++ b/cc3200/misc/mpirq.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,9 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - -#ifndef MPIRQ_H_ -#define MPIRQ_H_ +#ifndef MICROPY_INCLUDED_CC3200_MISC_MPIRQ_H +#define MICROPY_INCLUDED_CC3200_MISC_MPIRQ_H /****************************************************************************** DEFINE CONSTANTS @@ -72,4 +71,4 @@ void mp_irq_remove (const mp_obj_t parent); void mp_irq_handler (mp_obj_t self_in); uint mp_irq_translate_priority (uint priority); -#endif /* MPIRQ_H_ */ +#endif // MICROPY_INCLUDED_CC3200_MISC_MPIRQ_H diff --git a/cc3200/mods/modmachine.c b/cc3200/mods/modmachine.c index fd14856076..5f63d01967 100644 --- a/cc3200/mods/modmachine.c +++ b/cc3200/mods/modmachine.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -72,7 +72,7 @@ extern OsiTaskHandle xSimpleLinkSpawnTaskHndl; /// /******************************************************************************/ -// Micro Python bindings; +// MicroPython bindings; STATIC mp_obj_t machine_reset(void) { // disable wlan diff --git a/cc3200/mods/modnetwork.c b/cc3200/mods/modnetwork.c index d44f75acae..249e1be372 100644 --- a/cc3200/mods/modnetwork.c +++ b/cc3200/mods/modnetwork.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/cc3200/mods/modnetwork.h b/cc3200/mods/modnetwork.h index 7ecb8becb5..6ec90a2bac 100644 --- a/cc3200/mods/modnetwork.h +++ b/cc3200/mods/modnetwork.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -24,9 +24,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - -#ifndef MODNETWORK_H_ -#define MODNETWORK_H_ +#ifndef MICROPY_INCLUDED_CC3200_MODS_MODNETWORK_H +#define MICROPY_INCLUDED_CC3200_MODS_MODNETWORK_H /****************************************************************************** DEFINE CONSTANTS @@ -52,7 +51,7 @@ typedef struct _mod_network_socket_base_t { } u_param; int16_t sd; }; - bool has_timeout; + uint32_t timeout_ms; // 0 for no timeout bool cert_req; } mod_network_socket_base_t; @@ -71,4 +70,4 @@ extern const mod_network_nic_type_t mod_network_nic_type_wlan; ******************************************************************************/ void mod_network_init0(void); -#endif // MODNETWORK_H_ +#endif // MICROPY_INCLUDED_CC3200_MODS_MODNETWORK_H diff --git a/cc3200/mods/modubinascii.c b/cc3200/mods/modubinascii.c index 09f4b1e101..8bc2feacc1 100644 --- a/cc3200/mods/modubinascii.c +++ b/cc3200/mods/modubinascii.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -44,7 +44,7 @@ /******************************************************************************/ -// Micro Python bindings +// MicroPython bindings STATIC const mp_map_elem_t mp_module_binascii_globals_table[] = { { MP_OBJ_NEW_QSTR(MP_QSTR___name__), MP_OBJ_NEW_QSTR(MP_QSTR_ubinascii) }, diff --git a/cc3200/mods/modubinascii.h b/cc3200/mods/modubinascii.h index c04b70021f..eb9fc4f219 100644 --- a/cc3200/mods/modubinascii.h +++ b/cc3200/mods/modubinascii.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,9 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - -#ifndef MODUBINASCII_H_ -#define MODUBINASCII_H_ +#ifndef MICROPY_INCLUDED_CC3200_MODS_MODUBINASCII_H +#define MICROPY_INCLUDED_CC3200_MODS_MODUBINASCII_H -#endif /* MODUBINASCII_H_ */ +#endif // MICROPY_INCLUDED_CC3200_MODS_MODUBINASCII_H diff --git a/cc3200/mods/moduhashlib.c b/cc3200/mods/moduhashlib.c index e1145e4d8f..c90c727c2a 100644 --- a/cc3200/mods/moduhashlib.c +++ b/cc3200/mods/moduhashlib.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -117,7 +117,7 @@ STATIC mp_obj_t hash_read (mp_obj_t self_in) { } /******************************************************************************/ -// Micro Python bindings +// MicroPython bindings /// \classmethod \constructor([data[, block_size]]) /// initial data must be given if block_size wants to be passed diff --git a/cc3200/mods/moduos.c b/cc3200/mods/moduos.c index ed8879bf3e..51dc5834d4 100644 --- a/cc3200/mods/moduos.c +++ b/cc3200/mods/moduos.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -78,7 +78,7 @@ void osmount_unmount_all (void) { } /******************************************************************************/ -// Micro Python bindings +// MicroPython bindings // STATIC const qstr os_uname_info_fields[] = { diff --git a/cc3200/mods/moduos.h b/cc3200/mods/moduos.h index 4c8bc96595..f183715c90 100644 --- a/cc3200/mods/moduos.h +++ b/cc3200/mods/moduos.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -24,9 +24,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - -#ifndef MODUOS_H_ -#define MODUOS_H_ +#ifndef MICROPY_INCLUDED_CC3200_MODS_MODUOS_H +#define MICROPY_INCLUDED_CC3200_MODS_MODUOS_H #include "py/obj.h" @@ -45,4 +44,4 @@ typedef struct _os_term_dup_obj_t { ******************************************************************************/ void osmount_unmount_all (void); -#endif // MODUOS_H_ +#endif // MICROPY_INCLUDED_CC3200_MODS_MODUOS_H diff --git a/cc3200/mods/modusocket.c b/cc3200/mods/modusocket.c index ca28bf7ba9..7393553607 100644 --- a/cc3200/mods/modusocket.c +++ b/cc3200/mods/modusocket.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -34,6 +34,7 @@ #include "py/objstr.h" #include "py/runtime.h" #include "py/stream.h" +#include "py/mphal.h" #include "lib/netutils/netutils.h" #include "modnetwork.h" #include "modusocket.h" @@ -68,6 +69,31 @@ ip[2] = addr.sa_data[3]; \ ip[3] = addr.sa_data[2]; +#define SOCKET_TIMEOUT_QUANTA_MS (20) + +STATIC int convert_sl_errno(int sl_errno) { + return -sl_errno; +} + +// This function is left as non-static so it's not inlined. +int check_timedout(mod_network_socket_obj_t *s, int ret, uint32_t *timeout_ms, int *_errno) { + if (*timeout_ms == 0 || ret != SL_EAGAIN) { + if (s->sock_base.timeout_ms > 0 && ret == SL_EAGAIN) { + *_errno = MP_ETIMEDOUT; + } else { + *_errno = convert_sl_errno(ret); + } + return -1; + } + mp_hal_delay_ms(SOCKET_TIMEOUT_QUANTA_MS); + if (*timeout_ms < SOCKET_TIMEOUT_QUANTA_MS) { + *timeout_ms = 0; + } else { + *timeout_ms -= SOCKET_TIMEOUT_QUANTA_MS; + } + return 0; +} + STATIC int wlan_gethostbyname(const char *name, mp_uint_t len, uint8_t *out_ip, uint8_t family) { uint32_t ip; int result = sl_NetAppDnsGetHostByName((_i8 *)name, (_u16)len, (_u32*)&ip, (_u8)family); @@ -122,70 +148,111 @@ STATIC int wlan_socket_accept(mod_network_socket_obj_t *s, mod_network_socket_ob SlSockAddr_t addr; SlSocklen_t addr_len = sizeof(addr); - sd = sl_Accept(s->sock_base.sd, &addr, &addr_len); - // save the socket descriptor - s2->sock_base.sd = sd; - if (sd < 0) { - *_errno = sd; - return -1; + uint32_t timeout_ms = s->sock_base.timeout_ms; + for (;;) { + sd = sl_Accept(s->sock_base.sd, &addr, &addr_len); + if (sd >= 0) { + // save the socket descriptor + s2->sock_base.sd = sd; + // return ip and port + UNPACK_SOCKADDR(addr, ip, *port); + return 0; + } + if (check_timedout(s, sd, &timeout_ms, _errno)) { + return -1; + } } - - // return ip and port - UNPACK_SOCKADDR(addr, ip, *port); - return 0; } STATIC int wlan_socket_connect(mod_network_socket_obj_t *s, byte *ip, mp_uint_t port, int *_errno) { MAKE_SOCKADDR(addr, ip, port) - int ret = sl_Connect(s->sock_base.sd, &addr, sizeof(addr)); - if (ret != 0) { - *_errno = ret; - return -1; + uint32_t timeout_ms = s->sock_base.timeout_ms; + + // For a non-blocking connect the CC3100 will return SL_EALREADY while the + // connection is in progress. + + for (;;) { + int ret = sl_Connect(s->sock_base.sd, &addr, sizeof(addr)); + if (ret == 0) { + return 0; + } + + // Check if we are in non-blocking mode and the connection is in progress + if (s->sock_base.timeout_ms == 0 && ret == SL_EALREADY) { + // To match BSD we return EINPROGRESS here + *_errno = MP_EINPROGRESS; + return -1; + } + + // We are in blocking mode, so if the connection isn't in progress then error out + if (ret != SL_EALREADY) { + *_errno = convert_sl_errno(ret); + return -1; + } + + if (check_timedout(s, SL_EAGAIN, &timeout_ms, _errno)) { + return -1; + } } - return 0; } STATIC int wlan_socket_send(mod_network_socket_obj_t *s, const byte *buf, mp_uint_t len, int *_errno) { - mp_int_t bytes = 0; - if (len > 0) { - bytes = sl_Send(s->sock_base.sd, (const void *)buf, len, 0); + if (len == 0) { + return 0; } - if (bytes <= 0) { - *_errno = bytes; - return -1; + uint32_t timeout_ms = s->sock_base.timeout_ms; + for (;;) { + int ret = sl_Send(s->sock_base.sd, (const void *)buf, len, 0); + if (ret > 0) { + return ret; + } + if (check_timedout(s, ret, &timeout_ms, _errno)) { + return -1; + } } - return bytes; } STATIC int wlan_socket_recv(mod_network_socket_obj_t *s, byte *buf, mp_uint_t len, int *_errno) { - int ret = sl_Recv(s->sock_base.sd, buf, MIN(len, WLAN_MAX_RX_SIZE), 0); - if (ret < 0) { - *_errno = ret; - return -1; + uint32_t timeout_ms = s->sock_base.timeout_ms; + for (;;) { + int ret = sl_Recv(s->sock_base.sd, buf, MIN(len, WLAN_MAX_RX_SIZE), 0); + if (ret >= 0) { + return ret; + } + if (check_timedout(s, ret, &timeout_ms, _errno)) { + return -1; + } } - return ret; } STATIC int wlan_socket_sendto( mod_network_socket_obj_t *s, const byte *buf, mp_uint_t len, byte *ip, mp_uint_t port, int *_errno) { MAKE_SOCKADDR(addr, ip, port) - int ret = sl_SendTo(s->sock_base.sd, (byte*)buf, len, 0, (SlSockAddr_t*)&addr, sizeof(addr)); - if (ret < 0) { - *_errno = ret; - return -1; + uint32_t timeout_ms = s->sock_base.timeout_ms; + for (;;) { + int ret = sl_SendTo(s->sock_base.sd, (byte*)buf, len, 0, (SlSockAddr_t*)&addr, sizeof(addr)); + if (ret >= 0) { + return ret; + } + if (check_timedout(s, ret, &timeout_ms, _errno)) { + return -1; + } } - return ret; } STATIC int wlan_socket_recvfrom(mod_network_socket_obj_t *s, byte *buf, mp_uint_t len, byte *ip, mp_uint_t *port, int *_errno) { SlSockAddr_t addr; SlSocklen_t addr_len = sizeof(addr); - mp_int_t ret = sl_RecvFrom(s->sock_base.sd, buf, MIN(len, WLAN_MAX_RX_SIZE), 0, &addr, &addr_len); - if (ret < 0) { - *_errno = ret; - return -1; + uint32_t timeout_ms = s->sock_base.timeout_ms; + for (;;) { + int ret = sl_RecvFrom(s->sock_base.sd, buf, MIN(len, WLAN_MAX_RX_SIZE), 0, &addr, &addr_len); + if (ret >= 0) { + UNPACK_SOCKADDR(addr, ip, *port); + return ret; + } + if (check_timedout(s, ret, &timeout_ms, _errno)) { + return -1; + } } - UNPACK_SOCKADDR(addr, ip, *port); - return ret; } STATIC int wlan_socket_setsockopt(mod_network_socket_obj_t *s, mp_uint_t level, mp_uint_t opt, const void *optval, mp_uint_t optlen, int *_errno) { @@ -198,10 +265,8 @@ STATIC int wlan_socket_setsockopt(mod_network_socket_obj_t *s, mp_uint_t level, } STATIC int wlan_socket_settimeout(mod_network_socket_obj_t *s, mp_uint_t timeout_s, int *_errno) { - int ret; - bool has_timeout; + SlSockNonblocking_t option; if (timeout_s == 0 || timeout_s == -1) { - SlSockNonblocking_t option; if (timeout_s == 0) { // set non-blocking mode option.NonblockingEnabled = 1; @@ -209,23 +274,19 @@ STATIC int wlan_socket_settimeout(mod_network_socket_obj_t *s, mp_uint_t timeout // set blocking mode option.NonblockingEnabled = 0; } - ret = sl_SetSockOpt(s->sock_base.sd, SL_SOL_SOCKET, SL_SO_NONBLOCKING, &option, sizeof(option)); - has_timeout = false; + timeout_s = 0; } else { - // set timeout - struct SlTimeval_t timeVal; - timeVal.tv_sec = timeout_s; // seconds - timeVal.tv_usec = 0; // microseconds. 10000 microseconds resolution - ret = sl_SetSockOpt(s->sock_base.sd, SL_SOL_SOCKET, SL_SO_RCVTIMEO, &timeVal, sizeof(timeVal)); - has_timeout = true; + // synthesize timeout via non-blocking behaviour with a loop + option.NonblockingEnabled = 1; } + int ret = sl_SetSockOpt(s->sock_base.sd, SL_SOL_SOCKET, SL_SO_NONBLOCKING, &option, sizeof(option)); if (ret != 0) { - *_errno = ret; + *_errno = convert_sl_errno(ret); return -1; } - s->sock_base.has_timeout = has_timeout; + s->sock_base.timeout_ms = timeout_s * 1000; return 0; } @@ -379,7 +440,7 @@ STATIC mp_obj_t socket_make_new(const mp_obj_type_t *type, size_t n_args, size_t s->sock_base.u_param.type = SL_SOCK_STREAM; s->sock_base.u_param.proto = SL_IPPROTO_TCP; s->sock_base.u_param.fileno = -1; - s->sock_base.has_timeout = false; + s->sock_base.timeout_ms = 0; s->sock_base.cert_req = false; if (n_args > 0) { @@ -462,7 +523,7 @@ STATIC mp_obj_t socket_accept(mp_obj_t self_in) { mp_uint_t port = 0; int _errno = 0; if (wlan_socket_accept(self, socket2, ip, &port, &_errno) != 0) { - mp_raise_OSError(-_errno); + mp_raise_OSError(_errno); } // add the socket to the list @@ -490,7 +551,7 @@ STATIC mp_obj_t socket_connect(mp_obj_t self_in, mp_obj_t addr_in) { if (!self->sock_base.cert_req && _errno == SL_ESECSNOVERIFY) { return mp_const_none; } - mp_raise_OSError(-_errno); + mp_raise_OSError(_errno); } return mp_const_none; } @@ -504,7 +565,7 @@ STATIC mp_obj_t socket_send(mp_obj_t self_in, mp_obj_t buf_in) { int _errno; mp_int_t ret = wlan_socket_send(self, bufinfo.buf, bufinfo.len, &_errno); if (ret < 0) { - mp_raise_OSError(-_errno); + mp_raise_OSError(_errno); } return mp_obj_new_int_from_uint(ret); } @@ -519,10 +580,7 @@ STATIC mp_obj_t socket_recv(mp_obj_t self_in, mp_obj_t len_in) { int _errno; mp_int_t ret = wlan_socket_recv(self, (byte*)vstr.buf, len, &_errno); if (ret < 0) { - if (_errno == MP_EAGAIN && self->sock_base.has_timeout) { - mp_raise_OSError(MP_ETIMEDOUT); - } - mp_raise_OSError(-_errno); + mp_raise_OSError(_errno); } if (ret == 0) { return mp_const_empty_bytes; @@ -549,7 +607,7 @@ STATIC mp_obj_t socket_sendto(mp_obj_t self_in, mp_obj_t data_in, mp_obj_t addr_ int _errno = 0; mp_int_t ret = wlan_socket_sendto(self, bufinfo.buf, bufinfo.len, ip, port, &_errno); if (ret < 0) { - mp_raise_OSError(-_errno); + mp_raise_OSError(_errno); } return mp_obj_new_int(ret); } @@ -565,10 +623,7 @@ STATIC mp_obj_t socket_recvfrom(mp_obj_t self_in, mp_obj_t len_in) { int _errno = 0; mp_int_t ret = wlan_socket_recvfrom(self, (byte*)vstr.buf, vstr.len, ip, &port, &_errno); if (ret < 0) { - if (_errno == MP_EAGAIN && self->sock_base.has_timeout) { - mp_raise_OSError(MP_ETIMEDOUT); - } - mp_raise_OSError(-_errno); + mp_raise_OSError(_errno); } mp_obj_t tuple[2]; if (ret == 0) { @@ -624,9 +679,9 @@ STATIC mp_obj_t socket_settimeout(mp_obj_t self_in, mp_obj_t timeout_in) { } else { timeout = mp_obj_get_int(timeout_in); } - int _errno; + int _errno = 0; if (wlan_socket_settimeout(self, timeout, &_errno) != 0) { - mp_raise_OSError(-_errno); + mp_raise_OSError(_errno); } return mp_const_none; } @@ -643,17 +698,8 @@ STATIC mp_obj_t socket_setblocking(mp_obj_t self_in, mp_obj_t blocking) { STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_setblocking_obj, socket_setblocking); STATIC mp_obj_t socket_makefile(mp_uint_t n_args, const mp_obj_t *args) { - // TODO: CPython explicitly says that closing the returned object doesn't - // close the original socket (Python2 at all says that fd is dup()ed). But - // we save on the bloat. - mod_network_socket_obj_t *self = args[0]; - if (n_args > 1) { - const char *mode = mp_obj_str_get_str(args[1]); - if (strcmp(mode, "rb") && strcmp(mode, "wb")) { - mp_raise_ValueError(mpexception_value_invalid_arguments); - } - } - return self; + (void)n_args; + return args[0]; } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(socket_makefile_obj, 1, 6, socket_makefile); @@ -675,7 +721,7 @@ STATIC const mp_map_elem_t socket_locals_dict_table[] = { { MP_OBJ_NEW_QSTR(MP_QSTR_makefile), (mp_obj_t)&socket_makefile_obj }, // stream methods - { MP_OBJ_NEW_QSTR(MP_QSTR_read), (mp_obj_t)&mp_stream_read_obj }, + { MP_OBJ_NEW_QSTR(MP_QSTR_read), (mp_obj_t)&mp_stream_read1_obj }, { MP_OBJ_NEW_QSTR(MP_QSTR_readinto), (mp_obj_t)&mp_stream_readinto_obj }, { MP_OBJ_NEW_QSTR(MP_QSTR_readline), (mp_obj_t)&mp_stream_unbuffered_readline_obj}, { MP_OBJ_NEW_QSTR(MP_QSTR_write), (mp_obj_t)&mp_stream_write_obj }, @@ -689,10 +735,8 @@ STATIC mp_uint_t socket_read(mp_obj_t self_in, void *buf, mp_uint_t size, int *e if (ret < 0) { // we need to ignore the socket closed error here because a read() without params // only returns when the socket is closed by the other end - if (*errcode != SL_ESECCLOSED) { + if (*errcode != -SL_ESECCLOSED) { ret = MP_STREAM_ERROR; - // needed to convert simplelink's negative error codes to POSIX - (*errcode) *= -1; } else { ret = 0; } @@ -705,8 +749,6 @@ STATIC mp_uint_t socket_write(mp_obj_t self_in, const void *buf, mp_uint_t size, mp_int_t ret = wlan_socket_send(self, buf, size, errcode); if (ret < 0) { ret = MP_STREAM_ERROR; - // needed to convert simplelink's negative error codes to POSIX - (*errcode) *= -1; } return ret; } diff --git a/cc3200/mods/modusocket.h b/cc3200/mods/modusocket.h index 851f8e5be7..6e7758662e 100644 --- a/cc3200/mods/modusocket.h +++ b/cc3200/mods/modusocket.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,9 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - -#ifndef MODUSOCKET_H_ -#define MODUSOCKET_H_ +#ifndef MICROPY_INCLUDED_CC3200_MODS_MODUSOCKET_H +#define MICROPY_INCLUDED_CC3200_MODS_MODUSOCKET_H extern const mp_obj_dict_t socket_locals_dict; extern const mp_stream_p_t socket_stream_p; @@ -36,4 +35,4 @@ extern void modusocket_socket_delete (int16_t sd); extern void modusocket_enter_sleep (void); extern void modusocket_close_all_user_sockets (void); -#endif /* MODUSOCKET_H_ */ +#endif // MICROPY_INCLUDED_CC3200_MODS_MODUSOCKET_H diff --git a/cc3200/mods/modussl.c b/cc3200/mods/modussl.c index 95ecdbce7d..8082675718 100644 --- a/cc3200/mods/modussl.c +++ b/cc3200/mods/modussl.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -57,7 +57,7 @@ typedef struct _mp_obj_ssl_socket_t { STATIC const mp_obj_type_t ssl_socket_type; /******************************************************************************/ -// Micro Python bindings; SSL class +// MicroPython bindings; SSL class // ssl sockets inherit from normal socket, so we take its // locals and stream methods diff --git a/cc3200/mods/modutime.c b/cc3200/mods/modutime.c index 48fde67e7e..428b00f93e 100644 --- a/cc3200/mods/modutime.c +++ b/cc3200/mods/modutime.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -51,7 +51,7 @@ /// and for sleeping. /******************************************************************************/ -// Micro Python bindings +// MicroPython bindings /// \function localtime([secs]) /// Convert a time expressed in seconds since Jan 1, 2000 into an 8-tuple which diff --git a/cc3200/mods/modwipy.c b/cc3200/mods/modwipy.c index b4c18d1530..21a9cc63b5 100644 --- a/cc3200/mods/modwipy.c +++ b/cc3200/mods/modwipy.c @@ -5,7 +5,7 @@ /******************************************************************************/ -// Micro Python bindings +// MicroPython bindings STATIC mp_obj_t mod_wipy_heartbeat (mp_uint_t n_args, const mp_obj_t *args) { if (n_args) { diff --git a/cc3200/mods/modwlan.c b/cc3200/mods/modwlan.c index 68d892364f..77f5bd9915 100644 --- a/cc3200/mods/modwlan.c +++ b/cc3200/mods/modwlan.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -763,7 +763,7 @@ STATIC bool wlan_scan_result_is_unique (const mp_obj_list_t *nets, _u8 *bssid) { } /******************************************************************************/ -// Micro Python bindings; WLAN class +// MicroPython bindings; WLAN class /// \class WLAN - WiFi driver diff --git a/cc3200/mods/modwlan.h b/cc3200/mods/modwlan.h index 3bfd1fbbf9..b806644f55 100644 --- a/cc3200/mods/modwlan.h +++ b/cc3200/mods/modwlan.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,9 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - -#ifndef MODWLAN_H_ -#define MODWLAN_H_ +#ifndef MICROPY_INCLUDED_CC3200_MODS_MODWLAN_H +#define MICROPY_INCLUDED_CC3200_MODS_MODWLAN_H /****************************************************************************** DEFINE CONSTANTS @@ -97,4 +96,4 @@ extern bool wlan_is_connected (void); extern void wlan_set_current_time (uint32_t seconds_since_2000); extern void wlan_off_on (void); -#endif /* MODWLAN_H_ */ +#endif // MICROPY_INCLUDED_CC3200_MODS_MODWLAN_H diff --git a/cc3200/mods/pybadc.c b/cc3200/mods/pybadc.c index 696e7650b3..0b4f0ba68c 100644 --- a/cc3200/mods/pybadc.c +++ b/cc3200/mods/pybadc.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -126,7 +126,7 @@ STATIC void pyb_adc_deinit_all_channels (void) { } /******************************************************************************/ -/* Micro Python bindings : adc object */ +/* MicroPython bindings : adc object */ STATIC void adc_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { pyb_adc_obj_t *self = self_in; diff --git a/cc3200/mods/pybadc.h b/cc3200/mods/pybadc.h index b77c4af422..db04b006bc 100644 --- a/cc3200/mods/pybadc.h +++ b/cc3200/mods/pybadc.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -24,10 +24,9 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - -#ifndef PYBADC_H_ -#define PYBADC_H_ +#ifndef MICROPY_INCLUDED_CC3200_MODS_PYBADC_H +#define MICROPY_INCLUDED_CC3200_MODS_PYBADC_H extern const mp_obj_type_t pyb_adc_type; -#endif /* PYBADC_H_ */ +#endif // MICROPY_INCLUDED_CC3200_MODS_PYBADC_H diff --git a/cc3200/mods/pybi2c.c b/cc3200/mods/pybi2c.c index 9fc97d9140..9c62ffdc4c 100644 --- a/cc3200/mods/pybi2c.c +++ b/cc3200/mods/pybi2c.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -281,7 +281,7 @@ STATIC void pyb_i2c_readmem_into (mp_arg_val_t *args, vstr_t *vstr) { } /******************************************************************************/ -/* Micro Python bindings */ +/* MicroPython bindings */ /******************************************************************************/ 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 = self_in; diff --git a/cc3200/mods/pybi2c.h b/cc3200/mods/pybi2c.h index 7adffb2d99..dcc3f0468c 100644 --- a/cc3200/mods/pybi2c.h +++ b/cc3200/mods/pybi2c.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -24,10 +24,9 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - -#ifndef PYBI2C_H_ -#define PYBI2C_H_ +#ifndef MICROPY_INCLUDED_CC3200_MODS_PYBI2C_H +#define MICROPY_INCLUDED_CC3200_MODS_PYBI2C_H extern const mp_obj_type_t pyb_i2c_type; -#endif // PYBI2C_H_ +#endif // MICROPY_INCLUDED_CC3200_MODS_PYBI2C_H diff --git a/cc3200/mods/pybpin.c b/cc3200/mods/pybpin.c index c2a4691174..d59f113eb5 100644 --- a/cc3200/mods/pybpin.c +++ b/cc3200/mods/pybpin.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -519,7 +519,7 @@ STATIC void EXTI_Handler(uint port) { /******************************************************************************/ -// Micro Python bindings +// MicroPython bindings STATIC const mp_arg_t pin_init_args[] = { { MP_QSTR_mode, MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, diff --git a/cc3200/mods/pybpin.h b/cc3200/mods/pybpin.h index ad02cc777a..74f0af2b3c 100644 --- a/cc3200/mods/pybpin.h +++ b/cc3200/mods/pybpin.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -24,9 +24,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - -#ifndef PYBPIN_H_ -#define PYBPIN_H_ +#ifndef MICROPY_INCLUDED_CC3200_MODS_PYBPIN_H +#define MICROPY_INCLUDED_CC3200_MODS_PYBPIN_H enum { PORT_A0 = GPIOA0_BASE, @@ -138,4 +137,4 @@ uint8_t pin_find_peripheral_unit (const mp_obj_t pin, uint8_t fn, uint8_t type); uint8_t pin_find_peripheral_type (const mp_obj_t pin, uint8_t fn, uint8_t unit); int8_t pin_find_af_index (const pin_obj_t* pin, uint8_t fn, uint8_t unit, uint8_t type);; -#endif // PYBPIN_H_ +#endif // MICROPY_INCLUDED_CC3200_MODS_PYBPIN_H diff --git a/cc3200/mods/pybrtc.c b/cc3200/mods/pybrtc.c index 134bd440e7..14c4cd4199 100644 --- a/cc3200/mods/pybrtc.c +++ b/cc3200/mods/pybrtc.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -278,7 +278,7 @@ STATIC void rtc_msec_add (uint16_t msecs_1, uint32_t *secs, uint16_t *msecs_2) { } /******************************************************************************/ -// Micro Python bindings +// MicroPython bindings STATIC const mp_arg_t pyb_rtc_init_args[] = { { MP_QSTR_id, MP_ARG_INT, {.u_int = 0} }, diff --git a/cc3200/mods/pybrtc.h b/cc3200/mods/pybrtc.h index 5111b78f7c..f73de3f5a7 100644 --- a/cc3200/mods/pybrtc.h +++ b/cc3200/mods/pybrtc.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -24,9 +24,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - -#ifndef PYBRTC_H_ -#define PYBRTC_H_ +#ifndef MICROPY_INCLUDED_CC3200_MODS_PYBRTC_H +#define MICROPY_INCLUDED_CC3200_MODS_PYBRTC_H // RTC triggers #define PYB_RTC_ALARM0 (0x01) @@ -56,4 +55,4 @@ extern void pyb_rtc_calc_future_time (uint32_t a_mseconds, uint32_t *f_seconds, extern void pyb_rtc_repeat_alarm (pyb_rtc_obj_t *self); extern void pyb_rtc_disable_alarm (void); -#endif // PYBRTC_H_ +#endif // MICROPY_INCLUDED_CC3200_MODS_PYBRTC_H diff --git a/cc3200/mods/pybsd.c b/cc3200/mods/pybsd.c index 306baea8ba..5ba6119b29 100644 --- a/cc3200/mods/pybsd.c +++ b/cc3200/mods/pybsd.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -118,7 +118,7 @@ STATIC mp_obj_t pyb_sd_init_helper (pybsd_obj_t *self, const mp_arg_val_t *args) } /******************************************************************************/ -// Micro Python bindings +// MicroPython bindings // STATIC const mp_arg_t pyb_sd_init_args[] = { diff --git a/cc3200/mods/pybsd.h b/cc3200/mods/pybsd.h index a06df6d8d1..af942084d7 100644 --- a/cc3200/mods/pybsd.h +++ b/cc3200/mods/pybsd.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,8 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -#ifndef PYBSD_H_ -#define PYBSD_H_ +#ifndef MICROPY_INCLUDED_CC3200_MODS_PYBSD_H +#define MICROPY_INCLUDED_CC3200_MODS_PYBSD_H /****************************************************************************** DEFINE PUBLIC TYPES @@ -41,4 +41,4 @@ typedef struct { extern pybsd_obj_t pybsd_obj; extern const mp_obj_type_t pyb_sd_type; -#endif // PYBSD_H_ +#endif // MICROPY_INCLUDED_CC3200_MODS_PYBSD_H diff --git a/cc3200/mods/pybsleep.c b/cc3200/mods/pybsleep.c index ced7fef852..a7488c5f14 100644 --- a/cc3200/mods/pybsleep.c +++ b/cc3200/mods/pybsleep.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/cc3200/mods/pybsleep.h b/cc3200/mods/pybsleep.h index d34895ae0d..e98636178d 100644 --- a/cc3200/mods/pybsleep.h +++ b/cc3200/mods/pybsleep.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,9 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - -#ifndef PYBSLEEP_H_ -#define PYBSLEEP_H_ +#ifndef MICROPY_INCLUDED_CC3200_MODS_PYBSLEEP_H +#define MICROPY_INCLUDED_CC3200_MODS_PYBSLEEP_H /****************************************************************************** DEFINE CONSTANTS @@ -70,4 +69,4 @@ void pyb_sleep_deepsleep (void); pybsleep_reset_cause_t pyb_sleep_get_reset_cause (void); pybsleep_wake_reason_t pyb_sleep_get_wake_reason (void); -#endif /* PYBSLEEP_H_ */ +#endif // MICROPY_INCLUDED_CC3200_MODS_PYBSLEEP_H diff --git a/cc3200/mods/pybspi.c b/cc3200/mods/pybspi.c index 3cd384266a..9edad579a3 100644 --- a/cc3200/mods/pybspi.c +++ b/cc3200/mods/pybspi.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -144,7 +144,7 @@ STATIC void pybspi_transfer (pyb_spi_obj_t *self, const char *txdata, char *rxda } /******************************************************************************/ -/* Micro Python bindings */ +/* MicroPython bindings */ /******************************************************************************/ STATIC void pyb_spi_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { pyb_spi_obj_t *self = self_in; diff --git a/cc3200/mods/pybspi.h b/cc3200/mods/pybspi.h index 48e0edd613..b0fce88703 100644 --- a/cc3200/mods/pybspi.h +++ b/cc3200/mods/pybspi.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -24,10 +24,9 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - -#ifndef PYBSPI_H_ -#define PYBSPI_H_ +#ifndef MICROPY_INCLUDED_CC3200_MODS_PYBSPI_H +#define MICROPY_INCLUDED_CC3200_MODS_PYBSPI_H extern const mp_obj_type_t pyb_spi_type; -#endif // PYBSPI_H_ +#endif // MICROPY_INCLUDED_CC3200_MODS_PYBSPI_H diff --git a/cc3200/mods/pybtimer.c b/cc3200/mods/pybtimer.c index d25ac6c2b3..1ef9a4a440 100644 --- a/cc3200/mods/pybtimer.c +++ b/cc3200/mods/pybtimer.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -264,7 +264,7 @@ STATIC void timer_channel_init (pyb_timer_channel_obj_t *ch) { } /******************************************************************************/ -/* Micro Python bindings */ +/* MicroPython bindings */ STATIC void pyb_timer_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { pyb_timer_obj_t *tim = self_in; diff --git a/cc3200/mods/pybtimer.h b/cc3200/mods/pybtimer.h index 4e9de138d8..0af0864ca1 100644 --- a/cc3200/mods/pybtimer.h +++ b/cc3200/mods/pybtimer.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -24,6 +24,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ +#ifndef MICROPY_INCLUDED_CC3200_MODS_PYBTIMER_H +#define MICROPY_INCLUDED_CC3200_MODS_PYBTIMER_H /****************************************************************************** DECLARE EXPORTED DATA @@ -35,3 +37,4 @@ extern const mp_obj_type_t pyb_timer_type; ******************************************************************************/ void timer_init0 (void); +#endif // MICROPY_INCLUDED_CC3200_MODS_PYBTIMER_H diff --git a/cc3200/mods/pybuart.c b/cc3200/mods/pybuart.c index 92bb3e46e6..626357179b 100644 --- a/cc3200/mods/pybuart.c +++ b/cc3200/mods/pybuart.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -27,7 +27,6 @@ #include #include -#include #include #include "py/mpconfig.h" @@ -312,7 +311,7 @@ STATIC int uart_irq_flags (mp_obj_t self_in) { } /******************************************************************************/ -/* Micro Python bindings */ +/* MicroPython bindings */ STATIC void pyb_uart_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { pyb_uart_obj_t *self = self_in; diff --git a/cc3200/mods/pybuart.h b/cc3200/mods/pybuart.h index 19bc93607d..d481242f1f 100644 --- a/cc3200/mods/pybuart.h +++ b/cc3200/mods/pybuart.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -24,9 +24,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - -#ifndef PYBUART_H_ -#define PYBUART_H_ +#ifndef MICROPY_INCLUDED_CC3200_MODS_PYBUART_H +#define MICROPY_INCLUDED_CC3200_MODS_PYBUART_H typedef enum { PYB_UART_0 = 0, @@ -43,4 +42,4 @@ int uart_rx_char(pyb_uart_obj_t *uart_obj); bool uart_tx_char(pyb_uart_obj_t *self, int c); bool uart_tx_strn(pyb_uart_obj_t *uart_obj, const char *str, uint len); -#endif // PYBUART_H_ +#endif // MICROPY_INCLUDED_CC3200_MODS_PYBUART_H diff --git a/cc3200/mods/pybwdt.c b/cc3200/mods/pybwdt.c index 76c701ca07..114e7ac96a 100644 --- a/cc3200/mods/pybwdt.c +++ b/cc3200/mods/pybwdt.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -87,7 +87,7 @@ void pybwdt_sl_alive (void) { } /******************************************************************************/ -// Micro Python bindings +// MicroPython bindings STATIC const mp_arg_t pyb_wdt_init_args[] = { { MP_QSTR_id, MP_ARG_OBJ, {.u_obj = mp_const_none} }, diff --git a/cc3200/mods/pybwdt.h b/cc3200/mods/pybwdt.h index f87f0a7738..275c49435c 100644 --- a/cc3200/mods/pybwdt.h +++ b/cc3200/mods/pybwdt.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,9 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - -#ifndef PYBWDT_H_ -#define PYBWDT_H_ +#ifndef MICROPY_INCLUDED_CC3200_MODS_PYBWDT_H +#define MICROPY_INCLUDED_CC3200_MODS_PYBWDT_H #include "py/obj.h" @@ -36,4 +35,4 @@ void pybwdt_srv_alive (void); void pybwdt_srv_sleeping (bool state); void pybwdt_sl_alive (void); -#endif /* PYBWDT_H_ */ +#endif // MICROPY_INCLUDED_CC3200_MODS_PYBWDT_H diff --git a/cc3200/mpconfigport.h b/cc3200/mpconfigport.h index 4bd583a4b8..dcde9aae09 100644 --- a/cc3200/mpconfigport.h +++ b/cc3200/mpconfigport.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -25,9 +25,6 @@ * THE SOFTWARE. */ -#ifndef __INCLUDED_MPCONFIGPORT_H -#define __INCLUDED_MPCONFIGPORT_H - #include #ifndef BOOTLOADER @@ -35,7 +32,7 @@ #include "semphr.h" #endif -// options to control how Micro Python is built +// options to control how MicroPython is built #define MICROPY_ALLOC_PATH_MAX (128) #define MICROPY_PERSISTENT_CODE_LOAD (1) @@ -235,5 +232,3 @@ typedef long mp_off_t; #define MICROPY_PORT_WLAN_AP_KEY "www.wipy.io" #define MICROPY_PORT_WLAN_AP_SECURITY SL_SEC_TYPE_WPA_WPA2 #define MICROPY_PORT_WLAN_AP_CHANNEL 5 - -#endif // __INCLUDED_MPCONFIGPORT_H diff --git a/cc3200/mptask.c b/cc3200/mptask.c index d446711a29..09be8c441d 100644 --- a/cc3200/mptask.c +++ b/cc3200/mptask.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -112,7 +112,7 @@ static const char fresh_boot_py[] = "# boot.py -- run on boot-up\r\n" 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(); diff --git a/cc3200/mptask.h b/cc3200/mptask.h index e0d2f0eec1..a1c3eb2cbf 100644 --- a/cc3200/mptask.h +++ b/cc3200/mptask.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,9 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - -#ifndef MPTASK_H_ -#define MPTASK_H_ +#ifndef MICROPY_INCLUDED_CC3200_MPTASK_H +#define MICROPY_INCLUDED_CC3200_MPTASK_H /****************************************************************************** DEFINE CONSTANTS @@ -42,6 +41,6 @@ extern StackType_t mpTaskStack[]; /****************************************************************************** DECLARE PUBLIC FUNCTIONS ******************************************************************************/ -extern void TASK_Micropython (void *pvParameters); +extern void TASK_MicroPython (void *pvParameters); -#endif /* MPTASK_H_ */ +#endif // MICROPY_INCLUDED_CC3200_MPTASK_H diff --git a/cc3200/mpthreadport.h b/cc3200/mpthreadport.h index 2b49232ddf..dc9ba99204 100644 --- a/cc3200/mpthreadport.h +++ b/cc3200/mpthreadport.h @@ -23,8 +23,6 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -#ifndef __MICROPY_INCLUDED_CC3200_MPTHREADPORT_H__ -#define __MICROPY_INCLUDED_CC3200_MPTHREADPORT_H__ #ifndef BOOTLOADER #include "FreeRTOS.h" @@ -39,5 +37,3 @@ typedef struct _mp_thread_mutex_t { void mp_thread_init(void); void mp_thread_gc_others(void); - -#endif // __MICROPY_INCLUDED_CC3200_MPTHREADPORT_H__ diff --git a/cc3200/qstrdefsport.h b/cc3200/qstrdefsport.h index 2fc56668c3..d5f22d70a8 100644 --- a/cc3200/qstrdefsport.h +++ b/cc3200/qstrdefsport.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/cc3200/serverstask.c b/cc3200/serverstask.c index 6b5899e186..100b8d33b0 100644 --- a/cc3200/serverstask.c +++ b/cc3200/serverstask.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/cc3200/serverstask.h b/cc3200/serverstask.h index 2786ff6976..c4533d7174 100644 --- a/cc3200/serverstask.h +++ b/cc3200/serverstask.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,9 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - -#ifndef SERVERSTASK_H_ -#define SERVERSTASK_H_ +#ifndef MICROPY_INCLUDED_CC3200_SERVERSTASK_H +#define MICROPY_INCLUDED_CC3200_SERVERSTASK_H /****************************************************************************** DEFINE CONSTANTS @@ -73,4 +72,4 @@ extern void server_sleep_sockets (void); extern void servers_set_timeout (uint32_t timeout); extern uint32_t servers_get_timeout (void); -#endif /* SERVERSTASK_H_ */ +#endif // MICROPY_INCLUDED_CC3200_SERVERSTASK_H diff --git a/cc3200/telnet/telnet.c b/cc3200/telnet/telnet.c index 26e45a75f1..2f0818f6ba 100644 --- a/cc3200/telnet/telnet.c +++ b/cc3200/telnet/telnet.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/cc3200/telnet/telnet.h b/cc3200/telnet/telnet.h index aa55313940..51c5691041 100644 --- a/cc3200/telnet/telnet.h +++ b/cc3200/telnet/telnet.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,9 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - -#ifndef TELNET_H_ -#define TELNET_H_ +#ifndef MICROPY_INCLUDED_CC3200_TELNET_TELNET_H +#define MICROPY_INCLUDED_CC3200_TELNET_TELNET_H /****************************************************************************** DECLARE EXPORTED FUNCTIONS @@ -39,4 +38,4 @@ extern void telnet_enable (void); extern void telnet_disable (void); extern void telnet_reset (void); -#endif /* TELNET_H_ */ +#endif // MICROPY_INCLUDED_CC3200_TELNET_TELNET_H diff --git a/cc3200/util/cryptohash.c b/cc3200/util/cryptohash.c index d2d6222ffc..909dadc8cf 100644 --- a/cc3200/util/cryptohash.c +++ b/cc3200/util/cryptohash.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/cc3200/util/cryptohash.h b/cc3200/util/cryptohash.h index d9f624d192..15d46b705b 100644 --- a/cc3200/util/cryptohash.h +++ b/cc3200/util/cryptohash.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,9 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - -#ifndef CRYPTOHASH_H_ -#define CRYPTOHASH_H_ +#ifndef MICROPY_INCLUDED_CC3200_UTIL_CRYPTOHASH_H +#define MICROPY_INCLUDED_CC3200_UTIL_CRYPTOHASH_H /****************************************************************************** DECLARE PUBLIC FUNCTIONS @@ -35,4 +34,4 @@ extern void CRYPTOHASH_SHAMD5Start (uint32_t algo, uint32_t blocklen); extern void CRYPTOHASH_SHAMD5Update (uint8_t *data, uint32_t datalen); extern void CRYPTOHASH_SHAMD5Read (uint8_t *hash); -#endif /* CRYPTOHASH_H_ */ +#endif // MICROPY_INCLUDED_CC3200_UTIL_CRYPTOHASH_H diff --git a/cc3200/util/fifo.c b/cc3200/util/fifo.c index 166f99d985..421f837100 100644 --- a/cc3200/util/fifo.c +++ b/cc3200/util/fifo.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/cc3200/util/fifo.h b/cc3200/util/fifo.h index c8590f5c2c..6ede57e1e5 100644 --- a/cc3200/util/fifo.h +++ b/cc3200/util/fifo.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,9 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - -#ifndef FIFO_H_ -#define FIFO_H_ +#ifndef MICROPY_INCLUDED_CC3200_UTIL_FIFO_H +#define MICROPY_INCLUDED_CC3200_UTIL_FIFO_H typedef struct { void *pvElements; @@ -47,4 +46,4 @@ extern bool FIFO_IsEmpty (FIFO_t *fifo); extern bool FIFO_IsFull (FIFO_t *fifo); extern void FIFO_Flush (FIFO_t *fifo); -#endif /* FIFO_H_ */ +#endif // MICROPY_INCLUDED_CC3200_UTIL_FIFO_H diff --git a/cc3200/util/gccollect.c b/cc3200/util/gccollect.c index 8963852f7a..baee2eeef9 100644 --- a/cc3200/util/gccollect.c +++ b/cc3200/util/gccollect.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/cc3200/util/gccollect.h b/cc3200/util/gccollect.h index 281e84aa83..08d43d2837 100644 --- a/cc3200/util/gccollect.h +++ b/cc3200/util/gccollect.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -24,6 +24,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ +#ifndef MICROPY_INCLUDED_CC3200_UTIL_GCCOLLECT_H +#define MICROPY_INCLUDED_CC3200_UTIL_GCCOLLECT_H // variables defining memory layout extern uint32_t _etext; @@ -39,3 +41,5 @@ extern uint32_t _stack; extern uint32_t _estack; void gc_collect(void); + +#endif // MICROPY_INCLUDED_CC3200_UTIL_GCCOLLECT_H diff --git a/cc3200/util/gchelper.h b/cc3200/util/gchelper.h index 1f7d2fece4..48e81bc61d 100644 --- a/cc3200/util/gchelper.h +++ b/cc3200/util/gchelper.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -24,11 +24,10 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - -#ifndef GC_HELPER_H_ -#define GC_HELPER_H_ +#ifndef MICROPY_INCLUDED_CC3200_UTIL_GCHELPER_H +#define MICROPY_INCLUDED_CC3200_UTIL_GCHELPER_H extern mp_uint_t gc_helper_get_sp(void); extern mp_uint_t gc_helper_get_regs_and_sp(mp_uint_t *regs); -#endif /* GC_HELPER_H_ */ +#endif // MICROPY_INCLUDED_CC3200_UTIL_GCHELPER_H diff --git a/cc3200/util/random.c b/cc3200/util/random.c index 54aaa829cb..f8e9cdf0cb 100644 --- a/cc3200/util/random.c +++ b/cc3200/util/random.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -67,7 +67,7 @@ STATIC uint32_t lfsr (uint32_t input) { } /******************************************************************************/ -// Micro Python bindings; +// MicroPython bindings; STATIC mp_obj_t machine_rng_get(void) { return mp_obj_new_int(rng_get()); diff --git a/cc3200/util/random.h b/cc3200/util/random.h index 67fd1ff855..02cde6b522 100644 --- a/cc3200/util/random.h +++ b/cc3200/util/random.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,13 +23,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - -#ifndef __RANDOM_H -#define __RANDOM_H +#ifndef MICROPY_INCLUDED_CC3200_UTIL_RANDOM_H +#define MICROPY_INCLUDED_CC3200_UTIL_RANDOM_H void rng_init0 (void); uint32_t rng_get (void); MP_DECLARE_CONST_FUN_OBJ_0(machine_rng_get_obj); -#endif // __RANDOM_H +#endif // MICROPY_INCLUDED_CC3200_UTIL_RANDOM_H diff --git a/cc3200/util/sleeprestore.h b/cc3200/util/sleeprestore.h index 51416f0fce..e178f4c2d0 100644 --- a/cc3200/util/sleeprestore.h +++ b/cc3200/util/sleeprestore.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,11 +23,10 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - -#ifndef SLEEPRESTORE_H_ -#define SLEEPRESTORE_H_ +#ifndef MICROPY_INCLUDED_CC3200_UTIL_SLEEPRESTORE_H +#define MICROPY_INCLUDED_CC3200_UTIL_SLEEPRESTORE_H extern void sleep_store(void); extern void sleep_restore(void); -#endif /* SLEEPRESTORE_H_ */ +#endif // MICROPY_INCLUDED_CC3200_UTIL_SLEEPRESTORE_H diff --git a/cc3200/util/socketfifo.c b/cc3200/util/socketfifo.c index eb25f3be3e..d0a7150485 100644 --- a/cc3200/util/socketfifo.c +++ b/cc3200/util/socketfifo.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/cc3200/util/socketfifo.h b/cc3200/util/socketfifo.h index 69b17658ff..e6cf851b1a 100644 --- a/cc3200/util/socketfifo.h +++ b/cc3200/util/socketfifo.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,9 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - -#ifndef SOCKETFIFO_H_ -#define SOCKETFIFO_H_ +#ifndef MICROPY_INCLUDED_CC3200_UTIL_SOCKETFIFO_H +#define MICROPY_INCLUDED_CC3200_UTIL_SOCKETFIFO_H /*---------------------------------------------------------------------------- ** Imports @@ -60,4 +59,4 @@ extern bool SOCKETFIFO_IsFull (void); extern void SOCKETFIFO_Flush (void); extern unsigned int SOCKETFIFO_Count (void); -#endif /* SOCKETFIFO_H_ */ +#endif // MICROPY_INCLUDED_CC3200_UTIL_SOCKETFIFO_H diff --git a/cc3200/version.h b/cc3200/version.h index c8315d771c..fccb95c521 100644 --- a/cc3200/version.h +++ b/cc3200/version.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,10 +23,9 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - -#ifndef VERSION_H_ -#define VERSION_H_ +#ifndef MICROPY_INCLUDED_CC3200_VERSION_H +#define MICROPY_INCLUDED_CC3200_VERSION_H #define WIPY_SW_VERSION_NUMBER "1.2.0" -#endif /* VERSION_H_ */ +#endif // MICROPY_INCLUDED_CC3200_VERSION_H diff --git a/docs/conf.py b/docs/conf.py index e813f23836..2c3423d99b 100755 --- a/docs/conf.py +++ b/docs/conf.py @@ -96,10 +96,9 @@ copyright = '2014-2017, Damien P. George, Paul Sokolovsky, and contributors' # |version| and |release|, also used in various other places throughout the # built documents. # -# The short X.Y version. -version = '1.9' -# The full version, including alpha/beta/rc tags. -release = '1.9' +# We don't follow "The short X.Y version" vs "The full version, including alpha/beta/rc tags" +# breakdown, so use the same version identifier for both to avoid confusion. +version = release = '1.9.1' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. @@ -113,11 +112,11 @@ release = '1.9' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. -exclude_patterns = ['build'] +exclude_patterns = ['build', '.venv'] # The reST default role (used for this markup: `text`) to use for all # documents. -#default_role = None +default_role = 'any' # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True @@ -139,6 +138,12 @@ pygments_style = 'sphinx' # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False +# Global include files. Sphinx docs suggest using rst_epilog in preference +# of rst_prolog, so we follow. Absolute paths below mean "from the base +# of the doctree". +rst_epilog = """ +.. include:: /templates/replace.inc +""" # -- Options for HTML output ---------------------------------------------- @@ -246,6 +251,8 @@ latex_elements = { # Additional stuff for the LaTeX preamble. #'preamble': '', +# Include 3 levels of headers in PDF ToC +'preamble': '\setcounter{tocdepth}{2}', } # Grouping the document tree into LaTeX files. List of tuples @@ -315,7 +322,7 @@ texinfo_documents = [ # Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = {'http://docs.python.org/': None} +intersphinx_mapping = {'python': ('http://docs.python.org/3', None)} # Append the other ports' specific folders/files to the exclude pattern exclude_patterns.extend([port + '*' for port in ports if port != micropy_port]) diff --git a/docs/differences/index_template.txt b/docs/differences/index_template.txt index 6ade2c2dab..eb8b3ba640 100644 --- a/docs/differences/index_template.txt +++ b/docs/differences/index_template.txt @@ -1,4 +1,6 @@ -MicroPython Differences from CPython +.. _cpython_diffs: + +MicroPython differences from CPython ==================================== The operations listed in this section produce conflicting results in MicroPython when compared to standard Python. diff --git a/docs/esp8266/general.rst b/docs/esp8266/general.rst index 47df80d7ba..e23acb469b 100644 --- a/docs/esp8266/general.rst +++ b/docs/esp8266/general.rst @@ -116,9 +116,32 @@ Real-time clock RTC in ESP8266 has very bad accuracy, drift may be seconds per minute. As a workaround, to measure short enough intervals you can use ``utime.time()``, etc. functions, and for wall clock time, synchronize from -the net using included ``ntpdate.py`` module. +the net using included ``ntptime.py`` module. Due to limitations of the ESP8266 chip the internal real-time clock (RTC) will overflow every 7:45h. If a long-term working RTC time is required then ``time()`` or ``localtime()`` must be called at least once within 7 hours. MicroPython will then handle the overflow. + +Sockets and WiFi buffers overflow +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Socket instances remain active until they are explicitly closed. This has two +consequences. Firstly they occupy RAM, so an application which opens sockets +without closing them may eventually run out of memory. Secondly not properly +closed socket can cause the low-level part of the vendor WiFi stack to emit +``Lmac`` errors. This occurs if data comes in for a socket and is not +processed in a timely manner. This can overflow the WiFi stack input queue +and lead to a deadlock. The only recovery is by a hard reset. + +The above may also happen after an application terminates and quits to the REPL +for any reason including an exception. Subsequent arrival of data provokes the +failure with the above error message repeatedly issued. So, sockets should be +closed in any case, regardless whether an application terminates successfully +or by an exeption, for example using try/finally:: + + sock = socket(...) + try: + # Use sock + finally: + sock.close() diff --git a/docs/esp8266/tutorial/intro.rst b/docs/esp8266/tutorial/intro.rst index 67ed0ba67c..711db3fceb 100644 --- a/docs/esp8266/tutorial/intro.rst +++ b/docs/esp8266/tutorial/intro.rst @@ -50,12 +50,16 @@ From here, you have 3 main choices * Daily firmware builds for 1024kb modules and above. * Daily firmware builds for 512kb modules. -The best bet is nearly always to go for the Stable firmware builds. -An exception to this though is if you have an ESP8266 module with only 512kb -of onboard storage. You can easily tell by trying to load a Stable firmware -build and if you get the error below, then you may have to use the Daily -firmware builds for 512kb modules. - WARNING: Unlikely to work as data goes beyond end of flash. +If you are just starting with MicroPython, the best bet is to go for the Stable +firmware builds. If you are an advanced, experienced MicroPython ESP8266 user +who would like to follow development closely and help with testing new +features, there are daily builds (note: you actually may need some +development experience, e.g. being ready to follow git history to know +what new changes and features were introduced). + +Support for 512kb modules is provided on a feature preview basis. For end +users, it's recommended to use modules with flash of 1024kb or more. As +such, only daily builds for 512kb modules are provided. Deploying the firmware ---------------------- @@ -161,7 +165,9 @@ after it, here are troubleshooting recommendations: * If lower baud rate didn't help, you may want to try older version of esptool.py, which had a different programming algorithm:: + pip install esptool==1.0.1 + This version doesn't support ``--flash_size=detect`` option, so you will need to specify FlashROM size explicitly (in megabits). It also requires Python 2.7, so you may need to use ``pip2`` instead of ``pip`` in the @@ -176,8 +182,10 @@ after it, here are troubleshooting recommendations: * Additionally, you can check the firmware integrity from a MicroPython REPL prompt (assuming you were able to flash it and ``--verify`` option doesn't report errors):: + import esp esp.check_fw() + If the last output value is True, the firmware is OK. Otherwise, it's corrupted and need to be reflashed correctly. diff --git a/docs/esp8266/tutorial/powerctrl.rst b/docs/esp8266/tutorial/powerctrl.rst index 9e44339c86..3502624ab5 100644 --- a/docs/esp8266/tutorial/powerctrl.rst +++ b/docs/esp8266/tutorial/powerctrl.rst @@ -22,7 +22,7 @@ processing power, at the expense of current consumption:: 160000000 You can change to the higher frequency just while your code does the heavy -processing and then change back when its finished. +processing and then change back when it's finished. Deep-sleep mode --------------- diff --git a/docs/esp8266_contents.rst b/docs/esp8266_contents.rst deleted file mode 100644 index 7c35460bd9..0000000000 --- a/docs/esp8266_contents.rst +++ /dev/null @@ -1,12 +0,0 @@ -MicroPython documentation contents -================================== - -.. toctree:: - - esp8266/quickref.rst - esp8266/general.rst - esp8266/tutorial/index.rst - library/index.rst - reference/index.rst - genrst/index.rst - license.rst diff --git a/docs/esp8266_index.rst b/docs/esp8266_index.rst index 8654c43aa0..519acecda5 100644 --- a/docs/esp8266_index.rst +++ b/docs/esp8266_index.rst @@ -4,14 +4,9 @@ MicroPython documentation and references .. toctree:: esp8266/quickref.rst + esp8266/general.rst + esp8266/tutorial/index.rst library/index.rst + reference/index.rst genrst/index.rst license.rst - esp8266_contents.rst - -Indices and tables -================== - -* :ref:`genindex` -* :ref:`modindex` -* :ref:`search` diff --git a/docs/library/array.rst b/docs/library/array.rst index f52b4b385e..d096c6ec48 100644 --- a/docs/library/array.rst +++ b/docs/library/array.rst @@ -4,8 +4,7 @@ .. module:: array :synopsis: efficient arrays of numeric data -See `Python array `_ for more -information. +|see_cpython_module| :mod:`python:array`. Supported format codes: ``b``, ``B``, ``h``, ``H``, ``i``, ``I``, ``l``, ``L``, ``q``, ``Q``, ``f``, ``d`` (the latter 2 depending on the diff --git a/docs/library/btree.rst b/docs/library/btree.rst index bd7890586a..9322d32e6a 100644 --- a/docs/library/btree.rst +++ b/docs/library/btree.rst @@ -22,8 +22,14 @@ Example:: # First, we need to open a stream which holds a database # This is usually a file, but can be in-memory database - # using uio.BytesIO, a raw flash section, etc. - f = open("mydb", "w+b") + # using uio.BytesIO, a raw flash partition, etc. + # Oftentimes, you want to create a database file if it doesn't + # exist and open if it exists. Idiom below takes care of this. + # DO NOT open database with "a+b" access mode. + try: + f = open("mydb", "r+b") + except OSError: + f = open("mydb", "w+b") # Now open a database itself db = btree.open(f) @@ -33,6 +39,11 @@ Example:: db[b"1"] = b"one" db[b"2"] = b"two" + # Assume that any changes are cached in memory unless + # explicitly flushed (or database closed). Flush database + # at the end of each "transaction". + db.flush() + # Prints b'two' print(db[b"2"]) @@ -71,18 +82,18 @@ Functions other parameters are optional and keyword-only, and allow to tweak advanced parameters of the database operation (most users will not need them): - * `flags` - Currently unused. - * `cachesize` - Suggested maximum memory cache size in bytes. For a + * *flags* - Currently unused. + * *cachesize* - Suggested maximum memory cache size in bytes. For a board with enough memory using larger values may improve performance. The value is only a recommendation, the module may use more memory if values set too low. - * `pagesize` - Page size used for the nodes in BTree. Acceptable range + * *pagesize* - Page size used for the nodes in BTree. Acceptable range is 512-65536. If 0, underlying I/O block size will be used (the best compromise between memory usage and performance). - * `minkeypage` - Minimum number of keys to store per page. Default value + * *minkeypage* - Minimum number of keys to store per page. Default value of 0 equivalent to 2. - Returns a `BTree` object, which implements a dictionary protocol (set + Returns a BTree object, which implements a dictionary protocol (set of methods), and some additional methods described below. Methods @@ -92,7 +103,7 @@ Methods Close the database. It's mandatory to close the database at the end of processing, as some unwritten data may be still in the cache. Note that - this does not close underlying streamw with which the database was opened, + this does not close underlying stream with which the database was opened, it should be closed separately (which is also mandatory to make sure that data flushed from buffer to the underlying storage). @@ -101,10 +112,10 @@ Methods Flush any data in cache to the underlying stream. .. method:: btree.__getitem__(key) -.. method:: btree.get(key, default=None) -.. method:: btree.__setitem__(key, val) -.. method:: btree.__detitem__(key) -.. method:: btree.__contains__(key) + btree.get(key, default=None) + btree.__setitem__(key, val) + btree.__detitem__(key) + btree.__contains__(key) Standard dictionary methods. @@ -114,20 +125,20 @@ Methods to get access to all keys in order. .. method:: btree.keys([start_key, [end_key, [flags]]]) -.. method:: btree.values([start_key, [end_key, [flags]]]) -.. method:: btree.items([start_key, [end_key, [flags]]]) + btree.values([start_key, [end_key, [flags]]]) + btree.items([start_key, [end_key, [flags]]]) These methods are similar to standard dictionary methods, but also can take optional parameters to iterate over a key sub-range, instead of - the entire database. Note that for all 3 methods, `start_key` and - `end_key` arguments represent key values. For example, ``values()`` + the entire database. Note that for all 3 methods, *start_key* and + *end_key* arguments represent key values. For example, `values()` method will iterate over values corresponding to they key range - given. None values for `start_key` means "from the first key", no - `end_key` or its value of None means "until the end of database". - By default, range is inclusive of `start_key` and exclusive of - `end_key`, you can include `end_key` in iteration by passing `flags` + given. None values for *start_key* means "from the first key", no + *end_key* or its value of None means "until the end of database". + By default, range is inclusive of *start_key* and exclusive of + *end_key*, you can include *end_key* in iteration by passing *flags* of `btree.INCL`. You can iterate in descending key direction - by passing `flags` of `btree.DESC`. The flags values can be ORed + by passing *flags* of `btree.DESC`. The flags values can be ORed together. Constants diff --git a/docs/library/builtins.rst b/docs/library/builtins.rst index 46f762660a..365248dc76 100644 --- a/docs/library/builtins.rst +++ b/docs/library/builtins.rst @@ -1,8 +1,11 @@ -Builtin Functions -================= +Builtin functions and exceptions +================================ -All builtin functions are described here. They are also available via -``builtins`` module. +All builtin functions and exceptions are described here. They are also +available via ``builtins`` module. + +Functions and types +------------------- .. function:: abs() @@ -18,6 +21,8 @@ All builtin functions are described here. They are also available via .. class:: bytes() + |see_cpython| `python:bytes`. + .. function:: callable() .. function:: chr() @@ -144,3 +149,51 @@ All builtin functions are described here. They are also available via .. function:: type() .. function:: zip() + + +Exceptions +---------- + +.. exception:: AssertionError + +.. exception:: AttributeError + +.. exception:: Exception + +.. exception:: ImportError + +.. exception:: IndexError + +.. exception:: KeyboardInterrupt + +.. exception:: KeyError + +.. exception:: MemoryError + +.. exception:: NameError + +.. exception:: NotImplementedError + +.. exception:: OSError + + |see_cpython| `python:OSError`. MicroPython doesn't implement ``errno`` + attribute, instead use the standard way to access exception arguments: + ``exc.args[0]``. + +.. exception:: RuntimeError + +.. exception:: StopIteration + +.. exception:: SyntaxError + +.. exception:: SystemExit + + |see_cpython| `python:SystemExit`. + +.. exception:: TypeError + + |see_cpython| `python:TypeError`. + +.. exception:: ValueError + +.. exception:: ZeroDivisionError diff --git a/docs/library/cmath.rst b/docs/library/cmath.rst index 465cf54ad3..59e4ec1722 100644 --- a/docs/library/cmath.rst +++ b/docs/library/cmath.rst @@ -4,6 +4,8 @@ .. module:: cmath :synopsis: mathematical functions for complex numbers +|see_cpython_module| :mod:`python:cmath`. + The ``cmath`` module provides some basic mathematical functions for working with complex numbers. diff --git a/docs/library/esp.rst b/docs/library/esp.rst index 8cafb92cd0..121a80d42e 100644 --- a/docs/library/esp.rst +++ b/docs/library/esp.rst @@ -14,7 +14,7 @@ Functions Get or set the sleep type. - If the ``sleep_type`` parameter is provided, sets the sleep type to its + If the *sleep_type* parameter is provided, sets the sleep type to its value. If the function is called without parameters, returns the current sleep type. @@ -55,23 +55,23 @@ Functions 1MByte of flash (which is memory mapped), and this function controls the location. - If `start` and `length` are both `None` then the native code location is + If *start* and *length* are both ``None`` then the native code location is set to the unused portion of memory at the end of the iRAM1 region. The size of this unused portion depends on the firmware and is typically quite small (around 500 bytes), and is enough to store a few very small functions. The advantage of using this iRAM1 region is that it does not get worn out by writing to it. - If neither `start` nor `length` are `None` then they should be integers. - `start` should specify the byte offset from the beginning of the flash at - which native code should be stored. `length` specifies how many bytes of - flash from `start` can be used to store native code. `start` and `length` + If neither *start* nor *length* are ``None`` then they should be integers. + *start* should specify the byte offset from the beginning of the flash at + which native code should be stored. *length* specifies how many bytes of + flash from *start* can be used to store native code. *start* and *length* should be multiples of the sector size (being 4096 bytes). The flash will be automatically erased before writing to it so be sure to use a region of flash that is not otherwise used, for example by the firmware or the filesystem. - When using the flash to store native code `start+length` must be less + When using the flash to store native code *start+length* must be less than or equal to 1MByte. Note that the flash can be worn out if repeated erasures (and writes) are made so use this feature sparingly. In particular, native code needs to be recompiled and rewritten to flash diff --git a/docs/library/framebuf.rst b/docs/library/framebuf.rst index 61f0635f36..b92bd08eff 100644 --- a/docs/library/framebuf.rst +++ b/docs/library/framebuf.rst @@ -32,25 +32,25 @@ Constructors Construct a FrameBuffer object. The parameters are: - - `buffer` is an object with a buffer protocol which must be large + - *buffer* is an object with a buffer protocol which must be large enough to contain every pixel defined by the width, height and format of the FrameBuffer. - - `width` is the width of the FrameBuffer in pixels - - `height` is the height of the FrameBuffer in pixels - - `format` specifies the type of pixel used in the FrameBuffer; + - *width* is the width of the FrameBuffer in pixels + - *height* is the height of the FrameBuffer in pixels + - *format* specifies the type of pixel used in the FrameBuffer; valid values are ``framebuf.MVLSB``, ``framebuf.RGB565`` and ``framebuf.GS4_HMSB``. MVLSB is monochrome 1-bit color, RGB565 is RGB 16-bit color, and GS4_HMSB is grayscale 4-bit color. Where a color value c is passed to a method, c is a small integer with an encoding that is dependent on the format of the FrameBuffer. - - `stride` is the number of pixels between each horizontal line - of pixels in the FrameBuffer. This defaults to `width` but may + - *stride* is the number of pixels between each horizontal line + of pixels in the FrameBuffer. This defaults to *width* but may need adjustments when implementing a FrameBuffer within another - larger FrameBuffer or screen. The `buffer` size must accommodate + larger FrameBuffer or screen. The *buffer* size must accommodate an increased step size. - One must specify valid `buffer`, `width`, `height`, `format` and - optionally `stride`. Invalid `buffer` size or dimensions may lead to + One must specify valid *buffer*, *width*, *height*, *format* and + optionally *stride*. Invalid *buffer* size or dimensions may lead to unexpected errors. Drawing primitive shapes @@ -64,8 +64,8 @@ The following methods draw shapes onto the FrameBuffer. .. method:: FrameBuffer.pixel(x, y[, c]) - If `c` is not given, get the color value of the specified pixel. - If `c` is given, set the specified pixel to the given color. + If *c* is not given, get the color value of the specified pixel. + If *c* is given, set the specified pixel to the given color. .. method:: FrameBuffer.hline(x, y, w, c) .. method:: FrameBuffer.vline(x, y, h, c) @@ -106,7 +106,7 @@ Other methods .. method:: FrameBuffer.blit(fbuf, x, y[, key]) Draw another FrameBuffer on top of the current one at the given coordinates. - If `key` is specified then it should be a color integer and the + If *key* is specified then it should be a color integer and the corresponding color will be considered transparent: all pixels with that color value will not be drawn. diff --git a/docs/library/gc.rst b/docs/library/gc.rst index 01e63ae51e..c823aed3e6 100644 --- a/docs/library/gc.rst +++ b/docs/library/gc.rst @@ -4,6 +4,8 @@ .. module:: gc :synopsis: control the garbage collector +|see_cpython_module| :mod:`python:gc`. + Functions --------- @@ -24,6 +26,41 @@ Functions Return the number of bytes of heap RAM that are allocated. + .. admonition:: Difference to CPython + :class: attention + + This function is MicroPython extension. + .. function:: mem_free() - Return the number of bytes of available heap RAM. + Return the number of bytes of available heap RAM, or -1 if this amount + is not known. + + .. admonition:: Difference to CPython + :class: attention + + This function is MicroPython extension. + +.. function:: threshold([amount]) + + Set or query the additional GC allocation threshold. Normally, a collection + is triggered only when a new allocation cannot be satisfied, i.e. on an + out-of-memory (OOM) condition. If this function is called, in addition to + OOM, a collection will be triggered each time after *amount* bytes have been + allocated (in total, since the previous time such an amount of bytes + have been allocated). *amount* is usually specified as less than the + full heap size, with the intention to trigger a collection earlier than when the + heap becomes exhausted, and in the hope that an early collection will prevent + excessive memory fragmentation. This is a heuristic measure, the effect + of which will vary from application to application, as well as + the optimal value of the *amount* parameter. + + Calling the function without argument will return the current value of + the threshold. A value of -1 means a disabled allocation threshold. + + .. admonition:: Difference to CPython + :class: attention + + This function is a MicroPython extension. CPython has a similar + function - ``set_threshold()``, but due to different GC + implementations, its signature and semantics are different. diff --git a/docs/library/index.rst b/docs/library/index.rst index 770920a1ff..e884f266ee 100644 --- a/docs/library/index.rst +++ b/docs/library/index.rst @@ -1,3 +1,5 @@ +.. _micropython_lib: + MicroPython libraries ===================== @@ -72,16 +74,17 @@ it will fallback to loading the built-in ``ujson`` module. cmath.rst gc.rst math.rst - select.rst sys.rst ubinascii.rst ucollections.rst + uerrno.rst uhashlib.rst uheapq.rst uio.rst ujson.rst uos.rst ure.rst + uselect.rst usocket.rst ustruct.rst utime.rst @@ -97,16 +100,17 @@ it will fallback to loading the built-in ``ujson`` module. cmath.rst gc.rst math.rst - select.rst sys.rst ubinascii.rst ucollections.rst + uerrno.rst uhashlib.rst uheapq.rst uio.rst ujson.rst uos.rst ure.rst + uselect.rst usocket.rst ustruct.rst utime.rst @@ -120,12 +124,12 @@ it will fallback to loading the built-in ``ujson`` module. builtins.rst array.rst gc.rst - select.rst sys.rst ubinascii.rst ujson.rst uos.rst ure.rst + uselect.rst usocket.rst ussl.rst utime.rst @@ -142,12 +146,14 @@ it will fallback to loading the built-in ``ujson`` module. sys.rst ubinascii.rst ucollections.rst + uerrno.rst uhashlib.rst uheapq.rst uio.rst ujson.rst uos.rst ure.rst + uselect.rst usocket.rst ussl.rst ustruct.rst diff --git a/docs/library/lcd160cr.rst b/docs/library/lcd160cr.rst index bd47412986..567994640b 100644 --- a/docs/library/lcd160cr.rst +++ b/docs/library/lcd160cr.rst @@ -41,21 +41,21 @@ Constructors Construct an LCD160CR object. The parameters are: - - `connect` is a string specifying the physical connection of the LCD + - *connect* is a string specifying the physical connection of the LCD display to the board; valid values are "X", "Y", "XY", "YX". Use "X" when the display is connected to a pyboard in the X-skin position, and "Y" when connected in the Y-skin position. "XY" and "YX" are used when the display is connected to the right or left side of the pyboard, respectively. - - `pwr` is a Pin object connected to the LCD's power/enabled pin. - - `i2c` is an I2C object connected to the LCD's I2C interface. - - `spi` is an SPI object connected to the LCD's SPI interface. - - `i2c_addr` is the I2C address of the display. + - *pwr* is a Pin object connected to the LCD's power/enabled pin. + - *i2c* is an I2C object connected to the LCD's I2C interface. + - *spi* is an SPI object connected to the LCD's SPI interface. + - *i2c_addr* is the I2C address of the display. - One must specify either a valid `connect` or all of `pwr`, `i2c` and `spi`. - If a valid `connect` is given then any of `pwr`, `i2c` or `spi` which are - not passed as parameters (ie they are `None`) will be created based on the - value of `connect`. This allows to override the default interface to the + One must specify either a valid *connect* or all of *pwr*, *i2c* and *spi*. + If a valid *connect* is given then any of *pwr*, *i2c* or *spi* which are + not passed as parameters (i.e. they are ``None``) will be created based on the + value of *connect*. This allows to override the default interface to the display if needed. The default values are: @@ -103,12 +103,12 @@ Setup commands .. method:: LCD160CR.set_power(on) - Turn the display on or off, depending on the given value of `on`: 0 or `False` - will turn the display off, and 1 or `True` will turn it on. + Turn the display on or off, depending on the given value of *on*: 0 or ``False`` + will turn the display off, and 1 or ``True`` will turn it on. .. method:: LCD160CR.set_orient(orient) - Set the orientation of the display. The `orient` parameter can be one + Set the orientation of the display. The *orient* parameter can be one of `PORTRAIT`, `LANDSCAPE`, `PORTRAIT_UPSIDEDOWN`, `LANDSCAPE_UPSIDEDOWN`. .. method:: LCD160CR.set_brightness(value) @@ -117,7 +117,7 @@ Setup commands .. method:: LCD160CR.set_i2c_addr(addr) - Set the I2C address of the display. The `addr` value must have the + Set the I2C address of the display. The *addr* value must have the lower 2 bits cleared. .. method:: LCD160CR.set_uart_baudrate(baudrate) @@ -126,7 +126,7 @@ Setup commands .. method:: LCD160CR.set_startup_deco(value) - Set the start-up decoration of the display. The `value` parameter can be a + Set the start-up decoration of the display. The *value* parameter can be a logical or of `STARTUP_DECO_NONE`, `STARTUP_DECO_MLOGO`, `STARTUP_DECO_INFO`. .. method:: LCD160CR.save_to_flash() @@ -151,17 +151,17 @@ The following methods manipulate individual pixels on the display. .. method:: LCD160CR.get_line(x, y, buf) Low-level method to get a line of pixels into the given buffer. - To read `n` pixels `buf` should be `2*n+1` bytes in length. The first byte + To read *n* pixels *buf* should be *2*n+1* bytes in length. The first byte is a dummy byte and should be ignored, and subsequent bytes represent the - pixels in the line starting at coordinate `(x, y)`. + pixels in the line starting at coordinate *(x, y)*. .. method:: LCD160CR.screen_dump(buf, x=0, y=0, w=None, h=None) - Dump the contents of the screen to the given buffer. The parameters `x` and `y` - specify the starting coordinate, and `w` and `h` the size of the region. If `w` - or `h` are `None` then they will take on their maximum values, set by the size - of the screen minus the given `x` and `y` values. `buf` should be large enough - to hold `2*w*h` bytes. If it's smaller then only the initial horizontal lines + Dump the contents of the screen to the given buffer. The parameters *x* and *y* + specify the starting coordinate, and *w* and *h* the size of the region. If *w* + or *h* are ``None`` then they will take on their maximum values, set by the size + of the screen minus the given *x* and *y* values. *buf* should be large enough + to hold ``2*w*h`` bytes. If it's smaller then only the initial horizontal lines will be stored. .. method:: LCD160CR.screen_load(buf) @@ -188,18 +188,18 @@ To draw text one sets the position, color and font, and then uses Set the font for the text. Subsequent calls to `write` will use the newly configured font. The parameters are: - - `font` is the font family to use, valid values are 0, 1, 2, 3. - - `scale` is a scaling value for each character pixel, where the pixels - are drawn as a square with side length equal to `scale + 1`. The value + - *font* is the font family to use, valid values are 0, 1, 2, 3. + - *scale* is a scaling value for each character pixel, where the pixels + are drawn as a square with side length equal to *scale + 1*. The value can be between 0 and 63. - - `bold` controls the number of pixels to overdraw each character pixel, - making a bold effect. The lower 2 bits of `bold` are the number of + - *bold* controls the number of pixels to overdraw each character pixel, + making a bold effect. The lower 2 bits of *bold* are the number of pixels to overdraw in the horizontal direction, and the next 2 bits are - for the vertical direction. For example, a `bold` value of 5 will + for the vertical direction. For example, a *bold* value of 5 will overdraw 1 pixel in both the horizontal and vertical directions. - - `trans` can be either 0 or 1 and if set to 1 the characters will be + - *trans* can be either 0 or 1 and if set to 1 the characters will be drawn with a transparent background. - - `scroll` can be either 0 or 1 and if set to 1 the display will do a + - *scroll* can be either 0 or 1 and if set to 1 the display will do a soft scroll if the text moves to the next line. .. method:: LCD160CR.write(s) @@ -252,7 +252,7 @@ Primitive drawing commands use a foreground and background color set by the .. method:: LCD160CR.poly_dot(data) Draw a sequence of dots using the pen line color. - The `data` should be a buffer of bytes, with each successive pair of + The *data* should be a buffer of bytes, with each successive pair of bytes corresponding to coordinate pairs (x, y). .. method:: LCD160CR.poly_line(data) @@ -266,25 +266,25 @@ Touch screen methods Configure the touch panel: - - If `calib` is `True` then the call will trigger a touch calibration of + - If *calib* is ``True`` then the call will trigger a touch calibration of the resistive touch sensor. This requires the user to touch various parts of the screen. - - If `save` is `True` then the touch parameters will be saved to NVRAM + - If *save* is ``True`` then the touch parameters will be saved to NVRAM to persist across reset/power up. - - If `irq` is `True` then the display will be configured to pull the IRQ - line low when a touch force is detected. If `irq` is `False` then this - feature is disabled. If `irq` is `None` (the default value) then no + - If *irq* is ``True`` then the display will be configured to pull the IRQ + line low when a touch force is detected. If *irq* is ``False`` then this + feature is disabled. If *irq* is ``None`` (the default value) then no change is made to this setting. .. method:: LCD160CR.is_touched() - Returns a boolean: `True` if there is currently a touch force on the screen, + Returns a boolean: ``True`` if there is currently a touch force on the screen, `False` otherwise. .. method:: LCD160CR.get_touch() - Returns a 3-tuple of: (active, x, y). If there is currently a touch force - on the screen then `active` is 1, otherwise it is 0. The `x` and `y` values + Returns a 3-tuple of: *(active, x, y)*. If there is currently a touch force + on the screen then *active* is 1, otherwise it is 0. The *x* and *y* values indicate the position of the current or most recent touch. Advanced commands @@ -308,7 +308,7 @@ Advanced commands .. method:: LCD160CR.show_framebuf(buf) - Show the given buffer on the display. `buf` should be an array of bytes containing + Show the given buffer on the display. *buf* should be an array of bytes containing the 16-bit RGB values for the pixels, and they will be written to the area specified by :meth:`LCD160CR.set_spi_win`, starting from the top-left corner. @@ -325,35 +325,35 @@ Advanced commands Configure a window region for scrolling: - - `win` is the window id to configure. There are 0..7 standard windows for + - *win* is the window id to configure. There are 0..7 standard windows for general purpose use. Window 8 is the text scroll window (the ticker). - - `x`, `y`, `w`, `h` specify the location of the window in the display. - - `vec` specifies the direction and speed of scroll: it is a 16-bit value - of the form ``0bF.ddSSSSSSSSSSSS``. `dd` is 0, 1, 2, 3 for +x, +y, -x, - -y scrolling. `F` sets the speed format, with 0 meaning that the window - is shifted `S % 256` pixel every frame, and 1 meaning that the window - is shifted 1 pixel every `S` frames. - - `pat` is a 16-bit pattern mask for the background. - - `fill` is the fill color. - - `color` is the extra color, either of the text or pattern foreground. + - *x*, *y*, *w*, *h* specify the location of the window in the display. + - *vec* specifies the direction and speed of scroll: it is a 16-bit value + of the form ``0bF.ddSSSSSSSSSSSS``. *dd* is 0, 1, 2, 3 for +x, +y, -x, + -y scrolling. *F* sets the speed format, with 0 meaning that the window + is shifted *S % 256* pixel every frame, and 1 meaning that the window + is shifted 1 pixel every *S* frames. + - *pat* is a 16-bit pattern mask for the background. + - *fill* is the fill color. + - *color* is the extra color, either of the text or pattern foreground. .. method:: LCD160CR.set_scroll_win_param(win, param, value) Set a single parameter of a scrolling window region: - - `win` is the window id, 0..8. - - `param` is the parameter number to configure, 0..7, and corresponds + - *win* is the window id, 0..8. + - *param* is the parameter number to configure, 0..7, and corresponds to the parameters in the `set_scroll_win` method. - - `value` is the value to set. + - *value* is the value to set. .. method:: LCD160CR.set_scroll_buf(s) - Set the string for scrolling in window 8. The parameter `s` must be a string + Set the string for scrolling in window 8. The parameter *s* must be a string with length 32 or less. .. method:: LCD160CR.jpeg(buf) - Display a JPEG. `buf` should contain the entire JPEG data. JPEG data should + Display a JPEG. *buf* should contain the entire JPEG data. JPEG data should not include EXIF information. The following encodings are supported: Baseline DCT, Huffman coding, 8 bits per sample, 3 color components, YCbCr4:2:2. The origin of the JPEG is set by :meth:`LCD160CR.set_pos`. @@ -380,15 +380,15 @@ Constants --------- .. data:: lcd160cr.PORTRAIT -.. data:: lcd160cr.LANDSCAPE -.. data:: lcd160cr.PORTRAIT_UPSIDEDOWN -.. data:: lcd160cr.LANDSCAPE_UPSIDEDOWN + lcd160cr.LANDSCAPE + lcd160cr.PORTRAIT_UPSIDEDOWN + lcd160cr.LANDSCAPE_UPSIDEDOWN - orientation of the display, used by :meth:`LCD160CR.set_orient` + Orientations of the display, used by :meth:`LCD160CR.set_orient`. .. data:: lcd160cr.STARTUP_DECO_NONE -.. data:: lcd160cr.STARTUP_DECO_MLOGO -.. data:: lcd160cr.STARTUP_DECO_INFO + lcd160cr.STARTUP_DECO_MLOGO + lcd160cr.STARTUP_DECO_INFO - type of start-up decoration, can be or'd together, used by - :meth:`LCD160CR.set_startup_deco` + Types of start-up decoration, can be OR'ed together, used by + :meth:`LCD160CR.set_startup_deco`. diff --git a/docs/library/machine.I2C.rst b/docs/library/machine.I2C.rst index a1b4178905..a69c58999f 100644 --- a/docs/library/machine.I2C.rst +++ b/docs/library/machine.I2C.rst @@ -37,16 +37,16 @@ Constructors Construct and return a new I2C object using the following parameters: - - `id` identifies the particular I2C peripheral. The default + - *id* identifies a particular I2C peripheral. The default value of -1 selects a software implementation of I2C which can work (in most cases) with arbitrary pins for SCL and SDA. - If `id` is -1 then `scl` and `sda` must be specified. Other - allowed values for `id` depend on the particular port/board, - and specifying `scl` and `sda` may or may not be required or + If *id* is -1 then *scl* and *sda* must be specified. Other + allowed values for *id* depend on the particular port/board, + and specifying *scl* and *sda* may or may not be required or allowed in this case. - - `scl` should be a pin object specifying the pin to use for SCL. - - `sda` should be a pin object specifying the pin to use for SDA. - - `freq` should be an integer which sets the maximum frequency + - *scl* should be a pin object specifying the pin to use for SCL. + - *sda* should be a pin object specifying the pin to use for SDA. + - *freq* should be an integer which sets the maximum frequency for SCL. General Methods @@ -56,9 +56,9 @@ General Methods Initialise the I2C bus with the given arguments: - - `scl` is a pin object for the SCL line - - `sda` is a pin object for the SDA line - - `freq` is the SCL clock rate + - *scl* is a pin object for the SCL line + - *sda* is a pin object for the SDA line + - *freq* is the SCL clock rate .. method:: I2C.deinit() @@ -93,9 +93,9 @@ control over the bus, otherwise the standard methods (see below) can be used. .. method:: I2C.readinto(buf, nack=True) - Reads bytes from the bus and stores them into `buf`. The number of bytes - read is the length of `buf`. An ACK will be sent on the bus after - receiving all but the last byte. After the last byte is received, if `nack` + Reads bytes from the bus and stores them into *buf*. The number of bytes + read is the length of *buf*. An ACK will be sent on the bus after + receiving all but the last byte. After the last byte is received, if *nack* is true then a NACK will be sent, otherwise an ACK will be sent (and in this case the slave assumes more bytes are going to be read in a later call). @@ -103,7 +103,7 @@ control over the bus, otherwise the standard methods (see below) can be used. .. method:: I2C.write(buf) - Write the bytes from `buf` to the bus. Checks that an ACK is received + Write the bytes from *buf* to the bus. Checks that an ACK is received after each byte and stops transmitting the remaining bytes if a NACK is received. The function returns the number of ACKs that were received. @@ -117,23 +117,23 @@ operations that target a given slave device. .. method:: I2C.readfrom(addr, nbytes, stop=True) - Read `nbytes` from the slave specified by `addr`. - If `stop` is true then a STOP condition is generated at the end of the transfer. + Read *nbytes* from the slave specified by *addr*. + If *stop* is true then a STOP condition is generated at the end of the transfer. Returns a `bytes` object with the data read. .. method:: I2C.readfrom_into(addr, buf, stop=True) - Read into `buf` from the slave specified by `addr`. - The number of bytes read will be the length of `buf`. - If `stop` is true then a STOP condition is generated at the end of the transfer. + Read into *buf* from the slave specified by *addr*. + The number of bytes read will be the length of *buf*. + If *stop* is true then a STOP condition is generated at the end of the transfer. - The method returns `None`. + The method returns ``None``. .. method:: I2C.writeto(addr, buf, stop=True) - Write the bytes from `buf` to the slave specified by `addr`. If a - NACK is received following the write of a byte from `buf` then the - remaining bytes are not sent. If `stop` is true then a STOP condition is + Write the bytes from *buf* to the slave specified by *addr*. If a + NACK is received following the write of a byte from *buf* then the + remaining bytes are not sent. If *stop* is true then a STOP condition is generated at the end of the transfer, even if a NACK is received. The function returns the number of ACKs that were received. @@ -147,26 +147,26 @@ methods are convenience functions to communicate with such devices. .. method:: I2C.readfrom_mem(addr, memaddr, nbytes, \*, addrsize=8) - Read `nbytes` from the slave specified by `addr` starting from the memory - address specified by `memaddr`. - The argument `addrsize` specifies the address size in bits. + Read *nbytes* from the slave specified by *addr* starting from the memory + address specified by *memaddr*. + The argument *addrsize* specifies the address size in bits. Returns a `bytes` object with the data read. .. method:: I2C.readfrom_mem_into(addr, memaddr, buf, \*, addrsize=8) - Read into `buf` from the slave specified by `addr` starting from the - memory address specified by `memaddr`. The number of bytes read is the - length of `buf`. - The argument `addrsize` specifies the address size in bits (on ESP8266 + Read into *buf* from the slave specified by *addr* starting from the + memory address specified by *memaddr*. The number of bytes read is the + length of *buf*. + The argument *addrsize* specifies the address size in bits (on ESP8266 this argument is not recognised and the address size is always 8 bits). - The method returns `None`. + The method returns ``None``. .. method:: I2C.writeto_mem(addr, memaddr, buf, \*, addrsize=8) - Write `buf` to the slave specified by `addr` starting from the - memory address specified by `memaddr`. - The argument `addrsize` specifies the address size in bits (on ESP8266 + Write *buf* to the slave specified by *addr* starting from the + memory address specified by *memaddr*. + The argument *addrsize* specifies the address size in bits (on ESP8266 this argument is not recognised and the address size is always 8 bits). - The method returns `None`. + The method returns ``None``. diff --git a/docs/library/machine.UART.rst b/docs/library/machine.UART.rst index 64ff28e1ab..983ef0a947 100644 --- a/docs/library/machine.UART.rst +++ b/docs/library/machine.UART.rst @@ -18,7 +18,7 @@ UART objects can be created and initialised using:: Supported parameters differ on a board: -Pyboard: Bits can be 7, 8 or 9. Stop can be 1 or 2. With `parity=None`, +Pyboard: Bits can be 7, 8 or 9. Stop can be 1 or 2. With *parity=None*, only 8 and 9 bits are supported. With parity enabled, only 7 and 8 bits are supported. diff --git a/docs/library/machine.rst b/docs/library/machine.rst index 7ea7f565e7..087f19cc6c 100644 --- a/docs/library/machine.rst +++ b/docs/library/machine.rst @@ -13,7 +13,7 @@ damage. .. _machine_callbacks: -A note of callbacks used by functions and class methods of ``machine`` module: +A note of callbacks used by functions and class methods of :mod:`machine` module: all these callbacks should be considered as executing in an interrupt context. This is true for both physical devices with IDs >= 0 and "virtual" devices with negative IDs like -1 (these "virtual" devices are still thin shims on @@ -38,14 +38,14 @@ Interrupt related functions Disable interrupt requests. Returns the previous IRQ state which should be considered an opaque value. - This return value should be passed to the ``enable_irq`` function to restore - interrupts to their original state, before ``disable_irq`` was called. + This return value should be passed to the `enable_irq()` function to restore + interrupts to their original state, before `disable_irq()` was called. .. function:: enable_irq(state) Re-enable interrupt requests. - The ``state`` parameter should be the value that was returned from the most - recent call to the ``disable_irq`` function. + The *state* parameter should be the value that was returned from the most + recent call to the `disable_irq()` function. Power related functions ----------------------- @@ -71,8 +71,8 @@ Power related functions Stops the CPU and all peripherals (including networking interfaces, if any). Execution is resumed from the main script, just as with a reset. The reset cause can be checked - to know that we are coming from ``machine.DEEPSLEEP``. For wake up to actually happen, - wake sources should be configured first, like ``Pin`` change or ``RTC`` timeout. + to know that we are coming from `machine.DEEPSLEEP`. For wake up to actually happen, + wake sources should be configured first, like `Pin` change or `RTC` timeout. .. only:: port_wipy @@ -98,18 +98,18 @@ Miscellaneous functions .. function:: time_pulse_us(pin, pulse_level, timeout_us=1000000) - Time a pulse on the given `pin`, and return the duration of the pulse in - microseconds. The `pulse_level` argument should be 0 to time a low pulse + Time a pulse on the given *pin*, and return the duration of the pulse in + microseconds. The *pulse_level* argument should be 0 to time a low pulse or 1 to time a high pulse. - If the current input value of the pin is different to `pulse_level`, - the function first (*) waits until the pin input becomes equal to `pulse_level`, - then (**) times the duration that the pin is equal to `pulse_level`. - If the pin is already equal to `pulse_level` then timing starts straight away. + If the current input value of the pin is different to *pulse_level*, + the function first (*) waits until the pin input becomes equal to *pulse_level*, + then (**) times the duration that the pin is equal to *pulse_level*. + If the pin is already equal to *pulse_level* then timing starts straight away. The function will return -2 if there was timeout waiting for condition marked (*) above, and -1 if there was timeout during the main measurement, marked (**) - above. The timeout is the same for both cases and given by `timeout_us` (which + above. The timeout is the same for both cases and given by *timeout_us* (which is in microseconds). .. _machine_constants: diff --git a/docs/library/math.rst b/docs/library/math.rst index 9d5cf7b4ba..a6f13d48c1 100644 --- a/docs/library/math.rst +++ b/docs/library/math.rst @@ -4,6 +4,8 @@ .. module:: math :synopsis: mathematical functions +|see_cpython_module| :mod:`python:math`. + The ``math`` module provides some basic mathematical functions for working with floating-point numbers. diff --git a/docs/library/micropython.rst b/docs/library/micropython.rst index 7f40028565..4ff0b0c159 100644 --- a/docs/library/micropython.rst +++ b/docs/library/micropython.rst @@ -23,30 +23,30 @@ Functions variable, and does not take up any memory during execution. This `const` function is recognised directly by the MicroPython parser and is - provided as part of the `micropython` module mainly so that scripts can be + provided as part of the :mod:`micropython` module mainly so that scripts can be written which run under both CPython and MicroPython, by following the above pattern. .. function:: opt_level([level]) - If `level` is given then this function sets the optimisation level for subsequent - compilation of scripts, and returns `None`. Otherwise it returns the current + If *level* is given then this function sets the optimisation level for subsequent + compilation of scripts, and returns ``None``. Otherwise it returns the current optimisation level. .. function:: alloc_emergency_exception_buf(size) - Allocate ``size`` bytes of RAM for the emergency exception buffer (a good + Allocate *size* bytes of RAM for the emergency exception buffer (a good size is around 100 bytes). The buffer is used to create exceptions in cases when normal RAM allocation would fail (eg within an interrupt handler) and therefore give useful traceback information in these situations. A good way to use this function is to put it at the start of your main script - (eg boot.py or main.py) and then the emergency exception buffer will be active + (eg ``boot.py`` or ``main.py``) and then the emergency exception buffer will be active for all the code following it. .. function:: mem_info([verbose]) - Print information about currently used memory. If the ``verbose`` argument + Print information about currently used memory. If the *verbose`* argument is given then extra information is printed. The information that is printed is implementation dependent, but currently @@ -55,7 +55,7 @@ Functions .. function:: qstr_info([verbose]) - Print information about currently interned strings. If the ``verbose`` + Print information about currently interned strings. If the *verbose* argument is given then extra information is printed. The information that is printed is implementation dependent, but currently @@ -89,10 +89,10 @@ Functions incoming stream of characters that is usually used for the REPL, in case that stream is used for other purposes. -.. function:: schedule(fun, arg) +.. function:: schedule(func, arg) - Schedule the function `fun` to be executed "very soon". The function - is passed the value `arg` as its single argument. "very soon" means that + Schedule the function *func* to be executed "very soon". The function + is passed the value *arg* as its single argument. "Very soon" means that the MicroPython runtime will do its best to execute the function at the earliest possible time, given that it is also trying to be efficient, and that the following conditions hold: diff --git a/docs/library/network.rst b/docs/library/network.rst index 27fa0dcb2f..de93c0e01d 100644 --- a/docs/library/network.rst +++ b/docs/library/network.rst @@ -72,7 +72,7 @@ parameter should be `id`. connection parameters. For various medium types, there are different sets of predefined/recommended parameters, among them: - * WiFi: `bssid` keyword to connect by BSSID (MAC address) instead + * WiFi: *bssid* keyword to connect by BSSID (MAC address) instead of access point name .. method:: disconnect() @@ -118,7 +118,7 @@ parameter should be `id`. Get or set general network interface parameters. These methods allow to work with additional parameters beyond standard IP configuration (as dealt with by - ``ifconfig()``). These include network-specific and hardware-specific + `ifconfig()`). These include network-specific and hardware-specific parameters and status values. For setting parameters, the keyword argument syntax should be used, and multiple parameters can be set at once. For querying, a parameter name should be quoted as a string, and only one @@ -170,11 +170,11 @@ parameter should be `id`. Arguments are: - - ``spi`` is an :ref:`SPI object ` which is the SPI bus that the CC3000 is + - *spi* is an :ref:`SPI object ` which is the SPI bus that the CC3000 is connected to (the MOSI, MISO and CLK pins). - - ``pin_cs`` is a :ref:`Pin object ` which is connected to the CC3000 CS pin. - - ``pin_en`` is a :ref:`Pin object ` which is connected to the CC3000 VBEN pin. - - ``pin_irq`` is a :ref:`Pin object ` which is connected to the CC3000 IRQ pin. + - *pin_cs* is a :ref:`Pin object ` which is connected to the CC3000 CS pin. + - *pin_en* is a :ref:`Pin object ` which is connected to the CC3000 VBEN pin. + - *pin_irq* is a :ref:`Pin object ` which is connected to the CC3000 IRQ pin. All of these objects will be initialised by the driver, so there is no need to initialise them yourself. For example, you can use:: @@ -256,10 +256,10 @@ parameter should be `id`. Arguments are: - - ``spi`` is an :ref:`SPI object ` which is the SPI bus that the WIZnet5x00 is + - *spi* is an :ref:`SPI object ` which is the SPI bus that the WIZnet5x00 is connected to (the MOSI, MISO and SCLK pins). - - ``pin_cs`` is a :ref:`Pin object ` which is connected to the WIZnet5x00 nSS pin. - - ``pin_rst`` is a :ref:`Pin object ` which is connected to the WIZnet5x00 nRESET pin. + - *pin_cs* is a :ref:`Pin object ` which is connected to the WIZnet5x00 nSS pin. + - *pin_rst* is a :ref:`Pin object ` which is connected to the WIZnet5x00 nRESET pin. All of these objects will be initialised by the driver, so there is no need to initialise them yourself. For example, you can use:: @@ -294,7 +294,7 @@ parameter should be `id`. Get or set the PHY mode. - If the ``mode`` parameter is provided, sets the mode to its value. If + If the *mode* parameter is provided, sets the mode to its value. If the function is called without parameters, returns the current mode. The possible modes are defined as constants: @@ -322,7 +322,7 @@ parameter should be `id`. ``network.STA_IF`` (station aka client, connects to upstream WiFi access points) and ``network.AP_IF`` (access point, allows other WiFi clients to connect). Availability of the methods below depends on interface type. - For example, only STA interface may ``connect()`` to an access point. + For example, only STA interface may `connect()` to an access point. Methods ------- @@ -350,8 +350,8 @@ parameter should be `id`. (ssid, bssid, channel, RSSI, authmode, hidden) - `bssid` is hardware address of an access point, in binary form, returned as - bytes object. You can use ``ubinascii.hexlify()`` to convert it to ASCII form. + *bssid* is hardware address of an access point, in binary form, returned as + bytes object. You can use `ubinascii.hexlify()` to convert it to ASCII form. There are five values for authmode: @@ -399,7 +399,7 @@ parameter should be `id`. Get or set general network interface parameters. These methods allow to work with additional parameters beyond standard IP configuration (as dealt with by - ``wlan.ifconfig()``). These include network-specific and hardware-specific + `wlan.ifconfig()`). These include network-specific and hardware-specific parameters. For setting parameters, keyword argument syntax should be used, multiple parameters can be set at once. For querying, parameters name should be quoted as a string, and only one parameter can be queries at time:: @@ -450,7 +450,7 @@ parameter should be `id`. .. class:: WLAN(id=0, ...) - Create a WLAN object, and optionally configure it. See ``init`` for params of configuration. + Create a WLAN object, and optionally configure it. See `init()` for params of configuration. .. note:: @@ -469,14 +469,14 @@ parameter should be `id`. Arguments are: - - ``mode`` can be either ``WLAN.STA`` or ``WLAN.AP``. - - ``ssid`` is a string with the ssid name. Only needed when mode is ``WLAN.AP``. - - ``auth`` is a tuple with (sec, key). Security can be ``None``, ``WLAN.WEP``, + - *mode* can be either ``WLAN.STA`` or ``WLAN.AP``. + - *ssid* is a string with the ssid name. Only needed when mode is ``WLAN.AP``. + - *auth* is a tuple with (sec, key). Security can be ``None``, ``WLAN.WEP``, ``WLAN.WPA`` or ``WLAN.WPA2``. The key is a string with the network password. If ``sec`` is ``WLAN.WEP`` the key must be a string representing hexadecimal values (e.g. 'ABC1DE45BF'). Only needed when mode is ``WLAN.AP``. - - ``channel`` a number in the range 1-11. Only needed when mode is ``WLAN.AP``. - - ``antenna`` selects between the internal and the external antenna. Can be either + - *channel* a number in the range 1-11. Only needed when mode is ``WLAN.AP``. + - *antenna* selects between the internal and the external antenna. Can be either ``WLAN.INT_ANT`` or ``WLAN.EXT_ANT``. For example, you can do:: @@ -494,13 +494,13 @@ parameter should be `id`. Connect to a WiFi access point using the given SSID, and other security parameters. - - ``auth`` is a tuple with (sec, key). Security can be ``None``, ``WLAN.WEP``, + - *auth* is a tuple with (sec, key). Security can be ``None``, ``WLAN.WEP``, ``WLAN.WPA`` or ``WLAN.WPA2``. The key is a string with the network password. If ``sec`` is ``WLAN.WEP`` the key must be a string representing hexadecimal values (e.g. 'ABC1DE45BF'). - - ``bssid`` is the MAC address of the AP to connect to. Useful when there are several + - *bssid* is the MAC address of the AP to connect to. Useful when there are several APs with the same ssid. - - ``timeout`` is the maximum time in milliseconds to wait for the connection to succeed. + - *timeout* is the maximum time in milliseconds to wait for the connection to succeed. .. method:: wlan.scan() @@ -518,7 +518,7 @@ parameter should be `id`. .. method:: wlan.ifconfig(if_id=0, config=['dhcp' or configtuple]) - With no parameters given returns a 4-tuple of ``(ip, subnet_mask, gateway, DNS_server)``. + With no parameters given returns a 4-tuple of *(ip, subnet_mask, gateway, DNS_server)*. if ``'dhcp'`` is passed as a parameter then the DHCP client is enabled and the IP params are negotiated with the AP. @@ -556,8 +556,8 @@ parameter should be `id`. Create a callback to be triggered when a WLAN event occurs during ``machine.SLEEP`` mode. Events are triggered by socket activity or by WLAN connection/disconnection. - - ``handler`` is the function that gets called when the IRQ is triggered. - - ``wake`` must be ``machine.SLEEP``. + - *handler* is the function that gets called when the IRQ is triggered. + - *wake* must be ``machine.SLEEP``. Returns an IRQ object. diff --git a/docs/library/pyb.Switch.rst b/docs/library/pyb.Switch.rst index bc62b6eee9..0d5dc63b74 100644 --- a/docs/library/pyb.Switch.rst +++ b/docs/library/pyb.Switch.rst @@ -8,7 +8,8 @@ A Switch object is used to control a push-button switch. Usage:: sw = pyb.Switch() # create a switch object - sw() # get state (True if pressed, False otherwise) + sw.value() # get state (True if pressed, False otherwise) + sw() # shorthand notation to get the switch state sw.callback(f) # register a callback to be called when the # switch is pressed down sw.callback(None) # remove the callback @@ -34,6 +35,10 @@ Methods Call switch object directly to get its state: ``True`` if pressed down, ``False`` otherwise. +.. method:: Switch.value() + + Get the switch state. Returns `True` if pressed down, otherwise `False`. + .. method:: Switch.callback(fun) Register the given function to be called when the switch is pressed down. diff --git a/docs/library/pyb.rst b/docs/library/pyb.rst index 9c4933808a..7991601457 100644 --- a/docs/library/pyb.rst +++ b/docs/library/pyb.rst @@ -21,7 +21,7 @@ Time related functions Returns the number of milliseconds since the board was last reset. - The result is always a micropython smallint (31-bit signed number), so + The result is always a MicroPython smallint (31-bit signed number), so after 2^30 milliseconds (about 12.4 days) this will start to return negative numbers. @@ -33,7 +33,7 @@ Time related functions Returns the number of microseconds since the board was last reset. - The result is always a micropython smallint (31-bit signed number), so + The result is always a MicroPython smallint (31-bit signed number), so after 2^30 microseconds (about 17.8 minutes) this will start to return negative numbers. @@ -85,10 +85,10 @@ Reset related functions Enable or disable hard-fault debugging. A hard-fault is when there is a fatal error in the underlying system, like an invalid memory access. - If the `value` argument is `False` then the board will automatically reset if + If the *value* argument is ``False`` then the board will automatically reset if there is a hard fault. - If `value` is `True` then, when the board has a hard fault, it will print the + If *value* is ``True`` then, when the board has a hard fault, it will print the registers and the stack trace, and then cycle the LEDs indefinitely. The default value is disabled, i.e. to automatically reset. diff --git a/docs/library/sys.rst b/docs/library/sys.rst index 1d7579754f..0bec35cc90 100644 --- a/docs/library/sys.rst +++ b/docs/library/sys.rst @@ -4,19 +4,21 @@ .. module:: sys :synopsis: system specific functions +|see_cpython_module| :mod:`python:sys`. + Functions --------- .. function:: exit(retval=0) Terminate current program with a given exit code. Underlyingly, this - function raise as ``SystemExit`` exception. If an argument is given, its - value given as an argument to ``SystemExit``. + function raise as `SystemExit` exception. If an argument is given, its + value given as an argument to `SystemExit`. .. function:: print_exception(exc, file=sys.stdout) - Print exception with a traceback to a file-like object `file` (or - ``sys.stdout`` by default). + Print exception with a traceback to a file-like object *file* (or + `sys.stdout` by default). .. admonition:: Difference to CPython :class: attention @@ -24,7 +26,7 @@ Functions This is simplified version of a function which appears in the ``traceback`` module in CPython. Unlike ``traceback.print_exception()``, this function takes just exception value instead of exception type, - exception value, and traceback object; `file` argument should be + exception value, and traceback object; *file* argument should be positional; further arguments are not supported. CPython-compatible ``traceback`` module can be found in micropython-lib. @@ -37,15 +39,15 @@ Constants .. data:: byteorder - The byte order of the system ("little" or "big"). + The byte order of the system (``"little"`` or ``"big"``). .. data:: implementation Object with information about the current Python implementation. For MicroPython, it has following attributes: - * `name` - string "micropython" - * `version` - tuple (major, minor, micro), e.g. (1, 7, 0) + * *name* - string "micropython" + * *version* - tuple (major, minor, micro), e.g. (1, 7, 0) This object is the recommended way to distinguish MicroPython from other Python implementations (note that it still may not exist in the very @@ -95,10 +97,10 @@ Constants The platform that MicroPython is running on. For OS/RTOS ports, this is usually an identifier of the OS, e.g. ``"linux"``. For baremetal ports it - is an identifier of a board, e.g. "pyboard" for the original MicroPython + is an identifier of a board, e.g. ``"pyboard"`` for the original MicroPython reference board. It thus can be used to distinguish one board from another. If you need to check whether your program runs on MicroPython (vs other - Python implementation), use ``sys.implementation`` instead. + Python implementation), use `sys.implementation` instead. .. data:: stderr diff --git a/docs/library/ubinascii.rst b/docs/library/ubinascii.rst index 4931f90482..0664d5b09d 100644 --- a/docs/library/ubinascii.rst +++ b/docs/library/ubinascii.rst @@ -4,6 +4,8 @@ .. module:: ubinascii :synopsis: binary/ASCII conversions +|see_cpython_module| :mod:`python:binascii`. + This module implements conversions between binary data and various encodings of it in ASCII form (in both directions). @@ -17,7 +19,7 @@ Functions .. admonition:: Difference to CPython :class: attention - If additional argument, `sep` is supplied, it is used as a separator + If additional argument, *sep* is supplied, it is used as a separator between hexadecimal values. .. function:: unhexlify(data) diff --git a/docs/library/ucollections.rst b/docs/library/ucollections.rst index 4e9de9ac67..96de67acc4 100644 --- a/docs/library/ucollections.rst +++ b/docs/library/ucollections.rst @@ -4,6 +4,8 @@ .. module:: ucollections :synopsis: collection and container types +|see_cpython_module| :mod:`python:collections`. + This module implements advanced collection and container types to hold/accumulate various objects. diff --git a/docs/library/uerrno.rst b/docs/library/uerrno.rst new file mode 100644 index 0000000000..0cdcc84487 --- /dev/null +++ b/docs/library/uerrno.rst @@ -0,0 +1,34 @@ +:mod:`uerrno` -- system error codes +=================================== + +.. module:: uerrno + :synopsis: system error codes + +|see_cpython_module| :mod:`python:errno`. + +This module provides access to symbolic error codes for `OSError` exception. +A particular inventory of codes depends on `MicroPython port`. + +Constants +--------- + +.. data:: EEXIST, EAGAIN, etc. + + Error codes, based on ANSI C/POSIX standard. All error codes start with + "E". As mentioned above, inventory of the codes depends on + `MicroPython port`. Errors are usually accessible as ``exc.args[0]`` + where `exc` is an instance of `OSError`. Usage example:: + + try: + uos.mkdir("my_dir") + except OSError as exc: + if exc.args[0] == uerrno.EEXIST: + print("Directory already exists") + +.. data:: errorcode + + Dictionary mapping numeric error codes to strings with symbolic error + code (see above):: + + >>> print(uerrno.errorcode[uerrno.EEXIST]) + EEXIST diff --git a/docs/library/uhashlib.rst b/docs/library/uhashlib.rst index 6b9a764ba8..50ed658cc1 100644 --- a/docs/library/uhashlib.rst +++ b/docs/library/uhashlib.rst @@ -4,6 +4,8 @@ .. module:: uhashlib :synopsis: hashing algorithms +|see_cpython_module| :mod:`python:hashlib`. + This module implements binary data hashing algorithms. The exact inventory of available algorithms depends on a board. Among the algorithms which may be implemented: diff --git a/docs/library/uheapq.rst b/docs/library/uheapq.rst index c17dac0675..f822f1e7f3 100644 --- a/docs/library/uheapq.rst +++ b/docs/library/uheapq.rst @@ -4,6 +4,8 @@ .. module:: uheapq :synopsis: heap queue algorithm +|see_cpython_module| :mod:`python:heapq`. + This module implements the heap queue algorithm. A heap queue is simply a list that has its elements stored in a certain way. diff --git a/docs/library/uio.rst b/docs/library/uio.rst index 1239c6394e..7042a9e376 100644 --- a/docs/library/uio.rst +++ b/docs/library/uio.rst @@ -4,6 +4,8 @@ .. module:: uio :synopsis: input/output streams +|see_cpython_module| :mod:`python:io`. + This module contains additional types of stream (file-like) objects and helper functions. diff --git a/docs/library/ujson.rst b/docs/library/ujson.rst index 724bc90ee1..0932d0ab55 100644 --- a/docs/library/ujson.rst +++ b/docs/library/ujson.rst @@ -4,6 +4,8 @@ .. module:: ujson :synopsis: JSON encoding and decoding +|see_cpython_module| :mod:`python:json`. + This modules allows to convert between Python objects and the JSON data format. diff --git a/docs/library/uos.rst b/docs/library/uos.rst index 3d0aa46c70..7c52c1eead 100644 --- a/docs/library/uos.rst +++ b/docs/library/uos.rst @@ -4,6 +4,8 @@ .. module:: uos :synopsis: basic "operating system" services +|see_cpython_module| :mod:`python:os`. + The ``uos`` module contains functions for filesystem access and ``urandom`` function. @@ -22,15 +24,15 @@ Functions This function returns an iterator which then yields 3-tuples corresponding to the entries in the directory that it is listing. With no argument it lists the - current directory, otherwise it lists the directory given by `dir`. + current directory, otherwise it lists the directory given by *dir*. - The 3-tuples have the form `(name, type, inode)`: + The 3-tuples have the form *(name, type, inode)*: - - `name` is a string (or bytes if `dir` is a bytes object) and is the name of + - *name* is a string (or bytes if *dir* is a bytes object) and is the name of the entry; - - `type` is an integer that specifies the type of the entry, with 0x4000 for + - *type* is an integer that specifies the type of the entry, with 0x4000 for directories and 0x8000 for regular files; - - `inode` is an integer corresponding to the inode of the file, and may be 0 + - *inode* is an integer corresponding to the inode of the file, and may be 0 for filesystems that don't have such a notion. .. function:: listdir([dir]) @@ -90,5 +92,5 @@ Functions .. function:: dupterm(stream_object) Duplicate or switch MicroPython terminal (the REPL) on the passed stream-like - object. The given object must implement the `.readinto()` and `.write()` + object. The given object must implement the ``readinto()`` and ``write()`` methods. If ``None`` is passed, previously set redirection is cancelled. diff --git a/docs/library/ure.rst b/docs/library/ure.rst index ee360bcc47..67f4f54a1d 100644 --- a/docs/library/ure.rst +++ b/docs/library/ure.rst @@ -1,9 +1,11 @@ -:mod:`ure` -- regular expressions -================================= +:mod:`ure` -- simple regular expressions +======================================== .. module:: ure :synopsis: regular expressions +|see_cpython_module| :mod:`python:re`. + This module implements regular expression operations. Regular expression syntax supported is a subset of CPython ``re`` module (and actually is a subset of POSIX extended regular expressions). @@ -32,6 +34,10 @@ Supported operators are: ``'+?'`` +``'()'`` + Grouping. Each group is capturing (a substring it captures can be accessed + with `match.group()` method). + Counted repetitions (``{m,n}``), more advanced assertions, named groups, etc. are not supported. @@ -39,18 +45,18 @@ etc. are not supported. Functions --------- -.. function:: compile(regex) +.. function:: compile(regex_str) - Compile regular expression, return ``regex`` object. + Compile regular expression, return `regex ` object. -.. function:: match(regex, string) +.. function:: match(regex_str, string) - Match ``regex`` against ``string``. Match always happens from starting - position in a string. + Compile *regex_str* and match against *string*. Match always happens + from starting position in a string. -.. function:: search(regex, string) +.. function:: search(regex_str, string) - Search ``regex`` in a ``string``. Unlike ``match``, this will search + Compile *regex_str* and search it in a *string*. Unlike `match`, this will search string for first position which matches regex (which still may be 0 if regex is anchored). @@ -59,24 +65,33 @@ Functions Flag value, display debug information about compiled expression. +.. _regex: + Regex objects ------------- Compiled regular expression. Instances of this class are created using -``ure.compile()``. +`ure.compile()`. .. method:: regex.match(string) + regex.search(string) -.. method:: regex.search(string) + Similar to the module-level functions :meth:`match` and :meth:`search`. + Using methods is (much) more efficient if the same regex is applied to + multiple strings. .. method:: regex.split(string, max_split=-1) + Split a *string* using regex. If *max_split* is given, it specifies + maximum number of splits to perform. Returns list of strings (there + may be up to *max_split+1* elements if it's specified). Match objects ------------- -Match objects as returned by ``match()`` and ``search()`` methods. +Match objects as returned by `match()` and `search()` methods. .. method:: match.group([index]) - Only numeric groups are supported. + Return matching (sub)string. *index* is 0 for entire match, + 1 and above for each capturing group. Only numeric groups are supported. diff --git a/docs/library/select.rst b/docs/library/uselect.rst similarity index 52% rename from docs/library/select.rst rename to docs/library/uselect.rst index 8dcd4080f1..e330207dbd 100644 --- a/docs/library/select.rst +++ b/docs/library/uselect.rst @@ -1,18 +1,13 @@ -:mod:`select` -- wait for events on a set of streams +:mod:`uselect` -- wait for events on a set of streams ======================================================================== -.. module:: select +.. module:: uselect :synopsis: wait for events on a set of streams -This module provides functions to wait for events on streams (select streams -which are ready for operations). +|see_cpython_module| :mod:`python:select`. -Pyboard specifics ------------------ - -Polling is an efficient way of waiting for read/write activity on multiple -objects. Current objects that support polling are: :class:`pyb.UART`, -:class:`pyb.USB_VCP`. +This module provides functions to efficiently wait for events on multiple +streams (select streams which are ready for operations). Functions --------- @@ -25,8 +20,8 @@ Functions Wait for activity on a set of objects. - This function is provided for compatibility and is not efficient. Usage - of :class:`Poll` is recommended instead. + This function is provided by some MicroPython ports for compatibility + and is not efficient. Usage of :class:`Poll` is recommended instead. .. _class: Poll @@ -38,30 +33,46 @@ Methods .. method:: poll.register(obj[, eventmask]) - Register ``obj`` for polling. ``eventmask`` is logical OR of: + Register *obj* for polling. *eventmask* is logical OR of: * ``select.POLLIN`` - data available for reading * ``select.POLLOUT`` - more data can be written * ``select.POLLERR`` - error occurred * ``select.POLLHUP`` - end of stream/connection termination detected - ``eventmask`` defaults to ``select.POLLIN | select.POLLOUT``. + *eventmask* defaults to ``select.POLLIN | select.POLLOUT``. .. method:: poll.unregister(obj) - Unregister ``obj`` from polling. + Unregister *obj* from polling. .. method:: poll.modify(obj, eventmask) - Modify the ``eventmask`` for ``obj``. + Modify the *eventmask* for *obj*. .. method:: poll.poll([timeout]) Wait for at least one of the registered objects to become ready. Returns list of (``obj``, ``event``, ...) tuples, ``event`` element specifies - which events happened with a stream and is a combination of `select.POLL*` + which events happened with a stream and is a combination of ``select.POLL*`` constants described above. There may be other elements in tuple, depending on a platform and version, so don't assume that its size is 2. In case of timeout, an empty list is returned. Timeout is in milliseconds. + + .. admonition:: Difference to CPython + :class: attention + + Tuples returned may contain more than 2 elements as described above. + +.. method:: poll.ipoll([timeout]) + + Like :meth:`poll.poll`, but instead returns an iterator which yields + callee-owned tuples. This function provides efficient, allocation-free + way to poll on streams. + + .. admonition:: Difference to CPython + :class: attention + + This function is a MicroPython extension. diff --git a/docs/library/usocket.rst b/docs/library/usocket.rst index 71deaebc41..70d4f49fc2 100644 --- a/docs/library/usocket.rst +++ b/docs/library/usocket.rst @@ -5,23 +5,22 @@ .. module:: usocket :synopsis: socket module -This module provides access to the BSD socket interface. +|see_cpython_module| :mod:`python:socket`. -See the corresponding `CPython module `_ -for comparison. +This module provides access to the BSD socket interface. .. admonition:: Difference to CPython :class: attention CPython used to have a ``socket.error`` exception which is now deprecated, - and is an alias of OSError. In MicroPython, use OSError directly. + and is an alias of `OSError`. In MicroPython, use `OSError` directly. .. admonition:: Difference to CPython :class: attention For efficiency and consistency, socket objects in MicroPython implement a stream (file-like) interface directly. In CPython, you need to convert a socket to - a file-like object using ``makefile()`` method. This method is still supported + a file-like object using `makefile()` method. This method is still supported by MicroPython (but is a no-op), so where compatibility with CPython matters, be sure to use it. @@ -29,19 +28,19 @@ Socket address format(s) ------------------------ The functions below which expect a network address, accept it in the format of -`(ipv4_address, port)`, where `ipv4_address` is a string with dot-notation numeric +*(ipv4_address, port)*, where *ipv4_address* is a string with dot-notation numeric IPv4 address, e.g. ``"8.8.8.8"``, and port is integer port number in the range -1-65535. Note the domain names are not accepted as `ipv4_address`, they should be -resolved first using ``socket.getaddrinfo()``. +1-65535. Note the domain names are not accepted as *ipv4_address*, they should be +resolved first using `usocket.getaddrinfo()`. Functions --------- -.. function:: socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP) +.. function:: socket(af=AF_INET, type=SOCK_STREAM, proto=IPPROTO_TCP) Create a new socket using the given address family, socket type and protocol number. -.. function:: socket.getaddrinfo(host, port) +.. function:: getaddrinfo(host, port) Translate the host/port argument into a sequence of 5-tuples that contain all the necessary arguments for creating a socket connected to that service. The list of @@ -57,11 +56,11 @@ Functions .. admonition:: Difference to CPython :class: attention - CPython raises a ``socket.gaierror`` exception (OSError subclass) in case + CPython raises a ``socket.gaierror`` exception (`OSError` subclass) in case of error in this function. MicroPython doesn't have ``socket.gaierror`` - and raises OSError directly. Note that error numbers of ``getaddrinfo()`` + and raises OSError directly. Note that error numbers of `getaddrinfo()` form a separate namespace and may not match error numbers from - ``uerrno`` module. To distinguish ``getaddrinfo()`` errors, they are + `uerrno` module. To distinguish `getaddrinfo()` errors, they are represented by negative numbers, whereas standard system errors are positive numbers (error numbers are accessible using ``e.args[0]`` property from an exception object). The use of negative values is a provisional @@ -70,32 +69,34 @@ Functions Constants --------- -.. data:: socket.AF_INET - socket.AF_INET6 +.. data:: AF_INET + AF_INET6 Address family types. Availability depends on a particular board. -.. data:: socket.SOCK_STREAM - socket.SOCK_DGRAM +.. data:: SOCK_STREAM + SOCK_DGRAM Socket types. -.. data:: socket.IPPROTO_UDP - socket.IPPROTO_TCP +.. data:: IPPROTO_UDP + IPPROTO_TCP IP protocol numbers. -.. data:: socket.SOL_* +.. data:: usocket.SOL_* - Socket option levels (an argument to ``setsockopt()``). The exact inventory depends on a board. + Socket option levels (an argument to `setsockopt()`). The exact + inventory depends on a MicroPython port. -.. data:: socket.SO_* +.. data:: usocket.SO_* - Socket options (an argument to ``setsockopt()``). The exact inventory depends on a board. + Socket options (an argument to `setsockopt()`). The exact + inventory depends on a MicroPython port. Constants specific to WiPy: -.. data:: socket.IPPROTO_SEC +.. data:: IPPROTO_SEC Special protocol value to create SSL-compatible socket. @@ -105,21 +106,22 @@ class socket Methods ------- -.. method:: socket.close +.. method:: socket.close() - Mark the socket closed. Once that happens, all future operations on the socket - object will fail. The remote end will receive no more data (after queued data is flushed). + Mark the socket closed and release all resources. Once that happens, all future operations + on the socket object will fail. The remote end will receive EOF indication if + supported by protocol. Sockets are automatically closed when they are garbage-collected, but it is recommended - to close() them explicitly, or to use a with statement around them. + to `close()` them explicitly as soon you finished working with them. .. method:: socket.bind(address) - Bind the socket to address. The socket must not already be bound. + Bind the socket to *address*. The socket must not already be bound. .. method:: socket.listen([backlog]) - Enable a server to accept connections. If backlog is specified, it must be at least 0 + Enable a server to accept connections. If *backlog* is specified, it must be at least 0 (if it's lower, it will be set to 0); and specifies the number of unaccepted connections that the system will allow before refusing new connections. If not specified, a default reasonable value is chosen. @@ -133,7 +135,7 @@ Methods .. method:: socket.connect(address) - Connect to a remote socket at address. + Connect to a remote socket at *address*. .. method:: socket.send(bytes) @@ -144,11 +146,11 @@ Methods .. method:: socket.sendall(bytes) Send all data to the socket. The socket must be connected to a remote socket. - Unlike ``send()``, this method will try to send all of data, by sending data + Unlike `send()`, this method will try to send all of data, by sending data chunk by chunk consecutively. The behavior of this method on non-blocking sockets is undefined. Due to this, - on MicroPython, it's recommended to use ``write()`` method instead, which + on MicroPython, it's recommended to use `write()` method instead, which has the same "no short writes" policy for blocking sockets, and will return number of bytes sent on non-blocking sockets. @@ -160,25 +162,25 @@ Methods .. method:: socket.sendto(bytes, address) Send data to the socket. The socket should not be connected to a remote socket, since the - destination socket is specified by `address`. + destination socket is specified by *address*. .. method:: socket.recvfrom(bufsize) - Receive data from the socket. The return value is a pair (bytes, address) where bytes is a - bytes object representing the data received and address is the address of the socket sending + Receive data from the socket. The return value is a pair *(bytes, address)* where *bytes* is a + bytes object representing the data received and *address* is the address of the socket sending the data. .. method:: socket.setsockopt(level, optname, value) Set the value of the given socket option. The needed symbolic constants are defined in the - socket module (SO_* etc.). The value can be an integer or a bytes-like object representing + socket module (SO_* etc.). The *value* can be an integer or a bytes-like object representing a buffer. .. method:: socket.settimeout(value) Set a timeout on blocking socket operations. The value argument can be a nonnegative floating point number expressing seconds, or None. If a non-zero value is given, subsequent socket operations - will raise an ``OSError`` exception if the timeout period value has elapsed before the operation has + will raise an `OSError` exception if the timeout period value has elapsed before the operation has completed. If zero is given, the socket is put in non-blocking mode. If None is given, the socket is put in blocking mode. @@ -186,7 +188,7 @@ Methods :class: attention CPython raises a ``socket.timeout`` exception in case of timeout, - which is an ``OSError`` subclass. MicroPython raises an OSError directly + which is an `OSError` subclass. MicroPython raises an OSError directly instead. If you use ``except OSError:`` to catch the exception, your code will work both in MicroPython and CPython. @@ -195,7 +197,7 @@ Methods Set blocking or non-blocking mode of the socket: if flag is false, the socket is set to non-blocking, else to blocking mode. - This method is a shorthand for certain ``settimeout()`` calls: + This method is a shorthand for certain `settimeout()` calls: * ``sock.setblocking(True)`` is equivalent to ``sock.settimeout(None)`` * ``sock.setblocking(False)`` is equivalent to ``sock.settimeout(0)`` @@ -204,12 +206,12 @@ Methods Return a file object associated with the socket. The exact returned type depends on the arguments given to makefile(). The support is limited to binary modes only ('rb', 'wb', and 'rwb'). - CPython's arguments: ``encoding``, ``errors`` and ``newline`` are not supported. + CPython's arguments: *encoding*, *errors* and *newline* are not supported. .. admonition:: Difference to CPython :class: attention - As MicroPython doesn't support buffered streams, values of ``buffering`` + As MicroPython doesn't support buffered streams, values of *buffering* parameter is ignored and treated as if it was 0 (unbuffered). .. admonition:: Difference to CPython @@ -220,19 +222,19 @@ Methods .. method:: socket.read([size]) - Read up to size bytes from the socket. Return a bytes object. If ``size`` is not given, it - reads all data available from the socket until ``EOF``; as such the method will not return until + Read up to size bytes from the socket. Return a bytes object. If *size* is not given, it + reads all data available from the socket until EOF; as such the method will not return until the socket is closed. This function tries to read as much data as requested (no "short reads"). This may be not possible with non-blocking socket though, and then less data will be returned. .. method:: socket.readinto(buf[, nbytes]) - Read bytes into the ``buf``. If ``nbytes`` is specified then read at most - that many bytes. Otherwise, read at most ``len(buf)`` bytes. Just as - ``read()``, this method follows "no short reads" policy. + Read bytes into the *buf*. If *nbytes* is specified then read at most + that many bytes. Otherwise, read at most *len(buf)* bytes. Just as + `read()`, this method follows "no short reads" policy. - Return value: number of bytes read and stored into ``buf``. + Return value: number of bytes read and stored into *buf*. .. method:: socket.readline() @@ -245,6 +247,6 @@ Methods Write the buffer of bytes to the socket. This function will try to write all data to a socket (no "short writes"). This may be not possible with a non-blocking socket though, and returned value will be less than - the length of ``buf``. + the length of *buf*. Return value: number of bytes written. diff --git a/docs/library/ussl.rst b/docs/library/ussl.rst index 36f6d65a4a..c71b283ccb 100644 --- a/docs/library/ussl.rst +++ b/docs/library/ussl.rst @@ -4,6 +4,8 @@ .. module:: ussl :synopsis: TLS/SSL wrapper for socket objects +|see_cpython_module| :mod:`python:ssl`. + This module provides access to Transport Layer Security (previously and widely known as “Secure Sockets Layer”) encryption and peer authentication facilities for network sockets, both client-side and server-side. @@ -13,7 +15,7 @@ Functions .. function:: ssl.wrap_socket(sock, server_side=False, keyfile=None, certfile=None, cert_reqs=CERT_NONE, ca_certs=None) - Takes a stream `sock` (usually usocket.socket instance of ``SOCK_STREAM`` type), + Takes a stream *sock* (usually usocket.socket instance of ``SOCK_STREAM`` type), and returns an instance of ssl.SSLSocket, which wraps the underlying stream in an SSL context. Returned object has the usual stream interface methods like `read()`, `write()`, etc. In MicroPython, the returned object does not expose @@ -43,4 +45,4 @@ Constants ssl.CERT_OPTIONAL ssl.CERT_REQUIRED - Supported values for `cert_reqs` parameter. + Supported values for *cert_reqs* parameter. diff --git a/docs/library/ustruct.rst b/docs/library/ustruct.rst index 74e42af07a..81915d0a8d 100644 --- a/docs/library/ustruct.rst +++ b/docs/library/ustruct.rst @@ -4,8 +4,7 @@ .. module:: ustruct :synopsis: pack and unpack primitive data types -See `Python struct `_ for more -information. +|see_cpython_module| :mod:`python:struct`. Supported size/byte order prefixes: ``@``, ``<``, ``>``, ``!``. @@ -18,26 +17,26 @@ Functions .. function:: calcsize(fmt) - Return the number of bytes needed to store the given `fmt`. + Return the number of bytes needed to store the given *fmt*. .. function:: pack(fmt, v1, v2, ...) - Pack the values `v1`, `v2`, ... according to the format string `fmt`. + Pack the values *v1*, *v2*, ... according to the format string *fmt*. The return value is a bytes object encoding the values. .. function:: pack_into(fmt, buffer, offset, v1, v2, ...) - Pack the values `v1`, `v2`, ... according to the format string `fmt` - into a `buffer` starting at `offset`. `offset` may be negative to count - from the end of `buffer`. + Pack the values *v1*, *v2*, ... according to the format string *fmt* + into a *buffer* starting at *offset*. *offset* may be negative to count + from the end of *buffer*. .. function:: unpack(fmt, data) - Unpack from the `data` according to the format string `fmt`. + Unpack from the *data* according to the format string *fmt*. The return value is a tuple of the unpacked values. .. function:: unpack_from(fmt, data, offset=0) - Unpack from the `data` starting at `offset` according to the format string - `fmt`. `offset` may be negative to count from the end of `buffer`. The return + Unpack from the *data* starting at *offset* according to the format string + *fmt*. *offset* may be negative to count from the end of *buffer*. The return value is a tuple of the unpacked values. diff --git a/docs/library/utime.rst b/docs/library/utime.rst index f3a067cdef..a39f5ee733 100644 --- a/docs/library/utime.rst +++ b/docs/library/utime.rst @@ -4,6 +4,8 @@ .. module:: utime :synopsis: time related functions +|see_cpython_module| :mod:`python:time`. + The ``utime`` module provides functions for getting the current time and date, measuring time intervals, and for delays. @@ -57,10 +59,10 @@ Functions .. function:: sleep(seconds) - Sleep for the given number of seconds. Some boards may accept `seconds` as a + Sleep for the given number of seconds. Some boards may accept *seconds* as a floating-point number to sleep for a fractional number of seconds. Note that other boards may not accept a floating-point argument, for compatibility with - them use ``sleep_ms()`` and ``sleep_us()`` functions. + them use `sleep_ms()` and `sleep_us()` functions. .. function:: sleep_ms(ms) @@ -73,30 +75,32 @@ Functions .. function:: ticks_ms() Returns an increasing millisecond counter with an arbitrary reference point, that - wraps around after some value. This value is not explicitly exposed, but we will - refer to it as ``TICKS_MAX`` to simplify discussion. Period of the values is - ``TICKS_PERIOD = TICKS_MAX + 1``. ``TICKS_PERIOD`` is guaranteed to be a power of + wraps around after some value. + + The wrap-around value is not explicitly exposed, but we will + refer to it as *TICKS_MAX* to simplify discussion. Period of the values is + *TICKS_PERIOD = TICKS_MAX + 1*. *TICKS_PERIOD* is guaranteed to be a power of two, but otherwise may differ from port to port. The same period value is used - for all of ``ticks_ms()``, ``ticks_us()``, ``ticks_cpu()`` functions (for - simplicity). Thus, these functions will return a value in range [``0`` .. - ``TICKS_MAX``], inclusive, total ``TICKS_PERIOD`` values. Note that only + for all of `ticks_ms()`, `ticks_us()`, `ticks_cpu()` functions (for + simplicity). Thus, these functions will return a value in range [*0* .. + *TICKS_MAX*], inclusive, total *TICKS_PERIOD* values. Note that only non-negative values are used. For the most part, you should treat values returned by these functions as opaque. The only operations available for them are - ``ticks_diff()`` and ``ticks_add()`` functions described below. + `ticks_diff()` and `ticks_add()` functions described below. Note: Performing standard mathematical operations (+, -) or relational operators (<, <=, >, >=) directly on these value will lead to invalid result. Performing mathematical operations and then passing their results - as arguments to ``ticks_diff()`` or ``ticks_add()`` will also lead to + as arguments to `ticks_diff()` or `ticks_add()` will also lead to invalid results from the latter functions. .. function:: ticks_us() - Just like ``ticks_ms()`` above, but in microseconds. + Just like `ticks_ms()` above, but in microseconds. .. function:: ticks_cpu() - Similar to ``ticks_ms()`` and ``ticks_us()``, but with the highest possible resolution + Similar to `ticks_ms()` and `ticks_us()`, but with the highest possible resolution in the system. This is usually CPU clocks, and that's why the function is named that way. But it doesn't have to be a CPU clock, some other timing source available in a system (e.g. high-resolution timer) can be used instead. The exact timing unit @@ -111,13 +115,13 @@ Functions .. function:: ticks_add(ticks, delta) Offset ticks value by a given number, which can be either positive or negative. - Given a ``ticks`` value, this function allows to calculate ticks value ``delta`` + Given a *ticks* value, this function allows to calculate ticks value *delta* ticks before or after it, following modular-arithmetic definition of tick values - (see ``ticks_ms()`` above). ``ticks`` parameter must be a direct result of call - to ``ticks_ms()``, ``ticks_us()``, or ``ticks_cpu()`` functions (or from previous - call to ``ticks_add()``). However, ``delta`` can be an arbitrary integer number - or numeric expression. ``ticks_add()`` is useful for calculating deadlines for - events/tasks. (Note: you must use ``ticks_diff()`` function to work with + (see `ticks_ms()` above). *ticks* parameter must be a direct result of call + to `ticks_ms()`, `ticks_us()`, or `ticks_cpu()` functions (or from previous + call to `ticks_add()`). However, *delta* can be an arbitrary integer number + or numeric expression. `ticks_add()` is useful for calculating deadlines for + events/tasks. (Note: you must use `ticks_diff()` function to work with deadlines.) Examples:: @@ -136,23 +140,25 @@ Functions .. function:: ticks_diff(ticks1, ticks2) - Measure ticks difference between values returned from ``ticks_ms()``, ``ticks_us()``, - or ``ticks_cpu()`` functions. The argument order is the same as for subtraction + Measure ticks difference between values returned from `ticks_ms()`, `ticks_us()`, + or `ticks_cpu()` functions, as a signed value which may wrap around. + + The argument order is the same as for subtraction operator, ``ticks_diff(ticks1, ticks2)`` has the same meaning as ``ticks1 - ticks2``. - However, values returned by ``ticks_ms()``, etc. functions may wrap around, so + However, values returned by `ticks_ms()`, etc. functions may wrap around, so directly using subtraction on them will produce incorrect result. That is why - ``ticks_diff()`` is needed, it implements modular (or more specifically, ring) + `ticks_diff()` is needed, it implements modular (or more specifically, ring) arithmetics to produce correct result even for wrap-around values (as long as they not too distant inbetween, see below). The function returns **signed** value in the range - [``-TICKS_PERIOD/2`` .. ``TICKS_PERIOD/2-1``] (that's a typical range definition for + [*-TICKS_PERIOD/2* .. *TICKS_PERIOD/2-1*] (that's a typical range definition for two's-complement signed binary integers). If the result is negative, it means that - ``ticks1`` occurred earlier in time than ``ticks2``. Otherwise, it means that - ``ticks1`` occurred after ``ticks2``. This holds ``only`` if ``ticks1`` and ``ticks2`` - are apart from each other for no more than ``TICKS_PERIOD/2-1`` ticks. If that does + *ticks1* occurred earlier in time than *ticks2*. Otherwise, it means that + *ticks1* occurred after *ticks2*. This holds **only** if *ticks1* and *ticks2* + are apart from each other for no more than *TICKS_PERIOD/2-1* ticks. If that does not hold, incorrect result will be returned. Specifically, if two tick values are - apart for ``TICKS_PERIOD/2-1`` ticks, that value will be returned by the function. - However, if ``TICKS_PERIOD/2`` of real-time ticks has passed between them, the - function will return ``-TICKS_PERIOD/2`` instead, i.e. result value will wrap around + apart for *TICKS_PERIOD/2-1* ticks, that value will be returned by the function. + However, if *TICKS_PERIOD/2* of real-time ticks has passed between them, the + function will return *-TICKS_PERIOD/2* instead, i.e. result value will wrap around to the negative range of possible values. Informal rationale of the constraints above: Suppose you are locked in a room with no @@ -164,10 +170,10 @@ Functions behavior: don't let your application run any single task for too long. Run tasks in steps, and do time-keeping inbetween. - ``ticks_diff()`` is designed to accommodate various usage patterns, among them: + `ticks_diff()` is designed to accommodate various usage patterns, among them: - Polling with timeout. In this case, the order of events is known, and you will deal - only with positive results of ``ticks_diff()``:: + * Polling with timeout. In this case, the order of events is known, and you will deal + only with positive results of `ticks_diff()`:: # Wait for GPIO pin to be asserted, but at most 500us start = time.ticks_us() @@ -175,8 +181,8 @@ Functions if time.ticks_diff(time.ticks_us(), start) > 500: raise TimeoutError - Scheduling events. In this case, ``ticks_diff()`` result may be negative - if an event is overdue:: + * Scheduling events. In this case, `ticks_diff()` result may be negative + if an event is overdue:: # This code snippet is not optimized now = time.ticks_ms() @@ -192,8 +198,8 @@ Functions print("Oops, running late, tell task to run faster!") task.run(run_faster=true) - Note: Do not pass ``time()`` values to ``ticks_diff()``, you should use - normal mathematical operations on them. But note that ``time()`` may (and will) + Note: Do not pass `time()` values to `ticks_diff()`, you should use + normal mathematical operations on them. But note that `time()` may (and will) also overflow. This is known as https://en.wikipedia.org/wiki/Year_2038_problem . @@ -205,8 +211,8 @@ Functions embedded boards without a battery-backed RTC, usually since power up or reset). If you want to develop portable MicroPython application, you should not rely on this function to provide higher than second precision. If you need higher precision, use - ``ticks_ms()`` and ``ticks_us()`` functions, if you need calendar time, - ``localtime()`` without an argument is a better choice. + `ticks_ms()` and `ticks_us()` functions, if you need calendar time, + `localtime()` without an argument is a better choice. .. admonition:: Difference to CPython :class: attention diff --git a/docs/library/uzlib.rst b/docs/library/uzlib.rst index 8775ec3e07..fb1746fe8e 100644 --- a/docs/library/uzlib.rst +++ b/docs/library/uzlib.rst @@ -4,13 +4,35 @@ .. module:: uzlib :synopsis: zlib decompression -This modules allows to decompress binary data compressed with DEFLATE -algorithm (commonly used in zlib library and gzip archiver). Compression +|see_cpython_module| :mod:`python:zlib`. + +This module allows to decompress binary data compressed with +`DEFLATE algorithm `_ +(commonly used in zlib library and gzip archiver). Compression is not yet implemented. Functions --------- -.. function:: decompress(data) +.. function:: decompress(data, wbits=0, bufsize=0) - Return decompressed data as bytes. + Return decompressed *data* as bytes. *wbits* is DEFLATE dictionary window + size used during compression (8-15, the dictionary size is power of 2 of + that value). Additionally, if value is positive, *data* is assumed to be + zlib stream (with zlib header). Otherwise, if it's negative, it's assumed + to be raw DEFLATE stream. *bufsize* parameter is for compatibility with + CPython and is ignored. + +.. class:: DecompIO(stream, wbits=0) + + Create a stream wrapper which allows transparent decompression of + compressed data in another *stream*. This allows to process compressed + streams with data larger than available heap size. In addition to + values described in :func:`decompress`, *wbits* may take values + 24..31 (16 + 8..15), meaning that input stream has gzip header. + + .. admonition:: Difference to CPython + :class: attention + + This class is MicroPython extension. It's included on provisional + basis and may be changed considerably or removed in later versions. diff --git a/docs/license.rst b/docs/license.rst index bbc5016ed7..73caa90351 100644 --- a/docs/license.rst +++ b/docs/license.rst @@ -3,7 +3,7 @@ MicroPython license information The MIT License (MIT) -Copyright (c) 2013-2015 Damien P. George, and others +Copyright (c) 2013-2017 Damien P. George, and others 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/docs/pyboard/general.rst b/docs/pyboard/general.rst index 1d040f6ccc..97e9aabc0b 100644 --- a/docs/pyboard/general.rst +++ b/docs/pyboard/general.rst @@ -1,6 +1,8 @@ General information about the pyboard ===================================== +.. contents:: + Local filesystem and SD card ---------------------------- @@ -67,3 +69,12 @@ There are currently 2 kinds of errors that you might see: 2. If all 4 LEDs cycle on and off slowly, then there was a hard fault. This cannot be recovered from and you need to do a hard reset. +Guide for using the pyboard with Windows +---------------------------------------- + +The following PDF guide gives information about using the pyboard with Windows, +including setting up the serial prompt and downloading new firmware using +DFU programming: +`PDF guide `__. + +.. include:: hardware/index.rst diff --git a/docs/pyboard/hardware/index.rst b/docs/pyboard/hardware/index.rst index bc4726ce2d..91fea24e7a 100644 --- a/docs/pyboard/hardware/index.rst +++ b/docs/pyboard/hardware/index.rst @@ -1,7 +1,7 @@ .. _hardware_index: The pyboard hardware -==================== +-------------------- For the pyboard: @@ -16,14 +16,14 @@ For the official skin modules: * LCD160CRv1.0: see :mod:`lcd160cr` Datasheets for the components on the pyboard -============================================ +-------------------------------------------- * The microcontroller: `STM32F405RGT6 `_ (link to manufacturer's site) * The accelerometer: `Freescale MMA7660 `_ (800kiB PDF) * The LDO voltage regulator: `Microchip MCP1802 `_ (400kiB PDF) Datasheets for other components -=============================== +------------------------------- * The LCD display on the LCD touch-sensor skin: `Newhaven Display NHD-C12832A1Z-FSW-FBW-3V3 `_ (460KiB PDF) * The touch sensor chip on the LCD touch-sensor skin: `Freescale MPR121 `_ (280KiB PDF) diff --git a/docs/pyboard/tutorial/amp_skin.rst b/docs/pyboard/tutorial/amp_skin.rst index 64f139bb7e..697637f9d2 100644 --- a/docs/pyboard/tutorial/amp_skin.rst +++ b/docs/pyboard/tutorial/amp_skin.rst @@ -69,4 +69,30 @@ Then you can do:: >>> f = wave.open('test.wav') >>> dac.write_timed(f.readframes(f.getnframes()), f.getframerate()) -This should play the WAV file. +This should play the WAV file. Note that this will read the whole file into RAM +so it has to be small enough to fit in it. + +To play larger wave files you will have to use the micro-SD card to store it. +Also the file must be read and sent to the DAC in small chunks that will fit +the RAM limit of the microcontroller. Here is an example function that can +play 8-bit wave files with up to 16kHz sampling:: + + import wave + from pyb import DAC + from pyb import delay + dac = DAC(1) + + def play(filename): + f = wave.open(filename, 'r') + total_frames = f.getnframes() + framerate = f.getframerate() + + for position in range(0, total_frames, framerate): + f.setpos(position) + dac.write_timed(f.readframes(framerate), framerate) + delay(1000) + +This function reads one second worth of data and sends it to DAC. It then waits +one second and moves the file cursor to the new position to read the next second +of data in the next iteration of the for-loop. It plays one second of audio at +a time every one second. diff --git a/docs/pyboard/tutorial/index.rst b/docs/pyboard/tutorial/index.rst index 07f136c9b4..1dc155f149 100644 --- a/docs/pyboard/tutorial/index.rst +++ b/docs/pyboard/tutorial/index.rst @@ -1,7 +1,7 @@ .. _tutorial-index: -MicroPython tutorial -==================== +MicroPython tutorial for the pyboard +==================================== This tutorial is intended to get you started with your pyboard. All you need is a pyboard and a micro-USB cable to connect it to diff --git a/docs/pyboard/tutorial/switch.rst b/docs/pyboard/tutorial/switch.rst index 945e89aa05..91683fba45 100644 --- a/docs/pyboard/tutorial/switch.rst +++ b/docs/pyboard/tutorial/switch.rst @@ -15,12 +15,18 @@ the name ``pyb`` does not exist. With the switch object you can get its status:: - >>> sw() + >>> sw.value() False This will print ``False`` if the switch is not held, or ``True`` if it is held. Try holding the USR switch down while running the above command. +There is also a shorthand notation to get the switch status, by "calling" the +switch object:: + + >>> sw() + False + Switch callbacks ---------------- diff --git a/docs/pyboard_contents.rst b/docs/pyboard_contents.rst deleted file mode 100644 index 658dd366f2..0000000000 --- a/docs/pyboard_contents.rst +++ /dev/null @@ -1,14 +0,0 @@ -MicroPython documentation contents -================================== - -.. toctree:: - - pyboard/quickref.rst - pyboard/general.rst - pyboard/tutorial/index.rst - library/index.rst - reference/index.rst - pyboard/hardware/index.rst - genrst/index.rst - license.rst - diff --git a/docs/pyboard_index.rst b/docs/pyboard_index.rst index 4caa4cc883..2255a75607 100644 --- a/docs/pyboard_index.rst +++ b/docs/pyboard_index.rst @@ -7,14 +7,6 @@ MicroPython documentation and references pyboard/general.rst pyboard/tutorial/index.rst library/index.rst - pyboard/hardware/index.rst + reference/index.rst genrst/index.rst license.rst - pyboard_contents.rst - -Indices and tables -================== - -* :ref:`genindex` -* :ref:`modindex` -* :ref:`search` diff --git a/docs/reference/constrained.rst b/docs/reference/constrained.rst index 7c1b6a3eb2..14286aa262 100644 --- a/docs/reference/constrained.rst +++ b/docs/reference/constrained.rst @@ -119,10 +119,10 @@ symbols that have already been defined, e.g. ``1 << BIT``. Where there is a substantial volume of constant data and the platform supports execution from Flash, RAM may be saved as follows. The data should be located in -Python modules and frozen as bytecode. The data must be defined as ``bytes`` -objects. The compiler 'knows' that ``bytes`` objects are immutable and ensures +Python modules and frozen as bytecode. The data must be defined as `bytes` +objects. The compiler 'knows' that `bytes` objects are immutable and ensures that the objects remain in flash memory rather than being copied to RAM. The -``ustruct`` module can assist in converting between ``bytes`` types and other +`ustruct` module can assist in converting between `bytes` types and other Python built-in types. When considering the implications of frozen bytecode, note that in Python @@ -185,7 +185,7 @@ a file it will save RAM if this is done in a piecemeal fashion. Rather than creating a large string object, create a substring and feed it to the stream before dealing with the next. -The best way to create dynamic strings is by means of the string ``format`` +The best way to create dynamic strings is by means of the string `format` method: .. code:: @@ -226,26 +226,26 @@ function ``foo()``: foo(b'\1\2\xff') In the first call a tuple of integers is created in RAM. The second efficiently -creates a ``bytes`` object consuming the minimum amount of RAM. If the module -were frozen as bytecode, the ``bytes`` object would reside in flash. +creates a `bytes` object consuming the minimum amount of RAM. If the module +were frozen as bytecode, the `bytes` object would reside in flash. **Strings Versus Bytes** Python3 introduced Unicode support. This introduced a distinction between a string and an array of bytes. MicroPython ensures that Unicode strings take no additional space so long as all characters in the string are ASCII (i.e. have -a value < 126). If values in the full 8-bit range are required ``bytes`` and -``bytearray`` objects can be used to ensure that no additional space will be -required. Note that most string methods (e.g. ``strip()``) apply also to ``bytes`` +a value < 126). If values in the full 8-bit range are required `bytes` and +`bytearray` objects can be used to ensure that no additional space will be +required. Note that most string methods (e.g. :meth:`str.strip()`) apply also to `bytes` instances so the process of eliminating Unicode can be painless. .. code:: - s = 'the quick brown fox' # A string instance - b = b'the quick brown fox' # a bytes instance + s = 'the quick brown fox' # A string instance + b = b'the quick brown fox' # A bytes instance -Where it is necessary to convert between strings and bytes the string ``encode`` -and the bytes ``decode`` methods can be used. Note that both strings and bytes +Where it is necessary to convert between strings and bytes the :meth:`str.encode` +and the :meth:`bytes.decode` methods can be used. Note that both strings and bytes are immutable. Any operation which takes as input such an object and produces another implies at least one RAM allocation to produce the result. In the second line below a new bytes object is allocated. This would also occur if ``foo`` @@ -258,10 +258,10 @@ were a string. **Runtime compiler execution** -The Python keywords ``eval`` and ``exec`` invoke the compiler at runtime, which -requires significant amounts of RAM. Note that the ``pickle`` library employs -``exec``. It may be more RAM efficient to use the ``json`` library for object -serialisation. +The Python funcitons `eval` and `exec` invoke the compiler at runtime, which +requires significant amounts of RAM. Note that the `pickle` library from +`micropython-lib` employs `exec`. It may be more RAM efficient to use the +`ujson` library for object serialisation. **Storing strings in flash** @@ -300,7 +300,7 @@ from a fixed size pool known as the heap. When the object goes out of scope (in other words becomes inaccessible to code) the redundant object is known as "garbage". A process known as "garbage collection" (GC) reclaims that memory, returning it to the free heap. This process runs automatically, however it can -be invoked directly by issuing ``gc.collect()``. +be invoked directly by issuing `gc.collect()`. The discourse on this is somewhat involved. For a 'quick fix' issue the following periodically: @@ -332,7 +332,7 @@ Reporting ~~~~~~~~~ A number of library functions are available to report on memory allocation and -to control GC. These are to be found in the ``gc`` and ``micropython`` modules. +to control GC. These are to be found in the `gc` and `micropython` modules. The following example may be pasted at the REPL (``ctrl e`` to enter paste mode, ``ctrl d`` to run it). @@ -357,17 +357,17 @@ The following example may be pasted at the REPL (``ctrl e`` to enter paste mode, Methods employed above: -* ``gc.collect()`` Force a garbage collection. See footnote. -* ``micropython.mem_info()`` Print a summary of RAM utilisation. -* ``gc.mem_free()`` Return the free heap size in bytes. -* ``gc.mem_alloc()`` Return the number of bytes currently allocated. +* `gc.collect()` Force a garbage collection. See footnote. +* `micropython.mem_info()` Print a summary of RAM utilisation. +* `gc.mem_free()` Return the free heap size in bytes. +* `gc.mem_alloc()` Return the number of bytes currently allocated. * ``micropython.mem_info(1)`` Print a table of heap utilisation (detailed below). The numbers produced are dependent on the platform, but it can be seen that declaring the function uses a small amount of RAM in the form of bytecode emitted by the compiler (the RAM used by the compiler has been reclaimed). Running the function uses over 10KiB, but on return ``a`` is garbage because it -is out of scope and cannot be referenced. The final ``gc.collect()`` recovers +is out of scope and cannot be referenced. The final `gc.collect()` recovers that memory. The final output produced by ``micropython.mem_info(1)`` will vary in detail but @@ -394,7 +394,7 @@ line of the heap dump represents 0x400 bytes or 1KiB of RAM. Control of Garbage Collection ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -A GC can be demanded at any time by issuing ``gc.collect()``. It is advantageous +A GC can be demanded at any time by issuing `gc.collect()`. It is advantageous to do this at intervals, firstly to pre-empt fragmentation and secondly for performance. A GC can take several milliseconds but is quicker when there is little work to do (about 1ms on the Pyboard). An explicit call can minimise that @@ -417,7 +417,7 @@ occupied. In general modules should instantiate data objects at runtime using constructors or other initialisation functions. The reason is that if this occurs on initialisation the compiler may be starved of RAM when subsequent modules are -imported. If modules do instantiate data on import then ``gc.collect()`` issued +imported. If modules do instantiate data on import then `gc.collect()` issued after the import will ameliorate the problem. String Operations @@ -444,13 +444,13 @@ RAM usage and speed. Where variables are required whose size is neither a byte nor a machine word there are standard libraries which can assist in storing these efficiently and -in performing conversions. See the ``array``, ``ustruct`` and ``uctypes`` +in performing conversions. See the `array`, `ustruct` and `uctypes` modules. Footnote: gc.collect() return value ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -On Unix and Windows platforms the ``gc.collect()`` method returns an integer +On Unix and Windows platforms the `gc.collect()` method returns an integer which signifies the number of distinct memory regions that were reclaimed in the collection (more precisely, the number of heads that were turned into frees). For efficiency reasons bare metal ports do not return this value. diff --git a/docs/reference/glossary.rst b/docs/reference/glossary.rst new file mode 100644 index 0000000000..4099ae9516 --- /dev/null +++ b/docs/reference/glossary.rst @@ -0,0 +1,99 @@ +Glossary +======== + +.. glossary:: + + baremetal + A system without (full-fledged) OS, like an :term:`MCU`. When + running on a baremetal system, MicroPython effectively becomes + its user-facing OS with a command interpreter (REPL). + + board + A PCB board. Oftentimes, the term is used to denote a particular + model of an :term:`MCU` system. Sometimes, it is used to actually + refer to :term:`MicroPython port` to a particular board (and then + may also refer to "boardless" ports like + :term:`Unix port `). + + CPython + CPython is the reference implementation of Python programming + language, and the most well-known one, which most of the people + run. It is however one of many implementations (among which + Jython, IronPython, PyPy, and many more, including MicroPython). + As there is no formal specification of the Python language, only + CPython documentation, it is not always easy to draw a line + between Python the language and CPython its particular + implementation. This however leaves more freedom for other + implementations. For example, MicroPython does a lot of things + differently than CPython, while still aspiring to be a Python + language implementation. + + GPIO + General-purpose input/output. The simplest means to control + electrical signals. With GPIO, user can configure hardware + signal pin to be either input or output, and set or get + its digital signal value (logical "0" or "1"). MicroPython + abstracts GPIO access using :class:`machine.Pin` and :class:`machine.Signal` + classes. + + GPIO port + A group of :term:`GPIO` pins, usually based on hardware + properties of these pins (e.g. controllable by the same + register). + + MCU + Microcontroller. Microcontrollers usually have much less resources + than a full-fledged computing system, but smaller, cheaper and + require much less power. MicroPython is designed to be small and + optimized enough to run on an average modern microcontroller. + + micropython-lib + MicroPython is (usually) distributed as a single executable/binary + file with just few builtin modules. There is no extensive standard + library comparable with :term:`CPython`. Instead, there is a related, but + separate project + `micropython-lib `_ + which provides implementations for many modules from CPython's + standard library. However, large subset of these modules required + POSIX-like environment (Linux, MacOS, Windows may be partially + supported), and thus would work or make sense only with MicroPython + Unix port. Some subset of modules however usable for baremetal ports + too. + + Unlike monolithic :term:`CPython` stdlib, micropython-lib modules + are intended to be installed individually - either using manual + copying or using :term:`upip`. + + MicroPython port + MicroPython supports different :term:`boards `, RTOSes, + and OSes, and can be relatively easily adapted to new systems. + MicroPython with support for a particular system is called a + "port" to that system. + + MicroPython Unix port + Unix port is one of the major :term:`MicroPython ports `. + It is intended to run on POSIX-compatible operating systems, like + Linux, MacOS, FreeBSD, Solaris, etc. It also serves as the basis + of Windows port. The importance of Unix port lies in the fact + that while there are many different :term:`boards `, so + two random users unlikely have the same board, almost all modern + OSes have some level of POSIX compatibility, so Unix port serves + as a kind of "common ground" to which any user can have access. + So, Unix port is used for initial prototyping, different kinds + of testing, development of machine-independent features, etc. + All users of MicroPython, even those which are interested only + in running MicroPython on :term:`MCU` systems, are recommended + to be familiar with Unix (or Windows) port, as it is important + productivity helper and a part of normal MicroPython workflow. + + port + Either :term:`MicroPython port` or :term:`GPIO port`. If not clear + from context, it's recommended to use full specification like one + of the above. + + upip + (Literally, "micro pip"). A package manage for MicroPython, inspired + by :term:`CPython`'s pip, but much smaller and with reduced functionality. + upip runs both on :term:`Unix port ` and on + :term:`baremetal` ports (those which offer filesystem and networking + support). diff --git a/docs/reference/index.rst b/docs/reference/index.rst index 7a85fc5cf3..4d822d6fa6 100644 --- a/docs/reference/index.rst +++ b/docs/reference/index.rst @@ -1,17 +1,25 @@ The MicroPython language ======================== -MicroPython aims to implement the Python 3.4 standard, and most of -the features of MicroPython are identical to those described by the -documentation at -`docs.python.org `_. +MicroPython aims to implement the Python 3.4 standard (with selected +features from later versions) with respect to language syntax, and most +of the features of MicroPython are identical to those described by the +"Language Reference" documentation at +`docs.python.org `_. -Differences to standard Python as well as additional features of -MicroPython are described in the sections here. +The MicroPython standard library is described in the +:ref:`corresponding chapter `. The :ref:`cpython_diffs` +chapter describes differences between MicroPython and CPython (which +mostly concern standard library and types, but also some language-level +features). + +This chapter describes features and peculiarities of MicroPython +implementation and the best practices to use them. .. toctree:: :maxdepth: 1 + glossary.rst repl.rst isr_rules.rst speed_python.rst diff --git a/docs/reference/speed_python.rst b/docs/reference/speed_python.rst index 8efba4702b..279a1bbcdc 100644 --- a/docs/reference/speed_python.rst +++ b/docs/reference/speed_python.rst @@ -1,9 +1,11 @@ -Maximising Python Speed -======================= +Maximising MicroPython Speed +============================ + +.. contents:: This tutorial describes ways of improving the performance of MicroPython code. Optimisations involving other languages are covered elsewhere, namely the use -of modules written in C and the MicroPython inline ARM Thumb-2 assembler. +of modules written in C and the MicroPython inline assembler. The process of developing high performance code comprises the following stages which should be performed in the order listed. @@ -17,6 +19,7 @@ Optimisation steps: * Improve the efficiency of the Python code. * Use the native code emitter. * Use the viper code emitter. +* Use hardware-specific optimisations. Designing for speed ------------------- @@ -50,7 +53,7 @@ once only and not permitted to grow in size. This implies that the object persis for the duration of its use: typically it will be instantiated in a class constructor and used in various methods. -This is covered in further detail :ref:`Controlling garbage collection ` below. +This is covered in further detail :ref:`Controlling garbage collection ` below. Buffers ~~~~~~~ @@ -60,8 +63,8 @@ used for communication with a device. A typical driver will create the buffer in constructor and use it in its I/O methods which will be called repeatedly. The MicroPython libraries typically provide support for pre-allocated buffers. For -example, objects which support stream interface (e.g., file or UART) provide ``read()`` -method which allocate new buffer for read data, but also a ``readinto()`` method +example, objects which support stream interface (e.g., file or UART) provide `read()` +method which allocates new buffer for read data, but also a `readinto()` method to read data into an existing buffer. Floating Point @@ -79,14 +82,14 @@ Arrays ~~~~~~ Consider the use of the various types of array classes as an alternative to lists. -The ``array`` module supports various element types with 8-bit elements supported -by Python's built in ``bytes`` and ``bytearray`` classes. These data structures all store +The `array` module supports various element types with 8-bit elements supported +by Python's built in `bytes` and `bytearray` classes. These data structures all store elements in contiguous memory locations. Once again to avoid memory allocation in critical code these should be pre-allocated and passed as arguments or as bound objects. -When passing slices of objects such as ``bytearray`` instances, Python creates +When passing slices of objects such as `bytearray` instances, Python creates a copy which involves allocation of the size proportional to the size of slice. -This can be alleviated using a ``memoryview`` object. ``memoryview`` itself +This can be alleviated using a `memoryview` object. `memoryview` itself is allocated on heap, but is a small, fixed-size object, regardless of the size of slice it points too. @@ -97,7 +100,7 @@ of slice it points too. mv = memoryview(ba) # small object is allocated func(mv[30:2000]) # a pointer to memory is passed -A ``memoryview`` can only be applied to objects supporting the buffer protocol - this +A `memoryview` can only be applied to objects supporting the buffer protocol - this includes arrays but not lists. Small caveat is that while memoryview object is live, it also keeps alive the original buffer object. So, a memoryview isn't a universal panacea. For instance, in the example above, if you are done with 10K buffer and @@ -105,11 +108,11 @@ just need those bytes 30:2000 from it, it may be better to make a slice, and let the 10K buffer go (be ready for garbage collection), instead of making a long-living memoryview and keeping 10K blocked for GC. -Nonetheless, ``memoryview`` is indispensable for advanced preallocated buffer -management. ``.readinto()`` method discussed above puts data at the beginning +Nonetheless, `memoryview` is indispensable for advanced preallocated buffer +management. `readinto()` method discussed above puts data at the beginning of buffer and fills in entire buffer. What if you need to put data in the middle of existing buffer? Just create a memoryview into the needed section -of buffer and pass it to ``.readinto()``. +of buffer and pass it to `readinto()`. Identifying the slowest section of code --------------------------------------- @@ -118,8 +121,7 @@ This is a process known as profiling and is covered in textbooks and (for standard Python) supported by various software tools. For the type of smaller embedded application likely to be running on MicroPython platforms the slowest function or method can usually be established by judicious use -of the timing ``ticks`` group of functions documented -`here `_. +of the timing ``ticks`` group of functions documented in `utime`. Code execution time can be measured in ms, us, or CPU cycles. The following enables any function or method to be timed by adding an @@ -130,9 +132,9 @@ The following enables any function or method to be timed by adding an def timed_function(f, *args, **kwargs): myname = str(f).split(' ')[1] def new_func(*args, **kwargs): - t = time.ticks_us() + t = utime.ticks_us() result = f(*args, **kwargs) - delta = time.ticks_diff(time.ticks_us(), t) + delta = utime.ticks_diff(utime.ticks_us(), t) print('Function {} Time = {:6.3f}ms'.format(myname, delta/1000)) return result return new_func @@ -170,7 +172,7 @@ by caching the object in a local variable: This avoids the need repeatedly to look up ``self.ba`` and ``obj_display.framebuffer`` in the body of the method ``bar()``. -.. _gc: +.. _controlling_gc: Controlling garbage collection ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -182,7 +184,7 @@ process known as garbage collection reclaims the memory used by these redundant objects and the allocation is then tried again - a process which can take several milliseconds. -There are benefits in pre-empting this by periodically issuing ``gc.collect()``. +There may be benefits in pre-empting this by periodically issuing `gc.collect()`. Firstly doing a collection before it is actually required is quicker - typically on the order of 1ms if done frequently. Secondly you can determine the point in code where this time is used rather than have a longer delay occur at random points, @@ -190,34 +192,11 @@ possibly in a speed critical section. Finally performing collections regularly can reduce fragmentation in the heap. Severe fragmentation can lead to non-recoverable allocation failures. -Accessing hardware directly -~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -This comes into the category of more advanced programming and involves some knowledge -of the target MCU. Consider the example of toggling an output pin on the Pyboard. The -standard approach would be to write - -.. code:: python - - mypin.value(mypin.value() ^ 1) # mypin was instantiated as an output pin - -This involves the overhead of two calls to the ``Pin`` instance's ``value()`` -method. This overhead can be eliminated by performing a read/write to the relevant bit -of the chip's GPIO port output data register (odr). To facilitate this the ``stm`` -module provides a set of constants providing the addresses of the relevant registers. -A fast toggle of pin ``P4`` (CPU pin ``A14``) - corresponding to the green LED - -can be performed as follows: - -.. code:: python - - BIT14 = const(1 << 14) - stm.mem16[stm.GPIOA + stm.GPIO_ODR] ^= BIT14 - The Native code emitter ----------------------- -This causes the MicroPython compiler to emit ARM native opcodes rather than -bytecode. It covers the bulk of the Python language so most functions will require +This causes the MicroPython compiler to emit native CPU opcodes rather than +bytecode. It covers the bulk of the MicroPython functionality, so most functions will require no adaptation (but see below). It is invoked by means of a function decorator: .. code:: python @@ -276,7 +255,7 @@ Viper provides pointer types to assist the optimiser. These comprise * ``ptr32`` Points to a 32 bit machine word. The concept of a pointer may be unfamiliar to Python programmers. It has similarities -to a Python ``memoryview`` object in that it provides direct access to data stored in memory. +to a Python `memoryview` object in that it provides direct access to data stored in memory. Items are accessed using subscript notation, but slices are not supported: a pointer can return a single item only. Its purpose is to provide fast random access to data stored in contiguous memory locations - such as data stored in objects which support the buffer protocol, and @@ -330,3 +309,34 @@ The following example illustrates the use of a ``ptr16`` cast to toggle pin X1 ` A detailed technical description of the three code emitters may be found on Kickstarter here `Note 1 `_ and here `Note 2 `_ + +Accessing hardware directly +--------------------------- + +.. note:: + + Code examples in this section are given for the Pyboard. The techniques + described however may be applied to other MicroPython ports too. + +This comes into the category of more advanced programming and involves some knowledge +of the target MCU. Consider the example of toggling an output pin on the Pyboard. The +standard approach would be to write + +.. code:: python + + mypin.value(mypin.value() ^ 1) # mypin was instantiated as an output pin + +This involves the overhead of two calls to the `Pin` instance's :meth:`~machine.Pin.value()` +method. This overhead can be eliminated by performing a read/write to the relevant bit +of the chip's GPIO port output data register (odr). To facilitate this the ``stm`` +module provides a set of constants providing the addresses of the relevant registers. +A fast toggle of pin ``P4`` (CPU pin ``A14``) - corresponding to the green LED - +can be performed as follows: + +.. code:: python + + import machine + import stm + + BIT14 = const(1 << 14) + machine.mem16[stm.GPIOA + stm.GPIO_ODR] ^= BIT14 diff --git a/docs/templates/replace.inc b/docs/templates/replace.inc new file mode 100644 index 0000000000..319c53735f --- /dev/null +++ b/docs/templates/replace.inc @@ -0,0 +1,9 @@ +.. comment: This file is intended for global "replace" definitions. + +.. |see_cpython| replace:: See CPython documentation: + +.. |see_cpython_module| replace:: + + *This module implements a subset of the corresponding* `CPython` *module, + as described below. For more information, refer to the original + CPython documentation:* diff --git a/docs/topindex.html b/docs/templates/topindex.html similarity index 83% rename from docs/topindex.html rename to docs/templates/topindex.html index f32f3cea6b..76e5e18d72 100644 --- a/docs/topindex.html +++ b/docs/templates/topindex.html @@ -57,16 +57,6 @@ Language Reference
information about MicroPython specific language features

- {% if port == "pyboard" %} - - - {% endif %} + @@ -112,12 +106,6 @@ MicroPython on GitHub
contribute to the source code on GitHub

- {% if port == "wipy" %} - - {% endif %} diff --git a/docs/unix_contents.rst b/docs/unix_contents.rst deleted file mode 100644 index 8c5a586b29..0000000000 --- a/docs/unix_contents.rst +++ /dev/null @@ -1,9 +0,0 @@ -MicroPython documentation contents -================================== - -.. toctree:: - - library/index.rst - reference/index.rst - genrst/index.rst - license.rst diff --git a/docs/unix_index.rst b/docs/unix_index.rst index 7fa1753c23..1bfeb0bdac 100644 --- a/docs/unix_index.rst +++ b/docs/unix_index.rst @@ -4,13 +4,6 @@ MicroPython documentation and references .. toctree:: library/index.rst + reference/index.rst genrst/index.rst license.rst - unix_contents.rst - -Indices and tables -================== - -* :ref:`genindex` -* :ref:`modindex` -* :ref:`search` diff --git a/docs/wipy_contents.rst b/docs/wipy_contents.rst deleted file mode 100644 index 0e50a7c6ee..0000000000 --- a/docs/wipy_contents.rst +++ /dev/null @@ -1,12 +0,0 @@ -MicroPython documentation contents -================================== - -.. toctree:: - - wipy/quickref.rst - wipy/general.rst - wipy/tutorial/index.rst - library/index.rst - reference/index.rst - genrst/index.rst - license.rst diff --git a/docs/wipy_index.rst b/docs/wipy_index.rst index a390aecb1e..15c04c0fba 100644 --- a/docs/wipy_index.rst +++ b/docs/wipy_index.rst @@ -7,13 +7,6 @@ MicroPython documentation and references wipy/general.rst wipy/tutorial/index.rst library/index.rst + reference/index.rst genrst/index.rst license.rst - wipy_contents.rst - -Indices and tables -================== - -* :ref:`genindex` -* :ref:`modindex` -* :ref:`search` diff --git a/drivers/dht/dht.h b/drivers/dht/dht.h index 20954036df..883e077961 100644 --- a/drivers/dht/dht.h +++ b/drivers/dht/dht.h @@ -1,3 +1,8 @@ +#ifndef MICROPY_INCLUDED_DRIVERS_DHT_DHT_H +#define MICROPY_INCLUDED_DRIVERS_DHT_DHT_H + #include "py/obj.h" MP_DECLARE_CONST_FUN_OBJ_2(dht_readinto_obj); + +#endif // MICROPY_INCLUDED_DRIVERS_DHT_DHT_H diff --git a/drivers/memory/spiflash.h b/drivers/memory/spiflash.h index d2e817450c..967352b04e 100644 --- a/drivers/memory/spiflash.h +++ b/drivers/memory/spiflash.h @@ -23,7 +23,6 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - #ifndef MICROPY_INCLUDED_DRIVERS_MEMORY_SPIFLASH_H #define MICROPY_INCLUDED_DRIVERS_MEMORY_SPIFLASH_H diff --git a/drivers/nrf24l01/nrf24l01.py b/drivers/nrf24l01/nrf24l01.py index b45c137c6c..7274a79278 100644 --- a/drivers/nrf24l01/nrf24l01.py +++ b/drivers/nrf24l01/nrf24l01.py @@ -1,4 +1,4 @@ -"""NRF24L01 driver for Micro Python +"""NRF24L01 driver for MicroPython """ from micropython import const diff --git a/drivers/onewire/ds18x20.py b/drivers/onewire/ds18x20.py index 72adcbfd46..bf06094835 100644 --- a/drivers/onewire/ds18x20.py +++ b/drivers/onewire/ds18x20.py @@ -1,101 +1,51 @@ -""" -DS18x20 temperature sensor driver for MicroPython. +# DS18x20 temperature sensor driver for MicroPython. +# MIT license; Copyright (c) 2016 Damien P. George -This driver uses the OneWire driver to control DS18S20 and DS18B20 -temperature sensors. It supports multiple devices on the same 1-wire bus. +from micropython import const -The following example assumes the ground of your DS18x20 is connected to -Y11, vcc is connected to Y9 and the data pin is connected to Y10. +_CONVERT = const(0x44) +_RD_SCRATCH = const(0xbe) +_WR_SCRATCH = const(0x4e) ->>> from machine import Pin ->>> gnd = Pin('Y11', Pin.OUT_PP) ->>> gnd.off() ->>> vcc = Pin('Y9', Pin.OUT_PP) ->>> vcc.on() +class DS18X20: + def __init__(self, onewire): + self.ow = onewire + self.buf = bytearray(9) ->>> from ds18x20 import DS18X20 ->>> d = DS18X20(Pin('Y10')) + def scan(self): + return [rom for rom in self.ow.scan() if rom[0] == 0x10 or rom[0] == 0x28] -Call read_temps to read all sensors: + def convert_temp(self): + self.ow.reset(True) + self.ow.writebyte(self.ow.SKIP_ROM) + self.ow.writebyte(_CONVERT) ->>> result = d.read_temps() ->>> print(result) -[20.875, 20.8125] + def read_scratch(self, rom): + self.ow.reset(True) + self.ow.select_rom(rom) + self.ow.writebyte(_RD_SCRATCH) + self.ow.readinto(self.buf) + if self.ow.crc8(self.buf): + raise Exception('CRC error') + return self.buf -Call read_temp to read the temperature of a specific sensor: + def write_scratch(self, rom, buf): + self.ow.reset(True) + self.ow.select_rom(rom) + self.ow.writebyte(_WR_SCRATCH) + self.ow.write(buf) ->>> result = d.read_temp(d.roms[0]) ->>> print(result) -20.25 - -If only one DS18x20 is attached to the bus, then you don't need to -pass a ROM to read_temp: - ->>> result = d.read_temp() ->>> print(result) -20.25 - -""" - -from onewire import OneWire - -class DS18X20(object): - def __init__(self, pin): - self.ow = OneWire(pin) - # Scan the 1-wire devices, but only keep those which have the - # correct # first byte in their rom for a DS18x20 device. - self.roms = [rom for rom in self.ow.scan() if rom[0] == 0x10 or rom[0] == 0x28] - - def read_temp(self, rom=None): - """ - Read and return the temperature of one DS18x20 device. - Pass the 8-byte bytes object with the ROM of the specific device you want to read. - If only one DS18x20 device is attached to the bus you may omit the rom parameter. - """ - rom = rom or self.roms[0] - ow = self.ow - ow.reset() - ow.select_rom(rom) - ow.write_byte(0x44) # Convert Temp - while True: - if ow.read_bit(): - break - ow.reset() - ow.select_rom(rom) - ow.write_byte(0xbe) # Read scratch - data = ow.read_bytes(9) - return self.convert_temp(rom[0], data) - - def read_temps(self): - """ - Read and return the temperatures of all attached DS18x20 devices. - """ - temps = [] - for rom in self.roms: - temps.append(self.read_temp(rom)) - return temps - - def convert_temp(self, rom0, data): - """ - Convert the raw temperature data into degrees celsius and return as a float. - """ - temp_lsb = data[0] - temp_msb = data[1] - if rom0 == 0x10: - if temp_msb != 0: - # convert negative number - temp_read = temp_lsb >> 1 | 0x80 # truncate bit 0 by shifting, fill high bit with 1. - temp_read = -((~temp_read + 1) & 0xff) # now convert from two's complement + def read_temp(self, rom): + buf = self.read_scratch(rom) + if rom[0] == 0x10: + if buf[1]: + t = buf[0] >> 1 | 0x80 + t = -((~t + 1) & 0xff) else: - temp_read = temp_lsb >> 1 # truncate bit 0 by shifting - count_remain = data[6] - count_per_c = data[7] - temp = temp_read - 0.25 + (count_per_c - count_remain) / count_per_c - return temp - elif rom0 == 0x28: - temp = (temp_msb << 8 | temp_lsb) / 16 - if (temp_msb & 0xf8) == 0xf8: # for negative temperature - temp -= 0x1000 - return temp + t = buf[0] >> 1 + return t - 0.25 + (buf[7] - buf[6]) / buf[7] else: - assert False + t = buf[1] << 8 | buf[0] + if t & 0x8000: # sign bit set + t = -((t ^ 0xffff) + 1) + return t / 16 diff --git a/drivers/onewire/onewire.py b/drivers/onewire/onewire.py index c8016c0dac..3309ba0d27 100644 --- a/drivers/onewire/onewire.py +++ b/drivers/onewire/onewire.py @@ -1,336 +1,91 @@ -""" -OneWire library ported to MicroPython by Jason Hildebrand. +# 1-Wire driver for MicroPython +# MIT license; Copyright (c) 2016 Damien P. George +from micropython import const +import _onewire as _ow -TODO: - * implement and test parasite-power mode (as an init option) - * port the crc checks - -The original upstream copyright and terms follow. ------------------------------------------------------------------------------- - -Copyright (c) 2007, Jim Studt (original old version - many contributors since) - -OneWire has been maintained by Paul Stoffregen (paul@pjrc.com) since -January 2010. - -26 Sept 2008 -- Robin James - -Jim Studt's original library was modified by Josh Larios. - -Tom Pollard, pollard@alum.mit.edu, contributed around May 20, 2008 - -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. - -Much of the code was inspired by Derek Yerger's code, though I don't -think much of that remains. In any event that was.. - (copyleft) 2006 by Derek Yerger - Free to distribute freely. -""" - -import pyb -from pyb import disable_irq -from pyb import enable_irq +class OneWireError(Exception): + pass class OneWire: + SEARCH_ROM = const(0xf0) + MATCH_ROM = const(0x55) + SKIP_ROM = const(0xcc) + def __init__(self, pin): - """ - Pass the data pin connected to your one-wire device(s), for example Pin('X1'). - The one-wire protocol allows for multiple devices to be attached. - """ - self.data_pin = pin - self.write_delays = (1, 40, 40, 1) - self.read_delays = (1, 1, 40) + self.pin = pin + self.pin.init(pin.OPEN_DRAIN, pin.PULL_UP) - # cache a bunch of methods and attributes. This is necessary in _write_bit and - # _read_bit to achieve the timing required by the OneWire protocol. - self.cache = (pin.init, pin.value, pin.OUT_PP, pin.IN, pin.PULL_UP) + def reset(self, required=False): + reset = _ow.reset(self.pin) + if required and not reset: + raise OneWireError + return reset - pin.init(pin.IN, pin.PULL_UP) + def readbit(self): + return _ow.readbit(self.pin) - def reset(self): - """ - Perform the onewire reset function. - Returns 1 if a device asserted a presence pulse, 0 otherwise. + def readbyte(self): + return _ow.readbyte(self.pin) - If you receive 0, then check your wiring and make sure you are providing - power and ground to your devices. - """ - retries = 25 - self.data_pin.init(self.data_pin.IN, self.data_pin.PULL_UP) + def readinto(self, buf): + for i in range(len(buf)): + buf[i] = _ow.readbyte(self.pin) - # We will wait up to 250uS for - # the bus to come high, if it doesn't then it is broken or shorted - # and we return a 0; + def writebit(self, value): + return _ow.writebit(self.pin, value) - # wait until the wire is high... just in case - while True: - if self.data_pin.value(): - break - retries -= 1 - if retries == 0: - raise OSError("OneWire pin didn't go high") - pyb.udelay(10) + def writebyte(self, value): + return _ow.writebyte(self.pin, value) - # pull the bus low for at least 480us - self.data_pin.low() - self.data_pin.init(self.data_pin.OUT_PP) - pyb.udelay(480) - - # If there is a slave present, it should pull the bus low within 60us - i = pyb.disable_irq() - self.data_pin.init(self.data_pin.IN, self.data_pin.PULL_UP) - pyb.udelay(70) - presence = not self.data_pin.value() - pyb.enable_irq(i) - pyb.udelay(410) - return presence - - def write_bit(self, value): - """ - Write a single bit. - """ - pin_init, pin_value, Pin_OUT_PP, Pin_IN, Pin_PULL_UP = self.cache - self._write_bit(value, pin_init, pin_value, Pin_OUT_PP) - - def _write_bit(self, value, pin_init, pin_value, Pin_OUT_PP): - """ - Write a single bit - requires cached methods/attributes be passed as arguments. - See also write_bit() - """ - d0, d1, d2, d3 = self.write_delays - udelay = pyb.udelay - if value: - # write 1 - i = disable_irq() - pin_value(0) - pin_init(Pin_OUT_PP) - udelay(d0) - pin_value(1) - enable_irq(i) - udelay(d1) - else: - # write 0 - i = disable_irq() - pin_value(0) - pin_init(Pin_OUT_PP) - udelay(d2) - pin_value(1) - enable_irq(i) - udelay(d3) - - def write_byte(self, value): - """ - Write a byte. The pin will go tri-state at the end of the write to avoid - heating in a short or other mishap. - """ - pin_init, pin_value, Pin_OUT_PP, Pin_IN, Pin_PULL_UP = self.cache - for i in range(8): - self._write_bit(value & 1, pin_init, pin_value, Pin_OUT_PP) - value >>= 1 - pin_init(Pin_IN, Pin_PULL_UP) - - def write_bytes(self, bytestring): - """ - Write a sequence of bytes. - """ - for byte in bytestring: - self.write_byte(byte) - - def _read_bit(self, pin_init, pin_value, Pin_OUT_PP, Pin_IN, Pin_PULL_UP): - """ - Read a single bit - requires cached methods/attributes be passed as arguments. - See also read_bit() - """ - d0, d1, d2 = self.read_delays - udelay = pyb.udelay - pin_init(Pin_IN, Pin_PULL_UP) # TODO why do we need this? - i = disable_irq() - pin_value(0) - pin_init(Pin_OUT_PP) - udelay(d0) - pin_init(Pin_IN, Pin_PULL_UP) - udelay(d1) - value = pin_value() - enable_irq(i) - udelay(d2) - return value - - def read_bit(self): - """ - Read a single bit. - """ - pin_init, pin_value, Pin_OUT_PP, Pin_IN, Pin_PULL_UP = self.cache - return self._read_bit(pin_init, pin_value, Pin_OUT_PP, Pin_IN, Pin_PULL_UP) - - def read_byte(self): - """ - Read a single byte and return the value as an integer. - See also read_bytes() - """ - pin_init, pin_value, Pin_OUT_PP, Pin_IN, Pin_PULL_UP = self.cache - value = 0 - for i in range(8): - bit = self._read_bit(pin_init, pin_value, Pin_OUT_PP, Pin_IN, Pin_PULL_UP) - value |= bit << i - return value - - def read_bytes(self, count): - """ - Read a sequence of N bytes. - The bytes are returned as a bytearray. - """ - s = bytearray(count) - for i in range(count): - s[i] = self.read_byte() - return s + def write(self, buf): + for b in buf: + _ow.writebyte(self.pin, b) def select_rom(self, rom): - """ - Select a specific device to talk to. Pass in rom as a bytearray (8 bytes). - """ - assert len(rom) == 8, "ROM must be 8 bytes" self.reset() - self.write_byte(0x55) # ROM MATCH - self.write_bytes(rom) - - def read_rom(self): - """ - Read the ROM - this works if there is only a single device attached. - """ - self.reset() - self.write_byte(0x33) # READ ROM - rom = self.read_bytes(8) - # TODO: check CRC of the ROM - return rom - - def skip_rom(self): - """ - Send skip-rom command - this works if there is only one device attached. - """ - self.write_byte(0xCC) # SKIP ROM - - def depower(self): - self.data_pin.init(self.data_pin.IN, self.data_pin.PULL_NONE) + self.writebyte(MATCH_ROM) + self.write(rom) def scan(self): - """ - Return a list of ROMs for all attached devices. - Each ROM is returned as a bytes object of 8 bytes. - """ devices = [] - self._reset_search() - while True: - rom = self._search() - if not rom: - return devices - devices.append(rom) + diff = 65 + rom = False + for i in range(0xff): + rom, diff = self._search_rom(rom, diff) + if rom: + devices += [rom] + if diff == 0: + break + return devices - def _reset_search(self): - self.last_discrepancy = 0 - self.last_device_flag = False - self.last_family_discrepancy = 0 - self.rom = bytearray(8) - - def _search(self): - # initialize for search - id_bit_number = 1 - last_zero = 0 - rom_byte_number = 0 - rom_byte_mask = 1 - search_result = 0 - pin_init, pin_value, Pin_OUT_PP, Pin_IN, Pin_PULL_UP = self.cache - - # if the last call was not the last one - if not self.last_device_flag: - # 1-Wire reset - if not self.reset(): - self._reset_search() - return None - - # issue the search command - self.write_byte(0xF0) - - # loop to do the search - while rom_byte_number < 8: # loop until through all ROM bytes 0-7 - # read a bit and its complement - id_bit = self._read_bit(pin_init, pin_value, Pin_OUT_PP, Pin_IN, Pin_PULL_UP) - cmp_id_bit = self._read_bit(pin_init, pin_value, Pin_OUT_PP, Pin_IN, Pin_PULL_UP) - - # check for no devices on 1-wire - if (id_bit == 1) and (cmp_id_bit == 1): - break + def _search_rom(self, l_rom, diff): + if not self.reset(): + return None, 0 + self.writebyte(SEARCH_ROM) + if not l_rom: + l_rom = bytearray(8) + rom = bytearray(8) + next_diff = 0 + i = 64 + for byte in range(8): + r_b = 0 + for bit in range(8): + b = self.readbit() + if self.readbit(): + if b: # there are no devices or there is an error on the bus + return None, 0 else: - # all devices coupled have 0 or 1 - if (id_bit != cmp_id_bit): - search_direction = id_bit # bit write value for search - else: - # if this discrepancy if before the Last Discrepancy - # on a previous next then pick the same as last time - if (id_bit_number < self.last_discrepancy): - search_direction = (self.rom[rom_byte_number] & rom_byte_mask) > 0 - else: - # if equal to last pick 1, if not then pick 0 - search_direction = (id_bit_number == self.last_discrepancy) - - # if 0 was picked then record its position in LastZero - if search_direction == 0: - last_zero = id_bit_number - - # check for Last discrepancy in family - if last_zero < 9: - self.last_family_discrepancy = last_zero + if not b: # collision, two devices with different bit meaning + if diff > i or ((l_rom[byte] & (1 << bit)) and diff != i): + b = 1 + next_diff = i + self.writebit(b) + if b: + r_b |= 1 << bit + i -= 1 + rom[byte] = r_b + return rom, next_diff - # set or clear the bit in the ROM byte rom_byte_number - # with mask rom_byte_mask - if search_direction == 1: - self.rom[rom_byte_number] |= rom_byte_mask - else: - self.rom[rom_byte_number] &= ~rom_byte_mask - - # serial number search direction write bit - #print('sd', search_direction) - self.write_bit(search_direction) - - # increment the byte counter id_bit_number - # and shift the mask rom_byte_mask - id_bit_number += 1 - rom_byte_mask <<= 1 - - # if the mask is 0 then go to new SerialNum byte rom_byte_number and reset mask - if rom_byte_mask == 0x100: - rom_byte_number += 1 - rom_byte_mask = 1 - - # if the search was successful then - if not (id_bit_number < 65): - # search successful so set last_discrepancy,last_device_flag,search_result - self.last_discrepancy = last_zero - - # check for last device - if self.last_discrepancy == 0: - self.last_device_flag = True - search_result = True - - # if no device found then reset counters so next 'search' will be like a first - if not search_result or not self.rom[0]: - self._reset_search() - return None - else: - return bytes(self.rom) + def crc8(self, data): + return _ow.crc8(data) diff --git a/drivers/sdcard/sdcard.py b/drivers/sdcard/sdcard.py index e749d5376f..75a0c501ee 100644 --- a/drivers/sdcard/sdcard.py +++ b/drivers/sdcard/sdcard.py @@ -1,5 +1,5 @@ """ -Micro Python driver for SD cards using SPI bus. +MicroPython driver for SD cards using SPI bus. Requires an SPI bus and a CS pin. Provides readblocks and writeblocks methods so the device can be mounted as a filesystem. diff --git a/drivers/wiznet5k/README.md b/drivers/wiznet5k/README.md index 4f907e0b1d..88f25a2b8d 100644 --- a/drivers/wiznet5k/README.md +++ b/drivers/wiznet5k/README.md @@ -1,6 +1,6 @@ This is the driver for the WIZnet5x00 series of Ethernet controllers. -Adapted for Micro Python. +Adapted for MicroPython. Original source: https://github.com/Wiznet/W5500_EVB/tree/master/ioLibrary Taken on: 30 August 2014 diff --git a/esp8266/Makefile b/esp8266/Makefile index cf4b288ca2..1c169862ea 100644 --- a/esp8266/Makefile +++ b/esp8266/Makefile @@ -8,8 +8,8 @@ MICROPY_SSL_AXTLS = 1 MICROPY_FATFS = 1 MICROPY_PY_BTREE = 1 -FROZEN_DIR = scripts -FROZEN_MPY_DIR = modules +FROZEN_DIR ?= scripts +FROZEN_MPY_DIR ?= modules # include py core make definitions include ../py/py.mk @@ -68,7 +68,6 @@ SRC_C = \ lexerstr32.c \ uart.c \ esppwm.c \ - esponewire.c \ espneopixel.c \ espapa102.c \ intr.c \ @@ -85,19 +84,15 @@ SRC_C = \ modnetwork.c \ modutime.c \ moduos.c \ - modonewire.c \ ets_alt_task.c \ fatfs_port.c \ axtls_helpers.c \ hspi.c \ $(SRC_MOD) -STM_SRC_C = $(addprefix stmhal/,\ - pybstdio.c \ - ) - EXTMOD_SRC_C = $(addprefix extmod/,\ modlwip.c \ + modonewire.c \ ) LIB_SRC_C = $(addprefix lib/,\ @@ -125,6 +120,7 @@ LIB_SRC_C = $(addprefix lib/,\ timeutils/timeutils.c \ utils/pyexec.c \ utils/interrupt_char.c \ + utils/sys_stdio_mphal.c \ ) ifeq ($(MICROPY_FATFS), 1) @@ -144,14 +140,13 @@ OBJ = OBJ += $(PY_O) OBJ += $(addprefix $(BUILD)/, $(SRC_C:.c=.o)) OBJ += $(addprefix $(BUILD)/, $(SRC_S:.s=.o)) -OBJ += $(addprefix $(BUILD)/, $(STM_SRC_C:.c=.o)) OBJ += $(addprefix $(BUILD)/, $(EXTMOD_SRC_C:.c=.o)) OBJ += $(addprefix $(BUILD)/, $(LIB_SRC_C:.c=.o)) OBJ += $(addprefix $(BUILD)/, $(DRIVERS_SRC_C:.c=.o)) #OBJ += $(BUILD)/pins_$(BOARD).o # List of sources for qstr extraction -SRC_QSTR += $(SRC_C) $(STM_SRC_C) $(EXTMOD_SRC_C) $(DRIVERS_SRC_C) +SRC_QSTR += $(SRC_C) $(EXTMOD_SRC_C) $(LIB_SRC_C) $(DRIVERS_SRC_C) # Append any auto-generated sources that are needed by sources listed in SRC_QSTR SRC_QSTR_AUTO_DEPS += @@ -232,7 +227,11 @@ axtls: $(BUILD)/libaxtls.a $(BUILD)/libaxtls.a: cd ../lib/axtls; cp config/upyconfig config/.config - cd ../lib/axtls; make oldconfig -B - cd ../lib/axtls; make clean - cd ../lib/axtls; make all CC="$(CC)" LD="$(LD)" AR="$(AR)" CFLAGS_EXTRA="$(CFLAGS_XTENSA) -Dabort=abort_ -DRT_MAX_PLAIN_LENGTH=1024 -DRT_EXTRA=3072" + cd ../lib/axtls; $(MAKE) oldconfig -B + cd ../lib/axtls; $(MAKE) clean + cd ../lib/axtls; $(MAKE) all CC="$(CC)" LD="$(LD)" AR="$(AR)" CFLAGS_EXTRA="$(CFLAGS_XTENSA) -Dabort=abort_ -DRT_MAX_PLAIN_LENGTH=1024 -DRT_EXTRA=4096" cp ../lib/axtls/_stage/libaxtls.a $@ + +clean-modules: + git clean -f -d modules + rm -f build/frozen*.c diff --git a/esp8266/README.md b/esp8266/README.md index d717d26fed..252e195d83 100644 --- a/esp8266/README.md +++ b/esp8266/README.md @@ -114,8 +114,13 @@ Python prompt over WiFi, connecting through a browser. Please follow the instructions there. -More detailed instructions can be found at -http://docs.micropython.org/en/latest/esp8266/esp8266/tutorial/intro.html +Documentation +------------- + +More detailed documentation and instructions can be found at +http://docs.micropython.org/en/latest/esp8266/ , which includes Quick +Reference, Tutorial, General Information related to ESP8266 port, and +to MicroPython in general. Troubleshooting --------------- @@ -132,3 +137,5 @@ experience strange bootloops, crashes, lockups, here's a list to check against: Please consult dedicated ESP8266 forums/resources for hardware-related problems. + +Additional information may be available by the documentation links above. diff --git a/esp8266/esp8266_common.ld b/esp8266/esp8266_common.ld index bc983df700..de5268c8fe 100644 --- a/esp8266/esp8266_common.ld +++ b/esp8266/esp8266_common.ld @@ -125,8 +125,6 @@ SECTIONS *lib/timeutils/*.o*(.literal*, .text*) *lib/utils/*.o*(.literal*, .text*) - *stmhal/pybstdio.o(.literal*, .text*) - build/main.o(.literal* .text*) *gccollect.o(.literal* .text*) *gchelper.o(.literal* .text*) diff --git a/esp8266/esp_mphal.c b/esp8266/esp_mphal.c index 7ecc7776aa..61848fd343 100644 --- a/esp8266/esp_mphal.c +++ b/esp8266/esp_mphal.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -208,28 +208,6 @@ void mp_hal_signal_dupterm_input(void) { system_os_post(DUPTERM_TASK_ID, 0, 0); } -void mp_hal_pin_open_drain(mp_hal_pin_obj_t pin_id) { - const pyb_pin_obj_t *pin = &pyb_pin_obj[pin_id]; - - if (pin->phys_port == 16) { - // configure GPIO16 as input with output register holding 0 - WRITE_PERI_REG(PAD_XPD_DCDC_CONF, (READ_PERI_REG(PAD_XPD_DCDC_CONF) & 0xffffffbc) | 1); - WRITE_PERI_REG(RTC_GPIO_CONF, READ_PERI_REG(RTC_GPIO_CONF) & ~1); - WRITE_PERI_REG(RTC_GPIO_ENABLE, (READ_PERI_REG(RTC_GPIO_ENABLE) & ~1)); // input - WRITE_PERI_REG(RTC_GPIO_OUT, (READ_PERI_REG(RTC_GPIO_OUT) & ~1)); // out=0 - return; - } - - ETS_GPIO_INTR_DISABLE(); - PIN_FUNC_SELECT(pin->periph, pin->func); - GPIO_REG_WRITE(GPIO_PIN_ADDR(GPIO_ID_PIN(pin->phys_port)), - GPIO_REG_READ(GPIO_PIN_ADDR(GPIO_ID_PIN(pin->phys_port))) - | GPIO_PIN_PAD_DRIVER_SET(GPIO_PAD_DRIVER_ENABLE)); // open drain - GPIO_REG_WRITE(GPIO_ENABLE_ADDRESS, - GPIO_REG_READ(GPIO_ENABLE_ADDRESS) | (1 << pin->phys_port)); - ETS_GPIO_INTR_ENABLE(); -} - // Get pointer to esf_buf bookkeeping structure void *ets_get_esf_buf_ctlblk(void) { // Get literal ptr before start of esf_rx_buf_alloc func diff --git a/esp8266/esp_mphal.h b/esp8266/esp_mphal.h index d783f1f09a..913bd70dc9 100644 --- a/esp8266/esp_mphal.h +++ b/esp8266/esp_mphal.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -24,9 +24,6 @@ * THE SOFTWARE. */ -#ifndef _INCLUDED_MPHAL_H_ -#define _INCLUDED_MPHAL_H_ - #include "py/ringbuf.h" #include "lib/utils/interrupt_char.h" #include "xtirq.h" @@ -96,5 +93,3 @@ void mp_hal_pin_open_drain(mp_hal_pin_obj_t pin); void *ets_get_esf_buf_ctlblk(void); int ets_esf_free_bufs(int idx); - -#endif // _INCLUDED_MPHAL_H_ diff --git a/esp8266/espapa102.h b/esp8266/espapa102.h index 82c92025d3..dd7c5ab729 100644 --- a/esp8266/espapa102.h +++ b/esp8266/espapa102.h @@ -23,5 +23,9 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ +#ifndef MICROPY_INCLUDED_ESP8266_ESPAPA102_H +#define MICROPY_INCLUDED_ESP8266_ESPAPA102_H void esp_apa102_write(uint8_t clockPin, uint8_t dataPin, uint8_t *pixels, uint32_t numBytes); + +#endif // MICROPY_INCLUDED_ESP8266_ESPAPA102_H diff --git a/esp8266/espneopixel.h b/esp8266/espneopixel.h index 4b20afda58..c444740ff9 100644 --- a/esp8266/espneopixel.h +++ b/esp8266/espneopixel.h @@ -1 +1,6 @@ +#ifndef MICROPY_INCLUDED_ESP8266_ESPNEOPIXEL_H +#define MICROPY_INCLUDED_ESP8266_ESPNEOPIXEL_H + void esp_neopixel_write(uint8_t pin, uint8_t *pixels, uint32_t numBytes, bool is800KHz); + +#endif // MICROPY_INCLUDED_ESP8266_ESPNEOPIXEL_H diff --git a/esp8266/esponewire.c b/esp8266/esponewire.c deleted file mode 100644 index 22bb45b158..0000000000 --- a/esp8266/esponewire.c +++ /dev/null @@ -1,99 +0,0 @@ -/* - * This file is part of the MicroPython project, http://micropython.org/ - * - * The MIT License (MIT) - * - * Copyright (c) 2015-2016 Damien P. George - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -#include - -#include "etshal.h" -#include "user_interface.h" -#include "modmachine.h" -#include "esponewire.h" - -#define TIMING_RESET1 (0) -#define TIMING_RESET2 (1) -#define TIMING_RESET3 (2) -#define TIMING_READ1 (3) -#define TIMING_READ2 (4) -#define TIMING_READ3 (5) -#define TIMING_WRITE1 (6) -#define TIMING_WRITE2 (7) -#define TIMING_WRITE3 (8) - -uint16_t esp_onewire_timings[9] = {480, 40, 420, 5, 5, 40, 10, 50, 10}; - -static uint32_t disable_irq(void) { - ets_intr_lock(); - return 0; -} - -static void enable_irq(uint32_t i) { - ets_intr_unlock(); -} - -static void mp_hal_delay_us_no_irq(uint32_t us) { - uint32_t start = system_get_time(); - while (system_get_time() - start < us) { - } -} - -#define DELAY_US mp_hal_delay_us_no_irq - -int esp_onewire_reset(uint pin) { - pin_set(pin, 0); - DELAY_US(esp_onewire_timings[TIMING_RESET1]); - uint32_t i = disable_irq(); - pin_set(pin, 1); - DELAY_US(esp_onewire_timings[TIMING_RESET2]); - int status = !pin_get(pin); - enable_irq(i); - DELAY_US(esp_onewire_timings[TIMING_RESET3]); - return status; -} - -int esp_onewire_readbit(uint pin) { - pin_set(pin, 1); - uint32_t i = disable_irq(); - pin_set(pin, 0); - DELAY_US(esp_onewire_timings[TIMING_READ1]); - pin_set(pin, 1); - DELAY_US(esp_onewire_timings[TIMING_READ2]); - int value = pin_get(pin); - enable_irq(i); - DELAY_US(esp_onewire_timings[TIMING_READ3]); - return value; -} - -void esp_onewire_writebit(uint pin, int value) { - uint32_t i = disable_irq(); - pin_set(pin, 0); - DELAY_US(esp_onewire_timings[TIMING_WRITE1]); - if (value) { - pin_set(pin, 1); - } - DELAY_US(esp_onewire_timings[TIMING_WRITE2]); - pin_set(pin, 1); - DELAY_US(esp_onewire_timings[TIMING_WRITE3]); - enable_irq(i); -} diff --git a/esp8266/esponewire.h b/esp8266/esponewire.h deleted file mode 100644 index da0a1d3880..0000000000 --- a/esp8266/esponewire.h +++ /dev/null @@ -1,36 +0,0 @@ -/* - * This file is part of the MicroPython project, http://micropython.org/ - * - * The MIT License (MIT) - * - * Copyright (c) 2016 Damien P. George - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -#ifndef __MICROPY_INCLUDED_ESP8266_ESPONEWIRE_H__ -#define __MICROPY_INCLUDED_ESP8266_ESPONEWIRE_H__ - -extern uint16_t esp_onewire_timings[9]; - -int esp_onewire_reset(uint pin); -int esp_onewire_readbit(uint pin); -void esp_onewire_writebit(uint pin, int value); - -#endif // __MICROPY_INCLUDED_ESP8266_ESPONEWIRE_H__ diff --git a/esp8266/esppwm.h b/esp8266/esppwm.h index 242a9a2a6f..1ee4a2f55a 100644 --- a/esp8266/esppwm.h +++ b/esp8266/esppwm.h @@ -1,5 +1,5 @@ -#ifndef __ESPPWM_H__ -#define __ESPPWM_H__ +#ifndef MICROPY_INCLUDED_ESP8266_ESPPWM_H +#define MICROPY_INCLUDED_ESP8266_ESPPWM_H #include #include @@ -14,4 +14,4 @@ uint16_t pwm_get_freq(uint8_t channel); int pwm_add(uint8_t pin_id, uint32_t pin_mux, uint32_t pin_func); bool pwm_delete(uint8_t channel); -#endif +#endif // MICROPY_INCLUDED_ESP8266_ESPPWM_H diff --git a/esp8266/ets_alt_task.h b/esp8266/ets_alt_task.h index dba0c5fa64..33a9d3a002 100644 --- a/esp8266/ets_alt_task.h +++ b/esp8266/ets_alt_task.h @@ -1,4 +1,9 @@ +#ifndef MICROPY_INCLUDED_ESP8266_ETS_ALT_TASK_H +#define MICROPY_INCLUDED_ESP8266_ETS_ALT_TASK_H + extern int ets_loop_iter_disable; extern uint32_t system_time_high_word; bool ets_loop_iter(void); + +#endif // MICROPY_INCLUDED_ESP8266_ETS_ALT_TASK_H diff --git a/esp8266/etshal.h b/esp8266/etshal.h index 90af63ba2d..34787779f9 100644 --- a/esp8266/etshal.h +++ b/esp8266/etshal.h @@ -1,5 +1,5 @@ -#ifndef _INCLUDED_ETSHAL_H_ -#define _INCLUDED_ETSHAL_H_ +#ifndef MICROPY_INCLUDED_ESP8266_ETSHAL_H +#define MICROPY_INCLUDED_ESP8266_ETSHAL_H #include @@ -42,4 +42,4 @@ uint32_t SPIRead(uint32_t offset, void *buf, uint32_t len); uint32_t SPIWrite(uint32_t offset, const void *buf, uint32_t len); uint32_t SPIEraseSector(int sector); -#endif // _INCLUDED_ETSHAL_H_ +#endif // MICROPY_INCLUDED_ESP8266_ETSHAL_H diff --git a/esp8266/fatfs_port.c b/esp8266/fatfs_port.c index 02384f6055..a8865c817e 100644 --- a/esp8266/fatfs_port.c +++ b/esp8266/fatfs_port.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/esp8266/gccollect.c b/esp8266/gccollect.c index 1b9349f574..cd5d4932c5 100644 --- a/esp8266/gccollect.c +++ b/esp8266/gccollect.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/esp8266/gccollect.h b/esp8266/gccollect.h index d81cba12c4..5735d8a390 100644 --- a/esp8266/gccollect.h +++ b/esp8266/gccollect.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,6 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ +#ifndef MICROPY_INCLUDED_ESP8266_GCCOLLECT_H +#define MICROPY_INCLUDED_ESP8266_GCCOLLECT_H extern uint32_t _text_start; extern uint32_t _text_end; @@ -39,3 +41,5 @@ extern uint32_t _heap_end; void gc_collect(void); void esp_native_code_gc_collect(void); + +#endif // MICROPY_INCLUDED_ESP8266_GCCOLLECT_H diff --git a/esp8266/hspi.c b/esp8266/hspi.c index 436fb4f6f4..554a50460f 100644 --- a/esp8266/hspi.c +++ b/esp8266/hspi.c @@ -28,7 +28,7 @@ /* Wrapper to setup HSPI/SPI GPIO pins and default SPI clock spi_no - SPI (0) or HSPI (1) -Not used in Micropython. +Not used in MicroPython. */ void spi_init(uint8_t spi_no) { spi_init_gpio(spi_no, SPI_CLK_USE_DIV); @@ -48,7 +48,7 @@ Configures SPI mode parameters for clock edge and clock polarity. (1) Data is valid on clock trailing edge spi_cpol - (0) Clock is low when inactive (1) Clock is high when inactive -For Micropython this version is different from original. +For MicroPython this version is different from original. */ void spi_mode(uint8_t spi_no, uint8_t spi_cpha, uint8_t spi_cpol) { if (spi_cpol) { @@ -99,7 +99,7 @@ void spi_init_gpio(uint8_t spi_no, uint8_t sysclk_as_spiclk) { // GPIO14 is HSPI CLK pin (Clock) PIN_FUNC_SELECT(PERIPHS_IO_MUX_MTMS_U, 2); // GPIO15 is HSPI CS pin (Chip Select / Slave Select) - // In Micropython, we are handling CS ourself in drivers. + // In MicroPython, we are handling CS ourself in drivers. // PIN_FUNC_SELECT(PERIPHS_IO_MUX_MTDO_U, 2); } } diff --git a/esp8266/hspi_register.h b/esp8266/hspi_register.h index 30a5ff5884..4dd335b400 100644 --- a/esp8266/hspi_register.h +++ b/esp8266/hspi_register.h @@ -3,7 +3,7 @@ * Modified by David Ogilvy (MetalPhreak) * Based on original file included in SDK 1.0.0 * - * Missing defines from previous SDK versions have + * Missing defines from previous SDK versions have * been added and are noted with comments. The * names of these defines are likely to change. */ diff --git a/esp8266/machine_adc.c b/esp8266/machine_adc.c index f1fb5be315..c8c08695bd 100644 --- a/esp8266/machine_adc.c +++ b/esp8266/machine_adc.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -70,8 +70,8 @@ STATIC mp_obj_t pyb_adc_read(mp_obj_t self_in) { } STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_adc_read_obj, pyb_adc_read); -STATIC const mp_map_elem_t pyb_adc_locals_dict_table[] = { - { MP_OBJ_NEW_QSTR(MP_QSTR_read), (mp_obj_t)&pyb_adc_read_obj } +STATIC const mp_rom_map_elem_t pyb_adc_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_read), MP_ROM_PTR(&pyb_adc_read_obj) } }; STATIC MP_DEFINE_CONST_DICT(pyb_adc_locals_dict, pyb_adc_locals_dict_table); @@ -79,5 +79,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_t)&pyb_adc_locals_dict, + .locals_dict = (mp_obj_dict_t*)&pyb_adc_locals_dict, }; diff --git a/esp8266/machine_pin.c b/esp8266/machine_pin.c index 385551578e..de65735ba7 100644 --- a/esp8266/machine_pin.c +++ b/esp8266/machine_pin.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -163,6 +163,28 @@ void mp_hal_pin_output(mp_hal_pin_obj_t pin_id) { } } +void mp_hal_pin_open_drain(mp_hal_pin_obj_t pin_id) { + const pyb_pin_obj_t *pin = &pyb_pin_obj[pin_id]; + + if (pin->phys_port == 16) { + // configure GPIO16 as input with output register holding 0 + WRITE_PERI_REG(PAD_XPD_DCDC_CONF, (READ_PERI_REG(PAD_XPD_DCDC_CONF) & 0xffffffbc) | 1); + WRITE_PERI_REG(RTC_GPIO_CONF, READ_PERI_REG(RTC_GPIO_CONF) & ~1); + WRITE_PERI_REG(RTC_GPIO_ENABLE, (READ_PERI_REG(RTC_GPIO_ENABLE) & ~1)); // input + WRITE_PERI_REG(RTC_GPIO_OUT, (READ_PERI_REG(RTC_GPIO_OUT) & ~1)); // out=0 + return; + } + + ETS_GPIO_INTR_DISABLE(); + PIN_FUNC_SELECT(pin->periph, pin->func); + GPIO_REG_WRITE(GPIO_PIN_ADDR(GPIO_ID_PIN(pin->phys_port)), + GPIO_REG_READ(GPIO_PIN_ADDR(GPIO_ID_PIN(pin->phys_port))) + | GPIO_PIN_PAD_DRIVER_SET(GPIO_PAD_DRIVER_ENABLE)); // open drain + GPIO_REG_WRITE(GPIO_ENABLE_ADDRESS, + GPIO_REG_READ(GPIO_ENABLE_ADDRESS) | (1 << pin->phys_port)); + ETS_GPIO_INTR_ENABLE(); +} + int pin_get(uint pin) { if (pin == 16) { return READ_PERI_REG(RTC_GPIO_IN_DATA) & 1; @@ -404,24 +426,24 @@ STATIC mp_uint_t pin_ioctl(mp_obj_t self_in, mp_uint_t request, uintptr_t arg, i return -1; } -STATIC const mp_map_elem_t pyb_pin_locals_dict_table[] = { +STATIC const mp_rom_map_elem_t pyb_pin_locals_dict_table[] = { // instance methods - { MP_OBJ_NEW_QSTR(MP_QSTR_init), (mp_obj_t)&pyb_pin_init_obj }, - { MP_OBJ_NEW_QSTR(MP_QSTR_value), (mp_obj_t)&pyb_pin_value_obj }, - { MP_OBJ_NEW_QSTR(MP_QSTR_off), (mp_obj_t)&pyb_pin_off_obj }, - { MP_OBJ_NEW_QSTR(MP_QSTR_on), (mp_obj_t)&pyb_pin_on_obj }, - { MP_OBJ_NEW_QSTR(MP_QSTR_irq), (mp_obj_t)&pyb_pin_irq_obj }, + { MP_ROM_QSTR(MP_QSTR_init), MP_ROM_PTR(&pyb_pin_init_obj) }, + { MP_ROM_QSTR(MP_QSTR_value), MP_ROM_PTR(&pyb_pin_value_obj) }, + { MP_ROM_QSTR(MP_QSTR_off), MP_ROM_PTR(&pyb_pin_off_obj) }, + { MP_ROM_QSTR(MP_QSTR_on), MP_ROM_PTR(&pyb_pin_on_obj) }, + { MP_ROM_QSTR(MP_QSTR_irq), MP_ROM_PTR(&pyb_pin_irq_obj) }, // class constants - { MP_OBJ_NEW_QSTR(MP_QSTR_IN), MP_OBJ_NEW_SMALL_INT(GPIO_MODE_INPUT) }, - { MP_OBJ_NEW_QSTR(MP_QSTR_OUT), MP_OBJ_NEW_SMALL_INT(GPIO_MODE_OUTPUT) }, - { MP_OBJ_NEW_QSTR(MP_QSTR_OPEN_DRAIN), MP_OBJ_NEW_SMALL_INT(GPIO_MODE_OPEN_DRAIN) }, - { MP_OBJ_NEW_QSTR(MP_QSTR_PULL_UP), MP_OBJ_NEW_SMALL_INT(GPIO_PULL_UP) }, - //{ MP_OBJ_NEW_QSTR(MP_QSTR_PULL_DOWN), MP_OBJ_NEW_SMALL_INT(GPIO_PULL_DOWN) }, + { MP_ROM_QSTR(MP_QSTR_IN), MP_ROM_INT(GPIO_MODE_INPUT) }, + { 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) }, - // IRG triggers, can be or'd together - { MP_OBJ_NEW_QSTR(MP_QSTR_IRQ_RISING), MP_OBJ_NEW_SMALL_INT(GPIO_PIN_INTR_POSEDGE) }, - { MP_OBJ_NEW_QSTR(MP_QSTR_IRQ_FALLING), MP_OBJ_NEW_SMALL_INT(GPIO_PIN_INTR_NEGEDGE) }, + // IRQ triggers, can be or'd together + { MP_ROM_QSTR(MP_QSTR_IRQ_RISING), MP_ROM_INT(GPIO_PIN_INTR_POSEDGE) }, + { MP_ROM_QSTR(MP_QSTR_IRQ_FALLING), MP_ROM_INT(GPIO_PIN_INTR_NEGEDGE) }, }; STATIC MP_DEFINE_CONST_DICT(pyb_pin_locals_dict, pyb_pin_locals_dict_table); @@ -437,7 +459,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_t)&pyb_pin_locals_dict, + .locals_dict = (mp_obj_dict_t*)&pyb_pin_locals_dict, }; /******************************************************************************/ diff --git a/esp8266/machine_pwm.c b/esp8266/machine_pwm.c index 5d30f09656..8d73e6bb17 100644 --- a/esp8266/machine_pwm.c +++ b/esp8266/machine_pwm.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/esp8266/machine_rtc.c b/esp8266/machine_rtc.c index b17bcb2616..2ad44318f2 100644 --- a/esp8266/machine_rtc.c +++ b/esp8266/machine_rtc.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -173,7 +173,7 @@ STATIC mp_obj_t pyb_rtc_memory(mp_uint_t n_args, const mp_obj_t *args) { // read RTC memory system_rtc_mem_read(MEM_USER_LEN_ADDR, &len, sizeof(len)); - system_rtc_mem_read(MEM_USER_DATA_ADDR, rtcram, len + (4 - len % 4)); + system_rtc_mem_read(MEM_USER_DATA_ADDR, rtcram, (len + 3) & ~3); return mp_obj_new_bytes(rtcram, len); } else { @@ -195,7 +195,7 @@ STATIC mp_obj_t pyb_rtc_memory(mp_uint_t n_args, const mp_obj_t *args) { rtcram[i] = ((uint8_t *)bufinfo.buf)[i]; } - system_rtc_mem_write(MEM_USER_DATA_ADDR, rtcram, len + (4 - len % 4)); + system_rtc_mem_write(MEM_USER_DATA_ADDR, rtcram, (len + 3) & ~3); return mp_const_none; } @@ -255,13 +255,13 @@ STATIC mp_obj_t pyb_rtc_irq(size_t n_args, const mp_obj_t *pos_args, mp_map_t *k } STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_rtc_irq_obj, 1, pyb_rtc_irq); -STATIC const mp_map_elem_t pyb_rtc_locals_dict_table[] = { - { MP_OBJ_NEW_QSTR(MP_QSTR_datetime), (mp_obj_t)&pyb_rtc_datetime_obj }, - { MP_OBJ_NEW_QSTR(MP_QSTR_memory), (mp_obj_t)&pyb_rtc_memory_obj }, - { MP_OBJ_NEW_QSTR(MP_QSTR_alarm), (mp_obj_t)&pyb_rtc_alarm_obj }, - { MP_OBJ_NEW_QSTR(MP_QSTR_alarm_left), (mp_obj_t)&pyb_rtc_alarm_left_obj }, - { MP_OBJ_NEW_QSTR(MP_QSTR_irq), (mp_obj_t)&pyb_rtc_irq_obj }, - { MP_OBJ_NEW_QSTR(MP_QSTR_ALARM0), MP_OBJ_NEW_SMALL_INT(0) }, +STATIC const mp_rom_map_elem_t pyb_rtc_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_datetime), MP_ROM_PTR(&pyb_rtc_datetime_obj) }, + { MP_ROM_QSTR(MP_QSTR_memory), MP_ROM_PTR(&pyb_rtc_memory_obj) }, + { MP_ROM_QSTR(MP_QSTR_alarm), MP_ROM_PTR(&pyb_rtc_alarm_obj) }, + { MP_ROM_QSTR(MP_QSTR_alarm_left), MP_ROM_PTR(&pyb_rtc_alarm_left_obj) }, + { MP_ROM_QSTR(MP_QSTR_irq), MP_ROM_PTR(&pyb_rtc_irq_obj) }, + { MP_ROM_QSTR(MP_QSTR_ALARM0), MP_ROM_INT(0) }, }; STATIC MP_DEFINE_CONST_DICT(pyb_rtc_locals_dict, pyb_rtc_locals_dict_table); @@ -269,5 +269,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_t)&pyb_rtc_locals_dict, + .locals_dict = (mp_obj_dict_t*)&pyb_rtc_locals_dict, }; diff --git a/esp8266/machine_uart.c b/esp8266/machine_uart.c index 4d9f343db1..e8be5e538c 100644 --- a/esp8266/machine_uart.c +++ b/esp8266/machine_uart.c @@ -104,7 +104,7 @@ STATIC void pyb_uart_init_helper(pyb_uart_obj_t *self, size_t n_args, const mp_o self->bits = 8; break; default: - nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "invalid data bits")); + mp_raise_ValueError("invalid data bits"); break; } @@ -140,7 +140,7 @@ STATIC void pyb_uart_init_helper(pyb_uart_obj_t *self, size_t n_args, const mp_o self->stop = 2; break; default: - nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "invalid stop bits")); + mp_raise_ValueError("invalid stop bits"); break; } @@ -215,7 +215,7 @@ STATIC mp_uint_t pyb_uart_read(mp_obj_t self_in, void *buf_in, mp_uint_t size, i pyb_uart_obj_t *self = MP_OBJ_TO_PTR(self_in); if (self->uart_id == 1) { - nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_OSError, "UART(1) can't read")); + mp_raise_msg(&mp_type_OSError, "UART(1) can't read"); } // make sure we want at least 1 char diff --git a/esp8266/machine_wdt.c b/esp8266/machine_wdt.c index 83b5e8f322..5e23ff7826 100644 --- a/esp8266/machine_wdt.c +++ b/esp8266/machine_wdt.c @@ -71,9 +71,9 @@ STATIC mp_obj_t machine_wdt_deinit(mp_obj_t self_in) { } STATIC MP_DEFINE_CONST_FUN_OBJ_1(machine_wdt_deinit_obj, machine_wdt_deinit); -STATIC const mp_map_elem_t machine_wdt_locals_dict_table[] = { - { MP_OBJ_NEW_QSTR(MP_QSTR_feed), (mp_obj_t)&machine_wdt_feed_obj }, - { MP_OBJ_NEW_QSTR(MP_QSTR_deinit), (mp_obj_t)&machine_wdt_deinit_obj }, +STATIC const mp_rom_map_elem_t machine_wdt_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_feed), MP_ROM_PTR(&machine_wdt_feed_obj) }, + { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&machine_wdt_deinit_obj) }, }; STATIC MP_DEFINE_CONST_DICT(machine_wdt_locals_dict, machine_wdt_locals_dict_table); @@ -81,5 +81,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_t)&machine_wdt_locals_dict, + .locals_dict = (mp_obj_dict_t*)&machine_wdt_locals_dict, }; diff --git a/esp8266/main.c b/esp8266/main.c index e3188dfe40..957198aa05 100644 --- a/esp8266/main.c +++ b/esp8266/main.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -122,7 +122,7 @@ mp_import_stat_t mp_import_stat(const char *path) { return MP_IMPORT_STAT_NO_EXIST; } -mp_obj_t mp_builtin_open(uint n_args, const mp_obj_t *args, mp_map_t *kwargs) { +mp_obj_t mp_builtin_open(size_t n_args, const mp_obj_t *args, mp_map_t *kwargs) { return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_KW(mp_builtin_open_obj, 1, mp_builtin_open); diff --git a/esp8266/modesp.c b/esp8266/modesp.c index 5eaae27d6a..a63d505645 100644 --- a/esp8266/modesp.c +++ b/esp8266/modesp.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -347,50 +347,40 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_2(esp_set_native_code_location_obj, esp_set_nativ #endif -STATIC const mp_map_elem_t esp_module_globals_table[] = { - { MP_OBJ_NEW_QSTR(MP_QSTR___name__), MP_OBJ_NEW_QSTR(MP_QSTR_esp) }, +STATIC const mp_rom_map_elem_t esp_module_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_esp) }, - { MP_OBJ_NEW_QSTR(MP_QSTR_osdebug), (mp_obj_t)&esp_osdebug_obj }, - { MP_OBJ_NEW_QSTR(MP_QSTR_sleep_type), (mp_obj_t)&esp_sleep_type_obj }, - { MP_OBJ_NEW_QSTR(MP_QSTR_deepsleep), (mp_obj_t)&esp_deepsleep_obj }, - { MP_OBJ_NEW_QSTR(MP_QSTR_flash_id), (mp_obj_t)&esp_flash_id_obj }, - { MP_OBJ_NEW_QSTR(MP_QSTR_flash_read), (mp_obj_t)&esp_flash_read_obj }, - { MP_OBJ_NEW_QSTR(MP_QSTR_flash_write), (mp_obj_t)&esp_flash_write_obj }, - { MP_OBJ_NEW_QSTR(MP_QSTR_flash_erase), (mp_obj_t)&esp_flash_erase_obj }, - { MP_OBJ_NEW_QSTR(MP_QSTR_flash_size), (mp_obj_t)&esp_flash_size_obj }, - { MP_OBJ_NEW_QSTR(MP_QSTR_flash_user_start), (mp_obj_t)&esp_flash_user_start_obj }, + { MP_ROM_QSTR(MP_QSTR_osdebug), MP_ROM_PTR(&esp_osdebug_obj) }, + { MP_ROM_QSTR(MP_QSTR_sleep_type), MP_ROM_PTR(&esp_sleep_type_obj) }, + { MP_ROM_QSTR(MP_QSTR_deepsleep), MP_ROM_PTR(&esp_deepsleep_obj) }, + { MP_ROM_QSTR(MP_QSTR_flash_id), MP_ROM_PTR(&esp_flash_id_obj) }, + { MP_ROM_QSTR(MP_QSTR_flash_read), MP_ROM_PTR(&esp_flash_read_obj) }, + { MP_ROM_QSTR(MP_QSTR_flash_write), MP_ROM_PTR(&esp_flash_write_obj) }, + { MP_ROM_QSTR(MP_QSTR_flash_erase), MP_ROM_PTR(&esp_flash_erase_obj) }, + { MP_ROM_QSTR(MP_QSTR_flash_size), MP_ROM_PTR(&esp_flash_size_obj) }, + { MP_ROM_QSTR(MP_QSTR_flash_user_start), MP_ROM_PTR(&esp_flash_user_start_obj) }, #if MICROPY_ESP8266_NEOPIXEL - { MP_OBJ_NEW_QSTR(MP_QSTR_neopixel_write), (mp_obj_t)&esp_neopixel_write_obj }, + { MP_ROM_QSTR(MP_QSTR_neopixel_write), MP_ROM_PTR(&esp_neopixel_write_obj) }, #endif #if MICROPY_ESP8266_APA102 - { MP_OBJ_NEW_QSTR(MP_QSTR_apa102_write), (mp_obj_t)&esp_apa102_write_obj }, + { MP_ROM_QSTR(MP_QSTR_apa102_write), MP_ROM_PTR(&esp_apa102_write_obj) }, #endif - { MP_OBJ_NEW_QSTR(MP_QSTR_dht_readinto), (mp_obj_t)&dht_readinto_obj }, - { MP_OBJ_NEW_QSTR(MP_QSTR_freemem), (mp_obj_t)&esp_freemem_obj }, - { MP_OBJ_NEW_QSTR(MP_QSTR_meminfo), (mp_obj_t)&esp_meminfo_obj }, - { MP_OBJ_NEW_QSTR(MP_QSTR_check_fw), (mp_obj_t)&esp_check_fw_obj }, - { MP_OBJ_NEW_QSTR(MP_QSTR_info), (mp_obj_t)&pyb_info_obj }, // TODO delete/rename/move elsewhere - { MP_OBJ_NEW_QSTR(MP_QSTR_malloc), (mp_obj_t)&esp_malloc_obj }, - { MP_OBJ_NEW_QSTR(MP_QSTR_free), (mp_obj_t)&esp_free_obj }, - { MP_OBJ_NEW_QSTR(MP_QSTR_esf_free_bufs), (mp_obj_t)&esp_esf_free_bufs_obj }, + { MP_ROM_QSTR(MP_QSTR_dht_readinto), MP_ROM_PTR(&dht_readinto_obj) }, + { MP_ROM_QSTR(MP_QSTR_freemem), MP_ROM_PTR(&esp_freemem_obj) }, + { MP_ROM_QSTR(MP_QSTR_meminfo), MP_ROM_PTR(&esp_meminfo_obj) }, + { MP_ROM_QSTR(MP_QSTR_check_fw), MP_ROM_PTR(&esp_check_fw_obj) }, + { MP_ROM_QSTR(MP_QSTR_info), MP_ROM_PTR(&pyb_info_obj) }, // TODO delete/rename/move elsewhere + { MP_ROM_QSTR(MP_QSTR_malloc), MP_ROM_PTR(&esp_malloc_obj) }, + { MP_ROM_QSTR(MP_QSTR_free), MP_ROM_PTR(&esp_free_obj) }, + { MP_ROM_QSTR(MP_QSTR_esf_free_bufs), MP_ROM_PTR(&esp_esf_free_bufs_obj) }, #if MICROPY_EMIT_XTENSA || MICROPY_EMIT_INLINE_XTENSA - { MP_OBJ_NEW_QSTR(MP_QSTR_set_native_code_location), (mp_obj_t)&esp_set_native_code_location_obj }, + { MP_ROM_QSTR(MP_QSTR_set_native_code_location), MP_ROM_PTR(&esp_set_native_code_location_obj) }, #endif #if MODESP_INCLUDE_CONSTANTS - { MP_OBJ_NEW_QSTR(MP_QSTR_SLEEP_NONE), - MP_OBJ_NEW_SMALL_INT(NONE_SLEEP_T) }, - { MP_OBJ_NEW_QSTR(MP_QSTR_SLEEP_LIGHT), - MP_OBJ_NEW_SMALL_INT(LIGHT_SLEEP_T) }, - { MP_OBJ_NEW_QSTR(MP_QSTR_SLEEP_MODEM), - MP_OBJ_NEW_SMALL_INT(MODEM_SLEEP_T) }, - - { MP_OBJ_NEW_QSTR(MP_QSTR_STA_MODE), - MP_OBJ_NEW_SMALL_INT(STATION_MODE)}, - { MP_OBJ_NEW_QSTR(MP_QSTR_AP_MODE), - MP_OBJ_NEW_SMALL_INT(SOFTAP_MODE)}, - { MP_OBJ_NEW_QSTR(MP_QSTR_STA_AP_MODE), - MP_OBJ_NEW_SMALL_INT(STATIONAP_MODE)}, + { 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 }; diff --git a/esp8266/modmachine.c b/esp8266/modmachine.c index c26c633967..070e6fc54c 100644 --- a/esp8266/modmachine.c +++ b/esp8266/modmachine.c @@ -193,12 +193,12 @@ STATIC mp_obj_t esp_timer_deinit(mp_obj_t self_in) { } STATIC MP_DEFINE_CONST_FUN_OBJ_1(esp_timer_deinit_obj, esp_timer_deinit); -STATIC const mp_map_elem_t esp_timer_locals_dict_table[] = { - { MP_OBJ_NEW_QSTR(MP_QSTR_deinit), (mp_obj_t)&esp_timer_deinit_obj }, - { MP_OBJ_NEW_QSTR(MP_QSTR_init), (mp_obj_t)&esp_timer_init_obj }, -// { MP_OBJ_NEW_QSTR(MP_QSTR_callback), (mp_obj_t)&esp_timer_callback_obj }, - { MP_OBJ_NEW_QSTR(MP_QSTR_ONE_SHOT), MP_OBJ_NEW_SMALL_INT(false) }, - { MP_OBJ_NEW_QSTR(MP_QSTR_PERIODIC), MP_OBJ_NEW_SMALL_INT(true) }, +STATIC const mp_rom_map_elem_t esp_timer_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&esp_timer_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR_init), MP_ROM_PTR(&esp_timer_init_obj) }, +// { MP_ROM_QSTR(MP_QSTR_callback), MP_ROM_PTR(&esp_timer_callback_obj) }, + { MP_ROM_QSTR(MP_QSTR_ONE_SHOT), MP_ROM_INT(false) }, + { MP_ROM_QSTR(MP_QSTR_PERIODIC), MP_ROM_INT(true) }, }; STATIC MP_DEFINE_CONST_DICT(esp_timer_locals_dict, esp_timer_locals_dict_table); @@ -207,7 +207,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_t)&esp_timer_locals_dict, + .locals_dict = (mp_obj_dict_t*)&esp_timer_locals_dict, }; // this bit is unused in the Xtensa PS register diff --git a/esp8266/modmachine.h b/esp8266/modmachine.h index 414aaa85b0..eae351f68d 100644 --- a/esp8266/modmachine.h +++ b/esp8266/modmachine.h @@ -1,5 +1,5 @@ -#ifndef __MICROPY_INCLUDED_ESP8266_MODPYB_H__ -#define __MICROPY_INCLUDED_ESP8266_MODPYB_H__ +#ifndef MICROPY_INCLUDED_ESP8266_MODMACHINE_H +#define MICROPY_INCLUDED_ESP8266_MODMACHINE_H #include "py/obj.h" @@ -38,4 +38,4 @@ void pyb_rtc_set_us_since_2000(uint64_t nowus); uint64_t pyb_rtc_get_us_since_2000(); void rtc_prepare_deepsleep(uint64_t sleep_us); -#endif // __MICROPY_INCLUDED_ESP8266_MODPYB_H__ +#endif // MICROPY_INCLUDED_ESP8266_MODMACHINE_H diff --git a/esp8266/modnetwork.c b/esp8266/modnetwork.c index eb9d75e284..283abecafe 100644 --- a/esp8266/modnetwork.c +++ b/esp8266/modnetwork.c @@ -1,9 +1,9 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * - * Copyright (c) 2015 Paul Sokolovsky + * Copyright (c) 2015-2016 Paul Sokolovsky * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -427,15 +427,15 @@ unknown: } STATIC MP_DEFINE_CONST_FUN_OBJ_KW(esp_config_obj, 1, esp_config); -STATIC const mp_map_elem_t wlan_if_locals_dict_table[] = { - { MP_OBJ_NEW_QSTR(MP_QSTR_active), (mp_obj_t)&esp_active_obj }, - { MP_OBJ_NEW_QSTR(MP_QSTR_connect), (mp_obj_t)&esp_connect_obj }, - { MP_OBJ_NEW_QSTR(MP_QSTR_disconnect), (mp_obj_t)&esp_disconnect_obj }, - { MP_OBJ_NEW_QSTR(MP_QSTR_status), (mp_obj_t)&esp_status_obj }, - { MP_OBJ_NEW_QSTR(MP_QSTR_scan), (mp_obj_t)&esp_scan_obj }, - { MP_OBJ_NEW_QSTR(MP_QSTR_isconnected), (mp_obj_t)&esp_isconnected_obj }, - { MP_OBJ_NEW_QSTR(MP_QSTR_config), (mp_obj_t)&esp_config_obj }, - { MP_OBJ_NEW_QSTR(MP_QSTR_ifconfig), (mp_obj_t)&esp_ifconfig_obj }, +STATIC const mp_rom_map_elem_t wlan_if_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_active), MP_ROM_PTR(&esp_active_obj) }, + { MP_ROM_QSTR(MP_QSTR_connect), MP_ROM_PTR(&esp_connect_obj) }, + { MP_ROM_QSTR(MP_QSTR_disconnect), MP_ROM_PTR(&esp_disconnect_obj) }, + { MP_ROM_QSTR(MP_QSTR_status), MP_ROM_PTR(&esp_status_obj) }, + { MP_ROM_QSTR(MP_QSTR_scan), MP_ROM_PTR(&esp_scan_obj) }, + { MP_ROM_QSTR(MP_QSTR_isconnected), MP_ROM_PTR(&esp_isconnected_obj) }, + { MP_ROM_QSTR(MP_QSTR_config), MP_ROM_PTR(&esp_config_obj) }, + { MP_ROM_QSTR(MP_QSTR_ifconfig), MP_ROM_PTR(&esp_ifconfig_obj) }, }; STATIC MP_DEFINE_CONST_DICT(wlan_if_locals_dict, wlan_if_locals_dict_table); @@ -443,7 +443,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_t)&wlan_if_locals_dict, + .locals_dict = (mp_obj_dict_t*)&wlan_if_locals_dict, }; STATIC mp_obj_t esp_phy_mode(mp_uint_t n_args, const mp_obj_t *args) { @@ -456,47 +456,31 @@ STATIC mp_obj_t esp_phy_mode(mp_uint_t n_args, const mp_obj_t *args) { } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(esp_phy_mode_obj, 0, 1, esp_phy_mode); -STATIC const mp_map_elem_t mp_module_network_globals_table[] = { - { MP_OBJ_NEW_QSTR(MP_QSTR___name__), MP_OBJ_NEW_QSTR(MP_QSTR_network) }, - { MP_OBJ_NEW_QSTR(MP_QSTR_WLAN), (mp_obj_t)&get_wlan_obj }, - { MP_OBJ_NEW_QSTR(MP_QSTR_phy_mode), (mp_obj_t)&esp_phy_mode_obj }, +STATIC const mp_rom_map_elem_t mp_module_network_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_network) }, + { 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 - { MP_OBJ_NEW_QSTR(MP_QSTR_STA_IF), - MP_OBJ_NEW_SMALL_INT(STATION_IF)}, - { MP_OBJ_NEW_QSTR(MP_QSTR_AP_IF), - MP_OBJ_NEW_SMALL_INT(SOFTAP_IF)}, + { MP_ROM_QSTR(MP_QSTR_STA_IF), MP_ROM_INT(STATION_IF)}, + { MP_ROM_QSTR(MP_QSTR_AP_IF), MP_ROM_INT(SOFTAP_IF)}, - { MP_OBJ_NEW_QSTR(MP_QSTR_STAT_IDLE), - MP_OBJ_NEW_SMALL_INT(STATION_IDLE)}, - { MP_OBJ_NEW_QSTR(MP_QSTR_STAT_CONNECTING), - MP_OBJ_NEW_SMALL_INT(STATION_CONNECTING)}, - { MP_OBJ_NEW_QSTR(MP_QSTR_STAT_WRONG_PASSWORD), - MP_OBJ_NEW_SMALL_INT(STATION_WRONG_PASSWORD)}, - { MP_OBJ_NEW_QSTR(MP_QSTR_STAT_NO_AP_FOUND), - MP_OBJ_NEW_SMALL_INT(STATION_NO_AP_FOUND)}, - { MP_OBJ_NEW_QSTR(MP_QSTR_STAT_CONNECT_FAIL), - MP_OBJ_NEW_SMALL_INT(STATION_CONNECT_FAIL)}, - { MP_OBJ_NEW_QSTR(MP_QSTR_STAT_GOT_IP), - MP_OBJ_NEW_SMALL_INT(STATION_GOT_IP)}, + { MP_ROM_QSTR(MP_QSTR_STAT_IDLE), MP_ROM_INT(STATION_IDLE)}, + { MP_ROM_QSTR(MP_QSTR_STAT_CONNECTING), MP_ROM_INT(STATION_CONNECTING)}, + { MP_ROM_QSTR(MP_QSTR_STAT_WRONG_PASSWORD), MP_ROM_INT(STATION_WRONG_PASSWORD)}, + { MP_ROM_QSTR(MP_QSTR_STAT_NO_AP_FOUND), MP_ROM_INT(STATION_NO_AP_FOUND)}, + { MP_ROM_QSTR(MP_QSTR_STAT_CONNECT_FAIL), MP_ROM_INT(STATION_CONNECT_FAIL)}, + { MP_ROM_QSTR(MP_QSTR_STAT_GOT_IP), MP_ROM_INT(STATION_GOT_IP)}, - { MP_OBJ_NEW_QSTR(MP_QSTR_MODE_11B), - MP_OBJ_NEW_SMALL_INT(PHY_MODE_11B) }, - { MP_OBJ_NEW_QSTR(MP_QSTR_MODE_11G), - MP_OBJ_NEW_SMALL_INT(PHY_MODE_11G) }, - { MP_OBJ_NEW_QSTR(MP_QSTR_MODE_11N), - MP_OBJ_NEW_SMALL_INT(PHY_MODE_11N) }, + { MP_ROM_QSTR(MP_QSTR_MODE_11B), MP_ROM_INT(PHY_MODE_11B) }, + { MP_ROM_QSTR(MP_QSTR_MODE_11G), MP_ROM_INT(PHY_MODE_11G) }, + { MP_ROM_QSTR(MP_QSTR_MODE_11N), MP_ROM_INT(PHY_MODE_11N) }, - { MP_OBJ_NEW_QSTR(MP_QSTR_AUTH_OPEN), - MP_OBJ_NEW_SMALL_INT(AUTH_OPEN) }, - { MP_OBJ_NEW_QSTR(MP_QSTR_AUTH_WEP), - MP_OBJ_NEW_SMALL_INT(AUTH_WEP) }, - { MP_OBJ_NEW_QSTR(MP_QSTR_AUTH_WPA_PSK), - MP_OBJ_NEW_SMALL_INT(AUTH_WPA_PSK) }, - { MP_OBJ_NEW_QSTR(MP_QSTR_AUTH_WPA2_PSK), - MP_OBJ_NEW_SMALL_INT(AUTH_WPA2_PSK) }, - { MP_OBJ_NEW_QSTR(MP_QSTR_AUTH_WPA_WPA2_PSK), - MP_OBJ_NEW_SMALL_INT(AUTH_WPA_WPA2_PSK) }, + { MP_ROM_QSTR(MP_QSTR_AUTH_OPEN), MP_ROM_INT(AUTH_OPEN) }, + { MP_ROM_QSTR(MP_QSTR_AUTH_WEP), MP_ROM_INT(AUTH_WEP) }, + { 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 }; diff --git a/esp8266/modpyb.c b/esp8266/modpyb.c index 9fe8039bc6..e977191ee6 100644 --- a/esp8266/modpyb.c +++ b/esp8266/modpyb.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/esp8266/modules/ds18x20.py b/esp8266/modules/ds18x20.py deleted file mode 100644 index bf06094835..0000000000 --- a/esp8266/modules/ds18x20.py +++ /dev/null @@ -1,51 +0,0 @@ -# DS18x20 temperature sensor driver for MicroPython. -# MIT license; Copyright (c) 2016 Damien P. George - -from micropython import const - -_CONVERT = const(0x44) -_RD_SCRATCH = const(0xbe) -_WR_SCRATCH = const(0x4e) - -class DS18X20: - def __init__(self, onewire): - self.ow = onewire - self.buf = bytearray(9) - - def scan(self): - return [rom for rom in self.ow.scan() if rom[0] == 0x10 or rom[0] == 0x28] - - def convert_temp(self): - self.ow.reset(True) - self.ow.writebyte(self.ow.SKIP_ROM) - self.ow.writebyte(_CONVERT) - - def read_scratch(self, rom): - self.ow.reset(True) - self.ow.select_rom(rom) - self.ow.writebyte(_RD_SCRATCH) - self.ow.readinto(self.buf) - if self.ow.crc8(self.buf): - raise Exception('CRC error') - return self.buf - - def write_scratch(self, rom, buf): - self.ow.reset(True) - self.ow.select_rom(rom) - self.ow.writebyte(_WR_SCRATCH) - self.ow.write(buf) - - def read_temp(self, rom): - buf = self.read_scratch(rom) - if rom[0] == 0x10: - if buf[1]: - t = buf[0] >> 1 | 0x80 - t = -((~t + 1) & 0xff) - else: - t = buf[0] >> 1 - return t - 0.25 + (buf[7] - buf[6]) / buf[7] - else: - t = buf[1] << 8 | buf[0] - if t & 0x8000: # sign bit set - t = -((t ^ 0xffff) + 1) - return t / 16 diff --git a/esp8266/modules/ds18x20.py b/esp8266/modules/ds18x20.py new file mode 120000 index 0000000000..faae59d909 --- /dev/null +++ b/esp8266/modules/ds18x20.py @@ -0,0 +1 @@ +../../drivers/onewire/ds18x20.py \ No newline at end of file diff --git a/esp8266/modules/onewire.py b/esp8266/modules/onewire.py deleted file mode 100644 index 83318d1a47..0000000000 --- a/esp8266/modules/onewire.py +++ /dev/null @@ -1,91 +0,0 @@ -# 1-Wire driver for MicroPython on ESP8266 -# MIT license; Copyright (c) 2016 Damien P. George - -from micropython import const -import _onewire as _ow - -class OneWireError(Exception): - pass - -class OneWire: - SEARCH_ROM = const(0xf0) - MATCH_ROM = const(0x55) - SKIP_ROM = const(0xcc) - - def __init__(self, pin): - self.pin = pin - self.pin.init(pin.OPEN_DRAIN) - - def reset(self, required=False): - reset = _ow.reset(self.pin) - if required and not reset: - raise OneWireError - return reset - - def readbit(self): - return _ow.readbit(self.pin) - - def readbyte(self): - return _ow.readbyte(self.pin) - - def readinto(self, buf): - for i in range(len(buf)): - buf[i] = _ow.readbyte(self.pin) - - def writebit(self, value): - return _ow.writebit(self.pin, value) - - def writebyte(self, value): - return _ow.writebyte(self.pin, value) - - def write(self, buf): - for b in buf: - _ow.writebyte(self.pin, b) - - def select_rom(self, rom): - self.reset() - self.writebyte(MATCH_ROM) - self.write(rom) - - def scan(self): - devices = [] - diff = 65 - rom = False - for i in range(0xff): - rom, diff = self._search_rom(rom, diff) - if rom: - devices += [rom] - if diff == 0: - break - return devices - - def _search_rom(self, l_rom, diff): - if not self.reset(): - return None, 0 - self.writebyte(SEARCH_ROM) - if not l_rom: - l_rom = bytearray(8) - rom = bytearray(8) - next_diff = 0 - i = 64 - for byte in range(8): - r_b = 0 - for bit in range(8): - b = self.readbit() - if self.readbit(): - if b: # there are no devices or there is an error on the bus - return None, 0 - else: - if not b: # collision, two devices with different bit meaning - if diff > i or ((l_rom[byte] & (1 << bit)) and diff != i): - b = 1 - next_diff = i - self.writebit(b) - if b: - r_b |= 1 << bit - i -= 1 - rom[byte] = r_b - return rom, next_diff - - def crc8(self, data): - return _ow.crc8(data) diff --git a/esp8266/modules/onewire.py b/esp8266/modules/onewire.py new file mode 120000 index 0000000000..f6ec745e85 --- /dev/null +++ b/esp8266/modules/onewire.py @@ -0,0 +1 @@ +../../drivers/onewire/onewire.py \ No newline at end of file diff --git a/esp8266/moduos.c b/esp8266/moduos.c index 807d2e18a5..d0554096ed 100644 --- a/esp8266/moduos.c +++ b/esp8266/moduos.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/esp8266/modutime.c b/esp8266/modutime.c index bdeb3bb453..afb14dfd6a 100644 --- a/esp8266/modutime.c +++ b/esp8266/modutime.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/esp8266/mpconfigport.h b/esp8266/mpconfigport.h index 483f93d02b..bbded43f4b 100644 --- a/esp8266/mpconfigport.h +++ b/esp8266/mpconfigport.h @@ -1,6 +1,6 @@ #include -// options to control how Micro Python is built +// options to control how MicroPython is built #define MICROPY_OBJ_REPR (MICROPY_OBJ_REPR_C) #define MICROPY_ALLOC_PATH_MAX (128) @@ -17,6 +17,7 @@ #define MICROPY_DEBUG_PRINTER_DEST mp_debug_print #define MICROPY_READER_VFS (MICROPY_VFS) #define MICROPY_ENABLE_GC (1) +#define MICROPY_ENABLE_FINALISER (1) #define MICROPY_STACK_CHECK (1) #define MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF (1) #define MICROPY_KBD_EXCEPTION (1) @@ -157,17 +158,16 @@ extern const struct _mp_obj_module_t utime_module; extern const struct _mp_obj_module_t uos_module; extern const struct _mp_obj_module_t mp_module_lwip; extern const struct _mp_obj_module_t mp_module_machine; -extern const struct _mp_obj_module_t onewire_module; +extern const struct _mp_obj_module_t mp_module_onewire; #define MICROPY_PORT_BUILTIN_MODULES \ { MP_OBJ_NEW_QSTR(MP_QSTR_esp), (mp_obj_t)&esp_module }, \ - { MP_OBJ_NEW_QSTR(MP_QSTR_socket), (mp_obj_t)&mp_module_lwip }, \ { MP_OBJ_NEW_QSTR(MP_QSTR_usocket), (mp_obj_t)&mp_module_lwip }, \ { MP_OBJ_NEW_QSTR(MP_QSTR_network), (mp_obj_t)&network_module }, \ { MP_OBJ_NEW_QSTR(MP_QSTR_utime), (mp_obj_t)&utime_module }, \ { MP_OBJ_NEW_QSTR(MP_QSTR_uos), (mp_obj_t)&uos_module }, \ { MP_OBJ_NEW_QSTR(MP_QSTR_machine), (mp_obj_t)&mp_module_machine }, \ - { MP_OBJ_NEW_QSTR(MP_QSTR__onewire), (mp_obj_t)&onewire_module }, \ + { MP_OBJ_NEW_QSTR(MP_QSTR__onewire), (mp_obj_t)&mp_module_onewire }, \ #define MICROPY_PORT_BUILTIN_MODULE_WEAK_LINKS \ { MP_OBJ_NEW_QSTR(MP_QSTR_time), (mp_obj_t)&utime_module }, \ @@ -175,6 +175,7 @@ extern const struct _mp_obj_module_t onewire_module; { MP_OBJ_NEW_QSTR(MP_QSTR_json), (mp_obj_t)&mp_module_ujson }, \ { MP_OBJ_NEW_QSTR(MP_QSTR_errno), (mp_obj_t)&mp_module_uerrno }, \ { MP_OBJ_NEW_QSTR(MP_QSTR_select), (mp_obj_t)&mp_module_uselect }, \ + { MP_OBJ_NEW_QSTR(MP_QSTR_socket), (mp_obj_t)&mp_module_lwip }, \ #define MP_STATE_PORT MP_STATE_VM diff --git a/esp8266/mpconfigport_512k.h b/esp8266/mpconfigport_512k.h index 322fb4151a..b84c134792 100644 --- a/esp8266/mpconfigport_512k.h +++ b/esp8266/mpconfigport_512k.h @@ -5,6 +5,9 @@ #undef MICROPY_EMIT_INLINE_XTENSA #define MICROPY_EMIT_INLINE_XTENSA (0) +#undef MICROPY_ERROR_REPORTING +#define MICROPY_ERROR_REPORTING (MICROPY_ERROR_REPORTING_TERSE) + #undef MICROPY_VFS #define MICROPY_VFS (0) #undef MICROPY_VFS_FAT diff --git a/esp8266/qstrdefsport.h b/esp8266/qstrdefsport.h index 7610eb33da..8f301a69c5 100644 --- a/esp8266/qstrdefsport.h +++ b/esp8266/qstrdefsport.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/esp8266/uart.h b/esp8266/uart.h index f6850c42db..ebcd8b051a 100644 --- a/esp8266/uart.h +++ b/esp8266/uart.h @@ -1,5 +1,5 @@ -#ifndef _INCLUDED_UART_H_ -#define _INCLUDED_UART_H_ +#ifndef MICROPY_INCLUDED_ESP8266_UART_H +#define MICROPY_INCLUDED_ESP8266_UART_H #include @@ -103,4 +103,4 @@ void uart_setup(uint8 uart); int uart_rx_any(uint8 uart); int uart_tx_any_room(uint8 uart); -#endif // _INCLUDED_UART_H_ +#endif // MICROPY_INCLUDED_ESP8266_UART_H diff --git a/esp8266/xtirq.h b/esp8266/xtirq.h index 856ff075ac..595052fc73 100644 --- a/esp8266/xtirq.h +++ b/esp8266/xtirq.h @@ -23,9 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - -#ifndef __MICROPY_INCLUDED_ESP8266_XTIRQ_H__ -#define __MICROPY_INCLUDED_ESP8266_XTIRQ_H__ +#ifndef MICROPY_INCLUDED_ESP8266_XTIRQ_H +#define MICROPY_INCLUDED_ESP8266_XTIRQ_H #include @@ -57,4 +56,4 @@ static inline void enable_irq(uint32_t irq_state) { restore_irq_pri(irq_state); } -#endif // __MICROPY_INCLUDED_ESP8266_XTIRQ_H__ +#endif // MICROPY_INCLUDED_ESP8266_XTIRQ_H diff --git a/examples/embedding/Makefile.upylib b/examples/embedding/Makefile.upylib index 4663ad30ab..a9b6535170 100644 --- a/examples/embedding/Makefile.upylib +++ b/examples/embedding/Makefile.upylib @@ -55,8 +55,8 @@ CFLAGS += -U _FORTIFY_SOURCE endif # On OSX, 'gcc' is a symlink to clang unless a real gcc is installed. -# The unix port of micropython on OSX must be compiled with clang, -# while cross-compile ports require gcc, so we test here for OSX and +# The unix port of MicroPython on OSX must be compiled with clang, +# while cross-compile ports require gcc, so we test here for OSX and # if necessary override the value of 'CC' set in py/mkenv.mk ifeq ($(UNAME_S),Darwin) CC = clang diff --git a/examples/embedding/hello-embed.c b/examples/embedding/hello-embed.c index e3a4847835..3473e5bcd8 100644 --- a/examples/embedding/hello-embed.c +++ b/examples/embedding/hello-embed.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/examples/embedding/mpconfigport_minimal.h b/examples/embedding/mpconfigport_minimal.h index 87c87fa971..5b96aa4b01 100644 --- a/examples/embedding/mpconfigport_minimal.h +++ b/examples/embedding/mpconfigport_minimal.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -24,7 +24,7 @@ * THE SOFTWARE. */ -// options to control how Micro Python is built +// options to control how MicroPython is built #define MICROPY_ALLOC_PATH_MAX (PATH_MAX) #define MICROPY_ENABLE_GC (1) diff --git a/extmod/lwip-include/arch/cc.h b/extmod/lwip-include/arch/cc.h index 0a7907d347..400dc6ec75 100644 --- a/extmod/lwip-include/arch/cc.h +++ b/extmod/lwip-include/arch/cc.h @@ -1,5 +1,5 @@ -#ifndef __CC_H__ -#define __CC_H__ +#ifndef MICROPY_INCLUDED_EXTMOD_LWIP_INCLUDE_ARCH_CC_H +#define MICROPY_INCLUDED_EXTMOD_LWIP_INCLUDE_ARCH_CC_H #include @@ -38,4 +38,4 @@ typedef u32_t mem_ptr_t; #define PACK_STRUCT_BEGIN #define PACK_STRUCT_END -#endif /* __ARCH_CC_H__ */ +#endif // MICROPY_INCLUDED_EXTMOD_LWIP_INCLUDE_ARCH_CC_H diff --git a/extmod/lwip-include/arch/perf.h b/extmod/lwip-include/arch/perf.h index 51710701a2..d310fc339f 100644 --- a/extmod/lwip-include/arch/perf.h +++ b/extmod/lwip-include/arch/perf.h @@ -1,7 +1,7 @@ -#ifndef __PERF_H__ -#define __PERF_H__ +#ifndef MICROPY_INCLUDED_EXTMOD_LWIP_INCLUDE_ARCH_PERF_H +#define MICROPY_INCLUDED_EXTMOD_LWIP_INCLUDE_ARCH_PERF_H #define PERF_START /* null definition */ #define PERF_STOP(x) /* null definition */ -#endif /* __PERF_H__ */ +#endif // MICROPY_INCLUDED_EXTMOD_LWIP_INCLUDE_ARCH_PERF_H diff --git a/extmod/lwip-include/lwipopts.h b/extmod/lwip-include/lwipopts.h index e4a33b2381..2122f30f04 100644 --- a/extmod/lwip-include/lwipopts.h +++ b/extmod/lwip-include/lwipopts.h @@ -1,5 +1,5 @@ -#ifndef __LWIPOPTS_H__ -#define __LWIPOPTS_H__ +#ifndef MICROPY_INCLUDED_EXTMOD_LWIP_INCLUDE_LWIPOPTS_H +#define MICROPY_INCLUDED_EXTMOD_LWIP_INCLUDE_LWIPOPTS_H #include #include @@ -32,5 +32,4 @@ typedef uint32_t sys_prot_t; // things like this into a port-provided header file. #define sys_now mp_hal_ticks_ms -#endif - +#endif // MICROPY_INCLUDED_EXTMOD_LWIP_INCLUDE_LWIPOPTS_H diff --git a/extmod/machine_i2c.h b/extmod/machine_i2c.h index d49ff01e46..f5af6656f5 100644 --- a/extmod/machine_i2c.h +++ b/extmod/machine_i2c.h @@ -23,9 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - -#ifndef __MICROPY_INCLUDED_EXTMOD_MACHINE_I2C_H__ -#define __MICROPY_INCLUDED_EXTMOD_MACHINE_I2C_H__ +#ifndef MICROPY_INCLUDED_EXTMOD_MACHINE_I2C_H +#define MICROPY_INCLUDED_EXTMOD_MACHINE_I2C_H #include "py/obj.h" @@ -54,4 +53,4 @@ extern const mp_obj_dict_t mp_machine_soft_i2c_locals_dict; int mp_machine_soft_i2c_readfrom(mp_obj_base_t *self_in, uint16_t addr, uint8_t *dest, size_t len, bool stop); int mp_machine_soft_i2c_writeto(mp_obj_base_t *self_in, uint16_t addr, const uint8_t *src, size_t len, bool stop); -#endif // __MICROPY_INCLUDED_EXTMOD_MACHINE_I2C_H__ +#endif // MICROPY_INCLUDED_EXTMOD_MACHINE_I2C_H diff --git a/extmod/machine_mem.c b/extmod/machine_mem.c index 88c176803f..af987cb7f7 100644 --- a/extmod/machine_mem.c +++ b/extmod/machine_mem.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/extmod/machine_mem.h b/extmod/machine_mem.h index fddd7d46c1..a48a52c820 100644 --- a/extmod/machine_mem.h +++ b/extmod/machine_mem.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,10 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - - -#ifndef __MICROPY_INCLUDED_EXTMOD_MACHINE_MEM_H__ -#define __MICROPY_INCLUDED_EXTMOD_MACHINE_MEM_H__ +#ifndef MICROPY_INCLUDED_EXTMOD_MACHINE_MEM_H +#define MICROPY_INCLUDED_EXTMOD_MACHINE_MEM_H #include "py/obj.h" @@ -48,4 +46,4 @@ uintptr_t MICROPY_MACHINE_MEM_GET_READ_ADDR(mp_obj_t addr_o, uint align); uintptr_t MICROPY_MACHINE_MEM_GET_WRITE_ADDR(mp_obj_t addr_o, uint align); #endif -#endif // __MICROPY_INCLUDED_EXTMOD_MACHINE_MEM_H__ +#endif // MICROPY_INCLUDED_EXTMOD_MACHINE_MEM_H diff --git a/extmod/machine_pinbase.h b/extmod/machine_pinbase.h index ece3384cc6..c96abbc46c 100644 --- a/extmod/machine_pinbase.h +++ b/extmod/machine_pinbase.h @@ -23,13 +23,11 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - - -#ifndef __MICROPY_INCLUDED_EXTMOD_MACHINE_PINBASE_H__ -#define __MICROPY_INCLUDED_EXTMOD_MACHINE_PINBASE_H__ +#ifndef MICROPY_INCLUDED_EXTMOD_MACHINE_PINBASE_H +#define MICROPY_INCLUDED_EXTMOD_MACHINE_PINBASE_H #include "py/obj.h" extern const mp_obj_type_t machine_pinbase_type; -#endif // __MICROPY_INCLUDED_EXTMOD_MACHINE_PINBASE_H__ +#endif // MICROPY_INCLUDED_EXTMOD_MACHINE_PINBASE_H diff --git a/extmod/machine_pulse.h b/extmod/machine_pulse.h index cc1c4eda5f..e303dca02e 100644 --- a/extmod/machine_pulse.h +++ b/extmod/machine_pulse.h @@ -23,9 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - -#ifndef __MICROPY_INCLUDED_EXTMOD_MACHINE_PULSE_H__ -#define __MICROPY_INCLUDED_EXTMOD_MACHINE_PULSE_H__ +#ifndef MICROPY_INCLUDED_EXTMOD_MACHINE_PULSE_H +#define MICROPY_INCLUDED_EXTMOD_MACHINE_PULSE_H #include "py/obj.h" #include "py/mphal.h" @@ -34,4 +33,4 @@ mp_uint_t machine_time_pulse_us(mp_hal_pin_obj_t pin, int pulse_level, mp_uint_t MP_DECLARE_CONST_FUN_OBJ_VAR_BETWEEN(machine_time_pulse_us_obj); -#endif // __MICROPY_INCLUDED_EXTMOD_MACHINE_PULSE_H__ +#endif // MICROPY_INCLUDED_EXTMOD_MACHINE_PULSE_H diff --git a/extmod/machine_signal.c b/extmod/machine_signal.c index d089312962..78d0c3feef 100644 --- a/extmod/machine_signal.c +++ b/extmod/machine_signal.c @@ -96,7 +96,7 @@ STATIC mp_obj_t signal_make_new(const mp_obj_type_t *type, size_t n_args, size_t if (n_args == 1) { if (n_kw == 0) { } else if (n_kw == 1 && args[1] == MP_OBJ_NEW_QSTR(MP_QSTR_invert)) { - invert = mp_obj_is_true(args[1]); + invert = mp_obj_is_true(args[2]); } else { goto error; } diff --git a/extmod/machine_signal.h b/extmod/machine_signal.h index 7f88cbaa87..df1c3e2e90 100644 --- a/extmod/machine_signal.h +++ b/extmod/machine_signal.h @@ -23,13 +23,11 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - - -#ifndef __MICROPY_INCLUDED_EXTMOD_MACHINE_SIGNAL_H__ -#define __MICROPY_INCLUDED_EXTMOD_MACHINE_SIGNAL_H__ +#ifndef MICROPY_INCLUDED_EXTMOD_MACHINE_SIGNAL_H +#define MICROPY_INCLUDED_EXTMOD_MACHINE_SIGNAL_H #include "py/obj.h" extern const mp_obj_type_t machine_signal_type; -#endif // __MICROPY_INCLUDED_EXTMOD_MACHINE_SIGNAL_H__ +#endif // MICROPY_INCLUDED_EXTMOD_MACHINE_SIGNAL_H diff --git a/extmod/machine_spi.h b/extmod/machine_spi.h index 88a3e19f41..e24e41eb3d 100644 --- a/extmod/machine_spi.h +++ b/extmod/machine_spi.h @@ -23,7 +23,6 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - #ifndef MICROPY_INCLUDED_EXTMOD_MACHINE_SPI_H #define MICROPY_INCLUDED_EXTMOD_MACHINE_SPI_H diff --git a/extmod/misc.h b/extmod/misc.h index d7ead06549..6c13592c75 100644 --- a/extmod/misc.h +++ b/extmod/misc.h @@ -24,6 +24,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ +#ifndef MICROPY_INCLUDED_EXTMOD_MISC_H +#define MICROPY_INCLUDED_EXTMOD_MISC_H // This file contains cumulative declarations for extmod/ . @@ -38,3 +40,5 @@ void mp_uos_deactivate(const char *msg, mp_obj_t exc); #else #define mp_uos_dupterm_tx_strn(s, l) #endif + +#endif // MICROPY_INCLUDED_EXTMOD_MISC_H diff --git a/extmod/modbtree.c b/extmod/modbtree.c index 127dd71a39..229daaf0f9 100644 --- a/extmod/modbtree.c +++ b/extmod/modbtree.c @@ -26,7 +26,7 @@ #include #include -#include +#include // for declaration of global errno variable #include #include "py/nlr.h" diff --git a/extmod/modframebuf.c b/extmod/modframebuf.c index b8e84fe1c6..f4e8571297 100644 --- a/extmod/modframebuf.c +++ b/extmod/modframebuf.c @@ -62,10 +62,10 @@ typedef struct _mp_framebuf_p_t { // Functions for MHLSB and MHMSB -STATIC void mono_horiz_setpixel(const mp_obj_framebuf_t *fb, int x, int y, uint32_t color) { +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)) | ((color != 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) { @@ -90,10 +90,10 @@ STATIC void mono_horiz_fill_rect(const mp_obj_framebuf_t *fb, int x, int y, int // Functions for MVLSB format -STATIC void mvlsb_setpixel(const mp_obj_framebuf_t *fb, int x, int y, uint32_t color) { +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)) | ((color != 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) { @@ -114,19 +114,19 @@ 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 color) { - ((uint16_t*)fb->buf)[x + y * fb->stride] = color; +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; } STATIC uint32_t rgb565_getpixel(const mp_obj_framebuf_t *fb, int x, int y) { 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 colour) { +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]; while (h--) { for (int ww = w; ww; --ww) { - *b++ = colour; + *b++ = col; } b += fb->stride - w; } @@ -156,7 +156,7 @@ STATIC void gs4_hmsb_fill_rect(const mp_obj_framebuf_t *fb, int x, int y, int w, col &= 0x0f; uint8_t *pixel_pair = &((uint8_t*)fb->buf)[(x + y * fb->stride) >> 1]; uint8_t col_shifted_left = col << 4; - uint8_t colored_pixel_pair = col_shifted_left | col; + uint8_t col_pixel_pair = col_shifted_left | col; int pixel_count_till_next_line = (fb->stride - w) >> 1; bool odd_x = (x % 2 == 1); @@ -169,7 +169,7 @@ STATIC void gs4_hmsb_fill_rect(const mp_obj_framebuf_t *fb, int x, int y, int w, ww--; } - memset(pixel_pair, colored_pixel_pair, ww >> 1); + memset(pixel_pair, col_pixel_pair, ww >> 1); pixel_pair += ww >> 1; if (ww % 2) { @@ -191,8 +191,8 @@ STATIC mp_framebuf_p_t formats[] = { [FRAMEBUF_MHMSB] = {mono_horiz_setpixel, mono_horiz_getpixel, mono_horiz_fill_rect}, }; -static inline void setpixel(const mp_obj_framebuf_t *fb, int x, int y, uint32_t color) { - formats[fb->format].setpixel(fb, x, y, color); +static inline void setpixel(const mp_obj_framebuf_t *fb, int x, int y, uint32_t col) { + formats[fb->format].setpixel(fb, x, y, col); } static inline uint32_t getpixel(const mp_obj_framebuf_t *fb, int x, int y) { @@ -237,15 +237,16 @@ STATIC mp_obj_t framebuf_make_new(const mp_obj_type_t *type, size_t n_args, size switch (o->format) { case FRAMEBUF_MVLSB: case FRAMEBUF_RGB565: - case FRAMEBUF_GS4_HMSB: break; case FRAMEBUF_MHLSB: case FRAMEBUF_MHMSB: o->stride = (o->stride + 7) & ~7; break; + case FRAMEBUF_GS4_HMSB: + o->stride = (o->stride + 1) & ~1; + break; default: - nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, - "invalid format")); + mp_raise_ValueError("invalid format"); } return MP_OBJ_FROM_PTR(o); @@ -276,9 +277,9 @@ STATIC mp_obj_t framebuf_fill_rect(size_t n_args, const mp_obj_t *args) { mp_int_t y = mp_obj_get_int(args[2]); mp_int_t width = mp_obj_get_int(args[3]); mp_int_t height = mp_obj_get_int(args[4]); - mp_int_t color = mp_obj_get_int(args[5]); + mp_int_t col = mp_obj_get_int(args[5]); - fill_rect(self, x, y, width, height, color); + fill_rect(self, x, y, width, height, col); return mp_const_none; } @@ -443,14 +444,13 @@ STATIC mp_obj_t framebuf_blit(size_t n_args, const mp_obj_t *args) { int y1 = MAX(0, -y); int x0end = MIN(self->width, x + source->width); int y0end = MIN(self->height, y + source->height); - uint32_t color; for (; y0 < y0end; ++y0) { int cx1 = x1; for (int cx0 = x0; cx0 < x0end; ++cx0) { - color = getpixel(source, cx1, y1); - if (color != key) { - setpixel(self, cx0, y0, color); + uint32_t col = getpixel(source, cx1, y1); + if (col != (uint32_t)key) { + setpixel(self, cx0, y0, col); } ++cx1; } @@ -549,7 +549,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_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 @@ -578,12 +578,12 @@ STATIC const mp_rom_map_elem_t framebuf_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_framebuf) }, { MP_ROM_QSTR(MP_QSTR_FrameBuffer), MP_ROM_PTR(&mp_type_framebuf) }, { MP_ROM_QSTR(MP_QSTR_FrameBuffer1), MP_ROM_PTR(&legacy_framebuffer1_obj) }, - { MP_ROM_QSTR(MP_QSTR_MVLSB), MP_OBJ_NEW_SMALL_INT(FRAMEBUF_MVLSB) }, - { MP_ROM_QSTR(MP_QSTR_MONO_VLSB), MP_OBJ_NEW_SMALL_INT(FRAMEBUF_MVLSB) }, - { MP_ROM_QSTR(MP_QSTR_RGB565), MP_OBJ_NEW_SMALL_INT(FRAMEBUF_RGB565) }, - { MP_ROM_QSTR(MP_QSTR_GS4_HMSB), MP_OBJ_NEW_SMALL_INT(FRAMEBUF_GS4_HMSB) }, - { MP_ROM_QSTR(MP_QSTR_MONO_HLSB), MP_OBJ_NEW_SMALL_INT(FRAMEBUF_MHLSB) }, - { MP_ROM_QSTR(MP_QSTR_MONO_HMSB), MP_OBJ_NEW_SMALL_INT(FRAMEBUF_MHMSB) }, + { MP_ROM_QSTR(MP_QSTR_MVLSB), MP_ROM_INT(FRAMEBUF_MVLSB) }, + { MP_ROM_QSTR(MP_QSTR_MONO_VLSB), MP_ROM_INT(FRAMEBUF_MVLSB) }, + { MP_ROM_QSTR(MP_QSTR_RGB565), MP_ROM_INT(FRAMEBUF_RGB565) }, + { MP_ROM_QSTR(MP_QSTR_GS4_HMSB), MP_ROM_INT(FRAMEBUF_GS4_HMSB) }, + { MP_ROM_QSTR(MP_QSTR_MONO_HLSB), MP_ROM_INT(FRAMEBUF_MHLSB) }, + { MP_ROM_QSTR(MP_QSTR_MONO_HMSB), MP_ROM_INT(FRAMEBUF_MHMSB) }, }; STATIC MP_DEFINE_CONST_DICT(framebuf_module_globals, framebuf_module_globals_table); diff --git a/extmod/modlwip.c b/extmod/modlwip.c index 01190d200c..bde251ccac 100644 --- a/extmod/modlwip.c +++ b/extmod/modlwip.c @@ -5,7 +5,7 @@ * * Copyright (c) 2013, 2014 Damien P. George * Copyright (c) 2015 Galen Hazelwood - * Copyright (c) 2015-2016 Paul Sokolovsky + * Copyright (c) 2015-2017 Paul Sokolovsky * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -45,6 +45,7 @@ //#include "lwip/raw.h" #include "lwip/dns.h" #include "lwip/tcp_impl.h" +#include "lwip/igmp.h" #if 0 // print debugging info #define DEBUG_printf DEBUG_printf @@ -52,6 +53,10 @@ #define DEBUG_printf(...) (void)0 #endif +// All socket options should be globally distinct, +// because we ignore option levels for efficiency. +#define IP_ADD_MEMBERSHIP 0x400 + // For compatibilily with older lwIP versions. #ifndef ip_set_option #define ip_set_option(pcb, opt) ((pcb)->so_options |= (opt)) @@ -148,8 +153,8 @@ STATIC mp_obj_t lwip_slip_status(mp_obj_t self_in) { STATIC MP_DEFINE_CONST_FUN_OBJ_1(lwip_slip_status_obj, lwip_slip_status); -STATIC const mp_map_elem_t lwip_slip_locals_dict_table[] = { - { MP_OBJ_NEW_QSTR(MP_QSTR_status), (mp_obj_t)&lwip_slip_status_obj }, +STATIC const mp_rom_map_elem_t lwip_slip_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_status), MP_ROM_PTR(&lwip_slip_status_obj) }, }; STATIC MP_DEFINE_CONST_DICT(lwip_slip_locals_dict, lwip_slip_locals_dict_table); @@ -158,7 +163,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_t)&lwip_slip_locals_dict, + .locals_dict = (mp_obj_dict_t*)&lwip_slip_locals_dict, }; #endif // MICROPY_PY_LWIP_SLIP @@ -1079,10 +1084,10 @@ STATIC mp_obj_t lwip_socket_setsockopt(mp_uint_t n_args, const mp_obj_t *args) { return mp_const_none; } - // Integer options - mp_int_t val = mp_obj_get_int(args[3]); switch (opt) { - case SOF_REUSEADDR: + // level: SOL_SOCKET + case SOF_REUSEADDR: { + mp_int_t val = mp_obj_get_int(args[3]); // Options are common for UDP and TCP pcb's. if (val) { ip_set_option(socket->pcb.tcp, SOF_REUSEADDR); @@ -1090,6 +1095,24 @@ STATIC mp_obj_t lwip_socket_setsockopt(mp_uint_t n_args, const mp_obj_t *args) { ip_reset_option(socket->pcb.tcp, SOF_REUSEADDR); } break; + } + + // level: IPPROTO_IP + case IP_ADD_MEMBERSHIP: { + mp_buffer_info_t bufinfo; + mp_get_buffer_raise(args[3], &bufinfo, MP_BUFFER_READ); + if (bufinfo.len != sizeof(ip_addr_t) * 2) { + mp_raise_ValueError(NULL); + } + + // 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); + if (err != ERR_OK) { + mp_raise_OSError(error_lookup_table[-err]); + } + break; + } + default: printf("Warning: lwip.setsockopt() not implemented\n"); } @@ -1160,27 +1183,27 @@ STATIC mp_uint_t lwip_socket_ioctl(mp_obj_t self_in, mp_uint_t request, uintptr_ return ret; } -STATIC const mp_map_elem_t lwip_socket_locals_dict_table[] = { - { MP_OBJ_NEW_QSTR(MP_QSTR___del__), (mp_obj_t)&lwip_socket_close_obj }, - { MP_OBJ_NEW_QSTR(MP_QSTR_close), (mp_obj_t)&lwip_socket_close_obj }, - { MP_OBJ_NEW_QSTR(MP_QSTR_bind), (mp_obj_t)&lwip_socket_bind_obj }, - { MP_OBJ_NEW_QSTR(MP_QSTR_listen), (mp_obj_t)&lwip_socket_listen_obj }, - { MP_OBJ_NEW_QSTR(MP_QSTR_accept), (mp_obj_t)&lwip_socket_accept_obj }, - { MP_OBJ_NEW_QSTR(MP_QSTR_connect), (mp_obj_t)&lwip_socket_connect_obj }, - { MP_OBJ_NEW_QSTR(MP_QSTR_send), (mp_obj_t)&lwip_socket_send_obj }, - { MP_OBJ_NEW_QSTR(MP_QSTR_recv), (mp_obj_t)&lwip_socket_recv_obj }, - { MP_OBJ_NEW_QSTR(MP_QSTR_sendto), (mp_obj_t)&lwip_socket_sendto_obj }, - { MP_OBJ_NEW_QSTR(MP_QSTR_recvfrom), (mp_obj_t)&lwip_socket_recvfrom_obj }, - { MP_OBJ_NEW_QSTR(MP_QSTR_sendall), (mp_obj_t)&lwip_socket_sendall_obj }, - { MP_OBJ_NEW_QSTR(MP_QSTR_settimeout), (mp_obj_t)&lwip_socket_settimeout_obj }, - { MP_OBJ_NEW_QSTR(MP_QSTR_setblocking), (mp_obj_t)&lwip_socket_setblocking_obj }, - { MP_OBJ_NEW_QSTR(MP_QSTR_setsockopt), (mp_obj_t)&lwip_socket_setsockopt_obj }, - { MP_OBJ_NEW_QSTR(MP_QSTR_makefile), (mp_obj_t)&lwip_socket_makefile_obj }, +STATIC const mp_rom_map_elem_t lwip_socket_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&lwip_socket_close_obj) }, + { MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&lwip_socket_close_obj) }, + { MP_ROM_QSTR(MP_QSTR_bind), MP_ROM_PTR(&lwip_socket_bind_obj) }, + { MP_ROM_QSTR(MP_QSTR_listen), MP_ROM_PTR(&lwip_socket_listen_obj) }, + { MP_ROM_QSTR(MP_QSTR_accept), MP_ROM_PTR(&lwip_socket_accept_obj) }, + { MP_ROM_QSTR(MP_QSTR_connect), MP_ROM_PTR(&lwip_socket_connect_obj) }, + { MP_ROM_QSTR(MP_QSTR_send), MP_ROM_PTR(&lwip_socket_send_obj) }, + { MP_ROM_QSTR(MP_QSTR_recv), MP_ROM_PTR(&lwip_socket_recv_obj) }, + { MP_ROM_QSTR(MP_QSTR_sendto), MP_ROM_PTR(&lwip_socket_sendto_obj) }, + { MP_ROM_QSTR(MP_QSTR_recvfrom), MP_ROM_PTR(&lwip_socket_recvfrom_obj) }, + { MP_ROM_QSTR(MP_QSTR_sendall), MP_ROM_PTR(&lwip_socket_sendall_obj) }, + { MP_ROM_QSTR(MP_QSTR_settimeout), MP_ROM_PTR(&lwip_socket_settimeout_obj) }, + { MP_ROM_QSTR(MP_QSTR_setblocking), MP_ROM_PTR(&lwip_socket_setblocking_obj) }, + { MP_ROM_QSTR(MP_QSTR_setsockopt), MP_ROM_PTR(&lwip_socket_setsockopt_obj) }, + { MP_ROM_QSTR(MP_QSTR_makefile), MP_ROM_PTR(&lwip_socket_makefile_obj) }, - { MP_OBJ_NEW_QSTR(MP_QSTR_read), (mp_obj_t)&mp_stream_read_obj }, - { MP_OBJ_NEW_QSTR(MP_QSTR_readinto), (mp_obj_t)&mp_stream_readinto_obj }, - { MP_OBJ_NEW_QSTR(MP_QSTR_readline), (mp_obj_t)&mp_stream_unbuffered_readline_obj}, - { MP_OBJ_NEW_QSTR(MP_QSTR_write), (mp_obj_t)&mp_stream_write_obj }, + { MP_ROM_QSTR(MP_QSTR_read), MP_ROM_PTR(&mp_stream_read_obj) }, + { MP_ROM_QSTR(MP_QSTR_readinto), MP_ROM_PTR(&mp_stream_readinto_obj) }, + { MP_ROM_QSTR(MP_QSTR_readline), MP_ROM_PTR(&mp_stream_unbuffered_readline_obj) }, + { MP_ROM_QSTR(MP_QSTR_write), MP_ROM_PTR(&mp_stream_write_obj) }, }; STATIC MP_DEFINE_CONST_DICT(lwip_socket_locals_dict, lwip_socket_locals_dict_table); @@ -1196,7 +1219,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_t)&lwip_socket_locals_dict, + .locals_dict = (mp_obj_dict_t*)&lwip_socket_locals_dict, }; /******************************************************************************/ @@ -1321,27 +1344,30 @@ MP_DEFINE_CONST_FUN_OBJ_0(lwip_print_pcbs_obj, lwip_print_pcbs); #ifdef MICROPY_PY_LWIP -STATIC const mp_map_elem_t mp_module_lwip_globals_table[] = { - { MP_OBJ_NEW_QSTR(MP_QSTR___name__), MP_OBJ_NEW_QSTR(MP_QSTR_lwip) }, - { MP_OBJ_NEW_QSTR(MP_QSTR_reset), (mp_obj_t)&mod_lwip_reset_obj }, - { MP_OBJ_NEW_QSTR(MP_QSTR_callback), (mp_obj_t)&mod_lwip_callback_obj }, - { MP_OBJ_NEW_QSTR(MP_QSTR_getaddrinfo), (mp_obj_t)&lwip_getaddrinfo_obj }, - { MP_OBJ_NEW_QSTR(MP_QSTR_print_pcbs), (mp_obj_t)&lwip_print_pcbs_obj }, +STATIC const mp_rom_map_elem_t mp_module_lwip_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_lwip) }, + { MP_ROM_QSTR(MP_QSTR_reset), MP_ROM_PTR(&mod_lwip_reset_obj) }, + { MP_ROM_QSTR(MP_QSTR_callback), MP_ROM_PTR(&mod_lwip_callback_obj) }, + { MP_ROM_QSTR(MP_QSTR_getaddrinfo), MP_ROM_PTR(&lwip_getaddrinfo_obj) }, + { MP_ROM_QSTR(MP_QSTR_print_pcbs), MP_ROM_PTR(&lwip_print_pcbs_obj) }, // objects - { MP_OBJ_NEW_QSTR(MP_QSTR_socket), (mp_obj_t)&lwip_socket_type }, + { MP_ROM_QSTR(MP_QSTR_socket), MP_ROM_PTR(&lwip_socket_type) }, #ifdef MICROPY_PY_LWIP_SLIP - { MP_OBJ_NEW_QSTR(MP_QSTR_slip), (mp_obj_t)&lwip_slip_type }, + { MP_ROM_QSTR(MP_QSTR_slip), MP_ROM_PTR(&lwip_slip_type) }, #endif // class constants - { MP_OBJ_NEW_QSTR(MP_QSTR_AF_INET), MP_OBJ_NEW_SMALL_INT(MOD_NETWORK_AF_INET) }, - { MP_OBJ_NEW_QSTR(MP_QSTR_AF_INET6), MP_OBJ_NEW_SMALL_INT(MOD_NETWORK_AF_INET6) }, + { 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) }, - { MP_OBJ_NEW_QSTR(MP_QSTR_SOCK_STREAM), MP_OBJ_NEW_SMALL_INT(MOD_NETWORK_SOCK_STREAM) }, - { MP_OBJ_NEW_QSTR(MP_QSTR_SOCK_DGRAM), MP_OBJ_NEW_SMALL_INT(MOD_NETWORK_SOCK_DGRAM) }, - { MP_OBJ_NEW_QSTR(MP_QSTR_SOCK_RAW), MP_OBJ_NEW_SMALL_INT(MOD_NETWORK_SOCK_RAW) }, + { MP_ROM_QSTR(MP_QSTR_SOCK_STREAM), MP_ROM_INT(MOD_NETWORK_SOCK_STREAM) }, + { MP_ROM_QSTR(MP_QSTR_SOCK_DGRAM), MP_ROM_INT(MOD_NETWORK_SOCK_DGRAM) }, + { MP_ROM_QSTR(MP_QSTR_SOCK_RAW), MP_ROM_INT(MOD_NETWORK_SOCK_RAW) }, - { MP_OBJ_NEW_QSTR(MP_QSTR_SOL_SOCKET), MP_OBJ_NEW_SMALL_INT(1) }, - { MP_OBJ_NEW_QSTR(MP_QSTR_SO_REUSEADDR), MP_OBJ_NEW_SMALL_INT(SOF_REUSEADDR) }, + { MP_ROM_QSTR(MP_QSTR_SOL_SOCKET), MP_ROM_INT(1) }, + { MP_ROM_QSTR(MP_QSTR_SO_REUSEADDR), MP_ROM_INT(SOF_REUSEADDR) }, + + { MP_ROM_QSTR(MP_QSTR_IPPROTO_IP), MP_ROM_INT(0) }, + { MP_ROM_QSTR(MP_QSTR_IP_ADD_MEMBERSHIP), MP_ROM_INT(IP_ADD_MEMBERSHIP) }, }; STATIC MP_DEFINE_CONST_DICT(mp_module_lwip_globals, mp_module_lwip_globals_table); diff --git a/esp8266/modonewire.c b/extmod/modonewire.c similarity index 54% rename from esp8266/modonewire.c rename to extmod/modonewire.c index 1bf7722409..53c9456c20 100644 --- a/esp8266/modonewire.c +++ b/extmod/modonewire.c @@ -3,7 +3,7 @@ * * The MIT License (MIT) * - * Copyright (c) 2015 Damien P. George + * Copyright (c) 2015-2017 Damien P. George * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -29,50 +29,92 @@ #include "py/obj.h" #include "py/mphal.h" -#include "modmachine.h" -#include "esponewire.h" -STATIC mp_obj_t onewire_timings(mp_obj_t timings_in) { - mp_obj_t *items; - mp_obj_get_array_fixed_n(timings_in, 9, &items); - for (int i = 0; i < 9; ++i) { - esp_onewire_timings[i] = mp_obj_get_int(items[i]); - } - return mp_const_none; +/******************************************************************************/ +// Low-level 1-Wire routines + +#define TIMING_RESET1 (480) +#define TIMING_RESET2 (40) +#define TIMING_RESET3 (420) +#define TIMING_READ1 (5) +#define TIMING_READ2 (5) +#define TIMING_READ3 (40) +#define TIMING_WRITE1 (10) +#define TIMING_WRITE2 (50) +#define TIMING_WRITE3 (10) + +STATIC int onewire_bus_reset(mp_hal_pin_obj_t pin) { + mp_hal_pin_write(pin, 0); + mp_hal_delay_us(TIMING_RESET1); + uint32_t i = mp_hal_quiet_timing_enter(); + mp_hal_pin_write(pin, 1); + mp_hal_delay_us_fast(TIMING_RESET2); + int status = !mp_hal_pin_read(pin); + mp_hal_quiet_timing_exit(i); + mp_hal_delay_us(TIMING_RESET3); + return status; } -STATIC MP_DEFINE_CONST_FUN_OBJ_1(onewire_timings_obj, onewire_timings); + +STATIC int onewire_bus_readbit(mp_hal_pin_obj_t pin) { + mp_hal_pin_write(pin, 1); + uint32_t i = mp_hal_quiet_timing_enter(); + mp_hal_pin_write(pin, 0); + mp_hal_delay_us_fast(TIMING_READ1); + mp_hal_pin_write(pin, 1); + mp_hal_delay_us_fast(TIMING_READ2); + int value = mp_hal_pin_read(pin); + mp_hal_quiet_timing_exit(i); + mp_hal_delay_us_fast(TIMING_READ3); + return value; +} + +STATIC void onewire_bus_writebit(mp_hal_pin_obj_t pin, int value) { + uint32_t i = mp_hal_quiet_timing_enter(); + mp_hal_pin_write(pin, 0); + mp_hal_delay_us_fast(TIMING_WRITE1); + if (value) { + mp_hal_pin_write(pin, 1); + } + mp_hal_delay_us_fast(TIMING_WRITE2); + mp_hal_pin_write(pin, 1); + mp_hal_delay_us_fast(TIMING_WRITE3); + mp_hal_quiet_timing_exit(i); +} + +/******************************************************************************/ +// MicroPython bindings STATIC mp_obj_t onewire_reset(mp_obj_t pin_in) { - return mp_obj_new_bool(esp_onewire_reset(mp_obj_get_pin(pin_in))); + return mp_obj_new_bool(onewire_bus_reset(mp_hal_get_pin_obj(pin_in))); } STATIC MP_DEFINE_CONST_FUN_OBJ_1(onewire_reset_obj, onewire_reset); STATIC mp_obj_t onewire_readbit(mp_obj_t pin_in) { - return MP_OBJ_NEW_SMALL_INT(esp_onewire_readbit(mp_obj_get_pin(pin_in))); + return MP_OBJ_NEW_SMALL_INT(onewire_bus_readbit(mp_hal_get_pin_obj(pin_in))); } STATIC MP_DEFINE_CONST_FUN_OBJ_1(onewire_readbit_obj, onewire_readbit); STATIC mp_obj_t onewire_readbyte(mp_obj_t pin_in) { - uint pin = mp_obj_get_pin(pin_in); + mp_hal_pin_obj_t pin = mp_hal_get_pin_obj(pin_in); uint8_t value = 0; for (int i = 0; i < 8; ++i) { - value |= esp_onewire_readbit(pin) << i; + value |= onewire_bus_readbit(pin) << i; } return MP_OBJ_NEW_SMALL_INT(value); } STATIC MP_DEFINE_CONST_FUN_OBJ_1(onewire_readbyte_obj, onewire_readbyte); STATIC mp_obj_t onewire_writebit(mp_obj_t pin_in, mp_obj_t value_in) { - esp_onewire_writebit(mp_obj_get_pin(pin_in), mp_obj_get_int(value_in)); + onewire_bus_writebit(mp_hal_get_pin_obj(pin_in), mp_obj_get_int(value_in)); return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_2(onewire_writebit_obj, onewire_writebit); STATIC mp_obj_t onewire_writebyte(mp_obj_t pin_in, mp_obj_t value_in) { - uint pin = mp_obj_get_pin(pin_in); + mp_hal_pin_obj_t pin = mp_hal_get_pin_obj(pin_in); int value = mp_obj_get_int(value_in); for (int i = 0; i < 8; ++i) { - esp_onewire_writebit(pin, value & 1); + onewire_bus_writebit(pin, value & 1); value >>= 1; } return mp_const_none; @@ -101,21 +143,20 @@ STATIC mp_obj_t onewire_crc8(mp_obj_t data) { } STATIC MP_DEFINE_CONST_FUN_OBJ_1(onewire_crc8_obj, onewire_crc8); -STATIC const mp_map_elem_t onewire_module_globals_table[] = { +STATIC const mp_rom_map_elem_t onewire_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_onewire) }, - { MP_ROM_QSTR(MP_QSTR_timings), MP_ROM_PTR((mp_obj_t)&onewire_timings_obj) }, - { MP_ROM_QSTR(MP_QSTR_reset), MP_ROM_PTR((mp_obj_t)&onewire_reset_obj) }, - { MP_ROM_QSTR(MP_QSTR_readbit), MP_ROM_PTR((mp_obj_t)&onewire_readbit_obj) }, - { MP_ROM_QSTR(MP_QSTR_readbyte), MP_ROM_PTR((mp_obj_t)&onewire_readbyte_obj) }, - { MP_ROM_QSTR(MP_QSTR_writebit), MP_ROM_PTR((mp_obj_t)&onewire_writebit_obj) }, - { MP_ROM_QSTR(MP_QSTR_writebyte), MP_ROM_PTR((mp_obj_t)&onewire_writebyte_obj) }, - { MP_ROM_QSTR(MP_QSTR_crc8), MP_ROM_PTR((mp_obj_t)&onewire_crc8_obj) }, + { MP_ROM_QSTR(MP_QSTR_reset), MP_ROM_PTR(&onewire_reset_obj) }, + { MP_ROM_QSTR(MP_QSTR_readbit), MP_ROM_PTR(&onewire_readbit_obj) }, + { MP_ROM_QSTR(MP_QSTR_readbyte), MP_ROM_PTR(&onewire_readbyte_obj) }, + { MP_ROM_QSTR(MP_QSTR_writebit), MP_ROM_PTR(&onewire_writebit_obj) }, + { MP_ROM_QSTR(MP_QSTR_writebyte), MP_ROM_PTR(&onewire_writebyte_obj) }, + { MP_ROM_QSTR(MP_QSTR_crc8), MP_ROM_PTR(&onewire_crc8_obj) }, }; STATIC MP_DEFINE_CONST_DICT(onewire_module_globals, onewire_module_globals_table); -const mp_obj_module_t onewire_module = { +const mp_obj_module_t mp_module_onewire = { .base = { &mp_type_module }, .globals = (mp_obj_dict_t*)&onewire_module_globals, }; diff --git a/extmod/modubinascii.c b/extmod/modubinascii.c index 2ef1a6f21d..d79191b3e5 100644 --- a/extmod/modubinascii.c +++ b/extmod/modubinascii.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -42,6 +42,12 @@ mp_obj_t mod_binascii_hexlify(size_t n_args, const mp_obj_t *args) { mp_buffer_info_t bufinfo; mp_get_buffer_raise(args[0], &bufinfo, MP_BUFFER_READ); + // Code below assumes non-zero buffer length when computing size with + // separator, so handle the zero-length case here. + if (bufinfo.len == 0) { + return mp_const_empty_bytes; + } + vstr_t vstr; size_t out_len = bufinfo.len * 2; if (n_args > 1) { @@ -75,7 +81,7 @@ mp_obj_t mod_binascii_unhexlify(mp_obj_t data) { mp_get_buffer_raise(data, &bufinfo, MP_BUFFER_READ); if ((bufinfo.len & 1) != 0) { - nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "odd-length string")); + mp_raise_ValueError("odd-length string"); } vstr_t vstr; vstr_init_len(&vstr, bufinfo.len / 2); @@ -86,7 +92,7 @@ mp_obj_t mod_binascii_unhexlify(mp_obj_t data) { if (unichar_isxdigit(hex_ch)) { hex_byte += unichar_xdigit_value(hex_ch); } else { - nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "non-hex digit found")); + mp_raise_ValueError("non-hex digit found"); } if (i & 1) { hex_byte <<= 4; @@ -112,7 +118,7 @@ mp_obj_t mod_binascii_a2b_base64(mp_obj_t data) { vstr_init_len(&vstr, 0); } else { - vstr_init_len(&vstr, ((bufinfo.len / 4) * 3) - ((in[bufinfo.len-1] == '=') ? ((in[bufinfo.len-2] == '=') ? 2 : 1 ) : 0)); + vstr_init_len(&vstr, ((bufinfo.len / 4) * 3) - ((in[bufinfo.len-1] == '=') ? ((in[bufinfo.len-2] == '=') ? 2 : 1 ) : 0)); } byte *out = (byte*)vstr.buf; for (mp_uint_t i = bufinfo.len; i; i -= 4) { diff --git a/extmod/modubinascii.h b/extmod/modubinascii.h index 33d0f1cbd8..fb31692678 100644 --- a/extmod/modubinascii.h +++ b/extmod/modubinascii.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,9 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - -#ifndef MICROPY_EXTMOD_MODUBINASCII -#define MICROPY_EXTMOD_MODUBINASCII +#ifndef MICROPY_INCLUDED_EXTMOD_MODUBINASCII_H +#define MICROPY_INCLUDED_EXTMOD_MODUBINASCII_H extern mp_obj_t mod_binascii_hexlify(size_t n_args, const mp_obj_t *args); extern mp_obj_t mod_binascii_unhexlify(mp_obj_t data); @@ -39,4 +38,4 @@ MP_DECLARE_CONST_FUN_OBJ_1(mod_binascii_a2b_base64_obj); MP_DECLARE_CONST_FUN_OBJ_1(mod_binascii_b2a_base64_obj); MP_DECLARE_CONST_FUN_OBJ_VAR_BETWEEN(mod_binascii_crc32_obj); -#endif /* MICROPY_EXTMOD_MODUBINASCII */ +#endif // MICROPY_INCLUDED_EXTMOD_MODUBINASCII_H diff --git a/extmod/moductypes.c b/extmod/moductypes.c index d2d2e85de1..c2d2265628 100644 --- a/extmod/moductypes.c +++ b/extmod/moductypes.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -281,13 +281,13 @@ STATIC mp_obj_t uctypes_struct_sizeof(mp_obj_t obj_in) { } STATIC MP_DEFINE_CONST_FUN_OBJ_1(uctypes_struct_sizeof_obj, uctypes_struct_sizeof); -STATIC inline mp_obj_t get_unaligned(uint val_type, byte *p, int big_endian) { +static inline mp_obj_t get_unaligned(uint val_type, byte *p, int big_endian) { char struct_type = big_endian ? '>' : '<'; static const char type2char[16] = "BbHhIiQq------fd"; return mp_binary_get_val(struct_type, type2char[val_type], &p); } -STATIC inline void set_unaligned(uint val_type, byte *p, int big_endian, mp_obj_t val) { +static inline void set_unaligned(uint val_type, byte *p, int big_endian, mp_obj_t val) { char struct_type = big_endian ? '>' : '<'; static const char type2char[16] = "BbHhIiQq------fd"; mp_binary_set_val(struct_type, type2char[val_type], val, &p); diff --git a/extmod/moduhashlib.c b/extmod/moduhashlib.c index 13525cc3fa..f3beb39399 100644 --- a/extmod/moduhashlib.c +++ b/extmod/moduhashlib.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/extmod/moduheapq.c b/extmod/moduheapq.c index 567ee83da6..e6e417d2bc 100644 --- a/extmod/moduheapq.c +++ b/extmod/moduheapq.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/extmod/modujson.c b/extmod/modujson.c index bb2d452749..f94ec7db88 100644 --- a/extmod/modujson.c +++ b/extmod/modujson.c @@ -277,7 +277,7 @@ 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}; - mp_obj_stringio_t sio = {{&mp_type_stringio}, &vstr, 0}; + mp_obj_stringio_t sio = {{&mp_type_stringio}, &vstr, 0, MP_OBJ_NULL}; return mod_ujson_load(MP_OBJ_FROM_PTR(&sio)); } STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_ujson_loads_obj, mod_ujson_loads); diff --git a/extmod/modure.c b/extmod/modure.c index 7be091cc0d..b85ba26737 100644 --- a/extmod/modure.c +++ b/extmod/modure.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -31,6 +31,7 @@ #include "py/nlr.h" #include "py/runtime.h" #include "py/binary.h" +#include "py/objstr.h" #if MICROPY_PY_URE @@ -69,7 +70,8 @@ STATIC mp_obj_t match_group(mp_obj_t self_in, mp_obj_t no_in) { // no match for this group return mp_const_none; } - return mp_obj_new_str(start, self->caps[no * 2 + 1] - start, false); + return mp_obj_new_str_of_type(mp_obj_get_type(self->str), + (const byte*)start, self->caps[no * 2 + 1] - start); } MP_DEFINE_CONST_FUN_OBJ_2(match_group_obj, match_group); @@ -129,6 +131,7 @@ STATIC mp_obj_t re_split(size_t n_args, const mp_obj_t *args) { mp_obj_re_t *self = MP_OBJ_TO_PTR(args[0]); Subject subj; size_t len; + const mp_obj_type_t *str_type = mp_obj_get_type(args[1]); subj.begin = mp_obj_str_get_data(args[1], &len); subj.end = subj.begin + len; int caps_num = (self->re.sub + 1) * 2; @@ -150,7 +153,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(subj.begin, caps[0] - subj.begin, false); + 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_not_implemented("Splitting with sub-captures"); @@ -161,7 +164,7 @@ STATIC mp_obj_t re_split(size_t n_args, const mp_obj_t *args) { } } - mp_obj_t s = mp_obj_new_str(subj.begin, subj.end - subj.begin, false); + 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; } diff --git a/extmod/moduselect.c b/extmod/moduselect.c index 88dd29a49e..a9f25c1954 100644 --- a/extmod/moduselect.c +++ b/extmod/moduselect.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -362,10 +362,10 @@ STATIC const mp_rom_map_elem_t mp_module_select_globals_table[] = { { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_uselect) }, { MP_ROM_QSTR(MP_QSTR_select), MP_ROM_PTR(&mp_select_select_obj) }, { MP_ROM_QSTR(MP_QSTR_poll), MP_ROM_PTR(&mp_select_poll_obj) }, - { MP_ROM_QSTR(MP_QSTR_POLLIN), MP_OBJ_NEW_SMALL_INT(MP_STREAM_POLL_RD) }, - { MP_ROM_QSTR(MP_QSTR_POLLOUT), MP_OBJ_NEW_SMALL_INT(MP_STREAM_POLL_WR) }, - { MP_ROM_QSTR(MP_QSTR_POLLERR), MP_OBJ_NEW_SMALL_INT(MP_STREAM_POLL_ERR) }, - { MP_ROM_QSTR(MP_QSTR_POLLHUP), MP_OBJ_NEW_SMALL_INT(MP_STREAM_POLL_HUP) }, + { MP_ROM_QSTR(MP_QSTR_POLLIN), MP_ROM_INT(MP_STREAM_POLL_RD) }, + { MP_ROM_QSTR(MP_QSTR_POLLOUT), MP_ROM_INT(MP_STREAM_POLL_WR) }, + { MP_ROM_QSTR(MP_QSTR_POLLERR), MP_ROM_INT(MP_STREAM_POLL_ERR) }, + { MP_ROM_QSTR(MP_QSTR_POLLHUP), MP_ROM_INT(MP_STREAM_POLL_HUP) }, }; STATIC MP_DEFINE_CONST_DICT(mp_module_select_globals, mp_module_select_globals_table); diff --git a/extmod/modussl_axtls.c b/extmod/modussl_axtls.c index 4169158216..86dd8e29c8 100644 --- a/extmod/modussl_axtls.c +++ b/extmod/modussl_axtls.c @@ -1,9 +1,9 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * - * Copyright (c) 2015 Paul Sokolovsky + * Copyright (c) 2015-2017 Paul Sokolovsky * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -26,7 +26,6 @@ #include #include -#include #include "py/nlr.h" #include "py/runtime.h" @@ -45,9 +44,14 @@ typedef struct _mp_obj_ssl_socket_t { uint32_t bytes_left; } mp_obj_ssl_socket_t; +struct ssl_args { + mp_arg_val_t server_side; + mp_arg_val_t server_hostname; +}; + STATIC const mp_obj_type_t ussl_socket_type; -STATIC mp_obj_ssl_socket_t *socket_new(mp_obj_t sock, bool server_side) { +STATIC mp_obj_ssl_socket_t *socket_new(mp_obj_t sock, struct ssl_args *args) { mp_obj_ssl_socket_t *o = m_new_obj(mp_obj_ssl_socket_t); o->base.type = &ussl_socket_type; o->buf = NULL; @@ -59,18 +63,30 @@ STATIC mp_obj_ssl_socket_t *socket_new(mp_obj_t sock, bool server_side) { mp_raise_OSError(MP_EINVAL); } - if (server_side) { + if (args->server_side.u_bool) { o->ssl_sock = ssl_server_new(o->ssl_ctx, (long)sock); } else { - o->ssl_sock = ssl_client_new(o->ssl_ctx, (long)sock, NULL, 0); + SSL_EXTENSIONS *ext = ssl_ext_new(); - int res; - /* check the return status */ - if ((res = ssl_handshake_status(o->ssl_sock)) != SSL_OK) { + if (args->server_hostname.u_obj != mp_const_none) { + 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); + + int res = ssl_handshake_status(o->ssl_sock); + // Pointer to SSL_EXTENSIONS as being passed to ssl_client_new() + // is saved in ssl_sock->extensions. + // As of axTLS 2.1.3, extensions aren't used beyond the initial + // handshake, and that's pretty much how it's expected to be. So + // we allocate them on stack and reset the pointer after handshake. + + if (res != SSL_OK) { printf("ssl_handshake_status: %d\n", res); ssl_display_error(res); mp_raise_OSError(MP_EIO); } + } return o; @@ -85,6 +101,11 @@ STATIC void socket_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kin STATIC mp_uint_t socket_read(mp_obj_t o_in, void *buf, mp_uint_t size, int *errcode) { mp_obj_ssl_socket_t *o = MP_OBJ_TO_PTR(o_in); + if (o->ssl_sock == NULL) { + *errcode = EBADF; + return MP_STREAM_ERROR; + } + while (o->bytes_left == 0) { mp_int_t r = ssl_read(o->ssl_sock, &o->buf); if (r == SSL_OK) { @@ -114,6 +135,12 @@ STATIC mp_uint_t socket_read(mp_obj_t o_in, void *buf, mp_uint_t size, int *errc STATIC mp_uint_t socket_write(mp_obj_t o_in, const void *buf, mp_uint_t size, int *errcode) { mp_obj_ssl_socket_t *o = MP_OBJ_TO_PTR(o_in); + + if (o->ssl_sock == NULL) { + *errcode = EBADF; + return MP_STREAM_ERROR; + } + mp_int_t r = ssl_write(o->ssl_sock, buf, size); if (r < 0) { *errcode = r; @@ -134,9 +161,14 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_setblocking_obj, socket_setblocking); STATIC mp_obj_t socket_close(mp_obj_t self_in) { mp_obj_ssl_socket_t *self = MP_OBJ_TO_PTR(self_in); - ssl_free(self->ssl_sock); - ssl_ctx_free(self->ssl_ctx); - return mp_stream_close(self->sock); + if (self->ssl_sock != NULL) { + ssl_free(self->ssl_sock); + ssl_ctx_free(self->ssl_ctx); + self->ssl_sock = NULL; + return mp_stream_close(self->sock); + } + + return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_1(socket_close_obj, socket_close); @@ -171,18 +203,17 @@ STATIC mp_obj_t mod_ssl_wrap_socket(size_t n_args, const mp_obj_t *pos_args, mp_ // TODO: Implement more args static const mp_arg_t allowed_args[] = { { MP_QSTR_server_side, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = false} }, + { MP_QSTR_server_hostname, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, }; // TODO: Check that sock implements stream protocol mp_obj_t sock = pos_args[0]; - struct { - mp_arg_val_t server_side; - } args; + 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); - return MP_OBJ_FROM_PTR(socket_new(sock, args.server_side.u_bool)); + return MP_OBJ_FROM_PTR(socket_new(sock, &args)); } STATIC MP_DEFINE_CONST_FUN_OBJ_KW(mod_ssl_wrap_socket_obj, 1, mod_ssl_wrap_socket); diff --git a/extmod/modussl_mbedtls.c b/extmod/modussl_mbedtls.c index 40dd8c049f..597eaee73d 100644 --- a/extmod/modussl_mbedtls.c +++ b/extmod/modussl_mbedtls.c @@ -29,7 +29,7 @@ #include #include -#include +#include // needed because mp_is_nonblocking_error uses system error codes #include "py/nlr.h" #include "py/runtime.h" @@ -84,6 +84,9 @@ int _mbedtls_ssl_send(void *ctx, const byte *buf, size_t len) { int out_sz = sock_stream->write(sock, buf, len, &err); if (out_sz == MP_STREAM_ERROR) { + if (mp_is_nonblocking_error(err)) { + return MBEDTLS_ERR_SSL_WANT_WRITE; + } return -err; } else { return out_sz; @@ -98,6 +101,9 @@ int _mbedtls_ssl_recv(void *ctx, byte *buf, size_t len) { int out_sz = sock_stream->read(sock, buf, len, &err); if (out_sz == MP_STREAM_ERROR) { + if (mp_is_nonblocking_error(err)) { + return MBEDTLS_ERR_SSL_WANT_READ; + } return -err; } else { return out_sz; @@ -128,7 +134,7 @@ STATIC mp_obj_ssl_socket_t *socket_new(mp_obj_t sock, struct ssl_args *args) { } ret = mbedtls_ssl_config_defaults(&o->conf, - MBEDTLS_SSL_IS_CLIENT, + args->server_side.u_bool ? MBEDTLS_SSL_IS_SERVER : MBEDTLS_SSL_IS_CLIENT, MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT); if (ret != 0) { @@ -172,15 +178,11 @@ STATIC mp_obj_ssl_socket_t *socket_new(mp_obj_t sock, struct ssl_args *args) { assert(ret == 0); } - if (args->server_side.u_bool) { - assert(0); - } else { - while ((ret = mbedtls_ssl_handshake(&o->ssl)) != 0) { - if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) { - //assert(0); - printf("mbedtls_ssl_handshake error: -%x\n", -ret); - mp_raise_OSError(MP_EIO); - } + while ((ret = mbedtls_ssl_handshake(&o->ssl)) != 0) { + if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) { + //assert(0); + printf("mbedtls_ssl_handshake error: -%x\n", -ret); + mp_raise_OSError(MP_EIO); } } @@ -197,9 +199,16 @@ STATIC mp_uint_t socket_read(mp_obj_t o_in, void *buf, mp_uint_t size, int *errc mp_obj_ssl_socket_t *o = MP_OBJ_TO_PTR(o_in); int ret = mbedtls_ssl_read(&o->ssl, buf, size); + if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) { + // end of stream + return 0; + } if (ret >= 0) { return ret; } + if (ret == MBEDTLS_ERR_SSL_WANT_READ) { + ret = MP_EWOULDBLOCK; + } *errcode = ret; return MP_STREAM_ERROR; } @@ -211,32 +220,35 @@ STATIC mp_uint_t socket_write(mp_obj_t o_in, const void *buf, mp_uint_t size, in if (ret >= 0) { return ret; } + if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) { + ret = MP_EWOULDBLOCK; + } *errcode = ret; return MP_STREAM_ERROR; } STATIC mp_obj_t socket_setblocking(mp_obj_t self_in, mp_obj_t flag_in) { - // Currently supports only blocking mode - (void)self_in; - if (!mp_obj_is_true(flag_in)) { - mp_not_implemented(""); - } - return mp_const_none; + mp_obj_ssl_socket_t *o = MP_OBJ_TO_PTR(self_in); + mp_obj_t sock = o->sock; + mp_obj_t dest[3]; + mp_load_method(sock, MP_QSTR_setblocking, dest); + dest[2] = flag_in; + return mp_call_method_n_kw(1, 0, dest); } STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_setblocking_obj, socket_setblocking); STATIC mp_obj_t socket_close(mp_obj_t self_in) { mp_obj_ssl_socket_t *self = MP_OBJ_TO_PTR(self_in); + mbedtls_pk_free(&self->pkey); + mbedtls_x509_crt_free(&self->cert); mbedtls_x509_crt_free(&self->cacert); mbedtls_ssl_free(&self->ssl); mbedtls_ssl_config_free(&self->conf); mbedtls_ctr_drbg_free(&self->ctr_drbg); mbedtls_entropy_free(&self->entropy); - mp_obj_t dest[2]; - mp_load_method(self->sock, MP_QSTR_close, dest); - return mp_call_method_n_kw(0, 0, dest); + return mp_stream_close(self->sock); } STATIC MP_DEFINE_CONST_FUN_OBJ_1(socket_close_obj, socket_close); diff --git a/extmod/moduzlib.c b/extmod/moduzlib.c index a91405a93a..a05d0f2ed0 100644 --- a/extmod/moduzlib.c +++ b/extmod/moduzlib.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -143,7 +143,6 @@ STATIC const mp_obj_type_t decompio_type = { }; STATIC mp_obj_t mod_uzlib_decompress(size_t n_args, const mp_obj_t *args) { - (void)n_args; mp_obj_t data = args[0]; mp_buffer_info_t bufinfo; mp_get_buffer_raise(data, &bufinfo, MP_BUFFER_READ); diff --git a/extmod/modwebrepl.c b/extmod/modwebrepl.c index ce3c7dcbd5..d618f5370d 100644 --- a/extmod/modwebrepl.c +++ b/extmod/modwebrepl.c @@ -27,7 +27,6 @@ #include #include #include -#include #include "py/nlr.h" #include "py/obj.h" @@ -318,11 +317,11 @@ STATIC mp_obj_t webrepl_set_password(mp_obj_t passwd_in) { } STATIC MP_DEFINE_CONST_FUN_OBJ_1(webrepl_set_password_obj, webrepl_set_password); -STATIC const mp_map_elem_t webrepl_locals_dict_table[] = { - { MP_OBJ_NEW_QSTR(MP_QSTR_read), (mp_obj_t)&mp_stream_read_obj }, - { MP_OBJ_NEW_QSTR(MP_QSTR_readinto), (mp_obj_t)&mp_stream_readinto_obj }, - { MP_OBJ_NEW_QSTR(MP_QSTR_write), (mp_obj_t)&mp_stream_write_obj }, - { MP_OBJ_NEW_QSTR(MP_QSTR_close), (mp_obj_t)&webrepl_close_obj }, +STATIC const mp_rom_map_elem_t webrepl_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_read), MP_ROM_PTR(&mp_stream_read_obj) }, + { MP_ROM_QSTR(MP_QSTR_readinto), MP_ROM_PTR(&mp_stream_readinto_obj) }, + { MP_ROM_QSTR(MP_QSTR_write), MP_ROM_PTR(&mp_stream_write_obj) }, + { MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&webrepl_close_obj) }, }; STATIC MP_DEFINE_CONST_DICT(webrepl_locals_dict, webrepl_locals_dict_table); @@ -336,13 +335,13 @@ 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_t)&webrepl_locals_dict, + .locals_dict = (mp_obj_dict_t*)&webrepl_locals_dict, }; -STATIC const mp_map_elem_t webrepl_module_globals_table[] = { - { MP_OBJ_NEW_QSTR(MP_QSTR___name__), MP_OBJ_NEW_QSTR(MP_QSTR__webrepl) }, - { MP_OBJ_NEW_QSTR(MP_QSTR__webrepl), (mp_obj_t)&webrepl_type }, - { MP_OBJ_NEW_QSTR(MP_QSTR_password), (mp_obj_t)&webrepl_set_password_obj }, +STATIC const mp_rom_map_elem_t webrepl_module_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR__webrepl) }, + { MP_ROM_QSTR(MP_QSTR__webrepl), MP_ROM_PTR(&webrepl_type) }, + { MP_ROM_QSTR(MP_QSTR_password), MP_ROM_PTR(&webrepl_set_password_obj) }, }; STATIC MP_DEFINE_CONST_DICT(webrepl_module_globals, webrepl_module_globals_table); diff --git a/extmod/modwebsocket.c b/extmod/modwebsocket.c index 9e17d6a6d8..6c6e32c1a2 100644 --- a/extmod/modwebsocket.c +++ b/extmod/modwebsocket.c @@ -27,7 +27,6 @@ #include #include #include -#include #include "py/nlr.h" #include "py/obj.h" @@ -88,7 +87,7 @@ STATIC mp_uint_t websocket_read(mp_obj_t self_in, void *buf, mp_uint_t size, int self->buf_pos += out_sz; self->to_recv -= out_sz; if (self->to_recv != 0) { - *errcode = EAGAIN; + *errcode = MP_EAGAIN; return MP_STREAM_ERROR; } } @@ -267,7 +266,7 @@ STATIC mp_uint_t websocket_ioctl(mp_obj_t self_in, mp_uint_t request, uintptr_t return cur; } default: - *errcode = EINVAL; + *errcode = MP_EINVAL; return MP_STREAM_ERROR; } } diff --git a/extmod/modwebsocket.h b/extmod/modwebsocket.h index 7da147561c..2720147dfd 100644 --- a/extmod/modwebsocket.h +++ b/extmod/modwebsocket.h @@ -1,5 +1,10 @@ +#ifndef MICROPY_INCLUDED_EXTMOD_MODWEBSOCKET_H +#define MICROPY_INCLUDED_EXTMOD_MODWEBSOCKET_H + #define FRAME_OPCODE_MASK 0x0f enum { FRAME_CONT, FRAME_TXT, FRAME_BIN, FRAME_CLOSE = 0x8, FRAME_PING, FRAME_PONG }; + +#endif // MICROPY_INCLUDED_EXTMOD_MODWEBSOCKET_H diff --git a/extmod/uos_dupterm.c b/extmod/uos_dupterm.c index d888099dff..29a62ab898 100644 --- a/extmod/uos_dupterm.c +++ b/extmod/uos_dupterm.c @@ -24,7 +24,6 @@ * THE SOFTWARE. */ -#include #include #include "py/mpconfig.h" diff --git a/extmod/utime_mphal.c b/extmod/utime_mphal.c index e99ba46ce5..0fe3a3ba1d 100644 --- a/extmod/utime_mphal.c +++ b/extmod/utime_mphal.c @@ -38,7 +38,7 @@ STATIC mp_obj_t time_sleep(mp_obj_t seconds_o) { #if MICROPY_PY_BUILTINS_FLOAT - mp_hal_delay_ms(1000 * mp_obj_get_float(seconds_o)); + mp_hal_delay_ms((mp_uint_t)(1000 * mp_obj_get_float(seconds_o))); #else mp_hal_delay_ms(1000 * mp_obj_get_int(seconds_o)); #endif diff --git a/extmod/utime_mphal.h b/extmod/utime_mphal.h index 644387b676..88a9ed4d37 100644 --- a/extmod/utime_mphal.h +++ b/extmod/utime_mphal.h @@ -24,6 +24,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ +#ifndef MICROPY_INCLUDED_EXTMOD_UTIME_MPHAL_H +#define MICROPY_INCLUDED_EXTMOD_UTIME_MPHAL_H #include "py/obj.h" @@ -35,3 +37,5 @@ MP_DECLARE_CONST_FUN_OBJ_0(mp_utime_ticks_us_obj); MP_DECLARE_CONST_FUN_OBJ_0(mp_utime_ticks_cpu_obj); MP_DECLARE_CONST_FUN_OBJ_2(mp_utime_ticks_diff_obj); MP_DECLARE_CONST_FUN_OBJ_2(mp_utime_ticks_add_obj); + +#endif // MICROPY_INCLUDED_EXTMOD_UTIME_MPHAL_H diff --git a/extmod/vfs.h b/extmod/vfs.h index edaeb53496..f2efdbe795 100644 --- a/extmod/vfs.h +++ b/extmod/vfs.h @@ -23,7 +23,6 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - #ifndef MICROPY_INCLUDED_EXTMOD_VFS_H #define MICROPY_INCLUDED_EXTMOD_VFS_H diff --git a/extmod/vfs_fat.h b/extmod/vfs_fat.h index 6c7c05a9ac..443e4eda82 100644 --- a/extmod/vfs_fat.h +++ b/extmod/vfs_fat.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,6 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ +#ifndef MICROPY_INCLUDED_EXTMOD_VFS_FAT_H +#define MICROPY_INCLUDED_EXTMOD_VFS_FAT_H #include "py/lexer.h" #include "py/obj.h" @@ -58,3 +60,5 @@ mp_obj_t fatfs_builtin_open_self(mp_obj_t self_in, mp_obj_t path, mp_obj_t mode) MP_DECLARE_CONST_FUN_OBJ_KW(mp_builtin_open_obj); mp_obj_t fat_vfs_ilistdir2(struct _fs_user_mount_t *vfs, const char *path, bool is_str_type); + +#endif // MICROPY_INCLUDED_EXTMOD_VFS_FAT_H diff --git a/extmod/vfs_fat_diskio.c b/extmod/vfs_fat_diskio.c index 24c00ffba1..ff23c6b0cd 100644 --- a/extmod/vfs_fat_diskio.c +++ b/extmod/vfs_fat_diskio.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * Original template for this file comes from: * Low level disk I/O module skeleton for FatFs, (C)ChaN, 2013 diff --git a/extmod/vfs_fat_file.c b/extmod/vfs_fat_file.c index edffa37c76..8fb48f01a6 100644 --- a/extmod/vfs_fat_file.c +++ b/extmod/vfs_fat_file.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -28,7 +28,6 @@ #if MICROPY_VFS && MICROPY_VFS_FAT #include -#include #include "py/nlr.h" #include "py/runtime.h" diff --git a/extmod/virtpin.h b/extmod/virtpin.h index 0410103505..706affc192 100644 --- a/extmod/virtpin.h +++ b/extmod/virtpin.h @@ -23,6 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ +#ifndef MICROPY_INCLUDED_EXTMOD_VIRTPIN_H +#define MICROPY_INCLUDED_EXTMOD_VIRTPIN_H #include "py/obj.h" @@ -41,3 +43,5 @@ void mp_virtual_pin_write(mp_obj_t pin, int value); // If a port exposes a Pin object, it's constructor should be like this mp_obj_t mp_pin_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args); + +#endif // MICROPY_INCLUDED_EXTMOD_VIRTPIN_H diff --git a/lib/axtls b/lib/axtls index 67d27df4b5..9b3092eb3b 160000 --- a/lib/axtls +++ b/lib/axtls @@ -1 +1 @@ -Subproject commit 67d27df4b5d097e146599fc4fb160a2adcbf5632 +Subproject commit 9b3092eb3b4b230a63c0c389bfbd3c55682c620f diff --git a/lib/libc/string0.c b/lib/libc/string0.c index 1b37169edd..c2f2abd0f9 100644 --- a/lib/libc/string0.c +++ b/lib/libc/string0.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/lib/libm/ef_rem_pio2.c b/lib/libm/ef_rem_pio2.c index f7a695e179..ca55243fb4 100644 --- a/lib/libm/ef_rem_pio2.c +++ b/lib/libm/ef_rem_pio2.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * These math functions are taken from newlib-nano-2, the newlib/libm/math * directory, available from https://github.com/32bitmicro/newlib-nano-2. diff --git a/lib/libm/erf_lgamma.c b/lib/libm/erf_lgamma.c index a0da86b8df..877816a0c2 100644 --- a/lib/libm/erf_lgamma.c +++ b/lib/libm/erf_lgamma.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * These math functions are taken from newlib-nano-2, the newlib/libm/math * directory, available from https://github.com/32bitmicro/newlib-nano-2. diff --git a/lib/libm/fdlibm.h b/lib/libm/fdlibm.h index 529a3975ac..ace3b2da22 100644 --- a/lib/libm/fdlibm.h +++ b/lib/libm/fdlibm.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * This file is adapted from from newlib-nano-2, the newlib/libm/common/fdlib.h, * available from https://github.com/32bitmicro/newlib-nano-2. The main change diff --git a/lib/libm/kf_cos.c b/lib/libm/kf_cos.c index f1f883ced0..691f9842fd 100644 --- a/lib/libm/kf_cos.c +++ b/lib/libm/kf_cos.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * These math functions are taken from newlib-nano-2, the newlib/libm/math * directory, available from https://github.com/32bitmicro/newlib-nano-2. diff --git a/lib/libm/kf_rem_pio2.c b/lib/libm/kf_rem_pio2.c index e267b65f9a..c7e9479571 100644 --- a/lib/libm/kf_rem_pio2.c +++ b/lib/libm/kf_rem_pio2.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * These math functions are taken from newlib-nano-2, the newlib/libm/math * directory, available from https://github.com/32bitmicro/newlib-nano-2. diff --git a/lib/libm/kf_sin.c b/lib/libm/kf_sin.c index 81390b4ebb..07ea993446 100644 --- a/lib/libm/kf_sin.c +++ b/lib/libm/kf_sin.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * These math functions are taken from newlib-nano-2, the newlib/libm/math * directory, available from https://github.com/32bitmicro/newlib-nano-2. diff --git a/lib/libm/kf_tan.c b/lib/libm/kf_tan.c index 68254c682c..6da9bd8171 100644 --- a/lib/libm/kf_tan.c +++ b/lib/libm/kf_tan.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * These math functions are taken from newlib-nano-2, the newlib/libm/math * directory, available from https://github.com/32bitmicro/newlib-nano-2. diff --git a/lib/libm/math.c b/lib/libm/math.c index 732049236d..984636627c 100644 --- a/lib/libm/math.c +++ b/lib/libm/math.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -36,56 +36,6 @@ typedef union { }; } float_s_t; -typedef union { - double d; - struct { - uint64_t m : 52; - uint64_t e : 11; - uint64_t s : 1; - }; -} double_s_t; - -#if defined(__thumb__) - -double __attribute__((pcs("aapcs"))) __aeabi_i2d(int32_t x) { - return (float)x; -} - -// TODO -long long __attribute__((pcs("aapcs"))) __aeabi_f2lz(float x) { - return (long)x; -} - -double __attribute__((pcs("aapcs"))) __aeabi_f2d(float x) { - float_s_t fx={0}; - double_s_t dx={0}; - - fx.f = x; - dx.s = (fx.s); - dx.e = (fx.e-127+1023) & 0x7FF; - dx.m = fx.m; - dx.m <<=(52-23); // left justify - return dx.d; -} - -float __attribute__((pcs("aapcs"))) __aeabi_d2f(double x) { - float_s_t fx={0}; - double_s_t dx={0}; - - dx.d = x; - fx.s = (dx.s); - fx.e = (dx.e-1023+127) & 0xFF; - fx.m = (dx.m>>(52-23)); // right justify - return fx.f; -} - -double __aeabi_dmul(double x , double y) { - return 0.0; - -} - -#endif // defined(__thumb__) - #ifndef NDEBUG float copysignf(float x, float y) { float_s_t fx={.f = x}; diff --git a/lib/libm/sf_cos.c b/lib/libm/sf_cos.c index 33cde50e28..fabb129cd9 100644 --- a/lib/libm/sf_cos.c +++ b/lib/libm/sf_cos.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * These math functions are taken from newlib-nano-2, the newlib/libm/math * directory, available from https://github.com/32bitmicro/newlib-nano-2. diff --git a/lib/libm/sf_erf.c b/lib/libm/sf_erf.c index 00ac4baf1c..3f0172c6e9 100644 --- a/lib/libm/sf_erf.c +++ b/lib/libm/sf_erf.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * These math functions are taken from newlib-nano-2, the newlib/libm/math * directory, available from https://github.com/32bitmicro/newlib-nano-2. diff --git a/lib/libm/sf_frexp.c b/lib/libm/sf_frexp.c index 397373fdeb..df50fb7737 100644 --- a/lib/libm/sf_frexp.c +++ b/lib/libm/sf_frexp.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * These math functions are taken from newlib-nano-2, the newlib/libm/math * directory, available from https://github.com/32bitmicro/newlib-nano-2. diff --git a/lib/libm/sf_ldexp.c b/lib/libm/sf_ldexp.c index a0941df9fd..37968d475a 100644 --- a/lib/libm/sf_ldexp.c +++ b/lib/libm/sf_ldexp.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * These math functions are taken from newlib-nano-2, the newlib/libm/math * directory, available from https://github.com/32bitmicro/newlib-nano-2. diff --git a/lib/libm/sf_modf.c b/lib/libm/sf_modf.c index 4fcae057a5..410db2a373 100644 --- a/lib/libm/sf_modf.c +++ b/lib/libm/sf_modf.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * These math functions are taken from newlib-nano-2, the newlib/libm/common * directory, available from https://github.com/32bitmicro/newlib-nano-2. diff --git a/lib/libm/sf_sin.c b/lib/libm/sf_sin.c index 585ab8d8c9..d270507785 100644 --- a/lib/libm/sf_sin.c +++ b/lib/libm/sf_sin.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * These math functions are taken from newlib-nano-2, the newlib/libm/math * directory, available from https://github.com/32bitmicro/newlib-nano-2. diff --git a/lib/libm/sf_tan.c b/lib/libm/sf_tan.c index a9296d8bfb..148b16d618 100644 --- a/lib/libm/sf_tan.c +++ b/lib/libm/sf_tan.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * These math functions are taken from newlib-nano-2, the newlib/libm/math * directory, available from https://github.com/32bitmicro/newlib-nano-2. diff --git a/lib/libm/wf_lgamma.c b/lib/libm/wf_lgamma.c index 7d2f42c54b..d86ede790b 100644 --- a/lib/libm/wf_lgamma.c +++ b/lib/libm/wf_lgamma.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * These math functions are taken from newlib-nano-2, the newlib/libm/math * directory, available from https://github.com/32bitmicro/newlib-nano-2. diff --git a/lib/libm/wf_tgamma.c b/lib/libm/wf_tgamma.c index afd16bf674..64b2488d1d 100644 --- a/lib/libm/wf_tgamma.c +++ b/lib/libm/wf_tgamma.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * These math functions are taken from newlib-nano-2, the newlib/libm/math * directory, available from https://github.com/32bitmicro/newlib-nano-2. diff --git a/lib/libm_dbl/README b/lib/libm_dbl/README new file mode 100644 index 0000000000..512b328261 --- /dev/null +++ b/lib/libm_dbl/README @@ -0,0 +1,32 @@ +This directory contains source code for the standard double-precision math +functions. + +The files lgamma.c, log10.c and tanh.c are too small to have a meaningful +copyright or license. + +The rest of the files in this directory are copied from the musl library, +v1.1.16, and, unless otherwise stated in the individual file, have the +following copyright and MIT license: + +---------------------------------------------------------------------- +Copyright © 2005-2014 Rich Felker, et al. + +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. +---------------------------------------------------------------------- diff --git a/lib/libm_dbl/__cos.c b/lib/libm_dbl/__cos.c new file mode 100644 index 0000000000..46cefb3813 --- /dev/null +++ b/lib/libm_dbl/__cos.c @@ -0,0 +1,71 @@ +/* origin: FreeBSD /usr/src/lib/msun/src/k_cos.c */ +/* + * ==================================================== + * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + * + * Developed at SunSoft, a Sun Microsystems, Inc. business. + * Permission to use, copy, modify, and distribute this + * software is freely granted, provided that this notice + * is preserved. + * ==================================================== + */ +/* + * __cos( x, y ) + * kernel cos function on [-pi/4, pi/4], pi/4 ~ 0.785398164 + * Input x is assumed to be bounded by ~pi/4 in magnitude. + * Input y is the tail of x. + * + * Algorithm + * 1. Since cos(-x) = cos(x), we need only to consider positive x. + * 2. if x < 2^-27 (hx<0x3e400000 0), return 1 with inexact if x!=0. + * 3. cos(x) is approximated by a polynomial of degree 14 on + * [0,pi/4] + * 4 14 + * cos(x) ~ 1 - x*x/2 + C1*x + ... + C6*x + * where the remez error is + * + * | 2 4 6 8 10 12 14 | -58 + * |cos(x)-(1-.5*x +C1*x +C2*x +C3*x +C4*x +C5*x +C6*x )| <= 2 + * | | + * + * 4 6 8 10 12 14 + * 4. let r = C1*x +C2*x +C3*x +C4*x +C5*x +C6*x , then + * cos(x) ~ 1 - x*x/2 + r + * since cos(x+y) ~ cos(x) - sin(x)*y + * ~ cos(x) - x*y, + * a correction term is necessary in cos(x) and hence + * cos(x+y) = 1 - (x*x/2 - (r - x*y)) + * For better accuracy, rearrange to + * cos(x+y) ~ w + (tmp + (r-x*y)) + * where w = 1 - x*x/2 and tmp is a tiny correction term + * (1 - x*x/2 == w + tmp exactly in infinite precision). + * The exactness of w + tmp in infinite precision depends on w + * and tmp having the same precision as x. If they have extra + * precision due to compiler bugs, then the extra precision is + * only good provided it is retained in all terms of the final + * expression for cos(). Retention happens in all cases tested + * under FreeBSD, so don't pessimize things by forcibly clipping + * any extra precision in w. + */ + +#include "libm.h" + +static const double +C1 = 4.16666666666666019037e-02, /* 0x3FA55555, 0x5555554C */ +C2 = -1.38888888888741095749e-03, /* 0xBF56C16C, 0x16C15177 */ +C3 = 2.48015872894767294178e-05, /* 0x3EFA01A0, 0x19CB1590 */ +C4 = -2.75573143513906633035e-07, /* 0xBE927E4F, 0x809C52AD */ +C5 = 2.08757232129817482790e-09, /* 0x3E21EE9E, 0xBDB4B1C4 */ +C6 = -1.13596475577881948265e-11; /* 0xBDA8FAE9, 0xBE8838D4 */ + +double __cos(double x, double y) +{ + double_t hz,z,r,w; + + z = x*x; + w = z*z; + r = z*(C1+z*(C2+z*C3)) + w*w*(C4+z*(C5+z*C6)); + hz = 0.5*z; + w = 1.0-hz; + return w + (((1.0-w)-hz) + (z*r-x*y)); +} diff --git a/lib/libm_dbl/__expo2.c b/lib/libm_dbl/__expo2.c new file mode 100644 index 0000000000..740ac680e8 --- /dev/null +++ b/lib/libm_dbl/__expo2.c @@ -0,0 +1,16 @@ +#include "libm.h" + +/* k is such that k*ln2 has minimal relative error and x - kln2 > log(DBL_MIN) */ +static const int k = 2043; +static const double kln2 = 0x1.62066151add8bp+10; + +/* exp(x)/2 for x >= log(DBL_MAX), slightly better than 0.5*exp(x/2)*exp(x/2) */ +double __expo2(double x) +{ + double scale; + + /* note that k is odd and scale*scale overflows */ + INSERT_WORDS(scale, (uint32_t)(0x3ff + k/2) << 20, 0); + /* exp(x - k ln2) * 2**(k-1) */ + return exp(x - kln2) * scale * scale; +} diff --git a/lib/libm_dbl/__fpclassify.c b/lib/libm_dbl/__fpclassify.c new file mode 100644 index 0000000000..5c908ba3d2 --- /dev/null +++ b/lib/libm_dbl/__fpclassify.c @@ -0,0 +1,11 @@ +#include +#include + +int __fpclassifyd(double x) +{ + union {double f; uint64_t i;} u = {x}; + int e = u.i>>52 & 0x7ff; + if (!e) return u.i<<1 ? FP_SUBNORMAL : FP_ZERO; + if (e==0x7ff) return u.i<<12 ? FP_NAN : FP_INFINITE; + return FP_NORMAL; +} diff --git a/lib/libm_dbl/__rem_pio2.c b/lib/libm_dbl/__rem_pio2.c new file mode 100644 index 0000000000..d403f81c79 --- /dev/null +++ b/lib/libm_dbl/__rem_pio2.c @@ -0,0 +1,177 @@ +/* origin: FreeBSD /usr/src/lib/msun/src/e_rem_pio2.c */ +/* + * ==================================================== + * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + * + * Developed at SunSoft, a Sun Microsystems, Inc. business. + * Permission to use, copy, modify, and distribute this + * software is freely granted, provided that this notice + * is preserved. + * ==================================================== + * + * Optimized by Bruce D. Evans. + */ +/* __rem_pio2(x,y) + * + * return the remainder of x rem pi/2 in y[0]+y[1] + * use __rem_pio2_large() for large x + */ + +#include "libm.h" + +#if FLT_EVAL_METHOD==0 || FLT_EVAL_METHOD==1 +#define EPS DBL_EPSILON +#elif FLT_EVAL_METHOD==2 +#define EPS LDBL_EPSILON +#endif + +/* + * invpio2: 53 bits of 2/pi + * pio2_1: first 33 bit of pi/2 + * pio2_1t: pi/2 - pio2_1 + * pio2_2: second 33 bit of pi/2 + * pio2_2t: pi/2 - (pio2_1+pio2_2) + * pio2_3: third 33 bit of pi/2 + * pio2_3t: pi/2 - (pio2_1+pio2_2+pio2_3) + */ +static const double +toint = 1.5/EPS, +invpio2 = 6.36619772367581382433e-01, /* 0x3FE45F30, 0x6DC9C883 */ +pio2_1 = 1.57079632673412561417e+00, /* 0x3FF921FB, 0x54400000 */ +pio2_1t = 6.07710050650619224932e-11, /* 0x3DD0B461, 0x1A626331 */ +pio2_2 = 6.07710050630396597660e-11, /* 0x3DD0B461, 0x1A600000 */ +pio2_2t = 2.02226624879595063154e-21, /* 0x3BA3198A, 0x2E037073 */ +pio2_3 = 2.02226624871116645580e-21, /* 0x3BA3198A, 0x2E000000 */ +pio2_3t = 8.47842766036889956997e-32; /* 0x397B839A, 0x252049C1 */ + +/* caller must handle the case when reduction is not needed: |x| ~<= pi/4 */ +int __rem_pio2(double x, double *y) +{ + union {double f; uint64_t i;} u = {x}; + double_t z,w,t,r,fn; + double tx[3],ty[2]; + uint32_t ix; + int sign, n, ex, ey, i; + + sign = u.i>>63; + ix = u.i>>32 & 0x7fffffff; + if (ix <= 0x400f6a7a) { /* |x| ~<= 5pi/4 */ + if ((ix & 0xfffff) == 0x921fb) /* |x| ~= pi/2 or 2pi/2 */ + goto medium; /* cancellation -- use medium case */ + if (ix <= 0x4002d97c) { /* |x| ~<= 3pi/4 */ + if (!sign) { + z = x - pio2_1; /* one round good to 85 bits */ + y[0] = z - pio2_1t; + y[1] = (z-y[0]) - pio2_1t; + return 1; + } else { + z = x + pio2_1; + y[0] = z + pio2_1t; + y[1] = (z-y[0]) + pio2_1t; + return -1; + } + } else { + if (!sign) { + z = x - 2*pio2_1; + y[0] = z - 2*pio2_1t; + y[1] = (z-y[0]) - 2*pio2_1t; + return 2; + } else { + z = x + 2*pio2_1; + y[0] = z + 2*pio2_1t; + y[1] = (z-y[0]) + 2*pio2_1t; + return -2; + } + } + } + if (ix <= 0x401c463b) { /* |x| ~<= 9pi/4 */ + if (ix <= 0x4015fdbc) { /* |x| ~<= 7pi/4 */ + if (ix == 0x4012d97c) /* |x| ~= 3pi/2 */ + goto medium; + if (!sign) { + z = x - 3*pio2_1; + y[0] = z - 3*pio2_1t; + y[1] = (z-y[0]) - 3*pio2_1t; + return 3; + } else { + z = x + 3*pio2_1; + y[0] = z + 3*pio2_1t; + y[1] = (z-y[0]) + 3*pio2_1t; + return -3; + } + } else { + if (ix == 0x401921fb) /* |x| ~= 4pi/2 */ + goto medium; + if (!sign) { + z = x - 4*pio2_1; + y[0] = z - 4*pio2_1t; + y[1] = (z-y[0]) - 4*pio2_1t; + return 4; + } else { + z = x + 4*pio2_1; + y[0] = z + 4*pio2_1t; + y[1] = (z-y[0]) + 4*pio2_1t; + return -4; + } + } + } + if (ix < 0x413921fb) { /* |x| ~< 2^20*(pi/2), medium size */ +medium: + /* rint(x/(pi/2)), Assume round-to-nearest. */ + fn = (double_t)x*invpio2 + toint - toint; + n = (int32_t)fn; + r = x - fn*pio2_1; + w = fn*pio2_1t; /* 1st round, good to 85 bits */ + y[0] = r - w; + u.f = y[0]; + ey = u.i>>52 & 0x7ff; + ex = ix>>20; + if (ex - ey > 16) { /* 2nd round, good to 118 bits */ + t = r; + w = fn*pio2_2; + r = t - w; + w = fn*pio2_2t - ((t-r)-w); + y[0] = r - w; + u.f = y[0]; + ey = u.i>>52 & 0x7ff; + if (ex - ey > 49) { /* 3rd round, good to 151 bits, covers all cases */ + t = r; + w = fn*pio2_3; + r = t - w; + w = fn*pio2_3t - ((t-r)-w); + y[0] = r - w; + } + } + y[1] = (r - y[0]) - w; + return n; + } + /* + * all other (large) arguments + */ + if (ix >= 0x7ff00000) { /* x is inf or NaN */ + y[0] = y[1] = x - x; + return 0; + } + /* set z = scalbn(|x|,-ilogb(x)+23) */ + u.f = x; + u.i &= (uint64_t)-1>>12; + u.i |= (uint64_t)(0x3ff + 23)<<52; + z = u.f; + for (i=0; i < 2; i++) { + tx[i] = (double)(int32_t)z; + z = (z-tx[i])*0x1p24; + } + tx[i] = z; + /* skip zero terms, first term is non-zero */ + while (tx[i] == 0.0) + i--; + n = __rem_pio2_large(tx,ty,(int)(ix>>20)-(0x3ff+23),i+1,1); + if (sign) { + y[0] = -ty[0]; + y[1] = -ty[1]; + return -n; + } + y[0] = ty[0]; + y[1] = ty[1]; + return n; +} diff --git a/lib/libm_dbl/__rem_pio2_large.c b/lib/libm_dbl/__rem_pio2_large.c new file mode 100644 index 0000000000..958f28c255 --- /dev/null +++ b/lib/libm_dbl/__rem_pio2_large.c @@ -0,0 +1,442 @@ +/* origin: FreeBSD /usr/src/lib/msun/src/k_rem_pio2.c */ +/* + * ==================================================== + * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + * + * Developed at SunSoft, a Sun Microsystems, Inc. business. + * Permission to use, copy, modify, and distribute this + * software is freely granted, provided that this notice + * is preserved. + * ==================================================== + */ +/* + * __rem_pio2_large(x,y,e0,nx,prec) + * double x[],y[]; int e0,nx,prec; + * + * __rem_pio2_large return the last three digits of N with + * y = x - N*pi/2 + * so that |y| < pi/2. + * + * The method is to compute the integer (mod 8) and fraction parts of + * (2/pi)*x without doing the full multiplication. In general we + * skip the part of the product that are known to be a huge integer ( + * more accurately, = 0 mod 8 ). Thus the number of operations are + * independent of the exponent of the input. + * + * (2/pi) is represented by an array of 24-bit integers in ipio2[]. + * + * Input parameters: + * x[] The input value (must be positive) is broken into nx + * pieces of 24-bit integers in double precision format. + * x[i] will be the i-th 24 bit of x. The scaled exponent + * of x[0] is given in input parameter e0 (i.e., x[0]*2^e0 + * match x's up to 24 bits. + * + * Example of breaking a double positive z into x[0]+x[1]+x[2]: + * e0 = ilogb(z)-23 + * z = scalbn(z,-e0) + * for i = 0,1,2 + * x[i] = floor(z) + * z = (z-x[i])*2**24 + * + * + * y[] ouput result in an array of double precision numbers. + * The dimension of y[] is: + * 24-bit precision 1 + * 53-bit precision 2 + * 64-bit precision 2 + * 113-bit precision 3 + * The actual value is the sum of them. Thus for 113-bit + * precison, one may have to do something like: + * + * long double t,w,r_head, r_tail; + * t = (long double)y[2] + (long double)y[1]; + * w = (long double)y[0]; + * r_head = t+w; + * r_tail = w - (r_head - t); + * + * e0 The exponent of x[0]. Must be <= 16360 or you need to + * expand the ipio2 table. + * + * nx dimension of x[] + * + * prec an integer indicating the precision: + * 0 24 bits (single) + * 1 53 bits (double) + * 2 64 bits (extended) + * 3 113 bits (quad) + * + * External function: + * double scalbn(), floor(); + * + * + * Here is the description of some local variables: + * + * jk jk+1 is the initial number of terms of ipio2[] needed + * in the computation. The minimum and recommended value + * for jk is 3,4,4,6 for single, double, extended, and quad. + * jk+1 must be 2 larger than you might expect so that our + * recomputation test works. (Up to 24 bits in the integer + * part (the 24 bits of it that we compute) and 23 bits in + * the fraction part may be lost to cancelation before we + * recompute.) + * + * jz local integer variable indicating the number of + * terms of ipio2[] used. + * + * jx nx - 1 + * + * jv index for pointing to the suitable ipio2[] for the + * computation. In general, we want + * ( 2^e0*x[0] * ipio2[jv-1]*2^(-24jv) )/8 + * is an integer. Thus + * e0-3-24*jv >= 0 or (e0-3)/24 >= jv + * Hence jv = max(0,(e0-3)/24). + * + * jp jp+1 is the number of terms in PIo2[] needed, jp = jk. + * + * q[] double array with integral value, representing the + * 24-bits chunk of the product of x and 2/pi. + * + * q0 the corresponding exponent of q[0]. Note that the + * exponent for q[i] would be q0-24*i. + * + * PIo2[] double precision array, obtained by cutting pi/2 + * into 24 bits chunks. + * + * f[] ipio2[] in floating point + * + * iq[] integer array by breaking up q[] in 24-bits chunk. + * + * fq[] final product of x*(2/pi) in fq[0],..,fq[jk] + * + * ih integer. If >0 it indicates q[] is >= 0.5, hence + * it also indicates the *sign* of the result. + * + */ +/* + * Constants: + * The hexadecimal values are the intended ones for the following + * constants. The decimal values may be used, provided that the + * compiler will convert from decimal to binary accurately enough + * to produce the hexadecimal values shown. + */ + +#include "libm.h" + +static const int init_jk[] = {3,4,4,6}; /* initial value for jk */ + +/* + * Table of constants for 2/pi, 396 Hex digits (476 decimal) of 2/pi + * + * integer array, contains the (24*i)-th to (24*i+23)-th + * bit of 2/pi after binary point. The corresponding + * floating value is + * + * ipio2[i] * 2^(-24(i+1)). + * + * NB: This table must have at least (e0-3)/24 + jk terms. + * For quad precision (e0 <= 16360, jk = 6), this is 686. + */ +static const int32_t ipio2[] = { +0xA2F983, 0x6E4E44, 0x1529FC, 0x2757D1, 0xF534DD, 0xC0DB62, +0x95993C, 0x439041, 0xFE5163, 0xABDEBB, 0xC561B7, 0x246E3A, +0x424DD2, 0xE00649, 0x2EEA09, 0xD1921C, 0xFE1DEB, 0x1CB129, +0xA73EE8, 0x8235F5, 0x2EBB44, 0x84E99C, 0x7026B4, 0x5F7E41, +0x3991D6, 0x398353, 0x39F49C, 0x845F8B, 0xBDF928, 0x3B1FF8, +0x97FFDE, 0x05980F, 0xEF2F11, 0x8B5A0A, 0x6D1F6D, 0x367ECF, +0x27CB09, 0xB74F46, 0x3F669E, 0x5FEA2D, 0x7527BA, 0xC7EBE5, +0xF17B3D, 0x0739F7, 0x8A5292, 0xEA6BFB, 0x5FB11F, 0x8D5D08, +0x560330, 0x46FC7B, 0x6BABF0, 0xCFBC20, 0x9AF436, 0x1DA9E3, +0x91615E, 0xE61B08, 0x659985, 0x5F14A0, 0x68408D, 0xFFD880, +0x4D7327, 0x310606, 0x1556CA, 0x73A8C9, 0x60E27B, 0xC08C6B, + +#if LDBL_MAX_EXP > 1024 +0x47C419, 0xC367CD, 0xDCE809, 0x2A8359, 0xC4768B, 0x961CA6, +0xDDAF44, 0xD15719, 0x053EA5, 0xFF0705, 0x3F7E33, 0xE832C2, +0xDE4F98, 0x327DBB, 0xC33D26, 0xEF6B1E, 0x5EF89F, 0x3A1F35, +0xCAF27F, 0x1D87F1, 0x21907C, 0x7C246A, 0xFA6ED5, 0x772D30, +0x433B15, 0xC614B5, 0x9D19C3, 0xC2C4AD, 0x414D2C, 0x5D000C, +0x467D86, 0x2D71E3, 0x9AC69B, 0x006233, 0x7CD2B4, 0x97A7B4, +0xD55537, 0xF63ED7, 0x1810A3, 0xFC764D, 0x2A9D64, 0xABD770, +0xF87C63, 0x57B07A, 0xE71517, 0x5649C0, 0xD9D63B, 0x3884A7, +0xCB2324, 0x778AD6, 0x23545A, 0xB91F00, 0x1B0AF1, 0xDFCE19, +0xFF319F, 0x6A1E66, 0x615799, 0x47FBAC, 0xD87F7E, 0xB76522, +0x89E832, 0x60BFE6, 0xCDC4EF, 0x09366C, 0xD43F5D, 0xD7DE16, +0xDE3B58, 0x929BDE, 0x2822D2, 0xE88628, 0x4D58E2, 0x32CAC6, +0x16E308, 0xCB7DE0, 0x50C017, 0xA71DF3, 0x5BE018, 0x34132E, +0x621283, 0x014883, 0x5B8EF5, 0x7FB0AD, 0xF2E91E, 0x434A48, +0xD36710, 0xD8DDAA, 0x425FAE, 0xCE616A, 0xA4280A, 0xB499D3, +0xF2A606, 0x7F775C, 0x83C2A3, 0x883C61, 0x78738A, 0x5A8CAF, +0xBDD76F, 0x63A62D, 0xCBBFF4, 0xEF818D, 0x67C126, 0x45CA55, +0x36D9CA, 0xD2A828, 0x8D61C2, 0x77C912, 0x142604, 0x9B4612, +0xC459C4, 0x44C5C8, 0x91B24D, 0xF31700, 0xAD43D4, 0xE54929, +0x10D5FD, 0xFCBE00, 0xCC941E, 0xEECE70, 0xF53E13, 0x80F1EC, +0xC3E7B3, 0x28F8C7, 0x940593, 0x3E71C1, 0xB3092E, 0xF3450B, +0x9C1288, 0x7B20AB, 0x9FB52E, 0xC29247, 0x2F327B, 0x6D550C, +0x90A772, 0x1FE76B, 0x96CB31, 0x4A1679, 0xE27941, 0x89DFF4, +0x9794E8, 0x84E6E2, 0x973199, 0x6BED88, 0x365F5F, 0x0EFDBB, +0xB49A48, 0x6CA467, 0x427271, 0x325D8D, 0xB8159F, 0x09E5BC, +0x25318D, 0x3974F7, 0x1C0530, 0x010C0D, 0x68084B, 0x58EE2C, +0x90AA47, 0x02E774, 0x24D6BD, 0xA67DF7, 0x72486E, 0xEF169F, +0xA6948E, 0xF691B4, 0x5153D1, 0xF20ACF, 0x339820, 0x7E4BF5, +0x6863B2, 0x5F3EDD, 0x035D40, 0x7F8985, 0x295255, 0xC06437, +0x10D86D, 0x324832, 0x754C5B, 0xD4714E, 0x6E5445, 0xC1090B, +0x69F52A, 0xD56614, 0x9D0727, 0x50045D, 0xDB3BB4, 0xC576EA, +0x17F987, 0x7D6B49, 0xBA271D, 0x296996, 0xACCCC6, 0x5414AD, +0x6AE290, 0x89D988, 0x50722C, 0xBEA404, 0x940777, 0x7030F3, +0x27FC00, 0xA871EA, 0x49C266, 0x3DE064, 0x83DD97, 0x973FA3, +0xFD9443, 0x8C860D, 0xDE4131, 0x9D3992, 0x8C70DD, 0xE7B717, +0x3BDF08, 0x2B3715, 0xA0805C, 0x93805A, 0x921110, 0xD8E80F, +0xAF806C, 0x4BFFDB, 0x0F9038, 0x761859, 0x15A562, 0xBBCB61, +0xB989C7, 0xBD4010, 0x04F2D2, 0x277549, 0xF6B6EB, 0xBB22DB, +0xAA140A, 0x2F2689, 0x768364, 0x333B09, 0x1A940E, 0xAA3A51, +0xC2A31D, 0xAEEDAF, 0x12265C, 0x4DC26D, 0x9C7A2D, 0x9756C0, +0x833F03, 0xF6F009, 0x8C402B, 0x99316D, 0x07B439, 0x15200C, +0x5BC3D8, 0xC492F5, 0x4BADC6, 0xA5CA4E, 0xCD37A7, 0x36A9E6, +0x9492AB, 0x6842DD, 0xDE6319, 0xEF8C76, 0x528B68, 0x37DBFC, +0xABA1AE, 0x3115DF, 0xA1AE00, 0xDAFB0C, 0x664D64, 0xB705ED, +0x306529, 0xBF5657, 0x3AFF47, 0xB9F96A, 0xF3BE75, 0xDF9328, +0x3080AB, 0xF68C66, 0x15CB04, 0x0622FA, 0x1DE4D9, 0xA4B33D, +0x8F1B57, 0x09CD36, 0xE9424E, 0xA4BE13, 0xB52333, 0x1AAAF0, +0xA8654F, 0xA5C1D2, 0x0F3F0B, 0xCD785B, 0x76F923, 0x048B7B, +0x721789, 0x53A6C6, 0xE26E6F, 0x00EBEF, 0x584A9B, 0xB7DAC4, +0xBA66AA, 0xCFCF76, 0x1D02D1, 0x2DF1B1, 0xC1998C, 0x77ADC3, +0xDA4886, 0xA05DF7, 0xF480C6, 0x2FF0AC, 0x9AECDD, 0xBC5C3F, +0x6DDED0, 0x1FC790, 0xB6DB2A, 0x3A25A3, 0x9AAF00, 0x9353AD, +0x0457B6, 0xB42D29, 0x7E804B, 0xA707DA, 0x0EAA76, 0xA1597B, +0x2A1216, 0x2DB7DC, 0xFDE5FA, 0xFEDB89, 0xFDBE89, 0x6C76E4, +0xFCA906, 0x70803E, 0x156E85, 0xFF87FD, 0x073E28, 0x336761, +0x86182A, 0xEABD4D, 0xAFE7B3, 0x6E6D8F, 0x396795, 0x5BBF31, +0x48D784, 0x16DF30, 0x432DC7, 0x356125, 0xCE70C9, 0xB8CB30, +0xFD6CBF, 0xA200A4, 0xE46C05, 0xA0DD5A, 0x476F21, 0xD21262, +0x845CB9, 0x496170, 0xE0566B, 0x015299, 0x375550, 0xB7D51E, +0xC4F133, 0x5F6E13, 0xE4305D, 0xA92E85, 0xC3B21D, 0x3632A1, +0xA4B708, 0xD4B1EA, 0x21F716, 0xE4698F, 0x77FF27, 0x80030C, +0x2D408D, 0xA0CD4F, 0x99A520, 0xD3A2B3, 0x0A5D2F, 0x42F9B4, +0xCBDA11, 0xD0BE7D, 0xC1DB9B, 0xBD17AB, 0x81A2CA, 0x5C6A08, +0x17552E, 0x550027, 0xF0147F, 0x8607E1, 0x640B14, 0x8D4196, +0xDEBE87, 0x2AFDDA, 0xB6256B, 0x34897B, 0xFEF305, 0x9EBFB9, +0x4F6A68, 0xA82A4A, 0x5AC44F, 0xBCF82D, 0x985AD7, 0x95C7F4, +0x8D4D0D, 0xA63A20, 0x5F57A4, 0xB13F14, 0x953880, 0x0120CC, +0x86DD71, 0xB6DEC9, 0xF560BF, 0x11654D, 0x6B0701, 0xACB08C, +0xD0C0B2, 0x485551, 0x0EFB1E, 0xC37295, 0x3B06A3, 0x3540C0, +0x7BDC06, 0xCC45E0, 0xFA294E, 0xC8CAD6, 0x41F3E8, 0xDE647C, +0xD8649B, 0x31BED9, 0xC397A4, 0xD45877, 0xC5E369, 0x13DAF0, +0x3C3ABA, 0x461846, 0x5F7555, 0xF5BDD2, 0xC6926E, 0x5D2EAC, +0xED440E, 0x423E1C, 0x87C461, 0xE9FD29, 0xF3D6E7, 0xCA7C22, +0x35916F, 0xC5E008, 0x8DD7FF, 0xE26A6E, 0xC6FDB0, 0xC10893, +0x745D7C, 0xB2AD6B, 0x9D6ECD, 0x7B723E, 0x6A11C6, 0xA9CFF7, +0xDF7329, 0xBAC9B5, 0x5100B7, 0x0DB2E2, 0x24BA74, 0x607DE5, +0x8AD874, 0x2C150D, 0x0C1881, 0x94667E, 0x162901, 0x767A9F, +0xBEFDFD, 0xEF4556, 0x367ED9, 0x13D9EC, 0xB9BA8B, 0xFC97C4, +0x27A831, 0xC36EF1, 0x36C594, 0x56A8D8, 0xB5A8B4, 0x0ECCCF, +0x2D8912, 0x34576F, 0x89562C, 0xE3CE99, 0xB920D6, 0xAA5E6B, +0x9C2A3E, 0xCC5F11, 0x4A0BFD, 0xFBF4E1, 0x6D3B8E, 0x2C86E2, +0x84D4E9, 0xA9B4FC, 0xD1EEEF, 0xC9352E, 0x61392F, 0x442138, +0xC8D91B, 0x0AFC81, 0x6A4AFB, 0xD81C2F, 0x84B453, 0x8C994E, +0xCC2254, 0xDC552A, 0xD6C6C0, 0x96190B, 0xB8701A, 0x649569, +0x605A26, 0xEE523F, 0x0F117F, 0x11B5F4, 0xF5CBFC, 0x2DBC34, +0xEEBC34, 0xCC5DE8, 0x605EDD, 0x9B8E67, 0xEF3392, 0xB817C9, +0x9B5861, 0xBC57E1, 0xC68351, 0x103ED8, 0x4871DD, 0xDD1C2D, +0xA118AF, 0x462C21, 0xD7F359, 0x987AD9, 0xC0549E, 0xFA864F, +0xFC0656, 0xAE79E5, 0x362289, 0x22AD38, 0xDC9367, 0xAAE855, +0x382682, 0x9BE7CA, 0xA40D51, 0xB13399, 0x0ED7A9, 0x480569, +0xF0B265, 0xA7887F, 0x974C88, 0x36D1F9, 0xB39221, 0x4A827B, +0x21CF98, 0xDC9F40, 0x5547DC, 0x3A74E1, 0x42EB67, 0xDF9DFE, +0x5FD45E, 0xA4677B, 0x7AACBA, 0xA2F655, 0x23882B, 0x55BA41, +0x086E59, 0x862A21, 0x834739, 0xE6E389, 0xD49EE5, 0x40FB49, +0xE956FF, 0xCA0F1C, 0x8A59C5, 0x2BFA94, 0xC5C1D3, 0xCFC50F, +0xAE5ADB, 0x86C547, 0x624385, 0x3B8621, 0x94792C, 0x876110, +0x7B4C2A, 0x1A2C80, 0x12BF43, 0x902688, 0x893C78, 0xE4C4A8, +0x7BDBE5, 0xC23AC4, 0xEAF426, 0x8A67F7, 0xBF920D, 0x2BA365, +0xB1933D, 0x0B7CBD, 0xDC51A4, 0x63DD27, 0xDDE169, 0x19949A, +0x9529A8, 0x28CE68, 0xB4ED09, 0x209F44, 0xCA984E, 0x638270, +0x237C7E, 0x32B90F, 0x8EF5A7, 0xE75614, 0x08F121, 0x2A9DB5, +0x4D7E6F, 0x5119A5, 0xABF9B5, 0xD6DF82, 0x61DD96, 0x023616, +0x9F3AC4, 0xA1A283, 0x6DED72, 0x7A8D39, 0xA9B882, 0x5C326B, +0x5B2746, 0xED3400, 0x7700D2, 0x55F4FC, 0x4D5901, 0x8071E0, +#endif +}; + +static const double PIo2[] = { + 1.57079625129699707031e+00, /* 0x3FF921FB, 0x40000000 */ + 7.54978941586159635335e-08, /* 0x3E74442D, 0x00000000 */ + 5.39030252995776476554e-15, /* 0x3CF84698, 0x80000000 */ + 3.28200341580791294123e-22, /* 0x3B78CC51, 0x60000000 */ + 1.27065575308067607349e-29, /* 0x39F01B83, 0x80000000 */ + 1.22933308981111328932e-36, /* 0x387A2520, 0x40000000 */ + 2.73370053816464559624e-44, /* 0x36E38222, 0x80000000 */ + 2.16741683877804819444e-51, /* 0x3569F31D, 0x00000000 */ +}; + +int __rem_pio2_large(double *x, double *y, int e0, int nx, int prec) +{ + int32_t jz,jx,jv,jp,jk,carry,n,iq[20],i,j,k,m,q0,ih; + double z,fw,f[20],fq[20],q[20]; + + /* initialize jk*/ + jk = init_jk[prec]; + jp = jk; + + /* determine jx,jv,q0, note that 3>q0 */ + jx = nx-1; + jv = (e0-3)/24; if(jv<0) jv=0; + q0 = e0-24*(jv+1); + + /* set up f[0] to f[jx+jk] where f[jx+jk] = ipio2[jv+jk] */ + j = jv-jx; m = jx+jk; + for (i=0; i<=m; i++,j++) + f[i] = j<0 ? 0.0 : (double)ipio2[j]; + + /* compute q[0],q[1],...q[jk] */ + for (i=0; i<=jk; i++) { + for (j=0,fw=0.0; j<=jx; j++) + fw += x[j]*f[jx+i-j]; + q[i] = fw; + } + + jz = jk; +recompute: + /* distill q[] into iq[] reversingly */ + for (i=0,j=jz,z=q[jz]; j>0; i++,j--) { + fw = (double)(int32_t)(0x1p-24*z); + iq[i] = (int32_t)(z - 0x1p24*fw); + z = q[j-1]+fw; + } + + /* compute n */ + z = scalbn(z,q0); /* actual value of z */ + z -= 8.0*floor(z*0.125); /* trim off integer >= 8 */ + n = (int32_t)z; + z -= (double)n; + ih = 0; + if (q0 > 0) { /* need iq[jz-1] to determine n */ + i = iq[jz-1]>>(24-q0); n += i; + iq[jz-1] -= i<<(24-q0); + ih = iq[jz-1]>>(23-q0); + } + else if (q0 == 0) ih = iq[jz-1]>>23; + else if (z >= 0.5) ih = 2; + + if (ih > 0) { /* q > 0.5 */ + n += 1; carry = 0; + for (i=0; i 0) { /* rare case: chance is 1 in 12 */ + switch(q0) { + case 1: + iq[jz-1] &= 0x7fffff; break; + case 2: + iq[jz-1] &= 0x3fffff; break; + } + } + if (ih == 2) { + z = 1.0 - z; + if (carry != 0) + z -= scalbn(1.0,q0); + } + } + + /* check if recomputation is needed */ + if (z == 0.0) { + j = 0; + for (i=jz-1; i>=jk; i--) j |= iq[i]; + if (j == 0) { /* need recomputation */ + for (k=1; iq[jk-k]==0; k++); /* k = no. of terms needed */ + + for (i=jz+1; i<=jz+k; i++) { /* add q[jz+1] to q[jz+k] */ + f[jx+i] = (double)ipio2[jv+i]; + for (j=0,fw=0.0; j<=jx; j++) + fw += x[j]*f[jx+i-j]; + q[i] = fw; + } + jz += k; + goto recompute; + } + } + + /* chop off zero terms */ + if (z == 0.0) { + jz -= 1; + q0 -= 24; + while (iq[jz] == 0) { + jz--; + q0 -= 24; + } + } else { /* break z into 24-bit if necessary */ + z = scalbn(z,-q0); + if (z >= 0x1p24) { + fw = (double)(int32_t)(0x1p-24*z); + iq[jz] = (int32_t)(z - 0x1p24*fw); + jz += 1; + q0 += 24; + iq[jz] = (int32_t)fw; + } else + iq[jz] = (int32_t)z; + } + + /* convert integer "bit" chunk to floating-point value */ + fw = scalbn(1.0,q0); + for (i=jz; i>=0; i--) { + q[i] = fw*(double)iq[i]; + fw *= 0x1p-24; + } + + /* compute PIo2[0,...,jp]*q[jz,...,0] */ + for(i=jz; i>=0; i--) { + for (fw=0.0,k=0; k<=jp && k<=jz-i; k++) + fw += PIo2[k]*q[i+k]; + fq[jz-i] = fw; + } + + /* compress fq[] into y[] */ + switch(prec) { + case 0: + fw = 0.0; + for (i=jz; i>=0; i--) + fw += fq[i]; + y[0] = ih==0 ? fw : -fw; + break; + case 1: + case 2: + fw = 0.0; + for (i=jz; i>=0; i--) + fw += fq[i]; + // TODO: drop excess precision here once double_t is used + fw = (double)fw; + y[0] = ih==0 ? fw : -fw; + fw = fq[0]-fw; + for (i=1; i<=jz; i++) + fw += fq[i]; + y[1] = ih==0 ? fw : -fw; + break; + case 3: /* painful */ + for (i=jz; i>0; i--) { + fw = fq[i-1]+fq[i]; + fq[i] += fq[i-1]-fw; + fq[i-1] = fw; + } + for (i=jz; i>1; i--) { + fw = fq[i-1]+fq[i]; + fq[i] += fq[i-1]-fw; + fq[i-1] = fw; + } + for (fw=0.0,i=jz; i>=2; i--) + fw += fq[i]; + if (ih==0) { + y[0] = fq[0]; y[1] = fq[1]; y[2] = fw; + } else { + y[0] = -fq[0]; y[1] = -fq[1]; y[2] = -fw; + } + } + return n&7; +} diff --git a/lib/libm_dbl/__signbit.c b/lib/libm_dbl/__signbit.c new file mode 100644 index 0000000000..18c6728a50 --- /dev/null +++ b/lib/libm_dbl/__signbit.c @@ -0,0 +1,12 @@ +#include "libm.h" + +int __signbitd(double x) +{ + union { + double d; + uint64_t i; + } y = { x }; + return y.i>>63; +} + + diff --git a/lib/libm_dbl/__sin.c b/lib/libm_dbl/__sin.c new file mode 100644 index 0000000000..4030949664 --- /dev/null +++ b/lib/libm_dbl/__sin.c @@ -0,0 +1,64 @@ +/* origin: FreeBSD /usr/src/lib/msun/src/k_sin.c */ +/* + * ==================================================== + * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + * + * Developed at SunSoft, a Sun Microsystems, Inc. business. + * Permission to use, copy, modify, and distribute this + * software is freely granted, provided that this notice + * is preserved. + * ==================================================== + */ +/* __sin( x, y, iy) + * kernel sin function on ~[-pi/4, pi/4] (except on -0), pi/4 ~ 0.7854 + * Input x is assumed to be bounded by ~pi/4 in magnitude. + * Input y is the tail of x. + * Input iy indicates whether y is 0. (if iy=0, y assume to be 0). + * + * Algorithm + * 1. Since sin(-x) = -sin(x), we need only to consider positive x. + * 2. Callers must return sin(-0) = -0 without calling here since our + * odd polynomial is not evaluated in a way that preserves -0. + * Callers may do the optimization sin(x) ~ x for tiny x. + * 3. sin(x) is approximated by a polynomial of degree 13 on + * [0,pi/4] + * 3 13 + * sin(x) ~ x + S1*x + ... + S6*x + * where + * + * |sin(x) 2 4 6 8 10 12 | -58 + * |----- - (1+S1*x +S2*x +S3*x +S4*x +S5*x +S6*x )| <= 2 + * | x | + * + * 4. sin(x+y) = sin(x) + sin'(x')*y + * ~ sin(x) + (1-x*x/2)*y + * For better accuracy, let + * 3 2 2 2 2 + * r = x *(S2+x *(S3+x *(S4+x *(S5+x *S6)))) + * then 3 2 + * sin(x) = x + (S1*x + (x *(r-y/2)+y)) + */ + +#include "libm.h" + +static const double +S1 = -1.66666666666666324348e-01, /* 0xBFC55555, 0x55555549 */ +S2 = 8.33333333332248946124e-03, /* 0x3F811111, 0x1110F8A6 */ +S3 = -1.98412698298579493134e-04, /* 0xBF2A01A0, 0x19C161D5 */ +S4 = 2.75573137070700676789e-06, /* 0x3EC71DE3, 0x57B1FE7D */ +S5 = -2.50507602534068634195e-08, /* 0xBE5AE5E6, 0x8A2B9CEB */ +S6 = 1.58969099521155010221e-10; /* 0x3DE5D93A, 0x5ACFD57C */ + +double __sin(double x, double y, int iy) +{ + double_t z,r,v,w; + + z = x*x; + w = z*z; + r = S2 + z*(S3 + z*S4) + z*w*(S5 + z*S6); + v = z*x; + if (iy == 0) + return x + v*(S1 + z*r); + else + return x - ((z*(0.5*y - v*r) - y) - v*S1); +} diff --git a/lib/libm_dbl/__tan.c b/lib/libm_dbl/__tan.c new file mode 100644 index 0000000000..8019844d3b --- /dev/null +++ b/lib/libm_dbl/__tan.c @@ -0,0 +1,110 @@ +/* origin: FreeBSD /usr/src/lib/msun/src/k_tan.c */ +/* + * ==================================================== + * Copyright 2004 Sun Microsystems, Inc. All Rights Reserved. + * + * Permission to use, copy, modify, and distribute this + * software is freely granted, provided that this notice + * is preserved. + * ==================================================== + */ +/* __tan( x, y, k ) + * kernel tan function on ~[-pi/4, pi/4] (except on -0), pi/4 ~ 0.7854 + * Input x is assumed to be bounded by ~pi/4 in magnitude. + * Input y is the tail of x. + * Input odd indicates whether tan (if odd = 0) or -1/tan (if odd = 1) is returned. + * + * Algorithm + * 1. Since tan(-x) = -tan(x), we need only to consider positive x. + * 2. Callers must return tan(-0) = -0 without calling here since our + * odd polynomial is not evaluated in a way that preserves -0. + * Callers may do the optimization tan(x) ~ x for tiny x. + * 3. tan(x) is approximated by a odd polynomial of degree 27 on + * [0,0.67434] + * 3 27 + * tan(x) ~ x + T1*x + ... + T13*x + * where + * + * |tan(x) 2 4 26 | -59.2 + * |----- - (1+T1*x +T2*x +.... +T13*x )| <= 2 + * | x | + * + * Note: tan(x+y) = tan(x) + tan'(x)*y + * ~ tan(x) + (1+x*x)*y + * Therefore, for better accuracy in computing tan(x+y), let + * 3 2 2 2 2 + * r = x *(T2+x *(T3+x *(...+x *(T12+x *T13)))) + * then + * 3 2 + * tan(x+y) = x + (T1*x + (x *(r+y)+y)) + * + * 4. For x in [0.67434,pi/4], let y = pi/4 - x, then + * tan(x) = tan(pi/4-y) = (1-tan(y))/(1+tan(y)) + * = 1 - 2*(tan(y) - (tan(y)^2)/(1+tan(y))) + */ + +#include "libm.h" + +static const double T[] = { + 3.33333333333334091986e-01, /* 3FD55555, 55555563 */ + 1.33333333333201242699e-01, /* 3FC11111, 1110FE7A */ + 5.39682539762260521377e-02, /* 3FABA1BA, 1BB341FE */ + 2.18694882948595424599e-02, /* 3F9664F4, 8406D637 */ + 8.86323982359930005737e-03, /* 3F8226E3, E96E8493 */ + 3.59207910759131235356e-03, /* 3F6D6D22, C9560328 */ + 1.45620945432529025516e-03, /* 3F57DBC8, FEE08315 */ + 5.88041240820264096874e-04, /* 3F4344D8, F2F26501 */ + 2.46463134818469906812e-04, /* 3F3026F7, 1A8D1068 */ + 7.81794442939557092300e-05, /* 3F147E88, A03792A6 */ + 7.14072491382608190305e-05, /* 3F12B80F, 32F0A7E9 */ + -1.85586374855275456654e-05, /* BEF375CB, DB605373 */ + 2.59073051863633712884e-05, /* 3EFB2A70, 74BF7AD4 */ +}, +pio4 = 7.85398163397448278999e-01, /* 3FE921FB, 54442D18 */ +pio4lo = 3.06161699786838301793e-17; /* 3C81A626, 33145C07 */ + +double __tan(double x, double y, int odd) +{ + double_t z, r, v, w, s, a; + double w0, a0; + uint32_t hx; + int big, sign; + + GET_HIGH_WORD(hx,x); + big = (hx&0x7fffffff) >= 0x3FE59428; /* |x| >= 0.6744 */ + if (big) { + sign = hx>>31; + if (sign) { + x = -x; + y = -y; + } + x = (pio4 - x) + (pio4lo - y); + y = 0.0; + } + z = x * x; + w = z * z; + /* + * Break x^5*(T[1]+x^2*T[2]+...) into + * x^5(T[1]+x^4*T[3]+...+x^20*T[11]) + + * x^5(x^2*(T[2]+x^4*T[4]+...+x^22*[T12])) + */ + r = T[1] + w*(T[3] + w*(T[5] + w*(T[7] + w*(T[9] + w*T[11])))); + v = z*(T[2] + w*(T[4] + w*(T[6] + w*(T[8] + w*(T[10] + w*T[12]))))); + s = z * x; + r = y + z*(s*(r + v) + y) + s*T[0]; + w = x + r; + if (big) { + s = 1 - 2*odd; + v = s - 2.0 * (x + (r - w*w/(w + s))); + return sign ? -v : v; + } + if (!odd) + return w; + /* -1.0/(x+r) has up to 2ulp error, so compute it accurately */ + w0 = w; + SET_LOW_WORD(w0, 0); + v = r - (w0 - x); /* w0+v = r+x */ + a0 = a = -1.0 / w; + SET_LOW_WORD(a0, 0); + return a0 + a*(1.0 + a0*w0 + a0*v); +} diff --git a/lib/libm_dbl/acos.c b/lib/libm_dbl/acos.c new file mode 100644 index 0000000000..6104a32bc9 --- /dev/null +++ b/lib/libm_dbl/acos.c @@ -0,0 +1,101 @@ +/* origin: FreeBSD /usr/src/lib/msun/src/e_acos.c */ +/* + * ==================================================== + * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + * + * Developed at SunSoft, a Sun Microsystems, Inc. business. + * Permission to use, copy, modify, and distribute this + * software is freely granted, provided that this notice + * is preserved. + * ==================================================== + */ +/* acos(x) + * Method : + * acos(x) = pi/2 - asin(x) + * acos(-x) = pi/2 + asin(x) + * For |x|<=0.5 + * acos(x) = pi/2 - (x + x*x^2*R(x^2)) (see asin.c) + * For x>0.5 + * acos(x) = pi/2 - (pi/2 - 2asin(sqrt((1-x)/2))) + * = 2asin(sqrt((1-x)/2)) + * = 2s + 2s*z*R(z) ...z=(1-x)/2, s=sqrt(z) + * = 2f + (2c + 2s*z*R(z)) + * where f=hi part of s, and c = (z-f*f)/(s+f) is the correction term + * for f so that f+c ~ sqrt(z). + * For x<-0.5 + * acos(x) = pi - 2asin(sqrt((1-|x|)/2)) + * = pi - 0.5*(s+s*z*R(z)), where z=(1-|x|)/2,s=sqrt(z) + * + * Special cases: + * if x is NaN, return x itself; + * if |x|>1, return NaN with invalid signal. + * + * Function needed: sqrt + */ + +#include "libm.h" + +static const double +pio2_hi = 1.57079632679489655800e+00, /* 0x3FF921FB, 0x54442D18 */ +pio2_lo = 6.12323399573676603587e-17, /* 0x3C91A626, 0x33145C07 */ +pS0 = 1.66666666666666657415e-01, /* 0x3FC55555, 0x55555555 */ +pS1 = -3.25565818622400915405e-01, /* 0xBFD4D612, 0x03EB6F7D */ +pS2 = 2.01212532134862925881e-01, /* 0x3FC9C155, 0x0E884455 */ +pS3 = -4.00555345006794114027e-02, /* 0xBFA48228, 0xB5688F3B */ +pS4 = 7.91534994289814532176e-04, /* 0x3F49EFE0, 0x7501B288 */ +pS5 = 3.47933107596021167570e-05, /* 0x3F023DE1, 0x0DFDF709 */ +qS1 = -2.40339491173441421878e+00, /* 0xC0033A27, 0x1C8A2D4B */ +qS2 = 2.02094576023350569471e+00, /* 0x40002AE5, 0x9C598AC8 */ +qS3 = -6.88283971605453293030e-01, /* 0xBFE6066C, 0x1B8D0159 */ +qS4 = 7.70381505559019352791e-02; /* 0x3FB3B8C5, 0xB12E9282 */ + +static double R(double z) +{ + double_t p, q; + p = z*(pS0+z*(pS1+z*(pS2+z*(pS3+z*(pS4+z*pS5))))); + q = 1.0+z*(qS1+z*(qS2+z*(qS3+z*qS4))); + return p/q; +} + +double acos(double x) +{ + double z,w,s,c,df; + uint32_t hx,ix; + + GET_HIGH_WORD(hx, x); + ix = hx & 0x7fffffff; + /* |x| >= 1 or nan */ + if (ix >= 0x3ff00000) { + uint32_t lx; + + GET_LOW_WORD(lx,x); + if (((ix-0x3ff00000) | lx) == 0) { + /* acos(1)=0, acos(-1)=pi */ + if (hx >> 31) + return 2*pio2_hi + 0x1p-120f; + return 0; + } + return 0/(x-x); + } + /* |x| < 0.5 */ + if (ix < 0x3fe00000) { + if (ix <= 0x3c600000) /* |x| < 2**-57 */ + return pio2_hi + 0x1p-120f; + return pio2_hi - (x - (pio2_lo-x*R(x*x))); + } + /* x < -0.5 */ + if (hx >> 31) { + z = (1.0+x)*0.5; + s = sqrt(z); + w = R(z)*s-pio2_lo; + return 2*(pio2_hi - (s+w)); + } + /* x > 0.5 */ + z = (1.0-x)*0.5; + s = sqrt(z); + df = s; + SET_LOW_WORD(df,0); + c = (z-df*df)/(s+df); + w = R(z)*s+c; + return 2*(df+w); +} diff --git a/lib/libm_dbl/acosh.c b/lib/libm_dbl/acosh.c new file mode 100644 index 0000000000..badbf9081e --- /dev/null +++ b/lib/libm_dbl/acosh.c @@ -0,0 +1,24 @@ +#include "libm.h" + +#if FLT_EVAL_METHOD==2 +#undef sqrt +#define sqrt sqrtl +#endif + +/* acosh(x) = log(x + sqrt(x*x-1)) */ +double acosh(double x) +{ + union {double f; uint64_t i;} u = {.f = x}; + unsigned e = u.i >> 52 & 0x7ff; + + /* x < 1 domain error is handled in the called functions */ + + if (e < 0x3ff + 1) + /* |x| < 2, up to 2ulp error in [1,1.125] */ + return log1p(x-1 + sqrt((x-1)*(x-1)+2*(x-1))); + if (e < 0x3ff + 26) + /* |x| < 0x1p26 */ + return log(2*x - 1/(x+sqrt(x*x-1))); + /* |x| >= 0x1p26 or nan */ + return log(x) + 0.693147180559945309417232121458176568; +} diff --git a/lib/libm_dbl/asin.c b/lib/libm_dbl/asin.c new file mode 100644 index 0000000000..96b4cdfaaa --- /dev/null +++ b/lib/libm_dbl/asin.c @@ -0,0 +1,107 @@ +/* origin: FreeBSD /usr/src/lib/msun/src/e_asin.c */ +/* + * ==================================================== + * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + * + * Developed at SunSoft, a Sun Microsystems, Inc. business. + * Permission to use, copy, modify, and distribute this + * software is freely granted, provided that this notice + * is preserved. + * ==================================================== + */ +/* asin(x) + * Method : + * Since asin(x) = x + x^3/6 + x^5*3/40 + x^7*15/336 + ... + * we approximate asin(x) on [0,0.5] by + * asin(x) = x + x*x^2*R(x^2) + * where + * R(x^2) is a rational approximation of (asin(x)-x)/x^3 + * and its remez error is bounded by + * |(asin(x)-x)/x^3 - R(x^2)| < 2^(-58.75) + * + * For x in [0.5,1] + * asin(x) = pi/2-2*asin(sqrt((1-x)/2)) + * Let y = (1-x), z = y/2, s := sqrt(z), and pio2_hi+pio2_lo=pi/2; + * then for x>0.98 + * asin(x) = pi/2 - 2*(s+s*z*R(z)) + * = pio2_hi - (2*(s+s*z*R(z)) - pio2_lo) + * For x<=0.98, let pio4_hi = pio2_hi/2, then + * f = hi part of s; + * c = sqrt(z) - f = (z-f*f)/(s+f) ...f+c=sqrt(z) + * and + * asin(x) = pi/2 - 2*(s+s*z*R(z)) + * = pio4_hi+(pio4-2s)-(2s*z*R(z)-pio2_lo) + * = pio4_hi+(pio4-2f)-(2s*z*R(z)-(pio2_lo+2c)) + * + * Special cases: + * if x is NaN, return x itself; + * if |x|>1, return NaN with invalid signal. + * + */ + +#include "libm.h" + +static const double +pio2_hi = 1.57079632679489655800e+00, /* 0x3FF921FB, 0x54442D18 */ +pio2_lo = 6.12323399573676603587e-17, /* 0x3C91A626, 0x33145C07 */ +/* coefficients for R(x^2) */ +pS0 = 1.66666666666666657415e-01, /* 0x3FC55555, 0x55555555 */ +pS1 = -3.25565818622400915405e-01, /* 0xBFD4D612, 0x03EB6F7D */ +pS2 = 2.01212532134862925881e-01, /* 0x3FC9C155, 0x0E884455 */ +pS3 = -4.00555345006794114027e-02, /* 0xBFA48228, 0xB5688F3B */ +pS4 = 7.91534994289814532176e-04, /* 0x3F49EFE0, 0x7501B288 */ +pS5 = 3.47933107596021167570e-05, /* 0x3F023DE1, 0x0DFDF709 */ +qS1 = -2.40339491173441421878e+00, /* 0xC0033A27, 0x1C8A2D4B */ +qS2 = 2.02094576023350569471e+00, /* 0x40002AE5, 0x9C598AC8 */ +qS3 = -6.88283971605453293030e-01, /* 0xBFE6066C, 0x1B8D0159 */ +qS4 = 7.70381505559019352791e-02; /* 0x3FB3B8C5, 0xB12E9282 */ + +static double R(double z) +{ + double_t p, q; + p = z*(pS0+z*(pS1+z*(pS2+z*(pS3+z*(pS4+z*pS5))))); + q = 1.0+z*(qS1+z*(qS2+z*(qS3+z*qS4))); + return p/q; +} + +double asin(double x) +{ + double z,r,s; + uint32_t hx,ix; + + GET_HIGH_WORD(hx, x); + ix = hx & 0x7fffffff; + /* |x| >= 1 or nan */ + if (ix >= 0x3ff00000) { + uint32_t lx; + GET_LOW_WORD(lx, x); + if (((ix-0x3ff00000) | lx) == 0) + /* asin(1) = +-pi/2 with inexact */ + return x*pio2_hi + 0x1p-120f; + return 0/(x-x); + } + /* |x| < 0.5 */ + if (ix < 0x3fe00000) { + /* if 0x1p-1022 <= |x| < 0x1p-26, avoid raising underflow */ + if (ix < 0x3e500000 && ix >= 0x00100000) + return x; + return x + x*R(x*x); + } + /* 1 > |x| >= 0.5 */ + z = (1 - fabs(x))*0.5; + s = sqrt(z); + r = R(z); + if (ix >= 0x3fef3333) { /* if |x| > 0.975 */ + x = pio2_hi-(2*(s+s*r)-pio2_lo); + } else { + double f,c; + /* f+c = sqrt(z) */ + f = s; + SET_LOW_WORD(f,0); + c = (z-f*f)/(s+f); + x = 0.5*pio2_hi - (2*s*r - (pio2_lo-2*c) - (0.5*pio2_hi-2*f)); + } + if (hx >> 31) + return -x; + return x; +} diff --git a/lib/libm_dbl/asinh.c b/lib/libm_dbl/asinh.c new file mode 100644 index 0000000000..0829f228ef --- /dev/null +++ b/lib/libm_dbl/asinh.c @@ -0,0 +1,28 @@ +#include "libm.h" + +/* asinh(x) = sign(x)*log(|x|+sqrt(x*x+1)) ~= x - x^3/6 + o(x^5) */ +double asinh(double x) +{ + union {double f; uint64_t i;} u = {.f = x}; + unsigned e = u.i >> 52 & 0x7ff; + unsigned s = u.i >> 63; + + /* |x| */ + u.i &= (uint64_t)-1/2; + x = u.f; + + if (e >= 0x3ff + 26) { + /* |x| >= 0x1p26 or inf or nan */ + x = log(x) + 0.693147180559945309417232121458176568; + } else if (e >= 0x3ff + 1) { + /* |x| >= 2 */ + x = log(2*x + 1/(sqrt(x*x+1)+x)); + } else if (e >= 0x3ff - 26) { + /* |x| >= 0x1p-26, up to 1.6ulp error in [0.125,0.5] */ + x = log1p(x + x*x/(sqrt(x*x+1)+1)); + } else { + /* |x| < 0x1p-26, raise inexact if x != 0 */ + FORCE_EVAL(x + 0x1p120f); + } + return s ? -x : x; +} diff --git a/lib/libm_dbl/atan.c b/lib/libm_dbl/atan.c new file mode 100644 index 0000000000..63b0ab25e3 --- /dev/null +++ b/lib/libm_dbl/atan.c @@ -0,0 +1,116 @@ +/* origin: FreeBSD /usr/src/lib/msun/src/s_atan.c */ +/* + * ==================================================== + * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + * + * Developed at SunPro, a Sun Microsystems, Inc. business. + * Permission to use, copy, modify, and distribute this + * software is freely granted, provided that this notice + * is preserved. + * ==================================================== + */ +/* atan(x) + * Method + * 1. Reduce x to positive by atan(x) = -atan(-x). + * 2. According to the integer k=4t+0.25 chopped, t=x, the argument + * is further reduced to one of the following intervals and the + * arctangent of t is evaluated by the corresponding formula: + * + * [0,7/16] atan(x) = t-t^3*(a1+t^2*(a2+...(a10+t^2*a11)...) + * [7/16,11/16] atan(x) = atan(1/2) + atan( (t-0.5)/(1+t/2) ) + * [11/16.19/16] atan(x) = atan( 1 ) + atan( (t-1)/(1+t) ) + * [19/16,39/16] atan(x) = atan(3/2) + atan( (t-1.5)/(1+1.5t) ) + * [39/16,INF] atan(x) = atan(INF) + atan( -1/t ) + * + * Constants: + * The hexadecimal values are the intended ones for the following + * constants. The decimal values may be used, provided that the + * compiler will convert from decimal to binary accurately enough + * to produce the hexadecimal values shown. + */ + + +#include "libm.h" + +static const double atanhi[] = { + 4.63647609000806093515e-01, /* atan(0.5)hi 0x3FDDAC67, 0x0561BB4F */ + 7.85398163397448278999e-01, /* atan(1.0)hi 0x3FE921FB, 0x54442D18 */ + 9.82793723247329054082e-01, /* atan(1.5)hi 0x3FEF730B, 0xD281F69B */ + 1.57079632679489655800e+00, /* atan(inf)hi 0x3FF921FB, 0x54442D18 */ +}; + +static const double atanlo[] = { + 2.26987774529616870924e-17, /* atan(0.5)lo 0x3C7A2B7F, 0x222F65E2 */ + 3.06161699786838301793e-17, /* atan(1.0)lo 0x3C81A626, 0x33145C07 */ + 1.39033110312309984516e-17, /* atan(1.5)lo 0x3C700788, 0x7AF0CBBD */ + 6.12323399573676603587e-17, /* atan(inf)lo 0x3C91A626, 0x33145C07 */ +}; + +static const double aT[] = { + 3.33333333333329318027e-01, /* 0x3FD55555, 0x5555550D */ + -1.99999999998764832476e-01, /* 0xBFC99999, 0x9998EBC4 */ + 1.42857142725034663711e-01, /* 0x3FC24924, 0x920083FF */ + -1.11111104054623557880e-01, /* 0xBFBC71C6, 0xFE231671 */ + 9.09088713343650656196e-02, /* 0x3FB745CD, 0xC54C206E */ + -7.69187620504482999495e-02, /* 0xBFB3B0F2, 0xAF749A6D */ + 6.66107313738753120669e-02, /* 0x3FB10D66, 0xA0D03D51 */ + -5.83357013379057348645e-02, /* 0xBFADDE2D, 0x52DEFD9A */ + 4.97687799461593236017e-02, /* 0x3FA97B4B, 0x24760DEB */ + -3.65315727442169155270e-02, /* 0xBFA2B444, 0x2C6A6C2F */ + 1.62858201153657823623e-02, /* 0x3F90AD3A, 0xE322DA11 */ +}; + +double atan(double x) +{ + double_t w,s1,s2,z; + uint32_t ix,sign; + int id; + + GET_HIGH_WORD(ix, x); + sign = ix >> 31; + ix &= 0x7fffffff; + if (ix >= 0x44100000) { /* if |x| >= 2^66 */ + if (isnan(x)) + return x; + z = atanhi[3] + 0x1p-120f; + return sign ? -z : z; + } + if (ix < 0x3fdc0000) { /* |x| < 0.4375 */ + if (ix < 0x3e400000) { /* |x| < 2^-27 */ + if (ix < 0x00100000) + /* raise underflow for subnormal x */ + FORCE_EVAL((float)x); + return x; + } + id = -1; + } else { + x = fabs(x); + if (ix < 0x3ff30000) { /* |x| < 1.1875 */ + if (ix < 0x3fe60000) { /* 7/16 <= |x| < 11/16 */ + id = 0; + x = (2.0*x-1.0)/(2.0+x); + } else { /* 11/16 <= |x| < 19/16 */ + id = 1; + x = (x-1.0)/(x+1.0); + } + } else { + if (ix < 0x40038000) { /* |x| < 2.4375 */ + id = 2; + x = (x-1.5)/(1.0+1.5*x); + } else { /* 2.4375 <= |x| < 2^66 */ + id = 3; + x = -1.0/x; + } + } + } + /* end of argument reduction */ + z = x*x; + w = z*z; + /* break sum from i=0 to 10 aT[i]z**(i+1) into odd and even poly */ + s1 = z*(aT[0]+w*(aT[2]+w*(aT[4]+w*(aT[6]+w*(aT[8]+w*aT[10]))))); + s2 = w*(aT[1]+w*(aT[3]+w*(aT[5]+w*(aT[7]+w*aT[9])))); + if (id < 0) + return x - x*(s1+s2); + z = atanhi[id] - (x*(s1+s2) - atanlo[id] - x); + return sign ? -z : z; +} diff --git a/lib/libm_dbl/atan2.c b/lib/libm_dbl/atan2.c new file mode 100644 index 0000000000..91378b977a --- /dev/null +++ b/lib/libm_dbl/atan2.c @@ -0,0 +1,107 @@ +/* origin: FreeBSD /usr/src/lib/msun/src/e_atan2.c */ +/* + * ==================================================== + * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + * + * Developed at SunSoft, a Sun Microsystems, Inc. business. + * Permission to use, copy, modify, and distribute this + * software is freely granted, provided that this notice + * is preserved. + * ==================================================== + * + */ +/* atan2(y,x) + * Method : + * 1. Reduce y to positive by atan2(y,x)=-atan2(-y,x). + * 2. Reduce x to positive by (if x and y are unexceptional): + * ARG (x+iy) = arctan(y/x) ... if x > 0, + * ARG (x+iy) = pi - arctan[y/(-x)] ... if x < 0, + * + * Special cases: + * + * ATAN2((anything), NaN ) is NaN; + * ATAN2(NAN , (anything) ) is NaN; + * ATAN2(+-0, +(anything but NaN)) is +-0 ; + * ATAN2(+-0, -(anything but NaN)) is +-pi ; + * ATAN2(+-(anything but 0 and NaN), 0) is +-pi/2; + * ATAN2(+-(anything but INF and NaN), +INF) is +-0 ; + * ATAN2(+-(anything but INF and NaN), -INF) is +-pi; + * ATAN2(+-INF,+INF ) is +-pi/4 ; + * ATAN2(+-INF,-INF ) is +-3pi/4; + * ATAN2(+-INF, (anything but,0,NaN, and INF)) is +-pi/2; + * + * Constants: + * The hexadecimal values are the intended ones for the following + * constants. The decimal values may be used, provided that the + * compiler will convert from decimal to binary accurately enough + * to produce the hexadecimal values shown. + */ + +#include "libm.h" + +static const double +pi = 3.1415926535897931160E+00, /* 0x400921FB, 0x54442D18 */ +pi_lo = 1.2246467991473531772E-16; /* 0x3CA1A626, 0x33145C07 */ + +double atan2(double y, double x) +{ + double z; + uint32_t m,lx,ly,ix,iy; + + if (isnan(x) || isnan(y)) + return x+y; + EXTRACT_WORDS(ix, lx, x); + EXTRACT_WORDS(iy, ly, y); + if (((ix-0x3ff00000) | lx) == 0) /* x = 1.0 */ + return atan(y); + m = ((iy>>31)&1) | ((ix>>30)&2); /* 2*sign(x)+sign(y) */ + ix = ix & 0x7fffffff; + iy = iy & 0x7fffffff; + + /* when y = 0 */ + if ((iy|ly) == 0) { + switch(m) { + case 0: + case 1: return y; /* atan(+-0,+anything)=+-0 */ + case 2: return pi; /* atan(+0,-anything) = pi */ + case 3: return -pi; /* atan(-0,-anything) =-pi */ + } + } + /* when x = 0 */ + if ((ix|lx) == 0) + return m&1 ? -pi/2 : pi/2; + /* when x is INF */ + if (ix == 0x7ff00000) { + if (iy == 0x7ff00000) { + switch(m) { + case 0: return pi/4; /* atan(+INF,+INF) */ + case 1: return -pi/4; /* atan(-INF,+INF) */ + case 2: return 3*pi/4; /* atan(+INF,-INF) */ + case 3: return -3*pi/4; /* atan(-INF,-INF) */ + } + } else { + switch(m) { + case 0: return 0.0; /* atan(+...,+INF) */ + case 1: return -0.0; /* atan(-...,+INF) */ + case 2: return pi; /* atan(+...,-INF) */ + case 3: return -pi; /* atan(-...,-INF) */ + } + } + } + /* |y/x| > 0x1p64 */ + if (ix+(64<<20) < iy || iy == 0x7ff00000) + return m&1 ? -pi/2 : pi/2; + + /* z = atan(|y/x|) without spurious underflow */ + if ((m&2) && iy+(64<<20) < ix) /* |y/x| < 0x1p-64, x<0 */ + z = 0; + else + z = atan(fabs(y/x)); + switch (m) { + case 0: return z; /* atan(+,+) */ + case 1: return -z; /* atan(-,+) */ + case 2: return pi - (z-pi_lo); /* atan(+,-) */ + default: /* case 3 */ + return (z-pi_lo) - pi; /* atan(-,-) */ + } +} diff --git a/lib/libm_dbl/atanh.c b/lib/libm_dbl/atanh.c new file mode 100644 index 0000000000..63a035d706 --- /dev/null +++ b/lib/libm_dbl/atanh.c @@ -0,0 +1,29 @@ +#include "libm.h" + +/* atanh(x) = log((1+x)/(1-x))/2 = log1p(2x/(1-x))/2 ~= x + x^3/3 + o(x^5) */ +double atanh(double x) +{ + union {double f; uint64_t i;} u = {.f = x}; + unsigned e = u.i >> 52 & 0x7ff; + unsigned s = u.i >> 63; + double_t y; + + /* |x| */ + u.i &= (uint64_t)-1/2; + y = u.f; + + if (e < 0x3ff - 1) { + if (e < 0x3ff - 32) { + /* handle underflow */ + if (e == 0) + FORCE_EVAL((float)y); + } else { + /* |x| < 0.5, up to 1.7ulp error */ + y = 0.5*log1p(2*y + 2*y*y/(1-y)); + } + } else { + /* avoid overflow */ + y = 0.5*log1p(2*(y/(1-y))); + } + return s ? -y : y; +} diff --git a/lib/libm_dbl/ceil.c b/lib/libm_dbl/ceil.c new file mode 100644 index 0000000000..b13e6f2d63 --- /dev/null +++ b/lib/libm_dbl/ceil.c @@ -0,0 +1,31 @@ +#include "libm.h" + +#if FLT_EVAL_METHOD==0 || FLT_EVAL_METHOD==1 +#define EPS DBL_EPSILON +#elif FLT_EVAL_METHOD==2 +#define EPS LDBL_EPSILON +#endif +static const double_t toint = 1/EPS; + +double ceil(double x) +{ + union {double f; uint64_t i;} u = {x}; + int e = u.i >> 52 & 0x7ff; + double_t y; + + if (e >= 0x3ff+52 || x == 0) + return x; + /* y = int(x) - x, where int(x) is an integer neighbor of x */ + if (u.i >> 63) + y = x - toint + toint - x; + else + y = x + toint - toint - x; + /* special case because of non-nearest rounding modes */ + if (e <= 0x3ff-1) { + FORCE_EVAL(y); + return u.i >> 63 ? -0.0 : 1; + } + if (y < 0) + return x + y + 1; + return x + y; +} diff --git a/lib/libm_dbl/cos.c b/lib/libm_dbl/cos.c new file mode 100644 index 0000000000..ee97f68bbb --- /dev/null +++ b/lib/libm_dbl/cos.c @@ -0,0 +1,77 @@ +/* origin: FreeBSD /usr/src/lib/msun/src/s_cos.c */ +/* + * ==================================================== + * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + * + * Developed at SunPro, a Sun Microsystems, Inc. business. + * Permission to use, copy, modify, and distribute this + * software is freely granted, provided that this notice + * is preserved. + * ==================================================== + */ +/* cos(x) + * Return cosine function of x. + * + * kernel function: + * __sin ... sine function on [-pi/4,pi/4] + * __cos ... cosine function on [-pi/4,pi/4] + * __rem_pio2 ... argument reduction routine + * + * Method. + * Let S,C and T denote the sin, cos and tan respectively on + * [-PI/4, +PI/4]. Reduce the argument x to y1+y2 = x-k*pi/2 + * in [-pi/4 , +pi/4], and let n = k mod 4. + * We have + * + * n sin(x) cos(x) tan(x) + * ---------------------------------------------------------- + * 0 S C T + * 1 C -S -1/T + * 2 -S -C T + * 3 -C S -1/T + * ---------------------------------------------------------- + * + * Special cases: + * Let trig be any of sin, cos, or tan. + * trig(+-INF) is NaN, with signals; + * trig(NaN) is that NaN; + * + * Accuracy: + * TRIG(x) returns trig(x) nearly rounded + */ + +#include "libm.h" + +double cos(double x) +{ + double y[2]; + uint32_t ix; + unsigned n; + + GET_HIGH_WORD(ix, x); + ix &= 0x7fffffff; + + /* |x| ~< pi/4 */ + if (ix <= 0x3fe921fb) { + if (ix < 0x3e46a09e) { /* |x| < 2**-27 * sqrt(2) */ + /* raise inexact if x!=0 */ + FORCE_EVAL(x + 0x1p120f); + return 1.0; + } + return __cos(x, 0); + } + + /* cos(Inf or NaN) is NaN */ + if (ix >= 0x7ff00000) + return x-x; + + /* argument reduction */ + n = __rem_pio2(x, y); + switch (n&3) { + case 0: return __cos(y[0], y[1]); + case 1: return -__sin(y[0], y[1], 1); + case 2: return -__cos(y[0], y[1]); + default: + return __sin(y[0], y[1], 1); + } +} diff --git a/lib/libm_dbl/cosh.c b/lib/libm_dbl/cosh.c new file mode 100644 index 0000000000..100f8231d8 --- /dev/null +++ b/lib/libm_dbl/cosh.c @@ -0,0 +1,40 @@ +#include "libm.h" + +/* cosh(x) = (exp(x) + 1/exp(x))/2 + * = 1 + 0.5*(exp(x)-1)*(exp(x)-1)/exp(x) + * = 1 + x*x/2 + o(x^4) + */ +double cosh(double x) +{ + union {double f; uint64_t i;} u = {.f = x}; + uint32_t w; + double t; + + /* |x| */ + u.i &= (uint64_t)-1/2; + x = u.f; + w = u.i >> 32; + + /* |x| < log(2) */ + if (w < 0x3fe62e42) { + if (w < 0x3ff00000 - (26<<20)) { + /* raise inexact if x!=0 */ + FORCE_EVAL(x + 0x1p120f); + return 1; + } + t = expm1(x); + return 1 + t*t/(2*(1+t)); + } + + /* |x| < log(DBL_MAX) */ + if (w < 0x40862e42) { + t = exp(x); + /* note: if x>log(0x1p26) then the 1/t is not needed */ + return 0.5*(t + 1/t); + } + + /* |x| > log(DBL_MAX) or nan */ + /* note: the result is stored to handle overflow */ + t = __expo2(x); + return t; +} diff --git a/lib/libm_dbl/erf.c b/lib/libm_dbl/erf.c new file mode 100644 index 0000000000..2f30a298f9 --- /dev/null +++ b/lib/libm_dbl/erf.c @@ -0,0 +1,273 @@ +/* origin: FreeBSD /usr/src/lib/msun/src/s_erf.c */ +/* + * ==================================================== + * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + * + * Developed at SunPro, a Sun Microsystems, Inc. business. + * Permission to use, copy, modify, and distribute this + * software is freely granted, provided that this notice + * is preserved. + * ==================================================== + */ +/* double erf(double x) + * double erfc(double x) + * x + * 2 |\ + * erf(x) = --------- | exp(-t*t)dt + * sqrt(pi) \| + * 0 + * + * erfc(x) = 1-erf(x) + * Note that + * erf(-x) = -erf(x) + * erfc(-x) = 2 - erfc(x) + * + * Method: + * 1. For |x| in [0, 0.84375] + * erf(x) = x + x*R(x^2) + * erfc(x) = 1 - erf(x) if x in [-.84375,0.25] + * = 0.5 + ((0.5-x)-x*R) if x in [0.25,0.84375] + * where R = P/Q where P is an odd poly of degree 8 and + * Q is an odd poly of degree 10. + * -57.90 + * | R - (erf(x)-x)/x | <= 2 + * + * + * Remark. The formula is derived by noting + * erf(x) = (2/sqrt(pi))*(x - x^3/3 + x^5/10 - x^7/42 + ....) + * and that + * 2/sqrt(pi) = 1.128379167095512573896158903121545171688 + * is close to one. The interval is chosen because the fix + * point of erf(x) is near 0.6174 (i.e., erf(x)=x when x is + * near 0.6174), and by some experiment, 0.84375 is chosen to + * guarantee the error is less than one ulp for erf. + * + * 2. For |x| in [0.84375,1.25], let s = |x| - 1, and + * c = 0.84506291151 rounded to single (24 bits) + * erf(x) = sign(x) * (c + P1(s)/Q1(s)) + * erfc(x) = (1-c) - P1(s)/Q1(s) if x > 0 + * 1+(c+P1(s)/Q1(s)) if x < 0 + * |P1/Q1 - (erf(|x|)-c)| <= 2**-59.06 + * Remark: here we use the taylor series expansion at x=1. + * erf(1+s) = erf(1) + s*Poly(s) + * = 0.845.. + P1(s)/Q1(s) + * That is, we use rational approximation to approximate + * erf(1+s) - (c = (single)0.84506291151) + * Note that |P1/Q1|< 0.078 for x in [0.84375,1.25] + * where + * P1(s) = degree 6 poly in s + * Q1(s) = degree 6 poly in s + * + * 3. For x in [1.25,1/0.35(~2.857143)], + * erfc(x) = (1/x)*exp(-x*x-0.5625+R1/S1) + * erf(x) = 1 - erfc(x) + * where + * R1(z) = degree 7 poly in z, (z=1/x^2) + * S1(z) = degree 8 poly in z + * + * 4. For x in [1/0.35,28] + * erfc(x) = (1/x)*exp(-x*x-0.5625+R2/S2) if x > 0 + * = 2.0 - (1/x)*exp(-x*x-0.5625+R2/S2) if -6 x >= 28 + * erf(x) = sign(x) *(1 - tiny) (raise inexact) + * erfc(x) = tiny*tiny (raise underflow) if x > 0 + * = 2 - tiny if x<0 + * + * 7. Special case: + * erf(0) = 0, erf(inf) = 1, erf(-inf) = -1, + * erfc(0) = 1, erfc(inf) = 0, erfc(-inf) = 2, + * erfc/erf(NaN) is NaN + */ + +#include "libm.h" + +static const double +erx = 8.45062911510467529297e-01, /* 0x3FEB0AC1, 0x60000000 */ +/* + * Coefficients for approximation to erf on [0,0.84375] + */ +efx8 = 1.02703333676410069053e+00, /* 0x3FF06EBA, 0x8214DB69 */ +pp0 = 1.28379167095512558561e-01, /* 0x3FC06EBA, 0x8214DB68 */ +pp1 = -3.25042107247001499370e-01, /* 0xBFD4CD7D, 0x691CB913 */ +pp2 = -2.84817495755985104766e-02, /* 0xBF9D2A51, 0xDBD7194F */ +pp3 = -5.77027029648944159157e-03, /* 0xBF77A291, 0x236668E4 */ +pp4 = -2.37630166566501626084e-05, /* 0xBEF8EAD6, 0x120016AC */ +qq1 = 3.97917223959155352819e-01, /* 0x3FD97779, 0xCDDADC09 */ +qq2 = 6.50222499887672944485e-02, /* 0x3FB0A54C, 0x5536CEBA */ +qq3 = 5.08130628187576562776e-03, /* 0x3F74D022, 0xC4D36B0F */ +qq4 = 1.32494738004321644526e-04, /* 0x3F215DC9, 0x221C1A10 */ +qq5 = -3.96022827877536812320e-06, /* 0xBED09C43, 0x42A26120 */ +/* + * Coefficients for approximation to erf in [0.84375,1.25] + */ +pa0 = -2.36211856075265944077e-03, /* 0xBF6359B8, 0xBEF77538 */ +pa1 = 4.14856118683748331666e-01, /* 0x3FDA8D00, 0xAD92B34D */ +pa2 = -3.72207876035701323847e-01, /* 0xBFD7D240, 0xFBB8C3F1 */ +pa3 = 3.18346619901161753674e-01, /* 0x3FD45FCA, 0x805120E4 */ +pa4 = -1.10894694282396677476e-01, /* 0xBFBC6398, 0x3D3E28EC */ +pa5 = 3.54783043256182359371e-02, /* 0x3FA22A36, 0x599795EB */ +pa6 = -2.16637559486879084300e-03, /* 0xBF61BF38, 0x0A96073F */ +qa1 = 1.06420880400844228286e-01, /* 0x3FBB3E66, 0x18EEE323 */ +qa2 = 5.40397917702171048937e-01, /* 0x3FE14AF0, 0x92EB6F33 */ +qa3 = 7.18286544141962662868e-02, /* 0x3FB2635C, 0xD99FE9A7 */ +qa4 = 1.26171219808761642112e-01, /* 0x3FC02660, 0xE763351F */ +qa5 = 1.36370839120290507362e-02, /* 0x3F8BEDC2, 0x6B51DD1C */ +qa6 = 1.19844998467991074170e-02, /* 0x3F888B54, 0x5735151D */ +/* + * Coefficients for approximation to erfc in [1.25,1/0.35] + */ +ra0 = -9.86494403484714822705e-03, /* 0xBF843412, 0x600D6435 */ +ra1 = -6.93858572707181764372e-01, /* 0xBFE63416, 0xE4BA7360 */ +ra2 = -1.05586262253232909814e+01, /* 0xC0251E04, 0x41B0E726 */ +ra3 = -6.23753324503260060396e+01, /* 0xC04F300A, 0xE4CBA38D */ +ra4 = -1.62396669462573470355e+02, /* 0xC0644CB1, 0x84282266 */ +ra5 = -1.84605092906711035994e+02, /* 0xC067135C, 0xEBCCABB2 */ +ra6 = -8.12874355063065934246e+01, /* 0xC0545265, 0x57E4D2F2 */ +ra7 = -9.81432934416914548592e+00, /* 0xC023A0EF, 0xC69AC25C */ +sa1 = 1.96512716674392571292e+01, /* 0x4033A6B9, 0xBD707687 */ +sa2 = 1.37657754143519042600e+02, /* 0x4061350C, 0x526AE721 */ +sa3 = 4.34565877475229228821e+02, /* 0x407B290D, 0xD58A1A71 */ +sa4 = 6.45387271733267880336e+02, /* 0x40842B19, 0x21EC2868 */ +sa5 = 4.29008140027567833386e+02, /* 0x407AD021, 0x57700314 */ +sa6 = 1.08635005541779435134e+02, /* 0x405B28A3, 0xEE48AE2C */ +sa7 = 6.57024977031928170135e+00, /* 0x401A47EF, 0x8E484A93 */ +sa8 = -6.04244152148580987438e-02, /* 0xBFAEEFF2, 0xEE749A62 */ +/* + * Coefficients for approximation to erfc in [1/.35,28] + */ +rb0 = -9.86494292470009928597e-03, /* 0xBF843412, 0x39E86F4A */ +rb1 = -7.99283237680523006574e-01, /* 0xBFE993BA, 0x70C285DE */ +rb2 = -1.77579549177547519889e+01, /* 0xC031C209, 0x555F995A */ +rb3 = -1.60636384855821916062e+02, /* 0xC064145D, 0x43C5ED98 */ +rb4 = -6.37566443368389627722e+02, /* 0xC083EC88, 0x1375F228 */ +rb5 = -1.02509513161107724954e+03, /* 0xC0900461, 0x6A2E5992 */ +rb6 = -4.83519191608651397019e+02, /* 0xC07E384E, 0x9BDC383F */ +sb1 = 3.03380607434824582924e+01, /* 0x403E568B, 0x261D5190 */ +sb2 = 3.25792512996573918826e+02, /* 0x40745CAE, 0x221B9F0A */ +sb3 = 1.53672958608443695994e+03, /* 0x409802EB, 0x189D5118 */ +sb4 = 3.19985821950859553908e+03, /* 0x40A8FFB7, 0x688C246A */ +sb5 = 2.55305040643316442583e+03, /* 0x40A3F219, 0xCEDF3BE6 */ +sb6 = 4.74528541206955367215e+02, /* 0x407DA874, 0xE79FE763 */ +sb7 = -2.24409524465858183362e+01; /* 0xC03670E2, 0x42712D62 */ + +static double erfc1(double x) +{ + double_t s,P,Q; + + s = fabs(x) - 1; + P = pa0+s*(pa1+s*(pa2+s*(pa3+s*(pa4+s*(pa5+s*pa6))))); + Q = 1+s*(qa1+s*(qa2+s*(qa3+s*(qa4+s*(qa5+s*qa6))))); + return 1 - erx - P/Q; +} + +static double erfc2(uint32_t ix, double x) +{ + double_t s,R,S; + double z; + + if (ix < 0x3ff40000) /* |x| < 1.25 */ + return erfc1(x); + + x = fabs(x); + s = 1/(x*x); + if (ix < 0x4006db6d) { /* |x| < 1/.35 ~ 2.85714 */ + R = ra0+s*(ra1+s*(ra2+s*(ra3+s*(ra4+s*( + ra5+s*(ra6+s*ra7)))))); + S = 1.0+s*(sa1+s*(sa2+s*(sa3+s*(sa4+s*( + sa5+s*(sa6+s*(sa7+s*sa8))))))); + } else { /* |x| > 1/.35 */ + R = rb0+s*(rb1+s*(rb2+s*(rb3+s*(rb4+s*( + rb5+s*rb6))))); + S = 1.0+s*(sb1+s*(sb2+s*(sb3+s*(sb4+s*( + sb5+s*(sb6+s*sb7)))))); + } + z = x; + SET_LOW_WORD(z,0); + return exp(-z*z-0.5625)*exp((z-x)*(z+x)+R/S)/x; +} + +double erf(double x) +{ + double r,s,z,y; + uint32_t ix; + int sign; + + GET_HIGH_WORD(ix, x); + sign = ix>>31; + ix &= 0x7fffffff; + if (ix >= 0x7ff00000) { + /* erf(nan)=nan, erf(+-inf)=+-1 */ + return 1-2*sign + 1/x; + } + if (ix < 0x3feb0000) { /* |x| < 0.84375 */ + if (ix < 0x3e300000) { /* |x| < 2**-28 */ + /* avoid underflow */ + return 0.125*(8*x + efx8*x); + } + z = x*x; + r = pp0+z*(pp1+z*(pp2+z*(pp3+z*pp4))); + s = 1.0+z*(qq1+z*(qq2+z*(qq3+z*(qq4+z*qq5)))); + y = r/s; + return x + x*y; + } + if (ix < 0x40180000) /* 0.84375 <= |x| < 6 */ + y = 1 - erfc2(ix,x); + else + y = 1 - 0x1p-1022; + return sign ? -y : y; +} + +double erfc(double x) +{ + double r,s,z,y; + uint32_t ix; + int sign; + + GET_HIGH_WORD(ix, x); + sign = ix>>31; + ix &= 0x7fffffff; + if (ix >= 0x7ff00000) { + /* erfc(nan)=nan, erfc(+-inf)=0,2 */ + return 2*sign + 1/x; + } + if (ix < 0x3feb0000) { /* |x| < 0.84375 */ + if (ix < 0x3c700000) /* |x| < 2**-56 */ + return 1.0 - x; + z = x*x; + r = pp0+z*(pp1+z*(pp2+z*(pp3+z*pp4))); + s = 1.0+z*(qq1+z*(qq2+z*(qq3+z*(qq4+z*qq5)))); + y = r/s; + if (sign || ix < 0x3fd00000) { /* x < 1/4 */ + return 1.0 - (x+x*y); + } + return 0.5 - (x - 0.5 + x*y); + } + if (ix < 0x403c0000) { /* 0.84375 <= |x| < 28 */ + return sign ? 2 - erfc2(ix,x) : erfc2(ix,x); + } + return sign ? 2 - 0x1p-1022 : 0x1p-1022*0x1p-1022; +} diff --git a/lib/libm_dbl/exp.c b/lib/libm_dbl/exp.c new file mode 100644 index 0000000000..9ea672fac6 --- /dev/null +++ b/lib/libm_dbl/exp.c @@ -0,0 +1,134 @@ +/* origin: FreeBSD /usr/src/lib/msun/src/e_exp.c */ +/* + * ==================================================== + * Copyright (C) 2004 by Sun Microsystems, Inc. All rights reserved. + * + * Permission to use, copy, modify, and distribute this + * software is freely granted, provided that this notice + * is preserved. + * ==================================================== + */ +/* exp(x) + * Returns the exponential of x. + * + * Method + * 1. Argument reduction: + * Reduce x to an r so that |r| <= 0.5*ln2 ~ 0.34658. + * Given x, find r and integer k such that + * + * x = k*ln2 + r, |r| <= 0.5*ln2. + * + * Here r will be represented as r = hi-lo for better + * accuracy. + * + * 2. Approximation of exp(r) by a special rational function on + * the interval [0,0.34658]: + * Write + * R(r**2) = r*(exp(r)+1)/(exp(r)-1) = 2 + r*r/6 - r**4/360 + ... + * We use a special Remez algorithm on [0,0.34658] to generate + * a polynomial of degree 5 to approximate R. The maximum error + * of this polynomial approximation is bounded by 2**-59. In + * other words, + * R(z) ~ 2.0 + P1*z + P2*z**2 + P3*z**3 + P4*z**4 + P5*z**5 + * (where z=r*r, and the values of P1 to P5 are listed below) + * and + * | 5 | -59 + * | 2.0+P1*z+...+P5*z - R(z) | <= 2 + * | | + * The computation of exp(r) thus becomes + * 2*r + * exp(r) = 1 + ---------- + * R(r) - r + * r*c(r) + * = 1 + r + ----------- (for better accuracy) + * 2 - c(r) + * where + * 2 4 10 + * c(r) = r - (P1*r + P2*r + ... + P5*r ). + * + * 3. Scale back to obtain exp(x): + * From step 1, we have + * exp(x) = 2^k * exp(r) + * + * Special cases: + * exp(INF) is INF, exp(NaN) is NaN; + * exp(-INF) is 0, and + * for finite argument, only exp(0)=1 is exact. + * + * Accuracy: + * according to an error analysis, the error is always less than + * 1 ulp (unit in the last place). + * + * Misc. info. + * For IEEE double + * if x > 709.782712893383973096 then exp(x) overflows + * if x < -745.133219101941108420 then exp(x) underflows + */ + +#include "libm.h" + +static const double +half[2] = {0.5,-0.5}, +ln2hi = 6.93147180369123816490e-01, /* 0x3fe62e42, 0xfee00000 */ +ln2lo = 1.90821492927058770002e-10, /* 0x3dea39ef, 0x35793c76 */ +invln2 = 1.44269504088896338700e+00, /* 0x3ff71547, 0x652b82fe */ +P1 = 1.66666666666666019037e-01, /* 0x3FC55555, 0x5555553E */ +P2 = -2.77777777770155933842e-03, /* 0xBF66C16C, 0x16BEBD93 */ +P3 = 6.61375632143793436117e-05, /* 0x3F11566A, 0xAF25DE2C */ +P4 = -1.65339022054652515390e-06, /* 0xBEBBBD41, 0xC5D26BF1 */ +P5 = 4.13813679705723846039e-08; /* 0x3E663769, 0x72BEA4D0 */ + +double exp(double x) +{ + double_t hi, lo, c, xx, y; + int k, sign; + uint32_t hx; + + GET_HIGH_WORD(hx, x); + sign = hx>>31; + hx &= 0x7fffffff; /* high word of |x| */ + + /* special cases */ + if (hx >= 0x4086232b) { /* if |x| >= 708.39... */ + if (isnan(x)) + return x; + if (x > 709.782712893383973096) { + /* overflow if x!=inf */ + x *= 0x1p1023; + return x; + } + if (x < -708.39641853226410622) { + /* underflow if x!=-inf */ + FORCE_EVAL((float)(-0x1p-149/x)); + if (x < -745.13321910194110842) + return 0; + } + } + + /* argument reduction */ + if (hx > 0x3fd62e42) { /* if |x| > 0.5 ln2 */ + if (hx >= 0x3ff0a2b2) /* if |x| >= 1.5 ln2 */ + k = (int)(invln2*x + half[sign]); + else + k = 1 - sign - sign; + hi = x - k*ln2hi; /* k*ln2hi is exact here */ + lo = k*ln2lo; + x = hi - lo; + } else if (hx > 0x3e300000) { /* if |x| > 2**-28 */ + k = 0; + hi = x; + lo = 0; + } else { + /* inexact if x!=0 */ + FORCE_EVAL(0x1p1023 + x); + return 1 + x; + } + + /* x is now in primary range */ + xx = x*x; + c = x - xx*(P1+xx*(P2+xx*(P3+xx*(P4+xx*P5)))); + y = 1 + (x*c/(2-c) - lo + hi); + if (k == 0) + return y; + return scalbn(y, k); +} diff --git a/lib/libm_dbl/expm1.c b/lib/libm_dbl/expm1.c new file mode 100644 index 0000000000..ac1e61e4f7 --- /dev/null +++ b/lib/libm_dbl/expm1.c @@ -0,0 +1,201 @@ +/* origin: FreeBSD /usr/src/lib/msun/src/s_expm1.c */ +/* + * ==================================================== + * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + * + * Developed at SunPro, a Sun Microsystems, Inc. business. + * Permission to use, copy, modify, and distribute this + * software is freely granted, provided that this notice + * is preserved. + * ==================================================== + */ +/* expm1(x) + * Returns exp(x)-1, the exponential of x minus 1. + * + * Method + * 1. Argument reduction: + * Given x, find r and integer k such that + * + * x = k*ln2 + r, |r| <= 0.5*ln2 ~ 0.34658 + * + * Here a correction term c will be computed to compensate + * the error in r when rounded to a floating-point number. + * + * 2. Approximating expm1(r) by a special rational function on + * the interval [0,0.34658]: + * Since + * r*(exp(r)+1)/(exp(r)-1) = 2+ r^2/6 - r^4/360 + ... + * we define R1(r*r) by + * r*(exp(r)+1)/(exp(r)-1) = 2+ r^2/6 * R1(r*r) + * That is, + * R1(r**2) = 6/r *((exp(r)+1)/(exp(r)-1) - 2/r) + * = 6/r * ( 1 + 2.0*(1/(exp(r)-1) - 1/r)) + * = 1 - r^2/60 + r^4/2520 - r^6/100800 + ... + * We use a special Remez algorithm on [0,0.347] to generate + * a polynomial of degree 5 in r*r to approximate R1. The + * maximum error of this polynomial approximation is bounded + * by 2**-61. In other words, + * R1(z) ~ 1.0 + Q1*z + Q2*z**2 + Q3*z**3 + Q4*z**4 + Q5*z**5 + * where Q1 = -1.6666666666666567384E-2, + * Q2 = 3.9682539681370365873E-4, + * Q3 = -9.9206344733435987357E-6, + * Q4 = 2.5051361420808517002E-7, + * Q5 = -6.2843505682382617102E-9; + * z = r*r, + * with error bounded by + * | 5 | -61 + * | 1.0+Q1*z+...+Q5*z - R1(z) | <= 2 + * | | + * + * expm1(r) = exp(r)-1 is then computed by the following + * specific way which minimize the accumulation rounding error: + * 2 3 + * r r [ 3 - (R1 + R1*r/2) ] + * expm1(r) = r + --- + --- * [--------------------] + * 2 2 [ 6 - r*(3 - R1*r/2) ] + * + * To compensate the error in the argument reduction, we use + * expm1(r+c) = expm1(r) + c + expm1(r)*c + * ~ expm1(r) + c + r*c + * Thus c+r*c will be added in as the correction terms for + * expm1(r+c). Now rearrange the term to avoid optimization + * screw up: + * ( 2 2 ) + * ({ ( r [ R1 - (3 - R1*r/2) ] ) } r ) + * expm1(r+c)~r - ({r*(--- * [--------------------]-c)-c} - --- ) + * ({ ( 2 [ 6 - r*(3 - R1*r/2) ] ) } 2 ) + * ( ) + * + * = r - E + * 3. Scale back to obtain expm1(x): + * From step 1, we have + * expm1(x) = either 2^k*[expm1(r)+1] - 1 + * = or 2^k*[expm1(r) + (1-2^-k)] + * 4. Implementation notes: + * (A). To save one multiplication, we scale the coefficient Qi + * to Qi*2^i, and replace z by (x^2)/2. + * (B). To achieve maximum accuracy, we compute expm1(x) by + * (i) if x < -56*ln2, return -1.0, (raise inexact if x!=inf) + * (ii) if k=0, return r-E + * (iii) if k=-1, return 0.5*(r-E)-0.5 + * (iv) if k=1 if r < -0.25, return 2*((r+0.5)- E) + * else return 1.0+2.0*(r-E); + * (v) if (k<-2||k>56) return 2^k(1-(E-r)) - 1 (or exp(x)-1) + * (vi) if k <= 20, return 2^k((1-2^-k)-(E-r)), else + * (vii) return 2^k(1-((E+2^-k)-r)) + * + * Special cases: + * expm1(INF) is INF, expm1(NaN) is NaN; + * expm1(-INF) is -1, and + * for finite argument, only expm1(0)=0 is exact. + * + * Accuracy: + * according to an error analysis, the error is always less than + * 1 ulp (unit in the last place). + * + * Misc. info. + * For IEEE double + * if x > 7.09782712893383973096e+02 then expm1(x) overflow + * + * Constants: + * The hexadecimal values are the intended ones for the following + * constants. The decimal values may be used, provided that the + * compiler will convert from decimal to binary accurately enough + * to produce the hexadecimal values shown. + */ + +#include "libm.h" + +static const double +o_threshold = 7.09782712893383973096e+02, /* 0x40862E42, 0xFEFA39EF */ +ln2_hi = 6.93147180369123816490e-01, /* 0x3fe62e42, 0xfee00000 */ +ln2_lo = 1.90821492927058770002e-10, /* 0x3dea39ef, 0x35793c76 */ +invln2 = 1.44269504088896338700e+00, /* 0x3ff71547, 0x652b82fe */ +/* Scaled Q's: Qn_here = 2**n * Qn_above, for R(2*z) where z = hxs = x*x/2: */ +Q1 = -3.33333333333331316428e-02, /* BFA11111 111110F4 */ +Q2 = 1.58730158725481460165e-03, /* 3F5A01A0 19FE5585 */ +Q3 = -7.93650757867487942473e-05, /* BF14CE19 9EAADBB7 */ +Q4 = 4.00821782732936239552e-06, /* 3ED0CFCA 86E65239 */ +Q5 = -2.01099218183624371326e-07; /* BE8AFDB7 6E09C32D */ + +double expm1(double x) +{ + double_t y,hi,lo,c,t,e,hxs,hfx,r1,twopk; + union {double f; uint64_t i;} u = {x}; + uint32_t hx = u.i>>32 & 0x7fffffff; + int k, sign = u.i>>63; + + /* filter out huge and non-finite argument */ + if (hx >= 0x4043687A) { /* if |x|>=56*ln2 */ + if (isnan(x)) + return x; + if (sign) + return -1; + if (x > o_threshold) { + x *= 0x1p1023; + return x; + } + } + + /* argument reduction */ + if (hx > 0x3fd62e42) { /* if |x| > 0.5 ln2 */ + if (hx < 0x3FF0A2B2) { /* and |x| < 1.5 ln2 */ + if (!sign) { + hi = x - ln2_hi; + lo = ln2_lo; + k = 1; + } else { + hi = x + ln2_hi; + lo = -ln2_lo; + k = -1; + } + } else { + k = invln2*x + (sign ? -0.5 : 0.5); + t = k; + hi = x - t*ln2_hi; /* t*ln2_hi is exact here */ + lo = t*ln2_lo; + } + x = hi-lo; + c = (hi-x)-lo; + } else if (hx < 0x3c900000) { /* |x| < 2**-54, return x */ + if (hx < 0x00100000) + FORCE_EVAL((float)x); + return x; + } else + k = 0; + + /* x is now in primary range */ + hfx = 0.5*x; + hxs = x*hfx; + r1 = 1.0+hxs*(Q1+hxs*(Q2+hxs*(Q3+hxs*(Q4+hxs*Q5)))); + t = 3.0-r1*hfx; + e = hxs*((r1-t)/(6.0 - x*t)); + if (k == 0) /* c is 0 */ + return x - (x*e-hxs); + e = x*(e-c) - c; + e -= hxs; + /* exp(x) ~ 2^k (x_reduced - e + 1) */ + if (k == -1) + return 0.5*(x-e) - 0.5; + if (k == 1) { + if (x < -0.25) + return -2.0*(e-(x+0.5)); + return 1.0+2.0*(x-e); + } + u.i = (uint64_t)(0x3ff + k)<<52; /* 2^k */ + twopk = u.f; + if (k < 0 || k > 56) { /* suffice to return exp(x)-1 */ + y = x - e + 1.0; + if (k == 1024) + y = y*2.0*0x1p1023; + else + y = y*twopk; + return y - 1.0; + } + u.i = (uint64_t)(0x3ff - k)<<52; /* 2^-k */ + if (k < 20) + y = (x-e+(1-u.f))*twopk; + else + y = (x-(e+u.f)+1)*twopk; + return y; +} diff --git a/lib/libm_dbl/floor.c b/lib/libm_dbl/floor.c new file mode 100644 index 0000000000..14a31cd8c4 --- /dev/null +++ b/lib/libm_dbl/floor.c @@ -0,0 +1,31 @@ +#include "libm.h" + +#if FLT_EVAL_METHOD==0 || FLT_EVAL_METHOD==1 +#define EPS DBL_EPSILON +#elif FLT_EVAL_METHOD==2 +#define EPS LDBL_EPSILON +#endif +static const double_t toint = 1/EPS; + +double floor(double x) +{ + union {double f; uint64_t i;} u = {x}; + int e = u.i >> 52 & 0x7ff; + double_t y; + + if (e >= 0x3ff+52 || x == 0) + return x; + /* y = int(x) - x, where int(x) is an integer neighbor of x */ + if (u.i >> 63) + y = x - toint + toint - x; + else + y = x + toint - toint - x; + /* special case because of non-nearest rounding modes */ + if (e <= 0x3ff-1) { + FORCE_EVAL(y); + return u.i >> 63 ? -1 : 0; + } + if (y > 0) + return x + y - 1; + return x + y; +} diff --git a/lib/libm_dbl/fmod.c b/lib/libm_dbl/fmod.c new file mode 100644 index 0000000000..6849722bac --- /dev/null +++ b/lib/libm_dbl/fmod.c @@ -0,0 +1,68 @@ +#include +#include + +double fmod(double x, double y) +{ + union {double f; uint64_t i;} ux = {x}, uy = {y}; + int ex = ux.i>>52 & 0x7ff; + int ey = uy.i>>52 & 0x7ff; + int sx = ux.i>>63; + uint64_t i; + + /* in the followings uxi should be ux.i, but then gcc wrongly adds */ + /* float load/store to inner loops ruining performance and code size */ + uint64_t uxi = ux.i; + + if (uy.i<<1 == 0 || isnan(y) || ex == 0x7ff) + return (x*y)/(x*y); + if (uxi<<1 <= uy.i<<1) { + if (uxi<<1 == uy.i<<1) + return 0*x; + return x; + } + + /* normalize x and y */ + if (!ex) { + for (i = uxi<<12; i>>63 == 0; ex--, i <<= 1); + uxi <<= -ex + 1; + } else { + uxi &= -1ULL >> 12; + uxi |= 1ULL << 52; + } + if (!ey) { + for (i = uy.i<<12; i>>63 == 0; ey--, i <<= 1); + uy.i <<= -ey + 1; + } else { + uy.i &= -1ULL >> 12; + uy.i |= 1ULL << 52; + } + + /* x mod y */ + for (; ex > ey; ex--) { + i = uxi - uy.i; + if (i >> 63 == 0) { + if (i == 0) + return 0*x; + uxi = i; + } + uxi <<= 1; + } + i = uxi - uy.i; + if (i >> 63 == 0) { + if (i == 0) + return 0*x; + uxi = i; + } + for (; uxi>>52 == 0; uxi <<= 1, ex--); + + /* scale result */ + if (ex > 0) { + uxi -= 1ULL << 52; + uxi |= (uint64_t)ex << 52; + } else { + uxi >>= -ex + 1; + } + uxi |= (uint64_t)sx << 63; + ux.i = uxi; + return ux.f; +} diff --git a/lib/libm_dbl/frexp.c b/lib/libm_dbl/frexp.c new file mode 100644 index 0000000000..27b6266ed0 --- /dev/null +++ b/lib/libm_dbl/frexp.c @@ -0,0 +1,23 @@ +#include +#include + +double frexp(double x, int *e) +{ + union { double d; uint64_t i; } y = { x }; + int ee = y.i>>52 & 0x7ff; + + if (!ee) { + if (x) { + x = frexp(x*0x1p64, e); + *e -= 64; + } else *e = 0; + return x; + } else if (ee == 0x7ff) { + return x; + } + + *e = ee - 0x3fe; + y.i &= 0x800fffffffffffffull; + y.i |= 0x3fe0000000000000ull; + return y.d; +} diff --git a/lib/libm_dbl/ldexp.c b/lib/libm_dbl/ldexp.c new file mode 100644 index 0000000000..f4d1cd6af5 --- /dev/null +++ b/lib/libm_dbl/ldexp.c @@ -0,0 +1,6 @@ +#include + +double ldexp(double x, int n) +{ + return scalbn(x, n); +} diff --git a/lib/libm_dbl/lgamma.c b/lib/libm_dbl/lgamma.c new file mode 100644 index 0000000000..ed193da17d --- /dev/null +++ b/lib/libm_dbl/lgamma.c @@ -0,0 +1,8 @@ +#include + +double __lgamma_r(double, int*); + +double lgamma(double x) { + int sign; + return __lgamma_r(x, &sign); +} diff --git a/lib/libm_dbl/libm.h b/lib/libm_dbl/libm.h new file mode 100644 index 0000000000..dc0b431a44 --- /dev/null +++ b/lib/libm_dbl/libm.h @@ -0,0 +1,96 @@ +// Portions of this file are extracted from musl-1.1.16 src/internal/libm.h + +/* origin: FreeBSD /usr/src/lib/msun/src/math_private.h */ +/* + * ==================================================== + * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + * + * Developed at SunPro, a Sun Microsystems, Inc. business. + * Permission to use, copy, modify, and distribute this + * software is freely granted, provided that this notice + * is preserved. + * ==================================================== + */ + +#include +#include + +#define FLT_EVAL_METHOD 0 + +#define FORCE_EVAL(x) do { \ + if (sizeof(x) == sizeof(float)) { \ + volatile float __x; \ + __x = (x); \ + (void)__x; \ + } else if (sizeof(x) == sizeof(double)) { \ + volatile double __x; \ + __x = (x); \ + (void)__x; \ + } else { \ + volatile long double __x; \ + __x = (x); \ + (void)__x; \ + } \ +} while(0) + +/* Get two 32 bit ints from a double. */ +#define EXTRACT_WORDS(hi,lo,d) \ +do { \ + union {double f; uint64_t i;} __u; \ + __u.f = (d); \ + (hi) = __u.i >> 32; \ + (lo) = (uint32_t)__u.i; \ +} while (0) + +/* Get the more significant 32 bit int from a double. */ +#define GET_HIGH_WORD(hi,d) \ +do { \ + union {double f; uint64_t i;} __u; \ + __u.f = (d); \ + (hi) = __u.i >> 32; \ +} while (0) + +/* Get the less significant 32 bit int from a double. */ +#define GET_LOW_WORD(lo,d) \ +do { \ + union {double f; uint64_t i;} __u; \ + __u.f = (d); \ + (lo) = (uint32_t)__u.i; \ +} while (0) + +/* Set a double from two 32 bit ints. */ +#define INSERT_WORDS(d,hi,lo) \ +do { \ + union {double f; uint64_t i;} __u; \ + __u.i = ((uint64_t)(hi)<<32) | (uint32_t)(lo); \ + (d) = __u.f; \ +} while (0) + +/* Set the more significant 32 bits of a double from an int. */ +#define SET_HIGH_WORD(d,hi) \ +do { \ + union {double f; uint64_t i;} __u; \ + __u.f = (d); \ + __u.i &= 0xffffffff; \ + __u.i |= (uint64_t)(hi) << 32; \ + (d) = __u.f; \ +} while (0) + +/* Set the less significant 32 bits of a double from an int. */ +#define SET_LOW_WORD(d,lo) \ +do { \ + union {double f; uint64_t i;} __u; \ + __u.f = (d); \ + __u.i &= 0xffffffff00000000ull; \ + __u.i |= (uint32_t)(lo); \ + (d) = __u.f; \ +} while (0) + +#define DBL_EPSILON 2.22044604925031308085e-16 + +int __rem_pio2(double, double*); +int __rem_pio2_large(double*, double*, int, int, int); +double __sin(double, double, int); +double __cos(double, double); +double __tan(double, double, int); +double __expo2(double); diff --git a/lib/libm_dbl/log.c b/lib/libm_dbl/log.c new file mode 100644 index 0000000000..e61e113d41 --- /dev/null +++ b/lib/libm_dbl/log.c @@ -0,0 +1,118 @@ +/* origin: FreeBSD /usr/src/lib/msun/src/e_log.c */ +/* + * ==================================================== + * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + * + * Developed at SunSoft, a Sun Microsystems, Inc. business. + * Permission to use, copy, modify, and distribute this + * software is freely granted, provided that this notice + * is preserved. + * ==================================================== + */ +/* log(x) + * Return the logarithm of x + * + * Method : + * 1. Argument Reduction: find k and f such that + * x = 2^k * (1+f), + * where sqrt(2)/2 < 1+f < sqrt(2) . + * + * 2. Approximation of log(1+f). + * Let s = f/(2+f) ; based on log(1+f) = log(1+s) - log(1-s) + * = 2s + 2/3 s**3 + 2/5 s**5 + ....., + * = 2s + s*R + * We use a special Remez algorithm on [0,0.1716] to generate + * a polynomial of degree 14 to approximate R The maximum error + * of this polynomial approximation is bounded by 2**-58.45. In + * other words, + * 2 4 6 8 10 12 14 + * R(z) ~ Lg1*s +Lg2*s +Lg3*s +Lg4*s +Lg5*s +Lg6*s +Lg7*s + * (the values of Lg1 to Lg7 are listed in the program) + * and + * | 2 14 | -58.45 + * | Lg1*s +...+Lg7*s - R(z) | <= 2 + * | | + * Note that 2s = f - s*f = f - hfsq + s*hfsq, where hfsq = f*f/2. + * In order to guarantee error in log below 1ulp, we compute log + * by + * log(1+f) = f - s*(f - R) (if f is not too large) + * log(1+f) = f - (hfsq - s*(hfsq+R)). (better accuracy) + * + * 3. Finally, log(x) = k*ln2 + log(1+f). + * = k*ln2_hi+(f-(hfsq-(s*(hfsq+R)+k*ln2_lo))) + * Here ln2 is split into two floating point number: + * ln2_hi + ln2_lo, + * where n*ln2_hi is always exact for |n| < 2000. + * + * Special cases: + * log(x) is NaN with signal if x < 0 (including -INF) ; + * log(+INF) is +INF; log(0) is -INF with signal; + * log(NaN) is that NaN with no signal. + * + * Accuracy: + * according to an error analysis, the error is always less than + * 1 ulp (unit in the last place). + * + * Constants: + * The hexadecimal values are the intended ones for the following + * constants. The decimal values may be used, provided that the + * compiler will convert from decimal to binary accurately enough + * to produce the hexadecimal values shown. + */ + +#include +#include + +static const double +ln2_hi = 6.93147180369123816490e-01, /* 3fe62e42 fee00000 */ +ln2_lo = 1.90821492927058770002e-10, /* 3dea39ef 35793c76 */ +Lg1 = 6.666666666666735130e-01, /* 3FE55555 55555593 */ +Lg2 = 3.999999999940941908e-01, /* 3FD99999 9997FA04 */ +Lg3 = 2.857142874366239149e-01, /* 3FD24924 94229359 */ +Lg4 = 2.222219843214978396e-01, /* 3FCC71C5 1D8E78AF */ +Lg5 = 1.818357216161805012e-01, /* 3FC74664 96CB03DE */ +Lg6 = 1.531383769920937332e-01, /* 3FC39A09 D078C69F */ +Lg7 = 1.479819860511658591e-01; /* 3FC2F112 DF3E5244 */ + +double log(double x) +{ + union {double f; uint64_t i;} u = {x}; + double_t hfsq,f,s,z,R,w,t1,t2,dk; + uint32_t hx; + int k; + + hx = u.i>>32; + k = 0; + if (hx < 0x00100000 || hx>>31) { + if (u.i<<1 == 0) + return -1/(x*x); /* log(+-0)=-inf */ + if (hx>>31) + return (x-x)/0.0; /* log(-#) = NaN */ + /* subnormal number, scale x up */ + k -= 54; + x *= 0x1p54; + u.f = x; + hx = u.i>>32; + } else if (hx >= 0x7ff00000) { + return x; + } else if (hx == 0x3ff00000 && u.i<<32 == 0) + return 0; + + /* reduce x into [sqrt(2)/2, sqrt(2)] */ + hx += 0x3ff00000 - 0x3fe6a09e; + k += (int)(hx>>20) - 0x3ff; + hx = (hx&0x000fffff) + 0x3fe6a09e; + u.i = (uint64_t)hx<<32 | (u.i&0xffffffff); + x = u.f; + + f = x - 1.0; + hfsq = 0.5*f*f; + s = f/(2.0+f); + z = s*s; + w = z*z; + t1 = w*(Lg2+w*(Lg4+w*Lg6)); + t2 = z*(Lg1+w*(Lg3+w*(Lg5+w*Lg7))); + R = t2 + t1; + dk = k; + return s*(hfsq+R) + dk*ln2_lo - hfsq + f + dk*ln2_hi; +} diff --git a/lib/libm_dbl/log10.c b/lib/libm_dbl/log10.c new file mode 100644 index 0000000000..bddedd6829 --- /dev/null +++ b/lib/libm_dbl/log10.c @@ -0,0 +1,7 @@ +#include + +static const double _M_LN10 = 2.302585092994046; + +double log10(double x) { + return log(x) / (double)_M_LN10; +} diff --git a/lib/libm_dbl/log1p.c b/lib/libm_dbl/log1p.c new file mode 100644 index 0000000000..0097134940 --- /dev/null +++ b/lib/libm_dbl/log1p.c @@ -0,0 +1,122 @@ +/* origin: FreeBSD /usr/src/lib/msun/src/s_log1p.c */ +/* + * ==================================================== + * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + * + * Developed at SunPro, a Sun Microsystems, Inc. business. + * Permission to use, copy, modify, and distribute this + * software is freely granted, provided that this notice + * is preserved. + * ==================================================== + */ +/* double log1p(double x) + * Return the natural logarithm of 1+x. + * + * Method : + * 1. Argument Reduction: find k and f such that + * 1+x = 2^k * (1+f), + * where sqrt(2)/2 < 1+f < sqrt(2) . + * + * Note. If k=0, then f=x is exact. However, if k!=0, then f + * may not be representable exactly. In that case, a correction + * term is need. Let u=1+x rounded. Let c = (1+x)-u, then + * log(1+x) - log(u) ~ c/u. Thus, we proceed to compute log(u), + * and add back the correction term c/u. + * (Note: when x > 2**53, one can simply return log(x)) + * + * 2. Approximation of log(1+f): See log.c + * + * 3. Finally, log1p(x) = k*ln2 + log(1+f) + c/u. See log.c + * + * Special cases: + * log1p(x) is NaN with signal if x < -1 (including -INF) ; + * log1p(+INF) is +INF; log1p(-1) is -INF with signal; + * log1p(NaN) is that NaN with no signal. + * + * Accuracy: + * according to an error analysis, the error is always less than + * 1 ulp (unit in the last place). + * + * Constants: + * The hexadecimal values are the intended ones for the following + * constants. The decimal values may be used, provided that the + * compiler will convert from decimal to binary accurately enough + * to produce the hexadecimal values shown. + * + * Note: Assuming log() return accurate answer, the following + * algorithm can be used to compute log1p(x) to within a few ULP: + * + * u = 1+x; + * if(u==1.0) return x ; else + * return log(u)*(x/(u-1.0)); + * + * See HP-15C Advanced Functions Handbook, p.193. + */ + +#include "libm.h" + +static const double +ln2_hi = 6.93147180369123816490e-01, /* 3fe62e42 fee00000 */ +ln2_lo = 1.90821492927058770002e-10, /* 3dea39ef 35793c76 */ +Lg1 = 6.666666666666735130e-01, /* 3FE55555 55555593 */ +Lg2 = 3.999999999940941908e-01, /* 3FD99999 9997FA04 */ +Lg3 = 2.857142874366239149e-01, /* 3FD24924 94229359 */ +Lg4 = 2.222219843214978396e-01, /* 3FCC71C5 1D8E78AF */ +Lg5 = 1.818357216161805012e-01, /* 3FC74664 96CB03DE */ +Lg6 = 1.531383769920937332e-01, /* 3FC39A09 D078C69F */ +Lg7 = 1.479819860511658591e-01; /* 3FC2F112 DF3E5244 */ + +double log1p(double x) +{ + union {double f; uint64_t i;} u = {x}; + double_t hfsq,f,c,s,z,R,w,t1,t2,dk; + uint32_t hx,hu; + int k; + + hx = u.i>>32; + k = 1; + if (hx < 0x3fda827a || hx>>31) { /* 1+x < sqrt(2)+ */ + if (hx >= 0xbff00000) { /* x <= -1.0 */ + if (x == -1) + return x/0.0; /* log1p(-1) = -inf */ + return (x-x)/0.0; /* log1p(x<-1) = NaN */ + } + if (hx<<1 < 0x3ca00000<<1) { /* |x| < 2**-53 */ + /* underflow if subnormal */ + if ((hx&0x7ff00000) == 0) + FORCE_EVAL((float)x); + return x; + } + if (hx <= 0xbfd2bec4) { /* sqrt(2)/2- <= 1+x < sqrt(2)+ */ + k = 0; + c = 0; + f = x; + } + } else if (hx >= 0x7ff00000) + return x; + if (k) { + u.f = 1 + x; + hu = u.i>>32; + hu += 0x3ff00000 - 0x3fe6a09e; + k = (int)(hu>>20) - 0x3ff; + /* correction term ~ log(1+x)-log(u), avoid underflow in c/u */ + if (k < 54) { + c = k >= 2 ? 1-(u.f-x) : x-(u.f-1); + c /= u.f; + } else + c = 0; + /* reduce u into [sqrt(2)/2, sqrt(2)] */ + hu = (hu&0x000fffff) + 0x3fe6a09e; + u.i = (uint64_t)hu<<32 | (u.i&0xffffffff); + f = u.f - 1; + } + hfsq = 0.5*f*f; + s = f/(2.0+f); + z = s*s; + w = z*z; + t1 = w*(Lg2+w*(Lg4+w*Lg6)); + t2 = z*(Lg1+w*(Lg3+w*(Lg5+w*Lg7))); + R = t2 + t1; + dk = k; + return s*(hfsq+R) + (dk*ln2_lo+c) - hfsq + f + dk*ln2_hi; +} diff --git a/lib/libm_dbl/modf.c b/lib/libm_dbl/modf.c new file mode 100644 index 0000000000..1c8a1db90d --- /dev/null +++ b/lib/libm_dbl/modf.c @@ -0,0 +1,34 @@ +#include "libm.h" + +double modf(double x, double *iptr) +{ + union {double f; uint64_t i;} u = {x}; + uint64_t mask; + int e = (int)(u.i>>52 & 0x7ff) - 0x3ff; + + /* no fractional part */ + if (e >= 52) { + *iptr = x; + if (e == 0x400 && u.i<<12 != 0) /* nan */ + return x; + u.i &= 1ULL<<63; + return u.f; + } + + /* no integral part*/ + if (e < 0) { + u.i &= 1ULL<<63; + *iptr = u.f; + return x; + } + + mask = -1ULL>>12>>e; + if ((u.i & mask) == 0) { + *iptr = x; + u.i &= 1ULL<<63; + return u.f; + } + u.i &= ~mask; + *iptr = u.f; + return x - u.f; +} diff --git a/lib/libm_dbl/nearbyint.c b/lib/libm_dbl/nearbyint.c new file mode 100644 index 0000000000..6e9b0c1f78 --- /dev/null +++ b/lib/libm_dbl/nearbyint.c @@ -0,0 +1,20 @@ +//#include +#include + +/* nearbyint is the same as rint, but it must not raise the inexact exception */ + +double nearbyint(double x) +{ +#ifdef FE_INEXACT + #pragma STDC FENV_ACCESS ON + int e; + + e = fetestexcept(FE_INEXACT); +#endif + x = rint(x); +#ifdef FE_INEXACT + if (!e) + feclearexcept(FE_INEXACT); +#endif + return x; +} diff --git a/lib/libm_dbl/pow.c b/lib/libm_dbl/pow.c new file mode 100644 index 0000000000..3ddc1b6ff8 --- /dev/null +++ b/lib/libm_dbl/pow.c @@ -0,0 +1,328 @@ +/* origin: FreeBSD /usr/src/lib/msun/src/e_pow.c */ +/* + * ==================================================== + * Copyright (C) 2004 by Sun Microsystems, Inc. All rights reserved. + * + * Permission to use, copy, modify, and distribute this + * software is freely granted, provided that this notice + * is preserved. + * ==================================================== + */ +/* pow(x,y) return x**y + * + * n + * Method: Let x = 2 * (1+f) + * 1. Compute and return log2(x) in two pieces: + * log2(x) = w1 + w2, + * where w1 has 53-24 = 29 bit trailing zeros. + * 2. Perform y*log2(x) = n+y' by simulating muti-precision + * arithmetic, where |y'|<=0.5. + * 3. Return x**y = 2**n*exp(y'*log2) + * + * Special cases: + * 1. (anything) ** 0 is 1 + * 2. 1 ** (anything) is 1 + * 3. (anything except 1) ** NAN is NAN + * 4. NAN ** (anything except 0) is NAN + * 5. +-(|x| > 1) ** +INF is +INF + * 6. +-(|x| > 1) ** -INF is +0 + * 7. +-(|x| < 1) ** +INF is +0 + * 8. +-(|x| < 1) ** -INF is +INF + * 9. -1 ** +-INF is 1 + * 10. +0 ** (+anything except 0, NAN) is +0 + * 11. -0 ** (+anything except 0, NAN, odd integer) is +0 + * 12. +0 ** (-anything except 0, NAN) is +INF, raise divbyzero + * 13. -0 ** (-anything except 0, NAN, odd integer) is +INF, raise divbyzero + * 14. -0 ** (+odd integer) is -0 + * 15. -0 ** (-odd integer) is -INF, raise divbyzero + * 16. +INF ** (+anything except 0,NAN) is +INF + * 17. +INF ** (-anything except 0,NAN) is +0 + * 18. -INF ** (+odd integer) is -INF + * 19. -INF ** (anything) = -0 ** (-anything), (anything except odd integer) + * 20. (anything) ** 1 is (anything) + * 21. (anything) ** -1 is 1/(anything) + * 22. (-anything) ** (integer) is (-1)**(integer)*(+anything**integer) + * 23. (-anything except 0 and inf) ** (non-integer) is NAN + * + * Accuracy: + * pow(x,y) returns x**y nearly rounded. In particular + * pow(integer,integer) + * always returns the correct integer provided it is + * representable. + * + * Constants : + * The hexadecimal values are the intended ones for the following + * constants. The decimal values may be used, provided that the + * compiler will convert from decimal to binary accurately enough + * to produce the hexadecimal values shown. + */ + +#include "libm.h" + +static const double +bp[] = {1.0, 1.5,}, +dp_h[] = { 0.0, 5.84962487220764160156e-01,}, /* 0x3FE2B803, 0x40000000 */ +dp_l[] = { 0.0, 1.35003920212974897128e-08,}, /* 0x3E4CFDEB, 0x43CFD006 */ +two53 = 9007199254740992.0, /* 0x43400000, 0x00000000 */ +huge = 1.0e300, +tiny = 1.0e-300, +/* poly coefs for (3/2)*(log(x)-2s-2/3*s**3 */ +L1 = 5.99999999999994648725e-01, /* 0x3FE33333, 0x33333303 */ +L2 = 4.28571428578550184252e-01, /* 0x3FDB6DB6, 0xDB6FABFF */ +L3 = 3.33333329818377432918e-01, /* 0x3FD55555, 0x518F264D */ +L4 = 2.72728123808534006489e-01, /* 0x3FD17460, 0xA91D4101 */ +L5 = 2.30660745775561754067e-01, /* 0x3FCD864A, 0x93C9DB65 */ +L6 = 2.06975017800338417784e-01, /* 0x3FCA7E28, 0x4A454EEF */ +P1 = 1.66666666666666019037e-01, /* 0x3FC55555, 0x5555553E */ +P2 = -2.77777777770155933842e-03, /* 0xBF66C16C, 0x16BEBD93 */ +P3 = 6.61375632143793436117e-05, /* 0x3F11566A, 0xAF25DE2C */ +P4 = -1.65339022054652515390e-06, /* 0xBEBBBD41, 0xC5D26BF1 */ +P5 = 4.13813679705723846039e-08, /* 0x3E663769, 0x72BEA4D0 */ +lg2 = 6.93147180559945286227e-01, /* 0x3FE62E42, 0xFEFA39EF */ +lg2_h = 6.93147182464599609375e-01, /* 0x3FE62E43, 0x00000000 */ +lg2_l = -1.90465429995776804525e-09, /* 0xBE205C61, 0x0CA86C39 */ +ovt = 8.0085662595372944372e-017, /* -(1024-log2(ovfl+.5ulp)) */ +cp = 9.61796693925975554329e-01, /* 0x3FEEC709, 0xDC3A03FD =2/(3ln2) */ +cp_h = 9.61796700954437255859e-01, /* 0x3FEEC709, 0xE0000000 =(float)cp */ +cp_l = -7.02846165095275826516e-09, /* 0xBE3E2FE0, 0x145B01F5 =tail of cp_h*/ +ivln2 = 1.44269504088896338700e+00, /* 0x3FF71547, 0x652B82FE =1/ln2 */ +ivln2_h = 1.44269502162933349609e+00, /* 0x3FF71547, 0x60000000 =24b 1/ln2*/ +ivln2_l = 1.92596299112661746887e-08; /* 0x3E54AE0B, 0xF85DDF44 =1/ln2 tail*/ + +double pow(double x, double y) +{ + double z,ax,z_h,z_l,p_h,p_l; + double y1,t1,t2,r,s,t,u,v,w; + int32_t i,j,k,yisint,n; + int32_t hx,hy,ix,iy; + uint32_t lx,ly; + + EXTRACT_WORDS(hx, lx, x); + EXTRACT_WORDS(hy, ly, y); + ix = hx & 0x7fffffff; + iy = hy & 0x7fffffff; + + /* x**0 = 1, even if x is NaN */ + if ((iy|ly) == 0) + return 1.0; + /* 1**y = 1, even if y is NaN */ + if (hx == 0x3ff00000 && lx == 0) + return 1.0; + /* NaN if either arg is NaN */ + if (ix > 0x7ff00000 || (ix == 0x7ff00000 && lx != 0) || + iy > 0x7ff00000 || (iy == 0x7ff00000 && ly != 0)) + return x + y; + + /* determine if y is an odd int when x < 0 + * yisint = 0 ... y is not an integer + * yisint = 1 ... y is an odd int + * yisint = 2 ... y is an even int + */ + yisint = 0; + if (hx < 0) { + if (iy >= 0x43400000) + yisint = 2; /* even integer y */ + else if (iy >= 0x3ff00000) { + k = (iy>>20) - 0x3ff; /* exponent */ + if (k > 20) { + uint32_t j = ly>>(52-k); + if ((j<<(52-k)) == ly) + yisint = 2 - (j&1); + } else if (ly == 0) { + uint32_t j = iy>>(20-k); + if ((j<<(20-k)) == iy) + yisint = 2 - (j&1); + } + } + } + + /* special value of y */ + if (ly == 0) { + if (iy == 0x7ff00000) { /* y is +-inf */ + if (((ix-0x3ff00000)|lx) == 0) /* (-1)**+-inf is 1 */ + return 1.0; + else if (ix >= 0x3ff00000) /* (|x|>1)**+-inf = inf,0 */ + return hy >= 0 ? y : 0.0; + else /* (|x|<1)**+-inf = 0,inf */ + return hy >= 0 ? 0.0 : -y; + } + if (iy == 0x3ff00000) { /* y is +-1 */ + if (hy >= 0) + return x; + y = 1/x; +#if FLT_EVAL_METHOD!=0 + { + union {double f; uint64_t i;} u = {y}; + uint64_t i = u.i & -1ULL/2; + if (i>>52 == 0 && (i&(i-1))) + FORCE_EVAL((float)y); + } +#endif + return y; + } + if (hy == 0x40000000) /* y is 2 */ + return x*x; + if (hy == 0x3fe00000) { /* y is 0.5 */ + if (hx >= 0) /* x >= +0 */ + return sqrt(x); + } + } + + ax = fabs(x); + /* special value of x */ + if (lx == 0) { + if (ix == 0x7ff00000 || ix == 0 || ix == 0x3ff00000) { /* x is +-0,+-inf,+-1 */ + z = ax; + if (hy < 0) /* z = (1/|x|) */ + z = 1.0/z; + if (hx < 0) { + if (((ix-0x3ff00000)|yisint) == 0) { + z = (z-z)/(z-z); /* (-1)**non-int is NaN */ + } else if (yisint == 1) + z = -z; /* (x<0)**odd = -(|x|**odd) */ + } + return z; + } + } + + s = 1.0; /* sign of result */ + if (hx < 0) { + if (yisint == 0) /* (x<0)**(non-int) is NaN */ + return (x-x)/(x-x); + if (yisint == 1) /* (x<0)**(odd int) */ + s = -1.0; + } + + /* |y| is huge */ + if (iy > 0x41e00000) { /* if |y| > 2**31 */ + if (iy > 0x43f00000) { /* if |y| > 2**64, must o/uflow */ + if (ix <= 0x3fefffff) + return hy < 0 ? huge*huge : tiny*tiny; + if (ix >= 0x3ff00000) + return hy > 0 ? huge*huge : tiny*tiny; + } + /* over/underflow if x is not close to one */ + if (ix < 0x3fefffff) + return hy < 0 ? s*huge*huge : s*tiny*tiny; + if (ix > 0x3ff00000) + return hy > 0 ? s*huge*huge : s*tiny*tiny; + /* now |1-x| is tiny <= 2**-20, suffice to compute + log(x) by x-x^2/2+x^3/3-x^4/4 */ + t = ax - 1.0; /* t has 20 trailing zeros */ + w = (t*t)*(0.5 - t*(0.3333333333333333333333-t*0.25)); + u = ivln2_h*t; /* ivln2_h has 21 sig. bits */ + v = t*ivln2_l - w*ivln2; + t1 = u + v; + SET_LOW_WORD(t1, 0); + t2 = v - (t1-u); + } else { + double ss,s2,s_h,s_l,t_h,t_l; + n = 0; + /* take care subnormal number */ + if (ix < 0x00100000) { + ax *= two53; + n -= 53; + GET_HIGH_WORD(ix,ax); + } + n += ((ix)>>20) - 0x3ff; + j = ix & 0x000fffff; + /* determine interval */ + ix = j | 0x3ff00000; /* normalize ix */ + if (j <= 0x3988E) /* |x|>1)|0x20000000) + 0x00080000 + (k<<18)); + t_l = ax - (t_h-bp[k]); + s_l = v*((u-s_h*t_h)-s_h*t_l); + /* compute log(ax) */ + s2 = ss*ss; + r = s2*s2*(L1+s2*(L2+s2*(L3+s2*(L4+s2*(L5+s2*L6))))); + r += s_l*(s_h+ss); + s2 = s_h*s_h; + t_h = 3.0 + s2 + r; + SET_LOW_WORD(t_h, 0); + t_l = r - ((t_h-3.0)-s2); + /* u+v = ss*(1+...) */ + u = s_h*t_h; + v = s_l*t_h + t_l*ss; + /* 2/(3log2)*(ss+...) */ + p_h = u + v; + SET_LOW_WORD(p_h, 0); + p_l = v - (p_h-u); + z_h = cp_h*p_h; /* cp_h+cp_l = 2/(3*log2) */ + z_l = cp_l*p_h+p_l*cp + dp_l[k]; + /* log2(ax) = (ss+..)*2/(3*log2) = n + dp_h + z_h + z_l */ + t = (double)n; + t1 = ((z_h + z_l) + dp_h[k]) + t; + SET_LOW_WORD(t1, 0); + t2 = z_l - (((t1 - t) - dp_h[k]) - z_h); + } + + /* split up y into y1+y2 and compute (y1+y2)*(t1+t2) */ + y1 = y; + SET_LOW_WORD(y1, 0); + p_l = (y-y1)*t1 + y*t2; + p_h = y1*t1; + z = p_l + p_h; + EXTRACT_WORDS(j, i, z); + if (j >= 0x40900000) { /* z >= 1024 */ + if (((j-0x40900000)|i) != 0) /* if z > 1024 */ + return s*huge*huge; /* overflow */ + if (p_l + ovt > z - p_h) + return s*huge*huge; /* overflow */ + } else if ((j&0x7fffffff) >= 0x4090cc00) { /* z <= -1075 */ // FIXME: instead of abs(j) use unsigned j + if (((j-0xc090cc00)|i) != 0) /* z < -1075 */ + return s*tiny*tiny; /* underflow */ + if (p_l <= z - p_h) + return s*tiny*tiny; /* underflow */ + } + /* + * compute 2**(p_h+p_l) + */ + i = j & 0x7fffffff; + k = (i>>20) - 0x3ff; + n = 0; + if (i > 0x3fe00000) { /* if |z| > 0.5, set n = [z+0.5] */ + n = j + (0x00100000>>(k+1)); + k = ((n&0x7fffffff)>>20) - 0x3ff; /* new k for n */ + t = 0.0; + SET_HIGH_WORD(t, n & ~(0x000fffff>>k)); + n = ((n&0x000fffff)|0x00100000)>>(20-k); + if (j < 0) + n = -n; + p_h -= t; + } + t = p_l + p_h; + SET_LOW_WORD(t, 0); + u = t*lg2_h; + v = (p_l-(t-p_h))*lg2 + t*lg2_l; + z = u + v; + w = v - (z-u); + t = z*z; + t1 = z - t*(P1+t*(P2+t*(P3+t*(P4+t*P5)))); + r = (z*t1)/(t1-2.0) - (w + z*w); + z = 1.0 - (r-z); + GET_HIGH_WORD(j, z); + j += n<<20; + if ((j>>20) <= 0) /* subnormal output */ + z = scalbn(z,n); + else + SET_HIGH_WORD(z, j); + return s*z; +} diff --git a/lib/libm_dbl/rint.c b/lib/libm_dbl/rint.c new file mode 100644 index 0000000000..fbba390e7d --- /dev/null +++ b/lib/libm_dbl/rint.c @@ -0,0 +1,28 @@ +#include +#include +#include + +#if FLT_EVAL_METHOD==0 || FLT_EVAL_METHOD==1 +#define EPS DBL_EPSILON +#elif FLT_EVAL_METHOD==2 +#define EPS LDBL_EPSILON +#endif +static const double_t toint = 1/EPS; + +double rint(double x) +{ + union {double f; uint64_t i;} u = {x}; + int e = u.i>>52 & 0x7ff; + int s = u.i>>63; + double_t y; + + if (e >= 0x3ff+52) + return x; + if (s) + y = x - toint + toint; + else + y = x + toint - toint; + if (y == 0) + return s ? -0.0 : 0; + return y; +} diff --git a/lib/libm_dbl/scalbn.c b/lib/libm_dbl/scalbn.c new file mode 100644 index 0000000000..182f561068 --- /dev/null +++ b/lib/libm_dbl/scalbn.c @@ -0,0 +1,33 @@ +#include +#include + +double scalbn(double x, int n) +{ + union {double f; uint64_t i;} u; + double_t y = x; + + if (n > 1023) { + y *= 0x1p1023; + n -= 1023; + if (n > 1023) { + y *= 0x1p1023; + n -= 1023; + if (n > 1023) + n = 1023; + } + } else if (n < -1022) { + /* make sure final n < -53 to avoid double + rounding in the subnormal range */ + y *= 0x1p-1022 * 0x1p53; + n += 1022 - 53; + if (n < -1022) { + y *= 0x1p-1022 * 0x1p53; + n += 1022 - 53; + if (n < -1022) + n = -1022; + } + } + u.i = (uint64_t)(0x3ff+n)<<52; + x = y * u.f; + return x; +} diff --git a/lib/libm_dbl/sin.c b/lib/libm_dbl/sin.c new file mode 100644 index 0000000000..055e215bc8 --- /dev/null +++ b/lib/libm_dbl/sin.c @@ -0,0 +1,78 @@ +/* origin: FreeBSD /usr/src/lib/msun/src/s_sin.c */ +/* + * ==================================================== + * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + * + * Developed at SunPro, a Sun Microsystems, Inc. business. + * Permission to use, copy, modify, and distribute this + * software is freely granted, provided that this notice + * is preserved. + * ==================================================== + */ +/* sin(x) + * Return sine function of x. + * + * kernel function: + * __sin ... sine function on [-pi/4,pi/4] + * __cos ... cose function on [-pi/4,pi/4] + * __rem_pio2 ... argument reduction routine + * + * Method. + * Let S,C and T denote the sin, cos and tan respectively on + * [-PI/4, +PI/4]. Reduce the argument x to y1+y2 = x-k*pi/2 + * in [-pi/4 , +pi/4], and let n = k mod 4. + * We have + * + * n sin(x) cos(x) tan(x) + * ---------------------------------------------------------- + * 0 S C T + * 1 C -S -1/T + * 2 -S -C T + * 3 -C S -1/T + * ---------------------------------------------------------- + * + * Special cases: + * Let trig be any of sin, cos, or tan. + * trig(+-INF) is NaN, with signals; + * trig(NaN) is that NaN; + * + * Accuracy: + * TRIG(x) returns trig(x) nearly rounded + */ + +#include "libm.h" + +double sin(double x) +{ + double y[2]; + uint32_t ix; + unsigned n; + + /* High word of x. */ + GET_HIGH_WORD(ix, x); + ix &= 0x7fffffff; + + /* |x| ~< pi/4 */ + if (ix <= 0x3fe921fb) { + if (ix < 0x3e500000) { /* |x| < 2**-26 */ + /* raise inexact if x != 0 and underflow if subnormal*/ + FORCE_EVAL(ix < 0x00100000 ? x/0x1p120f : x+0x1p120f); + return x; + } + return __sin(x, 0.0, 0); + } + + /* sin(Inf or NaN) is NaN */ + if (ix >= 0x7ff00000) + return x - x; + + /* argument reduction needed */ + n = __rem_pio2(x, y); + switch (n&3) { + case 0: return __sin(y[0], y[1], 1); + case 1: return __cos(y[0], y[1]); + case 2: return -__sin(y[0], y[1], 1); + default: + return -__cos(y[0], y[1]); + } +} diff --git a/lib/libm_dbl/sinh.c b/lib/libm_dbl/sinh.c new file mode 100644 index 0000000000..00022c4e6f --- /dev/null +++ b/lib/libm_dbl/sinh.c @@ -0,0 +1,39 @@ +#include "libm.h" + +/* sinh(x) = (exp(x) - 1/exp(x))/2 + * = (exp(x)-1 + (exp(x)-1)/exp(x))/2 + * = x + x^3/6 + o(x^5) + */ +double sinh(double x) +{ + union {double f; uint64_t i;} u = {.f = x}; + uint32_t w; + double t, h, absx; + + h = 0.5; + if (u.i >> 63) + h = -h; + /* |x| */ + u.i &= (uint64_t)-1/2; + absx = u.f; + w = u.i >> 32; + + /* |x| < log(DBL_MAX) */ + if (w < 0x40862e42) { + t = expm1(absx); + if (w < 0x3ff00000) { + if (w < 0x3ff00000 - (26<<20)) + /* note: inexact and underflow are raised by expm1 */ + /* note: this branch avoids spurious underflow */ + return x; + return h*(2*t - t*t/(t+1)); + } + /* note: |x|>log(0x1p26)+eps could be just h*exp(x) */ + return h*(t + t/(t+1)); + } + + /* |x| > log(DBL_MAX) or nan */ + /* note: the result is stored to handle overflow */ + t = 2*h*__expo2(absx); + return t; +} diff --git a/lib/libm_dbl/sqrt.c b/lib/libm_dbl/sqrt.c new file mode 100644 index 0000000000..b277567385 --- /dev/null +++ b/lib/libm_dbl/sqrt.c @@ -0,0 +1,185 @@ +/* origin: FreeBSD /usr/src/lib/msun/src/e_sqrt.c */ +/* + * ==================================================== + * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + * + * Developed at SunSoft, a Sun Microsystems, Inc. business. + * Permission to use, copy, modify, and distribute this + * software is freely granted, provided that this notice + * is preserved. + * ==================================================== + */ +/* sqrt(x) + * Return correctly rounded sqrt. + * ------------------------------------------ + * | Use the hardware sqrt if you have one | + * ------------------------------------------ + * Method: + * Bit by bit method using integer arithmetic. (Slow, but portable) + * 1. Normalization + * Scale x to y in [1,4) with even powers of 2: + * find an integer k such that 1 <= (y=x*2^(2k)) < 4, then + * sqrt(x) = 2^k * sqrt(y) + * 2. Bit by bit computation + * Let q = sqrt(y) truncated to i bit after binary point (q = 1), + * i 0 + * i+1 2 + * s = 2*q , and y = 2 * ( y - q ). (1) + * i i i i + * + * To compute q from q , one checks whether + * i+1 i + * + * -(i+1) 2 + * (q + 2 ) <= y. (2) + * i + * -(i+1) + * If (2) is false, then q = q ; otherwise q = q + 2 . + * i+1 i i+1 i + * + * With some algebric manipulation, it is not difficult to see + * that (2) is equivalent to + * -(i+1) + * s + 2 <= y (3) + * i i + * + * The advantage of (3) is that s and y can be computed by + * i i + * the following recurrence formula: + * if (3) is false + * + * s = s , y = y ; (4) + * i+1 i i+1 i + * + * otherwise, + * -i -(i+1) + * s = s + 2 , y = y - s - 2 (5) + * i+1 i i+1 i i + * + * One may easily use induction to prove (4) and (5). + * Note. Since the left hand side of (3) contain only i+2 bits, + * it does not necessary to do a full (53-bit) comparison + * in (3). + * 3. Final rounding + * After generating the 53 bits result, we compute one more bit. + * Together with the remainder, we can decide whether the + * result is exact, bigger than 1/2ulp, or less than 1/2ulp + * (it will never equal to 1/2ulp). + * The rounding mode can be detected by checking whether + * huge + tiny is equal to huge, and whether huge - tiny is + * equal to huge for some floating point number "huge" and "tiny". + * + * Special cases: + * sqrt(+-0) = +-0 ... exact + * sqrt(inf) = inf + * sqrt(-ve) = NaN ... with invalid signal + * sqrt(NaN) = NaN ... with invalid signal for signaling NaN + */ + +#include "libm.h" + +static const double tiny = 1.0e-300; + +double sqrt(double x) +{ + double z; + int32_t sign = (int)0x80000000; + int32_t ix0,s0,q,m,t,i; + uint32_t r,t1,s1,ix1,q1; + + EXTRACT_WORDS(ix0, ix1, x); + + /* take care of Inf and NaN */ + if ((ix0&0x7ff00000) == 0x7ff00000) { + return x*x + x; /* sqrt(NaN)=NaN, sqrt(+inf)=+inf, sqrt(-inf)=sNaN */ + } + /* take care of zero */ + if (ix0 <= 0) { + if (((ix0&~sign)|ix1) == 0) + return x; /* sqrt(+-0) = +-0 */ + if (ix0 < 0) + return (x-x)/(x-x); /* sqrt(-ve) = sNaN */ + } + /* normalize x */ + m = ix0>>20; + if (m == 0) { /* subnormal x */ + while (ix0 == 0) { + m -= 21; + ix0 |= (ix1>>11); + ix1 <<= 21; + } + for (i=0; (ix0&0x00100000) == 0; i++) + ix0<<=1; + m -= i - 1; + ix0 |= ix1>>(32-i); + ix1 <<= i; + } + m -= 1023; /* unbias exponent */ + ix0 = (ix0&0x000fffff)|0x00100000; + if (m & 1) { /* odd m, double x to make it even */ + ix0 += ix0 + ((ix1&sign)>>31); + ix1 += ix1; + } + m >>= 1; /* m = [m/2] */ + + /* generate sqrt(x) bit by bit */ + ix0 += ix0 + ((ix1&sign)>>31); + ix1 += ix1; + q = q1 = s0 = s1 = 0; /* [q,q1] = sqrt(x) */ + r = 0x00200000; /* r = moving bit from right to left */ + + while (r != 0) { + t = s0 + r; + if (t <= ix0) { + s0 = t + r; + ix0 -= t; + q += r; + } + ix0 += ix0 + ((ix1&sign)>>31); + ix1 += ix1; + r >>= 1; + } + + r = sign; + while (r != 0) { + t1 = s1 + r; + t = s0; + if (t < ix0 || (t == ix0 && t1 <= ix1)) { + s1 = t1 + r; + if ((t1&sign) == sign && (s1&sign) == 0) + s0++; + ix0 -= t; + if (ix1 < t1) + ix0--; + ix1 -= t1; + q1 += r; + } + ix0 += ix0 + ((ix1&sign)>>31); + ix1 += ix1; + r >>= 1; + } + + /* use floating add to find out rounding direction */ + if ((ix0|ix1) != 0) { + z = 1.0 - tiny; /* raise inexact flag */ + if (z >= 1.0) { + z = 1.0 + tiny; + if (q1 == (uint32_t)0xffffffff) { + q1 = 0; + q++; + } else if (z > 1.0) { + if (q1 == (uint32_t)0xfffffffe) + q++; + q1 += 2; + } else + q1 += q1 & 1; + } + } + ix0 = (q>>1) + 0x3fe00000; + ix1 = q1>>1; + if (q&1) + ix1 |= sign; + ix0 += m << 20; + INSERT_WORDS(z, ix0, ix1); + return z; +} diff --git a/lib/libm_dbl/tan.c b/lib/libm_dbl/tan.c new file mode 100644 index 0000000000..9c724a45af --- /dev/null +++ b/lib/libm_dbl/tan.c @@ -0,0 +1,70 @@ +/* origin: FreeBSD /usr/src/lib/msun/src/s_tan.c */ +/* + * ==================================================== + * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + * + * Developed at SunPro, a Sun Microsystems, Inc. business. + * Permission to use, copy, modify, and distribute this + * software is freely granted, provided that this notice + * is preserved. + * ==================================================== + */ +/* tan(x) + * Return tangent function of x. + * + * kernel function: + * __tan ... tangent function on [-pi/4,pi/4] + * __rem_pio2 ... argument reduction routine + * + * Method. + * Let S,C and T denote the sin, cos and tan respectively on + * [-PI/4, +PI/4]. Reduce the argument x to y1+y2 = x-k*pi/2 + * in [-pi/4 , +pi/4], and let n = k mod 4. + * We have + * + * n sin(x) cos(x) tan(x) + * ---------------------------------------------------------- + * 0 S C T + * 1 C -S -1/T + * 2 -S -C T + * 3 -C S -1/T + * ---------------------------------------------------------- + * + * Special cases: + * Let trig be any of sin, cos, or tan. + * trig(+-INF) is NaN, with signals; + * trig(NaN) is that NaN; + * + * Accuracy: + * TRIG(x) returns trig(x) nearly rounded + */ + +#include "libm.h" + +double tan(double x) +{ + double y[2]; + uint32_t ix; + unsigned n; + + GET_HIGH_WORD(ix, x); + ix &= 0x7fffffff; + + /* |x| ~< pi/4 */ + if (ix <= 0x3fe921fb) { + if (ix < 0x3e400000) { /* |x| < 2**-27 */ + /* raise inexact if x!=0 and underflow if subnormal */ + FORCE_EVAL(ix < 0x00100000 ? x/0x1p120f : x+0x1p120f); + return x; + } + return __tan(x, 0.0, 0); + } + + /* tan(Inf or NaN) is NaN */ + if (ix >= 0x7ff00000) + return x - x; + + /* argument reduction */ + n = __rem_pio2(x, y); + return __tan(y[0], y[1], n&1); +} diff --git a/lib/libm_dbl/tanh.c b/lib/libm_dbl/tanh.c new file mode 100644 index 0000000000..89743ba90f --- /dev/null +++ b/lib/libm_dbl/tanh.c @@ -0,0 +1,5 @@ +#include + +double tanh(double x) { + return sinh(x) / cosh(x); +} diff --git a/lib/libm_dbl/tgamma.c b/lib/libm_dbl/tgamma.c new file mode 100644 index 0000000000..d1d0a04839 --- /dev/null +++ b/lib/libm_dbl/tgamma.c @@ -0,0 +1,222 @@ +/* +"A Precision Approximation of the Gamma Function" - Cornelius Lanczos (1964) +"Lanczos Implementation of the Gamma Function" - Paul Godfrey (2001) +"An Analysis of the Lanczos Gamma Approximation" - Glendon Ralph Pugh (2004) + +approximation method: + + (x - 0.5) S(x) +Gamma(x) = (x + g - 0.5) * ---------------- + exp(x + g - 0.5) + +with + a1 a2 a3 aN +S(x) ~= [ a0 + ----- + ----- + ----- + ... + ----- ] + x + 1 x + 2 x + 3 x + N + +with a0, a1, a2, a3,.. aN constants which depend on g. + +for x < 0 the following reflection formula is used: + +Gamma(x)*Gamma(-x) = -pi/(x sin(pi x)) + +most ideas and constants are from boost and python +*/ +#include "libm.h" + +static const double pi = 3.141592653589793238462643383279502884; + +/* sin(pi x) with x > 0x1p-100, if sin(pi*x)==0 the sign is arbitrary */ +static double sinpi(double x) +{ + int n; + + /* argument reduction: x = |x| mod 2 */ + /* spurious inexact when x is odd int */ + x = x * 0.5; + x = 2 * (x - floor(x)); + + /* reduce x into [-.25,.25] */ + n = 4 * x; + n = (n+1)/2; + x -= n * 0.5; + + x *= pi; + switch (n) { + default: /* case 4 */ + case 0: + return __sin(x, 0, 0); + case 1: + return __cos(x, 0); + case 2: + return __sin(-x, 0, 0); + case 3: + return -__cos(x, 0); + } +} + +#define N 12 +//static const double g = 6.024680040776729583740234375; +static const double gmhalf = 5.524680040776729583740234375; +static const double Snum[N+1] = { + 23531376880.410759688572007674451636754734846804940, + 42919803642.649098768957899047001988850926355848959, + 35711959237.355668049440185451547166705960488635843, + 17921034426.037209699919755754458931112671403265390, + 6039542586.3520280050642916443072979210699388420708, + 1439720407.3117216736632230727949123939715485786772, + 248874557.86205415651146038641322942321632125127801, + 31426415.585400194380614231628318205362874684987640, + 2876370.6289353724412254090516208496135991145378768, + 186056.26539522349504029498971604569928220784236328, + 8071.6720023658162106380029022722506138218516325024, + 210.82427775157934587250973392071336271166969580291, + 2.5066282746310002701649081771338373386264310793408, +}; +static const double Sden[N+1] = { + 0, 39916800, 120543840, 150917976, 105258076, 45995730, 13339535, + 2637558, 357423, 32670, 1925, 66, 1, +}; +/* n! for small integer n */ +static const double fact[] = { + 1, 1, 2, 6, 24, 120, 720, 5040.0, 40320.0, 362880.0, 3628800.0, 39916800.0, + 479001600.0, 6227020800.0, 87178291200.0, 1307674368000.0, 20922789888000.0, + 355687428096000.0, 6402373705728000.0, 121645100408832000.0, + 2432902008176640000.0, 51090942171709440000.0, 1124000727777607680000.0, +}; + +/* S(x) rational function for positive x */ +static double S(double x) +{ + double_t num = 0, den = 0; + int i; + + /* to avoid overflow handle large x differently */ + if (x < 8) + for (i = N; i >= 0; i--) { + num = num * x + Snum[i]; + den = den * x + Sden[i]; + } + else + for (i = 0; i <= N; i++) { + num = num / x + Snum[i]; + den = den / x + Sden[i]; + } + return num/den; +} + +double tgamma(double x) +{ + union {double f; uint64_t i;} u = {x}; + double absx, y; + double_t dy, z, r; + uint32_t ix = u.i>>32 & 0x7fffffff; + int sign = u.i>>63; + + /* special cases */ + if (ix >= 0x7ff00000) + /* tgamma(nan)=nan, tgamma(inf)=inf, tgamma(-inf)=nan with invalid */ + return x + INFINITY; + if (ix < (0x3ff-54)<<20) + /* |x| < 2^-54: tgamma(x) ~ 1/x, +-0 raises div-by-zero */ + return 1/x; + + /* integer arguments */ + /* raise inexact when non-integer */ + if (x == floor(x)) { + if (sign) + return 0/0.0; + if (x <= sizeof fact/sizeof *fact) + return fact[(int)x - 1]; + } + + /* x >= 172: tgamma(x)=inf with overflow */ + /* x =< -184: tgamma(x)=+-0 with underflow */ + if (ix >= 0x40670000) { /* |x| >= 184 */ + if (sign) { + FORCE_EVAL((float)(0x1p-126/x)); + if (floor(x) * 0.5 == floor(x * 0.5)) + return 0; + return -0.0; + } + x *= 0x1p1023; + return x; + } + + absx = sign ? -x : x; + + /* handle the error of x + g - 0.5 */ + y = absx + gmhalf; + if (absx > gmhalf) { + dy = y - absx; + dy -= gmhalf; + } else { + dy = y - gmhalf; + dy -= absx; + } + + z = absx - 0.5; + r = S(absx) * exp(-y); + if (x < 0) { + /* reflection formula for negative x */ + /* sinpi(absx) is not 0, integers are already handled */ + r = -pi / (sinpi(absx) * absx * r); + dy = -dy; + z = -z; + } + r += dy * (gmhalf+0.5) * r / y; + z = pow(y, 0.5*z); + y = r * z * z; + return y; +} + +#if 1 +double __lgamma_r(double x, int *sign) +{ + double r, absx; + + *sign = 1; + + /* special cases */ + if (!isfinite(x)) + /* lgamma(nan)=nan, lgamma(+-inf)=inf */ + return x*x; + + /* integer arguments */ + if (x == floor(x) && x <= 2) { + /* n <= 0: lgamma(n)=inf with divbyzero */ + /* n == 1,2: lgamma(n)=0 */ + if (x <= 0) + return 1/0.0; + return 0; + } + + absx = fabs(x); + + /* lgamma(x) ~ -log(|x|) for tiny |x| */ + if (absx < 0x1p-54) { + *sign = 1 - 2*!!signbit(x); + return -log(absx); + } + + /* use tgamma for smaller |x| */ + if (absx < 128) { + x = tgamma(x); + *sign = 1 - 2*!!signbit(x); + return log(fabs(x)); + } + + /* second term (log(S)-g) could be more precise here.. */ + /* or with stirling: (|x|-0.5)*(log(|x|)-1) + poly(1/|x|) */ + r = (absx-0.5)*(log(absx+gmhalf)-1) + (log(S(absx)) - (gmhalf+0.5)); + if (x < 0) { + /* reflection formula for negative x */ + x = sinpi(absx); + *sign = 2*!!signbit(x) - 1; + r = log(pi/(fabs(x)*absx)) - r; + } + return r; +} + +//weak_alias(__lgamma_r, lgamma_r); +#endif diff --git a/lib/libm_dbl/trunc.c b/lib/libm_dbl/trunc.c new file mode 100644 index 0000000000..d13711b501 --- /dev/null +++ b/lib/libm_dbl/trunc.c @@ -0,0 +1,19 @@ +#include "libm.h" + +double trunc(double x) +{ + union {double f; uint64_t i;} u = {x}; + int e = (int)(u.i >> 52 & 0x7ff) - 0x3ff + 12; + uint64_t m; + + if (e >= 52 + 12) + return x; + if (e < 12) + e = 1; + m = -1ULL >> e; + if ((u.i & m) == 0) + return x; + FORCE_EVAL(x + 0x1p120f); + u.i &= ~m; + return u.f; +} diff --git a/lib/mp-readline/readline.c b/lib/mp-readline/readline.c index 4b98751367..9d254d8cfe 100644 --- a/lib/mp-readline/readline.c +++ b/lib/mp-readline/readline.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -188,17 +188,17 @@ int readline_process_char(int c) { } else if (c == 9) { // tab magic const char *compl_str; - mp_uint_t compl_len = mp_repl_autocomplete(rl.line->buf + rl.orig_line_len, rl.cursor_pos - rl.orig_line_len, &mp_plat_print, &compl_str); + size_t compl_len = mp_repl_autocomplete(rl.line->buf + rl.orig_line_len, rl.cursor_pos - rl.orig_line_len, &mp_plat_print, &compl_str); if (compl_len == 0) { // no match - } else if (compl_len == (mp_uint_t)(-1)) { + } else if (compl_len == (size_t)(-1)) { // many matches mp_hal_stdout_tx_str(rl.prompt); mp_hal_stdout_tx_strn(rl.line->buf + rl.orig_line_len, rl.cursor_pos - rl.orig_line_len); redraw_from_cursor = true; } else { // one match - for (mp_uint_t i = 0; i < compl_len; ++i) { + for (size_t i = 0; i < compl_len; ++i) { vstr_ins_byte(rl.line, rl.cursor_pos + i, *compl_str++); } // set redraw parameters diff --git a/lib/mp-readline/readline.h b/lib/mp-readline/readline.h index f73934d237..00aa9622a8 100644 --- a/lib/mp-readline/readline.h +++ b/lib/mp-readline/readline.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,6 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ +#ifndef MICROPY_INCLUDED_LIB_MP_READLINE_READLINE_H +#define MICROPY_INCLUDED_LIB_MP_READLINE_READLINE_H #define CHAR_CTRL_A (1) #define CHAR_CTRL_B (2) @@ -42,3 +44,5 @@ void readline_push_history(const char *line); void readline_init(vstr_t *line, const char *prompt); void readline_note_newline(const char *prompt); int readline_process_char(int c); + +#endif // MICROPY_INCLUDED_LIB_MP_READLINE_READLINE_H diff --git a/lib/netutils/netutils.c b/lib/netutils/netutils.c index a2ea31cf38..a324521613 100644 --- a/lib/netutils/netutils.c +++ b/lib/netutils/netutils.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/lib/netutils/netutils.h b/lib/netutils/netutils.h index 45e0216402..4befc90db0 100644 --- a/lib/netutils/netutils.h +++ b/lib/netutils/netutils.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -24,8 +24,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -#ifndef __MICROPY_INCLUDED_LIB_NETUTILS_H__ -#define __MICROPY_INCLUDED_LIB_NETUTILS_H__ +#ifndef MICROPY_INCLUDED_LIB_NETUTILS_NETUTILS_H +#define MICROPY_INCLUDED_LIB_NETUTILS_NETUTILS_H #define NETUTILS_IPV4ADDR_BUFSIZE 4 @@ -47,4 +47,4 @@ void netutils_parse_ipv4_addr(mp_obj_t addr_in, uint8_t *out_ip, netutils_endian // puts IP in out_ip (which must take at least IPADDR_BUF_SIZE bytes). mp_uint_t netutils_parse_inet_addr(mp_obj_t addr_in, uint8_t *out_ip, netutils_endian_t endian); -#endif // __MICROPY_INCLUDED_LIB_NETUTILS_H__ +#endif // MICROPY_INCLUDED_LIB_NETUTILS_NETUTILS_H diff --git a/lib/timeutils/timeutils.c b/lib/timeutils/timeutils.c index 06915f25ae..eb3dc80d4b 100644 --- a/lib/timeutils/timeutils.c +++ b/lib/timeutils/timeutils.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -67,7 +67,7 @@ mp_uint_t timeutils_year_day(mp_uint_t year, mp_uint_t month, mp_uint_t date) { void timeutils_seconds_since_2000_to_struct_time(mp_uint_t t, timeutils_struct_time_t *tm) { // The following algorithm was adapted from musl's __secs_to_tm and adapted - // for differences in Micro Python's timebase. + // for differences in MicroPython's timebase. mp_int_t seconds = t - LEAPOCH; diff --git a/lib/timeutils/timeutils.h b/lib/timeutils/timeutils.h index c3f1fc2db1..9b1abeb8f3 100644 --- a/lib/timeutils/timeutils.h +++ b/lib/timeutils/timeutils.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -24,9 +24,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - -#ifndef __MICROPY_INCLUDED_LIB_TIMEUTILS_H__ -#define __MICROPY_INCLUDED_LIB_TIMEUTILS_H__ +#ifndef MICROPY_INCLUDED_LIB_TIMEUTILS_TIMEUTILS_H +#define MICROPY_INCLUDED_LIB_TIMEUTILS_TIMEUTILS_H typedef struct _timeutils_struct_time_t { uint16_t tm_year; // i.e. 2014 @@ -52,4 +51,4 @@ mp_uint_t timeutils_seconds_since_2000(mp_uint_t year, mp_uint_t month, mp_uint_t timeutils_mktime(mp_uint_t year, mp_int_t month, mp_int_t mday, mp_int_t hours, mp_int_t minutes, mp_int_t seconds); -#endif // __MICROPY_INCLUDED_LIB_TIMEUTILS_H__ +#endif // MICROPY_INCLUDED_LIB_TIMEUTILS_TIMEUTILS_H diff --git a/lib/utils/interrupt_char.h b/lib/utils/interrupt_char.h index ae0bf57e8a..ca50d4d567 100644 --- a/lib/utils/interrupt_char.h +++ b/lib/utils/interrupt_char.h @@ -23,7 +23,11 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ +#ifndef MICROPY_INCLUDED_LIB_UTILS_INTERRUPT_CHAR_H +#define MICROPY_INCLUDED_LIB_UTILS_INTERRUPT_CHAR_H extern int mp_interrupt_char; void mp_hal_set_interrupt_char(int c); void mp_keyboard_interrupt(void); + +#endif // MICROPY_INCLUDED_LIB_UTILS_INTERRUPT_CHAR_H diff --git a/lib/utils/printf.c b/lib/utils/printf.c index 303edfcca0..51dfa5b963 100644 --- a/lib/utils/printf.c +++ b/lib/utils/printf.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/lib/utils/pyexec.c b/lib/utils/pyexec.c index 7d0d1cc38b..d3500b42b3 100644 --- a/lib/utils/pyexec.c +++ b/lib/utils/pyexec.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/lib/utils/pyexec.h b/lib/utils/pyexec.h index d7d2a85ab7..bf385e1e53 100644 --- a/lib/utils/pyexec.h +++ b/lib/utils/pyexec.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,8 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -#ifndef __MICROPY_INCLUDED_LIB_UTILS_PYEXEC_H__ -#define __MICROPY_INCLUDED_LIB_UTILS_PYEXEC_H__ +#ifndef MICROPY_INCLUDED_LIB_UTILS_PYEXEC_H +#define MICROPY_INCLUDED_LIB_UTILS_PYEXEC_H typedef enum { PYEXEC_MODE_RAW_REPL, @@ -52,4 +52,4 @@ mp_obj_t pyb_set_repl_info(mp_obj_t o_value); MP_DECLARE_CONST_FUN_OBJ_1(pyb_set_repl_info_obj); -#endif // __MICROPY_INCLUDED_LIB_UTILS_PYEXEC_H__ +#endif // MICROPY_INCLUDED_LIB_UTILS_PYEXEC_H diff --git a/stmhal/pybstdio.c b/lib/utils/sys_stdio_mphal.c similarity index 89% rename from stmhal/pybstdio.c rename to lib/utils/sys_stdio_mphal.c index bd15c583df..fc8a74e7d6 100644 --- a/stmhal/pybstdio.c +++ b/lib/utils/sys_stdio_mphal.c @@ -1,9 +1,9 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * - * Copyright (c) 2013, 2014, 2015 Damien P. George + * Copyright (c) 2013-2017 Damien P. George * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -37,28 +37,28 @@ // objects are in a read-only module (py/modsys.c). /******************************************************************************/ -// Micro Python bindings +// MicroPython bindings #define STDIO_FD_IN (0) #define STDIO_FD_OUT (1) #define STDIO_FD_ERR (2) -typedef struct _pyb_stdio_obj_t { +typedef struct _sys_stdio_obj_t { mp_obj_base_t base; int fd; -} pyb_stdio_obj_t; +} sys_stdio_obj_t; #if MICROPY_PY_SYS_STDIO_BUFFER -STATIC const pyb_stdio_obj_t stdio_buffer_obj; +STATIC const sys_stdio_obj_t stdio_buffer_obj; #endif void stdio_obj_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { - pyb_stdio_obj_t *self = self_in; + sys_stdio_obj_t *self = self_in; mp_printf(print, "", self->fd); } STATIC mp_uint_t stdio_read(mp_obj_t self_in, void *buf, mp_uint_t size, int *errcode) { - pyb_stdio_obj_t *self = self_in; + sys_stdio_obj_t *self = self_in; if (self->fd == STDIO_FD_IN) { for (uint i = 0; i < size; i++) { int c = mp_hal_stdin_rx_chr(); @@ -75,7 +75,7 @@ STATIC mp_uint_t stdio_read(mp_obj_t self_in, void *buf, mp_uint_t size, int *er } STATIC mp_uint_t stdio_write(mp_obj_t self_in, const void *buf, mp_uint_t size, int *errcode) { - pyb_stdio_obj_t *self = self_in; + sys_stdio_obj_t *self = self_in; if (self->fd == STDIO_FD_OUT || self->fd == STDIO_FD_ERR) { mp_hal_stdout_tx_strn_cooked(buf, size); return size; @@ -126,9 +126,9 @@ STATIC const mp_obj_type_t stdio_obj_type = { .locals_dict = (mp_obj_dict_t*)&stdio_locals_dict, }; -const pyb_stdio_obj_t mp_sys_stdin_obj = {{&stdio_obj_type}, .fd = STDIO_FD_IN}; -const pyb_stdio_obj_t mp_sys_stdout_obj = {{&stdio_obj_type}, .fd = STDIO_FD_OUT}; -const pyb_stdio_obj_t mp_sys_stderr_obj = {{&stdio_obj_type}, .fd = STDIO_FD_ERR}; +const sys_stdio_obj_t mp_sys_stdin_obj = {{&stdio_obj_type}, .fd = STDIO_FD_IN}; +const sys_stdio_obj_t mp_sys_stdout_obj = {{&stdio_obj_type}, .fd = STDIO_FD_OUT}; +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) { @@ -159,5 +159,5 @@ STATIC const mp_obj_type_t stdio_buffer_obj_type = { .locals_dict = (mp_obj_t)&stdio_locals_dict, }; -STATIC const pyb_stdio_obj_t stdio_buffer_obj = {{&stdio_buffer_obj_type}, .fd = 0}; // fd unused +STATIC const sys_stdio_obj_t stdio_buffer_obj = {{&stdio_buffer_obj_type}, .fd = 0}; // fd unused #endif diff --git a/logo/FONT-LICENSE.txt b/logo/FONT-LICENSE.txt index 18ac0379f6..69c49d84c8 100644 --- a/logo/FONT-LICENSE.txt +++ b/logo/FONT-LICENSE.txt @@ -1,4 +1,4 @@ -The font used for the Micro Python logo is "Exo", +The font used for the MicroPython logo is "Exo", http://www.google.com/fonts/specimen/Exo. Copyright (c) 2013, Natanael Gama (https://plus.google.com/u/0/+NatanaelGama), diff --git a/minimal/Makefile b/minimal/Makefile index d615157970..994d26880d 100644 --- a/minimal/Makefile +++ b/minimal/Makefile @@ -22,23 +22,21 @@ DFU = ../tools/dfu.py PYDFU = ../tools/pydfu.py CFLAGS_CORTEX_M4 = -mthumb -mtune=cortex-m4 -mabi=aapcs-linux -mcpu=cortex-m4 -mfpu=fpv4-sp-d16 -mfloat-abi=hard -fsingle-precision-constant -Wdouble-promotion CFLAGS = $(INC) -Wall -Werror -std=c99 -nostdlib $(CFLAGS_CORTEX_M4) $(COPT) +LDFLAGS = -nostdlib -T stm32f405.ld -Map=$@.map --cref --gc-sections else +LD = gcc CFLAGS = -m32 $(INC) -Wall -Werror -std=c99 $(COPT) +LDFLAGS = -m32 -Wl,-Map=$@.map,--cref -Wl,--gc-sections endif -#Debugging/Optimization +# Tune for Debugging or Optimization ifeq ($(DEBUG), 1) CFLAGS += -O0 -ggdb else CFLAGS += -Os -DNDEBUG +CFLAGS += -fdata-sections -ffunction-sections endif -ifeq ($(CROSS), 1) -LDFLAGS = -nostdlib -T stm32f405.ld -Map=$@.map --cref -else -LD = gcc -LDFLAGS = -m32 -Wl,-Map=$@.map,--cref -endif LIBS = SRC_C = \ diff --git a/minimal/main.c b/minimal/main.c index 114fb96950..e28cfe45eb 100644 --- a/minimal/main.c +++ b/minimal/main.c @@ -77,7 +77,7 @@ mp_import_stat_t mp_import_stat(const char *path) { return MP_IMPORT_STAT_NO_EXIST; } -mp_obj_t mp_builtin_open(uint n_args, const mp_obj_t *args, mp_map_t *kwargs) { +mp_obj_t mp_builtin_open(size_t n_args, const mp_obj_t *args, mp_map_t *kwargs) { return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_KW(mp_builtin_open_obj, 1, mp_builtin_open); diff --git a/minimal/mpconfigport.h b/minimal/mpconfigport.h index 47fc984290..ce4f8f2404 100644 --- a/minimal/mpconfigport.h +++ b/minimal/mpconfigport.h @@ -1,6 +1,6 @@ #include -// options to control how Micro Python is built +// options to control how MicroPython is built // You can disable the built-in MicroPython compiler by setting the following // config option to 0. If you do this then you won't get a REPL prompt, but you diff --git a/minimal/stm32f405.ld b/minimal/stm32f405.ld index b4aeda744e..a202294a54 100644 --- a/minimal/stm32f405.ld +++ b/minimal/stm32f405.ld @@ -9,7 +9,7 @@ MEMORY CCMRAM (xrw) : ORIGIN = 0x10000000, LENGTH = 0x010000 /* 64 KiB */ RAM (xrw) : ORIGIN = 0x20000000, LENGTH = 0x020000 /* 128 KiB */ } - + /* top end of the stack */ _estack = ORIGIN(RAM) + LENGTH(RAM); @@ -45,7 +45,7 @@ SECTIONS . = ALIGN(4); _edata = .; /* define a global symbol at data end; used by startup code in order to initialise the .data section in RAM */ } >RAM - + /* Uninitialized data section */ .bss : { diff --git a/mpy-cross/Makefile b/mpy-cross/Makefile index f5b643c6cc..cdec130eed 100644 --- a/mpy-cross/Makefile +++ b/mpy-cross/Makefile @@ -44,8 +44,8 @@ COPT = -Os #-DNDEBUG endif # On OSX, 'gcc' is a symlink to clang unless a real gcc is installed. -# The unix port of micropython on OSX must be compiled with clang, -# while cross-compile ports require gcc, so we test here for OSX and +# The unix port of MicroPython on OSX must be compiled with clang, +# while cross-compile ports require gcc, so we test here for OSX and # if necessary override the value of 'CC' set in py/mkenv.mk ifeq ($(UNAME_S),Darwin) CC = clang diff --git a/mpy-cross/main.c b/mpy-cross/main.c index 4c88c72224..ca8d9633fa 100644 --- a/mpy-cross/main.c +++ b/mpy-cross/main.c @@ -28,7 +28,6 @@ #include #include #include -#include #include "py/mpstate.h" #include "py/compile.h" diff --git a/pic16bit/Makefile b/pic16bit/Makefile index 8c0c1c999e..1da4449521 100644 --- a/pic16bit/Makefile +++ b/pic16bit/Makefile @@ -39,8 +39,8 @@ SRC_C = \ modpyb.c \ modpybled.c \ modpybswitch.c \ - stmhal/pybstdio.c \ lib/utils/pyexec.c \ + lib/utils/sys_stdio_mphal.c \ lib/mp-readline/readline.c \ SRC_S = \ diff --git a/pic16bit/board.c b/pic16bit/board.c index 77f059fc70..0321b0ee22 100644 --- a/pic16bit/board.c +++ b/pic16bit/board.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/pic16bit/board.h b/pic16bit/board.h index 0eb022436b..f45f875449 100644 --- a/pic16bit/board.h +++ b/pic16bit/board.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,8 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -#ifndef __MICROPY_INCLUDED_PIC16BIT_BOARD_H__ -#define __MICROPY_INCLUDED_PIC16BIT_BOARD_H__ +#ifndef MICROPY_INCLUDED_PIC16BIT_BOARD_H +#define MICROPY_INCLUDED_PIC16BIT_BOARD_H void cpu_init(void); @@ -40,4 +40,4 @@ int uart_rx_any(void); int uart_rx_char(void); void uart_tx_char(int chr); -#endif // __MICROPY_INCLUDED_PIC16BIT_BOARD_H__ +#endif // MICROPY_INCLUDED_PIC16BIT_BOARD_H diff --git a/pic16bit/main.c b/pic16bit/main.c index 7de790069b..4a61c5ff53 100644 --- a/pic16bit/main.c +++ b/pic16bit/main.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -106,7 +106,7 @@ mp_import_stat_t mp_import_stat(const char *path) { return MP_IMPORT_STAT_NO_EXIST; } -mp_obj_t mp_builtin_open(uint n_args, const mp_obj_t *args, mp_map_t *kwargs) { +mp_obj_t mp_builtin_open(size_t n_args, const mp_obj_t *args, mp_map_t *kwargs) { return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_KW(mp_builtin_open_obj, 1, mp_builtin_open); diff --git a/pic16bit/modpyb.c b/pic16bit/modpyb.c index 326d37f8a1..4a608541e5 100644 --- a/pic16bit/modpyb.c +++ b/pic16bit/modpyb.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/pic16bit/modpyb.h b/pic16bit/modpyb.h index 6c68cbdfdd..ac19fd2f36 100644 --- a/pic16bit/modpyb.h +++ b/pic16bit/modpyb.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,11 +23,11 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -#ifndef __MICROPY_INCLUDED_PIC16BIT_MODPYB_H__ -#define __MICROPY_INCLUDED_PIC16BIT_MODPYB_H__ +#ifndef MICROPY_INCLUDED_PIC16BIT_MODPYB_H +#define MICROPY_INCLUDED_PIC16BIT_MODPYB_H extern const mp_obj_type_t pyb_led_type; extern const mp_obj_type_t pyb_switch_type; extern const mp_obj_module_t pyb_module; -#endif // __MICROPY_INCLUDED_PIC16BIT_MODPYB_H__ +#endif // MICROPY_INCLUDED_PIC16BIT_MODPYB_H diff --git a/pic16bit/modpybled.c b/pic16bit/modpybled.c index 797246d13c..eb04689aa8 100644 --- a/pic16bit/modpybled.c +++ b/pic16bit/modpybled.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/pic16bit/modpybswitch.c b/pic16bit/modpybswitch.c index aa102e8217..4af0c9dfc5 100644 --- a/pic16bit/modpybswitch.c +++ b/pic16bit/modpybswitch.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/pic16bit/mpconfigport.h b/pic16bit/mpconfigport.h index e4113956b3..3cd099c67a 100644 --- a/pic16bit/mpconfigport.h +++ b/pic16bit/mpconfigport.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/pic16bit/pic16bit_mphal.c b/pic16bit/pic16bit_mphal.c index 557b1e0dad..35955f2d3e 100644 --- a/pic16bit/pic16bit_mphal.c +++ b/pic16bit/pic16bit_mphal.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/pic16bit/pic16bit_mphal.h b/pic16bit/pic16bit_mphal.h index a858f7e0fd..f5da6cdc8d 100644 --- a/pic16bit/pic16bit_mphal.h +++ b/pic16bit/pic16bit_mphal.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,13 +23,9 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -#ifndef __MICROPY_INCLUDED_PIC16BIT_PIC16BIT_MPHAL_H__ -#define __MICROPY_INCLUDED_PIC16BIT_PIC16BIT_MPHAL_H__ #include "py/mpstate.h" void mp_hal_init(void); void mp_hal_set_interrupt_char(int c); - -#endif // __MICROPY_INCLUDED_PIC16BIT_PIC16BIT_MPHAL_H__ diff --git a/pic16bit/unistd.h b/pic16bit/unistd.h index cdd9fe0616..5b60c8a626 100644 --- a/pic16bit/unistd.h +++ b/pic16bit/unistd.h @@ -1,5 +1,10 @@ +#ifndef MICROPY_INCLUDED_PIC16BIT_UNISTD_H +#define MICROPY_INCLUDED_PIC16BIT_UNISTD_H + // XC16 compiler doesn't seem to have unistd.h file #define SEEK_CUR 1 typedef int ssize_t; + +#endif // MICROPY_INCLUDED_PIC16BIT_UNISTD_H diff --git a/py/argcheck.c b/py/argcheck.c index 9f225345d5..22fd9cd2c7 100644 --- a/py/argcheck.c +++ b/py/argcheck.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/py/asmarm.c b/py/asmarm.c index da07680e31..552fdfb344 100644 --- a/py/asmarm.c +++ b/py/asmarm.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -135,7 +135,7 @@ STATIC uint asm_arm_op_orr_reg(uint rd, uint rn, uint rm) { void asm_arm_bkpt(asm_arm_t *as) { // bkpt #0 - emit_al(as, 0x1200070); + emit_al(as, 0x1200070); } // locals: diff --git a/py/asmarm.h b/py/asmarm.h index e273b98d73..a302b15905 100644 --- a/py/asmarm.h +++ b/py/asmarm.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -24,8 +24,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -#ifndef __MICROPY_INCLUDED_PY_ASMARM_H__ -#define __MICROPY_INCLUDED_PY_ASMARM_H__ +#ifndef MICROPY_INCLUDED_PY_ASMARM_H +#define MICROPY_INCLUDED_PY_ASMARM_H #include "py/misc.h" #include "py/asmbase.h" @@ -202,4 +202,4 @@ void asm_arm_bl_ind(asm_arm_t *as, void *fun_ptr, uint fun_id, uint reg_temp); #endif // GENERIC_ASM_API -#endif // __MICROPY_INCLUDED_PY_ASMARM_H__ +#endif // MICROPY_INCLUDED_PY_ASMARM_H diff --git a/py/asmthumb.c b/py/asmthumb.c index 7e92e4de41..4360a6af9b 100644 --- a/py/asmthumb.c +++ b/py/asmthumb.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/py/asmthumb.h b/py/asmthumb.h index 52e663b3bd..7070e03ac2 100644 --- a/py/asmthumb.h +++ b/py/asmthumb.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,8 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -#ifndef __MICROPY_INCLUDED_PY_ASMTHUMB_H__ -#define __MICROPY_INCLUDED_PY_ASMTHUMB_H__ +#ifndef MICROPY_INCLUDED_PY_ASMTHUMB_H +#define MICROPY_INCLUDED_PY_ASMTHUMB_H #include "py/misc.h" #include "py/asmbase.h" @@ -318,4 +318,4 @@ void asm_thumb_bl_ind(asm_thumb_t *as, void *fun_ptr, uint fun_id, uint reg_temp #endif // GENERIC_ASM_API -#endif // __MICROPY_INCLUDED_PY_ASMTHUMB_H__ +#endif // MICROPY_INCLUDED_PY_ASMTHUMB_H diff --git a/py/asmx64.c b/py/asmx64.c index cf1a86b3f0..aa2a8ec7cc 100644 --- a/py/asmx64.c +++ b/py/asmx64.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -344,8 +344,9 @@ STATIC void asm_x64_mov_i32_to_r64(asm_x64_t *as, int src_i32, int dest_r64) { void asm_x64_mov_i64_to_r64(asm_x64_t *as, int64_t src_i64, int dest_r64) { // cpu defaults to i32 to r64 // to mov i64 to r64 need to use REX prefix - assert(dest_r64 < 8); - asm_x64_write_byte_2(as, REX_PREFIX | REX_W, OPCODE_MOV_I64_TO_R64 | dest_r64); + asm_x64_write_byte_2(as, + REX_PREFIX | REX_W | (dest_r64 < 8 ? 0 : REX_B), + OPCODE_MOV_I64_TO_R64 | (dest_r64 & 7)); asm_x64_write_word64(as, src_i64); } diff --git a/py/asmx64.h b/py/asmx64.h index 4499c53c32..425bdf2d39 100644 --- a/py/asmx64.h +++ b/py/asmx64.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,8 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -#ifndef __MICROPY_INCLUDED_PY_ASMX64_H__ -#define __MICROPY_INCLUDED_PY_ASMX64_H__ +#ifndef MICROPY_INCLUDED_PY_ASMX64_H +#define MICROPY_INCLUDED_PY_ASMX64_H #include "py/mpconfig.h" #include "py/misc.h" @@ -197,4 +197,4 @@ void asm_x64_call_ind(asm_x64_t* as, void* ptr, int temp_r32); #endif // GENERIC_ASM_API -#endif // __MICROPY_INCLUDED_PY_ASMX64_H__ +#endif // MICROPY_INCLUDED_PY_ASMX64_H diff --git a/py/asmx86.c b/py/asmx86.c index dd3ad02242..6a78fbd5ea 100644 --- a/py/asmx86.c +++ b/py/asmx86.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/py/asmx86.h b/py/asmx86.h index 0b44af6639..0a00e2e7c2 100644 --- a/py/asmx86.h +++ b/py/asmx86.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,8 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -#ifndef __MICROPY_INCLUDED_PY_ASMX86_H__ -#define __MICROPY_INCLUDED_PY_ASMX86_H__ +#ifndef MICROPY_INCLUDED_PY_ASMX86_H +#define MICROPY_INCLUDED_PY_ASMX86_H #include "py/mpconfig.h" #include "py/misc.h" @@ -195,4 +195,4 @@ void asm_x86_call_ind(asm_x86_t* as, void* ptr, mp_uint_t n_args, int temp_r32); #endif // GENERIC_ASM_API -#endif // __MICROPY_INCLUDED_PY_ASMX86_H__ +#endif // MICROPY_INCLUDED_PY_ASMX86_H diff --git a/py/bc.c b/py/bc.c index fc17946839..522eb0aeb0 100644 --- a/py/bc.c +++ b/py/bc.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -64,6 +64,14 @@ mp_uint_t mp_decode_uint_value(const byte *ptr) { return mp_decode_uint(&ptr); } +// This function is used to help reduce stack usage at the caller, for the case when +// the caller doesn't need the actual value and just wants to skip over it. +const byte *mp_decode_uint_skip(const byte *ptr) { + while ((*ptr++) & 0x80) { + } + return 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 // generic message, used also for other argument issues @@ -115,7 +123,7 @@ void mp_setup_code_state(mp_code_state_t *code_state, size_t n_args, size_t n_kw // get params size_t n_state = mp_decode_uint(&code_state->ip); - mp_decode_uint(&code_state->ip); // skip n_exc_stack + code_state->ip = mp_decode_uint_skip(code_state->ip); // skip n_exc_stack size_t scope_flags = *code_state->ip++; size_t n_pos_args = *code_state->ip++; size_t n_kwonly_args = *code_state->ip++; diff --git a/py/bc.h b/py/bc.h index e8d4286125..69e213e422 100644 --- a/py/bc.h +++ b/py/bc.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,8 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -#ifndef __MICROPY_INCLUDED_PY_BC_H__ -#define __MICROPY_INCLUDED_PY_BC_H__ +#ifndef MICROPY_INCLUDED_PY_BC_H +#define MICROPY_INCLUDED_PY_BC_H #include "py/runtime.h" #include "py/obj.h" @@ -92,6 +92,7 @@ typedef struct _mp_code_state_t { mp_uint_t mp_decode_uint(const byte **ptr); mp_uint_t mp_decode_uint_value(const byte *ptr); +const byte *mp_decode_uint_skip(const byte *ptr); mp_vm_return_kind_t mp_execute_bytecode(mp_code_state_t *code_state, volatile mp_obj_t inject_exc); mp_code_state_t *mp_obj_fun_bc_prepare_codestate(mp_obj_t func, size_t n_args, size_t n_kw, const mp_obj_t *args); @@ -118,4 +119,4 @@ uint mp_opcode_format(const byte *ip, size_t *opcode_size); #endif -#endif // __MICROPY_INCLUDED_PY_BC_H__ +#endif // MICROPY_INCLUDED_PY_BC_H diff --git a/py/bc0.h b/py/bc0.h index b5650abe41..f671c5b5a7 100644 --- a/py/bc0.h +++ b/py/bc0.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,10 +23,10 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -#ifndef __MICROPY_INCLUDED_PY_BC0_H__ -#define __MICROPY_INCLUDED_PY_BC0_H__ +#ifndef MICROPY_INCLUDED_PY_BC0_H +#define MICROPY_INCLUDED_PY_BC0_H -// Micro Python byte-codes. +// MicroPython byte-codes. // The comment at the end of the line (if it exists) tells the arguments to the byte-code. #define MP_BC_LOAD_CONST_FALSE (0x10) @@ -116,4 +116,4 @@ #define MP_BC_UNARY_OP_MULTI (0xd0) // + op(7) #define MP_BC_BINARY_OP_MULTI (0xd7) // + op(36) -#endif // __MICROPY_INCLUDED_PY_BC0_H__ +#endif // MICROPY_INCLUDED_PY_BC0_H diff --git a/py/binary.c b/py/binary.c index 34feb384ea..e38aae8ea3 100644 --- a/py/binary.c +++ b/py/binary.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -368,6 +368,7 @@ void mp_binary_set_val_array_from_int(char typecode, void *p, mp_uint_t index, m #if MICROPY_LONGINT_IMPL != MICROPY_LONGINT_IMPL_NONE case 'q': ((long long*)p)[index] = val; + break; case 'Q': ((unsigned long long*)p)[index] = val; break; @@ -383,5 +384,6 @@ void mp_binary_set_val_array_from_int(char typecode, void *p, mp_uint_t index, m // Extension to CPython: array of pointers case 'P': ((void**)p)[index] = (void*)(uintptr_t)val; + break; } } diff --git a/py/binary.h b/py/binary.h index 997d878c81..7b5c60f1ac 100644 --- a/py/binary.h +++ b/py/binary.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,8 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -#ifndef __MICROPY_INCLUDED_PY_BINARY_H__ -#define __MICROPY_INCLUDED_PY_BINARY_H__ +#ifndef MICROPY_INCLUDED_PY_BINARY_H +#define MICROPY_INCLUDED_PY_BINARY_H #include "py/obj.h" @@ -41,4 +41,4 @@ void mp_binary_set_val(char struct_type, char val_type, mp_obj_t val_in, byte ** long long mp_binary_get_int(mp_uint_t size, bool is_signed, bool big_endian, const byte *src); void mp_binary_set_int(mp_uint_t val_sz, bool big_endian, byte *dest, mp_uint_t val); -#endif // __MICROPY_INCLUDED_PY_BINARY_H__ +#endif // MICROPY_INCLUDED_PY_BINARY_H diff --git a/py/builtin.h b/py/builtin.h index ec326d037b..a637b6e222 100644 --- a/py/builtin.h +++ b/py/builtin.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,8 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -#ifndef __MICROPY_INCLUDED_PY_BUILTIN_H__ -#define __MICROPY_INCLUDED_PY_BUILTIN_H__ +#ifndef MICROPY_INCLUDED_PY_BUILTIN_H +#define MICROPY_INCLUDED_PY_BUILTIN_H #include "py/obj.h" @@ -120,4 +120,4 @@ extern const mp_obj_module_t mp_module_btree; extern const char *MICROPY_PY_BUILTINS_HELP_TEXT; -#endif // __MICROPY_INCLUDED_PY_BUILTIN_H__ +#endif // MICROPY_INCLUDED_PY_BUILTIN_H diff --git a/py/builtinevex.c b/py/builtinevex.c index d9a3833ccc..ba8048f702 100644 --- a/py/builtinevex.c +++ b/py/builtinevex.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -113,12 +113,15 @@ STATIC mp_obj_t eval_exec_helper(size_t n_args, const mp_obj_t *args, mp_parse_i // work out the context mp_obj_dict_t *globals = mp_globals_get(); mp_obj_dict_t *locals = mp_locals_get(); - if (n_args > 1) { - globals = MP_OBJ_TO_PTR(args[1]); - if (n_args > 2) { - locals = MP_OBJ_TO_PTR(args[2]); - } else { - locals = globals; + for (size_t i = 1; i < 3 && i < n_args; ++i) { + if (args[i] != mp_const_none) { + if (!MP_OBJ_IS_TYPE(args[i], &mp_type_dict)) { + mp_raise_TypeError(NULL); + } + locals = MP_OBJ_TO_PTR(args[i]); + if (i == 1) { + globals = locals; + } } } diff --git a/py/builtinimport.c b/py/builtinimport.c index 6994fc48f4..e0ce91d9be 100644 --- a/py/builtinimport.c +++ b/py/builtinimport.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -109,7 +109,7 @@ STATIC mp_import_stat_t find_file(const char *file_str, uint file_len, vstr_t *d #if MICROPY_PY_SYS } else { // go through each path looking for a directory or file - for (mp_uint_t i = 0; i < path_num; i++) { + 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); @@ -227,11 +227,11 @@ STATIC void do_load(mp_obj_t module_obj, vstr_t *file) { do_load_from_lexer(module_obj, lex); return; } - #endif + #else // If we get here then the file was not frozen and we can't compile scripts. - nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ImportError, - "script compilation not supported")); + mp_raise_msg(&mp_type_ImportError, "script compilation not supported"); + #endif } STATIC void chop_component(const char *start, const char **end) { @@ -248,7 +248,7 @@ 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 DEBUG_printf("__import__:\n"); - for (mp_uint_t i = 0; i < n_args; i++) { + for (size_t i = 0; i < n_args; i++) { DEBUG_printf(" "); mp_obj_print(args[i], PRINT_REPR); DEBUG_printf("\n"); @@ -262,6 +262,9 @@ mp_obj_t mp_builtin___import__(size_t n_args, const mp_obj_t *args) { fromtuple = args[3]; if (n_args >= 5) { level = MP_OBJ_SMALL_INT_VALUE(args[4]); + if (level < 0) { + mp_raise_ValueError(NULL); + } } } @@ -306,28 +309,13 @@ mp_obj_t mp_builtin___import__(size_t n_args, const mp_obj_t *args) { chop_component(this_name, &p); } - - uint dots_seen = 0; while (level--) { chop_component(this_name, &p); - dots_seen++; } - if (dots_seen == 0 && level >= 1) { - // http://legacy.python.org/dev/peps/pep-0328/#relative-imports-and-name - // "If the module's name does not contain any package information - // (e.g. it is set to '__main__') then relative imports are - // resolved as if the module were a top level module, regardless - // of where the module is actually located on the file system." - // Supposedly this if catches this condition and resolve it properly - // TODO: But nobody knows for sure. This condition happens when - // package's __init__.py does something like "import .submod". So, - // maybe we should check for package here? But quote above doesn't - // talk about packages, it talks about dot-less module names. - DEBUG_printf("Warning: no dots in current module name and level>0\n"); - p = this_name + this_name_l; - } else if (level != -1) { - mp_raise_msg(&mp_type_ImportError, "invalid relative import"); + // We must have some component left over to import from + if (p == this_name) { + mp_raise_ValueError("cannot perform relative import"); } uint new_mod_l = (mod_len == 0 ? (size_t)(p - this_name) : (size_t)(p - this_name) + 1 + mod_len); @@ -340,9 +328,6 @@ mp_obj_t mp_builtin___import__(size_t n_args, const mp_obj_t *args) { qstr new_mod_q = qstr_from_strn(new_mod, new_mod_l); DEBUG_printf("Resolved base name for relative import: '%s'\n", qstr_str(new_mod_q)); - if (new_mod_q == MP_QSTR_) { - mp_raise_ValueError("cannot perform relative import"); - } module_name = MP_OBJ_NEW_QSTR(new_mod_q); mod_str = new_mod; mod_len = new_mod_l; diff --git a/py/compile.c b/py/compile.c index 3b6a264d61..00052e190a 100644 --- a/py/compile.c +++ b/py/compile.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -40,6 +40,8 @@ // TODO need to mangle __attr names +#define INVALID_LABEL (0xffff) + typedef enum { // define rules with a compile function #define DEF_RULE(rule, comp, kind, ...) PN_##rule, @@ -567,7 +569,7 @@ STATIC void close_over_variables_etc(compiler_t *comp, scope_t *this_scope, int for (int j = 0; j < this_scope->id_info_len; j++) { id_info_t *id2 = &this_scope->id_info[j]; if (id2->kind == ID_INFO_KIND_FREE && id->qst == id2->qst) { - // in Micro Python we load closures using LOAD_FAST + // in MicroPython we load closures using LOAD_FAST EMIT_LOAD_FAST(id->qst, id->local_num); nfree += 1; } @@ -652,9 +654,9 @@ STATIC void compile_funcdef_lambdef_param(compiler_t *comp, mp_parse_node_t pn) if (comp->have_star) { comp->num_dict_params += 1; - // in Micro Python we put the default dict parameters into a dictionary using the bytecode + // in MicroPython we put the default dict parameters into a dictionary using the bytecode if (comp->num_dict_params == 1) { - // in Micro Python we put the default positional parameters into a tuple using the bytecode + // in MicroPython we put the default positional parameters into a tuple using the bytecode // we need to do this here before we start building the map for the default keywords if (comp->num_default_params > 0) { EMIT_ARG(build_tuple, comp->num_default_params); @@ -698,7 +700,7 @@ STATIC void compile_funcdef_lambdef(compiler_t *comp, scope_t *scope, mp_parse_n return; } - // in Micro Python we put the default positional parameters into a tuple using the bytecode + // in MicroPython we put the default positional parameters into a tuple using the bytecode // the default keywords args may have already made the tuple; if not, do it now if (comp->num_default_params > 0 && comp->num_dict_params == 0) { EMIT_ARG(build_tuple, comp->num_default_params); @@ -954,7 +956,7 @@ STATIC void compile_del_stmt(compiler_t *comp, mp_parse_node_struct_t *pns) { } STATIC void compile_break_stmt(compiler_t *comp, mp_parse_node_struct_t *pns) { - if (comp->break_label == 0) { + if (comp->break_label == INVALID_LABEL) { compile_syntax_error(comp, (mp_parse_node_t)pns, "'break' outside loop"); } assert(comp->cur_except_level >= comp->break_continue_except_level); @@ -962,7 +964,7 @@ STATIC void compile_break_stmt(compiler_t *comp, mp_parse_node_struct_t *pns) { } STATIC void compile_continue_stmt(compiler_t *comp, mp_parse_node_struct_t *pns) { - if (comp->continue_label == 0) { + if (comp->continue_label == INVALID_LABEL) { compile_syntax_error(comp, (mp_parse_node_t)pns, "'continue' outside loop"); } assert(comp->cur_except_level >= comp->break_continue_except_level); @@ -1406,7 +1408,20 @@ STATIC void compile_for_stmt_optimised_range(compiler_t *comp, mp_parse_node_t p // break/continue apply to outer loop (if any) in the else block END_BREAK_CONTINUE_BLOCK - compile_node(comp, pn_else); + // Compile the else block. We must pop the iterator variables before + // executing the else code because it may contain break/continue statements. + uint end_label = 0; + if (!MP_PARSE_NODE_IS_NULL(pn_else)) { + // discard final value of "var", and possible "end" value + EMIT(pop_top); + if (end_on_stack) { + EMIT(pop_top); + } + compile_node(comp, pn_else); + end_label = comp_next_label(comp); + EMIT_ARG(jump, end_label); + EMIT_ARG(adjust_stack_size, 1 + end_on_stack); + } EMIT_ARG(label_assign, break_label); @@ -1417,6 +1432,10 @@ STATIC void compile_for_stmt_optimised_range(compiler_t *comp, mp_parse_node_t p if (end_on_stack) { EMIT(pop_top); } + + if (!MP_PARSE_NODE_IS_NULL(pn_else)) { + EMIT_ARG(label_assign, end_label); + } } STATIC void compile_for_stmt(compiler_t *comp, mp_parse_node_struct_t *pns) { @@ -1496,7 +1515,7 @@ STATIC void compile_for_stmt(compiler_t *comp, mp_parse_node_struct_t *pns) { // break/continue apply to outer loop (if any) in the else block END_BREAK_CONTINUE_BLOCK - compile_node(comp, pns->nodes[3]); // else (not tested) + compile_node(comp, pns->nodes[3]); // else (may be empty) EMIT_ARG(label_assign, break_label); } @@ -2113,62 +2132,43 @@ STATIC void compile_and_expr(compiler_t *comp, mp_parse_node_struct_t *pns) { c_binary_op(comp, pns, MP_BINARY_OP_AND); } -STATIC void compile_shift_expr(compiler_t *comp, mp_parse_node_struct_t *pns) { - int num_nodes = MP_PARSE_NODE_STRUCT_NUM_NODES(pns); - compile_node(comp, pns->nodes[0]); - for (int i = 1; i + 1 < num_nodes; i += 2) { - compile_node(comp, pns->nodes[i + 1]); - if (MP_PARSE_NODE_IS_TOKEN_KIND(pns->nodes[i], MP_TOKEN_OP_DBL_LESS)) { - EMIT_ARG(binary_op, MP_BINARY_OP_LSHIFT); - } else { - assert(MP_PARSE_NODE_IS_TOKEN_KIND(pns->nodes[i], MP_TOKEN_OP_DBL_MORE)); // should be - EMIT_ARG(binary_op, MP_BINARY_OP_RSHIFT); - } - } -} - -STATIC void compile_arith_expr(compiler_t *comp, mp_parse_node_struct_t *pns) { - int num_nodes = MP_PARSE_NODE_STRUCT_NUM_NODES(pns); - compile_node(comp, pns->nodes[0]); - for (int i = 1; i + 1 < num_nodes; i += 2) { - compile_node(comp, pns->nodes[i + 1]); - if (MP_PARSE_NODE_IS_TOKEN_KIND(pns->nodes[i], MP_TOKEN_OP_PLUS)) { - EMIT_ARG(binary_op, MP_BINARY_OP_ADD); - } else { - assert(MP_PARSE_NODE_IS_TOKEN_KIND(pns->nodes[i], MP_TOKEN_OP_MINUS)); // should be - EMIT_ARG(binary_op, MP_BINARY_OP_SUBTRACT); - } - } -} - STATIC void compile_term(compiler_t *comp, mp_parse_node_struct_t *pns) { int num_nodes = MP_PARSE_NODE_STRUCT_NUM_NODES(pns); compile_node(comp, pns->nodes[0]); for (int i = 1; i + 1 < num_nodes; i += 2) { compile_node(comp, pns->nodes[i + 1]); - if (MP_PARSE_NODE_IS_TOKEN_KIND(pns->nodes[i], MP_TOKEN_OP_STAR)) { - EMIT_ARG(binary_op, MP_BINARY_OP_MULTIPLY); - } else if (MP_PARSE_NODE_IS_TOKEN_KIND(pns->nodes[i], MP_TOKEN_OP_DBL_SLASH)) { - EMIT_ARG(binary_op, MP_BINARY_OP_FLOOR_DIVIDE); - } else if (MP_PARSE_NODE_IS_TOKEN_KIND(pns->nodes[i], MP_TOKEN_OP_SLASH)) { - EMIT_ARG(binary_op, MP_BINARY_OP_TRUE_DIVIDE); - } else { - assert(MP_PARSE_NODE_IS_TOKEN_KIND(pns->nodes[i], MP_TOKEN_OP_PERCENT)); // should be - EMIT_ARG(binary_op, MP_BINARY_OP_MODULO); + 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; + default: + assert(tok == MP_TOKEN_OP_DBL_MORE); + op = MP_BINARY_OP_RSHIFT; + break; } + EMIT_ARG(binary_op, op); } } STATIC void compile_factor_2(compiler_t *comp, mp_parse_node_struct_t *pns) { compile_node(comp, pns->nodes[1]); - if (MP_PARSE_NODE_IS_TOKEN_KIND(pns->nodes[0], MP_TOKEN_OP_PLUS)) { - EMIT_ARG(unary_op, MP_UNARY_OP_POSITIVE); - } else if (MP_PARSE_NODE_IS_TOKEN_KIND(pns->nodes[0], MP_TOKEN_OP_MINUS)) { - EMIT_ARG(unary_op, MP_UNARY_OP_NEGATIVE); - } else { - assert(MP_PARSE_NODE_IS_TOKEN_KIND(pns->nodes[0], MP_TOKEN_OP_TILDE)); // should be - EMIT_ARG(unary_op, MP_UNARY_OP_INVERT); + 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; + default: + assert(tok == MP_TOKEN_OP_TILDE); + op = MP_UNARY_OP_INVERT; + break; } + EMIT_ARG(unary_op, op); } STATIC void compile_atom_expr_normal(compiler_t *comp, mp_parse_node_struct_t *pns) { @@ -2308,6 +2308,10 @@ STATIC void compile_trailer_paren_helper(compiler_t *comp, mp_parse_node_t pn_ar } } else { normal_argument: + if (star_flags) { + compile_syntax_error(comp, args[i], "non-keyword arg after */**"); + return; + } if (n_keyword > 0) { compile_syntax_error(comp, args[i], "non-keyword arg after keyword arg"); return; @@ -2939,7 +2943,7 @@ STATIC void check_for_doc_string(compiler_t *comp, mp_parse_node_t pn) { STATIC void compile_scope(compiler_t *comp, scope_t *scope, pass_kind_t pass) { comp->pass = pass; comp->scope_cur = scope; - comp->next_label = 1; + comp->next_label = 0; EMIT_ARG(start_pass, pass, scope); if (comp->pass == MP_PASS_SCOPE) { @@ -3114,7 +3118,7 @@ STATIC void compile_scope(compiler_t *comp, scope_t *scope, pass_kind_t pass) { STATIC void compile_scope_inline_asm(compiler_t *comp, scope_t *scope, pass_kind_t pass) { comp->pass = pass; comp->scope_cur = scope; - comp->next_label = 1; + comp->next_label = 0; if (scope->kind != SCOPE_FUNCTION) { compile_syntax_error(comp, MP_PARSE_NODE_NULL, "inline assembler must be a function"); @@ -3271,7 +3275,7 @@ STATIC void compile_scope_inline_asm(compiler_t *comp, scope_t *scope, pass_kind #endif STATIC void scope_compute_things(scope_t *scope) { - // in Micro Python we put the *x parameter after all other parameters (except **y) + // in MicroPython we put the *x parameter after all other parameters (except **y) if (scope->scope_flags & MP_SCOPE_FLAG_VARARGS) { id_info_t *id_param = NULL; for (int i = scope->id_info_len - 1; i >= 0; i--) { @@ -3309,7 +3313,7 @@ STATIC void scope_compute_things(scope_t *scope) { // compute the index of cell vars for (int i = 0; i < scope->id_info_len; i++) { id_info_t *id = &scope->id_info[i]; - // in Micro Python the cells come right after the fast locals + // in MicroPython the cells come right after the fast locals // parameters are not counted here, since they remain at the start // of the locals, even if they are cell vars if (id->kind == ID_INFO_KIND_CELL && !(id->flags & ID_FLAG_IS_PARAM)) { @@ -3329,14 +3333,14 @@ STATIC void scope_compute_things(scope_t *scope) { id_info_t *id2 = &scope->id_info[j]; if (id2->kind == ID_INFO_KIND_FREE && id->qst == id2->qst) { assert(!(id2->flags & ID_FLAG_IS_PARAM)); // free vars should not be params - // in Micro Python the frees come first, before the params + // in MicroPython the frees come first, before the params id2->local_num = num_free; num_free += 1; } } } } - // in Micro Python shift all other locals after the free locals + // in MicroPython shift all other locals after the free locals if (num_free > 0) { for (int i = 0; i < scope->id_info_len; i++) { id_info_t *id = &scope->id_info[i]; @@ -3360,6 +3364,8 @@ mp_raw_code_t *mp_compile_to_raw_code(mp_parse_tree_t *parse_tree, qstr source_f comp->source_file = source_file; comp->is_repl = is_repl; + comp->break_label = INVALID_LABEL; + comp->continue_label = INVALID_LABEL; // create the module scope scope_t *module_scope = scope_new_and_link(comp, SCOPE_MODULE, parse_tree->root, emit_opt); diff --git a/py/compile.h b/py/compile.h index 45a98588d8..3297e83aeb 100644 --- a/py/compile.h +++ b/py/compile.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,8 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -#ifndef __MICROPY_INCLUDED_PY_COMPILE_H__ -#define __MICROPY_INCLUDED_PY_COMPILE_H__ +#ifndef MICROPY_INCLUDED_PY_COMPILE_H +#define MICROPY_INCLUDED_PY_COMPILE_H #include "py/lexer.h" #include "py/parse.h" @@ -51,4 +51,4 @@ mp_raw_code_t *mp_compile_to_raw_code(mp_parse_tree_t *parse_tree, qstr source_f // this is implemented in runtime.c mp_obj_t mp_parse_compile_execute(mp_lexer_t *lex, mp_parse_input_kind_t parse_input_kind, mp_obj_dict_t *globals, mp_obj_dict_t *locals); -#endif // __MICROPY_INCLUDED_PY_COMPILE_H__ +#endif // MICROPY_INCLUDED_PY_COMPILE_H diff --git a/py/emit.h b/py/emit.h index 0236a9b8d0..2b2c904f60 100644 --- a/py/emit.h +++ b/py/emit.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,9 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - -#ifndef __MICROPY_INCLUDED_PY_EMIT_H__ -#define __MICROPY_INCLUDED_PY_EMIT_H__ +#ifndef MICROPY_INCLUDED_PY_EMIT_H +#define MICROPY_INCLUDED_PY_EMIT_H #include "py/lexer.h" #include "py/scope.h" @@ -284,4 +283,4 @@ void mp_emitter_warning(pass_kind_t pass, const char *msg); #define mp_emitter_warning(pass, msg) #endif -#endif // __MICROPY_INCLUDED_PY_EMIT_H__ +#endif // MICROPY_INCLUDED_PY_EMIT_H diff --git a/py/emitbc.c b/py/emitbc.c index ec12a62c6c..6770209257 100644 --- a/py/emitbc.c +++ b/py/emitbc.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -902,7 +902,7 @@ void mp_emit_bc_make_closure(emit_t *emit, scope_t *scope, mp_uint_t n_closed_ov emit_write_bytecode_byte(emit, n_closed_over); } else { assert(n_closed_over <= 255); - emit_bc_pre(emit, -2 - n_closed_over + 1); + emit_bc_pre(emit, -2 - (mp_int_t)n_closed_over + 1); emit_write_bytecode_byte_raw_code(emit, MP_BC_MAKE_CLOSURE_DEFARGS, scope->raw_code); emit_write_bytecode_byte(emit, n_closed_over); } diff --git a/py/emitcommon.c b/py/emitcommon.c index e914431d32..07b1dbb4ce 100644 --- a/py/emitcommon.c +++ b/py/emitcommon.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/py/emitglue.c b/py/emitglue.c index fb7a549264..383e6a136b 100644 --- a/py/emitglue.c +++ b/py/emitglue.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/py/emitglue.h b/py/emitglue.h index 37c4f1b18f..43930333d6 100644 --- a/py/emitglue.h +++ b/py/emitglue.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,8 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -#ifndef __MICROPY_INCLUDED_PY_EMITGLUE_H__ -#define __MICROPY_INCLUDED_PY_EMITGLUE_H__ +#ifndef MICROPY_INCLUDED_PY_EMITGLUE_H +#define MICROPY_INCLUDED_PY_EMITGLUE_H #include "py/obj.h" @@ -74,4 +74,4 @@ void mp_emit_glue_assign_native(mp_raw_code_t *rc, mp_raw_code_kind_t kind, void mp_obj_t mp_make_function_from_raw_code(const mp_raw_code_t *rc, mp_obj_t def_args, mp_obj_t def_kw_args); mp_obj_t mp_make_closure_from_raw_code(const mp_raw_code_t *rc, mp_uint_t n_closed_over, const mp_obj_t *args); -#endif // __MICROPY_INCLUDED_PY_EMITGLUE_H__ +#endif // MICROPY_INCLUDED_PY_EMITGLUE_H diff --git a/py/emitinlinethumb.c b/py/emitinlinethumb.c index c1a4eac5d0..577f656720 100644 --- a/py/emitinlinethumb.c +++ b/py/emitinlinethumb.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/py/emitnative.c b/py/emitnative.c index 99adc809c7..5ed69ff9b0 100644 --- a/py/emitnative.c +++ b/py/emitnative.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/py/formatfloat.c b/py/formatfloat.c index 9ff80d9f63..4130e8b26b 100644 --- a/py/formatfloat.c +++ b/py/formatfloat.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -161,7 +161,7 @@ int mp_format_float(FPTYPE f, char *buf, size_t buf_size, char fmt, int prec, ch if (fmt == 'g' && prec == 0) { prec = 1; } - int e, e1; + int e, e1; int dec = 0; char e_sign = '\0'; int num_digits = 0; @@ -209,7 +209,7 @@ int mp_format_float(FPTYPE f, char *buf, size_t buf_size, char fmt, int prec, ch e_sign_char = '+'; } } else if (fp_isless1(f)) { - e++; + e++; f *= FPCONST(10.0); } @@ -232,7 +232,7 @@ int mp_format_float(FPTYPE f, char *buf, size_t buf_size, char fmt, int prec, ch num_digits = prec; if (num_digits) { - *s++ = '.'; + *s++ = '.'; while (--e && num_digits) { *s++ = '0'; num_digits--; @@ -266,7 +266,7 @@ int mp_format_float(FPTYPE f, char *buf, size_t buf_size, char fmt, int prec, ch f *= FPCONST(0.1); } - // If the user specified fixed format (fmt == 'f') and e makes the + // If the user specified fixed format (fmt == 'f') and e makes the // number too big to fit into the available buffer, then we'll // switch to the 'e' format. @@ -327,12 +327,12 @@ int mp_format_float(FPTYPE f, char *buf, size_t buf_size, char fmt, int prec, ch if (prec == 0) { prec = 1; } - num_digits = prec; + num_digits = prec; } // Print the digits of the mantissa for (int i = 0; i < num_digits; ++i, --dec) { - int32_t d = f; + int32_t d = (int32_t)f; *s++ = '0' + d; if (dec == 0 && prec > 0) { *s++ = '.'; @@ -365,7 +365,7 @@ int mp_format_float(FPTYPE f, char *buf, size_t buf_size, char fmt, int prec, ch if (rs == buf) { break; } - rs--; + rs--; } if (*rs == '0') { // We need to insert a 1 @@ -376,12 +376,17 @@ int mp_format_float(FPTYPE f, char *buf, size_t buf_size, char fmt, int prec, ch rs[1] = '0'; if (e_sign == '-') { e--; + if (e == 0) { + e_sign = '+'; + } } else { - e++; + e++; } + } else { + // Need at extra digit at the end to make room for the leading '1' + s++; } - s++; - char *ss = s; + char *ss = s; while (ss > rs) { *ss = ss[-1]; ss--; diff --git a/py/formatfloat.h b/py/formatfloat.h index 0196034471..9a1643b4dd 100644 --- a/py/formatfloat.h +++ b/py/formatfloat.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,8 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -#ifndef __MICROPY_INCLUDED_PY_FORMATFLOAT_H__ -#define __MICROPY_INCLUDED_PY_FORMATFLOAT_H__ +#ifndef MICROPY_INCLUDED_PY_FORMATFLOAT_H +#define MICROPY_INCLUDED_PY_FORMATFLOAT_H #include "py/mpconfig.h" @@ -32,4 +32,4 @@ int mp_format_float(mp_float_t f, char *buf, size_t bufSize, char fmt, int prec, char sign); #endif -#endif // __MICROPY_INCLUDED_PY_FORMATFLOAT_H__ +#endif // MICROPY_INCLUDED_PY_FORMATFLOAT_H diff --git a/py/frozenmod.c b/py/frozenmod.c index 1eaaf574a2..06d4f84c8e 100644 --- a/py/frozenmod.c +++ b/py/frozenmod.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/py/frozenmod.h b/py/frozenmod.h index 4b125ff247..8cddef6819 100644 --- a/py/frozenmod.h +++ b/py/frozenmod.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,6 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ +#ifndef MICROPY_INCLUDED_PY_FROZENMOD_H +#define MICROPY_INCLUDED_PY_FROZENMOD_H #include "py/lexer.h" @@ -35,3 +37,5 @@ enum { int mp_find_frozen_module(const char *str, size_t len, void **data); const char *mp_find_frozen_str(const char *str, size_t *len); mp_import_stat_t mp_frozen_stat(const char *str); + +#endif // MICROPY_INCLUDED_PY_FROZENMOD_H diff --git a/py/gc.c b/py/gc.c index 937dae44f7..7253b7db68 100644 --- a/py/gc.c +++ b/py/gc.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -536,37 +536,34 @@ void gc_free(void *ptr) { DEBUG_printf("gc_free(%p)\n", ptr); - if (VERIFY_PTR(ptr)) { - size_t block = BLOCK_FROM_PTR(ptr); - if (ATB_GET_KIND(block) == AT_HEAD) { - #if MICROPY_ENABLE_FINALISER - FTB_CLEAR(block); - #endif - // set the last_free pointer to this block if it's earlier in the heap - if (block / BLOCKS_PER_ATB < MP_STATE_MEM(gc_last_free_atb_index)) { - MP_STATE_MEM(gc_last_free_atb_index) = block / BLOCKS_PER_ATB; - } - - // free head and all of its tail blocks - do { - ATB_ANY_TO_FREE(block); - block += 1; - } while (ATB_GET_KIND(block) == AT_TAIL); - - GC_EXIT(); - - #if EXTENSIVE_HEAP_PROFILING - gc_dump_alloc_table(); - #endif - } else { - GC_EXIT(); - assert(!"bad free"); - } - } else if (ptr != NULL) { + if (ptr == NULL) { GC_EXIT(); - assert(!"bad free"); } else { + // get the GC block number corresponding to this pointer + assert(VERIFY_PTR(ptr)); + size_t block = BLOCK_FROM_PTR(ptr); + assert(ATB_GET_KIND(block) == AT_HEAD); + + #if MICROPY_ENABLE_FINALISER + FTB_CLEAR(block); + #endif + + // set the last_free pointer to this block if it's earlier in the heap + if (block / BLOCKS_PER_ATB < MP_STATE_MEM(gc_last_free_atb_index)) { + MP_STATE_MEM(gc_last_free_atb_index) = block / BLOCKS_PER_ATB; + } + + // free head and all of its tail blocks + do { + ATB_ANY_TO_FREE(block); + block += 1; + } while (ATB_GET_KIND(block) == AT_TAIL); + GC_EXIT(); + + #if EXTENSIVE_HEAP_PROFILING + gc_dump_alloc_table(); + #endif } } diff --git a/py/gc.h b/py/gc.h index 7d8fe2bf8c..739349c1f5 100644 --- a/py/gc.h +++ b/py/gc.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,8 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -#ifndef __MICROPY_INCLUDED_PY_GC_H__ -#define __MICROPY_INCLUDED_PY_GC_H__ +#ifndef MICROPY_INCLUDED_PY_GC_H +#define MICROPY_INCLUDED_PY_GC_H #include @@ -64,4 +64,4 @@ void gc_info(gc_info_t *info); void gc_dump_info(void); void gc_dump_alloc_table(void); -#endif // __MICROPY_INCLUDED_PY_GC_H__ +#endif // MICROPY_INCLUDED_PY_GC_H diff --git a/py/grammar.h b/py/grammar.h index 930d96dc15..6abb1de8c0 100644 --- a/py/grammar.h +++ b/py/grammar.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -32,7 +32,7 @@ // # single_input is a single interactive statement; // # file_input is a module or sequence of commands read from an input file; // # eval_input is the input for the eval() functions. -// # NB: compound_stmt in single_input is followed by extra NEWLINE! --> not in Micro Python +// # NB: compound_stmt in single_input is followed by extra NEWLINE! --> not in MicroPython // single_input: NEWLINE | simple_stmt | compound_stmt // file_input: (NEWLINE | stmt)* ENDMARKER // eval_input: testlist NEWLINE* ENDMARKER @@ -244,9 +244,9 @@ DEF_RULE(star_expr, c(star_expr), and(2), tok(OP_STAR), rule(expr)) DEF_RULE(expr, c(expr), list, rule(xor_expr), tok(OP_PIPE)) DEF_RULE(xor_expr, c(xor_expr), list, rule(and_expr), tok(OP_CARET)) DEF_RULE(and_expr, c(and_expr), list, rule(shift_expr), tok(OP_AMPERSAND)) -DEF_RULE(shift_expr, c(shift_expr), list, rule(arith_expr), rule(shift_op)) +DEF_RULE(shift_expr, c(term), list, rule(arith_expr), rule(shift_op)) DEF_RULE_NC(shift_op, or(2), tok(OP_DBL_LESS), tok(OP_DBL_MORE)) -DEF_RULE(arith_expr, c(arith_expr), list, rule(term), rule(arith_op)) +DEF_RULE(arith_expr, c(term), list, rule(term), rule(arith_op)) DEF_RULE_NC(arith_op, or(2), tok(OP_PLUS), tok(OP_MINUS)) DEF_RULE(term, c(term), list, rule(factor), rule(term_op)) DEF_RULE_NC(term_op, or(4), tok(OP_STAR), tok(OP_SLASH), tok(OP_PERCENT), tok(OP_DBL_SLASH)) diff --git a/py/lexer.c b/py/lexer.c index abc1f3ebbb..32b3567cc2 100644 --- a/py/lexer.c +++ b/py/lexer.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -672,7 +672,7 @@ mp_lexer_t *mp_lexer_new(qstr src_name, mp_reader_t reader) { lex->source_name = src_name; lex->reader = reader; lex->line = 1; - lex->column = -2; // account for 3 dummy bytes + lex->column = (size_t)-2; // account for 3 dummy bytes lex->emit_dent = 0; lex->nested_bracket_level = 0; lex->alloc_indent_level = MICROPY_ALLOC_LEXER_INDENT_INIT; diff --git a/py/lexer.h b/py/lexer.h index 5d998b3521..a29709107d 100644 --- a/py/lexer.h +++ b/py/lexer.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,8 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -#ifndef __MICROPY_INCLUDED_PY_LEXER_H__ -#define __MICROPY_INCLUDED_PY_LEXER_H__ +#ifndef MICROPY_INCLUDED_PY_LEXER_H +#define MICROPY_INCLUDED_PY_LEXER_H #include @@ -32,7 +32,7 @@ #include "py/qstr.h" #include "py/reader.h" -/* lexer.h -- simple tokeniser for Micro Python +/* lexer.h -- simple tokeniser for MicroPython * * Uses (byte) length instead of null termination. * Tokens are the same - UTF-8 with (byte) length. @@ -192,4 +192,4 @@ mp_lexer_t *mp_lexer_new_from_file(const char *filename); mp_lexer_t *mp_lexer_new_from_fd(qstr filename, int fd, bool close_fd); #endif -#endif // __MICROPY_INCLUDED_PY_LEXER_H__ +#endif // MICROPY_INCLUDED_PY_LEXER_H diff --git a/py/makeqstrdefs.py b/py/makeqstrdefs.py index 92a19c3920..525dec1973 100644 --- a/py/makeqstrdefs.py +++ b/py/makeqstrdefs.py @@ -5,8 +5,10 @@ qstr. Each qstr is transformed into a qstr definition of the form 'Q(...)'. This script works with Python 2.6, 2.7, 3.3 and 3.4. """ +from __future__ import print_function + import re -import argparse +import sys import os # Blacklist of qstrings that are specially handled in further @@ -84,18 +86,18 @@ def cat_together(): if __name__ == "__main__": - parser = argparse.ArgumentParser(description='Generates qstr definitions from a specified source') + if len(sys.argv) != 5: + print('usage: %s command input_filename output_dir output_file' % sys.argv[0]) + sys.exit(2) - parser.add_argument('command', - help='Command (split/cat)') - parser.add_argument('input_filename', - help='Name of the input file (when not specified, the script reads standard input)') - parser.add_argument('output_dir', - help='Output directory to store individual qstr files') - parser.add_argument('output_file', - help='Name of the output file with collected qstrs') + class Args: + pass + args = Args() + args.command = sys.argv[1] + args.input_filename = sys.argv[2] + args.output_dir = sys.argv[3] + args.output_file = sys.argv[4] - args = parser.parse_args() try: os.makedirs(args.output_dir) except OSError: diff --git a/py/makeversionhdr.py b/py/makeversionhdr.py index 1d8f59bd22..749160b4df 100644 --- a/py/makeversionhdr.py +++ b/py/makeversionhdr.py @@ -59,8 +59,8 @@ def get_version_info_from_git(): 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: - if line.startswith("release = '"): - ver = line.strip()[10:].strip("'") + if line.startswith("version = release = '"): + ver = line.strip().split(" = ")[2].strip("'") git_tag = "v" + ver ver = ver.split(".") if len(ver) == 2: diff --git a/py/malloc.c b/py/malloc.c index f48cb8da4f..e679e20926 100644 --- a/py/malloc.c +++ b/py/malloc.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -46,7 +46,7 @@ #include "py/gc.h" // We redirect standard alloc functions to GC heap - just for the rest of -// this module. In the rest of micropython source, system malloc can be +// this module. In the rest of MicroPython source, system malloc can be // freely accessed - for interfacing with system and 3rd-party libs for // example. On the other hand, some (e.g. bare-metal) ports may use GC // heap as system heap, so, to avoid warnings, we do undef's first. diff --git a/py/map.c b/py/map.c index 50d74f38f5..7f3c900590 100644 --- a/py/map.c +++ b/py/map.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/py/misc.h b/py/misc.h index caa5945bf2..71425b85e1 100644 --- a/py/misc.h +++ b/py/misc.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,8 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -#ifndef __MICROPY_INCLUDED_PY_MISC_H__ -#define __MICROPY_INCLUDED_PY_MISC_H__ +#ifndef MICROPY_INCLUDED_PY_MISC_H +#define MICROPY_INCLUDED_PY_MISC_H // a mini library of useful types and functions @@ -92,7 +92,7 @@ void *m_realloc(void *ptr, size_t new_num_bytes); void *m_realloc_maybe(void *ptr, size_t new_num_bytes, bool allow_move); void m_free(void *ptr); #endif -void *m_malloc_fail(size_t num_bytes); +NORETURN void *m_malloc_fail(size_t num_bytes); #if MICROPY_MEM_STATS size_t m_get_total_bytes_allocated(void); @@ -223,4 +223,4 @@ static inline mp_uint_t count_lead_ones(byte val) { #define MP_FLOAT_EXP_BIAS ((1 << (MP_FLOAT_EXP_BITS - 1)) - 1) #endif // MICROPY_PY_BUILTINS_FLOAT -#endif // __MICROPY_INCLUDED_PY_MISC_H__ +#endif // MICROPY_INCLUDED_PY_MISC_H diff --git a/py/mkrules.mk b/py/mkrules.mk index 00ed279176..de2c92a3f4 100644 --- a/py/mkrules.mk +++ b/py/mkrules.mk @@ -6,7 +6,7 @@ endif # This file expects that OBJ contains a list of all of the object files. # The directory portion of each object file is used to locate the source -# and should not contain any ..'s but rather be relative to the top of the +# and should not contain any ..'s but rather be relative to the top of the # tree. # # So for example, py/map.c would have an object file name py/map.o @@ -47,7 +47,7 @@ $(BUILD)/%.o: %.c $(call compile_c) # List all native flags since the current build system doesn't have -# the micropython configuration available. However, these flags are +# the MicroPython configuration available. However, these flags are # needed to extract all qstrings QSTR_GEN_EXTRA_CFLAGS += -DNO_QSTR -DN_X64 -DN_X86 -DN_THUMB -DN_ARM -DN_XTENSA QSTR_GEN_EXTRA_CFLAGS += -I$(BUILD)/tmp @@ -135,7 +135,7 @@ $(PROG): $(OBJ) ifndef DEBUG $(Q)$(STRIP) $(STRIPFLAGS_EXTRA) $(PROG) endif - $(Q)$(SIZE) $(PROG) + $(Q)$(SIZE) $$(find $(BUILD)/build -name "frozen*.o") $(PROG) clean: clean-prog clean-prog: diff --git a/py/modarray.c b/py/modarray.c index 356e48bee0..c0cdca9286 100644 --- a/py/modarray.c +++ b/py/modarray.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/py/modbuiltins.c b/py/modbuiltins.c index fe8159953a..1c76b80739 100644 --- a/py/modbuiltins.c +++ b/py/modbuiltins.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -91,10 +91,8 @@ STATIC mp_obj_t mp_builtin___build_class__(size_t n_args, const mp_obj_t *args) MP_DEFINE_CONST_FUN_OBJ_VAR(mp_builtin___build_class___obj, 2, mp_builtin___build_class__); STATIC mp_obj_t mp_builtin_abs(mp_obj_t o_in) { - if (0) { - // dummy -#if MICROPY_PY_BUILTINS_FLOAT - } else if (mp_obj_is_float(o_in)) { + #if MICROPY_PY_BUILTINS_FLOAT + if (mp_obj_is_float(o_in)) { mp_float_t value = mp_obj_float_get(o_in); // TODO check for NaN etc if (value < 0) { @@ -102,17 +100,17 @@ STATIC mp_obj_t mp_builtin_abs(mp_obj_t o_in) { } else { return o_in; } -#if MICROPY_PY_BUILTINS_COMPLEX + #if MICROPY_PY_BUILTINS_COMPLEX } else if (MP_OBJ_IS_TYPE(o_in, &mp_type_complex)) { mp_float_t real, imag; mp_obj_complex_get(o_in, &real, &imag); return mp_obj_new_float(MICROPY_FLOAT_C_FUN(sqrt)(real*real + imag*imag)); -#endif -#endif - } else { - // this will raise a TypeError if the argument is not integral - return mp_obj_int_abs(o_in); + #endif } + #endif + + // this will raise a TypeError if the argument is not integral + return mp_obj_int_abs(o_in); } MP_DEFINE_CONST_FUN_OBJ_1(mp_builtin_abs_obj, mp_builtin_abs); @@ -226,14 +224,14 @@ STATIC mp_obj_t mp_builtin_dir(size_t n_args, const mp_obj_t *args) { mp_obj_t dir = mp_obj_new_list(0, NULL); if (dict != NULL) { - for (mp_uint_t i = 0; i < dict->map.alloc; i++) { + for (size_t i = 0; i < dict->map.alloc; i++) { if (MP_MAP_SLOT_IS_FILLED(&dict->map, i)) { mp_obj_list_append(dir, dict->map.table[i].key); } } } if (members != NULL) { - for (mp_uint_t i = 0; i < members->alloc; i++) { + for (size_t i = 0; i < members->alloc; i++) { if (MP_MAP_SLOT_IS_FILLED(members, i)) { mp_obj_list_append(dir, members->table[i].key); } @@ -326,7 +324,7 @@ STATIC mp_obj_t mp_builtin_min_max(size_t n_args, const mp_obj_t *args, mp_map_t // given many args mp_obj_t best_key = MP_OBJ_NULL; mp_obj_t best_obj = MP_OBJ_NULL; - for (mp_uint_t i = 0; i < n_args; i++) { + for (size_t i = 0; i < n_args; i++) { mp_obj_t key = key_fn == MP_OBJ_NULL ? args[i] : mp_call_function_1(key_fn, args[i]); if (best_obj == MP_OBJ_NULL || (mp_binary_op(op, key, best_key) == mp_const_true)) { best_key = key; @@ -398,8 +396,7 @@ STATIC mp_obj_t mp_builtin_ord(mp_obj_t o_in) { #endif if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) { - nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, - "ord expects a character")); + mp_raise_TypeError("ord expects a character"); } else { nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, "ord() expected a character, but string of length %d found", (int)len)); @@ -444,7 +441,7 @@ STATIC mp_obj_t mp_builtin_print(size_t n_args, const mp_obj_t *args, mp_map_t * mp_print_t print = {stream_obj, mp_stream_write_adaptor}; #endif - for (mp_uint_t i = 0; i < n_args; i++) { + for (size_t i = 0; i < n_args; i++) { if (i > 0) { #if MICROPY_PY_IO && MICROPY_PY_SYS_STDFILES mp_stream_write_adaptor(stream_obj, sep_data, sep_len); @@ -543,7 +540,7 @@ STATIC mp_obj_t mp_builtin_sorted(size_t n_args, const mp_obj_t *args, mp_map_t MP_DEFINE_CONST_FUN_OBJ_KW(mp_builtin_sorted_obj, 1, mp_builtin_sorted); // See mp_load_attr() if making any changes -STATIC inline mp_obj_t mp_load_attr_default(mp_obj_t base, qstr attr, mp_obj_t defval) { +static inline mp_obj_t mp_load_attr_default(mp_obj_t base, qstr attr, mp_obj_t defval) { mp_obj_t dest[2]; // use load_method, raising or not raising exception ((defval == MP_OBJ_NULL) ? mp_load_method : mp_load_method_maybe)(base, attr, dest); diff --git a/py/modcmath.c b/py/modcmath.c index 7ad8f5ad60..627a2cbadb 100644 --- a/py/modcmath.c +++ b/py/modcmath.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/py/modcollections.c b/py/modcollections.c index e610a28d24..1a1560387a 100644 --- a/py/modcollections.c +++ b/py/modcollections.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/py/modgc.c b/py/modgc.c index 24564622ec..d45e007ebe 100644 --- a/py/modgc.c +++ b/py/modgc.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/py/modio.c b/py/modio.c index 2d317d022a..353a002865 100644 --- a/py/modio.c +++ b/py/modio.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -112,9 +112,9 @@ STATIC mp_obj_t bufwriter_flush(mp_obj_t self_in) { } STATIC MP_DEFINE_CONST_FUN_OBJ_1(bufwriter_flush_obj, bufwriter_flush); -STATIC const mp_map_elem_t bufwriter_locals_dict_table[] = { - { MP_OBJ_NEW_QSTR(MP_QSTR_write), (mp_obj_t)&mp_stream_write_obj }, - { MP_OBJ_NEW_QSTR(MP_QSTR_flush), (mp_obj_t)&bufwriter_flush_obj }, +STATIC const mp_rom_map_elem_t bufwriter_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_write), MP_ROM_PTR(&mp_stream_write_obj) }, + { MP_ROM_QSTR(MP_QSTR_flush), MP_ROM_PTR(&bufwriter_flush_obj) }, }; STATIC MP_DEFINE_CONST_DICT(bufwriter_locals_dict, bufwriter_locals_dict_table); @@ -127,7 +127,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_t)&bufwriter_locals_dict, + .locals_dict = (mp_obj_dict_t*)&bufwriter_locals_dict, }; #endif // MICROPY_PY_IO_BUFFEREDWRITER diff --git a/py/modmath.c b/py/modmath.c index ddab337d05..c56056a5dd 100644 --- a/py/modmath.c +++ b/py/modmath.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -25,7 +25,7 @@ */ #include "py/builtin.h" -#include "py/nlr.h" +#include "py/runtime.h" #if MICROPY_PY_BUILTINS_FLOAT && MICROPY_PY_MATH @@ -41,7 +41,7 @@ /// working with floating-point numbers. STATIC NORETURN void math_error(void) { - nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "math domain error")); + mp_raise_ValueError("math domain error"); } #define MATH_FUN_1(py_name, c_name) \ @@ -168,6 +168,8 @@ STATIC mp_obj_t mp_math_log(size_t n_args, const mp_obj_t *args) { mp_float_t base = mp_obj_get_float(args[1]); if (base <= (mp_float_t)0.0) { math_error(); + } else if (base == (mp_float_t)1.0) { + mp_raise_msg(&mp_type_ZeroDivisionError, "division by zero"); } return mp_obj_new_float(l / MICROPY_FLOAT_C_FUN(log)(base)); } diff --git a/py/modmicropython.c b/py/modmicropython.c index d767062301..6fa3f9ad28 100644 --- a/py/modmicropython.c +++ b/py/modmicropython.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -72,7 +72,8 @@ mp_obj_t mp_micropython_mem_info(size_t n_args, const mp_obj_t *args) { (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 - mp_printf(&mp_plat_print, "stack: " UINT_FMT " out of " INT_FMT "\n", mp_stack_usage(), MP_STATE_THREAD(stack_limit)); + 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 mp_printf(&mp_plat_print, "stack: " UINT_FMT "\n", mp_stack_usage()); #endif diff --git a/py/modstruct.c b/py/modstruct.c index 3c99ef1d8d..1daa333388 100644 --- a/py/modstruct.c +++ b/py/modstruct.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/py/modsys.c b/py/modsys.c index b8c427ba87..ee6f8686e0 100644 --- a/py/modsys.c +++ b/py/modsys.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -87,7 +87,7 @@ STATIC const mp_rom_obj_tuple_t mp_sys_implementation_obj = { #undef I #ifdef MICROPY_PY_SYS_PLATFORM -/// \constant platform - the platform that Micro Python is running on +/// \constant platform - the platform that MicroPython is running on STATIC const MP_DEFINE_STR_OBJ(platform_obj, MICROPY_PY_SYS_PLATFORM); #endif @@ -168,7 +168,7 @@ STATIC const mp_rom_map_elem_t mp_module_sys_globals_table[] = { // to not try to compare sys.maxsize to some literal number (as this // number might not fit in available int size), but instead count number // of "one" bits in sys.maxsize. - { MP_ROM_QSTR(MP_QSTR_maxsize), MP_OBJ_NEW_SMALL_INT(MP_SMALL_INT_MAX) }, + { MP_ROM_QSTR(MP_QSTR_maxsize), MP_ROM_INT(MP_SMALL_INT_MAX) }, #else { MP_ROM_QSTR(MP_QSTR_maxsize), MP_ROM_PTR(&mp_maxsize_obj) }, #endif diff --git a/py/modthread.c b/py/modthread.c index d0e71dad3b..1d76027893 100644 --- a/py/modthread.c +++ b/py/modthread.c @@ -84,7 +84,9 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(thread_lock_acquire_obj, 1, 3, thread STATIC mp_obj_t thread_lock_release(mp_obj_t self_in) { mp_obj_thread_lock_t *self = MP_OBJ_TO_PTR(self_in); - // TODO check if already unlocked + if (!self->locked) { + mp_raise_msg(&mp_type_RuntimeError, NULL); + } self->locked = false; MP_THREAD_GIL_EXIT(); mp_thread_mutex_unlock(&self->mutex); diff --git a/py/mpconfig.h b/py/mpconfig.h index 1ec8ae21c8..fb507a503e 100644 --- a/py/mpconfig.h +++ b/py/mpconfig.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,8 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -#ifndef __MICROPY_INCLUDED_PY_MPCONFIG_H__ -#define __MICROPY_INCLUDED_PY_MPCONFIG_H__ +#ifndef MICROPY_INCLUDED_PY_MPCONFIG_H +#define MICROPY_INCLUDED_PY_MPCONFIG_H // This file contains default configuration settings for MicroPython. // You can override any of the options below using mpconfigport.h file @@ -51,13 +51,13 @@ /*****************************************************************************/ /* Object representation */ -// A Micro Python object is a machine word having the following form: +// A MicroPython object is a machine word having the following form: // - xxxx...xxx1 : a small int, bits 1 and above are the value // - xxxx...xx10 : a qstr, bits 2 and above are the value // - xxxx...xx00 : a pointer to an mp_obj_base_t (unless a fake object) #define MICROPY_OBJ_REPR_A (0) -// A Micro Python object is a machine word having the following form: +// A MicroPython object is a machine word having the following form: // - xxxx...xx01 : a small int, bits 2 and above are the value // - xxxx...xx11 : a qstr, bits 2 and above are the value // - xxxx...xxx0 : a pointer to an mp_obj_base_t (unless a fake object) @@ -73,7 +73,6 @@ // Str and float stored as O = R + 0x80800000, retrieved as R = O - 0x80800000. // This makes strs easier to encode/decode as they have zeros in the top 9 bits. // This scheme only works with 32-bit word size and float enabled. - #define MICROPY_OBJ_REPR_C (2) // A MicroPython object is a 64-bit word having the following form (called R): @@ -235,7 +234,7 @@ #endif /*****************************************************************************/ -/* Micro Python emitters */ +/* MicroPython emitters */ // Whether to support loading of persistent code #ifndef MICROPY_PERSISTENT_CODE_LOAD @@ -1254,4 +1253,4 @@ typedef double mp_float_t; #define MP_UNLIKELY(x) __builtin_expect((x), 0) #endif -#endif // __MICROPY_INCLUDED_PY_MPCONFIG_H__ +#endif // MICROPY_INCLUDED_PY_MPCONFIG_H diff --git a/py/mperrno.h b/py/mperrno.h index 6ea99ae227..f439f65554 100644 --- a/py/mperrno.h +++ b/py/mperrno.h @@ -23,9 +23,10 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ +#ifndef MICROPY_INCLUDED_PY_MPERRNO_H +#define MICROPY_INCLUDED_PY_MPERRNO_H -#ifndef __MICROPY_INCLUDED_PY_MPERRNO_H__ -#define __MICROPY_INCLUDED_PY_MPERRNO_H__ +#include "py/mpconfig.h" #if MICROPY_USE_INTERNAL_ERRNO @@ -139,7 +140,11 @@ #endif #if MICROPY_PY_UERRNO + +#include "py/obj.h" + qstr mp_errno_to_str(mp_obj_t errno_val); + #endif -#endif // __MICROPY_INCLUDED_PY_MPERRNO_H__ +#endif // MICROPY_INCLUDED_PY_MPERRNO_H diff --git a/py/mphal.h b/py/mphal.h index 8d5654f9e3..92de01d08b 100644 --- a/py/mphal.h +++ b/py/mphal.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,8 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -#ifndef __MICROPY_INCLUDED_PY_MPHAL_H__ -#define __MICROPY_INCLUDED_PY_MPHAL_H__ +#ifndef MICROPY_INCLUDED_PY_MPHAL_H +#define MICROPY_INCLUDED_PY_MPHAL_H #include "py/mpconfig.h" @@ -80,4 +80,4 @@ mp_uint_t mp_hal_ticks_cpu(void); #include "extmod/virtpin.h" #endif -#endif // __MICROPY_INCLUDED_PY_MPHAL_H__ +#endif // MICROPY_INCLUDED_PY_MPHAL_H diff --git a/py/mpprint.c b/py/mpprint.c index 4bc45fef4d..6c02d7cefb 100644 --- a/py/mpprint.c +++ b/py/mpprint.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -354,9 +354,6 @@ int mp_print_float(const mp_print_t *print, mp_float_t f, char fmt, int flags, c } int len = mp_format_float(f, buf, sizeof(buf), fmt, prec, sign); - if (len < 0) { - len = 0; - } char *s = buf; diff --git a/py/mpprint.h b/py/mpprint.h index 4fc904a20a..07462bddcc 100644 --- a/py/mpprint.h +++ b/py/mpprint.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,8 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -#ifndef __MICROPY_INCLUDED_PY_MPPRINT_H__ -#define __MICROPY_INCLUDED_PY_MPPRINT_H__ +#ifndef MICROPY_INCLUDED_PY_MPPRINT_H +#define MICROPY_INCLUDED_PY_MPPRINT_H #include "py/mpconfig.h" @@ -71,4 +71,4 @@ int mp_printf(const mp_print_t *print, const char *fmt, ...); int mp_vprintf(const mp_print_t *print, const char *fmt, va_list args); #endif -#endif // __MICROPY_INCLUDED_PY_MPPRINT_H__ +#endif // MICROPY_INCLUDED_PY_MPPRINT_H diff --git a/py/mpstate.c b/py/mpstate.c index 4fc8bc506e..6ce64adfd1 100644 --- a/py/mpstate.c +++ b/py/mpstate.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/py/mpstate.h b/py/mpstate.h index 2b8f29a6ae..eca14a9e44 100644 --- a/py/mpstate.h +++ b/py/mpstate.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,8 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -#ifndef __MICROPY_INCLUDED_PY_MPSTATE_H__ -#define __MICROPY_INCLUDED_PY_MPSTATE_H__ +#ifndef MICROPY_INCLUDED_PY_MPSTATE_H +#define MICROPY_INCLUDED_PY_MPSTATE_H #include @@ -36,7 +36,7 @@ #include "py/objlist.h" #include "py/objexcept.h" -// This file contains structures defining the state of the Micro Python +// This file contains structures defining the state of the MicroPython // memory system, runtime and virtual machine. The state is a global // variable, but in the future it is hoped that the state can become local. @@ -248,4 +248,4 @@ extern mp_state_thread_t *mp_thread_get_state(void); #define MP_STATE_THREAD(x) (mp_state_ctx.thread.x) #endif -#endif // __MICROPY_INCLUDED_PY_MPSTATE_H__ +#endif // MICROPY_INCLUDED_PY_MPSTATE_H diff --git a/py/mpthread.h b/py/mpthread.h index 04d4f19684..602df830c4 100644 --- a/py/mpthread.h +++ b/py/mpthread.h @@ -23,8 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -#ifndef __MICROPY_INCLUDED_PY_MPTHREAD_H__ -#define __MICROPY_INCLUDED_PY_MPTHREAD_H__ +#ifndef MICROPY_INCLUDED_PY_MPTHREAD_H +#define MICROPY_INCLUDED_PY_MPTHREAD_H #include "py/mpconfig.h" @@ -58,4 +58,4 @@ void mp_thread_mutex_unlock(mp_thread_mutex_t *mutex); #define MP_THREAD_GIL_EXIT() #endif -#endif // __MICROPY_INCLUDED_PY_MPTHREAD_H__ +#endif // MICROPY_INCLUDED_PY_MPTHREAD_H diff --git a/py/mpz.c b/py/mpz.c index f5675a2917..d300a8e5db 100644 --- a/py/mpz.c +++ b/py/mpz.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -939,10 +939,6 @@ void mpz_set_from_bytes(mpz_t *z, bool big_endian, size_t len, const byte *buf) z->len = mpn_remove_trailing_zeros(z->dig, z->dig + z->len); } -bool mpz_is_zero(const mpz_t *z) { - return z->len == 0; -} - #if 0 these functions are unused @@ -950,10 +946,6 @@ bool mpz_is_pos(const mpz_t *z) { return z->len > 0 && z->neg == 0; } -bool mpz_is_neg(const mpz_t *z) { - return z->len > 0 && z->neg != 0; -} - bool mpz_is_odd(const mpz_t *z) { return z->len > 0 && (z->dig[0] & 1) != 0; } diff --git a/py/mpz.h b/py/mpz.h index 5c88227223..e2d0c30aac 100644 --- a/py/mpz.h +++ b/py/mpz.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,8 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -#ifndef __MICROPY_INCLUDED_PY_MPZ_H__ -#define __MICROPY_INCLUDED_PY_MPZ_H__ +#ifndef MICROPY_INCLUDED_PY_MPZ_H +#define MICROPY_INCLUDED_PY_MPZ_H #include @@ -111,7 +111,8 @@ 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); -bool mpz_is_zero(const mpz_t *z); +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); @@ -139,4 +140,4 @@ mp_float_t mpz_as_float(const mpz_t *z); #endif size_t mpz_as_str_inpl(const mpz_t *z, unsigned int base, const char *prefix, char base_char, char comma, char *str); -#endif // __MICROPY_INCLUDED_PY_MPZ_H__ +#endif // MICROPY_INCLUDED_PY_MPZ_H diff --git a/py/nativeglue.c b/py/nativeglue.c index c75e5ec047..46c6906d96 100644 --- a/py/nativeglue.c +++ b/py/nativeglue.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -42,7 +42,7 @@ #if MICROPY_EMIT_NATIVE -// convert a Micro Python object to a valid native value based on type +// convert a MicroPython object to a valid native value based on type 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) { @@ -66,7 +66,7 @@ mp_uint_t mp_convert_obj_to_native(mp_obj_t obj, mp_uint_t type) { #if MICROPY_EMIT_NATIVE || MICROPY_EMIT_INLINE_ASM -// convert a native value to a Micro Python object based on type +// convert a native value to a MicroPython object based on 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) { diff --git a/py/nlr.h b/py/nlr.h index 7a71ef34bd..63fe392d9e 100644 --- a/py/nlr.h +++ b/py/nlr.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,8 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -#ifndef __MICROPY_INCLUDED_PY_NLR_H__ -#define __MICROPY_INCLUDED_PY_NLR_H__ +#ifndef MICROPY_INCLUDED_PY_NLR_H +#define MICROPY_INCLUDED_PY_NLR_H // non-local return // exception handling, basically a stack of setjmp/longjmp buffers @@ -112,4 +112,4 @@ NORETURN void nlr_jump_fail(void *val); #endif -#endif // __MICROPY_INCLUDED_PY_NLR_H__ +#endif // MICROPY_INCLUDED_PY_NLR_H diff --git a/py/nlrsetjmp.c b/py/nlrsetjmp.c index c3873e0b6d..1fb4594403 100644 --- a/py/nlrsetjmp.c +++ b/py/nlrsetjmp.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/py/obj.c b/py/obj.c index 493945a227..515a95b2e4 100644 --- a/py/obj.c +++ b/py/obj.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -460,8 +460,7 @@ mp_obj_t mp_obj_subscr(mp_obj_t base, mp_obj_t index, mp_obj_t value) { } } else if (value == MP_OBJ_SENTINEL) { if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) { - nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, - "object is not subscriptable")); + mp_raise_TypeError("object is not subscriptable"); } else { nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, "'%s' object is not subscriptable", mp_obj_get_type_str(base))); diff --git a/py/obj.h b/py/obj.h index a3c06a261a..22bfda0f99 100644 --- a/py/obj.h +++ b/py/obj.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,8 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -#ifndef __MICROPY_INCLUDED_PY_OBJ_H__ -#define __MICROPY_INCLUDED_PY_OBJ_H__ +#ifndef MICROPY_INCLUDED_PY_OBJ_H +#define MICROPY_INCLUDED_PY_OBJ_H #include "py/mpconfig.h" #include "py/misc.h" @@ -864,4 +864,4 @@ mp_obj_t mp_seq_extract_slice(size_t len, const mp_obj_t *seq, mp_bound_slice_t 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__ +#endif // MICROPY_INCLUDED_PY_OBJ_H diff --git a/py/objarray.c b/py/objarray.c index 21479a800f..99146bd4c1 100644 --- a/py/objarray.c +++ b/py/objarray.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/py/objarray.h b/py/objarray.h index 06a2a07efb..0389668458 100644 --- a/py/objarray.h +++ b/py/objarray.h @@ -24,9 +24,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - -#ifndef __MICROPY_INCLUDED_PY_OBJARRAY_H__ -#define __MICROPY_INCLUDED_PY_OBJARRAY_H__ +#ifndef MICROPY_INCLUDED_PY_OBJARRAY_H +#define MICROPY_INCLUDED_PY_OBJARRAY_H #include "py/obj.h" @@ -40,4 +39,4 @@ typedef struct _mp_obj_array_t { void *items; } mp_obj_array_t; -#endif // __MICROPY_INCLUDED_PY_OBJARRAY_H__ +#endif // MICROPY_INCLUDED_PY_OBJARRAY_H diff --git a/py/objattrtuple.c b/py/objattrtuple.c index 8c5e795757..3cc298d4e9 100644 --- a/py/objattrtuple.c +++ b/py/objattrtuple.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/py/objbool.c b/py/objbool.c index 5bc04bb6f9..e5bc3c2287 100644 --- a/py/objbool.c +++ b/py/objbool.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/py/objboundmeth.c b/py/objboundmeth.c index 57be6a6cfd..890f8b15b6 100644 --- a/py/objboundmeth.c +++ b/py/objboundmeth.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/py/objcell.c b/py/objcell.c index 06a88b9547..111906412e 100644 --- a/py/objcell.c +++ b/py/objcell.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/py/objclosure.c b/py/objclosure.c index 3e12358bbd..4eb9eb8b84 100644 --- a/py/objclosure.c +++ b/py/objclosure.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/py/objcomplex.c b/py/objcomplex.c index 5f9183f0e7..f945f35608 100644 --- a/py/objcomplex.c +++ b/py/objcomplex.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -196,7 +196,7 @@ mp_obj_t mp_obj_complex_binary_op(mp_uint_t op, mp_float_t lhs_real, mp_float_t } case MP_BINARY_OP_FLOOR_DIVIDE: case MP_BINARY_OP_INPLACE_FLOOR_DIVIDE: - nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, "can't do truncated division of a complex number")); + mp_raise_TypeError("can't do truncated division of a complex number"); case MP_BINARY_OP_TRUE_DIVIDE: case MP_BINARY_OP_INPLACE_TRUE_DIVIDE: diff --git a/py/objdict.c b/py/objdict.c index 12ba61b2e9..a272ebdb63 100644 --- a/py/objdict.c +++ b/py/objdict.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -278,18 +278,20 @@ STATIC mp_obj_t dict_fromkeys(size_t n_args, const mp_obj_t *args) { STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(dict_fromkeys_fun_obj, 2, 3, dict_fromkeys); STATIC MP_DEFINE_CONST_CLASSMETHOD_OBJ(dict_fromkeys_obj, MP_ROM_PTR(&dict_fromkeys_fun_obj)); -STATIC mp_obj_t dict_get_helper(mp_map_t *self, mp_obj_t key, mp_obj_t deflt, mp_map_lookup_kind_t lookup_kind) { - mp_map_elem_t *elem = mp_map_lookup(self, key, lookup_kind); +STATIC mp_obj_t dict_get_helper(size_t n_args, const mp_obj_t *args, mp_map_lookup_kind_t lookup_kind) { + mp_check_self(MP_OBJ_IS_DICT_TYPE(args[0])); + mp_obj_dict_t *self = MP_OBJ_TO_PTR(args[0]); + mp_map_elem_t *elem = mp_map_lookup(&self->map, args[1], lookup_kind); mp_obj_t value; if (elem == NULL || elem->value == MP_OBJ_NULL) { - if (deflt == MP_OBJ_NULL) { + if (n_args == 2) { if (lookup_kind == MP_MAP_LOOKUP_REMOVE_IF_FOUND) { - nlr_raise(mp_obj_new_exception_arg1(&mp_type_KeyError, key)); + nlr_raise(mp_obj_new_exception_arg1(&mp_type_KeyError, args[1])); } else { value = mp_const_none; } } else { - value = deflt; + value = args[2]; } if (lookup_kind == MP_MAP_LOOKUP_ADD_IF_NOT_FOUND) { elem->value = value; @@ -304,40 +306,20 @@ STATIC mp_obj_t dict_get_helper(mp_map_t *self, mp_obj_t key, mp_obj_t deflt, mp } STATIC mp_obj_t dict_get(size_t n_args, const mp_obj_t *args) { - mp_check_self(MP_OBJ_IS_DICT_TYPE(args[0])); - mp_obj_dict_t *self = MP_OBJ_TO_PTR(args[0]); - - return dict_get_helper(&self->map, - args[1], - n_args == 3 ? args[2] : MP_OBJ_NULL, - MP_MAP_LOOKUP); + return dict_get_helper(n_args, args, MP_MAP_LOOKUP); } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(dict_get_obj, 2, 3, dict_get); STATIC mp_obj_t dict_pop(size_t n_args, const mp_obj_t *args) { - mp_check_self(MP_OBJ_IS_DICT_TYPE(args[0])); - mp_obj_dict_t *self = MP_OBJ_TO_PTR(args[0]); - - return dict_get_helper(&self->map, - args[1], - n_args == 3 ? args[2] : MP_OBJ_NULL, - MP_MAP_LOOKUP_REMOVE_IF_FOUND); + return dict_get_helper(n_args, args, MP_MAP_LOOKUP_REMOVE_IF_FOUND); } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(dict_pop_obj, 2, 3, dict_pop); - STATIC mp_obj_t dict_setdefault(size_t n_args, const mp_obj_t *args) { - mp_check_self(MP_OBJ_IS_DICT_TYPE(args[0])); - mp_obj_dict_t *self = MP_OBJ_TO_PTR(args[0]); - - return dict_get_helper(&self->map, - args[1], - n_args == 3 ? args[2] : MP_OBJ_NULL, - MP_MAP_LOOKUP_ADD_IF_NOT_FOUND); + return dict_get_helper(n_args, args, MP_MAP_LOOKUP_ADD_IF_NOT_FOUND); } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(dict_setdefault_obj, 2, 3, dict_setdefault); - STATIC mp_obj_t dict_popitem(mp_obj_t self_in) { mp_check_self(MP_OBJ_IS_DICT_TYPE(self_in)); mp_obj_dict_t *self = MP_OBJ_TO_PTR(self_in); @@ -615,9 +597,8 @@ 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) { - mp_check_self(MP_OBJ_IS_DICT_TYPE(self_in)); - mp_obj_dict_t *self = MP_OBJ_TO_PTR(self_in); - dict_get_helper(&self->map, key, MP_OBJ_NULL, MP_MAP_LOOKUP_REMOVE_IF_FOUND); + mp_obj_t args[2] = {self_in, key}; + dict_get_helper(2, args, MP_MAP_LOOKUP_REMOVE_IF_FOUND); return self_in; } diff --git a/py/objenumerate.c b/py/objenumerate.c index faae6516c0..1a9d30f836 100644 --- a/py/objenumerate.c +++ b/py/objenumerate.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/py/objexcept.c b/py/objexcept.c index 4722aca914..a9fe040941 100644 --- a/py/objexcept.c +++ b/py/objexcept.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/py/objexcept.h b/py/objexcept.h index 3128fded79..f67651a7eb 100644 --- a/py/objexcept.h +++ b/py/objexcept.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,8 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -#ifndef __MICROPY_INCLUDED_PY_OBJEXCEPT_H__ -#define __MICROPY_INCLUDED_PY_OBJEXCEPT_H__ +#ifndef MICROPY_INCLUDED_PY_OBJEXCEPT_H +#define MICROPY_INCLUDED_PY_OBJEXCEPT_H #include "py/obj.h" #include "py/objtuple.h" @@ -37,4 +37,4 @@ typedef struct _mp_obj_exception_t { mp_obj_tuple_t *args; } mp_obj_exception_t; -#endif // __MICROPY_INCLUDED_PY_OBJEXCEPT_H__ +#endif // MICROPY_INCLUDED_PY_OBJEXCEPT_H diff --git a/py/objfilter.c b/py/objfilter.c index a655b8a785..cb965d8c32 100644 --- a/py/objfilter.c +++ b/py/objfilter.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/py/objfloat.c b/py/objfloat.c index d0e6166121..15edd810f1 100644 --- a/py/objfloat.c +++ b/py/objfloat.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/py/objfun.c b/py/objfun.c index 08d031c8d8..eaba131293 100644 --- a/py/objfun.c +++ b/py/objfun.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -141,11 +141,11 @@ const mp_obj_type_t mp_type_fun_builtin_var = { /* byte code functions */ qstr mp_obj_code_get_name(const byte *code_info) { - mp_decode_uint(&code_info); // skip code_info_size entry + code_info = mp_decode_uint_skip(code_info); // skip code_info_size entry #if MICROPY_PERSISTENT_CODE return code_info[0] | (code_info[1] << 8); #else - return mp_decode_uint(&code_info); + return mp_decode_uint_value(code_info); #endif } @@ -163,8 +163,8 @@ qstr mp_obj_fun_get_name(mp_const_obj_t fun_in) { #endif const byte *bc = fun->bytecode; - mp_decode_uint(&bc); // skip n_state - mp_decode_uint(&bc); // skip n_exc_stack + bc = mp_decode_uint_skip(bc); // skip n_state + bc = mp_decode_uint_skip(bc); // skip n_exc_stack bc++; // skip scope_params bc++; // skip n_pos_args bc++; // skip n_kwonly_args @@ -205,12 +205,9 @@ mp_code_state_t *mp_obj_fun_bc_prepare_codestate(mp_obj_t self_in, size_t n_args MP_STACK_CHECK(); mp_obj_fun_bc_t *self = MP_OBJ_TO_PTR(self_in); - // get start of bytecode - const byte *ip = self->bytecode; - // bytecode prelude: state size and exception stack size - size_t n_state = mp_decode_uint(&ip); - size_t n_exc_stack = mp_decode_uint(&ip); + size_t n_state = mp_decode_uint_value(self->bytecode); + size_t n_exc_stack = mp_decode_uint_value(mp_decode_uint_skip(self->bytecode)); // allocate state for locals and stack size_t state_size = n_state * sizeof(mp_obj_t) + n_exc_stack * sizeof(mp_exc_stack_t); @@ -243,12 +240,9 @@ STATIC mp_obj_t fun_bc_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp_obj_fun_bc_t *self = MP_OBJ_TO_PTR(self_in); DEBUG_printf("Func n_def_args: %d\n", self->n_def_args); - // get start of bytecode - const byte *ip = self->bytecode; - // bytecode prelude: state size and exception stack size - size_t n_state = mp_decode_uint(&ip); - size_t n_exc_stack = mp_decode_uint(&ip); + size_t n_state = mp_decode_uint_value(self->bytecode); + size_t n_exc_stack = mp_decode_uint_value(mp_decode_uint_skip(self->bytecode)); #if VM_DETECT_STACK_OVERFLOW n_state += 1; @@ -486,7 +480,7 @@ typedef mp_uint_t (*inline_asm_fun_2_t)(mp_uint_t, mp_uint_t); typedef mp_uint_t (*inline_asm_fun_3_t)(mp_uint_t, mp_uint_t, mp_uint_t); typedef mp_uint_t (*inline_asm_fun_4_t)(mp_uint_t, mp_uint_t, mp_uint_t, mp_uint_t); -// convert a Micro Python object to a sensible value for inline asm +// convert a MicroPython object to a sensible value for inline asm STATIC mp_uint_t convert_obj_for_inline_asm(mp_obj_t obj) { // TODO for byte_array, pass pointer to the array if (MP_OBJ_IS_SMALL_INT(obj)) { diff --git a/py/objfun.h b/py/objfun.h index d02fada9b1..fbb3516261 100644 --- a/py/objfun.h +++ b/py/objfun.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,8 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -#ifndef __MICROPY_INCLUDED_PY_OBJFUN_H__ -#define __MICROPY_INCLUDED_PY_OBJFUN_H__ +#ifndef MICROPY_INCLUDED_PY_OBJFUN_H +#define MICROPY_INCLUDED_PY_OBJFUN_H #include "py/obj.h" @@ -41,4 +41,4 @@ typedef struct _mp_obj_fun_bc_t { mp_obj_t extra_args[]; } mp_obj_fun_bc_t; -#endif // __MICROPY_INCLUDED_PY_OBJFUN_H__ +#endif // MICROPY_INCLUDED_PY_OBJFUN_H diff --git a/py/objgenerator.c b/py/objgenerator.c index 2e57fdf4b6..2f39f3a52b 100644 --- a/py/objgenerator.c +++ b/py/objgenerator.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -54,12 +54,9 @@ STATIC mp_obj_t gen_wrap_call(mp_obj_t self_in, size_t n_args, size_t n_kw, cons mp_obj_fun_bc_t *self_fun = (mp_obj_fun_bc_t*)self->fun; assert(self_fun->base.type == &mp_type_fun_bc); - // get start of bytecode - const byte *ip = self_fun->bytecode; - // bytecode prelude: get state size and exception stack size - mp_uint_t n_state = mp_decode_uint(&ip); - mp_uint_t n_exc_stack = mp_decode_uint(&ip); + size_t n_state = mp_decode_uint_value(self_fun->bytecode); + size_t n_exc_stack = mp_decode_uint_value(mp_decode_uint_skip(self_fun->bytecode)); // allocate the generator object, with room for local stack and exception stack mp_obj_gen_instance_t *o = m_new_obj_var(mp_obj_gen_instance_t, byte, @@ -77,6 +74,7 @@ const mp_obj_type_t mp_type_gen_wrap = { { &mp_type_type }, .name = MP_QSTR_generator, .call = gen_wrap_call, + .unary_op = mp_generic_unary_op, }; mp_obj_t mp_obj_new_gen_wrap(mp_obj_t fun) { @@ -238,6 +236,7 @@ const mp_obj_type_t mp_type_gen_instance = { { &mp_type_type }, .name = MP_QSTR_generator, .print = gen_instance_print, + .unary_op = mp_generic_unary_op, .getiter = mp_identity_getiter, .iternext = gen_instance_iternext, .locals_dict = (mp_obj_dict_t*)&gen_instance_locals_dict, diff --git a/py/objgenerator.h b/py/objgenerator.h index d1b9be4780..80bf9cd860 100644 --- a/py/objgenerator.h +++ b/py/objgenerator.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,12 +23,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -#ifndef __MICROPY_INCLUDED_PY_OBJGENERATOR_H__ -#define __MICROPY_INCLUDED_PY_OBJGENERATOR_H__ +#ifndef MICROPY_INCLUDED_PY_OBJGENERATOR_H +#define MICROPY_INCLUDED_PY_OBJGENERATOR_H #include "py/obj.h" #include "py/runtime.h" mp_vm_return_kind_t mp_obj_gen_resume(mp_obj_t self_in, mp_obj_t send_val, mp_obj_t throw_val, mp_obj_t *ret_val); -#endif // __MICROPY_INCLUDED_PY_OBJGENERATOR_H__ +#endif // MICROPY_INCLUDED_PY_OBJGENERATOR_H diff --git a/py/objgetitemiter.c b/py/objgetitemiter.c index a3c754448f..afd6fb22b0 100644 --- a/py/objgetitemiter.c +++ b/py/objgetitemiter.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/py/objint.c b/py/objint.c index bda9c46cf0..29d889629f 100644 --- a/py/objint.c +++ b/py/objint.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -106,7 +106,7 @@ STATIC mp_fp_as_int_class_t mp_classify_fp_as_int(mp_float_t val) { #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 & (1 << MP_FLOAT_SIGN_SHIFT_I32)) { + if (e & (1U << MP_FLOAT_SIGN_SHIFT_I32)) { #if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE e |= u.i[MP_ENDIANNESS_BIG] != 0; #endif @@ -432,15 +432,14 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(int_from_bytes_fun_obj, 3, 4, int_fro STATIC MP_DEFINE_CONST_CLASSMETHOD_OBJ(int_from_bytes_obj, MP_ROM_PTR(&int_from_bytes_fun_obj)); STATIC mp_obj_t int_to_bytes(size_t n_args, const mp_obj_t *args) { - // TODO: Support byteorder param // TODO: Support signed param (assumes signed=False) (void)n_args; - if (args[2] != MP_OBJ_NEW_QSTR(MP_QSTR_little)) { - mp_not_implemented(""); + mp_int_t len = mp_obj_get_int(args[1]); + if (len < 0) { + mp_raise_ValueError(NULL); } - - mp_uint_t len = MP_OBJ_SMALL_INT_VALUE(args[1]); + bool big_endian = args[2] != MP_OBJ_NEW_QSTR(MP_QSTR_little); vstr_t vstr; vstr_init_len(&vstr, len); @@ -449,12 +448,13 @@ STATIC mp_obj_t int_to_bytes(size_t n_args, const mp_obj_t *args) { #if MICROPY_LONGINT_IMPL != MICROPY_LONGINT_IMPL_NONE if (!MP_OBJ_IS_SMALL_INT(args[0])) { - mp_obj_int_to_bytes_impl(args[0], false, len, data); + mp_obj_int_to_bytes_impl(args[0], big_endian, len, data); } else #endif { mp_int_t val = MP_OBJ_SMALL_INT_VALUE(args[0]); - mp_binary_set_int(MIN((size_t)len, sizeof(val)), false, data, val); + size_t l = MIN((size_t)len, sizeof(val)); + mp_binary_set_int(l, big_endian, data + (big_endian ? (len - l) : 0), val); } return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr); diff --git a/py/objint.h b/py/objint.h index da56c18624..394c23714b 100644 --- a/py/objint.h +++ b/py/objint.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,8 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -#ifndef __MICROPY_INCLUDED_PY_OBJINT_H__ -#define __MICROPY_INCLUDED_PY_OBJINT_H__ +#ifndef MICROPY_INCLUDED_PY_OBJINT_H +#define MICROPY_INCLUDED_PY_OBJINT_H #include "py/mpz.h" #include "py/obj.h" @@ -63,4 +63,4 @@ mp_obj_t mp_obj_int_binary_op(mp_uint_t op, mp_obj_t lhs_in, mp_obj_t rhs_in); mp_obj_t mp_obj_int_binary_op_extra_cases(mp_uint_t op, mp_obj_t lhs_in, mp_obj_t rhs_in); mp_obj_t mp_obj_int_pow3(mp_obj_t base, mp_obj_t exponent, mp_obj_t modulus); -#endif // __MICROPY_INCLUDED_PY_OBJINT_H__ +#endif // MICROPY_INCLUDED_PY_OBJINT_H diff --git a/py/objint_longlong.c b/py/objint_longlong.c index f638a53202..02c005d2fd 100644 --- a/py/objint_longlong.c +++ b/py/objint_longlong.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -191,6 +191,13 @@ mp_obj_t mp_obj_int_binary_op(mp_uint_t op, mp_obj_t lhs_in, mp_obj_t rhs_in) { case MP_BINARY_OP_POWER: case MP_BINARY_OP_INPLACE_POWER: { + if (rhs_val < 0) { + #if MICROPY_PY_BUILTINS_FLOAT + return mp_obj_float_binary_op(op, lhs_val, rhs_in); + #else + mp_raise_ValueError("negative power with no float support"); + #endif + } long long ans = 1; while (rhs_val > 0) { if (rhs_val & 1) { @@ -247,7 +254,7 @@ mp_obj_t mp_obj_new_int_from_ll(long long val) { mp_obj_t mp_obj_new_int_from_ull(unsigned long long val) { // TODO raise an exception if the unsigned long long won't fit if (val >> (sizeof(unsigned long long) * 8 - 1) != 0) { - nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_OverflowError, "ulonglong too large")); + mp_raise_msg(&mp_type_OverflowError, "ulonglong too large"); } mp_obj_int_t *o = m_new_obj(mp_obj_int_t); o->base.type = &mp_type_int; diff --git a/py/objint_mpz.c b/py/objint_mpz.c index d818b6f407..0791a8af2c 100644 --- a/py/objint_mpz.c +++ b/py/objint_mpz.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -290,6 +290,13 @@ mp_obj_t mp_obj_int_binary_op(mp_uint_t op, mp_obj_t lhs_in, mp_obj_t rhs_in) { case MP_BINARY_OP_POWER: case MP_BINARY_OP_INPLACE_POWER: + if (mpz_is_neg(zrhs)) { + #if MICROPY_PY_BUILTINS_FLOAT + return mp_obj_float_binary_op(op, mpz_as_float(zlhs), rhs_in); + #else + mp_raise_ValueError("negative power with no float support"); + #endif + } mpz_pow_inpl(&res->mpz, zlhs, zrhs); break; diff --git a/py/objlist.c b/py/objlist.c index 45e69c8bcf..ba1c506771 100644 --- a/py/objlist.c +++ b/py/objlist.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/py/objlist.h b/py/objlist.h index 5b2d216fc2..28b5495a92 100644 --- a/py/objlist.h +++ b/py/objlist.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,8 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -#ifndef __MICROPY_INCLUDED_PY_OBJLIST_H__ -#define __MICROPY_INCLUDED_PY_OBJLIST_H__ +#ifndef MICROPY_INCLUDED_PY_OBJLIST_H +#define MICROPY_INCLUDED_PY_OBJLIST_H #include "py/obj.h" @@ -35,4 +35,4 @@ typedef struct _mp_obj_list_t { mp_obj_t *items; } mp_obj_list_t; -#endif // __MICROPY_INCLUDED_PY_OBJLIST_H__ +#endif // MICROPY_INCLUDED_PY_OBJLIST_H diff --git a/py/objmap.c b/py/objmap.c index 111c964fdd..908c61507e 100644 --- a/py/objmap.c +++ b/py/objmap.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/py/objmodule.c b/py/objmodule.c index 43bb36b98c..fc8507c27b 100644 --- a/py/objmodule.c +++ b/py/objmodule.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/py/objmodule.h b/py/objmodule.h index 4e6612adc7..b5c07dc333 100644 --- a/py/objmodule.h +++ b/py/objmodule.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,8 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -#ifndef __MICROPY_INCLUDED_PY_OBJMODULE_H__ -#define __MICROPY_INCLUDED_PY_OBJMODULE_H__ +#ifndef MICROPY_INCLUDED_PY_OBJMODULE_H +#define MICROPY_INCLUDED_PY_OBJMODULE_H #include "py/obj.h" @@ -34,4 +34,4 @@ extern const mp_map_t mp_builtin_module_weak_links_map; mp_obj_t mp_module_get(qstr module_name); void mp_module_register(qstr qstr, mp_obj_t module); -#endif // __MICROPY_INCLUDED_PY_OBJMODULE_H__ +#endif // MICROPY_INCLUDED_PY_OBJMODULE_H diff --git a/py/objnamedtuple.c b/py/objnamedtuple.c index cbd845dce8..fb9d9f02cf 100644 --- a/py/objnamedtuple.c +++ b/py/objnamedtuple.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -94,43 +94,37 @@ STATIC mp_obj_t namedtuple_make_new(const mp_obj_type_t *type_in, size_t n_args, } } - mp_obj_t *arg_objects; - if (n_args == num_fields) { - arg_objects = (mp_obj_t*)args; - } else { - size_t alloc_size = sizeof(mp_obj_t) * num_fields; - arg_objects = alloca(alloc_size); - memset(arg_objects, 0, alloc_size); + // Create a tuple and set the type to this namedtuple + mp_obj_tuple_t *tuple = MP_OBJ_TO_PTR(mp_obj_new_tuple(num_fields, NULL)); + tuple->base.type = type_in; - for (size_t i = 0; i < n_args; i++) { - arg_objects[i] = args[i]; - } + // Copy the positional args into the first slots of the namedtuple + memcpy(&tuple->items[0], args, sizeof(mp_obj_t) * n_args); - for (size_t i = n_args; i < n_args + 2 * n_kw; i += 2) { - qstr kw = mp_obj_str_get_qstr(args[i]); - size_t id = namedtuple_find_field(type, kw); - if (id == (size_t)-1) { - if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) { - mp_arg_error_terse_mismatch(); - } else { - nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, - "unexpected keyword argument '%q'", kw)); - } + // Fill in the remaining slots with the keyword args + memset(&tuple->items[n_args], 0, sizeof(mp_obj_t) * n_kw); + for (size_t i = n_args; i < n_args + 2 * n_kw; i += 2) { + qstr kw = mp_obj_str_get_qstr(args[i]); + size_t id = namedtuple_find_field(type, kw); + if (id == (size_t)-1) { + if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) { + mp_arg_error_terse_mismatch(); + } else { + nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, + "unexpected keyword argument '%q'", kw)); } - if (arg_objects[id] != MP_OBJ_NULL) { - if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) { - mp_arg_error_terse_mismatch(); - } else { - nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, - "function got multiple values for argument '%q'", kw)); - } - } - arg_objects[id] = args[i + 1]; } + if (tuple->items[id] != MP_OBJ_NULL) { + if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) { + mp_arg_error_terse_mismatch(); + } else { + nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, + "function got multiple values for argument '%q'", kw)); + } + } + tuple->items[id] = args[i + 1]; } - mp_obj_tuple_t *tuple = MP_OBJ_TO_PTR(mp_obj_new_tuple(num_fields, arg_objects)); - tuple->base.type = type_in; return MP_OBJ_FROM_PTR(tuple); } diff --git a/py/objnone.c b/py/objnone.c index 5d5b83540d..cd7319bec8 100644 --- a/py/objnone.c +++ b/py/objnone.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/py/objobject.c b/py/objobject.c index f9a7d17c34..49d2ec62ee 100644 --- a/py/objobject.c +++ b/py/objobject.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/py/objproperty.c b/py/objproperty.c index 8189935d20..0934fad058 100644 --- a/py/objproperty.c +++ b/py/objproperty.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/py/objrange.c b/py/objrange.c index 8c4e14f49c..33b07a9d44 100644 --- a/py/objrange.c +++ b/py/objrange.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/py/objreversed.c b/py/objreversed.c index fc85e72bfb..a596a2fde3 100644 --- a/py/objreversed.c +++ b/py/objreversed.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/py/objset.c b/py/objset.c index f74bc74a07..376439b73e 100644 --- a/py/objset.c +++ b/py/objset.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/py/objsingleton.c b/py/objsingleton.c index 394c127677..ea72ae38cc 100644 --- a/py/objsingleton.c +++ b/py/objsingleton.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/py/objslice.c b/py/objslice.c index 928be6dab1..358c44d061 100644 --- a/py/objslice.c +++ b/py/objslice.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/py/objstr.c b/py/objstr.c index e758dd0062..ddad7d3bdf 100644 --- a/py/objstr.c +++ b/py/objstr.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -469,6 +469,7 @@ STATIC mp_obj_t str_join(mp_obj_t self_in, mp_obj_t arg) { // return joined string return mp_obj_new_str_from_vstr(self_type, &vstr); } +MP_DEFINE_CONST_FUN_OBJ_2(str_join_obj, str_join); mp_obj_t mp_obj_str_split(size_t n_args, const mp_obj_t *args) { const mp_obj_type_t *self_type = mp_obj_get_type(args[0]); @@ -544,6 +545,7 @@ mp_obj_t mp_obj_str_split(size_t n_args, const mp_obj_t *args) { return res; } +MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_split_obj, 1, 3, mp_obj_str_split); #if MICROPY_PY_BUILTINS_STR_SPLITLINES STATIC mp_obj_t str_splitlines(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { @@ -589,6 +591,7 @@ STATIC mp_obj_t str_splitlines(size_t n_args, const mp_obj_t *pos_args, mp_map_t return res; } +MP_DEFINE_CONST_FUN_OBJ_KW(str_splitlines_obj, 1, str_splitlines); #endif STATIC mp_obj_t str_rsplit(size_t n_args, const mp_obj_t *args) { @@ -656,6 +659,7 @@ STATIC mp_obj_t str_rsplit(size_t n_args, const mp_obj_t *args) { return MP_OBJ_FROM_PTR(res); } +MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rsplit_obj, 1, 3, str_rsplit); STATIC mp_obj_t str_finder(size_t n_args, const mp_obj_t *args, int direction, bool is_index) { const mp_obj_type_t *self_type = mp_obj_get_type(args[0]); @@ -700,18 +704,22 @@ STATIC mp_obj_t str_finder(size_t n_args, const mp_obj_t *args, int direction, b STATIC mp_obj_t str_find(size_t n_args, const mp_obj_t *args) { return str_finder(n_args, args, 1, false); } +MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_find_obj, 2, 4, str_find); STATIC mp_obj_t str_rfind(size_t n_args, const mp_obj_t *args) { return str_finder(n_args, args, -1, false); } +MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rfind_obj, 2, 4, str_rfind); STATIC mp_obj_t str_index(size_t n_args, const mp_obj_t *args) { return str_finder(n_args, args, 1, true); } +MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_index_obj, 2, 4, str_index); STATIC mp_obj_t str_rindex(size_t n_args, const mp_obj_t *args) { return str_finder(n_args, args, -1, true); } +MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rindex_obj, 2, 4, str_rindex); // TODO: (Much) more variety in args STATIC mp_obj_t str_startswith(size_t n_args, const mp_obj_t *args) { @@ -727,6 +735,7 @@ STATIC mp_obj_t str_startswith(size_t n_args, const mp_obj_t *args) { } return mp_obj_new_bool(memcmp(start, prefix, prefix_len) == 0); } +MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_startswith_obj, 2, 3, str_startswith); STATIC mp_obj_t str_endswith(size_t n_args, const mp_obj_t *args) { GET_STR_DATA_LEN(args[0], str, str_len); @@ -740,6 +749,7 @@ STATIC mp_obj_t str_endswith(size_t n_args, const mp_obj_t *args) { } return mp_obj_new_bool(memcmp(str + (str_len - suffix_len), suffix, suffix_len) == 0); } +MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_endswith_obj, 2, 3, str_endswith); enum { LSTRIP, RSTRIP, STRIP }; @@ -817,14 +827,17 @@ STATIC mp_obj_t str_uni_strip(int type, size_t n_args, const mp_obj_t *args) { STATIC mp_obj_t str_strip(size_t n_args, const mp_obj_t *args) { return str_uni_strip(STRIP, n_args, args); } +MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_strip_obj, 1, 2, str_strip); STATIC mp_obj_t str_lstrip(size_t n_args, const mp_obj_t *args) { return str_uni_strip(LSTRIP, n_args, args); } +MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_lstrip_obj, 1, 2, str_lstrip); STATIC mp_obj_t str_rstrip(size_t n_args, const mp_obj_t *args) { return str_uni_strip(RSTRIP, n_args, args); } +MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rstrip_obj, 1, 2, str_rstrip); #if MICROPY_PY_BUILTINS_STR_CENTER STATIC mp_obj_t str_center(mp_obj_t str_in, mp_obj_t width_in) { @@ -841,6 +854,7 @@ STATIC mp_obj_t str_center(mp_obj_t str_in, mp_obj_t width_in) { memcpy(vstr.buf + left, str, str_len); return mp_obj_new_str_from_vstr(mp_obj_get_type(str_in), &vstr); } +MP_DEFINE_CONST_FUN_OBJ_2(str_center_obj, str_center); #endif // Takes an int arg, but only parses unsigned numbers, and only changes @@ -1064,7 +1078,6 @@ STATIC vstr_t mp_obj_str_format_helper(const char *str, const char *top, int *ar arg = mp_obj_new_str_from_vstr(&mp_type_str, &arg_vstr); } - char sign = '\0'; char fill = '\0'; char align = '\0'; int width = -1; @@ -1100,7 +1113,7 @@ STATIC vstr_t mp_obj_str_format_helper(const char *str, const char *top, int *ar } else if (*s == ' ') { flags |= PF_FLAG_SPACE_SIGN; } - sign = *s++; + s++; } if (*s == '#') { flags |= PF_FLAG_SHOW_PREFIX; @@ -1146,7 +1159,7 @@ STATIC vstr_t mp_obj_str_format_helper(const char *str, const char *top, int *ar fill = ' '; } - if (sign) { + if (flags & (PF_FLAG_SHOW_SIGN | PF_FLAG_SPACE_SIGN)) { if (type == 's') { if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) { terse_str_format_value_error(); @@ -1162,8 +1175,6 @@ STATIC vstr_t mp_obj_str_format_helper(const char *str, const char *top, int *ar "sign not allowed with integer format specifier 'c'"); } } - } else { - sign = '-'; } switch (align) { @@ -1346,6 +1357,7 @@ mp_obj_t mp_obj_str_format(size_t n_args, const mp_obj_t *args, mp_map_t *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_type_str, &vstr); } +MP_DEFINE_CONST_FUN_OBJ_KW(str_format_obj, 1, mp_obj_str_format); STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, size_t n_args, const mp_obj_t *args, mp_obj_t dict) { mp_check_self(MP_OBJ_IS_STR_OR_BYTES(pattern)); @@ -1649,6 +1661,7 @@ STATIC mp_obj_t str_replace(size_t n_args, const mp_obj_t *args) { return mp_obj_new_str_from_vstr(self_type, &vstr); } +MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_replace_obj, 3, 4, str_replace); STATIC mp_obj_t str_count(size_t n_args, const mp_obj_t *args) { const mp_obj_type_t *self_type = mp_obj_get_type(args[0]); @@ -1689,6 +1702,7 @@ STATIC mp_obj_t str_count(size_t n_args, const mp_obj_t *args) { return MP_OBJ_NEW_SMALL_INT(num_occurrences); } +MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_count_obj, 2, 4, str_count); #if MICROPY_PY_BUILTINS_STR_PARTITION STATIC mp_obj_t str_partitioner(mp_obj_t self_in, mp_obj_t arg, int direction) { @@ -1736,10 +1750,12 @@ STATIC mp_obj_t str_partitioner(mp_obj_t self_in, mp_obj_t arg, int direction) { STATIC mp_obj_t str_partition(mp_obj_t self_in, mp_obj_t arg) { return str_partitioner(self_in, arg, 1); } +MP_DEFINE_CONST_FUN_OBJ_2(str_partition_obj, str_partition); STATIC mp_obj_t str_rpartition(mp_obj_t self_in, mp_obj_t arg) { return str_partitioner(self_in, arg, -1); } +MP_DEFINE_CONST_FUN_OBJ_2(str_rpartition_obj, str_rpartition); #endif // Supposedly not too critical operations, so optimize for code size @@ -1757,10 +1773,12 @@ STATIC mp_obj_t str_caseconv(unichar (*op)(unichar), mp_obj_t self_in) { STATIC mp_obj_t str_lower(mp_obj_t self_in) { return str_caseconv(unichar_tolower, self_in); } +MP_DEFINE_CONST_FUN_OBJ_1(str_lower_obj, str_lower); STATIC mp_obj_t str_upper(mp_obj_t self_in) { return str_caseconv(unichar_toupper, self_in); } +MP_DEFINE_CONST_FUN_OBJ_1(str_upper_obj, str_upper); STATIC mp_obj_t str_uni_istype(bool (*f)(unichar), mp_obj_t self_in) { GET_STR_DATA_LEN(self_in, self_data, self_len); @@ -1798,22 +1816,27 @@ STATIC mp_obj_t str_uni_istype(bool (*f)(unichar), mp_obj_t self_in) { STATIC mp_obj_t str_isspace(mp_obj_t self_in) { return str_uni_istype(unichar_isspace, self_in); } +MP_DEFINE_CONST_FUN_OBJ_1(str_isspace_obj, str_isspace); STATIC mp_obj_t str_isalpha(mp_obj_t self_in) { return str_uni_istype(unichar_isalpha, self_in); } +MP_DEFINE_CONST_FUN_OBJ_1(str_isalpha_obj, str_isalpha); STATIC mp_obj_t str_isdigit(mp_obj_t self_in) { return str_uni_istype(unichar_isdigit, self_in); } +MP_DEFINE_CONST_FUN_OBJ_1(str_isdigit_obj, str_isdigit); STATIC mp_obj_t str_isupper(mp_obj_t self_in) { return str_uni_istype(unichar_isupper, self_in); } +MP_DEFINE_CONST_FUN_OBJ_1(str_isupper_obj, str_isupper); STATIC mp_obj_t str_islower(mp_obj_t self_in) { return str_uni_istype(unichar_islower, self_in); } +MP_DEFINE_CONST_FUN_OBJ_1(str_islower_obj, str_islower); #if MICROPY_CPYTHON_COMPAT // These methods are superfluous in the presence of str() and bytes() @@ -1829,6 +1852,7 @@ STATIC mp_obj_t bytes_decode(size_t n_args, const mp_obj_t *args) { } return mp_obj_str_make_new(&mp_type_str, n_args, 0, args); } +MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(bytes_decode_obj, 1, 3, bytes_decode); // TODO: should accept kwargs too STATIC mp_obj_t str_encode(size_t n_args, const mp_obj_t *args) { @@ -1841,6 +1865,7 @@ STATIC mp_obj_t str_encode(size_t n_args, const mp_obj_t *args) { } return bytes_make_new(NULL, n_args, 0, args); } +MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_encode_obj, 1, 3, str_encode); #endif mp_int_t mp_obj_str_get_buffer(mp_obj_t self_in, mp_buffer_info_t *bufinfo, mp_uint_t flags) { @@ -1859,43 +1884,6 @@ mp_int_t mp_obj_str_get_buffer(mp_obj_t self_in, mp_buffer_info_t *bufinfo, mp_u } } -#if MICROPY_CPYTHON_COMPAT -MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(bytes_decode_obj, 1, 3, bytes_decode); -MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_encode_obj, 1, 3, str_encode); -#endif -MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_find_obj, 2, 4, str_find); -MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rfind_obj, 2, 4, str_rfind); -MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_index_obj, 2, 4, str_index); -MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rindex_obj, 2, 4, str_rindex); -MP_DEFINE_CONST_FUN_OBJ_2(str_join_obj, str_join); -MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_split_obj, 1, 3, mp_obj_str_split); -#if MICROPY_PY_BUILTINS_STR_SPLITLINES -MP_DEFINE_CONST_FUN_OBJ_KW(str_splitlines_obj, 1, str_splitlines); -#endif -#if MICROPY_PY_BUILTINS_STR_CENTER -MP_DEFINE_CONST_FUN_OBJ_2(str_center_obj, str_center); -#endif -MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rsplit_obj, 1, 3, str_rsplit); -MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_startswith_obj, 2, 3, str_startswith); -MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_endswith_obj, 2, 3, str_endswith); -MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_strip_obj, 1, 2, str_strip); -MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_lstrip_obj, 1, 2, str_lstrip); -MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rstrip_obj, 1, 2, str_rstrip); -MP_DEFINE_CONST_FUN_OBJ_KW(str_format_obj, 1, mp_obj_str_format); -MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_replace_obj, 3, 4, str_replace); -MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_count_obj, 2, 4, str_count); -#if MICROPY_PY_BUILTINS_STR_PARTITION -MP_DEFINE_CONST_FUN_OBJ_2(str_partition_obj, str_partition); -MP_DEFINE_CONST_FUN_OBJ_2(str_rpartition_obj, str_rpartition); -#endif -MP_DEFINE_CONST_FUN_OBJ_1(str_lower_obj, str_lower); -MP_DEFINE_CONST_FUN_OBJ_1(str_upper_obj, str_upper); -MP_DEFINE_CONST_FUN_OBJ_1(str_isspace_obj, str_isspace); -MP_DEFINE_CONST_FUN_OBJ_1(str_isalpha_obj, str_isalpha); -MP_DEFINE_CONST_FUN_OBJ_1(str_isdigit_obj, str_isdigit); -MP_DEFINE_CONST_FUN_OBJ_1(str_isupper_obj, str_isupper); -MP_DEFINE_CONST_FUN_OBJ_1(str_islower_obj, str_islower); - STATIC const mp_rom_map_elem_t str8_locals_dict_table[] = { #if MICROPY_CPYTHON_COMPAT { MP_ROM_QSTR(MP_QSTR_decode), MP_ROM_PTR(&bytes_decode_obj) }, diff --git a/py/objstr.h b/py/objstr.h index e92832d106..3aef8c68e2 100644 --- a/py/objstr.h +++ b/py/objstr.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,8 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -#ifndef __MICROPY_INCLUDED_PY_OBJSTR_H__ -#define __MICROPY_INCLUDED_PY_OBJSTR_H__ +#ifndef MICROPY_INCLUDED_PY_OBJSTR_H +#define MICROPY_INCLUDED_PY_OBJSTR_H #include "py/obj.h" @@ -102,4 +102,4 @@ MP_DECLARE_CONST_FUN_OBJ_1(str_isdigit_obj); MP_DECLARE_CONST_FUN_OBJ_1(str_isupper_obj); MP_DECLARE_CONST_FUN_OBJ_1(str_islower_obj); -#endif // __MICROPY_INCLUDED_PY_OBJSTR_H__ +#endif // MICROPY_INCLUDED_PY_OBJSTR_H diff --git a/py/objstringio.c b/py/objstringio.c index 9f4adeebbf..046d325806 100644 --- a/py/objstringio.c +++ b/py/objstringio.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -68,10 +68,23 @@ STATIC mp_uint_t stringio_read(mp_obj_t o_in, void *buf, mp_uint_t size, int *er return size; } +STATIC void stringio_copy_on_write(mp_obj_stringio_t *o) { + const void *buf = o->vstr->buf; + o->vstr->buf = m_new(char, o->vstr->len); + memcpy(o->vstr->buf, buf, o->vstr->len); + o->vstr->fixed_buf = false; + o->ref_obj = MP_OBJ_NULL; +} + STATIC mp_uint_t stringio_write(mp_obj_t o_in, const void *buf, mp_uint_t size, int *errcode) { (void)errcode; mp_obj_stringio_t *o = MP_OBJ_TO_PTR(o_in); check_stringio_is_open(o); + + if (o->vstr->fixed_buf) { + stringio_copy_on_write(o); + } + mp_uint_t new_pos = o->pos + size; if (new_pos < size) { // Writing bytes will overflow o->pos beyond limit of mp_uint_t. @@ -155,11 +168,11 @@ STATIC mp_obj_t stringio___exit__(size_t n_args, const mp_obj_t *args) { } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(stringio___exit___obj, 4, 4, stringio___exit__); -STATIC mp_obj_stringio_t *stringio_new(const mp_obj_type_t *type, mp_uint_t alloc) { +STATIC mp_obj_stringio_t *stringio_new(const mp_obj_type_t *type) { mp_obj_stringio_t *o = m_new_obj(mp_obj_stringio_t); o->base.type = type; - o->vstr = vstr_new(alloc); o->pos = 0; + o->ref_obj = MP_OBJ_NULL; return o; } @@ -170,17 +183,28 @@ STATIC mp_obj_t stringio_make_new(const mp_obj_type_t *type_in, size_t n_args, s bool initdata = false; mp_buffer_info_t bufinfo; + mp_obj_stringio_t *o = stringio_new(type_in); + if (n_args > 0) { if (MP_OBJ_IS_INT(args[0])) { sz = mp_obj_get_int(args[0]); } else { mp_get_buffer_raise(args[0], &bufinfo, MP_BUFFER_READ); + + if (MP_OBJ_IS_STR_OR_BYTES(args[0])) { + o->vstr = m_new_obj(vstr_t); + vstr_init_fixed_buf(o->vstr, bufinfo.len, bufinfo.buf); + o->vstr->len = bufinfo.len; + o->ref_obj = args[0]; + return MP_OBJ_FROM_PTR(o); + } + sz = bufinfo.len; initdata = true; } } - mp_obj_stringio_t *o = stringio_new(type_in, sz); + o->vstr = vstr_new(sz); if (initdata) { stringio_write(MP_OBJ_FROM_PTR(o), bufinfo.buf, bufinfo.len, NULL); diff --git a/py/objstringio.h b/py/objstringio.h index 853bfb11b7..56738f4e45 100644 --- a/py/objstringio.h +++ b/py/objstringio.h @@ -33,6 +33,8 @@ typedef struct _mp_obj_stringio_t { vstr_t *vstr; // StringIO has single pointer used for both reading and writing mp_uint_t pos; + // Underlying object buffered by this StringIO + mp_obj_t ref_obj; } mp_obj_stringio_t; #endif // MICROPY_INCLUDED_PY_OBJSTRINGIO_H diff --git a/py/objstrunicode.c b/py/objstrunicode.c index 9a6ce9b9a2..0cf791ff7c 100644 --- a/py/objstrunicode.c +++ b/py/objstrunicode.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -142,7 +142,7 @@ const byte *str_index_to_ptr(const mp_obj_type_t *type, const byte *self_data, s if (is_slice) { return self_data; } - nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_IndexError, "string index out of range")); + mp_raise_msg(&mp_type_IndexError, "string index out of range"); } if (!UTF8_IS_CONT(*s)) { ++i; @@ -161,7 +161,7 @@ const byte *str_index_to_ptr(const mp_obj_type_t *type, const byte *self_data, s if (is_slice) { return top; } - nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_IndexError, "string index out of range")); + mp_raise_msg(&mp_type_IndexError, "string index out of range"); } // Then check completion if (i-- == 0) { diff --git a/py/objtuple.c b/py/objtuple.c index eaf0e37f47..0b05755fb3 100644 --- a/py/objtuple.c +++ b/py/objtuple.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/py/objtuple.h b/py/objtuple.h index 555c3b3c2c..05c6490fe6 100644 --- a/py/objtuple.h +++ b/py/objtuple.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,8 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -#ifndef __MICROPY_INCLUDED_PY_OBJTUPLE_H__ -#define __MICROPY_INCLUDED_PY_OBJTUPLE_H__ +#ifndef MICROPY_INCLUDED_PY_OBJTUPLE_H +#define MICROPY_INCLUDED_PY_OBJTUPLE_H #include "py/obj.h" @@ -61,4 +61,4 @@ void mp_obj_attrtuple_print_helper(const mp_print_t *print, const qstr *fields, mp_obj_t mp_obj_new_attrtuple(const qstr *fields, size_t n, const mp_obj_t *items); -#endif // __MICROPY_INCLUDED_PY_OBJTUPLE_H__ +#endif // MICROPY_INCLUDED_PY_OBJTUPLE_H diff --git a/py/objtype.c b/py/objtype.c index 2a119e40fb..a258915f34 100644 --- a/py/objtype.c +++ b/py/objtype.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -375,7 +375,7 @@ STATIC mp_obj_t instance_unary_op(mp_uint_t op, mp_obj_t self_in) { if (member[0] == MP_OBJ_NULL) { // https://docs.python.org/3/reference/datamodel.html#object.__hash__ // "User-defined classes have __eq__() and __hash__() methods by default; - // with them, all objects compare unequal (except with themselves) and + // with them, all objects compare unequal (except with themselves) and // x.__hash__() returns an appropriate value such that x == y implies // both that x is y and hash(x) == hash(y)." return MP_OBJ_NEW_SMALL_INT((mp_uint_t)self_in); @@ -917,8 +917,8 @@ const mp_obj_type_t mp_type_type = { }; mp_obj_t mp_obj_new_type(qstr name, mp_obj_t bases_tuple, mp_obj_t locals_dict) { - assert(MP_OBJ_IS_TYPE(bases_tuple, &mp_type_tuple)); // Micro Python restriction, for now - assert(MP_OBJ_IS_TYPE(locals_dict, &mp_type_dict)); // Micro Python restriction, for now + assert(MP_OBJ_IS_TYPE(bases_tuple, &mp_type_tuple)); // MicroPython restriction, for now + assert(MP_OBJ_IS_TYPE(locals_dict, &mp_type_dict)); // MicroPython restriction, for now // TODO might need to make a copy of locals_dict; at least that's how CPython does it diff --git a/py/objtype.h b/py/objtype.h index 61efd00c05..52419f3cdc 100644 --- a/py/objtype.h +++ b/py/objtype.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,8 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -#ifndef __MICROPY_INCLUDED_PY_OBJTYPE_H__ -#define __MICROPY_INCLUDED_PY_OBJTYPE_H__ +#ifndef MICROPY_INCLUDED_PY_OBJTYPE_H +#define MICROPY_INCLUDED_PY_OBJTYPE_H #include "py/obj.h" @@ -49,4 +49,4 @@ mp_obj_t mp_obj_instance_call(mp_obj_t self_in, size_t n_args, size_t n_kw, cons // this needs to be exposed for the above macros to work correctly mp_obj_t mp_obj_instance_make_new(const mp_obj_type_t *self_in, size_t n_args, size_t n_kw, const mp_obj_t *args); -#endif // __MICROPY_INCLUDED_PY_OBJTYPE_H__ +#endif // MICROPY_INCLUDED_PY_OBJTYPE_H diff --git a/py/objzip.c b/py/objzip.c index 6f72d15954..0183925e3c 100644 --- a/py/objzip.c +++ b/py/objzip.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/py/opmethods.c b/py/opmethods.c index 80a953fb89..1200ba39ef 100644 --- a/py/opmethods.c +++ b/py/opmethods.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/py/parse.c b/py/parse.c index 2f16748a6c..e399aac535 100644 --- a/py/parse.c +++ b/py/parse.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/py/parse.h b/py/parse.h index 769f5a8757..9a1a2b4dd4 100644 --- a/py/parse.h +++ b/py/parse.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,8 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -#ifndef __MICROPY_INCLUDED_PY_PARSE_H__ -#define __MICROPY_INCLUDED_PY_PARSE_H__ +#ifndef MICROPY_INCLUDED_PY_PARSE_H +#define MICROPY_INCLUDED_PY_PARSE_H #include #include @@ -104,4 +104,4 @@ typedef struct _mp_parse_t { mp_parse_tree_t mp_parse(struct _mp_lexer_t *lex, mp_parse_input_kind_t input_kind); void mp_parse_tree_clear(mp_parse_tree_t *tree); -#endif // __MICROPY_INCLUDED_PY_PARSE_H__ +#endif // MICROPY_INCLUDED_PY_PARSE_H diff --git a/py/parsenum.c b/py/parsenum.c index 1771188434..b62029f7c7 100644 --- a/py/parsenum.c +++ b/py/parsenum.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/py/parsenum.h b/py/parsenum.h index f140cfc85e..a5bed731d2 100644 --- a/py/parsenum.h +++ b/py/parsenum.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,8 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -#ifndef __MICROPY_INCLUDED_PY_PARSENUM_H__ -#define __MICROPY_INCLUDED_PY_PARSENUM_H__ +#ifndef MICROPY_INCLUDED_PY_PARSENUM_H +#define MICROPY_INCLUDED_PY_PARSENUM_H #include "py/mpconfig.h" #include "py/lexer.h" @@ -34,4 +34,4 @@ mp_obj_t mp_parse_num_integer(const char *restrict str, size_t len, int base, mp_lexer_t *lex); mp_obj_t mp_parse_num_decimal(const char *str, size_t len, bool allow_imag, bool force_complex, mp_lexer_t *lex); -#endif // __MICROPY_INCLUDED_PY_PARSENUM_H__ +#endif // MICROPY_INCLUDED_PY_PARSENUM_H diff --git a/py/parsenumbase.c b/py/parsenumbase.c index 73a3372f0a..ba10591226 100644 --- a/py/parsenumbase.c +++ b/py/parsenumbase.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/py/parsenumbase.h b/py/parsenumbase.h index 9da9db8412..3a525f993c 100644 --- a/py/parsenumbase.h +++ b/py/parsenumbase.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,11 +23,11 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -#ifndef __MICROPY_INCLUDED_PY_PARSENUMBASE_H__ -#define __MICROPY_INCLUDED_PY_PARSENUMBASE_H__ +#ifndef MICROPY_INCLUDED_PY_PARSENUMBASE_H +#define MICROPY_INCLUDED_PY_PARSENUMBASE_H #include "py/mpconfig.h" size_t mp_parse_num_base(const char *str, size_t len, int *base); -#endif // __MICROPY_INCLUDED_PY_PARSENUMBASE_H__ +#endif // MICROPY_INCLUDED_PY_PARSENUMBASE_H diff --git a/py/py.mk b/py/py.mk index 70891677d6..02f2df8e12 100644 --- a/py/py.mk +++ b/py/py.mk @@ -74,7 +74,7 @@ endif ifeq ($(MICROPY_PY_BTREE),1) BTREE_DIR = lib/berkeley-db-1.xx -CFLAGS_MOD += -D__DBINTERFACE_PRIVATE=1 -Dmpool_error=printf -Dabort=abort_ -Dvirt_fd_t=mp_obj_t "-DVIRT_FD_T_HEADER=" +BTREE_DEFS = -D__DBINTERFACE_PRIVATE=1 -Dmpool_error=printf -Dabort=abort_ -Dvirt_fd_t=mp_obj_t "-DVIRT_FD_T_HEADER=" INC += -I../$(BTREE_DIR)/PORT/include SRC_MOD += extmod/modbtree.c SRC_MOD += $(addprefix $(BTREE_DIR)/,\ @@ -95,7 +95,9 @@ mpool/mpool.c \ ) CFLAGS_MOD += -DMICROPY_PY_BTREE=1 # we need to suppress certain warnings to get berkeley-db to compile cleanly -$(BUILD)/$(BTREE_DIR)/%.o: CFLAGS += -Wno-old-style-definition -Wno-sign-compare -Wno-unused-parameter +# and we have separate BTREE_DEFS so the definitions don't interfere with other source code +$(BUILD)/$(BTREE_DIR)/%.o: CFLAGS += -Wno-old-style-definition -Wno-sign-compare -Wno-unused-parameter $(BTREE_DEFS) +$(BUILD)/extmod/modbtree.o: CFLAGS += $(BTREE_DEFS) endif # py object files diff --git a/py/qstr.c b/py/qstr.c index 5aa1610648..fdb38f1dec 100644 --- a/py/qstr.c +++ b/py/qstr.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/py/qstr.h b/py/qstr.h index 8c63fbbc8d..e2bdcc351e 100644 --- a/py/qstr.h +++ b/py/qstr.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,8 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -#ifndef __MICROPY_INCLUDED_PY_QSTR_H__ -#define __MICROPY_INCLUDED_PY_QSTR_H__ +#ifndef MICROPY_INCLUDED_PY_QSTR_H +#define MICROPY_INCLUDED_PY_QSTR_H #include "py/mpconfig.h" #include "py/misc.h" @@ -76,4 +76,4 @@ const byte *qstr_data(qstr q, size_t *len); void qstr_pool_info(size_t *n_pool, size_t *n_qstr, size_t *n_str_data_bytes, size_t *n_total_bytes); void qstr_dump_data(void); -#endif // __MICROPY_INCLUDED_PY_QSTR_H__ +#endif // MICROPY_INCLUDED_PY_QSTR_H diff --git a/py/qstrdefs.h b/py/qstrdefs.h index 4581e5e1b1..9375b9101a 100644 --- a/py/qstrdefs.h +++ b/py/qstrdefs.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/py/reader.c b/py/reader.c index 5df45c4957..c4d18d53dc 100644 --- a/py/reader.c +++ b/py/reader.c @@ -71,7 +71,6 @@ void mp_reader_new_mem(mp_reader_t *reader, const byte *buf, size_t len, size_t #include #include #include -#include typedef struct _mp_reader_posix_t { bool close_fd; diff --git a/py/repl.c b/py/repl.c index 6d8f7cca46..7e8922e19a 100644 --- a/py/repl.c +++ b/py/repl.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -32,7 +32,7 @@ #if MICROPY_HELPER_REPL STATIC bool str_startswith_word(const char *str, const char *head) { - mp_uint_t i; + size_t i; for (i = 0; str[i] && head[i]; i++) { if (str[i] != head[i]) { return false; @@ -124,7 +124,7 @@ bool mp_repl_continue_with_input(const char *input) { return false; } -mp_uint_t mp_repl_autocomplete(const char *str, mp_uint_t len, const mp_print_t *print, const char **compl_str) { +size_t mp_repl_autocomplete(const char *str, size_t len, const mp_print_t *print, const char **compl_str) { // scan backwards to find start of "a.b.c" chain const char *org_str = str; const char *top = str + len; @@ -145,13 +145,13 @@ mp_uint_t mp_repl_autocomplete(const char *str, mp_uint_t len, const mp_print_t while (str < top && *str != '.') { ++str; } - mp_uint_t s_len = str - s_start; + size_t s_len = str - s_start; if (str < top) { // a complete word, lookup in current dict mp_obj_t obj = MP_OBJ_NULL; - for (mp_uint_t i = 0; i < dict->map.alloc; i++) { + for (size_t i = 0; i < dict->map.alloc; i++) { if (MP_MAP_SLOT_IS_FILLED(&dict->map, i)) { size_t d_len; const char *d_str = mp_obj_str_get_data(dict->map.table[i].key, &d_len); @@ -194,8 +194,8 @@ mp_uint_t mp_repl_autocomplete(const char *str, mp_uint_t len, const mp_print_t // look for matches int n_found = 0; const char *match_str = NULL; - mp_uint_t match_len = 0; - for (mp_uint_t i = 0; i < dict->map.alloc; i++) { + size_t match_len = 0; + for (size_t i = 0; i < dict->map.alloc; i++) { if (MP_MAP_SLOT_IS_FILLED(&dict->map, i)) { size_t d_len; const char *d_str = mp_obj_str_get_data(dict->map.table[i].key, &d_len); @@ -206,7 +206,7 @@ mp_uint_t mp_repl_autocomplete(const char *str, mp_uint_t len, const mp_print_t } else { // search for longest common prefix of match_str and d_str // (assumes these strings are null-terminated) - for (mp_uint_t j = s_len; j <= match_len && j <= d_len; ++j) { + for (size_t j = s_len; j <= match_len && j <= d_len; ++j) { if (match_str[j] != d_str[j]) { match_len = j; break; @@ -245,7 +245,7 @@ mp_uint_t mp_repl_autocomplete(const char *str, mp_uint_t len, const mp_print_t #define MAX_LINE_LEN (4 * WORD_SLOT_LEN) int line_len = MAX_LINE_LEN; // force a newline for first word - for (mp_uint_t i = 0; i < dict->map.alloc; i++) { + for (size_t i = 0; i < dict->map.alloc; i++) { if (MP_MAP_SLOT_IS_FILLED(&dict->map, i)) { size_t d_len; const char *d_str = mp_obj_str_get_data(dict->map.table[i].key, &d_len); @@ -270,7 +270,7 @@ mp_uint_t mp_repl_autocomplete(const char *str, mp_uint_t len, const mp_print_t } mp_print_str(print, "\n"); - return (mp_uint_t)(-1); // indicate many matches + return (size_t)(-1); // indicate many matches } } } diff --git a/py/repl.h b/py/repl.h index c34a5b8692..a7a4136cad 100644 --- a/py/repl.h +++ b/py/repl.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,8 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -#ifndef __MICROPY_INCLUDED_PY_REPL_H__ -#define __MICROPY_INCLUDED_PY_REPL_H__ +#ifndef MICROPY_INCLUDED_PY_REPL_H +#define MICROPY_INCLUDED_PY_REPL_H #include "py/mpconfig.h" #include "py/misc.h" @@ -32,7 +32,7 @@ #if MICROPY_HELPER_REPL bool mp_repl_continue_with_input(const char *input); -mp_uint_t mp_repl_autocomplete(const char *str, mp_uint_t len, const mp_print_t *print, const char **compl_str); +size_t mp_repl_autocomplete(const char *str, size_t len, const mp_print_t *print, const char **compl_str); #endif -#endif // __MICROPY_INCLUDED_PY_REPL_H__ +#endif // MICROPY_INCLUDED_PY_REPL_H diff --git a/py/ringbuf.h b/py/ringbuf.h index 5e108afad7..b416927060 100644 --- a/py/ringbuf.h +++ b/py/ringbuf.h @@ -23,8 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -#ifndef __MICROPY_INCLUDED_PY_RINGBUF_H__ -#define __MICROPY_INCLUDED_PY_RINGBUF_H__ +#ifndef MICROPY_INCLUDED_PY_RINGBUF_H +#define MICROPY_INCLUDED_PY_RINGBUF_H typedef struct _ringbuf_t { uint8_t *buf; @@ -69,4 +69,4 @@ static inline int ringbuf_put(ringbuf_t *r, uint8_t v) { return 0; } -#endif // __MICROPY_INCLUDED_PY_RINGBUF_H__ +#endif // MICROPY_INCLUDED_PY_RINGBUF_H diff --git a/py/runtime.c b/py/runtime.c index bf2bfb8eae..6a0db007e3 100644 --- a/py/runtime.c +++ b/py/runtime.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -127,7 +127,7 @@ void mp_deinit(void) { //mp_obj_dict_free(&dict_main); //mp_map_deinit(&MP_STATE_VM(mp_loaded_modules_map)); - // call port specific deinitialization if any + // call port specific deinitialization if any #ifdef MICROPY_PORT_INIT_FUNC MICROPY_PORT_DEINIT_FUNC; #endif @@ -1038,7 +1038,7 @@ void mp_load_method_maybe(mp_obj_t obj, qstr attr, mp_obj_t *dest) { } else if (type->locals_dict != NULL) { // generic method lookup // this is a lookup in the object (ie not class or type) - assert(type->locals_dict->base.type == &mp_type_dict); // Micro Python restriction, for now + assert(type->locals_dict->base.type == &mp_type_dict); // MicroPython restriction, for now mp_map_t *locals_map = &type->locals_dict->map; mp_map_elem_t *elem = mp_map_lookup(locals_map, MP_OBJ_NEW_QSTR(attr), MP_MAP_LOOKUP); if (elem != NULL) { @@ -1408,18 +1408,15 @@ mp_obj_t mp_parse_compile_execute(mp_lexer_t *lex, mp_parse_input_kind_t parse_i #endif // MICROPY_ENABLE_COMPILER -void *m_malloc_fail(size_t num_bytes) { +NORETURN void *m_malloc_fail(size_t num_bytes) { DEBUG_printf("memory allocation failed, allocating %u bytes\n", (uint)num_bytes); - if (0) { - // dummy #if MICROPY_ENABLE_GC - } else if (gc_is_locked()) { + if (gc_is_locked()) { mp_raise_msg(&mp_type_MemoryError, "memory allocation failed, heap is locked"); - #endif - } else { - nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_MemoryError, - "memory allocation failed, allocating %u bytes", (uint)num_bytes)); } + #endif + nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_MemoryError, + "memory allocation failed, allocating %u bytes", (uint)num_bytes)); } NORETURN void mp_raise_msg(const mp_obj_type_t *exc_type, const char *msg) { diff --git a/py/runtime.h b/py/runtime.h index d75d23ff18..fe492885b1 100644 --- a/py/runtime.h +++ b/py/runtime.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,8 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -#ifndef __MICROPY_INCLUDED_PY_RUNTIME_H__ -#define __MICROPY_INCLUDED_PY_RUNTIME_H__ +#ifndef MICROPY_INCLUDED_PY_RUNTIME_H +#define MICROPY_INCLUDED_PY_RUNTIME_H #include "py/mpstate.h" #include "py/obj.h" @@ -178,4 +178,4 @@ void mp_warning(const char *msg, ...); #define mp_warning(msg, ...) #endif -#endif // __MICROPY_INCLUDED_PY_RUNTIME_H__ +#endif // MICROPY_INCLUDED_PY_RUNTIME_H diff --git a/py/runtime0.h b/py/runtime0.h index 720fe6a23b..d22c2fabe6 100644 --- a/py/runtime0.h +++ b/py/runtime0.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,8 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -#ifndef __MICROPY_INCLUDED_PY_RUNTIME0_H__ -#define __MICROPY_INCLUDED_PY_RUNTIME0_H__ +#ifndef MICROPY_INCLUDED_PY_RUNTIME0_H +#define MICROPY_INCLUDED_PY_RUNTIME0_H // These must fit in 8 bits; see scope.h #define MP_SCOPE_FLAG_VARARGS (0x01) @@ -151,4 +151,4 @@ typedef enum { extern void *const mp_fun_table[MP_F_NUMBER_OF]; -#endif // __MICROPY_INCLUDED_PY_RUNTIME0_H__ +#endif // MICROPY_INCLUDED_PY_RUNTIME0_H diff --git a/py/runtime_utils.c b/py/runtime_utils.c index e0495495aa..56a9180645 100644 --- a/py/runtime_utils.c +++ b/py/runtime_utils.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/py/scope.c b/py/scope.c index 8fe6f960ad..1a6ae7b8ad 100644 --- a/py/scope.c +++ b/py/scope.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/py/scope.h b/py/scope.h index 826064d7ef..e3b6a57c79 100644 --- a/py/scope.h +++ b/py/scope.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,8 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -#ifndef __MICROPY_INCLUDED_PY_SCOPE_H__ -#define __MICROPY_INCLUDED_PY_SCOPE_H__ +#ifndef MICROPY_INCLUDED_PY_SCOPE_H +#define MICROPY_INCLUDED_PY_SCOPE_H #include "py/parse.h" #include "py/emitglue.h" @@ -94,4 +94,4 @@ id_info_t *scope_find(scope_t *scope, qstr qstr); id_info_t *scope_find_global(scope_t *scope, qstr qstr); void scope_find_local_and_close_over(scope_t *scope, id_info_t *id, qstr qst); -#endif // __MICROPY_INCLUDED_PY_SCOPE_H__ +#endif // MICROPY_INCLUDED_PY_SCOPE_H diff --git a/py/sequence.c b/py/sequence.c index 32db640dc1..0752ee1098 100644 --- a/py/sequence.c +++ b/py/sequence.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/py/showbc.c b/py/showbc.c index 0bccf8427f..bb2b084ed7 100644 --- a/py/showbc.c +++ b/py/showbc.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/py/smallint.c b/py/smallint.c index 4c42ee0cc9..aa542ca7bf 100644 --- a/py/smallint.c +++ b/py/smallint.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/py/smallint.h b/py/smallint.h index b9686be30a..42679a78fb 100644 --- a/py/smallint.h +++ b/py/smallint.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,8 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -#ifndef __MICROPY_INCLUDED_PY_SMALLINT_H__ -#define __MICROPY_INCLUDED_PY_SMALLINT_H__ +#ifndef MICROPY_INCLUDED_PY_SMALLINT_H +#define MICROPY_INCLUDED_PY_SMALLINT_H #include "py/mpconfig.h" #include "py/misc.h" @@ -65,4 +65,4 @@ bool mp_small_int_mul_overflow(mp_int_t x, mp_int_t y); mp_int_t mp_small_int_modulo(mp_int_t dividend, mp_int_t divisor); mp_int_t mp_small_int_floor_divide(mp_int_t num, mp_int_t denom); -#endif // __MICROPY_INCLUDED_PY_SMALLINT_H__ +#endif // MICROPY_INCLUDED_PY_SMALLINT_H diff --git a/py/stackctrl.c b/py/stackctrl.c index 1843e7339e..0bcd82f4f6 100644 --- a/py/stackctrl.c +++ b/py/stackctrl.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/py/stackctrl.h b/py/stackctrl.h index e915f5000f..ff8da0ab13 100644 --- a/py/stackctrl.h +++ b/py/stackctrl.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,8 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -#ifndef __MICROPY_INCLUDED_PY_STACKCTRL_H__ -#define __MICROPY_INCLUDED_PY_STACKCTRL_H__ +#ifndef MICROPY_INCLUDED_PY_STACKCTRL_H +#define MICROPY_INCLUDED_PY_STACKCTRL_H #include "py/mpconfig.h" @@ -45,4 +45,4 @@ void mp_stack_check(void); #endif -#endif // __MICROPY_INCLUDED_PY_STACKCTRL_H__ +#endif // MICROPY_INCLUDED_PY_STACKCTRL_H diff --git a/py/stream.c b/py/stream.c index d3fc767bbd..5d18681538 100644 --- a/py/stream.c +++ b/py/stream.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -142,7 +142,7 @@ STATIC mp_obj_t stream_read_generic(size_t n_args, const mp_obj_t *args, byte fl while (more_bytes > 0) { char *p = vstr_add_len(&vstr, more_bytes); if (p == NULL) { - nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_MemoryError, "out of memory")); + mp_raise_msg(&mp_type_MemoryError, "out of memory"); } int error; mp_uint_t out_sz = mp_stream_read_exactly(args[0], p, more_bytes, &error); @@ -381,7 +381,7 @@ STATIC mp_obj_t stream_unbuffered_readline(size_t n_args, const mp_obj_t *args) while (max_size == -1 || max_size-- != 0) { char *p = vstr_add_len(&vstr, 1); if (p == NULL) { - nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_MemoryError, "out of memory")); + mp_raise_msg(&mp_type_MemoryError, "out of memory"); } int error; diff --git a/py/stream.h b/py/stream.h index 01199ab601..401ae313cd 100644 --- a/py/stream.h +++ b/py/stream.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,8 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -#ifndef __MICROPY_INCLUDED_PY_STREAM_H__ -#define __MICROPY_INCLUDED_PY_STREAM_H__ +#ifndef MICROPY_INCLUDED_PY_STREAM_H +#define MICROPY_INCLUDED_PY_STREAM_H #include "py/obj.h" #include "py/mperrno.h" @@ -103,4 +103,4 @@ int mp_stream_posix_fsync(mp_obj_t stream); #define mp_is_nonblocking_error(errno) (0) #endif -#endif // __MICROPY_INCLUDED_PY_STREAM_H__ +#endif // MICROPY_INCLUDED_PY_STREAM_H diff --git a/py/unicode.c b/py/unicode.c index c6f872038d..eddb007d5e 100644 --- a/py/unicode.c +++ b/py/unicode.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/py/unicode.h b/py/unicode.h index 89c28ed0ec..19487a65ae 100644 --- a/py/unicode.h +++ b/py/unicode.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,12 +23,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -#ifndef __MICROPY_INCLUDED_PY_UNICODE_H__ -#define __MICROPY_INCLUDED_PY_UNICODE_H__ +#ifndef MICROPY_INCLUDED_PY_UNICODE_H +#define MICROPY_INCLUDED_PY_UNICODE_H #include "py/mpconfig.h" #include "py/misc.h" mp_uint_t utf8_ptr_to_index(const byte *s, const byte *ptr); -#endif // __MICROPY_INCLUDED_PY_UNICODE_H__ +#endif // MICROPY_INCLUDED_PY_UNICODE_H diff --git a/py/vm.c b/py/vm.c index ad3d9e29c8..c7fc83d048 100644 --- a/py/vm.c +++ b/py/vm.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -162,9 +162,13 @@ mp_vm_return_kind_t mp_execute_bytecode(mp_code_state_t *code_state, volatile mp run_code_state: ; #endif // Pointers which are constant for particular invocation of mp_execute_bytecode() - size_t n_state = mp_decode_uint_value(code_state->fun_bc->bytecode); - mp_obj_t * /*const*/ fastn = &code_state->state[n_state - 1]; - mp_exc_stack_t * /*const*/ exc_stack = (mp_exc_stack_t*)(code_state->state + n_state); + 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); + } // variables that are visible to the exception handler (declared volatile) volatile bool currently_in_except_block = MP_TAGPTR_TAG0(code_state->exc_sp); // 0 or 1, to detect nested exceptions @@ -1159,8 +1163,7 @@ yield: ip--; PUSH(ret_value); goto yield; - } - if (ret_kind == MP_VM_RETURN_NORMAL) { + } else if (ret_kind == MP_VM_RETURN_NORMAL) { // Pop exhausted gen sp--; // TODO: When ret_value can be MP_OBJ_NULL here?? @@ -1176,8 +1179,8 @@ yield: // if it was swallowed, we re-raise GeneratorExit GENERATOR_EXIT_IF_NEEDED(t_exc); DISPATCH(); - } - if (ret_kind == MP_VM_RETURN_EXCEPTION) { + } else { + assert(ret_kind == MP_VM_RETURN_EXCEPTION); // Pop exhausted gen sp--; if (EXC_MATCH(ret_value, MP_OBJ_FROM_PTR(&mp_type_StopIteration))) { @@ -1363,22 +1366,25 @@ unwind_loop: // TODO need a better way of not adding traceback to constant objects (right now, just GeneratorExit_obj and MemoryError_obj) if (nlr.ret_val != &mp_const_GeneratorExit_obj && nlr.ret_val != &mp_const_MemoryError_obj) { const byte *ip = code_state->fun_bc->bytecode; - mp_decode_uint(&ip); // skip n_state - mp_decode_uint(&ip); // skip n_exc_stack + ip = mp_decode_uint_skip(ip); // skip n_state + ip = mp_decode_uint_skip(ip); // skip n_exc_stack ip++; // skip scope_params ip++; // skip n_pos_args ip++; // skip n_kwonly_args ip++; // skip n_def_pos_args size_t bc = code_state->ip - ip; - size_t code_info_size = mp_decode_uint(&ip); + size_t code_info_size = mp_decode_uint_value(ip); + ip = mp_decode_uint_skip(ip); // skip code_info_size bc -= code_info_size; #if MICROPY_PERSISTENT_CODE qstr block_name = ip[0] | (ip[1] << 8); qstr source_file = ip[2] | (ip[3] << 8); ip += 4; #else - qstr block_name = mp_decode_uint(&ip); - qstr source_file = mp_decode_uint(&ip); + qstr block_name = mp_decode_uint_value(ip); + ip = mp_decode_uint_skip(ip); + qstr source_file = mp_decode_uint_value(ip); + ip = mp_decode_uint_skip(ip); #endif size_t source_line = 1; size_t c; diff --git a/py/vmentrytable.h b/py/vmentrytable.h index dd9789e348..352a6dc315 100644 --- a/py/vmentrytable.h +++ b/py/vmentrytable.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/py/vstr.c b/py/vstr.c index 6a91552b5a..8a00f6c6f7 100644 --- a/py/vstr.c +++ b/py/vstr.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -34,7 +34,7 @@ #include "py/mpprint.h" // returned value is always at least 1 greater than argument -#define ROUND_ALLOC(a) (((a) & ((~0) - 7)) + 8) +#define ROUND_ALLOC(a) (((a) & ((~0U) - 7)) + 8) // Init the vstr so it allocs exactly given number of bytes. Set length to zero. void vstr_init(vstr_t *vstr, size_t alloc) { diff --git a/py/warning.c b/py/warning.c index 4cdf3b3f10..46b31ecca7 100644 --- a/py/warning.c +++ b/py/warning.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/qemu-arm/Makefile b/qemu-arm/Makefile index 07aa685720..743b6683a8 100644 --- a/qemu-arm/Makefile +++ b/qemu-arm/Makefile @@ -63,17 +63,13 @@ LIB_SRC_C = $(addprefix lib/,\ libm/asinfacosf.c \ libm/atanf.c \ libm/atan2f.c \ - ) - -STM_SRC_C = $(addprefix stmhal/,\ - pybstdio.c \ + utils/sys_stdio_mphal.c \ ) OBJ_COMMON = OBJ_COMMON += $(PY_O) OBJ_COMMON += $(addprefix $(BUILD)/, $(SRC_COMMON_C:.c=.o)) OBJ_COMMON += $(addprefix $(BUILD)/, $(LIB_SRC_C:.c=.o)) -OBJ_COMMON += $(addprefix $(BUILD)/, $(STM_SRC_C:.c=.o)) OBJ_RUN = OBJ_RUN += $(addprefix $(BUILD)/, $(SRC_RUN_C:.c=.o)) @@ -86,7 +82,7 @@ OBJ_TEST += $(BUILD)/tinytest.o OBJ = $(OBJ_COMMON) $(OBJ_RUN) $(OBJ_TEST) # List of sources for qstr extraction -SRC_QSTR += $(SRC_COMMON_C) $(SRC_RUN_C) $(STM_SRC_C) +SRC_QSTR += $(SRC_COMMON_C) $(SRC_RUN_C) $(LIB_SRC_C) all: run diff --git a/qemu-arm/mpconfigport.h b/qemu-arm/mpconfigport.h index ebec027e80..87e537af74 100644 --- a/qemu-arm/mpconfigport.h +++ b/qemu-arm/mpconfigport.h @@ -1,6 +1,6 @@ #include -// options to control how Micro Python is built +// options to control how MicroPython is built #define MICROPY_ALLOC_PATH_MAX (512) #define MICROPY_EMIT_X64 (0) diff --git a/stmhal/Makefile b/stmhal/Makefile index 2d9d44afd9..ae1db2ae95 100644 --- a/stmhal/Makefile +++ b/stmhal/Makefile @@ -48,18 +48,35 @@ INC += -I$(HAL_DIR)/inc INC += -I$(USBDEV_DIR)/core/inc -I$(USBDEV_DIR)/class/inc #INC += -I$(USBHOST_DIR) -CFLAGS_CORTEX_M = -mthumb -mfpu=fpv4-sp-d16 -mfloat-abi=hard -fsingle-precision-constant -Wdouble-promotion +# Basic Cortex-M flags +CFLAGS_CORTEX_M = -mthumb + +# Select hardware floating-point support +ifeq ($(CMSIS_MCU),$(filter $(CMSIS_MCU),STM32F767xx STM32F769xx)) +CFLAGS_CORTEX_M += -mfpu=fpv5-d16 -mfloat-abi=hard +else +CFLAGS_CORTEX_M += -mfpu=fpv4-sp-d16 -mfloat-abi=hard +endif + +# Options for particular MCU series CFLAGS_MCU_f4 = $(CFLAGS_CORTEX_M) -mtune=cortex-m4 -mcpu=cortex-m4 -DMCU_SERIES_F4 CFLAGS_MCU_f7 = $(CFLAGS_CORTEX_M) -mtune=cortex-m7 -mcpu=cortex-m7 -DMCU_SERIES_F7 CFLAGS_MCU_l4 = $(CFLAGS_CORTEX_M) -mtune=cortex-m4 -mcpu=cortex-m4 -DMCU_SERIES_L4 -CFLAGS = $(INC) -Wall -Wpointer-arith -Werror -std=gnu99 -nostdlib $(CFLAGS_MOD) +CFLAGS = $(INC) -Wall -Wpointer-arith -Werror -std=gnu99 -nostdlib $(CFLAGS_MOD) $(CFLAGS_EXTRA) CFLAGS += -D$(CMSIS_MCU) CFLAGS += $(CFLAGS_MCU_$(MCU_SERIES)) CFLAGS += $(COPT) CFLAGS += -Iboards/$(BOARD) CFLAGS += -DSTM32_HAL_H='' +ifeq ($(MICROPY_FLOAT_IMPL),double) +CFLAGS += -DMICROPY_FLOAT_IMPL=MICROPY_FLOAT_IMPL_DOUBLE +else +CFLAGS += -DMICROPY_FLOAT_IMPL=MICROPY_FLOAT_IMPL_FLOAT +CFLAGS += -fsingle-precision-constant -Wdouble-promotion +endif + LDFLAGS = -nostdlib -L $(LD_DIR) -T $(LD_FILE) -Map=$(@:.elf=.map) --cref LIBS = $(shell $(CC) $(CFLAGS) -print-libgcc-file-name) @@ -77,32 +94,6 @@ endif SRC_LIB = $(addprefix lib/,\ libc/string0.c \ - libm/math.c \ - libm/thumb_vfp_sqrtf.c \ - libm/asinfacosf.c \ - libm/atanf.c \ - libm/atan2f.c \ - libm/fmodf.c \ - libm/nearbyintf.c \ - libm/log1pf.c \ - libm/acoshf.c \ - libm/asinhf.c \ - libm/atanhf.c \ - libm/kf_rem_pio2.c \ - libm/kf_sin.c \ - libm/kf_cos.c \ - libm/kf_tan.c \ - libm/ef_rem_pio2.c \ - libm/erf_lgamma.c \ - libm/sf_sin.c \ - libm/sf_cos.c \ - libm/sf_tan.c \ - libm/sf_frexp.c \ - libm/sf_modf.c \ - libm/sf_ldexp.c \ - libm/sf_erf.c \ - libm/wf_lgamma.c \ - libm/wf_tgamma.c \ oofatfs/ff.c \ oofatfs/option/unicode.c \ mp-readline/readline.c \ @@ -110,8 +101,88 @@ SRC_LIB = $(addprefix lib/,\ timeutils/timeutils.c \ utils/pyexec.c \ utils/interrupt_char.c \ + utils/sys_stdio_mphal.c \ ) +ifeq ($(MICROPY_FLOAT_IMPL),double) +SRC_LIBM = $(addprefix lib/libm_dbl/,\ + __cos.c \ + __expo2.c \ + __fpclassify.c \ + __rem_pio2.c \ + __rem_pio2_large.c \ + __signbit.c \ + __sin.c \ + __tan.c \ + acos.c \ + acosh.c \ + asin.c \ + asinh.c \ + atan.c \ + atan2.c \ + atanh.c \ + ceil.c \ + cos.c \ + cosh.c \ + erf.c \ + exp.c \ + expm1.c \ + floor.c \ + fmod.c \ + frexp.c \ + ldexp.c \ + lgamma.c \ + log.c \ + log10.c \ + log1p.c \ + modf.c \ + nearbyint.c \ + pow.c \ + rint.c \ + scalbn.c \ + sin.c \ + sinh.c \ + sqrt.c \ + tan.c \ + tanh.c \ + tgamma.c \ + trunc.c \ + ) +else +SRC_LIBM = $(addprefix lib/libm/,\ + math.c \ + thumb_vfp_sqrtf.c \ + acoshf.c \ + asinfacosf.c \ + asinhf.c \ + atan2f.c \ + atanf.c \ + atanhf.c \ + ef_rem_pio2.c \ + erf_lgamma.c \ + fmodf.c \ + kf_cos.c \ + kf_rem_pio2.c \ + kf_sin.c \ + kf_tan.c \ + log1pf.c \ + nearbyintf.c \ + sf_cos.c \ + sf_erf.c \ + sf_frexp.c \ + sf_ldexp.c \ + sf_modf.c \ + sf_sin.c \ + sf_tan.c \ + wf_lgamma.c \ + wf_tgamma.c \ + ) +endif + +EXTMOD_SRC_C = $(addprefix extmod/,\ + modonewire.c \ + ) + DRIVERS_SRC_C = $(addprefix drivers/,\ memory/spiflash.c \ ) @@ -145,7 +216,6 @@ SRC_C = \ usb.c \ wdt.c \ gccollect.c \ - pybstdio.c \ help.c \ machine_i2c.c \ modmachine.c \ @@ -254,6 +324,8 @@ endif OBJ = OBJ += $(PY_O) OBJ += $(addprefix $(BUILD)/, $(SRC_LIB:.c=.o)) +OBJ += $(addprefix $(BUILD)/, $(SRC_LIBM:.c=.o)) +OBJ += $(addprefix $(BUILD)/, $(EXTMOD_SRC_C:.c=.o)) OBJ += $(addprefix $(BUILD)/, $(DRIVERS_SRC_C:.c=.o)) OBJ += $(addprefix $(BUILD)/, $(SRC_C:.c=.o)) OBJ += $(addprefix $(BUILD)/, $(SRC_O)) @@ -343,7 +415,7 @@ GEN_CDCINF_FILE = $(HEADER_BUILD)/pybcdc.inf GEN_CDCINF_HEADER = $(HEADER_BUILD)/pybcdc_inf.h # List of sources for qstr extraction -SRC_QSTR += $(SRC_C) $(SRC_MOD) $(SRC_LIB) +SRC_QSTR += $(SRC_C) $(SRC_MOD) $(SRC_LIB) $(EXTMOD_SRC_C) # Append any auto-generated sources that are needed by sources listed in # SRC_QSTR SRC_QSTR_AUTO_DEPS += $(GEN_CDCINF_HEADER) diff --git a/stmhal/accel.c b/stmhal/accel.c index d0d4148ab2..512a6e313a 100644 --- a/stmhal/accel.c +++ b/stmhal/accel.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -90,7 +90,7 @@ STATIC void accel_start(void) { } if (status != HAL_OK) { - nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_OSError, "accelerometer not found")); + mp_raise_msg(&mp_type_OSError, "accelerometer not found"); } // set MMA to active mode @@ -102,7 +102,7 @@ STATIC void accel_start(void) { } /******************************************************************************/ -/* Micro Python bindings */ +/* MicroPython bindings */ #define NUM_AXIS (3) #define FILT_DEPTH (4) diff --git a/stmhal/accel.h b/stmhal/accel.h index 10b095f799..fc35f77756 100644 --- a/stmhal/accel.h +++ b/stmhal/accel.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,7 +23,11 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ +#ifndef MICROPY_INCLUDED_STMHAL_ACCEL_H +#define MICROPY_INCLUDED_STMHAL_ACCEL_H extern const mp_obj_type_t pyb_accel_type; void accel_init(void); + +#endif // MICROPY_INCLUDED_STMHAL_ACCEL_H diff --git a/stmhal/adc.c b/stmhal/adc.c index 6485e2ab77..dd59e29c88 100644 --- a/stmhal/adc.c +++ b/stmhal/adc.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -263,7 +263,7 @@ STATIC uint32_t adc_read_channel(ADC_HandleTypeDef *adcHandle) { } /******************************************************************************/ -/* Micro Python bindings : adc object (single channel) */ +/* MicroPython bindings : adc object (single channel) */ STATIC void adc_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { pyb_obj_adc_t *self = self_in; @@ -596,7 +596,7 @@ float adc_read_core_vref(ADC_HandleTypeDef *adcHandle) { #endif /******************************************************************************/ -/* Micro Python bindings : adc_all object */ +/* MicroPython bindings : adc_all object */ STATIC mp_obj_t adc_all_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { // check number of arguments diff --git a/stmhal/adc.h b/stmhal/adc.h index ebaccbee3d..c90e6b3433 100644 --- a/stmhal/adc.h +++ b/stmhal/adc.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,6 +23,10 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ +#ifndef MICROPY_INCLUDED_STMHAL_ADC_H +#define MICROPY_INCLUDED_STMHAL_ADC_H extern const mp_obj_type_t pyb_adc_type; extern const mp_obj_type_t pyb_adc_all_type; + +#endif // MICROPY_INCLUDED_STMHAL_ADC_H diff --git a/stmhal/boards/ESPRUINO_PICO/mpconfigboard.h b/stmhal/boards/ESPRUINO_PICO/mpconfigboard.h index e84822957d..d065180d8a 100644 --- a/stmhal/boards/ESPRUINO_PICO/mpconfigboard.h +++ b/stmhal/boards/ESPRUINO_PICO/mpconfigboard.h @@ -1,6 +1,9 @@ #define MICROPY_HW_BOARD_NAME "Espruino Pico" #define MICROPY_HW_MCU_NAME "STM32F401CD" +#define MICROPY_EMIT_THUMB (0) +#define MICROPY_EMIT_INLINE_THUMB (0) +#define MICROPY_PY_BUILTINS_COMPLEX (0) #define MICROPY_PY_USOCKET (0) #define MICROPY_PY_NETWORK (0) diff --git a/stmhal/boards/ESPRUINO_PICO/mpconfigboard.mk b/stmhal/boards/ESPRUINO_PICO/mpconfigboard.mk index 4c44022c32..d531a594a1 100644 --- a/stmhal/boards/ESPRUINO_PICO/mpconfigboard.mk +++ b/stmhal/boards/ESPRUINO_PICO/mpconfigboard.mk @@ -2,3 +2,6 @@ MCU_SERIES = f4 CMSIS_MCU = STM32F401xE AF_FILE = boards/stm32f401_af.csv LD_FILE = boards/stm32f401xd.ld + +# Don't include default frozen modules because MCU is tight on flash space +FROZEN_MPY_DIR ?= diff --git a/stmhal/boards/LIMIFROG/mpconfigboard.h b/stmhal/boards/LIMIFROG/mpconfigboard.h index d04634ac38..42b862fcf5 100644 --- a/stmhal/boards/LIMIFROG/mpconfigboard.h +++ b/stmhal/boards/LIMIFROG/mpconfigboard.h @@ -1,5 +1,3 @@ -#include STM32_HAL_H - #define MICROPY_HW_BOARD_NAME "LIMIFROG" #define MICROPY_HW_MCU_NAME "STM32L476" diff --git a/stmhal/boards/NUCLEO_F429ZI/mpconfigboard.h b/stmhal/boards/NUCLEO_F429ZI/mpconfigboard.h new file mode 100644 index 0000000000..42cc9d68cd --- /dev/null +++ b/stmhal/boards/NUCLEO_F429ZI/mpconfigboard.h @@ -0,0 +1,83 @@ +#define MICROPY_HW_BOARD_NAME "NUCLEO-F429ZI" +#define MICROPY_HW_MCU_NAME "STM32F429" + +#define MICROPY_HW_HAS_SWITCH (1) +#define MICROPY_HW_HAS_FLASH (1) +#define MICROPY_HW_HAS_SDCARD (0) +#define MICROPY_HW_HAS_MMA7660 (0) +#define MICROPY_HW_HAS_LIS3DSH (0) +#define MICROPY_HW_HAS_LCD (0) +#define MICROPY_HW_ENABLE_RNG (1) +#define MICROPY_HW_ENABLE_RTC (1) +#define MICROPY_HW_ENABLE_TIMER (1) +#define MICROPY_HW_ENABLE_SERVO (0) +#define MICROPY_HW_ENABLE_DAC (0) +#define MICROPY_HW_ENABLE_CAN (1) + +// HSE is 8MHz +#define MICROPY_HW_CLK_PLLM (8) +#define MICROPY_HW_CLK_PLLN (180) +#define MICROPY_HW_CLK_PLLP (RCC_PLLP_DIV2) +#define MICROPY_HW_CLK_PLLQ (4) + +// From the reference manual, for 2.7V to 3.6V +// 151-180 MHz => 5 wait states +// 181-210 MHz => 6 wait states +// 211-216 MHz => 7 wait states +#define MICROPY_HW_FLASH_LATENCY FLASH_LATENCY_6 + +// UART config +#define MICROPY_HW_UART1_TX (pin_A9) +#define MICROPY_HW_UART1_RX (pin_A10) + +#define MICROPY_HW_UART2_TX (pin_D5) +#define MICROPY_HW_UART2_RX (pin_D6) + +#define MICROPY_HW_UART3_TX (pin_D8) +#define MICROPY_HW_UART3_RX (pin_D9) + +#define MICROPY_HW_UART4_TX (pin_A0) +#define MICROPY_HW_UART4_RX (pin_C11) + +#define MICROPY_HW_UART5_TX (pin_C12) +#define MICROPY_HW_UART5_RX (pin_D2) + +#define MICROPY_HW_UART_REPL PYB_UART_3 +#define MICROPY_HW_UART_REPL_BAUD 115200 + +// I2C busses +#define MICROPY_HW_I2C3_SCL (pin_A8) +#define MICROPY_HW_I2C3_SDA (pin_C9) + +// SPI busses +#define MICROPY_HW_SPI1_NSS (pin_A4) +#define MICROPY_HW_SPI1_SCK (pin_B3) +#define MICROPY_HW_SPI1_MISO (pin_B4) +#define MICROPY_HW_SPI1_MOSI (pin_B5) + +#define MICROPY_HW_SPI4_NSS (pin_E4) +#define MICROPY_HW_SPI4_SCK (pin_E2) +#define MICROPY_HW_SPI4_MISO (pin_E5) +#define MICROPY_HW_SPI4_MOSI (pin_E6) + +#define MICROPY_HW_SPI5_NSS (pin_F6) +#define MICROPY_HW_SPI5_SCK (pin_F7) +#define MICROPY_HW_SPI5_MISO (pin_F8) +#define MICROPY_HW_SPI5_MOSI (pin_F9) + +// USRSW is pulled low. Pressing the button makes the input go high. +#define MICROPY_HW_USRSW_PIN (pin_C13) +#define MICROPY_HW_USRSW_PULL (GPIO_NOPULL) +#define MICROPY_HW_USRSW_EXTI_MODE (GPIO_MODE_IT_RISING) +#define MICROPY_HW_USRSW_PRESSED (1) + +// LEDs +#define MICROPY_HW_LED1 (pin_B0) // green +#define MICROPY_HW_LED2 (pin_B7) // blue +#define MICROPY_HW_LED3 (pin_B14) // red +#define MICROPY_HW_LED_ON(pin) (mp_hal_pin_high(pin)) +#define MICROPY_HW_LED_OFF(pin) (mp_hal_pin_low(pin)) + +// USB config (CN13 - USB OTG FS) +#define MICROPY_HW_USB_VBUS_DETECT_PIN (pin_A9) +#define MICROPY_HW_USB_OTG_ID_PIN (pin_A10) diff --git a/stmhal/boards/NUCLEO_F429ZI/mpconfigboard.mk b/stmhal/boards/NUCLEO_F429ZI/mpconfigboard.mk new file mode 100644 index 0000000000..1bbf808b69 --- /dev/null +++ b/stmhal/boards/NUCLEO_F429ZI/mpconfigboard.mk @@ -0,0 +1,4 @@ +MCU_SERIES = f4 +CMSIS_MCU = STM32F429xx +AF_FILE = boards/stm32f429_af.csv +LD_FILE = boards/stm32f429.ld diff --git a/stmhal/boards/NUCLEO_F429ZI/pins.csv b/stmhal/boards/NUCLEO_F429ZI/pins.csv new file mode 100644 index 0000000000..8a892d3c2f --- /dev/null +++ b/stmhal/boards/NUCLEO_F429ZI/pins.csv @@ -0,0 +1,117 @@ +PF4,PF4 +PF5,PF5 +PF2,PF2 +PF3,PF3 +PF0,PF0 +PF1,PF1 +PC14,PC14 +PC15,PC15 +PE6,PE6 +PC13,PC13 +PE4,PE4 +PE5,PE5 +PE2,PE2 +PE3,PE3 +PE0,PE0 +PE1,PE1 +PB8,PB8 +PB9,PB9 +PB6,PB6 +PB7,PB7 +PB4,PB4 +PB5,PB5 +PG15,PG15 +PB3,PB3 +PG13,PG13 +PG14,PG14 +PG11,PG11 +PG12,PG12 +PG9,PG9 +PG10,PG10 +PD7,PD7 +PD6,PD6 +PD5,PD5 +PD4,PD4 +PD3,PD3 +PD2,PD2 +PD1,PD1 +PD0,PD0 +PC12,PC12 +PC11,PC11 +PC10,PC10 +PA15,PA15 +PA14,PA14 +PA13,PA13 +PA12,PA12 +PA11,PA11 +PA10,PA10 +PA9,PA9 +PA8,PA8 +PC9,PC9 +PC8,PC8 +PC7,PC7 +PC6,PC6 +PG8,PG8 +PG7,PG7 +PG6,PG6 +PG5,PG5 +PG4,PG4 +PF6,PF6 +PF8,PF8 +PF7,PF7 +PF10,PF10 +PF9,PF9 +PH1,PH1 +PH0,PH0 +PC1,PC1 +PC0,PC0 +PC3,PC3 +PC2,PC2 +PA1,PA1 +PA0,PA0 +PA3,PA3 +PA2,PA2 +PA5,PA5 +PA4,PA4 +PA7,PA7 +PA6,PA6 +PC5,PC5 +PC4,PC4 +PB1,PB1 +PB0,PB0 +PB2,PB2 +PF12,PF12 +PF11,PF11 +PF14,PF14 +PF13,PF13 +PG0,PG0 +PF15,PF15 +PE7,PE7 +PG1,PG1 +PE9,PE9 +PE8,PE8 +PE11,PE11 +PE10,PE10 +PE13,PE13 +PE12,PE12 +PE15,PE15 +PE14,PE14 +PB11,PB11 +PB10,PB10 +PB13,PB13 +PB12,PB12 +PB15,PB15 +PB14,PB14 +PD9,PD9 +PD8,PD8 +PD11,PD11 +PD10,PD10 +PD13,PD13 +PD12,PD12 +PD15,PD15 +PD14,PD14 +PG3,PG3 +PG2,PG2 +SW,PA0 +LED_GREEN,PG13 +LED_RED,PG14 diff --git a/stmhal/boards/NUCLEO_F429ZI/stm32f4xx_hal_conf.h b/stmhal/boards/NUCLEO_F429ZI/stm32f4xx_hal_conf.h new file mode 100644 index 0000000000..d121b18c5e --- /dev/null +++ b/stmhal/boards/NUCLEO_F429ZI/stm32f4xx_hal_conf.h @@ -0,0 +1,411 @@ +/** + ****************************************************************************** + * @file stm32f4xx_hal_conf.h + * @author MCD Application Team + * @version V1.1.0 + * @date 19-June-2014 + * @brief HAL configuration file. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32F4xx_HAL_CONF_H +#define __STM32F4xx_HAL_CONF_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Exported types ------------------------------------------------------------*/ +/* Exported constants --------------------------------------------------------*/ + +#define USE_USB_FS + + /* ########################## Module Selection ############################## */ +/** + * @brief This is the list of modules to be used in the HAL driver + */ +#define HAL_MODULE_ENABLED +#define HAL_ADC_MODULE_ENABLED +#define HAL_CAN_MODULE_ENABLED +/* #define HAL_CRC_MODULE_ENABLED */ +/* #define HAL_CRYP_MODULE_ENABLED */ +#define HAL_DAC_MODULE_ENABLED +/* #define HAL_DCMI_MODULE_ENABLED */ +#define HAL_DMA_MODULE_ENABLED +/* #define HAL_DMA2D_MODULE_ENABLED */ +/* #define HAL_ETH_MODULE_ENABLED */ +#define HAL_FLASH_MODULE_ENABLED +/* #define HAL_NAND_MODULE_ENABLED */ +/* #define HAL_NOR_MODULE_ENABLED */ +/* #define HAL_PCCARD_MODULE_ENABLED */ +/* #define HAL_SRAM_MODULE_ENABLED */ +/* #define HAL_SDRAM_MODULE_ENABLED */ +/* #define HAL_HASH_MODULE_ENABLED */ +#define HAL_GPIO_MODULE_ENABLED +#define HAL_I2C_MODULE_ENABLED +/* #define HAL_I2S_MODULE_ENABLED */ +/* #define HAL_IWDG_MODULE_ENABLED */ +/* #define HAL_LTDC_MODULE_ENABLED */ +#define HAL_PWR_MODULE_ENABLED +#define HAL_RCC_MODULE_ENABLED +#define HAL_RNG_MODULE_ENABLED +#define HAL_RTC_MODULE_ENABLED +/* #define HAL_SAI_MODULE_ENABLED */ +#define HAL_SD_MODULE_ENABLED +#define HAL_SPI_MODULE_ENABLED +#define HAL_TIM_MODULE_ENABLED +#define HAL_UART_MODULE_ENABLED +/* #define HAL_USART_MODULE_ENABLED */ +/* #define HAL_IRDA_MODULE_ENABLED */ +/* #define HAL_SMARTCARD_MODULE_ENABLED */ +/* #define HAL_WWDG_MODULE_ENABLED */ +#define HAL_CORTEX_MODULE_ENABLED +#define HAL_PCD_MODULE_ENABLED +/* #define HAL_HCD_MODULE_ENABLED */ + + +/* ########################## HSE/HSI Values adaptation ##################### */ +/** + * @brief Adjust the value of External High Speed oscillator (HSE) used in your application. + * This value is used by the RCC HAL module to compute the system frequency + * (when HSE is used as system clock source, directly or through the PLL). + */ +#if !defined (HSE_VALUE) + #define HSE_VALUE ((uint32_t)8000000) /*!< Value of the External oscillator in Hz */ +#endif /* HSE_VALUE */ + +#if !defined (HSE_STARTUP_TIMEOUT) + #define HSE_STARTUP_TIMEOUT ((uint32_t)100U) /*!< Time out for HSE start up, in ms */ +#endif /* HSE_STARTUP_TIMEOUT */ + +/** + * @brief Internal High Speed oscillator (HSI) value. + * This value is used by the RCC HAL module to compute the system frequency + * (when HSI is used as system clock source, directly or through the PLL). + */ +#if !defined (HSI_VALUE) + #define HSI_VALUE ((uint32_t)16000000) /*!< Value of the Internal oscillator in Hz*/ +#endif /* HSI_VALUE */ + +/** + * @brief Internal Low Speed oscillator (LSI) value. + */ +#if !defined (LSI_VALUE) + #define LSI_VALUE ((uint32_t)40000) +#endif /* LSI_VALUE */ /*!< Value of the Internal Low Speed oscillator in Hz + The real value may vary depending on the variations + in voltage and temperature. */ +/** + * @brief External Low Speed oscillator (LSE) value. + */ +#if !defined (LSE_VALUE) + #define LSE_VALUE ((uint32_t)32768) /*!< Value of the External Low Speed oscillator in Hz */ +#endif /* LSE_VALUE */ + +#if !defined (LSE_STARTUP_TIMEOUT) + #define LSE_STARTUP_TIMEOUT ((uint32_t)5000U) /*!< Time out for LSE start up, in ms */ +#endif /* LSE_STARTUP_TIMEOUT */ + +/** + * @brief External clock source for I2S peripheral + * This value is used by the I2S HAL module to compute the I2S clock source + * frequency, this source is inserted directly through I2S_CKIN pad. + */ +#if !defined (EXTERNAL_CLOCK_VALUE) + #define EXTERNAL_CLOCK_VALUE ((uint32_t)12288000) /*!< Value of the Internal oscillator in Hz*/ +#endif /* EXTERNAL_CLOCK_VALUE */ + +/* Tip: To avoid modifying this file each time you need to use different HSE, + === you can define the HSE value in your toolchain compiler preprocessor. */ + +/* ########################### System Configuration ######################### */ +/** + * @brief This is the HAL system configuration section + */ +#define VDD_VALUE ((uint32_t)3300) /*!< Value of VDD in mv */ +#define TICK_INT_PRIORITY ((uint32_t)0x00) /*!< tick interrupt priority */ +#define USE_RTOS 0 +#define PREFETCH_ENABLE 1 +#define INSTRUCTION_CACHE_ENABLE 1 +#define DATA_CACHE_ENABLE 1 + +/* ########################## Assert Selection ############################## */ +/** + * @brief Uncomment the line below to expanse the "assert_param" macro in the + * HAL drivers code + */ +/* #define USE_FULL_ASSERT 1 */ + +/* ################## Ethernet peripheral configuration ##################### */ + +/* Section 1 : Ethernet peripheral configuration */ + +/* MAC ADDRESS: MAC_ADDR0:MAC_ADDR1:MAC_ADDR2:MAC_ADDR3:MAC_ADDR4:MAC_ADDR5 */ +#define MAC_ADDR0 2 +#define MAC_ADDR1 0 +#define MAC_ADDR2 0 +#define MAC_ADDR3 0 +#define MAC_ADDR4 0 +#define MAC_ADDR5 0 + +/* Definition of the Ethernet driver buffers size and count */ +#define ETH_RX_BUF_SIZE ETH_MAX_PACKET_SIZE /* buffer size for receive */ +#define ETH_TX_BUF_SIZE ETH_MAX_PACKET_SIZE /* buffer size for transmit */ +#define ETH_RXBUFNB ((uint32_t)4) /* 4 Rx buffers of size ETH_RX_BUF_SIZE */ +#define ETH_TXBUFNB ((uint32_t)4) /* 4 Tx buffers of size ETH_TX_BUF_SIZE */ + +/* Section 2: PHY configuration section */ + +/* DP83848 PHY Address*/ +#define DP83848_PHY_ADDRESS 0x01 +/* PHY Reset delay these values are based on a 1 ms Systick interrupt*/ +#define PHY_RESET_DELAY ((uint32_t)0x000000FF) +/* PHY Configuration delay */ +#define PHY_CONFIG_DELAY ((uint32_t)0x00000FFF) + +#define PHY_READ_TO ((uint32_t)0x0000FFFF) +#define PHY_WRITE_TO ((uint32_t)0x0000FFFF) + +/* Section 3: Common PHY Registers */ + +#define PHY_BCR ((uint16_t)0x00) /*!< Transceiver Basic Control Register */ +#define PHY_BSR ((uint16_t)0x01) /*!< Transceiver Basic Status Register */ + +#define PHY_RESET ((uint16_t)0x8000) /*!< PHY Reset */ +#define PHY_LOOPBACK ((uint16_t)0x4000) /*!< Select loop-back mode */ +#define PHY_FULLDUPLEX_100M ((uint16_t)0x2100) /*!< Set the full-duplex mode at 100 Mb/s */ +#define PHY_HALFDUPLEX_100M ((uint16_t)0x2000) /*!< Set the half-duplex mode at 100 Mb/s */ +#define PHY_FULLDUPLEX_10M ((uint16_t)0x0100) /*!< Set the full-duplex mode at 10 Mb/s */ +#define PHY_HALFDUPLEX_10M ((uint16_t)0x0000) /*!< Set the half-duplex mode at 10 Mb/s */ +#define PHY_AUTONEGOTIATION ((uint16_t)0x1000) /*!< Enable auto-negotiation function */ +#define PHY_RESTART_AUTONEGOTIATION ((uint16_t)0x0200) /*!< Restart auto-negotiation function */ +#define PHY_POWERDOWN ((uint16_t)0x0800) /*!< Select the power down mode */ +#define PHY_ISOLATE ((uint16_t)0x0400) /*!< Isolate PHY from MII */ + +#define PHY_AUTONEGO_COMPLETE ((uint16_t)0x0020) /*!< Auto-Negotiation process completed */ +#define PHY_LINKED_STATUS ((uint16_t)0x0004) /*!< Valid link established */ +#define PHY_JABBER_DETECTION ((uint16_t)0x0002) /*!< Jabber condition detected */ + +/* Section 4: Extended PHY Registers */ + +#define PHY_SR ((uint16_t)0x10) /*!< PHY status register Offset */ +#define PHY_MICR ((uint16_t)0x11) /*!< MII Interrupt Control Register */ +#define PHY_MISR ((uint16_t)0x12) /*!< MII Interrupt Status and Misc. Control Register */ + +#define PHY_LINK_STATUS ((uint16_t)0x0001) /*!< PHY Link mask */ +#define PHY_SPEED_STATUS ((uint16_t)0x0002) /*!< PHY Speed mask */ +#define PHY_DUPLEX_STATUS ((uint16_t)0x0004) /*!< PHY Duplex mask */ + +#define PHY_MICR_INT_EN ((uint16_t)0x0002) /*!< PHY Enable interrupts */ +#define PHY_MICR_INT_OE ((uint16_t)0x0001) /*!< PHY Enable output interrupt events */ + +#define PHY_MISR_LINK_INT_EN ((uint16_t)0x0020) /*!< Enable Interrupt on change of link status */ +#define PHY_LINK_INTERRUPT ((uint16_t)0x2000) /*!< PHY link status interrupt mask */ + +/* Includes ------------------------------------------------------------------*/ +/** + * @brief Include module's header file + */ + +#ifdef HAL_RCC_MODULE_ENABLED + #include "stm32f4xx_hal_rcc.h" +#endif /* HAL_RCC_MODULE_ENABLED */ + +#ifdef HAL_GPIO_MODULE_ENABLED + #include "stm32f4xx_hal_gpio.h" +#endif /* HAL_GPIO_MODULE_ENABLED */ + +#ifdef HAL_DMA_MODULE_ENABLED + #include "stm32f4xx_hal_dma.h" +#endif /* HAL_DMA_MODULE_ENABLED */ + +#ifdef HAL_CORTEX_MODULE_ENABLED + #include "stm32f4xx_hal_cortex.h" +#endif /* HAL_CORTEX_MODULE_ENABLED */ + +#ifdef HAL_ADC_MODULE_ENABLED + #include "stm32f4xx_hal_adc.h" +#endif /* HAL_ADC_MODULE_ENABLED */ + +#ifdef HAL_CAN_MODULE_ENABLED + #include "stm32f4xx_hal_can.h" +#endif /* HAL_CAN_MODULE_ENABLED */ + +#ifdef HAL_CRC_MODULE_ENABLED + #include "stm32f4xx_hal_crc.h" +#endif /* HAL_CRC_MODULE_ENABLED */ + +#ifdef HAL_CRYP_MODULE_ENABLED + #include "stm32f4xx_hal_cryp.h" +#endif /* HAL_CRYP_MODULE_ENABLED */ + +#ifdef HAL_DMA2D_MODULE_ENABLED + #include "stm32f4xx_hal_dma2d.h" +#endif /* HAL_DMA2D_MODULE_ENABLED */ + +#ifdef HAL_DAC_MODULE_ENABLED + #include "stm32f4xx_hal_dac.h" +#endif /* HAL_DAC_MODULE_ENABLED */ + +#ifdef HAL_DCMI_MODULE_ENABLED + #include "stm32f4xx_hal_dcmi.h" +#endif /* HAL_DCMI_MODULE_ENABLED */ + +#ifdef HAL_ETH_MODULE_ENABLED + #include "stm32f4xx_hal_eth.h" +#endif /* HAL_ETH_MODULE_ENABLED */ + +#ifdef HAL_FLASH_MODULE_ENABLED + #include "stm32f4xx_hal_flash.h" +#endif /* HAL_FLASH_MODULE_ENABLED */ + +#ifdef HAL_SRAM_MODULE_ENABLED + #include "stm32f4xx_hal_sram.h" +#endif /* HAL_SRAM_MODULE_ENABLED */ + +#ifdef HAL_NOR_MODULE_ENABLED + #include "stm32f4xx_hal_nor.h" +#endif /* HAL_NOR_MODULE_ENABLED */ + +#ifdef HAL_NAND_MODULE_ENABLED + #include "stm32f4xx_hal_nand.h" +#endif /* HAL_NAND_MODULE_ENABLED */ + +#ifdef HAL_PCCARD_MODULE_ENABLED + #include "stm32f4xx_hal_pccard.h" +#endif /* HAL_PCCARD_MODULE_ENABLED */ + +#ifdef HAL_SDRAM_MODULE_ENABLED + #include "stm32f4xx_hal_sdram.h" +#endif /* HAL_SDRAM_MODULE_ENABLED */ + +#ifdef HAL_HASH_MODULE_ENABLED + #include "stm32f4xx_hal_hash.h" +#endif /* HAL_HASH_MODULE_ENABLED */ + +#ifdef HAL_I2C_MODULE_ENABLED + #include "stm32f4xx_hal_i2c.h" +#endif /* HAL_I2C_MODULE_ENABLED */ + +#ifdef HAL_I2S_MODULE_ENABLED + #include "stm32f4xx_hal_i2s.h" +#endif /* HAL_I2S_MODULE_ENABLED */ + +#ifdef HAL_IWDG_MODULE_ENABLED + #include "stm32f4xx_hal_iwdg.h" +#endif /* HAL_IWDG_MODULE_ENABLED */ + +#ifdef HAL_LTDC_MODULE_ENABLED + #include "stm32f4xx_hal_ltdc.h" +#endif /* HAL_LTDC_MODULE_ENABLED */ + +#ifdef HAL_PWR_MODULE_ENABLED + #include "stm32f4xx_hal_pwr.h" +#endif /* HAL_PWR_MODULE_ENABLED */ + +#ifdef HAL_RNG_MODULE_ENABLED + #include "stm32f4xx_hal_rng.h" +#endif /* HAL_RNG_MODULE_ENABLED */ + +#ifdef HAL_RTC_MODULE_ENABLED + #include "stm32f4xx_hal_rtc.h" +#endif /* HAL_RTC_MODULE_ENABLED */ + +#ifdef HAL_SAI_MODULE_ENABLED + #include "stm32f4xx_hal_sai.h" +#endif /* HAL_SAI_MODULE_ENABLED */ + +#ifdef HAL_SD_MODULE_ENABLED + #include "stm32f4xx_hal_sd.h" +#endif /* HAL_SD_MODULE_ENABLED */ + +#ifdef HAL_SPI_MODULE_ENABLED + #include "stm32f4xx_hal_spi.h" +#endif /* HAL_SPI_MODULE_ENABLED */ + +#ifdef HAL_TIM_MODULE_ENABLED + #include "stm32f4xx_hal_tim.h" +#endif /* HAL_TIM_MODULE_ENABLED */ + +#ifdef HAL_UART_MODULE_ENABLED + #include "stm32f4xx_hal_uart.h" +#endif /* HAL_UART_MODULE_ENABLED */ + +#ifdef HAL_USART_MODULE_ENABLED + #include "stm32f4xx_hal_usart.h" +#endif /* HAL_USART_MODULE_ENABLED */ + +#ifdef HAL_IRDA_MODULE_ENABLED + #include "stm32f4xx_hal_irda.h" +#endif /* HAL_IRDA_MODULE_ENABLED */ + +#ifdef HAL_SMARTCARD_MODULE_ENABLED + #include "stm32f4xx_hal_smartcard.h" +#endif /* HAL_SMARTCARD_MODULE_ENABLED */ + +#ifdef HAL_WWDG_MODULE_ENABLED + #include "stm32f4xx_hal_wwdg.h" +#endif /* HAL_WWDG_MODULE_ENABLED */ + +#ifdef HAL_PCD_MODULE_ENABLED + #include "stm32f4xx_hal_pcd.h" +#endif /* HAL_PCD_MODULE_ENABLED */ + +#ifdef HAL_HCD_MODULE_ENABLED + #include "stm32f4xx_hal_hcd.h" +#endif /* HAL_HCD_MODULE_ENABLED */ + +/* Exported macro ------------------------------------------------------------*/ +#ifdef USE_FULL_ASSERT +/** + * @brief The assert_param macro is used for function's parameters check. + * @param expr: If expr is false, it calls assert_failed function + * which reports the name of the source file and the source + * line number of the call that failed. + * If expr is true, it returns no value. + * @retval None + */ + #define assert_param(expr) ((expr) ? (void)0 : assert_failed((uint8_t *)__FILE__, __LINE__)) +/* Exported functions ------------------------------------------------------- */ + void assert_failed(uint8_t* file, uint32_t line); +#else + #define assert_param(expr) ((void)0) +#endif /* USE_FULL_ASSERT */ + + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32F4xx_HAL_CONF_H */ + + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/stmhal/boards/NUCLEO_F767ZI/mpconfigboard.mk b/stmhal/boards/NUCLEO_F767ZI/mpconfigboard.mk index f704f4ee9a..ba28a16e1e 100644 --- a/stmhal/boards/NUCLEO_F767ZI/mpconfigboard.mk +++ b/stmhal/boards/NUCLEO_F767ZI/mpconfigboard.mk @@ -1,4 +1,5 @@ MCU_SERIES = f7 CMSIS_MCU = STM32F767xx +MICROPY_FLOAT_IMPL = double AF_FILE = boards/stm32f767_af.csv LD_FILE = boards/stm32f767.ld diff --git a/stmhal/boards/STM32F429DISC/mpconfigboard.h b/stmhal/boards/STM32F429DISC/mpconfigboard.h index a8e379020c..fc07020252 100644 --- a/stmhal/boards/STM32F429DISC/mpconfigboard.h +++ b/stmhal/boards/STM32F429DISC/mpconfigboard.h @@ -1,5 +1,3 @@ -#include STM32_HAL_H - #define MICROPY_HW_BOARD_NAME "F429I-DISCO" #define MICROPY_HW_MCU_NAME "STM32F429" diff --git a/stmhal/boards/STM32F769DISC/mpconfigboard.mk b/stmhal/boards/STM32F769DISC/mpconfigboard.mk index b65a18afb2..99234e4cf1 100644 --- a/stmhal/boards/STM32F769DISC/mpconfigboard.mk +++ b/stmhal/boards/STM32F769DISC/mpconfigboard.mk @@ -1,4 +1,5 @@ MCU_SERIES = f7 CMSIS_MCU = STM32F769xx +MICROPY_FLOAT_IMPL = double AF_FILE = boards/stm32f767_af.csv LD_FILE = boards/stm32f769.ld diff --git a/stmhal/boards/STM32L476DISC/mpconfigboard.h b/stmhal/boards/STM32L476DISC/mpconfigboard.h index 258a86b606..9dbadd5300 100644 --- a/stmhal/boards/STM32L476DISC/mpconfigboard.h +++ b/stmhal/boards/STM32L476DISC/mpconfigboard.h @@ -1,5 +1,3 @@ -#include STM32_HAL_H - #define MICROPY_BOARD_EARLY_INIT STM32L476DISC_board_early_init void STM32L476DISC_board_early_init(void); diff --git a/stmhal/boards/common.ld b/stmhal/boards/common.ld index fcae1b4c6e..e5dea49d08 100644 --- a/stmhal/boards/common.ld +++ b/stmhal/boards/common.ld @@ -27,7 +27,7 @@ SECTIONS . = ALIGN(4); } >FLASH_ISR - + /* The program code and other data goes into FLASH */ .text : { @@ -40,10 +40,10 @@ SECTIONS . = ALIGN(4); _etext = .; /* define a global symbol at end of code */ } >FLASH_TEXT - + /* used by the startup to initialize data */ _sidata = LOADADDR(.data); - + /* This is the initialized data section The program executes knowing that the data is in the RAM but the loader puts the initial values in the FLASH (inidata). @@ -51,13 +51,13 @@ SECTIONS .data : { . = ALIGN(4); - _sdata = .; /* create a global symbol at data start; used by startup code in order to initialise the .data section in RAM */ + _sdata = .; /* create a global symbol at data start; used by startup code in order to initialise the .data section in RAM */ *(.data*) /* .data* sections */ . = ALIGN(4); _edata = .; /* define a global symbol at data end; used by startup code in order to initialise the .data section in RAM */ } >RAM AT> FLASH_TEXT - + /* Uninitialized data section */ .bss : { diff --git a/stmhal/boards/stm32f401xd.ld b/stmhal/boards/stm32f401xd.ld index 53aa83d53b..415c258496 100644 --- a/stmhal/boards/stm32f401xd.ld +++ b/stmhal/boards/stm32f401xd.ld @@ -15,7 +15,7 @@ MEMORY /* produce a link error if there is not this amount of RAM for these sections */ _minimum_stack_size = 2K; _minimum_heap_size = 16K; - + /* Define tho top end of the stack. The stack is full descending so begins just above last byte of RAM. Note that EABI requires the stack to be 8-byte aligned for a call. */ diff --git a/stmhal/boards/stm32f401xe.ld b/stmhal/boards/stm32f401xe.ld index a91eee0798..a2e693b491 100644 --- a/stmhal/boards/stm32f401xe.ld +++ b/stmhal/boards/stm32f401xe.ld @@ -15,7 +15,7 @@ MEMORY /* produce a link error if there is not this amount of RAM for these sections */ _minimum_stack_size = 2K; _minimum_heap_size = 16K; - + /* Define tho top end of the stack. The stack is full descending so begins just above last byte of RAM. Note that EABI requires the stack to be 8-byte aligned for a call. */ diff --git a/stmhal/boards/stm32f405.ld b/stmhal/boards/stm32f405.ld index 51be4538ad..c6107913f2 100644 --- a/stmhal/boards/stm32f405.ld +++ b/stmhal/boards/stm32f405.ld @@ -5,17 +5,18 @@ /* Specify the memory areas */ MEMORY { - FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 0x100000 /* entire flash, 1 MiB */ - FLASH_ISR (rx) : ORIGIN = 0x08000000, LENGTH = 0x004000 /* sector 0, 16 KiB */ - FLASH_TEXT (rx) : ORIGIN = 0x08020000, LENGTH = 0x080000 /* sectors 5,6,7,8, 4*128KiB = 512 KiB (could increase it more) */ - CCMRAM (xrw) : ORIGIN = 0x10000000, LENGTH = 0x010000 /* 64 KiB */ - RAM (xrw) : ORIGIN = 0x20000000, LENGTH = 0x020000 /* 128 KiB */ + FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 1024K /* entire flash */ + FLASH_ISR (rx) : ORIGIN = 0x08000000, LENGTH = 16K /* sector 0 */ + FLASH_FS (rx) : ORIGIN = 0x08004000, LENGTH = 112K /* sectors 1,2,3,4 are for filesystem */ + FLASH_TEXT (rx) : ORIGIN = 0x08020000, LENGTH = 896K /* sectors 5,6,7,8,9,10,11 */ + CCMRAM (xrw) : ORIGIN = 0x10000000, LENGTH = 64K + RAM (xrw) : ORIGIN = 0x20000000, LENGTH = 128K } /* produce a link error if there is not this amount of RAM for these sections */ _minimum_stack_size = 2K; _minimum_heap_size = 16K; - + /* Define tho top end of the stack. The stack is full descending so begins just above last byte of RAM. Note that EABI requires the stack to be 8-byte aligned for a call. */ diff --git a/stmhal/boards/stm32f411.ld b/stmhal/boards/stm32f411.ld index 0b7bcb553c..d156e852a0 100644 --- a/stmhal/boards/stm32f411.ld +++ b/stmhal/boards/stm32f411.ld @@ -11,11 +11,11 @@ MEMORY FLASH_TEXT (rx) : ORIGIN = 0x08020000, LENGTH = 0x060000 /* sectors 5,6,7 3*128KiB = 384 KiB */ RAM (xrw) : ORIGIN = 0x20000000, LENGTH = 0x020000 /* 128 KiB */ } - + /* produce a link error if there is not this amount of RAM for these sections */ _minimum_stack_size = 2K; _minimum_heap_size = 16K; - + /* Define tho top end of the stack. The stack is full descending so begins just above last byte of RAM. Note that EABI requires the stack to be 8-byte aligned for a call. */ diff --git a/stmhal/boards/stm32f429.ld b/stmhal/boards/stm32f429.ld index 0feb5bd621..f358233a60 100644 --- a/stmhal/boards/stm32f429.ld +++ b/stmhal/boards/stm32f429.ld @@ -4,18 +4,18 @@ /* Specify the memory areas */ MEMORY -{ +{ FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 0x0200000 /* entire flash, 2048 KiB */ FLASH_ISR (rx) : ORIGIN = 0x08000000, LENGTH = 0x0004000 /* sector 0, 16 KiB */ FLASH_TEXT (rx) : ORIGIN = 0x08020000, LENGTH = 0x0088000 /* sectors 5,6,7,8, 4*128KiB = 512 KiB (could increase it more) */ RAM (xrw) : ORIGIN = 0x20000000, LENGTH = 0x0030000 /* 192 KiB */ SDRAM(xrw) : ORIGIN = 0xC0000000, LENGTH = 0x0800000 /* 8 MByte */ } - + /* produce a link error if there is not this amount of RAM for these sections */ _minimum_stack_size = 2K; _minimum_heap_size = 16K; - + /* Define tho top end of the stack. The stack is full descending so begins just above last byte of RAM. Note that EABI requires the stack to be 8-byte aligned for a call. */ diff --git a/stmhal/boards/stm32l476xe.ld b/stmhal/boards/stm32l476xe.ld index 114158d8c8..bb9895d2a7 100644 --- a/stmhal/boards/stm32l476xe.ld +++ b/stmhal/boards/stm32l476xe.ld @@ -4,7 +4,7 @@ /* Specify the memory areas */ MEMORY -{ +{ FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 512K FLASH_ISR (rx) : ORIGIN = 0x08000000, LENGTH = 0x0004000 /* sectors 0-7, 16 KiB */ FLASH_TEXT (rx) : ORIGIN = 0x08004000, LENGTH = 0x005C000 /* sectors 8-191, 368 KiB */ @@ -16,7 +16,7 @@ MEMORY /* produce a link error if there is not this amount of RAM for these sections */ _minimum_stack_size = 2K; _minimum_heap_size = 16K; - + /* Define the top end of the stack. The stack is full descending so begins just above last byte of RAM. Note that EABI requires the stack to be 8-byte aligned for a call. */ diff --git a/stmhal/boards/stm32l476xg.ld b/stmhal/boards/stm32l476xg.ld index b9c29d624d..684078c430 100644 --- a/stmhal/boards/stm32l476xg.ld +++ b/stmhal/boards/stm32l476xg.ld @@ -4,7 +4,7 @@ /* Specify the memory areas */ MEMORY -{ +{ FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 1024K FLASH_ISR (rx) : ORIGIN = 0x08000000, LENGTH = 0x0004000 /* sectors 0-7, 16 KiB */ FLASH_TEXT (rx) : ORIGIN = 0x08004000, LENGTH = 0x007C000 /* sectors 8-255, 496 KiB */ @@ -18,7 +18,7 @@ ENTRY(Reset_Handler) /* produce a link error if there is not this amount of RAM for these sections */ _minimum_stack_size = 2K; _minimum_heap_size = 16K; - + /* Define the top end of the stack. The stack is full descending so begins just above last byte of RAM. Note that EABI requires the stack to be 8-byte aligned for a call. */ diff --git a/stmhal/bufhelper.c b/stmhal/bufhelper.c index ca76e9496d..79511969b7 100644 --- a/stmhal/bufhelper.c +++ b/stmhal/bufhelper.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/stmhal/bufhelper.h b/stmhal/bufhelper.h index abdeea6a80..c1967bf430 100644 --- a/stmhal/bufhelper.h +++ b/stmhal/bufhelper.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,6 +23,10 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ +#ifndef MICROPY_INCLUDED_STMHAL_BUFHELPER_H +#define MICROPY_INCLUDED_STMHAL_BUFHELPER_H void pyb_buf_get_for_send(mp_obj_t o, mp_buffer_info_t *bufinfo, byte *tmp_data); mp_obj_t pyb_buf_get_for_recv(mp_obj_t o, vstr_t *vstr); + +#endif // MICROPY_INCLUDED_STMHAL_BUFHELPER_H diff --git a/stmhal/can.c b/stmhal/can.c index fe52d8678e..9047e78ca6 100644 --- a/stmhal/can.c +++ b/stmhal/can.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -262,7 +262,7 @@ STATIC HAL_StatusTypeDef CAN_Transmit(CAN_HandleTypeDef *hcan, uint32_t Timeout) } /******************************************************************************/ -// Micro Python bindings +// MicroPython bindings STATIC void pyb_can_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { pyb_can_obj_t *self = self_in; @@ -321,7 +321,7 @@ STATIC mp_obj_t pyb_can_init_helper(pyb_can_obj_t *self, mp_uint_t n_args, const // init CAN (if it fails, it's because the port doesn't exist) if (!can_init(self)) { - nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "CAN port %d does not exist", self->can_id)); + nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "CAN(%d) doesn't exist", self->can_id)); } return mp_const_none; @@ -357,13 +357,13 @@ STATIC mp_obj_t pyb_can_make_new(const mp_obj_type_t *type, size_t n_args, size_ can_idx = PYB_CAN_2; #endif } else { - nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "CAN(%s) does not exist", port)); + nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "CAN(%s) doesn't exist", port)); } } else { can_idx = mp_obj_get_int(args[0]); } if (can_idx < 1 || can_idx > MP_ARRAY_SIZE(MP_STATE_PORT(pyb_can_obj_all))) { - nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "CAN(%d) does not exist", can_idx)); + nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "CAN(%d) doesn't exist", can_idx)); } pyb_can_obj_t *self; @@ -473,7 +473,7 @@ STATIC mp_obj_t pyb_can_send(mp_uint_t n_args, const mp_obj_t *pos_args, mp_map_ pyb_buf_get_for_send(args[0].u_obj, &bufinfo, data); if (bufinfo.len > 8) { - nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "CAN data field too long")); + mp_raise_ValueError("CAN data field too long"); } // send the data @@ -738,7 +738,7 @@ STATIC mp_obj_t pyb_can_setfilter(mp_uint_t n_args, const mp_obj_t *pos_args, mp return mp_const_none; error: - nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "CAN filter parameter error")); + mp_raise_ValueError("CAN filter parameter error"); } STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_can_setfilter_obj, 1, pyb_can_setfilter); diff --git a/stmhal/can.h b/stmhal/can.h index 4d4b1bb833..8600128139 100644 --- a/stmhal/can.h +++ b/stmhal/can.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,6 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ +#ifndef MICROPY_INCLUDED_STMHAL_CAN_H +#define MICROPY_INCLUDED_STMHAL_CAN_H #define PYB_CAN_1 (1) #define PYB_CAN_2 (2) @@ -32,3 +34,5 @@ extern const mp_obj_type_t pyb_can_type; void can_init0(void); void can_deinit(void); void can_rx_irq_handler(uint can_id, uint fifo_id); + +#endif // MICROPY_INCLUDED_STMHAL_CAN_H diff --git a/stmhal/dac.c b/stmhal/dac.c index 6524c6840e..cdb3a9bcd7 100644 --- a/stmhal/dac.c +++ b/stmhal/dac.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -28,9 +28,6 @@ #include #include -#include STM32_HAL_H - -#include "py/nlr.h" #include "py/runtime.h" #include "timer.h" #include "dac.h" @@ -127,7 +124,7 @@ STATIC uint32_t TIMx_Config(mp_obj_t timer) { } /******************************************************************************/ -// Micro Python bindings +// MicroPython bindings typedef enum { DAC_STATE_RESET, @@ -189,7 +186,7 @@ STATIC mp_obj_t pyb_dac_init_helper(pyb_dac_obj_t *self, mp_uint_t n_args, const if (args[0].u_int == 8 || args[0].u_int == 12) { self->bits = args[0].u_int; } else { - nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "unsupported bits")); + mp_raise_ValueError("unsupported bits"); } // reset state of DAC @@ -221,7 +218,7 @@ STATIC mp_obj_t pyb_dac_make_new(const mp_obj_type_t *type, size_t n_args, size_ } else if (pin == &pin_A5) { dac_id = 2; } else { - nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "pin %q does not have DAC capabilities", pin->name)); + nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Pin(%q) doesn't have DAC capabilities", pin->name)); } } @@ -237,7 +234,7 @@ STATIC mp_obj_t pyb_dac_make_new(const mp_obj_type_t *type, size_t n_args, size_ dac->dac_channel = DAC_CHANNEL_2; dac->tx_dma_descr = &dma_DAC_2_TX; } else { - nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "DAC %d does not exist", dac_id)); + nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "DAC(%d) doesn't exist", dac_id)); } // configure the peripheral diff --git a/stmhal/dac.h b/stmhal/dac.h index ba44158f39..f487f52a92 100644 --- a/stmhal/dac.h +++ b/stmhal/dac.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,7 +23,11 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ +#ifndef MICROPY_INCLUDED_STMHAL_DAC_H +#define MICROPY_INCLUDED_STMHAL_DAC_H void dac_init(void); extern const mp_obj_type_t pyb_dac_type; + +#endif // MICROPY_INCLUDED_STMHAL_DAC_H diff --git a/stmhal/dma.c b/stmhal/dma.c index 04c874dc27..df6275d652 100644 --- a/stmhal/dma.c +++ b/stmhal/dma.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -27,10 +27,9 @@ #include #include #include -#include STM32_HAL_H -#include "dma.h" #include "py/obj.h" +#include "dma.h" #include "irq.h" typedef enum { diff --git a/stmhal/dma.h b/stmhal/dma.h index 57b8f866d9..55fb621758 100644 --- a/stmhal/dma.h +++ b/stmhal/dma.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,9 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - -#ifndef __MICROPY_INCLUDED_STMHAL_DMA_H__ -#define __MICROPY_INCLUDED_STMHAL_DMA_H__ +#ifndef MICROPY_INCLUDED_STMHAL_DMA_H +#define MICROPY_INCLUDED_STMHAL_DMA_H typedef struct _dma_descr_t dma_descr_t; @@ -101,4 +100,4 @@ void dma_deinit(const dma_descr_t *dma_descr); void dma_invalidate_channel(const dma_descr_t *dma_descr); void dma_idle_handler(int controller); -#endif //__MICROPY_INCLUDED_STMHAL_DMA_H__ +#endif // MICROPY_INCLUDED_STMHAL_DMA_H diff --git a/stmhal/extint.c b/stmhal/extint.c index 642ecfd85e..24a68c2a22 100644 --- a/stmhal/extint.c +++ b/stmhal/extint.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -95,9 +95,13 @@ // The USB_FS_WAKUP event is a direct type and there is no support for it. #define EXTI_Mode_Interrupt offsetof(EXTI_TypeDef, IMR1) #define EXTI_Mode_Event offsetof(EXTI_TypeDef, EMR1) +#define EXTI_RTSR EXTI->RTSR1 +#define EXTI_FTSR EXTI->FTSR1 #else #define EXTI_Mode_Interrupt offsetof(EXTI_TypeDef, IMR) #define EXTI_Mode_Event offsetof(EXTI_TypeDef, EMR) +#define EXTI_RTSR EXTI->RTSR +#define EXTI_FTSR EXTI->FTSR #endif #define EXTI_SWIER_BB(line) (*(__IO uint32_t *)(PERIPH_BB_BASE + ((EXTI_OFFSET + offsetof(EXTI_TypeDef, SWIER)) * 32) + ((line) * 4))) @@ -107,7 +111,11 @@ typedef struct { mp_int_t line; } extint_obj_t; -STATIC uint32_t pyb_extint_mode[EXTI_NUM_VECTORS]; +STATIC uint8_t pyb_extint_mode[EXTI_NUM_VECTORS]; +STATIC bool pyb_extint_hard_irq[EXTI_NUM_VECTORS]; + +// The callback arg is a small-int or a ROM Pin object, so no need to scan by GC +STATIC mp_obj_t pyb_extint_callback_arg[EXTI_NUM_VECTORS]; #if !defined(ETH) #define ETH_WKUP_IRQn 62 // Some MCUs don't have ETH, but we want a value to put in our table @@ -187,6 +195,8 @@ uint extint_register(mp_obj_t pin_obj, uint32_t mode, uint32_t pull, mp_obj_t ca EXTI_Mode_Interrupt : EXTI_Mode_Event; if (*cb != mp_const_none) { + pyb_extint_hard_irq[v_line] = true; + pyb_extint_callback_arg[v_line] = MP_OBJ_NEW_SMALL_INT(v_line); mp_hal_gpio_clock_enable(pin->gpio); GPIO_InitTypeDef exti; @@ -205,6 +215,64 @@ uint extint_register(mp_obj_t pin_obj, uint32_t mode, uint32_t pull, mp_obj_t ca return v_line; } +// This function is intended to be used by the Pin.irq() method +void extint_register_pin(const pin_obj_t *pin, uint32_t mode, bool hard_irq, mp_obj_t callback_obj) { + uint32_t line = pin->pin; + + // Check if the ExtInt line is already in use by another Pin/ExtInt + mp_obj_t *cb = &MP_STATE_PORT(pyb_extint_callback)[line]; + if (*cb != mp_const_none && MP_OBJ_FROM_PTR(pin) != pyb_extint_callback_arg[line]) { + if (MP_OBJ_IS_SMALL_INT(pyb_extint_callback_arg[line])) { + nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_OSError, + "ExtInt vector %d is already in use", line)); + } else { + const pin_obj_t *other_pin = (const pin_obj_t*)pyb_extint_callback_arg[line]; + nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_OSError, + "IRQ resource already taken by Pin('%q')", other_pin->name)); + } + } + + extint_disable(line); + + *cb = callback_obj; + pyb_extint_mode[line] = (mode & 0x00010000) ? // GPIO_MODE_IT == 0x00010000 + EXTI_Mode_Interrupt : EXTI_Mode_Event; + + if (*cb != mp_const_none) { + // Configure and enable the callback + + pyb_extint_hard_irq[line] = hard_irq; + pyb_extint_callback_arg[line] = MP_OBJ_FROM_PTR(pin); + + // Route the GPIO to EXTI + __HAL_RCC_SYSCFG_CLK_ENABLE(); + SYSCFG->EXTICR[line >> 2] = + (SYSCFG->EXTICR[line >> 2] & ~(0x0f << (4 * (line & 0x03)))) + | ((uint32_t)(GPIO_GET_INDEX(pin->gpio)) << (4 * (line & 0x03))); + + // Enable or disable the rising detector + if ((mode & GPIO_MODE_IT_RISING) == GPIO_MODE_IT_RISING) { + EXTI_RTSR |= 1 << line; + } else { + EXTI_RTSR &= ~(1 << line); + } + + // Enable or disable the falling detector + if ((mode & GPIO_MODE_IT_FALLING) == GPIO_MODE_IT_FALLING) { + EXTI_FTSR |= 1 << line; + } else { + EXTI_FTSR &= ~(1 << line); + } + + // Configure the NVIC + HAL_NVIC_SetPriority(nvic_irq_channel[line], IRQ_PRI_EXTINT, IRQ_SUBPRI_EXTINT); + HAL_NVIC_EnableIRQ(nvic_irq_channel[line]); + + // Enable the interrupt + extint_enable(line); + } +} + void extint_enable(uint line) { if (line >= EXTI_NUM_VECTORS) { return; @@ -411,13 +479,19 @@ void Handle_EXTI_Irq(uint32_t line) { if (line < EXTI_NUM_VECTORS) { mp_obj_t *cb = &MP_STATE_PORT(pyb_extint_callback)[line]; if (*cb != mp_const_none) { + // If it's a soft IRQ handler then just schedule callback for later + if (!pyb_extint_hard_irq[line]) { + mp_sched_schedule(*cb, pyb_extint_callback_arg[line]); + return; + } + mp_sched_lock(); // When executing code within a handler we must lock the GC to prevent // any memory allocations. We must also catch any exceptions. gc_lock(); nlr_buf_t nlr; if (nlr_push(&nlr) == 0) { - mp_call_function_1(*cb, MP_OBJ_NEW_SMALL_INT(line)); + mp_call_function_1(*cb, pyb_extint_callback_arg[line]); nlr_pop(); } else { // Uncaught exception; disable the callback so it doesn't run again. diff --git a/stmhal/extint.h b/stmhal/extint.h index f0764aef25..846790b9be 100644 --- a/stmhal/extint.h +++ b/stmhal/extint.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,6 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ +#ifndef MICROPY_INCLUDED_STMHAL_EXTINT_H +#define MICROPY_INCLUDED_STMHAL_EXTINT_H // Vectors 0-15 are for regular pins // Vectors 16-22 are for internal sources. @@ -52,6 +54,7 @@ void extint_init0(void); uint extint_register(mp_obj_t pin_obj, uint32_t mode, uint32_t pull, mp_obj_t callback_obj, bool override_callback_obj); +void extint_register_pin(const pin_obj_t *pin, uint32_t mode, bool hard_irq, mp_obj_t callback_obj); void extint_enable(uint line); void extint_disable(uint line); @@ -60,3 +63,5 @@ void extint_swint(uint line); void Handle_EXTI_Irq(uint32_t line); extern const mp_obj_type_t extint_type; + +#endif // MICROPY_INCLUDED_STMHAL_EXTINT_H diff --git a/stmhal/flash.c b/stmhal/flash.c index 29de8b8daa..bebb3a1619 100644 --- a/stmhal/flash.c +++ b/stmhal/flash.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -24,11 +24,9 @@ * THE SOFTWARE. */ -#include STM32_HAL_H - -#include "flash.h" -#include "mpconfigport.h" +#include "py/mpconfig.h" #include "py/misc.h" +#include "flash.h" typedef struct { uint32_t base_address; diff --git a/stmhal/flash.h b/stmhal/flash.h index 007155ecb5..688e70a3cd 100644 --- a/stmhal/flash.h +++ b/stmhal/flash.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,7 +23,11 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ +#ifndef MICROPY_INCLUDED_STMHAL_FLASH_H +#define MICROPY_INCLUDED_STMHAL_FLASH_H uint32_t flash_get_sector_info(uint32_t addr, uint32_t *start_addr, uint32_t *size); void flash_erase(uint32_t flash_dest, const uint32_t *src, uint32_t num_word32); void flash_write(uint32_t flash_dest, const uint32_t *src, uint32_t num_word32); + +#endif // MICROPY_INCLUDED_STMHAL_FLASH_H diff --git a/stmhal/font_petme128_8x8.h b/stmhal/font_petme128_8x8.h index 7f928edda4..8b0cc9cb01 100644 --- a/stmhal/font_petme128_8x8.h +++ b/stmhal/font_petme128_8x8.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,6 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ +#ifndef MICROPY_INCLUDED_STMHAL_FONT_PETME128_8X8_H +#define MICROPY_INCLUDED_STMHAL_FONT_PETME128_8X8_H static const uint8_t font_petme128_8x8[] = { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, // 32= @@ -122,3 +124,5 @@ static const uint8_t font_petme128_8x8[] = { 0x00,0x02,0x03,0x01,0x03,0x02,0x03,0x01, // 126=~ 0xaa,0x55,0xaa,0x55,0xaa,0x55,0xaa,0x55, // 127 }; + +#endif // MICROPY_INCLUDED_STMHAL_FONT_PETME128_8X8_H diff --git a/stmhal/gccollect.c b/stmhal/gccollect.c index d7223dedc3..937fb6f36e 100644 --- a/stmhal/gccollect.c +++ b/stmhal/gccollect.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/stmhal/gccollect.h b/stmhal/gccollect.h index 07797be7e4..1b64a51a6a 100644 --- a/stmhal/gccollect.h +++ b/stmhal/gccollect.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,6 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ +#ifndef MICROPY_INCLUDED_STMHAL_GCCOLLECT_H +#define MICROPY_INCLUDED_STMHAL_GCCOLLECT_H // variables defining memory layout // (these probably belong somewhere else...) @@ -37,3 +39,5 @@ extern uint32_t _heap_start; extern uint32_t _heap_end; extern uint32_t _estack; extern uint32_t _ram_end; + +#endif // MICROPY_INCLUDED_STMHAL_GCCOLLECT_H diff --git a/stmhal/hal/l4/inc/stm32l4xx_hal_uart.h b/stmhal/hal/l4/inc/stm32l4xx_hal_uart.h index b890c3d987..52ca6406bc 100644 --- a/stmhal/hal/l4/inc/stm32l4xx_hal_uart.h +++ b/stmhal/hal/l4/inc/stm32l4xx_hal_uart.h @@ -1370,7 +1370,7 @@ void UART_AdvFeatureConfig(UART_HandleTypeDef *huart); /** * @} */ -/* Functions added by micropython */ +/* Functions added by MicroPython */ uint32_t HAL_UART_CalcBrr(uint32_t fck, uint32_t baud); #ifdef __cplusplus diff --git a/stmhal/hal/l4/src/stm32l4xx_hal_uart.c b/stmhal/hal/l4/src/stm32l4xx_hal_uart.c index 2b0d76d301..adb3d79ab7 100644 --- a/stmhal/hal/l4/src/stm32l4xx_hal_uart.c +++ b/stmhal/hal/l4/src/stm32l4xx_hal_uart.c @@ -2104,7 +2104,7 @@ static HAL_StatusTypeDef UART_Receive_IT(UART_HandleTypeDef *huart) /** * @brief Calculate register BRR value without using uint64. - * @note This function is added by the micropython project. + * @note This function is added by the MicroPython project. * @param fck: Input clock frequency to the uart block in Hz. * @param baud: baud rate should be one of {300, 600, 1200, 2400, 4800, 9600, 19200, 57600, 115200}. * @retval BRR value diff --git a/stmhal/help.c b/stmhal/help.c index 83ef7e596f..87b2af526e 100644 --- a/stmhal/help.c +++ b/stmhal/help.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/stmhal/i2c.c b/stmhal/i2c.c index 4a792d1630..3fcce327f4 100644 --- a/stmhal/i2c.c +++ b/stmhal/i2c.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -283,7 +283,7 @@ void i2c_init(I2C_HandleTypeDef *i2c) { const pyb_i2c_obj_t *self = &pyb_i2c_obj[i2c_unit - 1]; dma_invalidate_channel(self->tx_dma_descr); dma_invalidate_channel(self->rx_dma_descr); - + if (0) { #if defined(MICROPY_HW_I2C1_SCL) } else if (i2c->Instance == I2C1) { @@ -511,9 +511,9 @@ STATIC HAL_StatusTypeDef i2c_wait_dma_finished(I2C_HandleTypeDef *i2c, uint32_t } /******************************************************************************/ -/* Micro Python bindings */ +/* 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 = self_in; @@ -626,14 +626,14 @@ STATIC mp_obj_t pyb_i2c_make_new(const mp_obj_type_t *type, size_t n_args, size_ #endif } else { nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, - "I2C(%s) does not exist", port)); + "I2C(%s) doesn't exist", port)); } } else { i2c_id = mp_obj_get_int(args[0]); if (i2c_id < 1 || i2c_id > MP_ARRAY_SIZE(pyb_i2c_obj) || pyb_i2c_obj[i2c_id - 1].i2c == NULL) { nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, - "I2C(%d) does not exist", i2c_id)); + "I2C(%d) doesn't exist", i2c_id)); } } diff --git a/stmhal/i2c.h b/stmhal/i2c.h index fc7a6f613e..6affe3973b 100644 --- a/stmhal/i2c.h +++ b/stmhal/i2c.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,6 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ +#ifndef MICROPY_INCLUDED_STMHAL_I2C_H +#define MICROPY_INCLUDED_STMHAL_I2C_H #include "dma.h" @@ -49,3 +51,5 @@ void i2c_init_freq(const pyb_i2c_obj_t *self, mp_int_t freq); uint32_t i2c_get_baudrate(I2C_InitTypeDef *init); void i2c_ev_irq_handler(mp_uint_t i2c_id); void i2c_er_irq_handler(mp_uint_t i2c_id); + +#endif // MICROPY_INCLUDED_STMHAL_I2C_H diff --git a/stmhal/irq.c b/stmhal/irq.c index 44758e11bc..d6db8e83d8 100644 --- a/stmhal/irq.c +++ b/stmhal/irq.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/stmhal/irq.h b/stmhal/irq.h index a56f23652e..2cf58639ea 100644 --- a/stmhal/irq.h +++ b/stmhal/irq.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,6 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ +#ifndef MICROPY_INCLUDED_STMHAL_IRQ_H +#define MICROPY_INCLUDED_STMHAL_IRQ_H // these states correspond to values from query_irq, enable_irq and disable_irq #define IRQ_STATE_DISABLED (0x00000001) @@ -147,4 +149,4 @@ MP_DECLARE_CONST_FUN_OBJ_0(pyb_irq_stats_obj); #define IRQ_PRI_RTC_WKUP 15 #define IRQ_SUBPRI_RTC_WKUP 0 - +#endif // MICROPY_INCLUDED_STMHAL_IRQ_H diff --git a/stmhal/lcd.c b/stmhal/lcd.c index da09744606..7368193cf8 100644 --- a/stmhal/lcd.c +++ b/stmhal/lcd.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -220,7 +220,7 @@ STATIC mp_obj_t pyb_lcd_make_new(const mp_obj_type_t *type, size_t n_args, size_ lcd->pin_a0 = &pyb_pin_Y5; lcd->pin_bl = &pyb_pin_Y12; } else { - nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "LCD bus '%s' does not exist", lcd_id)); + nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "LCD(%s) doesn't exist", lcd_id)); } // init the SPI bus diff --git a/stmhal/lcd.h b/stmhal/lcd.h index 6a4b004bd9..c0d9bd97da 100644 --- a/stmhal/lcd.h +++ b/stmhal/lcd.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,5 +23,9 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ +#ifndef MICROPY_INCLUDED_STMHAL_LCD_H +#define MICROPY_INCLUDED_STMHAL_LCD_H extern const mp_obj_type_t pyb_lcd_type; + +#endif // MICROPY_INCLUDED_STMHAL_LCD_H diff --git a/stmhal/led.c b/stmhal/led.c index 4665146848..030a814dd6 100644 --- a/stmhal/led.c +++ b/stmhal/led.c @@ -279,7 +279,7 @@ void led_debug(int n, int delay) { } /******************************************************************************/ -/* Micro Python bindings */ +/* MicroPython bindings */ void led_obj_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { pyb_led_obj_t *self = self_in; @@ -299,7 +299,7 @@ STATIC mp_obj_t led_obj_make_new(const mp_obj_type_t *type, size_t n_args, size_ // check led number if (!(1 <= led_id && led_id <= NUM_LEDS)) { - nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "LED(%d) does not exist", led_id)); + nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "LED(%d) doesn't exist", led_id)); } // return static led object diff --git a/stmhal/led.h b/stmhal/led.h index f4cd673362..f1b05d1e28 100644 --- a/stmhal/led.h +++ b/stmhal/led.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,6 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ +#ifndef MICROPY_INCLUDED_STMHAL_LED_H +#define MICROPY_INCLUDED_STMHAL_LED_H typedef enum { // PYBv3 @@ -48,3 +50,5 @@ void led_toggle(pyb_led_t led); void led_debug(int value, int delay); extern const mp_obj_type_t pyb_led_type; + +#endif // MICROPY_INCLUDED_STMHAL_LED_H diff --git a/stmhal/machine_i2c.c b/stmhal/machine_i2c.c index aec53205f5..1be2151e3b 100644 --- a/stmhal/machine_i2c.c +++ b/stmhal/machine_i2c.c @@ -510,14 +510,14 @@ mp_obj_t machine_hard_i2c_make_new(const mp_obj_type_t *type, size_t n_args, siz #endif } else { nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, - "I2C(%s) does not exist", port)); + "I2C(%s) doesn't exist", port)); } } else { i2c_id = mp_obj_get_int(args[ARG_id].u_obj); if (i2c_id < 1 || i2c_id > MP_ARRAY_SIZE(machine_hard_i2c_obj) || machine_hard_i2c_obj[i2c_id - 1].base.type == NULL) { nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, - "I2C(%d) does not exist", i2c_id)); + "I2C(%d) doesn't exist", i2c_id)); } } diff --git a/stmhal/main.c b/stmhal/main.c index 566c2db07f..056c590cda 100644 --- a/stmhal/main.c +++ b/stmhal/main.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -511,7 +511,7 @@ soft_reset: // GC init gc_init(&_heap_start, &_heap_end); - // Micro Python init + // MicroPython init mp_init(); mp_obj_list_init(mp_sys_path, 0); mp_obj_list_append(mp_sys_path, MP_OBJ_NEW_QSTR(MP_QSTR_)); // current dir (or base dir of the script) diff --git a/stmhal/modmachine.h b/stmhal/modmachine.h index 164c5cfda2..ac39f854ed 100644 --- a/stmhal/modmachine.h +++ b/stmhal/modmachine.h @@ -23,9 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - -#ifndef __MICROPY_INCLUDED_STMHAL_MODMACHINE_H__ -#define __MICROPY_INCLUDED_STMHAL_MODMACHINE_H__ +#ifndef MICROPY_INCLUDED_STMHAL_MODMACHINE_H +#define MICROPY_INCLUDED_STMHAL_MODMACHINE_H #include "py/mpstate.h" #include "py/nlr.h" @@ -41,4 +40,4 @@ MP_DECLARE_CONST_FUN_OBJ_VAR_BETWEEN(machine_freq_obj); MP_DECLARE_CONST_FUN_OBJ_0(machine_sleep_obj); MP_DECLARE_CONST_FUN_OBJ_0(machine_deepsleep_obj); -#endif // __MICROPY_INCLUDED_STMHAL_MODMACHINE_H__ +#endif // MICROPY_INCLUDED_STMHAL_MODMACHINE_H diff --git a/stmhal/modnetwork.c b/stmhal/modnetwork.c index 09a80ef3cb..6b4949a0de 100644 --- a/stmhal/modnetwork.c +++ b/stmhal/modnetwork.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/stmhal/modnetwork.h b/stmhal/modnetwork.h index d3bc5674de..ecda94da41 100644 --- a/stmhal/modnetwork.h +++ b/stmhal/modnetwork.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,6 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ +#ifndef MICROPY_INCLUDED_STMHAL_MODNETWORK_H +#define MICROPY_INCLUDED_STMHAL_MODNETWORK_H #define MOD_NETWORK_IPADDR_BUF_SIZE (4) @@ -77,3 +79,5 @@ extern const mod_network_nic_type_t mod_network_nic_type_cc3k; void mod_network_init(void); void mod_network_register_nic(mp_obj_t nic); mp_obj_t mod_network_find_nic(const uint8_t *ip); + +#endif // MICROPY_INCLUDED_STMHAL_MODNETWORK_H diff --git a/stmhal/modnwcc3k.c b/stmhal/modnwcc3k.c index 957d74e6ec..a04a2d260c 100644 --- a/stmhal/modnwcc3k.c +++ b/stmhal/modnwcc3k.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -412,7 +412,7 @@ STATIC int cc3k_socket_ioctl(mod_network_socket_obj_t *socket, mp_uint_t request } /******************************************************************************/ -// Micro Python bindings; CC3K class +// MicroPython bindings; CC3K class typedef struct _cc3k_obj_t { mp_obj_base_t base; diff --git a/stmhal/modnwwiznet5k.c b/stmhal/modnwwiznet5k.c index 4752cdc0bc..eb7eb84438 100644 --- a/stmhal/modnwwiznet5k.c +++ b/stmhal/modnwwiznet5k.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -314,7 +314,7 @@ STATIC mp_obj_t wiznet5k_socket_disconnect(mp_obj_t self_in) { #endif /******************************************************************************/ -// Micro Python bindings +// MicroPython bindings /// \classmethod \constructor(spi, pin_cs, pin_rst) /// Create and return a WIZNET5K object. diff --git a/stmhal/modpyb.c b/stmhal/modpyb.c index b8da948ab5..5dc28e1325 100644 --- a/stmhal/modpyb.c +++ b/stmhal/modpyb.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -27,8 +27,6 @@ #include #include -#include STM32_HAL_H - #include "py/mpstate.h" #include "py/nlr.h" #include "py/obj.h" diff --git a/stmhal/modstm.c b/stmhal/modstm.c index 18882fa47a..2084c0aa0e 100644 --- a/stmhal/modstm.c +++ b/stmhal/modstm.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -27,15 +27,11 @@ #include #include -#include STM32_HAL_H - -#include "py/nlr.h" #include "py/obj.h" -#include "extmod/machine_mem.h" -#include "portmodules.h" - #include "py/objint.h" +#include "extmod/machine_mem.h" #include "genhdr/modstm_mpz.h" +#include "portmodules.h" STATIC const mp_rom_map_elem_t stm_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_stm) }, diff --git a/stmhal/modules/onewire.py b/stmhal/modules/onewire.py new file mode 120000 index 0000000000..f6ec745e85 --- /dev/null +++ b/stmhal/modules/onewire.py @@ -0,0 +1 @@ +../../drivers/onewire/onewire.py \ No newline at end of file diff --git a/stmhal/moduos.c b/stmhal/moduos.c index ece6019fbf..77a60c0cbc 100644 --- a/stmhal/moduos.c +++ b/stmhal/moduos.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/stmhal/modusocket.c b/stmhal/modusocket.c index 081a322ae2..e1da53a4b3 100644 --- a/stmhal/modusocket.c +++ b/stmhal/modusocket.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/stmhal/modutime.c b/stmhal/modutime.c index 97af35c491..fe13f80c06 100644 --- a/stmhal/modutime.c +++ b/stmhal/modutime.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -26,9 +26,8 @@ #include #include -#include STM32_HAL_H -#include "py/nlr.h" +#include "py/runtime.h" #include "py/smallint.h" #include "py/obj.h" #include "lib/timeutils/timeutils.h" diff --git a/stmhal/mpconfigport.h b/stmhal/mpconfigport.h index ac3c1f2470..a8ea2f02aa 100644 --- a/stmhal/mpconfigport.h +++ b/stmhal/mpconfigport.h @@ -27,10 +27,6 @@ // Options to control how MicroPython is built for this port, // overriding defaults in py/mpconfig.h. -#pragma once -#ifndef __INCLUDED_MPCONFIGPORT_H -#define __INCLUDED_MPCONFIGPORT_H - // board specific definitions #include "mpconfigboard.h" @@ -39,8 +35,12 @@ // emitters #define MICROPY_PERSISTENT_CODE_LOAD (1) +#ifndef MICROPY_EMIT_THUMB #define MICROPY_EMIT_THUMB (1) +#endif +#ifndef MICROPY_EMIT_INLINE_THUMB #define MICROPY_EMIT_INLINE_THUMB (1) +#endif // compiler configuration #define MICROPY_COMP_MODULE_CONST (1) @@ -65,7 +65,9 @@ #define MICROPY_REPL_AUTO_INDENT (1) #define MICROPY_LONGINT_IMPL (MICROPY_LONGINT_IMPL_MPZ) #define MICROPY_ENABLE_SOURCE_LINE (1) +#ifndef MICROPY_FLOAT_IMPL // can be configured by each board via mpconfigboard.mk #define MICROPY_FLOAT_IMPL (MICROPY_FLOAT_IMPL_FLOAT) +#endif #define MICROPY_STREAMS_NON_BLOCK (1) #define MICROPY_MODULE_WEAK_LINKS (1) #define MICROPY_CAN_OVERRIDE_BUILTINS (1) @@ -107,8 +109,9 @@ #define MICROPY_PY_SYS_PLATFORM "pyboard" #endif #define MICROPY_PY_UERRNO (1) +#ifndef MICROPY_PY_THREAD #define MICROPY_PY_THREAD (0) -#define MICROPY_PY_THREAD_GIL (0) +#endif // extended modules #define MICROPY_PY_UCTYPES (1) @@ -176,6 +179,7 @@ extern const struct _mp_obj_module_t mp_module_uos; extern const struct _mp_obj_module_t mp_module_utime; extern const struct _mp_obj_module_t mp_module_usocket; extern const struct _mp_obj_module_t mp_module_network; +extern const struct _mp_obj_module_t mp_module_onewire; #if MICROPY_PY_USOCKET #define SOCKET_BUILTIN_MODULE { MP_OBJ_NEW_QSTR(MP_QSTR_usocket), (mp_obj_t)&mp_module_usocket }, @@ -199,6 +203,7 @@ extern const struct _mp_obj_module_t mp_module_network; { MP_OBJ_NEW_QSTR(MP_QSTR_utime), (mp_obj_t)&mp_module_utime }, \ SOCKET_BUILTIN_MODULE \ NETWORK_BUILTIN_MODULE \ + { MP_OBJ_NEW_QSTR(MP_QSTR__onewire), (mp_obj_t)&mp_module_onewire }, \ #define MICROPY_PORT_BUILTIN_MODULE_WEAK_LINKS \ { MP_OBJ_NEW_QSTR(MP_QSTR_binascii), (mp_obj_t)&mp_module_ubinascii }, \ @@ -341,5 +346,3 @@ static inline mp_uint_t disable_irq(void) { #include #define MICROPY_PIN_DEFS_PORT_H "pin_defs_stmhal.h" - -#endif // __INCLUDED_MPCONFIGPORT_H diff --git a/stmhal/mphalport.h b/stmhal/mphalport.h index 77cb0204d0..8dd95c470c 100644 --- a/stmhal/mphalport.h +++ b/stmhal/mphalport.h @@ -27,6 +27,10 @@ void mp_hal_set_interrupt_char(int c); // -1 to disable // timing functions +#include "stmhal/irq.h" + +#define mp_hal_quiet_timing_enter() raise_irq_pri(1) +#define mp_hal_quiet_timing_exit(irq_state) restore_irq_pri(irq_state) #define mp_hal_delay_us_fast(us) mp_hal_delay_us(us) extern bool mp_hal_ticks_cpu_enabled; diff --git a/stmhal/mpthreadport.h b/stmhal/mpthreadport.h index 3d8b4ef011..8e2372dcb4 100644 --- a/stmhal/mpthreadport.h +++ b/stmhal/mpthreadport.h @@ -23,8 +23,6 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -#ifndef __MICROPY_INCLUDED_STMHAL_MPTHREADPORT_H__ -#define __MICROPY_INCLUDED_STMHAL_MPTHREADPORT_H__ #include "py/mpthread.h" #include "pybthread.h" @@ -53,5 +51,3 @@ static inline int mp_thread_mutex_lock(mp_thread_mutex_t *m, int wait) { static inline void mp_thread_mutex_unlock(mp_thread_mutex_t *m) { pyb_mutex_unlock(m); } - -#endif // __MICROPY_INCLUDED_STMHAL_MPTHREADPORT_H__ diff --git a/stmhal/pendsv.c b/stmhal/pendsv.c index 200d13a5a9..00ea12f460 100644 --- a/stmhal/pendsv.c +++ b/stmhal/pendsv.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -25,7 +25,6 @@ */ #include -#include STM32_HAL_H #include "py/mpstate.h" #include "py/runtime.h" diff --git a/stmhal/pendsv.h b/stmhal/pendsv.h index 77c78d4c18..6a9eb0d794 100644 --- a/stmhal/pendsv.h +++ b/stmhal/pendsv.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,6 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ +#ifndef MICROPY_INCLUDED_STMHAL_PENDSV_H +#define MICROPY_INCLUDED_STMHAL_PENDSV_H void pendsv_init(void); void pendsv_kbd_intr(void); @@ -30,3 +32,5 @@ void pendsv_kbd_intr(void); // since we play tricks with the stack, the compiler must not generate a // prelude for this function void pendsv_isr_handler(void) __attribute__((naked)); + +#endif // MICROPY_INCLUDED_STMHAL_PENDSV_H diff --git a/stmhal/pin.c b/stmhal/pin.c index db75969007..0dce0c1c08 100644 --- a/stmhal/pin.c +++ b/stmhal/pin.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -33,6 +33,7 @@ #include "py/mphal.h" #include "extmod/virtpin.h" #include "pin.h" +#include "extint.h" /// \moduleref pyb /// \class Pin - control I/O pins @@ -176,7 +177,7 @@ const pin_obj_t *pin_find(mp_obj_t user_obj) { return pin_obj; } - nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "pin '%s' not a valid pin identifier", mp_obj_str_get_str(user_obj))); + nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Pin(%s) doesn't exist", mp_obj_str_get_str(user_obj))); } /// \method __str__() @@ -414,6 +415,29 @@ STATIC mp_obj_t pin_on(mp_obj_t self_in) { } STATIC MP_DEFINE_CONST_FUN_OBJ_1(pin_on_obj, pin_on); +// pin.irq(handler=None, trigger=IRQ_FALLING|IRQ_RISING, hard=False) +STATIC mp_obj_t pin_irq(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + enum { ARG_handler, ARG_trigger, ARG_hard }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_handler, MP_ARG_OBJ, {.u_obj = mp_const_none} }, + { MP_QSTR_trigger, MP_ARG_INT, {.u_int = GPIO_MODE_IT_RISING | GPIO_MODE_IT_FALLING} }, + { MP_QSTR_hard, MP_ARG_BOOL, {.u_bool = false} }, + }; + pin_obj_t *self = MP_OBJ_TO_PTR(pos_args[0]); + mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; + mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); + + if (n_args > 1 || kw_args->used != 0) { + // configure irq + extint_register_pin(self, args[ARG_trigger].u_int, + args[ARG_hard].u_bool, args[ARG_handler].u_obj); + } + + // TODO should return an IRQ object + return mp_const_none; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pin_irq_obj, 1, pin_irq); + /// \method name() /// Get the pin name. STATIC mp_obj_t pin_name(mp_obj_t self_in) { @@ -498,6 +522,8 @@ STATIC const mp_rom_map_elem_t pin_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_value), MP_ROM_PTR(&pin_value_obj) }, { MP_ROM_QSTR(MP_QSTR_off), MP_ROM_PTR(&pin_off_obj) }, { MP_ROM_QSTR(MP_QSTR_on), MP_ROM_PTR(&pin_on_obj) }, + { MP_ROM_QSTR(MP_QSTR_irq), MP_ROM_PTR(&pin_irq_obj) }, + // Legacy names as used by pyb.Pin { MP_ROM_QSTR(MP_QSTR_low), MP_ROM_PTR(&pin_off_obj) }, { MP_ROM_QSTR(MP_QSTR_high), MP_ROM_PTR(&pin_on_obj) }, @@ -529,6 +555,8 @@ STATIC const mp_rom_map_elem_t pin_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_ANALOG), MP_ROM_INT(GPIO_MODE_ANALOG) }, { MP_ROM_QSTR(MP_QSTR_PULL_UP), MP_ROM_INT(GPIO_PULLUP) }, { MP_ROM_QSTR(MP_QSTR_PULL_DOWN), MP_ROM_INT(GPIO_PULLDOWN) }, + { MP_ROM_QSTR(MP_QSTR_IRQ_RISING), MP_ROM_INT(GPIO_MODE_IT_RISING) }, + { MP_ROM_QSTR(MP_QSTR_IRQ_FALLING), MP_ROM_INT(GPIO_MODE_IT_FALLING) }, // legacy class constants { MP_ROM_QSTR(MP_QSTR_OUT_PP), MP_ROM_INT(GPIO_MODE_OUTPUT_PP) }, diff --git a/stmhal/pin.h b/stmhal/pin.h index a11b0a0f8e..90de79e5ce 100644 --- a/stmhal/pin.h +++ b/stmhal/pin.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,9 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - -#ifndef __MICROPY_INCLUDED_STMHAL_PIN_H__ -#define __MICROPY_INCLUDED_STMHAL_PIN_H__ +#ifndef MICROPY_INCLUDED_STMHAL_PIN_H +#define MICROPY_INCLUDED_STMHAL_PIN_H // This file requires pin_defs_xxx.h (which has port specific enums and // defines, so we include it here. It should never be included directly @@ -98,4 +97,4 @@ const pin_af_obj_t *pin_find_af(const pin_obj_t *pin, uint8_t fn, uint8_t unit); const pin_af_obj_t *pin_find_af_by_index(const pin_obj_t *pin, mp_uint_t af_idx); const pin_af_obj_t *pin_find_af_by_name(const pin_obj_t *pin, const char *name); -#endif // __MICROPY_INCLUDED_STMHAL_PIN_H__ +#endif // MICROPY_INCLUDED_STMHAL_PIN_H diff --git a/stmhal/pin_defs_stmhal.h b/stmhal/pin_defs_stmhal.h index d6a2ef4242..6cf3b1b832 100644 --- a/stmhal/pin_defs_stmhal.h +++ b/stmhal/pin_defs_stmhal.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/stmhal/pin_named_pins.c b/stmhal/pin_named_pins.c index 9e5f9593b4..726da54dd6 100644 --- a/stmhal/pin_named_pins.c +++ b/stmhal/pin_named_pins.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -31,22 +31,15 @@ #include "py/mphal.h" #include "pin.h" -STATIC void pin_named_pins_obj_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { - pin_named_pins_obj_t *self = self_in; - mp_printf(print, "", self->name); -} - const mp_obj_type_t pin_cpu_pins_obj_type = { { &mp_type_type }, .name = MP_QSTR_cpu, - .print = pin_named_pins_obj_print, .locals_dict = (mp_obj_t)&pin_cpu_pins_locals_dict, }; const mp_obj_type_t pin_board_pins_obj_type = { { &mp_type_type }, .name = MP_QSTR_board, - .print = pin_named_pins_obj_print, .locals_dict = (mp_obj_t)&pin_board_pins_locals_dict, }; diff --git a/stmhal/portmodules.h b/stmhal/portmodules.h index 0b460f38c2..b575109b89 100644 --- a/stmhal/portmodules.h +++ b/stmhal/portmodules.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,6 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ +#ifndef MICROPY_INCLUDED_STMHAL_PORTMODULES_H +#define MICROPY_INCLUDED_STMHAL_PORTMODULES_H extern const mp_obj_module_t pyb_module; extern const mp_obj_module_t stm_module; @@ -37,3 +39,5 @@ MP_DECLARE_CONST_FUN_OBJ_1(time_sleep_us_obj); MP_DECLARE_CONST_FUN_OBJ_0(mod_os_sync_obj); MP_DECLARE_CONST_FUN_OBJ_VAR_BETWEEN(mod_os_dupterm_obj); + +#endif // MICROPY_INCLUDED_STMHAL_PORTMODULES_H diff --git a/stmhal/pybthread.h b/stmhal/pybthread.h index 6edb2400e2..f628f934bc 100644 --- a/stmhal/pybthread.h +++ b/stmhal/pybthread.h @@ -23,7 +23,6 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - #ifndef MICROPY_INCLUDED_STMHAL_PYBTHREAD_H #define MICROPY_INCLUDED_STMHAL_PYBTHREAD_H diff --git a/stmhal/qstrdefsport.h b/stmhal/qstrdefsport.h index 1d83f43bdd..31220c5a42 100644 --- a/stmhal/qstrdefsport.h +++ b/stmhal/qstrdefsport.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/stmhal/rng.c b/stmhal/rng.c index 2571bc3a01..c0c5e9aeb5 100644 --- a/stmhal/rng.c +++ b/stmhal/rng.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -26,8 +26,6 @@ #include -#include STM32_HAL_H - #include "py/obj.h" #include "rng.h" diff --git a/stmhal/rng.h b/stmhal/rng.h index ce1833e80b..43e49fe72e 100644 --- a/stmhal/rng.h +++ b/stmhal/rng.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,8 +23,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ +#ifndef MICROPY_INCLUDED_STMHAL_RNG_H +#define MICROPY_INCLUDED_STMHAL_RNG_H void rng_init0(void); uint32_t rng_get(void); MP_DECLARE_CONST_FUN_OBJ_0(pyb_rng_get_obj); + +#endif // MICROPY_INCLUDED_STMHAL_RNG_H diff --git a/stmhal/rtc.c b/stmhal/rtc.c index bc9c889c26..4efc56d5c8 100644 --- a/stmhal/rtc.c +++ b/stmhal/rtc.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -26,12 +26,9 @@ #include -#include STM32_HAL_H - #include "py/runtime.h" #include "rtc.h" #include "irq.h" -#include "mphalport.h" /// \moduleref pyb /// \class RTC - real time clock @@ -415,7 +412,7 @@ STATIC void RTC_CalendarConfig(void) { } /******************************************************************************/ -// Micro Python bindings +// MicroPython bindings typedef struct _pyb_rtc_obj_t { mp_obj_base_t base; diff --git a/stmhal/rtc.h b/stmhal/rtc.h index 69d64c778a..09ab2aedff 100644 --- a/stmhal/rtc.h +++ b/stmhal/rtc.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,9 +23,13 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ +#ifndef MICROPY_INCLUDED_STMHAL_RTC_H +#define MICROPY_INCLUDED_STMHAL_RTC_H extern RTC_HandleTypeDef RTCHandle; extern const mp_obj_type_t pyb_rtc_type; void rtc_init_start(bool force_init); void rtc_init_finalise(void); + +#endif // MICROPY_INCLUDED_STMHAL_RTC_H diff --git a/stmhal/sdcard.c b/stmhal/sdcard.c index 5a4b3b0e47..dfa7158a4c 100644 --- a/stmhal/sdcard.c +++ b/stmhal/sdcard.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -96,6 +96,18 @@ #endif +// If no custom SDIO pins defined, use the default ones +#ifndef MICROPY_HW_SDMMC_CK + +#define MICROPY_HW_SDMMC_D0 (pin_C8) +#define MICROPY_HW_SDMMC_D1 (pin_C9) +#define MICROPY_HW_SDMMC_D2 (pin_C10) +#define MICROPY_HW_SDMMC_D3 (pin_C11) +#define MICROPY_HW_SDMMC_CK (pin_C12) +#define MICROPY_HW_SDMMC_CMD (pin_D2) + +#endif + // TODO: Since SDIO is fundamentally half-duplex, we really only need to // tie up one DMA channel. However, the HAL DMA API doesn't // seem to provide a convenient way to change the direction. I believe that @@ -128,12 +140,12 @@ void sdcard_init(void) { mp_hal_pin_config_alt(&MICROPY_HW_SDMMC2_D3, MP_HAL_PIN_MODE_ALT, MP_HAL_PIN_PULL_UP, AF_FN_SDMMC, 2); #else // Default SDIO/SDMMC1 config - mp_hal_pin_config(&pin_C8, MP_HAL_PIN_MODE_ALT, MP_HAL_PIN_PULL_UP, GPIO_AF12_SDIO); - mp_hal_pin_config(&pin_C9, MP_HAL_PIN_MODE_ALT, MP_HAL_PIN_PULL_UP, GPIO_AF12_SDIO); - mp_hal_pin_config(&pin_C10, MP_HAL_PIN_MODE_ALT, MP_HAL_PIN_PULL_UP, GPIO_AF12_SDIO); - mp_hal_pin_config(&pin_C11, MP_HAL_PIN_MODE_ALT, MP_HAL_PIN_PULL_UP, GPIO_AF12_SDIO); - mp_hal_pin_config(&pin_C12, MP_HAL_PIN_MODE_ALT, MP_HAL_PIN_PULL_UP, GPIO_AF12_SDIO); - mp_hal_pin_config(&pin_D2, MP_HAL_PIN_MODE_ALT, MP_HAL_PIN_PULL_UP, GPIO_AF12_SDIO); + mp_hal_pin_config(&MICROPY_HW_SDMMC_D0, MP_HAL_PIN_MODE_ALT, MP_HAL_PIN_PULL_UP, GPIO_AF12_SDIO); + mp_hal_pin_config(&MICROPY_HW_SDMMC_D1, MP_HAL_PIN_MODE_ALT, MP_HAL_PIN_PULL_UP, GPIO_AF12_SDIO); + mp_hal_pin_config(&MICROPY_HW_SDMMC_D2, MP_HAL_PIN_MODE_ALT, MP_HAL_PIN_PULL_UP, GPIO_AF12_SDIO); + mp_hal_pin_config(&MICROPY_HW_SDMMC_D3, MP_HAL_PIN_MODE_ALT, MP_HAL_PIN_PULL_UP, GPIO_AF12_SDIO); + mp_hal_pin_config(&MICROPY_HW_SDMMC_CK, MP_HAL_PIN_MODE_ALT, MP_HAL_PIN_PULL_UP, GPIO_AF12_SDIO); + mp_hal_pin_config(&MICROPY_HW_SDMMC_CMD, MP_HAL_PIN_MODE_ALT, MP_HAL_PIN_PULL_UP, GPIO_AF12_SDIO); #endif // configure the SD card detect pin @@ -204,7 +216,7 @@ void sdcard_power_off(void) { if (!sd_handle.Instance) { return; } - HAL_SD_DeInit(&sd_handle); + HAL_SD_DeInit(&sd_handle); sd_handle.Instance = NULL; } @@ -344,7 +356,7 @@ mp_uint_t sdcard_write_blocks(const uint8_t *src, uint32_t block_num, uint32_t n } /******************************************************************************/ -// Micro Python bindings +// MicroPython bindings // // Expose the SD card as an object with the block protocol. diff --git a/stmhal/sdcard.h b/stmhal/sdcard.h index 237e48d8b9..8c698fc2f7 100644 --- a/stmhal/sdcard.h +++ b/stmhal/sdcard.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,6 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ +#ifndef MICROPY_INCLUDED_STMHAL_SDCARD_H +#define MICROPY_INCLUDED_STMHAL_SDCARD_H // this is a fixed size and should not be changed #define SDCARD_BLOCK_SIZE (512) @@ -42,3 +44,5 @@ extern const struct _mp_obj_base_t pyb_sdcard_obj; struct _fs_user_mount_t; void sdcard_init_vfs(struct _fs_user_mount_t *vfs, int part); + +#endif // MICROPY_INCLUDED_STMHAL_SDCARD_H diff --git a/stmhal/servo.c b/stmhal/servo.c index 4c62044dd9..fa39587a8e 100644 --- a/stmhal/servo.c +++ b/stmhal/servo.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -26,28 +26,30 @@ #include -#include STM32_HAL_H - -#include "py/nlr.h" #include "py/runtime.h" +#include "py/mphal.h" +#include "pin.h" +#include "genhdr/pins.h" #include "timer.h" #include "servo.h" -/// \moduleref pyb -/// \class Servo - 3-wire hobby servo driver -/// -/// Servo controls standard hobby servos with 3-wires (ground, power, signal). +#if MICROPY_HW_ENABLE_SERVO -// this servo driver uses hardware PWM to drive servos on PA0, PA1, PA2, PA3 = X1, X2, X3, X4 -// TIM2 and TIM5 have CH1, CH2, CH3, CH4 on PA0-PA3 respectively -// they are both 32-bit counters with 16-bit prescaler -// we use TIM5 +// This file implements the pyb.Servo class which controls standard hobby servo +// motors that have 3-wires (ground, power, signal). +// +// The driver uses hardware PWM to drive servos on pins X1, X2, X3, X4 which are +// assumed to be on PA0, PA1, PA2, PA3 but not necessarily in that order (the +// pins PA0-PA3 are used directly if the X pins are not defined). +// +// TIM2 and TIM5 have CH1-CH4 on PA0-PA3 respectively. They are both 32-bit +// counters with 16-bit prescaler. TIM5 is used by this driver. #define PYB_SERVO_NUM (4) typedef struct _pyb_servo_obj_t { mp_obj_base_t base; - uint8_t servo_id; + const pin_obj_t *pin; uint8_t pulse_min; // units of 10us uint8_t pulse_max; // units of 10us uint8_t pulse_centre; // units of 10us @@ -67,7 +69,6 @@ void servo_init(void) { // reset servo objects for (int i = 0; i < PYB_SERVO_NUM; i++) { pyb_servo_obj[i].base.type = &pyb_servo_type; - pyb_servo_obj[i].servo_id = i + 1; pyb_servo_obj[i].pulse_min = 64; pyb_servo_obj[i].pulse_max = 242; pyb_servo_obj[i].pulse_centre = 150; @@ -77,6 +78,19 @@ void servo_init(void) { pyb_servo_obj[i].pulse_dest = 0; pyb_servo_obj[i].time_left = 0; } + + // assign servo objects to specific pins (must be some permutation of PA0-PA3) + #ifdef pyb_pin_X1 + pyb_servo_obj[0].pin = &pyb_pin_X1; + pyb_servo_obj[1].pin = &pyb_pin_X2; + pyb_servo_obj[2].pin = &pyb_pin_X3; + pyb_servo_obj[3].pin = &pyb_pin_X4; + #else + pyb_servo_obj[0].pin = &pin_A0; + pyb_servo_obj[1].pin = &pin_A1; + pyb_servo_obj[2].pin = &pin_A2; + pyb_servo_obj[3].pin = &pin_A3; + #endif } void servo_timer_irq_callback(void) { @@ -102,12 +116,7 @@ void servo_timer_irq_callback(void) { need_it = true; } // set the pulse width - switch (s->servo_id) { - case 1: TIM5->CCR1 = s->pulse_cur; break; - case 2: TIM5->CCR2 = s->pulse_cur; break; - case 3: TIM5->CCR3 = s->pulse_cur; break; - case 4: TIM5->CCR4 = s->pulse_cur; break; - } + *(&TIM5->CCR1 + s->pin->pin) = s->pulse_cur; } } if (need_it) { @@ -118,24 +127,12 @@ void servo_timer_irq_callback(void) { } STATIC void servo_init_channel(pyb_servo_obj_t *s) { - uint32_t pin; - uint32_t channel; - switch (s->servo_id) { - case 1: pin = GPIO_PIN_0; channel = TIM_CHANNEL_1; break; - case 2: pin = GPIO_PIN_1; channel = TIM_CHANNEL_2; break; - case 3: pin = GPIO_PIN_2; channel = TIM_CHANNEL_3; break; - case 4: pin = GPIO_PIN_3; channel = TIM_CHANNEL_4; break; - default: return; - } + static const uint8_t channel_table[4] = + {TIM_CHANNEL_1, TIM_CHANNEL_2, TIM_CHANNEL_3, TIM_CHANNEL_4}; + uint32_t channel = channel_table[s->pin->pin]; // GPIO configuration - GPIO_InitTypeDef GPIO_InitStructure; - GPIO_InitStructure.Pin = pin; - GPIO_InitStructure.Mode = GPIO_MODE_AF_PP; - GPIO_InitStructure.Speed = GPIO_SPEED_FAST; - GPIO_InitStructure.Pull = GPIO_NOPULL; - GPIO_InitStructure.Alternate = GPIO_AF2_TIM5; - HAL_GPIO_Init(GPIOA, &GPIO_InitStructure); + mp_hal_pin_config(s->pin, MP_HAL_PIN_MODE_ALT, MP_HAL_PIN_PULL_NONE, GPIO_AF2_TIM5); // PWM mode configuration TIM_OC_InitTypeDef oc_init; @@ -150,7 +147,7 @@ STATIC void servo_init_channel(pyb_servo_obj_t *s) { } /******************************************************************************/ -// Micro Python bindings +// MicroPython bindings STATIC mp_obj_t pyb_servo_set(mp_obj_t port, mp_obj_t value) { int p = mp_obj_get_int(port); @@ -180,7 +177,7 @@ MP_DEFINE_CONST_FUN_OBJ_2(pyb_pwm_set_obj, pyb_pwm_set); STATIC void pyb_servo_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { pyb_servo_obj_t *self = self_in; - mp_printf(print, "", self->servo_id, 10 * self->pulse_cur); + mp_printf(print, "", self - &pyb_servo_obj[0] + 1, 10 * self->pulse_cur); } /// \classmethod \constructor(id) @@ -194,7 +191,7 @@ STATIC mp_obj_t pyb_servo_make_new(const mp_obj_type_t *type, size_t n_args, siz // check servo number if (!(0 <= servo_id && servo_id < PYB_SERVO_NUM)) { - nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Servo %d does not exist", servo_id + 1)); + nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Servo(%d) doesn't exist", servo_id + 1)); } // get and init servo object @@ -333,3 +330,5 @@ const mp_obj_type_t pyb_servo_type = { .make_new = pyb_servo_make_new, .locals_dict = (mp_obj_dict_t*)&pyb_servo_locals_dict, }; + +#endif // MICROPY_HW_ENABLE_SERVO diff --git a/stmhal/servo.h b/stmhal/servo.h index 0fca8fea17..c602a07da5 100644 --- a/stmhal/servo.h +++ b/stmhal/servo.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,6 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ +#ifndef MICROPY_INCLUDED_STMHAL_SERVO_H +#define MICROPY_INCLUDED_STMHAL_SERVO_H void servo_init(void); void servo_timer_irq_callback(void); @@ -31,3 +33,5 @@ extern const mp_obj_type_t pyb_servo_type; MP_DECLARE_CONST_FUN_OBJ_2(pyb_servo_set_obj); MP_DECLARE_CONST_FUN_OBJ_2(pyb_pwm_set_obj); + +#endif // MICROPY_INCLUDED_STMHAL_SERVO_H diff --git a/stmhal/spi.c b/stmhal/spi.c index eb7edbea06..574fed0739 100644 --- a/stmhal/spi.c +++ b/stmhal/spi.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -182,7 +182,7 @@ STATIC int spi_find(mp_obj_t id) { #endif } nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, - "SPI(%s) does not exist", port)); + "SPI(%s) doesn't exist", port)); } else { // given an integer id int spi_id = mp_obj_get_int(id); @@ -191,7 +191,7 @@ STATIC int spi_find(mp_obj_t id) { return spi_id; } nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, - "SPI(%d) does not exist", spi_id)); + "SPI(%d) doesn't exist", spi_id)); } } diff --git a/stmhal/spi.h b/stmhal/spi.h index 5686bde649..eda109a7ef 100644 --- a/stmhal/spi.h +++ b/stmhal/spi.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,6 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ +#ifndef MICROPY_INCLUDED_STMHAL_SPI_H +#define MICROPY_INCLUDED_STMHAL_SPI_H extern SPI_HandleTypeDef SPIHandle1; extern SPI_HandleTypeDef SPIHandle2; @@ -37,3 +39,5 @@ extern const mp_obj_type_t machine_hard_spi_type; void spi_init0(void); void spi_init(SPI_HandleTypeDef *spi, bool enable_nss_pin); SPI_HandleTypeDef *spi_get_handle(mp_obj_t o); + +#endif // MICROPY_INCLUDED_STMHAL_SPI_H diff --git a/stmhal/stm32_it.c b/stmhal/stm32_it.c index 913f1c9315..2111da1ae1 100644 --- a/stmhal/stm32_it.c +++ b/stmhal/stm32_it.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * Original template from ST Cube library. See below for header. * @@ -67,12 +67,10 @@ #include -#include "stm32_it.h" -#include STM32_HAL_H - #include "py/mpstate.h" #include "py/obj.h" #include "py/mphal.h" +#include "stm32_it.h" #include "pendsv.h" #include "irq.h" #include "pybthread.h" diff --git a/stmhal/stm32_it.h b/stmhal/stm32_it.h index a168cda838..b498dee8da 100644 --- a/stmhal/stm32_it.h +++ b/stmhal/stm32_it.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * Original template from ST Cube library. See below for header. * @@ -25,6 +25,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ +#ifndef MICROPY_INCLUDED_STMHAL_STM32_IT_H +#define MICROPY_INCLUDED_STMHAL_STM32_IT_H /** ****************************************************************************** @@ -80,3 +82,5 @@ void OTG_FS_IRQHandler(void); #ifdef USE_USB_HS void OTG_HS_IRQHandler(void); #endif + +#endif // MICROPY_INCLUDED_STMHAL_STM32_IT_H diff --git a/stmhal/storage.c b/stmhal/storage.c index 1931cd6079..6da1ba95c6 100644 --- a/stmhal/storage.c +++ b/stmhal/storage.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/stmhal/storage.h b/stmhal/storage.h index 4d3de77eda..291e09a9ae 100644 --- a/stmhal/storage.h +++ b/stmhal/storage.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,6 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ +#ifndef MICROPY_INCLUDED_STMHAL_STORAGE_H +#define MICROPY_INCLUDED_STMHAL_STORAGE_H #define FLASH_BLOCK_SIZE (512) @@ -45,3 +47,5 @@ extern const struct _mp_obj_type_t pyb_flash_type; struct _fs_user_mount_t; void pyb_flash_init_vfs(struct _fs_user_mount_t *vfs); + +#endif // MICROPY_INCLUDED_STMHAL_STORAGE_H diff --git a/stmhal/system_stm32.c b/stmhal/system_stm32.c index 266b8a92a5..7fc16b1483 100644 --- a/stmhal/system_stm32.c +++ b/stmhal/system_stm32.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * Taken from ST Cube library and modified. See below for original header. * @@ -87,8 +87,7 @@ * @{ */ -#include "mpconfigboard.h" -#include STM32_HAL_H +#include "py/mphal.h" void __fatal_error(const char *msg); diff --git a/stmhal/systick.c b/stmhal/systick.c index 4eac583e2a..c07d0fabce 100644 --- a/stmhal/systick.c +++ b/stmhal/systick.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/stmhal/systick.h b/stmhal/systick.h index 1e7f623355..c1def50c29 100644 --- a/stmhal/systick.h +++ b/stmhal/systick.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,6 +23,10 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ +#ifndef MICROPY_INCLUDED_STMHAL_SYSTICK_H +#define MICROPY_INCLUDED_STMHAL_SYSTICK_H void sys_tick_wait_at_least(uint32_t stc, uint32_t delay_ms); bool sys_tick_has_passed(uint32_t stc, uint32_t delay_ms); + +#endif // MICROPY_INCLUDED_STMHAL_SYSTICK_H diff --git a/stmhal/timer.c b/stmhal/timer.c index fd0695bdd2..570558775b 100644 --- a/stmhal/timer.c +++ b/stmhal/timer.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -28,11 +28,9 @@ #include #include -#include STM32_HAL_H #include "usbd_cdc_msc_hid.h" #include "usbd_cdc_interface.h" -#include "py/nlr.h" #include "py/runtime.h" #include "py/gc.h" #include "timer.h" @@ -218,9 +216,11 @@ TIM_HandleTypeDef *timer_tim6_init(uint freq) { // Interrupt dispatch void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) { + #if MICROPY_HW_ENABLE_SERVO if (htim == &TIM5_Handle) { servo_timer_irq_callback(); } + #endif } // Get the frequency (in Hz) of the source clock for the given timer. @@ -247,7 +247,7 @@ uint32_t timer_get_source_freq(uint32_t tim_id) { } /******************************************************************************/ -/* Micro Python bindings */ +/* MicroPython bindings */ STATIC const mp_obj_type_t pyb_timer_channel_type; @@ -702,7 +702,7 @@ STATIC mp_obj_t pyb_timer_make_new(const mp_obj_type_t *type, size_t n_args, siz #if defined(TIM17) case 17: tim->tim.Instance = TIM17; tim->irqn = TIM1_TRG_COM_TIM17_IRQn; break; #endif - default: nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Timer %d does not exist", tim->tim_id)); + default: nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Timer(%d) doesn't exist", tim->tim_id)); } // set the global variable for interrupt callbacks @@ -896,7 +896,7 @@ STATIC mp_obj_t pyb_timer_channel(mp_uint_t n_args, const mp_obj_t *pos_args, mp const pin_obj_t *pin = pin_obj; const pin_af_obj_t *af = pin_find_af(pin, AF_FN_TIM, self->tim_id); if (af == NULL) { - nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "pin %q doesn't have an af for TIM%d", pin->name, self->tim_id)); + nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Pin(%q) doesn't have an af for Timer(%d)", pin->name, self->tim_id)); } // pin.init(mode=AF_PP, af=idx) const mp_obj_t args2[6] = { @@ -1149,7 +1149,7 @@ STATIC mp_obj_t pyb_timer_period(mp_uint_t n_args, const mp_obj_t *args) { // Reset the counter to zero. Otherwise, if counter >= period it will // continue counting until it wraps (at either 16 or 32 bits depending // on the timer). - __HAL_TIM_SetCounter(&self->tim, 0); + __HAL_TIM_SetCounter(&self->tim, 0); return mp_const_none; } } diff --git a/stmhal/timer.h b/stmhal/timer.h index a18d7cf104..775accc3d4 100644 --- a/stmhal/timer.h +++ b/stmhal/timer.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,6 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ +#ifndef MICROPY_INCLUDED_STMHAL_TIMER_H +#define MICROPY_INCLUDED_STMHAL_TIMER_H extern TIM_HandleTypeDef TIM5_Handle; @@ -36,3 +38,5 @@ uint32_t timer_get_source_freq(uint32_t tim_id); void timer_irq_handler(uint tim_id); TIM_HandleTypeDef *pyb_timer_get_handle(mp_obj_t timer); + +#endif // MICROPY_INCLUDED_STMHAL_TIMER_H diff --git a/stmhal/uart.c b/stmhal/uart.c index b248138049..ddff8b9f2a 100644 --- a/stmhal/uart.c +++ b/stmhal/uart.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -509,7 +509,7 @@ void uart_irq_handler(mp_uint_t uart_id) { } /******************************************************************************/ -/* Micro Python bindings */ +/* MicroPython bindings */ STATIC void pyb_uart_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { pyb_uart_obj_t *self = self_in; @@ -597,7 +597,7 @@ STATIC mp_obj_t pyb_uart_init_helper(pyb_uart_obj_t *self, mp_uint_t n_args, con } else if (bits == 9) { init->WordLength = UART_WORDLENGTH_9B; } else { - nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "unsupported combination of bits and parity")); + mp_raise_ValueError("unsupported combination of bits and parity"); } // stop bits @@ -615,7 +615,7 @@ STATIC mp_obj_t pyb_uart_init_helper(pyb_uart_obj_t *self, mp_uint_t n_args, con // init UART (if it fails, it's because the port doesn't exist) if (!uart_init2(self)) { - nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "UART(%d) does not exist", self->uart_id)); + nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "UART(%d) doesn't exist", self->uart_id)); } // set timeout @@ -656,7 +656,7 @@ STATIC mp_obj_t pyb_uart_init_helper(pyb_uart_obj_t *self, mp_uint_t n_args, con self->read_buf_len = args.read_buf_len.u_int + 1; // +1 to adjust for usable length of buffer self->read_buf = m_new(byte, self->read_buf_len << self->char_width); __HAL_UART_ENABLE_IT(&self->uart, UART_IT_RXNE); - HAL_NVIC_SetPriority(self->irqn, IRQ_PRI_UART, IRQ_SUBPRI_UART); + HAL_NVIC_SetPriority(self->irqn, IRQ_PRI_UART, IRQ_SUBPRI_UART); HAL_NVIC_EnableIRQ(self->irqn); } @@ -751,12 +751,12 @@ STATIC mp_obj_t pyb_uart_make_new(const mp_obj_type_t *type, size_t n_args, size uart_id = PYB_UART_6; #endif } else { - nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "UART(%s) does not exist", port)); + nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "UART(%s) doesn't exist", port)); } } else { uart_id = mp_obj_get_int(args[0]); if (!uart_exists(uart_id)) { - nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "UART(%d) does not exist", uart_id)); + nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "UART(%d) doesn't exist", uart_id)); } } diff --git a/stmhal/uart.h b/stmhal/uart.h index 7fdc59de75..e96b25b5f4 100644 --- a/stmhal/uart.h +++ b/stmhal/uart.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,6 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ +#ifndef MICROPY_INCLUDED_STMHAL_UART_H +#define MICROPY_INCLUDED_STMHAL_UART_H typedef enum { PYB_UART_NONE = 0, @@ -47,3 +49,5 @@ mp_uint_t uart_rx_any(pyb_uart_obj_t *uart_obj); int uart_rx_char(pyb_uart_obj_t *uart_obj); void uart_tx_strn(pyb_uart_obj_t *uart_obj, const char *str, uint len); void uart_tx_strn_cooked(pyb_uart_obj_t *uart_obj, const char *str, uint len); + +#endif // MICROPY_INCLUDED_STMHAL_UART_H diff --git a/stmhal/usb.c b/stmhal/usb.c index f70dea1428..9bf351f499 100644 --- a/stmhal/usb.c +++ b/stmhal/usb.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -169,7 +169,7 @@ void usb_vcp_send_strn_cooked(const char *str, int len) { } /******************************************************************************/ -// Micro Python bindings for USB +// MicroPython bindings for USB /* Philosophy of USB driver and Python API: pyb.usb_mode(...) configures the USB @@ -324,7 +324,7 @@ bad_mode: MP_DEFINE_CONST_FUN_OBJ_KW(pyb_usb_mode_obj, 0, pyb_usb_mode); /******************************************************************************/ -// Micro Python bindings for USB VCP +// MicroPython bindings for USB VCP /// \moduleref pyb /// \class USB_VCP - USB virtual comm port @@ -525,7 +525,7 @@ const mp_obj_type_t pyb_usb_vcp_type = { }; /******************************************************************************/ -// Micro Python bindings for USB HID +// MicroPython bindings for USB HID typedef struct _pyb_usb_hid_obj_t { mp_obj_base_t base; diff --git a/stmhal/usb.h b/stmhal/usb.h index 42e6c76f81..d39f49a6cc 100644 --- a/stmhal/usb.h +++ b/stmhal/usb.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,6 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ +#ifndef MICROPY_INCLUDED_STMHAL_USB_H +#define MICROPY_INCLUDED_STMHAL_USB_H #include "usbd_cdc_msc_hid0.h" @@ -67,3 +69,5 @@ void usb_vcp_send_strn_cooked(const char *str, int len); void pyb_usb_host_init(void); void pyb_usb_host_process(void); uint pyb_usb_host_get_keyboard(void); + +#endif // MICROPY_INCLUDED_STMHAL_USB_H diff --git a/stmhal/usbd_cdc_interface.c b/stmhal/usbd_cdc_interface.c index addcf8c854..3e107d418e 100644 --- a/stmhal/usbd_cdc_interface.c +++ b/stmhal/usbd_cdc_interface.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * Taken from ST Cube library and heavily modified. See below for original * copyright header. @@ -23,8 +23,8 @@ * * http://www.st.com/software_license_agreement_liberty_v2 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. @@ -102,52 +102,14 @@ const USBD_CDC_ItfTypeDef USBD_CDC_fops = { * @param None * @retval Result of the opeartion: USBD_OK if all operations are OK else USBD_FAIL */ -static int8_t CDC_Itf_Init(USBD_HandleTypeDef *pdev) -{ -#if 0 - /*##-1- Configure the UART peripheral ######################################*/ - /* Put the USART peripheral in the Asynchronous mode (UART Mode) */ - /* USART configured as follow: - - Word Length = 8 Bits - - Stop Bit = One Stop bit - - Parity = No parity - - BaudRate = 115200 baud - - Hardware flow control disabled (RTS and CTS signals) */ - UartHandle.Instance = USARTx; - UartHandle.Init.BaudRate = 115200; - UartHandle.Init.WordLength = UART_WORDLENGTH_8B; - UartHandle.Init.StopBits = UART_STOPBITS_1; - UartHandle.Init.Parity = UART_PARITY_NONE; - UartHandle.Init.HwFlowCtl = UART_HWCONTROL_NONE; - UartHandle.Init.Mode = UART_MODE_TX_RX; - - if(HAL_UART_Init(&UartHandle) != HAL_OK) - { - /* Initialization Error */ - Error_Handler(); - } - - /*##-2- Put UART peripheral in IT reception process ########################*/ - /* Any data received will be stored in "UserTxBuffer" buffer */ - if(HAL_UART_Receive_IT(&UartHandle, (uint8_t *)UserTxBuffer, 1) != HAL_OK) - { - /* Transfer error in reception process */ - Error_Handler(); - } - - /*##-3- Configure the TIM Base generation #################################*/ - now done in HAL_MspInit - TIM_Config(); -#endif - - /*##-5- Set Application Buffers ############################################*/ +static int8_t CDC_Itf_Init(USBD_HandleTypeDef *pdev) { USBD_CDC_SetTxBuffer(pdev, UserTxBuffer, 0); USBD_CDC_SetRxBuffer(pdev, cdc_rx_packet_buf); cdc_rx_buf_put = 0; cdc_rx_buf_get = 0; - - return (USBD_OK); + + return USBD_OK; } /** @@ -156,22 +118,14 @@ static int8_t CDC_Itf_Init(USBD_HandleTypeDef *pdev) * @param None * @retval Result of the opeartion: USBD_OK if all operations are OK else USBD_FAIL */ -static int8_t CDC_Itf_DeInit(void) -{ -#if 0 - /* DeInitialize the UART peripheral */ - if(HAL_UART_DeInit(&UartHandle) != HAL_OK) - { - /* Initialization Error */ - } -#endif - return (USBD_OK); +static int8_t CDC_Itf_DeInit(void) { + return USBD_OK; } /** * @brief CDC_Itf_Control * Manage the CDC class requests - * @param Cmd: Command code + * @param Cmd: Command code * @param Buf: Buffer containing command data (request parameters) * @param Len: Number of data to be sent (in bytes) * @retval Result of the opeartion: USBD_OK if all operations are OK else USBD_FAIL @@ -210,16 +164,6 @@ static int8_t CDC_Itf_Control(uint8_t cmd, uint8_t* pbuf, uint16_t length) { break; case CDC_GET_LINE_CODING: - #if 0 - pbuf[0] = (uint8_t)(LineCoding.bitrate); - pbuf[1] = (uint8_t)(LineCoding.bitrate >> 8); - pbuf[2] = (uint8_t)(LineCoding.bitrate >> 16); - pbuf[3] = (uint8_t)(LineCoding.bitrate >> 24); - pbuf[4] = LineCoding.format; - pbuf[5] = LineCoding.paritytype; - pbuf[6] = LineCoding.datatype; - #endif - /* Add your code here */ pbuf[0] = (uint8_t)(115200); pbuf[1] = (uint8_t)(115200 >> 8); @@ -318,11 +262,6 @@ void HAL_PCD_SOFCallback(PCD_HandleTypeDef *hpcd) { * free to modify it. */ static int8_t CDC_Itf_Receive(USBD_HandleTypeDef *pdev, uint8_t* Buf, uint32_t *Len) { -#if 0 - // this sends the data over the UART using DMA - HAL_UART_Transmit_DMA(&UartHandle, Buf, *Len); -#endif - // copy the incoming data into the circular buffer for (uint8_t *src = Buf, *top = Buf + *Len; src < top; ++src) { if (mp_interrupt_char != -1 && *src == mp_interrupt_char) { diff --git a/stmhal/usbd_cdc_interface.h b/stmhal/usbd_cdc_interface.h index d96861a7e5..811a289280 100644 --- a/stmhal/usbd_cdc_interface.h +++ b/stmhal/usbd_cdc_interface.h @@ -1,6 +1,8 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ */ +#ifndef MICROPY_INCLUDED_STMHAL_USBD_CDC_INTERFACE_H +#define MICROPY_INCLUDED_STMHAL_USBD_CDC_INTERFACE_H /** ****************************************************************************** @@ -39,3 +41,5 @@ void USBD_CDC_TxAlways(const uint8_t *buf, uint32_t len); int USBD_CDC_RxNum(void); int USBD_CDC_Rx(uint8_t *buf, uint32_t len, uint32_t timeout); + +#endif // MICROPY_INCLUDED_STMHAL_USBD_CDC_INTERFACE_H diff --git a/stmhal/usbd_conf.c b/stmhal/usbd_conf.c index 1da987d89a..d39144851f 100644 --- a/stmhal/usbd_conf.c +++ b/stmhal/usbd_conf.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ */ /** @@ -30,7 +30,6 @@ */ /* Includes ------------------------------------------------------------------*/ -#include STM32_HAL_H #include "usbd_core.h" #include "py/obj.h" #include "irq.h" diff --git a/stmhal/usbd_conf.h b/stmhal/usbd_conf.h index 5415eb10b4..34ebe27b9a 100644 --- a/stmhal/usbd_conf.h +++ b/stmhal/usbd_conf.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ */ /** @@ -34,7 +34,6 @@ #define __USBD_CONF_H /* Includes ------------------------------------------------------------------*/ -#include STM32_HAL_H #include #include #include diff --git a/stmhal/usbd_desc.c b/stmhal/usbd_desc.c index 1ad960b468..09e1608c84 100644 --- a/stmhal/usbd_desc.c +++ b/stmhal/usbd_desc.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ */ /** diff --git a/stmhal/usbd_desc.h b/stmhal/usbd_desc.h index 93e222fc93..05cbbe5b17 100644 --- a/stmhal/usbd_desc.h +++ b/stmhal/usbd_desc.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,7 +23,11 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ +#ifndef MICROPY_INCLUDED_STMHAL_USBD_DESC_H +#define MICROPY_INCLUDED_STMHAL_USBD_DESC_H extern const USBD_DescriptorsTypeDef USBD_Descriptors; void USBD_SetVIDPIDRelease(uint16_t vid, uint16_t pid, uint16_t device_release_num, int cdc_only); + +#endif // MICROPY_INCLUDED_STMHAL_USBD_DESC_H diff --git a/stmhal/usbd_hid_interface.h b/stmhal/usbd_hid_interface.h index fbc874796e..b2ff75fa13 100644 --- a/stmhal/usbd_hid_interface.h +++ b/stmhal/usbd_hid_interface.h @@ -1,6 +1,8 @@ /* * This file is part of the MicroPython project, http://micropython.org/ */ +#ifndef MICROPY_INCLUDED_STMHAL_USBD_HID_INTERFACE_H +#define MICROPY_INCLUDED_STMHAL_USBD_HID_INTERFACE_H #include "usbd_cdc_msc_hid.h" @@ -8,3 +10,5 @@ extern const USBD_HID_ItfTypeDef USBD_HID_fops; int USBD_HID_RxNum(void); int USBD_HID_Rx(USBD_HandleTypeDef *pdev, uint8_t *buf, uint32_t len, uint32_t timeout); + +#endif // MICROPY_INCLUDED_STMHAL_USBD_HID_INTERFACE_H diff --git a/stmhal/usbd_msc_storage.c b/stmhal/usbd_msc_storage.c index cec9737418..f825c3d70d 100644 --- a/stmhal/usbd_msc_storage.c +++ b/stmhal/usbd_msc_storage.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ */ /** @@ -20,13 +20,13 @@ * * http://www.st.com/software_license_agreement_liberty_v2 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * - * Heavily modified by dpgeorge for Micro Python. + * Heavily modified by dpgeorge for MicroPython. * ****************************************************************************** */ @@ -134,13 +134,6 @@ int8_t FLASH_STORAGE_PreventAllowMediumRemoval(uint8_t lun, uint8_t param) { */ int8_t FLASH_STORAGE_Read(uint8_t lun, uint8_t *buf, uint32_t blk_addr, uint16_t blk_len) { storage_read_blocks(buf, blk_addr, blk_len); - /* - for (int i = 0; i < blk_len; i++) { - if (!storage_read_block(buf + i * FLASH_BLOCK_SIZE, blk_addr + i)) { - return -1; - } - } - */ return 0; } @@ -154,13 +147,6 @@ int8_t FLASH_STORAGE_Read(uint8_t lun, uint8_t *buf, uint32_t blk_addr, uint16_t */ 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); - /* - for (int i = 0; i < blk_len; i++) { - if (!storage_write_block(buf + i * FLASH_BLOCK_SIZE, blk_addr + i)) { - return -1; - } - } - */ return 0; } @@ -213,20 +199,6 @@ static const int8_t SDCARD_STORAGE_Inquirydata[] = { // 36 bytes * @retval Status */ int8_t SDCARD_STORAGE_Init(uint8_t lun) { - /* -#ifndef USE_STM3210C_EVAL - NVIC_InitTypeDef NVIC_InitStructure; - NVIC_InitStructure.NVIC_IRQChannel = SDIO_IRQn; - NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority =0; - NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; - NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; - NVIC_Init(&NVIC_InitStructure); -#endif - if( SD_Init() != 0) - { - return (-1); - } - */ if (!sdcard_power_on()) { return -1; } @@ -243,20 +215,8 @@ int8_t SDCARD_STORAGE_Init(uint8_t lun) { * @retval Status */ int8_t SDCARD_STORAGE_GetCapacity(uint8_t lun, uint32_t *block_num, uint16_t *block_size) { -/* -#ifdef USE_STM3210C_EVAL - SD_CardInfo SDCardInfo; - SD_GetCardInfo(&SDCardInfo); -#else - if(SD_GetStatus() != 0 ) { - return (-1); - } -#endif - */ - *block_size = SDCARD_BLOCK_SIZE; *block_num = sdcard_get_capacity_in_bytes() / SDCARD_BLOCK_SIZE; - return 0; } diff --git a/stmhal/usbd_msc_storage.h b/stmhal/usbd_msc_storage.h index 4a0d28ca82..6cc40d2d62 100644 --- a/stmhal/usbd_msc_storage.h +++ b/stmhal/usbd_msc_storage.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,6 +23,10 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ +#ifndef MICROPY_INCLUDED_STMHAL_USBD_MSC_STORAGE_H +#define MICROPY_INCLUDED_STMHAL_USBD_MSC_STORAGE_H extern const USBD_StorageTypeDef USBD_FLASH_STORAGE_fops; extern const USBD_StorageTypeDef USBD_SDCARD_STORAGE_fops; + +#endif // MICROPY_INCLUDED_STMHAL_USBD_MSC_STORAGE_H diff --git a/stmhal/usbdev/class/inc/usbd_cdc_msc_hid0.h b/stmhal/usbdev/class/inc/usbd_cdc_msc_hid0.h index bc9d0d21a6..08882bb1ae 100644 --- a/stmhal/usbdev/class/inc/usbd_cdc_msc_hid0.h +++ b/stmhal/usbdev/class/inc/usbd_cdc_msc_hid0.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,9 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - -#ifndef __MICROPY_INCLUDED_STMHAL_USB_CDC_MSC_HID0_H__ -#define __MICROPY_INCLUDED_STMHAL_USB_CDC_MSC_HID0_H__ +#ifndef MICROPY_INCLUDED_STMHAL_USBDEV_CLASS_INC_USBD_CDC_MSC_HID0_H +#define MICROPY_INCLUDED_STMHAL_USBDEV_CLASS_INC_USBD_CDC_MSC_HID0_H // these are exports for the CDC/MSC/HID interface that are independent // from any other definitions/declarations @@ -49,4 +48,4 @@ typedef struct _USBD_HID_ModeInfoTypeDef { const uint8_t *report_desc; } USBD_HID_ModeInfoTypeDef; -#endif // __MICROPY_INCLUDED_STMHAL_USB_CDC_MSC_HID0_H__ +#endif // MICROPY_INCLUDED_STMHAL_USBDEV_CLASS_INC_USBD_CDC_MSC_HID0_H diff --git a/stmhal/usbdev/class/inc/usbd_msc_scsi.h b/stmhal/usbdev/class/inc/usbd_msc_scsi.h index dea247bca8..34f059ee5d 100644 --- a/stmhal/usbdev/class/inc/usbd_msc_scsi.h +++ b/stmhal/usbdev/class/inc/usbd_msc_scsi.h @@ -55,6 +55,8 @@ #define SCSI_MODE_SENSE6 0x1A #define SCSI_MODE_SENSE10 0x5A #define SCSI_ALLOW_MEDIUM_REMOVAL 0x1E +#define SCSI_SYNCHRONIZE_CACHE10 0x35 +#define SCSI_SYNCHRONIZE_CACHE16 0x91 #define SCSI_READ6 0x08 #define SCSI_READ10 0x28 #define SCSI_READ12 0xA8 diff --git a/stmhal/usbdev/class/src/usbd_cdc_msc_hid.c b/stmhal/usbdev/class/src/usbd_cdc_msc_hid.c index e0edf13702..d61073f4d5 100644 --- a/stmhal/usbdev/class/src/usbd_cdc_msc_hid.c +++ b/stmhal/usbdev/class/src/usbd_cdc_msc_hid.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/stmhal/usbdev/class/src/usbd_msc_scsi.c b/stmhal/usbdev/class/src/usbd_msc_scsi.c index 366f1f00e9..b2931b7452 100644 --- a/stmhal/usbdev/class/src/usbd_msc_scsi.c +++ b/stmhal/usbdev/class/src/usbd_msc_scsi.c @@ -89,6 +89,7 @@ static int8_t SCSI_StartStopUnit(USBD_HandleTypeDef *pdev, uint8_t lun, uint8_t static int8_t SCSI_AllowMediumRemoval(USBD_HandleTypeDef *pdev, uint8_t lun, uint8_t *params); static int8_t SCSI_ModeSense6 (USBD_HandleTypeDef *pdev, uint8_t lun, uint8_t *params); static int8_t SCSI_ModeSense10 (USBD_HandleTypeDef *pdev, uint8_t lun, uint8_t *params); +static int8_t SCSI_SynchronizeCache(USBD_HandleTypeDef *pdev, uint8_t lun, uint8_t *params); static int8_t SCSI_Write10(USBD_HandleTypeDef *pdev, uint8_t lun , uint8_t *params); static int8_t SCSI_Read10(USBD_HandleTypeDef *pdev, uint8_t lun , uint8_t *params); static int8_t SCSI_Verify10(USBD_HandleTypeDef *pdev, uint8_t lun, uint8_t *params); @@ -151,6 +152,10 @@ int8_t SCSI_ProcessCmd(USBD_HandleTypeDef *pdev, case SCSI_MODE_SENSE10: return SCSI_ModeSense10 (pdev, lun, params); + case SCSI_SYNCHRONIZE_CACHE10: + case SCSI_SYNCHRONIZE_CACHE16: + return SCSI_SynchronizeCache(pdev, lun, params); + case SCSI_READ_FORMAT_CAPACITIES: return SCSI_ReadFormatCapacity(pdev, lun, params); @@ -374,6 +379,13 @@ static int8_t SCSI_ModeSense10 (USBD_HandleTypeDef *pdev, uint8_t lun, uint8_t return 0; } +static int8_t SCSI_SynchronizeCache(USBD_HandleTypeDef *pdev, uint8_t lun, uint8_t *params) { + // nothing to synchronize, so just return "success" + USBD_MSC_BOT_HandleTypeDef *hmsc = pdev->pClassData; + hmsc->bot_data_length = 0; + return 0; +} + /** * @brief SCSI_RequestSense * Process Request Sense command diff --git a/stmhal/usrsw.c b/stmhal/usrsw.c index d4f0c69394..a7721ad779 100644 --- a/stmhal/usrsw.c +++ b/stmhal/usrsw.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -63,7 +63,7 @@ int switch_get(void) { } /******************************************************************************/ -// Micro Python bindings +// MicroPython bindings typedef struct _pyb_switch_obj_t { mp_obj_base_t base; @@ -97,6 +97,12 @@ mp_obj_t pyb_switch_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp_ return switch_get() ? mp_const_true : mp_const_false; } +mp_obj_t pyb_switch_value(mp_obj_t self_in) { + (void)self_in; + return mp_obj_new_bool(switch_get()); +} +STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_switch_value_obj, pyb_switch_value); + STATIC mp_obj_t switch_callback(mp_obj_t line) { if (MP_STATE_PORT(pyb_switch_callback) != mp_const_none) { mp_call_function_0(MP_STATE_PORT(pyb_switch_callback)); @@ -123,6 +129,7 @@ mp_obj_t pyb_switch_callback(mp_obj_t self_in, mp_obj_t callback) { STATIC MP_DEFINE_CONST_FUN_OBJ_2(pyb_switch_callback_obj, pyb_switch_callback); STATIC const mp_rom_map_elem_t pyb_switch_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_value), MP_ROM_PTR(&pyb_switch_value_obj) }, { MP_ROM_QSTR(MP_QSTR_callback), MP_ROM_PTR(&pyb_switch_callback_obj) }, }; diff --git a/stmhal/usrsw.h b/stmhal/usrsw.h index b6dff2c431..d96e3c2813 100644 --- a/stmhal/usrsw.h +++ b/stmhal/usrsw.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,8 +23,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ +#ifndef MICROPY_INCLUDED_STMHAL_USRSW_H +#define MICROPY_INCLUDED_STMHAL_USRSW_H void switch_init0(void); int switch_get(void); extern const mp_obj_type_t pyb_switch_type; + +#endif // MICROPY_INCLUDED_STMHAL_USRSW_H diff --git a/stmhal/wdt.c b/stmhal/wdt.c index af2481e926..2b4967a434 100644 --- a/stmhal/wdt.c +++ b/stmhal/wdt.c @@ -26,8 +26,6 @@ #include -#include STM32_HAL_H - #include "py/runtime.h" #include "wdt.h" @@ -49,7 +47,7 @@ STATIC mp_obj_t pyb_wdt_make_new(const mp_obj_type_t *type, size_t n_args, size_ mp_int_t id = args[ARG_id].u_int; if (id != 0) { - nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "WDT(%d) does not exist", id)); + nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "WDT(%d) doesn't exist", id)); } // timeout is in milliseconds diff --git a/stmhal/wdt.h b/stmhal/wdt.h index 362d6ef68b..0a486f704d 100644 --- a/stmhal/wdt.h +++ b/stmhal/wdt.h @@ -23,5 +23,9 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ +#ifndef MICROPY_INCLUDED_STMHAL_WDT_H +#define MICROPY_INCLUDED_STMHAL_WDT_H extern const mp_obj_type_t pyb_wdt_type; + +#endif // MICROPY_INCLUDED_STMHAL_WDT_H diff --git a/teensy/Makefile b/teensy/Makefile index 923ea77ecd..575e15e542 100644 --- a/teensy/Makefile +++ b/teensy/Makefile @@ -96,7 +96,6 @@ STM_SRC_C = $(addprefix stmhal/,\ irq.c \ pin.c \ pin_named_pins.c \ - pybstdio.c \ ) STM_SRC_S = $(addprefix stmhal/,\ @@ -107,6 +106,7 @@ LIB_SRC_C = $(addprefix lib/,\ libc/string0.c \ mp-readline/readline.c \ utils/pyexec.c \ + utils/sys_stdio_mphal.c \ ) SRC_TEENSY = $(addprefix core/,\ @@ -207,7 +207,7 @@ GEN_PINS_AF_CONST = $(HEADER_BUILD)/pins_af_const.h GEN_PINS_AF_PY = $(BUILD)/pins_af.py # List of sources for qstr extraction -SRC_QSTR += $(SRC_C) $(STM_SRC_C) +SRC_QSTR += $(SRC_C) $(STM_SRC_C) $(LIB_SRC_C) # Append any auto-generated sources that are needed by sources listed in # SRC_QSTR SRC_QSTR_AUTO_DEPS += diff --git a/teensy/README.md b/teensy/README.md index 3e4a75b9ed..c586853b52 100644 --- a/teensy/README.md +++ b/teensy/README.md @@ -18,7 +18,7 @@ cd teensy ARDUINO=~/arduino-1.0.5 make ``` -To upload micropython to the Teensy 3.1. +To upload MicroPython to the Teensy 3.1. Press the Program button on the Teensy 3.1 ```bash diff --git a/teensy/hal_ftm.c b/teensy/hal_ftm.c index 28992881be..3c031bf6dd 100644 --- a/teensy/hal_ftm.c +++ b/teensy/hal_ftm.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/teensy/hal_ftm.h b/teensy/hal_ftm.h index 3dc15300d7..84fae8312b 100644 --- a/teensy/hal_ftm.h +++ b/teensy/hal_ftm.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,6 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ +#ifndef MICROPY_INCLUDED_TEENSY_HAL_FTM_H +#define MICROPY_INCLUDED_TEENSY_HAL_FTM_H #define FTM0 ((FTM_TypeDef *)&FTM0_SC) #define FTM1 ((FTM_TypeDef *)&FTM1_SC) @@ -181,4 +183,4 @@ 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); - +#endif // MICROPY_INCLUDED_TEENSY_HAL_FTM_H diff --git a/teensy/help.c b/teensy/help.c index 3b3916b943..ebe4bed6bf 100644 --- a/teensy/help.c +++ b/teensy/help.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/teensy/led.c b/teensy/led.c index c7ac8be1ff..c043e43996 100644 --- a/teensy/led.c +++ b/teensy/led.c @@ -81,7 +81,7 @@ void led_toggle(pyb_led_t led) { } /******************************************************************************/ -/* Micro Python bindings */ +/* MicroPython bindings */ void led_obj_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { pyb_led_obj_t *self = self_in; diff --git a/teensy/led.h b/teensy/led.h index 7f4ba18f26..5c45166ef2 100644 --- a/teensy/led.h +++ b/teensy/led.h @@ -1,3 +1,6 @@ +#ifndef MICROPY_INCLUDED_TEENSY_LED_H +#define MICROPY_INCLUDED_TEENSY_LED_H + typedef enum { PYB_LED_BUILTIN = 1, } pyb_led_t; @@ -7,3 +10,5 @@ void led_state(pyb_led_t led, int state); void led_toggle(pyb_led_t led); extern const mp_obj_type_t pyb_led_type; + +#endif // MICROPY_INCLUDED_TEENSY_LED_H diff --git a/teensy/lexermemzip.h b/teensy/lexermemzip.h index e5d4be5eae..cd7326a435 100644 --- a/teensy/lexermemzip.h +++ b/teensy/lexermemzip.h @@ -1,2 +1,6 @@ +#ifndef MICROPY_INCLUDED_TEENSY_LEXERMEMZIP_H +#define MICROPY_INCLUDED_TEENSY_LEXERMEMZIP_H + mp_lexer_t *mp_lexer_new_from_memzip_file(const char *filename); +#endif // MICROPY_INCLUDED_TEENSY_LEXERMEMZIP_H diff --git a/teensy/main.c b/teensy/main.c index 41bbeb5d93..3edaa28a06 100644 --- a/teensy/main.c +++ b/teensy/main.c @@ -266,7 +266,7 @@ soft_reset: // GC init gc_init(&_heap_start, (void*)HEAP_END); - // Micro Python init + // MicroPython init mp_init(); mp_obj_list_init(mp_sys_path, 0); mp_obj_list_append(mp_sys_path, MP_OBJ_NEW_QSTR(MP_QSTR_)); // current dir (or base dir of the script) diff --git a/teensy/modpyb.c b/teensy/modpyb.c index 9f601e327b..deb1f32f97 100644 --- a/teensy/modpyb.c +++ b/teensy/modpyb.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -154,7 +154,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_0(pyb_sync_obj, pyb_sync); /// \function millis() /// Returns the number of milliseconds since the board was last reset. /// -/// The result is always a micropython smallint (31-bit signed number), so +/// The result is always a MicroPython smallint (31-bit signed number), so /// after 2^30 milliseconds (about 12.4 days) this will start to return /// negative numbers. STATIC mp_obj_t pyb_millis(void) { @@ -185,7 +185,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_elapsed_millis_obj, pyb_elapsed_millis); /// \function micros() /// Returns the number of microseconds since the board was last reset. /// -/// The result is always a micropython smallint (31-bit signed number), so +/// The result is always a MicroPython smallint (31-bit signed number), so /// after 2^30 microseconds (about 17.8 minutes) this will start to return /// negative numbers. STATIC mp_obj_t pyb_micros(void) { diff --git a/teensy/mpconfigport.h b/teensy/mpconfigport.h index de30924d9e..69cd69d532 100644 --- a/teensy/mpconfigport.h +++ b/teensy/mpconfigport.h @@ -1,6 +1,6 @@ #include -// options to control how Micro Python is built +// options to control how MicroPython is built #define MICROPY_ALLOC_PATH_MAX (128) #define MICROPY_EMIT_THUMB (1) diff --git a/teensy/reg.h b/teensy/reg.h index 5d1d27443b..0da6378ee7 100644 --- a/teensy/reg.h +++ b/teensy/reg.h @@ -1,3 +1,6 @@ +#ifndef MICROPY_INCLUDED_TEENSY_REG_H +#define MICROPY_INCLUDED_TEENSY_REG_H + typedef struct { const char *name; mp_uint_t offset; @@ -6,3 +9,5 @@ typedef struct { #define REG_ENTRY(st, name) { #name, offsetof(st, name) } mp_obj_t reg_cmd(void *base, reg_t *reg, mp_uint_t num_reg, uint n_args, const mp_obj_t *args); + +#endif // MICROPY_INCLUDED_TEENSY_REG_H diff --git a/teensy/servo.h b/teensy/servo.h index 5f1c87b693..1ad34353d9 100644 --- a/teensy/servo.h +++ b/teensy/servo.h @@ -1,3 +1,6 @@ +#ifndef MICROPY_INCLUDED_TEENSY_SERVO_H +#define MICROPY_INCLUDED_TEENSY_SERVO_H + void servo_init(void); extern const mp_obj_type_t pyb_servo_type; @@ -5,3 +8,4 @@ extern const mp_obj_type_t pyb_servo_type; MP_DECLARE_CONST_FUN_OBJ_2(pyb_servo_set_obj); MP_DECLARE_CONST_FUN_OBJ_2(pyb_pwm_set_obj); +#endif // MICROPY_INCLUDED_TEENSY_SERVO_H diff --git a/teensy/std.h b/teensy/std.h index 42791877a3..ef55d22ddc 100644 --- a/teensy/std.h +++ b/teensy/std.h @@ -1,3 +1,6 @@ +#ifndef MICROPY_INCLUDED_TEENSY_STD_H +#define MICROPY_INCLUDED_TEENSY_STD_H + typedef unsigned int size_t; void __assert_func(void); @@ -18,3 +21,5 @@ char *strcat(char *dest, const char *src); int printf(const char *fmt, ...); int snprintf(char *str, size_t size, const char *fmt, ...); + +#endif // MICROPY_INCLUDED_TEENSY_STD_H diff --git a/teensy/teensy_hal.c b/teensy/teensy_hal.c index 8996c27c97..4fcf999225 100644 --- a/teensy/teensy_hal.c +++ b/teensy/teensy_hal.c @@ -2,6 +2,7 @@ #include #include "py/mpstate.h" +#include "py/runtime.h" #include "py/mphal.h" #include "usb.h" #include "uart.h" @@ -58,3 +59,7 @@ void mp_hal_stdout_tx_strn_cooked(const char *str, size_t len) { void mp_hal_gpio_clock_enable(GPIO_TypeDef *gpio) { } + +void extint_register_pin(const void *pin, uint32_t mode, int hard_irq, mp_obj_t callback_obj) { + mp_not_implemented(NULL); +} diff --git a/teensy/teensy_hal.h b/teensy/teensy_hal.h index 80f320e0c5..162effa85c 100644 --- a/teensy/teensy_hal.h +++ b/teensy/teensy_hal.h @@ -57,6 +57,8 @@ typedef struct { #define GPIO_MODE_AF_PP ((uint32_t)0x00000002) #define GPIO_MODE_AF_OD ((uint32_t)0x00000012) #define GPIO_MODE_ANALOG ((uint32_t)0x00000003) +#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) ||\ diff --git a/teensy/timer.c b/teensy/timer.c index 45bcc2b8fb..bc560d85e0 100644 --- a/teensy/timer.c +++ b/teensy/timer.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -119,7 +119,7 @@ mp_uint_t get_prescaler_shift(mp_int_t prescaler) { } /******************************************************************************/ -/* Micro Python bindings */ +/* MicroPython bindings */ STATIC const mp_obj_type_t pyb_timer_channel_type; diff --git a/teensy/timer.h b/teensy/timer.h index bfa7636f49..75c2e654e2 100644 --- a/teensy/timer.h +++ b/teensy/timer.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,8 +23,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ +#ifndef MICROPY_INCLUDED_TEENSY_TIMER_H +#define MICROPY_INCLUDED_TEENSY_TIMER_H extern const mp_obj_type_t pyb_timer_type; void timer_init0(void); void timer_deinit(void); + +#endif // MICROPY_INCLUDED_TEENSY_TIMER_H diff --git a/teensy/uart.c b/teensy/uart.c index b4c0a4d5b6..3dd2c50519 100644 --- a/teensy/uart.c +++ b/teensy/uart.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -221,7 +221,7 @@ void uart_tx_strn_cooked(pyb_uart_obj_t *uart_obj, const char *str, uint len) { } /******************************************************************************/ -/* Micro Python bindings */ +/* MicroPython bindings */ STATIC void pyb_uart_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { pyb_uart_obj_t *self = self_in; diff --git a/teensy/usb.h b/teensy/usb.h index 949d7a59c0..50fb3ff90d 100644 --- a/teensy/usb.h +++ b/teensy/usb.h @@ -1,3 +1,6 @@ +#ifndef MICROPY_INCLUDED_TEENSY_USB_H +#define MICROPY_INCLUDED_TEENSY_USB_H + bool usb_vcp_is_connected(void); bool usb_vcp_is_enabled(void); int usb_vcp_rx_num(void); @@ -5,3 +8,5 @@ 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_strn_cooked(const char *str, int len); + +#endif // MICROPY_INCLUDED_TEENSY_USB_H diff --git a/tests/README b/tests/README index b028cd062a..3458f36a80 100644 --- a/tests/README +++ b/tests/README @@ -13,6 +13,6 @@ condition a test. The run-tests script uses small scripts in the feature_check directory to check whether each such feature is present, and skips the relevant tests if not. -When creating new tests, anything that relies on float support should go in the +When creating new tests, anything that relies on float support should go in the float/ subdirectory. Anything that relies on import x, where x is not a built-in module, should go in the import/ subdirectory. diff --git a/tests/basics/array1.py b/tests/basics/array1.py index 43f775b797..bad879035c 100644 --- a/tests/basics/array1.py +++ b/tests/basics/array1.py @@ -1,9 +1,8 @@ try: import array except ImportError: - import sys print("SKIP") - sys.exit() + raise SystemExit a = array.array('B', [1, 2, 3]) print(a, len(a)) diff --git a/tests/basics/array_add.py b/tests/basics/array_add.py index 41cd77b428..76ce59f761 100644 --- a/tests/basics/array_add.py +++ b/tests/basics/array_add.py @@ -2,9 +2,8 @@ try: import array except ImportError: - import sys print("SKIP") - sys.exit() + raise SystemExit a1 = array.array('I', [1]) a2 = array.array('I', [2]) diff --git a/tests/basics/array_construct.py b/tests/basics/array_construct.py index cafa57784c..2221de9906 100644 --- a/tests/basics/array_construct.py +++ b/tests/basics/array_construct.py @@ -3,9 +3,8 @@ try: from array import array except ImportError: - import sys print("SKIP") - sys.exit() + raise SystemExit # tuple, list print(array('b', (1, 2))) diff --git a/tests/basics/array_construct2.py b/tests/basics/array_construct2.py index d1c1a6c70b..c305b7f011 100644 --- a/tests/basics/array_construct2.py +++ b/tests/basics/array_construct2.py @@ -1,9 +1,8 @@ try: from array import array except ImportError: - import sys print("SKIP") - sys.exit() + raise SystemExit # construct from something with unknown length (requires generators) print(array('i', (i for i in range(10)))) diff --git a/tests/basics/array_construct_endian.py b/tests/basics/array_construct_endian.py index bf34b05d15..990d7b1ea0 100644 --- a/tests/basics/array_construct_endian.py +++ b/tests/basics/array_construct_endian.py @@ -3,9 +3,8 @@ try: from array import array except ImportError: - import sys print("SKIP") - sys.exit() + raise SystemExit # raw copy from bytes, bytearray print(array('h', b'12')) diff --git a/tests/basics/array_intbig.py b/tests/basics/array_intbig.py index 4a3b2a0d42..5702a8ae63 100644 --- a/tests/basics/array_intbig.py +++ b/tests/basics/array_intbig.py @@ -3,9 +3,8 @@ try: from array import array except ImportError: - import sys print("SKIP") - sys.exit() + raise SystemExit print(array('L', [0, 2**32-1])) print(array('l', [-2**31, 0, 2**31-1])) diff --git a/tests/basics/array_micropython.py b/tests/basics/array_micropython.py index 0c1df0923b..e26ad7ae96 100644 --- a/tests/basics/array_micropython.py +++ b/tests/basics/array_micropython.py @@ -2,9 +2,8 @@ try: import array except ImportError: - import sys print("SKIP") - sys.exit() + raise SystemExit # arrays of objects a = array.array('O') diff --git a/tests/basics/attrtuple1.py b/tests/basics/attrtuple1.py index 597bfc2a32..78a0fbed1b 100644 --- a/tests/basics/attrtuple1.py +++ b/tests/basics/attrtuple1.py @@ -8,9 +8,8 @@ t = sys.implementation try: t.name except AttributeError: - import sys print("SKIP") - sys.exit() + raise SystemExit # test printing of attrtuple diff --git a/tests/basics/builtin_delattr.py b/tests/basics/builtin_delattr.py index 9b38837e44..65bd0f210d 100644 --- a/tests/basics/builtin_delattr.py +++ b/tests/basics/builtin_delattr.py @@ -2,9 +2,8 @@ try: delattr except: - import sys print("SKIP") - sys.exit() + raise SystemExit class A: pass a = A() diff --git a/tests/basics/builtin_exec.py b/tests/basics/builtin_exec.py new file mode 100644 index 0000000000..fd4e65c539 --- /dev/null +++ b/tests/basics/builtin_exec.py @@ -0,0 +1,32 @@ +print(exec("def foo(): return 42")) +print(foo()) + +d = {} +exec("def bar(): return 84", d) +print(d["bar"]()) + +# passing None/dict as args to globals/locals +foo = 11 +exec('print(foo)') +exec('print(foo)', None) +exec('print(foo)', {'foo':3}, None) +exec('print(foo)', None, {'foo':3}) +exec('print(foo)', None, {'bar':3}) +exec('print(foo)', {'bar':3}, locals()) + +try: + exec('print(foo)', {'bar':3}, None) +except NameError: + print('NameError') + +# invalid arg passed to globals +try: + exec('print(1)', 'foo') +except TypeError: + print('TypeError') + +# invalid arg passed to locals +try: + exec('print(1)', None, 123) +except TypeError: + print('TypeError') diff --git a/tests/basics/builtin_hash_gen.py b/tests/basics/builtin_hash_gen.py new file mode 100644 index 0000000000..d42e5ebfbc --- /dev/null +++ b/tests/basics/builtin_hash_gen.py @@ -0,0 +1,7 @@ +# test builtin hash function, on generators + +def gen(): + yield + +print(type(hash(gen))) +print(type(hash(gen()))) diff --git a/tests/basics/builtin_help.py b/tests/basics/builtin_help.py index d554f308d9..6ec39653fe 100644 --- a/tests/basics/builtin_help.py +++ b/tests/basics/builtin_help.py @@ -4,8 +4,7 @@ try: help except NameError: print("SKIP") - import sys - sys.exit() + raise SystemExit help() # no args help(help) # help for a function diff --git a/tests/basics/builtin_minmax.py b/tests/basics/builtin_minmax.py index a925b3fe92..184398e641 100644 --- a/tests/basics/builtin_minmax.py +++ b/tests/basics/builtin_minmax.py @@ -3,9 +3,8 @@ try: min max except: - import sys print("SKIP") - sys.exit() + raise SystemExit print(min(0,1)) print(min(1,0)) diff --git a/tests/basics/builtin_override.py b/tests/basics/builtin_override.py index f3632e59a7..9f91341edd 100644 --- a/tests/basics/builtin_override.py +++ b/tests/basics/builtin_override.py @@ -6,9 +6,8 @@ import builtins try: builtins.abs = lambda x: x + 1 except AttributeError: - import sys print("SKIP") - sys.exit() + raise SystemExit print(abs(1)) diff --git a/tests/basics/builtin_pow3.py b/tests/basics/builtin_pow3.py index dec7253bbd..69b57e5484 100644 --- a/tests/basics/builtin_pow3.py +++ b/tests/basics/builtin_pow3.py @@ -4,9 +4,8 @@ try: print(pow(3, 4, 7)) except NotImplementedError: - import sys print("SKIP") - sys.exit() + raise SystemExit # 3 arg pow is defined to only work on integers try: diff --git a/tests/basics/builtin_pow3_intbig.py b/tests/basics/builtin_pow3_intbig.py index 9f482cbde7..bedc8b36b7 100644 --- a/tests/basics/builtin_pow3_intbig.py +++ b/tests/basics/builtin_pow3_intbig.py @@ -4,9 +4,8 @@ try: print(pow(3, 4, 7)) except NotImplementedError: - import sys print("SKIP") - sys.exit() + raise SystemExit print(pow(555557, 1000002, 1000003)) diff --git a/tests/basics/builtin_property.py b/tests/basics/builtin_property.py index ff4ff073c4..89c3d49364 100644 --- a/tests/basics/builtin_property.py +++ b/tests/basics/builtin_property.py @@ -2,9 +2,8 @@ try: property except: - import sys print("SKIP") - sys.exit() + raise SystemExit # create a property object explicitly property() diff --git a/tests/basics/builtin_range_attrs.py b/tests/basics/builtin_range_attrs.py index 9327c802a5..05d666d139 100644 --- a/tests/basics/builtin_range_attrs.py +++ b/tests/basics/builtin_range_attrs.py @@ -3,9 +3,8 @@ try: range(0).start except AttributeError: - import sys print("SKIP") - sys.exit() + raise SystemExit # attrs print(range(1, 2, 3).start) diff --git a/tests/basics/builtin_reversed.py b/tests/basics/builtin_reversed.py index 59e9c78219..f43505a8bf 100644 --- a/tests/basics/builtin_reversed.py +++ b/tests/basics/builtin_reversed.py @@ -2,9 +2,8 @@ try: reversed except: - import sys print("SKIP") - sys.exit() + raise SystemExit # list print(list(reversed([]))) diff --git a/tests/basics/builtin_sorted.py b/tests/basics/builtin_sorted.py index 68855b61ba..6435f86d0e 100644 --- a/tests/basics/builtin_sorted.py +++ b/tests/basics/builtin_sorted.py @@ -3,9 +3,8 @@ try: sorted set except: - import sys print("SKIP") - sys.exit() + raise SystemExit print(sorted(set(range(100)))) print(sorted(set(range(100)), key=lambda x: x + 100*(x % 2))) diff --git a/tests/basics/bytearray_construct_array.py b/tests/basics/bytearray_construct_array.py index 6d45cafda3..bde5fa08bd 100644 --- a/tests/basics/bytearray_construct_array.py +++ b/tests/basics/bytearray_construct_array.py @@ -2,9 +2,8 @@ try: from array import array except ImportError: - import sys print("SKIP") - sys.exit() + raise SystemExit # arrays print(bytearray(array('b', [1, 2]))) diff --git a/tests/basics/bytearray_construct_endian.py b/tests/basics/bytearray_construct_endian.py index f68f9b89d1..0002f19c5f 100644 --- a/tests/basics/bytearray_construct_endian.py +++ b/tests/basics/bytearray_construct_endian.py @@ -2,9 +2,8 @@ try: from array import array except ImportError: - import sys print("SKIP") - sys.exit() + raise SystemExit # arrays print(bytearray(array('h', [1, 2]))) diff --git a/tests/basics/bytearray_slice_assign.py b/tests/basics/bytearray_slice_assign.py index c4b5c43e33..7f7d1d119a 100644 --- a/tests/basics/bytearray_slice_assign.py +++ b/tests/basics/bytearray_slice_assign.py @@ -2,10 +2,9 @@ try: bytearray()[:] = bytearray() except TypeError: print("SKIP") - import sys - sys.exit() + raise SystemExit -# test slices; only 2 argument version supported by Micro Python at the moment +# test slices; only 2 argument version supported by MicroPython at the moment x = bytearray(range(10)) # Assignment diff --git a/tests/basics/bytes_add_array.py b/tests/basics/bytes_add_array.py index 2b8cbccef5..b17556d83c 100644 --- a/tests/basics/bytes_add_array.py +++ b/tests/basics/bytes_add_array.py @@ -2,9 +2,8 @@ try: import array except ImportError: - import sys print("SKIP") - sys.exit() + raise SystemExit # should be byteorder-neutral print(b"123" + array.array('h', [0x1515])) diff --git a/tests/basics/bytes_add_endian.py b/tests/basics/bytes_add_endian.py index 1bbd0f2c3a..8cfffa7b6a 100644 --- a/tests/basics/bytes_add_endian.py +++ b/tests/basics/bytes_add_endian.py @@ -2,8 +2,7 @@ try: import array except ImportError: - import sys print("SKIP") - sys.exit() + raise SystemExit print(b"123" + array.array('i', [1])) diff --git a/tests/basics/bytes_compare_array.py b/tests/basics/bytes_compare_array.py index ad41d1d375..ad378de70c 100644 --- a/tests/basics/bytes_compare_array.py +++ b/tests/basics/bytes_compare_array.py @@ -1,9 +1,8 @@ try: import array except ImportError: - import sys print("SKIP") - sys.exit() + raise SystemExit print(array.array('b', [1, 2]) in b'\x01\x02\x03') # CPython gives False here diff --git a/tests/basics/bytes_construct_array.py b/tests/basics/bytes_construct_array.py index 72c2d0c585..453eb59010 100644 --- a/tests/basics/bytes_construct_array.py +++ b/tests/basics/bytes_construct_array.py @@ -2,9 +2,8 @@ try: from array import array except ImportError: - import sys print("SKIP") - sys.exit() + raise SystemExit # arrays print(bytes(array('b', [1, 2]))) diff --git a/tests/basics/bytes_construct_endian.py b/tests/basics/bytes_construct_endian.py index 77e0eaaa56..cf1a9f408f 100644 --- a/tests/basics/bytes_construct_endian.py +++ b/tests/basics/bytes_construct_endian.py @@ -3,9 +3,8 @@ try: from array import array except ImportError: - import sys print("SKIP") - sys.exit() + raise SystemExit # arrays print(bytes(array('h', [1, 2]))) diff --git a/tests/basics/bytes_partition.py b/tests/basics/bytes_partition.py index 7d3ffaaaaa..5b503f5443 100644 --- a/tests/basics/bytes_partition.py +++ b/tests/basics/bytes_partition.py @@ -2,8 +2,7 @@ try: str.partition except AttributeError: print("SKIP") - import sys - sys.exit() + raise SystemExit print(b"asdf".partition(b'g')) print(b"asdf".partition(b'a')) diff --git a/tests/basics/class_delattr_setattr.py b/tests/basics/class_delattr_setattr.py index 0d061aee68..190b4875b9 100644 --- a/tests/basics/class_delattr_setattr.py +++ b/tests/basics/class_delattr_setattr.py @@ -6,9 +6,8 @@ try: def __delattr__(self, attr): pass del Test().noexist except AttributeError: - import sys print('SKIP') - sys.exit() + raise SystemExit # this class just prints the calls to see if they were executed class A(): diff --git a/tests/basics/class_descriptor.py b/tests/basics/class_descriptor.py index 7f295f071e..eb88ba7b9c 100644 --- a/tests/basics/class_descriptor.py +++ b/tests/basics/class_descriptor.py @@ -21,9 +21,8 @@ m = Main() try: m.__class__ except AttributeError: - import sys print("SKIP") - sys.exit() + raise SystemExit r = m.Forward if 'Descriptor' in repr(r.__class__): diff --git a/tests/basics/class_new.py b/tests/basics/class_new.py index 0198456b24..9a7072ad03 100644 --- a/tests/basics/class_new.py +++ b/tests/basics/class_new.py @@ -3,9 +3,8 @@ try: # nothing to test. object.__new__ except AttributeError: - import sys print("SKIP") - sys.exit() + raise SystemExit class A: def __new__(cls): print("A.__new__") diff --git a/tests/basics/class_store_class.py b/tests/basics/class_store_class.py index 00a2915869..797f88f852 100644 --- a/tests/basics/class_store_class.py +++ b/tests/basics/class_store_class.py @@ -8,9 +8,8 @@ except ImportError: try: from ucollections import namedtuple except ImportError: - import sys print("SKIP") - sys.exit() + raise SystemExit _DefragResultBase = namedtuple('DefragResult', [ 'foo', 'bar' ]) diff --git a/tests/basics/class_super_object.py b/tests/basics/class_super_object.py index a841d34abb..1fddbb38fd 100644 --- a/tests/basics/class_super_object.py +++ b/tests/basics/class_super_object.py @@ -4,9 +4,8 @@ try: # nothing to test. object.__init__ except AttributeError: - import sys print("SKIP") - sys.exit() + raise SystemExit class Test(object): def __init__(self): diff --git a/tests/basics/dict_fromkeys2.py b/tests/basics/dict_fromkeys2.py index 7ea0cc5b36..dce1e8ef5a 100644 --- a/tests/basics/dict_fromkeys2.py +++ b/tests/basics/dict_fromkeys2.py @@ -1,9 +1,8 @@ try: reversed except: - import sys print("SKIP") - sys.exit() + raise SystemExit # argument to fromkeys has no __len__ d = dict.fromkeys(reversed(range(1))) diff --git a/tests/basics/enumerate.py b/tests/basics/enumerate.py index 3cc1350a0f..4f8239bf72 100644 --- a/tests/basics/enumerate.py +++ b/tests/basics/enumerate.py @@ -1,9 +1,8 @@ try: enumerate except: - import sys print("SKIP") - sys.exit() + raise SystemExit print(list(enumerate([]))) print(list(enumerate([1, 2, 3]))) diff --git a/tests/basics/errno1.py b/tests/basics/errno1.py index eae1bbe1b4..63930b767f 100644 --- a/tests/basics/errno1.py +++ b/tests/basics/errno1.py @@ -4,8 +4,7 @@ try: import uerrno except ImportError: print("SKIP") - import sys - sys.exit() + raise SystemExit # check that constants exist and are integers print(type(uerrno.EIO)) diff --git a/tests/basics/exec1.py b/tests/basics/exec1.py deleted file mode 100644 index 59de5d69a2..0000000000 --- a/tests/basics/exec1.py +++ /dev/null @@ -1,6 +0,0 @@ -print(exec("def foo(): return 42")) -print(foo()) - -d = {} -exec("def bar(): return 84", d) -print(d["bar"]()) diff --git a/tests/basics/filter.py b/tests/basics/filter.py index d0b36733c3..c6d97cf9b5 100644 --- a/tests/basics/filter.py +++ b/tests/basics/filter.py @@ -1,9 +1,8 @@ try: filter except: - import sys print("SKIP") - sys.exit() + raise SystemExit print(list(filter(lambda x: x & 1, range(-3, 4)))) print(list(filter(None, range(-3, 4)))) diff --git a/tests/basics/for_else.py b/tests/basics/for_else.py new file mode 100644 index 0000000000..0bb9415064 --- /dev/null +++ b/tests/basics/for_else.py @@ -0,0 +1,43 @@ +# test for-else statement + +# test optimised range with simple else +for i in range(2): + print(i) +else: + print('else') + +# test optimised range with break over else +for i in range(2): + print(i) + break +else: + print('else') + +# test nested optimised range with continue in the else +for i in range(4): + print(i) + for j in range(4): + pass + else: + continue + break + +# test optimised range with non-constant end value +N = 2 +for i in range(N): + print(i) +else: + print('else') + +# test generic iterator with simple else +for i in [0, 1]: + print(i) +else: + print('else') + +# test generic iterator with break over else +for i in [0, 1]: + print(i) + break +else: + print('else') diff --git a/tests/basics/frozenset1.py b/tests/basics/frozenset1.py index 7a4a335401..7bec24c295 100644 --- a/tests/basics/frozenset1.py +++ b/tests/basics/frozenset1.py @@ -4,8 +4,7 @@ try: frozenset except NameError: print("SKIP") - import sys - sys.exit() + raise SystemExit s = frozenset() print(s) diff --git a/tests/basics/frozenset_add.py b/tests/basics/frozenset_add.py index 415a8c2e13..fe24fbaf1d 100644 --- a/tests/basics/frozenset_add.py +++ b/tests/basics/frozenset_add.py @@ -2,8 +2,7 @@ try: frozenset except NameError: print("SKIP") - import sys - sys.exit() + raise SystemExit s = frozenset({1, 2, 3, 4}) try: diff --git a/tests/basics/frozenset_binop.py b/tests/basics/frozenset_binop.py index 5cc07e9e15..61af07a239 100644 --- a/tests/basics/frozenset_binop.py +++ b/tests/basics/frozenset_binop.py @@ -2,8 +2,7 @@ try: frozenset except NameError: print("SKIP") - import sys - sys.exit() + raise SystemExit sets = [ frozenset(), frozenset({1}), frozenset({1, 2}), frozenset({1, 2, 3}), frozenset({2, 3}), diff --git a/tests/basics/frozenset_copy.py b/tests/basics/frozenset_copy.py index 92e115d346..c90f541a13 100644 --- a/tests/basics/frozenset_copy.py +++ b/tests/basics/frozenset_copy.py @@ -2,8 +2,7 @@ try: frozenset except NameError: print("SKIP") - import sys - sys.exit() + raise SystemExit s = frozenset({1, 2, 3, 4}) t = s.copy() diff --git a/tests/basics/frozenset_difference.py b/tests/basics/frozenset_difference.py index 3d142f9595..bc8b9c21cc 100644 --- a/tests/basics/frozenset_difference.py +++ b/tests/basics/frozenset_difference.py @@ -2,8 +2,7 @@ try: frozenset except NameError: print("SKIP") - import sys - sys.exit() + raise SystemExit l = [1, 2, 3, 4] s = frozenset(l) diff --git a/tests/basics/frozenset_set.py b/tests/basics/frozenset_set.py index b334694b5b..3bf456acfd 100644 --- a/tests/basics/frozenset_set.py +++ b/tests/basics/frozenset_set.py @@ -2,8 +2,7 @@ try: frozenset except NameError: print("SKIP") - import sys - sys.exit() + raise SystemExit # Examples from https://docs.python.org/3/library/stdtypes.html#set # "Instances of set are compared to instances of frozenset based on their diff --git a/tests/basics/fun_error2.py b/tests/basics/fun_error2.py index c4d2c0b64d..2a00396e65 100644 --- a/tests/basics/fun_error2.py +++ b/tests/basics/fun_error2.py @@ -3,8 +3,7 @@ try: enumerate except: print("SKIP") - import sys - sys.exit() + raise SystemExit def test_exc(code, exc): try: diff --git a/tests/basics/gc1.py b/tests/basics/gc1.py index be6c6faed2..dcbe0bfcf6 100644 --- a/tests/basics/gc1.py +++ b/tests/basics/gc1.py @@ -4,8 +4,7 @@ try: import gc except ImportError: print("SKIP") - import sys - sys.exit() + raise SystemExit print(gc.isenabled()) gc.disable() diff --git a/tests/basics/int_bytes.py b/tests/basics/int_bytes.py index 93c00bba10..d1837ea75c 100644 --- a/tests/basics/int_bytes.py +++ b/tests/basics/int_bytes.py @@ -8,3 +8,15 @@ print(int.from_bytes(b"\x00\x01\0\0\0\0\0\0", "little")) # check that extra zero bytes don't change the internal int value print(int.from_bytes(bytes(20), "little") == 0) print(int.from_bytes(b"\x01" + bytes(20), "little") == 1) + +# big-endian conversion +print((10).to_bytes(1, "big")) +print((100).to_bytes(10, "big")) +print(int.from_bytes(b"\0\0\0\0\0\0\0\0\0\x01", "big")) +print(int.from_bytes(b"\x01\0", "big")) + +# negative number of bytes should raise an error +try: + (1).to_bytes(-1, "little") +except ValueError: + print("ValueError") diff --git a/tests/basics/int_bytes_intbig.py b/tests/basics/int_bytes_intbig.py index 0e0ad1cbb7..147362bef1 100644 --- a/tests/basics/int_bytes_intbig.py +++ b/tests/basics/int_bytes_intbig.py @@ -1,4 +1,5 @@ print((2**64).to_bytes(9, "little")) +print((2**64).to_bytes(9, "big")) b = bytes(range(20)) @@ -7,6 +8,7 @@ ib = int.from_bytes(b, "big") print(il) print(ib) print(il.to_bytes(20, "little")) +print(ib.to_bytes(20, "big")) # check that extra zero bytes don't change the internal int value print(int.from_bytes(b + bytes(10), "little") == int.from_bytes(b, "little")) diff --git a/tests/basics/int_bytes_notimpl.py b/tests/basics/int_bytes_notimpl.py deleted file mode 100644 index b149f44966..0000000000 --- a/tests/basics/int_bytes_notimpl.py +++ /dev/null @@ -1,4 +0,0 @@ -try: - print((10).to_bytes(1, "big")) -except Exception as e: - print(type(e)) diff --git a/tests/basics/int_bytes_notimpl.py.exp b/tests/basics/int_bytes_notimpl.py.exp deleted file mode 100644 index 606649a693..0000000000 --- a/tests/basics/int_bytes_notimpl.py.exp +++ /dev/null @@ -1 +0,0 @@ - diff --git a/tests/basics/list_slice_assign.py b/tests/basics/list_slice_assign.py index 1ad1ef27c1..8856157172 100644 --- a/tests/basics/list_slice_assign.py +++ b/tests/basics/list_slice_assign.py @@ -1,4 +1,4 @@ -# test slices; only 2 argument version supported by Micro Python at the moment +# test slices; only 2 argument version supported by MicroPython at the moment x = list(range(10)) # Assignment diff --git a/tests/basics/memoryview1.py b/tests/basics/memoryview1.py index a771acdda9..c4cc6ffab7 100644 --- a/tests/basics/memoryview1.py +++ b/tests/basics/memoryview1.py @@ -2,9 +2,8 @@ try: memoryview except: - import sys print("SKIP") - sys.exit() + raise SystemExit # test reading from bytes b = b'1234' diff --git a/tests/basics/memoryview2.py b/tests/basics/memoryview2.py index 4b5af852b2..06a7be59fd 100644 --- a/tests/basics/memoryview2.py +++ b/tests/basics/memoryview2.py @@ -3,9 +3,8 @@ try: from array import array memoryview except: - import sys print("SKIP") - sys.exit() + raise SystemExit print(list(memoryview(b'\x7f\x80\x81\xff'))) print(list(memoryview(array('b', [0x7f, -0x80])))) diff --git a/tests/basics/memoryview_gc.py b/tests/basics/memoryview_gc.py index 9d4857e362..d366cbbb15 100644 --- a/tests/basics/memoryview_gc.py +++ b/tests/basics/memoryview_gc.py @@ -2,9 +2,8 @@ try: memoryview except: - import sys print("SKIP") - sys.exit() + raise SystemExit b = bytearray(10) m = memoryview(b)[1:] diff --git a/tests/basics/memoryview_intbig.py b/tests/basics/memoryview_intbig.py index 180f15d186..a76d9cbec7 100644 --- a/tests/basics/memoryview_intbig.py +++ b/tests/basics/memoryview_intbig.py @@ -3,9 +3,8 @@ try: from array import array memoryview except: - import sys print("SKIP") - sys.exit() + raise SystemExit print(list(memoryview(array('i', [0x7f000000, -0x80000000])))) print(list(memoryview(array('I', [0x7f000000, 0x80000000, 0x81000000, 0xffffffff])))) diff --git a/tests/basics/namedtuple1.py b/tests/basics/namedtuple1.py index 70372f7cab..15e3b785ed 100644 --- a/tests/basics/namedtuple1.py +++ b/tests/basics/namedtuple1.py @@ -4,9 +4,8 @@ try: except ImportError: from ucollections import namedtuple except ImportError: - import sys print("SKIP") - sys.exit() + raise SystemExit T = namedtuple("Tup", ["foo", "bar"]) # CPython prints fully qualified name, what we don't bother to do so far @@ -25,6 +24,9 @@ for t in T(1, 2), T(bar=1, foo=2): print(isinstance(t, tuple)) +# Create using positional and keyword args +print(T(3, bar=4)) + try: t[0] = 200 except TypeError: diff --git a/tests/basics/object_dict.py b/tests/basics/object_dict.py index e6fb7b3d9c..7bf7094e3a 100644 --- a/tests/basics/object_dict.py +++ b/tests/basics/object_dict.py @@ -1,4 +1,3 @@ -import sys class Foo: @@ -9,6 +8,6 @@ class Foo: o = Foo() if not hasattr(o, "__dict__"): print("SKIP") - sys.exit() + raise SystemExit print(o.__dict__ == {'a': 1, 'b': 'bar'}) diff --git a/tests/basics/object_new.py b/tests/basics/object_new.py index 568feccda4..a9c9482cbb 100644 --- a/tests/basics/object_new.py +++ b/tests/basics/object_new.py @@ -7,9 +7,8 @@ try: # nothing to test. object.__new__ except AttributeError: - import sys print("SKIP") - sys.exit() + raise SystemExit class Foo: diff --git a/tests/basics/op_error_memoryview.py b/tests/basics/op_error_memoryview.py index 658ededc80..8d4403f777 100644 --- a/tests/basics/op_error_memoryview.py +++ b/tests/basics/op_error_memoryview.py @@ -2,9 +2,8 @@ try: memoryview except: - import sys print("SKIP") - sys.exit() + raise SystemExit def test_exc(code, exc): try: diff --git a/tests/basics/op_precedence.py b/tests/basics/op_precedence.py new file mode 100644 index 0000000000..519a2a1137 --- /dev/null +++ b/tests/basics/op_precedence.py @@ -0,0 +1,43 @@ +# see https://docs.python.org/3/reference/expressions.html#operator-precedence + +# '|' is the least binding numeric operator + +# '^' +# OK: 1 | (2 ^ 3) = 1 | 1 = 1 +# BAD: (1 | 2) ^ 3 = 3 ^ 3 = 0 +print(1 | 2 ^ 3) + +# '&' +# OK: 3 ^ (2 & 1) = 3 ^ 0 = 3 +# BAD: (3 ^ 2) & 1 = 1 & 1 = 1 +print(3 ^ 2 & 1) + +# '<<', '>>' +# OK: 2 & (3 << 1) = 2 & 6 = 2 +# BAD: (2 & 3) << 1 = 2 << 1 = 4 +print(2 & 3 << 1) +# OK: 6 & (4 >> 1) = 6 & 2 = 2 +# BAD: (6 & 4) >> 1 = 2 >> 1 = 1 +print(6 & 4 >> 1) + +# '+', '-' +# OK: 1 << (1 + 1) = 1 << 2 = 4 +# BAD: (1 << 1) + 1 = 2 + 1 = 3 +print(1 << 1 + 1) + +# '*', '/', '//', '%' +# OK: 2 + (2 * 2) = 2 + 4 = 6 +# BAD: (2 + 2) * 2 = 4 * 2 = 8 +print(2 + 2 * 2) + +# '+x', '-x', '~x' + +# '**' +# OK: -(2**2) = -4 +# BAD: (-2)**2 = 4 +print(-2**2) +# OK: 2**(-1) = 0.5 +print(2**-1) + +# (expr...) +print((2 + 2) * 2) diff --git a/tests/basics/ordereddict1.py b/tests/basics/ordereddict1.py index 7147968c58..d1633f0bb0 100644 --- a/tests/basics/ordereddict1.py +++ b/tests/basics/ordereddict1.py @@ -5,8 +5,7 @@ except ImportError: from ucollections import OrderedDict except ImportError: print("SKIP") - import sys - sys.exit() + raise SystemExit d = OrderedDict([(10, 20), ("b", 100), (1, 2)]) print(len(d)) diff --git a/tests/basics/ordereddict_eq.py b/tests/basics/ordereddict_eq.py index 2746608772..c69daf8802 100644 --- a/tests/basics/ordereddict_eq.py +++ b/tests/basics/ordereddict_eq.py @@ -5,8 +5,7 @@ except ImportError: from ucollections import OrderedDict except ImportError: print("SKIP") - import sys - sys.exit() + raise SystemExit x = OrderedDict() y = OrderedDict() diff --git a/tests/basics/parser.py b/tests/basics/parser.py index 8fb2a49bf9..626b67ad7a 100644 --- a/tests/basics/parser.py +++ b/tests/basics/parser.py @@ -4,8 +4,7 @@ try: compile except NameError: print("SKIP") - import sys - sys.exit() + raise SystemExit # completely empty string # uPy and CPy differ for this case diff --git a/tests/basics/python34.py b/tests/basics/python34.py index a23f347d64..d5cc59ad6c 100644 --- a/tests/basics/python34.py +++ b/tests/basics/python34.py @@ -20,6 +20,8 @@ def test_syntax(code): print("SyntaxError") test_syntax("f(*a, *b)") # can't have multiple * (in 3.5 we can) test_syntax("f(**a, **b)") # can't have multiple ** (in 3.5 we can) +test_syntax("f(*a, b)") # can't have positional after * +test_syntax("f(**a, b)") # can't have positional after ** test_syntax("() = []") # can't assign to empty tuple (in 3.6 we can) test_syntax("del ()") # can't delete empty tuple (in 3.6 we can) diff --git a/tests/basics/python34.py.exp b/tests/basics/python34.py.exp index f497df3b80..590fc364f4 100644 --- a/tests/basics/python34.py.exp +++ b/tests/basics/python34.py.exp @@ -7,5 +7,7 @@ SyntaxError SyntaxError SyntaxError SyntaxError +SyntaxError +SyntaxError 3.4 3 4 diff --git a/tests/basics/set_type.py b/tests/basics/set_type.py index d790fa062e..787a99e815 100644 --- a/tests/basics/set_type.py +++ b/tests/basics/set_type.py @@ -5,9 +5,8 @@ try: set except NameError: - import sys print("SKIP") - sys.exit() + raise SystemExit print(set) diff --git a/tests/basics/slice_attrs.py b/tests/basics/slice_attrs.py index 67456ff8e6..e85ead4ba9 100644 --- a/tests/basics/slice_attrs.py +++ b/tests/basics/slice_attrs.py @@ -8,9 +8,8 @@ class A: try: t = A()[1:2] except: - import sys print("SKIP") - sys.exit() + raise SystemExit A()[1:2:3] diff --git a/tests/basics/special_methods2.py b/tests/basics/special_methods2.py index 3623b30dcc..ba7cf27cda 100644 --- a/tests/basics/special_methods2.py +++ b/tests/basics/special_methods2.py @@ -100,9 +100,8 @@ cud2 = Cud() try: +cud1 except TypeError: - import sys print("SKIP") - sys.exit() + raise SystemExit # the following require MICROPY_PY_ALL_SPECIAL_METHODS +cud1 diff --git a/tests/basics/string_center.py b/tests/basics/string_center.py index a2739201ac..40e8af4b8d 100644 --- a/tests/basics/string_center.py +++ b/tests/basics/string_center.py @@ -1,9 +1,8 @@ try: str.center except: - import sys print("SKIP") - sys.exit() + raise SystemExit print("foo".center(0)) print("foo".center(1)) diff --git a/tests/basics/string_partition.py b/tests/basics/string_partition.py index b3b2f0907d..bc36388fde 100644 --- a/tests/basics/string_partition.py +++ b/tests/basics/string_partition.py @@ -2,8 +2,7 @@ try: str.partition except AttributeError: print("SKIP") - import sys - sys.exit() + raise SystemExit print("asdf".partition('g')) print("asdf".partition('a')) diff --git a/tests/basics/string_rpartition.py b/tests/basics/string_rpartition.py index 84e0031fb0..6d65dfaf21 100644 --- a/tests/basics/string_rpartition.py +++ b/tests/basics/string_rpartition.py @@ -2,8 +2,7 @@ try: str.partition except AttributeError: print("SKIP") - import sys - sys.exit() + raise SystemExit print("asdf".rpartition('g')) print("asdf".rpartition('a')) diff --git a/tests/basics/string_splitlines.py b/tests/basics/string_splitlines.py index 1d08f6e6d7..c4c3fcb804 100644 --- a/tests/basics/string_splitlines.py +++ b/tests/basics/string_splitlines.py @@ -3,9 +3,8 @@ try: str.splitlines except: - import sys print("SKIP") - sys.exit() + raise SystemExit # test \n as newline print("foo\nbar".splitlines()) diff --git a/tests/basics/struct1.py b/tests/basics/struct1.py index bb6877c785..a442beb1e5 100644 --- a/tests/basics/struct1.py +++ b/tests/basics/struct1.py @@ -4,9 +4,8 @@ except: try: import struct except ImportError: - import sys print("SKIP") - sys.exit() + raise SystemExit print(struct.calcsize("10}".format(s)`. +""" +print('abc'.ljust(10)) diff --git a/tests/extmod/btree1.py b/tests/extmod/btree1.py index 2127554db4..59638ef0a4 100644 --- a/tests/extmod/btree1.py +++ b/tests/extmod/btree1.py @@ -4,8 +4,7 @@ try: import uerrno except ImportError: print("SKIP") - import sys - sys.exit() + raise SystemExit #f = open("_test.db", "w+b") f = uio.BytesIO() diff --git a/tests/extmod/framebuf1.py b/tests/extmod/framebuf1.py index 990b0b120d..2c13665228 100644 --- a/tests/extmod/framebuf1.py +++ b/tests/extmod/framebuf1.py @@ -2,8 +2,7 @@ try: import framebuf except ImportError: print("SKIP") - import sys - sys.exit() + raise SystemExit w = 5 h = 16 diff --git a/tests/extmod/framebuf16.py b/tests/extmod/framebuf16.py index 3aa1d34def..fe81f7f93f 100644 --- a/tests/extmod/framebuf16.py +++ b/tests/extmod/framebuf16.py @@ -2,8 +2,7 @@ try: import framebuf except ImportError: print("SKIP") - import sys - sys.exit() + raise SystemExit def printbuf(): print("--8<--") diff --git a/tests/extmod/framebuf4.py b/tests/extmod/framebuf4.py index 641f5bfc59..8358fa55b9 100644 --- a/tests/extmod/framebuf4.py +++ b/tests/extmod/framebuf4.py @@ -2,8 +2,7 @@ try: import framebuf except ImportError: print("SKIP") - import sys - sys.exit() + raise SystemExit def printbuf(): print("--8<--") diff --git a/tests/extmod/machine1.py b/tests/extmod/machine1.py index e0c5611684..6ff38cc051 100644 --- a/tests/extmod/machine1.py +++ b/tests/extmod/machine1.py @@ -8,8 +8,7 @@ try: machine.mem8 except: print("SKIP") - import sys - sys.exit() + raise SystemExit print(machine.mem8) diff --git a/tests/extmod/machine_pinbase.py b/tests/extmod/machine_pinbase.py index 5e82823ec0..e91775504d 100644 --- a/tests/extmod/machine_pinbase.py +++ b/tests/extmod/machine_pinbase.py @@ -6,8 +6,7 @@ try: machine.PinBase except AttributeError: print("SKIP") - import sys - sys.exit() + raise SystemExit class MyPin(machine.PinBase): diff --git a/tests/extmod/machine_pulse.py b/tests/extmod/machine_pulse.py index 6491b54090..d525974e0c 100644 --- a/tests/extmod/machine_pulse.py +++ b/tests/extmod/machine_pulse.py @@ -7,8 +7,7 @@ try: machine.time_pulse_us except AttributeError: print("SKIP") - import sys - sys.exit() + raise SystemExit class ConstPin(machine.PinBase): diff --git a/tests/extmod/machine_signal.py b/tests/extmod/machine_signal.py index 96b8f43c73..53f4f5890c 100644 --- a/tests/extmod/machine_signal.py +++ b/tests/extmod/machine_signal.py @@ -9,8 +9,7 @@ try: machine.Signal except AttributeError: print("SKIP") - import sys - sys.exit() + raise SystemExit class Pin(machine.PinBase): def __init__(self): diff --git a/tests/extmod/time_ms_us.py b/tests/extmod/time_ms_us.py index 2078f1bb53..31f07d31ba 100644 --- a/tests/extmod/time_ms_us.py +++ b/tests/extmod/time_ms_us.py @@ -1,10 +1,9 @@ -import sys import utime try: utime.sleep_ms except AttributeError: print("SKIP") - sys.exit() + raise SystemExit utime.sleep_ms(1) utime.sleep_us(1) diff --git a/tests/extmod/ubinascii_a2b_base64.py b/tests/extmod/ubinascii_a2b_base64.py index 58eb0b50b6..b35f265910 100644 --- a/tests/extmod/ubinascii_a2b_base64.py +++ b/tests/extmod/ubinascii_a2b_base64.py @@ -4,9 +4,8 @@ try: except ImportError: import binascii except ImportError: - import sys print("SKIP") - sys.exit() + raise SystemExit print(binascii.a2b_base64(b'')) print(binascii.a2b_base64(b'Zg==')) diff --git a/tests/extmod/ubinascii_b2a_base64.py b/tests/extmod/ubinascii_b2a_base64.py index 1c0c30311d..f4bb69fe0c 100644 --- a/tests/extmod/ubinascii_b2a_base64.py +++ b/tests/extmod/ubinascii_b2a_base64.py @@ -4,9 +4,8 @@ try: except ImportError: import binascii except ImportError: - import sys print("SKIP") - sys.exit() + raise SystemExit print(binascii.b2a_base64(b'')) print(binascii.b2a_base64(b'f')) diff --git a/tests/extmod/ubinascii_crc32.py b/tests/extmod/ubinascii_crc32.py index b82c44d6bf..89664a9b36 100644 --- a/tests/extmod/ubinascii_crc32.py +++ b/tests/extmod/ubinascii_crc32.py @@ -4,16 +4,14 @@ try: except ImportError: import binascii except ImportError: - import sys print("SKIP") - sys.exit() + raise SystemExit try: binascii.crc32 except AttributeError: print("SKIP") - import sys - sys.exit() + raise SystemExit print(hex(binascii.crc32(b'The quick brown fox jumps over the lazy dog'))) print(hex(binascii.crc32(b'\x00' * 32))) diff --git a/tests/extmod/ubinascii_hexlify.py b/tests/extmod/ubinascii_hexlify.py index 5d70bda96d..bc99287476 100644 --- a/tests/extmod/ubinascii_hexlify.py +++ b/tests/extmod/ubinascii_hexlify.py @@ -4,9 +4,8 @@ try: except ImportError: import binascii except ImportError: - import sys print("SKIP") - sys.exit() + 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')) diff --git a/tests/extmod/ubinascii_micropython.py b/tests/extmod/ubinascii_micropython.py index 96f566bd14..77084ec9ee 100644 --- a/tests/extmod/ubinascii_micropython.py +++ b/tests/extmod/ubinascii_micropython.py @@ -4,10 +4,12 @@ try: except ImportError: import binascii except ImportError: - import sys print("SKIP") - sys.exit() + raise SystemExit # two arguments supported in uPy but not CPython a = binascii.hexlify(b'123', ':') print(a) + +# zero length buffer +print(binascii.hexlify(b'', b':')) diff --git a/tests/extmod/ubinascii_micropython.py.exp b/tests/extmod/ubinascii_micropython.py.exp index 0ae3d768ef..a195d2602c 100644 --- a/tests/extmod/ubinascii_micropython.py.exp +++ b/tests/extmod/ubinascii_micropython.py.exp @@ -1 +1,2 @@ b'31:32:33' +b'' diff --git a/tests/extmod/ubinascii_unhexlify.py b/tests/extmod/ubinascii_unhexlify.py index e669789ba8..865abfe3a8 100644 --- a/tests/extmod/ubinascii_unhexlify.py +++ b/tests/extmod/ubinascii_unhexlify.py @@ -4,9 +4,8 @@ try: except ImportError: import binascii except ImportError: - import sys print("SKIP") - sys.exit() + raise SystemExit print(binascii.unhexlify(b'0001020304050607')) print(binascii.unhexlify(b'08090a0b0c0d0e0f')) diff --git a/tests/extmod/uctypes_32bit_intbig.py b/tests/extmod/uctypes_32bit_intbig.py index a082dc3704..6b4d3d76cd 100644 --- a/tests/extmod/uctypes_32bit_intbig.py +++ b/tests/extmod/uctypes_32bit_intbig.py @@ -3,9 +3,8 @@ try: import uctypes except ImportError: - import sys print("SKIP") - sys.exit() + raise SystemExit buf = b"12345678abcd" struct = uctypes.struct( diff --git a/tests/extmod/uctypes_array_assign_le.py b/tests/extmod/uctypes_array_assign_le.py index bae467d092..6afa7e0a24 100644 --- a/tests/extmod/uctypes_array_assign_le.py +++ b/tests/extmod/uctypes_array_assign_le.py @@ -1,9 +1,8 @@ try: import uctypes except ImportError: - import sys print("SKIP") - sys.exit() + raise SystemExit desc = { # arr is array at offset 0, of UINT8 elements, array size is 2 diff --git a/tests/extmod/uctypes_array_assign_native_le.py b/tests/extmod/uctypes_array_assign_native_le.py index f0ecc0dad4..a538bf9add 100644 --- a/tests/extmod/uctypes_array_assign_native_le.py +++ b/tests/extmod/uctypes_array_assign_native_le.py @@ -3,11 +3,11 @@ try: import uctypes except ImportError: print("SKIP") - sys.exit() + raise SystemExit if sys.byteorder != "little": print("SKIP") - sys.exit() + raise SystemExit desc = { # arr is array at offset 0, of UINT8 elements, array size is 2 diff --git a/tests/extmod/uctypes_array_assign_native_le_intbig.py b/tests/extmod/uctypes_array_assign_native_le_intbig.py index f29a3b66e9..84dfba0e29 100644 --- a/tests/extmod/uctypes_array_assign_native_le_intbig.py +++ b/tests/extmod/uctypes_array_assign_native_le_intbig.py @@ -3,11 +3,11 @@ try: import uctypes except ImportError: print("SKIP") - sys.exit() + raise SystemExit if sys.byteorder != "little": print("SKIP") - sys.exit() + raise SystemExit desc = { # arr is array at offset 0, of UINT8 elements, array size is 2 diff --git a/tests/extmod/uctypes_bytearray.py b/tests/extmod/uctypes_bytearray.py index bf7845ab26..61c7da271f 100644 --- a/tests/extmod/uctypes_bytearray.py +++ b/tests/extmod/uctypes_bytearray.py @@ -1,9 +1,8 @@ try: import uctypes except ImportError: - import sys print("SKIP") - sys.exit() + raise SystemExit desc = { "arr": (uctypes.ARRAY | 0, uctypes.UINT8 | 2), diff --git a/tests/extmod/uctypes_le.py b/tests/extmod/uctypes_le.py index 829beda58b..7df5ac0909 100644 --- a/tests/extmod/uctypes_le.py +++ b/tests/extmod/uctypes_le.py @@ -1,9 +1,8 @@ try: import uctypes except ImportError: - import sys print("SKIP") - sys.exit() + raise SystemExit desc = { "s0": uctypes.UINT16 | 0, diff --git a/tests/extmod/uctypes_le_float.py b/tests/extmod/uctypes_le_float.py index a61305ba86..84ff2b84cf 100644 --- a/tests/extmod/uctypes_le_float.py +++ b/tests/extmod/uctypes_le_float.py @@ -1,9 +1,8 @@ try: import uctypes except ImportError: - import sys print("SKIP") - sys.exit() + raise SystemExit desc = { "f32": uctypes.FLOAT32 | 0, diff --git a/tests/extmod/uctypes_native_float.py b/tests/extmod/uctypes_native_float.py index 80cb54383d..acef47036d 100644 --- a/tests/extmod/uctypes_native_float.py +++ b/tests/extmod/uctypes_native_float.py @@ -1,9 +1,8 @@ try: import uctypes except ImportError: - import sys print("SKIP") - sys.exit() + raise SystemExit desc = { "f32": uctypes.FLOAT32 | 0, diff --git a/tests/extmod/uctypes_native_le.py b/tests/extmod/uctypes_native_le.py index 5900224d41..8bba03b38c 100644 --- a/tests/extmod/uctypes_native_le.py +++ b/tests/extmod/uctypes_native_le.py @@ -6,11 +6,11 @@ try: import uctypes except ImportError: print("SKIP") - sys.exit() + raise SystemExit if sys.byteorder != "little": print("SKIP") - sys.exit() + raise SystemExit desc = { diff --git a/tests/extmod/uctypes_print.py b/tests/extmod/uctypes_print.py index 76a009dc75..c310238e54 100644 --- a/tests/extmod/uctypes_print.py +++ b/tests/extmod/uctypes_print.py @@ -2,9 +2,8 @@ try: import uctypes except ImportError: - import sys print("SKIP") - sys.exit() + raise SystemExit # we use an address of "0" because we just want to print something deterministic # and don't actually need to set/get any values in the struct diff --git a/tests/extmod/uctypes_ptr_le.py b/tests/extmod/uctypes_ptr_le.py index e8a6243ce1..056e456506 100644 --- a/tests/extmod/uctypes_ptr_le.py +++ b/tests/extmod/uctypes_ptr_le.py @@ -3,11 +3,11 @@ try: import uctypes except ImportError: print("SKIP") - sys.exit() + raise SystemExit if sys.byteorder != "little": print("SKIP") - sys.exit() + raise SystemExit desc = { "ptr": (uctypes.PTR | 0, uctypes.UINT8), diff --git a/tests/extmod/uctypes_ptr_native_le.py b/tests/extmod/uctypes_ptr_native_le.py index 9b016c04d5..24508b1cb4 100644 --- a/tests/extmod/uctypes_ptr_native_le.py +++ b/tests/extmod/uctypes_ptr_native_le.py @@ -3,11 +3,11 @@ try: import uctypes except ImportError: print("SKIP") - sys.exit() + raise SystemExit if sys.byteorder != "little": print("SKIP") - sys.exit() + raise SystemExit desc = { diff --git a/tests/extmod/uctypes_sizeof.py b/tests/extmod/uctypes_sizeof.py index 266cd06943..5a6adb4376 100644 --- a/tests/extmod/uctypes_sizeof.py +++ b/tests/extmod/uctypes_sizeof.py @@ -1,9 +1,8 @@ try: import uctypes except ImportError: - import sys print("SKIP") - sys.exit() + raise SystemExit desc = { # arr is array at offset 0, of UINT8 elements, array size is 2 diff --git a/tests/extmod/uctypes_sizeof_native.py b/tests/extmod/uctypes_sizeof_native.py index f676c8c6de..32c740e773 100644 --- a/tests/extmod/uctypes_sizeof_native.py +++ b/tests/extmod/uctypes_sizeof_native.py @@ -1,9 +1,8 @@ try: import uctypes except ImportError: - import sys print("SKIP") - sys.exit() + raise SystemExit S1 = {} assert uctypes.sizeof(S1) == 0 diff --git a/tests/extmod/uhashlib_sha1.py b/tests/extmod/uhashlib_sha1.py index f12fc649aa..4f7066899a 100644 --- a/tests/extmod/uhashlib_sha1.py +++ b/tests/extmod/uhashlib_sha1.py @@ -1,4 +1,3 @@ -import sys try: import uhashlib as hashlib except ImportError: @@ -8,14 +7,14 @@ except ImportError: # This is neither uPy, nor cPy, so must be uPy with # uhashlib module disabled. print("SKIP") - sys.exit() + raise SystemExit try: hashlib.sha1 except AttributeError: # SHA1 is only available on some ports print("SKIP") - sys.exit() + raise SystemExit sha1 = hashlib.sha1(b'hello') sha1.update(b'world') diff --git a/tests/extmod/uhashlib_sha256.py b/tests/extmod/uhashlib_sha256.py index ff51f2ffa5..3200e8f5cd 100644 --- a/tests/extmod/uhashlib_sha256.py +++ b/tests/extmod/uhashlib_sha256.py @@ -1,4 +1,3 @@ -import sys try: import uhashlib as hashlib except ImportError: @@ -8,7 +7,7 @@ except ImportError: # This is neither uPy, nor cPy, so must be uPy with # uhashlib module disabled. print("SKIP") - sys.exit() + raise SystemExit h = hashlib.sha256() diff --git a/tests/extmod/uheapq1.py b/tests/extmod/uheapq1.py index 4b0e5de57e..7c1fe4e1ec 100644 --- a/tests/extmod/uheapq1.py +++ b/tests/extmod/uheapq1.py @@ -4,9 +4,8 @@ except: try: import heapq except ImportError: - import sys print("SKIP") - sys.exit() + raise SystemExit try: heapq.heappop([]) diff --git a/tests/extmod/ujson_dumps.py b/tests/extmod/ujson_dumps.py index 4a02f51704..d732718019 100644 --- a/tests/extmod/ujson_dumps.py +++ b/tests/extmod/ujson_dumps.py @@ -4,9 +4,8 @@ except ImportError: try: import json except ImportError: - import sys print("SKIP") - sys.exit() + raise SystemExit print(json.dumps(False)) print(json.dumps(True)) diff --git a/tests/extmod/ujson_dumps_extra.py b/tests/extmod/ujson_dumps_extra.py index a52e8224c4..21a388c32d 100644 --- a/tests/extmod/ujson_dumps_extra.py +++ b/tests/extmod/ujson_dumps_extra.py @@ -3,8 +3,7 @@ try: import ujson except ImportError: - import sys print("SKIP") - sys.exit() + raise SystemExit print(ujson.dumps(b'1234')) diff --git a/tests/extmod/ujson_dumps_float.py b/tests/extmod/ujson_dumps_float.py index d949ea6ddd..e8cceb6f1a 100644 --- a/tests/extmod/ujson_dumps_float.py +++ b/tests/extmod/ujson_dumps_float.py @@ -4,8 +4,7 @@ except ImportError: try: import json except ImportError: - import sys print("SKIP") - sys.exit() + raise SystemExit print(json.dumps(1.2)) diff --git a/tests/extmod/ujson_load.py b/tests/extmod/ujson_load.py index 901132a5f8..9725ab2ddc 100644 --- a/tests/extmod/ujson_load.py +++ b/tests/extmod/ujson_load.py @@ -6,9 +6,8 @@ except: from io import StringIO import json except ImportError: - import sys print("SKIP") - sys.exit() + raise SystemExit print(json.load(StringIO('null'))) print(json.load(StringIO('"abc\\u0064e"'))) diff --git a/tests/extmod/ujson_loads.py b/tests/extmod/ujson_loads.py index b2e18e3af7..adba3c068d 100644 --- a/tests/extmod/ujson_loads.py +++ b/tests/extmod/ujson_loads.py @@ -4,9 +4,8 @@ except ImportError: try: import json except ImportError: - import sys print("SKIP") - sys.exit() + raise SystemExit def my_print(o): if isinstance(o, dict): diff --git a/tests/extmod/ujson_loads_float.py b/tests/extmod/ujson_loads_float.py index b20a412ffb..f1b8cc364c 100644 --- a/tests/extmod/ujson_loads_float.py +++ b/tests/extmod/ujson_loads_float.py @@ -4,9 +4,8 @@ except ImportError: try: import json except ImportError: - import sys print("SKIP") - sys.exit() + raise SystemExit def my_print(o): print('%.3f' % o) diff --git a/tests/extmod/urandom_basic.py b/tests/extmod/urandom_basic.py index 885b8517f4..57e6b26cba 100644 --- a/tests/extmod/urandom_basic.py +++ b/tests/extmod/urandom_basic.py @@ -4,9 +4,8 @@ except ImportError: try: import random except ImportError: - import sys print("SKIP") - sys.exit() + raise SystemExit # check getrandbits returns a value within the bit range for b in (1, 2, 3, 4, 16, 32): diff --git a/tests/extmod/urandom_extra.py b/tests/extmod/urandom_extra.py index 925dd0dbcb..f5a34e1687 100644 --- a/tests/extmod/urandom_extra.py +++ b/tests/extmod/urandom_extra.py @@ -4,16 +4,14 @@ except ImportError: try: import random except ImportError: - import sys print("SKIP") - sys.exit() + raise SystemExit try: random.randint except AttributeError: - import sys print('SKIP') - sys.exit() + raise SystemExit print('randrange') for i in range(50): diff --git a/tests/extmod/ure1.py b/tests/extmod/ure1.py index a867f17515..6075990fcb 100644 --- a/tests/extmod/ure1.py +++ b/tests/extmod/ure1.py @@ -4,9 +4,8 @@ except ImportError: try: import re except ImportError: - import sys print("SKIP") - sys.exit() + raise SystemExit r = re.compile(".+") m = r.match("abc") @@ -81,3 +80,6 @@ try: re.compile("*") except: print("Caught invalid regex") + +# bytes objects +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 252df21e30..cfb264bb6d 100644 --- a/tests/extmod/ure_debug.py +++ b/tests/extmod/ure_debug.py @@ -2,8 +2,7 @@ try: import ure except ImportError: - import sys print("SKIP") - sys.exit() + raise SystemExit ure.compile('^a|b[0-9]\w$', ure.DEBUG) diff --git a/tests/extmod/ure_error.py b/tests/extmod/ure_error.py index 3f16f9158c..f52f735c7f 100644 --- a/tests/extmod/ure_error.py +++ b/tests/extmod/ure_error.py @@ -6,9 +6,8 @@ except ImportError: try: import re except ImportError: - import sys print("SKIP") - sys.exit() + raise SystemExit def test_re(r): try: diff --git a/tests/extmod/ure_group.py b/tests/extmod/ure_group.py index 98aae2a736..4e39468c5b 100644 --- a/tests/extmod/ure_group.py +++ b/tests/extmod/ure_group.py @@ -6,9 +6,8 @@ except ImportError: try: import re except ImportError: - import sys print("SKIP") - sys.exit() + raise SystemExit def print_groups(match): print('----') diff --git a/tests/extmod/ure_namedclass.py b/tests/extmod/ure_namedclass.py index e233f17c88..215d09613f 100644 --- a/tests/extmod/ure_namedclass.py +++ b/tests/extmod/ure_namedclass.py @@ -6,9 +6,8 @@ except ImportError: try: import re except ImportError: - import sys print("SKIP") - sys.exit() + raise SystemExit def print_groups(match): print('----') diff --git a/tests/extmod/ure_split.py b/tests/extmod/ure_split.py index 1e411c27c5..a8b9c1686c 100644 --- a/tests/extmod/ure_split.py +++ b/tests/extmod/ure_split.py @@ -4,9 +4,8 @@ except ImportError: try: import re except ImportError: - import sys print("SKIP") - sys.exit() + raise SystemExit r = re.compile(" ") s = r.split("a b c foobar") @@ -27,3 +26,8 @@ print(s) r = re.compile("[a-f]+") s = r.split("0a3b9") print(s) + +# bytes objects +r = re.compile(b"x") +s = r.split(b"fooxbar") +print(s) diff --git a/tests/extmod/ure_split_empty.py b/tests/extmod/ure_split_empty.py index ad6334ebae..76ce97ea67 100644 --- a/tests/extmod/ure_split_empty.py +++ b/tests/extmod/ure_split_empty.py @@ -7,9 +7,8 @@ try: import ure as re except ImportError: - import sys print("SKIP") - sys.exit() + raise SystemExit r = re.compile(" *") s = r.split("a b c foobar") diff --git a/tests/extmod/ure_split_notimpl.py b/tests/extmod/ure_split_notimpl.py index eca3ea512e..da6e9652d0 100644 --- a/tests/extmod/ure_split_notimpl.py +++ b/tests/extmod/ure_split_notimpl.py @@ -1,9 +1,8 @@ try: import ure as re except ImportError: - import sys print("SKIP") - sys.exit() + raise SystemExit r = re.compile('( )') try: diff --git a/tests/extmod/ussl_basic.py b/tests/extmod/ussl_basic.py index e9d435bca8..e8710ed51a 100644 --- a/tests/extmod/ussl_basic.py +++ b/tests/extmod/ussl_basic.py @@ -5,8 +5,7 @@ try: import ussl as ssl except ImportError: print("SKIP") - import sys - sys.exit() + raise SystemExit # create in client mode try: @@ -44,6 +43,14 @@ except OSError as er: # close ss.close() +# close 2nd time +ss.close() + +# read on closed socket +try: + ss.read(10) +except OSError as er: + print('read:', repr(er)) # write on closed socket try: diff --git a/tests/extmod/ussl_basic.py.exp b/tests/extmod/ussl_basic.py.exp index b4dd038606..cb9c51f7a1 100644 --- a/tests/extmod/ussl_basic.py.exp +++ b/tests/extmod/ussl_basic.py.exp @@ -5,4 +5,5 @@ setblocking: NotImplementedError 4 b'' read: OSError(-261,) -write: OSError(-256,) +read: OSError(9,) +write: OSError(9,) diff --git a/tests/extmod/utimeq1.py b/tests/extmod/utimeq1.py index 68d69e25e6..dc7f3b6600 100644 --- a/tests/extmod/utimeq1.py +++ b/tests/extmod/utimeq1.py @@ -5,8 +5,7 @@ try: from utimeq import utimeq except ImportError: print("SKIP") - import sys - sys.exit() + raise SystemExit DEBUG = 0 diff --git a/tests/extmod/utimeq_stable.py b/tests/extmod/utimeq_stable.py index 9f6ba76d4a..9fb522d514 100644 --- a/tests/extmod/utimeq_stable.py +++ b/tests/extmod/utimeq_stable.py @@ -2,8 +2,7 @@ try: from utimeq import utimeq except ImportError: print("SKIP") - import sys - sys.exit() + raise SystemExit h = utimeq(10) diff --git a/tests/extmod/uzlib_decompio.py b/tests/extmod/uzlib_decompio.py index 6f07c048c7..112a825976 100644 --- a/tests/extmod/uzlib_decompio.py +++ b/tests/extmod/uzlib_decompio.py @@ -2,9 +2,8 @@ try: import uzlib as zlib import uio as io except ImportError: - import sys print("SKIP") - sys.exit() + raise SystemExit # Raw DEFLATE bitstream diff --git a/tests/extmod/uzlib_decompio_gz.py b/tests/extmod/uzlib_decompio_gz.py index 7572e96939..02087f7639 100644 --- a/tests/extmod/uzlib_decompio_gz.py +++ b/tests/extmod/uzlib_decompio_gz.py @@ -2,9 +2,8 @@ try: import uzlib as zlib import uio as io except ImportError: - import sys print("SKIP") - sys.exit() + raise SystemExit # gzip bitstream diff --git a/tests/extmod/uzlib_decompress.py b/tests/extmod/uzlib_decompress.py index 10121ee7e1..63247955c9 100644 --- a/tests/extmod/uzlib_decompress.py +++ b/tests/extmod/uzlib_decompress.py @@ -4,9 +4,8 @@ except ImportError: try: import uzlib as zlib except ImportError: - import sys print("SKIP") - sys.exit() + raise SystemExit PATTERNS = [ # Packed results produced by CPy's zlib.compress() diff --git a/tests/extmod/vfs_basic.py b/tests/extmod/vfs_basic.py index fc016b8d5a..4fc67d34b2 100644 --- a/tests/extmod/vfs_basic.py +++ b/tests/extmod/vfs_basic.py @@ -9,8 +9,7 @@ try: uos.mount except (ImportError, AttributeError): print("SKIP") - import sys - sys.exit() + raise SystemExit class Filesystem: @@ -57,8 +56,8 @@ for path in uos.listdir('/'): # stat root dir print(uos.stat('/')) -# statvfs root dir -print(uos.statvfs('/')) +# statvfs root dir; verify that f_namemax has a sensible size +print(uos.statvfs('/')[9] >= 32) # getcwd when in root dir print(uos.getcwd()) diff --git a/tests/extmod/vfs_basic.py.exp b/tests/extmod/vfs_basic.py.exp index f8ecd07eaa..0ae2c2cc97 100644 --- a/tests/extmod/vfs_basic.py.exp +++ b/tests/extmod/vfs_basic.py.exp @@ -1,5 +1,5 @@ (16384, 0, 0, 0, 0, 0, 0, 0, 0, 0) -(0, 0, 0, 0, 0, 0, 0, 0, 0, 4096) +True / 1 mount False False ['test_mnt'] diff --git a/tests/extmod/vfs_fat_fileio1.py b/tests/extmod/vfs_fat_fileio1.py index 9036df7a5c..d19df120b5 100644 --- a/tests/extmod/vfs_fat_fileio1.py +++ b/tests/extmod/vfs_fat_fileio1.py @@ -1,4 +1,3 @@ -import sys try: import uerrno try: @@ -8,13 +7,13 @@ try: import uos except ImportError: print("SKIP") - sys.exit() + raise SystemExit try: uos.VfsFat except AttributeError: print("SKIP") - sys.exit() + raise SystemExit class RAMFS: @@ -46,7 +45,7 @@ try: bdev = RAMFS(50) except MemoryError: print("SKIP") - sys.exit() + raise SystemExit uos.VfsFat.mkfs(bdev) vfs = uos.VfsFat(bdev) diff --git a/tests/extmod/vfs_fat_fileio2.py b/tests/extmod/vfs_fat_fileio2.py index b2a0ba70f4..b5adb75c96 100644 --- a/tests/extmod/vfs_fat_fileio2.py +++ b/tests/extmod/vfs_fat_fileio2.py @@ -1,4 +1,3 @@ -import sys try: import uerrno try: @@ -8,13 +7,13 @@ try: import uos except ImportError: print("SKIP") - sys.exit() + raise SystemExit try: uos.VfsFat except AttributeError: print("SKIP") - sys.exit() + raise SystemExit class RAMFS: @@ -46,7 +45,7 @@ try: bdev = RAMFS(50) except MemoryError: print("SKIP") - sys.exit() + raise SystemExit uos.VfsFat.mkfs(bdev) vfs = uos.VfsFat(bdev) diff --git a/tests/extmod/vfs_fat_more.py b/tests/extmod/vfs_fat_more.py index dacb215535..baec96787b 100644 --- a/tests/extmod/vfs_fat_more.py +++ b/tests/extmod/vfs_fat_more.py @@ -1,4 +1,3 @@ -import sys import uerrno try: try: @@ -8,13 +7,13 @@ try: import uos except ImportError: print("SKIP") - sys.exit() + raise SystemExit try: uos.VfsFat except AttributeError: print("SKIP") - sys.exit() + raise SystemExit class RAMFS: @@ -47,7 +46,7 @@ try: bdev2 = RAMFS(50) except MemoryError: print("SKIP") - sys.exit() + raise SystemExit # first we umount any existing mount points the target may have try: diff --git a/tests/extmod/vfs_fat_oldproto.py b/tests/extmod/vfs_fat_oldproto.py index 3e66758c36..ef4f1da78e 100644 --- a/tests/extmod/vfs_fat_oldproto.py +++ b/tests/extmod/vfs_fat_oldproto.py @@ -1,4 +1,3 @@ -import sys try: import uerrno try: @@ -7,13 +6,13 @@ try: import uos except ImportError: print("SKIP") - sys.exit() + raise SystemExit try: uos.VfsFat except AttributeError: print("SKIP") - sys.exit() + raise SystemExit class RAMFS_OLD: @@ -43,7 +42,7 @@ try: bdev = RAMFS_OLD(50) except MemoryError: print("SKIP") - sys.exit() + raise SystemExit uos.VfsFat.mkfs(bdev) vfs = uos.VfsFat(bdev) diff --git a/tests/extmod/vfs_fat_ramdisk.py b/tests/extmod/vfs_fat_ramdisk.py index fe72a8beff..801c697862 100644 --- a/tests/extmod/vfs_fat_ramdisk.py +++ b/tests/extmod/vfs_fat_ramdisk.py @@ -1,4 +1,3 @@ -import sys try: import uerrno try: @@ -7,13 +6,13 @@ try: import uos except ImportError: print("SKIP") - sys.exit() + raise SystemExit try: uos.VfsFat except AttributeError: print("SKIP") - sys.exit() + raise SystemExit class RAMFS: @@ -45,7 +44,7 @@ try: bdev = RAMFS(50) except MemoryError: print("SKIP") - sys.exit() + raise SystemExit uos.VfsFat.mkfs(bdev) diff --git a/tests/extmod/websocket_basic.py b/tests/extmod/websocket_basic.py index 770836c8eb..9a80503a03 100644 --- a/tests/extmod/websocket_basic.py +++ b/tests/extmod/websocket_basic.py @@ -3,9 +3,8 @@ try: import uerrno import websocket except ImportError: - import sys print("SKIP") - sys.exit() + raise SystemExit # put raw data in the stream and do a websocket read def ws_read(msg, sz): diff --git a/tests/feature_check/float.py b/tests/feature_check/float.py new file mode 100644 index 0000000000..af93f59763 --- /dev/null +++ b/tests/feature_check/float.py @@ -0,0 +1,13 @@ +# detect how many bits of precision the floating point implementation has + +try: + float +except NameError: + print(0) +else: + if float('1.0000001') == float('1.0'): + print(30) + elif float('1e300') == float('inf'): + print(32) + else: + print(64) diff --git a/tests/feature_check/float.py.exp b/tests/feature_check/float.py.exp new file mode 100644 index 0000000000..900731ffd5 --- /dev/null +++ b/tests/feature_check/float.py.exp @@ -0,0 +1 @@ +64 diff --git a/tests/float/array_construct.py b/tests/float/array_construct.py index 7e01fd4768..938675835b 100644 --- a/tests/float/array_construct.py +++ b/tests/float/array_construct.py @@ -3,9 +3,8 @@ try: from array import array except ImportError: - import sys print("SKIP") - sys.exit() + raise SystemExit print(array('f', array('h', [1, 2]))) print(array('d', array('f', [1, 2]))) diff --git a/tests/float/builtin_float_minmax.py b/tests/float/builtin_float_minmax.py index 42cfa63822..266ed133d5 100644 --- a/tests/float/builtin_float_minmax.py +++ b/tests/float/builtin_float_minmax.py @@ -3,31 +3,30 @@ try: min max except: - import sys print("SKIP") - sys.exit() + raise SystemExit -print(min(0,1.0)) -print(min(1.0,0)) -print(min(0,-1.0)) -print(min(-1.0,0)) +print(min(0, 1.0)) +print(min(1.0, 0)) +print(min(0, -1.0)) +print(min(-1.0, 0)) -print(max(0,1.0)) -print(max(1.0,0)) -print(max(0,-1.0)) -print(max(-1.0,0)) +print(max(0, 1.0)) +print(max(1.0, 0)) +print(max(0, -1.0)) +print(max(-1.0, 0)) -print(min(1.5,-1.5)) -print(min(-1.5,1.5)) +print(min(1.5, -1.5)) +print(min(-1.5, 1.5)) -print(max(1.5,-1.5)) -print(max(-1.5,1.5)) +print(max(1.5, -1.5)) +print(max(-1.5, 1.5)) -print(min([1,2.9,4,0,-1,2])) -print(max([1,2.9,4,0,-1,2])) +print(min([1, 2.9, 4, 0, -1, 2])) +print(max([1, 2.9, 4, 0, -1, 2])) -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])) +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/bytearray_construct.py b/tests/float/bytearray_construct.py index db946a99d3..e960d624ec 100644 --- a/tests/float/bytearray_construct.py +++ b/tests/float/bytearray_construct.py @@ -3,8 +3,7 @@ try: from array import array except ImportError: - import sys print("SKIP") - sys.exit() + raise SystemExit print(bytearray(array('f', [1, 2.3]))) diff --git a/tests/float/bytes_construct.py b/tests/float/bytes_construct.py index 8664d7296d..0e4482e436 100644 --- a/tests/float/bytes_construct.py +++ b/tests/float/bytes_construct.py @@ -3,8 +3,7 @@ try: from array import array except ImportError: - import sys print("SKIP") - sys.exit() + raise SystemExit print(bytes(array('f', [1, 2.3]))) diff --git a/tests/float/cmath_fun.py b/tests/float/cmath_fun.py index 3ebcf59186..ae5921c304 100644 --- a/tests/float/cmath_fun.py +++ b/tests/float/cmath_fun.py @@ -4,8 +4,7 @@ try: from cmath import * except ImportError: print("SKIP") - import sys - sys.exit() + raise SystemExit # make sure these constants exist in cmath print("%.5g" % e) diff --git a/tests/float/cmath_fun_special.py b/tests/float/cmath_fun_special.py index 422964dd75..471fda8c0d 100644 --- a/tests/float/cmath_fun_special.py +++ b/tests/float/cmath_fun_special.py @@ -5,8 +5,7 @@ try: log10 except (ImportError, NameError): print("SKIP") - import sys - sys.exit() + raise SystemExit test_values_non_zero = [] base_values = (0.0, 0.5, 1.2345, 10.) diff --git a/tests/float/float_array.py b/tests/float/float_array.py index 8bc9634449..8c8edcff7c 100644 --- a/tests/float/float_array.py +++ b/tests/float/float_array.py @@ -1,9 +1,8 @@ try: from array import array except ImportError: - import sys print("SKIP") - sys.exit() + raise SystemExit def test(a): print(a) diff --git a/tests/float/float_struct.py b/tests/float/float_struct.py index a36ccce38b..c4c186b89e 100644 --- a/tests/float/float_struct.py +++ b/tests/float/float_struct.py @@ -5,9 +5,8 @@ try: except: import struct except ImportError: - import sys print("SKIP") - sys.exit() + raise SystemExit i = 1. + 1/2 # TODO: it looks like '=' format modifier is not yet supported diff --git a/tests/float/int_big_float.py b/tests/float/int_big_float.py index b1a26ca73d..0bd1662186 100644 --- a/tests/float/int_big_float.py +++ b/tests/float/int_big_float.py @@ -18,6 +18,10 @@ print("%.5g" % (i / 1.2)) # this should delegate to complex print("%.5g" % (i * 1.2j).imag) +# negative power should produce float +print("%.5g" % (i ** -1)) +print("%.5g" % ((2 + i - i) ** -3)) + try: i / 0 except ZeroDivisionError: diff --git a/tests/float/math_fun.py b/tests/float/math_fun.py index d9f179587d..2835b9bfbd 100644 --- a/tests/float/math_fun.py +++ b/tests/float/math_fun.py @@ -4,8 +4,7 @@ try: from math import * except ImportError: print("SKIP") - import sys - sys.exit() + raise SystemExit test_values = [-100., -1.23456, -1, -0.5, 0.0, 0.5, 1.23456, 100.] test_values_small = [-10., -1.23456, -1, -0.5, 0.0, 0.5, 1.23456, 10.] # so we don't overflow 32-bit precision @@ -52,7 +51,7 @@ binary_functions = [('copysign', copysign, [(23., 42.), (-23., 42.), (23., -42.) ('atan2', atan2, ((1., 0.), (0., 1.), (2., 0.5), (-3., 5.), (-3., -4.),)), ('fmod', fmod, ((1., 1.), (0., 1.), (2., 0.5), (-3., 5.), (-3., -4.),)), ('ldexp', ldexp, ((1., 0), (0., 1), (2., 2), (3., -2), (-3., -4),)), - ('log', log, ((2., 2.), (3., 2.), (4., 5.), (0., 1.), (1., 0.), (-1., 1.), (1., -1.))), + ('log', log, ((2., 2.), (3., 2.), (4., 5.), (0., 1.), (1., 0.), (-1., 1.), (1., -1.), (2., 1.))), ] for function_name, function, test_vals in binary_functions: @@ -60,5 +59,5 @@ for function_name, function, test_vals in binary_functions: for value1, value2 in test_vals: try: print("{:.5g}".format(function(value1, value2))) - except ValueError as e: - print(str(e)) + except (ValueError, ZeroDivisionError) as e: + print(type(e)) diff --git a/tests/float/math_fun_bool.py b/tests/float/math_fun_bool.py index 57232857ab..30ab14a522 100644 --- a/tests/float/math_fun_bool.py +++ b/tests/float/math_fun_bool.py @@ -4,8 +4,7 @@ try: from math import isfinite, isnan, isinf except ImportError: print("SKIP") - import sys - sys.exit() + raise SystemExit test_values = [1, 0, -1, 1.0, 0.0, -1.0, float('NaN'), float('Inf'), -float('NaN'), -float('Inf')] diff --git a/tests/float/math_fun_int.py b/tests/float/math_fun_int.py index ee54f0995a..5cadbb1e52 100644 --- a/tests/float/math_fun_int.py +++ b/tests/float/math_fun_int.py @@ -4,8 +4,7 @@ try: import math except ImportError: print("SKIP") - import sys - sys.exit() + raise SystemExit for fun in (math.ceil, math.floor, math.trunc): for x in (-1.6, -0.2, 0, 0.6, 1.4, float('inf'), float('nan')): diff --git a/tests/float/math_fun_intbig.py b/tests/float/math_fun_intbig.py index 962c10daa8..697ca7a6db 100644 --- a/tests/float/math_fun_intbig.py +++ b/tests/float/math_fun_intbig.py @@ -4,8 +4,7 @@ try: import math except ImportError: print("SKIP") - import sys - sys.exit() + raise SystemExit for fun in (math.ceil, math.floor, math.trunc): for x in (-1e25, 1e25): diff --git a/tests/float/math_fun_special.py b/tests/float/math_fun_special.py index 32249b4234..c3665a7cd9 100644 --- a/tests/float/math_fun_special.py +++ b/tests/float/math_fun_special.py @@ -5,8 +5,7 @@ try: erf except (ImportError, NameError): print("SKIP") - import sys - sys.exit() + raise SystemExit test_values = [-8., -2.5, -1, -0.5, 0.0, 0.5, 2.5, 8.,] pos_test_values = [0.001, 0.1, 0.5, 1.0, 1.5, 10.,] diff --git a/tests/float/string_format_modulo.py b/tests/float/string_format_modulo.py index 03c8dd00aa..aea534247c 100644 --- a/tests/float/string_format_modulo.py +++ b/tests/float/string_format_modulo.py @@ -44,3 +44,6 @@ print(('%.40g' % 1e-3)[:2]) print(('%.40g' % 1e-4)[:2]) print("%.0g" % 1) # 0 precision 'g' + +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_modulo3.py b/tests/float/string_format_modulo3.py index 5639647865..5d26f25751 100644 --- a/tests/float/string_format_modulo3.py +++ b/tests/float/string_format_modulo3.py @@ -1,4 +1,3 @@ # uPy and CPython outputs differ for the following print("%.1g" % -9.9) # round up 'g' with '-' sign -print("%.1e" % 9.99) # round up with positive exponent -print("%.1e" % 0.999) # round up with negative exponent +print("%.2g" % 99.9) # round up diff --git a/tests/float/string_format_modulo3.py.exp b/tests/float/string_format_modulo3.py.exp index b158c7d7f3..71432b3404 100644 --- a/tests/float/string_format_modulo3.py.exp +++ b/tests/float/string_format_modulo3.py.exp @@ -1,3 +1,2 @@ -10 -1.00e+01 -1.00e-00 +100 diff --git a/tests/import/builtin_import.py b/tests/import/builtin_import.py new file mode 100644 index 0000000000..088f631fcd --- /dev/null +++ b/tests/import/builtin_import.py @@ -0,0 +1,16 @@ +# test calling builtin import function + +# basic test +__import__('builtins') + +# first arg should be a string +try: + __import__(1) +except TypeError: + print('TypeError') + +# level argument should be non-negative +try: + __import__('xyz', None, None, None, -1) +except ValueError: + print('ValueError') diff --git a/tests/import/pkg7/subpkg1/subpkg2/mod3.py b/tests/import/pkg7/subpkg1/subpkg2/mod3.py index 7ed69bdee9..c73e2081f0 100644 --- a/tests/import/pkg7/subpkg1/subpkg2/mod3.py +++ b/tests/import/pkg7/subpkg1/subpkg2/mod3.py @@ -3,8 +3,7 @@ from ...mod2 import bar print(mod1.foo) print(bar) -# when attempting relative import beyond top-level package uPy raises ImportError -# whereas CPython raises a ValueError +# attempted relative import beyond top-level package try: from .... import mod1 except ValueError: diff --git a/tests/io/buffered_writer.py b/tests/io/buffered_writer.py index bb7b4e8dba..c2cedb9912 100644 --- a/tests/io/buffered_writer.py +++ b/tests/io/buffered_writer.py @@ -4,9 +4,8 @@ try: io.BytesIO io.BufferedWriter except AttributeError: - import sys print('SKIP') - sys.exit() + raise SystemExit bts = io.BytesIO() buf = io.BufferedWriter(bts, 8) diff --git a/tests/io/bytesio_cow.py b/tests/io/bytesio_cow.py new file mode 100644 index 0000000000..92654a0003 --- /dev/null +++ b/tests/io/bytesio_cow.py @@ -0,0 +1,20 @@ +# Make sure that write operations on io.BytesIO don't +# change original object it was constructed from. +try: + import uio as io +except ImportError: + import io + +b = b"foobar" + +a = io.BytesIO(b) +a.write(b"1") +print(b) +print(a.getvalue()) + +b = bytearray(b"foobar") + +a = io.BytesIO(b) +a.write(b"1") +print(b) +print(a.getvalue()) diff --git a/tests/io/open_append.py b/tests/io/open_append.py index 2120b72f04..a696823bc5 100644 --- a/tests/io/open_append.py +++ b/tests/io/open_append.py @@ -1,4 +1,3 @@ -import sys try: import uos as os except ImportError: @@ -6,7 +5,7 @@ except ImportError: if not hasattr(os, "unlink"): print("SKIP") - sys.exit() + raise SystemExit # cleanup in case testfile exists try: diff --git a/tests/io/open_plus.py b/tests/io/open_plus.py index 98598ee672..bba96fa2f9 100644 --- a/tests/io/open_plus.py +++ b/tests/io/open_plus.py @@ -1,4 +1,3 @@ -import sys try: import uos as os except ImportError: @@ -6,7 +5,7 @@ except ImportError: if not hasattr(os, "unlink"): print("SKIP") - sys.exit() + raise SystemExit # cleanup in case testfile exists try: diff --git a/tests/io/resource_stream.py b/tests/io/resource_stream.py index 86975f1181..37d985bf16 100644 --- a/tests/io/resource_stream.py +++ b/tests/io/resource_stream.py @@ -5,7 +5,7 @@ try: uio.resource_stream except AttributeError: print('SKIP') - sys.exit() + raise SystemExit buf = uio.resource_stream("data", "file2") print(buf.read()) diff --git a/tests/io/stringio1.py b/tests/io/stringio1.py index fa50f282e1..9f7c1e44ef 100644 --- a/tests/io/stringio1.py +++ b/tests/io/stringio1.py @@ -36,7 +36,7 @@ print(a.read()) a = io.StringIO() a.close() for f in [a.read, a.getvalue, lambda:a.write("")]: - # CPython throws for operations on closed I/O, micropython makes + # CPython throws for operations on closed I/O, MicroPython makes # the underlying string empty unless MICROPY_CPYTHON_COMPAT defined try: f() diff --git a/tests/io/write_ext.py b/tests/io/write_ext.py index 19b616174b..5a6eaa35cf 100644 --- a/tests/io/write_ext.py +++ b/tests/io/write_ext.py @@ -5,9 +5,8 @@ import uio try: uio.BytesIO except AttributeError: - import sys print('SKIP') - sys.exit() + raise SystemExit buf = uio.BytesIO() diff --git a/tests/jni/list.py b/tests/jni/list.py index 6725abb5a0..d58181d0ba 100644 --- a/tests/jni/list.py +++ b/tests/jni/list.py @@ -1,10 +1,9 @@ -import sys import jni try: ArrayList = jni.cls("java/util/ArrayList") except: print("SKIP") - sys.exit() + raise SystemExit l = ArrayList() print(l) diff --git a/tests/jni/object.py b/tests/jni/object.py index 6cf936c4d0..aa67615ec8 100644 --- a/tests/jni/object.py +++ b/tests/jni/object.py @@ -1,10 +1,9 @@ -import sys import jni try: Integer = jni.cls("java/lang/Integer") except: print("SKIP") - sys.exit() + raise SystemExit # Create object i = Integer(42) diff --git a/tests/jni/system_out.py b/tests/jni/system_out.py index 7a1f180306..86c4b9e112 100644 --- a/tests/jni/system_out.py +++ b/tests/jni/system_out.py @@ -1,9 +1,8 @@ -import sys try: import jni System = jni.cls("java/lang/System") except: print("SKIP") - sys.exit() + raise SystemExit System.out.println("Hello, Java!") diff --git a/tests/micropython/heapalloc_bytesio.py b/tests/micropython/heapalloc_bytesio.py index 2a8d50abe3..4aae2abf06 100644 --- a/tests/micropython/heapalloc_bytesio.py +++ b/tests/micropython/heapalloc_bytesio.py @@ -1,9 +1,8 @@ try: import uio except ImportError: - import sys print("SKIP") - sys.exit() + raise SystemExit import micropython diff --git a/tests/micropython/heapalloc_bytesio2.py b/tests/micropython/heapalloc_bytesio2.py new file mode 100644 index 0000000000..cd76f58077 --- /dev/null +++ b/tests/micropython/heapalloc_bytesio2.py @@ -0,0 +1,20 @@ +# Creating BytesIO from immutable object should not immediately +# copy its content. +try: + import uio + import micropython + micropython.mem_total +except (ImportError, AttributeError): + print("SKIP") + raise SystemExit + + +data = b"1234" * 256 + +before = micropython.mem_total() + +buf = uio.BytesIO(data) + +after = micropython.mem_total() + +print(after - before < len(data)) diff --git a/tests/micropython/heapalloc_bytesio2.py.exp b/tests/micropython/heapalloc_bytesio2.py.exp new file mode 100644 index 0000000000..0ca95142bb --- /dev/null +++ b/tests/micropython/heapalloc_bytesio2.py.exp @@ -0,0 +1 @@ +True diff --git a/tests/micropython/heapalloc_iter.py b/tests/micropython/heapalloc_iter.py index 45d3519e45..79461f999a 100644 --- a/tests/micropython/heapalloc_iter.py +++ b/tests/micropython/heapalloc_iter.py @@ -2,9 +2,8 @@ try: import array except ImportError: - import sys print("SKIP") - sys.exit() + raise SystemExit try: from micropython import heap_lock, heap_unlock diff --git a/tests/micropython/heapalloc_traceback.py b/tests/micropython/heapalloc_traceback.py index b3795293f3..f4212b6ce1 100644 --- a/tests/micropython/heapalloc_traceback.py +++ b/tests/micropython/heapalloc_traceback.py @@ -5,9 +5,8 @@ import sys try: import uio except ImportError: - import sys print("SKIP") - sys.exit() + raise SystemExit # preallocate exception instance with some room for a traceback global_exc = StopIteration() diff --git a/tests/micropython/heapalloc_traceback.py.exp b/tests/micropython/heapalloc_traceback.py.exp index facd0af137..291bbd697c 100644 --- a/tests/micropython/heapalloc_traceback.py.exp +++ b/tests/micropython/heapalloc_traceback.py.exp @@ -1,5 +1,5 @@ StopIteration Traceback (most recent call last): - File , line 23, in test + File , line 22, in test StopIteration: diff --git a/tests/micropython/kbd_intr.py b/tests/micropython/kbd_intr.py index a7ce7464b9..879c9a229f 100644 --- a/tests/micropython/kbd_intr.py +++ b/tests/micropython/kbd_intr.py @@ -6,8 +6,7 @@ try: micropython.kbd_intr except AttributeError: print('SKIP') - import sys - sys.exit() + raise SystemExit # just check we can actually call it micropython.kbd_intr(3) diff --git a/tests/micropython/schedule.py b/tests/micropython/schedule.py index 3d584eea4f..74f90cb2de 100644 --- a/tests/micropython/schedule.py +++ b/tests/micropython/schedule.py @@ -6,8 +6,7 @@ try: micropython.schedule except AttributeError: print('SKIP') - import sys - sys.exit() + raise SystemExit # Basic test of scheduling a function. diff --git a/tests/misc/non_compliant.py b/tests/misc/non_compliant.py index 31074ab016..b4c90e9fcf 100644 --- a/tests/misc/non_compliant.py +++ b/tests/misc/non_compliant.py @@ -4,9 +4,8 @@ try: import array import ustruct except ImportError: - import sys print("SKIP") - sys.exit() + raise SystemExit # when super can't find self try: diff --git a/tests/misc/print_exception.py b/tests/misc/print_exception.py index b833a79816..9ab8e728b9 100644 --- a/tests/misc/print_exception.py +++ b/tests/misc/print_exception.py @@ -6,7 +6,7 @@ try: import io except ImportError: print("SKIP") - sys.exit() + raise SystemExit if hasattr(sys, 'print_exception'): print_exception = sys.print_exception diff --git a/tests/misc/recursive_data.py b/tests/misc/recursive_data.py index 3830189453..3b7fa50952 100644 --- a/tests/misc/recursive_data.py +++ b/tests/misc/recursive_data.py @@ -2,9 +2,8 @@ try: import uio as io except ImportError: - import sys print("SKIP") - sys.exit() + raise SystemExit l = [1, 2, 3, None] l[-1] = l diff --git a/tests/misc/recursive_iternext.py b/tests/misc/recursive_iternext.py index d90f177168..edb5a843f2 100644 --- a/tests/misc/recursive_iternext.py +++ b/tests/misc/recursive_iternext.py @@ -6,9 +6,8 @@ try: max zip except: - import sys print("SKIP") - sys.exit() + raise SystemExit # We need to pick an N that is large enough to hit the recursion # limit, but not too large that we run out of heap memory. diff --git a/tests/misc/sys_exc_info.py b/tests/misc/sys_exc_info.py index de5b825624..4bb2c61e89 100644 --- a/tests/misc/sys_exc_info.py +++ b/tests/misc/sys_exc_info.py @@ -3,7 +3,7 @@ try: sys.exc_info except: print("SKIP") - sys.exit() + raise SystemExit def f(): print(sys.exc_info()[0:2]) diff --git a/tests/net_hosted/README b/tests/net_hosted/README new file mode 100644 index 0000000000..724dd61584 --- /dev/null +++ b/tests/net_hosted/README @@ -0,0 +1,11 @@ +This directory contains network tests which require just "peer to peer" +network connection between test host and device under test, instead of +full Internet connection. + +Note that setup for these tests and tests themselves are WIP, and may +not yet fully correspond to the functional specification above. + +So far, these tests are not run as part of the main testsuite and need +to be run seperately (from the main test/ directory): + + ./run-tests net_hosted/*.py diff --git a/tests/net_hosted/accept_nonblock.py b/tests/net_hosted/accept_nonblock.py new file mode 100644 index 0000000000..56f3288e28 --- /dev/null +++ b/tests/net_hosted/accept_nonblock.py @@ -0,0 +1,16 @@ +# test that socket.accept() on a non-blocking socket raises EAGAIN + +try: + import usocket as socket +except: + import socket + +s = socket.socket() +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 +s.close() diff --git a/tests/net_hosted/accept_nonblock.py.exp b/tests/net_hosted/accept_nonblock.py.exp new file mode 100644 index 0000000000..0ca95142bb --- /dev/null +++ b/tests/net_hosted/accept_nonblock.py.exp @@ -0,0 +1 @@ +True diff --git a/tests/net_hosted/accept_timeout.py b/tests/net_hosted/accept_timeout.py new file mode 100644 index 0000000000..44b3b8c7cd --- /dev/null +++ b/tests/net_hosted/accept_timeout.py @@ -0,0 +1,22 @@ +# test that socket.accept() on a socket with timeout raises ETIMEDOUT + +try: + import usocket as socket +except: + import socket + +try: + socket.socket.settimeout +except AttributeError: + print('SKIP') + raise SystemExit + +s = socket.socket() +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 +s.close() diff --git a/tests/net_hosted/accept_timeout.py.exp b/tests/net_hosted/accept_timeout.py.exp new file mode 100644 index 0000000000..0ca95142bb --- /dev/null +++ b/tests/net_hosted/accept_timeout.py.exp @@ -0,0 +1 @@ +True diff --git a/tests/net_hosted/connect_nonblock.py b/tests/net_hosted/connect_nonblock.py new file mode 100644 index 0000000000..6479978bea --- /dev/null +++ b/tests/net_hosted/connect_nonblock.py @@ -0,0 +1,20 @@ +# test that socket.connect() on a non-blocking socket raises EINPROGRESS + +try: + import usocket as socket +except: + import socket + + +def test(peer_addr): + s = socket.socket() + s.setblocking(False) + try: + s.connect(peer_addr) + except OSError as er: + print(er.args[0] == 115) # 115 is EINPROGRESS + s.close() + + +if __name__ == "__main__": + test(socket.getaddrinfo('micropython.org', 80)[0][-1]) diff --git a/tests/net_hosted/connect_nonblock.py.exp b/tests/net_hosted/connect_nonblock.py.exp new file mode 100644 index 0000000000..0ca95142bb --- /dev/null +++ b/tests/net_hosted/connect_nonblock.py.exp @@ -0,0 +1 @@ +True diff --git a/tests/net_inet/README b/tests/net_inet/README new file mode 100644 index 0000000000..9a5614efa6 --- /dev/null +++ b/tests/net_inet/README @@ -0,0 +1,5 @@ +This directory contains network tests which require Internet connection. +Note that these tests are not run as part of the main testsuite and need +to be run seperately (from the main test/ directory): + + ./run-tests net_inet/*.py diff --git a/tests/net_inet/test_tls_sites.py b/tests/net_inet/test_tls_sites.py new file mode 100644 index 0000000000..67345fd0b9 --- /dev/null +++ b/tests/net_inet/test_tls_sites.py @@ -0,0 +1,56 @@ +try: + import usocket as _socket +except: + import _socket +try: + import ussl as ssl +except: + import ssl + + +def test_one(site, opts): + ai = _socket.getaddrinfo(site, 443) + addr = ai[0][-1] + + s = _socket.socket() + + try: + s.connect(addr) + + if "sni" in opts: + s = ssl.wrap_socket(s, server_hostname=opts["host"]) + else: + s = ssl.wrap_socket(s) + + s.write(b"GET / HTTP/1.0\r\n\r\n") + resp = s.read(4096) +# print(resp) + + finally: + s.close() + + +SITES = [ + "google.com", + "www.google.com", + "api.telegram.org", +# "w9rybpfril.execute-api.ap-southeast-2.amazonaws.com", + {"host": "w9rybpfril.execute-api.ap-southeast-2.amazonaws.com", "sni": True}, +] + + +def main(): + for site in SITES: + opts = {} + if isinstance(site, dict): + opts = site + site = opts["host"] + + try: + test_one(site, opts) + print(site, "ok") + except Exception as e: + print(site, repr(e)) + + +main() diff --git a/tests/net_inet/test_tls_sites.py.exp b/tests/net_inet/test_tls_sites.py.exp new file mode 100644 index 0000000000..12732d1fa5 --- /dev/null +++ b/tests/net_inet/test_tls_sites.py.exp @@ -0,0 +1,4 @@ +google.com ok +www.google.com ok +api.telegram.org ok +w9rybpfril.execute-api.ap-southeast-2.amazonaws.com ok diff --git a/tests/pyb/can.py b/tests/pyb/can.py index 7f2d070ecb..0fd8c8368d 100644 --- a/tests/pyb/can.py +++ b/tests/pyb/can.py @@ -2,8 +2,7 @@ try: from pyb import CAN except ImportError: print('SKIP') - import sys - sys.exit() + raise SystemExit import pyb diff --git a/tests/pyb/dac.py b/tests/pyb/dac.py index 942f303543..6f03bbc64d 100644 --- a/tests/pyb/dac.py +++ b/tests/pyb/dac.py @@ -2,8 +2,7 @@ import pyb if not hasattr(pyb, 'DAC'): print('SKIP') - import sys - sys.exit() + raise SystemExit dac = pyb.DAC(1) print(dac) diff --git a/tests/pyb/pyb_f405.py b/tests/pyb/pyb_f405.py index 3c81fe109d..2f161ae099 100644 --- a/tests/pyb/pyb_f405.py +++ b/tests/pyb/pyb_f405.py @@ -4,8 +4,7 @@ import os, pyb if not 'STM32F405' in os.uname().machine: print('SKIP') - import sys - sys.exit() + raise SystemExit print(pyb.freq()) print(type(pyb.rng())) diff --git a/tests/pyb/pyb_f411.py b/tests/pyb/pyb_f411.py index 3286539650..50de302823 100644 --- a/tests/pyb/pyb_f411.py +++ b/tests/pyb/pyb_f411.py @@ -4,7 +4,6 @@ import os, pyb if not 'STM32F411' in os.uname().machine: print('SKIP') - import sys - sys.exit() + raise SystemExit print(pyb.freq()) diff --git a/tests/run-bench-tests b/tests/run-bench-tests index 1e5e7804be..d48b4b7ec5 100755 --- a/tests/run-bench-tests +++ b/tests/run-bench-tests @@ -26,7 +26,7 @@ def run_tests(pyb, test_dict): print(base_test + ":") for test_file in tests: - # run Micro Python + # run MicroPython if pyb is None: # run on PC try: diff --git a/tests/run-tests b/tests/run-tests index f24fc09617..f9c26283dc 100755 --- a/tests/run-tests +++ b/tests/run-tests @@ -239,6 +239,7 @@ def run_tests(pyb, tests, args, base_path="."): skip_tests.add('cmdline/repl_emacs_keys.py') upy_byteorder = run_feature_check(pyb, args, base_path, 'byteorder.py') + upy_float_precision = int(run_feature_check(pyb, args, base_path, 'float.py')) has_complex = run_feature_check(pyb, args, base_path, 'complex.py') == b'complex\n' has_coverage = run_feature_check(pyb, args, base_path, 'coverage.py') == b'coverage\n' cpy_byteorder = subprocess.check_output([CPYTHON3, base_path + '/feature_check/byteorder.py']) @@ -252,6 +253,19 @@ def run_tests(pyb, tests, args, base_path="."): skip_tests.add('thread/stress_heap.py') # has reliability issues skip_tests.add('thread/stress_recurse.py') # has reliability issues + if upy_float_precision == 0: + skip_tests.add('extmod/ujson_dumps_float.py') + skip_tests.add('extmod/ujson_loads_float.py') + skip_tests.add('misc/rge_sm.py') + if upy_float_precision < 32: + skip_tests.add('float/float2int_intbig.py') # requires fp32, there's float2int_fp30_intbig.py instead + skip_tests.add('float/string_format.py') # requires fp32, there's string_format_fp30.py instead + skip_tests.add('float/bytes_construct.py') # requires fp32 + skip_tests.add('float/bytearray_construct.py') # requires fp32 + if upy_float_precision < 64: + skip_tests.add('float/float_divmod.py') # tested by float/float_divmod_relaxed.py instead + skip_tests.add('float/float2int_doubleprec_intbig.py') + if not has_complex: skip_tests.add('float/complex1.py') skip_tests.add('float/complex1_intbig.py') @@ -272,8 +286,6 @@ def run_tests(pyb, tests, args, base_path="."): # Some tests shouldn't be run on pyboard if pyb is not None: skip_tests.add('basics/exception_chain.py') # warning is not printed - skip_tests.add('float/float_divmod.py') # tested by float/float_divmod_relaxed.py instead - skip_tests.add('float/float2int_doubleprec_intbig.py') # requires double precision floating point to work skip_tests.add('micropython/meminfo.py') # output is very different to PC output skip_tests.add('extmod/machine_mem.py') # raw memory access not supported @@ -282,19 +294,12 @@ def run_tests(pyb, tests, args, base_path="."): skip_tests.add('misc/recursion.py') # requires stack checking enabled skip_tests.add('misc/recursive_data.py') # requires stack checking enabled skip_tests.add('misc/recursive_iternext.py') # requires stack checking enabled - skip_tests.add('misc/rge_sm.py') # requires floating point skip_tests.update({'extmod/uctypes_%s.py' % t for t in 'bytearray le native_le ptr_le ptr_native_le sizeof sizeof_native array_assign_le array_assign_native_le'.split()}) # requires uctypes skip_tests.add('extmod/zlibd_decompress.py') # requires zlib - skip_tests.add('extmod/ujson_dumps_float.py') # requires floating point - skip_tests.add('extmod/ujson_loads_float.py') # requires floating point skip_tests.add('extmod/uheapq1.py') # uheapq not supported by WiPy skip_tests.add('extmod/urandom_basic.py') # requires urandom skip_tests.add('extmod/urandom_extra.py') # requires urandom elif args.target == 'esp8266': - skip_tests.add('float/float2int_intbig.py') # requires at least fp32, there's float2int_fp30_intbig.py instead - skip_tests.add('float/string_format.py') # requires at least fp32, there's string_format_fp30.py instead - skip_tests.add('float/bytes_construct.py') # requires fp32 - skip_tests.add('float/bytearray_construct.py') # requires fp32 skip_tests.add('misc/rge_sm.py') # too large elif args.target == 'minimal': skip_tests.add('misc/rge_sm.py') # too large @@ -318,6 +323,7 @@ def run_tests(pyb, tests, args, base_path="."): skip_tests.update({'basics/%s.py' % t for t in 'with_break with_continue with_return'.split()}) # require complete with support skip_tests.add('basics/array_construct2.py') # requires generators skip_tests.add('basics/bool1.py') # seems to randomly fail + skip_tests.add('basics/builtin_hash_gen.py') # requires yield skip_tests.add('basics/class_bind_self.py') # requires yield skip_tests.add('basics/del_deref.py') # requires checking for unbound local skip_tests.add('basics/del_local.py') # requires checking for unbound local @@ -382,7 +388,7 @@ def run_tests(pyb, tests, args, base_path="."): if args.write_exp: continue - # run Micro Python + # run MicroPython output_mupy = run_micropython(pyb, args, test_file) if output_mupy == b'SKIP\n': diff --git a/tests/thread/thread_lock1.py b/tests/thread/thread_lock1.py index ca585ffbb9..ba5c7dff06 100644 --- a/tests/thread/thread_lock1.py +++ b/tests/thread/thread_lock1.py @@ -38,3 +38,9 @@ try: except KeyError: print('KeyError') print(lock.locked()) + +# test that we can't release an unlocked lock +try: + lock.release() +except RuntimeError: + print('RuntimeError') diff --git a/tests/unix/extra_coverage.py b/tests/unix/extra_coverage.py index 870e7d5f22..7a496aa879 100644 --- a/tests/unix/extra_coverage.py +++ b/tests/unix/extra_coverage.py @@ -2,8 +2,7 @@ try: extra_coverage except NameError: print("SKIP") - import sys - sys.exit() + raise SystemExit import uerrno import uio diff --git a/tests/unix/extra_coverage.py.exp b/tests/unix/extra_coverage.py.exp index 4169938870..390ff1669d 100644 --- a/tests/unix/extra_coverage.py.exp +++ b/tests/unix/extra_coverage.py.exp @@ -11,6 +11,7 @@ false true 2147483648 80000000 80000000 +abc # vstr tests sts diff --git a/tests/unix/ffi_callback.py b/tests/unix/ffi_callback.py index 7f8af15b37..23b058bcec 100644 --- a/tests/unix/ffi_callback.py +++ b/tests/unix/ffi_callback.py @@ -1,9 +1,8 @@ -import sys try: import ffi except ImportError: print("SKIP") - sys.exit() + raise SystemExit def ffi_open(names): diff --git a/tests/unix/ffi_float.py b/tests/unix/ffi_float.py index cc12fa7ad9..c92a39bcdc 100644 --- a/tests/unix/ffi_float.py +++ b/tests/unix/ffi_float.py @@ -1,10 +1,9 @@ # test ffi float support -import sys try: import ffi except ImportError: print("SKIP") - sys.exit() + raise SystemExit def ffi_open(names): diff --git a/tests/unix/ffi_float2.py b/tests/unix/ffi_float2.py index d635a27140..721eb4d192 100644 --- a/tests/unix/ffi_float2.py +++ b/tests/unix/ffi_float2.py @@ -1,10 +1,9 @@ # test ffi float support -import sys try: import ffi except ImportError: print("SKIP") - sys.exit() + raise SystemExit def ffi_open(names): @@ -25,7 +24,7 @@ try: tgammaf = libm.func('f', 'tgammaf', 'f') except OSError: print("SKIP") - sys.exit() + raise SystemExit for fun in (tgammaf,): for val in (0.5, 1, 1.0, 1.5, 4, 4.0): diff --git a/tools/codestats.sh b/tools/codestats.sh index c868199e1c..5272f3e9c1 100755 --- a/tools/codestats.sh +++ b/tools/codestats.sh @@ -28,9 +28,9 @@ bin_stmhal=stmhal/build-PYBV10/firmware.elf bin_barearm_1=bare-arm/build/flash.elf bin_barearm_2=bare-arm/build/firmware.elf bin_minimal=minimal/build/firmware.elf -bin_cc3200_1=cc3200/build/LAUNCHXL/application.axf -bin_cc3200_2=cc3200/build/LAUNCHXL/release/application.axf -bin_cc3200_3=cc3200/build/WIPY/release/application.axf +bin_cc3200_1=cc3200/build/LAUNCHXL/application.axf +bin_cc3200_2=cc3200/build/LAUNCHXL/release/application.axf +bin_cc3200_3=cc3200/build/WIPY/release/application.axf # start at zero size; if build fails reuse previous valid size size_unix="0" diff --git a/tools/gen-cpydiff.py b/tools/gen-cpydiff.py index 4b273d97f1..aff5b56e7b 100644 --- a/tools/gen-cpydiff.py +++ b/tools/gen-cpydiff.py @@ -33,7 +33,7 @@ import time import re from collections import namedtuple -# Micropython supports syntax of CPython 3.4 with some features from 3.5, and +# MicroPython supports syntax of CPython 3.4 with some features from 3.5, and # such version should be used to test for differences. If your default python3 # executable is of lower version, you can point MICROPY_CPYTHON3 environment var # to the correct executable. @@ -185,7 +185,9 @@ def gen_rst(results): rst.write(RSTCHARS[min(i, len(RSTCHARS)-1)] * len(section[i])) rst.write('\n\n') class_ = section - rst.write('**' + output.desc + '**\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': diff --git a/tools/mpy_bin2res.py b/tools/mpy_bin2res.py new file mode 100755 index 0000000000..0c89e7e92b --- /dev/null +++ b/tools/mpy_bin2res.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python3 +# +# This tool converts binary resource files passed on the command line +# into a Python source file containing data from these files, which can +# be accessed using standard pkg_resources.resource_stream() function +# from micropython-lib: +# https://github.com/micropython/micropython-lib/tree/master/pkg_resources +# +import sys + +print("R = {") + +for fname in sys.argv[1:]: + with open(fname, "rb") as f: + b = f.read() + print("%r: %r," % (fname, b)) + +print("}") diff --git a/tools/pyboard.py b/tools/pyboard.py index 921ffc52d3..d15f520ac7 100755 --- a/tools/pyboard.py +++ b/tools/pyboard.py @@ -1,4 +1,28 @@ #!/usr/bin/env python +# +# This file is part of the MicroPython project, http://micropython.org/ +# +# The MIT License (MIT) +# +# Copyright (c) 2014-2016 Damien P. George +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. """ pyboard interface diff --git a/unix/Makefile b/unix/Makefile index 006bce0ef2..8672b4f188 100644 --- a/unix/Makefile +++ b/unix/Makefile @@ -30,7 +30,7 @@ ifdef DEBUG CFLAGS += -g COPT = -O0 else -COPT = -Os -fdata-sections -ffunction-sections #-DNDEBUG +COPT = -Os -fdata-sections -ffunction-sections -DNDEBUG # _FORTIFY_SOURCE is a feature in gcc/glibc which is intended to provide extra # security for detecting buffer overflows. Some distros (Ubuntu at the very least) # have it enabled by default. @@ -59,7 +59,7 @@ CFLAGS += -U _FORTIFY_SOURCE endif # On OSX, 'gcc' is a symlink to clang unless a real gcc is installed. -# The unix port of micropython on OSX must be compiled with clang, +# The unix port of MicroPython on OSX must be compiled with clang, # while cross-compile ports require gcc, so we test here for OSX and # if necessary override the value of 'CC' set in py/mkenv.mk ifeq ($(UNAME_S),Darwin) @@ -278,15 +278,15 @@ libffi: cd ../lib/libffi; ./autogen.sh mkdir -p ../lib/libffi/build_dir; cd ../lib/libffi/build_dir; \ ../configure $(CROSS_COMPILE_HOST) --prefix=$$PWD/out --disable-structs CC="$(CC)" CXX="$(CXX)" LD="$(LD)" CFLAGS="-Os -fomit-frame-pointer -fstrict-aliasing -ffast-math -fno-exceptions"; \ - make install-exec-recursive; make -C include install-data-am + $(MAKE) install-exec-recursive; $(MAKE) -C include install-data-am axtls: $(BUILD)/libaxtls.a $(BUILD)/libaxtls.a: ../lib/axtls/README | $(OBJ_DIRS) cd ../lib/axtls; cp config/upyconfig config/.config - cd ../lib/axtls; make oldconfig -B - cd ../lib/axtls; make clean - cd ../lib/axtls; make all CC="$(CC)" LD="$(LD)" + cd ../lib/axtls; $(MAKE) oldconfig -B + cd ../lib/axtls; $(MAKE) clean + cd ../lib/axtls; $(MAKE) all CC="$(CC)" LD="$(LD)" cp ../lib/axtls/_stage/libaxtls.a $@ ../lib/axtls/README: diff --git a/unix/alloc.c b/unix/alloc.c index 54fc1d3c4a..ca12d025b6 100644 --- a/unix/alloc.c +++ b/unix/alloc.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/unix/coverage.c b/unix/coverage.c index 09959525a0..4a9ab194bb 100644 --- a/unix/coverage.c +++ b/unix/coverage.c @@ -154,6 +154,7 @@ STATIC mp_obj_t extra_coverage(void) { mp_printf(&mp_plat_print, "%u\n", 0x80000000); // should print unsigned mp_printf(&mp_plat_print, "%x\n", 0x80000000); // should print unsigned mp_printf(&mp_plat_print, "%X\n", 0x80000000); // should print unsigned + mp_printf(&mp_plat_print, "abc\n%"); // string ends in middle of format specifier } // vstr @@ -189,7 +190,7 @@ STATIC mp_obj_t extra_coverage(void) { mp_printf(&mp_plat_print, "# repl\n"); const char *str; - mp_uint_t len = mp_repl_autocomplete("__n", 3, &mp_plat_print, &str); + size_t len = mp_repl_autocomplete("__n", 3, &mp_plat_print, &str); mp_printf(&mp_plat_print, "%.*s\n", (int)len, str); mp_store_global(MP_QSTR_sys, mp_import_name(MP_QSTR_sys, mp_const_none, MP_OBJ_NEW_SMALL_INT(0))); diff --git a/unix/fdfile.h b/unix/fdfile.h index 8e8e97c795..69a9b6be41 100644 --- a/unix/fdfile.h +++ b/unix/fdfile.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -24,12 +24,11 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ +#ifndef MICROPY_INCLUDED_UNIX_FDFILE_H +#define MICROPY_INCLUDED_UNIX_FDFILE_H #include "py/obj.h" -#ifndef __MICROPY_INCLUDED_UNIX_FILE_H__ -#define __MICROPY_INCLUDED_UNIX_FILE_H__ - typedef struct _mp_obj_fdfile_t { mp_obj_base_t base; int fd; @@ -38,4 +37,4 @@ typedef struct _mp_obj_fdfile_t { extern const mp_obj_type_t mp_type_fileio; extern const mp_obj_type_t mp_type_textio; -#endif // __MICROPY_INCLUDED_UNIX_FILE_H__ +#endif // MICROPY_INCLUDED_UNIX_FDFILE_H diff --git a/unix/file.c b/unix/file.c index a60840c813..f27e23547d 100644 --- a/unix/file.c +++ b/unix/file.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/unix/gccollect.c b/unix/gccollect.c index 4ec8c2bf54..02f6fc91a8 100644 --- a/unix/gccollect.c +++ b/unix/gccollect.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/unix/input.c b/unix/input.c index 4b10350dfc..7d60b46cc7 100644 --- a/unix/input.c +++ b/unix/input.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/unix/input.h b/unix/input.h index 7cbee33c5d..a76b87e644 100644 --- a/unix/input.h +++ b/unix/input.h @@ -1,3 +1,8 @@ +#ifndef MICROPY_INCLUDED_UNIX_INPUT_H +#define MICROPY_INCLUDED_UNIX_INPUT_H + char *prompt(char *p); void prompt_read_history(void); void prompt_write_history(void); + +#endif // MICROPY_INCLUDED_UNIX_INPUT_H diff --git a/unix/main.c b/unix/main.c index 633144c863..e861d7f112 100644 --- a/unix/main.c +++ b/unix/main.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/unix/modffi.c b/unix/modffi.c index 7a35d61ef4..6c5e4f22ee 100644 --- a/unix/modffi.c +++ b/unix/modffi.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -134,7 +134,7 @@ STATIC ffi_type *get_ffi_type(mp_obj_t o_in) } // TODO: Support actual libffi type objects - nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, "Unknown type")); + mp_raise_TypeError("Unknown type"); } STATIC mp_obj_t return_ffi_value(ffi_arg val, char type) @@ -203,7 +203,7 @@ STATIC mp_obj_t make_func(mp_obj_t rettype_in, void *func, mp_obj_t argtypes_in) int res = ffi_prep_cif(&o->cif, FFI_DEFAULT_ABI, nparams, char2ffi_type(*rettype), o->params); if (res != FFI_OK) { - nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Error in ffi_prep_cif")); + mp_raise_ValueError("Error in ffi_prep_cif"); } return MP_OBJ_FROM_PTR(o); @@ -261,12 +261,12 @@ STATIC mp_obj_t mod_ffi_callback(mp_obj_t rettype_in, mp_obj_t func_in, mp_obj_t int res = ffi_prep_cif(&o->cif, FFI_DEFAULT_ABI, nparams, char2ffi_type(*rettype), o->params); if (res != FFI_OK) { - nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Error in ffi_prep_cif")); + mp_raise_ValueError("Error in ffi_prep_cif"); } res = ffi_prep_closure_loc(o->clo, &o->cif, call_py_func, MP_OBJ_TO_PTR(func_in), o->func); if (res != FFI_OK) { - nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "ffi_prep_closure_loc")); + mp_raise_ValueError("ffi_prep_closure_loc"); } return MP_OBJ_FROM_PTR(o); diff --git a/unix/modjni.c b/unix/modjni.c index b474e26ea7..540964d446 100644 --- a/unix/modjni.c +++ b/unix/modjni.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -159,7 +159,7 @@ STATIC void jclass_attr(mp_obj_t self_in, qstr attr_in, mp_obj_t *dest) { STATIC mp_obj_t jclass_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp_obj_t *args) { if (n_kw != 0) { - nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, "kwargs not supported")); + mp_raise_TypeError("kwargs not supported"); } mp_obj_jclass_t *self = self_in; @@ -168,9 +168,9 @@ STATIC mp_obj_t jclass_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const return call_method(self->cls, NULL, methods, true, n_args, args); } -STATIC const mp_map_elem_t jclass_locals_dict_table[] = { -// { MP_OBJ_NEW_QSTR(MP_QSTR_get), (mp_obj_t)&ffivar_get_obj }, -// { MP_OBJ_NEW_QSTR(MP_QSTR_set), (mp_obj_t)&ffivar_set_obj }, +STATIC const mp_rom_map_elem_t jclass_locals_dict_table[] = { +// { MP_ROM_QSTR(MP_QSTR_get), MP_ROM_PTR(&ffivar_get_obj) }, +// { MP_ROM_QSTR(MP_QSTR_set), MP_ROM_PTR(&ffivar_set_obj) }, }; STATIC MP_DEFINE_CONST_DICT(jclass_locals_dict, jclass_locals_dict_table); @@ -181,7 +181,7 @@ STATIC const mp_obj_type_t jclass_type = { .print = jclass_print, .attr = jclass_attr, .call = jclass_call, - .locals_dict = (mp_obj_t)&jclass_locals_dict, + .locals_dict = (mp_obj_dict_t*)&jclass_locals_dict, }; STATIC mp_obj_t new_jclass(jclass jc) { @@ -331,7 +331,7 @@ STATIC const mp_obj_type_t jobject_type = { .attr = jobject_attr, .subscr = jobject_subscr, .getiter = subscr_getiter, -// .locals_dict = (mp_obj_t)&jobject_locals_dict, +// .locals_dict = (mp_obj_dict_t*)&jobject_locals_dict, }; STATIC mp_obj_t new_jobject(jobject jo) { @@ -433,7 +433,7 @@ STATIC bool py2jvalue(const char **jtypesig, mp_obj_t arg, jvalue *out) { } out->l = NULL; } else { - nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, "arg type not supported")); + mp_raise_TypeError("arg type not supported"); } *jtypesig = arg_type; @@ -534,7 +534,7 @@ STATIC mp_obj_t call_method(jobject obj, const char *name, jarray methods, bool ret = new_jobject(res); } else { JJ(ReleaseStringUTFChars, name_o, decl); - nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, "cannot handle return type")); + mp_raise_TypeError("cannot handle return type"); } JJ(ReleaseStringUTFChars, name_o, decl); @@ -550,13 +550,13 @@ next_method: JJ(DeleteLocalRef, meth); } - nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, "method not found")); + mp_raise_TypeError("method not found"); } STATIC mp_obj_t jmethod_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp_obj_t *args) { if (n_kw != 0) { - nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, "kwargs not supported")); + mp_raise_TypeError("kwargs not supported"); } mp_obj_jmethod_t *self = self_in; @@ -578,7 +578,7 @@ STATIC const mp_obj_type_t jmethod_type = { .print = jmethod_print, .call = jmethod_call, // .attr = jobject_attr, -// .locals_dict = (mp_obj_t)&jobject_locals_dict, +// .locals_dict = (mp_obj_dict_t*)&jobject_locals_dict, }; #ifdef __ANDROID__ @@ -602,13 +602,13 @@ STATIC void create_jvm() { void *libjvm = dlopen(LIBJVM_SO, RTLD_NOW | RTLD_GLOBAL); if (!libjvm) { - nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_OSError, "unable to load libjvm.so, use LD_LIBRARY_PATH")); + 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 st = _JNI_CreateJavaVM(&jvm, (void**)&env, &args); if (st < 0 || !env) { - nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_OSError, "unable to create JVM")); + mp_raise_msg(&mp_type_OSError, "unable to create JVM"); } Class_class = JJ(FindClass, "java/lang/Class"); @@ -707,11 +707,11 @@ STATIC mp_obj_t mod_jni_env() { } MP_DEFINE_CONST_FUN_OBJ_0(mod_jni_env_obj, mod_jni_env); -STATIC const mp_map_elem_t mp_module_jni_globals_table[] = { - { MP_OBJ_NEW_QSTR(MP_QSTR___name__), MP_OBJ_NEW_QSTR(MP_QSTR_jni) }, - { MP_OBJ_NEW_QSTR(MP_QSTR_cls), (mp_obj_t)&mod_jni_cls_obj }, - { MP_OBJ_NEW_QSTR(MP_QSTR_array), (mp_obj_t)&mod_jni_array_obj }, - { MP_OBJ_NEW_QSTR(MP_QSTR_env), (mp_obj_t)&mod_jni_env_obj }, +STATIC const mp_rom_map_elem_t mp_module_jni_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_jni) }, + { MP_ROM_QSTR(MP_QSTR_cls), MP_ROM_PTR(&mod_jni_cls_obj) }, + { MP_ROM_QSTR(MP_QSTR_array), MP_ROM_PTR(&mod_jni_array_obj) }, + { MP_ROM_QSTR(MP_QSTR_env), MP_ROM_PTR(&mod_jni_env_obj) }, }; STATIC MP_DEFINE_CONST_DICT(mp_module_jni_globals, mp_module_jni_globals_table); diff --git a/unix/modmachine.c b/unix/modmachine.c index 33a3b098e4..48dddec0ae 100644 --- a/unix/modmachine.c +++ b/unix/modmachine.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/unix/modos.c b/unix/modos.c index 8e746c1637..8b5d5790f3 100644 --- a/unix/modos.c +++ b/unix/modos.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/unix/modsocket.c b/unix/modsocket.c index c7be6461e8..c612f870d9 100644 --- a/unix/modsocket.c +++ b/unix/modsocket.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -391,7 +391,6 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_socket_htons_obj, mod_socket_htons); STATIC mp_obj_t mod_socket_gethostbyname(mp_obj_t arg) { - assert(MP_OBJ_IS_TYPE(arg, &mp_type_str)); const char *s = mp_obj_str_get_str(arg); struct hostent *h = gethostbyname(s); if (h == NULL) { @@ -441,9 +440,7 @@ STATIC mp_obj_t mod_socket_inet_ntop(mp_obj_t family_in, mp_obj_t binaddr_in) { STATIC MP_DEFINE_CONST_FUN_OBJ_2(mod_socket_inet_ntop_obj, mod_socket_inet_ntop); STATIC mp_obj_t mod_socket_getaddrinfo(size_t n_args, const mp_obj_t *args) { - // TODO: Implement all args - assert(n_args >= 2 && n_args <= 4); - assert(MP_OBJ_IS_STR(args[0])); + // TODO: Implement 5th and 6th args const char *host = mp_obj_str_get_str(args[0]); const char *serv = NULL; @@ -510,7 +507,7 @@ STATIC mp_obj_t mod_socket_getaddrinfo(size_t n_args, const mp_obj_t *args) { freeaddrinfo(addr_list); return list; } -STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_socket_getaddrinfo_obj, 2, 6, mod_socket_getaddrinfo); +STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_socket_getaddrinfo_obj, 2, 4, mod_socket_getaddrinfo); STATIC mp_obj_t mod_socket_sockaddr(mp_obj_t sockaddr_in) { mp_buffer_info_t bufinfo; diff --git a/unix/modtermios.c b/unix/modtermios.c index 5e82e772ac..fe19aac83c 100644 --- a/unix/modtermios.c +++ b/unix/modtermios.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/unix/modtime.c b/unix/modtime.c index 080d321ee4..a74b81f374 100644 --- a/unix/modtime.c +++ b/unix/modtime.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -125,21 +125,40 @@ STATIC mp_obj_t mod_time_sleep(mp_obj_t arg) { } STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_time_sleep_obj, mod_time_sleep); -STATIC mp_obj_t mod_time_strftime(size_t n_args, const mp_obj_t *args) { +STATIC mp_obj_t mod_time_localtime(size_t n_args, const mp_obj_t *args) { time_t t; - if (n_args == 1) { + if (n_args == 0) { t = time(NULL); } else { - // CPython requires passing struct tm, but we allow to pass time_t - // (and don't support struct tm so far). - t = mp_obj_get_int(args[1]); + #if MICROPY_PY_BUILTINS_FLOAT + mp_float_t val = mp_obj_get_float(args[0]); + t = (time_t)MICROPY_FLOAT_C_FUN(trunc)(val); + #else + t = mp_obj_get_int(args[0]); + #endif } struct tm *tm = localtime(&t); - char buf[32]; - size_t sz = strftime(buf, sizeof(buf), mp_obj_str_get_str(args[0]), tm); - return mp_obj_new_str(buf, sz, false); + + mp_obj_t ret = mp_obj_new_tuple(9, NULL); + + mp_obj_tuple_t *tuple = MP_OBJ_TO_PTR(ret); + tuple->items[0] = MP_OBJ_NEW_SMALL_INT(tm->tm_year + 1900); + tuple->items[1] = MP_OBJ_NEW_SMALL_INT(tm->tm_mon + 1); + tuple->items[2] = MP_OBJ_NEW_SMALL_INT(tm->tm_mday); + tuple->items[3] = MP_OBJ_NEW_SMALL_INT(tm->tm_hour); + tuple->items[4] = MP_OBJ_NEW_SMALL_INT(tm->tm_min); + tuple->items[5] = MP_OBJ_NEW_SMALL_INT(tm->tm_sec); + int wday = tm->tm_wday - 1; + if (wday < 0) { + wday = 6; + } + tuple->items[6] = MP_OBJ_NEW_SMALL_INT(wday); + tuple->items[7] = MP_OBJ_NEW_SMALL_INT(tm->tm_yday + 1); + tuple->items[8] = MP_OBJ_NEW_SMALL_INT(tm->tm_isdst); + + return ret; } -STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_time_strftime_obj, 1, 2, mod_time_strftime); +STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_time_localtime_obj, 0, 1, mod_time_localtime); STATIC const mp_rom_map_elem_t mp_module_time_globals_table[] = { { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_utime) }, @@ -153,7 +172,7 @@ STATIC const mp_rom_map_elem_t mp_module_time_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_ticks_cpu), MP_ROM_PTR(&mp_utime_ticks_cpu_obj) }, { MP_ROM_QSTR(MP_QSTR_ticks_add), MP_ROM_PTR(&mp_utime_ticks_add_obj) }, { MP_ROM_QSTR(MP_QSTR_ticks_diff), MP_ROM_PTR(&mp_utime_ticks_diff_obj) }, - { MP_ROM_QSTR(MP_QSTR_strftime), MP_ROM_PTR(&mod_time_strftime_obj) }, + { MP_ROM_QSTR(MP_QSTR_localtime), MP_ROM_PTR(&mod_time_localtime_obj) }, }; STATIC MP_DEFINE_CONST_DICT(mp_module_time_globals, mp_module_time_globals_table); diff --git a/unix/moduselect.c b/unix/moduselect.c index 37a3a33b28..ba1c195ef4 100644 --- a/unix/moduselect.c +++ b/unix/moduselect.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/unix/mpconfigport.h b/unix/mpconfigport.h index 047121fe66..b557f3d448 100644 --- a/unix/mpconfigport.h +++ b/unix/mpconfigport.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -24,7 +24,7 @@ * THE SOFTWARE. */ -// options to control how Micro Python is built +// options to control how MicroPython is built #define MICROPY_ALLOC_PATH_MAX (PATH_MAX) #define MICROPY_PERSISTENT_CODE_LOAD (1) diff --git a/unix/mpconfigport.mk b/unix/mpconfigport.mk index 8819546bfe..f0aa955c0c 100644 --- a/unix/mpconfigport.mk +++ b/unix/mpconfigport.mk @@ -4,7 +4,7 @@ MICROPY_FORCE_32BIT = 0 # This variable can take the following values: -# 0 - no readline, just simple input +# 0 - no readline, just simple stdin input # 1 - use MicroPython version of readline MICROPY_USE_READLINE = 1 @@ -23,9 +23,15 @@ MICROPY_PY_SOCKET = 1 # ffi module requires libffi (libffi-dev Debian package) MICROPY_PY_FFI = 1 -# ussl module requires axtls +# ussl module requires one of the TLS libraries below MICROPY_PY_USSL = 1 +# axTLS has minimal size and fully integrated with MicroPython, but +# implements only a subset of modern TLS functionality, so may have +# problems with some servers. MICROPY_SSL_AXTLS = 1 +# mbedTLS is more up to date and complete implementation, but also +# more bloated. Configuring and building of mbedTLS should be done +# outside of MicroPython, it can just link with mbedTLS library. MICROPY_SSL_MBEDTLS = 0 # jni module requires JVM/JNI diff --git a/unix/mpconfigport_fast.h b/unix/mpconfigport_fast.h index b5be9f334f..442159eb4f 100644 --- a/unix/mpconfigport_fast.h +++ b/unix/mpconfigport_fast.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/unix/mpconfigport_minimal.h b/unix/mpconfigport_minimal.h index b4d9f81439..e37605eabf 100644 --- a/unix/mpconfigport_minimal.h +++ b/unix/mpconfigport_minimal.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -24,7 +24,7 @@ * THE SOFTWARE. */ -// options to control how Micro Python is built +// options to control how MicroPython is built #define MICROPY_ALLOC_QSTR_CHUNK_INIT (64) #define MICROPY_ALLOC_PARSE_RULE_INIT (8) diff --git a/unix/mphalport.h b/unix/mphalport.h index cf227872f9..ff7a51567c 100644 --- a/unix/mphalport.h +++ b/unix/mphalport.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/unix/mpthreadport.h b/unix/mpthreadport.h index 51cf8d7860..b158ed5bcc 100644 --- a/unix/mpthreadport.h +++ b/unix/mpthreadport.h @@ -23,8 +23,6 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -#ifndef __MICROPY_INCLUDED_UNIX_MPTHREADPORT_H__ -#define __MICROPY_INCLUDED_UNIX_MPTHREADPORT_H__ #include @@ -32,5 +30,3 @@ typedef pthread_mutex_t mp_thread_mutex_t; void mp_thread_init(void); void mp_thread_gc_others(void); - -#endif // __MICROPY_INCLUDED_UNIX_MPTHREADPORT_H__ diff --git a/unix/qstrdefsport.h b/unix/qstrdefsport.h index 8ab2db58f5..ebfaa6ccab 100644 --- a/unix/qstrdefsport.h +++ b/unix/qstrdefsport.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/unix/unix_mphal.c b/unix/unix_mphal.c index 800484498e..02cdbea11f 100644 --- a/unix/unix_mphal.c +++ b/unix/unix_mphal.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/windows/fmode.h b/windows/fmode.h index 23d6d3d54d..c661c84d0c 100644 --- a/windows/fmode.h +++ b/windows/fmode.h @@ -23,9 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - -#ifndef __MICROPY_INCLUDED_WINDOWS_FMODE_H__ -#define __MICROPY_INCLUDED_WINDOWS_FMODE_H__ +#ifndef MICROPY_INCLUDED_WINDOWS_FMODE_H +#define MICROPY_INCLUDED_WINDOWS_FMODE_H // Treat files opened by open() as binary. No line ending translation is done. void set_fmode_binary(void); @@ -35,4 +34,4 @@ void set_fmode_binary(void); // When writing to the file \n will be converted into \r\n. void set_fmode_text(void); -#endif +#endif // MICROPY_INCLUDED_WINDOWS_FMODE_H diff --git a/windows/init.c b/windows/init.c index 6690923478..09fa10417b 100644 --- a/windows/init.c +++ b/windows/init.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/windows/init.h b/windows/init.h index 69e577689e..c6fddb257e 100644 --- a/windows/init.h +++ b/windows/init.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,6 +23,10 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ +#ifndef MICROPY_INCLUDED_WINDOWS_INIT_H +#define MICROPY_INCLUDED_WINDOWS_INIT_H void init(void); void deinit(void); + +#endif // MICROPY_INCLUDED_WINDOWS_INIT_H diff --git a/windows/mpconfigport.h b/windows/mpconfigport.h index f2f6cbd323..c4e6ba131a 100644 --- a/windows/mpconfigport.h +++ b/windows/mpconfigport.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -24,7 +24,7 @@ * THE SOFTWARE. */ -// options to control how Micro Python is built +// options to control how MicroPython is built // Linking with GNU readline (MICROPY_USE_READLINE == 2) causes binary to be licensed under GPL #ifndef MICROPY_USE_READLINE diff --git a/windows/msvc/dirent.h b/windows/msvc/dirent.h index 6172913ee1..fca06785a6 100644 --- a/windows/msvc/dirent.h +++ b/windows/msvc/dirent.h @@ -23,6 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ +#ifndef MICROPY_INCLUDED_WINDOWS_MSVC_DIRENT_H +#define MICROPY_INCLUDED_WINDOWS_MSVC_DIRENT_H // dirent.h implementation for msvc @@ -42,3 +44,5 @@ typedef struct dirent { DIR *opendir(const char *name); int closedir(DIR *dir); struct dirent *readdir(DIR *dir); + +#endif // MICROPY_INCLUDED_WINDOWS_MSVC_DIRENT_H diff --git a/windows/msvc/gettimeofday.c b/windows/msvc/gettimeofday.c index 363d59d7bc..5f816df709 100644 --- a/windows/msvc/gettimeofday.c +++ b/windows/msvc/gettimeofday.c @@ -1,5 +1,5 @@ /* -* This file is part of the Micro Python project, http://micropython.org/ +* This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -43,7 +43,7 @@ int gettimeofday(struct timeval *tp, struct timezone *tz) { // to microseconds ft.tm /= 10; - + // convert to unix format // number of microseconds intervals between the 1st january 1601 and the 1st january 1970 (369 years + 89 leap days) const unsigned __int64 deltaEpoch = 11644473600000000ull; diff --git a/windows/msvc/sys/time.h b/windows/msvc/sys/time.h index 96bca1ccbe..7c95d409e4 100644 --- a/windows/msvc/sys/time.h +++ b/windows/msvc/sys/time.h @@ -1,5 +1,5 @@ /* -* This file is part of the Micro Python project, http://micropython.org/ +* This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,6 +23,10 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ +#ifndef MICROPY_INCLUDED_WINDOWS_MSVC_SYS_TIME_H +#define MICROPY_INCLUDED_WINDOWS_MSVC_SYS_TIME_H // Get the definitions for timeval etc #include + +#endif // MICROPY_INCLUDED_WINDOWS_MSVC_SYS_TIME_H diff --git a/windows/msvc/unistd.h b/windows/msvc/unistd.h index add10c8843..1a1629be4f 100644 --- a/windows/msvc/unistd.h +++ b/windows/msvc/unistd.h @@ -1,5 +1,5 @@ /* -* This file is part of the Micro Python project, http://micropython.org/ +* This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,6 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ +#ifndef MICROPY_INCLUDED_WINDOWS_MSVC_UNISTD_H +#define MICROPY_INCLUDED_WINDOWS_MSVC_UNISTD_H // There's no unistd.h, but this is the equivalent #include @@ -38,3 +40,5 @@ #define SEEK_CUR 1 #define SEEK_END 2 #define SEEK_SET 0 + +#endif // MICROPY_INCLUDED_WINDOWS_MSVC_UNISTD_H diff --git a/windows/realpath.c b/windows/realpath.c index c0ed6b84da..ac9adf8125 100644 --- a/windows/realpath.c +++ b/windows/realpath.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/windows/realpath.h b/windows/realpath.h index 6f0a29a7e1..869fe80fae 100644 --- a/windows/realpath.h +++ b/windows/realpath.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,5 +23,9 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ +#ifndef MICROPY_INCLUDED_WINDOWS_REALPATH_H +#define MICROPY_INCLUDED_WINDOWS_REALPATH_H extern char *realpath(const char *path, char *resolved_path); + +#endif // MICROPY_INCLUDED_WINDOWS_REALPATH_H diff --git a/windows/sleep.c b/windows/sleep.c index 214d6d622a..6043ec7b7b 100644 --- a/windows/sleep.c +++ b/windows/sleep.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -31,7 +31,7 @@ HANDLE waitTimer = NULL; void init_sleep(void) { - waitTimer = CreateWaitableTimer(NULL, TRUE, NULL); + waitTimer = CreateWaitableTimer(NULL, TRUE, NULL); } void deinit_sleep(void) { diff --git a/windows/sleep.h b/windows/sleep.h index 09ad4afdca..430ec3a436 100644 --- a/windows/sleep.h +++ b/windows/sleep.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -23,6 +23,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ +#ifndef MICROPY_INCLUDED_WINDOWS_SLEEP_H +#define MICROPY_INCLUDED_WINDOWS_SLEEP_H void init_sleep(void); void deinit_sleep(void); @@ -30,3 +32,5 @@ void msec_sleep(double msec); #ifdef _MSC_VER int usleep(__int64 usec); #endif + +#endif // MICROPY_INCLUDED_WINDOWS_SLEEP_H diff --git a/windows/windows_mphal.c b/windows/windows_mphal.c index a73140e544..153b044235 100644 --- a/windows/windows_mphal.c +++ b/windows/windows_mphal.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/windows/windows_mphal.h b/windows/windows_mphal.h index 854e14a7a8..5a93d4e184 100644 --- a/windows/windows_mphal.h +++ b/windows/windows_mphal.h @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/zephyr/Makefile b/zephyr/Makefile index 9e8cb31d0a..988b32fe89 100644 --- a/zephyr/Makefile +++ b/zephyr/Makefile @@ -8,7 +8,7 @@ # To build a "minimal" configuration, use "make-minimal" wrapper. BOARD ?= qemu_x86 -CONF_FILE = prj.conf +CONF_FILE = prj_$(BOARD)_merged.conf OUTDIR_PREFIX = $(BOARD) # Default heap size is 16KB, which is on conservative side, to let @@ -17,9 +17,14 @@ OUTDIR_PREFIX = $(BOARD) MICROPY_HEAP_SIZE = 16384 FROZEN_DIR = scripts +# Default target +all: + # Zephyr (generated) config files - must be defined before include below Z_EXPORTS = outdir/$(OUTDIR_PREFIX)/Makefile.export +ifneq ($(MAKECMDGOALS), clean) include $(Z_EXPORTS) +endif include ../py/mkenv.mk include ../py/py.mk @@ -56,12 +61,12 @@ CFLAGS = $(KBUILD_CFLAGS) $(NOSTDINC_FLAGS) $(ZEPHYRINCLUDE) \ include ../py/mkrules.mk +# We use single target here ($(Z_EXPORTS)) for simplicity, but actually +# number of things get generated here: 'initconfig' generates C header for +# Kconfig configuration, 'outputexports' generates make environment with CC, +# etc., and 'lib' generates other headers which may be included by zephyr.h, +# e.g. DTS-related. $(Z_EXPORTS): $(CONF_FILE) - # We use single target here ($(Z_EXPORTS)) for simplicity, but actually - # number of things get generated here: 'initconfig' generates C header for - # Kconfig configuration, 'outputexports' generates make environment with CC, - # etc., and 'lib' generates other headers which may be included by zephyr.h, - # e.g. DTS-related. $(MAKE) -f Makefile.zephyr BOARD=$(BOARD) CONF_FILE=$(CONF_FILE) initconfig outputexports lib GENERIC_TARGETS = all zephyr run qemu qemugdb flash debug debugserver @@ -84,14 +89,16 @@ build/genhdr/qstr.i.last: | $(Z_EXPORTS) # If we recreate libmicropython, also cause zephyr.bin relink LIBMICROPYTHON_EXTRA_CMD = -$(RM) -f outdir/$(OUTDIR_PREFIX)/zephyr.lnk -# Clean Zephyr things too -clean: z_clean +# MicroPython's global clean cleans everything, fast +CLEAN_EXTRA = outdir +# Clean Zephyr things in Zephyr way z_clean: $(MAKE) -f Makefile.zephyr BOARD=$(BOARD) clean -.PHONY: prj.conf -prj.conf: prj_base.conf +# This rule is for prj_$(BOARD)_merged.conf, not $(CONF_FILE), which +# can be overriden +prj_$(BOARD)_merged.conf: prj_base.conf prj_$(BOARD).conf $(PYTHON) makeprj.py prj_base.conf prj_$(BOARD).conf $@ test: diff --git a/zephyr/machine_pin.c b/zephyr/machine_pin.c index f011f51fd3..c3722926a0 100644 --- a/zephyr/machine_pin.c +++ b/zephyr/machine_pin.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * @@ -117,7 +117,7 @@ STATIC mp_obj_t machine_pin_call(mp_obj_t self_in, size_t n_args, size_t n_kw, c mp_arg_check_num(n_args, n_kw, 0, 1, false); machine_pin_obj_t *self = self_in; if (n_args == 0) { - uint32_t pin_val; + u32_t pin_val; (void)gpio_pin_read(self->port, self->pin, &pin_val); return MP_OBJ_NEW_SMALL_INT(pin_val); } else { @@ -158,7 +158,7 @@ STATIC mp_uint_t machine_pin_ioctl(mp_obj_t self_in, mp_uint_t request, uintptr_ switch (request) { case MP_PIN_READ: { - uint32_t pin_val; + u32_t pin_val; gpio_pin_read(self->port, self->pin, &pin_val); return pin_val; } diff --git a/zephyr/modmachine.h b/zephyr/modmachine.h index 596c59b178..84e4d10a88 100644 --- a/zephyr/modmachine.h +++ b/zephyr/modmachine.h @@ -1,5 +1,5 @@ -#ifndef __MICROPY_INCLUDED_ZEPHYR_MODMACHINE_H__ -#define __MICROPY_INCLUDED_ZEPHYR_MODMACHINE_H__ +#ifndef MICROPY_INCLUDED_ZEPHYR_MODMACHINE_H +#define MICROPY_INCLUDED_ZEPHYR_MODMACHINE_H #include "py/obj.h" @@ -13,4 +13,4 @@ typedef struct _machine_pin_obj_t { uint32_t pin; } machine_pin_obj_t; -#endif // __MICROPY_INCLUDED_ZEPHYR_MODMACHINE_H__ +#endif // MICROPY_INCLUDED_ZEPHYR_MODMACHINE_H diff --git a/zephyr/modusocket.c b/zephyr/modusocket.c index cec0eec7c4..ff82ab67c8 100644 --- a/zephyr/modusocket.c +++ b/zephyr/modusocket.c @@ -37,6 +37,9 @@ #include #include #include +#ifdef CONFIG_NET_SOCKETS +#include +#endif #define DEBUG_PRINT 0 #if DEBUG_PRINT // print debugging info @@ -48,10 +51,12 @@ typedef struct _socket_obj_t { mp_obj_base_t base; struct net_context *ctx; + #ifndef CONFIG_NET_SOCKETS union { struct k_fifo recv_q; struct k_fifo accept_q; }; + #endif #define STATE_NEW 0 #define STATE_CONNECTING 1 @@ -62,6 +67,12 @@ typedef struct _socket_obj_t { STATIC const mp_obj_type_t socket_type; +#ifdef CONFIG_NET_SOCKETS +#define SOCK_FIELD(ptr, field) ((ptr)->ctx->field) +#else +#define SOCK_FIELD(ptr, field) ((ptr)->field) +#endif + // k_fifo extended API static inline void *_k_fifo_peek_head(struct k_fifo *fifo) @@ -95,6 +106,7 @@ static inline void _k_fifo_wait_non_empty(struct k_fifo *fifo, int32_t timeout) // Helper functions #define RAISE_ERRNO(x) { int _err = x; if (_err < 0) mp_raise_OSError(-_err); } +#define RAISE_SOCK_ERRNO(x) { if ((int)(x) == -1) mp_raise_OSError(errno); } STATIC void socket_check_closed(socket_obj_t *socket) { if (socket->ctx == NULL) { @@ -171,10 +183,10 @@ static void sock_received_cb(struct net_context *context, struct net_pkt *pkt, i // if net_buf == NULL, EOF if (pkt == NULL) { - struct net_pkt *last_pkt = _k_fifo_peek_tail(&socket->recv_q); + struct net_pkt *last_pkt = _k_fifo_peek_tail(&SOCK_FIELD(socket, recv_q)); if (last_pkt == NULL) { socket->state = STATE_PEER_CLOSED; - k_fifo_cancel_wait(&socket->recv_q); + k_fifo_cancel_wait(&SOCK_FIELD(socket, recv_q)); DEBUG_printf("Marked socket %p as peer-closed\n", socket); } else { // We abuse "buf_sent" flag to store EOF flag @@ -191,7 +203,7 @@ static void sock_received_cb(struct net_context *context, struct net_pkt *pkt, i unsigned header_len = net_pkt_appdata(pkt) - pkt->frags->data; net_buf_pull(pkt->frags, header_len); - k_fifo_put(&socket->recv_q, pkt); + k_fifo_put(&SOCK_FIELD(socket, recv_q), pkt); } // Callback for incoming connections. @@ -200,13 +212,12 @@ static void sock_accepted_cb(struct net_context *new_ctx, struct sockaddr *addr, DEBUG_printf("accept cb: context: %p, status: %d, new ctx: %p\n", socket->ctx, status, new_ctx); DEBUG_printf("new_ctx ref_cnt: %d\n", new_ctx->refcount); - k_fifo_put(&socket->accept_q, new_ctx); + k_fifo_put(&SOCK_FIELD(socket, accept_q), new_ctx); } socket_obj_t *socket_new(void) { socket_obj_t *socket = m_new_obj_with_finaliser(socket_obj_t); socket->base.type = (mp_obj_t)&socket_type; - k_fifo_init(&socket->recv_q); socket->state = STATE_NEW; return socket; } @@ -249,7 +260,13 @@ STATIC mp_obj_t socket_make_new(const mp_obj_type_t *type, size_t n_args, size_t } } + #ifdef CONFIG_NET_SOCKETS + socket->ctx = (void*)zsock_socket(family, socktype, proto); + RAISE_SOCK_ERRNO(socket->ctx); + #else RAISE_ERRNO(net_context_get(family, socktype, proto, &socket->ctx)); + k_fifo_init(&SOCK_FIELD(socket, recv_q)); + #endif return MP_OBJ_FROM_PTR(socket); } @@ -302,7 +319,7 @@ STATIC mp_obj_t socket_accept(mp_obj_t self_in) { socket_obj_t *socket = self_in; socket_check_closed(socket); - struct net_context *ctx = k_fifo_get(&socket->accept_q, K_FOREVER); + struct net_context *ctx = k_fifo_get(&SOCK_FIELD(socket, accept_q), K_FOREVER); // Was overwritten by fifo ctx->refcount = 1; @@ -375,7 +392,7 @@ STATIC mp_uint_t sock_read(mp_obj_t self_in, void *buf, mp_uint_t max_len, int * if (sock_type == SOCK_DGRAM) { - struct net_pkt *pkt = k_fifo_get(&socket->recv_q, K_FOREVER); + struct net_pkt *pkt = k_fifo_get(&SOCK_FIELD(socket, recv_q), K_FOREVER); recv_len = net_pkt_appdatalen(pkt); DEBUG_printf("recv: pkt=%p, appdatalen: %d\n", pkt, recv_len); @@ -395,8 +412,8 @@ STATIC mp_uint_t sock_read(mp_obj_t self_in, void *buf, mp_uint_t max_len, int * return 0; } - _k_fifo_wait_non_empty(&socket->recv_q, K_FOREVER); - struct net_pkt *pkt = _k_fifo_peek_head(&socket->recv_q); + _k_fifo_wait_non_empty(&SOCK_FIELD(socket, recv_q), K_FOREVER); + struct net_pkt *pkt = _k_fifo_peek_head(&SOCK_FIELD(socket, recv_q)); if (pkt == NULL) { DEBUG_printf("TCP recv: NULL return from fifo\n"); continue; @@ -426,7 +443,7 @@ STATIC mp_uint_t sock_read(mp_obj_t self_in, void *buf, mp_uint_t max_len, int * if (frag == NULL) { DEBUG_printf("Finished processing pkt %p\n", pkt); // Drop head packet from queue - k_fifo_get(&socket->recv_q, K_NO_WAIT); + k_fifo_get(&SOCK_FIELD(socket, recv_q), K_NO_WAIT); // If "sent" flag was set, it's last packet and we reached EOF if (net_pkt_sent(pkt)) { @@ -483,9 +500,10 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(socket_makefile_obj, 1, 3, socket_mak STATIC mp_obj_t socket_close(mp_obj_t self_in) { socket_obj_t *socket = self_in; - if (socket->ctx != NULL) { - RAISE_ERRNO(net_context_put(socket->ctx)); - socket->ctx = NULL; + if (socket->ctx != -1) { + int res = zsock_close(socket->ctx); + RAISE_SOCK_ERRNO(res); + socket->ctx = -1; } return mp_const_none; } diff --git a/zephyr/modutime.c b/zephyr/modutime.c index 0c268046a9..a5d32fe665 100644 --- a/zephyr/modutime.c +++ b/zephyr/modutime.c @@ -1,5 +1,5 @@ /* - * This file is part of the Micro Python project, http://micropython.org/ + * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * diff --git a/zephyr/mpconfigport.h b/zephyr/mpconfigport.h index 98a033be46..b4677f3ed5 100644 --- a/zephyr/mpconfigport.h +++ b/zephyr/mpconfigport.h @@ -80,6 +80,8 @@ #define MICROPY_COMP_CONST (0) #define MICROPY_COMP_DOUBLE_TUPLE_ASSIGN (0) +#define MICROPY_PY_SYS_PLATFORM "zephyr" + #ifdef CONFIG_BOARD #define MICROPY_HW_BOARD_NAME "zephyr-" CONFIG_BOARD #else @@ -96,9 +98,6 @@ typedef int mp_int_t; // must be pointer size typedef unsigned mp_uint_t; // must be pointer size - -typedef void *machine_ptr_t; // must be of pointer size -typedef const void *machine_const_ptr_t; // must be of pointer size typedef long mp_off_t; #define MP_STATE_PORT MP_STATE_VM diff --git a/zephyr/mpconfigport_minimal.h b/zephyr/mpconfigport_minimal.h index 772335c0a1..f0e57d7566 100644 --- a/zephyr/mpconfigport_minimal.h +++ b/zephyr/mpconfigport_minimal.h @@ -80,9 +80,6 @@ typedef int mp_int_t; // must be pointer size typedef unsigned mp_uint_t; // must be pointer size - -typedef void *machine_ptr_t; // must be of pointer size -typedef const void *machine_const_ptr_t; // must be of pointer size typedef long mp_off_t; #define MP_STATE_PORT MP_STATE_VM diff --git a/zephyr/prj_base.conf b/zephyr/prj_base.conf index 4346f20bf9..50b195b2f7 100644 --- a/zephyr/prj_base.conf +++ b/zephyr/prj_base.conf @@ -14,6 +14,7 @@ CONFIG_NET_IPV4=y CONFIG_NET_IPV6=y CONFIG_NET_UDP=y CONFIG_NET_TCP=y +CONFIG_NET_SOCKETS=y CONFIG_TEST_RANDOM_GENERATOR=y CONFIG_NET_NBUF_RX_COUNT=5