Coroutine.c 74.7 KB
Newer Older
1
//////////////////// GeneratorYieldFrom.proto ////////////////////
2

3
static CYTHON_INLINE PyObject* __Pyx_Generator_Yield_From(__pyx_CoroutineObject *gen, PyObject *source);
4

5
//////////////////// GeneratorYieldFrom ////////////////////
6 7
//@requires: Generator

8 9 10 11 12 13 14
static void __PyxPyIter_CheckErrorAndDecref(PyObject *source) {
    PyErr_Format(PyExc_TypeError,
                 "iter() returned non-iterator of type '%.100s'",
                 Py_TYPE(source)->tp_name);
    Py_DECREF(source);
}

15
static CYTHON_INLINE PyObject* __Pyx_Generator_Yield_From(__pyx_CoroutineObject *gen, PyObject *source) {
16
    PyObject *source_gen, *retval;
17 18 19 20 21 22 23 24 25
#ifdef __Pyx_Coroutine_USED
    if (__Pyx_Coroutine_CheckExact(source)) {
        // TODO: this should only happen for types.coroutine()ed generators, but we can't determine that here
        Py_INCREF(source);
        source_gen = source;
        retval = __Pyx_Generator_Next(source);
    } else
#endif
    {
26
#if CYTHON_USE_TYPE_SLOTS
27 28 29 30 31
        if (likely(Py_TYPE(source)->tp_iter)) {
            source_gen = Py_TYPE(source)->tp_iter(source);
            if (unlikely(!source_gen))
                return NULL;
            if (unlikely(!PyIter_Check(source_gen))) {
32
                __PyxPyIter_CheckErrorAndDecref(source_gen);
33 34
                return NULL;
            }
35
        } else
36
        // CPython also allows non-iterable sequences to be iterated over
37
#endif
38
        {
39
            source_gen = PyObject_GetIter(source);
40 41 42
            if (unlikely(!source_gen))
                return NULL;
        }
43
        // source_gen is now the iterator, make the first next() call
44
#if CYTHON_USE_TYPE_SLOTS
45
        retval = Py_TYPE(source_gen)->tp_iternext(source_gen);
46 47 48
#else
        retval = PyIter_Next(source_gen);
#endif
49
    }
50 51 52 53 54 55 56 57
    if (likely(retval)) {
        gen->yieldfrom = source_gen;
        return retval;
    }
    Py_DECREF(source_gen);
    return NULL;
}

58

59 60
//////////////////// CoroutineYieldFrom.proto ////////////////////

61
static CYTHON_INLINE PyObject* __Pyx_Coroutine_Yield_From(__pyx_CoroutineObject *gen, PyObject *source);
62 63 64 65 66

//////////////////// CoroutineYieldFrom ////////////////////
//@requires: Coroutine
//@requires: GetAwaitIter

67
static PyObject* __Pyx__Coroutine_Yield_From_Generic(__pyx_CoroutineObject *gen, PyObject *source) {
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
    PyObject *retval;
    PyObject *source_gen = __Pyx__Coroutine_GetAwaitableIter(source);
    if (unlikely(!source_gen)) {
        return NULL;
    }
    // source_gen is now the iterator, make the first next() call
    if (__Pyx_Coroutine_CheckExact(source_gen)) {
        retval = __Pyx_Generator_Next(source_gen);
    } else {
        retval = Py_TYPE(source_gen)->tp_iternext(source_gen);
    }
    if (retval) {
        gen->yieldfrom = source_gen;
        return retval;
    }
    Py_DECREF(source_gen);
    return NULL;
}

87
static CYTHON_INLINE PyObject* __Pyx_Coroutine_Yield_From(__pyx_CoroutineObject *gen, PyObject *source) {
88 89
    PyObject *retval;
    if (__Pyx_Coroutine_CheckExact(source)) {
90 91 92 93
        if (unlikely(((__pyx_CoroutineObject*)source)->yieldfrom)) {
            PyErr_SetString(
                PyExc_RuntimeError,
                "coroutine is being awaited already");
Stefan Behnel's avatar
Stefan Behnel committed
94
            return NULL;
95
        }
Stefan Behnel's avatar
Stefan Behnel committed
96
        retval = __Pyx_Generator_Next(source);
97
#ifdef __Pyx_AsyncGen_USED
Stefan Behnel's avatar
Stefan Behnel committed
98
    // inlined "__pyx_PyAsyncGenASend" handling to avoid the series of generic calls
99
    } else if (__pyx_PyAsyncGenASend_CheckExact(source)) {
100
        retval = __Pyx_async_gen_asend_iternext(source);
101
#endif
102
    } else {
103
        return __Pyx__Coroutine_Yield_From_Generic(gen, source);
104
    }
Stefan Behnel's avatar
Stefan Behnel committed
105 106 107 108 109
    if (retval) {
        Py_INCREF(source);
        gen->yieldfrom = source;
    }
    return retval;
110 111 112
}


113 114 115 116 117 118 119 120 121 122 123 124 125
//////////////////// GetAwaitIter.proto ////////////////////

static CYTHON_INLINE PyObject *__Pyx_Coroutine_GetAwaitableIter(PyObject *o); /*proto*/
static PyObject *__Pyx__Coroutine_GetAwaitableIter(PyObject *o); /*proto*/

//////////////////// GetAwaitIter ////////////////////
//@requires: ObjectHandling.c::PyObjectGetAttrStr
//@requires: ObjectHandling.c::PyObjectCallNoArg
//@requires: ObjectHandling.c::PyObjectCallOneArg

static CYTHON_INLINE PyObject *__Pyx_Coroutine_GetAwaitableIter(PyObject *o) {
#ifdef __Pyx_Coroutine_USED
    if (__Pyx_Coroutine_CheckExact(o)) {
126
        return __Pyx_NewRef(o);
127 128 129 130 131
    }
#endif
    return __Pyx__Coroutine_GetAwaitableIter(o);
}

132

Stefan Behnel's avatar
Stefan Behnel committed
133
static void __Pyx_Coroutine_AwaitableIterError(PyObject *source) {
134
#if PY_VERSION_HEX >= 0x030600B3 || defined(_PyErr_FormatFromCause)
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
    _PyErr_FormatFromCause(
        PyExc_TypeError,
        "'async for' received an invalid object "
        "from __anext__: %.100s",
        Py_TYPE(source)->tp_name);
#elif PY_MAJOR_VERSION >= 3
    PyObject *exc, *val, *val2, *tb;
    assert(PyErr_Occurred());
    PyErr_Fetch(&exc, &val, &tb);
    PyErr_NormalizeException(&exc, &val, &tb);
    if (tb != NULL) {
        PyException_SetTraceback(val, tb);
        Py_DECREF(tb);
    }
    Py_DECREF(exc);
    assert(!PyErr_Occurred());
    PyErr_Format(
        PyExc_TypeError,
        "'async for' received an invalid object "
        "from __anext__: %.100s",
        Py_TYPE(source)->tp_name);

    PyErr_Fetch(&exc, &val2, &tb);
    PyErr_NormalizeException(&exc, &val2, &tb);
    Py_INCREF(val);
    PyException_SetCause(val2, val);
    PyException_SetContext(val2, val);
    PyErr_Restore(exc, val2, tb);
#else
    // since Py2 does not have exception chaining, it's better to avoid shadowing exceptions there
    source++;
#endif
}

169 170
// adapted from genobject.c in Py3.5
static PyObject *__Pyx__Coroutine_GetAwaitableIter(PyObject *obj) {
171
    PyObject *res;
172
#if CYTHON_USE_ASYNC_SLOTS
173
    __Pyx_PyAsyncMethodsStruct* am = __Pyx_PyType_AsAsync(obj);
174 175
    if (likely(am && am->am_await)) {
        res = (*am->am_await)(obj);
176
    } else
177
#endif
178
#if PY_VERSION_HEX >= 0x030500B2 || defined(PyCoro_CheckExact)
179
    if (PyCoro_CheckExact(obj)) {
Stefan Behnel's avatar
Stefan Behnel committed
180
        return __Pyx_NewRef(obj);
181 182 183 184 185
    } else
#endif
#if CYTHON_COMPILING_IN_CPYTHON && defined(CO_ITERABLE_COROUTINE)
    if (PyGen_CheckExact(obj) && ((PyGenObject*)obj)->gi_code && ((PyCodeObject *)((PyGenObject*)obj)->gi_code)->co_flags & CO_ITERABLE_COROUTINE) {
        // Python generator marked with "@types.coroutine" decorator
Stefan Behnel's avatar
Stefan Behnel committed
186
        return __Pyx_NewRef(obj);
187
    } else
188 189 190 191
#endif
    {
        PyObject *method = __Pyx_PyObject_GetAttrStr(obj, PYIDENT("__await__"));
        if (unlikely(!method)) goto slot_error;
192
        #if CYTHON_UNPACK_METHODS
193 194 195 196 197 198 199
        if (likely(PyMethod_Check(method))) {
            PyObject *self = PyMethod_GET_SELF(method);
            if (likely(self)) {
                PyObject *function = PyMethod_GET_FUNCTION(method);
                res = __Pyx_PyObject_CallOneArg(function, self);
            } else
                res = __Pyx_PyObject_CallNoArg(method);
200
        } else
201
        #endif
202
            res = __Pyx_PyObject_CallNoArg(method);
203 204
        Py_DECREF(method);
    }
205 206
    if (unlikely(!res)) {
        // surprisingly, CPython replaces the exception here...
Stefan Behnel's avatar
Stefan Behnel committed
207
        __Pyx_Coroutine_AwaitableIterError(obj);
208 209
        goto bad;
    }
Stefan Behnel's avatar
Stefan Behnel committed
210
    if (unlikely(!PyIter_Check(res))) {
211 212 213 214 215 216 217 218 219
        PyErr_Format(PyExc_TypeError,
                     "__await__() returned non-iterator of type '%.100s'",
                     Py_TYPE(res)->tp_name);
        Py_CLEAR(res);
    } else {
        int is_coroutine = 0;
        #ifdef __Pyx_Coroutine_USED
        is_coroutine |= __Pyx_Coroutine_CheckExact(res);
        #endif
220
        #if PY_VERSION_HEX >= 0x030500B2 || defined(PyCoro_CheckExact)
221
        is_coroutine |= PyCoro_CheckExact(res);
222 223 224 225 226 227 228 229 230 231 232 233 234
        #endif
        if (unlikely(is_coroutine)) {
            /* __await__ must return an *iterator*, not
               a coroutine or another awaitable (see PEP 492) */
            PyErr_SetString(PyExc_TypeError,
                            "__await__() returned a coroutine");
            Py_CLEAR(res);
        }
    }
    return res;
slot_error:
    PyErr_Format(PyExc_TypeError,
                 "object %.100s can't be used in 'await' expression",
235
                 Py_TYPE(obj)->tp_name);
236 237 238 239 240
bad:
    return NULL;
}


241 242 243 244 245 246 247 248 249
//////////////////// AsyncIter.proto ////////////////////

static CYTHON_INLINE PyObject *__Pyx_Coroutine_GetAsyncIter(PyObject *o); /*proto*/
static CYTHON_INLINE PyObject *__Pyx_Coroutine_AsyncIterNext(PyObject *o); /*proto*/

//////////////////// AsyncIter ////////////////////
//@requires: GetAwaitIter
//@requires: ObjectHandling.c::PyObjectCallMethod0

Stefan Behnel's avatar
Stefan Behnel committed
250
static PyObject *__Pyx_Coroutine_GetAsyncIter_Generic(PyObject *obj) {
251 252 253 254 255 256
#if PY_VERSION_HEX < 0x030500B1
    {
        PyObject *iter = __Pyx_PyObject_CallMethod0(obj, PYIDENT("__aiter__"));
        if (likely(iter))
            return iter;
        // FIXME: for the sake of a nicely conforming exception message, assume any AttributeError meant '__aiter__'
257
        if (!PyErr_ExceptionMatches(PyExc_AttributeError))
258 259
            return NULL;
    }
260
#else
261
    // avoid C warning about 'unused function'
262
    if ((0)) (void) __Pyx_PyObject_CallMethod0(obj, PYIDENT("__aiter__"));
263 264 265 266 267 268 269
#endif

    PyErr_Format(PyExc_TypeError, "'async for' requires an object with __aiter__ method, got %.100s",
                 Py_TYPE(obj)->tp_name);
    return NULL;
}

