Exemplo n.º 1
0
/* Initialize sys.stdin, stdout, stderr and builtins.open */
static int
initstdio(void)
{
    PyObject *iomod = NULL, *wrapper;
    PyObject *bimod = NULL;
    PyObject *m;
    PyObject *std = NULL;
    int status = 0, fd;
    PyObject * encoding_attr;
    char *pythonioencoding = NULL, *encoding, *errors;

    /* Hack to avoid a nasty recursion issue when Python is invoked
       in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
    if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
        goto error;
    }
    Py_DECREF(m);

    if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
        goto error;
    }
    Py_DECREF(m);

    if (!(bimod = PyImport_ImportModule("builtins"))) {
        goto error;
    }

    if (!(iomod = PyImport_ImportModule("io"))) {
        goto error;
    }
    if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
        goto error;
    }

    /* Set builtins.open */
    if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
        Py_DECREF(wrapper);
        goto error;
    }
    Py_DECREF(wrapper);

    encoding = _Py_StandardStreamEncoding;
    errors = _Py_StandardStreamErrors;
    if (!encoding || !errors) {
        pythonioencoding = Py_GETENV("PYTHONIOENCODING");
        if (pythonioencoding) {
            char *err;
            pythonioencoding = _PyMem_Strdup(pythonioencoding);
            if (pythonioencoding == NULL) {
                PyErr_NoMemory();
                goto error;
            }
            err = strchr(pythonioencoding, ':');
            if (err) {
                *err = '\0';
                err++;
                if (*err && !errors) {
                    errors = err;
                }
            }
            if (*pythonioencoding && !encoding) {
                encoding = pythonioencoding;
            }
        }
        if (!errors && !(pythonioencoding && *pythonioencoding)) {
            /* When the LC_CTYPE locale is the POSIX locale ("C locale"),
               stdin and stdout use the surrogateescape error handler by
               default, instead of the strict error handler. */
            char *loc = setlocale(LC_CTYPE, NULL);
            if (loc != NULL && strcmp(loc, "C") == 0)
                errors = "surrogateescape";
        }
    }

    /* Set sys.stdin */
    fd = fileno(stdin);
    /* Under some conditions stdin, stdout and stderr may not be connected
     * and fileno() may point to an invalid file descriptor. For example
     * GUI apps don't have valid standard streams by default.
     */
    std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
    if (std == NULL)
        goto error;
    PySys_SetObject("__stdin__", std);
    _PySys_SetObjectId(&PyId_stdin, std);
    Py_DECREF(std);

    /* Set sys.stdout */
    fd = fileno(stdout);
    std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
    if (std == NULL)
        goto error;
    PySys_SetObject("__stdout__", std);
    _PySys_SetObjectId(&PyId_stdout, std);
    Py_DECREF(std);

#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
    /* Set sys.stderr, replaces the preliminary stderr */
    fd = fileno(stderr);
    std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
    if (std == NULL)
        goto error;

    /* Same as hack above, pre-import stderr's codec to avoid recursion
       when import.c tries to write to stderr in verbose mode. */
    encoding_attr = PyObject_GetAttrString(std, "encoding");
    if (encoding_attr != NULL) {
        const char * std_encoding;
        std_encoding = _PyUnicode_AsString(encoding_attr);
        if (std_encoding != NULL) {
            PyObject *codec_info = _PyCodec_Lookup(std_encoding);
            Py_XDECREF(codec_info);
        }
        Py_DECREF(encoding_attr);
    }
    PyErr_Clear();  /* Not a fatal error if codec isn't available */

    if (PySys_SetObject("__stderr__", std) < 0) {
        Py_DECREF(std);
        goto error;
    }
    if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
        Py_DECREF(std);
        goto error;
    }
    Py_DECREF(std);
#endif

    if (0) {
  error:
        status = -1;
    }

    /* We won't need them anymore. */
    if (_Py_StandardStreamEncoding) {
        PyMem_RawFree(_Py_StandardStreamEncoding);
        _Py_StandardStreamEncoding = NULL;
    }
    if (_Py_StandardStreamErrors) {
        PyMem_RawFree(_Py_StandardStreamErrors);
        _Py_StandardStreamErrors = NULL;
    }
    PyMem_Free(pythonioencoding);
    Py_XDECREF(bimod);
    Py_XDECREF(iomod);
    return status;
}
Exemplo n.º 2
0
static PyObject *
structseq_repr(PyStructSequence *obj)
{
	/* buffer and type size were chosen well considered. */
#define REPR_BUFFER_SIZE 512
#define TYPE_MAXSIZE 100

	PyObject *tup;
	PyTypeObject *typ = Py_TYPE(obj);
	int i, removelast = 0;
	Py_ssize_t len;
	char buf[REPR_BUFFER_SIZE];
	char *endofbuf, *pbuf = buf;

	/* pointer to end of writeable buffer; safes space for "...)\0" */
	endofbuf= &buf[REPR_BUFFER_SIZE-5];

	if ((tup = make_tuple(obj)) == NULL) {
		return NULL;
	}

	/* "typename(", limited to  TYPE_MAXSIZE */
	len = strlen(typ->tp_name) > TYPE_MAXSIZE ? TYPE_MAXSIZE :
						    strlen(typ->tp_name);
	strncpy(pbuf, typ->tp_name, len);
	pbuf += len;
	*pbuf++ = '(';

	for (i=0; i < VISIBLE_SIZE(obj); i++) {
		PyObject *val, *repr;
		char *cname, *crepr;

		cname = typ->tp_members[i].name;
		
		val = PyTuple_GetItem(tup, i);
		if (cname == NULL || val == NULL) {
			return NULL;
		}
		repr = PyObject_Repr(val);
		if (repr == NULL) {
			Py_DECREF(tup);
			return NULL;
		}
		crepr = _PyUnicode_AsString(repr);
		if (crepr == NULL) {
			Py_DECREF(tup);
			Py_DECREF(repr);
			return NULL;
		}
		
		/* + 3: keep space for "=" and ", " */
 		len = strlen(cname) + strlen(crepr) + 3;
		if ((pbuf+len) <= endofbuf) {
			strcpy(pbuf, cname);
			pbuf += strlen(cname);
			*pbuf++ = '=';
			strcpy(pbuf, crepr);
			pbuf += strlen(crepr);
			*pbuf++ = ',';
			*pbuf++ = ' ';
			removelast = 1;
			Py_DECREF(repr);
		}
		else {
			strcpy(pbuf, "...");
			pbuf += 3;
			removelast = 0;
			Py_DECREF(repr);
			break;
		}
	}
	Py_DECREF(tup);
	if (removelast) {
		/* overwrite last ", " */
		pbuf-=2;
	}
	*pbuf++ = ')';
	*pbuf = '\0';

	return PyUnicode_FromString(buf);
}
Exemplo n.º 3
0
static EnumPropertyItem *enum_items_from_py(PyObject *seq_fast, PyObject *def, int *defvalue, const short is_enum_flag)
{
	EnumPropertyItem *items= NULL;
	PyObject *item;
	int seq_len, i, totitem= 0;
	short def_used= 0;
	const char *def_cmp= NULL;

	seq_len= PySequence_Fast_GET_SIZE(seq_fast);

	if(is_enum_flag) {
		if(seq_len > RNA_ENUM_BITFLAG_SIZE) {
			PyErr_SetString(PyExc_TypeError, "EnumProperty(...): maximum " STRINGIFY(RNA_ENUM_BITFLAG_SIZE) " members for a ENUM_FLAG type property");
			return NULL;
		}
		if(def && !PySet_Check(def)) {
			PyErr_Format(PyExc_TypeError, "EnumProperty(...): default option must be a 'set' type when ENUM_FLAG is enabled, not a '%.200s'", Py_TYPE(def)->tp_name);
			return NULL;
		}
	}
	else {
		if(def) {
			def_cmp= _PyUnicode_AsString(def);
			if(def_cmp==NULL) {
				PyErr_Format(PyExc_TypeError, "EnumProperty(...): default option must be a 'str' type when ENUM_FLAG is disabled, not a '%.200s'", Py_TYPE(def)->tp_name);
				return NULL;
			}
		}
	}

	/* blank value */
	*defvalue= 0;

	for(i=0; i<seq_len; i++) {
		EnumPropertyItem tmp= {0, "", 0, "", ""};

		item= PySequence_Fast_GET_ITEM(seq_fast, i);
		if(PyTuple_Check(item)==0) {
			PyErr_SetString(PyExc_TypeError, "EnumProperty(...): expected a sequence of tuples for the enum items");
			if(items) MEM_freeN(items);
			return NULL;
		}

		if(!PyArg_ParseTuple(item, "sss", &tmp.identifier, &tmp.name, &tmp.description)) {
			PyErr_SetString(PyExc_TypeError, "EnumProperty(...): expected an identifier, name and description in the tuple");
			return NULL;
		}

		if(is_enum_flag) {
			tmp.value= 1<<i;

			if(def && PySet_Contains(def, PyTuple_GET_ITEM(item, 0))) {
				*defvalue |= tmp.value;
				def_used++;
			}
		}
		else {
			tmp.value= i;

			if(def && def_used == 0 && strcmp(def_cmp, tmp.identifier)==0) {
				*defvalue= tmp.value;
				def_used++; /* only ever 1 */
			}
		}

		RNA_enum_item_add(&items, &totitem, &tmp);
	}

	RNA_enum_item_end(&items, &totitem);

	if(is_enum_flag) {
		/* strict check that all set members were used */
		if(def && def_used != PySet_GET_SIZE(def)) {
			MEM_freeN(items);

			PyErr_Format(PyExc_TypeError, "EnumProperty(..., default={...}): set has %d unused member(s)", PySet_GET_SIZE(def) - def_used);
			return NULL;
		}
	}
	else {
		if(def && def_used == 0) {
			MEM_freeN(items);

			PyErr_Format(PyExc_TypeError, "EnumProperty(..., default=\'%s\'): not found in enum members", def);
			return NULL;
		}
	}

	return items;
}
Exemplo n.º 4
0
PyObject* pysqlite_row_subscript(pysqlite_Row* self, PyObject* idx)
{
    long _idx;
    char* key;
    Py_ssize_t nitems, i;
    char* compare_key;

    char* p1;
    char* p2;

    PyObject* item;

    if (PyLong_Check(idx)) {
        _idx = PyLong_AsLong(idx);
        item = PyTuple_GetItem(self->data, _idx);
        Py_XINCREF(item);
        return item;
    } else if (PyUnicode_Check(idx)) {
        key = _PyUnicode_AsString(idx);
        if (key == NULL)
            return NULL;

        nitems = PyTuple_Size(self->description);

        for (i = 0; i < nitems; i++) {
            PyObject *obj;
            obj = PyTuple_GET_ITEM(self->description, i);
            obj = PyTuple_GET_ITEM(obj, 0);
            compare_key = _PyUnicode_AsString(obj);
            if (!compare_key) {
                return NULL;
            }

            p1 = key;
            p2 = compare_key;

            while (1) {
                if ((*p1 == (char)0) || (*p2 == (char)0)) {
                    break;
                }

                if ((*p1 | 0x20) != (*p2 | 0x20)) {
                    break;
                }

                p1++;
                p2++;
            }

            if ((*p1 == (char)0) && (*p2 == (char)0)) {
                /* found item */
                item = PyTuple_GetItem(self->data, i);
                Py_INCREF(item);
                return item;
            }

        }

        PyErr_SetString(PyExc_IndexError, "No item with that key");
        return NULL;
    }
    else if (PySlice_Check(idx)) {
        PyErr_SetString(PyExc_ValueError, "slices not implemented, yet");
        return NULL;
    }
    else {
        PyErr_SetString(PyExc_IndexError, "Index must be int or string");
        return NULL;
    }
}
Exemplo n.º 5
0
/* copied from pythonrun.c, 3.2.0 */
static int
parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
				   int *lineno, int *offset, const char **text)
{
	long hold;
	PyObject *v;

	/* old style errors */
	if (PyTuple_Check(err))
		return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
								lineno, offset, text);

	/* new style errors.  `err' is an instance */

	if (! (v = PyObject_GetAttrString(err, "msg")))
		goto finally;
	*message = v;

	if (!(v = PyObject_GetAttrString(err, "filename")))
		goto finally;
	if (v == Py_None)
		*filename = NULL;
	else if (! (*filename = _PyUnicode_AsString(v)))
		goto finally;

	Py_DECREF(v);
	if (!(v = PyObject_GetAttrString(err, "lineno")))
		goto finally;
	hold = PyLong_AsLong(v);
	Py_DECREF(v);
	v = NULL;
	if (hold < 0 && PyErr_Occurred())
		goto finally;
	*lineno = (int)hold;

	if (!(v = PyObject_GetAttrString(err, "offset")))
		goto finally;
	if (v == Py_None) {
		*offset = -1;
		Py_DECREF(v);
		v = NULL;
	}
	else {
		hold = PyLong_AsLong(v);
		Py_DECREF(v);
		v = NULL;
		if (hold < 0 && PyErr_Occurred())
			goto finally;
		*offset = (int)hold;
	}

	if (!(v = PyObject_GetAttrString(err, "text")))
		goto finally;
	if (v == Py_None)
		*text = NULL;
	else if (!PyUnicode_Check(v) ||
			 !(*text = _PyUnicode_AsString(v)))
		goto finally;
	Py_DECREF(v);
	return 1;

