Exemple #1
0
static PyObject *pair_repr(PyObject *self) {
  PyObject *tmp = NULL;
  PyObject *col = PyList_New(0);
  PyObject *found = PyDict_New();
  size_t index = 0;

  PyObject *rest = self;
  PyObject *rest_id;

  PyList_Append(col, _str_cons_paren);

  while (rest->ob_type == &SibPairType) {
    rest_id = PyLong_FromVoidPtr(rest);

    if (PyDict_Contains(found, rest_id)) {
      /* recursive pair detected */
      PyList_Append(col, _str_recursive_true);

      if (rest != self) {
	tmp = PyDict_GetItem(found, rest_id);
	PyList_Insert(col, PyLong_AsSize_t(tmp) - 1, _str_cons_paren);
	PyList_Append(col, _str_close_paren);
      }
      Py_DECREF(rest_id);
      rest = NULL;
      break;

    } else {
      index += 2;

      tmp = PyLong_FromSize_t(index);
      PyDict_SetItem(found, rest_id, tmp);
      Py_DECREF(tmp);

      tmp = PyObject_Repr(SibPair_CAR(rest));
      PyList_Append(col, tmp);
      PyList_Append(col, _str_comma_space);
      Py_DECREF(tmp);

      rest = SibPair_CDR(rest);
      Py_DECREF(rest_id);
    }
  }

  if (rest) {
    PyList_Append(col, PyObject_Repr(rest));
  }

  PyList_Append(col, _str_close_paren);

  tmp = PyUnicode_Join(_str_empty, col);
  Py_DECREF(col);
  Py_DECREF(found);

  return tmp;
}
Exemple #2
0
static PyObject *
join_list_unicode(PyObject *lst)
{
    /* return ''.join(lst) */
    PyObject *sep, *ret;
    sep = PyUnicode_FromStringAndSize("", 0);
    ret = PyUnicode_Join(sep, lst);
    Py_DECREF(sep);
    return ret;
}
static PyObject *join_py_strings(const char *separator, PyObject *strings_seq)
{
    PyObject *py_separator = PyUnicode_FromString(separator);
    if (!py_separator) {
        log(LOG_ERR,
                "Unable to join python strings: PyUnicode_FromString() failed");
        log_python_exception();
        return NULL;
    }
    PyObject *py_result = PyUnicode_Join(py_separator, strings_seq);
    if (!py_result) {
        log(LOG_ERR,
                "Unable to join python strings: PyUnicode_Join() failed");
        log_python_exception();
        Py_DECREF(py_separator);
        return NULL;
    }
    Py_DECREF(py_separator);
    return py_result;
}
Exemple #4
0
static void
finalize_data(pycbc_HttpResult *htres)
{
    PyObject *sep;
    PyObject *res;

    if (htres->format != PYCBC_FMT_JSON && htres->format != PYCBC_FMT_UTF8) {
        return;
    }

    if (!PyObject_IsTrue(htres->http_data)) {
        return;
    }

    sep = pycbc_SimpleStringZ("");
    res = PyUnicode_Join(sep, htres->http_data);

    Py_DECREF(sep);

    /* Set the bytes */
    Py_DECREF(htres->http_data);
    htres->http_data = res;


    if (htres->format == PYCBC_FMT_JSON) {
        PyObject *args = Py_BuildValue("(O)", htres->http_data);

        pycbc_assert(PyErr_Occurred() == NULL);
        res = PyObject_CallObject(pycbc_helpers.json_decode, args);

        if (res) {
            Py_XDECREF(htres->http_data);
            htres->http_data = res;

        } else {
            PyErr_Clear();
        }

        Py_XDECREF(args);
    }
}
Exemple #5
0
QString
QPythonPriv::formatExc()
{
    PyObject *type = NULL;
    PyObject *value = NULL;
    PyObject *traceback = NULL;
    PyErr_Fetch(&type, &value, &traceback);
    PyErr_Clear();

    if (type == NULL && value == NULL && traceback == NULL) {
        return "No Error";
    }

    if (value != NULL && (type == NULL || traceback == NULL)) {
        return convertPyObjectToQVariant(PyObject_Str(value)).toString();
    }

    PyObject *list = PyObject_CallMethod(traceback_mod,
                                         "format_exception", "OOO", type, value, traceback);
    Q_ASSERT(list != NULL);
    PyObject *n = PyUnicode_FromString("\n");
    Q_ASSERT(n != NULL);
    PyObject *s = PyUnicode_Join(n, list);
    Q_ASSERT(s != NULL);
    if (s == NULL) {
        PyErr_Print();
        return "Exception";
    }
    QVariant v = convertPyObjectToQVariant(s);
    Q_ASSERT(v.isValid());
    Py_DECREF(s);
    Py_DECREF(n);
    Py_DECREF(list);

    Py_DECREF(type);
    Py_DECREF(value);
    Py_DECREF(traceback);

    qDebug() << v.toString();
    return v.toString();
}
Exemple #6
0
static PyObject *node_to_string(PyObject *node)
{
  PyObject *nodeType, *result, *descendants;

  nodeType = PyObject_GetAttrString(node, "nodeType");
  if (nodeType == NULL) {
    PyErr_Clear();
    return PyUnicode_FromUnicode(NULL, 0);
  }
  
  /* convert DOM node to string */
  switch (PyInt_AsLong(nodeType)) {
  case DOCUMENT_NODE:
  case ELEMENT_NODE:
    /* The concatenation of all text descendants in document order */
    descendants = PyList_New(0);
    if (node_descendants(node, descendants) == NULL) {
      Py_DECREF(descendants);
      return NULL;
    }
    result = PyUnicode_Join(PyUnicode_FromUnicode(NULL, 0), descendants);
    Py_DECREF(descendants);
    break;
  case ATTRIBUTE_NODE:
  case XPATH_NAMESPACE_NODE:
    result = PyObject_GetAttrString(node, "value");
    break;
  case PROCESSING_INSTRUCTION_NODE:
  case COMMENT_NODE:
  case TEXT_NODE:
    result = PyObject_GetAttrString(node, "data");
    break;
  default:
    result = PyUnicode_FromUnicode(NULL, 0);
  }

  Py_DECREF(nodeType);
  return result;
}
Exemple #7
0
extern "C" __declspec(dllexport) long __cdecl ExecuteFunction(const char *name, const char *args, wchar_t **value)
{
	PyObject *result = PyObject_CallMethod(iface, "exec_func", "ss", name, args);
	static wchar_t *text = NULL;
	if (text != NULL)
	{
		PyMem_Free(text);
		text = NULL;
	}

	if (result != NULL) 
	{
		text = PyUnicode_AsWideCharString(result, NULL);
		*value = (wchar_t *) text;
		Py_DECREF(result);
		return 0;
	}
	else
	{
	

	PyObject* excType, *excValue, *excTraceback;
    PyErr_Fetch(&excType, &excValue, &excTraceback);
    PyErr_NormalizeException(&excType, &excValue, &excTraceback);

	PyObject *mod = PyImport_ImportModule("traceback");
	PyObject *list = PyObject_CallMethod(mod, "format_exception", "OOO", excType, excValue, excTraceback);
	PyObject *separator = PyUnicode_FromString("\n");
	PyObject *exc_info = PyUnicode_Join(separator, list);

	text = PyUnicode_AsWideCharString(exc_info, NULL);
	*value = (wchar_t *) text;

		PyErr_Print();
		return -1;
	}

}
Exemple #8
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;
}
static PyObject *next(PyObject *self)
{
	ligolw_RowDumper *rowdumper = (ligolw_RowDumper *) self;
	const Py_ssize_t n = PyTuple_GET_SIZE(rowdumper->attributes);
	PyObject *tokens;
	PyObject *row;
	PyObject *result;
	Py_ssize_t i;

	/*
	 * retrieve the next row object
	 */

	if(!PyIter_Check(rowdumper->iter)) {
		PyErr_SetObject(PyExc_TypeError, rowdumper->iter);
		return NULL;
	}
	row = PyIter_Next(rowdumper->iter);
	if(!row) {
		if(!PyErr_Occurred()) {
			Py_DECREF(rowdumper->iter);
			rowdumper->iter = Py_None;
			Py_INCREF(rowdumper->iter);
			PyErr_SetNone(PyExc_StopIteration);
		}
		return NULL;
	}

	/*
	 * wipe out the tuple of tokens from the previous row, and start a
	 * new tuple
	 */

	Py_DECREF(rowdumper->tokens);
	rowdumper->tokens = Py_None;
	Py_INCREF(rowdumper->tokens);

	tokens = PyTuple_New(n);
	if(!tokens) {
		Py_DECREF(row);
		return NULL;
	}

	/*
	 * retrieve attributes from the row object one-by-one, convert to
	 * strings, and insert into new token tuple
	 */

	for(i = 0; i < n; i++) {
		PyObject *val = PyObject_GetAttr(row, PyTuple_GET_ITEM(rowdumper->attributes, i));
		PyObject *token;

		if(!val) {
			Py_DECREF(tokens);
			Py_DECREF(row);
			return NULL;
		}

		if(val == Py_None)
			token = PyUnicode_FromUnicode(NULL, 0); /* u"" */
		else
			token = PyObject_CallFunctionObjArgs(PyTuple_GET_ITEM(rowdumper->formats, i), val, NULL);
		Py_DECREF(val);

		if(!token) {
			Py_DECREF(tokens);
			Py_DECREF(row);
			return NULL;
		}

		PyTuple_SET_ITEM(tokens, i, token);
	}
	Py_DECREF(row);

	/*
	 * that worked, so expose the new token tuple
	 */

	Py_DECREF(rowdumper->tokens);
	rowdumper->tokens = tokens;

	/*
	 * return tokens concatenated into a single string using the
	 * delimiter
	 */

	result = PyUnicode_Join(rowdumper->delimiter, rowdumper->tokens);

	rowdumper->rows_converted += result != NULL;

	return result;
}
Exemple #10
0
// Returns a new string
MCHAR * pythonExceptionTraceback( bool clearException )
{
    /*
    	import traceback
    	return '\n'.join(traceback.format_exc()).encode('ascii','replace')
    */
    MCHAR * ret = 0;
    bool success = false;

    PyObject * type, * value, * traceback;
    /* Save the current exception */
    PyErr_Fetch(&type, &value, &traceback);
    if( type ) {

        PyObject * traceback_module = PyImport_ImportModule("traceback");
        if (traceback_module) {

            /* Call the traceback module's format_exception function, which returns a list */
            PyObject * traceback_list = PyObject_CallMethod(traceback_module, "format_exception", "OOO", type, value ? value : Py_None, traceback ? traceback : Py_None);
            if( traceback_list ) {

                PyObject * separator = PyString_FromString("");
                if( separator ) {

                    PyObject * retUni = PyUnicode_Join(separator, traceback_list);
                    if( retUni ) {
#ifdef UNICODE
                        ret = _tcsdup( PyUnicode_AsUnicode(retUni) );
#else
                        PyObject * retAscii = PyUnicode_AsEncodedString(retUni, "ascii", "replace");
                        if( retAscii ) {
                            Py_ssize_t len = 0;
                            char * tmp;
                            if( PyString_AsStringAndSize( retAscii, &tmp, &len ) != -1 ) {
                                ret = strdup( tmp );//, len );
                                success = true;
                            } else {
                                ret = _tcsdup( _T("Uhoh, failed to get pointer to ascii representation of the exception") );
                                success = false;
                            }
                            Py_DECREF( retAscii );
                        } else {
                            ret = _tcsdup( _T("Uhoh, encoding exception to ascii failed") );
                            success = false;
                        }
#endif
                        Py_DECREF(retUni);

                    } else
                        ret = _tcsdup(_T("PyUnicode_Join failed"));

                    Py_DECREF(separator);
                } else
                    ret = _tcsdup(_T("PyUnicode_FromString failed"));

                Py_DECREF(traceback_list);
            } else
                ret = _tcsdup(_T("Failure calling traceback.format_exception"));

            Py_DECREF(traceback_module);
        } else
            ret = _tcsdup(_T("Unable to load the traceback module, can't get exception text"));
    } else
        ret = _tcsdup(_T("pythonExceptionTraceback called, but no exception set"));

    if( clearException ) {
        Py_DECREF(type);
        Py_XDECREF(value);
        Py_XDECREF(traceback);
    } else
        PyErr_Restore(type,value,traceback);

    return ret;
}
Exemple #11
0
PyObject *string_join(PyStringObject *self, PyObject *orig)
{
    char *sep = PyString_AS_STRING(self);
    const Py_ssize_t seplen = PyString_GET_SIZE(self);
    PyObject *res = NULL;
    char *p;
    Py_ssize_t seqlen = 0;
    size_t sz = 0;
    Py_ssize_t i;
    PyObject *seq, *item;

    seq = PySequence_Fast(orig, "");
    if (seq == NULL) {
        return NULL;
    }

    seqlen = PySequence_Size(seq);
    if (seqlen == 0) {
        Py_DECREF(seq);
        return PyString_FromString("");
    }
    if (seqlen == 1) {
        item = PySequence_Fast_GET_ITEM(seq, 0);
        if (PyString_CheckExact(item) || PyUnicode_CheckExact(item)) {
            Py_INCREF(item);
            Py_DECREF(seq);
            return item;
        }
    }

    /* There are at least two things to join, or else we have a subclass
     * of the builtin types in the sequence.
     * Do a pre-pass to figure out the total amount of space we'll
     * need (sz), see whether any argument is absurd, and defer to
     * the Unicode join if appropriate.
     */
    for (i = 0; i < seqlen; i++) {
        const size_t old_sz = sz;
        item = PySequence_Fast_GET_ITEM(seq, i);
        if (!PyString_Check(item)){
#ifdef Py_USING_UNICODE
            if (PyUnicode_Check(item)) {
                /* Defer to Unicode join.
                 * CAUTION:  There's no gurantee that the
                 * original sequence can be iterated over
                 * again, so we must pass seq here.
                 */
                PyObject *result;
                result = PyUnicode_Join((PyObject *)self, seq);
                Py_DECREF(seq);
                return result;
            }
#endif
            PyErr_Format(PyExc_TypeError,
                         "sequence item %zd: expected string,"
                         " %.80s found",
                         i, Py_TYPE(item)->tp_name);
            Py_DECREF(seq);
            return NULL;
        }
        sz += PyString_GET_SIZE(item);
        if (i != 0)
            sz += seplen;
        if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
            PyErr_SetString(PyExc_OverflowError,
                "join() result is too long for a Python string");
            Py_DECREF(seq);
            return NULL;
        }
    }

    /* Allocate result space. */
    res = PyString_FromStringAndSize((char*)NULL, sz);
    if (res == NULL) {
        Py_DECREF(seq);
        return NULL;
    }

    /* Catenate everything. */
    p = PyString_AS_STRING(res);
    for (i = 0; i < seqlen; ++i) {
        size_t n;
        item = PySequence_Fast_GET_ITEM(seq, i);
        n = PyString_GET_SIZE(item);
        Py_MEMCPY(p, PyString_AS_STRING(item), n);
        p += n;
        if (i < seqlen - 1) {
            Py_MEMCPY(p, sep, seplen);
            p += seplen;
        }
    }

    Py_DECREF(seq);
    return res;
}
Exemple #12
0
QString
QPythonPriv::formatExc()
{
    PyObject *type = NULL;
    PyObject *value = NULL;
    PyObject *traceback = NULL;

    PyObject *list = NULL;
    PyObject *n = NULL;
    PyObject *s = NULL;

    PyErr_Fetch(&type, &value, &traceback);
    PyErr_NormalizeException(&type, &value, &traceback);

    QString message;
    QVariant v;

    if (type == NULL && value == NULL && traceback == NULL) {
        // No exception thrown?
        goto cleanup;
    }

    if (value != NULL) {
        // We can at least format the exception as string
        message = convertPyObjectToQVariant(PyObject_Str(value)).toString();
    }

    if (type == NULL || traceback == NULL) {
        // Cannot get a traceback for this exception
        goto cleanup;
    }

    list = PyObject_CallMethod(traceback_mod,
            "format_exception", "OOO", type, value, traceback);

    if (list == NULL) {
        // Could not format exception, fall back to original message
        PyErr_Print();
        goto cleanup;
    }

    n = PyUnicode_FromString("\n");
    if (n == NULL) {
        PyErr_Print();
        goto cleanup;
    }

    s = PyUnicode_Join(n, list);
    if (s == NULL) {
        PyErr_Print();
        goto cleanup;
    }

    v = convertPyObjectToQVariant(s);
    if (v.isValid()) {
        message = v.toString();
    }

cleanup:
    Py_XDECREF(s);
    Py_XDECREF(n);
    Py_XDECREF(list);

    Py_XDECREF(type);
    Py_XDECREF(value);
    Py_XDECREF(traceback);

    qDebug() << QString("PyOtherSide error: %1").arg(message);
    return message;
}
Exemple #13
0
static PyObject *
path_str(PycairoPath *p) {
  PyObject *s, *pieces = NULL, *result = NULL;
  cairo_path_t *path = p->path;
  cairo_path_data_t *data;
  int i, ret;
  char buf[80];

  pieces = PyList_New(0);
  if (pieces == NULL)
    goto Done;

  /* loop reading elements */
  for (i=0; i < path->num_data; i += path->data[i].header.length) {
    data = &path->data[i];
    switch (data->header.type) {

    case CAIRO_PATH_MOVE_TO:
      PyOS_snprintf(buf, sizeof(buf), "move_to %f %f",
		    data[1].point.x, data[1].point.y);
      s = PyUnicode_FromString(buf);
      if (!s)
	goto Done;
      ret = PyList_Append(pieces, s);
      Py_DECREF(s);
      if (ret < 0)
	goto Done;
      break;

    case CAIRO_PATH_LINE_TO:
      PyOS_snprintf(buf, sizeof(buf), "line_to %f %f",
		    data[1].point.x, data[1].point.y);
      s = PyUnicode_FromString(buf);
      if (!s)
	goto Done;
      ret = PyList_Append(pieces, s);
      Py_DECREF(s);
      if (ret < 0)
	goto Done;
      break;

    case CAIRO_PATH_CURVE_TO:
      PyOS_snprintf(buf, sizeof(buf), "curve_to %f %f %f %f %f %f",
		    data[1].point.x, data[1].point.y,
		    data[2].point.x, data[2].point.y,
		    data[3].point.x, data[3].point.y);
      s = PyUnicode_FromString(buf);
      if (!s)
	goto Done;
      ret = PyList_Append(pieces, s);
      Py_DECREF(s);
      if (ret < 0)
	goto Done;
      break;

    case CAIRO_PATH_CLOSE_PATH:
      s = PyUnicode_FromString("close path");
      if (!s)
	goto Done;
      ret = PyList_Append(pieces, s);
      Py_DECREF(s);
      if (ret < 0)
	goto Done;
      break;
    }
  }
  /* result = "\n".join(pieces) */
  s = PyUnicode_FromString("\n");
  if (s == NULL)
    goto Done;
  result = PyUnicode_Join(s, pieces);
  Py_DECREF(s);

Done:
  Py_XDECREF(pieces);
  return result;
}
Exemple #14
0
static PyObject *pair_str(PyObject *self) {
  PyObject *tmp = NULL;
  PyObject *col = PyList_New(0);
  PyObject *found = PyDict_New();
  size_t index = 0;

  PyObject *rest = self;
  PyObject *rest_id;

  PyList_Append(col, _str_open_paren);

  for (rest = self; SibPair_CheckExact(rest); rest = SibPair_CDR(rest)) {
    rest_id = PyLong_FromVoidPtr(rest);

    if (PyDict_Contains(found, rest_id)) {
      /* recursive pair detected */
      PyList_Append(col, _str_elipsis);
      PyList_Append(col, _str_close_paren);

      if (rest != self) {
	tmp = PyDict_GetItem(found, rest_id);
	PyList_Insert(col, PyLong_AsSize_t(tmp) - 1, _str_open_paren);
	PyList_Insert(col, PyLong_AsSize_t(tmp) - 1, _str_dot_space);
	PyList_Append(col, _str_close_paren);
      }
      Py_DECREF(rest_id);

      /* set rest to NULL so we don't try to close it like we would a
	 normal proper or improper list */
      rest = NULL;
      break;

    } else {
      index += 2;

      tmp = PyLong_FromSize_t(index);
      PyDict_SetItem(found, rest_id, tmp);
      Py_DECREF(tmp);
      Py_DECREF(rest_id);

      tmp = SibPair_CAR(rest);
      if (PyUnicode_CheckExact(tmp)) {
	tmp = sib_quoted(tmp);
      } else {
	tmp = PyObject_Str(tmp);
      }

      PyList_Append(col, tmp);
      Py_DECREF(tmp);

      PyList_Append(col, _str_space);
    }
  }

  if(SibNil_Check(rest)) {
    /* end of a proper list */

    Py_INCREF(_str_close_paren);
    PyList_SetItem(col, index, _str_close_paren);

  } else if (rest) {
    /* end of an improper list */

    tmp = rest;
    if (PyUnicode_CheckExact(tmp)) {
      tmp = sib_quoted(tmp);
    } else {
      tmp = PyObject_Str(tmp);
    }
    PyList_Append(col, _str_dot_space);
    PyList_Append(col, tmp);
    PyList_Append(col, _str_close_paren);
    Py_DECREF(tmp);
  }

  tmp = PyUnicode_Join(_str_empty, col);
  Py_DECREF(col);
  Py_DECREF(found);

  return tmp;
}