270

Stefan Behnel's avatar
Stefan Behnel committed
271
static CYTHON_INLINE PyObject *__Pyx_Coroutine_GetAsyncIter(PyObject *obj) {
272 273
#ifdef __Pyx_AsyncGen_USED
    if (__Pyx_AsyncGen_CheckExact(obj)) {
Stefan Behnel's avatar
Stefan Behnel committed
274
        return __Pyx_NewRef(obj);
275 276
    }
#endif
277
#if CYTHON_USE_ASYNC_SLOTS
278 279
    {
        __Pyx_PyAsyncMethodsStruct* am = __Pyx_PyType_AsAsync(obj);
Stefan Behnel's avatar
Stefan Behnel committed
280 281
        if (likely(am && am->am_aiter)) {
            return (*am->am_aiter)(obj);
282
        }
283 284
    }
#endif
Stefan Behnel's avatar
Stefan Behnel committed
285 286 287 288 289
    return __Pyx_Coroutine_GetAsyncIter_Generic(obj);
}


static PyObject *__Pyx__Coroutine_AsyncIterNext(PyObject *obj) {
290 291 292 293 294 295
#if PY_VERSION_HEX < 0x030500B1
    {
        PyObject *value = __Pyx_PyObject_CallMethod0(obj, PYIDENT("__anext__"));
        if (likely(value))
            return value;
    }
296
    // FIXME: for the sake of a nicely conforming exception message, assume any AttributeError meant '__anext__'
297
    if (PyErr_ExceptionMatches(PyExc_AttributeError))
298 299 300 301 302 303 304
#endif
        PyErr_Format(PyExc_TypeError, "'async for' requires an object with __anext__ method, got %.100s",
                     Py_TYPE(obj)->tp_name);
    return NULL;
}


Stefan Behnel's avatar
Stefan Behnel committed
305 306 307
static CYTHON_INLINE PyObject *__Pyx_Coroutine_AsyncIterNext(PyObject *obj) {
#ifdef __Pyx_AsyncGen_USED
    if (__Pyx_AsyncGen_CheckExact(obj)) {
308
        return __Pyx_async_gen_anext(obj);
Stefan Behnel's avatar
Stefan Behnel committed
309 310 311 312 313 314 315 316 317 318 319 320 321 322
    }
#endif
#if CYTHON_USE_ASYNC_SLOTS
    {
        __Pyx_PyAsyncMethodsStruct* am = __Pyx_PyType_AsAsync(obj);
        if (likely(am && am->am_anext)) {
            return (*am->am_anext)(obj);
        }
    }
#endif
    return __Pyx__Coroutine_AsyncIterNext(obj);
}


323 324
//////////////////// pep479.proto ////////////////////

325
static void __Pyx_Generator_Replace_StopIteration(int in_async_gen); /*proto*/
326 327 328 329

//////////////////// pep479 ////////////////////
//@requires: Exceptions.c::GetException

330 331
static void __Pyx_Generator_Replace_StopIteration(CYTHON_UNUSED int in_async_gen) {
    PyObject *exc, *val, *tb, *cur_exc;
332
    __Pyx_PyThreadState_declare
333 334 335 336 337
    #ifdef __Pyx_StopAsyncIteration_USED
    int is_async_stopiteration = 0;
    #endif

    cur_exc = PyErr_Occurred();
338
    if (likely(!__Pyx_PyErr_GivenExceptionMatches(cur_exc, PyExc_StopIteration))) {
339
        #ifdef __Pyx_StopAsyncIteration_USED
340
        if (in_async_gen && unlikely(__Pyx_PyErr_GivenExceptionMatches(cur_exc, __Pyx_PyExc_StopAsyncIteration))) {
341 342 343 344 345 346
            is_async_stopiteration = 1;
        } else
        #endif
            return;
    }

347
    __Pyx_PyThreadState_assign
348 349
    // Chain exceptions by moving Stop(Async)Iteration to exc_info before creating the RuntimeError.
    // In Py2.x, no chaining happens, but the exception still stays visible in exc_info.
350 351 352 353
    __Pyx_GetException(&exc, &val, &tb);
    Py_XDECREF(exc);
    Py_XDECREF(val);
    Py_XDECREF(tb);
354 355 356 357 358 359
    PyErr_SetString(PyExc_RuntimeError,
        #ifdef __Pyx_StopAsyncIteration_USED
        is_async_stopiteration ? "async generator raised StopAsyncIteration" :
        in_async_gen ? "async generator raised StopIteration" :
        #endif
        "generator raised StopIteration");
360 361 362
}


363
//////////////////// CoroutineBase.proto ////////////////////
364
//@substitute: naming
365

366
typedef PyObject *(*__pyx_coroutine_body_t)(PyObject *, PyThreadState *, PyObject *);
367 368 369

typedef struct {
    PyObject_HEAD
370
    __pyx_coroutine_body_t body;
371 372 373 374 375 376
    PyObject *closure;
    PyObject *exc_type;
    PyObject *exc_value;
    PyObject *exc_traceback;
    PyObject *gi_weakreflist;
    PyObject *classobj;
377
    PyObject *yieldfrom;
378 379
    PyObject *gi_name;
    PyObject *gi_qualname;
380
    PyObject *gi_modulename;
381
    int resume_label;
382 383
    // using T_BOOL for property below requires char value
    char is_running;
384
} __pyx_CoroutineObject;
385

386 387 388
static __pyx_CoroutineObject *__Pyx__Coroutine_New(
    PyTypeObject *type, __pyx_coroutine_body_t body, PyObject *closure,
    PyObject *name, PyObject *qualname, PyObject *module_name); /*proto*/
389 390 391 392 393

static __pyx_CoroutineObject *__Pyx__Coroutine_NewInit(
            __pyx_CoroutineObject *gen, __pyx_coroutine_body_t body, PyObject *closure,
            PyObject *name, PyObject *qualname, PyObject *module_name); /*proto*/

394
static int __Pyx_Coroutine_clear(PyObject *self); /*proto*/
395 396 397
static PyObject *__Pyx_Coroutine_Send(PyObject *self, PyObject *value); /*proto*/
static PyObject *__Pyx_Coroutine_Close(PyObject *self); /*proto*/
static PyObject *__Pyx_Coroutine_Throw(PyObject *gen, PyObject *args); /*proto*/
398

399 400 401 402 403 404 405 406 407 408
// macros for exception state swapping instead of inline functions to make use of the local thread state context
#define __Pyx_Coroutine_SwapException(self) { \
    __Pyx_ExceptionSwap(&(self)->exc_type, &(self)->exc_value, &(self)->exc_traceback); \
    __Pyx_Coroutine_ResetFrameBackpointer(self); \
    }
#define __Pyx_Coroutine_ResetAndClearException(self) { \
    __Pyx_ExceptionReset((self)->exc_type, (self)->exc_value, (self)->exc_traceback); \
    (self)->exc_type = (self)->exc_value = (self)->exc_traceback = NULL; \
    }

409 410 411
#if CYTHON_FAST_THREAD_STATE
#define __Pyx_PyGen_FetchStopIterationValue(pvalue) \
    __Pyx_PyGen__FetchStopIterationValue($local_tstate_cname, pvalue)
412
#else
413 414
#define __Pyx_PyGen_FetchStopIterationValue(pvalue) \
    __Pyx_PyGen__FetchStopIterationValue(__Pyx_PyThreadState_Current, pvalue)
415
#endif
416
static int __Pyx_PyGen__FetchStopIterationValue(PyThreadState *tstate, PyObject **pvalue); /*proto*/
417
static CYTHON_INLINE void __Pyx_Coroutine_ResetFrameBackpointer(__pyx_CoroutineObject *self); /*proto*/
418

419 420 421 422 423

//////////////////// Coroutine.proto ////////////////////

#define __Pyx_Coroutine_USED
static PyTypeObject *__pyx_CoroutineType = 0;
424
static PyTypeObject *__pyx_CoroutineAwaitType = 0;
425
#define __Pyx_Coroutine_CheckExact(obj) (Py_TYPE(obj) == __pyx_CoroutineType)
426
#define __Pyx_CoroutineAwait_CheckExact(obj) (Py_TYPE(obj) == __pyx_CoroutineAwaitType)
427

428 429
#define __Pyx_Coroutine_New(body, closure, name, qualname, module_name)  \
    __Pyx__Coroutine_New(__pyx_CoroutineType, body, closure, name, qualname, module_name)
430

Stefan Behnel's avatar
Stefan Behnel committed
431
static int __pyx_Coroutine_init(void); /*proto*/
432
static PyObject *__Pyx__Coroutine_await(PyObject *coroutine); /*proto*/
433

434 435 436 437 438 439 440 441
typedef struct {
    PyObject_HEAD
    PyObject *coroutine;
} __pyx_CoroutineAwaitObject;

static PyObject *__Pyx_CoroutineAwait_Close(__pyx_CoroutineAwaitObject *self); /*proto*/
static PyObject *__Pyx_CoroutineAwait_Throw(__pyx_CoroutineAwaitObject *self, PyObject *args); /*proto*/

442 443 444 445 446 447 448

//////////////////// Generator.proto ////////////////////

#define __Pyx_Generator_USED
static PyTypeObject *__pyx_GeneratorType = 0;
#define __Pyx_Generator_CheckExact(obj) (Py_TYPE(obj) == __pyx_GeneratorType)

449 450
#define __Pyx_Generator_New(body, closure, name, qualname, module_name)  \
    __Pyx__Coroutine_New(__pyx_GeneratorType, body, closure, name, qualname, module_name)
451

452
static PyObject *__Pyx_Generator_Next(PyObject *self);
Stefan Behnel's avatar
Stefan Behnel committed
453
static int __pyx_Generator_init(void); /*proto*/
454 455


456 457 458 459 460
//////////////////// AsyncGen ////////////////////
//@requires: AsyncGen.c::AsyncGenerator
// -> empty, only delegates to separate file


461
//////////////////// CoroutineBase ////////////////////
462
//@substitute: naming
463
//@requires: Exceptions.c::PyErrFetchRestore
464
//@requires: Exceptions.c::PyThreadStateGet
465 466
//@requires: Exceptions.c::SwapException
//@requires: Exceptions.c::RaiseException
467
//@requires: Exceptions.c::SaveResetException
468
//@requires: ObjectHandling.c::PyObjectCallMethod1
469
//@requires: ObjectHandling.c::PyObjectGetAttrStr
470
//@requires: CommonStructures.c::FetchCommonType
471

472 473
#include <structmember.h>
#include <frameobject.h>
474

475
#define __Pyx_Coroutine_Undelegate(gen) Py_CLEAR((gen)->yieldfrom)
476 477 478 479 480 481 482

