summaryrefslogtreecommitdiff
path: root/py
AgeCommit message (Collapse)Author
5 dayspy/parse: Fix missing nlr_pop call in complex path of binary_op_maybe.Jeff Epler
Reproducer (needs to be run as one compilation unit): ans = (-1) ** 2.3 aa Fixes issue #17815. Signed-off-by: Jeff Epler <jepler@gmail.com>
6 dayspy/asmthumb: Don't corrupt base register in large offset store.Chris Webb
asm_thumb_store_reg_reg_offset() modifies the base register when storing with a large offset which triggers the generic path. If a variable lives in that register, this corrupts it. Fix this by saving the base register on the stack before modifying it. Signed-off-by: Chris Webb <chris@arachsys.com>
6 dayspy/parse: Add support for math module constants and float folding.Yoctopuce dev
Add a new MICROPY_COMP_CONST_FLOAT feature, enabled by in mpy-cross and when compiling with MICROPY_CONFIG_ROM_LEVEL_CORE_FEATURES. The new feature leverages the code of MICROPY_COMP_CONST_FOLDING to support folding of floating point constants. If MICROPY_COMP_MODULE_CONST is defined as well, math module constants are made available at compile time. For example: _DEG_TO_GRADIANT = const(math.pi / 180) _INVALID_VALUE = const(math.nan) A few corner cases had to be handled: - The float const folding code should not fold expressions resulting into complex results, as the mpy parser for complex immediates has limitations. - The constant generation code must distinguish between -0.0 and 0.0, which are different even if C consider them as ==. This change removes previous limitations on the use of `const()` expressions that would result in floating point number, so the test cases of micropython/const_error have to be updated. Additional test cases have been added to cover the new repr() code (from a previous commit). A few other simple test cases have been added to handle the use of floats in `const()` expressions, but the float folding code itself is also tested when running general float test cases, as float expressions often get resolved at compile-time (with this change). Signed-off-by: Yoctopuce dev <dev@yoctopuce.com>
7 dayspy/formatfloat: Improve accuracy of float formatting code.Yoctopuce dev
Following discussions in PR #16666, this commit updates the float formatting code to improve the `repr` reversibility, i.e. the percentage of valid floating point numbers that do parse back to the same number when formatted by `repr` (in CPython it's 100%). This new code offers a choice of 3 float conversion methods, depending on the desired tradeoff between code size and conversion precision: - BASIC method is the smallest code footprint - APPROX method uses an iterative method to approximate the exact representation, which is a bit slower but but does not have a big impact on code size. It provides `repr` reversibility on >99.8% of the cases in double precision, and on >98.5% in single precision (except with REPR_C, where reversibility is 100% as the last two bits are not taken into account). - EXACT method uses higher-precision floats during conversion, which provides perfect results but has a higher impact on code size. It is faster than APPROX method, and faster than the CPython equivalent implementation. It is however not available on all compilers when using FLOAT_IMPL_DOUBLE. Here is the table comparing the impact of the three conversion methods on code footprint on PYBV10 (using single-precision floats) and reversibility rate for both single-precision and double-precision floats. The table includes current situation as a baseline for the comparison: PYBV10 REPR_C FLOAT DOUBLE current = 364688 12.9% 27.6% 37.9% basic = 364812 85.6% 60.5% 85.7% approx = 365080 100.0% 98.5% 99.8% exact = 366408 100.0% 100.0% 100.0% Signed-off-by: Yoctopuce dev <dev@yoctopuce.com>
7 dayspy/parsenum: Refactor float parsing code.Yoctopuce dev
This commit extracts from the current float parsing code two functions which could be reused elsewhere in MicroPython. The code used to multiply a float x by a power of 10 is also simplified by applying the binary exponent separately from the power of 5. This avoids the risk of overflow in the intermediate stage, before multiplying by x. Signed-off-by: Yoctopuce dev <dev@yoctopuce.com>
7 dayspy/objboundmeth: Add option to use mp_is_equal instead of == comparison.Damien George
This option is needed for ports such as webassembly where objects are proxied and can be identical without being the same C pointer. Signed-off-by: Damien George <damien@micropython.org>
8 dayspy/mphal: Add stddef.h header for size_t.Yanfeng Liu
This includes "stddef.h" for `size_t` to resolve NuttX integration build issues. Signed-off-by: Yanfeng Liu <yfliu2008@qq.com>
10 daysdocs: Document PEP487 __set_name__ implementation.Anson Mansfield
Signed-off-by: Anson Mansfield <amansfield@mantaro.com>
10 dayspy/objtype: Add support for PEP487 __set_name__.Anson Mansfield
This commit adds support for the `__set_name__` data model method specified by PEP487 - Simpler customisation of class creation. This includes support for methods that mutate the owner class, and avoids the naive modify-while-iterating hazard possible in a naive implementation like micropython/micropython#15503. Note that based on the benchmarks in micropython/micropython#16825, this is also as fast or faster than the naive implementation, thanks to clever data layout in `setname_list_t`, and the way this allows the capture step to run during an existing loop through the class dict. Other rejected approaches for dealing with the hazard include: - python/cpython#72983 During the implementation of this feature for MicroPython, it was discovered that some versions of CPython also have this naive hazard. CPython resolved this bug in BPO-28797 and now makes a complete flat copy of the class's dict to iterate. This design decision doesn't make much sense for a microcontroller though, even if it's perfectly reasonable in the desktop world where memcpy might actually be cheaper than a hard-to-branch-predict conditional; and it's also motivated in their case by error-tracing considerations. - micropython/micropython#16816 This is an equivalent implementation to CPython's approach that places this copy directly on the stack; however it is both slower and has larger code size than the approach taken here. - micropython/micropython#15503 The simplest implementation is to just not worry about it and let the user face the consequences if they mutate the owner class. That's not a very friendly behavior, though, and it's not actually much more performant than this implementation on either time or code size. - micropython/micropython#17693 Another alternative is to do the same as #15503 but leverage MicroPython's existing `is_fixed` field in its dict type to convert attempted mutations of the owner dict into `AttributeError`s. This is safer than just leaving the open hazard, but there's still important use-cases for owner-mutating descriptors, and the performance gain is small enough that it isn't worth missing support for those cases. - combined micropython/micropython#17693 with this Another version of this feature used a new feature define, `MICROPY_PY_METACLASSES_LITE`, to control whether this algorithm or the naive version is used. This was rejected in favor of simplicity, based on the very limited performance margin the naive version has (which in some cases even goes _against_ it). Signed-off-by: Anson Mansfield <amansfield@mantaro.com>
10 dayspy/objint_longlong: Fix longlong interoperability with floats.Yoctopuce dev
Current longlong implementation does not allow a float as RHS of mathematic operators, as it lacks the delegation code present in mpz. Signed-off-by: Yoctopuce dev <dev@yoctopuce.com>
10 dayspy/objint_longlong: Fix overflow check in mp_obj_int_get_checked.Yoctopuce dev
This is to fix an outstanding TODO. The test cases is using a range as this will exist in all builds, but `mp_obj_get_int` is used in many different parts of code where an overflow is more likely to occur. Signed-off-by: Yoctopuce dev <dev@yoctopuce.com>
10 dayspy/objint_mpz: Fix pow3 where third argument is zero.Jeff Epler
This finding is based on fuzzing MicroPython. I manually minimized the test case it provided. Signed-off-by: Jeff Epler <jepler@gmail.com>
13 dayspy/mpprint: Fix printing pointers with upper bit set.Jeff Epler
On a build like nanbox, `mp_uint_t` is wider than `u/intptr_t`. Using a signed type for fetching pointer values resulted in erroneous results: like `<function f at 0xfffffffff7a60bc0>` instead of `<function f at 0xf7a60bc0>`. Signed-off-by: Jeff Epler <jepler@gmail.com>
13 dayspy/objcell: Fix printing of cell ID/pointer.Jeff Epler
On the nanbox build, `o->obj` is a 64-bit type but `%p` formats a 32-bit type, leading to undefined behavior. Print the cell's ID as a hex integer instead. This location was found using an experimental gcc plugin for `mp_printf` error checking. Signed-off-by: Jeff Epler <jepler@gmail.com>
13 dayspy: Fix mp_printf integer size mismatches.Jeff Epler
The type of the argument must match the format string. Add casts to ensure that they do. It's possible that casting from `size_t` to `unsigned` loses the correct values by masking off upper bits, but it seems likely that the quantities involved in practice are small enough that the `%u` formatter (32 bits on most platforms, 16 on pic16bit) will in fact hold the correct value. The alternative, casting to a wider type, adds code size. These locations were found using an experimental gcc plugin for `mp_printf` error checking, cross-building for x64 windows on Linux. In one case there was already a cast, but it was written incorrectly and did not have the intended effect. Signed-off-by: Jeff Epler <jepler@gmail.com>
13 dayspy: Cast type names to qstr explicitly.Jeff Epler
The name field of type objects is of type `uint16_t` for efficiency, but when the type is passed to `mp_printf` it must be cast explicitly to type `qstr`. These locations were found using an experimental gcc plugin for `mp_printf` error checking, cross-building for x64 windows on Linux. Signed-off-by: Jeff Epler <jepler@gmail.com>
13 dayspy/mpconfig,ports: Define new HEX_FMT formatting macro.Jeff Epler
Signed-off-by: Jeff Epler <jepler@gmail.com>
2025-07-24py/objint_longlong: Fix left shift of negative values.Angus Gratton
Previous comment was wrong, left shifting a negative value is UB in C. Use the same approach as small int shifts (from runtime.c). Signed-off-by: Angus Gratton <angus@redyak.com.au>
2025-07-24py/obj: Add new type flag to indicate subscr accepts slice-on-stack.Damien George
The recently merged 5e9189d6d1c00c92694888bf9c74276779c40716 now allows temporary slices to be allocated on the C stack, which is much better than allocating them on the GC heap. Unfortunately there are cases where the C-allocated slice can escape and be retained as an object, which leads to crashes (because that object points to the C stack which now has other values on it). The fix here is to add a new `MP_TYPE_FLAG_SUBSCR_ALLOWS_STACK_SLICE`. Native types should set this flag if their subscr method is guaranteed not to hold on to a reference of the slice object. Fixes issue #17733 (see also #17723). Signed-off-by: Damien George <damien@micropython.org>
2025-07-24py/obj: Fix REPR_C bias toward zero.Yoctopuce dev
Current implementation of REPR_C works by clearing the two lower bits of the mantissa to zero. As this happens after each floating point operation, this tends to bias floating point numbers towards zero, causing decimals like .9997 instead of rounded numbers. This is visible in test cases involving repeated computations, such as `tests/misc/rge_sm.py` for instance. The suggested fix fills in the missing bits by copying the previous two bits. Although this cannot recreate missing information, it fixes the bias by inserting plausible values for the lost bits, at a relatively low cost. Some float tests involving irrational numbers have to be softened in case of REPR_C, as the 30 bits are not always enough to fulfill the expectations of the original test, and the change may randomly affect the last digits. Such cases have been made explicit by testing for REPR_C or by adding a clear comment. The perf_test fft code was also missing a call to round() before casting a log_2 operation to int, which was causing a failure due to a last-decimal change. Signed-off-by: Yoctopuce dev <dev@yoctopuce.com>
2025-07-24extmod/vfs_posix: Add MICROPY_VFS_POSIX_WRITABLE option.Jeff Epler
When this configuration flag is set, VfsPosix instances can be written. Otherwise, they will always be created "read only". This flag is useful when fuzzing micropython: Without VfsPosix, the fuzzing input script cannot be read; but with writable VfsPosix, fuzzing scripts can potentially perform undesired operations on the host filesystem. Signed-off-by: Jeff Epler <jepler@gmail.com>
2025-07-23extmod/mbedtls: Implement recommended DTLS features, make optional.Angus Gratton
- DTLS spec recommends HelloVerify and Anti Replay protection be enabled, and these are enabled in the default mbedTLS config. Implement them here. - To help compensate for the possible increase in code size, add a MICROPY_PY_SSL_DTLS build config macro that's enabled for EXTRA and above by default. This allows bare metal mbedTLS ports to use DTLS with HelloVerify support. This work was funded through GitHub Sponsors. Signed-off-by: Angus Gratton <angus@redyak.com.au>
2025-07-22py/modsys: Add sys.implementation._thread attribute.Damien George
This is useful to distinguish between GIL and non-GIL builds. Signed-off-by: Damien George <damien@micropython.org>
2025-07-20py/mkrules.mk: Mute blobless errors.Yanfeng Liu
This mutes usage error for blobless update from older `git` to reduce noise upon submodule updating. Signed-off-by: Yanfeng Liu <yfliu2008@qq.com>
2025-07-18py/objcode: Remove co_lnotab from v2 preview.Anson Mansfield
Signed-off-by: Anson Mansfield <amansfield@mantaro.com>
2025-07-18py/parsenum: Extend mp_parse_num_integer() to parse long long.Angus Gratton
If big integer support is 'long long' then mp_parse_num_integer() can parse to it directly instead of failing over from small int. This means strtoll() is no longer pulled in, and fixes some bugs parsing long long integers (i.e. can now parse negative values correctly, can now parse values which aren't NULL terminated). The (default) smallint parsing compiled code should stay the same here, macros and a typedef are used to abstract some parts of it out. When bigint is long long we parse to 'unsigned long long' first (to avoid the code size hit of pulling in signed 64-bit math routines) and the convert to signed at the end. One tricky case this routine correctly overflows on is int("9223372036854775808") which is one more than LLONG_MAX in decimal. No unit test case added for this as it's too hard to detect 64-bit long integer mode. This work was funded through GitHub Sponsors. Signed-off-by: Angus Gratton <angus@redyak.com.au>
2025-07-18py/smallint: Update mp_small_int_mul_overflow() to perform the multiply.Angus Gratton
Makes it compatible with the __builtin_mul_overflow() syntax, used in follow-up commit. Includes optimisation in runtime.c to minimise the code size impact from additional param. Signed-off-by: Damien George <damien@micropython.org> Signed-off-by: Angus Gratton <angus@redyak.com.au>
2025-07-18py/objint_longlong: Add arithmetic overflow checks.Angus Gratton
Long long big integer support now raises an exception on overflow rather than returning an undefined result. Also adds an error when shifting by a negative value. The new arithmetic checks are added in the misc.h header. This work was funded through GitHub Sponsors. Signed-off-by: Angus Gratton <angus@redyak.com.au>
2025-07-16py/mpprint: Rework integer vararg handling.Jeff Epler
This adds support for %llx (needed by XINT_FMT for printing cell objects) and incidentally support for capitalized output of %P. It also reduces code size due to the common handling of all integers. Signed-off-by: Jeff Epler <jepler@gmail.com>
2025-07-16py/vm: Avoid heap-allocating slices when subscripting built-ins.Jim Mussared
This commit adds a fast-path optimisation for when a BUILD_SLICE is immediately followed by a LOAD/STORE_SUBSCR for a native type, to avoid needing to allocate the slice on the heap. In some cases (e.g. `a[1:3] = x`) this can result in no allocations at all. We can't do this for instance types because the get/set/delattr implementation may keep a reference to the slice. Adds more tests to the basic slice tests to ensure that a stack-allocated slice never makes it to Python, and also a heapalloc test that verifies (when using bytecode) that assigning to a slice is no-alloc. This work was funded through GitHub Sponsors. Signed-off-by: Jim Mussared <jim.mussared@gmail.com> Signed-off-by: Damien George <damien@micropython.org>
2025-07-09shared/timeutils: Standardize supported date range on all platforms.Yoctopuce dev
This is code makes sure that time functions work properly on a reasonable date range, on all platforms, regardless of the epoch. The suggested minimum range is 1970 to 2099. In order to reduce code footprint, code to support far away dates is only enabled specified by the port. New types are defined to identify timestamps. The implementation with the smallest code footprint is when support timerange is limited to 1970-2099 and Epoch is 1970. This makes it possible to use 32 bit unsigned integers for all timestamps. On ARM4F, adding support for dates up to year 3000 adds 460 bytes of code. Supporting dates back to 1600 adds another 44 bytes of code. Signed-off-by: Yoctopuce dev <dev@yoctopuce.com>
2025-07-09py/obj: Add functions to retrieve large integers from mp_obj_t.Yoctopuce dev
This commit provides helpers to retrieve integer values from mp_obj_t when the content does not fit in a 32 bits integer, without risking an implicit wrap due to an int overflow. Signed-off-by: Yoctopuce dev <dev@yoctopuce.com>
2025-07-08py/objcode: Implement co_lines method.Anson Mansfield
Signed-off-by: Anson Mansfield <amansfield@mantaro.com>
2025-07-08py/showbc: Use line-number decoding helper.Anson Mansfield
Signed-off-by: Anson Mansfield <amansfield@mantaro.com>
2025-07-08py/bc: Factor out helper for line-number decoding.Anson Mansfield
Signed-off-by: Anson Mansfield <amansfield@mantaro.com>
2025-07-06py/profile: Fix printing lineno in frame objects.Jeff Epler
The argument corresponding to a `%q` specifier must be of type `qstr`, not a narrower type like `int16_t`. Not ensuring this caused an assertion error on one Windows x64 build. The argument corresponding to a `%d` specifier must be of type `int`, not a potentially-wider type like `mp_uint_t`. Not ensuring this prevented the function name from being printed on the unix nanbox build. Signed-off-by: Jeff Epler <jepler@gmail.com>
2025-07-06py/runtime: Initialize profile fields in mp_thread_init_state.Jeff Epler
If the fields added for `MICROPY_PY_SYS_SETTRACE` are not initialized properly, their value in a thread is indeterminate. In particular, if the callback is not NULL, it will be invoked as a function. Signed-off-by: Jeff Epler <jepler@gmail.com>
2025-07-04py/emitnative: Let emitters know the compiled entity's name.Alessandro Gatti
This commit introduces an optional feature to provide to native emitters the fully qualified name of the entity they are compiling. This is achieved by altering the generic ASM API to provide a third argument to the entry function, containing the name of the entity being compiled. Currently only the debug emitter uses this feature, as it is not really useful for other emitters for the time being; in fact the macros in question just strip the name away. Signed-off-by: Alessandro Gatti <a.gatti@frob.it>
2025-07-01py/asmthumb: Clean up integer-indexed load/store emitters.Alessandro Gatti
This commit cleans up the single entry point integer-indexed load/store emitters that have been built by merging the single operand type load/store functions in 1f5ba6998bb1895354f5afcd7bb52d83a02733be. To follow the same convention found in RV32 and Xtensa emitters, the function operand size is not named after the left shift amount to apply to the initial offset to get its true byte offset, but by a generic "operand size". Also, those functions were updated to use the new MP_FIT_UNSIGNED macros to perform bit width checks when figuring out which opcode encoding is the best one to use. Signed-off-by: Alessandro Gatti <a.gatti@frob.it>
2025-07-01py/asmx64: Implement the full set of Viper load/store operations.Alessandro Gatti
This commit expands the implementation of Viper load/store operations that are optimised for the x86 platform. Like x86, x64 already implemented all necessary functions and all it took to expose these to Viper after the infrastructure refactoring was to add a few defines. Signed-off-by: Alessandro Gatti <a.gatti@frob.it>
2025-07-01py/asmx86: Implement the full set of Viper load/store operations.Alessandro Gatti
This commit expands the implementation of Viper load/store operations that are optimised for the x86 platform. Unlike other platforms, x86 already implemented all necessary functions and all it took to expose these to Viper after the infrastructure refactoring was to add a few defines. Signed-off-by: Alessandro Gatti <a.gatti@frob.it>
2025-07-01py/asmthumb: Remove redundant load/store opcode implementations.Alessandro Gatti
This commit removes load/store opcode implementations that have been made redundant in 1f5ba6998bb1895354f5afcd7bb52d83a02733be. Signed-off-by: Alessandro Gatti <a.gatti@frob.it>
2025-07-01py/asmxtensa: Implement the full set of Viper load/store operations.Alessandro Gatti
This commit expands the implementation of Viper load/store operations that are optimised for the Xtensa platform. Now both load and store emitters should generate the shortest possible sequence in all cases. Redundant specialised operation emitters have been aliased to the general case implementation - this was the case of integer-indexed load/store operations with a fixed offset of zero. Signed-off-by: Alessandro Gatti <a.gatti@frob.it>
2025-07-01py/asmarm: Implement the full set of Viper load/store operations.Alessandro Gatti
This commit expands the implementation of Viper load/store operations that are optimised for the Arm platform. Now both load and store emitters should generate the shortest possible sequence in all cases. Redundant specialised operation emitters have been folded into the general case implementation - this was the case of integer-indexed load/store operations with a fixed offset of zero. Signed-off-by: Alessandro Gatti <a.gatti@frob.it>
2025-07-01py/asmrv32: Implement the full set of Viper load/store operations.Alessandro Gatti
This commit expands the implementation of Viper load/store operations that are optimised for the RV32 platform. Given the way opcodes are encoded, all value sizes are implemented with only two functions - one for loads and one for stores. This should reduce duplication with existing operations and should, in theory, save space as some code is removed. Both load and store emitters will generate the shortest possible sequence (as long as the stack pointer is not involved), using compressed opcodes when possible. Signed-off-by: Alessandro Gatti <a.gatti@frob.it>
2025-07-01py/misc: Introduce macros to check values' bits size.Alessandro Gatti
This commit adds two macros that lets check whether a given value can fit an arbitrary number of bits, either as a signed or as an unsigned number. The native emitter code backends perform a lot of bit size checks to see if a particular code sequence can be emitted instead of a generic one, and each platform backend has its own ad-hoc macros (usually one per bit count and signedness). With these macros there's a single way to perform those checks, plus there's no more chance for off-by-one mask length errors when dealing with signed numbers. Signed-off-by: Alessandro Gatti <a.gatti@frob.it>
2025-06-25py/misc: Fix fallback implementation of mp_popcount.Damien George
Tested using gcc 7.3.1 which does not have the popcount built-in and uses this fallback version. Without the fix, mpy-cross produces mpy files with corrupt RISC-V machine code. With the fix, mpy-cross output is correct. Signed-off-by: Damien George <damien@micropython.org>
2025-06-24py/obj: Fix nan handling in object REPR_C and REPR_D.Yoctopuce dev
CPython math.nan is positive with regards to copysign. The signaling bit (aka sign flag) was incorrectly set. In addition, REPR_C and REPR_D should only use the _true_ nan to prevent system crash in case of hand-crafted floats. For instance, with REPR_C, any nan-like float following the pattern `01111111 1xxxxxxx xxxxxxxx xxxxx1xx` would be switched to an immediate object or a qstr string. When the qstr index is too large, this would cause a crash. This commit fixes the issue, and adds the relevant test cases. Signed-off-by: Yoctopuce dev <dev@yoctopuce.com>
2025-06-23py/runtime: Add support for using __all__ in star import.Yoctopuce dev
When the symbol `__all__` is defined in a module, `mp_import_all()` should import all listed symbols into the global environment, rather than relying on the underscore-is-private default. This is the standard in CPython. Each item is loaded in the same way as if it would be an explicit import statement, and will invoke the module's `__getattr__` function if needed. This provides a straightforward solution for fixing star import of modules using a dynamic loader, such as `extmod/asyncio` (see issue #7266). This improvement has been enabled at BASIC_FEATURES level, to avoid impacting devices with limited ressources, for which star import is of little use anyway. Additionally, detailled reporting of errors during `__all__` import has been implemented to match CPython, but this is only enabled when ERROR_REPORTING is set to MICROPY_ERROR_REPORTING_DETAILED. Signed-off-by: Yoctopuce dev <dev@yoctopuce.com>
2025-06-19py/repl: Skip private variables when printing tab completion options.Andrew Leech
Any '_' variables/functions in frozen modules are currently printed, when they shouldn't be. That's due to underscore names possibly existing between the start and end qstrs which are used to print the auto-complete matches. The underscore names should be skipped when iterating between the two boundary qstrs. The underscore attributes are removed from the extra coverage exp file because tab completing "import <tab>" no longer lists modules beginning with an underscore. Signed-off-by: Andrew Leech <andrew.leech@planetinnovation.com.au>