예제 #1
0
VOID CALLBACK
py_win32_timer_callback (HWND hwnd, UINT msg, UINT_PTR timer_id, DWORD time)
{
	CEnterLeavePython _celp;
	PyObject * py_timer_id = PyWinLong_FromVoidPtr((void *)timer_id);
	if (!py_timer_id){
		PyErr_Print();
		return;
		}
	// is this timer id recognized?
	PyObject * callback_function = PyDict_GetItem (timer_id_callback_map, py_timer_id);
	if (!callback_function){
		::KillTimer (NULL, timer_id);
		PyErr_Warn(PyExc_RuntimeWarning, "Unrecognized timer id");
		Py_DECREF(py_timer_id);
		return;
		}
	// call the user's function
	// create a 'death grip' on the callback function, just incase
	// the callback itself removes the function from the map.
	Py_INCREF(callback_function);
	PyObject * callback_args = Py_BuildValue ("(Ok)", py_timer_id, time);
	PyObject * result = PyEval_CallObject (callback_function, callback_args);

	if (!result) {
		// Is this necessary, or will python already have flagged
		// an exception?  Can we even catch exceptions here?
		PyErr_Print();
		}

	// everything's ok, return
	Py_DECREF(callback_function);
	Py_XDECREF(callback_args);
	Py_XDECREF(result);
	Py_DECREF (py_timer_id);
	return;
}
예제 #2
0
static int
already_warned(PyObject *registry, PyObject *key, int should_set)
{
    PyObject *version_obj, *already_warned;
    _Py_IDENTIFIER(version);

    if (key == NULL)
        return -1;

    version_obj = _PyDict_GetItemId(registry, &PyId_version);
    if (version_obj == NULL
        || !PyLong_CheckExact(version_obj)
        || PyLong_AsLong(version_obj) != _filters_version) {
        PyDict_Clear(registry);
        version_obj = PyLong_FromLong(_filters_version);
        if (version_obj == NULL)
            return -1;
        if (_PyDict_SetItemId(registry, &PyId_version, version_obj) < 0) {
            Py_DECREF(version_obj);
            return -1;
        }
        Py_DECREF(version_obj);
    }
    else {
        already_warned = PyDict_GetItem(registry, key);
        if (already_warned != NULL) {
            int rc = PyObject_IsTrue(already_warned);
            if (rc != 0)
                return rc;
        }
    }

    /* This warning wasn't found in the registry, set it. */
    if (should_set)
        return PyDict_SetItem(registry, key, Py_True);
    return 0;
}
예제 #3
0
static PyObject *t_tzinfo_getInstance(PyTypeObject *cls, PyObject *id)
{
    PyObject *instance = PyDict_GetItem(_instances, id);

    if (instance)
    {
        Py_INCREF(instance);
        return instance;
    }

    int cmp = PyObject_RichCompareBool(id, FLOATING_TZNAME, Py_EQ);
    if (cmp == -1)
        return NULL;
    if (cmp)
        instance = t_tzinfo_getFloating(cls);
    else
    {
        PyObject *tz = t_timezone_createTimeZone(&TimeZoneType_, id);

        if (!tz)
            return NULL;

#if PY_VERSION_HEX < 0x02040000
        PyObject *args = Py_BuildValue("(O)", tz);
#else
        PyObject *args = PyTuple_Pack(1, tz);
#endif
        instance = PyObject_Call((PyObject *) &TZInfoType_, args, NULL);
        Py_DECREF(args);
        Py_DECREF(tz);
    }

    if (instance)
        PyDict_SetItem(_instances, id, instance);

    return instance;
}
예제 #4
0
NUITKA_MAY_BE_UNUSED static PyObject *DICT_GET_ITEM( PyObject *dict, PyObject *key )
{
    CHECK_OBJECT( dict );
    assert( PyDict_CheckExact( dict ) );

    CHECK_OBJECT( key );

    PyObject *result = PyDict_GetItem( dict, key );

    if ( result == NULL )
    {
        if (unlikely( PyErr_Occurred() ))
        {
            return NULL;
        }

        /* Wrap all kinds of tuples, because normalization will later unwrap
         * it, but then that changes the key for the KeyError, which is not
         * welcome. The check is inexact, as the unwrapping one is too.
         */
        if ( PyTuple_Check( key ) )
        {
            PyObject *tuple = PyTuple_Pack( 1, key );
            PyErr_SetObject( PyExc_KeyError, tuple );
            Py_DECREF( tuple );
        }
        else
        {
            PyErr_SetObject( PyExc_KeyError, key );
        }
        return NULL;
    }
    else
    {
        return INCREASE_REFCOUNT( result );
    }
}
예제 #5
0
/**
 * Interface for AtkUtilClass->remove_global_event_listener.
 */
static void
_class_remove_global_event_listener (guint listener_id)
{
    PyObject *dict = NULL;
    PyObject *obj = NULL;
    PyObject *key = NULL;
    int pos = 0;

    debug ("_class_remove_global_event_listener\n");

    key = PyInt_FromLong ((long) listener_id);
    while (PyDict_Next (_global_listeners, &pos, NULL, &dict))
    {
        obj = PyDict_GetItem (dict, key);
        if (obj)
        {
            PyDict_DelItem (dict, key);
            Py_DECREF (key);
            return;
        }
    }
    Py_DECREF (key);
    return;
}
예제 #6
0
/*
   Returns a new reference.
   A NULL return value can mean false or an error.
*/
static PyObject *
get_warnings_attr(const char *attr)
{
    static PyObject *warnings_str = NULL;
    PyObject *all_modules;
    PyObject *warnings_module;
    int result;

    if (warnings_str == NULL) {
        warnings_str = PyString_InternFromString("warnings");
        if (warnings_str == NULL)
            return NULL;
    }

    all_modules = PyImport_GetModuleDict();
    result = PyDict_Contains(all_modules, warnings_str);
    if (result == -1 || result == 0)
        return NULL;

    warnings_module = PyDict_GetItem(all_modules, warnings_str);
    if (!PyObject_HasAttrString(warnings_module, attr))
            return NULL;
    return PyObject_GetAttrString(warnings_module, attr);
}
예제 #7
0
NUITKA_MAY_BE_UNUSED static PyObject *DICT_GET_ITEM( PyObject *dict, PyObject *key )
{
    CHECK_OBJECT( dict );
    assert( PyDict_Check( dict ) );

    CHECK_OBJECT( key );

    PyObject *result = PyDict_GetItem( dict, key );

    if ( result == NULL )
    {
        if (unlikely( PyErr_Occurred() ))
        {
            return NULL;
        }

        PyErr_SetObject( PyExc_KeyError, key );
        return NULL;
    }
    else
    {
        return INCREASE_REFCOUNT( result );
    }
}
예제 #8
0
파일: serial.c 프로젝트: alonho/pytrace
void handle_call(PyFrameObject *frame) {
  PyObject *name, *value;
  int i, argcount, count = 0;
  increment_depth();
  if (in_no_trace_context()) {
    return;
  }
  if (FALSE == should_trace_frame(frame)) {
    enter_no_trace_context();
    return;
  }

  argcount = frame->f_code->co_argcount;
  if (frame->f_code->co_flags & CO_VARARGS) {
    argcount++;
  }
  if (frame->f_code->co_flags & CO_VARKEYWORDS) {
    argcount++;
  }

  for (i = 0; i < min(argcount, MAX_ARGS); i++) {
    name = PyTuple_GetItem(frame->f_code->co_varnames, i);
    if (NULL == frame->f_locals) {
      value = frame->f_localsplus[i];
    } else {
      value = PyDict_GetItem(frame->f_locals, name);
    }
    if (NULL != value) { // happens when exec is used
      set_string(&(arguments[i]->name), PYSTR_TO_CHAR(name));
      set_string(&(arguments[i]->type), value->ob_type->tp_name);
      set_string(&(arguments[i]->value), pyobj_to_cstr(value));
      count++;
    }
  }
  handle_trace(frame, RECORD__RECORD_TYPE__CALL, count);
}
예제 #9
0
/**
 * Removes an entry from the runloop-for-emitter dictionary for the given
 * emitter thread.
 *
 * :param emitter_thread:
 *     The emitter thread for which the dictionary entry will be removed.
 * :type emitter_thread:
 *     A pointer to a Python object representing the emitter thread.
 * :returns:
 *     The same as :func:`PyDict_DelItem`
 */
