Commit Graph

4134 Commits

Author SHA1 Message Date
Scott Shawcroft 6375d8699e
Validate builtin member is a module 2020-02-26 10:32:02 -08:00
Scott Shawcroft 86fd93bd03
Support importing native modules in native packages.
This only fixes the `import` portion. It doesn't actually change
reference behavior because modules within a package could already
be referenced through the parent package even though an error should
have been thrown.
2020-02-25 15:32:55 -08:00
Dan Halbert e31ac710be Enable _bleio adapter when _bleio is imported 2020-02-20 21:55:04 -05:00
Scott Shawcroft e8f7141564
Disable BLE file service for now
Fixes #2633
2020-02-20 12:15:56 -08:00
Dan Halbert c592bd612a Implement to_bytes(..., signed=True) 2020-02-14 15:12:20 -05:00
Scott Shawcroft e97b0cfc61
Merge pull request #2581 from jamesbowman/master
First draft of eveL, the low-level module of the Gameduino bindings
2020-02-13 11:21:32 -08:00
Scott Shawcroft 36e6cc8feb
Track first free atb for multiple block sizes.
This speeds up cases where no single block allocations happen while
Python code is allocating other block sizes.
2020-02-11 17:06:24 -08:00
James Bowman 5c6d94d3e5 Split into shared-module and shared-bindings 2020-02-07 10:30:49 -08:00
James Bowman acef93a253 Rename eveL to _eve, EVEL to _EVE 2020-02-05 18:17:58 -08:00
Dan Halbert e13642351c fix printing single-arg exceptions 2020-02-04 16:55:56 -05:00
Dan Halbert 7fe959ab39 fix multi-arg exception printing 2020-02-04 16:41:25 -05:00
Dan Halbert 5164719e67 preserve errno in OSError 2020-02-04 16:19:40 -05:00
Dan Halbert 57b566e736 Include filename for 'No such file/directory', etc. 2020-02-04 13:32:39 -05:00
James Bowman 8347f2b5c3 Correct default state to off for eveL module.
Fix build break because of overflowing small ports
2020-02-03 19:23:42 -08:00
James Bowman 7fd30e7d20 First draft of eveL, the low-level module of the Gameduino (and BridgeTek EVE) bindings.
[adafruit/circuitpython#2578]
2020-02-03 16:46:14 -08:00
Scott Shawcroft 55eb1730b8
Merge remote-tracking branch 'adafruit/master' into tweak_pixelbuf 2020-01-30 10:59:21 -08:00
Scott Shawcroft 2cc20e8816
Remove unneeded native cast. 2020-01-30 10:59:16 -08:00
Scott Shawcroft 5d24ade5c9
Tweak error messages to reduce code size. 2020-01-29 17:32:07 -08:00
Scott Shawcroft d655c785b6
Merge commit 'b36b24' into tweak_pixelbuf 2020-01-29 13:35:22 -08:00
Scott Shawcroft 5b6b4eb326
Merge pull request #2551 from jepler/build-mpy-cross-static-linux-win64
Build static binaries of mpy-cross for desktop linux, desktop windows, mac, and raspbian
2020-01-29 11:45:08 -08:00
Scott Shawcroft f6a635b102
Fix subclassing of objects that are tested. Others may still be broken. 2020-01-27 14:52:42 -08:00
Scott Shawcroft b36b2493bc
Merge pull request #2532 from tannewt/teensy4-dev
Refine iMX RT memory layout and add three boards
2020-01-27 14:11:08 -08:00
Jeff Epler d9e0742a07 accomodate excessively old gcc versions for raspbian mpy-cross cross-build 2020-01-25 15:32:52 -06:00
Scott Shawcroft 81c3bc411f
Don't assume native methods want the native object as self. 2020-01-24 18:22:28 -08:00
tsupplis b66abd47b8
Update fix (missing pragma gcc diagnostic push)
Update fix (missing pragma gcc diagnostic push)
2020-01-21 19:45:20 +00:00
Scott Shawcroft 7d8dac9211
Refine iMX RT memory layout and add three boards
Introduces a way to place CircuitPython code and data into
tightly coupled memory (TCM) which is accessible by the CPU in a
single cycle. It also frees up room in the corresponding cache for
intermittent data. Loading from external flash is slow!

The data cache is also now enabled.

Adds support for the iMX RT 1021 chip. Adds three new boards:
* iMX RT 1020 EVK
* iMX RT 1060 EVK
* Teensy 4.0

Related to #2492, #2472 and #2477. Fixes #2475.
2020-01-17 17:36:08 -08:00
Scott Shawcroft 8b61333937
Merge pull request #2510 from dhalbert/bonding-nvm
nrf: Add bonding to BLE pairing support
2020-01-15 16:11:09 -08:00
Scott Shawcroft 1d2e262a59
Merge pull request #2505 from theodox/master
Make all `PYTHON` env vars into `PYTHON3`
2020-01-14 10:55:23 -08:00
Scott Shawcroft ed811fb9c0
Merge pull request #2504 from rhooper/fix-tuple-subscr
Fix tuple subscr
2020-01-14 10:53:50 -08:00
Dan Halbert 2a75196aa3 merge from adafruit/circuitpython 2020-01-13 18:15:32 -05:00
Scott Shawcroft 2eb26a6d0b
Merge pull request #2457 from hierophect/stm32-cpython-compat
STM32: Cpython compatibility flag 2
2020-01-13 13:47:55 -08:00
Dan Halbert 9e7f8743c2 fix CCCD bonding store; avoid excessive bonding writes 2020-01-12 23:32:51 -05:00
Steve Theodore dd4b0f6e9c
Make all `PYTHON` env vars into `PYTHON3`
make file contained a mix of references to `PYTHON` and `PYTHON3`, and did not build on a fresh install of Ubuntu (under Windows LXSS)
2020-01-11 21:37:54 -08:00
Roy Hooper 73e076a40c make types that depend on tuple subscr work 2020-01-11 18:21:43 -05:00
Scott Shawcroft 6ea8d8a6c2
Merge pull request #2498 from dhalbert/optional-i2c-pullup-checking
Make requiring I2C pullups be optional
2020-01-10 11:42:44 -08:00
Scott Shawcroft 8708d3dc45
Merge pull request #2461 from jepler/urandom-hardfaults
Urandom hardfaults
2020-01-10 11:37:59 -08:00
Dan Halbert 189f2d5f07 Make requiring I2C pullups be optional 2020-01-09 17:31:50 -05:00
Hierophect 10eed78dd8 use CFLAG to properly set define 2020-01-08 17:37:20 -05:00
Jeff Epler f1c2dee1c0 style 2020-01-08 16:36:43 -06:00
Scott Shawcroft a10cd8580c
Merge pull request #2445 from jepler/mp3-jeplayer-fixes
Fixes for JEplayer
2020-01-08 12:50:13 -08:00
Scott Shawcroft d4492aaed0
Merge remote-tracking branch 'adafruit/master' into packet_buffer 2020-01-08 10:44:37 -08:00
Jeff Epler 5baaac55ce vstr_init_len: Don't crash if (size_t)-1 is passed
In this unusual case, (len + 1) is zero, the allocation in vstr_init
succeeds (allocating 1 byte), and then the caller is likely to erroneously
access outside the allocated region, for instance with a memset().

This could be triggered with os.urandom(-1) after it was converted to use
mp_obj_new_bytes_of_zeros.
2020-01-08 09:42:44 -06:00
Jeff Epler dd6010a17e Fix more build problems 2020-01-06 13:35:43 -06:00
Marius-450 3ad3d49959 changes only for monster m4sk 2020-01-04 12:32:49 -05:00
Marius-450 d2b2cf0add CIRCUITPY_DISPLAY_LIMIT = 2 2020-01-04 12:20:32 -05:00
Scott Shawcroft 82fb761c0f
Add PacketBuffer and MTU negotiation support.
PacketBuffer facilitates packet oriented BLE protocols such as BLE
MIDI and the Apple Media Service.

This also adds PHY, MTU and connection event extension negotiation
to speed up data transfer when possible.
2020-01-03 17:29:54 -08:00
Roy Hooper 767ce1cdf8 remove unnecessary GCC pragmas 2020-01-02 18:03:18 -05:00
Roy Hooper f1a9039632 Merge branch 'master' into pixelbuf-subscr-change 2019-12-29 13:56:31 -05:00
Scott Shawcroft b859e2b710
Remove `re` from CPX Displayio build to make space. 2019-12-20 11:43:56 -08:00
Jeff Epler 201f4648c4 py.mk: Fix race condition building .mo files
By having an order-only dependency on the directory itself, the directory
is sure to be created before the rule to create a .mo file is.

This fixes a low-freqency error on github actions such as

> msgfmt: error while opening "build/genhdr/en_US.mo" for writing: No such file or directory
2019-12-16 15:33:55 -06:00
Scott Shawcroft d8e66a5f32
try 2. make namedtuple types handle subclasses 2019-12-13 16:00:04 -08:00
Scott Shawcroft 7f7105d36d
Fix tuple test 2019-12-13 14:52:04 -08:00
Roy Hooper dc8dd6df20 Revert subscr signature change 2019-12-13 14:29:15 -05:00
Roy Hooper 15072c69c9 push changes 2019-12-13 14:07:53 -05:00
Roy Hooper 72ad2e9259 Merge branch 'master' into new-pixelbuf-api 2019-12-13 13:45:16 -05:00
Dan Halbert ef2ef7a6b8 merge from master 2019-12-12 15:51:13 -05:00
Damien George 767d47dd60
py/nlrthumb: Save and restore VFP registers s16-s21 when CPU has them.
These s16-s21 registers are used by gcc so need to be saved.  Future
versions of gcc (beyond v9.1.0), or other compilers, may eventually need
additional registers saved/restored.

See issue #4844.
2019-12-12 11:10:10 -08:00
Damien George 1cf0ce094a
py/nlr: Use MP_UNREACHABLE at the end of arch-specific nlr_jump funcs.
Recent versions of gcc perform optimisations which can lead to the
following code from the MP_NLR_JUMP_HEAD macro being omitted:

    top->ret_val = val; \
    MP_NLR_RESTORE_PYSTACK(top); \
    *_top_ptr = top->prev; \

This is noticeable (at least) in the unix coverage on x86-64 built with gcc
9.1.0.  This is because the nlr_jump function is marked as no-return, so
gcc deduces that the above code has no effect.

Adding MP_UNREACHABLE tells the compiler that the asm code may branch
elsewhere, and so it cannot optimise away the code.
2019-12-12 11:01:40 -08:00
Damien George 63046d800d
py: Introduce MP_UNREACHABLE macro to annotate unreachable code.
And use it to replace the same pattern at the end of nlrthumb.c:nlr_jump.
2019-12-12 11:01:39 -08:00
Dan Halbert 8176325130 Merge remote-tracking branch 'adafruit/master' into ld-cleanup 2019-12-11 22:52:59 -05:00
Dan Halbert 68ae47907c merge from upstream 2019-12-10 21:04:46 -05:00
Roy Hooper 0326c98fd5 Merge branch 'master' into new-pixelbuf-api 2019-12-10 20:44:43 -05:00
Dan Halbert 013c840862 working on all ports 2019-12-10 20:27:30 -05:00
Jeff Epler 6305d48947 gc_free: give a better error when freeing outside of VM 2019-12-10 17:07:52 -06:00
Jeff Epler a08d9e6d8e audiocore: Add MP3File using Adafruit_MP3 library 2019-12-10 14:03:06 -06:00
Scott Shawcroft 19ac8aea8c
Merge pull request #2353 from jepler/audiosample-protocol
Convert audiosamples to use micropython "protocols" (safely)
2019-12-09 14:50:16 -08:00
Dan Halbert d628d2a261 atmel-samd working 2019-12-06 15:18:20 -05:00
Dan Halbert 40434d6919 wip 2019-12-05 22:45:53 -05:00
Jeff Epler 49a547eed8 proto: Use %q format-string shortcut 2019-12-05 13:06:10 -06:00
Scott Shawcroft 17c8356b8c
Add connection interval and debugging
This also sets TinyUSB to master and to not include its submodules.

It also fixes an old displayio example comment and retries gattc
reads.
2019-12-04 14:39:02 -08:00
Jeff Epler 238e121236 protocols: Allow them to be (optionally) type-safe
Protocols are nice, but there is no way for C code to verify whether
a type's "protocol" structure actually implements some particular
protocol.  As a result, you can pass an object that implements the
"vfs" protocol to one that expects the "stream" protocol, and the
opposite of awesomeness ensues.

This patch adds an OPTIONAL (but enabled by default) protocol identifier
as the first member of any protocol structure.  This identifier is
simply a unique QSTR chosen by the protocol designer and used by each
protocol implementer.  When checking for protocol support, instead of
just checking whether the object's type has a non-NULL protocol field,
use `mp_proto_get` which implements the protocol check when possible.

The existing protocols are now named:
    protocol_framebuf
    protocol_i2c
    protocol_pin
    protocol_stream
    protocol_spi
    protocol_vfs
(most of these are unused in CP and are just inherited from MP; vfs and
stream are definitely used though)

I did not find any crashing examples, but here's one to give a flavor of what
is improved, using `micropython_coverage`.  Before the change,
the vfs "ioctl" protocol is invoked, and the result is not intelligible
as json (but it could have resulted in a hard fault, potentially):

    >>> import uos, ujson
    >>> u = uos.VfsPosix('/tmp')
    >>> ujson.load(u)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: syntax error in JSON

After the change, the vfs object is correctly detected as not supporting
the stream protocol:
    >>> ujson.load(p)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    OSError: stream operation not supported
2019-12-04 09:29:57 -06:00
Scott Shawcroft 15886b1505
Merge pull request #2345 from jepler/compressed-unicode
translation: Compress as unicode, not bytes
2019-12-02 17:11:49 -08:00
Jeff Epler 1a0dcb5caa makeqstrdata: reclaim some more bytes on some translations
If a translation only has unicode code points 255 and below, the "values"
array can be 8 bits instead of 16 bits.  This reclaims some code size,
e.g., in a local build, trinket_m0 / en_US reclaimed 112 bytes and de_DE
reclaimed 104 bytes.  However, languages like zh_Latn_pinyin, which use
code points above 255, did not benefit.
2019-12-02 14:49:23 -06:00
Roy Hooper a4bbf35092 Merge branch 'master' into new-pixelbuf-api 2019-12-02 14:06:33 -05:00
Jeff Epler 879e1041c9 makeqstrdata: fix printing of 'increased length' message 2019-12-02 10:18:48 -06:00
Jeff Epler e06a3bbceb translation: Compress as unicode, not bytes
By treating each unicode code-point as a single entity for huffman
compression, the overall compression rate can be somewhat improved
without changing the algorithm.  On the decompression side, when
compressed values above 127 are encountered, they need to be
converted from a 16-bit Unicode code point into a UTF-8 byte
sequence.

Doing this returns approximately 1.5kB of flash storage with the
zh_Latn_pinyin translation. (292 -> 1768 bytes remaining in my build
of trinket_m0)

Other "more ASCII" translations benefit less, and in fact
zh_Latn_pinyin is no longer the most constrained translation!
(de_DE 1156 -> 1384 bytes free in flash, I didn't check others
before pushing for CI)

English is slightly pessimized, 2840 -> 2788 bytes, probably mostly
because the "values" array was changed from uint8_t to uint16_t,
which is strictly not required for an all-ASCII translation.  This
could probably be avoided in this case, but as English is not the
most constrained translation it doesn't really matter.

Testing performed: built for feather nRF52840 express and trinket m0
in English and zh_Latn_pinyin; ran and verified the localized
messages such as
    Àn xià rènhé jiàn jìnrù REPL. Shǐyòng CTRL-D chóngxīn jiāzài.
and
    Press any key to enter the REPL. Use CTRL-D to reload.
were properly displayed.
2019-12-02 09:46:46 -06:00
Jeff Epler 95d9c49e43 Merge remote-tracking branch 'origin/master' into tick-refactor 2019-11-29 11:27:09 -06:00
Roy Hooper 56720eae0a remove unnecessary intermediate mp_obj_subscr wrapper 2019-11-26 18:39:08 -05:00
Thea Flowers 84e1d7f304
Make the @micropython.native decorator no-op if support isn't enabled
When adding the ability for boards to turn on the `@micropython.native`, `viper`, and `asm_thumb` decorators it was pointed out that it's somewhat awkward to write libraries and drivers that can take advantage of this since the decorators raise `SyntaxErrors` if they aren't enabled. In the case of `viper` and `asm_thumb` this behavior makes sense as they require writing non-normative code. Drivers could have a normal and viper/thumb implementation and implement them as such:

```python
try:
    import _viper_impl as _impl
except SyntaxError:
    import _python_impl as _impl

def do_thing():
    return _impl.do_thing()
```

For `native`, however, this behavior and the pattern to work around it is less than ideal. Since `native` code should also be valid Python code (although not necessarily the other way around) using the pattern above means *duplicating* the Python implementation and adding `@micropython.native` in the code. This is an unnecessary maintenance burden.

This commit *modifies* the behavior of the `@micropython.native` decorator. On boards with `CIRCUITPY_ENABLE_MPY_NATIVE` turned on it operates as usual. On boards with it turned off it does *nothing*- it doesn't raise a `SyntaxError` and doesn't apply optimizations. This means we can write our drivers/libraries once and take advantage of speedups on boards where they are enabled.
2019-11-26 13:09:30 -08:00
Scott Shawcroft 6e3b363f50
Merge pull request #2317 from babygrimes/frozen-mpy-bytes-gc_long_lived-crash
Only make objects long lived if they are on the GC heap
2019-11-24 23:12:56 -08:00
Roy Hooper a9baa441c9 disable -Wunused-parameter on subscr functions 2019-11-23 13:52:14 -05:00
Roy Hooper 6108fa3766 Merge branch 'master' into new-pixelbuf-api 2019-11-23 12:22:04 -05:00
Roy Hooper 27979f51ac use base for errors 2019-11-23 12:15:12 -05:00
Roy Hooper c770ccd939 make ->subscr take an instance to pass when instance_subscr is called from subscr. 2019-11-23 12:09:26 -05:00
Jeff Epler 77b78d7fb9 Merge remote-tracking branch 'origin/master' into tick-refactor 2019-11-22 14:28:51 -06:00
David Grimes f13ba7e8d9 * only make objects long lived if they are on the GC heap 2019-11-22 13:47:13 -05:00
Dan Halbert 1d411d2874 Merge remote-tracking branch 'adafruit/master' into testing-fixes 2019-11-22 11:55:34 -05:00
Scott Shawcroft 5e857fdb67
Use BluetoothError in _bleio
This better differentiates errors than using OSError everywhere.
2019-11-20 14:02:15 -08:00
Jeff Epler 568636d562 run_background_tasks: Do nothing unless there has been a tick
This improves performance of running python code by 34%, based
on the "pystone" benchmark on metro m4 express at 5000 passes
(1127.65 -> 1521.6 passes/second).

In addition, by instrumenting the tick function and monitoring on an
oscilloscope, the time actually spent in run_background_tasks() on
the metro m4 decreases from average 43% to 0.5%. (however, there's
some additional overhead that is moved around and not accounted for
in that "0.5%" figure, each time supervisor_run_background_tasks_if_tick
is called but no tick has occurred)

On the CPB, it increases pystone from 633 to 769, a smaller percentage
increase of 21%.  I did not measure the time actually spent in
run_background_tasks() on CPB.

Testing performed: on metro m4 and cpb, run pystone adapted from python3.4
(change time.time to time.monotonic for sub-second resolution)

Besides running a 5000 pass test, I also ran a 50-pass test while
scoping how long an output pin was set.  Average: 34.59ms or 1445/s on m4,
67.61ms or 739/s on cbp, both matching the other pystone result reasonably
well.

import pystone
import board
import digitalio
import time

d = digitalio.DigitalInOut(board.D13)
d.direction = digitalio.Direction.OUTPUT

while True:
    d.value = 0
    time.sleep(.01)
    d.value = 1
    pystone.main(50)
2019-11-18 11:26:48 -06:00
Jeff Epler 7f744a2369 Supervisor: move most of systick to the supervisor
This code is shared by most parts, except where not all the #ifdefs
inside the tick function were present in all ports.  This mostly would
have broken gamepad tick support on non-samd ports.

The "ms32" and "ms64" variants of the tick functions are introduced
because there is no 64-bit atomic read.  Disabling interrupts avoids
a low probability bug where milliseconds could be off by ~49.5 days
once every ~49.5 days (2^32 ms).

Avoiding disabling interrupts when only the low 32 bits are needed is a minor
optimization.

Testing performed: on metro m4 express, USB still works and
time.monotonic_ns() still counts up
2019-11-18 11:01:23 -06:00
Jeff Epler 45d1b290ee circuitpy_mpconfig.h: Express HOOKS in terms of RUN_BACKGROUND_TASKS
.. this means that when we want to modify RUN_BACKGROUND_TASKS, only one
change is needed instead of 3
2019-11-18 11:00:24 -06:00
Jeff Epler acde22a436 circuitpy_mpconfig.h: Move includes after include-guard
To benefit from gcc's "once-only headers" implementation, the
"wrapper-#ifndef" must be the first non-comment part of the file,
according to the manual for various gcc/cpp versions.
2019-11-18 11:00:24 -06:00
Roy Hooper fa57de0688 use instance for verbose errors 2019-11-16 14:04:12 -05:00
Thea Flowers 3439c36197
Fix bad call to mp_arg_check_num 2019-11-05 17:49:47 -08:00
Thea Flowers c7195c4bc5
Allow boards to enable the `micropython.native` decorator
Adds the `CIRCUITPY_ENABLE_MPY_NATIVE` for `mpconfigboard.mk` that enables
the `micropython.native` decorator.
2019-11-05 14:27:53 -08:00
Dan Halbert 1505da784f wip 2019-10-28 18:15:02 -04:00
Scott Shawcroft ae30a1e5aa
Refine _bleio
This PR refines the _bleio API. It was originally motivated by
the addition of a new CircuitPython service that enables reading
and modifying files on the device. Moving the BLE lifecycle outside
of the VM motivated a number of changes to remove heap allocations
in some APIs.

It also motivated unifying connection initiation to the Adapter class
rather than the Central and Peripheral classes which have been removed.
Adapter now handles the GAP portion of BLE including advertising, which
has moved but is largely unchanged, and scanning, which has been enhanced
to return an iterator of filtered results.

Once a connection is created (either by us (aka Central) or a remote
device (aka Peripheral)) it is represented by a new Connection class.
This class knows the current connection state and can discover and
instantiate remote Services along with their Characteristics and
Descriptors.

Relates to #586
2019-10-21 18:57:03 -07:00
Dan Halbert 7b79ac3739 Parameterize linker script 2019-10-20 23:50:12 -04:00
Roy Hooper 2970680e6a fix show and fix step > 1 2019-10-20 19:54:25 -04:00
Dan Halbert be8136dc6d Merge remote-tracking branch 'adafruit/master' into bonding1 2019-10-15 15:55:21 -04:00
Scott Shawcroft 1610d06bb4
Switch arg check back to allow ignored args for strings 2019-10-14 19:59:23 -07:00
Scott Shawcroft 9435e01f9e
Support __bytes
Fixes #1763
2019-10-14 16:05:17 -07:00
Jerry Needell 051670038e restructure nlr.h for udefined archtectures 2019-10-14 07:02:32 -04:00
Jeff Epler cd0ed65b29 mp_obj_instance_make_new: clearer way to avoid null pointer dereference 2019-10-10 13:25:24 +09:00
Jeff Epler 8fbe19b993 mp_obj_instance_make_new: avoid undefined behavior
If kw_args is NULL then memcpy() gets a NULL source argument.
This is undefined behavior under the C standard, even if 0 bytes
are being copied.

This problem was found using clang 7's scan-build static analyzer.
2019-10-08 11:31:06 +09:00
Jeff Epler 85f0048d22 mp_bytecode_print_str: avoid undefined behavior
Left shift of negative numbers is undefined in the "C" standard.  Multiplying
by 128 has the intended effect (in the absence of integer overflow, anyway),
can be implemented using the same shift instruction, but does not invoke
undefined behavior.

This problem was found using clang 7's scan-build static analyzer.
2019-10-08 11:16:11 +09:00
Jeff Epler 46b6870ffa gc_alloc: Remove redundant 'collected' assignment
The remaining assignment was added in upstream micropython; the
deleted assignment was added in circuitpython as part of the long-lived
object area feature.  During the merge, the redundant assignment
was not removed.

(since collected is a local variable and no pointers to it escape,
it doesn't seem possible for the placement of the assignment before
or after GC_ENTER() is important)

This diagnostic was found by clang 7's scan-build static analyzer.
2019-10-08 10:54:13 +09:00
Jeff Epler 0d96f1906b mp_binary_get_int: avoid undefined behavior
Left shift of negative numbers is undefined in the "C" standard.  Multiplying
by 256 has the intended effect (in the absence of integer overflow, anyway),
can be implemented using the same shift instruction, but does not invoke
undefined behavior.

This problem was found using clang 7's scan-build static analyzer.
2019-10-08 10:48:25 +09:00
Dan Halbert fc19e03128 WIP: bonding 2019-10-06 21:30:26 -04:00
Hierophect e017a5925d Revert modules with missed dependence 2019-10-04 15:04:24 -04:00
Hierophect 7a2f60c43d Add Always Build flag, remove redundancy 2019-10-03 15:23:45 -04:00
jepler 70daf007ae In py/, must guard uses of RUN_BACKGROUND_TASKS 2019-09-11 21:15:10 -05:00
jepler 932ac0960b stream_readall: This can be long-running, run background tasks
While finding sources of clicks and buzzes in nrf i2sout, I identified
this site as one which could be long running.  Reproducer code was to
play a 22.05kHz sample and repeatedly print `os.listdir('')`
2019-09-09 20:14:02 -05:00
jepler d9c8460934 py/obj.c: This can be long-running, run background tasks
While finding sources of clicks and buzzes in nrf i2sout, I identified
this site as one which could be long running.  Reproducer code was to
play a 22.05kHz sample and repeatedly print `os.listdir('')`
2019-09-09 20:14:02 -05:00
sommersoft b1c3d47413 Merge branch 'master' of https://github.com/adafruit/circuitpython into mixer_voice 2019-09-01 21:16:12 -05:00
sommersoft 8120f5cdad Merge branch 'master' of https://github.com/adafruit/circuitpython into mixer_voice 2019-08-29 22:14:53 -05:00
Dan Halbert 7a64af9280 rename bleio module to _bleio 2019-08-29 18:44:27 -04:00
Dan Halbert 19c59b41ed bleio: API change to create and connect related objects simulatenously: no orphan bleio objects 2019-08-28 16:15:09 -04:00
Scott Shawcroft 0876d5c4ad
Disable bitbangio on Itsy M0
Also, switch CIRCUITPY_BITBANG_APA102 to makefile setting so it can alter included files
2019-08-27 15:21:47 -07:00
sommersoft df5568d993 move Mixer & MixerVoice from 'audiocore' to 'audiomixer' 2019-08-24 23:36:18 -05:00
sommersoft b54fd961cb Merge branch 'master' of https://github.com/adafruit/circuitpython into mixer_voice 2019-08-24 17:14:05 -05:00
Scott Shawcroft 7324b70a7c
Rework based on Dan's review 2019-08-23 15:27:21 -07:00
Scott Shawcroft 9993a99906
Add initial Monster M4SK build 2019-08-22 14:24:32 -07:00
Scott Shawcroft 36a23e0fe3
Rework refresh API and factor common display stuff out
NOT TESTED! Just compiles

Fixes #1691
2019-08-22 14:23:27 -07:00
Scott Shawcroft c247e7df9c
Begin refresh rework. 2019-08-22 14:08:33 -07:00
Scott Shawcroft 70680d5b22
EPaper displays work mostly. 2019-08-22 14:08:33 -07:00
Dan Halbert e00696de7f merge from upstream and make translate 2019-08-20 13:06:23 -04:00
Scott Shawcroft bd4d3c6393
Merge pull request #2068 from jepler/audioio-compat
audioio: By default, be compatible with 4.x
2019-08-19 19:43:52 -07:00
sommersoft 1b2996a75e Merge branch 'master' of https://github.com/adafruit/circuitpython into mixer_voice 2019-08-19 21:23:27 -05:00
Dan Halbert e3dc5e3a66 Merge remote-tracking branch 'adafruit/master' into run-background-tasks
Restore dependencies indicated by indentation in circuitpy_mpconfig.h.
2019-08-19 12:41:20 -04:00
Dan Halbert e2a4c76a37 make nrf touchio be generic: now available for SAMD51 too 2019-08-18 08:44:10 -04:00
Jeff Epler 47d6dd843e audioio: By default, be compatible with 4.x
Testing performed: That the shipped .mpy files on a PyPortal (CP 4.x)
still work (play audio) with this branch, instead of erroring because
`WaveFile` can't be found in `audioio`.

Flash usage grew by 28 bytes.  (I expected 24, there must be some other
effect on size/alignment that I didn't predict)
2019-08-17 13:54:06 -05:00
Scott Shawcroft 85d7398476
Merge pull request #2066 from dhalbert/ble-pairing
BLE: more features
2019-08-16 14:50:00 -07:00
Scott Shawcroft b3de7efc07
Fix I2CDisplay lifecycle and splash lifecycle.
Fixes https://github.com/adafruit/Adafruit_CircuitPython_DisplayIO_SSD1306/issues/2
2019-08-14 15:53:58 -07:00
Jeff Epler 076cbcc4f8 cicuitpy_mpconfg.h: Define RUN_BACKGROUND_TASKS
In #2013, @danh says:
    My choice of where to put the semicolon is deliberate,
    so that we can say

        RUN_BACKGROUND_TASKS;

    not have a redundant semicolon, and not confuse C code formatting.
2019-08-11 08:53:02 -05:00
Jeff Epler 568dfc73a9 cicuitpy_mpconfg.h: Alphebetize and standardize indentation
.. no semantic change intended
2019-08-11 08:53:02 -05:00
Jeff Epler 3eb418af39 py: mp_obj_tuple_get: accept any item which can use tuple_getiter
.. such as namedtuple and attrtuple objects.  This is the same
predicate used elsewhere in the file to check for adequate compatibility
between the types.

This was discovered due to crashing `time.time()` on the nrf port.

Closes: #2052
2019-08-10 10:10:41 -05:00
Scott Shawcroft 47a0b7cba1
Merge pull request #2042 from jepler/qstr-expansion
makeqstrdata: permit longer "compressed" outputs
2019-08-06 14:13:48 -07:00
Jeff Epler c4f3a02b3b makeqstrdata: permit longer "compressed" outputs
It is possible for this routine to expand some inputs, and in fact
it does for certan strings in the proposed Korean translation of
CircuitPython (#1858).  I did not determine what the maximum
expansion is -- it's probably modest, like len()/7+2 bytes or
something -- so I tried to just make enc[] an adequate
over-allocation, and then ensured that all the strings in the
proposed ko.po now worked.  The worst actual expansion seems to be a
string that goes from 65 UTF-8-encoded bytes to 68 compressed bytes
(+4.6%).  Only a few out of all strings are reported as
non-compressed.
2019-08-06 07:39:09 -05:00
Dan Halbert 243334da75 Merge remote-tracking branch 'adafruit/master' into ble-pairing 2019-08-05 23:06:24 -04:00
sommersoft 065efb05b7 bring MixerVoice back to building state; update documentation 2019-08-03 11:20:06 -05:00
Dan Halbert 7ce3776b80 WIP: rework of Characteristic properties; enhance Descriptor; not tested 2019-08-02 17:57:31 -04:00
Dan Halbert 91d791afd0 cleanup adapter.address; add uniquish suffix to BLE device name 2019-07-31 00:30:24 -04:00
Jeff Epler b72352949b PWM audio: Rename AudioOut -> PWMAudioOut, _audioio_ -> _audiopwmio_ 2019-07-29 18:39:00 -04:00
Jeff Epler 54cde56ec5 audiopwmio: Add the shared files for this new module 2019-07-26 07:52:37 -05:00
Scott Shawcroft d99d3bd471
Merge pull request #2010 from jepler/audiocore
audiocore: Factor from audioio
2019-07-25 13:52:30 -07:00
Jeff Epler 6b44e40ee8 audiocore: Factor from audioio
When nrf pwm audio is introduced, it will be called `audiopwmio`.  To
enable code sharing with the existing (dac-based) `audioio`, factor
the sample and mixer types to `audiocore`.

INCOMPATIBLE CHANGE: Now, `Mixer`, `RawSample` and `WaveFile` must
be imported from `audiocore`, not `audioio`.
2019-07-25 06:44:26 -05:00
Scott Shawcroft 8ec2d6ce49
Merge pull request #2007 from hierophect/F4xx-port-setup
Add STM32 Discovery F412ZG and F411RE support
2019-07-24 18:49:48 -07:00
Hierophect a63df51893 Requested changes, general cleanup 2019-07-24 14:21:27 -04:00
Scott Shawcroft 6797ec6ed3
Add support for grayscale displays that are < 8 bit depth.
This also improves Palette so it stores the original RGB888 colors.

Lastly, it adds I2CDisplay as a display bus to talk over I2C. Particularly
useful for the SSD1306.

Fixes #1828. Fixes #1956
2019-07-19 16:06:11 -07:00
Dan Halbert 6a001786a9 merge from master 2019-07-09 08:58:49 -04:00
Scott Shawcroft 0cce7fcaa3
Merge remote-tracking branch 'adafruit/4.0.x' into merge_in_402 2019-06-27 14:06:26 -07:00
Scott Shawcroft 2494bfdc86
Validate raw code and mpy read length 2019-06-25 17:54:27 -07:00
Scott Shawcroft 330517bde9
Validate portions of mpy load to detect corruption
Fixes #1917
2019-06-25 15:39:33 -07:00
Dan Halbert 24ac1fdcab WIP: backup only; not compiled 2019-06-19 21:54:28 -04:00
Dan Halbert 35b9191857 Don't operate directly on bleio objects in shared-bindings: use common_hal
routines instead. Changes made but not yet tested.
2019-06-18 23:46:20 -04:00
Dan Halbert bed6d43a76 merge from upstream; WIP redo Address; no more AddressType 2019-06-13 21:55:07 -04:00
Dan Halbert ba1b36a800 Uncomment vm.c SUPEROPT (debugging typo); trim a few builds 2019-06-12 13:09:09 -04:00
Dan Halbert 1bb4fccc3b Turn off SUPEROPT on gc.c instead of trying to squueze inline limit so much; reorganize mpconfigboard.mk files 2019-06-12 11:08:22 -04:00
Dan Halbert aa3316b619 Merge remote-tracking branch 'adafruit/master' into vm-computed-goto 2019-06-11 18:01:04 -04:00
Dan Halbert 4fc189b60c Merge latest 4.0.x fixes into master 2019-06-11 16:16:29 -04:00
Dan Halbert ea760c042b Turn on MICROPY_OPT_COMPUTED_GOTO for 5x CPU-bound speedup 2019-06-11 12:43:48 -04:00
Dan Halbert 62de2506e4 Include display objects in gc. 2019-06-06 17:49:32 -04:00
Elvis Pfützenreuter 1da8d4b4da Add PS/2 support -- ps2io module 2019-06-04 18:05:46 -03:00
Dan Halbert 613e12f99f Replace Broadcaster with enhanced Peripheral 2019-06-03 20:40:05 -04:00
Dan Halbert 4e85c1ef91 Implement forced clean builds for boards so designated.
Mark boards that set CFLAGS_INLINE_LIMIT for particular langauges as needing clean builds.

Fixes #1910.
2019-05-24 15:32:24 -04:00
Scott Shawcroft 63b253c33a
Merge pull request #1906 from adafruit/4.0.x
Merge in all bug fixes from 4.0.1 into master
2019-05-22 15:23:24 -07:00
Dan Halbert da77eedafa Enable MICROPY_PY_BUILTINS_ROUND_INT; make round() work beter when it's disabled as well 2019-05-17 15:56:40 -04:00
Scott Shawcroft b7b55e0c0a
Make Group iterable via a generic native iterator.
Fixes #1694
2019-05-14 15:15:23 -07:00
Scott Shawcroft f29de51325
Check native object in case of early access
If a native displayio object is accessed before it's super().__init__()
has been called, then a placeholder is given that will cause a crash if
accessed. This is tricky to get right so we detect this case and raise
a NotInplementedError instead of crashing.

Fixes #1881
2019-05-13 17:31:30 -07:00
Dan Halbert 8664a6574b use approx of original @godlygeek code for smallints; add tests 2019-05-12 11:17:29 -04:00
Dan Halbert d103ac1d63 Handle truth values; speed up smallint checks 2019-05-12 00:10:53 -04:00
Matt Wozniski 1d0c61642b Reverse int to bytes buffer overflow conditionals
Rather than jumping to a label when an overflow is known to have
occurred, return early when one is known not to have.
2019-05-09 22:03:12 -04:00
Matt Wozniski f325bd848b Use OverflowError exception type for overflows
Initially I used one of the existing exception raise functions, but it's
more correct and not much more code to raise OverflowError instead.
2019-05-09 03:22:26 -04:00
Matt Wozniski 095c844004 Add overflow checks for int to bytes conversions
For both small and long integers, raise an exception if calling
struct.pack, adding an element to an array.array, or formatting an int
with int.to_bytes would overflow the requested size.
2019-05-09 03:22:25 -04:00
Scott Shawcroft 9ce042ad07
Merge pull request #1865 from terriko/mpy_error
Make status light flash blue for incompatible mpy (fixes #1369)
2019-05-08 20:22:59 -04:00
Terri Oda 8d9c2f3e9d Make MpyError a ValueError (since that's what it was before) 2019-05-08 13:58:31 -07:00
Terri Oda a9b05d37d7 Make status light flash blue for incompatible mpy (fixes #1369) 2019-05-08 11:54:08 -07:00
Scott Shawcroft bec84f20ab
Merge pull request #1859 from scottbelden/tabbing
enter four spaces when there are no matches
2019-05-08 14:49:11 -04:00
scottbelden 786cb40073 enter four spaces when there are no matches 2019-05-07 13:55:20 -04:00
Kathryn Lingel eb3cb4d99b Fix tests and clarify first character access 2019-05-07 09:30:55 -07:00
Kathryn Lingel 54aa1ce6de Filter private methods from tab completion 2019-05-06 12:16:29 -07:00
Scott Shawcroft 54ef87c6de
Correct collect of permanent pointers.
The previous implementation managed to keep all but the head
pointer of the list.

Fixes #1814
2019-04-18 15:44:44 -07:00
Scott Shawcroft 713a38d1a2
Merge pull request #1754 from dmazzella/dmazzella-patch-1
add support for USER_C_MODULES
2019-04-17 09:41:20 -07:00
Scott Shawcroft 6132a05fd9
Include cleanup and style tweaks 2019-04-16 10:19:07 -07:00
Scott Shawcroft 0e03a321e4
Fully split gamepadshift from gamepad 2019-04-16 10:11:54 -07:00
Scott Shawcroft c927e6b938
Split GamePadShift from GamePad to save space on most boards. 2019-04-15 15:40:06 -07:00
Radomir Dopieralski 4dc286fa14 Reorganize the gamepad code 2019-04-12 20:43:29 +02:00
Scott Shawcroft debff19126
Check for null local dictionaries 2019-04-10 14:48:27 -07:00
Scott Shawcroft a152ac1cef
Merge remote-tracking branch 'adafruit/master' into pybadge_revd 2019-04-10 10:58:45 -07:00
Scott Shawcroft 5028f87b09
Tweak pybadge and fix display bugs
* Update pybadge pins and flash for rev D
* TileGrid now validates the type of the pixel_shader.
* Display actually handles incoming subclass objects.
* MicroPython will inspect native parents to see if special
  accessors are used.
2019-04-09 18:32:52 -07:00
Scott Shawcroft ee7a77db65
Check that a never free pointer is on the heap.
This fixes a crash on boards with built-in displays which statically
allocate the display bus. When the pointer is provided to never
free, it tries to allocate on the non-existant heap and crashes.
2019-04-09 15:12:28 -07:00
Scott Shawcroft 72992070c5
Fix boards with no shared busses. 2019-04-09 11:36:10 -07:00
Scott Shawcroft 0f003ac5b8
Reorganize board busses into shared-bindings and shared-module. 2019-04-08 16:58:50 -07:00
Damiano Mazzella b6b5eaa878
Update mkrules.mk 2019-04-05 21:41:40 +02:00
Damiano Mazzella a20aab0491
Update obj.h 2019-04-05 21:41:10 +02:00
Damiano Mazzella af38f882ec
Update objmodule.c 2019-04-05 21:40:28 +02:00
Damiano Mazzella 7549326ceb
Update py.mk 2019-04-05 21:39:44 +02:00
Damiano Mazzella d1698230a1
Add files via upload 2019-04-05 21:38:32 +02:00
Dan Halbert c9571fe1ea ROTARYIO_MODULE mistakenly omitted from module list 2019-04-01 17:59:59 -04:00
Dan Halbert 35ab1a1983 Turn on frequencyio only on CIRCUITPY_FULL_BUILD 2019-03-27 16:57:35 -04:00
Dan Halbert 4c1849ae7c turn on reversed() for all builds 2019-03-26 22:15:26 -04:00
Scott Shawcroft 2c93ce5a28
Merge pull request #1672 from dhalbert/regular-fs-flush
flush flash filesystem once a second
2019-03-26 13:47:43 -07:00
Dan Halbert 26262cd477
Merge pull request #1670 from tannewt/fontio
Move Glyph and BuiltinFont into fontio
2019-03-20 17:36:04 -04:00
Dan Halbert fbf166af1a enable MICROPY_CPYTHON_COMPAT for most builds except CIRCUITPY_SMALL_BUILD; remove a few other things to make fit 2019-03-20 14:36:24 -04:00
Dan Halbert 2459eabd66 flush flash filesystem once a second 2019-03-20 12:21:36 -04:00
Scott Shawcroft 5e2fec714c
Move Glyph and BuiltinFont into fontio
It was confusing in displayio.

Fixes #1662
2019-03-19 16:22:09 -07:00
Scott Shawcroft 911509c80c
Fix function signature 2019-03-12 14:05:31 -07:00
Scott Shawcroft 03be42ab84
Enter safe mode when an allocation is attempted on an uninitialized heap. 2019-03-12 11:18:26 -07:00
sommersoft 2cd6a79016 better handle frequencyio inclusion 2019-03-01 22:46:57 -06:00
sommersoft a44bfc2730 Merge branch 'master' of https://github.com/adafruit/circuitpython into new_freq_in 2019-03-01 21:24:30 -06:00
Radomir Dopieralski 89b2788d11 Apply review fixes:
* fix formatting
* fix copyrights
* fix CIRCUITPYTHON_GAMEPAD guards
* add CIRCUITPYTHON_PEW guards to reset
* fix module list order
2019-03-01 16:05:15 +01:00
Radomir Dopieralski 45fea86554 Rebase on top of CircuitPython 4.x 2019-03-01 14:59:21 +01:00
Radomir Dopieralski 88e40193ae Add a _pew module 2019-02-28 23:32:58 +01:00
sommersoft 9d3fcf9a0d add frequencyio to circuipy_ configs 2019-02-24 18:05:51 -06:00
Scott Shawcroft 0261c57d32
Merge pull request #1582 from dhalbert/remove-u-names
rename ure, ujson, and uerrno to re, json, and errno
2019-02-21 13:24:07 -08:00
Dan Halbert 10d3a20f8a Add CIRCUITPY macro; rename u* only when CIRCUITPY=1 2019-02-21 11:09:44 -05:00
Dan Halbert c5dbdbe88c rename ure, ujson, and uerrno to re, json, and errno 2019-02-21 00:33:36 -05:00
Scott Shawcroft 46fd60c703
Prevent infinite display update recursion and fix VFS mounting
Fixes #1529
2019-02-19 14:50:31 -08:00
Dan Halbert 1177c32679
Merge pull request #1562 from debrouxl/minor_improvements_and_fixes
Minor fixes
2019-02-19 13:22:42 -05:00
Dan Halbert 263e9822ea typo 2019-02-18 12:21:31 -05:00
Dan Halbert ba77a9ca80 move non-u names for native modules to circuitpy_mpconfig.h 2019-02-18 12:08:23 -05:00
Dan Halbert 5c884bf6d6 forgot json 2019-02-18 07:57:54 -05:00
Dan Halbert c1144a288f regularize how module weak links and alternate names are listed 2019-02-18 00:45:43 -05:00
Dan Halbert 97aeb1953b correct weak module links; samd module only in m4 ports; update libraries 2019-02-17 23:48:08 -05:00
Dan Halbert 5ec92415b0 fix module weak links; add missing nrf features 2019-02-17 17:29:28 -05:00
Lionel Debroux 94e51de166 Define MP_SSIZE_MAX for LONGINT_IMPL_LONGLONG as well.
Signed-off-by: Lionel Debroux <lionel_debroux@yahoo.fr>
2019-02-17 11:21:35 +01:00
Dan Halbert 619b4f13fd
Merge pull request #1555 from tannewt/print_flush
Support print("", flush=True)
2019-02-15 21:46:16 -05:00
Dan Halbert 7b3f7605b8 address @tannewt changes: move and rename common files; remove PORT_HEAP_SIZE 2019-02-15 20:32:32 -05:00
Scott Shawcroft e6b140e7a0
Support print("", flush=True)
Fixes #1127
2019-02-15 16:53:19 -08:00
Noralf Trønnes 0865c9d381 extmod/ure: Support search/match() pos and endpos parameters
MICROPY_PY_URE_MATCH_SPAN_START_END is used to enable the functionality
since it's similar.
2019-02-14 15:42:28 +01:00
Damien George b9dc23c070 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.
2019-02-14 15:42:22 +01:00
Damien George cbeac094ef 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.
2019-02-14 15:42:21 +01:00
Damien George a24fabbb6f 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.
2019-02-14 15:42:19 +01:00
Scott Shawcroft c17f147be9
A variety of displayio improvements
This changes a number of things in displayio:
* Introduces BuiltinFont and Glyph so the built in font can be used by libraries. For boards with
  a font it is available as board.TERMINAL_FONT. Fixes #1172
* Remove _load_row from Bitmap in favor of bitmap[] access. Index can be x/y tuple or overall index. Fixes #1191
* Add width and height properties to Bitmap.
* Add insert and [] access to Group. Fixes #1518
* Add index param to pop on Group.
* Terminal no longer takes unicode character info. It takes a BuiltinFont instead.
* Fix Terminal's handling of [###D vt100 commands used when up arrowing into repl history.
* Add x and y positions to Group plus scale as well.
* Add bitmap accessor for BuiltinFont
2019-02-11 20:55:05 -08:00
Craig Forbes 1662e02c1b Add human readable text for ENOSPC. 2019-02-06 14:59:01 -06:00
Scott Shawcroft 0c50154c83
Use generic overflow so 64 bit is handled ok. 2019-02-04 16:11:16 -08:00
Scott Shawcroft c60f77d5ab
Check sequence multiply for length overflow
Fixes #1279
2019-02-04 15:33:36 -08:00
Scott Shawcroft 5555a24479
Never long live the main dictionary.
It's contents change often and may be referenced elsewhere.

Fixes #1443
2019-02-01 16:05:37 -08:00
Scott Shawcroft a39fc94dde
Don't long live class attributes
When they are added later, they are also referenced in the main
dictionary.

Fixes #1218
2019-02-01 16:04:16 -08:00
Damien George 3e25d611ef all: Bump version to 1.10. 2019-01-26 00:56:48 +11:00
Damien George aba83e66d7 py/mpconfig.h: Remove parentheses from MICROPY_VERSION_xxx macros.
Otherwise MICROPY_VERSION_STRING includes these parentheses in the string.
2019-01-26 00:44:35 +11:00
Damien George 5089b3ffb6 py/obj.h: Explicitly cast args to uint32_t in MP_OBJ_FUN_MAKE_SIG.
For architectures where size_t is less than 32 bits (eg 16 bits) the args
must be casted to uint32_t so the left shift will work.  For architectures
where size_t is greater than 32 bits (eg 64 bits) this new casting will not
lose any bits because the end result must anyway fit in a uint32_t.
2019-01-25 16:03:05 +11:00
Dan Halbert e170e03f8c Merge remote-tracking branch 'adafruit/master' into bleio2 2019-01-21 20:38:26 -05:00
Dan Halbert a8f4aa4796 Merge remote-tracking branch 'adafruit/master' into struct-compat 2019-01-20 21:47:13 -05:00
Scott Shawcroft 479b286600
Fix dict_make_new 2019-01-20 17:32:43 -08:00
Scott Shawcroft 5ddc50473a
Check for null kw_args 2019-01-20 16:18:34 -08:00
Dan Halbert 7a09af73ec Improve struct compatibility with CPython 2019-01-20 15:12:34 -05:00
Dan Halbert 62df7ab730 Improve struct compatibility with CPython 2019-01-20 15:10:09 -05:00
Dan Halbert 28cfd8a513 CharacteristicBuffer: make it be a stream class; add locking 2019-01-19 19:45:35 -05:00
Scott Shawcroft b569e8bab0
More make_new updates 2019-01-18 17:09:56 -08:00
Scott Shawcroft 0318a9a9bc
More make_new fixes for unix build 2019-01-18 11:53:09 -08:00
Scott Shawcroft c271754962
fixup micropy 2019-01-14 18:09:02 -08:00
Scott Shawcroft 12c8b00556
Don't build machine class we don't use. 2019-01-14 17:30:01 -08:00
Scott Shawcroft 72d993d60c
py changes for supporting superclass constructors that take kwargs 2019-01-14 17:29:19 -08:00
Damien George 529dcce2be py/modio: Make iobase_singleton object const so it goes in ROM. 2019-01-10 23:08:07 +11:00
Damien George afecc124e6 py: Fix location of VM returned exception in invalid opcode and comments
The location for a returned exception was changed to state[0] in
d95947b48a
2019-01-04 17:22:40 +11:00
Damien George 6d19934463 py: Get optional VM stack overflow check compiling and working again.
Changes to the layout of the bytecode header meant that this debug code was
no longer compiling.  This is now fixed and a new compile-time option is
introduced, MICROPY_DEBUG_VM_STACK_OVERFLOW, to turn on this feature (which
is disabled by default).  This option is needed because more than one file
needs to cooperate to make this check work.
2019-01-04 17:09:41 +11:00
Dan Halbert 1dc3957e72 LocalPeripheral is now Peripheral; more work on basic GATTS support; UART not working yet 2018-12-30 22:33:49 -05:00
Dan Halbert 4167bf5b24 wip: advertising works, but not connection 2018-12-27 00:04:04 -05:00
Damien George fa50047bbc py/runtime: Unlock the GIL in mp_deinit function.
This mirrors what is done in mp_init.  Some RTOSs require this symmetry to
get back to a clean state (when doing a soft reset, for example).
2018-12-27 14:20:31 +11:00
Damien George 7cd59c5bc3 py/mpconfig: Move MICROPY_VERSION macros to static ones in mpconfig.h.
It's more robust to have the version defined statically in a header file,
rather than dynamically generating it via git using a git tag.  In case
git doesn't exist, or a different source control tool is used, it's
important to still have the uPy version number available.
2018-12-22 01:40:38 +11:00
Paul Sokolovsky 5ed578e5b4 py/gc: Adjust gc_alloc() signature to be able to accept multiple flags.
The older "bool has_finaliser" gets recast as GC_ALLOC_FLAG_HAS_FINALISER=1
so this is a backwards compatible change to the signature.  Since bool gets
implicitly converted to 1 this patch doesn't include conversion of all
calls.
2018-12-20 17:52:16 +11:00
Paul Sokolovsky a261d8b615 py/objarray: Introduce "memview_offset" alias for "free" field of object
Both mp_type_array and mp_type_memoryview use the same object structure,
mp_obj_array_t, but for the case of memoryview, some fields, e.g. "free",
have different meaning.  As the "free" field is also a bitfield, assume
that (anonymous) union can't be used here (for the concerns of possible
compatibility issues with wide array of toolchains), and just add a field
alias using a #define.  As it's a define, it should be a selective
identifier, so use verbose "memview_offset" to avoid any clashes.
2018-12-20 17:40:48 +11:00
Damien George 0d165fec9c py/qstr: Put a lower bound on new qstr pool allocation. 2018-12-15 14:32:09 +11:00
Dan Halbert bfa66861ef Merge remote-tracking branch 'adafruit/master' into bleio-rev 2018-12-13 16:33:15 -05:00
Damien George 6bf8ecfe3a py/bc: Fix calculation of opcode size for opcodes with map caching.
All 4 opcodes that can have caching bytes also have qstrs, so the test for
them must go in the qstr part of the code.  The reason this incorrect
calculation of the opcode size did not lead to a bug is because the caching
byte is at the end of the opcode (byte, qstr, qstr, cache) and is always
0x00 when saving/loading, so was just treated as a single byte no-op
opcode.  Hence these opcodes were being saved/loaded/decoded correctly.

Thanks to @malinah for finding the problem and providing the initial patch.
2018-12-13 01:26:55 +11:00
Paul Sokolovsky fbb8335084 py/objdict: Make .fromkeys() method configurable.
On by default, turned off for minimal/bare-arm. Saves 144 bytes on x86.
2018-12-13 01:20:55 +11:00
Damien George 55830dd9bf py/objexcept: Make sure mp_obj_new_exception_msg doesn't copy/format msg
mp_obj_new_exception_msg() assumes that the message passed to it is in ROM
and so can use its data directly to create the string object for the
argument of the exception, saving RAM.  At the same time, this approach
also makes sure that there is no attempt to format the message with printf,
which could lead to faults if the message contained % characters.

Fixes issue #3004.
2018-12-10 16:01:05 +11:00
Damien George bad4e15da5 py/objexcept: Use macros to make offsets in emergency exc buf clearer. 2018-12-10 15:53:38 +11:00
Paul Sokolovsky 38151f35c1 extmod/moductypes: Add aliases for native C types.
SHORT, INT, LONG, LONGLONG, and unsigned (U*) variants are being defined.
This is done at compile using GCC-style predefined macros like
__SIZEOF_INT__.  If the compiler doesn't have such defines, no such types
will be defined.
2018-12-10 14:40:43 +11:00
Paul Sokolovsky b1d08726ee py/obj: Add support for __int__ special method.
Based on the discussion, this special method is available unconditionally,
as converting to int is a common operation.
2018-12-07 17:28:04 +11:00
Scott Shawcroft 6ef8639971
Rework safe mode and have heap overwrite trigger it.
This creates a common safe mode mechanic that ports can share.
As a result, the nRF52 now has safe mode support as well.

The common safe mode adds a 700ms delay at startup where a reset
during that window will cause a reset into safe mode. This window
is designated by a yellow status pixel and flashing the single led
three times.

A couple NeoPixel fixes are included for the nRF52 as well.

Fixes #1034. Fixes #990. Fixes #615.
2018-12-06 14:24:20 -08:00
Dan Halbert 125901e4e2 Merge remote-tracking branch 'adafruit/master' into bleio-rev 2018-12-06 12:41:38 -05: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
Scott Shawcroft 7ad2e6ace3
Add stack validity check and raise an error when it happens.
The backtrace cannot be given because it relies on the validity
of the qstr data structures on the heap which may have been
corrupted.

In fact, it still can crash hard when the bytecode itself is
overwritten. To fix, we'd need a way to skip gathering the
backtrace completely.

This also increases the default stack size on M4s so it can
accomodate the stack needed by ASF4s nvm API.
2018-12-04 23:26:04 -08:00
Ayke van Laethem 31cf528c75 py: Add option to reduce GC stack integer size to save RAM.
A new option MICROPY_GC_STACK_ENTRY_TYPE is added to select a custom type
instead of size_t for the gc_stack array items.  This can be beneficial for
small devices, especially those that are low on memory anyway.  If a device
has 1MB or less of heap (and 16-byte GC blocks) then this type can be
uint16_t, saving 128 bytes of RAM.
2018-12-04 17:17:25 +11:00
Dan Halbert 80db2cec99 UART changes: timeout in secs, write bytes, etc. 2018-12-03 12:04:32 -05:00
Craig Younkins 7f948a5645 py/py.mk: Fix broken Gmane URL. 2018-12-04 01:03:44 +11:00
Scott Shawcroft 9d07e95351
Add support for adding release info into adafruit/circuitpython-org
This also changes the build script to python with better output.
2018-11-30 00:30:57 -08:00
Damien George 7c85c7c210 py/unicode: Fix check for valid utf8 being stricter about contn chars. 2018-11-26 16:13:08 +11:00
Dan Halbert 1763ffe245 More UUID work; use mp_raise for exceptions 2018-11-20 23:04:58 -05:00
Noralf Trønnes c5aa2e9300 Support OSError attributes
This adds support for the OSError attributes : errno, strerror, filename and filename2.
CPython only sets errno if 2 arguments has been passed in. This has not been implemented here.

CPython OSError.args is capped at 2 items for backward compatibility reasons. This has not been
implemented here.

MICROPY_CPYTHON_COMPAT has to be enabled to get these attributes.

mp_common_errno_to_str() has been extended to check mp_errno_to_str() as well. This is done to ease
reuse for the strerror argument.
2018-11-13 22:04:44 +01:00
Scott Shawcroft 355abc835e
Fix output overflow and make help translatable 2018-11-09 16:41:08 -08:00
Scott Shawcroft 168e23e466
Build refinement to handle warnings and quiet output 2018-11-09 00:11:43 -08:00
Paul Sokolovsky 5c18730f28 py/runtime: Fix qstr assumptions when handling "import *".
There was an assumption that all names in a module dict are qstr's.
However, they can be dynamically generated (by assigning to globals()),
and in case of a long name, it won't be a qstr. Handle this situation
properly, including taking care of not creating superfluous qstr's for
names starting with "_" (which aren't imported by "import *").
2018-11-01 13:33:16 +11:00
Damien George e328a5d469 py/scope: Optimise scope_find_or_add_id to not need "added" arg.
Taking the address of a local variable is mildly expensive, in code size
and stack usage.  So optimise scope_find_or_add_id() to not need to take a
pointer to the "added" variable, and instead take the kind to use for newly
added identifiers.
2018-10-28 00:38:18 +11:00
Damien George ba92c79841 py/compile: Remove unneeded variable from global/nonlocal stmt helpers. 2018-10-28 00:38:18 +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 746dbf78d3 py/py.mk: When building axtls use -Wno-all to prevent all warnings.
Building axtls gives a lot of warnings with -Wall enabled, and explicitly
disabling all of them cannot be done in a way compatible with gcc and
clang, and likely other compilers.  So just use -Wno-all to prevent all of
the extra warnings (in addition to the necessary -Wno-unused-parameter,
-Wno-uninitialized, -Wno-sign-compare and -Wno-old-style-definition).

Fixes issue #4182.
2018-10-27 23:53:08 +11:00
Scott Shawcroft dc9d338612
Merge pull request #1167 from notro/cpython_stdlib
Support CPython standard library
2018-10-24 12:57:41 -07: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 5a91fce9f8 py/objstr: Make str.count() method configurable.
Configurable via MICROPY_PY_BUILTINS_STR_COUNT.  Default is enabled.
Disabled for bare-arm, minimal, unix-minimal and zephyr ports.  Disabling
it saves 408 bytes on x86.
2018-10-22 22:49:05 +11:00
Scott Shawcroft cb0126131a
Use python3 for mpy-tool 2018-10-18 10:37:42 -07: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
Scott Shawcroft 4f9c8b7361
Add debug info to the generated frozen_mpy.c
It adds size info and uses macros for byte code to make it more
readable.
2018-10-17 17:45:47 -07:00
Damien George de71035e02 py/emitnative: Put None/False/True in global native const table.
So these constant objects can be loaded by dereferencing the REG_FUN_TABLE
pointer instead of loading immediate values.  This reduces the size of
generated native code (when such constants are used), and means that
pointers to these constants are no longer stored in the assembly code.
2018-10-15 00:20:49 +11:00
Damien George 6c6050ca43 py/emitnative: Push internal None rather than const obj where possible.
This shifts the work of loading the constant None object on to
load_reg_stack_imm(), making the handling of None more centralised.
2018-10-15 00:20:49 +11:00
Damien George 7c16bc0406 py/emitnative: Simplify viper mode handling in emit_native_import_name. 2018-10-15 00:20:49 +11:00
Damien George 175739cd37 py/emitnative: Consolidate use of stacked immediate values to one func.
This commit adds the helper function load_reg_stack_imm() which deals with
constant immediate values and converting them to Python objects if needed.
2018-10-15 00:20:49 +11:00
Damien George 6bda951d4d py/emitnative: Remove unused ptr argument from ASM_CALL_IND macro. 2018-10-13 15:16:33 +11:00
Damien George 25571800fc py/asmthumb: Remove unused fun_ptr arg from asm_thumb_bl_ind function. 2018-10-13 15:16:33 +11:00
Damien George 5f1dd5b86b py/asmarm: Simplify asm_arm_bl_ind to only load via index, not literal.
The maximum index into mp_fun_table is currently less than 1024 and should
stay that way to keep things efficient for all architectures, so there is
no need to handle loading the pointer directly via a literal in this
function.
2018-10-13 15:16:33 +11:00
Damien George 006671056d py/emitnative: Load native fun table ptr from const table for all archs.
All architectures now have a dedicated register to hold the pointer to the
native function table mp_fun_table, and so they all need to load this
register at the start of the native function.  This commit makes the
loading of this register uniform across architectures by passing the
pointer in the constant table for the native function, and then loading the
register from the constant table.  Doing it this way means that the pointer
is not stored in the assembly code, helping to make the code more portable.
2018-10-13 15:16:33 +11:00
Damien George 355eb8eafb py/asmx86: Change indirect calls to load fun ptr from the native table.
Instead of storing the function pointer directly in the assembly code.
This makes the generated code more independent of the runtime (so easier to
relocate the code), and reduces the generated code size.
2018-10-13 15:16:33 +11:00
Damien George b7c6f859d0 py/asmx86: Change stack management to reference locals by esp not ebp.
The esp register is always a fixed distance below ebp, and using esp to
reference locals on the stack frees up the ebp register for general purpose
use (which is important for an architecture with only 8 user registers).
2018-10-13 15:16:33 +11:00
Damien George 8e4b4bac70 py/asmx64: Change indirect calls to load fun ptr from the native table.
Instead of storing the function pointer directly in the assembly code.
This makes the generated code more independent of the runtime (so easier to
relocate the code), and reduces the generated code size.
2018-10-13 15:16:33 +11:00
Damien George 8941c63290 py/asmx64: Change stack management to reference locals by rsp not rbp.
The rsp register is always a fixed distance below rbp, and using rsp to
reference locals on the stack frees up the rbp register for general purpose
use.
2018-10-13 15:16:33 +11:00
Noralf Trønnes db4a8f5d1a modsys: exc_info: Add traceback
Add traceback chain to sys.exec_info()[2].
No actual frame info is added, but just enough to recreate the printed
exception traceback.

Used by the unittest module which collects errors and failures and prints
them at the end.
2018-10-07 19:37:49 +02:00
Noralf Trønnes b897603cfa py/objboundmeth: Support __func__ property as in CPython
This gives access to the function underlying the bound method.

Used in the converted CPython stdlib logging.Formatter class to handle
overrriding a default converter method bound to a class variable.
The method becomes bound when accessed from an instance of that class.

I didn't investigate why CircuitPython turns it into a bound method.
2018-10-07 19:36:24 +02:00
Noralf Trønnes a63555abc1 py/builtinimport: Set __file__ on MPY modules
This sets the __file__ property on MPY modules like how it's done on pure python modules.
2018-10-07 19:36:12 +02:00
Uri Shaked cea079a022
fix compilation errors in emitinlinethumb.c 2018-10-07 02:09:44 +03:00
Damien George 34af10d2ef py/emitnative: Clean up unused macro and forward function declarations. 2018-10-02 15:01:56 +10:00
Damien George 69e7903904 py/obj.h: Use uint64_t instead of mp_int_t in repr-D MP_OBJ_IS_x macros.
This follows how it's already done in MP_OBJ_IS_OBJ: the objects are
considered 64-bit unsigned ints for the purpose of bitwise manipulation.
2018-10-01 16:36:46 +10:00
Damien George a9237cee82 py/runtime: Remove comment in mp_import_name about level being 0.
A non-zero level has been supported for some time now.
2018-10-01 15:35:10 +10:00
Damien George 4ab397576f py/runtime: Use mp_import_name to implement tail of mp_import_from. 2018-10-01 15:22:03 +10:00
Damien George cc2bd63c57 py/emitnative: Implement yield and yield-from in native emitter.
This commit adds first class support for yield and yield-from in the native
emitter, including send and throw support, and yields enclosed in exception
handlers (which requires pulling down the NLR stack before yielding, then
rebuilding it when resuming).

This has been fully tested and is working on unix x86 and x86-64, and
stm32.  Also basic tests have been done with the esp8266 port.  Performance
of existing native code is unchanged.
2018-10-01 13:31:11 +10:00
Damien George 8fec6f5434 py/emitnative: Reorder native state on C stack so nlr_buf_t is first.
The nlr_buf_t doesn't need to be part of the Python value stack (as it was
before this commit), it's simpler to have it separated as auxiliary state
that lives on the C stack.  This will help adding yield support because in
that case the nlr_buf_t and Python value stack live in separate memory
areas (C stack and heap respectively).
2018-10-01 12:36:21 +10:00
Damien George 4fc437f1ef py/asmxtensa: Use proper calculation for const table offset.
Instead of hard-coding it to 4 bytes.  This allows for there to be other
data stored at the very start of the emitted native code.
2018-10-01 12:34:58 +10:00
Damien George 5b19916d6e py/asmx64: Extend asm_x64_mov_reg_pcrel to accept high registers. 2018-10-01 12:34:36 +10:00
Damien George 1dc720dc01 py/asmx86: Comment out unused asm_x86_nop to prevent compiler warnings. 2018-10-01 12:34:23 +10:00
Damien George 87231132d4 py/asmthumb: Extend asm entry/exit to handle stack larger than 508 bytes 2018-09-30 23:31:17 +10:00
Damien George ef9394e76a py/asmthumb: Clean up asm_thumb_bl_ind to use new optimised ldr helper. 2018-09-30 23:30:18 +10:00
Damien George 07ccb192c5 py/asmthumb: Add wide ldr to handle larger offsets.
In particular this allows native functions on Thumb2 to index more than 32
constants in the constant table.
2018-09-30 23:27:01 +10:00
Damien George d95947b48a py/vm: When VM raises exception put exc obj at beginning of func state.
Instead of at end of state, n_state - 1.  It was originally (way back in
v1.0) put at the end of the state because the VM didn't have a pointer to
the start.  But now that the VM takes a mp_code_state_t pointer it does
have a pointer to the start of the state so can put the exception object
there.

This commit saves about 30 bytes of code on all architectures, and, more
importantly, reduces C-stack usage by a couple of words (8 bytes on Thumb2
and 16 bytes on x86-64) for every (non-generator) call of a bytecode
function because fun_bc_call no longer needs to remember the n_state
variable.
2018-09-29 23:25:08 +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 2eb0170157 py/objtype: Remove TODO about storing attributes to classes.
This behaviour is tested in basics/class_store.py and follows CPython.
2018-09-28 23:15:12 +10:00
Damien George 2c7a3061d5 py/runtime: Remove nlr protection when calling __next__ in mp_resume.
And remove related comment about needing such protection when calling send.

Reasoning for removal is as follows:
- mp_resume is only called by the VM in YIELD_FROM opcode
- if send_value != MP_OBJ_NULL then throw_value == MP_OBJ_NULL
- so if __next__ or send are called then throw_value == MP_OBJ_NULL
- if __next__ or send raise an exception without nlr protection then the
  exception will be handled by the global exception handler of the VM
- this handler already has code to handle exceptions raised in YIELD_FROM,
  including correct handling of StopIteration
- this handler doesn't handle the case of injection of GeneratorExit, but
  this won't be needed because throw_value == MP_OBJ_NULL

Note that it's already possible for mp_resume() to raise an exception
(including StopIteration) from the unprotected call to type->iternext(), so
that's why the VM already has code to handle the case of exceptions coming
out of mp_resume().

This commit reduces code size by a bit, and significantly reduces C stack
usage when using yield-from, from 88 bytes down to 40 for Thumb2, and 152
down to 72 bytes for x86-64 (better than half).  (Note that gcc doesn't
seem to tail-call optimise the call from mp_resume() to mp_obj_gen_resume()
so this saving in C stack usage helps all uses of yield-from.)
2018-09-28 22:16:56 +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 e9012a20f7 py/emitnative: Change type of const_table from uintptr_t to mp_uint_t.
This matches how bytecode does it, and matches the signature of
mp_emit_glue_assign_native.  Since the native emitter doesn't support
nan-boxing uintptr_t and mp_uint_t are anyway the same bit-width.
2018-09-28 00:04:10 +10:00
Damien George 2e86233263 py/asm*: Remove ASM_MOV_REG_ALIGNED_IMM emit macro, it's no longer used.
After the previous commit this macro is no longer needed by the native
emitter because live heap pointers are no longer stored in generated native
machine code.
2018-09-27 23:39:08 +10:00
Damien George 7d4b6cc868 py/emitnative: Place const objs for native code in separate const table.
This commit changes native code to handle constant objects like bytecode:
instead of storing the pointers inside the native code they are now stored
in a separate constant table (such pointers include objects like bignum,
bytes, and raw code for nested functions).  This removes the need for the
GC to scan native code for root pointers, and takes a step towards making
native code independent of the runtime (eg so it can be compiled offline by
mpy-cross).

Note that the changes to the struct scope_t did not increase its size: on a
32-bit architecture it is still 48 bytes, and on a 64-bit architecture it
decreased from 80 to 72 bytes.
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
Damien George 6d20be31ae py/vm: Reword TODO about invalid ip/sp after an exception to a note. 2018-09-27 15:17:37 +10:00
Damien George 04f7da78db py/objmodule: Remove TODO about checking store attr to a module.
The code implements correct behaviour, as tested by basics/module1.py.
2018-09-27 15:16:24 +10:00
Damien George cc5c3c64ca py/objint: Remove TODO about checking of int() arg types with 2 args.
The arguments are checked by mp_obj_str_get_data and mp_obj_get_int.
2018-09-27 15:15:29 +10:00
Damien George 814f17a3a4 py/objdict: Reword TODO about inlining mp_obj_dict_get to a note. 2018-09-27 15:14:12 +10:00
Damien George baa83a0c6d py/objslice: Remove long-obsolete comment about enhancing slice object.
Commit afaaf535e6 made this comment obsolete.
2018-09-27 11:23:31 +10:00
Damien George 76355c8863 py/vm: Make small optimisation of BUILD_SLICE opcode.
No need to call DECODE_UINT since the value will always be either 2 or 3.
2018-09-27 11:22:33 +10:00
stijn 57a7d5be9a py: Fix msvc C++ compiler warnings with MP_OBJ_FUN_MAKE_SIG macro.
When obj.h is compiled as C++ code, the cl compiler emits a warning about
possibly unsafe mixing of size_t and bool types in the or operation in
MP_OBJ_FUN_MAKE_SIG.  Similarly there's an implicit narrowing integer
conversion in runtime.h.  This commit fixes this by being explicit.
2018-09-26 15:34:59 +10:00
Paul Sokolovsky a135bca4a1 py/objstr: format: Return bytes result for bytes format string.
This is an improvement over previous behavior when str was returned for
both str and bytes input format.  This new behaviour is also consistent
with how the % operator works, as well as many other str/bytes methods.

It should be noted that it's not how current versions of CPython work,
where there's a gap in the functionality and bytes.format() is not
supported.
2018-09-26 15:29:41 +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
Romain Goyet b768cc6ca8 py/parsenum: Avoid rounding errors with negative powers-of-10.
This patches avoids multiplying with negative powers-of-10 when parsing
floating-point values, when those powers-of-10 can be exactly represented
as a positive power.  When represented as a positive power and used to
divide, the resulting float will not have any rounding errors.

The issue is that mp_parse_num_decimal will sometimes not give the closest
floating representation of the input string.  Eg for "0.3", which can't be
represented exactly in floating point, mp_parse_num_decimal gives a
slightly high (by 1LSB) result.  This is because it computes the answer as
3 * 0.1, and since 0.1 also can't be represented exactly, multiplying by 3
multiplies up the rounding error in the 0.1.  Computing it as 3 / 10, as
now done by the change in this commit, gives an answer which is as close to
the true value of "0.3" as possible.
2018-09-20 22:06:41 +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
Paul Sokolovsky 93f29975db py/modbuiltins: Make oct/hex work when !MICROPY_PY_BUILTINS_STR_OP_MODULO
Instead of redirecting to str.__mod__(), use str.format() in this case.
2018-09-20 14:41:35 +10:00
Paul Sokolovsky 2da5d41350 py/objstr: Make % (__mod__) formatting operator configurable.
Default is enabled, disabled for minimal builds. Saves 1296 bytes on x86,
976 bytes on ARM.
2018-09-20 14:41:08 +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 0a36a80f96 py/objtype: Clarify comment about configuring inplace op methods.
In 0e80f345f8 the inplace operations __iadd__
and __isub__ were made unconditionally available, so the comment about this
section is changed to reflect that.
2018-09-20 11:42:56 +10:00
Damien George 7e3dd9f8a3 py/asmthumb: Detect presence of I-cache using CMSIS macro.
Fixes issue #4113.
2018-09-16 01:50:45 +10:00
Damien George 30a45360e7 py/asmxtensa: Make indirect calls using func table, not raw pointers.
Loading a pointer by indexing into the native function table mp_fun_table,
rather than loading an immediate value (via a PC-relative load), uses less
code space.
2018-09-16 00:43:24 +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 f12e039c2b py/emitnative: Use macros instead of raw offsetof for slot locations.
Old globals are now stored in the second slot (ip in mp_code_state_t) to
make things simpler for viper.
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 43f1848bfa py: Make viper functions have the same entry signature as native.
This commit makes viper functions have the same signature as native
functions, at the level of the emitter/assembler.  This means that viper
functions can now be wrapped in the same uPy object as native functions.

Viper functions are now responsible for parsing their arguments (before it
was done by the runtime), and this makes calling them more efficient (in
most cases) because the viper entry code can be custom generated to suit
the signature of the function.

This change also opens the way forward for viper functions to take
arbitrary numbers of arguments, and for them to handle globals correctly,
among other things.
2018-09-15 22:39:27 +10:00
Damien George 460954734e py/emitnative: Reuse mp_native_type_from_qstr when searching for a cast. 2018-09-15 13:52:58 +10:00
Damien George 9f2067288a py/compile: Factor code that compiles viper type annotations. 2018-09-15 13:44:39 +10:00
Damien George a169a5848c py/compile: Merge viper annotation and normal param compilation stages.
Now that the compiler can store the results of the viper types in the
scope, the viper parameter annotation compilation stage can be merged with
the normal parameter compilation stage.
2018-09-15 13:20:54 +10:00
Damien George 80db30a510 py/emit: Completely remove set_native_type, arg type is set in compiler.
In viper mode, the type of the argument is now stored in id_info->flags.
2018-09-15 13:00:11 +10:00
Damien George 07caf4f969 py/emit: Remove need to call set_native_type to set viper return type.
Instead this return type is now stored in the scope_flags.
2018-09-15 12:41:25 +10:00
Damien George 1d7c221b30 py/emit: Remove need to call set_native_type to set native/viper mode.
The native emitter can easily determine the mode via scope->emit_options.
2018-09-15 12:17:14 +10:00
Damien George 3751512e9d py/emit: Move MP_EMIT_OPT_xxx enums from compile.h to emitglue.h. 2018-09-15 12:17:09 +10:00
Damien George abb536da49 py/{asmx86,asmx64}: Extend test_r8_with_r8 to accept all 8 lower regs. 2018-09-14 17:38:09 +10:00
Damien George dd522d63b6 py/asmx64: Fix bug in assembler when creating disp with r13 and 0 offset 2018-09-14 17:36:09 +10:00
Damien George 9f241ef398 py: Optimise call to mp_arg_check_num by compressing fun signature.
With 5 arguments to mp_arg_check_num(), some architectures need to pass
values on the stack.  So compressing n_args_min, n_args_max, takes_kw into
a single word and passing only 3 arguments makes the call more efficient,
because almost all calls to this function pass in constant values.  Code
size is also reduced by a decent amount:

   bare-arm:  -116
minimal x86:   -64
   unix x64:  -256
unix nanbox:  -112
      stm32:  -324
     cc3200:  -192
    esp8266:  -192
      esp32:  -144
2018-09-14 13:39:17 +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 5fe3730a30 extmod/moduhashlib: Add md5 implementation, using axTLS.
MD5 is still widely used, and may be important in some cases for networking
interoperability, e.g. HTTP Digest authentication.
2018-09-11 14:51:52 +10:00
stijn 89516b2b62 py/runtime: Fix incorrect test for MICROPY_PORT_DEINIT_FUNC. 2018-09-11 00:38:31 +10:00
Damien George 0be2ea50e9 py/py.mk: Build axtls library directly from its source files.
This removes the need for a separate axtls build stage, and builds all
axtls object files along with other code.  This simplifies and cleans up
the build process, automatically builds axtls when needed, and puts the
axtls object files in the correct $(BUILD) location.

The MicroPython axtls configuration file is provided in
extmod/axtls-include/config.h
2018-09-08 00:07:23 +10:00
Damien George 8014e7f15f py/compile: Factor code that compiles start/end of exception handler. 2018-09-04 16:06:22 +10:00
Damien George 4ae7111573 py/emitnative: Add support for return/break/continue in try and with.
This patch adds full support for unwinding jumps to the native emitter.
This means that return/break/continue can be used in try-except,
try-finally and with statements.  For code that doesn't use unwinding jumps
there is almost no overhead added to the generated code.
2018-09-04 14:31:28 +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
Noralf Trønnes 2d1fecc804 Revert "py/vm: Improve performance of opcode dispatch when using switch stmt."
This reverts commit 869024dd6e.

Ctrl-C stopped producing KeyboardInterrupt with this change on CircuitPython.

The Unix and stm32 ports handles Ctrl-C differently with a handler which is
probably why they where not affected.

Fixes #1092
2018-08-25 13:14:58 +02:00
Scott Shawcroft 4a4d84ba42
Merge pull request #1064 from notro/i2cslave
Add busio.I2CSlave
2018-08-17 16:51:45 -07:00
Damien George 4f9842ad80 py/emitnx86: Fix number of args passed to mp_setup_code_state, 4 not 5. 2018-08-17 15:03:51 +10:00
Damien George 794c32102e py/asmxtensa: Use narrow version of add instr to reduce native code size 2018-08-17 14:53:58 +10:00
Damien George a0a29724c8 py/emitnative: Fix bug with store of 16 and 32 values in viper ARM mode. 2018-08-17 14:11:37 +10:00
Damien George 1ad44acb15 py/asmxtensa: Optimise loading local addr and support larger offsets. 2018-08-17 14:11:37 +10:00
Damien George fd10a11c6b py/asmxtensa: Fix bug with order of regs in addi encoding. 2018-08-17 14:11:37 +10:00
Scott Shawcroft c3c5951d44
Fix test that broke due to decompressing to too small of a scope. 2018-08-16 17:41:53 -07:00
Scott Shawcroft 2cd166b573
Fix esp and samd 2018-08-16 17:41:35 -07:00
Scott Shawcroft 137a30ad75
fix mpy-cross 2018-08-16 17:40:57 -07:00
Scott Shawcroft de5a9d72dc
Compress all translated strings with Huffman coding.
This saves code space in builds which use link-time optimization.
The optimization drops the untranslated strings and replaces them
with a compressed_string_t struct. It can then be decompressed to
a c string.

Builds without LTO work as well but include both untranslated
strings and compressed strings.

This work could be expanded to include QSTRs and loaded strings if
a compress method is added to C. Its tracked in #531.
2018-08-16 17:40:57 -07:00
Noralf Trønnes 1ed0e45fc2 Add i2cslave.I2CSlave bindings 2018-08-16 17:11:20 +02:00
Damien George a3de776486 py/emitnative: Optimise and improve exception handling in native code.
Prior to this patch, native code would use a full nlr_buf_t for each
exception handler (try-except, try-finally, with).  For nested exception
handlers this would use a lot of C stack and be rather inefficient.

This patch changes how exceptions are handled in native code by setting up
only a single nlr_buf_t context for the entire function, and then manages a
state machine (using the PC) to work out which exception handler to run
when an exception is raised by an nlr_jump.  This keeps the C stack usage
at a constant level regardless of the depth of Python exception blocks.

The patch also fixes an existing bug when local variables are written to
within an exception handler, then their value was incorrectly restored if
an exception was raised (since the nlr_jump would restore register values,
back to the point of the nlr_push).

And it also gets nested try-finally+with working with the viper emitter.

Broadly speaking, efficiency of executing native code that doesn't use
any exception blocks is unchanged, and emitted code size is only slightly
increased for such function.  C stack usage of all native functions is
either equal or less than before.  Emitted code size for native functions
that use exception blocks is increased by roughly 10% (due in part to
fixing of above-mentioned bugs).

But, most importantly, this patch allows to implement more Python features
in native code, like unwind jumps and yielding from within nested exception
blocks.
2018-08-16 13:56:36 +10:00
Damien George 2964b41c28 py/asm*: Support assembling code to jump to a register, and get PC+off.
Useful for position independent code, and implementing state machines.
2018-08-16 13:45:24 +10:00
Damien George f7d6108d1a py/asmxtensa: Handle function entry/exit when stack use larger than 127. 2018-08-16 13:43:36 +10:00
Damien George 8c49995398 py/emitnative: Use small tables to simplify handling of local regs. 2018-08-15 10:55:11 +10:00
Damien George b8b2525576 extmod/modbtree: Update to work with new mp_stream_posix_XXX signatures. 2018-08-14 17:41:23 +10:00
Damien George 9ab816d676 py/stream: Adjust mp_stream_posix_XXX to take void*, not mp_obj_t.
These POSIX wrappers are assumed to be passed a concrete stream object so
it is more efficient (eg on nan-boxing builds) to pass in the pointer
rather than mp_obj_t, because then the users of these functions only need
to store a void* (and mp_obj_t may be wider than a pointer).  And things
would be further improved if the stream protocol functions eventually took
a pointer as their first argument (instead of an mp_obj_t).

This patch is a step to getting ussl/axtls compiling on nan-boxing builds.

See issue #3085.
2018-08-14 17:36:08 +10:00
Damien George a785a3dbfb py/objarray: Allow to build again when bytearray is disabled. 2018-08-14 16:23:21 +10:00
Damien George 91041945c9 py/gc: In gc_alloc, reset n_free var right before search for free mem.
Otherwise there is the possibility that n_free starts out non-zero from the
previous iteration, which may have found a few (but not enough) free blocks
at the end of the heap.  If this is the case, and if the very first blocks
that are scanned the second time around (starting at
gc_last_free_atb_index) are found to give enough memory (including the
blocks at the end of the heap from the previous iteration that left n_free
non-zero) then memory will be allocated starting before the location that
gc_last_free_atb_index points to, most likely leading to corruption.

This serious bug did not manifest itself in the past because a gc_collect
always resets gc_last_free_atb_index to point to the start of the GC heap,
and the first block there is almost always allocated to a long-lived
object (eg entries from sys.path, or mounted filesystem objects), which
means that n_free would be reset at the start of the search loop.

But with threading enabled with the GIL disabled it is possible to trigger
the bug via the following sequence of events:

1. Thread A runs gc_alloc, fails to find enough memory, and has a non-zero
   n_free at the end of the search.
2. Thread A calls gc_collect and frees a bunch of blocks on the GC heap.
3. Just after gc_collect finishes in thread A, thread B takes gc_mutex and
   does an allocation, moving gc_last_free_atb_index to point to the
   interior of the heap, to a place where there is most likely a run of
   available blocks.
4. Thread A regains gc_mutex and does its second search for free memory,
   starting with a non-zero n_free.  Since it's likely that the first block
   it searches is available it will allocate memory which overlaps with the
   memory before gc_last_free_atb_index.
2018-08-14 16:11:21 +10:00
Paul Sokolovsky bb28fe7b7b py/py.mk: Don't hardcode path to libaxtls.a.
Use -L$(BUILD), not -Lbuild. Otherwise, builds for different archs/subarchs
using different values of BUILD may fail.
2018-08-14 15:10:52 +10:00
Damien George cbec17f2cd py/compile: For dynamic compiler, widen literal 1 to get correct shift.
Without this patch, on 64-bit architectures the "1 << (small_int_bits - 1)"
is computed using only 32-bit values (since small_int_bits is a uint8_t)
and so will overflow (and give the wrong result) if small_int_bits is
larger than 32.
2018-08-13 23:34:47 +10:00
Scott Shawcroft 4513bd6ea3
Fix translation newlines
Escape table was incorrect
2018-08-10 16:17:03 -07:00
Scott Shawcroft 24e53ad591
Rework escaping and fix ESP build. 2018-08-09 15:58:45 -07:00
Scott Shawcroft 1835f1ab14
Update filter and handle nested quotes 2018-08-09 14:16:28 -07:00