Commit Graph

1714 Commits (jebbatime)

Author SHA1 Message Date
Damien George 69955238a2 tests/run-tests: Support running native tests via mpy. 2019-03-08 16:51:09 +11:00
Damien George 5996eeb48f py/persistentcode: Add a qstr window to save mpy files more efficiently.
This is an implementation of a sliding qstr window used to reduce the
number of qstrs stored in a .mpy file.  The window size is configured to 32
entries which takes a fixed 64 bytes (16-bits each) on the C stack when
loading/saving a .mpy file.  It allows to remember the most recent 32 qstrs
so they don't need to be stored again in the .mpy file.  The qstr window
uses a simple least-recently-used mechanism to discard the least recently
used qstr when the window overflows (similar to dictionary compression).
This scheme only needs a single pass to save/load the .mpy file.

Reduces mpy file size by about 25% with a window size of 32.
2019-03-05 16:25:07 +11:00
Damien George 5a2599d962 py: Replace POP_BLOCK and POP_EXCEPT opcodes with POP_EXCEPT_JUMP.
POP_BLOCK and POP_EXCEPT are now the same, and are always followed by a
JUMP.  So this optimisation reduces code size, and RAM usage of bytecode by
two bytes for each try-except handler.
2019-03-05 16:09:58 +11:00
Damien George e1fb03f3e2 py: Fix VM crash with unwinding jump out of a finally block.
This patch fixes a bug in the VM when breaking within a try-finally.  The
bug has to do with executing a break within the finally block of a
try-finally statement.  For example:

    def f():
        for x in (1,):
            print('a', x)
            try:
                raise Exception
            finally:
                print(1)
                break
            print('b', x)
    f()

Currently in uPy the above code will print:

    a 1
    1
    1
    segmentation fault (core dumped)  micropython

Not only is there a seg fault, but the "1" in the finally block is printed
twice.  This is because when the VM executes a finally block it doesn't
really know if that block was executed due to a fall-through of the try (no
exception raised), or because an exception is active.  In particular, for
nested finallys the VM has no idea which of the nested ones have active
exceptions and which are just fall-throughs.  So when a break (or continue)
is executed it tries to unwind all of the finallys, when in fact only some
may be active.

It's questionable whether break (or return or continue) should be allowed
within a finally block, because they implicitly swallow any active
exception, but nevertheless it's allowed by CPython (although almost never
used in the standard library).  And uPy should at least not crash in such a
case.

The solution here relies on the fact that exception and finally handlers
always appear in the bytecode after the try body.

Note: there was a similar bug with a return in a finally block, but that
was previously fixed in b735208403
2019-03-05 16:05:05 +11:00
Damien George 12ce9f2689 py/compile: Fix handling of unwinding BaseException in async with.
All exceptions that unwind through the async-with must be caught and
BaseException is the top-level class, which includes Exception and others.

Fixes issue #4552.
2019-02-26 23:52:10 +11:00
Damien George be41d6d6f9 tests/basics: Add tests for try-except-else and try-except-else-finally. 2019-02-21 16:22:41 +11:00
Yonatan Goldschmidt bc4f8b438b extmod/moduwebsocket: Refactor `websocket` to `uwebsocket`.
As mentioned in #4450, `websocket` was experimental with a single intended
user, `webrepl`. Therefore, we'll make this change without a weak
link `websocket` -> `uwebsocket`.
2019-02-14 00:35:45 +11:00
stijn 42863830be py: Add optional support for 2-argument version of built-in next().
Configurable via MICROPY_PY_BUILTINS_NEXT2, disabled by default.
2019-01-27 13:01:28 +11:00
Paul Sokolovsky d4d4bc5827 tests/basics/special_methods2: Typo fix in comment. 2018-12-13 01:29:01 +11:00
Damien George 074597f172 tests/extmod/uctypes_error: Add test for unsupported unary op. 2018-12-10 14:29:41 +11:00
Paul Sokolovsky 0de6815ec1 tests/extmod/uctypes_ptr_le: Test int() operation on a pointer field. 2018-12-10 14:25:06 +11:00
Paul Sokolovsky d690c2e148 tests/basics/special_methods: Add testcases for __int__. 2018-12-07 17:28:04 +11:00
Damien George 113f00a9ab py/objboundmeth: Support loading generic attrs from the method.
Instead of assuming that the method is a bytecode object, and only
supporting load of __name__, make the operation generic by delegating the
load to the method object itself.  Saves a bit of code size and fixes the
case of attempting to load __name__ on a native method, see issue #4028.
2018-12-06 18:02:41 +11:00
Damien George 8007d0bd16 stm32/uart: Add rxbuf keyword arg to UART constructor and init method.
As per the machine.UART documentation, this is used to set the length of
the RX buffer.  The legacy read_buf_len argument is retained for backwards
compatibility, with rxbuf overriding it if provided.
2018-12-05 13:24:11 +11:00
Damien George 9262f54138 stm32/uart: Always show the flow setting when printing a UART object.
Also change the order of printing of flow so it is after stop (so bits,
parity, stop are one after the other), and reduce code size by using
mp_print_str instead of mp_printf where possible.

