blob: 0ee7f1dc9a323e2ad3bdcd9a5c6131de5c561aef [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
Damien George612045f2014-09-17 22:56:34 +010094#if MICROPY_PY_UJSON
95STATIC void uni_print_json(void (*print)(void *env, const char *fmt, ...), void *env, const byte *str_data, uint str_len) {
96 print(env, "\"");
97 const byte *s = str_data, *top = str_data + str_len;
98 while (s < top) {
99 unichar ch;
100 ch = utf8_get_char(s);
101 s = utf8_next_char(s);
102 if (ch == '"' || ch == '\\' || ch == '/') {
103 print(env, "\\%c", ch);
104 } else if (32 <= ch && ch <= 126) {
105 print(env, "%c", ch);
106 } else if (*s == '\b') {
107 print(env, "\\b");
108 } else if (*s == '\f') {
109 print(env, "\\f");
110 } else if (*s == '\n') {
111 print(env, "\\n");
112 } else if (*s == '\r') {
113 print(env, "\\r");
114 } else if (*s == '\t') {
115 print(env, "\\t");
116 } else {
117 print(env, "\\u%04x", ch);
118 }
119 }
120 print(env, "\"");
121}
122#endif
123
Paul Sokolovsky86d38982014-06-13 23:00:15 +0300124STATIC 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 +0300125 GET_STR_DATA_LEN(self_in, str_data, str_len);
Damien George612045f2014-09-17 22:56:34 +0100126 #if MICROPY_PY_UJSON
127 if (kind == PRINT_JSON) {
128 uni_print_json(print, env, str_data, str_len);
129 return;
130 }
131 #endif
Paul Sokolovsky86d38982014-06-13 23:00:15 +0300132 if (kind == PRINT_STR) {
Paul Sokolovsky83865342014-06-13 00:51:34 +0300133 print(env, "%.*s", str_len, str_data);
134 } else {
Paul Sokolovsky86d38982014-06-13 23:00:15 +0300135 uni_print_quoted(print, env, str_data, str_len);
Paul Sokolovsky83865342014-06-13 00:51:34 +0300136 }
137}
138
Damien Georgeecc88e92014-08-30 00:35:11 +0100139STATIC mp_obj_t uni_unary_op(mp_uint_t op, mp_obj_t self_in) {
Paul Sokolovskye7f2b4c2014-06-13 23:37:18 +0300140 GET_STR_DATA_LEN(self_in, str_data, str_len);
141 switch (op) {
142 case MP_UNARY_OP_BOOL:
143 return MP_BOOL(str_len != 0);
144 case MP_UNARY_OP_LEN:
Paul Sokolovsky9e215fa2014-06-28 23:14:30 +0300145 return MP_OBJ_NEW_SMALL_INT(unichar_charlen((const char *)str_data, str_len));
Paul Sokolovskye7f2b4c2014-06-13 23:37:18 +0300146 default:
147 return MP_OBJ_NULL; // op not supported
148 }
149}
150
Damien Georgeecc88e92014-08-30 00:35:11 +0100151STATIC 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 +0300152#if MICROPY_CPYTHON_COMPAT
153 if (n_kw != 0) {
154 mp_arg_error_unimpl_kw();
155 }
156#endif
157
158 switch (n_args) {
159 case 0:
160 return MP_OBJ_NEW_QSTR(MP_QSTR_);
161
162 case 1:
163 {
164 vstr_t *vstr = vstr_new();
165 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, vstr, args[0], PRINT_STR);
166 mp_obj_t s = mp_obj_new_str(vstr->buf, vstr->len, false);
167 vstr_free(vstr);
168 return s;
169 }
170
171 case 2:
172 case 3:
173 {
174 // TODO: validate 2nd/3rd args
175 if (!MP_OBJ_IS_TYPE(args[0], &mp_type_bytes)) {
176 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "bytes expected"));
177 }
178 GET_STR_DATA_LEN(args[0], str_data, str_len);
179 GET_STR_HASH(args[0], str_hash);
180 mp_obj_str_t *o = mp_obj_new_str_of_type(&mp_type_str, NULL, str_len);
181 o->data = str_data;
182 o->hash = str_hash;
183 return o;
184 }
185
186 default:
187 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "str takes at most 3 arguments"));
188 }
189}
190
Chris Angelico64b468d2014-06-04 05:28:12 +1000191// Convert an index into a pointer to its lead byte. Out of bounds indexing will raise IndexError or
192// be capped to the first/last character of the string, depending on is_slice.
Damien George4abff752014-08-30 14:59:21 +0100193const 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 +0300194 mp_obj_t index, bool is_slice) {
Damien George40f3c022014-07-03 13:25:24 +0100195 mp_int_t i;
Chris Angelico64b468d2014-06-04 05:28:12 +1000196 // Copied from mp_get_index; I don't want bounds checking, just give me
197 // the integer as-is. (I can't bounds-check without scanning the whole
198 // string; an out-of-bounds index will be caught in the loops below.)
199 if (MP_OBJ_IS_SMALL_INT(index)) {
200 i = MP_OBJ_SMALL_INT_VALUE(index);
201 } else if (!mp_obj_get_int_maybe(index, &i)) {
202 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, "string indices must be integers, not %s", mp_obj_get_type_str(index)));
203 }
Paul Sokolovskyea2c9362014-06-15 00:35:09 +0300204 const byte *s, *top = self_data + self_len;
Chris Angelico64b468d2014-06-04 05:28:12 +1000205 if (i < 0)
206 {
207 // Negative indexing is performed by counting from the end of the string.
208 for (s = top - 1; i; --s) {
209 if (s < self_data) {
210 if (is_slice) {
211 return self_data;
212 }
213 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_IndexError, "string index out of range"));
214 }
215 if (!UTF8_IS_CONT(*s)) {
216 ++i;
217 }
218 }
219 ++s;
220 } else if (!i) {
221 return self_data; // Shortcut - str[0] is its base pointer
222 } else {
223 // Positive indexing, correspondingly, counts from the start of the string.
224 // It's assumed that negative indexing will generally be used with small
225 // absolute values (eg str[-1], not str[-1000000]), which means it'll be
226 // more efficient this way.
227 for (s = self_data; true; ++s) {
228 if (s >= top) {
229 if (is_slice) {
230 return top;
231 }
232 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_IndexError, "string index out of range"));
233 }
234 while (UTF8_IS_CONT(*s)) {
235 ++s;
236 }
237 if (!i--) {
238 return s;
239 }
240 }
241 }
242 return s;
243}
244
Paul Sokolovsky83865342014-06-13 00:51:34 +0300245STATIC mp_obj_t str_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) {
246 mp_obj_type_t *type = mp_obj_get_type(self_in);
247 GET_STR_DATA_LEN(self_in, self_data, self_len);
248 if (value == MP_OBJ_SENTINEL) {
249 // load
250#if MICROPY_PY_BUILTINS_SLICE
251 if (MP_OBJ_IS_TYPE(index, &mp_type_slice)) {
Chris Angelico64b468d2014-06-04 05:28:12 +1000252 mp_obj_t ostart, ostop, ostep;
253 mp_obj_slice_get(index, &ostart, &ostop, &ostep);
254 if (ostep != mp_const_none && ostep != MP_OBJ_NEW_SMALL_INT(1)) {
Paul Sokolovsky83865342014-06-13 00:51:34 +0300255 nlr_raise(mp_obj_new_exception_msg(&mp_type_NotImplementedError,
256 "only slices with step=1 (aka None) are supported"));
257 }
Chris Angelico64b468d2014-06-04 05:28:12 +1000258
259 if (type == &mp_type_bytes) {
Damien George40f3c022014-07-03 13:25:24 +0100260 mp_int_t start = 0, stop = self_len;
Chris Angelico64b468d2014-06-04 05:28:12 +1000261 if (ostart != mp_const_none) {
262 start = MP_OBJ_SMALL_INT_VALUE(ostart);
263 if (start < 0) {
264 start = self_len + start;
265 }
266 }
267 if (ostop != mp_const_none) {
268 stop = MP_OBJ_SMALL_INT_VALUE(ostop);
269 if (stop < 0) {
270 stop = self_len + stop;
271 }
272 }
273 return mp_obj_new_str_of_type(type, self_data + start, stop - start);
274 }
Paul Sokolovskyea2c9362014-06-15 00:35:09 +0300275 const byte *pstart, *pstop;
Chris Angelico64b468d2014-06-04 05:28:12 +1000276 if (ostart != mp_const_none) {
Paul Sokolovskyea2c9362014-06-15 00:35:09 +0300277 pstart = str_index_to_ptr(type, self_data, self_len, ostart, true);
Chris Angelico64b468d2014-06-04 05:28:12 +1000278 } else {
Paul Sokolovskyea2c9362014-06-15 00:35:09 +0300279 pstart = self_data;
Chris Angelico64b468d2014-06-04 05:28:12 +1000280 }
281 if (ostop != mp_const_none) {
282 // pstop will point just after the stop character. This depends on
283 // the \0 at the end of the string.
Paul Sokolovskyea2c9362014-06-15 00:35:09 +0300284 pstop = str_index_to_ptr(type, self_data, self_len, ostop, true);
Chris Angelico64b468d2014-06-04 05:28:12 +1000285 } else {
Paul Sokolovskyea2c9362014-06-15 00:35:09 +0300286 pstop = self_data + self_len;
Chris Angelico64b468d2014-06-04 05:28:12 +1000287 }
288 if (pstop < pstart) {
289 return MP_OBJ_NEW_QSTR(MP_QSTR_);
290 }
291 return mp_obj_new_str_of_type(type, (const byte *)pstart, pstop - pstart);
Paul Sokolovsky83865342014-06-13 00:51:34 +0300292 }
293#endif
Paul Sokolovsky83865342014-06-13 00:51:34 +0300294 if (type == &mp_type_bytes) {
Chris Angelico64b468d2014-06-04 05:28:12 +1000295 uint index_val = mp_get_index(type, self_len, index, false);
Damien Georgebb4c6f32014-07-31 10:49:14 +0100296 return MP_OBJ_NEW_SMALL_INT(self_data[index_val]);
Paul Sokolovsky83865342014-06-13 00:51:34 +0300297 }
Paul Sokolovskyea2c9362014-06-15 00:35:09 +0300298 const byte *s = str_index_to_ptr(type, self_data, self_len, index, false);
Chris Angelico64b468d2014-06-04 05:28:12 +1000299 int len = 1;
300 if (UTF8_IS_NONASCII(*s)) {
301 // Count the number of 1 bits (after the first)
302 for (char mask = 0x40; *s & mask; mask >>= 1) {
303 ++len;
304 }
305 }
Paul Sokolovskyea2c9362014-06-15 00:35:09 +0300306 return mp_obj_new_str((const char*)s, len, true); // This will create a one-character string
Paul Sokolovsky83865342014-06-13 00:51:34 +0300307 } else {
308 return MP_OBJ_NULL; // op not supported
309 }
310}
311
Paul Sokolovsky83865342014-06-13 00:51:34 +0300312STATIC const mp_map_elem_t str_locals_dict_table[] = {
313#if MICROPY_CPYTHON_COMPAT
Paul Sokolovsky83865342014-06-13 00:51:34 +0300314 { MP_OBJ_NEW_QSTR(MP_QSTR_encode), (mp_obj_t)&str_encode_obj },
315#endif
316 { MP_OBJ_NEW_QSTR(MP_QSTR_find), (mp_obj_t)&str_find_obj },
317 { MP_OBJ_NEW_QSTR(MP_QSTR_rfind), (mp_obj_t)&str_rfind_obj },
318 { MP_OBJ_NEW_QSTR(MP_QSTR_index), (mp_obj_t)&str_index_obj },
319 { MP_OBJ_NEW_QSTR(MP_QSTR_rindex), (mp_obj_t)&str_rindex_obj },
320 { MP_OBJ_NEW_QSTR(MP_QSTR_join), (mp_obj_t)&str_join_obj },
321 { MP_OBJ_NEW_QSTR(MP_QSTR_split), (mp_obj_t)&str_split_obj },
322 { MP_OBJ_NEW_QSTR(MP_QSTR_rsplit), (mp_obj_t)&str_rsplit_obj },
323 { MP_OBJ_NEW_QSTR(MP_QSTR_startswith), (mp_obj_t)&str_startswith_obj },
324 { MP_OBJ_NEW_QSTR(MP_QSTR_endswith), (mp_obj_t)&str_endswith_obj },
325 { MP_OBJ_NEW_QSTR(MP_QSTR_strip), (mp_obj_t)&str_strip_obj },
326 { MP_OBJ_NEW_QSTR(MP_QSTR_lstrip), (mp_obj_t)&str_lstrip_obj },
327 { MP_OBJ_NEW_QSTR(MP_QSTR_rstrip), (mp_obj_t)&str_rstrip_obj },
328 { MP_OBJ_NEW_QSTR(MP_QSTR_format), (mp_obj_t)&str_format_obj },
329 { MP_OBJ_NEW_QSTR(MP_QSTR_replace), (mp_obj_t)&str_replace_obj },
330 { MP_OBJ_NEW_QSTR(MP_QSTR_count), (mp_obj_t)&str_count_obj },
331 { MP_OBJ_NEW_QSTR(MP_QSTR_partition), (mp_obj_t)&str_partition_obj },
332 { MP_OBJ_NEW_QSTR(MP_QSTR_rpartition), (mp_obj_t)&str_rpartition_obj },
333 { MP_OBJ_NEW_QSTR(MP_QSTR_lower), (mp_obj_t)&str_lower_obj },
334 { MP_OBJ_NEW_QSTR(MP_QSTR_upper), (mp_obj_t)&str_upper_obj },
335 { MP_OBJ_NEW_QSTR(MP_QSTR_isspace), (mp_obj_t)&str_isspace_obj },
336 { MP_OBJ_NEW_QSTR(MP_QSTR_isalpha), (mp_obj_t)&str_isalpha_obj },
337 { MP_OBJ_NEW_QSTR(MP_QSTR_isdigit), (mp_obj_t)&str_isdigit_obj },
338 { MP_OBJ_NEW_QSTR(MP_QSTR_isupper), (mp_obj_t)&str_isupper_obj },
339 { MP_OBJ_NEW_QSTR(MP_QSTR_islower), (mp_obj_t)&str_islower_obj },
340};
341
342STATIC MP_DEFINE_CONST_DICT(str_locals_dict, str_locals_dict_table);
343
344const mp_obj_type_t mp_type_str = {
345 { &mp_type_type },
346 .name = MP_QSTR_str,
Paul Sokolovsky86d38982014-06-13 23:00:15 +0300347 .print = uni_print,
Paul Sokolovsky83865342014-06-13 00:51:34 +0300348 .make_new = str_make_new,
Paul Sokolovskye7f2b4c2014-06-13 23:37:18 +0300349 .unary_op = uni_unary_op,
Damien Georgee04a44e2014-06-28 10:27:23 +0100350 .binary_op = mp_obj_str_binary_op,
Paul Sokolovsky83865342014-06-13 00:51:34 +0300351 .subscr = str_subscr,
352 .getiter = mp_obj_new_str_iterator,
Damien Georgee04a44e2014-06-28 10:27:23 +0100353 .buffer_p = { .get_buffer = mp_obj_str_get_buffer },
Paul Sokolovsky83865342014-06-13 00:51:34 +0300354 .locals_dict = (mp_obj_t)&str_locals_dict,
355};
356
Paul Sokolovsky83865342014-06-13 00:51:34 +0300357/******************************************************************************/
358/* str iterator */
359
360typedef struct _mp_obj_str_it_t {
361 mp_obj_base_t base;
362 mp_obj_t str;
Damien George40f3c022014-07-03 13:25:24 +0100363 mp_uint_t cur;
Paul Sokolovsky83865342014-06-13 00:51:34 +0300364} mp_obj_str_it_t;
365
366STATIC mp_obj_t str_it_iternext(mp_obj_t self_in) {
367 mp_obj_str_it_t *self = self_in;
368 GET_STR_DATA_LEN(self->str, str, len);
369 if (self->cur < len) {
Paul Sokolovsky79b7fe22014-06-14 02:07:25 +0300370 const byte *cur = str + self->cur;
371 const byte *end = utf8_next_char(str + self->cur);
372 mp_obj_t o_out = mp_obj_new_str((const char*)cur, end - cur, true);
373 self->cur += end - cur;
Paul Sokolovsky83865342014-06-13 00:51:34 +0300374 return o_out;
375 } else {
376 return MP_OBJ_STOP_ITERATION;
377 }
378}
379
380STATIC const mp_obj_type_t mp_type_str_it = {
381 { &mp_type_type },
382 .name = MP_QSTR_iterator,
383 .getiter = mp_identity,
384 .iternext = str_it_iternext,
385};
386
Paul Sokolovsky83865342014-06-13 00:51:34 +0300387mp_obj_t mp_obj_new_str_iterator(mp_obj_t str) {
388 mp_obj_str_it_t *o = m_new_obj(mp_obj_str_it_t);
389 o->base.type = &mp_type_str_it;
390 o->str = str;
391 o->cur = 0;
392 return o;
393}
394
Paul Sokolovsky97319122014-06-13 22:01:26 +0300395#endif // MICROPY_PY_BUILTINS_STR_UNICODE