finally:
	Py_XDECREF(v);
	return 0;
}
/**
 * pyglib_gerror_exception_check:
 * @error: a standard GLib GError ** output parameter
 *
 * Checks to see if a GError exception has been raised, and if so
 * translates the python exception to a standard GLib GError.  If the
 * raised exception is not a GError then PyErr_Print() is called.
 *
 * Returns: 0 if no exception has been raised, -1 if it is a
 * valid glib.GError, -2 otherwise.
 */
gboolean
pyglib_gerror_exception_check(GError **error)
{
    PyObject *type, *value, *traceback;
    PyObject *py_message, *py_domain, *py_code;
    const char *bad_gerror_message;

    PyErr_Fetch(&type, &value, &traceback);
    if (type == NULL)
        return 0;
    PyErr_NormalizeException(&type, &value, &traceback);
    if (value == NULL) {
        PyErr_Restore(type, value, traceback);
        PyErr_Print();
        return -2;
    }
    if (!value ||
	!PyErr_GivenExceptionMatches(type,
				     (PyObject *) _PyGLib_API->gerror_exception)) {
        PyErr_Restore(type, value, traceback);
        PyErr_Print();
        return -2;
    }
    Py_DECREF(type);
    Py_XDECREF(traceback);

    py_message = PyObject_GetAttrString(value, "message");
    if (!py_message || !_PyUnicode_Check(py_message)) {
        bad_gerror_message = "glib.GError instances must have a 'message' string attribute";
        goto bad_gerror;
    }

    py_domain = PyObject_GetAttrString(value, "domain");
    if (!py_domain || !_PyUnicode_Check(py_domain)) {
        bad_gerror_message = "glib.GError instances must have a 'domain' string attribute";
        Py_DECREF(py_message);
        goto bad_gerror;
    }

    py_code = PyObject_GetAttrString(value, "code");
    if (!py_code || !_PyLong_Check(py_code)) {
        bad_gerror_message = "glib.GError instances must have a 'code' int attribute";
        Py_DECREF(py_message);
        Py_DECREF(py_domain);
        goto bad_gerror;
    }

    g_set_error(error, g_quark_from_string(_PyUnicode_AsString(py_domain)),
                _PyLong_AsLong(py_code), _PyUnicode_AsString(py_message));

    Py_DECREF(py_message);
    Py_DECREF(py_code);
    Py_DECREF(py_domain);
    return -1;

bad_gerror:
    Py_DECREF(value);
    g_set_error(error, g_quark_from_static_string("pyglib"), 0, bad_gerror_message);
    PyErr_SetString(PyExc_ValueError, bad_gerror_message);
    PyErr_Print();
    return -2;
}
int
PyRun_InteractiveOneObject(FILE *fp, PyObject *filename, PyCompilerFlags *flags)
{
    PyObject *m, *d, *v, *w, *oenc = NULL, *mod_name;
    mod_ty mod;
    PyArena *arena;
    char *ps1 = "", *ps2 = "", *enc = NULL;
    int errcode = 0;
    _Py_IDENTIFIER(encoding);
    _Py_IDENTIFIER(__main__);

    mod_name = _PyUnicode_FromId(&PyId___main__); /* borrowed */
    if (mod_name == NULL) {
        PyErr_Print();
        return -1;
    }

    if (fp == stdin) {
        /* Fetch encoding from sys.stdin if possible. */
        v = _PySys_GetObjectId(&PyId_stdin);
        if (v && v != Py_None) {
            oenc = _PyObject_GetAttrId(v, &PyId_encoding);
            if (oenc)
                enc = _PyUnicode_AsString(oenc);
            if (!enc)
                PyErr_Clear();
        }
    }
    v = _PySys_GetObjectId(&PyId_ps1);
    if (v != NULL) {
        v = PyObject_Str(v);
        if (v == NULL)
            PyErr_Clear();
        else if (PyUnicode_Check(v)) {
            ps1 = _PyUnicode_AsString(v);
            if (ps1 == NULL) {
                PyErr_Clear();
                ps1 = "";
            }
        }
    }
    w = _PySys_GetObjectId(&PyId_ps2);
    if (w != NULL) {
        w = PyObject_Str(w);
        if (w == NULL)
            PyErr_Clear();
        else if (PyUnicode_Check(w)) {
            ps2 = _PyUnicode_AsString(w);
            if (ps2 == NULL) {
                PyErr_Clear();
                ps2 = "";
            }
        }
    }
    arena = PyArena_New();
    if (arena == NULL) {
        Py_XDECREF(v);
        Py_XDECREF(w);
        Py_XDECREF(oenc);
        return -1;
    }
    mod = PyParser_ASTFromFileObject(fp, filename, enc,
                                     Py_single_input, ps1, ps2,
                                     flags, &errcode, arena);
    Py_XDECREF(v);
    Py_XDECREF(w);
    Py_XDECREF(oenc);
    if (mod == NULL) {
        PyArena_Free(arena);
        if (errcode == E_EOF) {
            PyErr_Clear();
            return E_EOF;
        }
        PyErr_Print();
        return -1;
    }
    m = PyImport_AddModuleObject(mod_name);
    if (m == NULL) {
        PyArena_Free(arena);
        return -1;
    }
    d = PyModule_GetDict(m);
    v = run_mod(mod, filename, d, d, flags, arena);
    PyArena_Free(arena);
    if (v == NULL) {
        PyErr_Print();
        flush_io();
        return -1;
    }
    Py_DECREF(v);
    flush_io();
    return 0;
}
Exemplo n.º 8
0
PyObject *
PyCode_Optimize(PyObject *code, PyObject* consts, PyObject *names,
                PyObject *lineno_obj)
{
    Py_ssize_t i, j, codelen;
    int nops, h, adj;
    int tgt, tgttgt, opcode;
    unsigned char *codestr = NULL;
    unsigned char *lineno;
    int *addrmap = NULL;
    int new_line, cum_orig_line, last_line, tabsiz;
    int cumlc=0, lastlc=0;      /* Count runs of consecutive LOAD_CONSTs */
    unsigned int *blocks = NULL;
    char *name;

    /* Bail out if an exception is set */
    if (PyErr_Occurred())
        goto exitError;

    /* Bypass optimization when the lineno table is too complex */
    assert(PyBytes_Check(lineno_obj));
    lineno = (unsigned char*)PyBytes_AS_STRING(lineno_obj);
    tabsiz = PyBytes_GET_SIZE(lineno_obj);
    if (memchr(lineno, 255, tabsiz) != NULL)
        goto exitUnchanged;

    /* Avoid situations where jump retargeting could overflow */
    assert(PyBytes_Check(code));
    codelen = PyBytes_GET_SIZE(code);
    if (codelen > 32700)
        goto exitUnchanged;

    /* Make a modifiable copy of the code string */
    codestr = (unsigned char *)PyMem_Malloc(codelen);
    if (codestr == NULL)
        goto exitError;
    codestr = (unsigned char *)memcpy(codestr,
                                      PyBytes_AS_STRING(code), codelen);

    /* Verify that RETURN_VALUE terminates the codestring.      This allows
       the various transformation patterns to look ahead several
       instructions without additional checks to make sure they are not
       looking beyond the end of the code string.
    */
    if (codestr[codelen-1] != RETURN_VALUE)
        goto exitUnchanged;

    /* Mapping to new jump targets after NOPs are removed */
    addrmap = (int *)PyMem_Malloc(codelen * sizeof(int));
    if (addrmap == NULL)
        goto exitError;

    blocks = markblocks(codestr, codelen);
    if (blocks == NULL)
        goto exitError;
    assert(PyList_Check(consts));

    for (i=0 ; i<codelen ; i += CODESIZE(codestr[i])) {
      reoptimize_current:
        opcode = codestr[i];

        lastlc = cumlc;
        cumlc = 0;

        switch (opcode) {
            /* Replace UNARY_NOT POP_JUMP_IF_FALSE
               with    POP_JUMP_IF_TRUE */
            case UNARY_NOT:
                if (codestr[i+1] != POP_JUMP_IF_FALSE
                    || !ISBASICBLOCK(blocks,i,4))
                    continue;
                j = GETARG(codestr, i+1);
                codestr[i] = POP_JUMP_IF_TRUE;
                SETARG(codestr, i, j);
                codestr[i+3] = NOP;
                goto reoptimize_current;

                /* not a is b -->  a is not b
                   not a in b -->  a not in b
                   not a is not b -->  a is b
                   not a not in b -->  a in b
                */
            case COMPARE_OP:
                j = GETARG(codestr, i);
                if (j < 6  ||  j > 9  ||
                    codestr[i+3] != UNARY_NOT  ||
                    !ISBASICBLOCK(blocks,i,4))
                    continue;
                SETARG(codestr, i, (j^1));
                codestr[i+3] = NOP;
                break;

                /* Replace LOAD_GLOBAL/LOAD_NAME None/True/False
                   with LOAD_CONST None/True/False */
            case LOAD_NAME:
            case LOAD_GLOBAL:
                j = GETARG(codestr, i);
                name = _PyUnicode_AsString(PyTuple_GET_ITEM(names, j));
                h = load_global(codestr, i, name, consts);
                if (h < 0)
                    goto exitError;
                else if (h == 0)
                    continue;
                cumlc = lastlc + 1;
                break;

                /* Skip over LOAD_CONST trueconst
                   POP_JUMP_IF_FALSE xx. This improves
                   "while 1" performance. */
            case LOAD_CONST:
                cumlc = lastlc + 1;
                j = GETARG(codestr, i);
                if (codestr[i+3] != POP_JUMP_IF_FALSE  ||
                    !ISBASICBLOCK(blocks,i,6)  ||
                    !PyObject_IsTrue(PyList_GET_ITEM(consts, j)))
                    continue;
                memset(codestr+i, NOP, 6);
                cumlc = 0;
                break;

                /* Try to fold tuples of constants (includes a case for lists and sets
                   which are only used for "in" and "not in" tests).
                   Skip over BUILD_SEQN 1 UNPACK_SEQN 1.
                   Replace BUILD_SEQN 2 UNPACK_SEQN 2 with ROT2.
                   Replace BUILD_SEQN 3 UNPACK_SEQN 3 with ROT3 ROT2. */
            case BUILD_TUPLE:
            case BUILD_LIST:
            case BUILD_SET:
                j = GETARG(codestr, i);
                h = i - 3 * j;
                if (h >= 0  &&
                    j <= lastlc                  &&
                    ((opcode == BUILD_TUPLE &&
                      ISBASICBLOCK(blocks, h, 3*(j+1))) ||
                     ((opcode == BUILD_LIST || opcode == BUILD_SET) &&
                      codestr[i+3]==COMPARE_OP &&
                      ISBASICBLOCK(blocks, h, 3*(j+2)) &&
                      (GETARG(codestr,i+3)==6 ||
                       GETARG(codestr,i+3)==7))) &&
                    tuple_of_constants(&codestr[h], j, consts)) {
                    assert(codestr[i] == LOAD_CONST);
                    cumlc = 1;
                    break;
                }
                if (codestr[i+3] != UNPACK_SEQUENCE  ||
                    !ISBASICBLOCK(blocks,i,6) ||
                    j != GETARG(codestr, i+3) ||
                    opcode == BUILD_SET)
                    continue;
                if (j == 1) {
                    memset(codestr+i, NOP, 6);
                } else if (j == 2) {
                    codestr[i] = ROT_TWO;
                    memset(codestr+i+1, NOP, 5);
                } else if (j == 3) {
                    codestr[i] = ROT_THREE;
                    codestr[i+1] = ROT_TWO;
                    memset(codestr+i+2, NOP, 4);
                }
                break;

                /* Fold binary ops on constants.
                   LOAD_CONST c1 LOAD_CONST c2 BINOP -->  LOAD_CONST binop(c1,c2) */
            case BINARY_POWER:
            case BINARY_MULTIPLY:
            case BINARY_TRUE_DIVIDE:
            case BINARY_FLOOR_DIVIDE:
            case BINARY_MODULO:
            case BINARY_ADD:
            case BINARY_SUBTRACT:
            case BINARY_SUBSCR:
            case BINARY_LSHIFT:
            case BINARY_RSHIFT:
            case BINARY_AND:
            case BINARY_XOR:
            case BINARY_OR:
                if (lastlc >= 2                  &&
                    ISBASICBLOCK(blocks, i-6, 7)  &&
                    fold_binops_on_constants(&codestr[i-6], consts)) {
                    i -= 2;
                    assert(codestr[i] == LOAD_CONST);
                    cumlc = 1;
                }
                break;

                /* Fold unary ops on constants.
                   LOAD_CONST c1  UNARY_OP -->                  LOAD_CONST unary_op(c) */
            case UNARY_NEGATIVE:
            case UNARY_INVERT:
            case UNARY_POSITIVE:
                if (lastlc >= 1                  &&
                    ISBASICBLOCK(blocks, i-3, 4)  &&
                    fold_unaryops_on_constants(&codestr[i-3], consts))                  {
                    i -= 2;
                    assert(codestr[i] == LOAD_CONST);
                    cumlc = 1;
                }
                break;

                /* Simplify conditional jump to conditional jump where the
                   result of the first test implies the success of a similar
                   test or the failure of the opposite test.
                   Arises in code like:
                   "if a and b:"
                   "if a or b:"
                   "a and b or c"
                   "(a and b) and c"
                   x:JUMP_IF_FALSE_OR_POP y   y:JUMP_IF_FALSE_OR_POP z
                      -->  x:JUMP_IF_FALSE_OR_POP z
                   x:JUMP_IF_FALSE_OR_POP y   y:JUMP_IF_TRUE_OR_POP z
                      -->  x:POP_JUMP_IF_FALSE y+3
                   where y+3 is the instruction following the second test.
                */
            case JUMP_IF_FALSE_OR_POP:
            case JUMP_IF_TRUE_OR_POP:
                tgt = GETJUMPTGT(codestr, i);
                j = codestr[tgt];
                if (CONDITIONAL_JUMP(j)) {
                    /* NOTE: all possible jumps here are
                       absolute! */
                    if (JUMPS_ON_TRUE(j) == JUMPS_ON_TRUE(opcode)) {
                        /* The second jump will be
                           taken iff the first is. */
                        tgttgt = GETJUMPTGT(codestr, tgt);
                        /* The current opcode inherits
                           its target's stack behaviour */
                        codestr[i] = j;
                        SETARG(codestr, i, tgttgt);
                        goto reoptimize_current;
                    } else {
                        /* The second jump is not taken
                           if the first is (so jump past
                           it), and all conditional
                           jumps pop their argument when
                           they're not taken (so change
                           the first jump to pop its
                           argument when it's taken). */
                        if (JUMPS_ON_TRUE(opcode))
                            codestr[i] = POP_JUMP_IF_TRUE;
                        else
                            codestr[i] = POP_JUMP_IF_FALSE;
                        SETARG(codestr, i, (tgt + 3));
                        goto reoptimize_current;
                    }
                }
                /* Intentional fallthrough */

                /* Replace jumps to unconditional jumps */
            case POP_JUMP_IF_FALSE:
            case POP_JUMP_IF_TRUE:
            case FOR_ITER:
            case JUMP_FORWARD:
            case JUMP_ABSOLUTE:
            case CONTINUE_LOOP:
            case SETUP_LOOP:
            case SETUP_EXCEPT:
            case SETUP_FINALLY:
            case SETUP_WITH:
                tgt = GETJUMPTGT(codestr, i);
                /* Replace JUMP_* to a RETURN into just a RETURN */
                if (UNCONDITIONAL_JUMP(opcode) &&
                    codestr[tgt] == RETURN_VALUE) {
                    codestr[i] = RETURN_VALUE;
                    memset(codestr+i+1, NOP, 2);
                    continue;
                }
                if (!UNCONDITIONAL_JUMP(codestr[tgt]))
                    continue;
                tgttgt = GETJUMPTGT(codestr, tgt);
                if (opcode == JUMP_FORWARD) /* JMP_ABS can go backwards */
                    opcode = JUMP_ABSOLUTE;
                if (!ABSOLUTE_JUMP(opcode))
                    tgttgt -= i + 3;     /* Calc relative jump addr */
                if (tgttgt < 0)                           /* No backward relative jumps */
                    continue;
                codestr[i] = opcode;
                SETARG(codestr, i, tgttgt);
                break;

            case EXTENDED_ARG:
                if (codestr[i+3] != MAKE_FUNCTION)
                    goto exitUnchanged;
                /* don't visit MAKE_FUNCTION as GETARG will be wrong */
                i += 3;
                break;

                /* Replace RETURN LOAD_CONST None RETURN with just RETURN */
                /* Remove unreachable JUMPs after RETURN */
            case RETURN_VALUE:
                if (i+4 >= codelen)
                    continue;
                if (codestr[i+4] == RETURN_VALUE &&
                    ISBASICBLOCK(blocks,i,5))
                    memset(codestr+i+1, NOP, 4);
                else if (UNCONDITIONAL_JUMP(codestr[i+1]) &&
                         ISBASICBLOCK(blocks,i,4))
                    memset(codestr+i+1, NOP, 3);
                break;
        }
    }

    /* Fixup linenotab */
    for (i=0, nops=0 ; i<codelen ; i += CODESIZE(codestr[i])) {
        addrmap[i] = i - nops;
        if (codestr[i] == NOP)
            nops++;
    }
    cum_orig_line = 0;
    last_line = 0;
    for (i=0 ; i < tabsiz ; i+=2) {
        cum_orig_line += lineno[i];
        new_line = addrmap[cum_orig_line];
        assert (new_line - last_line < 255);
        lineno[i] =((unsigned char)(new_line - last_line));
        last_line = new_line;
    }

    /* Remove NOPs and fixup jump targets */
    for (i=0, h=0 ; i<codelen ; ) {
        opcode = codestr[i];
        switch (opcode) {
            case NOP:
                i++;
                continue;

            case JUMP_ABSOLUTE:
            case CONTINUE_LOOP:
            case POP_JUMP_IF_FALSE:
            case POP_JUMP_IF_TRUE:
            case JUMP_IF_FALSE_OR_POP:
            case JUMP_IF_TRUE_OR_POP:
                j = addrmap[GETARG(codestr, i)];
                SETARG(codestr, i, j);
                break;

            case FOR_ITER:
            case JUMP_FORWARD:
            case SETUP_LOOP:
            case SETUP_EXCEPT:
            case SETUP_FINALLY:
            case SETUP_WITH:
                j = addrmap[GETARG(codestr, i) + i + 3] - addrmap[i] - 3;
                SETARG(codestr, i, j);
                break;
        }
        adj = CODESIZE(opcode);
        while (adj--)
            codestr[h++] = codestr[i++];
    }
    assert(h + nops == codelen);

    code = PyBytes_FromStringAndSize((char *)codestr, h);
    PyMem_Free(addrmap);
    PyMem_Free(codestr);
    PyMem_Free(blocks);
    return code;

 exitError:
    code = NULL;

 exitUnchanged:
    if (blocks != NULL)
        PyMem_Free(blocks);
    if (addrmap != NULL)
        PyMem_Free(addrmap);
    if (codestr != NULL)
        PyMem_Free(codestr);
    Py_XINCREF(code);
    return code;
}
Exemplo n.º 9
0
static PyObject *
normalizeUserObj(PyObject *obj)
{
    PyCFunctionObject *fn;
    if (!PyCFunction_Check(obj)) {
        Py_INCREF(obj);
        return obj;
    }
    /* Replace built-in function objects with a descriptive string
       because of built-in methods -- keeping a reference to
       __self__ is probably not a good idea. */
    fn = (PyCFunctionObject *)obj;

    if (fn->m_self == NULL) {
        /* built-in function: look up the module name */
        PyObject *mod = fn->m_module;
        const char *modname;
        if (mod && PyUnicode_Check(mod)) {
            /* XXX: The following will truncate module names with embedded
             * null-characters.  It is unlikely that this can happen in
             * practice and the concequences are not serious enough to
             * introduce extra checks here.
             */
            modname = _PyUnicode_AsString(mod);
            if (modname == NULL) {
                modname = "<encoding error>";
                PyErr_Clear();
            }
        }
        else if (mod && PyModule_Check(mod)) {
            modname = PyModule_GetName(mod);
            if (modname == NULL) {
                PyErr_Clear();
                modname = "builtins";
            }
        }
        else {
            modname = "builtins";
        }
        if (strcmp(modname, "builtins") != 0)
            return PyUnicode_FromFormat("<%s.%s>",
                                        modname,
                                        fn->m_ml->ml_name);
        else
            return PyUnicode_FromFormat("<%s>",
                                        fn->m_ml->ml_name);
    }
    else {
        /* built-in method: try to return
            repr(getattr(type(__self__), __name__))
        */
        PyObject *self = fn->m_self;
        PyObject *name = PyUnicode_FromString(fn->m_ml->ml_name);
        if (name != NULL) {
            PyObject *mo = _PyType_Lookup(Py_TYPE(self), name);
            Py_XINCREF(mo);
            Py_DECREF(name);
            if (mo != NULL) {
                PyObject *res = PyObject_Repr(mo);
                Py_DECREF(mo);
                if (res != NULL)
                    return res;
            }
        }
        PyErr_Clear();
        return PyUnicode_FromFormat("<built-in method %s>",
                                    fn->m_ml->ml_name);
    }
}
Exemplo n.º 10
0
/* use for both array and group */
static Py_hash_t BPy_IDGroup_hash(BPy_IDProperty *self)
{
	return _Py_HashPointer(self->prop);
}

