Debian Codegraph @

pypy/module/cpyext/object.py

raw symbols SCIP
1 from rpython.rtyper.lltypesystem import rffi, lltype
2 from rpython.rlib.rarithmetic import widen
3 from pypy.module.cpyext.api import (
4 cpython_api, generic_cpy_call, CANNOT_FAIL, Py_ssize_t,
5 PyVarObject, size_t, slot_function, cts,
6 Py_TPFLAGS_HEAPTYPE, Py_LT, Py_LE, Py_EQ, Py_NE, Py_GT,
7 Py_GE, CONST_STRING, FILEP, fwrite, c_only, PY_SSIZE_T_MAX)
8 from pypy.module.cpyext.pyobject import (
9 PyObject, PyObjectP, from_ref, incref, decref,
10 get_typedescr, hack_for_result_often_existing_obj)
11 from pypy.module.cpyext.pyerrors import PyErr_NoMemory, PyErr_BadInternalCall
12 from pypy.objspace.std.bytesobject import invoke_bytes_method
13 from pypy.interpreter.error import OperationError, oefmt
14 from pypy.interpreter.executioncontext import ExecutionContext
15 import pypy.module.__builtin__.operation as operation
16
17
18 @cpython_api([size_t], rffi.VOIDP)
19 def PyObject_Malloc(space, size):
20 # returns non-zero-initialized memory, like CPython
21 return lltype.malloc(rffi.VOIDP.TO, size,
22 flavor='raw',
23 add_memory_pressure=True)
24
25 @cpython_api([size_t, size_t], rffi.VOIDP)
26 def PyObject_Calloc(space, nelem, elsize):
27 if elsize != 0 and nelem > PY_SSIZE_T_MAX / elsize:
28 return lltype.nullptr(rffi.VOIDP.TO)
29 return lltype.malloc(rffi.VOIDP.TO, nelem * elsize,
30 flavor='raw', zero=True,
31 add_memory_pressure=True)
32
33 realloc = rffi.llexternal('realloc', [rffi.VOIDP, rffi.SIZE_T], rffi.VOIDP)
34
35 @cpython_api([rffi.VOIDP, size_t], rffi.VOIDP)
36 def PyObject_Realloc(space, ptr, size):
37 if not lltype.cast_ptr_to_int(ptr):
38 return lltype.malloc(rffi.VOIDP.TO, size,
39 flavor='raw',
40 add_memory_pressure=True)
41 # XXX FIXME
42 return realloc(ptr, size)
43
44 @c_only([rffi.VOIDP], lltype.Void)
45 def _PyPy_Free(ptr):
46 lltype.free(ptr, flavor='raw')
47
48 @c_only([Py_ssize_t], rffi.VOIDP)
49 def _PyPy_Malloc(size):
50 # XXX: the malloc inside BaseCpyTypedescr.allocate and
51 # typeobject.type_alloc specify zero=True, so this is why we use it also
52 # here. However, CPython does a simple non-initialized malloc, so we
53 # should investigate whether we can remove zero=True as well
54 return lltype.malloc(rffi.VOIDP.TO, size,
55 flavor='raw', zero=True,
56 add_memory_pressure=True)
57
58
59 def _dealloc(space, obj):
60 # This frees an object after its refcount dropped to zero, so we
61 # assert that it is really zero here.
62 assert obj.c_ob_refcnt == 0
63 pto = obj.c_ob_type
64 obj_voidp = rffi.cast(rffi.VOIDP, obj)
65 try:
66 generic_cpy_call(space, pto.c_tp_free, obj_voidp)
67 finally:
68 if widen(pto.c_tp_flags) & Py_TPFLAGS_HEAPTYPE:
69 decref(space, rffi.cast(PyObject, pto))
70
71 @cpython_api([PyObject], PyObjectP, error=CANNOT_FAIL)
72 def _PyObject_GetDictPtr(space, op):
73 return lltype.nullptr(PyObjectP.TO)
74
75 @cpython_api([PyObject], rffi.INT_real, error=-1)
76 def PyObject_IsTrue(space, w_obj):
77 return space.is_true(w_obj)
78
79 @cpython_api([PyObject], rffi.INT_real, error=-1)
80 def PyObject_Not(space, w_obj):
81 return not space.is_true(w_obj)
82
83 @cpython_api([PyObject, PyObject], PyObject, result_is_ll=True)
84 def PyObject_GetAttr(space, w_obj, w_name):
85 """Retrieve an attribute named attr_name from object o. Returns the attribute
86 value on success, or NULL on failure. This is the equivalent of the Python
87 expression o.attr_name."""
88 w_res = space.getattr(w_obj, w_name)
89 return hack_for_result_often_existing_obj(space, w_res)
90
91 @cpython_api([PyObject, CONST_STRING], PyObject, result_is_ll=True)
92 def PyObject_GetAttrString(space, w_obj, name_ptr):
93 """Retrieve an attribute named attr_name from object o. Returns the attribute
94 value on success, or NULL on failure. This is the equivalent of the Python
95 expression o.attr_name."""
96 name = rffi.charp2str(name_ptr)
97 w_res = space.getattr(w_obj, space.newtext(name))
98 return hack_for_result_often_existing_obj(space, w_res)
99
100 @cpython_api([PyObject, PyObject], rffi.INT_real, error=CANNOT_FAIL)
101 def PyObject_HasAttr(space, w_obj, w_name):
102 try:
103 w_res = operation.hasattr(space, w_obj, w_name)
104 return space.is_true(w_res)
105 except OperationError:
106 return 0
107
108 @cpython_api([PyObject, CONST_STRING], rffi.INT_real, error=CANNOT_FAIL)
109 def PyObject_HasAttrString(space, w_obj, name_ptr):
110 try:
111 name = rffi.charp2str(name_ptr)
112 w_res = operation.hasattr(space, w_obj, space.newtext(name))
113 return space.is_true(w_res)
114 except OperationError:
115 return 0
116
117 @cpython_api([PyObject, PyObject, PyObject], rffi.INT_real, error=-1)
118 def PyObject_SetAttr(space, w_obj, w_name, value):
119 if value:
120 w_value = from_ref(space, value)
121 operation.setattr(space, w_obj, w_name, w_value)
122 else:
123 space.delattr(w_obj, w_name)
124 return 0
125
126 @cpython_api([PyObject, CONST_STRING, PyObject], rffi.INT_real, error=-1)
127 def PyObject_SetAttrString(space, w_obj, name_ptr, value):
128 w_name = space.newtext(rffi.charp2str(name_ptr))
129 if value:
130 w_value = from_ref(space, value)
131 operation.setattr(space, w_obj, w_name, w_value)
132 else:
133 space.delattr(w_obj, w_name)
134 return 0
135
136 @cpython_api([PyObject], lltype.Void)
137 def PyObject_ClearWeakRefs(space, w_object):
138 w_object.clear_all_weakrefs()
139
140 @cpython_api([PyObject], Py_ssize_t, error=-1)
141 def PyObject_Size(space, w_obj):
142 return space.len_w(w_obj)
143
144 @cpython_api([PyObject], rffi.INT_real, error=CANNOT_FAIL)
145 def PyCallable_Check(space, w_obj):
146 """Determine if the object o is callable. Return 1 if the object is callable
147 and 0 otherwise. This function always succeeds."""
148 return int(space.is_true(space.callable(w_obj)))
149
150 @cpython_api([PyObject, PyObject], PyObject, result_is_ll=True)
151 def PyObject_GetItem(space, w_obj, w_key):
152 """Return element of o corresponding to the object key or NULL on failure.
153 This is the equivalent of the Python expression o[key]."""
154 w_res = space.getitem(w_obj, w_key)
155 return hack_for_result_often_existing_obj(space, w_res)
156
157 @cpython_api([PyObject, PyObject, PyObject], rffi.INT_real, error=-1)
158 def PyObject_SetItem(space, w_obj, w_key, w_value):
159 """Map the object key to the value v. Returns -1 on failure. This is the
160 equivalent of the Python statement o[key] = v."""
161 space.setitem(w_obj, w_key, w_value)
162 return 0
163
164 @cpython_api([PyObject, PyObject], rffi.INT_real, error=-1)
165 def PyObject_DelItem(space, w_obj, w_key):
166 """Delete the mapping for key from o. Returns -1 on failure. This is the
167 equivalent of the Python statement del o[key]."""
168 space.delitem(w_obj, w_key)
169 return 0
170
171 @cpython_api([PyObject], PyObject)
172 def PyObject_Type(space, w_obj):
173 """When o is non-NULL, returns a type object corresponding to the object type
174 of object o. On failure, raises SystemError and returns NULL. This
175 is equivalent to the Python expression type(o). This function increments the
176 reference count of the return value. There's really no reason to use this
177 function instead of the common expression o->ob_type, which returns a
178 pointer of type PyTypeObject*, except when the incremented reference
179 count is needed."""
180 return space.type(w_obj)
181
182 @cpython_api([PyObject], PyObject)
183 def PyObject_Str(space, w_obj):
184 if w_obj is None:
185 return space.newtext("<NULL>")
186 return space.str(w_obj)
187
188 @cts.decl("PyObject * PyObject_Bytes(PyObject *v)")
189 def PyObject_Bytes(space, w_obj):
190 from pypy.module.cpyext.bytesobject import PyBytes_FromObject
191 if w_obj is None:
192 return space.newbytes("<NULL>")
193 if space.type(w_obj) is space.w_bytes:
194 return w_obj
195 w_result = invoke_bytes_method(space, w_obj)
196 if w_result is not None:
197 return w_result
198 return PyBytes_FromObject(space, w_obj)
199
200 @cpython_api([PyObject], PyObject)
201 def PyObject_Repr(space, w_obj):
202 """Compute a string representation of object o. Returns the string
203 representation on success, NULL on failure. This is the equivalent of the
204 Python expression repr(o). Called by the repr() built-in function and
205 by reverse quotes."""
206 if w_obj is None:
207 return space.newtext("<NULL>")
208 return space.repr(w_obj)
209
210 @cpython_api([PyObject, PyObject], PyObject)
211 def PyObject_Format(space, w_obj, w_format_spec):
212 if w_format_spec is None:
213 w_format_spec = space.newtext('')
214 # issue 3404: handle PyObject_Format(type('a'), '')
215 if (space.isinstance_w(w_format_spec, space.w_unicode) and
216 space.len_w(w_format_spec) == 0):
217 return space.unicode_from_object(w_obj)
218 w_ret = space.call_method(w_obj, '__format__', w_format_spec)
219 if space.isinstance_w(w_format_spec, space.w_unicode):
220 return space.unicode_from_object(w_ret)
221 return w_ret
222
223 @cpython_api([PyObject], PyObject)
224 def PyObject_ASCII(space, w_obj):
225 r"""As PyObject_Repr(), compute a string representation of object
226 o, but escape the non-ASCII characters in the string returned by
227 PyObject_Repr() with \x, \u or \U escapes. This generates a
228 string similar to that returned by PyObject_Repr() in Python 2.
229 Called by the ascii() built-in function."""
230 return operation.ascii(space, w_obj)
231
232 @cpython_api([PyObject], PyObject)
233 def PyObject_Unicode(space, w_obj):
234 """Compute a Unicode string representation of object o. Returns the Unicode
235 string representation on success, NULL on failure. This is the equivalent of
236 the Python expression unicode(o). Called by the unicode() built-in
237 function."""
238 if w_obj is None:
239 return space.newutf8("<NULL>", 6)
240 return space.call_function(space.w_unicode, w_obj)
241
242 @cpython_api([PyObject, PyObject, rffi.INT_real], PyObject)
243 def PyObject_RichCompare(space, w_o1, w_o2, opid_int):
244 """Compare the values of o1 and o2 using the operation specified by opid,
245 which must be one of Py_LT, Py_LE, Py_EQ,
246 Py_NE, Py_GT, or Py_GE, corresponding to <,
247 <=, ==, !=, >, or >= respectively. This is the equivalent of
248 the Python expression o1 op o2, where op is the operator corresponding
249 to opid. Returns the value of the comparison on success, or NULL on failure."""
250 opid = rffi.cast(lltype.Signed, opid_int)
251 if opid == Py_LT: return space.lt(w_o1, w_o2)
252 if opid == Py_LE: return space.le(w_o1, w_o2)
253 if opid == Py_EQ: return space.eq(w_o1, w_o2)
254 if opid == Py_NE: return space.ne(w_o1, w_o2)
255 if opid == Py_GT: return space.gt(w_o1, w_o2)
256 if opid == Py_GE: return space.ge(w_o1, w_o2)
257 PyErr_BadInternalCall(space)
258
259 @cpython_api([PyObject, PyObject, rffi.INT_real], rffi.INT_real, error=-1)
260 def PyObject_RichCompareBool(space, w_o1, w_o2, opid_int):
261 """Compare the values of o1 and o2 using the operation specified by opid,
262 which must be one of Py_LT, Py_LE, Py_EQ,
263 Py_NE, Py_GT, or Py_GE, corresponding to <,
264 <=, ==, !=, >, or >= respectively. Returns -1 on error,
265 0 if the result is false, 1 otherwise. This is the equivalent of the
266 Python expression o1 op o2, where op is the operator corresponding to
267 opid."""
268 # Quick result when objects are the same.
269 # Guarantees that identity implies equality.
270 if space.is_w(w_o1, w_o2):
271 opid = rffi.cast(lltype.Signed, opid_int)
272 if opid == Py_EQ:
273 return 1
274 if opid == Py_NE:
275 return 0
276 w_res = PyObject_RichCompare(space, w_o1, w_o2, opid_int)
277 return int(space.is_true(w_res))
278
279 @cpython_api([PyObject], PyObject, result_is_ll=True)
280 def PyObject_SelfIter(space, ref):
281 """Undocumented function, this is what CPython does."""
282 incref(space, ref)
283 return ref
284
285 @cpython_api([PyObject, PyObject], PyObject)
286 def PyObject_GenericGetAttr(space, w_obj, w_name):
287 """Generic attribute getter function that is meant to be put into a type
288 object's tp_getattro slot. It looks for a descriptor in the dictionary
289 of classes in the object's MRO as well as an attribute in the object's
290 __dict__ (if present). As outlined in descriptors, data
291 descriptors take preference over instance attributes, while non-data
292 descriptors don't. Otherwise, an AttributeError is raised."""
293 from pypy.objspace.descroperation import object_getattribute
294 w_descr = object_getattribute(space)
295 return space.get_and_call_function(w_descr, w_obj, w_name)
296
297 @cpython_api([PyObject, PyObject, PyObject], rffi.INT_real, error=-1)
298 def PyObject_GenericSetAttr(space, w_obj, w_name, w_value):
299 """Generic attribute setter function that is meant to be put into a type
300 object's tp_setattro slot. It looks for a data descriptor in the
301 dictionary of classes in the object's MRO, and if found it takes preference
302 over setting the attribute in the instance dictionary. Otherwise, the
303 attribute is set in the object's __dict__ (if present). Otherwise,
304 an AttributeError is raised and -1 is returned."""
305 from pypy.objspace.descroperation import object_setattr, object_delattr
306 if w_value is not None:
307 w_descr = object_setattr(space)
308 space.get_and_call_function(w_descr, w_obj, w_name, w_value)
309 else:
310 w_descr = object_delattr(space)
311 space.get_and_call_function(w_descr, w_obj, w_name)
312 return 0
313
314 @cpython_api([PyObject, PyObject], rffi.INT_real, error=-1)
315 def PyObject_IsInstance(space, w_inst, w_cls):
316 """Returns 1 if inst is an instance of the class cls or a subclass of
317 cls, or 0 if not. On error, returns -1 and sets an exception. If
318 cls is a type object rather than a class object, PyObject_IsInstance()
319 returns 1 if inst is of type cls. If cls is a tuple, the check will
320 be done against every entry in cls. The result will be 1 when at least one
321 of the checks returns 1, otherwise it will be 0. If inst is not a class
322 instance and cls is neither a type object, nor a class object, nor a
323 tuple, inst must have a __class__ attribute --- the class relationship
324 of the value of that attribute with cls will be used to determine the result
325 of this function."""
326 from pypy.module.__builtin__.abstractinst import abstract_isinstance_w
327 return abstract_isinstance_w(space, w_inst, w_cls, allow_override=True)
328
329 @cpython_api([PyObject, PyObject], rffi.INT_real, error=-1)
330 def PyObject_IsSubclass(space, w_derived, w_cls):
331 """Returns 1 if the class derived is identical to or derived from the class
332 cls, otherwise returns 0. In case of an error, returns -1. If cls
333 is a tuple, the check will be done against every entry in cls. The result will
334 be 1 when at least one of the checks returns 1, otherwise it will be
335 0. If either derived or cls is not an actual class object (or tuple),
336 this function uses the generic algorithm described above."""
337 from pypy.module.__builtin__.abstractinst import abstract_issubclass_w
338 return abstract_issubclass_w(space, w_derived, w_cls, allow_override=True)
339
340 @cpython_api([PyObject], rffi.INT_real, error=-1)
341 def PyObject_AsFileDescriptor(space, w_obj):
342 """Derives a file descriptor from a Python object. If the object is an
343 integer or long integer, its value is returned. If not, the object's
344 fileno() method is called if it exists; the method must return an integer or
345 long integer, which is returned as the file descriptor value. Returns -1 on
346 failure."""
347 try:
348 fd = space.int_w(w_obj)
349 except OperationError:
350 try:
351 w_meth = space.getattr(w_obj, space.newtext('fileno'))
352 except OperationError:
353 raise oefmt(space.w_TypeError,
354 "argument must be an int, or have a fileno() method.")
355 else:
356 w_fd = space.call_function(w_meth)
357 fd = space.int_w(w_fd)
358
359 if fd < 0:
360 raise oefmt(space.w_ValueError,
361 "file descriptor cannot be a negative integer")
362
363 return rffi.cast(rffi.INT_real, fd)
364
365
366 @cpython_api([PyObject], lltype.Signed, error=-1)
367 def PyObject_Hash(space, pyobj):
368 """
369 Compute and return the hash value of an object o. On failure, return -1.
370 This is the equivalent of the Python expression hash(o)."""
371
372 from pypy.module.cpyext.typeobject import py_type_ready
373 py_type_ready(space, pyobj.c_ob_type)
374 w_obj = from_ref(space, pyobj)
375 return space.hash_w(w_obj)
376
377 @cpython_api([PyObject, rffi.DOUBLE], lltype.Signed, error=-1)
378 def _Py_HashDouble(space, w_obj, v):
379 """Specific function for double, in CPython this uses the value of v
380 except for nans
381 """
382 from pypy.objspace.std.floatobject import float_hash
383 return space.int_w(float_hash(space, w_obj, v))
384
385 @cpython_api([PyObject], lltype.Signed, error=-1)
386 def PyObject_HashNotImplemented(space, o):
387 """Set a TypeError indicating that type(o) is not hashable and return -1.
388 This function receives special treatment when stored in a tp_hash slot,
389 allowing a type to explicitly indicate to the interpreter that it is not
390 hashable.
391 """
392 raise oefmt(space.w_TypeError, "unhashable type")
393
394 @cpython_api([PyObject], PyObject)
395 def PyObject_Dir(space, w_o):
396 """This is equivalent to the Python expression dir(o), returning a (possibly
397 empty) list of strings appropriate for the object argument, or NULL if there
398 was an error. If the argument is NULL, this is like the Python dir(),
399 returning the names of the current locals; in this case, if no execution frame
400 is active then NULL is returned but PyErr_Occurred() will return false."""
401 return space.call_function(space.builtin.get('dir'), w_o)
402
403 # Also in include/object.h
404 Py_PRINT_RAW = 1 # No string quotes etc.
405
406 @cpython_api([PyObject, FILEP, rffi.INT_real], rffi.INT_real, error=-1)
407 def PyObject_Print(space, pyobj, fp, flags):
408 """Print an object o, on file fp. Returns -1 on error. The flags argument
409 is used to enable certain printing options. The only option currently
410 supported is Py_PRINT_RAW; if given, the str() of the object is written
411 instead of the repr()."""
412 if not pyobj:
413 w_str = space.newtext("<nil>")
414 else:
415 w_obj = from_ref(space, pyobj)
416 if rffi.cast(lltype.Signed, flags) & Py_PRINT_RAW:
417 w_str = space.str(w_obj)
418 else:
419 w_str = space.repr(w_obj)
420
421 count = space.len_w(w_str)
422 data = space.text_w(w_str)
423 with rffi.scoped_nonmovingbuffer(data) as buf:
424 fwrite(buf, 1, count, fp)
425 return 0
426
427 @cts.decl("""
428 Py_ssize_t PyObject_LengthHint(PyObject *o, Py_ssize_t defaultvalue)""",
429 error=-1)
430 def PyObject_LengthHint(space, w_o, defaultvalue):
431 return space.length_hint(w_o, defaultvalue)
432
433 @cpython_api([lltype.Signed], lltype.Void)
434 def _PyPyGC_AddMemoryPressure(space, report):
435 from rpython.rlib import rgc
436 rgc.add_memory_pressure(report)
437
438
439 ExecutionContext.cpyext_recursive_repr = None
440
441 @cpython_api([PyObject], rffi.INT_real, error=-1)
442 def Py_ReprEnter(space, w_obj):
443 ec = space.getexecutioncontext()
444 d = ec.cpyext_recursive_repr
445 if d is None:
446 d = ec.cpyext_recursive_repr = {}
447 if w_obj in d:
448 return 1
449 d[w_obj] = None
450 return 0
451
452 @cpython_api([PyObject], lltype.Void)
453 def Py_ReprLeave(space, w_obj):
454 ec = space.getexecutioncontext()
455 d = ec.cpyext_recursive_repr
456 if d is not None:
457 try:
458 del d[w_obj]
459 except KeyError:
460 pass
461
462 @cpython_api([PyObject, rffi.VOIDP], PyObject)
463 def PyObject_GenericGetDict(space, w_obj, context):
464 from pypy.interpreter.typedef import descr_get_dict
465 return descr_get_dict(space, w_obj)
466
467 @cpython_api([PyObject, PyObject, rffi.VOIDP], rffi.INT_real, error=-1)
468 def PyObject_GenericSetDict(space, w_obj, w_value, context):
469 from pypy.interpreter.typedef import descr_set_dict
470 if w_value is None:
471 raise oefmt(space.w_TypeError, "cannot delete __dict__")
472 descr_set_dict(space, w_obj, w_value)
473 return 0
474
475 @cpython_api([], rffi.INT_real, error=CANNOT_FAIL)
476 def PyGC_IsEnabled(space):
477 import gc
478 return int(gc.isenabled())
479
480 @cpython_api([], rffi.INT_real, error=CANNOT_FAIL)
481 def PyGC_Disable(space):
482 import gc
483 ret = int(gc.isenabled())
484 gc.disable()
485 return ret
486
487 @cpython_api([], rffi.INT_real, error=CANNOT_FAIL)
488 def PyGC_Enable(space):
489 import gc
490 ret = int(gc.isenabled())
491 gc.enable()
492 return ret
493
494 @cpython_api([PyObject], rffi.INT_real, error=CANNOT_FAIL)
495 def PyObject_GC_IsTracked(space, w_obj):
496 """All objects in PyPy are tracked, this will always return 1
497 """
498 return 1
499
500 @cpython_api([PyObject], rffi.INT_real, error=CANNOT_FAIL)
501 def PyObject_GC_IsFinalized(space, w_obj):
502 """For now, always return 0
503 """
504 return 0
505
506 @cpython_api([PyObject, PyObject], rffi.INT_real, error=-1)
507 def Py_Is(space, w_obj1, w_obj2):
508 res = space.is_w(w_obj1, w_obj2)
509 return int(res)
510
511 @cpython_api([], rffi.INT_real, error = -1)
512 def PyGC_Collect(space):
513 from rpython.rlib.objectmodel import we_are_translated
514 from rpython.rlib import rawrefcount
515 from pypy.module.cpyext.state import _rawrefcount_perform
516 if not we_are_translated():
517 from pypy.module.gc.interp_gc import _run_finalizers
518 rawrefcount._collect()
519 _run_finalizers(space)
520 rawrefcount._collect()
521 else:
522 import gc
523 gc.collect()
524 _rawrefcount_perform(space)
525 return 0