blob: 323f3295758b7cebfb2088ee47f9b902fc3db91d [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 Sokolovsky4db727a2014-03-31 21:18:28 +030043STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, uint n_args, const mp_obj_t *args);
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 Sokolovskya47b64a2014-05-15 07:28:19 +030057mp_obj_t str_new(const mp_obj_type_t *type, const byte* data, uint len);
Paul Sokolovskye9085912014-04-30 05:35:18 +030058STATIC NORETURN void bad_implicit_conversion(mp_obj_t self_in);
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +030059STATIC NORETURN void arg_type_mixup();
60
61STATIC bool is_str_or_bytes(mp_obj_t o) {
62 return MP_OBJ_IS_STR(o) || MP_OBJ_IS_TYPE(o, &mp_type_bytes);
63}
xyb8cfc9f02014-01-05 18:47:51 +080064
65/******************************************************************************/
66/* str */
67
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020068void mp_str_print_quoted(void (*print)(void *env, const char *fmt, ...), void *env, const byte *str_data, uint str_len) {
69 // 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;
72 for (const byte *s = str_data, *top = str_data + str_len; (!has_single_quote || !has_double_quote) && s < top; s++) {
73 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, "\\\\");
89 } else if (32 <= *s && *s <= 126) {
90 print(env, "%c", *s);
91 } else if (*s == '\n') {
92 print(env, "\\n");
Andrew Scheller12968fb2014-04-08 02:42:50 +010093 } else if (*s == '\r') {
94 print(env, "\\r");
95 } else if (*s == '\t') {
96 print(env, "\\t");
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020097 } else {
98 print(env, "\\x%02x", *s);
99 }
100 }
101 print(env, "%c", quote_char);
102}
103
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200104STATIC 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 +0000105 GET_STR_DATA_LEN(self_in, str_data, str_len);
Damien George3e1a5c12014-03-29 13:43:38 +0000106 bool is_bytes = MP_OBJ_IS_TYPE(self_in, &mp_type_bytes);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +0200107 if (kind == PRINT_STR && !is_bytes) {
Damien George5fa93b62014-01-22 14:35:10 +0000108 print(env, "%.*s", str_len, str_data);
Paul Sokolovsky76d982e2014-01-13 19:19:16 +0200109 } else {
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +0200110 if (is_bytes) {
111 print(env, "b");
112 }
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +0200113 mp_str_print_quoted(print, env, str_data, str_len);
Paul Sokolovsky76d982e2014-01-13 19:19:16 +0200114 }
Damiend99b0522013-12-21 18:17:45 +0000115}
116
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200117STATIC 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 +0300118#if MICROPY_CPYTHON_COMPAT
119 if (n_kw != 0) {
120 mp_arg_error_unimpl_kw();
121 }
122#endif
123
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200124 switch (n_args) {
125 case 0:
126 return MP_OBJ_NEW_QSTR(MP_QSTR_);
127
128 case 1:
129 {
130 vstr_t *vstr = vstr_new();
131 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, vstr, args[0], PRINT_STR);
132 mp_obj_t s = mp_obj_new_str((byte*)vstr->buf, vstr->len, false);
133 vstr_free(vstr);
134 return s;
135 }
136
137 case 2:
138 case 3:
139 {
140 // TODO: validate 2nd/3rd args
Damien George3e1a5c12014-03-29 13:43:38 +0000141 if (!MP_OBJ_IS_TYPE(args[0], &mp_type_bytes)) {
Damien Georgeea13f402014-04-05 18:32:08 +0100142 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "bytes expected"));
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200143 }
144 GET_STR_DATA_LEN(args[0], str_data, str_len);
145 GET_STR_HASH(args[0], str_hash);
Damien George3e1a5c12014-03-29 13:43:38 +0000146 mp_obj_str_t *o = str_new(&mp_type_str, NULL, str_len);
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200147 o->data = str_data;
148 o->hash = str_hash;
149 return o;
150 }
151
152 default:
Damien Georgeea13f402014-04-05 18:32:08 +0100153 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "str takes at most 3 arguments"));
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200154 }
155}
156
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200157STATIC mp_obj_t bytes_make_new(mp_obj_t type_in, uint n_args, uint n_kw, const mp_obj_t *args) {
158 if (n_args == 0) {
159 return mp_const_empty_bytes;
160 }
161
Paul Sokolovskyb473d0a2014-05-06 19:30:30 +0300162#if MICROPY_CPYTHON_COMPAT
163 if (n_kw != 0) {
164 mp_arg_error_unimpl_kw();
165 }
166#endif
167
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200168 if (MP_OBJ_IS_STR(args[0])) {
169 if (n_args < 2 || n_args > 3) {
170 goto wrong_args;
171 }
172 GET_STR_DATA_LEN(args[0], str_data, str_len);
173 GET_STR_HASH(args[0], str_hash);
Damien George3e1a5c12014-03-29 13:43:38 +0000174 mp_obj_str_t *o = str_new(&mp_type_bytes, NULL, str_len);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200175 o->data = str_data;
176 o->hash = str_hash;
177 return o;
178 }
179
180 if (n_args > 1) {
181 goto wrong_args;
182 }
183
184 if (MP_OBJ_IS_SMALL_INT(args[0])) {
185 uint len = MP_OBJ_SMALL_INT_VALUE(args[0]);
186 byte *data;
187
Damien George3e1a5c12014-03-29 13:43:38 +0000188 mp_obj_t o = mp_obj_str_builder_start(&mp_type_bytes, len, &data);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200189 memset(data, 0, len);
190 return mp_obj_str_builder_end(o);
191 }
192
193 int len;
194 byte *data;
195 vstr_t *vstr = NULL;
196 mp_obj_t o = NULL;
197 // Try to create array of exact len if initializer len is known
198 mp_obj_t len_in = mp_obj_len_maybe(args[0]);
199 if (len_in == MP_OBJ_NULL) {
200 len = -1;
201 vstr = vstr_new();
202 } else {
203 len = MP_OBJ_SMALL_INT_VALUE(len_in);
Damien George3e1a5c12014-03-29 13:43:38 +0000204 o = mp_obj_str_builder_start(&mp_type_bytes, len, &data);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200205 }
206
Damien Georged17926d2014-03-30 13:35:08 +0100207 mp_obj_t iterable = mp_getiter(args[0]);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200208 mp_obj_t item;
Damien Georgeea8d06c2014-04-17 23:19:36 +0100209 while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200210 if (len == -1) {
211 vstr_add_char(vstr, MP_OBJ_SMALL_INT_VALUE(item));
212 } else {
213 *data++ = MP_OBJ_SMALL_INT_VALUE(item);
214 }
215 }
216
217 if (len == -1) {
218 vstr_shrink(vstr);
219 // TODO: Optimize, borrow buffer from vstr
220 len = vstr_len(vstr);
Damien George3e1a5c12014-03-29 13:43:38 +0000221 o = mp_obj_str_builder_start(&mp_type_bytes, len, &data);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200222 memcpy(data, vstr_str(vstr), len);
223 vstr_free(vstr);
224 }
225
226 return mp_obj_str_builder_end(o);
227
228wrong_args:
Damien Georgeea13f402014-04-05 18:32:08 +0100229 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "wrong number of arguments"));
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200230}
231
Damien George55baff42014-01-21 21:40:13 +0000232// like strstr but with specified length and allows \0 bytes
233// TODO replace with something more efficient/standard
xbe17a5a832014-03-23 23:31:58 -0700234STATIC 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 +0000235 if (hlen >= nlen) {
xbe17a5a832014-03-23 23:31:58 -0700236 machine_uint_t str_index, str_index_end;
237 if (direction > 0) {
238 str_index = 0;
239 str_index_end = hlen - nlen;
240 } else {
241 str_index = hlen - nlen;
242 str_index_end = 0;
243 }
244 for (;;) {
245 if (memcmp(&haystack[str_index], needle, nlen) == 0) {
246 //found
247 return haystack + str_index;
Damien George55baff42014-01-21 21:40:13 +0000248 }
xbe17a5a832014-03-23 23:31:58 -0700249 if (str_index == str_index_end) {
250 //not found
251 break;
Damien George55baff42014-01-21 21:40:13 +0000252 }
xbe17a5a832014-03-23 23:31:58 -0700253 str_index += direction;
Damien George55baff42014-01-21 21:40:13 +0000254 }
255 }
256 return NULL;
257}
258
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200259STATIC 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 +0000260 GET_STR_DATA_LEN(lhs_in, lhs_data, lhs_len);
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300261 mp_obj_type_t *lhs_type = mp_obj_get_type(lhs_in);
262 mp_obj_type_t *rhs_type = mp_obj_get_type(rhs_in);
Damiend99b0522013-12-21 18:17:45 +0000263 switch (op) {
Damien Georged17926d2014-03-30 13:35:08 +0100264 case MP_BINARY_OP_ADD:
265 case MP_BINARY_OP_INPLACE_ADD:
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300266 if (lhs_type == rhs_type) {
267 // add 2 strings or bytes
Damien George5fa93b62014-01-22 14:35:10 +0000268
269 GET_STR_DATA_LEN(rhs_in, rhs_data, rhs_len);
Damien George55baff42014-01-21 21:40:13 +0000270 int alloc_len = lhs_len + rhs_len;
Damien George5fa93b62014-01-22 14:35:10 +0000271
272 /* code for making qstr
Damien George55baff42014-01-21 21:40:13 +0000273 byte *q_ptr;
274 byte *val = qstr_build_start(alloc_len, &q_ptr);
275 memcpy(val, lhs_data, lhs_len);
276 memcpy(val + lhs_len, rhs_data, rhs_len);
Damien George5fa93b62014-01-22 14:35:10 +0000277 return MP_OBJ_NEW_QSTR(qstr_build_end(q_ptr));
278 */
279
280 // code for non-qstr
281 byte *data;
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300282 mp_obj_t s = mp_obj_str_builder_start(lhs_type, alloc_len, &data);
Damien George5fa93b62014-01-22 14:35:10 +0000283 memcpy(data, lhs_data, lhs_len);
284 memcpy(data + lhs_len, rhs_data, rhs_len);
285 return mp_obj_str_builder_end(s);
Damiend99b0522013-12-21 18:17:45 +0000286 }
287 break;
Damien George5fa93b62014-01-22 14:35:10 +0000288
Damien Georged17926d2014-03-30 13:35:08 +0100289 case MP_BINARY_OP_IN:
John R. Lentonc1bef212014-01-11 12:39:33 +0000290 /* NOTE `a in b` is `b.__contains__(a)` */
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300291 if (lhs_type == rhs_type) {
Damien George5fa93b62014-01-22 14:35:10 +0000292 GET_STR_DATA_LEN(rhs_in, rhs_data, rhs_len);
xbe17a5a832014-03-23 23:31:58 -0700293 return MP_BOOL(find_subbytes(lhs_data, lhs_len, rhs_data, rhs_len, 1) != NULL);
John R. Lentonc1bef212014-01-11 12:39:33 +0000294 }
295 break;
Damien George5fa93b62014-01-22 14:35:10 +0000296
Damien Georged0a5bf32014-05-10 13:55:11 +0100297 case MP_BINARY_OP_MULTIPLY: {
Paul Sokolovsky545591a2014-01-21 00:27:33 +0200298 if (!MP_OBJ_IS_SMALL_INT(rhs_in)) {
Damien George6ac5dce2014-05-21 19:42:43 +0100299 return MP_OBJ_NULL; // op not supported
Paul Sokolovsky545591a2014-01-21 00:27:33 +0200300 }
301 int n = MP_OBJ_SMALL_INT_VALUE(rhs_in);
Damien George5fa93b62014-01-22 14:35:10 +0000302 byte *data;
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300303 mp_obj_t s = mp_obj_str_builder_start(lhs_type, lhs_len * n, &data);
Damien George5fa93b62014-01-22 14:35:10 +0000304 mp_seq_multiply(lhs_data, sizeof(*lhs_data), lhs_len, n, data);
305 return mp_obj_str_builder_end(s);
Paul Sokolovsky545591a2014-01-21 00:27:33 +0200306 }
Paul Sokolovsky87e85b72014-02-02 08:24:07 +0200307
Paul Sokolovsky4db727a2014-03-31 21:18:28 +0300308 case MP_BINARY_OP_MODULO: {
309 mp_obj_t *args;
310 uint n_args;
311 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);
314 } else {
315 args = &rhs_in;
316 n_args = 1;
317 }
318 return str_modulo_format(lhs_in, n_args, args);
319 }
320
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300321 //case MP_BINARY_OP_NOT_EQUAL: // This is never passed here
322 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 +0100323 case MP_BINARY_OP_LESS:
324 case MP_BINARY_OP_LESS_EQUAL:
325 case MP_BINARY_OP_MORE:
326 case MP_BINARY_OP_MORE_EQUAL:
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300327 if (lhs_type == rhs_type) {
Paul Sokolovsky87e85b72014-02-02 08:24:07 +0200328 GET_STR_DATA_LEN(rhs_in, rhs_data, rhs_len);
329 return MP_BOOL(mp_seq_cmp_bytes(op, lhs_data, lhs_len, rhs_data, rhs_len));
330 }
Paul Sokolovsky70328e42014-05-15 20:58:40 +0300331 if (lhs_type == &mp_type_bytes) {
332 mp_buffer_info_t bufinfo;
333 if (!mp_get_buffer(rhs_in, &bufinfo, MP_BUFFER_READ)) {
334 goto uncomparable;
335 }
336 return MP_BOOL(mp_seq_cmp_bytes(op, lhs_data, lhs_len, bufinfo.buf, bufinfo.len));
337 }
338uncomparable:
339 if (op == MP_BINARY_OP_EQUAL) {
340 return mp_const_false;
341 }
Damiend99b0522013-12-21 18:17:45 +0000342 }
343
Damien George6ac5dce2014-05-21 19:42:43 +0100344 return MP_OBJ_NULL; // op not supported
Damiend99b0522013-12-21 18:17:45 +0000345}
346
Damien George729f7b42014-04-17 22:10:53 +0100347STATIC 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 +0300348 mp_obj_type_t *type = mp_obj_get_type(self_in);
Damien George729f7b42014-04-17 22:10:53 +0100349 GET_STR_DATA_LEN(self_in, self_data, self_len);
350 if (value == MP_OBJ_SENTINEL) {
351 // load
352#if MICROPY_ENABLE_SLICE
353 if (MP_OBJ_IS_TYPE(index, &mp_type_slice)) {
354 machine_uint_t start, stop;
Paul Sokolovskyd915a522014-05-10 21:36:33 +0300355 if (!mp_seq_get_fast_slice_indexes(self_len, index, &start, &stop)) {
Damien George729f7b42014-04-17 22:10:53 +0100356 assert(0);
357 }
Paul Sokolovsky5ebd5f02014-05-11 21:22:59 +0300358 return str_new(type, self_data + start, stop - start);
Damien George729f7b42014-04-17 22:10:53 +0100359 }
360#endif
Damien George729f7b42014-04-17 22:10:53 +0100361 uint index_val = mp_get_index(type, self_len, index, false);
362 if (type == &mp_type_bytes) {
363 return MP_OBJ_NEW_SMALL_INT((mp_small_int_t)self_data[index_val]);
364 } else {
365 return mp_obj_new_str(self_data + index_val, 1, true);
366 }
367 } else {
Damien George6ac5dce2014-05-21 19:42:43 +0100368 return MP_OBJ_NULL; // op not supported
Damien George729f7b42014-04-17 22:10:53 +0100369 }
370}
371
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200372STATIC mp_obj_t str_join(mp_obj_t self_in, mp_obj_t arg) {
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300373 assert(is_str_or_bytes(self_in));
374 const mp_obj_type_t *self_type = mp_obj_get_type(self_in);
Damiend99b0522013-12-21 18:17:45 +0000375
Damien Georgefe8fb912014-01-02 16:36:09 +0000376 // get separation string
Damien George5fa93b62014-01-22 14:35:10 +0000377 GET_STR_DATA_LEN(self_in, sep_str, sep_len);
Damien Georgefe8fb912014-01-02 16:36:09 +0000378
379 // process args
Damiend99b0522013-12-21 18:17:45 +0000380 uint seq_len;
381 mp_obj_t *seq_items;
Damien George07ddab52014-03-29 13:15:08 +0000382 if (MP_OBJ_IS_TYPE(arg, &mp_type_tuple)) {
Damiend99b0522013-12-21 18:17:45 +0000383 mp_obj_tuple_get(arg, &seq_len, &seq_items);
Damiend99b0522013-12-21 18:17:45 +0000384 } else {
Damien Georgea157e4c2014-04-09 19:17:53 +0100385 if (!MP_OBJ_IS_TYPE(arg, &mp_type_list)) {
386 // arg is not a list, try to convert it to one
Paul Sokolovsky881d9af2014-04-10 01:42:40 +0300387 // TODO: Try to optimize?
Damien Georgea157e4c2014-04-09 19:17:53 +0100388 arg = mp_type_list.make_new((mp_obj_t)&mp_type_list, 1, 0, &arg);
389 }
390 mp_obj_list_get(arg, &seq_len, &seq_items);
Damiend99b0522013-12-21 18:17:45 +0000391 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000392
393 // count required length
394 int required_len = 0;
Damiend99b0522013-12-21 18:17:45 +0000395 for (int i = 0; i < seq_len; i++) {
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300396 if (mp_obj_get_type(seq_items[i]) != self_type) {
397 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
398 "join expects a list of str/bytes objects consistent with self object"));
Damiend99b0522013-12-21 18:17:45 +0000399 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000400 if (i > 0) {
401 required_len += sep_len;
402 }
Damien George5fa93b62014-01-22 14:35:10 +0000403 GET_STR_LEN(seq_items[i], l);
404 required_len += l;
Damiend99b0522013-12-21 18:17:45 +0000405 }
406
407 // make joined string
Damien George5fa93b62014-01-22 14:35:10 +0000408 byte *data;
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300409 mp_obj_t joined_str = mp_obj_str_builder_start(self_type, required_len, &data);
Damiend99b0522013-12-21 18:17:45 +0000410 for (int i = 0; i < seq_len; i++) {
Damiend99b0522013-12-21 18:17:45 +0000411 if (i > 0) {
Damien George5fa93b62014-01-22 14:35:10 +0000412 memcpy(data, sep_str, sep_len);
413 data += sep_len;
Damiend99b0522013-12-21 18:17:45 +0000414 }
Damien George5fa93b62014-01-22 14:35:10 +0000415 GET_STR_DATA_LEN(seq_items[i], s, l);
416 memcpy(data, s, l);
417 data += l;
Damiend99b0522013-12-21 18:17:45 +0000418 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000419
420 // return joined string
Damien George5fa93b62014-01-22 14:35:10 +0000421 return mp_obj_str_builder_end(joined_str);
Damiend99b0522013-12-21 18:17:45 +0000422}
423
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200424#define is_ws(c) ((c) == ' ' || (c) == '\t')
425
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200426STATIC mp_obj_t str_split(uint n_args, const mp_obj_t *args) {
Paul Sokolovskybfb88192014-05-11 21:17:28 +0300427 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Damien Georgedeed0872014-04-06 11:11:15 +0100428 machine_int_t splits = -1;
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200429 mp_obj_t sep = mp_const_none;
430 if (n_args > 1) {
431 sep = args[1];
432 if (n_args > 2) {
Damien Georgedeed0872014-04-06 11:11:15 +0100433 splits = mp_obj_get_int(args[2]);
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200434 }
435 }
Damien Georgedeed0872014-04-06 11:11:15 +0100436
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200437 mp_obj_t res = mp_obj_new_list(0, NULL);
Damien George5fa93b62014-01-22 14:35:10 +0000438 GET_STR_DATA_LEN(args[0], s, len);
439 const byte *top = s + len;
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200440
Damien Georgedeed0872014-04-06 11:11:15 +0100441 if (sep == mp_const_none) {
442 // sep not given, so separate on whitespace
443
444 // Initial whitespace is not counted as split, so we pre-do it
Damien George5fa93b62014-01-22 14:35:10 +0000445 while (s < top && is_ws(*s)) s++;
Damien Georgedeed0872014-04-06 11:11:15 +0100446 while (s < top && splits != 0) {
447 const byte *start = s;
448 while (s < top && !is_ws(*s)) s++;
Paul Sokolovskybfb88192014-05-11 21:17:28 +0300449 mp_obj_list_append(res, str_new(self_type, start, s - start));
Damien Georgedeed0872014-04-06 11:11:15 +0100450 if (s >= top) {
451 break;
452 }
453 while (s < top && is_ws(*s)) s++;
454 if (splits > 0) {
455 splits--;
456 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200457 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200458
Damien Georgedeed0872014-04-06 11:11:15 +0100459 if (s < top) {
Paul Sokolovskybfb88192014-05-11 21:17:28 +0300460 mp_obj_list_append(res, str_new(self_type, s, top - s));
Damien Georgedeed0872014-04-06 11:11:15 +0100461 }
462
463 } else {
464 // sep given
465
466 uint sep_len;
467 const char *sep_str = mp_obj_str_get_data(sep, &sep_len);
468
469 if (sep_len == 0) {
470 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
471 }
472
473 for (;;) {
474 const byte *start = s;
475 for (;;) {
476 if (splits == 0 || s + sep_len > top) {
477 s = top;
478 break;
479 } else if (memcmp(s, sep_str, sep_len) == 0) {
480 break;
481 }
482 s++;
483 }
Paul Sokolovskybfb88192014-05-11 21:17:28 +0300484 mp_obj_list_append(res, str_new(self_type, start, s - start));
Damien Georgedeed0872014-04-06 11:11:15 +0100485 if (s >= top) {
486 break;
487 }
488 s += sep_len;
489 if (splits > 0) {
490 splits--;
491 }
492 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200493 }
494
495 return res;
496}
497
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300498STATIC mp_obj_t str_rsplit(uint n_args, const mp_obj_t *args) {
499 if (n_args < 3) {
500 // If we don't have split limit, it doesn't matter from which side
501 // we split.
502 return str_split(n_args, args);
503 }
504 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
505 mp_obj_t sep = args[1];
506 GET_STR_DATA_LEN(args[0], s, len);
507
508 machine_int_t splits = mp_obj_get_int(args[2]);
509 machine_int_t org_splits = splits;
510 // Preallocate list to the max expected # of elements, as we
511 // will fill it from the end.
512 mp_obj_list_t *res = mp_obj_new_list(splits + 1, NULL);
513 int idx = splits;
514
515 if (sep == mp_const_none) {
516 // TODO
517 assert(0);
518 } else {
519 uint sep_len;
520 const char *sep_str = mp_obj_str_get_data(sep, &sep_len);
521
522 if (sep_len == 0) {
523 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
524 }
525
526 const byte *beg = s;
527 const byte *last = s + len;
528 for (;;) {
529 s = last - sep_len;
530 for (;;) {
531 if (splits == 0 || s < beg) {
532 break;
533 } else if (memcmp(s, sep_str, sep_len) == 0) {
534 break;
535 }
536 s--;
537 }
538 if (s < beg || splits == 0) {
539 res->items[idx] = str_new(self_type, beg, last - beg);
540 break;
541 }
542 res->items[idx--] = str_new(self_type, s + sep_len, last - s - sep_len);
543 last = s;
544 if (splits > 0) {
545 splits--;
546 }
547 }
548 if (idx != 0) {
549 // We split less parts than split limit, now go cleanup surplus
550 int used = org_splits + 1 - idx;
551 memcpy(res->items, &res->items[idx], used * sizeof(mp_obj_t));
552 mp_seq_clear(res->items, used, res->alloc, sizeof(*res->items));
553 res->len = used;
554 }
555 }
556
557 return res;
558}
559
560
xbe3d9a39e2014-04-08 11:42:19 -0700561STATIC 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 +0000562 assert(2 <= n_args && n_args <= 4);
Damien George5fa93b62014-01-22 14:35:10 +0000563 assert(MP_OBJ_IS_STR(args[0]));
564 assert(MP_OBJ_IS_STR(args[1]));
John R. Lentone8204912014-01-12 21:53:52 +0000565
Damien George5fa93b62014-01-22 14:35:10 +0000566 GET_STR_DATA_LEN(args[0], haystack, haystack_len);
567 GET_STR_DATA_LEN(args[1], needle, needle_len);
John R. Lentone8204912014-01-12 21:53:52 +0000568
xbec5538882014-03-16 17:58:35 -0700569 machine_uint_t start = 0;
570 machine_uint_t end = haystack_len;
John R. Lentone8204912014-01-12 21:53:52 +0000571 if (n_args >= 3 && args[2] != mp_const_none) {
Damien George3e1a5c12014-03-29 13:43:38 +0000572 start = mp_get_index(&mp_type_str, haystack_len, args[2], true);
John R. Lentone8204912014-01-12 21:53:52 +0000573 }
574 if (n_args >= 4 && args[3] != mp_const_none) {
Damien George3e1a5c12014-03-29 13:43:38 +0000575 end = mp_get_index(&mp_type_str, haystack_len, args[3], true);
John R. Lentone8204912014-01-12 21:53:52 +0000576 }
577
xbe17a5a832014-03-23 23:31:58 -0700578 const byte *p = find_subbytes(haystack + start, end - start, needle, needle_len, direction);
Damien George23005372014-01-13 19:39:01 +0000579 if (p == NULL) {
580 // not found
xbe3d9a39e2014-04-08 11:42:19 -0700581 if (is_index) {
582 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "substring not found"));
583 } else {
584 return MP_OBJ_NEW_SMALL_INT(-1);
585 }
Damien George23005372014-01-13 19:39:01 +0000586 } else {
587 // found
xbe17a5a832014-03-23 23:31:58 -0700588 return MP_OBJ_NEW_SMALL_INT(p - haystack);
John R. Lentone8204912014-01-12 21:53:52 +0000589 }
John R. Lentone8204912014-01-12 21:53:52 +0000590}
591
xbe17a5a832014-03-23 23:31:58 -0700592STATIC mp_obj_t str_find(uint n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700593 return str_finder(n_args, args, 1, false);
xbe17a5a832014-03-23 23:31:58 -0700594}
595
596STATIC mp_obj_t str_rfind(uint n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700597 return str_finder(n_args, args, -1, false);
598}
599
600STATIC mp_obj_t str_index(uint n_args, const mp_obj_t *args) {
601 return str_finder(n_args, args, 1, true);
602}
603
604STATIC mp_obj_t str_rindex(uint n_args, const mp_obj_t *args) {
605 return str_finder(n_args, args, -1, true);
xbe17a5a832014-03-23 23:31:58 -0700606}
607
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200608// TODO: (Much) more variety in args
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300609STATIC mp_obj_t str_startswith(uint n_args, const mp_obj_t *args) {
610 GET_STR_DATA_LEN(args[0], str, str_len);
611 GET_STR_DATA_LEN(args[1], prefix, prefix_len);
612 uint index_val = 0;
613 if (n_args > 2) {
614 index_val = mp_get_index(&mp_type_str, str_len, args[2], true);
615 }
616 if (prefix_len + index_val > str_len) {
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200617 return mp_const_false;
618 }
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300619 return MP_BOOL(memcmp(str + index_val, prefix, prefix_len) == 0);
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200620}
621
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +0300622STATIC mp_obj_t str_endswith(uint n_args, const mp_obj_t *args) {
623 GET_STR_DATA_LEN(args[0], str, str_len);
624 GET_STR_DATA_LEN(args[1], suffix, suffix_len);
625 assert(n_args == 2);
626
627 if (suffix_len > str_len) {
628 return mp_const_false;
629 }
630 return MP_BOOL(memcmp(str + (str_len - suffix_len), suffix, suffix_len) == 0);
631}
632
Paul Sokolovsky88107842014-04-26 06:20:08 +0300633enum { LSTRIP, RSTRIP, STRIP };
634
635STATIC mp_obj_t str_uni_strip(int type, uint n_args, const mp_obj_t *args) {
xbe7b0f39f2014-01-08 14:23:45 -0800636 assert(1 <= n_args && n_args <= 2);
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300637 assert(is_str_or_bytes(args[0]));
638 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Damien George5fa93b62014-01-22 14:35:10 +0000639
640 const byte *chars_to_del;
641 uint chars_to_del_len;
642 static const byte whitespace[] = " \t\n\r\v\f";
xbe7b0f39f2014-01-08 14:23:45 -0800643
644 if (n_args == 1) {
645 chars_to_del = whitespace;
Damien George5fa93b62014-01-22 14:35:10 +0000646 chars_to_del_len = sizeof(whitespace);
xbe7b0f39f2014-01-08 14:23:45 -0800647 } else {
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300648 if (mp_obj_get_type(args[1]) != self_type) {
649 arg_type_mixup();
650 }
Damien George5fa93b62014-01-22 14:35:10 +0000651 GET_STR_DATA_LEN(args[1], s, l);
652 chars_to_del = s;
653 chars_to_del_len = l;
xbe7b0f39f2014-01-08 14:23:45 -0800654 }
655
Damien George5fa93b62014-01-22 14:35:10 +0000656 GET_STR_DATA_LEN(args[0], orig_str, orig_str_len);
xbe7b0f39f2014-01-08 14:23:45 -0800657
xbec5538882014-03-16 17:58:35 -0700658 machine_uint_t first_good_char_pos = 0;
xbe7b0f39f2014-01-08 14:23:45 -0800659 bool first_good_char_pos_set = false;
xbec5538882014-03-16 17:58:35 -0700660 machine_uint_t last_good_char_pos = 0;
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300661 machine_uint_t i = 0;
662 machine_int_t delta = 1;
663 if (type == RSTRIP) {
664 i = orig_str_len - 1;
665 delta = -1;
666 }
667 for (machine_uint_t len = orig_str_len; len > 0; len--) {
xbe17a5a832014-03-23 23:31:58 -0700668 if (find_subbytes(chars_to_del, chars_to_del_len, &orig_str[i], 1, 1) == NULL) {
xbe7b0f39f2014-01-08 14:23:45 -0800669 if (!first_good_char_pos_set) {
670 first_good_char_pos = i;
Paul Sokolovsky88107842014-04-26 06:20:08 +0300671 if (type == LSTRIP) {
672 last_good_char_pos = orig_str_len - 1;
673 break;
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300674 } else if (type == RSTRIP) {
675 first_good_char_pos = 0;
676 last_good_char_pos = i;
677 break;
Paul Sokolovsky88107842014-04-26 06:20:08 +0300678 }
xbe7b0f39f2014-01-08 14:23:45 -0800679 first_good_char_pos_set = true;
680 }
Paul Sokolovsky88107842014-04-26 06:20:08 +0300681 last_good_char_pos = i;
xbe7b0f39f2014-01-08 14:23:45 -0800682 }
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300683 i += delta;
xbe7b0f39f2014-01-08 14:23:45 -0800684 }
685
686 if (first_good_char_pos == 0 && last_good_char_pos == 0) {
Damien George5fa93b62014-01-22 14:35:10 +0000687 // string is all whitespace, return ''
688 return MP_OBJ_NEW_QSTR(MP_QSTR_);
xbe7b0f39f2014-01-08 14:23:45 -0800689 }
690
691 assert(last_good_char_pos >= first_good_char_pos);
692 //+1 to accomodate the last character
xbec5538882014-03-16 17:58:35 -0700693 machine_uint_t stripped_len = last_good_char_pos - first_good_char_pos + 1;
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300694 return str_new(self_type, orig_str + first_good_char_pos, stripped_len);
xbe7b0f39f2014-01-08 14:23:45 -0800695}
696
Paul Sokolovsky88107842014-04-26 06:20:08 +0300697STATIC mp_obj_t str_strip(uint n_args, const mp_obj_t *args) {
698 return str_uni_strip(STRIP, n_args, args);
699}
700
701STATIC mp_obj_t str_lstrip(uint n_args, const mp_obj_t *args) {
702 return str_uni_strip(LSTRIP, n_args, args);
703}
704
705STATIC mp_obj_t str_rstrip(uint n_args, const mp_obj_t *args) {
706 return str_uni_strip(RSTRIP, n_args, args);
707}
708
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700709// Takes an int arg, but only parses unsigned numbers, and only changes
710// *num if at least one digit was parsed.
711static int str_to_int(const char *str, int *num) {
712 const char *s = str;
713 if (unichar_isdigit(*s)) {
714 *num = 0;
715 do {
716 *num = *num * 10 + (*s - '0');
717 s++;
718 }
719 while (unichar_isdigit(*s));
720 }
721 return s - str;
722}
723
724static bool isalignment(char ch) {
725 return ch && strchr("<>=^", ch) != NULL;
726}
727
728static bool istype(char ch) {
729 return ch && strchr("bcdeEfFgGnosxX%", ch) != NULL;
730}
731
732static bool arg_looks_integer(mp_obj_t arg) {
733 return MP_OBJ_IS_TYPE(arg, &mp_type_bool) || MP_OBJ_IS_INT(arg);
734}
735
736static bool arg_looks_numeric(mp_obj_t arg) {
737 return arg_looks_integer(arg)
738#if MICROPY_ENABLE_FLOAT
739 || MP_OBJ_IS_TYPE(arg, &mp_type_float)
740#endif
741 ;
742}
743
Dave Hylandsc4029e52014-04-07 11:19:51 -0700744static mp_obj_t arg_as_int(mp_obj_t arg) {
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700745#if MICROPY_ENABLE_FLOAT
746 if (MP_OBJ_IS_TYPE(arg, &mp_type_float)) {
Dave Hylandsc4029e52014-04-07 11:19:51 -0700747
748 // TODO: Needs a way to construct an mpz integer from a float
749
750 mp_small_int_t num = mp_obj_get_float(arg);
751 return MP_OBJ_NEW_SMALL_INT(num);
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700752 }
753#endif
Dave Hylandsc4029e52014-04-07 11:19:51 -0700754 return arg;
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700755}
756
Damien George897fe0c2014-04-15 22:03:55 +0100757mp_obj_t mp_obj_str_format(uint n_args, const mp_obj_t *args) {
Damien George5fa93b62014-01-22 14:35:10 +0000758 assert(MP_OBJ_IS_STR(args[0]));
Damiend99b0522013-12-21 18:17:45 +0000759
Damien George5fa93b62014-01-22 14:35:10 +0000760 GET_STR_DATA_LEN(args[0], str, len);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700761 int arg_i = 0;
Damiend99b0522013-12-21 18:17:45 +0000762 vstr_t *vstr = vstr_new();
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700763 pfenv_t pfenv_vstr;
764 pfenv_vstr.data = vstr;
765 pfenv_vstr.print_strn = pfenv_vstr_add_strn;
766
Damien George5fa93b62014-01-22 14:35:10 +0000767 for (const byte *top = str + len; str < top; str++) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700768 if (*str == '}') {
Damiend99b0522013-12-21 18:17:45 +0000769 str++;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700770 if (str < top && *str == '}') {
771 vstr_add_char(vstr, '}');
772 continue;
773 }
Damien Georgeea13f402014-04-05 18:32:08 +0100774 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "Single '}' encountered in format string"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700775 }
776 if (*str != '{') {
777 vstr_add_char(vstr, *str);
778 continue;
779 }
780
781 str++;
782 if (str < top && *str == '{') {
783 vstr_add_char(vstr, '{');
784 continue;
785 }
786
787 // replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"
788
789 vstr_t *field_name = NULL;
790 char conversion = '\0';
791 vstr_t *format_spec = NULL;
792
793 if (str < top && *str != '}' && *str != '!' && *str != ':') {
794 field_name = vstr_new();
795 while (str < top && *str != '}' && *str != '!' && *str != ':') {
796 vstr_add_char(field_name, *str++);
797 }
798 vstr_add_char(field_name, '\0');
799 }
800
801 // conversion ::= "r" | "s"
802
803 if (str < top && *str == '!') {
804 str++;
805 if (str < top && (*str == 'r' || *str == 's')) {
806 conversion = *str++;
Paul Sokolovskyf2b796e2014-01-15 22:45:20 +0200807 } else {
Damien Georgeea13f402014-04-05 18:32:08 +0100808 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 -0700809 }
810 }
811
812 if (str < top && *str == ':') {
813 str++;
814 // {:} is the same as {}, which is the same as {!s}
815 // This makes a difference when passing in a True or False
816 // '{}'.format(True) returns 'True'
817 // '{:d}'.format(True) returns '1'
818 // So we treat {:} as {} and this later gets treated to be {!s}
819 if (*str != '}') {
820 format_spec = vstr_new();
821 while (str < top && *str != '}') {
822 vstr_add_char(format_spec, *str++);
Damiend99b0522013-12-21 18:17:45 +0000823 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700824 vstr_add_char(format_spec, '\0');
825 }
826 }
827 if (str >= top) {
Damien Georgeea13f402014-04-05 18:32:08 +0100828 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "unmatched '{' in format"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700829 }
830 if (*str != '}') {
Damien Georgeea13f402014-04-05 18:32:08 +0100831 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "expected ':' after format specifier"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700832 }
833
834 mp_obj_t arg = mp_const_none;
835
836 if (field_name) {
837 if (arg_i > 0) {
Damien Georgeea13f402014-04-05 18:32:08 +0100838 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "cannot switch from automatic field numbering to manual field specification"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700839 }
Damien George3bb8bd82014-04-14 21:20:30 +0100840 int index = 0;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700841 if (str_to_int(vstr_str(field_name), &index) != vstr_len(field_name) - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100842 nlr_raise(mp_obj_new_exception_msg(&mp_type_KeyError, "attributes not supported yet"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700843 }
844 if (index >= n_args - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100845 nlr_raise(mp_obj_new_exception_msg(&mp_type_IndexError, "tuple index out of range"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700846 }
847 arg = args[index + 1];
848 arg_i = -1;
849 vstr_free(field_name);
850 field_name = NULL;
851 } else {
852 if (arg_i < 0) {
Damien Georgeea13f402014-04-05 18:32:08 +0100853 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "cannot switch from manual field specification to automatic field numbering"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700854 }
855 if (arg_i >= n_args - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100856 nlr_raise(mp_obj_new_exception_msg(&mp_type_IndexError, "tuple index out of range"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700857 }
858 arg = args[arg_i + 1];
859 arg_i++;
860 }
861 if (!format_spec && !conversion) {
862 conversion = 's';
863 }
864 if (conversion) {
865 mp_print_kind_t print_kind;
866 if (conversion == 's') {
867 print_kind = PRINT_STR;
868 } else if (conversion == 'r') {
869 print_kind = PRINT_REPR;
870 } else {
Damien Georgeea13f402014-04-05 18:32:08 +0100871 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Unknown conversion specifier %c", conversion));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700872 }
873 vstr_t *arg_vstr = vstr_new();
874 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, arg_vstr, arg, print_kind);
875 arg = mp_obj_new_str((const byte *)vstr_str(arg_vstr), vstr_len(arg_vstr), false);
876 vstr_free(arg_vstr);
877 }
878
879 char sign = '\0';
880 char fill = '\0';
881 char align = '\0';
882 int width = -1;
883 int precision = -1;
884 char type = '\0';
885 int flags = 0;
886
887 if (format_spec) {
888 // The format specifier (from http://docs.python.org/2/library/string.html#formatspec)
889 //
890 // [[fill]align][sign][#][0][width][,][.precision][type]
891 // fill ::= <any character>
892 // align ::= "<" | ">" | "=" | "^"
893 // sign ::= "+" | "-" | " "
894 // width ::= integer
895 // precision ::= integer
896 // type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
897
898 const char *s = vstr_str(format_spec);
899 if (isalignment(*s)) {
900 align = *s++;
901 } else if (*s && isalignment(s[1])) {
902 fill = *s++;
903 align = *s++;
904 }
905 if (*s == '+' || *s == '-' || *s == ' ') {
906 if (*s == '+') {
907 flags |= PF_FLAG_SHOW_SIGN;
908 } else if (*s == ' ') {
909 flags |= PF_FLAG_SPACE_SIGN;
910 }
911 sign = *s++;
912 }
913 if (*s == '#') {
914 flags |= PF_FLAG_SHOW_PREFIX;
915 s++;
916 }
917 if (*s == '0') {
918 if (!align) {
919 align = '=';
920 }
921 if (!fill) {
922 fill = '0';
923 }
924 }
925 s += str_to_int(s, &width);
926 if (*s == ',') {
927 flags |= PF_FLAG_SHOW_COMMA;
928 s++;
929 }
930 if (*s == '.') {
931 s++;
932 s += str_to_int(s, &precision);
933 }
934 if (istype(*s)) {
935 type = *s++;
936 }
937 if (*s) {
Damien Georgeea13f402014-04-05 18:32:08 +0100938 nlr_raise(mp_obj_new_exception_msg(&mp_type_KeyError, "Invalid conversion specification"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700939 }
940 vstr_free(format_spec);
941 format_spec = NULL;
942 }
943 if (!align) {
944 if (arg_looks_numeric(arg)) {
945 align = '>';
946 } else {
947 align = '<';
948 }
949 }
950 if (!fill) {
951 fill = ' ';
952 }
953
954 if (sign) {
955 if (type == 's') {
Damien Georgeea13f402014-04-05 18:32:08 +0100956 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "Sign not allowed in string format specifier"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700957 }
958 if (type == 'c') {
Damien Georgeea13f402014-04-05 18:32:08 +0100959 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "Sign not allowed with integer format specifier 'c'"));
Damiend99b0522013-12-21 18:17:45 +0000960 }
961 } else {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700962 sign = '-';
963 }
964
965 switch (align) {
966 case '<': flags |= PF_FLAG_LEFT_ADJUST; break;
967 case '=': flags |= PF_FLAG_PAD_AFTER_SIGN; break;
968 case '^': flags |= PF_FLAG_CENTER_ADJUST; break;
969 }
970
971 if (arg_looks_integer(arg)) {
972 switch (type) {
973 case 'b':
Damien Georgea12a0f72014-04-08 01:29:53 +0100974 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 2, 'a', flags, fill, width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700975 continue;
976
977 case 'c':
978 {
979 char ch = mp_obj_get_int(arg);
980 pfenv_print_strn(&pfenv_vstr, &ch, 1, flags, fill, width);
981 continue;
982 }
983
984 case '\0': // No explicit format type implies 'd'
985 case 'n': // I don't think we support locales in uPy so use 'd'
986 case 'd':
Damien Georgea12a0f72014-04-08 01:29:53 +0100987 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 10, 'a', flags, fill, width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700988 continue;
989
990 case 'o':
Dave Hylandsc4029e52014-04-07 11:19:51 -0700991 if (flags & PF_FLAG_SHOW_PREFIX) {
992 flags |= PF_FLAG_SHOW_OCTAL_LETTER;
993 }
994
Damien Georgea12a0f72014-04-08 01:29:53 +0100995 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 8, 'a', flags, fill, width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700996 continue;
997
998 case 'x':
Damien Georgea12a0f72014-04-08 01:29:53 +0100999 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 16, 'a', flags, fill, width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001000 continue;
1001
1002 case 'X':
Damien Georgea12a0f72014-04-08 01:29:53 +01001003 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 16, 'A', flags, fill, width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001004 continue;
1005
1006 case 'e':
1007 case 'E':
1008 case 'f':
1009 case 'F':
1010 case 'g':
1011 case 'G':
1012 case '%':
1013 // The floating point formatters all work with anything that
1014 // looks like an integer
1015 break;
1016
1017 default:
Damien Georgeea13f402014-04-05 18:32:08 +01001018 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001019 "Unknown format code '%c' for object of type '%s'", type, mp_obj_get_type_str(arg)));
1020 }
Damien Georgec322c5f2014-04-02 20:04:15 +01001021 }
Damien George70f33cd2014-04-02 17:06:05 +01001022
Dave Hylands22fe4d72014-04-02 12:07:31 -07001023 // NOTE: no else here. We need the e, f, g etc formats for integer
1024 // arguments (from above if) to take this if.
Damien Georgec322c5f2014-04-02 20:04:15 +01001025 if (arg_looks_numeric(arg)) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001026 if (!type) {
1027
1028 // Even though the docs say that an unspecified type is the same
1029 // as 'g', there is one subtle difference, when the exponent
1030 // is one less than the precision.
1031 //
1032 // '{:10.1}'.format(0.0) ==> '0e+00'
1033 // '{:10.1g}'.format(0.0) ==> '0'
1034 //
1035 // TODO: Figure out how to deal with this.
1036 //
1037 // A proper solution would involve adding a special flag
1038 // or something to format_float, and create a format_double
1039 // to deal with doubles. In order to fix this when using
1040 // sprintf, we'd need to use the e format and tweak the
1041 // returned result to strip trailing zeros like the g format
1042 // does.
1043 //
1044 // {:10.3} and {:10.2e} with 1.23e2 both produce 1.23e+02
1045 // but with 1.e2 you get 1e+02 and 1.00e+02
1046 //
1047 // Stripping the trailing 0's (like g) does would make the
1048 // e format give us the right format.
1049 //
1050 // CPython sources say:
1051 // Omitted type specifier. Behaves in the same way as repr(x)
1052 // and str(x) if no precision is given, else like 'g', but with
1053 // at least one digit after the decimal point. */
1054
1055 type = 'g';
1056 }
1057 if (type == 'n') {
1058 type = 'g';
1059 }
1060
1061 flags |= PF_FLAG_PAD_NAN_INF; // '{:06e}'.format(float('-inf')) should give '-00inf'
1062 switch (type) {
Damien Georgec322c5f2014-04-02 20:04:15 +01001063#if MICROPY_ENABLE_FLOAT
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001064 case 'e':
1065 case 'E':
1066 case 'f':
1067 case 'F':
1068 case 'g':
1069 case 'G':
1070 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg), type, flags, fill, width, precision);
1071 break;
1072
1073 case '%':
1074 flags |= PF_FLAG_ADD_PERCENT;
1075 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg) * 100.0F, 'f', flags, fill, width, precision);
1076 break;
Damien Georgec322c5f2014-04-02 20:04:15 +01001077#endif
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001078
1079 default:
Damien Georgeea13f402014-04-05 18:32:08 +01001080 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001081 "Unknown format code '%c' for object of type 'float'",
1082 type, mp_obj_get_type_str(arg)));
1083 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001084 } else {
Damien George70f33cd2014-04-02 17:06:05 +01001085 // arg doesn't look like a number
1086
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001087 if (align == '=') {
Damien Georgeea13f402014-04-05 18:32:08 +01001088 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "'=' alignment not allowed in string format specifier"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001089 }
Damien George70f33cd2014-04-02 17:06:05 +01001090
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001091 switch (type) {
1092 case '\0':
1093 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, vstr, arg, PRINT_STR);
1094 break;
1095
1096 case 's':
1097 {
1098 uint len;
1099 const char *s = mp_obj_str_get_data(arg, &len);
1100 if (precision < 0) {
1101 precision = len;
1102 }
1103 if (len > precision) {
1104 len = precision;
1105 }
1106 pfenv_print_strn(&pfenv_vstr, s, len, flags, fill, width);
1107 break;
1108 }
1109
1110 default:
Damien Georgeea13f402014-04-05 18:32:08 +01001111 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001112 "Unknown format code '%c' for object of type 'str'",
1113 type, mp_obj_get_type_str(arg)));
1114 }
Damiend99b0522013-12-21 18:17:45 +00001115 }
1116 }
1117
Damien George5fa93b62014-01-22 14:35:10 +00001118 mp_obj_t s = mp_obj_new_str((byte*)vstr->buf, vstr->len, false);
1119 vstr_free(vstr);
1120 return s;
Damiend99b0522013-12-21 18:17:45 +00001121}
1122
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001123STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, uint n_args, const mp_obj_t *args) {
1124 assert(MP_OBJ_IS_STR(pattern));
1125
1126 GET_STR_DATA_LEN(pattern, str, len);
Dave Hylands6756a372014-04-02 11:42:39 -07001127 const byte *start_str = str;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001128 int arg_i = 0;
1129 vstr_t *vstr = vstr_new();
Dave Hylands6756a372014-04-02 11:42:39 -07001130 pfenv_t pfenv_vstr;
1131 pfenv_vstr.data = vstr;
1132 pfenv_vstr.print_strn = pfenv_vstr_add_strn;
1133
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001134 for (const byte *top = str + len; str < top; str++) {
Dave Hylands6756a372014-04-02 11:42:39 -07001135 if (*str != '%') {
1136 vstr_add_char(vstr, *str);
1137 continue;
1138 }
1139 if (++str >= top) {
1140 break;
1141 }
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001142 if (*str == '%') {
Dave Hylands6756a372014-04-02 11:42:39 -07001143 vstr_add_char(vstr, '%');
1144 continue;
1145 }
1146 if (arg_i >= n_args) {
Damien Georgeea13f402014-04-05 18:32:08 +01001147 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "not enough arguments for format string"));
Dave Hylands6756a372014-04-02 11:42:39 -07001148 }
1149 int flags = 0;
1150 char fill = ' ';
1151 bool alt = false;
1152 while (str < top) {
1153 if (*str == '-') flags |= PF_FLAG_LEFT_ADJUST;
1154 else if (*str == '+') flags |= PF_FLAG_SHOW_SIGN;
1155 else if (*str == ' ') flags |= PF_FLAG_SPACE_SIGN;
1156 else if (*str == '#') alt = true;
1157 else if (*str == '0') {
1158 flags |= PF_FLAG_PAD_AFTER_SIGN;
1159 fill = '0';
1160 } else break;
1161 str++;
1162 }
1163 // parse width, if it exists
1164 int width = 0;
1165 if (str < top) {
1166 if (*str == '*') {
1167 width = mp_obj_get_int(args[arg_i++]);
1168 str++;
1169 } else {
1170 for (; str < top && '0' <= *str && *str <= '9'; str++) {
1171 width = width * 10 + *str - '0';
1172 }
1173 }
1174 }
1175 int prec = -1;
1176 if (str < top && *str == '.') {
1177 if (++str < top) {
1178 if (*str == '*') {
1179 prec = mp_obj_get_int(args[arg_i++]);
1180 str++;
1181 } else {
1182 prec = 0;
1183 for (; str < top && '0' <= *str && *str <= '9'; str++) {
1184 prec = prec * 10 + *str - '0';
1185 }
1186 }
1187 }
1188 }
1189
1190 if (str >= top) {
Damien Georgeea13f402014-04-05 18:32:08 +01001191 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "incomplete format"));
Dave Hylands6756a372014-04-02 11:42:39 -07001192 }
1193 mp_obj_t arg = args[arg_i];
1194 switch (*str) {
1195 case 'c':
1196 if (MP_OBJ_IS_STR(arg)) {
1197 uint len;
1198 const char *s = mp_obj_str_get_data(arg, &len);
1199 if (len != 1) {
Damien Georgeea13f402014-04-05 18:32:08 +01001200 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "%c requires int or char"));
Dave Hylands6756a372014-04-02 11:42:39 -07001201 break;
1202 }
1203 pfenv_print_strn(&pfenv_vstr, s, 1, flags, ' ', width);
1204 break;
1205 }
1206 if (arg_looks_integer(arg)) {
1207 char ch = mp_obj_get_int(arg);
1208 pfenv_print_strn(&pfenv_vstr, &ch, 1, flags, ' ', width);
1209 break;
1210 }
1211#if MICROPY_ENABLE_FLOAT
1212 // This is what CPython reports, so we report the same.
1213 if (MP_OBJ_IS_TYPE(arg, &mp_type_float)) {
Damien Georgeea13f402014-04-05 18:32:08 +01001214 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "integer argument expected, got float"));
Dave Hylands6756a372014-04-02 11:42:39 -07001215
1216 }
1217#endif
Damien Georgeea13f402014-04-05 18:32:08 +01001218 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "an integer is required"));
Dave Hylands6756a372014-04-02 11:42:39 -07001219 break;
1220
1221 case 'd':
1222 case 'i':
1223 case 'u':
Damien Georgea12a0f72014-04-08 01:29:53 +01001224 pfenv_print_mp_int(&pfenv_vstr, arg_as_int(arg), 1, 10, 'a', flags, fill, width);
Dave Hylands6756a372014-04-02 11:42:39 -07001225 break;
1226
1227#if MICROPY_ENABLE_FLOAT
1228 case 'e':
1229 case 'E':
1230 case 'f':
1231 case 'F':
1232 case 'g':
1233 case 'G':
1234 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg), *str, flags, fill, width, prec);
1235 break;
1236#endif
1237
1238 case 'o':
1239 if (alt) {
Dave Hylandsc4029e52014-04-07 11:19:51 -07001240 flags |= (PF_FLAG_SHOW_PREFIX | PF_FLAG_SHOW_OCTAL_LETTER);
Dave Hylands6756a372014-04-02 11:42:39 -07001241 }
Damien Georgea12a0f72014-04-08 01:29:53 +01001242 pfenv_print_mp_int(&pfenv_vstr, arg_as_int(arg), 1, 8, 'a', flags, fill, width);
Dave Hylands6756a372014-04-02 11:42:39 -07001243 break;
1244
1245 case 'r':
1246 case 's':
1247 {
1248 vstr_t *arg_vstr = vstr_new();
1249 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf,
1250 arg_vstr, arg, *str == 'r' ? PRINT_REPR : PRINT_STR);
1251 uint len = vstr_len(arg_vstr);
1252 if (prec < 0) {
1253 prec = len;
1254 }
1255 if (len > prec) {
1256 len = prec;
1257 }
1258 pfenv_print_strn(&pfenv_vstr, vstr_str(arg_vstr), len, flags, ' ', width);
1259 vstr_free(arg_vstr);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001260 break;
1261 }
Dave Hylands6756a372014-04-02 11:42:39 -07001262
1263 case 'x':
1264 if (alt) {
1265 flags |= PF_FLAG_SHOW_PREFIX;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001266 }
Damien Georgea12a0f72014-04-08 01:29:53 +01001267 pfenv_print_mp_int(&pfenv_vstr, arg_as_int(arg), 1, 16, 'a', flags, fill, width);
Dave Hylands6756a372014-04-02 11:42:39 -07001268 break;
1269
1270 case 'X':
1271 if (alt) {
1272 flags |= PF_FLAG_SHOW_PREFIX;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001273 }
Damien Georgea12a0f72014-04-08 01:29:53 +01001274 pfenv_print_mp_int(&pfenv_vstr, arg_as_int(arg), 1, 16, 'A', flags, fill, width);
Dave Hylands6756a372014-04-02 11:42:39 -07001275 break;
Damien Georgedeed0872014-04-06 11:11:15 +01001276
Dave Hylands6756a372014-04-02 11:42:39 -07001277 default:
Damien Georgeea13f402014-04-05 18:32:08 +01001278 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Dave Hylands6756a372014-04-02 11:42:39 -07001279 "unsupported format character '%c' (0x%x) at index %d",
1280 *str, *str, str - start_str));
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001281 }
Dave Hylands6756a372014-04-02 11:42:39 -07001282 arg_i++;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001283 }
1284
1285 if (arg_i != n_args) {
Damien Georgeea13f402014-04-05 18:32:08 +01001286 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "not all arguments converted during string formatting"));
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001287 }
1288
1289 mp_obj_t s = mp_obj_new_str((byte*)vstr->buf, vstr->len, false);
1290 vstr_free(vstr);
1291 return s;
1292}
1293
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001294STATIC mp_obj_t str_replace(uint n_args, const mp_obj_t *args) {
xbe480c15a2014-01-30 22:17:30 -08001295 assert(MP_OBJ_IS_STR(args[0]));
xbe480c15a2014-01-30 22:17:30 -08001296
Damien Georgeff715422014-04-07 00:39:13 +01001297 machine_int_t max_rep = -1;
xbe480c15a2014-01-30 22:17:30 -08001298 if (n_args == 4) {
Damien Georgeff715422014-04-07 00:39:13 +01001299 max_rep = mp_obj_get_int(args[3]);
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001300 if (max_rep == 0) {
1301 return args[0];
1302 } else if (max_rep < 0) {
Damien Georgeff715422014-04-07 00:39:13 +01001303 max_rep = -1;
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001304 }
xbe480c15a2014-01-30 22:17:30 -08001305 }
Damien George94f68302014-01-31 23:45:12 +00001306
xbe729be9b2014-04-07 14:46:39 -07001307 // if max_rep is still -1 by this point we will need to do all possible replacements
xbe480c15a2014-01-30 22:17:30 -08001308
Damien Georgeff715422014-04-07 00:39:13 +01001309 // check argument types
1310
1311 if (!MP_OBJ_IS_STR(args[1])) {
1312 bad_implicit_conversion(args[1]);
1313 }
1314
1315 if (!MP_OBJ_IS_STR(args[2])) {
1316 bad_implicit_conversion(args[2]);
1317 }
1318
1319 // extract string data
1320
xbe480c15a2014-01-30 22:17:30 -08001321 GET_STR_DATA_LEN(args[0], str, str_len);
1322 GET_STR_DATA_LEN(args[1], old, old_len);
1323 GET_STR_DATA_LEN(args[2], new, new_len);
Damien George94f68302014-01-31 23:45:12 +00001324
1325 // old won't exist in str if it's longer, so nothing to replace
xbe480c15a2014-01-30 22:17:30 -08001326 if (old_len > str_len) {
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001327 return args[0];
xbe480c15a2014-01-30 22:17:30 -08001328 }
1329
Damien George94f68302014-01-31 23:45:12 +00001330 // data for the replaced string
1331 byte *data = NULL;
1332 mp_obj_t replaced_str = MP_OBJ_NULL;
xbe480c15a2014-01-30 22:17:30 -08001333
Damien George94f68302014-01-31 23:45:12 +00001334 // do 2 passes over the string:
1335 // first pass computes the required length of the replaced string
1336 // second pass does the replacements
1337 for (;;) {
1338 machine_uint_t replaced_str_index = 0;
1339 machine_uint_t num_replacements_done = 0;
1340 const byte *old_occurrence;
1341 const byte *offset_ptr = str;
Damien Georgeff715422014-04-07 00:39:13 +01001342 machine_uint_t str_len_remain = str_len;
1343 if (old_len == 0) {
1344 // if old_str is empty, copy new_str to start of replaced string
1345 // copy the replacement string
1346 if (data != NULL) {
1347 memcpy(data, new, new_len);
1348 }
1349 replaced_str_index += new_len;
1350 num_replacements_done++;
1351 }
1352 while (num_replacements_done != max_rep && str_len_remain > 0 && (old_occurrence = find_subbytes(offset_ptr, str_len_remain, old, old_len, 1)) != NULL) {
1353 if (old_len == 0) {
1354 old_occurrence += 1;
1355 }
Damien George94f68302014-01-31 23:45:12 +00001356 // copy from just after end of last occurrence of to-be-replaced string to right before start of next occurrence
1357 if (data != NULL) {
1358 memcpy(data + replaced_str_index, offset_ptr, old_occurrence - offset_ptr);
1359 }
1360 replaced_str_index += old_occurrence - offset_ptr;
1361 // copy the replacement string
1362 if (data != NULL) {
1363 memcpy(data + replaced_str_index, new, new_len);
1364 }
1365 replaced_str_index += new_len;
1366 offset_ptr = old_occurrence + old_len;
Damien Georgeff715422014-04-07 00:39:13 +01001367 str_len_remain = str + str_len - offset_ptr;
Damien George94f68302014-01-31 23:45:12 +00001368 num_replacements_done++;
Damien George94f68302014-01-31 23:45:12 +00001369 }
1370
1371 // copy from just after end of last occurrence of to-be-replaced string to end of old string
1372 if (data != NULL) {
Damien Georgeff715422014-04-07 00:39:13 +01001373 memcpy(data + replaced_str_index, offset_ptr, str_len_remain);
Damien George94f68302014-01-31 23:45:12 +00001374 }
Damien Georgeff715422014-04-07 00:39:13 +01001375 replaced_str_index += str_len_remain;
Damien George94f68302014-01-31 23:45:12 +00001376
1377 if (data == NULL) {
1378 // first pass
1379 if (num_replacements_done == 0) {
1380 // no substr found, return original string
1381 return args[0];
1382 } else {
1383 // substr found, allocate new string
1384 replaced_str = mp_obj_str_builder_start(mp_obj_get_type(args[0]), replaced_str_index, &data);
Damien Georgeff715422014-04-07 00:39:13 +01001385 assert(data != NULL);
Damien George94f68302014-01-31 23:45:12 +00001386 }
1387 } else {
1388 // second pass, we are done
1389 break;
1390 }
xbe480c15a2014-01-30 22:17:30 -08001391 }
Damien George94f68302014-01-31 23:45:12 +00001392
xbe480c15a2014-01-30 22:17:30 -08001393 return mp_obj_str_builder_end(replaced_str);
1394}
1395
xbe9e1e8cd2014-03-12 22:57:16 -07001396STATIC mp_obj_t str_count(uint n_args, const mp_obj_t *args) {
1397 assert(2 <= n_args && n_args <= 4);
1398 assert(MP_OBJ_IS_STR(args[0]));
1399 assert(MP_OBJ_IS_STR(args[1]));
1400
1401 GET_STR_DATA_LEN(args[0], haystack, haystack_len);
1402 GET_STR_DATA_LEN(args[1], needle, needle_len);
1403
Damien George536dde22014-03-13 22:07:55 +00001404 machine_uint_t start = 0;
1405 machine_uint_t end = haystack_len;
xbe9e1e8cd2014-03-12 22:57:16 -07001406 if (n_args >= 3 && args[2] != mp_const_none) {
Damien George3e1a5c12014-03-29 13:43:38 +00001407 start = mp_get_index(&mp_type_str, haystack_len, args[2], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001408 }
1409 if (n_args >= 4 && args[3] != mp_const_none) {
Damien George3e1a5c12014-03-29 13:43:38 +00001410 end = mp_get_index(&mp_type_str, haystack_len, args[3], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001411 }
1412
Damien George536dde22014-03-13 22:07:55 +00001413 // if needle_len is zero then we count each gap between characters as an occurrence
1414 if (needle_len == 0) {
1415 return MP_OBJ_NEW_SMALL_INT(end - start + 1);
xbe9e1e8cd2014-03-12 22:57:16 -07001416 }
1417
Damien George536dde22014-03-13 22:07:55 +00001418 // count the occurrences
1419 machine_int_t num_occurrences = 0;
xbec5d70ba2014-03-13 00:29:15 -07001420 for (machine_uint_t haystack_index = start; haystack_index + needle_len <= end; haystack_index++) {
1421 if (memcmp(&haystack[haystack_index], needle, needle_len) == 0) {
1422 num_occurrences++;
1423 haystack_index += needle_len - 1;
1424 }
xbe9e1e8cd2014-03-12 22:57:16 -07001425 }
1426
1427 return MP_OBJ_NEW_SMALL_INT(num_occurrences);
1428}
1429
Damien Georgeb035db32014-03-21 20:39:40 +00001430STATIC 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 +03001431 if (!is_str_or_bytes(self_in)) {
1432 assert(0);
1433 }
1434 mp_obj_type_t *self_type = mp_obj_get_type(self_in);
1435 if (self_type != mp_obj_get_type(arg)) {
1436 arg_type_mixup();
xbe613a8e32014-03-18 00:06:29 -07001437 }
Damien Georgeb035db32014-03-21 20:39:40 +00001438
xbe613a8e32014-03-18 00:06:29 -07001439 GET_STR_DATA_LEN(self_in, str, str_len);
1440 GET_STR_DATA_LEN(arg, sep, sep_len);
1441
1442 if (sep_len == 0) {
Damien Georgeea13f402014-04-05 18:32:08 +01001443 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
xbe613a8e32014-03-18 00:06:29 -07001444 }
Damien Georgeb035db32014-03-21 20:39:40 +00001445
1446 mp_obj_t result[] = {MP_OBJ_NEW_QSTR(MP_QSTR_), MP_OBJ_NEW_QSTR(MP_QSTR_), MP_OBJ_NEW_QSTR(MP_QSTR_)};
1447
1448 if (direction > 0) {
1449 result[0] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001450 } else {
Damien Georgeb035db32014-03-21 20:39:40 +00001451 result[2] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001452 }
xbe613a8e32014-03-18 00:06:29 -07001453
xbe17a5a832014-03-23 23:31:58 -07001454 const byte *position_ptr = find_subbytes(str, str_len, sep, sep_len, direction);
1455 if (position_ptr != NULL) {
1456 machine_uint_t position = position_ptr - str;
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +03001457 result[0] = str_new(self_type, str, position);
xbe17a5a832014-03-23 23:31:58 -07001458 result[1] = arg;
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +03001459 result[2] = str_new(self_type, str + position + sep_len, str_len - position - sep_len);
xbe613a8e32014-03-18 00:06:29 -07001460 }
Damien Georgeb035db32014-03-21 20:39:40 +00001461
xbe0a6894c2014-03-21 01:12:26 -07001462 return mp_obj_new_tuple(3, result);
xbe613a8e32014-03-18 00:06:29 -07001463}
1464
Damien Georgeb035db32014-03-21 20:39:40 +00001465STATIC mp_obj_t str_partition(mp_obj_t self_in, mp_obj_t arg) {
1466 return str_partitioner(self_in, arg, 1);
xbe0a6894c2014-03-21 01:12:26 -07001467}
xbe4504ea82014-03-19 00:46:14 -07001468
Damien Georgeb035db32014-03-21 20:39:40 +00001469STATIC mp_obj_t str_rpartition(mp_obj_t self_in, mp_obj_t arg) {
1470 return str_partitioner(self_in, arg, -1);
xbe4504ea82014-03-19 00:46:14 -07001471}
1472
Paul Sokolovsky69135212014-05-10 19:47:41 +03001473enum { CASE_UPPER, CASE_LOWER };
1474
1475// Supposedly not too critical operations, so optimize for code size
1476STATIC mp_obj_t str_caseconv(int op, mp_obj_t self_in) {
1477 GET_STR_DATA_LEN(self_in, self_data, self_len);
1478 byte *data;
1479 mp_obj_t s = mp_obj_str_builder_start(mp_obj_get_type(self_in), self_len, &data);
1480 for (int i = 0; i < self_len; i++) {
1481 if (op == CASE_UPPER) {
1482 *data++ = unichar_toupper(*self_data++);
1483 } else {
1484 *data++ = unichar_tolower(*self_data++);
1485 }
1486 }
1487 *data = 0;
1488 return mp_obj_str_builder_end(s);
1489}
1490
1491STATIC mp_obj_t str_lower(mp_obj_t self_in) {
1492 return str_caseconv(CASE_LOWER, self_in);
1493}
1494
1495STATIC mp_obj_t str_upper(mp_obj_t self_in) {
1496 return str_caseconv(CASE_UPPER, self_in);
1497}
1498
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001499#if MICROPY_CPYTHON_COMPAT
1500// These methods are superfluous in the presense of str() and bytes()
1501// constructors.
1502// TODO: should accept kwargs too
1503STATIC mp_obj_t bytes_decode(uint n_args, const mp_obj_t *args) {
1504 mp_obj_t new_args[2];
1505 if (n_args == 1) {
1506 new_args[0] = args[0];
1507 new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
1508 args = new_args;
1509 n_args++;
1510 }
1511 return str_make_new(NULL, n_args, 0, args);
1512}
1513
1514// TODO: should accept kwargs too
1515STATIC mp_obj_t str_encode(uint n_args, const mp_obj_t *args) {
1516 mp_obj_t new_args[2];
1517 if (n_args == 1) {
1518 new_args[0] = args[0];
1519 new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
1520 args = new_args;
1521 n_args++;
1522 }
1523 return bytes_make_new(NULL, n_args, 0, args);
1524}
1525#endif
1526
Damien George57a4b4f2014-04-18 22:29:21 +01001527STATIC machine_int_t str_get_buffer(mp_obj_t self_in, mp_buffer_info_t *bufinfo, int flags) {
1528 if (flags == MP_BUFFER_READ) {
Damien George2da98302014-03-09 19:58:18 +00001529 GET_STR_DATA_LEN(self_in, str_data, str_len);
1530 bufinfo->buf = (void*)str_data;
1531 bufinfo->len = str_len;
Damien George57a4b4f2014-04-18 22:29:21 +01001532 bufinfo->typecode = 'b';
Damien George2da98302014-03-09 19:58:18 +00001533 return 0;
1534 } else {
1535 // can't write to a string
1536 bufinfo->buf = NULL;
1537 bufinfo->len = 0;
Damien George57a4b4f2014-04-18 22:29:21 +01001538 bufinfo->typecode = -1;
Damien George2da98302014-03-09 19:58:18 +00001539 return 1;
1540 }
1541}
1542
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001543#if MICROPY_CPYTHON_COMPAT
1544STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(bytes_decode_obj, 1, 3, bytes_decode);
1545STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_encode_obj, 1, 3, str_encode);
1546#endif
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001547STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_find_obj, 2, 4, str_find);
xbe17a5a832014-03-23 23:31:58 -07001548STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rfind_obj, 2, 4, str_rfind);
xbe3d9a39e2014-04-08 11:42:19 -07001549STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_index_obj, 2, 4, str_index);
1550STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rindex_obj, 2, 4, str_rindex);
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001551STATIC MP_DEFINE_CONST_FUN_OBJ_2(str_join_obj, str_join);
1552STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_split_obj, 1, 3, str_split);
Paul Sokolovsky2a273652014-05-13 08:07:08 +03001553STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rsplit_obj, 1, 3, str_rsplit);
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +03001554STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_startswith_obj, 2, 3, str_startswith);
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +03001555STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_endswith_obj, 2, 3, str_endswith);
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001556STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_strip_obj, 1, 2, str_strip);
Paul Sokolovsky88107842014-04-26 06:20:08 +03001557STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_lstrip_obj, 1, 2, str_lstrip);
1558STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rstrip_obj, 1, 2, str_rstrip);
Damien George897fe0c2014-04-15 22:03:55 +01001559STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(str_format_obj, 1, mp_obj_str_format);
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001560STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_replace_obj, 3, 4, str_replace);
xbe9e1e8cd2014-03-12 22:57:16 -07001561STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_count_obj, 2, 4, str_count);
xbe613a8e32014-03-18 00:06:29 -07001562STATIC MP_DEFINE_CONST_FUN_OBJ_2(str_partition_obj, str_partition);
xbe4504ea82014-03-19 00:46:14 -07001563STATIC MP_DEFINE_CONST_FUN_OBJ_2(str_rpartition_obj, str_rpartition);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001564STATIC MP_DEFINE_CONST_FUN_OBJ_1(str_lower_obj, str_lower);
1565STATIC MP_DEFINE_CONST_FUN_OBJ_1(str_upper_obj, str_upper);
Damiend99b0522013-12-21 18:17:45 +00001566
Damien George9b196cd2014-03-26 21:47:19 +00001567STATIC const mp_map_elem_t str_locals_dict_table[] = {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001568#if MICROPY_CPYTHON_COMPAT
1569 { MP_OBJ_NEW_QSTR(MP_QSTR_decode), (mp_obj_t)&bytes_decode_obj },
1570 { MP_OBJ_NEW_QSTR(MP_QSTR_encode), (mp_obj_t)&str_encode_obj },
1571#endif
Damien George9b196cd2014-03-26 21:47:19 +00001572 { MP_OBJ_NEW_QSTR(MP_QSTR_find), (mp_obj_t)&str_find_obj },
1573 { MP_OBJ_NEW_QSTR(MP_QSTR_rfind), (mp_obj_t)&str_rfind_obj },
xbe3d9a39e2014-04-08 11:42:19 -07001574 { MP_OBJ_NEW_QSTR(MP_QSTR_index), (mp_obj_t)&str_index_obj },
1575 { MP_OBJ_NEW_QSTR(MP_QSTR_rindex), (mp_obj_t)&str_rindex_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001576 { MP_OBJ_NEW_QSTR(MP_QSTR_join), (mp_obj_t)&str_join_obj },
1577 { MP_OBJ_NEW_QSTR(MP_QSTR_split), (mp_obj_t)&str_split_obj },
Paul Sokolovsky2a273652014-05-13 08:07:08 +03001578 { MP_OBJ_NEW_QSTR(MP_QSTR_rsplit), (mp_obj_t)&str_rsplit_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001579 { MP_OBJ_NEW_QSTR(MP_QSTR_startswith), (mp_obj_t)&str_startswith_obj },
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +03001580 { MP_OBJ_NEW_QSTR(MP_QSTR_endswith), (mp_obj_t)&str_endswith_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001581 { MP_OBJ_NEW_QSTR(MP_QSTR_strip), (mp_obj_t)&str_strip_obj },
Paul Sokolovsky88107842014-04-26 06:20:08 +03001582 { MP_OBJ_NEW_QSTR(MP_QSTR_lstrip), (mp_obj_t)&str_lstrip_obj },
1583 { MP_OBJ_NEW_QSTR(MP_QSTR_rstrip), (mp_obj_t)&str_rstrip_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001584 { MP_OBJ_NEW_QSTR(MP_QSTR_format), (mp_obj_t)&str_format_obj },
1585 { MP_OBJ_NEW_QSTR(MP_QSTR_replace), (mp_obj_t)&str_replace_obj },
1586 { MP_OBJ_NEW_QSTR(MP_QSTR_count), (mp_obj_t)&str_count_obj },
1587 { MP_OBJ_NEW_QSTR(MP_QSTR_partition), (mp_obj_t)&str_partition_obj },
1588 { MP_OBJ_NEW_QSTR(MP_QSTR_rpartition), (mp_obj_t)&str_rpartition_obj },
Paul Sokolovsky69135212014-05-10 19:47:41 +03001589 { MP_OBJ_NEW_QSTR(MP_QSTR_lower), (mp_obj_t)&str_lower_obj },
1590 { MP_OBJ_NEW_QSTR(MP_QSTR_upper), (mp_obj_t)&str_upper_obj },
ian-v7a16fad2014-01-06 09:52:29 -08001591};
Damien George97209d32014-01-07 15:58:30 +00001592
Damien George9b196cd2014-03-26 21:47:19 +00001593STATIC MP_DEFINE_CONST_DICT(str_locals_dict, str_locals_dict_table);
1594
Damien George3e1a5c12014-03-29 13:43:38 +00001595const mp_obj_type_t mp_type_str = {
Damien Georgec5966122014-02-15 16:10:44 +00001596 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001597 .name = MP_QSTR_str,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001598 .print = str_print,
Paul Sokolovskybe020c22014-03-21 11:39:01 +02001599 .make_new = str_make_new,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001600 .binary_op = str_binary_op,
Damien George729f7b42014-04-17 22:10:53 +01001601 .subscr = str_subscr,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001602 .getiter = mp_obj_new_str_iterator,
Damien George2da98302014-03-09 19:58:18 +00001603 .buffer_p = { .get_buffer = str_get_buffer },
Damien George9b196cd2014-03-26 21:47:19 +00001604 .locals_dict = (mp_obj_t)&str_locals_dict,
Damiend99b0522013-12-21 18:17:45 +00001605};
1606
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001607// Reuses most of methods from str
Damien George3e1a5c12014-03-29 13:43:38 +00001608const mp_obj_type_t mp_type_bytes = {
Damien Georgec5966122014-02-15 16:10:44 +00001609 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001610 .name = MP_QSTR_bytes,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001611 .print = str_print,
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001612 .make_new = bytes_make_new,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001613 .binary_op = str_binary_op,
Damien George729f7b42014-04-17 22:10:53 +01001614 .subscr = str_subscr,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001615 .getiter = mp_obj_new_bytes_iterator,
Paul Sokolovsky7a70a3a2014-04-08 17:30:47 +03001616 .buffer_p = { .get_buffer = str_get_buffer },
Damien George9b196cd2014-03-26 21:47:19 +00001617 .locals_dict = (mp_obj_t)&str_locals_dict,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001618};
1619
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001620// the zero-length bytes
Damien George3e1a5c12014-03-29 13:43:38 +00001621STATIC const mp_obj_str_t empty_bytes_obj = {{&mp_type_bytes}, 0, 0, NULL};
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001622const mp_obj_t mp_const_empty_bytes = (mp_obj_t)&empty_bytes_obj;
1623
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001624mp_obj_t mp_obj_str_builder_start(const mp_obj_type_t *type, uint len, byte **data) {
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001625 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001626 o->base.type = type;
Damien George5fa93b62014-01-22 14:35:10 +00001627 o->len = len;
Paul Sokolovsky504e2332014-04-19 03:09:17 +03001628 o->hash = 0;
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001629 byte *p = m_new(byte, len + 1);
1630 o->data = p;
1631 *data = p;
Damiend99b0522013-12-21 18:17:45 +00001632 return o;
1633}
1634
Damien George5fa93b62014-01-22 14:35:10 +00001635mp_obj_t mp_obj_str_builder_end(mp_obj_t o_in) {
Damien George5fa93b62014-01-22 14:35:10 +00001636 mp_obj_str_t *o = o_in;
1637 o->hash = qstr_compute_hash(o->data, o->len);
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001638 byte *p = (byte*)o->data;
1639 p[o->len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
Damien George5fa93b62014-01-22 14:35:10 +00001640 return o;
1641}
1642
Paul Sokolovskya47b64a2014-05-15 07:28:19 +03001643mp_obj_t str_new(const mp_obj_type_t *type, const byte* data, uint len) {
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001644 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001645 o->base.type = type;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001646 o->len = len;
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001647 if (data) {
1648 o->hash = qstr_compute_hash(data, len);
1649 byte *p = m_new(byte, len + 1);
1650 o->data = p;
1651 memcpy(p, data, len * sizeof(byte));
1652 p[len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
1653 }
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001654 return o;
1655}
1656
Damien George5fa93b62014-01-22 14:35:10 +00001657mp_obj_t mp_obj_new_str(const byte* data, uint len, bool make_qstr_if_not_already) {
1658 qstr q = qstr_find_strn(data, len);
1659 if (q != MP_QSTR_NULL) {
1660 // qstr with this data already exists
1661 return MP_OBJ_NEW_QSTR(q);
1662 } else if (make_qstr_if_not_already) {
1663 // no existing qstr, make a new one
1664 return MP_OBJ_NEW_QSTR(qstr_from_strn((const char*)data, len));
1665 } else {
1666 // no existing qstr, don't make one
Damien George3e1a5c12014-03-29 13:43:38 +00001667 return str_new(&mp_type_str, data, len);
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02001668 }
Damien George5fa93b62014-01-22 14:35:10 +00001669}
1670
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001671mp_obj_t mp_obj_new_bytes(const byte* data, uint len) {
Damien George3e1a5c12014-03-29 13:43:38 +00001672 return str_new(&mp_type_bytes, data, len);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001673}
1674
Damien George5fa93b62014-01-22 14:35:10 +00001675bool mp_obj_str_equal(mp_obj_t s1, mp_obj_t s2) {
1676 if (MP_OBJ_IS_QSTR(s1) && MP_OBJ_IS_QSTR(s2)) {
1677 return s1 == s2;
1678 } else {
1679 GET_STR_HASH(s1, h1);
1680 GET_STR_HASH(s2, h2);
Paul Sokolovsky59e269c2014-04-14 01:43:01 +03001681 // If any of hashes is 0, it means it's not valid
1682 if (h1 != 0 && h2 != 0 && h1 != h2) {
Damien George5fa93b62014-01-22 14:35:10 +00001683 return false;
1684 }
1685 GET_STR_DATA_LEN(s1, d1, l1);
1686 GET_STR_DATA_LEN(s2, d2, l2);
1687 if (l1 != l2) {
1688 return false;
1689 }
Damien George1e708fe2014-01-23 18:27:51 +00001690 return memcmp(d1, d2, l1) == 0;
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02001691 }
Damien George5fa93b62014-01-22 14:35:10 +00001692}
1693
Damien Georgedeed0872014-04-06 11:11:15 +01001694STATIC void bad_implicit_conversion(mp_obj_t self_in) {
Damien Georgeea13f402014-04-05 18:32:08 +01001695 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 +00001696}
1697
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +03001698STATIC void arg_type_mixup() {
1699 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "Can't mix str and bytes arguments"));
1700}
1701
Damien George5fa93b62014-01-22 14:35:10 +00001702uint mp_obj_str_get_hash(mp_obj_t self_in) {
Paul Sokolovskyf130ca12014-04-13 05:41:00 +03001703 // TODO: This has too big overhead for hash accessor
1704 if (MP_OBJ_IS_STR(self_in) || MP_OBJ_IS_TYPE(self_in, &mp_type_bytes)) {
Damien George5fa93b62014-01-22 14:35:10 +00001705 GET_STR_HASH(self_in, h);
1706 return h;
1707 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001708 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001709 }
1710}
1711
1712uint mp_obj_str_get_len(mp_obj_t self_in) {
Damien Georgeee014112014-04-15 23:10:00 +01001713 // TODO This has a double check for the type, one in obj.c and one here
1714 if (MP_OBJ_IS_STR(self_in) || MP_OBJ_IS_TYPE(self_in, &mp_type_bytes)) {
Damien George5fa93b62014-01-22 14:35:10 +00001715 GET_STR_LEN(self_in, l);
1716 return l;
1717 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001718 bad_implicit_conversion(self_in);
1719 }
1720}
1721
1722// use this if you will anyway convert the string to a qstr
1723// will be more efficient for the case where it's already a qstr
1724qstr mp_obj_str_get_qstr(mp_obj_t self_in) {
1725 if (MP_OBJ_IS_QSTR(self_in)) {
1726 return MP_OBJ_QSTR_VALUE(self_in);
Damien George3e1a5c12014-03-29 13:43:38 +00001727 } else if (MP_OBJ_IS_TYPE(self_in, &mp_type_str)) {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001728 mp_obj_str_t *self = self_in;
1729 return qstr_from_strn((char*)self->data, self->len);
1730 } else {
1731 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001732 }
1733}
1734
1735// only use this function if you need the str data to be zero terminated
1736// at the moment all strings are zero terminated to help with C ASCIIZ compatibility
1737const char *mp_obj_str_get_str(mp_obj_t self_in) {
1738 if (MP_OBJ_IS_STR(self_in)) {
1739 GET_STR_DATA_LEN(self_in, s, l);
1740 (void)l; // len unused
1741 return (const char*)s;
1742 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001743 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001744 }
1745}
1746
Damien George698ec212014-02-08 18:17:23 +00001747const char *mp_obj_str_get_data(mp_obj_t self_in, uint *len) {
Paul Sokolovskyeea01182014-05-11 13:51:24 +03001748 if (is_str_or_bytes(self_in)) {
Damien George5fa93b62014-01-22 14:35:10 +00001749 GET_STR_DATA_LEN(self_in, s, l);
1750 *len = l;
Damien George698ec212014-02-08 18:17:23 +00001751 return (const char*)s;
Damien George5fa93b62014-01-22 14:35:10 +00001752 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001753 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001754 }
Damiend99b0522013-12-21 18:17:45 +00001755}
xyb8cfc9f02014-01-05 18:47:51 +08001756
1757/******************************************************************************/
1758/* str iterator */
1759
1760typedef struct _mp_obj_str_it_t {
1761 mp_obj_base_t base;
Damien George5fa93b62014-01-22 14:35:10 +00001762 mp_obj_t str;
xyb8cfc9f02014-01-05 18:47:51 +08001763 machine_uint_t cur;
1764} mp_obj_str_it_t;
1765
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001766STATIC mp_obj_t str_it_iternext(mp_obj_t self_in) {
xyb8cfc9f02014-01-05 18:47:51 +08001767 mp_obj_str_it_t *self = self_in;
Damien George5fa93b62014-01-22 14:35:10 +00001768 GET_STR_DATA_LEN(self->str, str, len);
1769 if (self->cur < len) {
1770 mp_obj_t o_out = mp_obj_new_str(str + self->cur, 1, true);
xyb8cfc9f02014-01-05 18:47:51 +08001771 self->cur += 1;
1772 return o_out;
1773 } else {
Damien Georgeea8d06c2014-04-17 23:19:36 +01001774 return MP_OBJ_STOP_ITERATION;
xyb8cfc9f02014-01-05 18:47:51 +08001775 }
1776}
1777
Damien George3e1a5c12014-03-29 13:43:38 +00001778STATIC const mp_obj_type_t mp_type_str_it = {
Damien Georgec5966122014-02-15 16:10:44 +00001779 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001780 .name = MP_QSTR_iterator,
Paul Sokolovskyf7eaf602014-03-30 22:00:12 +03001781 .getiter = mp_identity,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001782 .iternext = str_it_iternext,
xyb8cfc9f02014-01-05 18:47:51 +08001783};
1784
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001785STATIC mp_obj_t bytes_it_iternext(mp_obj_t self_in) {
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001786 mp_obj_str_it_t *self = self_in;
1787 GET_STR_DATA_LEN(self->str, str, len);
1788 if (self->cur < len) {
Damien George7c9c6672014-01-25 00:17:36 +00001789 mp_obj_t o_out = MP_OBJ_NEW_SMALL_INT((mp_small_int_t)str[self->cur]);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001790 self->cur += 1;
1791 return o_out;
1792 } else {
Damien Georgeea8d06c2014-04-17 23:19:36 +01001793 return MP_OBJ_STOP_ITERATION;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001794 }
1795}
1796
Damien George3e1a5c12014-03-29 13:43:38 +00001797STATIC const mp_obj_type_t mp_type_bytes_it = {
Damien Georgec5966122014-02-15 16:10:44 +00001798 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001799 .name = MP_QSTR_iterator,
Paul Sokolovskyf7eaf602014-03-30 22:00:12 +03001800 .getiter = mp_identity,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001801 .iternext = bytes_it_iternext,
1802};
1803
1804mp_obj_t mp_obj_new_str_iterator(mp_obj_t str) {
xyb8cfc9f02014-01-05 18:47:51 +08001805 mp_obj_str_it_t *o = m_new_obj(mp_obj_str_it_t);
Damien George3e1a5c12014-03-29 13:43:38 +00001806 o->base.type = &mp_type_str_it;
xyb8cfc9f02014-01-05 18:47:51 +08001807 o->str = str;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001808 o->cur = 0;
1809 return o;
1810}
1811
1812mp_obj_t mp_obj_new_bytes_iterator(mp_obj_t str) {
1813 mp_obj_str_it_t *o = m_new_obj(mp_obj_str_it_t);
Damien George3e1a5c12014-03-29 13:43:38 +00001814 o->base.type = &mp_type_bytes_it;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001815 o->str = str;
1816 o->cur = 0;
xyb8cfc9f02014-01-05 18:47:51 +08001817 return o;
1818}