objstrunicode.c 11.5 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/*
 * This file is part of the Micro Python project, http://micropython.org/
 *
 * The MIT License (MIT)
 *
 * Copyright (c) 2013, 2014 Damien P. George
 * Copyright (c) 2014 Paul Sokolovsky
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#include <string.h>
#include <assert.h>

31
32
33
34
35
#include "py/nlr.h"
#include "py/objstr.h"
#include "py/objlist.h"
#include "py/runtime0.h"
#include "py/runtime.h"
36

37
#if MICROPY_PY_BUILTINS_STR_UNICODE
38
39
40
41
42
43

STATIC mp_obj_t mp_obj_new_str_iterator(mp_obj_t str);

/******************************************************************************/
/* str                                                                        */

44
STATIC void uni_print_quoted(const mp_print_t *print, const byte *str_data, uint str_len) {
45
46
47
48
49
50
51
52
53
54
    // this escapes characters, but it will be very slow to print (calling print many times)
    bool has_single_quote = false;
    bool has_double_quote = false;
    for (const byte *s = str_data, *top = str_data + str_len; !has_double_quote && s < top; s++) {
        if (*s == '\'') {
            has_single_quote = true;
        } else if (*s == '"') {
            has_double_quote = true;
        }
    }
55
    unichar quote_char = '\'';
56
57
58
    if (has_single_quote && !has_double_quote) {
        quote_char = '"';
    }
59
    mp_printf(print, "%c", quote_char);
60
    const byte *s = str_data, *top = str_data + str_len;
61
62
    while (s < top) {
        unichar ch;
63
64
        ch = utf8_get_char(s);
        s = utf8_next_char(s);
65
        if (ch == quote_char) {
66
            mp_printf(print, "\\%c", quote_char);
67
        } else if (ch == '\\') {
68
            mp_print_str(print, "\\\\");
69
        } else if (32 <= ch && ch <= 126) {
70
            mp_printf(print, "%c", ch);
71
        } else if (ch == '\n') {
72
            mp_print_str(print, "\\n");
73
        } else if (ch == '\r') {
74
            mp_print_str(print, "\\r");
75
        } else if (ch == '\t') {
76
            mp_print_str(print, "\\t");
77
        } else if (ch < 0x100) {
78
            mp_printf(print, "\\x%02x", ch);
79
        } else if (ch < 0x10000) {
80
            mp_printf(print, "\\u%04x", ch);
81
        } else {
82
            mp_printf(print, "\\U%08x", ch);
83
84
        }
    }
85
    mp_printf(print, "%c", quote_char);
86
87
}

88
STATIC void uni_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
89
    GET_STR_DATA_LEN(self_in, str_data, str_len);
90
91
    #if MICROPY_PY_UJSON
    if (kind == PRINT_JSON) {
92
        mp_str_print_json(print, str_data, str_len);
93
94
95
        return;
    }
    #endif
96
    if (kind == PRINT_STR) {
97
        mp_printf(print, "%.*s", str_len, str_data);
98
    } else {
99
        uni_print_quoted(print, str_data, str_len);
100
101
102
    }
}

103
STATIC mp_obj_t uni_unary_op(mp_uint_t op, mp_obj_t self_in) {
104
105
106
    GET_STR_DATA_LEN(self_in, str_data, str_len);
    switch (op) {
        case MP_UNARY_OP_BOOL:
107
            return mp_obj_new_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
111
112
113
114
        default:
            return MP_OBJ_NULL; // op not supported
    }
}