See issue #1981.
2018-12-04 19:16:16 +11:00
Paul Sokolovsky 5c34c2ff7f tests/io: Update tests to use uos.remove() instead of uos.unlink().
After Unix port switches from one to another, to be consistent with
baremetal ports.
2018-11-26 23:27:28 +11:00
Damien George 7c85c7c210 py/unicode: Fix check for valid utf8 being stricter about contn chars. 2018-11-26 16:13:08 +11:00
Paul Sokolovsky d94aa577a6 tests/import_long_dyn: Test for "import *" of a long dynamic name.
Such names aren't stored as qstr in module dict, and there was a bug in
"import *" handling which assumed any name in a module dict is a qstr.
2018-11-01 13:33:16 +11:00
stijn 06643a0df4 tests/extmod: Skip uselect test when CPython doesn't have poll().
CPython does not have an implementation of select.poll() on some
operating systems (Windows, OSX depending on version) so skip the
test in those cases instead of failing it.
2018-10-30 14:49:23 +11:00
Damien George 9201f46cc8 py/compile: Fix case of eager implicit conversion of local to nonlocal.
This ensures that implicit variables are only converted to implicit
closed-over variables (nonlocals) at the very end of the function scope.
If variables are closed-over when first used (read from, as was done prior
to this commit) then this can be incorrect because the variable may be
assigned to later on in the function which means they are just a plain
local, not closed over.

Fixes issue #4272.
2018-10-28 00:33:08 +11:00
Damien George c2074e7b66 tests/cmdline/cmd_showbc.py: Fix test to explicitly declare nonlocal.
The way it was written previously the variable x was not an implicit
nonlocal, it was just a normal local (but the compiler has a bug which
incorrectly makes it a nonlocal).
2018-10-27 23:57:14 +11:00
Damien George 27ca9ab8b2 tests/import: Add .exp file for module_getattr.py to not require Py 3.7. 2018-10-23 11:56:58 +11:00
Paul Sokolovsky c638d86660 tests/extmod/uctypes_sizeof_layout: Test for sizeof of different layout.
On almost all realistic platforms, native layout should be larger (or
equal) than packed layout.
2018-10-23 11:33:35 +11:00
Paul m. p. P 454cca6016 py/objmodule: Implement PEP 562's __getattr__ for modules.
Configurable via MICROPY_MODULE_GETATTR, disabled by default.  Among other
things __getattr__ for modules can help to build lazy loading / code
unloading at runtime.
2018-10-23 11:22:50 +11:00
Paul Sokolovsky a527313382 tests: Make bytes/str.count() tests skippable. 2018-10-22 22:50:28 +11:00
Damien George a07e56cbd8 tests/basics/class_getattr: Remove invalid test for __getattribute__.
Part of this test was trying to test some functionality of __getattribute__
but this method name was misspelt so it wasn't doing anything useful.
Fixing the typo in this name makes the test fail because MicroPython
doesn't support user defined __getattribute__ methods.  So this part of the
test is removed.  The remaining tests are modified slightly to make it
clearer what they are testing.
2018-10-18 12:28:09 +11:00
Damien George 7eb29c2000 py/objtype: Remove comment about catching exc from user __getattr__.
Any exception raised in a user __getattr__ should be propagated out.  A
test is added to verify these semantics.
2018-10-18 12:15:16 +11:00
Paul Sokolovsky 7059b4af6d tests/uctypes_sizeof_od: Test for using OrderedDict as struct descriptor
Just a copy of uctypes_sizeof.py with minimal changes.
2018-10-13 16:08:25 +11:00
Paul Sokolovsky 6ef783527d tests/uselect_poll_basic: Add basic test for uselect.poll invariants.
This test doesn't check the actual I/O behavior, just "static" invariants
like behavior on duplicate calls or calls when I/O object is not registered
with poller.
2018-10-05 16:57:40 +10:00
Paul Sokolovsky cb66b75692 tests/unix/ffi_float: Skip if strtof() is not available.
As the case for e.g. Android's Bionic Libc.
2018-10-05 16:49:32 +10:00
Damien George 5cc9517fc5 tests/run-tests: Enabled native tests that pass now that yield works. 2018-10-01 13:31:11 +10:00
Damien George dd288904db py/objtype: Support full object model for get/set/delitem special meths.
This makes these special methods have the same calling behaviour as other
methods in a class instance (mp_convert_member_lookup() is already called
by mp_obj_class_lookup()).
2018-09-28 23:22:34 +10:00
Damien George 0c9d452370 py/vm: Fix case of throwing GeneratorExit type into yield-from.
mp_make_raise_obj must be used to convert a possible exception type to an
instance object, otherwise the VM may raise a non-exception object.

An existing test is adjusted to test this case, with the original test
already moved to generator_throw.py.
2018-09-28 11:39:35 +10:00
Damien George e6078dfed2 tests/basics: Split out gen throw tests from yield-from-throw tests. 2018-09-28 11:35:31 +10:00
Damien George ac81cee3fc tests/micropython: Test loading const objs in native and viper funcs. 2018-09-27 23:39:08 +10:00
Damien George b3eadf3f3d py/objfloat: Fix abs(-0.0) so it returns 0.0.
Nan and inf (signed and unsigned) are also handled correctly by using
signbit (they were also handled correctly with "val<0", but that didn't
handle -0.0 correctly).  A test case is added for this behaviour.
2018-09-27 15:21:25 +10:00
Damien George fc1bb51af5 py/objgenerator: Remove TODO about returning gen being called again.
The code implements correct behaviour, as tested by the new test case added
in this commit.
2018-09-27 15:18:24 +10:00
Paul Sokolovsky 8181ec04a4 tests/cpydiff: Add case for difference in behaviour of bytes.format(). 2018-09-26 15:31:10 +10:00
Christopher Swenson 8c656754aa py/modmath: Add math.factorial, optimised and non-opt implementations.
This commit adds the math.factorial function in two variants:
- squared difference, which is faster than the naive version, relatively
  compact, and non-recursive;
