obj.c 20 KB

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