Ejemplo n.º 1
0
int
PyErr_GivenExceptionMatches(PyObject *err, PyObject *exc)
{
	if (err == NULL || exc == NULL) {
		/* maybe caused by "import exceptions" that failed early on */
		return 0;
	}
	if (PyTuple_Check(exc)) {
		int i, n;
		n = PyTuple_Size(exc);
		for (i = 0; i < n; i++) {
			/* Test recursively */
		     if (PyErr_GivenExceptionMatches(
			     err, PyTuple_GET_ITEM(exc, i)))
		     {
			     return 1;
		     }
		}
		return 0;
	}
	/* err might be an instance, so check its class. */
	if (PyInstance_Check(err))
		err = (PyObject*)((PyInstanceObject*)err)->in_class;

	if (PyClass_Check(err) && PyClass_Check(exc))
		return PyClass_IsSubclass(err, exc);

	return err == exc;
}
Ejemplo n.º 2
0
static int
hv_cli_class_le(PyObject * self, PyObject *a, PyObject *b)
{
    if (a == b)
        return 1;
    if (PyType_Check(a) && PyType_Check(b))
        return PyType_IsSubtype((PyTypeObject *)a, (PyTypeObject *)b);
    if (PyClass_Check(a) && PyClass_Check(b))
        return PyClass_IsSubclass(a, b);
    return 0;
}
Ejemplo n.º 3
0
//init the concoord module
int load_concoord_module(void){
    int ret=-1;

    #if PY_DEBUG
        fprintf(stderr,"I am here %s\n",__FUNCTION__);  
    #endif
    pname = PyString_FromString(module_name);  
    if(NULL==pname)   
    {  
    #if PY_DEBUG
        fprintf(stderr,"can't build python string object\n");  
    #endif
        goto load_module_error;  
    }  

    pmodule = PyImport_Import(pname);  
    if(NULL==pmodule)
    {  
    #if PY_DEBUG
        fprintf(stderr,"can't find concoord module\n");  
    #endif
        goto load_module_error;  
    }  

    pdict = PyModule_GetDict(pmodule);  
    if(NULL==pdict)           
    {  
    #if PY_DEBUG
        fprintf(stderr,"can't get the dict of concoord module\n");  
    #endif
        goto load_module_error;  
    }  

    pclass = PyDict_GetItemString(pdict, class_name);  
    if(NULL==pclass)           
    {  
    #if PY_DEBUG
        fprintf(stderr,"can't find class SimpleConcoordServer\n");  
    #endif
        goto load_module_error;  
    }  

    #if PY_DEBUG
    if(PyClass_Check(pclass)){
        fprintf(stderr,"we have found the class\n");
    }
    #endif

    flag_concoord_module = 1;
    ret = 0;
    goto load_module_exit;

load_module_error:
    if(NULL!=pname){Py_DECREF(pname);pname=NULL;}
    if(NULL!=pmodule){Py_DECREF(pmodule);pmodule=NULL;}
    if(NULL!=pdict){Py_DECREF(pdict);pdict=NULL;}
    if(NULL!=pclass){Py_DECREF(pclass);pclass=NULL;}
load_module_exit:
    return ret;
}
Ejemplo n.º 4
0
// Trawl a type's hierarchy looking for any slots, signals or properties.
static int trawl_hierarchy(PyTypeObject *pytype, qpycore_metaobject *qo,
        QMetaObjectBuilder &builder, QList<const qpycore_pyqtSignal *> &psigs,
        QMap<uint, PropertyData> &pprops)
{
    if (trawl_type(pytype, qo, builder, psigs, pprops) < 0)
        return -1;

    if (!pytype->tp_bases)
        return 0;

    Q_ASSERT(PyTuple_Check(pytype->tp_bases));

    for (SIP_SSIZE_T i = 0; i < PyTuple_GET_SIZE(pytype->tp_bases); ++i)
    {
        PyTypeObject *sup = (PyTypeObject *)PyTuple_GET_ITEM(pytype->tp_bases, i);

#if PY_MAJOR_VERSION < 3
        /* Ignore classic classes as mixins. */
        if (PyClass_Check((PyObject *)sup))
            continue;
#endif

        if (PyType_IsSubtype(sup, sipTypeAsPyTypeObject(sipType_QObject)))
            continue;

        if (trawl_hierarchy(sup, qo, builder, psigs, pprops) < 0)
            return -1;
    }

    return 0;
}
Ejemplo n.º 5
0
static PyObject *
inheritedAttribute(PyTypeObject *self, PyObject *name)
{
  int i;
  PyObject *d, *cls;

  for (i = 1; i < PyTuple_GET_SIZE(self->tp_mro); i++)
    {
      cls = PyTuple_GET_ITEM(self->tp_mro, i);
      if (PyType_Check(cls))
        d = ((PyTypeObject *)cls)->tp_dict;
      else if (PyClass_Check(cls))
        d = ((PyClassObject *)cls)->cl_dict;
      else
        /* Unrecognized thing, punt */
        d = NULL;
      
      if ((d == NULL) || (PyDict_GetItem(d, name) == NULL))
        continue;
                    
      return PyObject_GetAttr(cls, name);
    }

  PyErr_SetObject(PyExc_AttributeError, name);
  return NULL;
}
Ejemplo n.º 6
0
void
pymatecorba_register_stub(CORBA_TypeCode tc, PyObject *stub)
{
    init_hash_tables();

    if (tc->repo_id) {
        CORBA_Object_duplicate((CORBA_Object)tc, NULL);
        g_hash_table_replace(type_codes, tc->repo_id, tc);
    }

    if (stub) {
        PyObject *stub_dict = NULL;
        Py_INCREF(stub);
        g_hash_table_insert(stubs, tc->repo_id, stub);

        if (!strncmp(tc->repo_id, "IDL:omg.org/CORBA", 17)) {
            gchar *other_repo_id = g_strconcat("IDL:", &tc->repo_id[12], NULL);

            g_hash_table_insert(stubs, other_repo_id, stub);
        }

        if (PyType_Check(stub))
            stub_dict = ((PyTypeObject *)stub)->tp_dict;
        else if (PyClass_Check(stub))
            stub_dict = ((PyClassObject *)stub)->cl_dict;

        if (stub_dict && !PyDict_GetItemString(stub_dict, "__typecode__")) {
            PyObject *py_tc = pycorba_typecode_new(tc);

            PyDict_SetItemString(stub_dict, "__typecode__", py_tc);
            Py_DECREF(py_tc);
        }
    }
}
QString QgsPythonUtilsImpl::getTypeAsString( PyObject* obj )
{
  if ( obj == NULL )
    return NULL;

  if ( PyClass_Check( obj ) )
  {
    QgsDebugMsg( "got class" );
    return QString( PyString_AsString((( PyClassObject* )obj )->cl_name ) );
  }
  else if ( PyType_Check( obj ) )
  {
    QgsDebugMsg( "got type" );
    return QString((( PyTypeObject* )obj )->tp_name );
  }
  else
  {
    QgsDebugMsg( "got object" );
    PyObject* s = PyObject_Str( obj );
    QString str;
    if ( s && PyString_Check( s ) )
      str = QString( PyString_AsString( s ) );
    Py_XDECREF( s );
    return str;
  }
}
static char *hexin_http_scribe_init(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
{
	hexin_http_scribe_loc_conf_t *loc_conf = conf;
	hexin_http_scribe_python = ngx_palloc(cf->pool, sizeof(hexin_http_scribe_python_t));
		
	Py_Initialize();
	 // 检查初始化是否成功
	if (!Py_IsInitialized() ) {
		return NGX_CONF_ERROR;
	}
	
	PyRun_SimpleString("import sys");   
	PyRun_SimpleString((char*)loc_conf->scribe_python_workspace.data); 
	hexin_http_scribe_python->pModule = PyImport_ImportModule((char*)loc_conf->scribe_python_filename.data); 
	if (!hexin_http_scribe_python->pModule) {  
		printf("can't find ScribeClient.py");  
		getchar();
		return NGX_CONF_ERROR;  
	} 
	hexin_http_scribe_python->pDict = PyModule_GetDict(hexin_http_scribe_python->pModule);  
	if (!hexin_http_scribe_python->pDict) {
		return NGX_CONF_ERROR;  
	}  
	hexin_http_scribe_python->pScriberClientClass = PyDict_GetItemString(hexin_http_scribe_python->pDict, (char*)loc_conf->scribe_python_classname.data);
	if (!hexin_http_scribe_python->pScriberClientClass || !PyClass_Check(hexin_http_scribe_python->pScriberClientClass)) {
		return NGX_CONF_ERROR;  
	}

	PyObject *pArgs = PyTuple_New(3);
	PyTuple_SetItem(pArgs, 0, Py_BuildValue("s",loc_conf->scribe_host.data));
	PyTuple_SetItem(pArgs, 1, Py_BuildValue("s",loc_conf->scribe_port.data));
	PyTuple_SetItem(pArgs, 2, Py_BuildValue("b","False"));
	hexin_http_scribe_python->pScriberClient = PyInstance_New(hexin_http_scribe_python->pScriberClientClass, pArgs, NULL);
	 
	if (!hexin_http_scribe_python->pScriberClient) { 
		return NGX_CONF_ERROR;  
	}
	hexin_http_scribe_python->isinit = 1;
   
	ngx_http_complex_value_t  cv; 
    	ngx_memzero(&cv, sizeof(ngx_http_complex_value_t));
	cv.value.len = success_submit.len;
	cv.value.data = success_submit.data;
	hexin_http_scribe_python->success_response = cv;
	loc_conf->message_index = ngx_http_get_variable_index(cf, &message_flag);

	ngx_http_core_loc_conf_t  *clcf;

    	clcf = ngx_http_conf_get_module_loc_conf(cf, ngx_http_core_module);

    	clcf->handler = hexin_http_scribe_handler;

    	return NGX_CONF_OK;
}
Ejemplo n.º 9
0
//=============================================================================
// METHOD: SPELLvariableMonitor::retrieveLocalVariables()
//=============================================================================
void SPELLvariableMonitor::retrieveLocalVariables(std::vector<SPELLvarInfo>& vars)
{
	DEBUG("[VM] Retrieve Locals");

	/*
	 * Bottom stack frame is discarded,
	 * as globals and locals are the same dictionary
	 */
	if (m_frame->f_back == NULL) return;

	/*
	 * Get the names defined in the current code, including arguments
	 */
	std::vector<std::string> varNames = retrieveNames();

	/*
	 * Iterate over the locals dictionary, retrieving the names contained in
	 * varNames
	 */
	PyFrame_FastToLocals(m_frame);
	PyObject* dict = m_frame->f_locals;
	DEBUG("[VM] Frame: " + PYCREPR(m_frame));
	for( unsigned int index = 0; index< varNames.size(); index++)
	{
		std::string varName = varNames[index];
		PyObject* pyVarName = SSTRPY(varName);
		if (PyDict_Contains( dict, pyVarName ))
		{
			PyObject* object = PyDict_GetItem( dict, pyVarName );

			if (!SPELLpythonHelper::instance().isInstance(object, "Database", "spell.lib.adapter.databases.database"))
			{
				if (PyCallable_Check(object)) continue;
				if (PyClass_Check(object)) continue;
				if (PyModule_Check(object)) continue;
				if (PyInstance_Check(object)) continue;
			}
			DEBUG("[VM] Processing " + varName);
			std::string type = PYSSTR( PyObject_Type(object) );
			DEBUG("[VM] Type      : " + type);
			std::string value = PYREPR( object );
			DEBUG("[VM] Value     : " + value);
			DEBUG("[VM] Global    : " + BSTR(false));
			DEBUG("[VM] Registered: " + BSTR(isRegistered(varName)));

			// Mark empty values (empty strings) as "<empty>"
			if (value == "") value = EMPTY_STRING;

			vars.push_back( SPELLvarInfo(varName, type, value, false, isRegistered(varName)) );
		}
	}
	PyFrame_LocalsToFast(m_frame,0);
}
Ejemplo n.º 10
0
bool SET_ATTRIBUTE_CLASS_SLOT(PyObject *target, PyObject *value) {
    CHECK_OBJECT(target);
    CHECK_OBJECT(value);

#if PYTHON_VERSION < 300
    if (likely(PyInstance_Check(target))) {
        PyInstanceObject *target_instance = (PyInstanceObject *)target;

        if (unlikely(!PyClass_Check(value))) {
            PyErr_SetString(PyExc_TypeError, "__class__ must be set to a class");
            return false;
        }

        PyObject *old = (PyObject *)(target_instance->in_class);
        Py_INCREF(value);
        target_instance->in_class = (PyClassObject *)value;
        Py_DECREF(old);
    } else
#endif
    {
        PyTypeObject *type = Py_TYPE(target);

        if (type->tp_setattro != NULL) {
            int status = (*type->tp_setattro)(target, const_str_plain___class__, value);

            if (unlikely(status == -1)) {
                return false;
            }
        } else if (type->tp_setattr != NULL) {
            int status = (*type->tp_setattr)(target, (char *)"__class__", value);

            if (unlikely(status == -1)) {
                return false;
            }
        } else if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
            PyErr_Format(PyExc_TypeError, "'%s' object has no attributes (assign to __class__)", type->tp_name);

            return false;
        } else {
            PyErr_Format(PyExc_TypeError, "'%s' object has only read-only attributes (assign to __class__)",
                         type->tp_name);

            return false;
        }
    }

    return true;
}
Ejemplo n.º 11
0
PyObject *
PyErr_NewException(char *name, PyObject *base, PyObject *dict)
{
	char *dot;
	PyObject *modulename = NULL;
	PyObject *classname = NULL;
	PyObject *mydict = NULL;
	PyObject *bases = NULL;
	PyObject *result = NULL;
	dot = strrchr(name, '.');
	if (dot == NULL) {
		PyErr_SetString(PyExc_SystemError,
			"PyErr_NewException: name must be module.class");
		return NULL;
	}
	if (base == NULL)
		base = PyExc_Exception;
	if (!PyClass_Check(base)) {
		/* Must be using string-based standard exceptions (-X) */
		return PyString_FromString(name);
	}
	if (dict == NULL) {
		dict = mydict = PyDict_New();
		if (dict == NULL)
			goto failure;
	}
	if (PyDict_GetItemString(dict, "__module__") == NULL) {
		modulename = PyString_FromStringAndSize(name, (int)(dot-name));
		if (modulename == NULL)
			goto failure;
		if (PyDict_SetItemString(dict, "__module__", modulename) != 0)
			goto failure;
	}
	classname = PyString_FromString(dot+1);
	if (classname == NULL)
		goto failure;
	bases = Py_BuildValue("(O)", base);
	if (bases == NULL)
		goto failure;
	result = PyClass_New(bases, dict, classname);
  failure:
	Py_XDECREF(bases);
	Py_XDECREF(mydict);
	Py_XDECREF(classname);
	Py_XDECREF(modulename);
	return result;
}
Ejemplo n.º 12
0
static void
add_stub_to_container(CORBA_TypeCode tc, const gchar *name, PyObject *stub)
{
    PyObject *container;
    gchar *pyname;

    container = _pymatecorba_get_container(tc->repo_id, FALSE);
    if (!container)
        return;

    pyname = _pymatecorba_escape_name(name);
    if (PyType_Check(container)) {
        PyObject *container_dict = ((PyTypeObject *)container)->tp_dict;

        PyDict_SetItemString(container_dict, pyname, stub);
    } else {
        PyObject_SetAttrString(container, pyname, stub);
    }
    g_free(pyname);
    if (PyErr_Occurred())
        PyErr_Clear();

    /* set __module__ if it is not an alias ... */
    if (tc->kind != CORBA_tk_alias &&
            (PyType_Check(stub) || PyClass_Check(stub))) {
        PyObject *module = NULL;

        if (PyModule_Check(container)) {
            const gchar *name;
            name = PyModule_GetName(container);
            if (name) module = PyString_FromString(name);
        } else {
            module = PyObject_GetAttrString(container, "__module__");
        }
        if (module) {
            PyObject_SetAttrString(stub, "__module__", module);
            Py_DECREF(module);
        }
    }

    Py_DECREF(container);
}
Ejemplo n.º 13
0
/* A variant of _PyType_Lookup that doesn't look in ProxyType.
 *
 * If argument search_wrappertype is nonzero, we can look in WrapperType.
 */