- a mildly optimised recursive version, faster than the above one.

There are some more optimisations that could be done, but they tend to take
more code, and more storage space.  The recursive version seems like a
sensible compromise.

The new function is disabled by default, and uses the non-optimised version
by default if it is enabled.  The options are MICROPY_PY_MATH_FACTORIAL
and MICROPY_OPT_MATH_FACTORIAL.
2018-09-26 15:03:04 +10:00
Damien George 9849209ad8 tests/float/float_parse.py: Add tests for accuracy of small decimals. 2018-09-20 22:26:53 +10:00
Damien George 3f6ffe059f py/objgenerator: Implement PEP479, StopIteration convs to RuntimeError.
This commit implements PEP479 which disallows raising StopIteration inside
a generator to signal that it should be finished.  Instead, the generator
should simply return when it is complete.

See https://www.python.org/dev/peps/pep-0479/ for details.
2018-09-20 15:36:59 +10:00
Damien George b01f66c5f1 py: Shorten error messages by using contractions and some rewording. 2018-09-20 14:33:10 +10:00
Damien George 93d71c5436 py/emitnative: Make viper funcs run with their correct globals context.
Viper functions will now capture the globals at the point they were defined
and use these globals when executing.
2018-09-15 22:39:27 +10:00
Damien George a676b5acf6 py/emitnative: Support arbitrary number of arguments to viper functions. 2018-09-15 22:39:27 +10:00
Damien George 9f2067288a py/compile: Factor code that compiles viper type annotations. 2018-09-15 13:44:39 +10:00
Damien George 4f3d9429b5 py: Fix native functions so they run with their correct globals context.
Prior to this commit a function compiled with the native decorator
@micropython.native would not work correctly when accessing global
variables, because the globals dict was not being set upon function entry.

This commit fixes this problem by, upon function entry, setting as the
current globals dict the globals dict context the function was defined
within, as per normal Python semantics, and as bytecode does.  Upon
function exit the original globals dict is restored.

In order to restore the globals dict when an exception is raised the native
function must guard its internals with an nlr_push/nlr_pop pair.  Because
this push/pop is relatively expensive, in both C stack usage for the
nlr_buf_t and CPU execution time, the implementation here optimises things
as much as possible.  First, the compiler keeps track of whether a function
even needs to access global variables.  Using this information the native
emitter then generates three different kinds of code:

1. no globals used, no exception handlers: no nlr handling code and no
   setting of the globals dict.

2. globals used, no exception handlers: an nlr_buf_t is allocated on the
   C stack but it is not used if the globals dict is unchanged, saving
   execution time because nlr_push/nlr_pop don't need to run.

3. function has exception handlers, may use globals: an nlr_buf_t is
   allocated and nlr_push/nlr_pop are always called.

In the end, native functions that don't access globals and don't have
exception handlers will run more efficiently than those that do.

Fixes issue #1573.
2018-09-13 22:47:20 +10:00
Damien George f2de9d60f7 py/emitnative: Fix try-finally in outer scope, so finally is cancelled. 2018-09-11 15:33:25 +10:00
Paul Sokolovsky 674e069ba9 py/objarray: bytearray: Allow 2nd/3rd arg to constructor.
If bytearray is constructed from str, a second argument of encoding is
required (in CPython), and third arg of Unicode error handling is allowed,
e.g.:

bytearray("str", "utf-8", "strict")

This is similar to bytes:

bytes("str", "utf-8", "strict")

This patch just allows to pass 2nd/3rd arguments to bytearray, but
doesn't try to validate them to not impact code size. (This is also
similar to how bytes constructor is handled, though it does a bit
more validation, e.g. check that in case of str arg, encoding argument
is passed.)
2018-09-11 15:10:10 +10:00
Paul Sokolovsky b6ebb4f04e tests/extmod/uhashlib_md5: Add coverage tests for MD5 algorithm.
Based on tests/extmod/uhashlib_sha1.
2018-09-11 14:52:00 +10:00
Damien George e814db592d tests: Remove pyboard.py symlink and instead import from ../tools.
To eliminate the need for symlinks which don't work on systems like
Windows.
2018-09-05 15:36:33 +10:00
Damien George 5630f277bd tests/float: Test -inf and some larger values for special math funcs. 2018-09-04 17:03:37 +10:00
Damien George a111ca25ea tests/float/cmath_fun.py: Fix truncation of small real part of complex. 2018-09-04 17:02:36 +10:00
Damien George 4970e9bc8c tests/basics: Add test cases for context manager raising in enter/exit. 2018-09-04 14:37:30 +10:00
Damien George b14c705c18 tests/basics: Add more tests for return within try-finally. 2018-09-04 14:37:07 +10:00
Damien George 938daa4ff9 tests/run-tests: Enable native tests for unwinding jumps. 2018-09-04 14:33:43 +10:00
Damien George 3cd2c281d7 py/emitnative: Cancel caught exception once handled to prevent reraise.
The native emitter keeps the current exception in a slot in its C stack
(instead of on its Python value stack), so when it catches an exception it
must explicitly clear that slot so the same exception is not reraised later
on.
2018-09-03 17:41:02 +10:00
Damien George b735208403 py/vm: Fix handling of finally-return with complex nested finallys.
Back in 8047340d75 basic support was added in
the VM to handle return statements within a finally block.  But it didn't
cover all cases, in particular when some finally's were active and others
inactive when the "return" was executed.

