blob: d96ce0a5527a2770c52c778781cc5eb79746aa92 [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);
Paul Sokolovsky86d38982014-06-13 23:00:15 +030096 if (kind == PRINT_STR) {
Paul Sokolovsky83865342014-06-13 00:51:34 +030097 print(env, "%.*s", str_len, str_data);
98 } else {
Paul Sokolovsky86d38982014-06-13 23:00:15 +030099 uni_print_quoted(print, env, str_data, str_len);
Paul Sokolovsky83865342014-06-13 00:51:34 +0300100 }
101}
102
Paul Sokolovskye7f2b4c2014-06-13 23:37:18 +0300103STATIC mp_obj_t uni_unary_op(int op, mp_obj_t self_in) {
104 GET_STR_DATA_LEN(self_in, str_data, str_len);
105 switch (op) {
106 case MP_UNARY_OP_BOOL:
107 return MP_BOOL(str_len != 0);
108 case MP_UNARY_OP_LEN:
Paul Sokolovsky9e215fa2014-06-28 23:14:30 +0300109 return MP_OBJ_NEW_SMALL_INT(unichar_charlen((const char *)str_data, str_len));
Paul Sokolovskye7f2b4c2014-06-13 23:37:18 +0300110 default:
111 return MP_OBJ_NULL; // op not supported
112 }
113}
114
Paul Sokolovsky83865342014-06-13 00:51:34 +0300115STATIC mp_obj_t str_make_new(mp_obj_t type_in, uint n_args, uint n_kw, const mp_obj_t *args) {
116#if MICROPY_CPYTHON_COMPAT
117 if (n_kw != 0) {
118 mp_arg_error_unimpl_kw();
119 }
120#endif
121
122 switch (n_args) {
123 case 0:
124 return MP_OBJ_NEW_QSTR(MP_QSTR_);
125
126 case 1:
127 {
128 vstr_t *vstr = vstr_new();
129 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, vstr, args[0], PRINT_STR);
130 mp_obj_t s = mp_obj_new_str(vstr->buf, vstr->len, false);
131 vstr_free(vstr);
132 return s;
133 }
134
135 case 2:
136 case 3:
137 {
138 // TODO: validate 2nd/3rd args
139 if (!MP_OBJ_IS_TYPE(args[0], &mp_type_bytes)) {
140 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "bytes expected"));
141 }
142 GET_STR_DATA_LEN(args[0], str_data, str_len);
143 GET_STR_HASH(args[0], str_hash);
144 mp_obj_str_t *o = mp_obj_new_str_of_type(&mp_type_str, NULL, str_len);
145 o->data = str_data;
146 o->hash = str_hash;
147 return o;
148 }
149
150 default:
151 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "str takes at most 3 arguments"));
152 }
153}
154
Chris Angelico64b468d2014-06-04 05:28:12 +1000155// Convert an index into a pointer to its lead byte. Out of bounds indexing will raise IndexError or
156// be capped to the first/last character of the string, depending on is_slice.
Paul Sokolovskyea2c9362014-06-15 00:35:09 +0300157const byte *str_index_to_ptr(const mp_obj_type_t *type, const byte *self_data, uint self_len,
158 mp_obj_t index, bool is_slice) {
Chris Angelico64b468d2014-06-04 05:28:12 +1000159 machine_int_t i;
160 // Copied from mp_get_index; I don't want bounds checking, just give me
161 // the integer as-is. (I can't bounds-check without scanning the whole
162 // string; an out-of-bounds index will be caught in the loops below.)
163 if (MP_OBJ_IS_SMALL_INT(index)) {
164 i = MP_OBJ_SMALL_INT_VALUE(index);
165 } else if (!mp_obj_get_int_maybe(index, &i)) {
166 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, "string indices must be integers, not %s", mp_obj_get_type_str(index)));
167 }
Paul Sokolovskyea2c9362014-06-15 00:35:09 +0300168 const byte *s, *top = self_data + self_len;
Chris Angelico64b468d2014-06-04 05:28:12 +1000169 if (i < 0)
170 {
171 // Negative indexing is performed by counting from the end of the string.
172 for (s = top - 1; i; --s) {
173 if (s < self_data) {
174 if (is_slice) {
175 return self_data;
176 }
177 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_IndexError, "string index out of range"));
178 }
179 if (!UTF8_IS_CONT(*s)) {
180 ++i;
181 }
182 }
183 ++s;
184 } else if (!i) {
185 return self_data; // Shortcut - str[0] is its base pointer
186 } else {
187 // Positive indexing, correspondingly, counts from the start of the string.
188 // It's assumed that negative indexing will generally be used with small
189 // absolute values (eg str[-1], not str[-1000000]), which means it'll be
190 // more efficient this way.
191 for (s = self_data; true; ++s) {
192 if (s >= top) {
193 if (is_slice) {
194 return top;
195 }
196 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_IndexError, "string index out of range"));
197 }
198 while (UTF8_IS_CONT(*s)) {
199 ++s;
200 }
201 if (!i--) {
202 return s;
203 }
204 }
205 }
206 return s;
207}
208
Paul Sokolovsky83865342014-06-13 00:51:34 +0300209STATIC mp_obj_t str_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) {
210 mp_obj_type_t *type = mp_obj_get_type(self_in);
211 GET_STR_DATA_LEN(self_in, self_data, self_len);
212 if (value == MP_OBJ_SENTINEL) {
213 // load
214#if MICROPY_PY_BUILTINS_SLICE
215 if (MP_OBJ_IS_TYPE(index, &mp_type_slice)) {
Chris Angelico64b468d2014-06-04 05:28:12 +1000216 mp_obj_t ostart, ostop, ostep;
217 mp_obj_slice_get(index, &ostart, &ostop, &ostep);
218 if (ostep != mp_const_none && ostep != MP_OBJ_NEW_SMALL_INT(1)) {
Paul Sokolovsky83865342014-06-13 00:51:34 +0300219 nlr_raise(mp_obj_new_exception_msg(&mp_type_NotImplementedError,
220 "only slices with step=1 (aka None) are supported"));
221 }
Chris Angelico64b468d2014-06-04 05:28:12 +1000222
223 if (type == &mp_type_bytes) {
224 machine_int_t start = 0, stop = self_len;
225 if (ostart != mp_const_none) {
226 start = MP_OBJ_SMALL_INT_VALUE(ostart);
227 if (start < 0) {
228 start = self_len + start;
229 }
230 }
231 if (ostop != mp_const_none) {
232 stop = MP_OBJ_SMALL_INT_VALUE(ostop);
233 if (stop < 0) {
234 stop = self_len + stop;
235 }
236 }
237 return mp_obj_new_str_of_type(type, self_data + start, stop - start);
238 }
Paul Sokolovskyea2c9362014-06-15 00:35:09 +0300239 const byte *pstart, *pstop;
Chris Angelico64b468d2014-06-04 05:28:12 +1000240 if (ostart != mp_const_none) {
Paul Sokolovskyea2c9362014-06-15 00:35:09 +0300241 pstart = str_index_to_ptr(type, self_data, self_len, ostart, true);
Chris Angelico64b468d2014-06-04 05:28:12 +1000242 } else {
Paul Sokolovskyea2c9362014-06-15 00:35:09 +0300243 pstart = self_data;
Chris Angelico64b468d2014-06-04 05:28:12 +1000244 }
245 if (ostop != mp_const_none) {
246 // pstop will point just after the stop character. This depends on
247 // the \0 at the end of the string.
Paul Sokolovskyea2c9362014-06-15 00:35:09 +0300248 pstop = str_index_to_ptr(type, self_data, self_len, ostop, true);
Chris Angelico64b468d2014-06-04 05:28:12 +1000249 } else {
Paul Sokolovskyea2c9362014-06-15 00:35:09 +0300250 pstop = self_data + self_len;
Chris Angelico64b468d2014-06-04 05:28:12 +1000251 }
252 if (pstop < pstart) {
253 return MP_OBJ_NEW_QSTR(MP_QSTR_);
254 }
255 return mp_obj_new_str_of_type(type, (const byte *)pstart, pstop - pstart);
Paul Sokolovsky83865342014-06-13 00:51:34 +0300256 }
257#endif
Paul Sokolovsky83865342014-06-13 00:51:34 +0300258 if (type == &mp_type_bytes) {
Chris Angelico64b468d2014-06-04 05:28:12 +1000259 uint index_val = mp_get_index(type, self_len, index, false);
Paul Sokolovsky83865342014-06-13 00:51:34 +0300260 return MP_OBJ_NEW_SMALL_INT((mp_small_int_t)self_data[index_val]);
Paul Sokolovsky83865342014-06-13 00:51:34 +0300261 }
Paul Sokolovskyea2c9362014-06-15 00:35:09 +0300262 const byte *s = str_index_to_ptr(type, self_data, self_len, index, false);
Chris Angelico64b468d2014-06-04 05:28:12 +1000263 int len = 1;
264 if (UTF8_IS_NONASCII(*s)) {
265 // Count the number of 1 bits (after the first)
266 for (char mask = 0x40; *s & mask; mask >>= 1) {
267 ++len;
268 }
269 }
Paul Sokolovskyea2c9362014-06-15 00:35:09 +0300270 return mp_obj_new_str((const char*)s, len, true); // This will create a one-character string
Paul Sokolovsky83865342014-06-13 00:51:34 +0300271 } else {
272 return MP_OBJ_NULL; // op not supported
273 }
274}
275
Paul Sokolovsky83865342014-06-13 00:51:34 +0300276STATIC const mp_map_elem_t str_locals_dict_table[] = {
277#if MICROPY_CPYTHON_COMPAT
Paul Sokolovsky83865342014-06-13 00:51:34 +0300278 { MP_OBJ_NEW_QSTR(MP_QSTR_encode), (mp_obj_t)&str_encode_obj },
279#endif
280 { MP_OBJ_NEW_QSTR(MP_QSTR_find), (mp_obj_t)&str_find_obj },
281 { MP_OBJ_NEW_QSTR(MP_QSTR_rfind), (mp_obj_t)&str_rfind_obj },
282 { MP_OBJ_NEW_QSTR(MP_QSTR_index), (mp_obj_t)&str_index_obj },
283 { MP_OBJ_NEW_QSTR(MP_QSTR_rindex), (mp_obj_t)&str_rindex_obj },
284 { MP_OBJ_NEW_QSTR(MP_QSTR_join), (mp_obj_t)&str_join_obj },
285 { MP_OBJ_NEW_QSTR(MP_QSTR_split), (mp_obj_t)&str_split_obj },
286 { MP_OBJ_NEW_QSTR(MP_QSTR_rsplit), (mp_obj_t)&str_rsplit_obj },
287 { MP_OBJ_NEW_QSTR(MP_QSTR_startswith), (mp_obj_t)&str_startswith_obj },
288 { MP_OBJ_NEW_QSTR(MP_QSTR_endswith), (mp_obj_t)&str_endswith_obj },
289 { MP_OBJ_NEW_QSTR(MP_QSTR_strip), (mp_obj_t)&str_strip_obj },
290 { MP_OBJ_NEW_QSTR(MP_QSTR_lstrip), (mp_obj_t)&str_lstrip_obj },
291 { MP_OBJ_NEW_QSTR(MP_QSTR_rstrip), (mp_obj_t)&str_rstrip_obj },
292 { MP_OBJ_NEW_QSTR(MP_QSTR_format), (mp_obj_t)&str_format_obj },
293 { MP_OBJ_NEW_QSTR(MP_QSTR_replace), (mp_obj_t)&str_replace_obj },
294 { MP_OBJ_NEW_QSTR(MP_QSTR_count), (mp_obj_t)&str_count_obj },
295 { MP_OBJ_NEW_QSTR(MP_QSTR_partition), (mp_obj_t)&str_partition_obj },
296 { MP_OBJ_NEW_QSTR(MP_QSTR_rpartition), (mp_obj_t)&str_rpartition_obj },
297 { MP_OBJ_NEW_QSTR(MP_QSTR_lower), (mp_obj_t)&str_lower_obj },
298 { MP_OBJ_NEW_QSTR(MP_QSTR_upper), (mp_obj_t)&str_upper_obj },
299 { MP_OBJ_NEW_QSTR(MP_QSTR_isspace), (mp_obj_t)&str_isspace_obj },
300 { MP_OBJ_NEW_QSTR(MP_QSTR_isalpha), (mp_obj_t)&str_isalpha_obj },
301 { MP_OBJ_NEW_QSTR(MP_QSTR_isdigit), (mp_obj_t)&str_isdigit_obj },
302 { MP_OBJ_NEW_QSTR(MP_QSTR_isupper), (mp_obj_t)&str_isupper_obj },
303 { MP_OBJ_NEW_QSTR(MP_QSTR_islower), (mp_obj_t)&str_islower_obj },
304};
305
306STATIC MP_DEFINE_CONST_DICT(str_locals_dict, str_locals_dict_table);
307
308const mp_obj_type_t mp_type_str = {
309 { &mp_type_type },
310 .name = MP_QSTR_str,
Paul Sokolovsky86d38982014-06-13 23:00:15 +0300311 .print = uni_print,
Paul Sokolovsky83865342014-06-13 00:51:34 +0300312 .make_new = str_make_new,
Paul Sokolovskye7f2b4c2014-06-13 23:37:18 +0300313 .unary_op = uni_unary_op,
Damien Georgee04a44e2014-06-28 10:27:23 +0100314 .binary_op = mp_obj_str_binary_op,
Paul Sokolovsky83865342014-06-13 00:51:34 +0300315 .subscr = str_subscr,
316 .getiter = mp_obj_new_str_iterator,
Damien Georgee04a44e2014-06-28 10:27:23 +0100317 .buffer_p = { .get_buffer = mp_obj_str_get_buffer },
Paul Sokolovsky83865342014-06-13 00:51:34 +0300318 .locals_dict = (mp_obj_t)&str_locals_dict,
319};
320
Paul Sokolovsky83865342014-06-13 00:51:34 +0300321/******************************************************************************/
322/* str iterator */
323
324typedef struct _mp_obj_str_it_t {
325 mp_obj_base_t base;
326 mp_obj_t str;
327 machine_uint_t cur;
328} mp_obj_str_it_t;
329
330STATIC mp_obj_t str_it_iternext(mp_obj_t self_in) {
331 mp_obj_str_it_t *self = self_in;
332 GET_STR_DATA_LEN(self->str, str, len);
333 if (self->cur < len) {
Paul Sokolovsky79b7fe22014-06-14 02:07:25 +0300334 const byte *cur = str + self->cur;
335 const byte *end = utf8_next_char(str + self->cur);
336 mp_obj_t o_out = mp_obj_new_str((const char*)cur, end - cur, true);
337 self->cur += end - cur;
Paul Sokolovsky83865342014-06-13 00:51:34 +0300338 return o_out;
339 } else {
340 return MP_OBJ_STOP_ITERATION;
341 }
342}
343
344STATIC const mp_obj_type_t mp_type_str_it = {
345 { &mp_type_type },
346 .name = MP_QSTR_iterator,
347 .getiter = mp_identity,
348 .iternext = str_it_iternext,
349};
350
Paul Sokolovsky83865342014-06-13 00:51:34 +0300351mp_obj_t mp_obj_new_str_iterator(mp_obj_t str) {
352 mp_obj_str_it_t *o = m_new_obj(mp_obj_str_it_t);
353 o->base.type = &mp_type_str_it;
354 o->str = str;
355 o->cur = 0;
356 return o;
357}
358
Paul Sokolovsky97319122014-06-13 22:01:26 +0300359#endif // MICROPY_PY_BUILTINS_STR_UNICODE