Debian Codegraph @

pypy/module/cpyext/methodobject.py

raw symbols SCIP
1 from rpython.rtyper.lltypesystem import lltype, rffi
2 from rpython.rlib import jit
3
4 from pypy.interpreter.baseobjspace import W_Root
5 from pypy.interpreter.error import OperationError, oefmt
6 from pypy.interpreter.function import ClassMethod, _Method, StaticMethod
7 from pypy.interpreter.gateway import interp2app
8 from pypy.interpreter.typedef import (
9 GetSetProperty, TypeDef, interp_attrproperty, interp_attrproperty_w,
10 descr_generic_ne, make_weakref_descr)
11 from pypy.objspace.std.typeobject import W_TypeObject, extract_doc, extract_txtsig
12 from pypy.module.cpyext.api import (
13 CONST_STRING, METH_CLASS, METH_COEXIST, METH_KEYWORDS, METH_FASTCALL,
14 METH_NOARGS, METH_O, METH_STATIC, METH_VARARGS, METH_METHOD,
15 PyObject, bootstrap_function, cpython_api, generic_cpy_call,
16 CANNOT_FAIL, slot_function, cts, build_type_checkers,
17 PyObjectP, Py_ssize_t)
18 from pypy.module.cpyext.pyobject import (
19 decref, from_ref, make_ref, as_pyobj, make_typedescr)
20 from pypy.module.cpyext.state import State
21 from pypy.module.cpyext.tupleobject import tuple_from_args_w, PyTupleObject
22
23 PyMethodDef = cts.gettype('PyMethodDef')
24 PyCFunction = cts.gettype('PyCFunction')
25 PyCFunctionFast = cts.gettype('_PyCFunctionFast')
26 PyCFunctionKwArgs = cts.gettype('PyCFunctionWithKeywords')
27 PyCFunctionKwArgsFast = cts.gettype('_PyCFunctionFastWithKeywords')
28 PyCMethod = cts.gettype('PyCMethod')
29 PyCFunctionObject = cts.gettype('PyCFunctionObject*')
30 PyCMethodObject = cts.gettype('PyCMethodObject*')
31
32 @bootstrap_function
33 def init_functionobject(space):
34 make_typedescr(W_PyCFunctionObject.typedef,
35 basestruct=PyCFunctionObject.TO,
36 attach=cfunction_attach,
37 dealloc=cfunction_dealloc)
38
39 @bootstrap_function
40 def init_methodobject(space):
41 make_typedescr(W_PyCMethodObject.typedef,
42 basestruct=PyCMethodObject.TO,
43 attach=cmethod_attach,
44 dealloc=cmethod_dealloc)
45
46 def cfunction_attach(space, py_obj, w_obj, w_userdata=None):
47 assert isinstance(w_obj, W_PyCFunctionObject)
48 py_func = rffi.cast(PyCFunctionObject, py_obj)
49 py_func.c_m_ml = w_obj.ml
50 py_func.c_m_self = make_ref(space, w_obj.w_self)
51 py_func.c_m_module = make_ref(space, w_obj.w_module)
52
53 @slot_function([PyObject], lltype.Void)
54 def cfunction_dealloc(space, py_obj):
55 py_func = rffi.cast(PyCFunctionObject, py_obj)
56 decref(space, py_func.c_m_self)
57 decref(space, py_func.c_m_module)
58 from pypy.module.cpyext.object import _dealloc
59 _dealloc(space, py_obj)
60
61 def cmethod_attach(space, py_obj, w_obj, w_userdata=None):
62 assert isinstance(w_obj, W_PyCMethodObject)
63 py_func = rffi.cast(PyCFunctionObject, py_obj)
64 py_func.c_m_ml = w_obj.ml
65 py_func.c_m_self = make_ref(space, w_obj.w_self)
66 py_func.c_m_module = make_ref(space, w_obj.w_module)
67 py_meth = rffi.cast(PyCMethodObject, py_obj)
68 py_meth.c_mm_class = w_obj.w_objclass
69
70 @slot_function([PyObject], lltype.Void)
71 def cmethod_dealloc(space, py_obj):
72 py_func = rffi.cast(PyCFunctionObject, py_obj)
73 decref(space, py_func.c_func)
74 decref(space, py_func.c_m_module)
75 py_meth = rffi.cast(PyCMethodObject, py_obj)
76 decref(space, py_meth.c_mm_class)
77 from pypy.module.cpyext.object import _dealloc
78 _dealloc(space, py_obj)
79
80 def w_kwargs_from_args(space, __args__):
81 if __args__.keyword_names_w is None:
82 return None
83 # CCC: we should probably have a @jit.look_inside_iff if the
84 # keyword count is constant, as we do in Arguments.unpack
85 w_kwargs = space.newdict()
86 for i in range(len(__args__.keyword_names_w)):
87 w_key = __args__.keyword_names_w[i]
88 w_obj = __args__.keywords_w[i]
89 space.setitem(w_kwargs, w_key, w_obj)
90 return w_kwargs
91
92 def w_fastcall_args_from_args(space, __args__):
93 # Similar to the above, but pack keys into a tuple and positional and
94 # keyword arguments into a single tuple object (to be passed raw)
95 state = space.fromcache(State)
96
97 if __args__.keyword_names_w is not None and len(__args__.keyword_names_w) > 0:
98 py_args = tuple_from_args_w(space, __args__.arguments_w + __args__.keywords_w)
99 w_kwnames = space.newtuple(__args__.keyword_names_w)
100 else:
101 py_args = tuple_from_args_w(space, __args__.arguments_w)
102 w_kwnames = None
103
104 py_args = rffi.cast(PyTupleObject, py_args)
105 return py_args, len(__args__.arguments_w), w_kwnames
106
107 class W_PyCFunctionObject(W_Root):
108 _immutable_fields_ = ["flags", "ml"]
109
110 def __init__(self, space, ml, w_self, w_module=None, type_name=None):
111 self.ml = ml
112 self.name = rffi.charp2str(rffi.cast(rffi.CCHARP, self.ml.c_ml_name))
113 # class methods have type_name
114 if type_name:
115 self.qualname = type_name + "." + self.name
116 else:
117 self.qualname = self.name
118 self.flags = rffi.cast(lltype.Signed, self.ml.c_ml_flags)
119 self.w_self = w_self
120 self.w_module = w_module
121
122 def descr_call(self, space, __args__):
123 return self.call(space, self.w_self, __args__)
124
125 def call(self, space, w_self, __args__):
126 flags = self.flags & ~(METH_CLASS | METH_STATIC | METH_COEXIST)
127 length = len(__args__.arguments_w)
128 if not flags & METH_KEYWORDS and __args__.keyword_names_w:
129 raise oefmt(space.w_TypeError,
130 "%s() takes no keyword arguments", self.name)
131 elif flags & METH_FASTCALL:
132 if flags & METH_KEYWORDS:
133 if flags & METH_METHOD:
134 return self.call_keywords_fastcall_method(space, w_self, __args__)
135 return self.call_keywords_fastcall(space, w_self, __args__)
136 return self.call_varargs_fastcall(space, w_self, __args__)
137 elif flags & METH_KEYWORDS:
138 return self.call_keywords(space, w_self, __args__)
139 elif flags & METH_NOARGS:
140 if length == 0:
141 return self.call_noargs(space, w_self, __args__)
142 raise oefmt(space.w_TypeError,
143 "%s() takes no arguments (%d given)", self.name, length)
144 elif flags & METH_O:
145 if length != 1:
146 raise oefmt(space.w_TypeError,
147 "%s() takes exactly one argument (%d given)",
148 self.name, length)
149 return self.call_o(space, w_self, __args__)
150 elif flags & METH_VARARGS:
151 return self.call_varargs(space, w_self, __args__)
152 else: # shouldn't happen!
153 raise oefmt(space.w_RuntimeError, "unknown calling convention")
154
155 def call_noargs(self, space, w_self, __args__):
156 func = self.ml.c_ml_meth
157 return generic_cpy_call(space, func, w_self, None)
158
159 def call_o(self, space, w_self, __args__):
160 func = self.ml.c_ml_meth
161 w_o = __args__.arguments_w[0]
162 return generic_cpy_call(space, func, w_self, w_o)
163
164 def call_varargs(self, space, w_self, __args__):
165 state = space.fromcache(State)
166 func = self.ml.c_ml_meth
167 py_args = tuple_from_args_w(space, __args__.arguments_w)
168 try:
169 return generic_cpy_call(space, func, w_self, py_args)
170 finally:
171 decref(space, py_args)
172
173 def call_varargs_fastcall(self, space, w_self, __args__):
174 func = rffi.cast(PyCFunctionFast, self.ml.c_ml_meth)
175 py_args, len_args, _ = w_fastcall_args_from_args(space, __args__)
176 try:
177 return generic_cpy_call(space, func, w_self,
178 py_args.c_ob_item, len_args)
179 finally:
180 decref(space, py_args)
181
182 def call_keywords(self, space, w_self, __args__):
183 func = rffi.cast(PyCFunctionKwArgs, self.ml.c_ml_meth)
184 py_args = tuple_from_args_w(space, __args__.arguments_w)
185 w_kwargs = w_kwargs_from_args(space, __args__)
186 try:
187 return generic_cpy_call(space, func, w_self, py_args, w_kwargs)
188 finally:
189 decref(space, py_args)
190
191 def call_keywords_fastcall(self, space, w_self, __args__):
192 func = rffi.cast(PyCFunctionKwArgsFast, self.ml.c_ml_meth)
193 py_args, len_args, w_kwnames = w_fastcall_args_from_args(space, __args__)
194 try:
195 return generic_cpy_call(space, func, w_self,
196 py_args.c_ob_item, len_args, w_kwnames)
197 finally:
198 decref(space, py_args)
199
200 def call_keywords_fastcall_method(self, space, w_self, __args__):
201 func = rffi.cast(PyCMethod, self.ml.c_ml_meth)
202 py_args, len_args, w_kwnames = w_fastcall_args_from_args(space, __args__)
203 try:
204 # Signature is (PyObject *, PyTypeObject*, PyObject ** args, size_t nargs, PyObject*kwnames)
205 py_type = cts.cast("PyTypeObject*", make_ref(space, self.w_objclass))
206 return generic_cpy_call(space, func, w_self, py_type, py_args.c_ob_item,
207 rffi.cast(rffi.SIZE_T, len_args), w_kwnames)
208 finally:
209 decref(space, py_args)
210
211
212 def get_doc(self, space):
213 c_doc = self.ml.c_ml_doc
214 if c_doc:
215 rawdoc = rffi.charp2str(rffi.cast(rffi.CCHARP, c_doc))
216 doc = extract_doc(rawdoc, self.name)
217 if doc is not None:
218 return space.newtext(doc)
219 return space.w_None
220
221 def get_txtsig(self, space):
222 c_doc = self.ml.c_ml_doc
223 if c_doc:
224 rawdoc = rffi.charp2str(rffi.cast(rffi.CCHARP, c_doc))
225 txtsig = extract_txtsig(rawdoc, self.name)
226 if txtsig is not None:
227 return space.newtext(txtsig)
228 return space.w_None
229
230 def fget_module(self, space):
231 if self.w_module is None:
232 return space.w_None
233 return self.w_module
234
235 def fset_module(self, space, w_module):
236 self.w_module = w_module
237
238 def fdel_module(self, space):
239 self.w_module = space.w_None
240
241 def descr_reduce(self, space):
242 w_builtins = space.getbuiltinmodule('builtins')
243 w_getattr = space.getattr(w_builtins, space.newtext('getattr'))
244 w_mod = self.w_module
245 if w_mod is None or space.is_none(w_mod):
246 raise oefmt(space.w_TypeError,
247 "cannot pickle built-in function '%s': no __module__",
248 self.name)
249 # __module__ is stored as a string; resolve it via sys.modules
250 if space.isinstance_w(w_mod, space.w_unicode):
251 w_sys = space.getbuiltinmodule('sys')
252 w_modules = space.getattr(w_sys, space.newtext('modules'))
253 try:
254 w_mod = space.getitem(w_modules, w_mod)
255 except OperationError as e:
256 if not e.match(space, space.w_KeyError):
257 raise
258 raise oefmt(space.w_TypeError,
259 "cannot pickle built-in function '%s': "
260 "module not in sys.modules", self.name)
261 return space.newtuple2(w_getattr,
262 space.newtuple([w_mod, space.newtext(self.name)]))
263
264 class W_PyCMethodObject(W_PyCFunctionObject):
265
266 def __init__(self, space, ml, w_self, w_module, w_type, type_name):
267 W_PyCFunctionObject.__init__(self, space, ml, w_self, w_module, type_name)
268 self.space = space
269 self.w_objclass = w_type
270
271 def __repr__(self):
272 return self.space.unwrap(self.descr_method_repr())
273
274 def descr_method_repr(self):
275 w_objclass = self.w_objclass
276 assert isinstance(w_objclass, W_TypeObject)
277 return self.space.newtext("<method '%s' of '%s' objects>" % (
278 self.name, w_objclass.name))
279
280 def descr_call(self, space, __args__):
281 if len(__args__.arguments_w) == 0:
282 w_objclass = self.w_objclass
283 assert isinstance(w_objclass, W_TypeObject)
284 raise oefmt(space.w_TypeError,
285 "descriptor '%8' of '%s' object needs an argument",
286 self.name, self.w_objclass.getname(space))
287 w_instance = __args__.arguments_w[0]
288 # XXX: needs a stricter test
289 if not space.isinstance_w(w_instance, self.w_objclass):
290 w_objclass = self.w_objclass
291 assert isinstance(w_objclass, W_TypeObject)
292 raise oefmt(space.w_TypeError,
293 "descriptor '%8' requires a '%s' object but received a '%T'",
294 self.name, w_objclass.name, w_instance)
295 #
296 # CCC: we can surely do better than this
297 __args__ = __args__.replace_arguments(__args__.arguments_w[1:])
298 return self.call(space, w_instance, __args__)
299
300 def descr_reduce(self, space):
301 w_builtins = space.getbuiltinmodule('builtins')
302 w_getattr = space.getattr(w_builtins, space.newtext('getattr'))
303 return space.newtuple2(w_getattr,
304 space.newtuple([self.w_objclass,
305 space.newtext(self.name)]))
306
307 # PyPy addition, for Cython
308 _, _ = build_type_checkers("MethodDescr", W_PyCMethodObject)
309
310
311 @cpython_api([PyObject], rffi.INT_real, error=CANNOT_FAIL)
312 def PyCFunction_Check(space, pyobj):
313 w_obj = from_ref(space, pyobj)
314 from pypy.interpreter.function import BuiltinFunction
315 if w_obj is None:
316 return False
317 if isinstance(w_obj, W_PyCFunctionObject):
318 return True
319 return isinstance(w_obj, BuiltinFunction)
320
321 class W_PyCClassMethodObject(W_PyCFunctionObject):
322
323 def __init__(self, space, ml, w_type, type_name):
324 W_PyCFunctionObject.__init__(self, space, ml, w_self=None, type_name=type_name)
325 self.space = space
326 self.w_objclass = w_type
327
328 def __repr__(self):
329 return self.space.unwrap(self.descr_method_repr())
330
331 def descr_call(self, space, __args__):
332 if len(__args__.arguments_w) == 0:
333 raise oefmt(space.w_TypeError,
334 "descriptor '%8' of '%s' object needs an argument",
335 self.name, self.w_objclass.getname(space))
336 w_instance = __args__.arguments_w[0] # XXX typecheck missing
337 # CCC: we can surely do better than this
338 __args__ = __args__.replace_arguments(__args__.arguments_w[1:])
339 return self.call(space, w_instance, __args__)
340
341 def descr_method_repr(self):
342 return self.getrepr(
343 self.space, "built-in method '%s' of '%s' object" %
344 (self.name, self.w_objclass.getname(self.space)))
345
346
347 class W_PyCWrapperObject(W_Root):
348 """
349 Abstract class; for concrete subclasses, see slotdefs.py
350 """
351 def __init__(self, space, w_type, method_name, doc, func, type_name):
352 # When this is called, w_type is only partially constructed so we
353 # get its name via type_name
354 self.space = space
355 self.method_name = method_name
356 self.doc = doc
357 self.func = func
358 assert isinstance(w_type, W_TypeObject)
359 self.w_objclass = w_type
360 self.qualname = type_name + "." + method_name
361
362 def descr_call(self, space, w_self, __args__):
363 return self.call(space, w_self, __args__)
364
365 def call(self, space, w_self, __args__):
366 raise NotImplementedError
367
368 def get_func_to_call(self):
369 return self.func
370
371 def check_args(self, __args__, arity):
372 length = len(__args__.arguments_w)
373 if length != arity:
374 raise oefmt(self.space.w_TypeError, "expected %d arguments, got %d",
375 arity, length)
376 if __args__.keyword_names_w:
377 raise oefmt(self.space.w_TypeError,
378 "wrapper %s doesn't take any keyword arguments",
379 self.method_name)
380
381 def check_argsv(self, __args__, min, max):
382 length = len(__args__.arguments_w)
383 if not min <= length <= max:
384 raise oefmt(self.space.w_TypeError, "expected %d-%d arguments, got %d",
385 min, max, length)
386 if __args__.keyword_names_w:
387 raise oefmt(self.space.w_TypeError,
388 "wrapper %s doesn't take any keyword arguments",
389 self.method_name)
390
391 def descr_method_repr(self):
392 return self.space.newtext("<slot wrapper '%s' of '%s' objects>" %
393 (self.method_name,
394 self.w_objclass.name))
395
396 def descr_reduce(self, space):
397 w_builtins = space.getbuiltinmodule('builtins')
398 w_getattr = space.getattr(w_builtins, space.newtext('getattr'))
399 return space.newtuple2(w_getattr,
400 space.newtuple([self.w_objclass,
401 space.newtext(self.method_name)]))
402
403 def descr_get_doc(self, space):
404 py_obj = make_ref(space, self)
405 py_methoddescr = cts.cast('PyWrapperDescrObject*', py_obj)
406 if py_methoddescr.c_d_base and py_methoddescr.c_d_base.c_doc:
407 doc = rffi.constcharp2str(py_methoddescr.c_d_base.c_doc)
408 else:
409 doc = self.doc
410 if doc:
411 return space.newtext(doc)
412 return space.w_None
413
414 def descr_get_txtsig(self, space):
415 py_obj = make_ref(space, self)
416 py_methoddescr = cts.cast('PyWrapperDescrObject*', py_obj)
417 if py_methoddescr.c_d_base and py_methoddescr.c_d_base.c_doc:
418 rawdoc = rffi.constcharp2str(py_methoddescr.c_d_base.c_doc)
419 else:
420 rawdoc = self.doc
421 if rawdoc:
422 txtsig = extract_txtsig(rawdoc, self.method_name)
423 if txtsig is not None:
424 return space.newtext(txtsig)
425 return space.w_None
426
427 class CMethod(_Method):
428 # Differentiate this from an app-level class Method
429 # so isinstance(c-class-meth, type(app-class-method)) is False
430 def descr_method__new__(space, w_subtype, w_function, w_instance):
431 if space.is_w(w_instance, space.w_None):
432 w_instance = None
433 if w_instance is None:
434 raise oefmt(space.w_TypeError, "self must not be None")
435 method = space.allocate_instance(CMethod, w_subtype)
436 _Method.__init__(method, space, w_function, w_instance)
437 return method
438
439 pass
440
441 CMethod.typedef = TypeDef(
442 "builtin method",
443 __doc__ = GetSetProperty(CMethod.descr_get_doc),
444 __new__ = interp2app(CMethod.descr_method__new__.im_func),
445 __call__ = interp2app(CMethod.descr_method_call),
446 __get__ = interp2app(CMethod.descr_method_get),
447 __func__ = interp_attrproperty_w('w_function', cls=CMethod),
448 __self__ = interp_attrproperty_w('w_instance', cls=CMethod),
449 __getattribute__ = interp2app(CMethod.descr_method_getattribute),
450 __eq__ = interp2app(CMethod.descr_method_eq),
451 __ne__ = descr_generic_ne,
452 __hash__ = interp2app(CMethod.descr_method_hash),
453 __repr__ = interp2app(CMethod.descr_method_repr),
454 __reduce__ = interp2app(CMethod.descr_method__reduce__),
455 __weakref__ = make_weakref_descr(CMethod),
456 )
457 CMethod.typedef.acceptable_as_base_class = False
458 CMethod.typedef.doc = """instancemethod(function, instance)
459
460 Create an instance method object."""
461
462
463 def cmethod_descr_get(space, w_function, w_obj, w_cls=None):
464 if w_obj is None or space.is_w(w_obj, space.w_None):
465 return w_function
466 else:
467 return CMethod(space, w_function, w_obj)
468
469 def cclassmethod_descr_get(space, w_function, w_obj, w_cls=None):
470 if not w_cls:
471 w_cls = space.type(w_obj)
472 return CMethod(space, w_function, w_cls)
473
474
475 W_PyCFunctionObject.typedef = TypeDef(
476 'builtin_function_or_method',
477 __call__ = interp2app(W_PyCFunctionObject.descr_call),
478 __doc__ = GetSetProperty(W_PyCFunctionObject.get_doc),
479 __text_signature__ = GetSetProperty(W_PyCFunctionObject.get_txtsig),
480 __module__ = GetSetProperty(W_PyCFunctionObject.fget_module,
481 W_PyCFunctionObject.fset_module,
482 W_PyCFunctionObject.fdel_module),
483 __name__ = interp_attrproperty('name', cls=W_PyCFunctionObject,
484 wrapfn="newtext_or_none"),
485 __qualname__ = interp_attrproperty('qualname', cls=W_PyCFunctionObject,
486 wrapfn="newtext_or_none"),
487 __self__ = interp_attrproperty_w('w_self', cls=W_PyCFunctionObject),
488 __reduce__ = interp2app(W_PyCFunctionObject.descr_reduce),
489 )
490 W_PyCFunctionObject.typedef.acceptable_as_base_class = False
491
492 W_PyCMethodObject.typedef = TypeDef(
493 'method_descriptor',
494 __get__ = interp2app(cmethod_descr_get),
495 __call__ = interp2app(W_PyCMethodObject.descr_call),
496 __doc__ = GetSetProperty(W_PyCMethodObject.get_doc),
497 __text_signature__ = GetSetProperty(W_PyCMethodObject.get_txtsig),
498 __name__ = interp_attrproperty('name', cls=W_PyCMethodObject,
499 wrapfn="newtext_or_none"),
500 __qualname__ = interp_attrproperty('qualname', cls=W_PyCMethodObject,
501 wrapfn="newtext_or_none"),
502 __objclass__ = interp_attrproperty_w('w_objclass', cls=W_PyCMethodObject),
503 __repr__ = interp2app(W_PyCMethodObject.descr_method_repr),
504 __reduce__ = interp2app(W_PyCMethodObject.descr_reduce),
505 )
506 W_PyCMethodObject.typedef.acceptable_as_base_class = False
507
508 W_PyCClassMethodObject.typedef = TypeDef(
509 'builtin_function_or_method',
510 __get__ = interp2app(cclassmethod_descr_get),
511 __call__ = interp2app(W_PyCClassMethodObject.descr_call),
512 __doc__ = GetSetProperty(W_PyCClassMethodObject.get_doc),
513 __text_signature__ = GetSetProperty(W_PyCClassMethodObject.get_txtsig),
514 __name__ = interp_attrproperty('name', cls=W_PyCClassMethodObject,
515 wrapfn="newtext_or_none"),
516 __qualname__ = interp_attrproperty('qualname', cls=W_PyCClassMethodObject,
517 wrapfn="newtext_or_none"),
518 __objclass__ = interp_attrproperty_w('w_objclass',
519 cls=W_PyCClassMethodObject),
520 __repr__ = interp2app(W_PyCClassMethodObject.descr_method_repr),
521 )
522 W_PyCClassMethodObject.typedef.acceptable_as_base_class = False
523
524
525 W_PyCWrapperObject.typedef = TypeDef(
526 'wrapper_descriptor',
527 __call__ = interp2app(W_PyCWrapperObject.descr_call),
528 __get__ = interp2app(cmethod_descr_get),
529 __name__ = interp_attrproperty('method_name', cls=W_PyCWrapperObject,
530 wrapfn="newtext_or_none"),
531 __qualname__ = interp_attrproperty('qualname', cls=W_PyCWrapperObject,
532 wrapfn="newtext_or_none"),
533 __doc__ = GetSetProperty(W_PyCWrapperObject.descr_get_doc),
534 __text_signature__ = GetSetProperty(W_PyCWrapperObject.descr_get_txtsig),
535 __objclass__ = interp_attrproperty_w('w_objclass', cls=W_PyCWrapperObject),
536 __repr__ = interp2app(W_PyCWrapperObject.descr_method_repr),
537 __reduce__ = interp2app(W_PyCWrapperObject.descr_reduce),
538 # XXX missing: __getattribute__
539 )
540 W_PyCWrapperObject.typedef.acceptable_as_base_class = False
541
542
543 @cpython_api([lltype.Ptr(PyMethodDef), PyObject, PyObject, PyObject], PyObject)
544 def PyCMethod_New(space, ml, w_self, w_name, w_type):
545 flags = rffi.cast(lltype.Signed, ml.c_ml_flags)
546 if flags & METH_METHOD:
547 if w_type is None:
548 raise oefmt(space.w_SystemError,
549 "attempting to create PyCMethod with a METH_METHOD "
550 "flag but no class");
551 if not isinstance(w_type, W_TypeObject):
552 raise oefmt(space.w_SystemError,
553 "bad argument to PyCMethod_New")
554 assert isinstance(w_type, W_TypeObject)
555 return W_PyCMethodObject(space, ml, w_self, w_name, w_type, w_type.qualname)
556 else:
557 if w_type:
558 raise oefmt(space.w_SystemError,
559 "attempting to create PyCFunction with class "
560 "but no METH_METHOD flag");
561 return W_PyCFunctionObject(space, ml, w_self, w_name)
562
563 @cts.decl("PyCFunction PyCFunction_GetFunction(PyObject *)")
564 def PyCFunction_GetFunction(space, w_obj):
565 try:
566 cfunction = space.interp_w(W_PyCFunctionObject, w_obj)
567 except OperationError as e:
568 if e.match(space, space.w_TypeError):
569 raise oefmt(space.w_SystemError,
570 "bad argument to internal function")
571 raise
572 return cfunction.ml.c_ml_meth
573
574 @cpython_api([PyObject], PyObject)
575 def PyStaticMethod_New(space, w_func):
576 return StaticMethod(w_func)
577
578 @cpython_api([PyObject], PyObject)
579 def PyClassMethod_New(space, w_func):
580 return ClassMethod(w_func)
581
582 @cts.decl("""
583 PyObject *
584 PyDescr_NewMethod(PyTypeObject *type, PyMethodDef *method)""")
585 def PyDescr_NewMethod(space, w_type, method):
586 return W_PyCMethodObject(space, method, None, None, w_type, None)
587
588 @cts.decl("""
589 PyObject *
590 PyDescr_NewClassMethod(PyTypeObject *type, PyMethodDef *method)""")
591 def PyDescr_NewClassMethod(space, w_type, method):
592 if not isinstance(w_type, W_TypeObject):
593 raise oefmt(space.w_SystemError,
594 "bad argument to PyDescr_NewClassMethod")
595 assert isinstance(w_type, W_TypeObject)
596 return W_PyCClassMethodObject(space, method, w_type, w_type.qualname)
597
598 @cpython_api([lltype.Ptr(PyMethodDef), PyObject, CONST_STRING], PyObject)
599 def Py_FindMethod(space, table, w_obj, name_ptr):
600 """Return a bound method object for an extension type implemented in
601 C. This can be useful in the implementation of a tp_getattro or
602 tp_getattr handler that does not use the PyObject_GenericGetAttr()
603 function.
604 """
605 # XXX handle __doc__
606
607 name = rffi.charp2str(name_ptr)
608 methods = rffi.cast(rffi.CArrayPtr(PyMethodDef), table)
609 method_list_w = []
610
611 if methods:
612 i = -1
613 while True:
614 i = i + 1
615 method = methods[i]
616 if not method.c_ml_name:
617 break
618 if name == "__methods__":
619 method_list_w.append(space.newtext(rffi.charp2str(
620 rffi.cast(rffi.CCHARP, method.c_ml_name))))
621 elif rffi.charp2str(rffi.cast(rffi.CCHARP, method.c_ml_name)) == name: # XXX expensive copy
622 return W_PyCFunctionObject(space, method, w_obj)
623 if name == "__methods__":
624 return space.newlist(method_list_w)
625 raise OperationError(space.w_AttributeError, space.newtext(name))
626
627 def argtuple_from_pyobject_array(space, py_args, n):
628 args_w = [None] * n
629 for i in range(n):
630 args_w[i] = from_ref(space, py_args[i])
631 return space.newtuple(args_w)
632
633 def obj_and_tuple_from_pyobject_array(space, py_args, n_minus_1):
634 args_w = [None] * n_minus_1
635 for i in range(n_minus_1):
636 args_w[i] = from_ref(space, py_args[i + 1])
637 return from_ref(space, py_args[0]), args_w
638
639 def PyVectorcall_NARGS(n):
640 PY_VECTORCALL_ARGUMENTS_OFFSET = 1 << (8 * rffi.sizeof(rffi.SIZE_T) - 1)
641 return n & ~PY_VECTORCALL_ARGUMENTS_OFFSET
642
643 @cts.decl("PyObject *PyObject_Vectorcall(PyObject *, PyObject *const *, "
644 "size_t, PyObject *)")
645 def PyObject_Vectorcall(space, w_func, py_args, n, w_argnames):
646
647 if w_argnames is None:
648 n_kwargs = -1
649 else:
650 n_kwargs = space.len_w(w_argnames)
651 n = PyVectorcall_NARGS(n)
652 w_args = argtuple_from_pyobject_array(space, py_args, n)
653 if w_argnames is None:
654 w_kwargs = None
655 else:
656 w_kwargs = space.newdict()
657 for i in range(n_kwargs):
658 space.setitem(w_kwargs, space.getitem(w_argnames, space.newint(i)),
659 from_ref(space, py_args[n + i]))
660 w_result = space.call(w_func, w_args, w_kwargs)
661 return w_result
662
663 @cts.decl("PyObject *_PyObject_FastCall(PyObject *, PyObject *const *, "
664 "size_t)")
665 def _PyObject_FastCall(space, w_func, py_args, n):
666 return PyObject_Vectorcall(space, w_func, py_args, n, lltype.nullptr(PyObject.TO))
667
668 @cts.decl("PyObject *PyObject_VectorcallDict(PyObject *, PyObject *const *, "
669 "size_t, PyObject *)")
670 def PyObject_VectorcallDict(space, w_func, py_args, n, w_kwargs):
671 w_args = argtuple_from_pyobject_array(space, py_args, n)
672 w_result = space.call(w_func, w_args, w_kwargs)
673 return w_result
674
675 @cts.decl("PyObject *PyObject_VectorcallMethod(PyObject *, PyObject *const *, "
676 "size_t, PyObject *)")
677 def PyObject_VectorcallMethod(space, w_name, py_args, n, w_argnames):
678 if w_argnames is None:
679 n_kwargs = -1
680 else:
681 n_kwargs = space.len_w(w_argnames)
682 n = PyVectorcall_NARGS(n)
683 n_minus_1 = n - 1
684 if n_minus_1 < 0:
685 raise oefmt(space.w_ValueError, "n<1 in call to PyObject_VectorcallMethod")
686 w_obj, args_w = obj_and_tuple_from_pyobject_array(space, py_args, n_minus_1)
687 if w_argnames is None:
688 # fast path. Cannot use call_method(... *args_w)
689 name = space.text_w(w_name)
690 if n_minus_1 == 0:
691 return space.call_method(w_obj, name)
692 elif n_minus_1 == 1:
693 return space.call_method(w_obj, name, args_w[0])
694 elif n_minus_1 == 2:
695 return space.call_method(w_obj, name, args_w[0], args_w[1])
696 elif n_minus_1 == 3:
697 return space.call_method(w_obj, name, args_w[0], args_w[1], args_w[2])
698 w_meth = space.getattr(w_obj, w_name)
699 return space.call(w_meth, space.newtuple(args_w))
700 w_kwargs = space.newdict()
701 for i in range(n_kwargs):
702 space.setitem(w_kwargs, space.getitem(w_argnames, space.newint(i)),
703 from_ref(space, py_args[n + i]))
704 w_meth = space.getattr(w_obj, w_name)
705 return space.call(w_meth, space.newtuple(args_w), w_kwargs)
706
707