static PyObject *BPy_IDGroup_repr(BPy_IDProperty *self)
{
	return PyUnicode_FromFormat("<bpy id prop: owner=\"%s\", name=\"%s\", address=%p>",
	                            self->id ? self->id->name : "<NONE>", self->prop->name, self->prop);
}

PyObject *BPy_IDGroup_WrapData(ID *id, IDProperty *prop, IDProperty *parent)
{
	switch (prop->type) {
		case IDP_STRING:   return idprop_py_from_idp_string(prop);
		case IDP_INT:      return idprop_py_from_idp_int(prop);
		case IDP_FLOAT:    return idprop_py_from_idp_float(prop);
		case IDP_DOUBLE:   return idprop_py_from_idp_double(prop);
		case IDP_GROUP:    return idprop_py_from_idp_group(id, prop, parent);
		case IDP_ARRAY:    return idprop_py_from_idp_array(id, prop);
		case IDP_IDPARRAY: return idprop_py_from_idp_idparray(id, prop); /* this could be better a internal type */
		case IDP_ID:       return idprop_py_from_idp_id(prop);
		default: Py_RETURN_NONE;
	}
}

#if 0 /* UNUSED, currently assignment overwrites into new properties, rather than setting in-place */
static int BPy_IDGroup_SetData(BPy_IDProperty *self, IDProperty *prop, PyObject *value)
{
	switch (prop->type) {
		case IDP_STRING:
		{
			char *st;
			if (!PyUnicode_Check(value)) {
				PyErr_SetString(PyExc_TypeError, "expected a string!");
				return -1;
			}
			/* NOTE: if this code is enabled, bytes support needs to be added */
#ifdef USE_STRING_COERCE
			{
				int alloc_len;
				PyObject *value_coerce = NULL;

				st = (char *)PyC_UnicodeAsByte(value, &value_coerce);
				alloc_len = strlen(st) + 1;

				st = _PyUnicode_AsString(value);
				IDP_ResizeArray(prop, alloc_len);
				memcpy(IDP_Array(prop), st, alloc_len);
				Py_XDECREF(value_coerce);
			}
#else
			st = _PyUnicode_AsString(value);
			IDP_ResizeArray(prop, strlen(st) + 1);
			strcpy(IDP_Array(prop), st);
#endif

			return 0;
		}

		case IDP_INT:
		{
			int ivalue = PyLong_AsSsize_t(value);
			if (ivalue == -1 && PyErr_Occurred()) {
				PyErr_SetString(PyExc_TypeError, "expected an int type");
				return -1;
			}
			IDP_Int(prop) = ivalue;
			break;
		}
		case IDP_FLOAT:
		{
			float fvalue = (float)PyFloat_AsDouble(value);
			if (fvalue == -1 && PyErr_Occurred()) {
				PyErr_SetString(PyExc_TypeError, "expected a float");
				return -1;
			}
			IDP_Float(self->prop) = fvalue;
			break;
		}
		case IDP_DOUBLE:
		{
			double dvalue = PyFloat_AsDouble(value);
			if (dvalue == -1 && PyErr_Occurred()) {
				PyErr_SetString(PyExc_TypeError, "expected a float");
				return -1;
			}
			IDP_Double(self->prop) = dvalue;
			break;
		}
		default:
			PyErr_SetString(PyExc_AttributeError, "attempt to set read-only attribute!");
			return -1;
	}
	return 0;
}
Exemplo n.º 11
0
/**
 * Evaluate the code and return the value
 * @return
 */
