Wykres commitów

2331 Commity (master)

Autor SHA1 Wiadomość Data
Damien George 932556d5fc tests/micropython: Add test for builtin execfile() function.
Signed-off-by: Damien George <damien@micropython.org>
2022-06-29 12:48:42 +10:00
Angus Gratton e024a4c59c tests: Fix run-perfbench parsing "no matching params" case.
Signed-off-by: Angus Gratton <gus@projectgus.com>
2022-06-28 14:22:06 +10:00
Angus Gratton ad308bc322 tests: Add an explanation of run-perfbench.py.
Also changes this file to a Markdown file.

Signed-off-by: Angus Gratton <gus@projectgus.com>
2022-06-28 14:21:41 +10:00
Angus Gratton 5568c324ba tests/perf_bench: Add some configurations for N=32, M=10.
For STM32L072 and similar, very low end targets.

The other perf_bench tests run out of memory, crash, or fail on
prerequisite features.

Signed-off-by: Angus Gratton <gus@projectgus.com>
2022-06-28 10:32:18 +10:00
Damien George e22b7fb4af py/objfun: Support function attributes on native functions.
Native functions can just reuse the bytecode function attribute code.

Signed-off-by: Damien George <damien@micropython.org>
2022-06-25 00:22:15 +10:00
Damien George 268ec1e3eb tests/basics: Add tests for __name__ and __globals__ attrs on closures.
Signed-off-by: Damien George <damien@micropython.org>
2022-06-24 23:55:13 +10:00
Damien George db7682e02d extmod/uasyncio: Implement stream read(-1) to read all data up to EOF.
Fixes issue #6355.

Signed-off-by: Damien George <damien@micropython.org>
2022-06-24 17:04:57 +10:00
Damien George 2a2589738c tests/extmod: Add heap-lock test for stream writing.
Signed-off-by: Damien George <damien@micropython.org>
2022-06-24 17:00:24 +10:00
Damien George 61ce260ff7 py/parsenum: Fix parsing of complex "j" and also "nanj", "infj".
Prior to this commit, complex("j") would return 0j, and complex("nanj")
would return nan+0j.  This commit makes sure "j" is tested for after
parsing the number (nan, inf or a decimal), and also supports the case of
"j" on its own.

Signed-off-by: Damien George <damien@micropython.org>
2022-06-23 11:46:47 +10:00
Jim Mussared 0172292762 py/parsenum: Support parsing complex numbers of the form "a+bj".
To conform with CPython.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2022-06-23 11:46:47 +10:00
David Lechner a565811f23 extmod/modbtree: Use buffer protocol for keys/values.
This changes the btree implementation to use the buffer protocol for
reading key/values in all methods.  `str` and `bytes` objects are not the
only bytes-like objects that could be used.

Documentation and tests are also updated.

Addresses issue #8748.

Signed-off-by: David Lechner <david@pybricks.com>
2022-06-21 00:44:49 +10:00
Damien George a506335524 py/emit: Suppress unreachable bytecode/native code that follows jump.
This new logic tracks when an unconditional jump/raise occurs in the
emitted code stream (bytecode or native machine code) and suppresses all
subsequent code, until a label is assigned.  This eliminates a lot of
cases of dead code, with relatively simple logic.

This commit combined with the previous one (that removed the existing
dead-code finding logic) has the following code size change:

       bare-arm:   -16 -0.028%
    minimal x86:   -60 -0.036%
       unix x64:  -368 -0.070%
    unix nanbox:   -80 -0.017%
          stm32:  -204 -0.052% PYBV10
         cc3200:    +0 +0.000%
        esp8266:  -232 -0.033% GENERIC
          esp32:  -224 -0.015% GENERIC[incl -40(data)]
         mimxrt:  -192 -0.054% TEENSY40
     renesas-ra:  -200 -0.032% RA6M2_EK
            nrf:   +28 +0.015% pca10040
            rp2:  -256 -0.050% PICO
           samd:   -12 -0.009% ADAFRUIT_ITSYBITSY_M4_EXPRESS

Signed-off-by: Damien George <damien@micropython.org>
2022-06-20 22:28:18 +10:00
Damien George e85a096302 py/emit: Remove logic to detect last-emit-was-return-value.
This optimisation to remove dead code is not as good as it could be.

Signed-off-by: Damien George <damien@micropython.org>
2022-06-20 22:28:18 +10:00
Damien George 182256dc13 tests/stress: Adjust bytecode_limit test so it can SKIP if no memory.
Signed-off-by: Damien George <damien@micropython.org>
2022-06-08 15:00:59 +10:00
Damien George 1d143cec63 tests/basics: Add .exp file for sys.tracebacklimit test.
The sys.tracebacklimit feature has changed semantics a bit from CPython 3.7
(in the way it modifies the output), so provide a .exp file for the test so
it doesn't rely on CPython.

Signed-off-by: Damien George <damien@micropython.org>
2022-06-07 16:55:18 +10:00
Damien George b37b578214 py/persistentcode: Remove remaining native qstr linking support.
Support for architecture-specific qstr linking was removed in
d4d53e9e11, where native code was changed to
access qstr values via qstr_table.  The only remaining use for the special
qstr link table in persistentcode.c is to support native module written in
C, linked via mpy_ld.py.  But native modules can also use the standard
module-level qstr_table (and obj_table) which was introduced in the .mpy
file reworking in f2040bfc7e.

This commit removes the remaining native qstr liking support in
persistentcode.c's load_raw_code function, and adds two new relocation
options for constants.qstr_table and constants.obj_table.  mpy_ld.py is
updated to use these relocations options instead of the native qstr link
table.

Signed-off-by: Damien George <damien@micropython.org>
2022-06-07 13:19:55 +10:00
Andrew Leech b7a39ad2d1 tests/run-multitests.py: Read IP address from boot nic if available.
This works if your network is pre-configured in boot.py as an object called
"nic".  Without this, multitests expects to access the WLAN/LAN class which
isn't always correct.

Signed-off-by: Andrew Leech <andrew@alelec.net>
2022-06-03 14:35:37 +10:00
Andrew Leech 73a1ea8812 tests/net_inet: Remove broken api.telegram.org from tests.
Signed-off-by: Andrew Leech <andrew@alelec.net>
2022-06-03 14:34:29 +10:00
Takeo Takahashi 19c680ff57 test/renesas-ra: Remove unsupported feature test of Pin.
Signed-off-by: Takeo Takahashi <takeo.takahashi.xv@renesas.com>
2022-06-03 10:58:16 +10:00
Damien George a1afb337d2 extmod/uasyncio: Fix edge case for cancellation of wait_for.
This fixes the cases where the task being waited on finishes just before or
just after the wait_for itself is cancelled.

Fixes issue #8717.

Signed-off-by: Damien George <damien@micropython.org>
2022-06-02 17:14:20 +10:00
Damien George 065df5568c tests: Move native while test from pybnative to micropython.
And make it so this test can run on any target.

LED and time testing has been removed from this test, that can now be
tested using: ./run-tests.py --via-mpy --emit native.

Signed-off-by: Damien George <damien@micropython.org>
2022-05-26 12:54:43 +10:00
Damien George 20d9f3409a tests/run-tests.py: Add rp2 test target.
Signed-off-by: Damien George <damien@micropython.org>
2022-05-26 12:54:43 +10:00
Damien George 80a86c48e3 tests/micropython: Make import_mpy_native test run on all architectures.
Signed-off-by: Damien George <damien@micropython.org>
2022-05-26 12:54:43 +10:00
Damien George 3180113aef tests/micropython: Make import_mpy_native_gc run on ARMv6-M and above.
Signed-off-by: Damien George <damien@micropython.org>
2022-05-26 12:23:49 +10:00
robert-hh dd35f76db3 tests/run-multitests.py: Use LAN for IP address if WLAN doesn't exist.
This allows running the test on boards with just a LAN interface.

Fixes issue #8681.
2022-05-24 13:21:05 +10:00
iabdalkader beeb250d58 tests/multi_net: Fix TCP accept test when using system error numbers.
If a port is not using internal error numbers, which match both lwIP and
Linux error numbers, ENTOCONN from standard libraries errno.h equals 128,
not 107.
2022-05-24 13:15:22 +10:00
Damien George 5fa8ea1b8b tests/extmod: Change expected errno code from 36 to 30 in VfsLfs2 test.
Errno 30 is EROFS, which is now the correct value reported by littlefs 2.

Signed-off-by: Damien George <damien@micropython.org>
2022-05-24 12:52:00 +10:00
David Lechner d42d35f56d tests/run-tests.py: Enable `-X realtime` option for macOS tests.
This enables the new `-X realtime` runtime option when running tests on
macOS.  This causes MicroPython to configure all threads to be high
priority so that they are allowed to use high precision timers.  This
makes tests that depend on the passage of time more likely to succeed.

CI tests that were disabled because of this are now enabled again.

Signed-off-by: David Lechner <david@pybricks.com>
2022-05-24 00:52:44 +10:00
Damien George 7d3204783a tests/run-tests.py: Handle case where mpy-cross fails to compile script.
Signed-off-by: Damien George <damien@micropython.org>
2022-05-23 15:45:21 +10:00
Damien George a8492253c1 tests/basics: Unlock heap if skipping nanbox small-int test.
Signed-off-by: Damien George <damien@micropython.org>
2022-05-23 15:45:16 +10:00
Damien George 54ab9d23e9 tests/run-perfbench.py: Allow running tests via mpy and native emitter.
The performance benchmark tests now support `--via-mpy` and `--emit native`
on remote targets.  For example:

    $ ./run-perfbench.py -p --via-mpy --emit native 100 100

Signed-off-by: Damien George <damien@micropython.org>
2022-05-19 17:31:56 +10:00
Damien George 1786dacc83 tests/run-tests.py: Allow running tests via mpy-cross on remote targets.
This adds support for the `--via-mpy` and `--emit native` options when
running tests on remote targets (via pyboard.py).  It's now possible to do:

    $ ./run-tests.py --target pyboard --via-mpy
    $ ./run-tests.py --target pyboard --via-mpy --emit native

Signed-off-by: Damien George <damien@micropython.org>
2022-05-19 17:31:56 +10:00
Damien George 079f3e5e5b py/parse: Allow all constant objects to be used in "X = const(o)".
Now that constant tuples are supported in the parser, eg (1, True, "str"),
it's a small step to allow anything that is a constant to be used with the
pattern:

    from micropython import const

    X = const(obj)

This commit makes the required changes to allow the following types of
constants:

    from micropython import const

    _INT = const(123)
    _FLOAT = const(1.2)
    _COMPLEX = const(3.4j)
    _STR = const("str")
    _BYTES = const(b"bytes")
    _TUPLE = const((_INT, _STR, _BYTES))
    _TUPLE2 = const((None, False, True, ..., (), _TUPLE))

Prior to this, only integers could be used in const(...).

Signed-off-by: Damien George <damien@micropython.org>
2022-05-18 16:18:35 +10:00
Damien George 761d2f6741 tests/micropython: Add more test cases for native generators.
Signed-off-by: Damien George <damien@micropython.org>
2022-05-18 15:23:11 +10:00
Damien George 80938839c1 tests/extmod: Use bytearray instead of bytes for uctypes test.
Because the test modifies the (now) bytearray object, and if it's a bytes
object it's not guaranteed that it can be modified, or that this constant
object isn't used elsewhere.

Signed-off-by: Damien George <damien@micropython.org>
2022-05-18 15:23:11 +10:00
Damien George b3d0f5f67c tests/micropython: Fully unlink nested list in extreme exc test.
To make sure there are no dangling references to the lists, and the GC can
reclaim heap memory.

Signed-off-by: Damien George <damien@micropython.org>
2022-05-18 09:16:33 +10:00
Damien George 90682f43af py/compile: Allow new qstrs to be allocated at all compiler passes.
Prior to this commit, all qstrs were required to be allocated (by calling
mp_emit_common_use_qstr) in the MP_PASS_SCOPE pass (the first one).  But
this is an unnecessary restriction, which is lifted by this commit.
Lifting the restriction simplifies the compiler because it can allocate
qstrs in later passes.

This also generates better code, because in some cases (eg when a variable
is closed over) the scope of an identifier is not known until a bit later
and then the identifier no longer needs its qstr allocated in the global
table.

Code size is reduced for all ports with this commit.

Signed-off-by: Damien George <damien@micropython.org>
2022-05-17 23:39:22 +10:00
Damien George acfc3bbdf8 tests/multi_net: Skip SSL test if relevant modules aren't available.
Signed-off-by: Damien George <damien@micropython.org>
2022-05-17 14:25:51 +10:00
Damien George ab0a8f3086 tests/run-tests.py: Exclude settrace tests when using native emitter.
Signed-off-by: Damien George <damien@micropython.org>
2022-05-17 14:25:51 +10:00
Damien George 5f650b7b7a tests/thread: Use less resources for stress_aes if settrace enabled.
Signed-off-by: Damien George <damien@micropython.org>
2022-05-17 14:25:51 +10:00
Damien George 6f68a8c240 tests/run-perfbench.py: Return error code if any test fails on target.
Signed-off-by: Damien George <damien@micropython.org>
2022-05-17 14:06:41 +10:00
Damien George d7cf8a3b9d tests/perf_bench: Update .mpy file header to remove old unicode flag.
Signed-off-by: Damien George <damien@micropython.org>
2022-05-17 14:06:41 +10:00
Damien George c49d5207e9 py/persistentcode: Remove unicode feature flag from .mpy file.
Prior to this commit, even with unicode disabled .py and .mpy files could
contain unicode characters, eg by entering them directly in a string as
utf-8 encoded.

The only thing the compiler disallowed (with unicode disabled) was using
\uxxxx and \Uxxxxxxxx notation to specify a character within a string with
value >= 0x100; that would give a SyntaxError.

