Debian Codegraph @

pypy/module/cpyext/number.py

raw symbols SCIP
1 from pypy.interpreter.error import OperationError, oefmt
2 from pypy.module.cpyext.api import (
3 cpython_api, CANNOT_FAIL, Py_ssize_t, PyVarObject, PY_SSIZE_T_MAX,
4 PY_SSIZE_T_MIN)
5 from pypy.module.cpyext.pyobject import PyObject, PyObjectP, from_ref, make_ref
6 from rpython.rtyper.lltypesystem import rffi, lltype
7 from rpython.rlib.rarithmetic import widen
8 from rpython.tool.sourcetools import func_with_new_name
9 from pypy.objspace.std import newformat
10
11 @cpython_api([PyObject, PyObject], Py_ssize_t, error=-1)
12 def PyNumber_AsSsize_t(space, w_obj, w_exc):
13 """Returns o converted to a Py_ssize_t value if o can be interpreted as an
14 integer. If o can be converted to a Python int or long but the attempt to
15 convert to a Py_ssize_t value would raise an OverflowError, then the
16 exc argument is the type of exception that will be raised (usually
17 IndexError or OverflowError). If exc is NULL, then the
18 exception is cleared and the value is clipped to PY_SSIZE_T_MIN for a negative
19 integer or PY_SSIZE_T_MAX for a positive integer.
20 """
21 try:
22 return space.int_w(w_obj) #XXX: this is wrong on win64
23 except OperationError as e:
24 if e.match(space, space.w_OverflowError):
25 if not w_exc:
26 if space.isinstance_w(w_obj, space.w_long):
27 if w_obj.bigint_w(space).get_sign() < 0:
28 return PY_SSIZE_T_MIN
29 else:
30 return PY_SSIZE_T_MAX
31 # XXX not sure this is ever reached?
32 # CPython does _PyLong_Sign(value) < 0 which is equivalent to
33 # Py_SIZE(value) < 0 which is value->ob_size
34 pyobj = make_ref(space, w_obj)
35 if rffi.cast(PyVarObject, pyobj).c_ob_size < 0:
36 return PY_SSIZE_T_MIN
37 else:
38 return PY_SSIZE_T_MAX
39 else:
40 raise oefmt(w_exc, "cannot fit '%T' into an index-sized integer", w_obj)
41 else:
42 raise
43
44 @cpython_api([PyObject], PyObject)
45 def PyNumber_Long(space, w_obj):
46 """Returns the o converted to a long integer object on success, or NULL on
47 failure. This is the equivalent of the Python expression long(o)."""
48 return space.call_function(space.w_int, w_obj)
49
50 @cpython_api([PyObject], PyObject)
51 def PyNumber_Index(space, w_obj):
52 """Returns the o converted to a Python int or long on success or NULL with a
53 TypeError exception raised on failure.
54 """
55 return space.index(w_obj)
56
57 @cpython_api([PyObject, rffi.INT_real], PyObject)
58 def PyNumber_ToBase(space, w_obj, base):
59 """Returns the integer n converted to base as a string with a base
60 marker of '0b', '0o', or '0x' if applicable. When
61 base is not 2, 8, 10, or 16, the format is 'x#num' where x is the
62 base. If n is not an int object, it is converted with
63 PyNumber_Index() first.
64 """
65 base = widen(base)
66 if not (base == 2 or base == 8 or base == 10 or base ==16):
67 # In Python3.7 this becomes a SystemError. Before that, CPython would
68 # assert in debug or segfault in release. bpo 38643
69 raise oefmt(space.w_SystemError,
70 "PyNumber_ToBase: base must be 2, 8, 10 or 16")
71 w_index = space.index(w_obj)
72 # A slight hack to call the internal _*_to_base method, which
73 # accepts an int base rather than a str spec
74 formatter = newformat.unicode_formatter(space, '')
75 try:
76 value = space.int_w(w_index)
77 except OperationError as e:
78 if not e.match(space, space.w_OverflowError):
79 raise
80 value = space.bigint_w(w_index)
81 return space.newtext(formatter._long_to_base(base, value))
82 return space.newtext(formatter._int_to_base(base, value))
83
84
85 def func_rename(newname):
86 return lambda func: func_with_new_name(func, newname)
87
88 def make_numbermethod(cname, spacemeth):
89 @cpython_api([PyObject, PyObject], PyObject)
90 @func_rename(cname)
91 def PyNumber_Method(space, w_o1, w_o2):
92 meth = getattr(space, spacemeth)
93 return meth(w_o1, w_o2)
94 return PyNumber_Method
95
96 def make_unary_numbermethod(name, spacemeth):
97 @cpython_api([PyObject], PyObject)
98 @func_rename(cname)
99 def PyNumber_Method(space, w_o1):
100 meth = getattr(space, spacemeth)
101 return meth(w_o1)
102 return PyNumber_Method
103
104 def make_inplace_numbermethod(cname, spacemeth):
105 spacemeth = 'inplace_' + spacemeth.rstrip('_')
106 @cpython_api([PyObject, PyObject], PyObject)
107 @func_rename(cname)
108 def PyNumber_Method(space, w_o1, w_o2):
109 meth = getattr(space, spacemeth)
110 return meth(w_o1, w_o2)
111 return PyNumber_Method
112
113 for name, spacemeth in [
114 ('Add', 'add'),
115 ('Subtract', 'sub'),
116 ('Multiply', 'mul'),
117 ('Divide', 'div'),
118 ('FloorDivide', 'floordiv'),
119 ('TrueDivide', 'truediv'),
120 ('Remainder', 'mod'),
121 ('Lshift', 'lshift'),
122 ('Rshift', 'rshift'),
123 ('And', 'and_'),
124 ('Xor', 'xor'),
125 ('Or', 'or_'),
126 ('Divmod', 'divmod'),
127 ('MatrixMultiply', 'matmul')]:
128 cname = 'PyNumber_%s' % (name,)
129 globals()[cname] = make_numbermethod(cname, spacemeth)
130 if name != 'Divmod':
131 cname = 'PyNumber_InPlace%s' % (name,)
132 globals()[cname] = make_inplace_numbermethod(cname, spacemeth)
133
134 for name, spacemeth in [
135 ('Negative', 'neg'),
136 ('Positive', 'pos'),
137 ('Absolute', 'abs'),
138 ('Invert', 'invert')]:
139 cname = 'PyNumber_%s' % (name,)
140 globals()[cname] = make_unary_numbermethod(cname, spacemeth)
141
142 @cpython_api([PyObject, PyObject, PyObject], PyObject)
143 def PyNumber_Power(space, w_o1, w_o2, w_o3):
144 return space.pow(w_o1, w_o2, w_o3)
145
146 @cpython_api([PyObject, PyObject, PyObject], PyObject)
147 def PyNumber_InPlacePower(space, w_o1, w_o2, w_o3):
148 if not space.is_w(w_o3, space.w_None):
149 raise oefmt(space.w_ValueError,
150 "PyNumber_InPlacePower with non-None modulus is not "
151 "supported")
152 return space.inplace_pow(w_o1, w_o2)