blob: 6656090c84f05db403ba96d7065d478cbbfdeb14 [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
Damien George5fa93b62014-01-22 14:35:10 +000046// use this macro to extract the string hash
47#define GET_STR_HASH(str_obj_in, str_hash) uint str_hash; if (MP_OBJ_IS_QSTR(str_obj_in)) { str_hash = qstr_hash(MP_OBJ_QSTR_VALUE(str_obj_in)); } else { str_hash = ((mp_obj_str_t*)str_obj_in)->hash; }
48
49// use this macro to extract the string length
50#define GET_STR_LEN(str_obj_in, str_len) uint str_len; if (MP_OBJ_IS_QSTR(str_obj_in)) { str_len = qstr_len(MP_OBJ_QSTR_VALUE(str_obj_in)); } else { str_len = ((mp_obj_str_t*)str_obj_in)->len; }
51
52// use this macro to extract the string data and length
53#define GET_STR_DATA_LEN(str_obj_in, str_data, str_len) const byte *str_data; uint str_len; if (MP_OBJ_IS_QSTR(str_obj_in)) { str_data = qstr_data(MP_OBJ_QSTR_VALUE(str_obj_in), &str_len); } else { str_len = ((mp_obj_str_t*)str_obj_in)->len; str_data = ((mp_obj_str_t*)str_obj_in)->data; }
54
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +020055STATIC mp_obj_t mp_obj_new_str_iterator(mp_obj_t str);
56STATIC mp_obj_t mp_obj_new_bytes_iterator(mp_obj_t str);
Paul Sokolovskye9085912014-04-30 05:35:18 +030057STATIC NORETURN void bad_implicit_conversion(mp_obj_t self_in);
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +030058STATIC NORETURN void arg_type_mixup();
59
60STATIC bool is_str_or_bytes(mp_obj_t o) {
61 return MP_OBJ_IS_STR(o) || MP_OBJ_IS_TYPE(o, &mp_type_bytes);
62}
xyb8cfc9f02014-01-05 18:47:51 +080063
64/******************************************************************************/
65/* str */
66
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020067void mp_str_print_quoted(void (*print)(void *env, const char *fmt, ...), void *env, const byte *str_data, uint str_len) {
68 // this escapes characters, but it will be very slow to print (calling print many times)
69 bool has_single_quote = false;
70 bool has_double_quote = false;
Chris Angelico48674132014-06-04 03:26:40 +100071 for (const byte *s = str_data, *top = str_data + str_len; !has_double_quote && s < top; s++) {
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020072 if (*s == '\'') {
73 has_single_quote = true;
74 } else if (*s == '"') {
75 has_double_quote = true;
76 }
77 }
78 int quote_char = '\'';
79 if (has_single_quote && !has_double_quote) {
80 quote_char = '"';
81 }
82 print(env, "%c", quote_char);
83 for (const byte *s = str_data, *top = str_data + str_len; s < top; s++) {
84 if (*s == quote_char) {
85 print(env, "\\%c", quote_char);
86 } else if (*s == '\\') {
87 print(env, "\\\\");
88 } else if (32 <= *s && *s <= 126) {
89 print(env, "%c", *s);
90 } else if (*s == '\n') {
91 print(env, "\\n");
Andrew Scheller12968fb2014-04-08 02:42:50 +010092 } else if (*s == '\r') {
93 print(env, "\\r");
94 } else if (*s == '\t') {
95 print(env, "\\t");
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020096 } else {
97 print(env, "\\x%02x", *s);
98 }
99 }
100 print(env, "%c", quote_char);
101}
102
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200103STATIC 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 +0000104 GET_STR_DATA_LEN(self_in, str_data, str_len);
Damien George3e1a5c12014-03-29 13:43:38 +0000105 bool is_bytes = MP_OBJ_IS_TYPE(self_in, &mp_type_bytes);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +0200106 if (kind == PRINT_STR && !is_bytes) {
Damien George5fa93b62014-01-22 14:35:10 +0000107 print(env, "%.*s", str_len, str_data);
Paul Sokolovsky76d982e2014-01-13 19:19:16 +0200108 } else {
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +0200109 if (is_bytes) {
110 print(env, "b");
111 }
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +0200112 mp_str_print_quoted(print, env, str_data, str_len);
Paul Sokolovsky76d982e2014-01-13 19:19:16 +0200113 }
Damiend99b0522013-12-21 18:17:45 +0000114}
115
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200116STATIC 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 +0300117#if MICROPY_CPYTHON_COMPAT
118 if (n_kw != 0) {
119 mp_arg_error_unimpl_kw();
120 }
121#endif
122
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200123 switch (n_args) {
124 case 0:
125 return MP_OBJ_NEW_QSTR(MP_QSTR_);
126
127 case 1:
128 {
129 vstr_t *vstr = vstr_new();
130 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, vstr, args[0], PRINT_STR);
Damien George2617eeb2014-05-25 22:27:57 +0100131 mp_obj_t s = mp_obj_new_str(vstr->buf, vstr->len, false);
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200132 vstr_free(vstr);
133 return s;
134 }
135
136 case 2:
137 case 3:
138 {
139 // TODO: validate 2nd/3rd args
Damien George3e1a5c12014-03-29 13:43:38 +0000140 if (!MP_OBJ_IS_TYPE(args[0], &mp_type_bytes)) {
Damien Georgeea13f402014-04-05 18:32:08 +0100141 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "bytes expected"));
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200142 }
143 GET_STR_DATA_LEN(args[0], str_data, str_len);
144 GET_STR_HASH(args[0], str_hash);
Damien Georgef600a6a2014-05-25 22:34:34 +0100145 mp_obj_str_t *o = mp_obj_new_str_of_type(&mp_type_str, NULL, str_len);
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200146 o->data = str_data;
147 o->hash = str_hash;
148 return o;
149 }
150
151 default:
Damien Georgeea13f402014-04-05 18:32:08 +0100152 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "str takes at most 3 arguments"));
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200153 }
154}
155
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200156STATIC mp_obj_t bytes_make_new(mp_obj_t type_in, uint n_args, uint n_kw, const mp_obj_t *args) {
157 if (n_args == 0) {
158 return mp_const_empty_bytes;
159 }
160
Paul Sokolovskyb473d0a2014-05-06 19:30:30 +0300161#if MICROPY_CPYTHON_COMPAT
162 if (n_kw != 0) {
163 mp_arg_error_unimpl_kw();
164 }
165#endif
166
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200167 if (MP_OBJ_IS_STR(args[0])) {
168 if (n_args < 2 || n_args > 3) {
169 goto wrong_args;
170 }
171 GET_STR_DATA_LEN(args[0], str_data, str_len);
172 GET_STR_HASH(args[0], str_hash);
Damien Georgef600a6a2014-05-25 22:34:34 +0100173 mp_obj_str_t *o = mp_obj_new_str_of_type(&mp_type_bytes, NULL, str_len);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200174 o->data = str_data;
175 o->hash = str_hash;
176 return o;
177 }
178
179 if (n_args > 1) {
180 goto wrong_args;
181 }
182
183 if (MP_OBJ_IS_SMALL_INT(args[0])) {
184 uint len = MP_OBJ_SMALL_INT_VALUE(args[0]);
185 byte *data;
186
Damien George3e1a5c12014-03-29 13:43:38 +0000187 mp_obj_t o = mp_obj_str_builder_start(&mp_type_bytes, len, &data);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200188 memset(data, 0, len);
189 return mp_obj_str_builder_end(o);
190 }
191
192 int len;
193 byte *data;
194 vstr_t *vstr = NULL;
195 mp_obj_t o = NULL;
196 // Try to create array of exact len if initializer len is known
197 mp_obj_t len_in = mp_obj_len_maybe(args[0]);
198 if (len_in == MP_OBJ_NULL) {
199 len = -1;
200 vstr = vstr_new();
201 } else {
202 len = MP_OBJ_SMALL_INT_VALUE(len_in);
Damien George3e1a5c12014-03-29 13:43:38 +0000203 o = mp_obj_str_builder_start(&mp_type_bytes, len, &data);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200204 }
205
Damien Georged17926d2014-03-30 13:35:08 +0100206 mp_obj_t iterable = mp_getiter(args[0]);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200207 mp_obj_t item;
Damien Georgeea8d06c2014-04-17 23:19:36 +0100208 while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200209 if (len == -1) {
210 vstr_add_char(vstr, MP_OBJ_SMALL_INT_VALUE(item));
211 } else {
212 *data++ = MP_OBJ_SMALL_INT_VALUE(item);
213 }
214 }
215
216 if (len == -1) {
217 vstr_shrink(vstr);
218 // TODO: Optimize, borrow buffer from vstr
219 len = vstr_len(vstr);
Damien George3e1a5c12014-03-29 13:43:38 +0000220 o = mp_obj_str_builder_start(&mp_type_bytes, len, &data);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200221 memcpy(data, vstr_str(vstr), len);
222 vstr_free(vstr);
223 }
224
225 return mp_obj_str_builder_end(o);
226
227wrong_args:
Damien Georgeea13f402014-04-05 18:32:08 +0100228 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "wrong number of arguments"));
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200229}
230
Damien George55baff42014-01-21 21:40:13 +0000231// like strstr but with specified length and allows \0 bytes
232// TODO replace with something more efficient/standard
xbe17a5a832014-03-23 23:31:58 -0700233STATIC 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 +0000234 if (hlen >= nlen) {
xbe17a5a832014-03-23 23:31:58 -0700235 machine_uint_t str_index, str_index_end;
236 if (direction > 0) {
237 str_index = 0;
238 str_index_end = hlen - nlen;
239 } else {
240 str_index = hlen - nlen;
241 str_index_end = 0;
242 }
243 for (;;) {
244 if (memcmp(&haystack[str_index], needle, nlen) == 0) {
245 //found
246 return haystack + str_index;
Damien George55baff42014-01-21 21:40:13 +0000247 }
xbe17a5a832014-03-23 23:31:58 -0700248 if (str_index == str_index_end) {
249 //not found
250 break;
Damien George55baff42014-01-21 21:40:13 +0000251 }
xbe17a5a832014-03-23 23:31:58 -0700252 str_index += direction;
Damien George55baff42014-01-21 21:40:13 +0000253 }
254 }
255 return NULL;
256}
257
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200258STATIC mp_obj_t str_binary_op(int op, mp_obj_t lhs_in, mp_obj_t rhs_in) {
Damien George5fa93b62014-01-22 14:35:10 +0000259 GET_STR_DATA_LEN(lhs_in, lhs_data, lhs_len);
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300260 mp_obj_type_t *lhs_type = mp_obj_get_type(lhs_in);
261 mp_obj_type_t *rhs_type = mp_obj_get_type(rhs_in);
Damiend99b0522013-12-21 18:17:45 +0000262 switch (op) {
Damien Georged17926d2014-03-30 13:35:08 +0100263 case MP_BINARY_OP_ADD:
264 case MP_BINARY_OP_INPLACE_ADD:
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300265 if (lhs_type == rhs_type) {
266 // add 2 strings or bytes
Damien George5fa93b62014-01-22 14:35:10 +0000267
268 GET_STR_DATA_LEN(rhs_in, rhs_data, rhs_len);
Damien George55baff42014-01-21 21:40:13 +0000269 int alloc_len = lhs_len + rhs_len;
Damien George5fa93b62014-01-22 14:35:10 +0000270
271 /* code for making qstr
Damien George55baff42014-01-21 21:40:13 +0000272 byte *q_ptr;
273 byte *val = qstr_build_start(alloc_len, &q_ptr);
274 memcpy(val, lhs_data, lhs_len);
275 memcpy(val + lhs_len, rhs_data, rhs_len);
Damien George5fa93b62014-01-22 14:35:10 +0000276 return MP_OBJ_NEW_QSTR(qstr_build_end(q_ptr));
277 */
278
279 // code for non-qstr
280 byte *data;
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300281 mp_obj_t s = mp_obj_str_builder_start(lhs_type, alloc_len, &data);
Damien George5fa93b62014-01-22 14:35:10 +0000282 memcpy(data, lhs_data, lhs_len);
283 memcpy(data + lhs_len, rhs_data, rhs_len);
284 return mp_obj_str_builder_end(s);
Damiend99b0522013-12-21 18:17:45 +0000285 }
286 break;
Damien George5fa93b62014-01-22 14:35:10 +0000287
Damien Georged17926d2014-03-30 13:35:08 +0100288 case MP_BINARY_OP_IN:
John R. Lentonc1bef212014-01-11 12:39:33 +0000289 /* NOTE `a in b` is `b.__contains__(a)` */
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300290 if (lhs_type == rhs_type) {
Damien George5fa93b62014-01-22 14:35:10 +0000291 GET_STR_DATA_LEN(rhs_in, rhs_data, rhs_len);
xbe17a5a832014-03-23 23:31:58 -0700292 return MP_BOOL(find_subbytes(lhs_data, lhs_len, rhs_data, rhs_len, 1) != NULL);
John R. Lentonc1bef212014-01-11 12:39:33 +0000293 }
294 break;
Damien George5fa93b62014-01-22 14:35:10 +0000295
Damien Georged0a5bf32014-05-10 13:55:11 +0100296 case MP_BINARY_OP_MULTIPLY: {
Paul Sokolovsky545591a2014-01-21 00:27:33 +0200297 if (!MP_OBJ_IS_SMALL_INT(rhs_in)) {
Damien George6ac5dce2014-05-21 19:42:43 +0100298 return MP_OBJ_NULL; // op not supported
Paul Sokolovsky545591a2014-01-21 00:27:33 +0200299 }
300 int n = MP_OBJ_SMALL_INT_VALUE(rhs_in);
Damien George5fa93b62014-01-22 14:35:10 +0000301 byte *data;
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300302 mp_obj_t s = mp_obj_str_builder_start(lhs_type, lhs_len * n, &data);
Damien George5fa93b62014-01-22 14:35:10 +0000303 mp_seq_multiply(lhs_data, sizeof(*lhs_data), lhs_len, n, data);
304 return mp_obj_str_builder_end(s);
Paul Sokolovsky545591a2014-01-21 00:27:33 +0200305 }
Paul Sokolovsky87e85b72014-02-02 08:24:07 +0200306
Paul Sokolovsky4db727a2014-03-31 21:18:28 +0300307 case MP_BINARY_OP_MODULO: {
308 mp_obj_t *args;
309 uint n_args;
Paul Sokolovsky75ce9252014-06-05 20:02:15 +0300310 mp_obj_t dict = MP_OBJ_NULL;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +0300311 if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_tuple)) {
312 // TODO: Support tuple subclasses?
313 mp_obj_tuple_get(rhs_in, &n_args, &args);
Paul Sokolovsky75ce9252014-06-05 20:02:15 +0300314 } else if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_dict)) {
315 args = NULL;
316 n_args = 0;
317 dict = rhs_in;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +0300318 } else {
319 args = &rhs_in;
320 n_args = 1;
321 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +0300322 return str_modulo_format(lhs_in, n_args, args, dict);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +0300323 }
324
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300325 //case MP_BINARY_OP_NOT_EQUAL: // This is never passed here
326 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 +0100327 case MP_BINARY_OP_LESS:
328 case MP_BINARY_OP_LESS_EQUAL:
329 case MP_BINARY_OP_MORE:
330 case MP_BINARY_OP_MORE_EQUAL:
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300331 if (lhs_type == rhs_type) {
Paul Sokolovsky87e85b72014-02-02 08:24:07 +0200332 GET_STR_DATA_LEN(rhs_in, rhs_data, rhs_len);
333 return MP_BOOL(mp_seq_cmp_bytes(op, lhs_data, lhs_len, rhs_data, rhs_len));
334 }
Paul Sokolovsky70328e42014-05-15 20:58:40 +0300335 if (lhs_type == &mp_type_bytes) {
336 mp_buffer_info_t bufinfo;
337 if (!mp_get_buffer(rhs_in, &bufinfo, MP_BUFFER_READ)) {
338 goto uncomparable;
339 }
340 return MP_BOOL(mp_seq_cmp_bytes(op, lhs_data, lhs_len, bufinfo.buf, bufinfo.len));
341 }
342uncomparable:
343 if (op == MP_BINARY_OP_EQUAL) {
344 return mp_const_false;
345 }
Damiend99b0522013-12-21 18:17:45 +0000346 }
347
Damien George6ac5dce2014-05-21 19:42:43 +0100348 return MP_OBJ_NULL; // op not supported
Damiend99b0522013-12-21 18:17:45 +0000349}
350
Damien George729f7b42014-04-17 22:10:53 +0100351STATIC 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 +0300352 mp_obj_type_t *type = mp_obj_get_type(self_in);
Damien George729f7b42014-04-17 22:10:53 +0100353 GET_STR_DATA_LEN(self_in, self_data, self_len);
354 if (value == MP_OBJ_SENTINEL) {
355 // load
Damien Georgefb510b32014-06-01 13:32:54 +0100356#if MICROPY_PY_BUILTINS_SLICE
Damien George729f7b42014-04-17 22:10:53 +0100357 if (MP_OBJ_IS_TYPE(index, &mp_type_slice)) {
Paul Sokolovskyde4b9322014-05-25 21:21:57 +0300358 mp_bound_slice_t slice;
359 if (!mp_seq_get_fast_slice_indexes(self_len, index, &slice)) {
Paul Sokolovsky5fd5af92014-05-25 22:12:56 +0300360 nlr_raise(mp_obj_new_exception_msg(&mp_type_NotImplementedError,
Damien George11de8392014-06-05 18:57:38 +0100361 "only slices with step=1 (aka None) are supported"));
Damien George729f7b42014-04-17 22:10:53 +0100362 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100363 return mp_obj_new_str_of_type(type, self_data + slice.start, slice.stop - slice.start);
Damien George729f7b42014-04-17 22:10:53 +0100364 }
365#endif
Damien George729f7b42014-04-17 22:10:53 +0100366 uint index_val = mp_get_index(type, self_len, index, false);
367 if (type == &mp_type_bytes) {
368 return MP_OBJ_NEW_SMALL_INT((mp_small_int_t)self_data[index_val]);
369 } else {
Damien George2617eeb2014-05-25 22:27:57 +0100370 return mp_obj_new_str((char*)self_data + index_val, 1, true);
Damien George729f7b42014-04-17 22:10:53 +0100371 }
372 } else {
Damien George6ac5dce2014-05-21 19:42:43 +0100373 return MP_OBJ_NULL; // op not supported
Damien George729f7b42014-04-17 22:10:53 +0100374 }
375}
376
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200377STATIC mp_obj_t str_join(mp_obj_t self_in, mp_obj_t arg) {
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300378 assert(is_str_or_bytes(self_in));
379 const mp_obj_type_t *self_type = mp_obj_get_type(self_in);
Damiend99b0522013-12-21 18:17:45 +0000380
Damien Georgefe8fb912014-01-02 16:36:09 +0000381 // get separation string
Damien George5fa93b62014-01-22 14:35:10 +0000382 GET_STR_DATA_LEN(self_in, sep_str, sep_len);
Damien Georgefe8fb912014-01-02 16:36:09 +0000383
384 // process args
Damiend99b0522013-12-21 18:17:45 +0000385 uint seq_len;
386 mp_obj_t *seq_items;
Damien George07ddab52014-03-29 13:15:08 +0000387 if (MP_OBJ_IS_TYPE(arg, &mp_type_tuple)) {
Damiend99b0522013-12-21 18:17:45 +0000388 mp_obj_tuple_get(arg, &seq_len, &seq_items);
Damiend99b0522013-12-21 18:17:45 +0000389 } else {
Damien Georgea157e4c2014-04-09 19:17:53 +0100390 if (!MP_OBJ_IS_TYPE(arg, &mp_type_list)) {
391 // arg is not a list, try to convert it to one
Paul Sokolovsky881d9af2014-04-10 01:42:40 +0300392 // TODO: Try to optimize?
Damien Georgea157e4c2014-04-09 19:17:53 +0100393 arg = mp_type_list.make_new((mp_obj_t)&mp_type_list, 1, 0, &arg);
394 }
395 mp_obj_list_get(arg, &seq_len, &seq_items);
Damiend99b0522013-12-21 18:17:45 +0000396 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000397
398 // count required length
399 int required_len = 0;
Damiend99b0522013-12-21 18:17:45 +0000400 for (int i = 0; i < seq_len; i++) {
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300401 if (mp_obj_get_type(seq_items[i]) != self_type) {
402 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
403 "join expects a list of str/bytes objects consistent with self object"));
Damiend99b0522013-12-21 18:17:45 +0000404 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000405 if (i > 0) {
406 required_len += sep_len;
407 }
Damien George5fa93b62014-01-22 14:35:10 +0000408 GET_STR_LEN(seq_items[i], l);
409 required_len += l;
Damiend99b0522013-12-21 18:17:45 +0000410 }
411
412 // make joined string
Damien George5fa93b62014-01-22 14:35:10 +0000413 byte *data;
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300414 mp_obj_t joined_str = mp_obj_str_builder_start(self_type, required_len, &data);
Damiend99b0522013-12-21 18:17:45 +0000415 for (int i = 0; i < seq_len; i++) {
Damiend99b0522013-12-21 18:17:45 +0000416 if (i > 0) {
Damien George5fa93b62014-01-22 14:35:10 +0000417 memcpy(data, sep_str, sep_len);
418 data += sep_len;
Damiend99b0522013-12-21 18:17:45 +0000419 }
Damien George5fa93b62014-01-22 14:35:10 +0000420 GET_STR_DATA_LEN(seq_items[i], s, l);
421 memcpy(data, s, l);
422 data += l;
Damiend99b0522013-12-21 18:17:45 +0000423 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000424
425 // return joined string
Damien George5fa93b62014-01-22 14:35:10 +0000426 return mp_obj_str_builder_end(joined_str);
Damiend99b0522013-12-21 18:17:45 +0000427}
428
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200429#define is_ws(c) ((c) == ' ' || (c) == '\t')
430
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200431STATIC mp_obj_t str_split(uint n_args, const mp_obj_t *args) {
Paul Sokolovskybfb88192014-05-11 21:17:28 +0300432 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Damien Georgedeed0872014-04-06 11:11:15 +0100433 machine_int_t splits = -1;
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200434 mp_obj_t sep = mp_const_none;
435 if (n_args > 1) {
436 sep = args[1];
437 if (n_args > 2) {
Damien Georgedeed0872014-04-06 11:11:15 +0100438 splits = mp_obj_get_int(args[2]);
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200439 }
440 }
Damien Georgedeed0872014-04-06 11:11:15 +0100441
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200442 mp_obj_t res = mp_obj_new_list(0, NULL);
Damien George5fa93b62014-01-22 14:35:10 +0000443 GET_STR_DATA_LEN(args[0], s, len);
444 const byte *top = s + len;
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200445
Damien Georgedeed0872014-04-06 11:11:15 +0100446 if (sep == mp_const_none) {
447 // sep not given, so separate on whitespace
448
449 // Initial whitespace is not counted as split, so we pre-do it
Damien George5fa93b62014-01-22 14:35:10 +0000450 while (s < top && is_ws(*s)) s++;
Damien Georgedeed0872014-04-06 11:11:15 +0100451 while (s < top && splits != 0) {
452 const byte *start = s;
453 while (s < top && !is_ws(*s)) s++;
Damien Georgef600a6a2014-05-25 22:34:34 +0100454 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, s - start));
Damien Georgedeed0872014-04-06 11:11:15 +0100455 if (s >= top) {
456 break;
457 }
458 while (s < top && is_ws(*s)) s++;
459 if (splits > 0) {
460 splits--;
461 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200462 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200463
Damien Georgedeed0872014-04-06 11:11:15 +0100464 if (s < top) {
Damien Georgef600a6a2014-05-25 22:34:34 +0100465 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, s, top - s));
Damien Georgedeed0872014-04-06 11:11:15 +0100466 }
467
468 } else {
469 // sep given
470
471 uint sep_len;
472 const char *sep_str = mp_obj_str_get_data(sep, &sep_len);
473
474 if (sep_len == 0) {
475 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
476 }
477
478 for (;;) {
479 const byte *start = s;
480 for (;;) {
481 if (splits == 0 || s + sep_len > top) {
482 s = top;
483 break;
484 } else if (memcmp(s, sep_str, sep_len) == 0) {
485 break;
486 }
487 s++;
488 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100489 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, s - start));
Damien Georgedeed0872014-04-06 11:11:15 +0100490 if (s >= top) {
491 break;
492 }
493 s += sep_len;
494 if (splits > 0) {
495 splits--;
496 }
497 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200498 }
499
500 return res;
501}
502
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300503STATIC mp_obj_t str_rsplit(uint n_args, const mp_obj_t *args) {
504 if (n_args < 3) {
505 // If we don't have split limit, it doesn't matter from which side
506 // we split.
507 return str_split(n_args, args);
508 }
509 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
510 mp_obj_t sep = args[1];
511 GET_STR_DATA_LEN(args[0], s, len);
512
513 machine_int_t splits = mp_obj_get_int(args[2]);
514 machine_int_t org_splits = splits;
515 // Preallocate list to the max expected # of elements, as we
516 // will fill it from the end.
517 mp_obj_list_t *res = mp_obj_new_list(splits + 1, NULL);
518 int idx = splits;
519
520 if (sep == mp_const_none) {
Chris Angelico9ab8ab22014-06-04 05:04:23 +1000521 assert(!"TODO: rsplit(None,n) not implemented");
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300522 } else {
523 uint sep_len;
524 const char *sep_str = mp_obj_str_get_data(sep, &sep_len);
525
526 if (sep_len == 0) {
527 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
528 }
529
530 const byte *beg = s;
531 const byte *last = s + len;
532 for (;;) {
533 s = last - sep_len;
534 for (;;) {
535 if (splits == 0 || s < beg) {
536 break;
537 } else if (memcmp(s, sep_str, sep_len) == 0) {
538 break;
539 }
540 s--;
541 }
542 if (s < beg || splits == 0) {
Damien Georgef600a6a2014-05-25 22:34:34 +0100543 res->items[idx] = mp_obj_new_str_of_type(self_type, beg, last - beg);
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300544 break;
545 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100546 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 +0300547 last = s;
548 if (splits > 0) {
549 splits--;
550 }
551 }
552 if (idx != 0) {
553 // We split less parts than split limit, now go cleanup surplus
554 int used = org_splits + 1 - idx;
555 memcpy(res->items, &res->items[idx], used * sizeof(mp_obj_t));
556 mp_seq_clear(res->items, used, res->alloc, sizeof(*res->items));
557 res->len = used;
558 }
559 }
560
561 return res;
562}
563
564
xbe3d9a39e2014-04-08 11:42:19 -0700565STATIC mp_obj_t str_finder(uint n_args, const mp_obj_t *args, machine_int_t direction, bool is_index) {
John R. Lentone8204912014-01-12 21:53:52 +0000566 assert(2 <= n_args && n_args <= 4);
Damien George5fa93b62014-01-22 14:35:10 +0000567 assert(MP_OBJ_IS_STR(args[0]));
568 assert(MP_OBJ_IS_STR(args[1]));
John R. Lentone8204912014-01-12 21:53:52 +0000569
Damien George5fa93b62014-01-22 14:35:10 +0000570 GET_STR_DATA_LEN(args[0], haystack, haystack_len);
571 GET_STR_DATA_LEN(args[1], needle, needle_len);
John R. Lentone8204912014-01-12 21:53:52 +0000572
xbec5538882014-03-16 17:58:35 -0700573 machine_uint_t start = 0;
574 machine_uint_t end = haystack_len;
John R. Lentone8204912014-01-12 21:53:52 +0000575 if (n_args >= 3 && args[2] != mp_const_none) {
Damien George3e1a5c12014-03-29 13:43:38 +0000576 start = mp_get_index(&mp_type_str, haystack_len, args[2], true);
John R. Lentone8204912014-01-12 21:53:52 +0000577 }
578 if (n_args >= 4 && args[3] != mp_const_none) {
Damien George3e1a5c12014-03-29 13:43:38 +0000579 end = mp_get_index(&mp_type_str, haystack_len, args[3], true);
John R. Lentone8204912014-01-12 21:53:52 +0000580 }
581
xbe17a5a832014-03-23 23:31:58 -0700582 const byte *p = find_subbytes(haystack + start, end - start, needle, needle_len, direction);
Damien George23005372014-01-13 19:39:01 +0000583 if (p == NULL) {
584 // not found
xbe3d9a39e2014-04-08 11:42:19 -0700585 if (is_index) {
586 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "substring not found"));
587 } else {
588 return MP_OBJ_NEW_SMALL_INT(-1);
589 }
Damien George23005372014-01-13 19:39:01 +0000590 } else {
591 // found
xbe17a5a832014-03-23 23:31:58 -0700592 return MP_OBJ_NEW_SMALL_INT(p - haystack);
John R. Lentone8204912014-01-12 21:53:52 +0000593 }
John R. Lentone8204912014-01-12 21:53:52 +0000594}
595
xbe17a5a832014-03-23 23:31:58 -0700596STATIC mp_obj_t str_find(uint n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700597 return str_finder(n_args, args, 1, false);
xbe17a5a832014-03-23 23:31:58 -0700598}
599
600STATIC mp_obj_t str_rfind(uint n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700601 return str_finder(n_args, args, -1, false);
602}
603
604STATIC mp_obj_t str_index(uint n_args, const mp_obj_t *args) {
605 return str_finder(n_args, args, 1, true);
606}
607
608STATIC mp_obj_t str_rindex(uint n_args, const mp_obj_t *args) {
609 return str_finder(n_args, args, -1, true);
xbe17a5a832014-03-23 23:31:58 -0700610}
611
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200612// TODO: (Much) more variety in args
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300613STATIC mp_obj_t str_startswith(uint n_args, const mp_obj_t *args) {
614 GET_STR_DATA_LEN(args[0], str, str_len);
615 GET_STR_DATA_LEN(args[1], prefix, prefix_len);
616 uint index_val = 0;
617 if (n_args > 2) {
618 index_val = mp_get_index(&mp_type_str, str_len, args[2], true);
619 }
620 if (prefix_len + index_val > str_len) {
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200621 return mp_const_false;
622 }
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300623 return MP_BOOL(memcmp(str + index_val, prefix, prefix_len) == 0);
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200624}
625
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +0300626STATIC mp_obj_t str_endswith(uint n_args, const mp_obj_t *args) {
627 GET_STR_DATA_LEN(args[0], str, str_len);
628 GET_STR_DATA_LEN(args[1], suffix, suffix_len);
629 assert(n_args == 2);
630
631 if (suffix_len > str_len) {
632 return mp_const_false;
633 }
634 return MP_BOOL(memcmp(str + (str_len - suffix_len), suffix, suffix_len) == 0);
635}
636
Paul Sokolovsky88107842014-04-26 06:20:08 +0300637enum { LSTRIP, RSTRIP, STRIP };
638
639STATIC mp_obj_t str_uni_strip(int type, uint n_args, const mp_obj_t *args) {
xbe7b0f39f2014-01-08 14:23:45 -0800640 assert(1 <= n_args && n_args <= 2);
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300641 assert(is_str_or_bytes(args[0]));
642 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Damien George5fa93b62014-01-22 14:35:10 +0000643
644 const byte *chars_to_del;
645 uint chars_to_del_len;
646 static const byte whitespace[] = " \t\n\r\v\f";
xbe7b0f39f2014-01-08 14:23:45 -0800647
648 if (n_args == 1) {
649 chars_to_del = whitespace;
Damien George5fa93b62014-01-22 14:35:10 +0000650 chars_to_del_len = sizeof(whitespace);
xbe7b0f39f2014-01-08 14:23:45 -0800651 } else {
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300652 if (mp_obj_get_type(args[1]) != self_type) {
653 arg_type_mixup();
654 }
Damien George5fa93b62014-01-22 14:35:10 +0000655 GET_STR_DATA_LEN(args[1], s, l);
656 chars_to_del = s;
657 chars_to_del_len = l;
xbe7b0f39f2014-01-08 14:23:45 -0800658 }
659
Damien George5fa93b62014-01-22 14:35:10 +0000660 GET_STR_DATA_LEN(args[0], orig_str, orig_str_len);
xbe7b0f39f2014-01-08 14:23:45 -0800661
xbec5538882014-03-16 17:58:35 -0700662 machine_uint_t first_good_char_pos = 0;
xbe7b0f39f2014-01-08 14:23:45 -0800663 bool first_good_char_pos_set = false;
xbec5538882014-03-16 17:58:35 -0700664 machine_uint_t last_good_char_pos = 0;
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300665 machine_uint_t i = 0;
666 machine_int_t delta = 1;
667 if (type == RSTRIP) {
668 i = orig_str_len - 1;
669 delta = -1;
670 }
671 for (machine_uint_t len = orig_str_len; len > 0; len--) {
xbe17a5a832014-03-23 23:31:58 -0700672 if (find_subbytes(chars_to_del, chars_to_del_len, &orig_str[i], 1, 1) == NULL) {
xbe7b0f39f2014-01-08 14:23:45 -0800673 if (!first_good_char_pos_set) {
Paul Sokolovskybcdffe52014-05-30 03:07:05 +0300674 first_good_char_pos_set = true;
xbe7b0f39f2014-01-08 14:23:45 -0800675 first_good_char_pos = i;
Paul Sokolovsky88107842014-04-26 06:20:08 +0300676 if (type == LSTRIP) {
677 last_good_char_pos = orig_str_len - 1;
678 break;
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300679 } else if (type == RSTRIP) {
680 first_good_char_pos = 0;
681 last_good_char_pos = i;
682 break;
Paul Sokolovsky88107842014-04-26 06:20:08 +0300683 }
xbe7b0f39f2014-01-08 14:23:45 -0800684 }
Paul Sokolovsky88107842014-04-26 06:20:08 +0300685 last_good_char_pos = i;
xbe7b0f39f2014-01-08 14:23:45 -0800686 }
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300687 i += delta;
xbe7b0f39f2014-01-08 14:23:45 -0800688 }
689
Paul Sokolovskybcdffe52014-05-30 03:07:05 +0300690 if (!first_good_char_pos_set) {
Damien George5fa93b62014-01-22 14:35:10 +0000691 // string is all whitespace, return ''
692 return MP_OBJ_NEW_QSTR(MP_QSTR_);
xbe7b0f39f2014-01-08 14:23:45 -0800693 }
694
695 assert(last_good_char_pos >= first_good_char_pos);
696 //+1 to accomodate the last character
xbec5538882014-03-16 17:58:35 -0700697 machine_uint_t stripped_len = last_good_char_pos - first_good_char_pos + 1;
Paul Sokolovsky88276822014-05-30 03:11:44 +0300698 if (stripped_len == orig_str_len) {
699 // If nothing was stripped, don't bother to dup original string
700 // TODO: watch out for this case when we'll get to bytearray.strip()
701 assert(first_good_char_pos == 0);
702 return args[0];
703 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100704 return mp_obj_new_str_of_type(self_type, orig_str + first_good_char_pos, stripped_len);
xbe7b0f39f2014-01-08 14:23:45 -0800705}
706
Paul Sokolovsky88107842014-04-26 06:20:08 +0300707STATIC mp_obj_t str_strip(uint n_args, const mp_obj_t *args) {
708 return str_uni_strip(STRIP, n_args, args);
709}
710
711STATIC mp_obj_t str_lstrip(uint n_args, const mp_obj_t *args) {
712 return str_uni_strip(LSTRIP, n_args, args);
713}
714
715STATIC mp_obj_t str_rstrip(uint n_args, const mp_obj_t *args) {
716 return str_uni_strip(RSTRIP, n_args, args);
717}
718
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700719// Takes an int arg, but only parses unsigned numbers, and only changes
720// *num if at least one digit was parsed.
721static int str_to_int(const char *str, int *num) {
722 const char *s = str;
723 if (unichar_isdigit(*s)) {
724 *num = 0;
725 do {
726 *num = *num * 10 + (*s - '0');
727 s++;
728 }
729 while (unichar_isdigit(*s));
730 }
731 return s - str;
732}
733
734static bool isalignment(char ch) {
735 return ch && strchr("<>=^", ch) != NULL;
736}
737
738static bool istype(char ch) {
739 return ch && strchr("bcdeEfFgGnosxX%", ch) != NULL;
740}
741
742static bool arg_looks_integer(mp_obj_t arg) {
743 return MP_OBJ_IS_TYPE(arg, &mp_type_bool) || MP_OBJ_IS_INT(arg);
744}
745
746static bool arg_looks_numeric(mp_obj_t arg) {
747 return arg_looks_integer(arg)
Damien Georgefb510b32014-06-01 13:32:54 +0100748#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700749 || MP_OBJ_IS_TYPE(arg, &mp_type_float)
750#endif
751 ;
752}
753
Dave Hylandsc4029e52014-04-07 11:19:51 -0700754static mp_obj_t arg_as_int(mp_obj_t arg) {
Damien Georgefb510b32014-06-01 13:32:54 +0100755#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700756 if (MP_OBJ_IS_TYPE(arg, &mp_type_float)) {
Dave Hylandsc4029e52014-04-07 11:19:51 -0700757
758 // TODO: Needs a way to construct an mpz integer from a float
759
760 mp_small_int_t num = mp_obj_get_float(arg);
761 return MP_OBJ_NEW_SMALL_INT(num);
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700762 }
763#endif
Dave Hylandsc4029e52014-04-07 11:19:51 -0700764 return arg;
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700765}
766
Damien George897fe0c2014-04-15 22:03:55 +0100767mp_obj_t mp_obj_str_format(uint n_args, const mp_obj_t *args) {
Damien George5fa93b62014-01-22 14:35:10 +0000768 assert(MP_OBJ_IS_STR(args[0]));
Damiend99b0522013-12-21 18:17:45 +0000769
Damien George5fa93b62014-01-22 14:35:10 +0000770 GET_STR_DATA_LEN(args[0], str, len);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700771 int arg_i = 0;
Damiend99b0522013-12-21 18:17:45 +0000772 vstr_t *vstr = vstr_new();
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700773 pfenv_t pfenv_vstr;
774 pfenv_vstr.data = vstr;
775 pfenv_vstr.print_strn = pfenv_vstr_add_strn;
776
Damien George5fa93b62014-01-22 14:35:10 +0000777 for (const byte *top = str + len; str < top; str++) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700778 if (*str == '}') {
Damiend99b0522013-12-21 18:17:45 +0000779 str++;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700780 if (str < top && *str == '}') {
781 vstr_add_char(vstr, '}');
782 continue;
783 }
Damien George11de8392014-06-05 18:57:38 +0100784 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "single '}' encountered in format string"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700785 }
786 if (*str != '{') {
787 vstr_add_char(vstr, *str);
788 continue;
789 }
790
791 str++;
792 if (str < top && *str == '{') {
793 vstr_add_char(vstr, '{');
794 continue;
795 }
796
797 // replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"
798
799 vstr_t *field_name = NULL;
800 char conversion = '\0';
801 vstr_t *format_spec = NULL;
802
803 if (str < top && *str != '}' && *str != '!' && *str != ':') {
804 field_name = vstr_new();
805 while (str < top && *str != '}' && *str != '!' && *str != ':') {
806 vstr_add_char(field_name, *str++);
807 }
808 vstr_add_char(field_name, '\0');
809 }
810
811 // conversion ::= "r" | "s"
812
813 if (str < top && *str == '!') {
814 str++;
815 if (str < top && (*str == 'r' || *str == 's')) {
816 conversion = *str++;
Paul Sokolovskyf2b796e2014-01-15 22:45:20 +0200817 } else {
Damien Georgeea13f402014-04-05 18:32:08 +0100818 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 -0700819 }
820 }
821
822 if (str < top && *str == ':') {
823 str++;
824 // {:} is the same as {}, which is the same as {!s}
825 // This makes a difference when passing in a True or False
826 // '{}'.format(True) returns 'True'
827 // '{:d}'.format(True) returns '1'
828 // So we treat {:} as {} and this later gets treated to be {!s}
829 if (*str != '}') {
Damien George11de8392014-06-05 18:57:38 +0100830 format_spec = vstr_new();
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700831 while (str < top && *str != '}') {
832 vstr_add_char(format_spec, *str++);
Damiend99b0522013-12-21 18:17:45 +0000833 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700834 vstr_add_char(format_spec, '\0');
835 }
836 }
837 if (str >= top) {
Damien Georgeea13f402014-04-05 18:32:08 +0100838 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "unmatched '{' in format"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700839 }
840 if (*str != '}') {
Damien Georgeea13f402014-04-05 18:32:08 +0100841 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "expected ':' after format specifier"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700842 }
843
844 mp_obj_t arg = mp_const_none;
845
846 if (field_name) {
847 if (arg_i > 0) {
Damien George11de8392014-06-05 18:57:38 +0100848 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 -0700849 }
Damien George3bb8bd82014-04-14 21:20:30 +0100850 int index = 0;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700851 if (str_to_int(vstr_str(field_name), &index) != vstr_len(field_name) - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100852 nlr_raise(mp_obj_new_exception_msg(&mp_type_KeyError, "attributes not supported yet"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700853 }
854 if (index >= n_args - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100855 nlr_raise(mp_obj_new_exception_msg(&mp_type_IndexError, "tuple index out of range"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700856 }
857 arg = args[index + 1];
858 arg_i = -1;
859 vstr_free(field_name);
860 field_name = NULL;
861 } else {
862 if (arg_i < 0) {
Damien George11de8392014-06-05 18:57:38 +0100863 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 -0700864 }
865 if (arg_i >= n_args - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100866 nlr_raise(mp_obj_new_exception_msg(&mp_type_IndexError, "tuple index out of range"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700867 }
868 arg = args[arg_i + 1];
869 arg_i++;
870 }
871 if (!format_spec && !conversion) {
872 conversion = 's';
873 }
874 if (conversion) {
875 mp_print_kind_t print_kind;
876 if (conversion == 's') {
877 print_kind = PRINT_STR;
878 } else if (conversion == 'r') {
879 print_kind = PRINT_REPR;
880 } else {
Damien George11de8392014-06-05 18:57:38 +0100881 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "unknown conversion specifier %c", conversion));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700882 }
883 vstr_t *arg_vstr = vstr_new();
884 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, arg_vstr, arg, print_kind);
Damien George2617eeb2014-05-25 22:27:57 +0100885 arg = mp_obj_new_str(vstr_str(arg_vstr), vstr_len(arg_vstr), false);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700886 vstr_free(arg_vstr);
887 }
888
889 char sign = '\0';
890 char fill = '\0';
891 char align = '\0';
892 int width = -1;
893 int precision = -1;
894 char type = '\0';
895 int flags = 0;
896
897 if (format_spec) {
898 // The format specifier (from http://docs.python.org/2/library/string.html#formatspec)
899 //
900 // [[fill]align][sign][#][0][width][,][.precision][type]
901 // fill ::= <any character>
902 // align ::= "<" | ">" | "=" | "^"
903 // sign ::= "+" | "-" | " "
904 // width ::= integer
905 // precision ::= integer
906 // type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
907
908 const char *s = vstr_str(format_spec);
909 if (isalignment(*s)) {
910 align = *s++;
911 } else if (*s && isalignment(s[1])) {
912 fill = *s++;
913 align = *s++;
914 }
915 if (*s == '+' || *s == '-' || *s == ' ') {
916 if (*s == '+') {
917 flags |= PF_FLAG_SHOW_SIGN;
918 } else if (*s == ' ') {
919 flags |= PF_FLAG_SPACE_SIGN;
920 }
921 sign = *s++;
922 }
923 if (*s == '#') {
924 flags |= PF_FLAG_SHOW_PREFIX;
925 s++;
926 }
927 if (*s == '0') {
928 if (!align) {
929 align = '=';
930 }
931 if (!fill) {
932 fill = '0';
933 }
934 }
935 s += str_to_int(s, &width);
936 if (*s == ',') {
937 flags |= PF_FLAG_SHOW_COMMA;
938 s++;
939 }
940 if (*s == '.') {
941 s++;
942 s += str_to_int(s, &precision);
943 }
944 if (istype(*s)) {
945 type = *s++;
946 }
947 if (*s) {
Damien Georgeea13f402014-04-05 18:32:08 +0100948 nlr_raise(mp_obj_new_exception_msg(&mp_type_KeyError, "Invalid conversion specification"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700949 }
950 vstr_free(format_spec);
951 format_spec = NULL;
952 }
953 if (!align) {
954 if (arg_looks_numeric(arg)) {
955 align = '>';
956 } else {
957 align = '<';
958 }
959 }
960 if (!fill) {
961 fill = ' ';
962 }
963
964 if (sign) {
965 if (type == 's') {
Damien Georgeea13f402014-04-05 18:32:08 +0100966 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "Sign not allowed in string format specifier"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700967 }
968 if (type == 'c') {
Damien Georgeea13f402014-04-05 18:32:08 +0100969 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "Sign not allowed with integer format specifier 'c'"));
Damiend99b0522013-12-21 18:17:45 +0000970 }
971 } else {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700972 sign = '-';
973 }
974
975 switch (align) {
976 case '<': flags |= PF_FLAG_LEFT_ADJUST; break;
977 case '=': flags |= PF_FLAG_PAD_AFTER_SIGN; break;
978 case '^': flags |= PF_FLAG_CENTER_ADJUST; break;
979 }
980
981 if (arg_looks_integer(arg)) {
982 switch (type) {
983 case 'b':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -0700984 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 2, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700985 continue;
986
987 case 'c':
988 {
989 char ch = mp_obj_get_int(arg);
990 pfenv_print_strn(&pfenv_vstr, &ch, 1, flags, fill, width);
991 continue;
992 }
993
994 case '\0': // No explicit format type implies 'd'
995 case 'n': // I don't think we support locales in uPy so use 'd'
996 case 'd':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -0700997 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 10, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700998 continue;
999
1000 case 'o':
Dave Hylandsc4029e52014-04-07 11:19:51 -07001001 if (flags & PF_FLAG_SHOW_PREFIX) {
1002 flags |= PF_FLAG_SHOW_OCTAL_LETTER;
1003 }
1004
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001005 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 8, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001006 continue;
1007
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001008 case 'X':
Damien George11de8392014-06-05 18:57:38 +01001009 case 'x':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001010 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 16, type - ('X' - 'A'), flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001011 continue;
1012
1013 case 'e':
1014 case 'E':
1015 case 'f':
1016 case 'F':
1017 case 'g':
1018 case 'G':
1019 case '%':
1020 // The floating point formatters all work with anything that
1021 // looks like an integer
1022 break;
1023
1024 default:
Damien Georgeea13f402014-04-05 18:32:08 +01001025 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Damien George11de8392014-06-05 18:57:38 +01001026 "unknown format code '%c' for object of type '%s'", type, mp_obj_get_type_str(arg)));
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001027 }
Damien Georgec322c5f2014-04-02 20:04:15 +01001028 }
Damien George70f33cd2014-04-02 17:06:05 +01001029
Dave Hylands22fe4d72014-04-02 12:07:31 -07001030 // NOTE: no else here. We need the e, f, g etc formats for integer
1031 // arguments (from above if) to take this if.
Damien Georgec322c5f2014-04-02 20:04:15 +01001032 if (arg_looks_numeric(arg)) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001033 if (!type) {
1034
1035 // Even though the docs say that an unspecified type is the same
1036 // as 'g', there is one subtle difference, when the exponent
1037 // is one less than the precision.
Damien George11de8392014-06-05 18:57:38 +01001038 //
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001039 // '{:10.1}'.format(0.0) ==> '0e+00'
1040 // '{:10.1g}'.format(0.0) ==> '0'
1041 //
1042 // TODO: Figure out how to deal with this.
1043 //
1044 // A proper solution would involve adding a special flag
1045 // or something to format_float, and create a format_double
1046 // to deal with doubles. In order to fix this when using
1047 // sprintf, we'd need to use the e format and tweak the
1048 // returned result to strip trailing zeros like the g format
1049 // does.
1050 //
1051 // {:10.3} and {:10.2e} with 1.23e2 both produce 1.23e+02
1052 // but with 1.e2 you get 1e+02 and 1.00e+02
1053 //
1054 // Stripping the trailing 0's (like g) does would make the
1055 // e format give us the right format.
1056 //
1057 // CPython sources say:
1058 // Omitted type specifier. Behaves in the same way as repr(x)
1059 // and str(x) if no precision is given, else like 'g', but with
1060 // at least one digit after the decimal point. */
1061
1062 type = 'g';
1063 }
1064 if (type == 'n') {
1065 type = 'g';
1066 }
1067
1068 flags |= PF_FLAG_PAD_NAN_INF; // '{:06e}'.format(float('-inf')) should give '-00inf'
1069 switch (type) {
Damien Georgefb510b32014-06-01 13:32:54 +01001070#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001071 case 'e':
1072 case 'E':
1073 case 'f':
1074 case 'F':
1075 case 'g':
1076 case 'G':
Damien George11de8392014-06-05 18:57:38 +01001077 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg), type, flags, fill, width, precision);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001078 break;
1079
1080 case '%':
1081 flags |= PF_FLAG_ADD_PERCENT;
1082 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg) * 100.0F, 'f', flags, fill, width, precision);
1083 break;
Damien Georgec322c5f2014-04-02 20:04:15 +01001084#endif
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001085
1086 default:
Damien Georgeea13f402014-04-05 18:32:08 +01001087 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Damien George11de8392014-06-05 18:57:38 +01001088 "unknown format code '%c' for object of type 'float'",
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001089 type, mp_obj_get_type_str(arg)));
1090 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001091 } else {
Damien George70f33cd2014-04-02 17:06:05 +01001092 // arg doesn't look like a number
1093
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001094 if (align == '=') {
Damien Georgeea13f402014-04-05 18:32:08 +01001095 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "'=' alignment not allowed in string format specifier"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001096 }
Damien George70f33cd2014-04-02 17:06:05 +01001097
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001098 switch (type) {
1099 case '\0':
1100 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, vstr, arg, PRINT_STR);
1101 break;
1102
1103 case 's':
1104 {
1105 uint len;
1106 const char *s = mp_obj_str_get_data(arg, &len);
1107 if (precision < 0) {
1108 precision = len;
1109 }
1110 if (len > precision) {
1111 len = precision;
1112 }
1113 pfenv_print_strn(&pfenv_vstr, s, len, flags, fill, width);
1114 break;
1115 }
1116
1117 default:
Damien Georgeea13f402014-04-05 18:32:08 +01001118 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Damien George11de8392014-06-05 18:57:38 +01001119 "unknown format code '%c' for object of type 'str'",
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001120 type, mp_obj_get_type_str(arg)));
1121 }
Damiend99b0522013-12-21 18:17:45 +00001122 }
1123 }
1124
Damien George2617eeb2014-05-25 22:27:57 +01001125 mp_obj_t s = mp_obj_new_str(vstr->buf, vstr->len, false);
Damien George5fa93b62014-01-22 14:35:10 +00001126 vstr_free(vstr);
1127 return s;
Damiend99b0522013-12-21 18:17:45 +00001128}
1129
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001130STATIC 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 +03001131 assert(MP_OBJ_IS_STR(pattern));
1132
1133 GET_STR_DATA_LEN(pattern, str, len);
Dave Hylands6756a372014-04-02 11:42:39 -07001134 const byte *start_str = str;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001135 int arg_i = 0;
1136 vstr_t *vstr = vstr_new();
Dave Hylands6756a372014-04-02 11:42:39 -07001137 pfenv_t pfenv_vstr;
1138 pfenv_vstr.data = vstr;
1139 pfenv_vstr.print_strn = pfenv_vstr_add_strn;
1140
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001141 for (const byte *top = str + len; str < top; str++) {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001142 mp_obj_t arg = MP_OBJ_NULL;
Dave Hylands6756a372014-04-02 11:42:39 -07001143 if (*str != '%') {
1144 vstr_add_char(vstr, *str);
1145 continue;
1146 }
1147 if (++str >= top) {
1148 break;
1149 }
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001150 if (*str == '%') {
Dave Hylands6756a372014-04-02 11:42:39 -07001151 vstr_add_char(vstr, '%');
1152 continue;
1153 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001154
1155 // Dictionary value lookup
1156 if (*str == '(') {
1157 const byte *key = ++str;
1158 while (*str != ')') {
1159 if (str >= top) {
1160 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "incomplete format key"));
1161 }
1162 ++str;
1163 }
1164 mp_obj_t k_obj = mp_obj_new_str((const char*)key, str - key, true);
1165 arg = mp_obj_dict_get(dict, k_obj);
1166 str++;
Dave Hylands6756a372014-04-02 11:42:39 -07001167 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001168
Dave Hylands6756a372014-04-02 11:42:39 -07001169 int flags = 0;
1170 char fill = ' ';
Damien George11de8392014-06-05 18:57:38 +01001171 int alt = 0;
Dave Hylands6756a372014-04-02 11:42:39 -07001172 while (str < top) {
1173 if (*str == '-') flags |= PF_FLAG_LEFT_ADJUST;
1174 else if (*str == '+') flags |= PF_FLAG_SHOW_SIGN;
1175 else if (*str == ' ') flags |= PF_FLAG_SPACE_SIGN;
Damien George11de8392014-06-05 18:57:38 +01001176 else if (*str == '#') alt = PF_FLAG_SHOW_PREFIX;
Dave Hylands6756a372014-04-02 11:42:39 -07001177 else if (*str == '0') {
1178 flags |= PF_FLAG_PAD_AFTER_SIGN;
1179 fill = '0';
1180 } else break;
1181 str++;
1182 }
1183 // parse width, if it exists
Damien George11de8392014-06-05 18:57:38 +01001184 int width = 0;
Dave Hylands6756a372014-04-02 11:42:39 -07001185 if (str < top) {
1186 if (*str == '*') {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001187 if (arg_i >= n_args) {
1188 goto not_enough_args;
1189 }
Dave Hylands6756a372014-04-02 11:42:39 -07001190 width = mp_obj_get_int(args[arg_i++]);
1191 str++;
1192 } else {
1193 for (; str < top && '0' <= *str && *str <= '9'; str++) {
1194 width = width * 10 + *str - '0';
1195 }
1196 }
1197 }
1198 int prec = -1;
1199 if (str < top && *str == '.') {
1200 if (++str < top) {
1201 if (*str == '*') {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001202 if (arg_i >= n_args) {
1203 goto not_enough_args;
1204 }
Dave Hylands6756a372014-04-02 11:42:39 -07001205 prec = mp_obj_get_int(args[arg_i++]);
1206 str++;
1207 } else {
1208 prec = 0;
1209 for (; str < top && '0' <= *str && *str <= '9'; str++) {
1210 prec = prec * 10 + *str - '0';
1211 }
1212 }
1213 }
1214 }
1215
1216 if (str >= top) {
Damien Georgeea13f402014-04-05 18:32:08 +01001217 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "incomplete format"));
Dave Hylands6756a372014-04-02 11:42:39 -07001218 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001219
1220 // Tuple value lookup
1221 if (arg == MP_OBJ_NULL) {
1222 if (arg_i >= n_args) {
1223not_enough_args:
1224 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "not enough arguments for format string"));
1225 }
1226 arg = args[arg_i++];
1227 }
Dave Hylands6756a372014-04-02 11:42:39 -07001228 switch (*str) {
1229 case 'c':
1230 if (MP_OBJ_IS_STR(arg)) {
1231 uint len;
1232 const char *s = mp_obj_str_get_data(arg, &len);
1233 if (len != 1) {
Damien George11de8392014-06-05 18:57:38 +01001234 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "%%c requires int or char"));
Dave Hylands6756a372014-04-02 11:42:39 -07001235 break;
1236 }
1237 pfenv_print_strn(&pfenv_vstr, s, 1, flags, ' ', width);
1238 break;
1239 }
1240 if (arg_looks_integer(arg)) {
1241 char ch = mp_obj_get_int(arg);
1242 pfenv_print_strn(&pfenv_vstr, &ch, 1, flags, ' ', width);
1243 break;
1244 }
Damien Georgefb510b32014-06-01 13:32:54 +01001245#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylands6756a372014-04-02 11:42:39 -07001246 // This is what CPython reports, so we report the same.
1247 if (MP_OBJ_IS_TYPE(arg, &mp_type_float)) {
Damien George11de8392014-06-05 18:57:38 +01001248 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "integer argument expected, got float"));
Dave Hylands6756a372014-04-02 11:42:39 -07001249
1250 }
1251#endif
Damien George11de8392014-06-05 18:57:38 +01001252 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "an integer is required"));
1253 break;
Dave Hylands6756a372014-04-02 11:42:39 -07001254
1255 case 'd':
1256 case 'i':
1257 case 'u':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001258 pfenv_print_mp_int(&pfenv_vstr, arg_as_int(arg), 1, 10, 'a', flags, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001259 break;
1260
Damien Georgefb510b32014-06-01 13:32:54 +01001261#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylands6756a372014-04-02 11:42:39 -07001262 case 'e':
1263 case 'E':
1264 case 'f':
1265 case 'F':
1266 case 'g':
1267 case 'G':
1268 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg), *str, flags, fill, width, prec);
1269 break;
1270#endif
1271
1272 case 'o':
1273 if (alt) {
Dave Hylandsc4029e52014-04-07 11:19:51 -07001274 flags |= (PF_FLAG_SHOW_PREFIX | PF_FLAG_SHOW_OCTAL_LETTER);
Dave Hylands6756a372014-04-02 11:42:39 -07001275 }
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001276 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 8, 'a', flags, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001277 break;
1278
1279 case 'r':
1280 case 's':
1281 {
1282 vstr_t *arg_vstr = vstr_new();
1283 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf,
1284 arg_vstr, arg, *str == 'r' ? PRINT_REPR : PRINT_STR);
1285 uint len = vstr_len(arg_vstr);
1286 if (prec < 0) {
1287 prec = len;
1288 }
1289 if (len > prec) {
1290 len = prec;
1291 }
1292 pfenv_print_strn(&pfenv_vstr, vstr_str(arg_vstr), len, flags, ' ', width);
1293 vstr_free(arg_vstr);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001294 break;
1295 }
Dave Hylands6756a372014-04-02 11:42:39 -07001296
Dave Hylands6756a372014-04-02 11:42:39 -07001297 case 'X':
Damien George11de8392014-06-05 18:57:38 +01001298 case 'x':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001299 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 16, *str - ('X' - 'A'), flags | alt, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001300 break;
Damien Georgedeed0872014-04-06 11:11:15 +01001301
Dave Hylands6756a372014-04-02 11:42:39 -07001302 default:
Damien Georgeea13f402014-04-05 18:32:08 +01001303 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Dave Hylands6756a372014-04-02 11:42:39 -07001304 "unsupported format character '%c' (0x%x) at index %d",
1305 *str, *str, str - start_str));
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001306 }
1307 }
1308
1309 if (arg_i != n_args) {
Damien Georgeea13f402014-04-05 18:32:08 +01001310 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "not all arguments converted during string formatting"));
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001311 }
1312
Damien George2617eeb2014-05-25 22:27:57 +01001313 mp_obj_t s = mp_obj_new_str(vstr->buf, vstr->len, false);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001314 vstr_free(vstr);
1315 return s;
1316}
1317
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001318STATIC mp_obj_t str_replace(uint n_args, const mp_obj_t *args) {
xbe480c15a2014-01-30 22:17:30 -08001319 assert(MP_OBJ_IS_STR(args[0]));
xbe480c15a2014-01-30 22:17:30 -08001320
Damien Georgeff715422014-04-07 00:39:13 +01001321 machine_int_t max_rep = -1;
xbe480c15a2014-01-30 22:17:30 -08001322 if (n_args == 4) {
Damien Georgeff715422014-04-07 00:39:13 +01001323 max_rep = mp_obj_get_int(args[3]);
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001324 if (max_rep == 0) {
1325 return args[0];
1326 } else if (max_rep < 0) {
Damien Georgeff715422014-04-07 00:39:13 +01001327 max_rep = -1;
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001328 }
xbe480c15a2014-01-30 22:17:30 -08001329 }
Damien George94f68302014-01-31 23:45:12 +00001330
xbe729be9b2014-04-07 14:46:39 -07001331 // if max_rep is still -1 by this point we will need to do all possible replacements
xbe480c15a2014-01-30 22:17:30 -08001332
Damien Georgeff715422014-04-07 00:39:13 +01001333 // check argument types
1334
1335 if (!MP_OBJ_IS_STR(args[1])) {
1336 bad_implicit_conversion(args[1]);
1337 }
1338
1339 if (!MP_OBJ_IS_STR(args[2])) {
1340 bad_implicit_conversion(args[2]);
1341 }
1342
1343 // extract string data
1344
xbe480c15a2014-01-30 22:17:30 -08001345 GET_STR_DATA_LEN(args[0], str, str_len);
1346 GET_STR_DATA_LEN(args[1], old, old_len);
1347 GET_STR_DATA_LEN(args[2], new, new_len);
Damien George94f68302014-01-31 23:45:12 +00001348
1349 // old won't exist in str if it's longer, so nothing to replace
xbe480c15a2014-01-30 22:17:30 -08001350 if (old_len > str_len) {
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001351 return args[0];
xbe480c15a2014-01-30 22:17:30 -08001352 }
1353
Damien George94f68302014-01-31 23:45:12 +00001354 // data for the replaced string
1355 byte *data = NULL;
1356 mp_obj_t replaced_str = MP_OBJ_NULL;
xbe480c15a2014-01-30 22:17:30 -08001357
Damien George94f68302014-01-31 23:45:12 +00001358 // do 2 passes over the string:
1359 // first pass computes the required length of the replaced string
1360 // second pass does the replacements
1361 for (;;) {
1362 machine_uint_t replaced_str_index = 0;
1363 machine_uint_t num_replacements_done = 0;
1364 const byte *old_occurrence;
1365 const byte *offset_ptr = str;
Damien Georgeff715422014-04-07 00:39:13 +01001366 machine_uint_t str_len_remain = str_len;
1367 if (old_len == 0) {
1368 // if old_str is empty, copy new_str to start of replaced string
1369 // copy the replacement string
1370 if (data != NULL) {
1371 memcpy(data, new, new_len);
1372 }
1373 replaced_str_index += new_len;
1374 num_replacements_done++;
1375 }
1376 while (num_replacements_done != max_rep && str_len_remain > 0 && (old_occurrence = find_subbytes(offset_ptr, str_len_remain, old, old_len, 1)) != NULL) {
1377 if (old_len == 0) {
1378 old_occurrence += 1;
1379 }
Damien George94f68302014-01-31 23:45:12 +00001380 // copy from just after end of last occurrence of to-be-replaced string to right before start of next occurrence
1381 if (data != NULL) {
1382 memcpy(data + replaced_str_index, offset_ptr, old_occurrence - offset_ptr);
1383 }
1384 replaced_str_index += old_occurrence - offset_ptr;
1385 // copy the replacement string
1386 if (data != NULL) {
1387 memcpy(data + replaced_str_index, new, new_len);
1388 }
1389 replaced_str_index += new_len;
1390 offset_ptr = old_occurrence + old_len;
Damien Georgeff715422014-04-07 00:39:13 +01001391 str_len_remain = str + str_len - offset_ptr;
Damien George94f68302014-01-31 23:45:12 +00001392 num_replacements_done++;
Damien George94f68302014-01-31 23:45:12 +00001393 }
1394
1395 // copy from just after end of last occurrence of to-be-replaced string to end of old string
1396 if (data != NULL) {
Damien Georgeff715422014-04-07 00:39:13 +01001397 memcpy(data + replaced_str_index, offset_ptr, str_len_remain);
Damien George94f68302014-01-31 23:45:12 +00001398 }
Damien Georgeff715422014-04-07 00:39:13 +01001399 replaced_str_index += str_len_remain;
Damien George94f68302014-01-31 23:45:12 +00001400
1401 if (data == NULL) {
1402 // first pass
1403 if (num_replacements_done == 0) {
1404 // no substr found, return original string
1405 return args[0];
1406 } else {
1407 // substr found, allocate new string
1408 replaced_str = mp_obj_str_builder_start(mp_obj_get_type(args[0]), replaced_str_index, &data);
Damien Georgeff715422014-04-07 00:39:13 +01001409 assert(data != NULL);
Damien George94f68302014-01-31 23:45:12 +00001410 }
1411 } else {
1412 // second pass, we are done
1413 break;
1414 }
xbe480c15a2014-01-30 22:17:30 -08001415 }
Damien George94f68302014-01-31 23:45:12 +00001416
xbe480c15a2014-01-30 22:17:30 -08001417 return mp_obj_str_builder_end(replaced_str);
1418}
1419
xbe9e1e8cd2014-03-12 22:57:16 -07001420STATIC mp_obj_t str_count(uint n_args, const mp_obj_t *args) {
1421 assert(2 <= n_args && n_args <= 4);
1422 assert(MP_OBJ_IS_STR(args[0]));
1423 assert(MP_OBJ_IS_STR(args[1]));
1424
1425 GET_STR_DATA_LEN(args[0], haystack, haystack_len);
1426 GET_STR_DATA_LEN(args[1], needle, needle_len);
1427
Damien George536dde22014-03-13 22:07:55 +00001428 machine_uint_t start = 0;
1429 machine_uint_t end = haystack_len;
xbe9e1e8cd2014-03-12 22:57:16 -07001430 if (n_args >= 3 && args[2] != mp_const_none) {
Damien George3e1a5c12014-03-29 13:43:38 +00001431 start = mp_get_index(&mp_type_str, haystack_len, args[2], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001432 }
1433 if (n_args >= 4 && args[3] != mp_const_none) {
Damien George3e1a5c12014-03-29 13:43:38 +00001434 end = mp_get_index(&mp_type_str, haystack_len, args[3], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001435 }
1436
Damien George536dde22014-03-13 22:07:55 +00001437 // if needle_len is zero then we count each gap between characters as an occurrence
1438 if (needle_len == 0) {
1439 return MP_OBJ_NEW_SMALL_INT(end - start + 1);
xbe9e1e8cd2014-03-12 22:57:16 -07001440 }
1441
Damien George536dde22014-03-13 22:07:55 +00001442 // count the occurrences
1443 machine_int_t num_occurrences = 0;
xbec5d70ba2014-03-13 00:29:15 -07001444 for (machine_uint_t haystack_index = start; haystack_index + needle_len <= end; haystack_index++) {
1445 if (memcmp(&haystack[haystack_index], needle, needle_len) == 0) {
1446 num_occurrences++;
1447 haystack_index += needle_len - 1;
1448 }
xbe9e1e8cd2014-03-12 22:57:16 -07001449 }
1450
1451 return MP_OBJ_NEW_SMALL_INT(num_occurrences);
1452}
1453
Damien Georgeb035db32014-03-21 20:39:40 +00001454STATIC 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 +03001455 if (!is_str_or_bytes(self_in)) {
1456 assert(0);
1457 }
1458 mp_obj_type_t *self_type = mp_obj_get_type(self_in);
1459 if (self_type != mp_obj_get_type(arg)) {
1460 arg_type_mixup();
xbe613a8e32014-03-18 00:06:29 -07001461 }
Damien Georgeb035db32014-03-21 20:39:40 +00001462
xbe613a8e32014-03-18 00:06:29 -07001463 GET_STR_DATA_LEN(self_in, str, str_len);
1464 GET_STR_DATA_LEN(arg, sep, sep_len);
1465
1466 if (sep_len == 0) {
Damien Georgeea13f402014-04-05 18:32:08 +01001467 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
xbe613a8e32014-03-18 00:06:29 -07001468 }
Damien Georgeb035db32014-03-21 20:39:40 +00001469
1470 mp_obj_t result[] = {MP_OBJ_NEW_QSTR(MP_QSTR_), MP_OBJ_NEW_QSTR(MP_QSTR_), MP_OBJ_NEW_QSTR(MP_QSTR_)};
1471
1472 if (direction > 0) {
1473 result[0] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001474 } else {
Damien Georgeb035db32014-03-21 20:39:40 +00001475 result[2] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001476 }
xbe613a8e32014-03-18 00:06:29 -07001477
xbe17a5a832014-03-23 23:31:58 -07001478 const byte *position_ptr = find_subbytes(str, str_len, sep, sep_len, direction);
1479 if (position_ptr != NULL) {
1480 machine_uint_t position = position_ptr - str;
Damien Georgef600a6a2014-05-25 22:34:34 +01001481 result[0] = mp_obj_new_str_of_type(self_type, str, position);
xbe17a5a832014-03-23 23:31:58 -07001482 result[1] = arg;
Damien Georgef600a6a2014-05-25 22:34:34 +01001483 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 -07001484 }
Damien Georgeb035db32014-03-21 20:39:40 +00001485
xbe0a6894c2014-03-21 01:12:26 -07001486 return mp_obj_new_tuple(3, result);
xbe613a8e32014-03-18 00:06:29 -07001487}
1488
Damien Georgeb035db32014-03-21 20:39:40 +00001489STATIC mp_obj_t str_partition(mp_obj_t self_in, mp_obj_t arg) {
1490 return str_partitioner(self_in, arg, 1);
xbe0a6894c2014-03-21 01:12:26 -07001491}
xbe4504ea82014-03-19 00:46:14 -07001492
Damien Georgeb035db32014-03-21 20:39:40 +00001493STATIC mp_obj_t str_rpartition(mp_obj_t self_in, mp_obj_t arg) {
1494 return str_partitioner(self_in, arg, -1);
xbe4504ea82014-03-19 00:46:14 -07001495}
1496
Paul Sokolovsky69135212014-05-10 19:47:41 +03001497// Supposedly not too critical operations, so optimize for code size
Damien Georgefcc9cf62014-06-01 18:22:09 +01001498STATIC mp_obj_t str_caseconv(unichar (*op)(unichar), mp_obj_t self_in) {
Paul Sokolovsky69135212014-05-10 19:47:41 +03001499 GET_STR_DATA_LEN(self_in, self_data, self_len);
1500 byte *data;
1501 mp_obj_t s = mp_obj_str_builder_start(mp_obj_get_type(self_in), self_len, &data);
1502 for (int i = 0; i < self_len; i++) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001503 *data++ = op(*self_data++);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001504 }
1505 *data = 0;
1506 return mp_obj_str_builder_end(s);
1507}
1508
1509STATIC mp_obj_t str_lower(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001510 return str_caseconv(unichar_tolower, self_in);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001511}
1512
1513STATIC mp_obj_t str_upper(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001514 return str_caseconv(unichar_toupper, self_in);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001515}
1516
Damien Georgefcc9cf62014-06-01 18:22:09 +01001517STATIC mp_obj_t str_uni_istype(bool (*f)(unichar), mp_obj_t self_in) {
Kim Bautersa3f4b832014-05-31 07:30:03 +01001518 GET_STR_DATA_LEN(self_in, self_data, self_len);
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001519
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001520 if (self_len == 0) {
1521 return mp_const_false; // default to False for empty str
1522 }
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001523
Damien Georgefcc9cf62014-06-01 18:22:09 +01001524 if (f != unichar_isupper && f != unichar_islower) {
Kim Bautersa3f4b832014-05-31 07:30:03 +01001525 for (int i = 0; i < self_len; i++) {
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001526 if (!f(*self_data++)) {
1527 return mp_const_false;
1528 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001529 }
1530 } else {
Kim Bautersa3f4b832014-05-31 07:30:03 +01001531 bool contains_alpha = false;
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001532
Kim Bautersa3f4b832014-05-31 07:30:03 +01001533 for (int i = 0; i < self_len; i++) { // only check alphanumeric characters
1534 if (unichar_isalpha(*self_data++)) {
1535 contains_alpha = true;
Damien Georgefcc9cf62014-06-01 18:22:09 +01001536 if (!f(*(self_data - 1))) { // -1 because we already incremented above
1537 return mp_const_false;
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001538 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001539 }
1540 }
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001541
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001542 if (!contains_alpha) {
1543 return mp_const_false;
1544 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001545 }
1546
1547 return mp_const_true;
1548}
1549
1550STATIC mp_obj_t str_isspace(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001551 return str_uni_istype(unichar_isspace, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001552}
1553
1554STATIC mp_obj_t str_isalpha(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001555 return str_uni_istype(unichar_isalpha, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001556}
1557
1558STATIC mp_obj_t str_isdigit(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001559 return str_uni_istype(unichar_isdigit, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001560}
1561
1562STATIC mp_obj_t str_isupper(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001563 return str_uni_istype(unichar_isupper, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001564}
1565
1566STATIC mp_obj_t str_islower(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001567 return str_uni_istype(unichar_islower, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001568}
1569
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001570#if MICROPY_CPYTHON_COMPAT
1571// These methods are superfluous in the presense of str() and bytes()
1572// constructors.
1573// TODO: should accept kwargs too
1574STATIC mp_obj_t bytes_decode(uint n_args, const mp_obj_t *args) {
1575 mp_obj_t new_args[2];
1576 if (n_args == 1) {
1577 new_args[0] = args[0];
1578 new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
1579 args = new_args;
1580 n_args++;
1581 }
1582 return str_make_new(NULL, n_args, 0, args);
1583}
1584
1585// TODO: should accept kwargs too
1586STATIC mp_obj_t str_encode(uint n_args, const mp_obj_t *args) {
1587 mp_obj_t new_args[2];
1588 if (n_args == 1) {
1589 new_args[0] = args[0];
1590 new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
1591 args = new_args;
1592 n_args++;
1593 }
1594 return bytes_make_new(NULL, n_args, 0, args);
1595}
1596#endif
1597
Damien George57a4b4f2014-04-18 22:29:21 +01001598STATIC machine_int_t str_get_buffer(mp_obj_t self_in, mp_buffer_info_t *bufinfo, int flags) {
1599 if (flags == MP_BUFFER_READ) {
Damien George2da98302014-03-09 19:58:18 +00001600 GET_STR_DATA_LEN(self_in, str_data, str_len);
1601 bufinfo->buf = (void*)str_data;
1602 bufinfo->len = str_len;
Damien George57a4b4f2014-04-18 22:29:21 +01001603 bufinfo->typecode = 'b';
Damien George2da98302014-03-09 19:58:18 +00001604 return 0;
1605 } else {
1606 // can't write to a string
1607 bufinfo->buf = NULL;
1608 bufinfo->len = 0;
Damien George57a4b4f2014-04-18 22:29:21 +01001609 bufinfo->typecode = -1;
Damien George2da98302014-03-09 19:58:18 +00001610 return 1;
1611 }
1612}
1613
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001614#if MICROPY_CPYTHON_COMPAT
1615STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(bytes_decode_obj, 1, 3, bytes_decode);
1616STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_encode_obj, 1, 3, str_encode);
1617#endif
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001618STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_find_obj, 2, 4, str_find);
xbe17a5a832014-03-23 23:31:58 -07001619STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rfind_obj, 2, 4, str_rfind);
xbe3d9a39e2014-04-08 11:42:19 -07001620STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_index_obj, 2, 4, str_index);
1621STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rindex_obj, 2, 4, str_rindex);
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001622STATIC MP_DEFINE_CONST_FUN_OBJ_2(str_join_obj, str_join);
1623STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_split_obj, 1, 3, str_split);
Paul Sokolovsky2a273652014-05-13 08:07:08 +03001624STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rsplit_obj, 1, 3, str_rsplit);
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +03001625STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_startswith_obj, 2, 3, str_startswith);
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +03001626STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_endswith_obj, 2, 3, str_endswith);
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001627STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_strip_obj, 1, 2, str_strip);
Paul Sokolovsky88107842014-04-26 06:20:08 +03001628STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_lstrip_obj, 1, 2, str_lstrip);
1629STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rstrip_obj, 1, 2, str_rstrip);
Damien George897fe0c2014-04-15 22:03:55 +01001630STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(str_format_obj, 1, mp_obj_str_format);
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001631STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_replace_obj, 3, 4, str_replace);
xbe9e1e8cd2014-03-12 22:57:16 -07001632STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_count_obj, 2, 4, str_count);
xbe613a8e32014-03-18 00:06:29 -07001633STATIC MP_DEFINE_CONST_FUN_OBJ_2(str_partition_obj, str_partition);
xbe4504ea82014-03-19 00:46:14 -07001634STATIC MP_DEFINE_CONST_FUN_OBJ_2(str_rpartition_obj, str_rpartition);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001635STATIC MP_DEFINE_CONST_FUN_OBJ_1(str_lower_obj, str_lower);
1636STATIC MP_DEFINE_CONST_FUN_OBJ_1(str_upper_obj, str_upper);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001637STATIC MP_DEFINE_CONST_FUN_OBJ_1(str_isspace_obj, str_isspace);
1638STATIC MP_DEFINE_CONST_FUN_OBJ_1(str_isalpha_obj, str_isalpha);
1639STATIC MP_DEFINE_CONST_FUN_OBJ_1(str_isdigit_obj, str_isdigit);
1640STATIC MP_DEFINE_CONST_FUN_OBJ_1(str_isupper_obj, str_isupper);
1641STATIC MP_DEFINE_CONST_FUN_OBJ_1(str_islower_obj, str_islower);
Damiend99b0522013-12-21 18:17:45 +00001642
Damien George9b196cd2014-03-26 21:47:19 +00001643STATIC const mp_map_elem_t str_locals_dict_table[] = {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001644#if MICROPY_CPYTHON_COMPAT
1645 { MP_OBJ_NEW_QSTR(MP_QSTR_decode), (mp_obj_t)&bytes_decode_obj },
1646 { MP_OBJ_NEW_QSTR(MP_QSTR_encode), (mp_obj_t)&str_encode_obj },
1647#endif
Damien George9b196cd2014-03-26 21:47:19 +00001648 { MP_OBJ_NEW_QSTR(MP_QSTR_find), (mp_obj_t)&str_find_obj },
1649 { MP_OBJ_NEW_QSTR(MP_QSTR_rfind), (mp_obj_t)&str_rfind_obj },
xbe3d9a39e2014-04-08 11:42:19 -07001650 { MP_OBJ_NEW_QSTR(MP_QSTR_index), (mp_obj_t)&str_index_obj },
1651 { MP_OBJ_NEW_QSTR(MP_QSTR_rindex), (mp_obj_t)&str_rindex_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001652 { MP_OBJ_NEW_QSTR(MP_QSTR_join), (mp_obj_t)&str_join_obj },
1653 { MP_OBJ_NEW_QSTR(MP_QSTR_split), (mp_obj_t)&str_split_obj },
Paul Sokolovsky2a273652014-05-13 08:07:08 +03001654 { MP_OBJ_NEW_QSTR(MP_QSTR_rsplit), (mp_obj_t)&str_rsplit_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001655 { MP_OBJ_NEW_QSTR(MP_QSTR_startswith), (mp_obj_t)&str_startswith_obj },
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +03001656 { MP_OBJ_NEW_QSTR(MP_QSTR_endswith), (mp_obj_t)&str_endswith_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001657 { MP_OBJ_NEW_QSTR(MP_QSTR_strip), (mp_obj_t)&str_strip_obj },
Paul Sokolovsky88107842014-04-26 06:20:08 +03001658 { MP_OBJ_NEW_QSTR(MP_QSTR_lstrip), (mp_obj_t)&str_lstrip_obj },
1659 { MP_OBJ_NEW_QSTR(MP_QSTR_rstrip), (mp_obj_t)&str_rstrip_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001660 { MP_OBJ_NEW_QSTR(MP_QSTR_format), (mp_obj_t)&str_format_obj },
1661 { MP_OBJ_NEW_QSTR(MP_QSTR_replace), (mp_obj_t)&str_replace_obj },
1662 { MP_OBJ_NEW_QSTR(MP_QSTR_count), (mp_obj_t)&str_count_obj },
1663 { MP_OBJ_NEW_QSTR(MP_QSTR_partition), (mp_obj_t)&str_partition_obj },
1664 { MP_OBJ_NEW_QSTR(MP_QSTR_rpartition), (mp_obj_t)&str_rpartition_obj },
Paul Sokolovsky69135212014-05-10 19:47:41 +03001665 { MP_OBJ_NEW_QSTR(MP_QSTR_lower), (mp_obj_t)&str_lower_obj },
1666 { MP_OBJ_NEW_QSTR(MP_QSTR_upper), (mp_obj_t)&str_upper_obj },
Kim Bautersa3f4b832014-05-31 07:30:03 +01001667 { MP_OBJ_NEW_QSTR(MP_QSTR_isspace), (mp_obj_t)&str_isspace_obj },
1668 { MP_OBJ_NEW_QSTR(MP_QSTR_isalpha), (mp_obj_t)&str_isalpha_obj },
1669 { MP_OBJ_NEW_QSTR(MP_QSTR_isdigit), (mp_obj_t)&str_isdigit_obj },
1670 { MP_OBJ_NEW_QSTR(MP_QSTR_isupper), (mp_obj_t)&str_isupper_obj },
1671 { MP_OBJ_NEW_QSTR(MP_QSTR_islower), (mp_obj_t)&str_islower_obj },
ian-v7a16fad2014-01-06 09:52:29 -08001672};
Damien George97209d32014-01-07 15:58:30 +00001673
Damien George9b196cd2014-03-26 21:47:19 +00001674STATIC MP_DEFINE_CONST_DICT(str_locals_dict, str_locals_dict_table);
1675
Damien George3e1a5c12014-03-29 13:43:38 +00001676const mp_obj_type_t mp_type_str = {
Damien Georgec5966122014-02-15 16:10:44 +00001677 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001678 .name = MP_QSTR_str,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001679 .print = str_print,
Paul Sokolovskybe020c22014-03-21 11:39:01 +02001680 .make_new = str_make_new,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001681 .binary_op = str_binary_op,
Damien George729f7b42014-04-17 22:10:53 +01001682 .subscr = str_subscr,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001683 .getiter = mp_obj_new_str_iterator,
Damien George2da98302014-03-09 19:58:18 +00001684 .buffer_p = { .get_buffer = str_get_buffer },
Damien George9b196cd2014-03-26 21:47:19 +00001685 .locals_dict = (mp_obj_t)&str_locals_dict,
Damiend99b0522013-12-21 18:17:45 +00001686};
1687
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001688// Reuses most of methods from str
Damien George3e1a5c12014-03-29 13:43:38 +00001689const mp_obj_type_t mp_type_bytes = {
Damien Georgec5966122014-02-15 16:10:44 +00001690 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001691 .name = MP_QSTR_bytes,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001692 .print = str_print,
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001693 .make_new = bytes_make_new,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001694 .binary_op = str_binary_op,
Damien George729f7b42014-04-17 22:10:53 +01001695 .subscr = str_subscr,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001696 .getiter = mp_obj_new_bytes_iterator,
Paul Sokolovsky7a70a3a2014-04-08 17:30:47 +03001697 .buffer_p = { .get_buffer = str_get_buffer },
Damien George9b196cd2014-03-26 21:47:19 +00001698 .locals_dict = (mp_obj_t)&str_locals_dict,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001699};
1700
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001701// the zero-length bytes
Damien George3e1a5c12014-03-29 13:43:38 +00001702STATIC const mp_obj_str_t empty_bytes_obj = {{&mp_type_bytes}, 0, 0, NULL};
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001703const mp_obj_t mp_const_empty_bytes = (mp_obj_t)&empty_bytes_obj;
1704
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001705mp_obj_t mp_obj_str_builder_start(const mp_obj_type_t *type, uint len, byte **data) {
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001706 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001707 o->base.type = type;
Damien George5fa93b62014-01-22 14:35:10 +00001708 o->len = len;
Paul Sokolovsky504e2332014-04-19 03:09:17 +03001709 o->hash = 0;
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001710 byte *p = m_new(byte, len + 1);
1711 o->data = p;
1712 *data = p;
Damiend99b0522013-12-21 18:17:45 +00001713 return o;
1714}
1715
Damien George5fa93b62014-01-22 14:35:10 +00001716mp_obj_t mp_obj_str_builder_end(mp_obj_t o_in) {
Damien George5fa93b62014-01-22 14:35:10 +00001717 mp_obj_str_t *o = o_in;
1718 o->hash = qstr_compute_hash(o->data, o->len);
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001719 byte *p = (byte*)o->data;
1720 p[o->len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
Damien George5fa93b62014-01-22 14:35:10 +00001721 return o;
1722}
1723
Damien Georgef600a6a2014-05-25 22:34:34 +01001724mp_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 +02001725 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001726 o->base.type = type;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001727 o->len = len;
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001728 if (data) {
1729 o->hash = qstr_compute_hash(data, len);
1730 byte *p = m_new(byte, len + 1);
1731 o->data = p;
1732 memcpy(p, data, len * sizeof(byte));
1733 p[len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
1734 }
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001735 return o;
1736}
1737
Damien George2617eeb2014-05-25 22:27:57 +01001738mp_obj_t mp_obj_new_str(const char* data, uint len, bool make_qstr_if_not_already) {
Damien Georgef600a6a2014-05-25 22:34:34 +01001739 if (make_qstr_if_not_already) {
1740 // use existing, or make a new qstr
Damien George2617eeb2014-05-25 22:27:57 +01001741 return MP_OBJ_NEW_QSTR(qstr_from_strn(data, len));
Damien George5fa93b62014-01-22 14:35:10 +00001742 } else {
Damien Georgef600a6a2014-05-25 22:34:34 +01001743 qstr q = qstr_find_strn(data, len);
1744 if (q != MP_QSTR_NULL) {
1745 // qstr with this data already exists
1746 return MP_OBJ_NEW_QSTR(q);
1747 } else {
1748 // no existing qstr, don't make one
1749 return mp_obj_new_str_of_type(&mp_type_str, (const byte*)data, len);
1750 }
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02001751 }
Damien George5fa93b62014-01-22 14:35:10 +00001752}
1753
Paul Sokolovskyb4efac12014-06-08 01:13:35 +03001754mp_obj_t mp_obj_str_intern(mp_obj_t str) {
1755 GET_STR_DATA_LEN(str, data, len);
1756 return MP_OBJ_NEW_QSTR(qstr_from_strn((const char*)data, len));
1757}
1758
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001759mp_obj_t mp_obj_new_bytes(const byte* data, uint len) {
Damien Georgef600a6a2014-05-25 22:34:34 +01001760 return mp_obj_new_str_of_type(&mp_type_bytes, data, len);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001761}
1762
Damien George5fa93b62014-01-22 14:35:10 +00001763bool mp_obj_str_equal(mp_obj_t s1, mp_obj_t s2) {
1764 if (MP_OBJ_IS_QSTR(s1) && MP_OBJ_IS_QSTR(s2)) {
1765 return s1 == s2;
1766 } else {
1767 GET_STR_HASH(s1, h1);
1768 GET_STR_HASH(s2, h2);
Paul Sokolovsky59e269c2014-04-14 01:43:01 +03001769 // If any of hashes is 0, it means it's not valid
1770 if (h1 != 0 && h2 != 0 && h1 != h2) {
Damien George5fa93b62014-01-22 14:35:10 +00001771 return false;
1772 }
1773 GET_STR_DATA_LEN(s1, d1, l1);
1774 GET_STR_DATA_LEN(s2, d2, l2);
1775 if (l1 != l2) {
1776 return false;
1777 }
Damien George1e708fe2014-01-23 18:27:51 +00001778 return memcmp(d1, d2, l1) == 0;
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02001779 }
Damien George5fa93b62014-01-22 14:35:10 +00001780}
1781
Damien Georgedeed0872014-04-06 11:11:15 +01001782STATIC void bad_implicit_conversion(mp_obj_t self_in) {
Damien Georgeea13f402014-04-05 18:32:08 +01001783 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 +00001784}
1785
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +03001786STATIC void arg_type_mixup() {
1787 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "Can't mix str and bytes arguments"));
1788}
1789
Damien George5fa93b62014-01-22 14:35:10 +00001790uint mp_obj_str_get_hash(mp_obj_t self_in) {
Paul Sokolovskyf130ca12014-04-13 05:41:00 +03001791 // TODO: This has too big overhead for hash accessor
1792 if (MP_OBJ_IS_STR(self_in) || MP_OBJ_IS_TYPE(self_in, &mp_type_bytes)) {
Damien George5fa93b62014-01-22 14:35:10 +00001793 GET_STR_HASH(self_in, h);
1794 return h;
1795 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001796 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001797 }
1798}
1799
1800uint mp_obj_str_get_len(mp_obj_t self_in) {
Damien Georgeee014112014-04-15 23:10:00 +01001801 // TODO This has a double check for the type, one in obj.c and one here
1802 if (MP_OBJ_IS_STR(self_in) || MP_OBJ_IS_TYPE(self_in, &mp_type_bytes)) {
Damien George5fa93b62014-01-22 14:35:10 +00001803 GET_STR_LEN(self_in, l);
1804 return l;
1805 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001806 bad_implicit_conversion(self_in);
1807 }
1808}
1809
1810// use this if you will anyway convert the string to a qstr
1811// will be more efficient for the case where it's already a qstr
1812qstr mp_obj_str_get_qstr(mp_obj_t self_in) {
1813 if (MP_OBJ_IS_QSTR(self_in)) {
1814 return MP_OBJ_QSTR_VALUE(self_in);
Damien George3e1a5c12014-03-29 13:43:38 +00001815 } else if (MP_OBJ_IS_TYPE(self_in, &mp_type_str)) {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001816 mp_obj_str_t *self = self_in;
1817 return qstr_from_strn((char*)self->data, self->len);
1818 } else {
1819 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001820 }
1821}
1822
1823// only use this function if you need the str data to be zero terminated
1824// at the moment all strings are zero terminated to help with C ASCIIZ compatibility
1825const char *mp_obj_str_get_str(mp_obj_t self_in) {
1826 if (MP_OBJ_IS_STR(self_in)) {
1827 GET_STR_DATA_LEN(self_in, s, l);
1828 (void)l; // len unused
1829 return (const char*)s;
1830 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001831 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001832 }
1833}
1834
Damien George698ec212014-02-08 18:17:23 +00001835const char *mp_obj_str_get_data(mp_obj_t self_in, uint *len) {
Paul Sokolovskyeea01182014-05-11 13:51:24 +03001836 if (is_str_or_bytes(self_in)) {
Damien George5fa93b62014-01-22 14:35:10 +00001837 GET_STR_DATA_LEN(self_in, s, l);
1838 *len = l;
Damien George698ec212014-02-08 18:17:23 +00001839 return (const char*)s;
Damien George5fa93b62014-01-22 14:35:10 +00001840 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001841 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001842 }
Damiend99b0522013-12-21 18:17:45 +00001843}
xyb8cfc9f02014-01-05 18:47:51 +08001844
1845/******************************************************************************/
1846/* str iterator */
1847
1848typedef struct _mp_obj_str_it_t {
1849 mp_obj_base_t base;
Damien George5fa93b62014-01-22 14:35:10 +00001850 mp_obj_t str;
xyb8cfc9f02014-01-05 18:47:51 +08001851 machine_uint_t cur;
1852} mp_obj_str_it_t;
1853
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001854STATIC mp_obj_t str_it_iternext(mp_obj_t self_in) {
xyb8cfc9f02014-01-05 18:47:51 +08001855 mp_obj_str_it_t *self = self_in;
Damien George5fa93b62014-01-22 14:35:10 +00001856 GET_STR_DATA_LEN(self->str, str, len);
1857 if (self->cur < len) {
Damien George2617eeb2014-05-25 22:27:57 +01001858 mp_obj_t o_out = mp_obj_new_str((const char*)str + self->cur, 1, true);
xyb8cfc9f02014-01-05 18:47:51 +08001859 self->cur += 1;
1860 return o_out;
1861 } else {
Damien Georgeea8d06c2014-04-17 23:19:36 +01001862 return MP_OBJ_STOP_ITERATION;
xyb8cfc9f02014-01-05 18:47:51 +08001863 }
1864}
1865
Damien George3e1a5c12014-03-29 13:43:38 +00001866STATIC const mp_obj_type_t mp_type_str_it = {
Damien Georgec5966122014-02-15 16:10:44 +00001867 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001868 .name = MP_QSTR_iterator,
Paul Sokolovskyf7eaf602014-03-30 22:00:12 +03001869 .getiter = mp_identity,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001870 .iternext = str_it_iternext,
xyb8cfc9f02014-01-05 18:47:51 +08001871};
1872
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001873STATIC mp_obj_t bytes_it_iternext(mp_obj_t self_in) {
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001874 mp_obj_str_it_t *self = self_in;
1875 GET_STR_DATA_LEN(self->str, str, len);
1876 if (self->cur < len) {
Damien George7c9c6672014-01-25 00:17:36 +00001877 mp_obj_t o_out = MP_OBJ_NEW_SMALL_INT((mp_small_int_t)str[self->cur]);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001878 self->cur += 1;
1879 return o_out;
1880 } else {
Damien Georgeea8d06c2014-04-17 23:19:36 +01001881 return MP_OBJ_STOP_ITERATION;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001882 }
1883}
1884
Damien George3e1a5c12014-03-29 13:43:38 +00001885STATIC const mp_obj_type_t mp_type_bytes_it = {
Damien Georgec5966122014-02-15 16:10:44 +00001886 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001887 .name = MP_QSTR_iterator,
Paul Sokolovskyf7eaf602014-03-30 22:00:12 +03001888 .getiter = mp_identity,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001889 .iternext = bytes_it_iternext,
1890};
1891
1892mp_obj_t mp_obj_new_str_iterator(mp_obj_t str) {
xyb8cfc9f02014-01-05 18:47:51 +08001893 mp_obj_str_it_t *o = m_new_obj(mp_obj_str_it_t);
Damien George3e1a5c12014-03-29 13:43:38 +00001894 o->base.type = &mp_type_str_it;
xyb8cfc9f02014-01-05 18:47:51 +08001895 o->str = str;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001896 o->cur = 0;
1897 return o;
1898}
1899
1900mp_obj_t mp_obj_new_bytes_iterator(mp_obj_t str) {
1901 mp_obj_str_it_t *o = m_new_obj(mp_obj_str_it_t);
Damien George3e1a5c12014-03-29 13:43:38 +00001902 o->base.type = &mp_type_bytes_it;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001903 o->str = str;
1904 o->cur = 0;
xyb8cfc9f02014-01-05 18:47:51 +08001905 return o;
1906}