//   If StopIteration exception is set, fetches its 'value'
//   attribute if any, otherwise sets pvalue to None.
//
//   Returns 0 if no exception or StopIteration is set.
//   If any other exception is set, returns -1 and leaves
//   pvalue unchanged.
483
static int __Pyx_PyGen__FetchStopIterationValue(CYTHON_UNUSED PyThreadState *$local_tstate_cname, PyObject **pvalue) {
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
    PyObject *et, *ev, *tb;
    PyObject *value = NULL;

    __Pyx_ErrFetch(&et, &ev, &tb);

    if (!et) {
        Py_XDECREF(tb);
        Py_XDECREF(ev);
        Py_INCREF(Py_None);
        *pvalue = Py_None;
        return 0;
    }

    // most common case: plain StopIteration without or with separate argument
    if (likely(et == PyExc_StopIteration)) {
499 500 501 502
        if (!ev) {
            Py_INCREF(Py_None);
            value = Py_None;
        }
503
#if PY_VERSION_HEX >= 0x030300A0
504
        else if (Py_TYPE(ev) == (PyTypeObject*)PyExc_StopIteration) {
505 506 507 508 509
            value = ((PyStopIterationObject *)ev)->value;
            Py_INCREF(value);
            Py_DECREF(ev);
        }
#endif
510 511 512 513
        // PyErr_SetObject() and friends put the value directly into ev
        else if (unlikely(PyTuple_Check(ev))) {
            // if it's a tuple, it is interpreted as separate constructor arguments (surprise!)
            if (PyTuple_GET_SIZE(ev) >= 1) {
514
#if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS
515 516
                value = PyTuple_GET_ITEM(ev, 0);
                Py_INCREF(value);
517 518
#else
                value = PySequence_ITEM(ev, 0);
519
#endif
520 521 522
            } else {
                Py_INCREF(Py_None);
                value = Py_None;
523
            }
524 525
            Py_DECREF(ev);
        }
526
        else if (!__Pyx_TypeCheck(ev, (PyTypeObject*)PyExc_StopIteration)) {
527 528 529 530
            // 'steal' reference to ev
            value = ev;
        }
        if (likely(value)) {
531 532
            Py_XDECREF(tb);
            Py_DECREF(et);
533
            *pvalue = value;
534 535
            return 0;
        }
536
    } else if (!__Pyx_PyErr_GivenExceptionMatches(et, PyExc_StopIteration)) {
537 538
        __Pyx_ErrRestore(et, ev, tb);
        return -1;
539
    }
540

541 542
    // otherwise: normalise and check what that gives us
    PyErr_NormalizeException(&et, &ev, &tb);
543
    if (unlikely(!PyObject_TypeCheck(ev, (PyTypeObject*)PyExc_StopIteration))) {
544 545 546 547 548 549 550 551 552 553 554 555
        // looks like normalisation failed - raise the new exception
        __Pyx_ErrRestore(et, ev, tb);
        return -1;
    }
    Py_XDECREF(tb);
    Py_DECREF(et);
#if PY_VERSION_HEX >= 0x030300A0
    value = ((PyStopIterationObject *)ev)->value;
    Py_INCREF(value);
    Py_DECREF(ev);
#else
    {
556
        PyObject* args = __Pyx_PyObject_GetAttrStr(ev, PYIDENT("args"));
557 558
        Py_DECREF(ev);
        if (likely(args)) {
559
            value = PySequence_GetItem(args, 0);
560 561 562 563 564 565 566 567 568 569 570 571 572
            Py_DECREF(args);
        }
        if (unlikely(!value)) {
            __Pyx_ErrRestore(NULL, NULL, NULL);
            Py_INCREF(Py_None);
            value = Py_None;
        }
    }
#endif
    *pvalue = value;
    return 0;
}

573
static CYTHON_INLINE
574
void __Pyx_Coroutine_ExceptionClear(__pyx_CoroutineObject *self) {
575 576 577
    PyObject *exc_type = self->exc_type;
    PyObject *exc_value = self->exc_value;
    PyObject *exc_traceback = self->exc_traceback;
578 579 580 581

    self->exc_type = NULL;
    self->exc_value = NULL;
    self->exc_traceback = NULL;
582 583 584 585

    Py_XDECREF(exc_type);
    Py_XDECREF(exc_value);
    Py_XDECREF(exc_traceback);
586 587
}

Stefan Behnel's avatar
Stefan Behnel committed
588
#define __Pyx_Coroutine_AlreadyRunningError(gen)  (__Pyx__Coroutine_AlreadyRunningError(gen), (PyObject*)NULL)
589
static void __Pyx__Coroutine_AlreadyRunningError(CYTHON_UNUSED __pyx_CoroutineObject *gen) {
Stefan Behnel's avatar
Stefan Behnel committed
590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606
    const char *msg;
    if (0) {
    #ifdef __Pyx_Coroutine_USED
    } else if (__Pyx_Coroutine_CheckExact((PyObject*)gen)) {
        msg = "coroutine already executing";
    #endif
    #ifdef __Pyx_AsyncGen_USED
    } else if (__Pyx_AsyncGen_CheckExact((PyObject*)gen)) {
        msg = "async generator already executing";
    #endif
    } else {
        msg = "generator already executing";
    }
    PyErr_SetString(PyExc_ValueError, msg);
}

#define __Pyx_Coroutine_NotStartedError(gen)  (__Pyx__Coroutine_NotStartedError(gen), (PyObject*)NULL)
Stefan Behnel's avatar
Stefan Behnel committed
607
static void __Pyx__Coroutine_NotStartedError(CYTHON_UNUSED PyObject *gen) {
Stefan Behnel's avatar
Stefan Behnel committed
608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624
    const char *msg;
    if (0) {
    #ifdef __Pyx_Coroutine_USED
    } else if (__Pyx_Coroutine_CheckExact(gen)) {
        msg = "can't send non-None value to a just-started coroutine";
    #endif
    #ifdef __Pyx_AsyncGen_USED
    } else if (__Pyx_AsyncGen_CheckExact(gen)) {
        msg = "can't send non-None value to a just-started async generator";
    #endif
    } else {
        msg = "can't send non-None value to a just-started generator";
    }
    PyErr_SetString(PyExc_TypeError, msg);
}

#define __Pyx_Coroutine_AlreadyTerminatedError(gen, value, closing)  (__Pyx__Coroutine_AlreadyTerminatedError(gen, value, closing), (PyObject*)NULL)
Stefan Behnel's avatar
Stefan Behnel committed
625
static void __Pyx__Coroutine_AlreadyTerminatedError(CYTHON_UNUSED PyObject *gen, PyObject *value, CYTHON_UNUSED int closing) {
Stefan Behnel's avatar
Stefan Behnel committed
626 627 628 629 630 631 632 633 634 635 636
    #ifdef __Pyx_Coroutine_USED
    if (!closing && __Pyx_Coroutine_CheckExact(gen)) {
        // `self` is an exhausted coroutine: raise an error,
        // except when called from gen_close(), which should
        // always be a silent method.
        PyErr_SetString(PyExc_RuntimeError, "cannot reuse already awaited coroutine");
    } else
    #endif
    if (value) {
        // `gen` is an exhausted generator:
        // only set exception if called from send().
637
        #ifdef __Pyx_AsyncGen_USED
Stefan Behnel's avatar
Stefan Behnel committed
638 639 640
        if (__Pyx_AsyncGen_CheckExact(gen))
            PyErr_SetNone(__Pyx_PyExc_StopAsyncIteration);
        else
641
        #endif
Stefan Behnel's avatar
Stefan Behnel committed
642
        PyErr_SetNone(PyExc_StopIteration);
643
    }
644 645
}

Stefan Behnel's avatar
Stefan Behnel committed
646 647
static
PyObject *__Pyx_Coroutine_SendEx(__pyx_CoroutineObject *self, PyObject *value, int closing) {
648
    __Pyx_PyThreadState_declare
649
    PyThreadState *tstate;
650
    PyObject *retval;
651 652

    assert(!self->is_running);
653

654 655
    if (unlikely(self->resume_label == 0)) {
        if (unlikely(value && value != Py_None)) {
Stefan Behnel's avatar
Stefan Behnel committed
656
            return __Pyx_Coroutine_NotStartedError((PyObject*)self);
657 658 659
        }
    }

660
    if (unlikely(self->resume_label == -1)) {
Stefan Behnel's avatar
Stefan Behnel committed
661
        return __Pyx_Coroutine_AlreadyTerminatedError((PyObject*)self, value, closing);
662 663
    }

664
#if CYTHON_FAST_THREAD_STATE
665
    __Pyx_PyThreadState_assign
666 667 668 669 670
    tstate = $local_tstate_cname;
#else
    tstate = __Pyx_PyThreadState_Current;
#endif

671 672 673 674 675 676 677 678
    // Traceback/Frame rules:
    // - on entry, save external exception state in self->exc_*, restore it on exit
    // - on exit, keep internally generated exceptions in self->exc_*, clear everything else
    // - on entry, set "f_back" pointer of internal exception traceback to (current) outer call frame
    // - on exit, clear "f_back" of internal exception traceback
    // - do not touch external frames and tracebacks

    if (self->exc_type) {
Boxiang Sun's avatar
Boxiang Sun committed
679
#if CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_PYSTON
680 681
        // FIXME: what to do in PyPy?
#else
682 683
        // Generators always return to their most recent caller, not
        // necessarily their creator.
684 685 686 687
        if (self->exc_traceback) {
            PyTracebackObject *tb = (PyTracebackObject *) self->exc_traceback;
            PyFrameObject *f = tb->tb_frame;

688
            Py_XINCREF(tstate->frame);
689
            assert(f->f_back == NULL);
690
            f->f_back = tstate->frame;
691
        }
692
#endif
693 694
        // We were in an except handler when we left,
        // restore the exception state which was put aside.
695 696
        __Pyx_ExceptionSwap(&self->exc_type, &self->exc_value,
                            &self->exc_traceback);
697
        // self->exc_* now holds the exception state of the caller
698
    } else {
699
        // save away the exception state of the caller
700
        __Pyx_Coroutine_ExceptionClear(self);
701
        __Pyx_ExceptionSave(&self->exc_type, &self->exc_value, &self->exc_traceback);
702
    }
703 704

    self->is_running = 1;
705
    retval = self->body((PyObject *) self, tstate, value);
706 707
    self->is_running = 0;

708 709 710
    return retval;
}

711
static CYTHON_INLINE void __Pyx_Coroutine_ResetFrameBackpointer(__pyx_CoroutineObject *self) {
712 713 714
    // Don't keep the reference to f_back any longer than necessary.  It
    // may keep a chain of frames alive or it could create a reference
    // cycle.
715
    if (likely(self->exc_traceback)) {
716 717 718
#if CYTHON_COMPILING_IN_PYPY || CYTHON_COMPILING_IN_PYSTON
    // FIXME: what to do in PyPy?
#else
719 720
        PyTracebackObject *tb = (PyTracebackObject *) self->exc_traceback;
        PyFrameObject *f = tb->tb_frame;
721
        Py_CLEAR(f->f_back);
722
#endif
723
    }
724 725
}

726
static CYTHON_INLINE
727
PyObject *__Pyx_Coroutine_MethodReturn(CYTHON_UNUSED PyObject* gen, PyObject *retval) {
728 729 730 731 732 733 734 735 736 737 738 739
    if (unlikely(!retval)) {
        __Pyx_PyThreadState_declare
        __Pyx_PyThreadState_assign
        if (!__Pyx_PyErr_Occurred()) {
            // method call must not terminate with NULL without setting an exception
            PyObject *exc = PyExc_StopIteration;
            #ifdef __Pyx_AsyncGen_USED
            if (__Pyx_AsyncGen_CheckExact(gen))
                exc = __Pyx_PyExc_StopAsyncIteration;
            #endif
            __Pyx_PyErr_SetNone(exc);
        }
740 741 742 743
    }
    return retval;
}

744
static CYTHON_INLINE
745
PyObject *__Pyx_Coroutine_FinishDelegation(__pyx_CoroutineObject *gen) {
746 747
    PyObject *ret;
    PyObject *val = NULL;
748
    __Pyx_Coroutine_Undelegate(gen);
749
    __Pyx_PyGen__FetchStopIterationValue(__Pyx_PyThreadState_Current, &val);
750
    // val == NULL on failure => pass on exception
751
    ret = __Pyx_Coroutine_SendEx(gen, val, 0);
752 753
    Py_XDECREF(val);
    return ret;
754 755
}