int
Watchdog_CFRunLoopForEmitter_DelItem(PyObject *emitter_thread)
{
    CFRunLoopRef emitter_runloop = NULL;
    int return_value = 0;
    // refcount(emitter_thread) = 2
    // refcount(emitter_runloop) = 2
    // from previous successful addition to the dict.
    emitter_runloop = PyDict_GetItem(g__runloop_for_emitter, emitter_thread);
    RETURN_IF(NULL == emitter_runloop);

    return_value = PyDict_DelItem(g__runloop_for_emitter, emitter_thread);
    if (0 == return_value)
        {
            // Success!
            // refcount(emitter_thread) = 1
            // refcount(emitter_runloop) = 1
            Py_DECREF(emitter_runloop);
            // refcount(emitter_runloop) = 0
            // refcount(emitter_thread) = 1
            // back to python land.
        }
    return return_value;
}
예제 #10
0
PyObject*
pyg_flags_from_gtype (GType gtype, int value)
{
    PyObject *pyclass, *values, *retval, *pyint;

    g_return_val_if_fail(gtype != G_TYPE_INVALID, NULL);

    /* Get a wrapper class by:
     * 1. check for one attached to the gtype
     * 2. lookup one in a typelib
     * 3. creating a new one
     */
    pyclass = (PyObject*)g_type_get_qdata(gtype, pygflags_class_key);
    if (!pyclass)
        pyclass = pygi_type_import_by_g_type(gtype);
    if (!pyclass)
        pyclass = pyg_flags_add(NULL, g_type_name(gtype), NULL, gtype);
    if (!pyclass)
	return PYGLIB_PyLong_FromLong(value);

    values = PyDict_GetItemString(((PyTypeObject *)pyclass)->tp_dict,
				  "__flags_values__");
    pyint = PYGLIB_PyLong_FromLong(value);
    retval = PyDict_GetItem(values, pyint);
    if (!retval) {
	PyErr_Clear();

	retval = pyg_flags_val_new(pyclass, gtype, pyint);
	g_assert(retval != NULL);
    } else {
	Py_INCREF(retval);
    }
    Py_DECREF(pyint);
    
    return retval;
}
예제 #11
0
static int
unpack_add_info(LogReaderObject *self)
{
    PyObject *key;
    PyObject *value = NULL;
    int err;

    err = unpack_string(self, &key);
    if (!err) {
        err = unpack_string(self, &value);
        if (err)
            Py_DECREF(key);
        else {
            PyObject *list = PyDict_GetItem(self->info, key);
            if (list == NULL) {
                list = PyList_New(0);
                if (list == NULL) {
                    err = ERR_EXCEPTION;
                    goto finally;
                }
                if (PyDict_SetItem(self->info, key, list)) {
                    Py_DECREF(list);
                    err = ERR_EXCEPTION;
                    goto finally;
                }
                Py_DECREF(list);
            }
            if (PyList_Append(list, value))
                err = ERR_EXCEPTION;
        }
    }
 finally:
    Py_XDECREF(key);
    Py_XDECREF(value);
    return err;
}
예제 #12
0
PyObject* GetConnectionInfo(PyObject* pConnectionString, Connection* cnxn)
{
    // Looks-up or creates a CnxnInfo object for the given connection string.  The connection string can be a Unicode
    // or String object.

    Object hash(GetHash(pConnectionString));

    if (hash.IsValid())
    {
        PyObject* info = PyDict_GetItem(map_hash_to_info, hash);

        if (info)
        {
            Py_INCREF(info);
            return info;
        }
    }

    PyObject* info = CnxnInfo_New(cnxn);
    if (info != 0 && hash.IsValid())
        PyDict_SetItem(map_hash_to_info, hash, info);

    return info;
}
예제 #13
0
파일: callproc.c 프로젝트: pieper/python
/*
  This function creates and returns a thread-local Python object that has
  space to store two integer error numbers; once created the Python object is
  kept alive in the thread state dictionary as long as the thread itself.
*/
PyObject *
get_error_object(int **pspace)
{
	PyObject *dict = PyThreadState_GetDict();
	PyObject *errobj;
	static PyObject *error_object_name;
	if (dict == 0) {
		PyErr_SetString(PyExc_RuntimeError,
				"cannot get thread state");
		return NULL;
	}
	if (error_object_name == NULL) {
		error_object_name = PyString_InternFromString("ctypes.error_object");
		if (error_object_name == NULL)
			return NULL;
	}
	errobj = PyDict_GetItem(dict, error_object_name);
	if (errobj)
		Py_INCREF(errobj);
	else {
		void *space = PyMem_Malloc(sizeof(int) * 2);
		if (space == NULL)
			return NULL;
		memset(space, 0, sizeof(int) * 2);
		errobj = PyCObject_FromVoidPtr(space, PyMem_Free);
		if (errobj == NULL)
			return NULL;
		if (-1 == PyDict_SetItem(dict, error_object_name,
					 errobj)) {
			Py_DECREF(errobj);
			return NULL;
		}
	}
	*pspace = (int *)PyCObject_AsVoidPtr(errobj);
	return errobj;
}
예제 #14
0
파일: buffer.c 프로젝트: Linxiao-Chen/numpy
/* Clear buffer info from the global dictionary */
static void
_buffer_clear_info(PyObject *arr)
{
    PyObject *key, *item_list, *item;
    _buffer_info_t *info;
    int k;

    if (_buffer_info_cache == NULL) {
        return;
    }

    key = PyLong_FromVoidPtr((void*)arr);
    item_list = PyDict_GetItem(_buffer_info_cache, key);
    if (item_list != NULL) {
        for (k = 0; k < PyList_GET_SIZE(item_list); ++k) {
            item = PyList_GET_ITEM(item_list, k);
            info = (_buffer_info_t*)PyLong_AsVoidPtr(item);
            _buffer_info_free(info);
        }
        PyDict_DelItem(_buffer_info_cache, key);
    }

    Py_DECREF(key);
}
예제 #15
0
/*
  This function creates and returns a thread-local Python object that has
  space to store two integer error numbers; once created the Python object is
  kept alive in the thread state dictionary as long as the thread itself.
*/
PyObject *
_ctypes_get_errobj(int **pspace)
{
	PyObject *dict = PyThreadState_GetDict();
	PyObject *errobj;
	static PyObject *error_object_name;
	if (dict == 0) {
		PyErr_SetString(PyExc_RuntimeError,
				"cannot get thread state");
		return NULL;
	}
	if (error_object_name == NULL) {
		error_object_name = PyUnicode_InternFromString("ctypes.error_object");
		if (error_object_name == NULL)
			return NULL;
	}
	errobj = PyDict_GetItem(dict, error_object_name);
	if (errobj)
		Py_INCREF(errobj);
	else {
		void *space = PyMem_Malloc(sizeof(int) * 2);
		if (space == NULL)
			return NULL;
		memset(space, 0, sizeof(int) * 2);
		errobj = PyCapsule_New(space, CTYPES_CAPSULE_NAME_PYMEM, pymem_destructor);
		if (errobj == NULL)
			return NULL;
		if (-1 == PyDict_SetItem(dict, error_object_name,
					 errobj)) {
			Py_DECREF(errobj);
			return NULL;
		}
	}
	*pspace = (int *)PyCapsule_GetPointer(errobj, CTYPES_CAPSULE_NAME_PYMEM);
	return errobj;
}
예제 #16
0
파일: jcc.cpp 프로젝트: ahua/java
static PyObject *t_jccenv__dumpRefs(PyObject *self,
                                    PyObject *args, PyObject *kwds)
{
    static char *kwnames[] = {
        "classes", "values", NULL
    };
    int classes = 0, values = 0;
    PyObject *result;

    if (!PyArg_ParseTupleAndKeywords(args, kwds, "|ii", kwnames,
                                     &classes, &values))
        return NULL;

    if (classes)
        result = PyDict_New();
    else
        result = PyList_New(env->refs.size());

    int count = 0;

    for (std::multimap<int, countedRef>::iterator iter = env->refs.begin();
         iter != env->refs.end();
         iter++) {
        if (classes)  // return dict of { class name: instance count }
        {
            char *name = env->getClassName(iter->second.global);
            PyObject *key = PyString_FromString(name);
            PyObject *value = PyDict_GetItem(result, key);

            if (value == NULL)
                value = PyInt_FromLong(1);
            else
                value = PyInt_FromLong(PyInt_AS_LONG(value) + 1);

            PyDict_SetItem(result, key, value);
            Py_DECREF(key);
            Py_DECREF(value);

            delete name;
        }
        else if (values)  // return list of (value string, ref count)
        {
            char *str = env->toString(iter->second.global);
            PyObject *key = PyString_FromString(str);
            PyObject *value = PyInt_FromLong(iter->second.count);

#if PY_VERSION_HEX < 0x02040000
            PyList_SET_ITEM(result, count++, Py_BuildValue("(OO)", key, value));
#else
            PyList_SET_ITEM(result, count++, PyTuple_Pack(2, key, value));
#endif
            Py_DECREF(key);
            Py_DECREF(value);

            delete str;
        }
        else  // return list of (id hash code, ref count)
        {
            PyObject *key = PyInt_FromLong(iter->first);
            PyObject *value = PyInt_FromLong(iter->second.count);

#if PY_VERSION_HEX < 0x02040000
            PyList_SET_ITEM(result, count++, Py_BuildValue("(OO)", key, value));
#else
            PyList_SET_ITEM(result, count++, PyTuple_Pack(2, key, value));
#endif
            Py_DECREF(key);
            Py_DECREF(value);
        }
    }

    return result;
}
예제 #17
0
static PyObject *bpy_user_map(PyObject *UNUSED(self), PyObject *args, PyObject *kwds)
{
#if 0  /* If someone knows how to get a proper 'self' in that case... */
	BPy_StructRNA *pyrna = (BPy_StructRNA *)self;
	Main *bmain = pyrna->ptr.data;
#else
	Main *bmain = G.main;  /* XXX Ugly, but should work! */
#endif

	static const char *kwlist[] = {"subset", "key_types", "value_types", NULL};
	PyObject *subset = NULL;

	PyObject *key_types = NULL;
	PyObject *val_types = NULL;
	BLI_bitmap *key_types_bitmap = NULL;
	BLI_bitmap *val_types_bitmap = NULL;

	PyObject *ret = NULL;


	if (!PyArg_ParseTupleAndKeywords(
	        args, kwds, "|O$O!O!:user_map", (char **)kwlist,
	        &subset,
	        &PySet_Type, &key_types,
	        &PySet_Type, &val_types))
	{
		return NULL;
	}

	if (key_types) {
		key_types_bitmap = pyrna_set_to_enum_bitmap(
		        rna_enum_id_type_items, key_types, sizeof(short), true, USHRT_MAX, "key types");
		if (key_types_bitmap == NULL) {
			goto error;
		}
	}

	if (val_types) {
		val_types_bitmap = pyrna_set_to_enum_bitmap(
		        rna_enum_id_type_items, val_types, sizeof(short), true, USHRT_MAX, "value types");
		if (val_types_bitmap == NULL) {
			goto error;
		}
	}

	IDUserMapData data_cb = {NULL};

	if (subset) {
		PyObject *subset_fast = PySequence_Fast(subset, "user_map");
		if (subset_fast == NULL) {
			goto error;
		}

		PyObject **subset_array = PySequence_Fast_ITEMS(subset_fast);
		Py_ssize_t subset_len = PySequence_Fast_GET_SIZE(subset_fast);

		data_cb.user_map = _PyDict_NewPresized(subset_len);
		data_cb.is_subset = true;
		for (; subset_len; subset_array++, subset_len--) {
			PyObject *set = PySet_New(NULL);
			PyDict_SetItem(data_cb.user_map, *subset_array, set);
			Py_DECREF(set);
		}
		Py_DECREF(subset_fast);
	}
	else {
		data_cb.user_map = PyDict_New();
	}

	data_cb.types_bitmap = key_types_bitmap;

	ListBase *lb_array[MAX_LIBARRAY];
	int lb_index;
	lb_index = set_listbasepointers(bmain, lb_array);

	while (lb_index--) {

		if (val_types_bitmap && lb_array[lb_index]->first) {
			if (!id_check_type(lb_array[lb_index]->first, val_types_bitmap)) {
				continue;
			}
		}

		for (ID *id = lb_array[lb_index]->first; id; id = id->next) {
			/* One-time init, ID is just used as placeholder here, we abuse this in iterator callback
			 * to avoid having to rebuild a complete bpyrna object each time for the key searching
			 * (where only ID pointer value is used). */
			if (data_cb.py_id_key_lookup_only == NULL) {
				data_cb.py_id_key_lookup_only = pyrna_id_CreatePyObject(id);
			}

			if (!data_cb.is_subset) {
				PyObject *key = data_cb.py_id_key_lookup_only;
				PyObject *set;

				RNA_id_pointer_create(id, &((BPy_StructRNA *)key)->ptr);

				/* We have to insert the key now, otherwise ID unused would be missing from final dict... */
				if ((set = PyDict_GetItem(data_cb.user_map, key)) == NULL) {
					/* Cannot use our placeholder key here! */
					key = pyrna_id_CreatePyObject(id);
					set = PySet_New(NULL);
					PyDict_SetItem(data_cb.user_map, key, set);
					Py_DECREF(set);
					Py_DECREF(key);
				}
			}

			data_cb.id_curr = id;
			BKE_library_foreach_ID_link(id, foreach_libblock_id_user_map_callback, &data_cb, IDWALK_NOP);

			if (data_cb.py_id_curr) {
				Py_DECREF(data_cb.py_id_curr);
				data_cb.py_id_curr = NULL;
			}
		}
	}

	ret = data_cb.user_map;


error:

	Py_XDECREF(data_cb.py_id_key_lookup_only);

	if (key_types_bitmap) {
		MEM_freeN(key_types_bitmap);
	}

	if (val_types_bitmap) {
		MEM_freeN(val_types_bitmap);
	}

	return ret;

}
예제 #18
0
파일: codecs.c 프로젝트: 0xcc/python-read
PyObject *_PyCodec_Lookup(const char *encoding)
{
    PyInterpreterState *interp;
    PyObject *result, *args = NULL, *v;
    Py_ssize_t i, len;

    if (encoding == NULL) {
        PyErr_BadArgument();
        goto onError;
    }

    interp = PyThreadState_GET()->interp;
    if (interp->codec_search_path == NULL && _PyCodecRegistry_Init())
        goto onError;

    /* Convert the encoding to a normalized Python string: all
       characters are converted to lower case, spaces and hyphens are
       replaced with underscores. */
    v = normalizestring(encoding);
    if (v == NULL)
        goto onError;
    PyString_InternInPlace(&v);

    /* First, try to lookup the name in the registry dictionary */
    result = PyDict_GetItem(interp->codec_search_cache, v);
    if (result != NULL) {
        Py_INCREF(result);
        Py_DECREF(v);
        return result;
    }

    /* Next, scan the search functions in order of registration */
    args = PyTuple_New(1);
    if (args == NULL)
        goto onError;
    PyTuple_SET_ITEM(args,0,v);

    len = PyList_Size(interp->codec_search_path);
    if (len < 0)
        goto onError;
    if (len == 0) {
        PyErr_SetString(PyExc_LookupError,
                        "no codec search functions registered: "
                        "can't find encoding");
        goto onError;
    }

    for (i = 0; i < len; i++) {
        PyObject *func;

        func = PyList_GetItem(interp->codec_search_path, i);
        if (func == NULL)
            goto onError;
        result = PyEval_CallObject(func, args);
        if (result == NULL)
            goto onError;
        if (result == Py_None) {
            Py_DECREF(result);
            continue;
        }
        if (!PyTuple_Check(result) || PyTuple_GET_SIZE(result) != 4) {
            PyErr_SetString(PyExc_TypeError,
                            "codec search functions must return 4-tuples");
            Py_DECREF(result);
            goto onError;
        }
        break;
    }
    if (i == len) {
        /* XXX Perhaps we should cache misses too ? */
        PyErr_Format(PyExc_LookupError,
                     "unknown encoding: %s", encoding);
        goto onError;
    }

    /* Cache and return the result */
    PyDict_SetItem(interp->codec_search_cache, v, result);
    Py_DECREF(args);
    return result;

 onError:
    Py_XDECREF(args);
    return NULL;
}
예제 #19
0
파일: Builtins.c 프로젝트: B-Rich/cython
static PyObject* __Pyx_PyExec3(PyObject* o, PyObject* globals, PyObject* locals) {
    PyObject* result;
    PyObject* s = 0;
    char *code = 0;

    if (!globals || globals == Py_None) {
        globals = PyModule_GetDict($module_cname);
        if (!globals)
            goto bad;
    } else if (!PyDict_Check(globals)) {
        PyErr_Format(PyExc_TypeError, "exec() arg 2 must be a dict, not %.200s",
                     Py_TYPE(globals)->tp_name);
        goto bad;
    }
    if (!locals || locals == Py_None) {
        locals = globals;
    }

    if (PyDict_GetItem(globals, PYIDENT("__builtins__")) == NULL) {
        if (PyDict_SetItem(globals, PYIDENT("__builtins__"), PyEval_GetBuiltins()) < 0)
            goto bad;
    }

    if (PyCode_Check(o)) {
        if (PyCode_GetNumFree((PyCodeObject *)o) > 0) {
            PyErr_SetString(PyExc_TypeError,
                "code object passed to exec() may not contain free variables");
            goto bad;
        }
        #if PY_VERSION_HEX < 0x030200B1
        result = PyEval_EvalCode((PyCodeObject *)o, globals, locals);
        #else
        result = PyEval_EvalCode(o, globals, locals);
        #endif
    } else {
        PyCompilerFlags cf;
        cf.cf_flags = 0;
        if (PyUnicode_Check(o)) {
            cf.cf_flags = PyCF_SOURCE_IS_UTF8;
            s = PyUnicode_AsUTF8String(o);
            if (!s) goto bad;
            o = s;
        #if PY_MAJOR_VERSION >= 3
        } else if (!PyBytes_Check(o)) {
        #else
        } else if (!PyString_Check(o)) {
        #endif
            PyErr_Format(PyExc_TypeError,
                "exec: arg 1 must be string, bytes or code object, got %.200s",
                Py_TYPE(o)->tp_name);
            goto bad;
        }
        #if PY_MAJOR_VERSION >= 3
        code = PyBytes_AS_STRING(o);
        #else
        code = PyString_AS_STRING(o);
        #endif
        if (PyEval_MergeCompilerFlags(&cf)) {
            result = PyRun_StringFlags(code, Py_file_input, globals, locals, &cf);
        } else {
            result = PyRun_String(code, Py_file_input, globals, locals);
        }
        Py_XDECREF(s);
    }

    return result;
bad:
    Py_XDECREF(s);
    return 0;
}
예제 #20
0
PyObject* xcsoar_Airspaces_findIntrusions(Pyxcsoar_Airspaces *self, PyObject *args) {
  PyObject *py_flight = nullptr;

  if (!PyArg_ParseTuple(args, "O", &py_flight)) {
    PyErr_SetString(PyExc_AttributeError, "Can't parse argument.");
    return nullptr;
  }

  DebugReplay *replay = ((Pyxcsoar_Flight*)py_flight)->flight->Replay();

  if (replay == nullptr) {
    PyErr_SetString(PyExc_IOError, "Can't start replay - file not found.");
    return nullptr;
  }

  PyObject *py_result = PyDict_New();
  Airspaces::AirspaceVector last_airspaces;

  while (replay->Next()) {
    const MoreData &basic = replay->Basic();

    if (!basic.time_available || !basic.location_available ||
        !basic.NavAltitudeAvailable())
      continue;

    Airspaces::AirspaceVector airspaces = self->airspace_database->FindInside(
      ToAircraftState(basic, replay->Calculated())
    );

    for (auto it = airspaces.begin(); it != airspaces.end(); it++) {
      PyObject *py_name = PyString_FromString((*it).GetAirspace().GetName());
      PyObject *py_airspace = nullptr,
               *py_period = nullptr;

      if (PyDict_Contains(py_result, py_name) == 0) {
        // this is the first fix inside this airspace
        py_airspace = PyList_New(0);
        PyDict_SetItem(py_result, py_name, py_airspace);

        py_period = PyList_New(0);
        PyList_Append(py_airspace, py_period);
        Py_DECREF(py_period);

      } else {
        // this airspace was hit some time before...
        py_airspace = PyDict_GetItem(py_result, py_name);

        // check if the last fix was already inside this airspace
        auto in_last = std::find(last_airspaces.begin(), last_airspaces.end(), *it);

        if (in_last == last_airspaces.end()) {
          // create a new period
          py_period = PyList_New(0);
          PyList_Append(py_airspace, py_period);
          Py_DECREF(py_period);
        } else {
          py_period = PyList_GET_ITEM(py_airspace, PyList_GET_SIZE(py_airspace) - 1);
        }
      }

      PyList_Append(py_period, Py_BuildValue("{s:N,s:N}",
        "time", Python::BrokenDateTimeToPy(basic.date_time_utc),
        "location", Python::WriteLonLat(basic.location)));
    }

    last_airspaces.swap(airspaces);
  }

  delete replay;

  return py_result;
}
예제 #21
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;
}
예제 #22
0
파일: skipdict.c 프로젝트: malthe/skipdict
    slIterDel(it->iter);
    Py_XDECREF(it->skipdict);
    PyObject_GC_Del(it);
}

