Debian Codegraph @

pypy/module/_cppyy/executor.py

raw symbols SCIP
1 import sys
2
3 from pypy.interpreter.error import oefmt
4 from pypy.interpreter.argument import Arguments
5 from pypy.objspace.std.unicodeobject import W_UnicodeObject
6
7 from rpython.rtyper.lltypesystem import rffi, lltype
8 from rpython.rlib import jit_libffi
9
10 from pypy.module._rawffi.interp_rawffi import letter2tp
11 from pypy.module._cppyy import helper, capi, ffitypes, lowlevelviews
12
13 # Executor objects are used to dispatch C++ methods. They are defined by their
14 # return type only: arguments are converted by Converter objects, and Executors
15 # only deal with arrays of memory that are either passed to a stub or libffi.
16 # No argument checking or conversions are done.
17 #
18 # If a libffi function is not implemented, FastCallNotPossible is raised. If a
19 # stub function is missing (e.g. if no reflection info is available for the
20 # return type), an app-level TypeError is raised.
21 #
22 # Executor instances are created by get_executor(<return type name>), see
23 # below. The name given should be qualified in case there is a specialised,
24 # exact match for the qualified type.
25
26
27 NULL = lltype.nullptr(jit_libffi.FFI_TYPE_P.TO)
28
29 class Executor(object):
30 def __init__(self, space, extra):
31 pass
32
33 def cffi_type(self, space):
34 from pypy.module._cppyy.interp_cppyy import FastCallNotPossible
35 raise FastCallNotPossible
36
37 def execute(self, space, cppmethod, cppthis, num_args, args):
38 raise oefmt(space.w_TypeError,
39 "return type not available or supported")
40
41 def execute_libffi(self, space, cif_descr, funcaddr, buf):
42 from pypy.module._cppyy.interp_cppyy import FastCallNotPossible
43 raise FastCallNotPossible
44
45
46 class PtrTypeExecutor(Executor):
47 _immutable_fields_ = ['typecode']
48 typecode = 'P'
49
50 def cffi_type(self, space):
51 state = space.fromcache(ffitypes.State)
52 return state.c_voidp
53
54 def execute(self, space, cppmethod, cppthis, num_args, args):
55 if hasattr(space, "fake"):
56 raise NotImplementedError
57 address = capi.c_call_r(space, cppmethod, cppthis, num_args, args)
58 ipv = rffi.cast(rffi.UINTPTR_T, address)
59 if ipv == rffi.cast(rffi.UINTPTR_T, 0):
60 from pypy.module._cppyy import interp_cppyy
61 return interp_cppyy.get_nullptr(space)
62 shape = letter2tp(space, self.typecode)
63 return lowlevelviews.W_LowLevelView(space, shape, sys.maxint/shape.size, ipv)
64
65
66 class VoidExecutor(Executor):
67 def cffi_type(self, space):
68 state = space.fromcache(ffitypes.State)
69 return state.c_void
70
71 def execute(self, space, cppmethod, cppthis, num_args, args):
72 capi.c_call_v(space, cppmethod, cppthis, num_args, args)
73 return space.w_None
74
75 def execute_libffi(self, space, cif_descr, funcaddr, buf):
76 jit_libffi.jit_ffi_call(cif_descr, funcaddr, buf)
77 return space.w_None
78
79
80 class NumericExecutorMixin(object):
81 _mixin_ = True
82
83 def execute(self, space, cppmethod, cppthis, num_args, args):
84 result = self.c_stubcall(space, cppmethod, cppthis, num_args, args)
85 return self._wrap_object(space, rffi.cast(self.c_type, result))
86
87 def execute_libffi(self, space, cif_descr, funcaddr, buf):
88 jit_libffi.jit_ffi_call(cif_descr, funcaddr, buf)
89 result = rffi.ptradd(buf, cif_descr.exchange_result)
90 return self._wrap_object(space, rffi.cast(self.c_ptrtype, result)[0])
91
92 class NumericRefExecutorMixin(object):
93 _mixin_ = True
94
95 def __init__(self, space, extra):
96 Executor.__init__(self, space, extra)
97 self.do_assign = False
98 self.w_item = space.w_None
99
100 def set_item(self, space, w_item):
101 self.w_item = w_item
102 self.do_assign = True
103
104 def _wrap_reference(self, space, rffiptr):
105 if self.do_assign:
106 rffiptr[0] = rffi.cast(self.c_type, self._unwrap_object(space, self.w_item))
107 self.do_assign = False
108 return self._wrap_object(space, rffiptr[0]) # all paths, for rtyper
109
110 def execute(self, space, cppmethod, cppthis, num_args, args):
111 result = capi.c_call_r(space, cppmethod, cppthis, num_args, args)
112 return self._wrap_reference(space, rffi.cast(self.c_ptrtype, result))
113
114 def execute_libffi(self, space, cif_descr, funcaddr, buf):
115 jit_libffi.jit_ffi_call(cif_descr, funcaddr, buf)
116 result = rffi.ptradd(buf, cif_descr.exchange_result)
117 return self._wrap_reference(space,
118 rffi.cast(self.c_ptrtype, rffi.cast(rffi.VOIDPP, result)[0]))
119
120 class LongDoubleExecutorMixin(object):
121 # Note: not really supported, but returns normal double
122 _mixin_ = True
123
124 def execute(self, space, cppmethod, cppthis, num_args, args):
125 result = self.c_stubcall(space, cppmethod, cppthis, num_args, args)
126 return space.newfloat(result)
127
128 def execute_libffi(self, space, cif_descr, funcaddr, buf):
129 from pypy.module._cppyy.interp_cppyy import FastCallNotPossible
130 raise FastCallNotPossible
131
132 class LongDoubleExecutor(ffitypes.typeid(rffi.LONGDOUBLE), LongDoubleExecutorMixin, Executor):
133 _immutable_ = True
134 c_stubcall = staticmethod(capi.c_call_ld)
135
136 class LongDoubleRefExecutorMixin(NumericRefExecutorMixin):
137 # Note: not really supported, but returns normal double
138 _mixin_ = True
139
140 def _wrap_reference(self, space, rffiptr):
141 if self.do_assign:
142 capi.c_double2longdouble(space, space.float_w(self.w_item), rffiptr)
143 self.do_assign = False
144 return self.w_item
145 return space.newfloat(capi.c_longdouble2double(space, rffiptr))
146
147 def execute(self, space, cppmethod, cppthis, num_args, args):
148 result = capi.c_call_r(space, cppmethod, cppthis, num_args, args)
149 return self._wrap_reference(space, rffi.cast(self.c_ptrtype, result))
150
151 def execute_libffi(self, space, cif_descr, funcaddr, buf):
152 jit_libffi.jit_ffi_call(cif_descr, funcaddr, buf)
153 result = rffi.ptradd(buf, cif_descr.exchange_result)
154 return self._wrap_reference(space,
155 rffi.cast(self.c_ptrtype, rffi.cast(rffi.VOIDPP, result)[0]))
156
157 class LongDoubleRefExecutor(ffitypes.typeid(rffi.LONGDOUBLE), LongDoubleRefExecutorMixin, Executor):
158 def cffi_type(self, space):
159 state = space.fromcache(ffitypes.State)
160 return state.c_voidp
161
162
163 class CStringExecutor(Executor):
164 def execute(self, space, cppmethod, cppthis, num_args, args):
165 vptr = capi.c_call_r(space, cppmethod, cppthis, num_args, args)
166 ccp = rffi.cast(rffi.CCHARP, vptr)
167 if ccp == rffi.cast(rffi.CCHARP, 0):
168 return space.newbytes("")
169 result = rffi.charp2str(ccp) # TODO: make it a choice to free
170 # debatable whether this should be newtext or newbytes; they are bytes
171 # but will be more likely used as text after binding ... probably need
172 # to make this configurable on a per-function bases (same as the old
173 # char* v.s. byte* problem)
174 return space.newtext(result)
175 return space.newtext(result)
176
177
178 class CharNExecutor(object):
179 _mixin_ = True
180 def execute(self, space, cppmethod, cppthis, num_args, args):
181 lres = capi.c_call_l(space, cppmethod, cppthis, num_args, args)
182 return self._wrap_object(space, lres)
183
184 def execute_libffi(self, space, cif_descr, funcaddr, buf):
185 jit_libffi.jit_ffi_call(cif_descr, funcaddr, buf)
186 vptr = rffi.ptradd(buf, cif_descr.exchange_result)
187 lres = rffi.cast(rffi.LONG, rffi.cast(rffi.LONGP, vptr)[0])
188 return self._wrap_object(space, lres)
189
190 class WCharExecutor(ffitypes.typeid(lltype.UniChar), CharNExecutor, Executor):
191 pass
192
193 class Char16Executor(ffitypes.typeid(ffitypes.CHAR16_T), CharNExecutor, Executor):
194 pass
195
196 class Char32Executor(ffitypes.typeid(ffitypes.CHAR32_T), CharNExecutor, Executor):
197 pass
198
199
200 class ConstructorExecutor(Executor):
201 def execute(self, space, cppmethod, cpptype, num_args, args):
202 from pypy.module._cppyy import interp_cppyy
203 newthis = capi.c_constructor(space, cppmethod, cpptype, num_args, args)
204 assert lltype.typeOf(newthis) == capi.C_OBJECT
205 return space.newlong(rffi.cast(rffi.LONG, newthis)) # really want ptrdiff_t here
206
207
208 class InstanceExecutor(Executor):
209 # For return of a C++ instance by value: MyClass func()
210 _immutable_fields_ = ['clsdecl']
211
212 def __init__(self, space, clsdecl):
213 Executor.__init__(self, space, clsdecl)
214 self.clsdecl = clsdecl
215
216 def _wrap_result(self, space, obj):
217 from pypy.module._cppyy import interp_cppyy
218 return interp_cppyy.wrap_cppinstance(space,
219 obj, self.clsdecl, do_cast=False, python_owns=True, fresh=True)
220
221 def execute(self, space, cppmethod, cppthis, num_args, args):
222 oresult = capi.c_call_o(space, cppmethod, cppthis, num_args, args, self.clsdecl)
223 return self._wrap_result(space, rffi.cast(capi.C_OBJECT, oresult))
224
225
226 class InstancePtrExecutor(InstanceExecutor):
227 # For return of a C++ instance by pointer: MyClass* func()
228
229 def cffi_type(self, space):
230 state = space.fromcache(ffitypes.State)
231 return state.c_voidp
232
233 def _wrap_result(self, space, obj):
234 from pypy.module._cppyy import interp_cppyy
235 return interp_cppyy.wrap_cppinstance(space, obj, self.clsdecl)
236
237 def execute(self, space, cppmethod, cppthis, num_args, args):
238 vptr = capi.c_call_r(space, cppmethod, cppthis, num_args, args)
239 return self._wrap_result(space, rffi.cast(capi.C_OBJECT, vptr))
240
241 def execute_libffi(self, space, cif_descr, funcaddr, buf):
242 jit_libffi.jit_ffi_call(cif_descr, funcaddr, buf)
243 presult = rffi.ptradd(buf, cif_descr.exchange_result)
244 obj = rffi.cast(capi.C_OBJECT, rffi.cast(rffi.VOIDPP, presult)[0])
245 return self._wrap_result(space, obj)
246
247 class InstancePtrPtrExecutor(InstancePtrExecutor):
248 # For return of a C++ instance by ptr-to-ptr or ptr-to-ref: MyClass*& func()
249
250 def execute(self, space, cppmethod, cppthis, num_args, args):
251 presult = capi.c_call_r(space, cppmethod, cppthis, num_args, args)
252 vref = rffi.cast(rffi.VOIDPP, presult)
253 return self._wrap_result(space, rffi.cast(capi.C_OBJECT, vref[0]))
254
255 def execute_libffi(self, space, cif_descr, funcaddr, buf):
256 from pypy.module._cppyy.interp_cppyy import FastCallNotPossible
257 raise FastCallNotPossible
258
259
260 class ComplexExecutor(Executor):
261 _immutable_fields_ = ['clsdecl', 'realf', 'imagf']
262
263 def __init__(self, space, clsdecl):
264 Executor.__init__(self, space, clsdecl)
265 self.clsdecl = clsdecl
266 self.realf = self.clsdecl.scope__dispatch__('real', '')
267 self.imagf = self.clsdecl.scope__dispatch__('imag', '')
268
269 def _convert2complex(self, space, cmplx):
270 w_real = self.realf.call_impl(cmplx, [])
271 w_imag = self.imagf.call_impl(cmplx, [])
272 return space.newcomplex(space.float_w(w_real), space.float_w(w_imag))
273
274 def execute(self, space, cppmethod, cppthis, num_args, args):
275 cmplx = capi.c_call_o(space, cppmethod, cppthis, num_args, args, self.clsdecl)
276 pycmplx = self._convert2complex(space, rffi.cast(capi.C_OBJECT, cmplx))
277 capi.c_destruct(space, self.clsdecl, cmplx)
278 return pycmplx
279
280 class ComplexRefExecutor(ComplexExecutor):
281 def execute(self, space, cppmethod, cppthis, num_args, args):
282 cmplx = capi.c_call_r(space, cppmethod, cppthis, num_args, args)
283 return self._convert2complex(space, rffi.cast(capi.C_OBJECT, cmplx))
284
285 def execute_libffi(self, space, cif_descr, funcaddr, buf):
286 jit_libffi.jit_ffi_call(cif_descr, funcaddr, buf)
287 result = rffi.ptradd(buf, cif_descr.exchange_result)
288 return self._convert2complex(space,
289 rffi.cast(capi.C_OBJECT, rffi.cast(rffi.VOIDPP, result)[0]))
290
291
292 class StdStringExecutor(InstancePtrExecutor):
293 def execute(self, space, cppmethod, cppthis, num_args, args):
294 cstr, cstr_len = capi.c_call_s(space, cppmethod, cppthis, num_args, args)
295 pystr = rffi.charpsize2str(cstr, cstr_len)
296 capi.c_free(space, rffi.cast(rffi.VOIDP, cstr))
297 return space.newbytes(pystr)
298
299 def execute_libffi(self, space, cif_descr, funcaddr, buf):
300 from pypy.module._cppyy.interp_cppyy import FastCallNotPossible
301 raise FastCallNotPossible
302
303 class StdStringRefExecutor(InstancePtrExecutor):
304 def __init__(self, space, clsdecl):
305 from pypy.module._cppyy import interp_cppyy
306 clsdecl = interp_cppyy.scope_byname(space, capi.std_string_name)
307 InstancePtrExecutor.__init__(self, space, clsdecl)
308
309
310 class PyObjectExecutor(PtrTypeExecutor):
311 def wrap_result(self, space, lresult):
312 space.getbuiltinmodule("cpyext")
313 from pypy.module.cpyext.pyobject import PyObject, from_ref, make_ref, decref
314 result = rffi.cast(PyObject, lresult)
315 w_obj = from_ref(space, result)
316 if result:
317 decref(space, result)
318 return w_obj
319
320 def execute(self, space, cppmethod, cppthis, num_args, args):
321 if hasattr(space, "fake"):
322 raise NotImplementedError
323 vptr = capi.c_call_r(space, cppmethod, cppthis, num_args, args)
324 return self.wrap_result(space, vptr)
325
326 def execute_libffi(self, space, cif_descr, funcaddr, buf):
327 if hasattr(space, "fake"):
328 raise NotImplementedError
329 jit_libffi.jit_ffi_call(cif_descr, funcaddr, buf)
330 result = rffi.ptradd(buf, cif_descr.exchange_result)
331 return self.wrap_result(space, rffi.cast(rffi.VOIDPP, result)[0])
332
333
334 class SmartPointerExecutor(InstanceExecutor):
335 _immutable_fields_ = ['smartdecl', 'deref']
336
337 def __init__(self, space, smartdecl, raw, deref):
338 from pypy.module._cppyy.interp_cppyy import W_CPPClassDecl, get_pythonized_cppclass
339 w_raw = get_pythonized_cppclass(space, raw)
340 rawdecl = space.interp_w(W_CPPClassDecl, space.findattr(w_raw, space.newtext("__cppdecl__")))
341 InstanceExecutor.__init__(self, space, rawdecl)
342 self.smartdecl = smartdecl
343 self.deref = deref
344
345 def _wrap_result(self, space, obj):
346 from pypy.module._cppyy import interp_cppyy
347 return interp_cppyy.wrap_cppinstance(space, obj, self.clsdecl,
348 self.smartdecl, self.deref, do_cast=False, python_owns=True, fresh=True)
349
350 class SmartPointerPtrExecutor(InstancePtrExecutor):
351 _immutable_fields_ = ['smartdecl', 'deref']
352
353 def __init__(self, space, smartdecl, raw, deref):
354 # TODO: share this with SmartPointerExecutor through in mixin
355 from pypy.module._cppyy.interp_cppyy import W_CPPClassDecl, get_pythonized_cppclass
356 w_raw = get_pythonized_cppclass(space, raw)
357 rawdecl = space.interp_w(W_CPPClassDecl, space.findattr(w_raw, space.newtext("__cppdecl__")))
358 InstancePtrExecutor.__init__(self, space, rawdecl)
359 self.smartdecl = smartdecl
360 self.deref = deref
361
362 def _wrap_result(self, space, obj):
363 from pypy.module._cppyy import interp_cppyy
364 # TODO: this is a pointer to a smart pointer, take ownership on the smart one?
365 return interp_cppyy.wrap_cppinstance(space, obj, self.clsdecl,
366 self.smartdecl, self.deref, do_cast=False)
367
368
369 _executors = {}
370 def get_executor(space, name):
371 # Matching of 'name' to an executor factory goes through up to four levels:
372 # 1) full, qualified match
373 # 2) drop '&': by-ref is pretty much the same as by-value, python-wise
374 # 3) types/classes, either by ref/ptr or by value
375 # 4) additional special cases
376 #
377 # If all fails, a default is used, which can be ignored at least until use.
378
379 # original, exact match
380 try:
381 return _executors[name](space, None)
382 except KeyError:
383 pass
384
385 # resolved, exact match
386 name = capi.c_resolve_name(space, name)
387 try:
388 return _executors[name](space, None)
389 except KeyError:
390 pass
391
392 compound = helper.compound(name)
393 clean_name = capi.c_resolve_name(space, helper.clean_type(name))
394
395 # clean lookup
396 try:
397 return _executors[clean_name+compound](space, None)
398 except KeyError:
399 pass
400
401 # drop '&': by-ref is pretty much the same as by-value, python-wise
402 if compound and compound[len(compound)-1] == '&':
403 # TODO: this does not actually work with Reflex (?)
404 try:
405 return _executors[clean_name](space, None)
406 except KeyError:
407 pass
408
409 # types/classes, either by ref/ptr or by value
410 from pypy.module._cppyy import interp_cppyy
411 cppclass = interp_cppyy.scope_byname(space, clean_name)
412 if cppclass:
413 # type check for the benefit of the annotator
414 from pypy.module._cppyy.interp_cppyy import W_CPPClassDecl
415 clsdecl = space.interp_w(W_CPPClassDecl, cppclass, can_be_None=False)
416
417 # check smart pointer type
418 check_smart = capi.c_smartptr_info(space, clean_name)
419 if check_smart[0]:
420 if compound == '':
421 return SmartPointerExecutor(space, clsdecl, check_smart[1], check_smart[2])
422 elif compound == '*' or compound == '&':
423 return SmartPointerPtrExecutor(space, clsdecl, check_smart[1], check_smart[2])
424 # fall through: can still return smart pointer in non-smart way
425
426 if clean_name.find('std::complex', 0, 12) == 0 and\
427 (0 < clean_name.find('double') or 0 < clean_name.find('float')):
428 if compound == '':
429 return ComplexExecutor(space, clsdecl)
430 elif compound == '&':
431 return ComplexRefExecutor(space, clsdecl)
432
433 if compound == '':
434 return InstanceExecutor(space, clsdecl)
435 elif compound == '*' or compound == '&':
436 return InstancePtrExecutor(space, clsdecl)
437 elif compound == '**' or compound == '*&':
438 return InstancePtrPtrExecutor(space, clsdecl)
439 elif "(anonymous)" in name:
440 # special case: enum w/o a type name
441 return _executors["internal_enum_type_t"](space, None)
442
443 # 4) additional special cases
444 if compound == '*':
445 return _executors['void*'](space, None) # allow at least passing of the pointer
446
447 # currently used until proper lazy instantiation available in interp_cppyy
448 return Executor(space, None)
449
450
451 _executors["void"] = VoidExecutor
452 _executors["void*"] = PtrTypeExecutor
453 _executors["const char*"] = CStringExecutor
454 _executors["wchar_t"] = WCharExecutor
455 _executors["char16_t"] = Char16Executor
456 _executors["char32_t"] = Char32Executor
457
458 # long double not really supported: narrows to double
459 _executors["long double"] = LongDoubleExecutor
460 _executors["long double&"] = LongDoubleRefExecutor
461
462 # special cases (note: 'string' aliases added below)
463 _executors["constructor"] = ConstructorExecutor
464
465 _executors["std::basic_string<char>"] = StdStringExecutor
466 _executors["const std::basic_string<char>&"] = StdStringRefExecutor
467 _executors["std::basic_string<char>&"] = StdStringRefExecutor
468
469 _executors["PyObject*"] = PyObjectExecutor
470
471 # add basic (builtin) executors
472 def _build_basic_executors():
473 "NOT_RPYTHON"
474 type_info = (
475 (bool, capi.c_call_b, ("bool",)),
476 # TODO: either signed or unsigned is correct for a given platform ...
477 (rffi.CHAR, capi.c_call_c, ("char", "unsigned char", "signed char")),
478 (ffitypes.INT8_T, capi.c_call_c, ("int8_t",)),
479 (ffitypes.UINT8_T, capi.c_call_c, ("uint8_t", "std::byte", "byte",)),
480 (rffi.SHORT, capi.c_call_h, ("short", "short int", "unsigned short", "unsigned short int")),
481 (rffi.INT, capi.c_call_i, ("int", "internal_enum_type_t")),
482 (rffi.UINT, capi.c_call_l, ("unsigned", "unsigned int")),
483 (rffi.LONG, capi.c_call_l, ("long", "long int")),
484 (rffi.ULONG, capi.c_call_l, ("unsigned long", "unsigned long int")),
485 (rffi.LONGLONG, capi.c_call_ll, ("long long", "long long int", "Long64_t")),
486 (rffi.ULONGLONG, capi.c_call_ll, ("unsigned long long", "unsigned long long int", "ULong64_t")),
487 (rffi.FLOAT, capi.c_call_f, ("float",)),
488 (rffi.DOUBLE, capi.c_call_d, ("double",)),
489 # (rffi.LONGDOUBLE, capi.c_call_ld, ("long double",)),
490 )
491
492 for c_type, stub, names in type_info:
493 class BasicExecutor(ffitypes.typeid(c_type), NumericExecutorMixin, Executor):
494 _immutable_ = True
495 c_stubcall = staticmethod(stub)
496 class BasicRefExecutor(ffitypes.typeid(c_type), NumericRefExecutorMixin, Executor):
497 def cffi_type(self, space):
498 state = space.fromcache(ffitypes.State)
499 return state.c_voidp
500 for name in names:
501 _executors[name] = BasicExecutor
502 _executors[name+'&'] = BasicRefExecutor
503 _executors['const '+name+'&'] = BasicRefExecutor # no copy needed for builtins
504 _build_basic_executors()
505
506 # create the pointer executors; all real work is in the PtrTypeExecutor, since
507 # all pointer types are of the same size
508 def _build_ptr_executors():
509 "NOT_RPYTHON"
510 ptr_info = (
511 ('b', ("bool",)), # really unsigned char, but this works ...
512 ('h', ("short int", "short")),
513 ('H', ("unsigned short int", "unsigned short")),
514 ('i', ("int",)),
515 ('I', ("unsigned int", "unsigned")),
516 ('l', ("long int", "long")),
517 ('L', ("unsigned long int", "unsigned long")),
518 ('f', ("float",)),
519 ('d', ("double",)),
520 )
521
522 for tcode, names in ptr_info:
523 class PtrExecutor(PtrTypeExecutor):
524 _immutable_fields_ = ['typecode']
525 typecode = tcode
526 for name in names:
527 _executors[name+'*'] = PtrExecutor
528 _build_ptr_executors()
529
530 # add another set of aliased names
531 def _add_aliased_executors():
532 "NOT_RPYTHON"
533 aliases = (
534 ("const char*", "char*"),
535
536 ("std::basic_string<char>", "std::string"),
537 ("const std::basic_string<char>&", "const std::string&"),
538 ("std::basic_string<char>&", "std::string&"),
539
540 ("PyObject*", "_object*"),
541 )
542
543 for c_type, alias in aliases:
544 _executors[alias] = _executors[c_type]
545 _add_aliased_executors()