756
static PyObject *__Pyx_Coroutine_Send(PyObject *self, PyObject *value) {
757
    PyObject *retval;
758
    __pyx_CoroutineObject *gen = (__pyx_CoroutineObject*) self;
759
    PyObject *yf = gen->yieldfrom;
Stefan Behnel's avatar
Stefan Behnel committed
760 761
    if (unlikely(gen->is_running))
        return __Pyx_Coroutine_AlreadyRunningError(gen);
762 763 764 765 766
    if (yf) {
        PyObject *ret;
        // FIXME: does this really need an INCREF() ?
        //Py_INCREF(yf);
        gen->is_running = 1;
767
        #ifdef __Pyx_Generator_USED
768
        if (__Pyx_Generator_CheckExact(yf)) {
769 770 771 772 773 774 775 776
            ret = __Pyx_Coroutine_Send(yf, value);
        } else
        #endif
        #ifdef __Pyx_Coroutine_USED
        if (__Pyx_Coroutine_CheckExact(yf)) {
            ret = __Pyx_Coroutine_Send(yf, value);
        } else
        #endif
777 778
        #ifdef __Pyx_AsyncGen_USED
        if (__pyx_PyAsyncGenASend_CheckExact(yf)) {
779
            ret = __Pyx_async_gen_asend_send(yf, value);
780 781
        } else
        #endif
782 783 784 785 786
        #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x03030000
        if (PyGen_CheckExact(yf)) {
            ret = _PyGen_Send((PyGenObject*)yf, value == Py_None ? NULL : value);
        } else
        #endif
787 788 789 790 791
        #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x03050000 && defined(PyCoro_CheckExact)
        if (PyCoro_CheckExact(yf)) {
            ret = _PyGen_Send((PyGenObject*)yf, value == Py_None ? NULL : value);
        } else
        #endif
792
        {
793
            if (value == Py_None)
794
                ret = Py_TYPE(yf)->tp_iternext(yf);
795
            else
796
                ret = __Pyx_PyObject_CallMethod1(yf, PYIDENT("send"), value);
797 798 799 800 801 802
        }
        gen->is_running = 0;
        //Py_DECREF(yf);
        if (likely(ret)) {
            return ret;
        }
803
        retval = __Pyx_Coroutine_FinishDelegation(gen);
804
    } else {
805
        retval = __Pyx_Coroutine_SendEx(gen, value, 0);
806
    }
807
    return __Pyx_Coroutine_MethodReturn(self, retval);
808 809 810 811
}

//   This helper function is used by gen_close and gen_throw to
//   close a subiterator being delegated to by yield-from.
812
static int __Pyx_Coroutine_CloseIter(__pyx_CoroutineObject *gen, PyObject *yf) {
813 814 815
    PyObject *retval = NULL;
    int err = 0;

816
    #ifdef __Pyx_Generator_USED
817
    if (__Pyx_Generator_CheckExact(yf)) {
818
        retval = __Pyx_Coroutine_Close(yf);
819 820
        if (!retval)
            return -1;
821 822 823 824 825 826 827 828
    } else
    #endif
    #ifdef __Pyx_Coroutine_USED
    if (__Pyx_Coroutine_CheckExact(yf)) {
        retval = __Pyx_Coroutine_Close(yf);
        if (!retval)
            return -1;
    } else
829 830 831 832 833 834 835 836 837 838 839 840 841 842 843
    if (__Pyx_CoroutineAwait_CheckExact(yf)) {
        retval = __Pyx_CoroutineAwait_Close((__pyx_CoroutineAwaitObject*)yf);
        if (!retval)
            return -1;
    } else
    #endif
    #ifdef __Pyx_AsyncGen_USED
    if (__pyx_PyAsyncGenASend_CheckExact(yf)) {
        retval = __Pyx_async_gen_asend_close(yf, NULL);
        // cannot fail
    } else
    if (__pyx_PyAsyncGenAThrow_CheckExact(yf)) {
        retval = __Pyx_async_gen_athrow_close(yf, NULL);
        // cannot fail
    } else
844 845
    #endif
    {
846 847
        PyObject *meth;
        gen->is_running = 1;
848
        meth = __Pyx_PyObject_GetAttrStr(yf, PYIDENT("close"));
849
        if (unlikely(!meth)) {
850
            if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
851 852 853 854
                PyErr_WriteUnraisable(yf);
            }
            PyErr_Clear();
        } else {
855
            retval = PyObject_CallFunction(meth, NULL);
856 857 858 859 860 861 862 863 864 865
            Py_DECREF(meth);
            if (!retval)
                err = -1;
        }
        gen->is_running = 0;
    }
    Py_XDECREF(retval);
    return err;
}

866 867 868
static PyObject *__Pyx_Generator_Next(PyObject *self) {
    __pyx_CoroutineObject *gen = (__pyx_CoroutineObject*) self;
    PyObject *yf = gen->yieldfrom;
Stefan Behnel's avatar
Stefan Behnel committed
869 870
    if (unlikely(gen->is_running))
        return __Pyx_Coroutine_AlreadyRunningError(gen);
871 872 873 874 875 876
    if (yf) {
        PyObject *ret;
        // FIXME: does this really need an INCREF() ?
        //Py_INCREF(yf);
        // YieldFrom code ensures that yf is an iterator
        gen->is_running = 1;
877 878 879 880
        #ifdef __Pyx_Generator_USED
        if (__Pyx_Generator_CheckExact(yf)) {
            ret = __Pyx_Generator_Next(yf);
        } else
881 882 883 884 885
        #endif
        #if CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x03030000
        if (PyGen_CheckExact(yf)) {
            ret = _PyGen_Send((PyGenObject*)yf, NULL);
        } else
886 887
        #endif
            ret = Py_TYPE(yf)->tp_iternext(yf);
888 889 890 891 892 893 894
        gen->is_running = 0;
        //Py_DECREF(yf);
        if (likely(ret)) {
            return ret;
        }
        return __Pyx_Coroutine_FinishDelegation(gen);
    }
895
    return __Pyx_Coroutine_SendEx(gen, Py_None, 0);
896 897
}

898 899
static PyObject *__Pyx_Coroutine_Close(PyObject *self) {
    __pyx_CoroutineObject *gen = (__pyx_CoroutineObject *) self;
900 901 902 903
    PyObject *retval, *raised_exception;
    PyObject *yf = gen->yieldfrom;
    int err = 0;

Stefan Behnel's avatar
Stefan Behnel committed
904 905
    if (unlikely(gen->is_running))
        return __Pyx_Coroutine_AlreadyRunningError(gen);
906 907 908

    if (yf) {
        Py_INCREF(yf);
909 910
        err = __Pyx_Coroutine_CloseIter(gen, yf);
        __Pyx_Coroutine_Undelegate(gen);
911 912 913 914
        Py_DECREF(yf);
    }
    if (err == 0)
        PyErr_SetNone(PyExc_GeneratorExit);
915
    retval = __Pyx_Coroutine_SendEx(gen, NULL, 1);
916
    if (unlikely(retval)) {
917
        const char *msg;
918
        Py_DECREF(retval);
919
        if ((0)) {
920 921 922 923 924 925
        #ifdef __Pyx_Coroutine_USED
        } else if (__Pyx_Coroutine_CheckExact(self)) {
            msg = "coroutine ignored GeneratorExit";
        #endif
        #ifdef __Pyx_AsyncGen_USED
        } else if (__Pyx_AsyncGen_CheckExact(self)) {
926 927 928
#if PY_VERSION_HEX < 0x03060000
            msg = "async generator ignored GeneratorExit - might require Python 3.6+ finalisation (PEP 525)";
#else
929
            msg = "async generator ignored GeneratorExit";
930
#endif
931 932 933 934 935
        #endif
        } else {
            msg = "generator ignored GeneratorExit";
        }
        PyErr_SetString(PyExc_RuntimeError, msg);
936 937
        return NULL;
    }
938
    raised_exception = PyErr_Occurred();
939
    if (likely(!raised_exception || __Pyx_PyErr_GivenExceptionMatches2(raised_exception, PyExc_GeneratorExit, PyExc_StopIteration))) {
940 941
        // ignore these errors
        if (raised_exception) PyErr_Clear();
942 943 944 945 946 947
        Py_INCREF(Py_None);
        return Py_None;
    }
    return NULL;
}

948 949
static PyObject *__Pyx__Coroutine_Throw(PyObject *self, PyObject *typ, PyObject *val, PyObject *tb,
                                        PyObject *args, int close_on_genexit) {
950
    __pyx_CoroutineObject *gen = (__pyx_CoroutineObject *) self;
951
    PyObject *yf = gen->yieldfrom;
952

Stefan Behnel's avatar
Stefan Behnel committed
953 954
    if (unlikely(gen->is_running))
        return __Pyx_Coroutine_AlreadyRunningError(gen);
955 956 957 958

    if (yf) {
        PyObject *ret;
        Py_INCREF(yf);
959
        if (__Pyx_PyErr_GivenExceptionMatches(typ, PyExc_GeneratorExit) && close_on_genexit) {
960 961 962
            // Asynchronous generators *should not* be closed right away.
            // We have to allow some awaits to work it through, hence the
            // `close_on_genexit` parameter here.
963
            int err = __Pyx_Coroutine_CloseIter(gen, yf);
964
            Py_DECREF(yf);
965
            __Pyx_Coroutine_Undelegate(gen);
966
            if (err < 0)
967
                return __Pyx_Coroutine_MethodReturn(self, __Pyx_Coroutine_SendEx(gen, NULL, 0));
968 969 970
            goto throw_here;
        }
        gen->is_running = 1;
971
        if (0
972
        #ifdef __Pyx_Generator_USED
973
            || __Pyx_Generator_CheckExact(yf)
974 975
        #endif
        #ifdef __Pyx_Coroutine_USED
976 977 978 979
            || __Pyx_Coroutine_CheckExact(yf)
        #endif
            ) {
            ret = __Pyx__Coroutine_Throw(yf, typ, val, tb, args, close_on_genexit);
980 981 982 983
        #ifdef __Pyx_Coroutine_USED
        } else if (__Pyx_CoroutineAwait_CheckExact(yf)) {
            ret = __Pyx__Coroutine_Throw(((__pyx_CoroutineAwaitObject*)yf)->coroutine, typ, val, tb, args, close_on_genexit);
        #endif
984
        } else {
985
            PyObject *meth = __Pyx_PyObject_GetAttrStr(yf, PYIDENT("throw"));
986 987
            if (unlikely(!meth)) {
                Py_DECREF(yf);
988
                if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
989 990 991 992
                    gen->is_running = 0;
                    return NULL;
                }
                PyErr_Clear();
993
                __Pyx_Coroutine_Undelegate(gen);
994 995 996
                gen->is_running = 0;
                goto throw_here;
            }
997 998 999 1000 1001 1002
            if (likely(args)) {
                ret = PyObject_CallObject(meth, args);
            } else {
                // "tb" or even "val" might be NULL, but that also correctly terminates the argument list
                ret = PyObject_CallFunctionObjArgs(meth, typ, val, tb, NULL);
            }
1003 1004 1005 1006 1007
            Py_DECREF(meth);
        }
        gen->is_running = 0;
        Py_DECREF(yf);
        if (!ret) {
1008
            ret = __Pyx_Coroutine_FinishDelegation(gen);
1009
        }
1010
        return __Pyx_Coroutine_MethodReturn(self, ret);
1011 1012
    }
throw_here:
1013
    __Pyx_Raise(typ, val, tb, NULL);
1014
    return __Pyx_Coroutine_MethodReturn(self, __Pyx_Coroutine_SendEx(gen, NULL, 0));
1015 1016
}

1017 1018 1019 1020
static PyObject *__Pyx_Coroutine_Throw(PyObject *self, PyObject *args) {
    PyObject *typ;
    PyObject *val = NULL;
    PyObject *tb = NULL;
1021

1022 1023 1024 1025 1026 1027 1028
    if (!PyArg_UnpackTuple(args, (char *)"throw", 1, 3, &typ, &val, &tb))
        return NULL;

    return __Pyx__Coroutine_Throw(self, typ, val, tb, args, 1);
}

static int __Pyx_Coroutine_traverse(__pyx_CoroutineObject *gen, visitproc visit, void *arg) {
1029 1030
    Py_VISIT(gen->closure);
    Py_VISIT(gen->classobj);
1031
    Py_VISIT(gen->yieldfrom);
1032 1033 1034 1035 1036 1037
    Py_VISIT(gen->exc_type);
    Py_VISIT(gen->exc_value);
    Py_VISIT(gen->exc_traceback);
    return 0;
}

