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-2017 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 
28 #include <string.h>
29 #include <assert.h>
30 
31 #include "py/objtuple.h"
32 #include "py/runtime.h"
33 
34 // type check is done on getiter method to allow tuple, namedtuple, attrtuple
35 #define mp_obj_is_tuple_compatible(o) (mp_obj_get_type(o)->getiter == mp_obj_tuple_getiter)
36 
37 /******************************************************************************/
38 /* tuple                                                                      */
39 
mp_obj_tuple_print(const mp_print_t * print,mp_obj_t o_in,mp_print_kind_t kind)40 void mp_obj_tuple_print(const mp_print_t *print, mp_obj_t o_in, mp_print_kind_t kind) {
41     mp_obj_tuple_t *o = MP_OBJ_TO_PTR(o_in);
42     const char *item_separator = ", ";
43     if (MICROPY_PY_UJSON && kind == PRINT_JSON) {
44         mp_print_str(print, "[");
45         #if MICROPY_PY_UJSON_SEPARATORS
46         item_separator = MP_PRINT_GET_EXT(print)->item_separator;
47         #endif
48     } else {
49         mp_print_str(print, "(");
50         kind = PRINT_REPR;
51     }
52     for (size_t i = 0; i < o->len; i++) {
53         if (i > 0) {
54             mp_print_str(print, item_separator);
55         }
56         mp_obj_print_helper(print, o->items[i], kind);
57     }
58     if (MICROPY_PY_UJSON && kind == PRINT_JSON) {
59         mp_print_str(print, "]");
60     } else {
61         if (o->len == 1) {
62             mp_print_str(print, ",");
63         }
64         mp_print_str(print, ")");
65     }
66 }
67 
mp_obj_tuple_make_new(const mp_obj_type_t * type_in,size_t n_args,size_t n_kw,const mp_obj_t * args)68 STATIC mp_obj_t mp_obj_tuple_make_new(const mp_obj_type_t *type_in, size_t n_args, size_t n_kw, const mp_obj_t *args) {
69     (void)type_in;
70 
71     mp_arg_check_num(n_args, n_kw, 0, 1, false);
72 
73     switch (n_args) {
74         case 0:
75             // return a empty tuple
76             return mp_const_empty_tuple;
77 
78         case 1:
79         default: {
80             // 1 argument, an iterable from which we make a new tuple
81             if (mp_obj_is_type(args[0], &mp_type_tuple)) {
82                 return args[0];
83             }
84 
85             // TODO optimise for cases where we know the length of the iterator
86 
87             size_t alloc = 4;
88             size_t len = 0;
89             mp_obj_t *items = m_new(mp_obj_t, alloc);
90 
91             mp_obj_t iterable = mp_getiter(args[0], NULL);
92             mp_obj_t item;
93             while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
94                 if (len >= alloc) {
95                     items = m_renew(mp_obj_t, items, alloc, alloc * 2);
96                     alloc *= 2;
97                 }
98                 items[len++] = item;
99             }
100 
101             mp_obj_t tuple = mp_obj_new_tuple(len, items);
102             m_del(mp_obj_t, items, alloc);
103 
104             return tuple;
105         }
106     }
107 }
108 
109 // Don't pass MP_BINARY_OP_NOT_EQUAL here
tuple_cmp_helper(mp_uint_t op,mp_obj_t self_in,mp_obj_t another_in)110 STATIC mp_obj_t tuple_cmp_helper(mp_uint_t op, mp_obj_t self_in, mp_obj_t another_in) {
111     mp_check_self(mp_obj_is_tuple_compatible(self_in));
112     const mp_obj_type_t *another_type = mp_obj_get_type(another_in);
113     mp_obj_tuple_t *self = MP_OBJ_TO_PTR(self_in);
114     if (another_type->getiter != mp_obj_tuple_getiter) {
115         // Slow path for user subclasses
116         another_in = mp_obj_cast_to_native_base(another_in, MP_OBJ_FROM_PTR(&mp_type_tuple));
117         if (another_in == MP_OBJ_NULL) {
118             return MP_OBJ_NULL;
119         }
120     }
121     mp_obj_tuple_t *another = MP_OBJ_TO_PTR(another_in);
122 
123     return mp_obj_new_bool(mp_seq_cmp_objs(op, self->items, self->len, another->items, another->len));
124 }
125 
mp_obj_tuple_unary_op(mp_unary_op_t op,mp_obj_t self_in)126 mp_obj_t mp_obj_tuple_unary_op(mp_unary_op_t op, mp_obj_t self_in) {
127     mp_obj_tuple_t *self = MP_OBJ_TO_PTR(self_in);
128     switch (op) {
129         case MP_UNARY_OP_BOOL:
130             return mp_obj_new_bool(self->len != 0);
131         case MP_UNARY_OP_HASH: {
132             // start hash with pointer to empty tuple, to make it fairly unique
133             mp_int_t hash = (mp_int_t)mp_const_empty_tuple;
134             for (size_t i = 0; i < self->len; i++) {
135                 hash += MP_OBJ_SMALL_INT_VALUE(mp_unary_op(MP_UNARY_OP_HASH, self->items[i]));
136             }
137             return MP_OBJ_NEW_SMALL_INT(hash);
138         }
139         case MP_UNARY_OP_LEN:
140             return MP_OBJ_NEW_SMALL_INT(self->len);
141         default:
142             return MP_OBJ_NULL;      // op not supported
143     }
144 }
145 
mp_obj_tuple_binary_op(mp_binary_op_t op,mp_obj_t lhs,mp_obj_t rhs)146 mp_obj_t mp_obj_tuple_binary_op(mp_binary_op_t op, mp_obj_t lhs, mp_obj_t rhs) {
147     mp_obj_tuple_t *o = MP_OBJ_TO_PTR(lhs);
148     switch (op) {
149         case MP_BINARY_OP_ADD:
150         case MP_BINARY_OP_INPLACE_ADD: {
151             if (!mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(mp_obj_get_type(rhs)), MP_OBJ_FROM_PTR(&mp_type_tuple))) {
152                 return MP_OBJ_NULL; // op not supported
153             }
154             mp_obj_tuple_t *p = MP_OBJ_TO_PTR(rhs);
155             mp_obj_tuple_t *s = MP_OBJ_TO_PTR(mp_obj_new_tuple(o->len + p->len, NULL));
156             mp_seq_cat(s->items, o->items, o->len, p->items, p->len, mp_obj_t);
157             return MP_OBJ_FROM_PTR(s);
158         }
159         case MP_BINARY_OP_MULTIPLY:
160         case MP_BINARY_OP_INPLACE_MULTIPLY: {
161             mp_int_t n;
162             if (!mp_obj_get_int_maybe(rhs, &n)) {
163                 return MP_OBJ_NULL; // op not supported
164             }
165             if (n <= 0) {
166                 return mp_const_empty_tuple;
167             }
168             mp_obj_tuple_t *s = MP_OBJ_TO_PTR(mp_obj_new_tuple(o->len * n, NULL));
169             mp_seq_multiply(o->items, sizeof(*o->items), o->len, n, s->items);
170             return MP_OBJ_FROM_PTR(s);
171         }
172         case MP_BINARY_OP_EQUAL:
173         case MP_BINARY_OP_LESS:
174         case MP_BINARY_OP_LESS_EQUAL:
175         case MP_BINARY_OP_MORE:
176         case MP_BINARY_OP_MORE_EQUAL:
177             return tuple_cmp_helper(op, lhs, rhs);
178 
179         default:
180             return MP_OBJ_NULL; // op not supported
181     }
182 }
183 
mp_obj_tuple_subscr(mp_obj_t self_in,mp_obj_t index,mp_obj_t value)184 mp_obj_t mp_obj_tuple_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) {
185     if (value == MP_OBJ_SENTINEL) {
186         // load
187         mp_obj_tuple_t *self = MP_OBJ_TO_PTR(self_in);
188         #if MICROPY_PY_BUILTINS_SLICE
189         if (mp_obj_is_type(index, &mp_type_slice)) {
190             mp_bound_slice_t slice;
191             if (!mp_seq_get_fast_slice_indexes(self->len, index, &slice)) {
192                 mp_raise_NotImplementedError(MP_ERROR_TEXT("only slices with step=1 (aka None) are supported"));
193             }
194             mp_obj_tuple_t *res = MP_OBJ_TO_PTR(mp_obj_new_tuple(slice.stop - slice.start, NULL));
195             mp_seq_copy(res->items, self->items + slice.start, res->len, mp_obj_t);
196             return MP_OBJ_FROM_PTR(res);
197         }
198         #endif
199         size_t index_value = mp_get_index(self->base.type, self->len, index, false);
200         return self->items[index_value];
201     } else {
202         return MP_OBJ_NULL; // op not supported
203     }
204 }
205 
tuple_count(mp_obj_t self_in,mp_obj_t value)206 STATIC mp_obj_t tuple_count(mp_obj_t self_in, mp_obj_t value) {
207     mp_check_self(mp_obj_is_type(self_in, &mp_type_tuple));
208     mp_obj_tuple_t *self = MP_OBJ_TO_PTR(self_in);
209     return mp_seq_count_obj(self->items, self->len, value);
210 }
211 STATIC MP_DEFINE_CONST_FUN_OBJ_2(tuple_count_obj, tuple_count);
212 
tuple_index(size_t n_args,const mp_obj_t * args)213 STATIC mp_obj_t tuple_index(size_t n_args, const mp_obj_t *args) {
214     mp_check_self(mp_obj_is_type(args[0], &mp_type_tuple));
215     mp_obj_tuple_t *self = MP_OBJ_TO_PTR(args[0]);
216     return mp_seq_index_obj(self->items, self->len, n_args, args);
217 }
218 STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(tuple_index_obj, 2, 4, tuple_index);
219 
220 STATIC const mp_rom_map_elem_t tuple_locals_dict_table[] = {
221     { MP_ROM_QSTR(MP_QSTR_count), MP_ROM_PTR(&tuple_count_obj) },
222     { MP_ROM_QSTR(MP_QSTR_index), MP_ROM_PTR(&tuple_index_obj) },
223 };
224 
225 STATIC MP_DEFINE_CONST_DICT(tuple_locals_dict, tuple_locals_dict_table);
226 
227 const mp_obj_type_t mp_type_tuple = {
228     { &mp_type_type },
229     .name = MP_QSTR_tuple,
230     .print = mp_obj_tuple_print,
231     .make_new = mp_obj_tuple_make_new,
232     .unary_op = mp_obj_tuple_unary_op,
233     .binary_op = mp_obj_tuple_binary_op,
234     .subscr = mp_obj_tuple_subscr,
235     .getiter = mp_obj_tuple_getiter,
236     .locals_dict = (mp_obj_dict_t *)&tuple_locals_dict,
237 };
238 
239 // the zero-length tuple
240 const mp_obj_tuple_t mp_const_empty_tuple_obj = {{&mp_type_tuple}, 0};
241 
mp_obj_new_tuple(size_t n,const mp_obj_t * items)242 mp_obj_t mp_obj_new_tuple(size_t n, const mp_obj_t *items) {
243     if (n == 0) {
244         return mp_const_empty_tuple;
245     }
246     mp_obj_tuple_t *o = m_new_obj_var(mp_obj_tuple_t, mp_obj_t, n);
247     o->base.type = &mp_type_tuple;
248     o->len = n;
249     if (items) {
250         for (size_t i = 0; i < n; i++) {
251             o->items[i] = items[i];
252         }
253     }
254     return MP_OBJ_FROM_PTR(o);
255 }
256 
mp_obj_tuple_get(mp_obj_t self_in,size_t * len,mp_obj_t ** items)257 void mp_obj_tuple_get(mp_obj_t self_in, size_t *len, mp_obj_t **items) {
258     assert(mp_obj_is_tuple_compatible(self_in));
259     mp_obj_tuple_t *self = MP_OBJ_TO_PTR(self_in);
260     *len = self->len;
261     *items = &self->items[0];
262 }
263 
mp_obj_tuple_del(mp_obj_t self_in)264 void mp_obj_tuple_del(mp_obj_t self_in) {
265     assert(mp_obj_is_type(self_in, &mp_type_tuple));
266     mp_obj_tuple_t *self = MP_OBJ_TO_PTR(self_in);
267     m_del_var(mp_obj_tuple_t, mp_obj_t, self->len, self);
268 }
269 
270 /******************************************************************************/
271 /* tuple iterator                                                             */
272 
273 typedef struct _mp_obj_tuple_it_t {
274     mp_obj_base_t base;
275     mp_fun_1_t iternext;
276     mp_obj_tuple_t *tuple;
277     size_t cur;
278 } mp_obj_tuple_it_t;
279 
tuple_it_iternext(mp_obj_t self_in)280 STATIC mp_obj_t tuple_it_iternext(mp_obj_t self_in) {
281     mp_obj_tuple_it_t *self = MP_OBJ_TO_PTR(self_in);
282     if (self->cur < self->tuple->len) {
283         mp_obj_t o_out = self->tuple->items[self->cur];
284         self->cur += 1;
285         return o_out;
286     } else {
287         return MP_OBJ_STOP_ITERATION;
288     }
289 }
290 
mp_obj_tuple_getiter(mp_obj_t o_in,mp_obj_iter_buf_t * iter_buf)291 mp_obj_t mp_obj_tuple_getiter(mp_obj_t o_in, mp_obj_iter_buf_t *iter_buf) {
292     assert(sizeof(mp_obj_tuple_it_t) <= sizeof(mp_obj_iter_buf_t));
293     mp_obj_tuple_it_t *o = (mp_obj_tuple_it_t *)iter_buf;
294     o->base.type = &mp_type_polymorph_iter;
295     o->iternext = tuple_it_iternext;
296     o->tuple = MP_OBJ_TO_PTR(o_in);
297     o->cur = 0;
298     return MP_OBJ_FROM_PTR(o);
299 }
300