コード例 #1
0
static PyObject *
longrangeiter_next(longrangeiterobject *r)
{
    PyObject *one, *product, *new_index, *result;
    if (PyObject_RichCompareBool(r->index, r->len, Py_LT) != 1)
        return NULL;

    one = PyLong_FromLong(1);
    if (!one)
        return NULL;

    new_index = PyNumber_Add(r->index, one);
    Py_DECREF(one);
    if (!new_index)
        return NULL;

    product = PyNumber_Multiply(r->index, r->step);
    if (!product) {
        Py_DECREF(new_index);
        return NULL;
    }

    result = PyNumber_Add(r->start, product);
    Py_DECREF(product);
    if (result) {
        Py_XSETREF(r->index, new_index);
    }
    else {
        Py_DECREF(new_index);
    }

    return result;
}
コード例 #2
0
ファイル: pywrapper.cpp プロジェクト: cbehan/symengine.py
//! Addition
RCP<const Number> PyNumber::add(const Number &other) const {
    PyObject *other_p, *result;
    if (is_a<PyNumber>(other)) {
        other_p = static_cast<const PyNumber &>(other).pyobject_;
        result = PyNumber_Add(pyobject_, other_p);
    } else {
        other_p = pymodule_->to_py_(other.rcp_from_this_cast<const Basic>());
        result = PyNumber_Add(pyobject_, other_p);
        Py_XDECREF(other_p);
    }
    return make_rcp<PyNumber>(result, pymodule_);
}
コード例 #3
0
static PyObject *Proxy_add(PyObject *o1, PyObject *o2)
{
    Proxy__WRAPPED_REPLACE_OR_RETURN_NULL(o1);
    Proxy__WRAPPED_REPLACE_OR_RETURN_NULL(o2);

    return PyNumber_Add(o1, o2);
}
コード例 #4
0
static PyObject *
range_item(rangeobject *r, Py_ssize_t i)
{
    Py_ssize_t len = range_length(r);
    PyObject *rem, *incr, *result;

    /* XXX(nnorwitz): should negative indices be supported? */
    /* XXX(nnorwitz): should support range[x] where x > PY_SSIZE_T_MAX? */
    if (i < 0 || i >= len) {
        if (!PyErr_Occurred())
            PyErr_SetString(PyExc_IndexError,
                            "range object index out of range");
        return NULL;
    }

    /* XXX(nnorwitz): optimize for short ints. */
    rem = PyLong_FromSsize_t(i);
    if (!rem)
        return NULL;
    incr = PyNumber_Multiply(rem, r->step);
    Py_DECREF(rem);
    if (!incr)
        return NULL;
    result = PyNumber_Add(r->start, incr);
    Py_DECREF(incr);
    return result;
}
コード例 #5
0
static PyObject *
longrangeiter_reduce(longrangeiterobject *r)
{
    PyObject *product, *stop=NULL;
    PyObject *range;

    /* create a range object for pickling.  Must calculate the "stop" value */
    product = PyNumber_Multiply(r->len, r->step);
    if (product == NULL)
        return NULL;
    stop = PyNumber_Add(r->start, product);
    Py_DECREF(product);
    if (stop ==  NULL)
        return NULL;
    Py_INCREF(r->start);
    Py_INCREF(r->step);
    range =  (PyObject*)make_range_object(&PyRange_Type,
                               r->start, stop, r->step);
    if (range == NULL) {
        Py_DECREF(r->start);
        Py_DECREF(stop);
        Py_DECREF(r->step);
        return NULL;
    }

    /* return the result */
    return Py_BuildValue("N(N)O", _PyObject_GetBuiltin("iter"), range, r->index);
}
コード例 #6
0
inline CObject operator+ (const CObject& a, const CObject& b)
{
    PyObject* tmp_obj = PyNumber_Add(a.Get(), b.Get());
    if ( !tmp_obj ) {
        throw CArithmeticError("PyNumber_Add");
    }
    return CObject(tmp_obj, eTakeOwnership);
}
コード例 #7
0
static PyObject *
compute_range_item(rangeobject *r, PyObject *arg)
{
    int cmp_result;
    PyObject *i, *result;

    PyObject *zero = PyLong_FromLong(0);
    if (zero == NULL)
        return NULL;

    /* PyLong equivalent to:
     *   if (arg < 0) {
     *     i = r->length + arg
     *   } else {
     *     i = arg
     *   }
     */
    cmp_result = PyObject_RichCompareBool(arg, zero, Py_LT);
    if (cmp_result == -1) {
        Py_DECREF(zero);
        return NULL;
    }
    if (cmp_result == 1) {
      i = PyNumber_Add(r->length, arg);
      if (!i) {
        Py_DECREF(zero);
        return NULL;
      }
    } else {
      i = arg;
      Py_INCREF(i);
    }

    /* PyLong equivalent to:
     *   if (i < 0 || i >= r->length) {
     *     <report index out of bounds>
     *   }
     */
    cmp_result = PyObject_RichCompareBool(i, zero, Py_LT);
    Py_DECREF(zero);
    if (cmp_result == 0) {
        cmp_result = PyObject_RichCompareBool(i, r->length, Py_GE);
    }
    if (cmp_result == -1) {
       Py_DECREF(i);
       return NULL;
    }
    if (cmp_result == 1) {
        Py_DECREF(i);
        PyErr_SetString(PyExc_IndexError,
                        "range object index out of range");
        return NULL;
    }

    result = compute_item(r, i);
    Py_DECREF(i);
    return result;
}
コード例 #8
0
ファイル: nwchem_wrap.c プロジェクト: bwang2453/nwchem_csx
static PyObject*
second_func(PyObject *self, PyObject *args)
{
	PyObject *a, *b;
	
	if (!PyArg_UnpackTuple(args, "func", 2, 2, &a, &b)) {
		return NULL;
	}

	return PyNumber_Add(a, b);
}
コード例 #9
0
static PyObject *
compute_item(rangeobject *r, PyObject *i)
{
    PyObject *incr, *result;
    /* PyLong equivalent to:
     *    return r->start + (i * r->step)
     */
    incr = PyNumber_Multiply(i, r->step);
    if (!incr)
        return NULL;
    result = PyNumber_Add(r->start, incr);
    Py_DECREF(incr);
    return result;
}
コード例 #10
0
ファイル: entity.c プロジェクト: abed-hawa/amara
entity_init(EntityObject *self, PyObject *documentURI)
{
  PyObject *creationIndex, *unparsed_entities;

  if (documentURI == NULL || !XmlString_NullCheck(documentURI)) {
    PyErr_BadInternalCall();
    Py_DECREF(self);
    return NULL;
  }

  creationIndex = PyNumber_Add(creation_counter, counter_inc);
  if (creationIndex == NULL) {
    Py_DECREF(self);
    return NULL;
  }

  unparsed_entities = PyDict_New();
  if (unparsed_entities == NULL) {
    Py_DECREF(creationIndex);
    Py_DECREF(self);
    return NULL;
  }

  if (documentURI == Py_None) {
    documentURI = PyUnicode_FromUnicode(NULL, 0);
    if (documentURI == NULL) {
      Py_DECREF(creationIndex);
      Py_DECREF(unparsed_entities);
      Py_DECREF(self);
      return NULL;
    }
  } else {
    Py_INCREF(documentURI);
  }

  self->creationIndex = creationIndex;
  self->unparsed_entities = unparsed_entities;
  Entity_SET_DOCUMENT_URI(self, documentURI);
  Entity_SET_PUBLIC_ID(self, Py_None);
  Py_INCREF(Py_None);
  Entity_SET_SYSTEM_ID(self, Py_None);
  Py_INCREF(Py_None);

  /* update creation counter */
  Py_INCREF(creationIndex);
  Py_DECREF(creation_counter);
  creation_counter = creationIndex;

  return self;
}
コード例 #11
0
ファイル: fibo.c プロジェクト: makkalot/pyalgorithm
static PyObject*
fibo_iter(PyObject* self,PyObject *args){

    // the numbers to be added
    PyObject *first_num;
    PyObject *second_num;
    PyObject *tmp_res;

    long int fibo_number,i;

    if (!PyArg_ParseTuple(args, "l", &fibo_number))
             return NULL;

    //printf("\nThe value to compute is %ld",fibo_number);

    if(fibo_number == 0 || fibo_number == 1)
        return Py_BuildValue("l",fibo_number);

    //Dont forget to decref ...
    first_num = Py_BuildValue("l",0);
    second_num = Py_BuildValue("l",1);

    //PyObject_Print(first_num, stdout, 0);
    //printf("\n\n");
    //PyObject_Print(second_num, stdout, 0);
    //printf("\n\n");

    //computes the fibo iteratively
    for (i=1;i<fibo_number;i++){
        //we have a new reference
        tmp_res = PyNumber_Add(first_num,second_num);
        
        Py_INCREF(second_num);
        Py_XDECREF(first_num);
        first_num = second_num;
        

        Py_INCREF(tmp_res);
        Py_XDECREF(second_num);
        second_num = tmp_res;

        //give back the reference
        Py_XDECREF(tmp_res);
    }
    Py_XDECREF(first_num);
    return second_num;
}
コード例 #12
0
ファイル: rowe_1.c プロジェクト: jwilk/Pyrex
/* Implementation of rowe_1 */

static PyObject *__pyx_f_6rowe_1_function(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
static PyObject *__pyx_f_6rowe_1_function(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
  PyObject *__pyx_v_data = 0;
  PyObject *__pyx_v_a;
  PyObject *__pyx_r;
  PyObject *__pyx_1 = 0;
  PyObject *__pyx_2 = 0;
  int __pyx_3;
  Py_ssize_t __pyx_4;
  Py_ssize_t __pyx_5;
  static char *__pyx_argnames[] = {"data",0};
  if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "O", __pyx_argnames, &__pyx_v_data)) return 0;
  Py_INCREF(__pyx_v_data);
  __pyx_v_a = Py_None; Py_INCREF(Py_None);

  /* "/Local/Projects/D/Pyrex/Source/Tests/Bugs/other/rowe_1.pyx":7 */
  __pyx_1 = PyInt_FromLong(4); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 7; goto __pyx_L1;}
  __pyx_2 = PyNumber_Multiply(__pyx_1, __pyx_v_a); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 7; goto __pyx_L1;}
  Py_DECREF(__pyx_1); __pyx_1 = 0;
  __pyx_3 = PyInt_AsLong(__pyx_2); if (PyErr_Occurred()) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 7; goto __pyx_L1;}
  Py_DECREF(__pyx_2); __pyx_2 = 0;
  blarg(__pyx_3);

  /* "/Local/Projects/D/Pyrex/Source/Tests/Bugs/other/rowe_1.pyx":8 */
  __pyx_4 = PyInt_AsSsize_t(__pyx_v_a); if (PyErr_Occurred()) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 8; goto __pyx_L1;}
  __pyx_1 = __Pyx_GetName(__pyx_b, __pyx_n_b); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 8; goto __pyx_L1;}
  __pyx_2 = PyNumber_Add(__pyx_v_a, __pyx_1); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 8; goto __pyx_L1;}
  Py_DECREF(__pyx_1); __pyx_1 = 0;
  __pyx_5 = PyInt_AsSsize_t(__pyx_2); if (PyErr_Occurred()) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 8; goto __pyx_L1;}
  Py_DECREF(__pyx_2); __pyx_2 = 0;
  __pyx_1 = PySequence_GetSlice(__pyx_v_data, __pyx_4, __pyx_5); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 8; goto __pyx_L1;}
  __pyx_r = __pyx_1;
  __pyx_1 = 0;
  goto __pyx_L0;

  __pyx_r = Py_None; Py_INCREF(Py_None);
  goto __pyx_L0;
  __pyx_L1:;
  Py_XDECREF(__pyx_1);
  Py_XDECREF(__pyx_2);
  __Pyx_AddTraceback("rowe_1.function");
  __pyx_r = 0;
  __pyx_L0:;
  Py_DECREF(__pyx_v_a);
  Py_DECREF(__pyx_v_data);
  return __pyx_r;
}
コード例 #13
0
ファイル: concatcstrings.c プロジェクト: jwilk/Pyrex
/* Implementation of concatcstrings */