1038 1039
static int __Pyx_Coroutine_clear(PyObject *self) {
    __pyx_CoroutineObject *gen = (__pyx_CoroutineObject *) self;
1040 1041 1042 1043 1044 1045 1046

    Py_CLEAR(gen->closure);
    Py_CLEAR(gen->classobj);
    Py_CLEAR(gen->yieldfrom);
    Py_CLEAR(gen->exc_type);
    Py_CLEAR(gen->exc_value);
    Py_CLEAR(gen->exc_traceback);
1047 1048
#ifdef __Pyx_AsyncGen_USED
    if (__Pyx_AsyncGen_CheckExact(self)) {
1049
        Py_CLEAR(((__pyx_PyAsyncGenObject*)gen)->ag_finalizer);
1050 1051
    }
#endif
1052 1053
    Py_CLEAR(gen->gi_name);
    Py_CLEAR(gen->gi_qualname);
1054 1055 1056
    return 0;
}

1057 1058
static void __Pyx_Coroutine_dealloc(PyObject *self) {
    __pyx_CoroutineObject *gen = (__pyx_CoroutineObject *) self;
1059

1060 1061 1062 1063
    PyObject_GC_UnTrack(gen);
    if (gen->gi_weakreflist != NULL)
        PyObject_ClearWeakRefs(self);

1064 1065
    if (gen->resume_label >= 0) {
        // Generator is paused or unstarted, so we need to close
1066 1067 1068 1069
        PyObject_GC_Track(self);
#if PY_VERSION_HEX >= 0x030400a1
        if (PyObject_CallFinalizerFromDealloc(self))
#else
1070 1071
        Py_TYPE(gen)->tp_del(self);
        if (self->ob_refcnt > 0)
1072
#endif
1073 1074 1075 1076
        {
            // resurrected.  :(
            return;
        }
1077
        PyObject_GC_UnTrack(self);
1078 1079
    }

1080 1081 1082 1083 1084 1085 1086 1087
#ifdef __Pyx_AsyncGen_USED
    if (__Pyx_AsyncGen_CheckExact(self)) {
        /* We have to handle this case for asynchronous generators
           right here, because this code has to be between UNTRACK
           and GC_Del. */
        Py_CLEAR(((__pyx_PyAsyncGenObject*)self)->ag_finalizer);
    }
#endif
1088
    __Pyx_Coroutine_clear(self);
1089 1090 1091
    PyObject_GC_Del(gen);
}

1092
static void __Pyx_Coroutine_del(PyObject *self) {
1093
    PyObject *error_type, *error_value, *error_traceback;
1094
    __pyx_CoroutineObject *gen = (__pyx_CoroutineObject *) self;
1095
    __Pyx_PyThreadState_declare
1096

1097
    if (gen->resume_label < 0) {
Stefan Behnel's avatar
Stefan Behnel committed
1098
        // already terminated => nothing to clean up
1099 1100
        return;
    }
1101

1102
#if PY_VERSION_HEX < 0x030400a1
1103
    // Temporarily resurrect the object.
1104 1105
    assert(self->ob_refcnt == 0);
    self->ob_refcnt = 1;
1106
#endif
1107

1108
    __Pyx_PyThreadState_assign
1109

1110 1111 1112
    // Save the current exception, if any.
    __Pyx_ErrFetch(&error_type, &error_value, &error_traceback);

1113 1114 1115 1116 1117
#ifdef __Pyx_AsyncGen_USED
    if (__Pyx_AsyncGen_CheckExact(self)) {
        __pyx_PyAsyncGenObject *agen = (__pyx_PyAsyncGenObject*)self;
        PyObject *finalizer = agen->ag_finalizer;
        if (finalizer && !agen->ag_closed) {
1118 1119
            PyObject *res = __Pyx_PyObject_CallOneArg(finalizer, self);
            if (unlikely(!res)) {
1120 1121 1122 1123
                PyErr_WriteUnraisable(self);
            } else {
                Py_DECREF(res);
            }
1124
            // Restore the saved exception.
1125 1126 1127 1128 1129 1130
            __Pyx_ErrRestore(error_type, error_value, error_traceback);
            return;
        }
    }
#endif

1131
    if (unlikely(gen->resume_label == 0 && !error_value)) {
1132 1133 1134 1135 1136 1137
#ifdef __Pyx_Coroutine_USED
#ifdef __Pyx_Generator_USED
    // only warn about (async) coroutines
    if (!__Pyx_Generator_CheckExact(self))
#endif
        {
1138 1139
        // untrack dead object as we are executing Python code (which might trigger GC)
        PyObject_GC_UnTrack(self);
1140
#if PY_MAJOR_VERSION >= 3 /* PY_VERSION_HEX >= 0x03030000*/ || defined(PyErr_WarnFormat)
1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153
        if (unlikely(PyErr_WarnFormat(PyExc_RuntimeWarning, 1, "coroutine '%.50S' was never awaited", gen->gi_qualname) < 0))
            PyErr_WriteUnraisable(self);
#else
        {PyObject *msg;
        char *cmsg;
        #if CYTHON_COMPILING_IN_PYPY
        msg = NULL;
        cmsg = (char*) "coroutine was never awaited";
        #else
        char *cname;
        PyObject *qualname;
        qualname = gen->gi_qualname;
        cname = PyString_AS_STRING(qualname);
1154
        msg = PyString_FromFormat("coroutine '%.50s' was never awaited", cname);
1155

1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167
        if (unlikely(!msg)) {
            PyErr_Clear();
            cmsg = (char*) "coroutine was never awaited";
        } else {
            cmsg = PyString_AS_STRING(msg);
        }
        #endif
        if (unlikely(PyErr_WarnEx(PyExc_RuntimeWarning, cmsg, 1) < 0))
            PyErr_WriteUnraisable(self);
        Py_XDECREF(msg);}
#endif
        PyObject_GC_Track(self);
1168 1169
        }
#endif /*__Pyx_Coroutine_USED*/
1170 1171 1172 1173 1174 1175 1176 1177 1178
    } else {
        PyObject *res = __Pyx_Coroutine_Close(self);
        if (unlikely(!res)) {
            if (PyErr_Occurred())
                PyErr_WriteUnraisable(self);
        } else {
            Py_DECREF(res);
        }
    }
1179

1180
    // Restore the saved exception.
1181 1182
    __Pyx_ErrRestore(error_type, error_value, error_traceback);

1183
#if PY_VERSION_HEX < 0x030400a1
1184 1185
    // Undo the temporary resurrection; can't use DECREF here, it would
    // cause a recursive call.
1186
    assert(self->ob_refcnt > 0);
1187 1188 1189 1190
    if (--self->ob_refcnt == 0) {
        // this is the normal path out
        return;
    }
1191

1192 1193
    // close() resurrected it!  Make it look like the original Py_DECREF
    // never happened.
1194 1195 1196 1197 1198
    {
        Py_ssize_t refcnt = self->ob_refcnt;
        _Py_NewReference(self);
        self->ob_refcnt = refcnt;
    }
1199
#if CYTHON_COMPILING_IN_CPYTHON
1200 1201 1202
    assert(PyType_IS_GC(self->ob_type) &&
           _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);

1203 1204
    // If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
    // we need to undo that.
1205
    _Py_DEC_REFTOTAL;
1206
#endif
1207 1208 1209 1210 1211
    // If Py_TRACE_REFS, _Py_NewReference re-added self to the object
    // chain, so no more to do there.
    // If COUNT_ALLOCS, the original decref bumped tp_frees, and
    // _Py_NewReference bumped tp_allocs:  both of those need to be
    // undone.
1212
#ifdef COUNT_ALLOCS
1213 1214
    --Py_TYPE(self)->tp_frees;
    --Py_TYPE(self)->tp_allocs;
1215
#endif
1216
#endif
1217
}
1218

1219
static PyObject *
1220
__Pyx_Coroutine_get_name(__pyx_CoroutineObject *self)
1221
{
1222 1223 1224 1225 1226
    PyObject *name = self->gi_name;
    // avoid NULL pointer dereference during garbage collection
    if (unlikely(!name)) name = Py_None;
    Py_INCREF(name);
    return name;
1227 1228 1229
}

