blob: 704fa07e1de54ca956f8912e7a2ff75bf397eb3e [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
Damiend99b0522013-12-21 18:17:45 +000028#include <string.h>
29#include <assert.h>
30
Damien George51dfcb42015-01-01 20:27:54 +000031#include "py/nlr.h"
32#include "py/unicode.h"
33#include "py/objstr.h"
34#include "py/objlist.h"
35#include "py/runtime0.h"
36#include "py/runtime.h"
Damiend99b0522013-12-21 18:17:45 +000037
Damien Georgeecc88e92014-08-30 00:35:11 +010038STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, mp_uint_t n_args, const mp_obj_t *args, mp_obj_t dict);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +020039
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +020040STATIC mp_obj_t mp_obj_new_bytes_iterator(mp_obj_t str);
Paul Sokolovskye9085912014-04-30 05:35:18 +030041STATIC NORETURN void bad_implicit_conversion(mp_obj_t self_in);
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +030042
xyb8cfc9f02014-01-05 18:47:51 +080043/******************************************************************************/
44/* str */
45
Damien George7f9d1d62015-04-09 23:56:15 +010046void mp_str_print_quoted(const mp_print_t *print, const byte *str_data, mp_uint_t str_len, bool is_bytes) {
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020047 // this escapes characters, but it will be very slow to print (calling print many times)
48 bool has_single_quote = false;
49 bool has_double_quote = false;
Chris Angelico48674132014-06-04 03:26:40 +100050 for (const byte *s = str_data, *top = str_data + str_len; !has_double_quote && s < top; s++) {
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020051 if (*s == '\'') {
52 has_single_quote = true;
53 } else if (*s == '"') {
54 has_double_quote = true;
55 }
56 }
57 int quote_char = '\'';
58 if (has_single_quote && !has_double_quote) {
59 quote_char = '"';
60 }
Damien George7f9d1d62015-04-09 23:56:15 +010061 mp_printf(print, "%c", quote_char);
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020062 for (const byte *s = str_data, *top = str_data + str_len; s < top; s++) {
63 if (*s == quote_char) {
Damien George7f9d1d62015-04-09 23:56:15 +010064 mp_printf(print, "\\%c", quote_char);
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020065 } else if (*s == '\\') {
Damien George7f9d1d62015-04-09 23:56:15 +010066 mp_print_str(print, "\\\\");
Paul Sokolovsky2ec38a12014-06-13 21:23:00 +030067 } else if (*s >= 0x20 && *s != 0x7f && (!is_bytes || *s < 0x80)) {
68 // In strings, anything which is not ascii control character
69 // is printed as is, this includes characters in range 0x80-0xff
70 // (which can be non-Latin letters, etc.)
Damien George7f9d1d62015-04-09 23:56:15 +010071 mp_printf(print, "%c", *s);
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020072 } else if (*s == '\n') {
Damien George7f9d1d62015-04-09 23:56:15 +010073 mp_print_str(print, "\\n");
Andrew Scheller12968fb2014-04-08 02:42:50 +010074 } else if (*s == '\r') {
Damien George7f9d1d62015-04-09 23:56:15 +010075 mp_print_str(print, "\\r");
Andrew Scheller12968fb2014-04-08 02:42:50 +010076 } else if (*s == '\t') {
Damien George7f9d1d62015-04-09 23:56:15 +010077 mp_print_str(print, "\\t");
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020078 } else {
Damien George7f9d1d62015-04-09 23:56:15 +010079 mp_printf(print, "\\x%02x", *s);
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020080 }
81 }
Damien George7f9d1d62015-04-09 23:56:15 +010082 mp_printf(print, "%c", quote_char);
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020083}
84
Damien George612045f2014-09-17 22:56:34 +010085#if MICROPY_PY_UJSON
Damien George7f9d1d62015-04-09 23:56:15 +010086void mp_str_print_json(const mp_print_t *print, const byte *str_data, mp_uint_t str_len) {
Damien Georgecde0ca22014-09-25 17:35:56 +010087 // for JSON spec, see http://www.ietf.org/rfc/rfc4627.txt
88 // if we are given a valid utf8-encoded string, we will print it in a JSON-conforming way
Damien George7f9d1d62015-04-09 23:56:15 +010089 mp_print_str(print, "\"");
Damien George612045f2014-09-17 22:56:34 +010090 for (const byte *s = str_data, *top = str_data + str_len; s < top; s++) {
Damien Georgecde0ca22014-09-25 17:35:56 +010091 if (*s == '"' || *s == '\\') {
Damien George7f9d1d62015-04-09 23:56:15 +010092 mp_printf(print, "\\%c", *s);
Damien Georgecde0ca22014-09-25 17:35:56 +010093 } else if (*s >= 32) {
94 // this will handle normal and utf-8 encoded chars
Damien George7f9d1d62015-04-09 23:56:15 +010095 mp_printf(print, "%c", *s);
Damien George612045f2014-09-17 22:56:34 +010096 } else if (*s == '\n') {
Damien George7f9d1d62015-04-09 23:56:15 +010097 mp_print_str(print, "\\n");
Damien George612045f2014-09-17 22:56:34 +010098 } else if (*s == '\r') {
Damien George7f9d1d62015-04-09 23:56:15 +010099 mp_print_str(print, "\\r");
Damien George612045f2014-09-17 22:56:34 +0100100 } else if (*s == '\t') {
Damien George7f9d1d62015-04-09 23:56:15 +0100101 mp_print_str(print, "\\t");
Damien George612045f2014-09-17 22:56:34 +0100102 } else {
Damien Georgecde0ca22014-09-25 17:35:56 +0100103 // this will handle control chars
Damien George7f9d1d62015-04-09 23:56:15 +0100104 mp_printf(print, "\\u%04x", *s);
Damien George612045f2014-09-17 22:56:34 +0100105 }
106 }
Damien George7f9d1d62015-04-09 23:56:15 +0100107 mp_print_str(print, "\"");
Damien George612045f2014-09-17 22:56:34 +0100108}
109#endif
110
Damien George7f9d1d62015-04-09 23:56:15 +0100111STATIC void str_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
Damien George5fa93b62014-01-22 14:35:10 +0000112 GET_STR_DATA_LEN(self_in, str_data, str_len);
Damien George612045f2014-09-17 22:56:34 +0100113 #if MICROPY_PY_UJSON
114 if (kind == PRINT_JSON) {
Damien George7f9d1d62015-04-09 23:56:15 +0100115 mp_str_print_json(print, str_data, str_len);
Damien George612045f2014-09-17 22:56:34 +0100116 return;
117 }
118 #endif
Damien Georgee2aa1172015-09-03 23:03:57 +0100119 #if !MICROPY_PY_BUILTINS_STR_UNICODE
Damien Georgecde0ca22014-09-25 17:35:56 +0100120 bool is_bytes = MP_OBJ_IS_TYPE(self_in, &mp_type_bytes);
Damien Georgee2aa1172015-09-03 23:03:57 +0100121 #else
122 bool is_bytes = true;
123 #endif
124 if (!MICROPY_PY_BUILTINS_STR_UNICODE && kind == PRINT_STR && !is_bytes) {
Damien George7f9d1d62015-04-09 23:56:15 +0100125 mp_printf(print, "%.*s", str_len, str_data);
Paul Sokolovsky76d982e2014-01-13 19:19:16 +0200126 } else {
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +0200127 if (is_bytes) {
Damien George7f9d1d62015-04-09 23:56:15 +0100128 mp_print_str(print, "b");
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +0200129 }
Damien George7f9d1d62015-04-09 23:56:15 +0100130 mp_str_print_quoted(print, str_data, str_len, is_bytes);
Paul Sokolovsky76d982e2014-01-13 19:19:16 +0200131 }
Damiend99b0522013-12-21 18:17:45 +0000132}
133
Paul Sokolovsky344e15b2015-01-23 02:15:56 +0200134mp_obj_t mp_obj_str_make_new(mp_obj_t type_in, mp_uint_t n_args, mp_uint_t n_kw, const mp_obj_t *args) {
Paul Sokolovskyb473d0a2014-05-06 19:30:30 +0300135#if MICROPY_CPYTHON_COMPAT
136 if (n_kw != 0) {
137 mp_arg_error_unimpl_kw();
138 }
139#endif
140
Damien George1e9a92f2014-11-06 17:36:16 +0000141 mp_arg_check_num(n_args, n_kw, 0, 3, false);
142
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200143 switch (n_args) {
144 case 0:
145 return MP_OBJ_NEW_QSTR(MP_QSTR_);
146
Damien George1e9a92f2014-11-06 17:36:16 +0000147 case 1: {
Damien George0b9ee862015-01-21 19:14:25 +0000148 vstr_t vstr;
Damien George7f9d1d62015-04-09 23:56:15 +0100149 mp_print_t print;
150 vstr_init_print(&vstr, 16, &print);
151 mp_obj_print_helper(&print, args[0], PRINT_STR);
Damien George0b9ee862015-01-21 19:14:25 +0000152 return mp_obj_new_str_from_vstr(type_in, &vstr);
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200153 }
154
Damien George1e9a92f2014-11-06 17:36:16 +0000155 default: // 2 or 3 args
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200156 // TODO: validate 2nd/3rd args
Paul Sokolovskye62a0fe2014-10-30 23:58:08 +0200157 if (MP_OBJ_IS_TYPE(args[0], &mp_type_bytes)) {
158 GET_STR_DATA_LEN(args[0], str_data, str_len);
159 GET_STR_HASH(args[0], str_hash);
Damien George0b9ee862015-01-21 19:14:25 +0000160 mp_obj_str_t *o = mp_obj_new_str_of_type(type_in, NULL, str_len);
Paul Sokolovskye62a0fe2014-10-30 23:58:08 +0200161 o->data = str_data;
162 o->hash = str_hash;
163 return o;
164 } else {
165 mp_buffer_info_t bufinfo;
166 mp_get_buffer_raise(args[0], &bufinfo, MP_BUFFER_READ);
167 return mp_obj_new_str(bufinfo.buf, bufinfo.len, false);
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200168 }
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200169 }
170}
171
Damien Georgeecc88e92014-08-30 00:35:11 +0100172STATIC mp_obj_t bytes_make_new(mp_obj_t type_in, mp_uint_t n_args, mp_uint_t n_kw, const mp_obj_t *args) {
Damien Georgeff8dd3f2015-01-20 12:47:20 +0000173 (void)type_in;
174
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200175 if (n_args == 0) {
176 return mp_const_empty_bytes;
177 }
178
Paul Sokolovskyb473d0a2014-05-06 19:30:30 +0300179#if MICROPY_CPYTHON_COMPAT
180 if (n_kw != 0) {
181 mp_arg_error_unimpl_kw();
182 }
183#endif
184
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200185 if (MP_OBJ_IS_STR(args[0])) {
186 if (n_args < 2 || n_args > 3) {
187 goto wrong_args;
188 }
189 GET_STR_DATA_LEN(args[0], str_data, str_len);
190 GET_STR_HASH(args[0], str_hash);
Damien Georgef600a6a2014-05-25 22:34:34 +0100191 mp_obj_str_t *o = mp_obj_new_str_of_type(&mp_type_bytes, NULL, str_len);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200192 o->data = str_data;
193 o->hash = str_hash;
194 return o;
195 }
196
197 if (n_args > 1) {
198 goto wrong_args;
199 }
200
201 if (MP_OBJ_IS_SMALL_INT(args[0])) {
202 uint len = MP_OBJ_SMALL_INT_VALUE(args[0]);
Damien George05005f62015-01-21 22:48:37 +0000203 vstr_t vstr;
204 vstr_init_len(&vstr, len);
205 memset(vstr.buf, 0, len);
206 return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200207 }
208
Damien George32ef3a32014-12-04 15:46:14 +0000209 // check if argument has the buffer protocol
210 mp_buffer_info_t bufinfo;
211 if (mp_get_buffer(args[0], &bufinfo, MP_BUFFER_READ)) {
212 return mp_obj_new_str_of_type(&mp_type_bytes, bufinfo.buf, bufinfo.len);
213 }
214
Damien George0b9ee862015-01-21 19:14:25 +0000215 vstr_t vstr;
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200216 // Try to create array of exact len if initializer len is known
217 mp_obj_t len_in = mp_obj_len_maybe(args[0]);
218 if (len_in == MP_OBJ_NULL) {
Damien George0b9ee862015-01-21 19:14:25 +0000219 vstr_init(&vstr, 16);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200220 } else {
Damien George0b9ee862015-01-21 19:14:25 +0000221 mp_int_t len = MP_OBJ_SMALL_INT_VALUE(len_in);
Damien George0d3cb672015-01-28 23:43:01 +0000222 vstr_init(&vstr, len);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200223 }
224
Damien Georged17926d2014-03-30 13:35:08 +0100225 mp_obj_t iterable = mp_getiter(args[0]);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200226 mp_obj_t item;
Damien Georgeea8d06c2014-04-17 23:19:36 +0100227 while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
Damien Georgeede0f3a2015-04-23 15:28:18 +0100228 mp_int_t val = mp_obj_get_int(item);
229 #if MICROPY_CPYTHON_COMPAT
230 if (val < 0 || val > 255) {
231 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "bytes value out of range"));
232 }
233 #endif
234 vstr_add_byte(&vstr, val);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200235 }
236
Damien George0b9ee862015-01-21 19:14:25 +0000237 return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200238
239wrong_args:
Damien George1e9a92f2014-11-06 17:36:16 +0000240 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "wrong number of arguments"));
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200241}
242
Damien George55baff42014-01-21 21:40:13 +0000243// like strstr but with specified length and allows \0 bytes
244// TODO replace with something more efficient/standard
Damien George40f3c022014-07-03 13:25:24 +0100245STATIC const byte *find_subbytes(const byte *haystack, mp_uint_t hlen, const byte *needle, mp_uint_t nlen, mp_int_t direction) {
Damien George55baff42014-01-21 21:40:13 +0000246 if (hlen >= nlen) {
Damien George40f3c022014-07-03 13:25:24 +0100247 mp_uint_t str_index, str_index_end;
xbe17a5a832014-03-23 23:31:58 -0700248 if (direction > 0) {
249 str_index = 0;
250 str_index_end = hlen - nlen;
251 } else {
252 str_index = hlen - nlen;
253 str_index_end = 0;
254 }
255 for (;;) {
256 if (memcmp(&haystack[str_index], needle, nlen) == 0) {
257 //found
258 return haystack + str_index;
Damien George55baff42014-01-21 21:40:13 +0000259 }
xbe17a5a832014-03-23 23:31:58 -0700260 if (str_index == str_index_end) {
261 //not found
262 break;
Damien George55baff42014-01-21 21:40:13 +0000263 }
xbe17a5a832014-03-23 23:31:58 -0700264 str_index += direction;
Damien George55baff42014-01-21 21:40:13 +0000265 }
266 }
267 return NULL;
268}
269
Damien Georgea75b02e2014-08-27 09:20:30 +0100270// Note: this function is used to check if an object is a str or bytes, which
271// works because both those types use it as their binary_op method. Revisit
272// MP_OBJ_IS_STR_OR_BYTES if this fact changes.
Damien Georgeecc88e92014-08-30 00:35:11 +0100273mp_obj_t mp_obj_str_binary_op(mp_uint_t op, mp_obj_t lhs_in, mp_obj_t rhs_in) {
Damien Georgea65c03c2014-11-05 16:30:34 +0000274 // check for modulo
275 if (op == MP_BINARY_OP_MODULO) {
276 mp_obj_t *args;
277 mp_uint_t n_args;
278 mp_obj_t dict = MP_OBJ_NULL;
279 if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_tuple)) {
280 // TODO: Support tuple subclasses?
281 mp_obj_tuple_get(rhs_in, &n_args, &args);
282 } else if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_dict)) {
283 args = NULL;
284 n_args = 0;
285 dict = rhs_in;
286 } else {
287 args = &rhs_in;
288 n_args = 1;
289 }
290 return str_modulo_format(lhs_in, n_args, args, dict);
291 }
292
293 // from now on we need lhs type and data, so extract them
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300294 mp_obj_type_t *lhs_type = mp_obj_get_type(lhs_in);
Damien Georgea65c03c2014-11-05 16:30:34 +0000295 GET_STR_DATA_LEN(lhs_in, lhs_data, lhs_len);
296
297 // check for multiply
298 if (op == MP_BINARY_OP_MULTIPLY) {
299 mp_int_t n;
300 if (!mp_obj_get_int_maybe(rhs_in, &n)) {
301 return MP_OBJ_NULL; // op not supported
302 }
303 if (n <= 0) {
304 if (lhs_type == &mp_type_str) {
305 return MP_OBJ_NEW_QSTR(MP_QSTR_); // empty str
306 } else {
307 return mp_const_empty_bytes;
308 }
309 }
Damien George05005f62015-01-21 22:48:37 +0000310 vstr_t vstr;
311 vstr_init_len(&vstr, lhs_len * n);
312 mp_seq_multiply(lhs_data, sizeof(*lhs_data), lhs_len, n, vstr.buf);
313 return mp_obj_new_str_from_vstr(lhs_type, &vstr);
Damien Georgea65c03c2014-11-05 16:30:34 +0000314 }
315
316 // From now on all operations allow:
317 // - str with str
318 // - bytes with bytes
319 // - bytes with bytearray
320 // - bytes with array.array
321 // To do this efficiently we use the buffer protocol to extract the raw
322 // data for the rhs, but only if the lhs is a bytes object.
323 //
324 // NOTE: CPython does not allow comparison between bytes ard array.array
325 // (even if the array is of type 'b'), even though it allows addition of
326 // such types. We are not compatible with this (we do allow comparison
327 // of bytes with anything that has the buffer protocol). It would be
328 // easy to "fix" this with a bit of extra logic below, but it costs code
329 // size and execution time so we don't.
330
331 const byte *rhs_data;
332 mp_uint_t rhs_len;
333 if (lhs_type == mp_obj_get_type(rhs_in)) {
334 GET_STR_DATA_LEN(rhs_in, rhs_data_, rhs_len_);
335 rhs_data = rhs_data_;
336 rhs_len = rhs_len_;
337 } else if (lhs_type == &mp_type_bytes) {
338 mp_buffer_info_t bufinfo;
339 if (!mp_get_buffer(rhs_in, &bufinfo, MP_BUFFER_READ)) {
Damien Georgee233a552015-01-11 21:07:15 +0000340 return MP_OBJ_NULL; // op not supported
Damien Georgea65c03c2014-11-05 16:30:34 +0000341 }
342 rhs_data = bufinfo.buf;
343 rhs_len = bufinfo.len;
344 } else {
345 // incompatible types
Damien Georgea65c03c2014-11-05 16:30:34 +0000346 return MP_OBJ_NULL; // op not supported
347 }
348
Damiend99b0522013-12-21 18:17:45 +0000349 switch (op) {
Damien Georged17926d2014-03-30 13:35:08 +0100350 case MP_BINARY_OP_ADD:
Damien Georgea65c03c2014-11-05 16:30:34 +0000351 case MP_BINARY_OP_INPLACE_ADD: {
Damien George05005f62015-01-21 22:48:37 +0000352 vstr_t vstr;
353 vstr_init_len(&vstr, lhs_len + rhs_len);
354 memcpy(vstr.buf, lhs_data, lhs_len);
355 memcpy(vstr.buf + lhs_len, rhs_data, rhs_len);
356 return mp_obj_new_str_from_vstr(lhs_type, &vstr);
Paul Sokolovsky545591a2014-01-21 00:27:33 +0200357 }
Paul Sokolovsky87e85b72014-02-02 08:24:07 +0200358
Damien Georgea65c03c2014-11-05 16:30:34 +0000359 case MP_BINARY_OP_IN:
360 /* NOTE `a in b` is `b.__contains__(a)` */
361 return MP_BOOL(find_subbytes(lhs_data, lhs_len, rhs_data, rhs_len, 1) != NULL);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +0300362
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300363 //case MP_BINARY_OP_NOT_EQUAL: // This is never passed here
364 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 +0100365 case MP_BINARY_OP_LESS:
366 case MP_BINARY_OP_LESS_EQUAL:
367 case MP_BINARY_OP_MORE:
368 case MP_BINARY_OP_MORE_EQUAL:
Damien Georgea65c03c2014-11-05 16:30:34 +0000369 return MP_BOOL(mp_seq_cmp_bytes(op, lhs_data, lhs_len, rhs_data, rhs_len));
Damiend99b0522013-12-21 18:17:45 +0000370 }
371
Damien George6ac5dce2014-05-21 19:42:43 +0100372 return MP_OBJ_NULL; // op not supported
Damiend99b0522013-12-21 18:17:45 +0000373}
374
Paul Sokolovskyea2c9362014-06-15 00:35:09 +0300375#if !MICROPY_PY_BUILTINS_STR_UNICODE
376// objstrunicode defines own version
Damien George4abff752014-08-30 14:59:21 +0100377const byte *str_index_to_ptr(const mp_obj_type_t *type, const byte *self_data, mp_uint_t self_len,
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300378 mp_obj_t index, bool is_slice) {
Damien George40f3c022014-07-03 13:25:24 +0100379 mp_uint_t index_val = mp_get_index(type, self_len, index, is_slice);
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300380 return self_data + index_val;
381}
Paul Sokolovskyea2c9362014-06-15 00:35:09 +0300382#endif
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300383
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300384// This is used for both bytes and 8-bit strings. This is not used for unicode strings.
385STATIC mp_obj_t bytes_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) {
Paul Sokolovsky5ebd5f02014-05-11 21:22:59 +0300386 mp_obj_type_t *type = mp_obj_get_type(self_in);
Damien George729f7b42014-04-17 22:10:53 +0100387 GET_STR_DATA_LEN(self_in, self_data, self_len);
388 if (value == MP_OBJ_SENTINEL) {
389 // load
Damien Georgefb510b32014-06-01 13:32:54 +0100390#if MICROPY_PY_BUILTINS_SLICE
Damien George729f7b42014-04-17 22:10:53 +0100391 if (MP_OBJ_IS_TYPE(index, &mp_type_slice)) {
Paul Sokolovskyde4b9322014-05-25 21:21:57 +0300392 mp_bound_slice_t slice;
393 if (!mp_seq_get_fast_slice_indexes(self_len, index, &slice)) {
Damien George821b7f22015-09-03 23:14:06 +0100394 mp_not_implemented("only slices with step=1 (aka None) are supported");
Damien George729f7b42014-04-17 22:10:53 +0100395 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100396 return mp_obj_new_str_of_type(type, self_data + slice.start, slice.stop - slice.start);
Damien George729f7b42014-04-17 22:10:53 +0100397 }
398#endif
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300399 mp_uint_t index_val = mp_get_index(type, self_len, index, false);
Damien George2eb1f602014-08-11 23:24:29 +0100400 // If we have unicode enabled the type will always be bytes, so take the short cut.
401 if (MICROPY_PY_BUILTINS_STR_UNICODE || type == &mp_type_bytes) {
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300402 return MP_OBJ_NEW_SMALL_INT(self_data[index_val]);
Damien George729f7b42014-04-17 22:10:53 +0100403 } else {
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300404 return mp_obj_new_str((char*)&self_data[index_val], 1, true);
Damien George729f7b42014-04-17 22:10:53 +0100405 }
406 } else {
Damien George6ac5dce2014-05-21 19:42:43 +0100407 return MP_OBJ_NULL; // op not supported
Damien George729f7b42014-04-17 22:10:53 +0100408 }
409}
410
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200411STATIC mp_obj_t str_join(mp_obj_t self_in, mp_obj_t arg) {
Dave Hylandsb7f7c652014-08-26 12:44:46 -0700412 assert(MP_OBJ_IS_STR_OR_BYTES(self_in));
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300413 const mp_obj_type_t *self_type = mp_obj_get_type(self_in);
Damiend99b0522013-12-21 18:17:45 +0000414
Damien Georgefe8fb912014-01-02 16:36:09 +0000415 // get separation string
Damien George5fa93b62014-01-22 14:35:10 +0000416 GET_STR_DATA_LEN(self_in, sep_str, sep_len);
Damien Georgefe8fb912014-01-02 16:36:09 +0000417
418 // process args
Damien George9c4cbe22014-08-30 14:04:14 +0100419 mp_uint_t seq_len;
Damiend99b0522013-12-21 18:17:45 +0000420 mp_obj_t *seq_items;
Damien George07ddab52014-03-29 13:15:08 +0000421 if (MP_OBJ_IS_TYPE(arg, &mp_type_tuple)) {
Damiend99b0522013-12-21 18:17:45 +0000422 mp_obj_tuple_get(arg, &seq_len, &seq_items);
Damiend99b0522013-12-21 18:17:45 +0000423 } else {
Damien Georgea157e4c2014-04-09 19:17:53 +0100424 if (!MP_OBJ_IS_TYPE(arg, &mp_type_list)) {
425 // arg is not a list, try to convert it to one
Paul Sokolovsky881d9af2014-04-10 01:42:40 +0300426 // TODO: Try to optimize?
Damien Georgea157e4c2014-04-09 19:17:53 +0100427 arg = mp_type_list.make_new((mp_obj_t)&mp_type_list, 1, 0, &arg);
428 }
429 mp_obj_list_get(arg, &seq_len, &seq_items);
Damiend99b0522013-12-21 18:17:45 +0000430 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000431
432 // count required length
Damien George39dc1452014-10-03 19:52:22 +0100433 mp_uint_t required_len = 0;
434 for (mp_uint_t i = 0; i < seq_len; i++) {
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300435 if (mp_obj_get_type(seq_items[i]) != self_type) {
436 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
437 "join expects a list of str/bytes objects consistent with self object"));
Damiend99b0522013-12-21 18:17:45 +0000438 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000439 if (i > 0) {
440 required_len += sep_len;
441 }
Damien George5fa93b62014-01-22 14:35:10 +0000442 GET_STR_LEN(seq_items[i], l);
443 required_len += l;
Damiend99b0522013-12-21 18:17:45 +0000444 }
445
446 // make joined string
Damien George05005f62015-01-21 22:48:37 +0000447 vstr_t vstr;
448 vstr_init_len(&vstr, required_len);
449 byte *data = (byte*)vstr.buf;
Damien George39dc1452014-10-03 19:52:22 +0100450 for (mp_uint_t i = 0; i < seq_len; i++) {
Damiend99b0522013-12-21 18:17:45 +0000451 if (i > 0) {
Damien George5fa93b62014-01-22 14:35:10 +0000452 memcpy(data, sep_str, sep_len);
453 data += sep_len;
Damiend99b0522013-12-21 18:17:45 +0000454 }
Damien George5fa93b62014-01-22 14:35:10 +0000455 GET_STR_DATA_LEN(seq_items[i], s, l);
456 memcpy(data, s, l);
457 data += l;
Damiend99b0522013-12-21 18:17:45 +0000458 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000459
460 // return joined string
Damien George05005f62015-01-21 22:48:37 +0000461 return mp_obj_new_str_from_vstr(self_type, &vstr);
Damiend99b0522013-12-21 18:17:45 +0000462}
463
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +0300464enum {SPLIT = 0, KEEP = 1, SPLITLINES = 2};
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200465
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +0300466STATIC inline mp_obj_t str_split_internal(mp_uint_t n_args, const mp_obj_t *args, int type) {
Paul Sokolovskybfb88192014-05-11 21:17:28 +0300467 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Damien George40f3c022014-07-03 13:25:24 +0100468 mp_int_t splits = -1;
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200469 mp_obj_t sep = mp_const_none;
470 if (n_args > 1) {
471 sep = args[1];
472 if (n_args > 2) {
Damien Georgedeed0872014-04-06 11:11:15 +0100473 splits = mp_obj_get_int(args[2]);
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200474 }
475 }
Damien Georgedeed0872014-04-06 11:11:15 +0100476
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200477 mp_obj_t res = mp_obj_new_list(0, NULL);
Damien George5fa93b62014-01-22 14:35:10 +0000478 GET_STR_DATA_LEN(args[0], s, len);
479 const byte *top = s + len;
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200480
Damien Georgedeed0872014-04-06 11:11:15 +0100481 if (sep == mp_const_none) {
482 // sep not given, so separate on whitespace
483
484 // Initial whitespace is not counted as split, so we pre-do it
Paul Sokolovsky8b7faa32015-04-12 00:17:16 +0300485 while (s < top && unichar_isspace(*s)) s++;
Damien Georgedeed0872014-04-06 11:11:15 +0100486 while (s < top && splits != 0) {
487 const byte *start = s;
Paul Sokolovsky8b7faa32015-04-12 00:17:16 +0300488 while (s < top && !unichar_isspace(*s)) s++;
Damien Georgef600a6a2014-05-25 22:34:34 +0100489 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, s - start));
Damien Georgedeed0872014-04-06 11:11:15 +0100490 if (s >= top) {
491 break;
492 }
Paul Sokolovsky8b7faa32015-04-12 00:17:16 +0300493 while (s < top && unichar_isspace(*s)) s++;
Damien Georgedeed0872014-04-06 11:11:15 +0100494 if (splits > 0) {
495 splits--;
496 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200497 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200498
Damien Georgedeed0872014-04-06 11:11:15 +0100499 if (s < top) {
Damien Georgef600a6a2014-05-25 22:34:34 +0100500 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, s, top - s));
Damien Georgedeed0872014-04-06 11:11:15 +0100501 }
502
503 } else {
504 // sep given
Paul Sokolovsky0c549852014-08-10 23:14:35 +0300505 if (mp_obj_get_type(sep) != self_type) {
Damien Georgec55a4d82014-12-24 20:28:30 +0000506 bad_implicit_conversion(sep);
Paul Sokolovsky0c549852014-08-10 23:14:35 +0300507 }
Damien Georgedeed0872014-04-06 11:11:15 +0100508
Damien Georged182b982014-08-30 14:19:41 +0100509 mp_uint_t sep_len;
Damien Georgedeed0872014-04-06 11:11:15 +0100510 const char *sep_str = mp_obj_str_get_data(sep, &sep_len);
511
512 if (sep_len == 0) {
513 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
514 }
515
516 for (;;) {
517 const byte *start = s;
518 for (;;) {
519 if (splits == 0 || s + sep_len > top) {
520 s = top;
521 break;
522 } else if (memcmp(s, sep_str, sep_len) == 0) {
523 break;
524 }
525 s++;
526 }
Paul Sokolovskyacf6aec2015-04-04 01:23:18 +0300527 mp_uint_t sub_len = s - start;
Paul Sokolovsky7f59b4b2015-04-04 01:55:40 +0300528 if (MP_LIKELY(!(sub_len == 0 && s == top && (type && SPLITLINES)))) {
529 if (start + sub_len != top && (type & KEEP)) {
Paul Sokolovskyacf6aec2015-04-04 01:23:18 +0300530 sub_len++;
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +0300531 }
Paul Sokolovskyacf6aec2015-04-04 01:23:18 +0300532 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, sub_len));
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +0300533 }
Damien Georgedeed0872014-04-06 11:11:15 +0100534 if (s >= top) {
535 break;
536 }
537 s += sep_len;
538 if (splits > 0) {
539 splits--;
540 }
541 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200542 }
543
544 return res;
545}
546
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +0300547mp_obj_t mp_obj_str_split(mp_uint_t n_args, const mp_obj_t *args) {
548 return str_split_internal(n_args, args, SPLIT);
549}
550
551#if MICROPY_PY_BUILTINS_STR_SPLITLINES
552STATIC mp_obj_t str_splitlines(mp_uint_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
553 static const mp_arg_t allowed_args[] = {
554 { MP_QSTR_keepends, MP_ARG_BOOL, {.u_bool = false} },
555 };
556
557 // parse args
558 mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
559 mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
560
561 mp_obj_t new_args[2] = {pos_args[0], MP_OBJ_NEW_QSTR(MP_QSTR__backslash_n)};
562 return str_split_internal(2, new_args, SPLITLINES | (args[0].u_bool ? KEEP : 0));
563}
564#endif
565
Damien Georgeecc88e92014-08-30 00:35:11 +0100566STATIC mp_obj_t str_rsplit(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300567 if (n_args < 3) {
568 // If we don't have split limit, it doesn't matter from which side
569 // we split.
Paul Sokolovsky87051712015-03-23 22:15:12 +0200570 return mp_obj_str_split(n_args, args);
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300571 }
572 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
573 mp_obj_t sep = args[1];
574 GET_STR_DATA_LEN(args[0], s, len);
575
Damien George40f3c022014-07-03 13:25:24 +0100576 mp_int_t splits = mp_obj_get_int(args[2]);
577 mp_int_t org_splits = splits;
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300578 // Preallocate list to the max expected # of elements, as we
579 // will fill it from the end.
580 mp_obj_list_t *res = mp_obj_new_list(splits + 1, NULL);
Damien George39dc1452014-10-03 19:52:22 +0100581 mp_int_t idx = splits;
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300582
583 if (sep == mp_const_none) {
Damien George22602cc2015-09-01 15:35:31 +0100584 mp_not_implemented("rsplit(None,n)");
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300585 } else {
Damien Georged182b982014-08-30 14:19:41 +0100586 mp_uint_t sep_len;
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300587 const char *sep_str = mp_obj_str_get_data(sep, &sep_len);
588
589 if (sep_len == 0) {
590 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
591 }
592
593 const byte *beg = s;
594 const byte *last = s + len;
595 for (;;) {
596 s = last - sep_len;
597 for (;;) {
598 if (splits == 0 || s < beg) {
599 break;
600 } else if (memcmp(s, sep_str, sep_len) == 0) {
601 break;
602 }
603 s--;
604 }
605 if (s < beg || splits == 0) {
Damien Georgef600a6a2014-05-25 22:34:34 +0100606 res->items[idx] = mp_obj_new_str_of_type(self_type, beg, last - beg);
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300607 break;
608 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100609 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 +0300610 last = s;
611 if (splits > 0) {
612 splits--;
613 }
614 }
615 if (idx != 0) {
616 // We split less parts than split limit, now go cleanup surplus
Damien George39dc1452014-10-03 19:52:22 +0100617 mp_int_t used = org_splits + 1 - idx;
Damien George17ae2392014-08-29 21:07:54 +0100618 memmove(res->items, &res->items[idx], used * sizeof(mp_obj_t));
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300619 mp_seq_clear(res->items, used, res->alloc, sizeof(*res->items));
620 res->len = used;
621 }
622 }
623
624 return res;
625}
626
Damien Georgeecc88e92014-08-30 00:35:11 +0100627STATIC mp_obj_t str_finder(mp_uint_t n_args, const mp_obj_t *args, mp_int_t direction, bool is_index) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300628 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
John R. Lentone8204912014-01-12 21:53:52 +0000629 assert(2 <= n_args && n_args <= 4);
Damien Georgebe8e99c2014-11-05 16:45:54 +0000630 assert(MP_OBJ_IS_STR_OR_BYTES(args[0]));
631
632 // check argument type
Damien Georgec55a4d82014-12-24 20:28:30 +0000633 if (mp_obj_get_type(args[1]) != self_type) {
Damien Georgebe8e99c2014-11-05 16:45:54 +0000634 bad_implicit_conversion(args[1]);
635 }
John R. Lentone8204912014-01-12 21:53:52 +0000636
Damien George5fa93b62014-01-22 14:35:10 +0000637 GET_STR_DATA_LEN(args[0], haystack, haystack_len);
638 GET_STR_DATA_LEN(args[1], needle, needle_len);
John R. Lentone8204912014-01-12 21:53:52 +0000639
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300640 const byte *start = haystack;
641 const byte *end = haystack + haystack_len;
John R. Lentone8204912014-01-12 21:53:52 +0000642 if (n_args >= 3 && args[2] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300643 start = str_index_to_ptr(self_type, haystack, haystack_len, args[2], true);
John R. Lentone8204912014-01-12 21:53:52 +0000644 }
645 if (n_args >= 4 && args[3] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300646 end = str_index_to_ptr(self_type, haystack, haystack_len, args[3], true);
John R. Lentone8204912014-01-12 21:53:52 +0000647 }
648
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300649 const byte *p = find_subbytes(start, end - start, needle, needle_len, direction);
Damien George23005372014-01-13 19:39:01 +0000650 if (p == NULL) {
651 // not found
xbe3d9a39e2014-04-08 11:42:19 -0700652 if (is_index) {
653 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "substring not found"));
654 } else {
655 return MP_OBJ_NEW_SMALL_INT(-1);
656 }
Damien George23005372014-01-13 19:39:01 +0000657 } else {
658 // found
Paul Sokolovsky5048df02014-06-14 03:15:00 +0300659 #if MICROPY_PY_BUILTINS_STR_UNICODE
660 if (self_type == &mp_type_str) {
661 return MP_OBJ_NEW_SMALL_INT(utf8_ptr_to_index(haystack, p));
662 }
663 #endif
xbe17a5a832014-03-23 23:31:58 -0700664 return MP_OBJ_NEW_SMALL_INT(p - haystack);
John R. Lentone8204912014-01-12 21:53:52 +0000665 }
John R. Lentone8204912014-01-12 21:53:52 +0000666}
667
Damien Georgeecc88e92014-08-30 00:35:11 +0100668STATIC mp_obj_t str_find(mp_uint_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700669 return str_finder(n_args, args, 1, false);
xbe17a5a832014-03-23 23:31:58 -0700670}
671
Damien Georgeecc88e92014-08-30 00:35:11 +0100672STATIC mp_obj_t str_rfind(mp_uint_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700673 return str_finder(n_args, args, -1, false);
674}
675
Damien Georgeecc88e92014-08-30 00:35:11 +0100676STATIC mp_obj_t str_index(mp_uint_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700677 return str_finder(n_args, args, 1, true);
678}
679
Damien Georgeecc88e92014-08-30 00:35:11 +0100680STATIC mp_obj_t str_rindex(mp_uint_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700681 return str_finder(n_args, args, -1, true);
xbe17a5a832014-03-23 23:31:58 -0700682}
683
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200684// TODO: (Much) more variety in args
Damien Georgeecc88e92014-08-30 00:35:11 +0100685STATIC mp_obj_t str_startswith(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300686 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300687 GET_STR_DATA_LEN(args[0], str, str_len);
688 GET_STR_DATA_LEN(args[1], prefix, prefix_len);
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300689 const byte *start = str;
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300690 if (n_args > 2) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300691 start = str_index_to_ptr(self_type, str, str_len, args[2], true);
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300692 }
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300693 if (prefix_len + (start - str) > str_len) {
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200694 return mp_const_false;
695 }
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300696 return MP_BOOL(memcmp(start, prefix, prefix_len) == 0);
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200697}
698
Damien Georgeecc88e92014-08-30 00:35:11 +0100699STATIC mp_obj_t str_endswith(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +0300700 GET_STR_DATA_LEN(args[0], str, str_len);
701 GET_STR_DATA_LEN(args[1], suffix, suffix_len);
Damien George55b11e62015-09-04 16:49:56 +0100702 if (n_args > 2) {
703 mp_not_implemented("start/end indices");
704 }
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +0300705
706 if (suffix_len > str_len) {
707 return mp_const_false;
708 }
709 return MP_BOOL(memcmp(str + (str_len - suffix_len), suffix, suffix_len) == 0);
710}
711
Paul Sokolovsky88107842014-04-26 06:20:08 +0300712enum { LSTRIP, RSTRIP, STRIP };
713
Damien Georgeecc88e92014-08-30 00:35:11 +0100714STATIC mp_obj_t str_uni_strip(int type, mp_uint_t n_args, const mp_obj_t *args) {
xbe7b0f39f2014-01-08 14:23:45 -0800715 assert(1 <= n_args && n_args <= 2);
Dave Hylandsb7f7c652014-08-26 12:44:46 -0700716 assert(MP_OBJ_IS_STR_OR_BYTES(args[0]));
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300717 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Damien George5fa93b62014-01-22 14:35:10 +0000718
719 const byte *chars_to_del;
720 uint chars_to_del_len;
721 static const byte whitespace[] = " \t\n\r\v\f";
xbe7b0f39f2014-01-08 14:23:45 -0800722
723 if (n_args == 1) {
724 chars_to_del = whitespace;
Damien George5fa93b62014-01-22 14:35:10 +0000725 chars_to_del_len = sizeof(whitespace);
xbe7b0f39f2014-01-08 14:23:45 -0800726 } else {
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300727 if (mp_obj_get_type(args[1]) != self_type) {
Damien Georgec55a4d82014-12-24 20:28:30 +0000728 bad_implicit_conversion(args[1]);
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300729 }
Damien George5fa93b62014-01-22 14:35:10 +0000730 GET_STR_DATA_LEN(args[1], s, l);
731 chars_to_del = s;
732 chars_to_del_len = l;
xbe7b0f39f2014-01-08 14:23:45 -0800733 }
734
Damien George5fa93b62014-01-22 14:35:10 +0000735 GET_STR_DATA_LEN(args[0], orig_str, orig_str_len);
xbe7b0f39f2014-01-08 14:23:45 -0800736
Damien George40f3c022014-07-03 13:25:24 +0100737 mp_uint_t first_good_char_pos = 0;
xbe7b0f39f2014-01-08 14:23:45 -0800738 bool first_good_char_pos_set = false;
Damien George40f3c022014-07-03 13:25:24 +0100739 mp_uint_t last_good_char_pos = 0;
740 mp_uint_t i = 0;
741 mp_int_t delta = 1;
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300742 if (type == RSTRIP) {
743 i = orig_str_len - 1;
744 delta = -1;
745 }
Damien George40f3c022014-07-03 13:25:24 +0100746 for (mp_uint_t len = orig_str_len; len > 0; len--) {
xbe17a5a832014-03-23 23:31:58 -0700747 if (find_subbytes(chars_to_del, chars_to_del_len, &orig_str[i], 1, 1) == NULL) {
xbe7b0f39f2014-01-08 14:23:45 -0800748 if (!first_good_char_pos_set) {
Paul Sokolovskybcdffe52014-05-30 03:07:05 +0300749 first_good_char_pos_set = true;
xbe7b0f39f2014-01-08 14:23:45 -0800750 first_good_char_pos = i;
Paul Sokolovsky88107842014-04-26 06:20:08 +0300751 if (type == LSTRIP) {
752 last_good_char_pos = orig_str_len - 1;
753 break;
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300754 } else if (type == RSTRIP) {
755 first_good_char_pos = 0;
756 last_good_char_pos = i;
757 break;
Paul Sokolovsky88107842014-04-26 06:20:08 +0300758 }
xbe7b0f39f2014-01-08 14:23:45 -0800759 }
Paul Sokolovsky88107842014-04-26 06:20:08 +0300760 last_good_char_pos = i;
xbe7b0f39f2014-01-08 14:23:45 -0800761 }
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300762 i += delta;
xbe7b0f39f2014-01-08 14:23:45 -0800763 }
764
Paul Sokolovskybcdffe52014-05-30 03:07:05 +0300765 if (!first_good_char_pos_set) {
Damien George5fa93b62014-01-22 14:35:10 +0000766 // string is all whitespace, return ''
Damien Georgec55a4d82014-12-24 20:28:30 +0000767 if (self_type == &mp_type_str) {
768 return MP_OBJ_NEW_QSTR(MP_QSTR_);
769 } else {
770 return mp_const_empty_bytes;
771 }
xbe7b0f39f2014-01-08 14:23:45 -0800772 }
773
774 assert(last_good_char_pos >= first_good_char_pos);
775 //+1 to accomodate the last character
Damien George40f3c022014-07-03 13:25:24 +0100776 mp_uint_t stripped_len = last_good_char_pos - first_good_char_pos + 1;
Paul Sokolovsky88276822014-05-30 03:11:44 +0300777 if (stripped_len == orig_str_len) {
778 // If nothing was stripped, don't bother to dup original string
779 // TODO: watch out for this case when we'll get to bytearray.strip()
780 assert(first_good_char_pos == 0);
781 return args[0];
782 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100783 return mp_obj_new_str_of_type(self_type, orig_str + first_good_char_pos, stripped_len);
xbe7b0f39f2014-01-08 14:23:45 -0800784}
785
Damien Georgeecc88e92014-08-30 00:35:11 +0100786STATIC mp_obj_t str_strip(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky88107842014-04-26 06:20:08 +0300787 return str_uni_strip(STRIP, n_args, args);
788}
789
Damien Georgeecc88e92014-08-30 00:35:11 +0100790STATIC mp_obj_t str_lstrip(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky88107842014-04-26 06:20:08 +0300791 return str_uni_strip(LSTRIP, n_args, args);
792}
793
Damien Georgeecc88e92014-08-30 00:35:11 +0100794STATIC mp_obj_t str_rstrip(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky88107842014-04-26 06:20:08 +0300795 return str_uni_strip(RSTRIP, n_args, args);
796}
797
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700798// Takes an int arg, but only parses unsigned numbers, and only changes
799// *num if at least one digit was parsed.
Damien George2801e6f2015-04-04 15:53:11 +0100800STATIC int str_to_int(const char *str, int *num) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700801 const char *s = str;
Damien George81836c22014-12-21 21:07:03 +0000802 if ('0' <= *s && *s <= '9') {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700803 *num = 0;
804 do {
805 *num = *num * 10 + (*s - '0');
806 s++;
807 }
Damien George81836c22014-12-21 21:07:03 +0000808 while ('0' <= *s && *s <= '9');
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700809 }
810 return s - str;
811}
812
Damien George2801e6f2015-04-04 15:53:11 +0100813STATIC bool isalignment(char ch) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700814 return ch && strchr("<>=^", ch) != NULL;
815}
816
Damien George2801e6f2015-04-04 15:53:11 +0100817STATIC bool istype(char ch) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700818 return ch && strchr("bcdeEfFgGnosxX%", ch) != NULL;
819}
820
Damien George2801e6f2015-04-04 15:53:11 +0100821STATIC bool arg_looks_integer(mp_obj_t arg) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700822 return MP_OBJ_IS_TYPE(arg, &mp_type_bool) || MP_OBJ_IS_INT(arg);
823}
824
Damien George2801e6f2015-04-04 15:53:11 +0100825STATIC bool arg_looks_numeric(mp_obj_t arg) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700826 return arg_looks_integer(arg)
Damien Georgefb510b32014-06-01 13:32:54 +0100827#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700828 || MP_OBJ_IS_TYPE(arg, &mp_type_float)
829#endif
830 ;
831}
832
Damien George2801e6f2015-04-04 15:53:11 +0100833STATIC mp_obj_t arg_as_int(mp_obj_t arg) {
Damien Georgefb510b32014-06-01 13:32:54 +0100834#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700835 if (MP_OBJ_IS_TYPE(arg, &mp_type_float)) {
Paul Sokolovsky2c756652014-12-31 02:20:57 +0200836 return mp_obj_new_int_from_float(mp_obj_get_float(arg));
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700837 }
838#endif
Dave Hylandsc4029e52014-04-07 11:19:51 -0700839 return arg;
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700840}
841
Damien George1e9a92f2014-11-06 17:36:16 +0000842STATIC NORETURN void terse_str_format_value_error(void) {
843 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "bad format string"));
844}
845
Paul Sokolovskyc1144962015-01-04 00:14:13 +0200846mp_obj_t mp_obj_str_format(mp_uint_t n_args, const mp_obj_t *args, mp_map_t *kwargs) {
Damien Georgebe8e99c2014-11-05 16:45:54 +0000847 assert(MP_OBJ_IS_STR_OR_BYTES(args[0]));
Damiend99b0522013-12-21 18:17:45 +0000848
Damien George5fa93b62014-01-22 14:35:10 +0000849 GET_STR_DATA_LEN(args[0], str, len);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700850 int arg_i = 0;
Damien George0b9ee862015-01-21 19:14:25 +0000851 vstr_t vstr;
Damien George7f9d1d62015-04-09 23:56:15 +0100852 mp_print_t print;
853 vstr_init_print(&vstr, 16, &print);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700854
Damien George5fa93b62014-01-22 14:35:10 +0000855 for (const byte *top = str + len; str < top; str++) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700856 if (*str == '}') {
Damiend99b0522013-12-21 18:17:45 +0000857 str++;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700858 if (str < top && *str == '}') {
Damien George51b9a0d2015-08-26 15:29:49 +0100859 vstr_add_byte(&vstr, '}');
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700860 continue;
861 }
Damien George1e9a92f2014-11-06 17:36:16 +0000862 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
863 terse_str_format_value_error();
864 } else {
865 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
866 "single '}' encountered in format string"));
867 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700868 }
869 if (*str != '{') {
Damien George51b9a0d2015-08-26 15:29:49 +0100870 vstr_add_byte(&vstr, *str);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700871 continue;
872 }
873
874 str++;
875 if (str < top && *str == '{') {
Damien George51b9a0d2015-08-26 15:29:49 +0100876 vstr_add_byte(&vstr, '{');
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700877 continue;
878 }
879
880 // replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"
881
882 vstr_t *field_name = NULL;
883 char conversion = '\0';
884 vstr_t *format_spec = NULL;
885
886 if (str < top && *str != '}' && *str != '!' && *str != ':') {
887 field_name = vstr_new();
888 while (str < top && *str != '}' && *str != '!' && *str != ':') {
Damien George51b9a0d2015-08-26 15:29:49 +0100889 vstr_add_byte(field_name, *str++);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700890 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700891 }
892
893 // conversion ::= "r" | "s"
894
895 if (str < top && *str == '!') {
896 str++;
897 if (str < top && (*str == 'r' || *str == 's')) {
898 conversion = *str++;
Paul Sokolovskyf2b796e2014-01-15 22:45:20 +0200899 } else {
Damien George1e9a92f2014-11-06 17:36:16 +0000900 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
901 terse_str_format_value_error();
Damien George000730e2015-08-30 12:43:21 +0100902 } else if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_NORMAL) {
Damien George1e9a92f2014-11-06 17:36:16 +0000903 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
Damien George000730e2015-08-30 12:43:21 +0100904 "bad conversion specifier"));
905 } else {
906 if (str >= top) {
907 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
908 "end of format while looking for conversion specifier"));
909 } else {
910 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
911 "unknown conversion specifier %c", *str));
912 }
Damien George1e9a92f2014-11-06 17:36:16 +0000913 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700914 }
915 }
916
917 if (str < top && *str == ':') {
918 str++;
919 // {:} is the same as {}, which is the same as {!s}
920 // This makes a difference when passing in a True or False
921 // '{}'.format(True) returns 'True'
922 // '{:d}'.format(True) returns '1'
923 // So we treat {:} as {} and this later gets treated to be {!s}
924 if (*str != '}') {
Damien George11de8392014-06-05 18:57:38 +0100925 format_spec = vstr_new();
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700926 while (str < top && *str != '}') {
Damien George51b9a0d2015-08-26 15:29:49 +0100927 vstr_add_byte(format_spec, *str++);
Damiend99b0522013-12-21 18:17:45 +0000928 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700929 }
930 }
931 if (str >= top) {
Damien George1e9a92f2014-11-06 17:36:16 +0000932 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
933 terse_str_format_value_error();
934 } else {
935 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
936 "unmatched '{' in format"));
937 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700938 }
939 if (*str != '}') {
Damien George1e9a92f2014-11-06 17:36:16 +0000940 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
941 terse_str_format_value_error();
942 } else {
943 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
944 "expected ':' after format specifier"));
945 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700946 }
947
948 mp_obj_t arg = mp_const_none;
949
950 if (field_name) {
Damien George3bb8bd82014-04-14 21:20:30 +0100951 int index = 0;
Damien George827b0f72015-01-29 13:57:23 +0000952 const char *field = vstr_null_terminated_str(field_name);
Paul Sokolovskyc1144962015-01-04 00:14:13 +0200953 const char *lookup = NULL;
954 if (MP_LIKELY(unichar_isdigit(*field))) {
955 if (arg_i > 0) {
956 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
957 terse_str_format_value_error();
958 } else {
959 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
960 "can't switch from automatic field numbering to manual field specification"));
961 }
962 }
Paul Sokolovskyff8e35b2015-01-04 13:23:44 +0200963 lookup = str_to_int(field, &index) + field;
Damien George963a5a32015-01-16 17:47:07 +0000964 if ((uint)index >= n_args - 1) {
Paul Sokolovskyc1144962015-01-04 00:14:13 +0200965 nlr_raise(mp_obj_new_exception_msg(&mp_type_IndexError, "tuple index out of range"));
966 }
967 arg = args[index + 1];
968 arg_i = -1;
969 } else {
970 for (lookup = field; *lookup && *lookup != '.' && *lookup != '['; lookup++);
971 mp_obj_t field_q = mp_obj_new_str(field, lookup - field, true/*?*/);
972 mp_map_elem_t *key_elem = mp_map_lookup(kwargs, field_q, MP_MAP_LOOKUP);
973 if (key_elem == NULL) {
974 nlr_raise(mp_obj_new_exception_arg1(&mp_type_KeyError, field_q));
975 }
976 arg = key_elem->value;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700977 }
Paul Sokolovskyc1144962015-01-04 00:14:13 +0200978 if (*lookup) {
Damien George821b7f22015-09-03 23:14:06 +0100979 mp_not_implemented("attributes not supported yet");
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700980 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700981 vstr_free(field_name);
982 field_name = NULL;
983 } else {
984 if (arg_i < 0) {
Damien George1e9a92f2014-11-06 17:36:16 +0000985 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
986 terse_str_format_value_error();
987 } else {
988 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
989 "can't switch from manual field specification to automatic field numbering"));
990 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700991 }
Damien George963a5a32015-01-16 17:47:07 +0000992 if ((uint)arg_i >= n_args - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100993 nlr_raise(mp_obj_new_exception_msg(&mp_type_IndexError, "tuple index out of range"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700994 }
995 arg = args[arg_i + 1];
996 arg_i++;
997 }
998 if (!format_spec && !conversion) {
999 conversion = 's';
1000 }
1001 if (conversion) {
1002 mp_print_kind_t print_kind;
1003 if (conversion == 's') {
1004 print_kind = PRINT_STR;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001005 } else {
Damien George000730e2015-08-30 12:43:21 +01001006 assert(conversion == 'r');
1007 print_kind = PRINT_REPR;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001008 }
Damien George0b9ee862015-01-21 19:14:25 +00001009 vstr_t arg_vstr;
Damien George7f9d1d62015-04-09 23:56:15 +01001010 mp_print_t arg_print;
1011 vstr_init_print(&arg_vstr, 16, &arg_print);
1012 mp_obj_print_helper(&arg_print, arg, print_kind);
Damien George0b9ee862015-01-21 19:14:25 +00001013 arg = mp_obj_new_str_from_vstr(&mp_type_str, &arg_vstr);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001014 }
1015
1016 char sign = '\0';
1017 char fill = '\0';
1018 char align = '\0';
1019 int width = -1;
1020 int precision = -1;
1021 char type = '\0';
1022 int flags = 0;
1023
1024 if (format_spec) {
1025 // The format specifier (from http://docs.python.org/2/library/string.html#formatspec)
1026 //
1027 // [[fill]align][sign][#][0][width][,][.precision][type]
1028 // fill ::= <any character>
1029 // align ::= "<" | ">" | "=" | "^"
1030 // sign ::= "+" | "-" | " "
1031 // width ::= integer
1032 // precision ::= integer
1033 // type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
1034
Damien George827b0f72015-01-29 13:57:23 +00001035 const char *s = vstr_null_terminated_str(format_spec);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001036 if (isalignment(*s)) {
1037 align = *s++;
1038 } else if (*s && isalignment(s[1])) {
1039 fill = *s++;
1040 align = *s++;
1041 }
1042 if (*s == '+' || *s == '-' || *s == ' ') {
1043 if (*s == '+') {
1044 flags |= PF_FLAG_SHOW_SIGN;
1045 } else if (*s == ' ') {
1046 flags |= PF_FLAG_SPACE_SIGN;
1047 }
1048 sign = *s++;
1049 }
1050 if (*s == '#') {
1051 flags |= PF_FLAG_SHOW_PREFIX;
1052 s++;
1053 }
1054 if (*s == '0') {
1055 if (!align) {
1056 align = '=';
1057 }
1058 if (!fill) {
1059 fill = '0';
1060 }
1061 }
1062 s += str_to_int(s, &width);
1063 if (*s == ',') {
1064 flags |= PF_FLAG_SHOW_COMMA;
1065 s++;
1066 }
1067 if (*s == '.') {
1068 s++;
1069 s += str_to_int(s, &precision);
1070 }
1071 if (istype(*s)) {
1072 type = *s++;
1073 }
1074 if (*s) {
Damien George7ef75f92015-08-26 15:42:25 +01001075 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1076 terse_str_format_value_error();
1077 } else {
1078 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
1079 "invalid format specifier"));
1080 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001081 }
1082 vstr_free(format_spec);
1083 format_spec = NULL;
1084 }
1085 if (!align) {
1086 if (arg_looks_numeric(arg)) {
1087 align = '>';
1088 } else {
1089 align = '<';
1090 }
1091 }
1092 if (!fill) {
1093 fill = ' ';
1094 }
1095
1096 if (sign) {
1097 if (type == 's') {
Damien George1e9a92f2014-11-06 17:36:16 +00001098 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1099 terse_str_format_value_error();
1100 } else {
1101 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
1102 "sign not allowed in string format specifier"));
1103 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001104 }
1105 if (type == 'c') {
Damien George1e9a92f2014-11-06 17:36:16 +00001106 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1107 terse_str_format_value_error();
1108 } else {
1109 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
1110 "sign not allowed with integer format specifier 'c'"));
1111 }
Damiend99b0522013-12-21 18:17:45 +00001112 }
1113 } else {
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001114 sign = '-';
1115 }
1116
1117 switch (align) {
1118 case '<': flags |= PF_FLAG_LEFT_ADJUST; break;
1119 case '=': flags |= PF_FLAG_PAD_AFTER_SIGN; break;
1120 case '^': flags |= PF_FLAG_CENTER_ADJUST; break;
1121 }
1122
1123 if (arg_looks_integer(arg)) {
1124 switch (type) {
1125 case 'b':
Damien George7f9d1d62015-04-09 23:56:15 +01001126 mp_print_mp_int(&print, arg, 2, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001127 continue;
1128
1129 case 'c':
1130 {
1131 char ch = mp_obj_get_int(arg);
Damien George7f9d1d62015-04-09 23:56:15 +01001132 mp_print_strn(&print, &ch, 1, flags, fill, width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001133 continue;
1134 }
1135
1136 case '\0': // No explicit format type implies 'd'
1137 case 'n': // I don't think we support locales in uPy so use 'd'
1138 case 'd':
Damien George7f9d1d62015-04-09 23:56:15 +01001139 mp_print_mp_int(&print, arg, 10, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001140 continue;
1141
1142 case 'o':
Dave Hylandsc4029e52014-04-07 11:19:51 -07001143 if (flags & PF_FLAG_SHOW_PREFIX) {
1144 flags |= PF_FLAG_SHOW_OCTAL_LETTER;
1145 }
1146
Damien George7f9d1d62015-04-09 23:56:15 +01001147 mp_print_mp_int(&print, arg, 8, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001148 continue;
1149
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001150 case 'X':
Damien George11de8392014-06-05 18:57:38 +01001151 case 'x':
Damien George7f9d1d62015-04-09 23:56:15 +01001152 mp_print_mp_int(&print, arg, 16, type - ('X' - 'A'), flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001153 continue;
1154
1155 case 'e':
1156 case 'E':
1157 case 'f':
1158 case 'F':
1159 case 'g':
1160 case 'G':
1161 case '%':
1162 // The floating point formatters all work with anything that
1163 // looks like an integer
1164 break;
1165
1166 default:
Damien George1e9a92f2014-11-06 17:36:16 +00001167 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1168 terse_str_format_value_error();
1169 } else {
1170 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
1171 "unknown format code '%c' for object of type '%s'",
1172 type, mp_obj_get_type_str(arg)));
1173 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001174 }
Damien Georgec322c5f2014-04-02 20:04:15 +01001175 }
Damien George70f33cd2014-04-02 17:06:05 +01001176
Dave Hylands22fe4d72014-04-02 12:07:31 -07001177 // NOTE: no else here. We need the e, f, g etc formats for integer
1178 // arguments (from above if) to take this if.
Damien Georgec322c5f2014-04-02 20:04:15 +01001179 if (arg_looks_numeric(arg)) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001180 if (!type) {
1181
1182 // Even though the docs say that an unspecified type is the same
1183 // as 'g', there is one subtle difference, when the exponent
1184 // is one less than the precision.
Damien George11de8392014-06-05 18:57:38 +01001185 //
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001186 // '{:10.1}'.format(0.0) ==> '0e+00'
1187 // '{:10.1g}'.format(0.0) ==> '0'
1188 //
1189 // TODO: Figure out how to deal with this.
1190 //
1191 // A proper solution would involve adding a special flag
1192 // or something to format_float, and create a format_double
1193 // to deal with doubles. In order to fix this when using
1194 // sprintf, we'd need to use the e format and tweak the
1195 // returned result to strip trailing zeros like the g format
1196 // does.
1197 //
1198 // {:10.3} and {:10.2e} with 1.23e2 both produce 1.23e+02
1199 // but with 1.e2 you get 1e+02 and 1.00e+02
1200 //
1201 // Stripping the trailing 0's (like g) does would make the
1202 // e format give us the right format.
1203 //
1204 // CPython sources say:
1205 // Omitted type specifier. Behaves in the same way as repr(x)
1206 // and str(x) if no precision is given, else like 'g', but with
1207 // at least one digit after the decimal point. */
1208
1209 type = 'g';
1210 }
1211 if (type == 'n') {
1212 type = 'g';
1213 }
1214
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001215 switch (type) {
Damien Georgefb510b32014-06-01 13:32:54 +01001216#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001217 case 'e':
1218 case 'E':
1219 case 'f':
1220 case 'F':
1221 case 'g':
1222 case 'G':
Damien George7f9d1d62015-04-09 23:56:15 +01001223 mp_print_float(&print, mp_obj_get_float(arg), type, flags, fill, width, precision);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001224 break;
1225
1226 case '%':
1227 flags |= PF_FLAG_ADD_PERCENT;
Damien George0178aa92015-01-12 21:56:35 +00001228 #if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT
1229 #define F100 100.0F
1230 #else
1231 #define F100 100.0
1232 #endif
Damien George7f9d1d62015-04-09 23:56:15 +01001233 mp_print_float(&print, mp_obj_get_float(arg) * F100, 'f', flags, fill, width, precision);
Damien George0178aa92015-01-12 21:56:35 +00001234 #undef F100
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001235 break;
Damien Georgec322c5f2014-04-02 20:04:15 +01001236#endif
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001237
1238 default:
Damien George1e9a92f2014-11-06 17:36:16 +00001239 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1240 terse_str_format_value_error();
1241 } else {
1242 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
1243 "unknown format code '%c' for object of type 'float'",
1244 type, mp_obj_get_type_str(arg)));
1245 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001246 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001247 } else {
Damien George70f33cd2014-04-02 17:06:05 +01001248 // arg doesn't look like a number
1249
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001250 if (align == '=') {
Damien George1e9a92f2014-11-06 17:36:16 +00001251 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1252 terse_str_format_value_error();
1253 } else {
1254 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
1255 "'=' alignment not allowed in string format specifier"));
1256 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001257 }
Damien George70f33cd2014-04-02 17:06:05 +01001258
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001259 switch (type) {
1260 case '\0':
Damien George7f9d1d62015-04-09 23:56:15 +01001261 mp_obj_print_helper(&print, arg, PRINT_STR);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001262 break;
1263
Damien Georged182b982014-08-30 14:19:41 +01001264 case 's': {
Damien George50912e72015-01-20 11:55:10 +00001265 mp_uint_t slen;
1266 const char *s = mp_obj_str_get_data(arg, &slen);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001267 if (precision < 0) {
Damien George50912e72015-01-20 11:55:10 +00001268 precision = slen;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001269 }
Damien George50912e72015-01-20 11:55:10 +00001270 if (slen > (mp_uint_t)precision) {
1271 slen = precision;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001272 }
Damien George7f9d1d62015-04-09 23:56:15 +01001273 mp_print_strn(&print, s, slen, flags, fill, width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001274 break;
1275 }
1276
1277 default:
Damien George1e9a92f2014-11-06 17:36:16 +00001278 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1279 terse_str_format_value_error();
1280 } else {
1281 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
1282 "unknown format code '%c' for object of type 'str'",
1283 type, mp_obj_get_type_str(arg)));
1284 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001285 }
Damiend99b0522013-12-21 18:17:45 +00001286 }
1287 }
1288
Damien George0b9ee862015-01-21 19:14:25 +00001289 return mp_obj_new_str_from_vstr(&mp_type_str, &vstr);
Damiend99b0522013-12-21 18:17:45 +00001290}
1291
Damien Georgeecc88e92014-08-30 00:35:11 +01001292STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, mp_uint_t n_args, const mp_obj_t *args, mp_obj_t dict) {
Damien Georgebe8e99c2014-11-05 16:45:54 +00001293 assert(MP_OBJ_IS_STR_OR_BYTES(pattern));
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001294
1295 GET_STR_DATA_LEN(pattern, str, len);
Dave Hylands6756a372014-04-02 11:42:39 -07001296 const byte *start_str = str;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001297 int arg_i = 0;
Damien George0b9ee862015-01-21 19:14:25 +00001298 vstr_t vstr;
Damien George7f9d1d62015-04-09 23:56:15 +01001299 mp_print_t print;
1300 vstr_init_print(&vstr, 16, &print);
Dave Hylands6756a372014-04-02 11:42:39 -07001301
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001302 for (const byte *top = str + len; str < top; str++) {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001303 mp_obj_t arg = MP_OBJ_NULL;
Dave Hylands6756a372014-04-02 11:42:39 -07001304 if (*str != '%') {
Damien George51b9a0d2015-08-26 15:29:49 +01001305 vstr_add_byte(&vstr, *str);
Dave Hylands6756a372014-04-02 11:42:39 -07001306 continue;
1307 }
1308 if (++str >= top) {
Damien Georgeb648e982015-08-26 15:45:06 +01001309 goto incomplete_format;
Dave Hylands6756a372014-04-02 11:42:39 -07001310 }
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001311 if (*str == '%') {
Damien George51b9a0d2015-08-26 15:29:49 +01001312 vstr_add_byte(&vstr, '%');
Dave Hylands6756a372014-04-02 11:42:39 -07001313 continue;
1314 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001315
1316 // Dictionary value lookup
1317 if (*str == '(') {
1318 const byte *key = ++str;
1319 while (*str != ')') {
1320 if (str >= top) {
Damien George1e9a92f2014-11-06 17:36:16 +00001321 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1322 terse_str_format_value_error();
1323 } else {
1324 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
1325 "incomplete format key"));
1326 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001327 }
1328 ++str;
1329 }
1330 mp_obj_t k_obj = mp_obj_new_str((const char*)key, str - key, true);
1331 arg = mp_obj_dict_get(dict, k_obj);
1332 str++;
Dave Hylands6756a372014-04-02 11:42:39 -07001333 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001334
Dave Hylands6756a372014-04-02 11:42:39 -07001335 int flags = 0;
1336 char fill = ' ';
Damien George11de8392014-06-05 18:57:38 +01001337 int alt = 0;
Dave Hylands6756a372014-04-02 11:42:39 -07001338 while (str < top) {
1339 if (*str == '-') flags |= PF_FLAG_LEFT_ADJUST;
1340 else if (*str == '+') flags |= PF_FLAG_SHOW_SIGN;
1341 else if (*str == ' ') flags |= PF_FLAG_SPACE_SIGN;
Damien George11de8392014-06-05 18:57:38 +01001342 else if (*str == '#') alt = PF_FLAG_SHOW_PREFIX;
Dave Hylands6756a372014-04-02 11:42:39 -07001343 else if (*str == '0') {
1344 flags |= PF_FLAG_PAD_AFTER_SIGN;
1345 fill = '0';
1346 } else break;
1347 str++;
1348 }
1349 // parse width, if it exists
Damien George11de8392014-06-05 18:57:38 +01001350 int width = 0;
Dave Hylands6756a372014-04-02 11:42:39 -07001351 if (str < top) {
1352 if (*str == '*') {
Damien George963a5a32015-01-16 17:47:07 +00001353 if ((uint)arg_i >= n_args) {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001354 goto not_enough_args;
1355 }
Dave Hylands6756a372014-04-02 11:42:39 -07001356 width = mp_obj_get_int(args[arg_i++]);
1357 str++;
1358 } else {
Damien George81836c22014-12-21 21:07:03 +00001359 str += str_to_int((const char*)str, &width);
Dave Hylands6756a372014-04-02 11:42:39 -07001360 }
1361 }
1362 int prec = -1;
1363 if (str < top && *str == '.') {
1364 if (++str < top) {
1365 if (*str == '*') {
Damien George963a5a32015-01-16 17:47:07 +00001366 if ((uint)arg_i >= n_args) {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001367 goto not_enough_args;
1368 }
Dave Hylands6756a372014-04-02 11:42:39 -07001369 prec = mp_obj_get_int(args[arg_i++]);
1370 str++;
1371 } else {
1372 prec = 0;
Damien George81836c22014-12-21 21:07:03 +00001373 str += str_to_int((const char*)str, &prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001374 }
1375 }
1376 }
1377
1378 if (str >= top) {
Damien Georgeb648e982015-08-26 15:45:06 +01001379incomplete_format:
Damien George1e9a92f2014-11-06 17:36:16 +00001380 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1381 terse_str_format_value_error();
1382 } else {
1383 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
1384 "incomplete format"));
1385 }
Dave Hylands6756a372014-04-02 11:42:39 -07001386 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001387
1388 // Tuple value lookup
1389 if (arg == MP_OBJ_NULL) {
Damien George963a5a32015-01-16 17:47:07 +00001390 if ((uint)arg_i >= n_args) {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001391not_enough_args:
1392 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "not enough arguments for format string"));
1393 }
1394 arg = args[arg_i++];
1395 }
Dave Hylands6756a372014-04-02 11:42:39 -07001396 switch (*str) {
1397 case 'c':
1398 if (MP_OBJ_IS_STR(arg)) {
Damien George50912e72015-01-20 11:55:10 +00001399 mp_uint_t slen;
1400 const char *s = mp_obj_str_get_data(arg, &slen);
1401 if (slen != 1) {
Damien George1e9a92f2014-11-06 17:36:16 +00001402 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
1403 "%%c requires int or char"));
Dave Hylands6756a372014-04-02 11:42:39 -07001404 }
Damien George7f9d1d62015-04-09 23:56:15 +01001405 mp_print_strn(&print, s, 1, flags, ' ', width);
Damien George1e9a92f2014-11-06 17:36:16 +00001406 } else if (arg_looks_integer(arg)) {
Dave Hylands6756a372014-04-02 11:42:39 -07001407 char ch = mp_obj_get_int(arg);
Damien George7f9d1d62015-04-09 23:56:15 +01001408 mp_print_strn(&print, &ch, 1, flags, ' ', width);
Damien George1e9a92f2014-11-06 17:36:16 +00001409 } else {
1410 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
1411 "integer required"));
Dave Hylands6756a372014-04-02 11:42:39 -07001412 }
Damien George11de8392014-06-05 18:57:38 +01001413 break;
Dave Hylands6756a372014-04-02 11:42:39 -07001414
1415 case 'd':
1416 case 'i':
1417 case 'u':
Damien George7f9d1d62015-04-09 23:56:15 +01001418 mp_print_mp_int(&print, arg_as_int(arg), 10, 'a', flags, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001419 break;
1420
Damien Georgefb510b32014-06-01 13:32:54 +01001421#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylands6756a372014-04-02 11:42:39 -07001422 case 'e':
1423 case 'E':
1424 case 'f':
1425 case 'F':
1426 case 'g':
1427 case 'G':
Damien George7f9d1d62015-04-09 23:56:15 +01001428 mp_print_float(&print, mp_obj_get_float(arg), *str, flags, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001429 break;
1430#endif
1431
1432 case 'o':
1433 if (alt) {
Dave Hylandsc4029e52014-04-07 11:19:51 -07001434 flags |= (PF_FLAG_SHOW_PREFIX | PF_FLAG_SHOW_OCTAL_LETTER);
Dave Hylands6756a372014-04-02 11:42:39 -07001435 }
Damien George7f9d1d62015-04-09 23:56:15 +01001436 mp_print_mp_int(&print, arg, 8, 'a', flags, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001437 break;
1438
1439 case 'r':
1440 case 's':
1441 {
Damien George0b9ee862015-01-21 19:14:25 +00001442 vstr_t arg_vstr;
Damien George7f9d1d62015-04-09 23:56:15 +01001443 mp_print_t arg_print;
1444 vstr_init_print(&arg_vstr, 16, &arg_print);
1445 mp_obj_print_helper(&arg_print, arg, *str == 'r' ? PRINT_REPR : PRINT_STR);
Damien George0b9ee862015-01-21 19:14:25 +00001446 uint vlen = arg_vstr.len;
Dave Hylands6756a372014-04-02 11:42:39 -07001447 if (prec < 0) {
Damien George50912e72015-01-20 11:55:10 +00001448 prec = vlen;
Dave Hylands6756a372014-04-02 11:42:39 -07001449 }
Damien George50912e72015-01-20 11:55:10 +00001450 if (vlen > (uint)prec) {
1451 vlen = prec;
Dave Hylands6756a372014-04-02 11:42:39 -07001452 }
Damien George7f9d1d62015-04-09 23:56:15 +01001453 mp_print_strn(&print, arg_vstr.buf, vlen, flags, ' ', width);
Damien George0b9ee862015-01-21 19:14:25 +00001454 vstr_clear(&arg_vstr);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001455 break;
1456 }
Dave Hylands6756a372014-04-02 11:42:39 -07001457
Dave Hylands6756a372014-04-02 11:42:39 -07001458 case 'X':
Damien George11de8392014-06-05 18:57:38 +01001459 case 'x':
Damien George7f9d1d62015-04-09 23:56:15 +01001460 mp_print_mp_int(&print, arg, 16, *str - ('X' - 'A'), flags | alt, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001461 break;
Damien Georgedeed0872014-04-06 11:11:15 +01001462
Dave Hylands6756a372014-04-02 11:42:39 -07001463 default:
Damien George1e9a92f2014-11-06 17:36:16 +00001464 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1465 terse_str_format_value_error();
1466 } else {
1467 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
1468 "unsupported format character '%c' (0x%x) at index %d",
1469 *str, *str, str - start_str));
1470 }
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001471 }
1472 }
1473
Damien George963a5a32015-01-16 17:47:07 +00001474 if ((uint)arg_i != n_args) {
Damien Georgeea13f402014-04-05 18:32:08 +01001475 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "not all arguments converted during string formatting"));
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001476 }
1477
Damien George0b9ee862015-01-21 19:14:25 +00001478 return mp_obj_new_str_from_vstr(&mp_type_str, &vstr);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001479}
1480
Paul Sokolovskyf44cc512015-06-26 17:33:21 +03001481// The implementation is optimized, returning the original string if there's
1482// nothing to replace.
Damien Georgeecc88e92014-08-30 00:35:11 +01001483STATIC mp_obj_t str_replace(mp_uint_t n_args, const mp_obj_t *args) {
Damien Georgebe8e99c2014-11-05 16:45:54 +00001484 assert(MP_OBJ_IS_STR_OR_BYTES(args[0]));
xbe480c15a2014-01-30 22:17:30 -08001485
Damien George40f3c022014-07-03 13:25:24 +01001486 mp_int_t max_rep = -1;
xbe480c15a2014-01-30 22:17:30 -08001487 if (n_args == 4) {
Damien Georgeff715422014-04-07 00:39:13 +01001488 max_rep = mp_obj_get_int(args[3]);
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001489 if (max_rep == 0) {
1490 return args[0];
1491 } else if (max_rep < 0) {
Damien Georgeff715422014-04-07 00:39:13 +01001492 max_rep = -1;
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001493 }
xbe480c15a2014-01-30 22:17:30 -08001494 }
Damien George94f68302014-01-31 23:45:12 +00001495
xbe729be9b2014-04-07 14:46:39 -07001496 // if max_rep is still -1 by this point we will need to do all possible replacements
xbe480c15a2014-01-30 22:17:30 -08001497
Damien Georgeff715422014-04-07 00:39:13 +01001498 // check argument types
1499
Damien Georgec55a4d82014-12-24 20:28:30 +00001500 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
1501
1502 if (mp_obj_get_type(args[1]) != self_type) {
Damien Georgeff715422014-04-07 00:39:13 +01001503 bad_implicit_conversion(args[1]);
1504 }
1505
Damien Georgec55a4d82014-12-24 20:28:30 +00001506 if (mp_obj_get_type(args[2]) != self_type) {
Damien Georgeff715422014-04-07 00:39:13 +01001507 bad_implicit_conversion(args[2]);
1508 }
1509
1510 // extract string data
1511
xbe480c15a2014-01-30 22:17:30 -08001512 GET_STR_DATA_LEN(args[0], str, str_len);
1513 GET_STR_DATA_LEN(args[1], old, old_len);
1514 GET_STR_DATA_LEN(args[2], new, new_len);
Damien George94f68302014-01-31 23:45:12 +00001515
1516 // old won't exist in str if it's longer, so nothing to replace
xbe480c15a2014-01-30 22:17:30 -08001517 if (old_len > str_len) {
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001518 return args[0];
xbe480c15a2014-01-30 22:17:30 -08001519 }
1520
Damien George94f68302014-01-31 23:45:12 +00001521 // data for the replaced string
1522 byte *data = NULL;
Damien George05005f62015-01-21 22:48:37 +00001523 vstr_t vstr;
xbe480c15a2014-01-30 22:17:30 -08001524
Damien George94f68302014-01-31 23:45:12 +00001525 // do 2 passes over the string:
1526 // first pass computes the required length of the replaced string
1527 // second pass does the replacements
1528 for (;;) {
Damien George40f3c022014-07-03 13:25:24 +01001529 mp_uint_t replaced_str_index = 0;
1530 mp_uint_t num_replacements_done = 0;
Damien George94f68302014-01-31 23:45:12 +00001531 const byte *old_occurrence;
1532 const byte *offset_ptr = str;
Damien George40f3c022014-07-03 13:25:24 +01001533 mp_uint_t str_len_remain = str_len;
Damien Georgeff715422014-04-07 00:39:13 +01001534 if (old_len == 0) {
1535 // if old_str is empty, copy new_str to start of replaced string
1536 // copy the replacement string
1537 if (data != NULL) {
1538 memcpy(data, new, new_len);
1539 }
1540 replaced_str_index += new_len;
1541 num_replacements_done++;
1542 }
Damien George963a5a32015-01-16 17:47:07 +00001543 while (num_replacements_done != (mp_uint_t)max_rep && str_len_remain > 0 && (old_occurrence = find_subbytes(offset_ptr, str_len_remain, old, old_len, 1)) != NULL) {
Damien Georgeff715422014-04-07 00:39:13 +01001544 if (old_len == 0) {
1545 old_occurrence += 1;
1546 }
Damien George94f68302014-01-31 23:45:12 +00001547 // copy from just after end of last occurrence of to-be-replaced string to right before start of next occurrence
1548 if (data != NULL) {
1549 memcpy(data + replaced_str_index, offset_ptr, old_occurrence - offset_ptr);
1550 }
1551 replaced_str_index += old_occurrence - offset_ptr;
1552 // copy the replacement string
1553 if (data != NULL) {
1554 memcpy(data + replaced_str_index, new, new_len);
1555 }
1556 replaced_str_index += new_len;
1557 offset_ptr = old_occurrence + old_len;
Damien Georgeff715422014-04-07 00:39:13 +01001558 str_len_remain = str + str_len - offset_ptr;
Damien George94f68302014-01-31 23:45:12 +00001559 num_replacements_done++;
Damien George94f68302014-01-31 23:45:12 +00001560 }
1561
1562 // copy from just after end of last occurrence of to-be-replaced string to end of old string
1563 if (data != NULL) {
Damien Georgeff715422014-04-07 00:39:13 +01001564 memcpy(data + replaced_str_index, offset_ptr, str_len_remain);
Damien George94f68302014-01-31 23:45:12 +00001565 }
Damien Georgeff715422014-04-07 00:39:13 +01001566 replaced_str_index += str_len_remain;
Damien George94f68302014-01-31 23:45:12 +00001567
1568 if (data == NULL) {
1569 // first pass
1570 if (num_replacements_done == 0) {
1571 // no substr found, return original string
1572 return args[0];
1573 } else {
1574 // substr found, allocate new string
Damien George05005f62015-01-21 22:48:37 +00001575 vstr_init_len(&vstr, replaced_str_index);
1576 data = (byte*)vstr.buf;
Damien Georgeff715422014-04-07 00:39:13 +01001577 assert(data != NULL);
Damien George94f68302014-01-31 23:45:12 +00001578 }
1579 } else {
1580 // second pass, we are done
1581 break;
1582 }
xbe480c15a2014-01-30 22:17:30 -08001583 }
Damien George94f68302014-01-31 23:45:12 +00001584
Damien George05005f62015-01-21 22:48:37 +00001585 return mp_obj_new_str_from_vstr(self_type, &vstr);
xbe480c15a2014-01-30 22:17:30 -08001586}
1587
Damien Georgeecc88e92014-08-30 00:35:11 +01001588STATIC mp_obj_t str_count(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001589 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
xbe9e1e8cd2014-03-12 22:57:16 -07001590 assert(2 <= n_args && n_args <= 4);
Damien Georgebe8e99c2014-11-05 16:45:54 +00001591 assert(MP_OBJ_IS_STR_OR_BYTES(args[0]));
1592
1593 // check argument type
Damien Georgec55a4d82014-12-24 20:28:30 +00001594 if (mp_obj_get_type(args[1]) != self_type) {
Damien Georgebe8e99c2014-11-05 16:45:54 +00001595 bad_implicit_conversion(args[1]);
1596 }
xbe9e1e8cd2014-03-12 22:57:16 -07001597
1598 GET_STR_DATA_LEN(args[0], haystack, haystack_len);
1599 GET_STR_DATA_LEN(args[1], needle, needle_len);
1600
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001601 const byte *start = haystack;
1602 const byte *end = haystack + haystack_len;
xbe9e1e8cd2014-03-12 22:57:16 -07001603 if (n_args >= 3 && args[2] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001604 start = str_index_to_ptr(self_type, haystack, haystack_len, args[2], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001605 }
1606 if (n_args >= 4 && args[3] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001607 end = str_index_to_ptr(self_type, haystack, haystack_len, args[3], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001608 }
1609
Damien George536dde22014-03-13 22:07:55 +00001610 // if needle_len is zero then we count each gap between characters as an occurrence
1611 if (needle_len == 0) {
Paul Sokolovsky9e215fa2014-06-28 23:14:30 +03001612 return MP_OBJ_NEW_SMALL_INT(unichar_charlen((const char*)start, end - start) + 1);
xbe9e1e8cd2014-03-12 22:57:16 -07001613 }
1614
Damien George536dde22014-03-13 22:07:55 +00001615 // count the occurrences
Damien George40f3c022014-07-03 13:25:24 +01001616 mp_int_t num_occurrences = 0;
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001617 for (const byte *haystack_ptr = start; haystack_ptr + needle_len <= end;) {
1618 if (memcmp(haystack_ptr, needle, needle_len) == 0) {
xbec5d70ba2014-03-13 00:29:15 -07001619 num_occurrences++;
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001620 haystack_ptr += needle_len;
1621 } else {
1622 haystack_ptr = utf8_next_char(haystack_ptr);
xbec5d70ba2014-03-13 00:29:15 -07001623 }
xbe9e1e8cd2014-03-12 22:57:16 -07001624 }
1625
1626 return MP_OBJ_NEW_SMALL_INT(num_occurrences);
1627}
1628
Damien George40f3c022014-07-03 13:25:24 +01001629STATIC mp_obj_t str_partitioner(mp_obj_t self_in, mp_obj_t arg, mp_int_t direction) {
Damien Georgec55a4d82014-12-24 20:28:30 +00001630 assert(MP_OBJ_IS_STR_OR_BYTES(self_in));
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +03001631 mp_obj_type_t *self_type = mp_obj_get_type(self_in);
1632 if (self_type != mp_obj_get_type(arg)) {
Damien Georgec55a4d82014-12-24 20:28:30 +00001633 bad_implicit_conversion(arg);
xbe613a8e32014-03-18 00:06:29 -07001634 }
Damien Georgeb035db32014-03-21 20:39:40 +00001635
xbe613a8e32014-03-18 00:06:29 -07001636 GET_STR_DATA_LEN(self_in, str, str_len);
1637 GET_STR_DATA_LEN(arg, sep, sep_len);
1638
1639 if (sep_len == 0) {
Damien Georgeea13f402014-04-05 18:32:08 +01001640 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
xbe613a8e32014-03-18 00:06:29 -07001641 }
Damien Georgeb035db32014-03-21 20:39:40 +00001642
Damien Georgec55a4d82014-12-24 20:28:30 +00001643 mp_obj_t result[3];
1644 if (self_type == &mp_type_str) {
1645 result[0] = MP_OBJ_NEW_QSTR(MP_QSTR_);
1646 result[1] = MP_OBJ_NEW_QSTR(MP_QSTR_);
1647 result[2] = MP_OBJ_NEW_QSTR(MP_QSTR_);
1648 } else {
1649 result[0] = mp_const_empty_bytes;
1650 result[1] = mp_const_empty_bytes;
1651 result[2] = mp_const_empty_bytes;
1652 }
Damien Georgeb035db32014-03-21 20:39:40 +00001653
1654 if (direction > 0) {
1655 result[0] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001656 } else {
Damien Georgeb035db32014-03-21 20:39:40 +00001657 result[2] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001658 }
xbe613a8e32014-03-18 00:06:29 -07001659
xbe17a5a832014-03-23 23:31:58 -07001660 const byte *position_ptr = find_subbytes(str, str_len, sep, sep_len, direction);
1661 if (position_ptr != NULL) {
Damien George40f3c022014-07-03 13:25:24 +01001662 mp_uint_t position = position_ptr - str;
Damien Georgef600a6a2014-05-25 22:34:34 +01001663 result[0] = mp_obj_new_str_of_type(self_type, str, position);
xbe17a5a832014-03-23 23:31:58 -07001664 result[1] = arg;
Damien Georgef600a6a2014-05-25 22:34:34 +01001665 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 -07001666 }
Damien Georgeb035db32014-03-21 20:39:40 +00001667
xbe0a6894c2014-03-21 01:12:26 -07001668 return mp_obj_new_tuple(3, result);
xbe613a8e32014-03-18 00:06:29 -07001669}
1670
Damien Georgeb035db32014-03-21 20:39:40 +00001671STATIC mp_obj_t str_partition(mp_obj_t self_in, mp_obj_t arg) {
1672 return str_partitioner(self_in, arg, 1);
xbe0a6894c2014-03-21 01:12:26 -07001673}
xbe4504ea82014-03-19 00:46:14 -07001674
Damien Georgeb035db32014-03-21 20:39:40 +00001675STATIC mp_obj_t str_rpartition(mp_obj_t self_in, mp_obj_t arg) {
1676 return str_partitioner(self_in, arg, -1);
xbe4504ea82014-03-19 00:46:14 -07001677}
1678
Paul Sokolovsky69135212014-05-10 19:47:41 +03001679// Supposedly not too critical operations, so optimize for code size
Damien Georgefcc9cf62014-06-01 18:22:09 +01001680STATIC mp_obj_t str_caseconv(unichar (*op)(unichar), mp_obj_t self_in) {
Paul Sokolovsky69135212014-05-10 19:47:41 +03001681 GET_STR_DATA_LEN(self_in, self_data, self_len);
Damien George05005f62015-01-21 22:48:37 +00001682 vstr_t vstr;
1683 vstr_init_len(&vstr, self_len);
1684 byte *data = (byte*)vstr.buf;
Damien George39dc1452014-10-03 19:52:22 +01001685 for (mp_uint_t i = 0; i < self_len; i++) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001686 *data++ = op(*self_data++);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001687 }
Damien George05005f62015-01-21 22:48:37 +00001688 return mp_obj_new_str_from_vstr(mp_obj_get_type(self_in), &vstr);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001689}
1690
1691STATIC mp_obj_t str_lower(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001692 return str_caseconv(unichar_tolower, self_in);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001693}
1694
1695STATIC mp_obj_t str_upper(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001696 return str_caseconv(unichar_toupper, self_in);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001697}
1698
Damien Georgefcc9cf62014-06-01 18:22:09 +01001699STATIC mp_obj_t str_uni_istype(bool (*f)(unichar), mp_obj_t self_in) {
Kim Bautersa3f4b832014-05-31 07:30:03 +01001700 GET_STR_DATA_LEN(self_in, self_data, self_len);
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001701
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001702 if (self_len == 0) {
1703 return mp_const_false; // default to False for empty str
1704 }
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001705
Damien Georgefcc9cf62014-06-01 18:22:09 +01001706 if (f != unichar_isupper && f != unichar_islower) {
Damien George39dc1452014-10-03 19:52:22 +01001707 for (mp_uint_t i = 0; i < self_len; i++) {
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001708 if (!f(*self_data++)) {
1709 return mp_const_false;
1710 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001711 }
1712 } else {
Kim Bautersa3f4b832014-05-31 07:30:03 +01001713 bool contains_alpha = false;
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001714
Damien George39dc1452014-10-03 19:52:22 +01001715 for (mp_uint_t i = 0; i < self_len; i++) { // only check alphanumeric characters
Kim Bautersa3f4b832014-05-31 07:30:03 +01001716 if (unichar_isalpha(*self_data++)) {
1717 contains_alpha = true;
Damien Georgefcc9cf62014-06-01 18:22:09 +01001718 if (!f(*(self_data - 1))) { // -1 because we already incremented above
1719 return mp_const_false;
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001720 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001721 }
1722 }
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001723
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001724 if (!contains_alpha) {
1725 return mp_const_false;
1726 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001727 }
1728
1729 return mp_const_true;
1730}
1731
1732STATIC mp_obj_t str_isspace(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001733 return str_uni_istype(unichar_isspace, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001734}
1735
1736STATIC mp_obj_t str_isalpha(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001737 return str_uni_istype(unichar_isalpha, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001738}
1739
1740STATIC mp_obj_t str_isdigit(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001741 return str_uni_istype(unichar_isdigit, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001742}
1743
1744STATIC mp_obj_t str_isupper(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001745 return str_uni_istype(unichar_isupper, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001746}
1747
1748STATIC mp_obj_t str_islower(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001749 return str_uni_istype(unichar_islower, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001750}
1751
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001752#if MICROPY_CPYTHON_COMPAT
1753// These methods are superfluous in the presense of str() and bytes()
1754// constructors.
1755// TODO: should accept kwargs too
Damien Georgeecc88e92014-08-30 00:35:11 +01001756STATIC mp_obj_t bytes_decode(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001757 mp_obj_t new_args[2];
1758 if (n_args == 1) {
1759 new_args[0] = args[0];
1760 new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
1761 args = new_args;
1762 n_args++;
1763 }
Paul Sokolovsky344e15b2015-01-23 02:15:56 +02001764 return mp_obj_str_make_new((mp_obj_t)&mp_type_str, n_args, 0, args);
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001765}
1766
1767// TODO: should accept kwargs too
Damien Georgeecc88e92014-08-30 00:35:11 +01001768STATIC mp_obj_t str_encode(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001769 mp_obj_t new_args[2];
1770 if (n_args == 1) {
1771 new_args[0] = args[0];
1772 new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
1773 args = new_args;
1774 n_args++;
1775 }
1776 return bytes_make_new(NULL, n_args, 0, args);
1777}
1778#endif
1779
Damien George4d917232014-08-30 14:28:06 +01001780mp_int_t mp_obj_str_get_buffer(mp_obj_t self_in, mp_buffer_info_t *bufinfo, mp_uint_t flags) {
Damien George57a4b4f2014-04-18 22:29:21 +01001781 if (flags == MP_BUFFER_READ) {
Damien George2da98302014-03-09 19:58:18 +00001782 GET_STR_DATA_LEN(self_in, str_data, str_len);
1783 bufinfo->buf = (void*)str_data;
1784 bufinfo->len = str_len;
Damien George57a4b4f2014-04-18 22:29:21 +01001785 bufinfo->typecode = 'b';
Damien George2da98302014-03-09 19:58:18 +00001786 return 0;
1787 } else {
1788 // can't write to a string
1789 bufinfo->buf = NULL;
1790 bufinfo->len = 0;
Damien George57a4b4f2014-04-18 22:29:21 +01001791 bufinfo->typecode = -1;
Damien George2da98302014-03-09 19:58:18 +00001792 return 1;
1793 }
1794}
1795
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001796#if MICROPY_CPYTHON_COMPAT
Paul Sokolovsky97319122014-06-13 22:01:26 +03001797MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(bytes_decode_obj, 1, 3, bytes_decode);
1798MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_encode_obj, 1, 3, str_encode);
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001799#endif
Paul Sokolovsky97319122014-06-13 22:01:26 +03001800MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_find_obj, 2, 4, str_find);
1801MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rfind_obj, 2, 4, str_rfind);
1802MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_index_obj, 2, 4, str_index);
1803MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rindex_obj, 2, 4, str_rindex);
1804MP_DEFINE_CONST_FUN_OBJ_2(str_join_obj, str_join);
Paul Sokolovsky87051712015-03-23 22:15:12 +02001805MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_split_obj, 1, 3, mp_obj_str_split);
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +03001806#if MICROPY_PY_BUILTINS_STR_SPLITLINES
1807MP_DEFINE_CONST_FUN_OBJ_KW(str_splitlines_obj, 1, str_splitlines);
1808#endif
Paul Sokolovsky97319122014-06-13 22:01:26 +03001809MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rsplit_obj, 1, 3, str_rsplit);
1810MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_startswith_obj, 2, 3, str_startswith);
1811MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_endswith_obj, 2, 3, str_endswith);
1812MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_strip_obj, 1, 2, str_strip);
1813MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_lstrip_obj, 1, 2, str_lstrip);
1814MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rstrip_obj, 1, 2, str_rstrip);
Paul Sokolovskyc1144962015-01-04 00:14:13 +02001815MP_DEFINE_CONST_FUN_OBJ_KW(str_format_obj, 1, mp_obj_str_format);
Paul Sokolovsky97319122014-06-13 22:01:26 +03001816MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_replace_obj, 3, 4, str_replace);
1817MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_count_obj, 2, 4, str_count);
1818MP_DEFINE_CONST_FUN_OBJ_2(str_partition_obj, str_partition);
1819MP_DEFINE_CONST_FUN_OBJ_2(str_rpartition_obj, str_rpartition);
1820MP_DEFINE_CONST_FUN_OBJ_1(str_lower_obj, str_lower);
1821MP_DEFINE_CONST_FUN_OBJ_1(str_upper_obj, str_upper);
1822MP_DEFINE_CONST_FUN_OBJ_1(str_isspace_obj, str_isspace);
1823MP_DEFINE_CONST_FUN_OBJ_1(str_isalpha_obj, str_isalpha);
1824MP_DEFINE_CONST_FUN_OBJ_1(str_isdigit_obj, str_isdigit);
1825MP_DEFINE_CONST_FUN_OBJ_1(str_isupper_obj, str_isupper);
1826MP_DEFINE_CONST_FUN_OBJ_1(str_islower_obj, str_islower);
Damiend99b0522013-12-21 18:17:45 +00001827
Paul Sokolovsky6113eb22015-01-23 02:05:58 +02001828STATIC const mp_map_elem_t str8_locals_dict_table[] = {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001829#if MICROPY_CPYTHON_COMPAT
1830 { MP_OBJ_NEW_QSTR(MP_QSTR_decode), (mp_obj_t)&bytes_decode_obj },
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001831 #if !MICROPY_PY_BUILTINS_STR_UNICODE
1832 // If we have separate unicode type, then here we have methods only
1833 // for bytes type, and it should not have encode() methods. Otherwise,
1834 // we have non-compliant-but-practical bytestring type, which shares
1835 // method table with bytes, so they both have encode() and decode()
1836 // methods (which should do type checking at runtime).
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001837 { MP_OBJ_NEW_QSTR(MP_QSTR_encode), (mp_obj_t)&str_encode_obj },
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001838 #endif
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001839#endif
Damien George9b196cd2014-03-26 21:47:19 +00001840 { MP_OBJ_NEW_QSTR(MP_QSTR_find), (mp_obj_t)&str_find_obj },
1841 { MP_OBJ_NEW_QSTR(MP_QSTR_rfind), (mp_obj_t)&str_rfind_obj },
xbe3d9a39e2014-04-08 11:42:19 -07001842 { MP_OBJ_NEW_QSTR(MP_QSTR_index), (mp_obj_t)&str_index_obj },
1843 { MP_OBJ_NEW_QSTR(MP_QSTR_rindex), (mp_obj_t)&str_rindex_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001844 { MP_OBJ_NEW_QSTR(MP_QSTR_join), (mp_obj_t)&str_join_obj },
1845 { MP_OBJ_NEW_QSTR(MP_QSTR_split), (mp_obj_t)&str_split_obj },
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +03001846 #if MICROPY_PY_BUILTINS_STR_SPLITLINES
1847 { MP_OBJ_NEW_QSTR(MP_QSTR_splitlines), (mp_obj_t)&str_splitlines_obj },
1848 #endif
Paul Sokolovsky2a273652014-05-13 08:07:08 +03001849 { MP_OBJ_NEW_QSTR(MP_QSTR_rsplit), (mp_obj_t)&str_rsplit_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001850 { MP_OBJ_NEW_QSTR(MP_QSTR_startswith), (mp_obj_t)&str_startswith_obj },
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +03001851 { MP_OBJ_NEW_QSTR(MP_QSTR_endswith), (mp_obj_t)&str_endswith_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001852 { MP_OBJ_NEW_QSTR(MP_QSTR_strip), (mp_obj_t)&str_strip_obj },
Paul Sokolovsky88107842014-04-26 06:20:08 +03001853 { MP_OBJ_NEW_QSTR(MP_QSTR_lstrip), (mp_obj_t)&str_lstrip_obj },
1854 { MP_OBJ_NEW_QSTR(MP_QSTR_rstrip), (mp_obj_t)&str_rstrip_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001855 { MP_OBJ_NEW_QSTR(MP_QSTR_format), (mp_obj_t)&str_format_obj },
1856 { MP_OBJ_NEW_QSTR(MP_QSTR_replace), (mp_obj_t)&str_replace_obj },
1857 { MP_OBJ_NEW_QSTR(MP_QSTR_count), (mp_obj_t)&str_count_obj },
1858 { MP_OBJ_NEW_QSTR(MP_QSTR_partition), (mp_obj_t)&str_partition_obj },
1859 { MP_OBJ_NEW_QSTR(MP_QSTR_rpartition), (mp_obj_t)&str_rpartition_obj },
Paul Sokolovsky69135212014-05-10 19:47:41 +03001860 { MP_OBJ_NEW_QSTR(MP_QSTR_lower), (mp_obj_t)&str_lower_obj },
1861 { MP_OBJ_NEW_QSTR(MP_QSTR_upper), (mp_obj_t)&str_upper_obj },
Kim Bautersa3f4b832014-05-31 07:30:03 +01001862 { MP_OBJ_NEW_QSTR(MP_QSTR_isspace), (mp_obj_t)&str_isspace_obj },
1863 { MP_OBJ_NEW_QSTR(MP_QSTR_isalpha), (mp_obj_t)&str_isalpha_obj },
1864 { MP_OBJ_NEW_QSTR(MP_QSTR_isdigit), (mp_obj_t)&str_isdigit_obj },
1865 { MP_OBJ_NEW_QSTR(MP_QSTR_isupper), (mp_obj_t)&str_isupper_obj },
1866 { MP_OBJ_NEW_QSTR(MP_QSTR_islower), (mp_obj_t)&str_islower_obj },
ian-v7a16fad2014-01-06 09:52:29 -08001867};
Damien George97209d32014-01-07 15:58:30 +00001868
Paul Sokolovsky6113eb22015-01-23 02:05:58 +02001869STATIC MP_DEFINE_CONST_DICT(str8_locals_dict, str8_locals_dict_table);
Damien George9b196cd2014-03-26 21:47:19 +00001870
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001871#if !MICROPY_PY_BUILTINS_STR_UNICODE
Damien George44e7cbf2015-05-17 16:44:24 +01001872STATIC mp_obj_t mp_obj_new_str_iterator(mp_obj_t str);
1873
Damien George3e1a5c12014-03-29 13:43:38 +00001874const mp_obj_type_t mp_type_str = {
Damien Georgec5966122014-02-15 16:10:44 +00001875 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001876 .name = MP_QSTR_str,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001877 .print = str_print,
Paul Sokolovsky344e15b2015-01-23 02:15:56 +02001878 .make_new = mp_obj_str_make_new,
Damien Georgee04a44e2014-06-28 10:27:23 +01001879 .binary_op = mp_obj_str_binary_op,
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +03001880 .subscr = bytes_subscr,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001881 .getiter = mp_obj_new_str_iterator,
Damien Georgee04a44e2014-06-28 10:27:23 +01001882 .buffer_p = { .get_buffer = mp_obj_str_get_buffer },
Paul Sokolovsky6113eb22015-01-23 02:05:58 +02001883 .locals_dict = (mp_obj_t)&str8_locals_dict,
Damiend99b0522013-12-21 18:17:45 +00001884};
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001885#endif
Damiend99b0522013-12-21 18:17:45 +00001886
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001887// Reuses most of methods from str
Damien George3e1a5c12014-03-29 13:43:38 +00001888const mp_obj_type_t mp_type_bytes = {
Damien Georgec5966122014-02-15 16:10:44 +00001889 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001890 .name = MP_QSTR_bytes,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001891 .print = str_print,
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001892 .make_new = bytes_make_new,
Damien Georgee04a44e2014-06-28 10:27:23 +01001893 .binary_op = mp_obj_str_binary_op,
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +03001894 .subscr = bytes_subscr,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001895 .getiter = mp_obj_new_bytes_iterator,
Damien Georgee04a44e2014-06-28 10:27:23 +01001896 .buffer_p = { .get_buffer = mp_obj_str_get_buffer },
Paul Sokolovsky6113eb22015-01-23 02:05:58 +02001897 .locals_dict = (mp_obj_t)&str8_locals_dict,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001898};
1899
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001900// the zero-length bytes
Damien George20f59e12014-10-11 17:56:43 +01001901const mp_obj_str_t mp_const_empty_bytes_obj = {{&mp_type_bytes}, 0, 0, NULL};
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001902
Damien George77089be2015-01-21 23:08:36 +00001903// Create a str/bytes object using the given data. New memory is allocated and
1904// the data is copied across.
Damien George4abff752014-08-30 14:59:21 +01001905mp_obj_t mp_obj_new_str_of_type(const mp_obj_type_t *type, const byte* data, mp_uint_t len) {
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001906 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001907 o->base.type = type;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001908 o->len = len;
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001909 if (data) {
1910 o->hash = qstr_compute_hash(data, len);
1911 byte *p = m_new(byte, len + 1);
1912 o->data = p;
1913 memcpy(p, data, len * sizeof(byte));
1914 p[len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
1915 }
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001916 return o;
1917}
1918
Damien George77089be2015-01-21 23:08:36 +00001919// Create a str/bytes object from the given vstr. The vstr buffer is resized to
1920// the exact length required and then reused for the str/bytes object. The vstr
1921// is cleared and can safely be passed to vstr_free if it was heap allocated.
Damien George0b9ee862015-01-21 19:14:25 +00001922mp_obj_t mp_obj_new_str_from_vstr(const mp_obj_type_t *type, vstr_t *vstr) {
1923 // if not a bytes object, look if a qstr with this data already exists
1924 if (type == &mp_type_str) {
1925 qstr q = qstr_find_strn(vstr->buf, vstr->len);
1926 if (q != MP_QSTR_NULL) {
1927 vstr_clear(vstr);
1928 vstr->alloc = 0;
1929 return MP_OBJ_NEW_QSTR(q);
1930 }
1931 }
1932
1933 // make a new str/bytes object
1934 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
1935 o->base.type = type;
1936 o->len = vstr->len;
1937 o->hash = qstr_compute_hash((byte*)vstr->buf, vstr->len);
Dave Hylands9f76dcd2015-05-18 13:25:36 -07001938 if (vstr->len + 1 == vstr->alloc) {
1939 o->data = (byte*)vstr->buf;
1940 } else {
1941 o->data = (byte*)m_renew(char, vstr->buf, vstr->alloc, vstr->len + 1);
1942 }
Damien George0d3cb672015-01-28 23:43:01 +00001943 ((byte*)o->data)[o->len] = '\0'; // add null byte
Damien George0b9ee862015-01-21 19:14:25 +00001944 vstr->buf = NULL;
1945 vstr->alloc = 0;
1946 return o;
1947}
1948
Damien Georged182b982014-08-30 14:19:41 +01001949mp_obj_t mp_obj_new_str(const char* data, mp_uint_t len, bool make_qstr_if_not_already) {
Damien Georgef600a6a2014-05-25 22:34:34 +01001950 if (make_qstr_if_not_already) {
1951 // use existing, or make a new qstr
Damien George2617eeb2014-05-25 22:27:57 +01001952 return MP_OBJ_NEW_QSTR(qstr_from_strn(data, len));
Damien George5fa93b62014-01-22 14:35:10 +00001953 } else {
Damien Georgef600a6a2014-05-25 22:34:34 +01001954 qstr q = qstr_find_strn(data, len);
1955 if (q != MP_QSTR_NULL) {
1956 // qstr with this data already exists
1957 return MP_OBJ_NEW_QSTR(q);
1958 } else {
1959 // no existing qstr, don't make one
1960 return mp_obj_new_str_of_type(&mp_type_str, (const byte*)data, len);
1961 }
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02001962 }
Damien George5fa93b62014-01-22 14:35:10 +00001963}
1964
Paul Sokolovskyb4efac12014-06-08 01:13:35 +03001965mp_obj_t mp_obj_str_intern(mp_obj_t str) {
1966 GET_STR_DATA_LEN(str, data, len);
1967 return MP_OBJ_NEW_QSTR(qstr_from_strn((const char*)data, len));
1968}
1969
Damien Georged182b982014-08-30 14:19:41 +01001970mp_obj_t mp_obj_new_bytes(const byte* data, mp_uint_t len) {
Damien Georgef600a6a2014-05-25 22:34:34 +01001971 return mp_obj_new_str_of_type(&mp_type_bytes, data, len);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001972}
1973
Damien George5fa93b62014-01-22 14:35:10 +00001974bool mp_obj_str_equal(mp_obj_t s1, mp_obj_t s2) {
1975 if (MP_OBJ_IS_QSTR(s1) && MP_OBJ_IS_QSTR(s2)) {
1976 return s1 == s2;
1977 } else {
1978 GET_STR_HASH(s1, h1);
1979 GET_STR_HASH(s2, h2);
Paul Sokolovsky59e269c2014-04-14 01:43:01 +03001980 // If any of hashes is 0, it means it's not valid
1981 if (h1 != 0 && h2 != 0 && h1 != h2) {
Damien George5fa93b62014-01-22 14:35:10 +00001982 return false;
1983 }
1984 GET_STR_DATA_LEN(s1, d1, l1);
1985 GET_STR_DATA_LEN(s2, d2, l2);
1986 if (l1 != l2) {
1987 return false;
1988 }
Damien George1e708fe2014-01-23 18:27:51 +00001989 return memcmp(d1, d2, l1) == 0;
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02001990 }
Damien George5fa93b62014-01-22 14:35:10 +00001991}
1992
Damien Georgedeed0872014-04-06 11:11:15 +01001993STATIC void bad_implicit_conversion(mp_obj_t self_in) {
Damien George1e9a92f2014-11-06 17:36:16 +00001994 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1995 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
1996 "can't convert to str implicitly"));
1997 } else {
1998 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
1999 "can't convert '%s' object to str implicitly",
2000 mp_obj_get_type_str(self_in)));
2001 }
Damien Georgeb829b5c2014-01-25 13:51:19 +00002002}
2003
Damien Georgeb829b5c2014-01-25 13:51:19 +00002004// use this if you will anyway convert the string to a qstr
2005// will be more efficient for the case where it's already a qstr
2006qstr mp_obj_str_get_qstr(mp_obj_t self_in) {
2007 if (MP_OBJ_IS_QSTR(self_in)) {
2008 return MP_OBJ_QSTR_VALUE(self_in);
Damien George3e1a5c12014-03-29 13:43:38 +00002009 } else if (MP_OBJ_IS_TYPE(self_in, &mp_type_str)) {
Damien Georgeb829b5c2014-01-25 13:51:19 +00002010 mp_obj_str_t *self = self_in;
2011 return qstr_from_strn((char*)self->data, self->len);
2012 } else {
2013 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00002014 }
2015}
2016
2017// only use this function if you need the str data to be zero terminated
2018// at the moment all strings are zero terminated to help with C ASCIIZ compatibility
2019const char *mp_obj_str_get_str(mp_obj_t self_in) {
Paul Sokolovsky31619cc2014-10-30 16:36:41 +02002020 if (MP_OBJ_IS_STR_OR_BYTES(self_in)) {
Damien George5fa93b62014-01-22 14:35:10 +00002021 GET_STR_DATA_LEN(self_in, s, l);
2022 (void)l; // len unused
2023 return (const char*)s;
2024 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00002025 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00002026 }
2027}
2028
Damien Georged182b982014-08-30 14:19:41 +01002029const char *mp_obj_str_get_data(mp_obj_t self_in, mp_uint_t *len) {
Dave Hylandsb7f7c652014-08-26 12:44:46 -07002030 if (MP_OBJ_IS_STR_OR_BYTES(self_in)) {
Damien George5fa93b62014-01-22 14:35:10 +00002031 GET_STR_DATA_LEN(self_in, s, l);
2032 *len = l;
Damien George698ec212014-02-08 18:17:23 +00002033 return (const char*)s;
Damien George5fa93b62014-01-22 14:35:10 +00002034 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00002035 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00002036 }
Damiend99b0522013-12-21 18:17:45 +00002037}
xyb8cfc9f02014-01-05 18:47:51 +08002038
2039/******************************************************************************/
2040/* str iterator */
2041
Damien George44e7cbf2015-05-17 16:44:24 +01002042typedef struct _mp_obj_str8_it_t {
xyb8cfc9f02014-01-05 18:47:51 +08002043 mp_obj_base_t base;
Damien George5fa93b62014-01-22 14:35:10 +00002044 mp_obj_t str;
Damien George40f3c022014-07-03 13:25:24 +01002045 mp_uint_t cur;
Damien George44e7cbf2015-05-17 16:44:24 +01002046} mp_obj_str8_it_t;
xyb8cfc9f02014-01-05 18:47:51 +08002047
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03002048#if !MICROPY_PY_BUILTINS_STR_UNICODE
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02002049STATIC mp_obj_t str_it_iternext(mp_obj_t self_in) {
Damien George44e7cbf2015-05-17 16:44:24 +01002050 mp_obj_str8_it_t *self = self_in;
Damien George5fa93b62014-01-22 14:35:10 +00002051 GET_STR_DATA_LEN(self->str, str, len);
2052 if (self->cur < len) {
Damien George2617eeb2014-05-25 22:27:57 +01002053 mp_obj_t o_out = mp_obj_new_str((const char*)str + self->cur, 1, true);
xyb8cfc9f02014-01-05 18:47:51 +08002054 self->cur += 1;
2055 return o_out;
2056 } else {
Damien Georgeea8d06c2014-04-17 23:19:36 +01002057 return MP_OBJ_STOP_ITERATION;
xyb8cfc9f02014-01-05 18:47:51 +08002058 }
2059}
2060
Damien George3e1a5c12014-03-29 13:43:38 +00002061STATIC const mp_obj_type_t mp_type_str_it = {
Damien Georgec5966122014-02-15 16:10:44 +00002062 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00002063 .name = MP_QSTR_iterator,
Paul Sokolovskyf7eaf602014-03-30 22:00:12 +03002064 .getiter = mp_identity,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02002065 .iternext = str_it_iternext,
xyb8cfc9f02014-01-05 18:47:51 +08002066};
2067
Damien George44e7cbf2015-05-17 16:44:24 +01002068STATIC mp_obj_t mp_obj_new_str_iterator(mp_obj_t str) {
2069 mp_obj_str8_it_t *o = m_new_obj(mp_obj_str8_it_t);
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03002070 o->base.type = &mp_type_str_it;
2071 o->str = str;
2072 o->cur = 0;
2073 return o;
2074}
2075#endif
2076
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02002077STATIC mp_obj_t bytes_it_iternext(mp_obj_t self_in) {
Damien George44e7cbf2015-05-17 16:44:24 +01002078 mp_obj_str8_it_t *self = self_in;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002079 GET_STR_DATA_LEN(self->str, str, len);
2080 if (self->cur < len) {
Damien Georgebb4c6f32014-07-31 10:49:14 +01002081 mp_obj_t o_out = MP_OBJ_NEW_SMALL_INT(str[self->cur]);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002082 self->cur += 1;
2083 return o_out;
2084 } else {
Damien Georgeea8d06c2014-04-17 23:19:36 +01002085 return MP_OBJ_STOP_ITERATION;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002086 }
2087}
2088
Damien George3e1a5c12014-03-29 13:43:38 +00002089STATIC const mp_obj_type_t mp_type_bytes_it = {
Damien Georgec5966122014-02-15 16:10:44 +00002090 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00002091 .name = MP_QSTR_iterator,
Paul Sokolovskyf7eaf602014-03-30 22:00:12 +03002092 .getiter = mp_identity,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002093 .iternext = bytes_it_iternext,
2094};
2095
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002096mp_obj_t mp_obj_new_bytes_iterator(mp_obj_t str) {
Damien George44e7cbf2015-05-17 16:44:24 +01002097 mp_obj_str8_it_t *o = m_new_obj(mp_obj_str8_it_t);
Damien George3e1a5c12014-03-29 13:43:38 +00002098 o->base.type = &mp_type_bytes_it;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002099 o->str = str;
2100 o->cur = 0;
xyb8cfc9f02014-01-05 18:47:51 +08002101 return o;
2102}