static PyObject * function_call(PyObject *func, PyObject *arg, PyObject *kw) { PyObject *result; PyObject *argdefs; PyObject *kwtuple = NULL; PyObject **d, **k; Py_ssize_t nk, nd; argdefs = PyFunction_GET_DEFAULTS(func); if (argdefs != NULL && PyTuple_Check(argdefs)) { d = &PyTuple_GET_ITEM((PyTupleObject *)argdefs, 0); nd = PyTuple_GET_SIZE(argdefs); } else { d = NULL; nd = 0; } if (kw != NULL && PyDict_Check(kw)) { Py_ssize_t pos, i; nk = PyDict_GET_SIZE(kw); kwtuple = PyTuple_New(2*nk); if (kwtuple == NULL) return NULL; k = &PyTuple_GET_ITEM(kwtuple, 0); pos = i = 0; while (PyDict_Next(kw, &pos, &k[i], &k[i+1])) { Py_INCREF(k[i]); Py_INCREF(k[i+1]); i += 2; } nk = i/2; } else { k = NULL; nk = 0; } result = PyEval_EvalCodeEx( PyFunction_GET_CODE(func), PyFunction_GET_GLOBALS(func), (PyObject *)NULL, &PyTuple_GET_ITEM(arg, 0), PyTuple_GET_SIZE(arg), k, nk, d, nd, PyFunction_GET_KW_DEFAULTS(func), PyFunction_GET_CLOSURE(func)); Py_XDECREF(kwtuple); return result; }
/* could be moved into bpy_utils */ static void printf_func_error(PyObject *py_func) { /* since we return to C code we can't leave the error */ PyCodeObject *f_code= (PyCodeObject *)PyFunction_GET_CODE(py_func); PyErr_Print(); PyErr_Clear(); /* use py style error */ fprintf(stderr, "File \"%s\", line %d, in %s\n", _PyUnicode_AsString(f_code->co_filename), f_code->co_firstlineno, _PyUnicode_AsString(((PyFunctionObject *)py_func)->func_name) ); }
void CPyScriptAutoConfigDlg::OnCbnSelchangeCbFuncName() { m_ctlAddlParams.SetWindowText(_T("")); if( m_pDictionary == 0 ) if( !InitPython() ) return; SetModified(); // in any case, this changes things, so enable the Apply button int nIndex = m_cbFunctionNames.GetCurSel(); if( nIndex < 0 ) m_cbFunctionNames.GetWindowText(m_strFuncName); else m_cbFunctionNames.GetLBText(nIndex,m_strFuncName); if( !m_strFuncName.IsEmpty() ) { PyObject* pFunc = PyDict_GetItemString(m_pDictionary, CT2A(m_strFuncName)); if( MyPyFunction_Check(pFunc) ) { PyCodeObject* pCode = (PyCodeObject*)PyFunction_GET_CODE(pFunc); CStringArray astrArgs; EnumerateTuple(pCode->co_varnames, astrArgs, pCode->co_argcount); CString strFuncPrototype; strFuncPrototype.Format(_T(" def %s(%s):"), m_strFuncName, ToString(astrArgs)); m_ctlFuncPrototype.SetWindowText(strFuncPrototype); // if the argument count is greater than 1, then allow additional parameters BOOL bAddlParams = pCode->co_argcount > 1; m_ctlAddlParams.EnableWindow(bAddlParams); if( bAddlParams ) { CString strPrototypeParams; int nExtraArgs = (int)astrArgs.GetCount() - 1; for(int i = 0; i < nExtraArgs; i++) { CString strFormat; strFormat.Format(_T("<%s>;"), astrArgs[i]); strPrototypeParams += strFormat; } m_ctlAddlParams.SetWindowText(strPrototypeParams.Left(strPrototypeParams.GetLength() - 1)); } return; } } m_ctlAddlParams.EnableWindow(); // just in case, we can't access the file for whatever reasons m_ctlFuncPrototype.SetWindowText(_T("")); }
static PyObject * fast_function(PyObject *func, PyObject ***pp_stack, int n, int na, int nk) { PyCodeObject *co = (PyCodeObject *)PyFunction_GET_CODE(func); PyObject *globals = PyFunction_GET_GLOBALS(func); PyObject *argdefs = PyFunction_GET_DEFAULTS(func); PyObject **d = NULL; int nd = 0; if (argdefs == NULL && co->co_argcount == n && nk==0 && co->co_flags == (CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE)) { PyFrameObject *f; PyObject *retval = NULL; PyThreadState *tstate = PyThreadState_GET(); PyObject **fastlocals, **stack; int i; /* XXX Perhaps we should create a specialized PyFrame_New() that doesn't take locals, but does take builtins without sanity checking them. */ f = PyFrame_New(tstate, co, globals, NULL); if (f == NULL) return NULL; fastlocals = f->f_localsplus; stack = (*pp_stack) - n; for (i = 0; i < n; i++) { Py_INCREF(*stack); fastlocals[i] = *stack++; } retval = eval_frame(f); ++tstate->recursion_depth; Py_DECREF(f); --tstate->recursion_depth; return retval; } if (argdefs != NULL) { d = &PyTuple_GET_ITEM(argdefs, 0); nd = ((PyTupleObject *)argdefs)->ob_size; } return PyEval_EvalCodeEx(co, globals, (PyObject *)NULL, (*pp_stack)-n, na, (*pp_stack)-2*nk, nk, d, nd, PyFunction_GET_CLOSURE(func)); }
DEFINEFN vinfo_t* pfunction_simple_call(PsycoObject* po, PyObject* f, vinfo_t* arg, bool allow_inline) { PyObject* glob; PyObject* defl; PyCodeObject* co; vinfo_t* fglobals; vinfo_t* fdefaults; vinfo_t* result; int saved_inlining; /* XXX we capture the code object, so this breaks if someone changes the .func_code attribute of the function later */ co = (PyCodeObject*) PyFunction_GET_CODE(f); if (PyCode_GetNumFree(co) > 0) goto fallback; glob = PyFunction_GET_GLOBALS(f); defl = PyFunction_GET_DEFAULTS(f); Py_INCREF(glob); fglobals = vinfo_new(CompileTime_NewSk(sk_new ((long)glob, SkFlagPyObj))); if (defl == NULL) fdefaults = psyco_vi_Zero(); else { Py_INCREF(defl); fdefaults = vinfo_new(CompileTime_NewSk(sk_new ((long)defl, SkFlagPyObj))); } saved_inlining = po->pr.is_inlining; if (!allow_inline) po->pr.is_inlining = true; result = psyco_call_pyfunc(po, co, fglobals, fdefaults, arg, po->pr.auto_recursion); po->pr.is_inlining = saved_inlining; vinfo_decref(fdefaults, po); vinfo_decref(fglobals, po); return result; fallback: return psyco_generic_call(po, PyFunction_Type.tp_call, CfReturnRef|CfPyErrIfNull, "lvl", (long) f, arg, 0); }
static int bpy_prop_callback_check(PyObject *py_func, int argcount) { if(py_func) { if(!PyFunction_Check(py_func)) { PyErr_Format(PyExc_TypeError, "update keyword: expected a function type, not a %.200s", Py_TYPE(py_func)->tp_name); return -1; } else { PyCodeObject *f_code= (PyCodeObject *)PyFunction_GET_CODE(py_func); if (f_code->co_argcount != argcount) { PyErr_Format(PyExc_TypeError, "update keyword: expected a function taking %d arguments, not %d", argcount, f_code->co_argcount); return -1; } } } return 0; }
bool SCA_PythonController::Import() { m_bModified= false; /* in case we re-import */ Py_XDECREF(m_function); m_function= NULL; std::string mod_path = m_scriptText; /* just for storage, use C style string access */ std::string function_string; const int pos = mod_path.rfind('.'); if (pos != std::string::npos) { function_string = mod_path.substr(pos + 1); mod_path = mod_path.substr(0, pos); } if (function_string.empty()) { CM_LogicBrickError(this, "python module name formatting expected 'SomeModule.Func', got '" << m_scriptText << "'"); return false; } // Import the module and print an error if it's not found PyObject *mod = PyImport_ImportModule(mod_path.c_str()); if (mod == NULL) { ErrorPrint("Python module can't be imported"); return false; } if (m_debug) mod = PyImport_ReloadModule(mod); if (mod == NULL) { ErrorPrint("Python module can't be reloaded"); return false; } // Get the function object m_function = PyObject_GetAttrString(mod, function_string.c_str()); // DECREF the module as we don't need it anymore Py_DECREF(mod); if (m_function==NULL) { if (PyErr_Occurred()) ErrorPrint("python controller found the module but could not access the function"); else CM_LogicBrickError(this, "python module '" << m_scriptText << "' found but function missing"); return false; } if (!PyCallable_Check(m_function)) { Py_DECREF(m_function); m_function = NULL; CM_LogicBrickError(this, "python module function '" << m_scriptText << "' not callable"); return false; } m_function_argc = 0; /* rare cases this could be a function that isn't defined in python, assume zero args */ if (PyFunction_Check(m_function)) { m_function_argc= ((PyCodeObject *)PyFunction_GET_CODE(m_function))->co_argcount; } if (m_function_argc > 1) { Py_DECREF(m_function); m_function = NULL; CM_LogicBrickError(this, "python module function:\n '" << m_scriptText << "' takes " << m_function_argc << " args, should be zero or 1 controller arg"); return false; } return true; }
bool SCA_PythonController::Import() { //printf("py module modified '%s'\n", m_scriptName.Ptr()); m_bModified= false; /* incase we re-import */ Py_XDECREF(m_function); m_function= NULL; STR_String mod_path_str= m_scriptText; /* just for storage, use C style string access */ char *mod_path= mod_path_str.Ptr(); char *function_string; function_string= strrchr(mod_path, '.'); if(function_string == NULL) { printf("Python module name formatting error \"%s\":\n\texpected \"SomeModule.Func\", got \"%s\"\n", GetName().Ptr(), m_scriptText.Ptr()); return false; } *function_string= '\0'; function_string++; // Import the module and print an error if it's not found PyObject *mod = PyImport_ImportModule(mod_path); if (mod == NULL) { ErrorPrint("Python module can't be imported"); return false; } if(m_debug) mod = PyImport_ReloadModule(mod); if (mod == NULL) { ErrorPrint("Python module can't be reloaded"); return false; } // Get the function object m_function = PyObject_GetAttrString(mod, function_string); // DECREF the module as we don't need it anymore Py_DECREF(mod); if(m_function==NULL) { if(PyErr_Occurred()) ErrorPrint("Python controller found the module but could not access the function"); else printf("Python module error \"%s\":\n \"%s\" module found but function missing\n", GetName().Ptr(), m_scriptText.Ptr()); return false; } if(!PyCallable_Check(m_function)) { Py_DECREF(m_function); printf("Python module function error \"%s\":\n \"%s\" not callable\n", GetName().Ptr(), m_scriptText.Ptr()); return false; } m_function_argc = 0; /* rare cases this could be a function that isnt defined in python, assume zero args */ if (PyFunction_Check(m_function)) { PyObject *py_arg_count = PyObject_GetAttrString(PyFunction_GET_CODE(m_function), "co_argcount"); if(py_arg_count) { m_function_argc = PyLong_AsLong(py_arg_count); Py_DECREF(py_arg_count); } else { PyErr_Clear(); /* unlikely to fail but just incase */ } } if(m_function_argc > 1) { Py_DECREF(m_function); printf("Python module function has \"%s\":\n \"%s\" takes %d args, should be zero or 1 controller arg\n", GetName().Ptr(), m_scriptText.Ptr(), m_function_argc); return false; } return true; }
static PyObject *BPy_EnumProperty(PyObject *self, PyObject *args, PyObject *kw) { StructRNA *srna; BPY_PROPDEF_HEAD(EnumProperty) if(srna) { static const char *kwlist[]= {"attr", "items", "name", "description", "default", "options", "update", NULL}; const char *id=NULL, *name="", *description=""; PyObject *def= NULL; int id_len; int defvalue=0; PyObject *items, *items_fast; EnumPropertyItem *eitems; PropertyRNA *prop; PyObject *pyopts= NULL; int opts=0; short is_itemf= FALSE; PyObject *update_cb= NULL; if (!PyArg_ParseTupleAndKeywords(args, kw, "s#O|ssOO!O:EnumProperty", (char **)kwlist, &id, &id_len, &items, &name, &description, &def, &PySet_Type, &pyopts, &update_cb)) { return NULL; } BPY_PROPDEF_CHECK(EnumProperty, property_flag_enum_items) if (bpy_prop_callback_check(update_cb, 2) == -1) { return NULL; } /* items can be a list or a callable */ if(PyFunction_Check(items)) { /* dont use PyCallable_Check because we need the function code for errors */ PyCodeObject *f_code= (PyCodeObject *)PyFunction_GET_CODE(items); if(f_code->co_argcount != 2) { PyErr_Format(PyExc_ValueError, "EnumProperty(...): expected 'items' function to take 2 arguments, not %d", f_code->co_argcount); return NULL; } if(def) { /* note, using type error here is odd but python does this for invalid arguments */ PyErr_SetString(PyExc_TypeError, "EnumProperty(...): 'default' can't be set when 'items' is a function"); return NULL; } is_itemf= TRUE; eitems= DummyRNA_NULL_items; } else { if(!(items_fast= PySequence_Fast(items, "EnumProperty(...): expected a sequence of tuples for the enum items or a function"))) { return NULL; } eitems= enum_items_from_py(items_fast, def, &defvalue, (opts & PROP_ENUM_FLAG)!=0); Py_DECREF(items_fast); if(!eitems) { return NULL; } } if(opts & PROP_ENUM_FLAG) prop= RNA_def_enum_flag(srna, id, eitems, defvalue, name, description); else prop= RNA_def_enum(srna, id, eitems, defvalue, name, description); if(is_itemf) { RNA_def_enum_funcs(prop, bpy_props_enum_itemf); RNA_def_enum_py_data(prop, (void *)items); /* Py_INCREF(items); */ /* watch out!, if user is tricky they can probably crash blender if they manage to free the callback, take care! */ } if(pyopts) { if(opts & PROP_HIDDEN) RNA_def_property_flag(prop, PROP_HIDDEN); if((opts & PROP_ANIMATABLE)==0) RNA_def_property_clear_flag(prop, PROP_ANIMATABLE); } bpy_prop_callback_assign(prop, update_cb); RNA_def_property_duplicate_pointers(srna, prop); if(is_itemf == FALSE) { MEM_freeN(eitems); } } Py_RETURN_NONE; }
static PyObject* copyrec(PyObject* o) { PyTypeObject* t; PyObject* n; PyObject* key; KeyObject* fkey; if (o == Py_None || o->ob_type == &PyInt_Type || o->ob_type == &PyString_Type) { Py_INCREF(o); return o; } if (ss_next_in_block < 0) { struct key_block* b = (struct key_block*) malloc(sizeof(struct key_block)); if (!b) { PyErr_NoMemory(); goto fail1; } b->next = ss_block; ss_block = b; ss_next_in_block = KEYS_BY_BLOCK - 1; } fkey = ss_block->keys + ss_next_in_block; fkey->ob_refcnt = 1; fkey->ob_type = &keytype; fkey->o = o; key = (PyObject*) fkey; n = PyDict_GetItem(ss_memo, key); if (n) { Py_INCREF(n); return n; } ss_next_in_block--; Py_INCREF(o); /* reference stored in 'fkey->o' */ t = o->ob_type; if (t == &PyTuple_Type) { int i, count = PyTuple_GET_SIZE(o); n = PyTuple_New(count); if (!n || PyDict_SetItem(ss_memo, key, n)) goto fail; for (i=0; i<count; i++) PyTuple_SET_ITEM(n, i, copyrec(PyTuple_GET_ITEM(o, i))); return n; } if (t == &PyList_Type) { int i, count = PyList_GET_SIZE(o); n = PyList_New(count); if (!n || PyDict_SetItem(ss_memo, key, n)) goto fail; for (i=0; i<count; i++) PyList_SET_ITEM(n, i, copyrec(PyList_GET_ITEM(o, i))); return n; } if (t == &PyDict_Type) { int i = 0; PyObject* dictkey; PyObject* dictvalue; n = PyDict_New(); if (!n || PyDict_SetItem(ss_memo, key, n)) goto fail; while (PyDict_Next(o, &i, &dictkey, &dictvalue)) if (PyDict_SetItem(n, copyrec(dictkey), copyrec(dictvalue))) goto fail; return n; } if (t == &PyInstance_Type) { int i = 0; PyObject* dictkey; PyObject* dictvalue; PyObject* dsrc; PyObject* ddest; PyObject* inst_build = PyObject_GetAttr(o, str_inst_build); if (inst_build == NULL) { PyErr_Clear(); goto unmodified; } n = PyObject_CallObject(inst_build, NULL); if (!n || PyDict_SetItem(ss_memo, key, n)) goto fail; dsrc = ((PyInstanceObject*) o)->in_dict; ddest = ((PyInstanceObject*) n)->in_dict; while (PyDict_Next(dsrc, &i, &dictkey, &dictvalue)) if (PyDict_SetItem(ddest, copyrec(dictkey), copyrec(dictvalue))) goto fail; return n; } if (t == &PyFunction_Type) { int i, count; PyObject* tsrc = PyFunction_GET_DEFAULTS(o); PyObject* tdest; if (!tsrc) goto unmodified; count = PyTuple_GET_SIZE(tsrc); if (count == 0) goto unmodified; n = PyFunction_New(PyFunction_GET_CODE(o), PyFunction_GET_GLOBALS(o)); if (!n || PyDict_SetItem(ss_memo, key, n)) goto fail; tdest = PyTuple_New(count); if (!tdest) goto fail; for (i=0; i<count; i++) PyTuple_SET_ITEM(tdest, i, copyrec(PyTuple_GET_ITEM(tsrc, i))); i = PyFunction_SetDefaults(n, tdest); Py_DECREF(tdest); if (i) goto fail; return n; } if (t == &PyMethod_Type) { PyObject* x; n = PyMethod_New(PyMethod_GET_FUNCTION(o), PyMethod_GET_SELF(o), PyMethod_GET_CLASS(o)); if (!n || PyDict_SetItem(ss_memo, key, n)) goto fail; x = copyrec(PyMethod_GET_FUNCTION(n)); Py_DECREF(PyMethod_GET_FUNCTION(n)); PyMethod_GET_FUNCTION(n) = x; x = copyrec(PyMethod_GET_SELF(n)); Py_DECREF(PyMethod_GET_SELF(n)); PyMethod_GET_SELF(n) = x; return n; } if (t == GeneratorType) { n = genbuild(o); if (!n || PyDict_SetItem(ss_memo, key, n)) goto fail; if (gencopy(n, o)) goto fail; return n; } if (t == &PySeqIter_Type) { n = seqiterbuild(o); if (!n || PyDict_SetItem(ss_memo, key, n)) goto fail; if (seqitercopy(n, o)) goto fail; return n; } ss_next_in_block++; return o; /* reference no longer stored in 'fkey->o' */ unmodified: PyDict_SetItem(ss_memo, key, o); Py_INCREF(o); return o; fail1: n = NULL; fail: Py_INCREF(o); Py_XDECREF(n); return o; }
NUITKA_MAY_BE_UNUSED static PyObject *fast_python_call( PyObject *func, PyObject **args, int count ) { PyCodeObject *co = (PyCodeObject *)PyFunction_GET_CODE( func ); PyObject *globals = PyFunction_GET_GLOBALS( func ); PyObject *argdefs = PyFunction_GET_DEFAULTS( func ); #if PYTHON_VERSION >= 300 PyObject *kwdefs = PyFunction_GET_KW_DEFAULTS( func ); if ( kwdefs == NULL && argdefs == NULL && co->co_argcount == count && co->co_flags == ( CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE )) #else if ( argdefs == NULL && co->co_argcount == count && co->co_flags == ( CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE )) #endif { PyThreadState *tstate = PyThreadState_GET(); assertObject( globals ); PyFrameObject *frame = PyFrame_New( tstate, co, globals, NULL ); if (unlikely( frame == NULL )) { return NULL; }; for ( int i = 0; i < count; i++ ) { frame->f_localsplus[i] = INCREASE_REFCOUNT( args[i] ); } PyObject *result = PyEval_EvalFrameEx( frame, 0 ); // Frame release protects against recursion as it may lead to variable // destruction. ++tstate->recursion_depth; Py_DECREF( frame ); --tstate->recursion_depth; return result; } PyObject **defaults = NULL; int nd = 0; if ( argdefs != NULL ) { defaults = &PyTuple_GET_ITEM( argdefs, 0 ); nd = int( Py_SIZE( argdefs ) ); } PyObject *result = PyEval_EvalCodeEx( #if PYTHON_VERSION >= 300 (PyObject *)co, #else co, // code object #endif globals, // globals NULL, // no locals args, // args count, // argcount NULL, // kwds 0, // kwcount defaults, // defaults nd, // defcount #if PYTHON_VERSION >= 300 kwdefs, #endif PyFunction_GET_CLOSURE( func ) ); return result; }