With this change mpy-cross will now accept \u and \U notation to insert a
character with value >= 0x100 into a string (because the -mno-unicode
option is now gone, there's no way to forbid this).  The runtime will
happily work with strings with such characters, just like it already works
with strings with characters that were utf-8 encoded directly.

This change simplifies things because there are no longer any feature
flags in .mpy files, and any bytecode .mpy will now run on any target.

Signed-off-by: Damien George <damien@micropython.org>
2022-05-17 12:51:54 +10:00
Damien George 8aa254c369 tests: Fix tests to use sys.implementation._mpy.
The field was renamed to _mpy in 59c5d41611

Signed-off-by: Damien George <damien@micropython.org>
2022-05-17 09:46:40 +10:00
Damien George fca5701f74 py/malloc: Introduce m_tracked_calloc, m_tracked_free functions.
Enabled by MICROPY_TRACKED_ALLOC.

Signed-off-by: Damien George <damien@micropython.org>
2022-05-05 10:31:50 +10:00
Damien George c90f097519 tests/extmod: Increase timing on uasyncio tests to make more reliable.
Non-real-time systems like Windows, Linux and macOS do not have reliable
timing, so increase the sleep intervals to make these tests more likely to
pass.

Signed-off-by: Damien George <damien@micropython.org>
2022-05-03 22:53:12 +10:00
Damien George 590de399f0 py/emitcommon: Don't implicitly close class vars that are assigned to.
When in a class body or at the module level don't implicitly close over
variables that have been assigned to.

Fixes issue #8603.

Signed-off-by: Damien George <damien@micropython.org>
2022-05-03 16:38:43 +10:00
Takeo Takahashi 3717d599e2 tests/run-tests.py: Update for renesas-ra port.
Signed-off-by: Takeo Takahashi <takeo.takahashi.xv@renesas.com>
2022-04-29 12:29:08 +09:00
Takeo Takahashi 4753913253 tests/renesas-ra: Add tests for renesas-ra port.
Signed-off-by: Takeo Takahashi <takeo.takahashi.xv@renesas.com>
2022-04-29 12:29:07 +09:00
Damien George 6bec5c4da5 tests/cmdline: Add test for REPL auto-indent.
Signed-off-by: Damien George <damien@micropython.org>
2022-04-22 17:00:16 +10:00
Damien George 28e7e15c0a extmod/uasyncio: Fix bug with task ending just after gather is cancel'd.
This fixes a bug where the gather is cancelled externally and then one of
its sub-tasks (that the gather was waiting on) finishes right between the
cancellation being queued and being executed.

Signed-off-by: Damien George <damien@micropython.org>
2022-04-21 14:25:17 +10:00
Damien George 8631753ff4 tests/run-tests.py: Add timeout for running PC-based MicroPython test.
So the test suite runs to completion, even if the interpreter locks up.

Signed-off-by: Damien George <damien@micropython.org>
2022-04-21 14:25:17 +10:00
Damien George ef1c2cdab0 tests/extmod/uasyncio_gather: Make double-raise gather test reliable.
This double-raise test could fail when task[0] raises and stops the gather
before task[1] raises, then task[1] is left to raise later on and spoil the
test.

Signed-off-by: Damien George <damien@micropython.org>
2022-04-20 19:32:49 +10:00
Jon Bjarni Bjarnason 1ded8a2977 py/objtype: Convert result of user __contains__ method to bool.
Per https://docs.python.org/3/reference/expressions.html#membership-test-operations

    For user-defined classes which define the contains() method, x in y
    returns True if y.contains(x) returns a true value, and False
    otherwise.

Fixes issue #7884.
2022-04-20 15:44:46 +10:00
Damien George 865b61dac2 tests/micropython: Add tests that const tuples don't use the heap.
Signed-off-by: Damien George <damien@micropython.org>
2022-04-15 00:17:02 +10:00
Damien George 999abbb8b5 tests/perf_bench: Update import tests for changes to .mpy consts.
Signed-off-by: Damien George <damien@micropython.org>
2022-04-14 23:52:14 +10:00
Damien George 35c0cff92b py/parse: Add MICROPY_COMP_CONST_TUPLE option to build const tuples.
This commit adds support to the parser so that tuples which contain only
constant elements (bool, int, str, bytes, etc) are immediately converted to
a tuple object.  This makes it more efficient to use tuples containing
constant data because they no longer need to be created at runtime by the
bytecode (or native code).

Furthermore, with this improvement constant tuples that are part of frozen
code are now able to be stored fully in ROM (this will be implemented in
later commits).

Code size is increased by about 400 bytes on Cortex-M4 platforms.

See related issue #722.

Signed-off-by: Damien George <damien@micropython.org>
2022-04-14 23:52:12 +10:00
Damien George 24bc1f61f9 py/parse: Print const object value in mp_parse_node_print.
To give more information when printing the parse tree.

Signed-off-by: Damien George <damien@micropython.org>
2022-04-14 22:45:42 +10:00
Christian Zietz d6c59c9d72 tests/inlineasm: Add test for PUSH LR and POP PC. 2022-04-11 15:35:42 +10:00
Jon Bjarni Bjarnason 919f696ad2 extmod/modusocket: Implement optional socket.listen backlog argument.
This follows the CPython change: https://bugs.python.org/issue21455

Socket listen backlog defaults to 2 if not given, based on most bare metal
targets not having many resources for a large backlog.  On UNIX it defaults
to SOMAXCONN or 128, whichever is less.
2022-04-11 15:26:47 +10:00
Damien George 71344c15f4 tests/pyb: Update CAN tests to match revised CAN API.
Signed-off-by: Damien George <damien@micropython.org>
2022-04-02 22:46:31 +11:00
Damien George 1dbf393962 tests/basics/fun_callstardblstar: Add test for large arg allocation.
Signed-off-by: Damien George <damien@micropython.org>
2022-04-01 09:20:42 +11:00
Damien George bd556b6996 py: Fix compiling and decoding of *args at large arg positions.
There were two issues with the existing code:

1. "1 << i" is computed as a 32-bit number so would overflow when
   executed on 64-bit machines (when mp_uint_t is 64-bit).  This meant that
   *args beyond 32 positions would not be handled correctly.

2. star_args must fit as a positive small int so that it is encoded
   correctly in the emitted code.  MP_SMALL_INT_BITS is too big because it
   overflows a small int by 1 bit.  MP_SMALL_INT_BITS - 1 does not work
   because it produces a signed small int which is then sign extended when
   extracted (even by mp_obj_get_int_truncated), and this sign extension
   means that any position arg after *args is also treated as a star-arg.
   So the maximum bit position is MP_SMALL_INT_BITS - 2.  This means that
   MP_OBJ_SMALL_INT_VALUE() can be used instead of
   mp_obj_get_int_truncated() to get the value of star_args.

These issues are fixed by this commit, and a test added.

Signed-off-by: Damien George <damien@micropython.org>
2022-04-01 09:20:42 +11:00
David Lechner 47685180f0 tests/basics/fun_callstardblstar: Add coverage test.
This fixes code coverage for the case where a *arg without __len__ is
unpacked and uses exactly the amount of memory that was allocated for
kw args. This triggers the code branch where the memory for the kw args
gets reallocated since it was used already by the *arg unpacking.

Signed-off-by: David Lechner <david@pybricks.com>
2022-03-31 17:01:15 +11:00
David Lechner 783b1a868f py/runtime: Allow multiple *args in a function call.
This is a partial implementation of PEP 448 to allow unpacking multiple
star args in a function or method call.

This is implemented by changing the emitted bytecodes so that both
positional args and star args are stored as positional args.  A bitmap is
added to indicate if an argument at a given position is a positional
argument or a star arg.

In the generated code, this new bitmap takes the place of the old star arg.
It is stored as a small int, so this means only the first N arguments can
be star args where N is the number of bits in a small int.

The runtime is modified to interpret this new bytecode format while still
trying to perform as few memory reallocations as possible.

Signed-off-by: David Lechner <david@pybricks.com>
2022-03-31 16:59:30 +11:00
David Lechner 1e99d29f36 py/runtime: Allow multiple **args in a function call.
This is a partial implementation of PEP 448 to allow multiple ** unpackings
when calling a function or method.

The compiler is modified to encode the argument as a None: obj key-value
pair (similar to how regular keyword arguments are encoded as str: obj
pairs).  The extra object that was pushed on the stack to hold a single **
unpacking object is no longer used and is removed.

The runtime is modified to decode this new format.

Signed-off-by: David Lechner <david@pybricks.com>
2022-03-31 16:54:00 +11:00
Damien George 90aaf2dbef extmod/uasyncio: Fix gather cancelling and handling of exceptions.
The following fixes are made:
- cancelling a gather now cancels all sub-tasks of the gather (previously
  it would only cancel the first)
- if any sub-task of a gather raises an exception then the gather finishes
  (previously it would only finish if the first sub-task raised)

Fixes issues #5798, #7807, #7901.

Signed-off-by: Damien George <damien@micropython.org>
2022-03-30 16:07:44 +11:00
Damien George 3e70be8ee9 tests/extmod: Update I2S rate test to work on mimxrt.
Tested on Teensy 4.0.

Signed-off-by: Damien George <damien@micropython.org>
2022-03-30 14:14:57 +11:00
Damien George 7266285845 tests/extmod: Add test for machine.I2S data rate.
Signed-off-by: Damien George <damien@micropython.org>
2022-03-29 11:44:08 +11:00
Damien George acd2c5c834 py/emitbc: Add check for bytecode jump offset overflow.
Signed-off-by: Damien George <damien@micropython.org>
2022-03-28 15:41:51 +11:00
Damien George 538c3c0a55 py: Change jump opcodes to emit 1-byte jump offset when possible.
This commit introduces changes:

- All jump opcodes are changed to have variable length arguments, of either
  1 or 2 bytes (previously they were fixed at 2 bytes).  In most cases only
  1 byte is needed to encode the short jump offset, saving bytecode size.

- The bytecode emitter now selects 1 byte jump arguments when the jump
  offset is guaranteed to fit in 1 byte.  This is achieved by checking if
  the code size changed during the last pass and, if it did (if it shrank),
  then requesting that the compiler make another pass to get the correct
  offsets of the now-smaller code.  This can continue multiple times until
  the code stabilises.  The code can only ever shrink so this iteration is
  guaranteed to complete.  In most cases no extra passes are needed, the
  original 4 passes are enough to get it right by the 4th pass (because the
  2nd pass computes roughly the correct labels and the 3rd pass computes
  the correct size for the jump argument).

This change to the jump opcode encoding reduces .mpy files and RAM usage
(when bytecode is in RAM) by about 2% on average.

The performance of the VM is not impacted, at least within measurment of
the performance benchmark suite.

Code size is reduced for builds that include a decent amount of frozen
bytecode.  ARM Cortex-M builds without any frozen code increase by about
350 bytes.

Signed-off-by: Damien George <damien@micropython.org>
2022-03-28 15:41:38 +11:00
David Lechner e7a92c0e69 tests/cmdline/cmd_showbc: Fix spelling of sequence. 2022-03-25 12:11:17 +11:00
Damien George 63f0e700f4 extmod/modure: Set subject begin_line so ^ doesn't match interior.
Fixes issue #8402.

Signed-off-by: Damien George <damien@micropython.org>
2022-03-16 12:21:00 +11:00
Damien George 3c7cab4e98 py/parse: Put const bytes objects in parse tree as const object.
Instead of as an intermediate qstr, which may unnecessarily intern the data
of the bytes object.

Signed-off-by: Damien George <damien@micropython.org>
2022-03-16 00:41:10 +11:00
Damien George ac2293161e py/modsys: Add optional mutable attributes sys.ps1/ps2 and use them.
This allows customising the REPL prompt strings.

Signed-off-by: Damien George <damien@micropython.org>
2022-03-10 10:58:33 +11:00
Damien George cac939ddc3 py/modsys: Add optional sys.tracebacklimit attribute.
With behaviour as per CPython.

Signed-off-by: Damien George <damien@micropython.org>
2022-03-10 10:43:21 +11:00
Damien George d470c5a5ba tests/extmod/vfs_posix.py: Only test statvfs if it exists.
Signed-off-by: Damien George <damien@micropython.org>
2022-03-10 00:41:03 +11:00
Damien George 3440201e2e tests/micropython: Switch from set.pop to raise-0 to test exc strings.
To not rely on sets, which are an optional feature.

Signed-off-by: Damien George <damien@micropython.org>
2022-03-07 16:48:35 +11:00
Damien George 9a8ee6a5df tests/run-tests.py: Include test files ending in _set as set tests.
Signed-off-by: Damien George <damien@micropython.org>
2022-03-07 16:48:35 +11:00
Damien George 7cd166ff92 tests/basics: Add test for creating small-ints in nan-box builds.
Signed-off-by: Damien George <damien@micropython.org>
2022-03-07 15:25:11 +11:00
Damien George c4b8dae438 tests/unix: Add coverage test for freezing various objects.
Signed-off-by: Damien George <damien@micropython.org>
2022-02-28 19:02:58 +11:00
Damien George 414b59d39c qemu-arm: Add tests for freezing viper and asm_thumb code.
Signed-off-by: Damien George <damien@micropython.org>
2022-02-24 18:29:02 +11:00
Damien George 0a2895b099 tests/perf_bench: Skip bm_chaos test if random.randrange is unavailable.
Signed-off-by: Damien George <damien@micropython.org>
2022-02-24 18:29:02 +11:00
Damien George f2040bfc7e py: Rework bytecode and .mpy file format to be mostly static data.
Background: .mpy files are precompiled .py files, built using mpy-cross,
that contain compiled bytecode functions (and can also contain machine
code). The benefit of using an .mpy file over a .py file is that they are
faster to import and take less memory when importing.  They are also
smaller on disk.

But the real benefit of .mpy files comes when they are frozen into the
firmware.  This is done by loading the .mpy file during compilation of the
firmware and turning it into a set of big C data structures (the job of
mpy-tool.py), which are then compiled and downloaded into the ROM of a
device.  These C data structures can be executed in-place, ie directly from
ROM.  This makes importing even faster because there is very little to do,
and also means such frozen modules take up much less RAM (because their
bytecode stays in ROM).

The downside of frozen code is that it requires recompiling and reflashing
the entire firmware.  This can be a big barrier to entry, slows down
development time, and makes it harder to do OTA updates of frozen code
(because the whole firmware must be updated).

This commit attempts to solve this problem by providing a solution that
sits between loading .mpy files into RAM and freezing them into the
firmware.  The .mpy file format has been reworked so that it consists of
data and bytecode which is mostly static and ready to run in-place.  If
these new .mpy files are located in flash/ROM which is memory addressable,
the .mpy file can be executed (mostly) in-place.

With this approach there is still a small amount of unpacking and linking
of the .mpy file that needs to be done when it's imported, but it's still
much better than loading an .mpy from disk into RAM (although not as good
as freezing .mpy files into the firmware).

The main trick to make static .mpy files is to adjust the bytecode so any
qstrs that it references now go through a lookup table to convert from
local qstr number in the module to global qstr number in the firmware.
That means the bytecode does not need linking/rewriting of qstrs when it's
loaded.  Instead only a small qstr table needs to be built (and put in RAM)
at import time.  This means the bytecode itself is static/constant and can
be used directly if it's in addressable memory.  Also the qstr string data
in the .mpy file, and some constant object data, can be used directly.
Note that the qstr table is global to the module (ie not per function).

In more detail, in the VM what used to be (schematically):

    qst = DECODE_QSTR_VALUE;

is now (schematically):

    idx = DECODE_QSTR_INDEX;
    qst = qstr_table[idx];

That allows the bytecode to be fixed at compile time and not need
relinking/rewriting of the qstr values.  Only qstr_table needs to be linked
when the .mpy is loaded.

Incidentally, this helps to reduce the size of bytecode because what used
to be 2-byte qstr values in the bytecode are now (mostly) 1-byte indices.
If the module uses the same qstr more than two times then the bytecode is
smaller than before.

The following changes are measured for this commit compared to the
previous (the baseline):
- average 7%-9% reduction in size of .mpy files
- frozen code size is reduced by about 5%-7%
- importing .py files uses about 5% less RAM in total
- importing .mpy files uses about 4% less RAM in total
- importing .py and .mpy files takes about the same time as before

The qstr indirection in the bytecode has only a small impact on VM
performance.  For stm32 on PYBv1.0 the performance change of this commit
is:

diff of scores (higher is better)
N=100 M=100             baseline -> this-commit  diff      diff% (error%)
bm_chaos.py               371.07 ->  357.39 :  -13.68 =  -3.687% (+/-0.02%)
bm_fannkuch.py             78.72 ->   77.49 :   -1.23 =  -1.563% (+/-0.01%)
bm_fft.py                2591.73 -> 2539.28 :  -52.45 =  -2.024% (+/-0.00%)
bm_float.py              6034.93 -> 5908.30 : -126.63 =  -2.098% (+/-0.01%)
bm_hexiom.py               48.96 ->   47.93 :   -1.03 =  -2.104% (+/-0.00%)
bm_nqueens.py            4510.63 -> 4459.94 :  -50.69 =  -1.124% (+/-0.00%)
bm_pidigits.py            650.28 ->  644.96 :   -5.32 =  -0.818% (+/-0.23%)
core_import_mpy_multi.py  564.77 ->  581.49 :  +16.72 =  +2.960% (+/-0.01%)
core_import_mpy_single.py  68.67 ->   67.16 :   -1.51 =  -2.199% (+/-0.01%)
core_qstr.py               64.16 ->   64.12 :   -0.04 =  -0.062% (+/-0.00%)
core_yield_from.py        362.58 ->  354.50 :   -8.08 =  -2.228% (+/-0.00%)
misc_aes.py               429.69 ->  405.59 :  -24.10 =  -5.609% (+/-0.01%)
misc_mandel.py           3485.13 -> 3416.51 :  -68.62 =  -1.969% (+/-0.00%)
misc_pystone.py          2496.53 -> 2405.56 :  -90.97 =  -3.644% (+/-0.01%)
misc_raytrace.py          381.47 ->  374.01 :   -7.46 =  -1.956% (+/-0.01%)
viper_call0.py            576.73 ->  572.49 :   -4.24 =  -0.735% (+/-0.04%)
viper_call1a.py           550.37 ->  546.21 :   -4.16 =  -0.756% (+/-0.09%)
viper_call1b.py           438.23 ->  435.68 :   -2.55 =  -0.582% (+/-0.06%)
viper_call1c.py           442.84 ->  440.04 :   -2.80 =  -0.632% (+/-0.08%)
viper_call2a.py           536.31 ->  532.35 :   -3.96 =  -0.738% (+/-0.06%)
viper_call2b.py           382.34 ->  377.07 :   -5.27 =  -1.378% (+/-0.03%)

And for unix on x64:

diff of scores (higher is better)
N=2000 M=2000        baseline -> this-commit     diff      diff% (error%)
bm_chaos.py          13594.20 ->  13073.84 :  -520.36 =  -3.828% (+/-5.44%)
bm_fannkuch.py          60.63 ->     59.58 :    -1.05 =  -1.732% (+/-3.01%)
bm_fft.py           112009.15 -> 111603.32 :  -405.83 =  -0.362% (+/-4.03%)
bm_float.py         246202.55 -> 247923.81 : +1721.26 =  +0.699% (+/-2.79%)
bm_hexiom.py           615.65 ->    617.21 :    +1.56 =  +0.253% (+/-1.64%)
bm_nqueens.py       215807.95 -> 215600.96 :  -206.99 =  -0.096% (+/-3.52%)
bm_pidigits.py        8246.74 ->   8422.82 :  +176.08 =  +2.135% (+/-3.64%)
misc_aes.py          16133.00 ->  16452.74 :  +319.74 =  +1.982% (+/-1.50%)
misc_mandel.py      128146.69 -> 130796.43 : +2649.74 =  +2.068% (+/-3.18%)
misc_pystone.py      83811.49 ->  83124.85 :  -686.64 =  -0.819% (+/-1.03%)
misc_raytrace.py     21688.02 ->  21385.10 :  -302.92 =  -1.397% (+/-3.20%)

The code size change is (firmware with a lot of frozen code benefits the
most):

       bare-arm:  +396 +0.697%
    minimal x86: +1595 +0.979% [incl +32(data)]
       unix x64: +2408 +0.470% [incl +800(data)]
    unix nanbox: +1396 +0.309% [incl -96(data)]
          stm32: -1256 -0.318% PYBV10
         cc3200:  +288 +0.157%
        esp8266:  -260 -0.037% GENERIC
          esp32:  -216 -0.014% GENERIC[incl -1072(data)]
            nrf:  +116 +0.067% pca10040
            rp2:  -664 -0.135% PICO
           samd:  +844 +0.607% ADAFRUIT_ITSYBITSY_M4_EXPRESS

As part of this change the .mpy file format version is bumped to version 6.
And mpy-tool.py has been improved to provide a good visualisation of the
contents of .mpy files.

In summary: this commit changes the bytecode to use qstr indirection, and
reworks the .mpy file format to be simpler and allow .mpy files to be
executed in-place.  Performance is not impacted too much.  Eventually it
will be possible to store such .mpy files in a linear, read-only, memory-
mappable filesystem so they can be executed from flash/ROM.  This will
essentially be able to replace frozen code for most applications.

Signed-off-by: Damien George <damien@micropython.org>
2022-02-24 18:08:43 +11:00
stijn ff9c708507 tests/run-tests.py: Skip repl tests when running windows underneath.
Some versions of Python (for instance: the mingw-w64 version which can be
installed on MSYS2) do include a pty module and claim to be posix-like
(os.name == 'posix'), yet the select.select call used in run-tests.py hangs
forever.  To be on the safe side just exclude anything which might be
running on windows.
2022-02-18 15:14:47 +11:00
Damien George 2ea21abae0 tests/extmod/vfs_fat_finaliser.py: Make finalisation more robust.
Signed-off-by: Damien George <damien@micropython.org>
2022-02-12 09:45:32 +11:00
Damien George e8bc4a3a5b tests/run-perfbench.py: Use SKIP consistently, and increase print width.
A script will print "SKIP" if it wants to be skipped, so the test runner
must also use uppercase SKIP.

Signed-off-by: Damien George <damien@micropython.org>
2022-02-11 22:19:38 +11:00
Damien George a434705700 tests/perf_bench: Add perf test for yield-from execution.
Signed-off-by: Damien George <damien@micropython.org>
2022-02-11 13:42:00 +11:00
Damien George 75da124cf8 tests/perf_bench: Add perf tests for qstr interning and importing .mpy.
Signed-off-by: Damien George <damien@micropython.org>
2022-02-10 15:25:33 +11:00
Damien George b33fdbe535 tests/run-perfbench.py: Allow a test to SKIP, and to have a .exp file.
Signed-off-by: Damien George <damien@micropython.org>
2022-02-10 15:25:33 +11:00
iabdalkader 30a022548f tests/multi_net/udp_data.py: Make UDP test more reliable.
The current test depends on a specific number and order of packets to pass,
which can't be reproduced every run due to the unreliable UDP protocol.
This patch adds simple packets sequencing, retransmits with timeouts, and a
packet loss threshold, to make the test more tolerant to UDP protocol
packet drops and reordering.
2022-02-09 14:05:01 +11:00
Damien George ab2923dfa1 all: Update Python formatting to latest Black version 22.1.0.
Signed-off-by: Damien George <damien@micropython.org>
2022-02-02 16:49:55 +11:00
Christian Decker 2e3a2785cd extmod/modubinascii: Add newline keyword to b2a_base64 function.
This allows encoding things (eg a Basic-Auth header for a request) without
slicing the \n from the string, which allocates additional memory.

Co-authored-by: David Lechner <david@lechnology.com>
2022-01-23 10:18:01 +11:00
stijn dd6967202a py/modmath: Add math.tau, math.nan and math.inf constants.
Configurable by the new MICROPY_PY_MATH_CONSTANTS option.
2022-01-23 09:28:33 +11:00
iabdalkader 6e8f4eaa52 tests/multi_net/udp_data.py: Allow reusing port before bind. 2022-01-21 13:34:33 +11:00
iabdalkader e6ddda29ca tests/multi_net: Close accepted sockets when tests are done.
gc_sweep_all() cleans up sockets via the finaliser, but tests should
cleanly free resources they use.
2022-01-21 13:34:20 +11:00
Jeff Epler 037b2c72a1 py/objstr: Support '{:08}'.format("Jan") like Python 3.10.
The new test has an .exp file, because it is not compatible with Python 3.9
and lower.

See CPython version of the issue at https://bugs.python.org/issue27772

Signed-off-by: Jeff Epler <jepler@gmail.com>
2022-01-19 15:34:32 +11:00
Damien George 2c9dc5742a tests/multi_net: Add testing key/cert to SSL server/client test.
So that this tests works with mbedtls.

Signed-off-by: Damien George <damien@micropython.org>
2022-01-17 17:35:04 +11:00
Damien George c54717a78f tests/run-multitests.py: Set HOST_IP so tests work between PC and board.
Signed-off-by: Damien George <damien@micropython.org>
2022-01-17 17:35:04 +11:00
Damien George 5df1d8be6c tests/run-multitests.py: Ignore lld_pdu_get_tx_flush_nb msgs from IDF.
BLE still functions correctly even though these messages are sometimes
printed by the IDF.  Ignoring them allows the multi_bluetooth tests to pass
on an esp32 board.

Signed-off-by: Damien George <damien@micropython.org>
2022-01-17 14:23:24 +11:00
stijn 19d949a866 tests/extmod: Skip uselect_poll_udp when poll() is not available.
This is the same fix as applied in uselect_poll_basic.py.
2022-01-04 15:07:45 +11:00
Damien George aac5a97d08 ports: Move '.frozen' to second entry in sys.path.
In commit 86ce442607 the '.frozen' entry was
added at the start of sys.path, to allow control over when frozen modules
are searched during import, and retain existing behaviour whereby frozen
was searched before the filesystem.

But Python semantics of sys.path require sys.path[0] to be the directory of
the currently executing script, or ''.

This commit moves the '.frozen' entry to second place in sys.path, so
sys.path[0] retains its correct value (described above).

Signed-off-by: Damien George <damien@micropython.org>
2021-12-29 23:55:36 +11:00
Damien George c768704cfd tests/basics/int_big_cmp.py: Add more tests for big-int comparison.
To improve coverage of mpz_cmp and mpn_cmp.

Signed-off-by: Damien George <damien@micropython.org>
2021-12-21 18:00:11 +11:00
Damien George 2c139bbf4e py/mpz: Fix bugs with bitwise of -0 by ensuring all 0's are positive.
This commit makes sure that the value zero is always encoded in an mpz_t as
neg=0 and len=0 (previously it was just len=0).

This invariant is needed for some of the bitwise operations that operate on
negative numbers, because they cannot handle -0.  For example
(-((1<<100)-(1<<100)))|1 was being computed as -65535, instead of 1.

Fixes issue #8042.

Signed-off-by: Damien George <damien@micropython.org>
2021-12-21 18:00:05 +11:00
Jim Mussared cc23e99f32 py/modio: Remove io.resource_stream function.
This feature is not enabled on any port, it's not in CPython's io module,
and functionality is better suited to the micropython-lib implementation of
pkg_resources.
2021-12-17 23:53:44 +11:00
Jim Mussared 3770fab334 all: Update Python formatting to latest Black version 21.12b0.
Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2021-12-09 12:09:40 +11:00
Jim Mussared e99f7b6d25 tests/cpydiff: Clarify f-string diffs regarding concatenation.
Concatenation of any literals (including f-strings) should be avoided.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2021-11-25 22:09:59 +11:00
Damien George 11ed94797d py/lexer: Support nested [] and {} characters within f-string params.
Signed-off-by: Damien George <damien@micropython.org>
2021-11-25 21:50:58 +11:00
Damien George 78ab2eeda3 py/showbc: Print unary-op string when dumping bytecode.
Signed-off-by: Damien George <damien@micropython.org>
2021-11-19 17:05:40 +11:00
jc_.kim 19f09414a6 tests/micropython/const.py: Add comment about required config for test.
Expected result of const.py will be matched only when MICROPY_COMP_CONST is
enabled.  For easy understanding, added description at the first of the
test code.
2021-11-17 14:28:20 +11:00
Damien George 43d08688c3 extmod/uasyncio: Fix gather returning exceptions from a cancelled task.
Fixes issue #5882.
2021-11-17 14:11:31 +11:00
Mike Wadsten c3c2c37fbc tests/basics: Add tests for type-checking subclassed exc instances. 2021-10-21 12:42:48 +11:00
Jim Mussared b326edf68c all: Remove MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE.
This commit removes all parts of code associated with the existing
MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE optimisation option, including the
-mcache-lookup-bc option to mpy-cross.

This feature originally provided a significant performance boost for Unix,
but wasn't able to be enabled for MCU targets (due to frozen bytecode), and
added significant extra complexity to generating and distributing .mpy
files.

The equivalent performance gain is now provided by the combination of
MICROPY_OPT_LOAD_ATTR_FAST_PATH and MICROPY_OPT_MAP_LOOKUP_CACHE (which has
been enabled on the unix port in the previous commit).

It's hard to provide precise performance numbers, but tests have been run
on a wide variety of architectures (x86-64, ARM Cortex, Aarch64, RISC-V,
xtensa) and they all generally agree on the qualitative improvements seen
by the combination of MICROPY_OPT_LOAD_ATTR_FAST_PATH and
MICROPY_OPT_MAP_LOOKUP_CACHE.

For example, on a "quiet" Linux x64 environment (i3-5010U @ 2.10GHz) the
change from CACHE_MAP_LOOKUP_IN_BYTECODE, to LOAD_ATTR_FAST_PATH combined
with MAP_LOOKUP_CACHE is:

diff of scores (higher is better)
N=2000 M=2000       bccache -> attrmapcache      diff      diff% (error%)
bm_chaos.py        13742.56 ->   13905.67 :   +163.11 =  +1.187% (+/-3.75%)
bm_fannkuch.py        60.13 ->      61.34 :     +1.21 =  +2.012% (+/-2.11%)
bm_fft.py         113083.20 ->  114793.68 :  +1710.48 =  +1.513% (+/-1.57%)
bm_float.py       256552.80 ->  243908.29 : -12644.51 =  -4.929% (+/-1.90%)
bm_hexiom.py         521.93 ->     625.41 :   +103.48 = +19.826% (+/-0.40%)
bm_nqueens.py     197544.25 ->  217713.12 : +20168.87 = +10.210% (+/-3.01%)
bm_pidigits.py      8072.98 ->    8198.75 :   +125.77 =  +1.558% (+/-3.22%)
misc_aes.py        17283.45 ->   16480.52 :   -802.93 =  -4.646% (+/-0.82%)
misc_mandel.py     99083.99 ->  128939.84 : +29855.85 = +30.132% (+/-5.88%)
misc_pystone.py    83860.10 ->   82592.56 :  -1267.54 =  -1.511% (+/-2.27%)
misc_raytrace.py   21490.40 ->   22227.23 :   +736.83 =  +3.429% (+/-1.88%)

This shows that the new optimisations are at least as good as the existing
inline-bytecode-caching, and are sometimes much better (because the new
ones apply caching to a wider variety of map lookups).

The new optimisations can also benefit code generated by the native
emitter, because they apply to the runtime rather than the generated code.
The improvement for the native emitter when LOAD_ATTR_FAST_PATH and
MAP_LOOKUP_CACHE are enabled is (same Linux environment as above):

diff of scores (higher is better)
N=2000 M=2000        native -> nat-attrmapcache  diff      diff% (error%)
bm_chaos.py        14130.62 ->   15464.68 :  +1334.06 =  +9.441% (+/-7.11%)
bm_fannkuch.py        74.96 ->      76.16 :     +1.20 =  +1.601% (+/-1.80%)
bm_fft.py         166682.99 ->  168221.86 :  +1538.87 =  +0.923% (+/-4.20%)
bm_float.py       233415.23 ->  265524.90 : +32109.67 = +13.756% (+/-2.57%)
bm_hexiom.py         628.59 ->     734.17 :   +105.58 = +16.796% (+/-1.39%)
bm_nqueens.py     225418.44 ->  232926.45 :  +7508.01 =  +3.331% (+/-3.10%)
bm_pidigits.py      6322.00 ->    6379.52 :    +57.52 =  +0.910% (+/-5.62%)
misc_aes.py        20670.10 ->   27223.18 :  +6553.08 = +31.703% (+/-1.56%)
misc_mandel.py    138221.11 ->  152014.01 : +13792.90 =  +9.979% (+/-2.46%)
misc_pystone.py    85032.14 ->  105681.44 : +20649.30 = +24.284% (+/-2.25%)
misc_raytrace.py   19800.01 ->   23350.73 :  +3550.72 = +17.933% (+/-2.79%)

In summary, compared to MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE, the new
MICROPY_OPT_LOAD_ATTR_FAST_PATH and MICROPY_OPT_MAP_LOOKUP_CACHE options:
- are simpler;
- take less code size;
- are faster (generally);
- work with code generated by the native emitter;
- can be used on embedded targets with a small and constant RAM overhead;
- allow the same .mpy bytecode to run on all targets.

See #7680 for further discussion.  And see also #7653 for a discussion
about simplifying mpy-cross options.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2021-09-16 16:04:03 +10:00
Damien George 426785a19e py/emitnative: Ensure load_subscr does not clobber existing REG_RET.
Fixes issue #7782, and part of issue #6314.

Signed-off-by: Damien George <damien@micropython.org>
2021-09-13 22:30:24 +10:00
Damien George c0761d28fc tests/perf_bench: Use math.log instead of math.log2.
So MICROPY_PY_MATH_SPECIAL_FUNCTIONS is not needed for these performance
tests.

Signed-off-by: Damien George <damien@micropython.org>
2021-09-13 18:27:39 +10:00
Damien George 08ff71dfcd tests/pybnative: Make while.py test run on boards without pyb.delay.
Signed-off-by: Damien George <damien@micropython.org>
2021-09-01 00:43:41 +10:00
Damien George 8c4ba575fd tests/basics: Split f-string debug printing to separate file with .exp.
This feature {x=} was introduced in Python 3.8 so needs a separate .exp
file to run on earlier Python versions.

See https://bugs.python.org/issue36817

Signed-off-by: Damien George <damien@micropython.org>
2021-08-26 23:56:02 +10:00
Peter Hinch 2296df0a32 extmod/modframebuf: Enable blit between different formats via a palette.
This achieves a substantial performance improvement when rendering glyphs
to color displays, the benefit increasing proportional to the number of
pixels in the glyph.
2021-08-25 15:31:23 +10:00
Jim Mussared 91a99fcf0e tests/extmod/vfs_fat_finaliser.py: Ensure alloc at never-used GC blocks.
Prevents the finaliser from being missed if there's a dangling reference
on the stack to one of the blocks for the files (that this test checks
that they get finalised).

See github.com/micropython/micropython/pull/7659#issuecomment-899479793

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2021-08-17 11:20:58 +10:00
Jim Mussared c70930fb24 tests/multi_bluetooth/ble_subscribe.py: Add test for subscription.
This tests both sending indications/notifications from a server to
subscribed clients via gatts_write(...,send_update=True) and subscribing
from a client.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2021-08-14 22:44:47 +10:00
Jim Mussared 692d36d779 py: Implement partial PEP-498 (f-string) support.
This implements (most of) the PEP-498 spec for f-strings and is based on
https://github.com/micropython/micropython/pull/4998 by @klardotsh.

It is implemented in the lexer as a syntax translation to `str.format`:
  f"{a}" --> "{}".format(a)

It also supports:
  f"{a=}" --> "a={}".format(a)

This is done by extracting the arguments into a temporary vstr buffer,
then after the string has been tokenized, the lexer input queue is saved
and the contents of the temporary vstr buffer are injected into the lexer
instead.

There are four main limitations:
- raw f-strings (`fr` or `rf` prefixes) are not supported and will raise
  `SyntaxError: raw f-strings are not supported`.

- literal concatenation of f-strings with adjacent strings will fail
    "{}" f"{a}" --> "{}{}".format(a)    (str.format will incorrectly use
                                         the braces from the non-f-string)
    f"{a}" f"{a}" --> "{}".format(a) "{}".format(a) (cannot concatenate)

- PEP-498 requires the full parser to understand the interpolated
  argument, however because this entirely runs in the lexer it cannot
  resolve nested braces in expressions like
    f"{'}'}"

- The !r, !s, and !a conversions are not supported.

Includes tests and cpydiffs.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2021-08-14 16:58:40 +10:00
Damien George 8fcdb5490c extmod/modlwip: Fix close and clean up of UDP and raw sockets.
The correct callback-deregister functions must be called dependent on the
socket type, otherwise resources may not be freed correctly.

Signed-off-by: Damien George <damien@micropython.org>
2021-08-13 23:46:11 +10:00
Damien George 90d47ee34d tests/run-multitests.py: Add broadcast and wait facility.
Test instances can now use the following methods to synchronise their
execution:

    multitest.broadcast("sync message")
    multitest.wait("sync message")

Signed-off-by: Damien George <damien@micropython.org>
2021-08-13 23:26:34 +10:00
Peter Züger d290f369d0 tests/extmod/ujson: Add tests for dump/dumps separators argument.
Basically just copied ujson_dump(s).py and added various valid/invalid
separator tests.

Signed-off-by: Peter Züger <zueger.peter@icloud.com>
2021-08-07 13:52:16 +10:00
Jim Mussared 4e39ff221a py/runtime: Fix bool unary op for subclasses of native types.
Previously a subclass of a type that didn't implement unary_op, or didn't
handle MP_UNARY_OP_BOOL, would raise TypeError on bool conversion.

Fixes #5677.
2021-07-23 12:40:00 +10:00
Jim Mussared 0e3752e82a py/emitnative: Ensure stack settling is safe mid-branch.
And add a test for the case where REG_RET could be in use.

Fixes #7523.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2021-07-19 23:18:59 +10:00
David P f365025c9c stm32: Replace master/slave with controller/peripheral in I2C and SPI.
Replace "master" with "controller" and "slave" with "peripheral" in
comments, errors, and debug messages.

Add CONTROLLER and PERIPHERAL constants to pyb.SPI and pyb.I2C classes;
retain MASTER and SLAVE constants for backward compatiblity.
2021-07-18 11:23:41 +10:00
Damien George bb00125aaa py: Support single argument to optimised MP_OBJ_STOP_ITERATION.
The MP_OBJ_STOP_ITERATION optimisation is a shortcut for creating a
StopIteration() exception object, and means that heap memory does not need
to be allocated for the exception (in cases where it can be used).  This
commit allows this optimised object to take an optional argument (before,
it could only have no argument).

The commit also adds some new tests to cover corner cases with
StopIteration and generators that previously did not work.

Signed-off-by: Damien George <damien@micropython.org>
2021-07-15 00:12:41 +10:00
Damien George e3825e28e6 py/objexcept: Make mp_obj_exception_get_value support subclassed excs.
Signed-off-by: Damien George <damien@micropython.org>
2021-07-15 00:12:41 +10:00
David Lechner cd506d6220 tests/cpydiff/modules_struct_whitespace_in_format: Run black.
This test snuck through without proper formatting and is causing CI for
other unrelated changes to fail.

Signed-off-by: David Lechner <david@pybricks.com>
2021-07-06 18:19:55 -05:00
Tom McDermott c1f74b3005 docs/library: Warn that ustruct doesn't handle spaces in format strings.
And also add a test to capture the CPython difference.
2021-07-06 14:59:50 +10:00
David Lechner 58e4d72338 py/objexcept: Pretty print OSError also when it has 2 arguments.
This extends pretty-printing of OSError's to handle two arguments when the
exception name is known.

Signed-off-by: David Lechner <david@pybricks.com>
2021-07-01 13:23:54 +10:00
Damien George 7ec95c2768 extmod/uasyncio: Get addr and bind server socket before creating task.
Currently when using uasyncio.start_server() the socket configuration is
done inside a uasyncio.create_task() background function.  If the address
and port are already in use however this throws an OSError which cannot be
cleanly caught behind the create_task().

This commit moves the getaddrinfo and socket binding to the start_server()
function, and only creates the task if that succeeds.  This means that any
OSError from the initial socket configuration is propagated directly up the
call stack, compatible with CPython behaviour.

See #7444.

Signed-off-by: Damien George <damien@micropython.org>
2021-06-26 22:30:22 +10:00
Damien George 180c54d6cc tests/extmod: Make uasyncio_heaplock test more deterministic.
This helps the test pass on systems with an inaccurate sleep time.

Signed-off-by: Damien George <damien@micropython.org>
2021-06-25 11:31:00 +10:00
Damien George adf35cbab0 tests/float: Make bytes/bytearray construct tests work with obj repr C.
2.5 can be represented correctly in object representation C, but 2.3 cannot
(it is slightly truncated).

Signed-off-by: Damien George <damien@micropython.org>
2021-06-18 14:16:07 +10:00
Damien George 514bf1a191 extmod/uasyncio: Fix race with cancelled task waiting on finished task.
This commit fixes a problem with a race between cancellation of task A and
completion of task B, when A waits on B.  If task B completes just before
task A is cancelled then the cancellation of A does not work.  Instead,
the CancelledError meant to cancel A gets passed through to B (that's
expected behaviour) but B handles it as a "Task exception wasn't retrieved"
scenario, printing out such a message (this is because finished tasks point
their "coro" attribute to themselves to indicate they are done, and
implement the throw() method, but that method inadvertently catches the
CancelledError).  The correct behaviour is for B to bounce that
CancelledError back out.

This bug is mainly seen when wait_for() is used, and in that context the
symptoms are:
- occurs when using wait_for(T, S), if the task T being waited on finishes
  at exactly the same time as the wait-for timeout S expires
- task T will have run to completion
- the "Task exception wasn't retrieved message" is printed with
  "<class 'CancelledError'>" as the error (ie no traceback)
- the wait_for(T, S) call never returns (it's never put back on the
  uasyncio run queue) and all tasks waiting on this are blocked forever
  from running
- uasyncio otherwise continues to function and other tasks continue to be
  scheduled as normal

The fix here reworks the "waiting" attribute of Task to be called "state"
and uses it to indicate whether a task is: running and not awaited on,
running and awaited on, finished and not awaited on, or finished and
awaited on.  This means the task does not need to point "coro" to itself to
indicate finished, and also allows removal of the throw() method.

A benefit of this is that "Task exception wasn't retrieved" messages can go
back to being able to print the name of the coroutine function.

Fixes issue #7386.

Signed-off-by: Damien George <damien@micropython.org>
2021-06-16 13:02:37 +10:00
Mike Teachman b0b8ebc4f6 extmod/uasyncio: Add readinto() method to Stream class.
With docs and a multi-test using TCP server/client.

This method is a MicroPython extension, although there is discussion of
adding it to CPython: https://bugs.python.org/issue41305

Signed-off-by: Mike Teachman <mike.teachman@gmail.com>
2021-06-15 13:13:35 +10:00
Zoltán Vörös c4ed17ff34 tests/cpydiff: Add test for array constructor with overflowing value. 2021-06-13 10:30:14 +10:00
Damien George 20a8f4f7ec tests/unix: Add ffi test for integer types.
Signed-off-by: Damien George <damien@micropython.org>
2021-06-06 22:52:25 +10:00
Damien George 7842085434 tests/multi_bluetooth/ble_gap_advertise.py: Allow to work without set.
Signed-off-by: Damien George <damien@micropython.org>
2021-06-06 21:58:07 +10:00
Damien George da8e47da21 tests/run-multitests.py: Allow to work without sys.stdout on target.
Signed-off-by: Damien George <damien@micropython.org>
2021-06-06 21:58:07 +10:00
Damien George 53519e322a py/builtinimport: Change relative import's ValueError to ImportError.
Following CPython change, see https://bugs.python.org/issue37444.

Signed-off-by: Damien George <damien@micropython.org>
2021-05-30 19:35:03 +10:00
Damien George c3199f5649 extmod/modurandom: Support an argument of bits=0 to getrandbits.
This was changed in CPython 3.9; see https://bugs.python.org/issue40282.

Signed-off-by: Damien George <damien@micropython.org>
2021-05-30 17:05:56 +10:00
Macarthur Inbody 34d4dab683 extmod/modurandom: Add error message when getrandbits has bad value.
The random module's getrandbits() method didn't give a proper error message
when calling it with a value that was outside of the range of 1-32, which
can lead to confusion using this function (which under CPython can accept
numbers larger than 32).  Now instead of simply giving a ValueError it
gives an error message that states that the number of bits is constrained.

Also, since the random module's functions getrandbits() and randint()
differ from CPython, tests have been added to describe these differences.
For getrandbits the relevant documentation is shown and added to the docs.
The same is given for randint method so that the information is more easily
found.

Finally, since the int object lacks the bit_length() method there is a test
for that method also to include within the docs, showing the difference to
CPython.
2021-05-30 16:41:30 +10:00
Damien George 025e4b6fbc tests/basics: Split out literal tests that raise SyntaxWarning on CPy.
Fixes issue #7330.

Signed-off-by: Damien George <damien@micropython.org>
2021-05-30 13:41:37 +10:00
Jeff Epler 486fe71c6e tests/extmod/btree_gc.py: Close the database to avoid a memory leak.
Signed-off-by: Jeff Epler <jepler@gmail.com>
2021-05-30 11:50:51 +10:00
Jeff Epler f2dbc91022 py/compile: Raise an error on async with/for outside an async function.
A simple reproducer is:

   async for x in (): x

Before this change, it would cause an assertion error in mpy-cross and
micropython-coverage.
2021-05-30 10:38:48 +10:00
Damien George 6a127810c0 extmod/moduhashlib: Put hash obj in final state after digest is called.
If digest is called then the hash object is put in a "final" state and
calling update() or digest() again will raise a ValueError (instead of
silently producing the wrong result).

See issue #4119.

Signed-off-by: Damien George <damien@micropython.org>
2021-05-26 21:44:46 +10:00
Damien George dc86e04476 tests: Make float and framebuf tests skip or run on big-endian archs.
Signed-off-by: Damien George <damien@micropython.org>
2021-05-26 16:33:18 +10:00
Damien George 5176a2d732 py/emitnative: Fix x86-64 emitter to generate correct 8/16-bit stores.
Fixes issue #6643.

Signed-off-by: Damien George <damien@micropython.org>
2021-05-20 23:43:25 +10:00
Damien George 6d2680fa36 py/objarray: Fix constructing a memoryview from a memoryview.
Fixes issue #7261.

Signed-off-by: Damien George <damien@micropython.org>
2021-05-18 10:18:56 +10:00
Damien George 47e6c52f0c tests/cpydiff: Add test and workaround for function.__module__ attr.
MicroPython does not store any reference from a function object to the
module it was defined in, but there is a way to use function.__globals__ to
indirectly get the module.

See issue #7259.

Signed-off-by: Damien George <damien@micropython.org>
2021-05-16 11:06:46 +10:00
Jeff Epler 94a3f8a4b0 tests/run-tests.py: Parallelize running tests by default.
This significantly reduces the time taken to run the test suite (on the
unix port).  Use `-j1` to disable this feature.

Signed-off-by: Jeff Epler <jepler@gmail.com>
2021-05-14 11:33:31 +10:00
stijn 09be0c083c py/objarray: Implement more/less comparisons for array. 2021-05-13 22:16:14 +10:00
stijn 57365d8557 py/objarray: Prohibit comparison of mismatching types.
Array equality is defined as each element being equal but to keep
code size down MicroPython implements a binary comparison.  This
can only be used correctly for elements with the same binary layout
though so turn it into an NotImplementedError when comparing types
for which the binary comparison yielded incorrect results: types
with different sizes, and floating point numbers because nan != nan.
2021-05-13 22:16:14 +10:00
Damien George 6affcb0104 tests/run-multitests.py: Flush stdout for each line of trace output.
Signed-off-by: Damien George <damien@micropython.org>
2021-05-13 16:26:07 +10:00
Damien George 18d984c8b2 tests/run-perfbench.py: Fix native feature check.
This was broken by 8459f538eb

Signed-off-by: Damien George <damien@micropython.org>
2021-05-11 23:45:36 +10:00
Damien George 4cdcbdb753 tests/thread: Make exc1,exit1,exit2,stacksize1,start1 tests run on rp2.
The RP2040 has 2 cores and supports running at most 2 Python threads (the
main one plus another), and will raise OSError if a thread cannot be
created because core1 is already in use.  This commit adjusts some thread
tests to be robust against such OSError's.  These tests now pass on rp2
boards.

Signed-off-by: Damien George <damien@micropython.org>
2021-05-10 13:07:16 +10:00
Damien George b6b39bff47 py/gc: Make gc_lock_depth have a count per thread.
This commit makes gc_lock_depth have one counter per thread, instead of one
global counter.  This makes threads properly independent with respect to
the GC, in particular threads can now independently lock the GC for
themselves without locking it for other threads.  It also means a given
thread can run a hard IRQ without temporarily locking the GC for all other
threads and potentially making them have MemoryError exceptions at random
locations (this really only occurs on MCUs with multiple cores and no GIL,
eg on the rp2 port).

The commit also removes protection of the GC lock/unlock functions, which
is no longer needed when the counter is per thread (and this also fixes the
cas where a hard IRQ calling gc_lock() may stall waiting for the mutex).

It also puts the check for `gc_lock_depth > 0` outside the GC mutex in
gc_alloc, gc_realloc and gc_free, to potentially prevent a hard IRQ from
waiting on a mutex if it does attempt to allocate heap memory (and putting
the check outside the GC mutex is now safe now that there is a
gc_lock_depth per thread).

Signed-off-by: Damien George <damien@micropython.org>
2021-05-10 13:07:16 +10:00
Damien George 7b923d6c72 tests/thread: Make stress_aes.py test run on bare-metal ports.
This is a long-running test, so make it run in reasonable time on slower,
bare-metal ports.

Signed-off-by: Damien George <damien@micropython.org>
2021-05-08 22:47:03 +10:00
Damien George 9340cfe774 tests/thread: Make stress_create.py test run on esp32.
The esp32 port needs to be idle for finished threads and their resources to
be freed up.

Signed-off-by: Damien George <damien@micropython.org>
2021-05-08 22:47:03 +10:00
Damien George 864e4ecc47 esp32/mpthreadport: Use binary semaphore instead of mutex.
So a lock can be acquired on one Python thread and then released on
another.  A test for this is added.

Signed-off-by: Damien George <damien@micropython.org>
2021-05-08 22:47:03 +10:00
Damien George 47583d8cbd extmod/moductypes: Fix size and offset calculation for ARRAY of FLOAT32.
uctypes.FLOAT32 has a special value representation and
uctypes_struct_scalar_size() should be used instead of GET_SCALAR_SIZE().

Signed-off-by: Damien George <damien@micropython.org>
2021-05-06 13:11:33 +10:00
Damien George 9e29217c73 unix/modffi: Use a union for passing/returning FFI values.
This fixes a bug where double arguments on a 32-bit architecture would not
be passed correctly because they only had 4 bytes of storage (not 8).  It
also fixes a compiler warning/error in return_ffi_value on certian
architectures: array subscript 'double[0]' is partly outside array bounds
of 'ffi_arg[1]' {aka 'long unsigned int[1]'}.

Fixes issue #7064.

Signed-off-by: Damien George <damien@micropython.org>
2021-05-06 12:17:10 +10:00
Artyom Skrobov ca35c0059c py/repl: Autocomplete builtin modules.
Doing "import <tab>" will now complete/list built-in modules.

Originally at adafruit#4548 and adafruit#4608

Signed-off-by: Artyom Skrobov <tyomitch@gmail.com>
2021-05-02 23:11:14 +10:00
Kathryn Lingel 1f1a54d0b1 py/repl: Filter private methods from tab completion.
Anything beginning with "_" will now only be tab-completed if there is
already a partial match for such an entry.  In other words, entering
foo.<tab> will no longer complete/list anything beginning with "_".

Originally at adafruit#1850

Signed-off-by: Kathryn Lingel <kathryn@lingel.net>
2021-05-02 23:11:03 +10:00
Damien George 1d9528210b tests/multi_bluetooth: Add performance test for gatt char writes.
Signed-off-by: Damien George <damien@micropython.org>
2021-04-30 16:14:48 +10:00
Damien George 76dab3bf31 tests/run-multitests.py: Provide some convenient serial device shorcuts.
It's now possible to specify a device serial port using shorcuts like:

    $ ./run-multitests.py -i pyb:a0 -i pyb:u1 multi_bluetooth/*.py

Signed-off-by: Damien George <damien@micropython.org>
2021-04-30 15:47:22 +10:00
Damien George 3123f6918b tests: Use .errno instead of .args[0] for OSError exceptions.
Signed-off-by: Damien George <damien@micropython.org>
2021-04-23 22:03:46 +10:00
Damien George 3c4bfd1dec py/objexcept: Support errno attribute on OSError exceptions.
This commit adds the errno attribute to exceptions, so code can retrieve
errno codes from an OSError using exc.errno.

The implementation here simply lets `errno` (and the existing `value`)
attributes work on any exception instance (they both alias args[0]).  This
is for efficiency and to keep code size down.  The pros and cons of this
are:

Pros:
- more compatible with CPython, less difference to document and learn
- OSError().errno will correctly return None, whereas the current way of
  doing it via OSError().args[0] will raise an IndexError
- it reduces code size on most bare-metal ports (because they already have
  the errno qstr)
- for Python code that uses exc.errno the generated bytecode is 2 bytes
  smaller and more efficient to execute (compared with exc.args[0]); so
  bytecode loaded to RAM saves 2 bytes RAM for each use of this attribute,
  and bytecode that is frozen saves 2 bytes flash/ROM for each use
- it's easier/shorter to type, and saves 2 bytes of space in .py files that
  use it (for each use)

Cons:
- increases code size by 4-8 bytes on minimal ports that don't already have
  the `errno` qstr
- all exceptions now have .errno and .value attributes (a cpydiff test is
  added to address this)

See also #2407.

Signed-off-by: Damien George <damien@micropython.org>
2021-04-23 22:03:46 +10:00
Damien George 7d911d2069 tests/net_inet: Add 'Strict-Transport-Security' to exp file.
Because micropython.org now adds this to the headers.

Signed-off-by: Damien George <damien@micropython.org>
2021-04-18 23:20:26 +10:00
Damien George 8459f538eb tests/feature_check: Check for lack of pass result rather than failure.
Commit cb68a5741a broke automatic Python
feature detection when running tests, because some detection relied on a
crash of a feature script returning exactly b"CRASH".

This commit fixes this and improves the situation by testing for the lack
of a known pass result, rather than an exact failure result.

Signed-off-by: Damien George <damien@micropython.org>
2021-04-15 00:52:56 +10:00
stijn a66286f3a0 unix: Improve command line argument processing.
Per CPython everything which comes after the command, module or file
argument is not an option for the interpreter itself.  Hence the processing
of options should stop when encountering those, and the remainder be passed
as sys.argv.  Note the latter was already the case for a module or file but
not for a command.

This fixes issues like 'micropython myfile.py -h' showing the help and
exiting instead of passing '-h' as sys.argv[1], likewise for
'-X <something>' being treated as a special option no matter where it
occurs on the command line.
2021-04-07 12:41:25 +10:00
Jeff Epler 172fb5230a extmod/re1.5: Check and report byte overflow errors in _compilecode.
The generated regex code is limited in the range of jumps and counts, and
this commit checks all cases which can overflow given the right kind of
input regex, and returns an error in such a case.

This change assumes that the results that overflow an int8_t do not
overflow a platform int.

Closes: #7078

Signed-off-by: Jeff Epler <jepler@gmail.com>
2021-04-06 13:36:42 +10:00
Damien George cb68a5741a tests/run-tests.py: Provide more info if script run via pyboard crashes.
Signed-off-by: Damien George <damien@micropython.org>
2021-03-16 14:49:57 +11:00
Damien George a79d97cb76 tests/extmod/vfs_fat_fileio2.py: Close test file at end of test.
Otherwise it can lead to inconsistent results running subsequent tests.

Signed-off-by: Damien George <damien@micropython.org>
2021-03-16 14:49:57 +11:00
Damien George e98ff3f08e tests/multi_bluetooth: Skip tests when BLE features are unsupported.
Signed-off-by: Damien George <damien@micropython.org>
2021-03-12 20:08:20 +11:00
Damien George 2a38d71036 tests/run-tests.py: Reformat with Black.
Signed-off-by: Damien George <damien@micropython.org>
2021-03-12 19:56:09 +11:00
Damien George 6129b8e401 tests: Rename run-tests to run-tests.py for consistency.
Signed-off-by: Damien George <damien@micropython.org>
2021-03-12 19:56:09 +11:00
Jim Mussared 1342debb9b tests/multi_bluetooth: Add basic performance tests.
1. Exchange GATT notifications.
2. Transmit a stream of data over L2CAP.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2021-02-19 17:53:43 +11:00
Thorsten von Eicken c10d431819 esp32: Add basic support for Non-Volatile-Storage in esp32 module.
This commit implements basic NVS support for the esp32.  It follows the
pattern of the esp32.Partition class and exposes an NVS object per NVS
namespace.  The initial support provided is only for signed 32-bit integers
and binary blobs.  It's easy (albeit a bit tedious) to add support for
more types.

See discussions in: #4436, #4707, #6780
2021-02-19 15:05:19 +11:00
Thorsten von Eicken 2c1299b007 extmod/modussl: Fix ussl read/recv/send/write errors when non-blocking.
Also fix related problems with socket on esp32, improve docs for
wrap_socket, and add more tests.
2021-02-17 11:50:54 +11:00
Jim Mussared 83d23059ef tests/extmod: Add test for ThreadSafeFlag.
Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2021-02-16 17:08:36 +11:00
Thorsten von Eicken 902da05a18 esp32: Set MICROPY_USE_INTERNAL_ERRNO=0 to use toolchain's errno.h.
The underlying OS (the ESP-IDF) uses it's own internal errno codes and so
it's simpler and cleaner to use those rather than trying to convert
everything to the values defined in py/mperrno.h.
2021-02-15 23:47:02 +11:00
Jim Mussared 7ed99544e4 extmod/uasyncio: Add asyncio.current_task().
Matches CPython behavior.

Fixes #6686
2021-02-13 15:11:17 +11:00
Damien George df85e48813 tests/extmod/vfs_posix.py: Add more tests for VfsPosix class.
Signed-off-by: Damien George <damien@micropython.org>
2021-02-11 23:49:44 +11:00
Damien George 26b4ef4c46 extmod/vfs_posix_file: Allow closing an already closed file.
Signed-off-by: Damien George <damien@micropython.org>
2021-02-11 22:54:41 +11:00
Damien George 0a59938574 py/mpz: Fix overflow of borrow in mpn_div.
For certain operands to mpn_div, the existing code path for
`DIG_SIZE == MPZ_DBL_DIG_SIZE / 2` had a bug in it where borrow could still
overflow in the `(x >= *n || *n - x <= borrow)` branch, ie
`borrow + x - (mpz_dbl_dig_t)*n` overflows the borrow variable.  In such
cases the subsequent right-shift of borrow would not bring in the overflow
bit, leading to an error in the result.  An example division that had
overflow when MPZ_DIG_SIZE = 16 is `(2 ** 48 - 1) ** 2 // (2 ** 48 - 1)`.

This is fixed in this commit by simplifying the code and handling the low
digits of borrow first, and then the upper bits (to shift down) separately.
There is no longer a distinction between `DIG_SIZE < MPZ_DBL_DIG_SIZE / 2`
and `DIG_SIZE == MPZ_DBL_DIG_SIZE / 2`.

This commit also simplifies the second part of the calculation so that
borrow does not need to be negated (instead the code just works knowing
that borrow is negative and using + instead of - in calculations involving
borrow).

Fixes #6777.

Signed-off-by: Damien George <damien@micropython.org>
2021-02-08 11:50:05 +11:00
stijn 0397448501 tests/run-tests: Change default Python command used on Windows.
Default to just calling python since that is most commonly available: the
official installer or zipfiles from python.org, anaconda, nupkg all result
in python being available but not python3.  In other words: the default
used so far is wrong.  Note that os.name is 'posix' when running the python
version which comes with Cygwin or MSys2 so they are not affected by this.
However of all possible ways to get Python on Windows, only Cygwin provides
no python command so update the default way for running tests in the
README.
2021-02-02 21:32:20 +11:00
Damien George 35a6f6231e tests/extmod/utime_time_ns.py: Relax bounds on time_ns measurement.
Some devices have lower precision than 1ms for time_ns() (eg PYBv1.x has
3.9ms resolution of the RTC) so make the test more lenient for them.

Signed-off-by: Damien George <damien@micropython.org>
2021-02-01 18:44:28 +11:00
Damien George 7a97e4351b tests: Move native for test from pybnative to micropython.
And make it generic so it can be run on any target.

Signed-off-by: Damien George <damien@micropython.org>
2021-01-29 23:57:10 +11:00
Damien George 925bd67cfb py/objfun: Support fun.__globals__ attribute.
This returns a reference to the globals dict associated with the function,
ie the global scope that the function was defined in.  This attribute is
read-only but the dict itself is modifiable, per CPython behaviour.

Signed-off-by: Damien George <damien@micropython.org>
2021-01-29 23:57:10 +11:00
Damien George 71ea438561 extmod/vfs: Check block 0 and 1 when auto-detecting littlefs.
The superblock for littlefs is in block 0 and 1, but block 0 may be erased
or partially written, so block 1 must be checked if block 0 does not have a
valid littlefs superblock in it.

Prior to this commit, the mount of a block device which auto-detected the
filysystem type would fail for littlefs if block 0 did not contain a valid
superblock.  That is now fixed.

Signed-off-by: Damien George <damien@micropython.org>
2021-01-29 15:02:55 +11:00
Oliver Joos 419134bea4 tests/extmod: Add test for the precision of utime functions.
According to documentation time() has a precision of at least 1 second.
This test runs for 2.5 seconds and calls all utime functions every 100ms.
Then it checks if they returned enough different results.  All functions
with sub-second precision will return ~25 results.  This test passes with
15 results or more.  Functions that do not exist are skipped silently.
2021-01-23 16:54:57 +11:00
stijn 069557edef tests/misc/sys_settrace_features.py: Fix running with non-dflt encoding.
Notably git-cmd which comes with git installations on Windows alters the
encoding resulting in CPython tracing encodings/cp1252.py calls.
2020-12-18 13:57:17 +11:00
stijn 108183fcc0 tests/misc/sys_settrace: Make test output independent of invoked path.
The original logic of reducing a full path to a relative one assumes
"tests/misc" is in the filename which is limited in usage: it never works
for CPython on Windows since that will use a backslash as path separator,
and also won't work when the filename is a path not relative to the tests
directory which happens for example in the common case of running
"./run-tests -d misc".

Fix all cases by printing only the bare filename, which requires them all
to start with sys_settrace_ hence the renaming.
2020-12-18 13:56:45 +11:00
Oliver Joos dc1fd4df73 tests/extmod: Add test to try and mount a block device directly.
Mounting a bdev directly tries to auto-detect the filesystem and if none is
found an OSError(19,) should be raised.

The fourth parameter of readblocks() and writeblocks() must be optional to
support ports with MICROPY_VFS_FAT=1.  Otherwise mounting a bdev may fail
because looking for a FATFS will call readblocks() with only 3 parameters.
2020-12-17 22:43:19 +11:00
Damien George e0bb7a53c3 tests/misc/sys_settrace_features.py: Ignore CPython zipimport traces.
Signed-off-by: Damien George <damien@micropython.org>
2020-12-14 13:04:50 +11:00
Joris Peeraer 5020b14d54 py/mpprint: Fix length calculation for strings with precision-modifier.
Two issues are tackled:

1. The calculation of the correct length to print is fixed to treat the
   precision as a maximum length instead as the exact length.
   This is done for both qstr (%q) and for regular str (%s).

2. Fix the incorrect use of mp_printf("%.*s") to mp_print_strn().

   Because of the fix of above issue, some testcases that would print
   an embedded null-byte (^@ in test-output) would now fail.
   The bug here is that "%s" was used to print null-bytes. Instead,
   mp_print_strn is used to make sure all bytes are outputted and the
   exact length is respected.

Test-cases are added for both %s and %q with a combination of precision
and padding specifiers.
2020-12-07 23:32:06 +11:00
Damien George c8b0557178 tests/multi_bluetooth: Add multitests for BLE pairing and bonding.
Signed-off-by: Damien George <damien@micropython.org>
2020-12-02 14:44:55 +11:00
Damien George b505971069 extmod/uasyncio: Fix cancellation handling of wait_for.
This commit switches the roles of the helper task from a cancellation task
to a runner task, to get the correct semantics for cancellation of
wait_for.

Some uasyncio tests are now disabled for the native emitter due to issues
with native code generation of generators and yield-from.

Fixes #5797.

Signed-off-by: Damien George <damien@micropython.org>
2020-12-02 12:31:37 +11:00
Damien George 309dfe39e0 extmod/uasyncio: Add Task.done() method.
This is added because task.coro==None is no longer the way to detect if a
task is finished.  Providing a (CPython compatible) function for this
allows the implementation to be abstracted away.

Signed-off-by: Damien George <damien@micropython.org>
2020-12-02 12:07:06 +11:00
Damien George ca40eb0fda extmod/uasyncio: Delay calling Loop.call_exception_handler by 1 loop.
When a tasks raises an exception which is uncaught, and no other task
await's on that task, then an error message is printed (or a user function
called) via a call to Loop.call_exception_handler.  In CPython this call is
made when the Task object is freed (eg via reference counting) because it's
at that point that it is known that the exception that was raised will
never be handled.

MicroPython does not have reference counting and the current behaviour is
to deal with uncaught exceptions as early as possible, ie as soon as they
terminate the task.  But this can be undesirable because in certain cases
a task can start and raise an exception immediately (before any await is
executed in that task's coro) and before any other task gets a chance to
await on it to catch the exception.

This commit changes the behaviour so that tasks which end due to an
uncaught exception are scheduled one more time for execution, and if they
are not await'ed on by the next scheduling loop, then the exception handler
is called (eg the exception is printed out).

Signed-off-by: Damien George <damien@micropython.org>
2020-12-02 12:07:06 +11:00
Damien George 02b44a0154 tests/run-tests: Update skipped tests on CI for GitHub Actions.
Signed-off-by: Damien George <damien@micropython.org>
2020-11-30 10:48:41 +11:00
Damien George 6a3d70db96 tests/extmod: Add vfs_posix.py test for uos.VfsPosix class.
Signed-off-by: Damien George <damien@micropython.org>
2020-11-29 17:31:24 +11:00
Jim Mussared 23fad2526d tests/multi_bluetooth: Add L2CAP channels multi-test.
Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2020-11-24 01:07:17 +11:00
Jim Mussared efc0800132 tests/multi_bluetooth: Add a test for WB55 concurrent flash access.
This test currently passes on Unix/PYBD, but fails on WB55 because it lacks
synchronisation of the internal flash.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2020-11-16 17:04:02 +11:00
Jim Mussared 7e75245d54 tests/multi_bluetooth: Change dict index-and-del to pop, to clear event.
Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2020-11-16 17:03:27 +11:00
Jim Mussared c75ce37910 tests/run-multitests.py: Add a -p flag to run permutations of instances.
Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2020-11-13 17:19:05 +11:00
Jim Mussared ccfd535af4 tests/multi_bluetooth: Improve reliability of event waiting.
Use the same `wait_for_event` in all tests that doesn't hold a reference to
the event data tuple and handles repeat events.

Also fix a few misc reliability issues around timeouts and sequencing.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2020-11-13 17:19:05 +11:00
Jim Mussared 309fb822e6 tests/run-multitests.py: Fix diff order, show changes relative to truth.
Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2020-11-13 17:18:20 +11:00
Arrowana 922f81dfd1 extmod/machine_mem: Only allow integers in machine.memX subscript.
Prior to this change machine.mem32['foo'] (or using any other non-integer
subscript) could result in a fault due to 'foo' being interpreted as an
integer.  And when writing code it's hard to tell if the fault is due to a
bad subscript type, or an integer subscript that specifies an invalid
memory address.

The type of the object used in the subscript is now tested to be an
integer by using mp_obj_get_int_truncated instead of
mp_obj_int_get_truncated.  The performance hit of this change is minimal,
and machine.memX objects are more for convenience than performance (there
are many other ways to read/write memory in a faster way),

Fixes issue #6588.
2020-11-13 11:13:37 +11:00
Damien George d7e1526593 py/binary: Fix sign extension setting wide integer on 32-bit archs.
Signed-off-by: Damien George <damien@micropython.org>
2020-11-11 22:18:24 +11:00
Damien George bdfb584b29 extmod/moductypes: Fix storing to (U)INT64 arrays on 32-bit archs.
Fixes issue #6583.

Signed-off-by: Damien George <damien@micropython.org>
2020-11-11 22:18:24 +11:00
Damien George 1fef5662ab py/mpz: Do sign extension in mpz_as_bytes for negative values.
Signed-off-by: Damien George <damien@micropython.org>
2020-11-11 22:18:24 +11:00
Damien George ed7ddd4dd4 tests/micropython/extreme_exc.py: Unlink alloc'd lists earlier in chain.
To help the GC collect this memory that's no longer needed after the test.

Signed-off-by: Damien George <damien@micropython.org>
2020-10-29 23:35:36 +11:00
stijn 25c4563f26 examples: Add example code for user C modules, both C and C++.
Add working example code to provide a starting point for users with files
that they can just copy, and include the modules in the coverage test to
verify the complete user C module build functionality.  The cexample module
uses the code originally found in cmodules.rst, which has been updated to
reflect this and partially rewritten with more complete information.
2020-10-29 15:30:42 +11:00
stijn fad4079778 esp32,unix: Support building C++ code.
Support building .cpp files and linking them into the micropython
executable in a way similar to how it is done for .c files.  The main
incentive here is to enable user C modules to use C++ files (which are put
in SRC_MOD_CXX by py.mk) since the core itself does not utilize C++.

However, to verify build functionality a unix overage test is added.  The
esp32 port already has CXXFLAGS so just add the user modules' flags to it.
For the unix port use a copy of the CFLAGS but strip the ones which are not
usable for C++.
2020-10-29 15:29:50 +11:00
Damien George 6f34800884 extmod/modurandom: Support urandom.seed() without an argument.
If a port provides MICROPY_PY_URANDOM_SEED_INIT_FUNC as a source of
randomness then this will be used when urandom.seed() is called without
an argument (or with None as the argument) to seed the pRNG.

Other related changes in this commit:
- mod_urandom___init__ is changed to call seed() without arguments, instead
  of explicitly passing in the result of MICROPY_PY_URANDOM_SEED_INIT_FUNC.
- mod_urandom___init__ will only ever seed the pRNG once (before it could
  seed it again if imported by, eg, random and then urandom).
- The Yasmarang state is moved to the BSS for builds where the state is
  guaranteed to be initialised on import of the (u)random module.

Signed-off-by: Damien George <damien@micropython.org>
2020-10-29 14:15:16 +11:00
Damien George 03a1f94ea1 extmod/vfs_lfs: Support mounting LFS filesystems in read-only mode.
Signed-off-by: Damien George <damien@micropython.org>
2020-10-29 11:43:52 +11:00
Damien George 368c1a0961 tests/thread/stress_schedule.py: Assign globals before running test.
When threading is enabled without the GIL then there can be races between
the threads accessing the globals dict.  Avoid this issue by making sure
all globals variables are allocated before starting the threads.

Signed-off-by: Damien George <damien@micropython.org>
2020-10-28 00:54:30 +11:00
Jim Mussared b137d064e9 py/objtype: Handle __dict__ attribute when type has no locals. 2020-10-10 00:16:32 +11:00
Damien George 817b80a102 unix/variants: Enable MICROPY_DEBUG_PARSE_RULE_NAME on coverage build.
Signed-off-by: Damien George <damien@micropython.org>
2020-10-01 15:26:43 +10:00
Damien George d4b61b0017 extmod/utime_mphal: Add generic utime.time_ns() function.
It requires mp_hal_time_ns() to be provided by a port.  This function
allows very accurate absolute timestamps.

Enabled on unix, windows, stm32, esp8266 and esp32.

Signed-off-by: Damien George <damien@micropython.org>
2020-10-01 14:20:42 +10:00
Andrew Leech 319437d4bd extmod/modure: Allow \\ in re.sub replacements. 2020-09-30 23:18:34 +10:00
Damien George 9123b67d64 tests/run-tests: Use -BS flags when running CPython.
The use of -S ensures that only the CPython standard library is accessible,
which makes tests run the same regardless of any site-packages that are
installed.  It also improves start-up time of CPython, reducing the overall
time spent running the test suite.

tests/basics/containment.py is updated to work around issue with old Python
versions not being able to str-format a dict-keys object, which becomes
apparent when -S is used.

Signed-off-by: Damien George <damien@micropython.org>
2020-09-25 12:27:23 +10:00
Damien George 81f2162ca0 extmod/modbluetooth: Change module-owned bytes objects to memoryview.
A read-only memoryview object is a better representation of the data, which
is owned by the ubluetooth module and may change between calls to the
user's irq callback function.

Signed-off-by: Damien George <damien@micropython.org>
2020-09-25 12:23:11 +10:00
Damien George 71adf506ce extmod/vfs: Fix lookup of entry in root dir so it fails correctly.
Prior to this commit, uos.chdir('/') followed by uos.stat('noexist') would
succeed that stat even though the entry did not exist (some other functions
like listdir would have similar issues).  This is because, if the current
directory was the root and the path was relative, mp_vfs_lookup_path would
return success for bad paths.

Signed-off-by: Damien George <damien@micropython.org>
2020-09-23 16:23:35 +10:00
Damien George 42342fa3cb tests/basics: Add test for MICROPY_PY_ALL_INPLACE_SPECIAL_METHODS ops.
And enable this feature on unix, the coverage variant.  The .exp test file
is needed so the test can run on CPython versions prior to "@=" operator
support.

Signed-off-by: Damien George <damien@micropython.org>
2020-09-18 18:40:42 +10:00
Damien George c410a86814 tests/basics: Enable == and != special-method tests now that they work.
These work since 3aab54bf43

Signed-off-by: Damien George <damien@micropython.org>
2020-09-18 18:40:42 +10:00
Jim Mussared 3086d35e16 tests/multi_bluetooth/ble_mtu.py: Add multitest for BLE MTU. 2020-09-18 12:51:21 +10:00
Jim Mussared 06dda48144 tests/run-multitests.py: Show test/truth diff. 2020-09-18 12:51:21 +10:00
Jim Mussared fe642ced43 tests/multi_bluetooth: Update UUID format in .exp files. 2020-09-18 12:51:21 +10:00
stijn 2e54d9d146 py: Fix handling of NaN in certain pow implementations.
Adds a new compile-time option MICROPY_PY_MATH_POW_FIX_NAN for use with
toolchains that don't handle pow-of-NaN correctly.
2020-09-11 10:04:57 +10:00
Damien George 8d5a40c86e py/objfloat: Fix handling of negative float to power of nan.
Prior to this commit, pow(-2, float('nan')) would return (nan+nanj), or
raise an exception on targets that don't support complex numbers.  This is
fixed to return simply nan, as CPython does.

Signed-off-by: Damien George <damien@micropython.org>
2020-09-11 10:03:57 +10:00
Jim Mussared 5eda362e0a tests/multi_bluetooth: Make ble_gap_connect robust against event timing. 2020-09-08 23:53:12 +10:00
Jim Mussared 26b66804e9 tests/multi_bluetooth: Update to new config('mac') behaviour. 2020-09-08 12:53:24 +10:00
stijn 40ad8f1666 all: Rename "sys" module to "usys".
This is consistent with the other 'micro' modules and allows implementing
additional features in Python via e.g. micropython-lib's sys.

Note this is a breaking change (not backwards compatible) for ports which
do not enable weak links, as "import sys" must now be replaced with
"import usys".
2020-09-04 00:10:24 +10:00
Damien George 0e6ef40359 tests/extmod: Add tests for verifying FAT and littlefs mtime values.
Verifies mtime timestamps on files match the value returned by time.time().

Also update vfs_fat_ramdisk.py so it doesn't check FAT timestamp of the
root, because that may change across runs/ports.

Signed-off-by: Damien George <damien@micropython.org>
2020-09-02 00:19:38 +10:00
Damien George d1995e50eb extmod/modlwip: Fix error return for TCP recv when not connected.
This commit fixes the cases when a TCP socket is in STATE_NEW,
STATE_LISTENING or STATE_CONNECTING and recv() is called on it.  It now
raises ENOTCONN instead of a random error code due to it previously
indexing beyond the start of error_lookup_table[].

Signed-off-by: Damien George <damien@micropython.org>
2020-08-30 13:20:51 +10:00
Damien George 06659077a8 all: Update Python code to conform to latest black formatting.
Updating to Black v20.8b1 there are two changes that affect the code in
this repository:

- If there is a trailing comma in a list (eg [], () or function call) then
  that list is now written out with one line per element.  So remove such
  trailing commas where the list should stay on one line.

- Spaces at the start of """ doc strings are removed.

Signed-off-by: Damien George <damien@micropython.org>
2020-08-29 15:18:01 +10:00
Damien George 0c7354afaf tests: Split out complex reverse-op tests to separate test file.
So they can be skipped if __rOP__'s are not supported on the target.  Also
fix the typo in the complex_special_methods.py filename.

Signed-off-by: Damien George <damien@micropython.org>
2020-08-29 14:12:20 +10:00
stijn 0c3f9d58a5 tests/run-tests: Make test output directory configurable.
A configurable result directory is advantageous because it enables
using a dedicated location, eventually outside of the source tree,
instead of forcing the output files into a fixed directory which might
also contain other files already. For that reason the default output
directory also has been changed to tests/results/.
2020-08-27 11:12:08 +10:00
stijn 405893afc6 tests/run-tests: Use absolute paths where possible.
Replace some usages of paths relative to the current working directory
with absolute paths relative to the tests directory.

Fixes and resulting changes:
- default values of MICROPYTHON and MPYCROSS are absolute paths and
  always correct
- likewise, the correct full paths for tools and extmod directories
  are appended to sys.path
- printing/cleaning failures works properly since it expects the .exp
  and .out files in the tests directory which is also where they
  are written to now, plus no more need for changing directories

This fixes #5872 and allows running custom tests which use run-tests
without having to cd to the tests directory first, and the test output
still is in the tests/ directory instead of the current working directory.

Discovery of tests and all skip test logic based on paths relative to
the current working directory remains unchanged which essentially means
that for running most of MicroPython's own tests, run-tests must still
be ran from within it's directory, so document that.
2020-08-27 11:12:08 +10:00
Damien George 5fb276de33 tests/extmod: Make uasyncio_fair test more reliable by adjusting sleeps.
With sleep(0.2) a multiple of sleep(0.1), the order of task 2 and 3
execution is not well defined, and depends on the precision of the system
clock and how fast the rest of the code runs.  So change 0.2 to 0.18 to
make the test more reliable.

Also fix a typo of t3/t4, and cancel t4 at the end.

Signed-off-by: Damien George <damien@micropython.org>
2020-08-26 17:05:52 +10:00
Damien George 2acc087880 extmod/vfs_lfs: Add mtime support to littlefs files.
This commit adds support for modification time of files on littlefs v2
filesystems, using file attributes.  For some background see issue #6114.

Features/properties of this implementation:
- Only supported on littlefs2 (not littlefs1).
- Uses littlefs2's general file attributes to store the timestamp.
- The timestamp is 64-bits and stores nanoseconds since 1970/1/1 (if the
  range to the year 2554 is not enough then additional bits can be added to
  this timestamp by adding another file attribute).
- mtime is enabled by default but can be disabled in the constructor, eg:
  uos.mount(uos.VfsLfs2(bdev, mtime=False), '/flash')
- It's fully backwards compatible, existing littlefs2 filesystems will work
  without reformatting and timestamps will be added transparently to
  existing files (once they are opened for writing).
- Files without timestamps will open correctly, and stat will just return 0
  for their timestamp.
- mtime can be disabled or enabled each mount time and timestamps will only
  be updated if mtime is enabled (otherwise they will be untouched).

Signed-off-by: Damien George <damien@micropython.org>
2020-08-25 17:35:19 +10:00
Damien George 55c76eaac1 extmod/uasyncio: Truncate negative sleeps to 0.
Otherwise a task that continuously awaits on a large negative sleep can
monopolise the scheduler (because its wake time is always less than
everything else in the pairing heap).

Signed-off-by: Damien George <damien@micropython.org>
2020-08-22 12:17:06 +10:00
Damien George 20948a3d54 tests/extmod: Add test for uasyncio.sleep of a negative time.
It should take 0 time to await on a negative sleep.

Signed-off-by: Damien George <damien@micropython.org>
2020-08-22 12:17:06 +10:00
Damien George 5f9b105244 py/runtime: Fix builtin compile() in "single" mode so it prints exprs.
As per CPython behaviour, compile(stmt, "file", "single") should create
code which prints to stdout (via __repl_print__) the results of any
expressions in stmt.

Signed-off-by: Damien George <damien@micropython.org>
2020-08-22 11:38:46 +10:00
Damien George 60f5b941e0 extmod/vfs_reader: Fix mp_reader_new_file to open file in "rb" mode.
mp_reader_new_file() is used to read in files for importing, either .py or
.mpy files, for the lexer and persistent code loader respectively.  In both
cases the file should be opened in raw bytes mode: the lexer handles
unicode characters itself, and .mpy files contain 8-bit bytes by nature.

Before this commit importing was working correctly because, although the
file was opened in text mode, all native filesystem implementations (POSIX,
FAT, LFS) would access the file in raw bytes mode via mp_stream_rw()
calling mp_stream_p_t.read().  So it was only an issue for non-native
filesystems, such as those implemented in Python.  For Python-based
filesystem implementations, a call to mp_stream_rw() would go via IOBase
and then to readinto() at the Python level, and readinto() is only defined
on files opened in raw bytes mode.

Signed-off-by: Damien George <damien@micropython.org>
2020-08-12 23:40:50 +10:00
Damien George 9883d8e818 py/persistentcode: Maintain root ptr list of imported native .mpy code.
On ports where normal heap memory can contain executable code (eg ARM-based
ports such as stm32), native code loaded from an .mpy file may be reclaimed
by the GC because there's no reference to the very start of the native
machine code block that is reachable from root pointers (only pointers to
internal parts of the machine code block are reachable, but that doesn't
help the GC find the memory).

This commit fixes this issue by maintaining an explicit list of root
pointers pointing to native code that is loaded from an .mpy file.  This
is not needed for all ports so is selectable by the new configuration
option MICROPY_PERSISTENT_CODE_TRACK_RELOC_CODE.  It's enabled by default
if a port does not specify any special functions to allocate or commit
executable memory.

A test is included to test that native code loaded from an .mpy file does
not get reclaimed by the GC.

Fixes #6045.

Signed-off-by: Damien George <damien@micropython.org>
2020-08-02 22:34:09 +10:00
Damien George 8da40baa47 tests/micropython: Improve .mpy import tests to run on more targets.
All imports are now tested to see if the test should be skipped,
UserFile.read is removed, and UserFile.readinto is made more efficient.

Signed-off-by: Damien George <damien@micropython.org>
2020-07-26 22:44:59 +10:00
Damien George 0c0cef9870 tests: Move .mpy import tests from import/ to micropython/ dir.
These tests are specific to MicroPython so have a better home in the
micropython/ test subdir, and putting them here allows them to be run by
all targets, not just those that have access to the local filesystem (eg
the unix port).

Signed-off-by: Damien George <damien@micropython.org>
2020-07-26 22:04:31 +10:00
Damien George 441460d81f extmod/uasyncio: Add StreamReader.readexactly(n) method.
It raises on EOFError instead of an IncompleteReadError (which is what
CPython does).  But the latter is derived from EOFError so code compatible
with MicroPython and CPython can be written by catching EOFError (eg see
included test).

Fixes issue #6156.

Signed-off-by: Damien George <damien@micropython.org>
2020-07-25 23:10:05 +10:00
Jonathan Hogg 37e1b5c891 py/compile: Don't await __aiter__ special method in async-for.
MicroPython's original implementation of __aiter__ was correct for an
earlier (provisional) version of PEP492 (CPython 3.5), where __aiter__ was
an async-def function.  But that changed in the final version of PEP492 (in
CPython 3.5.2) where the function was changed to a normal one.  See
https://www.python.org/dev/peps/pep-0492/#why-aiter-does-not-return-an-awaitable
See also the note at the end of this subsection in the docs:
https://docs.python.org/3.5/reference/datamodel.html#asynchronous-iterators
And for completeness the BPO: https://bugs.python.org/issue27243

To be consistent with the Python spec as it stands today (and now that
PEP492 is final) this commit changes MicroPython's behaviour to match
CPython:  __aiter__ should return an async-iterable object, but is not
itself awaitable.

The relevant tests are updated to match.

See #6267.
2020-07-25 00:58:18 +10:00
Damien George a853fff838 py/obj.h: Fix mp_seq_replace_slice_no_grow to use memmove not memcpy.
Because the argument arrays may overlap, as show by the new tests in this
commit.

Also remove the debugging comments for these macros, add a new comment
about overlapping regions, and separate the macros by blank lines to make
them easier to read.

Fixes issue #6244.

Signed-off-by: Damien George <damien@micropython.org>
2020-07-21 01:05:59 +10:00
Damien George 895b1dbdda tests/basics: Split out memoryview slice-assign tests to separate file.
Signed-off-by: Damien George <damien@micropython.org>
2020-07-21 01:05:59 +10:00
Thorsten von Eicken 5264478007 extmod/modussl_mbedtls: Integrate shorter error strings.
The stm32 and esp32 ports now use shorter error strings for mbedtls errors.
Also, MBEDTLS_ERROR_C is enabled on stm32 by default to get these strings.
2020-07-21 00:31:05 +10:00
Thorsten von Eicken 9aa214077e extmod/modussl: Improve exception error messages.
This commit adds human readable error messages when mbedtls or axtls raise
an exception.  Currently often just an EIO error is raised so the user is
lost and can't tell whether it's a cert error, buffer overrun, connecting
to a non-ssl port, etc.  The axtls and mbedtls error raising in the ussl
module is modified to raise:

    OSError(-err_num, "error string")

For axtls a small error table of strings is added and used for the second
argument of the OSErrer.  For mbedtls the code uses mbedtls' built-in
strerror function, and if there is an out of memory condition it just
produces OSError(-err_num).  Producing the error string for mbedtls is
conditional on them being included in the mbedtls build, via
MBEDTLS_ERROR_C.
2020-07-20 23:41:45 +10:00
Jim Mussared 9d823a5d9a extmod/modbluetooth: Add event for "indicate acknowledgement".
This commit adds the IRQ_GATTS_INDICATE_DONE BLE event which will be raised
with the status of gatts_indicate (unlike notify, indications require
acknowledgement).

An example of its use is added to ble_temperature.py, and to the multitests
in ble_characteristic.py.

Implemented for btstack and nimble bindings, tested in both directions
between unix/btstack and pybd/nimble.
2020-07-20 23:26:41 +10:00
Jim Mussared e152d0c197 extmod/btstack: Schedule notify/indicate/write ops for bg completion.
The goal of this commit is to allow using ble.gatts_notify() at any time,
even if the stack is not ready to send the notification right now.  It also
addresses the same issue for ble.gatts_indicate() and ble.gattc_write()
(without response).  In addition this commit fixes the case where the
buffer passed to write-with-response wasn't copied, meaning it could be
modified by the caller, affecting the in-progress write.

The changes are:

- gatts_notify/indicate will now run in the background if the ACL buffer is
  currently full, meaning that notify/indicate can be called at any time.

- gattc_write(mode=0) (no response) will now allow for one outstanding
  write.

- gattc_write(mode=1) (with response) will now copy the buffer so that it
  can't be modified by the caller while the write is in progress.

All four paths also now track the buffer while the operation is in
progress, which prevents the GC free'ing the buffer while it's still
needed.
2020-07-18 14:23:47 +10:00
Damien George 332d83343f py: Rework mp_convert_member_lookup to properly handle built-ins.
This commit fixes lookups of class members to make it so that built-in
functions that are used as methods/functions of a class work correctly.

The mp_convert_member_lookup() function is pretty much completely changed
by this commit, but for the most part it's just reorganised and the
indenting changed.  The functional changes are:

- staticmethod and classmethod checks moved to later in the if-logic,
  because they are less common and so should be checked after the more
  common cases.

- The explicit mp_obj_is_type(member, &mp_type_type) check is removed
  because it's now subsumed by other, more general tests in this function.

- MP_TYPE_FLAG_BINDS_SELF and MP_TYPE_FLAG_BUILTIN_FUN type flags added to
  make the checks in this function much simpler (now they just test this
  bit in type->flags).

- An extra check is made for mp_obj_is_instance_type(type) to fix lookup of
  built-in functions.

Fixes #1326 and #6198.

Signed-off-by: Damien George <damien@micropython.org>
2020-06-30 23:55:32 +10:00
Damien George 9f911d822e py/objcomplex: Add mp_obj_get_complex_maybe for use in complex bin-op.
This allows complex binary operations to fail gracefully with unsupported
operation rather than raising an exception, so that special methods work
correctly.

Signed-off-by: Damien George <damien@micropython.org>
2020-06-27 01:03:10 +10:00
Damien George 41fa8b5482 py/emitnative: Implement binary operations for viper uint operands.
uint types in viper mode can now be used for all binary operators except
floor-divide and modulo.

Fixes issue #1847 and issue #6177.

Signed-off-by: Damien George <damien@micropython.org>
2020-06-27 00:24:04 +10:00
Damien George 457fdf61c3 py/objtype: Support passing in an OrderedDict to type() as the locals.
An OrderedDict can now be used for the locals when creating a type
explicitly via type(name, bases, locals).

Signed-off-by: Damien George <damien@micropython.org>
2020-06-24 12:05:40 +10:00
Damien George a51eef4471 tests/basics: Add tests for variable annotations. 2020-06-16 23:18:01 +10:00
Damien George a3c89cf907 tests/cpydiff: Add CPy diff test for assignment expression behaviour. 2020-06-16 22:06:47 +10:00
Damien George e0fe8ea644 tests/basics: Add tests for assignment operator :=. 2020-06-16 22:06:30 +10:00
Damien George 1783950311 py/compile: Implement PEP 572, assignment expressions with := operator.
The syntax matches CPython and the semantics are equivalent except that,
unlike CPython, MicroPython allows using := to assign to comprehension
iteration variables, because disallowing this would take a lot of code to
check for it.

The new compile-time option MICROPY_PY_ASSIGN_EXPR selects this feature and
is enabled by default, following MICROPY_PY_ASYNC_AWAIT.
2020-06-16 22:02:24 +10:00
Jim Mussared 00c3e2156a tests/run-multitests.py: Allow passing unique env vars to each instance.
For example, to run the BLE multitests entirely with the unix port:

    env MICROPY_MICROPYTHON=../ports/unix/micropython-dev ./run-multitests.py \
        -i micropython,MICROPYBTUSB=01 \
        -i micropython,MICROPYBTUSB=02:02 \
        multi_bluetooth/ble_*.py
2020-06-10 22:41:57 +10:00
Damien George a4c96fb3b0 extmod/uasyncio: Add asyncio.wait_for_ms function.
Fixes issue #6107.
2020-06-10 22:29:44 +10:00
Andrew Leech 28370c0450 py/objtype: Add __dict__ attribute for class objects.
The behavior mirrors the instance object dict attribute where a copy of the
local attributes are provided (unless the dict is read-only, then that dict
itself is returned, as an optimisation).  MicroPython does not support
modifying this dict because the changes will not be reflected in the class.

The feature is only enabled if MICROPY_CPYTHON_COMPAT is set, the same as
the instance version.
2020-06-10 21:58:13 +10:00
stijn 51fd6c9777 extmod/ure: Use single function for match/search/sub.
Saves about 500 bytes on unix x64 and enables CPython-conform
usage of passing a re object to these functions.
2020-06-08 09:16:09 +02:00
Jim Mussared 9902ce12eb tests/multi_bluetooth: Update to work with new BLE events.
Updates the tests to use non-bitmask events, event renames, as well as some
of the new completion events to improve reliability of the tests.
2020-06-05 14:08:47 +10:00
Damien George 203b10703e py/modbuiltins: Fix getattr to work with class raising AttributeError.
Fixes issue #6089.
2020-06-02 15:42:20 +10:00
Damien George 22806ed5df extmod/vfs: Retain previous working directory if chdir fails.
Fixes issue #6069.
2020-05-29 23:05:01 +10:00
stijn 81db22f693 py/modmath: Work around msvc float bugs in atan2, fmod and modf.
Older implementations deal with infinity/negative zero incorrectly.  This
commit adds generic fixes that can be enabled by any port that needs them,
along with new tests cases.
2020-05-28 09:54:54 +10:00
Damien George 7dffbfd22a extmod/vfs_lfsx: Fix import_stat so it takes into account current dir.
CPython semantics require searching the current directory if the import is
not absolute (when "" is in sys.path).

Fixes issue #6037.
2020-05-15 11:31:32 +10:00
Damien George 3b6c9119eb extmod/modbluetooth: Add support for changing the GAP device name.
This commit allows the user to set/get the GAP device name used by service
0x1800, characteristic 0x2a00.  The usage is:

    BLE.config(gap_name="myname")
    print(BLE.config("gap_name"))

As part of this change the compile-time setting
MICROPY_PY_BLUETOOTH_DEFAULT_NAME is renamed to
MICROPY_PY_BLUETOOTH_DEFAULT_GAP_NAME to emphasise its link to GAP and this
new "gap_name" config value.  And the default value of this for the NimBLE
bindings is changed from "PYBD" to "MPY NIMBLE" to be more generic.
2020-05-11 21:30:41 +10:00
Thorsten von Eicken ab4e197707 esp32/modsocket: Fix getaddrinfo to raise on error.
This commit fixes the behaviour of socket.getaddrinfo on the ESP32 so it
raises an OSError when the name resolution fails instead of returning a []
or a resolution for 0.0.0.0.

Tests are added (generic and ESP32-specific) to verify behaviour consistent
with CPython, modulo the different types of exceptions per MicroPython
documentation.
2020-05-09 16:43:48 +10:00
Damien George adb6733022 tests/run-tests: Skip REPL feature checks when running via pyboard.py. 2020-05-09 16:20:40 +10:00
Damien George 035059eaf5 tests/run-multitests.py: Add TRACE banner and move TEST output to end.
To make it easier to understand the output when both -s and -t are used.
2020-05-09 00:06:06 +10:00
robert 0f83ef395c extmod/vfs_lfsx: Fix rename to respect cur dir for new path.
If the new name start with '/', cur_dir is not prepened any more, so that
the current working directory is respected.  And extend the test cases for
rename to cover this functionality.
2020-05-08 21:54:04 +10:00
robert d3ea28d04a extmod/vfs_lfsx: Normalize path name in chdir.
This change scans for '.', '..' and multiple '/' and normalizes the new
path name.  If the resulting path does not exist, an error is raised.
Non-existing interim path elements are ignored if they are removed during
normalization.
2020-05-08 21:52:15 +10:00
robert a5ea4b9f3f extmod/vfs_lfsx: Fix path handling in uos.stat() to consider cur dir.
This fixes the bug, that stat(filename) would not consider the current
working directory.  So if e.g. the cwd is "lib", then stat("main.py") would
return the info for "/main.py" instead of "/lib/main.py".
2020-05-08 21:37:51 +10:00
Damien George 037c83b0ed tests/multi_bluetooth: Fix typo printing wrong IRQ type. 2020-05-08 13:23:45 +10:00
yangfl 138a28dc07 tests/thread/thread_stacksize1.py: Increase stack size for CPython.
On arm64 with CPython:

  >>> _thread.stack_size(32*1024)
  Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
  ValueError: size not valid: 32768 bytes

So increase the CPython value in the test to 512k so it runs on more
systems (on modern Linux the default stack size is usually 8MB).
2020-05-05 00:43:24 +10:00
Damien George 4ede703687 py/parse: Support constant folding of power operator for integers.
Constant expression like "2 ** 3" will now be folded, and the special form
"X = const(2 ** 3)" will now compile because the argument to the const is
now a constant.

Fixes issue #5865.
2020-05-03 16:23:19 +10:00
Thorsten von Eicken 952ff8a8ea esp32: Improve support for OTA updates.
This commit adds several small items to improve the support for OTA
updates on an esp32:

- a partition table for 4MB flash modules that has two OTA partitions ready
  to go to do updates
- a GENERIC_OTA board that uses that partition table and that enables
  automatic roll-back in the bootloader
- a new esp32.Partition.mark_app_valid_cancel_rollback() class-method to
  signal that the boot is successful and should not be rolled back at the
  next reset
- an automated test for doing an OTA update
- documentation updates
2020-05-03 15:00:45 +10:00
Jim Mussared 309c19d39b tests/cpydiff: Add cpydiff test for __all__ used in imported package. 2020-05-02 17:41:04 +10:00
Damien George 73c58150f5 extmod/modbtree: Retain reference to underlying stream so it's not GC'd.
For ports that have a system malloc which is not garbage collected (eg
unix, esp32), the stream object for the DB must be retained separately to
prevent it from being reclaimed by the MicroPython GC (because the
berkeley-db library uses malloc to allocate the DB structure which stores
the only reference to the stream).

Although in some cases the user code will explicitly retain a reference to
the underlying stream because it needs to call close() on it, this is not
always the case, eg in cases where the DB is intended to live forever.

Fixes issue #5940.
2020-05-02 16:08:04 +10:00
Jim Mussared 59a7865a7d tests/run-multitests.py: Add shortcuts for local Python instances.
One can now use `-i micropython` and `-i cpython` to add instances using
the `MICROPYTHON` and `CPYTHON3` variables (which can be overridden by env
vars).
2020-04-29 16:45:46 +10:00
Jim Mussared 9b06efb943 tests/multi_bluetooth/ble_gap_advertise: Fix bytes/str compare warning. 2020-04-29 16:45:46 +10:00
Jim Mussared f588138bbe tests/run-multitests.py: Allow filtering out lines from stdout.
And use this new feature to filter out certain lines in the Bluetooth
multitests.
2020-04-29 16:45:46 +10:00
Damien George 4fa6d939d6 tests/extmod: Add btree test for errors raised by btree DB library.
This test now passes given the previous two commits.
2020-04-27 23:59:09 +10:00
Jim Mussared 57fce3bdb2 py/objdict: Fix popitem for ordered dicts.
The popitem method wasn't implemented for ordered dicts and would result in
an invalid state.

Fixes issue #5956.
2020-04-27 23:53:17 +10:00
Thorsten von Eicken 1ae7e0e561 esp32: Consolidate check_esp_err functions and add IDF error string.
This commit consolidates a number of check_esp_err functions that check
whether an ESP-IDF return code is OK and raises an exception if not.  The
exception raised is an OSError with the error code as the first argument
(negative if it's ESP-IDF specific) and the ESP-IDF error string as the
second argument.

This commit also fixes esp32.Partition.set_boot to use check_esp_err, and
uses that function for a unit test.
2020-04-23 10:59:07 +10:00
Thorsten von Eicken a177831c46 esp32/modesp32: Add idf_heap_info(capabilities) to esp32 module.
This commit adds an idf_heap_info(capabilities) method to the esp32 module
which returns info about the ESP-IDF heaps.  It's useful to get a bit of a
picture of what's going on when code fails because ESP-IDF can't allocate
memory anymore.  Includes documentation and a test.
2020-04-23 00:02:11 +10:00
stijn f31f9a8b70 py/objint: Do not use fpclassify.
For combinations of certain versions of glibc and gcc the definition of
fpclassify always takes float as argument instead of adapting itself to
float/double/long double as required by the C99 standard.  At the time of
writing this happens for instance for glibc 2.27 with gcc 7.5.0 when
compiled with -Os and glibc 3.0.7 with gcc 9.3.0.  When calling fpclassify
with double as argument, as in objint.c, this results in an implicit
narrowing conversion which is not really correct plus results in a warning
when compiled with -Wfloat-conversion.  So fix this by spelling out the
logic manually.
2020-04-18 22:42:24 +10:00
stijn 7fb9edf436 tests/float: Fix cmath_fun_special for MICROPY_FLOAT_IMPL_FLOAT.
When the unix and windows ports use MICROPY_FLOAT_IMPL_FLOAT instead of
MICROPY_FLOAT_IMPL_DOUBLE, the test output has for example
complex(-0.15052, 0.34109) instead of the expected
complex(-0.15051, 0.34109).

Use one decimal place less for the output printing to fix this.
2020-04-18 22:36:49 +10:00