-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathunicode.py
2675 lines (2151 loc) · 87.9 KB
/
unicode.py
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import sys
import operator
import numpy as np
from llvmlite.ir import IntType, Constant
from numba.core.cgutils import is_nonelike
from numba.core.extending import (
models,
register_model,
make_attribute_wrapper,
unbox,
box,
NativeValue,
overload,
overload_method,
intrinsic,
register_jitable,
)
from numba.core.imputils import (lower_constant, lower_cast, lower_builtin,
iternext_impl, impl_ret_new_ref, RefType)
from numba.core.datamodel import register_default, StructModel
from numba.core import types, cgutils, config
from numba.core.utils import PYVERSION
from numba.core.pythonapi import (
PY_UNICODE_1BYTE_KIND,
PY_UNICODE_2BYTE_KIND,
PY_UNICODE_4BYTE_KIND,
)
from numba._helperlib import c_helpers
from numba.cpython.hashing import _Py_hash_t
from numba.core.unsafe.bytes import memcpy_region
from numba.core.errors import TypingError
from numba.cpython.unicode_support import (_Py_TOUPPER, _Py_TOLOWER, _Py_UCS4,
_Py_ISALNUM,
_PyUnicode_ToUpperFull,
_PyUnicode_ToLowerFull,
_PyUnicode_ToFoldedFull,
_PyUnicode_ToTitleFull,
_PyUnicode_IsPrintable,
_PyUnicode_IsSpace,
_Py_ISSPACE,
_PyUnicode_IsXidStart,
_PyUnicode_IsXidContinue,
_PyUnicode_IsCased,
_PyUnicode_IsCaseIgnorable,
_PyUnicode_IsUppercase,
_PyUnicode_IsLowercase,
_PyUnicode_IsLineBreak,
_Py_ISLINEBREAK,
_Py_ISLINEFEED,
_Py_ISCARRIAGERETURN,
_PyUnicode_IsTitlecase,
_Py_ISLOWER,
_Py_ISUPPER,
_Py_TAB,
_Py_LINEFEED,
_Py_CARRIAGE_RETURN,
_Py_SPACE,
_PyUnicode_IsAlpha,
_PyUnicode_IsNumeric,
_Py_ISALPHA,
_PyUnicode_IsDigit,
_PyUnicode_IsDecimalDigit)
from numba.cpython import slicing
if PYVERSION in ((3, 10), (3, 11)):
from numba.core.pythonapi import PY_UNICODE_WCHAR_KIND
# https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Objects/unicodeobject.c#L84-L85 # noqa: E501
_MAX_UNICODE = 0x10ffff
# https://github.com/python/cpython/blob/1960eb005e04b7ad8a91018088cfdb0646bc1ca0/Objects/stringlib/fastsearch.h#L31 # noqa: E501
if config.USE_LEGACY_TYPE_SYSTEM:
_BLOOM_WIDTH = types.intp.bitwidth
else:
_BLOOM_WIDTH = types.py_int.bitwidth
# DATA MODEL
@register_model(types.UnicodeType)
class UnicodeModel(models.StructModel):
def __init__(self, dmm, fe_type):
members = [
('data', types.voidptr),
('length', types.intp),
('kind', types.int32),
('is_ascii', types.uint32),
('hash', _Py_hash_t),
('meminfo', types.MemInfoPointer(types.voidptr)),
# A pointer to the owner python str/unicode object
('parent', types.pyobject),
]
models.StructModel.__init__(self, dmm, fe_type, members)
make_attribute_wrapper(types.UnicodeType, 'data', '_data')
make_attribute_wrapper(types.UnicodeType, 'length', '_length')
make_attribute_wrapper(types.UnicodeType, 'kind', '_kind')
make_attribute_wrapper(types.UnicodeType, 'is_ascii', '_is_ascii')
make_attribute_wrapper(types.UnicodeType, 'hash', '_hash')
@register_default(types.UnicodeIteratorType)
class UnicodeIteratorModel(StructModel):
def __init__(self, dmm, fe_type):
members = [('index', types.EphemeralPointer(types.uintp)),
('data', fe_type.data)]
super(UnicodeIteratorModel, self).__init__(dmm, fe_type, members)
# CAST
def compile_time_get_string_data(obj):
"""Get string data from a python string for use at compile-time to embed
the string data into the LLVM module.
"""
from ctypes import (
CFUNCTYPE, c_void_p, c_int, c_uint, c_ssize_t, c_ubyte, py_object,
POINTER, byref,
)
extract_unicode_fn = c_helpers['extract_unicode']
proto = CFUNCTYPE(c_void_p, py_object, POINTER(c_ssize_t), POINTER(c_int),
POINTER(c_uint), POINTER(c_ssize_t))
fn = proto(extract_unicode_fn)
length = c_ssize_t()
kind = c_int()
is_ascii = c_uint()
hashv = c_ssize_t()
data = fn(obj, byref(length), byref(kind), byref(is_ascii), byref(hashv))
if data is None:
raise ValueError("cannot extract unicode data from the given string")
length = length.value
kind = kind.value
is_ascii = is_ascii.value
nbytes = (length + 1) * _kind_to_byte_width(kind)
out = (c_ubyte * nbytes).from_address(data)
return bytes(out), length, kind, is_ascii, hashv.value
def make_string_from_constant(context, builder, typ, literal_string):
"""
Get string data by `compile_time_get_string_data()` and return a
unicode_type LLVM value
"""
databytes, length, kind, is_ascii, hashv = \
compile_time_get_string_data(literal_string)
mod = builder.module
gv = context.insert_const_bytes(mod, databytes)
uni_str = cgutils.create_struct_proxy(typ)(context, builder)
uni_str.data = gv
uni_str.length = uni_str.length.type(length)
uni_str.kind = uni_str.kind.type(kind)
uni_str.is_ascii = uni_str.is_ascii.type(is_ascii)
# Set hash to -1 to indicate that it should be computed.
# We cannot bake in the hash value because of hashseed randomization.
uni_str.hash = uni_str.hash.type(-1)
return uni_str._getvalue()
@lower_cast(types.StringLiteral, types.unicode_type)
def cast_from_literal(context, builder, fromty, toty, val):
return make_string_from_constant(
context, builder, toty, fromty.literal_value,
)
# CONSTANT
@lower_constant(types.unicode_type)
def constant_unicode(context, builder, typ, pyval):
return make_string_from_constant(context, builder, typ, pyval)
# BOXING
@unbox(types.UnicodeType)
def unbox_unicode_str(typ, obj, c):
"""
Convert a unicode str object to a native unicode structure.
"""
ok, data, length, kind, is_ascii, hashv = \
c.pyapi.string_as_string_size_and_kind(obj)
uni_str = cgutils.create_struct_proxy(typ)(c.context, c.builder)
uni_str.data = data
uni_str.length = length
uni_str.kind = kind
uni_str.is_ascii = is_ascii
uni_str.hash = hashv
uni_str.meminfo = c.pyapi.nrt_meminfo_new_from_pyobject(
data, # the borrowed data pointer
obj, # the owner pyobject; the call will incref it.
)
uni_str.parent = obj
is_error = cgutils.is_not_null(c.builder, c.pyapi.err_occurred())
return NativeValue(uni_str._getvalue(), is_error=is_error)
@box(types.UnicodeType)
def box_unicode_str(typ, val, c):
"""
Convert a native unicode structure to a unicode string
"""
uni_str = cgutils.create_struct_proxy(typ)(c.context, c.builder, value=val)
res = c.pyapi.string_from_kind_and_data(
uni_str.kind, uni_str.data, uni_str.length)
# hash isn't needed now, just compute it so it ends up in the unicodeobject
# hash cache, cpython doesn't always do this, depends how a string was
# created it's safe, just burns the cycles required to hash on @box
c.pyapi.object_hash(res)
c.context.nrt.decref(c.builder, typ, val)
return res
# HELPER FUNCTIONS
def make_deref_codegen(bitsize):
def codegen(context, builder, signature, args):
data, idx = args
ptr = builder.bitcast(data, IntType(bitsize).as_pointer())
ch = builder.load(builder.gep(ptr, [idx]))
return builder.zext(ch, IntType(32))
return codegen
@intrinsic
def deref_uint8(typingctx, data, offset):
sig = types.uint32(types.voidptr, types.intp)
return sig, make_deref_codegen(8)
@intrinsic
def deref_uint16(typingctx, data, offset):
sig = types.uint32(types.voidptr, types.intp)
return sig, make_deref_codegen(16)
@intrinsic
def deref_uint32(typingctx, data, offset):
sig = types.uint32(types.voidptr, types.intp)
return sig, make_deref_codegen(32)
@intrinsic
def _malloc_string(typingctx, kind, char_bytes, length, is_ascii):
"""make empty string with data buffer of size alloc_bytes.
Must set length and kind values for string after it is returned
"""
def details(context, builder, signature, args):
[kind_val, char_bytes_val, length_val, is_ascii_val] = args
# fill the struct
uni_str_ctor = cgutils.create_struct_proxy(types.unicode_type)
uni_str = uni_str_ctor(context, builder)
# add null padding character
nbytes_val = builder.mul(char_bytes_val,
builder.add(length_val,
Constant(length_val.type, 1)))
uni_str.meminfo = context.nrt.meminfo_alloc(builder, nbytes_val)
uni_str.kind = kind_val
uni_str.is_ascii = is_ascii_val
uni_str.length = length_val
# empty string has hash value -1 to indicate "need to compute hash"
uni_str.hash = context.get_constant(_Py_hash_t, -1)
uni_str.data = context.nrt.meminfo_data(builder, uni_str.meminfo)
# Set parent to NULL
uni_str.parent = cgutils.get_null_value(uni_str.parent.type)
return uni_str._getvalue()
sig = types.unicode_type(types.int32, types.intp, types.intp, types.uint32)
return sig, details
@register_jitable
def _empty_string(kind, length, is_ascii=0):
char_width = _kind_to_byte_width(kind)
s = _malloc_string(kind, char_width, length, is_ascii)
_set_code_point(s, length, np.uint32(0)) # Write NULL character
return s
# Disable RefCt for performance.
@register_jitable(_nrt=False)
def _get_code_point(a, i):
if a._kind == PY_UNICODE_1BYTE_KIND:
return deref_uint8(a._data, i)
elif a._kind == PY_UNICODE_2BYTE_KIND:
return deref_uint16(a._data, i)
elif a._kind == PY_UNICODE_4BYTE_KIND:
return deref_uint32(a._data, i)
else:
# there's also a wchar kind, but that's one of the above,
# so skipping for this example
return 0
####
def make_set_codegen(bitsize):
def codegen(context, builder, signature, args):
data, idx, ch = args
if bitsize < 32:
ch = builder.trunc(ch, IntType(bitsize))
ptr = builder.bitcast(data, IntType(bitsize).as_pointer())
builder.store(ch, builder.gep(ptr, [idx]))
return context.get_dummy_value()
return codegen
@intrinsic
def set_uint8(typingctx, data, idx, ch):
sig = types.void(types.voidptr, types.int64, types.uint32)
return sig, make_set_codegen(8)
@intrinsic
def set_uint16(typingctx, data, idx, ch):
sig = types.void(types.voidptr, types.int64, types.uint32)
return sig, make_set_codegen(16)
@intrinsic
def set_uint32(typingctx, data, idx, ch):
sig = types.void(types.voidptr, types.int64, types.uint32)
return sig, make_set_codegen(32)
@register_jitable(_nrt=False)
def _set_code_point(a, i, ch):
# WARNING: This method is very dangerous:
# * Assumes that data contents can be changed (only allowed for new
# strings)
# * Assumes that the kind of unicode string is sufficiently wide to
# accept ch. Will truncate ch to make it fit.
# * Assumes that i is within the valid boundaries of the function
if a._kind == PY_UNICODE_1BYTE_KIND:
set_uint8(a._data, i, ch)
elif a._kind == PY_UNICODE_2BYTE_KIND:
set_uint16(a._data, i, ch)
elif a._kind == PY_UNICODE_4BYTE_KIND:
set_uint32(a._data, i, ch)
else:
raise AssertionError(
"Unexpected unicode representation in _set_code_point")
if PYVERSION in ((3, 12), (3, 13)):
@register_jitable
def _pick_kind(kind1, kind2):
if kind1 == PY_UNICODE_1BYTE_KIND:
return kind2
elif kind1 == PY_UNICODE_2BYTE_KIND:
if kind2 == PY_UNICODE_4BYTE_KIND:
return kind2
else:
return kind1
elif kind1 == PY_UNICODE_4BYTE_KIND:
return kind1
else:
raise AssertionError(
"Unexpected unicode representation in _pick_kind")
elif PYVERSION in ((3, 10), (3, 11)):
@register_jitable
def _pick_kind(kind1, kind2):
if (kind1 == PY_UNICODE_WCHAR_KIND or kind2 == PY_UNICODE_WCHAR_KIND):
raise AssertionError("PY_UNICODE_WCHAR_KIND unsupported")
if kind1 == PY_UNICODE_1BYTE_KIND:
return kind2
elif kind1 == PY_UNICODE_2BYTE_KIND:
if kind2 == PY_UNICODE_4BYTE_KIND:
return kind2
else:
return kind1
elif kind1 == PY_UNICODE_4BYTE_KIND:
return kind1
else:
raise AssertionError(
"Unexpected unicode representation in _pick_kind")
else:
raise NotImplementedError(PYVERSION)
@register_jitable
def _pick_ascii(is_ascii1, is_ascii2):
if is_ascii1 == 1 and is_ascii2 == 1:
return types.uint32(1)
return types.uint32(0)
if PYVERSION in ((3, 12), (3, 13)):
@register_jitable
def _kind_to_byte_width(kind):
if kind == PY_UNICODE_1BYTE_KIND:
return 1
elif kind == PY_UNICODE_2BYTE_KIND:
return 2
elif kind == PY_UNICODE_4BYTE_KIND:
return 4
else:
raise AssertionError("Unexpected unicode encoding encountered")
elif PYVERSION in ((3, 10), (3, 11)):
@register_jitable
def _kind_to_byte_width(kind):
if kind == PY_UNICODE_1BYTE_KIND:
return 1
elif kind == PY_UNICODE_2BYTE_KIND:
return 2
elif kind == PY_UNICODE_4BYTE_KIND:
return 4
elif kind == PY_UNICODE_WCHAR_KIND:
raise AssertionError("PY_UNICODE_WCHAR_KIND unsupported")
else:
raise AssertionError("Unexpected unicode encoding encountered")
else:
raise NotImplementedError(PYVERSION)
@register_jitable(_nrt=False)
def _cmp_region(a, a_offset, b, b_offset, n):
if n == 0:
return 0
elif a_offset + n > a._length:
return -1
elif b_offset + n > b._length:
return 1
for i in range(n):
a_chr = _get_code_point(a, a_offset + i)
b_chr = _get_code_point(b, b_offset + i)
if a_chr < b_chr:
return -1
elif a_chr > b_chr:
return 1
return 0
@register_jitable
def _codepoint_to_kind(cp):
"""
Compute the minimum unicode kind needed to hold a given codepoint
"""
if cp < 256:
return PY_UNICODE_1BYTE_KIND
elif cp < 65536:
return PY_UNICODE_2BYTE_KIND
else:
# Maximum code point of Unicode 6.0: 0x10ffff (1,114,111)
MAX_UNICODE = 0x10ffff
if cp > MAX_UNICODE:
msg = "Invalid codepoint. Found value greater than Unicode maximum"
raise ValueError(msg)
return PY_UNICODE_4BYTE_KIND
@register_jitable
def _codepoint_is_ascii(ch):
"""
Returns true if a codepoint is in the ASCII range
"""
return ch < 128
# PUBLIC API
@overload(len)
def unicode_len(s):
if isinstance(s, types.UnicodeType):
def len_impl(s):
return s._length
return len_impl
@overload(operator.eq)
def unicode_eq(a, b):
if not (a.is_internal and b.is_internal):
return
if isinstance(a, types.Optional):
check_a = a.type
else:
check_a = a
if isinstance(b, types.Optional):
check_b = b.type
else:
check_b = b
accept = (types.UnicodeType, types.StringLiteral, types.UnicodeCharSeq)
a_unicode = isinstance(check_a, accept)
b_unicode = isinstance(check_b, accept)
if a_unicode and b_unicode:
def eq_impl(a, b):
# handle Optionals at runtime
a_none = a is None
b_none = b is None
if a_none or b_none:
if a_none and b_none:
return True
else:
return False
# the str() is for UnicodeCharSeq, it's a nop else
a = str(a)
b = str(b)
if len(a) != len(b):
return False
return _cmp_region(a, 0, b, 0, len(a)) == 0
return eq_impl
elif a_unicode ^ b_unicode:
# one of the things is unicode, everything compares False
def eq_impl(a, b):
return False
return eq_impl
@overload(operator.ne)
def unicode_ne(a, b):
if not (a.is_internal and b.is_internal):
return
accept = (types.UnicodeType, types.StringLiteral, types.UnicodeCharSeq)
a_unicode = isinstance(a, accept)
b_unicode = isinstance(b, accept)
if a_unicode and b_unicode:
def ne_impl(a, b):
return not (a == b)
return ne_impl
elif a_unicode ^ b_unicode:
# one of the things is unicode, everything compares True
def eq_impl(a, b):
return True
return eq_impl
@overload(operator.lt)
def unicode_lt(a, b):
a_unicode = isinstance(a, (types.UnicodeType, types.StringLiteral))
b_unicode = isinstance(b, (types.UnicodeType, types.StringLiteral))
if a_unicode and b_unicode:
def lt_impl(a, b):
minlen = min(len(a), len(b))
eqcode = _cmp_region(a, 0, b, 0, minlen)
if eqcode == -1:
return True
elif eqcode == 0:
return len(a) < len(b)
return False
return lt_impl
@overload(operator.gt)
def unicode_gt(a, b):
a_unicode = isinstance(a, (types.UnicodeType, types.StringLiteral))
b_unicode = isinstance(b, (types.UnicodeType, types.StringLiteral))
if a_unicode and b_unicode:
def gt_impl(a, b):
minlen = min(len(a), len(b))
eqcode = _cmp_region(a, 0, b, 0, minlen)
if eqcode == 1:
return True
elif eqcode == 0:
return len(a) > len(b)
return False
return gt_impl
@overload(operator.le)
def unicode_le(a, b):
a_unicode = isinstance(a, (types.UnicodeType, types.StringLiteral))
b_unicode = isinstance(b, (types.UnicodeType, types.StringLiteral))
if a_unicode and b_unicode:
def le_impl(a, b):
return not (a > b)
return le_impl
@overload(operator.ge)
def unicode_ge(a, b):
a_unicode = isinstance(a, (types.UnicodeType, types.StringLiteral))
b_unicode = isinstance(b, (types.UnicodeType, types.StringLiteral))
if a_unicode and b_unicode:
def ge_impl(a, b):
return not (a < b)
return ge_impl
@overload(operator.contains)
def unicode_contains(a, b):
if isinstance(a, types.UnicodeType) and isinstance(b, types.UnicodeType):
def contains_impl(a, b):
# note parameter swap: contains(a, b) == b in a
return _find(a, b) > -1
return contains_impl
def unicode_idx_check_type(ty, name):
"""Check object belongs to one of specific types
ty: type
Type of the object
name: str
Name of the object
"""
thety = ty
# if the type is omitted, the concrete type is the value
if isinstance(ty, types.Omitted):
thety = ty.value
# if the type is optional, the concrete type is the captured type
elif isinstance(ty, types.Optional):
thety = ty.type
accepted = (types.Integer, types.NoneType)
if thety is not None and not isinstance(thety, accepted):
raise TypingError('"{}" must be {}, not {}'.format(name, accepted, ty))
def unicode_sub_check_type(ty, name):
"""Check object belongs to unicode type"""
if not isinstance(ty, types.UnicodeType):
msg = '"{}" must be {}, not {}'.format(name, types.UnicodeType, ty)
raise TypingError(msg)
# FAST SEARCH algorithm implementation from cpython
@register_jitable
def _bloom_add(mask, ch):
mask |= (1 << (ch & (_BLOOM_WIDTH - 1)))
return mask
@register_jitable
def _bloom_check(mask, ch):
return mask & (1 << (ch & (_BLOOM_WIDTH - 1)))
# https://github.com/python/cpython/blob/1960eb005e04b7ad8a91018088cfdb0646bc1ca0/Objects/stringlib/fastsearch.h#L550 # noqa: E501
@register_jitable
def _default_find(data, substr, start, end):
"""Left finder."""
m = len(substr)
if m == 0:
return start
gap = mlast = m - 1
last = _get_code_point(substr, mlast)
zero = types.intp(0)
mask = _bloom_add(zero, last)
for i in range(mlast):
ch = _get_code_point(substr, i)
mask = _bloom_add(mask, ch)
if ch == last:
gap = mlast - i - 1
i = start
while i <= end - m:
ch = _get_code_point(data, mlast + i)
if ch == last:
j = 0
while j < mlast:
haystack_ch = _get_code_point(data, i + j)
needle_ch = _get_code_point(substr, j)
if haystack_ch != needle_ch:
break
j += 1
if j == mlast:
# got a match
return i
ch = _get_code_point(data, mlast + i + 1)
if _bloom_check(mask, ch) == 0:
i += m
else:
i += gap
else:
ch = _get_code_point(data, mlast + i + 1)
if _bloom_check(mask, ch) == 0:
i += m
i += 1
return -1
@register_jitable
def _default_rfind(data, substr, start, end):
"""Right finder."""
m = len(substr)
if m == 0:
return end
skip = mlast = m - 1
mfirst = _get_code_point(substr, 0)
mask = _bloom_add(0, mfirst)
i = mlast
while i > 0:
ch = _get_code_point(substr, i)
mask = _bloom_add(mask, ch)
if ch == mfirst:
skip = i - 1
i -= 1
i = end - m
while i >= start:
ch = _get_code_point(data, i)
if ch == mfirst:
j = mlast
while j > 0:
haystack_ch = _get_code_point(data, i + j)
needle_ch = _get_code_point(substr, j)
if haystack_ch != needle_ch:
break
j -= 1
if j == 0:
# got a match
return i
ch = _get_code_point(data, i - 1)
if i > start and _bloom_check(mask, ch) == 0:
i -= m
else:
i -= skip
else:
ch = _get_code_point(data, i - 1)
if i > start and _bloom_check(mask, ch) == 0:
i -= m
i -= 1
return -1
def generate_finder(find_func):
"""Generate finder either left or right."""
def impl(data, substr, start=None, end=None):
length = len(data)
sub_length = len(substr)
if start is None:
start = 0
if end is None:
end = length
start, end = _adjust_indices(length, start, end)
if end - start < sub_length:
return -1
return find_func(data, substr, start, end)
return impl
_find = register_jitable(generate_finder(_default_find))
_rfind = register_jitable(generate_finder(_default_rfind))
@overload_method(types.UnicodeType, 'find')
def unicode_find(data, substr, start=None, end=None):
"""Implements str.find()"""
if isinstance(substr, types.UnicodeCharSeq):
def find_impl(data, substr, start=None, end=None):
return data.find(str(substr))
return find_impl
unicode_idx_check_type(start, 'start')
unicode_idx_check_type(end, 'end')
unicode_sub_check_type(substr, 'substr')
return _find
@overload_method(types.UnicodeType, 'rfind')
def unicode_rfind(data, substr, start=None, end=None):
"""Implements str.rfind()"""
if isinstance(substr, types.UnicodeCharSeq):
def rfind_impl(data, substr, start=None, end=None):
return data.rfind(str(substr))
return rfind_impl
unicode_idx_check_type(start, 'start')
unicode_idx_check_type(end, 'end')
unicode_sub_check_type(substr, 'substr')
return _rfind
# https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Objects/unicodeobject.c#L12831-L12857 # noqa: E501
@overload_method(types.UnicodeType, 'rindex')
def unicode_rindex(s, sub, start=None, end=None):
"""Implements str.rindex()"""
unicode_idx_check_type(start, 'start')
unicode_idx_check_type(end, 'end')
unicode_sub_check_type(sub, 'sub')
def rindex_impl(s, sub, start=None, end=None):
result = s.rfind(sub, start, end)
if result < 0:
raise ValueError('substring not found')
return result
return rindex_impl
# https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Objects/unicodeobject.c#L11692-L11718 # noqa: E501
@overload_method(types.UnicodeType, 'index')
def unicode_index(s, sub, start=None, end=None):
"""Implements str.index()"""
unicode_idx_check_type(start, 'start')
unicode_idx_check_type(end, 'end')
unicode_sub_check_type(sub, 'sub')
def index_impl(s, sub, start=None, end=None):
result = s.find(sub, start, end)
if result < 0:
raise ValueError('substring not found')
return result
return index_impl
# https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Objects/unicodeobject.c#L12922-L12976 # noqa: E501
@overload_method(types.UnicodeType, 'partition')
def unicode_partition(data, sep):
"""Implements str.partition()"""
thety = sep
# if the type is omitted, the concrete type is the value
if isinstance(sep, types.Omitted):
thety = sep.value
# if the type is optional, the concrete type is the captured type
elif isinstance(sep, types.Optional):
thety = sep.type
accepted = (types.UnicodeType, types.UnicodeCharSeq)
if thety is not None and not isinstance(thety, accepted):
msg = '"{}" must be {}, not {}'.format('sep', accepted, sep)
raise TypingError(msg)
def impl(data, sep):
# https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Objects/stringlib/partition.h#L7-L60 # noqa: E501
sep = str(sep)
empty_str = _empty_string(data._kind, 0, data._is_ascii)
sep_length = len(sep)
if data._kind < sep._kind or len(data) < sep_length:
return data, empty_str, empty_str
if sep_length == 0:
raise ValueError('empty separator')
pos = data.find(sep)
if pos < 0:
return data, empty_str, empty_str
return data[0:pos], sep, data[pos + sep_length:len(data)]
return impl
@overload_method(types.UnicodeType, 'count')
def unicode_count(src, sub, start=None, end=None):
_count_args_types_check(start)
_count_args_types_check(end)
if isinstance(sub, types.UnicodeType):
def count_impl(src, sub, start=None, end=None):
count = 0
src_len = len(src)
sub_len = len(sub)
start = _normalize_slice_idx_count(start, src_len, 0)
end = _normalize_slice_idx_count(end, src_len, src_len)
if end - start < 0 or start > src_len:
return 0
src = src[start : end]
src_len = len(src)
start, end = 0, src_len
if sub_len == 0:
return src_len + 1
while (start + sub_len <= src_len):
if src[start : start + sub_len] == sub:
count += 1
start += sub_len
else:
start += 1
return count
return count_impl
error_msg = "The substring must be a UnicodeType, not {}"
raise TypingError(error_msg.format(type(sub)))
# https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Objects/unicodeobject.c#L12979-L13033 # noqa: E501
@overload_method(types.UnicodeType, 'rpartition')
def unicode_rpartition(data, sep):
"""Implements str.rpartition()"""
thety = sep
# if the type is omitted, the concrete type is the value
if isinstance(sep, types.Omitted):
thety = sep.value
# if the type is optional, the concrete type is the captured type
elif isinstance(sep, types.Optional):
thety = sep.type
accepted = (types.UnicodeType, types.UnicodeCharSeq)
if thety is not None and not isinstance(thety, accepted):
msg = '"{}" must be {}, not {}'.format('sep', accepted, sep)
raise TypingError(msg)
def impl(data, sep):
# https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Objects/stringlib/partition.h#L62-L115 # noqa: E501
sep = str(sep)
empty_str = _empty_string(data._kind, 0, data._is_ascii)
sep_length = len(sep)
if data._kind < sep._kind or len(data) < sep_length:
return empty_str, empty_str, data
if sep_length == 0:
raise ValueError('empty separator')
pos = data.rfind(sep)
if pos < 0:
return empty_str, empty_str, data
return data[0:pos], sep, data[pos + sep_length:len(data)]
return impl
# https://github.com/python/cpython/blob/201c8f79450628241574fba940e08107178dc3a5/Objects/unicodeobject.c#L9342-L9354 # noqa: E501
@register_jitable
def _adjust_indices(length, start, end):
if end > length:
end = length
if end < 0:
end += length
if end < 0:
end = 0
if start < 0:
start += length
if start < 0:
start = 0
return start, end
@overload_method(types.UnicodeType, 'startswith')
def unicode_startswith(s, prefix, start=None, end=None):
if not is_nonelike(start) and not isinstance(start, types.Integer):
raise TypingError(
"When specified, the arg 'start' must be an Integer or None")
if not is_nonelike(end) and not isinstance(end, types.Integer):
raise TypingError(
"When specified, the arg 'end' must be an Integer or None")
if isinstance(prefix, types.UniTuple) and \
isinstance(prefix.dtype, types.UnicodeType):
def startswith_tuple_impl(s, prefix, start=None, end=None):
for item in prefix:
if s.startswith(item, start, end):
return True
return False
return startswith_tuple_impl
elif isinstance(prefix, types.UnicodeCharSeq):
def startswith_char_seq_impl(s, prefix, start=None, end=None):
return s.startswith(str(prefix), start, end)
return startswith_char_seq_impl
elif isinstance(prefix, types.UnicodeType):
def startswith_unicode_impl(s, prefix, start=None, end=None):
length, prefix_length = len(s), len(prefix)
if start is None:
start = 0
if end is None:
end = length
start, end = _adjust_indices(length, start, end)
if end - start < prefix_length:
return False
if prefix_length == 0:
return True
s_slice = s[start:end]
return _cmp_region(s_slice, 0, prefix, 0, prefix_length) == 0