Commit Graph

3250 Commits

Author SHA1 Message Date
Damien George 4df013c8cc py/objtype: mp_obj_new_super doesn't need to be public, so inline it.
Saves code size (20 bytes on bare-arm) and makes it a tiny bit more
efficient.
2017-04-22 12:14:04 +10:00
Paul Sokolovsky 9e8f316392 extmod/moductypes: Fix bigint handling for 32-bit ports. 2017-04-21 16:43:21 +03:00
Damien George 7a72c0db5a py: Reduce str/repr precision of float numbers when floats are 30-bit.
With 30-bit floats there aren't enough bits to faithfully print 7 decimal
digits, so reduce the precision to 6 digits.
2017-04-21 16:21:56 +10:00
Damien George bbb4b9822f py/modmicropython: Add micropython.kbd_intr() function.
It controls the character that's used to (asynchronously) raise a
KeyboardInterrupt exception.  Passing "-1" allows to disable the
interception of the interrupt character (as long as a port allows such a
behaviour).
2017-04-18 17:24:30 +10:00
Damien George c7e8c6f7de py/gc: Execute finaliser code in a protected environment.
If a finaliser raises an exception then it must not propagate through the
GC sweep function.  This patch protects against such a thing by running
finaliser code via the mp_call_function_1_protected call.

This patch also adds scheduler lock/unlock calls around the finaliser
execution to further protect against any possible reentrancy issues: the
memory manager is already locked when doing a collection, but we also don't
want to allow any scheduled code to run, KeyboardInterrupts to interupt the
code, nor threads to switch.
2017-04-12 13:52:04 +10:00
Damien George 08242eed26 py/nlrsetjmp: Add check for failed NLR jump.
Also optimise the function so it only needs to call the MP_STATE_THREAD
macro once (following how other nlr code is written).
2017-04-12 13:50:31 +10:00
Damien George a73501b1d6 py/objfloat: Add implementation of high-quality float hashing.
Disabled by default.
2017-04-12 13:38:17 +10:00
Damien George 816413e4b2 py: Optimise types for common case where type has a single parent type.
The common cases for inheritance are 0 or 1 parent types, for both built-in
types (eg built-in exceptions) as well as user defined types.  So it makes
sense to optimise the case of 1 parent type by storing just the type and
not a tuple of 1 value (that value being the single parent type).

This patch makes such an optimisation.  Even though there is a bit more
code to handle the two cases (either a single type or a tuple with 2 or
more values) it helps reduce overall code size because it eliminates the
need to create a static tuple to hold single parents (eg for the built-in
exceptions).  It also helps reduce RAM usage for user defined types that
only derive from a single parent.

Changes in code size (in bytes) due to this patch:

    bare-arm:       -16
    minimal (x86): -176
    unix (x86-64): -320
    unix nanbox:   -384
    stmhal:         -64
    cc3200:         -32
    esp8266:       -108
2017-04-12 13:22:21 +10:00
Damien George fc710169b7 py/obj: Clean up and add comments describing mp_obj_type_t struct. 2017-04-12 13:20:26 +10:00
Damien George e31fbd9b41 py/objint: Use unsigned arithmetic when formatting an integer.
Otherwise the edge case of the most negative integer value will not convert
correctly.
2017-04-11 15:18:35 +10:00
Damien George f66df1efc8 py/objint: Extract small int value directly because type is known. 2017-04-11 15:16:09 +10:00
Damien George 79ce664952 py/runtime: When init'ing kbd intr exc, use tuple ptr instead of object. 2017-04-10 17:07:26 +10:00
Damien George ee86de1f1a py: Make sure that static emg-exc-buffer is aligned to size of mp_obj_t.
This buffer is used to allocate objects temporarily, and such objects
require that their underlying memory be correctly aligned for their data
type.  Aligning for mp_obj_t should be sufficient for emergency exceptions,
but in general the memory buffer should aligned to the maximum alignment of
the machine (eg on a 32-bit machine with mp_obj_t being 4 bytes, a double
may not be correctly aligned).

This patch fixes a bug for certain nan-boxing builds, where mp_obj_t is 8
bytes and must be aligned to 8 bytes (even though the machine is 32 bit).
2017-04-10 16:02:56 +10:00
Damien George 81d2ca2b12 py/objtuple: Add support for inplace add (same as normal add). 2017-04-05 12:38:02 +10:00
Damien George de9b53695d py: Raise a ValueError if range() step is zero.
Following CPython.  Otherwise one gets either an infinite loop (if code is
optimised by the uPy compiler) or possibly a divide-by-zero CPU exception.
2017-04-05 10:50:26 +10:00
Damien George fc245d1ca4 py/objint: Consolidate mp_obj_new_int_from_float to one implementation.
This reduces code duplication and allows to make mp_classify_fp_as_int
static, which reduces code size.
2017-04-04 16:45:49 +10:00
Damien George 19f2e47d59 py: Add very simple but correct hashing for float and complex numbers.
Hashing of float and complex numbers that are exact (real) integers should
return the same integer hash value as hashing the corresponding integer
value.  Eg hash(1), hash(1.0) and hash(1+0j) should all be the same (this
is how Python is specified: if x==y then hash(x)==hash(y)).

This patch implements the simplest way of doing float/complex hashing by
just converting the value to int and returning that value.
2017-04-04 11:57:21 +10:00
Paul Sokolovsky 9a973977bb py/objstr: Use MICROPY_FULL_CHECKS for range checking when constructing bytes.
Split this setting from MICROPY_CPYTHON_COMPAT. The idea is to be able to
keep MICROPY_CPYTHON_COMPAT disabled, but still pass more of regression
testsuite. In particular, this fixes last failing test in basics/ for
Zephyr port.
2017-04-02 21:20:07 +03:00
Damien George a5500a8aad py/obj.h: Make sequence grow more efficient and support overlapping.
The first memmove now copies less bytes in some cases (because len_adj <=
slice_len), and the memcpy is replaced with memmove to support the
possibility that dest and slice regions are overlapping.
2017-04-02 17:28:24 +10:00
Damien George 4c307bfba1 all: Move BYTES_PER_WORD definition from ports to py/mpconfig.h
It can still be overwritten by a port in mpconfigport.h but for almost
all cases one can use the provided default.
2017-04-01 11:39:38 +11:00
Damien George b6c7e4b143 all: Use full path name when including mp-readline/timeutils/netutils.
This follows the pattern of how all other headers are now included, and
makes it explicit where the header file comes from.  This patch also
removes -I options from Makefile's that specify the mp-readline/timeutils/
netutils directories, which are no longer needed.
2017-03-31 22:29:39 +11:00
Damien George 4b753515c7 py/objzip: Convert mp_uint_t to size_t. 2017-03-30 22:58:08 +11:00
Paul Sokolovsky 29dd92c82a zephyr/Makefile: Rework to use modern, official build integration.
Build happens in 3 stages:

1. Zephyr config header and make vars are generated from prj.conf.
2. libmicropython is built using them.
3. Zephyr is built and final link happens.
2017-03-30 00:08:27 +03:00
Damien George 6b34107537 py: Change mp_uint_t to size_t for mp_obj_str_get_data len arg. 2017-03-29 12:56:45 +11:00
Damien George 6213ad7f46 py: Convert mp_uint_t to size_t for tuple/list accessors.
This patch changes mp_uint_t to size_t for the len argument of the
following public facing C functions:

mp_obj_tuple_get
mp_obj_list_get
mp_obj_get_array

These functions take a pointer to the len argument (to be filled in by the
function) and callers of these functions should update their code so the
type of len is changed to size_t.  For ports that don't use nan-boxing
there should be no change in generate code because the size of the type
remains the same (word sized), and in a lot of cases there won't even be a
compiler warning if the type remains as mp_uint_t.

The reason for this change is to standardise on the use of size_t for
variables that count memory (or memory related) sizes/lengths.  It helps
builds that use nan-boxing.
2017-03-29 12:56:17 +11:00
Damien George f9b0e644e5 py/compile: Provide terse error message for invalid dict/set literals. 2017-03-29 12:44:27 +11:00
Damien George 18c059febf py: Shorten a couple of error messages. 2017-03-29 12:36:46 +11:00
Damien George f55a059e7a py/compile: Simplify syntax-error messages for illegal assignments.
With this patch all illegal assignments are reported as "can't assign to
expression".  Before the patch there were special cases for a literal on
the LHS, and for augmented assignments (eg +=), but it seems a waste of
bytes (and there are lots of bytes used in error messages) to spend on
distinguishing such errors which a user will rarely encounter.
2017-03-29 12:28:33 +11:00
Damien George 5010d1958f py/lexer: Simplify and reduce code size for operator tokenising.
By removing the 'E' code from the operator token encoding mini-language the
tokenising can be simplified.  The 'E' code was only used for the !=
operator which is now handled as a special case; the optimisations for the
general case more than make up for the addition of this single, special
case.  Furthermore, the . and ... operators can be handled in the same way
as != which reduces the code size a little further.

This simplification also removes a "goto".

Changes in code size for this patch are (measured in bytes):