This patch adds further support for return-within-finally by correctly
managing the currently_in_except_block flag, and should fix all cases.  The
main point is that finally handlers remain on the exception stack even if
they are active (currently being executed), and the unwind return code
should only execute those finally's which are inactive.

New tests are added for the cases which now pass.
2018-09-03 13:08:16 +10:00
Damien George 828f771e32 tests/basics: Provide .exp files for generator tests that fail PEP479.
PEP479 (see https://www.python.org/dev/peps/pep-0479/) prohibited raising
StopIteration from within a generator (it is turned into a RuntimeError).
This behaviour was introduced in Python 3.5 and in 3.7 was made compulsory.
Until uPy implements PEP479, this patch adds .py.exp files for the relevant
tests so they can be run under Python 3.7.
2018-08-17 15:50:21 +10:00
Damien George 8979ce1671 tests: Modify tests that print repr of an exception with 1 arg.
In Python 3.7 the behaviour of repr() of an exception with one argument
changed: it no longer prints a trailing comma in the argument list.  See
https://bugs.python.org/issue30399

This patch modifies tests that rely on this behaviour to not rely on it.
And the python34.py test is updated to include a test for this behaviour
with a .exp file.
2018-08-17 15:46:04 +10:00
Damien George 0988b14cd6 tests/basics/int_big_error.py: Use bytearray to test for int overflow.
In Python 3.7 "1 >> (big int)" is now allowed, it no longer raises an
OverflowError.  So use bytearray to test big-int conversion overflow.
2018-08-17 15:43:47 +10:00
Damien George 96e1fd480d tests/basics/set_pop.py: Sort set before printing for consistent output. 2018-08-17 15:42:51 +10:00
Damien George f774614110 tests/micropython: Add tests for try and with blocks under native/viper. 2018-08-17 14:11:36 +10:00
stijn ca0d78cebb run-tests: Make .exp and .out file names unique by prefixing with dir.
Input files like basics/string_format.py and float/string_format.py have
the same basename so using that name for writing the output (.exp and .out
files) when both tests fail, results in the output of the first one being
overwritten.

Avoid this by using unique names for the output, replacing path characters
with underscores.
2018-08-10 16:33:42 +10:00
Damien George ce786da196 tests/run-tests: Enable bool1.py test with native emitter.
It should work reliably now.
2018-08-04 22:19:04 +10:00
Damien George 49529f22d4 tests/micropython/viper_cond: Add test for large int as bool. 2018-08-04 22:16:24 +10:00
Ayke van Laethem 6572029dc0 tests: Make tests work on targets without float support. 2018-08-04 15:14:23 +10:00
Damien George 571295d090 tests/extmod/ujson_dump_iobase.py: Return number of bytes written.
Otherwise returning None indicates that the write would block and nothing
was actually written.  Fixes issue #3990.
2018-07-30 12:05:48 +10:00
Ayke van Laethem 055ee18919 tests/run-tests: Improve crash reporting when running on remote targets.
It is very useful to know the actual error when debugging why a test fails.
2018-07-20 09:27:28 +10:00
Ayke van Laethem 1b88433f2d
tests/run-tests: Add nrf target. 2018-07-20 00:50:57 +02:00
Ayke van Laethem 7c98c6b053
tests: Improve feature detection for VFS. 2018-07-20 00:50:57 +02:00
Damien George e2e22e3d7e py/objgenerator: Implement __name__ with normal fun attr accessor code.
With the recent change b488a4a848, a
generating function now has the same layout in memory as a normal bytecode
function, and so can reuse the latter's attribute accessor code to
implement __name__.
2018-07-10 16:33:57 +10:00
Damien George e30a5fc7bc extmod/modure: Add ure.sub() function and method, and tests.
This feature is controlled at compile time by MICROPY_PY_URE_SUB, disabled
by default.

Thanks to @dmazzella for the original patch for this feature; see #3770.
2018-07-02 14:55:02 +10:00
Damien George 1e9b871d29 extmod/modure: Add match.span(), start() and end() methods, and tests.
This feature is controlled at compile time by
MICROPY_PY_URE_MATCH_SPAN_START_END, disabled by default.

Thanks to @dmazzella for the original patch for this feature; see #3770.
2018-07-02 14:54:56 +10:00
Damien George 1f86460910 extmod/modure: Add match.groups() method, and tests.
This feature is controlled at compile time by MICROPY_PY_URE_MATCH_GROUPS,
disabled by default.

Thanks to @dmazzella for the original patch for this feature; see #3770.
2018-07-02 14:53:30 +10:00
Damien George d8dc918deb py/compile: Handle return/break/continue correctly in async with.
Before this patch the context manager's __aexit__() method would not be
executed if a return/break/continue statement was used to exit an async
with block.  async with now has the same semantics as normal with.

The fix here applies purely to the compiler, and does not modify the
runtime at all. It might (eventually) be better to define new bytecode(s)
to handle async with (and maybe other async constructs) in a cleaner, more
efficient way.

One minor drawback with addressing this issue purely in the compiler is
that it wasn't possible to get 100% CPython semantics.  The thing that is
different here to CPython is that the __aexit__ method is not looked up in
the context manager until it is needed, which is after the body of the
async with statement has executed.  So if a context manager doesn't have
__aexit__ then CPython raises an exception before the async with is
executed, whereas uPy will raise it after it is executed.  Note that
__aenter__ is looked up at the beginning in uPy because it needs to be
called straightaway, so if the context manager isn't a context manager then
it'll still raise an exception at the same location as CPython.  The only
difference is if the context manager has the __aenter__ method but not the
__aexit__ method, then in that case uPy has different behaviour.  But this
is a very minor, and acceptable, difference.
2018-06-27 16:57:42 +10:00
Damien George 726804ea40 tests: Move non-filesystem io tests to basics dir with io_ prefix. 2018-06-27 16:55:05 +10:00
Paul Sokolovsky bdceea1d12 tests/basics/namedtuple*: Import ucollections first.
Otherwise, test may have artefacts in the presence of the micropython-lib
module.
2018-06-27 14:58:14 +10:00
Paul Sokolovsky bb634115fc tests/extmod/ucryptolib*: Add into and inplace tests for ucryptolib.
Tests for separate input and output buffer (alloc-free operation) and
the same writable buffer used as input and output (inplace operation).
2018-06-27 14:56:46 +10:00
Paul Sokolovsky bf77f34819 tests/extmod/ucryptolib*: Add tests for ucryptolib module. 2018-06-27 14:56:31 +10:00
Damien George b92a8adbfa tests: Add tests using "file" argument in print and sys.print_exception. 2018-06-20 16:08:25 +10:00
Damien George 6d8816fe84 tests/import: Add test for importing invalid .mpy file. 2018-06-18 17:50:34 +10:00
Damien George 48829cd3c6 tests/extmod: Add test for ujson.dump writing to a user IOBase object. 2018-06-18 12:35:56 +10:00
Damien George 0ecce77c66 tests/extmod/ujson_dump.py: Add test for dump to non-stream object. 2018-06-18 12:35:56 +10:00
Damien George a5f5552a0a tests/unix/extra_coverage: Don't test stream objs with NULL write fun.
This behaviour of a NULL write C method on a stream that uses the write
adaptor objects is no longer supported.  It was only ever used by the
coverage build for testing the fail path of mp_get_stream_raise().
2018-06-18 12:35:56 +10:00
Damien George c901cc6862 tests/extmod: Add test for VFS and user-defined filesystem and files. 2018-06-12 12:29:26 +10:00
Damien George 9144b1f10c tests/io: Add simple IOBase test. 2018-06-12 12:29:26 +10:00
Damien George 6a445b60fa py/lexer: Add support for underscores in numeric literals.
This is a very convenient feature introduced in Python 3.6 by PEP 515.
2018-06-12 12:17:43 +10:00
Damien George a12d046c42 tests/pyb: Make i2c and pyb1 pyboard tests run again.
For i2c.py: the accelerometer now uses the new I2C driver so need to
explicitly init the legacy i2c object to get the test working.

For pyb1.py: the legacy pyb.hid() call will crash if the USB_HID object is
not initialised.
2018-06-08 13:00:27 +10:00
Damien George 36c1052183 py/objtype: Optimise instance get/set/del by skipping special accessors.
This patch is a code optimisation, trading text bytes for speed.  On
pyboard it's an increase of 0.06% in code size for a gain (in pystone
performance) of roughly 6.5%.

