Debian Codegraph @

pypy/module/_cppyy/pythonify.py

raw symbols SCIP
1 # NOT_RPYTHON
2 # do not load _cppyy here, see _post_import_startup()
3 import sys
4
5 class _C:
6 def _m(self): pass
7 MethodType = type(_C()._m)
8
9 # Metaclasses are needed to store C++ static data members as properties and to
10 # provide Python language features such as a customized __dir__ for namespaces
11 # and __getattr__ for both. These features are used for lazy lookup/creation.
12 # Since the interp-level does not support metaclasses, this is all done at the
13 # app-level.
14 #
15 # C++ namespaces: are represented as Python classes, with CPPNamespace as the
16 # base class, which is at the moment just a label, and CPPNamespaceMeta as
17 # the base class of their invididualized meta class.
18 #
19 # C++ classes: are represented as Python classes, with CPPClass as the base
20 # class, which is a subclass of the interp-level CPPInstance. The former
21 # sets up the Python-class behavior for bound classes, the latter adds the
22 # bound object behavior that lives at the class level.
23
24 class CPPScopeMeta(type):
25 def __getattr__(self, name):
26 try:
27 return get_scoped_pycppitem(self, name) # will cache on self
28 except Exception as e:
29 raise AttributeError("%s object has no attribute '%s' (details: %s)" %
30 (self, name, str(e)))
31
32 class CPPNamespaceMeta(CPPScopeMeta):
33 def __dir__(self):
34 # For Py3: can actually call base class __dir__ (lives in type)
35 values = set(self.__dict__.keys())
36 values.update(object.__dict__.keys())
37 values.update(type(self).__dict__.keys())
38
39 # add C++ entities
40 values.update(self.__cppdecl__.__dir__())
41 return list(values)
42
43 class CPPClassMeta(CPPScopeMeta):
44 pass
45
46 # from six.py ---
47 # Copyright (c) 2010-2017 Benjamin Peterson
48 #
49 # Permission is hereby granted, free of charge, to any person obtaining a copy
50 # of this software and associated documentation files (the "Software"), to deal
51 # in the Software without restriction, including without limitation the rights
52 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
53 # copies of the Software, and to permit persons to whom the Software is
54 # furnished to do so, subject to the following conditions:
55 #
56 # The above copyright notice and this permission notice shall be included in all
57 # copies or substantial portions of the Software.
58 #
59 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
60 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
61 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
62 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
63 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
64 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
65 # SOFTWARE.
66
67 def with_metaclass(meta, *bases):
68 """Create a base class with a metaclass."""
69 # This requires a bit of explanation: the basic idea is to make a dummy
70 # metaclass for one level of class instantiation that replaces itself with
71 # the actual metaclass.
72 class metaclass(type):
73
74 def __new__(cls, name, this_bases, d):
75 return meta(name, bases, d)
76
77 @classmethod
78 def __prepare__(cls, name, this_bases):
79 return meta.__prepare__(name, bases)
80 return type.__new__(metaclass, 'temporary_class', (), {})
81 # --- end from six.py
82
83 # C++ namespace base class (the C++ class base class defined in _post_import_startup)
84 class CPPNamespace(with_metaclass(CPPNamespaceMeta, object)):
85 def __init__(self):
86 raise TypeError("cannot instantiate namespace '%s'", self.__cpp_name__)
87
88
89 # TODO: this can be moved to the interp level (and share template argument
90 # construction with function templates there)
91 class CPPTemplate(object):
92 def __init__(self, name, scope=None):
93 self._name = name
94 if scope is None:
95 self._scope = gbl
96 else:
97 self._scope = scope
98
99 def _arg_to_str(self, arg):
100 # arguments are strings representing types, types, or builtins
101 if type(arg) == str:
102 return arg # string describing type
103 elif hasattr(arg, '__cpp_name__'):
104 return arg.__cpp_name__ # C++ bound type
105 elif arg == str:
106 import _cppyy
107 return _cppyy._std_string_name() # special case pystr -> C++ string
108 elif isinstance(arg, type): # builtin types
109 return arg.__name__
110 return str(arg) # builtin values
111
112 def __call__(self, *args):
113 fullname = ''.join(
114 [self._name, '<', ','.join(map(self._arg_to_str, args))])
115 fullname += '>'
116 try:
117 return self._scope.__dict__[fullname]
118 except KeyError:
119 pass
120 result = get_scoped_pycppitem(self._scope, fullname, True)
121 if not result:
122 raise TypeError("%s does not exist" % fullname)
123 return result
124
125 def __getitem__(self, *args):
126 if args and type(args[0]) == tuple:
127 return self.__call__(*(args[0]))
128 return self.__call__(*args)
129
130
131 def scope_splitter(name):
132 is_open_template, scope = 0, ""
133 for c in name:
134 if c == ':' and not is_open_template:
135 if scope:
136 yield scope
137 scope = ""
138 continue
139 elif c == '<':
140 is_open_template += 1
141 elif c == '>':
142 is_open_template -= 1
143 scope += c
144 yield scope
145
146 def get_pycppitem(final_scoped_name):
147 # walk scopes recursively down from global namespace ("::") to get the
148 # actual (i.e. not typedef'ed) class, triggering all necessary creation
149 scope = gbl
150 for name in scope_splitter(final_scoped_name):
151 scope = getattr(scope, name)
152 return scope
153 get_pycppclass = get_pycppitem # currently no distinction, but might
154 # in future for performance
155
156
157 # callbacks (originating from interp_cppyy.py) to allow interp-level to
158 # initiate creation of app-level classes and function
159 def clgen_callback(final_scoped_name):
160 return get_pycppclass(final_scoped_name)
161
162 def fngen_callback(func, npar): # todo, some kind of arg transform spec
163 if npar == 0:
164 def wrapper(a0, a1):
165 la0 = [a0[0], a0[1], a0[2], a0[3]]
166 return func(la0)
167 return wrapper
168 else:
169 def wrapper(a0, a1):
170 la0 = [a0[0], a0[1], a0[2], a0[3]]
171 la1 = [a1[i] for i in range(npar)]
172 return func(la0, la1)
173 return wrapper
174
175
176 # construction of namespaces and classes, and their helpers
177 def make_module_name(scope):
178 if scope:
179 return scope.__module__ + '.' + scope.__name__
180 return 'cppyy'
181
182 def make_cppnamespace(scope, name, decl):
183 # build up a representation of a C++ namespace (namespaces are classes)
184
185 # create a metaclass to allow properties (for static data write access)
186 import _cppyy
187 ns_meta = type(CPPNamespace)(name+'_meta', (CPPNamespaceMeta,), {})
188
189 # create the python-side C++ namespace representation, cache in scope if given
190 d = {"__cppdecl__" : decl,
191 "__module__" : make_module_name(scope),
192 "__cpp_name__" : decl.__cpp_name__ }
193 pyns = ns_meta(name, (CPPNamespace,), d)
194 if scope:
195 setattr(scope, name, pyns)
196
197 # install as modules to allow importing from (note naming: cppyy)
198 sys.modules[make_module_name(pyns)] = pyns
199 return pyns
200
201 def _drop_cycles(bases):
202 # TODO: figure out why this is necessary?
203 for b1 in bases:
204 for b2 in bases:
205 if not (b1 is b2) and issubclass(b2, b1):
206 bases.remove(b1) # removes lateral class
207 break
208 return tuple(bases)
209
210 def make_new(decl):
211 def __new__(cls, *args):
212 # create a place-holder only as there may be a derived class defined
213 # TODO: get rid of the import and add user-land bind_object that uses
214 # _bind_object (see interp_cppyy.py)
215 import _cppyy
216 instance = _cppyy._bind_object(0, decl, True)
217 if not instance.__class__ is cls:
218 instance.__class__ = cls # happens for derived class
219 return instance
220 return __new__
221
222 def make_cppclass(scope, cl_name, decl):
223 import _cppyy
224
225 # get a list of base classes for class creation
226 bases = [get_pycppclass(base) for base in decl.get_base_names()]
227 if not bases:
228 bases = [CPPClass,]
229 else:
230 # it's possible that the required class now has been built if one of
231 # the base classes uses it in e.g. a function interface
232 try:
233 return scope.__dict__[cl_name]
234 except KeyError:
235 pass
236
237 # prepare dictionary for metaclass
238 d_meta = {}
239
240 # prepare dictionary for python-side C++ class representation
241 def dispatch(self, m_name, signature):
242 cppol = decl.__dispatch__(m_name, signature)
243 return MethodType(cppol, self, type(self))
244 d_class = {"__cppdecl__" : decl,
245 "__new__" : make_new(decl),
246 "__module__" : make_module_name(scope),
247 "__cpp_name__" : decl.__cpp_name__,
248 "__dispatch__" : dispatch,}
249
250 # insert (static) methods into the class dictionary
251 for m_name in decl.get_method_names():
252 cppol = decl.get_overload(m_name)
253 d_class[m_name] = cppol
254
255 # add all data members to the dictionary of the class to be created, and
256 # static ones also to the metaclass (needed for property setters)
257 for d_name in decl.get_datamember_names():
258 cppdm = decl.get_datamember(d_name)
259 d_class[d_name] = cppdm
260 if _cppyy._is_static_data(cppdm):
261 d_meta[d_name] = cppdm
262
263 # create a metaclass to allow properties (for static data write access)
264 metabases = [type(base) for base in bases]
265 cl_meta = type(CPPClassMeta)(cl_name+'_meta', _drop_cycles(metabases), d_meta)
266
267 # create the python-side C++ class
268 pycls = cl_meta(cl_name, _drop_cycles(bases), d_class)
269
270 # store the class on its outer scope
271 setattr(scope, cl_name, pycls)
272
273 # the call to register will add back-end specific pythonizations and thus
274 # needs to run first, so that the generic pythonizations can use them
275 import _cppyy
276 _cppyy._register_class(pycls)
277 _pythonize(pycls, pycls.__cpp_name__)
278 return pycls
279
280 def make_cpptemplatetype(scope, template_name):
281 return CPPTemplate(template_name, scope)
282
283
284 def get_scoped_pycppitem(scope, name, type_only=False):
285 import _cppyy
286
287 # resolve typedefs/aliases: these may cross namespaces, in which case
288 # the lookup must trigger the creation of all necessary scopes
289 scoped_name = (scope == gbl) and name or (scope.__cpp_name__+'::'+name)
290 final_scoped_name = _cppyy._resolve_name(scoped_name)
291 if final_scoped_name != scoped_name:
292 pycppitem = get_pycppitem(final_scoped_name)
293 # also store on the requested scope (effectively a typedef or pointer copy)
294 setattr(scope, name, pycppitem)
295 return pycppitem
296
297 pycppitem = None
298
299 # scopes (classes and namespaces)
300 cppitem = _cppyy._scope_byname(final_scoped_name)
301 if cppitem:
302 if cppitem.is_namespace():
303 pycppitem = make_cppnamespace(scope, name, cppitem)
304 else:
305 pycppitem = make_cppclass(scope, name, cppitem)
306
307 if type_only:
308 return pycppitem
309
310 # templates
311 if not cppitem:
312 cppitem = _cppyy._is_template(final_scoped_name)
313 if cppitem:
314 pycppitem = make_cpptemplatetype(scope, name)
315 setattr(scope, name, pycppitem)
316
317 # functions
318 if not cppitem:
319 try:
320 cppitem = scope.__cppdecl__.get_overload(name)
321 setattr(scope, name, cppitem)
322 pycppitem = getattr(scope, name) # binds function as needed
323 except AttributeError:
324 pass
325
326 # data
327 if not cppitem:
328 try:
329 cppdm = scope.__cppdecl__.get_datamember(name)
330 setattr(scope, name, cppdm)
331 if _cppyy._is_static_data(cppdm):
332 setattr(scope.__class__, name, cppdm)
333 pycppitem = getattr(scope, name) # gets actual property value
334 except AttributeError:
335 pass
336
337 # enum type
338 if not cppitem:
339 if scope.__cppdecl__.has_enum(name):
340 pycppitem = int
341
342 if pycppitem is not None: # pycppitem could be a bound C++ NULL, so check explicitly for Py_None
343 return pycppitem
344
345 raise AttributeError("'%s' has no attribute '%s'" % (str(scope), name))
346
347
348 # helper for pythonization API
349 def extract_namespace(name):
350 # find the namespace the named class lives in, take care of templates
351 tpl_open = 0
352 for pos in range(len(name)-1, 1, -1):
353 c = name[pos]
354
355 # count '<' and '>' to be able to skip template contents
356 if c == '>':
357 tpl_open += 1
358 elif c == '<':
359 tpl_open -= 1
360
361 # collect name up to "::"
362 elif tpl_open == 0 and c == ':' and name[pos-1] == ':':
363 # found the extend of the scope ... done
364 return name[:pos-1], name[pos+1:]
365
366 # no namespace; assume outer scope
367 return '', name
368
369 # pythonization by decoration (move to their own file?)
370 def python_style_getitem(self, _idx):
371 # python-style indexing: check for size and allow indexing from the back
372 sz = len(self)
373 idx = _idx
374 if isinstance(idx, int):
375 if idx < 0: idx = sz + idx
376 if 0 <= idx < sz:
377 return self._getitem__unchecked(idx)
378 else:
379 raise IndexError(
380 'index out of range: %s requested for %s of size %d' % (str(idx), str(self), sz))
381 # may fail for the same reasons as above, but will now give proper error message
382 return self._getitem__unchecked(_idx)
383
384 def python_style_sliceable_getitem(self, slice_or_idx):
385 if type(slice_or_idx) == slice:
386 nseq = self.__class__()
387 nseq += [python_style_getitem(self, i) \
388 for i in range(*slice_or_idx.indices(len(self)))]
389 return nseq
390 return python_style_getitem(self, slice_or_idx)
391
392 def _pythonize(pyclass, name):
393 # general note: use 'in pyclass.__dict__' rather than 'hasattr' to prevent
394 # adding pythonizations multiple times in derived classes
395
396 import _cppyy
397
398 # map __eq__/__ne__ through a comparison to None
399 if '__eq__' in pyclass.__dict__:
400 def __eq__(self, other):
401 if other is None: return not self
402 if not self and not other: return True
403 try:
404 return self._cxx_eq(other)
405 except TypeError:
406 return NotImplemented
407 pyclass._cxx_eq = pyclass.__dict__['__eq__']
408 pyclass.__eq__ = __eq__
409
410 if '__ne__' in pyclass.__dict__:
411 def __ne__(self, other):
412 if other is None: return not not self
413 if type(self) is not type(other): return True
414 return self._cxx_ne(other)
415 pyclass._cxx_ne = pyclass.__dict__['__ne__']
416 pyclass.__ne__ = __ne__
417
418 # map size -> __len__ (generally true for STL)
419 if 'size' in pyclass.__dict__ and not '__len__' in pyclass.__dict__ \
420 and callable(pyclass.size):
421 pyclass.__len__ = pyclass.size
422
423 # map push_back -> __iadd__ (generally true for STL)
424 if 'push_back' in pyclass.__dict__ and not '__iadd__' in pyclass.__dict__:
425 if 'reserve' in pyclass.__dict__:
426 def iadd(self, ll):
427 self.reserve(len(ll))
428 for x in ll: self.push_back(x)
429 return self
430 else:
431 def iadd(self, ll):
432 for x in ll: self.push_back(x)
433 return self
434 pyclass.__iadd__ = iadd
435
436 is_vector = name.find('std::vector', 0, 11) == 0
437
438 # map begin()/end() protocol to iter protocol on STL(-like) classes, but
439 # not on vector, which is pythonized in the capi (interp-level; there is
440 # also the fallback on the indexed __getitem__, but that is slower)
441 add_checked_item = False
442 if not is_vector:
443 if 'begin' in pyclass.__dict__ and 'end' in pyclass.__dict__:
444 if _cppyy._scope_byname(name+'::iterator') or \
445 _cppyy._scope_byname(name+'::const_iterator'):
446 def __iter__(self):
447 i = self.begin()
448 end = self.size()
449 count = 0
450 while count != end:
451 yield i.__deref__()
452 i.__preinc__()
453 count += 1
454 i.__destruct__()
455 raise StopIteration
456 pyclass.__iter__ = __iter__
457 else:
458 # rely on numbered iteration
459 add_checked_item = True
460
461 # add python collection based initializer
462 else:
463 pyclass.__real_init__ = pyclass.__init__
464 def vector_init(self, *args):
465 if len(args) == 1 and isinstance(args[0], (tuple, list)):
466 ll = args[0]
467 self.__real_init__()
468 self.reserve(len(ll))
469 for item in ll:
470 self.push_back(item)
471 return
472 return self.__real_init__(*args)
473 pyclass.__init__ = vector_init
474
475 # size-up the return of data()
476 if hasattr(pyclass, 'data'): # not the case for e.g. vector<bool>
477 pyclass.__real_data = pyclass.data
478 def data_with_len(self):
479 arr = self.__real_data()
480 arr.reshape((len(self),))
481 return arr
482 pyclass.data = data_with_len
483
484 # TODO: must be a simpler way to check (or at least hook these to a namespace
485 # std specific pythonizor)
486 if add_checked_item or is_vector or \
487 name.find('std::array', 0, 11) == 0 or name.find('std::deque', 0, 10) == 0:
488 # combine __getitem__ and __len__ to make a pythonized __getitem__
489 if '__getitem__' in pyclass.__dict__ and '__len__' in pyclass.__dict__:
490 pyclass._getitem__unchecked = pyclass.__getitem__
491 if '__setitem__' in pyclass.__dict__ and '__iadd__' in pyclass.__dict__:
492 pyclass.__getitem__ = python_style_sliceable_getitem
493 else:
494 pyclass.__getitem__ = python_style_getitem
495
496 # string comparisons
497 if name == _cppyy._std_string_name():
498 def eq(self, other):
499 if type(other) == pyclass:
500 return self.c_str() == other.c_str()
501 else:
502 return self.c_str() == other
503 pyclass.__eq__ = eq
504 pyclass.__str__ = pyclass.c_str
505
506 # std::pair unpacking through iteration
507 elif name.find('std::pair', 0, 9) == 0:
508 def getitem(self, idx):
509 if idx == 0: return self.first
510 if idx == 1: return self.second
511 raise IndexError("out of bounds")
512 def return2(self):
513 return 2
514 pyclass.__getitem__ = getitem
515 pyclass.__len__ = return2
516
517 # std::complex integration with Python complex
518 elif name.find('std::complex', 0, 12) == 0:
519 def getreal(obj):
520 return obj.__cpp_real()
521 def setreal(obj, val):
522 obj.__cpp_real(val)
523 pyclass.__cpp_real = pyclass.real
524 pyclass.real = property(getreal, setreal)
525
526 def getimag(obj):
527 return obj.__cpp_imag()
528 def setimag(obj, val):
529 obj.__cpp_imag(val)
530 pyclass.__cpp_imag = pyclass.imag
531 pyclass.imag = property(getimag, setimag)
532
533 def cmplx(self):
534 return self.real+self.imag*1.j
535 pyclass.__complex__ = cmplx
536
537 def cmplx_repr(self):
538 return repr(self.__complex__())
539 pyclass.__repr__ = cmplx_repr
540
541 # user provided, custom pythonizations
542 try:
543 ns_name, cl_name = extract_namespace(name)
544 pythonizors = _pythonizations[ns_name]
545 name = cl_name
546 except KeyError:
547 pythonizors = _pythonizations[''] # global scope
548
549 for p in pythonizors:
550 p(pyclass, name)
551
552 cppyyIsInitialized = False
553 def _post_import_startup():
554 # run only once (function is explicitly called in testing)
555 global cppyyIsInitialized
556 if cppyyIsInitialized:
557 return
558
559 # _cppyy should not be loaded at the module level, as that will trigger a
560 # call to space.getbuiltinmodule(), which will cause _cppyy to be loaded
561 # at pypy-c startup, rather than on the "import _cppyy" statement
562 import _cppyy
563
564 # root of all proxy classes: CPPClass in pythonify exists to combine the
565 # CPPClassMeta metaclass (for Python-side class behavior) with the
566 # interp-level CPPInstance (for bound object behavior)
567 global CPPClass
568 class CPPClass(with_metaclass(CPPClassMeta, _cppyy.CPPInstance)):
569 pass
570
571 # class generator callback
572 _cppyy._set_class_generator(clgen_callback)
573
574 # function generator callback
575 _cppyy._set_function_generator(fngen_callback)
576
577 # user interface objects
578 global gbl
579 gbl = make_cppnamespace(None, 'gbl', _cppyy._scope_byname(''))
580 gbl.__module__ = 'cppyy'
581 gbl.__doc__ = 'Global C++ namespace.'
582
583 # pre-create std to allow direct importing
584 gbl.std = make_cppnamespace(gbl, 'std', _cppyy._scope_byname('std'))
585
586 # add move cast
587 gbl.std.move = _cppyy.move
588
589 # install a type for enums to refer to
590 setattr(gbl, 'internal_enum_type_t', int)
591 setattr(gbl, 'unsigned int', int) # if resolved
592
593 # install for user access
594 _cppyy.gbl = gbl
595
596 # install nullptr as a unique reference
597 _cppyy.nullptr = _cppyy._get_nullptr()
598
599 # done
600 cppyyIsInitialized = True
601
602
603 # user-defined pythonizations interface
604 _pythonizations = {'' : list()}
605 def add_pythonization(pythonizor, scope = ''):
606 """<pythonizor> should be a callable taking two arguments: a class proxy,
607 and its C++ name. It is called on each time a named class from <scope>
608 (the global one by default, but a relevant C++ namespace is recommended)
609 is bound.
610 """
611 if not callable(pythonizor):
612 raise TypeError("given '%s' object is not callable" % str(pythonizor))
613 try:
614 _pythonizations[scope].append(pythonizor)
615 except KeyError:
616 _pythonizations[scope] = list()
617 _pythonizations[scope].append(pythonizor)
618
619 def remove_pythonization(pythonizor, scope = ''):
620 """Remove previously registered <pythonizor> from <scope>.
621 """
622 try:
623 _pythonizations[scope].remove(pythonizor)
624 return True
625 except (KeyError, ValueError):
626 return False