blob: 741f1b76e8381d65f3e7231ea6e1cf2b409bdca2 [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 Sokolovsky97319122014-06-13 22:01:26 +030050STATIC void uni_print_quoted(void (*print)(void *env, const char *fmt, ...), void *env, const byte *str_data, uint str_len, bool is_bytes) {
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;
69 if (is_bytes) {
70 ch = *(unsigned char *)s++; // Don't sign-extend bytes
Paul Sokolovsky83865342014-06-13 00:51:34 +030071 } else {
Chris Angelico64b468d2014-06-04 05:28:12 +100072 ch = utf8_get_char(s);
73 s = utf8_next_char(s);
74 }
75 if (ch == quote_char) {
76 print(env, "\\%c", quote_char);
77 } else if (ch == '\\') {
78 print(env, "\\\\");
79 } else if (32 <= ch && ch <= 126) {
80 print(env, "%c", ch);
81 } else if (ch == '\n') {
82 print(env, "\\n");
83 } else if (ch == '\r') {
84 print(env, "\\r");
85 } else if (ch == '\t') {
86 print(env, "\\t");
87 } else if (ch < 0x100) {
88 print(env, "\\x%02x", ch);
89 } else if (ch < 0x10000) {
90 print(env, "\\u%04x", ch);
91 } else {
92 print(env, "\\U%08x", ch);
Paul Sokolovsky83865342014-06-13 00:51:34 +030093 }
94 }
95 print(env, "%c", quote_char);
96}
97
98STATIC void str_print(void (*print)(void *env, const char *fmt, ...), void *env, mp_obj_t self_in, mp_print_kind_t kind) {
99 GET_STR_DATA_LEN(self_in, str_data, str_len);
100 bool is_bytes = MP_OBJ_IS_TYPE(self_in, &mp_type_bytes);
101 if (kind == PRINT_STR && !is_bytes) {
102 print(env, "%.*s", str_len, str_data);
103 } else {
104 if (is_bytes) {
105 print(env, "b");
106 }
Paul Sokolovsky97319122014-06-13 22:01:26 +0300107 uni_print_quoted(print, env, str_data, str_len, is_bytes);
Paul Sokolovsky83865342014-06-13 00:51:34 +0300108 }
109}
110
111STATIC mp_obj_t str_make_new(mp_obj_t type_in, uint n_args, uint n_kw, const mp_obj_t *args) {
112#if MICROPY_CPYTHON_COMPAT
113 if (n_kw != 0) {
114 mp_arg_error_unimpl_kw();
115 }
116#endif
117
118 switch (n_args) {
119 case 0:
120 return MP_OBJ_NEW_QSTR(MP_QSTR_);
121
122 case 1:
123 {
124 vstr_t *vstr = vstr_new();
125 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, vstr, args[0], PRINT_STR);
126 mp_obj_t s = mp_obj_new_str(vstr->buf, vstr->len, false);
127 vstr_free(vstr);
128 return s;
129 }
130
131 case 2:
132 case 3:
133 {
134 // TODO: validate 2nd/3rd args
135 if (!MP_OBJ_IS_TYPE(args[0], &mp_type_bytes)) {
136 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "bytes expected"));
137 }
138 GET_STR_DATA_LEN(args[0], str_data, str_len);
139 GET_STR_HASH(args[0], str_hash);
140 mp_obj_str_t *o = mp_obj_new_str_of_type(&mp_type_str, NULL, str_len);
141 o->data = str_data;
142 o->hash = str_hash;
143 return o;
144 }
145
146 default:
147 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "str takes at most 3 arguments"));
148 }
149}
150
Chris Angelico64b468d2014-06-04 05:28:12 +1000151// Convert an index into a pointer to its lead byte. Out of bounds indexing will raise IndexError or
152// be capped to the first/last character of the string, depending on is_slice.
153STATIC const char *str_index_to_ptr(const char *self_data, uint self_len, mp_obj_t index, bool is_slice) {
154 machine_int_t i;
155 // Copied from mp_get_index; I don't want bounds checking, just give me
156 // the integer as-is. (I can't bounds-check without scanning the whole
157 // string; an out-of-bounds index will be caught in the loops below.)
158 if (MP_OBJ_IS_SMALL_INT(index)) {
159 i = MP_OBJ_SMALL_INT_VALUE(index);
160 } else if (!mp_obj_get_int_maybe(index, &i)) {
161 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, "string indices must be integers, not %s", mp_obj_get_type_str(index)));
162 }
163 const char *s, *top = self_data + self_len;
164 if (i < 0)
165 {
166 // Negative indexing is performed by counting from the end of the string.
167 for (s = top - 1; i; --s) {
168 if (s < self_data) {
169 if (is_slice) {
170 return self_data;
171 }
172 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_IndexError, "string index out of range"));
173 }
174 if (!UTF8_IS_CONT(*s)) {
175 ++i;
176 }
177 }
178 ++s;
179 } else if (!i) {
180 return self_data; // Shortcut - str[0] is its base pointer
181 } else {
182 // Positive indexing, correspondingly, counts from the start of the string.
183 // It's assumed that negative indexing will generally be used with small
184 // absolute values (eg str[-1], not str[-1000000]), which means it'll be
185 // more efficient this way.
186 for (s = self_data; true; ++s) {
187 if (s >= top) {
188 if (is_slice) {
189 return top;
190 }
191 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_IndexError, "string index out of range"));
192 }
193 while (UTF8_IS_CONT(*s)) {
194 ++s;
195 }
196 if (!i--) {
197 return s;
198 }
199 }
200 }
201 return s;
202}
203
Paul Sokolovsky83865342014-06-13 00:51:34 +0300204STATIC mp_obj_t str_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) {
205 mp_obj_type_t *type = mp_obj_get_type(self_in);
206 GET_STR_DATA_LEN(self_in, self_data, self_len);
207 if (value == MP_OBJ_SENTINEL) {
208 // load
209#if MICROPY_PY_BUILTINS_SLICE
210 if (MP_OBJ_IS_TYPE(index, &mp_type_slice)) {
Chris Angelico64b468d2014-06-04 05:28:12 +1000211 mp_obj_t ostart, ostop, ostep;
212 mp_obj_slice_get(index, &ostart, &ostop, &ostep);
213 if (ostep != mp_const_none && ostep != MP_OBJ_NEW_SMALL_INT(1)) {
Paul Sokolovsky83865342014-06-13 00:51:34 +0300214 nlr_raise(mp_obj_new_exception_msg(&mp_type_NotImplementedError,
215 "only slices with step=1 (aka None) are supported"));
216 }
Chris Angelico64b468d2014-06-04 05:28:12 +1000217
218 if (type == &mp_type_bytes) {
219 machine_int_t start = 0, stop = self_len;
220 if (ostart != mp_const_none) {
221 start = MP_OBJ_SMALL_INT_VALUE(ostart);
222 if (start < 0) {
223 start = self_len + start;
224 }
225 }
226 if (ostop != mp_const_none) {
227 stop = MP_OBJ_SMALL_INT_VALUE(ostop);
228 if (stop < 0) {
229 stop = self_len + stop;
230 }
231 }
232 return mp_obj_new_str_of_type(type, self_data + start, stop - start);
233 }
234 const char *pstart, *pstop;
235 if (ostart != mp_const_none) {
236 pstart = str_index_to_ptr((const char *)self_data, self_len, ostart, true);
237 } else {
238 pstart = (const char *)self_data;
239 }
240 if (ostop != mp_const_none) {
241 // pstop will point just after the stop character. This depends on
242 // the \0 at the end of the string.
243 pstop = str_index_to_ptr((const char *)self_data, self_len, ostop, true);
244 } else {
245 pstop = (const char *)self_data + self_len;
246 }
247 if (pstop < pstart) {
248 return MP_OBJ_NEW_QSTR(MP_QSTR_);
249 }
250 return mp_obj_new_str_of_type(type, (const byte *)pstart, pstop - pstart);
Paul Sokolovsky83865342014-06-13 00:51:34 +0300251 }
252#endif
Paul Sokolovsky83865342014-06-13 00:51:34 +0300253 if (type == &mp_type_bytes) {
Chris Angelico64b468d2014-06-04 05:28:12 +1000254 uint index_val = mp_get_index(type, self_len, index, false);
Paul Sokolovsky83865342014-06-13 00:51:34 +0300255 return MP_OBJ_NEW_SMALL_INT((mp_small_int_t)self_data[index_val]);
Paul Sokolovsky83865342014-06-13 00:51:34 +0300256 }
Chris Angelico64b468d2014-06-04 05:28:12 +1000257 const char *s = str_index_to_ptr((const char *)self_data, self_len, index, false);
258 int len = 1;
259 if (UTF8_IS_NONASCII(*s)) {
260 // Count the number of 1 bits (after the first)
261 for (char mask = 0x40; *s & mask; mask >>= 1) {
262 ++len;
263 }
264 }
265 return mp_obj_new_str(s, len, true); // This will create a one-character string
Paul Sokolovsky83865342014-06-13 00:51:34 +0300266 } else {
267 return MP_OBJ_NULL; // op not supported
268 }
269}
270
Paul Sokolovsky83865342014-06-13 00:51:34 +0300271STATIC const mp_map_elem_t str_locals_dict_table[] = {
272#if MICROPY_CPYTHON_COMPAT
Paul Sokolovsky83865342014-06-13 00:51:34 +0300273 { MP_OBJ_NEW_QSTR(MP_QSTR_encode), (mp_obj_t)&str_encode_obj },
274#endif
275 { MP_OBJ_NEW_QSTR(MP_QSTR_find), (mp_obj_t)&str_find_obj },
276 { MP_OBJ_NEW_QSTR(MP_QSTR_rfind), (mp_obj_t)&str_rfind_obj },
277 { MP_OBJ_NEW_QSTR(MP_QSTR_index), (mp_obj_t)&str_index_obj },
278 { MP_OBJ_NEW_QSTR(MP_QSTR_rindex), (mp_obj_t)&str_rindex_obj },
279 { MP_OBJ_NEW_QSTR(MP_QSTR_join), (mp_obj_t)&str_join_obj },
280 { MP_OBJ_NEW_QSTR(MP_QSTR_split), (mp_obj_t)&str_split_obj },
281 { MP_OBJ_NEW_QSTR(MP_QSTR_rsplit), (mp_obj_t)&str_rsplit_obj },
282 { MP_OBJ_NEW_QSTR(MP_QSTR_startswith), (mp_obj_t)&str_startswith_obj },
283 { MP_OBJ_NEW_QSTR(MP_QSTR_endswith), (mp_obj_t)&str_endswith_obj },
284 { MP_OBJ_NEW_QSTR(MP_QSTR_strip), (mp_obj_t)&str_strip_obj },
285 { MP_OBJ_NEW_QSTR(MP_QSTR_lstrip), (mp_obj_t)&str_lstrip_obj },
286 { MP_OBJ_NEW_QSTR(MP_QSTR_rstrip), (mp_obj_t)&str_rstrip_obj },
287 { MP_OBJ_NEW_QSTR(MP_QSTR_format), (mp_obj_t)&str_format_obj },
288 { MP_OBJ_NEW_QSTR(MP_QSTR_replace), (mp_obj_t)&str_replace_obj },
289 { MP_OBJ_NEW_QSTR(MP_QSTR_count), (mp_obj_t)&str_count_obj },
290 { MP_OBJ_NEW_QSTR(MP_QSTR_partition), (mp_obj_t)&str_partition_obj },
291 { MP_OBJ_NEW_QSTR(MP_QSTR_rpartition), (mp_obj_t)&str_rpartition_obj },
292 { MP_OBJ_NEW_QSTR(MP_QSTR_lower), (mp_obj_t)&str_lower_obj },
293 { MP_OBJ_NEW_QSTR(MP_QSTR_upper), (mp_obj_t)&str_upper_obj },
294 { MP_OBJ_NEW_QSTR(MP_QSTR_isspace), (mp_obj_t)&str_isspace_obj },
295 { MP_OBJ_NEW_QSTR(MP_QSTR_isalpha), (mp_obj_t)&str_isalpha_obj },
296 { MP_OBJ_NEW_QSTR(MP_QSTR_isdigit), (mp_obj_t)&str_isdigit_obj },
297 { MP_OBJ_NEW_QSTR(MP_QSTR_isupper), (mp_obj_t)&str_isupper_obj },
298 { MP_OBJ_NEW_QSTR(MP_QSTR_islower), (mp_obj_t)&str_islower_obj },
299};
300
301STATIC MP_DEFINE_CONST_DICT(str_locals_dict, str_locals_dict_table);
302
303const mp_obj_type_t mp_type_str = {
304 { &mp_type_type },
305 .name = MP_QSTR_str,
306 .print = str_print,
307 .make_new = str_make_new,
308 .binary_op = str_binary_op,
309 .subscr = str_subscr,
310 .getiter = mp_obj_new_str_iterator,
Paul Sokolovsky97319122014-06-13 22:01:26 +0300311// .buffer_p = { .get_buffer = str_get_buffer },
Paul Sokolovsky83865342014-06-13 00:51:34 +0300312 .locals_dict = (mp_obj_t)&str_locals_dict,
313};
314
Paul Sokolovsky83865342014-06-13 00:51:34 +0300315/******************************************************************************/
316/* str iterator */
317
318typedef struct _mp_obj_str_it_t {
319 mp_obj_base_t base;
320 mp_obj_t str;
321 machine_uint_t cur;
322} mp_obj_str_it_t;
323
324STATIC mp_obj_t str_it_iternext(mp_obj_t self_in) {
325 mp_obj_str_it_t *self = self_in;
326 GET_STR_DATA_LEN(self->str, str, len);
327 if (self->cur < len) {
328 mp_obj_t o_out = mp_obj_new_str((const char*)str + self->cur, 1, true);
329 self->cur += 1;
330 return o_out;
331 } else {
332 return MP_OBJ_STOP_ITERATION;
333 }
334}
335
336STATIC const mp_obj_type_t mp_type_str_it = {
337 { &mp_type_type },
338 .name = MP_QSTR_iterator,
339 .getiter = mp_identity,
340 .iternext = str_it_iternext,
341};
342
Paul Sokolovsky83865342014-06-13 00:51:34 +0300343mp_obj_t mp_obj_new_str_iterator(mp_obj_t str) {
344 mp_obj_str_it_t *o = m_new_obj(mp_obj_str_it_t);
345 o->base.type = &mp_type_str_it;
346 o->str = str;
347 o->cur = 0;
348 return o;
349}
350
Paul Sokolovsky97319122014-06-13 22:01:26 +0300351#endif // MICROPY_PY_BUILTINS_STR_UNICODE