115
116
// Convert an index into a pointer to its lead byte. Out of bounds indexing will raise IndexError or
// be capped to the first/last character of the string, depending on is_slice.
117
const byte *str_index_to_ptr(const mp_obj_type_t *type, const byte *self_data, mp_uint_t self_len,
118
                             mp_obj_t index, bool is_slice) {
119
    (void)type;
120
    mp_int_t i;
121
122
123
124
125
126
127
128
    // Copied from mp_get_index; I don't want bounds checking, just give me
    // the integer as-is. (I can't bounds-check without scanning the whole
    // string; an out-of-bounds index will be caught in the loops below.)
    if (MP_OBJ_IS_SMALL_INT(index)) {
        i = MP_OBJ_SMALL_INT_VALUE(index);
    } else if (!mp_obj_get_int_maybe(index, &i)) {
        nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, "string indices must be integers, not %s", mp_obj_get_type_str(index)));
    }
129
    const byte *s, *top = self_data + self_len;
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
    if (i < 0)
    {
        // Negative indexing is performed by counting from the end of the string.
        for (s = top - 1; i; --s) {
            if (s < self_data) {
                if (is_slice) {
                    return self_data;
                }
                nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_IndexError, "string index out of range"));
            }
            if (!UTF8_IS_CONT(*s)) {
                ++i;
            }
        }
        ++s;
    } else if (!i) {
        return self_data; // Shortcut - str[0] is its base pointer
    } else {
        // Positive indexing, correspondingly, counts from the start of the string.
        // It's assumed that negative indexing will generally be used with small
        // absolute values (eg str[-1], not str[-1000000]), which means it'll be
        // more efficient this way.
        for (s = self_data; true; ++s) {
            if (s >= top) {
                if (is_slice) {
                    return top;
                }
                nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_IndexError, "string index out of range"));
            }
            while (UTF8_IS_CONT(*s)) {
                ++s;
            }
            if (!i--) {
                return s;
            }
        }
    }
    return s;
}

170
171
STATIC mp_obj_t str_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) {
    mp_obj_type_t *type = mp_obj_get_type(self_in);
172
    assert(type == &mp_type_str);
173
174
175
176
177
    GET_STR_DATA_LEN(self_in, self_data, self_len);
    if (value == MP_OBJ_SENTINEL) {
        // load
#if MICROPY_PY_BUILTINS_SLICE
        if (MP_OBJ_IS_TYPE(index, &mp_type_slice)) {
178
179
180
            mp_obj_t ostart, ostop, ostep;
            mp_obj_slice_get(index, &ostart, &ostop, &ostep);
            if (ostep != mp_const_none && ostep != MP_OBJ_NEW_SMALL_INT(1)) {
181
                mp_not_implemented("only slices with step=1 (aka None) are supported");
182
            }
183

184
            const byte *pstart, *pstop;
185
            if (ostart != mp_const_none) {
186
                pstart = str_index_to_ptr(type, self_data, self_len, ostart, true);
187
            } else {
188
                pstart = self_data;
189
190
191
192
            }
            if (ostop != mp_const_none) {
                // pstop will point just after the stop character. This depends on
                // the \0 at the end of the string.
193
                pstop = str_index_to_ptr(type, self_data, self_len, ostop, true);
194
            } else {
195
                pstop = self_data + self_len;
196
197
198
199
200
            }
            if (pstop < pstart) {
                return MP_OBJ_NEW_QSTR(MP_QSTR_);
            }
            return mp_obj_new_str_of_type(type, (const byte *)pstart, pstop - pstart);
201
202
        }
#endif
203
        const byte *s = str_index_to_ptr(type, self_data, self_len, index, false);
204
205
206
207
208
209
210
        int len = 1;
        if (UTF8_IS_NONASCII(*s)) {
            // Count the number of 1 bits (after the first)
            for (char mask = 0x40; *s & mask; mask >>= 1) {
                ++len;
            }
        }
211
        return mp_obj_new_str((const char*)s, len, true); // This will create a one-character string
212
213
214
215
216
    } else {
        return MP_OBJ_NULL; // op not supported
    }
}

