Debian Codegraph @

pypy/module/cpyext/typeobject.py

raw symbols SCIP
1 from rpython.rlib.unroll import unrolling_iterable
2 from rpython.rlib import jit, rawrefcount
3 from rpython.rlib.objectmodel import specialize, we_are_translated
4 from rpython.rtyper.lltypesystem import rffi, lltype
5 from rpython.rlib.rarithmetic import widen
6
7 from pypy.interpreter.baseobjspace import DescrMismatch
8 from pypy.interpreter.error import oefmt
9 from pypy.interpreter.typedef import GetSetProperty, TypeDef, interp_attrproperty
10 from pypy.interpreter.gateway import interp2app
11 from pypy.module.__builtin__.abstractinst import abstract_issubclass_w
12 from pypy.module.cpyext import structmemberdefs
13 from pypy.module.cpyext.api import (
14 cpython_api, cpython_struct, bootstrap_function, Py_ssize_t,
15 slot_function, generic_cpy_call, METH_VARARGS, METH_KEYWORDS, CANNOT_FAIL,
16 build_type_checkers_flags, cts, parse_dir, PyTypeObject,
17 PyTypeObjectPtr, Py_buffer,
18 Py_TPFLAGS_HEAPTYPE, Py_TPFLAGS_READY, Py_TPFLAGS_READYING,
19 Py_TPFLAGS_LONG_SUBCLASS, Py_TPFLAGS_LIST_SUBCLASS,
20 Py_TPFLAGS_TUPLE_SUBCLASS, Py_TPFLAGS_UNICODE_SUBCLASS,
21 Py_TPFLAGS_DICT_SUBCLASS, Py_TPFLAGS_BASE_EXC_SUBCLASS,
22 Py_TPFLAGS_TYPE_SUBCLASS, Py_TPFLAGS_MANAGED_DICT, Py_TPFLAGS_MANAGED_WEAKREF,
23 Py_TPFLAGS_BYTES_SUBCLASS, Py_TPFLAGS_BASETYPE, Py_TPFLAGS_DISALLOW_INSTANTIATION,
24 Py_TPFLAGS_HAVE_VECTORCALL, Py_TPFLAGS_METHOD_DESCRIPTOR,
25 PyObject, PyVarObject,
26 )
27
28 from rpython.tool.cparser import CTypeSpace
29 from pypy.module.cpyext.methodobject import (W_PyCClassMethodObject,
30 PyCFunction, PyMethodDef,
31 W_PyCMethodObject, W_PyCFunctionObject, W_PyCWrapperObject)
32 from pypy.module.cpyext.modsupport import convert_method_defs
33 from pypy.module.cpyext.pyobject import (
34 make_ref, from_ref, get_typedescr, make_typedescr,
35 track_reference, decref, as_pyobj, incref)
36 from pypy.module.cpyext.slotdefs import (
37 slotdefs_for_tp_slots, slotdefs_for_wrappers, get_slot_tp_function,
38 llslot)
39 from pypy.module.cpyext.state import State
40 from pypy.module.cpyext.structmember import PyMember_GetOne, PyMember_SetOne
41 from pypy.module.cpyext.typeobjectdefs import (
42 PyGetSetDef, PyMemberDef, PyMappingMethods,
43 PyNumberMethods, PySequenceMethods, PyBufferProcs)
44 from pypy.objspace.std.typeobject import (W_TypeObject, find_best_base,
45 extract_doc, extract_txtsig)
46
47
48 #WARN_ABOUT_MISSING_SLOT_FUNCTIONS = False
49
50 PyType_Check, PyType_CheckExact = build_type_checkers_flags("Type")
51
52 PyHeapTypeObject = cts.gettype('PyHeapTypeObject *')
53
54 cts.parse_header(parse_dir / "typeslots.h")
55
56
57 class W_GetSetPropertyEx(GetSetProperty):
58 def __init__(self, getset, w_type):
59 self.getset = getset
60 self.w_type = w_type
61 doc = fset = fget = fdel = None
62 if getset.c_doc:
63 doc = rffi.constcharp2str(getset.c_doc)
64 if getset.c_get:
65 fget = GettersAndSetters.getter.im_func
66 if getset.c_set:
67 fset = GettersAndSetters.setter.im_func
68 fdel = GettersAndSetters.deleter.im_func
69 GetSetProperty.__init__(self, fget, fset, fdel, doc,
70 cls=None, use_closure=True,
71 tag="cpyext_1")
72 self.name = rffi.constcharp2str(getset.c_name)
73
74 def readonly_attribute(self, space): # overwritten
75 raise oefmt(space.w_AttributeError,
76 "attribute '%s' of '%N' objects is not writable",
77 self.name, self.w_type)
78
79
80 @cpython_api([PyTypeObjectPtr, lltype.Ptr(PyGetSetDef)], PyObject, result_is_ll=True)
81 def PyDescr_NewGetSet(space, w_type, getset):
82 # Note the arguments are reversed
83 w_descr = W_GetSetPropertyEx(getset, w_type)
84 return make_ref(space, w_descr, w_type)
85
86 def make_GetSet(space, getsetprop):
87 py_getsetdef = lltype.malloc(PyGetSetDef, flavor='raw')
88 doc = getsetprop.doc
89 if doc:
90 py_getsetdef.c_doc = rffi.cast(rffi.CONST_CCHARP, rffi.str2charp(doc))
91 else:
92 py_getsetdef.c_doc = rffi.cast(rffi.CONST_CCHARP, 0)
93 py_getsetdef.c_name = rffi.cast(rffi.CONST_CCHARP,
94 rffi.str2charp(getsetprop.getname(space)))
95 # XXX FIXME - actually assign these !!!
96 py_getsetdef.c_get = cts.cast('getter', 0)
97 py_getsetdef.c_set = cts.cast('setter', 0)
98 py_getsetdef.c_closure = cts.cast('void*', 0)
99 return py_getsetdef
100
101
102 class W_MemberDescr(GetSetProperty):
103 name = 'member_descriptor'
104 def __init__(self, member, w_type):
105 self.member = member
106 self.name = rffi.constcharp2str(member.c_name)
107 self.w_type = w_type
108 flags = rffi.cast(lltype.Signed, member.c_flags)
109 doc = set = None
110 if member.c_doc:
111 doc = rffi.constcharp2str(member.c_doc)
112 get = GettersAndSetters.member_getter.im_func
113 del_ = GettersAndSetters.member_delete.im_func
114 if not (flags & structmemberdefs.READONLY):
115 set = GettersAndSetters.member_setter.im_func
116 GetSetProperty.__init__(self, get, set, del_, doc,
117 cls=None, use_closure=True,
118 tag="cpyext_2")
119
120 # change the typedef name
121 W_MemberDescr.typedef = TypeDef(
122 "member_descriptor",
123 __get__ = interp2app(GetSetProperty.descr_property_get),
124 __set__ = interp2app(GetSetProperty.descr_property_set),
125 __delete__ = interp2app(GetSetProperty.descr_property_del),
126 __name__ = interp_attrproperty('name', cls=GetSetProperty,
127 wrapfn="newtext_or_none"),
128 __objclass__ = GetSetProperty(GetSetProperty.descr_get_objclass),
129 __doc__ = interp_attrproperty('doc', cls=GetSetProperty,
130 wrapfn="newtext_or_none"),
131 )
132 assert not W_MemberDescr.typedef.acceptable_as_base_class # no __new__
133
134 @bootstrap_function
135 def init_memberdescrobject(space):
136 make_typedescr(W_MemberDescr.typedef,
137 basestruct=cts.gettype('PyMemberDescrObject'),
138 attach=memberdescr_attach,
139 realize=memberdescr_realize,
140 dealloc=descr_dealloc,
141 )
142 make_typedescr(W_GetSetPropertyEx.typedef,
143 basestruct=cts.gettype('PyGetSetDescrObject'),
144 attach=getsetdescr_attach,
145 dealloc=descr_dealloc,
146 )
147 make_typedescr(W_PyCClassMethodObject.typedef,
148 basestruct=cts.gettype('PyMethodDescrObject'),
149 attach=methoddescr_attach,
150 realize=classmethoddescr_realize,
151 dealloc=descr_dealloc,
152 )
153 make_typedescr(W_PyCMethodObject.typedef,
154 basestruct=cts.gettype('PyMethodDescrObject'),
155 attach=methoddescr_attach,
156 realize=methoddescr_realize,
157 dealloc=descr_dealloc,
158 )
159 make_typedescr(W_PyCWrapperObject.typedef,
160 basestruct=cts.gettype('PyWrapperDescrObject'),
161 attach=wrapperdescr_attach,
162 realize=wrapperdescr_realize,
163 dealloc=wrapper_dealloc,
164 )
165
166 def init_descr(space, py_obj, w_type, name):
167 """Initialises the common fields in a PyDescrObject
168
169 Arguments:
170 py_obj: PyObject* pointer to a PyDescrObject
171 w_type: W_TypeObject
172 c_name: char*
173 """
174 py_descr = cts.cast('PyDescrObject*', py_obj)
175 py_descr.c_d_type = cts.cast(
176 'PyTypeObject*', make_ref(space, w_type))
177 py_descr.c_d_name = make_ref(space, space.newtext(name))
178
179 @slot_function([PyObject], lltype.Void)
180 def descr_dealloc(space, py_obj):
181 from pypy.module.cpyext.object import _dealloc
182 py_descr = cts.cast('PyDescrObject*', py_obj)
183 decref(space, py_descr.c_d_type)
184 decref(space, py_descr.c_d_name)
185 _dealloc(space, py_obj)
186
187 def memberdescr_attach(space, py_obj, w_obj, w_userdata=None):
188 """
189 Fills a newly allocated PyMemberDescrObject with the given W_MemberDescr
190 object. The values must not be modified.
191 """
192 py_memberdescr = cts.cast('PyMemberDescrObject*', py_obj)
193 assert isinstance(w_obj, W_MemberDescr)
194 py_memberdescr.c_d_member = w_obj.member
195 init_descr(space, py_obj, w_obj.w_type, w_obj.name)
196
197 def memberdescr_realize(space, obj):
198 # XXX NOT TESTED When is this ever called?
199 member = cts.cast('PyMemberDef*', obj)
200 w_type = from_ref(space, rffi.cast(PyObject, obj.c_ob_type))
201 w_obj = space.allocate_instance(W_MemberDescr, w_type)
202 w_obj.__init__(member, w_type)
203 track_reference(space, obj, w_obj)
204 return w_obj
205
206 def getsetdescr_attach(space, py_obj, w_obj, w_userdata=None):
207 """
208 Fills a newly allocated PyGetSetDescrObject with the given W_GetSetPropertyEx
209 object. The values must not be modified.
210 """
211 py_getsetdescr = cts.cast('PyGetSetDescrObject*', py_obj)
212 if not isinstance(w_obj, W_GetSetPropertyEx):
213 assert isinstance(w_obj, GetSetProperty)
214 py_getsetdef = make_GetSet(space, w_obj)
215 assert space.isinstance_w(w_userdata, space.w_type)
216 w_obj = W_GetSetPropertyEx(py_getsetdef, w_userdata)
217 # now w_obj.getset is py_getsetdef, which was freshly allocated
218 # XXX how is this ever released?
219 assert isinstance(w_obj, W_GetSetPropertyEx)
220 py_getsetdescr.c_d_getset = w_obj.getset
221 init_descr(space, py_obj, w_obj.w_type, w_obj.name)
222
223 def methoddescr_attach(space, py_obj, w_obj, w_userdata=None):
224 py_methoddescr = cts.cast('PyMethodDescrObject*', py_obj)
225 assert isinstance(w_obj, W_PyCFunctionObject)
226 py_methoddescr.c_d_method = w_obj.ml
227 init_descr(space, py_obj, w_obj.w_objclass, w_obj.name)
228
229 def classmethoddescr_realize(space, obj):
230 # XXX NOT TESTED When is this ever called?
231 method = rffi.cast(lltype.Ptr(PyMethodDef), obj)
232 w_type = from_ref(space, rffi.cast(PyObject, obj.c_ob_type))
233 w_obj = space.allocate_instance(W_PyCClassMethodObject, w_type)
234 assert isinstance(w_type, W_TypeObject)
235 w_obj.__init__(space, method, w_type, w_type.qualname)
236 track_reference(space, obj, w_obj)
237 return w_obj
238
239 def methoddescr_realize(space, obj):
240 # XXX NOT TESTED When is this ever called?
241 method = rffi.cast(lltype.Ptr(PyMethodDef), obj)
242 w_type = from_ref(space, rffi.cast(PyObject, obj.c_ob_type))
243 w_obj = space.allocate_instance(W_PyCMethodObject, w_type)
244 assert isinstance(w_type, W_TypeObject)
245 w_obj.__init__(space, method, None, None, w_type, w_type.qualname)
246 track_reference(space, obj, w_obj)
247 return w_obj
248
249 def wrapperdescr_attach(space, py_obj, w_obj, w_userdata=None):
250 assert isinstance(w_obj, W_PyCWrapperObject)
251 py_methoddescr = cts.cast('PyWrapperDescrObject*', py_obj)
252 init_descr(space, py_obj, w_obj.w_objclass, w_obj.getname(space))
253 py_methoddescr.c_d_wrapped = w_obj.get_func_to_call()
254 # CPython starts from the d_base, since this is the basic structure
255 # filled in by the slotdef macros in Objects/typeobject.c
256 # We only need it for compatibility, so we leave it all 0.
257 # see the way wrapperbase is modified in test/specmethdocstring.c,
258 # which adds a docstring to the slot function via d_base.doc
259 py_methoddescr.c_d_base = lltype.malloc(cts.gettype('struct wrapperbase'),
260 zero=True, flavor='raw', track_allocation=False)
261
262 def wrapperdescr_realize(space, obj):
263 raise oefmt(space.w_RuntimeError,
264 "cannot yet create a Python wrapper_descriptor from a C "
265 "PyWrapperDescrObject. Please report this to PyPy")
266
267 @slot_function([PyObject], lltype.Void)
268 def wrapper_dealloc(space, py_obj):
269 from pypy.module.cpyext.object import _dealloc
270 py_descr = cts.cast('PyDescrObject*', py_obj)
271 if py_descr:
272 decref(space, py_descr.c_d_type)
273 decref(space, py_descr.c_d_name)
274 py_wrapperdescr = cts.cast('PyWrapperDescrObject*', py_obj)
275 if py_wrapperdescr.c_d_base:
276 lltype.free(py_wrapperdescr.c_d_base, flavor="raw", track_allocation=False)
277 py_wrapperdescr.c_d_base = rffi.cast(cts.gettype('struct wrapperbase*'), 0)
278 _dealloc(space, py_obj)
279
280 def convert_getset_defs(space, dict_w, getsets, w_type):
281 getsets = rffi.cast(rffi.CArrayPtr(PyGetSetDef), getsets)
282 if getsets:
283 i = -1
284 while True:
285 i = i + 1
286 getset = getsets[i]
287 name = getset.c_name
288 if not name:
289 break
290 name = rffi.constcharp2str(name)
291 w_descr = W_GetSetPropertyEx(getset, w_type)
292 dict_w[name] = w_descr
293
294 def convert_member_defs(space, dict_w, members, w_type):
295 members = rffi.cast(rffi.CArrayPtr(PyMemberDef), members)
296 if members:
297 i = 0
298 while True:
299 member = members[i]
300 cname = member.c_name
301 if not cname:
302 break
303 name = rffi.constcharp2str(cname)
304 w_descr = W_MemberDescr(member, w_type)
305 dict_w[name] = w_descr
306 i += 1
307
308 WARN_MISSING_SLOTS = False
309 missing_slots={}
310 def warn_missing_slot(space, method_name, slot_name, w_type):
311 if WARN_MISSING_SLOTS and not we_are_translated():
312 if slot_name not in missing_slots:
313 missing_slots[slot_name] = w_type.getname(space)
314 print "missing slot %r/%r, discovered on %r" % (
315 method_name, slot_name, w_type.getname(space))
316
317 def update_all_slots(space, w_type, pto):
318 # fill slots in pto
319 for method_name, slot_name, slot_names, slot_apifunc in slotdefs_for_tp_slots:
320 slot_func_helper = None
321 w_descr = w_type.dict_w.get(method_name, None)
322 if w_descr:
323 # use the slot_apifunc (userslots) to lookup at runtime
324 pass
325 elif method_name == "__call__":
326 # 'inherit' from tp_base, but not __call__
327 continue
328 elif len(slot_names) ==1:
329 slot_func_helper = getattr(pto.c_tp_base, slot_names[0])
330 else:
331 struct = getattr(pto.c_tp_base, slot_names[0])
332 if struct:
333 slot_func_helper = getattr(struct, slot_names[1])
334
335 if not slot_func_helper:
336 if not slot_apifunc:
337 warn_missing_slot(space, method_name, slot_name, w_type)
338 continue
339 if not w_descr:
340 continue
341 slot_func_helper = slot_apifunc.get_llhelper(space)
342 fill_slot(space, pto, w_type, slot_names, slot_func_helper)
343
344 def update_all_slots_builtin(space, w_type, pto):
345 typedef = w_type.layout.typedef
346 for method_name, slot_name, slot_names, slot_apifunc in slotdefs_for_tp_slots:
347 slot_apifunc = get_slot_tp_function(space, typedef, slot_name, method_name)
348 if not slot_apifunc:
349 warn_missing_slot(space, method_name, slot_name, w_type)
350 continue
351 slot_llfunc = slot_apifunc.get_llhelper(space)
352 fill_slot(space, pto, w_type, slot_names, slot_llfunc)
353
354 @specialize.arg(3)
355 def fill_slot(space, pto, w_type, slot_names, slot_func_helper):
356 # XXX special case wrapper-functions and use a "specific" slot func
357 if len(slot_names) == 1:
358 setattr(pto, slot_names[0], slot_func_helper)
359 elif ((w_type is space.w_list or w_type is space.w_tuple) and
360 slot_names[0] == 'c_tp_as_number'):
361 # XXX hack - how can we generalize this? The problem is method
362 # names like __mul__ map to more than one slot, and we have no
363 # convenient way to indicate which slots CPython have filled
364 #
365 # We need at least this special case since Numpy checks that
366 # (list, tuple) do __not__ fill tp_as_number
367 pass
368 elif ((space.issubtype_w(w_type, space.w_bytes) or
369 space.issubtype_w(w_type, space.w_unicode)) and
370 slot_names[0] == 'c_tp_as_number'):
371 # like above but for any str type
372 pass
373 else:
374 assert len(slot_names) == 2
375 struct = getattr(pto, slot_names[0])
376 if not struct:
377 #assert not space.config.translating
378 assert not widen(pto.c_tp_flags) & Py_TPFLAGS_HEAPTYPE
379 if slot_names[0] == 'c_tp_as_number':
380 STRUCT_TYPE = PyNumberMethods
381 elif slot_names[0] == 'c_tp_as_sequence':
382 STRUCT_TYPE = PySequenceMethods
383 elif slot_names[0] == 'c_tp_as_buffer':
384 STRUCT_TYPE = PyBufferProcs
385 elif slot_names[0] == 'c_tp_as_mapping':
386 STRUCT_TYPE = PyMappingMethods
387 else:
388 raise AssertionError(
389 "Structure not allocated: %s" % (slot_names[0],))
390 struct = lltype.malloc(STRUCT_TYPE, flavor='raw', zero=True)
391 setattr(pto, slot_names[0], struct)
392
393 setattr(struct, slot_names[1], slot_func_helper)
394
395 def _add_operators(space, w_type, dict_w, pto, type_name):
396 from pypy.module.cpyext.object import PyObject_HashNotImplemented
397 hash_not_impl = llslot(space, PyObject_HashNotImplemented)
398 for method_name, slot_names, wrapper_class, doc in slotdefs_for_wrappers:
399 if method_name in dict_w:
400 continue
401 if len(slot_names) == 1:
402 func = getattr(pto, slot_names[0])
403 if slot_names[0] == 'c_tp_hash':
404 # two special cases where __hash__ is explicitly set to None
405 # (which leads to an unhashable type):
406 # 1) tp_hash == PyObject_HashNotImplemented
407 # 2) tp_hash == NULL and tp_richcompare not NULL
408 if hash_not_impl == func or (
409 not func and pto.c_tp_richcompare):
410 dict_w[method_name] = space.w_None
411 continue
412 else:
413 assert len(slot_names) == 2
414 struct = getattr(pto, slot_names[0])
415 if not struct:
416 continue
417 func = getattr(struct, slot_names[1])
418 func_voidp = rffi.cast(rffi.VOIDP, func)
419 if not func:
420 continue
421 if wrapper_class is None:
422 continue
423
424 assert issubclass(wrapper_class, W_PyCWrapperObject)
425
426 w_obj = wrapper_class(space, w_type, method_name, doc, func_voidp, type_name)
427 dict_w[method_name] = w_obj
428
429 @slot_function([PyObject, PyObject, PyObject], PyObject)
430 def tp_new_wrapper(space, self, w_args, w_kwds):
431 self_pytype = rffi.cast(PyTypeObjectPtr, self)
432 tp_new = self_pytype.c_tp_new
433
434 # Check that the user doesn't do something silly and unsafe like
435 # object.__new__(dict). To do this, we check that the most
436 # derived base that's not a heap type is this type.
437 # XXX do it
438
439 args_w = space.fixedview(w_args)
440 w_subtype = args_w[0]
441 w_args = space.newtuple(args_w[1:])
442 subtype = rffi.cast(PyTypeObjectPtr, make_ref(space, w_subtype))
443 try:
444 w_obj = generic_cpy_call(space, tp_new, subtype, w_args, w_kwds)
445 finally:
446 decref(space, subtype)
447 return w_obj
448
449 @specialize.memo()
450 def get_new_method_def(space):
451 state = space.fromcache(State)
452 if state.new_method_def:
453 return state.new_method_def
454 ptr = lltype.malloc(PyMethodDef, flavor="raw", zero=True,
455 immortal=True)
456 ptr.c_ml_name = rffi.cast(rffi.CONST_CCHARP, rffi.str2charp("__new__"))
457 lltype.render_immortal(ptr.c_ml_name)
458 rffi.setintfield(ptr, 'c_ml_flags', METH_VARARGS | METH_KEYWORDS)
459 ptr.c_ml_doc = rffi.cast(rffi.CONST_CCHARP, rffi.str2charp(
460 "Create and return a new object. "
461 "See help(type) for accurate signature."))
462 lltype.render_immortal(ptr.c_ml_doc)
463 state.new_method_def = ptr
464 return ptr
465
466 def setup_new_method_def(space):
467 ptr = get_new_method_def(space)
468 ptr.c_ml_meth = rffi.cast(PyCFunction, llslot(space, tp_new_wrapper))
469
470 @jit.dont_look_inside
471 def is_tp_new_wrapper(space, ml):
472 return ml.c_ml_meth == rffi.cast(PyCFunction, llslot(space, tp_new_wrapper))
473
474 def add_tp_new_wrapper(space, dict_w, pto):
475 if "__new__" in dict_w:
476 return
477 pyo = rffi.cast(PyObject, pto)
478 dict_w["__new__"] = W_PyCFunctionObject(space, get_new_method_def(space),
479 from_ref(space, pyo), None)
480
481 def add_disallow_new(space, dict_w, pto):
482 from typeobjectdefs import newfunc
483 dict_w["__new__"] = space.lookup(space.w_DisallowNew, '__new__')
484 pto.c_tp_new = rffi.cast(newfunc, 0)
485
486 def inherit_special(space, pto, w_obj, base_pto):
487 # if tp_basicsize is zero or too low, we copy it from the base
488 if pto.c_tp_basicsize < base_pto.c_tp_basicsize:
489 pto.c_tp_basicsize = base_pto.c_tp_basicsize
490 # tp_itemsize is set elsewhere
491
492 #/* Setup fast subclass flags */
493 flags = widen(pto.c_tp_flags)
494 if space.issubtype_w(w_obj, space.w_BaseException):
495 flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS
496 elif space.issubtype_w(w_obj, space.w_type):
497 flags |= Py_TPFLAGS_TYPE_SUBCLASS
498 elif space.issubtype_w(w_obj, space.w_int):
499 flags |= Py_TPFLAGS_LONG_SUBCLASS
500 elif space.issubtype_w(w_obj, space.w_bytes):
501 flags |= Py_TPFLAGS_BYTES_SUBCLASS
502 elif space.issubtype_w(w_obj, space.w_unicode):
503 flags |= Py_TPFLAGS_UNICODE_SUBCLASS
504 elif space.issubtype_w(w_obj, space.w_tuple):
505 flags |= Py_TPFLAGS_TUPLE_SUBCLASS
506 elif space.issubtype_w(w_obj, space.w_list):
507 flags |= Py_TPFLAGS_LIST_SUBCLASS
508 elif space.issubtype_w(w_obj, space.w_dict):
509 flags |= Py_TPFLAGS_DICT_SUBCLASS
510
511 # Inherit Py_TPFLAGS_METHOD_DESCRIPTOR for non-heap static types,
512 # but only when tp_descr_get is also inherited (not overridden).
513 if not (flags & Py_TPFLAGS_HEAPTYPE):
514 if widen(base_pto.c_tp_flags) & Py_TPFLAGS_METHOD_DESCRIPTOR:
515 if not pto.c_tp_descr_get or pto.c_tp_descr_get == base_pto.c_tp_descr_get:
516 flags |= Py_TPFLAGS_METHOD_DESCRIPTOR
517
518 # Inherit Py_TPFLAGS_HAVE_VECTORCALL for non-heap static types that do
519 # not override tp_vectorcall_offset or tp_call.
520 # Note: inherit_slots runs after inherit_special, so a zero offset here
521 # means "not overridden" and will be inherited from base.
522 if not (flags & Py_TPFLAGS_HEAPTYPE):
523 if widen(base_pto.c_tp_flags) & Py_TPFLAGS_HAVE_VECTORCALL:
524 same_offset = (pto.c_tp_vectorcall_offset == 0 or
525 pto.c_tp_vectorcall_offset == base_pto.c_tp_vectorcall_offset)
526 if (same_offset
527 and (not pto.c_tp_call or pto.c_tp_call == base_pto.c_tp_call)):
528 flags |= Py_TPFLAGS_HAVE_VECTORCALL
529
530 pto.c_tp_flags = rffi.cast(rffi.ULONG, flags)
531
532 def check_descr(space, w_self, w_type):
533 if not space.isinstance_w(w_self, w_type):
534 raise DescrMismatch()
535
536 class GettersAndSetters:
537 def getter(self, space, w_self):
538 assert isinstance(self, W_GetSetPropertyEx)
539 check_descr(space, w_self, self.w_type)
540 return generic_cpy_call(
541 space, self.getset.c_get, w_self,
542 self.getset.c_closure)
543
544 def setter(self, space, w_self, w_value):
545 assert isinstance(self, W_GetSetPropertyEx)
546 check_descr(space, w_self, self.w_type)
547 res = generic_cpy_call(
548 space, self.getset.c_set, w_self, w_value,
549 self.getset.c_closure)
550 if rffi.cast(lltype.Signed, res) < 0:
551 state = space.fromcache(State)
552 state.check_and_raise_exception()
553
554 def deleter(self, space, w_self):
555 assert isinstance(self, W_GetSetPropertyEx)
556 check_descr(space, w_self, self.w_type)
557 res = generic_cpy_call(
558 space, self.getset.c_set, w_self, None,
559 self.getset.c_closure)
560 if rffi.cast(lltype.Signed, res) < 0:
561 state = space.fromcache(State)
562 state.check_and_raise_exception()
563
564 def member_getter(self, space, w_self):
565 assert isinstance(self, W_MemberDescr)
566 check_descr(space, w_self, self.w_type)
567 pyref = make_ref(space, w_self)
568 try:
569 return PyMember_GetOne(
570 space, rffi.cast(rffi.CCHARP, pyref), self.member)
571 finally:
572 decref(space, pyref)
573
574 def member_delete(self, space, w_self):
575 assert isinstance(self, W_MemberDescr)
576 check_descr(space, w_self, self.w_type)
577 pyref = make_ref(space, w_self)
578 try:
579 PyMember_SetOne(
580 space, rffi.cast(rffi.CCHARP, pyref), self.member, None)
581 finally:
582 decref(space, pyref)
583
584 def member_setter(self, space, w_self, w_value):
585 assert isinstance(self, W_MemberDescr)
586 check_descr(space, w_self, self.w_type)
587 pyref = make_ref(space, w_self)
588 try:
589 PyMember_SetOne(
590 space, rffi.cast(rffi.CCHARP, pyref), self.member, w_value)
591 finally:
592 decref(space, pyref)
593
594 def get_type_name(name):
595 # This is a refactored copy of W_TypeObject.getname()
596 # we cannot use self.getname since the self is not fully initialized
597 dot = name.rfind('.')
598 if dot >= 0:
599 result = name[dot+1:]
600 else:
601 result = name
602 return result
603
604
605
606 class W_PyCTypeObject(W_TypeObject):
607 @jit.dont_look_inside
608 def __init__(self, space, pto):
609 bases_w = space.fixedview(from_ref(space, pto.c_tp_bases))
610 dict_w = {}
611
612 flags = widen(pto.c_tp_flags)
613 flag_heaptype = flags & Py_TPFLAGS_HEAPTYPE
614 if flag_heaptype:
615 type_name = space.text_w(from_ref(space, rffi.cast(PyHeapTypeObject, pto).c_ht_name))
616 name = type_name
617 else:
618 name = rffi.constcharp2str(pto.c_tp_name)
619 type_name = get_type_name(name)
620 _add_operators(space, self, dict_w, pto, type_name)
621 convert_method_defs(space, dict_w, pto.c_tp_methods, self, type_name=type_name)
622 convert_getset_defs(space, dict_w, pto.c_tp_getset, self)
623 convert_member_defs(space, dict_w, pto.c_tp_members, self)
624
625 if pto.c_tp_doc:
626 raw_doc = rffi.constcharp2str(pto.c_tp_doc)
627 dict_w['__doc__'] = space.newtext_or_none(extract_doc(raw_doc, name))
628 if flags & Py_TPFLAGS_DISALLOW_INSTANTIATION:
629 add_disallow_new(space, dict_w, pto)
630 elif pto.c_tp_new:
631 add_tp_new_wrapper(space, dict_w, pto)
632
633 w_dict = from_ref(space, pto.c_tp_dict)
634 if w_dict is not None:
635 dictkeys_w = space.listview(w_dict)
636 for w_key in dictkeys_w:
637 key = space.text_w(w_key)
638 dict_w[key] = space.getitem(w_dict, w_key)
639
640 # Manual heaptypes (allocated via PyType_Type.tp_alloc, then PyType_Ready)
641 # set tp_basicsize = sizeof(PyHeapTypeObject). For those, new_layout is
642 # True only when the type adds fields *beyond* PyHeapTypeObject.
643 #
644 # Spec-created types (PyType_FromSpecWithBases / PyType_FromModuleAndSpec)
645 # also carry Py_TPFLAGS_HEAPTYPE but their tp_basicsize is the *instance*
646 # struct size, which is always smaller than sizeof(PyHeapTypeObject).
647 # Using sizeof(PyHeapTypeObject) as minsize for those types incorrectly
648 # gives new_layout=False, causing find_best_base() to prefer any Python
649 # type over a C type, giving a too-small minsize
650 #
651 # Distinguish the two cases by the magnitude of tp_basicsize:
652 if flag_heaptype and (pto.c_tp_basicsize >=
653 rffi.sizeof(PyHeapTypeObject.TO)):
654 minsize = rffi.sizeof(PyHeapTypeObject.TO)
655 else:
656 minsize = rffi.sizeof(PyObject.TO)
657 extra = pto.c_tp_basicsize - minsize
658 if pto.c_tp_dictoffset > 0:
659 extra -= rffi.sizeof(rffi.VOIDP)
660 if pto.c_tp_weaklistoffset > 0:
661 extra -= rffi.sizeof(rffi.VOIDP)
662 new_layout = (extra > 0 or pto.c_tp_itemsize > 0)
663 self.flag_cpytype = True
664 W_TypeObject.__init__(self, space, name,
665 bases_w or [space.w_object], dict_w, force_new_layout=new_layout,
666 is_heaptype=flag_heaptype)
667
668 # if a sequence or a mapping, then set the flag to force it
669 if pto.c_tp_as_sequence and pto.c_tp_as_sequence.c_sq_item:
670 self.flag_map_or_seq = 'S'
671 elif pto.c_tp_as_mapping and pto.c_tp_as_mapping.c_mp_subscript:
672 self.flag_map_or_seq = 'M'
673 if pto.c_tp_doc:
674 rawdoc = rffi.constcharp2str(pto.c_tp_doc)
675 self.w_doc = space.newtext_or_none(extract_doc(rawdoc, name))
676 self.text_signature = extract_txtsig(rawdoc, name)
677
678 def _cpyext_attach_pyobj(self, space, py_obj):
679 self._cpy_ref = py_obj
680 rawrefcount.create_link_pyobj(self, py_obj)
681
682 def get_flags(self):
683 flags = W_TypeObject.get_flags(self)
684 # Add cpyext-specific flags
685 flags |= widen(rffi.cast(PyTypeObjectPtr, make_ref(self.space, self)).c_tp_flags)
686 return flags
687
688 def acceptable_as_base_class(self, space):
689 if not self.layout.typedef.acceptable_as_base_class:
690 return False
691 pyref = make_ref(space, self)
692 pto = rffi.cast(PyTypeObjectPtr, pyref)
693 acceptable_as_base_class = bool(widen(pto.c_tp_flags) & Py_TPFLAGS_BASETYPE)
694 decref(space, pyref)
695 return acceptable_as_base_class
696
697 @bootstrap_function
698 def init_typeobject(space):
699 make_typedescr(space.w_type.layout.typedef,
700 basestruct=PyHeapTypeObject.TO,
701 alloc=type_alloc,
702 attach=type_attach,
703 realize=type_realize,
704 dealloc=type_dealloc)
705
706 @slot_function([PyObject], lltype.Void)
707 def type_dealloc(space, obj):
708 from pypy.module.cpyext.object import _dealloc
709 obj_pto = rffi.cast(PyTypeObjectPtr, obj)
710 base_pyo = rffi.cast(PyObject, obj_pto.c_tp_base)
711 decref(space, obj_pto.c_tp_bases)
712 decref(space, obj_pto.c_tp_mro)
713 decref(space, obj_pto.c_tp_cache) # let's do it like cpython
714 decref(space, obj_pto.c_tp_dict)
715 if widen(obj_pto.c_tp_flags) & Py_TPFLAGS_HEAPTYPE:
716 # TODO release tp_doc?
717 heaptype = rffi.cast(PyHeapTypeObject, obj)
718 decref(space, heaptype.c_ht_name)
719 decref(space, heaptype.c_ht_qualname)
720 decref(space, base_pyo)
721 _dealloc(space, obj)
722
723
724 # CCC port it to C
725 def type_alloc(typedescr, space, w_metatype, itemsize=0):
726 metatype = rffi.cast(PyTypeObjectPtr, make_ref(space, w_metatype))
727 # Don't increase refcount for non-heaptypes
728 if metatype:
729 flags = widen(metatype.c_tp_flags)
730 if not flags & Py_TPFLAGS_HEAPTYPE:
731 decref(space, metatype)
732
733 # Follow the logic in _PyObject_VAR_SIZE, allocate at least 1 itemsize
734 # see test_heaptype_metaclass, the metaclass_bad type has tp_itemsize
735 # instead of tp_basicsize
736 basicsize = max(rffi.sizeof(PyHeapTypeObject.TO), metatype.c_tp_basicsize)
737 extra_size = metatype.c_tp_itemsize
738 heaptype = lltype.malloc(rffi.VOIDP.TO,
739 basicsize + extra_size,
740 flavor='raw', zero=True,
741 add_memory_pressure=True)
742 heaptype = rffi.cast(PyHeapTypeObject, heaptype)
743 pto = heaptype.c_ht_type
744 rffi.cast(PyObject, pto).c_ob_refcnt = 1
745 rffi.cast(PyObject, pto).c_ob_pypy_link = 0
746 rffi.cast(PyObject, pto).c_ob_type = metatype
747 pto.c_tp_flags = rffi.cast(rffi.ULONG, widen(pto.c_tp_flags) | Py_TPFLAGS_HEAPTYPE)
748 pto.c_tp_as_async = heaptype.c_as_async
749 pto.c_tp_as_number = heaptype.c_as_number
750 pto.c_tp_as_sequence = heaptype.c_as_sequence
751 pto.c_tp_as_mapping = heaptype.c_as_mapping
752 pto.c_tp_as_buffer = heaptype.c_as_buffer
753 pto.c_tp_basicsize = -1 # hopefully this makes malloc bail out
754 pto.c_tp_itemsize = 0
755
756 return rffi.cast(PyObject, heaptype)
757
758 def type_attach(space, py_obj, w_type, w_userdata=None):
759 """
760 Fills a newly allocated PyTypeObject from an existing type.
761 """
762 assert isinstance(w_type, W_TypeObject)
763
764 pto = rffi.cast(PyTypeObjectPtr, py_obj)
765
766 typedescr = get_typedescr(w_type.layout.typedef)
767
768 if space.issubtype_w(w_type, space.w_bytes):
769 pto.c_tp_itemsize = 1
770 elif space.issubtype_w(w_type, space.w_tuple):
771 pto.c_tp_itemsize = rffi.sizeof(PyObject)
772 elif space.is_w(w_type, space.w_type):
773 pto.c_tp_itemsize = rffi.sizeof(PyMemberDef)
774
775 state = space.fromcache(State)
776 pto.c_tp_free = state.C.PyObject_Free
777 pto.c_tp_alloc = state.C.PyType_GenericAlloc
778 builder = state.builder
779 if w_type.layout.typedef.acceptable_as_base_class:
780 pto.c_tp_flags = rffi.cast(rffi.ULONG, widen(pto.c_tp_flags) | Py_TPFLAGS_BASETYPE)
781 if ((widen(pto.c_tp_flags) & Py_TPFLAGS_HEAPTYPE) != 0
782 and builder.cpyext_type_init is None):
783 # this ^^^ is not None only during startup of cpyext. At that
784 # point we might get into troubles by doing make_ref() when
785 # things are not initialized yet. So in this case, simply use
786 # str2charp() and "leak" the string.
787 heaptype = cts.cast('PyHeapTypeObject*', pto)
788 w_typename = space.getattr(w_type, space.newtext('__name__'))
789 w_qualname = space.getattr(w_type, space.newtext('__qualname__'))
790 heaptype.c_ht_name = make_ref(space, w_typename)
791 heaptype.c_ht_qualname = make_ref(space, w_qualname)
792 from pypy.module.cpyext.unicodeobject import PyUnicode_AsUTF8
793 utf8 = PyUnicode_AsUTF8(space, heaptype.c_ht_name)
794 pto.c_tp_name = cts.cast('const char *', utf8)
795 else:
796 pto.c_tp_name = cts.cast('const char*', rffi.str2charp(w_type.name))
797 # uninitialized fields:
798 # c_tp_print
799 # XXX implement
800 # c_tp_compare and more?
801 w_base = best_base(space, w_type.bases_w)
802 pto.c_tp_base = rffi.cast(PyTypeObjectPtr, make_ref(space, w_base))
803
804 # dealloc
805 if space.gettypeobject(w_type.layout.typedef) is w_type:
806 # only for the exact type, like 'space.w_tuple' or 'space.w_list'
807 pto.c_tp_dealloc = typedescr.get_dealloc(space)
808 else:
809 # for all subtypes, use base's dealloc (requires sorting in attach_all)
810 pto.c_tp_dealloc = pto.c_tp_base.c_tp_dealloc
811 if not pto.c_tp_dealloc:
812 # strange, but happens (ABCMeta)
813 pto.c_tp_dealloc = state.C._PyPy_subtype_dealloc
814
815 if builder.cpyext_type_init is not None:
816 builder.cpyext_type_init.append((pto, w_type))
817 else:
818 finish_type_1(space, pto, w_type.bases_w)
819 finish_type_2(space, pto, w_type)
820
821 pto.c_tp_basicsize = rffi.sizeof(typedescr.basestruct)
822 if space.issubtype_w(w_type, space.w_list):
823 # Make sure Py_SIZE() can cast the PyListObject to PyVarObject
824 pto.c_tp_basicsize = max(pto.c_tp_basicsize, rffi.sizeof(PyVarObject.TO))
825 if pto.c_tp_base:
826 if pto.c_tp_base.c_tp_basicsize > pto.c_tp_basicsize:
827 pto.c_tp_basicsize = pto.c_tp_base.c_tp_basicsize
828 # Do not override pto.c_tp_itemsize here, it is done elsewhere
829 if w_type.is_heaptype():
830 update_all_slots(space, w_type, pto)
831 else:
832 update_all_slots_builtin(space, w_type, pto)
833
834 # XXX generlize this pattern for various slot functions implemented in C
835 if space.is_w(w_type, space.w_tuple):
836 pto.c_tp_new = state.C.tuple_new
837
838 if not pto.c_tp_new:
839 base_object_pyo = make_ref(space, space.w_object)
840 base_object_pto = rffi.cast(PyTypeObjectPtr, base_object_pyo)
841 flags = widen(pto.c_tp_flags)
842 if pto.c_tp_base != base_object_pto or flags & Py_TPFLAGS_HEAPTYPE:
843 pto.c_tp_new = pto.c_tp_base.c_tp_new
844 decref(space, base_object_pyo)
845 pto.c_tp_flags = rffi.cast(rffi.ULONG, widen(pto.c_tp_flags) | Py_TPFLAGS_READY)
846 return pto
847
848 def type_reattach(space, w_type):
849 """Called when the w_type base class or bases has been changed, need to
850 re-assign many c slots
851 """
852
853 pto = rffi.cast(PyTypeObjectPtr, w_type._cpyext_as_pyobj(space))
854 w_base = best_base(space, w_type.bases_w)
855 pto.c_tp_base = rffi.cast(PyTypeObjectPtr, make_ref(space, w_base))
856 finish_type_1(space, pto, w_type.bases_w)
857 finish_type_2(space, pto, w_type)
858
859 typedescr = get_typedescr(w_type.layout.typedef)
860 pto.c_tp_basicsize = rffi.sizeof(typedescr.basestruct)
861 if pto.c_tp_base:
862 if pto.c_tp_base.c_tp_basicsize > pto.c_tp_basicsize:
863 pto.c_tp_basicsize = pto.c_tp_base.c_tp_basicsize
864 if pto.c_tp_itemsize < pto.c_tp_base.c_tp_itemsize:
865 pto.c_tp_itemsize = pto.c_tp_base.c_tp_itemsize
866
867 if w_type.is_heaptype():
868 update_all_slots(space, w_type, pto)
869 else:
870 update_all_slots_builtin(space, w_type, pto)
871
872 def py_type_ready(space, pto):
873 if widen(pto.c_tp_flags) & Py_TPFLAGS_READY:
874 return
875 type_realize(space, rffi.cast(PyObject, pto))
876
877 @cpython_api([PyTypeObjectPtr], rffi.INT_real, error=-1)
878 def PyType_Ready(space, pto):
879 py_type_ready(space, pto)
880 return 0
881
882 def type_realize(space, py_obj):
883 pto = rffi.cast(PyTypeObjectPtr, py_obj)
884 flags = widen(pto.c_tp_flags)
885 assert flags & Py_TPFLAGS_READY == 0
886 assert flags & Py_TPFLAGS_READYING == 0
887 if flags & Py_TPFLAGS_MANAGED_DICT:
888 raise oefmt(space.w_RuntimeError, "cannot use Py_TPFLAGS_MANAGED_DICT")
889 if flags & Py_TPFLAGS_MANAGED_WEAKREF:
890 raise oefmt(space.w_RuntimeError, "cannot use Py_TPFLAGS_MANAGED_WEAKREF")
891 pto.c_tp_flags = rffi.cast(rffi.ULONG, flags | Py_TPFLAGS_READYING)
892 try:
893 w_obj = _type_realize(space, py_obj)
894 finally:
895 pto.c_tp_flags = rffi.cast(rffi.ULONG, widen(pto.c_tp_flags) & ~Py_TPFLAGS_READYING)
896 pto.c_tp_flags = rffi.cast(rffi.ULONG, widen(pto.c_tp_flags) | Py_TPFLAGS_READY)
897 return w_obj
898
899 def solid_base(space, w_type):
900 typedef = w_type.layout.typedef
901 return space.gettypeobject(typedef)
902
903 def best_base(space, bases_w):
904 if not bases_w:
905 return None
906 return find_best_base(bases_w)
907
908 num_names = unrolling_iterable(("c_nb_add", "c_nb_subtract", "c_nb_multiply",
909 "c_nb_divmod", "c_nb_power", "c_nb_negative", "c_nb_positive",
910 "c_nb_absolute", "c_nb_bool", "c_nb_invert", "c_nb_lshift",
911 "c_nb_rshift", "c_nb_and", "c_nb_xor", "c_nb_or", "c_nb_int",
912 "c_nb_float", "c_nb_inplace_add", "c_nb_inplace_subtract",
913 "c_nb_inplace_multiply", "c_nb_inplace_remainder",
914 "c_nb_inplace_power", "c_nb_inplace_lshift", "c_nb_inplace_rshift",
915 "c_nb_inplace_and", "c_nb_inplace_xor", "c_nb_inplace_or",
916 "c_nb_true_divide", "c_nb_floor_divide",
917 "c_nb_inplace_true_divide", "c_nb_inplace_floor_divide",
918 "c_nb_index", "c_nb_matrix_multiply", "c_nb_remainder",
919 "c_nb_inplace_matrix_multiply"))
920 def copynum(pto, base):
921 for nb in num_names:
922 if not getattr(pto.c_tp_as_number, nb):
923 setattr(pto.c_tp_as_number, nb, getattr(base.c_tp_as_number, nb))
924
925 async_names = unrolling_iterable(["c_am_await", "c_am_aiter", "c_am_anext"])
926 def copyasync(pto, base):
927 for nb in async_names:
928 if not getattr(pto.c_tp_as_async, nb):
929 setattr(pto.c_tp_as_async, nb, getattr(base.c_tp_as_async, nb))
930
931 seq_names = unrolling_iterable(["c_sq_length", "c_sq_concat", "c_sq_repeat", "c_sq_item",
932 "c_sq_ass_item", "c_sq_contains", "c_sq_inplace_concat",
933 "c_sq_inplace_repeat"])
934 def copyseq(pto, base):
935 for nb in seq_names:
936 if not getattr(pto.c_tp_as_sequence, nb):
937 setattr(pto.c_tp_as_sequence, nb, getattr(base.c_tp_as_sequence, nb))
938
939 map_names = unrolling_iterable(["c_mp_length", "c_mp_subscript", "c_mp_ass_subscript"])
940 def copymap(pto, base):
941 for nb in map_names:
942 if not getattr(pto.c_tp_as_mapping, nb):
943 setattr(pto.c_tp_as_mapping, nb, getattr(base.c_tp_as_mapping, nb))
944
945 def inherit_slots(space, pto, w_base):
946 base_pyo = make_ref(space, w_base)
947 try:
948 base = rffi.cast(PyTypeObjectPtr, base_pyo)
949 if not pto.c_tp_dealloc:
950 pto.c_tp_dealloc = base.c_tp_dealloc
951 if not pto.c_tp_init:
952 pto.c_tp_init = base.c_tp_init
953 if not pto.c_tp_alloc:
954 pto.c_tp_alloc = base.c_tp_alloc
955 # XXX check for correct GC flags!
956 if not pto.c_tp_free:
957 pto.c_tp_free = base.c_tp_free
958 if not pto.c_tp_setattro:
959 pto.c_tp_setattro = base.c_tp_setattro
960 if not pto.c_tp_getattro:
961 pto.c_tp_getattro = base.c_tp_getattro
962 if not pto.c_tp_as_buffer:
963 pto.c_tp_as_buffer = base.c_tp_as_buffer
964 if base.c_tp_as_buffer:
965 # inherit base.c_tp_as_buffer functions not inherited from w_type
966 pto_as = pto.c_tp_as_buffer
967 base_as = base.c_tp_as_buffer
968 if not pto_as.c_bf_getbuffer:
969 pto_as.c_bf_getbuffer = base_as.c_bf_getbuffer
970 if not pto_as.c_bf_releasebuffer:
971 pto_as.c_bf_releasebuffer = base_as.c_bf_releasebuffer
972 if pto.c_tp_vectorcall_offset == 0:
973 pto.c_tp_vectorcall_offset = base.c_tp_vectorcall_offset
974
975 if not pto.c_tp_as_number:
976 pto.c_tp_as_number = base.c_tp_as_number
977 elif base.c_tp_as_number:
978 copynum(pto, base)
979
980 if not pto.c_tp_as_async:
981 pto.c_tp_as_async = base.c_tp_as_async
982 elif base.c_tp_as_async:
983 copyasync(pto, base)
984
985 if not pto.c_tp_as_sequence:
986 pto.c_tp_as_sequence = base.c_tp_as_sequence
987 elif base.c_tp_as_sequence:
988 copyseq(pto, base)
989
990 if not pto.c_tp_as_mapping:
991 pto.c_tp_as_mapping = base.c_tp_as_mapping
992 elif base.c_tp_as_mapping:
993 copymap(pto, base)
994
995 finally:
996 decref(space, base_pyo)
997
998 def _type_realize(space, py_obj):
999 """
1000 Creates an interpreter type from a PyTypeObject structure.
1001 """
1002 # missing:
1003 # unsupported:
1004 # tp_mro, tp_subclasses
1005 py_type = rffi.cast(PyTypeObjectPtr, py_obj)
1006
1007 if not py_type.c_tp_base:
1008 # borrowed reference, but w_object is unlikely to disappear
1009 base = as_pyobj(space, space.w_object)
1010 py_type.c_tp_base = rffi.cast(PyTypeObjectPtr, base)
1011
1012 if py_type.c_tp_itemsize == 0:
1013 w_base = from_ref(space, rffi.cast(PyObject, py_type.c_tp_base))
1014 if space.is_w(w_base, space.w_bytes):
1015 py_type.c_tp_itemsize = 1
1016 elif space.is_w(w_base, space.w_tuple):
1017 py_type.c_tp_itemsize = rffi.sizeof(PyObject)
1018 # elif space.is_w(w_base, space.w_type):
1019 # py_type.c_tp_itemsize = rffi.sizeof(PyMemberDef)
1020
1021 finish_type_1(space, py_type)
1022 ob_type = rffi.cast(PyObject, py_type).c_ob_type
1023
1024 if ob_type:
1025 w_metatype = from_ref(space, rffi.cast(PyObject, ob_type))
1026 else:
1027 # Somehow the tp_base type is created with no ob_type, notably
1028 # PyString_Type and PyBaseString_Type
1029 # While this is a hack, cpython does it as well.
1030 w_metatype = space.w_type
1031
1032 w_obj = rawrefcount.to_obj(W_PyCTypeObject, py_obj)
1033 if w_obj is None:
1034 w_obj = space.allocate_instance(W_PyCTypeObject, w_metatype)
1035 track_reference(space, py_obj, w_obj)
1036 # __init__ wraps all slotdefs functions from py_type via _add_operators
1037 w_obj.__init__(space, py_type)
1038 w_obj.ready()
1039
1040 finish_type_2(space, py_type, w_obj)
1041 base = py_type.c_tp_base
1042 return w_obj
1043
1044 def finish_type_1(space, pto, bases_w=None):
1045 """
1046 Sets up tp_bases, necessary before creating the interpreter type.
1047 """
1048 base = pto.c_tp_base
1049 base_pyo = rffi.cast(PyObject, base)
1050 if base and not widen(base.c_tp_flags) & Py_TPFLAGS_READY:
1051 type_realize(space, base_pyo)
1052 pto_pyobj = rffi.cast(PyObject, pto)
1053 if base and not pto_pyobj.c_ob_type: # will be filled later
1054 pto_pyobj.c_ob_type = rffi.cast(PyObject, base).c_ob_type
1055 if not pto.c_tp_bases:
1056 if bases_w is None:
1057 if not base:
1058 bases_w = []
1059 else:
1060 bases_w = [from_ref(space, base_pyo)]
1061 is_heaptype = bool(widen(pto.c_tp_flags) & Py_TPFLAGS_HEAPTYPE)
1062 pto.c_tp_bases = make_ref(space, space.newtuple(bases_w),
1063 immortal=not is_heaptype)
1064
1065 def finish_type_2(space, pto, w_obj):
1066 """
1067 Sets up other attributes, when the interpreter type has been created.
1068 """
1069 pto.c_tp_mro = make_ref(space, space.newtuple(w_obj.mro_w))
1070 base = pto.c_tp_base
1071 if base:
1072 inherit_special(space, pto, w_obj, base)
1073 for w_base in space.fixedview(from_ref(space, pto.c_tp_bases)):
1074 if isinstance(w_base, W_TypeObject):
1075 inherit_slots(space, pto, w_base)
1076 #else:
1077 # w_base is a W_ClassObject, ignore it
1078
1079 if not pto.c_tp_setattro:
1080 from pypy.module.cpyext.object import PyObject_GenericSetAttr
1081 pto.c_tp_setattro = llslot(space, PyObject_GenericSetAttr)
1082
1083 if not pto.c_tp_getattro:
1084 from pypy.module.cpyext.object import PyObject_GenericGetAttr
1085 pto.c_tp_getattro = llslot(space, PyObject_GenericGetAttr)
1086
1087 if w_obj.is_cpytype():
1088 decref(space, pto.c_tp_dict)
1089 w_dict = w_obj.getdict(space)
1090 # pass in the w_obj to convert any values that are
1091 # unbound GetSetProperty into bound PyGetSetDescrObject
1092 pto.c_tp_dict = make_ref(space, w_dict, w_obj)
1093
1094 def _parse_typeslots():
1095 slots_hdr = CTypeSpace()
1096 slots_hdr.parse_header(parse_dir / "typeslots.h")
1097 prefix2member = {
1098 'tp': "ht_type",
1099 'am': "as_async",
1100 'nb': "as_number",
1101 'mp': "as_mapping",
1102 'sq': "as_sequence",
1103 'bf': "as_buffer"}
1104
1105 TABLE = []
1106 HTO = cts.gettype('PyHeapTypeObject')
1107 slots_len = 0
1108 for name, num in slots_hdr.macros.items():
1109 assert isinstance(num, int)
1110 assert name.startswith('Py_')
1111 name = name[3:]
1112 membername = 'c_' + prefix2member[name[:2]]
1113 slotname = 'c_' + name
1114 TARGET = HTO._flds[membername]._flds[slotname]
1115 TABLE.append((num, membername, slotname, TARGET))
1116 slots_len += 1
1117 return unrolling_iterable(TABLE), slots_len
1118 SLOT_TABLE, slots_len = _parse_typeslots()
1119
1120 def fill_ht_slot(ht, slotnum, ptr):
1121 for num, membername, slotname, TARGET in SLOT_TABLE:
1122 if num == slotnum:
1123 setattr(getattr(ht, membername), slotname, rffi.cast(TARGET, ptr))
1124
1125 def get_slot_by_num(typ, slotnum):
1126 isheaptype = widen(typ.c_tp_flags) & Py_TPFLAGS_HEAPTYPE
1127 ht = rffi.cast(PyHeapTypeObject, typ)
1128 for num, membername, slotname, TARGET in SLOT_TABLE:
1129 if num == slotnum:
1130 if membername == 'c_as_number' and typ.c_tp_as_number:
1131 return rffi.cast(rffi.VOIDP, getattr(typ.c_tp_as_number, slotname))
1132 elif membername == 'c_as_mapping' and typ.c_tp_as_mapping:
1133 return rffi.cast(rffi.VOIDP, getattr(typ.c_tp_as_mapping, slotname))
1134 elif membername == 'c_as_sequnce' and typ.c_tp_as_sequnce:
1135 return rffi.cast(rffi.VOIDP, getattr(typ.c_tp_as_sequnce, slotname))
1136 elif membername == 'c_as_async' and typ.c_tp_as_async:
1137 return rffi.cast(rffi.VOIDP, getattr(typ.c_tp_as_async, slotname))
1138 elif membername == 'c_as_buffer' and typ.c_tp_as_buffer:
1139 return rffi.cast(rffi.VOIDP, getattr(typ.c_tp_as_buffer, slotname))
1140 # Some of the slots are only available for heap types
1141 elif membername != "c_ht_type" and not isheaptype:
1142 return rffi.cast(rffi.VOIDP, 0)
1143 # raise oefmt(space.w_SystemError, "Bad internal call!")
1144 return rffi.cast(rffi.VOIDP, getattr(getattr(ht, membername), slotname))
1145 return rffi.cast(rffi.VOIDP, 0)
1146
1147 @cts.decl("""PyObject *
1148 PyType_FromSpecWithBases(PyType_Spec *spec, PyObject *bases)""",
1149 result_is_ll=True)
1150 def PyType_FromSpecWithBases(space, spec, bases):
1151 return PyType_FromModuleAndSpec(space, None, spec, bases)
1152
1153 @cts.decl("""PyObject *
1154 PyType_FromModuleAndSpec(PyObject *module, PyType_Spec *spec, PyObject *bases)""",
1155 result_is_ll=True)
1156 def PyType_FromModuleAndSpec(space, module, spec, bases):
1157 from pypy.module.cpyext.unicodeobject import PyUnicode_AsUTF8
1158 state = space.fromcache(State)
1159 p_type = cts.cast('PyTypeObject*', make_ref(space, space.w_type))
1160 slotdefs = rffi.cast(rffi.CArrayPtr(cts.gettype('PyType_Slot')), spec.c_slots)
1161 specname = rffi.constcharp2str(spec.c_name)
1162 dotpos = specname.rfind('.')
1163 if dotpos < 0:
1164 name = specname
1165 modname = None
1166 else:
1167 name = specname[dotpos + 1:]
1168 modname = specname[:dotpos]
1169 # XXX Traverse the slots, look for errors, raise them before allocating the
1170 # type. Also:
1171 # - set nmembers since the alloc should allow size to hold them
1172 # and then set typ.tp_member to point to them
1173 # - calculate tp_doc if Py_tp_doc is used
1174 nmembers = weaklistoffset = dictoffset = vectorcalloffset = 0;
1175 tp_doc = None
1176 tp_txtsig = None
1177 module_from_spec = False
1178 i = 0
1179 while True:
1180 slotdef = slotdefs[i]
1181 slot = rffi.cast(lltype.Signed, slotdef.c_slot)
1182 if slot == 0:
1183 break
1184 if slot < 0: # or slot > len(slotoffsets):
1185 raise oefmt(space.w_RuntimeError, "invalid slot offset")
1186 if slot == cts.macros['Py_tp_members']:
1187 if nmembers != 0:
1188 raise oefmt(space.w_SystemError,
1189 "Multiple Py_tp_member slots are not supported")
1190 members = rffi.cast(rffi.CArrayPtr(PyMemberDef), slotdef.c_pfunc)
1191 if members:
1192 while True:
1193 member = members[nmembers]
1194 cname = member.c_name
1195 nmembers += 1 # make sure nmembers includes the null finalizer
1196 if not cname:
1197 break
1198 m_name = rffi.constcharp2str(cname)
1199 if m_name == "__weaklistoffset__":
1200 assert widen(member.c_type) == structmemberdefs.T_PYSSIZET
1201 assert widen(member.c_flags) == structmemberdefs.READONLY
1202 weaklistoffset = member.c_offset
1203 elif m_name == "__dictoffset__":
1204 assert widen(member.c_type) == structmemberdefs.T_PYSSIZET
1205 assert widen(member.c_flags) == structmemberdefs.READONLY
1206 dictoffset = member.c_offset
1207 elif m_name == "__vectorcalloffset__":
1208 assert widen(member.c_type) == structmemberdefs.T_PYSSIZET
1209 assert widen(member.c_flags) == structmemberdefs.READONLY
1210 vectorcalloffset = member.c_offset
1211 elif m_name == "__module__":
1212 module_from_spec = True
1213
1214 elif slot == cts.macros['Py_tp_doc']:
1215 if slotdef.c_pfunc:
1216 from_pfunc = rffi.charp2str(cts.cast("char *", slotdef.c_pfunc))
1217 # Remove the signature if any from the docstring
1218 tp_doc = extract_doc(from_pfunc, name)
1219 tp_txtsig = extract_txtsig(from_pfunc, name)
1220 i += 1
1221 if not spec.c_name:
1222 raise oefmt(space.w_SystemError,
1223 "Type spec does not define the name field.");
1224
1225 res = state.ccall("PyType_GenericAlloc", p_type, nmembers)
1226 res = cts.cast('PyHeapTypeObject *', res)
1227 typ = res.c_ht_type
1228 typ.c_tp_flags = rffi.cast(rffi.ULONG, widen(spec.c_flags) | Py_TPFLAGS_HEAPTYPE)
1229 res.c_ht_name = make_ref(space, space.newtext(name))
1230 res.c_ht_qualname = make_ref(space, space.newtext(name))
1231 incref(space, res.c_ht_qualname)
1232 typ.c_tp_name = spec.c_name
1233 if module:
1234 incref(space, module)
1235 res.c_ht_module = module
1236 if not bases:
1237 w_base = space.w_object
1238 bases_w = []
1239 i = 0
1240 while True:
1241 slotdef = slotdefs[i]
1242 slotnum = rffi.cast(lltype.Signed, slotdef.c_slot)
1243 if slotnum == 0:
1244 break
1245 elif slotnum == cts.macros['Py_tp_base']:
1246 w_base = from_ref(space, cts.cast('PyObject*', slotdef.c_pfunc))
1247 elif slotnum == cts.macros['Py_tp_bases']:
1248 bases = cts.cast('PyObject*', slotdef.c_pfunc)
1249 bases_w = space.fixedview(from_ref(space, bases))
1250 i += 1
1251 if not bases_w:
1252 bases_w = [w_base]
1253 else:
1254 w_bases = from_ref(space, bases)
1255 if not space.isinstance_w(w_bases, space.w_tuple):
1256 bases_w = [w_bases]
1257 else:
1258 bases_w = space.fixedview(w_bases)
1259 w_base = best_base(space, bases_w)
1260 base = cts.cast('PyTypeObject*', make_ref(space, w_base))
1261 if False: # not widen(base.c_tp_flags) & Py_TPFLAGS_BASETYPE:
1262 # CPython allows this, but disallows inheriting from
1263 # python, see W_PyCTypeObject.acceptable_as_base_class
1264 raise oefmt(space.w_TypeError,
1265 "type '%s' is not an acceptable base type",
1266 rffi.constcharp2str(base.c_tp_name))
1267
1268 # Initialize essential fields
1269 typ.c_tp_as_async = res.c_as_async
1270 typ.c_tp_as_number = res.c_as_number
1271 typ.c_tp_as_sequence = res.c_as_sequence
1272 typ.c_tp_as_mapping = res.c_as_mapping
1273 typ.c_tp_as_buffer = res.c_as_buffer
1274 typ.c_tp_bases = bases
1275 typ.c_tp_base = base
1276 typ.c_tp_basicsize = cts.cast('Py_ssize_t', spec.c_basicsize)
1277 typ.c_tp_itemsize = cts.cast('Py_ssize_t', spec.c_itemsize)
1278 if tp_doc is not None:
1279 typ.c_tp_doc = rffi.str2constcharp(tp_doc, track_allocation=False)
1280
1281 i = 0
1282 while True:
1283 slotdef = slotdefs[i]
1284 slot = rffi.cast(lltype.Signed, slotdef.c_slot)
1285 if slot == 0:
1286 break
1287 if slot < 0: # or slot > len(slotoffsets):
1288 raise oefmt(space.w_RuntimeError, "invalid slot offset")
1289 elif slot in (cts.macros['Py_tp_base'], cts.macros['Py_tp_bases'], cts.macros['Py_tp_doc']):
1290 pass
1291 # Processed above
1292 elif slot == cts.macros['Py_tp_members']:
1293 # Move the member defs to the heap type itself, including the
1294 # {0,0,0} finalizer
1295 ob_type = rffi.cast(PyObject, typ).c_ob_type
1296 length = ob_type.c_tp_itemsize * nmembers
1297 # loc = PyHeapType_GETMEMBERS(typ)
1298 loc = rffi.ptradd(cts.cast("char *", typ), ob_type.c_tp_basicsize)
1299 const_pfunc = rffi.cast(rffi.CONST_VOIDP, slotdef.c_pfunc)
1300 rffi.c_memcpy(loc, const_pfunc, length)
1301 typ.c_tp_members = cts.cast("PyMemberDef *", loc)
1302 else:
1303 fill_ht_slot(res, slot, slotdef.c_pfunc)
1304 i += 1
1305
1306 if not typ.c_tp_dealloc:
1307 typ.c_tp_dealloc = state.C._PyPy_subtype_dealloc
1308
1309 if vectorcalloffset:
1310 typ.c_tp_vectorcall_offset = vectorcalloffset
1311 if weaklistoffset:
1312 typ.c_tp_weaklistoffset = weaklistoffset
1313 if dictoffset:
1314 typ.c_tp_dictoffset = dictoffset
1315
1316 py_type_ready(space, typ)
1317
1318 res_obj = cts.cast('PyObject*', res)
1319 w_type = from_ref(space, res_obj)
1320 if tp_txtsig is not None:
1321 assert isinstance(w_type, W_PyCTypeObject)
1322 w_type.text_signature = tp_txtsig
1323 if not module_from_spec and modname is not None:
1324 w_type.setdictvalue(space, '__module__', space.newtext(modname))
1325 # Convert getsets
1326 if typ.c_tp_getset:
1327 getsets = rffi.cast(rffi.CArrayPtr(PyGetSetDef), typ.c_tp_getset)
1328 i = -1
1329 while True:
1330 i = i + 1
1331 getset = getsets[i]
1332 name = getset.c_name
1333 if not name:
1334 break
1335 name = rffi.constcharp2str(name)
1336 w_descr = W_GetSetPropertyEx(getset, w_type)
1337 w_type.setdictvalue(space, name, w_descr)
1338 if dictoffset:
1339 # Link the PyDictObject and w_type.__dict__
1340 # See also create_ref
1341 try:
1342 w_dict = space.getattr(w_type, space.newtext("__dict__"))
1343 except:
1344 dictref = make_ref(space, space.w_None)
1345 else:
1346 dictref = make_ref(space, w_dict)
1347 if dictoffset < 0:
1348 dictoffset += typ.c_tp_basicsize
1349 loc = rffi.ptradd(cts.cast("char *", typ), dictoffset)
1350 dictloc = cts.cast("PyObject **", loc)[0]
1351 dictloc = dictref
1352 return res_obj
1353
1354 @cpython_api([PyTypeObjectPtr, rffi.INT], rffi.VOIDP, error=rffi.cast(rffi.VOIDP, 0))
1355 def PyType_GetSlot(space, typ, slot):
1356 """ Use the Py_tp* macros in typeslots.h to return a slot function
1357 """
1358 slot = widen(slot)
1359 if slot <=0 or slot >= slots_len:
1360 raise oefmt(space.w_SystemError, "Bad internal call!")
1361 return get_slot_by_num(typ, slot)
1362
1363 @cpython_api([PyTypeObjectPtr, PyObject], PyObject, error=CANNOT_FAIL,
1364 result_borrowed=True)
1365 def _PyType_Lookup(space, type, w_name):
1366 """Internal API to look for a name through the MRO.
1367 This returns a borrowed reference, and doesn't set an exception!"""
1368 w_type = from_ref(space, rffi.cast(PyObject, type))
1369 assert isinstance(w_type, W_TypeObject)
1370
1371 if not space.isinstance_w(w_name, space.w_text):
1372 return None
1373 name = space.text_w(w_name)
1374 w_obj = w_type.lookup(name)
1375 # this assumes that w_obj is not dynamically created, but will stay alive
1376 # until w_type is modified or dies. Assuming this, we return a borrowed ref
1377 return w_obj
1378
1379 @cpython_api([PyTypeObjectPtr], lltype.Void)
1380 def PyType_Modified(space, w_obj):
1381 """Invalidate the internal lookup cache for the type and all of its
1382 subtypes. This function must be called after any manual
1383 modification of the attributes or base classes of the type.
1384 """
1385 # Invalidate the type cache in case of a builtin type.
1386 if not isinstance(w_obj, W_TypeObject):
1387 return
1388 if w_obj.is_cpytype():
1389 w_obj.mutated(None)
1390
1391 @cpython_api([PyObject, PyObject], PyObject, header='genericaliasobject.h')
1392 def Py_GenericAlias(space, w_cls, w_item):
1393 from pypy.objspace.std.util import generic_alias_class_getitem
1394 return generic_alias_class_getitem(space, w_cls, w_item)