blob: d41e92db4a398be8ff54c28804d2a75c2c01d49e [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);
Chris Angelico64b468d2014-06-04 05:28:12 +100066 const char *s = (const char *)str_data, *top = (const char *)str_data + str_len;
67 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
103STATIC mp_obj_t str_make_new(mp_obj_t type_in, uint n_args, uint n_kw, const mp_obj_t *args) {
104#if MICROPY_CPYTHON_COMPAT
105 if (n_kw != 0) {
106 mp_arg_error_unimpl_kw();
107 }
108#endif
109
110 switch (n_args) {
111 case 0:
112 return MP_OBJ_NEW_QSTR(MP_QSTR_);
113
114 case 1:
115 {
116 vstr_t *vstr = vstr_new();
117 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, vstr, args[0], PRINT_STR);
118 mp_obj_t s = mp_obj_new_str(vstr->buf, vstr->len, false);
119 vstr_free(vstr);
120 return s;
121 }
122
123 case 2:
124 case 3:
125 {
126 // TODO: validate 2nd/3rd args
127 if (!MP_OBJ_IS_TYPE(args[0], &mp_type_bytes)) {
128 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "bytes expected"));
129 }
130 GET_STR_DATA_LEN(args[0], str_data, str_len);
131 GET_STR_HASH(args[0], str_hash);
132 mp_obj_str_t *o = mp_obj_new_str_of_type(&mp_type_str, NULL, str_len);
133 o->data = str_data;
134 o->hash = str_hash;
135 return o;
136 }
137
138 default:
139 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "str takes at most 3 arguments"));
140 }
141}
142
Chris Angelico64b468d2014-06-04 05:28:12 +1000143// Convert an index into a pointer to its lead byte. Out of bounds indexing will raise IndexError or
144// be capped to the first/last character of the string, depending on is_slice.
145STATIC const char *str_index_to_ptr(const char *self_data, uint self_len, mp_obj_t index, bool is_slice) {
146 machine_int_t i;
147 // Copied from mp_get_index; I don't want bounds checking, just give me
148 // the integer as-is. (I can't bounds-check without scanning the whole
149 // string; an out-of-bounds index will be caught in the loops below.)
150 if (MP_OBJ_IS_SMALL_INT(index)) {
151 i = MP_OBJ_SMALL_INT_VALUE(index);
152 } else if (!mp_obj_get_int_maybe(index, &i)) {
153 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, "string indices must be integers, not %s", mp_obj_get_type_str(index)));
154 }
155 const char *s, *top = self_data + self_len;
156 if (i < 0)
157 {
158 // Negative indexing is performed by counting from the end of the string.
159 for (s = top - 1; i; --s) {
160 if (s < self_data) {
161 if (is_slice) {
162 return self_data;
163 }
164 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_IndexError, "string index out of range"));
165 }
166 if (!UTF8_IS_CONT(*s)) {
167 ++i;
168 }
169 }
170 ++s;
171 } else if (!i) {
172 return self_data; // Shortcut - str[0] is its base pointer
173 } else {
174 // Positive indexing, correspondingly, counts from the start of the string.
175 // It's assumed that negative indexing will generally be used with small
176 // absolute values (eg str[-1], not str[-1000000]), which means it'll be
177 // more efficient this way.
178 for (s = self_data; true; ++s) {
179 if (s >= top) {
180 if (is_slice) {
181 return top;
182 }
183 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_IndexError, "string index out of range"));
184 }
185 while (UTF8_IS_CONT(*s)) {
186 ++s;
187 }
188 if (!i--) {
189 return s;
190 }
191 }
192 }
193 return s;
194}
195
Paul Sokolovsky83865342014-06-13 00:51:34 +0300196STATIC mp_obj_t str_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) {
197 mp_obj_type_t *type = mp_obj_get_type(self_in);
198 GET_STR_DATA_LEN(self_in, self_data, self_len);
199 if (value == MP_OBJ_SENTINEL) {
200 // load
201#if MICROPY_PY_BUILTINS_SLICE
202 if (MP_OBJ_IS_TYPE(index, &mp_type_slice)) {
Chris Angelico64b468d2014-06-04 05:28:12 +1000203 mp_obj_t ostart, ostop, ostep;
204 mp_obj_slice_get(index, &ostart, &ostop, &ostep);
205 if (ostep != mp_const_none && ostep != MP_OBJ_NEW_SMALL_INT(1)) {
Paul Sokolovsky83865342014-06-13 00:51:34 +0300206 nlr_raise(mp_obj_new_exception_msg(&mp_type_NotImplementedError,
207 "only slices with step=1 (aka None) are supported"));
208 }
Chris Angelico64b468d2014-06-04 05:28:12 +1000209
210 if (type == &mp_type_bytes) {
211 machine_int_t start = 0, stop = self_len;
212 if (ostart != mp_const_none) {
213 start = MP_OBJ_SMALL_INT_VALUE(ostart);
214 if (start < 0) {
215 start = self_len + start;
216 }
217 }
218 if (ostop != mp_const_none) {
219 stop = MP_OBJ_SMALL_INT_VALUE(ostop);
220 if (stop < 0) {
221 stop = self_len + stop;
222 }
223 }
224 return mp_obj_new_str_of_type(type, self_data + start, stop - start);
225 }
226 const char *pstart, *pstop;
227 if (ostart != mp_const_none) {
228 pstart = str_index_to_ptr((const char *)self_data, self_len, ostart, true);
229 } else {
230 pstart = (const char *)self_data;
231 }
232 if (ostop != mp_const_none) {
233 // pstop will point just after the stop character. This depends on
234 // the \0 at the end of the string.
235 pstop = str_index_to_ptr((const char *)self_data, self_len, ostop, true);
236 } else {
237 pstop = (const char *)self_data + self_len;
238 }
239 if (pstop < pstart) {
240 return MP_OBJ_NEW_QSTR(MP_QSTR_);
241 }
242 return mp_obj_new_str_of_type(type, (const byte *)pstart, pstop - pstart);
Paul Sokolovsky83865342014-06-13 00:51:34 +0300243 }
244#endif
Paul Sokolovsky83865342014-06-13 00:51:34 +0300245 if (type == &mp_type_bytes) {
Chris Angelico64b468d2014-06-04 05:28:12 +1000246 uint index_val = mp_get_index(type, self_len, index, false);
Paul Sokolovsky83865342014-06-13 00:51:34 +0300247 return MP_OBJ_NEW_SMALL_INT((mp_small_int_t)self_data[index_val]);
Paul Sokolovsky83865342014-06-13 00:51:34 +0300248 }
Chris Angelico64b468d2014-06-04 05:28:12 +1000249 const char *s = str_index_to_ptr((const char *)self_data, self_len, index, false);
250 int len = 1;
251 if (UTF8_IS_NONASCII(*s)) {
252 // Count the number of 1 bits (after the first)
253 for (char mask = 0x40; *s & mask; mask >>= 1) {
254 ++len;
255 }
256 }
257 return mp_obj_new_str(s, len, true); // This will create a one-character string
Paul Sokolovsky83865342014-06-13 00:51:34 +0300258 } else {
259 return MP_OBJ_NULL; // op not supported
260 }
261}
262
Paul Sokolovsky83865342014-06-13 00:51:34 +0300263STATIC const mp_map_elem_t str_locals_dict_table[] = {
264#if MICROPY_CPYTHON_COMPAT
Paul Sokolovsky83865342014-06-13 00:51:34 +0300265 { MP_OBJ_NEW_QSTR(MP_QSTR_encode), (mp_obj_t)&str_encode_obj },
266#endif
267 { MP_OBJ_NEW_QSTR(MP_QSTR_find), (mp_obj_t)&str_find_obj },
268 { MP_OBJ_NEW_QSTR(MP_QSTR_rfind), (mp_obj_t)&str_rfind_obj },
269 { MP_OBJ_NEW_QSTR(MP_QSTR_index), (mp_obj_t)&str_index_obj },
270 { MP_OBJ_NEW_QSTR(MP_QSTR_rindex), (mp_obj_t)&str_rindex_obj },
271 { MP_OBJ_NEW_QSTR(MP_QSTR_join), (mp_obj_t)&str_join_obj },
272 { MP_OBJ_NEW_QSTR(MP_QSTR_split), (mp_obj_t)&str_split_obj },
273 { MP_OBJ_NEW_QSTR(MP_QSTR_rsplit), (mp_obj_t)&str_rsplit_obj },
274 { MP_OBJ_NEW_QSTR(MP_QSTR_startswith), (mp_obj_t)&str_startswith_obj },
275 { MP_OBJ_NEW_QSTR(MP_QSTR_endswith), (mp_obj_t)&str_endswith_obj },
276 { MP_OBJ_NEW_QSTR(MP_QSTR_strip), (mp_obj_t)&str_strip_obj },
277 { MP_OBJ_NEW_QSTR(MP_QSTR_lstrip), (mp_obj_t)&str_lstrip_obj },
278 { MP_OBJ_NEW_QSTR(MP_QSTR_rstrip), (mp_obj_t)&str_rstrip_obj },
279 { MP_OBJ_NEW_QSTR(MP_QSTR_format), (mp_obj_t)&str_format_obj },
280 { MP_OBJ_NEW_QSTR(MP_QSTR_replace), (mp_obj_t)&str_replace_obj },
281 { MP_OBJ_NEW_QSTR(MP_QSTR_count), (mp_obj_t)&str_count_obj },
282 { MP_OBJ_NEW_QSTR(MP_QSTR_partition), (mp_obj_t)&str_partition_obj },
283 { MP_OBJ_NEW_QSTR(MP_QSTR_rpartition), (mp_obj_t)&str_rpartition_obj },
284 { MP_OBJ_NEW_QSTR(MP_QSTR_lower), (mp_obj_t)&str_lower_obj },
285 { MP_OBJ_NEW_QSTR(MP_QSTR_upper), (mp_obj_t)&str_upper_obj },
286 { MP_OBJ_NEW_QSTR(MP_QSTR_isspace), (mp_obj_t)&str_isspace_obj },
287 { MP_OBJ_NEW_QSTR(MP_QSTR_isalpha), (mp_obj_t)&str_isalpha_obj },
288 { MP_OBJ_NEW_QSTR(MP_QSTR_isdigit), (mp_obj_t)&str_isdigit_obj },
289 { MP_OBJ_NEW_QSTR(MP_QSTR_isupper), (mp_obj_t)&str_isupper_obj },
290 { MP_OBJ_NEW_QSTR(MP_QSTR_islower), (mp_obj_t)&str_islower_obj },
291};
292
293STATIC MP_DEFINE_CONST_DICT(str_locals_dict, str_locals_dict_table);
294
295const mp_obj_type_t mp_type_str = {
296 { &mp_type_type },
297 .name = MP_QSTR_str,
Paul Sokolovsky86d38982014-06-13 23:00:15 +0300298 .print = uni_print,
Paul Sokolovsky83865342014-06-13 00:51:34 +0300299 .make_new = str_make_new,
300 .binary_op = str_binary_op,
301 .subscr = str_subscr,
302 .getiter = mp_obj_new_str_iterator,
Paul Sokolovsky97319122014-06-13 22:01:26 +0300303// .buffer_p = { .get_buffer = str_get_buffer },
Paul Sokolovsky83865342014-06-13 00:51:34 +0300304 .locals_dict = (mp_obj_t)&str_locals_dict,
305};
306
Paul Sokolovsky83865342014-06-13 00:51:34 +0300307/******************************************************************************/
308/* str iterator */
309
310typedef struct _mp_obj_str_it_t {
311 mp_obj_base_t base;
312 mp_obj_t str;
313 machine_uint_t cur;
314} mp_obj_str_it_t;
315
316STATIC mp_obj_t str_it_iternext(mp_obj_t self_in) {
317 mp_obj_str_it_t *self = self_in;
318 GET_STR_DATA_LEN(self->str, str, len);
319 if (self->cur < len) {
320 mp_obj_t o_out = mp_obj_new_str((const char*)str + self->cur, 1, true);
321 self->cur += 1;
322 return o_out;
323 } else {
324 return MP_OBJ_STOP_ITERATION;
325 }
326}
327
328STATIC const mp_obj_type_t mp_type_str_it = {
329 { &mp_type_type },
330 .name = MP_QSTR_iterator,
331 .getiter = mp_identity,
332 .iternext = str_it_iternext,
333};
334
Paul Sokolovsky83865342014-06-13 00:51:34 +0300335mp_obj_t mp_obj_new_str_iterator(mp_obj_t str) {
336 mp_obj_str_it_t *o = m_new_obj(mp_obj_str_it_t);
337 o->base.type = &mp_type_str_it;
338 o->str = str;
339 o->cur = 0;
340 return o;
341}
342
Paul Sokolovsky97319122014-06-13 22:01:26 +0300343#endif // MICROPY_PY_BUILTINS_STR_UNICODE