Debian Codegraph @

pypy/objspace/std/longobject.py

raw symbols SCIP
1 """The builtin int type based on rbigint (the old long type)"""
2
3 import functools
4
5 from rpython.rlib import jit
6 from rpython.rlib.objectmodel import specialize
7 from rpython.rlib.rarithmetic import intmask, ovfcheck
8 from rpython.rlib.rbigint import SHIFT, _load_unsigned_digit, rbigint
9 from rpython.tool.sourcetools import func_renamer, func_with_new_name
10
11 from pypy.interpreter.baseobjspace import W_Root
12 from pypy.interpreter.error import oefmt
13 from pypy.interpreter.gateway import WrappedDefault, unwrap_spec
14 from pypy.objspace.std import newformat
15 from pypy.objspace.std.intobject import (
16 HASH_BITS, HASH_MODULUS, W_AbstractIntObject, W_IntObject)
17 from pypy.objspace.std.util import (
18 BINARY_OPS, CMP_OPS, COMMUTATIVE_OPS, IDTAG_LONG, IDTAG_SHIFT, wrap_parsestringerror)
19
20
21 def delegate_other(func):
22 @functools.wraps(func)
23 def delegated(self, space, w_other):
24 if isinstance(w_other, W_IntObject):
25 w_other = w_other.as_w_long(space)
26 elif not isinstance(w_other, W_AbstractLongObject):
27 return space.w_NotImplemented
28 return func(self, space, w_other)
29 return delegated
30
31
32 class W_AbstractLongObject(W_AbstractIntObject):
33
34 __slots__ = ()
35
36 def unwrap(self, space):
37 return self.longval()
38
39 def int(self, space):
40 raise NotImplementedError
41
42 def asbigint(self):
43 raise NotImplementedError
44
45 def descr_getnewargs(self, space):
46 return space.newtuple([newlong(space, self.asbigint())])
47
48 def descr_bit_length(self, space):
49 bigint = space.bigint_w(self)
50 try:
51 return space.newint(bigint.bit_length())
52 except OverflowError:
53 raise oefmt(space.w_OverflowError, "too many digits in integer")
54
55 def descr_bit_count(self, space):
56 bigint = space.bigint_w(self)
57 try:
58 return space.newint(bigint.bit_count())
59 except OverflowError:
60 raise oefmt(space.w_OverflowError, "too many digits in integer")
61
62 def _truediv(self, space, w_other):
63 try:
64 f = self.asbigint().truediv(w_other.asbigint())
65 except ZeroDivisionError:
66 raise oefmt(space.w_ZeroDivisionError, "division by zero")
67 except OverflowError:
68 raise oefmt(space.w_OverflowError,
69 "integer division result too large for a float")
70 return space.newfloat(f)
71
72 @delegate_other
73 def descr_truediv(self, space, w_other):
74 return W_AbstractLongObject._truediv(self, space, w_other)
75
76 @delegate_other
77 def descr_rtruediv(self, space, w_other):
78 return W_AbstractLongObject._truediv(w_other, space, self)
79
80 def descr_format(self, space, w_format_spec):
81 return newformat.run_formatter(space, w_format_spec,
82 "format_int_or_long", self,
83 newformat.LONG_KIND)
84
85 def descr_hash(self, space):
86 return space.newint(_hash_long(self.asbigint()))
87
88 def descr_str(self, space):
89 from pypy.module.sys.system import MAX_STR_DIGITS_THRESHOLD
90 from pypy.module.sys.state import get_int_max_str_digits
91 from rpython.rlib.rbigint import SHIFT, MaxIntError
92 msg_fmt_to_str = ("Exceeds the limit (%d) for integer string "
93 "conversion; use sys.set_int_max_str_digits() to increase the "
94 "limit")
95
96 bigint = space.bigint_w(self)
97 numdigits = bigint.numdigits()
98 max_str_digits = space.int_w(get_int_max_str_digits(space))
99 # quick and dirty pre-check for overflowing the decimal digit limit,
100 if bigint.numdigits() >= (10 * MAX_STR_DIGITS_THRESHOLD /
101 (3 * SHIFT + 2)):
102 if (max_str_digits != 0 and
103 max_str_digits / (3 * SHIFT) <= (numdigits - 11) / 10):
104 raise oefmt(space.w_ValueError, msg_fmt_to_str, max_str_digits)
105 # Do an additional more accurate check that
106 # strlen(res) < max_str_digits (actually they check before allocating
107 # the buffer to hold the string.
108 try:
109 res = self.asbigint().str(max_str_digits=max_str_digits)
110 except MaxIntError:
111 raise oefmt(space.w_ValueError, msg_fmt_to_str, max_str_digits)
112 return space.newutf8(res, len(res))
113 descr_repr = descr_str
114
115
116 class W_LongObject(W_AbstractLongObject):
117 """This is a wrapper of rbigint."""
118
119 _immutable_fields_ = ['num']
120
121 def __init__(self, num):
122 self.num = num # instance of rbigint
123
124 @staticmethod
125 def fromint(space, intval):
126 return W_LongObject(rbigint.fromint(intval))
127
128 def longval(self):
129 return self.num.tolong()
130
131 def tofloat(self, space):
132 try:
133 return self.num.tofloat()
134 except OverflowError:
135 raise oefmt(space.w_OverflowError,
136 "int too large to convert to float")
137
138 def toint(self):
139 return self.num.toint()
140
141 def _fits_int(self):
142 return self.num.fits_int()
143
144 @staticmethod
145 def fromfloat(space, f):
146 return newlong(space, rbigint.fromfloat(f))
147
148 @staticmethod
149 def fromlong(l):
150 return W_LongObject(rbigint.fromlong(l))
151
152 @staticmethod
153 @specialize.argtype(0)
154 def fromrarith_int(i):
155 return W_LongObject(rbigint.fromrarith_int(i))
156
157 def _int_w(self, space):
158 try:
159 return self.num.toint()
160 except OverflowError:
161 raise oefmt(space.w_OverflowError,
162 "int too large to convert to int")
163
164 def uint_w(self, space):
165 try:
166 return self.num.touint()
167 except ValueError:
168 raise oefmt(space.w_ValueError,
169 "cannot convert negative integer to unsigned int")
170 except OverflowError:
171 raise oefmt(space.w_OverflowError,
172 "int too large to convert to unsigned int")
173
174 def bigint_w(self, space, allow_conversion=True):
175 return self.num
176
177 def _bigint_w(self, space):
178 return self.num
179
180 def float_w(self, space, allow_conversion=True):
181 return self.tofloat(space)
182
183 def _float_w(self, space):
184 return self.tofloat(space)
185
186 def int(self, space):
187 if type(self) is W_LongObject:
188 return self
189 if not space.is_overloaded(self, space.w_int, '__int__'):
190 return W_LongObject(self.num)
191 return W_Root.int(self, space)
192
193 def asbigint(self):
194 return self.num
195
196 def __repr__(self):
197 return '<W_LongObject(%d)>' % self.num.tolong()
198
199 def descr_float(self, space):
200 return space.newfloat(self.tofloat(space))
201
202 def descr_bool(self, space):
203 return space.newbool(self.num.tobool())
204
205 @unwrap_spec(w_modulus=WrappedDefault(None))
206 def descr_pow(self, space, w_exponent, w_modulus=None):
207 from pypy.objspace.std.intobject import invmod
208 exp_int = 0
209 exp_bigint = None
210 sign = 0
211
212 if isinstance(w_exponent, W_IntObject):
213 exp_int = w_exponent.int_w(space)
214 if exp_int > 0:
215 sign = 1
216 elif exp_int < 0:
217 sign = -1
218 elif not isinstance(w_exponent, W_AbstractLongObject):
219 return space.w_NotImplemented
220 else:
221 exp_bigint = w_exponent.asbigint()
222 sign = exp_bigint.get_sign()
223
224 if space.is_none(w_modulus):
225 if sign < 0:
226 self = self.descr_float(space)
227 w_exponent = w_exponent.descr_float(space)
228 return space.pow(self, w_exponent, space.w_None)
229 if not exp_bigint:
230 return W_LongObject(self.num.int_pow(exp_int))
231 else:
232 return W_LongObject(self.num.pow(exp_bigint))
233
234 elif isinstance(w_modulus, W_AbstractIntObject):
235 pass
236
237 elif not isinstance(w_modulus, W_AbstractLongObject):
238 return space.w_NotImplemented
239
240 base = self.num
241 if sign < 0:
242 w_base = invmod(space, self, space.abs(w_modulus))
243 if isinstance(w_base, W_IntObject):
244 w_base = w_base.as_w_long(space)
245 base = w_base.asbigint()
246
247 if exp_bigint is not None:
248 exp_bigint = exp_bigint.neg()
249 else:
250 try:
251 exp_int = ovfcheck(-exp_int)
252 except OverflowError:
253 # MININT
254 exp_bigint = rbigint.fromint(exp_int).neg()
255 try:
256 if not exp_bigint:
257 result = base.int_pow(exp_int, w_modulus.asbigint())
258 else:
259 result = base.pow(exp_bigint, w_modulus.asbigint())
260 except ValueError:
261 raise oefmt(space.w_ValueError, "pow 3rd argument cannot be 0")
262 return W_LongObject(result)
263
264 @unwrap_spec(w_modulus=WrappedDefault(None))
265 def descr_rpow(self, space, w_base, w_modulus=None):
266 if isinstance(w_base, W_IntObject):
267 w_base = w_base.as_w_long(space)
268 elif not isinstance(w_base, W_AbstractLongObject):
269 return space.w_NotImplemented
270 return w_base.descr_pow(space, self, w_modulus)
271
272 def _make_descr_unaryop(opname):
273 op = getattr(rbigint, opname)
274 @func_renamer('descr_' + opname)
275 def descr_unaryop(self, space):
276 return W_LongObject(op(self.num))
277 return descr_unaryop
278
279 descr_neg = _make_descr_unaryop('neg')
280 descr_abs = _make_descr_unaryop('abs')
281 descr_invert = _make_descr_unaryop('invert')
282
283 def _make_descr_cmp(opname):
284 op = getattr(rbigint, opname)
285 intop = getattr(rbigint, "int_" + opname)
286
287 @func_renamer('descr_' + opname)
288 def descr_impl(self, space, w_other):
289 if isinstance(w_other, W_IntObject):
290 return space.newbool(intop(self.num, w_other.int_w(space)))
291 elif not isinstance(w_other, W_AbstractLongObject):
292 return space.w_NotImplemented
293 return space.newbool(op(self.num, w_other.asbigint()))
294
295 return descr_impl
296
297 descr_lt = _make_descr_cmp('lt')
298 descr_le = _make_descr_cmp('le')
299 descr_eq = _make_descr_cmp('eq')
300 descr_ne = _make_descr_cmp('ne')
301 descr_gt = _make_descr_cmp('gt')
302 descr_ge = _make_descr_cmp('ge')
303
304 def descr_sub(self, space, w_other):
305 if isinstance(w_other, W_IntObject):
306 return W_LongObject(self.num.int_sub(w_other.int_w(space)))
307 elif not isinstance(w_other, W_AbstractLongObject):
308 return space.w_NotImplemented
309 return W_LongObject(self.num.sub(w_other.asbigint()))
310
311 @delegate_other
312 def descr_rsub(self, space, w_other):
313 return W_LongObject(w_other.asbigint().sub(self.num))
314
315 def _make_generic_descr_binop(opname):
316 if opname not in COMMUTATIVE_OPS:
317 raise Exception("Not supported")
318
319 methname = opname + '_' if opname in ('and', 'or') else opname
320 descr_rname = 'descr_r' + opname
321 op = getattr(rbigint, methname)
322 intop = getattr(rbigint, "int_" + methname)
323
324 @func_renamer('descr_' + opname)
325 def descr_binop(self, space, w_other):
326 if isinstance(w_other, W_IntObject):
327 return W_LongObject(intop(self.num, w_other.int_w(space)))
328 elif not isinstance(w_other, W_AbstractLongObject):
329 return space.w_NotImplemented
330
331 return W_LongObject(op(self.num, w_other.asbigint()))
332
333 @func_renamer(descr_rname)
334 def descr_rbinop(self, space, w_other):
335 if isinstance(w_other, W_IntObject):
336 return W_LongObject(intop(self.num, w_other.int_w(space)))
337 elif not isinstance(w_other, W_AbstractLongObject):
338 return space.w_NotImplemented
339
340 return W_LongObject(op(w_other.asbigint(), self.num))
341
342 return descr_binop, descr_rbinop
343
344 descr_add, descr_radd = _make_generic_descr_binop('add')
345
346 descr_mul, descr_rmul = _make_generic_descr_binop('mul')
347 descr_and, descr_rand = _make_generic_descr_binop('and')
348 descr_or, descr_ror = _make_generic_descr_binop('or')
349 descr_xor, descr_rxor = _make_generic_descr_binop('xor')
350
351 def _make_descr_binop(func, int_func):
352 opname = func.__name__[1:]
353
354 @func_renamer('descr_' + opname)
355 def descr_binop(self, space, w_other):
356 if isinstance(w_other, W_IntObject):
357 return int_func(self, space, w_other.int_w(space))
358 elif not isinstance(w_other, W_AbstractLongObject):
359 return space.w_NotImplemented
360 return func(self, space, w_other)
361
362 @delegate_other
363 @func_renamer('descr_r' + opname)
364 def descr_rbinop(self, space, w_other):
365 if not isinstance(w_other, W_LongObject):
366 # coerce other W_AbstractLongObjects
367 w_other = W_LongObject(w_other.asbigint())
368 return func(w_other, space, self)
369
370 return descr_binop, descr_rbinop
371
372 def _lshift(self, space, w_other):
373 if w_other.asbigint().get_sign() < 0:
374 raise oefmt(space.w_ValueError, "negative shift count")
375 try:
376 shift = w_other.asbigint().toint()
377 except OverflowError: # b too big
378 if self.num.get_sign() == 0:
379 return self
380 raise oefmt(space.w_OverflowError, "shift count too large")
381 return W_LongObject(self.num.lshift(shift))
382
383 def _int_lshift(self, space, other):
384 if other < 0:
385 raise oefmt(space.w_ValueError, "negative shift count")
386 return W_LongObject(self.num.lshift(other))
387
388 descr_lshift, descr_rlshift = _make_descr_binop(_lshift, _int_lshift)
389
390 def _rshift(self, space, w_other):
391 if w_other.asbigint().get_sign() < 0:
392 raise oefmt(space.w_ValueError, "negative shift count")
393 try:
394 shift = w_other.asbigint().toint()
395 except OverflowError:
396 if self.num.get_sign() < 0:
397 return space.newint(-1)
398 return space.newint(0)
399 raise oefmt(space.w_OverflowError, "shift count too large")
400 return newlong(space, self.num.rshift(shift))
401
402 def _int_rshift(self, space, other):
403 if other < 0:
404 raise oefmt(space.w_ValueError, "negative shift count")
405
406 return newlong(space, self.num.rshift(other))
407 descr_rshift, descr_rrshift = _make_descr_binop(_rshift, _int_rshift)
408
409 def _floordiv(self, space, w_other):
410 try:
411 z = self.num.floordiv(w_other.asbigint())
412 except ZeroDivisionError:
413 raise oefmt(space.w_ZeroDivisionError,
414 "long division or modulo by zero")
415 return newlong(space, z)
416
417 def _int_floordiv(self, space, other):
418 try:
419 z = self.num.int_floordiv(other)
420 except ZeroDivisionError:
421 raise oefmt(space.w_ZeroDivisionError,
422 "integer division or modulo by zero")
423 return newlong(space, z)
424 descr_floordiv, descr_rfloordiv = _make_descr_binop(_floordiv, _int_floordiv)
425
426 def _mod(self, space, w_other):
427 try:
428 z = self.num.mod(w_other.asbigint())
429 except ZeroDivisionError:
430 raise oefmt(space.w_ZeroDivisionError,
431 "integer division or modulo by zero")
432 return newlong(space, z)
433
434 def _int_mod(self, space, other):
435 try:
436 z = self.num.int_mod_int_result(other)
437 except ZeroDivisionError:
438 raise oefmt(space.w_ZeroDivisionError,
439 "long division or modulo by zero")
440 return space.newint(z)
441 descr_mod, descr_rmod = _make_descr_binop(_mod, _int_mod)
442
443 def _divmod(self, space, w_other):
444 try:
445 div, mod = self.num.divmod(w_other.asbigint())
446 except ZeroDivisionError:
447 raise oefmt(space.w_ZeroDivisionError,
448 "integer division or modulo by zero")
449 return space.newtuple2(newlong(space, div), newlong(space, mod))
450
451 def _int_divmod(self, space, other):
452 try:
453 div, mod = self.num.int_divmod(other)
454 except ZeroDivisionError:
455 raise oefmt(space.w_ZeroDivisionError,
456 "long division or modulo by zero")
457 return space.newtuple2(newlong(space, div), newlong(space, mod))
458
459 descr_divmod, descr_rdivmod = _make_descr_binop(_divmod, _int_divmod)
460
461
462 # In _hash_long we would like to shift intermediate results by SHIFT.
463 # Since HASH_MODULUS is a Mersenne prime, the result is congruent
464 # to shifting by (SHIFT % HASH_BITS). A smaller shift amount lets
465 # us apply extra optimizations to the hash function.
466 _HASH_SHIFT = SHIFT % HASH_BITS
467
468 @jit.elidable
469 def _hash_long(v):
470 i = v.numdigits() - 1
471 if i == -1:
472 return 0
473
474 # compute v % HASH_MODULUS
475 x = _load_unsigned_digit(0)
476 while i >= 0:
477 # This computes (x << _HASH_SHIFT) + v.udigit(i) modulo HASH_MODULUS
478 # efficiently and without overflow, as HASH_MODULUS is a Mersenne
479 # prime. See detailed explanation in CPython function long_hash
480 # in longobject.c.
481 # Basically, to compute (x << _HASH_SHIFT) modulo HASH_MODULUS,
482 # we rotate it left by _HASH_SHIFT. Then, if SHIFT <= HASH_BITS,
483 # after adding v.udigit(i), the result is at most 2*HASH_MODULUS-1.
484 x = ((x << _HASH_SHIFT) & HASH_MODULUS) + (x >> HASH_BITS - _HASH_SHIFT)
485 x += v.udigit(i)
486 if SHIFT > HASH_BITS:
487 x = (x & HASH_MODULUS) + (x >> HASH_BITS)
488 if x >= HASH_MODULUS:
489 x -= HASH_MODULUS
490 i -= 1
491 h = intmask(intmask(x) * v.get_sign())
492 return h - (h == -1)
493
494
495 def newlong(space, bigint):
496 """Turn the bigint into a W_LongObject. If withsmalllong is
497 enabled, check if the bigint would fit in a smalllong, and return a
498 W_SmallLongObject instead if it does.
499 """
500 if space.config.objspace.std.withsmalllong:
501 try:
502 z = bigint.tolonglong()
503 except OverflowError:
504 pass
505 else:
506 from pypy.objspace.std.smalllongobject import W_SmallLongObject
507 return W_SmallLongObject(z)
508 return W_LongObject(bigint)
509
510
511 def newlong_from_float(space, floatval):
512 """Return a W_LongObject from an RPython float.
513
514 Raises app-level exceptions on failure.
515 """
516 try:
517 return W_LongObject.fromfloat(space, floatval)
518 except OverflowError:
519 raise oefmt(space.w_OverflowError,
520 "cannot convert float infinity to integer")
521 except ValueError:
522 raise oefmt(space.w_ValueError, "cannot convert float NaN to integer")
523
524
525 def newbigint(space, w_longtype, bigint):
526 """Turn the bigint into a W_LongObject. If withsmalllong is enabled,
527 check if the bigint would fit in a smalllong, and return a
528 W_SmallLongObject instead if it does. Similar to newlong() in
529 longobject.py, but takes an explicit w_longtype argument.
530 """
531 if (space.config.objspace.std.withsmalllong
532 and space.is_w(w_longtype, space.w_int)):
533 try:
534 z = bigint.tolonglong()
535 except OverflowError:
536 pass
537 else:
538 from pypy.objspace.std.smalllongobject import W_SmallLongObject
539 return W_SmallLongObject(z)
540 w_obj = space.allocate_instance(W_LongObject, w_longtype)
541 W_LongObject.__init__(w_obj, bigint)
542 return w_obj