blob: d70b33f8feb1c6890a3475dd06967f8b362981fa [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
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:
109 return MP_OBJ_NEW_SMALL_INT(unichar_charlen((const char *)str_data, str_len));
110 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.
157STATIC const char *str_index_to_ptr(const char *self_data, uint self_len, mp_obj_t index, bool is_slice) {
158 machine_int_t i;
159 // Copied from mp_get_index; I don't want bounds checking, just give me
160 // the integer as-is. (I can't bounds-check without scanning the whole
161 // string; an out-of-bounds index will be caught in the loops below.)
162 if (MP_OBJ_IS_SMALL_INT(index)) {
163 i = MP_OBJ_SMALL_INT_VALUE(index);
164 } else if (!mp_obj_get_int_maybe(index, &i)) {
165 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, "string indices must be integers, not %s", mp_obj_get_type_str(index)));
166 }
167 const char *s, *top = self_data + self_len;
168 if (i < 0)
169 {
170 // Negative indexing is performed by counting from the end of the string.
171 for (s = top - 1; i; --s) {
172 if (s < self_data) {
173 if (is_slice) {
174 return self_data;
175 }
176 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_IndexError, "string index out of range"));
177 }
178 if (!UTF8_IS_CONT(*s)) {
179 ++i;
180 }
181 }
182 ++s;
183 } else if (!i) {
184 return self_data; // Shortcut - str[0] is its base pointer
185 } else {
186 // Positive indexing, correspondingly, counts from the start of the string.
187 // It's assumed that negative indexing will generally be used with small
188 // absolute values (eg str[-1], not str[-1000000]), which means it'll be
189 // more efficient this way.
190 for (s = self_data; true; ++s) {
191 if (s >= top) {
192 if (is_slice) {
193 return top;
194 }
195 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_IndexError, "string index out of range"));
196 }
197 while (UTF8_IS_CONT(*s)) {
198 ++s;
199 }
200 if (!i--) {
201 return s;
202 }
203 }
204 }
205 return s;
206}
207
Paul Sokolovsky83865342014-06-13 00:51:34 +0300208STATIC mp_obj_t str_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) {
209 mp_obj_type_t *type = mp_obj_get_type(self_in);
210 GET_STR_DATA_LEN(self_in, self_data, self_len);
211 if (value == MP_OBJ_SENTINEL) {
212 // load
213#if MICROPY_PY_BUILTINS_SLICE
214 if (MP_OBJ_IS_TYPE(index, &mp_type_slice)) {
Chris Angelico64b468d2014-06-04 05:28:12 +1000215 mp_obj_t ostart, ostop, ostep;
216 mp_obj_slice_get(index, &ostart, &ostop, &ostep);
217 if (ostep != mp_const_none && ostep != MP_OBJ_NEW_SMALL_INT(1)) {
Paul Sokolovsky83865342014-06-13 00:51:34 +0300218 nlr_raise(mp_obj_new_exception_msg(&mp_type_NotImplementedError,
219 "only slices with step=1 (aka None) are supported"));
220 }
Chris Angelico64b468d2014-06-04 05:28:12 +1000221
222 if (type == &mp_type_bytes) {
223 machine_int_t start = 0, stop = self_len;
224 if (ostart != mp_const_none) {
225 start = MP_OBJ_SMALL_INT_VALUE(ostart);
226 if (start < 0) {
227 start = self_len + start;
228 }
229 }
230 if (ostop != mp_const_none) {
231 stop = MP_OBJ_SMALL_INT_VALUE(ostop);
232 if (stop < 0) {
233 stop = self_len + stop;
234 }
235 }
236 return mp_obj_new_str_of_type(type, self_data + start, stop - start);
237 }
238 const char *pstart, *pstop;
239 if (ostart != mp_const_none) {
240 pstart = str_index_to_ptr((const char *)self_data, self_len, ostart, true);
241 } else {
242 pstart = (const char *)self_data;
243 }
244 if (ostop != mp_const_none) {
245 // pstop will point just after the stop character. This depends on
246 // the \0 at the end of the string.
247 pstop = str_index_to_ptr((const char *)self_data, self_len, ostop, true);
248 } else {
249 pstop = (const char *)self_data + self_len;
250 }
251 if (pstop < pstart) {
252 return MP_OBJ_NEW_QSTR(MP_QSTR_);
253 }
254 return mp_obj_new_str_of_type(type, (const byte *)pstart, pstop - pstart);
Paul Sokolovsky83865342014-06-13 00:51:34 +0300255 }
256#endif
Paul Sokolovsky83865342014-06-13 00:51:34 +0300257 if (type == &mp_type_bytes) {
Chris Angelico64b468d2014-06-04 05:28:12 +1000258 uint index_val = mp_get_index(type, self_len, index, false);
Paul Sokolovsky83865342014-06-13 00:51:34 +0300259 return MP_OBJ_NEW_SMALL_INT((mp_small_int_t)self_data[index_val]);
Paul Sokolovsky83865342014-06-13 00:51:34 +0300260 }
Chris Angelico64b468d2014-06-04 05:28:12 +1000261 const char *s = str_index_to_ptr((const char *)self_data, self_len, index, false);
262 int len = 1;
263 if (UTF8_IS_NONASCII(*s)) {
264 // Count the number of 1 bits (after the first)
265 for (char mask = 0x40; *s & mask; mask >>= 1) {
266 ++len;
267 }
268 }
269 return mp_obj_new_str(s, len, true); // This will create a one-character string
Paul Sokolovsky83865342014-06-13 00:51:34 +0300270 } else {
271 return MP_OBJ_NULL; // op not supported
272 }
273}
274
Paul Sokolovsky83865342014-06-13 00:51:34 +0300275STATIC const mp_map_elem_t str_locals_dict_table[] = {
276#if MICROPY_CPYTHON_COMPAT
Paul Sokolovsky83865342014-06-13 00:51:34 +0300277 { MP_OBJ_NEW_QSTR(MP_QSTR_encode), (mp_obj_t)&str_encode_obj },
278#endif
279 { MP_OBJ_NEW_QSTR(MP_QSTR_find), (mp_obj_t)&str_find_obj },
280 { MP_OBJ_NEW_QSTR(MP_QSTR_rfind), (mp_obj_t)&str_rfind_obj },
281 { MP_OBJ_NEW_QSTR(MP_QSTR_index), (mp_obj_t)&str_index_obj },
282 { MP_OBJ_NEW_QSTR(MP_QSTR_rindex), (mp_obj_t)&str_rindex_obj },
283 { MP_OBJ_NEW_QSTR(MP_QSTR_join), (mp_obj_t)&str_join_obj },
284 { MP_OBJ_NEW_QSTR(MP_QSTR_split), (mp_obj_t)&str_split_obj },
285 { MP_OBJ_NEW_QSTR(MP_QSTR_rsplit), (mp_obj_t)&str_rsplit_obj },
286 { MP_OBJ_NEW_QSTR(MP_QSTR_startswith), (mp_obj_t)&str_startswith_obj },
287 { MP_OBJ_NEW_QSTR(MP_QSTR_endswith), (mp_obj_t)&str_endswith_obj },
288 { MP_OBJ_NEW_QSTR(MP_QSTR_strip), (mp_obj_t)&str_strip_obj },
289 { MP_OBJ_NEW_QSTR(MP_QSTR_lstrip), (mp_obj_t)&str_lstrip_obj },
290 { MP_OBJ_NEW_QSTR(MP_QSTR_rstrip), (mp_obj_t)&str_rstrip_obj },
291 { MP_OBJ_NEW_QSTR(MP_QSTR_format), (mp_obj_t)&str_format_obj },
292 { MP_OBJ_NEW_QSTR(MP_QSTR_replace), (mp_obj_t)&str_replace_obj },
293 { MP_OBJ_NEW_QSTR(MP_QSTR_count), (mp_obj_t)&str_count_obj },
294 { MP_OBJ_NEW_QSTR(MP_QSTR_partition), (mp_obj_t)&str_partition_obj },
295 { MP_OBJ_NEW_QSTR(MP_QSTR_rpartition), (mp_obj_t)&str_rpartition_obj },
296 { MP_OBJ_NEW_QSTR(MP_QSTR_lower), (mp_obj_t)&str_lower_obj },
297 { MP_OBJ_NEW_QSTR(MP_QSTR_upper), (mp_obj_t)&str_upper_obj },
298 { MP_OBJ_NEW_QSTR(MP_QSTR_isspace), (mp_obj_t)&str_isspace_obj },
299 { MP_OBJ_NEW_QSTR(MP_QSTR_isalpha), (mp_obj_t)&str_isalpha_obj },
300 { MP_OBJ_NEW_QSTR(MP_QSTR_isdigit), (mp_obj_t)&str_isdigit_obj },
301 { MP_OBJ_NEW_QSTR(MP_QSTR_isupper), (mp_obj_t)&str_isupper_obj },
302 { MP_OBJ_NEW_QSTR(MP_QSTR_islower), (mp_obj_t)&str_islower_obj },
303};
304
305STATIC MP_DEFINE_CONST_DICT(str_locals_dict, str_locals_dict_table);
306
307const mp_obj_type_t mp_type_str = {
308 { &mp_type_type },
309 .name = MP_QSTR_str,
Paul Sokolovsky86d38982014-06-13 23:00:15 +0300310 .print = uni_print,
Paul Sokolovsky83865342014-06-13 00:51:34 +0300311 .make_new = str_make_new,
Paul Sokolovskye7f2b4c2014-06-13 23:37:18 +0300312 .unary_op = uni_unary_op,
Paul Sokolovsky83865342014-06-13 00:51:34 +0300313 .binary_op = str_binary_op,
314 .subscr = str_subscr,
315 .getiter = mp_obj_new_str_iterator,
Paul Sokolovskycdc020d2014-06-14 01:19:52 +0300316 .buffer_p = { .get_buffer = str_get_buffer },
Paul Sokolovsky83865342014-06-13 00:51:34 +0300317 .locals_dict = (mp_obj_t)&str_locals_dict,
318};
319
Paul Sokolovsky83865342014-06-13 00:51:34 +0300320/******************************************************************************/
321/* str iterator */
322
323typedef struct _mp_obj_str_it_t {
324 mp_obj_base_t base;
325 mp_obj_t str;
326 machine_uint_t cur;
327} mp_obj_str_it_t;
328
329STATIC mp_obj_t str_it_iternext(mp_obj_t self_in) {
330 mp_obj_str_it_t *self = self_in;
331 GET_STR_DATA_LEN(self->str, str, len);
332 if (self->cur < len) {
Paul Sokolovsky79b7fe22014-06-14 02:07:25 +0300333 const byte *cur = str + self->cur;
334 const byte *end = utf8_next_char(str + self->cur);
335 mp_obj_t o_out = mp_obj_new_str((const char*)cur, end - cur, true);
336 self->cur += end - cur;
Paul Sokolovsky83865342014-06-13 00:51:34 +0300337 return o_out;
338 } else {
339 return MP_OBJ_STOP_ITERATION;
340 }
341}
342
343STATIC const mp_obj_type_t mp_type_str_it = {
344 { &mp_type_type },
345 .name = MP_QSTR_iterator,
346 .getiter = mp_identity,
347 .iternext = str_it_iternext,
348};
349
Paul Sokolovsky83865342014-06-13 00:51:34 +0300350mp_obj_t mp_obj_new_str_iterator(mp_obj_t str) {
351 mp_obj_str_it_t *o = m_new_obj(mp_obj_str_it_t);
352 o->base.type = &mp_type_str_it;
353 o->str = str;
354 o->cur = 0;
355 return o;
356}
357
Paul Sokolovsky97319122014-06-13 22:01:26 +0300358#endif // MICROPY_PY_BUILTINS_STR_UNICODE