static int
skipdictiter_traverse(SkipDictIterObject *it, visitproc visit, void *arg)
{
    Py_VISIT(it->skipdict);
    return 0;
}

static int
skipdict_delitem(SkipDictObject *self, PyObject *key, int delete)
{
    PyObject* item = PyDict_GetItem(self->mapping, key);
    if (!item) goto Fail;
    PyObject* value = PyTuple_GET_ITEM(item, 1);
    if (delete) PyDict_DelItem(self->mapping, key);
    if (!slDelete(self->skiplist, PyFloat_AsDouble(value), (void*) item, 0)) {
        goto Fail;
    }
    return 0;
 Fail:
    PyErr_SetObject(PyExc_KeyError, key);
    return -1;
}

static int
skipdict_insertobj(SkipDictObject *self, PyObject *key, PyObject *value,
                   int mode)
예제 #23
0
파일: greenlet.c 프로젝트: vietlq/greenlet
static int green_updatecurrent(void)
{
	PyObject *exc, *val, *tb;
	PyThreadState* tstate;
	PyGreenlet* current;
	PyGreenlet* previous;
	PyObject* deleteme;

	/* save current exception */
	PyErr_Fetch(&exc, &val, &tb);

	/* get ts_current from the active tstate */
	tstate = PyThreadState_GET();
	if (tstate->dict && (current =
	    (PyGreenlet*) PyDict_GetItem(tstate->dict, ts_curkey))) {
		/* found -- remove it, to avoid keeping a ref */
		Py_INCREF(current);
		PyDict_DelItem(tstate->dict, ts_curkey);
	}
	else {
		/* first time we see this tstate */
		current = green_create_main();
		if (current == NULL) {
			Py_XDECREF(exc);
			Py_XDECREF(val);
			Py_XDECREF(tb);
			return -1;
		}
	}

green_updatecurrent_retry:
	/* update ts_current as soon as possible, in case of nested switches */
	Py_INCREF(current);
	previous = ts_current;
	ts_current = current;

	/* save ts_current as the current greenlet of its own thread */
	if (PyDict_SetItem(previous->run_info, ts_curkey, (PyObject*) previous)) {
		Py_DECREF(previous);
		Py_DECREF(current);
		Py_XDECREF(exc);
		Py_XDECREF(val);
		Py_XDECREF(tb);
		return -1;
	}
	Py_DECREF(previous);

	/* green_dealloc() cannot delete greenlets from other threads, so
	   it stores them in the thread dict; delete them now. */
	deleteme = PyDict_GetItem(tstate->dict, ts_delkey);
	if (deleteme != NULL) {
		PyList_SetSlice(deleteme, 0, INT_MAX, NULL);
	}

	if (ts_current != current) {
		/* some Python code executed above and there was a thread switch,
		 * so ts_current points to some other thread again. We need to
		 * delete ts_curkey (it's likely there) and retry. */
		PyDict_DelItem(tstate->dict, ts_curkey);
		goto green_updatecurrent_retry;
	}

	/* release an extra reference */
	Py_DECREF(current);

	/* restore current exception */
	PyErr_Restore(exc, val, tb);

	return 0;
}
예제 #24
0
static
PyObject* Capsule_GetClass(CapsuleObject *self){
    PyObject *pycls = GetClassesDict();
    auto_pyobject key = GetClassName(self->capsule);
    return PyDict_GetItem(pycls, *key);    // borrowed reference
}
예제 #25
0
TerrainChunk* terrain_chunk_read(Reader* r, int version) {
    PyObject* block_type_table = NULL;

    TerrainChunk* tc = (TerrainChunk*)PyObject_CallObject((PyObject*)&TerrainChunkType, NULL);
    FAIL_IF(tc == NULL);

    tc->version = version;
    tc->save = calloc(sizeof(TerrainChunkSave), 1);

    READ(tc->save->save_id);
    FAIL_IF(read_register_object(r, tc->save->save_id, (PyObject*)tc) < 0);
    READ(tc->stable_id);


    if (version >= 5) {
        READ(tc->flags);
    }

    uint16_t buf[1 << (3 * CHUNK_BITS)];
    READ(buf);

    block_type_table = read_block_type_table(r);
    FAIL_IF(block_type_table == NULL);
    for (int i = 0; i < 1 << (3 * CHUNK_BITS); ++i) {
        PyObject* key = PyLong_FromLong(buf[i]);
        FAIL_IF(key == NULL);

        PyObject* value = PyDict_GetItem(block_type_table, key);
        if (value == NULL) {
            Py_DECREF(key);
            goto fail;
        }

        Py_INCREF(value);
        if (PyList_SetItem(tc->blocks, i, value) < 0) {
            // XXX: SetItem does steal the reference even on failure, right?
            Py_DECREF(key);
            goto fail;
        }
    }
    Py_DECREF(block_type_table);
    block_type_table = NULL;


    // No script extras for TerrainChunk yet.
    if (version >= 999999) {
        tc->save->extra_raw = extra_read(r, version);
        FAIL_IF(tc->save->extra_raw  == NULL);
    } else {
        Py_INCREF(Py_None);
        tc->save->extra_raw = Py_None;
    }


    uint32_t count;
    READ(count);
    for (uint32_t i = 0; i < count; ++i) {
        Structure* obj = structure_read(r, version);
        FAIL_IF(obj == NULL);
        FAIL_IF(PyList_Append(tc->child_structures, (PyObject*)obj) == -1);
    }

    return tc;

fail:
    SET_EXC();
    Py_XDECREF(tc);
    Py_XDECREF(block_type_table);
    return NULL;
}
예제 #26
0
MOD_INIT_DECL( Crypto$Util )
{

#if defined(_NUITKA_EXE) || PYTHON_VERSION >= 300
    static bool _init_done = false;

    // Packages can be imported recursively in deep executables.
    if ( _init_done )
    {
        return MOD_RETURN_VALUE( module_Crypto$Util );
    }
    else
    {
        _init_done = true;
    }
#endif

#ifdef _NUITKA_MODULE
    // In case of a stand alone extension module, need to call initialization
    // the init here because that's the first and only time we are going to get
    // called here.

    // Initialize the constant values used.
    _initBuiltinModule();
    _initConstants();

    // Initialize the compiled types of Nuitka.
    PyType_Ready( &Nuitka_Generator_Type );
    PyType_Ready( &Nuitka_Function_Type );
    PyType_Ready( &Nuitka_Method_Type );
    PyType_Ready( &Nuitka_Frame_Type );
#if PYTHON_VERSION < 300
    initSlotCompare();
#endif

    patchBuiltinModule();
    patchTypeComparison();

#endif

#if _MODULE_UNFREEZER
    registerMetaPathBasedUnfreezer( meta_path_loader_entries );
#endif

    _initModuleConstants();
    _initModuleCodeObjects();

    // puts( "in initCrypto$Util" );

    // Create the module object first. There are no methods initially, all are
    // added dynamically in actual code only.  Also no "__doc__" is initially
    // set at this time, as it could not contain NUL characters this way, they
    // are instead set in early module code.  No "self" for modules, we have no
    // use for it.
#if PYTHON_VERSION < 300
    module_Crypto$Util = Py_InitModule4(
        "Crypto.Util",       // Module Name
        NULL,                    // No methods initially, all are added
                                 // dynamically in actual module code only.
        NULL,                    // No __doc__ is initially set, as it could
                                 // not contain NUL this way, added early in
                                 // actual code.
        NULL,                    // No self for modules, we don't use it.
        PYTHON_API_VERSION
    );
#else
    module_Crypto$Util = PyModule_Create( &mdef_Crypto$Util );
#endif

    moduledict_Crypto$Util = (PyDictObject *)((PyModuleObject *)module_Crypto$Util)->md_dict;

    assertObject( module_Crypto$Util );

// Seems to work for Python2.7 out of the box, but for Python3, the module
// doesn't automatically enter "sys.modules", so do it manually.
#if PYTHON_VERSION >= 300
    {
        int r = PyObject_SetItem( PySys_GetObject( (char *)"modules" ), const_str_digest_84c8a7acde99de10deb810738421e657, module_Crypto$Util );

        assert( r != -1 );
    }
#endif

    // For deep importing of a module we need to have "__builtins__", so we set
    // it ourselves in the same way than CPython does. Note: This must be done
    // before the frame object is allocated, or else it may fail.

    PyObject *module_dict = PyModule_GetDict( module_Crypto$Util );

    if ( PyDict_GetItem( module_dict, const_str_plain___builtins__ ) == NULL )
    {
        PyObject *value = (PyObject *)builtin_module;

        // Check if main module, not a dict then.
#if !defined(_NUITKA_EXE) || !0
        value = PyModule_GetDict( value );
#endif

#ifndef __NUITKA_NO_ASSERT__
        int res =
#endif
            PyDict_SetItem( module_dict, const_str_plain___builtins__, value );

        assert( res == 0 );
    }

#if PYTHON_VERSION >= 330
#if _MODULE_UNFREEZER
    PyDict_SetItem( module_dict, const_str_plain___loader__, metapath_based_loader );
#else
    PyDict_SetItem( module_dict, const_str_plain___loader__, Py_None );
#endif
#endif

    // Temp variables if any
    PyObject *tmp_assign_source_1;
    PyObject *tmp_assign_source_2;
    PyObject *tmp_assign_source_3;
    PyObject *tmp_assign_source_4;
    PyObject *tmp_assign_source_5;

    // Module code.
    tmp_assign_source_1 = const_str_digest_2d19cbaeda533a9f2ae817323976daff;
    UPDATE_STRING_DICT0( moduledict_Crypto$Util, (Nuitka_StringObject *)const_str_plain___doc__, tmp_assign_source_1 );
    tmp_assign_source_2 = const_str_digest_ede8c8f1dce1a60961ad7994cb95ec71;
    UPDATE_STRING_DICT0( moduledict_Crypto$Util, (Nuitka_StringObject *)const_str_plain___file__, tmp_assign_source_2 );
    tmp_assign_source_3 = LIST_COPY( const_list_str_digest_8cacdff8c7fede7c8e3e11000eea2cbe_list );
    UPDATE_STRING_DICT1( moduledict_Crypto$Util, (Nuitka_StringObject *)const_str_plain___path__, tmp_assign_source_3 );
    tmp_assign_source_4 = LIST_COPY( const_list_c9502e80b601e4836ea5b2f226787166_list );
    UPDATE_STRING_DICT1( moduledict_Crypto$Util, (Nuitka_StringObject *)const_str_plain___all__, tmp_assign_source_4 );
    tmp_assign_source_5 = const_str_digest_e716a6839c8454d1d77f5308c1bdd157;
    UPDATE_STRING_DICT0( moduledict_Crypto$Util, (Nuitka_StringObject *)const_str_plain___revision__, tmp_assign_source_5 );

    return MOD_RETURN_VALUE( module_Crypto$Util );
}
예제 #27
0
static PyObject *
namespace_repr(PyObject *ns)
{
    int i, loop_error = 0;
    PyObject *pairs = NULL, *d = NULL, *keys = NULL, *keys_iter = NULL;
    PyObject *key;
    PyObject *separator, *pairsrepr, *repr = NULL;
    const char * name;

    name = (Py_TYPE(ns) == &_PyNamespace_Type) ? "namespace"
                                               : ns->ob_type->tp_name;

    i = Py_ReprEnter(ns);
    if (i != 0) {
        return i > 0 ? PyUnicode_FromFormat("%s(...)", name) : NULL;
    }

    pairs = PyList_New(0);
    if (pairs == NULL)
        goto error;

    d = ((_PyNamespaceObject *)ns)->ns_dict;
    assert(d != NULL);
    Py_INCREF(d);

    keys = PyDict_Keys(d);
    if (keys == NULL)
        goto error;
    if (PyList_Sort(keys) != 0)
        goto error;

    keys_iter = PyObject_GetIter(keys);
    if (keys_iter == NULL)
        goto error;

    while ((key = PyIter_Next(keys_iter)) != NULL) {
        if (PyUnicode_Check(key) && PyUnicode_GET_LENGTH(key) > 0) {
            PyObject *value, *item;

            value = PyDict_GetItem(d, key);
            assert(value != NULL);

            item = PyUnicode_FromFormat("%S=%R", key, value);
            if (item == NULL) {
                loop_error = 1;
            }
            else {
                loop_error = PyList_Append(pairs, item);
                Py_DECREF(item);
            }
        }

        Py_DECREF(key);
        if (loop_error)
            goto error;
    }

    separator = PyUnicode_FromString(", ");
    if (separator == NULL)
        goto error;

    pairsrepr = PyUnicode_Join(separator, pairs);
    Py_DECREF(separator);
    if (pairsrepr == NULL)
        goto error;

    repr = PyUnicode_FromFormat("%s(%S)", name, pairsrepr);
    Py_DECREF(pairsrepr);

error:
    Py_XDECREF(pairs);
    Py_XDECREF(d);
    Py_XDECREF(keys);
    Py_XDECREF(keys_iter);
    Py_ReprLeave(ns);

    return repr;
}
예제 #28
0
QList<PythonVariable> PythonEngine::variableList()
{
    QStringList filter_name;
    filter_name << "__builtins__" << "StdoutCatcher" << "python_engine_stdout" << "chdir"
                << "python_engine_get_completion_file" << "python_engine_get_completion_string"
                << "python_engine_get_completion_string_dot" << "PythonLabRopeProject"
                << "pythonlab_rope_project"
                << "python_engine_pyflakes_check";

    QStringList filter_type;
    filter_type << "builtin_function_or_method";

    QList<PythonVariable> list;

    PyObject *keys = PyDict_Keys(m_dict);
    for (int i = 0; i < PyList_Size(keys); ++i)
    {
        PyObject *key = PyList_GetItem(keys, i);
        PyObject *value = PyDict_GetItem(m_dict, key);

        // variable
        PythonVariable var;

        // variable name
        var.name = PyString_AsString(key);

        // variable type
        var.type = value->ob_type->tp_name;

        // variable value
        if (var.type == "bool")
        {
            var.value = PyInt_AsLong(value) ? "True" : "False";
        }
        else if (var.type == "int")
        {
            var.value = (int) PyInt_AsLong(value);
        }
        else if (var.type == "float")
        {
            var.value = PyFloat_AsDouble(value);
        }
        else if (var.type == "str")
        {
            var.value = PyString_AsString(value);
        }
        else if (var.type == "list")
        {
            var.value = QString("%1 items").arg(PyList_Size(value));
        }
        else if (var.type == "tuple")
        {
            var.value = QString("%1 items").arg(PyTuple_Size(value));
        }
        else if (var.type == "dict")
        {
            var.value = QString("%1 items").arg(PyDict_Size(value));
        }
        else if (var.type == "numpy.ndarray")
        {
            var.value = ""; //TODO count
        }
        else if (var.type == "module")
        {
            var.value = PyString_AsString(PyObject_GetAttrString(value, "__name__"));
        }
        else if (var.type == "function"
                 || var.type == "instance"
                 || var.type == "classobj")
        {
            // qDebug() << value->ob_type->tp_name;
        }

        // append
        if (!filter_name.contains(var.name) && !filter_type.contains(var.type))
        {
            list.append(var);
        }
    }
    Py_DECREF(keys);

    return list;
}
예제 #29
0
파일: super.cpp 프로젝트: KrishMunot/pyston
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;
}
예제 #30
0
파일: buffer.c 프로젝트: Linxiao-Chen/numpy
static int
_buffer_format_string(PyArray_Descr *descr, _tmp_string_t *str,
                      PyArrayObject* arr, Py_ssize_t *offset,
                      char *active_byteorder)
{
    int k;
    char _active_byteorder = '@';
    Py_ssize_t _offset = 0;

    if (active_byteorder == NULL) {
        active_byteorder = &_active_byteorder;
    }
    if (offset == NULL) {
        offset = &_offset;
    }

    if (descr->subarray) {
        PyObject *item, *subarray_tuple;
        Py_ssize_t total_count = 1;
        Py_ssize_t dim_size;
        char buf[128];
        int old_offset;
        int ret;

        if (PyTuple_Check(descr->subarray->shape)) {
            subarray_tuple = descr->subarray->shape;
            Py_INCREF(subarray_tuple);
        }
        else {
            subarray_tuple = Py_BuildValue("(O)", descr->subarray->shape);
        }

        _append_char(str, '(');
        for (k = 0; k < PyTuple_GET_SIZE(subarray_tuple); ++k) {
            if (k > 0) {
                _append_char(str, ',');
            }
            item = PyTuple_GET_ITEM(subarray_tuple, k);
            dim_size = PyNumber_AsSsize_t(item, NULL);

            PyOS_snprintf(buf, sizeof(buf), "%ld", (long)dim_size);
            _append_str(str, buf);
            total_count *= dim_size;
        }
        _append_char(str, ')');

        Py_DECREF(subarray_tuple);

        old_offset = *offset;
        ret = _buffer_format_string(descr->subarray->base, str, arr, offset,
                                    active_byteorder);
        *offset = old_offset + (*offset - old_offset) * total_count;
        return ret;
    }
    else if (PyDataType_HASFIELDS(descr)) {
        int base_offset = *offset;

        _append_str(str, "T{");
        for (k = 0; k < PyTuple_GET_SIZE(descr->names); ++k) {
            PyObject *name, *item, *offset_obj, *tmp;
            PyArray_Descr *child;
            char *p;
            Py_ssize_t len;
            int new_offset;

            name = PyTuple_GET_ITEM(descr->names, k);
            item = PyDict_GetItem(descr->fields, name);

            child = (PyArray_Descr*)PyTuple_GetItem(item, 0);
            offset_obj = PyTuple_GetItem(item, 1);
            new_offset = base_offset + PyInt_AsLong(offset_obj);

            /* Insert padding manually */
            if (*offset > new_offset) {
                PyErr_SetString(PyExc_RuntimeError,
                                "This should never happen: Invalid offset in "
                                "buffer format string generation. Please "
                                "report a bug to the Numpy developers.");
                return -1;
            }
            while (*offset < new_offset) {
                _append_char(str, 'x');
                ++*offset;
            }

            /* Insert child item */
            _buffer_format_string(child, str, arr, offset,
                                  active_byteorder);

            /* Insert field name */
#if defined(NPY_PY3K)
            /* FIXME: XXX -- should it use UTF-8 here? */
            tmp = PyUnicode_AsUTF8String(name);
#else
            tmp = name;
#endif
            if (tmp == NULL || PyBytes_AsStringAndSize(tmp, &p, &len) < 0) {
                PyErr_SetString(PyExc_ValueError, "invalid field name");
                return -1;
            }
            _append_char(str, ':');
            while (len > 0) {
                if (*p == ':') {
                    Py_DECREF(tmp);
                    PyErr_SetString(PyExc_ValueError,
                                    "':' is not an allowed character in buffer "
                                    "field names");
                    return -1;
                }
                _append_char(str, *p);
                ++p;
                --len;
            }
            _append_char(str, ':');
#if defined(NPY_PY3K)
            Py_DECREF(tmp);
#endif
        }
        _append_char(str, '}');
    }
    else {
        int is_standard_size = 1;
        int is_native_only_type = (descr->type_num == NPY_LONGDOUBLE ||
                                   descr->type_num == NPY_CLONGDOUBLE);
#if NPY_SIZEOF_LONG_LONG != 8
        is_native_only_type = is_native_only_type || (
            descr->type_num == NPY_LONGLONG ||
            descr->type_num == NPY_ULONGLONG);
#endif

        *offset += descr->elsize;

        if (descr->byteorder == '=' &&
                _is_natively_aligned_at(descr, arr, *offset)) {
            /* Prefer native types, to cater for Cython */
            is_standard_size = 0;
            if (*active_byteorder != '@') {
                _append_char(str, '@');
                *active_byteorder = '@';
            }
        }
        else if (descr->byteorder == '=' && is_native_only_type) {
            /* Data types that have no standard size */
            is_standard_size = 0;
            if (*active_byteorder != '^') {
                _append_char(str, '^');
                *active_byteorder = '^';
            }
        }
        else if (descr->byteorder == '<' || descr->byteorder == '>' ||
                 descr->byteorder == '=') {
            is_standard_size = 1;
            if (*active_byteorder != descr->byteorder) {
                _append_char(str, descr->byteorder);
                *active_byteorder = descr->byteorder;
            }

            if (is_native_only_type) {
                /*
                 * It's not possible to express native-only data types
                 * in non-native npy_byte orders
                 */
                PyErr_Format(PyExc_ValueError,
                             "cannot expose native-only dtype '%c' in "
                             "non-native byte order '%c' via buffer interface",
                             descr->type, descr->byteorder);
            }
        }

        switch (descr->type_num) {
        case NPY_BOOL:         if (_append_char(str, '?')) return -1; break;
        case NPY_BYTE:         if (_append_char(str, 'b')) return -1; break;
        case NPY_UBYTE:        if (_append_char(str, 'B')) return -1; break;
        case NPY_SHORT:        if (_append_char(str, 'h')) return -1; break;
        case NPY_USHORT:       if (_append_char(str, 'H')) return -1; break;
        case NPY_INT:          if (_append_char(str, 'i')) return -1; break;
        case NPY_UINT:         if (_append_char(str, 'I')) return -1; break;
        case NPY_LONG:
            if (is_standard_size && (NPY_SIZEOF_LONG == 8)) {
                if (_append_char(str, 'q')) return -1;
            }
            else {
                if (_append_char(str, 'l')) return -1;
            }
            break;
        case NPY_ULONG:
            if (is_standard_size && (NPY_SIZEOF_LONG == 8)) {
                if (_append_char(str, 'Q')) return -1;
            }
            else {
                if (_append_char(str, 'L')) return -1;
            }
            break;
        case NPY_LONGLONG:     if (_append_char(str, 'q')) return -1; break;
        case NPY_ULONGLONG:    if (_append_char(str, 'Q')) return -1; break;
        case NPY_HALF:         if (_append_char(str, 'e')) return -1; break;
        case NPY_FLOAT:        if (_append_char(str, 'f')) return -1; break;
        case NPY_DOUBLE:       if (_append_char(str, 'd')) return -1; break;
        case NPY_LONGDOUBLE:   if (_append_char(str, 'g')) return -1; break;
        case NPY_CFLOAT:       if (_append_str(str, "Zf")) return -1; break;
        case NPY_CDOUBLE:      if (_append_str(str, "Zd")) return -1; break;
        case NPY_CLONGDOUBLE:  if (_append_str(str, "Zg")) return -1; break;
        /* XXX: datetime */
        /* XXX: timedelta */
        case NPY_OBJECT:       if (_append_char(str, 'O')) return -1; break;
        case NPY_STRING: {
            char buf[128];
            PyOS_snprintf(buf, sizeof(buf), "%ds", descr->elsize);
            if (_append_str(str, buf)) return -1;
            break;
        }
        case NPY_UNICODE: {
            /* Numpy Unicode is always 4-byte */
            char buf[128];
            assert(descr->elsize % 4 == 0);
            PyOS_snprintf(buf, sizeof(buf), "%dw", descr->elsize / 4);
            if (_append_str(str, buf)) return -1;
            break;
        }
        case NPY_VOID: {
            /* Insert padding bytes */
            char buf[128];
            PyOS_snprintf(buf, sizeof(buf), "%dx", descr->elsize);
            if (_append_str(str, buf)) return -1;
            break;
        }
        default:
            PyErr_Format(PyExc_ValueError,
                         "cannot include dtype '%c' in a buffer",
                         descr->type);
            return -1;
        }
    }

    return 0;
}