PyObject *
WrapperType_Lookup(PyTypeObject *type, PyObject *name)
{
    int i, n;
    PyObject *mro, *res, *base, *dict;

    /* Look in tp_dict of types in MRO */
    mro = type->tp_mro;

    /* If mro is NULL, the type is either not yet initialized
       by PyType_Ready(), or already cleared by type_clear().
       Either way the safest thing to do is to return NULL. */
    if (mro == NULL)
        return NULL;

    assert(PyTuple_Check(mro));

    n = PyTuple_GET_SIZE(mro)
      - 1; /* We don't want to look at the last item, which is object. */

    for (i = 0; i < n; i++) {
        base = PyTuple_GET_ITEM(mro, i);

        if (((PyTypeObject *)base) != &ProxyType) {
#if PY_MAJOR_VERSION < 3
            if (PyClass_Check(base))
                dict = ((PyClassObject *)base)->cl_dict;
            else
#endif
            {
                assert(PyType_Check(base));
                dict = ((PyTypeObject *)base)->tp_dict;
            }

            assert(dict && PyDict_Check(dict));
            res = PyDict_GetItem(dict, name);
            if (res != NULL)
                return res;
        }
    }
    return NULL;
}
Ejemplo n.º 14
0
QString QgsPythonUtilsImpl::getTypeAsString( PyObject* obj )
{
  if ( obj == NULL )
    return NULL;
  if ( PyClass_Check( obj ) )
  {
    QgsDebugMsg( "got class" );
    return QString( PyString_AsString((( PyClassObject* )obj )->cl_name ) );
  }
  else if ( PyType_Check( obj ) )
  {
    QgsDebugMsg( "got type" );
    return QString((( PyTypeObject* )obj )->tp_name );
  }
  else
  {
    QgsDebugMsg( "got object" );
    return PyObjectToQString( obj );
  }
}
Ejemplo n.º 15
0
//=============================================================================
// METHOD    : SPELLwsClassDataHandler::write()
//=============================================================================
void SPELLwsClassDataHandler::write()
{
	assert( PyClass_Check(getObject()) );

	PyClassObject* classObject = reinterpret_cast<PyClassObject*>(getObject());

	DEBUG("[CDH] Storing name: " + PYREPR(classObject->cl_name) );
	SPELLwsObjectDataHandler nameHandler( classObject->cl_name );
	nameHandler.setStorage(getStorage());

	DEBUG("[CDH] Storing dictionary: " + PYREPR(classObject->cl_dict));
	SPELLwsDictDataHandler dictHandler( classObject->cl_dict );
	dictHandler.setStorage(getStorage());

	// Store the class name, We dont need a data code, we know what is there
	nameHandler.write();
	// Store the class dictionary
	dictHandler.write();
	DEBUG("[CDH] Storing class done" );
}
Ejemplo n.º 16
0
static char const *GET_CALLABLE_DESC( PyObject *object )
{
    if ( Nuitka_Function_Check( object ) || Nuitka_Generator_Check( object ) || PyMethod_Check( object ) || PyFunction_Check( object ) || PyCFunction_Check( object ) )
    {
        return "()";
    }
#if PYTHON_VERSION < 300
    else if ( PyClass_Check( object ) )
    {
        return " constructor";
    }
    else if ( PyInstance_Check( object ))
    {
        return " instance";
    }
#endif
    else
    {
        return " object";
    }
}
Ejemplo n.º 17
0
void init_plugin(char* plugin, obj_list container){
	char* myplg = DYN_STR(plugin);
	char* path = (char*)malloc(strlen(plugin)+strlen(PLUGINS_PATH)+1);
	if(isupper(myplg[0])){
		myplg[0] = tolower(myplg[0]);
	}
	strcpy(path, PLUGINS_PATH);
	strcat(path, myplg);
	PyObject* plug_module = PyImport_ImportModule(path);
	if(!plug_module){
		printf("Couldn't import the module plugin module...\n");
		PyErr_Print();
	}
	if(islower(myplg[0])){
		myplg[0] = toupper(myplg[0]);

	}
	PyObject* clazz = PyObject_GetAttrString(plug_module, myplg);
	if(!clazz){
		printf("Couldn't get the plugin class...\n");
		PyErr_Print();
	}
	//TODO check for plugin subclassing
	Py_DECREF(plug_module);
	free(myplg);
	free(path);
	if(!PyClass_Check(clazz)){
		fprintf(stderr, "Got something that wasn't a class object...\n");
	}

	PyObject* plugin_instance = PyInstance_New(clazz, NULL, NULL);
	if(!plugin_instance){
		printf("Couldn't make plugin instance...\n");
		PyErr_Print();
	}
	Py_DECREF(clazz);
	obj_list_add(container, plugin_instance);
}
Ejemplo n.º 18
0
PyObject *FIND_ATTRIBUTE_IN_CLASS(PyClassObject *klass, PyObject *attr_name) {
    CHECK_OBJECT(klass);
    CHECK_OBJECT(attr_name);

    assert(PyClass_Check(klass));
    assert(PyString_CheckExact(attr_name));

    PyObject *result = GET_STRING_DICT_VALUE((PyDictObject *)klass->cl_dict, (PyStringObject *)attr_name);

    if (result == NULL) {
        Py_ssize_t base_count = PyTuple_Size(klass->cl_bases);

        for (Py_ssize_t i = 0; i < base_count; i++) {
            result = FIND_ATTRIBUTE_IN_CLASS((PyClassObject *)PyTuple_GetItem(klass->cl_bases, i), attr_name);

            if (result != NULL) {
                break;
            }
        }
    }

    return result;
}
Ejemplo n.º 19
0
static char const *GET_CLASS_NAME( PyObject *klass )
{
    if ( klass == NULL )
    {
        return "?";
    }
    else
    {
#if PYTHON_VERSION < 300
        if ( PyClass_Check( klass ) )
        {
            return Nuitka_String_AsString( ((PyClassObject *)klass)->cl_name );
        }
#endif

        if ( !PyType_Check( klass ) )
        {
            klass = (PyObject *)Py_TYPE( klass );
        }

        return ((PyTypeObject *)klass)->tp_name;
    }
}
Ejemplo n.º 20
0
static char const *GET_CALLABLE_NAME( PyObject *object )
{
    if ( Nuitka_Function_Check( object ) )
    {
        return Nuitka_String_AsString( Nuitka_Function_GetName( object ) );
    }
    else if ( Nuitka_Generator_Check( object ) )
    {
        return Nuitka_String_AsString( Nuitka_Generator_GetName( object ) );
    }
    else if ( PyMethod_Check( object ) )
    {
        return PyEval_GetFuncName( PyMethod_GET_FUNCTION( object ) );
    }
    else if ( PyFunction_Check( object ) )
    {
        return Nuitka_String_AsString( ((PyFunctionObject*)object)->func_name );
    }
#if PYTHON_VERSION < 300
    else if ( PyInstance_Check( object ) )
    {
        return Nuitka_String_AsString( ((PyInstanceObject*)object)->in_class->cl_name );
    }
    else if ( PyClass_Check( object ) )
    {
        return Nuitka_String_AsString( ((PyClassObject*)object)->cl_name );
    }
#endif
    else if ( PyCFunction_Check( object ) )
    {
        return ((PyCFunctionObject*)object)->m_ml->ml_name;
    }
    else
    {
        return Py_TYPE( object )->tp_name;
    }
}
Ejemplo n.º 21
0
QString QgsPythonUtilsImpl::getTypeAsString( PyObject* obj )
{
  if ( !obj )
    return nullptr;

#if (PY_VERSION_HEX < 0x03000000)
  if ( PyClass_Check( obj ) )
  {
    QgsDebugMsg( "got class" );
    return QString( PyString_AsString((( PyClassObject* )obj )->cl_name ) );
  }
  else
#endif
    if ( PyType_Check( obj ) )
    {
      QgsDebugMsg( "got type" );
      return QString((( PyTypeObject* )obj )->tp_name );
    }
    else
    {
      QgsDebugMsg( "got object" );
      return PyObjectToQString( obj );
    }
}
Ejemplo n.º 22
0
PyObject* PythonModule_InstatiateClass( PythonModule* Self, char* Name, char* Parameter )
{
  if( Name == NULL || Self == NULL )
    return NULL;

  PyObject* Instance;
  PyObject* Class;

  Class = PyObject_GetAttrString( Self->Module, Name );  
  if( !Class || !PyClass_Check( Class ) )
  {
    PyErr_Print();
    PythonModule_LeaveThread( Self );   
    return NULL;  
  }
  Instance = PyInstance_New( Class, PythonModule_CreateArgument( Parameter ), NULL );
  if( !Instance || !PyInstance_Check( Instance) )
  {
    PyErr_Print();
    PythonModule_LeaveThread( Self );   
    return NULL;  
  }
  return Instance;
}
Ejemplo n.º 23
0
Box* superGetattribute(Box* _s, Box* _attr) {
    RELEASE_ASSERT(_s->cls == super_cls, "");
    BoxedSuper* s = static_cast<BoxedSuper*>(_s);

    RELEASE_ASSERT(_attr->cls == str_cls, "");
    BoxedString* attr = static_cast<BoxedString*>(_attr);

    bool skip = s->obj_type == NULL;

    if (!skip) {
        // Looks like __class__ is supposed to be "super", not the class of the the proxied object.
        skip = (attr->s() == class_str);
    }

    if (!skip) {
        PyObject* mro, *res, *tmp, *dict;
        PyTypeObject* starttype;
        descrgetfunc f;
        Py_ssize_t i, n;

        starttype = s->obj_type;
        mro = starttype->tp_mro;

        if (mro == NULL)
            n = 0;
        else {
            assert(PyTuple_Check(mro));
            n = PyTuple_GET_SIZE(mro);
        }
        for (i = 0; i < n; i++) {
            if ((PyObject*)(s->type) == PyTuple_GET_ITEM(mro, i))
                break;
        }
        i++;
        res = NULL;
        for (; i < n; i++) {
            tmp = PyTuple_GET_ITEM(mro, i);

// Pyston change:
#if 0
            if (PyType_Check(tmp))
                dict = ((PyTypeObject *)tmp)->tp_dict;
            else if (PyClass_Check(tmp))
                dict = ((PyClassObject *)tmp)->cl_dict;
            else
                continue;
            res = PyDict_GetItem(dict, name);
#endif
            res = tmp->getattr(attr);

            if (res != NULL) {
// Pyston change:
#if 0
                Py_INCREF(res);
                f = Py_TYPE(res)->tp_descr_get;
                if (f != NULL) {
                    tmp = f(res,
                        /* Only pass 'obj' param if
                           this is instance-mode sper
                           (See SF ID #743627)
                        */
                        (s->obj == (PyObject *)
                                    s->obj_type
                            ? (PyObject *)NULL
                            : s->obj),
                        (PyObject *)starttype);
                    Py_DECREF(res);
                    res = tmp;
                }
#endif
                return processDescriptor(res, (s->obj == s->obj_type ? None : s->obj), s->obj_type);
            }
        }
    }

    Box* rtn = PyObject_GenericGetAttr(s, attr);
    if (!rtn)
        throwCAPIException();
    return rtn;
}
Ejemplo n.º 24
0
//=============================================================================
// STATIC : SPELLwsDataHandlerFactory::createDataHandler()
//=============================================================================
SPELLwsDataHandler* SPELLwsDataHandlerFactory::createDataHandler( PyObject* object )
{
	assert(object != NULL);

	SPELLwsDataHandler* handler = NULL;

	DEBUG("[DHF] Creating handler for object of type " + PYREPR( PyObject_Type(object) ));

	if (PyDict_Check(object))
	{
		DEBUG("[DHF] Object is a dictionary");
		handler = new SPELLwsDictDataHandler(object);
	}
	else if (PyList_Check(object))
	{
		DEBUG("[DHF] Object is a list");
		handler = new SPELLwsListDataHandler(object);
	}
	else if ( Py_None == object )
	{
		DEBUG("[DHF] Object is None");
		handler = new SPELLwsNoneDataHandler();
	}
	else if (SPELLpythonHelper::instance().isDatabase(object))
	{
		DEBUG("[DHF] Object is database");
		handler = new SPELLwsDbDataHandler(object);
	}
	else if (SPELLpythonHelper::instance().isTime(object))
	{
		DEBUG("[DHF] Object is TIME");
		handler = new SPELLwsTimeDataHandler(object);
	}
	else if (PyClass_Check(object))
	{
		DEBUG("[DHF] Object is a class: " + PYCREPR(object));
		handler = new SPELLwsClassDataHandler(object);
	}
	else if (PyInstance_Check(object))
	{
		DEBUG("[DHF] Object is a instance: " + PYCREPR(object));
		handler = new SPELLwsInstanceDataHandler(object);
	}
	else if (SPELLpythonHelper::instance().isSubclassInstance(object, "TmItemClass", "spell.lib.adapter.tm_item"))
	{
		DEBUG("[DHF] Object is a TM item: " + PYCREPR(object));
		handler = new SPELLwsTmItemDataHandler(object);
	}
	// Look discussion at mail.python.org/pipermail/python-dev/2004-July/046074.html
	else if ((object->ob_type->tp_flags & Py_TPFLAGS_HEAPTYPE)>0)
	{
		DEBUG("[DHF] Object is a custom type: " + PYCREPR(object));
		handler = new SPELLwsCustomTypeDataHandler(object);
	}
	else
	{
		DEBUG("[DHF] Default to object handler: " + PYCREPR(object));
		handler = new SPELLwsObjectDataHandler(object);
	}
	return handler;
}
Ejemplo n.º 25
0
//=============================================================================
// METHOD: SPELLvariableMonitor::retrieveGlobalVariables()
//=============================================================================
void SPELLvariableMonitor::retrieveGlobalVariables(std::vector<SPELLvarInfo>& vars,
												   std::set<std::string> locals)
{
	DEBUG("[VM] Retrieve Globals");

	/*
	 * Once we get the bottom stack frame, we have to iterate over all the keys
	 * in the globals dictionary, and filter them agains the m_initialVariables
	 */
	PyObject* dict = m_frame->f_globals;
	PyObject* itemList = PyDict_Keys(dict);
	unsigned int numItems = PyList_Size(itemList);
	for( unsigned int index = 0; index<numItems; index++)
	{
		PyObject* key = PyList_GetItem( itemList, index );
		std::string varName = PYSSTR(key);

		// Do the following check just when the considered variables are not internal databases
		if ( (varName != DatabaseConstants::SCDB) &&
			 (varName != DatabaseConstants::GDB)  &&
			 (varName != DatabaseConstants::PROC) &&
			 (varName != DatabaseConstants::ARGS) &&
			 (varName != DatabaseConstants::IVARS))
		{
			/* If they key is contained in the initial variables set, then ignore it */
			if (m_initialVariables.find(varName) != m_initialVariables.end())
			{
				continue;
			}
		}
		/* If a variable with the same name has been retrieved in the local scope
		 * then it must be ignored */
		if (locals.find(varName) != locals.end())
		{
			continue;
		}

		// Ignore internal flags
		if (varName == "__USERLIB__") continue;

		PyObject* object = PyDict_GetItem( dict, key );

		if (!SPELLpythonHelper::instance().isInstance(object, "Database", "spell.lib.adapter.databases.database"))
		{
			if (PyCallable_Check(object)) continue;
			if (PyClass_Check(object)) continue;
			if (PyModule_Check(object)) continue;
			if (PyInstance_Check(object)) continue;
		}
		DEBUG("[VM] Processing " + varName);

		std::string type = PYSSTR( PyObject_Type(object) );
		std::string value = PYREPR( object );

		DEBUG("[VM] Type      : " + type);
		DEBUG("[VM] Value     : " + value);
		DEBUG("[VM] Global    : " + BSTR(true));
		DEBUG("[VM] Registered: " + BSTR(isRegistered(PYSSTR(key))));

		// Mark empty values (empty strings) as "<empty>"
		if (value == "") value = EMPTY_STRING;

		vars.push_back( SPELLvarInfo(varName, type, value, true, isRegistered(PYSSTR(key))) );
	}
}
Ejemplo n.º 26
0
PyObject *
Base_getattro(PyObject *obj, PyObject *name)
{
  /* This is a modified copy of PyObject_GenericGetAttr.
     See the change note below. */

	PyTypeObject *tp = obj->ob_type;
	PyObject *descr = NULL;
	PyObject *res = NULL;
	descrgetfunc f;
	long dictoffset;
	PyObject **dictptr;

	if (!PyString_Check(name)){
#ifdef Py_USING_UNICODE
		/* The Unicode to string conversion is done here because the
		   existing tp_setattro slots expect a string object as name
		   and we wouldn't want to break those. */
		if (PyUnicode_Check(name)) {
			name = PyUnicode_AsEncodedString(name, NULL, NULL);
			if (name == NULL)
				return NULL;
		}
		else
#endif
		{
			PyErr_SetString(PyExc_TypeError,
					"attribute name must be string");
			return NULL;
		}
	}
	else
		Py_INCREF(name);

	if (tp->tp_dict == NULL) {
		if (PyType_Ready(tp) < 0)
			goto done;
	}

#if !defined(Py_TPFLAGS_HAVE_VERSION_TAG)
	/* Inline _PyType_Lookup */
	/* this is not quite _PyType_Lookup anymore */
	{
		int i, n;
		PyObject *mro, *base, *dict;

		/* Look in tp_dict of types in MRO */
		mro = tp->tp_mro;
		assert(mro != NULL);
		assert(PyTuple_Check(mro));
		n = PyTuple_GET_SIZE(mro);
		for (i = 0; i < n; i++) {
			base = PyTuple_GET_ITEM(mro, i);
			if (PyClass_Check(base))
				dict = ((PyClassObject *)base)->cl_dict;
			else {
				assert(PyType_Check(base));
				dict = ((PyTypeObject *)base)->tp_dict;
			}
			assert(dict && PyDict_Check(dict));
			descr = PyDict_GetItem(dict, name);
			if (descr != NULL)
				break;
		}
	}
#else
    descr = _PyType_Lookup(tp, name);
#endif

    Py_XINCREF(descr);

	f = NULL;
	if (descr != NULL &&
	    PyType_HasFeature(descr->ob_type, Py_TPFLAGS_HAVE_CLASS)) {
		f = descr->ob_type->tp_descr_get;
		if (f != NULL && PyDescr_IsData(descr)) {
			res = f(descr, obj, (PyObject *)obj->ob_type);
            Py_DECREF(descr);
			goto done;
		}
	}

	/* Inline _PyObject_GetDictPtr */
	dictoffset = tp->tp_dictoffset;
	if (dictoffset != 0) {
		PyObject *dict;
		if (dictoffset < 0) {
			int tsize;
			size_t size;

			tsize = ((PyVarObject *)obj)->ob_size;
			if (tsize < 0)
				tsize = -tsize;
			size = _PyObject_VAR_SIZE(tp, tsize);

			dictoffset += (long)size;
			assert(dictoffset > 0);
			assert(dictoffset % SIZEOF_VOID_P == 0);
		}
		dictptr = (PyObject **) ((char *)obj + dictoffset);
		dict = *dictptr;
		if (dict != NULL) {
			Py_INCREF(dict);
			res = PyDict_GetItem(dict, name);
			if (res != NULL) {
				Py_INCREF(res);
				Py_XDECREF(descr);
				Py_DECREF(dict);

                          /* CHANGED!
                             If the tp_descr_get of res is of_get, 
                             then call it. */
                          if ((strcmp(PyString_AsString(name), "__parent__") != 0) &&
                              PyObject_TypeCheck(res->ob_type,
                                                 &ExtensionClassType)
                              && res->ob_type->tp_descr_get != NULL) {
                            PyObject *tres;
                            tres = res->ob_type->tp_descr_get(
                                                 res, obj, 
                                                 OBJECT(obj->ob_type));
                            Py_DECREF(res);
                            res = tres;
                          }
                          goto done;
			}
			Py_DECREF(dict);
		}
	}

	if (f != NULL) {
		res = f(descr, obj, (PyObject *)obj->ob_type);
		Py_DECREF(descr);
		goto done;
	}

	if (descr != NULL) {
		res = descr;
        /* descr was already increfed above */
		goto done;
	}

        /* CHANGED: Just use the name. Don't format. */
        PyErr_SetObject(PyExc_AttributeError, name);
  done:
	Py_DECREF(name);
	return res;
}
Ejemplo n.º 27
0
void
PyErr_PrintEx(int set_sys_last_vars)
{
	int err = 0;
	PyObject *exception, *v, *tb, *f;
	PyErr_Fetch(&exception, &v, &tb);
	PyErr_NormalizeException(&exception, &v, &tb);

	if (exception == NULL)
		return;

	if (PyErr_GivenExceptionMatches(exception, PyExc_SystemExit)) {
		if (Py_FlushLine())
			PyErr_Clear();
		fflush(stdout);
		if (v == NULL || v == Py_None)
			Py_Exit(0);
		if (PyInstance_Check(v)) {
			/* we expect the error code to be store in the
			   `code' attribute
			*/
			PyObject *code = PyObject_GetAttrString(v, "code");
			if (code) {
				Py_DECREF(v);
				v = code;
				if (v == Py_None)
					Py_Exit(0);
			}
			/* if we failed to dig out the "code" attribute,
			   then just let the else clause below print the
			   error
			*/
		}
		if (PyInt_Check(v))
			Py_Exit((int)PyInt_AsLong(v));
		else {
			/* OK to use real stderr here */
			PyObject_Print(v, stderr, Py_PRINT_RAW);
			fprintf(stderr, "\n");
			Py_Exit(1);
		}
	}
	if (set_sys_last_vars) {
		PySys_SetObject("last_type", exception);
		PySys_SetObject("last_value", v);
		PySys_SetObject("last_traceback", tb);
	}
	f = PySys_GetObject("stderr");
	if (f == NULL)
		fprintf(stderr, "lost sys.stderr\n");
	else {
		if (Py_FlushLine())
			PyErr_Clear();
		fflush(stdout);
		err = PyTraceBack_Print(tb, f);
		if (err == 0 &&
		    PyErr_GivenExceptionMatches(exception, PyExc_SyntaxError))
		{
			PyObject *message;
			char *filename, *text;
			int lineno, offset;
			if (!parse_syntax_error(v, &message, &filename,
						&lineno, &offset, &text))
				PyErr_Clear();
			else {
				char buf[10];
				PyFile_WriteString("  File \"", f);
				if (filename == NULL)
					PyFile_WriteString("<string>", f);
				else
					PyFile_WriteString(filename, f);
				PyFile_WriteString("\", line ", f);
				sprintf(buf, "%d", lineno);
				PyFile_WriteString(buf, f);
				PyFile_WriteString("\n", f);
				if (text != NULL) {
					char *nl;
					if (offset > 0 &&
					    offset == (int)strlen(text))
						offset--;
					for (;;) {
						nl = strchr(text, '\n');
						if (nl == NULL ||
						    nl-text >= offset)
							break;
						offset -= (nl+1-text);
						text = nl+1;
					}
					while (*text == ' ' || *text == '\t') {
						text++;
						offset--;
					}
					PyFile_WriteString("    ", f);
					PyFile_WriteString(text, f);
					if (*text == '\0' ||
					    text[strlen(text)-1] != '\n')
						PyFile_WriteString("\n", f);
					PyFile_WriteString("    ", f);
					offset--;
					while (offset > 0) {
						PyFile_WriteString(" ", f);
						offset--;
					}
					PyFile_WriteString("^\n", f);
				}
				Py_INCREF(message);
				Py_DECREF(v);
				v = message;
				/* Can't be bothered to check all those
				   PyFile_WriteString() calls */
				if (PyErr_Occurred())
					err = -1;
			}
		}
		if (err) {
			/* Don't do anything else */
		}
		else if (PyClass_Check(exception)) {
			PyClassObject* exc = (PyClassObject*)exception;
			PyObject* className = exc->cl_name;
			PyObject* moduleName =
			      PyDict_GetItemString(exc->cl_dict, "__module__");

			if (moduleName == NULL)
				err = PyFile_WriteString("<unknown>", f);
			else {
				char* modstr = PyString_AsString(moduleName);
				if (modstr && strcmp(modstr, "exceptions")) 
				{
					err = PyFile_WriteString(modstr, f);
					err += PyFile_WriteString(".", f);
				}
			}
			if (err == 0) {
				if (className == NULL)
				      err = PyFile_WriteString("<unknown>", f);
				else
				      err = PyFile_WriteObject(className, f,
							       Py_PRINT_RAW);
			}
		}
		else
			err = PyFile_WriteObject(exception, f, Py_PRINT_RAW);
		if (err == 0) {
			if (v != NULL && v != Py_None) {
				PyObject *s = PyObject_Str(v);
				/* only print colon if the str() of the
				   object is not the empty string
				*/
				if (s == NULL)
					err = -1;
				else if (!PyString_Check(s) ||
					 PyString_GET_SIZE(s) != 0)
					err = PyFile_WriteString(": ", f);
				if (err == 0)
				  err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
				Py_XDECREF(s);
			}
		}
		if (err == 0)
			err = PyFile_WriteString("\n", f);
	}
	Py_XDECREF(exception);
	Py_XDECREF(v);
	Py_XDECREF(tb);
	/* If an error happened here, don't show it.
	   XXX This is wrong, but too many callers rely on this behavior. */
	if (err != 0)
		PyErr_Clear();
}
Ejemplo n.º 28
0
/****************************
 * SV* Py2Pl(PyObject *obj)
 *
 * Converts arbitrary Python data structures to Perl data structures
 * Note on references: does not Py_DECREF(obj).
 *
 * Modifications by Eric Wilhelm 2004-07-11 marked as elw
 *
 ****************************/
