| 1 |
"""The builtin tuple implementation""" |
| 2 |
|
| 3 |
import sys |
| 4 |
|
| 5 |
from pypy.interpreter.baseobjspace import W_Root |
| 6 |
from pypy.interpreter.error import OperationError, oefmt |
| 7 |
from pypy.interpreter.gateway import ( |
| 8 |
WrappedDefault, interp2app, interpindirect2app, unwrap_spec) |
| 9 |
from pypy.interpreter.typedef import TypeDef |
| 10 |
from pypy.objspace.std.objectobject import ObjectObjectDocstrings |
| 11 |
from pypy.objspace.std.sliceobject import (W_SliceObject, unwrap_start_stop, |
| 12 |
normalize_simple_slice) |
| 13 |
from pypy.objspace.std.util import negate, IDTAG_SPECIAL, IDTAG_SHIFT, \ |
| 14 |
generic_alias_class_getitem, builtinclass_new_args_check |
| 15 |
from rpython.rlib import jit |
| 16 |
from rpython.rlib.debug import make_sure_not_resized |
| 17 |
from rpython.rlib.rarithmetic import intmask, r_ulonglong, r_uint |
| 18 |
|
| 19 |
|
| 20 |
UNROLL_CUTOFF = 10 |
| 21 |
|
| 22 |
|
| 23 |
def _unroll_condition_cmp(self, space, other): |
| 24 |
return self._unroll_condition() or other._unroll_condition() |
| 25 |
|
| 26 |
|
| 27 |
def get_printable_location(tp): |
| 28 |
return "tuple.contains [%s]" % (tp.getname(tp.space), ) |
| 29 |
|
| 30 |
contains_driver = jit.JitDriver(greens = ['tp'], reds = 'auto', |
| 31 |
name = 'tuple.contains', |
| 32 |
get_printable_location=get_printable_location) |
| 33 |
|
| 34 |
def get_printable_location(w_type): |
| 35 |
return "tuple.hash [%s]" % (w_type.getname(w_type.space), ) |
| 36 |
|
| 37 |
hash_driver = jit.JitDriver( |
| 38 |
name='tuple.hash', |
| 39 |
greens=['w_type'], |
| 40 |
reds='auto', |
| 41 |
get_printable_location=get_printable_location |
| 42 |
) |
| 43 |
|
| 44 |
class W_AbstractTupleObject(W_Root): |
| 45 |
__slots__ = () |
| 46 |
|
| 47 |
def is_w(self, space, w_other): |
| 48 |
if not isinstance(w_other, W_AbstractTupleObject): |
| 49 |
return False |
| 50 |
if self is w_other: |
| 51 |
return True |
| 52 |
if self.user_overridden_class or w_other.user_overridden_class: |
| 53 |
return False |
| 54 |
|
| 55 |
return 0 == w_other.length() == self.length() |
| 56 |
|
| 57 |
def immutable_unique_id(self, space): |
| 58 |
if self.user_overridden_class or self.length() > 0: |
| 59 |
return None |
| 60 |
|
| 61 |
uid = (258 << IDTAG_SHIFT) | IDTAG_SPECIAL |
| 62 |
return space.newint(uid) |
| 63 |
|
| 64 |
def __repr__(self): |
| 65 |
"""representation for debugging purposes""" |
| 66 |
reprlist = [repr(w_item) for w_item in self.tolist()] |
| 67 |
return "%s(%s)" % (self.__class__.__name__, ', '.join(reprlist)) |
| 68 |
|
| 69 |
def unwrap(self, space): |
| 70 |
items = [space.unwrap(w_item) for w_item in self.tolist()] |
| 71 |
return tuple(items) |
| 72 |
|
| 73 |
def tolist(self): |
| 74 |
"""Returns the items, as a fixed-size list.""" |
| 75 |
raise NotImplementedError |
| 76 |
|
| 77 |
def getitems_copy(self): |
| 78 |
"""Returns a copy of the items, as a resizable list.""" |
| 79 |
raise NotImplementedError |
| 80 |
|
| 81 |
def length(self): |
| 82 |
raise NotImplementedError |
| 83 |
|
| 84 |
def getitem(self, space, item): |
| 85 |
raise NotImplementedError |
| 86 |
|
| 87 |
def descr_len(self, space): |
| 88 |
result = self.length() |
| 89 |
return space.newint(result) |
| 90 |
|
| 91 |
def descr_iter(self, space): |
| 92 |
from pypy.objspace.std import iterobject |
| 93 |
return iterobject.W_FastTupleIterObject(self, self.tolist()) |
| 94 |
|
| 95 |
@staticmethod |
| 96 |
def descr_new(space, w_tupletype, w_sequence=None, __posonly__=None, __args__=None): |
| 97 |
builtinclass_new_args_check(space, "tuple", space.w_tuple, w_tupletype, __args__) |
| 98 |
if w_sequence is None: |
| 99 |
tuple_w = [] |
| 100 |
elif (space.is_w(w_tupletype, space.w_tuple) and |
| 101 |
space.is_w(space.type(w_sequence), space.w_tuple)): |
| 102 |
return w_sequence |
| 103 |
else: |
| 104 |
tuple_w = space.fixedview(w_sequence) |
| 105 |
w_obj = space.allocate_instance(W_TupleObject, w_tupletype) |
| 106 |
W_TupleObject.__init__(w_obj, tuple_w) |
| 107 |
return w_obj |
| 108 |
|
| 109 |
def descr_repr(self, space): |
| 110 |
items = self.tolist() |
| 111 |
if len(items) == 1: |
| 112 |
return space.newtext( |
| 113 |
b"(" + space.utf8_w(space.repr(items[0])) + b",)") |
| 114 |
tmp = b", ".join([space.utf8_w(space.repr(item)) |
| 115 |
for item in items]) |
| 116 |
return space.newtext(b"(" + tmp + b")") |
| 117 |
|
| 118 |
def descr_hash(self, space): |
| 119 |
raise NotImplementedError |
| 120 |
|
| 121 |
def descr_eq(self, space, w_other): |
| 122 |
raise NotImplementedError |
| 123 |
|
| 124 |
def descr_ne(self, space, w_other): |
| 125 |
raise NotImplementedError |
| 126 |
|
| 127 |
def _make_tuple_comparison(name): |
| 128 |
import operator |
| 129 |
op = getattr(operator, name) |
| 130 |
|
| 131 |
def compare_tuples(self, space, w_other): |
| 132 |
if not isinstance(w_other, W_AbstractTupleObject): |
| 133 |
return space.w_NotImplemented |
| 134 |
return _compare_tuples(self, space, w_other) |
| 135 |
|
| 136 |
@jit.look_inside_iff(_unroll_condition_cmp) |
| 137 |
def _compare_tuples(self, space, w_other): |
| 138 |
items1 = self.tolist() |
| 139 |
items2 = w_other.tolist() |
| 140 |
ncmp = min(len(items1), len(items2)) |
| 141 |
|
| 142 |
for p in range(ncmp): |
| 143 |
if not space.eq_w(items1[p], items2[p]): |
| 144 |
return getattr(space, name)(items1[p], items2[p]) |
| 145 |
|
| 146 |
return space.newbool(op(len(items1), len(items2))) |
| 147 |
|
| 148 |
compare_tuples.__name__ = 'descr_' + name |
| 149 |
return compare_tuples |
| 150 |
|
| 151 |
descr_lt = _make_tuple_comparison('lt') |
| 152 |
descr_le = _make_tuple_comparison('le') |
| 153 |
descr_gt = _make_tuple_comparison('gt') |
| 154 |
descr_ge = _make_tuple_comparison('ge') |
| 155 |
|
| 156 |
def descr_contains(self, space, w_obj): |
| 157 |
if self._unroll_condition(): |
| 158 |
return self._descr_contains_unroll_safe(space, w_obj) |
| 159 |
else: |
| 160 |
return self._descr_contains_jmp(space, w_obj) |
| 161 |
|
| 162 |
@jit.unroll_safe |
| 163 |
def _descr_contains_unroll_safe(self, space, w_obj): |
| 164 |
for w_item in self.tolist(): |
| 165 |
if space.eq_w(w_obj, w_item): |
| 166 |
return space.w_True |
| 167 |
return space.w_False |
| 168 |
|
| 169 |
def _descr_contains_jmp(self, space, w_obj): |
| 170 |
tp = space.type(w_obj) |
| 171 |
list_w = self.tolist() |
| 172 |
i = 0 |
| 173 |
while i < len(list_w): |
| 174 |
contains_driver.jit_merge_point(tp=tp) |
| 175 |
w_item = list_w[i] |
| 176 |
if space.eq_w(w_item, w_obj): |
| 177 |
return space.w_True |
| 178 |
i += 1 |
| 179 |
return space.w_False |
| 180 |
|
| 181 |
def descr_add(self, space, w_other): |
| 182 |
if not isinstance(w_other, W_AbstractTupleObject): |
| 183 |
return space.w_NotImplemented |
| 184 |
items1 = self.tolist() |
| 185 |
items2 = w_other.tolist() |
| 186 |
return space.newtuple(items1 + items2) |
| 187 |
|
| 188 |
def descr_mul(self, space, w_times): |
| 189 |
try: |
| 190 |
times = space.getindex_w(w_times, space.w_OverflowError) |
| 191 |
except OperationError as e: |
| 192 |
if e.match(space, space.w_TypeError): |
| 193 |
return space.w_NotImplemented |
| 194 |
raise |
| 195 |
if times == 1 and space.type(self) == space.w_tuple: |
| 196 |
return self |
| 197 |
items = self.tolist() |
| 198 |
return space.newtuple(items * times) |
| 199 |
|
| 200 |
def descr_getitem(self, space, w_index): |
| 201 |
if isinstance(w_index, W_SliceObject): |
| 202 |
return self._getslice(space, w_index) |
| 203 |
index = space.getindex_w(w_index, space.w_IndexError, "tuple") |
| 204 |
return self.getitem(space, index) |
| 205 |
|
| 206 |
def _getslice(self, space, w_index): |
| 207 |
items = self.tolist() |
| 208 |
length = len(items) |
| 209 |
start, stop, step, slicelength = w_index.indices4(space, length) |
| 210 |
if slicelength == 0: |
| 211 |
subitems = [] |
| 212 |
elif step == 1: |
| 213 |
assert 0 <= start <= stop |
| 214 |
subitems = items[start:stop] |
| 215 |
else: |
| 216 |
subitems = self._getslice_advanced(items, start, step, slicelength) |
| 217 |
return space.newtuple(subitems) |
| 218 |
|
| 219 |
@staticmethod |
| 220 |
def _getslice_advanced(items, start, step, slicelength): |
| 221 |
assert slicelength >= 0 |
| 222 |
subitems = [None] * slicelength |
| 223 |
for i in range(slicelength): |
| 224 |
subitems[i] = items[start] |
| 225 |
start += step |
| 226 |
return subitems |
| 227 |
|
| 228 |
def descr_getnewargs(self, space): |
| 229 |
return space.newtuple([space.newtuple(self.tolist())]) |
| 230 |
|
| 231 |
@jit.look_inside_iff(lambda self, _1, _2: self._unroll_condition()) |
| 232 |
def descr_count(self, space, w_obj): |
| 233 |
"""count(obj) -> number of times obj appears in the tuple""" |
| 234 |
count = 0 |
| 235 |
for w_item in self.tolist(): |
| 236 |
if space.eq_w(w_item, w_obj): |
| 237 |
count += 1 |
| 238 |
return space.newint(count) |
| 239 |
|
| 240 |
@unwrap_spec(w_start=WrappedDefault(0), w_stop=WrappedDefault(sys.maxint)) |
| 241 |
@jit.look_inside_iff(lambda self, _1, _2, _3, _4: self._unroll_condition()) |
| 242 |
def descr_index(self, space, w_obj, w_start, w_stop): |
| 243 |
"""index(obj, [start, [stop]]) -> first index that obj appears in the |
| 244 |
tuple |
| 245 |
""" |
| 246 |
length = self.length() |
| 247 |
start, stop = unwrap_start_stop(space, length, w_start, w_stop) |
| 248 |
for i in range(start, min(stop, length)): |
| 249 |
w_item = self.tolist()[i] |
| 250 |
if space.eq_w(w_item, w_obj): |
| 251 |
return space.newint(i) |
| 252 |
raise oefmt(space.w_ValueError, "tuple.index(x): x not in tuple") |
| 253 |
|
| 254 |
def _unroll_condition(self): |
| 255 |
raise NotImplementedError("abstract base class") |
| 256 |
|
| 257 |
class TupleDocstrings: |
| 258 |
|
| 259 |
def __eq__(): |
| 260 |
"""x.__eq__(y) <==> x==y'""" |
| 261 |
|
| 262 |
def __ne__(): |
| 263 |
"""x.__ne__(y) <==> x!=y""" |
| 264 |
|
| 265 |
def __lt__(): |
| 266 |
"""x.__lt__(y) <==> x<y""" |
| 267 |
|
| 268 |
def __le__(): |
| 269 |
"""x.__le__(y) <==> x<=y""" |
| 270 |
|
| 271 |
def __gt__(): |
| 272 |
"""x.__gt__(y) <==> x>y""" |
| 273 |
|
| 274 |
def __ge__(): |
| 275 |
"""x.__ge__(y) <==> x>=y""" |
| 276 |
|
| 277 |
def __len__(): |
| 278 |
"""x.__len__() <==> len(x)""" |
| 279 |
|
| 280 |
def __iter__(): |
| 281 |
"""x.__iter__() <==> iter(x)""" |
| 282 |
|
| 283 |
def __contains__(): |
| 284 |
"""x.__contains__(y) <==> y in x""" |
| 285 |
|
| 286 |
def __add__(): |
| 287 |
"""x.__add__(y) <==> x+y""" |
| 288 |
|
| 289 |
def __mul__(): |
| 290 |
"""x.__mul__(n) <==> x*n""" |
| 291 |
|
| 292 |
def __rmul__(): |
| 293 |
"""x.__rmul__(n) <==> n*x""" |
| 294 |
|
| 295 |
def __getitem__(): |
| 296 |
"""x.__getitem__(y) <==> x[y]""" |
| 297 |
|
| 298 |
def __getslice__(): |
| 299 |
"""x.__getslice__(i, j) <==> x[i:j] |
| 300 |
|
| 301 |
Use of negative indices is not supported.""" |
| 302 |
|
| 303 |
def __getnewargs__(): |
| 304 |
"""""" |
| 305 |
|
| 306 |
def count(): |
| 307 |
"""T.count(value) -> integer -- return number of occurrences of value""" |
| 308 |
|
| 309 |
def index(): |
| 310 |
""""T.index(value, [start, [stop]]) -> integer -- return first index of value. |
| 311 |
Raises ValueError if the value is not present.""" |
| 312 |
|
| 313 |
W_AbstractTupleObject.typedef = TypeDef( |
| 314 |
"tuple", |
| 315 |
__doc__ = """tuple() -> an empty tuple |
| 316 |
tuple(sequence) -> tuple initialized from sequence's items |
| 317 |
|
| 318 |
If the argument is a tuple, the return value is the same object.""", |
| 319 |
__new__ = interp2app(W_AbstractTupleObject.descr_new, |
| 320 |
doc=ObjectObjectDocstrings.__new__.__doc__), |
| 321 |
__repr__ = interp2app(W_AbstractTupleObject.descr_repr, |
| 322 |
doc=ObjectObjectDocstrings.__repr__.__doc__), |
| 323 |
__hash__ = interpindirect2app(W_AbstractTupleObject.descr_hash), |
| 324 |
|
| 325 |
__eq__ = interpindirect2app(W_AbstractTupleObject.descr_eq), |
| 326 |
__ne__ = interpindirect2app(W_AbstractTupleObject.descr_ne), |
| 327 |
__lt__ = interp2app(W_AbstractTupleObject.descr_lt, |
| 328 |
doc=TupleDocstrings.__lt__.__doc__), |
| 329 |
__le__ = interp2app(W_AbstractTupleObject.descr_le, |
| 330 |
doc=TupleDocstrings.__le__.__doc__), |
| 331 |
__gt__ = interp2app(W_AbstractTupleObject.descr_gt, |
| 332 |
doc=TupleDocstrings.__gt__.__doc__), |
| 333 |
__ge__ = interp2app(W_AbstractTupleObject.descr_ge, |
| 334 |
doc=TupleDocstrings.__ge__.__doc__), |
| 335 |
|
| 336 |
__len__ = interp2app(W_AbstractTupleObject.descr_len, |
| 337 |
doc=TupleDocstrings.__len__.__doc__), |
| 338 |
__iter__ = interp2app(W_AbstractTupleObject.descr_iter, |
| 339 |
doc=TupleDocstrings.__iter__.__doc__), |
| 340 |
__contains__ = interp2app(W_AbstractTupleObject.descr_contains, |
| 341 |
doc=TupleDocstrings.__contains__.__doc__), |
| 342 |
|
| 343 |
__add__ = interp2app(W_AbstractTupleObject.descr_add, |
| 344 |
doc=TupleDocstrings.__add__.__doc__), |
| 345 |
__mul__ = interp2app(W_AbstractTupleObject.descr_mul, |
| 346 |
doc=TupleDocstrings.__mul__.__doc__), |
| 347 |
__rmul__ = interp2app(W_AbstractTupleObject.descr_mul, |
| 348 |
doc=TupleDocstrings.__rmul__.__doc__), |
| 349 |
|
| 350 |
__getitem__ = interp2app(W_AbstractTupleObject.descr_getitem, |
| 351 |
doc=TupleDocstrings.__getitem__.__doc__), |
| 352 |
__getnewargs__ = interp2app(W_AbstractTupleObject.descr_getnewargs, |
| 353 |
doc=TupleDocstrings.__getnewargs__.__doc__), |
| 354 |
__class_getitem__ = interp2app( |
| 355 |
generic_alias_class_getitem, as_classmethod=True), |
| 356 |
count = interp2app(W_AbstractTupleObject.descr_count, |
| 357 |
doc=TupleDocstrings.count.__doc__), |
| 358 |
index = interp2app(W_AbstractTupleObject.descr_index, |
| 359 |
doc=TupleDocstrings.index.__doc__) |
| 360 |
) |
| 361 |
W_AbstractTupleObject.typedef.flag_sequence_bug_compat = True |
| 362 |
|
| 363 |
if sys.maxint == 2 ** 31 - 1: |
| 364 |
XXPRIME_1 = r_uint(2654435761) |
| 365 |
XXPRIME_2 = r_uint(2246822519) |
| 366 |
XXPRIME_5 = r_uint(374761393) |
| 367 |
xxrotate = lambda x: ((x << 13) | (x >> 19)) |
| 368 |
uhash_type = r_uint |
| 369 |
else: |
| 370 |
XXPRIME_1 = r_ulonglong(11400714785074694791) |
| 371 |
XXPRIME_2 = r_ulonglong(14029467366897019727) |
| 372 |
XXPRIME_5 = r_ulonglong(2870177450012600261) |
| 373 |
xxrotate = lambda x: ((x << 31) | (x >> 33)) |
| 374 |
uhash_type = r_ulonglong |
| 375 |
|
| 376 |
class W_TupleObject(W_AbstractTupleObject): |
| 377 |
_immutable_fields_ = ['wrappeditems[*]'] |
| 378 |
|
| 379 |
def __init__(self, wrappeditems): |
| 380 |
make_sure_not_resized(wrappeditems) |
| 381 |
self.wrappeditems = wrappeditems |
| 382 |
|
| 383 |
def tolist(self): |
| 384 |
return self.wrappeditems |
| 385 |
|
| 386 |
def getitems_copy(self): |
| 387 |
return self.wrappeditems[:] |
| 388 |
|
| 389 |
def length(self): |
| 390 |
return len(self.wrappeditems) |
| 391 |
|
| 392 |
def descr_hash(self, space): |
| 393 |
if self._unroll_condition(): |
| 394 |
acc = self._descr_hash_unroll(space) |
| 395 |
else: |
| 396 |
acc = self._descr_hash_jitdriver(space) |
| 397 |
|
| 398 |
|
| 399 |
acc += len(self.wrappeditems) ^ (XXPRIME_5 ^ uhash_type(3527539)) |
| 400 |
acc += (acc == uhash_type(-1)) * uhash_type(1546275796 + 1) |
| 401 |
return space.newint(intmask(acc)) |
| 402 |
|
| 403 |
@jit.unroll_safe |
| 404 |
def _descr_hash_unroll(self, space): |
| 405 |
|
| 406 |
|
| 407 |
|
| 408 |
|
| 409 |
|
| 410 |
|
| 411 |
|
| 412 |
|
| 413 |
|
| 414 |
|
| 415 |
|
| 416 |
|
| 417 |
|
| 418 |
|
| 419 |
acc = XXPRIME_5 |
| 420 |
for w_item in self.wrappeditems: |
| 421 |
lane = uhash_type(space.hash_w(w_item)) |
| 422 |
acc += lane * XXPRIME_2 |
| 423 |
acc = xxrotate(acc) |
| 424 |
acc *= XXPRIME_1 |
| 425 |
return acc |
| 426 |
|
| 427 |
def _descr_hash_jitdriver(self, space): |
| 428 |
|
| 429 |
acc = XXPRIME_5 |
| 430 |
w_type = space.type(self.wrappeditems[0]) |
| 431 |
wrappeditems = self.wrappeditems |
| 432 |
i = 0 |
| 433 |
while i < len(wrappeditems): |
| 434 |
hash_driver.jit_merge_point(w_type=w_type) |
| 435 |
w_item = wrappeditems[i] |
| 436 |
lane = uhash_type(space.hash_w(w_item)) |
| 437 |
acc += lane * XXPRIME_2 |
| 438 |
acc = xxrotate(acc) |
| 439 |
acc *= XXPRIME_1 |
| 440 |
i += 1 |
| 441 |
return acc |
| 442 |
|
| 443 |
def descr_eq(self, space, w_other): |
| 444 |
if not isinstance(w_other, W_AbstractTupleObject): |
| 445 |
return space.w_NotImplemented |
| 446 |
return self._descr_eq(space, w_other) |
| 447 |
|
| 448 |
@jit.look_inside_iff(_unroll_condition_cmp) |
| 449 |
def _descr_eq(self, space, w_other): |
| 450 |
items1 = self.wrappeditems |
| 451 |
items2 = w_other.tolist() |
| 452 |
lgt1 = len(items1) |
| 453 |
lgt2 = len(items2) |
| 454 |
if lgt1 != lgt2: |
| 455 |
return space.w_False |
| 456 |
|
| 457 |
for i in range(lgt1): |
| 458 |
item1 = items1[i] |
| 459 |
item2 = items2[i] |
| 460 |
if not space.eq_w(item1, item2): |
| 461 |
return space.w_False |
| 462 |
return space.w_True |
| 463 |
|
| 464 |
descr_ne = negate(descr_eq) |
| 465 |
|
| 466 |
def getitem(self, space, index): |
| 467 |
try: |
| 468 |
return self.wrappeditems[index] |
| 469 |
except IndexError: |
| 470 |
raise oefmt(space.w_IndexError, "tuple index out of range") |
| 471 |
|
| 472 |
def _unroll_condition(self): |
| 473 |
return jit.loop_unrolling_heuristic( |
| 474 |
self.wrappeditems, self.length(), UNROLL_CUTOFF) |
| 475 |
|
| 476 |
|
| 477 |
def wraptuple(space, list_w): |
| 478 |
if space.config.objspace.std.withspecialisedtuple: |
| 479 |
from specialisedtupleobject import makespecialisedtuple, NotSpecialised |
| 480 |
try: |
| 481 |
return makespecialisedtuple(space, list_w) |
| 482 |
except NotSpecialised: |
| 483 |
pass |
| 484 |
return W_TupleObject(list_w) |
| 485 |
|
| 486 |
def wraptuple2(space, w_a, w_b): |
| 487 |
if space.config.objspace.std.withspecialisedtuple: |
| 488 |
from specialisedtupleobject import makespecialisedtuple2, NotSpecialised |
| 489 |
try: |
| 490 |
return makespecialisedtuple2(space, w_a, w_b) |
| 491 |
except NotSpecialised: |
| 492 |
pass |
| 493 |
return W_TupleObject([w_a, w_b]) |
| 494 |
|