static struct PyMethodDef __pyx_methods[] = {
  {0, 0, 0, 0}
};

static void __pyx_init_filenames(void); /*proto*/

PyMODINIT_FUNC initconcatcstrings(void); /*proto*/
PyMODINIT_FUNC initconcatcstrings(void) {
  PyObject *__pyx_1 = 0;
  __pyx_init_filenames();
  __pyx_m = Py_InitModule4("concatcstrings", __pyx_methods, 0, 0, PYTHON_API_VERSION);
  if (!__pyx_m) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; goto __pyx_L1;};
  Py_INCREF(__pyx_m);
  __pyx_b = PyImport_AddModule("__builtin__");
  if (!__pyx_b) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; goto __pyx_L1;};
  if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; goto __pyx_L1;};
  if (__Pyx_InitStrings(__pyx_string_tab) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; goto __pyx_L1;};
  __pyx_1 = PyNumber_Add(__pyx_k1p, __pyx_k2p); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; goto __pyx_L1;}
  if (PyObject_SetAttr(__pyx_m, __pyx_n_spam, __pyx_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; goto __pyx_L1;}
  Py_DECREF(__pyx_1); __pyx_1 = 0;
  return;
  __pyx_L1:;
  Py_XDECREF(__pyx_1);
  __Pyx_AddTraceback("concatcstrings");
}
コード例 #14
0
ファイル: scxx_demo.cpp プロジェクト: HunterAllman/kod
void test_PythonAPI()
{
  double a_ = 3.4;
  PyObject* a = PyFloat_FromDouble(a_);
  PyObject* b = PyFloat_FromDouble(7);
  PyObject* c = PyNumber_Add(a, b); 
  PyObject* list = PyList_New(0);
  PyList_Append(list, a);
  PyList_Append(list, c);
  PyList_Append(list, b);
  PyObject* tp = PyList_AsTuple(list);
  int tp_len = PySequence_Length(tp);
  for (int i=0; i<tp_len; i++) {
    PyObject* qp = PySequence_GetItem(tp, i);
    double q = PyFloat_AS_DOUBLE(qp);
    std::cout << "tp[" << i << "]=" << q << " ";
  }
  std::cout << std::endl;
}
コード例 #15
0
ファイル: enumobject.c プロジェクト: Vignesh2736/IncPy
static PyObject *
enum_next_long(enumobject *en, PyObject* next_item)
{
	static PyObject *one = NULL;
	PyObject *result = en->en_result;
	PyObject *next_index;
	PyObject *stepped_up;

	if (en->en_longindex == NULL) {
		en->en_longindex = PyInt_FromSsize_t(PY_SSIZE_T_MAX);
		if (en->en_longindex == NULL)
			return NULL;
	}
	if (one == NULL) {
		one = PyInt_FromLong(1);
		if (one == NULL)
			return NULL;
	}
	next_index = en->en_longindex;
	assert(next_index != NULL);
	stepped_up = PyNumber_Add(next_index, one);
	if (stepped_up == NULL)
		return NULL;
	en->en_longindex = stepped_up;

	if (result->ob_refcnt == 1) {
		Py_INCREF(result);
		Py_DECREF(PyTuple_GET_ITEM(result, 0));
		Py_DECREF(PyTuple_GET_ITEM(result, 1));
	} else {
		result = PyTuple_New(2);
		if (result == NULL) {
			Py_DECREF(next_index);
			Py_DECREF(next_item);
			return NULL;
		}
	}
	PyTuple_SET_ITEM(result, 0, next_index);
	PyTuple_SET_ITEM(result, 1, next_item);
	return result;
}
コード例 #16
0
ファイル: gtop.c プロジェクト: ZevenOS/wnck-patches
static PyObject* build_128bit_long(guint64 values[2])
{
	PyObject *res, *x, *y;

	res = PyL_ULL(values[0]);	/* res = values[0]	*/

	x = PyI_L(64);			/* x = 64		*/

	y = PyNumber_Lshift(res, x);	/* y = res << x		*/

	Py_DECREF(x);
	Py_DECREF(res);			/* res = y		*/
	res = y;

	x = PyL_ULL(values[1]);		/* x = values[1]	*/

	y = PyNumber_Add(res, x);	/* y = res + x		*/

	Py_DECREF(x);			/* res = y		*/
	Py_DECREF(res);
	res = y;

	return res;
}
コード例 #17
0
ファイル: peephole.c プロジェクト: 1564143452/kbengine
/* Replace LOAD_CONST c1. LOAD_CONST c2 BINOP
   with    LOAD_CONST binop(c1,c2)
   The consts table must still be in list form so that the
   new constant can be appended.
   Called with codestr pointing to the BINOP.
   Abandons the transformation if the folding fails (i.e.  1+'a').
   If the new constant is a sequence, only folds when the size
   is below a threshold value.  That keeps pyc files from
   becoming large in the presence of code like:  (None,)*1000.
*/
static int
fold_binops_on_constants(unsigned char *codestr, PyObject *consts, PyObject **objs)
{
    PyObject *newconst, *v, *w;
    Py_ssize_t len_consts, size;
    int opcode;

    /* Pre-conditions */
    assert(PyList_CheckExact(consts));

    /* Create new constant */
    v = objs[0];
    w = objs[1];
    opcode = codestr[0];
    switch (opcode) {
        case BINARY_POWER:
            newconst = PyNumber_Power(v, w, Py_None);
            break;
        case BINARY_MULTIPLY:
            newconst = PyNumber_Multiply(v, w);
            break;
        case BINARY_TRUE_DIVIDE:
            newconst = PyNumber_TrueDivide(v, w);
            break;
        case BINARY_FLOOR_DIVIDE:
            newconst = PyNumber_FloorDivide(v, w);
            break;
        case BINARY_MODULO:
            newconst = PyNumber_Remainder(v, w);
            break;
        case BINARY_ADD:
            newconst = PyNumber_Add(v, w);
            break;
        case BINARY_SUBTRACT:
            newconst = PyNumber_Subtract(v, w);
            break;
        case BINARY_SUBSCR:
            newconst = PyObject_GetItem(v, w);
            break;
        case BINARY_LSHIFT:
            newconst = PyNumber_Lshift(v, w);
            break;
        case BINARY_RSHIFT:
            newconst = PyNumber_Rshift(v, w);
            break;
        case BINARY_AND:
            newconst = PyNumber_And(v, w);
            break;
        case BINARY_XOR:
            newconst = PyNumber_Xor(v, w);
            break;
        case BINARY_OR:
            newconst = PyNumber_Or(v, w);
            break;
        default:
            /* Called with an unknown opcode */
            PyErr_Format(PyExc_SystemError,
                 "unexpected binary operation %d on a constant",
                     opcode);
            return 0;
    }
    if (newconst == NULL) {
        if(!PyErr_ExceptionMatches(PyExc_KeyboardInterrupt))
            PyErr_Clear();
        return 0;
    }
    size = PyObject_Size(newconst);
    if (size == -1) {
        if (PyErr_ExceptionMatches(PyExc_KeyboardInterrupt))
            return 0;
        PyErr_Clear();
    } else if (size > 20) {
        Py_DECREF(newconst);
        return 0;
    }

    /* Append folded constant into consts table */
    len_consts = PyList_GET_SIZE(consts);
    if (PyList_Append(consts, newconst)) {
        Py_DECREF(newconst);
        return 0;
    }
    Py_DECREF(newconst);

    /* Write NOP NOP NOP NOP LOAD_CONST newconst */
    codestr[-2] = LOAD_CONST;
    SETARG(codestr, -2, len_consts);
    return 1;
}
コード例 #18
0
/* Replace LOAD_CONST c1. LOAD_CONST c2 BINOP
   with	   LOAD_CONST binop(c1,c2)
   The consts table must still be in list form so that the
   new constant can be appended.
   Called with codestr pointing to the first LOAD_CONST. 
   Abandons the transformation if the folding fails (i.e.  1+'a').  
   If the new constant is a sequence, only folds when the size
   is below a threshold value.	That keeps pyc files from
   becoming large in the presence of code like:	 (None,)*1000.
*/
static int
fold_binops_on_constants(unsigned char *codestr, PyObject *consts)
{
	PyObject *newconst, *v, *w;
	Py_ssize_t len_consts, size;
	int opcode;

	/* Pre-conditions */
	assert(PyList_CheckExact(consts));
	assert(codestr[0] == LOAD_CONST);
	assert(codestr[3] == LOAD_CONST);

	/* Create new constant */
	v = PyList_GET_ITEM(consts, GETARG(codestr, 0));
	w = PyList_GET_ITEM(consts, GETARG(codestr, 3));
	opcode = codestr[6];
	switch (opcode) {
		case BINARY_POWER:
			newconst = PyNumber_Power(v, w, Py_None);
			break;
		case BINARY_MULTIPLY:
			newconst = PyNumber_Multiply(v, w);
			break;
		case BINARY_DIVIDE:
			/* Cannot fold this operation statically since
                           the result can depend on the run-time presence
                           of the -Qnew flag */
			return 0;
		case BINARY_TRUE_DIVIDE:
			newconst = PyNumber_TrueDivide(v, w);
			break;
		case BINARY_FLOOR_DIVIDE:
			newconst = PyNumber_FloorDivide(v, w);
			break;
		case BINARY_MODULO:
			newconst = PyNumber_Remainder(v, w);
			break;
		case BINARY_ADD:
			newconst = PyNumber_Add(v, w);
			break;
		case BINARY_SUBTRACT:
			newconst = PyNumber_Subtract(v, w);
			break;
		case BINARY_SUBSCR:
			newconst = PyObject_GetItem(v, w);
			break;
		case BINARY_LSHIFT:
			newconst = PyNumber_Lshift(v, w);
			break;
		case BINARY_RSHIFT:
			newconst = PyNumber_Rshift(v, w);
			break;
		case BINARY_AND:
			newconst = PyNumber_And(v, w);
			break;
		case BINARY_XOR:
			newconst = PyNumber_Xor(v, w);
			break;
		case BINARY_OR:
			newconst = PyNumber_Or(v, w);
			break;
		default:
			/* Called with an unknown opcode */
			PyErr_Format(PyExc_SystemError,
			     "unexpected binary operation %d on a constant",
				     opcode);
			return 0;
	}
	if (newconst == NULL) {
		PyErr_Clear();
		return 0;
	}
	size = PyObject_Size(newconst);
	if (size == -1)
		PyErr_Clear();
	else if (size > 20) {
		Py_DECREF(newconst);
		return 0;
	}

	/* Append folded constant into consts table */
	len_consts = PyList_GET_SIZE(consts);
	if (PyList_Append(consts, newconst)) {
		Py_DECREF(newconst);
		return 0;
	}
	Py_DECREF(newconst);

	/* Write NOP NOP NOP NOP LOAD_CONST newconst */
	memset(codestr, NOP, 4);
	codestr[4] = LOAD_CONST;
	SETARG(codestr, 4, len_consts);
	return 1;
}
コード例 #19
0
ファイル: sliceobject.c プロジェクト: adrian17/cpython
int
_PySlice_GetLongIndices(PySliceObject *self, PyObject *length,
                        PyObject **start_ptr, PyObject **stop_ptr,
                        PyObject **step_ptr)
{
    PyObject *start=NULL, *stop=NULL, *step=NULL;
    PyObject *upper=NULL, *lower=NULL;
    int step_is_negative, cmp_result;

    /* Convert step to an integer; raise for zero step. */
    if (self->step == Py_None) {
        step = _PyLong_One;
        Py_INCREF(step);
        step_is_negative = 0;
    }
    else {
        int step_sign;
        step = evaluate_slice_index(self->step);
        if (step == NULL)
            goto error;
        step_sign = _PyLong_Sign(step);
        if (step_sign == 0) {
            PyErr_SetString(PyExc_ValueError,
                            "slice step cannot be zero");
            goto error;
        }
        step_is_negative = step_sign < 0;
    }

    /* Find lower and upper bounds for start and stop. */
    if (step_is_negative) {
        lower = PyLong_FromLong(-1L);
        if (lower == NULL)
            goto error;

        upper = PyNumber_Add(length, lower);
        if (upper == NULL)
            goto error;
    }
    else {
        lower = _PyLong_Zero;
        Py_INCREF(lower);
        upper = length;
        Py_INCREF(upper);
    }

    /* Compute start. */
    if (self->start == Py_None) {
        start = step_is_negative ? upper : lower;
        Py_INCREF(start);
    }
    else {
        start = evaluate_slice_index(self->start);
        if (start == NULL)
            goto error;

        if (_PyLong_Sign(start) < 0) {
            /* start += length */
            PyObject *tmp = PyNumber_Add(start, length);
            Py_DECREF(start);
            start = tmp;
            if (start == NULL)
                goto error;

            cmp_result = PyObject_RichCompareBool(start, lower, Py_LT);
            if (cmp_result < 0)
                goto error;
            if (cmp_result) {
                Py_INCREF(lower);
                Py_DECREF(start);
                start = lower;
            }
        }
        else {
            cmp_result = PyObject_RichCompareBool(start, upper, Py_GT);
            if (cmp_result < 0)
                goto error;
            if (cmp_result) {
                Py_INCREF(upper);
                Py_DECREF(start);
                start = upper;
            }
        }
    }

    /* Compute stop. */
    if (self->stop == Py_None) {
        stop = step_is_negative ? lower : upper;
        Py_INCREF(stop);
    }
    else {
        stop = evaluate_slice_index(self->stop);
        if (stop == NULL)
            goto error;

        if (_PyLong_Sign(stop) < 0) {
            /* stop += length */
            PyObject *tmp = PyNumber_Add(stop, length);
            Py_DECREF(stop);
            stop = tmp;
            if (stop == NULL)
                goto error;

            cmp_result = PyObject_RichCompareBool(stop, lower, Py_LT);
            if (cmp_result < 0)
                goto error;
            if (cmp_result) {
                Py_INCREF(lower);
                Py_DECREF(stop);
                stop = lower;
            }
        }
        else {
            cmp_result = PyObject_RichCompareBool(stop, upper, Py_GT);
            if (cmp_result < 0)
                goto error;
            if (cmp_result) {
                Py_INCREF(upper);
                Py_DECREF(stop);
                stop = upper;
            }
        }
    }

    *start_ptr = start;
    *stop_ptr = stop;
    *step_ptr = step;
    Py_DECREF(upper);
    Py_DECREF(lower);
    return 0;

  error:
    *start_ptr = *stop_ptr = *step_ptr = NULL;
    Py_XDECREF(start);
    Py_XDECREF(stop);
    Py_XDECREF(step);
    Py_XDECREF(upper);
    Py_XDECREF(lower);
    return -1;
}
コード例 #20
0
/* Return number of items in range (lo, hi, step) as a PyLong object,
 * when arguments are PyLong objects.  Arguments MUST return 1 with
 * PyLong_Check().  Return NULL when there is an error.
 */
