objtype.c 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400
  1. /*
  2. * This file is part of the MicroPython project, http://micropython.org/
  3. *
  4. * The MIT License (MIT)
  5. *
  6. * Copyright (c) 2013-2018 Damien P. George
  7. * Copyright (c) 2014-2016 Paul Sokolovsky
  8. *
  9. * Permission is hereby granted, free of charge, to any person obtaining a copy
  10. * of this software and associated documentation files (the "Software"), to deal
  11. * in the Software without restriction, including without limitation the rights
  12. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. * copies of the Software, and to permit persons to whom the Software is
  14. * furnished to do so, subject to the following conditions:
  15. *
  16. * The above copyright notice and this permission notice shall be included in
  17. * all copies or substantial portions of the Software.
  18. *
  19. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. * THE SOFTWARE.
  26. */
  27. #include <stdio.h>
  28. #include <stddef.h>
  29. #include <string.h>
  30. #include <assert.h>
  31. #include "py/objtype.h"
  32. #include "py/runtime.h"
  33. #if MICROPY_DEBUG_VERBOSE // print debugging info
  34. #define DEBUG_PRINT (1)
  35. #define DEBUG_printf DEBUG_printf
  36. #else // don't print debugging info
  37. #define DEBUG_PRINT (0)
  38. #define DEBUG_printf(...) (void)0
  39. #endif
  40. #define ENABLE_SPECIAL_ACCESSORS \
  41. (MICROPY_PY_DESCRIPTORS || MICROPY_PY_DELATTR_SETATTR || MICROPY_PY_BUILTINS_PROPERTY)
  42. #define TYPE_FLAG_IS_SUBCLASSED (0x0001)
  43. #define TYPE_FLAG_HAS_SPECIAL_ACCESSORS (0x0002)
  44. STATIC mp_obj_t static_class_method_make_new(const mp_obj_type_t *self_in, size_t n_args, size_t n_kw, const mp_obj_t *args);
  45. /******************************************************************************/
  46. // instance object
  47. STATIC int instance_count_native_bases(const mp_obj_type_t *type, const mp_obj_type_t **last_native_base) {
  48. int count = 0;
  49. for (;;) {
  50. if (type == &mp_type_object) {
  51. // Not a "real" type, end search here.
  52. return count;
  53. } else if (mp_obj_is_native_type(type)) {
  54. // Native types don't have parents (at least not from our perspective) so end.
  55. *last_native_base = type;
  56. return count + 1;
  57. } else if (type->parent == NULL) {
  58. // No parents so end search here.
  59. return count;
  60. #if MICROPY_MULTIPLE_INHERITANCE
  61. } else if (((mp_obj_base_t*)type->parent)->type == &mp_type_tuple) {
  62. // Multiple parents, search through them all recursively.
  63. const mp_obj_tuple_t *parent_tuple = type->parent;
  64. const mp_obj_t *item = parent_tuple->items;
  65. const mp_obj_t *top = item + parent_tuple->len;
  66. for (; item < top; ++item) {
  67. assert(MP_OBJ_IS_TYPE(*item, &mp_type_type));
  68. const mp_obj_type_t *bt = (const mp_obj_type_t *)MP_OBJ_TO_PTR(*item);
  69. count += instance_count_native_bases(bt, last_native_base);
  70. }
  71. return count;
  72. #endif
  73. } else {
  74. // A single parent, use iteration to continue the search.
  75. type = type->parent;
  76. }
  77. }
  78. }
  79. // This wrapper function is allows a subclass of a native type to call the
  80. // __init__() method (corresponding to type->make_new) of the native type.
  81. STATIC mp_obj_t native_base_init_wrapper(size_t n_args, const mp_obj_t *args) {
  82. mp_obj_instance_t *self = MP_OBJ_TO_PTR(args[0]);
  83. const mp_obj_type_t *native_base = NULL;
  84. instance_count_native_bases(self->base.type, &native_base);
  85. self->subobj[0] = native_base->make_new(native_base, n_args - 1, 0, args + 1);
  86. return mp_const_none;
  87. }
  88. STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(native_base_init_wrapper_obj, 1, MP_OBJ_FUN_ARGS_MAX, native_base_init_wrapper);
  89. #if !MICROPY_CPYTHON_COMPAT
  90. STATIC
  91. #endif
  92. mp_obj_instance_t *mp_obj_new_instance(const mp_obj_type_t *class, const mp_obj_type_t **native_base) {
  93. size_t num_native_bases = instance_count_native_bases(class, native_base);
  94. assert(num_native_bases < 2);
  95. mp_obj_instance_t *o = m_new_obj_var(mp_obj_instance_t, mp_obj_t, num_native_bases);
  96. o->base.type = class;
  97. mp_map_init(&o->members, 0);
  98. // Initialise the native base-class slot (should be 1 at most) with a valid
  99. // object. It doesn't matter which object, so long as it can be uniquely
  100. // distinguished from a native class that is initialised.
  101. if (num_native_bases != 0) {
  102. o->subobj[0] = MP_OBJ_FROM_PTR(&native_base_init_wrapper_obj);
  103. }
  104. return o;
  105. }
  106. // TODO
  107. // This implements depth-first left-to-right MRO, which is not compliant with Python3 MRO
  108. // http://python-history.blogspot.com/2010/06/method-resolution-order.html
  109. // https://www.python.org/download/releases/2.3/mro/
  110. //
  111. // will keep lookup->dest[0]'s value (should be MP_OBJ_NULL on invocation) if attribute
  112. // is not found
  113. // will set lookup->dest[0] to MP_OBJ_SENTINEL if special method was found in a native
  114. // type base via slot id (as specified by lookup->meth_offset). As there can be only one
  115. // native base, it's known that it applies to instance->subobj[0]. In most cases, we also
  116. // don't need to know which type it was - because instance->subobj[0] is of that type.
  117. // The only exception is when object is not yet constructed, then we need to know base
  118. // native type to construct its instance->subobj[0] from. But this case is handled via
  119. // instance_count_native_bases(), which returns a native base which it saw.
  120. struct class_lookup_data {
  121. mp_obj_instance_t *obj;
  122. qstr attr;
  123. size_t meth_offset;
  124. mp_obj_t *dest;
  125. bool is_type;
  126. };
  127. STATIC void mp_obj_class_lookup(struct class_lookup_data *lookup, const mp_obj_type_t *type) {
  128. assert(lookup->dest[0] == MP_OBJ_NULL);
  129. assert(lookup->dest[1] == MP_OBJ_NULL);
  130. for (;;) {
  131. DEBUG_printf("mp_obj_class_lookup: Looking up %s in %s\n", qstr_str(lookup->attr), qstr_str(type->name));
  132. // Optimize special method lookup for native types
  133. // This avoids extra method_name => slot lookup. On the other hand,
  134. // this should not be applied to class types, as will result in extra
  135. // lookup either.
  136. if (lookup->meth_offset != 0 && mp_obj_is_native_type(type)) {
  137. if (*(void**)((char*)type + lookup->meth_offset) != NULL) {
  138. DEBUG_printf("mp_obj_class_lookup: Matched special meth slot (off=%d) for %s\n",
  139. lookup->meth_offset, qstr_str(lookup->attr));
  140. lookup->dest[0] = MP_OBJ_SENTINEL;
  141. return;
  142. }
  143. }
  144. if (type->locals_dict != NULL) {
  145. // search locals_dict (the set of methods/attributes)
  146. assert(type->locals_dict->base.type == &mp_type_dict); // MicroPython restriction, for now
  147. mp_map_t *locals_map = &type->locals_dict->map;
  148. mp_map_elem_t *elem = mp_map_lookup(locals_map, MP_OBJ_NEW_QSTR(lookup->attr), MP_MAP_LOOKUP);
  149. if (elem != NULL) {
  150. if (lookup->is_type) {
  151. // If we look up a class method, we need to return original type for which we
  152. // do a lookup, not a (base) type in which we found the class method.
  153. const mp_obj_type_t *org_type = (const mp_obj_type_t*)lookup->obj;
  154. mp_convert_member_lookup(MP_OBJ_NULL, org_type, elem->value, lookup->dest);
  155. } else {
  156. mp_obj_instance_t *obj = lookup->obj;
  157. mp_obj_t obj_obj;
  158. if (obj != NULL && mp_obj_is_native_type(type) && type != &mp_type_object /* object is not a real type */) {
  159. // If we're dealing with native base class, then it applies to native sub-object
  160. obj_obj = obj->subobj[0];
  161. } else {
  162. obj_obj = MP_OBJ_FROM_PTR(obj);
  163. }
  164. mp_convert_member_lookup(obj_obj, type, elem->value, lookup->dest);
  165. }
  166. #if DEBUG_PRINT
  167. printf("mp_obj_class_lookup: Returning: ");
  168. mp_obj_print(lookup->dest[0], PRINT_REPR); printf(" ");
  169. // Don't try to repr() lookup->dest[1], as we can be called recursively
  170. printf("<%s @%p>\n", mp_obj_get_type_str(lookup->dest[1]), lookup->dest[1]);
  171. #endif
  172. return;
  173. }
  174. }
  175. // Previous code block takes care about attributes defined in .locals_dict,
  176. // but some attributes of native types may be handled using .load_attr method,
  177. // so make sure we try to lookup those too.
  178. if (lookup->obj != NULL && !lookup->is_type && mp_obj_is_native_type(type) && type != &mp_type_object /* object is not a real type */) {
  179. mp_load_method_maybe(lookup->obj->subobj[0], lookup->attr, lookup->dest);
  180. if (lookup->dest[0] != MP_OBJ_NULL) {
  181. return;
  182. }
  183. }
  184. // attribute not found, keep searching base classes
  185. if (type->parent == NULL) {
  186. DEBUG_printf("mp_obj_class_lookup: No more parents\n");
  187. return;
  188. #if MICROPY_MULTIPLE_INHERITANCE
  189. } else if (((mp_obj_base_t*)type->parent)->type == &mp_type_tuple) {
  190. const mp_obj_tuple_t *parent_tuple = type->parent;
  191. const mp_obj_t *item = parent_tuple->items;
  192. const mp_obj_t *top = item + parent_tuple->len - 1;
  193. for (; item < top; ++item) {
  194. assert(MP_OBJ_IS_TYPE(*item, &mp_type_type));
  195. mp_obj_type_t *bt = (mp_obj_type_t*)MP_OBJ_TO_PTR(*item);
  196. if (bt == &mp_type_object) {
  197. // Not a "real" type
  198. continue;
  199. }
  200. mp_obj_class_lookup(lookup, bt);
  201. if (lookup->dest[0] != MP_OBJ_NULL) {
  202. return;
  203. }
  204. }
  205. // search last base (simple tail recursion elimination)
  206. assert(MP_OBJ_IS_TYPE(*item, &mp_type_type));
  207. type = (mp_obj_type_t*)MP_OBJ_TO_PTR(*item);
  208. #endif
  209. } else {
  210. type = type->parent;
  211. }
  212. if (type == &mp_type_object) {
  213. // Not a "real" type
  214. return;
  215. }
  216. }
  217. }
  218. STATIC void instance_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
  219. mp_obj_instance_t *self = MP_OBJ_TO_PTR(self_in);
  220. qstr meth = (kind == PRINT_STR) ? MP_QSTR___str__ : MP_QSTR___repr__;
  221. mp_obj_t member[2] = {MP_OBJ_NULL};
  222. struct class_lookup_data lookup = {
  223. .obj = self,
  224. .attr = meth,
  225. .meth_offset = offsetof(mp_obj_type_t, print),
  226. .dest = member,
  227. .is_type = false,
  228. };
  229. mp_obj_class_lookup(&lookup, self->base.type);
  230. if (member[0] == MP_OBJ_NULL && kind == PRINT_STR) {
  231. // If there's no __str__, fall back to __repr__
  232. lookup.attr = MP_QSTR___repr__;
  233. lookup.meth_offset = 0;
  234. mp_obj_class_lookup(&lookup, self->base.type);
  235. }
  236. if (member[0] == MP_OBJ_SENTINEL) {
  237. // Handle Exception subclasses specially
  238. if (mp_obj_is_native_exception_instance(self->subobj[0])) {
  239. if (kind != PRINT_STR) {
  240. mp_print_str(print, qstr_str(self->base.type->name));
  241. }
  242. mp_obj_print_helper(print, self->subobj[0], kind | PRINT_EXC_SUBCLASS);
  243. } else {
  244. mp_obj_print_helper(print, self->subobj[0], kind);
  245. }
  246. return;
  247. }
  248. if (member[0] != MP_OBJ_NULL) {
  249. mp_obj_t r = mp_call_function_1(member[0], self_in);
  250. mp_obj_print_helper(print, r, PRINT_STR);
  251. return;
  252. }
  253. // TODO: CPython prints fully-qualified type name
  254. mp_printf(print, "<%s object at %p>", mp_obj_get_type_str(self_in), self);
  255. }
  256. mp_obj_t mp_obj_instance_make_new(const mp_obj_type_t *self, size_t n_args, size_t n_kw, const mp_obj_t *args) {
  257. assert(mp_obj_is_instance_type(self));
  258. // look for __new__ function
  259. mp_obj_t init_fn[2] = {MP_OBJ_NULL};
  260. struct class_lookup_data lookup = {
  261. .obj = NULL,
  262. .attr = MP_QSTR___new__,
  263. .meth_offset = offsetof(mp_obj_type_t, make_new),
  264. .dest = init_fn,
  265. .is_type = false,
  266. };
  267. mp_obj_class_lookup(&lookup, self);
  268. const mp_obj_type_t *native_base = NULL;
  269. mp_obj_instance_t *o;
  270. if (init_fn[0] == MP_OBJ_NULL || init_fn[0] == MP_OBJ_SENTINEL) {
  271. // Either there is no __new__() method defined or there is a native
  272. // constructor. In both cases create a blank instance.
  273. o = mp_obj_new_instance(self, &native_base);
  274. // Since type->make_new() implements both __new__() and __init__() in
  275. // one go, of which the latter may be overridden by the Python subclass,
  276. // we defer (see the end of this function) the call of the native
  277. // constructor to give a chance for the Python __init__() method to call
  278. // said native constructor.
  279. } else {
  280. // Call Python class __new__ function with all args to create an instance
  281. mp_obj_t new_ret;
  282. if (n_args == 0 && n_kw == 0) {
  283. mp_obj_t args2[1] = {MP_OBJ_FROM_PTR(self)};
  284. new_ret = mp_call_function_n_kw(init_fn[0], 1, 0, args2);
  285. } else {
  286. mp_obj_t *args2 = m_new(mp_obj_t, 1 + n_args + 2 * n_kw);
  287. args2[0] = MP_OBJ_FROM_PTR(self);
  288. memcpy(args2 + 1, args, (n_args + 2 * n_kw) * sizeof(mp_obj_t));
  289. new_ret = mp_call_function_n_kw(init_fn[0], n_args + 1, n_kw, args2);
  290. m_del(mp_obj_t, args2, 1 + n_args + 2 * n_kw);
  291. }
  292. // https://docs.python.org/3.4/reference/datamodel.html#object.__new__
  293. // "If __new__() does not return an instance of cls, then the new
  294. // instance's __init__() method will not be invoked."
  295. if (mp_obj_get_type(new_ret) != self) {
  296. return new_ret;
  297. }
  298. // The instance returned by __new__() becomes the new object
  299. o = MP_OBJ_TO_PTR(new_ret);
  300. }
  301. // now call Python class __init__ function with all args
  302. // This method has a chance to call super().__init__() to construct a
  303. // possible native base class.
  304. init_fn[0] = init_fn[1] = MP_OBJ_NULL;
  305. lookup.obj = o;
  306. lookup.attr = MP_QSTR___init__;
  307. lookup.meth_offset = 0;
  308. mp_obj_class_lookup(&lookup, self);
  309. if (init_fn[0] != MP_OBJ_NULL) {
  310. mp_obj_t init_ret;
  311. if (n_args == 0 && n_kw == 0) {
  312. init_ret = mp_call_method_n_kw(0, 0, init_fn);
  313. } else {
  314. mp_obj_t *args2 = m_new(mp_obj_t, 2 + n_args + 2 * n_kw);
  315. args2[0] = init_fn[0];
  316. args2[1] = init_fn[1];
  317. memcpy(args2 + 2, args, (n_args + 2 * n_kw) * sizeof(mp_obj_t));
  318. init_ret = mp_call_method_n_kw(n_args, n_kw, args2);
  319. m_del(mp_obj_t, args2, 2 + n_args + 2 * n_kw);
  320. }
  321. if (init_ret != mp_const_none) {
  322. if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
  323. mp_raise_TypeError("__init__() should return None");
  324. } else {
  325. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
  326. "__init__() should return None, not '%s'", mp_obj_get_type_str(init_ret)));
  327. }
  328. }
  329. }
  330. // If the type had a native base that was not explicitly initialised
  331. // (constructed) by the Python __init__() method then construct it now.
  332. if (native_base != NULL && o->subobj[0] == MP_OBJ_FROM_PTR(&native_base_init_wrapper_obj)) {
  333. o->subobj[0] = native_base->make_new(native_base, n_args, n_kw, args);
  334. }
  335. return MP_OBJ_FROM_PTR(o);
  336. }
  337. // Qstrs for special methods are guaranteed to have a small value, so we use byte
  338. // type to represent them.
  339. const byte mp_unary_op_method_name[MP_UNARY_OP_NUM_RUNTIME] = {
  340. [MP_UNARY_OP_BOOL] = MP_QSTR___bool__,
  341. [MP_UNARY_OP_LEN] = MP_QSTR___len__,
  342. [MP_UNARY_OP_HASH] = MP_QSTR___hash__,
  343. #if MICROPY_PY_ALL_SPECIAL_METHODS
  344. [MP_UNARY_OP_POSITIVE] = MP_QSTR___pos__,
  345. [MP_UNARY_OP_NEGATIVE] = MP_QSTR___neg__,
  346. [MP_UNARY_OP_INVERT] = MP_QSTR___invert__,
  347. [MP_UNARY_OP_ABS] = MP_QSTR___abs__,
  348. #endif
  349. #if MICROPY_PY_SYS_GETSIZEOF
  350. [MP_UNARY_OP_SIZEOF] = MP_QSTR___sizeof__,
  351. #endif
  352. };
  353. STATIC mp_obj_t instance_unary_op(mp_unary_op_t op, mp_obj_t self_in) {
  354. mp_obj_instance_t *self = MP_OBJ_TO_PTR(self_in);
  355. #if MICROPY_PY_SYS_GETSIZEOF
  356. if (MP_UNLIKELY(op == MP_UNARY_OP_SIZEOF)) {
  357. // TODO: This doesn't count inherited objects (self->subobj)
  358. const mp_obj_type_t *native_base;
  359. size_t num_native_bases = instance_count_native_bases(mp_obj_get_type(self_in), &native_base);
  360. size_t sz = sizeof(*self) + sizeof(*self->subobj) * num_native_bases
  361. + sizeof(*self->members.table) * self->members.alloc;
  362. return MP_OBJ_NEW_SMALL_INT(sz);
  363. }
  364. #endif
  365. qstr op_name = mp_unary_op_method_name[op];
  366. /* Still try to lookup native slot
  367. if (op_name == 0) {
  368. return MP_OBJ_NULL;
  369. }
  370. */
  371. mp_obj_t member[2] = {MP_OBJ_NULL};
  372. struct class_lookup_data lookup = {
  373. .obj = self,
  374. .attr = op_name,
  375. .meth_offset = offsetof(mp_obj_type_t, unary_op),
  376. .dest = member,
  377. .is_type = false,
  378. };
  379. mp_obj_class_lookup(&lookup, self->base.type);
  380. if (member[0] == MP_OBJ_SENTINEL) {
  381. return mp_unary_op(op, self->subobj[0]);
  382. } else if (member[0] != MP_OBJ_NULL) {
  383. mp_obj_t val = mp_call_function_1(member[0], self_in);
  384. // __hash__ must return a small int
  385. if (op == MP_UNARY_OP_HASH) {
  386. val = MP_OBJ_NEW_SMALL_INT(mp_obj_get_int_truncated(val));
  387. }
  388. return val;
  389. } else {
  390. if (op == MP_UNARY_OP_HASH) {
  391. lookup.attr = MP_QSTR___eq__;
  392. mp_obj_class_lookup(&lookup, self->base.type);
  393. if (member[0] == MP_OBJ_NULL) {
  394. // https://docs.python.org/3/reference/datamodel.html#object.__hash__
  395. // "User-defined classes have __eq__() and __hash__() methods by default;
  396. // with them, all objects compare unequal (except with themselves) and
  397. // x.__hash__() returns an appropriate value such that x == y implies
  398. // both that x is y and hash(x) == hash(y)."
  399. return MP_OBJ_NEW_SMALL_INT((mp_uint_t)self_in);
  400. }
  401. // "A class that overrides __eq__() and does not define __hash__() will have its __hash__() implicitly set to None.
  402. // When the __hash__() method of a class is None, instances of the class will raise an appropriate TypeError"
  403. }
  404. return MP_OBJ_NULL; // op not supported
  405. }
  406. }
  407. // Binary-op enum values not listed here will have the default value of 0 in the
  408. // table, corresponding to MP_QSTR_NULL, and are therefore unsupported (a lookup will
  409. // fail). They can be added at the expense of code size for the qstr.
  410. // Qstrs for special methods are guaranteed to have a small value, so we use byte
  411. // type to represent them.
  412. const byte mp_binary_op_method_name[MP_BINARY_OP_NUM_RUNTIME] = {
  413. [MP_BINARY_OP_LESS] = MP_QSTR___lt__,
  414. [MP_BINARY_OP_MORE] = MP_QSTR___gt__,
  415. [MP_BINARY_OP_EQUAL] = MP_QSTR___eq__,
  416. [MP_BINARY_OP_LESS_EQUAL] = MP_QSTR___le__,
  417. [MP_BINARY_OP_MORE_EQUAL] = MP_QSTR___ge__,
  418. // MP_BINARY_OP_NOT_EQUAL, // a != b calls a == b and inverts result
  419. [MP_BINARY_OP_CONTAINS] = MP_QSTR___contains__,
  420. // All inplace methods are optional, and normal methods will be used
  421. // as a fallback.
  422. [MP_BINARY_OP_INPLACE_ADD] = MP_QSTR___iadd__,
  423. [MP_BINARY_OP_INPLACE_SUBTRACT] = MP_QSTR___isub__,
  424. #if MICROPY_PY_ALL_INPLACE_SPECIAL_METHODS
  425. [MP_BINARY_OP_INPLACE_MULTIPLY] = MP_QSTR___imul__,
  426. [MP_BINARY_OP_INPLACE_FLOOR_DIVIDE] = MP_QSTR___ifloordiv__,
  427. [MP_BINARY_OP_INPLACE_TRUE_DIVIDE] = MP_QSTR___itruediv__,
  428. [MP_BINARY_OP_INPLACE_MODULO] = MP_QSTR___imod__,
  429. [MP_BINARY_OP_INPLACE_POWER] = MP_QSTR___ipow__,
  430. [MP_BINARY_OP_INPLACE_OR] = MP_QSTR___ior__,
  431. [MP_BINARY_OP_INPLACE_XOR] = MP_QSTR___ixor__,
  432. [MP_BINARY_OP_INPLACE_AND] = MP_QSTR___iand__,
  433. [MP_BINARY_OP_INPLACE_LSHIFT] = MP_QSTR___ilshift__,
  434. [MP_BINARY_OP_INPLACE_RSHIFT] = MP_QSTR___irshift__,
  435. #endif
  436. [MP_BINARY_OP_ADD] = MP_QSTR___add__,
  437. [MP_BINARY_OP_SUBTRACT] = MP_QSTR___sub__,
  438. #if MICROPY_PY_ALL_SPECIAL_METHODS
  439. [MP_BINARY_OP_MULTIPLY] = MP_QSTR___mul__,
  440. [MP_BINARY_OP_FLOOR_DIVIDE] = MP_QSTR___floordiv__,
  441. [MP_BINARY_OP_TRUE_DIVIDE] = MP_QSTR___truediv__,
  442. [MP_BINARY_OP_MODULO] = MP_QSTR___mod__,
  443. [MP_BINARY_OP_DIVMOD] = MP_QSTR___divmod__,
  444. [MP_BINARY_OP_POWER] = MP_QSTR___pow__,
  445. [MP_BINARY_OP_OR] = MP_QSTR___or__,
  446. [MP_BINARY_OP_XOR] = MP_QSTR___xor__,
  447. [MP_BINARY_OP_AND] = MP_QSTR___and__,
  448. [MP_BINARY_OP_LSHIFT] = MP_QSTR___lshift__,
  449. [MP_BINARY_OP_RSHIFT] = MP_QSTR___rshift__,
  450. #endif
  451. #if MICROPY_PY_REVERSE_SPECIAL_METHODS
  452. [MP_BINARY_OP_REVERSE_ADD] = MP_QSTR___radd__,
  453. [MP_BINARY_OP_REVERSE_SUBTRACT] = MP_QSTR___rsub__,
  454. #if MICROPY_PY_ALL_SPECIAL_METHODS
  455. [MP_BINARY_OP_REVERSE_MULTIPLY] = MP_QSTR___rmul__,
  456. [MP_BINARY_OP_REVERSE_FLOOR_DIVIDE] = MP_QSTR___rfloordiv__,
  457. [MP_BINARY_OP_REVERSE_TRUE_DIVIDE] = MP_QSTR___rtruediv__,
  458. [MP_BINARY_OP_REVERSE_MODULO] = MP_QSTR___rmod__,
  459. [MP_BINARY_OP_REVERSE_POWER] = MP_QSTR___rpow__,
  460. [MP_BINARY_OP_REVERSE_OR] = MP_QSTR___ror__,
  461. [MP_BINARY_OP_REVERSE_XOR] = MP_QSTR___rxor__,
  462. [MP_BINARY_OP_REVERSE_AND] = MP_QSTR___rand__,
  463. [MP_BINARY_OP_REVERSE_LSHIFT] = MP_QSTR___rlshift__,
  464. [MP_BINARY_OP_REVERSE_RSHIFT] = MP_QSTR___rrshift__,
  465. #endif
  466. #endif
  467. };
  468. STATIC mp_obj_t instance_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_in) {
  469. // Note: For ducktyping, CPython does not look in the instance members or use
  470. // __getattr__ or __getattribute__. It only looks in the class dictionary.
  471. mp_obj_instance_t *lhs = MP_OBJ_TO_PTR(lhs_in);
  472. retry:;
  473. qstr op_name = mp_binary_op_method_name[op];
  474. /* Still try to lookup native slot
  475. if (op_name == 0) {
  476. return MP_OBJ_NULL;
  477. }
  478. */
  479. mp_obj_t dest[3] = {MP_OBJ_NULL};
  480. struct class_lookup_data lookup = {
  481. .obj = lhs,
  482. .attr = op_name,
  483. .meth_offset = offsetof(mp_obj_type_t, binary_op),
  484. .dest = dest,
  485. .is_type = false,
  486. };
  487. mp_obj_class_lookup(&lookup, lhs->base.type);
  488. mp_obj_t res;
  489. if (dest[0] == MP_OBJ_SENTINEL) {
  490. res = mp_binary_op(op, lhs->subobj[0], rhs_in);
  491. } else if (dest[0] != MP_OBJ_NULL) {
  492. dest[2] = rhs_in;
  493. res = mp_call_method_n_kw(1, 0, dest);
  494. } else {
  495. // If this was an inplace method, fallback to normal method
  496. // https://docs.python.org/3/reference/datamodel.html#object.__iadd__ :
  497. // "If a specific method is not defined, the augmented assignment
  498. // falls back to the normal methods."
  499. if (op >= MP_BINARY_OP_INPLACE_OR && op <= MP_BINARY_OP_INPLACE_POWER) {
  500. op -= MP_BINARY_OP_INPLACE_OR - MP_BINARY_OP_OR;
  501. goto retry;
  502. }
  503. return MP_OBJ_NULL; // op not supported
  504. }
  505. #if MICROPY_PY_BUILTINS_NOTIMPLEMENTED
  506. // NotImplemented means "try other fallbacks (like calling __rop__
  507. // instead of __op__) and if nothing works, raise TypeError". As
  508. // MicroPython doesn't implement any fallbacks, signal to raise
  509. // TypeError right away.
  510. if (res == mp_const_notimplemented) {
  511. return MP_OBJ_NULL; // op not supported
  512. }
  513. #endif
  514. return res;
  515. }
  516. STATIC void mp_obj_instance_load_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) {
  517. // logic: look in instance members then class locals
  518. assert(mp_obj_is_instance_type(mp_obj_get_type(self_in)));
  519. mp_obj_instance_t *self = MP_OBJ_TO_PTR(self_in);
  520. mp_map_elem_t *elem = mp_map_lookup(&self->members, MP_OBJ_NEW_QSTR(attr), MP_MAP_LOOKUP);
  521. if (elem != NULL) {
  522. // object member, always treated as a value
  523. dest[0] = elem->value;
  524. return;
  525. }
  526. #if MICROPY_CPYTHON_COMPAT
  527. if (attr == MP_QSTR___dict__) {
  528. // Create a new dict with a copy of the instance's map items.
  529. // This creates, unlike CPython, a 'read-only' __dict__: modifying
  530. // it will not result in modifications to the actual instance members.
  531. mp_map_t *map = &self->members;
  532. mp_obj_t attr_dict = mp_obj_new_dict(map->used);
  533. for (size_t i = 0; i < map->alloc; ++i) {
  534. if (MP_MAP_SLOT_IS_FILLED(map, i)) {
  535. mp_obj_dict_store(attr_dict, map->table[i].key, map->table[i].value);
  536. }
  537. }
  538. dest[0] = attr_dict;
  539. return;
  540. }
  541. #endif
  542. struct class_lookup_data lookup = {
  543. .obj = self,
  544. .attr = attr,
  545. .meth_offset = 0,
  546. .dest = dest,
  547. .is_type = false,
  548. };
  549. mp_obj_class_lookup(&lookup, self->base.type);
  550. mp_obj_t member = dest[0];
  551. if (member != MP_OBJ_NULL) {
  552. if (!(self->base.type->flags & TYPE_FLAG_HAS_SPECIAL_ACCESSORS)) {
  553. // Class doesn't have any special accessors to check so return straightaway
  554. return;
  555. }
  556. #if MICROPY_PY_BUILTINS_PROPERTY
  557. if (MP_OBJ_IS_TYPE(member, &mp_type_property)) {
  558. // object member is a property; delegate the load to the property
  559. // Note: This is an optimisation for code size and execution time.
  560. // The proper way to do it is have the functionality just below
  561. // in a __get__ method of the property object, and then it would
  562. // be called by the descriptor code down below. But that way
  563. // requires overhead for the nested mp_call's and overhead for
  564. // the code.
  565. const mp_obj_t *proxy = mp_obj_property_get(member);
  566. if (proxy[0] == mp_const_none) {
  567. mp_raise_msg(&mp_type_AttributeError, "unreadable attribute");
  568. } else {
  569. dest[0] = mp_call_function_n_kw(proxy[0], 1, 0, &self_in);
  570. }
  571. return;
  572. }
  573. #endif
  574. #if MICROPY_PY_DESCRIPTORS
  575. // found a class attribute; if it has a __get__ method then call it with the
  576. // class instance and class as arguments and return the result
  577. // Note that this is functionally correct but very slow: each load_attr
  578. // requires an extra mp_load_method_maybe to check for the __get__.
  579. mp_obj_t attr_get_method[4];
  580. mp_load_method_maybe(member, MP_QSTR___get__, attr_get_method);
  581. if (attr_get_method[0] != MP_OBJ_NULL) {
  582. attr_get_method[2] = self_in;
  583. attr_get_method[3] = MP_OBJ_FROM_PTR(mp_obj_get_type(self_in));
  584. dest[0] = mp_call_method_n_kw(2, 0, attr_get_method);
  585. }
  586. #endif
  587. return;
  588. }
  589. // try __getattr__
  590. if (attr != MP_QSTR___getattr__) {
  591. #if MICROPY_PY_DELATTR_SETATTR
  592. // If the requested attr is __setattr__/__delattr__ then don't delegate the lookup
  593. // to __getattr__. If we followed CPython's behaviour then __setattr__/__delattr__
  594. // would have already been found in the "object" base class.
  595. if (attr == MP_QSTR___setattr__ || attr == MP_QSTR___delattr__) {
  596. return;
  597. }
  598. #endif
  599. mp_obj_t dest2[3];
  600. mp_load_method_maybe(self_in, MP_QSTR___getattr__, dest2);
  601. if (dest2[0] != MP_OBJ_NULL) {
  602. // __getattr__ exists, call it and return its result
  603. // XXX if this fails to load the requested attr, should we catch the attribute error and return silently?
  604. dest2[2] = MP_OBJ_NEW_QSTR(attr);
  605. dest[0] = mp_call_method_n_kw(1, 0, dest2);
  606. return;
  607. }
  608. }
  609. }
  610. STATIC bool mp_obj_instance_store_attr(mp_obj_t self_in, qstr attr, mp_obj_t value) {
  611. mp_obj_instance_t *self = MP_OBJ_TO_PTR(self_in);
  612. if (!(self->base.type->flags & TYPE_FLAG_HAS_SPECIAL_ACCESSORS)) {
  613. // Class doesn't have any special accessors so skip their checks
  614. goto skip_special_accessors;
  615. }
  616. #if MICROPY_PY_BUILTINS_PROPERTY || MICROPY_PY_DESCRIPTORS
  617. // With property and/or descriptors enabled we need to do a lookup
  618. // first in the class dict for the attribute to see if the store should
  619. // be delegated.
  620. mp_obj_t member[2] = {MP_OBJ_NULL};
  621. struct class_lookup_data lookup = {
  622. .obj = self,
  623. .attr = attr,
  624. .meth_offset = 0,
  625. .dest = member,
  626. .is_type = false,
  627. };
  628. mp_obj_class_lookup(&lookup, self->base.type);
  629. if (member[0] != MP_OBJ_NULL) {
  630. #if MICROPY_PY_BUILTINS_PROPERTY
  631. if (MP_OBJ_IS_TYPE(member[0], &mp_type_property)) {
  632. // attribute exists and is a property; delegate the store/delete
  633. // Note: This is an optimisation for code size and execution time.
  634. // The proper way to do it is have the functionality just below in
  635. // a __set__/__delete__ method of the property object, and then it
  636. // would be called by the descriptor code down below. But that way
  637. // requires overhead for the nested mp_call's and overhead for
  638. // the code.
  639. const mp_obj_t *proxy = mp_obj_property_get(member[0]);
  640. mp_obj_t dest[2] = {self_in, value};
  641. if (value == MP_OBJ_NULL) {
  642. // delete attribute
  643. if (proxy[2] == mp_const_none) {
  644. // TODO better error message?
  645. return false;
  646. } else {
  647. mp_call_function_n_kw(proxy[2], 1, 0, dest);
  648. return true;
  649. }
  650. } else {
  651. // store attribute
  652. if (proxy[1] == mp_const_none) {
  653. // TODO better error message?
  654. return false;
  655. } else {
  656. mp_call_function_n_kw(proxy[1], 2, 0, dest);
  657. return true;
  658. }
  659. }
  660. }
  661. #endif
  662. #if MICROPY_PY_DESCRIPTORS
  663. // found a class attribute; if it has a __set__/__delete__ method then
  664. // call it with the class instance (and value) as arguments
  665. if (value == MP_OBJ_NULL) {
  666. // delete attribute
  667. mp_obj_t attr_delete_method[3];
  668. mp_load_method_maybe(member[0], MP_QSTR___delete__, attr_delete_method);
  669. if (attr_delete_method[0] != MP_OBJ_NULL) {
  670. attr_delete_method[2] = self_in;
  671. mp_call_method_n_kw(1, 0, attr_delete_method);
  672. return true;
  673. }
  674. } else {
  675. // store attribute
  676. mp_obj_t attr_set_method[4];
  677. mp_load_method_maybe(member[0], MP_QSTR___set__, attr_set_method);
  678. if (attr_set_method[0] != MP_OBJ_NULL) {
  679. attr_set_method[2] = self_in;
  680. attr_set_method[3] = value;
  681. mp_call_method_n_kw(2, 0, attr_set_method);
  682. return true;
  683. }
  684. }
  685. #endif
  686. }
  687. #endif
  688. #if MICROPY_PY_DELATTR_SETATTR
  689. if (value == MP_OBJ_NULL) {
  690. // delete attribute
  691. // try __delattr__ first
  692. mp_obj_t attr_delattr_method[3];
  693. mp_load_method_maybe(self_in, MP_QSTR___delattr__, attr_delattr_method);
  694. if (attr_delattr_method[0] != MP_OBJ_NULL) {
  695. // __delattr__ exists, so call it
  696. attr_delattr_method[2] = MP_OBJ_NEW_QSTR(attr);
  697. mp_call_method_n_kw(1, 0, attr_delattr_method);
  698. return true;
  699. }
  700. } else {
  701. // store attribute
  702. // try __setattr__ first
  703. mp_obj_t attr_setattr_method[4];
  704. mp_load_method_maybe(self_in, MP_QSTR___setattr__, attr_setattr_method);
  705. if (attr_setattr_method[0] != MP_OBJ_NULL) {
  706. // __setattr__ exists, so call it
  707. attr_setattr_method[2] = MP_OBJ_NEW_QSTR(attr);
  708. attr_setattr_method[3] = value;
  709. mp_call_method_n_kw(2, 0, attr_setattr_method);
  710. return true;
  711. }
  712. }
  713. #endif
  714. skip_special_accessors:
  715. if (value == MP_OBJ_NULL) {
  716. // delete attribute
  717. mp_map_elem_t *elem = mp_map_lookup(&self->members, MP_OBJ_NEW_QSTR(attr), MP_MAP_LOOKUP_REMOVE_IF_FOUND);
  718. return elem != NULL;
  719. } else {
  720. // store attribute
  721. mp_map_lookup(&self->members, MP_OBJ_NEW_QSTR(attr), MP_MAP_LOOKUP_ADD_IF_NOT_FOUND)->value = value;
  722. return true;
  723. }
  724. }
  725. STATIC void mp_obj_instance_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) {
  726. if (dest[0] == MP_OBJ_NULL) {
  727. mp_obj_instance_load_attr(self_in, attr, dest);
  728. } else {
  729. if (mp_obj_instance_store_attr(self_in, attr, dest[1])) {
  730. dest[0] = MP_OBJ_NULL; // indicate success
  731. }
  732. }
  733. }
  734. STATIC mp_obj_t instance_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) {
  735. mp_obj_instance_t *self = MP_OBJ_TO_PTR(self_in);
  736. mp_obj_t member[2] = {MP_OBJ_NULL};
  737. struct class_lookup_data lookup = {
  738. .obj = self,
  739. .meth_offset = offsetof(mp_obj_type_t, subscr),
  740. .dest = member,
  741. .is_type = false,
  742. };
  743. size_t meth_args;
  744. if (value == MP_OBJ_NULL) {
  745. // delete item
  746. lookup.attr = MP_QSTR___delitem__;
  747. mp_obj_class_lookup(&lookup, self->base.type);
  748. meth_args = 2;
  749. } else if (value == MP_OBJ_SENTINEL) {
  750. // load item
  751. lookup.attr = MP_QSTR___getitem__;
  752. mp_obj_class_lookup(&lookup, self->base.type);
  753. meth_args = 2;
  754. } else {
  755. // store item
  756. lookup.attr = MP_QSTR___setitem__;
  757. mp_obj_class_lookup(&lookup, self->base.type);
  758. meth_args = 3;
  759. }
  760. if (member[0] == MP_OBJ_SENTINEL) {
  761. return mp_obj_subscr(self->subobj[0], index, value);
  762. } else if (member[0] != MP_OBJ_NULL) {
  763. mp_obj_t args[3] = {self_in, index, value};
  764. // TODO probably need to call mp_convert_member_lookup, and use mp_call_method_n_kw
  765. mp_obj_t ret = mp_call_function_n_kw(member[0], meth_args, 0, args);
  766. if (value == MP_OBJ_SENTINEL) {
  767. return ret;
  768. } else {
  769. return mp_const_none;
  770. }
  771. } else {
  772. return MP_OBJ_NULL; // op not supported
  773. }
  774. }
  775. STATIC mp_obj_t mp_obj_instance_get_call(mp_obj_t self_in, mp_obj_t *member) {
  776. mp_obj_instance_t *self = MP_OBJ_TO_PTR(self_in);
  777. struct class_lookup_data lookup = {
  778. .obj = self,
  779. .attr = MP_QSTR___call__,
  780. .meth_offset = offsetof(mp_obj_type_t, call),
  781. .dest = member,
  782. .is_type = false,
  783. };
  784. mp_obj_class_lookup(&lookup, self->base.type);
  785. return member[0];
  786. }
  787. bool mp_obj_instance_is_callable(mp_obj_t self_in) {
  788. mp_obj_t member[2] = {MP_OBJ_NULL, MP_OBJ_NULL};
  789. return mp_obj_instance_get_call(self_in, member) != MP_OBJ_NULL;
  790. }
  791. mp_obj_t mp_obj_instance_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp_obj_t *args) {
  792. mp_obj_t member[2] = {MP_OBJ_NULL, MP_OBJ_NULL};
  793. mp_obj_t call = mp_obj_instance_get_call(self_in, member);
  794. if (call == MP_OBJ_NULL) {
  795. if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
  796. mp_raise_TypeError("object not callable");
  797. } else {
  798. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
  799. "'%s' object is not callable", mp_obj_get_type_str(self_in)));
  800. }
  801. }
  802. mp_obj_instance_t *self = MP_OBJ_TO_PTR(self_in);
  803. if (call == MP_OBJ_SENTINEL) {
  804. return mp_call_function_n_kw(self->subobj[0], n_args, n_kw, args);
  805. }
  806. return mp_call_method_self_n_kw(member[0], member[1], n_args, n_kw, args);
  807. }
  808. STATIC mp_obj_t instance_getiter(mp_obj_t self_in, mp_obj_iter_buf_t *iter_buf) {
  809. mp_obj_instance_t *self = MP_OBJ_TO_PTR(self_in);
  810. mp_obj_t member[2] = {MP_OBJ_NULL};
  811. struct class_lookup_data lookup = {
  812. .obj = self,
  813. .attr = MP_QSTR___iter__,
  814. .meth_offset = offsetof(mp_obj_type_t, getiter),
  815. .dest = member,
  816. .is_type = false,
  817. };
  818. mp_obj_class_lookup(&lookup, self->base.type);
  819. if (member[0] == MP_OBJ_NULL) {
  820. return MP_OBJ_NULL;
  821. } else if (member[0] == MP_OBJ_SENTINEL) {
  822. mp_obj_type_t *type = mp_obj_get_type(self->subobj[0]);
  823. return type->getiter(self->subobj[0], iter_buf);
  824. } else {
  825. return mp_call_method_n_kw(0, 0, member);
  826. }
  827. }
  828. STATIC mp_int_t instance_get_buffer(mp_obj_t self_in, mp_buffer_info_t *bufinfo, mp_uint_t flags) {
  829. mp_obj_instance_t *self = MP_OBJ_TO_PTR(self_in);
  830. mp_obj_t member[2] = {MP_OBJ_NULL};
  831. struct class_lookup_data lookup = {
  832. .obj = self,
  833. .attr = MP_QSTR_, // don't actually look for a method
  834. .meth_offset = offsetof(mp_obj_type_t, buffer_p.get_buffer),
  835. .dest = member,
  836. .is_type = false,
  837. };
  838. mp_obj_class_lookup(&lookup, self->base.type);
  839. if (member[0] == MP_OBJ_SENTINEL) {
  840. mp_obj_type_t *type = mp_obj_get_type(self->subobj[0]);
  841. return type->buffer_p.get_buffer(self->subobj[0], bufinfo, flags);
  842. } else {
  843. return 1; // object does not support buffer protocol
  844. }
  845. }
  846. /******************************************************************************/
  847. // type object
  848. // - the struct is mp_obj_type_t and is defined in obj.h so const types can be made
  849. // - there is a constant mp_obj_type_t (called mp_type_type) for the 'type' object
  850. // - creating a new class (a new type) creates a new mp_obj_type_t
  851. #if ENABLE_SPECIAL_ACCESSORS
  852. STATIC bool check_for_special_accessors(mp_obj_t key, mp_obj_t value) {
  853. #if MICROPY_PY_DELATTR_SETATTR
  854. if (key == MP_OBJ_NEW_QSTR(MP_QSTR___setattr__) || key == MP_OBJ_NEW_QSTR(MP_QSTR___delattr__)) {
  855. return true;
  856. }
  857. #endif
  858. #if MICROPY_PY_BUILTINS_PROPERTY
  859. if (MP_OBJ_IS_TYPE(value, &mp_type_property)) {
  860. return true;
  861. }
  862. #endif
  863. #if MICROPY_PY_DESCRIPTORS
  864. static const uint8_t to_check[] = {
  865. MP_QSTR___get__, MP_QSTR___set__, MP_QSTR___delete__,
  866. };
  867. for (size_t i = 0; i < MP_ARRAY_SIZE(to_check); ++i) {
  868. mp_obj_t dest_temp[2];
  869. mp_load_method_protected(value, to_check[i], dest_temp, true);
  870. if (dest_temp[0] != MP_OBJ_NULL) {
  871. return true;
  872. }
  873. }
  874. #endif
  875. return false;
  876. }
  877. #endif
  878. STATIC void type_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
  879. (void)kind;
  880. mp_obj_type_t *self = MP_OBJ_TO_PTR(self_in);
  881. mp_printf(print, "<class '%q'>", self->name);
  882. }
  883. STATIC mp_obj_t type_make_new(const mp_obj_type_t *type_in, size_t n_args, size_t n_kw, const mp_obj_t *args) {
  884. (void)type_in;
  885. mp_arg_check_num(n_args, n_kw, 1, 3, false);
  886. switch (n_args) {
  887. case 1:
  888. return MP_OBJ_FROM_PTR(mp_obj_get_type(args[0]));
  889. case 3:
  890. // args[0] = name
  891. // args[1] = bases tuple
  892. // args[2] = locals dict
  893. return mp_obj_new_type(mp_obj_str_get_qstr(args[0]), args[1], args[2]);
  894. default:
  895. mp_raise_TypeError("type takes 1 or 3 arguments");
  896. }
  897. }
  898. STATIC mp_obj_t type_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp_obj_t *args) {
  899. // instantiate an instance of a class
  900. mp_obj_type_t *self = MP_OBJ_TO_PTR(self_in);
  901. if (self->make_new == NULL) {
  902. if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
  903. mp_raise_TypeError("cannot create instance");
  904. } else {
  905. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
  906. "cannot create '%q' instances", self->name));
  907. }
  908. }
  909. // make new instance
  910. mp_obj_t o = self->make_new(self, n_args, n_kw, args);
  911. // return new instance
  912. return o;
  913. }
  914. STATIC void type_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) {
  915. assert(MP_OBJ_IS_TYPE(self_in, &mp_type_type));
  916. mp_obj_type_t *self = MP_OBJ_TO_PTR(self_in);
  917. if (dest[0] == MP_OBJ_NULL) {
  918. // load attribute
  919. #if MICROPY_CPYTHON_COMPAT
  920. if (attr == MP_QSTR___name__) {
  921. dest[0] = MP_OBJ_NEW_QSTR(self->name);
  922. return;
  923. }
  924. #endif
  925. struct class_lookup_data lookup = {
  926. .obj = (mp_obj_instance_t*)self,
  927. .attr = attr,
  928. .meth_offset = 0,
  929. .dest = dest,
  930. .is_type = true,
  931. };
  932. mp_obj_class_lookup(&lookup, self);
  933. } else {
  934. // delete/store attribute
  935. // TODO CPython allows STORE_ATTR to a class, but is this the correct implementation?
  936. if (self->locals_dict != NULL) {
  937. assert(self->locals_dict->base.type == &mp_type_dict); // MicroPython restriction, for now
  938. mp_map_t *locals_map = &self->locals_dict->map;
  939. if (locals_map->is_fixed) {
  940. // can't apply delete/store to a fixed map
  941. return;
  942. }
  943. if (dest[1] == MP_OBJ_NULL) {
  944. // delete attribute
  945. mp_map_elem_t *elem = mp_map_lookup(locals_map, MP_OBJ_NEW_QSTR(attr), MP_MAP_LOOKUP_REMOVE_IF_FOUND);
  946. if (elem != NULL) {
  947. dest[0] = MP_OBJ_NULL; // indicate success
  948. }
  949. } else {
  950. #if ENABLE_SPECIAL_ACCESSORS
  951. // Check if we add any special accessor methods with this store
  952. if (!(self->flags & TYPE_FLAG_HAS_SPECIAL_ACCESSORS)) {
  953. if (check_for_special_accessors(MP_OBJ_NEW_QSTR(attr), dest[1])) {
  954. if (self->flags & TYPE_FLAG_IS_SUBCLASSED) {
  955. // This class is already subclassed so can't have special accessors added
  956. mp_raise_msg(&mp_type_AttributeError, "can't add special method to already-subclassed class");
  957. }
  958. self->flags |= TYPE_FLAG_HAS_SPECIAL_ACCESSORS;
  959. }
  960. }
  961. #endif
  962. // store attribute
  963. mp_map_elem_t *elem = mp_map_lookup(locals_map, MP_OBJ_NEW_QSTR(attr), MP_MAP_LOOKUP_ADD_IF_NOT_FOUND);
  964. elem->value = dest[1];
  965. dest[0] = MP_OBJ_NULL; // indicate success
  966. }
  967. }
  968. }
  969. }
  970. const mp_obj_type_t mp_type_type = {
  971. { &mp_type_type },
  972. .name = MP_QSTR_type,
  973. .print = type_print,
  974. .make_new = type_make_new,
  975. .call = type_call,
  976. .unary_op = mp_generic_unary_op,
  977. .attr = type_attr,
  978. };
  979. mp_obj_t mp_obj_new_type(qstr name, mp_obj_t bases_tuple, mp_obj_t locals_dict) {
  980. // Verify input objects have expected type
  981. if (!MP_OBJ_IS_TYPE(bases_tuple, &mp_type_tuple)) {
  982. mp_raise_TypeError(NULL);
  983. }
  984. if (!MP_OBJ_IS_TYPE(locals_dict, &mp_type_dict)) {
  985. mp_raise_TypeError(NULL);
  986. }
  987. // TODO might need to make a copy of locals_dict; at least that's how CPython does it
  988. // Basic validation of base classes
  989. uint16_t base_flags = 0;
  990. size_t bases_len;
  991. mp_obj_t *bases_items;
  992. mp_obj_tuple_get(bases_tuple, &bases_len, &bases_items);
  993. for (size_t i = 0; i < bases_len; i++) {
  994. if (!MP_OBJ_IS_TYPE(bases_items[i], &mp_type_type)) {
  995. mp_raise_TypeError(NULL);
  996. }
  997. mp_obj_type_t *t = MP_OBJ_TO_PTR(bases_items[i]);
  998. // TODO: Verify with CPy, tested on function type
  999. if (t->make_new == NULL) {
  1000. if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
  1001. mp_raise_TypeError("type is not an acceptable base type");
  1002. } else {
  1003. nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
  1004. "type '%q' is not an acceptable base type", t->name));
  1005. }
  1006. }
  1007. #if ENABLE_SPECIAL_ACCESSORS
  1008. if (mp_obj_is_instance_type(t)) {
  1009. t->flags |= TYPE_FLAG_IS_SUBCLASSED;
  1010. base_flags |= t->flags & TYPE_FLAG_HAS_SPECIAL_ACCESSORS;
  1011. }
  1012. #endif
  1013. }
  1014. mp_obj_type_t *o = m_new0(mp_obj_type_t, 1);
  1015. o->base.type = &mp_type_type;
  1016. o->flags = base_flags;
  1017. o->name = name;
  1018. o->print = instance_print;
  1019. o->make_new = mp_obj_instance_make_new;
  1020. o->call = mp_obj_instance_call;
  1021. o->unary_op = instance_unary_op;
  1022. o->binary_op = instance_binary_op;
  1023. o->attr = mp_obj_instance_attr;
  1024. o->subscr = instance_subscr;
  1025. o->getiter = instance_getiter;
  1026. //o->iternext = ; not implemented
  1027. o->buffer_p.get_buffer = instance_get_buffer;
  1028. if (bases_len > 0) {
  1029. // Inherit protocol from a base class. This allows to define an
  1030. // abstract base class which would translate C-level protocol to
  1031. // Python method calls, and any subclass inheriting from it will
  1032. // support this feature.
  1033. o->protocol = ((mp_obj_type_t*)MP_OBJ_TO_PTR(bases_items[0]))->protocol;
  1034. if (bases_len >= 2) {
  1035. #if MICROPY_MULTIPLE_INHERITANCE
  1036. o->parent = MP_OBJ_TO_PTR(bases_tuple);
  1037. #else
  1038. mp_raise_NotImplementedError("multiple inheritance not supported");
  1039. #endif
  1040. } else {
  1041. o->parent = MP_OBJ_TO_PTR(bases_items[0]);
  1042. }
  1043. }
  1044. o->locals_dict = MP_OBJ_TO_PTR(locals_dict);
  1045. #if ENABLE_SPECIAL_ACCESSORS
  1046. // Check if the class has any special accessor methods
  1047. if (!(o->flags & TYPE_FLAG_HAS_SPECIAL_ACCESSORS)) {
  1048. for (size_t i = 0; i < o->locals_dict->map.alloc; i++) {
  1049. if (MP_MAP_SLOT_IS_FILLED(&o->locals_dict->map, i)) {
  1050. const mp_map_elem_t *elem = &o->locals_dict->map.table[i];
  1051. if (check_for_special_accessors(elem->key, elem->value)) {
  1052. o->flags |= TYPE_FLAG_HAS_SPECIAL_ACCESSORS;
  1053. break;
  1054. }
  1055. }
  1056. }
  1057. }
  1058. #endif
  1059. const mp_obj_type_t *native_base;
  1060. size_t num_native_bases = instance_count_native_bases(o, &native_base);
  1061. if (num_native_bases > 1) {
  1062. mp_raise_TypeError("multiple bases have instance lay-out conflict");
  1063. }
  1064. mp_map_t *locals_map = &o->locals_dict->map;
  1065. mp_map_elem_t *elem = mp_map_lookup(locals_map, MP_OBJ_NEW_QSTR(MP_QSTR___new__), MP_MAP_LOOKUP);
  1066. if (elem != NULL) {
  1067. // __new__ slot exists; check if it is a function
  1068. if (MP_OBJ_IS_FUN(elem->value)) {
  1069. // __new__ is a function, wrap it in a staticmethod decorator
  1070. elem->value = static_class_method_make_new(&mp_type_staticmethod, 1, 0, &elem->value);
  1071. }
  1072. }
  1073. return MP_OBJ_FROM_PTR(o);
  1074. }
  1075. /******************************************************************************/
  1076. // super object
  1077. typedef struct _mp_obj_super_t {
  1078. mp_obj_base_t base;
  1079. mp_obj_t type;
  1080. mp_obj_t obj;
  1081. } mp_obj_super_t;
  1082. STATIC void super_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
  1083. (void)kind;
  1084. mp_obj_super_t *self = MP_OBJ_TO_PTR(self_in);
  1085. mp_print_str(print, "<super: ");
  1086. mp_obj_print_helper(print, self->type, PRINT_STR);
  1087. mp_print_str(print, ", ");
  1088. mp_obj_print_helper(print, self->obj, PRINT_STR);
  1089. mp_print_str(print, ">");
  1090. }
  1091. STATIC mp_obj_t super_make_new(const mp_obj_type_t *type_in, size_t n_args, size_t n_kw, const mp_obj_t *args) {
  1092. (void)type_in;
  1093. // 0 arguments are turned into 2 in the compiler
  1094. // 1 argument is not yet implemented
  1095. mp_arg_check_num(n_args, n_kw, 2, 2, false);
  1096. if (!MP_OBJ_IS_TYPE(args[0], &mp_type_type)) {
  1097. mp_raise_TypeError(NULL);
  1098. }
  1099. mp_obj_super_t *o = m_new_obj(mp_obj_super_t);
  1100. *o = (mp_obj_super_t){{type_in}, args[0], args[1]};
  1101. return MP_OBJ_FROM_PTR(o);
  1102. }
  1103. STATIC void super_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) {
  1104. if (dest[0] != MP_OBJ_NULL) {
  1105. // not load attribute
  1106. return;
  1107. }
  1108. assert(MP_OBJ_IS_TYPE(self_in, &mp_type_super));
  1109. mp_obj_super_t *self = MP_OBJ_TO_PTR(self_in);
  1110. assert(MP_OBJ_IS_TYPE(self->type, &mp_type_type));
  1111. mp_obj_type_t *type = MP_OBJ_TO_PTR(self->type);
  1112. struct class_lookup_data lookup = {
  1113. .obj = MP_OBJ_TO_PTR(self->obj),
  1114. .attr = attr,
  1115. .meth_offset = 0,
  1116. .dest = dest,
  1117. .is_type = false,
  1118. };
  1119. // Allow a call super().__init__() to reach any native base classes
  1120. if (attr == MP_QSTR___init__) {
  1121. lookup.meth_offset = offsetof(mp_obj_type_t, make_new);
  1122. }
  1123. if (type->parent == NULL) {
  1124. // no parents, do nothing
  1125. #if MICROPY_MULTIPLE_INHERITANCE
  1126. } else if (((mp_obj_base_t*)type->parent)->type == &mp_type_tuple) {
  1127. const mp_obj_tuple_t *parent_tuple = type->parent;
  1128. size_t len = parent_tuple->len;
  1129. const mp_obj_t *items = parent_tuple->items;
  1130. for (size_t i = 0; i < len; i++) {
  1131. assert(MP_OBJ_IS_TYPE(items[i], &mp_type_type));
  1132. if (MP_OBJ_TO_PTR(items[i]) == &mp_type_object) {
  1133. // The "object" type will be searched at the end of this function,
  1134. // and we don't want to lookup native methods in object.
  1135. continue;
  1136. }
  1137. mp_obj_class_lookup(&lookup, (mp_obj_type_t*)MP_OBJ_TO_PTR(items[i]));
  1138. if (dest[0] != MP_OBJ_NULL) {
  1139. break;
  1140. }
  1141. }
  1142. #endif
  1143. } else if (type->parent != &mp_type_object) {
  1144. mp_obj_class_lookup(&lookup, type->parent);
  1145. }
  1146. if (dest[0] != MP_OBJ_NULL) {
  1147. if (dest[0] == MP_OBJ_SENTINEL) {
  1148. // Looked up native __init__ so defer to it
  1149. dest[0] = MP_OBJ_FROM_PTR(&native_base_init_wrapper_obj);
  1150. dest[1] = self->obj;
  1151. }
  1152. return;
  1153. }
  1154. // Reset meth_offset so we don't look up any native methods in object,
  1155. // because object never takes up the native base-class slot.
  1156. lookup.meth_offset = 0;
  1157. mp_obj_class_lookup(&lookup, &mp_type_object);
  1158. }
  1159. const mp_obj_type_t mp_type_super = {
  1160. { &mp_type_type },
  1161. .name = MP_QSTR_super,
  1162. .print = super_print,
  1163. .make_new = super_make_new,
  1164. .attr = super_attr,
  1165. };
  1166. void mp_load_super_method(qstr attr, mp_obj_t *dest) {
  1167. mp_obj_super_t super = {{&mp_type_super}, dest[1], dest[2]};
  1168. mp_load_method(MP_OBJ_FROM_PTR(&super), attr, dest);
  1169. }
  1170. /******************************************************************************/
  1171. // subclassing and built-ins specific to types
  1172. // object and classinfo should be type objects
  1173. // (but the function will fail gracefully if they are not)
  1174. bool mp_obj_is_subclass_fast(mp_const_obj_t object, mp_const_obj_t classinfo) {
  1175. for (;;) {
  1176. if (object == classinfo) {
  1177. return true;
  1178. }
  1179. // not equivalent classes, keep searching base classes
  1180. // object should always be a type object, but just return false if it's not
  1181. if (!MP_OBJ_IS_TYPE(object, &mp_type_type)) {
  1182. return false;
  1183. }
  1184. const mp_obj_type_t *self = MP_OBJ_TO_PTR(object);
  1185. if (self->parent == NULL) {
  1186. // type has no parents
  1187. return false;
  1188. #if MICROPY_MULTIPLE_INHERITANCE
  1189. } else if (((mp_obj_base_t*)self->parent)->type == &mp_type_tuple) {
  1190. // get the base objects (they should be type objects)
  1191. const mp_obj_tuple_t *parent_tuple = self->parent;
  1192. const mp_obj_t *item = parent_tuple->items;
  1193. const mp_obj_t *top = item + parent_tuple->len - 1;
  1194. // iterate through the base objects
  1195. for (; item < top; ++item) {
  1196. if (mp_obj_is_subclass_fast(*item, classinfo)) {
  1197. return true;
  1198. }
  1199. }
  1200. // search last base (simple tail recursion elimination)
  1201. object = *item;
  1202. #endif
  1203. } else {
  1204. // type has 1 parent
  1205. object = MP_OBJ_FROM_PTR(self->parent);
  1206. }
  1207. }
  1208. }
  1209. STATIC mp_obj_t mp_obj_is_subclass(mp_obj_t object, mp_obj_t classinfo) {
  1210. size_t len;
  1211. mp_obj_t *items;
  1212. if (MP_OBJ_IS_TYPE(classinfo, &mp_type_type)) {
  1213. len = 1;
  1214. items = &classinfo;
  1215. } else if (MP_OBJ_IS_TYPE(classinfo, &mp_type_tuple)) {
  1216. mp_obj_tuple_get(classinfo, &len, &items);
  1217. } else {
  1218. mp_raise_TypeError("issubclass() arg 2 must be a class or a tuple of classes");
  1219. }
  1220. for (size_t i = 0; i < len; i++) {
  1221. // We explicitly check for 'object' here since no-one explicitly derives from it
  1222. if (items[i] == MP_OBJ_FROM_PTR(&mp_type_object) || mp_obj_is_subclass_fast(object, items[i])) {
  1223. return mp_const_true;
  1224. }
  1225. }
  1226. return mp_const_false;
  1227. }
  1228. STATIC mp_obj_t mp_builtin_issubclass(mp_obj_t object, mp_obj_t classinfo) {
  1229. if (!MP_OBJ_IS_TYPE(object, &mp_type_type)) {
  1230. mp_raise_TypeError("issubclass() arg 1 must be a class");
  1231. }
  1232. return mp_obj_is_subclass(object, classinfo);
  1233. }
  1234. MP_DEFINE_CONST_FUN_OBJ_2(mp_builtin_issubclass_obj, mp_builtin_issubclass);
  1235. STATIC mp_obj_t mp_builtin_isinstance(mp_obj_t object, mp_obj_t classinfo) {
  1236. return mp_obj_is_subclass(MP_OBJ_FROM_PTR(mp_obj_get_type(object)), classinfo);
  1237. }
  1238. MP_DEFINE_CONST_FUN_OBJ_2(mp_builtin_isinstance_obj, mp_builtin_isinstance);
  1239. mp_obj_t mp_instance_cast_to_native_base(mp_const_obj_t self_in, mp_const_obj_t native_type) {
  1240. mp_obj_type_t *self_type = mp_obj_get_type(self_in);
  1241. if (!mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(self_type), native_type)) {
  1242. return MP_OBJ_NULL;
  1243. }
  1244. mp_obj_instance_t *self = (mp_obj_instance_t*)MP_OBJ_TO_PTR(self_in);
  1245. return self->subobj[0];
  1246. }
  1247. /******************************************************************************/
  1248. // staticmethod and classmethod types (probably should go in a different file)
  1249. STATIC mp_obj_t static_class_method_make_new(const mp_obj_type_t *self, size_t n_args, size_t n_kw, const mp_obj_t *args) {
  1250. assert(self == &mp_type_staticmethod || self == &mp_type_classmethod);
  1251. mp_arg_check_num(n_args, n_kw, 1, 1, false);
  1252. mp_obj_static_class_method_t *o = m_new_obj(mp_obj_static_class_method_t);
  1253. *o = (mp_obj_static_class_method_t){{self}, args[0]};
  1254. return MP_OBJ_FROM_PTR(o);
  1255. }
  1256. const mp_obj_type_t mp_type_staticmethod = {
  1257. { &mp_type_type },
  1258. .name = MP_QSTR_staticmethod,
  1259. .make_new = static_class_method_make_new,
  1260. };
  1261. const mp_obj_type_t mp_type_classmethod = {
  1262. { &mp_type_type },
  1263. .name = MP_QSTR_classmethod,
  1264. .make_new = static_class_method_make_new,
  1265. };