static int
1230
__Pyx_Coroutine_set_name(__pyx_CoroutineObject *self, PyObject *value)
1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250
{
    PyObject *tmp;

#if PY_MAJOR_VERSION >= 3
    if (unlikely(value == NULL || !PyUnicode_Check(value))) {
#else
    if (unlikely(value == NULL || !PyString_Check(value))) {
#endif
        PyErr_SetString(PyExc_TypeError,
                        "__name__ must be set to a string object");
        return -1;
    }
    tmp = self->gi_name;
    Py_INCREF(value);
    self->gi_name = value;
    Py_XDECREF(tmp);
    return 0;
}

static PyObject *
1251
__Pyx_Coroutine_get_qualname(__pyx_CoroutineObject *self)
1252
{
1253 1254 1255 1256 1257
    PyObject *name = self->gi_qualname;
    // avoid NULL pointer dereference during garbage collection
    if (unlikely(!name)) name = Py_None;
    Py_INCREF(name);
    return name;
1258 1259 1260
}

static int
1261
__Pyx_Coroutine_set_qualname(__pyx_CoroutineObject *self, PyObject *value)
1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280
{
    PyObject *tmp;

#if PY_MAJOR_VERSION >= 3
    if (unlikely(value == NULL || !PyUnicode_Check(value))) {
#else
    if (unlikely(value == NULL || !PyString_Check(value))) {
#endif
        PyErr_SetString(PyExc_TypeError,
                        "__qualname__ must be set to a string object");
        return -1;
    }
    tmp = self->gi_qualname;
    Py_INCREF(value);
    self->gi_qualname = value;
    Py_XDECREF(tmp);
    return 0;
}

1281 1282 1283
static __pyx_CoroutineObject *__Pyx__Coroutine_New(
            PyTypeObject* type, __pyx_coroutine_body_t body, PyObject *closure,
            PyObject *name, PyObject *qualname, PyObject *module_name) {
1284
    __pyx_CoroutineObject *gen = PyObject_GC_New(__pyx_CoroutineObject, type);
1285
    if (unlikely(!gen))
1286
        return NULL;
1287 1288
    return __Pyx__Coroutine_NewInit(gen, body, closure, name, qualname, module_name);
}
1289

1290 1291 1292
static __pyx_CoroutineObject *__Pyx__Coroutine_NewInit(
            __pyx_CoroutineObject *gen, __pyx_coroutine_body_t body, PyObject *closure,
            PyObject *name, PyObject *qualname, PyObject *module_name) {
1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307
    gen->body = body;
    gen->closure = closure;
    Py_XINCREF(closure);
    gen->is_running = 0;
    gen->resume_label = 0;
    gen->classobj = NULL;
    gen->yieldfrom = NULL;
    gen->exc_type = NULL;
    gen->exc_value = NULL;
    gen->exc_traceback = NULL;
    gen->gi_weakreflist = NULL;
    Py_XINCREF(qualname);
    gen->gi_qualname = qualname;
    Py_XINCREF(name);
    gen->gi_name = name;
1308 1309
    Py_XINCREF(module_name);
    gen->gi_modulename = module_name;
1310 1311 1312 1313 1314 1315 1316 1317 1318 1319

    PyObject_GC_Track(gen);
    return gen;
}


//////////////////// Coroutine ////////////////////
//@requires: CoroutineBase
//@requires: PatchGeneratorABC

1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356
static void __Pyx_CoroutineAwait_dealloc(PyObject *self) {
    PyObject_GC_UnTrack(self);
    Py_CLEAR(((__pyx_CoroutineAwaitObject*)self)->coroutine);
    PyObject_GC_Del(self);
}

static int __Pyx_CoroutineAwait_traverse(__pyx_CoroutineAwaitObject *self, visitproc visit, void *arg) {
    Py_VISIT(self->coroutine);
    return 0;
}

static int __Pyx_CoroutineAwait_clear(__pyx_CoroutineAwaitObject *self) {
    Py_CLEAR(self->coroutine);
    return 0;
}

static PyObject *__Pyx_CoroutineAwait_Next(__pyx_CoroutineAwaitObject *self) {
    return __Pyx_Generator_Next(self->coroutine);
}

static PyObject *__Pyx_CoroutineAwait_Send(__pyx_CoroutineAwaitObject *self, PyObject *value) {
    return __Pyx_Coroutine_Send(self->coroutine, value);
}

static PyObject *__Pyx_CoroutineAwait_Throw(__pyx_CoroutineAwaitObject *self, PyObject *args) {
    return __Pyx_Coroutine_Throw(self->coroutine, args);
}

static PyObject *__Pyx_CoroutineAwait_Close(__pyx_CoroutineAwaitObject *self) {
    return __Pyx_Coroutine_Close(self->coroutine);
}

static PyObject *__Pyx_CoroutineAwait_self(PyObject *self) {
    Py_INCREF(self);
    return self;
}

1357
#if !CYTHON_COMPILING_IN_PYPY
1358
static PyObject *__Pyx_CoroutineAwait_no_new(CYTHON_UNUSED PyTypeObject *type, CYTHON_UNUSED PyObject *args, CYTHON_UNUSED PyObject *kwargs) {
Stefan Behnel's avatar
Stefan Behnel committed
1359
    PyErr_SetString(PyExc_TypeError, "cannot instantiate type, use 'await coroutine' instead");
1360 1361
    return NULL;
}
1362
#endif
1363 1364

static PyMethodDef __pyx_CoroutineAwait_methods[] = {
1365 1366 1367 1368 1369 1370
    {"send", (PyCFunction) __Pyx_CoroutineAwait_Send, METH_O,
     (char*) PyDoc_STR("send(arg) -> send 'arg' into coroutine,\nreturn next yielded value or raise StopIteration.")},
    {"throw", (PyCFunction) __Pyx_CoroutineAwait_Throw, METH_VARARGS,
     (char*) PyDoc_STR("throw(typ[,val[,tb]]) -> raise exception in coroutine,\nreturn next yielded value or raise StopIteration.")},
    {"close", (PyCFunction) __Pyx_CoroutineAwait_Close, METH_NOARGS,
     (char*) PyDoc_STR("close() -> raise GeneratorExit inside coroutine.")},
1371 1372 1373 1374 1375
    {0, 0, 0, 0}
};

static PyTypeObject __pyx_CoroutineAwaitType_type = {
    PyVarObject_HEAD_INIT(0, 0)
1376
    "coroutine_wrapper",                /*tp_name*/
1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411
    sizeof(__pyx_CoroutineAwaitObject), /*tp_basicsize*/
    0,                                  /*tp_itemsize*/
    (destructor) __Pyx_CoroutineAwait_dealloc,/*tp_dealloc*/
    0,                                  /*tp_print*/
    0,                                  /*tp_getattr*/
    0,                                  /*tp_setattr*/
    0,                                  /*tp_as_async resp. tp_compare*/
    0,                                  /*tp_repr*/
    0,                                  /*tp_as_number*/
    0,                                  /*tp_as_sequence*/
    0,                                  /*tp_as_mapping*/
    0,                                  /*tp_hash*/
    0,                                  /*tp_call*/
    0,                                  /*tp_str*/
    0,                                  /*tp_getattro*/
    0,                                  /*tp_setattro*/
    0,                                  /*tp_as_buffer*/
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
    PyDoc_STR("A wrapper object implementing __await__ for coroutines."), /*tp_doc*/
    (traverseproc) __Pyx_CoroutineAwait_traverse,   /*tp_traverse*/
    (inquiry) __Pyx_CoroutineAwait_clear,           /*tp_clear*/
    0,                                  /*tp_richcompare*/
    0,                                  /*tp_weaklistoffset*/
    __Pyx_CoroutineAwait_self,          /*tp_iter*/
    (iternextfunc) __Pyx_CoroutineAwait_Next, /*tp_iternext*/
    __pyx_CoroutineAwait_methods,       /*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*/
    0,                                  /*tp_init*/
    0,                                  /*tp_alloc*/
1412
#if !CYTHON_COMPILING_IN_PYPY
1413
    __Pyx_CoroutineAwait_no_new,        /*tp_new*/
1414 1415 1416
#else
    0,                                  /*tp_new*/
#endif
1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435
    0,                                  /*tp_free*/
    0,                                  /*tp_is_gc*/
    0,                                  /*tp_bases*/
    0,                                  /*tp_mro*/
    0,                                  /*tp_cache*/
    0,                                  /*tp_subclasses*/
    0,                                  /*tp_weaklist*/
    0,                                  /*tp_del*/
    0,                                  /*tp_version_tag*/
#if PY_VERSION_HEX >= 0x030400a1
    0,                                  /*tp_finalize*/
#endif
};

static CYTHON_INLINE PyObject *__Pyx__Coroutine_await(PyObject *coroutine) {
    __pyx_CoroutineAwaitObject *await = PyObject_GC_New(__pyx_CoroutineAwaitObject, __pyx_CoroutineAwaitType);
    if (unlikely(!await)) return NULL;
    Py_INCREF(coroutine);
    await->coroutine = coroutine;
1436
    PyObject_GC_Track(await);
1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447
    return (PyObject*)await;
}

static PyObject *__Pyx_Coroutine_await(PyObject *coroutine) {
    if (unlikely(!coroutine || !__Pyx_Coroutine_CheckExact(coroutine))) {
        PyErr_SetString(PyExc_TypeError, "invalid input, expected coroutine");
        return NULL;
    }
    return __Pyx__Coroutine_await(coroutine);
}

1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461
#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 && PY_VERSION_HEX < 0x030500B1
static PyObject *__Pyx_Coroutine_compare(PyObject *obj, PyObject *other, int op) {
    PyObject* result;
    switch (op) {
        case Py_EQ: result = (other == obj) ? Py_True : Py_False; break;
        case Py_NE: result = (other != obj) ? Py_True : Py_False; break;
        default:
            result = Py_NotImplemented;
    }
    Py_INCREF(result);
    return result;
}
#endif

1462
static PyMethodDef __pyx_Coroutine_methods[] = {
1463
    {"send", (PyCFunction) __Pyx_Coroutine_Send, METH_O,
1464
     (char*) PyDoc_STR("send(arg) -> send 'arg' into coroutine,\nreturn next iterated value or raise StopIteration.")},
1465
    {"throw", (PyCFunction) __Pyx_Coroutine_Throw, METH_VARARGS,
1466
     (char*) PyDoc_STR("throw(typ[,val[,tb]]) -> raise exception in coroutine,\nreturn next iterated value or raise StopIteration.")},
1467 1468
    {"close", (PyCFunction) __Pyx_Coroutine_Close, METH_NOARGS,
     (char*) PyDoc_STR("close() -> raise GeneratorExit inside coroutine.")},
1469
#if PY_VERSION_HEX < 0x030500B1
1470
    {"__await__", (PyCFunction) __Pyx_Coroutine_await, METH_NOARGS,
1471
     (char*) PyDoc_STR("__await__() -> return an iterator to be used in await expression.")},
1472 1473 1474 1475
#endif
    {0, 0, 0, 0}
};

1476 1477
static PyMemberDef __pyx_Coroutine_memberlist[] = {
    {(char *) "cr_running", T_BOOL, offsetof(__pyx_CoroutineObject, is_running), READONLY, NULL},
1478
    {(char*) "cr_await", T_OBJECT, offsetof(__pyx_CoroutineObject, yieldfrom), READONLY,
1479
     (char*) PyDoc_STR("object being awaited, or None")},
1480
    {(char *) "__module__", T_OBJECT, offsetof(__pyx_CoroutineObject, gi_modulename), PY_WRITE_RESTRICTED, 0},
1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491
    {0, 0, 0, 0, 0}
};

static PyGetSetDef __pyx_Coroutine_getsets[] = {
    {(char *) "__name__", (getter)__Pyx_Coroutine_get_name, (setter)__Pyx_Coroutine_set_name,
     (char*) PyDoc_STR("name of the coroutine"), 0},
    {(char *) "__qualname__", (getter)__Pyx_Coroutine_get_qualname, (setter)__Pyx_Coroutine_set_qualname,
     (char*) PyDoc_STR("qualified name of the coroutine"), 0},
    {0, 0, 0, 0, 0}
};

1492
#if CYTHON_USE_ASYNC_SLOTS
1493
static __Pyx_PyAsyncMethodsStruct __pyx_Coroutine_as_async = {
Stefan Behnel's avatar
Stefan Behnel committed
1494
    __Pyx_Coroutine_await, /*am_await*/
1495 1496
    0, /*am_aiter*/
    0, /*am_anext*/
1497
};
1498 1499
#endif

1500
static PyTypeObject __pyx_CoroutineType_type = {
1501
    PyVarObject_HEAD_INIT(0, 0)
1502 1503
    "coroutine",                        /*tp_name*/
    sizeof(__pyx_CoroutineObject),      /*tp_basicsize*/
1504
    0,                                  /*tp_itemsize*/
1505
    (destructor) __Pyx_Coroutine_dealloc,/*tp_dealloc*/
1506 1507 1508
    0,                                  /*tp_print*/
    0,                                  /*tp_getattr*/
    0,                                  /*tp_setattr*/
1509 1510
#if CYTHON_USE_ASYNC_SLOTS
    &__pyx_Coroutine_as_async,          /*tp_as_async (tp_reserved) - Py3 only! */
1511
#else
1512
    0,                                  /*tp_reserved*/
1513
#endif
1514
    0,                                  /*tp_repr*/
1515 1516 1517 1518 1519 1520
    0,                                  /*tp_as_number*/
    0,                                  /*tp_as_sequence*/
    0,                                  /*tp_as_mapping*/
    0,                                  /*tp_hash*/
    0,                                  /*tp_call*/
    0,                                  /*tp_str*/
Stefan Behnel's avatar
Stefan Behnel committed
1521
    0,                                  /*tp_getattro*/
1522 1523
    0,                                  /*tp_setattro*/
    0,                                  /*tp_as_buffer*/
1524
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_HAVE_FINALIZE, /*tp_flags*/
1525
    0,                                  /*tp_doc*/
1526
    (traverseproc) __Pyx_Coroutine_traverse,   /*tp_traverse*/
1527
    0,                                  /*tp_clear*/
1528
#if CYTHON_USE_ASYNC_SLOTS && CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 && PY_VERSION_HEX < 0x030500B1
1529 1530 1531
    // in order to (mis-)use tp_reserved above, we must also implement tp_richcompare
    __Pyx_Coroutine_compare,            /*tp_richcompare*/
#else
1532
    0,                                  /*tp_richcompare*/
1533
#endif
1534
    offsetof(__pyx_CoroutineObject, gi_weakreflist), /*tp_weaklistoffset*/
Stefan Behnel's avatar
Stefan Behnel committed
1535
    // no tp_iter() as iterator is only available through __await__()
Stefan Behnel's avatar
Stefan Behnel committed
1536
    0,                                  /*tp_iter*/
1537
    0,                                  /*tp_iternext*/
1538 1539 1540
    __pyx_Coroutine_methods,            /*tp_methods*/
    __pyx_Coroutine_memberlist,         /*tp_members*/
    __pyx_Coroutine_getsets,            /*tp_getset*/
1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555
    0,                                  /*tp_base*/
    0,                                  /*tp_dict*/
    0,                                  /*tp_descr_get*/
    0,                                  /*tp_descr_set*/
    0,                                  /*tp_dictoffset*/
    0,                                  /*tp_init*/
    0,                                  /*tp_alloc*/
    0,                                  /*tp_new*/
    0,                                  /*tp_free*/
    0,                                  /*tp_is_gc*/
    0,                                  /*tp_bases*/
    0,                                  /*tp_mro*/
    0,                                  /*tp_cache*/
    0,                                  /*tp_subclasses*/
    0,                                  /*tp_weaklist*/
1556
#if CYTHON_USE_TP_FINALIZE
1557 1558
    0,                                  /*tp_del*/
#else
1559
    __Pyx_Coroutine_del,                /*tp_del*/
1560
#endif
1561
    0,                                  /*tp_version_tag*/
1562
#if CYTHON_USE_TP_FINALIZE
1563
    __Pyx_Coroutine_del,                /*tp_finalize*/
1564
#endif
1565 1566
};

1567
static int __pyx_Coroutine_init(void) {
1568 1569
    // on Windows, C-API functions can't be used in slots statically
    __pyx_CoroutineType_type.tp_getattro = PyObject_GenericGetAttr;
1570

1571
    __pyx_CoroutineType = __Pyx_FetchCommonType(&__pyx_CoroutineType_type);
1572 1573 1574 1575 1576
    if (unlikely(!__pyx_CoroutineType))
        return -1;

    __pyx_CoroutineAwaitType = __Pyx_FetchCommonType(&__pyx_CoroutineAwaitType_type);
    if (unlikely(!__pyx_CoroutineAwaitType))
1577 1578 1579
        return -1;
    return 0;
}
1580

1581 1582 1583 1584
//////////////////// Generator ////////////////////
//@requires: CoroutineBase
//@requires: PatchGeneratorABC

1585
static PyMethodDef __pyx_Generator_methods[] = {
1586 1587 1588 1589 1590 1591
    {"send", (PyCFunction) __Pyx_Coroutine_Send, METH_O,
     (char*) PyDoc_STR("send(arg) -> send 'arg' into generator,\nreturn next yielded value or raise StopIteration.")},
    {"throw", (PyCFunction) __Pyx_Coroutine_Throw, METH_VARARGS,
     (char*) PyDoc_STR("throw(typ[,val[,tb]]) -> raise exception in generator,\nreturn next yielded value or raise StopIteration.")},
    {"close", (PyCFunction) __Pyx_Coroutine_Close, METH_NOARGS,
     (char*) PyDoc_STR("close() -> raise GeneratorExit inside generator.")},
1592 1593 1594
    {0, 0, 0, 0}
};

1595 1596
static PyMemberDef __pyx_Generator_memberlist[] = {
    {(char *) "gi_running", T_BOOL, offsetof(__pyx_CoroutineObject, is_running), READONLY, NULL},
1597 1598
    {(char*) "gi_yieldfrom", T_OBJECT, offsetof(__pyx_CoroutineObject, yieldfrom), READONLY,
     (char*) PyDoc_STR("object being iterated by 'yield from', or None")},
1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609
    {0, 0, 0, 0, 0}
};

static PyGetSetDef __pyx_Generator_getsets[] = {
    {(char *) "__name__", (getter)__Pyx_Coroutine_get_name, (setter)__Pyx_Coroutine_set_name,
     (char*) PyDoc_STR("name of the generator"), 0},
    {(char *) "__qualname__", (getter)__Pyx_Coroutine_get_qualname, (setter)__Pyx_Coroutine_set_qualname,
     (char*) PyDoc_STR("qualified name of the generator"), 0},
    {0, 0, 0, 0, 0}
};

1610 1611 1612 1613 1614 1615 1616 1617 1618
static PyTypeObject __pyx_GeneratorType_type = {
    PyVarObject_HEAD_INIT(0, 0)
    "generator",                        /*tp_name*/
    sizeof(__pyx_CoroutineObject),      /*tp_basicsize*/
    0,                                  /*tp_itemsize*/
    (destructor) __Pyx_Coroutine_dealloc,/*tp_dealloc*/
    0,                                  /*tp_print*/
    0,                                  /*tp_getattr*/
    0,                                  /*tp_setattr*/
1619
    0,                                  /*tp_compare / tp_as_async*/
1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637
    0,                                  /*tp_repr*/
    0,                                  /*tp_as_number*/
    0,                                  /*tp_as_sequence*/
    0,                                  /*tp_as_mapping*/
    0,                                  /*tp_hash*/
    0,                                  /*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_FINALIZE, /*tp_flags*/
    0,                                  /*tp_doc*/
    (traverseproc) __Pyx_Coroutine_traverse,   /*tp_traverse*/
    0,                                  /*tp_clear*/
    0,                                  /*tp_richcompare*/
    offsetof(__pyx_CoroutineObject, gi_weakreflist), /*tp_weaklistoffset*/
    0,                                  /*tp_iter*/
    (iternextfunc) __Pyx_Generator_Next, /*tp_iternext*/
1638
    __pyx_Generator_methods,            /*tp_methods*/
1639 1640
    __pyx_Generator_memberlist,         /*tp_members*/
    __pyx_Generator_getsets,            /*tp_getset*/
1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655
    0,                                  /*tp_base*/
    0,                                  /*tp_dict*/
    0,                                  /*tp_descr_get*/
    0,                                  /*tp_descr_set*/
    0,                                  /*tp_dictoffset*/
    0,                                  /*tp_init*/
    0,                                  /*tp_alloc*/
    0,                                  /*tp_new*/
    0,                                  /*tp_free*/
    0,                                  /*tp_is_gc*/
    0,                                  /*tp_bases*/
    0,                                  /*tp_mro*/
    0,                                  /*tp_cache*/
    0,                                  /*tp_subclasses*/
    0,                                  /*tp_weaklist*/
1656
#if CYTHON_USE_TP_FINALIZE
1657 1658 1659 1660 1661
    0,                                  /*tp_del*/
#else
    __Pyx_Coroutine_del,                /*tp_del*/
#endif
    0,                                  /*tp_version_tag*/
1662
#if CYTHON_USE_TP_FINALIZE
1663 1664 1665 1666
    __Pyx_Coroutine_del,                /*tp_finalize*/
#endif
};

1667
static int __pyx_Generator_init(void) {
1668
    // on Windows, C-API functions can't be used in slots statically
Stefan Behnel's avatar
Stefan Behnel committed
1669 1670
    __pyx_GeneratorType_type.tp_getattro = PyObject_GenericGetAttr;
    __pyx_GeneratorType_type.tp_iter = PyObject_SelfIter;
1671 1672

    __pyx_GeneratorType = __Pyx_FetchCommonType(&__pyx_GeneratorType_type);
1673
    if (unlikely(!__pyx_GeneratorType)) {
1674 1675 1676
        return -1;
    }
    return 0;
1677
}
1678 1679


1680 1681
/////////////// ReturnWithStopIteration.proto ///////////////

1682 1683
#define __Pyx_ReturnWithStopIteration(value)  \
    if (value == Py_None) PyErr_SetNone(PyExc_StopIteration); else __Pyx__ReturnWithStopIteration(value)
1684 1685 1686
static void __Pyx__ReturnWithStopIteration(PyObject* value); /*proto*/

/////////////// ReturnWithStopIteration ///////////////
1687
//@requires: Exceptions.c::PyErrFetchRestore
1688
//@requires: Exceptions.c::PyThreadStateGet
1689 1690 1691 1692 1693
//@substitute: naming

// 1) Instantiating an exception just to pass back a value is costly.
// 2) CPython 3.3 <= x < 3.5b1 crash in yield-from when the StopIteration is not instantiated.
// 3) Passing a tuple as value into PyErr_SetObject() passes its items on as arguments.
1694 1695
// 4) Passing an exception as value will interpret it as an exception on unpacking and raise it (or unpack its value).
// 5) If there is currently an exception being handled, we need to chain it.
1696 1697 1698

static void __Pyx__ReturnWithStopIteration(PyObject* value) {
    PyObject *exc, *args;
1699
#if CYTHON_COMPILING_IN_CPYTHON || CYTHON_COMPILING_IN_PYSTON
1700
    __Pyx_PyThreadState_declare
1701 1702
    if ((PY_VERSION_HEX >= 0x03030000 && PY_VERSION_HEX < 0x030500B1)
            || unlikely(PyTuple_Check(value) || PyExceptionInstance_Check(value))) {
1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714
        args = PyTuple_New(1);
        if (unlikely(!args)) return;
        Py_INCREF(value);
        PyTuple_SET_ITEM(args, 0, value);
        exc = PyType_Type.tp_call(PyExc_StopIteration, args, NULL);
        Py_DECREF(args);
        if (!exc) return;
    } else {
        // it's safe to avoid instantiating the exception
        Py_INCREF(value);
        exc = value;
    }
1715 1716
    __Pyx_PyThreadState_assign
    if (!$local_tstate_cname->exc_type) {
1717 1718 1719 1720 1721 1722 1723 1724
        // no chaining needed => avoid the overhead in PyErr_SetObject()
        Py_INCREF(PyExc_StopIteration);
        __Pyx_ErrRestore(PyExc_StopIteration, exc, NULL);
        return;
    }
#else
    args = PyTuple_Pack(1, value);
    if (unlikely(!args)) return;
1725 1726
    exc = PyObject_Call(PyExc_StopIteration, args, NULL);
    Py_DECREF(args);
1727
    if (unlikely(!exc)) return;
1728
#endif
1729 1730 1731
    PyErr_SetObject(PyExc_StopIteration, exc);
    Py_DECREF(exc);
}
1732 1733


1734
//////////////////// PatchModuleWithCoroutine.proto ////////////////////
1735

1736
static PyObject* __Pyx_Coroutine_patch_module(PyObject* module, const char* py_code); /*proto*/
1737

1738
//////////////////// PatchModuleWithCoroutine ////////////////////
1739 1740
//@substitute: naming

1741 1742
static PyObject* __Pyx_Coroutine_patch_module(PyObject* module, const char* py_code) {
#if defined(__Pyx_Generator_USED) || defined(__Pyx_Coroutine_USED)
1743
    int result;
1744 1745
    PyObject *globals, *result_obj;
    globals = PyDict_New();  if (unlikely(!globals)) goto ignore;
1746
    result = PyDict_SetItemString(globals, "_cython_coroutine_type",
1747
    #ifdef __Pyx_Coroutine_USED
1748 1749 1750
        (PyObject*)__pyx_CoroutineType);
    #else
        Py_None);
1751
    #endif
1752 1753
    if (unlikely(result < 0)) goto ignore;
    result = PyDict_SetItemString(globals, "_cython_generator_type",
1754
    #ifdef __Pyx_Generator_USED
1755 1756 1757
        (PyObject*)__pyx_GeneratorType);
    #else
        Py_None);
1758
    #endif
1759
    if (unlikely(result < 0)) goto ignore;
1760
    if (unlikely(PyDict_SetItemString(globals, "_module", module) < 0)) goto ignore;
1761
    if (unlikely(PyDict_SetItemString(globals, "__builtins__", $builtins_cname) < 0)) goto ignore;
1762 1763 1764 1765 1766 1767 1768 1769
    result_obj = PyRun_String(py_code, Py_file_input, globals, globals);
    if (unlikely(!result_obj)) goto ignore;
    Py_DECREF(result_obj);
    Py_DECREF(globals);
    return module;

ignore:
    Py_XDECREF(globals);
1770
    PyErr_WriteUnraisable(module);
1771 1772 1773 1774
    if (unlikely(PyErr_WarnEx(PyExc_RuntimeWarning, "Cython module failed to patch module with custom type", 1) < 0)) {
        Py_DECREF(module);
        module = NULL;
    }
1775 1776 1777 1778
#else
    // avoid "unused" warning
    py_code++;
#endif
1779 1780
    return module;
}
1781