SV *Py2Pl(PyObject * const obj) {
    /* elw: see what python says things are */
#if PY_MAJOR_VERSION >= 3
    int const is_string = PyBytes_Check(obj) || PyUnicode_Check(obj);
#else
    int const is_string = PyString_Check(obj) || PyUnicode_Check(obj);
#endif
#ifdef I_PY_DEBUG
    PyObject *this_type = PyObject_Type(obj); /* new reference */
    PyObject *t_string = PyObject_Str(this_type); /* new reference */
#if PY_MAJOR_VERSION >= 3
    PyObject *type_str_bytes = PyUnicode_AsUTF8String(t_string); /* new reference */
    char *type_str = PyBytes_AsString(type_str_bytes);
#else
    char *type_str = PyString_AsString(t_string);
#endif
    Printf(("type is %s\n", type_str));
    printf("Py2Pl object:\n\t");
    PyObject_Print(obj, stdout, Py_PRINT_RAW);
    printf("\ntype:\n\t");
    PyObject_Print(this_type, stdout, Py_PRINT_RAW);
    printf("\n");
    Printf(("String check:   %i\n", is_string));
    Printf(("Number check:   %i\n", PyNumber_Check(obj)));
    Printf(("Int check:      %i\n", PyInt_Check(obj)));
    Printf(("Long check:     %i\n", PyLong_Check(obj)));
    Printf(("Float check:    %i\n", PyFloat_Check(obj)));
    Printf(("Type check:     %i\n", PyType_Check(obj)));
#if PY_MAJOR_VERSION < 3
    Printf(("Class check:    %i\n", PyClass_Check(obj)));
    Printf(("Instance check: %i\n", PyInstance_Check(obj)));
#endif
    Printf(("Dict check:     %i\n", PyDict_Check(obj)));
    Printf(("Mapping check:  %i\n", PyMapping_Check(obj)));
    Printf(("Sequence check: %i\n", PySequence_Check(obj)));
    Printf(("Iter check:     %i\n", PyIter_Check(obj)));
    Printf(("Function check: %i\n", PyFunction_Check(obj)));
    Printf(("Module check:   %i\n", PyModule_Check(obj)));
    Printf(("Method check:   %i\n", PyMethod_Check(obj)));
#if PY_MAJOR_VERSION < 3
    if ((obj->ob_type->tp_flags & Py_TPFLAGS_HEAPTYPE))
        printf("heaptype true\n");
    if ((obj->ob_type->tp_flags & Py_TPFLAGS_HAVE_CLASS))
        printf("has class\n");
#else
    Py_DECREF(type_str_bytes);
#endif
    Py_DECREF(t_string);
    Py_DECREF(this_type);
#endif
    /* elw: this needs to be early */
    /* None (like undef) */
    if (!obj || obj == Py_None) {
        Printf(("Py2Pl: Py_None\n"));
        return &PL_sv_undef;
    }
    else

#ifdef EXPOSE_PERL
    /* unwrap Perl objects */
    if (PerlObjObject_Check(obj)) {
        Printf(("Py2Pl: Obj_object\n"));
        return ((PerlObj_object *) obj)->obj;
    }

    /* unwrap Perl code refs */
    else if (PerlSubObject_Check(obj)) {
        Printf(("Py2Pl: Sub_object\n"));
        SV * ref = ((PerlSub_object *) obj)->ref;
        if (! ref) { /* probably an inherited method */
            if (! ((PerlSub_object *) obj)->obj)
                croak("Error: could not find a code reference or object method for PerlSub");
            SV * const sub_obj = (SV*)SvRV(((PerlSub_object *) obj)->obj);
            HV * const pkg = SvSTASH(sub_obj);
#if PY_MAJOR_VERSION >= 3
            char * const sub = PyBytes_AsString(((PerlSub_object *) obj)->sub);
#else
            PyObject *obj_sub_str = PyObject_Str(((PerlSub_object *) obj)->sub); /* new ref. */
            char * const sub = PyString_AsString(obj_sub_str);
#endif
            GV * const gv = Perl_gv_fetchmethod_autoload(aTHX_ pkg, sub, TRUE);
            if (gv && isGV(gv)) {
                ref = (SV *)GvCV(gv);
            }
#if PY_MAJOR_VERSION < 3
            Py_DECREF(obj_sub_str);
#endif
        }
        return newRV_inc((SV *) ref);
    }

    else
#endif

    /* wrap an instance of a Python class */
    /* elw: here we need to make these look like instances: */
    if ((obj->ob_type->tp_flags & Py_TPFLAGS_HEAPTYPE)
#if PY_MAJOR_VERSION < 3
        || PyInstance_Check(obj)
#endif
    ) {

        /* This is a Python class instance -- bless it into an
         * Inline::Python::Object. If we're being called from an
         * Inline::Python class, it will be re-blessed into whatever
         * class that is.
         */
        SV * const inst_ptr = newSViv(0);
        SV * const inst = newSVrv(inst_ptr, "Inline::Python::Object");;
        _inline_magic priv;

        /* set up magic */
        priv.key = INLINE_MAGIC_KEY;
        sv_magic(inst, inst, PERL_MAGIC_ext, (char *) &priv, sizeof(priv));
        MAGIC * const mg = mg_find(inst, PERL_MAGIC_ext);
        mg->mg_virtual = &inline_mg_vtbl;

        sv_setiv(inst, (IV) obj);
        /*SvREADONLY_on(inst); */ /* to uncomment this means I can't
            re-bless it */
        Py_INCREF(obj);
        Printf(("Py2Pl: Instance. Obj: %p, inst_ptr: %p\n", obj, inst_ptr));

        sv_2mortal(inst_ptr);
        return inst_ptr;
    }

    /* a tuple or a list */
    else if (PySequence_Check(obj) && !is_string) {
        AV * const retval = newAV();
        int i;
        int const sz = PySequence_Length(obj);

        Printf(("sequence (%i)\n", sz));

        for (i = 0; i < sz; i++) {
            PyObject * const tmp = PySequence_GetItem(obj, i);    /* new reference */
            SV * const next = Py2Pl(tmp);
            av_push(retval, next);
            if (sv_isobject(next)) // needed because objects get mortalized in Py2Pl
                SvREFCNT_inc(next);
            Py_DECREF(tmp);
        }

        if (PyTuple_Check(obj)) {
            _inline_magic priv;
            priv.key = TUPLE_MAGIC_KEY;

            sv_magic((SV * const)retval, (SV * const)NULL, PERL_MAGIC_ext, (char *) &priv, sizeof(priv));
        }

        return newRV_noinc((SV *) retval);
    }

    /* a dictionary or fake Mapping object */
    /* elw: PyMapping_Check() now returns true for strings */
    else if (! is_string && PyMapping_Check(obj)) {
        HV * const retval = newHV();
        int i;
        int const sz = PyMapping_Length(obj);
        PyObject * const keys = PyMapping_Keys(obj);   /* new reference */
        PyObject * const vals = PyMapping_Values(obj); /* new reference */

        Printf(("Py2Pl: dict/map\n"));
        Printf(("mapping (%i)\n", sz));

        for (i = 0; i < sz; i++) {
            PyObject * const key = PySequence_GetItem(keys, i), /* new reference */
                                 * const val = PySequence_GetItem(vals, i); /* new reference */
            SV       * const sv_val = Py2Pl(val);
            char     *       key_val;

            if (PyUnicode_Check(key)) {
                PyObject * const utf8_string = PyUnicode_AsUTF8String(key); /* new reference */
#if PY_MAJOR_VERSION >= 3
                key_val = PyBytes_AsString(utf8_string);
                SV * const utf8_key = newSVpv(key_val, PyBytes_Size(utf8_string));
#else
                key_val = PyString_AsString(utf8_string);
                SV * const utf8_key = newSVpv(key_val, PyString_Size(utf8_string));
#endif
                SvUTF8_on(utf8_key);

                hv_store_ent(retval, utf8_key, sv_val, 0);
                Py_DECREF(utf8_string);
            }
            else {
                PyObject * s = NULL;
#if PY_MAJOR_VERSION >= 3
                PyObject * s_bytes = NULL;
                if (PyBytes_Check(key)) {
                    key_val = PyBytes_AsString(key);
#else
                if (PyString_Check(key)) {
                    key_val = PyString_AsString(key);
#endif
                }
                else {
                    /* Warning -- encountered a non-string key value while converting a
                     * Python dictionary into a Perl hash. Perl can only use strings as
                     * key values. Using Python's string representation of the key as
                     * Perl's key value.
                     */
                    s = PyObject_Str(key); /* new reference */
#if PY_MAJOR_VERSION >= 3
                    s_bytes = PyUnicode_AsUTF8String(s); /* new reference */
                    key_val = PyBytes_AsString(s_bytes);
#else
                    key_val = PyString_AsString(s);
#endif
                    Py_DECREF(s);
                    if (PL_dowarn)
                        warn("Stringifying non-string hash key value: '%s'",
                             key_val);
                }

                if (!key_val) {
                    croak("Invalid key on key %i of mapping\n", i);
                }

                hv_store(retval, key_val, strlen(key_val), sv_val, 0);
#if PY_MAJOR_VERSION >= 3
                Py_XDECREF(s_bytes);
#endif
                Py_XDECREF(s);
            }
            if (sv_isobject(sv_val)) // needed because objects get mortalized in Py2Pl
                SvREFCNT_inc(sv_val);
            Py_DECREF(key);
            Py_DECREF(val);
        }
        Py_DECREF(keys);
        Py_DECREF(vals);
        return newRV_noinc((SV *) retval);
    }

    /* a boolean */
    else if (PyBool_Check(obj)) {
Ejemplo n.º 29
0
static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb,
                        CYTHON_UNUSED PyObject *cause) {
    /* cause is unused */
    Py_XINCREF(type);
    Py_XINCREF(value);
    Py_XINCREF(tb);
    /* First, check the traceback argument, replacing None with NULL. */
    if (tb == Py_None) {
        Py_DECREF(tb);
        tb = 0;
    }
    else if (tb != NULL && !PyTraceBack_Check(tb)) {
        PyErr_SetString(PyExc_TypeError,
            "raise: arg 3 must be a traceback or None");
        goto raise_error;
    }
    /* Next, replace a missing value with None */
    if (value == NULL) {
        value = Py_None;
        Py_INCREF(value);
    }
    #if PY_VERSION_HEX < 0x02050000
    if (!PyClass_Check(type))
    #else
    if (!PyType_Check(type))
    #endif
    {
        /* Raising an instance.  The value should be a dummy. */
        if (value != Py_None) {
            PyErr_SetString(PyExc_TypeError,
                "instance exception may not have a separate value");
            goto raise_error;
        }
        /* Normalize to raise <class>, <instance> */
        Py_DECREF(value);
        value = type;
        #if PY_VERSION_HEX < 0x02050000
            if (PyInstance_Check(type)) {
                type = (PyObject*) ((PyInstanceObject*)type)->in_class;
                Py_INCREF(type);
            }
            else {
                type = 0;
                PyErr_SetString(PyExc_TypeError,
                    "raise: exception must be an old-style class or instance");
                goto raise_error;
            }
        #else
            type = (PyObject*) Py_TYPE(type);
            Py_INCREF(type);
            if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) {
                PyErr_SetString(PyExc_TypeError,
                    "raise: exception class must be a subclass of BaseException");
                goto raise_error;
            }
        #endif
    }

    __Pyx_ErrRestore(type, value, tb);
    return;
raise_error:
    Py_XDECREF(value);
    Py_XDECREF(type);
    Py_XDECREF(tb);
    return;
}
Ejemplo n.º 30
0
/* Used in many places to normalize a raised exception, including in
   eval_code2(), do_raise(), and PyErr_Print()
*/
void
PyErr_NormalizeException(PyObject **exc, PyObject **val, PyObject **tb)
{
	PyObject *type = *exc;
	PyObject *value = *val;
	PyObject *inclass = NULL;
	PyObject *initial_tb = NULL;

	if (type == NULL) {
		/* There was no exception, so nothing to do. */
		return;
	}

	/* If PyErr_SetNone() was used, the value will have been actually
	   set to NULL.
	*/
	if (!value) {
		value = Py_None;
		Py_INCREF(value);
	}

	if (PyInstance_Check(value))
		inclass = (PyObject*)((PyInstanceObject*)value)->in_class;

	/* Normalize the exception so that if the type is a class, the
	   value will be an instance.
	*/
	if (PyClass_Check(type)) {
		/* if the value was not an instance, or is not an instance
		   whose class is (or is derived from) type, then use the
		   value as an argument to instantiation of the type
		   class.
		*/
		if (!inclass || !PyClass_IsSubclass(inclass, type)) {
			PyObject *args, *res;

			if (value == Py_None)
				args = Py_BuildValue("()");
			else if (PyTuple_Check(value)) {
				Py_INCREF(value);
				args = value;
			}
			else
				args = Py_BuildValue("(O)", value);

			if (args == NULL)
				goto finally;
			res = PyEval_CallObject(type, args);
			Py_DECREF(args);
			if (res == NULL)
				goto finally;
			Py_DECREF(value);
			value = res;
		}
		/* if the class of the instance doesn't exactly match the
		   class of the type, believe the instance
		*/
		else if (inclass != type) {
 			Py_DECREF(type);
			type = inclass;
			Py_INCREF(type);
		}
	}
	*exc = type;
	*val = value;
	return;
finally:
	Py_DECREF(type);
	Py_DECREF(value);
	/* If the new exception doesn't set a traceback and the old
	   exception had a traceback, use the old traceback for the
	   new exception.  It's better than nothing.
	*/
	initial_tb = *tb;
	PyErr_Fetch(exc, val, tb);
	if (initial_tb != NULL) {
		if (*tb == NULL)
			*tb = initial_tb;
		else
			Py_DECREF(initial_tb);
	}
	/* normalize recursively */
	PyErr_NormalizeException(exc, val, tb);
}