blob: 39c24205be537b71888894b61d626a132498e11e [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
Paul Sokolovsky881d9af2014-04-10 01:42:40 +0300333 // TODO: Try to optimize?
Damien Georgea157e4c2014-04-09 19:17:53 +0100334 arg = mp_type_list.make_new((mp_obj_t)&mp_type_list, 1, 0, &arg);
335 }
336 mp_obj_list_get(arg, &seq_len, &seq_items);
Damiend99b0522013-12-21 18:17:45 +0000337 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000338
339 // count required length
340 int required_len = 0;
Damiend99b0522013-12-21 18:17:45 +0000341 for (int i = 0; i < seq_len; i++) {
Damien George5fa93b62014-01-22 14:35:10 +0000342 if (!MP_OBJ_IS_STR(seq_items[i])) {
Damien Georgea157e4c2014-04-09 19:17:53 +0100343 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "join expected a list of str's"));
Damiend99b0522013-12-21 18:17:45 +0000344 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000345 if (i > 0) {
346 required_len += sep_len;
347 }
Damien George5fa93b62014-01-22 14:35:10 +0000348 GET_STR_LEN(seq_items[i], l);
349 required_len += l;
Damiend99b0522013-12-21 18:17:45 +0000350 }
351
352 // make joined string
Damien George5fa93b62014-01-22 14:35:10 +0000353 byte *data;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +0200354 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 +0000355 for (int i = 0; i < seq_len; i++) {
Damiend99b0522013-12-21 18:17:45 +0000356 if (i > 0) {
Damien George5fa93b62014-01-22 14:35:10 +0000357 memcpy(data, sep_str, sep_len);
358 data += sep_len;
Damiend99b0522013-12-21 18:17:45 +0000359 }
Damien George5fa93b62014-01-22 14:35:10 +0000360 GET_STR_DATA_LEN(seq_items[i], s, l);
361 memcpy(data, s, l);
362 data += l;
Damiend99b0522013-12-21 18:17:45 +0000363 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000364
365 // return joined string
Damien George5fa93b62014-01-22 14:35:10 +0000366 return mp_obj_str_builder_end(joined_str);
Damiend99b0522013-12-21 18:17:45 +0000367}
368
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200369#define is_ws(c) ((c) == ' ' || (c) == '\t')
370
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200371STATIC mp_obj_t str_split(uint n_args, const mp_obj_t *args) {
Damien Georgedeed0872014-04-06 11:11:15 +0100372 machine_int_t splits = -1;
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200373 mp_obj_t sep = mp_const_none;
374 if (n_args > 1) {
375 sep = args[1];
376 if (n_args > 2) {
Damien Georgedeed0872014-04-06 11:11:15 +0100377 splits = mp_obj_get_int(args[2]);
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200378 }
379 }
Damien Georgedeed0872014-04-06 11:11:15 +0100380
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200381 mp_obj_t res = mp_obj_new_list(0, NULL);
Damien George5fa93b62014-01-22 14:35:10 +0000382 GET_STR_DATA_LEN(args[0], s, len);
383 const byte *top = s + len;
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200384
Damien Georgedeed0872014-04-06 11:11:15 +0100385 if (sep == mp_const_none) {
386 // sep not given, so separate on whitespace
387
388 // Initial whitespace is not counted as split, so we pre-do it
Damien George5fa93b62014-01-22 14:35:10 +0000389 while (s < top && is_ws(*s)) s++;
Damien Georgedeed0872014-04-06 11:11:15 +0100390 while (s < top && splits != 0) {
391 const byte *start = s;
392 while (s < top && !is_ws(*s)) s++;
393 mp_obj_list_append(res, mp_obj_new_str(start, s - start, false));
394 if (s >= top) {
395 break;
396 }
397 while (s < top && is_ws(*s)) s++;
398 if (splits > 0) {
399 splits--;
400 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200401 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200402
Damien Georgedeed0872014-04-06 11:11:15 +0100403 if (s < top) {
404 mp_obj_list_append(res, mp_obj_new_str(s, top - s, false));
405 }
406
407 } else {
408 // sep given
409
410 uint sep_len;
411 const char *sep_str = mp_obj_str_get_data(sep, &sep_len);
412
413 if (sep_len == 0) {
414 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
415 }
416
417 for (;;) {
418 const byte *start = s;
419 for (;;) {
420 if (splits == 0 || s + sep_len > top) {
421 s = top;
422 break;
423 } else if (memcmp(s, sep_str, sep_len) == 0) {
424 break;
425 }
426 s++;
427 }
428 mp_obj_list_append(res, mp_obj_new_str(start, s - start, false));
429 if (s >= top) {
430 break;
431 }
432 s += sep_len;
433 if (splits > 0) {
434 splits--;
435 }
436 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200437 }
438
439 return res;
440}
441
xbe3d9a39e2014-04-08 11:42:19 -0700442STATIC 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 +0000443 assert(2 <= n_args && n_args <= 4);
Damien George5fa93b62014-01-22 14:35:10 +0000444 assert(MP_OBJ_IS_STR(args[0]));
445 assert(MP_OBJ_IS_STR(args[1]));
John R. Lentone8204912014-01-12 21:53:52 +0000446
Damien George5fa93b62014-01-22 14:35:10 +0000447 GET_STR_DATA_LEN(args[0], haystack, haystack_len);
448 GET_STR_DATA_LEN(args[1], needle, needle_len);
John R. Lentone8204912014-01-12 21:53:52 +0000449
xbec5538882014-03-16 17:58:35 -0700450 machine_uint_t start = 0;
451 machine_uint_t end = haystack_len;
John R. Lentone8204912014-01-12 21:53:52 +0000452 if (n_args >= 3 && args[2] != mp_const_none) {
Damien George3e1a5c12014-03-29 13:43:38 +0000453 start = mp_get_index(&mp_type_str, haystack_len, args[2], true);
John R. Lentone8204912014-01-12 21:53:52 +0000454 }
455 if (n_args >= 4 && args[3] != mp_const_none) {
Damien George3e1a5c12014-03-29 13:43:38 +0000456 end = mp_get_index(&mp_type_str, haystack_len, args[3], true);
John R. Lentone8204912014-01-12 21:53:52 +0000457 }
458
xbe17a5a832014-03-23 23:31:58 -0700459 const byte *p = find_subbytes(haystack + start, end - start, needle, needle_len, direction);
Damien George23005372014-01-13 19:39:01 +0000460 if (p == NULL) {
461 // not found
xbe3d9a39e2014-04-08 11:42:19 -0700462 if (is_index) {
463 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "substring not found"));
464 } else {
465 return MP_OBJ_NEW_SMALL_INT(-1);
466 }
Damien George23005372014-01-13 19:39:01 +0000467 } else {
468 // found
xbe17a5a832014-03-23 23:31:58 -0700469 return MP_OBJ_NEW_SMALL_INT(p - haystack);
John R. Lentone8204912014-01-12 21:53:52 +0000470 }
John R. Lentone8204912014-01-12 21:53:52 +0000471}
472
xbe17a5a832014-03-23 23:31:58 -0700473STATIC mp_obj_t str_find(uint n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700474 return str_finder(n_args, args, 1, false);
xbe17a5a832014-03-23 23:31:58 -0700475}
476
477STATIC mp_obj_t str_rfind(uint n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700478 return str_finder(n_args, args, -1, false);
479}
480
481STATIC mp_obj_t str_index(uint n_args, const mp_obj_t *args) {
482 return str_finder(n_args, args, 1, true);
483}
484
485STATIC mp_obj_t str_rindex(uint n_args, const mp_obj_t *args) {
486 return str_finder(n_args, args, -1, true);
xbe17a5a832014-03-23 23:31:58 -0700487}
488
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200489// TODO: (Much) more variety in args
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200490STATIC mp_obj_t str_startswith(mp_obj_t self_in, mp_obj_t arg) {
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200491 GET_STR_DATA_LEN(self_in, str, str_len);
492 GET_STR_DATA_LEN(arg, prefix, prefix_len);
493 if (prefix_len > str_len) {
494 return mp_const_false;
495 }
496 return MP_BOOL(memcmp(str, prefix, prefix_len) == 0);
497}
498
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200499STATIC mp_obj_t str_strip(uint n_args, const mp_obj_t *args) {
xbe7b0f39f2014-01-08 14:23:45 -0800500 assert(1 <= n_args && n_args <= 2);
Damien George5fa93b62014-01-22 14:35:10 +0000501 assert(MP_OBJ_IS_STR(args[0]));
502
503 const byte *chars_to_del;
504 uint chars_to_del_len;
505 static const byte whitespace[] = " \t\n\r\v\f";
xbe7b0f39f2014-01-08 14:23:45 -0800506
507 if (n_args == 1) {
508 chars_to_del = whitespace;
Damien George5fa93b62014-01-22 14:35:10 +0000509 chars_to_del_len = sizeof(whitespace);
xbe7b0f39f2014-01-08 14:23:45 -0800510 } else {
Damien George5fa93b62014-01-22 14:35:10 +0000511 assert(MP_OBJ_IS_STR(args[1]));
512 GET_STR_DATA_LEN(args[1], s, l);
513 chars_to_del = s;
514 chars_to_del_len = l;
xbe7b0f39f2014-01-08 14:23:45 -0800515 }
516
Damien George5fa93b62014-01-22 14:35:10 +0000517 GET_STR_DATA_LEN(args[0], orig_str, orig_str_len);
xbe7b0f39f2014-01-08 14:23:45 -0800518
xbec5538882014-03-16 17:58:35 -0700519 machine_uint_t first_good_char_pos = 0;
xbe7b0f39f2014-01-08 14:23:45 -0800520 bool first_good_char_pos_set = false;
xbec5538882014-03-16 17:58:35 -0700521 machine_uint_t last_good_char_pos = 0;
522 for (machine_uint_t i = 0; i < orig_str_len; i++) {
xbe17a5a832014-03-23 23:31:58 -0700523 if (find_subbytes(chars_to_del, chars_to_del_len, &orig_str[i], 1, 1) == NULL) {
xbe7b0f39f2014-01-08 14:23:45 -0800524 last_good_char_pos = i;
525 if (!first_good_char_pos_set) {
526 first_good_char_pos = i;
527 first_good_char_pos_set = true;
528 }
529 }
530 }
531
532 if (first_good_char_pos == 0 && last_good_char_pos == 0) {
Damien George5fa93b62014-01-22 14:35:10 +0000533 // string is all whitespace, return ''
534 return MP_OBJ_NEW_QSTR(MP_QSTR_);
xbe7b0f39f2014-01-08 14:23:45 -0800535 }
536
537 assert(last_good_char_pos >= first_good_char_pos);
538 //+1 to accomodate the last character
xbec5538882014-03-16 17:58:35 -0700539 machine_uint_t stripped_len = last_good_char_pos - first_good_char_pos + 1;
Damien George5fa93b62014-01-22 14:35:10 +0000540 return mp_obj_new_str(orig_str + first_good_char_pos, stripped_len, false);
xbe7b0f39f2014-01-08 14:23:45 -0800541}
542
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700543// Takes an int arg, but only parses unsigned numbers, and only changes
544// *num if at least one digit was parsed.
545static int str_to_int(const char *str, int *num) {
546 const char *s = str;
547 if (unichar_isdigit(*s)) {
548 *num = 0;
549 do {
550 *num = *num * 10 + (*s - '0');
551 s++;
552 }
553 while (unichar_isdigit(*s));
554 }
555 return s - str;
556}
557
558static bool isalignment(char ch) {
559 return ch && strchr("<>=^", ch) != NULL;
560}
561
562static bool istype(char ch) {
563 return ch && strchr("bcdeEfFgGnosxX%", ch) != NULL;
564}
565
566static bool arg_looks_integer(mp_obj_t arg) {
567 return MP_OBJ_IS_TYPE(arg, &mp_type_bool) || MP_OBJ_IS_INT(arg);
568}
569
570static bool arg_looks_numeric(mp_obj_t arg) {
571 return arg_looks_integer(arg)
572#if MICROPY_ENABLE_FLOAT
573 || MP_OBJ_IS_TYPE(arg, &mp_type_float)
574#endif
575 ;
576}
577
Dave Hylandsc4029e52014-04-07 11:19:51 -0700578static mp_obj_t arg_as_int(mp_obj_t arg) {
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700579#if MICROPY_ENABLE_FLOAT
580 if (MP_OBJ_IS_TYPE(arg, &mp_type_float)) {
Dave Hylandsc4029e52014-04-07 11:19:51 -0700581
582 // TODO: Needs a way to construct an mpz integer from a float
583
584 mp_small_int_t num = mp_obj_get_float(arg);
585 return MP_OBJ_NEW_SMALL_INT(num);
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700586 }
587#endif
Dave Hylandsc4029e52014-04-07 11:19:51 -0700588 return arg;
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700589}
590
Damien Georgea11ceca2014-01-19 16:02:09 +0000591mp_obj_t str_format(uint n_args, const mp_obj_t *args) {
Damien George5fa93b62014-01-22 14:35:10 +0000592 assert(MP_OBJ_IS_STR(args[0]));
Damiend99b0522013-12-21 18:17:45 +0000593
Damien George5fa93b62014-01-22 14:35:10 +0000594 GET_STR_DATA_LEN(args[0], str, len);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700595 int arg_i = 0;
Damiend99b0522013-12-21 18:17:45 +0000596 vstr_t *vstr = vstr_new();
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700597 pfenv_t pfenv_vstr;
598 pfenv_vstr.data = vstr;
599 pfenv_vstr.print_strn = pfenv_vstr_add_strn;
600
Damien George5fa93b62014-01-22 14:35:10 +0000601 for (const byte *top = str + len; str < top; str++) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700602 if (*str == '}') {
Damiend99b0522013-12-21 18:17:45 +0000603 str++;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700604 if (str < top && *str == '}') {
605 vstr_add_char(vstr, '}');
606 continue;
607 }
Damien Georgeea13f402014-04-05 18:32:08 +0100608 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "Single '}' encountered in format string"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700609 }
610 if (*str != '{') {
611 vstr_add_char(vstr, *str);
612 continue;
613 }
614
615 str++;
616 if (str < top && *str == '{') {
617 vstr_add_char(vstr, '{');
618 continue;
619 }
620
621 // replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"
622
623 vstr_t *field_name = NULL;
624 char conversion = '\0';
625 vstr_t *format_spec = NULL;
626
627 if (str < top && *str != '}' && *str != '!' && *str != ':') {
628 field_name = vstr_new();
629 while (str < top && *str != '}' && *str != '!' && *str != ':') {
630 vstr_add_char(field_name, *str++);
631 }
632 vstr_add_char(field_name, '\0');
633 }
634
635 // conversion ::= "r" | "s"
636
637 if (str < top && *str == '!') {
638 str++;
639 if (str < top && (*str == 'r' || *str == 's')) {
640 conversion = *str++;
Paul Sokolovskyf2b796e2014-01-15 22:45:20 +0200641 } else {
Damien Georgeea13f402014-04-05 18:32:08 +0100642 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 -0700643 }
644 }
645
646 if (str < top && *str == ':') {
647 str++;
648 // {:} is the same as {}, which is the same as {!s}
649 // This makes a difference when passing in a True or False
650 // '{}'.format(True) returns 'True'
651 // '{:d}'.format(True) returns '1'
652 // So we treat {:} as {} and this later gets treated to be {!s}
653 if (*str != '}') {
654 format_spec = vstr_new();
655 while (str < top && *str != '}') {
656 vstr_add_char(format_spec, *str++);
Damiend99b0522013-12-21 18:17:45 +0000657 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700658 vstr_add_char(format_spec, '\0');
659 }
660 }
661 if (str >= top) {
Damien Georgeea13f402014-04-05 18:32:08 +0100662 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "unmatched '{' in format"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700663 }
664 if (*str != '}') {
Damien Georgeea13f402014-04-05 18:32:08 +0100665 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "expected ':' after format specifier"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700666 }
667
668 mp_obj_t arg = mp_const_none;
669
670 if (field_name) {
671 if (arg_i > 0) {
Damien Georgeea13f402014-04-05 18:32:08 +0100672 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 -0700673 }
674 int index;
675 if (str_to_int(vstr_str(field_name), &index) != vstr_len(field_name) - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100676 nlr_raise(mp_obj_new_exception_msg(&mp_type_KeyError, "attributes not supported yet"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700677 }
678 if (index >= n_args - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100679 nlr_raise(mp_obj_new_exception_msg(&mp_type_IndexError, "tuple index out of range"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700680 }
681 arg = args[index + 1];
682 arg_i = -1;
683 vstr_free(field_name);
684 field_name = NULL;
685 } else {
686 if (arg_i < 0) {
Damien Georgeea13f402014-04-05 18:32:08 +0100687 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 -0700688 }
689 if (arg_i >= n_args - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100690 nlr_raise(mp_obj_new_exception_msg(&mp_type_IndexError, "tuple index out of range"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700691 }
692 arg = args[arg_i + 1];
693 arg_i++;
694 }
695 if (!format_spec && !conversion) {
696 conversion = 's';
697 }
698 if (conversion) {
699 mp_print_kind_t print_kind;
700 if (conversion == 's') {
701 print_kind = PRINT_STR;
702 } else if (conversion == 'r') {
703 print_kind = PRINT_REPR;
704 } else {
Damien Georgeea13f402014-04-05 18:32:08 +0100705 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Unknown conversion specifier %c", conversion));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700706 }
707 vstr_t *arg_vstr = vstr_new();
708 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, arg_vstr, arg, print_kind);
709 arg = mp_obj_new_str((const byte *)vstr_str(arg_vstr), vstr_len(arg_vstr), false);
710 vstr_free(arg_vstr);
711 }
712
713 char sign = '\0';
714 char fill = '\0';
715 char align = '\0';
716 int width = -1;
717 int precision = -1;
718 char type = '\0';
719 int flags = 0;
720
721 if (format_spec) {
722 // The format specifier (from http://docs.python.org/2/library/string.html#formatspec)
723 //
724 // [[fill]align][sign][#][0][width][,][.precision][type]
725 // fill ::= <any character>
726 // align ::= "<" | ">" | "=" | "^"
727 // sign ::= "+" | "-" | " "
728 // width ::= integer
729 // precision ::= integer
730 // type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
731
732 const char *s = vstr_str(format_spec);
733 if (isalignment(*s)) {
734 align = *s++;
735 } else if (*s && isalignment(s[1])) {
736 fill = *s++;
737 align = *s++;
738 }
739 if (*s == '+' || *s == '-' || *s == ' ') {
740 if (*s == '+') {
741 flags |= PF_FLAG_SHOW_SIGN;
742 } else if (*s == ' ') {
743 flags |= PF_FLAG_SPACE_SIGN;
744 }
745 sign = *s++;
746 }
747 if (*s == '#') {
748 flags |= PF_FLAG_SHOW_PREFIX;
749 s++;
750 }
751 if (*s == '0') {
752 if (!align) {
753 align = '=';
754 }
755 if (!fill) {
756 fill = '0';
757 }
758 }
759 s += str_to_int(s, &width);
760 if (*s == ',') {
761 flags |= PF_FLAG_SHOW_COMMA;
762 s++;
763 }
764 if (*s == '.') {
765 s++;
766 s += str_to_int(s, &precision);
767 }
768 if (istype(*s)) {
769 type = *s++;
770 }
771 if (*s) {
Damien Georgeea13f402014-04-05 18:32:08 +0100772 nlr_raise(mp_obj_new_exception_msg(&mp_type_KeyError, "Invalid conversion specification"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700773 }
774 vstr_free(format_spec);
775 format_spec = NULL;
776 }
777 if (!align) {
778 if (arg_looks_numeric(arg)) {
779 align = '>';
780 } else {
781 align = '<';
782 }
783 }
784 if (!fill) {
785 fill = ' ';
786 }
787
788 if (sign) {
789 if (type == 's') {
Damien Georgeea13f402014-04-05 18:32:08 +0100790 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "Sign not allowed in string format specifier"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700791 }
792 if (type == 'c') {
Damien Georgeea13f402014-04-05 18:32:08 +0100793 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "Sign not allowed with integer format specifier 'c'"));
Damiend99b0522013-12-21 18:17:45 +0000794 }
795 } else {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700796 sign = '-';
797 }
798
799 switch (align) {
800 case '<': flags |= PF_FLAG_LEFT_ADJUST; break;
801 case '=': flags |= PF_FLAG_PAD_AFTER_SIGN; break;
802 case '^': flags |= PF_FLAG_CENTER_ADJUST; break;
803 }
804
805 if (arg_looks_integer(arg)) {
806 switch (type) {
807 case 'b':
Damien Georgea12a0f72014-04-08 01:29:53 +0100808 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 2, 'a', flags, fill, width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700809 continue;
810
811 case 'c':
812 {
813 char ch = mp_obj_get_int(arg);
814 pfenv_print_strn(&pfenv_vstr, &ch, 1, flags, fill, width);
815 continue;
816 }
817
818 case '\0': // No explicit format type implies 'd'
819 case 'n': // I don't think we support locales in uPy so use 'd'
820 case 'd':
Damien Georgea12a0f72014-04-08 01:29:53 +0100821 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 10, 'a', flags, fill, width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700822 continue;
823
824 case 'o':
Dave Hylandsc4029e52014-04-07 11:19:51 -0700825 if (flags & PF_FLAG_SHOW_PREFIX) {
826 flags |= PF_FLAG_SHOW_OCTAL_LETTER;
827 }
828
Damien Georgea12a0f72014-04-08 01:29:53 +0100829 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 8, 'a', flags, fill, width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700830 continue;
831
832 case 'x':
Damien Georgea12a0f72014-04-08 01:29:53 +0100833 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 16, 'a', flags, fill, width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700834 continue;
835
836 case 'X':
Damien Georgea12a0f72014-04-08 01:29:53 +0100837 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 16, 'A', flags, fill, width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700838 continue;
839
840 case 'e':
841 case 'E':
842 case 'f':
843 case 'F':
844 case 'g':
845 case 'G':
846 case '%':
847 // The floating point formatters all work with anything that
848 // looks like an integer
849 break;
850
851 default:
Damien Georgeea13f402014-04-05 18:32:08 +0100852 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700853 "Unknown format code '%c' for object of type '%s'", type, mp_obj_get_type_str(arg)));
854 }
Damien Georgec322c5f2014-04-02 20:04:15 +0100855 }
Damien George70f33cd2014-04-02 17:06:05 +0100856
Dave Hylands22fe4d72014-04-02 12:07:31 -0700857 // NOTE: no else here. We need the e, f, g etc formats for integer
858 // arguments (from above if) to take this if.
Damien Georgec322c5f2014-04-02 20:04:15 +0100859 if (arg_looks_numeric(arg)) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700860 if (!type) {
861
862 // Even though the docs say that an unspecified type is the same
863 // as 'g', there is one subtle difference, when the exponent
864 // is one less than the precision.
865 //
866 // '{:10.1}'.format(0.0) ==> '0e+00'
867 // '{:10.1g}'.format(0.0) ==> '0'
868 //
869 // TODO: Figure out how to deal with this.
870 //
871 // A proper solution would involve adding a special flag
872 // or something to format_float, and create a format_double
873 // to deal with doubles. In order to fix this when using
874 // sprintf, we'd need to use the e format and tweak the
875 // returned result to strip trailing zeros like the g format
876 // does.
877 //
878 // {:10.3} and {:10.2e} with 1.23e2 both produce 1.23e+02
879 // but with 1.e2 you get 1e+02 and 1.00e+02
880 //
881 // Stripping the trailing 0's (like g) does would make the
882 // e format give us the right format.
883 //
884 // CPython sources say:
885 // Omitted type specifier. Behaves in the same way as repr(x)
886 // and str(x) if no precision is given, else like 'g', but with
887 // at least one digit after the decimal point. */
888
889 type = 'g';
890 }
891 if (type == 'n') {
892 type = 'g';
893 }
894
895 flags |= PF_FLAG_PAD_NAN_INF; // '{:06e}'.format(float('-inf')) should give '-00inf'
896 switch (type) {
Damien Georgec322c5f2014-04-02 20:04:15 +0100897#if MICROPY_ENABLE_FLOAT
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700898 case 'e':
899 case 'E':
900 case 'f':
901 case 'F':
902 case 'g':
903 case 'G':
904 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg), type, flags, fill, width, precision);
905 break;
906
907 case '%':
908 flags |= PF_FLAG_ADD_PERCENT;
909 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg) * 100.0F, 'f', flags, fill, width, precision);
910 break;
Damien Georgec322c5f2014-04-02 20:04:15 +0100911#endif
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700912
913 default:
Damien Georgeea13f402014-04-05 18:32:08 +0100914 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700915 "Unknown format code '%c' for object of type 'float'",
916 type, mp_obj_get_type_str(arg)));
917 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700918 } else {
Damien George70f33cd2014-04-02 17:06:05 +0100919 // arg doesn't look like a number
920
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700921 if (align == '=') {
Damien Georgeea13f402014-04-05 18:32:08 +0100922 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "'=' alignment not allowed in string format specifier"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700923 }
Damien George70f33cd2014-04-02 17:06:05 +0100924
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700925 switch (type) {
926 case '\0':
927 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, vstr, arg, PRINT_STR);
928 break;
929
930 case 's':
931 {
932 uint len;
933 const char *s = mp_obj_str_get_data(arg, &len);
934 if (precision < 0) {
935 precision = len;
936 }
937 if (len > precision) {
938 len = precision;
939 }
940 pfenv_print_strn(&pfenv_vstr, s, len, flags, fill, width);
941 break;
942 }
943
944 default:
Damien Georgeea13f402014-04-05 18:32:08 +0100945 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700946 "Unknown format code '%c' for object of type 'str'",
947 type, mp_obj_get_type_str(arg)));
948 }
Damiend99b0522013-12-21 18:17:45 +0000949 }
950 }
951
Damien George5fa93b62014-01-22 14:35:10 +0000952 mp_obj_t s = mp_obj_new_str((byte*)vstr->buf, vstr->len, false);
953 vstr_free(vstr);
954 return s;
Damiend99b0522013-12-21 18:17:45 +0000955}
956
Paul Sokolovsky4db727a2014-03-31 21:18:28 +0300957STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, uint n_args, const mp_obj_t *args) {
958 assert(MP_OBJ_IS_STR(pattern));
959
960 GET_STR_DATA_LEN(pattern, str, len);
Dave Hylands6756a372014-04-02 11:42:39 -0700961 const byte *start_str = str;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +0300962 int arg_i = 0;
963 vstr_t *vstr = vstr_new();
Dave Hylands6756a372014-04-02 11:42:39 -0700964 pfenv_t pfenv_vstr;
965 pfenv_vstr.data = vstr;
966 pfenv_vstr.print_strn = pfenv_vstr_add_strn;
967
Paul Sokolovsky4db727a2014-03-31 21:18:28 +0300968 for (const byte *top = str + len; str < top; str++) {
Dave Hylands6756a372014-04-02 11:42:39 -0700969 if (*str != '%') {
970 vstr_add_char(vstr, *str);
971 continue;
972 }
973 if (++str >= top) {
974 break;
975 }
Paul Sokolovsky4db727a2014-03-31 21:18:28 +0300976 if (*str == '%') {
Dave Hylands6756a372014-04-02 11:42:39 -0700977 vstr_add_char(vstr, '%');
978 continue;
979 }
980 if (arg_i >= n_args) {
Damien Georgeea13f402014-04-05 18:32:08 +0100981 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "not enough arguments for format string"));
Dave Hylands6756a372014-04-02 11:42:39 -0700982 }
983 int flags = 0;
984 char fill = ' ';
985 bool alt = false;
986 while (str < top) {
987 if (*str == '-') flags |= PF_FLAG_LEFT_ADJUST;
988 else if (*str == '+') flags |= PF_FLAG_SHOW_SIGN;
989 else if (*str == ' ') flags |= PF_FLAG_SPACE_SIGN;
990 else if (*str == '#') alt = true;
991 else if (*str == '0') {
992 flags |= PF_FLAG_PAD_AFTER_SIGN;
993 fill = '0';
994 } else break;
995 str++;
996 }
997 // parse width, if it exists
998 int width = 0;
999 if (str < top) {
1000 if (*str == '*') {
1001 width = mp_obj_get_int(args[arg_i++]);
1002 str++;
1003 } else {
1004 for (; str < top && '0' <= *str && *str <= '9'; str++) {
1005 width = width * 10 + *str - '0';
1006 }
1007 }
1008 }
1009 int prec = -1;
1010 if (str < top && *str == '.') {
1011 if (++str < top) {
1012 if (*str == '*') {
1013 prec = mp_obj_get_int(args[arg_i++]);
1014 str++;
1015 } else {
1016 prec = 0;
1017 for (; str < top && '0' <= *str && *str <= '9'; str++) {
1018 prec = prec * 10 + *str - '0';
1019 }
1020 }
1021 }
1022 }
1023
1024 if (str >= top) {
Damien Georgeea13f402014-04-05 18:32:08 +01001025 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "incomplete format"));
Dave Hylands6756a372014-04-02 11:42:39 -07001026 }
1027 mp_obj_t arg = args[arg_i];
1028 switch (*str) {
1029 case 'c':
1030 if (MP_OBJ_IS_STR(arg)) {
1031 uint len;
1032 const char *s = mp_obj_str_get_data(arg, &len);
1033 if (len != 1) {
Damien Georgeea13f402014-04-05 18:32:08 +01001034 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "%c requires int or char"));
Dave Hylands6756a372014-04-02 11:42:39 -07001035 break;
1036 }
1037 pfenv_print_strn(&pfenv_vstr, s, 1, flags, ' ', width);
1038 break;
1039 }
1040 if (arg_looks_integer(arg)) {
1041 char ch = mp_obj_get_int(arg);
1042 pfenv_print_strn(&pfenv_vstr, &ch, 1, flags, ' ', width);
1043 break;
1044 }
1045#if MICROPY_ENABLE_FLOAT
1046 // This is what CPython reports, so we report the same.
1047 if (MP_OBJ_IS_TYPE(arg, &mp_type_float)) {
Damien Georgeea13f402014-04-05 18:32:08 +01001048 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "integer argument expected, got float"));
Dave Hylands6756a372014-04-02 11:42:39 -07001049
1050 }
1051#endif
Damien Georgeea13f402014-04-05 18:32:08 +01001052 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "an integer is required"));
Dave Hylands6756a372014-04-02 11:42:39 -07001053 break;
1054
1055 case 'd':
1056 case 'i':
1057 case 'u':
Damien Georgea12a0f72014-04-08 01:29:53 +01001058 pfenv_print_mp_int(&pfenv_vstr, arg_as_int(arg), 1, 10, 'a', flags, fill, width);
Dave Hylands6756a372014-04-02 11:42:39 -07001059 break;
1060
1061#if MICROPY_ENABLE_FLOAT
1062 case 'e':
1063 case 'E':
1064 case 'f':
1065 case 'F':
1066 case 'g':
1067 case 'G':
1068 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg), *str, flags, fill, width, prec);
1069 break;
1070#endif
1071
1072 case 'o':
1073 if (alt) {
Dave Hylandsc4029e52014-04-07 11:19:51 -07001074 flags |= (PF_FLAG_SHOW_PREFIX | PF_FLAG_SHOW_OCTAL_LETTER);
Dave Hylands6756a372014-04-02 11:42:39 -07001075 }
Damien Georgea12a0f72014-04-08 01:29:53 +01001076 pfenv_print_mp_int(&pfenv_vstr, arg_as_int(arg), 1, 8, 'a', flags, fill, width);
Dave Hylands6756a372014-04-02 11:42:39 -07001077 break;
1078
1079 case 'r':
1080 case 's':
1081 {
1082 vstr_t *arg_vstr = vstr_new();
1083 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf,
1084 arg_vstr, arg, *str == 'r' ? PRINT_REPR : PRINT_STR);
1085 uint len = vstr_len(arg_vstr);
1086 if (prec < 0) {
1087 prec = len;
1088 }
1089 if (len > prec) {
1090 len = prec;
1091 }
1092 pfenv_print_strn(&pfenv_vstr, vstr_str(arg_vstr), len, flags, ' ', width);
1093 vstr_free(arg_vstr);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001094 break;
1095 }
Dave Hylands6756a372014-04-02 11:42:39 -07001096
1097 case 'x':
1098 if (alt) {
1099 flags |= PF_FLAG_SHOW_PREFIX;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001100 }
Damien Georgea12a0f72014-04-08 01:29:53 +01001101 pfenv_print_mp_int(&pfenv_vstr, arg_as_int(arg), 1, 16, 'a', flags, fill, width);
Dave Hylands6756a372014-04-02 11:42:39 -07001102 break;
1103
1104 case 'X':
1105 if (alt) {
1106 flags |= PF_FLAG_SHOW_PREFIX;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001107 }
Damien Georgea12a0f72014-04-08 01:29:53 +01001108 pfenv_print_mp_int(&pfenv_vstr, arg_as_int(arg), 1, 16, 'A', flags, fill, width);
Dave Hylands6756a372014-04-02 11:42:39 -07001109 break;
Damien Georgedeed0872014-04-06 11:11:15 +01001110
Dave Hylands6756a372014-04-02 11:42:39 -07001111 default:
Damien Georgeea13f402014-04-05 18:32:08 +01001112 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Dave Hylands6756a372014-04-02 11:42:39 -07001113 "unsupported format character '%c' (0x%x) at index %d",
1114 *str, *str, str - start_str));
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001115 }
Dave Hylands6756a372014-04-02 11:42:39 -07001116 arg_i++;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001117 }
1118
1119 if (arg_i != n_args) {
Damien Georgeea13f402014-04-05 18:32:08 +01001120 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "not all arguments converted during string formatting"));
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001121 }
1122
1123 mp_obj_t s = mp_obj_new_str((byte*)vstr->buf, vstr->len, false);
1124 vstr_free(vstr);
1125 return s;
1126}
1127
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001128STATIC mp_obj_t str_replace(uint n_args, const mp_obj_t *args) {
xbe480c15a2014-01-30 22:17:30 -08001129 assert(MP_OBJ_IS_STR(args[0]));
xbe480c15a2014-01-30 22:17:30 -08001130
Damien Georgeff715422014-04-07 00:39:13 +01001131 machine_int_t max_rep = -1;
xbe480c15a2014-01-30 22:17:30 -08001132 if (n_args == 4) {
Damien Georgeff715422014-04-07 00:39:13 +01001133 max_rep = mp_obj_get_int(args[3]);
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001134 if (max_rep == 0) {
1135 return args[0];
1136 } else if (max_rep < 0) {
Damien Georgeff715422014-04-07 00:39:13 +01001137 max_rep = -1;
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001138 }
xbe480c15a2014-01-30 22:17:30 -08001139 }
Damien George94f68302014-01-31 23:45:12 +00001140
xbe729be9b2014-04-07 14:46:39 -07001141 // if max_rep is still -1 by this point we will need to do all possible replacements
xbe480c15a2014-01-30 22:17:30 -08001142
Damien Georgeff715422014-04-07 00:39:13 +01001143 // check argument types
1144
1145 if (!MP_OBJ_IS_STR(args[1])) {
1146 bad_implicit_conversion(args[1]);
1147 }
1148
1149 if (!MP_OBJ_IS_STR(args[2])) {
1150 bad_implicit_conversion(args[2]);
1151 }
1152
1153 // extract string data
1154
xbe480c15a2014-01-30 22:17:30 -08001155 GET_STR_DATA_LEN(args[0], str, str_len);
1156 GET_STR_DATA_LEN(args[1], old, old_len);
1157 GET_STR_DATA_LEN(args[2], new, new_len);
Damien George94f68302014-01-31 23:45:12 +00001158
1159 // old won't exist in str if it's longer, so nothing to replace
xbe480c15a2014-01-30 22:17:30 -08001160 if (old_len > str_len) {
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001161 return args[0];
xbe480c15a2014-01-30 22:17:30 -08001162 }
1163
Damien George94f68302014-01-31 23:45:12 +00001164 // data for the replaced string
1165 byte *data = NULL;
1166 mp_obj_t replaced_str = MP_OBJ_NULL;
xbe480c15a2014-01-30 22:17:30 -08001167
Damien George94f68302014-01-31 23:45:12 +00001168 // do 2 passes over the string:
1169 // first pass computes the required length of the replaced string
1170 // second pass does the replacements
1171 for (;;) {
1172 machine_uint_t replaced_str_index = 0;
1173 machine_uint_t num_replacements_done = 0;
1174 const byte *old_occurrence;
1175 const byte *offset_ptr = str;
Damien Georgeff715422014-04-07 00:39:13 +01001176 machine_uint_t str_len_remain = str_len;
1177 if (old_len == 0) {
1178 // if old_str is empty, copy new_str to start of replaced string
1179 // copy the replacement string
1180 if (data != NULL) {
1181 memcpy(data, new, new_len);
1182 }
1183 replaced_str_index += new_len;
1184 num_replacements_done++;
1185 }
1186 while (num_replacements_done != max_rep && str_len_remain > 0 && (old_occurrence = find_subbytes(offset_ptr, str_len_remain, old, old_len, 1)) != NULL) {
1187 if (old_len == 0) {
1188 old_occurrence += 1;
1189 }
Damien George94f68302014-01-31 23:45:12 +00001190 // copy from just after end of last occurrence of to-be-replaced string to right before start of next occurrence
1191 if (data != NULL) {
1192 memcpy(data + replaced_str_index, offset_ptr, old_occurrence - offset_ptr);
1193 }
1194 replaced_str_index += old_occurrence - offset_ptr;
1195 // copy the replacement string
1196 if (data != NULL) {
1197 memcpy(data + replaced_str_index, new, new_len);
1198 }
1199 replaced_str_index += new_len;
1200 offset_ptr = old_occurrence + old_len;
Damien Georgeff715422014-04-07 00:39:13 +01001201 str_len_remain = str + str_len - offset_ptr;
Damien George94f68302014-01-31 23:45:12 +00001202 num_replacements_done++;
Damien George94f68302014-01-31 23:45:12 +00001203 }
1204
1205 // copy from just after end of last occurrence of to-be-replaced string to end of old string
1206 if (data != NULL) {
Damien Georgeff715422014-04-07 00:39:13 +01001207 memcpy(data + replaced_str_index, offset_ptr, str_len_remain);
Damien George94f68302014-01-31 23:45:12 +00001208 }
Damien Georgeff715422014-04-07 00:39:13 +01001209 replaced_str_index += str_len_remain;
Damien George94f68302014-01-31 23:45:12 +00001210
1211 if (data == NULL) {
1212 // first pass
1213 if (num_replacements_done == 0) {
1214 // no substr found, return original string
1215 return args[0];
1216 } else {
1217 // substr found, allocate new string
1218 replaced_str = mp_obj_str_builder_start(mp_obj_get_type(args[0]), replaced_str_index, &data);
Damien Georgeff715422014-04-07 00:39:13 +01001219 assert(data != NULL);
Damien George94f68302014-01-31 23:45:12 +00001220 }
1221 } else {
1222 // second pass, we are done
1223 break;
1224 }
xbe480c15a2014-01-30 22:17:30 -08001225 }
Damien George94f68302014-01-31 23:45:12 +00001226
xbe480c15a2014-01-30 22:17:30 -08001227 return mp_obj_str_builder_end(replaced_str);
1228}
1229
xbe9e1e8cd2014-03-12 22:57:16 -07001230STATIC mp_obj_t str_count(uint n_args, const mp_obj_t *args) {
1231 assert(2 <= n_args && n_args <= 4);
1232 assert(MP_OBJ_IS_STR(args[0]));
1233 assert(MP_OBJ_IS_STR(args[1]));
1234
1235 GET_STR_DATA_LEN(args[0], haystack, haystack_len);
1236 GET_STR_DATA_LEN(args[1], needle, needle_len);
1237
Damien George536dde22014-03-13 22:07:55 +00001238 machine_uint_t start = 0;
1239 machine_uint_t end = haystack_len;
xbe9e1e8cd2014-03-12 22:57:16 -07001240 if (n_args >= 3 && args[2] != mp_const_none) {
Damien George3e1a5c12014-03-29 13:43:38 +00001241 start = mp_get_index(&mp_type_str, haystack_len, args[2], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001242 }
1243 if (n_args >= 4 && args[3] != mp_const_none) {
Damien George3e1a5c12014-03-29 13:43:38 +00001244 end = mp_get_index(&mp_type_str, haystack_len, args[3], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001245 }
1246
Damien George536dde22014-03-13 22:07:55 +00001247 // if needle_len is zero then we count each gap between characters as an occurrence
1248 if (needle_len == 0) {
1249 return MP_OBJ_NEW_SMALL_INT(end - start + 1);
xbe9e1e8cd2014-03-12 22:57:16 -07001250 }
1251
Damien George536dde22014-03-13 22:07:55 +00001252 // count the occurrences
1253 machine_int_t num_occurrences = 0;
xbec5d70ba2014-03-13 00:29:15 -07001254 for (machine_uint_t haystack_index = start; haystack_index + needle_len <= end; haystack_index++) {
1255 if (memcmp(&haystack[haystack_index], needle, needle_len) == 0) {
1256 num_occurrences++;
1257 haystack_index += needle_len - 1;
1258 }
xbe9e1e8cd2014-03-12 22:57:16 -07001259 }
1260
1261 return MP_OBJ_NEW_SMALL_INT(num_occurrences);
1262}
1263
Damien Georgeb035db32014-03-21 20:39:40 +00001264STATIC mp_obj_t str_partitioner(mp_obj_t self_in, mp_obj_t arg, machine_int_t direction) {
xbe613a8e32014-03-18 00:06:29 -07001265 assert(MP_OBJ_IS_STR(self_in));
1266 if (!MP_OBJ_IS_STR(arg)) {
Damien Georgedeed0872014-04-06 11:11:15 +01001267 bad_implicit_conversion(arg);
xbe613a8e32014-03-18 00:06:29 -07001268 }
Damien Georgeb035db32014-03-21 20:39:40 +00001269
xbe613a8e32014-03-18 00:06:29 -07001270 GET_STR_DATA_LEN(self_in, str, str_len);
1271 GET_STR_DATA_LEN(arg, sep, sep_len);
1272
1273 if (sep_len == 0) {
Damien Georgeea13f402014-04-05 18:32:08 +01001274 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
xbe613a8e32014-03-18 00:06:29 -07001275 }
Damien Georgeb035db32014-03-21 20:39:40 +00001276
1277 mp_obj_t result[] = {MP_OBJ_NEW_QSTR(MP_QSTR_), MP_OBJ_NEW_QSTR(MP_QSTR_), MP_OBJ_NEW_QSTR(MP_QSTR_)};
1278
1279 if (direction > 0) {
1280 result[0] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001281 } else {
Damien Georgeb035db32014-03-21 20:39:40 +00001282 result[2] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001283 }
xbe613a8e32014-03-18 00:06:29 -07001284
xbe17a5a832014-03-23 23:31:58 -07001285 const byte *position_ptr = find_subbytes(str, str_len, sep, sep_len, direction);
1286 if (position_ptr != NULL) {
1287 machine_uint_t position = position_ptr - str;
1288 result[0] = mp_obj_new_str(str, position, false);
1289 result[1] = arg;
1290 result[2] = mp_obj_new_str(str + position + sep_len, str_len - position - sep_len, false);
xbe613a8e32014-03-18 00:06:29 -07001291 }
Damien Georgeb035db32014-03-21 20:39:40 +00001292
xbe0a6894c2014-03-21 01:12:26 -07001293 return mp_obj_new_tuple(3, result);
xbe613a8e32014-03-18 00:06:29 -07001294}
1295
Damien Georgeb035db32014-03-21 20:39:40 +00001296STATIC mp_obj_t str_partition(mp_obj_t self_in, mp_obj_t arg) {
1297 return str_partitioner(self_in, arg, 1);
xbe0a6894c2014-03-21 01:12:26 -07001298}
xbe4504ea82014-03-19 00:46:14 -07001299
Damien Georgeb035db32014-03-21 20:39:40 +00001300STATIC mp_obj_t str_rpartition(mp_obj_t self_in, mp_obj_t arg) {
1301 return str_partitioner(self_in, arg, -1);
xbe4504ea82014-03-19 00:46:14 -07001302}
1303
Damien George2da98302014-03-09 19:58:18 +00001304STATIC machine_int_t str_get_buffer(mp_obj_t self_in, buffer_info_t *bufinfo, int flags) {
1305 if (flags == BUFFER_READ) {
1306 GET_STR_DATA_LEN(self_in, str_data, str_len);
1307 bufinfo->buf = (void*)str_data;
1308 bufinfo->len = str_len;
1309 return 0;
1310 } else {
1311 // can't write to a string
1312 bufinfo->buf = NULL;
1313 bufinfo->len = 0;
1314 return 1;
1315 }
1316}
1317
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001318STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_find_obj, 2, 4, str_find);
xbe17a5a832014-03-23 23:31:58 -07001319STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rfind_obj, 2, 4, str_rfind);
xbe3d9a39e2014-04-08 11:42:19 -07001320STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_index_obj, 2, 4, str_index);
1321STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rindex_obj, 2, 4, str_rindex);
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001322STATIC MP_DEFINE_CONST_FUN_OBJ_2(str_join_obj, str_join);
1323STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_split_obj, 1, 3, str_split);
1324STATIC MP_DEFINE_CONST_FUN_OBJ_2(str_startswith_obj, str_startswith);
1325STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_strip_obj, 1, 2, str_strip);
1326STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(str_format_obj, 1, str_format);
1327STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_replace_obj, 3, 4, str_replace);
xbe9e1e8cd2014-03-12 22:57:16 -07001328STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_count_obj, 2, 4, str_count);
xbe613a8e32014-03-18 00:06:29 -07001329STATIC MP_DEFINE_CONST_FUN_OBJ_2(str_partition_obj, str_partition);
xbe4504ea82014-03-19 00:46:14 -07001330STATIC MP_DEFINE_CONST_FUN_OBJ_2(str_rpartition_obj, str_rpartition);
Damiend99b0522013-12-21 18:17:45 +00001331
Damien George9b196cd2014-03-26 21:47:19 +00001332STATIC const mp_map_elem_t str_locals_dict_table[] = {
1333 { MP_OBJ_NEW_QSTR(MP_QSTR_find), (mp_obj_t)&str_find_obj },
1334 { MP_OBJ_NEW_QSTR(MP_QSTR_rfind), (mp_obj_t)&str_rfind_obj },
xbe3d9a39e2014-04-08 11:42:19 -07001335 { MP_OBJ_NEW_QSTR(MP_QSTR_index), (mp_obj_t)&str_index_obj },
1336 { MP_OBJ_NEW_QSTR(MP_QSTR_rindex), (mp_obj_t)&str_rindex_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001337 { MP_OBJ_NEW_QSTR(MP_QSTR_join), (mp_obj_t)&str_join_obj },
1338 { MP_OBJ_NEW_QSTR(MP_QSTR_split), (mp_obj_t)&str_split_obj },
1339 { MP_OBJ_NEW_QSTR(MP_QSTR_startswith), (mp_obj_t)&str_startswith_obj },
1340 { MP_OBJ_NEW_QSTR(MP_QSTR_strip), (mp_obj_t)&str_strip_obj },
1341 { MP_OBJ_NEW_QSTR(MP_QSTR_format), (mp_obj_t)&str_format_obj },
1342 { MP_OBJ_NEW_QSTR(MP_QSTR_replace), (mp_obj_t)&str_replace_obj },
1343 { MP_OBJ_NEW_QSTR(MP_QSTR_count), (mp_obj_t)&str_count_obj },
1344 { MP_OBJ_NEW_QSTR(MP_QSTR_partition), (mp_obj_t)&str_partition_obj },
1345 { MP_OBJ_NEW_QSTR(MP_QSTR_rpartition), (mp_obj_t)&str_rpartition_obj },
ian-v7a16fad2014-01-06 09:52:29 -08001346};
Damien George97209d32014-01-07 15:58:30 +00001347
Damien George9b196cd2014-03-26 21:47:19 +00001348STATIC MP_DEFINE_CONST_DICT(str_locals_dict, str_locals_dict_table);
1349
Damien George3e1a5c12014-03-29 13:43:38 +00001350const mp_obj_type_t mp_type_str = {
Damien Georgec5966122014-02-15 16:10:44 +00001351 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001352 .name = MP_QSTR_str,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001353 .print = str_print,
Paul Sokolovskybe020c22014-03-21 11:39:01 +02001354 .make_new = str_make_new,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001355 .binary_op = str_binary_op,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001356 .getiter = mp_obj_new_str_iterator,
Damien George2da98302014-03-09 19:58:18 +00001357 .buffer_p = { .get_buffer = str_get_buffer },
Damien George9b196cd2014-03-26 21:47:19 +00001358 .locals_dict = (mp_obj_t)&str_locals_dict,
Damiend99b0522013-12-21 18:17:45 +00001359};
1360
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001361// Reuses most of methods from str
Damien George3e1a5c12014-03-29 13:43:38 +00001362const mp_obj_type_t mp_type_bytes = {
Damien Georgec5966122014-02-15 16:10:44 +00001363 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001364 .name = MP_QSTR_bytes,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001365 .print = str_print,
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001366 .make_new = bytes_make_new,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001367 .binary_op = str_binary_op,
1368 .getiter = mp_obj_new_bytes_iterator,
Paul Sokolovsky7a70a3a2014-04-08 17:30:47 +03001369 .buffer_p = { .get_buffer = str_get_buffer },
Damien George9b196cd2014-03-26 21:47:19 +00001370 .locals_dict = (mp_obj_t)&str_locals_dict,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001371};
1372
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001373// the zero-length bytes
Damien George3e1a5c12014-03-29 13:43:38 +00001374STATIC const mp_obj_str_t empty_bytes_obj = {{&mp_type_bytes}, 0, 0, NULL};
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001375const mp_obj_t mp_const_empty_bytes = (mp_obj_t)&empty_bytes_obj;
1376
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001377mp_obj_t mp_obj_str_builder_start(const mp_obj_type_t *type, uint len, byte **data) {
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001378 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001379 o->base.type = type;
Damien George5fa93b62014-01-22 14:35:10 +00001380 o->len = len;
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001381 byte *p = m_new(byte, len + 1);
1382 o->data = p;
1383 *data = p;
Damiend99b0522013-12-21 18:17:45 +00001384 return o;
1385}
1386
Damien George5fa93b62014-01-22 14:35:10 +00001387mp_obj_t mp_obj_str_builder_end(mp_obj_t o_in) {
Damien George5fa93b62014-01-22 14:35:10 +00001388 mp_obj_str_t *o = o_in;
1389 o->hash = qstr_compute_hash(o->data, o->len);
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001390 byte *p = (byte*)o->data;
1391 p[o->len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
Damien George5fa93b62014-01-22 14:35:10 +00001392 return o;
1393}
1394
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001395STATIC mp_obj_t str_new(const mp_obj_type_t *type, const byte* data, uint len) {
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001396 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001397 o->base.type = type;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001398 o->len = len;
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001399 if (data) {
1400 o->hash = qstr_compute_hash(data, len);
1401 byte *p = m_new(byte, len + 1);
1402 o->data = p;
1403 memcpy(p, data, len * sizeof(byte));
1404 p[len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
1405 }
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001406 return o;
1407}
1408
Damien George5fa93b62014-01-22 14:35:10 +00001409mp_obj_t mp_obj_new_str(const byte* data, uint len, bool make_qstr_if_not_already) {
1410 qstr q = qstr_find_strn(data, len);
1411 if (q != MP_QSTR_NULL) {
1412 // qstr with this data already exists
1413 return MP_OBJ_NEW_QSTR(q);
1414 } else if (make_qstr_if_not_already) {
1415 // no existing qstr, make a new one
1416 return MP_OBJ_NEW_QSTR(qstr_from_strn((const char*)data, len));
1417 } else {
1418 // no existing qstr, don't make one
Damien George3e1a5c12014-03-29 13:43:38 +00001419 return str_new(&mp_type_str, data, len);
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02001420 }
Damien George5fa93b62014-01-22 14:35:10 +00001421}
1422
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001423mp_obj_t mp_obj_new_bytes(const byte* data, uint len) {
Damien George3e1a5c12014-03-29 13:43:38 +00001424 return str_new(&mp_type_bytes, data, len);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001425}
1426
Damien George5fa93b62014-01-22 14:35:10 +00001427bool mp_obj_str_equal(mp_obj_t s1, mp_obj_t s2) {
1428 if (MP_OBJ_IS_QSTR(s1) && MP_OBJ_IS_QSTR(s2)) {
1429 return s1 == s2;
1430 } else {
1431 GET_STR_HASH(s1, h1);
1432 GET_STR_HASH(s2, h2);
1433 if (h1 != h2) {
1434 return false;
1435 }
1436 GET_STR_DATA_LEN(s1, d1, l1);
1437 GET_STR_DATA_LEN(s2, d2, l2);
1438 if (l1 != l2) {
1439 return false;
1440 }
Damien George1e708fe2014-01-23 18:27:51 +00001441 return memcmp(d1, d2, l1) == 0;
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02001442 }
Damien George5fa93b62014-01-22 14:35:10 +00001443}
1444
Damien Georgedeed0872014-04-06 11:11:15 +01001445STATIC void bad_implicit_conversion(mp_obj_t self_in) {
Damien Georgeea13f402014-04-05 18:32:08 +01001446 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 +00001447}
1448
Damien George5fa93b62014-01-22 14:35:10 +00001449uint mp_obj_str_get_hash(mp_obj_t self_in) {
1450 if (MP_OBJ_IS_STR(self_in)) {
1451 GET_STR_HASH(self_in, h);
1452 return h;
1453 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001454 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001455 }
1456}
1457
1458uint mp_obj_str_get_len(mp_obj_t self_in) {
1459 if (MP_OBJ_IS_STR(self_in)) {
1460 GET_STR_LEN(self_in, l);
1461 return l;
1462 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001463 bad_implicit_conversion(self_in);
1464 }
1465}
1466
1467// use this if you will anyway convert the string to a qstr
1468// will be more efficient for the case where it's already a qstr
1469qstr mp_obj_str_get_qstr(mp_obj_t self_in) {
1470 if (MP_OBJ_IS_QSTR(self_in)) {
1471 return MP_OBJ_QSTR_VALUE(self_in);
Damien George3e1a5c12014-03-29 13:43:38 +00001472 } else if (MP_OBJ_IS_TYPE(self_in, &mp_type_str)) {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001473 mp_obj_str_t *self = self_in;
1474 return qstr_from_strn((char*)self->data, self->len);
1475 } else {
1476 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001477 }
1478}
1479
1480// only use this function if you need the str data to be zero terminated
1481// at the moment all strings are zero terminated to help with C ASCIIZ compatibility
1482const char *mp_obj_str_get_str(mp_obj_t self_in) {
1483 if (MP_OBJ_IS_STR(self_in)) {
1484 GET_STR_DATA_LEN(self_in, s, l);
1485 (void)l; // len unused
1486 return (const char*)s;
1487 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001488 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001489 }
1490}
1491
Damien George698ec212014-02-08 18:17:23 +00001492const char *mp_obj_str_get_data(mp_obj_t self_in, uint *len) {
Damien George5fa93b62014-01-22 14:35:10 +00001493 if (MP_OBJ_IS_STR(self_in)) {
1494 GET_STR_DATA_LEN(self_in, s, l);
1495 *len = l;
Damien George698ec212014-02-08 18:17:23 +00001496 return (const char*)s;
Damien George5fa93b62014-01-22 14:35:10 +00001497 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001498 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001499 }
Damiend99b0522013-12-21 18:17:45 +00001500}
xyb8cfc9f02014-01-05 18:47:51 +08001501
1502/******************************************************************************/
1503/* str iterator */
1504
1505typedef struct _mp_obj_str_it_t {
1506 mp_obj_base_t base;
Damien George5fa93b62014-01-22 14:35:10 +00001507 mp_obj_t str;
xyb8cfc9f02014-01-05 18:47:51 +08001508 machine_uint_t cur;
1509} mp_obj_str_it_t;
1510
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001511STATIC mp_obj_t str_it_iternext(mp_obj_t self_in) {
xyb8cfc9f02014-01-05 18:47:51 +08001512 mp_obj_str_it_t *self = self_in;
Damien George5fa93b62014-01-22 14:35:10 +00001513 GET_STR_DATA_LEN(self->str, str, len);
1514 if (self->cur < len) {
1515 mp_obj_t o_out = mp_obj_new_str(str + self->cur, 1, true);
xyb8cfc9f02014-01-05 18:47:51 +08001516 self->cur += 1;
1517 return o_out;
1518 } else {
Damien George66eaf842014-03-26 19:27:58 +00001519 return MP_OBJ_NULL;
xyb8cfc9f02014-01-05 18:47:51 +08001520 }
1521}
1522
Damien George3e1a5c12014-03-29 13:43:38 +00001523STATIC const mp_obj_type_t mp_type_str_it = {
Damien Georgec5966122014-02-15 16:10:44 +00001524 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001525 .name = MP_QSTR_iterator,
Paul Sokolovskyf7eaf602014-03-30 22:00:12 +03001526 .getiter = mp_identity,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001527 .iternext = str_it_iternext,
xyb8cfc9f02014-01-05 18:47:51 +08001528};
1529
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001530STATIC mp_obj_t bytes_it_iternext(mp_obj_t self_in) {
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001531 mp_obj_str_it_t *self = self_in;
1532 GET_STR_DATA_LEN(self->str, str, len);
1533 if (self->cur < len) {
Damien George7c9c6672014-01-25 00:17:36 +00001534 mp_obj_t o_out = MP_OBJ_NEW_SMALL_INT((mp_small_int_t)str[self->cur]);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001535 self->cur += 1;
1536 return o_out;
1537 } else {
Damien George66eaf842014-03-26 19:27:58 +00001538 return MP_OBJ_NULL;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001539 }
1540}
1541
Damien George3e1a5c12014-03-29 13:43:38 +00001542STATIC const mp_obj_type_t mp_type_bytes_it = {
Damien Georgec5966122014-02-15 16:10:44 +00001543 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001544 .name = MP_QSTR_iterator,
Paul Sokolovskyf7eaf602014-03-30 22:00:12 +03001545 .getiter = mp_identity,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001546 .iternext = bytes_it_iternext,
1547};
1548
1549mp_obj_t mp_obj_new_str_iterator(mp_obj_t str) {
xyb8cfc9f02014-01-05 18:47:51 +08001550 mp_obj_str_it_t *o = m_new_obj(mp_obj_str_it_t);
Damien George3e1a5c12014-03-29 13:43:38 +00001551 o->base.type = &mp_type_str_it;
xyb8cfc9f02014-01-05 18:47:51 +08001552 o->str = str;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001553 o->cur = 0;
1554 return o;
1555}
1556
1557mp_obj_t mp_obj_new_bytes_iterator(mp_obj_t str) {
1558 mp_obj_str_it_t *o = m_new_obj(mp_obj_str_it_t);
Damien George3e1a5c12014-03-29 13:43:38 +00001559 o->base.type = &mp_type_bytes_it;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001560 o->str = str;
1561 o->cur = 0;
xyb8cfc9f02014-01-05 18:47:51 +08001562 return o;
1563}