Debian Codegraph @

pypy/objspace/std/unicodeobject.py

raw symbols SCIP
1 """The builtin str implementation"""
2
3 import sys
4
5 from rpython.rlib.objectmodel import (
6 compute_hash, compute_unique_id, import_from_mixin, always_inline,
7 enforceargs, newlist_hint, specialize, we_are_translated)
8 from rpython.rlib.nonconst import NonConstant
9 from rpython.rlib.rarithmetic import ovfcheck, r_uint, intmask
10 from rpython.rlib.rstring import (
11 StringBuilder, split, rsplit, replace_count, startswith, endswith)
12 from rpython.rlib import rutf8, runicode, jit
13
14 from pypy.interpreter import unicodehelper
15 from pypy.interpreter.baseobjspace import W_Root
16 from pypy.interpreter.error import OperationError, oefmt
17 from pypy.interpreter.gateway import WrappedDefault, interp2app, unwrap_spec
18 from pypy.interpreter.typedef import TypeDef
19 from pypy.module.unicodedata.interp_ucd import unicodedb
20 from pypy.objspace.std import newformat
21 from pypy.objspace.std.formatting import mod_format, FORMAT_UNICODE
22 from pypy.objspace.std.sliceobject import (W_SliceObject,
23 unwrap_start_stop, normalize_simple_slice)
24 from pypy.objspace.std.stringmethods import StringMethods
25 from pypy.objspace.std.util import IDTAG_SPECIAL, IDTAG_SHIFT, IDTAG_ALT_UID
26
27 __all__ = ['W_UnicodeObject', 'encode_object', 'decode_object',
28 'unicode_from_object', 'unicode_to_decimal_w']
29
30 MAX_UNROLL_NEXT_CODEPOINT_POS = 4
31
32 @jit.elidable
33 def next_codepoint_pos_dont_look_inside(utf8, p):
34 return rutf8.next_codepoint_pos(utf8, p)
35
36 @jit.elidable
37 def prev_codepoint_pos_dont_look_inside(utf8, p):
38 return rutf8.prev_codepoint_pos(utf8, p)
39
40 @jit.elidable
41 def codepoint_at_pos_dont_look_inside(utf8, p):
42 return rutf8.codepoint_at_pos(utf8, p)
43
44
45 def get_printable_location(selfisnotempty, tpfirst, greenkey):
46 return "unicode.join [selfisnotempty=%s, tpfirst=%s, %s]" % (
47 selfisnotempty, tpfirst, greenkey.iterator_greenkey_printable())
48 joindriver = jit.JitDriver(greens = ['selfisnotempty', 'tpfirst', 'greenkey'], reds = 'auto',
49 name='joindriver', get_printable_location=get_printable_location)
50
51 class BadUtf8(Exception):
52 pass
53 CHECK_ALL_STRINGS = False
54 # CHECK_ALL_STRINGS: after translation. Set to False to avoid overhead!
55
56
57 class W_UnicodeObject(W_Root):
58 import_from_mixin(StringMethods)
59 _immutable_fields_ = ['_utf8', '_length']
60
61 @enforceargs(utf8str=str)
62 def __init__(self, utf8str, length):
63 assert isinstance(utf8str, bytes)
64 # TODO: how to handle surrogates
65 assert length >= 0
66 self._utf8 = utf8str
67 self._length = length
68 self._index_storage = rutf8.null_storage()
69 if CHECK_ALL_STRINGS or not we_are_translated():
70 # utf8str must always be a valid utf8 string, except maybe with
71 # explicit surrogate characters---which .decode('utf-8') doesn't
72 # special-case in Python 2, which is exactly what we want here
73 try:
74 if sys.maxunicode == 0xffff:
75 # can't use .decode('utf-8') because it will add surrogates
76 real_length = rutf8.check_utf8(utf8str, True)
77 else:
78 real_length = len(utf8str.decode('utf-8'))
79 except (rutf8.CheckError, UnicodeDecodeError):
80 real_length = -999
81 if length != real_length:
82 from rpython.rlib.debug import debug_print
83 debug_print("!!! BAD UTF8 !!!")
84 debug_print(str([ord(c) for c in utf8str]))
85 debug_print("length", length, "real_length", real_length)
86 raise BadUtf8
87
88 @staticmethod
89 def from_utf8builder(builder):
90 return W_UnicodeObject(
91 builder.build(), builder.getlength())
92
93 def __repr__(self):
94 """representation for debugging purposes"""
95 return "%s(%r)" % (self.__class__.__name__, self._utf8)
96
97 def unwrap(self, space):
98 # for testing
99 return space.realunicode_w(self)
100
101 def is_w(self, space, w_other):
102 if not isinstance(w_other, W_UnicodeObject):
103 return False
104 if self is w_other:
105 return True
106 if self.user_overridden_class or w_other.user_overridden_class:
107 return False
108 s1 = space.utf8_w(self)
109 s2 = space.utf8_w(w_other)
110 if self._len() > 1:
111 return s1 is s2
112 else: # strings of len <= 1 are unique-ified
113 return s1 == s2
114
115 def immutable_unique_id(self, space):
116 if self.user_overridden_class:
117 return None
118 l = self._len()
119 if l > 1:
120 # return the uid plus 2, to make sure we don't get
121 # conflicts with W_BytesObject, whose id() might be
122 # identical
123 uid = compute_unique_id(self._utf8) + IDTAG_ALT_UID
124 else: # strings of len <= 1 are unique-ified
125 if l == 1:
126 base = rutf8.codepoint_at_pos(self._utf8, 0)
127 base = ~base # negative base values
128 else:
129 base = 257 # empty unicode string: base value 257
130 uid = (base << IDTAG_SHIFT) | IDTAG_SPECIAL
131 return space.newint(uid)
132
133 def text_w(self, space):
134 return self._utf8
135
136 def utf8_w(self, space):
137 jit.record_known_result(self._length, rutf8._check_utf8, self._utf8, True, 0, -1)
138 return self._utf8
139
140 def listview_ascii(self):
141 if self.is_ascii():
142 return self._listview_is_ascii(self._utf8)
143 # rpython note: can't use list() to return a list of strings
144 # (only a list of chars is supported)
145 return None
146
147 @staticmethod
148 def _listview_is_ascii(chars):
149 return [c for c in chars]
150
151 def descr_iter(self, space):
152 from pypy.objspace.std.iterobject import W_FastUnicodeIterObject
153 return W_FastUnicodeIterObject(self)
154
155 def ord(self, space):
156 if self._len() != 1:
157 raise oefmt(space.w_TypeError,
158 "ord() expected a character, but string of length %d "
159 "found", self._len())
160 return space.newint(self.codepoint_at_pos_dont_look_inside(0))
161
162 def _empty(self):
163 return W_UnicodeObject.EMPTY
164
165 def _len(self):
166 return self._length
167
168 @staticmethod
169 def _use_rstr_ops(space, w_other):
170 # Always return true because we always need to copy the other
171 # operand(s) before we can do comparisons
172 return True
173
174 @staticmethod
175 def convert_arg_to_w_unicode(space, w_other, strict=None):
176 if isinstance(w_other, W_UnicodeObject):
177 return w_other
178 if space.isinstance_w(w_other, space.w_bytes):
179 raise oefmt(space.w_TypeError,
180 "Can't convert '%T' object to str implicitly", w_other)
181 if strict:
182 raise oefmt(space.w_TypeError,
183 "%s arg must be None or str", strict)
184 return decode_object(space, w_other, 'utf8', "strict")
185
186 def convert_to_w_unicode(self, space):
187 return self
188
189 @specialize.argtype(1)
190 def _chr(self, char):
191 assert len(char) == 1
192 return unichr(ord(char[0]))
193
194 def _multi_chr(self, unichar):
195 return unichar
196
197 def _generic_name(self):
198 return "str"
199
200 def _isupper(self, ch):
201 return unicodedb.isupper(ch)
202
203 def _islower(self, ch):
204 return unicodedb.islower(ch)
205
206 def _isnumeric(self, ch):
207 return unicodedb.isnumeric(ch)
208
209 def _istitle(self, ch):
210 return unicodedb.isupper(ch) or unicodedb.istitle(ch)
211
212 @staticmethod
213 def _isspace(ch):
214 return unicodedb.isspace(ch)
215
216 def _isalpha(self, ch):
217 return unicodedb.isalpha(ch)
218
219 def _isalnum(self, ch):
220 return unicodedb.isalnum(ch)
221
222 def _isdigit(self, ch):
223 return unicodedb.isdigit(ch)
224
225 def _isdecimal(self, ch):
226 return unicodedb.isdecimal(ch)
227
228 def _iscased(self, ch):
229 return unicodedb.iscased(ch)
230
231 def _islinebreak(self, ch):
232 return unicodedb.islinebreak(ch)
233
234 @staticmethod
235 def descr_new(space, w_unicodetype, w_object=None, w_encoding=None,
236 w_errors=None):
237 if w_object is None:
238 w_value = W_UnicodeObject.EMPTY
239 else:
240 encoding, errors = get_encoding_and_errors(space,
241 w_encoding, w_errors)
242 if encoding is None and errors is None:
243 # this is very quick if w_object is already a w_unicode
244 w_value = unicode_from_object(space, w_object)
245 else:
246 if space.isinstance_w(w_object, space.w_unicode):
247 raise oefmt(space.w_TypeError,
248 "decoding str is not supported")
249 w_value = decode_object(space, w_object, encoding, errors)
250 if space.is_w(w_unicodetype, space.w_unicode):
251 return w_value
252
253 assert isinstance(w_value, W_UnicodeObject)
254 w_newobj = space.allocate_instance(W_UnicodeObject, w_unicodetype)
255 W_UnicodeObject.__init__(w_newobj, w_value._utf8, w_value._length)
256 if w_value._index_storage:
257 # copy the storage if it's there
258 w_newobj._index_storage = w_value._index_storage
259 return w_newobj
260
261 @staticmethod
262 def descr_maketrans(space, w_type, w_x, w_y=None, w_z=None):
263 y = None if space.is_none(w_y) else space.utf8_w(w_y)
264 z = None if space.is_none(w_z) else space.utf8_w(w_z)
265 w_new = space.newdict()
266
267 if y is not None:
268 # x must be a string too, of equal length
269 try:
270 x = space.utf8_w(w_x)
271 except OperationError as e:
272 if not e.match(space, space.w_TypeError):
273 raise
274 raise oefmt(space.w_TypeError,
275 "first maketrans argument must be a string if "
276 "there is a second argument")
277 if space.len_w(w_x) != space.len_w(w_y):
278 raise oefmt(space.w_ValueError,
279 "the first two maketrans arguments must have "
280 "equal length")
281 # create entries for translating chars in x to those in y
282 iter2 = rutf8.Utf8StringIterator(y)
283 for xch in rutf8.Utf8StringIterator(x):
284 ych = iter2.next()
285 w_key = space.newint(xch)
286 w_value = space.newint(ych)
287 space.setitem(w_new, w_key, w_value)
288 # create entries for deleting chars in z
289 if z is not None:
290 for zch in rutf8.Utf8StringIterator(z):
291 w_key = space.newint(zch)
292 space.setitem(w_new, w_key, space.w_None)
293 else:
294 # x must be a dict
295 if not space.is_w(space.type(w_x), space.w_dict):
296 raise oefmt(space.w_TypeError,
297 "if you give only one argument to maketrans it "
298 "must be a dict")
299 # copy entries into the new dict, converting string keys to int keys
300 w_iter = space.iter(space.call_method(w_x, "items"))
301 while True:
302 try:
303 w_item = space.next(w_iter)
304 except OperationError as e:
305 if not e.match(space, space.w_StopIteration):
306 raise
307 break
308 w_key, w_value = space.unpackiterable(w_item, 2)
309 if space.isinstance_w(w_key, space.w_unicode):
310 # convert string keys to integer keys
311 if space.len_w(w_key) != 1:
312 raise oefmt(space.w_ValueError,
313 "string keys in translate table must be "
314 "of length 1")
315 val = space.utf8_w(w_key)
316 w_key = space.newint(rutf8.codepoint_at_pos(val, 0))
317 else:
318 # just keep integer keys
319 try:
320 space.int_w(w_key)
321 except OperationError as e:
322 if not e.match(space, space.w_TypeError):
323 raise
324 raise oefmt(space.w_TypeError,
325 "keys in translate table must be strings "
326 "or integers")
327 space.setitem(w_new, w_key, w_value)
328 return w_new
329
330 def descr_repr(self, space):
331 return space.newtext(_repr_function(self._utf8)) # quotes=True
332
333 def descr_str(self, space):
334 if space.is_w(space.type(self), space.w_unicode):
335 return self
336 # Subtype -- return genuine unicode string with the same value.
337 return space.newtext(space.utf8_w(self), space.len_w(self))
338
339 def hash_w(self):
340 # shortcut for UnicodeDictStrategy
341 x = compute_hash(self._utf8)
342 x -= (x == -1) # convert -1 to -2 without creating a bridge
343 return x
344
345 def descr_hash(self, space):
346 return space.newint(self.hash_w())
347
348 def eq_w(self, w_other):
349 # shortcut for UnicodeDictStrategy
350 assert isinstance(w_other, W_UnicodeObject)
351 return self._utf8 == w_other._utf8
352
353 def eq_unwrapped(self, other):
354 # for argument.py
355 return self._utf8 == other
356
357 def descr_eq(self, space, w_other):
358 try:
359 res = self._utf8 == self.convert_arg_to_w_unicode(space, w_other,
360 strict='__eq__')._utf8
361 except OperationError as e:
362 if e.match(space, space.w_TypeError):
363 return space.w_NotImplemented
364 raise
365 return space.newbool(res)
366
367 def descr_ne(self, space, w_other):
368 try:
369 res = self._utf8 != self.convert_arg_to_w_unicode(space, w_other,
370 strict='__neq__')._utf8
371 except OperationError as e:
372 if e.match(space, space.w_TypeError):
373 return space.w_NotImplemented
374 raise
375 return space.newbool(res)
376
377 def descr_lt(self, space, w_other):
378 try:
379 res = self._utf8 < self.convert_arg_to_w_unicode(space, w_other,
380 strict='__lt__')._utf8
381 except OperationError as e:
382 if e.match(space, space.w_TypeError):
383 return space.w_NotImplemented
384 raise
385 return space.newbool(res)
386
387 def descr_le(self, space, w_other):
388 try:
389 res = self._utf8 <= self.convert_arg_to_w_unicode(space, w_other,
390 strict='__le__')._utf8
391 except OperationError as e:
392 if e.match(space, space.w_TypeError):
393 return space.w_NotImplemented
394 raise
395 return space.newbool(res)
396
397 def descr_gt(self, space, w_other):
398 try:
399 res = self._utf8 > self.convert_arg_to_w_unicode(space, w_other,
400 strict='__gt__')._utf8
401 except OperationError as e:
402 if e.match(space, space.w_TypeError):
403 return space.w_NotImplemented
404 raise
405 return space.newbool(res)
406
407 def descr_ge(self, space, w_other):
408 try:
409 res = self._utf8 >= self.convert_arg_to_w_unicode(space, w_other,
410 strict='__ge__')._utf8
411 except OperationError as e:
412 if e.match(space, space.w_TypeError):
413 return space.w_NotImplemented
414 raise
415 return space.newbool(res)
416
417 def _parse_format_arg(self, space, w_kwds, __args__):
418 for i in range(len(__args__.keyword_names_w)):
419 w_arg = __args__.keyword_names_w[i]
420 space.setitem(w_kwds, w_arg, __args__.keywords_w[i])
421
422 def descr_format(self, space, __args__):
423 w_kwds = space.newdict()
424 if __args__.keyword_names_w:
425 self._parse_format_arg(space, w_kwds, __args__)
426 return newformat.format_method(space, self, __args__.arguments_w,
427 w_kwds, True)
428
429 def descr_format_map(self, space, w_mapping):
430 return newformat.format_method(space, self, None, w_mapping, True)
431
432 def descr__format__(self, space, w_format_spec):
433 return newformat.run_formatter(space, w_format_spec, "format_string",
434 self)
435
436 def descr_mod(self, space, w_values):
437 return mod_format(space, self, w_values, fmt_type=FORMAT_UNICODE)
438
439 def descr_rmod(self, space, w_values):
440 # this should never be reachable for valid invocations
441 if not space.isinstance_w(w_values, space.w_unicode):
442 return space.w_NotImplemented
443 return mod_format(space, w_values, self, fmt_type=FORMAT_UNICODE)
444
445 def descr_swapcase(self, space):
446 return W_UnicodeObject._swapcase_unicode(self._utf8)
447
448 @staticmethod
449 @jit.elidable
450 def _swapcase_unicode(value):
451 if len(value) == 0:
452 return W_UnicodeObject.EMPTY
453 builder = rutf8.Utf8StringBuilder(len(value))
454 for ch, pos in rutf8.Utf8StringPosIterator(value):
455 if unicodedb.isupper(ch):
456 codes = W_UnicodeObject._lower_char(ch, value, pos)
457 elif unicodedb.islower(ch):
458 codes = unicodedb.toupper_full(ch)
459 else:
460 codes = [ch,]
461 for c in codes:
462 builder.append_code(c)
463 return W_UnicodeObject.from_utf8builder(builder)
464
465 def descr_title(self, space):
466 return W_UnicodeObject._title_unicode(self._utf8)
467
468 @staticmethod
469 @jit.elidable
470 def _title_unicode(value):
471 if len(value) == 0:
472 return W_UnicodeObject.EMPTY
473 builder = rutf8.Utf8StringBuilder(len(value))
474 previous_is_cased = False
475 for ch, pos in rutf8.Utf8StringPosIterator(value):
476 if previous_is_cased:
477 codes = W_UnicodeObject._lower_char(ch, value, pos)
478 else:
479 codes = unicodedb.totitle_full(ch)
480 for c in codes:
481 builder.append_code(c)
482 previous_is_cased = unicodedb.iscased(ch)
483 return W_UnicodeObject.from_utf8builder(builder)
484
485 @staticmethod
486 def _lower_char(ch, value, bytepos):
487 if ch == 0x3a3:
488 return [W_UnicodeObject._handle_capital_sigma(value, bytepos), ]
489 else:
490 return unicodedb.tolower_full(ch)
491
492 @staticmethod
493 def _handle_capital_sigma(value, bytepos):
494 # U+03A3 is in the Final_Sigma context when, it is found like this:
495 #\p{cased} \p{case-ignorable}* U+03A3 not(\p{case-ignorable}* \p{cased})
496 # where \p{xxx} is a character with property xxx.
497
498 final_sigma = False
499 if bytepos > 0:
500 j = rutf8.prev_codepoint_pos(value, bytepos)
501 while j >= 0:
502 ch = rutf8.codepoint_at_pos(value, j)
503 if unicodedb.iscaseignorable(ch):
504 if j == 0:
505 break
506 j = rutf8.prev_codepoint_pos(value, j)
507 continue
508 final_sigma = unicodedb.iscased(ch)
509 break
510 if final_sigma and bytepos < len(value):
511 j = rutf8.next_codepoint_pos(value, bytepos)
512 length = len(value)
513 while j < length:
514 ch = rutf8.codepoint_at_pos(value, j)
515 if unicodedb.iscaseignorable(ch):
516 j = rutf8.next_codepoint_pos(value, j)
517 continue
518 final_sigma = not unicodedb.iscased(ch)
519 break
520 if final_sigma:
521 return 0x3C2
522 else:
523 return 0x3C3
524
525 def descr_translate(self, space, w_table):
526 builder = rutf8.Utf8StringBuilder(len(self._utf8))
527 for codepoint in rutf8.Utf8StringIterator(self._utf8):
528 try:
529 w_newval = space.getitem(w_table, space.newint(codepoint))
530 except OperationError as e:
531 if not e.match(space, space.w_LookupError):
532 raise
533 else:
534 if space.is_w(w_newval, space.w_None):
535 continue
536 elif space.isinstance_w(w_newval, space.w_int):
537 codepoint = space.int_w(w_newval)
538 elif isinstance(w_newval, W_UnicodeObject):
539 builder.append_utf8(w_newval._utf8, w_newval._length)
540 continue
541 else:
542 raise oefmt(space.w_TypeError,
543 "character mapping must return integer, None "
544 "or str")
545 try:
546 builder.append_code(codepoint)
547 except rutf8.OutOfRange:
548 raise oefmt(space.w_ValueError,
549 "character mapping must be in range(0x110000)")
550 return self.from_utf8builder(builder)
551
552 def descr_find(self, space, w_sub, w_start=None, w_end=None):
553 w_result = self._unwrap_and_search(space, w_sub, w_start, w_end)
554 if w_result is None:
555 w_result = space.newint(-1)
556 return w_result
557
558 def descr_rfind(self, space, w_sub, w_start=None, w_end=None):
559 w_result = self._unwrap_and_search(space, w_sub, w_start, w_end,
560 forward=False)
561 if w_result is None:
562 w_result = space.newint(-1)
563 return w_result
564
565 def descr_index(self, space, w_sub, w_start=None, w_end=None):
566 w_result = self._unwrap_and_search(space, w_sub, w_start, w_end)
567 if w_result is None:
568 raise oefmt(space.w_ValueError,
569 "substring not found in string.index")
570 return w_result
571
572 def descr_rindex(self, space, w_sub, w_start=None, w_end=None):
573 w_result = self._unwrap_and_search(space, w_sub, w_start, w_end,
574 forward=False)
575 if w_result is None:
576 raise oefmt(space.w_ValueError,
577 "substring not found in string.rindex")
578 return w_result
579
580 @specialize.arg(2)
581 def _is_generic(self, space, func_name):
582 func = getattr(self, func_name)
583 if self._length == 0:
584 return space.w_False
585 if self._length == 1:
586 return space.newbool(func(self.codepoint_at_pos_dont_look_inside(0)))
587 else:
588 return self._is_generic_loop(space, self._utf8, func_name)
589
590 @specialize.arg(3)
591 def _is_generic_loop(self, space, v, func_name):
592 func = getattr(self, func_name)
593 val = self._utf8
594 for uchar in rutf8.Utf8StringIterator(val):
595 if not func(uchar):
596 return space.w_False
597 return space.w_True
598
599 def descr_encode(self, space, w_encoding=None, w_errors=None):
600 encoding, errors = get_encoding_and_errors(space, w_encoding, w_errors)
601 return encode_object(space, self, encoding, errors)
602
603 @unwrap_spec(tabsize=int)
604 def descr_expandtabs(self, space, tabsize=8):
605 value = self._utf8
606 if not value:
607 return self._empty()
608 if tabsize == 0:
609 res, replacements = replace_count(value, '\t', '')
610 if not replacements and type(self) is W_UnicodeObject:
611 return self
612 newlength = self._length - replacements
613 assert res is not None
614 return W_UnicodeObject(res, newlength)
615
616 splitted = value.split('\t')
617
618 try:
619 ovfcheck(len(splitted) * tabsize)
620 except OverflowError:
621 raise oefmt(space.w_OverflowError, "new string is too long")
622 newlen = self._len() - len(splitted) + 1
623 builder = StringBuilder(len(value))
624 oldtoken = splitted[0]
625 builder.append(oldtoken)
626
627 for index in range(1, len(splitted)):
628 token = splitted[index]
629 dist = self._tabindent(oldtoken, tabsize)
630 builder.append_multiple_char(' ', dist)
631 builder.append(token)
632 newlen += dist
633 oldtoken = token
634
635 return W_UnicodeObject(builder.build(), newlen)
636
637 def _tabindent(self, token, tabsize):
638 if tabsize <= 0:
639 return 0
640 distance = tabsize
641 if token:
642 distance = 0
643 offset = len(token)
644
645 while 1:
646 if token[offset-1] == "\n" or token[offset-1] == "\r":
647 break
648 distance += 1
649 offset = rutf8.prev_codepoint_pos(token, offset)
650 if offset == 0:
651 break
652
653 # the same like distance = len(token) - (offset + 1)
654 distance = (tabsize - distance) % tabsize
655 if distance == 0:
656 distance = tabsize
657
658 return distance
659
660 def _join_utf8_len_w(self, space, w_element, i):
661 try:
662 return space.utf8_len_w(w_element)
663 except OperationError as e:
664 if not e.match(space, space.w_TypeError):
665 raise
666 raise oefmt(space.w_TypeError,
667 "sequence item %d: expected %s, %T found",
668 i, self._generic_name(), w_element)
669
670 def _join_ascii(self, space, l):
671 if len(l) == 1:
672 return space.newutf8(l[0], len(l[0]))
673 s = self._utf8.join(l)
674 if self.is_ascii():
675 resultlen = len(s)
676 else:
677 # carefully compute the result length
678 resultlen = len(s) - (len(self._utf8) - self._length) * (len(l) - 1)
679 return space.newutf8(s, resultlen)
680
681 def _join_from_list(self, space, w_list):
682 list_w = space.listview(w_list)
683 if len(list_w) == 0:
684 return self.EMPTY
685 if len(list_w) == 1:
686 w_s = list_w[0]
687 # only one item, return it if it's not a subclass of str
688 if self._join_return_one(space, w_s):
689 return w_s
690 # the stringmethods implementation makes a copy of the list to
691 # pre-compute the correct size for preallocation. that sounds like the
692 # wrong tradeoff somehow...
693 builder = None
694 # use first element to guess preallocation size
695 w_first = list_w[0]
696 utf8first, lenfirst = self._join_utf8_len_w(space, w_first, 0)
697 prealloc = len(self._utf8) * (len(list_w) - 1) + len(utf8first) * len(list_w)
698 builder = rutf8.Utf8StringBuilder(prealloc)
699 builder.append_utf8(utf8first, lenfirst)
700 for i in range(1, len(list_w)):
701 w_element = list_w[i]
702 utf8, l = self._join_utf8_len_w(space, w_element, i)
703 if self._length:
704 builder.append_utf8(self._utf8, self._length)
705 builder.append_utf8(utf8, l)
706 return self.from_utf8builder(builder)
707
708 def _join_from_iterable(self, space, w_iterable):
709 sizehint = space.length_hint(w_iterable, -1)
710
711 # get the first element to guess the preallocation size
712 w_iter = space.iter(w_iterable)
713 try:
714 w_first = space.next(w_iter)
715 except OperationError as e:
716 if not e.match(space, space.w_StopIteration):
717 raise
718 return W_UnicodeObject.EMPTY
719
720 utf8first, lenfirst = self._join_utf8_len_w(space, w_first, 0)
721 if sizehint >= 0:
722 prealloc = len(self._utf8) * (sizehint - 1) + len(utf8first) * sizehint
723 else:
724 prealloc = len(self._utf8) + len(utf8first)
725
726 # build the result
727 builder = rutf8.Utf8StringBuilder(prealloc)
728 builder.append_utf8(utf8first, lenfirst)
729 size = 1
730 selfisnotempty = self._length != 0
731 tpfirst = space.type(w_first)
732 greenkey = space.iterator_greenkey(w_iter)
733 while 1:
734 joindriver.jit_merge_point(tpfirst=tpfirst, greenkey=greenkey, selfisnotempty=selfisnotempty)
735 try:
736 w_element = space.next(w_iter)
737 except OperationError as e:
738 if not e.match(space, space.w_StopIteration):
739 raise
740 break
741 if selfisnotempty:
742 builder.append_utf8(self._utf8, self._length)
743 utf8, l = self._join_utf8_len_w(space, w_element, size)
744 builder.append_utf8(utf8, l)
745 size += 1
746 if size == 1 and self._join_return_one(space, w_first):
747 return w_first
748 return W_UnicodeObject.from_utf8builder(builder)
749
750 def descr_join(self, space, w_iterable):
751 from pypy.objspace.std.listobject import W_ListObject
752 # somewhat overengineered, but it's quite common
753
754 # first, a shortcut for when w_iterable is ascii-only
755 l = space.listview_ascii(w_iterable)
756 if l is not None:
757 return self._join_ascii(space, l)
758
759 if type(w_iterable) is W_ListObject or (isinstance(w_iterable, W_ListObject) and
760 space._uses_list_iter(w_iterable)):
761 self._join_from_list(space, w_iterable)
762 return self._join_from_iterable(space, w_iterable)
763
764 def _join_return_one(self, space, w_obj):
765 return space.is_w(space.type(w_obj), space.w_unicode)
766
767 def descr_casefold(self, space):
768 return W_UnicodeObject._casefold_unicode(self._utf8)
769
770 @staticmethod
771 @jit.elidable
772 def _casefold_unicode(value):
773 if len(value) == 0:
774 return W_UnicodeObject.EMPTY
775 builder = rutf8.Utf8StringBuilder(len(value))
776 for ch in rutf8.Utf8StringIterator(value):
777 folded = unicodedb.casefold_lookup(ch)
778 if folded is None:
779 builder.append_code(unicodedb.tolower(ch))
780 else:
781 for r in folded:
782 builder.append_code(r)
783 return W_UnicodeObject.from_utf8builder(builder)
784
785 def descr_lower(self, space):
786 if self.is_ascii():
787 return space.newutf8(self._utf8.lower(), len(self._utf8))
788 return W_UnicodeObject._lower_unicode(self._utf8)
789
790 @staticmethod
791 @jit.elidable
792 def _lower_unicode(value):
793 if len(value) == 0:
794 return W_UnicodeObject.EMPTY
795 builder = rutf8.Utf8StringBuilder(len(value))
796 for ch, pos in rutf8.Utf8StringPosIterator(value):
797 codes = W_UnicodeObject._lower_char(ch, value, pos)
798 for c in codes:
799 builder.append_code(c)
800 return W_UnicodeObject.from_utf8builder(builder)
801
802 def descr_isdecimal(self, space):
803 return self._is_generic(space, '_isdecimal')
804
805 def descr_isnumeric(self, space):
806 return self._is_generic(space, '_isnumeric')
807
808 def descr_islower(self, space):
809 cased = False
810 for uchar in rutf8.Utf8StringIterator(self._utf8):
811 if (unicodedb.isupper(uchar) or
812 unicodedb.istitle(uchar)):
813 return space.w_False
814 if not cased and unicodedb.islower(uchar):
815 cased = True
816 return space.newbool(cased)
817
818 def descr_istitle(self, space):
819 cased = False
820 previous_is_cased = False
821 for uchar in rutf8.Utf8StringIterator(self._utf8):
822 if unicodedb.isupper(uchar) or unicodedb.istitle(uchar):
823 if previous_is_cased:
824 return space.w_False
825 previous_is_cased = True
826 cased = True
827 elif unicodedb.islower(uchar):
828 if not previous_is_cased:
829 return space.w_False
830 cased = True
831 else:
832 previous_is_cased = False
833 return space.newbool(cased)
834
835 def descr_isupper(self, space):
836 cased = False
837 for uchar in rutf8.Utf8StringIterator(self._utf8):
838 if (unicodedb.islower(uchar) or
839 unicodedb.istitle(uchar)):
840 return space.w_False
841 if not cased and unicodedb.isupper(uchar):
842 cased = True
843 return space.newbool(cased)
844
845 def descr_isidentifier(self, space):
846 return space.newbool(_isidentifier(self._utf8))
847
848 def descr_startswith(self, space, w_prefix, w_start=None, w_end=None):
849 start, end = self._unwrap_and_compute_idx_params(space, w_start, w_end)
850 value = self._utf8
851 if space.isinstance_w(w_prefix, space.w_tuple):
852 return self._startswith_tuple(space, value, w_prefix, start, end)
853 try:
854 return space.newbool(self._startswith(space, value, w_prefix, start,
855 end))
856 except OperationError as e:
857 if e.match(space, space.w_TypeError):
858 raise oefmt(space.w_TypeError, 'startswith first arg must be str '
859 'or a tuple of str, not %T', w_prefix)
860
861 def _startswith(self, space, value, w_prefix, start, end):
862 prefix = self.convert_arg_to_w_unicode(space, w_prefix)._utf8
863 if start > end:
864 return False
865 if len(prefix) == 0:
866 return True
867 return startswith(value, prefix, start, end)
868
869 def descr_endswith(self, space, w_suffix, w_start=None, w_end=None):
870 start, end = self._unwrap_and_compute_idx_params(space, w_start, w_end)
871 value = self._utf8
872 if space.isinstance_w(w_suffix, space.w_tuple):
873 return self._endswith_tuple(space, value, w_suffix, start, end)
874 try:
875 return space.newbool(self._endswith(space, value, w_suffix, start,
876 end))
877 except OperationError as e:
878 if e.match(space, space.w_TypeError):
879 raise oefmt(space.w_TypeError, 'endswith first arg must be str '
880 'or a tuple of str, not %T', w_suffix)
881
882 def _endswith(self, space, value, w_prefix, start, end):
883 prefix = self.convert_arg_to_w_unicode(space, w_prefix)._utf8
884 if start > end:
885 return False
886 if len(prefix) == 0:
887 return True
888 return endswith(value, prefix, start, end)
889
890 def descr_add(self, space, w_other):
891 try:
892 w_other = self.convert_arg_to_w_unicode(space, w_other, strict='__add__')
893 except OperationError as e:
894 if e.match(space, space.w_TypeError):
895 return space.w_NotImplemented
896 raise
897 return W_UnicodeObject(self._utf8 + w_other._utf8,
898 self._len() + w_other._len())
899
900 @jit.look_inside_iff(lambda self, space, list_w, size:
901 jit.loop_unrolling_heuristic(list_w, size))
902 def _str_join_many_items(self, space, list_w, size):
903 value = self._utf8
904 lgt = self._len() * (size - 1)
905
906 prealloc_size = len(value) * (size - 1)
907 unwrapped = newlist_hint(size)
908 for i in range(size):
909 w_s = list_w[i]
910 if not (space.isinstance_w(w_s, space.w_bytes) or
911 space.isinstance_w(w_s, space.w_unicode)):
912 raise oefmt(space.w_TypeError,
913 "sequence item %d: expected string or unicode, %T found",
914 i, w_s)
915 # XXX Maybe the extra copy here is okay? It was basically going to
916 # happen anyway, what with being placed into the builder
917 w_u = self.convert_arg_to_w_unicode(space, w_s)
918 unwrapped.append(w_u._utf8)
919 lgt += w_u._length
920 prealloc_size += len(unwrapped[i])
921
922 sb = StringBuilder(prealloc_size)
923 for i in range(size):
924 if value and i != 0:
925 sb.append(value)
926 sb.append(unwrapped[i])
927 return W_UnicodeObject(sb.build(), lgt)
928
929 @unwrap_spec(keepends=bool)
930 def descr_splitlines(self, space, keepends=False):
931 value = self._utf8
932 strs_w = unicode_splitlines(value, keepends)
933 return space.newlist(strs_w)
934
935 def descr_upper(self, space):
936 if self.is_ascii():
937 return space.newutf8(self._utf8.upper(), len(self._utf8))
938 return W_UnicodeObject._upper_unicode(self._utf8)
939
940 @staticmethod
941 @jit.elidable
942 def _upper_unicode(value):
943 if len(value) == 0:
944 return W_UnicodeObject.EMPTY
945 builder = rutf8.Utf8StringBuilder(len(value))
946 for ch in rutf8.Utf8StringIterator(value):
947 codes = unicodedb.toupper_full(ch)
948 for c in codes:
949 builder.append_code(c)
950 return W_UnicodeObject.from_utf8builder(builder)
951
952 @unwrap_spec(width=int)
953 def descr_zfill(self, space, width):
954 selfval = self._utf8
955 if len(selfval) == 0:
956 return W_UnicodeObject('0' * width, width)
957 num_zeros = width - self._len()
958 if num_zeros <= 0:
959 # cannot return self, in case it is a subclass of str
960 return W_UnicodeObject(selfval, self._len())
961 builder = StringBuilder(num_zeros + len(selfval))
962 if len(selfval) > 0 and (selfval[0] == '+' or selfval[0] == '-'):
963 # copy sign to first position
964 builder.append(selfval[0])
965 start = 1
966 else:
967 start = 0
968 builder.append_multiple_char('0', num_zeros)
969 builder.append_slice(selfval, start, len(selfval))
970 return W_UnicodeObject(builder.build(), width)
971
972 @unwrap_spec(maxsplit=int)
973 def descr_split(self, space, w_sep=None, maxsplit=-1):
974 res = []
975 value = self._utf8
976 is_ascii = self.is_ascii()
977 if space.is_none(w_sep):
978 # need two calls, due to the specialization
979 if is_ascii:
980 res = split(value, maxsplit=maxsplit, isutf8=False)
981 else:
982 return space.newlist(unicode_split_none_wrapped(space, value, self._len(), maxsplit=maxsplit))
983 return space.newlist_utf8(res, is_ascii)
984
985 by = self.convert_arg_to_w_unicode(space, w_sep)._utf8
986 if len(by) == 0:
987 raise oefmt(space.w_ValueError, "empty separator")
988 res = split(value, by, maxsplit, isutf8=True)
989
990 return space.newlist_utf8(res, self.is_ascii())
991
992 @unwrap_spec(maxsplit=int)
993 def descr_rsplit(self, space, w_sep=None, maxsplit=-1):
994 res = []
995 value = self._utf8
996 is_ascii = self.is_ascii()
997 if space.is_none(w_sep):
998 if is_ascii:
999 res = rsplit(value, maxsplit=maxsplit, isutf8=False)
1000 else:
1001 res = unicode_rsplit_none(value, maxsplit=maxsplit)
1002 return space.newlist_utf8(res, self.is_ascii())
1003
1004 by = self.convert_arg_to_w_unicode(space, w_sep)._utf8
1005 if len(by) == 0:
1006 raise oefmt(space.w_ValueError, "empty separator")
1007 res = rsplit(value, by, maxsplit, isutf8=True)
1008
1009 return space.newlist_utf8(res, self.is_ascii())
1010
1011 def descr_getitem(self, space, w_index):
1012 if isinstance(w_index, W_SliceObject):
1013 length = self._len()
1014 start, stop, step, sl = w_index.indices4(space, length)
1015 if sl == 0:
1016 return self._empty()
1017 elif step == 1:
1018 if jit.we_are_jitted() and \
1019 self._unroll_slice_heuristic(start, stop, w_index.w_stop):
1020 return self._unicode_sliced_constant_index_jit(space, start, stop)
1021 assert start >= 0 and stop >= 0
1022 return self._unicode_sliced(space, start, stop)
1023 else:
1024 return self._getitem_slice_slowpath(space, start, step, sl)
1025
1026 index = space.getindex_w(w_index, space.w_IndexError, "string")
1027 return self._getitem_result(space, index)
1028
1029 def _getitem_slice_slowpath(self, space, start, step, sl):
1030 # XXX same comment as in _unicode_sliced
1031 builder = StringBuilder(step * sl)
1032 byte_pos = self._index_to_byte(start)
1033 i = 0
1034 while True:
1035 next_pos = rutf8.next_codepoint_pos(self._utf8, byte_pos)
1036 builder.append_slice(self._utf8, byte_pos, next_pos)
1037 if i == sl - 1:
1038 break
1039 i += 1
1040 byte_pos = self._index_to_byte(start + i * step)
1041 return W_UnicodeObject(builder.build(), sl)
1042
1043 def _unicode_sliced(self, space, start, stop):
1044 # XXX maybe some heuristic, like first slice does not create
1045 # full index, but second does?
1046 assert start >= 0
1047 assert stop >= 0
1048 byte_start = self._index_to_byte(start)
1049 byte_stop = self._index_to_byte(stop)
1050 return W_UnicodeObject(self._utf8[byte_start:byte_stop], stop - start)
1051
1052 @jit.unroll_safe
1053 def _unicode_sliced_constant_index_jit(self, space, start, stop):
1054 assert start >= 0
1055 assert stop >= 0
1056 byte_start = 0
1057 for i in range(start):
1058 byte_start = next_codepoint_pos_dont_look_inside(self._utf8, byte_start)
1059 byte_stop = len(self._utf8)
1060 for i in range(self._len() - stop):
1061 byte_stop = prev_codepoint_pos_dont_look_inside(self._utf8, byte_stop)
1062 return W_UnicodeObject(self._utf8[byte_start:byte_stop], stop - start)
1063
1064 def _unroll_slice_heuristic(self, start, stop, w_stop):
1065 from pypy.objspace.std.intobject import W_IntObject
1066 # the reason we use the *wrapped* stop is that for
1067 # w_stop == wrapped -1, or w_None the stop that is computed will *not*
1068 # be constant, because the length is often not constant.
1069 return (not self.is_ascii() and
1070 jit.isconstant(start) and
1071 (jit.isconstant(w_stop) or
1072 (isinstance(w_stop, W_IntObject) and
1073 jit.isconstant(w_stop.intval))) and
1074 start <= MAX_UNROLL_NEXT_CODEPOINT_POS and
1075 self._len() - stop <= MAX_UNROLL_NEXT_CODEPOINT_POS)
1076
1077 def descr_capitalize(self, space):
1078 return W_UnicodeObject._capitalize_unicode(self._utf8)
1079
1080 @staticmethod
1081 @jit.elidable
1082 def _capitalize_unicode(value):
1083 if len(value) == 0:
1084 return W_UnicodeObject.EMPTY
1085 builder = rutf8.Utf8StringBuilder(len(value))
1086 it = rutf8.Utf8StringPosIterator(value)
1087 uchar, _ = it.next()
1088 codes = unicodedb.totitle_full(uchar)
1089 # can sometimes give more than one, like for omega-with-Ypogegrammeni, 8179
1090 for c in codes:
1091 builder.append_code(c)
1092 for ch, pos in it:
1093 codes = W_UnicodeObject._lower_char(ch, value, pos)
1094 for c in codes:
1095 builder.append_code(c)
1096 return W_UnicodeObject.from_utf8builder(builder)
1097
1098 @unwrap_spec(width=int, w_fillchar=WrappedDefault(u' '))
1099 def descr_center(self, space, width, w_fillchar):
1100 value = self._utf8
1101 fillchar = space.utf8_w(w_fillchar)
1102 if space.len_w(w_fillchar) != 1:
1103 raise oefmt(space.w_TypeError,
1104 "center() argument 2 must be a single character")
1105
1106 d = width - self._len()
1107 if d > 0:
1108 offset = d//2 + (d & width & 1)
1109 centered = offset * fillchar + value + (d - offset) * fillchar
1110 else:
1111 centered = value
1112 d = 0
1113
1114 return W_UnicodeObject(centered, self._len() + d)
1115
1116 def descr_count(self, space, w_sub, w_start=None, w_end=None):
1117 value = self._utf8
1118 start_index, end_index = self._unwrap_and_compute_idx_params(
1119 space, w_start, w_end)
1120 sub = self.convert_arg_to_w_unicode(space, w_sub)._utf8
1121 return space.newint(value.count(sub, start_index, end_index))
1122
1123 def descr_contains(self, space, w_sub):
1124 value = self._utf8
1125 w_other = self.convert_arg_to_w_unicode(space, w_sub)
1126 return space.newbool(value.find(w_other._utf8) >= 0)
1127
1128 def descr_partition(self, space, w_sub):
1129 value = self._utf8
1130 sub = self.convert_arg_to_w_unicode(space, w_sub)
1131 sublen = sub._len()
1132 if sublen == 0:
1133 raise oefmt(space.w_ValueError, "empty separator")
1134
1135 pos = value.find(sub._utf8)
1136
1137 if pos < 0:
1138 return space.newtuple([self, self._empty(), self._empty()])
1139 else:
1140 lgt = rutf8.check_utf8(value, True, stop=pos)
1141 return space.newtuple(
1142 [W_UnicodeObject(value[0:pos], lgt), w_sub,
1143 W_UnicodeObject(value[pos + len(sub._utf8):len(value)],
1144 self._len() - lgt - sublen)])
1145
1146 def descr_rpartition(self, space, w_sub):
1147 value = self._utf8
1148 sub = self.convert_arg_to_w_unicode(space, w_sub)
1149 sublen = sub._len()
1150 if sublen == 0:
1151 raise oefmt(space.w_ValueError, "empty separator")
1152
1153 pos = value.rfind(sub._utf8)
1154
1155 if pos < 0:
1156 return space.newtuple([self._empty(), self._empty(), self])
1157 else:
1158 lgt = rutf8.check_utf8(value, True, stop=pos)
1159 return space.newtuple(
1160 [W_UnicodeObject(value[0:pos], lgt), w_sub,
1161 W_UnicodeObject(value[pos + len(sub._utf8):len(value)],
1162 self._len() - lgt - sublen)])
1163
1164 @unwrap_spec(count=int)
1165 def descr_replace(self, space, w_old, w_new, count=-1):
1166 input = self._utf8
1167
1168 w_sub = self.convert_arg_to_w_unicode(space, w_old)
1169 w_by = self.convert_arg_to_w_unicode(space, w_new)
1170 try:
1171 res, replacements = replace_count(input, w_sub._utf8, w_by._utf8,
1172 count, isutf8=True)
1173 except OverflowError:
1174 raise oefmt(space.w_OverflowError, "replace string is too long")
1175 if type(self) is W_UnicodeObject and replacements == 0:
1176 return self
1177
1178 newlength = self._length + replacements * (w_by._length - w_sub._length)
1179 assert res is not None
1180 return W_UnicodeObject(res, newlength)
1181
1182 def descr_mul(self, space, w_times):
1183 times = space.getindex_w(w_times, space.w_OverflowError)
1184 if times <= 0:
1185 return self._empty()
1186 if times == 1:
1187 from pypy.objspace.std.bytesobject import W_BytesObject
1188 if type(self) is W_UnicodeObject:
1189 return self
1190 if len(self._utf8) == 1:
1191 return W_UnicodeObject(self._utf8[0] * times, times)
1192 return W_UnicodeObject(self._utf8 * times, times * self._len())
1193
1194 descr_rmul = descr_mul
1195
1196 def _get_index_storage(self):
1197 return jit.conditional_call_elidable(self._index_storage,
1198 W_UnicodeObject._compute_index_storage, self)
1199
1200 def _compute_index_storage(self):
1201 storage = rutf8.create_utf8_index_storage(self._utf8, self._length)
1202 self._index_storage = storage
1203 return storage
1204
1205 def _getitem_result(self, space, index):
1206 if (jit.we_are_jitted() and
1207 not self.is_ascii() and
1208 jit.isconstant(index) and
1209 -MAX_UNROLL_NEXT_CODEPOINT_POS <= index <= MAX_UNROLL_NEXT_CODEPOINT_POS):
1210 return self._getitem_result_constant_index_jit(space, index)
1211 if index < 0:
1212 index += self._length
1213 if index < 0 or index >= self._length:
1214 raise oefmt(space.w_IndexError, "string index out of range")
1215 start = self._index_to_byte(index)
1216 # we must not inline next_codepoint_pos, otherwise we produce a guard!
1217 end = self.next_codepoint_pos_dont_look_inside(start)
1218 return W_UnicodeObject(self._utf8[start:end], 1)
1219
1220 @jit.unroll_safe
1221 def _getitem_result_constant_index_jit(self, space, index):
1222 # for small known indices, call next/prev_codepoint_pos a few times
1223 # instead of possibly creating an index structure
1224 if index < 0:
1225 posindex = index + self._length
1226 if posindex < 0:
1227 raise oefmt(space.w_IndexError, "string index out of range")
1228 end = len(self._utf8)
1229 start = self.prev_codepoint_pos_dont_look_inside(end)
1230 for i in range(-index-1):
1231 end = start
1232 start = self.prev_codepoint_pos_dont_look_inside(start)
1233 else:
1234 if index >= self._length:
1235 raise oefmt(space.w_IndexError, "string index out of range")
1236 start = 0
1237 end = self.next_codepoint_pos_dont_look_inside(start)
1238 for i in range(index):
1239 start = end
1240 end = self.next_codepoint_pos_dont_look_inside(end)
1241 assert start >= 0
1242 assert end >= 0
1243 return W_UnicodeObject(self._utf8[start:end], 1)
1244
1245 def is_ascii(self):
1246 return self._length == len(self._utf8)
1247
1248 def descr_isascii(self, space):
1249 return space.newbool(self.is_ascii())
1250
1251 def _index_to_byte(self, index):
1252 if self.is_ascii():
1253 assert index >= 0
1254 return index
1255 return rutf8.codepoint_position_at_index(
1256 self._utf8, self._get_index_storage(), index)
1257
1258 def _codepoints_in_utf8(self, start, end):
1259 if self.is_ascii():
1260 return end - start
1261 return rutf8.codepoints_in_utf8(self._utf8, start, end)
1262
1263 def _byte_to_index(self, bytepos):
1264 """ this returns index such that self._index_to_byte(index) == bytepos
1265 NB: this is slow! roughly logarithmic with a big constant
1266 """
1267 if self.is_ascii():
1268 return bytepos
1269 return rutf8.codepoint_index_at_byte_position(
1270 self._utf8, self._get_index_storage(), bytepos, self._len())
1271
1272 def next_codepoint_pos_dont_look_inside(self, pos):
1273 if self.is_ascii():
1274 return pos + 1
1275 return next_codepoint_pos_dont_look_inside(self._utf8, pos)
1276
1277 def prev_codepoint_pos_dont_look_inside(self, pos):
1278 if self.is_ascii():
1279 return pos - 1
1280 return prev_codepoint_pos_dont_look_inside(self._utf8, pos)
1281
1282 def codepoint_at_pos_dont_look_inside(self, pos):
1283 if self.is_ascii():
1284 return ord(self._utf8[pos])
1285 return codepoint_at_pos_dont_look_inside(self._utf8, pos)
1286
1287 @always_inline
1288 def _unwrap_and_search(self, space, w_sub, w_start, w_end, forward=True):
1289 w_sub = self.convert_arg_to_w_unicode(space, w_sub)
1290 start, end = unwrap_start_stop(space, self._length, w_start, w_end)
1291 if start == 0:
1292 start_index = 0
1293 elif start > self._length:
1294 return None
1295 else:
1296 start_index = self._index_to_byte(start)
1297
1298 if end >= self._length:
1299 end = self._length
1300 end_index = len(self._utf8)
1301 else:
1302 end_index = self._index_to_byte(end)
1303
1304 if forward:
1305 res_index = self._utf8.find(w_sub._utf8, start_index, end_index)
1306 if res_index < 0:
1307 return None
1308 res = self._byte_to_index(res_index)
1309 assert res >= 0
1310 return space.newint(res)
1311 else:
1312 res_index = self._utf8.rfind(w_sub._utf8, start_index, end_index)
1313 if res_index < 0:
1314 return None
1315 res = self._byte_to_index(res_index)
1316 assert res >= 0
1317 return space.newint(res)
1318
1319 def _unwrap_and_compute_idx_params(self, space, w_start, w_end):
1320 # unwrap start and stop indices, optimized for the case where
1321 # start == 0 and end == self._length. Note that 'start' and
1322 # 'end' are measured in codepoints whereas 'start_index' and
1323 # 'end_index' are measured in bytes.
1324 start, end = unwrap_start_stop(space, self._length, w_start, w_end)
1325 start_index = 0
1326 end_index = len(self._utf8)
1327 if start > 0:
1328 if start > self._length:
1329 start_index = end_index + 1
1330 else:
1331 start_index = self._index_to_byte(start)
1332 if end < self._length:
1333 end_index = self._index_to_byte(end)
1334 return (start_index, end_index)
1335
1336 @unwrap_spec(width=int, w_fillchar=WrappedDefault(u' '))
1337 def descr_rjust(self, space, width, w_fillchar):
1338 value = self._utf8
1339 lgt = self._len()
1340 w_fillchar = self.convert_arg_to_w_unicode(space, w_fillchar)
1341 if w_fillchar._len() != 1:
1342 raise oefmt(space.w_TypeError,
1343 "rjust() argument 2 must be a single character")
1344 d = width - lgt
1345 if d > 0:
1346 if len(w_fillchar._utf8) == 1:
1347 # speedup
1348 value = d * w_fillchar._utf8[0] + value
1349 else:
1350 value = d * w_fillchar._utf8 + value
1351 return W_UnicodeObject(value, width)
1352
1353 return W_UnicodeObject(value, lgt)
1354
1355 @unwrap_spec(width=int, w_fillchar=WrappedDefault(u' '))
1356 def descr_ljust(self, space, width, w_fillchar):
1357 value = self._utf8
1358 w_fillchar = self.convert_arg_to_w_unicode(space, w_fillchar)
1359 if w_fillchar._len() != 1:
1360 raise oefmt(space.w_TypeError,
1361 "ljust() argument 2 must be a single character")
1362 d = width - self._len()
1363 if d > 0:
1364 if len(w_fillchar._utf8) == 1:
1365 # speedup
1366 value = value + d * w_fillchar._utf8[0]
1367 else:
1368 value = value + d * w_fillchar._utf8
1369 return W_UnicodeObject(value, width)
1370
1371 return W_UnicodeObject(value, self._len())
1372
1373 def _utf8_sliced(self, start, stop, lgt):
1374 assert start >= 0
1375 assert stop >= 0
1376 #if start == 0 and stop == len(s) and space.is_w(space.type(orig_obj),
1377 # space.w_bytes):
1378 # return orig_obj
1379 return W_UnicodeObject(self._utf8[start:stop], lgt)
1380
1381 def _strip_none(self, space, left, right):
1382 "internal function called by str_xstrip methods"
1383 value = self._utf8
1384 if self.is_ascii():
1385 # in the ascii case we can do even better and do the allocation in
1386 # the trace
1387 lpos = 0
1388 rpos = len(value)
1389 if left:
1390 lpos = self._strip_none_bytes_unboxed_left(value, lpos, rpos)
1391 if right:
1392 rpos = self._strip_none_bytes_unboxed_right(value, lpos, rpos)
1393 return self._utf8_sliced(lpos, rpos, rpos - lpos)
1394 lgt = self._len()
1395 return self._strip_none_unboxed(value, lgt, left, right)
1396
1397 @staticmethod
1398 @jit.elidable
1399 def _strip_none_bytes_unboxed_left(value, lpos, rpos):
1400 while lpos < rpos and rutf8.isspace(value, lpos):
1401 lpos += 1
1402 return lpos
1403
1404 @staticmethod
1405 @jit.elidable
1406 def _strip_none_bytes_unboxed_right(value, lpos, rpos):
1407 while rpos > lpos and rutf8.isspace(value, rpos - 1):
1408 rpos -= 1
1409 return rpos
1410
1411
1412 @staticmethod
1413 @jit.elidable
1414 def _strip_none_unboxed(value, lgt, left, right):
1415 lpos = 0
1416 rpos = len(value)
1417
1418 if left:
1419 while lpos < rpos:
1420 codepoint = rutf8.codepoint_at_pos(value, lpos)
1421 if not unicodedb.isspace(codepoint):
1422 break
1423 lpos = rutf8.next_codepoint_pos(value, lpos)
1424 lgt -= 1
1425
1426 if right:
1427 while rpos > lpos:
1428 prev = rutf8.prev_codepoint_pos(value, rpos)
1429 codepoint = rutf8.codepoint_at_pos(value, prev)
1430 if not unicodedb.isspace(codepoint):
1431 break
1432 rpos = prev
1433 lgt -= 1
1434
1435 assert rpos >= lpos # annotator hint, don't remove
1436 assert lpos >= 0
1437 assert rpos >= 0
1438 return W_UnicodeObject(value[lpos:rpos], lgt)
1439
1440 def _strip(self, space, w_chars, left, right, name='strip'):
1441 "internal function called by str_xstrip methods"
1442 value = self._utf8
1443 chars = self.convert_arg_to_w_unicode(space, w_chars, name)._utf8
1444
1445 lgt = self._len()
1446
1447 if self.is_ascii():
1448 # in the ascii case we can do even better and do the allocation in
1449 # the trace
1450 lpos = 0
1451 rpos = len(value)
1452 if left:
1453 lpos = StringMethods._strip_bytes_unboxed_left(value, chars)
1454 if right:
1455 rpos = StringMethods._strip_bytes_unboxed_right(value, chars, lpos)
1456 return self._utf8_sliced(lpos, rpos, rpos - lpos)
1457 return self._strip_unboxed(value, lgt, chars, left, right)
1458
1459 @staticmethod
1460 @jit.elidable
1461 def _strip_unboxed(value, lgt, chars, left, right):
1462 lpos = 0
1463 rpos = len(value)
1464 if left:
1465 while lpos < rpos and rutf8.utf8_in_chars(value, lpos, chars):
1466 lpos = rutf8.next_codepoint_pos(value, lpos)
1467 lgt -= 1
1468
1469 if right:
1470 while rpos > lpos:
1471 prev = rutf8.prev_codepoint_pos(value, rpos)
1472 if not rutf8.utf8_in_chars(value, prev, chars):
1473 break
1474 rpos = prev
1475 lgt -= 1
1476
1477 assert rpos >= lpos # annotator hint, don't remove
1478 assert lpos >= 0
1479 assert rpos >= 0
1480 return W_UnicodeObject(value[lpos:rpos], lgt)
1481
1482 def descr_getnewargs(self, space):
1483 return space.newtuple([W_UnicodeObject(self._utf8, self._length)])
1484
1485
1486 def descr_isprintable(self, space):
1487 for ch in rutf8.Utf8StringIterator(self._utf8):
1488 if not unicodedb.isprintable(ch):
1489 return space.w_False
1490 return space.w_True
1491
1492 @staticmethod
1493 def _iter_getitem_result(self, space, index):
1494 assert isinstance(self, W_UnicodeObject)
1495 return self._getitem_result(space, index)
1496
1497 def descr_removeprefix(self, space, w_prefix):
1498 w_prefix = self.convert_arg_to_w_unicode(space, w_prefix)
1499 prefix = w_prefix._utf8
1500 selfval = self._utf8
1501 if startswith(selfval, prefix):
1502 return W_UnicodeObject(selfval[len(prefix):], self._length - w_prefix._length)
1503 if type(self) is W_UnicodeObject:
1504 return self
1505 return W_UnicodeObject(selfval, self._length)
1506
1507 def descr_removesuffix(self, space, w_suffix):
1508 w_suffix = self.convert_arg_to_w_unicode(space, w_suffix)
1509 suffix = w_suffix._utf8
1510 selfval = self._utf8
1511 if suffix and endswith(selfval, suffix):
1512 end = len(selfval) - len(suffix)
1513 assert end >= 0
1514 return W_UnicodeObject(selfval[:end], self._length - w_suffix._length)
1515 if type(self) is W_UnicodeObject:
1516 return self
1517 return W_UnicodeObject(selfval, self._length)
1518
1519
1520 def unicode_split_none_wrapped(space, value, length_codepoints, maxsplit=-1):
1521 # we can use the rstring versions, because they use unicode version 5.2
1522 length = len(value)
1523 i = 0
1524 res = []
1525 length_left = length_codepoints
1526 while True:
1527 # find the beginning of the next word
1528 while i < length:
1529 codepoint = rutf8.codepoint_at_pos(value, i)
1530 if not unicodedb.isspace(codepoint):
1531 break # found
1532 i = rutf8.next_codepoint_pos(value, i)
1533 length_left -= 1
1534 else:
1535 break # end of string, finished
1536
1537 # find the end of the word
1538 if maxsplit == 0:
1539 j = length # take all the rest of the string
1540 length_substring = length_left
1541 else:
1542 length_substring = 1
1543 j = rutf8.next_codepoint_pos(value, i)
1544 length_left -= 1
1545 while j < length:
1546 codepoint = rutf8.codepoint_at_pos(value, j)
1547 if unicodedb.isspace(codepoint):
1548 break
1549 j = rutf8.next_codepoint_pos(value, j)
1550 length_substring += 1
1551 length_left -= 1
1552 maxsplit -= 1 # NB. if it's already < 0, it stays < 0
1553
1554 # the word is value[i:j]
1555 res.append(space.newutf8(value[i:j], length_substring))
1556
1557 # continue to look from the character following the space after the word
1558 if j < length:
1559 i = rutf8.next_codepoint_pos(value, j)
1560 length_left -= 1
1561 else:
1562 break
1563 return res
1564
1565 def unicode_rsplit_none(value, maxsplit=-1):
1566 # we can use the rstring versions, because they use unicode version 5.2
1567 def prev(value, pos):
1568 if pos <= 0:
1569 return -1
1570 return intmask(rutf8.prev_codepoint_pos(value, pos))
1571
1572 res = []
1573
1574 i = prev(value, len(value))
1575 while True:
1576 # starting from the end, find the end of the next word
1577 while i >= 0:
1578 codepoint = rutf8.codepoint_at_pos(value, i)
1579 if not unicodedb.isspace(codepoint):
1580 break # found
1581 i = prev(value, i)
1582 else:
1583 break # end of string, finished
1584
1585 # find the start of the word as 'j1'
1586 if maxsplit == 0:
1587 j1 = 0 # take all the rest of the string
1588 j = -1
1589 else:
1590 j1 = i
1591 while True:
1592 j = prev(value, j1)
1593 codepoint = rutf8.codepoint_at_pos(value, j)
1594 if j < 0 or unicodedb.isspace(codepoint):
1595 break
1596 j1 = j
1597 maxsplit -= 1 # NB. if it's already < 0, it stays < 0
1598
1599 # the word is value[j1:i+1]
1600 assert j1 >= 0
1601 i1 = rutf8.next_codepoint_pos(value, i)
1602 res.append(value[j1:i1])
1603
1604 # continue to look from the character before the space before the word
1605 i = prev(value, j)
1606
1607 res.reverse()
1608 return res
1609
1610 def unicode_splitlines(value, keepends):
1611 length = len(value)
1612 strs_w = []
1613 pos = 0
1614 while pos < length:
1615 sol = pos
1616 lgt = 0
1617 while pos < length and not rutf8.islinebreak(value, pos):
1618 pos = rutf8.next_codepoint_pos(value, pos)
1619 lgt += 1
1620 eol = pos
1621 if pos < length:
1622 # read CRLF as one line break
1623 if (value[pos] == '\r' and pos + 1 < length
1624 and value[pos + 1] == '\n'):
1625 pos += 2
1626 line_end_chars = 2
1627 else:
1628 pos = rutf8.next_codepoint_pos(value, pos)
1629 line_end_chars = 1
1630 if keepends:
1631 eol = pos
1632 lgt += line_end_chars
1633 assert eol >= 0
1634 assert sol >= 0
1635 strs_w.append(W_UnicodeObject(value[sol:eol], lgt))
1636 return strs_w
1637
1638 def _isidentifier(u):
1639 if not u:
1640 return False
1641
1642 # PEP 3131 says that the first character must be in XID_Start and
1643 # subsequent characters in XID_Continue, and for the ASCII range,
1644 # the 2.x rules apply (i.e start with letters and underscore,
1645 # continue with letters, digits, underscore). However, given the
1646 # current definition of XID_Start and XID_Continue, it is sufficient
1647 # to check just for these, except that _ must be allowed as starting
1648 # an identifier.
1649 first = u[0]
1650 it = rutf8.Utf8StringIterator(u)
1651 code = it.next()
1652 if not (unicodedb.isxidstart(code) or first == '_'):
1653 return False
1654
1655 for ch in it:
1656 if not unicodedb.isxidcontinue(ch):
1657 return False
1658 return True
1659
1660 # stuff imported from bytesobject for interoperability
1661
1662
1663 # ____________________________________________________________
1664
1665 def getdefaultencoding(space):
1666 return space.sys.defaultencoding
1667
1668
1669 def get_encoding_and_errors(space, w_encoding, w_errors):
1670 from pypy.module._codecs.interp_codecs import utf8_encode_wrapper
1671 if w_encoding is None:
1672 encoding = None
1673 else:
1674 utf8 = space.text_w(w_encoding)
1675 encoding = utf8_encode_wrapper(space, utf8, w_encoding, "strict")
1676 if w_errors is None:
1677 errors = None
1678 else:
1679 utf8 = space.text_w(w_errors)
1680 errors = utf8_encode_wrapper(space, utf8, w_errors, "strict")
1681 return encoding, errors
1682
1683 def encode_object(space, w_obj, encoding, errors):
1684 from pypy.module._codecs.interp_codecs import(
1685 _call_codec, lookup_text_codec, lookup_error)
1686 # fast paths, only ascii, in the other cases it's too easy to mess up
1687 # the errors
1688 if ((errors is None or errors == 'strict') and
1689 isinstance(w_obj, W_UnicodeObject) and w_obj.is_ascii()):
1690 utf8 = w_obj.utf8_w(space)
1691 if (encoding is None or encoding == 'utf-8' or
1692 encoding == 'utf8' or encoding == 'UTF-8' or
1693 encoding == "latin1" or encoding == "latin-1" or
1694 encoding == 'ascii'):
1695 return space.newbytes(utf8)
1696 if encoding is None:
1697 encoding = space.sys.defaultencoding
1698 w_codec_info = lookup_text_codec(space, 'encode', encoding)
1699 if errors is not None and space.sys.get_flag('dev_mode'):
1700 lookup_error(space, errors)
1701 w_encfunc = space.getitem(w_codec_info, space.newint(0))
1702 w_retval = _call_codec(space, w_encfunc, w_obj, "encoding", encoding, errors)
1703 if not space.isinstance_w(w_retval, space.w_bytes):
1704 raise oefmt(space.w_TypeError,
1705 "'%s' encoder returned '%T' instead of 'bytes'; "
1706 "use codecs.encode() to encode to arbitrary types",
1707 encoding,
1708 w_retval)
1709 return w_retval
1710
1711
1712 def decode_object(space, w_obj, encoding, errors=None):
1713 from pypy.module._codecs.interp_codecs import(
1714 _call_codec, lookup_text_codec, lookup_error)
1715 # in all cases, call space.charbuf_w() first. This will fail with a
1716 # TypeError if w_obj is of a random type. Do this even if we're not
1717 # going to use 's'
1718 try:
1719 s = space.charbuf_w(w_obj)
1720 except OperationError as e:
1721 if not e.match(space, space.w_TypeError):
1722 raise
1723 raise oefmt(space.w_TypeError, "decoding to str: %S",
1724 e.get_w_value(space))
1725 #
1726 if errors == 'strict' or errors is None:
1727 # fast paths
1728 if encoding == 'ascii':
1729 unicodehelper.check_ascii_or_raise(space, s, w_obj)
1730 return space.newtext(s, len(s))
1731 if encoding == 'utf-8' or encoding == 'utf8':
1732 lgt = unicodehelper.check_utf8_or_raise(space, s)
1733 return space.newutf8(s, lgt)
1734 if encoding is None:
1735 encoding = space.sys.defaultencoding
1736 if errors is not None and space.sys.get_flag('dev_mode'):
1737 lookup_error(space, errors)
1738 w_codec_info = lookup_text_codec(space, 'decode', encoding)
1739 w_encfunc = space.getitem(w_codec_info, space.newint(1))
1740 w_retval = _call_codec(space, w_encfunc, w_obj, "decoding", encoding, errors)
1741 if not isinstance(w_retval, W_UnicodeObject):
1742 raise oefmt(space.w_TypeError,
1743 "'%s' decoder returned '%T' instead of 'str'; "
1744 "use codecs.decode() to decode to arbitrary types",
1745 encoding,
1746 w_retval)
1747 return w_retval
1748
1749 def unicode_from_object(space, w_obj):
1750 if space.is_w(space.type(w_obj), space.w_unicode):
1751 return w_obj
1752 if space.lookup(w_obj, "__str__") is not None:
1753 return space.str(w_obj)
1754 return space.repr(w_obj)
1755
1756 def ascii_from_object(space, w_obj):
1757 """Implements builtins.ascii()"""
1758 # repr is guaranteed to be unicode
1759 w_repr = space.repr(w_obj)
1760 w_type = space.type(w_repr)
1761 w_encoded = encode_object(space, w_repr, 'ascii', 'backslashreplace')
1762 # Weird CPython logic
1763 if w_type is space.w_text or (space.len_w(w_repr) != space.len_w(w_encoded)):
1764 return decode_object(space, w_encoded, 'ascii', 'strict')
1765 else:
1766 w_obj = decode_object(space, w_encoded, 'ascii', 'strict')
1767 w_newfunc = space.getattr(w_type, space.newtext('__new__'))
1768 return space.call_function(w_newfunc, w_type, w_obj)
1769
1770 def unicode_from_string(space, w_bytes):
1771 # this is a performance and bootstrapping hack
1772 encoding = getdefaultencoding(space)
1773 if encoding != 'ascii':
1774 return decode_object(space, w_bytes, encoding, "strict")
1775 s = space.bytes_w(w_bytes)
1776 unicodehelper.check_ascii_or_raise(space, s, w_bytes)
1777 return W_UnicodeObject(s, len(s))
1778
1779
1780 class UnicodeDocstrings:
1781 """str(object='') -> str
1782 str(bytes_or_buffer[, encoding[, errors]]) -> str
1783
1784 Create a new string object from the given object. If encoding or
1785 errors is specified, then the object must expose a data buffer
1786 that will be decoded using the given encoding and error handler.
1787 Otherwise, returns the result of object.__str__() (if defined)
1788 or repr(object).
1789 encoding defaults to sys.getdefaultencoding().
1790 errors defaults to 'strict'.
1791
1792 """
1793
1794 def __add__():
1795 """x.__add__(y) <==> x+y"""
1796
1797 def __contains__():
1798 """x.__contains__(y) <==> y in x"""
1799
1800 def __eq__():
1801 """x.__eq__(y) <==> x==y"""
1802
1803 def __format__():
1804 """S.__format__(format_spec) -> unicode
1805
1806 Return a formatted version of S as described by format_spec.
1807 """
1808
1809 def __ge__():
1810 """x.__ge__(y) <==> x>=y"""
1811
1812 def __getattribute__():
1813 """x.__getattribute__('name') <==> x.name"""
1814
1815 def __getitem__():
1816 """x.__getitem__(y) <==> x[y]"""
1817
1818 def __getnewargs__():
1819 ""
1820
1821 def __gt__():
1822 """x.__gt__(y) <==> x>y"""
1823
1824 def __hash__():
1825 """x.__hash__() <==> hash(x)"""
1826
1827 def __iter__():
1828 """x.__iter__() <==> iter(x)"""
1829
1830 def __le__():
1831 """x.__le__(y) <==> x<=y"""
1832
1833 def __len__():
1834 """x.__len__() <==> len(x)"""
1835
1836 def __lt__():
1837 """x.__lt__(y) <==> x<y"""
1838
1839 def __mod__():
1840 """x.__mod__(y) <==> x%y"""
1841
1842 def __rmod__():
1843 """x.__rmod__(y) <==> y%x"""
1844
1845 def __mul__():
1846 """x.__mul__(n) <==> x*n"""
1847
1848 def __ne__():
1849 """x.__ne__(y) <==> x!=y"""
1850
1851 def __repr__():
1852 """x.__repr__() <==> repr(x)"""
1853
1854 def __rmod__():
1855 """x.__rmod__(y) <==> y%x"""
1856
1857 def __rmul__():
1858 """x.__rmul__(n) <==> n*x"""
1859
1860 def __sizeof__():
1861 """S.__sizeof__() -> size of S in memory, in bytes"""
1862
1863 def __str__():
1864 """x.__str__() <==> str(x)"""
1865
1866 def capitalize():
1867 """S.capitalize() -> unicode
1868
1869 Return a capitalized version of S, i.e. make the first character
1870 have upper case and the rest lower case.
1871 """
1872
1873 def center():
1874 """S.center(width[, fillchar]) -> unicode
1875
1876 Return S centered in a Unicode string of length width. Padding is
1877 done using the specified fill character (default is a space).
1878 """
1879
1880 def count():
1881 """S.count(sub[, start[, end]]) -> int
1882
1883 Return the number of non-overlapping occurrences of substring sub in
1884 Unicode string S[start:end]. Optional arguments start and end are
1885 interpreted as in slice notation.
1886 """
1887
1888 def encode():
1889 """S.encode(encoding=None, errors='strict') -> string or unicode
1890
1891 Encode S using the codec registered for encoding. encoding defaults
1892 to the default encoding. errors may be given to set a different error
1893 handling scheme. Default is 'strict' meaning that encoding errors raise
1894 a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
1895 'xmlcharrefreplace' as well as any other name registered with
1896 codecs.register_error that can handle UnicodeEncodeErrors.
1897 """
1898
1899 def endswith():
1900 """S.endswith(suffix[, start[, end]]) -> bool
1901
1902 Return True if S ends with the specified suffix, False otherwise.
1903 With optional start, test S beginning at that position.
1904 With optional end, stop comparing S at that position.
1905 suffix can also be a tuple of strings to try.
1906 """
1907
1908 def expandtabs():
1909 """S.expandtabs([tabsize]) -> unicode
1910
1911 Return a copy of S where all tab characters are expanded using spaces.
1912 If tabsize is not given, a tab size of 8 characters is assumed.
1913 """
1914
1915 def find():
1916 """S.find(sub[, start[, end]]) -> int
1917
1918 Return the lowest index in S where substring sub is found,
1919 such that sub is contained within S[start:end]. Optional
1920 arguments start and end are interpreted as in slice notation.
1921
1922 Return -1 on failure.
1923 """
1924
1925 def format():
1926 """S.format(*args, **kwargs) -> unicode
1927
1928 Return a formatted version of S, using substitutions from args and
1929 kwargs. The substitutions are identified by braces ('{' and '}').
1930 """
1931
1932 def format_map():
1933 """S.format_map(mapping) -> str
1934
1935 Return a formatted version of S, using substitutions from
1936 mapping. The substitutions are identified by braces ('{' and
1937 '}').
1938 """
1939
1940 def index():
1941 """S.index(sub[, start[, end]]) -> int
1942
1943 Like S.find() but raise ValueError when the substring is not found.
1944 """
1945
1946 def isalnum():
1947 """S.isalnum() -> bool
1948
1949 Return True if all characters in S are alphanumeric
1950 and there is at least one character in S, False otherwise.
1951 """
1952
1953 def isalpha():
1954 """S.isalpha() -> bool
1955
1956 Return True if all characters in S are alphabetic
1957 and there is at least one character in S, False otherwise.
1958 """
1959
1960 def isascii():
1961 """Return True if all characters in the string are ASCII, False otherwise.
1962
1963 ASCII characters have code points in the range U+0000-U+007F.
1964 Empty string is ASCII too.
1965 """
1966
1967 def casefold():
1968 """S.casefold() -> str
1969
1970 Return a version of S suitable for caseless comparisons.
1971 """
1972
1973 def isdecimal():
1974 """S.isdecimal() -> bool
1975
1976 Return True if there are only decimal characters in S,
1977 False otherwise.
1978 """
1979
1980 def isdigit():
1981 """S.isdigit() -> bool
1982
1983 Return True if all characters in S are digits
1984 and there is at least one character in S, False otherwise.
1985 """
1986
1987 def isidentifier():
1988 """S.isidentifier() -> bool
1989
1990 Return True if S is a valid identifier according to the language
1991 definition.
1992 """
1993
1994 def islower():
1995 """S.islower() -> bool
1996
1997 Return True if all cased characters in S are lowercase and there is
1998 at least one cased character in S, False otherwise.
1999 """
2000
2001 def isnumeric():
2002 """S.isnumeric() -> bool
2003
2004 Return True if there are only numeric characters in S,
2005 False otherwise.
2006 """
2007
2008 def isprintable():
2009 """S.isprintable() -> bool
2010
2011 Return True if all characters in S are considered printable in
2012 repr() or S is empty, False otherwise.
2013 """
2014
2015 def isspace():
2016 """S.isspace() -> bool
2017
2018 Return True if all characters in S are whitespace
2019 and there is at least one character in S, False otherwise.
2020 """
2021
2022 def istitle():
2023 """S.istitle() -> bool
2024
2025 Return True if S is a titlecased string and there is at least one
2026 character in S, i.e. upper- and titlecase characters may only
2027 follow uncased characters and lowercase characters only cased ones.
2028 Return False otherwise.
2029 """
2030
2031 def isupper():
2032 """S.isupper() -> bool
2033
2034 Return True if all cased characters in S are uppercase and there is
2035 at least one cased character in S, False otherwise.
2036 """
2037
2038 def join():
2039 """S.join(iterable) -> unicode
2040
2041 Return a string which is the concatenation of the strings in the
2042 iterable. The separator between elements is S.
2043 """
2044
2045 def ljust():
2046 """S.ljust(width[, fillchar]) -> int
2047
2048 Return S left-justified in a Unicode string of length width. Padding is
2049 done using the specified fill character (default is a space).
2050 """
2051
2052 def lower():
2053 """S.lower() -> unicode
2054
2055 Return a copy of the string S converted to lowercase.
2056 """
2057
2058 def lstrip():
2059 """S.lstrip([chars]) -> unicode
2060
2061 Return a copy of the string S with leading whitespace removed.
2062 If chars is given and not None, remove characters in chars instead.
2063 If chars is a str, it will be converted to unicode before stripping
2064 """
2065
2066 def maketrans():
2067 """str.maketrans(x[, y[, z]]) -> dict (static method)
2068
2069 Return a translation table usable for str.translate(). If there
2070 is only one argument, it must be a dictionary mapping Unicode
2071 ordinals (integers) or characters to Unicode ordinals, strings
2072 or None. Character keys will be then converted to ordinals. If
2073 there are two arguments, they must be strings of equal length,
2074 and in the resulting dictionary, each character in x will be
2075 mapped to the character at the same position in y. If there is a
2076 third argument, it must be a string, whose characters will be
2077 mapped to None in the result.
2078 """
2079
2080 def partition():
2081 """S.partition(sep) -> (head, sep, tail)
2082
2083 Search for the separator sep in S, and return the part before it,
2084 the separator itself, and the part after it. If the separator is not
2085 found, return S and two empty strings.
2086 """
2087
2088 def replace():
2089 """S.replace(old, new[, count]) -> unicode
2090
2091 Return a copy of S with all occurrences of substring
2092 old replaced by new. If the optional argument count is
2093 given, only the first count occurrences are replaced.
2094 """
2095
2096 def rfind():
2097 """S.rfind(sub[, start[, end]]) -> int
2098
2099 Return the highest index in S where substring sub is found,
2100 such that sub is contained within S[start:end]. Optional
2101 arguments start and end are interpreted as in slice notation.
2102
2103 Return -1 on failure.
2104 """
2105
2106 def rindex():
2107 """S.rindex(sub[, start[, end]]) -> int
2108
2109 Like S.rfind() but raise ValueError when the substring is not found.
2110 """
2111
2112 def rjust():
2113 """S.rjust(width[, fillchar]) -> unicode
2114
2115 Return S right-justified in a Unicode string of length width. Padding
2116 is done using the specified fill character (default is a space).
2117 """
2118
2119 def rpartition():
2120 """S.rpartition(sep) -> (head, sep, tail)
2121
2122 Search for the separator sep in S, starting at the end of S, and return
2123 the part before it, the separator itself, and the part after it. If
2124 the separator is not found, return two empty strings and S.
2125 """
2126
2127 def rsplit():
2128 """S.rsplit(sep=None, maxsplit=-1) -> list of strings
2129
2130 Return a list of the words in S, using sep as the
2131 delimiter string, starting at the end of the string and
2132 working to the front. If maxsplit is given, at most maxsplit
2133 splits are done. If sep is not specified, any whitespace string
2134 is a separator.
2135 """
2136
2137 def rstrip():
2138 """S.rstrip([chars]) -> unicode
2139
2140 Return a copy of the string S with trailing whitespace removed.
2141 If chars is given and not None, remove characters in chars instead.
2142 If chars is a str, it will be converted to unicode before stripping
2143 """
2144
2145 def split():
2146 """S.split(sep=None, maxsplit=-1) -> list of strings
2147
2148 Return a list of the words in S, using sep as the
2149 delimiter string. If maxsplit is given, at most maxsplit
2150 splits are done. If sep is not specified or is None, any
2151 whitespace string is a separator and empty strings are
2152 removed from the result.
2153 """
2154
2155 def splitlines():
2156 """S.splitlines(keepends=False) -> list of strings
2157
2158 Return a list of the lines in S, breaking at line boundaries.
2159 Line breaks are not included in the resulting list unless keepends
2160 is given and true.
2161 """
2162
2163 def startswith():
2164 """S.startswith(prefix[, start[, end]]) -> bool
2165
2166 Return True if S starts with the specified prefix, False otherwise.
2167 With optional start, test S beginning at that position.
2168 With optional end, stop comparing S at that position.
2169 prefix can also be a tuple of strings to try.
2170 """
2171
2172 def strip():
2173 """S.strip([chars]) -> unicode
2174
2175 Return a copy of the string S with leading and trailing
2176 whitespace removed.
2177 If chars is given and not None, remove characters in chars instead.
2178 If chars is a str, it will be converted to unicode before stripping
2179 """
2180
2181 def swapcase():
2182 """S.swapcase() -> unicode
2183
2184 Return a copy of S with uppercase characters converted to lowercase
2185 and vice versa.
2186 """
2187
2188 def title():
2189 """S.title() -> unicode
2190
2191 Return a titlecased version of S, i.e. words start with title case
2192 characters, all remaining cased characters have lower case.
2193 """
2194
2195 def translate():
2196 """S.translate(table) -> unicode
2197
2198 Return a copy of the string S, where all characters have been mapped
2199 through the given translation table, which must be a mapping of
2200 Unicode ordinals to Unicode ordinals, Unicode strings or None.
2201 Unmapped characters are left untouched. Characters mapped to None
2202 are deleted.
2203 """
2204
2205 def upper():
2206 """S.upper() -> unicode
2207
2208 Return a copy of S converted to uppercase.
2209 """
2210
2211 def zfill():
2212 """S.zfill(width) -> unicode
2213
2214 Pad a numeric string S with zeros on the left, to fill a field
2215 of the specified width. The string S is never truncated.
2216 """
2217
2218
2219 W_UnicodeObject.typedef = TypeDef(
2220 "str",
2221 __new__ = interp2app(W_UnicodeObject.descr_new),
2222 __doc__ = UnicodeDocstrings.__doc__,
2223
2224 __repr__ = interp2app(W_UnicodeObject.descr_repr,
2225 doc=UnicodeDocstrings.__repr__.__doc__),
2226 __str__ = interp2app(W_UnicodeObject.descr_str,
2227 doc=UnicodeDocstrings.__str__.__doc__),
2228 __hash__ = interp2app(W_UnicodeObject.descr_hash,
2229 doc=UnicodeDocstrings.__hash__.__doc__),
2230
2231 __eq__ = interp2app(W_UnicodeObject.descr_eq,
2232 doc=UnicodeDocstrings.__eq__.__doc__),
2233 __ne__ = interp2app(W_UnicodeObject.descr_ne,
2234 doc=UnicodeDocstrings.__ne__.__doc__),
2235 __lt__ = interp2app(W_UnicodeObject.descr_lt,
2236 doc=UnicodeDocstrings.__lt__.__doc__),
2237 __le__ = interp2app(W_UnicodeObject.descr_le,
2238 doc=UnicodeDocstrings.__le__.__doc__),
2239 __gt__ = interp2app(W_UnicodeObject.descr_gt,
2240 doc=UnicodeDocstrings.__gt__.__doc__),
2241 __ge__ = interp2app(W_UnicodeObject.descr_ge,
2242 doc=UnicodeDocstrings.__ge__.__doc__),
2243
2244 __iter__ = interp2app(W_UnicodeObject.descr_iter,
2245 doc=UnicodeDocstrings.__iter__.__doc__),
2246 __len__ = interp2app(W_UnicodeObject.descr_len,
2247 doc=UnicodeDocstrings.__len__.__doc__),
2248 __contains__ = interp2app(W_UnicodeObject.descr_contains,
2249 doc=UnicodeDocstrings.__contains__.__doc__),
2250
2251 __add__ = interp2app(W_UnicodeObject.descr_add,
2252 doc=UnicodeDocstrings.__add__.__doc__),
2253 __mul__ = interp2app(W_UnicodeObject.descr_mul,
2254 doc=UnicodeDocstrings.__mul__.__doc__),
2255 __rmul__ = interp2app(W_UnicodeObject.descr_mul,
2256 doc=UnicodeDocstrings.__rmul__.__doc__),
2257
2258 __getitem__ = interp2app(W_UnicodeObject.descr_getitem,
2259 doc=UnicodeDocstrings.__getitem__.__doc__),
2260
2261 capitalize = interp2app(W_UnicodeObject.descr_capitalize,
2262 doc=UnicodeDocstrings.capitalize.__doc__),
2263 casefold = interp2app(W_UnicodeObject.descr_casefold,
2264 doc=UnicodeDocstrings.casefold.__doc__),
2265 center = interp2app(W_UnicodeObject.descr_center,
2266 doc=UnicodeDocstrings.center.__doc__),
2267 count = interp2app(W_UnicodeObject.descr_count,
2268 doc=UnicodeDocstrings.count.__doc__),
2269 encode = interp2app(W_UnicodeObject.descr_encode,
2270 doc=UnicodeDocstrings.encode.__doc__),
2271 expandtabs = interp2app(W_UnicodeObject.descr_expandtabs,
2272 doc=UnicodeDocstrings.expandtabs.__doc__),
2273 find = interp2app(W_UnicodeObject.descr_find,
2274 doc=UnicodeDocstrings.find.__doc__),
2275 rfind = interp2app(W_UnicodeObject.descr_rfind,
2276 doc=UnicodeDocstrings.rfind.__doc__),
2277 index = interp2app(W_UnicodeObject.descr_index,
2278 doc=UnicodeDocstrings.index.__doc__),
2279 rindex = interp2app(W_UnicodeObject.descr_rindex,
2280 doc=UnicodeDocstrings.rindex.__doc__),
2281 isalnum = interp2app(W_UnicodeObject.descr_isalnum,
2282 doc=UnicodeDocstrings.isalnum.__doc__),
2283 isalpha = interp2app(W_UnicodeObject.descr_isalpha,
2284 doc=UnicodeDocstrings.isalpha.__doc__),
2285 isascii = interp2app(W_UnicodeObject.descr_isascii,
2286 doc=UnicodeDocstrings.isascii.__doc__),
2287 isdecimal = interp2app(W_UnicodeObject.descr_isdecimal,
2288 doc=UnicodeDocstrings.isdecimal.__doc__),
2289 isdigit = interp2app(W_UnicodeObject.descr_isdigit,
2290 doc=UnicodeDocstrings.isdigit.__doc__),
2291 isidentifier = interp2app(W_UnicodeObject.descr_isidentifier,
2292 doc=UnicodeDocstrings.isidentifier.__doc__),
2293 islower = interp2app(W_UnicodeObject.descr_islower,
2294 doc=UnicodeDocstrings.islower.__doc__),
2295 isnumeric = interp2app(W_UnicodeObject.descr_isnumeric,
2296 doc=UnicodeDocstrings.isnumeric.__doc__),
2297 isprintable = interp2app(W_UnicodeObject.descr_isprintable,
2298 doc=UnicodeDocstrings.isprintable.__doc__),
2299 isspace = interp2app(W_UnicodeObject.descr_isspace,
2300 doc=UnicodeDocstrings.isspace.__doc__),
2301 istitle = interp2app(W_UnicodeObject.descr_istitle,
2302 doc=UnicodeDocstrings.istitle.__doc__),
2303 isupper = interp2app(W_UnicodeObject.descr_isupper,
2304 doc=UnicodeDocstrings.isupper.__doc__),
2305 join = interp2app(W_UnicodeObject.descr_join,
2306 doc=UnicodeDocstrings.join.__doc__),
2307 ljust = interp2app(W_UnicodeObject.descr_ljust,
2308 doc=UnicodeDocstrings.ljust.__doc__),
2309 rjust = interp2app(W_UnicodeObject.descr_rjust,
2310 doc=UnicodeDocstrings.rjust.__doc__),
2311 lower = interp2app(W_UnicodeObject.descr_lower,
2312 doc=UnicodeDocstrings.lower.__doc__),
2313 partition = interp2app(W_UnicodeObject.descr_partition,
2314 doc=UnicodeDocstrings.partition.__doc__),
2315 rpartition = interp2app(W_UnicodeObject.descr_rpartition,
2316 doc=UnicodeDocstrings.rpartition.__doc__),
2317 replace = interp2app(W_UnicodeObject.descr_replace,
2318 doc=UnicodeDocstrings.replace.__doc__),
2319 split = interp2app(W_UnicodeObject.descr_split,
2320 doc=UnicodeDocstrings.split.__doc__),
2321 rsplit = interp2app(W_UnicodeObject.descr_rsplit,
2322 doc=UnicodeDocstrings.rsplit.__doc__),
2323 splitlines = interp2app(W_UnicodeObject.descr_splitlines,
2324 doc=UnicodeDocstrings.splitlines.__doc__),
2325 startswith = interp2app(W_UnicodeObject.descr_startswith,
2326 doc=UnicodeDocstrings.startswith.__doc__),
2327 endswith = interp2app(W_UnicodeObject.descr_endswith,
2328 doc=UnicodeDocstrings.endswith.__doc__),
2329 strip = interp2app(W_UnicodeObject.descr_strip,
2330 doc=UnicodeDocstrings.strip.__doc__),
2331 lstrip = interp2app(W_UnicodeObject.descr_lstrip,
2332 doc=UnicodeDocstrings.lstrip.__doc__),
2333 rstrip = interp2app(W_UnicodeObject.descr_rstrip,
2334 doc=UnicodeDocstrings.rstrip.__doc__),
2335 swapcase = interp2app(W_UnicodeObject.descr_swapcase,
2336 doc=UnicodeDocstrings.swapcase.__doc__),
2337 title = interp2app(W_UnicodeObject.descr_title,
2338 doc=UnicodeDocstrings.title.__doc__),
2339 translate = interp2app(W_UnicodeObject.descr_translate,
2340 doc=UnicodeDocstrings.translate.__doc__),
2341 upper = interp2app(W_UnicodeObject.descr_upper,
2342 doc=UnicodeDocstrings.upper.__doc__),
2343 zfill = interp2app(W_UnicodeObject.descr_zfill,
2344 doc=UnicodeDocstrings.zfill.__doc__),
2345
2346 format = interp2app(W_UnicodeObject.descr_format,
2347 doc=UnicodeDocstrings.format.__doc__),
2348 format_map = interp2app(W_UnicodeObject.descr_format_map,
2349 doc=UnicodeDocstrings.format_map.__doc__),
2350 __format__ = interp2app(W_UnicodeObject.descr__format__,
2351 doc=UnicodeDocstrings.__format__.__doc__),
2352 __mod__ = interp2app(W_UnicodeObject.descr_mod,
2353 doc=UnicodeDocstrings.__mod__.__doc__),
2354 __rmod__ = interp2app(W_UnicodeObject.descr_rmod,
2355 doc=UnicodeDocstrings.__rmod__.__doc__),
2356 __getnewargs__ = interp2app(W_UnicodeObject.descr_getnewargs,
2357 doc=UnicodeDocstrings.__getnewargs__.__doc__),
2358 maketrans = interp2app(W_UnicodeObject.descr_maketrans,
2359 as_classmethod=True,
2360 doc=UnicodeDocstrings.maketrans.__doc__),
2361
2362 removeprefix = interp2app(W_UnicodeObject.descr_removeprefix),
2363 removesuffix = interp2app(W_UnicodeObject.descr_removesuffix),
2364 )
2365 W_UnicodeObject.typedef.flag_sequence_bug_compat = True
2366
2367
2368 W_UnicodeObject.EMPTY = W_UnicodeObject('', 0)
2369
2370 # Helper for converting int/long this is called only from
2371 # {int,long,float}type.descr__new__: in the default branch this is implemented
2372 # using the same logic as PyUnicode_EncodeDecimal, as CPython 2.7 does.
2373 #
2374 # In CPython3 the call to PyUnicode_EncodeDecimal has been replaced to a call
2375 # to _PyUnicode_TransformDecimalAndSpaceToASCII, which is much simpler.
2376 # We do that here plus the final step of encoding the result to utf-8.
2377 # This final step corresponds to encode_utf8. In float.__new__() and
2378 # complex.__new__(), a lone surrogate will throw an app-level
2379 # UnicodeEncodeError.
2380
2381 def unicode_to_decimal_w(space, w_unistr):
2382 if not isinstance(w_unistr, W_UnicodeObject):
2383 raise oefmt(space.w_TypeError, "expected unicode, got '%T'", w_unistr)
2384 if w_unistr.is_ascii():
2385 # fast path
2386 return w_unistr._utf8
2387 else:
2388 return _unicode_to_decimal_w(space, w_unistr)
2389
2390 def _unicode_to_decimal_w(space, w_unistr):
2391 # slow path, in a separate function for the JIT's benefit
2392 utf8 = w_unistr._utf8
2393 result = StringBuilder(w_unistr._len())
2394 it = rutf8.Utf8StringIterator(utf8)
2395 for uchr in it:
2396 if uchr > 127:
2397 if W_UnicodeObject._isspace(uchr):
2398 result.append(' ')
2399 continue
2400 try:
2401 uchr = ord(u'0') + unicodedb.decimal(uchr)
2402 except KeyError:
2403 pass
2404 try:
2405 c = rutf8.unichr_as_utf8(r_uint(uchr))
2406 except rutf8.OutOfRange:
2407 w_encoding = space.newtext('utf-8')
2408 pos = it.get_pos()
2409 w_start = space.newint(pos)
2410 w_end = space.newint(pos + 1)
2411 w_reason = space.newtext('surrogates not allowed')
2412 raise OperationError(space.w_UnicodeEncodeError,
2413 space.newtuple([w_encoding, w_unistr,
2414 w_start, w_end,
2415 w_reason]))
2416 result.append(c)
2417 return result.build()
2418
2419 _repr_function = rutf8.make_utf8_escape_function(
2420 pass_printable=True, quotes=True, prefix='',
2421 unicodedb=unicodedb)