1782

1783 1784
//////////////////// PatchGeneratorABC.proto ////////////////////

1785
// register with Generator/Coroutine ABCs in 'collections.abc'
1786 1787 1788 1789
// see https://bugs.python.org/issue24018
static int __Pyx_patch_abc(void); /*proto*/

//////////////////// PatchGeneratorABC ////////////////////
1790
//@requires: PatchModuleWithCoroutine
1791

1792 1793 1794 1795
#ifndef CYTHON_REGISTER_ABCS
#define CYTHON_REGISTER_ABCS 1
#endif

1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814
#if defined(__Pyx_Generator_USED) || defined(__Pyx_Coroutine_USED)
static PyObject* __Pyx_patch_abc_module(PyObject *module); /*proto*/
static PyObject* __Pyx_patch_abc_module(PyObject *module) {
    module = __Pyx_Coroutine_patch_module(
        module, CSTRING("""\
if _cython_generator_type is not None:
    try: Generator = _module.Generator
    except AttributeError: pass
    else: Generator.register(_cython_generator_type)
if _cython_coroutine_type is not None:
    try: Coroutine = _module.Coroutine
    except AttributeError: pass
    else: Coroutine.register(_cython_coroutine_type)
""")
    );
    return module;
}
#endif

1815
static int __Pyx_patch_abc(void) {
1816
#if defined(__Pyx_Generator_USED) || defined(__Pyx_Coroutine_USED)
1817
    static int abc_patched = 0;
1818
    if (CYTHON_REGISTER_ABCS && !abc_patched) {
1819
        PyObject *module;
1820
        module = PyImport_ImportModule((PY_MAJOR_VERSION >= 3) ? "collections.abc" : "collections");
1821
        if (!module) {
1822
            PyErr_WriteUnraisable(NULL);
1823
            if (unlikely(PyErr_WarnEx(PyExc_RuntimeWarning,
1824
                    ((PY_MAJOR_VERSION >= 3) ?
1825 1826
                        "Cython module failed to register with collections.abc module" :
                        "Cython module failed to register with collections module"), 1) < 0)) {
1827 1828 1829
                return -1;
            }
        } else {
1830
            module = __Pyx_patch_abc_module(module);
1831 1832 1833
            abc_patched = 1;
            if (unlikely(!module))
                return -1;
1834 1835
            Py_DECREF(module);
        }
1836 1837 1838 1839 1840 1841 1842 1843 1844
        // also register with "backports_abc" module if available, just in case
        module = PyImport_ImportModule("backports_abc");
        if (module) {
            module = __Pyx_patch_abc_module(module);
            Py_XDECREF(module);
        }
        if (!module) {
            PyErr_Clear();
        }
1845 1846
    }
#else
1847
    // avoid "unused" warning for __Pyx_Coroutine_patch_module()
1848
    if ((0)) __Pyx_Coroutine_patch_module(NULL, NULL);
1849 1850 1851 1852 1853
#endif
    return 0;
}


