objtype.c 50 KB

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