blob: c5acca32556f205e491ee36ddd8c79a46353c7d6 [file] [log] [blame]
Damien George04b91472014-05-03 23:27:38 +01001/*
2 * This file is part of the Micro Python project, http://micropython.org/
3 *
4 * The MIT License (MIT)
5 *
6 * Copyright (c) 2013, 2014 Damien P. George
Paul Sokolovskyda9f0922014-05-13 08:44:45 +03007 * Copyright (c) 2014 Paul Sokolovsky
Damien George04b91472014-05-03 23:27:38 +01008 *
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
xbeefe34222014-03-16 00:14:26 -070028#include <stdbool.h>
Damiend99b0522013-12-21 18:17:45 +000029#include <string.h>
30#include <assert.h>
31
Paul Sokolovskyf54bcbf2014-05-02 17:47:01 +030032#include "mpconfig.h"
Damiend99b0522013-12-21 18:17:45 +000033#include "nlr.h"
34#include "misc.h"
Damien George55baff42014-01-21 21:40:13 +000035#include "qstr.h"
Damiend99b0522013-12-21 18:17:45 +000036#include "obj.h"
37#include "runtime0.h"
38#include "runtime.h"
Dave Hylandsbaf6f142014-03-30 21:06:50 -070039#include "pfenv.h"
Paul Sokolovsky58676fc2014-04-14 01:45:06 +030040#include "objstr.h"
Paul Sokolovsky2a273652014-05-13 08:07:08 +030041#include "objlist.h"
Damiend99b0522013-12-21 18:17:45 +000042
Paul Sokolovsky75ce9252014-06-05 20:02:15 +030043STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, uint n_args, const mp_obj_t *args, mp_obj_t dict);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +020044const mp_obj_t mp_const_empty_bytes;
45
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +020046STATIC mp_obj_t mp_obj_new_str_iterator(mp_obj_t str);
47STATIC mp_obj_t mp_obj_new_bytes_iterator(mp_obj_t str);
Paul Sokolovskye9085912014-04-30 05:35:18 +030048STATIC NORETURN void bad_implicit_conversion(mp_obj_t self_in);
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +030049STATIC NORETURN void arg_type_mixup();
50
51STATIC bool is_str_or_bytes(mp_obj_t o) {
52 return MP_OBJ_IS_STR(o) || MP_OBJ_IS_TYPE(o, &mp_type_bytes);
53}
xyb8cfc9f02014-01-05 18:47:51 +080054
55/******************************************************************************/
56/* str */
57
Paul Sokolovsky2ec38a12014-06-13 21:23:00 +030058void mp_str_print_quoted(void (*print)(void *env, const char *fmt, ...), void *env,
59 const byte *str_data, uint str_len, bool is_bytes) {
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020060 // this escapes characters, but it will be very slow to print (calling print many times)
61 bool has_single_quote = false;
62 bool has_double_quote = false;
Chris Angelico48674132014-06-04 03:26:40 +100063 for (const byte *s = str_data, *top = str_data + str_len; !has_double_quote && s < top; s++) {
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020064 if (*s == '\'') {
65 has_single_quote = true;
66 } else if (*s == '"') {
67 has_double_quote = true;
68 }
69 }
70 int quote_char = '\'';
71 if (has_single_quote && !has_double_quote) {
72 quote_char = '"';
73 }
74 print(env, "%c", quote_char);
75 for (const byte *s = str_data, *top = str_data + str_len; s < top; s++) {
76 if (*s == quote_char) {
77 print(env, "\\%c", quote_char);
78 } else if (*s == '\\') {
79 print(env, "\\\\");
Paul Sokolovsky2ec38a12014-06-13 21:23:00 +030080 } else if (*s >= 0x20 && *s != 0x7f && (!is_bytes || *s < 0x80)) {
81 // In strings, anything which is not ascii control character
82 // is printed as is, this includes characters in range 0x80-0xff
83 // (which can be non-Latin letters, etc.)
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020084 print(env, "%c", *s);
85 } else if (*s == '\n') {
86 print(env, "\\n");
Andrew Scheller12968fb2014-04-08 02:42:50 +010087 } else if (*s == '\r') {
88 print(env, "\\r");
89 } else if (*s == '\t') {
90 print(env, "\\t");
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020091 } else {
92 print(env, "\\x%02x", *s);
93 }
94 }
95 print(env, "%c", quote_char);
96}
97
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +020098STATIC void str_print(void (*print)(void *env, const char *fmt, ...), void *env, mp_obj_t self_in, mp_print_kind_t kind) {
Damien George5fa93b62014-01-22 14:35:10 +000099 GET_STR_DATA_LEN(self_in, str_data, str_len);
Damien George3e1a5c12014-03-29 13:43:38 +0000100 bool is_bytes = MP_OBJ_IS_TYPE(self_in, &mp_type_bytes);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +0200101 if (kind == PRINT_STR && !is_bytes) {
Damien George5fa93b62014-01-22 14:35:10 +0000102 print(env, "%.*s", str_len, str_data);
Paul Sokolovsky76d982e2014-01-13 19:19:16 +0200103 } else {
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +0200104 if (is_bytes) {
105 print(env, "b");
106 }
Paul Sokolovsky2ec38a12014-06-13 21:23:00 +0300107 mp_str_print_quoted(print, env, str_data, str_len, is_bytes);
Paul Sokolovsky76d982e2014-01-13 19:19:16 +0200108 }
Damiend99b0522013-12-21 18:17:45 +0000109}
110
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200111STATIC mp_obj_t str_make_new(mp_obj_t type_in, uint n_args, uint n_kw, const mp_obj_t *args) {
Paul Sokolovskyb473d0a2014-05-06 19:30:30 +0300112#if MICROPY_CPYTHON_COMPAT
113 if (n_kw != 0) {
114 mp_arg_error_unimpl_kw();
115 }
116#endif
117
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200118 switch (n_args) {
119 case 0:
120 return MP_OBJ_NEW_QSTR(MP_QSTR_);
121
122 case 1:
123 {
124 vstr_t *vstr = vstr_new();
125 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, vstr, args[0], PRINT_STR);
Damien George2617eeb2014-05-25 22:27:57 +0100126 mp_obj_t s = mp_obj_new_str(vstr->buf, vstr->len, false);
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200127 vstr_free(vstr);
128 return s;
129 }
130
131 case 2:
132 case 3:
133 {
134 // TODO: validate 2nd/3rd args
Damien George3e1a5c12014-03-29 13:43:38 +0000135 if (!MP_OBJ_IS_TYPE(args[0], &mp_type_bytes)) {
Damien Georgeea13f402014-04-05 18:32:08 +0100136 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "bytes expected"));
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200137 }
138 GET_STR_DATA_LEN(args[0], str_data, str_len);
139 GET_STR_HASH(args[0], str_hash);
Damien Georgef600a6a2014-05-25 22:34:34 +0100140 mp_obj_str_t *o = mp_obj_new_str_of_type(&mp_type_str, NULL, str_len);
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200141 o->data = str_data;
142 o->hash = str_hash;
143 return o;
144 }
145
146 default:
Damien Georgeea13f402014-04-05 18:32:08 +0100147 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "str takes at most 3 arguments"));
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200148 }
149}
150
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200151STATIC mp_obj_t bytes_make_new(mp_obj_t type_in, uint n_args, uint n_kw, const mp_obj_t *args) {
152 if (n_args == 0) {
153 return mp_const_empty_bytes;
154 }
155
Paul Sokolovskyb473d0a2014-05-06 19:30:30 +0300156#if MICROPY_CPYTHON_COMPAT
157 if (n_kw != 0) {
158 mp_arg_error_unimpl_kw();
159 }
160#endif
161
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200162 if (MP_OBJ_IS_STR(args[0])) {
163 if (n_args < 2 || n_args > 3) {
164 goto wrong_args;
165 }
166 GET_STR_DATA_LEN(args[0], str_data, str_len);
167 GET_STR_HASH(args[0], str_hash);
Damien Georgef600a6a2014-05-25 22:34:34 +0100168 mp_obj_str_t *o = mp_obj_new_str_of_type(&mp_type_bytes, NULL, str_len);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200169 o->data = str_data;
170 o->hash = str_hash;
171 return o;
172 }
173
174 if (n_args > 1) {
175 goto wrong_args;
176 }
177
178 if (MP_OBJ_IS_SMALL_INT(args[0])) {
179 uint len = MP_OBJ_SMALL_INT_VALUE(args[0]);
180 byte *data;
181
Damien George3e1a5c12014-03-29 13:43:38 +0000182 mp_obj_t o = mp_obj_str_builder_start(&mp_type_bytes, len, &data);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200183 memset(data, 0, len);
184 return mp_obj_str_builder_end(o);
185 }
186
187 int len;
188 byte *data;
189 vstr_t *vstr = NULL;
190 mp_obj_t o = NULL;
191 // Try to create array of exact len if initializer len is known
192 mp_obj_t len_in = mp_obj_len_maybe(args[0]);
193 if (len_in == MP_OBJ_NULL) {
194 len = -1;
195 vstr = vstr_new();
196 } else {
197 len = MP_OBJ_SMALL_INT_VALUE(len_in);
Damien George3e1a5c12014-03-29 13:43:38 +0000198 o = mp_obj_str_builder_start(&mp_type_bytes, len, &data);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200199 }
200
Damien Georged17926d2014-03-30 13:35:08 +0100201 mp_obj_t iterable = mp_getiter(args[0]);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200202 mp_obj_t item;
Damien Georgeea8d06c2014-04-17 23:19:36 +0100203 while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200204 if (len == -1) {
205 vstr_add_char(vstr, MP_OBJ_SMALL_INT_VALUE(item));
206 } else {
207 *data++ = MP_OBJ_SMALL_INT_VALUE(item);
208 }
209 }
210
211 if (len == -1) {
212 vstr_shrink(vstr);
213 // TODO: Optimize, borrow buffer from vstr
214 len = vstr_len(vstr);
Damien George3e1a5c12014-03-29 13:43:38 +0000215 o = mp_obj_str_builder_start(&mp_type_bytes, len, &data);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200216 memcpy(data, vstr_str(vstr), len);
217 vstr_free(vstr);
218 }
219
220 return mp_obj_str_builder_end(o);
221
222wrong_args:
Damien Georgeea13f402014-04-05 18:32:08 +0100223 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "wrong number of arguments"));
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200224}
225
Damien George55baff42014-01-21 21:40:13 +0000226// like strstr but with specified length and allows \0 bytes
227// TODO replace with something more efficient/standard
xbe17a5a832014-03-23 23:31:58 -0700228STATIC const byte *find_subbytes(const byte *haystack, machine_uint_t hlen, const byte *needle, machine_uint_t nlen, machine_int_t direction) {
Damien George55baff42014-01-21 21:40:13 +0000229 if (hlen >= nlen) {
xbe17a5a832014-03-23 23:31:58 -0700230 machine_uint_t str_index, str_index_end;
231 if (direction > 0) {
232 str_index = 0;
233 str_index_end = hlen - nlen;
234 } else {
235 str_index = hlen - nlen;
236 str_index_end = 0;
237 }
238 for (;;) {
239 if (memcmp(&haystack[str_index], needle, nlen) == 0) {
240 //found
241 return haystack + str_index;
Damien George55baff42014-01-21 21:40:13 +0000242 }
xbe17a5a832014-03-23 23:31:58 -0700243 if (str_index == str_index_end) {
244 //not found
245 break;
Damien George55baff42014-01-21 21:40:13 +0000246 }
xbe17a5a832014-03-23 23:31:58 -0700247 str_index += direction;
Damien George55baff42014-01-21 21:40:13 +0000248 }
249 }
250 return NULL;
251}
252
Paul Sokolovsky97319122014-06-13 22:01:26 +0300253mp_obj_t str_binary_op(int op, mp_obj_t lhs_in, mp_obj_t rhs_in) {
Damien George5fa93b62014-01-22 14:35:10 +0000254 GET_STR_DATA_LEN(lhs_in, lhs_data, lhs_len);
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300255 mp_obj_type_t *lhs_type = mp_obj_get_type(lhs_in);
256 mp_obj_type_t *rhs_type = mp_obj_get_type(rhs_in);
Damiend99b0522013-12-21 18:17:45 +0000257 switch (op) {
Damien Georged17926d2014-03-30 13:35:08 +0100258 case MP_BINARY_OP_ADD:
259 case MP_BINARY_OP_INPLACE_ADD:
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300260 if (lhs_type == rhs_type) {
261 // add 2 strings or bytes
Damien George5fa93b62014-01-22 14:35:10 +0000262
263 GET_STR_DATA_LEN(rhs_in, rhs_data, rhs_len);
Damien George55baff42014-01-21 21:40:13 +0000264 int alloc_len = lhs_len + rhs_len;
Damien George5fa93b62014-01-22 14:35:10 +0000265
266 /* code for making qstr
Damien George55baff42014-01-21 21:40:13 +0000267 byte *q_ptr;
268 byte *val = qstr_build_start(alloc_len, &q_ptr);
269 memcpy(val, lhs_data, lhs_len);
270 memcpy(val + lhs_len, rhs_data, rhs_len);
Damien George5fa93b62014-01-22 14:35:10 +0000271 return MP_OBJ_NEW_QSTR(qstr_build_end(q_ptr));
272 */
273
274 // code for non-qstr
275 byte *data;
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300276 mp_obj_t s = mp_obj_str_builder_start(lhs_type, alloc_len, &data);
Damien George5fa93b62014-01-22 14:35:10 +0000277 memcpy(data, lhs_data, lhs_len);
278 memcpy(data + lhs_len, rhs_data, rhs_len);
279 return mp_obj_str_builder_end(s);
Damiend99b0522013-12-21 18:17:45 +0000280 }
281 break;
Damien George5fa93b62014-01-22 14:35:10 +0000282
Damien Georged17926d2014-03-30 13:35:08 +0100283 case MP_BINARY_OP_IN:
John R. Lentonc1bef212014-01-11 12:39:33 +0000284 /* NOTE `a in b` is `b.__contains__(a)` */
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300285 if (lhs_type == rhs_type) {
Damien George5fa93b62014-01-22 14:35:10 +0000286 GET_STR_DATA_LEN(rhs_in, rhs_data, rhs_len);
xbe17a5a832014-03-23 23:31:58 -0700287 return MP_BOOL(find_subbytes(lhs_data, lhs_len, rhs_data, rhs_len, 1) != NULL);
John R. Lentonc1bef212014-01-11 12:39:33 +0000288 }
289 break;
Damien George5fa93b62014-01-22 14:35:10 +0000290
Damien Georged0a5bf32014-05-10 13:55:11 +0100291 case MP_BINARY_OP_MULTIPLY: {
Paul Sokolovsky545591a2014-01-21 00:27:33 +0200292 if (!MP_OBJ_IS_SMALL_INT(rhs_in)) {
Damien George6ac5dce2014-05-21 19:42:43 +0100293 return MP_OBJ_NULL; // op not supported
Paul Sokolovsky545591a2014-01-21 00:27:33 +0200294 }
295 int n = MP_OBJ_SMALL_INT_VALUE(rhs_in);
Damien George5fa93b62014-01-22 14:35:10 +0000296 byte *data;
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300297 mp_obj_t s = mp_obj_str_builder_start(lhs_type, lhs_len * n, &data);
Damien George5fa93b62014-01-22 14:35:10 +0000298 mp_seq_multiply(lhs_data, sizeof(*lhs_data), lhs_len, n, data);
299 return mp_obj_str_builder_end(s);
Paul Sokolovsky545591a2014-01-21 00:27:33 +0200300 }
Paul Sokolovsky87e85b72014-02-02 08:24:07 +0200301
Paul Sokolovsky4db727a2014-03-31 21:18:28 +0300302 case MP_BINARY_OP_MODULO: {
303 mp_obj_t *args;
304 uint n_args;
Paul Sokolovsky75ce9252014-06-05 20:02:15 +0300305 mp_obj_t dict = MP_OBJ_NULL;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +0300306 if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_tuple)) {
307 // TODO: Support tuple subclasses?
308 mp_obj_tuple_get(rhs_in, &n_args, &args);
Paul Sokolovsky75ce9252014-06-05 20:02:15 +0300309 } else if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_dict)) {
310 args = NULL;
311 n_args = 0;
312 dict = rhs_in;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +0300313 } else {
314 args = &rhs_in;
315 n_args = 1;
316 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +0300317 return str_modulo_format(lhs_in, n_args, args, dict);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +0300318 }
319
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300320 //case MP_BINARY_OP_NOT_EQUAL: // This is never passed here
321 case MP_BINARY_OP_EQUAL: // This will be passed only for bytes, str is dealt with in mp_obj_equal()
Damien Georged17926d2014-03-30 13:35:08 +0100322 case MP_BINARY_OP_LESS:
323 case MP_BINARY_OP_LESS_EQUAL:
324 case MP_BINARY_OP_MORE:
325 case MP_BINARY_OP_MORE_EQUAL:
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300326 if (lhs_type == rhs_type) {
Paul Sokolovsky87e85b72014-02-02 08:24:07 +0200327 GET_STR_DATA_LEN(rhs_in, rhs_data, rhs_len);
328 return MP_BOOL(mp_seq_cmp_bytes(op, lhs_data, lhs_len, rhs_data, rhs_len));
329 }
Paul Sokolovsky70328e42014-05-15 20:58:40 +0300330 if (lhs_type == &mp_type_bytes) {
331 mp_buffer_info_t bufinfo;
332 if (!mp_get_buffer(rhs_in, &bufinfo, MP_BUFFER_READ)) {
333 goto uncomparable;
334 }
335 return MP_BOOL(mp_seq_cmp_bytes(op, lhs_data, lhs_len, bufinfo.buf, bufinfo.len));
336 }
337uncomparable:
338 if (op == MP_BINARY_OP_EQUAL) {
339 return mp_const_false;
340 }
Damiend99b0522013-12-21 18:17:45 +0000341 }
342
Damien George6ac5dce2014-05-21 19:42:43 +0100343 return MP_OBJ_NULL; // op not supported
Damiend99b0522013-12-21 18:17:45 +0000344}
345
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300346const byte *str_index_to_ptr(const mp_obj_type_t *type, const byte *self_data, uint self_len,
347 mp_obj_t index, bool is_slice) {
348 machine_uint_t index_val = mp_get_index(type, self_len, index, is_slice);
349 return self_data + index_val;
350}
351
Damien George729f7b42014-04-17 22:10:53 +0100352STATIC mp_obj_t str_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) {
Paul Sokolovsky5ebd5f02014-05-11 21:22:59 +0300353 mp_obj_type_t *type = mp_obj_get_type(self_in);
Damien George729f7b42014-04-17 22:10:53 +0100354 GET_STR_DATA_LEN(self_in, self_data, self_len);
355 if (value == MP_OBJ_SENTINEL) {
356 // load
Damien Georgefb510b32014-06-01 13:32:54 +0100357#if MICROPY_PY_BUILTINS_SLICE
Damien George729f7b42014-04-17 22:10:53 +0100358 if (MP_OBJ_IS_TYPE(index, &mp_type_slice)) {
Paul Sokolovskyde4b9322014-05-25 21:21:57 +0300359 mp_bound_slice_t slice;
360 if (!mp_seq_get_fast_slice_indexes(self_len, index, &slice)) {
Paul Sokolovsky5fd5af92014-05-25 22:12:56 +0300361 nlr_raise(mp_obj_new_exception_msg(&mp_type_NotImplementedError,
Damien George11de8392014-06-05 18:57:38 +0100362 "only slices with step=1 (aka None) are supported"));
Damien George729f7b42014-04-17 22:10:53 +0100363 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100364 return mp_obj_new_str_of_type(type, self_data + slice.start, slice.stop - slice.start);
Damien George729f7b42014-04-17 22:10:53 +0100365 }
366#endif
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300367 const byte *p = str_index_to_ptr(type, self_data, self_len, index, false);
Damien George729f7b42014-04-17 22:10:53 +0100368 if (type == &mp_type_bytes) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300369 return MP_OBJ_NEW_SMALL_INT((mp_small_int_t)*p);
Damien George729f7b42014-04-17 22:10:53 +0100370 } else {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300371 return mp_obj_new_str((char*)p, 1, true);
Damien George729f7b42014-04-17 22:10:53 +0100372 }
373 } else {
Damien George6ac5dce2014-05-21 19:42:43 +0100374 return MP_OBJ_NULL; // op not supported
Damien George729f7b42014-04-17 22:10:53 +0100375 }
376}
377
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200378STATIC mp_obj_t str_join(mp_obj_t self_in, mp_obj_t arg) {
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300379 assert(is_str_or_bytes(self_in));
380 const mp_obj_type_t *self_type = mp_obj_get_type(self_in);
Damiend99b0522013-12-21 18:17:45 +0000381
Damien Georgefe8fb912014-01-02 16:36:09 +0000382 // get separation string
Damien George5fa93b62014-01-22 14:35:10 +0000383 GET_STR_DATA_LEN(self_in, sep_str, sep_len);
Damien Georgefe8fb912014-01-02 16:36:09 +0000384
385 // process args
Damiend99b0522013-12-21 18:17:45 +0000386 uint seq_len;
387 mp_obj_t *seq_items;
Damien George07ddab52014-03-29 13:15:08 +0000388 if (MP_OBJ_IS_TYPE(arg, &mp_type_tuple)) {
Damiend99b0522013-12-21 18:17:45 +0000389 mp_obj_tuple_get(arg, &seq_len, &seq_items);
Damiend99b0522013-12-21 18:17:45 +0000390 } else {
Damien Georgea157e4c2014-04-09 19:17:53 +0100391 if (!MP_OBJ_IS_TYPE(arg, &mp_type_list)) {
392 // arg is not a list, try to convert it to one
Paul Sokolovsky881d9af2014-04-10 01:42:40 +0300393 // TODO: Try to optimize?
Damien Georgea157e4c2014-04-09 19:17:53 +0100394 arg = mp_type_list.make_new((mp_obj_t)&mp_type_list, 1, 0, &arg);
395 }
396 mp_obj_list_get(arg, &seq_len, &seq_items);
Damiend99b0522013-12-21 18:17:45 +0000397 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000398
399 // count required length
400 int required_len = 0;
Damiend99b0522013-12-21 18:17:45 +0000401 for (int i = 0; i < seq_len; i++) {
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300402 if (mp_obj_get_type(seq_items[i]) != self_type) {
403 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
404 "join expects a list of str/bytes objects consistent with self object"));
Damiend99b0522013-12-21 18:17:45 +0000405 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000406 if (i > 0) {
407 required_len += sep_len;
408 }
Damien George5fa93b62014-01-22 14:35:10 +0000409 GET_STR_LEN(seq_items[i], l);
410 required_len += l;
Damiend99b0522013-12-21 18:17:45 +0000411 }
412
413 // make joined string
Damien George5fa93b62014-01-22 14:35:10 +0000414 byte *data;
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300415 mp_obj_t joined_str = mp_obj_str_builder_start(self_type, required_len, &data);
Damiend99b0522013-12-21 18:17:45 +0000416 for (int i = 0; i < seq_len; i++) {
Damiend99b0522013-12-21 18:17:45 +0000417 if (i > 0) {
Damien George5fa93b62014-01-22 14:35:10 +0000418 memcpy(data, sep_str, sep_len);
419 data += sep_len;
Damiend99b0522013-12-21 18:17:45 +0000420 }
Damien George5fa93b62014-01-22 14:35:10 +0000421 GET_STR_DATA_LEN(seq_items[i], s, l);
422 memcpy(data, s, l);
423 data += l;
Damiend99b0522013-12-21 18:17:45 +0000424 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000425
426 // return joined string
Damien George5fa93b62014-01-22 14:35:10 +0000427 return mp_obj_str_builder_end(joined_str);
Damiend99b0522013-12-21 18:17:45 +0000428}
429
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200430#define is_ws(c) ((c) == ' ' || (c) == '\t')
431
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200432STATIC mp_obj_t str_split(uint n_args, const mp_obj_t *args) {
Paul Sokolovskybfb88192014-05-11 21:17:28 +0300433 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Damien Georgedeed0872014-04-06 11:11:15 +0100434 machine_int_t splits = -1;
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200435 mp_obj_t sep = mp_const_none;
436 if (n_args > 1) {
437 sep = args[1];
438 if (n_args > 2) {
Damien Georgedeed0872014-04-06 11:11:15 +0100439 splits = mp_obj_get_int(args[2]);
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200440 }
441 }
Damien Georgedeed0872014-04-06 11:11:15 +0100442
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200443 mp_obj_t res = mp_obj_new_list(0, NULL);
Damien George5fa93b62014-01-22 14:35:10 +0000444 GET_STR_DATA_LEN(args[0], s, len);
445 const byte *top = s + len;
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200446
Damien Georgedeed0872014-04-06 11:11:15 +0100447 if (sep == mp_const_none) {
448 // sep not given, so separate on whitespace
449
450 // Initial whitespace is not counted as split, so we pre-do it
Damien George5fa93b62014-01-22 14:35:10 +0000451 while (s < top && is_ws(*s)) s++;
Damien Georgedeed0872014-04-06 11:11:15 +0100452 while (s < top && splits != 0) {
453 const byte *start = s;
454 while (s < top && !is_ws(*s)) s++;
Damien Georgef600a6a2014-05-25 22:34:34 +0100455 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, s - start));
Damien Georgedeed0872014-04-06 11:11:15 +0100456 if (s >= top) {
457 break;
458 }
459 while (s < top && is_ws(*s)) s++;
460 if (splits > 0) {
461 splits--;
462 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200463 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200464
Damien Georgedeed0872014-04-06 11:11:15 +0100465 if (s < top) {
Damien Georgef600a6a2014-05-25 22:34:34 +0100466 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, s, top - s));
Damien Georgedeed0872014-04-06 11:11:15 +0100467 }
468
469 } else {
470 // sep given
471
472 uint sep_len;
473 const char *sep_str = mp_obj_str_get_data(sep, &sep_len);
474
475 if (sep_len == 0) {
476 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
477 }
478
479 for (;;) {
480 const byte *start = s;
481 for (;;) {
482 if (splits == 0 || s + sep_len > top) {
483 s = top;
484 break;
485 } else if (memcmp(s, sep_str, sep_len) == 0) {
486 break;
487 }
488 s++;
489 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100490 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, s - start));
Damien Georgedeed0872014-04-06 11:11:15 +0100491 if (s >= top) {
492 break;
493 }
494 s += sep_len;
495 if (splits > 0) {
496 splits--;
497 }
498 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200499 }
500
501 return res;
502}
503
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300504STATIC mp_obj_t str_rsplit(uint n_args, const mp_obj_t *args) {
505 if (n_args < 3) {
506 // If we don't have split limit, it doesn't matter from which side
507 // we split.
508 return str_split(n_args, args);
509 }
510 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
511 mp_obj_t sep = args[1];
512 GET_STR_DATA_LEN(args[0], s, len);
513
514 machine_int_t splits = mp_obj_get_int(args[2]);
515 machine_int_t org_splits = splits;
516 // Preallocate list to the max expected # of elements, as we
517 // will fill it from the end.
518 mp_obj_list_t *res = mp_obj_new_list(splits + 1, NULL);
519 int idx = splits;
520
521 if (sep == mp_const_none) {
Chris Angelico9ab8ab22014-06-04 05:04:23 +1000522 assert(!"TODO: rsplit(None,n) not implemented");
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300523 } else {
524 uint sep_len;
525 const char *sep_str = mp_obj_str_get_data(sep, &sep_len);
526
527 if (sep_len == 0) {
528 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
529 }
530
531 const byte *beg = s;
532 const byte *last = s + len;
533 for (;;) {
534 s = last - sep_len;
535 for (;;) {
536 if (splits == 0 || s < beg) {
537 break;
538 } else if (memcmp(s, sep_str, sep_len) == 0) {
539 break;
540 }
541 s--;
542 }
543 if (s < beg || splits == 0) {
Damien Georgef600a6a2014-05-25 22:34:34 +0100544 res->items[idx] = mp_obj_new_str_of_type(self_type, beg, last - beg);
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300545 break;
546 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100547 res->items[idx--] = mp_obj_new_str_of_type(self_type, s + sep_len, last - s - sep_len);
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300548 last = s;
549 if (splits > 0) {
550 splits--;
551 }
552 }
553 if (idx != 0) {
554 // We split less parts than split limit, now go cleanup surplus
555 int used = org_splits + 1 - idx;
556 memcpy(res->items, &res->items[idx], used * sizeof(mp_obj_t));
557 mp_seq_clear(res->items, used, res->alloc, sizeof(*res->items));
558 res->len = used;
559 }
560 }
561
562 return res;
563}
564
565
xbe3d9a39e2014-04-08 11:42:19 -0700566STATIC mp_obj_t str_finder(uint n_args, const mp_obj_t *args, machine_int_t direction, bool is_index) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300567 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
John R. Lentone8204912014-01-12 21:53:52 +0000568 assert(2 <= n_args && n_args <= 4);
Damien George5fa93b62014-01-22 14:35:10 +0000569 assert(MP_OBJ_IS_STR(args[0]));
570 assert(MP_OBJ_IS_STR(args[1]));
John R. Lentone8204912014-01-12 21:53:52 +0000571
Damien George5fa93b62014-01-22 14:35:10 +0000572 GET_STR_DATA_LEN(args[0], haystack, haystack_len);
573 GET_STR_DATA_LEN(args[1], needle, needle_len);
John R. Lentone8204912014-01-12 21:53:52 +0000574
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300575 const byte *start = haystack;
576 const byte *end = haystack + haystack_len;
John R. Lentone8204912014-01-12 21:53:52 +0000577 if (n_args >= 3 && args[2] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300578 start = str_index_to_ptr(self_type, haystack, haystack_len, args[2], true);
John R. Lentone8204912014-01-12 21:53:52 +0000579 }
580 if (n_args >= 4 && args[3] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300581 end = str_index_to_ptr(self_type, haystack, haystack_len, args[3], true);
John R. Lentone8204912014-01-12 21:53:52 +0000582 }
583
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300584 const byte *p = find_subbytes(start, end - start, needle, needle_len, direction);
Damien George23005372014-01-13 19:39:01 +0000585 if (p == NULL) {
586 // not found
xbe3d9a39e2014-04-08 11:42:19 -0700587 if (is_index) {
588 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "substring not found"));
589 } else {
590 return MP_OBJ_NEW_SMALL_INT(-1);
591 }
Damien George23005372014-01-13 19:39:01 +0000592 } else {
593 // found
xbe17a5a832014-03-23 23:31:58 -0700594 return MP_OBJ_NEW_SMALL_INT(p - haystack);
John R. Lentone8204912014-01-12 21:53:52 +0000595 }
John R. Lentone8204912014-01-12 21:53:52 +0000596}
597
xbe17a5a832014-03-23 23:31:58 -0700598STATIC mp_obj_t str_find(uint n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700599 return str_finder(n_args, args, 1, false);
xbe17a5a832014-03-23 23:31:58 -0700600}
601
602STATIC mp_obj_t str_rfind(uint n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700603 return str_finder(n_args, args, -1, false);
604}
605
606STATIC mp_obj_t str_index(uint n_args, const mp_obj_t *args) {
607 return str_finder(n_args, args, 1, true);
608}
609
610STATIC mp_obj_t str_rindex(uint n_args, const mp_obj_t *args) {
611 return str_finder(n_args, args, -1, true);
xbe17a5a832014-03-23 23:31:58 -0700612}
613
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200614// TODO: (Much) more variety in args
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300615STATIC mp_obj_t str_startswith(uint n_args, const mp_obj_t *args) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300616 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300617 GET_STR_DATA_LEN(args[0], str, str_len);
618 GET_STR_DATA_LEN(args[1], prefix, prefix_len);
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300619 const byte *start = str;
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300620 if (n_args > 2) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300621 start = str_index_to_ptr(self_type, str, str_len, args[2], true);
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300622 }
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300623 if (prefix_len + (start - str) > str_len) {
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200624 return mp_const_false;
625 }
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300626 return MP_BOOL(memcmp(start, prefix, prefix_len) == 0);
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200627}
628
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +0300629STATIC mp_obj_t str_endswith(uint n_args, const mp_obj_t *args) {
630 GET_STR_DATA_LEN(args[0], str, str_len);
631 GET_STR_DATA_LEN(args[1], suffix, suffix_len);
632 assert(n_args == 2);
633
634 if (suffix_len > str_len) {
635 return mp_const_false;
636 }
637 return MP_BOOL(memcmp(str + (str_len - suffix_len), suffix, suffix_len) == 0);
638}
639
Paul Sokolovsky88107842014-04-26 06:20:08 +0300640enum { LSTRIP, RSTRIP, STRIP };
641
642STATIC mp_obj_t str_uni_strip(int type, uint n_args, const mp_obj_t *args) {
xbe7b0f39f2014-01-08 14:23:45 -0800643 assert(1 <= n_args && n_args <= 2);
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300644 assert(is_str_or_bytes(args[0]));
645 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Damien George5fa93b62014-01-22 14:35:10 +0000646
647 const byte *chars_to_del;
648 uint chars_to_del_len;
649 static const byte whitespace[] = " \t\n\r\v\f";
xbe7b0f39f2014-01-08 14:23:45 -0800650
651 if (n_args == 1) {
652 chars_to_del = whitespace;
Damien George5fa93b62014-01-22 14:35:10 +0000653 chars_to_del_len = sizeof(whitespace);
xbe7b0f39f2014-01-08 14:23:45 -0800654 } else {
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300655 if (mp_obj_get_type(args[1]) != self_type) {
656 arg_type_mixup();
657 }
Damien George5fa93b62014-01-22 14:35:10 +0000658 GET_STR_DATA_LEN(args[1], s, l);
659 chars_to_del = s;
660 chars_to_del_len = l;
xbe7b0f39f2014-01-08 14:23:45 -0800661 }
662
Damien George5fa93b62014-01-22 14:35:10 +0000663 GET_STR_DATA_LEN(args[0], orig_str, orig_str_len);
xbe7b0f39f2014-01-08 14:23:45 -0800664
xbec5538882014-03-16 17:58:35 -0700665 machine_uint_t first_good_char_pos = 0;
xbe7b0f39f2014-01-08 14:23:45 -0800666 bool first_good_char_pos_set = false;
xbec5538882014-03-16 17:58:35 -0700667 machine_uint_t last_good_char_pos = 0;
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300668 machine_uint_t i = 0;
669 machine_int_t delta = 1;
670 if (type == RSTRIP) {
671 i = orig_str_len - 1;
672 delta = -1;
673 }
674 for (machine_uint_t len = orig_str_len; len > 0; len--) {
xbe17a5a832014-03-23 23:31:58 -0700675 if (find_subbytes(chars_to_del, chars_to_del_len, &orig_str[i], 1, 1) == NULL) {
xbe7b0f39f2014-01-08 14:23:45 -0800676 if (!first_good_char_pos_set) {
Paul Sokolovskybcdffe52014-05-30 03:07:05 +0300677 first_good_char_pos_set = true;
xbe7b0f39f2014-01-08 14:23:45 -0800678 first_good_char_pos = i;
Paul Sokolovsky88107842014-04-26 06:20:08 +0300679 if (type == LSTRIP) {
680 last_good_char_pos = orig_str_len - 1;
681 break;
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300682 } else if (type == RSTRIP) {
683 first_good_char_pos = 0;
684 last_good_char_pos = i;
685 break;
Paul Sokolovsky88107842014-04-26 06:20:08 +0300686 }
xbe7b0f39f2014-01-08 14:23:45 -0800687 }
Paul Sokolovsky88107842014-04-26 06:20:08 +0300688 last_good_char_pos = i;
xbe7b0f39f2014-01-08 14:23:45 -0800689 }
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300690 i += delta;
xbe7b0f39f2014-01-08 14:23:45 -0800691 }
692
Paul Sokolovskybcdffe52014-05-30 03:07:05 +0300693 if (!first_good_char_pos_set) {
Damien George5fa93b62014-01-22 14:35:10 +0000694 // string is all whitespace, return ''
695 return MP_OBJ_NEW_QSTR(MP_QSTR_);
xbe7b0f39f2014-01-08 14:23:45 -0800696 }
697
698 assert(last_good_char_pos >= first_good_char_pos);
699 //+1 to accomodate the last character
xbec5538882014-03-16 17:58:35 -0700700 machine_uint_t stripped_len = last_good_char_pos - first_good_char_pos + 1;
Paul Sokolovsky88276822014-05-30 03:11:44 +0300701 if (stripped_len == orig_str_len) {
702 // If nothing was stripped, don't bother to dup original string
703 // TODO: watch out for this case when we'll get to bytearray.strip()
704 assert(first_good_char_pos == 0);
705 return args[0];
706 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100707 return mp_obj_new_str_of_type(self_type, orig_str + first_good_char_pos, stripped_len);
xbe7b0f39f2014-01-08 14:23:45 -0800708}
709
Paul Sokolovsky88107842014-04-26 06:20:08 +0300710STATIC mp_obj_t str_strip(uint n_args, const mp_obj_t *args) {
711 return str_uni_strip(STRIP, n_args, args);
712}
713
714STATIC mp_obj_t str_lstrip(uint n_args, const mp_obj_t *args) {
715 return str_uni_strip(LSTRIP, n_args, args);
716}
717
718STATIC mp_obj_t str_rstrip(uint n_args, const mp_obj_t *args) {
719 return str_uni_strip(RSTRIP, n_args, args);
720}
721
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700722// Takes an int arg, but only parses unsigned numbers, and only changes
723// *num if at least one digit was parsed.
724static int str_to_int(const char *str, int *num) {
725 const char *s = str;
726 if (unichar_isdigit(*s)) {
727 *num = 0;
728 do {
729 *num = *num * 10 + (*s - '0');
730 s++;
731 }
732 while (unichar_isdigit(*s));
733 }
734 return s - str;
735}
736
737static bool isalignment(char ch) {
738 return ch && strchr("<>=^", ch) != NULL;
739}
740
741static bool istype(char ch) {
742 return ch && strchr("bcdeEfFgGnosxX%", ch) != NULL;
743}
744
745static bool arg_looks_integer(mp_obj_t arg) {
746 return MP_OBJ_IS_TYPE(arg, &mp_type_bool) || MP_OBJ_IS_INT(arg);
747}
748
749static bool arg_looks_numeric(mp_obj_t arg) {
750 return arg_looks_integer(arg)
Damien Georgefb510b32014-06-01 13:32:54 +0100751#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700752 || MP_OBJ_IS_TYPE(arg, &mp_type_float)
753#endif
754 ;
755}
756
Dave Hylandsc4029e52014-04-07 11:19:51 -0700757static mp_obj_t arg_as_int(mp_obj_t arg) {
Damien Georgefb510b32014-06-01 13:32:54 +0100758#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700759 if (MP_OBJ_IS_TYPE(arg, &mp_type_float)) {
Dave Hylandsc4029e52014-04-07 11:19:51 -0700760
761 // TODO: Needs a way to construct an mpz integer from a float
762
763 mp_small_int_t num = mp_obj_get_float(arg);
764 return MP_OBJ_NEW_SMALL_INT(num);
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700765 }
766#endif
Dave Hylandsc4029e52014-04-07 11:19:51 -0700767 return arg;
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700768}
769
Damien George897fe0c2014-04-15 22:03:55 +0100770mp_obj_t mp_obj_str_format(uint n_args, const mp_obj_t *args) {
Damien George5fa93b62014-01-22 14:35:10 +0000771 assert(MP_OBJ_IS_STR(args[0]));
Damiend99b0522013-12-21 18:17:45 +0000772
Damien George5fa93b62014-01-22 14:35:10 +0000773 GET_STR_DATA_LEN(args[0], str, len);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700774 int arg_i = 0;
Damiend99b0522013-12-21 18:17:45 +0000775 vstr_t *vstr = vstr_new();
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700776 pfenv_t pfenv_vstr;
777 pfenv_vstr.data = vstr;
778 pfenv_vstr.print_strn = pfenv_vstr_add_strn;
779
Damien George5fa93b62014-01-22 14:35:10 +0000780 for (const byte *top = str + len; str < top; str++) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700781 if (*str == '}') {
Damiend99b0522013-12-21 18:17:45 +0000782 str++;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700783 if (str < top && *str == '}') {
784 vstr_add_char(vstr, '}');
785 continue;
786 }
Damien George11de8392014-06-05 18:57:38 +0100787 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "single '}' encountered in format string"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700788 }
789 if (*str != '{') {
790 vstr_add_char(vstr, *str);
791 continue;
792 }
793
794 str++;
795 if (str < top && *str == '{') {
796 vstr_add_char(vstr, '{');
797 continue;
798 }
799
800 // replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"
801
802 vstr_t *field_name = NULL;
803 char conversion = '\0';
804 vstr_t *format_spec = NULL;
805
806 if (str < top && *str != '}' && *str != '!' && *str != ':') {
807 field_name = vstr_new();
808 while (str < top && *str != '}' && *str != '!' && *str != ':') {
809 vstr_add_char(field_name, *str++);
810 }
811 vstr_add_char(field_name, '\0');
812 }
813
814 // conversion ::= "r" | "s"
815
816 if (str < top && *str == '!') {
817 str++;
818 if (str < top && (*str == 'r' || *str == 's')) {
819 conversion = *str++;
Paul Sokolovskyf2b796e2014-01-15 22:45:20 +0200820 } else {
Damien Georgeea13f402014-04-05 18:32:08 +0100821 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "end of format while looking for conversion specifier"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700822 }
823 }
824
825 if (str < top && *str == ':') {
826 str++;
827 // {:} is the same as {}, which is the same as {!s}
828 // This makes a difference when passing in a True or False
829 // '{}'.format(True) returns 'True'
830 // '{:d}'.format(True) returns '1'
831 // So we treat {:} as {} and this later gets treated to be {!s}
832 if (*str != '}') {
Damien George11de8392014-06-05 18:57:38 +0100833 format_spec = vstr_new();
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700834 while (str < top && *str != '}') {
835 vstr_add_char(format_spec, *str++);
Damiend99b0522013-12-21 18:17:45 +0000836 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700837 vstr_add_char(format_spec, '\0');
838 }
839 }
840 if (str >= top) {
Damien Georgeea13f402014-04-05 18:32:08 +0100841 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "unmatched '{' in format"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700842 }
843 if (*str != '}') {
Damien Georgeea13f402014-04-05 18:32:08 +0100844 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "expected ':' after format specifier"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700845 }
846
847 mp_obj_t arg = mp_const_none;
848
849 if (field_name) {
850 if (arg_i > 0) {
Damien George11de8392014-06-05 18:57:38 +0100851 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "can't switch from automatic field numbering to manual field specification"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700852 }
Damien George3bb8bd82014-04-14 21:20:30 +0100853 int index = 0;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700854 if (str_to_int(vstr_str(field_name), &index) != vstr_len(field_name) - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100855 nlr_raise(mp_obj_new_exception_msg(&mp_type_KeyError, "attributes not supported yet"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700856 }
857 if (index >= n_args - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100858 nlr_raise(mp_obj_new_exception_msg(&mp_type_IndexError, "tuple index out of range"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700859 }
860 arg = args[index + 1];
861 arg_i = -1;
862 vstr_free(field_name);
863 field_name = NULL;
864 } else {
865 if (arg_i < 0) {
Damien George11de8392014-06-05 18:57:38 +0100866 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "can't switch from manual field specification to automatic field numbering"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700867 }
868 if (arg_i >= n_args - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100869 nlr_raise(mp_obj_new_exception_msg(&mp_type_IndexError, "tuple index out of range"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700870 }
871 arg = args[arg_i + 1];
872 arg_i++;
873 }
874 if (!format_spec && !conversion) {
875 conversion = 's';
876 }
877 if (conversion) {
878 mp_print_kind_t print_kind;
879 if (conversion == 's') {
880 print_kind = PRINT_STR;
881 } else if (conversion == 'r') {
882 print_kind = PRINT_REPR;
883 } else {
Damien George11de8392014-06-05 18:57:38 +0100884 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "unknown conversion specifier %c", conversion));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700885 }
886 vstr_t *arg_vstr = vstr_new();
887 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, arg_vstr, arg, print_kind);
Damien George2617eeb2014-05-25 22:27:57 +0100888 arg = mp_obj_new_str(vstr_str(arg_vstr), vstr_len(arg_vstr), false);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700889 vstr_free(arg_vstr);
890 }
891
892 char sign = '\0';
893 char fill = '\0';
894 char align = '\0';
895 int width = -1;
896 int precision = -1;
897 char type = '\0';
898 int flags = 0;
899
900 if (format_spec) {
901 // The format specifier (from http://docs.python.org/2/library/string.html#formatspec)
902 //
903 // [[fill]align][sign][#][0][width][,][.precision][type]
904 // fill ::= <any character>
905 // align ::= "<" | ">" | "=" | "^"
906 // sign ::= "+" | "-" | " "
907 // width ::= integer
908 // precision ::= integer
909 // type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
910
911 const char *s = vstr_str(format_spec);
912 if (isalignment(*s)) {
913 align = *s++;
914 } else if (*s && isalignment(s[1])) {
915 fill = *s++;
916 align = *s++;
917 }
918 if (*s == '+' || *s == '-' || *s == ' ') {
919 if (*s == '+') {
920 flags |= PF_FLAG_SHOW_SIGN;
921 } else if (*s == ' ') {
922 flags |= PF_FLAG_SPACE_SIGN;
923 }
924 sign = *s++;
925 }
926 if (*s == '#') {
927 flags |= PF_FLAG_SHOW_PREFIX;
928 s++;
929 }
930 if (*s == '0') {
931 if (!align) {
932 align = '=';
933 }
934 if (!fill) {
935 fill = '0';
936 }
937 }
938 s += str_to_int(s, &width);
939 if (*s == ',') {
940 flags |= PF_FLAG_SHOW_COMMA;
941 s++;
942 }
943 if (*s == '.') {
944 s++;
945 s += str_to_int(s, &precision);
946 }
947 if (istype(*s)) {
948 type = *s++;
949 }
950 if (*s) {
Damien Georgeea13f402014-04-05 18:32:08 +0100951 nlr_raise(mp_obj_new_exception_msg(&mp_type_KeyError, "Invalid conversion specification"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700952 }
953 vstr_free(format_spec);
954 format_spec = NULL;
955 }
956 if (!align) {
957 if (arg_looks_numeric(arg)) {
958 align = '>';
959 } else {
960 align = '<';
961 }
962 }
963 if (!fill) {
964 fill = ' ';
965 }
966
967 if (sign) {
968 if (type == 's') {
Damien Georgeea13f402014-04-05 18:32:08 +0100969 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "Sign not allowed in string format specifier"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700970 }
971 if (type == 'c') {
Damien Georgeea13f402014-04-05 18:32:08 +0100972 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "Sign not allowed with integer format specifier 'c'"));
Damiend99b0522013-12-21 18:17:45 +0000973 }
974 } else {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700975 sign = '-';
976 }
977
978 switch (align) {
979 case '<': flags |= PF_FLAG_LEFT_ADJUST; break;
980 case '=': flags |= PF_FLAG_PAD_AFTER_SIGN; break;
981 case '^': flags |= PF_FLAG_CENTER_ADJUST; break;
982 }
983
984 if (arg_looks_integer(arg)) {
985 switch (type) {
986 case 'b':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -0700987 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 2, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700988 continue;
989
990 case 'c':
991 {
992 char ch = mp_obj_get_int(arg);
993 pfenv_print_strn(&pfenv_vstr, &ch, 1, flags, fill, width);
994 continue;
995 }
996
997 case '\0': // No explicit format type implies 'd'
998 case 'n': // I don't think we support locales in uPy so use 'd'
999 case 'd':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001000 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 10, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001001 continue;
1002
1003 case 'o':
Dave Hylandsc4029e52014-04-07 11:19:51 -07001004 if (flags & PF_FLAG_SHOW_PREFIX) {
1005 flags |= PF_FLAG_SHOW_OCTAL_LETTER;
1006 }
1007
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001008 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 8, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001009 continue;
1010
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001011 case 'X':
Damien George11de8392014-06-05 18:57:38 +01001012 case 'x':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001013 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 16, type - ('X' - 'A'), flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001014 continue;
1015
1016 case 'e':
1017 case 'E':
1018 case 'f':
1019 case 'F':
1020 case 'g':
1021 case 'G':
1022 case '%':
1023 // The floating point formatters all work with anything that
1024 // looks like an integer
1025 break;
1026
1027 default:
Damien Georgeea13f402014-04-05 18:32:08 +01001028 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Damien George11de8392014-06-05 18:57:38 +01001029 "unknown format code '%c' for object of type '%s'", type, mp_obj_get_type_str(arg)));
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001030 }
Damien Georgec322c5f2014-04-02 20:04:15 +01001031 }
Damien George70f33cd2014-04-02 17:06:05 +01001032
Dave Hylands22fe4d72014-04-02 12:07:31 -07001033 // NOTE: no else here. We need the e, f, g etc formats for integer
1034 // arguments (from above if) to take this if.
Damien Georgec322c5f2014-04-02 20:04:15 +01001035 if (arg_looks_numeric(arg)) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001036 if (!type) {
1037
1038 // Even though the docs say that an unspecified type is the same
1039 // as 'g', there is one subtle difference, when the exponent
1040 // is one less than the precision.
Damien George11de8392014-06-05 18:57:38 +01001041 //
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001042 // '{:10.1}'.format(0.0) ==> '0e+00'
1043 // '{:10.1g}'.format(0.0) ==> '0'
1044 //
1045 // TODO: Figure out how to deal with this.
1046 //
1047 // A proper solution would involve adding a special flag
1048 // or something to format_float, and create a format_double
1049 // to deal with doubles. In order to fix this when using
1050 // sprintf, we'd need to use the e format and tweak the
1051 // returned result to strip trailing zeros like the g format
1052 // does.
1053 //
1054 // {:10.3} and {:10.2e} with 1.23e2 both produce 1.23e+02
1055 // but with 1.e2 you get 1e+02 and 1.00e+02
1056 //
1057 // Stripping the trailing 0's (like g) does would make the
1058 // e format give us the right format.
1059 //
1060 // CPython sources say:
1061 // Omitted type specifier. Behaves in the same way as repr(x)
1062 // and str(x) if no precision is given, else like 'g', but with
1063 // at least one digit after the decimal point. */
1064
1065 type = 'g';
1066 }
1067 if (type == 'n') {
1068 type = 'g';
1069 }
1070
1071 flags |= PF_FLAG_PAD_NAN_INF; // '{:06e}'.format(float('-inf')) should give '-00inf'
1072 switch (type) {
Damien Georgefb510b32014-06-01 13:32:54 +01001073#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001074 case 'e':
1075 case 'E':
1076 case 'f':
1077 case 'F':
1078 case 'g':
1079 case 'G':
Damien George11de8392014-06-05 18:57:38 +01001080 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg), type, flags, fill, width, precision);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001081 break;
1082
1083 case '%':
1084 flags |= PF_FLAG_ADD_PERCENT;
1085 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg) * 100.0F, 'f', flags, fill, width, precision);
1086 break;
Damien Georgec322c5f2014-04-02 20:04:15 +01001087#endif
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001088
1089 default:
Damien Georgeea13f402014-04-05 18:32:08 +01001090 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Damien George11de8392014-06-05 18:57:38 +01001091 "unknown format code '%c' for object of type 'float'",
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001092 type, mp_obj_get_type_str(arg)));
1093 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001094 } else {
Damien George70f33cd2014-04-02 17:06:05 +01001095 // arg doesn't look like a number
1096
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001097 if (align == '=') {
Damien Georgeea13f402014-04-05 18:32:08 +01001098 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "'=' alignment not allowed in string format specifier"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001099 }
Damien George70f33cd2014-04-02 17:06:05 +01001100
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001101 switch (type) {
1102 case '\0':
1103 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, vstr, arg, PRINT_STR);
1104 break;
1105
1106 case 's':
1107 {
1108 uint len;
1109 const char *s = mp_obj_str_get_data(arg, &len);
1110 if (precision < 0) {
1111 precision = len;
1112 }
1113 if (len > precision) {
1114 len = precision;
1115 }
1116 pfenv_print_strn(&pfenv_vstr, s, len, flags, fill, width);
1117 break;
1118 }
1119
1120 default:
Damien Georgeea13f402014-04-05 18:32:08 +01001121 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Damien George11de8392014-06-05 18:57:38 +01001122 "unknown format code '%c' for object of type 'str'",
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001123 type, mp_obj_get_type_str(arg)));
1124 }
Damiend99b0522013-12-21 18:17:45 +00001125 }
1126 }
1127
Damien George2617eeb2014-05-25 22:27:57 +01001128 mp_obj_t s = mp_obj_new_str(vstr->buf, vstr->len, false);
Damien George5fa93b62014-01-22 14:35:10 +00001129 vstr_free(vstr);
1130 return s;
Damiend99b0522013-12-21 18:17:45 +00001131}
1132
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001133STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, uint n_args, const mp_obj_t *args, mp_obj_t dict) {
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001134 assert(MP_OBJ_IS_STR(pattern));
1135
1136 GET_STR_DATA_LEN(pattern, str, len);
Dave Hylands6756a372014-04-02 11:42:39 -07001137 const byte *start_str = str;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001138 int arg_i = 0;
1139 vstr_t *vstr = vstr_new();
Dave Hylands6756a372014-04-02 11:42:39 -07001140 pfenv_t pfenv_vstr;
1141 pfenv_vstr.data = vstr;
1142 pfenv_vstr.print_strn = pfenv_vstr_add_strn;
1143
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001144 for (const byte *top = str + len; str < top; str++) {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001145 mp_obj_t arg = MP_OBJ_NULL;
Dave Hylands6756a372014-04-02 11:42:39 -07001146 if (*str != '%') {
1147 vstr_add_char(vstr, *str);
1148 continue;
1149 }
1150 if (++str >= top) {
1151 break;
1152 }
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001153 if (*str == '%') {
Dave Hylands6756a372014-04-02 11:42:39 -07001154 vstr_add_char(vstr, '%');
1155 continue;
1156 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001157
1158 // Dictionary value lookup
1159 if (*str == '(') {
1160 const byte *key = ++str;
1161 while (*str != ')') {
1162 if (str >= top) {
1163 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "incomplete format key"));
1164 }
1165 ++str;
1166 }
1167 mp_obj_t k_obj = mp_obj_new_str((const char*)key, str - key, true);
1168 arg = mp_obj_dict_get(dict, k_obj);
1169 str++;
Dave Hylands6756a372014-04-02 11:42:39 -07001170 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001171
Dave Hylands6756a372014-04-02 11:42:39 -07001172 int flags = 0;
1173 char fill = ' ';
Damien George11de8392014-06-05 18:57:38 +01001174 int alt = 0;
Dave Hylands6756a372014-04-02 11:42:39 -07001175 while (str < top) {
1176 if (*str == '-') flags |= PF_FLAG_LEFT_ADJUST;
1177 else if (*str == '+') flags |= PF_FLAG_SHOW_SIGN;
1178 else if (*str == ' ') flags |= PF_FLAG_SPACE_SIGN;
Damien George11de8392014-06-05 18:57:38 +01001179 else if (*str == '#') alt = PF_FLAG_SHOW_PREFIX;
Dave Hylands6756a372014-04-02 11:42:39 -07001180 else if (*str == '0') {
1181 flags |= PF_FLAG_PAD_AFTER_SIGN;
1182 fill = '0';
1183 } else break;
1184 str++;
1185 }
1186 // parse width, if it exists
Damien George11de8392014-06-05 18:57:38 +01001187 int width = 0;
Dave Hylands6756a372014-04-02 11:42:39 -07001188 if (str < top) {
1189 if (*str == '*') {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001190 if (arg_i >= n_args) {
1191 goto not_enough_args;
1192 }
Dave Hylands6756a372014-04-02 11:42:39 -07001193 width = mp_obj_get_int(args[arg_i++]);
1194 str++;
1195 } else {
1196 for (; str < top && '0' <= *str && *str <= '9'; str++) {
1197 width = width * 10 + *str - '0';
1198 }
1199 }
1200 }
1201 int prec = -1;
1202 if (str < top && *str == '.') {
1203 if (++str < top) {
1204 if (*str == '*') {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001205 if (arg_i >= n_args) {
1206 goto not_enough_args;
1207 }
Dave Hylands6756a372014-04-02 11:42:39 -07001208 prec = mp_obj_get_int(args[arg_i++]);
1209 str++;
1210 } else {
1211 prec = 0;
1212 for (; str < top && '0' <= *str && *str <= '9'; str++) {
1213 prec = prec * 10 + *str - '0';
1214 }
1215 }
1216 }
1217 }
1218
1219 if (str >= top) {
Damien Georgeea13f402014-04-05 18:32:08 +01001220 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "incomplete format"));
Dave Hylands6756a372014-04-02 11:42:39 -07001221 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001222
1223 // Tuple value lookup
1224 if (arg == MP_OBJ_NULL) {
1225 if (arg_i >= n_args) {
1226not_enough_args:
1227 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "not enough arguments for format string"));
1228 }
1229 arg = args[arg_i++];
1230 }
Dave Hylands6756a372014-04-02 11:42:39 -07001231 switch (*str) {
1232 case 'c':
1233 if (MP_OBJ_IS_STR(arg)) {
1234 uint len;
1235 const char *s = mp_obj_str_get_data(arg, &len);
1236 if (len != 1) {
Damien George11de8392014-06-05 18:57:38 +01001237 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "%%c requires int or char"));
Dave Hylands6756a372014-04-02 11:42:39 -07001238 break;
1239 }
1240 pfenv_print_strn(&pfenv_vstr, s, 1, flags, ' ', width);
1241 break;
1242 }
1243 if (arg_looks_integer(arg)) {
1244 char ch = mp_obj_get_int(arg);
1245 pfenv_print_strn(&pfenv_vstr, &ch, 1, flags, ' ', width);
1246 break;
1247 }
Damien Georgefb510b32014-06-01 13:32:54 +01001248#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylands6756a372014-04-02 11:42:39 -07001249 // This is what CPython reports, so we report the same.
1250 if (MP_OBJ_IS_TYPE(arg, &mp_type_float)) {
Damien George11de8392014-06-05 18:57:38 +01001251 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "integer argument expected, got float"));
Dave Hylands6756a372014-04-02 11:42:39 -07001252
1253 }
1254#endif
Damien George11de8392014-06-05 18:57:38 +01001255 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "an integer is required"));
1256 break;
Dave Hylands6756a372014-04-02 11:42:39 -07001257
1258 case 'd':
1259 case 'i':
1260 case 'u':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001261 pfenv_print_mp_int(&pfenv_vstr, arg_as_int(arg), 1, 10, 'a', flags, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001262 break;
1263
Damien Georgefb510b32014-06-01 13:32:54 +01001264#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylands6756a372014-04-02 11:42:39 -07001265 case 'e':
1266 case 'E':
1267 case 'f':
1268 case 'F':
1269 case 'g':
1270 case 'G':
1271 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg), *str, flags, fill, width, prec);
1272 break;
1273#endif
1274
1275 case 'o':
1276 if (alt) {
Dave Hylandsc4029e52014-04-07 11:19:51 -07001277 flags |= (PF_FLAG_SHOW_PREFIX | PF_FLAG_SHOW_OCTAL_LETTER);
Dave Hylands6756a372014-04-02 11:42:39 -07001278 }
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001279 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 8, 'a', flags, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001280 break;
1281
1282 case 'r':
1283 case 's':
1284 {
1285 vstr_t *arg_vstr = vstr_new();
1286 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf,
1287 arg_vstr, arg, *str == 'r' ? PRINT_REPR : PRINT_STR);
1288 uint len = vstr_len(arg_vstr);
1289 if (prec < 0) {
1290 prec = len;
1291 }
1292 if (len > prec) {
1293 len = prec;
1294 }
1295 pfenv_print_strn(&pfenv_vstr, vstr_str(arg_vstr), len, flags, ' ', width);
1296 vstr_free(arg_vstr);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001297 break;
1298 }
Dave Hylands6756a372014-04-02 11:42:39 -07001299
Dave Hylands6756a372014-04-02 11:42:39 -07001300 case 'X':
Damien George11de8392014-06-05 18:57:38 +01001301 case 'x':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001302 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 16, *str - ('X' - 'A'), flags | alt, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001303 break;
Damien Georgedeed0872014-04-06 11:11:15 +01001304
Dave Hylands6756a372014-04-02 11:42:39 -07001305 default:
Damien Georgeea13f402014-04-05 18:32:08 +01001306 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Dave Hylands6756a372014-04-02 11:42:39 -07001307 "unsupported format character '%c' (0x%x) at index %d",
1308 *str, *str, str - start_str));
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001309 }
1310 }
1311
1312 if (arg_i != n_args) {
Damien Georgeea13f402014-04-05 18:32:08 +01001313 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "not all arguments converted during string formatting"));
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001314 }
1315
Damien George2617eeb2014-05-25 22:27:57 +01001316 mp_obj_t s = mp_obj_new_str(vstr->buf, vstr->len, false);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001317 vstr_free(vstr);
1318 return s;
1319}
1320
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001321STATIC mp_obj_t str_replace(uint n_args, const mp_obj_t *args) {
xbe480c15a2014-01-30 22:17:30 -08001322 assert(MP_OBJ_IS_STR(args[0]));
xbe480c15a2014-01-30 22:17:30 -08001323
Damien Georgeff715422014-04-07 00:39:13 +01001324 machine_int_t max_rep = -1;
xbe480c15a2014-01-30 22:17:30 -08001325 if (n_args == 4) {
Damien Georgeff715422014-04-07 00:39:13 +01001326 max_rep = mp_obj_get_int(args[3]);
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001327 if (max_rep == 0) {
1328 return args[0];
1329 } else if (max_rep < 0) {
Damien Georgeff715422014-04-07 00:39:13 +01001330 max_rep = -1;
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001331 }
xbe480c15a2014-01-30 22:17:30 -08001332 }
Damien George94f68302014-01-31 23:45:12 +00001333
xbe729be9b2014-04-07 14:46:39 -07001334 // if max_rep is still -1 by this point we will need to do all possible replacements
xbe480c15a2014-01-30 22:17:30 -08001335
Damien Georgeff715422014-04-07 00:39:13 +01001336 // check argument types
1337
1338 if (!MP_OBJ_IS_STR(args[1])) {
1339 bad_implicit_conversion(args[1]);
1340 }
1341
1342 if (!MP_OBJ_IS_STR(args[2])) {
1343 bad_implicit_conversion(args[2]);
1344 }
1345
1346 // extract string data
1347
xbe480c15a2014-01-30 22:17:30 -08001348 GET_STR_DATA_LEN(args[0], str, str_len);
1349 GET_STR_DATA_LEN(args[1], old, old_len);
1350 GET_STR_DATA_LEN(args[2], new, new_len);
Damien George94f68302014-01-31 23:45:12 +00001351
1352 // old won't exist in str if it's longer, so nothing to replace
xbe480c15a2014-01-30 22:17:30 -08001353 if (old_len > str_len) {
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001354 return args[0];
xbe480c15a2014-01-30 22:17:30 -08001355 }
1356
Damien George94f68302014-01-31 23:45:12 +00001357 // data for the replaced string
1358 byte *data = NULL;
1359 mp_obj_t replaced_str = MP_OBJ_NULL;
xbe480c15a2014-01-30 22:17:30 -08001360
Damien George94f68302014-01-31 23:45:12 +00001361 // do 2 passes over the string:
1362 // first pass computes the required length of the replaced string
1363 // second pass does the replacements
1364 for (;;) {
1365 machine_uint_t replaced_str_index = 0;
1366 machine_uint_t num_replacements_done = 0;
1367 const byte *old_occurrence;
1368 const byte *offset_ptr = str;
Damien Georgeff715422014-04-07 00:39:13 +01001369 machine_uint_t str_len_remain = str_len;
1370 if (old_len == 0) {
1371 // if old_str is empty, copy new_str to start of replaced string
1372 // copy the replacement string
1373 if (data != NULL) {
1374 memcpy(data, new, new_len);
1375 }
1376 replaced_str_index += new_len;
1377 num_replacements_done++;
1378 }
1379 while (num_replacements_done != max_rep && str_len_remain > 0 && (old_occurrence = find_subbytes(offset_ptr, str_len_remain, old, old_len, 1)) != NULL) {
1380 if (old_len == 0) {
1381 old_occurrence += 1;
1382 }
Damien George94f68302014-01-31 23:45:12 +00001383 // copy from just after end of last occurrence of to-be-replaced string to right before start of next occurrence
1384 if (data != NULL) {
1385 memcpy(data + replaced_str_index, offset_ptr, old_occurrence - offset_ptr);
1386 }
1387 replaced_str_index += old_occurrence - offset_ptr;
1388 // copy the replacement string
1389 if (data != NULL) {
1390 memcpy(data + replaced_str_index, new, new_len);
1391 }
1392 replaced_str_index += new_len;
1393 offset_ptr = old_occurrence + old_len;
Damien Georgeff715422014-04-07 00:39:13 +01001394 str_len_remain = str + str_len - offset_ptr;
Damien George94f68302014-01-31 23:45:12 +00001395 num_replacements_done++;
Damien George94f68302014-01-31 23:45:12 +00001396 }
1397
1398 // copy from just after end of last occurrence of to-be-replaced string to end of old string
1399 if (data != NULL) {
Damien Georgeff715422014-04-07 00:39:13 +01001400 memcpy(data + replaced_str_index, offset_ptr, str_len_remain);
Damien George94f68302014-01-31 23:45:12 +00001401 }
Damien Georgeff715422014-04-07 00:39:13 +01001402 replaced_str_index += str_len_remain;
Damien George94f68302014-01-31 23:45:12 +00001403
1404 if (data == NULL) {
1405 // first pass
1406 if (num_replacements_done == 0) {
1407 // no substr found, return original string
1408 return args[0];
1409 } else {
1410 // substr found, allocate new string
1411 replaced_str = mp_obj_str_builder_start(mp_obj_get_type(args[0]), replaced_str_index, &data);
Damien Georgeff715422014-04-07 00:39:13 +01001412 assert(data != NULL);
Damien George94f68302014-01-31 23:45:12 +00001413 }
1414 } else {
1415 // second pass, we are done
1416 break;
1417 }
xbe480c15a2014-01-30 22:17:30 -08001418 }
Damien George94f68302014-01-31 23:45:12 +00001419
xbe480c15a2014-01-30 22:17:30 -08001420 return mp_obj_str_builder_end(replaced_str);
1421}
1422
xbe9e1e8cd2014-03-12 22:57:16 -07001423STATIC mp_obj_t str_count(uint n_args, const mp_obj_t *args) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001424 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
xbe9e1e8cd2014-03-12 22:57:16 -07001425 assert(2 <= n_args && n_args <= 4);
1426 assert(MP_OBJ_IS_STR(args[0]));
1427 assert(MP_OBJ_IS_STR(args[1]));
1428
1429 GET_STR_DATA_LEN(args[0], haystack, haystack_len);
1430 GET_STR_DATA_LEN(args[1], needle, needle_len);
1431
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001432 const byte *start = haystack;
1433 const byte *end = haystack + haystack_len;
xbe9e1e8cd2014-03-12 22:57:16 -07001434 if (n_args >= 3 && args[2] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001435 start = str_index_to_ptr(self_type, haystack, haystack_len, args[2], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001436 }
1437 if (n_args >= 4 && args[3] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001438 end = str_index_to_ptr(self_type, haystack, haystack_len, args[3], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001439 }
1440
Damien George536dde22014-03-13 22:07:55 +00001441 // if needle_len is zero then we count each gap between characters as an occurrence
1442 if (needle_len == 0) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001443 return MP_OBJ_NEW_SMALL_INT(unichar_charlen((const char*)start, end - start) + 1);
xbe9e1e8cd2014-03-12 22:57:16 -07001444 }
1445
Damien George536dde22014-03-13 22:07:55 +00001446 // count the occurrences
1447 machine_int_t num_occurrences = 0;
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001448 for (const byte *haystack_ptr = start; haystack_ptr + needle_len <= end;) {
1449 if (memcmp(haystack_ptr, needle, needle_len) == 0) {
xbec5d70ba2014-03-13 00:29:15 -07001450 num_occurrences++;
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001451 haystack_ptr += needle_len;
1452 } else {
1453 haystack_ptr = utf8_next_char(haystack_ptr);
xbec5d70ba2014-03-13 00:29:15 -07001454 }
xbe9e1e8cd2014-03-12 22:57:16 -07001455 }
1456
1457 return MP_OBJ_NEW_SMALL_INT(num_occurrences);
1458}
1459
Damien Georgeb035db32014-03-21 20:39:40 +00001460STATIC mp_obj_t str_partitioner(mp_obj_t self_in, mp_obj_t arg, machine_int_t direction) {
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +03001461 if (!is_str_or_bytes(self_in)) {
1462 assert(0);
1463 }
1464 mp_obj_type_t *self_type = mp_obj_get_type(self_in);
1465 if (self_type != mp_obj_get_type(arg)) {
1466 arg_type_mixup();
xbe613a8e32014-03-18 00:06:29 -07001467 }
Damien Georgeb035db32014-03-21 20:39:40 +00001468
xbe613a8e32014-03-18 00:06:29 -07001469 GET_STR_DATA_LEN(self_in, str, str_len);
1470 GET_STR_DATA_LEN(arg, sep, sep_len);
1471
1472 if (sep_len == 0) {
Damien Georgeea13f402014-04-05 18:32:08 +01001473 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
xbe613a8e32014-03-18 00:06:29 -07001474 }
Damien Georgeb035db32014-03-21 20:39:40 +00001475
1476 mp_obj_t result[] = {MP_OBJ_NEW_QSTR(MP_QSTR_), MP_OBJ_NEW_QSTR(MP_QSTR_), MP_OBJ_NEW_QSTR(MP_QSTR_)};
1477
1478 if (direction > 0) {
1479 result[0] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001480 } else {
Damien Georgeb035db32014-03-21 20:39:40 +00001481 result[2] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001482 }
xbe613a8e32014-03-18 00:06:29 -07001483
xbe17a5a832014-03-23 23:31:58 -07001484 const byte *position_ptr = find_subbytes(str, str_len, sep, sep_len, direction);
1485 if (position_ptr != NULL) {
1486 machine_uint_t position = position_ptr - str;
Damien Georgef600a6a2014-05-25 22:34:34 +01001487 result[0] = mp_obj_new_str_of_type(self_type, str, position);
xbe17a5a832014-03-23 23:31:58 -07001488 result[1] = arg;
Damien Georgef600a6a2014-05-25 22:34:34 +01001489 result[2] = mp_obj_new_str_of_type(self_type, str + position + sep_len, str_len - position - sep_len);
xbe613a8e32014-03-18 00:06:29 -07001490 }
Damien Georgeb035db32014-03-21 20:39:40 +00001491
xbe0a6894c2014-03-21 01:12:26 -07001492 return mp_obj_new_tuple(3, result);
xbe613a8e32014-03-18 00:06:29 -07001493}
1494
Damien Georgeb035db32014-03-21 20:39:40 +00001495STATIC mp_obj_t str_partition(mp_obj_t self_in, mp_obj_t arg) {
1496 return str_partitioner(self_in, arg, 1);
xbe0a6894c2014-03-21 01:12:26 -07001497}
xbe4504ea82014-03-19 00:46:14 -07001498
Damien Georgeb035db32014-03-21 20:39:40 +00001499STATIC mp_obj_t str_rpartition(mp_obj_t self_in, mp_obj_t arg) {
1500 return str_partitioner(self_in, arg, -1);
xbe4504ea82014-03-19 00:46:14 -07001501}
1502
Paul Sokolovsky69135212014-05-10 19:47:41 +03001503// Supposedly not too critical operations, so optimize for code size
Damien Georgefcc9cf62014-06-01 18:22:09 +01001504STATIC mp_obj_t str_caseconv(unichar (*op)(unichar), mp_obj_t self_in) {
Paul Sokolovsky69135212014-05-10 19:47:41 +03001505 GET_STR_DATA_LEN(self_in, self_data, self_len);
1506 byte *data;
1507 mp_obj_t s = mp_obj_str_builder_start(mp_obj_get_type(self_in), self_len, &data);
1508 for (int i = 0; i < self_len; i++) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001509 *data++ = op(*self_data++);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001510 }
1511 *data = 0;
1512 return mp_obj_str_builder_end(s);
1513}
1514
1515STATIC mp_obj_t str_lower(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001516 return str_caseconv(unichar_tolower, self_in);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001517}
1518
1519STATIC mp_obj_t str_upper(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001520 return str_caseconv(unichar_toupper, self_in);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001521}
1522
Damien Georgefcc9cf62014-06-01 18:22:09 +01001523STATIC mp_obj_t str_uni_istype(bool (*f)(unichar), mp_obj_t self_in) {
Kim Bautersa3f4b832014-05-31 07:30:03 +01001524 GET_STR_DATA_LEN(self_in, self_data, self_len);
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001525
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001526 if (self_len == 0) {
1527 return mp_const_false; // default to False for empty str
1528 }
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001529
Damien Georgefcc9cf62014-06-01 18:22:09 +01001530 if (f != unichar_isupper && f != unichar_islower) {
Kim Bautersa3f4b832014-05-31 07:30:03 +01001531 for (int i = 0; i < self_len; i++) {
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001532 if (!f(*self_data++)) {
1533 return mp_const_false;
1534 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001535 }
1536 } else {
Kim Bautersa3f4b832014-05-31 07:30:03 +01001537 bool contains_alpha = false;
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001538
Kim Bautersa3f4b832014-05-31 07:30:03 +01001539 for (int i = 0; i < self_len; i++) { // only check alphanumeric characters
1540 if (unichar_isalpha(*self_data++)) {
1541 contains_alpha = true;
Damien Georgefcc9cf62014-06-01 18:22:09 +01001542 if (!f(*(self_data - 1))) { // -1 because we already incremented above
1543 return mp_const_false;
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001544 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001545 }
1546 }
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001547
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001548 if (!contains_alpha) {
1549 return mp_const_false;
1550 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001551 }
1552
1553 return mp_const_true;
1554}
1555
1556STATIC mp_obj_t str_isspace(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001557 return str_uni_istype(unichar_isspace, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001558}
1559
1560STATIC mp_obj_t str_isalpha(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001561 return str_uni_istype(unichar_isalpha, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001562}
1563
1564STATIC mp_obj_t str_isdigit(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001565 return str_uni_istype(unichar_isdigit, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001566}
1567
1568STATIC mp_obj_t str_isupper(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001569 return str_uni_istype(unichar_isupper, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001570}
1571
1572STATIC mp_obj_t str_islower(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001573 return str_uni_istype(unichar_islower, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001574}
1575
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001576#if MICROPY_CPYTHON_COMPAT
1577// These methods are superfluous in the presense of str() and bytes()
1578// constructors.
1579// TODO: should accept kwargs too
1580STATIC mp_obj_t bytes_decode(uint n_args, const mp_obj_t *args) {
1581 mp_obj_t new_args[2];
1582 if (n_args == 1) {
1583 new_args[0] = args[0];
1584 new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
1585 args = new_args;
1586 n_args++;
1587 }
1588 return str_make_new(NULL, n_args, 0, args);
1589}
1590
1591// TODO: should accept kwargs too
1592STATIC mp_obj_t str_encode(uint n_args, const mp_obj_t *args) {
1593 mp_obj_t new_args[2];
1594 if (n_args == 1) {
1595 new_args[0] = args[0];
1596 new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
1597 args = new_args;
1598 n_args++;
1599 }
1600 return bytes_make_new(NULL, n_args, 0, args);
1601}
1602#endif
1603
Damien George57a4b4f2014-04-18 22:29:21 +01001604STATIC machine_int_t str_get_buffer(mp_obj_t self_in, mp_buffer_info_t *bufinfo, int flags) {
1605 if (flags == MP_BUFFER_READ) {
Damien George2da98302014-03-09 19:58:18 +00001606 GET_STR_DATA_LEN(self_in, str_data, str_len);
1607 bufinfo->buf = (void*)str_data;
1608 bufinfo->len = str_len;
Damien George57a4b4f2014-04-18 22:29:21 +01001609 bufinfo->typecode = 'b';
Damien George2da98302014-03-09 19:58:18 +00001610 return 0;
1611 } else {
1612 // can't write to a string
1613 bufinfo->buf = NULL;
1614 bufinfo->len = 0;
Damien George57a4b4f2014-04-18 22:29:21 +01001615 bufinfo->typecode = -1;
Damien George2da98302014-03-09 19:58:18 +00001616 return 1;
1617 }
1618}
1619
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001620#if MICROPY_CPYTHON_COMPAT
Paul Sokolovsky97319122014-06-13 22:01:26 +03001621MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(bytes_decode_obj, 1, 3, bytes_decode);
1622MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_encode_obj, 1, 3, str_encode);
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001623#endif
Paul Sokolovsky97319122014-06-13 22:01:26 +03001624MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_find_obj, 2, 4, str_find);
1625MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rfind_obj, 2, 4, str_rfind);
1626MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_index_obj, 2, 4, str_index);
1627MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rindex_obj, 2, 4, str_rindex);
1628MP_DEFINE_CONST_FUN_OBJ_2(str_join_obj, str_join);
1629MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_split_obj, 1, 3, str_split);
1630MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rsplit_obj, 1, 3, str_rsplit);
1631MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_startswith_obj, 2, 3, str_startswith);
1632MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_endswith_obj, 2, 3, str_endswith);
1633MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_strip_obj, 1, 2, str_strip);
1634MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_lstrip_obj, 1, 2, str_lstrip);
1635MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rstrip_obj, 1, 2, str_rstrip);
1636MP_DEFINE_CONST_FUN_OBJ_VAR(str_format_obj, 1, mp_obj_str_format);
1637MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_replace_obj, 3, 4, str_replace);
1638MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_count_obj, 2, 4, str_count);
1639MP_DEFINE_CONST_FUN_OBJ_2(str_partition_obj, str_partition);
1640MP_DEFINE_CONST_FUN_OBJ_2(str_rpartition_obj, str_rpartition);
1641MP_DEFINE_CONST_FUN_OBJ_1(str_lower_obj, str_lower);
1642MP_DEFINE_CONST_FUN_OBJ_1(str_upper_obj, str_upper);
1643MP_DEFINE_CONST_FUN_OBJ_1(str_isspace_obj, str_isspace);
1644MP_DEFINE_CONST_FUN_OBJ_1(str_isalpha_obj, str_isalpha);
1645MP_DEFINE_CONST_FUN_OBJ_1(str_isdigit_obj, str_isdigit);
1646MP_DEFINE_CONST_FUN_OBJ_1(str_isupper_obj, str_isupper);
1647MP_DEFINE_CONST_FUN_OBJ_1(str_islower_obj, str_islower);
Damiend99b0522013-12-21 18:17:45 +00001648
Damien George9b196cd2014-03-26 21:47:19 +00001649STATIC const mp_map_elem_t str_locals_dict_table[] = {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001650#if MICROPY_CPYTHON_COMPAT
1651 { MP_OBJ_NEW_QSTR(MP_QSTR_decode), (mp_obj_t)&bytes_decode_obj },
1652 { MP_OBJ_NEW_QSTR(MP_QSTR_encode), (mp_obj_t)&str_encode_obj },
1653#endif
Damien George9b196cd2014-03-26 21:47:19 +00001654 { MP_OBJ_NEW_QSTR(MP_QSTR_find), (mp_obj_t)&str_find_obj },
1655 { MP_OBJ_NEW_QSTR(MP_QSTR_rfind), (mp_obj_t)&str_rfind_obj },
xbe3d9a39e2014-04-08 11:42:19 -07001656 { MP_OBJ_NEW_QSTR(MP_QSTR_index), (mp_obj_t)&str_index_obj },
1657 { MP_OBJ_NEW_QSTR(MP_QSTR_rindex), (mp_obj_t)&str_rindex_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001658 { MP_OBJ_NEW_QSTR(MP_QSTR_join), (mp_obj_t)&str_join_obj },
1659 { MP_OBJ_NEW_QSTR(MP_QSTR_split), (mp_obj_t)&str_split_obj },
Paul Sokolovsky2a273652014-05-13 08:07:08 +03001660 { MP_OBJ_NEW_QSTR(MP_QSTR_rsplit), (mp_obj_t)&str_rsplit_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001661 { MP_OBJ_NEW_QSTR(MP_QSTR_startswith), (mp_obj_t)&str_startswith_obj },
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +03001662 { MP_OBJ_NEW_QSTR(MP_QSTR_endswith), (mp_obj_t)&str_endswith_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001663 { MP_OBJ_NEW_QSTR(MP_QSTR_strip), (mp_obj_t)&str_strip_obj },
Paul Sokolovsky88107842014-04-26 06:20:08 +03001664 { MP_OBJ_NEW_QSTR(MP_QSTR_lstrip), (mp_obj_t)&str_lstrip_obj },
1665 { MP_OBJ_NEW_QSTR(MP_QSTR_rstrip), (mp_obj_t)&str_rstrip_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001666 { MP_OBJ_NEW_QSTR(MP_QSTR_format), (mp_obj_t)&str_format_obj },
1667 { MP_OBJ_NEW_QSTR(MP_QSTR_replace), (mp_obj_t)&str_replace_obj },
1668 { MP_OBJ_NEW_QSTR(MP_QSTR_count), (mp_obj_t)&str_count_obj },
1669 { MP_OBJ_NEW_QSTR(MP_QSTR_partition), (mp_obj_t)&str_partition_obj },
1670 { MP_OBJ_NEW_QSTR(MP_QSTR_rpartition), (mp_obj_t)&str_rpartition_obj },
Paul Sokolovsky69135212014-05-10 19:47:41 +03001671 { MP_OBJ_NEW_QSTR(MP_QSTR_lower), (mp_obj_t)&str_lower_obj },
1672 { MP_OBJ_NEW_QSTR(MP_QSTR_upper), (mp_obj_t)&str_upper_obj },
Kim Bautersa3f4b832014-05-31 07:30:03 +01001673 { MP_OBJ_NEW_QSTR(MP_QSTR_isspace), (mp_obj_t)&str_isspace_obj },
1674 { MP_OBJ_NEW_QSTR(MP_QSTR_isalpha), (mp_obj_t)&str_isalpha_obj },
1675 { MP_OBJ_NEW_QSTR(MP_QSTR_isdigit), (mp_obj_t)&str_isdigit_obj },
1676 { MP_OBJ_NEW_QSTR(MP_QSTR_isupper), (mp_obj_t)&str_isupper_obj },
1677 { MP_OBJ_NEW_QSTR(MP_QSTR_islower), (mp_obj_t)&str_islower_obj },
ian-v7a16fad2014-01-06 09:52:29 -08001678};
Damien George97209d32014-01-07 15:58:30 +00001679
Damien George9b196cd2014-03-26 21:47:19 +00001680STATIC MP_DEFINE_CONST_DICT(str_locals_dict, str_locals_dict_table);
1681
Damien George3e1a5c12014-03-29 13:43:38 +00001682const mp_obj_type_t mp_type_str = {
Damien Georgec5966122014-02-15 16:10:44 +00001683 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001684 .name = MP_QSTR_str,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001685 .print = str_print,
Paul Sokolovskybe020c22014-03-21 11:39:01 +02001686 .make_new = str_make_new,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001687 .binary_op = str_binary_op,
Damien George729f7b42014-04-17 22:10:53 +01001688 .subscr = str_subscr,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001689 .getiter = mp_obj_new_str_iterator,
Damien George2da98302014-03-09 19:58:18 +00001690 .buffer_p = { .get_buffer = str_get_buffer },
Damien George9b196cd2014-03-26 21:47:19 +00001691 .locals_dict = (mp_obj_t)&str_locals_dict,
Damiend99b0522013-12-21 18:17:45 +00001692};
1693
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001694// Reuses most of methods from str
Damien George3e1a5c12014-03-29 13:43:38 +00001695const mp_obj_type_t mp_type_bytes = {
Damien Georgec5966122014-02-15 16:10:44 +00001696 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001697 .name = MP_QSTR_bytes,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001698 .print = str_print,
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001699 .make_new = bytes_make_new,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001700 .binary_op = str_binary_op,
Damien George729f7b42014-04-17 22:10:53 +01001701 .subscr = str_subscr,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001702 .getiter = mp_obj_new_bytes_iterator,
Paul Sokolovsky7a70a3a2014-04-08 17:30:47 +03001703 .buffer_p = { .get_buffer = str_get_buffer },
Damien George9b196cd2014-03-26 21:47:19 +00001704 .locals_dict = (mp_obj_t)&str_locals_dict,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001705};
1706
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001707// the zero-length bytes
Damien George3e1a5c12014-03-29 13:43:38 +00001708STATIC const mp_obj_str_t empty_bytes_obj = {{&mp_type_bytes}, 0, 0, NULL};
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001709const mp_obj_t mp_const_empty_bytes = (mp_obj_t)&empty_bytes_obj;
1710
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001711mp_obj_t mp_obj_str_builder_start(const mp_obj_type_t *type, uint len, byte **data) {
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001712 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001713 o->base.type = type;
Damien George5fa93b62014-01-22 14:35:10 +00001714 o->len = len;
Paul Sokolovsky504e2332014-04-19 03:09:17 +03001715 o->hash = 0;
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001716 byte *p = m_new(byte, len + 1);
1717 o->data = p;
1718 *data = p;
Damiend99b0522013-12-21 18:17:45 +00001719 return o;
1720}
1721
Damien George5fa93b62014-01-22 14:35:10 +00001722mp_obj_t mp_obj_str_builder_end(mp_obj_t o_in) {
Damien George5fa93b62014-01-22 14:35:10 +00001723 mp_obj_str_t *o = o_in;
1724 o->hash = qstr_compute_hash(o->data, o->len);
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001725 byte *p = (byte*)o->data;
1726 p[o->len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
Damien George5fa93b62014-01-22 14:35:10 +00001727 return o;
1728}
1729
Damien Georgef600a6a2014-05-25 22:34:34 +01001730mp_obj_t mp_obj_new_str_of_type(const mp_obj_type_t *type, const byte* data, uint len) {
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001731 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001732 o->base.type = type;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001733 o->len = len;
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001734 if (data) {
1735 o->hash = qstr_compute_hash(data, len);
1736 byte *p = m_new(byte, len + 1);
1737 o->data = p;
1738 memcpy(p, data, len * sizeof(byte));
1739 p[len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
1740 }
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001741 return o;
1742}
1743
Damien George2617eeb2014-05-25 22:27:57 +01001744mp_obj_t mp_obj_new_str(const char* data, uint len, bool make_qstr_if_not_already) {
Damien Georgef600a6a2014-05-25 22:34:34 +01001745 if (make_qstr_if_not_already) {
1746 // use existing, or make a new qstr
Damien George2617eeb2014-05-25 22:27:57 +01001747 return MP_OBJ_NEW_QSTR(qstr_from_strn(data, len));
Damien George5fa93b62014-01-22 14:35:10 +00001748 } else {
Damien Georgef600a6a2014-05-25 22:34:34 +01001749 qstr q = qstr_find_strn(data, len);
1750 if (q != MP_QSTR_NULL) {
1751 // qstr with this data already exists
1752 return MP_OBJ_NEW_QSTR(q);
1753 } else {
1754 // no existing qstr, don't make one
1755 return mp_obj_new_str_of_type(&mp_type_str, (const byte*)data, len);
1756 }
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02001757 }
Damien George5fa93b62014-01-22 14:35:10 +00001758}
1759
Paul Sokolovskyb4efac12014-06-08 01:13:35 +03001760mp_obj_t mp_obj_str_intern(mp_obj_t str) {
1761 GET_STR_DATA_LEN(str, data, len);
1762 return MP_OBJ_NEW_QSTR(qstr_from_strn((const char*)data, len));
1763}
1764
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001765mp_obj_t mp_obj_new_bytes(const byte* data, uint len) {
Damien Georgef600a6a2014-05-25 22:34:34 +01001766 return mp_obj_new_str_of_type(&mp_type_bytes, data, len);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001767}
1768
Damien George5fa93b62014-01-22 14:35:10 +00001769bool mp_obj_str_equal(mp_obj_t s1, mp_obj_t s2) {
1770 if (MP_OBJ_IS_QSTR(s1) && MP_OBJ_IS_QSTR(s2)) {
1771 return s1 == s2;
1772 } else {
1773 GET_STR_HASH(s1, h1);
1774 GET_STR_HASH(s2, h2);
Paul Sokolovsky59e269c2014-04-14 01:43:01 +03001775 // If any of hashes is 0, it means it's not valid
1776 if (h1 != 0 && h2 != 0 && h1 != h2) {
Damien George5fa93b62014-01-22 14:35:10 +00001777 return false;
1778 }
1779 GET_STR_DATA_LEN(s1, d1, l1);
1780 GET_STR_DATA_LEN(s2, d2, l2);
1781 if (l1 != l2) {
1782 return false;
1783 }
Damien George1e708fe2014-01-23 18:27:51 +00001784 return memcmp(d1, d2, l1) == 0;
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02001785 }
Damien George5fa93b62014-01-22 14:35:10 +00001786}
1787
Damien Georgedeed0872014-04-06 11:11:15 +01001788STATIC void bad_implicit_conversion(mp_obj_t self_in) {
Damien Georgeea13f402014-04-05 18:32:08 +01001789 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, "Can't convert '%s' object to str implicitly", mp_obj_get_type_str(self_in)));
Damien Georgeb829b5c2014-01-25 13:51:19 +00001790}
1791
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +03001792STATIC void arg_type_mixup() {
1793 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "Can't mix str and bytes arguments"));
1794}
1795
Damien George5fa93b62014-01-22 14:35:10 +00001796uint mp_obj_str_get_hash(mp_obj_t self_in) {
Paul Sokolovskyf130ca12014-04-13 05:41:00 +03001797 // TODO: This has too big overhead for hash accessor
1798 if (MP_OBJ_IS_STR(self_in) || MP_OBJ_IS_TYPE(self_in, &mp_type_bytes)) {
Damien George5fa93b62014-01-22 14:35:10 +00001799 GET_STR_HASH(self_in, h);
1800 return h;
1801 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001802 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001803 }
1804}
1805
1806uint mp_obj_str_get_len(mp_obj_t self_in) {
Damien Georgeee014112014-04-15 23:10:00 +01001807 // TODO This has a double check for the type, one in obj.c and one here
1808 if (MP_OBJ_IS_STR(self_in) || MP_OBJ_IS_TYPE(self_in, &mp_type_bytes)) {
Damien George5fa93b62014-01-22 14:35:10 +00001809 GET_STR_LEN(self_in, l);
1810 return l;
1811 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001812 bad_implicit_conversion(self_in);
1813 }
1814}
1815
1816// use this if you will anyway convert the string to a qstr
1817// will be more efficient for the case where it's already a qstr
1818qstr mp_obj_str_get_qstr(mp_obj_t self_in) {
1819 if (MP_OBJ_IS_QSTR(self_in)) {
1820 return MP_OBJ_QSTR_VALUE(self_in);
Damien George3e1a5c12014-03-29 13:43:38 +00001821 } else if (MP_OBJ_IS_TYPE(self_in, &mp_type_str)) {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001822 mp_obj_str_t *self = self_in;
1823 return qstr_from_strn((char*)self->data, self->len);
1824 } else {
1825 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001826 }
1827}
1828
1829// only use this function if you need the str data to be zero terminated
1830// at the moment all strings are zero terminated to help with C ASCIIZ compatibility
1831const char *mp_obj_str_get_str(mp_obj_t self_in) {
1832 if (MP_OBJ_IS_STR(self_in)) {
1833 GET_STR_DATA_LEN(self_in, s, l);
1834 (void)l; // len unused
1835 return (const char*)s;
1836 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001837 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001838 }
1839}
1840
Damien George698ec212014-02-08 18:17:23 +00001841const char *mp_obj_str_get_data(mp_obj_t self_in, uint *len) {
Paul Sokolovskyeea01182014-05-11 13:51:24 +03001842 if (is_str_or_bytes(self_in)) {
Damien George5fa93b62014-01-22 14:35:10 +00001843 GET_STR_DATA_LEN(self_in, s, l);
1844 *len = l;
Damien George698ec212014-02-08 18:17:23 +00001845 return (const char*)s;
Damien George5fa93b62014-01-22 14:35:10 +00001846 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001847 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001848 }
Damiend99b0522013-12-21 18:17:45 +00001849}
xyb8cfc9f02014-01-05 18:47:51 +08001850
1851/******************************************************************************/
1852/* str iterator */
1853
1854typedef struct _mp_obj_str_it_t {
1855 mp_obj_base_t base;
Damien George5fa93b62014-01-22 14:35:10 +00001856 mp_obj_t str;
xyb8cfc9f02014-01-05 18:47:51 +08001857 machine_uint_t cur;
1858} mp_obj_str_it_t;
1859
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001860STATIC mp_obj_t str_it_iternext(mp_obj_t self_in) {
xyb8cfc9f02014-01-05 18:47:51 +08001861 mp_obj_str_it_t *self = self_in;
Damien George5fa93b62014-01-22 14:35:10 +00001862 GET_STR_DATA_LEN(self->str, str, len);
1863 if (self->cur < len) {
Damien George2617eeb2014-05-25 22:27:57 +01001864 mp_obj_t o_out = mp_obj_new_str((const char*)str + self->cur, 1, true);
xyb8cfc9f02014-01-05 18:47:51 +08001865 self->cur += 1;
1866 return o_out;
1867 } else {
Damien Georgeea8d06c2014-04-17 23:19:36 +01001868 return MP_OBJ_STOP_ITERATION;
xyb8cfc9f02014-01-05 18:47:51 +08001869 }
1870}
1871
Damien George3e1a5c12014-03-29 13:43:38 +00001872STATIC const mp_obj_type_t mp_type_str_it = {
Damien Georgec5966122014-02-15 16:10:44 +00001873 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001874 .name = MP_QSTR_iterator,
Paul Sokolovskyf7eaf602014-03-30 22:00:12 +03001875 .getiter = mp_identity,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001876 .iternext = str_it_iternext,
xyb8cfc9f02014-01-05 18:47:51 +08001877};
1878
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001879STATIC mp_obj_t bytes_it_iternext(mp_obj_t self_in) {
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001880 mp_obj_str_it_t *self = self_in;
1881 GET_STR_DATA_LEN(self->str, str, len);
1882 if (self->cur < len) {
Damien George7c9c6672014-01-25 00:17:36 +00001883 mp_obj_t o_out = MP_OBJ_NEW_SMALL_INT((mp_small_int_t)str[self->cur]);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001884 self->cur += 1;
1885 return o_out;
1886 } else {
Damien Georgeea8d06c2014-04-17 23:19:36 +01001887 return MP_OBJ_STOP_ITERATION;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001888 }
1889}
1890
Damien George3e1a5c12014-03-29 13:43:38 +00001891STATIC const mp_obj_type_t mp_type_bytes_it = {
Damien Georgec5966122014-02-15 16:10:44 +00001892 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001893 .name = MP_QSTR_iterator,
Paul Sokolovskyf7eaf602014-03-30 22:00:12 +03001894 .getiter = mp_identity,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001895 .iternext = bytes_it_iternext,
1896};
1897
1898mp_obj_t mp_obj_new_str_iterator(mp_obj_t str) {
xyb8cfc9f02014-01-05 18:47:51 +08001899 mp_obj_str_it_t *o = m_new_obj(mp_obj_str_it_t);
Damien George3e1a5c12014-03-29 13:43:38 +00001900 o->base.type = &mp_type_str_it;
xyb8cfc9f02014-01-05 18:47:51 +08001901 o->str = str;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001902 o->cur = 0;
1903 return o;
1904}
1905
1906mp_obj_t mp_obj_new_bytes_iterator(mp_obj_t str) {
1907 mp_obj_str_it_t *o = m_new_obj(mp_obj_str_it_t);
Damien George3e1a5c12014-03-29 13:43:38 +00001908 o->base.type = &mp_type_bytes_it;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001909 o->str = str;
1910 o->cur = 0;
xyb8cfc9f02014-01-05 18:47:51 +08001911 return o;
1912}