217
STATIC const mp_map_elem_t struni_locals_dict_table[] = {
218
219
220
221
222
223
224
225
226
#if MICROPY_CPYTHON_COMPAT
    { MP_OBJ_NEW_QSTR(MP_QSTR_encode), (mp_obj_t)&str_encode_obj },
#endif
    { MP_OBJ_NEW_QSTR(MP_QSTR_find), (mp_obj_t)&str_find_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_rfind), (mp_obj_t)&str_rfind_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_index), (mp_obj_t)&str_index_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_rindex), (mp_obj_t)&str_rindex_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_join), (mp_obj_t)&str_join_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_split), (mp_obj_t)&str_split_obj },
227
228
229
    #if MICROPY_PY_BUILTINS_STR_SPLITLINES
    { MP_OBJ_NEW_QSTR(MP_QSTR_splitlines), (mp_obj_t)&str_splitlines_obj },
    #endif
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
    { MP_OBJ_NEW_QSTR(MP_QSTR_rsplit), (mp_obj_t)&str_rsplit_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_startswith), (mp_obj_t)&str_startswith_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_endswith), (mp_obj_t)&str_endswith_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_strip), (mp_obj_t)&str_strip_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_lstrip), (mp_obj_t)&str_lstrip_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_rstrip), (mp_obj_t)&str_rstrip_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_format), (mp_obj_t)&str_format_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_replace), (mp_obj_t)&str_replace_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_count), (mp_obj_t)&str_count_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_partition), (mp_obj_t)&str_partition_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_rpartition), (mp_obj_t)&str_rpartition_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_lower), (mp_obj_t)&str_lower_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_upper), (mp_obj_t)&str_upper_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_isspace), (mp_obj_t)&str_isspace_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_isalpha), (mp_obj_t)&str_isalpha_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_isdigit), (mp_obj_t)&str_isdigit_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_isupper), (mp_obj_t)&str_isupper_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_islower), (mp_obj_t)&str_islower_obj },
};
249

250
STATIC MP_DEFINE_CONST_DICT(struni_locals_dict, struni_locals_dict_table);
251

252
253
254
const mp_obj_type_t mp_type_str = {
    { &mp_type_type },
    .name = MP_QSTR_str,
255
    .print = uni_print,
256
    .make_new = mp_obj_str_make_new,
257
    .unary_op = uni_unary_op,
258
    .binary_op = mp_obj_str_binary_op,
259
260
    .subscr = str_subscr,
    .getiter = mp_obj_new_str_iterator,
261
    .buffer_p = { .get_buffer = mp_obj_str_get_buffer },
262
    .locals_dict = (mp_obj_t)&struni_locals_dict,
263
};
264

265
266
/******************************************************************************/
/* str iterator                                                               */
267

268
269
270
typedef struct _mp_obj_str_it_t {
    mp_obj_base_t base;
    mp_obj_t str;
271
    mp_uint_t cur;
272
} mp_obj_str_it_t;
273

274
275
276
277
STATIC mp_obj_t str_it_iternext(mp_obj_t self_in) {
    mp_obj_str_it_t *self = self_in;
    GET_STR_DATA_LEN(self->str, str, len);
    if (self->cur < len) {
278
279
280
281
        const byte *cur = str + self->cur;
        const byte *end = utf8_next_char(str + self->cur);
        mp_obj_t o_out = mp_obj_new_str((const char*)cur, end - cur, true);
        self->cur += end - cur;
282
        return o_out;
283
    } else {
284
        return MP_OBJ_STOP_ITERATION;
285
286
287
    }
}

288
289
290
291
292
293
STATIC const mp_obj_type_t mp_type_str_it = {
    { &mp_type_type },
    .name = MP_QSTR_iterator,
    .getiter = mp_identity,
    .iternext = str_it_iternext,
};
294

295
STATIC mp_obj_t mp_obj_new_str_iterator(mp_obj_t str) {
296
297
298
299
300
    mp_obj_str_it_t *o = m_new_obj(mp_obj_str_it_t);
    o->base.type = &mp_type_str_it;
    o->str = str;
    o->cur = 0;
    return o;
301
302
}

303
#endif // MICROPY_PY_BUILTINS_STR_UNICODE