cinap_lenrekadd hg and python4bb9e2215 years agoHistory
941 lines · 28.6 KB · C
RawDownload
#include "Python.h"#include "structmember.h"  #define GET_WEAKREFS_LISTPTR(o) \        ((PyWeakReference **) PyObject_GET_WEAKREFS_LISTPTR(o))  Py_ssize_t_PyWeakref_GetWeakrefCount(PyWeakReference *head){    Py_ssize_t count = 0;     while (head != NULL) {        ++count;        head = head->wr_next;    }    return count;}  static voidinit_weakref(PyWeakReference *self, PyObject *ob, PyObject *callback){    self->hash = -1;    self->wr_object = ob;    Py_XINCREF(callback);    self->wr_callback = callback;} static PyWeakReference *new_weakref(PyObject *ob, PyObject *callback){    PyWeakReference *result;     result = PyObject_GC_New(PyWeakReference, &_PyWeakref_RefType);    if (result) {        init_weakref(result, ob, callback);        PyObject_GC_Track(result);    }    return result;}  /* This function clears the passed-in reference and removes it from the * list of weak references for the referent.  This is the only code that * removes an item from the doubly-linked list of weak references for an * object; it is also responsible for clearing the callback slot. */static voidclear_weakref(PyWeakReference *self){    PyObject *callback = self->wr_callback;     if (PyWeakref_GET_OBJECT(self) != Py_None) {        PyWeakReference **list = GET_WEAKREFS_LISTPTR(            PyWeakref_GET_OBJECT(self));         if (*list == self)	    /* If 'self' is the end of the list (and thus self->wr_next == NULL)	       then the weakref list itself (and thus the value of *list) will	       end up being set to NULL. */            *list = self->wr_next;        self->wr_object = Py_None;        if (self->wr_prev != NULL)            self->wr_prev->wr_next = self->wr_next;        if (self->wr_next != NULL)            self->wr_next->wr_prev = self->wr_prev;        self->wr_prev = NULL;        self->wr_next = NULL;    }    if (callback != NULL) {        Py_DECREF(callback);        self->wr_callback = NULL;    }} /* Cyclic gc uses this to *just* clear the passed-in reference, leaving * the callback intact and uncalled.  It must be possible to call self's * tp_dealloc() after calling this, so self has to be left in a sane enough * state for that to work.  We expect tp_dealloc to decref the callback * then.  The reason for not letting clear_weakref() decref the callback * right now is that if the callback goes away, that may in turn trigger * another callback (if a weak reference to the callback exists) -- running * arbitrary Python code in the middle of gc is a disaster.  The convolution * here allows gc to delay triggering such callbacks until the world is in * a sane state again. */void_PyWeakref_ClearRef(PyWeakReference *self){    PyObject *callback;     assert(self != NULL);    assert(PyWeakref_Check(self));    /* Preserve and restore the callback around clear_weakref. */    callback = self->wr_callback;    self->wr_callback = NULL;    clear_weakref(self);    self->wr_callback = callback;} static voidweakref_dealloc(PyObject *self){    PyObject_GC_UnTrack(self);    clear_weakref((PyWeakReference *) self);    self->ob_type->tp_free(self);}  static intgc_traverse(PyWeakReference *self, visitproc visit, void *arg){    Py_VISIT(self->wr_callback);    return 0;}  static intgc_clear(PyWeakReference *self){    clear_weakref(self);    return 0;}  static PyObject *weakref_call(PyWeakReference *self, PyObject *args, PyObject *kw){    static char *kwlist[] = {NULL};     if (PyArg_ParseTupleAndKeywords(args, kw, ":__call__", kwlist)) {        PyObject *object = PyWeakref_GET_OBJECT(self);        Py_INCREF(object);        return (object);    }    return NULL;}  static longweakref_hash(PyWeakReference *self){    if (self->hash != -1)        return self->hash;    if (PyWeakref_GET_OBJECT(self) == Py_None) {        PyErr_SetString(PyExc_TypeError, "weak object has gone away");        return -1;    }    self->hash = PyObject_Hash(PyWeakref_GET_OBJECT(self));    return self->hash;}  static PyObject *weakref_repr(PyWeakReference *self){    char buffer[256];    if (PyWeakref_GET_OBJECT(self) == Py_None) {        PyOS_snprintf(buffer, sizeof(buffer), "<weakref at %p; dead>", self);    }    else {	char *name = NULL;	PyObject *nameobj = PyObject_GetAttrString(PyWeakref_GET_OBJECT(self),						   "__name__");	if (nameobj == NULL)		PyErr_Clear();	else if (PyString_Check(nameobj))		name = PyString_AS_STRING(nameobj);        PyOS_snprintf(buffer, sizeof(buffer),		      name ? "<weakref at %p; to '%.50s' at %p (%s)>"		           : "<weakref at %p; to '%.50s' at %p>",		      self,		      PyWeakref_GET_OBJECT(self)->ob_type->tp_name,		      PyWeakref_GET_OBJECT(self),		      name);	Py_XDECREF(nameobj);    }    return PyString_FromString(buffer);} /* Weak references only support equality, not ordering. Two weak references   are equal if the underlying objects are equal. If the underlying object has   gone away, they are equal if they are identical. */ static PyObject *weakref_richcompare(PyWeakReference* self, PyWeakReference* other, int op){    if (op != Py_EQ || self->ob_type != other->ob_type) {        Py_INCREF(Py_NotImplemented);        return Py_NotImplemented;    }    if (PyWeakref_GET_OBJECT(self) == Py_None        || PyWeakref_GET_OBJECT(other) == Py_None) {        PyObject *res = self==other ? Py_True : Py_False;        Py_INCREF(res);        return res;    }    return PyObject_RichCompare(PyWeakref_GET_OBJECT(self),                                PyWeakref_GET_OBJECT(other), op);} /* Given the head of an object's list of weak references, extract the * two callback-less refs (ref and proxy).  Used to determine if the * shared references exist and to determine the back link for newly * inserted references. */static voidget_basic_refs(PyWeakReference *head,               PyWeakReference **refp, PyWeakReference **proxyp){    *refp = NULL;    *proxyp = NULL;     if (head != NULL && head->wr_callback == NULL) {        /* We need to be careful that the "basic refs" aren't           subclasses of the main types.  That complicates this a           little. */        if (PyWeakref_CheckRefExact(head)) {            *refp = head;            head = head->wr_next;        }        if (head != NULL            && head->wr_callback == NULL            && PyWeakref_CheckProxy(head)) {            *proxyp = head;            /* head = head->wr_next; */        }    }} /* Insert 'newref' in the list after 'prev'.  Both must be non-NULL. */static voidinsert_after(PyWeakReference *newref, PyWeakReference *prev){    newref->wr_prev = prev;    newref->wr_next = prev->wr_next;    if (prev->wr_next != NULL)        prev->wr_next->wr_prev = newref;    prev->wr_next = newref;} /* Insert 'newref' at the head of the list; 'list' points to the variable * that stores the head. */static voidinsert_head(PyWeakReference *newref, PyWeakReference **list){    PyWeakReference *next = *list;     newref->wr_prev = NULL;    newref->wr_next = next;    if (next != NULL)        next->wr_prev = newref;    *list = newref;} static intparse_weakref_init_args(char *funcname, PyObject *args, PyObject *kwargs,                        PyObject **obp, PyObject **callbackp){    /* XXX Should check that kwargs == NULL or is empty. */    return PyArg_UnpackTuple(args, funcname, 1, 2, obp, callbackp);} static PyObject *weakref___new__(PyTypeObject *type, PyObject *args, PyObject *kwargs){    PyWeakReference *self = NULL;    PyObject *ob, *callback = NULL;     if (parse_weakref_init_args("__new__", args, kwargs, &ob, &callback)) {        PyWeakReference *ref, *proxy;        PyWeakReference **list;         if (!PyType_SUPPORTS_WEAKREFS(ob->ob_type)) {            PyErr_Format(PyExc_TypeError,                         "cannot create weak reference to '%s' object",                         ob->ob_type->tp_name);            return NULL;        }        if (callback == Py_None)            callback = NULL;        list = GET_WEAKREFS_LISTPTR(ob);        get_basic_refs(*list, &ref, &proxy);        if (callback == NULL && type == &_PyWeakref_RefType) {            if (ref != NULL) {                /* We can re-use an existing reference. */                Py_INCREF(ref);                return (PyObject *)ref;            }        }        /* We have to create a new reference. */        /* Note: the tp_alloc() can trigger cyclic GC, so the weakref           list on ob can be mutated.  This means that the ref and           proxy pointers we got back earlier may have been collected,           so we need to compute these values again before we use           them. */        self = (PyWeakReference *) (type->tp_alloc(type, 0));        if (self != NULL) {            init_weakref(self, ob, callback);            if (callback == NULL && type == &_PyWeakref_RefType) {                insert_head(self, list);            }            else {                PyWeakReference *prev;                 get_basic_refs(*list, &ref, &proxy);                prev = (proxy == NULL) ? ref : proxy;                if (prev == NULL)                    insert_head(self, list);                else                    insert_after(self, prev);            }        }    }    return (PyObject *)self;} static intweakref___init__(PyObject *self, PyObject *args, PyObject *kwargs){    PyObject *tmp;     if (parse_weakref_init_args("__init__", args, kwargs, &tmp, &tmp))        return 0;    else        return 1;}  PyTypeObject_PyWeakref_RefType = {    PyObject_HEAD_INIT(&PyType_Type)    0,    "weakref",    sizeof(PyWeakReference),    0,    weakref_dealloc,            /*tp_dealloc*/    0,	                        /*tp_print*/    0,                          /*tp_getattr*/    0,                          /*tp_setattr*/    0,	                        /*tp_compare*/    (reprfunc)weakref_repr,     /*tp_repr*/    0,                          /*tp_as_number*/    0,                          /*tp_as_sequence*/    0,                          /*tp_as_mapping*/    (hashfunc)weakref_hash,     /*tp_hash*/    (ternaryfunc)weakref_call,  /*tp_call*/    0,                          /*tp_str*/    0,                          /*tp_getattro*/    0,                          /*tp_setattro*/    0,                          /*tp_as_buffer*/    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_HAVE_RICHCOMPARE        | Py_TPFLAGS_BASETYPE,  /*tp_flags*/    0,                          /*tp_doc*/    (traverseproc)gc_traverse,  /*tp_traverse*/    (inquiry)gc_clear,          /*tp_clear*/    (richcmpfunc)weakref_richcompare,	/*tp_richcompare*/    0,                          /*tp_weaklistoffset*/    0,                          /*tp_iter*/    0,                          /*tp_iternext*/    0,                          /*tp_methods*/    0,                          /*tp_members*/    0,                          /*tp_getset*/    0,                          /*tp_base*/    0,                          /*tp_dict*/    0,                          /*tp_descr_get*/    0,                          /*tp_descr_set*/    0,                          /*tp_dictoffset*/    weakref___init__,           /*tp_init*/    PyType_GenericAlloc,        /*tp_alloc*/    weakref___new__,            /*tp_new*/    PyObject_GC_Del,            /*tp_free*/};  static intproxy_checkref(PyWeakReference *proxy){    if (PyWeakref_GET_OBJECT(proxy) == Py_None) {        PyErr_SetString(PyExc_ReferenceError,                        "weakly-referenced object no longer exists");        return 0;    }    return 1;}  /* If a parameter is a proxy, check that it is still "live" and wrap it, * replacing the original value with the raw object.  Raises ReferenceError * if the param is a dead proxy. */#define UNWRAP(o) \        if (PyWeakref_CheckProxy(o)) { \            if (!proxy_checkref((PyWeakReference *)o)) \                return NULL; \            o = PyWeakref_GET_OBJECT(o); \        } #define UNWRAP_I(o) \        if (PyWeakref_CheckProxy(o)) { \            if (!proxy_checkref((PyWeakReference *)o)) \                return -1; \            o = PyWeakref_GET_OBJECT(o); \        } #define WRAP_UNARY(method, generic) \    static PyObject * \    method(PyObject *proxy) { \        UNWRAP(proxy); \        return generic(proxy); \    } #define WRAP_BINARY(method, generic) \    static PyObject * \    method(PyObject *x, PyObject *y) { \        UNWRAP(x); \        UNWRAP(y); \        return generic(x, y); \    } /* Note that the third arg needs to be checked for NULL since the tp_call * slot can receive NULL for this arg. */#define WRAP_TERNARY(method, generic) \    static PyObject * \    method(PyObject *proxy, PyObject *v, PyObject *w) { \        UNWRAP(proxy); \        UNWRAP(v); \        if (w != NULL) \            UNWRAP(w); \        return generic(proxy, v, w); \    }  /* direct slots */ WRAP_BINARY(proxy_getattr, PyObject_GetAttr)WRAP_UNARY(proxy_str, PyObject_Str)WRAP_TERNARY(proxy_call, PyEval_CallObjectWithKeywords) static PyObject *proxy_repr(PyWeakReference *proxy){    char buf[160];    PyOS_snprintf(buf, sizeof(buf),		  "<weakproxy at %p to %.100s at %p>", proxy,		  PyWeakref_GET_OBJECT(proxy)->ob_type->tp_name,		  PyWeakref_GET_OBJECT(proxy));    return PyString_FromString(buf);}  static intproxy_setattr(PyWeakReference *proxy, PyObject *name, PyObject *value){    if (!proxy_checkref(proxy))        return -1;    return PyObject_SetAttr(PyWeakref_GET_OBJECT(proxy), name, value);} static intproxy_compare(PyObject *proxy, PyObject *v){    UNWRAP_I(proxy);    UNWRAP_I(v);    return PyObject_Compare(proxy, v);} /* number slots */WRAP_BINARY(proxy_add, PyNumber_Add)WRAP_BINARY(proxy_sub, PyNumber_Subtract)WRAP_BINARY(proxy_mul, PyNumber_Multiply)WRAP_BINARY(proxy_div, PyNumber_Divide)WRAP_BINARY(proxy_mod, PyNumber_Remainder)WRAP_BINARY(proxy_divmod, PyNumber_Divmod)WRAP_TERNARY(proxy_pow, PyNumber_Power)WRAP_UNARY(proxy_neg, PyNumber_Negative)WRAP_UNARY(proxy_pos, PyNumber_Positive)WRAP_UNARY(proxy_abs, PyNumber_Absolute)WRAP_UNARY(proxy_invert, PyNumber_Invert)WRAP_BINARY(proxy_lshift, PyNumber_Lshift)WRAP_BINARY(proxy_rshift, PyNumber_Rshift)WRAP_BINARY(proxy_and, PyNumber_And)WRAP_BINARY(proxy_xor, PyNumber_Xor)WRAP_BINARY(proxy_or, PyNumber_Or)WRAP_UNARY(proxy_int, PyNumber_Int)WRAP_UNARY(proxy_long, PyNumber_Long)WRAP_UNARY(proxy_float, PyNumber_Float)WRAP_BINARY(proxy_iadd, PyNumber_InPlaceAdd)WRAP_BINARY(proxy_isub, PyNumber_InPlaceSubtract)WRAP_BINARY(proxy_imul, PyNumber_InPlaceMultiply)WRAP_BINARY(proxy_idiv, PyNumber_InPlaceDivide)WRAP_BINARY(proxy_imod, PyNumber_InPlaceRemainder)WRAP_TERNARY(proxy_ipow, PyNumber_InPlacePower)WRAP_BINARY(proxy_ilshift, PyNumber_InPlaceLshift)WRAP_BINARY(proxy_irshift, PyNumber_InPlaceRshift)WRAP_BINARY(proxy_iand, PyNumber_InPlaceAnd)

Lines 1–500 of 941.