-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathlistobject.py
1543 lines (1238 loc) · 45.1 KB
/
listobject.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
"""
Compiler-side implementation of the Numba typed-list.
"""
import operator
from enum import IntEnum
from llvmlite import ir
from numba.core.extending import (
overload,
overload_method,
overload_attribute,
register_jitable,
intrinsic,
register_model,
models,
lower_builtin,
)
from numba.core.imputils import iternext_impl
from numba.core import types, cgutils, config
from numba.core.types import (
ListType,
ListTypeIterableType,
ListTypeIteratorType,
Type,
NoneType,
)
from numba.core.imputils import impl_ret_borrowed, RefType
from numba.core.errors import TypingError, NumbaTypeError
from numba.core import typing
from numba.typed.typedobjectutils import (_as_bytes, _cast, _nonoptional,
_get_incref_decref,
_container_get_data,
_container_get_meminfo,)
from numba.cpython import listobj
ll_list_type = cgutils.voidptr_t
ll_listiter_type = cgutils.voidptr_t
ll_voidptr_type = cgutils.voidptr_t
ll_status = cgutils.int32_t
ll_ssize_t = cgutils.intp_t
ll_bytes = cgutils.voidptr_t
_meminfo_listptr = types.MemInfoPointer(types.voidptr)
if config.USE_LEGACY_TYPE_SYSTEM:
INDEXTY = types.intp
index_types = types.integer_domain
else:
INDEXTY = types.py_int
index_types = types.py_integer_domain
DEFAULT_ALLOCATED = 0
@register_model(ListType)
class ListModel(models.StructModel):
def __init__(self, dmm, fe_type):
members = [
('meminfo', _meminfo_listptr),
('data', types.voidptr), # ptr to the C list
]
super(ListModel, self).__init__(dmm, fe_type, members)
@register_model(ListTypeIterableType)
@register_model(ListTypeIteratorType)
class ListIterModel(models.StructModel):
def __init__(self, dmm, fe_type):
members = [
('size', types.intp), # the size of the iteration space
('parent', fe_type.parent), # the parent list
('index', types.EphemeralPointer(types.intp)), # current index
]
super(ListIterModel, self).__init__(dmm, fe_type, members)
class ListStatus(IntEnum):
"""Status code for other list operations.
"""
LIST_OK = 0,
LIST_ERR_INDEX = -1
LIST_ERR_NO_MEMORY = -2
LIST_ERR_MUTATED = -3
LIST_ERR_ITER_EXHAUSTED = -4
LIST_ERR_IMMUTABLE = -5
class ErrorHandler(object):
"""ErrorHandler for calling codegen functions from this file.
Stores the state needed to raise an exception from nopython mode.
"""
def __init__(self, context):
self.context = context
def __call__(self, builder, status, msg):
ok_status = status.type(int(ListStatus.LIST_OK))
with builder.if_then(builder.icmp_signed('!=', status, ok_status),
likely=True):
self.context.call_conv.return_user_exc(
builder, RuntimeError, (msg,))
def _check_for_none_typed(lst, method):
if isinstance(lst.dtype, NoneType):
raise TypingError("method support for List[None] is limited, "
"not supported: '{}'.".format(method))
@intrinsic
def _as_meminfo(typingctx, lstobj):
"""Returns the MemInfoPointer of a list.
"""
if not isinstance(lstobj, types.ListType):
raise TypingError('expected *lstobj* to be a ListType')
def codegen(context, builder, sig, args):
[tl] = sig.args
[l] = args
# Incref
context.nrt.incref(builder, tl, l)
ctor = cgutils.create_struct_proxy(tl)
lstruct = ctor(context, builder, value=l)
# Returns the plain MemInfo
return lstruct.meminfo
sig = _meminfo_listptr(lstobj)
return sig, codegen
@intrinsic
def _from_meminfo(typingctx, mi, listtyperef):
"""Recreate a list from a MemInfoPointer
"""
if mi != _meminfo_listptr:
raise TypingError('expected a MemInfoPointer for list.')
listtype = listtyperef.instance_type
if not isinstance(listtype, ListType):
raise TypingError('expected a {}'.format(ListType))
def codegen(context, builder, sig, args):
[tmi, tdref] = sig.args
td = tdref.instance_type
[mi, _] = args
ctor = cgutils.create_struct_proxy(td)
dstruct = ctor(context, builder)
data_pointer = context.nrt.meminfo_data(builder, mi)
data_pointer = builder.bitcast(data_pointer, ll_list_type.as_pointer())
dstruct.data = builder.load(data_pointer)
dstruct.meminfo = mi
return impl_ret_borrowed(
context,
builder,
listtype,
dstruct._getvalue(),
)
sig = listtype(mi, listtyperef)
return sig, codegen
def _list_codegen_set_method_table(context, builder, lp, itemty):
vtablety = ir.LiteralStructType([
ll_voidptr_type, # item incref
ll_voidptr_type, # item decref
])
setmethod_fnty = ir.FunctionType(
ir.VoidType(),
[ll_list_type, vtablety.as_pointer()]
)
setmethod_fn = cgutils.get_or_insert_function(
builder.module,
setmethod_fnty,
'numba_list_set_method_table')
vtable = cgutils.alloca_once(builder, vtablety, zfill=True)
# install item incref/decref
item_incref_ptr = cgutils.gep_inbounds(builder, vtable, 0, 0)
item_decref_ptr = cgutils.gep_inbounds(builder, vtable, 0, 1)
dm_item = context.data_model_manager[itemty]
if dm_item.contains_nrt_meminfo():
item_incref, item_decref = _get_incref_decref(
context, builder.module, dm_item, "list"
)
builder.store(
builder.bitcast(item_incref, item_incref_ptr.type.pointee),
item_incref_ptr,
)
builder.store(
builder.bitcast(item_decref, item_decref_ptr.type.pointee),
item_decref_ptr,
)
builder.call(setmethod_fn, [lp, vtable])
@intrinsic
def _list_set_method_table(typingctx, lp, itemty):
"""Wrap numba_list_set_method_table
"""
resty = types.void
sig = resty(lp, itemty)
def codegen(context, builder, sig, args):
_list_codegen_set_method_table(
context, builder, args[0], itemty.instance_type)
return sig, codegen
@lower_builtin(operator.is_, types.ListType, types.ListType)
def list_is(context, builder, sig, args):
a_meminfo = _container_get_meminfo(context, builder, sig.args[0], args[0])
b_meminfo = _container_get_meminfo(context, builder, sig.args[1], args[1])
ma = builder.ptrtoint(a_meminfo, cgutils.intp_t)
mb = builder.ptrtoint(b_meminfo, cgutils.intp_t)
return builder.icmp_signed('==', ma, mb)
def _call_list_free(context, builder, ptr):
"""Call numba_list_free(ptr)
"""
fnty = ir.FunctionType(
ir.VoidType(),
[ll_list_type],
)
free = cgutils.get_or_insert_function(builder.module, fnty,
'numba_list_free')
builder.call(free, [ptr])
# FIXME: this needs a careful review
def _imp_dtor(context, module):
"""Define the dtor for list
"""
llvoidptr = context.get_value_type(types.voidptr)
llsize = context.get_value_type(types.uintp)
fnty = ir.FunctionType(
ir.VoidType(),
[llvoidptr, llsize, llvoidptr],
)
fname = '_numba_list_dtor'
fn = cgutils.get_or_insert_function(module, fnty, fname)
if fn.is_declaration:
# Set linkage
fn.linkage = 'linkonce_odr'
# Define
builder = ir.IRBuilder(fn.append_basic_block())
lp = builder.bitcast(fn.args[0], ll_list_type.as_pointer())
l = builder.load(lp)
_call_list_free(context, builder, l)
builder.ret_void()
return fn
def new_list(item, allocated=DEFAULT_ALLOCATED):
"""Construct a new list. (Not implemented in the interpreter yet)
Parameters
----------
item: TypeRef
Item type of the new list.
allocated: int
number of items to pre-allocate
"""
# With JIT disabled, ignore all arguments and return a Python list.
return list()
def _add_meminfo(context, builder, lstruct):
alloc_size = context.get_abi_sizeof(
context.get_value_type(types.voidptr),
)
dtor = _imp_dtor(context, builder.module)
meminfo = context.nrt.meminfo_alloc_dtor(
builder,
context.get_constant(types.uintp, alloc_size),
dtor,
)
data_pointer = context.nrt.meminfo_data(builder, meminfo)
data_pointer = builder.bitcast(data_pointer, ll_list_type.as_pointer())
builder.store(lstruct.data, data_pointer)
lstruct.meminfo = meminfo
@intrinsic
def _make_list(typingctx, itemty, ptr):
"""Make a list struct with the given *ptr*
Parameters
----------
itemty: Type
Type of the item.
ptr : llvm pointer value
Points to the list object.
"""
list_ty = types.ListType(itemty.instance_type)
def codegen(context, builder, signature, args):
ptr = args[1]
ctor = cgutils.create_struct_proxy(list_ty)
lstruct = ctor(context, builder)
lstruct.data = ptr
_add_meminfo(context, builder, lstruct)
return lstruct._getvalue()
sig = list_ty(itemty, ptr)
return sig, codegen
def _list_new_codegen(context, builder, itemty, new_size, error_handler):
fnty = ir.FunctionType(
ll_status,
[ll_list_type.as_pointer(), ll_ssize_t, ll_ssize_t],
)
fn = cgutils.get_or_insert_function(builder.module, fnty, 'numba_list_new')
# Determine sizeof item types
ll_item = context.get_data_type(itemty)
sz_item = context.get_abi_sizeof(ll_item)
reflp = cgutils.alloca_once(builder, ll_list_type, zfill=True)
status = builder.call(
fn,
[reflp, ll_ssize_t(sz_item), new_size],
)
msg = "Failed to allocate list"
error_handler(
builder,
status,
msg,
)
lp = builder.load(reflp)
return lp
@intrinsic
def _list_new(typingctx, itemty, allocated):
"""Wrap numba_list_new.
Allocate a new list object with zero capacity.
Parameters
----------
itemty: Type
Type of the items
allocated: int
number of items to pre-allocate
"""
resty = types.voidptr
sig = resty(itemty, allocated)
def codegen(context, builder, sig, args):
error_handler = ErrorHandler(context)
return _list_new_codegen(context,
builder,
itemty.instance_type,
args[1],
error_handler,
)
return sig, codegen
@overload(new_list)
def impl_new_list(item, allocated=DEFAULT_ALLOCATED):
"""Creates a new list.
Parameters
----------
item: Numba type
type of the list item.
allocated: int
number of items to pre-allocate
"""
if not isinstance(item, Type):
raise NumbaTypeError("expecting *item* to be a Numba Type")
itemty = item
def imp(item, allocated=DEFAULT_ALLOCATED):
if allocated < 0:
raise RuntimeError("expecting *allocated* to be >= 0")
lp = _list_new(itemty, allocated)
_list_set_method_table(lp, itemty)
l = _make_list(itemty, lp)
return l
return imp
@overload(len)
def impl_len(l):
"""len(list)
"""
if isinstance(l, types.ListType):
def impl(l):
return _list_length(l)
return impl
@intrinsic
def _list_length(typingctx, l):
"""Wrap numba_list_length
Returns the length of the list.
"""
sig = types.intp(l)
def codegen(context, builder, sig, args):
[tl] = sig.args
[l] = args
fnty = ir.FunctionType(
ll_ssize_t,
[ll_list_type],
)
fname = 'numba_list_size_address'
fn = cgutils.get_or_insert_function(builder.module, fnty, fname)
fn.attributes.add('alwaysinline')
fn.attributes.add('readonly')
fn.attributes.add('nounwind')
lp = _container_get_data(context, builder, tl, l)
len_addr = builder.call(fn, [lp,],)
ptr = builder.inttoptr(len_addr, cgutils.intp_t.as_pointer())
return builder.load(ptr)
return sig, codegen
@overload_method(types.ListType, "_allocated")
def impl_allocated(l):
"""list._allocated()
"""
if isinstance(l, types.ListType):
def impl(l):
return _list_allocated(l)
return impl
@intrinsic
def _list_allocated(typingctx, l):
"""Wrap numba_list_allocated
Returns the allocation of the list.
"""
resty = types.intp
sig = resty(l)
def codegen(context, builder, sig, args):
fnty = ir.FunctionType(
ll_ssize_t,
[ll_list_type],
)
fn = cgutils.get_or_insert_function(builder.module, fnty,
'numba_list_allocated')
[l] = args
[tl] = sig.args
lp = _container_get_data(context, builder, tl, l)
n = builder.call(fn, [lp])
return n
return sig, codegen
@overload_method(types.ListType, "_is_mutable")
def impl_is_mutable(l):
"""list._is_mutable()"""
if isinstance(l, types.ListType):
def impl(l):
return bool(_list_is_mutable(l))
return impl
@intrinsic
def _list_is_mutable(typingctx, l):
"""Wrap numba_list_is_mutable
Returns the state of the is_mutable member
"""
resty = types.int32
sig = resty(l)
def codegen(context, builder, sig, args):
fnty = ir.FunctionType(
ll_status,
[ll_list_type],
)
fn = cgutils.get_or_insert_function(builder.module, fnty,
'numba_list_is_mutable')
[l] = args
[tl] = sig.args
lp = _container_get_data(context, builder, tl, l)
n = builder.call(fn, [lp])
return n
return sig, codegen
@overload_method(types.ListType, "_make_mutable")
def impl_make_mutable(l):
"""list._make_mutable()"""
if isinstance(l, types.ListType):
def impl(l):
_list_set_is_mutable(l, 1)
return impl
@overload_method(types.ListType, "_make_immutable")
def impl_make_immutable(l):
"""list._make_immutable()"""
if isinstance(l, types.ListType):
def impl(l):
_list_set_is_mutable(l, 0)
return impl
@intrinsic
def _list_set_is_mutable(typingctx, l, is_mutable):
"""Wrap numba_list_set_mutable
Sets the state of the is_mutable member.
"""
resty = types.void
sig = resty(l, is_mutable)
def codegen(context, builder, sig, args):
fnty = ir.FunctionType(
ir.VoidType(),
[ll_list_type, cgutils.intp_t],
)
fn = cgutils.get_or_insert_function(builder.module, fnty,
'numba_list_set_is_mutable')
[l, i] = args
[tl, ti] = sig.args
lp = _container_get_data(context, builder, tl, l)
builder.call(fn, [lp, i])
return sig, codegen
@intrinsic
def _list_append(typingctx, l, item):
"""Wrap numba_list_append
"""
resty = types.int32
sig = resty(l, l.item_type)
def codegen(context, builder, sig, args):
fnty = ir.FunctionType(
ll_status,
[ll_list_type, ll_bytes],
)
[l, item] = args
[tl, titem] = sig.args
fn = cgutils.get_or_insert_function(builder.module, fnty,
'numba_list_append')
dm_item = context.data_model_manager[titem]
data_item = dm_item.as_data(builder, item)
ptr_item = cgutils.alloca_once_value(builder, data_item)
lp = _container_get_data(context, builder, tl, l)
status = builder.call(
fn,
[
lp,
_as_bytes(builder, ptr_item),
],
)
return status
return sig, codegen
@overload_method(types.ListType, 'append')
def impl_append(l, item):
if not isinstance(l, types.ListType):
return
itemty = l.item_type
def impl(l, item):
casteditem = _cast(item, itemty)
status = _list_append(l, casteditem)
if status == ListStatus.LIST_OK:
return
elif status == ListStatus.LIST_ERR_IMMUTABLE:
raise ValueError('list is immutable')
elif status == ListStatus.LIST_ERR_NO_MEMORY:
raise MemoryError('Unable to allocate memory to append item')
else:
raise RuntimeError('list.append failed unexpectedly')
if l.is_precise():
# Handle the precise case.
return impl
else:
# Handle the imprecise case.
l = l.refine(item)
# Re-bind the item type to match the arguments.
itemty = l.item_type
# Create the signature that we wanted this impl to have.
sig = typing.signature(types.void, l, itemty)
return sig, impl
@intrinsic
def fix_index(tyctx, list_ty, index_ty):
sig = types.intp(list_ty, index_ty)
def codegen(context, builder, sig, args):
[list_ty, index_ty] = sig.args
[ll_list, ll_idx] = args
is_negative = builder.icmp_signed('<', ll_idx,
ir.Constant(ll_idx.type, 0))
fast_len_sig, length_fn = _list_length._defn(context.typing_context,
list_ty)
length = length_fn(context, builder, fast_len_sig, (ll_list,))
# length is an intp
# index can be any sort of int
# indexing in general is done with a ssize_t which correlates to an
# intp. In llvmlite sext and trunc are guarded to return the value
# itself if the types are the same, so there's no need to handle the
# "equal widths" case separately. This sexts/truncs the index to the
# length type such that `add` works for the wraparound case.
st = 'sext' if ll_idx.type.width < length.type.width else 'trunc'
op = getattr(builder, st)
fixedup_idx = op(ll_idx, length.type)
wrapped_index = builder.add(fixedup_idx, length)
return builder.select(is_negative, wrapped_index, fixedup_idx)
return sig, codegen
@register_jitable
def handle_index(l, index):
"""Handle index.
If the index is negative, convert it. If the index is out of range, raise
an IndexError.
"""
# convert negative indices to positive ones
index = fix_index(l, index)
# check that the index is in range
if index < 0 or index >= len(l):
raise IndexError("list index out of range")
return index
@register_jitable
def handle_slice(l, s):
"""Handle slice.
Convert a slice object for a given list into a range object that can be
used to index the list. Many subtle caveats here, especially if the step is
negative.
"""
if len(l) == 0: # ignore slice for empty list
return range(0)
ll, sa, so, se = len(l), s.start, s.stop, s.step
if se > 0:
start = max(ll + sa, 0) if s.start < 0 else min(ll, sa)
stop = max(ll + so, 0) if so < 0 else min(ll, so)
elif se < 0:
start = max(ll + sa, -1) if s.start < 0 else min(ll - 1, sa)
stop = max(ll + so, -1) if so < 0 else min(ll, so)
else:
# should be caught earlier, but isn't, so we raise here
raise ValueError("slice step cannot be zero")
return range(start, stop, s.step)
def _gen_getitem(borrowed):
@intrinsic
def impl(typingctx, l_ty, index_ty):
is_none = isinstance(l_ty.item_type, types.NoneType)
if is_none:
resty = types.Tuple([types.int32, l_ty.item_type])
else:
resty = types.Tuple([types.int32, types.Optional(l_ty.item_type)])
sig = resty(l_ty, index_ty)
def codegen(context, builder, sig, args):
[tl, tindex] = sig.args
[l, index] = args
fnty = ir.FunctionType(
ll_voidptr_type,
[ll_list_type],
)
fname = 'numba_list_base_ptr'
fn = cgutils.get_or_insert_function(builder.module, fnty, fname)
fn.attributes.add('alwaysinline')
fn.attributes.add('nounwind')
fn.attributes.add('readonly')
lp = _container_get_data(context, builder, tl, l)
base_ptr = builder.call(
fn,
[lp,],
)
llty = context.get_data_type(tl.item_type)
casted_base_ptr = builder.bitcast(base_ptr, llty.as_pointer())
item_ptr = cgutils.gep(builder, casted_base_ptr, index)
if is_none:
out = builder.load(item_ptr)
else:
out = context.make_optional_none(builder, tl.item_type)
pout = cgutils.alloca_once_value(builder, out)
dm_item = context.data_model_manager[tl.item_type]
item = dm_item.load_from_data_pointer(builder, item_ptr)
if not borrowed:
context.nrt.incref(builder, tl.item_type, item)
if is_none:
loaded = item
else:
loaded = context.make_optional_value(builder, tl.item_type,
item)
builder.store(loaded, pout)
out = builder.load(pout)
return context.make_tuple(builder, resty, [ll_status(0), out])
return sig, codegen
return impl
_list_getitem = _gen_getitem(False)
_list_getitem_borrowed = _gen_getitem(True)
@overload(operator.getitem)
def impl_getitem(l, index):
if not isinstance(l, types.ListType):
return
indexty = INDEXTY
itemty = l.item_type
IS_NOT_NONE = not isinstance(l.item_type, types.NoneType)
if index in index_types:
if IS_NOT_NONE:
def integer_non_none_impl(l, index):
castedindex = _cast(index, indexty)
handledindex = handle_index(l, castedindex)
status, item = _list_getitem(l, handledindex)
if status == ListStatus.LIST_OK:
return _nonoptional(item)
else:
raise AssertionError("internal list error during getitem")
return integer_non_none_impl
else:
def integer_none_impl(l, index):
index = handle_index(l, index)
return None
return integer_none_impl
elif isinstance(index, types.SliceType):
def slice_impl(l, index):
newl = new_list(itemty)
for i in handle_slice(l, index):
newl.append(l[i])
return newl
return slice_impl
else:
raise TypingError("list indices must be integers or slices")
@intrinsic
def _list_setitem(typingctx, l, index, item):
"""Wrap numba_list_setitem
"""
resty = types.int32
sig = resty(l, index, item)
def codegen(context, builder, sig, args):
fnty = ir.FunctionType(
ll_status,
[ll_list_type, ll_ssize_t, ll_bytes],
)
[l, index, item] = args
[tl, tindex, titem] = sig.args
fn = cgutils.get_or_insert_function(builder.module, fnty,
'numba_list_setitem')
dm_item = context.data_model_manager[titem]
data_item = dm_item.as_data(builder, item)
ptr_item = cgutils.alloca_once_value(builder, data_item)
lp = _container_get_data(context, builder, tl, l)
status = builder.call(
fn,
[
lp,
index,
_as_bytes(builder, ptr_item),
],
)
return status
return sig, codegen
@overload(operator.setitem)
def impl_setitem(l, index, item):
if not isinstance(l, types.ListType):
return
indexty = INDEXTY
itemty = l.item_type
if index in index_types:
def impl_integer(l, index, item):
index = handle_index(l, index)
castedindex = _cast(index, indexty)
casteditem = _cast(item, itemty)
status = _list_setitem(l, castedindex, casteditem)
if status == ListStatus.LIST_OK:
return
elif status == ListStatus.LIST_ERR_IMMUTABLE:
raise ValueError("list is immutable")
else:
raise AssertionError("internal list error during settitem")
return impl_integer
elif isinstance(index, types.SliceType):
if not isinstance(item, types.IterableType):
raise TypingError("can only assign an iterable when using a slice "
"with assignment/setitem")
def impl_slice(l, index, item):
if not l._is_mutable():
raise ValueError("list is immutable")
# special case "a[i:j] = a", need to copy first
if l is item:
item = item.copy()
slice_range = handle_slice(l, index)
# non-extended (simple) slices
if slice_range.step == 1:
# replace
if len(item) == len(slice_range):
for i, j in zip(slice_range, item):
l[i] = j
# replace and insert
if len(item) > len(slice_range):
# do the replaces we can
for i, j in zip(slice_range, item[:len(slice_range)]):
l[i] = j
# insert the remaining ones
insert_range = range(slice_range.stop,
slice_range.stop +
len(item) - len(slice_range))
for i, k in zip(insert_range, item[len(slice_range):]):
# FIXME: This may be slow. Each insert can incur a
# memory copy of one or more items.
l.insert(i, k)
# replace and delete
if len(item) < len(slice_range):
# do the replaces we can
replace_range = range(slice_range.start,
slice_range.start + len(item))
for i,j in zip(replace_range, item):
l[i] = j
# delete remaining ones
del l[slice_range.start + len(item):slice_range.stop]
# Extended slices
else:
if len(slice_range) != len(item):
raise ValueError("length mismatch for extended slice "
"and sequence")
# extended slice can only replace
for i, j in zip(slice_range, item):
l[i] = j
return impl_slice
else:
raise TypingError("list indices must be integers or slices")
@overload_method(types.ListType, 'pop')
def impl_pop(l, index=-1):
if not isinstance(l, types.ListType):
return
_check_for_none_typed(l, 'pop')
indexty = INDEXTY
# FIXME: this type check works, but it isn't clear why and if it optimal
if (isinstance(index, int)
or index in index_types
or isinstance(index, types.Omitted)):
def impl(l, index=-1):
if len(l) == 0:
raise IndexError("pop from empty list")
cindex = _cast(handle_index(l, index), indexty)
item = l[cindex]
del l[cindex]
return item
return impl
else:
raise TypingError("argument for pop must be an integer")
@intrinsic
def _list_delitem(typingctx, l, index):
resty = types.int32
sig = resty(l, index)
def codegen(context, builder, sig, args):
fnty = ir.FunctionType(
ll_status,
[ll_list_type, ll_ssize_t],
)
[tl, tindex] = sig.args
[l, index] = args
fn = cgutils.get_or_insert_function(builder.module, fnty,
'numba_list_delitem')
lp = _container_get_data(context, builder, tl, l)
status = builder.call(fn, [lp, index])
return status
return sig, codegen
@intrinsic
def _list_delete_slice(typingctx, l, start, stop, step):
"""Wrap numba_list_delete_slice
"""
resty = types.int32
sig = resty(l, start, stop, step)
def codegen(context, builder, sig, args):
fnty = ir.FunctionType(
ll_status,
[ll_list_type, ll_ssize_t, ll_ssize_t, ll_ssize_t],
)
[l, start, stop, step] = args
[tl, tstart, tstop, tstep] = sig.args
fn = cgutils.get_or_insert_function(builder.module, fnty,
'numba_list_delete_slice')
lp = _container_get_data(context, builder, tl, l)
status = builder.call(
fn,
[
lp,
start,
stop,
step,
],
)
return status
return sig, codegen
@overload(operator.delitem)
def impl_delitem(l, index):
if not isinstance(l, types.ListType):
return
_check_for_none_typed(l, 'delitem')
if index in index_types:
def integer_impl(l, index):