blob: 2c8d02491f6c8c4a24528a8c13f9520fca246b7d [file] [log] [blame]
Paul Sokolovsky83865342014-06-13 00:51:34 +03001/*
2 * This file is part of the Micro Python project, http://micropython.org/
3 *
4 * The MIT License (MIT)
5 *
6 * Copyright (c) 2013, 2014 Damien P. George
7 * Copyright (c) 2014 Paul Sokolovsky
8 *
9 * Permission is hereby granted, free of charge, to any person obtaining a copy
10 * of this software and associated documentation files (the "Software"), to deal
11 * in the Software without restriction, including without limitation the rights
12 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 * copies of the Software, and to permit persons to whom the Software is
14 * furnished to do so, subject to the following conditions:
15 *
16 * The above copyright notice and this permission notice shall be included in
17 * all copies or substantial portions of the Software.
18 *
19 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 * THE SOFTWARE.
26 */
27
28#include <stdbool.h>
29#include <string.h>
30#include <assert.h>
31
32#include "mpconfig.h"
33#include "nlr.h"
34#include "misc.h"
35#include "qstr.h"
36#include "obj.h"
37#include "runtime0.h"
38#include "runtime.h"
39#include "pfenv.h"
40#include "objstr.h"
41#include "objlist.h"
42
Paul Sokolovsky97319122014-06-13 22:01:26 +030043#if MICROPY_PY_BUILTINS_STR_UNICODE
Paul Sokolovsky83865342014-06-13 00:51:34 +030044
45STATIC mp_obj_t mp_obj_new_str_iterator(mp_obj_t str);
Paul Sokolovsky83865342014-06-13 00:51:34 +030046
47/******************************************************************************/
48/* str */
49
Paul Sokolovsky86d38982014-06-13 23:00:15 +030050STATIC void uni_print_quoted(void (*print)(void *env, const char *fmt, ...), void *env, const byte *str_data, uint str_len) {
Paul Sokolovsky83865342014-06-13 00:51:34 +030051 // this escapes characters, but it will be very slow to print (calling print many times)
52 bool has_single_quote = false;
53 bool has_double_quote = false;
54 for (const byte *s = str_data, *top = str_data + str_len; !has_double_quote && s < top; s++) {
55 if (*s == '\'') {
56 has_single_quote = true;
57 } else if (*s == '"') {
58 has_double_quote = true;
59 }
60 }
61 int quote_char = '\'';
62 if (has_single_quote && !has_double_quote) {
63 quote_char = '"';
64 }
65 print(env, "%c", quote_char);
Paul Sokolovsky00c904b2014-06-14 17:48:40 +030066 const byte *s = str_data, *top = str_data + str_len;
Chris Angelico64b468d2014-06-04 05:28:12 +100067 while (s < top) {
68 unichar ch;
Paul Sokolovsky86d38982014-06-13 23:00:15 +030069 ch = utf8_get_char(s);
70 s = utf8_next_char(s);
Chris Angelico64b468d2014-06-04 05:28:12 +100071 if (ch == quote_char) {
72 print(env, "\\%c", quote_char);
73 } else if (ch == '\\') {
74 print(env, "\\\\");
75 } else if (32 <= ch && ch <= 126) {
76 print(env, "%c", ch);
77 } else if (ch == '\n') {
78 print(env, "\\n");
79 } else if (ch == '\r') {
80 print(env, "\\r");
81 } else if (ch == '\t') {
82 print(env, "\\t");
83 } else if (ch < 0x100) {
84 print(env, "\\x%02x", ch);
85 } else if (ch < 0x10000) {
86 print(env, "\\u%04x", ch);
87 } else {
88 print(env, "\\U%08x", ch);
Paul Sokolovsky83865342014-06-13 00:51:34 +030089 }
90 }
91 print(env, "%c", quote_char);
92}
93
Paul Sokolovsky86d38982014-06-13 23:00:15 +030094STATIC void uni_print(void (*print)(void *env, const char *fmt, ...), void *env, mp_obj_t self_in, mp_print_kind_t kind) {
Paul Sokolovsky83865342014-06-13 00:51:34 +030095 GET_STR_DATA_LEN(self_in, str_data, str_len);
Damien George612045f2014-09-17 22:56:34 +010096 #if MICROPY_PY_UJSON
97 if (kind == PRINT_JSON) {
Damien Georgecde0ca22014-09-25 17:35:56 +010098 mp_str_print_json(print, env, str_data, str_len);
Damien George612045f2014-09-17 22:56:34 +010099 return;
100 }
101 #endif
Paul Sokolovsky86d38982014-06-13 23:00:15 +0300102 if (kind == PRINT_STR) {
Paul Sokolovsky83865342014-06-13 00:51:34 +0300103 print(env, "%.*s", str_len, str_data);
104 } else {
Paul Sokolovsky86d38982014-06-13 23:00:15 +0300105 uni_print_quoted(print, env, str_data, str_len);
Paul Sokolovsky83865342014-06-13 00:51:34 +0300106 }
107}
108
Damien Georgeecc88e92014-08-30 00:35:11 +0100109STATIC mp_obj_t uni_unary_op(mp_uint_t op, mp_obj_t self_in) {
Paul Sokolovskye7f2b4c2014-06-13 23:37:18 +0300110 GET_STR_DATA_LEN(self_in, str_data, str_len);
111 switch (op) {
112 case MP_UNARY_OP_BOOL:
113 return MP_BOOL(str_len != 0);
114 case MP_UNARY_OP_LEN:
Paul Sokolovsky9e215fa2014-06-28 23:14:30 +0300115 return MP_OBJ_NEW_SMALL_INT(unichar_charlen((const char *)str_data, str_len));
Paul Sokolovskye7f2b4c2014-06-13 23:37:18 +0300116 default:
117 return MP_OBJ_NULL; // op not supported
118 }
119}
120
Damien Georgeecc88e92014-08-30 00:35:11 +0100121STATIC mp_obj_t str_make_new(mp_obj_t type_in, mp_uint_t n_args, mp_uint_t n_kw, const mp_obj_t *args) {
Paul Sokolovsky83865342014-06-13 00:51:34 +0300122#if MICROPY_CPYTHON_COMPAT
123 if (n_kw != 0) {
124 mp_arg_error_unimpl_kw();
125 }
126#endif
127
128 switch (n_args) {
129 case 0:
130 return MP_OBJ_NEW_QSTR(MP_QSTR_);
131
132 case 1:
133 {
134 vstr_t *vstr = vstr_new();
135 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, vstr, args[0], PRINT_STR);
136 mp_obj_t s = mp_obj_new_str(vstr->buf, vstr->len, false);
137 vstr_free(vstr);
138 return s;
139 }
140
141 case 2:
142 case 3:
143 {
144 // TODO: validate 2nd/3rd args
Paul Sokolovskye62a0fe2014-10-30 23:58:08 +0200145 if (MP_OBJ_IS_TYPE(args[0], &mp_type_bytes)) {
146 GET_STR_DATA_LEN(args[0], str_data, str_len);
147 GET_STR_HASH(args[0], str_hash);
148 mp_obj_str_t *o = mp_obj_new_str_of_type(&mp_type_str, NULL, str_len);
149 o->data = str_data;
150 o->hash = str_hash;
151 return o;
152 } else {
153 mp_buffer_info_t bufinfo;
154 mp_get_buffer_raise(args[0], &bufinfo, MP_BUFFER_READ);
155 return mp_obj_new_str(bufinfo.buf, bufinfo.len, false);
Paul Sokolovsky83865342014-06-13 00:51:34 +0300156 }
Paul Sokolovsky83865342014-06-13 00:51:34 +0300157 }
158
159 default:
160 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "str takes at most 3 arguments"));
161 }
162}
163
Chris Angelico64b468d2014-06-04 05:28:12 +1000164// Convert an index into a pointer to its lead byte. Out of bounds indexing will raise IndexError or
165// be capped to the first/last character of the string, depending on is_slice.
Damien George4abff752014-08-30 14:59:21 +0100166const byte *str_index_to_ptr(const mp_obj_type_t *type, const byte *self_data, mp_uint_t self_len,
Paul Sokolovskyea2c9362014-06-15 00:35:09 +0300167 mp_obj_t index, bool is_slice) {
Damien George40f3c022014-07-03 13:25:24 +0100168 mp_int_t i;
Chris Angelico64b468d2014-06-04 05:28:12 +1000169 // Copied from mp_get_index; I don't want bounds checking, just give me
170 // the integer as-is. (I can't bounds-check without scanning the whole
171 // string; an out-of-bounds index will be caught in the loops below.)
172 if (MP_OBJ_IS_SMALL_INT(index)) {
173 i = MP_OBJ_SMALL_INT_VALUE(index);
174 } else if (!mp_obj_get_int_maybe(index, &i)) {
175 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, "string indices must be integers, not %s", mp_obj_get_type_str(index)));
176 }
Paul Sokolovskyea2c9362014-06-15 00:35:09 +0300177 const byte *s, *top = self_data + self_len;
Chris Angelico64b468d2014-06-04 05:28:12 +1000178 if (i < 0)
179 {
180 // Negative indexing is performed by counting from the end of the string.
181 for (s = top - 1; i; --s) {
182 if (s < self_data) {
183 if (is_slice) {
184 return self_data;
185 }
186 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_IndexError, "string index out of range"));
187 }
188 if (!UTF8_IS_CONT(*s)) {
189 ++i;
190 }
191 }
192 ++s;
193 } else if (!i) {
194 return self_data; // Shortcut - str[0] is its base pointer
195 } else {
196 // Positive indexing, correspondingly, counts from the start of the string.
197 // It's assumed that negative indexing will generally be used with small
198 // absolute values (eg str[-1], not str[-1000000]), which means it'll be
199 // more efficient this way.
200 for (s = self_data; true; ++s) {
201 if (s >= top) {
202 if (is_slice) {
203 return top;
204 }
205 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_IndexError, "string index out of range"));
206 }
207 while (UTF8_IS_CONT(*s)) {
208 ++s;
209 }
210 if (!i--) {
211 return s;
212 }
213 }
214 }
215 return s;
216}
217
Paul Sokolovsky83865342014-06-13 00:51:34 +0300218STATIC mp_obj_t str_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) {
219 mp_obj_type_t *type = mp_obj_get_type(self_in);
220 GET_STR_DATA_LEN(self_in, self_data, self_len);
221 if (value == MP_OBJ_SENTINEL) {
222 // load
223#if MICROPY_PY_BUILTINS_SLICE
224 if (MP_OBJ_IS_TYPE(index, &mp_type_slice)) {
Chris Angelico64b468d2014-06-04 05:28:12 +1000225 mp_obj_t ostart, ostop, ostep;
226 mp_obj_slice_get(index, &ostart, &ostop, &ostep);
227 if (ostep != mp_const_none && ostep != MP_OBJ_NEW_SMALL_INT(1)) {
Paul Sokolovsky83865342014-06-13 00:51:34 +0300228 nlr_raise(mp_obj_new_exception_msg(&mp_type_NotImplementedError,
229 "only slices with step=1 (aka None) are supported"));
230 }
Chris Angelico64b468d2014-06-04 05:28:12 +1000231
232 if (type == &mp_type_bytes) {
Damien George40f3c022014-07-03 13:25:24 +0100233 mp_int_t start = 0, stop = self_len;
Chris Angelico64b468d2014-06-04 05:28:12 +1000234 if (ostart != mp_const_none) {
235 start = MP_OBJ_SMALL_INT_VALUE(ostart);
236 if (start < 0) {
237 start = self_len + start;
238 }
239 }
240 if (ostop != mp_const_none) {
241 stop = MP_OBJ_SMALL_INT_VALUE(ostop);
242 if (stop < 0) {
243 stop = self_len + stop;
244 }
245 }
246 return mp_obj_new_str_of_type(type, self_data + start, stop - start);
247 }
Paul Sokolovskyea2c9362014-06-15 00:35:09 +0300248 const byte *pstart, *pstop;
Chris Angelico64b468d2014-06-04 05:28:12 +1000249 if (ostart != mp_const_none) {
Paul Sokolovskyea2c9362014-06-15 00:35:09 +0300250 pstart = str_index_to_ptr(type, self_data, self_len, ostart, true);
Chris Angelico64b468d2014-06-04 05:28:12 +1000251 } else {
Paul Sokolovskyea2c9362014-06-15 00:35:09 +0300252 pstart = self_data;
Chris Angelico64b468d2014-06-04 05:28:12 +1000253 }
254 if (ostop != mp_const_none) {
255 // pstop will point just after the stop character. This depends on
256 // the \0 at the end of the string.
Paul Sokolovskyea2c9362014-06-15 00:35:09 +0300257 pstop = str_index_to_ptr(type, self_data, self_len, ostop, true);
Chris Angelico64b468d2014-06-04 05:28:12 +1000258 } else {
Paul Sokolovskyea2c9362014-06-15 00:35:09 +0300259 pstop = self_data + self_len;
Chris Angelico64b468d2014-06-04 05:28:12 +1000260 }
261 if (pstop < pstart) {
262 return MP_OBJ_NEW_QSTR(MP_QSTR_);
263 }
264 return mp_obj_new_str_of_type(type, (const byte *)pstart, pstop - pstart);
Paul Sokolovsky83865342014-06-13 00:51:34 +0300265 }
266#endif
Paul Sokolovsky83865342014-06-13 00:51:34 +0300267 if (type == &mp_type_bytes) {
Chris Angelico64b468d2014-06-04 05:28:12 +1000268 uint index_val = mp_get_index(type, self_len, index, false);
Damien Georgebb4c6f32014-07-31 10:49:14 +0100269 return MP_OBJ_NEW_SMALL_INT(self_data[index_val]);
Paul Sokolovsky83865342014-06-13 00:51:34 +0300270 }
Paul Sokolovskyea2c9362014-06-15 00:35:09 +0300271 const byte *s = str_index_to_ptr(type, self_data, self_len, index, false);
Chris Angelico64b468d2014-06-04 05:28:12 +1000272 int len = 1;
273 if (UTF8_IS_NONASCII(*s)) {
274 // Count the number of 1 bits (after the first)
275 for (char mask = 0x40; *s & mask; mask >>= 1) {
276 ++len;
277 }
278 }
Paul Sokolovskyea2c9362014-06-15 00:35:09 +0300279 return mp_obj_new_str((const char*)s, len, true); // This will create a one-character string
Paul Sokolovsky83865342014-06-13 00:51:34 +0300280 } else {
281 return MP_OBJ_NULL; // op not supported
282 }
283}
284
Paul Sokolovsky83865342014-06-13 00:51:34 +0300285STATIC const mp_map_elem_t str_locals_dict_table[] = {
286#if MICROPY_CPYTHON_COMPAT
Paul Sokolovsky83865342014-06-13 00:51:34 +0300287 { MP_OBJ_NEW_QSTR(MP_QSTR_encode), (mp_obj_t)&str_encode_obj },
288#endif
289 { MP_OBJ_NEW_QSTR(MP_QSTR_find), (mp_obj_t)&str_find_obj },
290 { MP_OBJ_NEW_QSTR(MP_QSTR_rfind), (mp_obj_t)&str_rfind_obj },
291 { MP_OBJ_NEW_QSTR(MP_QSTR_index), (mp_obj_t)&str_index_obj },
292 { MP_OBJ_NEW_QSTR(MP_QSTR_rindex), (mp_obj_t)&str_rindex_obj },
293 { MP_OBJ_NEW_QSTR(MP_QSTR_join), (mp_obj_t)&str_join_obj },
294 { MP_OBJ_NEW_QSTR(MP_QSTR_split), (mp_obj_t)&str_split_obj },
295 { MP_OBJ_NEW_QSTR(MP_QSTR_rsplit), (mp_obj_t)&str_rsplit_obj },
296 { MP_OBJ_NEW_QSTR(MP_QSTR_startswith), (mp_obj_t)&str_startswith_obj },
297 { MP_OBJ_NEW_QSTR(MP_QSTR_endswith), (mp_obj_t)&str_endswith_obj },
298 { MP_OBJ_NEW_QSTR(MP_QSTR_strip), (mp_obj_t)&str_strip_obj },
299 { MP_OBJ_NEW_QSTR(MP_QSTR_lstrip), (mp_obj_t)&str_lstrip_obj },
300 { MP_OBJ_NEW_QSTR(MP_QSTR_rstrip), (mp_obj_t)&str_rstrip_obj },
301 { MP_OBJ_NEW_QSTR(MP_QSTR_format), (mp_obj_t)&str_format_obj },
302 { MP_OBJ_NEW_QSTR(MP_QSTR_replace), (mp_obj_t)&str_replace_obj },
303 { MP_OBJ_NEW_QSTR(MP_QSTR_count), (mp_obj_t)&str_count_obj },
304 { MP_OBJ_NEW_QSTR(MP_QSTR_partition), (mp_obj_t)&str_partition_obj },
305 { MP_OBJ_NEW_QSTR(MP_QSTR_rpartition), (mp_obj_t)&str_rpartition_obj },
306 { MP_OBJ_NEW_QSTR(MP_QSTR_lower), (mp_obj_t)&str_lower_obj },
307 { MP_OBJ_NEW_QSTR(MP_QSTR_upper), (mp_obj_t)&str_upper_obj },
308 { MP_OBJ_NEW_QSTR(MP_QSTR_isspace), (mp_obj_t)&str_isspace_obj },
309 { MP_OBJ_NEW_QSTR(MP_QSTR_isalpha), (mp_obj_t)&str_isalpha_obj },
310 { MP_OBJ_NEW_QSTR(MP_QSTR_isdigit), (mp_obj_t)&str_isdigit_obj },
311 { MP_OBJ_NEW_QSTR(MP_QSTR_isupper), (mp_obj_t)&str_isupper_obj },
312 { MP_OBJ_NEW_QSTR(MP_QSTR_islower), (mp_obj_t)&str_islower_obj },
313};
314
315STATIC MP_DEFINE_CONST_DICT(str_locals_dict, str_locals_dict_table);
316
317const mp_obj_type_t mp_type_str = {
318 { &mp_type_type },
319 .name = MP_QSTR_str,
Paul Sokolovsky86d38982014-06-13 23:00:15 +0300320 .print = uni_print,
Paul Sokolovsky83865342014-06-13 00:51:34 +0300321 .make_new = str_make_new,
Paul Sokolovskye7f2b4c2014-06-13 23:37:18 +0300322 .unary_op = uni_unary_op,
Damien Georgee04a44e2014-06-28 10:27:23 +0100323 .binary_op = mp_obj_str_binary_op,
Paul Sokolovsky83865342014-06-13 00:51:34 +0300324 .subscr = str_subscr,
325 .getiter = mp_obj_new_str_iterator,
Damien Georgee04a44e2014-06-28 10:27:23 +0100326 .buffer_p = { .get_buffer = mp_obj_str_get_buffer },
Paul Sokolovsky83865342014-06-13 00:51:34 +0300327 .locals_dict = (mp_obj_t)&str_locals_dict,
328};
329
Paul Sokolovsky83865342014-06-13 00:51:34 +0300330/******************************************************************************/
331/* str iterator */
332
333typedef struct _mp_obj_str_it_t {
334 mp_obj_base_t base;
335 mp_obj_t str;
Damien George40f3c022014-07-03 13:25:24 +0100336 mp_uint_t cur;
Paul Sokolovsky83865342014-06-13 00:51:34 +0300337} mp_obj_str_it_t;
338
339STATIC mp_obj_t str_it_iternext(mp_obj_t self_in) {
340 mp_obj_str_it_t *self = self_in;
341 GET_STR_DATA_LEN(self->str, str, len);
342 if (self->cur < len) {
Paul Sokolovsky79b7fe22014-06-14 02:07:25 +0300343 const byte *cur = str + self->cur;
344 const byte *end = utf8_next_char(str + self->cur);
345 mp_obj_t o_out = mp_obj_new_str((const char*)cur, end - cur, true);
346 self->cur += end - cur;
Paul Sokolovsky83865342014-06-13 00:51:34 +0300347 return o_out;
348 } else {
349 return MP_OBJ_STOP_ITERATION;
350 }
351}
352
353STATIC const mp_obj_type_t mp_type_str_it = {
354 { &mp_type_type },
355 .name = MP_QSTR_iterator,
356 .getiter = mp_identity,
357 .iternext = str_it_iternext,
358};
359
Paul Sokolovsky83865342014-06-13 00:51:34 +0300360mp_obj_t mp_obj_new_str_iterator(mp_obj_t str) {
361 mp_obj_str_it_t *o = m_new_obj(mp_obj_str_it_t);
362 o->base.type = &mp_type_str_it;
363 o->str = str;
364 o->cur = 0;
365 return o;
366}
367
Paul Sokolovsky97319122014-06-13 22:01:26 +0300368#endif // MICROPY_PY_BUILTINS_STR_UNICODE