1854 1855 1856 1857 1858 1859
//////////////////// PatchAsyncIO.proto ////////////////////

// run after importing "asyncio" to patch Cython generator support into it
static PyObject* __Pyx_patch_asyncio(PyObject* module); /*proto*/

//////////////////// PatchAsyncIO ////////////////////
1860
//@requires: ImportExport.c::Import
1861
//@requires: PatchModuleWithCoroutine
1862 1863 1864
//@requires: PatchInspect

static PyObject* __Pyx_patch_asyncio(PyObject* module) {
1865
#if PY_VERSION_HEX < 0x030500B2 && \
1866 1867
        (defined(__Pyx_Coroutine_USED) || defined(__Pyx_Generator_USED)) && \
        (!defined(CYTHON_PATCH_ASYNCIO) || CYTHON_PATCH_ASYNCIO)
1868 1869 1870 1871 1872 1873
    PyObject *patch_module = NULL;
    static int asyncio_patched = 0;
    if (unlikely((!asyncio_patched) && module)) {
        PyObject *package;
        package = __Pyx_Import(PYIDENT("asyncio.coroutines"), NULL, 0);
        if (package) {
1874
            patch_module = __Pyx_Coroutine_patch_module(
1875
                PyObject_GetAttrString(package, "coroutines"), CSTRING("""\
1876 1877 1878 1879 1880 1881 1882 1883
try:
    coro_types = _module._COROUTINE_TYPES
except AttributeError: pass
else:
    if _cython_coroutine_type is not None and _cython_coroutine_type not in coro_types:
        coro_types = tuple(coro_types) + (_cython_coroutine_type,)
    if _cython_generator_type is not None and _cython_generator_type not in coro_types:
        coro_types = tuple(coro_types) + (_cython_generator_type,)
1884
_module._COROUTINE_TYPES = coro_types
1885
""")
1886 1887 1888
            );
        } else {
            PyErr_Clear();
1889 1890
#if PY_VERSION_HEX < 0x03040200
            // Py3.4.1 used to have asyncio.tasks instead of asyncio.coroutines
1891 1892
            package = __Pyx_Import(PYIDENT("asyncio.tasks"), NULL, 0);
            if (unlikely(!package)) goto asyncio_done;
1893
            patch_module = __Pyx_Coroutine_patch_module(
1894
                PyObject_GetAttrString(package, "tasks"), CSTRING("""\
1895
if hasattr(_module, 'iscoroutine'):
1896 1897 1898 1899
    old_types = getattr(_module.iscoroutine, '_cython_coroutine_types', None)
    if old_types is None or not isinstance(old_types, set):
        old_types = set()
        def cy_wrap(orig_func, type=type, cython_coroutine_types=old_types):
1900 1901 1902 1903
            def cy_iscoroutine(obj): return type(obj) in cython_coroutine_types or orig_func(obj)
            cy_iscoroutine._cython_coroutine_types = cython_coroutine_types
            return cy_iscoroutine
        _module.iscoroutine = cy_wrap(_module.iscoroutine)
1904 1905 1906 1907
    if _cython_coroutine_type is not None:
        old_types.add(_cython_coroutine_type)
    if _cython_generator_type is not None:
        old_types.add(_cython_generator_type)
1908
""")
1909
            );
Stefan Behnel's avatar
Stefan Behnel committed
1910
#endif
1911
// Py < 0x03040200
1912 1913 1914
        }
        Py_DECREF(package);
        if (unlikely(!patch_module)) goto ignore;
1915
#if PY_VERSION_HEX < 0x03040200
1916 1917 1918 1919
asyncio_done:
        PyErr_Clear();
#endif
        asyncio_patched = 1;
1920
#ifdef __Pyx_Generator_USED
1921 1922 1923 1924
        // now patch inspect.isgenerator() by looking up the imported module in the patched asyncio module
        {
            PyObject *inspect_module;
            if (patch_module) {
1925
                inspect_module = PyObject_GetAttr(patch_module, PYIDENT("inspect"));
1926 1927 1928 1929 1930 1931 1932 1933 1934 1935
                Py_DECREF(patch_module);
            } else {
                inspect_module = __Pyx_Import(PYIDENT("inspect"), NULL, 0);
            }
            if (unlikely(!inspect_module)) goto ignore;
            inspect_module = __Pyx_patch_inspect(inspect_module);
            if (unlikely(!inspect_module)) {
                Py_DECREF(module);
                module = NULL;
            }
1936
            Py_XDECREF(inspect_module);
1937
        }
1938 1939
#else
        // avoid "unused" warning for __Pyx_patch_inspect()
1940
        if ((0)) return __Pyx_patch_inspect(module);
1941
#endif
1942 1943 1944 1945 1946 1947 1948 1949
    }
    return module;
ignore:
    PyErr_WriteUnraisable(module);
    if (unlikely(PyErr_WarnEx(PyExc_RuntimeWarning, "Cython module failed to patch asyncio package with custom generator type", 1) < 0)) {
        Py_DECREF(module);
        module = NULL;
    }
1950
#else
1951
    // avoid "unused" warning for __Pyx_Coroutine_patch_module()
1952
    if ((0)) return __Pyx_patch_inspect(__Pyx_Coroutine_patch_module(module, NULL));
1953
#endif
1954 1955 1956 1957 1958 1959 1960 1961 1962 1963
    return module;
}


//////////////////// PatchInspect.proto ////////////////////

// run after importing "inspect" to patch Cython generator support into it
static PyObject* __Pyx_patch_inspect(PyObject* module); /*proto*/

//////////////////// PatchInspect ////////////////////
1964
//@requires: PatchModuleWithCoroutine
1965 1966

static PyObject* __Pyx_patch_inspect(PyObject* module) {
1967
#if defined(__Pyx_Generator_USED) && (!defined(CYTHON_PATCH_INSPECT) || CYTHON_PATCH_INSPECT)
1968 1969
    static int inspect_patched = 0;
    if (unlikely((!inspect_patched) && module)) {
1970
        module = __Pyx_Coroutine_patch_module(
1971 1972 1973 1974 1975 1976 1977
            module, CSTRING("""\
old_types = getattr(_module.isgenerator, '_cython_generator_types', None)
if old_types is None or not isinstance(old_types, set):
    old_types = set()
    def cy_wrap(orig_func, type=type, cython_generator_types=old_types):
        def cy_isgenerator(obj): return type(obj) in cython_generator_types or orig_func(obj)
        cy_isgenerator._cython_generator_types = cython_generator_types
1978 1979
        return cy_isgenerator
    _module.isgenerator = cy_wrap(_module.isgenerator)
1980
old_types.add(_cython_generator_type)
1981
""")
1982 1983 1984
        );
        inspect_patched = 1;
    }
1985
#else
1986
    // avoid "unused" warning for __Pyx_Coroutine_patch_module()
1987
    if ((0)) return __Pyx_Coroutine_patch_module(module, NULL);
1988
#endif
1989 1990
    return module;
}
1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010


//////////////////// StopAsyncIteration.proto ////////////////////

#define __Pyx_StopAsyncIteration_USED
static PyObject *__Pyx_PyExc_StopAsyncIteration;
static int __pyx_StopAsyncIteration_init(void); /*proto*/

//////////////////// StopAsyncIteration ////////////////////

#if PY_VERSION_HEX < 0x030500B1
static PyTypeObject __Pyx__PyExc_StopAsyncIteration_type = {
    PyVarObject_HEAD_INIT(0, 0)
    "StopAsyncIteration",               /*tp_name*/
    sizeof(PyBaseExceptionObject),      /*tp_basicsize*/
    0,                                  /*tp_itemsize*/
    0,                                  /*tp_dealloc*/
    0,                                  /*tp_print*/
    0,                                  /*tp_getattr*/
    0,                                  /*tp_setattr*/
Stefan Behnel's avatar
Stefan Behnel committed
2011
    0,                                  /*tp_compare / reserved*/
2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061
    0,                                  /*tp_repr*/
    0,                                  /*tp_as_number*/
    0,                                  /*tp_as_sequence*/
    0,                                  /*tp_as_mapping*/
    0,                                  /*tp_hash*/
    0,                                  /*tp_call*/
    0,                                  /*tp_str*/
    0,                                  /*tp_getattro*/
    0,                                  /*tp_setattro*/
    0,                                  /*tp_as_buffer*/
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,  /*tp_flags*/
    PyDoc_STR("Signal the end from iterator.__anext__()."),  /*tp_doc*/
    0,                                  /*tp_traverse*/
    0,                                  /*tp_clear*/
    0,                                  /*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*/
    0,                                  /*tp_init*/
    0,                                  /*tp_alloc*/
    0,                                  /*tp_new*/
    0,                                  /*tp_free*/
    0,                                  /*tp_is_gc*/
    0,                                  /*tp_bases*/
    0,                                  /*tp_mro*/
    0,                                  /*tp_cache*/
    0,                                  /*tp_subclasses*/
    0,                                  /*tp_weaklist*/
    0,                                  /*tp_del*/
    0,                                  /*tp_version_tag*/
#if PY_VERSION_HEX >= 0x030400a1
    0,                                  /*tp_finalize*/
#endif
};
#endif

static int __pyx_StopAsyncIteration_init(void) {
#if PY_VERSION_HEX >= 0x030500B1
    __Pyx_PyExc_StopAsyncIteration = PyExc_StopAsyncIteration;
#else
    PyObject *builtins = PyEval_GetBuiltins();
    if (likely(builtins)) {
Stefan Behnel's avatar
Stefan Behnel committed
2062
        PyObject *exc = PyMapping_GetItemString(builtins, (char*) "StopAsyncIteration");
2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077
        if (exc) {
            __Pyx_PyExc_StopAsyncIteration = exc;
            return 0;
        }
    }
    PyErr_Clear();

    __Pyx__PyExc_StopAsyncIteration_type.tp_traverse = ((PyTypeObject*)PyExc_BaseException)->tp_traverse;
    __Pyx__PyExc_StopAsyncIteration_type.tp_clear = ((PyTypeObject*)PyExc_BaseException)->tp_clear;
    __Pyx__PyExc_StopAsyncIteration_type.tp_dictoffset = ((PyTypeObject*)PyExc_BaseException)->tp_dictoffset;
    __Pyx__PyExc_StopAsyncIteration_type.tp_base = (PyTypeObject*)PyExc_Exception;

    __Pyx_PyExc_StopAsyncIteration = (PyObject*) __Pyx_FetchCommonType(&__Pyx__PyExc_StopAsyncIteration_type);
    if (unlikely(!__Pyx_PyExc_StopAsyncIteration))
        return -1;
Stefan Behnel's avatar
Stefan Behnel committed
2078
    if (builtins && unlikely(PyMapping_SetItemString(builtins, (char*) "StopAsyncIteration", __Pyx_PyExc_StopAsyncIteration) < 0))
2079 2080 2081 2082
        return -1;
#endif
    return 0;
}