3#include "structmember.h"
4#if PY_VERSION_HEX < 0x02050000
6#elif PY_VERSION_HEX < 0x030b0000
11#define CO_NOFREE 0x0040
33#ifndef CPPOverload_MAXFREELIST
34#define CPPOverload_MAXFREELIST 32
39class TPythonCallback :
public PyCallable {
45 if (!PyCallable_Check(callable)) {
46 PyErr_SetString(PyExc_TypeError,
"parameter must be callable");
53 virtual ~TPythonCallback() {
58 virtual PyObject* GetSignature(
bool =
true) {
61 virtual PyObject* GetPrototype(
bool =
true) {
65 if (PyObject_HasAttrString(fCallable,
"__doc__")) {
66 return PyObject_GetAttrString(fCallable,
"__doc__");
68 return GetPrototype();
72 virtual int GetPriority() {
return 100; };
73 virtual bool IsGreedy() {
return false; };
75 virtual int GetMaxArgs() {
return 100; };
79 virtual PyObject* GetArgDefault(
int ) {
91 virtual PyCallable* Clone() {
return new TPythonCallback(*
this); }
99 newArgs = PyTuple_New(nargs+1);
101 PyTuple_SET_ITEM(newArgs, 0, (
PyObject*)self);
102 for (
Py_ssize_t iarg = 0; iarg < nargs; ++iarg) {
103 PyObject* pyarg = PyTuple_GET_ITEM(args, iarg);
105 PyTuple_SET_ITEM(newArgs, iarg+1, pyarg);
111 return PyObject_Call(fCallable, newArgs, kwds);
116static inline bool IsPseudoFunc(CPPOverload* pymeth)
122static int PriorityCmp(PyCallable* left, PyCallable* right)
124 return left->GetPriority() > right->GetPriority();
128static inline void ResetCallState(CPPInstance*& selfnew, CPPInstance* selfold,
bool clear)
130 if (selfnew != selfold) {
140static inline PyObject* HandleReturn(
148 if (
IsCreator(pymeth->fMethodInfo->fFlags)) {
153 pymeth->fSelf->PythonOwns();
158 ((CPPInstance*)
result)->PythonOwns();
168 CPPInstance* cppself = (CPPInstance*)pymeth->fSelf;
169 CPPInstance* cppres = (CPPInstance*)
result;
176 ptrdiff_t
offset = (ptrdiff_t)cppres->GetObject() - (ptrdiff_t)cppself->GetObject();
198 ResetCallState(pymeth->fSelf, oldSelf,
false);
205static PyObject* mp_name(CPPOverload* pymeth,
void*)
211static PyObject* mp_module(CPPOverload* ,
void*)
218static PyObject* mp_doc(CPPOverload* pymeth,
void*)
224 CPPOverload::Methods_t::size_type nMethods = methods.size();
227 PyObject* doc = methods[0]->GetDocString();
235 for (CPPOverload::Methods_t::size_type i = 1; i < nMethods; ++i) {
239 Py_DECREF(separator);
245static PyObject* mp_meth_func(CPPOverload* pymeth,
void*)
251 *pymeth->fMethodInfo->fRefCount += 1;
252 newPyMeth->fMethodInfo = pymeth->fMethodInfo;
262static PyObject* mp_meth_self(CPPOverload* pymeth,
void*)
266 if (IsPseudoFunc(pymeth)) {
267 PyErr_Format(PyExc_AttributeError,
268 "function %s has no attribute \'im_self\'", pymeth->fMethodInfo->fName.c_str());
270 }
else if (pymeth->fSelf != 0) {
271 Py_INCREF((
PyObject*)pymeth->fSelf);
279static PyObject* mp_meth_class(CPPOverload* pymeth,
void*)
283 if (!IsPseudoFunc(pymeth) && pymeth->fMethodInfo->fMethods.size()) {
284 PyObject* pyclass = pymeth->fMethodInfo->fMethods[0]->GetScopeProxy();
286 PyErr_Format(PyExc_AttributeError,
287 "function %s has no attribute \'im_class\'", pymeth->fMethodInfo->fName.c_str());
295static PyObject* mp_func_closure(CPPOverload* ,
void*)
302static PyObject* mp_func_code(CPPOverload* pymeth,
void*)
305#if PY_VERSION_HEX < 0x03000000
310 PyObject* co_varnames = methods.size() == 1 ? methods[0]->GetCoVarNames() :
nullptr;
313 co_varnames = PyTuple_New(1 + 1 );
318 int co_argcount = (
int)PyTuple_Size(co_varnames);
321 PyObject* co_code = PyString_FromStringAndSize(
"d\x00\x00S", 4);
324 PyObject* co_consts = PyTuple_New(0);
325 PyObject* co_names = PyTuple_New(0);
328 PyObject* co_unused = PyTuple_New(0);
331 PyObject* co_filename = PyString_FromString(
"cppyy.py");
334 PyObject* co_name = PyString_FromString(pymeth->GetName().c_str());
339 PyObject* co_lnotab = PyString_FromString(
"\x00\x01\x0c\x01");
357 Py_DECREF(co_lnotab);
359 Py_DECREF(co_unused);
360 Py_DECREF(co_filename);
361 Py_DECREF(co_varnames);
363 Py_DECREF(co_consts);
375static PyObject* mp_func_defaults(CPPOverload* pymeth,
void*)
381 if (methods.size() != 1)
382 return PyTuple_New(0);
384 int maxarg = methods[0]->GetMaxArgs();
386 PyObject* defaults = PyTuple_New(maxarg);
389 for (
int iarg = 0; iarg < maxarg; ++iarg) {
390 PyObject* defvalue = methods[0]->GetArgDefault(iarg);
392 PyTuple_SET_ITEM(defaults, itup++, defvalue);
394 _PyTuple_Resize(&defaults, itup);
400static PyObject* mp_func_globals(CPPOverload* ,
void*)
404 PyObject* pyglobal = PyModule_GetDict(PyImport_AddModule((
char*)
"cppyy"));
405 Py_XINCREF(pyglobal);
414 pymeth->fMethodInfo->fFlags &= ~flag;
418 long istrue = PyLong_AsLong(
value);
419 if (istrue == -1 && PyErr_Occurred()) {
420 PyErr_Format(PyExc_ValueError,
"a boolean 1 or 0 is required for %s",
name);
425 pymeth->fMethodInfo->fFlags |= flag;
427 pymeth->fMethodInfo->fFlags &= ~flag;
433static PyObject* mp_getcreates(CPPOverload* pymeth,
void*)
436 return PyInt_FromLong((
long)
IsCreator(pymeth->fMethodInfo->fFlags));
440static int mp_setcreates(CPPOverload* pymeth,
PyObject*
value,
void*)
447static PyObject* mp_getmempolicy(CPPOverload* pymeth,
void*)
456 return PyInt_FromLong(-1);
460static int mp_setmempolicy(CPPOverload* pymeth,
PyObject*
value,
void*)
463 long mempolicy = PyLong_AsLong(
value);
466 pymeth->fMethodInfo->fFlags &= ~CallContext::kUseStrict;
469 pymeth->fMethodInfo->fFlags &= ~CallContext::kUseHeuristics;
471 PyErr_SetString(PyExc_ValueError,
472 "expected kMemoryStrict or kMemoryHeuristics as value for __mempolicy__");
481#define CPPYY_BOOLEAN_PROPERTY(name, flag, label) \
482static PyObject* mp_get##name(CPPOverload* pymeth, void*) { \
483 if (pymeth->fMethodInfo->fFlags & flag) { \
489static int mp_set##name(CPPOverload* pymeth, PyObject* value, void*) { \
490 return set_flag(pymeth, value, flag, label); \
499static PyGetSetDef mp_getset[] = {
500 {(
char*)
"__name__", (getter)mp_name,
nullptr,
nullptr,
nullptr},
501 {(
char*)
"__module__", (getter)mp_module,
nullptr,
nullptr,
nullptr},
502 {(
char*)
"__doc__", (getter)mp_doc,
nullptr,
nullptr,
nullptr},
507 {(
char*)
"im_func", (getter)mp_meth_func,
nullptr,
nullptr,
nullptr},
508 {(
char*)
"im_self", (getter)mp_meth_self,
nullptr,
nullptr,
nullptr},
509 {(
char*)
"im_class", (getter)mp_meth_class,
nullptr,
nullptr,
nullptr},
511 {(
char*)
"func_closure", (getter)mp_func_closure,
nullptr,
nullptr,
nullptr},
512 {(
char*)
"func_code", (getter)mp_func_code,
nullptr,
nullptr,
nullptr},
513 {(
char*)
"func_defaults", (getter)mp_func_defaults,
nullptr,
nullptr,
nullptr},
514 {(
char*)
"func_globals", (getter)mp_func_globals,
nullptr,
nullptr,
nullptr},
515 {(
char*)
"func_doc", (getter)mp_doc,
nullptr,
nullptr,
nullptr},
516 {(
char*)
"func_name", (getter)mp_name,
nullptr,
nullptr,
nullptr},
518 {(
char*)
"__creates__", (getter)mp_getcreates, (setter)mp_setcreates,
519 (
char*)
"For ownership rules of result: if true, objects are python-owned",
nullptr},
520 {(
char*)
"__mempolicy__", (getter)mp_getmempolicy, (setter)mp_setmempolicy,
521 (
char*)
"For argument ownership rules: like global, either heuristic or strict",
nullptr},
522 {(
char*)
"__set_lifeline__", (getter)mp_getlifeline, (setter)mp_setlifeline,
523 (
char*)
"If true, set a lifeline from the return value onto self",
nullptr},
524 {(
char*)
"__release_gil__", (getter)mp_getthreaded, (setter)mp_setthreaded,
525 (
char*)
"If true, releases GIL on call into C++",
nullptr},
526 {(
char*)
"__useffi__", (getter)mp_getuseffi, (setter)mp_setuseffi,
527 (
char*)
"not implemented",
nullptr},
528 {(
char*)
"__sig2exc__", (getter)mp_getsig2exc, (setter)mp_setsig2exc,
529 (
char*)
"If true, turn signals into Python exceptions",
nullptr},
530 {(
char*)
nullptr,
nullptr,
nullptr,
nullptr,
nullptr}
538 CPPInstance* oldSelf = pymeth->fSelf;
541 auto& methods = pymeth->fMethodInfo->fMethods;
543 CPPOverload::Methods_t::size_type nMethods = methods.size();
546 const auto mflags = pymeth->fMethodInfo->fFlags;
552 ctxt.fPyContext = (
PyObject*)pymeth->fSelf;
555 if (kwds && PyDict_CheckExact(kwds) && PyDict_Size(kwds) != 0) {
558 if (!PyDict_Size(kwds)) kwds =
nullptr;
566 PyObject*
result = methods[0]->Call(pymeth->fSelf, args, kwds, &ctxt);
567 return HandleReturn(pymeth, oldSelf,
result);
574 auto& dispatchMap = pymeth->fMethodInfo->fDispatchMap;
575 PyCallable* memoized_pc =
nullptr;
576 for (
const auto&
p : dispatchMap) {
577 if (
p.first == sighash) {
578 memoized_pc =
p.second;
583 PyObject*
result = memoized_pc->Call(pymeth->fSelf, args, kwds, &ctxt);
595 std::stable_sort(methods.begin(), methods.end(), PriorityCmp);
599 std::vector<Utility::PyError_t> errors;
600 std::vector<bool> implicit_possible(methods.size());
601 for (
int stage = 0; stage < 2; ++stage) {
602 bool bHaveImplicit =
false;
603 for (CPPOverload::Methods_t::size_type i = 0; i < nMethods; ++i) {
604 if (stage && !implicit_possible[i])
607 PyObject*
result = methods[i]->Call(pymeth->fSelf, args, kwds, &ctxt);
611 dispatchMap.push_back(std::make_pair(sighash, methods[i]));
615 for (
auto&
p : dispatchMap) {
616 if (
p.first == sighash) {
617 p.second = methods[i];
626 return HandleReturn(pymeth, oldSelf,
result);
636 if (!PyErr_Occurred()) {
638 PyObject* sig = methods[i]->GetPrototype();
639 PyErr_Format(PyExc_SystemError,
"%s =>\n %s",
646 bHaveImplicit =
true;
647 implicit_possible[i] =
true;
648 ctxt.fFlags &= ~CallContext::kHaveImplicit;
650 implicit_possible[i] =
false;
651 ResetCallState(pymeth->fSelf, oldSelf,
false);
663 "none of the %d overloaded methods succeeded. Full details:", (
int)nMethods);
671static PyObject* mp_str(CPPOverload* cppinst)
674 std::ostringstream s;
675 s <<
"<C++ overload \"" << cppinst->fMethodInfo->fName <<
"\" at " << (
void*)cppinst <<
">";
680static CPPOverload* mp_descrget(CPPOverload* pymeth, CPPInstance* pyobj,
PyObject*)
690 if (newPyMeth != NULL) {
691 free_list = (CPPOverload*)(newPyMeth->fSelf);
702 *pymeth->fMethodInfo->fRefCount += 1;
703 newPyMeth->fMethodInfo = pymeth->fMethodInfo;
707 newPyMeth->fSelf = pyobj;
709 PyObject_GC_Track(newPyMeth);
719 pymeth->fSelf =
nullptr;
720 pymeth->fMethodInfo =
new CPPOverload::MethodInfo_t;
722 PyObject_GC_Track(pymeth);
727static void mp_dealloc(CPPOverload* pymeth)
730 PyObject_GC_UnTrack(pymeth);
732 Py_CLEAR(pymeth->fSelf);
734 if (--(*pymeth->fMethodInfo->fRefCount) <= 0) {
735 delete pymeth->fMethodInfo;
744 PyObject_GC_Del(pymeth);
753 return _Py_HashPointer(pymeth->fMethodInfo);
757static int mp_traverse(CPPOverload* pymeth, visitproc visit,
void* args)
761 return visit((
PyObject*)pymeth->fSelf, args);
767static int mp_clear(CPPOverload* pymeth)
770 Py_CLEAR(pymeth->fSelf);
776static PyObject* mp_richcompare(CPPOverload* self, CPPOverload* other,
int op)
784 if ((
Py_TYPE(self) ==
Py_TYPE(other) && self->fMethodInfo == other->fMethodInfo) && \
785 ((IsPseudoFunc(self) && IsPseudoFunc(other)) || self->fSelf == other->fSelf)) {
797 PyErr_Format(PyExc_TypeError,
"__overload__() argument 1 must be string, not %.50s",
798 sigarg == Py_None ?
"None" :
Py_TYPE(sigarg)->tp_name);
803 sig1.erase(std::remove(sig1.begin(), sig1.end(),
' '), std::end(sig1));
806 for (
auto& meth : methods) {
810 PyObject* pysig2 = meth->GetSignature(
false);
812 sig2.erase(std::remove(sig2.begin(), sig2.end(),
' '), std::end(sig2));
814 if (sig1 == sig2) found =
true;
817 pysig2 = meth->GetSignature(
true);
819 sig3.erase(std::remove(sig3.begin(), sig3.end(),
' '), std::end(sig3));
821 if (sig1 == sig3) found =
true;
825 CPPOverload* newmeth = mp_new(
nullptr,
nullptr,
nullptr);
827 newmeth->Set(pymeth->fMethodInfo->fName,
vec);
830 Py_INCREF(pymeth->fSelf);
831 newmeth->fSelf = pymeth->fSelf;
833 newmeth->fMethodInfo->fFlags = pymeth->fMethodInfo->fFlags;
839 PyErr_Format(PyExc_LookupError,
845static PyObject* mp_add_overload(CPPOverload* pymeth,
PyObject* new_overload)
847 TPythonCallback* cb =
new TPythonCallback(new_overload);
848 pymeth->AdoptMethod(cb);
852static PyMethodDef mp_methods[] = {
853 {(
char*)
"__overload__", (PyCFunction)mp_overload, METH_O,
854 (
char*)
"select overload for dispatch" },
855 {(
char*)
"__add_overload__", (PyCFunction)mp_add_overload, METH_O,
856 (
char*)
"add a new overload" },
857 {(
char*)
nullptr,
nullptr, 0,
nullptr }
866 (
char*)
"cppyy.CPPOverload",
869 (destructor)mp_dealloc,
879 (ternaryfunc)mp_call,
884 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
885 (
char*)
"cppyy method proxy (internal)",
886 (traverseproc)mp_traverse,
888 (richcmpfunc)mp_richcompare,
897 (descrgetfunc)mp_descrget,
910#if PY_VERSION_HEX >= 0x02030000
913#if PY_VERSION_HEX >= 0x02060000
916#if PY_VERSION_HEX >= 0x03040000
933 if (
name ==
"__init__")
938 name.find(
"Clone") != std::string::npos)
946 fMethodInfo->fMethods.push_back(pc);
955 fMethodInfo->fMethods.insert(fMethodInfo->fMethods.end(),
966 for (Methods_t::iterator it = fMethods.begin(); it != fMethods.end(); ++it) {
#define CPPOverload_MAXFREELIST
#define CPPYY_BOOLEAN_PROPERTY(name, flag, label)
#define CPyCppyy_PyText_Append
#define CPyCppyy_PyText_AsString
#define CPyCppyy_PyText_AppendAndDel
#define CPyCppyy_PyText_FromFormat
#define CPyCppyy_PyText_FromString
#define CPyCppyy_PyText_Check
#define PyVarObject_HEAD_INIT(type, size)
winID h TVirtualViewer3D TVirtualGLPainter p
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h offset
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t result
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void value
void MergeOverload(CPPOverload *meth)
void AdoptMethod(PyCallable *pc)
MethodInfo_t * fMethodInfo
std::vector< PyCallable * > Methods_t
void Set(const std::string &name, std::vector< PyCallable * > &methods)
size_t FetchError(std::vector< PyError_t > &)
void SetDetailedException(std::vector< PyError_t > &errors, PyObject *topmsg, PyObject *defexc)
Set of helper functions that are invoked from the pythonizors, on the Python side.
bool HaveImplicit(CallContext *ctxt)
PyObject * GetScopeProxy(Cppyy::TCppScope_t)
static PyMethodObject * free_list
bool NoImplicit(CallContext *ctxt)
bool IsCreator(uint64_t flags)
bool CPPInstance_Check(T *object)
PyTypeObject CPPOverload_Type
uint64_t HashSignature(PyObject *args)
bool IsConstructor(uint64_t flags)
bool IsSorted(uint64_t flags)
RPY_EXPORTED size_t SizeOf(TCppType_t klass)
RPY_EXPORTED TCppFuncAddr_t GetFunctionAddress(TCppMethod_t method, bool check_enabled=true)
void(off) SmallVectorTemplateBase< T
CPPOverload::DispatchMap_t fDispatchMap
CPPOverload::Methods_t fMethods
static ECallFlags sMemoryPolicy
static void Clear(PyError_t &e)