objtype.c 48 KB

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