blob: 519ff464d644ce2f599606c0ee45d5e335ebe82a [file] [log] [blame]
xbeefe34222014-03-16 00:14:26 -07001#include <stdbool.h>
Damiend99b0522013-12-21 18:17:45 +00002#include <string.h>
3#include <assert.h>
4
5#include "nlr.h"
6#include "misc.h"
7#include "mpconfig.h"
Damien George55baff42014-01-21 21:40:13 +00008#include "qstr.h"
Damiend99b0522013-12-21 18:17:45 +00009#include "obj.h"
10#include "runtime0.h"
11#include "runtime.h"
Dave Hylandsbaf6f142014-03-30 21:06:50 -070012#include "pfenv.h"
Damiend99b0522013-12-21 18:17:45 +000013
14typedef struct _mp_obj_str_t {
15 mp_obj_base_t base;
Damien George5fa93b62014-01-22 14:35:10 +000016 machine_uint_t hash : 16; // XXX here we assume the hash size is 16 bits (it is at the moment; see qstr.c)
17 machine_uint_t len : 16; // len == number of bytes used in data, alloc = len + 1 because (at the moment) we also append a null byte
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +020018 const byte *data;
Damiend99b0522013-12-21 18:17:45 +000019} mp_obj_str_t;
20
Paul Sokolovsky4db727a2014-03-31 21:18:28 +030021STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, uint n_args, const mp_obj_t *args);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +020022const mp_obj_t mp_const_empty_bytes;
23
Damien George5fa93b62014-01-22 14:35:10 +000024// use this macro to extract the string hash
25#define GET_STR_HASH(str_obj_in, str_hash) uint str_hash; if (MP_OBJ_IS_QSTR(str_obj_in)) { str_hash = qstr_hash(MP_OBJ_QSTR_VALUE(str_obj_in)); } else { str_hash = ((mp_obj_str_t*)str_obj_in)->hash; }
26
27// use this macro to extract the string length
28#define GET_STR_LEN(str_obj_in, str_len) uint str_len; if (MP_OBJ_IS_QSTR(str_obj_in)) { str_len = qstr_len(MP_OBJ_QSTR_VALUE(str_obj_in)); } else { str_len = ((mp_obj_str_t*)str_obj_in)->len; }
29
30// use this macro to extract the string data and length
31#define GET_STR_DATA_LEN(str_obj_in, str_data, str_len) const byte *str_data; uint str_len; if (MP_OBJ_IS_QSTR(str_obj_in)) { str_data = qstr_data(MP_OBJ_QSTR_VALUE(str_obj_in), &str_len); } else { str_len = ((mp_obj_str_t*)str_obj_in)->len; str_data = ((mp_obj_str_t*)str_obj_in)->data; }
32
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +020033STATIC mp_obj_t mp_obj_new_str_iterator(mp_obj_t str);
34STATIC mp_obj_t mp_obj_new_bytes_iterator(mp_obj_t str);
Paul Sokolovskybe020c22014-03-21 11:39:01 +020035STATIC mp_obj_t str_new(const mp_obj_type_t *type, const byte* data, uint len);
Damien Georgedeed0872014-04-06 11:11:15 +010036STATIC void bad_implicit_conversion(mp_obj_t self_in) __attribute__((noreturn));
xyb8cfc9f02014-01-05 18:47:51 +080037
38/******************************************************************************/
39/* str */
40
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020041void mp_str_print_quoted(void (*print)(void *env, const char *fmt, ...), void *env, const byte *str_data, uint str_len) {
42 // this escapes characters, but it will be very slow to print (calling print many times)
43 bool has_single_quote = false;
44 bool has_double_quote = false;
45 for (const byte *s = str_data, *top = str_data + str_len; (!has_single_quote || !has_double_quote) && s < top; s++) {
46 if (*s == '\'') {
47 has_single_quote = true;
48 } else if (*s == '"') {
49 has_double_quote = true;
50 }
51 }
52 int quote_char = '\'';
53 if (has_single_quote && !has_double_quote) {
54 quote_char = '"';
55 }
56 print(env, "%c", quote_char);
57 for (const byte *s = str_data, *top = str_data + str_len; s < top; s++) {
58 if (*s == quote_char) {
59 print(env, "\\%c", quote_char);
60 } else if (*s == '\\') {
61 print(env, "\\\\");
62 } else if (32 <= *s && *s <= 126) {
63 print(env, "%c", *s);
64 } else if (*s == '\n') {
65 print(env, "\\n");
Andrew Scheller12968fb2014-04-08 02:42:50 +010066 } else if (*s == '\r') {
67 print(env, "\\r");
68 } else if (*s == '\t') {
69 print(env, "\\t");
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020070 } else {
71 print(env, "\\x%02x", *s);
72 }
73 }
74 print(env, "%c", quote_char);
75}
76
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +020077STATIC void str_print(void (*print)(void *env, const char *fmt, ...), void *env, mp_obj_t self_in, mp_print_kind_t kind) {
Damien George5fa93b62014-01-22 14:35:10 +000078 GET_STR_DATA_LEN(self_in, str_data, str_len);
Damien George3e1a5c12014-03-29 13:43:38 +000079 bool is_bytes = MP_OBJ_IS_TYPE(self_in, &mp_type_bytes);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +020080 if (kind == PRINT_STR && !is_bytes) {
Damien George5fa93b62014-01-22 14:35:10 +000081 print(env, "%.*s", str_len, str_data);
Paul Sokolovsky76d982e2014-01-13 19:19:16 +020082 } else {
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +020083 if (is_bytes) {
84 print(env, "b");
85 }
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020086 mp_str_print_quoted(print, env, str_data, str_len);
Paul Sokolovsky76d982e2014-01-13 19:19:16 +020087 }
Damiend99b0522013-12-21 18:17:45 +000088}
89
Paul Sokolovskybe020c22014-03-21 11:39:01 +020090STATIC mp_obj_t str_make_new(mp_obj_t type_in, uint n_args, uint n_kw, const mp_obj_t *args) {
91 switch (n_args) {
92 case 0:
93 return MP_OBJ_NEW_QSTR(MP_QSTR_);
94
95 case 1:
96 {
97 vstr_t *vstr = vstr_new();
98 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, vstr, args[0], PRINT_STR);
99 mp_obj_t s = mp_obj_new_str((byte*)vstr->buf, vstr->len, false);
100 vstr_free(vstr);
101 return s;
102 }
103
104 case 2:
105 case 3:
106 {
107 // TODO: validate 2nd/3rd args
Damien George3e1a5c12014-03-29 13:43:38 +0000108 if (!MP_OBJ_IS_TYPE(args[0], &mp_type_bytes)) {
Damien Georgeea13f402014-04-05 18:32:08 +0100109 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "bytes expected"));
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200110 }
111 GET_STR_DATA_LEN(args[0], str_data, str_len);
112 GET_STR_HASH(args[0], str_hash);
Damien George3e1a5c12014-03-29 13:43:38 +0000113 mp_obj_str_t *o = str_new(&mp_type_str, NULL, str_len);
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200114 o->data = str_data;
115 o->hash = str_hash;
116 return o;
117 }
118
119 default:
Damien Georgeea13f402014-04-05 18:32:08 +0100120 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "str takes at most 3 arguments"));
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200121 }
122}
123
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200124STATIC mp_obj_t bytes_make_new(mp_obj_t type_in, uint n_args, uint n_kw, const mp_obj_t *args) {
125 if (n_args == 0) {
126 return mp_const_empty_bytes;
127 }
128
129 if (MP_OBJ_IS_STR(args[0])) {
130 if (n_args < 2 || n_args > 3) {
131 goto wrong_args;
132 }
133 GET_STR_DATA_LEN(args[0], str_data, str_len);
134 GET_STR_HASH(args[0], str_hash);
Damien George3e1a5c12014-03-29 13:43:38 +0000135 mp_obj_str_t *o = str_new(&mp_type_bytes, NULL, str_len);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200136 o->data = str_data;
137 o->hash = str_hash;
138 return o;
139 }
140
141 if (n_args > 1) {
142 goto wrong_args;
143 }
144
145 if (MP_OBJ_IS_SMALL_INT(args[0])) {
146 uint len = MP_OBJ_SMALL_INT_VALUE(args[0]);
147 byte *data;
148
Damien George3e1a5c12014-03-29 13:43:38 +0000149 mp_obj_t o = mp_obj_str_builder_start(&mp_type_bytes, len, &data);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200150 memset(data, 0, len);
151 return mp_obj_str_builder_end(o);
152 }
153
154 int len;
155 byte *data;
156 vstr_t *vstr = NULL;
157 mp_obj_t o = NULL;
158 // Try to create array of exact len if initializer len is known
159 mp_obj_t len_in = mp_obj_len_maybe(args[0]);
160 if (len_in == MP_OBJ_NULL) {
161 len = -1;
162 vstr = vstr_new();
163 } else {
164 len = MP_OBJ_SMALL_INT_VALUE(len_in);
Damien George3e1a5c12014-03-29 13:43:38 +0000165 o = mp_obj_str_builder_start(&mp_type_bytes, len, &data);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200166 }
167
Damien Georged17926d2014-03-30 13:35:08 +0100168 mp_obj_t iterable = mp_getiter(args[0]);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200169 mp_obj_t item;
Damien Georged17926d2014-03-30 13:35:08 +0100170 while ((item = mp_iternext(iterable)) != MP_OBJ_NULL) {
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200171 if (len == -1) {
172 vstr_add_char(vstr, MP_OBJ_SMALL_INT_VALUE(item));
173 } else {
174 *data++ = MP_OBJ_SMALL_INT_VALUE(item);
175 }
176 }
177
178 if (len == -1) {
179 vstr_shrink(vstr);
180 // TODO: Optimize, borrow buffer from vstr
181 len = vstr_len(vstr);
Damien George3e1a5c12014-03-29 13:43:38 +0000182 o = mp_obj_str_builder_start(&mp_type_bytes, len, &data);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200183 memcpy(data, vstr_str(vstr), len);
184 vstr_free(vstr);
185 }
186
187 return mp_obj_str_builder_end(o);
188
189wrong_args:
Damien Georgeea13f402014-04-05 18:32:08 +0100190 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "wrong number of arguments"));
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200191}
192
Damien George55baff42014-01-21 21:40:13 +0000193// like strstr but with specified length and allows \0 bytes
194// TODO replace with something more efficient/standard
xbe17a5a832014-03-23 23:31:58 -0700195STATIC const byte *find_subbytes(const byte *haystack, machine_uint_t hlen, const byte *needle, machine_uint_t nlen, machine_int_t direction) {
Damien George55baff42014-01-21 21:40:13 +0000196 if (hlen >= nlen) {
xbe17a5a832014-03-23 23:31:58 -0700197 machine_uint_t str_index, str_index_end;
198 if (direction > 0) {
199 str_index = 0;
200 str_index_end = hlen - nlen;
201 } else {
202 str_index = hlen - nlen;
203 str_index_end = 0;
204 }
205 for (;;) {
206 if (memcmp(&haystack[str_index], needle, nlen) == 0) {
207 //found
208 return haystack + str_index;
Damien George55baff42014-01-21 21:40:13 +0000209 }
xbe17a5a832014-03-23 23:31:58 -0700210 if (str_index == str_index_end) {
211 //not found
212 break;
Damien George55baff42014-01-21 21:40:13 +0000213 }
xbe17a5a832014-03-23 23:31:58 -0700214 str_index += direction;
Damien George55baff42014-01-21 21:40:13 +0000215 }
216 }
217 return NULL;
218}
219
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200220STATIC mp_obj_t str_binary_op(int op, mp_obj_t lhs_in, mp_obj_t rhs_in) {
Damien George5fa93b62014-01-22 14:35:10 +0000221 GET_STR_DATA_LEN(lhs_in, lhs_data, lhs_len);
Damiend99b0522013-12-21 18:17:45 +0000222 switch (op) {
Damien Georged17926d2014-03-30 13:35:08 +0100223 case MP_BINARY_OP_SUBSCR:
Damien Georgeb5fbd0b2014-04-09 19:55:33 +0100224 if (mp_obj_is_integer(rhs_in)) {
xbe9e1e8cd2014-03-12 22:57:16 -0700225 uint index = mp_get_index(mp_obj_get_type(lhs_in), lhs_len, rhs_in, false);
Damien George3e1a5c12014-03-29 13:43:38 +0000226 if (MP_OBJ_IS_TYPE(lhs_in, &mp_type_bytes)) {
Damien George7c9c6672014-01-25 00:17:36 +0000227 return MP_OBJ_NEW_SMALL_INT((mp_small_int_t)lhs_data[index]);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +0200228 } else {
229 return mp_obj_new_str(lhs_data + index, 1, true);
230 }
Paul Sokolovskye606cb62014-01-04 01:34:23 +0200231#if MICROPY_ENABLE_SLICE
Damien George3e1a5c12014-03-29 13:43:38 +0000232 } else if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_slice)) {
Paul Sokolovsky7364af22014-02-02 02:38:22 +0200233 machine_uint_t start, stop;
Paul Sokolovskyea2509d2014-02-02 08:57:05 +0200234 if (!m_seq_get_fast_slice_indexes(lhs_len, rhs_in, &start, &stop)) {
235 assert(0);
236 }
Damien George5fa93b62014-01-22 14:35:10 +0000237 return mp_obj_new_str(lhs_data + start, stop - start, false);
Paul Sokolovskye606cb62014-01-04 01:34:23 +0200238#endif
Paul Sokolovsky31ba60f2014-01-03 02:51:16 +0200239 } else {
Paul Sokolovskyf8b9d3c2014-01-04 01:38:26 +0200240 // Message doesn't match CPython, but we don't have so much bytes as they
241 // to spend them on verbose wording
Damien Georgeea13f402014-04-05 18:32:08 +0100242 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "index must be int"));
Paul Sokolovsky31ba60f2014-01-03 02:51:16 +0200243 }
Damiend99b0522013-12-21 18:17:45 +0000244
Damien Georged17926d2014-03-30 13:35:08 +0100245 case MP_BINARY_OP_ADD:
246 case MP_BINARY_OP_INPLACE_ADD:
Damien George5fa93b62014-01-22 14:35:10 +0000247 if (MP_OBJ_IS_STR(rhs_in)) {
Damiend99b0522013-12-21 18:17:45 +0000248 // add 2 strings
Damien George5fa93b62014-01-22 14:35:10 +0000249
250 GET_STR_DATA_LEN(rhs_in, rhs_data, rhs_len);
Damien George55baff42014-01-21 21:40:13 +0000251 int alloc_len = lhs_len + rhs_len;
Damien George5fa93b62014-01-22 14:35:10 +0000252
253 /* code for making qstr
Damien George55baff42014-01-21 21:40:13 +0000254 byte *q_ptr;
255 byte *val = qstr_build_start(alloc_len, &q_ptr);
256 memcpy(val, lhs_data, lhs_len);
257 memcpy(val + lhs_len, rhs_data, rhs_len);
Damien George5fa93b62014-01-22 14:35:10 +0000258 return MP_OBJ_NEW_QSTR(qstr_build_end(q_ptr));
259 */
260
261 // code for non-qstr
262 byte *data;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +0200263 mp_obj_t s = mp_obj_str_builder_start(mp_obj_get_type(lhs_in), alloc_len, &data);
Damien George5fa93b62014-01-22 14:35:10 +0000264 memcpy(data, lhs_data, lhs_len);
265 memcpy(data + lhs_len, rhs_data, rhs_len);
266 return mp_obj_str_builder_end(s);
Damiend99b0522013-12-21 18:17:45 +0000267 }
268 break;
Damien George5fa93b62014-01-22 14:35:10 +0000269
Damien Georged17926d2014-03-30 13:35:08 +0100270 case MP_BINARY_OP_IN:
John R. Lentonc1bef212014-01-11 12:39:33 +0000271 /* NOTE `a in b` is `b.__contains__(a)` */
Damien George5fa93b62014-01-22 14:35:10 +0000272 if (MP_OBJ_IS_STR(rhs_in)) {
273 GET_STR_DATA_LEN(rhs_in, rhs_data, rhs_len);
xbe17a5a832014-03-23 23:31:58 -0700274 return MP_BOOL(find_subbytes(lhs_data, lhs_len, rhs_data, rhs_len, 1) != NULL);
John R. Lentonc1bef212014-01-11 12:39:33 +0000275 }
276 break;
Damien George5fa93b62014-01-22 14:35:10 +0000277
Damien Georged17926d2014-03-30 13:35:08 +0100278 case MP_BINARY_OP_MULTIPLY:
Paul Sokolovsky545591a2014-01-21 00:27:33 +0200279 {
280 if (!MP_OBJ_IS_SMALL_INT(rhs_in)) {
281 return NULL;
282 }
283 int n = MP_OBJ_SMALL_INT_VALUE(rhs_in);
Damien George5fa93b62014-01-22 14:35:10 +0000284 byte *data;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +0200285 mp_obj_t s = mp_obj_str_builder_start(mp_obj_get_type(lhs_in), lhs_len * n, &data);
Damien George5fa93b62014-01-22 14:35:10 +0000286 mp_seq_multiply(lhs_data, sizeof(*lhs_data), lhs_len, n, data);
287 return mp_obj_str_builder_end(s);
Paul Sokolovsky545591a2014-01-21 00:27:33 +0200288 }
Paul Sokolovsky87e85b72014-02-02 08:24:07 +0200289
Paul Sokolovsky4db727a2014-03-31 21:18:28 +0300290 case MP_BINARY_OP_MODULO: {
291 mp_obj_t *args;
292 uint n_args;
293 if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_tuple)) {
294 // TODO: Support tuple subclasses?
295 mp_obj_tuple_get(rhs_in, &n_args, &args);
296 } else {
297 args = &rhs_in;
298 n_args = 1;
299 }
300 return str_modulo_format(lhs_in, n_args, args);
301 }
302
Damien Georged17926d2014-03-30 13:35:08 +0100303 // These 2 are never passed here, dealt with as a special case in mp_binary_op().
304 //case MP_BINARY_OP_EQUAL:
305 //case MP_BINARY_OP_NOT_EQUAL:
306 case MP_BINARY_OP_LESS:
307 case MP_BINARY_OP_LESS_EQUAL:
308 case MP_BINARY_OP_MORE:
309 case MP_BINARY_OP_MORE_EQUAL:
Paul Sokolovsky87e85b72014-02-02 08:24:07 +0200310 if (MP_OBJ_IS_STR(rhs_in)) {
311 GET_STR_DATA_LEN(rhs_in, rhs_data, rhs_len);
312 return MP_BOOL(mp_seq_cmp_bytes(op, lhs_data, lhs_len, rhs_data, rhs_len));
313 }
Damiend99b0522013-12-21 18:17:45 +0000314 }
315
316 return MP_OBJ_NULL; // op not supported
317}
318
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200319STATIC mp_obj_t str_join(mp_obj_t self_in, mp_obj_t arg) {
Damien George5fa93b62014-01-22 14:35:10 +0000320 assert(MP_OBJ_IS_STR(self_in));
Damiend99b0522013-12-21 18:17:45 +0000321
Damien Georgefe8fb912014-01-02 16:36:09 +0000322 // get separation string
Damien George5fa93b62014-01-22 14:35:10 +0000323 GET_STR_DATA_LEN(self_in, sep_str, sep_len);
Damien Georgefe8fb912014-01-02 16:36:09 +0000324
325 // process args
Damiend99b0522013-12-21 18:17:45 +0000326 uint seq_len;
327 mp_obj_t *seq_items;
Damien George07ddab52014-03-29 13:15:08 +0000328 if (MP_OBJ_IS_TYPE(arg, &mp_type_tuple)) {
Damiend99b0522013-12-21 18:17:45 +0000329 mp_obj_tuple_get(arg, &seq_len, &seq_items);
Damiend99b0522013-12-21 18:17:45 +0000330 } else {
Damien Georgea157e4c2014-04-09 19:17:53 +0100331 if (!MP_OBJ_IS_TYPE(arg, &mp_type_list)) {
332 // arg is not a list, try to convert it to one
333 arg = mp_type_list.make_new((mp_obj_t)&mp_type_list, 1, 0, &arg);
334 }
335 mp_obj_list_get(arg, &seq_len, &seq_items);
Damiend99b0522013-12-21 18:17:45 +0000336 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000337
338 // count required length
339 int required_len = 0;
Damiend99b0522013-12-21 18:17:45 +0000340 for (int i = 0; i < seq_len; i++) {
Damien George5fa93b62014-01-22 14:35:10 +0000341 if (!MP_OBJ_IS_STR(seq_items[i])) {
Damien Georgea157e4c2014-04-09 19:17:53 +0100342 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "join expected a list of str's"));
Damiend99b0522013-12-21 18:17:45 +0000343 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000344 if (i > 0) {
345 required_len += sep_len;
346 }
Damien George5fa93b62014-01-22 14:35:10 +0000347 GET_STR_LEN(seq_items[i], l);
348 required_len += l;
Damiend99b0522013-12-21 18:17:45 +0000349 }
350
351 // make joined string
Damien George5fa93b62014-01-22 14:35:10 +0000352 byte *data;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +0200353 mp_obj_t joined_str = mp_obj_str_builder_start(mp_obj_get_type(self_in), required_len, &data);
Damiend99b0522013-12-21 18:17:45 +0000354 for (int i = 0; i < seq_len; i++) {
Damiend99b0522013-12-21 18:17:45 +0000355 if (i > 0) {
Damien George5fa93b62014-01-22 14:35:10 +0000356 memcpy(data, sep_str, sep_len);
357 data += sep_len;
Damiend99b0522013-12-21 18:17:45 +0000358 }
Damien George5fa93b62014-01-22 14:35:10 +0000359 GET_STR_DATA_LEN(seq_items[i], s, l);
360 memcpy(data, s, l);
361 data += l;
Damiend99b0522013-12-21 18:17:45 +0000362 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000363
364 // return joined string
Damien George5fa93b62014-01-22 14:35:10 +0000365 return mp_obj_str_builder_end(joined_str);
Damiend99b0522013-12-21 18:17:45 +0000366}
367
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200368#define is_ws(c) ((c) == ' ' || (c) == '\t')
369
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200370STATIC mp_obj_t str_split(uint n_args, const mp_obj_t *args) {
Damien Georgedeed0872014-04-06 11:11:15 +0100371 machine_int_t splits = -1;
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200372 mp_obj_t sep = mp_const_none;
373 if (n_args > 1) {
374 sep = args[1];
375 if (n_args > 2) {
Damien Georgedeed0872014-04-06 11:11:15 +0100376 splits = mp_obj_get_int(args[2]);
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200377 }
378 }
Damien Georgedeed0872014-04-06 11:11:15 +0100379
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200380 mp_obj_t res = mp_obj_new_list(0, NULL);
Damien George5fa93b62014-01-22 14:35:10 +0000381 GET_STR_DATA_LEN(args[0], s, len);
382 const byte *top = s + len;
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200383
Damien Georgedeed0872014-04-06 11:11:15 +0100384 if (sep == mp_const_none) {
385 // sep not given, so separate on whitespace
386
387 // Initial whitespace is not counted as split, so we pre-do it
Damien George5fa93b62014-01-22 14:35:10 +0000388 while (s < top && is_ws(*s)) s++;
Damien Georgedeed0872014-04-06 11:11:15 +0100389 while (s < top && splits != 0) {
390 const byte *start = s;
391 while (s < top && !is_ws(*s)) s++;
392 mp_obj_list_append(res, mp_obj_new_str(start, s - start, false));
393 if (s >= top) {
394 break;
395 }
396 while (s < top && is_ws(*s)) s++;
397 if (splits > 0) {
398 splits--;
399 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200400 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200401
Damien Georgedeed0872014-04-06 11:11:15 +0100402 if (s < top) {
403 mp_obj_list_append(res, mp_obj_new_str(s, top - s, false));
404 }
405
406 } else {
407 // sep given
408
409 uint sep_len;
410 const char *sep_str = mp_obj_str_get_data(sep, &sep_len);
411
412 if (sep_len == 0) {
413 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
414 }
415
416 for (;;) {
417 const byte *start = s;
418 for (;;) {
419 if (splits == 0 || s + sep_len > top) {
420 s = top;
421 break;
422 } else if (memcmp(s, sep_str, sep_len) == 0) {
423 break;
424 }
425 s++;
426 }
427 mp_obj_list_append(res, mp_obj_new_str(start, s - start, false));
428 if (s >= top) {
429 break;
430 }
431 s += sep_len;
432 if (splits > 0) {
433 splits--;
434 }
435 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200436 }
437
438 return res;
439}
440
xbe3d9a39e2014-04-08 11:42:19 -0700441STATIC mp_obj_t str_finder(uint n_args, const mp_obj_t *args, machine_int_t direction, bool is_index) {
John R. Lentone8204912014-01-12 21:53:52 +0000442 assert(2 <= n_args && n_args <= 4);
Damien George5fa93b62014-01-22 14:35:10 +0000443 assert(MP_OBJ_IS_STR(args[0]));
444 assert(MP_OBJ_IS_STR(args[1]));
John R. Lentone8204912014-01-12 21:53:52 +0000445
Damien George5fa93b62014-01-22 14:35:10 +0000446 GET_STR_DATA_LEN(args[0], haystack, haystack_len);
447 GET_STR_DATA_LEN(args[1], needle, needle_len);
John R. Lentone8204912014-01-12 21:53:52 +0000448
xbec5538882014-03-16 17:58:35 -0700449 machine_uint_t start = 0;
450 machine_uint_t end = haystack_len;
John R. Lentone8204912014-01-12 21:53:52 +0000451 if (n_args >= 3 && args[2] != mp_const_none) {
Damien George3e1a5c12014-03-29 13:43:38 +0000452 start = mp_get_index(&mp_type_str, haystack_len, args[2], true);
John R. Lentone8204912014-01-12 21:53:52 +0000453 }
454 if (n_args >= 4 && args[3] != mp_const_none) {
Damien George3e1a5c12014-03-29 13:43:38 +0000455 end = mp_get_index(&mp_type_str, haystack_len, args[3], true);
John R. Lentone8204912014-01-12 21:53:52 +0000456 }
457
xbe17a5a832014-03-23 23:31:58 -0700458 const byte *p = find_subbytes(haystack + start, end - start, needle, needle_len, direction);
Damien George23005372014-01-13 19:39:01 +0000459 if (p == NULL) {
460 // not found
xbe3d9a39e2014-04-08 11:42:19 -0700461 if (is_index) {
462 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "substring not found"));
463 } else {
464 return MP_OBJ_NEW_SMALL_INT(-1);
465 }
Damien George23005372014-01-13 19:39:01 +0000466 } else {
467 // found
xbe17a5a832014-03-23 23:31:58 -0700468 return MP_OBJ_NEW_SMALL_INT(p - haystack);
John R. Lentone8204912014-01-12 21:53:52 +0000469 }
John R. Lentone8204912014-01-12 21:53:52 +0000470}
471
xbe17a5a832014-03-23 23:31:58 -0700472STATIC mp_obj_t str_find(uint n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700473 return str_finder(n_args, args, 1, false);
xbe17a5a832014-03-23 23:31:58 -0700474}
475
476STATIC mp_obj_t str_rfind(uint n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700477 return str_finder(n_args, args, -1, false);
478}
479
480STATIC mp_obj_t str_index(uint n_args, const mp_obj_t *args) {
481 return str_finder(n_args, args, 1, true);
482}
483
484STATIC mp_obj_t str_rindex(uint n_args, const mp_obj_t *args) {
485 return str_finder(n_args, args, -1, true);
xbe17a5a832014-03-23 23:31:58 -0700486}
487
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200488// TODO: (Much) more variety in args
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200489STATIC mp_obj_t str_startswith(mp_obj_t self_in, mp_obj_t arg) {
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200490 GET_STR_DATA_LEN(self_in, str, str_len);
491 GET_STR_DATA_LEN(arg, prefix, prefix_len);
492 if (prefix_len > str_len) {
493 return mp_const_false;
494 }
495 return MP_BOOL(memcmp(str, prefix, prefix_len) == 0);
496}
497
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200498STATIC mp_obj_t str_strip(uint n_args, const mp_obj_t *args) {
xbe7b0f39f2014-01-08 14:23:45 -0800499 assert(1 <= n_args && n_args <= 2);
Damien George5fa93b62014-01-22 14:35:10 +0000500 assert(MP_OBJ_IS_STR(args[0]));
501
502 const byte *chars_to_del;
503 uint chars_to_del_len;
504 static const byte whitespace[] = " \t\n\r\v\f";
xbe7b0f39f2014-01-08 14:23:45 -0800505
506 if (n_args == 1) {
507 chars_to_del = whitespace;
Damien George5fa93b62014-01-22 14:35:10 +0000508 chars_to_del_len = sizeof(whitespace);
xbe7b0f39f2014-01-08 14:23:45 -0800509 } else {
Damien George5fa93b62014-01-22 14:35:10 +0000510 assert(MP_OBJ_IS_STR(args[1]));
511 GET_STR_DATA_LEN(args[1], s, l);
512 chars_to_del = s;
513 chars_to_del_len = l;
xbe7b0f39f2014-01-08 14:23:45 -0800514 }
515
Damien George5fa93b62014-01-22 14:35:10 +0000516 GET_STR_DATA_LEN(args[0], orig_str, orig_str_len);
xbe7b0f39f2014-01-08 14:23:45 -0800517
xbec5538882014-03-16 17:58:35 -0700518 machine_uint_t first_good_char_pos = 0;
xbe7b0f39f2014-01-08 14:23:45 -0800519 bool first_good_char_pos_set = false;
xbec5538882014-03-16 17:58:35 -0700520 machine_uint_t last_good_char_pos = 0;
521 for (machine_uint_t i = 0; i < orig_str_len; i++) {
xbe17a5a832014-03-23 23:31:58 -0700522 if (find_subbytes(chars_to_del, chars_to_del_len, &orig_str[i], 1, 1) == NULL) {
xbe7b0f39f2014-01-08 14:23:45 -0800523 last_good_char_pos = i;
524 if (!first_good_char_pos_set) {
525 first_good_char_pos = i;
526 first_good_char_pos_set = true;
527 }
528 }
529 }
530
531 if (first_good_char_pos == 0 && last_good_char_pos == 0) {
Damien George5fa93b62014-01-22 14:35:10 +0000532 // string is all whitespace, return ''
533 return MP_OBJ_NEW_QSTR(MP_QSTR_);
xbe7b0f39f2014-01-08 14:23:45 -0800534 }
535
536 assert(last_good_char_pos >= first_good_char_pos);
537 //+1 to accomodate the last character
xbec5538882014-03-16 17:58:35 -0700538 machine_uint_t stripped_len = last_good_char_pos - first_good_char_pos + 1;
Damien George5fa93b62014-01-22 14:35:10 +0000539 return mp_obj_new_str(orig_str + first_good_char_pos, stripped_len, false);
xbe7b0f39f2014-01-08 14:23:45 -0800540}
541
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700542// Takes an int arg, but only parses unsigned numbers, and only changes
543// *num if at least one digit was parsed.
544static int str_to_int(const char *str, int *num) {
545 const char *s = str;
546 if (unichar_isdigit(*s)) {
547 *num = 0;
548 do {
549 *num = *num * 10 + (*s - '0');
550 s++;
551 }
552 while (unichar_isdigit(*s));
553 }
554 return s - str;
555}
556
557static bool isalignment(char ch) {
558 return ch && strchr("<>=^", ch) != NULL;
559}
560
561static bool istype(char ch) {
562 return ch && strchr("bcdeEfFgGnosxX%", ch) != NULL;
563}
564
565static bool arg_looks_integer(mp_obj_t arg) {
566 return MP_OBJ_IS_TYPE(arg, &mp_type_bool) || MP_OBJ_IS_INT(arg);
567}
568
569static bool arg_looks_numeric(mp_obj_t arg) {
570 return arg_looks_integer(arg)
571#if MICROPY_ENABLE_FLOAT
572 || MP_OBJ_IS_TYPE(arg, &mp_type_float)
573#endif
574 ;
575}
576
Dave Hylandsc4029e52014-04-07 11:19:51 -0700577static mp_obj_t arg_as_int(mp_obj_t arg) {
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700578#if MICROPY_ENABLE_FLOAT
579 if (MP_OBJ_IS_TYPE(arg, &mp_type_float)) {
Dave Hylandsc4029e52014-04-07 11:19:51 -0700580
581 // TODO: Needs a way to construct an mpz integer from a float
582
583 mp_small_int_t num = mp_obj_get_float(arg);
584 return MP_OBJ_NEW_SMALL_INT(num);
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700585 }
586#endif
Dave Hylandsc4029e52014-04-07 11:19:51 -0700587 return arg;
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700588}
589
Damien Georgea11ceca2014-01-19 16:02:09 +0000590mp_obj_t str_format(uint n_args, const mp_obj_t *args) {
Damien George5fa93b62014-01-22 14:35:10 +0000591 assert(MP_OBJ_IS_STR(args[0]));
Damiend99b0522013-12-21 18:17:45 +0000592
Damien George5fa93b62014-01-22 14:35:10 +0000593 GET_STR_DATA_LEN(args[0], str, len);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700594 int arg_i = 0;
Damiend99b0522013-12-21 18:17:45 +0000595 vstr_t *vstr = vstr_new();
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700596 pfenv_t pfenv_vstr;
597 pfenv_vstr.data = vstr;
598 pfenv_vstr.print_strn = pfenv_vstr_add_strn;
599
Damien George5fa93b62014-01-22 14:35:10 +0000600 for (const byte *top = str + len; str < top; str++) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700601 if (*str == '}') {
Damiend99b0522013-12-21 18:17:45 +0000602 str++;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700603 if (str < top && *str == '}') {
604 vstr_add_char(vstr, '}');
605 continue;
606 }
Damien Georgeea13f402014-04-05 18:32:08 +0100607 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "Single '}' encountered in format string"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700608 }
609 if (*str != '{') {
610 vstr_add_char(vstr, *str);
611 continue;
612 }
613
614 str++;
615 if (str < top && *str == '{') {
616 vstr_add_char(vstr, '{');
617 continue;
618 }
619
620 // replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"
621
622 vstr_t *field_name = NULL;
623 char conversion = '\0';
624 vstr_t *format_spec = NULL;
625
626 if (str < top && *str != '}' && *str != '!' && *str != ':') {
627 field_name = vstr_new();
628 while (str < top && *str != '}' && *str != '!' && *str != ':') {
629 vstr_add_char(field_name, *str++);
630 }
631 vstr_add_char(field_name, '\0');
632 }
633
634 // conversion ::= "r" | "s"
635
636 if (str < top && *str == '!') {
637 str++;
638 if (str < top && (*str == 'r' || *str == 's')) {
639 conversion = *str++;
Paul Sokolovskyf2b796e2014-01-15 22:45:20 +0200640 } else {
Damien Georgeea13f402014-04-05 18:32:08 +0100641 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "end of format while looking for conversion specifier"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700642 }
643 }
644
645 if (str < top && *str == ':') {
646 str++;
647 // {:} is the same as {}, which is the same as {!s}
648 // This makes a difference when passing in a True or False
649 // '{}'.format(True) returns 'True'
650 // '{:d}'.format(True) returns '1'
651 // So we treat {:} as {} and this later gets treated to be {!s}
652 if (*str != '}') {
653 format_spec = vstr_new();
654 while (str < top && *str != '}') {
655 vstr_add_char(format_spec, *str++);
Damiend99b0522013-12-21 18:17:45 +0000656 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700657 vstr_add_char(format_spec, '\0');
658 }
659 }
660 if (str >= top) {
Damien Georgeea13f402014-04-05 18:32:08 +0100661 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "unmatched '{' in format"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700662 }
663 if (*str != '}') {
Damien Georgeea13f402014-04-05 18:32:08 +0100664 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "expected ':' after format specifier"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700665 }
666
667 mp_obj_t arg = mp_const_none;
668
669 if (field_name) {
670 if (arg_i > 0) {
Damien Georgeea13f402014-04-05 18:32:08 +0100671 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "cannot switch from automatic field numbering to manual field specification"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700672 }
673 int index;
674 if (str_to_int(vstr_str(field_name), &index) != vstr_len(field_name) - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100675 nlr_raise(mp_obj_new_exception_msg(&mp_type_KeyError, "attributes not supported yet"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700676 }
677 if (index >= n_args - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100678 nlr_raise(mp_obj_new_exception_msg(&mp_type_IndexError, "tuple index out of range"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700679 }
680 arg = args[index + 1];
681 arg_i = -1;
682 vstr_free(field_name);
683 field_name = NULL;
684 } else {
685 if (arg_i < 0) {
Damien Georgeea13f402014-04-05 18:32:08 +0100686 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "cannot switch from manual field specification to automatic field numbering"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700687 }
688 if (arg_i >= n_args - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100689 nlr_raise(mp_obj_new_exception_msg(&mp_type_IndexError, "tuple index out of range"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700690 }
691 arg = args[arg_i + 1];
692 arg_i++;
693 }
694 if (!format_spec && !conversion) {
695 conversion = 's';
696 }
697 if (conversion) {
698 mp_print_kind_t print_kind;
699 if (conversion == 's') {
700 print_kind = PRINT_STR;
701 } else if (conversion == 'r') {
702 print_kind = PRINT_REPR;
703 } else {
Damien Georgeea13f402014-04-05 18:32:08 +0100704 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Unknown conversion specifier %c", conversion));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700705 }
706 vstr_t *arg_vstr = vstr_new();
707 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, arg_vstr, arg, print_kind);
708 arg = mp_obj_new_str((const byte *)vstr_str(arg_vstr), vstr_len(arg_vstr), false);
709 vstr_free(arg_vstr);
710 }
711
712 char sign = '\0';
713 char fill = '\0';
714 char align = '\0';
715 int width = -1;
716 int precision = -1;
717 char type = '\0';
718 int flags = 0;
719
720 if (format_spec) {
721 // The format specifier (from http://docs.python.org/2/library/string.html#formatspec)
722 //
723 // [[fill]align][sign][#][0][width][,][.precision][type]
724 // fill ::= <any character>
725 // align ::= "<" | ">" | "=" | "^"
726 // sign ::= "+" | "-" | " "
727 // width ::= integer
728 // precision ::= integer
729 // type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
730
731 const char *s = vstr_str(format_spec);
732 if (isalignment(*s)) {
733 align = *s++;
734 } else if (*s && isalignment(s[1])) {
735 fill = *s++;
736 align = *s++;
737 }
738 if (*s == '+' || *s == '-' || *s == ' ') {
739 if (*s == '+') {
740 flags |= PF_FLAG_SHOW_SIGN;
741 } else if (*s == ' ') {
742 flags |= PF_FLAG_SPACE_SIGN;
743 }
744 sign = *s++;
745 }
746 if (*s == '#') {
747 flags |= PF_FLAG_SHOW_PREFIX;
748 s++;
749 }
750 if (*s == '0') {
751 if (!align) {
752 align = '=';
753 }
754 if (!fill) {
755 fill = '0';
756 }
757 }
758 s += str_to_int(s, &width);
759 if (*s == ',') {
760 flags |= PF_FLAG_SHOW_COMMA;
761 s++;
762 }
763 if (*s == '.') {
764 s++;
765 s += str_to_int(s, &precision);
766 }
767 if (istype(*s)) {
768 type = *s++;
769 }
770 if (*s) {
Damien Georgeea13f402014-04-05 18:32:08 +0100771 nlr_raise(mp_obj_new_exception_msg(&mp_type_KeyError, "Invalid conversion specification"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700772 }
773 vstr_free(format_spec);
774 format_spec = NULL;
775 }
776 if (!align) {
777 if (arg_looks_numeric(arg)) {
778 align = '>';
779 } else {
780 align = '<';
781 }
782 }
783 if (!fill) {
784 fill = ' ';
785 }
786
787 if (sign) {
788 if (type == 's') {
Damien Georgeea13f402014-04-05 18:32:08 +0100789 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "Sign not allowed in string format specifier"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700790 }
791 if (type == 'c') {
Damien Georgeea13f402014-04-05 18:32:08 +0100792 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "Sign not allowed with integer format specifier 'c'"));
Damiend99b0522013-12-21 18:17:45 +0000793 }
794 } else {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700795 sign = '-';
796 }
797
798 switch (align) {
799 case '<': flags |= PF_FLAG_LEFT_ADJUST; break;
800 case '=': flags |= PF_FLAG_PAD_AFTER_SIGN; break;
801 case '^': flags |= PF_FLAG_CENTER_ADJUST; break;
802 }
803
804 if (arg_looks_integer(arg)) {
805 switch (type) {
806 case 'b':
Damien Georgea12a0f72014-04-08 01:29:53 +0100807 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 2, 'a', flags, fill, width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700808 continue;
809
810 case 'c':
811 {
812 char ch = mp_obj_get_int(arg);
813 pfenv_print_strn(&pfenv_vstr, &ch, 1, flags, fill, width);
814 continue;
815 }
816
817 case '\0': // No explicit format type implies 'd'
818 case 'n': // I don't think we support locales in uPy so use 'd'
819 case 'd':
Damien Georgea12a0f72014-04-08 01:29:53 +0100820 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 10, 'a', flags, fill, width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700821 continue;
822
823 case 'o':
Dave Hylandsc4029e52014-04-07 11:19:51 -0700824 if (flags & PF_FLAG_SHOW_PREFIX) {
825 flags |= PF_FLAG_SHOW_OCTAL_LETTER;
826 }
827
Damien Georgea12a0f72014-04-08 01:29:53 +0100828 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 8, 'a', flags, fill, width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700829 continue;
830
831 case 'x':
Damien Georgea12a0f72014-04-08 01:29:53 +0100832 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 16, 'a', flags, fill, width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700833 continue;
834
835 case 'X':
Damien Georgea12a0f72014-04-08 01:29:53 +0100836 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 16, 'A', flags, fill, width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700837 continue;
838
839 case 'e':
840 case 'E':
841 case 'f':
842 case 'F':
843 case 'g':
844 case 'G':
845 case '%':
846 // The floating point formatters all work with anything that
847 // looks like an integer
848 break;
849
850 default:
Damien Georgeea13f402014-04-05 18:32:08 +0100851 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700852 "Unknown format code '%c' for object of type '%s'", type, mp_obj_get_type_str(arg)));
853 }
Damien Georgec322c5f2014-04-02 20:04:15 +0100854 }
Damien George70f33cd2014-04-02 17:06:05 +0100855
Dave Hylands22fe4d72014-04-02 12:07:31 -0700856 // NOTE: no else here. We need the e, f, g etc formats for integer
857 // arguments (from above if) to take this if.
Damien Georgec322c5f2014-04-02 20:04:15 +0100858 if (arg_looks_numeric(arg)) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700859 if (!type) {
860
861 // Even though the docs say that an unspecified type is the same
862 // as 'g', there is one subtle difference, when the exponent
863 // is one less than the precision.
864 //
865 // '{:10.1}'.format(0.0) ==> '0e+00'
866 // '{:10.1g}'.format(0.0) ==> '0'
867 //
868 // TODO: Figure out how to deal with this.
869 //
870 // A proper solution would involve adding a special flag
871 // or something to format_float, and create a format_double
872 // to deal with doubles. In order to fix this when using
873 // sprintf, we'd need to use the e format and tweak the
874 // returned result to strip trailing zeros like the g format
875 // does.
876 //
877 // {:10.3} and {:10.2e} with 1.23e2 both produce 1.23e+02
878 // but with 1.e2 you get 1e+02 and 1.00e+02
879 //
880 // Stripping the trailing 0's (like g) does would make the
881 // e format give us the right format.
882 //
883 // CPython sources say:
884 // Omitted type specifier. Behaves in the same way as repr(x)
885 // and str(x) if no precision is given, else like 'g', but with
886 // at least one digit after the decimal point. */
887
888 type = 'g';
889 }
890 if (type == 'n') {
891 type = 'g';
892 }
893
894 flags |= PF_FLAG_PAD_NAN_INF; // '{:06e}'.format(float('-inf')) should give '-00inf'
895 switch (type) {
Damien Georgec322c5f2014-04-02 20:04:15 +0100896#if MICROPY_ENABLE_FLOAT
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700897 case 'e':
898 case 'E':
899 case 'f':
900 case 'F':
901 case 'g':
902 case 'G':
903 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg), type, flags, fill, width, precision);
904 break;
905
906 case '%':
907 flags |= PF_FLAG_ADD_PERCENT;
908 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg) * 100.0F, 'f', flags, fill, width, precision);
909 break;
Damien Georgec322c5f2014-04-02 20:04:15 +0100910#endif
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700911
912 default:
Damien Georgeea13f402014-04-05 18:32:08 +0100913 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700914 "Unknown format code '%c' for object of type 'float'",
915 type, mp_obj_get_type_str(arg)));
916 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700917 } else {
Damien George70f33cd2014-04-02 17:06:05 +0100918 // arg doesn't look like a number
919
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700920 if (align == '=') {
Damien Georgeea13f402014-04-05 18:32:08 +0100921 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "'=' alignment not allowed in string format specifier"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700922 }
Damien George70f33cd2014-04-02 17:06:05 +0100923
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700924 switch (type) {
925 case '\0':
926 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, vstr, arg, PRINT_STR);
927 break;
928
929 case 's':
930 {
931 uint len;
932 const char *s = mp_obj_str_get_data(arg, &len);
933 if (precision < 0) {
934 precision = len;
935 }
936 if (len > precision) {
937 len = precision;
938 }
939 pfenv_print_strn(&pfenv_vstr, s, len, flags, fill, width);
940 break;
941 }
942
943 default:
Damien Georgeea13f402014-04-05 18:32:08 +0100944 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700945 "Unknown format code '%c' for object of type 'str'",
946 type, mp_obj_get_type_str(arg)));
947 }
Damiend99b0522013-12-21 18:17:45 +0000948 }
949 }
950
Damien George5fa93b62014-01-22 14:35:10 +0000951 mp_obj_t s = mp_obj_new_str((byte*)vstr->buf, vstr->len, false);
952 vstr_free(vstr);
953 return s;
Damiend99b0522013-12-21 18:17:45 +0000954}
955
Paul Sokolovsky4db727a2014-03-31 21:18:28 +0300956STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, uint n_args, const mp_obj_t *args) {
957 assert(MP_OBJ_IS_STR(pattern));
958
959 GET_STR_DATA_LEN(pattern, str, len);
Dave Hylands6756a372014-04-02 11:42:39 -0700960 const byte *start_str = str;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +0300961 int arg_i = 0;
962 vstr_t *vstr = vstr_new();
Dave Hylands6756a372014-04-02 11:42:39 -0700963 pfenv_t pfenv_vstr;
964 pfenv_vstr.data = vstr;
965 pfenv_vstr.print_strn = pfenv_vstr_add_strn;
966
Paul Sokolovsky4db727a2014-03-31 21:18:28 +0300967 for (const byte *top = str + len; str < top; str++) {
Dave Hylands6756a372014-04-02 11:42:39 -0700968 if (*str != '%') {
969 vstr_add_char(vstr, *str);
970 continue;
971 }
972 if (++str >= top) {
973 break;
974 }
Paul Sokolovsky4db727a2014-03-31 21:18:28 +0300975 if (*str == '%') {
Dave Hylands6756a372014-04-02 11:42:39 -0700976 vstr_add_char(vstr, '%');
977 continue;
978 }
979 if (arg_i >= n_args) {
Damien Georgeea13f402014-04-05 18:32:08 +0100980 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "not enough arguments for format string"));
Dave Hylands6756a372014-04-02 11:42:39 -0700981 }
982 int flags = 0;
983 char fill = ' ';
984 bool alt = false;
985 while (str < top) {
986 if (*str == '-') flags |= PF_FLAG_LEFT_ADJUST;
987 else if (*str == '+') flags |= PF_FLAG_SHOW_SIGN;
988 else if (*str == ' ') flags |= PF_FLAG_SPACE_SIGN;
989 else if (*str == '#') alt = true;
990 else if (*str == '0') {
991 flags |= PF_FLAG_PAD_AFTER_SIGN;
992 fill = '0';
993 } else break;
994 str++;
995 }
996 // parse width, if it exists
997 int width = 0;
998 if (str < top) {
999 if (*str == '*') {
1000 width = mp_obj_get_int(args[arg_i++]);
1001 str++;
1002 } else {
1003 for (; str < top && '0' <= *str && *str <= '9'; str++) {
1004 width = width * 10 + *str - '0';
1005 }
1006 }
1007 }
1008 int prec = -1;
1009 if (str < top && *str == '.') {
1010 if (++str < top) {
1011 if (*str == '*') {
1012 prec = mp_obj_get_int(args[arg_i++]);
1013 str++;
1014 } else {
1015 prec = 0;
1016 for (; str < top && '0' <= *str && *str <= '9'; str++) {
1017 prec = prec * 10 + *str - '0';
1018 }
1019 }
1020 }
1021 }
1022
1023 if (str >= top) {
Damien Georgeea13f402014-04-05 18:32:08 +01001024 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "incomplete format"));
Dave Hylands6756a372014-04-02 11:42:39 -07001025 }
1026 mp_obj_t arg = args[arg_i];
1027 switch (*str) {
1028 case 'c':
1029 if (MP_OBJ_IS_STR(arg)) {
1030 uint len;
1031 const char *s = mp_obj_str_get_data(arg, &len);
1032 if (len != 1) {
Damien Georgeea13f402014-04-05 18:32:08 +01001033 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "%c requires int or char"));
Dave Hylands6756a372014-04-02 11:42:39 -07001034 break;
1035 }
1036 pfenv_print_strn(&pfenv_vstr, s, 1, flags, ' ', width);
1037 break;
1038 }
1039 if (arg_looks_integer(arg)) {
1040 char ch = mp_obj_get_int(arg);
1041 pfenv_print_strn(&pfenv_vstr, &ch, 1, flags, ' ', width);
1042 break;
1043 }
1044#if MICROPY_ENABLE_FLOAT
1045 // This is what CPython reports, so we report the same.
1046 if (MP_OBJ_IS_TYPE(arg, &mp_type_float)) {
Damien Georgeea13f402014-04-05 18:32:08 +01001047 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "integer argument expected, got float"));
Dave Hylands6756a372014-04-02 11:42:39 -07001048
1049 }
1050#endif
Damien Georgeea13f402014-04-05 18:32:08 +01001051 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "an integer is required"));
Dave Hylands6756a372014-04-02 11:42:39 -07001052 break;
1053
1054 case 'd':
1055 case 'i':
1056 case 'u':
Damien Georgea12a0f72014-04-08 01:29:53 +01001057 pfenv_print_mp_int(&pfenv_vstr, arg_as_int(arg), 1, 10, 'a', flags, fill, width);
Dave Hylands6756a372014-04-02 11:42:39 -07001058 break;
1059
1060#if MICROPY_ENABLE_FLOAT
1061 case 'e':
1062 case 'E':
1063 case 'f':
1064 case 'F':
1065 case 'g':
1066 case 'G':
1067 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg), *str, flags, fill, width, prec);
1068 break;
1069#endif
1070
1071 case 'o':
1072 if (alt) {
Dave Hylandsc4029e52014-04-07 11:19:51 -07001073 flags |= (PF_FLAG_SHOW_PREFIX | PF_FLAG_SHOW_OCTAL_LETTER);
Dave Hylands6756a372014-04-02 11:42:39 -07001074 }
Damien Georgea12a0f72014-04-08 01:29:53 +01001075 pfenv_print_mp_int(&pfenv_vstr, arg_as_int(arg), 1, 8, 'a', flags, fill, width);
Dave Hylands6756a372014-04-02 11:42:39 -07001076 break;
1077
1078 case 'r':
1079 case 's':
1080 {
1081 vstr_t *arg_vstr = vstr_new();
1082 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf,
1083 arg_vstr, arg, *str == 'r' ? PRINT_REPR : PRINT_STR);
1084 uint len = vstr_len(arg_vstr);
1085 if (prec < 0) {
1086 prec = len;
1087 }
1088 if (len > prec) {
1089 len = prec;
1090 }
1091 pfenv_print_strn(&pfenv_vstr, vstr_str(arg_vstr), len, flags, ' ', width);
1092 vstr_free(arg_vstr);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001093 break;
1094 }
Dave Hylands6756a372014-04-02 11:42:39 -07001095
1096 case 'x':
1097 if (alt) {
1098 flags |= PF_FLAG_SHOW_PREFIX;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001099 }
Damien Georgea12a0f72014-04-08 01:29:53 +01001100 pfenv_print_mp_int(&pfenv_vstr, arg_as_int(arg), 1, 16, 'a', flags, fill, width);
Dave Hylands6756a372014-04-02 11:42:39 -07001101 break;
1102
1103 case 'X':
1104 if (alt) {
1105 flags |= PF_FLAG_SHOW_PREFIX;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001106 }
Damien Georgea12a0f72014-04-08 01:29:53 +01001107 pfenv_print_mp_int(&pfenv_vstr, arg_as_int(arg), 1, 16, 'A', flags, fill, width);
Dave Hylands6756a372014-04-02 11:42:39 -07001108 break;
Damien Georgedeed0872014-04-06 11:11:15 +01001109
Dave Hylands6756a372014-04-02 11:42:39 -07001110 default:
Damien Georgeea13f402014-04-05 18:32:08 +01001111 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Dave Hylands6756a372014-04-02 11:42:39 -07001112 "unsupported format character '%c' (0x%x) at index %d",
1113 *str, *str, str - start_str));
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001114 }
Dave Hylands6756a372014-04-02 11:42:39 -07001115 arg_i++;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001116 }
1117
1118 if (arg_i != n_args) {
Damien Georgeea13f402014-04-05 18:32:08 +01001119 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "not all arguments converted during string formatting"));
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001120 }
1121
1122 mp_obj_t s = mp_obj_new_str((byte*)vstr->buf, vstr->len, false);
1123 vstr_free(vstr);
1124 return s;
1125}
1126
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001127STATIC mp_obj_t str_replace(uint n_args, const mp_obj_t *args) {
xbe480c15a2014-01-30 22:17:30 -08001128 assert(MP_OBJ_IS_STR(args[0]));
xbe480c15a2014-01-30 22:17:30 -08001129
Damien Georgeff715422014-04-07 00:39:13 +01001130 machine_int_t max_rep = -1;
xbe480c15a2014-01-30 22:17:30 -08001131 if (n_args == 4) {
Damien Georgeff715422014-04-07 00:39:13 +01001132 max_rep = mp_obj_get_int(args[3]);
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001133 if (max_rep == 0) {
1134 return args[0];
1135 } else if (max_rep < 0) {
Damien Georgeff715422014-04-07 00:39:13 +01001136 max_rep = -1;
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001137 }
xbe480c15a2014-01-30 22:17:30 -08001138 }
Damien George94f68302014-01-31 23:45:12 +00001139
xbe729be9b2014-04-07 14:46:39 -07001140 // if max_rep is still -1 by this point we will need to do all possible replacements
xbe480c15a2014-01-30 22:17:30 -08001141
Damien Georgeff715422014-04-07 00:39:13 +01001142 // check argument types
1143
1144 if (!MP_OBJ_IS_STR(args[1])) {
1145 bad_implicit_conversion(args[1]);
1146 }
1147
1148 if (!MP_OBJ_IS_STR(args[2])) {
1149 bad_implicit_conversion(args[2]);
1150 }
1151
1152 // extract string data
1153
xbe480c15a2014-01-30 22:17:30 -08001154 GET_STR_DATA_LEN(args[0], str, str_len);
1155 GET_STR_DATA_LEN(args[1], old, old_len);
1156 GET_STR_DATA_LEN(args[2], new, new_len);
Damien George94f68302014-01-31 23:45:12 +00001157
1158 // old won't exist in str if it's longer, so nothing to replace
xbe480c15a2014-01-30 22:17:30 -08001159 if (old_len > str_len) {
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001160 return args[0];
xbe480c15a2014-01-30 22:17:30 -08001161 }
1162
Damien George94f68302014-01-31 23:45:12 +00001163 // data for the replaced string
1164 byte *data = NULL;
1165 mp_obj_t replaced_str = MP_OBJ_NULL;
xbe480c15a2014-01-30 22:17:30 -08001166
Damien George94f68302014-01-31 23:45:12 +00001167 // do 2 passes over the string:
1168 // first pass computes the required length of the replaced string
1169 // second pass does the replacements
1170 for (;;) {
1171 machine_uint_t replaced_str_index = 0;
1172 machine_uint_t num_replacements_done = 0;
1173 const byte *old_occurrence;
1174 const byte *offset_ptr = str;
Damien Georgeff715422014-04-07 00:39:13 +01001175 machine_uint_t str_len_remain = str_len;
1176 if (old_len == 0) {
1177 // if old_str is empty, copy new_str to start of replaced string
1178 // copy the replacement string
1179 if (data != NULL) {
1180 memcpy(data, new, new_len);
1181 }
1182 replaced_str_index += new_len;
1183 num_replacements_done++;
1184 }
1185 while (num_replacements_done != max_rep && str_len_remain > 0 && (old_occurrence = find_subbytes(offset_ptr, str_len_remain, old, old_len, 1)) != NULL) {
1186 if (old_len == 0) {
1187 old_occurrence += 1;
1188 }
Damien George94f68302014-01-31 23:45:12 +00001189 // copy from just after end of last occurrence of to-be-replaced string to right before start of next occurrence
1190 if (data != NULL) {
1191 memcpy(data + replaced_str_index, offset_ptr, old_occurrence - offset_ptr);
1192 }
1193 replaced_str_index += old_occurrence - offset_ptr;
1194 // copy the replacement string
1195 if (data != NULL) {
1196 memcpy(data + replaced_str_index, new, new_len);
1197 }
1198 replaced_str_index += new_len;
1199 offset_ptr = old_occurrence + old_len;
Damien Georgeff715422014-04-07 00:39:13 +01001200 str_len_remain = str + str_len - offset_ptr;
Damien George94f68302014-01-31 23:45:12 +00001201 num_replacements_done++;
Damien George94f68302014-01-31 23:45:12 +00001202 }
1203
1204 // copy from just after end of last occurrence of to-be-replaced string to end of old string
1205 if (data != NULL) {
Damien Georgeff715422014-04-07 00:39:13 +01001206 memcpy(data + replaced_str_index, offset_ptr, str_len_remain);
Damien George94f68302014-01-31 23:45:12 +00001207 }
Damien Georgeff715422014-04-07 00:39:13 +01001208 replaced_str_index += str_len_remain;
Damien George94f68302014-01-31 23:45:12 +00001209
1210 if (data == NULL) {
1211 // first pass
1212 if (num_replacements_done == 0) {
1213 // no substr found, return original string
1214 return args[0];
1215 } else {
1216 // substr found, allocate new string
1217 replaced_str = mp_obj_str_builder_start(mp_obj_get_type(args[0]), replaced_str_index, &data);
Damien Georgeff715422014-04-07 00:39:13 +01001218 assert(data != NULL);
Damien George94f68302014-01-31 23:45:12 +00001219 }
1220 } else {
1221 // second pass, we are done
1222 break;
1223 }
xbe480c15a2014-01-30 22:17:30 -08001224 }
Damien George94f68302014-01-31 23:45:12 +00001225
xbe480c15a2014-01-30 22:17:30 -08001226 return mp_obj_str_builder_end(replaced_str);
1227}
1228
xbe9e1e8cd2014-03-12 22:57:16 -07001229STATIC mp_obj_t str_count(uint n_args, const mp_obj_t *args) {
1230 assert(2 <= n_args && n_args <= 4);
1231 assert(MP_OBJ_IS_STR(args[0]));
1232 assert(MP_OBJ_IS_STR(args[1]));
1233
1234 GET_STR_DATA_LEN(args[0], haystack, haystack_len);
1235 GET_STR_DATA_LEN(args[1], needle, needle_len);
1236
Damien George536dde22014-03-13 22:07:55 +00001237 machine_uint_t start = 0;
1238 machine_uint_t end = haystack_len;
xbe9e1e8cd2014-03-12 22:57:16 -07001239 if (n_args >= 3 && args[2] != mp_const_none) {
Damien George3e1a5c12014-03-29 13:43:38 +00001240 start = mp_get_index(&mp_type_str, haystack_len, args[2], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001241 }
1242 if (n_args >= 4 && args[3] != mp_const_none) {
Damien George3e1a5c12014-03-29 13:43:38 +00001243 end = mp_get_index(&mp_type_str, haystack_len, args[3], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001244 }
1245
Damien George536dde22014-03-13 22:07:55 +00001246 // if needle_len is zero then we count each gap between characters as an occurrence
1247 if (needle_len == 0) {
1248 return MP_OBJ_NEW_SMALL_INT(end - start + 1);
xbe9e1e8cd2014-03-12 22:57:16 -07001249 }
1250
Damien George536dde22014-03-13 22:07:55 +00001251 // count the occurrences
1252 machine_int_t num_occurrences = 0;
xbec5d70ba2014-03-13 00:29:15 -07001253 for (machine_uint_t haystack_index = start; haystack_index + needle_len <= end; haystack_index++) {
1254 if (memcmp(&haystack[haystack_index], needle, needle_len) == 0) {
1255 num_occurrences++;
1256 haystack_index += needle_len - 1;
1257 }
xbe9e1e8cd2014-03-12 22:57:16 -07001258 }
1259
1260 return MP_OBJ_NEW_SMALL_INT(num_occurrences);
1261}
1262
Damien Georgeb035db32014-03-21 20:39:40 +00001263STATIC mp_obj_t str_partitioner(mp_obj_t self_in, mp_obj_t arg, machine_int_t direction) {
xbe613a8e32014-03-18 00:06:29 -07001264 assert(MP_OBJ_IS_STR(self_in));
1265 if (!MP_OBJ_IS_STR(arg)) {
Damien Georgedeed0872014-04-06 11:11:15 +01001266 bad_implicit_conversion(arg);
xbe613a8e32014-03-18 00:06:29 -07001267 }
Damien Georgeb035db32014-03-21 20:39:40 +00001268
xbe613a8e32014-03-18 00:06:29 -07001269 GET_STR_DATA_LEN(self_in, str, str_len);
1270 GET_STR_DATA_LEN(arg, sep, sep_len);
1271
1272 if (sep_len == 0) {
Damien Georgeea13f402014-04-05 18:32:08 +01001273 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
xbe613a8e32014-03-18 00:06:29 -07001274 }
Damien Georgeb035db32014-03-21 20:39:40 +00001275
1276 mp_obj_t result[] = {MP_OBJ_NEW_QSTR(MP_QSTR_), MP_OBJ_NEW_QSTR(MP_QSTR_), MP_OBJ_NEW_QSTR(MP_QSTR_)};
1277
1278 if (direction > 0) {
1279 result[0] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001280 } else {
Damien Georgeb035db32014-03-21 20:39:40 +00001281 result[2] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001282 }
xbe613a8e32014-03-18 00:06:29 -07001283
xbe17a5a832014-03-23 23:31:58 -07001284 const byte *position_ptr = find_subbytes(str, str_len, sep, sep_len, direction);
1285 if (position_ptr != NULL) {
1286 machine_uint_t position = position_ptr - str;
1287 result[0] = mp_obj_new_str(str, position, false);
1288 result[1] = arg;
1289 result[2] = mp_obj_new_str(str + position + sep_len, str_len - position - sep_len, false);
xbe613a8e32014-03-18 00:06:29 -07001290 }
Damien Georgeb035db32014-03-21 20:39:40 +00001291
xbe0a6894c2014-03-21 01:12:26 -07001292 return mp_obj_new_tuple(3, result);
xbe613a8e32014-03-18 00:06:29 -07001293}
1294
Damien Georgeb035db32014-03-21 20:39:40 +00001295STATIC mp_obj_t str_partition(mp_obj_t self_in, mp_obj_t arg) {
1296 return str_partitioner(self_in, arg, 1);
xbe0a6894c2014-03-21 01:12:26 -07001297}
xbe4504ea82014-03-19 00:46:14 -07001298
Damien Georgeb035db32014-03-21 20:39:40 +00001299STATIC mp_obj_t str_rpartition(mp_obj_t self_in, mp_obj_t arg) {
1300 return str_partitioner(self_in, arg, -1);
xbe4504ea82014-03-19 00:46:14 -07001301}
1302
Damien George2da98302014-03-09 19:58:18 +00001303STATIC machine_int_t str_get_buffer(mp_obj_t self_in, buffer_info_t *bufinfo, int flags) {
1304 if (flags == BUFFER_READ) {
1305 GET_STR_DATA_LEN(self_in, str_data, str_len);
1306 bufinfo->buf = (void*)str_data;
1307 bufinfo->len = str_len;
1308 return 0;
1309 } else {
1310 // can't write to a string
1311 bufinfo->buf = NULL;
1312 bufinfo->len = 0;
1313 return 1;
1314 }
1315}
1316
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001317STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_find_obj, 2, 4, str_find);
xbe17a5a832014-03-23 23:31:58 -07001318STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rfind_obj, 2, 4, str_rfind);
xbe3d9a39e2014-04-08 11:42:19 -07001319STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_index_obj, 2, 4, str_index);
1320STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rindex_obj, 2, 4, str_rindex);
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001321STATIC MP_DEFINE_CONST_FUN_OBJ_2(str_join_obj, str_join);
1322STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_split_obj, 1, 3, str_split);
1323STATIC MP_DEFINE_CONST_FUN_OBJ_2(str_startswith_obj, str_startswith);
1324STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_strip_obj, 1, 2, str_strip);
1325STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(str_format_obj, 1, str_format);
1326STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_replace_obj, 3, 4, str_replace);
xbe9e1e8cd2014-03-12 22:57:16 -07001327STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_count_obj, 2, 4, str_count);
xbe613a8e32014-03-18 00:06:29 -07001328STATIC MP_DEFINE_CONST_FUN_OBJ_2(str_partition_obj, str_partition);
xbe4504ea82014-03-19 00:46:14 -07001329STATIC MP_DEFINE_CONST_FUN_OBJ_2(str_rpartition_obj, str_rpartition);
Damiend99b0522013-12-21 18:17:45 +00001330
Damien George9b196cd2014-03-26 21:47:19 +00001331STATIC const mp_map_elem_t str_locals_dict_table[] = {
1332 { MP_OBJ_NEW_QSTR(MP_QSTR_find), (mp_obj_t)&str_find_obj },
1333 { MP_OBJ_NEW_QSTR(MP_QSTR_rfind), (mp_obj_t)&str_rfind_obj },
xbe3d9a39e2014-04-08 11:42:19 -07001334 { MP_OBJ_NEW_QSTR(MP_QSTR_index), (mp_obj_t)&str_index_obj },
1335 { MP_OBJ_NEW_QSTR(MP_QSTR_rindex), (mp_obj_t)&str_rindex_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001336 { MP_OBJ_NEW_QSTR(MP_QSTR_join), (mp_obj_t)&str_join_obj },
1337 { MP_OBJ_NEW_QSTR(MP_QSTR_split), (mp_obj_t)&str_split_obj },
1338 { MP_OBJ_NEW_QSTR(MP_QSTR_startswith), (mp_obj_t)&str_startswith_obj },
1339 { MP_OBJ_NEW_QSTR(MP_QSTR_strip), (mp_obj_t)&str_strip_obj },
1340 { MP_OBJ_NEW_QSTR(MP_QSTR_format), (mp_obj_t)&str_format_obj },
1341 { MP_OBJ_NEW_QSTR(MP_QSTR_replace), (mp_obj_t)&str_replace_obj },
1342 { MP_OBJ_NEW_QSTR(MP_QSTR_count), (mp_obj_t)&str_count_obj },
1343 { MP_OBJ_NEW_QSTR(MP_QSTR_partition), (mp_obj_t)&str_partition_obj },
1344 { MP_OBJ_NEW_QSTR(MP_QSTR_rpartition), (mp_obj_t)&str_rpartition_obj },
ian-v7a16fad2014-01-06 09:52:29 -08001345};
Damien George97209d32014-01-07 15:58:30 +00001346
Damien George9b196cd2014-03-26 21:47:19 +00001347STATIC MP_DEFINE_CONST_DICT(str_locals_dict, str_locals_dict_table);
1348
Damien George3e1a5c12014-03-29 13:43:38 +00001349const mp_obj_type_t mp_type_str = {
Damien Georgec5966122014-02-15 16:10:44 +00001350 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001351 .name = MP_QSTR_str,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001352 .print = str_print,
Paul Sokolovskybe020c22014-03-21 11:39:01 +02001353 .make_new = str_make_new,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001354 .binary_op = str_binary_op,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001355 .getiter = mp_obj_new_str_iterator,
Damien George2da98302014-03-09 19:58:18 +00001356 .buffer_p = { .get_buffer = str_get_buffer },
Damien George9b196cd2014-03-26 21:47:19 +00001357 .locals_dict = (mp_obj_t)&str_locals_dict,
Damiend99b0522013-12-21 18:17:45 +00001358};
1359
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001360// Reuses most of methods from str
Damien George3e1a5c12014-03-29 13:43:38 +00001361const mp_obj_type_t mp_type_bytes = {
Damien Georgec5966122014-02-15 16:10:44 +00001362 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001363 .name = MP_QSTR_bytes,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001364 .print = str_print,
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001365 .make_new = bytes_make_new,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001366 .binary_op = str_binary_op,
1367 .getiter = mp_obj_new_bytes_iterator,
Paul Sokolovsky7a70a3a2014-04-08 17:30:47 +03001368 .buffer_p = { .get_buffer = str_get_buffer },
Damien George9b196cd2014-03-26 21:47:19 +00001369 .locals_dict = (mp_obj_t)&str_locals_dict,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001370};
1371
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001372// the zero-length bytes
Damien George3e1a5c12014-03-29 13:43:38 +00001373STATIC const mp_obj_str_t empty_bytes_obj = {{&mp_type_bytes}, 0, 0, NULL};
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001374const mp_obj_t mp_const_empty_bytes = (mp_obj_t)&empty_bytes_obj;
1375
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001376mp_obj_t mp_obj_str_builder_start(const mp_obj_type_t *type, uint len, byte **data) {
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001377 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001378 o->base.type = type;
Damien George5fa93b62014-01-22 14:35:10 +00001379 o->len = len;
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001380 byte *p = m_new(byte, len + 1);
1381 o->data = p;
1382 *data = p;
Damiend99b0522013-12-21 18:17:45 +00001383 return o;
1384}
1385
Damien George5fa93b62014-01-22 14:35:10 +00001386mp_obj_t mp_obj_str_builder_end(mp_obj_t o_in) {
Damien George5fa93b62014-01-22 14:35:10 +00001387 mp_obj_str_t *o = o_in;
1388 o->hash = qstr_compute_hash(o->data, o->len);
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001389 byte *p = (byte*)o->data;
1390 p[o->len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
Damien George5fa93b62014-01-22 14:35:10 +00001391 return o;
1392}
1393
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001394STATIC mp_obj_t str_new(const mp_obj_type_t *type, const byte* data, uint len) {
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001395 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001396 o->base.type = type;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001397 o->len = len;
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001398 if (data) {
1399 o->hash = qstr_compute_hash(data, len);
1400 byte *p = m_new(byte, len + 1);
1401 o->data = p;
1402 memcpy(p, data, len * sizeof(byte));
1403 p[len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
1404 }
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001405 return o;
1406}
1407
Damien George5fa93b62014-01-22 14:35:10 +00001408mp_obj_t mp_obj_new_str(const byte* data, uint len, bool make_qstr_if_not_already) {
1409 qstr q = qstr_find_strn(data, len);
1410 if (q != MP_QSTR_NULL) {
1411 // qstr with this data already exists
1412 return MP_OBJ_NEW_QSTR(q);
1413 } else if (make_qstr_if_not_already) {
1414 // no existing qstr, make a new one
1415 return MP_OBJ_NEW_QSTR(qstr_from_strn((const char*)data, len));
1416 } else {
1417 // no existing qstr, don't make one
Damien George3e1a5c12014-03-29 13:43:38 +00001418 return str_new(&mp_type_str, data, len);
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02001419 }
Damien George5fa93b62014-01-22 14:35:10 +00001420}
1421
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001422mp_obj_t mp_obj_new_bytes(const byte* data, uint len) {
Damien George3e1a5c12014-03-29 13:43:38 +00001423 return str_new(&mp_type_bytes, data, len);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001424}
1425
Damien George5fa93b62014-01-22 14:35:10 +00001426bool mp_obj_str_equal(mp_obj_t s1, mp_obj_t s2) {
1427 if (MP_OBJ_IS_QSTR(s1) && MP_OBJ_IS_QSTR(s2)) {
1428 return s1 == s2;
1429 } else {
1430 GET_STR_HASH(s1, h1);
1431 GET_STR_HASH(s2, h2);
1432 if (h1 != h2) {
1433 return false;
1434 }
1435 GET_STR_DATA_LEN(s1, d1, l1);
1436 GET_STR_DATA_LEN(s2, d2, l2);
1437 if (l1 != l2) {
1438 return false;
1439 }
Damien George1e708fe2014-01-23 18:27:51 +00001440 return memcmp(d1, d2, l1) == 0;
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02001441 }
Damien George5fa93b62014-01-22 14:35:10 +00001442}
1443
Damien Georgedeed0872014-04-06 11:11:15 +01001444STATIC void bad_implicit_conversion(mp_obj_t self_in) {
Damien Georgeea13f402014-04-05 18:32:08 +01001445 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, "Can't convert '%s' object to str implicitly", mp_obj_get_type_str(self_in)));
Damien Georgeb829b5c2014-01-25 13:51:19 +00001446}
1447
Damien George5fa93b62014-01-22 14:35:10 +00001448uint mp_obj_str_get_hash(mp_obj_t self_in) {
1449 if (MP_OBJ_IS_STR(self_in)) {
1450 GET_STR_HASH(self_in, h);
1451 return h;
1452 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001453 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001454 }
1455}
1456
1457uint mp_obj_str_get_len(mp_obj_t self_in) {
1458 if (MP_OBJ_IS_STR(self_in)) {
1459 GET_STR_LEN(self_in, l);
1460 return l;
1461 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001462 bad_implicit_conversion(self_in);
1463 }
1464}
1465
1466// use this if you will anyway convert the string to a qstr
1467// will be more efficient for the case where it's already a qstr
1468qstr mp_obj_str_get_qstr(mp_obj_t self_in) {
1469 if (MP_OBJ_IS_QSTR(self_in)) {
1470 return MP_OBJ_QSTR_VALUE(self_in);
Damien George3e1a5c12014-03-29 13:43:38 +00001471 } else if (MP_OBJ_IS_TYPE(self_in, &mp_type_str)) {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001472 mp_obj_str_t *self = self_in;
1473 return qstr_from_strn((char*)self->data, self->len);
1474 } else {
1475 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001476 }
1477}
1478
1479// only use this function if you need the str data to be zero terminated
1480// at the moment all strings are zero terminated to help with C ASCIIZ compatibility
1481const char *mp_obj_str_get_str(mp_obj_t self_in) {
1482 if (MP_OBJ_IS_STR(self_in)) {
1483 GET_STR_DATA_LEN(self_in, s, l);
1484 (void)l; // len unused
1485 return (const char*)s;
1486 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001487 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001488 }
1489}
1490
Damien George698ec212014-02-08 18:17:23 +00001491const char *mp_obj_str_get_data(mp_obj_t self_in, uint *len) {
Damien George5fa93b62014-01-22 14:35:10 +00001492 if (MP_OBJ_IS_STR(self_in)) {
1493 GET_STR_DATA_LEN(self_in, s, l);
1494 *len = l;
Damien George698ec212014-02-08 18:17:23 +00001495 return (const char*)s;
Damien George5fa93b62014-01-22 14:35:10 +00001496 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001497 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001498 }
Damiend99b0522013-12-21 18:17:45 +00001499}
xyb8cfc9f02014-01-05 18:47:51 +08001500
1501/******************************************************************************/
1502/* str iterator */
1503
1504typedef struct _mp_obj_str_it_t {
1505 mp_obj_base_t base;
Damien George5fa93b62014-01-22 14:35:10 +00001506 mp_obj_t str;
xyb8cfc9f02014-01-05 18:47:51 +08001507 machine_uint_t cur;
1508} mp_obj_str_it_t;
1509
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001510STATIC mp_obj_t str_it_iternext(mp_obj_t self_in) {
xyb8cfc9f02014-01-05 18:47:51 +08001511 mp_obj_str_it_t *self = self_in;
Damien George5fa93b62014-01-22 14:35:10 +00001512 GET_STR_DATA_LEN(self->str, str, len);
1513 if (self->cur < len) {
1514 mp_obj_t o_out = mp_obj_new_str(str + self->cur, 1, true);
xyb8cfc9f02014-01-05 18:47:51 +08001515 self->cur += 1;
1516 return o_out;
1517 } else {
Damien George66eaf842014-03-26 19:27:58 +00001518 return MP_OBJ_NULL;
xyb8cfc9f02014-01-05 18:47:51 +08001519 }
1520}
1521
Damien George3e1a5c12014-03-29 13:43:38 +00001522STATIC const mp_obj_type_t mp_type_str_it = {
Damien Georgec5966122014-02-15 16:10:44 +00001523 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001524 .name = MP_QSTR_iterator,
Paul Sokolovskyf7eaf602014-03-30 22:00:12 +03001525 .getiter = mp_identity,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001526 .iternext = str_it_iternext,
xyb8cfc9f02014-01-05 18:47:51 +08001527};
1528
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001529STATIC mp_obj_t bytes_it_iternext(mp_obj_t self_in) {
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001530 mp_obj_str_it_t *self = self_in;
1531 GET_STR_DATA_LEN(self->str, str, len);
1532 if (self->cur < len) {
Damien George7c9c6672014-01-25 00:17:36 +00001533 mp_obj_t o_out = MP_OBJ_NEW_SMALL_INT((mp_small_int_t)str[self->cur]);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001534 self->cur += 1;
1535 return o_out;
1536 } else {
Damien George66eaf842014-03-26 19:27:58 +00001537 return MP_OBJ_NULL;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001538 }
1539}
1540
Damien George3e1a5c12014-03-29 13:43:38 +00001541STATIC const mp_obj_type_t mp_type_bytes_it = {
Damien Georgec5966122014-02-15 16:10:44 +00001542 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001543 .name = MP_QSTR_iterator,
Paul Sokolovskyf7eaf602014-03-30 22:00:12 +03001544 .getiter = mp_identity,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001545 .iternext = bytes_it_iternext,
1546};
1547
1548mp_obj_t mp_obj_new_str_iterator(mp_obj_t str) {
xyb8cfc9f02014-01-05 18:47:51 +08001549 mp_obj_str_it_t *o = m_new_obj(mp_obj_str_it_t);
Damien George3e1a5c12014-03-29 13:43:38 +00001550 o->base.type = &mp_type_str_it;
xyb8cfc9f02014-01-05 18:47:51 +08001551 o->str = str;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001552 o->cur = 0;
1553 return o;
1554}
1555
1556mp_obj_t mp_obj_new_bytes_iterator(mp_obj_t str) {
1557 mp_obj_str_it_t *o = m_new_obj(mp_obj_str_it_t);
Damien George3e1a5c12014-03-29 13:43:38 +00001558 o->base.type = &mp_type_bytes_it;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001559 o->str = str;
1560 o->cur = 0;
xyb8cfc9f02014-01-05 18:47:51 +08001561 return o;
1562}