The patch optimises load/store/delete of attributes in user defined classes
by not looking up special accessors (@property, __get__, __delete__,
__set__, __setattr__ and __getattr_) if they are guaranteed not to exist in
the class.

Currently, if you do my_obj.foo() then the runtime has to do a few checks
to see if foo is a property or has __get__, and if so delegate the call.
And for stores things like my_obj.foo = 1 has to first check if foo is a
property or has __set__ defined on it.

Doing all those checks each and every time the attribute is accessed has a
performance penalty.  This patch eliminates all those checks for cases when
it's guaranteed that the checks will always fail, ie no attributes are
properties nor have any special accessor methods defined on them.

To make this guarantee it checks all attributes of a user-defined class
when it is first created.  If any of the attributes of the user class are
properties or have special accessors, or any of the base classes of the
user class have them, then it sets a flag in the class to indicate that
special accessors must be checked for.  Then in the load/store/delete code
it checks this flag to see if it can take the shortcut and optimise the
lookup.

It's an optimisation that's pretty widely applicable because it improves
lookup performance for all methods of user defined classes, and stores of
attributes, at least for those that don't have special accessors.  And, it
allows to enable descriptors with minimal additional runtime overhead if
they are not used for a particular user class.

There is one restriction on dynamic class creation that has been introduced
by this patch: a user-defined class cannot go from zero special accessors
to one special accessor (or more) after that class has been subclassed.  If
the script attempts this an AttributeError is raised (see addition to
tests/misc/non_compliant.py for an example of this case).