QVariant PythonScript::evaluateImpl() {
  ScopedPythonGIL lock;
  PyObject *compiledCode = this->compileToByteCode(true);
  if (!compiledCode) {
    return QVariant("");
  }
  PyObject *pyret;
  beginStdoutRedirect();
  if (PyCallable_Check(compiledCode)) {
    PyObject *empty_tuple = PyTuple_New(0);
    pyret = PyObject_Call(compiledCode, empty_tuple, localDict);
    Py_DECREF(empty_tuple);
  } else {
    pyret = PyEval_EvalCode(CODE_OBJECT(compiledCode), localDict, localDict);
  }
  endStdoutRedirect();
  if (!pyret) {
    if (PyErr_ExceptionMatches(PyExc_ValueError) ||
        PyErr_ExceptionMatches(PyExc_ZeroDivisionError)) {
      PyErr_Clear(); // silently ignore errors
      return QVariant("");
    } else {
      emit_error();
      return QVariant();
    }
  }

  QVariant qret = QVariant();
  /* None */
  if (pyret == Py_None) {
    qret = QVariant("");
  }
  /* numeric types */
  else if (PyFloat_Check(pyret)) {
    qret = QVariant(PyFloat_AS_DOUBLE(pyret));
  } else if (INT_CHECK(pyret)) {
    qret = QVariant((qlonglong)TO_LONG(pyret));
  }
#if !defined(IS_PY3K)
  else if (PyLong_Check(pyret)) {
    qret = QVariant((qlonglong)PyLong_AsLongLong(pyret));
  }
#endif
  else if (PyNumber_Check(pyret)) {
    PyObject *number = PyNumber_Float(pyret);
    if (number) {
      qret = QVariant(PyFloat_AS_DOUBLE(number));
      Py_DECREF(number);
    }
  }
  /* bool */
  else if (PyBool_Check(pyret)) {
    qret = QVariant(pyret == Py_True);
  }
  // could handle advanced types (such as PyList->QValueList) here if needed
  /* fallback: try to convert to (unicode) string */
  if (!qret.isValid()) {
#if defined(IS_PY3K)
    // In 3 everything is unicode
    PyObject *pystring = PyObject_Str(pyret);
    if (pystring) {
      qret = QVariant(QString::fromUtf8(_PyUnicode_AsString(pystring)));
    }
#else
    PyObject *pystring = PyObject_Unicode(pyret);
    if (pystring) {
      PyObject *asUTF8 =
          PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(pystring),
                               (int)PyUnicode_GET_DATA_SIZE(pystring), nullptr);
      Py_DECREF(pystring);
      if (asUTF8) {
        qret = QVariant(QString::fromUtf8(PyString_AS_STRING(asUTF8)));
        Py_DECREF(asUTF8);
      } else if ((pystring = PyObject_Str(pyret))) {
        qret = QVariant(QString(PyString_AS_STRING(pystring)));
        Py_DECREF(pystring);
      }
    }
#endif
  }
  Py_DECREF(pyret);
  if (PyErr_Occurred()) {
    if (PyErr_ExceptionMatches(PyExc_ValueError) ||
        PyErr_ExceptionMatches(PyExc_ZeroDivisionError)) {
      PyErr_Clear(); // silently ignore errors
      return QVariant("");
    } else {
      emit_error();
    }
    return QVariant();
  }
  return qret;
}
Exemplo n.º 12
0
/* a close copy of ConvertPythonToGameObject but for meshes */
bool ConvertPythonToMesh(PyObject * value, RAS_MeshObject **object, bool py_none_ok, const char *error_prefix)
{
	if (value==NULL) {
		PyErr_Format(PyExc_TypeError, "%s, python pointer NULL, should never happen", error_prefix);
		*object = NULL;
		return false;
	}
		
	if (value==Py_None) {
		*object = NULL;
		
		if (py_none_ok) {
			return true;
		} else {
			PyErr_Format(PyExc_TypeError, "%s, expected KX_MeshProxy or a KX_MeshProxy name, None is invalid", error_prefix);
			return false;
		}
	}
	
	if (PyUnicode_Check(value)) {
		*object = (RAS_MeshObject*)SCA_ILogicBrick::m_sCurrentLogicManager->GetMeshByName(STR_String( _PyUnicode_AsString(value) ));
		
		if (*object) {
			return true;
		} else {
			PyErr_Format(PyExc_ValueError, "%s, requested name \"%s\" did not match any KX_MeshProxy in this scene", error_prefix, _PyUnicode_AsString(value));
			return false;
		}
	}
	
	if (PyObject_TypeCheck(value, &KX_MeshProxy::Type)) {
		KX_MeshProxy *kx_mesh = static_cast<KX_MeshProxy*>BGE_PROXY_REF(value);
		
		/* sets the error */
		if (kx_mesh==NULL) {
			PyErr_Format(PyExc_SystemError, "%s, " BGE_PROXY_ERROR_MSG, error_prefix);
			return false;
		}		
		
		*object = kx_mesh->GetMesh();
		return true;
	}
Exemplo n.º 13
0
static int set_defaults(double *control)
{
    int_t pos=0;
    int param_id;
    PyObject *param, *key, *value;
#if PY_MAJOR_VERSION < 3
    char *keystr; 
#endif
    char err_str[100];

    amd_defaults(control);

    if (!(param = PyObject_GetAttrString(amd_module, "options")) ||
        !PyDict_Check(param)){
        PyErr_SetString(PyExc_AttributeError, "missing amd.options"
            "dictionary");
        return 0;
    }
    while (PyDict_Next(param, &pos, &key, &value))
#if PY_MAJOR_VERSION >= 3
        if ((PyUnicode_Check(key)) && 
            get_param_idx(_PyUnicode_AsString(key),&param_id)) {
            if (!PyLong_Check(value) && !PyFloat_Check(value)){
                sprintf(err_str, "invalid value for AMD parameter: %-.20s",
                    _PyUnicode_AsString(key));
#else
        if ((keystr = PyString_AsString(key)) && get_param_idx(keystr,
            &param_id)) {
            if (!PyInt_Check(value) && !PyFloat_Check(value)){
                sprintf(err_str, "invalid value for AMD parameter: "
                    "%-.20s", keystr);
#endif
                PyErr_SetString(PyExc_ValueError, err_str);
                Py_DECREF(param);
                return 0;
            }
            control[param_id] = PyFloat_AsDouble(value);
        }
    Py_DECREF(param);
    return 1;
}


static char doc_order[] =
    "Computes the approximate minimum degree ordering of a square "
    "matrix.\n\n"
    "p = order(A, uplo='L')\n\n"
    "PURPOSE\n"
    "Computes a permutation p that reduces fill-in in the Cholesky\n"
    "factorization of A[p,p].\n\n"
    "ARGUMENTS\n"
    "A         square sparse matrix\n\n"
    "uplo      'L' or 'U'.  If uplo is 'L', the lower triangular part\n"
    "          of A is used and the upper triangular is ignored.  If\n"
    "          uplo is 'U', the upper triangular part is used and the\n"
    "          lower triangular part is ignored.\n\n"
    "p         'i' matrix of length equal to the order of A";


static PyObject* order_c(PyObject *self, PyObject *args, PyObject *kwrds)
{
    spmatrix *A;
    matrix *perm;
#if PY_MAJOR_VERSION >= 3
    int uplo_ = 'L';
#endif
    char uplo = 'L';
    int j, k, n, nnz, alloc=0, info;
    int_t *rowind=NULL, *colptr=NULL;
    double control[AMD_CONTROL];
    char *kwlist[] = {"A", "uplo", NULL};

#if PY_MAJOR_VERSION >= 3
    if (!PyArg_ParseTupleAndKeywords(args, kwrds, "O|C", kwlist, &A,
        &uplo_)) return NULL;
    uplo = (char) uplo_;
#else
    if (!PyArg_ParseTupleAndKeywords(args, kwrds, "O|c", kwlist, &A,
        &uplo)) return NULL;
#endif
    if (!set_defaults(control)) return NULL;
    if (!SpMatrix_Check(A) || SP_NROWS(A) != SP_NCOLS(A)){
        PyErr_SetString(PyExc_TypeError, "A must be a square sparse "
            "matrix");
        return NULL;
    }
    if (uplo != 'U' && uplo != 'L') err_char("uplo", "'L', 'U'");
    if (!(perm = (matrix *) Matrix_New((int)SP_NROWS(A),1,INT)))
        return PyErr_NoMemory();
    n = SP_NROWS(A);
    for (nnz=0, j=0; j<n; j++) {
        if (uplo == 'L'){
            for (k=SP_COL(A)[j]; k<SP_COL(A)[j+1] && SP_ROW(A)[k]<j; k++);
            nnz += SP_COL(A)[j+1] - k;
        }
        else {
            for (k=SP_COL(A)[j]; k<SP_COL(A)[j+1] && SP_ROW(A)[k] <= j;
                k++);
            nnz += k - SP_COL(A)[j];
        }
    }
    if (nnz == SP_NNZ(A)){
        colptr = (int_t *) SP_COL(A);
        rowind = (int_t *) SP_ROW(A);
    }
    else {
        alloc = 1;
        colptr = (int_t *) calloc(n+1, sizeof(int_t));
        rowind = (int_t *) calloc(nnz, sizeof(int_t));
        if (!colptr || !rowind) {
            Py_XDECREF(perm);  free(colptr);  free(rowind);
            return PyErr_NoMemory();
        }
        colptr[0] = 0;
        for (j=0; j<n; j++) {
            if (uplo == 'L'){
                for (k=SP_COL(A)[j]; k<SP_COL(A)[j+1] && SP_ROW(A)[k] < j; 
                    k++);
                nnz = SP_COL(A)[j+1] - k;
                colptr[j+1] = colptr[j] + nnz;
                memcpy(rowind + colptr[j], (int_t *) SP_ROW(A) + k,
                    nnz*sizeof(int_t));
            }
            else {
                for (k=SP_COL(A)[j]; k<SP_COL(A)[j+1] && SP_ROW(A)[k] <= j;
                    k++);
                nnz = k - SP_COL(A)[j];
                colptr[j+1] = colptr[j] + nnz;
                memcpy(rowind + colptr[j], (int_t *) (SP_ROW(A) +
                    SP_COL(A)[j]), nnz*sizeof(int_t));
            }
        }
    }
    info = amd_order(n, colptr, rowind, MAT_BUFI(perm), control, NULL);
    if (alloc){
        free(colptr);
        free(rowind);
    }
    switch (info) {
        case AMD_OUT_OF_MEMORY:
            Py_XDECREF(perm);
            return PyErr_NoMemory();

        case AMD_INVALID:
            Py_XDECREF(perm);
            return Py_BuildValue("");

        case AMD_OK:
            return (PyObject *) perm;
    }
    return Py_BuildValue("");
}

static PyMethodDef amd_functions[] = {
    {"order", (PyCFunction) order_c, METH_VARARGS|METH_KEYWORDS, doc_order},
    {NULL}  /* Sentinel */
};

#if PY_MAJOR_VERSION >= 3

static PyModuleDef amd_module_def = {
    PyModuleDef_HEAD_INIT,
    "amd",
    amd__doc__,
    -1,
    amd_functions,
    NULL, NULL, NULL, NULL
};

PyMODINIT_FUNC PyInit_amd(void)
{
    if (!(amd_module = PyModule_Create(&amd_module_def))) return NULL;
    PyModule_AddObject(amd_module, "options", PyDict_New());
    if (import_cvxopt() < 0) return NULL;
    return amd_module;
}

#else
PyMODINIT_FUNC initamd(void)
{
    amd_module = Py_InitModule3("cvxopt.amd", amd_functions, amd__doc__);
    PyModule_AddObject(amd_module, "options", PyDict_New());
    if (import_cvxopt() < 0) return;
}
Exemplo n.º 14
0
static EnumPropertyItem *enum_items_from_py(PyObject *seq_fast, PyObject *def, int *defvalue, const short is_enum_flag)
{
	EnumPropertyItem *items;
	PyObject *item;
	const Py_ssize_t seq_len= PySequence_Fast_GET_SIZE(seq_fast);
	Py_ssize_t totbuf= 0;
	int i;
	short def_used= 0;
	const char *def_cmp= NULL;

	if(is_enum_flag) {
		if(seq_len > RNA_ENUM_BITFLAG_SIZE) {
			PyErr_SetString(PyExc_TypeError, "EnumProperty(...): maximum " STRINGIFY(RNA_ENUM_BITFLAG_SIZE) " members for a ENUM_FLAG type property");
			return NULL;
		}
		if(def && !PySet_Check(def)) {
			PyErr_Format(PyExc_TypeError,
			             "EnumProperty(...): default option must be a 'set' "
			             "type when ENUM_FLAG is enabled, not a '%.200s'",
			             Py_TYPE(def)->tp_name);
			return NULL;
		}
	}
	else {
		if(def) {
			def_cmp= _PyUnicode_AsString(def);
			if(def_cmp==NULL) {
				PyErr_Format(PyExc_TypeError,
				             "EnumProperty(...): default option must be a 'str' "
				             "type when ENUM_FLAG is disabled, not a '%.200s'",
				             Py_TYPE(def)->tp_name);
				return NULL;
			}
		}
	}

	/* blank value */
	*defvalue= 0;

	items= MEM_callocN(sizeof(EnumPropertyItem) * (seq_len + 1), "enum_items_from_py1");

	for(i=0; i<seq_len; i++) {
		EnumPropertyItem tmp= {0, "", 0, "", ""};
		Py_ssize_t id_str_size;
		Py_ssize_t name_str_size;
		Py_ssize_t desc_str_size;

		item= PySequence_Fast_GET_ITEM(seq_fast, i);

		if(		(PyTuple_CheckExact(item)) &&
		        (PyTuple_GET_SIZE(item) == 3) &&
		        (tmp.identifier=  _PyUnicode_AsStringAndSize(PyTuple_GET_ITEM(item, 0), &id_str_size)) &&
		        (tmp.name=        _PyUnicode_AsStringAndSize(PyTuple_GET_ITEM(item, 1), &name_str_size)) &&
		        (tmp.description= _PyUnicode_AsStringAndSize(PyTuple_GET_ITEM(item, 2), &desc_str_size))
		) {
			if(is_enum_flag) {
				tmp.value= 1<<i;

				if(def && PySet_Contains(def, PyTuple_GET_ITEM(item, 0))) {
					*defvalue |= tmp.value;
					def_used++;
				}
			}
			else {
				tmp.value= i;

				if(def && def_used == 0 && strcmp(def_cmp, tmp.identifier)==0) {
					*defvalue= tmp.value;
					def_used++; /* only ever 1 */
				}
			}

			items[i]= tmp;

			/* calculate combine string length */
			totbuf += id_str_size + name_str_size + desc_str_size + 3; /* 3 is for '\0's */
		}
		else {
			MEM_freeN(items);
			PyErr_SetString(PyExc_TypeError, "EnumProperty(...): expected an tuple containing (identifier, name description)");
			return NULL;
		}

	}

	if(is_enum_flag) {
		/* strict check that all set members were used */
		if(def && def_used != PySet_GET_SIZE(def)) {
			MEM_freeN(items);

			PyErr_Format(PyExc_TypeError,
			             "EnumProperty(..., default={...}): set has %d unused member(s)",
			             PySet_GET_SIZE(def) - def_used);
			return NULL;
		}
	}
	else {
		if(def && def_used == 0) {
			MEM_freeN(items);

			PyErr_Format(PyExc_TypeError,
			             "EnumProperty(..., default=\'%s\'): not found in enum members",
			             def);
			return NULL;
		}
	}

	/* disabled duplicating strings because the array can still be freed and
	 * the strings from it referenced, for now we can't support dynamically
	 * created strings from python. */
#if 0
	/* this would all work perfectly _but_ the python strings may be freed
	 * immediately after use, so we need to duplicate them, ugh.
	 * annoying because it works most of the time without this. */
	{
		EnumPropertyItem *items_dup= MEM_mallocN((sizeof(EnumPropertyItem) * (seq_len + 1)) + (sizeof(char) * totbuf), "enum_items_from_py2");
		EnumPropertyItem *items_ptr= items_dup;
		char *buf= ((char *)items_dup) + (sizeof(EnumPropertyItem) * (seq_len + 1));
		memcpy(items_dup, items, sizeof(EnumPropertyItem) * (seq_len + 1));
		for(i=0; i<seq_len; i++, items_ptr++) {
			buf += strswapbufcpy(buf, &items_ptr->identifier);
			buf += strswapbufcpy(buf, &items_ptr->name);
			buf += strswapbufcpy(buf, &items_ptr->description);
		}
		MEM_freeN(items);
		items=items_dup;
	}
	/* end string duplication */
#endif

	return items;
}
Exemplo n.º 15
0
/*
  Retrive the (optional) _pack_ attribute from a type, the _fields_ attribute,
  and create an StgDictObject.  Used for Structure and Union subclasses.
*/
int
PyCStructUnionType_update_stgdict(PyObject *type, PyObject *fields, int isStruct)
{
    StgDictObject *stgdict, *basedict;
    Py_ssize_t len, offset, size, align, i;
    Py_ssize_t union_size, total_align;
    Py_ssize_t field_size = 0;
    int bitofs;
    PyObject *isPacked;
    int pack = 0;
    Py_ssize_t ffi_ofs;
    int big_endian;

    /* HACK Alert: I cannot be bothered to fix ctypes.com, so there has to
       be a way to use the old, broken sematics: _fields_ are not extended
       but replaced in subclasses.

       XXX Remove this in ctypes 1.0!
    */
    int use_broken_old_ctypes_semantics;

    if (fields == NULL)
        return 0;

#ifdef WORDS_BIGENDIAN
    big_endian = PyObject_HasAttrString(type, "_swappedbytes_") ? 0 : 1;
#else
    big_endian = PyObject_HasAttrString(type, "_swappedbytes_") ? 1 : 0;
#endif

    use_broken_old_ctypes_semantics = \
        PyObject_HasAttrString(type, "_use_broken_old_ctypes_structure_semantics_");

    isPacked = PyObject_GetAttrString(type, "_pack_");
    if (isPacked) {
        pack = _PyLong_AsInt(isPacked);
        if (pack < 0 || PyErr_Occurred()) {
            Py_XDECREF(isPacked);
            PyErr_SetString(PyExc_ValueError,
                            "_pack_ must be a non-negative integer");
            return -1;
        }
        Py_DECREF(isPacked);
    } else
        PyErr_Clear();

    len = PySequence_Length(fields);
    if (len == -1) {
        PyErr_SetString(PyExc_TypeError,
                        "'_fields_' must be a sequence of pairs");
        return -1;
    }

    stgdict = PyType_stgdict(type);
    if (!stgdict)
        return -1;
    /* If this structure/union is already marked final we cannot assign
       _fields_ anymore. */

    if (stgdict->flags & DICTFLAG_FINAL) {/* is final ? */
        PyErr_SetString(PyExc_AttributeError,
                        "_fields_ is final");
        return -1;
    }

    if (stgdict->format) {
        PyMem_Free(stgdict->format);
        stgdict->format = NULL;
    }

    if (stgdict->ffi_type_pointer.elements)
        PyMem_Free(stgdict->ffi_type_pointer.elements);

    basedict = PyType_stgdict((PyObject *)((PyTypeObject *)type)->tp_base);
    if (basedict && !use_broken_old_ctypes_semantics) {
        size = offset = basedict->size;
        align = basedict->align;
        union_size = 0;
        total_align = align ? align : 1;
        stgdict->ffi_type_pointer.type = FFI_TYPE_STRUCT;
        stgdict->ffi_type_pointer.elements = PyMem_Malloc(sizeof(ffi_type *) * (basedict->length + len + 1));
        if (stgdict->ffi_type_pointer.elements == NULL) {
            PyErr_NoMemory();
            return -1;
        }
        memset(stgdict->ffi_type_pointer.elements, 0,
               sizeof(ffi_type *) * (basedict->length + len + 1));
        memcpy(stgdict->ffi_type_pointer.elements,
               basedict->ffi_type_pointer.elements,
               sizeof(ffi_type *) * (basedict->length));
        ffi_ofs = basedict->length;
    } else {
        offset = 0;
        size = 0;
        align = 0;
        union_size = 0;
        total_align = 1;
        stgdict->ffi_type_pointer.type = FFI_TYPE_STRUCT;
        stgdict->ffi_type_pointer.elements = PyMem_Malloc(sizeof(ffi_type *) * (len + 1));
        if (stgdict->ffi_type_pointer.elements == NULL) {
            PyErr_NoMemory();
            return -1;
        }
        memset(stgdict->ffi_type_pointer.elements, 0,
               sizeof(ffi_type *) * (len + 1));
        ffi_ofs = 0;
    }

    assert(stgdict->format == NULL);
    if (isStruct && !isPacked) {
        stgdict->format = _ctypes_alloc_format_string(NULL, "T{");
    } else {
        /* PEP3118 doesn't support union, or packed structures (well,
           only standard packing, but we dont support the pep for
           that). Use 'B' for bytes. */
        stgdict->format = _ctypes_alloc_format_string(NULL, "B");
    }

#define realdict ((PyObject *)&stgdict->dict)
    for (i = 0; i < len; ++i) {
        PyObject *name = NULL, *desc = NULL;
        PyObject *pair = PySequence_GetItem(fields, i);
        PyObject *prop;
        StgDictObject *dict;
        int bitsize = 0;

        if (!pair || !PyArg_ParseTuple(pair, "UO|i", &name, &desc, &bitsize)) {
            PyErr_SetString(PyExc_TypeError,
                            "'_fields_' must be a sequence of (name, C type) pairs");
            Py_XDECREF(pair);
            return -1;
        }
        dict = PyType_stgdict(desc);
        if (dict == NULL) {
            Py_DECREF(pair);
            PyErr_Format(PyExc_TypeError,
                         "second item in _fields_ tuple (index %zd) must be a C type",
                         i);
            return -1;
        }
        stgdict->ffi_type_pointer.elements[ffi_ofs + i] = &dict->ffi_type_pointer;
        if (dict->flags & (TYPEFLAG_ISPOINTER | TYPEFLAG_HASPOINTER))
            stgdict->flags |= TYPEFLAG_HASPOINTER;
        dict->flags |= DICTFLAG_FINAL; /* mark field type final */
        if (PyTuple_Size(pair) == 3) { /* bits specified */
            switch(dict->ffi_type_pointer.type) {
            case FFI_TYPE_UINT8:
            case FFI_TYPE_UINT16:
            case FFI_TYPE_UINT32:
            case FFI_TYPE_SINT64:
            case FFI_TYPE_UINT64:
                break;

            case FFI_TYPE_SINT8:
            case FFI_TYPE_SINT16:
            case FFI_TYPE_SINT32:
                if (dict->getfunc != _ctypes_get_fielddesc("c")->getfunc
#ifdef CTYPES_UNICODE
                    && dict->getfunc != _ctypes_get_fielddesc("u")->getfunc
#endif
                    )
                    break;
                /* else fall through */
            default:
                PyErr_Format(PyExc_TypeError,
                             "bit fields not allowed for type %s",
                             ((PyTypeObject *)desc)->tp_name);
                Py_DECREF(pair);
                return -1;
            }
            if (bitsize <= 0 || bitsize > dict->size * 8) {
                PyErr_SetString(PyExc_ValueError,
                                "number of bits invalid for bit field");
                Py_DECREF(pair);
                return -1;
            }
        } else
            bitsize = 0;

        if (isStruct && !isPacked) {
            char *fieldfmt = dict->format ? dict->format : "B";
            char *fieldname = _PyUnicode_AsString(name);
            char *ptr;
            Py_ssize_t len; 
            char *buf;

            if (fieldname == NULL)
            {
                Py_DECREF(pair);
                return -1;
            }

            len = strlen(fieldname) + strlen(fieldfmt);

            buf = PyMem_Malloc(len + 2 + 1);
            if (buf == NULL) {
                Py_DECREF(pair);
                PyErr_NoMemory();
                return -1;
            }
            sprintf(buf, "%s:%s:", fieldfmt, fieldname);

            ptr = stgdict->format;
            stgdict->format = _ctypes_alloc_format_string(stgdict->format, buf);
            PyMem_Free(ptr);
            PyMem_Free(buf);

            if (stgdict->format == NULL) {
                Py_DECREF(pair);
                return -1;
            }
        }

        if (isStruct) {
            prop = PyCField_FromDesc(desc, i,
                                   &field_size, bitsize, &bitofs,
                                   &size, &offset, &align,
                                   pack, big_endian);
        } else /* union */ {
            size = 0;
            offset = 0;
            align = 0;
            prop = PyCField_FromDesc(desc, i,
                                   &field_size, bitsize, &bitofs,
                                   &size, &offset, &align,
                                   pack, big_endian);
            union_size = max(size, union_size);
        }
        total_align = max(align, total_align);

        if (!prop) {
            Py_DECREF(pair);
            return -1;
        }
        if (-1 == PyObject_SetAttr(type, name, prop)) {
            Py_DECREF(prop);
            Py_DECREF(pair);
            return -1;
        }
        Py_DECREF(pair);
        Py_DECREF(prop);
    }
#undef realdict

    if (isStruct && !isPacked) {
        char *ptr = stgdict->format;
        stgdict->format = _ctypes_alloc_format_string(stgdict->format, "}");
        PyMem_Free(ptr);
        if (stgdict->format == NULL)
            return -1;
    }

    if (!isStruct)
        size = union_size;

    /* Adjust the size according to the alignment requirements */
    size = ((size + total_align - 1) / total_align) * total_align;

    stgdict->ffi_type_pointer.alignment = Py_SAFE_DOWNCAST(total_align,
                                                           Py_ssize_t,
                                                           unsigned short);
    stgdict->ffi_type_pointer.size = size;

    stgdict->size = size;
    stgdict->align = total_align;
    stgdict->length = len;      /* ADD ffi_ofs? */

    /* We did check that this flag was NOT set above, it must not
       have been set until now. */
    if (stgdict->flags & DICTFLAG_FINAL) {
        PyErr_SetString(PyExc_AttributeError,
                        "Structure or union cannot contain itself");
        return -1;
    }
    stgdict->flags |= DICTFLAG_FINAL;

    return MakeAnonFields(type);
}
Exemplo n.º 16
0
static PyObject *bpy_lib_exit(BPy_Library *self, PyObject *UNUSED(args))
{
	Main *bmain = CTX_data_main(BPy_GetContext());
	Main *mainl = NULL;
	int err = 0;

	BKE_main_id_flag_all(bmain, LIB_TAG_PRE_EXISTING, true);

	/* here appending/linking starts */
	mainl = BLO_library_link_begin(bmain, &(self->blo_handle), self->relpath);

	{
		int idcode_step = 0, idcode;
		while ((idcode = BKE_idcode_iter_step(&idcode_step))) {
			if (BKE_idcode_is_linkable(idcode)) {
				const char *name_plural = BKE_idcode_to_name_plural(idcode);
				PyObject *ls = PyDict_GetItemString(self->dict, name_plural);
				// printf("lib: %s\n", name_plural);
				if (ls && PyList_Check(ls)) {
					/* loop */
					Py_ssize_t size = PyList_GET_SIZE(ls);
					Py_ssize_t i;
					PyObject *item;
					const char *item_str;

					for (i = 0; i < size; i++) {
						item = PyList_GET_ITEM(ls, i);
						item_str = _PyUnicode_AsString(item);

						// printf("  %s\n", item_str);

						if (item_str) {
							ID *id = BLO_library_link_named_part(mainl, &(self->blo_handle), idcode, item_str);
							if (id) {
#ifdef USE_RNA_DATABLOCKS
								/* swap name for pointer to the id */
								Py_DECREF(item);
								item = PyCapsule_New((void *)id, NULL, NULL);
#endif
							}
							else {
								bpy_lib_exit_warn_idname(self, name_plural, item_str);
								/* just warn for now */
								/* err = -1; */
#ifdef USE_RNA_DATABLOCKS
								item = Py_INCREF_RET(Py_None);
#endif
							}

							/* ID or None */
						}
						else {
							/* XXX, could complain about this */
							bpy_lib_exit_warn_type(self, item);
							PyErr_Clear();

#ifdef USE_RNA_DATABLOCKS
							item = Py_INCREF_RET(Py_None);
#endif
						}

#ifdef USE_RNA_DATABLOCKS
						PyList_SET_ITEM(ls, i, item);
#endif
					}
				}
			}
		}
	}

	if (err == -1) {
		/* exception raised above, XXX, this leaks some memory */
		BLO_blendhandle_close(self->blo_handle);
		self->blo_handle = NULL;
		BKE_main_id_flag_all(bmain, LIB_TAG_PRE_EXISTING, false);
		return NULL;
	}
	else {
		Library *lib = mainl->curlib; /* newly added lib, assign before append end */
		BLO_library_link_end(mainl, &(self->blo_handle), self->flag, NULL, NULL);
		BLO_blendhandle_close(self->blo_handle);
		self->blo_handle = NULL;

		/* copied from wm_operator.c */
		{
			/* mark all library linked objects to be updated */
			BKE_main_lib_objects_recalc_all(G.main);

			/* append, rather than linking */
			if ((self->flag & FILE_LINK) == 0) {
				BKE_library_make_local(bmain, lib, true);
			}
		}

		BKE_main_id_flag_all(bmain, LIB_TAG_PRE_EXISTING, false);

		/* finally swap the capsules for real bpy objects
		 * important since BLO_library_append_end initializes NodeTree types used by srna->refine */
		{
			int idcode_step = 0, idcode;
			while ((idcode = BKE_idcode_iter_step(&idcode_step))) {
				if (BKE_idcode_is_linkable(idcode)) {
					const char *name_plural = BKE_idcode_to_name_plural(idcode);
					PyObject *ls = PyDict_GetItemString(self->dict, name_plural);
					if (ls && PyList_Check(ls)) {
						Py_ssize_t size = PyList_GET_SIZE(ls);
						Py_ssize_t i;
						PyObject *item;

						for (i = 0; i < size; i++) {
							item = PyList_GET_ITEM(ls, i);
							if (PyCapsule_CheckExact(item)) {
								PointerRNA id_ptr;
								ID *id;

								id = PyCapsule_GetPointer(item, NULL);
								Py_DECREF(item);

								RNA_id_pointer_create(id, &id_ptr);
								item = pyrna_struct_CreatePyObject(&id_ptr);
								PyList_SET_ITEM(ls, i, item);
							}
						}
					}
				}
			}
		}

		Py_RETURN_NONE;
	}
}
Exemplo n.º 17
0
static void _build_translations_cache(PyObject *py_messages, const char *locale)
{
	PyObject *uuid, *uuid_dict;
	Py_ssize_t pos = 0;
	char *language = NULL, *language_country = NULL, *language_variant = NULL;

	/* For each py dict, we'll search for full locale, then language+country, then language+variant,
	 * then only language keys... */
	BLF_locale_explode(locale, &language, NULL, NULL, &language_country, &language_variant);

	/* Clear the cached ghash if needed, and create a new one. */
	_clear_translations_cache();
	_translations_cache = BLI_ghash_new(_ghashutil_keyhash, _ghashutil_keycmp, __func__);

	/* Iterate over all py dicts. */
	while (PyDict_Next(py_messages, &pos, &uuid, &uuid_dict)) {
		PyObject *lang_dict;

#if 0
		PyObject_Print(uuid_dict, stdout, 0);
		printf("\n");
#endif

		/* Try to get first complete locale, then language+country, then language+variant, then only language */
		lang_dict = PyDict_GetItemString(uuid_dict, locale);
		if (!lang_dict && language_country) {
			lang_dict = PyDict_GetItemString(uuid_dict, language_country);
			locale = language_country;
		}
		if (!lang_dict && language_variant) {
			lang_dict = PyDict_GetItemString(uuid_dict, language_variant);
			locale = language_variant;
		}
		if (!lang_dict && language) {
			lang_dict = PyDict_GetItemString(uuid_dict, language);
			locale = language;
		}

		if (lang_dict) {
			PyObject *pykey, *trans;
			Py_ssize_t ppos = 0;

			if (!PyDict_Check(lang_dict)) {
				printf("WARNING! In translations' dict of \"");
				PyObject_Print(uuid, stdout, Py_PRINT_RAW);
				printf("\":\n");
				printf("    Each language key must have a dictionary as value, \"%s\" is not valid, skipping: ",
				       locale);
				PyObject_Print(lang_dict, stdout, Py_PRINT_RAW);
				printf("\n");
				continue;
			}

			/* Iterate over all translations of the found language dict, and populate our ghash cache. */
			while (PyDict_Next(lang_dict, &ppos, &pykey, &trans)) {
				GHashKey *key;
				const char *msgctxt = NULL, *msgid = NULL;
				bool invalid_key = false;

				if ((PyTuple_CheckExact(pykey) == false) || (PyTuple_GET_SIZE(pykey) != 2)) {
					invalid_key = true;
				}
				else {
					PyObject *tmp = PyTuple_GET_ITEM(pykey, 0);
					if (tmp == Py_None) {
						msgctxt = BLF_I18NCONTEXT_DEFAULT_BPYRNA;
					}
					else if (PyUnicode_Check(tmp)) {
						msgctxt = _PyUnicode_AsString(tmp);
					}
					else {
						invalid_key = true;
					}

					tmp = PyTuple_GET_ITEM(pykey, 1);
					if (PyUnicode_Check(tmp)) {
						msgid = _PyUnicode_AsString(tmp);
					}
					else {
						invalid_key = true;
					}
				}

				if (invalid_key) {
					printf("WARNING! In translations' dict of \"");
					PyObject_Print(uuid, stdout, Py_PRINT_RAW);
					printf("\", %s language:\n", locale);
					printf("    Keys must be tuples of (msgctxt [string or None], msgid [string]), "
					       "this one is not valid, skipping: ");
					PyObject_Print(pykey, stdout, Py_PRINT_RAW);
					printf("\n");
					continue;
				}
				if (PyUnicode_Check(trans) == false) {
					printf("WARNING! In translations' dict of \"");
					PyObject_Print(uuid, stdout, Py_PRINT_RAW);
					printf("\":\n");
					printf("    Values must be strings, this one is not valid, skipping: ");
					PyObject_Print(trans, stdout, Py_PRINT_RAW);
					printf("\n");
					continue;
				}

				key = _ghashutil_keyalloc(msgctxt, msgid);

				/* Do not overwrite existing keys! */
				if (BLI_ghash_lookup(_translations_cache, (void *)key)) {
					continue;
				}

				BLI_ghash_insert(_translations_cache, key, BLI_strdup(_PyUnicode_AsString(trans)));
			}
		}
	}

	/* Clean up! */
	MEM_SAFE_FREE(language);
	MEM_SAFE_FREE(language_country);
	MEM_SAFE_FREE(language_variant);
}
Exemplo n.º 18
0
static const char *traceback_filepath(PyTracebackObject *tb)
{
	return _PyUnicode_AsString(tb->tb_frame->f_code->co_filename);
}
Exemplo n.º 19
0
PyObject* pysqlite_row_subscript(pysqlite_Row* self, PyObject* idx)
{
    Py_ssize_t _idx;
    char* key;
    Py_ssize_t nitems, i;
    char* compare_key;

    char* p1;
    char* p2;

    PyObject* item;

    if (PyLong_Check(idx)) {
        _idx = PyNumber_AsSsize_t(idx, PyExc_IndexError);
        if (_idx == -1 && PyErr_Occurred())
            return NULL;
        if (_idx < 0)
           _idx += PyTuple_GET_SIZE(self->data);
        item = PyTuple_GetItem(self->data, _idx);
        Py_XINCREF(item);
        return item;
#if PY_MAJOR_VERSION < 3
    } else if (PyString_Check(idx)) {
        key = PyString_AsString(idx);
#else
    } else if (PyUnicode_Check(idx)) {
        key = _PyUnicode_AsString(idx);
#endif
        if (key == NULL)
            return NULL;

        nitems = PyTuple_Size(self->description);

        for (i = 0; i < nitems; i++) {
            PyObject *obj;
            obj = PyTuple_GET_ITEM(self->description, i);
            obj = PyTuple_GET_ITEM(obj, 0);
#if PY_MAJOR_VERSION < 3
            compare_key = PyString_AsString(obj);
#else
            compare_key = _PyUnicode_AsString(obj);
#endif
            if (!compare_key) {
                return NULL;
            }

            p1 = key;
            p2 = compare_key;

            while (1) {
                if ((*p1 == (char)0) || (*p2 == (char)0)) {
                    break;
                }

                if ((*p1 | 0x20) != (*p2 | 0x20)) {
                    break;
                }

                p1++;
                p2++;
            }

            if ((*p1 == (char)0) && (*p2 == (char)0)) {
                /* found item */
                item = PyTuple_GetItem(self->data, i);
                Py_INCREF(item);
                return item;
            }

        }

        PyErr_SetString(PyExc_IndexError, "No item with that key");
        return NULL;
    } else if (PySlice_Check(idx)) {
        return PyObject_GetItem(self->data, idx);
    } else {
        PyErr_SetString(PyExc_IndexError, "Index must be int or string");
        return NULL;
    }
}
Exemplo n.º 20
0
static int set_options(void)
{
    int_t pos=0;
    PyObject *param, *key, *value;
    char err_str[100];
#if PY_MAJOR_VERSION < 3
    char *keystr; 
#endif

    CHOL(defaults)(&Common);
    Common.print = 0;
    Common.supernodal = 2;

    if (!(param = PyObject_GetAttrString(cholmod_module, "options")) ||
        ! PyDict_Check(param)) {
        PyErr_SetString(PyExc_AttributeError, "missing cholmod.options"
            "dictionary");
        return 0;
    }
    while (PyDict_Next(param, &pos, &key, &value))
#if PY_MAJOR_VERSION >= 3
        if (PyUnicode_Check(key)) {
            const char *keystr = _PyUnicode_AsString(key);
            if (!strcmp("supernodal", keystr) && PyLong_Check(value))
                Common.supernodal = (int) PyLong_AsLong(value);
            else if (!strcmp("print", keystr) && PyLong_Check(value))
                Common.print = (int) PyLong_AsLong(value);
            else if (!strcmp("nmethods", keystr) && PyLong_Check(value))
                Common.nmethods = (int) PyLong_AsLong(value);
            else if (!strcmp("postorder", keystr) &&
                PyBool_Check(value))
                Common.postorder = (int) PyLong_AsLong(value);
            else if (!strcmp("dbound", keystr) && PyFloat_Check(value))
                Common.dbound = (double) PyFloat_AsDouble(value);
            else {
                sprintf(err_str, "invalid value for CHOLMOD parameter:" \
                   " %-.20s", keystr);
                PyErr_SetString(PyExc_ValueError, err_str);
                Py_DECREF(param);
                return 0;
            }
        }
#else
        if ((keystr = PyString_AsString(key))) {
            if (!strcmp("supernodal", keystr) && PyInt_Check(value))
                Common.supernodal = (int) PyInt_AsLong(value);
            else if (!strcmp("print", keystr) && PyInt_Check(value))
                Common.print = (int) PyInt_AsLong(value);
            else if (!strcmp("nmethods", keystr) && PyInt_Check(value))
                Common.nmethods = (int) PyInt_AsLong(value);
            else if (!strcmp("postorder", keystr) &&
                PyBool_Check(value))
                Common.postorder = (int) PyInt_AsLong(value);
            else if (!strcmp("dbound", keystr) && PyFloat_Check(value))
                Common.dbound = (double) PyFloat_AsDouble(value);
            else {
                sprintf(err_str, "invalid value for CHOLMOD parameter:" \
                   " %-.20s", keystr);
                PyErr_SetString(PyExc_ValueError, err_str);
                Py_DECREF(param);
                return 0;
            }
        }
#endif
    Py_DECREF(param);
    return 1;
}
Exemplo n.º 21
0
void
_PyModule_Clear(PyObject *m)
{
    /* To make the execution order of destructors for global
       objects a bit more predictable, we first zap all objects
       whose name starts with a single underscore, before we clear
       the entire dictionary.  We zap them by replacing them with
       None, rather than deleting them from the dictionary, to
       avoid rehashing the dictionary (to some extent). */

    Py_ssize_t pos;
    PyObject *key, *value;
    PyObject *d;

    d = ((PyModuleObject *)m)->md_dict;
    if (d == NULL)
        return;

    /* First, clear only names starting with a single underscore */
    pos = 0;
    while (PyDict_Next(d, &pos, &key, &value)) {
        if (value != Py_None && PyUnicode_Check(key)) {
            if (PyUnicode_READ_CHAR(key, 0) == '_' &&
                PyUnicode_READ_CHAR(key, 1) != '_') {
                if (Py_VerboseFlag > 1) {
                    const char *s = _PyUnicode_AsString(key);
                    if (s != NULL)
                        PySys_WriteStderr("#   clear[1] %s\n", s);
                    else
                        PyErr_Clear();
                }
                if (PyDict_SetItem(d, key, Py_None) != 0)
                    PyErr_Clear();
            }
        }
    }

    /* Next, clear all names except for __builtins__ */
    pos = 0;
    while (PyDict_Next(d, &pos, &key, &value)) {
        if (value != Py_None && PyUnicode_Check(key)) {
            if (PyUnicode_READ_CHAR(key, 0) != '_' ||
                PyUnicode_CompareWithASCIIString(key, "__builtins__") != 0)
            {
                if (Py_VerboseFlag > 1) {
                    const char *s = _PyUnicode_AsString(key);
                    if (s != NULL)
                        PySys_WriteStderr("#   clear[2] %s\n", s);
                    else
                        PyErr_Clear();
                }
                if (PyDict_SetItem(d, key, Py_None) != 0)
                    PyErr_Clear();
            }
        }
    }

    /* Note: we leave __builtins__ in place, so that destructors
       of non-global objects defined in this module can still use
       builtins, in particularly 'None'. */

}
Exemplo n.º 22
0
PyObject* BL_ActionActuator::PyGetChannel(PyObject* value)
{
	PyErr_SetString(PyExc_NotImplementedError, "BL_ActionActuator.getChannel() no longer works, please use BL_ArmatureObject.channels instead");
	return NULL;
#if 0 // XXX To be removed in a later version (first removed in 2.64)
	const char *string= _PyUnicode_AsString(value);

	if (GetParent()->GetGameObjectType() != SCA_IObject::OBJ_ARMATURE)
	{
		PyErr_SetString(PyExc_NotImplementedError, "actuator.getChannel(): Only armatures support channels");
		return NULL;
	}
	
	if (!string) {
		PyErr_SetString(PyExc_TypeError, "expected a single string");
		return NULL;
	}
	
	bPoseChannel *pchan;
	
	if (m_userpose==NULL && m_pose==NULL) {
		BL_ArmatureObject *obj = (BL_ArmatureObject*)GetParent();
		obj->GetPose(&m_pose); /* Get the underlying pose from the armature */
	}
	
	// BKE_pose_channel_find_name accounts for NULL pose, run on both in case one exists but
	// the channel doesnt
	if (		!(pchan=BKE_pose_channel_find_name(m_userpose, string)) &&
			!(pchan=BKE_pose_channel_find_name(m_pose, string))  )
	{
		PyErr_SetString(PyExc_ValueError, "channel doesnt exist");
		return NULL;
	}

	PyObject *ret = PyTuple_New(3);
	
	PyObject *list = PyList_New(3); 
	PyList_SET_ITEM(list, 0, PyFloat_FromDouble(pchan->loc[0]));
	PyList_SET_ITEM(list, 1, PyFloat_FromDouble(pchan->loc[1]));
	PyList_SET_ITEM(list, 2, PyFloat_FromDouble(pchan->loc[2]));
	PyTuple_SET_ITEM(ret, 0, list);
	
	list = PyList_New(3);
	PyList_SET_ITEM(list, 0, PyFloat_FromDouble(pchan->size[0]));
	PyList_SET_ITEM(list, 1, PyFloat_FromDouble(pchan->size[1]));
	PyList_SET_ITEM(list, 2, PyFloat_FromDouble(pchan->size[2]));
	PyTuple_SET_ITEM(ret, 1, list);
	
	list = PyList_New(4);
	PyList_SET_ITEM(list, 0, PyFloat_FromDouble(pchan->quat[0]));
	PyList_SET_ITEM(list, 1, PyFloat_FromDouble(pchan->quat[1]));
	PyList_SET_ITEM(list, 2, PyFloat_FromDouble(pchan->quat[2]));
	PyList_SET_ITEM(list, 3, PyFloat_FromDouble(pchan->quat[3]));
	PyTuple_SET_ITEM(ret, 2, list);

	return ret;
#if 0
	return Py_BuildValue("([fff][fff][ffff])",
		pchan->loc[0], pchan->loc[1], pchan->loc[2],
		pchan->size[0], pchan->size[1], pchan->size[2],
		pchan->quat[0], pchan->quat[1], pchan->quat[2], pchan->quat[3] );
#endif
#endif
}
Exemplo n.º 23
0
int    KX_VertexProxy::py_setattro(PyObject *attr, PyObject *pyvalue)
{
  char *attr_str= _PyUnicode_AsString(attr);
  if (PySequence_Check(pyvalue))
  {
	if (!strcmp(attr_str, "XYZ"))
	{
		MT_Point3 vec;
		if (PyVecTo(pyvalue, vec))
		{
			m_vertex->SetXYZ(vec);
			m_mesh->SetMeshModified(true);
			return PY_SET_ATTR_SUCCESS;
		}
		return PY_SET_ATTR_FAIL;
	}

	if (!strcmp(attr_str, "UV"))
	{
		MT_Point2 vec;
		if (PyVecTo(pyvalue, vec))
		{
			m_vertex->SetUV(vec);
			m_mesh->SetMeshModified(true);
			return PY_SET_ATTR_SUCCESS;
		}
		return PY_SET_ATTR_FAIL;
	}

	if (!strcmp(attr_str, "color") || !strcmp(attr_str, "colour"))
	{
		MT_Vector4 vec;
		if (PyVecTo(pyvalue, vec))
		{
			m_vertex->SetRGBA(vec);
			m_mesh->SetMeshModified(true);
			return PY_SET_ATTR_SUCCESS;
		}
		return PY_SET_ATTR_FAIL;
	}

	if (!strcmp(attr_str, "normal"))
	{
		MT_Vector3 vec;
		if (PyVecTo(pyvalue, vec))
		{
			m_vertex->SetNormal(vec);
			m_mesh->SetMeshModified(true);
			return PY_SET_ATTR_SUCCESS;
		}
		return PY_SET_ATTR_FAIL;
	}
  }

  if (PyFloat_Check(pyvalue))
  {
  	float val = PyFloat_AsDouble(pyvalue);
  	// pos
	MT_Point3 pos(m_vertex->getXYZ());
  	if (!strcmp(attr_str, "x"))
	{
		pos.x() = val;
		m_vertex->SetXYZ(pos);
		m_mesh->SetMeshModified(true);
		return PY_SET_ATTR_SUCCESS;
	}

  	if (!strcmp(attr_str, "y"))
	{
		pos.y() = val;
		m_vertex->SetXYZ(pos);
		m_mesh->SetMeshModified(true);
		return PY_SET_ATTR_SUCCESS;
	}

	if (!strcmp(attr_str, "z"))
	{
		pos.z() = val;
		m_vertex->SetXYZ(pos);
		m_mesh->SetMeshModified(true);
		return PY_SET_ATTR_SUCCESS;
	}

	// uv
	MT_Point2 uv = m_vertex->getUV1();
	if (!strcmp(attr_str, "u"))
	{
		uv[0] = val;
		m_vertex->SetUV(uv);
		m_mesh->SetMeshModified(true);
		return PY_SET_ATTR_SUCCESS;
	}

	if (!strcmp(attr_str, "v"))
	{
		uv[1] = val;
		m_vertex->SetUV(uv);
		m_mesh->SetMeshModified(true);
		return PY_SET_ATTR_SUCCESS;
	}

	// uv
	MT_Point2 uv2 = m_vertex->getUV2();
	if (!strcmp(attr_str, "u2"))
	{
		uv[0] = val;
		m_vertex->SetUV2(uv);
		m_mesh->SetMeshModified(true);
		return 0;
	}

	if (!strcmp(attr_str, "v2"))
	{
		uv[1] = val;
		m_vertex->SetUV2(uv);
		m_mesh->SetMeshModified(true);
		return PY_SET_ATTR_SUCCESS;
	}

	// col
	unsigned int icol = *((const unsigned int *)m_vertex->getRGBA());
	unsigned char *cp = (unsigned char*) &icol;
	val *= 255.0;
	if (!strcmp(attr_str, "r"))
	{
		cp[0] = (unsigned char) val;
		m_vertex->SetRGBA(icol);
		m_mesh->SetMeshModified(true);
		return PY_SET_ATTR_SUCCESS;
	}
	if (!strcmp(attr_str, "g"))
	{
		cp[1] = (unsigned char) val;
		m_vertex->SetRGBA(icol);
		m_mesh->SetMeshModified(true);
		return PY_SET_ATTR_SUCCESS;
	}
	if (!strcmp(attr_str, "b"))
	{
		cp[2] = (unsigned char) val;
		m_vertex->SetRGBA(icol);
		m_mesh->SetMeshModified(true);
		return PY_SET_ATTR_SUCCESS;
	}
	if (!strcmp(attr_str, "a"))
	{
		cp[3] = (unsigned char) val;
		m_vertex->SetRGBA(icol);
		m_mesh->SetMeshModified(true);
		return PY_SET_ATTR_SUCCESS;
	}
  }

  return CValue::py_setattro(attr, pyvalue);
}