ROOT  6.06/09
Reference Guide
MethodProxy.cxx
Go to the documentation of this file.
1 // @(#)root/pyroot:$Id$
2 // Author: Wim Lavrijsen, Jan 2005
3 
4 // Bindings
5 #include "PyROOT.h"
6 #include "structmember.h" // from Python
7 #if PY_VERSION_HEX >= 0x02050000
8 #include "code.h" // from Python
9 #else
10 #include "compile.h" // from Python
11 #endif
12 #ifndef CO_NOFREE
13 // python2.2 does not have CO_NOFREE defined
14 #define CO_NOFREE 0x0040
15 #endif
16 #include "MethodProxy.h"
17 #include "ObjectProxy.h"
18 #include "TCallContext.h"
19 #include "TPyException.h"
20 #include "PyStrings.h"
21 
22 // Standard
23 #include <algorithm>
24 #include <vector>
25 
26 
27 namespace PyROOT {
28 
29 // TODO: only used here, but may be better off integrated with Pythonize.cxx callbacks
30  class TPythonCallback : public PyCallable {
31  public:
32  PyObject* fCallable;
33 
34  TPythonCallback( PyObject* callable ) {
35  if ( !PyCallable_Check( callable ) ) {
36  PyErr_SetString(PyExc_TypeError, "parameter must be callable");
37  return;
38  }
39  fCallable = callable;
40  Py_INCREF( fCallable );
41  }
42 
43  virtual ~TPythonCallback() {
44  Py_DECREF( fCallable );
45  fCallable = 0;
46  }
47 
48  virtual PyObject* GetSignature() { return PyROOT_PyUnicode_FromString( "*args, **kwargs" ); } ;
49  virtual PyObject* GetPrototype() { return PyROOT_PyUnicode_FromString( "<callback>" ); } ;
50  virtual PyObject* GetDocString() {
51  if ( PyObject_HasAttrString( fCallable, "__doc__" )) {
52  return PyObject_GetAttrString( fCallable, "__doc__" );
53  } else {
54  return GetPrototype();
55  }
56  }
57 
58  virtual Int_t GetPriority() { return 100; };
59 
60  virtual Int_t GetMaxArgs() { return 100; };
61  virtual PyObject* GetCoVarNames() { // TODO: pick these up from the callable
62  Py_INCREF( Py_None );
63  return Py_None;
64  }
65  virtual PyObject* GetArgDefault( Int_t /* iarg */ ) { // TODO: pick these up from the callable
66  Py_INCREF( Py_None );
67  return Py_None;
68  }
69 
70  virtual PyObject* GetScopeProxy() { // should this be the module ??
71  Py_INCREF( Py_None );
72  return Py_None;
73  }
74 
75  virtual PyCallable* Clone() { return new TPythonCallback( *this ); }
76 
77  virtual PyObject* Call(
78  ObjectProxy*& self, PyObject* args, PyObject* kwds, TCallContext* /* ctxt = 0 */ ) {
79 
80  PyObject* newArgs = nullptr;
81  if ( self ) {
82  Py_ssize_t nargs = PyTuple_Size( args );
83  newArgs = PyTuple_New( nargs+1 );
84  Py_INCREF( self );
85  PyTuple_SET_ITEM( newArgs, 0, (PyObject*)self );
86  for ( Py_ssize_t iarg = 0; iarg < nargs; ++iarg ) {
87  PyObject* pyarg = PyTuple_GET_ITEM( args, iarg );
88  Py_INCREF( pyarg );
89  PyTuple_SET_ITEM( newArgs, iarg+1, pyarg );
90  }
91  } else {
92  Py_INCREF( args );
93  newArgs = args;
94  }
95  return PyObject_Call( fCallable, newArgs, kwds );
96  }
97  };
98 
99 namespace {
100 
101 // helper to test whether a method is used in a pseudo-function modus
102  Bool_t inline IsPseudoFunc( MethodProxy* pymeth )
103  {
104  return (void*)pymeth == (void*)pymeth->fSelf;
105  }
106 
107 // helper for collecting/maintaining exception data in overload dispatch
108  struct PyError_t {
109  PyError_t() { fType = fValue = fTrace = 0; }
110 
111  static void Clear( PyError_t& e )
112  {
113  // Remove exception information.
114  Py_XDECREF( e.fType ); Py_XDECREF( e.fValue ); Py_XDECREF( e.fTrace );
115  e.fType = e.fValue = e.fTrace = 0;
116  }
117 
119  };
120 
121 // helper to hash tuple (using tuple hash would cause self-tailing loops)
122  inline Long_t HashSignature( PyObject* args )
123  {
124  // Build a hash from the types of the given python function arguments.
125  ULong_t hash = 0;
126 
127  Int_t nargs = PyTuple_GET_SIZE( args );
128  for ( Int_t i = 0; i < nargs; ++i ) {
129  hash += (ULong_t) Py_TYPE( PyTuple_GET_ITEM( args, i ) );
130  hash += (hash << 10); hash ^= (hash >> 6);
131  }
132 
133  hash += (hash << 3); hash ^= (hash >> 11); hash += (hash << 15);
134 
135  return hash;
136  }
137 
138 // helper to sort on method priority
139  int PriorityCmp( PyCallable* left, PyCallable* right )
140  {
141  return left->GetPriority() > right->GetPriority();
142  }
143 
144 // return helper
145  inline void ResetCallState( ObjectProxy*& selfnew, ObjectProxy* selfold, Bool_t clear ) {
146  if ( selfnew != selfold ) {
147  Py_XDECREF( selfnew );
148  selfnew = selfold;
149  }
150 
151  if ( clear )
152  PyErr_Clear();
153  }
154 
155 // helper to factor out return logic of mp_call
156  inline PyObject* HandleReturn( MethodProxy* pymeth, ObjectProxy* oldSelf, PyObject* result ) {
157 
158  // special case for python exceptions, propagated through C++ layer
159  if ( result ) {
160 
161  // if this method creates new objects, always take ownership
162  if ( IsCreator( pymeth->fMethodInfo->fFlags ) ) {
163 
164  // either be a constructor with a fresh object proxy self ...
165  if ( IsConstructor( pymeth->fMethodInfo->fFlags ) ) {
166  if ( pymeth->fSelf )
167  pymeth->fSelf->HoldOn();
168  }
169 
170  // ... or be a method with an object proxy return value
171  else if ( ObjectProxy_Check( result ) )
172  ((ObjectProxy*)result)->HoldOn();
173  }
174 
175  // if this new object falls inside self, make sure its lifetime is proper
176  if ( ObjectProxy_Check( pymeth->fSelf ) && ObjectProxy_Check( result ) ) {
177  Long_t ptrdiff = (Long_t)((ObjectProxy*)result)->GetObject() - (Long_t)pymeth->fSelf->GetObject();
178  if ( 0 <= ptrdiff && ptrdiff < (Long_t)Cppyy::SizeOf( pymeth->fSelf->ObjectIsA() ) ) {
179  if ( PyObject_SetAttr( result, PyStrings::gLifeLine, (PyObject*)pymeth->fSelf ) == -1 )
180  PyErr_Clear(); // ignored
181  }
182  }
183  }
184 
185  // reset self as necessary to allow re-use of the MethodProxy
186  ResetCallState( pymeth->fSelf, oldSelf, kFALSE );
187 
188  return result;
189  }
190 
191 
192 //= PyROOT method proxy object behaviour =====================================
193  PyObject* mp_name( MethodProxy* pymeth, void* )
194  {
195  return PyROOT_PyUnicode_FromString( pymeth->GetName().c_str() );
196  }
197 
198 ////////////////////////////////////////////////////////////////////////////////
199 
200  PyObject* mp_module( MethodProxy* /* pymeth */, void* )
201  {
202  Py_INCREF( PyStrings::gROOTns );
203  return PyStrings::gROOTns;
204  }
205 
206 ////////////////////////////////////////////////////////////////////////////////
207 /// Build python document string ('__doc__') from all C++-side overloads.
208 
209  PyObject* mp_doc( MethodProxy* pymeth, void* )
210  {
211  MethodProxy::Methods_t& methods = pymeth->fMethodInfo->fMethods;
212 
213  // collect doc strings
214  Int_t nMethods = methods.size();
215  PyObject* doc = methods[0]->GetDocString();
216 
217  // simple case
218  if ( nMethods == 1 )
219  return doc;
220 
221  // overloaded method
222  PyObject* separator = PyROOT_PyUnicode_FromString( "\n" );
223  for ( Int_t i = 1; i < nMethods; ++i ) {
224  PyROOT_PyUnicode_Append( &doc, separator );
225  PyROOT_PyUnicode_AppendAndDel( &doc, methods[i]->GetDocString() );
226  }
227  Py_DECREF( separator );
228 
229  return doc;
230  }
231 
232 ////////////////////////////////////////////////////////////////////////////////
233 /// Create a new method proxy to be returned.
234 
235  PyObject* mp_meth_func( MethodProxy* pymeth, void* )
236  {
237  MethodProxy* newPyMeth = (MethodProxy*)MethodProxy_Type.tp_alloc( &MethodProxy_Type, 0 );
238 
239  // method info is shared, as it contains the collected overload knowledge
240  *pymeth->fMethodInfo->fRefCount += 1;
241  newPyMeth->fMethodInfo = pymeth->fMethodInfo;
242 
243  // new method is unbound, use of 'meth' is for keeping track whether this
244  // proxy is used in the capacity of a method or a function
245  newPyMeth->fSelf = (ObjectProxy*)newPyMeth;
246 
247  return (PyObject*)newPyMeth;
248  }
249 
250 ////////////////////////////////////////////////////////////////////////////////
251 /// Return the bound self, if any; in case of pseudo-function role, pretend
252 /// that the data member im_self does not exist.
253 
254  PyObject* mp_meth_self( MethodProxy* pymeth, void* )
255  {
256  if ( IsPseudoFunc( pymeth ) ) {
257  PyErr_Format( PyExc_AttributeError,
258  "function %s has no attribute \'im_self\'", pymeth->fMethodInfo->fName.c_str() );
259  return 0;
260  } else if ( pymeth->fSelf != 0 ) {
261  Py_INCREF( (PyObject*)pymeth->fSelf );
262  return (PyObject*)pymeth->fSelf;
263  }
264 
265  Py_INCREF( Py_None );
266  return Py_None;
267  }
268 
269 ////////////////////////////////////////////////////////////////////////////////
270 /// Return scoping class; in case of pseudo-function role, pretend that there
271 /// is no encompassing class (i.e. global scope).
272 
273  PyObject* mp_meth_class( MethodProxy* pymeth, void* )
274  {
275  if ( ! IsPseudoFunc( pymeth ) ) {
276  PyObject* pyclass = pymeth->fMethodInfo->fMethods[0]->GetScopeProxy();
277  if ( ! pyclass )
278  PyErr_Format( PyExc_AttributeError,
279  "function %s has no attribute \'im_class\'", pymeth->fMethodInfo->fName.c_str() );
280  return pyclass;
281  }
282 
283  Py_INCREF( Py_None );
284  return Py_None;
285  }
286 
287 ////////////////////////////////////////////////////////////////////////////////
288 /// Stub only, to fill out the python function interface.
289 
290  PyObject* mp_func_closure( MethodProxy* /* pymeth */, void* )
291  {
292  Py_INCREF( Py_None );
293  return Py_None;
294  }
295 
296 ////////////////////////////////////////////////////////////////////////////////
297 /// Code details are used in module inspect to fill out interactive help()
298 
299  PyObject* mp_func_code( MethodProxy* pymeth, void* )
300  {
301 #if PY_VERSION_HEX < 0x03000000
302  MethodProxy::Methods_t& methods = pymeth->fMethodInfo->fMethods;
303 
304  // collect arguments only if there is just 1 overload, otherwise put in a
305  // fake *args (see below for co_varnames)
306  PyObject* co_varnames = methods.size() == 1 ? methods[0]->GetCoVarNames() : NULL;
307  if ( !co_varnames ) {
308  // TODO: static methods need no 'self' (but is harmless otherwise)
309  co_varnames = PyTuple_New( 1 /* self */ + 1 /* fake */ );
310  PyTuple_SET_ITEM( co_varnames, 0, PyROOT_PyUnicode_FromString( "self" ) );
311  PyTuple_SET_ITEM( co_varnames, 1, PyROOT_PyUnicode_FromString( "*args" ) );
312  }
313 
314  int co_argcount = PyTuple_Size( co_varnames );
315 
316  // for now, code object representing the statement 'pass'
317  PyObject* co_code = PyString_FromStringAndSize( "d\x00\x00S", 4 );
318 
319  // tuples with all the const literals used in the function
320  PyObject* co_consts = PyTuple_New( 0 );
321  PyObject* co_names = PyTuple_New( 0 );
322 
323  // names, freevars, and cellvars go unused
324  PyObject* co_unused = PyTuple_New( 0 );
325 
326  // filename is made-up
327  PyObject* co_filename = PyString_FromString( "ROOT.py" );
328 
329  // name is the function name, also through __name__ on the function itself
330  PyObject* co_name = PyString_FromString( pymeth->GetName().c_str() );
331 
332  // firstlineno is the line number of first function code in the containing scope
333 
334  // lnotab is a packed table that maps instruction count and line number
335  PyObject* co_lnotab = PyString_FromString( "\x00\x01\x0c\x01" );
336 
337  PyObject* code = (PyObject*)PyCode_New(
338  co_argcount, // argcount
339  co_argcount + 1, // nlocals
340  2, // stacksize
341  CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE, // flags
342  co_code, // code
343  co_consts, // consts
344  co_names, // names
345  co_varnames, // varnames
346  co_unused, // freevars
347  co_unused, // cellvars
348  co_filename, // filename
349  co_name, // name
350  1, // firstlineno
351  co_lnotab ); // lnotab
352 
353  Py_DECREF( co_lnotab );
354  Py_DECREF( co_name );
355  Py_DECREF( co_unused );
356  Py_DECREF( co_filename );
357  Py_DECREF( co_varnames );
358  Py_DECREF( co_names );
359  Py_DECREF( co_consts );
360  Py_DECREF( co_code );
361 
362  return code;
363 #else
364 // not important for functioning of most code, so not implemented for p3 for now (TODO)
365  pymeth = 0;
366  if ( pymeth || !pymeth) Py_INCREF( Py_None );
367  return Py_None;
368 #endif
369  }
370 
371 ////////////////////////////////////////////////////////////////////////////////
372 /// Create a tuple of default values, if there is only one method (otherwise
373 /// leave undefined: this is only used by inspect for interactive help())
374 
375  PyObject* mp_func_defaults( MethodProxy* pymeth, void* )
376  {
377  MethodProxy::Methods_t& methods = pymeth->fMethodInfo->fMethods;
378 
379  if ( methods.size() != 1 )
380  return PyTuple_New( 0 );
381 
382  int maxarg = methods[0]->GetMaxArgs();
383 
384  PyObject* defaults = PyTuple_New( maxarg );
385 
386  int itup = 0;
387  for ( int iarg = 0; iarg < maxarg; ++iarg ) {
388  PyObject* defvalue = methods[0]->GetArgDefault( iarg );
389  if ( defvalue )
390  PyTuple_SET_ITEM( defaults, itup++, defvalue );
391  }
392  _PyTuple_Resize( &defaults, itup );
393 
394  return defaults;
395  }
396 
397 ////////////////////////////////////////////////////////////////////////////////
398 /// Return this function's global dict (hard-wired to be the ROOT module); used
399 /// for lookup of names from co_code indexing into co_names.
400 
401  PyObject* mp_func_globals( MethodProxy* /* pymeth */, void* )
402  {
403  PyObject* pyglobal = PyModule_GetDict( PyImport_AddModule( (char*)"ROOT" ) );
404  Py_XINCREF( pyglobal );
405  return pyglobal;
406  }
407 
408 ////////////////////////////////////////////////////////////////////////////////
409 /// Get '_creates' boolean, which determines ownership of return values.
410 
411  PyObject* mp_getcreates( MethodProxy* pymeth, void* )
412  {
413  return PyInt_FromLong( (Bool_t)IsCreator( pymeth->fMethodInfo->fFlags ) );
414  }
415 
416 ////////////////////////////////////////////////////////////////////////////////
417 /// Set '_creates' boolean, which determines ownership of return values.
418 
419  int mp_setcreates( MethodProxy* pymeth, PyObject* value, void* )
420  {
421  if ( ! value ) { // means that _creates is being deleted
422  pymeth->fMethodInfo->fFlags &= ~TCallContext::kIsCreator;
423  return 0;
424  }
425 
426  Long_t iscreator = PyLong_AsLong( value );
427  if ( iscreator == -1 && PyErr_Occurred() ) {
428  PyErr_SetString( PyExc_ValueError, "a boolean 1 or 0 is required for _creates" );
429  return -1;
430  }
431 
432  if ( iscreator )
433  pymeth->fMethodInfo->fFlags |= TCallContext::kIsCreator;
434  else
435  pymeth->fMethodInfo->fFlags &= ~TCallContext::kIsCreator;
436 
437  return 0;
438  }
439 
440 ////////////////////////////////////////////////////////////////////////////////
441 /// Get '_mempolicy' enum, which determines ownership of call arguments.
442 
443  PyObject* mp_getmempolicy( MethodProxy* pymeth, void* )
444  {
445  if ( (Bool_t)(pymeth->fMethodInfo->fFlags & TCallContext::kUseHeuristics ) )
446  return PyInt_FromLong( TCallContext::kUseHeuristics );
447 
448  if ( (Bool_t)(pymeth->fMethodInfo->fFlags & TCallContext::kUseStrict ) )
449  return PyInt_FromLong( TCallContext::kUseStrict );
450 
451  return PyInt_FromLong( -1 );
452  }
453 
454 ////////////////////////////////////////////////////////////////////////////////
455 /// Set '_mempolicy' enum, which determines ownership of call arguments.
456 
457  int mp_setmempolicy( MethodProxy* pymeth, PyObject* value, void* )
458  {
459  Long_t mempolicy = PyLong_AsLong( value );
460  if ( mempolicy == TCallContext::kUseHeuristics ) {
461  pymeth->fMethodInfo->fFlags |= TCallContext::kUseHeuristics;
462  pymeth->fMethodInfo->fFlags &= ~TCallContext::kUseStrict;
463  } else if ( mempolicy == TCallContext::kUseStrict ) {
464  pymeth->fMethodInfo->fFlags |= TCallContext::kUseStrict;
465  pymeth->fMethodInfo->fFlags &= ~TCallContext::kUseHeuristics;
466  } else {
467  PyErr_SetString( PyExc_ValueError,
468  "expected kMemoryStrict or kMemoryHeuristics as value for _mempolicy" );
469  return -1;
470  }
471 
472  return 0;
473  }
474 
475 ////////////////////////////////////////////////////////////////////////////////
476 /// Get '_manage_smart_ptr' boolean, which determines whether or not to
477 /// manage returned smart pointers intelligently.
478 
479  PyObject* mp_get_manage_smart_ptr( MethodProxy* pymeth, void* )
480  {
481  return PyInt_FromLong(
482  (Bool_t)(pymeth->fMethodInfo->fFlags & TCallContext::kManageSmartPtr) );
483  }
484 
485 ////////////////////////////////////////////////////////////////////////////////
486 /// Set '_manage_smart_ptr' boolean, which determines whether or not to
487 /// manage returned smart pointers intelligently.
488 
489  int mp_set_manage_smart_ptr( MethodProxy* pymeth, PyObject* value, void* )
490  {
491  Long_t policy = PyLong_AsLong( value );
492  if ( policy == -1 && PyErr_Occurred() ) {
493  PyErr_SetString( PyExc_ValueError, "a boolean 1 or 0 is required for _manage_smart_ptr" );
494  return -1;
495  }
496 
497  pymeth->fMethodInfo->fFlags |= TCallContext::kManageSmartPtr;
498 
499  return 0;
500  }
501 
502 ////////////////////////////////////////////////////////////////////////////////
503 /// Get '_threaded' boolean, which determines whether the GIL will be released.
504 
505  PyObject* mp_getthreaded( MethodProxy* pymeth, void* )
506  {
507  return PyInt_FromLong(
508  (Bool_t)(pymeth->fMethodInfo->fFlags & TCallContext::kReleaseGIL) );
509  }
510 
511 ////////////////////////////////////////////////////////////////////////////////
512 /// Set '_threaded' boolean, which determines whether the GIL will be released.
513 
514  int mp_setthreaded( MethodProxy* pymeth, PyObject* value, void* )
515  {
516  Long_t isthreaded = PyLong_AsLong( value );
517  if ( isthreaded == -1 && PyErr_Occurred() ) {
518  PyErr_SetString( PyExc_ValueError, "a boolean 1 or 0 is required for _creates" );
519  return -1;
520  }
521 
522  if ( isthreaded )
523  pymeth->fMethodInfo->fFlags |= TCallContext::kReleaseGIL;
524  else
525  pymeth->fMethodInfo->fFlags &= ~TCallContext::kReleaseGIL;
526 
527  return 0;
528  }
529 
530 ////////////////////////////////////////////////////////////////////////////////
531 
532  PyGetSetDef mp_getset[] = {
533  { (char*)"__name__", (getter)mp_name, NULL, NULL, NULL },
534  { (char*)"__module__", (getter)mp_module, NULL, NULL, NULL },
535  { (char*)"__doc__", (getter)mp_doc, NULL, NULL, NULL },
536 
537  // to be more python-like, where these are duplicated as well; to actually
538  // derive from the python method or function type is too memory-expensive,
539  // given that most of the members of those types would not be used
540  { (char*)"im_func", (getter)mp_meth_func, NULL, NULL, NULL },
541  { (char*)"im_self", (getter)mp_meth_self, NULL, NULL, NULL },
542  { (char*)"im_class", (getter)mp_meth_class, NULL, NULL, NULL },
543 
544  { (char*)"func_closure", (getter)mp_func_closure, NULL, NULL, NULL },
545  { (char*)"func_code", (getter)mp_func_code, NULL, NULL, NULL },
546  { (char*)"func_defaults", (getter)mp_func_defaults, NULL, NULL, NULL },
547  { (char*)"func_globals", (getter)mp_func_globals, NULL, NULL, NULL },
548  { (char*)"func_doc", (getter)mp_doc, NULL, NULL, NULL },
549  { (char*)"func_name", (getter)mp_name, NULL, NULL, NULL },
550 
551  { (char*)"_creates", (getter)mp_getcreates, (setter)mp_setcreates,
552  (char*)"For ownership rules of result: if true, objects are python-owned", NULL },
553  { (char*)"_mempolicy", (getter)mp_getmempolicy, (setter)mp_setmempolicy,
554  (char*)"For argument ownership rules: like global, either heuristic or strict", NULL },
555  { (char*)"_manage_smart_ptr", (getter)mp_get_manage_smart_ptr, (setter)mp_set_manage_smart_ptr,
556  (char*)"If a smart pointer is returned, determines management policy.", NULL },
557  { (char*)"_threaded", (getter)mp_getthreaded, (setter)mp_setthreaded,
558  (char*)"If true, releases GIL on call into C++", NULL },
559  { (char*)NULL, NULL, NULL, NULL, NULL }
560  };
561 
562 //= PyROOT method proxy function behavior ====================================
563  PyObject* mp_call( MethodProxy* pymeth, PyObject* args, PyObject* kwds )
564  {
565  // Call the appropriate overload of this method.
566 
567  // if called through im_func pseudo-representation (this can be gamed if the
568  // user really wants to ... )
569  if ( IsPseudoFunc( pymeth ) )
570  pymeth->fSelf = NULL;
571 
572  ObjectProxy* oldSelf = pymeth->fSelf;
573 
574  // get local handles to proxy internals
575  auto& methods = pymeth->fMethodInfo->fMethods;
576  auto& dispatchMap = pymeth->fMethodInfo->fDispatchMap;
577  auto& mflags = pymeth->fMethodInfo->fFlags;
578 
579  Int_t nMethods = methods.size();
580 
581  TCallContext ctxt = { 0 };
582  ctxt.fFlags |= (mflags & TCallContext::kUseHeuristics);
583  ctxt.fFlags |= (mflags & TCallContext::kUseStrict);
584  ctxt.fFlags |= (mflags & TCallContext::kManageSmartPtr);
585  if ( ! ctxt.fFlags ) ctxt.fFlags |= TCallContext::sMemoryPolicy;
586  ctxt.fFlags |= (mflags & TCallContext::kReleaseGIL);
587 
588  // simple case
589  if ( nMethods == 1 ) {
590  PyObject* result = methods[0]->Call( pymeth->fSelf, args, kwds, &ctxt );
591  return HandleReturn( pymeth, oldSelf, result );
592  }
593 
594  // otherwise, handle overloading
595  Long_t sighash = HashSignature( args );
596 
597  // look for known signatures ...
598  MethodProxy::DispatchMap_t::iterator m = dispatchMap.find( sighash );
599  if ( m != dispatchMap.end() ) {
600  Int_t index = m->second;
601  PyObject* result = methods[ index ]->Call( pymeth->fSelf, args, kwds, &ctxt );
602  result = HandleReturn( pymeth, oldSelf, result );
603 
604  if ( result != 0 )
605  return result;
606 
607  // fall through: python is dynamic, and so, the hashing isn't infallible
608  ResetCallState( pymeth->fSelf, oldSelf, kTRUE );
609  }
610 
611  // ... otherwise loop over all methods and find the one that does not fail
612  if ( ! IsSorted( mflags ) ) {
613  std::stable_sort( methods.begin(), methods.end(), PriorityCmp );
614  mflags |= TCallContext::kIsSorted;
615  }
616 
617  std::vector< PyError_t > errors;
618  for ( Int_t i = 0; i < nMethods; ++i ) {
619  PyObject* result = methods[i]->Call( pymeth->fSelf, args, kwds, &ctxt );
620 
621  if ( result != 0 ) {
622  // success: update the dispatch map for subsequent calls
623  dispatchMap[ sighash ] = i;
624  std::for_each( errors.begin(), errors.end(), PyError_t::Clear );
625  return HandleReturn( pymeth, oldSelf, result );
626  }
627 
628  // failure: collect error message/trace (automatically clears exception, too)
629  if ( ! PyErr_Occurred() ) {
630  // this should not happen; set an error to prevent core dump and report
631  PyObject* sig = methods[i]->GetPrototype();
632  PyErr_Format( PyExc_SystemError, "%s =>\n %s",
633  PyROOT_PyUnicode_AsString( sig ), (char*)"NULL result without error in mp_call" );
634  Py_DECREF( sig );
635  }
636  PyError_t e;
637  PyErr_Fetch( &e.fType, &e.fValue, &e.fTrace );
638  errors.push_back( e );
639  ResetCallState( pymeth->fSelf, oldSelf, kFALSE );
640  }
641 
642  // first summarize, then add details
644  "none of the %d overloaded methods succeeded. Full details:", nMethods );
645  PyObject* separator = PyROOT_PyUnicode_FromString( "\n " );
646 
647  // if this point is reached, none of the overloads succeeded: notify user
648  PyObject* exc_type = NULL;
649  for ( std::vector< PyError_t >::iterator e = errors.begin(); e != errors.end(); ++e ) {
650  if ( e->fType != PyExc_NotImplementedError ) {
651  if ( ! exc_type ) exc_type = e->fType;
652  else if ( exc_type != e->fType ) exc_type = PyExc_TypeError;
653  }
654  PyROOT_PyUnicode_Append( &value, separator );
655  PyROOT_PyUnicode_Append( &value, e->fValue );
656  }
657 
658  Py_DECREF( separator );
659  std::for_each( errors.begin(), errors.end(), PyError_t::Clear );
660 
661  // report failure
662  PyErr_SetObject( exc_type ? exc_type : PyExc_TypeError, value );
663  Py_DECREF( value );
664  return 0;
665  }
666 
667 ////////////////////////////////////////////////////////////////////////////////
668 /// Descriptor; create and return a new bound method proxy (language requirement).
669 
670  MethodProxy* mp_descrget( MethodProxy* pymeth, ObjectProxy* pyobj, PyObject* )
671  {
672  MethodProxy* newPyMeth = (MethodProxy*)MethodProxy_Type.tp_alloc( &MethodProxy_Type, 0 );
673 
674  // method info is shared, as it contains the collected overload knowledge
675  *pymeth->fMethodInfo->fRefCount += 1;
676  newPyMeth->fMethodInfo = pymeth->fMethodInfo;
677 
678  // new method is to be bound to current object (may be NULL)
679  Py_XINCREF( (PyObject*)pyobj );
680  newPyMeth->fSelf = pyobj;
681 
682  return newPyMeth;
683  }
684 
685 
686 //= PyROOT method proxy construction/destruction =================================
687  MethodProxy* mp_new( PyTypeObject*, PyObject*, PyObject* )
688  {
689  // Create a new method proxy object.
690  MethodProxy* pymeth = PyObject_GC_New( MethodProxy, &MethodProxy_Type );
691  pymeth->fSelf = NULL;
692  pymeth->fMethodInfo = new MethodProxy::MethodInfo_t;
693 
694  PyObject_GC_Track( pymeth );
695  return pymeth;
696  }
697 
698 ////////////////////////////////////////////////////////////////////////////////
699 /// Deallocate memory held by method proxy object.
700 
701  void mp_dealloc( MethodProxy* pymeth )
702  {
703  PyObject_GC_UnTrack( pymeth );
704 
705  if ( ! IsPseudoFunc( pymeth ) )
706  Py_CLEAR( pymeth->fSelf );
707  pymeth->fSelf = NULL;
708 
709  if ( --(*pymeth->fMethodInfo->fRefCount) <= 0 ) {
710  delete pymeth->fMethodInfo;
711  }
712 
713  PyObject_GC_Del( pymeth );
714  }
715 
716 
717 ////////////////////////////////////////////////////////////////////////////////
718 /// Hash of method proxy object for insertion into dictionaries; with actual
719 /// method (fMethodInfo) shared, its address is best suited.
720 
721  Long_t mp_hash( MethodProxy* pymeth )
722  {
723  return _Py_HashPointer( pymeth->fMethodInfo );
724  }
725 
726 ////////////////////////////////////////////////////////////////////////////////
727 /// Garbage collector traverse of held python member objects.
728 
729  int mp_traverse( MethodProxy* pymeth, visitproc visit, void* args )
730  {
731  if ( pymeth->fSelf && ! IsPseudoFunc( pymeth ) )
732  return visit( (PyObject*)pymeth->fSelf, args );
733 
734  return 0;
735  }
736 
737 ////////////////////////////////////////////////////////////////////////////////
738 /// Garbage collector clear of held python member objects.
739 
740  int mp_clear( MethodProxy* pymeth )
741  {
742  if ( ! IsPseudoFunc( pymeth ) )
743  Py_CLEAR( pymeth->fSelf );
744  pymeth->fSelf = NULL;
745 
746  return 0;
747  }
748 
749 ////////////////////////////////////////////////////////////////////////////////
750 /// Rich set of comparison objects; only equals is defined.
751 
752  PyObject* mp_richcompare( MethodProxy* self, MethodProxy* other, int op )
753  {
754  if ( op != Py_EQ )
755  return PyType_Type.tp_richcompare( (PyObject*)self, (PyObject*)other, op );
756 
757  // defined by type + (shared) MethodInfo + bound self, with special case for fSelf (i.e. pseudo-function)
758  if ( ( Py_TYPE(self) == Py_TYPE(other) && self->fMethodInfo == other->fMethodInfo ) && \
759  ( ( IsPseudoFunc( self ) && IsPseudoFunc( other ) ) || self->fSelf == other->fSelf ) ) {
760  Py_INCREF( Py_True );
761  return Py_True;
762  }
763  Py_INCREF( Py_False );
764  return Py_False;
765  }
766 
767 
768 //= PyROOT method proxy access to internals =================================
769  PyObject* mp_disp( MethodProxy* pymeth, PyObject* sigarg )
770  {
771  // Select and call a specific C++ overload, based on its signature.
772  if ( ! PyROOT_PyUnicode_Check( sigarg ) ) {
773  PyErr_Format( PyExc_TypeError, "disp() argument 1 must be string, not %.50s",
774  sigarg == Py_None ? "None" : Py_TYPE(sigarg)->tp_name );
775  return 0;
776  }
777 
779 
780  MethodProxy::Methods_t& methods = pymeth->fMethodInfo->fMethods;
781  for ( Int_t i = 0; i < (Int_t)methods.size(); ++i ) {
782 
783  PyObject* sig2 = methods[ i ]->GetSignature();
784  if ( PyObject_RichCompareBool( sig1, sig2, Py_EQ ) ) {
785  Py_DECREF( sig2 );
786 
787  MethodProxy* newmeth = mp_new( NULL, NULL, NULL );
788  MethodProxy::Methods_t vec; vec.push_back( methods[ i ]->Clone() );
789  newmeth->Set( pymeth->fMethodInfo->fName, vec );
790 
791  if ( pymeth->fSelf && ! IsPseudoFunc( pymeth ) ) {
792  Py_INCREF( pymeth->fSelf );
793  newmeth->fSelf = pymeth->fSelf;
794  }
795 
796  Py_DECREF( sig1 );
797  return (PyObject*)newmeth;
798  }
799 
800  Py_DECREF( sig2 );
801  }
802 
803  Py_DECREF( sig1 );
804  PyErr_Format( PyExc_LookupError, "signature \"%s\" not found", PyROOT_PyUnicode_AsString( sigarg ) );
805  return 0;
806  }
807 
808 //= PyROOT method proxy access to internals =================================
809  PyObject* mp_add_overload( MethodProxy* pymeth, PyObject* new_overload )
810  {
811  TPythonCallback* cb = new TPythonCallback(new_overload);
812  pymeth->AddMethod( cb );
813  Py_INCREF( Py_None );
814  return Py_None;
815  }
816 
817  PyMethodDef mp_methods[] = {
818  { (char*)"disp", (PyCFunction)mp_disp, METH_O, (char*)"select overload for dispatch" },
819  { (char*)"__add_overload__", (PyCFunction)mp_add_overload, METH_O, (char*)"add a new overload" },
820  { (char*)NULL, NULL, 0, NULL }
821  };
822 
823 } // unnamed namespace
824 
825 ////////////////////////////////////////////////////////////////////////////////
826 
827 
828 //= PyROOT method proxy type =================================================
829 PyTypeObject MethodProxy_Type = {
830  PyVarObject_HEAD_INIT( &PyType_Type, 0 )
831  (char*)"ROOT.MethodProxy", // tp_name
832  sizeof(MethodProxy), // tp_basicsize
833  0, // tp_itemsize
834  (destructor)mp_dealloc, // tp_dealloc
835  0, // tp_print
836  0, // tp_getattr
837  0, // tp_setattr
838  0, // tp_compare
839  0, // tp_repr
840  0, // tp_as_number
841  0, // tp_as_sequence
842  0, // tp_as_mapping
843  (hashfunc)mp_hash, // tp_hash
844  (ternaryfunc)mp_call, // tp_call
845  0, // tp_str
846  0, // tp_getattro
847  0, // tp_setattro
848  0, // tp_as_buffer
849  Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, // tp_flags
850  (char*)"PyROOT method proxy (internal)", // tp_doc
851  (traverseproc)mp_traverse, // tp_traverse
852  (inquiry)mp_clear, // tp_clear
853  (richcmpfunc)mp_richcompare, // tp_richcompare
854  0, // tp_weaklistoffset
855  0, // tp_iter
856  0, // tp_iternext
857  mp_methods, // tp_methods
858  0, // tp_members
859  mp_getset, // tp_getset
860  0, // tp_base
861  0, // tp_dict
862  (descrgetfunc)mp_descrget, // tp_descr_get
863  0, // tp_descr_set
864  0, // tp_dictoffset
865  0, // tp_init
866  0, // tp_alloc
867  (newfunc)mp_new, // tp_new
868  0, // tp_free
869  0, // tp_is_gc
870  0, // tp_bases
871  0, // tp_mro
872  0, // tp_cache
873  0, // tp_subclasses
874  0 // tp_weaklist
875 #if PY_VERSION_HEX >= 0x02030000
876  , 0 // tp_del
877 #endif
878 #if PY_VERSION_HEX >= 0x02060000
879  , 0 // tp_version_tag
880 #endif
881 #if PY_VERSION_HEX >= 0x03040000
882  , 0 // tp_finalize
883 #endif
884 };
885 
886 } // namespace PyROOT
887 
888 
889 //- public members -----------------------------------------------------------
890 void PyROOT::MethodProxy::Set( const std::string& name, std::vector< PyCallable* >& methods )
891 {
892 // Fill in the data of a freshly created method proxy.
893  fMethodInfo->fName = name;
894  fMethodInfo->fMethods.swap( methods );
895  fMethodInfo->fFlags &= ~TCallContext::kIsSorted;
896  fMethodInfo->fFlags |= TCallContext::kManageSmartPtr;
897 
898 // special case: all constructors are considered creators by default
899  if ( name == "__init__" )
900  fMethodInfo->fFlags |= (TCallContext::kIsCreator | TCallContext::kIsConstructor);
901 
902 // special case, in heuristics mode also tag *Clone* methods as creators
904  name.find( "Clone" ) != std::string::npos )
905  fMethodInfo->fFlags |= TCallContext::kIsCreator;
906 }
907 
908 ////////////////////////////////////////////////////////////////////////////////
909 /// Fill in the data of a freshly created method proxy.
910 
912 {
913  fMethodInfo->fMethods.push_back( pc );
914  fMethodInfo->fFlags &= ~TCallContext::kIsSorted;
915 }
916 
917 ////////////////////////////////////////////////////////////////////////////////
918 
920 {
921  fMethodInfo->fMethods.insert( fMethodInfo->fMethods.end(),
922  meth->fMethodInfo->fMethods.begin(), meth->fMethodInfo->fMethods.end() );
923  fMethodInfo->fFlags &= ~TCallContext::kIsSorted;
924 }
925 
926 ////////////////////////////////////////////////////////////////////////////////
927 /// Destructor (this object is reference counted).
928 
930 {
931  for ( Methods_t::iterator it = fMethods.begin(); it != fMethods.end(); ++it ) {
932  delete *it;
933  }
934  fMethods.clear();
935  delete fRefCount;
936 }
#define PyROOT_PyUnicode_FromString
Definition: PyROOT.h:71
#define CO_NOFREE
Definition: MethodProxy.cxx:14
PyObject * fTrace
void Set(const std::string &name, std::vector< PyCallable * > &methods)
std::vector< PyCallable * > Methods_t
Definition: MethodProxy.h:24
int Int_t
Definition: RtypesCore.h:41
bool Bool_t
Definition: RtypesCore.h:59
const Bool_t kFALSE
Definition: Rtypes.h:92
#define PyVarObject_HEAD_INIT(type, size)
Definition: PyROOT.h:147
Bool_t IsSorted(UInt_t flags)
Definition: TCallContext.h:61
#define PyROOT_PyUnicode_FromFormat
Definition: PyROOT.h:70
#define PyROOT_PyUnicode_Append
Definition: PyROOT.h:73
MethodProxy::Methods_t fMethods
Definition: MethodProxy.h:32
#define PyROOT_PyUnicode_AsString
Definition: PyROOT.h:66
Bool_t IsConstructor(UInt_t flags)
Definition: TCallContext.h:69
Bool_t ObjectProxy_Check(T *object)
Definition: ObjectProxy.h:91
R__EXTERN PyObject * gROOTns
Definition: PyStrings.h:55
PyObject * fValue
PyObject * fType
long Long_t
Definition: RtypesCore.h:50
MethodInfo_t * fMethodInfo
Definition: MethodProxy.h:52
#define PyROOT_PyUnicode_AppendAndDel
Definition: PyROOT.h:74
void AddMethod(PyCallable *pc)
Fill in the data of a freshly created method proxy.
R__EXTERN PyObject * gLifeLine
Definition: PyStrings.h:30
unsigned long ULong_t
Definition: RtypesCore.h:51
#define PyROOT_PyUnicode_Check
Definition: PyROOT.h:64
~MethodInfo_t()
Destructor (this object is reference counted).
#define name(a, b)
Definition: linkTestLib0.cpp:5
size_t SizeOf(TCppType_t klass)
Definition: Cppyy.cxx:192
#define Py_TYPE(ob)
Definition: PyROOT.h:149
int Py_ssize_t
Definition: PyROOT.h:154
Bool_t IsCreator(UInt_t flags)
Definition: TCallContext.h:65
PyObject * GetScopeProxy(Cppyy::TCppScope_t)
Retrieve scope proxy from the known ones.
#define NULL
Definition: Rtypes.h:82
void * GetObject() const
double result[121]
const Bool_t kTRUE
Definition: Rtypes.h:91
static ECallFlags sMemoryPolicy
Definition: TCallContext.h:49
_object PyObject
Definition: TPyArg.h:22