bare-arm:       -48
minimal x86:    -64
unix x86-64:   -112
unix nanbox:    -64
stmhal:         -48
cc3200:         -48
esp8266:        -76
2017-03-29 10:56:52 +11:00
Damien George 94c41bb06f py: Use mp_raise_TypeError/mp_raise_ValueError helpers where possible.
Saves 168 bytes on bare-arm.
2017-03-28 22:37:26 +11:00
Damien George 54507f78ee py/objmap: Convert mp_uint_t to size_t. 2017-03-27 12:19:24 +11:00
Damien George 40c1272e55 py/compile: When compiling super(), handle closed-over self variable.
The self variable may be closed-over in the function, and in that case the
call to super() should load the contents of the closure cell using
LOAD_DEREF (before this patch it would just load the cell directly).
2017-03-27 11:27:08 +11:00
Damien George a0973b09ce py/vm: Fix VM opcode tracing to print correct stack pointer.
Also const_table is now moved to the code_state->fun_bc structure.
2017-03-27 10:52:04 +11:00
Damien George 3f810daeb3 py/obj: Change mp_uint_t to size_t for mp_obj_get_array_fixed_n len arg. 2017-03-26 19:20:06 +11:00
Paul Sokolovsky 99866a00a0 py/nlrx86: Better check for Zephyr (requires 1.7). 2017-03-26 00:33:23 +03:00
Damien George ab5689bc9d py/objarray: Use mp_obj_str_get_str instead of mp_obj_str_get_data. 2017-03-25 19:53:31 +11:00
Damien George 64a4f11b2d py: Remove MP_STATE_CTX, use MP_STATE_THREAD instead (it's an alias).
MP_STATE_CTX was recently aliased to MP_STATE_THREAD and can now be
removed.
2017-03-24 18:43:28 +11:00
Damien George 707f16b05c py: Use mp_locals/mp_globals accessor funcs instead of MP_STATE_CTX.
To improve maintainability of the code.
2017-03-24 18:41:11 +11:00
Damien George f4ee1ba9b4 py/objnamedtuple: Use size_t where appropriate, instead of mp_uint_t. 2017-03-24 17:25:25 +11:00
Damien George d1b93ced78 py/objtype: Use size_t where appropriate, instead of mp_uint_t or uint. 2017-03-24 16:58:13 +11:00
Damien George c236ebfea7 py/modbuiltins: Allow round() to return a big int if necessary.
Previous to this patch, if the result of the round function overflowed a
small int, or was inf or nan, then a garbage value was returned.  With
this patch the correct big-int is returned if necessary and exceptions are
raised for inf or nan.
2017-03-24 11:00:45 +11:00
Damien George 125eae1ba3 py/modbuiltins: For round() builtin use nearbyint instead of round.
The C nearbyint function has exactly the semantics that Python's round()
requires, whereas C's round() requires extra steps to handle rounding of
numbers half way between integers.  So using nearbyint reduces code size
and potentially eliminates any source of errors in the handling of half-way
numbers.

Also, bare-metal implementations of nearbyint can be more efficient than
round, so further code size is saved (and efficiency improved).

nearbyint is provided in the C99 standard so it should be available on all
supported platforms.
2017-03-24 11:00:45 +11:00
Damien George c073519ec8 py/objint: Handle special case of -0 when classifying fp as int.
Otherwise -0.0 is classified as a bigint, which for builds without bigints
will lead unexpectedly to an overflow.
2017-03-23 23:51:35 +11:00
Damien George febeff4af4 py/modmath: Allow trunc/ceil/floor to return a big int if necessary.
Previous to this patch, if the result of the trunc/ceil/floor functions
overflowed a small int, or was inf or nan, then a garbage value was
returned.  With this patch the correct big-int is returned if necessary,
and exceptions are raised for inf or nan.
2017-03-23 22:57:08 +11:00
Damien George f64a3e296e py/lexer: Remove obsolete comment, since lexer can now raise exceptions. 2017-03-23 16:40:24 +11:00
Damien George 60656eaea4 py: Define and use MP_OBJ_ITER_BUF_NSLOTS to get size of stack iter buf.
It improves readability of code and reduces the chance to make a mistake.

This patch also fixes a bug with nan-boxing builds by rounding up the
calculation of the new NSLOTS variable, giving the correct number of slots
(being 4) even if mp_obj_t is larger than the native machine size.
2017-03-23 16:36:08 +11:00
Damien George 507119f4d8 py/sequence: Convert mp_uint_t to size_t where appropriate. 2017-03-23 16:23:20 +11:00
Damien George c88cfe165b py: Use size_t as len argument and return type of mp_get_index.
These values are used to compute memory addresses and so size_t is the
more appropriate type to use.
2017-03-23 16:17:40 +11:00
Damien George 58f23def55 py/bc: Provide better error message for an unexpected keyword argument.
Now, passing a keyword argument that is not expected will correctly report
that fact.  If normal or detailed error messages are enabled then the name
of the unexpected argument will be reported.

This patch decreases the code size of bare-arm and stmhal by 12 bytes, and
cc3200 by 8 bytes.  Other ports (minimal, unix, esp8266) remain the same in
code size.  For terse error message configuration this is because the new
message is shorter than the old one.  For normal (and detailed) error
message configuration this is because the new error message already exists
in py/objnamedtuple.c so there's no extra space in ROM needed for the
string.
2017-03-22 13:40:27 +11:00
Damien George 1a5c8d1053 py/vm: Don't release the GIL if the scheduler is locked.
The scheduler being locked general means we are running a scheduled
function, and switching to another thread violates that, so don't switch in
such a case (even though we technically could).

And if we are running a scheduled function then we want to finish it ASAP,
so we shouldn't switch to another thread.

Furthermore, ports with threading enabled will lock the scheduler during a
hard IRQ, and this patch to the VM will make sure that threads are not
switched during a hard IRQ (which would crash the VM).
2017-03-20 18:42:27 +11:00
Damien George 6e74d24f30 py: Add micropython.schedule() function and associated runtime code. 2017-03-20 15:20:26 +11:00
stijn bf29fe2e13 py/objstr: Use better msg in bad implicit str/bytes conversion exception
Instead of always reporting some object cannot be implicitly be converted
to a 'str', even when it is a 'bytes' object, adjust the logic so that
when trying to convert str to bytes it is shown like that.
This will still report bad implicit conversion from e.g. 'int to bytes'
as 'int to str' but it will not result in the confusing
'can't convert 'str' object to str implicitly' anymore for calls like
b'somestring'.count('a').
2017-03-20 15:11:45 +11:00
Damien George 5640e6dacd py: Provide mp_decode_uint_value to help optimise stack usage.
This has a noticeable improvement on x86-64 and Thumb2 archs, where stack
usage is reduced by 2 machine words in the VM.
2017-03-17 16:50:19 +11:00
Damien George 71a3d6ec3b py: Reduce size of mp_code_state_t structure.
Instead of caching data that is constant (code_info, const_table and
n_state), store just a pointer to the underlying function object from which
this data can be derived.

This helps reduce stack usage for the case when the mp_code_state_t
structure is stored on the stack, as well as heap usage when it's stored
on the heap.

The downside is that the VM becomes a little more complex because it now
needs to derive the data from the underlying function object.  But this
doesn't impact the performance by much (if at all) because most of the
decoding of data is done outside the main opcode loop.  Measurements using
pystone show that little to no performance is lost.

This patch also fixes a nasty bug whereby the bytecode can be reclaimed by
the GC during execution.  With this patch there is always a pointer to the
function object held by the VM during execution, since it's stored in the
mp_code_state_t structure.
2017-03-17 16:39:13 +11:00
Damien George d279bcff8a py/objstr: Fix eager optimisation of str/bytes addition.
The RHS can only be returned if it is the same type as the LHS.
2017-03-16 14:30:04 +11:00
Damien George 23a693ec2d py/mkrules.mk: Remove special check for "-B" in qstr auto generation.
When make is passed "-B" it seems that everything is considered out-of-date
and so $? expands to all prerequisites.  Thus there is no need for a
special check to see if $? is emtpy.
2017-03-15 21:50:48 +11:00
Damien George d65371538d py/mpprint: Fix int formatting so "+" is printed for 0-valued integer. 2017-03-15 17:25:12 +11:00
Damien George 8cd4911e63 py/emitnative: Remove obsolete commented out code. 2017-03-15 10:03:22 +11:00
Damien George a5a84e1f85 py/emitnative: Use assertions and mp_not_implemented correctly.
Assertions are used to check expressions that should always be true,
and mp_not_implemented is used for code that can be reached.
2017-03-14 23:05:40 +11:00
Damien George d1ae6ae080 py/objint: Allow to print long-long ints without using the heap.
Some stack is allocated to format ints, and when the int implementation uses
long-long there should be additional stack allocated compared with the other
cases.  This patch uses the existing "fmt_int_t" type to determine the
amount of stack to allocate.
2017-03-14 14:54:20 +11:00
Damien George 1831034be1 py: Allow lexer to raise exceptions during construction.
This patch refactors the error handling in the lexer, to simplify it (ie
reduce code size).

A long time ago, when the lexer/parser/compiler were first written, the
lexer and parser were designed so they didn't use exceptions (ie nlr) to
report errors but rather returned an error code.  Over time that has
gradually changed, the parser in particular has more and more ways of
raising exceptions.  Also, the lexer never really handled all errors without
raising, eg there were some memory errors which could raise an exception
(and in these rare cases one would get a fatal nlr-not-handled fault).

This patch accepts the fact that the lexer can raise exceptions in some
cases and allows it to raise exceptions to handle all its errors, which are
for the most part just out-of-memory errors during construction of the
lexer.  This makes the lexer a bit simpler, and also the persistent code
stuff is simplified.

What this means for users of the lexer is that calls to it must be wrapped
in a nlr handler.  But all uses of the lexer already have such an nlr
handler for the parser (and compiler) so that doesn't put any extra burden
on the callers.
2017-03-14 11:52:05 +11:00
Paul Sokolovsky 776883cb80 py/objint_longlong: Implement mp_obj_int_from_bytes_impl().
This makes int.from_bytes() work for MICROPY_LONGINT_IMPL_LONGLONG.
2017-03-10 00:22:53 +01:00
Damien George 52b6764894 py/nlrx64: Fixes to support Mac OS.
Two independent fixes:
- need to prefix symbols referenced from asm with underscore;
- need to undo the C-function prelude.
2017-03-08 22:36:02 +11:00
Paul Sokolovsky fd49ff9917 py/nlrx86: Add workaround for Zephyr.
Actually, this removes -fno-omit-frame-pointer workaround for Zephyr.
2017-03-07 16:48:09 +01:00
Krzysztof Blazewicz 7e480e8a30 py: Use mp_obj_get_array where sequence may be a tuple or a list. 2017-03-07 16:48:16 +11:00
Krzysztof Blazewicz 1215dc47e2 py/runtime.c: Remove optimization of '*a,=b', it caused a bug.
*a, = b should always make a copy of b, instead, before this patch
if b was a list it would copy only a reference to it.
2017-03-07 16:48:16 +11:00
Paul Sokolovsky 96aa3a3102 py/modsys: Use MP_SMALL_INT_MAX for sys.maxsize in case of LONGINT_IMPL_NONE.
INT_MAX used previosly is indeed max value for int, whereas on LP64
platforms, long is used for mp_int_t. Using MP_SMALL_INT_MAX is the
correct way to do it anyway.
2017-03-06 12:15:25 +01:00
Damien George 914648ce0e py/py.mk: Force nlr files to be compiled with -Os. 2017-03-06 17:13:43 +11:00
Damien George f0dddb688d py/nlrx86: Convert from assembler to C file with inline asm. 2017-03-06 17:13:43 +11:00
Damien George 321848470c py/nlrx64: Convert from assembler to C file with inline asm. 2017-03-06 17:13:35 +11:00
Damien George a85755aa22 py/nlrxtensa: Convert from assembler to C file with inline asm.
nlr_jump is a little bit inefficient because it now saves a register to
the stack.
2017-03-06 17:13:16 +11:00
Damien George be3d7f91e5 py/nlr.h: Mark nlr_jump_fail as NORETURN. 2017-03-06 17:13:16 +11:00
Damien George 05fe66f68a py: Move locals/globals dicts to the thread-specific state.
Each threads needs to have its own private references to its current
locals/globals dicts, otherwise functions running within different
contexts (eg imported from different files) can behave very strangely.
2017-03-06 17:01:56 +11:00
Damien George 9275c18270 py/map: Fix bugs with deletion of elements from OrderedDict.
There were 2 bugs, now fixed by this patch:
- after deleting an element the len of the dict did not decrease by 1
- after deleting an element searching through the dict could lead to
  a seg fault due to there being an MP_OBJ_SENTINEL in the ordered array
2017-03-03 11:21:19 +11:00
Damien George f4a12dca58 py/objarray: Disallow slice-assignment to read-only memoryview.
Also comes with a test for this.  Fixes issue #2904.
2017-02-27 16:09:57 +11:00
Paul Sokolovsky 4b3da60324 py/runtime: mp_raise_msg(): Accept NULL argument for message.
In this case, raise an exception without a message.

This would allow to shove few code bytes comparing to currently used
mp_raise_msg(..., "") pattern. (Actual savings depend on function code
alignment used by a particular platform.)
2017-02-24 09:57:25 -05:00
Damien George f615d82d5b py/parse: Simplify handling of errors by raising them directly.
The parser was originally written to work without raising any exceptions
and instead return an error value to the caller.  But it's now required
that a call to the parser be wrapped in an nlr handler, so we may as well
make use of that fact and simplify the parser so that it doesn't need to
keep track of any memory errors that it had.  The parser anyway explicitly
raises an exception at the end if there was an error.

This patch simplifies the parser by letting the underlying memory
allocation functions raise an exception if they fail to allocate any
memory.  And if there is an error parsing the "<id> = const(<val>)" pattern
then that also raises an exception right away instead of trying to recover
gracefully and then raise.
2017-02-24 14:56:37 +11:00
Damien George 5255255fb9 py: Create str/bytes objects in the parser, not the compiler.
Previous to this patch any non-interned str/bytes objects would create a
special parse node that held a copy of the str/bytes data.  Then in the
compiler this data would be turned into a str/bytes object.  This actually
lead to 2 copies of the data, one in the parse node and one in the object.
The parse node's copy of the data would be freed at the end of the compile
stage but nevertheless it meant that the peak memory usage of the
parse/compile stage was higher than it needed to be (by an amount equal to
the number of bytes in all the non-interned str/bytes objects).

This patch changes the behaviour so that str/bytes objects are created
directly in the parser and the object stored in a const-object parse node
(which already exists for bignum, float and complex const objects).  This
reduces peak RAM usage of the parse/compile stage, simplifies the parser
and compiler, and reduces code size by about 170 bytes on Thumb2 archs,
and by about 300 bytes on Xtensa archs.
2017-02-24 13:43:43 +11:00
Damien George 74f4d2c659 py/parse: Allow parser/compiler consts to be bignums.
This patch allows uPy consts to be bignums, eg:

    X = const(1 << 100)

The infrastructure for consts to be a bignum (rather than restricted to
small integers) has been in place for a while, ever since constant folding
was upgraded to allow bignums.  It just required a small change (in this
patch) to enable it.
2017-02-24 13:03:44 +11:00
Damien George b1b090255c py/moduerrno: Make list of errno codes configurable.
It's configurable by defining MICROPY_PY_UERRNO_LIST.  If this is not
defined then a default is provided.
2017-02-22 12:58:11 +11:00
Damien George f563406d2e py/moduerrno: Make uerrno.errorcode dict configurable.
It's configured by MICROPY_PY_UERRNO_ERRORCODE and enabled by default
(since that's the behaviour before this patch).

Without this dict the lookup of errno codes to strings must use the
uerrno module itself.
2017-02-22 12:58:11 +11:00
Damien George 89267886cc py/objlist: For list slice assignment, allow RHS to be a tuple or list.
Before this patch, assigning anything other than a list would lead to a
crash.  Fixes issue #2886.
2017-02-20 15:09:59 +11:00
Damien George bdebfaa4bf py/grammar: Remove unused rule.
Since the recent changes to string/bytes literal concatenation, this rule
is no longer used.
2017-02-17 12:48:45 +11:00
Damien George 5124a94067 py/lexer: Convert mp_uint_t to size_t where appropriate. 2017-02-17 12:44:24 +11:00
Damien George 534b7c368d py: Do adjacent str/bytes literal concatenation in lexer, not compiler.
It's much more efficient in RAM and code size to do implicit literal string
concatenation in the lexer, as opposed to the compiler.

RAM usage is reduced because the concatenation can be done right away in the
tokeniser by just accumulating the string/bytes literals into the lexer's
vstr.  Prior to this patch adjacent strings/bytes would create a parse tree
(one node per string/bytes) and then in the compiler a whole new chunk of
memory was allocated to store the concatenated string, which used more than
double the memory compared to just accumulating in the lexer.

This patch also significantly reduces code size:

bare-arm: -204
minimal:  -204
unix x64: -328
stmhal:   -208
esp8266:  -284
cc3200:   -224
2017-02-17 12:12:40 +11:00
Damien George 773278ec30 py/lexer: Simplify handling of line-continuation error.
Previous to this patch there was an explicit check for errors with line
continuation (where backslash was not immediately followed by a newline).

But this check is not necessary: if there is an error then the remaining
logic of the tokeniser will reject the backslash and correctly produce a
syntax error.
2017-02-17 11:30:14 +11:00
Damien George ae43679792 py/lexer: Use strcmp to make keyword searching more efficient.
Since the table of keywords is sorted, we can use strcmp to do the search
and stop part way through the search if the comparison is less-than.

Because all tokens that are names are subject to this search, this
optimisation will improve the overall speed of the lexer when processing
a script.

The change also decreases code size by a little bit because we now use
strcmp instead of the custom str_strn_equal function.
2017-02-17 11:10:35 +11:00
Damien George a68c754688 py/lexer: Move check for keyword to name-tokenising block.
Keywords only needs to be searched for if the token is a MP_TOKEN_NAME, so
we can move the seach to the part of the code that does the tokenising for
MP_TOKEN_NAME.
2017-02-17 10:59:57 +11:00
Damien George 98b3072da5 py/lexer: Simplify handling of indenting of very first token. 2017-02-17 10:56:06 +11:00
Damien George 6a11048af1 py/persistentcode: Bump .mpy version due to change in bytecode. 2017-02-17 00:19:34 +11:00
Damien George c264414746 py/lexer: Don't generate string representation for period or ellipsis.
It's not needed.
2017-02-16 20:23:41 +11:00
Damien George 71019ae4f5 py/grammar: Group no-compile grammar rules together to shrink tables.
Grammar rules have 2 variants: ones that are attached to a specific
compile function which is called to compile that grammar node, and ones
that don't have a compile function and are instead just inspected to see
what form they take.

In the compiler there is a table of all grammar rules, with each entry
having a pointer to the associated compile function.  Those rules with no
compile function have a null pointer.  There are 120 such rules, so that's
120 words of essentially wasted code space.

By grouping together the compile vs no-compile rules we can put all the
no-compile rules at the end of the list of rules, and then we don't need
to store the null pointers.  We just have a truncated table and it's
guaranteed that when indexing this table we only index the first half,
the half with populated pointers.

This patch implements such a grouping by having a specific macro for the
compile vs no-compile grammar rules (DEF_RULE vs DEF_RULE_NC).  It saves
around 460 bytes of code on 32-bit archs.
2017-02-16 19:45:06 +11:00
Damien George e6003f466e py: De-optimise some uses of mp_getiter, so they don't use the C stack.
In these cases the heap is anyway used to create a new object so no real
need to use the C stack for iterating.  It saves a few bytes of code size.
2017-02-16 19:11:34 +11:00
Damien George 4d2bab1444 py/compile: Optimise list/dict/set comprehensions to use stack iter. 2017-02-16 18:38:07 +11:00
Damien George cb6300697c py/runtime: Optimise case of identity iterator so it doesn't alloc RAM. 2017-02-16 18:38:06 +11:00
Damien George 30b42dd72d py: Remove unused "use_stack" argument from for_iter_end emit function. 2017-02-16 18:38:06 +11:00
Damien George 088740ecc4 py: Optimise storage of iterator so it takes only 4 slots on Py stack. 2017-02-16 18:38:06 +11:00
Damien George 6e769da0da py: Make FOR_ITER opcode pop 1+4 slots from the stack when finished.
The extra 4 slots correspond to the iterator object stored on the stack.
2017-02-16 18:38:06 +11:00
Damien George f4df3aaa72 py: Allow bytecode/native to put iter_buf on stack for simple for loops.
So that the "for x in it: ..." statement can now work without using the
heap (so long as the iterator argument fits in an iter_buf structure).
2017-02-16 18:38:06 +11:00
Damien George ae8d867586 py: Add iter_buf to getiter type method.
Allows to iterate over the following without allocating on the heap:
- tuple
- list
- string, bytes
- bytearray, array
- dict (not dict.keys, dict.values, dict.items)
- set, frozenset

Allows to call the following without heap memory:
- all, any, min, max, sum

TODO: still need to allocate stack memory in bytecode for iter_buf.
2017-02-16 18:38:06 +11:00
Damien George 101886f529 py/vm: Convert mp_uint_t to size_t where appropriate. 2017-02-16 16:51:17 +11:00
Damien George da36f5232d py/objint: Convert mp_uint_t to size_t where appropriate. 2017-02-16 16:51:17 +11:00
Damien George fa5a591757 py/objexcept: Convert mp_uint_t to size_t where appropriate. 2017-02-16 16:51:17 +11:00
Damien George efa629028a py/objclosure: Convert mp_uint_t to size_t where appropriate. 2017-02-16 16:51:17 +11:00
Damien George dbcdb9f8d8 py/objfun: Convert mp_uint_t to size_t where appropriate. 2017-02-16 16:51:16 +11:00
Damien George ccc5254224 py/objarray: Convert mp_uint_t to size_t where appropriate. 2017-02-16 16:51:16 +11:00
Damien George c0d9500eee py/objstr: Convert mp_uint_t to size_t (and use int) where appropriate. 2017-02-16 16:51:16 +11:00
Damien George 68cd3a93f0 py/objset: Convert mp_uint_t to size_t where appropriate. 2017-02-16 16:51:16 +11:00
Damien George 1ea2f7a8ce py/objdict: Convert mp_uint_t to size_t where appropriate. 2017-02-16 16:51:16 +11:00
Damien George 58d9eeb8d9 py/objlist: Convert mp_uint_t to size_t where appropriate. 2017-02-16 16:51:16 +11:00
Damien George 229823942c py/objtuple: Convert mp_uint_t to size_t where appropriate. 2017-02-16 16:51:16 +11:00
Damien George 891dc5c62c py/persistentcode: Replace mp_uint_t with size_t where appropriate. 2017-02-16 16:51:16 +11:00
Damien George 6ed77bedbd py/mpz: Change type of "base" args from mp_uint_t to unsigned int. 2017-02-16 16:51:16 +11:00
Damien George eb90edb5c0 py/mpz: Remove obsolete declaration of mpz_as_str_size. 2017-02-16 16:51:16 +11:00
Damien George dcdcc43dad py/mpz: Convert mp_uint_t to size_t where appropriate. 2017-02-16 16:51:13 +11:00
Damien George 4e3bac2e42 py/runtime: Convert mp_uint_t to size_t where appropriate. 2017-02-16 16:51:13 +11:00
Damien George f6c22a0679 py/vm: Add MICROPY_PY_THREAD_GIL_VM_DIVISOR option.
This improves efficiency of GIL release within the VM, by only doing the
release after a fixed number of jump-opcodes have executed in the current
thread.
2017-02-15 11:28:15 +11:00
Damien George 234f07f16c py/modthread: Use system-provided mutexs for _thread locks.
It's more efficient using the system mutexs instead of synthetic ones with
a busy-wait loop.  The system can do proper scheduling and blocking of the
threads waiting on the mutex.
2017-02-15 11:28:02 +11:00
Damien George adc80b8f84 py/objtype: Replace non-ASCII single-quote char with ASCII version. 2017-02-14 20:55:31 +11:00
Damien George cc2dbdd1fe py/emitbc: Produce correct line number info for large bytecode chunks.
Previous to this patch, for large chunks of bytecode that originated from
a single source-code line, the bytecode-line mapping would generate
something like (for 42 bytecode bytes and 1 line):

  BC_SKIP=31  LINE_SKIP=1
  BC_SKIP=11  LINE_SKIP=0

This would mean that any errors in the last 11 bytecode bytes would be
reported on the following line.  This patch fixes it to generate instead:

  BC_SKIP=31  LINE_SKIP=0
  BC_SKIP=11  LINE_SKIP=1
2017-02-10 11:58:10 +11:00
dmazzella 18e6569166 py/objtype: Implement __delattr__ and __setattr__.
This patch implements support for class methods __delattr__ and __setattr__
for customising attribute access.  It is controlled by the config option
MICROPY_PY_DELATTR_SETATTR and is disabled by default.
2017-02-09 12:40:15 +11:00
Dave Hylands aa34c553ec py/nlr: Fix execstack builds for ARM.
It seems that the gcc toolchain on the RaspberryPi
likes %progbits instead of @progbits. I verified that
%progbits also works under x86, so this should
fix #2848 and fix #2842

I verified that unix and mpy-cross both compile
on my RaspberryPi and on my x64 machine.
2017-02-08 11:12:26 +11:00
Damien George af622eb2a6 py/map: Change mp_uint_t to size_t where appropriate.
The internal map/set functions now use size_t exclusively for computing
addresses.  size_t is enough to reach all of available memory when
computing addresses so is the right type to use.  In particular, for
nanbox builds it saves quite a bit of code size and RAM compared to the
original use of mp_uint_t (which is 64-bits on nanbox builds).
2017-02-08 11:00:15 +11:00
Damien George a25aa2bcc3 py/asmxtensa.h: Explicitly cast args to 32-bits so left-shift is legal.
For archs that have 16-bit pointers, the asmxtensa.h file can give compiler
warnings about left-shift being greater than the width of the type (due to
the inline functions in this header file).  Explicitly casting the
constants to uint32_t stops these warnings.
2017-02-08 10:48:51 +11:00
Damien George bd04ed3e8a py/objcomplex: Fix typo in ternary expression.
This typo actually did the correct thing, but it was very obscure (came
about from think in terms of Python's "x if cond else y" expression).
2017-02-04 00:23:56 +11:00
Damien George 90ab191b65 py/objstr: Convert some instances of mp_uint_t to size_t. 2017-02-03 13:04:56 +11:00
Damien George a19b5a01ce py/mpconfig.h: Move PY_BUILTINS_POW3 config option to diff part of file.
With so many config options it's good to (at least try to) keep them
grouped into logical sections.
2017-02-03 12:35:48 +11:00
Damien George 7317e34383 py/objstr: Give correct behaviour when passing a dict to %-formatting.
This patch fixes two main things:
- dicts can be printed directly using '%s' % dict
- %-formatting should not crash when passed a non-dict to, eg, '%(foo)s'
2017-02-03 12:13:44 +11:00
Nicko van Someren df0117c8ae py: Added optimised support for 3-argument calls to builtin.pow()
Updated modbuiltin.c to add conditional support for 3-arg calls to
pow() using MICROPY_PY_BUILTINS_POW3 config parameter. Added support in
objint_mpz.c for for optimised implementation.
2017-02-02 22:23:10 +03:00
Damien George 2486c4ff46 py/objset: Fix inplace binary ops so frozensets are not modified. 2017-02-03 00:27:56 +11:00
Damien George 3ed0e5e5d4 py/objcomplex: Correctly handle case of 0j to power of something.
0j to the power of negative now raises ZeroDivisionError, and 0j to the
power of positive returns 0.
2017-02-03 00:01:45 +11:00
Damien George 4b8ec5256d py/objfloat: Raise ZeroDivisionError for 0 to negative power. 2017-02-03 00:01:37 +11:00
Damien George 30cf503e97 py/objset: Make inplace binary operators actually modify the set. 2017-02-02 23:33:49 +11:00
Paul Sokolovsky 50d3a9df67 py/objstringio: Allow to specify initial capacity by passing numeric argument.
E.g. uio.BytesIO(100) will allocate buffer with 100 bytes of space.
2017-02-02 00:33:43 +03:00
Dave Hylands aee74a1dae unix: Make stack be non-executable
This PR is to address issue #2812.
2017-02-01 23:03:10 +03:00
Damien George 1808b2e8d5 extmod: Remove MICROPY_FSUSERMOUNT and related files.
Replaced by MICROPY_VFS and the VFS sub-system.
2017-01-30 12:26:07 +11:00
Damien George 8beba7310f extmod/vfs_fat: Remove MICROPY_READER_FATFS component. 2017-01-30 12:26:07 +11:00
Paul Sokolovsky 7a7516d40d extmod/machine_signal: Implement "signal" abstraction for machine module.
A signal is like a pin, but ca also be inverted (active low). As such, it
abstracts properties of various physical devices, like LEDs, buttons,
relays, buzzers, etc. To instantiate a Signal:

pin = machine.Pin(...)
signal = machine.Signal(pin, inverted=True)

signal has the same .value() and __call__() methods as a pin.
2017-01-29 18:57:36 +03:00
Damien George 3f6b4e08e3 extmod/vfs: Expose mp_vfs_mount_t type.
It should only be used for low-level things and with caution, for example
putting mounted VFS data in ROM or the static data section.
2017-01-27 23:22:15 +11:00
Damien George dcb9ea7215 extmod: Add generic VFS sub-system.
This provides mp_vfs_XXX functions (eg mount, open, listdir) which are
agnostic to the underlying filesystem type, and just require an object with
the relevant filesystem-like methods (eg .mount, .open, .listidr) which can
then be mounted.

These mp_vfs_XXX functions would typically be used by a port to implement
the "uos" module, and mp_vfs_open would be the builtin open function.

This feature is controlled by MICROPY_VFS, disabled by default.
2017-01-27 17:19:06 +11:00
Damien George d4464b0050 py/py.mk: Add CFLAGS_MOD flag to set config file for FatFs. 2017-01-27 13:19:10 +11:00
Damien George cc4c1adf6e py/showbc: Make sure to set the const_table before printing bytecode. 2017-01-27 12:34:09 +11:00
Paul Sokolovsky e2e663291d py/objstr: Optimize string concatenation with empty string.
In this, don't allocate copy, just return non-empty string. This helps
with a standard pattern of buffering data in case of short reads:

    buf = b""
    while ...:
        s = f.read(...)
        buf += s
        ...

For a typical case when single read returns all data needed, there won't
be extra allocation. This optimization helps uasyncio.
2017-01-27 00:49:39 +03:00
Damien George e9cb1f8077 py/objmodule: Move module init/deinit code into runtime functions.
They are one-line functions and having them inline in mp_init/mp_deinit
eliminates the overhead of a function call, and matches how other state
is initialised in mp_init.
2017-01-26 23:30:38 +11:00
Damien George eaa77455c3 py/objint: Fix left-shift overflow in checking for large int. 2017-01-25 14:39:13 +11:00
Damien George f5172af1c4 py/builtinhelp: Implement help('modules') to list available modules.
This is how CPython does it, and it's very useful to help users discover
the available modules for a given port, especially built-in and frozen
modules.  The function does not list modules that are in the filesystem
because this would require a fair bit of work to do correctly, and is very
port specific (depending on the filesystem).
2017-01-22 12:12:54 +11:00
Damien George 9de91914fb py: Move weak-link map to objmodule.c, and expose module maps as public. 2017-01-22 11:59:29 +11:00
Damien George 9f04dfb568 py: Add builtin help function to core, with default help msg.
This builtin is configured using MICROPY_PY_BUILTINS_HELP, and is disabled
by default.
2017-01-22 11:56:16 +11:00
Paul Sokolovsky e6ab43e2c0 py/objint_longlong: Add stub for mp_obj_int_from_bytes_impl().
To be implemented later.
2017-01-21 20:15:05 +03:00
Paul Sokolovsky bec7bfb29d py/objint: from_bytes(): Implement "byteorder" param and arbitrary precision.
If result guaranteedly fits in a small int, it is handled in objint.c.
Otherwise, it is delegated to mp_obj_int_from_bytes_impl(), which should
be implemented by individual objint_*.c, similar to
mp_obj_int_to_bytes_impl().
2017-01-21 20:14:18 +03:00
Paul Sokolovsky 1b42f5251f py/mpz: Implement mpz_set_from_bytes() as a foundation for int.from_bytes(). 2017-01-21 20:07:50 +03:00
Damien George e873243aa3 py/objint_mpz: Refactor switch-statement to remove unreachable default. 2017-01-19 23:35:45 +11:00
Damien George 94a587a750 py/formatfloat: Remove unreachable code.
The if-block that this unreachable code is in has a condition "f>=5" so
"fp_isless1(f)" will always fail.
2017-01-19 23:32:16 +11:00
Paul Sokolovsky af90461931 py/binary: mp_binary_get_size: Raise error on unsupported typecodes.
Previouly, we had errors checked in callers, which led to duplicate code
or missing checks in some places.
2017-01-17 22:53:06 +03:00
Damien George d7150b09d7 py/runtime: Refactor default case of switch to remove assert(0). 2017-01-17 17:03:56 +11:00
Damien George 5bea080737 py/objexcept: Replace if-cond and assert(0) with simple assert. 2017-01-17 17:03:16 +11:00
Damien George f51f22dd42 py/emitnative: Remove assert(0)'s or replace with mp_not_implemented. 2017-01-17 17:02:21 +11:00
Damien George 86e942309a py/parse: Refactor code to remove assert(0)'s.
This helps to improve code coverage.  Note that most of the changes in
this patch are just de-denting the cases of the switch statements.
2017-01-17 17:00:55 +11:00
Damien George 239f920299 py/objgenerator: Don't raise RuntimeError if GeneratorExit ignored.
In this case it's allowed to be ignored.
2017-01-17 00:16:56 +11:00
Damien George 681994638b py/objgenerator: When throwing an object, don't make an exc instance.
Arguments to throw() for generators don't need to be exceptions.
2017-01-17 00:14:14 +11:00
Damien George aeb2655073 py/runtime: Fix handling of throw() when resuming generator.
If GeneratorExit is injected as a throw-value then that should lead to
the close() method being called, if it exists.  If close() does not exist
then throw() should not be called, and this patch fixes this.
2017-01-17 00:10:49 +11:00
Damien George 40863fce6f py/runtime: Refactor assert(0) to improve coverage. 2017-01-17 00:09:56 +11:00
Damien George d23834bc96 py/builtinimport: Remove unreachable code and change obj-import comment. 2017-01-16 16:41:43 +11:00
Damien George 63e291de70 py/builtinimport: Raise ValueError for bad relative import, per CPython. 2017-01-16 16:21:04 +11:00
Damien George b528e9a428 py/builtinimport: Fix bug when importing names from frozen packages.
The commit d9047d3c8a introduced a bug
whereby "from a.b import c" stopped working for frozen packages.  This is
because the path was not properly truncated and became "a//b".  Such a
path resolves correctly for a "real" filesystem, but not for a search in
the list of frozen modules.
2017-01-08 20:17:23 +11:00
Damien George 343b4189b0 py/mkrules.mk: Add MPY_CROSS_FLAGS option to pass flags to mpy-cross.
So that ports can pass their own custom options to mpy-cross.
2017-01-05 15:51:36 +11:00
Damien George 3f9c45efd1 py/asmarm: Fix assembler's PASS_EMIT constant name. 2017-01-03 15:40:50 +11:00
Damien George afc5063539 py/unicode: Comment-out unused function unichar_isprint. 2016-12-28 17:50:10 +11:00
Damien George ea6a958393 py/objint: Simplify mp_int_format_size and remove unreachable code.
One never needs to format integers with a base larger than 16 (but code
can be easily extended beyond this value if needed in the future).
2016-12-28 12:46:20 +11:00
Damien George 44bf8e1f2b py/mpprint: Add assertion for, and comment about, valid base values. 2016-12-28 12:45:33 +11:00
Damien George ca7af9a778 py/parsenum: Fix warning for signed/unsigned comparison. 2016-12-28 12:25:00 +11:00
Damien George 2d9440e2d1 py/mpz: Fix assertion in mpz_set_from_str which checks value of base. 2016-12-28 12:04:19 +11:00
Damien George c2dd494bd9 py/parsenum: Simplify and generalise decoding of digit values.
This function should be able to parse integers with any value for the
base, because it is called by int('xxx', base).
2016-12-28 12:02:49 +11:00
Paul Sokolovsky 25f44c19f1 cc3200: Re-add support for UART REPL (MICROPY_STDIO_UART setting).
UART REPL support was lost in os.dupterm() refactorings, etc. As
os.dupterm() is there, implement UART REPL support at the high level -
if MICROPY_STDIO_UART is set, make default boot.py contain os.dupterm()
call for a UART. This means that changing MICROPY_STDIO_UART value will
also require erasing flash on a module to force boot.py re-creation.
2016-12-27 01:05:37 +03:00
Paul Sokolovsky cf96be60dc py/misc.h: Typo fix in comment. 2016-12-27 01:05:30 +03:00
Damien George c305ae3243 py/lexer: Permanently disable the mp_lexer_show_token function.
The lexer is very mature and this debug function is no longer used.  If
it's really needed one can uncomment it and recompile.
2016-12-22 10:49:54 +11:00
Damien George f4aebafe7a py/lexer: Remove unnecessary check for EOF in lexer's next_char func.
This check always fails (ie chr0 is never EOF) because the callers of this
function never call it past the end of the input stream.  And even if they
did it would be harmless because 1) reader.readbyte must continue to
return an EOF char if the stream is exhausted; 2) next_char would just
count the subsequent EOF's as characters worth 1 column.
2016-12-22 10:39:06 +11:00
Damien George b9c4783273 py/lexer: Remove unreachable code in string tokeniser. 2016-12-22 10:37:13 +11:00
Damien George adccafb42a tests/basics/lexer: Add a test for newline-escaping within a string. 2016-12-22 10:32:06 +11:00
Paul Sokolovsky d02f6a9956 extmod/modutimeq: Refactor into optimized class.
import utimeq, utime
    # Max queue size, the queue allocated statically on creation
    q = utimeq.utimeq(10)
    q.push(utime.ticks_ms(), data1, data2)
    res = [0, 0, 0]
    # Items in res are filled up with results
    q.pop(res)
2016-12-22 00:29:32 +03:00
Damien George 46a6592f9a py/emitglue: Refactor to remove assert(0), to improve coverage. 2016-12-21 11:52:05 +11:00
Damien George e4af712125 py/objint: Rename mp_obj_int_as_float to mp_obj_int_as_float_impl.
And also simplify it to remove the check for small int.  This can be done
because this function is only ever called if the argument is not a small
int.
2016-12-21 11:46:27 +11:00
Damien George 7318949c46 py/modbuiltins: Remove unreachable code. 2016-12-20 14:00:59 +11:00
Damien George de9cd00b39 py/compile: Add an extra pass for Xtensa inline assembler.
It needs an extra pass to compute the size of the constant table for the
l32r instructions.
2016-12-19 17:42:25 +11:00
Damien George 7f1da0a03b py: Add MICROPY_KBD_EXCEPTION config option to provide mp_kbd_exception.
Defining and initialising mp_kbd_exception is boiler-plate code and so the
core runtime can provide it, instead of each port needing to do it
themselves.

The exception object is placed in the VM state rather than on the heap.
2016-12-15 13:00:19 +11:00
Paul Sokolovsky 403c93053e py/mpconfig.h: Enable MICROPY_PY_SYS_EXIT by default.
sys.exit() is an important function to terminate a program. In particular,
the testsuite relies on it to skip tests (i.e. any other functionality may
be disabled, but sys.exit() is required to at least report that properly).
2016-12-14 21:22:05 +03:00
Damien George e8f2db7da3 py/runtime: Zero out fs_user_mount array in mp_init.
There's no need to force ports to copy-and-paste this initialisation
code.  If FSUSERMOUNT is enabled then this zeroing out must be done.
2016-12-14 11:40:11 +11:00
Damien George e83f140463 py/mpz: Remove unreachable code in mpn_or_neg functions. 2016-12-14 10:39:41 +11:00
Damien George d9047d3c8a py/builtinimport: Support importing packages from compiled .mpy files.
This patch ensures that __init__.mpy files are imported if their
containing directory is imported as a package.
2016-12-13 15:09:48 +11:00
Damien George a3c61004c2 py/binary: Do zero extension when storing a value larger than word size. 2016-12-12 15:00:06 +11:00
Paul Sokolovsky 9d787de2a1 py/objint: from_bytes, to_bytes: Require byteorder arg, require "little".
CPython requires byteorder arg, make uPy compatible. As we support only
"little", error out on anything else.
2016-12-09 21:15:16 +03:00
Damien George 93ee6603b1 py/asm: Fix x86 and ARM assemblers due to recent code refactoring. 2016-12-09 22:54:45 +11:00
Damien George 155fdc74d5 py/asm: Remove need for dummy_data when doing initial assembler passes.
For all but the last pass the assembler only needs to count how much space
is needed for the machine code, it doesn't actually need to emit anything.
The dummy_data just uses unnecessary RAM and without it the code is not
any more complex (and code size does not increase for Thumb and Xtensa
archs).
2016-12-09 22:50:58 +11:00
Damien George e920bab976 py/emitinline: Move common code for end of final pass to compiler.
This patch moves some common code from the individual inline assemblers to
the compiler, the code that calls the emit-glue to assign the machine code
to the functions scope.
2016-12-09 21:23:17 +11:00
Damien George dd53b12193 py/emitinline: Move inline-asm align and data methods to compiler.
These are generic methods that don't depend on the architecture and so
can be handled directly by the compiler.
2016-12-09 20:54:54 +11:00
Damien George a7fd786a1f py/emitinline: Embed entire asm struct instead of a pointer to it.
This reduces fragmentation, and memory use by 1 word.  But more
importantly it means the emit_inline_asm_t struct now "derives" from
mp_asm_base.
2016-12-09 20:35:21 +11:00
Damien George f76b1bfa9f py: Add inline Xtensa assembler.
This patch adds the MICROPY_EMIT_INLINE_XTENSA option, which, when
enabled, allows the @micropython.asm_xtensa decorator to be used.

The following opcodes are currently supported (ax is a register, a0-a15):

    ret_n()
    callx0(ax)
    j(label)
    jx(ax)

    beqz(ax, label)
    bnez(ax, label)
    mov(ax, ay)
    movi(ax, imm) # imm can be full 32-bit, uses l32r if needed

    and_(ax, ay, az)
    or_(ax, ay, az)
    xor(ax, ay, az)
    add(ax, ay, az)
    sub(ax, ay, az)
    mull(ax, ay, az)

    l8ui(ax, ay, imm)
    l16ui(ax, ay, imm)
    l32i(ax, ay, imm)
    s8i(ax, ay, imm)
    s16i(ax, ay, imm)
    s32i(ax, ay, imm)
    l16si(ax, ay, imm)
    addi(ax, ay, imm)

    ball(ax, ay, label)
    bany(ax, ay, label)
    bbc(ax, ay, label)
    bbs(ax, ay, label)
    beq(ax, ay, label)
    bge(ax, ay, label)
    bgeu(ax, ay, label)
    blt(ax, ay, label)
    bnall(ax, ay, label)
    bne(ax, ay, label)
    bnone(ax, ay, label)

Upon entry to the assembly function the registers a0, a12, a13, a14 are
pushed to the stack and the stack pointer (a1) decreased by 16.  Upon
exit, these registers and the stack pointer are restored, and ret.n is
executed to return to the caller (caller address is in a0).

Note that the ABI for the Xtensa emitters is non-windowing.
2016-12-09 17:07:38 +11:00
Damien George ad297a1950 py: Allow inline-assembler emitter to be generic.
This patch refactors some code so that it is easier to integrate new
inline assemblers for different architectures other than ARM Thumb.
2016-12-09 17:06:21 +11:00
Damien George 8e5aced1fd py: Integrate Xtensa assembler into native emitter.
The config option MICROPY_EMIT_XTENSA can now be enabled to target the
Xtensa architecture with @micropython.native and @micropython.viper
decorators.
2016-12-09 16:51:49 +11:00
Damien George fcac4b07f1 py/asmxtensa: Add low-level Xtensa assembler. 2016-12-09 16:51:49 +11:00
Damien George 81316fa411 py/asmbase: Add MP_PLAT_COMMIT_EXEC option for handling exec code.
If a port defines MP_PLAT_COMMIT_EXEC then this function is used to turn
RAM data into executable code.  For example a port may want to write the
data to flash for execution.  The function must return a pointer to the
executable data.
2016-12-09 16:51:49 +11:00
Damien George c8746e1e72 py: Move arch-specific assembler macros from emitnative to asmXXX.h. 2016-12-09 16:51:49 +11:00
Damien George c2713592bc py/emit.h: Remove long-obsolete declarations for cpython emitter. 2016-12-09 13:28:25 +11:00
Damien George 080a78b15e py/compile: Simplify configuration of native emitter. 2016-12-07 11:17:17 +11:00
Damien George 304cfda8c4 py/stream: Move ad-hoc ioctl constants to stream.h and rename them.
The constants MP_IOCTL_POLL_xxx, which were stmhal-specific, are moved
from stmhal/pybioctl.h (now deleted) to py/stream.h.  And they are renamed
to MP_STREAM_POLL_xxx to be consistent with other such constants.

All uses of these constants have been updated.
2016-12-02 16:37:29 +11:00
Damien George 63e82dcdfe py/asmthumb: Fix build for F7 MCUs after recent code refactoring. 2016-11-30 00:11:25 +11:00
Damien George 612599587b py: Factor out common code from assemblers into asmbase.[ch].
All assemblers should "derive" from mp_asm_base_t.
2016-11-28 09:24:50 +11:00
Damien George e6cf5fb2cc py/compile: Remove comment about TODO for short circuiting for if-stmt.
Short circuiting is handled correctly by c_if_cond, and constants within
short-circuit expressions are optimised by the parser.
2016-11-26 16:15:55 +11:00
Paul Sokolovsky 037e6912c6 py/objtype: Implement __call__ handling for an instance w/o heap alloc.
By refactoring and reusing code from objboundmeth.
2016-11-22 01:33:55 +03:00
Paul Sokolovsky 8f5bc3ffc0 stmhal/moduselect: Move to extmod/ for reuse by other ports. 2016-11-21 00:05:56 +03:00
Damien George 5bdf1650de py/lexer: Make lexer use an mp_reader as its source. 2016-11-16 18:35:01 +11:00
Damien George 66d955c218 py/lexer: Rewrite mp_lexer_new_from_fd in terms of mp_reader. 2016-11-16 18:13:51 +11:00
Damien George e5ef15a9d7 py/lexer: Provide generic mp_lexer_new_from_file based on mp_reader.
If a port defines MICROPY_READER_POSIX or MICROPY_READER_FATFS then
lexer.c now provides an implementation of mp_lexer_new_from_file using
the mp_reader_new_file function.
2016-11-16 18:13:51 +11:00
Damien George 511c083811 py/lexer: Rewrite mp_lexer_new_from_str_len in terms of mp_reader_mem. 2016-11-16 18:13:50 +11:00
Damien George 6b239c271c py: Factor out persistent-code reader into separate files.
Implementations of persistent-code reader are provided for POSIX systems
and systems using FatFS.  Macros to use these are MICROPY_READER_POSIX and
MICROPY_READER_FATFS respectively.  If an alternative implementation is
needed then a port can define the function mp_reader_new_file.
2016-11-16 18:13:50 +11:00
Damien George 6810f2c134 py: Factor persistent code load/save funcs into persistentcode.[ch]. 2016-11-16 16:14:14 +11:00
Damien George 9b525134d1 py/parse: Add code to fold logical constants in or/and/not operations.
Adds about 200 bytes to the code size when constant folding is enabled.
2016-11-15 16:48:49 +11:00
Damien George ed9c93f0f1 py/parse: Make mp_parse_node_new_leaf an inline function.
It is split into 2 functions, one to make small ints and the other to make
a non-small-int leaf node.  This reduces code size by 32 bytes on
bare-arm, 64 bytes on unix (x64-64) and 144 bytes on stmhal.
2016-11-15 16:48:48 +11:00
Damien George b0cbfb0492 py/parse: Move function to check for const parse node to parse.[ch]. 2016-11-15 16:48:48 +11:00
Damien George 659b06b250 py/*.mk: Replace uses of 'sed' with $(SED). 2016-11-15 16:09:43 +11:00
Dave Hylands 0400fa45ba py/mkrules.mk: Rework find command so it works on OSX.
The Mac version of find doesn't support -printf, so this changes
things to use sed to strip off the leading path element instead.
2016-11-15 16:07:48 +11:00
Paul Sokolovsky a0b2c6ad32 py/runtime: mp_resume: Fix exception handling for nanbox port. 2016-11-15 01:41:22 +03:00
Paul Sokolovsky 79d996a57b py/runtime: mp_resume: Handle exceptions in Python __next__().
This includes StopIteration and thus are important to make Python-coded
iterables work with yield from/await.

Exceptions in Python send() are still not handled and left for future
consideration and optimization.
2016-11-15 01:10:34 +03:00
Paul Sokolovsky c3d96d387c py/objexcept: Allow clearing traceback with 'exc.__traceback__ = None'.
We allow 'exc.__traceback__ = None' assignment as a low-level optimization
of pre-allocating exception instance and raising it repeatedly - this
avoids memory allocation during raise. However, uPy will keep adding
traceback entries to such exception instance, so before throwing it,
traceback should be cleared like above.

'exc.__traceback__ = None' syntax is CPython compatible. However, unlike
it, reading that attribute or setting it to any other value is not
supported (and not intended to be supported, again, the only reason for
adding this feature is to allow zero-memalloc exception raising).
2016-11-14 02:29:09 +03:00
Paul Sokolovsky 59a1201da9 all: Remove readall() method, which is equivalent to read() w/o args.
Its addition was due to an early exploration on how to add CPython-like
stream interface. It's clear that it's not needed and just takes up
bytes in all ports.
2016-11-14 00:24:22 +03:00
Damien George 0f3388de1e py/emitnative: Fix native import emitter when in viper mode. 2016-11-10 22:53:04 +11:00
Damien George fcda6a2a78 py: Strip leading dirs from frozen mpy files, so any path can be used.
With this patch one can now do "make FROZEN_MPY_DIR=../../frozen" to
specify a directory containing scripts to be frozen (as well as absolute
paths).

The compiled .mpy files are now stored in $(BUILD)/frozen_mpy/.
2016-11-08 14:36:06 +11:00
Damien George bdf33bc136 py: Move frozen bytecode Makefile rules from ports to common mk files.
Now, to use frozen bytecode all a port needs to do is define
FROZEN_MPY_DIR to the directory containing the .py files to freeze, and
define MICROPY_MODULE_FROZEN_MPY and MICROPY_QSTR_EXTRA_POOL.
2016-11-08 14:28:30 +11:00
Damien George 561844f3ba py: Add MICROPY_FLOAT_CONST macro for defining float constants.
All float constants in the core should use this macro to prevent
unnecessary creation of double-precision floats, which makes code less
efficient.
2016-11-03 12:33:01 +11:00
Colin Hogben 828df54bfe py: Change config default so m_malloc0 uses memset if GC not enabled.
With MICROPY_ENABLE_GC set to false the alternate memory manager may not
clear all memory that is allocated, so it must be cleared in m_malloc0.
2016-11-03 10:16:31 +11:00
Colin Hogben f9b6b37cf6 py: Fix wrong assumption that m_renew will not move if shrinking
In both parse.c and qstr.c, an internal chunking allocator tidies up
by calling m_renew to shrink an allocated chunk to the size used, and
assumes that the chunk will not move.  However, when MICROPY_ENABLE_GC
is false, m_renew calls the system realloc, which does not guarantee
this behaviour.  Environments where realloc may return a different
pointer include:

(1) mbed-os with MBED_HEAP_STATS_ENABLED (which adds a wrapper around
malloc & friends; this is where I was hit by the bug);

(2) valgrind on linux (how I diagnosed it).

The fix is to call m_renew_maybe with allow_move=false.
2016-11-02 23:15:41 +11:00
Jan Pochyla ffb04a5845 unix: fix symbol references for x86 Mac 2016-11-02 00:42:04 +03:00
Pavol Rusnak 7ffc959c00 py: remove asserts that are always true in emitbc.c 2016-10-31 23:21:22 +03:00
Pavol Rusnak 3679ee9b52 py: fix null pointer dereference in mpz.c, fix missing va_end in warning.c 2016-10-31 23:21:15 +03:00
Fabio Utzig 8908e505ce py/sequence: Fix reverse slicing of lists. 2016-10-30 15:54:19 -02:00
Paul Sokolovsky 76146b3d9a extmod/utime_mphal: Allow ticks functions period be configurable by a port.
Using MICROPY_PY_UTIME_TICKS_PERIOD config var.
2016-10-30 03:02:07 +03:00
Paul Sokolovsky 8a49905a2f py/stream: Typo fix in comment. 2016-10-27 22:13:45 +03:00
Paul Sokolovsky f00ecdb54d extmod/moduos_dupterm: Renamed to uos_dupterm.
As part of file naming clean up (moduos_dupterm doesn't implement a
full module, so should skip "mod" prefix, similar to other files in
extmod/).
2016-10-26 02:08:37 +03:00
Damien George 5076e5c339 py: Add "delattr" builtin, conditional on MICROPY_CPYTHON_COMPAT. 2016-10-24 13:50:03 +11:00
Damien George bdb0d2d0bc py/modbuiltins: Add builtin "slice", pointing to existing slice type. 2016-10-24 13:35:39 +11:00
Paul Sokolovsky 3730090d8f py/{modbuiltins,obj}: Use MP_PYTHON_PRINTER where possible. 2016-10-22 01:07:07 +03:00
Erik Moqvist f64e806f50 lib/utils/pyhelp.c: Use mp_printf() instead of printf()
This patch introduces MP_PYTHON_PRINTER for general use.
2016-10-21 18:30:58 +11:00
Damien George 571e6f26db py: Specialise builtin funcs to use separate type for fixed arg count.
Builtin functions with a fixed number of arguments (0, 1, 2 or 3) are
quite common.  Before this patch the wrapper for such a function cost
3 machine words.  After this patch it only takes 2, which can reduce the
code size by quite a bit (and pays off even more, the more functions are
added).  It also makes function dispatch slightly more efficient in CPU
usage, and furthermore reduces stack usage for these cases.  On x86 and
Thumb archs the dispatch functions are now tail-call optimised by the
compiler.

The bare-arm port has its code size increase by 76 bytes, but stmhal drops
by 904 bytes.  Stack usage by these builtin functions is decreased by 48
bytes on Thumb2 archs.
2016-10-21 16:26:01 +11:00
Damien George 4ebdb1f2b2 py: Be more specific with MP_DECLARE_CONST_FUN_OBJ macros.
In order to have more fine-grained control over how builtin functions are
constructed, the MP_DECLARE_CONST_FUN_OBJ macros are made more specific,
with suffix of _0, _1, _2, _3, _VAR, _VAR_BETEEN or _KW.  These names now
match the MP_DEFINE_CONST_FUN_OBJ macros.
2016-10-21 16:26:01 +11:00
Paul Sokolovsky b440307b4a py/py.mk: Automatically add frozen.c to source list if FROZEN_DIR is defined.
Now frozen modules generation handled fully by py.mk and available for reuse
by any port.
2016-10-21 01:08:43 +03:00
Damien George 7d0d7215d2 py: Use mp_raise_msg helper function where appropriate.
Saves the following number of bytes of code space: 176 for bare-arm, 352
for minimal, 272 for unix x86-64, 140 for stmhal, 120 for esp8266.
2016-10-17 12:17:37 +11:00
Damien George 2750a7b38e py/objdict: Actually provide the key that failed in KeyError exception.
The failed key is available as exc.args[0], as per CPython.
2016-10-17 12:00:19 +11:00
Damien George a3edeb9ea5 py/objdict: Fix optimisation for allocating result in fromkeys.
Iterables don't respond to __len__, so call __len__ on the original
argument.
2016-10-17 11:58:57 +11:00
Paul Sokolovsky a97284423e extmod/utime_mphal: Factor out implementations in terms of mp_hal_* for reuse.
As long as a port implement mp_hal_sleep_ms(), mp_hal_ticks_ms(), etc.
functions, it can just use standard implementations of utime.sleel_ms(),
utime.ticks_ms(), etc. Python-level functions.
2016-10-14 20:14:01 +03:00
Damien George 824f5c5a32 py/vstr: Combine vstr_new_size with vstr_new since they are rarely used.
Now there is just one function to allocate a new vstr, namely vstr_new
(in addition to vstr_init etc).  The caller of this function should know
what initial size to allocate for the buffer, or at least have some policy
or config option, instead of leaving it to a default (as it was before).
2016-10-14 16:46:34 +11:00
Damien George e93c1ca5da extmod/modujson: Implement ujson.load() to load JSON from a stream.
This refactors ujson.loads(s) to behave as ujson.load(StringIO(s)).

Increase in code size is: 366 bytes for unix x86-64, 180 bytes for
stmhal, 84 bytes for esp8266.
2016-10-13 11:46:14 +11:00
Damien George af8d791bd0 esp8266: Enable importing of precompiled .mpy files. 2016-10-12 11:03:58 +11:00
Damien George 31101d91ce py/lexer: Remove unnecessary code, and unreachable code.
Setting emit_dent=0 is unnecessary because arriving in that part of the
if-logic will guarantee that emit_dent is already zero.

The block to check indent_top(lex)>0 is unreachable because a newline is
always inserted an the end of the input stream, and hence dedents are
always processed before EOF.
2016-10-12 11:00:17 +11:00
Damien George deaa57acf3 py/compile: Remove debugging code for compiler dispatch.
It was a relic from the days of developing the compiler and is no longer
needed, and it's impossible to trigger via a test.
2016-10-12 10:20:48 +11:00
Damien George 6dff3df501 py/objint: Use size_t for arguments that measure bytes/sizes. 2016-10-11 13:20:11 +11:00
Damien George 8bb7d958f1 py: Factor duplicated function to calculate size of formatted int. 2016-10-11 13:11:32 +11:00
Damien George df3e5d2b2f py/mpz: Use assert to verify mpz does not have a fixed digit buffer. 2016-10-11 13:00:56 +11:00
Damien George 48874942f0 py/mpz: In divmod, replace check for rhs!=0 with assert.
The check for division by zero is made by the caller of this function.
2016-10-11 13:00:01 +11:00
Damien George e49153fb98 py/compile: Remove unreachable code. 2016-10-11 12:29:54 +11:00
Damien George 7dc2345715 py/modmicropython: Add micropython.opt_level([value]) function.
This allows to get/set at runtime the optimisation level of the compiler.
2016-10-11 10:56:22 +11:00
Paul Sokolovsky d22a04d9c4 py/objstringio: Add readinto() method.
Also, drop deprecated (as for MicroPython) readall() method.
2016-10-09 11:56:11 +03:00
Damien George 3a0a771730 py: Add mp_raise_OSError(errno) helper function.
This is an often used code pattern, and its use reduces code size of the
core by about 100 bytes.
2016-10-07 13:31:59 +11:00
Damien George dffa383b06 py/modstruct: Remove unreachable code, and add comment about CPy diff.
The deleted code is unreachable because calcsize_items guarantees that
num_items corresponds to how many items there are in fmt to unpack.
2016-10-07 12:54:14 +11:00
Damien George 8de270b4fc py/objbool: Make a slight simplification of bool constructor.
Reduces code size for some archs.
2016-09-30 17:02:07 +10:00
Damien George eca1408f16 py/objbool: Defer bool's unary op implementation to small int.
Similar to how binary op already works.  Common unary operations already
have fast paths for bool so there's no need to have explicit handling of
ops in bool_unary_op, especially since they have the same behaviour as
integers.
2016-09-30 17:02:06 +10:00
Damien George 3be4f886ce py/argcheck: Simplify if-chain so that the last one is the default. 2016-09-30 16:45:43 +10:00
Damien George 216a711cd4 py/compile: Fix typo when checking for parse-node kind. 2016-09-30 14:48:06 +10:00
Damien George 0d10517a45 py/scope: Factor common code to find locals and close over them.
Saves 50-100 bytes of code.
2016-09-30 13:53:00 +10:00
Damien George d5495966ce py/scope: Shrink scope_t struct by 1 machine word.
On 32-bit archs this makes the scope_t struct 48 bytes in size, which fits
in 3 GC blocks (previously it used 4 GC blocks).  This will lead to some
savings when compiling scripts because there are usually quite a few scopes,
one for each function and class.

Note that qstrs will fit in 16 bits, this assumption is made in a few other
places.
2016-09-30 12:45:00 +10:00
Damien George 3dea8c9e92 py/scope: Use lookup-table to determine a scope's simple name.
Generates slightly smaller and more efficient code.
2016-09-30 12:34:05 +10:00
Damien George b32c01b748 py/compile: Fix async-for/async-with to work with simpler exc on stack.
There is now just the exception instance on the stack when an exception is
raised, not the full (type, exc, traceback).
2016-09-28 11:52:13 +10:00
Damien George 2c7716fed0 py/objset: Ensure that use of frozenset.update raises an exception. 2016-09-28 11:06:18 +10:00
Damien George dd4135aeaf py/objset: Use mp_check_self() to check args of set/frozenset methods.
Following how other objects work, set/frozenset methods should use the
mp_check_self() macro to check the type of the self argument, because in
most cases this check can be a null operation.

Saves about 100-180 bytes of code for builds with set and frozenset
enabled.
2016-09-28 10:55:23 +10:00
Damien George 0c595fa094 py/objfun: Use if instead of switch to check return value of VM execute.
It's simpler and improves code coverage.
2016-09-27 23:08:10 +10:00
Damien George c71edaed73 py/objfun: Remove unnecessary check for viper fun with 5 or more args.
The native emitter/compiler restricts viper functions to 4 args, so there
is no need for an extra check in the dynamic dispatch.
2016-09-27 23:05:51 +10:00
Damien George 7385b018ed py/emitbc: Remove/refactor unreachable code, to improve coverage. 2016-09-27 15:46:50 +10:00
Damien George 897129a7ff py/objstr: Remove unreachable function used only for terse error msgs. 2016-09-27 15:45:42 +10:00
Damien George 791b65f4b2 py/modmicropython: Add micropython.const, alias for identity function.
Having a micropython.const identity function, and writing "from micropython
import const" at the start of scripts that use the const feature, allows to
write scripts which are compatible with CPython, and with uPy builds that
don't include const optimisation.

This patch adds such a function and updates the tests to do the import.
2016-09-27 13:34:21 +10:00
Damien George 71fec076dc py/vm: Use MP_OBJ_FROM_PTR to cast a type to an object. 2016-09-27 13:21:23 +10:00
Damien George f040685b0c py: Only store the exception instance on Py stack in bytecode try block.
When an exception is raised and is to be handled by the VM, it is stored
on the Python value stack so the bytecode can access it.  CPython stores
3 objects on the stack for each exception: exc type, exc instance and
traceback.  uPy followed this approach, but it turns out not to be
necessary.  Instead, it is enough to store just the exception instance on
the Python value stack.  The only place where the 3 values are needed
explicitly is for the __exit__ handler of a with-statement context, but
for these cases the 3 values can be extracted from the single exception
instance.

This patch removes the need to store 3 values on the stack, and instead
just stores the exception instance.

Code size is reduced by about 50-100 bytes, the compiler and VM are
slightly simpler, generate bytecode is smaller (by 2 bytes for each try
block), and the Python value stack is reduced in size for functions that
handle exceptions.
2016-09-27 12:37:21 +10:00
Paul Sokolovsky 9cc8ec843e py/py.mk: Add support for building modussl_mbedtls. 2016-09-23 14:30:46 +03:00
Damien George 6d310a5552 py/parse: Only replace constants that are standalone identifiers.
This fixes constant substitution so that only standalone identifiers are
replaced with their constant value (if they have one).  I.e. don't
replace NAME in expressions like obj.NAME or NAME = expr.
2016-09-23 17:23:16 +10:00
Damien George 7df9291b6c py: Update opcode format table because 3 opcodes were removed, 1 added.
LIST_APPEND, MAP_ADD and SET_ADD have been removed, and STORE_COMP has
been added in adaf0d865c.
2016-09-23 12:48:57 +10:00
Damien George e97df97600 py: Shrink mp_arg_t struct by using reduced-size integer members.
qstrs ids are restricted to fit within 2 bytes already (eg in persistent
bytecode) so it's safe to use a uint16_t to store them in mp_arg_t.  And
the flags member only needs a maximum of 2 bytes so can also use uint16_t.

Savings in code size can be significant when many mp_arg_t structs are
used for argument parsing.  Eg, this patch reduces stmhal by 480 bytes.
2016-09-23 12:13:51 +10:00
Damien George 6c79980b0e py/py.mk: Suppress some compiler warnings when building berkeley-db. 2016-09-22 11:09:21 +10:00
Damien George 79ec869f95 py/stream: Remove unnecessary check for NULL return from vstr_extend.
vstr_extend will now only return NULL if the vstr is a fixed buffer, which
in this case it is not.
2016-09-22 10:50:47 +10:00
Damien George 93c4a6a3f7 all: Remove 'name' member from mp_obj_module_t struct.
One can instead lookup __name__ in the modules dict to get the value.
2016-09-22 00:23:16 +10:00
Paul Sokolovsky 7ea3fa2641 py/builtinimport: Fix nanbox build after change to better handle -m modules. 2016-09-20 17:55:42 +03:00
Delio Brignoli 21c719bd0a builtinimport: add the module specified by -m to sys.modules as '__main__' 2016-09-20 14:01:31 +03:00
Damien George fbddea929d py/showbc: Make printf's go to the platform print stream.
The system printf is no longer used by the core uPy code.  Instead, the
platform print stream or DEBUG_printf is used.  Using DEBUG_printf in the
showbc functions would mean that the code can't be tested by the test
suite, so use the normal output instead.

This patch also fixes parsing of bytecode-line-number mappings.
2016-09-20 11:30:54 +10:00
Damien George e60835bac5 py/qstr: Remove a comment.
qstrs are always null terminated so qstr_str will stay as part of the API.
2016-09-19 13:18:54 +10:00
Damien George 8dd5960ac0 py/objnone: Use mp_generic_unary_op instead of custom one. 2016-09-19 12:28:55 +10:00
Damien George 5da0d29d3c py/vstr: Remove vstr.had_error flag and inline basic vstr functions.
The vstr.had_error flag was a relic from the very early days which assumed
that the malloc functions (eg m_new, m_renew) returned NULL if they failed
to allocate.  But that's no longer the case: these functions will raise an
exception if they fail.

Since it was impossible for had_error to be set, this patch introduces no
change in behaviour.

An alternative option would be to change the malloc calls to the _maybe
variants, which return NULL instead of raising, but then a lot of code
will need to explicitly check if the vstr had an error and raise if it
did.

The code-size savings for this patch are, in bytes: bare-arm:188,
minimal:456, unix(NDEBUG,x86-64):368, stmhal:228, esp8266:360.
2016-09-19 12:28:55 +10:00
Damien George adaf0d865c py: Combine 3 comprehension opcodes (list/dict/set) into 1.
With the previous patch combining 3 emit functions into 1, it now makes
sense to also combine the corresponding VM opcodes, which is what this
patch does.  This eliminates 2 opcodes which simplifies the VM and reduces
code size, in bytes: bare-arm:44, minimal:64, unix(NDEBUG,x86-64):272,
stmhal:92, esp8266:200.  Profiling (with a simple script that creates many
list/dict/set comprehensions) shows no measurable change in performance.
2016-09-19 12:28:03 +10:00
Damien George a5624bf381 py: Combine 3 comprehension emit functions (list/dict/set) into 1.
The 3 kinds of comprehensions are similar enough that merging their emit
functions reduces code size.  Decreases in code size in bytes are:
bare-arm:24, minimal:96, unix(NDEBUG,x86-64):328, stmhal:80, esp8266:76.
2016-09-19 12:23:31 +10:00
Paul Sokolovsky f28efa1971 py: Move frozen modules rules from esp8266 port for reuse across ports.
A port now just needs to define FROZEN_DIR var and add $(BUILD)/frozen.c
to SRC_C to support frozen modules.
2016-09-17 21:00:40 +03:00
Damien George f84b341618 py/objnone: Remove unnecessary handling of MP_UNARY_OP_BOOL.
bool(None) has a fast path in mp_obj_is_true so doesn't need to be
handled in none_unary_op.  The only caveat is that subclassing may
bypass the mp_obj_is_true function, but actually you aren't allowed to
subclass classes that have singleton instances like NoneType (see
https://mail.python.org/pipermail/python-dev/2002-March/020822.html for
reference on this point).
2016-09-16 12:30:09 +10:00
Chris Packham a50b26e4b0 py/makeqstrdefs.py: Use python 2.6 syntax for set creation.
py/makeqstrdefs.py declares that it works with python 2.6 however the
syntax used to initialise of a set with values was only added in python
2.7. This leads to build failures when the host system doesn't have
python 2.7 or newer.

Instead of using the new syntax pass a list of initial values through
set() to achieve the same result. This should work for python versions
from at least 2.6 onwards.

Helped-by: Thomas Petazzoni <thomas.petazzoni@free-electrons.com>
Signed-off-by: Chris Packham <judge.packham@gmail.com>
2016-09-09 23:01:23 +10:00
Antonin ENFRUN f3b19ef634 py/asmthumb: Flush D-cache, and invalidate I-cache on STM32F7.
Tested on a STM32F7DISCO at 216MHz.  All tests generating code (inlineasm,
native, viper) now pass, except pybnative/while.py, but that's because
there is no LED(2).
2016-09-09 14:48:15 +10:00
Delio Brignoli e2ac8bb3f1 py: Add MICROPY_USE_INTERNAL_PRINTF option, defaults to enabled.
This new config option allows to control whether MicroPython uses its own
internal printf or not (if not, an external one should be linked in).
Accompanying this new option is the inclusion of lib/utils/printf.c in the
core list of source files, so that ports no longer need to include it
themselves.
2016-09-05 12:18:53 +10:00
Chris Packham 8c6856d2e7 py/emitglue.c: provide mp_raw_code_load_file for any unix architecture
Signed-off-by: Chris Packham <chris.packham@alliedtelesis.co.nz>
2016-09-04 16:17:46 +10:00
Damien George 5f3bda422a py: If str/bytes hash is 0 then explicitly compute it. 2016-09-02 14:49:50 +10:00
Damien George f127bef3e4 py/makeqstrdata.py: Compute the qstr hash from bytes, not characters. 2016-09-02 14:32:47 +10:00
Delio Brignoli f98bb2ddcb py/mpprint: Fail an assertion with unsupported format specifiers.
Arguments of an unknown type cannot be skipped and continuing to parse a
format string after encountering an unknown format specifier leads to
undefined behaviour.  This patch helps to find use of unsupported formats.
2016-09-01 18:09:44 +10:00
Damien George 0823c1baf8 extmod: Add machine_spi with generic SPI C-protocol and helper methods.
The idea is that all ports can use these helper methods and only need to
provide initialisation of the SPI bus, as well as a single transfer
function.  The coding pattern follows the stream protocol and helper
methods.
2016-09-01 15:07:20 +10:00
Paul Sokolovsky 1f61fe07a2 py/mkrules.mk: Allow to override name of libmicropython.a
Or alternatively, refer to an exact library file, not just phony target
"lib".
2016-08-30 00:59:17 +03:00
Damien George f4ee9f8853 py/bc.h: Rename _mp_code_state to _mp_code_state_t.
This rename was missed in the previous patch.
2016-08-27 23:23:51 +10:00
Damien George 581a59a456 py: Rename struct mp_code_state to mp_code_state_t.
Also at _t to mp_exc_stack pre-declaration in struct typedef.
2016-08-27 23:21:00 +10:00
Damien George 26295e04ff py/emitglue: Use more compact mp_raise_ValueError function. 2016-08-26 23:45:07 +10:00
Damien George fe3cc5bb53 py/modstruct: Use more compact mp_raise_ValueError function.
Saves a few bytes of code size.
2016-08-26 23:42:40 +10:00
Damien George 24df30c133 py/compile: Don't compile assert statements when optimisations enabled.
As per CPython.
2016-08-26 22:28:22 +10:00
Damien George 5ffe1d8dc0 py/gc: Add MICROPY_GC_CONSERVATIVE_CLEAR option to always zero memory.
There can be stray pointers in memory blocks that are not properly zero'd
after allocation.  This patch adds a new config option to always zero all
allocated memory (via gc_alloc and gc_realloc) and hence help to eliminate
stray pointers.

See issue #2195.
2016-08-26 15:35:26 +10:00
Paul Sokolovsky c428367543 extmod/modubinascii: Make crc32() support configurable.
Disable by default, enable in unix port.
2016-08-24 18:28:43 +03:00
Krzysztof Blazewicz 6562076454 py/stream.c: use mp_obj_get_type in mp_get_stream_raise
In current state `mp_get_stream_raise` assumes that `self_in` is an object
and always performs a pointer derefence which may cause a segfault.

This function shall throw an exception whenever `self_in` does not implement
a stream protocol, that includes qstr's and numbers.

fixes #2331
2016-08-24 01:33:31 +03:00
Damien George 095e43a9a5 py/sequence: Allow to use bignums as indices in slice objects.
See issue #2264.
2016-08-15 23:26:34 +10:00
Damien George 41fceae559 py/obj.h: For obj reprs A,B,C use void* explicitly for mp_obj_t typedef.
The machine_ptr_t type is long obsolete as the type of mp_obj_t is now
defined by the object representation, ie by MICROPY_OBJ_REPR.  So just use
void* explicitly for the typedef of mp_obj_t.

If a port wants to use something different then they should define a new
object representation.
2016-08-15 10:56:55 +10:00
Damien George 2196799051 py/objstr: Use mp_raise_{Type,Value}Error instead of mp_raise_msg.
This patch does further refactoring using the new mp_raise_TypeError
and mp_raise_ValueError functions.
2016-08-14 16:51:54 +10:00
Damien George 1a0d3fd632 py/runtime.h: Move comment about mp_not_implemented to correct place. 2016-08-14 16:35:10 +10:00
Damien George 4aaa5adf9f py/objtuple: In tuple_cmp_helper, use mp_check_self instead of raising.
Only tuple, namedtuple and attrtuple use the tuple_cmp_helper function,
and they all have getiter=mp_obj_tuple_getiter, so the check here is only
to ensure that the self object is consistent.  Hence use mp_check_self.
2016-08-14 16:28:05 +10:00
Paul Sokolovsky c4a8004933 py: Get rid of assert() in method argument checking functions.
Checks for number of args removes where guaranteed by function descriptor,
self checking is replaced with mp_check_self(). In few cases, exception
is raised instead of assert.
2016-08-12 22:39:03 +03:00
Paul Sokolovsky 83e0ebabb4 py/objdict: Get rid of asserts (remove/replace with mp_check_self()). 2016-08-12 22:01:11 +03:00
Paul Sokolovsky 8c50f93a41 py/runtime.h: Define mp_check_self(pred) helper macro.
Indended to replace raw asserts in bunch of files. Expands to empty
if MICROPY_BUILTIN_METHOD_CHECK_SELF_ARG is defined, otehrwise by
default still to assert, though a particular port may define it to
something else.
2016-08-12 21:58:56 +03:00
Paul Sokolovsky 9e1b61dedd py/runtime: Factor out exception raising helpers.
Introduce mp_raise_msg(), mp_raise_ValueError(), mp_raise_TypeError()
instead of previous pattern nlr_raise(mp_obj_new_exception_msg(...)).
Save few bytes on each call, which are many.
2016-08-12 21:28:45 +03:00
Paul Sokolovsky 1bc2911174 py/mpconfig.h: Define MP_ALWAYSINLINE for reuse.
Similar to existing MP_NOINLINE.
2016-08-07 22:36:05 +03:00
Paul Sokolovsky 1563388001 py/objstr,objstrunicode: Fix inconistent #if indentation. 2016-08-07 15:24:57 +03:00
Paul Sokolovsky 56eb25f049 py/objstr: Make .partition()/.rpartition() methods configurable.
Default is disabled, enabled for unix port. Saves 600 bytes on x86.
2016-08-07 06:46:55 +03:00
Paul Sokolovsky 7fb31479bf py/mkrules.mk: Allow to add more items for "clean" target using CLEAN_EXTRA. 2016-08-04 23:46:08 +03:00
Paul Sokolovsky 0dfe849413 py/py.mk: Extra switches to build "embedded" BerkeleyDB BTree lib. 2016-07-31 00:39:09 +03:00
Paul Sokolovsky 61e77a4e88 py/mpconfig.h: Add MICROPY_STREAMS_POSIX_API setting.
To filter out even prototypes of mp_stream_posix_*() functions, which
require POSIX types like ssize_t & off_t, which may be not available in
some ports.
2016-07-30 20:05:56 +03:00
Paul Sokolovsky c8b80e4740 lib/embed/abort_: Implementation of abort_() function raising uPy exception.
Helpful when porting existing C libraries to MicroPython. abort()ing in
embedded environment isn't a good idea, so when compiling such library,
-Dabort=abort_ option can be given to redirect standard abort() to this
"safe" version.
2016-07-30 00:35:50 +03:00
Paul Sokolovsky 4f1b0292db py/stream: Add adapter methods with POSIX-compatible signatures.
Previoussly such read() and write() methods were used by modussl_axtls,
move to py/stream for reuse.
2016-07-30 00:25:06 +03:00
Paul Sokolovsky 3990b1715d py/objstringio: Implement MP_STREAM_SEEK ioctl and add seek() method. 2016-07-28 01:53:44 +03:00
Paul Sokolovsky f039ac5bd7 py/objstringio: Add MP_STREAM_FLUSH ioctl and flush() method.
No-op for this object.
2016-07-28 01:14:32 +03:00
Paul Sokolovsky a60b0263ba py/stream: Implement generic flush() method, in terms of C-level ioctl. 2016-07-27 00:39:10 +03:00
Paul Sokolovsky f2f761c0c3 py/stream: Stream module works with errno's, so should include mperrno.h. 2016-07-26 15:05:15 +03:00
Paul Sokolovsky ed1c194ebf py/objstrunicode: str_index_to_ptr: Implement positive indexing properly.
Order out-of-bounds check, completion check, and increment in the right way.
2016-07-25 19:28:04 +03:00
Paul Sokolovsky 6af90b2972 py/objstrunicode: str_index_to_ptr: Should handle bytes too.
There's single str_index_to_ptr() function, called for both bytes and
unicode objects, so should handle each properly.
2016-07-25 14:45:08 +03:00
Paul Sokolovsky 16f324641f py/stream.h: Remove dated comment of POSIX-specificity of EAGAIN.
We have adopted POSIX-compatible error numbers as MicroPython's native.
2016-07-25 00:47:00 +03:00
Paul Sokolovsky 1a7e28d8b7 py/stream.h: Move mp_stream_write_adaptor() inside ifdef block. 2016-07-25 00:16:51 +03:00
Paul Sokolovsky 918851e836 unix: Enable MICROPY_PY_STR_BYTES_CMP_WARN.
Also, fix a warning text (remove "duplicate" BytesWarning).
2016-07-22 00:52:07 +03:00
Paul Sokolovsky a1b442bc07 py/mpconfig.h: Fix description for MICROPY_PY_STR_BYTES_CMP_WARN. 2016-07-22 00:46:24 +03:00
Paul Sokolovsky 707cae7494 py/obj: Issue a warning when str and bytes objects are compared.
Something like:

if foo == "bar":

will be always false if foo is b"bar". In CPython, warning is issued if
interpreter is started as "python3 -b". In MicroPython,
MICROPY_PY_STR_BYTES_CMP_WARN setting controls it.
2016-07-22 00:34:34 +03:00
Dave Hylands 26b7d8a7be py: Fix nlrthumb.c when DEBUG=1 is defined 2016-07-21 00:54:21 +03:00
Paul Sokolovsky 93e353e384 py/gc: Implement GC running by allocation threshold.
Currently, MicroPython runs GC when it could not allocate a block of memory,
which happens when heap is exhausted. However, that policy can't work well
with "inifinity" heaps, e.g. backed by a virtual memory - there will be a
lot of swap thrashing long before VM will be exhausted. Instead, in such
cases "allocation threshold" policy is used: a GC is run after some number of
allocations have been made. Details vary, for example, number or total amount
of allocations can be used, threshold may be self-adjusting based on GC
outcome, etc.

This change implements a simple variant of such policy for MicroPython. Amount
of allocated memory so far is used for threshold, to make it useful to typical
finite-size, and small, heaps as used with MicroPython ports. And such GC policy
is indeed useful for such types of heaps too, as it allows to better control
fragmentation. For example, if a threshold is set to half size of heap, then
for an application which usually makes big number of small allocations, that
will (try to) keep half of heap memory in a nice defragmented state for an
occasional large allocation.

For an application which doesn't exhibit such behavior, there won't be any
visible effects, except for GC running more frequently, which however may
affect performance. To address this, the GC threshold is configurable, and
by default is off so far. It's configured with gc.threshold(amount_in_bytes)
call (can be queries without an argument).
2016-07-21 00:37:30 +03:00
Paul Sokolovsky 6aa7c805cc esp8266: Cache Xtensa-built libaxtls.a in local build dir.
Allows to build the library variant for other archs in parallel.
2016-07-16 04:56:23 +03:00
Paul Sokolovsky ad9b9c7621 py/stream: Implement 2- and 3-arg write() method as an extension to CPython.
3-arg form:

stream.write(data, offset, length)

2-arg form:

stream.write(data, length)

These allow efficient buffer writing without incurring extra memory
allocation for slicing or creating memoryview() object, what is
important for low-memory ports.

All arguments must be positional. It might be not so bad idea to standardize
on 3-arg form, but 2-arg case would need check and raising an exception
anyway then, so instead it was just made to work.
2016-07-14 01:44:50 +03:00
Paul Sokolovsky 20283aec10 extmod/modussl_axtls: Further changes to allow alternative SSL modules.
Make variable MICROPY_SSL_AXTLS=1 should be defined to activate modussl_axtls
and link with -laxtls.
2016-07-13 01:49:38 +03:00
Paul Sokolovsky e32d1e17bb extmod/modussl: Rename to modussl_axtls.c, to allow impl using other SSL libs. 2016-07-13 01:35:59 +03:00
Damien George 3593d8e10c py/nlrx64.S: Prefix mp_thread_get_state with an underscore on Mac. 2016-07-11 14:27:47 +01:00
Daniel Tralamazza 9626662819 qemu-arm: Enable gcc LTO option for nlrthumb.c
LTO can't "see" inside naked functions, but we can mark `nlr_push_tail` as used.
2016-07-11 12:04:56 +01:00
Paul Sokolovsky ec7fe92531 py/objarray: Split out header to allow direct access to object.
This follows source code/header file organization similar to few other
objects, and intended to be used only is special cases, where efficiency/
simplicity matters.
2016-07-06 18:19:27 +03:00
Paul Sokolovsky 426112ce88 extmod/moduos_dupterm: Reserve buffer bytearray object for dupterm.
Allocating it for each read/write operation is a memory fragmentation
hazard.
2016-07-04 13:32:30 +03:00
Paul Sokolovsky 737bd9c314 py/mpconfig.h: Mention MICROPY_PY_BTREE config option.
However, as it requires linking with external libraries, it actually
should be ste on Makefile level.
2016-07-02 14:57:42 +03:00
Paul Sokolovsky ae184cb9de py/builtinimport: Disable "imported as namespace package" warning.
Namespace packages are natural part of Python3, CPython3 doesn't have such
warning, it made sense only from point of view of Python2 legacy.
2016-07-02 14:45:49 +03:00
Paul Sokolovsky 749cbaca7f py/gc: Calculate (and report) maximum contiguous free block size.
Just as maximum allocated block size, it's reported in allocation units
(not bytes).
2016-07-01 00:09:55 +03:00
Paul Sokolovsky 6a6e0b7e05 py/gc: Be sure to count last allocated block at heap end in stats.
Previously, if there was chain of allocated blocks ending with the last
block of heap, it wasn't included in number of 1/2-block or max block
size stats.
2016-06-30 12:56:21 +03:00
Damien George 77e37ff98b py/mpthread: Include mpstate.h when defining GIL macros. 2016-06-28 11:28:52 +01:00
Damien George 94238d4ae5 py/nlrsetjmp: Update to take into account new location of nlr_top.
It's now accessed via the MP_STATE_THREAD macro.
2016-06-28 11:28:52 +01:00
Damien George 1df4168c33 py/nlrthumb: Convert NLR thumb funcs from asm to C with inline-asm.
Now only the bits that really need to be written in assembler are written
in it, otherwise C is used.  This means that the assembler code no longer
needs to know about the global state structure which makes it much easier
to maintain.
2016-06-28 11:28:52 +01:00
Damien George df95f52583 py/modthread: Allow to properly set the stack limit of a thread.
We rely on the port setting and adjusting the stack size so there is
enough room to recover from hitting the stack limit.
2016-06-28 11:28:51 +01:00
Damien George e90b6ce0b5 py/mpthread.h: Move GIL macros outside MICROPY_PY_THREAD block.
The GIL macros are needed even if threading is not enabled.
2016-06-28 11:28:50 +01:00
Damien George c567afc5fa py/modthread: Make Lock objects work when GIL is enabled. 2016-06-28 11:28:50 +01:00
Damien George a1c93a62b1 py: Don't use gc or qstr mutex when the GIL is enabled.
There is no need since the GIL already makes gc and qstr operations
atomic.
2016-06-28 11:28:50 +01:00
Damien George 4cec63a9db py: Implement a simple global interpreter lock.
This makes the VM/runtime thread safe, at the cost of not being able to
run code in parallel.
2016-06-28 11:28:50 +01:00
Damien George 1f54ad2aed py: Make interning of qstrs thread safe. 2016-06-28 11:28:50 +01:00
Damien George 3653f5144a py/gc: Fix GC+thread bug where ptr gets lost because it's not computed.
GC_EXIT() can cause a pending thread (waiting on the mutex) to be
scheduled right away.  This other thread may trigger a garbage
collection.  If the pointer to the newly-allocated block (allocated by
the original thread) is not computed before the switch (so it's just left
as a block number) then the block will be wrongly reclaimed.

This patch makes sure the pointer is computed before allowing any thread
switch to occur.
2016-06-28 11:28:49 +01:00
Damien George 9172c0cb25 py/modthread: Call mp_thread_start/mp_thread_finish around threads.
So the underlying thread implementation can do any necessary bookkeeping.
2016-06-28 11:28:49 +01:00
Damien George 722cff5fd0 py/modthread: Be more careful with root pointers when creating a thread. 2016-06-28 11:28:49 +01:00
Damien George e33806aaff py/gc: Fix 2 cases of concurrent access to ATB and FTB. 2016-06-28 11:28:49 +01:00
Damien George 7f4658a7ee py/modthread: Satisfy unused-args warning. 2016-06-28 11:28:49 +01:00
Damien George c93d9caa8b py/gc: Make memory manager and garbage collector thread safe.
By using a single, global mutex, all memory-related functions (alloc,
free, realloc, collect, etc) are made thread safe.  This means that only
one thread can be in such a function at any one time.
2016-06-28 11:28:49 +01:00
Damien George 34fc006f5e py/modthread: Add with-context capabilities to lock object. 2016-06-28 11:28:49 +01:00
Damien George 801d1b3803 py/modthread: Implement lock object, for creating a mutex. 2016-06-28 11:28:49 +01:00
Damien George 2dacd604c5 py/modthread: Add exit() function.
Simply raises the SystemExit exception.
2016-06-28 11:28:48 +01:00
Damien George 707f98f207 py/modthread: Add stack_size() function. 2016-06-28 11:28:48 +01:00
Damien George 3eb7a26809 py/modthread: Properly cast concrete exception pointer to an object. 2016-06-28 11:28:48 +01:00
Damien George 27cc07721b py: Add basic _thread module, with ability to start a new thread. 2016-06-28 11:28:48 +01:00
Damien George 330165a2cc py: Add MP_STATE_THREAD to hold state specific to a given thread. 2016-06-28 11:09:31 +01:00
Paul Sokolovsky c7fba524cb py/objtype: Inherit protocol vtable from base class only if it exists. 2016-06-19 00:56:06 +03:00
Paul Sokolovsky 41167554e4 py/mphal.h: If virtpin API is used, automagically include its header. 2016-06-19 00:12:37 +03:00
Paul Sokolovsky 413c3e10b4 py/objtype: instance: Inherit protocol vtable from a base class.
This allows to define an  abstract base class which would translate
C-level protocol to Python method calls, and any subclass inheriting
from it will support this feature. This in particular actually enables
recently introduced machine.PinBase class.
2016-06-19 00:01:59 +03:00
Paul Sokolovsky 3fecbb2462 extmod/machine_pinbase: Implementation of PinBase class.
Allows to translate C-level pin API to Python-level pin API. In other
words, allows to implement a pin class and Python which will be usable
for efficient C-coded algorithms, like bitbanging SPI/I2C, time_pulse,
etc.
2016-06-18 23:40:28 +03:00
Paul Sokolovsky 07209f8592 all: Rename mp_obj_type_t::stream_p to protocol.
It's now used for more than just stream protocol (e.g. pin protocol), so
don't use false names.
2016-06-18 18:44:57 +03:00
Paul Sokolovsky f469c76442 py: Rename __QSTR_EXTRACT flag to NO_QSTR.
It has more usages than just qstr extraction, for example, embedding (where
people don't care about efficient predefined qstrs).
2016-06-16 01:42:48 +03:00
Paul Sokolovsky 230d5cda05 py/mkrules.mk: Define "lib" outside conditional block.
"lib" happened to be defined inside block conditional on $(PROG).
2016-06-16 01:11:24 +03:00
Paul Sokolovsky dcb904416a py/makeqstrdefs.py: Remove restriction that source path can't be absolute.
That's arbitrary restriction, in case of embedding, a source file path may
be absolute. For the purpose of filtering out system includes, checking
for ".c" suffix is enough.
2016-06-16 01:04:42 +03:00
Paul Sokolovsky 0f5bf1aafe py/mpconfig.h: MP_NOINLINE is universally useful, move from unix port. 2016-06-15 23:52:00 +03:00
Paul Sokolovsky 337111ba9e py: Support to build berkeley db 1.85 and "btree" module. 2016-06-15 00:52:45 +03:00
Mark Anthony Palomer 3131053e1a py/objdict: Implemented OrderedDict equality check. 2016-06-12 17:33:48 +03:00
Damien George b1533c4366 py/parse: Treat constants that start with underscore as private.
Assignments of the form "_id = const(value)" are treated as private
(following a similar CPython convention) and code is no longer emitted
for the assignment to a global variable.

See issue #2111.
2016-06-06 17:28:32 +01:00
Damien George 33168081f4 extmod/machine: Add MICROPY_PY_MACHINE_PULSE config for time_pulse_us.
Since not all ports that enable the machine module have the pin HAL
functions.
2016-05-31 14:25:19 +01:00
Damien George 4940bee62a extmod: Add machine time_pulse_us function (at C and Python level).
The C implementation is taken from the DHT driver.
2016-05-31 13:58:48 +01:00
Damien George 715ee9d925 py/modstruct: Allow to have "0s" in struct format. 2016-05-28 23:27:38 +01:00
Paul Sokolovsky 2ec0ee082a py/moduerrno: Add ECONNREFUSED, one of frequent networking errors. 2016-05-28 00:17:19 +03:00
Paul Sokolovsky 751e3b7a82 extmod/virtpin: Initial implementation of open-ended C-level Pin interface.
Using usual method of virtual method tables. Single virtual method,
ioctl, is defined currently for all operations. This universal and
extensible vtable-based method is also defined as a default MPHAL
GPIO implementation, but a specific port may override it with its
own implementation (e.g. close-ended, but very efficient, e.g. avoiding
virtual method dispatch).
2016-05-27 01:08:43 +03:00
Paul Sokolovsky c76acd8c23 py/moduerrno: Add EEXIST, EISDIR.
Useful to check file/dir operations result, in particular used by upip.
2016-05-25 01:23:57 +03:00
Antonin ENFRUN ca41dc2750 py/objnamedtuple: Allow passing field names as a tuple.
So the documentation's example works.  Besides, a tuple can be more
memory efficient.
2016-05-23 21:08:07 +01:00
Damien George 202d5acd06 py/makeqstrdata.py: Allow to have double-quote characters in qstrs.
When rendering the qstr for a C header file, the double-quate character
must be escaped.
2016-05-23 15:18:55 +01:00
Damien George 274952a117 py: Allow to stat and import frozen mpy files using new frozen "VFS".
Freezing mpy files using mpy-tool.py now works again.
2016-05-23 12:42:23 +01:00
Paul Sokolovsky 9dde6062cc py/objstr: Fix mix-signed comparison in str.center(). 2016-05-22 02:22:14 +03:00
Dave Hylands 6a60fb3cf4 py/objstr*: Properly ifdef str.center(). 2016-05-22 01:54:41 +03:00
Paul Sokolovsky 1b5abfcaae py/objstr: Implement str.center().
Disabled by default, enabled in unix port. Need for this method easily
pops up when working with text UI/reporting, and coding workalike
manually again and again counter-productive.
2016-05-22 00:13:44 +03:00
Paul Sokolovsky 2c573f00b8 py/builtinimport: Unbreak bare-arm build. 2016-05-21 22:37:58 +03:00
Paul Sokolovsky 8a2970e136 py/builtinimport: Unbreak minimal build.
These are workarounds required until frozen .mpy loading following standard
frozen modules code path.
2016-05-21 22:23:08 +03:00
Paul Sokolovsky fb742cdc12 py/{builtinimport,frozenmod}: Rework frozen modules support to support packages.
Now frozen modules is treated just as a kind of VFS, and all operations
performed on it correspond to operations on normal filesystem. This allows
to support packages properly, and potentially also data files.

This change also have changes to rework frozen bytecode modules support to
use the same framework, but it's not finished (and actually may not work,
as older adhox handling of any type of frozen modules is removed).
2016-05-21 21:38:50 +03:00
Paul Sokolovsky 5a2a4e9452 py/mphal.h: Provide default prototypes for mp_hal_delay_us/mp_hal_ticks_us.
Similar to existing mp_hal_delay_ms/mp_hal_ticks_ms.
2016-05-21 02:13:50 +03:00
Paul Sokolovsky 497660fcda py/stream: Add mp_stream_close() helper function. 2016-05-20 21:18:49 +03:00
Damien George 3ff16ff52e py: Declare constant data as properly constant.
Otherwise some compilers (eg without optimisation) will put this read-only
data in RAM instead of ROM.
2016-05-20 12:46:20 +01:00
Paul Sokolovsky 7f7c84b10a py/stream: Support both "exact size" and "one underlying call" operations.
Both read and write operations support variants where either a) a single
call is made to the undelying stream implementation and returned buffer
length may be less than requested, or b) calls are repeated until requested
amount of data is collected, shorter amount is returned only in case of
EOF or error.

These operations are available from the level of C support functions to be
used by other C modules to implementations of Python methods to be used in
user-facing objects.

The rationale of these changes is to allow to write concise and robust
code to work with *blocking* streams of types prone to short reads, like
serial interfaces and sockets. Particular object types may select "exact"
vs "once" types of methods depending on their needs. E.g., for sockets,
revc() and send() methods continue to be "once", while read() and write()
thus converted to "exactly" versions.

These changes don't affect non-blocking handling, e.g. trying "exact"
method on the non-blocking socket will return as much data as available
without blocking. No data available is continued to be signaled as None
return value to read() and write().

From the point of view of CPython compatibility, this model is a cross
between its io.RawIOBase and io.BufferedIOBase abstract classes. For
blocking streams, it works as io.BufferedIOBase model (guaranteeing
lack of short reads/writes), while for non-blocking - as io.RawIOBase,
returning None in case of lack of data (instead of raising expensive
exception, as required by io.BufferedIOBase). Such a cross-behavior
should be optimal for MicroPython needs.
2016-05-18 02:41:45 +03:00
Paul Sokolovsky e53fb1bf03 py/modstruct: Raise ValueError on unsupported format char. 2016-05-14 15:47:08 +03:00
Paul Sokolovsky 2ae6697300 py/objstringio: Add TODO comment about avoiding copying on .getvalue(). 2016-05-14 14:46:13 +03:00
Damien George cc80c4dd59 py/objstr: Make dedicated splitlines function, supporting diff newlines.
It now supports \n, \r and \r\n as newline separators.

Adds 56 bytes to stmhal and 80 bytes to unix x86-64.

Fixes issue #1689.
2016-05-13 12:21:32 +01:00
Paul Sokolovsky 68a7a92cec py/gc: gc_dump_alloc_table(): Dump heap offset instead of actual address.
Address printed was truncated anyway and in general confusing to outsider.
A line which dumps it is still left in the source, commented, for peculiar
cases when it may be needed (e.g. when running under debugger).
2016-05-13 00:16:38 +03:00
Paul Sokolovsky 9a8751b006 gc: gc_dump_alloc_table(): Use '=' char for tail blocks.
'=' is pretty natural character for tail, and gives less dense picture
where it's easier to see what object types are actually there.
2016-05-13 00:16:38 +03:00
Paul Sokolovsky 10503f3534 py/moduerrno: Add EACCES, pretty common error on Unix. 2016-05-13 00:15:38 +03:00
Damien George 9a92499641 py/objexcept: Don't convert errno to str in constructor, do it in print.
OSError's are now printed like:

    OSError: [Errno 1] EPERM

but only if the string corresponding to the errno is found.
2016-05-12 14:27:52 +01:00
Paul Sokolovsky a314b842bb py/emitglue: Fix build on AArch64 (ARMv8, etc.) related to loading .mpy files.
Actual loading of .mpy files isn't tested.
2016-05-12 16:00:57 +03:00
Colin Hogben a896951a9a py/objfloat, py/modmath: Ensure M_PI and M_E defined.
In some compliation enviroments (e.g. mbed online compiler) with
strict standards compliance, <math.h> does not define constants such
as M_PI.  Provide fallback definitions of M_E and M_PI where needed.
2016-05-12 13:28:45 +01:00
Damien George d45e5f8c35 py: Add mp_errno_to_str() and use it to provide nicer OSError msgs.
If an OSError is raised with an integer argument, and that integer
corresponds to an errno, then the string for the errno is used as the
argument to the exception, instead of the integer.  Only works if
the uerrno module is enabled.
2016-05-12 13:20:40 +01:00
Damien George 47bf6ba61a py/moduerrno: Add more constants to the errno module. 2016-05-12 13:18:48 +01:00
Damien George c9a7430dbe py/mperrno: Add some more MP_Exxx constants, related to networking. 2016-05-12 12:48:47 +01:00
Paul Sokolovsky bc04dc277e py/gc: Make (byte)array type dumping conditional on these types being enabled. 2016-05-11 19:21:53 +03:00
Paul Sokolovsky 3d7f3f00e0 py/gc: gc_dump_alloc_table(): Show byte/str and (byte)array objects.
These are typical consumers of large chunks of memory, so it's useful to
see at least their number (how much memory isn't clearly shown, as the data
for these objects is allocated elsewhere).
2016-05-11 19:00:15 +03:00
Damien George 80a8d473f6 py/repl: Fix handling of backslash in quotes when checking continuation. 2016-05-11 16:05:22 +01:00
Damien George 83a9a723b9 py/mperrno: Add EAFNOSUPPORT definition. 2016-05-10 23:44:59 +01:00
Damien George e36ff98c80 py/parse: Add uerrno to list of modules to look for constants in. 2016-05-10 23:30:39 +01:00
Damien George 596a3feb8f py: Add uerrno module, with errno constants and dict. 2016-05-10 23:30:39 +01:00
Damien George 3f56fd64b8 py: Add mperrno.h file with uPy defined errno constants. 2016-05-10 23:30:39 +01:00
Paul Sokolovsky 6f34e138f1 py/vstr: Change allocation policy, +16 to requested size, instead of *2.
Effect measured on esp8266 port:

Before:
>>> pystone_lowmem.main(10000)
Pystone(1.2) time for 10000 passes = 44214 ms
This machine benchmarks at 226 pystones/second
>>> pystone_lowmem.main(10000)
Pystone(1.2) time for 10000 passes = 44246 ms
This machine benchmarks at 226 pystones/second

After:
>>> pystone_lowmem.main(10000)
Pystone(1.2) time for 10000 passes = 44343ms
This machine benchmarks at 225 pystones/second
>>> pystone_lowmem.main(10000)
Pystone(1.2) time for 10000 passes = 44376ms
This machine benchmarks at 225 pystones/second
2016-05-10 00:56:51 +03:00
Paul Sokolovsky 40f0096ee7 Revert "py/objstr: .format(): Avoid call to vstr_null_terminated_str()."
This reverts commit 6de8dbb488. The change
was incorrect (correct change would require comparing with end pointer in
each if statement in the block).
2016-05-09 23:42:42 +03:00
Paul Sokolovsky a1f2245a81 py/vstr: vstr_null_terminated_str(): Extend string by at most one byte.
vstr_null_terminated_str is almost certainly a vstr finalization operation,
so it should add the requested NUL byte, and not try to pre-allocate more.
The previous implementation could actually allocate double of the buffer
size.
2016-05-09 22:39:57 +03:00
Paul Sokolovsky 6de8dbb488 py/objstr: .format(): Avoid call to vstr_null_terminated_str().
By comparing with string end pointer instead of checking for NUL byte.
Should alleviate reallocations and fragmentation a tiny bit.
2016-05-09 21:55:09 +03:00
Damien George 460b086333 py/mpz: Fix mpn_div so that it doesn't modify memory of denominator.
Previous to this patch bignum division and modulo would temporarily
modify the RHS argument to the operation (eg x/y would modify y), but on
return the RHS would be restored to its original value.  This is not
allowed because arguments to binary operations are const, and in
particular might live in ROM.  The modification was to normalise the arg
(and then unnormalise before returning), and this patch makes it so the
normalisation is done on the fly and the arg is now accessed as read-only.

This change doesn't increase the order complexity of the operation, and
actually reduces code size.
2016-05-09 17:21:42 +01:00
Damien George 65402ab1ec py/mpz: Do Python style division/modulo within bignum divmod routine.
This patch consolidates the Python logic for division/modulo to one place
within the bignum code.
2016-05-08 22:21:21 +01:00
Damien George dc3faea040 py/mpz: Fix bug with overflowing C-shift in division routine.
When DIG_SIZE=32, a uint32_t is used to store limbs, and no normalisation
is needed because the MSB is already set, then there will be left and
right shifts (in C) by 32 of a 32-bit variable, leading to undefined
behaviour.  This patch fixes this bug.
2016-05-08 21:38:43 +01:00
Paul Sokolovsky d59c2e5e45 py/repl: If there're no better alternatives, try to complete "import".
Also do that only for the first word in a line. The idea is that when you
start up interpreter, high chance that you want to do an import. With this
patch, this can be achieved with "i<tab>".
2016-05-08 20:40:47 +03:00
Damien George 470c429ee1 py/runtime: Properly handle passing user mappings to ** keyword args. 2016-05-07 22:02:46 +01:00
Damien George 12dd8df375 py/objstr: Binary type of str/bytes for buffer protocol is 'B'.
The type is an unsigned 8-bit value, since bytes objects are exactly
that.  And it's also sensible for unicode strings to return unsigned
values when accessed in a byte-wise manner (CPython does not allow this).
2016-05-07 21:18:17 +01:00
Damien George eb54e4d065 py/obj: Add warning note about get_array return value and GC blocks. 2016-05-04 10:19:08 +01:00
Paul Sokolovsky 9549590fc6 py/modcollections: Rename module name have "u" prefix for consistency. 2016-05-02 13:57:46 +03:00
Paul Sokolovsky ddb9dba2f7 py/modio: Rename module name to "uio" for consistency with other modules. 2016-05-02 13:56:33 +03:00
Paul Sokolovsky 25d0f7d59d extmod/modwebrepl: Module to handle WebREPL protocol.
While just a websocket is enough for handling terminal part of WebREPL,
handling file transfer operations requires demultiplexing and acting
upon, which is encapsulated in _webrepl class provided by this module,
which wraps a websocket object.
2016-04-29 00:52:52 +03:00
Paul Sokolovsky eff85bb1dc py/vm: "yield from" didn't handle MP_OBJ_STOP_ITERATION optimization.
E.g. crashed when yielding from already stopped generators.
2016-04-28 02:08:43 +03:00
Paul Sokolovsky 51cee4495e py/mkrules.mk: Typo fixes in comments. 2016-04-26 12:39:28 +03:00
Damien George 23df4b08fb py/emitnative: Use MP_OBJ_NEW_SMALL_INT instead of manual bit shifting. 2016-04-26 10:02:32 +01:00
Damien George 2bddfd4922 py/obj.h: When constructing a small-int cast to mp_uint_t for bit-shift.
The C standard says that left-shifting a signed value (on the LHS of the
operator) is undefined.  So we cast to an unsigned integer before the
shift.  gcc does not issue a warning about this, but clang does.
2016-04-26 09:51:37 +01:00
stijn 9264d42e2a py/makeqstrdefs.py: Windows compatibility.
- msvc preprocessor output contains full paths with backslashes so the
  ':' and '\' characters needs to be erased from the paths as well
- use a regex for extraction of filenames from preprocessor output so it
  can handle both gcc and msvc preprocessor output, and spaces in paths
  (also thanks to a PR from @travnicekivo for part of that regex)
- os.rename will fail on windows if the destination file already exists,
  so simply attempt to delete that file first
2016-04-25 22:34:22 +01:00
stijn b2b771ca02 py/makeqstrdefs.py: Remove unused function/variable/import. 2016-04-25 22:34:20 +01:00
Paul Sokolovsky bababce6de py/runtime_utils: Fix nanbox build. 2016-04-25 20:03:14 +03:00
Paul Sokolovsky 6d103b6548 py: Move call_function_*_protected() functions to py/ for reuse.
They almost certainly needed by any C code which calls Python callbacks.
2016-04-25 19:31:17 +03:00