obj.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  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. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy
  9. * of this software and associated documentation files (the "Software"), to deal
  10. * in the Software without restriction, including without limitation the rights
  11. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. * copies of the Software, and to permit persons to whom the Software is
  13. * furnished to do so, subject to the following conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in
  16. * all copies or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  24. * THE SOFTWARE.
  25. */
  26. #include <stdint.h>
  27. #include <stdio.h>
  28. #include <stdarg.h>
  29. #include <assert.h>
  30. #include "py/obj.h"
  31. #include "py/objtype.h"
  32. #include "py/objint.h"
  33. #include "py/objstr.h"
  34. #include "py/runtime.h"
  35. #include "py/stackctrl.h"
  36. #include "py/stream.h" // for mp_obj_print
  37. // Allocates an object and also sets type, for mp_obj_malloc{,_var} macros.
  38. MP_NOINLINE void *mp_obj_malloc_helper(size_t num_bytes, const mp_obj_type_t *type) {
  39. mp_obj_base_t *base = (mp_obj_base_t *)m_malloc(num_bytes);
  40. base->type = type;
  41. return base;
  42. }
  43. #if MICROPY_ENABLE_FINALISER
  44. // Allocates an object and also sets type, for mp_obj_malloc{,_var}_with_finaliser macros.
  45. MP_NOINLINE void *mp_obj_malloc_with_finaliser_helper(size_t num_bytes, const mp_obj_type_t *type) {
  46. mp_obj_base_t *base = (mp_obj_base_t *)m_malloc_with_finaliser(num_bytes);
  47. base->type = type;
  48. return base;
  49. }
  50. #endif
  51. const mp_obj_type_t *MICROPY_WRAP_MP_OBJ_GET_TYPE(mp_obj_get_type)(mp_const_obj_t o_in) {
  52. #if MICROPY_OBJ_IMMEDIATE_OBJS && MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_A
  53. if (mp_obj_is_obj(o_in)) {
  54. const mp_obj_base_t *o = MP_OBJ_TO_PTR(o_in);
  55. return o->type;
  56. } else {
  57. static const mp_obj_type_t *const types[] = {
  58. NULL, &mp_type_int, &mp_type_str, &mp_type_int,
  59. NULL, &mp_type_int, &mp_type_NoneType, &mp_type_int,
  60. NULL, &mp_type_int, &mp_type_str, &mp_type_int,
  61. NULL, &mp_type_int, &mp_type_bool, &mp_type_int,
  62. };
  63. return types[(uintptr_t)o_in & 0xf];
  64. }
  65. #elif MICROPY_OBJ_IMMEDIATE_OBJS && MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_C
  66. if (mp_obj_is_small_int(o_in)) {
  67. return &mp_type_int;
  68. } else if (mp_obj_is_obj(o_in)) {
  69. const mp_obj_base_t *o = MP_OBJ_TO_PTR(o_in);
  70. return o->type;
  71. #if MICROPY_PY_BUILTINS_FLOAT
  72. } else if ((((mp_uint_t)(o_in)) & 0xff800007) != 0x00000006) {
  73. return &mp_type_float;
  74. #endif
  75. } else {
  76. static const mp_obj_type_t *const types[] = {
  77. &mp_type_str, &mp_type_NoneType, &mp_type_str, &mp_type_bool,
  78. };
  79. return types[((uintptr_t)o_in >> 3) & 3];
  80. }
  81. #else
  82. if (mp_obj_is_small_int(o_in)) {
  83. return &mp_type_int;
  84. } else if (mp_obj_is_qstr(o_in)) {
  85. return &mp_type_str;
  86. #if MICROPY_PY_BUILTINS_FLOAT && ( \
  87. MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_C || MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_D)
  88. } else if (mp_obj_is_float(o_in)) {
  89. return &mp_type_float;
  90. #endif
  91. #if MICROPY_OBJ_IMMEDIATE_OBJS
  92. } else if (mp_obj_is_immediate_obj(o_in)) {
  93. static const mp_obj_type_t *const types[2] = {&mp_type_NoneType, &mp_type_bool};
  94. return types[MP_OBJ_IMMEDIATE_OBJ_VALUE(o_in) & 1];
  95. #endif
  96. } else {
  97. const mp_obj_base_t *o = MP_OBJ_TO_PTR(o_in);
  98. return o->type;
  99. }
  100. #endif
  101. }
  102. const char *mp_obj_get_type_str(mp_const_obj_t o_in) {
  103. return qstr_str(mp_obj_get_type(o_in)->name);
  104. }
  105. void mp_obj_print_helper(const mp_print_t *print, mp_obj_t o_in, mp_print_kind_t kind) {
  106. // There can be data structures nested too deep, or just recursive
  107. MP_STACK_CHECK();
  108. #ifndef NDEBUG
  109. if (o_in == MP_OBJ_NULL) {
  110. mp_print_str(print, "(nil)");
  111. return;
  112. }
  113. #endif
  114. const mp_obj_type_t *type = mp_obj_get_type(o_in);
  115. if (MP_OBJ_TYPE_HAS_SLOT(type, print)) {
  116. MP_OBJ_TYPE_GET_SLOT(type, print)((mp_print_t *)print, o_in, kind);
  117. } else {
  118. mp_printf(print, "<%q>", type->name);
  119. }
  120. }
  121. void mp_obj_print(mp_obj_t o_in, mp_print_kind_t kind) {
  122. mp_obj_print_helper(MP_PYTHON_PRINTER, o_in, kind);
  123. }
  124. // helper function to print an exception with traceback
  125. void mp_obj_print_exception(const mp_print_t *print, mp_obj_t exc) {
  126. if (mp_obj_is_exception_instance(exc)) {
  127. size_t n, *values;
  128. mp_obj_exception_get_traceback(exc, &n, &values);
  129. if (n > 0) {
  130. assert(n % 3 == 0);
  131. mp_print_str(print, "Traceback (most recent call last):\n");
  132. for (int i = n - 3; i >= 0; i -= 3) {
  133. #if MICROPY_ENABLE_SOURCE_LINE
  134. mp_printf(print, " File \"%q\", line %d", values[i], (int)values[i + 1]);
  135. #else
  136. mp_printf(print, " File \"%q\"", values[i]);
  137. #endif
  138. // the block name can be NULL if it's unknown
  139. qstr block = values[i + 2];
  140. if (block == MP_QSTRnull) {
  141. mp_print_str(print, "\n");
  142. } else {
  143. mp_printf(print, ", in %q\n", block);
  144. }
  145. }
  146. }
  147. }
  148. mp_obj_print_helper(print, exc, PRINT_EXC);
  149. mp_print_str(print, "\n");
  150. }
  151. bool mp_obj_is_true(mp_obj_t arg) {
  152. if (arg == mp_const_false) {
  153. return 0;
  154. } else if (arg == mp_const_true) {
  155. return 1;
  156. } else if (arg == mp_const_none) {
  157. return 0;
  158. } else if (mp_obj_is_small_int(arg)) {
  159. if (arg == MP_OBJ_NEW_SMALL_INT(0)) {
  160. return 0;
  161. } else {
  162. return 1;
  163. }
  164. } else {
  165. const mp_obj_type_t *type = mp_obj_get_type(arg);
  166. if (MP_OBJ_TYPE_HAS_SLOT(type, unary_op)) {
  167. mp_obj_t result = MP_OBJ_TYPE_GET_SLOT(type, unary_op)(MP_UNARY_OP_BOOL, arg);
  168. if (result != MP_OBJ_NULL) {
  169. return result == mp_const_true;
  170. }
  171. }
  172. mp_obj_t len = mp_obj_len_maybe(arg);
  173. if (len != MP_OBJ_NULL) {
  174. // obj has a length, truth determined if len != 0
  175. return len != MP_OBJ_NEW_SMALL_INT(0);
  176. } else {
  177. // any other obj is true per Python semantics
  178. return 1;
  179. }
  180. }
  181. }
  182. bool mp_obj_is_callable(mp_obj_t o_in) {
  183. const mp_call_fun_t call = MP_OBJ_TYPE_GET_SLOT_OR_NULL(mp_obj_get_type(o_in), call);
  184. if (call != mp_obj_instance_call) {
  185. return call != NULL;
  186. }
  187. return mp_obj_instance_is_callable(o_in);
  188. }
  189. // This function implements the '==' and '!=' operators.
  190. //
  191. // From the Python language reference:
  192. // (https://docs.python.org/3/reference/expressions.html#not-in)
  193. // "The objects need not have the same type. If both are numbers, they are converted
  194. // to a common type. Otherwise, the == and != operators always consider objects of
  195. // different types to be unequal."
  196. //
  197. // This means that False==0 and True==1 are true expressions.
  198. //
  199. // Furthermore, from the v3.4.2 code for object.c: "Practical amendments: If rich
  200. // comparison returns NotImplemented, == and != are decided by comparing the object
  201. // pointer."
  202. mp_obj_t mp_obj_equal_not_equal(mp_binary_op_t op, mp_obj_t o1, mp_obj_t o2) {
  203. mp_obj_t local_true = (op == MP_BINARY_OP_NOT_EQUAL) ? mp_const_false : mp_const_true;
  204. mp_obj_t local_false = (op == MP_BINARY_OP_NOT_EQUAL) ? mp_const_true : mp_const_false;
  205. int pass_number = 0;
  206. // Shortcut for very common cases
  207. if (o1 == o2 &&
  208. (mp_obj_is_small_int(o1) || !(mp_obj_get_type(o1)->flags & MP_TYPE_FLAG_EQ_NOT_REFLEXIVE))) {
  209. return local_true;
  210. }
  211. // fast path for strings
  212. if (mp_obj_is_str(o1)) {
  213. if (mp_obj_is_str(o2)) {
  214. // both strings, use special function
  215. return mp_obj_str_equal(o1, o2) ? local_true : local_false;
  216. #if MICROPY_PY_STR_BYTES_CMP_WARN
  217. } else if (mp_obj_is_type(o2, &mp_type_bytes)) {
  218. str_bytes_cmp:
  219. mp_warning(MP_WARN_CAT(BytesWarning), "Comparison between bytes and str");
  220. return local_false;
  221. #endif
  222. } else {
  223. goto skip_one_pass;
  224. }
  225. #if MICROPY_PY_STR_BYTES_CMP_WARN
  226. } else if (mp_obj_is_str(o2) && mp_obj_is_type(o1, &mp_type_bytes)) {
  227. // o1 is not a string (else caught above), so the objects are not equal
  228. goto str_bytes_cmp;
  229. #endif
  230. }
  231. // fast path for small ints
  232. if (mp_obj_is_small_int(o1)) {
  233. if (mp_obj_is_small_int(o2)) {
  234. // both SMALL_INT, and not equal if we get here
  235. return local_false;
  236. } else {
  237. goto skip_one_pass;
  238. }
  239. }
  240. // generic type, call binary_op(MP_BINARY_OP_EQUAL)
  241. while (pass_number < 2) {
  242. const mp_obj_type_t *type = mp_obj_get_type(o1);
  243. // If a full equality test is not needed and the other object is a different
  244. // type then we don't need to bother trying the comparison.
  245. if (MP_OBJ_TYPE_HAS_SLOT(type, binary_op) &&
  246. ((type->flags & MP_TYPE_FLAG_EQ_CHECKS_OTHER_TYPE) || mp_obj_get_type(o2) == type)) {
  247. // CPython is asymmetric: it will try __eq__ if there's no __ne__ but not the
  248. // other way around. If the class doesn't need a full test we can skip __ne__.
  249. if (op == MP_BINARY_OP_NOT_EQUAL && (type->flags & MP_TYPE_FLAG_EQ_HAS_NEQ_TEST)) {
  250. mp_obj_t r = MP_OBJ_TYPE_GET_SLOT(type, binary_op)(MP_BINARY_OP_NOT_EQUAL, o1, o2);
  251. if (r != MP_OBJ_NULL) {
  252. return r;
  253. }
  254. }
  255. // Try calling __eq__.
  256. mp_obj_t r = MP_OBJ_TYPE_GET_SLOT(type, binary_op)(MP_BINARY_OP_EQUAL, o1, o2);
  257. if (r != MP_OBJ_NULL) {
  258. if (op == MP_BINARY_OP_EQUAL) {
  259. return r;
  260. } else {
  261. return mp_obj_is_true(r) ? local_true : local_false;
  262. }
  263. }
  264. }
  265. skip_one_pass:
  266. // Try the other way around if none of the above worked
  267. ++pass_number;
  268. mp_obj_t temp = o1;
  269. o1 = o2;
  270. o2 = temp;
  271. }
  272. // equality not implemented, so fall back to pointer comparison
  273. return (o1 == o2) ? local_true : local_false;
  274. }
  275. bool mp_obj_equal(mp_obj_t o1, mp_obj_t o2) {
  276. return mp_obj_is_true(mp_obj_equal_not_equal(MP_BINARY_OP_EQUAL, o1, o2));
  277. }
  278. mp_int_t mp_obj_get_int(mp_const_obj_t arg) {
  279. // This function essentially performs implicit type conversion to int
  280. // Note that Python does NOT provide implicit type conversion from
  281. // float to int in the core expression language, try some_list[1.0].
  282. mp_int_t val;
  283. if (!mp_obj_get_int_maybe(arg, &val)) {
  284. mp_raise_TypeError_int_conversion(arg);
  285. }
  286. return val;
  287. }
  288. mp_int_t mp_obj_get_int_truncated(mp_const_obj_t arg) {
  289. if (mp_obj_is_int(arg)) {
  290. return mp_obj_int_get_truncated(arg);
  291. } else {
  292. return mp_obj_get_int(arg);
  293. }
  294. }
  295. // returns false if arg is not of integral type
  296. // returns true and sets *value if it is of integral type
  297. // can throw OverflowError if arg is of integral type, but doesn't fit in a mp_int_t
  298. bool mp_obj_get_int_maybe(mp_const_obj_t arg, mp_int_t *value) {
  299. if (arg == mp_const_false) {
  300. *value = 0;
  301. } else if (arg == mp_const_true) {
  302. *value = 1;
  303. } else if (mp_obj_is_small_int(arg)) {
  304. *value = MP_OBJ_SMALL_INT_VALUE(arg);
  305. } else if (mp_obj_is_exact_type(arg, &mp_type_int)) {
  306. *value = mp_obj_int_get_checked(arg);
  307. } else {
  308. arg = mp_unary_op(MP_UNARY_OP_INT_MAYBE, (mp_obj_t)arg);
  309. if (arg != MP_OBJ_NULL) {
  310. *value = mp_obj_int_get_checked(arg);
  311. } else {
  312. return false;
  313. }
  314. }
  315. return true;
  316. }
  317. #if MICROPY_PY_BUILTINS_FLOAT
  318. bool mp_obj_get_float_maybe(mp_obj_t arg, mp_float_t *value) {
  319. mp_float_t val;
  320. if (arg == mp_const_false) {
  321. val = 0;
  322. } else if (arg == mp_const_true) {
  323. val = 1;
  324. } else if (mp_obj_is_small_int(arg)) {
  325. val = (mp_float_t)MP_OBJ_SMALL_INT_VALUE(arg);
  326. #if MICROPY_LONGINT_IMPL != MICROPY_LONGINT_IMPL_NONE
  327. } else if (mp_obj_is_exact_type(arg, &mp_type_int)) {
  328. val = mp_obj_int_as_float_impl(arg);
  329. #endif
  330. } else if (mp_obj_is_float(arg)) {
  331. val = mp_obj_float_get(arg);
  332. } else {
  333. arg = mp_unary_op(MP_UNARY_OP_FLOAT_MAYBE, (mp_obj_t)arg);
  334. if (arg != MP_OBJ_NULL && mp_obj_is_float(arg)) {
  335. val = mp_obj_float_get(arg);
  336. } else {
  337. return false;
  338. }
  339. }
  340. *value = val;
  341. return true;
  342. }
  343. mp_float_t mp_obj_get_float(mp_obj_t arg) {
  344. mp_float_t val;
  345. if (!mp_obj_get_float_maybe(arg, &val)) {
  346. #if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
  347. mp_raise_TypeError(MP_ERROR_TEXT("can't convert to float"));
  348. #else
  349. mp_raise_msg_varg(&mp_type_TypeError,
  350. MP_ERROR_TEXT("can't convert %s to float"), mp_obj_get_type_str(arg));
  351. #endif
  352. }
  353. return val;
  354. }
  355. #if MICROPY_PY_BUILTINS_COMPLEX
  356. bool mp_obj_get_complex_maybe(mp_obj_t arg, mp_float_t *real, mp_float_t *imag) {
  357. if (mp_obj_get_float_maybe(arg, real)) {
  358. *imag = 0;
  359. } else if (mp_obj_is_type(arg, &mp_type_complex)) {
  360. mp_obj_complex_get(arg, real, imag);
  361. } else {
  362. arg = mp_unary_op(MP_UNARY_OP_COMPLEX_MAYBE, (mp_obj_t)arg);
  363. if (arg != MP_OBJ_NULL && mp_obj_is_type(arg, &mp_type_complex)) {
  364. mp_obj_complex_get(arg, real, imag);
  365. } else {
  366. return false;
  367. }
  368. }
  369. return true;
  370. }
  371. void mp_obj_get_complex(mp_obj_t arg, mp_float_t *real, mp_float_t *imag) {
  372. if (!mp_obj_get_complex_maybe(arg, real, imag)) {
  373. #if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
  374. mp_raise_TypeError(MP_ERROR_TEXT("can't convert to complex"));
  375. #else
  376. mp_raise_msg_varg(&mp_type_TypeError,
  377. MP_ERROR_TEXT("can't convert %s to complex"), mp_obj_get_type_str(arg));
  378. #endif
  379. }
  380. }
  381. #endif
  382. #endif
  383. // note: returned value in *items may point to the interior of a GC block
  384. void mp_obj_get_array(mp_obj_t o, size_t *len, mp_obj_t **items) {
  385. if (mp_obj_is_type(o, &mp_type_tuple)) {
  386. mp_obj_tuple_get(o, len, items);
  387. } else if (mp_obj_is_type(o, &mp_type_list)) {
  388. mp_obj_list_get(o, len, items);
  389. } else {
  390. #if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
  391. mp_raise_TypeError(MP_ERROR_TEXT("expected tuple/list"));
  392. #else
  393. mp_raise_msg_varg(&mp_type_TypeError,
  394. MP_ERROR_TEXT("object '%s' isn't a tuple or list"), mp_obj_get_type_str(o));
  395. #endif
  396. }
  397. }
  398. // note: returned value in *items may point to the interior of a GC block
  399. void mp_obj_get_array_fixed_n(mp_obj_t o, size_t len, mp_obj_t **items) {
  400. size_t seq_len;
  401. mp_obj_get_array(o, &seq_len, items);
  402. if (seq_len != len) {
  403. #if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
  404. mp_raise_ValueError(MP_ERROR_TEXT("tuple/list has wrong length"));
  405. #else
  406. mp_raise_msg_varg(&mp_type_ValueError,
  407. MP_ERROR_TEXT("requested length %d but object has length %d"), (int)len, (int)seq_len);
  408. #endif
  409. }
  410. }
  411. // is_slice determines whether the index is a slice index
  412. size_t mp_get_index(const mp_obj_type_t *type, size_t len, mp_obj_t index, bool is_slice) {
  413. mp_int_t i;
  414. if (mp_obj_is_small_int(index)) {
  415. i = MP_OBJ_SMALL_INT_VALUE(index);
  416. } else if (!mp_obj_get_int_maybe(index, &i)) {
  417. #if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
  418. mp_raise_TypeError(MP_ERROR_TEXT("indices must be integers"));
  419. #else
  420. mp_raise_msg_varg(&mp_type_TypeError,
  421. MP_ERROR_TEXT("%q indices must be integers, not %s"),
  422. type->name, mp_obj_get_type_str(index));
  423. #endif
  424. }
  425. if (i < 0) {
  426. i += len;
  427. }
  428. if (is_slice) {
  429. if (i < 0) {
  430. i = 0;
  431. } else if ((mp_uint_t)i > len) {
  432. i = len;
  433. }
  434. } else {
  435. if (i < 0 || (mp_uint_t)i >= len) {
  436. #if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
  437. mp_raise_msg(&mp_type_IndexError, MP_ERROR_TEXT("index out of range"));
  438. #else
  439. mp_raise_msg_varg(&mp_type_IndexError, MP_ERROR_TEXT("%q index out of range"), type->name);
  440. #endif
  441. }
  442. }
  443. // By this point 0 <= i <= len and so fits in a size_t
  444. return (size_t)i;
  445. }
  446. mp_obj_t mp_obj_id(mp_obj_t o_in) {
  447. mp_int_t id = (mp_int_t)o_in;
  448. if (!mp_obj_is_obj(o_in)) {
  449. return mp_obj_new_int(id);
  450. } else if (id >= 0) {
  451. // Many OSes and CPUs have affinity for putting "user" memories
  452. // into low half of address space, and "system" into upper half.
  453. // We're going to take advantage of that and return small int
  454. // (signed) for such "user" addresses.
  455. return MP_OBJ_NEW_SMALL_INT(id);
  456. } else {
  457. // If that didn't work, well, let's return long int, just as
  458. // a (big) positive value, so it will never clash with the range
  459. // of small int returned in previous case.
  460. return mp_obj_new_int_from_uint((mp_uint_t)id);
  461. }
  462. }
  463. // will raise a TypeError if object has no length
  464. mp_obj_t mp_obj_len(mp_obj_t o_in) {
  465. mp_obj_t len = mp_obj_len_maybe(o_in);
  466. if (len == MP_OBJ_NULL) {
  467. #if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
  468. mp_raise_TypeError(MP_ERROR_TEXT("object has no len"));
  469. #else
  470. mp_raise_msg_varg(&mp_type_TypeError,
  471. MP_ERROR_TEXT("object of type '%s' has no len()"), mp_obj_get_type_str(o_in));
  472. #endif
  473. } else {
  474. return len;
  475. }
  476. }
  477. // may return MP_OBJ_NULL
  478. mp_obj_t mp_obj_len_maybe(mp_obj_t o_in) {
  479. if (
  480. #if !MICROPY_PY_BUILTINS_STR_UNICODE
  481. // It's simple - unicode is slow, non-unicode is fast
  482. mp_obj_is_str(o_in) ||
  483. #endif
  484. mp_obj_is_type(o_in, &mp_type_bytes)) {
  485. GET_STR_LEN(o_in, l);
  486. return MP_OBJ_NEW_SMALL_INT(l);
  487. } else {
  488. const mp_obj_type_t *type = mp_obj_get_type(o_in);
  489. if (MP_OBJ_TYPE_HAS_SLOT(type, unary_op)) {
  490. return MP_OBJ_TYPE_GET_SLOT(type, unary_op)(MP_UNARY_OP_LEN, o_in);
  491. } else {
  492. return MP_OBJ_NULL;
  493. }
  494. }
  495. }
  496. mp_obj_t mp_obj_subscr(mp_obj_t base, mp_obj_t index, mp_obj_t value) {
  497. const mp_obj_type_t *type = mp_obj_get_type(base);
  498. if (MP_OBJ_TYPE_HAS_SLOT(type, subscr)) {
  499. mp_obj_t ret = MP_OBJ_TYPE_GET_SLOT(type, subscr)(base, index, value);
  500. if (ret != MP_OBJ_NULL) {
  501. return ret;
  502. }
  503. // TODO: call base classes here?
  504. }
  505. if (value == MP_OBJ_NULL) {
  506. #if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
  507. mp_raise_TypeError(MP_ERROR_TEXT("object doesn't support item deletion"));
  508. #else
  509. mp_raise_msg_varg(&mp_type_TypeError,
  510. MP_ERROR_TEXT("'%s' object doesn't support item deletion"), mp_obj_get_type_str(base));
  511. #endif
  512. } else if (value == MP_OBJ_SENTINEL) {
  513. #if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
  514. mp_raise_TypeError(MP_ERROR_TEXT("object isn't subscriptable"));
  515. #else
  516. mp_raise_msg_varg(&mp_type_TypeError,
  517. MP_ERROR_TEXT("'%s' object isn't subscriptable"), mp_obj_get_type_str(base));
  518. #endif
  519. } else {
  520. #if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
  521. mp_raise_TypeError(MP_ERROR_TEXT("object doesn't support item assignment"));
  522. #else
  523. mp_raise_msg_varg(&mp_type_TypeError,
  524. MP_ERROR_TEXT("'%s' object doesn't support item assignment"), mp_obj_get_type_str(base));
  525. #endif
  526. }
  527. }
  528. // Return input argument. Useful as .getiter for objects which are
  529. // their own iterators, etc.
  530. mp_obj_t mp_identity(mp_obj_t self) {
  531. return self;
  532. }
  533. MP_DEFINE_CONST_FUN_OBJ_1(mp_identity_obj, mp_identity);
  534. // mp_obj_t mp_identity_getiter(mp_obj_t self, mp_obj_iter_buf_t *iter_buf) {
  535. // (void)iter_buf;
  536. // return self;
  537. // }
  538. bool mp_get_buffer(mp_obj_t obj, mp_buffer_info_t *bufinfo, mp_uint_t flags) {
  539. const mp_obj_type_t *type = mp_obj_get_type(obj);
  540. if (MP_OBJ_TYPE_HAS_SLOT(type, buffer)
  541. && MP_OBJ_TYPE_GET_SLOT(type, buffer)(obj, bufinfo, flags & MP_BUFFER_RW) == 0) {
  542. return true;
  543. }
  544. if (flags & MP_BUFFER_RAISE_IF_UNSUPPORTED) {
  545. mp_raise_TypeError(MP_ERROR_TEXT("object with buffer protocol required"));
  546. }
  547. return false;
  548. }