The cost in code space bytes for the optimisation in this patch is:

   unix x64:  +528
unix nanbox:  +508
      stm32:  +192
     cc3200:  +200
    esp8266:  +332
      esp32:  +244

Performance tests that were done:

- on unix x86-64, pystone improved by about 5%
- on pyboard, pystone improved by about 6.5%, from 1683 up to 1794
- on pyboard, bm_chaos (from CPython benchmark suite) improved by about 5%
- on esp32, pystone improved by about 30% (but there are caching effects)
- on esp32, bm_chaos improved by about 11%
2018-06-08 12:12:08 +10:00
Damien George 5ef0d2ab14 tests/extmod: Remove conditional import of uos_vfs, it no longer exists.
This conditional import was only used to get the tests working on the unix
coverage build, which has now switched to use VFS by default so the uos
module alone has the required functionality.
2018-06-06 14:28:23 +10:00
Damien George 6c02da2eec tests/extmod: Add test for importing a script from a user VFS. 2018-06-06 14:28:23 +10:00
Jeff Epler c60589c02b py/objtype: Fix assertion failures in super_attr by checking type.
Fixes assertion failures and segmentation faults when making calls like:

    super(1, 1).x
2018-05-30 11:14:07 +10:00
Jeff Epler 05b13fd292 py/objtype: Fix assertion failures in mp_obj_new_type by checking types.
Fixes assertion failures when the arguments to type() were not of valid
types, e.g., when making calls like:

    type("", (), 3)
    type("", 3, {})
2018-05-30 11:11:24 +10:00
Damien George dfeaea1441 py/objtype: Remove TODO comment about needing to check for property.
Instance members are always treated as values, even if they are properties.
A test is added to show this is the case.
2018-05-25 10:59:40 +10:00
Damien George e686c94052 py/emit: Combine yield value and yield-from emit funcs into one.
Reduces code size by:

   bare-arm:   -24
minimal x86:   -72
   unix x64:  -200
unix nanbox:   -72
      stm32:   -52
     cc3200:   -32
    esp8266:   -84
      esp32:   -24
2018-05-23 00:22:35 +10:00
Damien George 400273a799 py/objgenerator: Protect against reentering a generator.
Generators that are already executing cannot be reexecuted.  This patch
puts in a check for such a case.

Thanks to @jepler for finding the bug.
2018-05-22 16:54:03 +10:00
Jan Klusacek b318ebf101 py/modbuiltins: Add support for rounding integers.
As per CPython semantics.  This feature is controlled by
MICROPY_PY_BUILTINS_ROUND_INT which is disabled by default.
2018-05-22 14:18:16 +10:00
Damien George 1ad0013dec tests: Add some tests for bigint hash, float hash and float parsing.
Following outcome of recent fuzz testing and sanitizing by @jepler.
2018-05-21 13:05:40 +10:00
Damien George 7541be5637 tests/basics/special_methods2: Enable some additional tests that work.
These special methods are all available if MICROPY_PY_ALL_SPECIAL_METHODS
is enabled.
2018-05-11 17:37:16 +10:00
Damien George d2c1db1e5c tests/float/float_parse: Allow test to run on 32-bit archs.
Printing of uPy floats can differ by the floating-point precision on
different architectures (eg 64-bit vs 32-bit x86), so it's not possible to
using printing of floats in some parts of this test.  Instead we can just
check for equivalence with what is known to be the correct answer.
2018-05-11 13:51:18 +10:00
Damien George 3678a6bdc6 py/modbuiltins: Make built-in dir support the __dir__ special method.
If MICROPY_PY_ALL_SPECIAL_METHODS is enabled then dir() will now delegate
to the special method __dir__ if the object it is listing has this method.
2018-05-10 23:14:23 +10:00
Damien George 529860643b py/modbuiltins: Make built-in hasattr work properly for user types.
It now allows __getattr__ in a user type to raise AttributeError when the
attribute does not exist.
2018-05-10 23:03:30 +10:00
Damien George 2ada1124d4 tests/cpydiff: Remove types_int_tobytesfloat now that it doesn't fail.
Commit e269cabe3e added a check that the
first argument to the to_bytes() method is an integer, and now uPy
follows CPython behaviour and raises a TypeError for this test.

Note: CPython checks the argument types before checking the number of
arguments, but uPy does it the other way around, so they give different
exception messages for this test, but still the same type, a TypeError.
2018-05-08 17:05:32 +10:00
Damien George 74ab341d3a tests/cpydiff: Remove working cases from types_float_rounding. 2018-05-04 22:30:50 +10:00
Damien George cd9d71edc8 tests/cpydiff: Remove types_str_decodeerror now that it succeeds.
Commit 68c28174d0 implemented checking for
valid utf-8 data.
2018-05-04 22:27:14 +10:00
Damien George 4b5111f8e1 tests/cpydiff: Remove core_function_unpacking now that it succeeds.
Commit 1e70fda69f fixes this difference.
2018-05-04 22:19:50 +10:00
Ayke van Laethem 5eb198c441 tests/run-tests: Support esp32 as a target for running the test suite. 2018-05-02 17:20:48 +10:00
Damien George db2bdad8a2 tests/pyb: Update tests to run correctly on PYBv1.0.
In adcall.py the pyb module may not be imported, so use ADCAll directly.

