-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathdictobject.py
1367 lines (1082 loc) · 40 KB
/
dictobject.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 dictionary.
"""
import ctypes
import operator
from enum import IntEnum
from llvmlite import ir
from numba import _helperlib
from numba.core.extending import (
overload,
overload_method,
overload_attribute,
intrinsic,
register_model,
models,
lower_builtin,
lower_cast,
make_attribute_wrapper,
)
from numba.core.imputils import iternext_impl, impl_ret_untracked
from numba.core import types, cgutils
from numba.core.types import (
DictType,
DictItemsIterableType,
DictKeysIterableType,
DictValuesIterableType,
DictIteratorType,
Type,
)
from numba.core.imputils import impl_ret_borrowed, RefType
from numba.core.errors import TypingError, LoweringError, NumbaTypeError
from numba.core import typing
from numba.typed.typedobjectutils import (_as_bytes, _cast, _nonoptional,
_sentry_safe_cast_default,
_get_incref_decref,
_get_equal, _container_get_data,)
ll_dict_type = cgutils.voidptr_t
ll_dictiter_type = cgutils.voidptr_t
ll_voidptr_type = cgutils.voidptr_t
ll_status = cgutils.int32_t
ll_ssize_t = cgutils.intp_t
ll_hash = ll_ssize_t
ll_bytes = cgutils.voidptr_t
_meminfo_dictptr = types.MemInfoPointer(types.voidptr)
# The following enums must match _dictobject.c
class DKIX(IntEnum):
"""Special return value of dict lookup.
"""
EMPTY = -1
class Status(IntEnum):
"""Status code for other dict operations.
"""
OK = 0
OK_REPLACED = 1
ERR_NO_MEMORY = -1
ERR_DICT_MUTATED = -2
ERR_ITER_EXHAUSTED = -3
ERR_DICT_EMPTY = -4
ERR_CMP_FAILED = -5
def new_dict(key, value, n_keys=0):
"""Construct a new dict with enough space for *n_keys* without a resize.
Parameters
----------
key, value : TypeRef
Key type and value type of the new dict.
n_keys : int, default 0
The number of keys to insert without needing a resize.
A value of 0 creates a dict with minimum size.
"""
# With JIT disabled, ignore all arguments and return a Python dict.
return dict()
@register_model(DictType)
class DictModel(models.StructModel):
def __init__(self, dmm, fe_type):
members = [
('meminfo', _meminfo_dictptr),
('data', types.voidptr), # ptr to the C dict
]
super(DictModel, self).__init__(dmm, fe_type, members)
@register_model(DictItemsIterableType)
@register_model(DictKeysIterableType)
@register_model(DictValuesIterableType)
@register_model(DictIteratorType)
class DictIterModel(models.StructModel):
def __init__(self, dmm, fe_type):
members = [
('parent', fe_type.parent), # reference to the dict
('state', types.voidptr), # iterator state in C code
]
super(DictIterModel, self).__init__(dmm, fe_type, members)
# Make _parent available to make len simple
make_attribute_wrapper(DictItemsIterableType, "parent", "_parent")
make_attribute_wrapper(DictKeysIterableType, "parent", "_parent")
make_attribute_wrapper(DictValuesIterableType, "parent", "_parent")
def _raise_if_error(context, builder, status, msg):
"""Raise an internal error depending on the value of *status*
"""
ok_status = status.type(int(Status.OK))
with builder.if_then(builder.icmp_signed('!=', status, ok_status)):
context.call_conv.return_user_exc(builder, RuntimeError, (msg,))
@intrinsic
def _as_meminfo(typingctx, dctobj):
"""Returns the MemInfoPointer of a dictionary.
"""
if not isinstance(dctobj, types.DictType):
raise TypingError('expected *dctobj* to be a DictType')
def codegen(context, builder, sig, args):
[td] = sig.args
[d] = args
# Incref
context.nrt.incref(builder, td, d)
ctor = cgutils.create_struct_proxy(td)
dstruct = ctor(context, builder, value=d)
# Returns the plain MemInfo
return dstruct.meminfo
sig = _meminfo_dictptr(dctobj)
return sig, codegen
@intrinsic
def _from_meminfo(typingctx, mi, dicttyperef):
"""Recreate a dictionary from a MemInfoPointer
"""
if mi != _meminfo_dictptr:
raise TypingError('expected a MemInfoPointer for dict.')
dicttype = dicttyperef.instance_type
if not isinstance(dicttype, DictType):
raise TypingError('expected a {}'.format(DictType))
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_dict_type.as_pointer())
dstruct.data = builder.load(data_pointer)
dstruct.meminfo = mi
return impl_ret_borrowed(
context,
builder,
dicttype,
dstruct._getvalue(),
)
sig = dicttype(mi, dicttyperef)
return sig, codegen
def _call_dict_free(context, builder, ptr):
"""Call numba_dict_free(ptr)
"""
fnty = ir.FunctionType(
ir.VoidType(),
[ll_dict_type],
)
free = cgutils.get_or_insert_function(builder.module, fnty,
'numba_dict_free')
builder.call(free, [ptr])
def _imp_dtor(context, module):
"""Define the dtor for dictionary
"""
llvoidptr = context.get_value_type(types.voidptr)
llsize = context.get_value_type(types.uintp)
fnty = ir.FunctionType(
ir.VoidType(),
[llvoidptr, llsize, llvoidptr],
)
fname = '_numba_dict_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())
dp = builder.bitcast(fn.args[0], ll_dict_type.as_pointer())
d = builder.load(dp)
_call_dict_free(context, builder, d)
builder.ret_void()
return fn
@intrinsic
def _dict_new_sized(typingctx, n_keys, keyty, valty):
"""Wrap numba_dict_new_sized.
Allocate a new dictionary object with enough space to hold
*n_keys* keys without needing a resize.
Parameters
----------
keyty, valty: Type
Type of the key and value, respectively.
n_keys: int
The number of keys to insert without needing a resize.
A value of 0 creates a dict with minimum size.
"""
resty = types.voidptr
sig = resty(n_keys, keyty, valty)
def codegen(context, builder, sig, args):
n_keys = builder.bitcast(args[0], ll_ssize_t)
# Determine sizeof key and value types
ll_key = context.get_data_type(keyty.instance_type)
ll_val = context.get_data_type(valty.instance_type)
sz_key = context.get_abi_sizeof(ll_key)
sz_val = context.get_abi_sizeof(ll_val)
refdp = cgutils.alloca_once(builder, ll_dict_type, zfill=True)
argtys = [ll_dict_type.as_pointer(), ll_ssize_t, ll_ssize_t, ll_ssize_t]
fnty = ir.FunctionType(ll_status, argtys)
fn = ir.Function(builder.module, fnty, 'numba_dict_new_sized')
args = [refdp, n_keys, ll_ssize_t(sz_key), ll_ssize_t(sz_val)]
status = builder.call(fn, args)
allocated_failed_msg = "Failed to allocate dictionary"
_raise_if_error(context, builder, status, msg=allocated_failed_msg)
dp = builder.load(refdp)
return dp
return sig, codegen
@intrinsic
def _dict_set_method_table(typingctx, dp, keyty, valty):
"""Wrap numba_dict_set_method_table
"""
resty = types.void
sig = resty(dp, keyty, valty)
def codegen(context, builder, sig, args):
vtablety = ir.LiteralStructType([
ll_voidptr_type, # equal
ll_voidptr_type, # key incref
ll_voidptr_type, # key decref
ll_voidptr_type, # val incref
ll_voidptr_type, # val decref
])
setmethod_fnty = ir.FunctionType(
ir.VoidType(),
[ll_dict_type, vtablety.as_pointer()]
)
setmethod_fn = ir.Function(
builder.module,
setmethod_fnty,
name='numba_dict_set_method_table',
)
dp = args[0]
vtable = cgutils.alloca_once(builder, vtablety, zfill=True)
# install key incref/decref
key_equal_ptr = cgutils.gep_inbounds(builder, vtable, 0, 0)
key_incref_ptr = cgutils.gep_inbounds(builder, vtable, 0, 1)
key_decref_ptr = cgutils.gep_inbounds(builder, vtable, 0, 2)
val_incref_ptr = cgutils.gep_inbounds(builder, vtable, 0, 3)
val_decref_ptr = cgutils.gep_inbounds(builder, vtable, 0, 4)
dm_key = context.data_model_manager[keyty.instance_type]
if dm_key.contains_nrt_meminfo():
equal = _get_equal(context, builder.module, dm_key, 'dict_key')
key_incref, key_decref = _get_incref_decref(
context, builder.module, dm_key, 'dict_key'
)
builder.store(
builder.bitcast(equal, key_equal_ptr.type.pointee),
key_equal_ptr,
)
builder.store(
builder.bitcast(key_incref, key_incref_ptr.type.pointee),
key_incref_ptr,
)
builder.store(
builder.bitcast(key_decref, key_decref_ptr.type.pointee),
key_decref_ptr,
)
dm_val = context.data_model_manager[valty.instance_type]
if dm_val.contains_nrt_meminfo():
val_incref, val_decref = _get_incref_decref(
context, builder.module, dm_val, 'dict_value'
)
builder.store(
builder.bitcast(val_incref, val_incref_ptr.type.pointee),
val_incref_ptr,
)
builder.store(
builder.bitcast(val_decref, val_decref_ptr.type.pointee),
val_decref_ptr,
)
builder.call(setmethod_fn, [dp, vtable])
return sig, codegen
@intrinsic
def _dict_insert(typingctx, d, key, hashval, val):
"""Wrap numba_dict_insert
"""
resty = types.int32
sig = resty(d, d.key_type, types.intp, d.value_type)
def codegen(context, builder, sig, args):
fnty = ir.FunctionType(
ll_status,
[ll_dict_type, ll_bytes, ll_hash, ll_bytes, ll_bytes],
)
[d, key, hashval, val] = args
[td, tkey, thashval, tval] = sig.args
fn = cgutils.get_or_insert_function(builder.module, fnty,
'numba_dict_insert')
dm_key = context.data_model_manager[tkey]
dm_val = context.data_model_manager[tval]
data_key = dm_key.as_data(builder, key)
data_val = dm_val.as_data(builder, val)
ptr_key = cgutils.alloca_once_value(builder, data_key)
cgutils.memset_padding(builder, ptr_key)
ptr_val = cgutils.alloca_once_value(builder, data_val)
# TODO: the ptr_oldval is not used. needed for refct
ptr_oldval = cgutils.alloca_once(builder, data_val.type)
dp = _container_get_data(context, builder, td, d)
status = builder.call(
fn,
[
dp,
_as_bytes(builder, ptr_key),
hashval,
_as_bytes(builder, ptr_val),
_as_bytes(builder, ptr_oldval),
],
)
return status
return sig, codegen
@intrinsic
def _dict_length(typingctx, d):
"""Wrap numba_dict_length
Returns the length of the dictionary.
"""
resty = types.intp
sig = resty(d)
def codegen(context, builder, sig, args):
fnty = ir.FunctionType(
ll_ssize_t,
[ll_dict_type],
)
fn = cgutils.get_or_insert_function(builder.module, fnty,
'numba_dict_length')
[d] = args
[td] = sig.args
dp = _container_get_data(context, builder, td, d)
n = builder.call(fn, [dp])
return n
return sig, codegen
@intrinsic
def _dict_dump(typingctx, d):
"""Dump the dictionary keys and values.
Wraps numba_dict_dump for debugging.
"""
resty = types.void
sig = resty(d)
def codegen(context, builder, sig, args):
fnty = ir.FunctionType(
ir.VoidType(),
[ll_dict_type],
)
[td] = sig.args
[d] = args
dp = _container_get_data(context, builder, td, d)
fn = cgutils.get_or_insert_function(builder.module, fnty,
'numba_dict_dump')
builder.call(fn, [dp])
return sig, codegen
@intrinsic
def _dict_lookup(typingctx, d, key, hashval):
"""Wrap numba_dict_lookup
Returns 2-tuple of (intp, ?value_type)
"""
resty = types.Tuple([types.intp, types.Optional(d.value_type)])
sig = resty(d, key, hashval)
def codegen(context, builder, sig, args):
fnty = ir.FunctionType(
ll_ssize_t,
[ll_dict_type, ll_bytes, ll_hash, ll_bytes],
)
[td, tkey, thashval] = sig.args
[d, key, hashval] = args
fn = cgutils.get_or_insert_function(builder.module, fnty,
'numba_dict_lookup')
dm_key = context.data_model_manager[tkey]
dm_val = context.data_model_manager[td.value_type]
data_key = dm_key.as_data(builder, key)
ptr_key = cgutils.alloca_once_value(builder, data_key)
cgutils.memset_padding(builder, ptr_key)
ll_val = context.get_data_type(td.value_type)
ptr_val = cgutils.alloca_once(builder, ll_val)
dp = _container_get_data(context, builder, td, d)
ix = builder.call(
fn,
[
dp,
_as_bytes(builder, ptr_key),
hashval,
_as_bytes(builder, ptr_val),
],
)
# Load value if output is available
found = builder.icmp_signed('>', ix, ix.type(int(DKIX.EMPTY)))
out = context.make_optional_none(builder, td.value_type)
pout = cgutils.alloca_once_value(builder, out)
with builder.if_then(found):
val = dm_val.load_from_data_pointer(builder, ptr_val)
context.nrt.incref(builder, td.value_type, val)
loaded = context.make_optional_value(builder, td.value_type, val)
builder.store(loaded, pout)
out = builder.load(pout)
return context.make_tuple(builder, resty, [ix, out])
return sig, codegen
@intrinsic
def _dict_popitem(typingctx, d):
"""Wrap numba_dict_popitem
"""
keyvalty = types.Tuple([d.key_type, d.value_type])
resty = types.Tuple([types.int32, types.Optional(keyvalty)])
sig = resty(d)
def codegen(context, builder, sig, args):
fnty = ir.FunctionType(
ll_status,
[ll_dict_type, ll_bytes, ll_bytes],
)
[d] = args
[td] = sig.args
fn = cgutils.get_or_insert_function(builder.module, fnty,
'numba_dict_popitem')
dm_key = context.data_model_manager[td.key_type]
dm_val = context.data_model_manager[td.value_type]
ptr_key = cgutils.alloca_once(builder, dm_key.get_data_type())
ptr_val = cgutils.alloca_once(builder, dm_val.get_data_type())
dp = _container_get_data(context, builder, td, d)
status = builder.call(
fn,
[
dp,
_as_bytes(builder, ptr_key),
_as_bytes(builder, ptr_val),
],
)
out = context.make_optional_none(builder, keyvalty)
pout = cgutils.alloca_once_value(builder, out)
cond = builder.icmp_signed('==', status, status.type(int(Status.OK)))
with builder.if_then(cond):
key = dm_key.load_from_data_pointer(builder, ptr_key)
val = dm_val.load_from_data_pointer(builder, ptr_val)
keyval = context.make_tuple(builder, keyvalty, [key, val])
optkeyval = context.make_optional_value(builder, keyvalty, keyval)
builder.store(optkeyval, pout)
out = builder.load(pout)
return cgutils.pack_struct(builder, [status, out])
return sig, codegen
@intrinsic
def _dict_delitem(typingctx, d, hk, ix):
"""Wrap numba_dict_delitem
"""
resty = types.int32
sig = resty(d, hk, types.intp)
def codegen(context, builder, sig, args):
fnty = ir.FunctionType(
ll_status,
[ll_dict_type, ll_hash, ll_ssize_t],
)
[d, hk, ix] = args
[td, thk, tix] = sig.args
fn = cgutils.get_or_insert_function(builder.module, fnty,
'numba_dict_delitem')
dp = _container_get_data(context, builder, td, d)
status = builder.call(fn, [dp, hk, ix])
return status
return sig, codegen
def _iterator_codegen(resty):
"""The common codegen for iterator intrinsics.
Populates the iterator struct and increfs.
"""
def codegen(context, builder, sig, args):
[d] = args
[td] = sig.args
iterhelper = context.make_helper(builder, resty)
iterhelper.parent = d
iterhelper.state = iterhelper.state.type(None)
return impl_ret_borrowed(
context,
builder,
resty,
iterhelper._getvalue(),
)
return codegen
@intrinsic
def _dict_items(typingctx, d):
"""Get dictionary iterator for .items()"""
resty = types.DictItemsIterableType(d)
sig = resty(d)
codegen = _iterator_codegen(resty)
return sig, codegen
@intrinsic
def _dict_keys(typingctx, d):
"""Get dictionary iterator for .keys()"""
resty = types.DictKeysIterableType(d)
sig = resty(d)
codegen = _iterator_codegen(resty)
return sig, codegen
@intrinsic
def _dict_values(typingctx, d):
"""Get dictionary iterator for .values()"""
resty = types.DictValuesIterableType(d)
sig = resty(d)
codegen = _iterator_codegen(resty)
return sig, codegen
@intrinsic
def _make_dict(typingctx, keyty, valty, ptr):
"""Make a dictionary struct with the given *ptr*
Parameters
----------
keyty, valty: Type
Type of the key and value, respectively.
ptr : llvm pointer value
Points to the dictionary object.
"""
dict_ty = types.DictType(keyty.instance_type, valty.instance_type)
def codegen(context, builder, signature, args):
[_, _, ptr] = args
ctor = cgutils.create_struct_proxy(dict_ty)
dstruct = ctor(context, builder)
dstruct.data = ptr
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_dict_type.as_pointer())
builder.store(ptr, data_pointer)
dstruct.meminfo = meminfo
return dstruct._getvalue()
sig = dict_ty(keyty, valty, ptr)
return sig, codegen
@overload(new_dict)
def impl_new_dict(key, value, n_keys=0):
"""Creates a new dictionary with *key* and *value* as the type
of the dictionary key and value, respectively. *n_keys* is the
number of keys to insert without requiring a resize, where a
value of 0 creates a dictionary with minimum size.
"""
if any([
not isinstance(key, Type),
not isinstance(value, Type),
]):
raise NumbaTypeError("expecting *key* and *value* to be a Numba Type")
keyty, valty = key, value
def imp(key, value, n_keys=0):
if n_keys < 0:
raise RuntimeError("expecting *n_keys* to be >= 0")
dp = _dict_new_sized(n_keys, keyty, valty)
_dict_set_method_table(dp, keyty, valty)
d = _make_dict(keyty, valty, dp)
return d
return imp
@overload(len)
def impl_len(d):
"""len(dict)
"""
if not isinstance(d, types.DictType):
return
def impl(d):
return _dict_length(d)
return impl
@overload(len)
def impl_len_iters(d):
"""len(dict.keys()), len(dict.values()), len(dict.items())
"""
if not isinstance(d, (DictKeysIterableType,
DictValuesIterableType, DictItemsIterableType)):
return
def impl(d):
return _dict_length(d._parent)
return impl
@overload_method(types.DictType, '__setitem__')
@overload(operator.setitem)
def impl_setitem(d, key, value):
if not isinstance(d, types.DictType):
return
keyty, valty = d.key_type, d.value_type
def impl(d, key, value):
castedkey = _cast(key, keyty)
castedval = _cast(value, valty)
status = _dict_insert(d, castedkey, hash(castedkey), castedval)
if status == Status.OK:
return
elif status == Status.OK_REPLACED:
# replaced
# XXX handle refcount
return
elif status == Status.ERR_CMP_FAILED:
raise ValueError('key comparison failed')
else:
raise RuntimeError('dict.__setitem__ failed unexpectedly')
if d.is_precise():
# Handle the precise case.
return impl
else:
# Handle the imprecise case.
d = d.refine(key, value)
# Re-bind the key type and value type to match the arguments.
keyty, valty = d.key_type, d.value_type
# Create the signature that we wanted this impl to have.
sig = typing.signature(types.void, d, keyty, valty)
return sig, impl
@overload_method(types.DictType, 'get')
def impl_get(dct, key, default=None):
if not isinstance(dct, types.DictType):
return
keyty = dct.key_type
valty = dct.value_type
_sentry_safe_cast_default(default, valty)
def impl(dct, key, default=None):
castedkey = _cast(key, keyty)
ix, val = _dict_lookup(dct, castedkey, hash(castedkey))
if ix > DKIX.EMPTY:
return val
return default
return impl
@overload_attribute(types.DictType, '__hash__')
def impl_hash(dct):
if not isinstance(dct, types.DictType):
return
return lambda dct: None
@overload(operator.getitem)
def impl_getitem(d, key):
if not isinstance(d, types.DictType):
return
keyty = d.key_type
def impl(d, key):
castedkey = _cast(key, keyty)
ix, val = _dict_lookup(d, castedkey, hash(castedkey))
if ix == DKIX.EMPTY:
raise KeyError()
elif ix < DKIX.EMPTY:
raise AssertionError("internal dict error during lookup")
else:
return _nonoptional(val)
return impl
@overload_method(types.DictType, 'popitem')
def impl_popitem(d):
if not isinstance(d, types.DictType):
return
def impl(d):
status, keyval = _dict_popitem(d)
if status == Status.OK:
return _nonoptional(keyval)
elif status == Status.ERR_DICT_EMPTY:
raise KeyError()
else:
raise AssertionError('internal dict error during popitem')
return impl
@overload_method(types.DictType, 'pop')
def impl_pop(dct, key, default=None):
if not isinstance(dct, types.DictType):
return
keyty = dct.key_type
valty = dct.value_type
should_raise = isinstance(default, types.Omitted)
_sentry_safe_cast_default(default, valty)
def impl(dct, key, default=None):
castedkey = _cast(key, keyty)
hashed = hash(castedkey)
ix, val = _dict_lookup(dct, castedkey, hashed)
if ix == DKIX.EMPTY:
if should_raise:
raise KeyError()
else:
return default
elif ix < DKIX.EMPTY:
raise AssertionError("internal dict error during lookup")
else:
status = _dict_delitem(dct, hashed, ix)
if status != Status.OK:
raise AssertionError("internal dict error during delitem")
return val
return impl
@overload(operator.delitem)
def impl_delitem(d, k):
if not isinstance(d, types.DictType):
return
def impl(d, k):
d.pop(k)
return impl
@overload(operator.contains)
def impl_contains(d, k):
if not isinstance(d, types.DictType):
return
keyty = d.key_type
def impl(d, k):
k = _cast(k, keyty)
ix, val = _dict_lookup(d, k, hash(k))
return ix > DKIX.EMPTY
return impl
@overload_method(types.DictType, 'clear')
def impl_clear(d):
if not isinstance(d, types.DictType):
return
def impl(d):
while len(d):
d.popitem()
return impl
@overload_method(types.DictType, 'copy')
def impl_copy(d):
if not isinstance(d, types.DictType):
return
key_type, val_type = d.key_type, d.value_type
def impl(d):
newd = new_dict(key_type, val_type, n_keys=len(d))
for k, v in d.items():
newd[k] = v
return newd
return impl
@overload_method(types.DictType, 'setdefault')
def impl_setdefault(dct, key, default=None):
if not isinstance(dct, types.DictType):
return
def impl(dct, key, default=None):
if key not in dct:
dct[key] = default
return dct[key]
return impl
@overload_method(types.DictType, 'items')
def impl_items(d):
if not isinstance(d, types.DictType):
return
def impl(d):
it = _dict_items(d)
return it
return impl
@overload_method(types.DictType, 'keys')
def impl_keys(d):
if not isinstance(d, types.DictType):
return
def impl(d):
return _dict_keys(d)
return impl
@overload_method(types.DictType, 'values')
def impl_values(d):
if not isinstance(d, types.DictType):
return
def impl(d):
return _dict_values(d)
return impl
@overload_method(types.DictType, 'update')
def ol_dict_update(d, other):
if not isinstance(d, types.DictType):
return
if not isinstance(other, types.DictType):
return
def impl(d, other):
for k, v in other.items():
d[k] = v
return impl
@overload(operator.eq)
def impl_equal(da, db):
if not isinstance(da, types.DictType):
return
if not isinstance(db, types.DictType):
# If RHS is not a dictionary, always returns False
def impl_type_mismatch(da, db):
return False
return impl_type_mismatch
otherkeyty = db.key_type
def impl_type_matched(da, db):
if len(da) != len(db):
return False
for ka, va in da.items():
# Cast key from LHS to the key-type of RHS
kb = _cast(ka, otherkeyty)
ix, vb = _dict_lookup(db, kb, hash(kb))
if ix <= DKIX.EMPTY:
# Quit early if the key is not found
return False
if va != vb:
# Quit early if the values do not match
return False
return True
return impl_type_matched
@overload(operator.ne)
def impl_not_equal(da, db):
if not isinstance(da, types.DictType):
return
def impl(da, db):
return not (da == db)
return impl
@lower_builtin('getiter', types.DictItemsIterableType)
@lower_builtin('getiter', types.DictKeysIterableType)
@lower_builtin('getiter', types.DictValuesIterableType)
def impl_iterable_getiter(context, builder, sig, args):
"""Implement iter() for .keys(), .values(), .items()
"""
iterablety = sig.args[0]
it = context.make_helper(builder, iterablety.iterator_type, args[0])
fnty = ir.FunctionType(
ir.VoidType(),
[ll_dictiter_type, ll_dict_type],
)