aboutsummaryrefslogtreecommitdiff
path: root/py/objtype.c
AgeCommit message (Collapse)Author
2022-05-03all: Use mp_obj_malloc everywhere it's applicable.Jim Mussared
This replaces occurences of foo_t *foo = m_new_obj(foo_t); foo->base.type = &foo_type; with foo_t *foo = mp_obj_malloc(foo_t, &foo_type); Excludes any places where base is a sub-field or when new0/memset is used. Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2022-04-20py/objtype: Convert result of user __contains__ method to bool.Jon Bjarni Bjarnason
Per https://docs.python.org/3/reference/expressions.html#membership-test-operations For user-defined classes which define the contains() method, x in y returns True if y.contains(x) returns a true value, and False otherwise. Fixes issue #7884.
2021-09-16py/vm: Add a fast path for LOAD_ATTR on instance types.Jim Mussared
When the LOAD_ATTR opcode is executed there are quite a few different cases that have to be handled, but the common case is accessing a member on an instance type. Typically, built-in types provide methods which is why this is common. Fortunately, for this specific case, if the member is found in the member map then there's no further processing. This optimisation does a relatively cheap check (type is instance) and then forwards directly to the member map lookup, falling back to the regular path if necessary. Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
2021-04-27py: Add option to compile without any error messages at all.Damien George
This introduces a new option, MICROPY_ERROR_REPORTING_NONE, which completely disables all error messages. To be used in cases where MicroPython needs to fit in very limited systems. Signed-off-by: Damien George <damien@micropython.org>
2020-10-10py/objtype: Handle __dict__ attribute when type has no locals.Jim Mussared
2020-06-24py/objtype: Support passing in an OrderedDict to type() as the locals.Damien George
An OrderedDict can now be used for the locals when creating a type explicitly via type(name, bases, locals). Signed-off-by: Damien George <damien@micropython.org>
2020-06-10py/objtype: Use mp_obj_dict_copy() for creating obj.__dict__ attribute.Andrew Leech
The resulting dict is now marked as read-only (is_fixed=1) to enforce the fact that changes to this dict will not be reflected in the class instance. This commit reduces code size by about 20 bytes, and should be more efficient because it creates a direct copy of the dict rather than reinserting all elements.
2020-06-10py/objtype: Add __dict__ attribute for class objects.Andrew Leech
The behavior mirrors the instance object dict attribute where a copy of the local attributes are provided (unless the dict is read-only, then that dict itself is returned, as an optimisation). MicroPython does not support modifying this dict because the changes will not be reflected in the class. The feature is only enabled if MICROPY_CPYTHON_COMPAT is set, the same as the instance version.
2020-04-23all: Format code to add space after C++-style comment start.stijn
Note: the uncrustify configuration is explicitly set to 'add' instead of 'force' in order not to alter the comments which use extra spaces after // as a means of indenting text for clarity.
2020-04-13all: Clean up error strings to use lowercase and change cannot to can't.Damien George
Now that error string compression is supported it's more important to have consistent error string formatting (eg all lowercase English words, consistent contractions). This commit cleans up some of the strings to make them more consistent.
2020-04-05all: Use MP_ERROR_TEXT for all error messages.Jim Mussared
2020-04-05py: Use preprocessor to detect error reporting level (terse/detailed).Jim Mussared
Instead of compiler-level if-logic. This is necessary to know what error strings are included in the build at the preprocessor stage, so that string compression can be implemented.
2020-02-28all: Reformat C and Python source code with tools/codeformat.py.Damien George
This is run with uncrustify 0.70.1, and black 19.10b0.
2020-02-21py/objtype: Allow mp_instance_cast_to_native_base to take native obj.Damien George
And rename it to mp_obj_cast_to_native_base() to indicate this. This allows users of this function to easily support native and native-subclass objects in the same way (by just passing the object through this function).
2020-02-13py: Add mp_raise_msg_varg helper and use it where appropriate.Damien George
This commit adds mp_raise_msg_varg(type, fmt, ...) as a helper for nlr_raise(mp_obj_new_exception_msg_varg(type, fmt, ...)). It makes the C-level API for raising exceptions more consistent, and reduces code size on most ports: bare-arm: +28 +0.042% minimal x86: +100 +0.067% unix x64: -56 -0.011% unix nanbox: -300 -0.068% stm32: -204 -0.054% PYBV10 cc3200: +0 +0.000% esp8266: -64 -0.010% GENERIC esp32: -104 -0.007% GENERIC nrf: -136 -0.094% pca10040 samd: +0 +0.000% ADAFRUIT_ITSYBITSY_M4_EXPRESS
2020-02-11py: Expand type equality flags to 3 separate ones, fix bool/namedtuple.Damien George
Both bool and namedtuple will check against other types for equality; int, float and complex for bool, and tuple for namedtuple. So to make them work after the recent commit 3aab54bf434e7f025a91ea05052f1bac439fad8c they would need MP_TYPE_FLAG_NEEDS_FULL_EQ_TEST set. But that makes all bool and namedtuple equality checks less efficient because mp_obj_equal_not_equal() could no longer short-cut x==x, and would need to try __ne__. To improve this, this commit splits the MP_TYPE_FLAG_NEEDS_FULL_EQ_TEST flags into 3 separate flags to give types more fine-grained control over how their equality behaves. These new flags are then used to fix bool and namedtuple equality. Fixes issue #5615 and #5620.
2020-01-30py: Support non-boolean results for equality and inequality tests.Nicko van Someren
This commit implements a more complete replication of CPython's behaviour for equality and inequality testing of objects. This addresses the issues discussed in #5382 and a few other inconsistencies. Improvements over the old code include: - Support for returning non-boolean results from comparisons (as used by numpy and others). - Support for non-reflexive equality tests. - Preferential use of __ne__ methods and MP_BINARY_OP_NOT_EQUAL binary operators for inequality tests, when available. - Fallback to op2 == op1 or op2 != op1 when op1 does not implement the (in)equality operators. The scheme here makes use of a new flag, MP_TYPE_FLAG_NEEDS_FULL_EQ_TEST, in the flags word of mp_obj_type_t to indicate if various shortcuts can or cannot be used when performing equality and inequality tests. Currently four built-in classes have the flag set: float and complex are non-reflexive (since nan != nan) while bytearray and frozenszet instances can equal other builtin class instances (bytes and set respectively). The flag is also set for any new class defined by the user. This commit also includes a more comprehensive set of tests for the behaviour of (in)equality operators implemented in special methods.
2020-01-30py/objtype: Make mp_obj_type_t.flags constants public, moved to obj.h.Damien George
2020-01-09py: Make mp_obj_get_type() return a const ptr to mp_obj_type_t.Damien George
Most types are in rodata/ROM, and mp_obj_base_t.type is a constant pointer, so enforce this const-ness throughout the code base. If a type ever needs to be modified (eg a user type) then a simple cast can be used.
2019-12-27py/runtime: Don't allocate iter buf for user-defined types.Damien George
A user-defined type that defines __iter__ doesn't need any memory to be pre-allocated for its iterator (because it can't use such memory). So optimise for this case by not allocating the iter-buf.
2019-10-18py/objtype: Add type.__bases__ attribute.Josh Lloyd
Enabled as part of MICROPY_CPYTHON_COMPAT.
2019-09-26py: Rename MP_QSTR_NULL to MP_QSTRnull to avoid intern collisions.Josh Lloyd
Fixes #5140.
2019-09-26py: Add support for matmul operator @ as per PEP 465.Damien George
To make progress towards MicroPython supporting Python 3.5, adding the matmul operator is important because it's a really "low level" part of the language, being a new token and modifications to the grammar. It doesn't make sense to make it configurable because 1) it would make the grammar and lexer complicated/messy; 2) no other operators are configurable; 3) it's not a feature that can be "dynamically plugged in" via an import. And matmul can be useful as a general purpose user-defined operator, it doesn't have to be just for numpy use. Based on work done by Jim Mussared.
2019-02-12py: Downcase MP_xxx_SLOT_IS_FILLED inline functions.Damien George
2019-02-12py: Downcase all MP_OBJ_IS_xxx macros to make a more consistent C API.Damien George
These macros could in principle be (inline) functions so it makes sense to have them lower case, to match the other C API functions. The remaining macros that are upper case are: - MP_OBJ_TO_PTR, MP_OBJ_FROM_PTR - MP_OBJ_NEW_SMALL_INT, MP_OBJ_SMALL_INT_VALUE - MP_OBJ_NEW_QSTR, MP_OBJ_QSTR_VALUE - MP_OBJ_FUN_MAKE_SIG - MP_DECLARE_CONST_xxx - MP_DEFINE_CONST_xxx These must remain macros because they are used when defining const data (at least, MP_OBJ_NEW_SMALL_INT is so it makes sense to have MP_OBJ_SMALL_INT_VALUE also a macro). For those macros that have been made lower case, compatibility macros are provided for the old names so that users do not need to change their code immediately.
2019-02-06py: Update my copyright info on some files.Paul Sokolovsky
Based on git history.
2018-12-07py/obj: Add support for __int__ special method.Paul Sokolovsky
Based on the discussion, this special method is available unconditionally, as converting to int is a common operation.
2018-10-18py/objtype: Remove comment about catching exc from user __getattr__.Damien George
Any exception raised in a user __getattr__ should be propagated out. A test is added to verify these semantics.
2018-09-28py/objtype: Support full object model for get/set/delitem special meths.Damien George
This makes these special methods have the same calling behaviour as other methods in a class instance (mp_convert_member_lookup() is already called by mp_obj_class_lookup()).
2018-09-28py/objtype: Remove TODO about storing attributes to classes.Damien George
This behaviour is tested in basics/class_store.py and follows CPython.
2018-09-20py: Shorten error messages by using contractions and some rewording.Damien George
2018-09-20py/objtype: Clarify comment about configuring inplace op methods.Damien George
In 0e80f345f88c5db7c2353a5a9d29ed08b0af42f4 the inplace operations __iadd__ and __isub__ were made unconditionally available, so the comment about this section is changed to reflect that.
2018-08-02py: Fix compiling with debug enabled and make more use of DEBUG_printf.Damien George
DEBUG_printf and MICROPY_DEBUG_PRINTER is now used instead of normal printf, and a fault is fixed in mp_obj_class_lookup with debugging enabled; see issue #3999. Debugging can now be enabled on all ports including when nan-boxing is used.
2018-06-08py/objtype: Optimise instance get/set/del by skipping special accessors.Damien George
This patch is a code optimisation, trading text bytes for speed. On pyboard it's an increase of 0.06% in code size for a gain (in pystone performance) of roughly 6.5%. The patch optimises load/store/delete of attributes in user defined classes by not looking up special accessors (@property, __get__, __delete__, __set__, __setattr__ and __getattr_) if they are guaranteed not to exist in the class. Currently, if you do my_obj.foo() then the runtime has to do a few checks to see if foo is a property or has __get__, and if so delegate the call. And for stores things like my_obj.foo = 1 has to first check if foo is a property or has __set__ defined on it. Doing all those checks each and every time the attribute is accessed has a performance penalty. This patch eliminates all those checks for cases when it's guaranteed that the checks will always fail, ie no attributes are properties nor have any special accessor methods defined on them. To make this guarantee it checks all attributes of a user-defined class when it is first created. If any of the attributes of the user class are properties or have special accessors, or any of the base classes of the user class have them, then it sets a flag in the class to indicate that special accessors must be checked for. Then in the load/store/delete code it checks this flag to see if it can take the shortcut and optimise the lookup. It's an optimisation that's pretty widely applicable because it improves lookup performance for all methods of user defined classes, and stores of attributes, at least for those that don't have special accessors. And, it allows to enable descriptors with minimal additional runtime overhead if they are not used for a particular user class. There is one restriction on dynamic class creation that has been introduced by this patch: a user-defined class cannot go from zero special accessors to one special accessor (or more) after that class has been subclassed. If the script attempts this an AttributeError is raised (see addition to tests/misc/non_compliant.py for an example of this case). The cost in code space bytes for the optimisation in this patch is: unix x64: +528 unix nanbox: +508 stm32: +192 cc3200: +200 esp8266: +332 esp32: +244 Performance tests that were done: - on unix x86-64, pystone improved by about 5% - on pyboard, pystone improved by about 6.5%, from 1683 up to 1794 - on pyboard, bm_chaos (from CPython benchmark suite) improved by about 5% - on esp32, pystone improved by about 30% (but there are caching effects) - on esp32, bm_chaos improved by about 11%
2018-06-08py/objtype: Don't expose mp_obj_instance_attr().Damien George
mp_obj_is_instance_type() can be used instead to check for instance types.
2018-05-30py/objtype: Fix assertion failures in super_attr by checking type.Jeff Epler
Fixes assertion failures and segmentation faults when making calls like: super(1, 1).x
2018-05-30py/objtype: Fix assertion failures in mp_obj_new_type by checking types.Jeff Epler
Fixes assertion failures when the arguments to type() were not of valid types, e.g., when making calls like: type("", (), 3) type("", 3, {})
2018-05-25py/objtype: Remove TODO comment about needing to check for property.Damien George
Instance members are always treated as values, even if they are properties. A test is added to show this is the case.
2018-02-07py/objtype: Check and prevent delete/store on a fixed locals map.Damien George
Note that the check for elem!=NULL is removed for the MP_MAP_LOOKUP_ADD_IF_NOT_FOUND case because mp_map_lookup will always return non-NULL for such a case.
2017-12-12py/objtype: Refactor object's handling of __new__ to not create 2 objs.Damien George
Before this patch, if a user defined the __new__() function for a class then two instances of that class would be created: once before __new__ is called and once during the __new__ call (assuming the user creates some instance, eg using super().__new__, which is most of the time). The first one was then discarded. This refactor makes it so that a new instance is only created if the user __new__ function doesn't exist.
2017-12-12py/objtype: Implement better support for overriding native's __init__.Damien George
This patch cleans up and generalises part of the code which handles overriding and calling a native base-class's __init__ method. It defers the call to the native make_new() function until after the user (Python) __init__() method has run. That user method now has the chance to call the native __init__/make_new and pass it different arguments. If the user doesn't call the super().__init__ method then it will be called automatically after the user code finishes, to finalise construction of the instance.
2017-11-24py/runtime: Add MP_BINARY_OP_CONTAINS as reverse of MP_BINARY_OP_IN.Damien George
Before this patch MP_BINARY_OP_IN had two meanings: coming from bytecode it meant that the args needed to be swapped, but coming from within the runtime meant that the args were already in the correct order. This lead to some confusion in the code and comments stating how args were reversed. It also lead to 2 bugs: 1) containment for a subclass of a native type didn't work; 2) the expression "{True} in True" would illegally succeed and return True. In both of these cases it was because the args to MP_BINARY_OP_IN ended up being reversed twice. To fix these things this patch introduces MP_BINARY_OP_CONTAINS which corresponds exactly to the __contains__ special method, and this is the operator that built-in types should implement. MP_BINARY_OP_IN is now only emitted by the compiler and is converted to MP_BINARY_OP_CONTAINS by swapping the arguments.
2017-11-20py: Add config option to disable multiple inheritance.Damien George
This patch introduces a new compile-time config option to disable multiple inheritance at the Python level: MICROPY_MULTIPLE_INHERITANCE. It is enabled by default. Disabling multiple inheritance eliminates a lot of recursion in the call graph (which is important for some embedded systems), and can be used to reduce code size for ports that are really constrained (by around 200 bytes for Thumb2 archs). With multiple inheritance disabled all tests in the test-suite pass except those that explicitly test for multiple inheritance.
2017-11-11py/objtype: mp_obj_new_type: Name base types related vars more clearly.Paul Sokolovsky
As vars contains array of base types and its length, name them as such, avoid generic "items" and "len" names.
2017-10-27py/objtype: Introduce MICROPY_PY_ALL_INPLACE_SPECIAL_METHODS.Paul Sokolovsky
This allows to configure support for inplace special methods separately, similar to "normal" and reverse special methods. This is useful, because inplace methods are "the most optional" ones, for example, if inplace methods aren't defined, the operation will be executed using normal methods instead. As a caveat, __iadd__ and __isub__ are implemented even if MICROPY_PY_ALL_INPLACE_SPECIAL_METHODS isn't defined. This is similar to the state of affairs before binary operations refactor, and allows to run existing tests even if MICROPY_PY_ALL_INPLACE_SPECIAL_METHODS isn't defined.
2017-10-27py/objtype: Define all special methods if requested.Paul Sokolovsky
If MICROPY_PY_ALL_SPECIAL_METHODS is defined, actually define all special methods (still subject to gating by e.g. MICROPY_PY_REVERSE_SPECIAL_METHODS). This adds quite a number of qstr's, so should be used sparingly.
2017-10-21py/objtype: Fit qstrs for special methods in byte type.Paul Sokolovsky
Update makeqstrdata.py to sort strings starting with "__" to the beginning of qstr list, so they get low qstr id's, guaranteedly fitting in 8 bits. Then use this property to further compact op_id => qstr mapping arrays.
2017-10-19py/objtype: Use CPython compatible method name for sizeof.Paul Sokolovsky
Per https://docs.python.org/3/library/sys.html#sys.getsizeof: getsizeof() calls the object’s __sizeof__ method. Previously, "getsizeof" was used mostly to save on new qstr, as we don't really support calling this method on arbitrary objects (so it was used only for reporting). However, normalize it all now.
2017-10-05py/objtype: Clean up unary- and binary-op enum-to-qstr mapping tables.Damien George
2017-10-04all: Remove inclusion of internal py header files.Damien George
Header files that are considered internal to the py core and should not normally be included directly are: py/nlr.h - internal nlr configuration and declarations py/bc0.h - contains bytecode macro definitions py/runtime0.h - contains basic runtime enums Instead, the top-level header files to include are one of: py/obj.h - includes runtime0.h and defines everything to use the mp_obj_t type py/runtime.h - includes mpstate.h and hence nlr.h, obj.h, runtime0.h, and defines everything to use the general runtime support functions Additional, specific headers (eg py/objlist.h) can be included if needed.