In dac.py the DAC object now prints more info, so update .exp file.

In spi.py the SPI should be deinitialised upon exit, so the test can run a
second time correctly.
2018-05-02 15:25:37 +10:00
Mike Wadsten 9f1eafc380 tests/io/bytesio_ext2: Remove dependency on specific EINVAL value
If MICROPY_USE_INTERNAL_ERRNO is disabled, MP_EINVAL is not guaranteed
to have the value 22, so we cannot depend on OSError(22,).
Instead, to support any given port's errno values, without relying
on uerrno, we just check that the args[0] is positive.
2018-05-01 15:48:43 +10:00
Damien George d12483d936 tests/pyb: Add test for pyb.ADCAll class. 2018-04-11 17:12:13 +10:00
Damien George b30e0d2f26 stm32/dac: Add buffering argument to constructor and init() method.
This can be used to select the output buffer behaviour of the DAC.  The
default values are chosen to retain backwards compatibility with existing
behaviour.

Thanks to @peterhinch for the initial idea to add this feature.
2018-04-11 14:22:21 +10:00
Peter Hinch 4f40fa5cf4 stm32/adc: Add read_timed_multi() static method, with docs and tests. 2018-04-11 13:36:17 +10:00
Damien George 0096a4bd00 tests/pyb/adc.py: Fix test so that it really does test ADC values.
Reading into a bytearray will truncate values to 0xff so the assertions
checking read_timed() would previously always succeed.

Thanks to @peterhinch for finding this problem and providing the solution.
2018-04-11 13:21:57 +10:00
Damien George 5ad27d4b8b tests: Move recursive tests to the tests/stress/ subdir.
Keeping all the stress related tests in one place makes it easier to
stress-test a given port, and to also not run such tests on ports that
can't handle them.
2018-04-10 14:43:52 +10:00
Damien George 605fdcf754 tests/stress/recursive_gen: Add test for recursive gen with iter. 2018-04-10 14:39:51 +10:00
Jeff Epler cbf981f330 py/objgenerator: Check stack before resuming a generator.
This turns a hard crash in a recursive generator into a 'maximum recursion
depth exceeded' exception.
2018-04-10 14:06:26 +10:00
Jeff Epler d6cf5c6749 py/objstr: In find/rfind, don't crash when end < start. 2018-04-05 16:14:17 +10:00
Damien George b9c78425a6 tests/micropython/extreme_exc.py: Allow to run without any emg exc buf. 2018-04-05 03:03:16 +10:00
Damien George 4caadc3c01 tests/micropython/extreme_exc.py: Fix test to run on more ports/configs. 2018-04-05 02:33:48 +10:00
Damien George 5995a199a3 tests/micropython: Add set of tests for extreme cases of raising exc's. 2018-04-05 01:06:40 +10:00
Damien George 1bfc774a08 tests/basics/string_compare.py: Add test with string that hashes to 0.
The string "Q+?" is special in that it hashes to zero with the djb2
algorithm (among other strings), and a zero hash should be incremented to a
hash of 1.
2018-04-05 01:04:38 +10:00
Damien George 22161acf47 tests/basics/class_super.py: Add tests for store/delete of super attr. 2018-04-05 01:03:57 +10:00
Damien George 7b7bbd0ee7 tests/basics: Add tests for edge cases of nan-box's 47-bit small int. 2018-04-05 00:59:49 +10:00
Damien George dd48ccb1e3 tests/basics: Add test for subclassing an iterable native type. 2018-04-04 15:26:18 +10:00
Damien George df02f5620a tests/basics/int_big1.py: Add test for big int in mp_obj_get_int_maybe. 2018-04-04 15:23:32 +10:00
Damien George a45a34ec31 tests/stress: Add test to verify the GC can trace nested objects. 2018-04-04 14:22:54 +10:00
Damien George 7d5c753b17 tests/basics: Modify int-big tests to prevent constant folding.
So that these tests test the runtime behaviour, not the compiler (which may
be executed offline).
2018-04-04 13:57:22 +10:00
Damien George f684e9e1ab tests/basics/int_big1.py: Add test converting str with non-print chars. 2018-04-04 13:56:00 +10:00
Damien George 430efb0444 tests/basics: Add test for use of return within try-except.
The case of a return statement in the try suite of a try-except statement
was previously only tested by builtin_compile.py, and only then in the part
of this test which checked for the existence of the compile builtin.  So
this patch adds an explicit unit test for this case.
2018-04-04 01:43:16 +10:00
Damien George bcfff4fc98 tests/basics/iter1.py: Add more tests for walking a user-defined iter.
Some code in mp_iternext() was only tested by the native emitter, so the
tests added here test this function using just the bytecode emitter.
2018-03-30 14:23:13 +11:00
Damien George f50b64cab5 py/runtime: Be sure that non-intercepted thrown object is an exception.
The VM expects that, if mp_resume() returns MP_VM_RETURN_EXCEPTION, then
the returned value is an exception instance (eg to add a traceback to it).
It's possible that a value passed to a generator's throw() is not an
exception so must be explicitly checked for if the thrown value is not
intercepted by the generator.

