blob: f9cc27344716c6a78e3ecbdb389e17f19826f0e7 [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 Sokolovsky2ec38a12014-06-13 21:23:00 +030067void mp_str_print_quoted(void (*print)(void *env, const char *fmt, ...), void *env,
68 const byte *str_data, uint str_len, bool is_bytes) {
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020069 // this escapes characters, but it will be very slow to print (calling print many times)
70 bool has_single_quote = false;
71 bool has_double_quote = false;
Chris Angelico48674132014-06-04 03:26:40 +100072 for (const byte *s = str_data, *top = str_data + str_len; !has_double_quote && s < top; s++) {
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020073 if (*s == '\'') {
74 has_single_quote = true;
75 } else if (*s == '"') {
76 has_double_quote = true;
77 }
78 }
79 int quote_char = '\'';
80 if (has_single_quote && !has_double_quote) {
81 quote_char = '"';
82 }
83 print(env, "%c", quote_char);
84 for (const byte *s = str_data, *top = str_data + str_len; s < top; s++) {
85 if (*s == quote_char) {
86 print(env, "\\%c", quote_char);
87 } else if (*s == '\\') {
88 print(env, "\\\\");
Paul Sokolovsky2ec38a12014-06-13 21:23:00 +030089 } else if (*s >= 0x20 && *s != 0x7f && (!is_bytes || *s < 0x80)) {
90 // In strings, anything which is not ascii control character
91 // is printed as is, this includes characters in range 0x80-0xff
92 // (which can be non-Latin letters, etc.)
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020093 print(env, "%c", *s);
94 } else if (*s == '\n') {
95 print(env, "\\n");
Andrew Scheller12968fb2014-04-08 02:42:50 +010096 } else if (*s == '\r') {
97 print(env, "\\r");
98 } else if (*s == '\t') {
99 print(env, "\\t");
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +0200100 } else {
101 print(env, "\\x%02x", *s);
102 }
103 }
104 print(env, "%c", quote_char);
105}
106
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200107STATIC 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 +0000108 GET_STR_DATA_LEN(self_in, str_data, str_len);
Damien George3e1a5c12014-03-29 13:43:38 +0000109 bool is_bytes = MP_OBJ_IS_TYPE(self_in, &mp_type_bytes);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +0200110 if (kind == PRINT_STR && !is_bytes) {
Damien George5fa93b62014-01-22 14:35:10 +0000111 print(env, "%.*s", str_len, str_data);
Paul Sokolovsky76d982e2014-01-13 19:19:16 +0200112 } else {
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +0200113 if (is_bytes) {
114 print(env, "b");
115 }
Paul Sokolovsky2ec38a12014-06-13 21:23:00 +0300116 mp_str_print_quoted(print, env, str_data, str_len, is_bytes);
Paul Sokolovsky76d982e2014-01-13 19:19:16 +0200117 }
Damiend99b0522013-12-21 18:17:45 +0000118}
119
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200120STATIC 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 +0300121#if MICROPY_CPYTHON_COMPAT
122 if (n_kw != 0) {
123 mp_arg_error_unimpl_kw();
124 }
125#endif
126
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200127 switch (n_args) {
128 case 0:
129 return MP_OBJ_NEW_QSTR(MP_QSTR_);
130
131 case 1:
132 {
133 vstr_t *vstr = vstr_new();
134 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, vstr, args[0], PRINT_STR);
Damien George2617eeb2014-05-25 22:27:57 +0100135 mp_obj_t s = mp_obj_new_str(vstr->buf, vstr->len, false);
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200136 vstr_free(vstr);
137 return s;
138 }
139
140 case 2:
141 case 3:
142 {
143 // TODO: validate 2nd/3rd args
Damien George3e1a5c12014-03-29 13:43:38 +0000144 if (!MP_OBJ_IS_TYPE(args[0], &mp_type_bytes)) {
Damien Georgeea13f402014-04-05 18:32:08 +0100145 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "bytes expected"));
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200146 }
147 GET_STR_DATA_LEN(args[0], str_data, str_len);
148 GET_STR_HASH(args[0], str_hash);
Damien Georgef600a6a2014-05-25 22:34:34 +0100149 mp_obj_str_t *o = mp_obj_new_str_of_type(&mp_type_str, NULL, str_len);
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200150 o->data = str_data;
151 o->hash = str_hash;
152 return o;
153 }
154
155 default:
Damien Georgeea13f402014-04-05 18:32:08 +0100156 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "str takes at most 3 arguments"));
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200157 }
158}
159
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200160STATIC mp_obj_t bytes_make_new(mp_obj_t type_in, uint n_args, uint n_kw, const mp_obj_t *args) {
161 if (n_args == 0) {
162 return mp_const_empty_bytes;
163 }
164
Paul Sokolovskyb473d0a2014-05-06 19:30:30 +0300165#if MICROPY_CPYTHON_COMPAT
166 if (n_kw != 0) {
167 mp_arg_error_unimpl_kw();
168 }
169#endif
170
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200171 if (MP_OBJ_IS_STR(args[0])) {
172 if (n_args < 2 || n_args > 3) {
173 goto wrong_args;
174 }
175 GET_STR_DATA_LEN(args[0], str_data, str_len);
176 GET_STR_HASH(args[0], str_hash);
Damien Georgef600a6a2014-05-25 22:34:34 +0100177 mp_obj_str_t *o = mp_obj_new_str_of_type(&mp_type_bytes, NULL, str_len);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200178 o->data = str_data;
179 o->hash = str_hash;
180 return o;
181 }
182
183 if (n_args > 1) {
184 goto wrong_args;
185 }
186
187 if (MP_OBJ_IS_SMALL_INT(args[0])) {
188 uint len = MP_OBJ_SMALL_INT_VALUE(args[0]);
189 byte *data;
190
Damien George3e1a5c12014-03-29 13:43:38 +0000191 mp_obj_t o = mp_obj_str_builder_start(&mp_type_bytes, len, &data);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200192 memset(data, 0, len);
193 return mp_obj_str_builder_end(o);
194 }
195
196 int len;
197 byte *data;
198 vstr_t *vstr = NULL;
199 mp_obj_t o = NULL;
200 // Try to create array of exact len if initializer len is known
201 mp_obj_t len_in = mp_obj_len_maybe(args[0]);
202 if (len_in == MP_OBJ_NULL) {
203 len = -1;
204 vstr = vstr_new();
205 } else {
206 len = MP_OBJ_SMALL_INT_VALUE(len_in);
Damien George3e1a5c12014-03-29 13:43:38 +0000207 o = mp_obj_str_builder_start(&mp_type_bytes, len, &data);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200208 }
209
Damien Georged17926d2014-03-30 13:35:08 +0100210 mp_obj_t iterable = mp_getiter(args[0]);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200211 mp_obj_t item;
Damien Georgeea8d06c2014-04-17 23:19:36 +0100212 while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200213 if (len == -1) {
214 vstr_add_char(vstr, MP_OBJ_SMALL_INT_VALUE(item));
215 } else {
216 *data++ = MP_OBJ_SMALL_INT_VALUE(item);
217 }
218 }
219
220 if (len == -1) {
221 vstr_shrink(vstr);
222 // TODO: Optimize, borrow buffer from vstr
223 len = vstr_len(vstr);
Damien George3e1a5c12014-03-29 13:43:38 +0000224 o = mp_obj_str_builder_start(&mp_type_bytes, len, &data);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200225 memcpy(data, vstr_str(vstr), len);
226 vstr_free(vstr);
227 }
228
229 return mp_obj_str_builder_end(o);
230
231wrong_args:
Damien Georgeea13f402014-04-05 18:32:08 +0100232 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "wrong number of arguments"));
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200233}
234
Damien George55baff42014-01-21 21:40:13 +0000235// like strstr but with specified length and allows \0 bytes
236// TODO replace with something more efficient/standard
xbe17a5a832014-03-23 23:31:58 -0700237STATIC 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 +0000238 if (hlen >= nlen) {
xbe17a5a832014-03-23 23:31:58 -0700239 machine_uint_t str_index, str_index_end;
240 if (direction > 0) {
241 str_index = 0;
242 str_index_end = hlen - nlen;
243 } else {
244 str_index = hlen - nlen;
245 str_index_end = 0;
246 }
247 for (;;) {
248 if (memcmp(&haystack[str_index], needle, nlen) == 0) {
249 //found
250 return haystack + str_index;
Damien George55baff42014-01-21 21:40:13 +0000251 }
xbe17a5a832014-03-23 23:31:58 -0700252 if (str_index == str_index_end) {
253 //not found
254 break;
Damien George55baff42014-01-21 21:40:13 +0000255 }
xbe17a5a832014-03-23 23:31:58 -0700256 str_index += direction;
Damien George55baff42014-01-21 21:40:13 +0000257 }
258 }
259 return NULL;
260}
261
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200262STATIC 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 +0000263 GET_STR_DATA_LEN(lhs_in, lhs_data, lhs_len);
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300264 mp_obj_type_t *lhs_type = mp_obj_get_type(lhs_in);
265 mp_obj_type_t *rhs_type = mp_obj_get_type(rhs_in);
Damiend99b0522013-12-21 18:17:45 +0000266 switch (op) {
Damien Georged17926d2014-03-30 13:35:08 +0100267 case MP_BINARY_OP_ADD:
268 case MP_BINARY_OP_INPLACE_ADD:
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300269 if (lhs_type == rhs_type) {
270 // add 2 strings or bytes
Damien George5fa93b62014-01-22 14:35:10 +0000271
272 GET_STR_DATA_LEN(rhs_in, rhs_data, rhs_len);
Damien George55baff42014-01-21 21:40:13 +0000273 int alloc_len = lhs_len + rhs_len;
Damien George5fa93b62014-01-22 14:35:10 +0000274
275 /* code for making qstr
Damien George55baff42014-01-21 21:40:13 +0000276 byte *q_ptr;
277 byte *val = qstr_build_start(alloc_len, &q_ptr);
278 memcpy(val, lhs_data, lhs_len);
279 memcpy(val + lhs_len, rhs_data, rhs_len);
Damien George5fa93b62014-01-22 14:35:10 +0000280 return MP_OBJ_NEW_QSTR(qstr_build_end(q_ptr));
281 */
282
283 // code for non-qstr
284 byte *data;
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300285 mp_obj_t s = mp_obj_str_builder_start(lhs_type, alloc_len, &data);
Damien George5fa93b62014-01-22 14:35:10 +0000286 memcpy(data, lhs_data, lhs_len);
287 memcpy(data + lhs_len, rhs_data, rhs_len);
288 return mp_obj_str_builder_end(s);
Damiend99b0522013-12-21 18:17:45 +0000289 }
290 break;
Damien George5fa93b62014-01-22 14:35:10 +0000291
Damien Georged17926d2014-03-30 13:35:08 +0100292 case MP_BINARY_OP_IN:
John R. Lentonc1bef212014-01-11 12:39:33 +0000293 /* NOTE `a in b` is `b.__contains__(a)` */
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300294 if (lhs_type == rhs_type) {
Damien George5fa93b62014-01-22 14:35:10 +0000295 GET_STR_DATA_LEN(rhs_in, rhs_data, rhs_len);
xbe17a5a832014-03-23 23:31:58 -0700296 return MP_BOOL(find_subbytes(lhs_data, lhs_len, rhs_data, rhs_len, 1) != NULL);
John R. Lentonc1bef212014-01-11 12:39:33 +0000297 }
298 break;
Damien George5fa93b62014-01-22 14:35:10 +0000299
Damien Georged0a5bf32014-05-10 13:55:11 +0100300 case MP_BINARY_OP_MULTIPLY: {
Paul Sokolovsky545591a2014-01-21 00:27:33 +0200301 if (!MP_OBJ_IS_SMALL_INT(rhs_in)) {
Damien George6ac5dce2014-05-21 19:42:43 +0100302 return MP_OBJ_NULL; // op not supported
Paul Sokolovsky545591a2014-01-21 00:27:33 +0200303 }
304 int n = MP_OBJ_SMALL_INT_VALUE(rhs_in);
Damien George5fa93b62014-01-22 14:35:10 +0000305 byte *data;
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300306 mp_obj_t s = mp_obj_str_builder_start(lhs_type, lhs_len * n, &data);
Damien George5fa93b62014-01-22 14:35:10 +0000307 mp_seq_multiply(lhs_data, sizeof(*lhs_data), lhs_len, n, data);
308 return mp_obj_str_builder_end(s);
Paul Sokolovsky545591a2014-01-21 00:27:33 +0200309 }
Paul Sokolovsky87e85b72014-02-02 08:24:07 +0200310
Paul Sokolovsky4db727a2014-03-31 21:18:28 +0300311 case MP_BINARY_OP_MODULO: {
312 mp_obj_t *args;
313 uint n_args;
Paul Sokolovsky75ce9252014-06-05 20:02:15 +0300314 mp_obj_t dict = MP_OBJ_NULL;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +0300315 if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_tuple)) {
316 // TODO: Support tuple subclasses?
317 mp_obj_tuple_get(rhs_in, &n_args, &args);
Paul Sokolovsky75ce9252014-06-05 20:02:15 +0300318 } else if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_dict)) {
319 args = NULL;
320 n_args = 0;
321 dict = rhs_in;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +0300322 } else {
323 args = &rhs_in;
324 n_args = 1;
325 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +0300326 return str_modulo_format(lhs_in, n_args, args, dict);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +0300327 }
328
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300329 //case MP_BINARY_OP_NOT_EQUAL: // This is never passed here
330 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 +0100331 case MP_BINARY_OP_LESS:
332 case MP_BINARY_OP_LESS_EQUAL:
333 case MP_BINARY_OP_MORE:
334 case MP_BINARY_OP_MORE_EQUAL:
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300335 if (lhs_type == rhs_type) {
Paul Sokolovsky87e85b72014-02-02 08:24:07 +0200336 GET_STR_DATA_LEN(rhs_in, rhs_data, rhs_len);
337 return MP_BOOL(mp_seq_cmp_bytes(op, lhs_data, lhs_len, rhs_data, rhs_len));
338 }
Paul Sokolovsky70328e42014-05-15 20:58:40 +0300339 if (lhs_type == &mp_type_bytes) {
340 mp_buffer_info_t bufinfo;
341 if (!mp_get_buffer(rhs_in, &bufinfo, MP_BUFFER_READ)) {
342 goto uncomparable;
343 }
344 return MP_BOOL(mp_seq_cmp_bytes(op, lhs_data, lhs_len, bufinfo.buf, bufinfo.len));
345 }
346uncomparable:
347 if (op == MP_BINARY_OP_EQUAL) {
348 return mp_const_false;
349 }
Damiend99b0522013-12-21 18:17:45 +0000350 }
351
Damien George6ac5dce2014-05-21 19:42:43 +0100352 return MP_OBJ_NULL; // op not supported
Damiend99b0522013-12-21 18:17:45 +0000353}
354
Damien George729f7b42014-04-17 22:10:53 +0100355STATIC 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 +0300356 mp_obj_type_t *type = mp_obj_get_type(self_in);
Damien George729f7b42014-04-17 22:10:53 +0100357 GET_STR_DATA_LEN(self_in, self_data, self_len);
358 if (value == MP_OBJ_SENTINEL) {
359 // load
Damien Georgefb510b32014-06-01 13:32:54 +0100360#if MICROPY_PY_BUILTINS_SLICE
Damien George729f7b42014-04-17 22:10:53 +0100361 if (MP_OBJ_IS_TYPE(index, &mp_type_slice)) {
Paul Sokolovskyde4b9322014-05-25 21:21:57 +0300362 mp_bound_slice_t slice;
363 if (!mp_seq_get_fast_slice_indexes(self_len, index, &slice)) {
Paul Sokolovsky5fd5af92014-05-25 22:12:56 +0300364 nlr_raise(mp_obj_new_exception_msg(&mp_type_NotImplementedError,
Damien George11de8392014-06-05 18:57:38 +0100365 "only slices with step=1 (aka None) are supported"));
Damien George729f7b42014-04-17 22:10:53 +0100366 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100367 return mp_obj_new_str_of_type(type, self_data + slice.start, slice.stop - slice.start);
Damien George729f7b42014-04-17 22:10:53 +0100368 }
369#endif
Damien George729f7b42014-04-17 22:10:53 +0100370 uint index_val = mp_get_index(type, self_len, index, false);
371 if (type == &mp_type_bytes) {
372 return MP_OBJ_NEW_SMALL_INT((mp_small_int_t)self_data[index_val]);
373 } else {
Damien George2617eeb2014-05-25 22:27:57 +0100374 return mp_obj_new_str((char*)self_data + index_val, 1, true);
Damien George729f7b42014-04-17 22:10:53 +0100375 }
376 } else {
Damien George6ac5dce2014-05-21 19:42:43 +0100377 return MP_OBJ_NULL; // op not supported
Damien George729f7b42014-04-17 22:10:53 +0100378 }
379}
380
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200381STATIC mp_obj_t str_join(mp_obj_t self_in, mp_obj_t arg) {
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300382 assert(is_str_or_bytes(self_in));
383 const mp_obj_type_t *self_type = mp_obj_get_type(self_in);
Damiend99b0522013-12-21 18:17:45 +0000384
Damien Georgefe8fb912014-01-02 16:36:09 +0000385 // get separation string
Damien George5fa93b62014-01-22 14:35:10 +0000386 GET_STR_DATA_LEN(self_in, sep_str, sep_len);
Damien Georgefe8fb912014-01-02 16:36:09 +0000387
388 // process args
Damiend99b0522013-12-21 18:17:45 +0000389 uint seq_len;
390 mp_obj_t *seq_items;
Damien George07ddab52014-03-29 13:15:08 +0000391 if (MP_OBJ_IS_TYPE(arg, &mp_type_tuple)) {
Damiend99b0522013-12-21 18:17:45 +0000392 mp_obj_tuple_get(arg, &seq_len, &seq_items);
Damiend99b0522013-12-21 18:17:45 +0000393 } else {
Damien Georgea157e4c2014-04-09 19:17:53 +0100394 if (!MP_OBJ_IS_TYPE(arg, &mp_type_list)) {
395 // arg is not a list, try to convert it to one
Paul Sokolovsky881d9af2014-04-10 01:42:40 +0300396 // TODO: Try to optimize?
Damien Georgea157e4c2014-04-09 19:17:53 +0100397 arg = mp_type_list.make_new((mp_obj_t)&mp_type_list, 1, 0, &arg);
398 }
399 mp_obj_list_get(arg, &seq_len, &seq_items);
Damiend99b0522013-12-21 18:17:45 +0000400 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000401
402 // count required length
403 int required_len = 0;
Damiend99b0522013-12-21 18:17:45 +0000404 for (int i = 0; i < seq_len; i++) {
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300405 if (mp_obj_get_type(seq_items[i]) != self_type) {
406 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
407 "join expects a list of str/bytes objects consistent with self object"));
Damiend99b0522013-12-21 18:17:45 +0000408 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000409 if (i > 0) {
410 required_len += sep_len;
411 }
Damien George5fa93b62014-01-22 14:35:10 +0000412 GET_STR_LEN(seq_items[i], l);
413 required_len += l;
Damiend99b0522013-12-21 18:17:45 +0000414 }
415
416 // make joined string
Damien George5fa93b62014-01-22 14:35:10 +0000417 byte *data;
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300418 mp_obj_t joined_str = mp_obj_str_builder_start(self_type, required_len, &data);
Damiend99b0522013-12-21 18:17:45 +0000419 for (int i = 0; i < seq_len; i++) {
Damiend99b0522013-12-21 18:17:45 +0000420 if (i > 0) {
Damien George5fa93b62014-01-22 14:35:10 +0000421 memcpy(data, sep_str, sep_len);
422 data += sep_len;
Damiend99b0522013-12-21 18:17:45 +0000423 }
Damien George5fa93b62014-01-22 14:35:10 +0000424 GET_STR_DATA_LEN(seq_items[i], s, l);
425 memcpy(data, s, l);
426 data += l;
Damiend99b0522013-12-21 18:17:45 +0000427 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000428
429 // return joined string
Damien George5fa93b62014-01-22 14:35:10 +0000430 return mp_obj_str_builder_end(joined_str);
Damiend99b0522013-12-21 18:17:45 +0000431}
432
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200433#define is_ws(c) ((c) == ' ' || (c) == '\t')
434
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200435STATIC mp_obj_t str_split(uint n_args, const mp_obj_t *args) {
Paul Sokolovskybfb88192014-05-11 21:17:28 +0300436 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Damien Georgedeed0872014-04-06 11:11:15 +0100437 machine_int_t splits = -1;
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200438 mp_obj_t sep = mp_const_none;
439 if (n_args > 1) {
440 sep = args[1];
441 if (n_args > 2) {
Damien Georgedeed0872014-04-06 11:11:15 +0100442 splits = mp_obj_get_int(args[2]);
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200443 }
444 }
Damien Georgedeed0872014-04-06 11:11:15 +0100445
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200446 mp_obj_t res = mp_obj_new_list(0, NULL);
Damien George5fa93b62014-01-22 14:35:10 +0000447 GET_STR_DATA_LEN(args[0], s, len);
448 const byte *top = s + len;
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200449
Damien Georgedeed0872014-04-06 11:11:15 +0100450 if (sep == mp_const_none) {
451 // sep not given, so separate on whitespace
452
453 // Initial whitespace is not counted as split, so we pre-do it
Damien George5fa93b62014-01-22 14:35:10 +0000454 while (s < top && is_ws(*s)) s++;
Damien Georgedeed0872014-04-06 11:11:15 +0100455 while (s < top && splits != 0) {
456 const byte *start = s;
457 while (s < top && !is_ws(*s)) s++;
Damien Georgef600a6a2014-05-25 22:34:34 +0100458 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, s - start));
Damien Georgedeed0872014-04-06 11:11:15 +0100459 if (s >= top) {
460 break;
461 }
462 while (s < top && is_ws(*s)) s++;
463 if (splits > 0) {
464 splits--;
465 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200466 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200467
Damien Georgedeed0872014-04-06 11:11:15 +0100468 if (s < top) {
Damien Georgef600a6a2014-05-25 22:34:34 +0100469 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, s, top - s));
Damien Georgedeed0872014-04-06 11:11:15 +0100470 }
471
472 } else {
473 // sep given
474
475 uint sep_len;
476 const char *sep_str = mp_obj_str_get_data(sep, &sep_len);
477
478 if (sep_len == 0) {
479 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
480 }
481
482 for (;;) {
483 const byte *start = s;
484 for (;;) {
485 if (splits == 0 || s + sep_len > top) {
486 s = top;
487 break;
488 } else if (memcmp(s, sep_str, sep_len) == 0) {
489 break;
490 }
491 s++;
492 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100493 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, s - start));
Damien Georgedeed0872014-04-06 11:11:15 +0100494 if (s >= top) {
495 break;
496 }
497 s += sep_len;
498 if (splits > 0) {
499 splits--;
500 }
501 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200502 }
503
504 return res;
505}
506
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300507STATIC mp_obj_t str_rsplit(uint n_args, const mp_obj_t *args) {
508 if (n_args < 3) {
509 // If we don't have split limit, it doesn't matter from which side
510 // we split.
511 return str_split(n_args, args);
512 }
513 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
514 mp_obj_t sep = args[1];
515 GET_STR_DATA_LEN(args[0], s, len);
516
517 machine_int_t splits = mp_obj_get_int(args[2]);
518 machine_int_t org_splits = splits;
519 // Preallocate list to the max expected # of elements, as we
520 // will fill it from the end.
521 mp_obj_list_t *res = mp_obj_new_list(splits + 1, NULL);
522 int idx = splits;
523
524 if (sep == mp_const_none) {
Chris Angelico9ab8ab22014-06-04 05:04:23 +1000525 assert(!"TODO: rsplit(None,n) not implemented");
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300526 } else {
527 uint sep_len;
528 const char *sep_str = mp_obj_str_get_data(sep, &sep_len);
529
530 if (sep_len == 0) {
531 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
532 }
533
534 const byte *beg = s;
535 const byte *last = s + len;
536 for (;;) {
537 s = last - sep_len;
538 for (;;) {
539 if (splits == 0 || s < beg) {
540 break;
541 } else if (memcmp(s, sep_str, sep_len) == 0) {
542 break;
543 }
544 s--;
545 }
546 if (s < beg || splits == 0) {
Damien Georgef600a6a2014-05-25 22:34:34 +0100547 res->items[idx] = mp_obj_new_str_of_type(self_type, beg, last - beg);
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300548 break;
549 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100550 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 +0300551 last = s;
552 if (splits > 0) {
553 splits--;
554 }
555 }
556 if (idx != 0) {
557 // We split less parts than split limit, now go cleanup surplus
558 int used = org_splits + 1 - idx;
559 memcpy(res->items, &res->items[idx], used * sizeof(mp_obj_t));
560 mp_seq_clear(res->items, used, res->alloc, sizeof(*res->items));
561 res->len = used;
562 }
563 }
564
565 return res;
566}
567
568
xbe3d9a39e2014-04-08 11:42:19 -0700569STATIC 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 +0000570 assert(2 <= n_args && n_args <= 4);
Damien George5fa93b62014-01-22 14:35:10 +0000571 assert(MP_OBJ_IS_STR(args[0]));
572 assert(MP_OBJ_IS_STR(args[1]));
John R. Lentone8204912014-01-12 21:53:52 +0000573
Damien George5fa93b62014-01-22 14:35:10 +0000574 GET_STR_DATA_LEN(args[0], haystack, haystack_len);
575 GET_STR_DATA_LEN(args[1], needle, needle_len);
John R. Lentone8204912014-01-12 21:53:52 +0000576
xbec5538882014-03-16 17:58:35 -0700577 machine_uint_t start = 0;
578 machine_uint_t end = haystack_len;
John R. Lentone8204912014-01-12 21:53:52 +0000579 if (n_args >= 3 && args[2] != mp_const_none) {
Damien George3e1a5c12014-03-29 13:43:38 +0000580 start = mp_get_index(&mp_type_str, haystack_len, args[2], true);
John R. Lentone8204912014-01-12 21:53:52 +0000581 }
582 if (n_args >= 4 && args[3] != mp_const_none) {
Damien George3e1a5c12014-03-29 13:43:38 +0000583 end = mp_get_index(&mp_type_str, haystack_len, args[3], true);
John R. Lentone8204912014-01-12 21:53:52 +0000584 }
585
xbe17a5a832014-03-23 23:31:58 -0700586 const byte *p = find_subbytes(haystack + start, end - start, needle, needle_len, direction);
Damien George23005372014-01-13 19:39:01 +0000587 if (p == NULL) {
588 // not found
xbe3d9a39e2014-04-08 11:42:19 -0700589 if (is_index) {
590 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "substring not found"));
591 } else {
592 return MP_OBJ_NEW_SMALL_INT(-1);
593 }
Damien George23005372014-01-13 19:39:01 +0000594 } else {
595 // found
xbe17a5a832014-03-23 23:31:58 -0700596 return MP_OBJ_NEW_SMALL_INT(p - haystack);
John R. Lentone8204912014-01-12 21:53:52 +0000597 }
John R. Lentone8204912014-01-12 21:53:52 +0000598}
599
xbe17a5a832014-03-23 23:31:58 -0700600STATIC mp_obj_t str_find(uint n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700601 return str_finder(n_args, args, 1, false);
xbe17a5a832014-03-23 23:31:58 -0700602}
603
604STATIC mp_obj_t str_rfind(uint n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700605 return str_finder(n_args, args, -1, false);
606}
607
608STATIC mp_obj_t str_index(uint n_args, const mp_obj_t *args) {
609 return str_finder(n_args, args, 1, true);
610}
611
612STATIC mp_obj_t str_rindex(uint n_args, const mp_obj_t *args) {
613 return str_finder(n_args, args, -1, true);
xbe17a5a832014-03-23 23:31:58 -0700614}
615
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200616// TODO: (Much) more variety in args
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300617STATIC mp_obj_t str_startswith(uint n_args, const mp_obj_t *args) {
618 GET_STR_DATA_LEN(args[0], str, str_len);
619 GET_STR_DATA_LEN(args[1], prefix, prefix_len);
620 uint index_val = 0;
621 if (n_args > 2) {
622 index_val = mp_get_index(&mp_type_str, str_len, args[2], true);
623 }
624 if (prefix_len + index_val > str_len) {
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200625 return mp_const_false;
626 }
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300627 return MP_BOOL(memcmp(str + index_val, prefix, prefix_len) == 0);
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200628}
629
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +0300630STATIC mp_obj_t str_endswith(uint n_args, const mp_obj_t *args) {
631 GET_STR_DATA_LEN(args[0], str, str_len);
632 GET_STR_DATA_LEN(args[1], suffix, suffix_len);
633 assert(n_args == 2);
634
635 if (suffix_len > str_len) {
636 return mp_const_false;
637 }
638 return MP_BOOL(memcmp(str + (str_len - suffix_len), suffix, suffix_len) == 0);
639}
640
Paul Sokolovsky88107842014-04-26 06:20:08 +0300641enum { LSTRIP, RSTRIP, STRIP };
642
643STATIC mp_obj_t str_uni_strip(int type, uint n_args, const mp_obj_t *args) {
xbe7b0f39f2014-01-08 14:23:45 -0800644 assert(1 <= n_args && n_args <= 2);
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300645 assert(is_str_or_bytes(args[0]));
646 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Damien George5fa93b62014-01-22 14:35:10 +0000647
648 const byte *chars_to_del;
649 uint chars_to_del_len;
650 static const byte whitespace[] = " \t\n\r\v\f";
xbe7b0f39f2014-01-08 14:23:45 -0800651
652 if (n_args == 1) {
653 chars_to_del = whitespace;
Damien George5fa93b62014-01-22 14:35:10 +0000654 chars_to_del_len = sizeof(whitespace);
xbe7b0f39f2014-01-08 14:23:45 -0800655 } else {
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300656 if (mp_obj_get_type(args[1]) != self_type) {
657 arg_type_mixup();
658 }
Damien George5fa93b62014-01-22 14:35:10 +0000659 GET_STR_DATA_LEN(args[1], s, l);
660 chars_to_del = s;
661 chars_to_del_len = l;
xbe7b0f39f2014-01-08 14:23:45 -0800662 }
663
Damien George5fa93b62014-01-22 14:35:10 +0000664 GET_STR_DATA_LEN(args[0], orig_str, orig_str_len);
xbe7b0f39f2014-01-08 14:23:45 -0800665
xbec5538882014-03-16 17:58:35 -0700666 machine_uint_t first_good_char_pos = 0;
xbe7b0f39f2014-01-08 14:23:45 -0800667 bool first_good_char_pos_set = false;
xbec5538882014-03-16 17:58:35 -0700668 machine_uint_t last_good_char_pos = 0;
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300669 machine_uint_t i = 0;
670 machine_int_t delta = 1;
671 if (type == RSTRIP) {
672 i = orig_str_len - 1;
673 delta = -1;
674 }
675 for (machine_uint_t len = orig_str_len; len > 0; len--) {
xbe17a5a832014-03-23 23:31:58 -0700676 if (find_subbytes(chars_to_del, chars_to_del_len, &orig_str[i], 1, 1) == NULL) {
xbe7b0f39f2014-01-08 14:23:45 -0800677 if (!first_good_char_pos_set) {
Paul Sokolovskybcdffe52014-05-30 03:07:05 +0300678 first_good_char_pos_set = true;
xbe7b0f39f2014-01-08 14:23:45 -0800679 first_good_char_pos = i;
Paul Sokolovsky88107842014-04-26 06:20:08 +0300680 if (type == LSTRIP) {
681 last_good_char_pos = orig_str_len - 1;
682 break;
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300683 } else if (type == RSTRIP) {
684 first_good_char_pos = 0;
685 last_good_char_pos = i;
686 break;
Paul Sokolovsky88107842014-04-26 06:20:08 +0300687 }
xbe7b0f39f2014-01-08 14:23:45 -0800688 }
Paul Sokolovsky88107842014-04-26 06:20:08 +0300689 last_good_char_pos = i;
xbe7b0f39f2014-01-08 14:23:45 -0800690 }
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300691 i += delta;
xbe7b0f39f2014-01-08 14:23:45 -0800692 }
693
Paul Sokolovskybcdffe52014-05-30 03:07:05 +0300694 if (!first_good_char_pos_set) {
Damien George5fa93b62014-01-22 14:35:10 +0000695 // string is all whitespace, return ''
696 return MP_OBJ_NEW_QSTR(MP_QSTR_);
xbe7b0f39f2014-01-08 14:23:45 -0800697 }
698
699 assert(last_good_char_pos >= first_good_char_pos);
700 //+1 to accomodate the last character
xbec5538882014-03-16 17:58:35 -0700701 machine_uint_t stripped_len = last_good_char_pos - first_good_char_pos + 1;
Paul Sokolovsky88276822014-05-30 03:11:44 +0300702 if (stripped_len == orig_str_len) {
703 // If nothing was stripped, don't bother to dup original string
704 // TODO: watch out for this case when we'll get to bytearray.strip()
705 assert(first_good_char_pos == 0);
706 return args[0];
707 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100708 return mp_obj_new_str_of_type(self_type, orig_str + first_good_char_pos, stripped_len);
xbe7b0f39f2014-01-08 14:23:45 -0800709}
710
Paul Sokolovsky88107842014-04-26 06:20:08 +0300711STATIC mp_obj_t str_strip(uint n_args, const mp_obj_t *args) {
712 return str_uni_strip(STRIP, n_args, args);
713}
714
715STATIC mp_obj_t str_lstrip(uint n_args, const mp_obj_t *args) {
716 return str_uni_strip(LSTRIP, n_args, args);
717}
718
719STATIC mp_obj_t str_rstrip(uint n_args, const mp_obj_t *args) {
720 return str_uni_strip(RSTRIP, n_args, args);
721}
722
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700723// Takes an int arg, but only parses unsigned numbers, and only changes
724// *num if at least one digit was parsed.
725static int str_to_int(const char *str, int *num) {
726 const char *s = str;
727 if (unichar_isdigit(*s)) {
728 *num = 0;
729 do {
730 *num = *num * 10 + (*s - '0');
731 s++;
732 }
733 while (unichar_isdigit(*s));
734 }
735 return s - str;
736}
737
738static bool isalignment(char ch) {
739 return ch && strchr("<>=^", ch) != NULL;
740}
741
742static bool istype(char ch) {
743 return ch && strchr("bcdeEfFgGnosxX%", ch) != NULL;
744}
745
746static bool arg_looks_integer(mp_obj_t arg) {
747 return MP_OBJ_IS_TYPE(arg, &mp_type_bool) || MP_OBJ_IS_INT(arg);
748}
749
750static bool arg_looks_numeric(mp_obj_t arg) {
751 return arg_looks_integer(arg)
Damien Georgefb510b32014-06-01 13:32:54 +0100752#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700753 || MP_OBJ_IS_TYPE(arg, &mp_type_float)
754#endif
755 ;
756}
757
Dave Hylandsc4029e52014-04-07 11:19:51 -0700758static mp_obj_t arg_as_int(mp_obj_t arg) {
Damien Georgefb510b32014-06-01 13:32:54 +0100759#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700760 if (MP_OBJ_IS_TYPE(arg, &mp_type_float)) {
Dave Hylandsc4029e52014-04-07 11:19:51 -0700761
762 // TODO: Needs a way to construct an mpz integer from a float
763
764 mp_small_int_t num = mp_obj_get_float(arg);
765 return MP_OBJ_NEW_SMALL_INT(num);
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700766 }
767#endif
Dave Hylandsc4029e52014-04-07 11:19:51 -0700768 return arg;
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700769}
770
Damien George897fe0c2014-04-15 22:03:55 +0100771mp_obj_t mp_obj_str_format(uint n_args, const mp_obj_t *args) {
Damien George5fa93b62014-01-22 14:35:10 +0000772 assert(MP_OBJ_IS_STR(args[0]));
Damiend99b0522013-12-21 18:17:45 +0000773
Damien George5fa93b62014-01-22 14:35:10 +0000774 GET_STR_DATA_LEN(args[0], str, len);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700775 int arg_i = 0;
Damiend99b0522013-12-21 18:17:45 +0000776 vstr_t *vstr = vstr_new();
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700777 pfenv_t pfenv_vstr;
778 pfenv_vstr.data = vstr;
779 pfenv_vstr.print_strn = pfenv_vstr_add_strn;
780
Damien George5fa93b62014-01-22 14:35:10 +0000781 for (const byte *top = str + len; str < top; str++) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700782 if (*str == '}') {
Damiend99b0522013-12-21 18:17:45 +0000783 str++;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700784 if (str < top && *str == '}') {
785 vstr_add_char(vstr, '}');
786 continue;
787 }
Damien George11de8392014-06-05 18:57:38 +0100788 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "single '}' encountered in format string"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700789 }
790 if (*str != '{') {
791 vstr_add_char(vstr, *str);
792 continue;
793 }
794
795 str++;
796 if (str < top && *str == '{') {
797 vstr_add_char(vstr, '{');
798 continue;
799 }
800
801 // replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"
802
803 vstr_t *field_name = NULL;
804 char conversion = '\0';
805 vstr_t *format_spec = NULL;
806
807 if (str < top && *str != '}' && *str != '!' && *str != ':') {
808 field_name = vstr_new();
809 while (str < top && *str != '}' && *str != '!' && *str != ':') {
810 vstr_add_char(field_name, *str++);
811 }
812 vstr_add_char(field_name, '\0');
813 }
814
815 // conversion ::= "r" | "s"
816
817 if (str < top && *str == '!') {
818 str++;
819 if (str < top && (*str == 'r' || *str == 's')) {
820 conversion = *str++;
Paul Sokolovskyf2b796e2014-01-15 22:45:20 +0200821 } else {
Damien Georgeea13f402014-04-05 18:32:08 +0100822 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 -0700823 }
824 }
825
826 if (str < top && *str == ':') {
827 str++;
828 // {:} is the same as {}, which is the same as {!s}
829 // This makes a difference when passing in a True or False
830 // '{}'.format(True) returns 'True'
831 // '{:d}'.format(True) returns '1'
832 // So we treat {:} as {} and this later gets treated to be {!s}
833 if (*str != '}') {
Damien George11de8392014-06-05 18:57:38 +0100834 format_spec = vstr_new();
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700835 while (str < top && *str != '}') {
836 vstr_add_char(format_spec, *str++);
Damiend99b0522013-12-21 18:17:45 +0000837 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700838 vstr_add_char(format_spec, '\0');
839 }
840 }
841 if (str >= top) {
Damien Georgeea13f402014-04-05 18:32:08 +0100842 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "unmatched '{' in format"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700843 }
844 if (*str != '}') {
Damien Georgeea13f402014-04-05 18:32:08 +0100845 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "expected ':' after format specifier"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700846 }
847
848 mp_obj_t arg = mp_const_none;
849
850 if (field_name) {
851 if (arg_i > 0) {
Damien George11de8392014-06-05 18:57:38 +0100852 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 -0700853 }
Damien George3bb8bd82014-04-14 21:20:30 +0100854 int index = 0;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700855 if (str_to_int(vstr_str(field_name), &index) != vstr_len(field_name) - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100856 nlr_raise(mp_obj_new_exception_msg(&mp_type_KeyError, "attributes not supported yet"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700857 }
858 if (index >= n_args - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100859 nlr_raise(mp_obj_new_exception_msg(&mp_type_IndexError, "tuple index out of range"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700860 }
861 arg = args[index + 1];
862 arg_i = -1;
863 vstr_free(field_name);
864 field_name = NULL;
865 } else {
866 if (arg_i < 0) {
Damien George11de8392014-06-05 18:57:38 +0100867 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 -0700868 }
869 if (arg_i >= n_args - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100870 nlr_raise(mp_obj_new_exception_msg(&mp_type_IndexError, "tuple index out of range"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700871 }
872 arg = args[arg_i + 1];
873 arg_i++;
874 }
875 if (!format_spec && !conversion) {
876 conversion = 's';
877 }
878 if (conversion) {
879 mp_print_kind_t print_kind;
880 if (conversion == 's') {
881 print_kind = PRINT_STR;
882 } else if (conversion == 'r') {
883 print_kind = PRINT_REPR;
884 } else {
Damien George11de8392014-06-05 18:57:38 +0100885 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "unknown conversion specifier %c", conversion));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700886 }
887 vstr_t *arg_vstr = vstr_new();
888 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, arg_vstr, arg, print_kind);
Damien George2617eeb2014-05-25 22:27:57 +0100889 arg = mp_obj_new_str(vstr_str(arg_vstr), vstr_len(arg_vstr), false);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700890 vstr_free(arg_vstr);
891 }
892
893 char sign = '\0';
894 char fill = '\0';
895 char align = '\0';
896 int width = -1;
897 int precision = -1;
898 char type = '\0';
899 int flags = 0;
900
901 if (format_spec) {
902 // The format specifier (from http://docs.python.org/2/library/string.html#formatspec)
903 //
904 // [[fill]align][sign][#][0][width][,][.precision][type]
905 // fill ::= <any character>
906 // align ::= "<" | ">" | "=" | "^"
907 // sign ::= "+" | "-" | " "
908 // width ::= integer
909 // precision ::= integer
910 // type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
911
912 const char *s = vstr_str(format_spec);
913 if (isalignment(*s)) {
914 align = *s++;
915 } else if (*s && isalignment(s[1])) {
916 fill = *s++;
917 align = *s++;
918 }
919 if (*s == '+' || *s == '-' || *s == ' ') {
920 if (*s == '+') {
921 flags |= PF_FLAG_SHOW_SIGN;
922 } else if (*s == ' ') {
923 flags |= PF_FLAG_SPACE_SIGN;
924 }
925 sign = *s++;
926 }
927 if (*s == '#') {
928 flags |= PF_FLAG_SHOW_PREFIX;
929 s++;
930 }
931 if (*s == '0') {
932 if (!align) {
933 align = '=';
934 }
935 if (!fill) {
936 fill = '0';
937 }
938 }
939 s += str_to_int(s, &width);
940 if (*s == ',') {
941 flags |= PF_FLAG_SHOW_COMMA;
942 s++;
943 }
944 if (*s == '.') {
945 s++;
946 s += str_to_int(s, &precision);
947 }
948 if (istype(*s)) {
949 type = *s++;
950 }
951 if (*s) {
Damien Georgeea13f402014-04-05 18:32:08 +0100952 nlr_raise(mp_obj_new_exception_msg(&mp_type_KeyError, "Invalid conversion specification"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700953 }
954 vstr_free(format_spec);
955 format_spec = NULL;
956 }
957 if (!align) {
958 if (arg_looks_numeric(arg)) {
959 align = '>';
960 } else {
961 align = '<';
962 }
963 }
964 if (!fill) {
965 fill = ' ';
966 }
967
968 if (sign) {
969 if (type == 's') {
Damien Georgeea13f402014-04-05 18:32:08 +0100970 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "Sign not allowed in string format specifier"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700971 }
972 if (type == 'c') {
Damien Georgeea13f402014-04-05 18:32:08 +0100973 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "Sign not allowed with integer format specifier 'c'"));
Damiend99b0522013-12-21 18:17:45 +0000974 }
975 } else {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700976 sign = '-';
977 }
978
979 switch (align) {
980 case '<': flags |= PF_FLAG_LEFT_ADJUST; break;
981 case '=': flags |= PF_FLAG_PAD_AFTER_SIGN; break;
982 case '^': flags |= PF_FLAG_CENTER_ADJUST; break;
983 }
984
985 if (arg_looks_integer(arg)) {
986 switch (type) {
987 case 'b':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -0700988 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 2, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700989 continue;
990
991 case 'c':
992 {
993 char ch = mp_obj_get_int(arg);
994 pfenv_print_strn(&pfenv_vstr, &ch, 1, flags, fill, width);
995 continue;
996 }
997
998 case '\0': // No explicit format type implies 'd'
999 case 'n': // I don't think we support locales in uPy so use 'd'
1000 case 'd':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001001 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 10, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001002 continue;
1003
1004 case 'o':
Dave Hylandsc4029e52014-04-07 11:19:51 -07001005 if (flags & PF_FLAG_SHOW_PREFIX) {
1006 flags |= PF_FLAG_SHOW_OCTAL_LETTER;
1007 }
1008
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001009 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 8, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001010 continue;
1011
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001012 case 'X':
Damien George11de8392014-06-05 18:57:38 +01001013 case 'x':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001014 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 16, type - ('X' - 'A'), flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001015 continue;
1016
1017 case 'e':
1018 case 'E':
1019 case 'f':
1020 case 'F':
1021 case 'g':
1022 case 'G':
1023 case '%':
1024 // The floating point formatters all work with anything that
1025 // looks like an integer
1026 break;
1027
1028 default:
Damien Georgeea13f402014-04-05 18:32:08 +01001029 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Damien George11de8392014-06-05 18:57:38 +01001030 "unknown format code '%c' for object of type '%s'", type, mp_obj_get_type_str(arg)));
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001031 }
Damien Georgec322c5f2014-04-02 20:04:15 +01001032 }
Damien George70f33cd2014-04-02 17:06:05 +01001033
Dave Hylands22fe4d72014-04-02 12:07:31 -07001034 // NOTE: no else here. We need the e, f, g etc formats for integer
1035 // arguments (from above if) to take this if.
Damien Georgec322c5f2014-04-02 20:04:15 +01001036 if (arg_looks_numeric(arg)) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001037 if (!type) {
1038
1039 // Even though the docs say that an unspecified type is the same
1040 // as 'g', there is one subtle difference, when the exponent
1041 // is one less than the precision.
Damien George11de8392014-06-05 18:57:38 +01001042 //
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001043 // '{:10.1}'.format(0.0) ==> '0e+00'
1044 // '{:10.1g}'.format(0.0) ==> '0'
1045 //
1046 // TODO: Figure out how to deal with this.
1047 //
1048 // A proper solution would involve adding a special flag
1049 // or something to format_float, and create a format_double
1050 // to deal with doubles. In order to fix this when using
1051 // sprintf, we'd need to use the e format and tweak the
1052 // returned result to strip trailing zeros like the g format
1053 // does.
1054 //
1055 // {:10.3} and {:10.2e} with 1.23e2 both produce 1.23e+02
1056 // but with 1.e2 you get 1e+02 and 1.00e+02
1057 //
1058 // Stripping the trailing 0's (like g) does would make the
1059 // e format give us the right format.
1060 //
1061 // CPython sources say:
1062 // Omitted type specifier. Behaves in the same way as repr(x)
1063 // and str(x) if no precision is given, else like 'g', but with
1064 // at least one digit after the decimal point. */
1065
1066 type = 'g';
1067 }
1068 if (type == 'n') {
1069 type = 'g';
1070 }
1071
1072 flags |= PF_FLAG_PAD_NAN_INF; // '{:06e}'.format(float('-inf')) should give '-00inf'
1073 switch (type) {
Damien Georgefb510b32014-06-01 13:32:54 +01001074#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001075 case 'e':
1076 case 'E':
1077 case 'f':
1078 case 'F':
1079 case 'g':
1080 case 'G':
Damien George11de8392014-06-05 18:57:38 +01001081 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg), type, flags, fill, width, precision);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001082 break;
1083
1084 case '%':
1085 flags |= PF_FLAG_ADD_PERCENT;
1086 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg) * 100.0F, 'f', flags, fill, width, precision);
1087 break;
Damien Georgec322c5f2014-04-02 20:04:15 +01001088#endif
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001089
1090 default:
Damien Georgeea13f402014-04-05 18:32:08 +01001091 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Damien George11de8392014-06-05 18:57:38 +01001092 "unknown format code '%c' for object of type 'float'",
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001093 type, mp_obj_get_type_str(arg)));
1094 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001095 } else {
Damien George70f33cd2014-04-02 17:06:05 +01001096 // arg doesn't look like a number
1097
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001098 if (align == '=') {
Damien Georgeea13f402014-04-05 18:32:08 +01001099 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "'=' alignment not allowed in string format specifier"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001100 }
Damien George70f33cd2014-04-02 17:06:05 +01001101
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001102 switch (type) {
1103 case '\0':
1104 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, vstr, arg, PRINT_STR);
1105 break;
1106
1107 case 's':
1108 {
1109 uint len;
1110 const char *s = mp_obj_str_get_data(arg, &len);
1111 if (precision < 0) {
1112 precision = len;
1113 }
1114 if (len > precision) {
1115 len = precision;
1116 }
1117 pfenv_print_strn(&pfenv_vstr, s, len, flags, fill, width);
1118 break;
1119 }
1120
1121 default:
Damien Georgeea13f402014-04-05 18:32:08 +01001122 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Damien George11de8392014-06-05 18:57:38 +01001123 "unknown format code '%c' for object of type 'str'",
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001124 type, mp_obj_get_type_str(arg)));
1125 }
Damiend99b0522013-12-21 18:17:45 +00001126 }
1127 }
1128
Damien George2617eeb2014-05-25 22:27:57 +01001129 mp_obj_t s = mp_obj_new_str(vstr->buf, vstr->len, false);
Damien George5fa93b62014-01-22 14:35:10 +00001130 vstr_free(vstr);
1131 return s;
Damiend99b0522013-12-21 18:17:45 +00001132}
1133
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001134STATIC 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 +03001135 assert(MP_OBJ_IS_STR(pattern));
1136
1137 GET_STR_DATA_LEN(pattern, str, len);
Dave Hylands6756a372014-04-02 11:42:39 -07001138 const byte *start_str = str;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001139 int arg_i = 0;
1140 vstr_t *vstr = vstr_new();
Dave Hylands6756a372014-04-02 11:42:39 -07001141 pfenv_t pfenv_vstr;
1142 pfenv_vstr.data = vstr;
1143 pfenv_vstr.print_strn = pfenv_vstr_add_strn;
1144
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001145 for (const byte *top = str + len; str < top; str++) {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001146 mp_obj_t arg = MP_OBJ_NULL;
Dave Hylands6756a372014-04-02 11:42:39 -07001147 if (*str != '%') {
1148 vstr_add_char(vstr, *str);
1149 continue;
1150 }
1151 if (++str >= top) {
1152 break;
1153 }
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001154 if (*str == '%') {
Dave Hylands6756a372014-04-02 11:42:39 -07001155 vstr_add_char(vstr, '%');
1156 continue;
1157 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001158
1159 // Dictionary value lookup
1160 if (*str == '(') {
1161 const byte *key = ++str;
1162 while (*str != ')') {
1163 if (str >= top) {
1164 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "incomplete format key"));
1165 }
1166 ++str;
1167 }
1168 mp_obj_t k_obj = mp_obj_new_str((const char*)key, str - key, true);
1169 arg = mp_obj_dict_get(dict, k_obj);
1170 str++;
Dave Hylands6756a372014-04-02 11:42:39 -07001171 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001172
Dave Hylands6756a372014-04-02 11:42:39 -07001173 int flags = 0;
1174 char fill = ' ';
Damien George11de8392014-06-05 18:57:38 +01001175 int alt = 0;
Dave Hylands6756a372014-04-02 11:42:39 -07001176 while (str < top) {
1177 if (*str == '-') flags |= PF_FLAG_LEFT_ADJUST;
1178 else if (*str == '+') flags |= PF_FLAG_SHOW_SIGN;
1179 else if (*str == ' ') flags |= PF_FLAG_SPACE_SIGN;
Damien George11de8392014-06-05 18:57:38 +01001180 else if (*str == '#') alt = PF_FLAG_SHOW_PREFIX;
Dave Hylands6756a372014-04-02 11:42:39 -07001181 else if (*str == '0') {
1182 flags |= PF_FLAG_PAD_AFTER_SIGN;
1183 fill = '0';
1184 } else break;
1185 str++;
1186 }
1187 // parse width, if it exists
Damien George11de8392014-06-05 18:57:38 +01001188 int width = 0;
Dave Hylands6756a372014-04-02 11:42:39 -07001189 if (str < top) {
1190 if (*str == '*') {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001191 if (arg_i >= n_args) {
1192 goto not_enough_args;
1193 }
Dave Hylands6756a372014-04-02 11:42:39 -07001194 width = mp_obj_get_int(args[arg_i++]);
1195 str++;
1196 } else {
1197 for (; str < top && '0' <= *str && *str <= '9'; str++) {
1198 width = width * 10 + *str - '0';
1199 }
1200 }
1201 }
1202 int prec = -1;
1203 if (str < top && *str == '.') {
1204 if (++str < top) {
1205 if (*str == '*') {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001206 if (arg_i >= n_args) {
1207 goto not_enough_args;
1208 }
Dave Hylands6756a372014-04-02 11:42:39 -07001209 prec = mp_obj_get_int(args[arg_i++]);
1210 str++;
1211 } else {
1212 prec = 0;
1213 for (; str < top && '0' <= *str && *str <= '9'; str++) {
1214 prec = prec * 10 + *str - '0';
1215 }
1216 }
1217 }
1218 }
1219
1220 if (str >= top) {
Damien Georgeea13f402014-04-05 18:32:08 +01001221 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "incomplete format"));
Dave Hylands6756a372014-04-02 11:42:39 -07001222 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001223
1224 // Tuple value lookup
1225 if (arg == MP_OBJ_NULL) {
1226 if (arg_i >= n_args) {
1227not_enough_args:
1228 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "not enough arguments for format string"));
1229 }
1230 arg = args[arg_i++];
1231 }
Dave Hylands6756a372014-04-02 11:42:39 -07001232 switch (*str) {
1233 case 'c':
1234 if (MP_OBJ_IS_STR(arg)) {
1235 uint len;
1236 const char *s = mp_obj_str_get_data(arg, &len);
1237 if (len != 1) {
Damien George11de8392014-06-05 18:57:38 +01001238 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "%%c requires int or char"));
Dave Hylands6756a372014-04-02 11:42:39 -07001239 break;
1240 }
1241 pfenv_print_strn(&pfenv_vstr, s, 1, flags, ' ', width);
1242 break;
1243 }
1244 if (arg_looks_integer(arg)) {
1245 char ch = mp_obj_get_int(arg);
1246 pfenv_print_strn(&pfenv_vstr, &ch, 1, flags, ' ', width);
1247 break;
1248 }
Damien Georgefb510b32014-06-01 13:32:54 +01001249#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylands6756a372014-04-02 11:42:39 -07001250 // This is what CPython reports, so we report the same.
1251 if (MP_OBJ_IS_TYPE(arg, &mp_type_float)) {
Damien George11de8392014-06-05 18:57:38 +01001252 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "integer argument expected, got float"));
Dave Hylands6756a372014-04-02 11:42:39 -07001253
1254 }
1255#endif
Damien George11de8392014-06-05 18:57:38 +01001256 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "an integer is required"));
1257 break;
Dave Hylands6756a372014-04-02 11:42:39 -07001258
1259 case 'd':
1260 case 'i':
1261 case 'u':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001262 pfenv_print_mp_int(&pfenv_vstr, arg_as_int(arg), 1, 10, 'a', flags, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001263 break;
1264
Damien Georgefb510b32014-06-01 13:32:54 +01001265#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylands6756a372014-04-02 11:42:39 -07001266 case 'e':
1267 case 'E':
1268 case 'f':
1269 case 'F':
1270 case 'g':
1271 case 'G':
1272 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg), *str, flags, fill, width, prec);
1273 break;
1274#endif
1275
1276 case 'o':
1277 if (alt) {
Dave Hylandsc4029e52014-04-07 11:19:51 -07001278 flags |= (PF_FLAG_SHOW_PREFIX | PF_FLAG_SHOW_OCTAL_LETTER);
Dave Hylands6756a372014-04-02 11:42:39 -07001279 }
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001280 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 8, 'a', flags, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001281 break;
1282
1283 case 'r':
1284 case 's':
1285 {
1286 vstr_t *arg_vstr = vstr_new();
1287 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf,
1288 arg_vstr, arg, *str == 'r' ? PRINT_REPR : PRINT_STR);
1289 uint len = vstr_len(arg_vstr);
1290 if (prec < 0) {
1291 prec = len;
1292 }
1293 if (len > prec) {
1294 len = prec;
1295 }
1296 pfenv_print_strn(&pfenv_vstr, vstr_str(arg_vstr), len, flags, ' ', width);
1297 vstr_free(arg_vstr);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001298 break;
1299 }
Dave Hylands6756a372014-04-02 11:42:39 -07001300
Dave Hylands6756a372014-04-02 11:42:39 -07001301 case 'X':
Damien George11de8392014-06-05 18:57:38 +01001302 case 'x':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001303 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 16, *str - ('X' - 'A'), flags | alt, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001304 break;
Damien Georgedeed0872014-04-06 11:11:15 +01001305
Dave Hylands6756a372014-04-02 11:42:39 -07001306 default:
Damien Georgeea13f402014-04-05 18:32:08 +01001307 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Dave Hylands6756a372014-04-02 11:42:39 -07001308 "unsupported format character '%c' (0x%x) at index %d",
1309 *str, *str, str - start_str));
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001310 }
1311 }
1312
1313 if (arg_i != n_args) {
Damien Georgeea13f402014-04-05 18:32:08 +01001314 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "not all arguments converted during string formatting"));
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001315 }
1316
Damien George2617eeb2014-05-25 22:27:57 +01001317 mp_obj_t s = mp_obj_new_str(vstr->buf, vstr->len, false);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001318 vstr_free(vstr);
1319 return s;
1320}
1321
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001322STATIC mp_obj_t str_replace(uint n_args, const mp_obj_t *args) {
xbe480c15a2014-01-30 22:17:30 -08001323 assert(MP_OBJ_IS_STR(args[0]));
xbe480c15a2014-01-30 22:17:30 -08001324
Damien Georgeff715422014-04-07 00:39:13 +01001325 machine_int_t max_rep = -1;
xbe480c15a2014-01-30 22:17:30 -08001326 if (n_args == 4) {
Damien Georgeff715422014-04-07 00:39:13 +01001327 max_rep = mp_obj_get_int(args[3]);
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001328 if (max_rep == 0) {
1329 return args[0];
1330 } else if (max_rep < 0) {
Damien Georgeff715422014-04-07 00:39:13 +01001331 max_rep = -1;
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001332 }
xbe480c15a2014-01-30 22:17:30 -08001333 }
Damien George94f68302014-01-31 23:45:12 +00001334
xbe729be9b2014-04-07 14:46:39 -07001335 // if max_rep is still -1 by this point we will need to do all possible replacements
xbe480c15a2014-01-30 22:17:30 -08001336
Damien Georgeff715422014-04-07 00:39:13 +01001337 // check argument types
1338
1339 if (!MP_OBJ_IS_STR(args[1])) {
1340 bad_implicit_conversion(args[1]);
1341 }
1342
1343 if (!MP_OBJ_IS_STR(args[2])) {
1344 bad_implicit_conversion(args[2]);
1345 }
1346
1347 // extract string data
1348
xbe480c15a2014-01-30 22:17:30 -08001349 GET_STR_DATA_LEN(args[0], str, str_len);
1350 GET_STR_DATA_LEN(args[1], old, old_len);
1351 GET_STR_DATA_LEN(args[2], new, new_len);
Damien George94f68302014-01-31 23:45:12 +00001352
1353 // old won't exist in str if it's longer, so nothing to replace
xbe480c15a2014-01-30 22:17:30 -08001354 if (old_len > str_len) {
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001355 return args[0];
xbe480c15a2014-01-30 22:17:30 -08001356 }
1357
Damien George94f68302014-01-31 23:45:12 +00001358 // data for the replaced string
1359 byte *data = NULL;
1360 mp_obj_t replaced_str = MP_OBJ_NULL;
xbe480c15a2014-01-30 22:17:30 -08001361
Damien George94f68302014-01-31 23:45:12 +00001362 // do 2 passes over the string:
1363 // first pass computes the required length of the replaced string
1364 // second pass does the replacements
1365 for (;;) {
1366 machine_uint_t replaced_str_index = 0;
1367 machine_uint_t num_replacements_done = 0;
1368 const byte *old_occurrence;
1369 const byte *offset_ptr = str;
Damien Georgeff715422014-04-07 00:39:13 +01001370 machine_uint_t str_len_remain = str_len;
1371 if (old_len == 0) {
1372 // if old_str is empty, copy new_str to start of replaced string
1373 // copy the replacement string
1374 if (data != NULL) {
1375 memcpy(data, new, new_len);
1376 }
1377 replaced_str_index += new_len;
1378 num_replacements_done++;
1379 }
1380 while (num_replacements_done != max_rep && str_len_remain > 0 && (old_occurrence = find_subbytes(offset_ptr, str_len_remain, old, old_len, 1)) != NULL) {
1381 if (old_len == 0) {
1382 old_occurrence += 1;
1383 }
Damien George94f68302014-01-31 23:45:12 +00001384 // copy from just after end of last occurrence of to-be-replaced string to right before start of next occurrence
1385 if (data != NULL) {
1386 memcpy(data + replaced_str_index, offset_ptr, old_occurrence - offset_ptr);
1387 }
1388 replaced_str_index += old_occurrence - offset_ptr;
1389 // copy the replacement string
1390 if (data != NULL) {
1391 memcpy(data + replaced_str_index, new, new_len);
1392 }
1393 replaced_str_index += new_len;
1394 offset_ptr = old_occurrence + old_len;
Damien Georgeff715422014-04-07 00:39:13 +01001395 str_len_remain = str + str_len - offset_ptr;
Damien George94f68302014-01-31 23:45:12 +00001396 num_replacements_done++;
Damien George94f68302014-01-31 23:45:12 +00001397 }
1398
1399 // copy from just after end of last occurrence of to-be-replaced string to end of old string
1400 if (data != NULL) {
Damien Georgeff715422014-04-07 00:39:13 +01001401 memcpy(data + replaced_str_index, offset_ptr, str_len_remain);
Damien George94f68302014-01-31 23:45:12 +00001402 }
Damien Georgeff715422014-04-07 00:39:13 +01001403 replaced_str_index += str_len_remain;
Damien George94f68302014-01-31 23:45:12 +00001404
1405 if (data == NULL) {
1406 // first pass
1407 if (num_replacements_done == 0) {
1408 // no substr found, return original string
1409 return args[0];
1410 } else {
1411 // substr found, allocate new string
1412 replaced_str = mp_obj_str_builder_start(mp_obj_get_type(args[0]), replaced_str_index, &data);
Damien Georgeff715422014-04-07 00:39:13 +01001413 assert(data != NULL);
Damien George94f68302014-01-31 23:45:12 +00001414 }
1415 } else {
1416 // second pass, we are done
1417 break;
1418 }
xbe480c15a2014-01-30 22:17:30 -08001419 }
Damien George94f68302014-01-31 23:45:12 +00001420
xbe480c15a2014-01-30 22:17:30 -08001421 return mp_obj_str_builder_end(replaced_str);
1422}
1423
xbe9e1e8cd2014-03-12 22:57:16 -07001424STATIC mp_obj_t str_count(uint n_args, const mp_obj_t *args) {
1425 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
Damien George536dde22014-03-13 22:07:55 +00001432 machine_uint_t start = 0;
1433 machine_uint_t end = haystack_len;
xbe9e1e8cd2014-03-12 22:57:16 -07001434 if (n_args >= 3 && args[2] != mp_const_none) {
Damien George3e1a5c12014-03-29 13:43:38 +00001435 start = mp_get_index(&mp_type_str, haystack_len, args[2], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001436 }
1437 if (n_args >= 4 && args[3] != mp_const_none) {
Damien George3e1a5c12014-03-29 13:43:38 +00001438 end = mp_get_index(&mp_type_str, 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) {
1443 return MP_OBJ_NEW_SMALL_INT(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;
xbec5d70ba2014-03-13 00:29:15 -07001448 for (machine_uint_t haystack_index = start; haystack_index + needle_len <= end; haystack_index++) {
1449 if (memcmp(&haystack[haystack_index], needle, needle_len) == 0) {
1450 num_occurrences++;
1451 haystack_index += needle_len - 1;
1452 }
xbe9e1e8cd2014-03-12 22:57:16 -07001453 }
1454
1455 return MP_OBJ_NEW_SMALL_INT(num_occurrences);
1456}
1457
Damien Georgeb035db32014-03-21 20:39:40 +00001458STATIC 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 +03001459 if (!is_str_or_bytes(self_in)) {
1460 assert(0);
1461 }
1462 mp_obj_type_t *self_type = mp_obj_get_type(self_in);
1463 if (self_type != mp_obj_get_type(arg)) {
1464 arg_type_mixup();
xbe613a8e32014-03-18 00:06:29 -07001465 }
Damien Georgeb035db32014-03-21 20:39:40 +00001466
xbe613a8e32014-03-18 00:06:29 -07001467 GET_STR_DATA_LEN(self_in, str, str_len);
1468 GET_STR_DATA_LEN(arg, sep, sep_len);
1469
1470 if (sep_len == 0) {
Damien Georgeea13f402014-04-05 18:32:08 +01001471 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
xbe613a8e32014-03-18 00:06:29 -07001472 }
Damien Georgeb035db32014-03-21 20:39:40 +00001473
1474 mp_obj_t result[] = {MP_OBJ_NEW_QSTR(MP_QSTR_), MP_OBJ_NEW_QSTR(MP_QSTR_), MP_OBJ_NEW_QSTR(MP_QSTR_)};
1475
1476 if (direction > 0) {
1477 result[0] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001478 } else {
Damien Georgeb035db32014-03-21 20:39:40 +00001479 result[2] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001480 }
xbe613a8e32014-03-18 00:06:29 -07001481
xbe17a5a832014-03-23 23:31:58 -07001482 const byte *position_ptr = find_subbytes(str, str_len, sep, sep_len, direction);
1483 if (position_ptr != NULL) {
1484 machine_uint_t position = position_ptr - str;
Damien Georgef600a6a2014-05-25 22:34:34 +01001485 result[0] = mp_obj_new_str_of_type(self_type, str, position);
xbe17a5a832014-03-23 23:31:58 -07001486 result[1] = arg;
Damien Georgef600a6a2014-05-25 22:34:34 +01001487 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 -07001488 }
Damien Georgeb035db32014-03-21 20:39:40 +00001489
xbe0a6894c2014-03-21 01:12:26 -07001490 return mp_obj_new_tuple(3, result);
xbe613a8e32014-03-18 00:06:29 -07001491}
1492
Damien Georgeb035db32014-03-21 20:39:40 +00001493STATIC mp_obj_t str_partition(mp_obj_t self_in, mp_obj_t arg) {
1494 return str_partitioner(self_in, arg, 1);
xbe0a6894c2014-03-21 01:12:26 -07001495}
xbe4504ea82014-03-19 00:46:14 -07001496
Damien Georgeb035db32014-03-21 20:39:40 +00001497STATIC mp_obj_t str_rpartition(mp_obj_t self_in, mp_obj_t arg) {
1498 return str_partitioner(self_in, arg, -1);
xbe4504ea82014-03-19 00:46:14 -07001499}
1500
Paul Sokolovsky69135212014-05-10 19:47:41 +03001501// Supposedly not too critical operations, so optimize for code size
Damien Georgefcc9cf62014-06-01 18:22:09 +01001502STATIC mp_obj_t str_caseconv(unichar (*op)(unichar), mp_obj_t self_in) {
Paul Sokolovsky69135212014-05-10 19:47:41 +03001503 GET_STR_DATA_LEN(self_in, self_data, self_len);
1504 byte *data;
1505 mp_obj_t s = mp_obj_str_builder_start(mp_obj_get_type(self_in), self_len, &data);
1506 for (int i = 0; i < self_len; i++) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001507 *data++ = op(*self_data++);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001508 }
1509 *data = 0;
1510 return mp_obj_str_builder_end(s);
1511}
1512
1513STATIC mp_obj_t str_lower(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001514 return str_caseconv(unichar_tolower, self_in);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001515}
1516
1517STATIC mp_obj_t str_upper(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001518 return str_caseconv(unichar_toupper, self_in);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001519}
1520
Damien Georgefcc9cf62014-06-01 18:22:09 +01001521STATIC mp_obj_t str_uni_istype(bool (*f)(unichar), mp_obj_t self_in) {
Kim Bautersa3f4b832014-05-31 07:30:03 +01001522 GET_STR_DATA_LEN(self_in, self_data, self_len);
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001523
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001524 if (self_len == 0) {
1525 return mp_const_false; // default to False for empty str
1526 }
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001527
Damien Georgefcc9cf62014-06-01 18:22:09 +01001528 if (f != unichar_isupper && f != unichar_islower) {
Kim Bautersa3f4b832014-05-31 07:30:03 +01001529 for (int i = 0; i < self_len; i++) {
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001530 if (!f(*self_data++)) {
1531 return mp_const_false;
1532 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001533 }
1534 } else {
Kim Bautersa3f4b832014-05-31 07:30:03 +01001535 bool contains_alpha = false;
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001536
Kim Bautersa3f4b832014-05-31 07:30:03 +01001537 for (int i = 0; i < self_len; i++) { // only check alphanumeric characters
1538 if (unichar_isalpha(*self_data++)) {
1539 contains_alpha = true;
Damien Georgefcc9cf62014-06-01 18:22:09 +01001540 if (!f(*(self_data - 1))) { // -1 because we already incremented above
1541 return mp_const_false;
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001542 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001543 }
1544 }
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001545
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001546 if (!contains_alpha) {
1547 return mp_const_false;
1548 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001549 }
1550
1551 return mp_const_true;
1552}
1553
1554STATIC mp_obj_t str_isspace(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001555 return str_uni_istype(unichar_isspace, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001556}
1557
1558STATIC mp_obj_t str_isalpha(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001559 return str_uni_istype(unichar_isalpha, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001560}
1561
1562STATIC mp_obj_t str_isdigit(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001563 return str_uni_istype(unichar_isdigit, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001564}
1565
1566STATIC mp_obj_t str_isupper(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001567 return str_uni_istype(unichar_isupper, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001568}
1569
1570STATIC mp_obj_t str_islower(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001571 return str_uni_istype(unichar_islower, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001572}
1573
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001574#if MICROPY_CPYTHON_COMPAT
1575// These methods are superfluous in the presense of str() and bytes()
1576// constructors.
1577// TODO: should accept kwargs too
1578STATIC mp_obj_t bytes_decode(uint n_args, const mp_obj_t *args) {
1579 mp_obj_t new_args[2];
1580 if (n_args == 1) {
1581 new_args[0] = args[0];
1582 new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
1583 args = new_args;
1584 n_args++;
1585 }
1586 return str_make_new(NULL, n_args, 0, args);
1587}
1588
1589// TODO: should accept kwargs too
1590STATIC mp_obj_t str_encode(uint n_args, const mp_obj_t *args) {
1591 mp_obj_t new_args[2];
1592 if (n_args == 1) {
1593 new_args[0] = args[0];
1594 new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
1595 args = new_args;
1596 n_args++;
1597 }
1598 return bytes_make_new(NULL, n_args, 0, args);
1599}
1600#endif
1601
Damien George57a4b4f2014-04-18 22:29:21 +01001602STATIC machine_int_t str_get_buffer(mp_obj_t self_in, mp_buffer_info_t *bufinfo, int flags) {
1603 if (flags == MP_BUFFER_READ) {
Damien George2da98302014-03-09 19:58:18 +00001604 GET_STR_DATA_LEN(self_in, str_data, str_len);
1605 bufinfo->buf = (void*)str_data;
1606 bufinfo->len = str_len;
Damien George57a4b4f2014-04-18 22:29:21 +01001607 bufinfo->typecode = 'b';
Damien George2da98302014-03-09 19:58:18 +00001608 return 0;
1609 } else {
1610 // can't write to a string
1611 bufinfo->buf = NULL;
1612 bufinfo->len = 0;
Damien George57a4b4f2014-04-18 22:29:21 +01001613 bufinfo->typecode = -1;
Damien George2da98302014-03-09 19:58:18 +00001614 return 1;
1615 }
1616}
1617
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001618#if MICROPY_CPYTHON_COMPAT
1619STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(bytes_decode_obj, 1, 3, bytes_decode);
1620STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_encode_obj, 1, 3, str_encode);
1621#endif
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001622STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_find_obj, 2, 4, str_find);
xbe17a5a832014-03-23 23:31:58 -07001623STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rfind_obj, 2, 4, str_rfind);
xbe3d9a39e2014-04-08 11:42:19 -07001624STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_index_obj, 2, 4, str_index);
1625STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rindex_obj, 2, 4, str_rindex);
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001626STATIC MP_DEFINE_CONST_FUN_OBJ_2(str_join_obj, str_join);
1627STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_split_obj, 1, 3, str_split);
Paul Sokolovsky2a273652014-05-13 08:07:08 +03001628STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rsplit_obj, 1, 3, str_rsplit);
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +03001629STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_startswith_obj, 2, 3, str_startswith);
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +03001630STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_endswith_obj, 2, 3, str_endswith);
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001631STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_strip_obj, 1, 2, str_strip);
Paul Sokolovsky88107842014-04-26 06:20:08 +03001632STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_lstrip_obj, 1, 2, str_lstrip);
1633STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rstrip_obj, 1, 2, str_rstrip);
Damien George897fe0c2014-04-15 22:03:55 +01001634STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(str_format_obj, 1, mp_obj_str_format);
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001635STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_replace_obj, 3, 4, str_replace);
xbe9e1e8cd2014-03-12 22:57:16 -07001636STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_count_obj, 2, 4, str_count);
xbe613a8e32014-03-18 00:06:29 -07001637STATIC MP_DEFINE_CONST_FUN_OBJ_2(str_partition_obj, str_partition);
xbe4504ea82014-03-19 00:46:14 -07001638STATIC MP_DEFINE_CONST_FUN_OBJ_2(str_rpartition_obj, str_rpartition);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001639STATIC MP_DEFINE_CONST_FUN_OBJ_1(str_lower_obj, str_lower);
1640STATIC MP_DEFINE_CONST_FUN_OBJ_1(str_upper_obj, str_upper);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001641STATIC MP_DEFINE_CONST_FUN_OBJ_1(str_isspace_obj, str_isspace);
1642STATIC MP_DEFINE_CONST_FUN_OBJ_1(str_isalpha_obj, str_isalpha);
1643STATIC MP_DEFINE_CONST_FUN_OBJ_1(str_isdigit_obj, str_isdigit);
1644STATIC MP_DEFINE_CONST_FUN_OBJ_1(str_isupper_obj, str_isupper);
1645STATIC MP_DEFINE_CONST_FUN_OBJ_1(str_islower_obj, str_islower);
Damiend99b0522013-12-21 18:17:45 +00001646
Damien George9b196cd2014-03-26 21:47:19 +00001647STATIC const mp_map_elem_t str_locals_dict_table[] = {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001648#if MICROPY_CPYTHON_COMPAT
1649 { MP_OBJ_NEW_QSTR(MP_QSTR_decode), (mp_obj_t)&bytes_decode_obj },
1650 { MP_OBJ_NEW_QSTR(MP_QSTR_encode), (mp_obj_t)&str_encode_obj },
1651#endif
Damien George9b196cd2014-03-26 21:47:19 +00001652 { MP_OBJ_NEW_QSTR(MP_QSTR_find), (mp_obj_t)&str_find_obj },
1653 { MP_OBJ_NEW_QSTR(MP_QSTR_rfind), (mp_obj_t)&str_rfind_obj },
xbe3d9a39e2014-04-08 11:42:19 -07001654 { MP_OBJ_NEW_QSTR(MP_QSTR_index), (mp_obj_t)&str_index_obj },
1655 { MP_OBJ_NEW_QSTR(MP_QSTR_rindex), (mp_obj_t)&str_rindex_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001656 { MP_OBJ_NEW_QSTR(MP_QSTR_join), (mp_obj_t)&str_join_obj },
1657 { MP_OBJ_NEW_QSTR(MP_QSTR_split), (mp_obj_t)&str_split_obj },
Paul Sokolovsky2a273652014-05-13 08:07:08 +03001658 { MP_OBJ_NEW_QSTR(MP_QSTR_rsplit), (mp_obj_t)&str_rsplit_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001659 { MP_OBJ_NEW_QSTR(MP_QSTR_startswith), (mp_obj_t)&str_startswith_obj },
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +03001660 { MP_OBJ_NEW_QSTR(MP_QSTR_endswith), (mp_obj_t)&str_endswith_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001661 { MP_OBJ_NEW_QSTR(MP_QSTR_strip), (mp_obj_t)&str_strip_obj },
Paul Sokolovsky88107842014-04-26 06:20:08 +03001662 { MP_OBJ_NEW_QSTR(MP_QSTR_lstrip), (mp_obj_t)&str_lstrip_obj },
1663 { MP_OBJ_NEW_QSTR(MP_QSTR_rstrip), (mp_obj_t)&str_rstrip_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001664 { MP_OBJ_NEW_QSTR(MP_QSTR_format), (mp_obj_t)&str_format_obj },
1665 { MP_OBJ_NEW_QSTR(MP_QSTR_replace), (mp_obj_t)&str_replace_obj },
1666 { MP_OBJ_NEW_QSTR(MP_QSTR_count), (mp_obj_t)&str_count_obj },
1667 { MP_OBJ_NEW_QSTR(MP_QSTR_partition), (mp_obj_t)&str_partition_obj },
1668 { MP_OBJ_NEW_QSTR(MP_QSTR_rpartition), (mp_obj_t)&str_rpartition_obj },
Paul Sokolovsky69135212014-05-10 19:47:41 +03001669 { MP_OBJ_NEW_QSTR(MP_QSTR_lower), (mp_obj_t)&str_lower_obj },
1670 { MP_OBJ_NEW_QSTR(MP_QSTR_upper), (mp_obj_t)&str_upper_obj },
Kim Bautersa3f4b832014-05-31 07:30:03 +01001671 { MP_OBJ_NEW_QSTR(MP_QSTR_isspace), (mp_obj_t)&str_isspace_obj },
1672 { MP_OBJ_NEW_QSTR(MP_QSTR_isalpha), (mp_obj_t)&str_isalpha_obj },
1673 { MP_OBJ_NEW_QSTR(MP_QSTR_isdigit), (mp_obj_t)&str_isdigit_obj },
1674 { MP_OBJ_NEW_QSTR(MP_QSTR_isupper), (mp_obj_t)&str_isupper_obj },
1675 { MP_OBJ_NEW_QSTR(MP_QSTR_islower), (mp_obj_t)&str_islower_obj },
ian-v7a16fad2014-01-06 09:52:29 -08001676};
Damien George97209d32014-01-07 15:58:30 +00001677
Damien George9b196cd2014-03-26 21:47:19 +00001678STATIC MP_DEFINE_CONST_DICT(str_locals_dict, str_locals_dict_table);
1679
Damien George3e1a5c12014-03-29 13:43:38 +00001680const mp_obj_type_t mp_type_str = {
Damien Georgec5966122014-02-15 16:10:44 +00001681 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001682 .name = MP_QSTR_str,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001683 .print = str_print,
Paul Sokolovskybe020c22014-03-21 11:39:01 +02001684 .make_new = str_make_new,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001685 .binary_op = str_binary_op,
Damien George729f7b42014-04-17 22:10:53 +01001686 .subscr = str_subscr,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001687 .getiter = mp_obj_new_str_iterator,
Damien George2da98302014-03-09 19:58:18 +00001688 .buffer_p = { .get_buffer = str_get_buffer },
Damien George9b196cd2014-03-26 21:47:19 +00001689 .locals_dict = (mp_obj_t)&str_locals_dict,
Damiend99b0522013-12-21 18:17:45 +00001690};
1691
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001692// Reuses most of methods from str
Damien George3e1a5c12014-03-29 13:43:38 +00001693const mp_obj_type_t mp_type_bytes = {
Damien Georgec5966122014-02-15 16:10:44 +00001694 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001695 .name = MP_QSTR_bytes,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001696 .print = str_print,
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001697 .make_new = bytes_make_new,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001698 .binary_op = str_binary_op,
Damien George729f7b42014-04-17 22:10:53 +01001699 .subscr = str_subscr,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001700 .getiter = mp_obj_new_bytes_iterator,
Paul Sokolovsky7a70a3a2014-04-08 17:30:47 +03001701 .buffer_p = { .get_buffer = str_get_buffer },
Damien George9b196cd2014-03-26 21:47:19 +00001702 .locals_dict = (mp_obj_t)&str_locals_dict,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001703};
1704
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001705// the zero-length bytes
Damien George3e1a5c12014-03-29 13:43:38 +00001706STATIC const mp_obj_str_t empty_bytes_obj = {{&mp_type_bytes}, 0, 0, NULL};
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001707const mp_obj_t mp_const_empty_bytes = (mp_obj_t)&empty_bytes_obj;
1708
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001709mp_obj_t mp_obj_str_builder_start(const mp_obj_type_t *type, uint len, byte **data) {
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001710 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001711 o->base.type = type;
Damien George5fa93b62014-01-22 14:35:10 +00001712 o->len = len;
Paul Sokolovsky504e2332014-04-19 03:09:17 +03001713 o->hash = 0;
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001714 byte *p = m_new(byte, len + 1);
1715 o->data = p;
1716 *data = p;
Damiend99b0522013-12-21 18:17:45 +00001717 return o;
1718}
1719
Damien George5fa93b62014-01-22 14:35:10 +00001720mp_obj_t mp_obj_str_builder_end(mp_obj_t o_in) {
Damien George5fa93b62014-01-22 14:35:10 +00001721 mp_obj_str_t *o = o_in;
1722 o->hash = qstr_compute_hash(o->data, o->len);
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001723 byte *p = (byte*)o->data;
1724 p[o->len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
Damien George5fa93b62014-01-22 14:35:10 +00001725 return o;
1726}
1727
Damien Georgef600a6a2014-05-25 22:34:34 +01001728mp_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 +02001729 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001730 o->base.type = type;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001731 o->len = len;
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001732 if (data) {
1733 o->hash = qstr_compute_hash(data, len);
1734 byte *p = m_new(byte, len + 1);
1735 o->data = p;
1736 memcpy(p, data, len * sizeof(byte));
1737 p[len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
1738 }
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001739 return o;
1740}
1741
Damien George2617eeb2014-05-25 22:27:57 +01001742mp_obj_t mp_obj_new_str(const char* data, uint len, bool make_qstr_if_not_already) {
Damien Georgef600a6a2014-05-25 22:34:34 +01001743 if (make_qstr_if_not_already) {
1744 // use existing, or make a new qstr
Damien George2617eeb2014-05-25 22:27:57 +01001745 return MP_OBJ_NEW_QSTR(qstr_from_strn(data, len));
Damien George5fa93b62014-01-22 14:35:10 +00001746 } else {
Damien Georgef600a6a2014-05-25 22:34:34 +01001747 qstr q = qstr_find_strn(data, len);
1748 if (q != MP_QSTR_NULL) {
1749 // qstr with this data already exists
1750 return MP_OBJ_NEW_QSTR(q);
1751 } else {
1752 // no existing qstr, don't make one
1753 return mp_obj_new_str_of_type(&mp_type_str, (const byte*)data, len);
1754 }
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02001755 }
Damien George5fa93b62014-01-22 14:35:10 +00001756}
1757
Paul Sokolovskyb4efac12014-06-08 01:13:35 +03001758mp_obj_t mp_obj_str_intern(mp_obj_t str) {
1759 GET_STR_DATA_LEN(str, data, len);
1760 return MP_OBJ_NEW_QSTR(qstr_from_strn((const char*)data, len));
1761}
1762
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001763mp_obj_t mp_obj_new_bytes(const byte* data, uint len) {
Damien Georgef600a6a2014-05-25 22:34:34 +01001764 return mp_obj_new_str_of_type(&mp_type_bytes, data, len);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001765}
1766
Damien George5fa93b62014-01-22 14:35:10 +00001767bool mp_obj_str_equal(mp_obj_t s1, mp_obj_t s2) {
1768 if (MP_OBJ_IS_QSTR(s1) && MP_OBJ_IS_QSTR(s2)) {
1769 return s1 == s2;
1770 } else {
1771 GET_STR_HASH(s1, h1);
1772 GET_STR_HASH(s2, h2);
Paul Sokolovsky59e269c2014-04-14 01:43:01 +03001773 // If any of hashes is 0, it means it's not valid
1774 if (h1 != 0 && h2 != 0 && h1 != h2) {
Damien George5fa93b62014-01-22 14:35:10 +00001775 return false;
1776 }
1777 GET_STR_DATA_LEN(s1, d1, l1);
1778 GET_STR_DATA_LEN(s2, d2, l2);
1779 if (l1 != l2) {
1780 return false;
1781 }
Damien George1e708fe2014-01-23 18:27:51 +00001782 return memcmp(d1, d2, l1) == 0;
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02001783 }
Damien George5fa93b62014-01-22 14:35:10 +00001784}
1785
Damien Georgedeed0872014-04-06 11:11:15 +01001786STATIC void bad_implicit_conversion(mp_obj_t self_in) {
Damien Georgeea13f402014-04-05 18:32:08 +01001787 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 +00001788}
1789
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +03001790STATIC void arg_type_mixup() {
1791 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "Can't mix str and bytes arguments"));
1792}
1793
Damien George5fa93b62014-01-22 14:35:10 +00001794uint mp_obj_str_get_hash(mp_obj_t self_in) {
Paul Sokolovskyf130ca12014-04-13 05:41:00 +03001795 // TODO: This has too big overhead for hash accessor
1796 if (MP_OBJ_IS_STR(self_in) || MP_OBJ_IS_TYPE(self_in, &mp_type_bytes)) {
Damien George5fa93b62014-01-22 14:35:10 +00001797 GET_STR_HASH(self_in, h);
1798 return h;
1799 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001800 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001801 }
1802}
1803
1804uint mp_obj_str_get_len(mp_obj_t self_in) {
Damien Georgeee014112014-04-15 23:10:00 +01001805 // TODO This has a double check for the type, one in obj.c and one here
1806 if (MP_OBJ_IS_STR(self_in) || MP_OBJ_IS_TYPE(self_in, &mp_type_bytes)) {
Damien George5fa93b62014-01-22 14:35:10 +00001807 GET_STR_LEN(self_in, l);
1808 return l;
1809 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001810 bad_implicit_conversion(self_in);
1811 }
1812}
1813
1814// use this if you will anyway convert the string to a qstr
1815// will be more efficient for the case where it's already a qstr
1816qstr mp_obj_str_get_qstr(mp_obj_t self_in) {
1817 if (MP_OBJ_IS_QSTR(self_in)) {
1818 return MP_OBJ_QSTR_VALUE(self_in);
Damien George3e1a5c12014-03-29 13:43:38 +00001819 } else if (MP_OBJ_IS_TYPE(self_in, &mp_type_str)) {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001820 mp_obj_str_t *self = self_in;
1821 return qstr_from_strn((char*)self->data, self->len);
1822 } else {
1823 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001824 }
1825}
1826
1827// only use this function if you need the str data to be zero terminated
1828// at the moment all strings are zero terminated to help with C ASCIIZ compatibility
1829const char *mp_obj_str_get_str(mp_obj_t self_in) {
1830 if (MP_OBJ_IS_STR(self_in)) {
1831 GET_STR_DATA_LEN(self_in, s, l);
1832 (void)l; // len unused
1833 return (const char*)s;
1834 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001835 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001836 }
1837}
1838
Damien George698ec212014-02-08 18:17:23 +00001839const char *mp_obj_str_get_data(mp_obj_t self_in, uint *len) {
Paul Sokolovskyeea01182014-05-11 13:51:24 +03001840 if (is_str_or_bytes(self_in)) {
Damien George5fa93b62014-01-22 14:35:10 +00001841 GET_STR_DATA_LEN(self_in, s, l);
1842 *len = l;
Damien George698ec212014-02-08 18:17:23 +00001843 return (const char*)s;
Damien George5fa93b62014-01-22 14:35:10 +00001844 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001845 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001846 }
Damiend99b0522013-12-21 18:17:45 +00001847}
xyb8cfc9f02014-01-05 18:47:51 +08001848
1849/******************************************************************************/
1850/* str iterator */
1851
1852typedef struct _mp_obj_str_it_t {
1853 mp_obj_base_t base;
Damien George5fa93b62014-01-22 14:35:10 +00001854 mp_obj_t str;
xyb8cfc9f02014-01-05 18:47:51 +08001855 machine_uint_t cur;
1856} mp_obj_str_it_t;
1857
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001858STATIC mp_obj_t str_it_iternext(mp_obj_t self_in) {
xyb8cfc9f02014-01-05 18:47:51 +08001859 mp_obj_str_it_t *self = self_in;
Damien George5fa93b62014-01-22 14:35:10 +00001860 GET_STR_DATA_LEN(self->str, str, len);
1861 if (self->cur < len) {
Damien George2617eeb2014-05-25 22:27:57 +01001862 mp_obj_t o_out = mp_obj_new_str((const char*)str + self->cur, 1, true);
xyb8cfc9f02014-01-05 18:47:51 +08001863 self->cur += 1;
1864 return o_out;
1865 } else {
Damien Georgeea8d06c2014-04-17 23:19:36 +01001866 return MP_OBJ_STOP_ITERATION;
xyb8cfc9f02014-01-05 18:47:51 +08001867 }
1868}
1869
Damien George3e1a5c12014-03-29 13:43:38 +00001870STATIC const mp_obj_type_t mp_type_str_it = {
Damien Georgec5966122014-02-15 16:10:44 +00001871 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001872 .name = MP_QSTR_iterator,
Paul Sokolovskyf7eaf602014-03-30 22:00:12 +03001873 .getiter = mp_identity,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001874 .iternext = str_it_iternext,
xyb8cfc9f02014-01-05 18:47:51 +08001875};
1876
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001877STATIC mp_obj_t bytes_it_iternext(mp_obj_t self_in) {
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001878 mp_obj_str_it_t *self = self_in;
1879 GET_STR_DATA_LEN(self->str, str, len);
1880 if (self->cur < len) {
Damien George7c9c6672014-01-25 00:17:36 +00001881 mp_obj_t o_out = MP_OBJ_NEW_SMALL_INT((mp_small_int_t)str[self->cur]);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001882 self->cur += 1;
1883 return o_out;
1884 } else {
Damien Georgeea8d06c2014-04-17 23:19:36 +01001885 return MP_OBJ_STOP_ITERATION;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001886 }
1887}
1888
Damien George3e1a5c12014-03-29 13:43:38 +00001889STATIC const mp_obj_type_t mp_type_bytes_it = {
Damien Georgec5966122014-02-15 16:10:44 +00001890 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001891 .name = MP_QSTR_iterator,
Paul Sokolovskyf7eaf602014-03-30 22:00:12 +03001892 .getiter = mp_identity,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001893 .iternext = bytes_it_iternext,
1894};
1895
1896mp_obj_t mp_obj_new_str_iterator(mp_obj_t str) {
xyb8cfc9f02014-01-05 18:47:51 +08001897 mp_obj_str_it_t *o = m_new_obj(mp_obj_str_it_t);
Damien George3e1a5c12014-03-29 13:43:38 +00001898 o->base.type = &mp_type_str_it;
xyb8cfc9f02014-01-05 18:47:51 +08001899 o->str = str;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001900 o->cur = 0;
1901 return o;
1902}
1903
1904mp_obj_t mp_obj_new_bytes_iterator(mp_obj_t str) {
1905 mp_obj_str_it_t *o = m_new_obj(mp_obj_str_it_t);
Damien George3e1a5c12014-03-29 13:43:38 +00001906 o->base.type = &mp_type_bytes_it;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001907 o->str = str;
1908 o->cur = 0;
xyb8cfc9f02014-01-05 18:47:51 +08001909 return o;
1910}