Debian Codegraph @

pypy/module/_cppyy/interp_cppyy.py

raw symbols SCIP
1 import pypy.module._cppyy.capi as capi
2
3 from pypy.interpreter.error import OperationError, oefmt
4 from pypy.interpreter.function import Method
5 from pypy.interpreter.argument import Arguments
6 from pypy.interpreter.typedef import interp_attrproperty_w, descr_generic_ne, make_weakref_descr
7 from pypy.interpreter.gateway import interp2app, unwrap_spec
8 from pypy.interpreter.typedef import TypeDef, GetSetProperty, interp_attrproperty
9 from pypy.interpreter.baseobjspace import W_Root
10
11 from rpython.rtyper.lltypesystem import rffi, lltype, llmemory
12
13 from rpython.rlib import jit, rweakref, rgc
14 from rpython.rlib import jit_libffi, clibffi
15 from rpython.rlib.objectmodel import we_are_translated, keepalive_until_here
16
17 from pypy.module._cffi_backend import ctypefunc
18 from pypy.module._cppyy import converter, executor, ffitypes, helper
19
20 CLASS_FLAGS_IS_PINNED = 0x0001
21
22 INSTANCE_FLAGS_PYTHON_OWNS = 0x0001
23 INSTANCE_FLAGS_IS_REF = 0x0002
24 INSTANCE_FLAGS_IS_RVALUE = 0x0004
25
26 OVERLOAD_FLAGS_USE_FFI = 0x0001
27 OVERLOAD_FLAGS_CREATES = 0x0002
28
29 FUNCTION_IS_GLOBAL = 0x0001
30 FUNCTION_IS_STATIC = 0x0001
31 FUNCTION_IS_METHOD = 0x0002
32 FUNCTION_IS_CONSTRUCTOR = 0x0004
33 FUNCTION_IS_TEMPLATE = 0x0008
34 FUNCTION_IS_SETITEM = 0x0010
35
36
37 class FastCallNotPossible(Exception):
38 pass
39
40 # overload priorities: lower is preferred
41 priority = { 'void*' : 100,
42 'void**' : 100,
43 'float' : 30,
44 'double' : 10,
45 'bool' : 1,
46 'const string&' : 1, } # solves a specific string ctor overload
47
48 from rpython.rlib.listsort import make_timsort_class
49 CPPMethodBaseTimSort = make_timsort_class()
50 class CPPMethodSort(CPPMethodBaseTimSort):
51 def lt(self, a, b):
52 return a.priority() < b.priority()
53
54 class State(object):
55 def __init__(self, space):
56 # final scoped name -> opaque handle
57 self.cppscope_cache = {
58 'void' : W_CPPClassDecl(space, capi.C_NULL_TYPE, 'void') }
59 # opaque handle -> app-level python class
60 self.cppclass_registry = {}
61 # app-level class generator callback
62 self.w_clgen_callback = None
63 # app-level function generator callback (currently not used)
64 self.w_fngen_callback = None
65 # C++11's nullptr
66 self.w_nullptr = None
67
68 def get_nullptr(space):
69 # construct a unique address that compares to NULL, serves as nullptr
70 if hasattr(space, 'fake'):
71 raise NotImplementedError
72 state = space.fromcache(State)
73 if state.w_nullptr is None:
74 from pypy.module._rawffi.interp_rawffi import unpack_simple_shape
75 from pypy.module._rawffi.interp_array import W_Array, W_ArrayInstance
76 arr = space.interp_w(W_Array, unpack_simple_shape(space, space.newtext('P')))
77 # TODO: fix this hack; fromaddress() will allocate memory if address
78 # is null and there seems to be no way around it (ll_buffer can not
79 # be touched directly)
80 nullarr = arr.fromaddress(space, rffi.cast(rffi.ULONG, 0), 0)
81 assert isinstance(nullarr, W_ArrayInstance)
82 nullarr.free(space)
83 state.w_nullptr = nullarr
84 return state.w_nullptr
85
86 @unwrap_spec(scoped_name='text')
87 def resolve_name(space, scoped_name):
88 return space.newtext(capi.c_resolve_name(space, scoped_name))
89
90
91 # memoized lookup of handles by final, scoped, name of classes/namespaces
92 @unwrap_spec(final_scoped_name='text')
93 def scope_byname(space, final_scoped_name):
94 state = space.fromcache(State)
95 try:
96 return state.cppscope_cache[final_scoped_name]
97 except KeyError:
98 pass
99
100 opaque_handle = capi.c_get_scope_opaque(space, final_scoped_name)
101 assert lltype.typeOf(opaque_handle) == capi.C_SCOPE
102 if opaque_handle:
103 isns = capi.c_is_namespace(space, opaque_handle)
104 if isns:
105 cppscope = W_CPPNamespaceDecl(space, opaque_handle, final_scoped_name)
106 else:
107 if capi.c_has_complex_hierarchy(space, opaque_handle):
108 cppscope = W_CPPComplexClassDecl(space, opaque_handle, final_scoped_name)
109 else:
110 cppscope = W_CPPClassDecl(space, opaque_handle, final_scoped_name)
111
112 # store in the cache to prevent recursion
113 state.cppscope_cache[final_scoped_name] = cppscope
114
115 if not isns:
116 # build overloads/data; TODO: also defer this for classes (a functional __dir__
117 # and instrospection for help() is enough and allows more lazy loading)
118 cppscope._build_overloads()
119 cppscope._find_datamembers()
120
121 return cppscope
122
123 return None
124
125 @unwrap_spec(final_scoped_name='text')
126 def is_template(space, final_scoped_name):
127 return space.newbool(capi.c_is_template(space, final_scoped_name))
128
129 def std_string_name(space):
130 return space.newtext(capi.std_string_name)
131
132 @unwrap_spec(w_callback=W_Root)
133 def set_class_generator(space, w_callback):
134 state = space.fromcache(State)
135 state.w_clgen_callback = w_callback
136
137 @unwrap_spec(w_callback=W_Root)
138 def set_function_generator(space, w_callback):
139 state = space.fromcache(State)
140 state.w_fngen_callback = w_callback
141
142 def register_class(space, w_pycppclass):
143 w_cppclass = space.findattr(w_pycppclass, space.newtext("__cppdecl__"))
144 cppclass = space.interp_w(W_CPPClassDecl, w_cppclass)
145 # add back-end specific method pythonizations (doing this on the wrapped
146 # class allows simple aliasing of methods)
147 capi.pythonize(space, w_pycppclass, cppclass.name)
148 state = space.fromcache(State)
149 state.cppclass_registry[cppclass.handle] = w_pycppclass
150
151
152 class W_CPPLibrary(W_Root):
153 _immutable_ = True
154
155 def __init__(self, space, cdll):
156 self.cdll = cdll
157 self.space = space
158
159 W_CPPLibrary.typedef = TypeDef(
160 'CPPLibrary',
161 )
162 W_CPPLibrary.typedef.acceptable_as_base_class = True
163
164
165 #-----
166 # Classes involved with methods and functions come at two levels:
167 # - overloads: user-facing collections of overloaded functions
168 # - wrappers: internal holders of the individual C++ methods
169 #
170 # W_CPPOverload: instance methods (base class)
171 # W_CPPConstructorOverload: constructors
172 # W_CPPAbstractCtorOverload: to prevent instantiation of abstract classes
173 # W_CPPStaticOverload: free and static functions
174 # W_CPPTemplateOverload: templated methods
175 # W_CPPTemplateStaticOverload: templated free and static functions
176 #
177 # CPPMethod: a single function or method (base class)
178 # CPPSetItem: specialization for Python's __setitem__
179 #
180 # MethodWithProps: python instancemethod that forwards properties
181 #
182 # All methods/functions derive from CPPMethod and are collected as overload
183 # candidates in user-facing overload classes. Templated methods are a two-step
184 # process, where first the template is instantiated (or selected if already
185 # available), which returns a callable object that is the actual bound method.
186
187 class CPPMethod(object):
188 """Dispatcher of methods. Checks the arguments, find the corresponding FFI
189 function if available, makes the call, and returns the wrapped result. It
190 also takes care of offset casting and recycling of known objects through
191 the memory_regulator."""
192
193 _attrs_ = ['space', 'scope', 'cppmethod', 'arg_defs', 'args_required',
194 'converters', 'executor', '_funcaddr', 'cif_descr']
195 _immutable_fields_ = ['scope', 'cppmethod', 'arg_defs', 'args_required',
196 'converters', 'executor', '_funcaddr', 'cif_descr']
197
198 def __init__(self, space, decl_scope, cppmethod, arg_defs, args_required):
199 self.space = space
200 self.scope = decl_scope
201 self.cppmethod = cppmethod
202 self.arg_defs = arg_defs
203 self.args_required = args_required
204
205 # Setup of the method dispatch's innards is done lazily, i.e. only when
206 # the method is actually used.
207 self.converters = None
208 self.executor = None
209 self.cif_descr = lltype.nullptr(jit_libffi.CIF_DESCRIPTION)
210 self._funcaddr = lltype.nullptr(capi.C_FUNC_PTR.TO)
211
212 @jit.unroll_safe
213 def call(self, cppthis, args_w, useffi):
214 jit.promote(self)
215
216 assert lltype.typeOf(cppthis) == capi.C_OBJECT
217
218 # check number of given arguments against required (== total - defaults)
219 args_expected = len(self.arg_defs)
220 args_given = len(args_w)
221
222 if args_given < self.args_required:
223 raise oefmt(self.space.w_TypeError,
224 "takes at least %d arguments (%d given)", self.args_required, args_given)
225 elif args_expected < args_given:
226 raise oefmt(self.space.w_TypeError,
227 "takes at most %d arguments (%d given)", args_expected, args_given)
228
229 # initial setup of converters, executors, and libffi (if available)
230 if self.converters is None:
231 try:
232 self._setup(cppthis)
233 except Exception as e:
234 if self.converters is None:
235 raise oefmt(self.space.w_SystemError,
236 "unable to initialize converters (%s)", str(e))
237
238 # attempt to call directly through ffi chain
239 if useffi and self._funcaddr:
240 try:
241 return self.do_fast_call(cppthis, args_w)
242 except FastCallNotPossible:
243 pass # can happen if converters or executor does not implement ffi
244
245 # ffi chain must have failed; using stub functions instead
246 args, stat = self.prepare_arguments(args_w)
247 try:
248 result = self.executor.execute(
249 self.space, self.cppmethod, cppthis, len(args_w), args)
250 if stat[0] != rffi.cast(rffi.ULONG, 0):
251 what = rffi.cast(rffi.CCHARP, stat[1])
252 pywhat = rffi.charp2str(what)
253 capi.c_free(self.space, rffi.cast(rffi.VOIDP, what))
254 raise OperationError(self.space.w_Exception, self.space.newtext(pywhat))
255 return result
256 finally:
257 self.finalize_call(args, args_w)
258
259 @jit.unroll_safe
260 def do_fast_call(self, cppthis, args_w):
261 if self.cif_descr == lltype.nullptr(jit_libffi.CIF_DESCRIPTION):
262 raise FastCallNotPossible
263 jit.promote(self)
264 cif_descr = self.cif_descr
265 # add extra space for const-ref support (see converter.py)
266 buffer = lltype.malloc(rffi.CCHARP.TO,
267 cif_descr.exchange_size+len(self.arg_defs)*rffi.sizeof(rffi.DOUBLE), flavor='raw')
268 thisoff = 0
269 try:
270 if cppthis:
271 # this pointer
272 data = rffi.ptradd(buffer, cif_descr.exchange_args[0])
273 x = rffi.cast(rffi.VOIDPP, data)
274 x[0] = rffi.cast(rffi.VOIDP, cppthis)
275 thisoff = 1
276
277 # actual provided arguments
278 i = -1 # needed if all arguments are defaults
279 for i in range(len(args_w)):
280 conv = self.converters[i]
281 data = rffi.ptradd(buffer, cif_descr.exchange_args[i+thisoff])
282 scratch = rffi.ptradd(buffer, cif_descr.exchange_size+i*rffi.sizeof(rffi.DOUBLE))
283 conv.convert_argument_libffi(self.space, args_w[i], data, scratch)
284 # drop in defaults for the rest
285 for j in range(i+1, len(self.arg_defs)):
286 conv = self.converters[j]
287 data = rffi.ptradd(buffer, cif_descr.exchange_args[j+thisoff])
288 conv.default_argument_libffi(self.space, data)
289
290 assert self._funcaddr
291 w_res = self.executor.execute_libffi(
292 self.space, cif_descr, self._funcaddr, buffer)
293 finally:
294 lltype.free(buffer, flavor='raw')
295 keepalive_until_here(args_w)
296 return w_res
297
298 # from ctypefunc; have my own version for annotater purposes and to disable
299 # memory tracking (method life time is longer than the tests)
300 @jit.dont_look_inside
301 def _rawallocate(self, builder):
302 builder.space = self.space
303
304 # compute the total size needed in the CIF_DESCRIPTION buffer
305 builder.nb_bytes = 0
306 builder.bufferp = lltype.nullptr(rffi.CCHARP.TO)
307 builder.fb_build()
308
309 # allocate the buffer
310 if we_are_translated():
311 rawmem = lltype.malloc(rffi.CCHARP.TO, builder.nb_bytes,
312 flavor='raw')
313 rawmem = rffi.cast(jit_libffi.CIF_DESCRIPTION_P, rawmem)
314 else:
315 # gross overestimation of the length below, but too bad
316 rawmem = lltype.malloc(jit_libffi.CIF_DESCRIPTION_P.TO, builder.nb_bytes,
317 flavor='raw', track_allocation=False)
318
319 # the buffer is automatically managed from the W_CTypeFunc instance
320 self.cif_descr = rawmem
321
322 # call again fb_build() to really build the libffi data structures
323 builder.bufferp = rffi.cast(rffi.CCHARP, rawmem)
324 builder.fb_build()
325 assert builder.bufferp == rffi.ptradd(rffi.cast(rffi.CCHARP, rawmem),
326 builder.nb_bytes)
327
328 # fill in the 'exchange_*' fields
329 builder.fb_build_exchange(rawmem)
330
331 # fill in the extra fields
332 builder.fb_extra_fields(rawmem)
333
334 # call libffi's ffi_prep_cif() function
335 res = jit_libffi.jit_ffi_prep_cif(rawmem)
336 if res != clibffi.FFI_OK:
337 raise oefmt(self.space.w_SystemError,
338 "libffi failed to build this function type")
339
340 def _setup(self, cppthis):
341 self.converters = [converter.get_converter(self.space, arg_type, arg_dflt)
342 for arg_type, arg_dflt in self.arg_defs]
343 self.executor = executor.get_executor(
344 self.space, capi.c_method_result_type(self.space, self.cppmethod))
345
346 # Each CPPMethod corresponds one-to-one to a C++ equivalent and cppthis
347 # has been offset to the matching class. Hence, the libffi pointer is
348 # uniquely defined and needs to be setup only once.
349 funcaddr = capi.c_function_address(self.space, self.cppmethod)
350 if funcaddr:
351 state = self.space.fromcache(ffitypes.State)
352
353 # argument type specification (incl. cppthis if applicable)
354 fargs = []
355 try:
356 if cppthis: fargs.append(state.c_voidp)
357 for i, conv in enumerate(self.converters):
358 fargs.append(conv.cffi_type(self.space))
359 fresult = self.executor.cffi_type(self.space)
360 except:
361 raise FastCallNotPossible
362
363 # the following is derived from _cffi_backend.ctypefunc
364 builder = ctypefunc.CifDescrBuilder(fargs[:], fresult, clibffi.FFI_DEFAULT_ABI)
365 try:
366 self._rawallocate(builder)
367 except OperationError as e:
368 if not e.match(self.space, self.space.w_NotImplementedError):
369 raise
370 # else, eat the NotImplementedError. We will get the
371 # exception if we see an actual call
372 if self.cif_descr: # should not be True, but you never know
373 lltype.free(self.cif_descr, flavor='raw')
374 self.cif_descr = lltype.nullptr(jit_libffi.CIF_DESCRIPTION)
375 raise FastCallNotPossible
376
377 # success ...
378 self._funcaddr = funcaddr
379
380 @jit.unroll_safe
381 def prepare_arguments(self, args_w):
382 args = capi.c_allocate_function_args(self.space, len(args_w))
383 stride = capi.c_function_arg_sizeof(self.space)
384 for i in range(len(args_w)):
385 conv = self.converters[i]
386 w_arg = args_w[i]
387 try:
388 arg_i = lltype.direct_ptradd(rffi.cast(rffi.CCHARP, args), i*stride)
389 conv.convert_argument(self.space, w_arg, rffi.cast(capi.C_OBJECT, arg_i))
390 except:
391 # fun :-(
392 for j in range(i):
393 conv = self.converters[j]
394 arg_j = lltype.direct_ptradd(rffi.cast(rffi.CCHARP, args), j*stride)
395 conv.free_argument(self.space, rffi.cast(capi.C_OBJECT, arg_j))
396 capi.c_deallocate_function_args(self.space, args)
397 raise
398 stat = rffi.cast(rffi.ULONGP,
399 lltype.direct_ptradd(rffi.cast(rffi.CCHARP, args), int(len(args_w))*stride))
400 stat[0] = rffi.cast(rffi.ULONG, 0)
401 return args, stat
402
403 @jit.unroll_safe
404 def finalize_call(self, args, args_w):
405 stride = capi.c_function_arg_sizeof(self.space)
406 for i in range(len(args_w)):
407 conv = self.converters[i]
408 arg_i = lltype.direct_ptradd(rffi.cast(rffi.CCHARP, args), i*stride)
409 conv.finalize_call(self.space, args_w[i])
410 conv.free_argument(self.space, rffi.cast(capi.C_OBJECT, arg_i))
411 capi.c_deallocate_function_args(self.space, args)
412
413 def signature(self, show_formalargs=True):
414 return capi.c_method_signature(self.space, self.cppmethod, show_formalargs)
415
416 def prototype(self, show_formalargs=True):
417 return capi.c_method_prototype(self.space, self.scope, self.cppmethod, show_formalargs)
418
419 def priority(self):
420 total_arg_priority = 0
421 for arg_type, arg_dflt in self.arg_defs:
422 total_arg_priority += priority.get(arg_type, 0)
423 if '&&' in arg_type:
424 total_arg_priority += 100
425 return total_arg_priority
426
427 @rgc.must_be_light_finalizer
428 def __del__(self):
429 try:
430 if self.cif_descr:
431 lltype.free(self.cif_descr, flavor='raw')
432 except Exception: # TODO: happens for templates, why?
433 pass
434
435 def __repr__(self):
436 return "CPPMethod: %s" % self.prototype()
437
438 def _freeze_(self):
439 assert 0, "you should never have a pre-built instance of this!"
440
441
442 class CPPSetItem(CPPMethod):
443 """Method dispatcher specific to Python's __setitem__ mapped onto C++'s
444 operator[](T). The former function takes an extra argument to assign to
445 the return type of the latter."""
446
447 _attrs_ = []
448
449 def call(self, cppthis, args_w, useffi):
450 end = len(args_w)-1
451 if 0 <= end:
452 w_item = args_w[end]
453 args_w = args_w[:end]
454 if self.converters is None:
455 self._setup(cppthis)
456 self.executor.set_item(self.space, w_item) # TODO: what about threads?
457 CPPMethod.call(self, cppthis, args_w, useffi)
458
459
460 # CPPOverloads have settable flags that control memory and ffi behavior. These flags
461 # need forwarding, which the normal instancemethod does not provide, hence this
462 # derived class.
463 class MethodWithProps(Method):
464 # set life management of result from the call
465 def fget_creates(self, space):
466 f = space.interp_w(W_CPPOverload, self.w_function)
467 return f.fget_creates(space)
468
469 @unwrap_spec(value=bool)
470 def fset_creates(self, space, value):
471 f = space.interp_w(W_CPPOverload, self.w_function)
472 f.fset_creates(space, value)
473
474 # set ownership policy of arguments (not yet implemented)
475 def fget_mempolicy(self, space):
476 f = space.interp_w(W_CPPOverload, self.w_function)
477 return f.fget_mempolicy(space)
478
479 @unwrap_spec(value=int)
480 def fset_mempolicy(self, space, value):
481 f = space.interp_w(W_CPPOverload, self.w_function)
482 f.fset_mempolicy(space, value)
483
484 # set to release the gil during call (not yet implemented)
485 def fget_release_gil(self, space):
486 f = space.interp_w(W_CPPOverload, self.w_function)
487 return f.fget_release_gil(space)
488
489 @unwrap_spec(value=bool)
490 def fset_release_gil(self, space, value):
491 f = space.interp_w(W_CPPOverload, self.w_function)
492 f.fset_release_gil(space, value)
493
494 # allow user to determine ffi use rules per overload
495 def fget_useffi(self, space):
496 f = space.interp_w(W_CPPOverload, self.w_function)
497 return f.fget_useffi(space)
498
499 @unwrap_spec(value=bool)
500 def fset_useffi(self, space, value):
501 f = space.interp_w(W_CPPOverload, self.w_function)
502 f.fset_useffi(space, value)
503
504 MethodWithProps.typedef = TypeDef(
505 "cpp_instancemethod",
506 __doc__ = """cpp_instancemethod(function, instance, class)
507
508 Create an instance method object.""",
509 __new__ = interp2app(MethodWithProps.descr_method__new__.im_func),
510 __call__ = interp2app(MethodWithProps.descr_method_call),
511 __get__ = interp2app(MethodWithProps.descr_method_get),
512 __func__ = interp_attrproperty_w('w_function', cls=MethodWithProps),
513 __self__ = interp_attrproperty_w('w_instance', cls=MethodWithProps),
514 __getattribute__ = interp2app(MethodWithProps.descr_method_getattribute),
515 __eq__ = interp2app(MethodWithProps.descr_method_eq),
516 __ne__ = descr_generic_ne,
517 __hash__ = interp2app(MethodWithProps.descr_method_hash),
518 __repr__ = interp2app(MethodWithProps.descr_method_repr),
519 __reduce__ = interp2app(MethodWithProps.descr_method__reduce__),
520 __weakref__ = make_weakref_descr(MethodWithProps),
521 __creates__ = GetSetProperty(MethodWithProps.fget_creates, MethodWithProps.fset_creates),
522 __mempolicy__ = GetSetProperty(MethodWithProps.fget_mempolicy, MethodWithProps.fset_mempolicy),
523 __release_gil__ = GetSetProperty(MethodWithProps.fget_release_gil, MethodWithProps.fset_release_gil),
524 __useffi__ = GetSetProperty(MethodWithProps.fget_useffi, MethodWithProps.fset_useffi),
525 )
526 MethodWithProps.typedef.acceptable_as_base_class = False
527
528
529 class W_CPPOverload(W_Root):
530 """App-level dispatcher: controls a collection of (potentially) overloaded methods
531 or functions. Calls these in order and deals with error handling and reporting."""
532
533 _attrs_ = ['space', 'scope', 'functions', 'flags']
534 _immutable_fields_ = ['scope', 'functions[*]']
535
536 def __init__(self, space, decl_scope, funcs, flags = OVERLOAD_FLAGS_USE_FFI):
537 self.space = space
538 self.scope = decl_scope
539 from rpython.rlib import debug
540 self.functions = debug.make_sure_not_resized(funcs)
541 self.flags = flags
542
543 def descr_get(self, w_obj, w_cls=None):
544 """functionobject.__get__(obj[, type]) -> method"""
545 # TODO: check validity of w_cls if given
546 # TODO: this does not work for Python 3, which does not have
547 # unbound methods (probably no common code possible, see also
548 # pypy/interpreter/function.py)
549 space = self.space
550 asking_for_bound = (space.is_none(w_cls) or
551 not space.is_w(w_obj, space.w_None) or
552 space.is_w(w_cls, space.type(space.w_None)))
553 if asking_for_bound:
554 return MethodWithProps(space, self, w_obj)
555 else:
556 return self # unbound methods don't exist in Python 3
557
558 @unwrap_spec(args_w='args_w')
559 def call_args(self, args_w):
560 jit.promote(self)
561 w_this = args_w[0]
562 cppinstance = self.space.interp_w(W_CPPInstance, w_this)
563 cppinstance._nullcheck()
564 if not capi.c_is_subtype(self.space, cppinstance.clsdecl, self.scope):
565 raise oefmt(self.space.w_TypeError,
566 "cannot pass %T instance as %s", w_this, self.scope.name)
567 return self.call_impl(cppinstance.get_cppthis(self.scope), args_w[1:])
568
569 @jit.unroll_safe
570 def call_impl(self, cppthis, args_w):
571 assert lltype.typeOf(cppthis) == capi.C_OBJECT
572
573 # The following code tries out each of the functions in order. If
574 # argument conversion fails (or simply if the number of arguments do
575 # not match), that will lead to an exception, The JIT will snip out
576 # those (always) failing paths, but only if they have no side-effects.
577 # A second loop gathers all exceptions in the case all methods fail
578 # (the exception gathering would otherwise be a side-effect as far as
579 # the JIT is concerned).
580 #
581 # TODO: figure out what happens if a callback into from the C++ call
582 # raises a Python exception.
583 jit.promote(self)
584 for i in range(len(self.functions)):
585 cppyyfunc = self.functions[i]
586 try:
587 w_result = cppyyfunc.call(cppthis, args_w, self.flags & OVERLOAD_FLAGS_USE_FFI)
588 if self.flags & OVERLOAD_FLAGS_CREATES:
589 if isinstance(w_result, W_CPPInstance):
590 cppinstance = self.space.interp_w(W_CPPInstance, w_result)
591 cppinstance.fset_python_owns(self.space, self.space.w_True)
592 return w_result
593 except Exception:
594 pass
595
596 # only get here if all overloads failed ...
597 errmsg = 'none of the %d overloaded methods succeeded. Full details:' % len(self.functions)
598 if hasattr(self.space, "fake"): # FakeSpace fails errorstr (see below)
599 raise OperationError(self.space.w_TypeError, self.space.newtext(errmsg))
600 w_exc_type = None
601 all_same_type = True
602 for i in range(len(self.functions)):
603 cppyyfunc = self.functions[i]
604 try:
605 # no need to set ownership on the return value, as none of the methods execute
606 return cppyyfunc.call(cppthis, args_w, self.flags & OVERLOAD_FLAGS_USE_FFI)
607 except OperationError as e:
608 # special case if there's just one function, to prevent clogging the error message
609 if len(self.functions) == 1:
610 raise
611 if w_exc_type is None:
612 w_exc_type = e.w_type
613 elif all_same_type and not e.match(self.space, w_exc_type):
614 all_same_type = False
615 errmsg += '\n '+cppyyfunc.prototype()+' =>\n'
616 errmsg += ' '+e.errorstr(self.space)
617 except Exception as e:
618 # can not special case this for non-overloaded functions as we anyway need an
619 # OperationError error down from here
620 errmsg += '\n '+cppyyfunc.prototype()+' =>\n'
621 errmsg += ' Exception: '+str(e)
622
623 if all_same_type and w_exc_type is not None:
624 raise OperationError(w_exc_type, self.space.newtext(errmsg))
625 else:
626 raise OperationError(self.space.w_TypeError, self.space.newtext(errmsg))
627
628 def prototype(self):
629 sig = self.functions[0].prototype()
630 for i in range(1, len(self.functions)):
631 sig += '\n'+self.functions[i].prototype()
632 return self.space.newtext(sig)
633
634 @unwrap_spec(signature='text')
635 def mp_overload(self, signature):
636 sig = '(%s)' % signature
637 for f in self.functions:
638 if f.signature(False) == sig:
639 if isinstance(self, W_CPPStaticOverload):
640 return W_CPPStaticOverload(self.space, self.scope, [f])
641 return W_CPPOverload(self.space, self.scope, [f])
642 raise oefmt(self.space.w_LookupError, "signature '%s' not found", signature)
643
644 # set life management of result from the call
645 def fget_creates(self, space):
646 return space.newbool(bool(self.flags & OVERLOAD_FLAGS_CREATES))
647
648 @unwrap_spec(value=bool)
649 def fset_creates(self, space, value):
650 if space.is_true(value):
651 self.flags |= OVERLOAD_FLAGS_CREATES
652 else:
653 self.flags &= ~OVERLOAD_FLAGS_CREATES
654
655 # set ownership policy of arguments (not yet implemented)
656 def fget_mempolicy(self, space):
657 return space.newint(0)
658
659 @unwrap_spec(value=int)
660 def fset_mempolicy(self, space, value):
661 pass
662
663 # set to release the gil during call (not yet implemented)
664 def fget_release_gil(self, space):
665 return space.newbool(True)
666
667 @unwrap_spec(value=bool)
668 def fset_release_gil(self, space, value):
669 pass
670
671 # allow user to determine ffi use rules per overload
672 def fget_useffi(self, space):
673 return space.newbool(bool(self.flags & OVERLOAD_FLAGS_USE_FFI))
674
675 @unwrap_spec(value=bool)
676 def fset_useffi(self, space, value):
677 if space.is_true(value):
678 self.flags |= OVERLOAD_FLAGS_USE_FFI
679 else:
680 self.flags &= ~OVERLOAD_FLAGS_USE_FFI
681
682 def fget_doc(self, space):
683 return self.prototype()
684
685 def getname(self, space):
686 # for the benefit of Method/instancemethod
687 return capi.c_method_name(space, self.functions[0].cppmethod)
688
689 def __repr__(self):
690 return "W_CPPOverload(%s)" % [f.prototype() for f in self.functions]
691
692 W_CPPOverload.typedef = TypeDef(
693 'CPPOverload',
694 __get__ = interp2app(W_CPPOverload.descr_get),
695 __call__ = interp2app(W_CPPOverload.call_args),
696 __creates__ = GetSetProperty(W_CPPOverload.fget_creates, W_CPPOverload.fset_creates),
697 __mempolicy__ = GetSetProperty(W_CPPOverload.fget_mempolicy, W_CPPOverload.fset_mempolicy),
698 __release_gil__ = GetSetProperty(W_CPPOverload.fget_release_gil, W_CPPOverload.fset_release_gil),
699 __useffi__ = GetSetProperty(W_CPPOverload.fget_useffi, W_CPPOverload.fset_useffi),
700 __overload__ = interp2app(W_CPPOverload.mp_overload),
701 __doc__ = GetSetProperty(W_CPPOverload.fget_doc)
702 )
703
704
705 # overload collection of static (class and free) functions; these differ
706 # from methods only in the handling of 'cppthis'
707 class W_CPPStaticOverload(W_CPPOverload):
708 _attrs_ = []
709
710 def descr_get(self, w_obj, w_cls=None):
711 if isinstance(w_obj, W_CPPInstance):
712 # two possibilities: this is a static function called on an
713 # instance and w_this must not be set, or a free function rebound
714 # onto a class and w_this should be set
715 cppinstance = self.space.interp_w(W_CPPInstance, w_obj)
716 if cppinstance.clsdecl.handle != self.scope.handle:
717 return MethodWithProps(self.space, self, w_obj) # bound
718 return self # unbound
719
720 @unwrap_spec(args_w='args_w')
721 def call_args(self, args_w):
722 jit.promote(self)
723 return self.call_impl(capi.C_NULL_OBJECT, args_w)
724
725 def __repr__(self):
726 return "W_CPPStaticOverload(%s)" % [f.prototype() for f in self.functions]
727
728 W_CPPStaticOverload.typedef = TypeDef(
729 'CPPStaticOverload',
730 __get__ = interp2app(W_CPPStaticOverload.descr_get),
731 __call__ = interp2app(W_CPPStaticOverload.call_args),
732 __creates__ = GetSetProperty(W_CPPStaticOverload.fget_creates, W_CPPStaticOverload.fset_creates),
733 __mempolicy__ = GetSetProperty(W_CPPStaticOverload.fget_mempolicy, W_CPPStaticOverload.fset_mempolicy),
734 __release_gil__ = GetSetProperty(W_CPPStaticOverload.fget_release_gil, W_CPPStaticOverload.fset_release_gil),
735 __useffi__ = GetSetProperty(W_CPPStaticOverload.fget_useffi, W_CPPStaticOverload.fset_useffi),
736 __overload__ = interp2app(W_CPPStaticOverload.mp_overload),
737 __doc__ = GetSetProperty(W_CPPStaticOverload.fget_doc)
738 )
739
740
741 class W_CPPConstructorOverload(W_CPPOverload):
742 _attrs_ = []
743
744 def __init__(self, space, decl_scope, funcs, flags = OVERLOAD_FLAGS_USE_FFI):
745 W_CPPOverload.__init__(self, space, decl_scope, funcs, flags)
746 self.flags &= ~OVERLOAD_FLAGS_USE_FFI
747
748 @unwrap_spec(args_w='args_w')
749 def call_args(self, args_w):
750 jit.promote(self)
751 cppinstance = self.space.interp_w(W_CPPInstance, args_w[0])
752 w_result = self.call_impl(rffi.cast(capi.C_OBJECT, self.scope.handle), args_w[1:])
753 newthis = rffi.cast(capi.C_OBJECT, self.space.uint_w(w_result))
754 if cppinstance is not None:
755 cppinstance._rawobject = newthis
756 memory_regulator.register(cppinstance)
757
758 def __repr__(self):
759 return "W_CPPConstructorOverload(%s)" % [f.prototype() for f in self.functions]
760
761 W_CPPConstructorOverload.typedef = TypeDef(
762 'CPPConstructorOverload',
763 __get__ = interp2app(W_CPPConstructorOverload.descr_get),
764 __call__ = interp2app(W_CPPConstructorOverload.call_args),
765 __overload__ = interp2app(W_CPPConstructorOverload.mp_overload),
766 __doc__ = GetSetProperty(W_CPPConstructorOverload.fget_doc)
767 )
768
769 class W_CPPAbstractCtorOverload(W_CPPOverload):
770 _attrs_ = []
771
772 @unwrap_spec(args_w='args_w')
773 def call_args(self, args_w):
774 raise oefmt(self.space.w_TypeError,
775 "cannot instantiate abstract class '%s'", self.scope.name)
776
777 def __repr__(self):
778 return "W_CPPAbstractCtorOverload"
779
780 W_CPPAbstractCtorOverload.typedef = TypeDef(
781 'CPPAbstractCtorOverload',
782 __get__ = interp2app(W_CPPAbstractCtorOverload.descr_get),
783 __call__ = interp2app(W_CPPAbstractCtorOverload.call_args),
784 )
785
786
787 class TemplateOverloadMixin(object):
788 """Mixin to instantiate templated methods/functions."""
789
790 _attrs_ = ['tmpl_args_w']
791 _mixin_ = True
792
793 def construct_template_args(self, w_tpArgs, args_w = None):
794 space = self.space
795 tmpl_args = ''
796 for i in range(space.len_w(w_tpArgs)):
797 w_tp = space.getitem(w_tpArgs, space.newint(i))
798 if space.isinstance_w(w_tp, space.w_text):
799 s = space.text_w(w_tp) # string describing type
800 elif space.isinstance_w(w_tp, space.w_type):
801 try:
802 # cppyy bound types
803 s = space.text_w(space.getattr(w_tp, space.newtext('__cpp_name__')))
804 if args_w:
805 # try to specialize the type match for the given object
806 cppinstance = self.space.interp_w(W_CPPInstance, args_w[i])
807 if cppinstance.rt_flags & INSTANCE_FLAGS_IS_RVALUE:
808 sugar = "&&"
809 elif cppinstance.flags & INSTANCE_FLAGS_IS_REF:
810 sugar = "*"
811 else:
812 sugar = "&"
813 s += sugar
814 except OperationError:
815 # generic python types
816 s = space.text_w(space.getattr(w_tp, space.newtext('__name__')))
817 else:
818 # builtin types etc.
819 s = space.text_w(space.str(w_tp))
820 # map python types -> C++ types
821 if s == 'str': s = 'std::string'
822 if i != 0: tmpl_args += ', '
823 tmpl_args += s
824 return tmpl_args
825
826 def instantiate_method_template(self, name, proto = ''):
827 # instantiate/find new callable function
828 space = self.space
829 cppmeth = capi.c_get_method_template(space, self.scope, name, proto)
830 if not cppmeth:
831 raise oefmt(self.space.w_AttributeError,
832 "failed to instantiate %s::%s for arguments '%s'",
833 self.scope.name, name, proto)
834
835 funcs = []
836 ftype = self.scope._make_cppfunction(name, cppmeth, funcs)
837 if ftype & FUNCTION_IS_STATIC:
838 cppol = W_CPPStaticOverload(space, self.scope, funcs[:], self.flags)
839 else:
840 cppol = W_CPPOverload(space, self.scope, funcs[:], self.flags)
841 return cppol
842
843 def _call_method(self, method, args_w):
844 if not self.space.is_w(self.w_this, self.space.w_None):
845 return self.space.call_obj_args(method, self.w_this, Arguments(self.space, args_w))
846 return self.space.call_args(method, Arguments(self.space, args_w))
847
848 def template_call(self, name, tmpl_args, args_w):
849 method = None
850
851 fullname = name
852 if tmpl_args is not None:
853 fullname = fullname+'<'+tmpl_args+'>'
854
855 try:
856 # existing cached instantiations
857 method = self.master.overloads[fullname]
858 return self._call_method(method, args_w)
859 except Exception:
860 pass
861
862 # if not known, or failed, try instantiation
863 w_types = self.space.newtuple([self.space.type(obj_w) for obj_w in args_w])
864 proto = self.construct_template_args(w_types, args_w)
865 method = self.instantiate_method_template(fullname, proto) # may raise
866
867 # cache result as the full templated name only
868 if fullname[-1] != '>':
869 fullname = capi.c_method_full_name(self.space, method.functions[0].cppmethod)
870 try:
871 existing = self.master.overloads[fullname]
872 allf = existing.functions + method.functions
873 if isinstance(existing, W_CPPStaticOverload):
874 cppol = W_CPPStaticOverload(self.space, self.scope, allf, self.flags)
875 else:
876 cppol = W_CPPOverload(self.space, self.scope, allf, self.flags)
877 self.master.overloads[fullname] = cppol
878 except KeyError:
879 self.master.overloads[fullname] = method
880
881 # perform actual call (which may still fail)
882 return self._call_method(method, args_w)
883
884 def getitem_impl(self, name, w_args):
885 space = self.space
886
887 if not space.isinstance_w(w_args, space.w_tuple):
888 w_args = space.newtuple([w_args])
889
890 tmpl_args = self.construct_template_args(w_args)
891 return self.clone(tmpl_args) # defer instantiation until arguments are known
892
893
894 class W_CPPTemplateOverload(W_CPPOverload, TemplateOverloadMixin):
895 """App-level dispatcher to allow both lookup/instantiation of templated methods and
896 dispatch among overloads between templated and non-templated method."""
897
898 _attrs_ = ['name', 'tmpl_args', 'overloads', 'master', 'w_this']
899 _immutable_fields_ = ['name', 'tmpl_args']
900
901 def __init__(self, space, name, tmpl_args, decl_scope, functions, flags = OVERLOAD_FLAGS_USE_FFI):
902 W_CPPOverload.__init__(self, space, decl_scope, functions, flags)
903 self.name = name
904 self.tmpl_args = tmpl_args
905 self.overloads = {}
906 self.master = self
907 self.w_this = space.w_None
908
909 def clone(self, tmpl_args):
910 other = W_CPPTemplateOverload(self.space, self.name, tmpl_args, self.scope, self.functions, self.flags)
911 other.overloads = self.overloads
912 other.master = self.master
913 other.w_this = self.w_this
914 return other
915
916 def descr_get(self, w_cppinstance, w_cls=None):
917 # TODO: don't return copy, but bind in an external object (like W_CPPOverload)
918 if self.space.is_w(w_cppinstance, self.space.w_None):
919 return self # unbound, so no new instance needed
920 cppol = W_CPPTemplateOverload(self.space, self.name, self.tmpl_args, self.scope, self.functions, self.flags)
921 cppol.w_this = w_cppinstance
922 cppol.master = self.master
923 return cppol # bound
924
925 @unwrap_spec(args_w='args_w')
926 def call_args(self, args_w):
927 # direct call: either pick non-templated overload or attempt to deduce
928 # the template instantiation from the argument types
929 try:
930 return W_CPPOverload.call_args(self, [self.w_this]+args_w)
931 except Exception:
932 pass
933 return self.template_call(self.name, self.tmpl_args, args_w)
934
935 def getitem(self, w_arg):
936 return self.getitem_impl(self.name, w_arg)
937
938 def getname(self, space):
939 return self.name
940
941 def __repr__(self):
942 return "W_CPPTemplateOverload(%s)" % [f.prototype() for f in self.functions]
943
944 W_CPPTemplateOverload.typedef = TypeDef(
945 'CPPTemplateOverload',
946 __get__ = interp2app(W_CPPTemplateOverload.descr_get),
947 __getitem__ = interp2app(W_CPPTemplateOverload.getitem),
948 __call__ = interp2app(W_CPPTemplateOverload.call_args),
949 __creates__ = GetSetProperty(W_CPPTemplateOverload.fget_creates, W_CPPTemplateOverload.fset_creates),
950 __mempolicy__ = GetSetProperty(W_CPPTemplateOverload.fget_mempolicy, W_CPPTemplateOverload.fset_mempolicy),
951 __release_gil__ = GetSetProperty(W_CPPTemplateOverload.fget_release_gil, W_CPPTemplateOverload.fset_release_gil),
952 __useffi__ = GetSetProperty(W_CPPTemplateOverload.fget_useffi, W_CPPTemplateOverload.fset_useffi),
953 __doc__ = GetSetProperty(W_CPPTemplateOverload.fget_doc)
954 )
955
956 class W_CPPTemplateStaticOverload(W_CPPStaticOverload, TemplateOverloadMixin):
957 """Dispatcher to allow both lookup/instantiation of templated methods and
958 select among templated and non-templated method overloads."""
959
960 _attrs_ = ['name', 'tmpl_args', 'overloads', 'master', 'w_this']
961 _immutable_fields_ = ['name', 'tmpl_args']
962
963 def __init__(self, space, name, tmpl_args, decl_scope, funcs, flags = OVERLOAD_FLAGS_USE_FFI):
964 W_CPPStaticOverload.__init__(self, space, decl_scope, funcs, flags)
965 self.name = name
966 self.tmpl_args = tmpl_args
967 self.overloads = {}
968 self.master = self
969 self.w_this = space.w_None
970
971 def clone(self, tmpl_args):
972 other = W_CPPTemplateStaticOverload(self.space, self.name,
973 tmpl_args, self.scope, self.functions, self.flags)
974 other.overloads = self.overloads
975 other.master = self.master
976 other.w_this = self.w_this
977 return other
978
979 def descr_get(self, w_cppinstance, w_cls=None):
980 # TODO: don't return copy, but bind in an external object (like W_CPPOverload)
981 if isinstance(w_cppinstance, W_CPPInstance):
982 cppinstance = self.space.interp_w(W_CPPInstance, w_cppinstance)
983 if cppinstance.clsdecl.handle != self.scope.handle:
984 cppol = W_CPPTemplateStaticOverload(self.space, self.name,
985 self.tmpl_args, self.scope, self.functions, self.flags)
986 cppol.w_this = w_cppinstance
987 cppol.master = self.master
988 return cppol # bound
989 return self # unbound
990
991 @unwrap_spec(args_w='args_w')
992 def call_args(self, args_w):
993 # direct call: either pick non-templated overload or attempt to deduce
994 # the template instantiation from the argument types
995 try:
996 return W_CPPStaticOverload.call_args(self, [self.w_this]+args_w)
997 except Exception:
998 pass
999 return self.template_call(self.name, self.tmpl_args, args_w)
1000
1001 def getitem(self, w_arg):
1002 return self.getitem_impl(self.name, w_arg)
1003
1004 def getname(self, space):
1005 return self.name
1006
1007 def __repr__(self):
1008 return "W_CPPTemplateStaticOverload(%s)" % [f.prototype() for f in self.functions]
1009
1010 W_CPPTemplateStaticOverload.typedef = TypeDef(
1011 'CPPTemplateStaticOverload',
1012 __get__ = interp2app(W_CPPTemplateStaticOverload.descr_get),
1013 __getitem__ = interp2app(W_CPPTemplateStaticOverload.getitem),
1014 __call__ = interp2app(W_CPPTemplateStaticOverload.call_args),
1015 __creates__ = GetSetProperty(W_CPPTemplateStaticOverload.fget_creates,
1016 W_CPPTemplateStaticOverload.fset_creates),
1017 __mempolicy__ = GetSetProperty(W_CPPTemplateStaticOverload.fget_mempolicy,
1018 W_CPPTemplateStaticOverload.fset_mempolicy),
1019 __release_gil__ = GetSetProperty(W_CPPTemplateStaticOverload.fget_release_gil,
1020 W_CPPTemplateStaticOverload.fset_release_gil),
1021 __useffi__ = GetSetProperty(W_CPPTemplateStaticOverload.fget_useffi,
1022 W_CPPTemplateStaticOverload.fset_useffi),
1023 __doc__ = GetSetProperty(W_CPPTemplateStaticOverload.fget_doc)
1024 )
1025
1026
1027 #-----
1028 # Classes for data members:
1029 #
1030 # W_CPPDataMember: instance data members
1031 # W_CPPConstDataMember: specialization for const data members
1032 # W_CPPStaticData: class-level and global/static data
1033 # W_CPPConstStaticData: specialization for const global/static data
1034 #
1035 # Data is represented by an offset which is either a global pointer (static data)
1036 # or an offset from the start of an instance (data members). The "const"
1037 # specializations raise when attempting to set their value.
1038
1039 class W_CPPDataMember(W_Root):
1040 _attrs_ = ['space', 'scope', 'converter', 'offset']
1041 _immutable_fields = ['scope', 'converter', 'offset']
1042
1043 def __init__(self, space, decl_scope, type_name, dimensions, offset):
1044 self.space = space
1045 self.scope = decl_scope
1046 self.converter = converter.get_converter(self.space, type_name, dimensions)
1047 self.offset = rffi.cast(rffi.INTPTR_T, offset)
1048
1049 def _get_offset(self, cppinstance):
1050 if cppinstance:
1051 assert isinstance(cppinstance.clsdecl, W_CPPClassDecl)
1052 assert lltype.typeOf(cppinstance.clsdecl.handle) == lltype.typeOf(self.scope.handle)
1053 offset = self.offset + cppinstance.clsdecl.get_base_offset(cppinstance, self.scope)
1054 else:
1055 offset = self.offset
1056 return offset
1057
1058 def get(self, w_cppinstance, w_pycppclass):
1059 cppinstance = self.space.interp_w(W_CPPInstance, w_cppinstance, can_be_None=True)
1060 if not cppinstance:
1061 raise oefmt(self.space.w_AttributeError,
1062 "attribute access requires an instance")
1063 offset = self._get_offset(cppinstance)
1064 return self.converter.from_memory(self.space, w_cppinstance, offset)
1065
1066 def set(self, w_cppinstance, w_value):
1067 cppinstance = self.space.interp_w(W_CPPInstance, w_cppinstance, can_be_None=True)
1068 if not cppinstance:
1069 raise oefmt(self.space.w_AttributeError,
1070 "attribute access requires an instance")
1071 offset = self._get_offset(cppinstance)
1072 self.converter.to_memory(self.space, w_cppinstance, w_value, offset)
1073 return self.space.w_None
1074
1075 W_CPPDataMember.typedef = TypeDef(
1076 'CPPDataMember',
1077 __get__ = interp2app(W_CPPDataMember.get),
1078 __set__ = interp2app(W_CPPDataMember.set),
1079 )
1080 W_CPPDataMember.typedef.acceptable_as_base_class = False
1081
1082
1083 class W_CPPConstDataMember(W_CPPDataMember):
1084 def set(self, w_cppinstance, w_value):
1085 raise oefmt(self.space.w_TypeError, "assignment to const data not allowed")
1086
1087 W_CPPConstDataMember.typedef = TypeDef(
1088 'CPPConstDataMember',
1089 __get__ = interp2app(W_CPPDataMember.get),
1090 __set__ = interp2app(W_CPPConstDataMember.set),
1091 )
1092 W_CPPConstDataMember.typedef.acceptable_as_base_class = False
1093
1094
1095 class W_CPPStaticData(W_CPPDataMember):
1096 @jit.elidable_promote()
1097 def _get_offset(self, cppinstance):
1098 return self.offset
1099
1100 def get(self, w_cppinstance, w_pycppclass):
1101 return self.converter.from_memory(self.space, self.space.w_None, self.offset)
1102
1103 def set(self, w_cppinstance, w_value):
1104 self.converter.to_memory(self.space, self.space.w_None, w_value, self.offset)
1105 return self.space.w_None
1106
1107 W_CPPStaticData.typedef = TypeDef(
1108 'CPPStaticData',
1109 __get__ = interp2app(W_CPPStaticData.get),
1110 __set__ = interp2app(W_CPPStaticData.set),
1111 )
1112 W_CPPStaticData.typedef.acceptable_as_base_class = False
1113
1114
1115 class W_CPPConstStaticData(W_CPPStaticData):
1116 def set(self, w_cppinstance, w_value):
1117 raise oefmt(self.space.w_TypeError, "assignment to const data not allowed")
1118
1119 W_CPPConstStaticData.typedef = TypeDef(
1120 'CPPConstStaticData',
1121 __get__ = interp2app(W_CPPConstStaticData.get),
1122 __set__ = interp2app(W_CPPConstStaticData.set),
1123 )
1124 W_CPPConstStaticData.typedef.acceptable_as_base_class = False
1125
1126
1127 def is_static_data(space, w_obj):
1128 try:
1129 space.interp_w(W_CPPStaticData, w_obj)
1130 return space.w_True
1131 except Exception:
1132 return space.w_False
1133
1134 #-----
1135 # Classes for data members:
1136 #
1137 # W_CPPScopeDecl : scope base class
1138 # W_CPPNamespaceDecl : namespace scope
1139 # W_CPPClassDecl : class scope
1140 #
1141 # Namespaces and classes mainly differ in lookups of methods. Whereas classes
1142 # can grown templated methods, namespaces are wide open to any additions. Such
1143 # lookups are triggered from get_scoped_pycppitem (in pythonify.py). Further
1144 # specialization is done on the type of data/methods that each can have.
1145
1146 class W_CPPScopeDecl(W_Root):
1147 _attrs_ = ['space', 'handle', 'flags', 'name', 'overloads', 'datamembers']
1148 _immutable_fields_ = ['handle', 'name']
1149
1150 def __init__(self, space, opaque_handle, final_scoped_name):
1151 self.space = space
1152 assert lltype.typeOf(opaque_handle) == capi.C_SCOPE
1153 self.handle = opaque_handle
1154 self.flags = 0
1155 self.name = final_scoped_name
1156 self.overloads = {}
1157 # Do not call "self._build_overloadss()" here, so that a distinction can
1158 # be made between testing for existence (i.e. existence in the cache
1159 # of classes) and actual use. Point being that a class can use itself,
1160 # e.g. as a return type or an argument to one of its methods.
1161
1162 self.datamembers = {}
1163 # Idem as for self.overloads: a type could hold itself by pointer.
1164
1165 def get_method_names(self):
1166 return self.space.newlist([self.space.newtext(name) for name in self.overloads])
1167
1168 @unwrap_spec(name='text')
1169 def get_overload(self, name):
1170 try:
1171 return self.overloads[name]
1172 except KeyError:
1173 pass
1174 new_ol = self.find_overload(name)
1175 self.overloads[name] = new_ol
1176 return new_ol
1177
1178 def get_datamember_names(self):
1179 return self.space.newlist([self.space.newtext(name) for name in self.datamembers])
1180
1181 @unwrap_spec(name='text')
1182 def get_datamember(self, name):
1183 try:
1184 return self.datamembers[name]
1185 except KeyError:
1186 pass
1187 new_dm = self.find_datamember(name)
1188 self.datamembers[name] = new_dm
1189 return new_dm
1190
1191 @unwrap_spec(name='text')
1192 def has_enum(self, name):
1193 if capi.c_is_enum(self.space, self.name+'::'+name):
1194 return self.space.w_True
1195 return self.space.w_False
1196
1197 def _encode_dm_dimensions(self, idata):
1198 # encode dimensions (TODO: this is ugly, but here's where the info is)
1199 dims = []
1200 sz = capi.c_get_dimension_size(self.space, self, idata, len(dims))
1201 while 0 < sz:
1202 dims.append(str(sz))
1203 sz = capi.c_get_dimension_size(self.space, self, idata, len(dims))
1204 return ':'.join(dims)
1205
1206 @unwrap_spec(name='text', signature='text')
1207 def scope__dispatch__(self, name, signature):
1208 overload = self.get_overload(name)
1209 sig = '(%s)' % signature
1210 for f in overload.functions:
1211 if f.signature(False) == sig:
1212 if isinstance(overload, W_CPPStaticOverload):
1213 return W_CPPStaticOverload(self.space, self, [f])
1214 return W_CPPOverload(self.space, self, [f])
1215 raise oefmt(self.space.w_LookupError, "no overload matches signature")
1216
1217 def __eq__(self, other):
1218 return self.handle == other.handle
1219
1220 def __ne__(self, other):
1221 return self.handle != other.handle
1222
1223
1224 # Namespaces and classes are separate as namespaces are (more) extensible
1225 # with info from multiple dictionaries and do not need to bother with meta
1226 # classes for inheritance. Both are python classes, though, and further
1227 # refactoring may be in order at some point.
1228 class W_CPPNamespaceDecl(W_CPPScopeDecl):
1229 _attrs_ = ['space', 'handle', 'name', 'overloads', 'datamembers']
1230 _immutable_fields_ = ['handle', 'name']
1231
1232 def _make_cppfunction(self, pyname, cppmeth, funcs):
1233 num_args = capi.c_method_num_args(self.space, cppmeth)
1234 args_required = capi.c_method_req_args(self.space, cppmeth)
1235 arg_defs = []
1236 for i in range(num_args):
1237 arg_type = capi.c_method_arg_type(self.space, cppmeth, i)
1238 arg_dflt = capi.c_method_arg_default(self.space, cppmeth, i)
1239 arg_defs.append((arg_type, arg_dflt))
1240 funcs.append(CPPMethod(self.space, self, cppmeth, arg_defs, args_required))
1241 return FUNCTION_IS_GLOBAL
1242
1243 def _make_datamember(self, dm_name, dm_idx):
1244 type_name = capi.c_datamember_type(self.space, self, dm_idx)
1245 if capi.c_is_enum_data(self.space, self, dm_idx):
1246 type_name = capi.c_resolve_enum(self.space, type_name)
1247 offset = capi.c_datamember_offset(self.space, self, dm_idx)
1248 if offset == rffi.cast(rffi.INTPTR_T, -1):
1249 raise self.missing_attribute_error(dm_name)
1250 dims = self._encode_dm_dimensions(dm_idx)
1251 if capi.c_is_const_data(self.space, self, dm_idx):
1252 datamember = W_CPPConstStaticData(self.space, self, type_name, dims, offset)
1253 else:
1254 datamember = W_CPPStaticData(self.space, self, type_name, dims, offset)
1255 self.datamembers[dm_name] = datamember
1256 return datamember
1257
1258 def find_overload(self, meth_name):
1259 indices = capi.c_method_indices_from_name(self.space, self, meth_name)
1260 if indices:
1261 cppfunctions, ftype = [], 0
1262 templated = False
1263 for idx in indices:
1264 cppmeth = capi.c_get_method(self.space, self, idx)
1265 ftype |= self._make_cppfunction(meth_name, cppmeth, cppfunctions)
1266 if capi.c_method_is_template(self.space, self, idx):
1267 templated = True
1268 if templated:
1269 return W_CPPTemplateStaticOverload(self.space, meth_name, None, self, cppfunctions[:])
1270 return W_CPPStaticOverload(self.space, self, cppfunctions[:])
1271 elif capi.c_exists_method_template(self.space, self, meth_name):
1272 return W_CPPTemplateStaticOverload(self.space, meth_name, None, self, [])
1273 raise self.missing_attribute_error(meth_name)
1274
1275 def find_datamember(self, dm_name):
1276 dm_idx = capi.c_datamember_index(self.space, self, dm_name)
1277 if dm_idx < 0:
1278 raise self.missing_attribute_error(dm_name)
1279 datamember = self._make_datamember(dm_name, dm_idx)
1280 return datamember
1281
1282 def is_namespace(self):
1283 return self.space.w_True
1284
1285 def ns__dir__(self):
1286 alldir = capi.c_get_all_cpp_names(self.space, self)
1287 w_alldir = self.space.newlist([])
1288 for name in alldir:
1289 w_alldir.append(self.space.newtext(name))
1290 return w_alldir
1291
1292 def missing_attribute_error(self, name):
1293 return oefmt(self.space.w_AttributeError,
1294 "namespace '%s' has no attribute %s", self.name, name)
1295
1296
1297 W_CPPNamespaceDecl.typedef = TypeDef(
1298 'CPPNamespaceDecl',
1299 get_method_names = interp2app(W_CPPNamespaceDecl.get_method_names),
1300 get_overload = interp2app(W_CPPNamespaceDecl.get_overload),
1301 get_datamember_names = interp2app(W_CPPNamespaceDecl.get_datamember_names),
1302 get_datamember = interp2app(W_CPPNamespaceDecl.get_datamember),
1303 is_namespace = interp2app(W_CPPNamespaceDecl.is_namespace),
1304 has_enum = interp2app(W_CPPNamespaceDecl.has_enum),
1305 __cpp_name__ = interp_attrproperty('name', W_CPPNamespaceDecl, wrapfn="newtext"),
1306 __dispatch__ = interp2app(W_CPPNamespaceDecl.scope__dispatch__),
1307 __dir__ = interp2app(W_CPPNamespaceDecl.ns__dir__),
1308 )
1309 W_CPPNamespaceDecl.typedef.acceptable_as_base_class = False
1310
1311
1312 class W_CPPClassDecl(W_CPPScopeDecl):
1313 _attrs_ = ['space', 'handle', 'name', 'overloads', 'datamembers', 'cppobjects']
1314 _immutable_fields_ = ['handle', 'name', 'overloads[*]', 'datamembers[*]']
1315
1316 def __init__(self, space, opaque_handle, final_scoped_name):
1317 W_CPPScopeDecl.__init__(self, space, opaque_handle, final_scoped_name)
1318 self.cppobjects = rweakref.RWeakValueDictionary(int, W_CPPInstance)
1319
1320 def _build_overloads(self):
1321 assert len(self.overloads) == 0
1322 methods_tmp = {}; ftype_tmp = {}
1323
1324 # add all ordinary methods (incl. pre-instantiated templates)
1325 for idx in range(capi.c_num_methods(self.space, self)):
1326 cppmeth = capi.c_get_method(self.space, self, idx)
1327 if capi.c_is_constructor(self.space, cppmeth):
1328 pyname = '__init__'
1329 else:
1330 pyname = helper.map_operator_name(self.space,
1331 capi.c_method_name(self.space, cppmeth),
1332 capi.c_method_num_args(self.space, cppmeth),
1333 capi.c_method_result_type(self.space, cppmeth))
1334 try:
1335 methods = methods_tmp[pyname]
1336 except KeyError:
1337 methods_tmp[pyname] = []; ftype_tmp[pyname] = 0
1338 methods = methods_tmp[pyname]
1339 ftype_tmp[pyname] |= self._make_cppfunction(pyname, cppmeth, methods)
1340 if capi.c_method_is_template(self.space, self, idx):
1341 ftype_tmp[pyname] |= FUNCTION_IS_TEMPLATE
1342
1343 # the following covers the case where the only kind of operator[](idx)
1344 # returns are the ones that produce non-const references; these can be
1345 # used for __getitem__ just as much as for __setitem__, though
1346 if not "__getitem__" in methods_tmp:
1347 try:
1348 si_methods = methods_tmp["__setitem__"]
1349 gi_methods = []; ftype = 0
1350 for m in si_methods:
1351 ftype |= self._make_cppfunction("__getitem__", m.cppmethod, gi_methods)
1352 methods_tmp["__getitem__"] = gi_methods; ftype_tmp["__getitem__"] = ftype
1353 except KeyError:
1354 pass # just means there's no __setitem__ either
1355
1356 # create the overloads from the method sets
1357 for pyname, methods in methods_tmp.iteritems():
1358 ftype = ftype_tmp[pyname]
1359 CPPMethodSort(methods).sort()
1360 if ftype & FUNCTION_IS_CONSTRUCTOR:
1361 if capi.c_is_abstract(self.space, self):
1362 overload = W_CPPAbstractCtorOverload(self.space, self, methods[:])
1363 else:
1364 overload = W_CPPConstructorOverload(self.space, self, methods[:])
1365 elif ftype & FUNCTION_IS_STATIC:
1366 if ftype & FUNCTION_IS_TEMPLATE:
1367 cppname = capi.c_method_name(self.space, methods[0].cppmethod)
1368 overload = W_CPPTemplateStaticOverload(self.space, cppname, None, self, methods[:])
1369 else:
1370 overload = W_CPPStaticOverload(self.space, self, methods[:])
1371 elif ftype & FUNCTION_IS_TEMPLATE:
1372 cppname = capi.c_method_name(self.space, methods[0].cppmethod)
1373 overload = W_CPPTemplateOverload(self.space, cppname, None, self, methods[:])
1374 else:
1375 overload = W_CPPOverload(self.space, self, methods[:])
1376 self.overloads[pyname] = overload
1377
1378 # add placeholders for all non-instantiated templated methods
1379 for idx in range(capi.c_get_num_templated_methods(self.space, self)):
1380 cppname = capi.c_get_templated_method_name(self.space, self, idx)
1381 self.overloads[cppname] = W_CPPTemplateOverload(self.space, cppname, None, self, [])
1382
1383 def _make_cppfunction(self, pyname, cppmeth, funcs):
1384 num_args = capi.c_method_num_args(self.space, cppmeth)
1385 args_required = capi.c_method_req_args(self.space, cppmeth)
1386 arg_defs = []
1387 for i in range(num_args):
1388 arg_type = capi.c_method_arg_type(self.space, cppmeth, i)
1389 arg_dflt = capi.c_method_arg_default(self.space, cppmeth, i)
1390 arg_defs.append((arg_type, arg_dflt))
1391 ftype = 0
1392 if pyname == "__setitem__":
1393 cppfunction = CPPSetItem(self.space, self, cppmeth, arg_defs, args_required)
1394 ftype = FUNCTION_IS_SETITEM
1395 else:
1396 cppfunction = CPPMethod(self.space, self, cppmeth, arg_defs, args_required)
1397 if capi.c_is_constructor(self.space, cppmeth):
1398 ftype = FUNCTION_IS_CONSTRUCTOR
1399 elif capi.c_is_staticmethod(self.space, cppmeth):
1400 ftype = FUNCTION_IS_STATIC
1401 else:
1402 ftype = FUNCTION_IS_METHOD
1403 funcs.append(cppfunction)
1404 return ftype
1405
1406 def _find_datamembers(self):
1407 num_datamembers = capi.c_num_datamembers(self.space, self)
1408 for i in range(num_datamembers):
1409 if not capi.c_is_publicdata(self.space, self, i):
1410 continue
1411 datamember_name = capi.c_datamember_name(self.space, self, i)
1412 type_name = capi.c_datamember_type(self.space, self, i)
1413 offset = capi.c_datamember_offset(self.space, self, i)
1414 if offset == rffi.cast(rffi.INTPTR_T, -1):
1415 continue # dictionary problem; raises AttributeError on use
1416 is_static = bool(capi.c_is_staticdata(self.space, self, i))
1417 is_const = bool(capi.c_is_const_data(self.space, self, i))
1418 dims = self._encode_dm_dimensions(i)
1419 if is_static and is_const:
1420 datamember = W_CPPConstStaticData(self.space, self, type_name, dims, offset)
1421 elif is_static:
1422 datamember = W_CPPStaticData(self.space, self, type_name, dims, offset)
1423 elif is_const:
1424 datamember = W_CPPConstDataMember(self.space, self, type_name, dims, offset)
1425 else:
1426 datamember = W_CPPDataMember(self.space, self, type_name, dims, offset)
1427 self.datamembers[datamember_name] = datamember
1428
1429 def find_overload(self, meth_name):
1430 raise self.missing_attribute_error(meth_name)
1431
1432 def find_datamember(self, name):
1433 raise self.missing_attribute_error(name)
1434
1435 def get_base_offset(self, cppinstance, calling_scope):
1436 assert isinstance(cppinstance.clsdecl, W_CPPClassDecl)
1437 assert self == cppinstance.clsdecl
1438 return 0
1439
1440 def get_cppthis(self, cppinstance, calling_scope):
1441 assert isinstance(cppinstance.clsdecl, W_CPPClassDecl)
1442 assert self == cppinstance.clsdecl
1443 return cppinstance.get_rawobject()
1444
1445 def is_namespace(self):
1446 return self.space.w_False
1447
1448 def get_base_names(self):
1449 bases = []
1450 num_bases = capi.c_num_bases(self.space, self)
1451 for i in range(num_bases):
1452 base_name = capi.c_base_name(self.space, self, i)
1453 bases.append(self.space.newtext(base_name))
1454 return self.space.newlist(bases)
1455
1456 def missing_attribute_error(self, name):
1457 return oefmt(self.space.w_AttributeError,
1458 "class '%s' has no attribute %s", self.name, name)
1459
1460
1461 W_CPPClassDecl.typedef = TypeDef(
1462 'CPPClassDecl',
1463 get_base_names = interp2app(W_CPPClassDecl.get_base_names),
1464 get_method_names = interp2app(W_CPPClassDecl.get_method_names),
1465 get_overload = interp2app(W_CPPClassDecl.get_overload),
1466 get_datamember_names = interp2app(W_CPPClassDecl.get_datamember_names),
1467 get_datamember = interp2app(W_CPPClassDecl.get_datamember),
1468 is_namespace = interp2app(W_CPPClassDecl.is_namespace),
1469 has_enum = interp2app(W_CPPClassDecl.has_enum),
1470 __cpp_name__ = interp_attrproperty('name', W_CPPClassDecl, wrapfn="newtext"),
1471 __dispatch__ = interp2app(W_CPPClassDecl.scope__dispatch__)
1472 )
1473 W_CPPClassDecl.typedef.acceptable_as_base_class = False
1474
1475
1476 class W_CPPComplexClassDecl(W_CPPClassDecl):
1477 def get_base_offset(self, cppinstance, calling_scope):
1478 assert isinstance(cppinstance.clsdecl, W_CPPComplexClassDecl)
1479 assert self == cppinstance.clsdecl
1480 offset = capi.c_base_offset(self.space,
1481 self, calling_scope, cppinstance.get_rawobject(), 1)
1482 return offset
1483
1484 def get_cppthis(self, cppinstance, calling_scope):
1485 assert isinstance(cppinstance.clsdecl, W_CPPComplexClassDecl)
1486 assert self == cppinstance.clsdecl
1487 offset = self.get_base_offset(cppinstance, calling_scope)
1488 return capi.direct_ptradd(cppinstance.get_rawobject(), offset)
1489
1490 W_CPPComplexClassDecl.typedef = TypeDef(
1491 'CPPComplexClassDecl',
1492 get_base_names = interp2app(W_CPPComplexClassDecl.get_base_names),
1493 get_method_names = interp2app(W_CPPComplexClassDecl.get_method_names),
1494 get_overload = interp2app(W_CPPComplexClassDecl.get_overload),
1495 get_datamember_names = interp2app(W_CPPComplexClassDecl.get_datamember_names),
1496 get_datamember = interp2app(W_CPPComplexClassDecl.get_datamember),
1497 is_namespace = interp2app(W_CPPComplexClassDecl.is_namespace),
1498 __cpp_name__ = interp_attrproperty('name', W_CPPComplexClassDecl, wrapfn="newtext"),
1499 __dispatch__ = interp2app(W_CPPComplexClassDecl.scope__dispatch__)
1500 )
1501 W_CPPComplexClassDecl.typedef.acceptable_as_base_class = False
1502
1503
1504 class W_CPPInstance(W_Root):
1505 _attrs_ = ['space', 'clsdecl', '_rawobject', 'smartdecl', 'deref', 'flags', 'rt_flags',
1506 'finalizer_registered']
1507 _immutable_fields_ = ['clsdecl', 'smartdecl', 'deref', 'flags']
1508
1509 finalizer_registered = False
1510
1511 def __init__(self, space, decl, rawobject, isref, python_owns,
1512 smartdecl=None, deref=rffi.cast(capi.C_METHOD, 0)):
1513 self.space = space
1514 self.clsdecl = decl
1515 assert isinstance(self.clsdecl, W_CPPClassDecl)
1516 assert lltype.typeOf(rawobject) == capi.C_OBJECT
1517 assert not isref or rawobject
1518 self._rawobject = rawobject
1519 assert not isref or not python_owns
1520 self.flags = 0
1521 if isref or (smartdecl and deref):
1522 self.flags |= INSTANCE_FLAGS_IS_REF
1523 self.rt_flags = 0
1524 if python_owns:
1525 self.rt_flags |= INSTANCE_FLAGS_PYTHON_OWNS
1526 self._opt_register_finalizer()
1527 self.smartdecl = smartdecl
1528 self.deref = deref
1529
1530 def _opt_register_finalizer(self):
1531 if not self.finalizer_registered and not hasattr(self.space, "fake"):
1532 assert self.rt_flags & INSTANCE_FLAGS_PYTHON_OWNS
1533 self.register_finalizer(self.space)
1534 self.finalizer_registered = True
1535
1536 def _nullcheck(self):
1537 if not self._rawobject or \
1538 ((self.flags & INSTANCE_FLAGS_IS_REF) and not self.get_rawobject()):
1539 raise oefmt(self.space.w_ReferenceError,
1540 "trying to access a NULL pointer")
1541
1542 # allow user to determine ownership rules on a per object level
1543 def fget_python_owns(self, space):
1544 return space.newbool(bool(self.rt_flags & INSTANCE_FLAGS_PYTHON_OWNS))
1545
1546 @unwrap_spec(value=bool)
1547 def fset_python_owns(self, space, value):
1548 if space.is_true(value):
1549 self.rt_flags |= INSTANCE_FLAGS_PYTHON_OWNS
1550 self._opt_register_finalizer()
1551 else:
1552 self.rt_flags &= ~INSTANCE_FLAGS_PYTHON_OWNS
1553
1554 def get_cppthis(self, calling_scope):
1555 assert isinstance(self.clsdecl, W_CPPClassDecl)
1556 return self.clsdecl.get_cppthis(self, calling_scope)
1557
1558 def get_rawobject(self):
1559 if not (self.flags & INSTANCE_FLAGS_IS_REF):
1560 return self._rawobject
1561 elif self.smartdecl and self.deref:
1562 args = capi.c_allocate_function_args(self.space, 0)
1563 rawptr = capi.c_call_r(self.space, self.deref, self._rawobject, 0, args)
1564 capi.c_deallocate_function_args(self.space, args)
1565 return rffi.cast(capi.C_OBJECT, rawptr)
1566 else:
1567 ptrptr = rffi.cast(rffi.VOIDPP, self._rawobject)
1568 return rffi.cast(capi.C_OBJECT, ptrptr[0])
1569
1570 def _get_as_builtin(self):
1571 try:
1572 return self.space.call_method(self, "_cppyy_as_builtin")
1573 except OperationError as e:
1574 if not (e.match(self.space, self.space.w_TypeError) or
1575 e.match(self.space, self.space.w_AttributeError)):
1576 # TODO: TypeError is raised by call_method if the method is not found;
1577 # it'd be a lot nicer if only AttributeError were raise
1578 raise
1579 return None
1580
1581 def instance__init__(self, args_w):
1582 raise oefmt(self.space.w_TypeError,
1583 "cannot instantiate abstract class '%s'",
1584 self.clsdecl.name)
1585
1586 def instance__eq__(self, w_other):
1587 # special case: if other is None, compare pointer-style
1588 if self.space.is_w(w_other, self.space.w_None):
1589 return self.space.newbool(not self._rawobject)
1590
1591 # get here if no class-specific overloaded operator is available, try to
1592 # find a global overload in gbl, in __gnu_cxx (for iterators), or in the
1593 # scopes of the argument classes (TODO: implement that last option)
1594 try:
1595 # TODO: expecting w_other to be an W_CPPInstance is too limiting
1596 other = self.space.interp_w(W_CPPInstance, w_other)
1597 for name in ["", "__gnu_cxx", "__1"]:
1598 nss = scope_byname(self.space, name)
1599 meth_idx = capi.c_get_global_operator(
1600 self.space, nss, self.clsdecl, other.clsdecl, "operator==")
1601 if meth_idx != rffi.cast(capi.C_INDEX, -1):
1602 funcs = []
1603 cppmeth = capi.c_get_method(self.space, nss, meth_idx)
1604 nss._make_cppfunction("operator==", cppmeth, funcs)
1605 ol = W_CPPStaticOverload(self.space, nss, funcs[:])
1606 # TODO: cache this operator (not done yet, as the above does not
1607 # select all overloads)
1608 return ol.call_args([self, w_other])
1609 except OperationError as e:
1610 if not e.match(self.space, self.space.w_TypeError):
1611 raise
1612
1613 # fallback 1: convert the object to a builtin equivalent
1614 w_as_builtin = self._get_as_builtin()
1615 if w_as_builtin is not None:
1616 return self.space.eq(w_as_builtin, w_other)
1617
1618 # fallback 2: direct pointer comparison (the class comparison is needed since
1619 # the first data member in a struct and the struct have the same address)
1620 other = self.space.interp_w(W_CPPInstance, w_other) # TODO: factor out
1621 iseq = (self._rawobject == other._rawobject) and (self.clsdecl == other.clsdecl)
1622 return self.space.newbool(iseq)
1623
1624 def instance__ne__(self, w_other):
1625 return self.space.not_(self.instance__eq__(w_other))
1626
1627 def instance__nonzero__(self):
1628 if not self._rawobject or \
1629 ((self.flags & INSTANCE_FLAGS_IS_REF) and not self.get_rawobject()):
1630 return self.space.w_False
1631 return self.space.w_True
1632
1633 def instance__len__(self):
1634 w_as_builtin = self._get_as_builtin()
1635 if w_as_builtin is not None:
1636 return self.space.len(w_as_builtin)
1637 raise oefmt(self.space.w_TypeError,
1638 "'%s' has no length", self.clsdecl.name)
1639
1640 def instance__cmp__(self, w_other):
1641 from pypy.module.sys.version import CPYTHON_VERSION
1642 if CPYTHON_VERSION[0] != 3:
1643 w_as_builtin = self._get_as_builtin()
1644 if w_as_builtin is not None:
1645 return self.space.cmp(w_as_builtin, w_other)
1646 raise oefmt(self.space.w_AttributeError,
1647 "'%s' has no attribute __cmp__", self.clsdecl.name)
1648
1649 def instance__repr__(self):
1650 w_as_builtin = self._get_as_builtin()
1651 if w_as_builtin is not None:
1652 return self.space.repr(w_as_builtin)
1653 return self.space.newtext("<%s object at 0x%x>" %
1654 (self.clsdecl.name, rffi.cast(rffi.UINTPTR_T, self.get_rawobject())))
1655
1656 def smartptr(self):
1657 if self._rawobject and self.smartdecl:
1658 return wrap_cppinstance(self.space, self._rawobject, self.smartdecl, do_cast=False)
1659
1660 def destruct(self):
1661 if self._rawobject:
1662 assert isinstance(self.clsdecl, W_CPPClassDecl)
1663 if self.smartdecl and self.deref:
1664 klass = self.smartdecl
1665 elif not (self.flags & INSTANCE_FLAGS_IS_REF):
1666 klass = self.clsdecl
1667 else:
1668 return
1669 memory_regulator.unregister(self)
1670 capi.c_destruct(self.space, klass, self._rawobject)
1671 self._rawobject = capi.C_NULL_OBJECT
1672
1673 def _finalize_(self):
1674 if self.rt_flags & INSTANCE_FLAGS_PYTHON_OWNS:
1675 self.destruct()
1676
1677 W_CPPInstance.typedef = TypeDef(
1678 'CPPInstance',
1679 __python_owns__ = GetSetProperty(W_CPPInstance.fget_python_owns, W_CPPInstance.fset_python_owns),
1680 __init__ = interp2app(W_CPPInstance.instance__init__),
1681 __eq__ = interp2app(W_CPPInstance.instance__eq__),
1682 __ne__ = interp2app(W_CPPInstance.instance__ne__),
1683 # should be based on python version, but syntax is simpler this way
1684 __nonzero__ = interp2app(W_CPPInstance.instance__nonzero__),
1685 __bool__ = interp2app(W_CPPInstance.instance__nonzero__),
1686 __len__ = interp2app(W_CPPInstance.instance__len__),
1687 __cmp__ = interp2app(W_CPPInstance.instance__cmp__),
1688 __repr__ = interp2app(W_CPPInstance.instance__repr__),
1689 __smartptr__ = interp2app(W_CPPInstance.smartptr),
1690 __destruct__ = interp2app(W_CPPInstance.destruct),
1691 )
1692 W_CPPInstance.typedef.acceptable_as_base_class = True
1693
1694
1695 class MemoryRegulator:
1696 _immutable_ = True
1697
1698 @staticmethod
1699 def register(obj):
1700 if not obj._rawobject:
1701 return
1702 addr_as_int = int(rffi.cast(rffi.INTPTR_T, obj.get_rawobject()))
1703 clsdecl = obj.clsdecl
1704 assert isinstance(clsdecl, W_CPPClassDecl)
1705 clsdecl.cppobjects.set(addr_as_int, obj)
1706
1707 @staticmethod
1708 def unregister(obj):
1709 if not obj._rawobject:
1710 return
1711 addr_as_int = int(rffi.cast(rffi.INTPTR_T, obj.get_rawobject()))
1712 clsdecl = obj.clsdecl
1713 assert isinstance(clsdecl, W_CPPClassDecl)
1714 clsdecl.cppobjects.set(addr_as_int, None) # actually deletes (pops)
1715
1716 @staticmethod
1717 def retrieve(clsdecl, address):
1718 if not address:
1719 return None
1720 addr_as_int = int(rffi.cast(rffi.INTPTR_T, address))
1721 assert isinstance(clsdecl, W_CPPClassDecl)
1722 return clsdecl.cppobjects.get(addr_as_int)
1723
1724 memory_regulator = MemoryRegulator()
1725
1726
1727 def get_pythonized_cppclass(space, handle):
1728 state = space.fromcache(State)
1729 try:
1730 w_pycppclass = state.cppclass_registry[handle]
1731 except KeyError:
1732 final_name = capi.c_scoped_final_name(space, handle)
1733 # the callback will cache the class by calling register_class
1734 w_pycppclass = space.call_function(state.w_clgen_callback, space.newtext(final_name))
1735 return w_pycppclass
1736
1737 def get_interface_func(space, w_callable, npar):
1738 state = space.fromcache(State)
1739 return space.call_function(state.w_fngen_callback, w_callable, space.newint(npar))
1740
1741 def wrap_cppinstance(space, rawobject, clsdecl,
1742 smartdecl=None, deref=rffi.cast(capi.C_METHOD, 0),
1743 do_cast=True, python_owns=False, is_ref=False, fresh=False):
1744 rawobject = rffi.cast(capi.C_OBJECT, rawobject)
1745
1746 # cast to actual if requested and possible
1747 w_pycppclass = None
1748 if do_cast and rawobject and not (clsdecl.flags & CLASS_FLAGS_IS_PINNED):
1749 actual = capi.c_actual_class(space, clsdecl, rawobject)
1750 if actual != clsdecl.handle:
1751 try:
1752 w_pycppclass = get_pythonized_cppclass(space, actual)
1753 offset = capi.c_base_offset1(space, actual, clsdecl, rawobject, -1)
1754 rawobject = capi.direct_ptradd(rawobject, offset)
1755 w_cppdecl = space.findattr(w_pycppclass, space.newtext("__cppdecl__"))
1756 clsdecl = space.interp_w(W_CPPClassDecl, w_cppdecl)
1757 except Exception:
1758 # failed to locate/build the derived class, so stick to the base (note
1759 # that only get_pythonized_cppclass is expected to raise, so none of
1760 # the variables are re-assigned yet)
1761 pass
1762
1763 if w_pycppclass is None:
1764 w_pycppclass = get_pythonized_cppclass(space, clsdecl.handle)
1765
1766 # try to recycle existing object if this one is not newly created
1767 if not fresh and rawobject:
1768 address = rawobject
1769 if is_ref:
1770 address = rffi.cast(capi.C_OBJECT, rffi.cast(rffi.VOIDPP, address)[0])
1771 obj = memory_regulator.retrieve(clsdecl, address)
1772 if obj is not None:
1773 return obj
1774
1775 # fresh creation
1776 w_cppinstance = space.allocate_instance(W_CPPInstance, w_pycppclass)
1777 cppinstance = space.interp_w(W_CPPInstance, w_cppinstance)
1778 cppinstance.__init__(space, clsdecl, rawobject, is_ref, python_owns, smartdecl, deref)
1779 memory_regulator.register(cppinstance)
1780 return w_cppinstance
1781
1782 def _addressof(space, w_obj):
1783 try:
1784 # attempt to extract address from array
1785 return rffi.cast(rffi.INTPTR_T, converter.get_rawbuffer(space, w_obj))
1786 except TypeError:
1787 pass
1788 # attempt to get address of C++ instance
1789 return rffi.cast(rffi.INTPTR_T, converter.get_rawobject(space, w_obj, False))
1790
1791 @unwrap_spec(w_obj=W_Root)
1792 def addressof(space, w_obj):
1793 """Takes a bound C++ instance or array, returns the raw address."""
1794 address = _addressof(space, w_obj)
1795 return space.newlong(address)
1796
1797 @unwrap_spec(owns=bool, cast=bool)
1798 def _bind_object(space, w_obj, w_clsdecl, owns=False, cast=False):
1799 try:
1800 # attempt address from array or C++ instance
1801 rawobject = rffi.cast(capi.C_OBJECT, _addressof(space, w_obj))
1802 except Exception:
1803 # accept integer value as address
1804 rawobject = rffi.cast(capi.C_OBJECT, space.uint_w(w_obj))
1805 decl = space.interp_w(W_CPPClassDecl, w_clsdecl)
1806 return wrap_cppinstance(space, rawobject, decl, python_owns=owns, do_cast=cast)
1807
1808 @unwrap_spec(owns=bool, cast=bool)
1809 def bind_object(space, w_obj, w_pycppclass, owns=False, cast=False):
1810 """Takes an address and a bound C++ class proxy, returns a bound instance."""
1811 w_clsdecl = space.findattr(w_pycppclass, space.newtext("__cppdecl__"))
1812 if not w_clsdecl:
1813 w_clsdecl = scope_byname(space, space.text_w(w_pycppclass))
1814 if not w_clsdecl:
1815 raise oefmt(space.w_TypeError,
1816 "no such class: %s", space.text_w(w_pycppclass))
1817 return _bind_object(space, w_obj, w_clsdecl, owns, cast)
1818
1819 def move(space, w_obj):
1820 """Casts the given instance into an C++-style rvalue."""
1821 obj = space.interp_w(W_CPPInstance, w_obj)
1822 if obj:
1823 obj.rt_flags |= INSTANCE_FLAGS_IS_RVALUE
1824 return w_obj
1825
1826
1827 # pythonization interface ---------------------------------------------------
1828
1829 # do not auto-cast to given type
1830 @unwrap_spec(w_pycppclass=W_Root)
1831 def _pin_type(space, w_pycppclass):
1832 w_clsdecl = space.findattr(w_pycppclass, space.newtext("__cppdecl__"))
1833 decl = space.interp_w(W_CPPClassDecl, w_clsdecl)
1834 decl.flags |= CLASS_FLAGS_IS_PINNED