6 #include "structmember.h"
7 #if PY_VERSION_HEX >= 0x02050000
14 #define CO_NOFREE 0x0040
30 class TPythonCallback :
public PyCallable {
34 TPythonCallback(
PyObject* callable ) {
35 if ( !PyCallable_Check( callable ) ) {
36 PyErr_SetString(PyExc_TypeError,
"parameter must be callable");
40 Py_INCREF( fCallable );
43 virtual ~TPythonCallback() {
44 Py_DECREF( fCallable );
51 if ( PyObject_HasAttrString( fCallable,
"__doc__" )) {
52 return PyObject_GetAttrString( fCallable,
"__doc__" );
54 return GetPrototype();
58 virtual Int_t GetPriority() {
return 100; };
60 virtual Int_t GetMaxArgs() {
return 100; };
75 virtual PyCallable* Clone() {
return new TPythonCallback( *
this ); }
83 newArgs = PyTuple_New( nargs+1 );
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 );
89 PyTuple_SET_ITEM( newArgs, iarg+1, pyarg );
95 return PyObject_Call( fCallable, newArgs, kwds );
102 Bool_t inline IsPseudoFunc( MethodProxy* pymeth )
104 return (
void*)pymeth == (
void*)pymeth->fSelf;
111 static void Clear( PyError_t& e )
114 Py_XDECREF( e.fType ); Py_XDECREF( e.fValue ); Py_XDECREF( e.fTrace );
115 e.fType = e.fValue = e.fTrace = 0;
127 Int_t nargs = PyTuple_GET_SIZE( args );
128 for (
Int_t i = 0; i < nargs; ++i ) {
130 hash += (hash << 10); hash ^= (hash >> 6);
133 hash += (hash << 3); hash ^= (hash >> 11); hash += (hash << 15);
139 int PriorityCmp( PyCallable* left, PyCallable* right )
141 return left->GetPriority() > right->GetPriority();
145 inline PyObject* HandleReturn( MethodProxy* pymeth, ObjectProxy* oldSelf,
PyObject* result ) {
151 if (
IsCreator( pymeth->fMethodInfo->fFlags ) ) {
156 pymeth->fSelf->HoldOn();
161 ((ObjectProxy*)result)->HoldOn();
177 if ( pymeth->fSelf != oldSelf ) {
178 Py_XDECREF( pymeth->fSelf );
179 pymeth->fSelf = oldSelf;
187 PyObject* mp_name( MethodProxy* pymeth,
void* )
194 PyObject* mp_module( MethodProxy* ,
void* )
203 PyObject* mp_doc( MethodProxy* pymeth,
void* )
208 Int_t nMethods = methods.size();
209 PyObject* doc = methods[0]->GetDocString();
217 for (
Int_t i = 1; i < nMethods; ++i ) {
221 Py_DECREF( separator );
229 PyObject* mp_meth_func( MethodProxy* pymeth,
void* )
231 MethodProxy* newPyMeth = (MethodProxy*)MethodProxy_Type.tp_alloc( &MethodProxy_Type, 0 );
234 *pymeth->fMethodInfo->fRefCount += 1;
235 newPyMeth->fMethodInfo = pymeth->fMethodInfo;
239 newPyMeth->fSelf = (ObjectProxy*)newPyMeth;
248 PyObject* mp_meth_self( MethodProxy* pymeth,
void* )
250 if ( IsPseudoFunc( pymeth ) ) {
251 PyErr_Format( PyExc_AttributeError,
252 "function %s has no attribute \'im_self\'", pymeth->fMethodInfo->fName.c_str() );
254 }
else if ( pymeth->fSelf != 0 ) {
255 Py_INCREF( (
PyObject*)pymeth->fSelf );
259 Py_INCREF( Py_None );
267 PyObject* mp_meth_class( MethodProxy* pymeth,
void* )
269 if ( ! IsPseudoFunc( pymeth ) ) {
270 PyObject* pyclass = pymeth->fMethodInfo->fMethods[0]->GetScopeProxy();
272 PyErr_Format( PyExc_AttributeError,
273 "function %s has no attribute \'im_class\'", pymeth->fMethodInfo->fName.c_str() );
277 Py_INCREF( Py_None );
284 PyObject* mp_func_closure( MethodProxy* ,
void* )
286 Py_INCREF( Py_None );
293 PyObject* mp_func_code( MethodProxy* pymeth,
void* )
295 #if PY_VERSION_HEX < 0x03000000
300 PyObject* co_varnames = methods.size() == 1 ? methods[0]->GetCoVarNames() :
NULL;
301 if ( !co_varnames ) {
303 co_varnames = PyTuple_New( 1 + 1 );
308 int co_argcount = PyTuple_Size( co_varnames );
311 PyObject* co_code = PyString_FromStringAndSize(
"d\x00\x00S", 4 );
314 PyObject* co_consts = PyTuple_New( 0 );
315 PyObject* co_names = PyTuple_New( 0 );
318 PyObject* co_unused = PyTuple_New( 0 );
321 PyObject* co_filename = PyString_FromString(
"ROOT.py" );
324 PyObject* co_name = PyString_FromString( pymeth->GetName().c_str() );
329 PyObject* co_lnotab = PyString_FromString(
"\x00\x01\x0c\x01" );
347 Py_DECREF( co_lnotab );
348 Py_DECREF( co_name );
349 Py_DECREF( co_unused );
350 Py_DECREF( co_filename );
351 Py_DECREF( co_varnames );
352 Py_DECREF( co_names );
353 Py_DECREF( co_consts );
354 Py_DECREF( co_code );
360 if ( pymeth || !pymeth) Py_INCREF( Py_None );
369 PyObject* mp_func_defaults( MethodProxy* pymeth,
void* )
373 if ( methods.size() != 1 )
374 return PyTuple_New( 0 );
376 int maxarg = methods[0]->GetMaxArgs();
378 PyObject* defaults = PyTuple_New( maxarg );
381 for (
int iarg = 0; iarg < maxarg; ++iarg ) {
382 PyObject* defvalue = methods[0]->GetArgDefault( iarg );
384 PyTuple_SET_ITEM( defaults, itup++, defvalue );
386 _PyTuple_Resize( &defaults, itup );
395 PyObject* mp_func_globals( MethodProxy* ,
void* )
397 PyObject* pyglobal = PyModule_GetDict( PyImport_AddModule( (
char*)
"ROOT" ) );
398 Py_XINCREF( pyglobal );
405 PyObject* mp_getcreates( MethodProxy* pymeth,
void* )
407 return PyInt_FromLong( (
Bool_t)
IsCreator( pymeth->fMethodInfo->fFlags ) );
413 int mp_setcreates( MethodProxy* pymeth,
PyObject* value,
void* )
416 pymeth->fMethodInfo->fFlags &= ~TCallContext::kIsCreator;
420 Long_t iscreator = PyLong_AsLong( value );
421 if ( iscreator == -1 && PyErr_Occurred() ) {
422 PyErr_SetString( PyExc_ValueError,
"a boolean 1 or 0 is required for _creates" );
429 pymeth->fMethodInfo->fFlags &= ~TCallContext::kIsCreator;
437 PyObject* mp_getmempolicy( MethodProxy* pymeth,
void* )
445 return PyInt_FromLong( -1 );
451 int mp_setmempolicy( MethodProxy* pymeth,
PyObject* value,
void* )
453 Long_t mempolicy = PyLong_AsLong( value );
456 pymeth->fMethodInfo->fFlags &= ~TCallContext::kUseStrict;
459 pymeth->fMethodInfo->fFlags &= ~TCallContext::kUseHeuristics;
461 PyErr_SetString( PyExc_ValueError,
462 "expected kMemoryStrict or kMemoryHeuristics as value for _mempolicy" );
473 PyObject* mp_get_manage_smart_ptr( MethodProxy* pymeth,
void* )
475 return PyInt_FromLong(
483 int mp_set_manage_smart_ptr( MethodProxy* pymeth,
PyObject* value,
void* )
485 Long_t policy = PyLong_AsLong( value );
486 if ( policy == -1 && PyErr_Occurred() ) {
487 PyErr_SetString( PyExc_ValueError,
"a boolean 1 or 0 is required for _manage_smart_ptr" );
499 PyObject* mp_getthreaded( MethodProxy* pymeth,
void* )
501 return PyInt_FromLong(
508 int mp_setthreaded( MethodProxy* pymeth,
PyObject* value,
void* )
510 Long_t isthreaded = PyLong_AsLong( value );
511 if ( isthreaded == -1 && PyErr_Occurred() ) {
512 PyErr_SetString( PyExc_ValueError,
"a boolean 1 or 0 is required for _creates" );
519 pymeth->fMethodInfo->fFlags &= ~TCallContext::kReleaseGIL;
526 PyGetSetDef mp_getset[] = {
538 { (
char*)
"func_closure", (
getter)mp_func_closure,
NULL,
NULL, NULL },
540 { (
char*)
"func_defaults", (
getter)mp_func_defaults,
NULL,
NULL, NULL },
541 { (
char*)
"func_globals", (
getter)mp_func_globals,
NULL,
NULL, NULL },
545 { (
char*)
"_creates", (
getter)mp_getcreates, (
setter)mp_setcreates,
546 (
char*)
"For ownership rules of result: if true, objects are python-owned",
NULL },
547 { (
char*)
"_mempolicy", (
getter)mp_getmempolicy, (
setter)mp_setmempolicy,
548 (
char*)
"For argument ownership rules: like global, either heuristic or strict",
NULL },
549 { (
char*)
"_manage_smart_ptr", (
getter)mp_get_manage_smart_ptr, (
setter)mp_set_manage_smart_ptr,
550 (
char*)
"If a smart pointer is returned, determines management policy.",
NULL },
551 { (
char*)
"_threaded", (
getter)mp_getthreaded, (
setter)mp_setthreaded,
552 (
char*)
"If true, releases GIL on call into C++",
NULL },
563 if ( IsPseudoFunc( pymeth ) )
564 pymeth->fSelf =
NULL;
566 ObjectProxy* oldSelf = pymeth->fSelf;
569 auto& methods = pymeth->fMethodInfo->fMethods;
570 auto& dispatchMap = pymeth->fMethodInfo->fDispatchMap;
571 auto& mflags = pymeth->fMethodInfo->fFlags;
573 Int_t nMethods = methods.size();
575 TCallContext ctxt = { 0 };
583 if ( nMethods == 1 ) {
584 PyObject* result = methods[0]->Call( pymeth->fSelf, args, kwds, &ctxt );
585 return HandleReturn( pymeth, oldSelf, result );
589 Long_t sighash = HashSignature( args );
592 MethodProxy::DispatchMap_t::iterator m = dispatchMap.find( sighash );
593 if ( m != dispatchMap.end() ) {
594 Int_t index = m->second;
595 PyObject* result = methods[ index ]->Call( pymeth->fSelf, args, kwds, &ctxt );
596 result = HandleReturn( pymeth, oldSelf, result );
607 std::stable_sort( methods.begin(), methods.end(), PriorityCmp );
611 std::vector< PyError_t >
errors;
612 for (
Int_t i = 0; i < nMethods; ++i ) {
613 PyObject* result = methods[i]->Call( pymeth->fSelf, args, kwds, &ctxt );
616 std::for_each( errors.begin(), errors.end(), PyError_t::Clear );
621 std::for_each( errors.begin(), errors.end(), PyError_t::Clear );
627 dispatchMap[ sighash ] = i;
628 std::for_each( errors.begin(), errors.end(), PyError_t::Clear );
629 return HandleReturn( pymeth, oldSelf, result );
633 if ( ! PyErr_Occurred() ) {
635 PyObject* sig = methods[i]->GetPrototype();
636 PyErr_Format( PyExc_SystemError,
"%s =>\n %s",
641 PyErr_Fetch( &e.fType, &e.fValue, &e.fTrace );
642 errors.push_back( e );
647 "none of the %d overloaded methods succeeded. Full details:", nMethods );
652 for ( std::vector< PyError_t >::iterator e = errors.begin(); e != errors.end(); ++e ) {
653 if ( e->fType != PyExc_NotImplementedError ) {
654 if ( ! exc_type ) exc_type = e->fType;
655 else if ( exc_type != e->fType ) exc_type = PyExc_TypeError;
661 Py_DECREF( separator );
662 std::for_each( errors.begin(), errors.end(), PyError_t::Clear );
665 PyErr_SetObject( exc_type ? exc_type : PyExc_TypeError, value );
673 MethodProxy* mp_descrget( MethodProxy* pymeth, ObjectProxy* pyobj,
PyObject* )
675 MethodProxy* newPyMeth = (MethodProxy*)MethodProxy_Type.tp_alloc( &MethodProxy_Type, 0 );
678 *pymeth->fMethodInfo->fRefCount += 1;
679 newPyMeth->fMethodInfo = pymeth->fMethodInfo;
683 newPyMeth->fSelf = pyobj;
693 MethodProxy* pymeth = PyObject_GC_New( MethodProxy, &MethodProxy_Type );
694 pymeth->fSelf =
NULL;
695 pymeth->fMethodInfo =
new MethodProxy::MethodInfo_t;
697 PyObject_GC_Track( pymeth );
704 void mp_dealloc( MethodProxy* pymeth )
706 PyObject_GC_UnTrack( pymeth );
708 if ( ! IsPseudoFunc( pymeth ) )
709 Py_CLEAR( pymeth->fSelf );
710 pymeth->fSelf =
NULL;
712 if ( --(*pymeth->fMethodInfo->fRefCount) <= 0 ) {
713 delete pymeth->fMethodInfo;
716 PyObject_GC_Del( pymeth );
724 Long_t mp_hash( MethodProxy* pymeth )
726 return _Py_HashPointer( pymeth->fMethodInfo );
732 int mp_traverse( MethodProxy* pymeth, visitproc visit,
void* args )
734 if ( pymeth->fSelf && ! IsPseudoFunc( pymeth ) )
735 return visit( (
PyObject*)pymeth->fSelf, args );
743 int mp_clear( MethodProxy* pymeth )
745 if ( ! IsPseudoFunc( pymeth ) )
746 Py_CLEAR( pymeth->fSelf );
747 pymeth->fSelf =
NULL;
755 PyObject* mp_richcompare( MethodProxy*
self, MethodProxy* other,
int op )
761 if ( (
Py_TYPE(
self) ==
Py_TYPE(other) && self->fMethodInfo == other->fMethodInfo ) && \
762 ( ( IsPseudoFunc(
self ) && IsPseudoFunc( other ) ) || self->fSelf == other->fSelf ) ) {
763 Py_INCREF( Py_True );
766 Py_INCREF( Py_False );
776 PyErr_Format( PyExc_TypeError,
"disp() argument 1 must be string, not %.50s",
777 sigarg == Py_None ?
"None" :
Py_TYPE(sigarg)->tp_name );
784 for (
Int_t i = 0; i < (
Int_t)methods.size(); ++i ) {
786 PyObject* sig2 = methods[ i ]->GetSignature();
787 if ( PyObject_RichCompareBool( sig1, sig2, Py_EQ ) ) {
792 newmeth->Set( pymeth->fMethodInfo->fName, vec );
794 if ( pymeth->fSelf && ! IsPseudoFunc( pymeth ) ) {
795 Py_INCREF( pymeth->fSelf );
796 newmeth->fSelf = pymeth->fSelf;
814 TPythonCallback* cb =
new TPythonCallback(new_overload);
815 pymeth->AddMethod( cb );
816 Py_INCREF( Py_None );
820 PyMethodDef mp_methods[] = {
821 { (
char*)
"disp", (PyCFunction)mp_disp, METH_O, (
char*)
"select overload for dispatch" },
822 { (
char*)
"__add_overload__", (PyCFunction)mp_add_overload, METH_O, (
char*)
"add a new overload" },
832 PyTypeObject MethodProxy_Type = {
834 (
char*)
"ROOT.MethodProxy",
837 (destructor)mp_dealloc,
847 (ternaryfunc)mp_call,
852 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
853 (
char*)
"PyROOT method proxy (internal)",
854 (traverseproc)mp_traverse,
856 (richcmpfunc)mp_richcompare,
865 (descrgetfunc)mp_descrget,
878 #
if PY_VERSION_HEX >= 0x02030000
881 #
if PY_VERSION_HEX >= 0x02060000
884 #
if PY_VERSION_HEX >= 0x03040000
896 fMethodInfo->fName =
name;
897 fMethodInfo->fMethods.swap( methods );
902 if ( name ==
"__init__" )
907 name.find(
"Clone" ) != std::string::npos )
916 fMethodInfo->fMethods.push_back( pc );
924 fMethodInfo->fMethods.insert( fMethodInfo->fMethods.end(),
934 for ( Methods_t::iterator it = fMethods.begin(); it != fMethods.end(); ++it ) {
#define PyROOT_PyUnicode_FromString
void Set(const std::string &name, std::vector< PyCallable * > &methods)
std::vector< PyCallable * > Methods_t
#define PyVarObject_HEAD_INIT(type, size)
Bool_t IsSorted(UInt_t flags)
#define PyROOT_PyUnicode_FromFormat
R__EXTERN void * TPyExceptionMagic
#define PyROOT_PyUnicode_Append
MethodProxy::Methods_t fMethods
#define PyROOT_PyUnicode_AsString
Bool_t IsConstructor(UInt_t flags)
Bool_t ObjectProxy_Check(T *object)
R__EXTERN PyObject * gROOTns
MethodInfo_t * fMethodInfo
#define PyROOT_PyUnicode_AppendAndDel
void AddMethod(PyCallable *pc)
Fill in the data of a freshly created method proxy.
R__EXTERN PyObject * gLifeLine
#define PyROOT_PyUnicode_Check
~MethodInfo_t()
Destructor (this object is reference counted).
size_t SizeOf(TCppType_t klass)
Bool_t IsCreator(UInt_t flags)
PyObject * GetScopeProxy(Cppyy::TCppScope_t)
Retrieve scope proxy from the known ones.
R__EXTERN void * TPyCPPExceptionMagic
std::vector< double > errors
static ECallFlags sMemoryPolicy