Thanks to @jepler for finding the bug.
2018-03-30 12:43:38 +11:00
Damien George 3280788195 py/runtime: Check that keys in dicts passed as ** args are strings.
Prior to this patch the code would crash if a key in a ** dict was anything
other than a str or qstr.  This is because mp_setup_code_state() assumes
that keys in kwargs are qstrs (for efficiency).

Thanks to @jepler for finding the bug.
2018-03-30 11:13:32 +11:00
Damien George 22c693aa6f tests/pyb/can: Update to test pyb.CAN restart, state, info, inplace recv 2018-03-19 15:15:39 +11:00
Damien George 9600a1f207 tests/pyb: Update CAN test to expect that auto_restart is printed. 2018-03-16 18:37:55 +11:00
Damien George c926e72750 tests/cpydiff: Indent workaround code snippet so it formats correctly. 2018-03-15 15:49:38 +11:00
Tom Collins 4d3a92c67c extmod/vfs_fat: Add file size as 4th element of uos.ilistdir tuple. 2018-03-12 12:26:36 +11:00
Damien George 72adc381fb tests/basics/builtin_enumerate: Add test for many pos args to enumerate. 2018-03-08 12:51:06 +11:00
Damien George 0acf868bb7 tests/extmod/time_ms_us: Fix ticks tests, ticks_diff args are reversed. 2018-03-04 00:38:15 +11:00
Damien George e3d11b6a6e tests/extmod/time_ms_us: Add test for calling ticks_cpu().
This is just to test that the function exists and returns some kind of
valid value.  Although this file is for testing ms/us functions, put the
ticks_cpu() test here so not to add a new test file.
2018-03-04 00:17:33 +11:00
Damien George 512f4a6ad1 tests/unix: Add coverage test for uio.resource_stream from frozen str. 2018-03-03 23:58:03 +11:00
Damien George c607b58efe tests: Move heap-realloc-while-locked test from C to Python.
This test for calling gc_realloc() while the GC is locked can be done in
pure Python, so better to do it that way since it can then be tested on
more ports.
2018-03-02 10:59:09 +11:00
Damien George c3f1b22338 tests/unix: Add coverage tests for various GC calls. 2018-03-01 22:49:15 +11:00
Damien George 955ee6477f py/formatfloat: Fix case where floats could render with negative digits.
Prior to this patch, some architectures (eg unix x86) could render floats
with "negative" digits, like ")".  For example, '%.23e' % 1e-80 would come
out as "1.0000000000000000/)/(,*0e-80".  This patch fixes the known cases.
2018-03-01 17:00:02 +11:00
Damien George 7b050fa76c py/formatfloat: Fix case where floats could render with a ":" character.
Prior to this patch, some architectures (eg unix x86) could render floats
with a ":" character in them, eg 1e+39 would come out as ":e+38" (":" is
just after "9" in ASCII so this is like 10e+38).  This patch fixes some of
these cases.
2018-03-01 16:02:59 +11:00
Damien George bc12eca461 py/formatfloat: Fix rounding of %f format with edge-case FP values.
Prior to this patch the %f formatting of some FP values could be off by up
to 1, eg '%.0f' % 123 would return "122" (unix x64).  Depending on the FP
precision (single vs double) certain numbers would format correctly, but
others wolud not.  This patch should fix all cases of rounding for %f.
2018-03-01 15:51:03 +11:00
Damien George 90e719a232 tests/extmod/vfs_fat_fileio1: Add test for calling file obj finaliser. 2018-02-28 15:27:51 +11:00
Damien George 439acddc60 tests/basics/gc1: Add test which triggers GC threshold. 2018-02-27 22:39:17 +11:00
Damien George d3cac18d49 tests/unix: Add coverage test for VM executing invalid bytecode. 2018-02-27 16:18:11 +11:00
Damien George 22ade2f5c4 py/vm: Fix case of handling raised StopIteration within yield from.
This patch concerns the handling of an NLR-raised StopIteration, raised
during a call to mp_resume() which is handling the yield from opcode.

Previously, commit 6738c1dded introduced code
to handle this case, along with a test.  It seems that it was lucky that
the test worked because the code did not correctly handle the stack pointer
(sp).

Furthermore, commit 79d996a57b improved the
way mp_resume() propagated certain exceptions: it changed raising an NLR
value to returning MP_VM_RETURN_EXCEPTION.  This change meant that the
test introduced in gen_yield_from_ducktype.py was no longer hitting the
code introduced in 6738c1dded.

The patch here does two things:

1. Fixes the handling of sp in the VM for the case that yield from is
   interrupted by a StopIteration raised via NLR.

2. Introduces a new test to check this handling of sp and re-covers the
   code in the VM.
2018-02-27 15:39:31 +11:00
Damien George 6dad088569 tests/float: Adjust float-parsing tests to pass with only a small error.
Float parsing (both single and double precision) may have a relative error
of order the floating point precision, so adjust tests to take this into
account by not printing all of the digits of the answer.
2018-02-26 15:54:03 +11:00