static PyObject*
compute_range_length(PyObject *start, PyObject *stop, PyObject *step)
{
    /* -------------------------------------------------------------
    Algorithm is equal to that of get_len_of_range(), but it operates
    on PyObjects (which are assumed to be PyLong objects).
    ---------------------------------------------------------------*/
    int cmp_result;
    PyObject *lo, *hi;
    PyObject *diff = NULL;
    PyObject *one = NULL;
    PyObject *tmp1 = NULL, *tmp2 = NULL, *result;
                /* holds sub-expression evaluations */

    PyObject *zero = PyLong_FromLong(0);
    if (zero == NULL)
        return NULL;
    cmp_result = PyObject_RichCompareBool(step, zero, Py_GT);
    Py_DECREF(zero);
    if (cmp_result == -1)
        return NULL;

    if (cmp_result == 1) {
        lo = start;
        hi = stop;
        Py_INCREF(step);
    } else {
        lo = stop;
        hi = start;
        step = PyNumber_Negative(step);
        if (!step)
            return NULL;
    }

    /* if (lo >= hi), return length of 0. */
    cmp_result = PyObject_RichCompareBool(lo, hi, Py_GE);
    if (cmp_result != 0) {
        Py_XDECREF(step);
        if (cmp_result < 0)
            return NULL;
        return PyLong_FromLong(0);
    }

    if ((one = PyLong_FromLong(1L)) == NULL)
        goto Fail;

    if ((tmp1 = PyNumber_Subtract(hi, lo)) == NULL)
        goto Fail;

    if ((diff = PyNumber_Subtract(tmp1, one)) == NULL)
        goto Fail;

    if ((tmp2 = PyNumber_FloorDivide(diff, step)) == NULL)
        goto Fail;

    if ((result = PyNumber_Add(tmp2, one)) == NULL)
        goto Fail;

    Py_DECREF(tmp2);
    Py_DECREF(diff);
    Py_DECREF(step);
    Py_DECREF(tmp1);
    Py_DECREF(one);
    return result;

  Fail:
    Py_XDECREF(tmp2);
    Py_XDECREF(diff);
    Py_XDECREF(step);
    Py_XDECREF(tmp1);
    Py_XDECREF(one);
    return NULL;
}
コード例 #21
0
static PyObject *
range_reverse(PyObject *seq)
{
    rangeobject *range = (rangeobject*) seq;
    longrangeiterobject *it;
    PyObject *one, *sum, *diff, *len = NULL, *product;
    long lstart, lstop, lstep;

    /* XXX(nnorwitz): do the calc for the new start/stop first,
        then if they fit, call the proper iter()?
    */
    assert(PyRange_Check(seq));

    /* If all three fields convert to long, use the int version */
    lstart = PyLong_AsLong(range->start);
    if (lstart != -1 || !PyErr_Occurred()) {
	lstop = PyLong_AsLong(range->stop);
	if (lstop != -1 || !PyErr_Occurred()) {
	    lstep = PyLong_AsLong(range->step);
	    if (lstep != -1 || !PyErr_Occurred()) {
		/* XXX(nnorwitz): need to check for overflow and simplify. */
		long len = get_len_of_range(lstart, lstop, lstep);
		long new_start = lstart + (len - 1) * lstep;
		long new_stop = lstart;
		if (lstep > 0)
		    new_stop -= 1;
		else
		    new_stop += 1;
		return int_range_iter(new_start, new_stop, -lstep);
	    }
	}
    }
    PyErr_Clear();

    it = PyObject_New(longrangeiterobject, &PyLongRangeIter_Type);
    if (it == NULL)
        return NULL;

    /* start + (len - 1) * step */
    len = range_length_obj(range);
    if (!len)
        goto create_failure;

    one = PyLong_FromLong(1);
    if (!one)
        goto create_failure;

    diff = PyNumber_Subtract(len, one);
    Py_DECREF(one);
    if (!diff)
        goto create_failure;

    product = PyNumber_Multiply(len, range->step);
    if (!product)
        goto create_failure;

    sum = PyNumber_Add(range->start, product);
    Py_DECREF(product);
    it->start = sum;
    if (!it->start)
        goto create_failure;
    it->step = PyNumber_Negative(range->step);
    if (!it->step) {
        Py_DECREF(it->start);
        PyObject_Del(it);
        return NULL;
    }

    /* Steal reference to len. */
    it->len = len;

    it->index = PyLong_FromLong(0);
    if (!it->index) {
        Py_DECREF(it);
        return NULL;
    }

    return (PyObject *)it;

create_failure:
    Py_XDECREF(len);
    PyObject_Del(it);
    return NULL;
}
コード例 #22
0
ファイル: Stemmer.c プロジェクト: buriy/pystemmer
static PyObject *__pyx_f_7Stemmer_7Stemmer_stemWord(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
  PyObject *__pyx_v_word = 0;
  char *__pyx_v_c_word;
  PyObject *__pyx_v_was_unicode;
  PyObject *__pyx_v_cacheditem;
  PyObject *__pyx_v_result;
  PyObject *__pyx_v_length;
  PyObject *__pyx_r;
  PyObject *__pyx_1 = 0;
  int __pyx_2;
  PyObject *__pyx_3 = 0;
  PyObject *__pyx_4 = 0;
  char *__pyx_5;
  Py_ssize_t __pyx_6;
  PyObject *__pyx_7 = 0;
  PyObject *__pyx_8 = 0;
  static char *__pyx_argnames[] = {"word",0};
  if (!PyArg_ParseTupleAndKeywords(__pyx_args, __pyx_kwds, "O", __pyx_argnames, &__pyx_v_word)) return 0;
  Py_INCREF(__pyx_v_self);
  Py_INCREF(__pyx_v_word);
  __pyx_v_was_unicode = Py_None; Py_INCREF(Py_None);
  __pyx_v_cacheditem = Py_None; Py_INCREF(Py_None);
  __pyx_v_result = Py_None; Py_INCREF(Py_None);
  __pyx_v_length = Py_None; Py_INCREF(Py_None);

  /* "/home/richard/private/Working/snowball/pystemmer/src/Stemmer.pyx":171 */
  __pyx_1 = PyInt_FromLong(0); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 171; goto __pyx_L1;}
  Py_DECREF(__pyx_v_was_unicode);
  __pyx_v_was_unicode = __pyx_1;
  __pyx_1 = 0;

  /* "/home/richard/private/Working/snowball/pystemmer/src/Stemmer.pyx":172 */
  __pyx_1 = __Pyx_GetName(__pyx_b, __pyx_n_unicode); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 172; goto __pyx_L1;}
  __pyx_2 = PyObject_IsInstance(__pyx_v_word,__pyx_1); if (__pyx_2 == -1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 172; goto __pyx_L1;}
  Py_DECREF(__pyx_1); __pyx_1 = 0;
  if (__pyx_2) {

    /* "/home/richard/private/Working/snowball/pystemmer/src/Stemmer.pyx":173 */
    __pyx_1 = PyInt_FromLong(1); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 173; goto __pyx_L1;}
    Py_DECREF(__pyx_v_was_unicode);
    __pyx_v_was_unicode = __pyx_1;
    __pyx_1 = 0;

    /* "/home/richard/private/Working/snowball/pystemmer/src/Stemmer.pyx":174 */
    __pyx_1 = PyObject_GetAttr(__pyx_v_word, __pyx_n_encode); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 174; goto __pyx_L1;}
    __pyx_3 = PyTuple_New(1); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 174; goto __pyx_L1;}
    Py_INCREF(__pyx_k9p);
    PyTuple_SET_ITEM(__pyx_3, 0, __pyx_k9p);
    __pyx_4 = PyObject_CallObject(__pyx_1, __pyx_3); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 174; goto __pyx_L1;}
    Py_DECREF(__pyx_1); __pyx_1 = 0;
    Py_DECREF(__pyx_3); __pyx_3 = 0;
    Py_DECREF(__pyx_v_word);
    __pyx_v_word = __pyx_4;
    __pyx_4 = 0;
    goto __pyx_L2;
  }
  __pyx_L2:;

  /* "/home/richard/private/Working/snowball/pystemmer/src/Stemmer.pyx":176 */
  __pyx_2 = (((struct __pyx_obj_7Stemmer_Stemmer *)__pyx_v_self)->max_cache_size > 0);
  if (__pyx_2) {
    /*try:*/ {

      /* "/home/richard/private/Working/snowball/pystemmer/src/Stemmer.pyx":178 */
      __pyx_1 = PyObject_GetItem(((struct __pyx_obj_7Stemmer_Stemmer *)__pyx_v_self)->cache, __pyx_v_word); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 178; goto __pyx_L4;}
      Py_DECREF(__pyx_v_cacheditem);
      __pyx_v_cacheditem = __pyx_1;
      __pyx_1 = 0;

      /* "/home/richard/private/Working/snowball/pystemmer/src/Stemmer.pyx":179 */
      __pyx_3 = __Pyx_GetItemInt(__pyx_v_cacheditem, 0); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 179; goto __pyx_L4;}
      Py_DECREF(__pyx_v_result);
      __pyx_v_result = __pyx_3;
      __pyx_3 = 0;

      /* "/home/richard/private/Working/snowball/pystemmer/src/Stemmer.pyx":180 */
      if (__Pyx_SetItemInt(__pyx_v_cacheditem, 1, ((struct __pyx_obj_7Stemmer_Stemmer *)__pyx_v_self)->counter) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 180; goto __pyx_L4;}

      /* "/home/richard/private/Working/snowball/pystemmer/src/Stemmer.pyx":181 */
      __pyx_4 = PyInt_FromLong(1); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 181; goto __pyx_L4;}
      __pyx_1 = PyNumber_Add(((struct __pyx_obj_7Stemmer_Stemmer *)__pyx_v_self)->counter, __pyx_4); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 181; goto __pyx_L4;}
      Py_DECREF(__pyx_4); __pyx_4 = 0;
      Py_DECREF(((struct __pyx_obj_7Stemmer_Stemmer *)__pyx_v_self)->counter);
      ((struct __pyx_obj_7Stemmer_Stemmer *)__pyx_v_self)->counter = __pyx_1;
      __pyx_1 = 0;
    }
    goto __pyx_L5;
    __pyx_L4:;
    Py_XDECREF(__pyx_3); __pyx_3 = 0;
    Py_XDECREF(__pyx_4); __pyx_4 = 0;
    Py_XDECREF(__pyx_1); __pyx_1 = 0;

    /* "/home/richard/private/Working/snowball/pystemmer/src/Stemmer.pyx":182 */
    __pyx_2 = PyErr_ExceptionMatches(PyExc_KeyError);
    if (__pyx_2) {
      __Pyx_AddTraceback("Stemmer.stemWord");
      if (__Pyx_GetException(&__pyx_3, &__pyx_4, &__pyx_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 182; goto __pyx_L1;}

      /* "/home/richard/private/Working/snowball/pystemmer/src/Stemmer.pyx":183 */
      __pyx_5 = PyString_AsString(__pyx_v_word); if (!__pyx_5) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 183; goto __pyx_L1;}
      __pyx_v_c_word = __pyx_5;

      /* "/home/richard/private/Working/snowball/pystemmer/src/Stemmer.pyx":184 */
      __pyx_6 = PyObject_Length(__pyx_v_word); if (__pyx_6 == -1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 184; goto __pyx_L1;}
      __pyx_v_c_word = ((char *)sb_stemmer_stem(((struct __pyx_obj_7Stemmer_Stemmer *)__pyx_v_self)->cobj,((sb_symbol *)__pyx_v_c_word),__pyx_6));

      /* "/home/richard/private/Working/snowball/pystemmer/src/Stemmer.pyx":185 */
      __pyx_7 = PyInt_FromLong(sb_stemmer_length(((struct __pyx_obj_7Stemmer_Stemmer *)__pyx_v_self)->cobj)); if (!__pyx_7) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 185; goto __pyx_L1;}
      Py_DECREF(__pyx_v_length);
      __pyx_v_length = __pyx_7;
      __pyx_7 = 0;

      /* "/home/richard/private/Working/snowball/pystemmer/src/Stemmer.pyx":186 */
      __pyx_2 = PyInt_AsLong(__pyx_v_length); if (PyErr_Occurred()) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 186; goto __pyx_L1;}
      __pyx_7 = PyString_FromStringAndSize(__pyx_v_c_word,__pyx_2); if (!__pyx_7) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 186; goto __pyx_L1;}
      Py_DECREF(__pyx_v_result);
      __pyx_v_result = __pyx_7;
      __pyx_7 = 0;

      /* "/home/richard/private/Working/snowball/pystemmer/src/Stemmer.pyx":187 */
      __pyx_7 = PyList_New(2); if (!__pyx_7) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 187; goto __pyx_L1;}
      Py_INCREF(__pyx_v_result);
      PyList_SET_ITEM(__pyx_7, 0, __pyx_v_result);
      Py_INCREF(((struct __pyx_obj_7Stemmer_Stemmer *)__pyx_v_self)->counter);
      PyList_SET_ITEM(__pyx_7, 1, ((struct __pyx_obj_7Stemmer_Stemmer *)__pyx_v_self)->counter);
      if (PyObject_SetItem(((struct __pyx_obj_7Stemmer_Stemmer *)__pyx_v_self)->cache, __pyx_v_word, __pyx_7) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 187; goto __pyx_L1;}
      Py_DECREF(__pyx_7); __pyx_7 = 0;

      /* "/home/richard/private/Working/snowball/pystemmer/src/Stemmer.pyx":188 */
      __pyx_7 = PyInt_FromLong(1); if (!__pyx_7) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 188; goto __pyx_L1;}
      __pyx_8 = PyNumber_Add(((struct __pyx_obj_7Stemmer_Stemmer *)__pyx_v_self)->counter, __pyx_7); if (!__pyx_8) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 188; goto __pyx_L1;}
      Py_DECREF(__pyx_7); __pyx_7 = 0;
      Py_DECREF(((struct __pyx_obj_7Stemmer_Stemmer *)__pyx_v_self)->counter);
      ((struct __pyx_obj_7Stemmer_Stemmer *)__pyx_v_self)->counter = __pyx_8;
      __pyx_8 = 0;

      /* "/home/richard/private/Working/snowball/pystemmer/src/Stemmer.pyx":189 */
      __pyx_7 = PyObject_GetAttr(__pyx_v_self, __pyx_n___purgeCache); if (!__pyx_7) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 189; goto __pyx_L1;}
      __pyx_8 = PyObject_CallObject(__pyx_7, 0); if (!__pyx_8) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 189; goto __pyx_L1;}
      Py_DECREF(__pyx_7); __pyx_7 = 0;
      Py_DECREF(__pyx_8); __pyx_8 = 0;
      Py_DECREF(__pyx_3); __pyx_3 = 0;
      Py_DECREF(__pyx_4); __pyx_4 = 0;
      Py_DECREF(__pyx_1); __pyx_1 = 0;
      goto __pyx_L5;
    }
    goto __pyx_L1;
    __pyx_L5:;
    goto __pyx_L3;
  }
  /*else*/ {

    /* "/home/richard/private/Working/snowball/pystemmer/src/Stemmer.pyx":191 */
    __pyx_5 = PyString_AsString(__pyx_v_word); if (!__pyx_5) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 191; goto __pyx_L1;}
    __pyx_v_c_word = __pyx_5;

    /* "/home/richard/private/Working/snowball/pystemmer/src/Stemmer.pyx":192 */
    __pyx_6 = PyObject_Length(__pyx_v_word); if (__pyx_6 == -1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 192; goto __pyx_L1;}
    __pyx_v_c_word = ((char *)sb_stemmer_stem(((struct __pyx_obj_7Stemmer_Stemmer *)__pyx_v_self)->cobj,((sb_symbol *)__pyx_v_c_word),__pyx_6));

    /* "/home/richard/private/Working/snowball/pystemmer/src/Stemmer.pyx":193 */
    __pyx_7 = PyInt_FromLong(sb_stemmer_length(((struct __pyx_obj_7Stemmer_Stemmer *)__pyx_v_self)->cobj)); if (!__pyx_7) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 193; goto __pyx_L1;}
    Py_DECREF(__pyx_v_length);
    __pyx_v_length = __pyx_7;
    __pyx_7 = 0;

    /* "/home/richard/private/Working/snowball/pystemmer/src/Stemmer.pyx":194 */
    __pyx_2 = PyInt_AsLong(__pyx_v_length); if (PyErr_Occurred()) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 194; goto __pyx_L1;}
    __pyx_8 = PyString_FromStringAndSize(__pyx_v_c_word,__pyx_2); if (!__pyx_8) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 194; goto __pyx_L1;}
    Py_DECREF(__pyx_v_result);
    __pyx_v_result = __pyx_8;
    __pyx_8 = 0;
  }
  __pyx_L3:;

  /* "/home/richard/private/Working/snowball/pystemmer/src/Stemmer.pyx":196 */
  __pyx_2 = PyObject_IsTrue(__pyx_v_was_unicode); if (__pyx_2 < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 196; goto __pyx_L1;}
  if (__pyx_2) {
    __pyx_3 = PyObject_GetAttr(__pyx_v_result, __pyx_n_decode); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 197; goto __pyx_L1;}
    __pyx_4 = PyTuple_New(1); if (!__pyx_4) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 197; goto __pyx_L1;}
    Py_INCREF(__pyx_k9p);
    PyTuple_SET_ITEM(__pyx_4, 0, __pyx_k9p);
    __pyx_1 = PyObject_CallObject(__pyx_3, __pyx_4); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 197; goto __pyx_L1;}
    Py_DECREF(__pyx_3); __pyx_3 = 0;
    Py_DECREF(__pyx_4); __pyx_4 = 0;
    __pyx_r = __pyx_1;
    __pyx_1 = 0;
    goto __pyx_L0;
    goto __pyx_L6;
  }
  __pyx_L6:;

  /* "/home/richard/private/Working/snowball/pystemmer/src/Stemmer.pyx":198 */
  Py_INCREF(__pyx_v_result);
  __pyx_r = __pyx_v_result;
  goto __pyx_L0;

  __pyx_r = Py_None; Py_INCREF(Py_None);
  goto __pyx_L0;
  __pyx_L1:;
  Py_XDECREF(__pyx_1);
  Py_XDECREF(__pyx_3);
  Py_XDECREF(__pyx_4);
  Py_XDECREF(__pyx_7);
  Py_XDECREF(__pyx_8);
  __Pyx_AddTraceback("Stemmer.Stemmer.stemWord");
  __pyx_r = 0;
  __pyx_L0:;
  Py_DECREF(__pyx_v_was_unicode);
  Py_DECREF(__pyx_v_cacheditem);
  Py_DECREF(__pyx_v_result);
  Py_DECREF(__pyx_v_length);
  Py_DECREF(__pyx_v_self);
  Py_DECREF(__pyx_v_word);
  return __pyx_r;
}
コード例 #23
0
static PyObject *
range_reverse(PyObject *seq)
{
    rangeobject *range = (rangeobject*) seq;
    longrangeiterobject *it;
    PyObject *one, *sum, *diff, *product;
    long lstart, lstop, lstep, new_start, new_stop;
    unsigned long ulen;

    assert(PyRange_Check(seq));

    /* reversed(range(start, stop, step)) can be expressed as
       range(start+(n-1)*step, start-step, -step), where n is the number of
       integers in the range.

       If each of start, stop, step, -step, start-step, and the length
       of the iterator is representable as a C long, use the int
       version.  This excludes some cases where the reversed range is
       representable as a range_iterator, but it's good enough for
       common cases and it makes the checks simple. */

    lstart = PyLong_AsLong(range->start);
    if (lstart == -1 && PyErr_Occurred()) {
        PyErr_Clear();
        goto long_range;
    }
    lstop = PyLong_AsLong(range->stop);
    if (lstop == -1 && PyErr_Occurred()) {
        PyErr_Clear();
        goto long_range;
    }
    lstep = PyLong_AsLong(range->step);
    if (lstep == -1 && PyErr_Occurred()) {
        PyErr_Clear();
        goto long_range;
    }
    /* check for possible overflow of -lstep */
    if (lstep == LONG_MIN)
        goto long_range;

    /* check for overflow of lstart - lstep:

       for lstep > 0, need only check whether lstart - lstep < LONG_MIN.
       for lstep < 0, need only check whether lstart - lstep > LONG_MAX

       Rearrange these inequalities as:

           lstart - LONG_MIN < lstep  (lstep > 0)
           LONG_MAX - lstart < -lstep  (lstep < 0)

       and compute both sides as unsigned longs, to avoid the
       possibility of undefined behaviour due to signed overflow. */

    if (lstep > 0) {
         if ((unsigned long)lstart - LONG_MIN < (unsigned long)lstep)
            goto long_range;
    }
    else {
        if (LONG_MAX - (unsigned long)lstart < 0UL - lstep)
            goto long_range;
    }

    ulen = get_len_of_range(lstart, lstop, lstep);
    if (ulen > (unsigned long)LONG_MAX)
        goto long_range;

    new_stop = lstart - lstep;
    new_start = (long)(new_stop + ulen * lstep);
    return fast_range_iter(new_start, new_stop, -lstep);

long_range:
    it = PyObject_New(longrangeiterobject, &PyLongRangeIter_Type);
    if (it == NULL)
        return NULL;

    /* start + (len - 1) * step */
    it->len = range->length;
    Py_INCREF(it->len);

    one = PyLong_FromLong(1);
    if (!one)
        goto create_failure;

    diff = PyNumber_Subtract(it->len, one);
    Py_DECREF(one);
    if (!diff)
        goto create_failure;

    product = PyNumber_Multiply(diff, range->step);
    Py_DECREF(diff);
    if (!product)
        goto create_failure;

    sum = PyNumber_Add(range->start, product);
    Py_DECREF(product);
    it->start = sum;
    if (!it->start)
        goto create_failure;

    it->step = PyNumber_Negative(range->step);
    if (!it->step)
        goto create_failure;

    it->index = PyLong_FromLong(0);
    if (!it->index)
        goto create_failure;

    return (PyObject *)it;

create_failure:
    Py_DECREF(it);
    return NULL;
}
コード例 #24
0
ファイル: peephole.c プロジェクト: AbnerChang/edk2-staging
/* Replace LOAD_CONST c1. LOAD_CONST c2 BINOP
   with    LOAD_CONST binop(c1,c2)
   The consts table must still be in list form so that the
   new constant can be appended.
   Called with codestr pointing to the first LOAD_CONST.
   Abandons the transformation if the folding fails (i.e.  1+'a').
   If the new constant is a sequence, only folds when the size
   is below a threshold value.  That keeps pyc files from
   becoming large in the presence of code like:  (None,)*1000.
*/
static int
fold_binops_on_constants(unsigned char *codestr, PyObject *consts)
{
    PyObject *newconst, *v, *w;
    Py_ssize_t len_consts, size;
    int opcode;

    /* Pre-conditions */
    assert(PyList_CheckExact(consts));
    assert(codestr[0] == LOAD_CONST);
    assert(codestr[3] == LOAD_CONST);

    /* Create new constant */
    v = PyList_GET_ITEM(consts, GETARG(codestr, 0));
    w = PyList_GET_ITEM(consts, GETARG(codestr, 3));
    opcode = codestr[6];
    switch (opcode) {
        case BINARY_POWER:
            newconst = PyNumber_Power(v, w, Py_None);
            break;
        case BINARY_MULTIPLY:
            newconst = PyNumber_Multiply(v, w);
            break;
        case BINARY_DIVIDE:
            /* Cannot fold this operation statically since
               the result can depend on the run-time presence
               of the -Qnew flag */
            return 0;
        case BINARY_TRUE_DIVIDE:
            newconst = PyNumber_TrueDivide(v, w);
            break;
        case BINARY_FLOOR_DIVIDE:
            newconst = PyNumber_FloorDivide(v, w);
            break;
        case BINARY_MODULO:
            newconst = PyNumber_Remainder(v, w);
            break;
        case BINARY_ADD:
            newconst = PyNumber_Add(v, w);
            break;
        case BINARY_SUBTRACT:
            newconst = PyNumber_Subtract(v, w);
            break;
        case BINARY_SUBSCR:
            newconst = PyObject_GetItem(v, w);
            /* #5057: if v is unicode, there might be differences between
               wide and narrow builds in cases like u'\U00012345'[0].
               Wide builds will return a non-BMP char, whereas narrow builds
               will return a surrogate.  In both the cases skip the
               optimization in order to produce compatible pycs.
             */
            if (newconst != NULL &&
                PyUnicode_Check(v) && PyUnicode_Check(newconst)) {
                Py_UNICODE ch = PyUnicode_AS_UNICODE(newconst)[0];
#ifdef Py_UNICODE_WIDE
                if (ch > 0xFFFF) {
#else
                if (ch >= 0xD800 && ch <= 0xDFFF) {
#endif
                    Py_DECREF(newconst);
                    return 0;
                }
            }
            break;
        case BINARY_LSHIFT:
            newconst = PyNumber_Lshift(v, w);
            break;
        case BINARY_RSHIFT:
            newconst = PyNumber_Rshift(v, w);
            break;
        case BINARY_AND:
            newconst = PyNumber_And(v, w);
            break;
        case BINARY_XOR:
            newconst = PyNumber_Xor(v, w);
            break;
        case BINARY_OR:
            newconst = PyNumber_Or(v, w);
            break;
        default:
            /* Called with an unknown opcode */
            PyErr_Format(PyExc_SystemError,
                 "unexpected binary operation %d on a constant",
                     opcode);
            return 0;
    }
    if (newconst == NULL) {
        PyErr_Clear();
        return 0;
    }
    size = PyObject_Size(newconst);
    if (size == -1)
        PyErr_Clear();
    else if (size > 20) {
        Py_DECREF(newconst);
        return 0;
    }

    /* Append folded constant into consts table */
    len_consts = PyList_GET_SIZE(consts);
    if (PyList_Append(consts, newconst)) {
        Py_DECREF(newconst);
        return 0;
    }
    Py_DECREF(newconst);

    /* Write NOP NOP NOP NOP LOAD_CONST newconst */
    memset(codestr, NOP, 4);
    codestr[4] = LOAD_CONST;
    SETARG(codestr, 4, len_consts);
    return 1;
}

static int
fold_unaryops_on_constants(unsigned char *codestr, PyObject *consts)
{
    PyObject *newconst=NULL, *v;
    Py_ssize_t len_consts;
    int opcode;

    /* Pre-conditions */
    assert(PyList_CheckExact(consts));
    assert(codestr[0] == LOAD_CONST);

    /* Create new constant */
    v = PyList_GET_ITEM(consts, GETARG(codestr, 0));
    opcode = codestr[3];
    switch (opcode) {
        case UNARY_NEGATIVE:
            /* Preserve the sign of -0.0 */
            if (PyObject_IsTrue(v) == 1)
                newconst = PyNumber_Negative(v);
            break;
        case UNARY_CONVERT:
            newconst = PyObject_Repr(v);
            break;
        case UNARY_INVERT:
            newconst = PyNumber_Invert(v);
            break;
        default:
            /* Called with an unknown opcode */
            PyErr_Format(PyExc_SystemError,
                 "unexpected unary operation %d on a constant",
                     opcode);
            return 0;
    }
    if (newconst == NULL) {
        PyErr_Clear();
        return 0;
    }

    /* Append folded constant into consts table */
    len_consts = PyList_GET_SIZE(consts);
    if (PyList_Append(consts, newconst)) {
        Py_DECREF(newconst);
        return 0;
    }
    Py_DECREF(newconst);

    /* Write NOP LOAD_CONST newconst */
    codestr[0] = NOP;
    codestr[1] = LOAD_CONST;
    SETARG(codestr, 1, len_consts);
    return 1;
}
コード例 #25
0
ファイル: multass.c プロジェクト: jwilk/Pyrex
static void __pyx_f_7multass_f(void) {
  PyObject *__pyx_v_obj1a;
  PyObject *__pyx_v_obj2a;
  PyObject *__pyx_v_obj3a;
  PyObject *__pyx_v_obj1b;
  PyObject *__pyx_v_obj2b;
  PyObject *__pyx_v_obj3b;
  int __pyx_v_int1;
  int __pyx_v_int2;
  char *__pyx_v_ptr1;
  char *__pyx_v_ptr2;
  PyObject *__pyx_1 = 0;
  PyObject *__pyx_2 = 0;
  PyObject *__pyx_3 = 0;
  int __pyx_4;
  char *__pyx_5;
  PyObject *__pyx_6 = 0;
  __pyx_v_obj1a = Py_None; Py_INCREF(Py_None);
  __pyx_v_obj2a = Py_None; Py_INCREF(Py_None);
  __pyx_v_obj3a = Py_None; Py_INCREF(Py_None);
  __pyx_v_obj1b = Py_None; Py_INCREF(Py_None);
  __pyx_v_obj2b = Py_None; Py_INCREF(Py_None);
  __pyx_v_obj3b = Py_None; Py_INCREF(Py_None);

  /* "/Local/Projects/D/Pyrex/Source/Tests/3/multass.pyx":5 */
  __pyx_1 = __pyx_v_obj1b;
  Py_INCREF(__pyx_1);
  __pyx_2 = __pyx_v_obj2b;
  Py_INCREF(__pyx_2);
  Py_DECREF(__pyx_v_obj1a);
  __pyx_v_obj1a = __pyx_1;
  __pyx_1 = 0;
  Py_DECREF(__pyx_v_obj2a);
  __pyx_v_obj2a = __pyx_2;
  __pyx_2 = 0;

  /* "/Local/Projects/D/Pyrex/Source/Tests/3/multass.pyx":6 */
  __pyx_1 = __pyx_v_obj1b;
  Py_INCREF(__pyx_1);
  __pyx_2 = __pyx_v_obj2b;
  Py_INCREF(__pyx_2);
  __pyx_3 = __pyx_v_obj3b;
  Py_INCREF(__pyx_3);
  Py_DECREF(__pyx_v_obj1a);
  __pyx_v_obj1a = __pyx_1;
  __pyx_1 = 0;
  Py_DECREF(__pyx_v_obj2a);
  __pyx_v_obj2a = __pyx_2;
  __pyx_2 = 0;
  Py_DECREF(__pyx_v_obj3a);
  __pyx_v_obj3a = __pyx_3;
  __pyx_3 = 0;

  /* "/Local/Projects/D/Pyrex/Source/Tests/3/multass.pyx":7 */
  __pyx_4 = __pyx_v_int2;
  __pyx_5 = __pyx_v_ptr2;
  __pyx_1 = __pyx_v_obj1b;
  Py_INCREF(__pyx_1);
  __pyx_v_int1 = __pyx_4;
  __pyx_v_ptr1 = __pyx_5;
  Py_DECREF(__pyx_v_obj1a);
  __pyx_v_obj1a = __pyx_1;
  __pyx_1 = 0;

  /* "/Local/Projects/D/Pyrex/Source/Tests/3/multass.pyx":8 */
  __pyx_2 = PyInt_FromLong(1); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 8; goto __pyx_L1;}
  __pyx_3 = PyNumber_Add(__pyx_v_obj1b, __pyx_2); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 8; goto __pyx_L1;}
  Py_DECREF(__pyx_2); __pyx_2 = 0;
  __pyx_1 = PyInt_FromLong(2); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 8; goto __pyx_L1;}
  __pyx_2 = PyNumber_Add(__pyx_v_obj2b, __pyx_1); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 8; goto __pyx_L1;}
  Py_DECREF(__pyx_1); __pyx_1 = 0;
  __pyx_1 = PyInt_FromLong(3); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 8; goto __pyx_L1;}
  __pyx_6 = PyNumber_Add(__pyx_v_obj3b, __pyx_1); if (!__pyx_6) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 8; goto __pyx_L1;}
  Py_DECREF(__pyx_1); __pyx_1 = 0;
  Py_DECREF(__pyx_v_obj1a);
  __pyx_v_obj1a = __pyx_3;
  __pyx_3 = 0;
  Py_DECREF(__pyx_v_obj2a);
  __pyx_v_obj2a = __pyx_2;
  __pyx_2 = 0;
  Py_DECREF(__pyx_v_obj3a);
  __pyx_v_obj3a = __pyx_6;
  __pyx_6 = 0;

  goto __pyx_L0;
  __pyx_L1:;
  Py_XDECREF(__pyx_1);
  Py_XDECREF(__pyx_2);
  Py_XDECREF(__pyx_3);
  Py_XDECREF(__pyx_6);
  __Pyx_WriteUnraisable("multass.f");
  __pyx_L0:;
  Py_DECREF(__pyx_v_obj1a);
  Py_DECREF(__pyx_v_obj2a);
  Py_DECREF(__pyx_v_obj3a);
  Py_DECREF(__pyx_v_obj1b);
  Py_DECREF(__pyx_v_obj2b);
  Py_DECREF(__pyx_v_obj3b);
}
コード例 #26
0
static PyObject *bip_sum(term_t t) {
  PyObject *seq;
  PyObject *result = NULL;
  PyObject *temp, *item, *iter;

  if (!PL_get_arg(1, t, t))
    return NULL;
  seq = term_to_python(t, true);
  iter = PyObject_GetIter(seq);
  if (iter == NULL)
    return NULL;

  if (result == NULL) {
#if PY_MAJOR_VERSION < 3
    result = PyInt_FromLong(0);
#else
    result = PyLong_FromLong(0);
#endif
    if (result == NULL) {
      Py_DECREF(iter);
      return NULL;
    }
  } else {
#if PY_MAJOR_VERSION < 3
    /* reject string values for 'start' parameter */
    if (PyObject_TypeCheck(result, &PyBaseString_Type)) {
      PyErr_SetString(PyExc_TypeError,
                      "sum() can't sum strings [use ''.join(seq) instead]");
      Py_DECREF(iter);
      return NULL;
    }
    Py_INCREF(result);
#endif
  }

#ifndef SLOW_SUM
/* Fast addition by keeping temporary sums in C instead of new Python objects.
Assumes all inputs are the same type.  If the assumption fails, default
to the more general routine.
*/
#if PY_MAJOR_VERSION < 3
  if (PyInt_CheckExact(result)) {
    long i_result = PyInt_AS_LONG(result);
#else
  if (PyLong_CheckExact(result)) {
    long i_result = PyLong_AS_LONG(result);
#endif
    Py_DECREF(result);
    result = NULL;
    while (result == NULL) {
      item = PyIter_Next(iter);
      if (item == NULL) {
        Py_DECREF(iter);
        if (PyErr_Occurred())
          return NULL;
#if PY_MAJOR_VERSION < 3
        return PyInt_FromLong(i_result);
#else
        return PyLong_FromLong(i_result);
#endif
      }
#if PY_MAJOR_VERSION < 3
      if (PyInt_CheckExact(item)) {
        long b = PyInt_AS_LONG(item);
#else
      if (PyLong_CheckExact(item)) {
        long b = PyLong_AS_LONG(item);
#endif
        long x = i_result + b;
        if ((x ^ i_result) >= 0 || (x ^ b) >= 0) {
          i_result = x;
          Py_DECREF(item);
          continue;
        }
      }
/* Either overflowed or is not an int. Restore real objects and process normally
 */
#if PY_MAJOR_VERSION < 3
      result = PyInt_FromLong(i_result);
#else
      result = PyLong_FromLong(i_result);
#endif
      temp = PyNumber_Add(result, item);
      Py_DECREF(result);
      Py_DECREF(item);
      result = temp;
      if (result == NULL) {
        Py_DECREF(iter);
        return NULL;
      }
    }
  }

  if (PyFloat_CheckExact(result)) {
    double f_result = PyFloat_AS_DOUBLE(result);
    Py_DECREF(result);
    result = NULL;
    while (result == NULL) {
      item = PyIter_Next(iter);
      if (item == NULL) {
        Py_DECREF(iter);
        if (PyErr_Occurred())
          return NULL;
        return PyFloat_FromDouble(f_result);
      }
      if (PyFloat_CheckExact(item)) {
        PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
            f_result += PyFloat_AS_DOUBLE(item);
        PyFPE_END_PROTECT(f_result) Py_DECREF(item);
        continue;
      }
#if PY_MAJOR_VERSION < 3
      if (PyInt_CheckExact(item)) {
        PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
            f_result += (double)PyInt_AS_LONG(item);
        PyFPE_END_PROTECT(f_result) Py_DECREF(item);
        continue;
      }
#else
      if (PyLong_CheckExact(item)) {
        PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
            f_result += PyLong_AsDouble(item);
        PyFPE_END_PROTECT(f_result) Py_DECREF(item);
        continue;
      }
#endif
      result = PyFloat_FromDouble(f_result);
      temp = PyNumber_Add(result, item);
      Py_DECREF(result);
      Py_DECREF(item);
      result = temp;
      if (result == NULL) {
        Py_DECREF(iter);
        return NULL;
      }
    }
#endif
  }

  for (;;) {
    item = PyIter_Next(iter);
    if (item == NULL) {
      /* error, or end-of-sequence */
      if (PyErr_Occurred()) {
        Py_DECREF(result);
        result = NULL;
      }
      break;
    }
    /* It's tempting to use PyNumber_InPlaceAdd instead of
    PyNumber_Add here, to avoid quadratic running time
    when doing 'sum(list_of_lists, [])'.  However, this
    would produce a change in behaviour: a snippet like

    empty = []
    sum([[x] for x in range(10)], empty)

    would change the value of empty. */
    temp = PyNumber_Add(result, item);
    Py_DECREF(result);
    Py_DECREF(item);
    result = temp;
    if (result == NULL)
      break;
  }
  Py_DECREF(iter);
  return result;
}

//@}

static long get_int(term_t arg, bool eval) {
  long low;

  if (!PL_get_long(arg, &low)) {
    PyObject *low = term_to_python(arg, eval);
    if (PyLong_Check(low)) {
      return PyLong_AsLong(low);
#if PY_MAJOR_VERSION < 3
    } else if (PyInt_Check(low)) {
      return PyInt_AsLong(low);
#endif
    } else {
      return 0;
    }
  }
  return low;
}

/* Return number of items in range/xrange (lo, hi, step).  step > 0
* required.  Return a value < 0 if & only if the true value is too
* large to fit in a signed long.
*/
static long get_len_of_range(long lo, long hi, long step) {
  /* -------------------------------------------------------------
  If lo >= hi, the range is empty.
  Else if n values are in the range, the last one is
  lo + (n-1)*step, which must be <= hi-1.  Rearranging,
  n <= (hi - lo - 1)/step + 1, so taking the floor of the RHS gives
  the proper value.  Since lo < hi in this case, hi-lo-1 >= 0, so
  the RHS is non-negative and so truncation is the same as the
  floor.  Letting M be the largest positive long, the worst case
  for the RHS numerator is hi=M, lo=-M-1, and then
  hi-lo-1 = M-(-M-1)-1 = 2*M.  Therefore unsigned long has enough
  precision to compute the RHS exactly.
  ---------------------------------------------------------------*/
  long n = 0;
  if (lo < hi) {
    unsigned long uhi = (unsigned long)hi;
    unsigned long ulo = (unsigned long)lo;
    unsigned long diff = uhi - ulo - 1;
    n = (long)(diff / (unsigned long)step + 1);
  }
  return n;
}
コード例 #27
0
ファイル: gmpy_mpmath.c プロジェクト: chevah/python-package
static PyObject *
Pympz_mpmath_create(PyObject *self, PyObject *args)
{
    long sign;
    mpir_si bc, shift, zbits, carry = 0, prec = 0;
    PyObject *exp = 0, *newexp = 0, *newexp2 = 0, *tmp = 0;
    PympzObject *man = 0, *upper = 0, *lower = 0;

    const char *rnd = "f";

    if (PyTuple_GET_SIZE(args) < 2) {
        TYPE_ERROR("mpmath_create() expects 'mpz','int'[,'int','str'] arguments");
        return NULL;
    }

    switch (PyTuple_GET_SIZE(args)) {
        case 4:
            rnd = Py2or3String_AsString(PyTuple_GET_ITEM(args, 3));
        case 3:
            prec = SI_From_Integer(PyTuple_GET_ITEM(args, 2));
            if (prec == -1 && PyErr_Occurred())
                return NULL;
            prec = ABS(prec);
        case 2:
            exp = PyTuple_GET_ITEM(args, 1);
        case 1:
            man = Pympz_From_Integer(PyTuple_GET_ITEM(args, 0));
            if (!man) {
                TYPE_ERROR("mpmath_create() expects 'mpz','int'[,'int','str'] arguments");
                return NULL;
            }
    }

    /* If the mantissa is 0, return the normalized representation. */
    if (!mpz_sgn(man->z)) {
        return mpmath_build_mpf(0, man, 0, 0);
    }

    upper = (PympzObject*)Pympz_new();
    lower = (PympzObject*)Pympz_new();
    if (!upper || !lower) {
        Py_DECREF((PyObject*)man);
        Py_XDECREF((PyObject*)upper);
        Py_XDECREF((PyObject*)lower);
        return NULL;
    }

    /* Extract sign, make man positive, and set bit count */
    sign = (mpz_sgn(man->z) == -1);
    mpz_abs(upper->z, man->z);
    bc = mpz_sizeinbase(upper->z, 2);

    if (!prec) prec = bc;

    shift = bc - prec;
    if (shift > 0) {
        switch (rnd[0]) {
            case 'f':
                if(sign) {
                    mpz_cdiv_q_2exp(upper->z, upper->z, shift);
                }
                else {
                    mpz_fdiv_q_2exp(upper->z, upper->z, shift);
                }
                break;
            case 'c':
                if(sign) {
                    mpz_fdiv_q_2exp(upper->z, upper->z, shift);
                }
                else {
                    mpz_cdiv_q_2exp(upper->z, upper->z, shift);
                }
                break;
            case 'd':
                mpz_fdiv_q_2exp(upper->z, upper->z, shift);
                break;
            case 'u':
                mpz_cdiv_q_2exp(upper->z, upper->z, shift);
                break;
            case 'n':
            default:
                mpz_tdiv_r_2exp(lower->z, upper->z, shift);
                mpz_tdiv_q_2exp(upper->z, upper->z, shift);
                if (mpz_sgn(lower->z)) {
                    /* lower is not 0 so it must have at least 1 bit set */
                    if (mpz_sizeinbase(lower->z, 2)==shift) {
                        /* lower is >= 1/2 */
                        if (mpz_scan1(lower->z, 0)==shift-1) {
                            /* lower is exactly 1/2 */
                            if (mpz_odd_p(upper->z))
                                carry = 1;
                        }
                        else {
                            carry = 1;
                        }
                    }
                }
                if (carry)
                    mpz_add_ui(upper->z, upper->z, 1);
        }
        if (!(tmp = PyIntOrLong_FromSI(shift))) {
            Py_DECREF((PyObject*)upper);
            Py_DECREF((PyObject*)lower);
            return NULL;
        }
        if (!(newexp = PyNumber_Add(exp, tmp))) {
            Py_DECREF((PyObject*)man);
            Py_DECREF((PyObject*)upper);
            Py_DECREF((PyObject*)lower);
            Py_DECREF(tmp);
            return NULL;
        }
        Py_DECREF(tmp);
        bc = prec;
    }
    else {
        newexp = exp;
        Py_INCREF(newexp);
    }

    /* Strip trailing 0 bits. */
    if ((zbits = mpz_scan1(upper->z, 0)))
        mpz_tdiv_q_2exp(upper->z, upper->z, zbits);

    if (!(tmp = PyIntOrLong_FromSI(zbits))) {
        Py_DECREF((PyObject*)man);
        Py_DECREF((PyObject*)upper);
        Py_DECREF((PyObject*)lower);
        Py_DECREF(newexp);
        return NULL;
    }
    if (!(newexp2 = PyNumber_Add(newexp, tmp))) {
        Py_DECREF((PyObject*)man);
        Py_DECREF((PyObject*)upper);
        Py_DECREF((PyObject*)lower);
        Py_DECREF(tmp);
        Py_DECREF(newexp);
        return NULL;
    }
    Py_DECREF(newexp);
    Py_DECREF(tmp);

    bc -= zbits;
    /* Check if one less than a power of 2 was rounded up. */
    if (!mpz_cmp_ui(upper->z, 1))
        bc = 1;

    Py_DECREF((PyObject*)lower);
    Py_DECREF((PyObject*)man);
    return mpmath_build_mpf(sign, upper, newexp2, bc);
}
コード例 #28
0
ファイル: gmpy_mpmath.c プロジェクト: chevah/python-package
static PyObject *
Pympz_mpmath_normalize(PyObject *self, PyObject *args)
{
    long sign = 0;
    mpir_si bc = 0, prec = 0, shift, zbits, carry = 0;
    PyObject *exp = 0, *newexp = 0, *newexp2 = 0, *tmp = 0, *rndstr = 0;
    PympzObject *man = 0, *upper = 0, *lower = 0;
    char rnd = 0;

    if (PyTuple_GET_SIZE(args) == 6) {
        /* Need better error-checking here. Under Python 3.0, overflow into
           C-long is possible. */
        sign = clong_From_Integer(PyTuple_GET_ITEM(args, 0));
        man = (PympzObject *)PyTuple_GET_ITEM(args, 1);
        exp = PyTuple_GET_ITEM(args, 2);
        bc = SI_From_Integer(PyTuple_GET_ITEM(args, 3));
        prec = SI_From_Integer(PyTuple_GET_ITEM(args, 4));
        rndstr = PyTuple_GET_ITEM(args, 5);
        if (PyErr_Occurred()) {
            TYPE_ERROR("arguments long, PympzObject*, PyObject*, long, long, char needed");
            return NULL;
        }
    }
    else {
        TYPE_ERROR("6 arguments required");
        return NULL;
    }

    if (!Pympz_Check(man)) {
        TYPE_ERROR("argument is not an mpz");
        return NULL;
    }

    /* If rndstr really is a string, extract the first character. */
    if (Py2or3String_Check(rndstr)) {
        rnd = Py2or3String_AsString(rndstr)[0];
    }
    else {
        VALUE_ERROR("invalid rounding mode specified");
        return NULL;
    }

    /* If the mantissa is 0, return the normalized representation. */
    if (!mpz_sgn(man->z)) {
        Py_INCREF((PyObject*)man);
        return mpmath_build_mpf(0, man, 0, 0);
    }

    /* if bc <= prec and the number is odd return it */
    if ((bc <= prec) && mpz_odd_p(man->z)) {
        Py_INCREF((PyObject*)man);
        Py_INCREF((PyObject*)exp);
        return mpmath_build_mpf(sign, man, exp, bc);
    }

    if (!(upper = (PympzObject*)Pympz_new()) ||
        !(lower = (PympzObject*)Pympz_new())) {
        Py_XDECREF((PyObject*)upper);
        Py_XDECREF((PyObject*)lower);
    }

    shift = bc - prec;
    if (shift>0) {
        switch (rnd) {
            case 'f':
                if(sign) {
                    mpz_cdiv_q_2exp(upper->z, man->z, shift);
                }
                else {
                    mpz_fdiv_q_2exp(upper->z, man->z, shift);
                }
                break;
            case 'c':
                if(sign) {
                    mpz_fdiv_q_2exp(upper->z, man->z, shift);
                }
                else {
                    mpz_cdiv_q_2exp(upper->z, man->z, shift);
                }
                break;
            case 'd':
                mpz_fdiv_q_2exp(upper->z, man->z, shift);
                break;
            case 'u':
                mpz_cdiv_q_2exp(upper->z, man->z, shift);
                break;
            case 'n':
            default:
                mpz_tdiv_r_2exp(lower->z, man->z, shift);
                mpz_tdiv_q_2exp(upper->z, man->z, shift);
                if (mpz_sgn(lower->z)) {
                    /* lower is not 0 so it must have at least 1 bit set */
                    if (mpz_sizeinbase(lower->z, 2) == shift) {
                        /* lower is >= 1/2 */
                        if (mpz_scan1(lower->z, 0) == shift-1) {
                            /* lower is exactly 1/2 */
                            if (mpz_odd_p(upper->z))
                                carry = 1;
                        }
                        else {
                            carry = 1;
                        }
                    }
                }
                if (carry)
                    mpz_add_ui(upper->z, upper->z, 1);
        }

        if (!(tmp = PyIntOrLong_FromSI(shift))) {
            Py_DECREF((PyObject*)upper);
            Py_DECREF((PyObject*)lower);
            return NULL;
        }

        if (!(newexp = PyNumber_Add(exp, tmp))) {
            Py_DECREF((PyObject*)upper);
            Py_DECREF((PyObject*)lower);
            Py_DECREF(tmp);
            return NULL;
        }
        Py_DECREF(tmp);
        bc = prec;
    }
    else {
        mpz_set(upper->z, man->z);
        newexp = exp;
        Py_INCREF(newexp);
    }

    /* Strip trailing 0 bits. */
    if ((zbits = mpz_scan1(upper->z, 0)))
        mpz_tdiv_q_2exp(upper->z, upper->z, zbits);

    if (!(tmp = PyIntOrLong_FromSI(zbits))) {
        Py_DECREF((PyObject*)upper);
        Py_DECREF((PyObject*)lower);
        Py_DECREF(newexp);
        return NULL;
    }
    if (!(newexp2 = PyNumber_Add(newexp, tmp))) {
        Py_DECREF((PyObject*)upper);
        Py_DECREF((PyObject*)lower);
        Py_DECREF(tmp);
        Py_DECREF(newexp);
        return NULL;
    }
    Py_DECREF(newexp);
    Py_DECREF(tmp);

    bc -= zbits;
    /* Check if one less than a power of 2 was rounded up. */
    if (!mpz_cmp_ui(upper->z, 1))
        bc = 1;

    Py_DECREF((PyObject*)lower);
    return mpmath_build_mpf(sign, upper, newexp2, bc);
}
コード例 #29
0
ファイル: peephole.c プロジェクト: Jimlan/kbengine
/* Replace LOAD_CONST c1. LOAD_CONST c2 BINOP
   with    LOAD_CONST binop(c1,c2)
   The consts table must still be in list form so that the
   new constant can be appended.
   Called with codestr pointing to the first LOAD_CONST.
   Abandons the transformation if the folding fails (i.e.  1+'a').
   If the new constant is a sequence, only folds when the size
   is below a threshold value.  That keeps pyc files from
   becoming large in the presence of code like:  (None,)*1000.
*/
static int
fold_binops_on_constants(unsigned char *codestr, PyObject *consts)
{
    PyObject *newconst, *v, *w;
    Py_ssize_t len_consts, size;
    int opcode;

    /* Pre-conditions */
    assert(PyList_CheckExact(consts));
    assert(codestr[0] == LOAD_CONST);
    assert(codestr[3] == LOAD_CONST);

    /* Create new constant */
    v = PyList_GET_ITEM(consts, GETARG(codestr, 0));
    w = PyList_GET_ITEM(consts, GETARG(codestr, 3));
    opcode = codestr[6];
    switch (opcode) {
        case BINARY_POWER:
            newconst = PyNumber_Power(v, w, Py_None);
            break;
        case BINARY_MULTIPLY:
            newconst = PyNumber_Multiply(v, w);
            break;
        case BINARY_TRUE_DIVIDE:
            newconst = PyNumber_TrueDivide(v, w);
            break;
        case BINARY_FLOOR_DIVIDE:
            newconst = PyNumber_FloorDivide(v, w);
            break;
        case BINARY_MODULO:
            newconst = PyNumber_Remainder(v, w);
            break;
        case BINARY_ADD:
            newconst = PyNumber_Add(v, w);
            break;
        case BINARY_SUBTRACT:
            newconst = PyNumber_Subtract(v, w);
            break;
        case BINARY_SUBSCR:
            /* #5057: if v is unicode, there might be differences between
               wide and narrow builds in cases like '\U00012345'[0] or
               '\U00012345abcdef'[3], so it's better to skip the optimization
               in order to produce compatible pycs.
            */
            if (PyUnicode_Check(v))
                return 0;
            newconst = PyObject_GetItem(v, w);
            break;
        case BINARY_LSHIFT:
            newconst = PyNumber_Lshift(v, w);
            break;
        case BINARY_RSHIFT:
            newconst = PyNumber_Rshift(v, w);
            break;
        case BINARY_AND:
            newconst = PyNumber_And(v, w);
            break;
        case BINARY_XOR:
            newconst = PyNumber_Xor(v, w);
            break;
        case BINARY_OR:
            newconst = PyNumber_Or(v, w);
            break;
        default:
            /* Called with an unknown opcode */
            PyErr_Format(PyExc_SystemError,
                 "unexpected binary operation %d on a constant",
                     opcode);
            return 0;
    }
    if (newconst == NULL) {
        if(!PyErr_ExceptionMatches(PyExc_KeyboardInterrupt))
            PyErr_Clear();
        return 0;
    }
    size = PyObject_Size(newconst);
    if (size == -1) {
        if (PyErr_ExceptionMatches(PyExc_KeyboardInterrupt))
            return 0;
        PyErr_Clear();
    } else if (size > 20) {
        Py_DECREF(newconst);
        return 0;
    }

    /* Append folded constant into consts table */
    len_consts = PyList_GET_SIZE(consts);
    if (PyList_Append(consts, newconst)) {
        Py_DECREF(newconst);
        return 0;
    }
    Py_DECREF(newconst);

    /* Write NOP NOP NOP NOP LOAD_CONST newconst */
    memset(codestr, NOP, 4);
    codestr[4] = LOAD_CONST;
    SETARG(codestr, 4, len_consts);
    return 1;
}
コード例 #30
0
ファイル: inplace_lhs.c プロジェクト: jwilk/Pyrex
static int __pyx_f_11inplace_lhs_f(void) {
  int __pyx_v_i;
  int __pyx_v_j;
  int __pyx_v_k;
  float __pyx_v_x;
  float __pyx_v_y;
  float __pyx_v_z;
  PyObject *__pyx_v_a;
  PyObject *__pyx_v_b;
  PyObject *__pyx_v_c;
  PyObject *__pyx_v_d;
  int __pyx_v_m[3];
  struct __pyx_t_11inplace_lhs_S __pyx_v_s;
  int __pyx_r;
  PyObject *__pyx_1 = 0;
  PyObject *__pyx_2 = 0;
  PyObject *__pyx_3 = 0;
  __pyx_v_a = Py_None; Py_INCREF(Py_None);
  __pyx_v_b = Py_None; Py_INCREF(Py_None);
  __pyx_v_c = Py_None; Py_INCREF(Py_None);
  __pyx_v_d = Py_None; Py_INCREF(Py_None);

  /* "/Local/Projects/D/Pyrex/Source/Tests/10/inplace_lhs.pyx":11 */
  __pyx_v_i += (__pyx_v_j + __pyx_v_k);

  /* "/Local/Projects/D/Pyrex/Source/Tests/10/inplace_lhs.pyx":12 */
  __pyx_v_x += (__pyx_v_y + __pyx_v_z);

  /* "/Local/Projects/D/Pyrex/Source/Tests/10/inplace_lhs.pyx":13 */
  __pyx_v_x += __pyx_v_i;

  /* "/Local/Projects/D/Pyrex/Source/Tests/10/inplace_lhs.pyx":14 */
  __pyx_1 = PyNumber_Add(__pyx_v_b, __pyx_v_c); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; goto __pyx_L1;}
  __pyx_2 = PyNumber_InPlaceAdd(__pyx_v_a, __pyx_1); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; goto __pyx_L1;}
  Py_DECREF(__pyx_1); __pyx_1 = 0;
  Py_DECREF(__pyx_v_a);
  __pyx_v_a = __pyx_2;

  /* "/Local/Projects/D/Pyrex/Source/Tests/10/inplace_lhs.pyx":15 */
  __pyx_1 = __Pyx_GetName(__pyx_m, __pyx_n_g); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 15; goto __pyx_L1;}
  __pyx_2 = PyNumber_InPlaceAdd(__pyx_1, __pyx_v_a); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 15; goto __pyx_L1;}
  Py_DECREF(__pyx_1); __pyx_1 = 0;
  if (PyObject_SetAttr(__pyx_m, __pyx_n_g, __pyx_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 15; goto __pyx_L1;}
  Py_DECREF(__pyx_2); __pyx_2 = 0;

  /* "/Local/Projects/D/Pyrex/Source/Tests/10/inplace_lhs.pyx":16 */
  (__pyx_v_m[__pyx_v_i]) += __pyx_v_j;

  /* "/Local/Projects/D/Pyrex/Source/Tests/10/inplace_lhs.pyx":17 */
  __pyx_1 = PyNumber_Add(__pyx_v_b, __pyx_v_c); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 17; goto __pyx_L1;}
  __pyx_2 = PyInt_FromLong(__pyx_v_i); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 17; goto __pyx_L1;}
  __pyx_3 = PyObject_GetItem(__pyx_v_a, __pyx_2); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 17; goto __pyx_L1;}
  __pyx_3 = PyNumber_InPlaceAdd(__pyx_2, __pyx_1); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 17; goto __pyx_L1;}
  Py_DECREF(__pyx_2); __pyx_2 = 0;
  Py_DECREF(__pyx_1); __pyx_1 = 0;
  if (PyObject_SetItem(__pyx_v_a, __pyx_2, __pyx_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 17; goto __pyx_L1;}
  Py_DECREF(__pyx_3); __pyx_3 = 0;
  Py_DECREF(__pyx_2); __pyx_2 = 0;

  /* "/Local/Projects/D/Pyrex/Source/Tests/10/inplace_lhs.pyx":18 */
  __pyx_2 = PyNumber_Add(__pyx_v_b, __pyx_v_c); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 18; goto __pyx_L1;}
  __pyx_1 = PyObject_GetItem(__pyx_v_a, __pyx_2); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 18; goto __pyx_L1;}
  __pyx_3 = PyNumber_InPlaceAdd(__pyx_1, __pyx_v_d); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 18; goto __pyx_L1;}
  Py_DECREF(__pyx_1); __pyx_1 = 0;
  if (PyObject_SetItem(__pyx_v_a, __pyx_2, __pyx_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 18; goto __pyx_L1;}
  Py_DECREF(__pyx_3); __pyx_3 = 0;
  Py_DECREF(__pyx_2); __pyx_2 = 0;

  /* "/Local/Projects/D/Pyrex/Source/Tests/10/inplace_lhs.pyx":19 */
  __pyx_1 = PyNumber_Add(__pyx_v_a, __pyx_v_b); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 19; goto __pyx_L1;}
  __pyx_3 = PyObject_GetItem(__pyx_1, __pyx_v_c); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 19; goto __pyx_L1;}
  __pyx_2 = PyNumber_InPlaceAdd(__pyx_3, __pyx_v_d); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 19; goto __pyx_L1;}
  Py_DECREF(__pyx_3); __pyx_3 = 0;
  if (PyObject_SetItem(__pyx_1, __pyx_v_c, __pyx_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 19; goto __pyx_L1;}
  Py_DECREF(__pyx_2); __pyx_2 = 0;
  Py_DECREF(__pyx_1); __pyx_1 = 0;

  /* "/Local/Projects/D/Pyrex/Source/Tests/10/inplace_lhs.pyx":20 */
  __pyx_3 = PySequence_GetSlice(__pyx_v_a, __pyx_v_i, __pyx_v_j); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 20; goto __pyx_L1;}
  __pyx_2 = PyNumber_InPlaceAdd(__pyx_3, __pyx_v_b); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 20; goto __pyx_L1;}
  Py_DECREF(__pyx_3); __pyx_3 = 0;
  if (PySequence_SetSlice(__pyx_v_a, __pyx_v_i, __pyx_v_j, __pyx_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 20; goto __pyx_L1;}
  Py_DECREF(__pyx_2); __pyx_2 = 0;

  /* "/Local/Projects/D/Pyrex/Source/Tests/10/inplace_lhs.pyx":21 */
  __pyx_1 = PyNumber_Add(__pyx_v_a, __pyx_v_b); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; goto __pyx_L1;}
  __pyx_3 = PySequence_GetSlice(__pyx_1, __pyx_v_i, __pyx_v_j); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; goto __pyx_L1;}
  __pyx_2 = PyNumber_InPlaceAdd(__pyx_3, __pyx_v_c); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; goto __pyx_L1;}
  Py_DECREF(__pyx_3); __pyx_3 = 0;
  if (PySequence_SetSlice(__pyx_1, __pyx_v_i, __pyx_v_j, __pyx_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; goto __pyx_L1;}
  Py_DECREF(__pyx_2); __pyx_2 = 0;
  Py_DECREF(__pyx_1); __pyx_1 = 0;

  /* "/Local/Projects/D/Pyrex/Source/Tests/10/inplace_lhs.pyx":22 */
  __pyx_3 = PyNumber_Add(__pyx_v_c, __pyx_v_d); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 22; goto __pyx_L1;}
  __pyx_2 = PyObject_GetAttr(__pyx_v_a, __pyx_n_b); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 22; goto __pyx_L1;}
  __pyx_1 = PyNumber_InPlaceAdd(__pyx_2, __pyx_3); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 22; goto __pyx_L1;}
  Py_DECREF(__pyx_2); __pyx_2 = 0;
  Py_DECREF(__pyx_3); __pyx_3 = 0;
  if (PyObject_SetAttr(__pyx_v_a, __pyx_n_b, __pyx_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 22; goto __pyx_L1;}
  Py_DECREF(__pyx_1); __pyx_1 = 0;

  /* "/Local/Projects/D/Pyrex/Source/Tests/10/inplace_lhs.pyx":23 */
  __pyx_2 = PyNumber_Add(__pyx_v_a, __pyx_v_b); if (!__pyx_2) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 23; goto __pyx_L1;}
  __pyx_3 = PyObject_GetAttr(__pyx_2, __pyx_n_c); if (!__pyx_3) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 23; goto __pyx_L1;}
  __pyx_1 = PyNumber_InPlaceAdd(__pyx_3, __pyx_v_d); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 23; goto __pyx_L1;}
  Py_DECREF(__pyx_3); __pyx_3 = 0;
  if (PyObject_SetAttr(__pyx_2, __pyx_n_c, __pyx_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 23; goto __pyx_L1;}
  Py_DECREF(__pyx_1); __pyx_1 = 0;
  Py_DECREF(__pyx_2); __pyx_2 = 0;

  /* "/Local/Projects/D/Pyrex/Source/Tests/10/inplace_lhs.pyx":24 */
  __pyx_v_s.q += __pyx_v_i;

  __pyx_r = 0;
  goto __pyx_L0;
  __pyx_L1:;
  Py_XDECREF(__pyx_1);
  Py_XDECREF(__pyx_2);
  Py_XDECREF(__pyx_3);
  Py_XDECREF(__pyx_4);
  __Pyx_AddTraceback("inplace_lhs.f");
  __pyx_r = (-1);
  __pyx_L0:;
  Py_DECREF(__pyx_v_a);
  Py_DECREF(__pyx_v_b);
  Py_DECREF(__pyx_v_c);
  Py_DECREF(__pyx_v_d);
  return __pyx_r;
}