Coverage Report

Created: 2026-10-17 06:15

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Objects/genobject.c
Line
Count
Source
1
/* Generator object implementation */
2
3
#define _PY_INTERPRETER
4
5
#include "Python.h"
6
#include "pycore_call.h"          // _PyObject_CallNoArgs()
7
#include "pycore_ceval.h"         // _PyEval_EvalFrame()
8
#include "pycore_frame.h"         // _PyInterpreterFrame
9
#include "pycore_freelist.h"      // _Py_FREELIST_FREE()
10
#include "pycore_gc.h"            // _PyGC_CLEAR_FINALIZED()
11
#include "pycore_genobject.h"     // _PyGen_SetStopIterationValue()
12
#include "pycore_interpframe.h"   // _PyFrame_GetCode()
13
#include "pycore_lock.h"          // _Py_yield()
14
#include "pycore_modsupport.h"    // _PyArg_CheckPositional()
15
#include "pycore_object.h"        // _PyObject_GC_UNTRACK()
16
#include "pycore_opcode_utils.h"  // RESUME_AFTER_YIELD_FROM
17
#include "pycore_pyatomic_ft_wrappers.h" // FT_ATOMIC_LOAD_UINT8_RELAXED()
18
#include "pycore_pyerrors.h"      // _PyErr_ClearExcState()
19
#include "pycore_pystate.h"       // _PyThreadState_GET()
20
#include "pycore_warnings.h"      // _PyErr_WarnUnawaitedCoroutine()
21
#include "pycore_weakref.h"       // FT_CLEAR_WEAKREFS()
22
23
24
#include "opcode_ids.h"           // RESUME, etc
25
26
// Forward declarations
27
static PyObject* gen_close(PyObject *, PyObject *);
28
static PyObject* async_gen_asend_new(PyAsyncGenObject *, PyObject *);
29
static PyObject* async_gen_athrow_new(PyAsyncGenObject *, PyObject *);
30
31
32
#define _PyGen_CAST(op) \
33
107M
    _Py_CAST(PyGenObject*, (op))
34
#define _PyCoroObject_CAST(op) \
35
0
    (assert(PyCoro_CheckExact(op)), \
36
0
     _Py_CAST(PyCoroObject*, (op)))
37
#define _PyAsyncGenObject_CAST(op) \
38
0
    _Py_CAST(PyAsyncGenObject*, (op))
39
40
#ifdef Py_GIL_DISABLED
41
static bool
42
gen_try_set_frame_state(PyGenObject *gen, int8_t *expected, int8_t state)
43
{
44
    if (*expected == FRAME_SUSPENDED_YIELD_FROM_LOCKED) {
45
        // Wait for the in-progress gi_yieldfrom read to complete
46
        _Py_yield();
47
        *expected = _Py_atomic_load_int8_relaxed(&gen->gi_frame_state);
48
        return false;
49
    }
50
    return _Py_atomic_compare_exchange_int8(&gen->gi_frame_state, expected, state);
51
}
52
53
# define _Py_GEN_TRY_SET_FRAME_STATE(gen, expected, state) \
54
    gen_try_set_frame_state((gen), &(expected), (state))
55
#else
56
# define _Py_GEN_TRY_SET_FRAME_STATE(gen, expected, state) \
57
64.4M
    ((gen)->gi_frame_state = (state), true)
58
#endif
59
60
61
static const char *NON_INIT_CORO_MSG = "can't send non-None value to a "
62
                                 "just-started coroutine";
63
64
static const char *ASYNC_GEN_IGNORED_EXIT_MSG =
65
                                 "async generator ignored GeneratorExit";
66
67
/* Returns a borrowed reference */
68
static inline PyCodeObject *
69
174k
_PyGen_GetCode(PyGenObject *gen) {
70
174k
    return _PyFrame_GetCode(&gen->gi_iframe);
71
174k
}
72
73
PyCodeObject *
74
0
PyGen_GetCode(PyGenObject *gen) {
75
0
    assert(PyGen_Check(gen));
76
0
    PyCodeObject *res = _PyGen_GetCode(gen);
77
0
    Py_INCREF(res);
78
0
    return res;
79
0
}
80
81
static int
82
gen_traverse(PyObject *self, visitproc visit, void *arg)
83
431k
{
84
431k
    PyGenObject *gen = _PyGen_CAST(self);
85
431k
    Py_VISIT(gen->gi_name);
86
431k
    Py_VISIT(gen->gi_qualname);
87
431k
    if (gen->gi_frame_state != FRAME_CLEARED) {
88
431k
        _PyInterpreterFrame *frame = &gen->gi_iframe;
89
431k
        assert(frame->frame_obj == NULL ||
90
431k
               frame->frame_obj->f_frame->owner == FRAME_OWNED_BY_GENERATOR);
91
431k
        int err = _PyFrame_Traverse(frame, visit, arg);
92
431k
        if (err) {
93
0
            return err;
94
0
        }
95
431k
    }
96
862
    else {
97
        // We still need to visit the code object when the frame is cleared to
98
        // ensure that it's kept alive if the reference is deferred.
99
862
        _Py_VISIT_STACKREF(gen->gi_iframe.f_executable);
100
862
    }
101
    /* No need to visit cr_origin, because it's just tuples/str/int, so can't
102
       participate in a reference cycle. */
103
431k
    Py_VISIT(gen->gi_exc_state.exc_value);
104
431k
    return 0;
105
431k
}
106
107
static void
108
gen_finalize(PyObject *self)
109
42.4M
{
110
42.4M
    PyGenObject *gen = (PyGenObject *)self;
111
112
42.4M
    if (FRAME_STATE_FINISHED(gen->gi_frame_state)) {
113
        /* Generator isn't paused, so no need to close */
114
42.2M
        return;
115
42.2M
    }
116
117
174k
    if (PyAsyncGen_CheckExact(self)) {
118
37
        PyAsyncGenObject *agen = (PyAsyncGenObject*)self;
119
37
        PyObject *finalizer = agen->ag_origin_or_finalizer;
120
37
        if (finalizer && !agen->ag_closed) {
121
            /* Save the current exception, if any. */
122
0
            PyObject *exc = PyErr_GetRaisedException();
123
124
0
            PyObject *res = PyObject_CallOneArg(finalizer, self);
125
0
            if (res == NULL) {
126
0
                PyErr_FormatUnraisable("Exception ignored while "
127
0
                                       "finalizing generator %R", self);
128
0
            }
129
0
            else {
130
0
                Py_DECREF(res);
131
0
            }
132
            /* Restore the saved exception. */
133
0
            PyErr_SetRaisedException(exc);
134
0
            return;
135
0
        }
136
37
    }
137
138
    /* Save the current exception, if any. */
139
174k
    PyObject *exc = PyErr_GetRaisedException();
140
141
    /* If `gen` is a coroutine, and if it was never awaited on,
142
       issue a RuntimeWarning. */
143
174k
    assert(_PyGen_GetCode(gen) != NULL);
144
174k
    if (_PyGen_GetCode(gen)->co_flags & CO_COROUTINE &&
145
0
        gen->gi_frame_state == FRAME_CREATED)
146
0
    {
147
0
        _PyErr_WarnUnawaitedCoroutine((PyObject *)gen);
148
0
    }
149
174k
    else {
150
174k
        PyObject *res = gen_close((PyObject*)gen, NULL);
151
174k
        if (res == NULL) {
152
0
            if (PyErr_Occurred()) {
153
0
                PyErr_FormatUnraisable("Exception ignored while "
154
0
                                       "closing generator %R", self);
155
0
            }
156
0
        }
157
174k
        else {
158
174k
            Py_DECREF(res);
159
174k
        }
160
174k
    }
161
162
    /* Restore the saved exception. */
163
174k
    PyErr_SetRaisedException(exc);
164
174k
}
165
166
static void
167
gen_clear_frame(PyGenObject *gen)
168
174k
{
169
174k
    assert(FT_ATOMIC_LOAD_INT8_RELAXED(gen->gi_frame_state) == FRAME_CLEARED);
170
174k
    _PyInterpreterFrame *frame = &gen->gi_iframe;
171
174k
    _PyThreadState_UpdateLastProfiledFrame(_PyThreadState_GET(), frame, frame->previous);
172
174k
    frame->previous = NULL;
173
174k
    Py_BEGIN_CRITICAL_SECTION(gen);
174
174k
    _PyFrame_ClearExceptCode(frame);
175
174k
    Py_END_CRITICAL_SECTION();
176
174k
    _PyErr_ClearExcState(&gen->gi_exc_state);
177
174k
}
178
179
int
180
_PyGen_ClearFrame(PyGenObject *gen)
181
0
{
182
0
    int8_t frame_state = FT_ATOMIC_LOAD_INT8_RELAXED(gen->gi_frame_state);
183
0
    do {
184
0
        if (FRAME_STATE_FINISHED(frame_state)) {
185
0
            return 0;
186
0
        }
187
0
        else if (frame_state == FRAME_EXECUTING) {
188
0
            PyErr_SetString(PyExc_RuntimeError,
189
0
                            "cannot clear an executing frame");
190
0
            return -1;
191
0
        }
192
0
        else if (FRAME_STATE_SUSPENDED(frame_state)) {
193
0
            PyErr_SetString(PyExc_RuntimeError,
194
0
                            "cannot clear an suspended frame");
195
0
            return -1;
196
0
        }
197
0
        assert(frame_state == FRAME_CREATED);
198
0
    } while (!_Py_GEN_TRY_SET_FRAME_STATE(gen, frame_state, FRAME_CLEARED));
199
200
0
    if (_PyGen_GetCode(gen)->co_flags & CO_COROUTINE) {
201
0
        _PyErr_WarnUnawaitedCoroutine((PyObject *)gen);
202
0
    }
203
0
    gen_clear_frame(gen);
204
0
    return 0;
205
0
}
206
207
static void
208
gen_dealloc(PyObject *self)
209
42.4M
{
210
42.4M
    PyGenObject *gen = _PyGen_CAST(self);
211
212
42.4M
    _PyObject_GC_UNTRACK(gen);
213
214
42.4M
    FT_CLEAR_WEAKREFS(self, gen->gi_weakreflist);
215
216
42.4M
    _PyObject_GC_TRACK(self);
217
218
42.4M
    if (PyObject_CallFinalizerFromDealloc(self))
219
0
        return;                     /* resurrected.  :( */
220
221
42.4M
    _PyObject_GC_UNTRACK(self);
222
42.4M
    if (PyAsyncGen_CheckExact(gen)) {
223
        /* We have to handle this case for asynchronous generators
224
           right here, because this code has to be between UNTRACK
225
           and GC_Del. */
226
37
        Py_CLEAR(((PyAsyncGenObject*)gen)->ag_origin_or_finalizer);
227
37
    }
228
42.4M
    if (PyCoro_CheckExact(gen)) {
229
37
        Py_CLEAR(((PyCoroObject *)gen)->cr_origin_or_finalizer);
230
37
    }
231
42.4M
    if (gen->gi_frame_state != FRAME_CLEARED) {
232
0
        gen->gi_frame_state = FRAME_CLEARED;
233
0
        gen_clear_frame(gen);
234
0
    }
235
42.4M
    assert(gen->gi_exc_state.exc_value == NULL);
236
42.4M
    PyStackRef_CLEAR(gen->gi_iframe.f_executable);
237
42.4M
    Py_CLEAR(gen->gi_name);
238
42.4M
    Py_CLEAR(gen->gi_qualname);
239
240
42.4M
    PyObject_GC_Del(gen);
241
42.4M
}
242
243
static void
244
gen_raise_already_executing_error(PyGenObject *gen)
245
0
{
246
0
    const char *msg = "generator already executing";
247
0
    if (PyCoro_CheckExact(gen)) {
248
0
        msg = "coroutine already executing";
249
0
    }
250
0
    else if (PyAsyncGen_CheckExact(gen)) {
251
0
        msg = "async generator already executing";
252
0
    }
253
0
    PyErr_SetString(PyExc_ValueError, msg);
254
0
}
255
256
// Send 'arg' into 'gen'. On success, return PYGEN_NEXT or PYGEN_RETURN.
257
// Returns PYGEN_ERROR on failure. 'presult' is set to the yielded or
258
// returned value.
259
// The generator must be in the FRAME_EXECUTING state when this function
260
// is called.
261
static PySendResult
262
gen_send_ex2(PyGenObject *gen, PyObject *arg, PyObject **presult, int exc)
263
64.1M
{
264
64.1M
    assert(FT_ATOMIC_LOAD_INT8_RELAXED(gen->gi_frame_state) == FRAME_EXECUTING);
265
266
64.1M
    PyThreadState *tstate = _PyThreadState_GET();
267
64.1M
    _PyInterpreterFrame *frame = &gen->gi_iframe;
268
269
    /* Push arg onto the frame's value stack */
270
64.1M
    PyObject *arg_obj = arg ? arg : Py_None;
271
64.1M
    _PyFrame_StackPush(frame, PyStackRef_FromPyObjectNew(arg_obj));
272
273
64.1M
    _PyErr_StackItem *prev_exc_info = tstate->exc_info;
274
64.1M
    gen->gi_exc_state.previous_item = prev_exc_info;
275
64.1M
    tstate->exc_info = &gen->gi_exc_state;
276
277
64.1M
    if (exc) {
278
36.6k
        assert(_PyErr_Occurred(tstate));
279
36.6k
        _PyErr_ChainStackItem();
280
36.6k
    }
281
282
64.1M
    EVAL_CALL_STAT_INC(EVAL_CALL_GENERATOR);
283
64.1M
    PyObject *result = _PyEval_EvalFrame(tstate, frame, exc);
284
64.1M
    assert(tstate->exc_info == prev_exc_info);
285
64.1M
#ifndef Py_GIL_DISABLED
286
64.1M
    assert(gen->gi_exc_state.previous_item == NULL);
287
64.1M
    assert(frame->previous == NULL);
288
64.1M
    assert(gen->gi_frame_state != FRAME_EXECUTING);
289
64.1M
#endif
290
291
    // The generator_return_kind field is used to distinguish between a
292
    // yield and a return from within _PyEval_EvalFrame(). Earlier versions
293
    // of CPython (prior to 3.15) used gi_frame_state for this purpose, but
294
    // that requires the GIL for thread-safety.
295
64.1M
    int return_kind = ((_PyThreadStateImpl *)tstate)->generator_return_kind;
296
297
64.1M
    if (return_kind == GENERATOR_YIELD) {
298
52.6M
        assert(result != NULL && !_PyErr_Occurred(tstate));
299
52.6M
#ifndef Py_GIL_DISABLED
300
52.6M
        assert(FRAME_STATE_SUSPENDED(gen->gi_frame_state));
301
52.6M
#endif
302
52.6M
        *presult = result;
303
52.6M
        return PYGEN_NEXT;
304
52.6M
    }
305
306
64.1M
    assert(return_kind == GENERATOR_RETURN);
307
11.4M
    assert(gen->gi_exc_state.exc_value == NULL);
308
11.4M
    assert(FT_ATOMIC_LOAD_INT8_RELAXED(gen->gi_frame_state) == FRAME_CLEARED);
309
310
    /* If the generator just returned (as opposed to yielding), signal
311
     * that the generator is exhausted. */
312
11.4M
    if (result) {
313
11.4M
        assert(result == Py_None || !PyAsyncGen_CheckExact(gen));
314
11.4M
        if (result == Py_None && !PyAsyncGen_CheckExact(gen) && !arg) {
315
            /* Return NULL if called by gen_iternext() */
316
11.4M
            Py_CLEAR(result);
317
11.4M
        }
318
11.4M
    }
319
54.4k
    else {
320
54.4k
        assert(!PyErr_ExceptionMatches(PyExc_StopIteration));
321
54.4k
        assert(!PyAsyncGen_CheckExact(gen) ||
322
54.4k
            !PyErr_ExceptionMatches(PyExc_StopAsyncIteration));
323
54.4k
    }
324
325
11.4M
    *presult = result;
326
11.4M
    return result ? PYGEN_RETURN : PYGEN_ERROR;
327
64.1M
}
328
329
// Set the generator 'gen' to the executing state and send 'arg' into it.
330
// See gen_send_ex2() for details.
331
static PySendResult
332
gen_send_ex(PyGenObject *gen, PyObject *arg, PyObject **presult)
333
64.1M
{
334
64.1M
    *presult = NULL;
335
64.1M
    int8_t frame_state = FT_ATOMIC_LOAD_INT8_RELAXED(gen->gi_frame_state);
336
64.1M
    do {
337
64.1M
        if (frame_state == FRAME_CREATED && arg && arg != Py_None) {
338
0
            const char *msg = "can't send non-None value to a "
339
0
                                "just-started generator";
340
0
            if (PyCoro_CheckExact(gen)) {
341
0
                msg = NON_INIT_CORO_MSG;
342
0
            }
343
0
            else if (PyAsyncGen_CheckExact(gen)) {
344
0
                msg = "can't send non-None value to a "
345
0
                        "just-started async generator";
346
0
            }
347
0
            PyErr_SetString(PyExc_TypeError, msg);
348
0
            return PYGEN_ERROR;
349
0
        }
350
64.1M
        if (frame_state == FRAME_EXECUTING) {
351
0
            gen_raise_already_executing_error(gen);
352
0
            return PYGEN_ERROR;
353
0
        }
354
64.1M
        if (FRAME_STATE_FINISHED(frame_state)) {
355
20.2k
            if (PyCoro_CheckExact(gen)) {
356
                /* `gen` is an exhausted coroutine: raise an error,
357
                except when called from gen_close(), which should
358
                always be a silent method. */
359
0
                PyErr_SetString(
360
0
                    PyExc_RuntimeError,
361
0
                    "cannot reuse already awaited coroutine");
362
0
            }
363
20.2k
            else if (arg) {
364
                /* `gen` is an exhausted generator:
365
                only return value if called from send(). */
366
0
                *presult = Py_None;
367
0
                return PYGEN_RETURN;
368
0
            }
369
20.2k
            return PYGEN_ERROR;
370
20.2k
        }
371
372
64.1M
        assert((frame_state == FRAME_CREATED) ||
373
64.1M
               FRAME_STATE_SUSPENDED(frame_state));
374
64.1M
    } while (!_Py_GEN_TRY_SET_FRAME_STATE(gen, frame_state, FRAME_EXECUTING));
375
376
64.1M
    return gen_send_ex2(gen, arg, presult, 0);
377
64.1M
}
378
379
static PySendResult
380
PyGen_am_send(PyObject *self, PyObject *arg, PyObject **result)
381
0
{
382
0
    PyGenObject *gen = _PyGen_CAST(self);
383
0
    return gen_send_ex(gen, arg, result);
384
0
}
385
386
static PyObject *
387
gen_set_stop_iteration(PyGenObject *gen, PyObject *result)
388
0
{
389
0
    if (PyAsyncGen_CheckExact(gen)) {
390
0
        assert(result == Py_None);
391
0
        PyErr_SetNone(PyExc_StopAsyncIteration);
392
0
    }
393
0
    else if (result == Py_None) {
394
0
        PyErr_SetNone(PyExc_StopIteration);
395
0
    }
396
0
    else {
397
0
        _PyGen_SetStopIterationValue(result);
398
0
    }
399
0
    Py_DECREF(result);
400
0
    return NULL;
401
0
}
402
403
PyDoc_STRVAR(send_doc,
404
"send(value) -> send 'value' into generator,\n\
405
return next yielded value or raise StopIteration.");
406
407
static PyObject *
408
gen_send(PyObject *op, PyObject *arg)
409
0
{
410
0
    PyObject *result;
411
0
    PyGenObject *gen = _PyGen_CAST(op);
412
0
    if (gen_send_ex(gen, arg, &result) == PYGEN_RETURN) {
413
0
        return gen_set_stop_iteration(gen, result);
414
0
    }
415
0
    return result;
416
0
}
417
418
PyDoc_STRVAR(close_doc,
419
"close() -> raise GeneratorExit inside generator.");
420
421
/*
422
 *   This helper function is used by gen_close and gen_throw to
423
 *   close a subiterator being delegated to by yield-from.
424
 */
425
426
static int
427
gen_close_iter(PyObject *yf)
428
0
{
429
0
    PyObject *retval = NULL;
430
431
0
    if (PyGen_CheckExact(yf) || PyCoro_CheckExact(yf)) {
432
0
        retval = gen_close((PyObject *)yf, NULL);
433
0
        if (retval == NULL)
434
0
            return -1;
435
0
    }
436
0
    else {
437
0
        PyObject *meth;
438
0
        if (PyObject_GetOptionalAttr(yf, &_Py_ID(close), &meth) < 0) {
439
0
            PyErr_FormatUnraisable("Exception ignored while "
440
0
                                   "closing generator %R", yf);
441
0
        }
442
0
        if (meth) {
443
0
            retval = _PyObject_CallNoArgs(meth);
444
0
            Py_DECREF(meth);
445
0
            if (retval == NULL)
446
0
                return -1;
447
0
        }
448
0
    }
449
0
    Py_XDECREF(retval);
450
0
    return 0;
451
0
}
452
453
static inline bool
454
is_resume(_Py_CODEUNIT *instr)
455
26.7k
{
456
26.7k
    uint8_t code = FT_ATOMIC_LOAD_UINT8_RELAXED(instr->op.code);
457
26.7k
    return (
458
26.7k
        code == RESUME ||
459
25.0k
        code == RESUME_CHECK ||
460
0
        code == RESUME_CHECK_JIT ||
461
0
        code == INSTRUMENTED_RESUME
462
26.7k
    );
463
26.7k
}
464
465
static PyObject *
466
gen_close(PyObject *self, PyObject *args)
467
174k
{
468
174k
    PyGenObject *gen = _PyGen_CAST(self);
469
470
174k
    int8_t frame_state = FT_ATOMIC_LOAD_INT8_RELAXED(gen->gi_frame_state);
471
174k
    do {
472
174k
        if (frame_state == FRAME_CREATED) {
473
            // && (1) to avoid -Wunreachable-code warning on Clang
474
148k
            if (!_Py_GEN_TRY_SET_FRAME_STATE(gen, frame_state, FRAME_CLEARED) && (1)) {
475
0
                continue;
476
0
            }
477
148k
            gen_clear_frame(gen);
478
148k
            Py_RETURN_NONE;
479
148k
        }
480
481
26.7k
        if (FRAME_STATE_FINISHED(frame_state)) {
482
0
            Py_RETURN_NONE;
483
0
        }
484
485
26.7k
        if (frame_state == FRAME_EXECUTING) {
486
0
            gen_raise_already_executing_error(gen);
487
0
            return NULL;
488
0
        }
489
490
26.7k
        assert(FRAME_STATE_SUSPENDED(frame_state));
491
26.7k
    } while (!_Py_GEN_TRY_SET_FRAME_STATE(gen, frame_state, FRAME_EXECUTING));
492
493
26.7k
    int err = 0;
494
26.7k
    _PyInterpreterFrame *frame = &gen->gi_iframe;
495
26.7k
    if (frame_state == FRAME_SUSPENDED_YIELD_FROM) {
496
0
        PyObject *yf = PyStackRef_AsPyObjectNew(_PyFrame_StackPeek(frame, 2));
497
0
        err = gen_close_iter(yf);
498
0
        Py_DECREF(yf);
499
0
    }
500
501
26.7k
    if (is_resume(frame->instr_ptr)) {
502
26.7k
        bool no_unwind_tools = _PyEval_NoToolsForUnwind(_PyThreadState_GET(), frame);
503
        /* We can safely ignore the outermost try block
504
         * as it is automatically generated to handle
505
         * StopIteration. */
506
26.7k
        int oparg = frame->instr_ptr->op.arg;
507
26.7k
        if (oparg & RESUME_OPARG_DEPTH1_MASK && no_unwind_tools) {
508
            // RESUME after YIELD_VALUE and exception depth is 1
509
26.3k
            assert((oparg & RESUME_OPARG_LOCATION_MASK) != RESUME_AT_FUNC_START);
510
26.3k
            FT_ATOMIC_STORE_INT8_RELEASE(gen->gi_frame_state, FRAME_CLEARED);
511
26.3k
            gen_clear_frame(gen);
512
26.3k
            Py_RETURN_NONE;
513
26.3k
        }
514
26.7k
    }
515
377
    if (err == 0) {
516
377
        PyErr_SetNone(PyExc_GeneratorExit);
517
377
    }
518
519
377
    PyObject *retval;
520
377
    if (gen_send_ex2(gen, Py_None, &retval, 1) == PYGEN_RETURN) {
521
        // the generator returned a value while closing, return the value here
522
0
        assert(!PyErr_Occurred());
523
0
        return retval;
524
0
    }
525
377
    else if (retval) {
526
0
        const char *msg = "generator ignored GeneratorExit";
527
0
        if (PyCoro_CheckExact(gen)) {
528
0
            msg = "coroutine ignored GeneratorExit";
529
0
        } else if (PyAsyncGen_CheckExact(gen)) {
530
0
            msg = ASYNC_GEN_IGNORED_EXIT_MSG;
531
0
        }
532
0
        Py_DECREF(retval);
533
0
        PyErr_SetString(PyExc_RuntimeError, msg);
534
0
        return NULL;
535
0
    }
536
377
    assert(PyErr_Occurred());
537
538
377
    if (PyErr_ExceptionMatches(PyExc_GeneratorExit)) {
539
377
        PyErr_Clear();          /* ignore this error */
540
377
        Py_RETURN_NONE;
541
377
    }
542
0
    return NULL;
543
377
}
544
545
// Set an exception for a gen.throw() call.
546
// Return 0 on success, -1 on failure.
547
int
548
_PyGen_SetException(PyObject *typ, PyObject *val, PyObject *tb)
549
36.3k
{
550
    /* First, check the traceback argument, replacing None with
551
       NULL. */
552
36.3k
    if (tb == Py_None) {
553
0
        tb = NULL;
554
0
    }
555
36.3k
    else if (tb != NULL && !PyTraceBack_Check(tb)) {
556
0
        PyErr_SetString(PyExc_TypeError,
557
0
            "throw() third argument must be a traceback object");
558
0
        return -1;
559
0
    }
560
561
36.3k
    Py_INCREF(typ);
562
36.3k
    Py_XINCREF(val);
563
36.3k
    Py_XINCREF(tb);
564
565
36.3k
    if (PyExceptionClass_Check(typ)) {
566
0
        PyErr_NormalizeException(&typ, &val, &tb);
567
0
    }
568
36.3k
    else if (PyExceptionInstance_Check(typ)) {
569
        /* Raising an instance.  The value should be a dummy. */
570
36.3k
        if (val && val != Py_None) {
571
0
            PyErr_SetString(PyExc_TypeError,
572
0
              "instance exception may not have a separate value");
573
0
            goto failed_throw;
574
0
        }
575
36.3k
        else {
576
            /* Normalize to raise <class>, <instance> */
577
36.3k
            Py_XSETREF(val, typ);
578
36.3k
            typ = Py_NewRef(PyExceptionInstance_Class(typ));
579
580
36.3k
            if (tb == NULL)
581
                /* Returns NULL if there's no traceback */
582
36.3k
                tb = PyException_GetTraceback(val);
583
36.3k
        }
584
36.3k
    }
585
0
    else {
586
        /* Not something you can raise.  throw() fails. */
587
0
        PyErr_Format(PyExc_TypeError,
588
0
                     "exceptions must be classes or instances "
589
0
                     "deriving from BaseException, not %s",
590
0
                     Py_TYPE(typ)->tp_name);
591
0
            goto failed_throw;
592
0
    }
593
594
36.3k
    PyErr_Restore(typ, val, tb);
595
36.3k
    return 0;
596
597
0
failed_throw:
598
    /* Didn't use our arguments, so restore their original refcounts */
599
0
    Py_DECREF(typ);
600
0
    Py_XDECREF(val);
601
0
    Py_XDECREF(tb);
602
0
    return -1;
603
36.3k
}
604
605
static PyObject *
606
gen_throw_current_exception(PyGenObject *gen)
607
36.3k
{
608
36.3k
    assert(FT_ATOMIC_LOAD_INT8_RELAXED(gen->gi_frame_state) == FRAME_EXECUTING);
609
610
36.3k
    PyObject *result;
611
36.3k
    if (gen_send_ex2(gen, Py_None, &result, 1) == PYGEN_RETURN) {
612
0
        return gen_set_stop_iteration(gen, result);
613
0
    }
614
36.3k
    return result;
615
36.3k
}
616
617
PyDoc_STRVAR(throw_doc,
618
"throw(value)\n\
619
throw(type[,value[,tb]])\n\
620
\n\
621
Raise exception in generator, return next yielded value or raise\n\
622
StopIteration.\n\
623
the (type, val, tb) signature is deprecated, \n\
624
and may be removed in a future version of Python.");
625
626
static PyObject *
627
_gen_throw(PyGenObject *gen, int close_on_genexit,
628
           PyObject *typ, PyObject *val, PyObject *tb)
629
36.3k
{
630
36.3k
    int8_t frame_state = FT_ATOMIC_LOAD_INT8_RELAXED(gen->gi_frame_state);
631
36.3k
    do {
632
36.3k
        if (frame_state == FRAME_EXECUTING) {
633
0
            gen_raise_already_executing_error(gen);
634
0
            return NULL;
635
0
        }
636
637
36.3k
        if (FRAME_STATE_FINISHED(frame_state)) {
638
0
            if (PyCoro_CheckExact(gen)) {
639
                /* `gen` is an exhausted coroutine: raise an error */
640
0
                PyErr_SetString(
641
0
                    PyExc_RuntimeError,
642
0
                    "cannot reuse already awaited coroutine");
643
0
                return NULL;
644
0
            }
645
0
            _PyGen_SetException(typ, val, tb);
646
0
            return NULL;
647
0
        }
648
649
36.3k
        assert((frame_state == FRAME_CREATED) ||
650
36.3k
               FRAME_STATE_SUSPENDED(frame_state));
651
36.3k
    } while (!_Py_GEN_TRY_SET_FRAME_STATE(gen, frame_state, FRAME_EXECUTING));
652
653
36.3k
    if (frame_state == FRAME_SUSPENDED_YIELD_FROM) {
654
0
        _PyInterpreterFrame *frame = &gen->gi_iframe;
655
0
        PyObject *yf = PyStackRef_AsPyObjectNew(_PyFrame_StackPeek(frame, 2));
656
0
        PyObject *ret;
657
0
        int err;
658
0
        if (PyErr_GivenExceptionMatches(typ, PyExc_GeneratorExit) &&
659
0
            close_on_genexit
660
0
        ) {
661
            /* Asynchronous generators *should not* be closed right away.
662
               We have to allow some awaits to work it through, hence the
663
               `close_on_genexit` parameter here.
664
            */
665
0
            err = gen_close_iter(yf);
666
0
            Py_DECREF(yf);
667
0
            if (err < 0) {
668
0
                return gen_throw_current_exception(gen);
669
0
            }
670
0
            goto throw_here;
671
0
        }
672
0
        PyThreadState *tstate = _PyThreadState_GET();
673
0
        assert(tstate != NULL);
674
0
        if (PyGen_CheckExact(yf) || PyCoro_CheckExact(yf)) {
675
            /* `yf` is a generator or a coroutine. */
676
677
            /* Link frame into the stack to enable complete backtraces. */
678
            /* XXX We should probably be updating the current frame somewhere in
679
               ceval.c. */
680
0
            _PyInterpreterFrame *prev = tstate->current_frame;
681
0
            frame->previous = prev;
682
0
            tstate->current_frame = frame;
683
            /* Close the generator that we are currently iterating with
684
               'yield from' or awaiting on with 'await'. */
685
0
            ret = _gen_throw((PyGenObject *)yf, close_on_genexit,
686
0
                             typ, val, tb);
687
0
            _PyThreadState_UpdateLastProfiledFrame(tstate, frame, prev);
688
0
            tstate->current_frame = prev;
689
0
            frame->previous = NULL;
690
0
        }
691
0
        else {
692
            /* `yf` is an iterator or a coroutine-like object. */
693
0
            PyObject *meth;
694
0
            if (PyObject_GetOptionalAttr(yf, &_Py_ID(throw), &meth) < 0) {
695
0
                Py_DECREF(yf);
696
0
                FT_ATOMIC_STORE_INT8_RELEASE(gen->gi_frame_state, frame_state);
697
0
                return NULL;
698
0
            }
699
0
            if (meth == NULL) {
700
0
                Py_DECREF(yf);
701
0
                goto throw_here;
702
0
            }
703
704
0
            _PyInterpreterFrame *prev = tstate->current_frame;
705
0
            frame->previous = prev;
706
0
            tstate->current_frame = frame;
707
0
            ret = PyObject_CallFunctionObjArgs(meth, typ, val, tb, NULL);
708
0
            _PyThreadState_UpdateLastProfiledFrame(tstate, frame, prev);
709
0
            tstate->current_frame = prev;
710
0
            frame->previous = NULL;
711
0
            Py_DECREF(meth);
712
0
        }
713
0
        Py_DECREF(yf);
714
0
        if (!ret) {
715
0
            return gen_throw_current_exception(gen);
716
0
        }
717
0
        FT_ATOMIC_STORE_INT8_RELEASE(gen->gi_frame_state, frame_state);
718
0
        return ret;
719
0
    }
720
721
36.3k
throw_here:
722
36.3k
    assert(FT_ATOMIC_LOAD_INT8_RELAXED(gen->gi_frame_state) == FRAME_EXECUTING);
723
36.3k
    if (_PyGen_SetException(typ, val, tb) < 0) {
724
0
        FT_ATOMIC_STORE_INT8_RELEASE(gen->gi_frame_state, frame_state);
725
0
        return NULL;
726
0
    }
727
36.3k
    return gen_throw_current_exception(gen);
728
36.3k
}
729
730
731
static PyObject *
732
gen_throw(PyObject *op, PyObject *const *args, Py_ssize_t nargs)
733
36.3k
{
734
36.3k
    PyGenObject *gen = _PyGen_CAST(op);
735
36.3k
    PyObject *typ;
736
36.3k
    PyObject *tb = NULL;
737
36.3k
    PyObject *val = NULL;
738
739
36.3k
    if (!_PyArg_CheckPositional("throw", nargs, 1, 3)) {
740
0
        return NULL;
741
0
    }
742
36.3k
    if (nargs > 1) {
743
0
        if (PyErr_WarnEx(PyExc_DeprecationWarning,
744
0
                            "the (type, exc, tb) signature of throw() is deprecated, "
745
0
                            "use the single-arg signature instead.",
746
0
                            1) < 0) {
747
0
            return NULL;
748
0
        }
749
0
    }
750
36.3k
    typ = args[0];
751
36.3k
    if (nargs == 3) {
752
0
        val = args[1];
753
0
        tb = args[2];
754
0
    }
755
36.3k
    else if (nargs == 2) {
756
0
        val = args[1];
757
0
    }
758
36.3k
    return _gen_throw(gen, 1, typ, val, tb);
759
36.3k
}
760
761
762
static PyObject *
763
gen_iternext(PyObject *self)
764
64.1M
{
765
64.1M
    assert(PyGen_CheckExact(self) || PyCoro_CheckExact(self));
766
64.1M
    PyGenObject *gen = _PyGen_CAST(self);
767
768
64.1M
    PyObject *result;
769
64.1M
    if (gen_send_ex(gen, NULL, &result) == PYGEN_RETURN) {
770
0
        if (result != Py_None) {
771
0
            _PyGen_SetStopIterationValue(result);
772
0
        }
773
0
        Py_CLEAR(result);
774
0
    }
775
64.1M
    return result;
776
64.1M
}
777
778
/*
779
 * Set StopIteration with specified value.  Value can be arbitrary object
780
 * or NULL.
781
 *
782
 * Returns 0 if StopIteration is set and -1 if any other exception is set.
783
 */
784
int
785
_PyGen_SetStopIterationValue(PyObject *value)
786
0
{
787
0
    assert(!PyErr_Occurred());
788
    // Construct an exception instance manually with PyObject_CallOneArg()
789
    // but use PyErr_SetRaisedException() instead of PyErr_SetObject() as
790
    // PyErr_SetObject(exc_type, value) has a fast path when 'value'
791
    // is a tuple, where the value of the StopIteration exception would be
792
    // set to 'value[0]' instead of 'value'.
793
0
    PyObject *exc = value == NULL
794
0
        ? PyObject_CallNoArgs(PyExc_StopIteration)
795
0
        : PyObject_CallOneArg(PyExc_StopIteration, value);
796
0
    if (exc == NULL) {
797
0
        return -1;
798
0
    }
799
0
    PyErr_SetRaisedException(exc /* stolen */);
800
0
    return 0;
801
0
}
802
803
/*
804
 *   If StopIteration exception is set, fetches its 'value'
805
 *   attribute if any, otherwise sets pvalue to None.
806
 *
807
 *   Returns 0 if no exception or StopIteration is set.
808
 *   If any other exception is set, returns -1 and leaves
809
 *   pvalue unchanged.
810
 */
811
812
int
813
_PyGen_FetchStopIterationValue(PyObject **pvalue)
814
0
{
815
0
    PyObject *value = NULL;
816
0
    if (PyErr_ExceptionMatches(PyExc_StopIteration)) {
817
0
        PyObject *exc = PyErr_GetRaisedException();
818
0
        value = Py_NewRef(((PyStopIterationObject *)exc)->value);
819
0
        Py_DECREF(exc);
820
0
    } else if (PyErr_Occurred()) {
821
0
        return -1;
822
0
    }
823
0
    if (value == NULL) {
824
0
        value = Py_NewRef(Py_None);
825
0
    }
826
0
    *pvalue = value;
827
0
    return 0;
828
0
}
829
830
static PyObject *
831
gen_repr(PyObject *self)
832
0
{
833
0
    PyGenObject *gen = _PyGen_CAST(self);
834
0
    return PyUnicode_FromFormat("<generator object %S at %p>",
835
0
                                gen->gi_qualname, gen);
836
0
}
837
838
static PyObject *
839
gen_get_name(PyObject *self, void *Py_UNUSED(ignored))
840
0
{
841
0
    PyGenObject *op = _PyGen_CAST(self);
842
0
    PyObject *name = FT_ATOMIC_LOAD_PTR_ACQUIRE(op->gi_name);
843
0
    return Py_NewRef(name);
844
0
}
845
846
static int
847
gen_set_name(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
848
0
{
849
0
    PyGenObject *op = _PyGen_CAST(self);
850
    /* Not legal to del gen.gi_name or to set it to anything
851
     * other than a string object. */
852
0
    if (value == NULL || !PyUnicode_Check(value)) {
853
0
        PyErr_SetString(PyExc_TypeError,
854
0
                        "__name__ must be set to a string object");
855
0
        return -1;
856
0
    }
857
0
    Py_BEGIN_CRITICAL_SECTION(self);
858
    // gh-133931: To prevent use-after-free from other threads that reference
859
    // the gi_name.
860
0
    _PyObject_XSetRefDelayed(&op->gi_name, Py_NewRef(value));
861
0
    Py_END_CRITICAL_SECTION();
862
0
    return 0;
863
0
}
864
865
static PyObject *
866
gen_get_qualname(PyObject *self, void *Py_UNUSED(ignored))
867
0
{
868
0
    PyGenObject *op = _PyGen_CAST(self);
869
0
    PyObject *qualname = FT_ATOMIC_LOAD_PTR_ACQUIRE(op->gi_qualname);
870
0
    return Py_NewRef(qualname);
871
0
}
872
873
static int
874
gen_set_qualname(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
875
0
{
876
0
    PyGenObject *op = _PyGen_CAST(self);
877
    /* Not legal to del gen.__qualname__ or to set it to anything
878
     * other than a string object. */
879
0
    if (value == NULL || !PyUnicode_Check(value)) {
880
0
        PyErr_SetString(PyExc_TypeError,
881
0
                        "__qualname__ must be set to a string object");
882
0
        return -1;
883
0
    }
884
0
    Py_BEGIN_CRITICAL_SECTION(self);
885
    // gh-133931: To prevent use-after-free from other threads that reference
886
    // the gi_qualname.
887
0
    _PyObject_XSetRefDelayed(&op->gi_qualname, Py_NewRef(value));
888
0
    Py_END_CRITICAL_SECTION();
889
0
    return 0;
890
0
}
891
892
static PyObject *
893
gen_getyieldfrom(PyObject *self, void *Py_UNUSED(ignored))
894
0
{
895
0
    PyGenObject *gen = _PyGen_CAST(self);
896
#ifdef Py_GIL_DISABLED
897
    int8_t frame_state = _Py_atomic_load_int8_relaxed(&gen->gi_frame_state);
898
    do {
899
        if (frame_state != FRAME_SUSPENDED_YIELD_FROM &&
900
            frame_state != FRAME_SUSPENDED_YIELD_FROM_LOCKED)
901
        {
902
            Py_RETURN_NONE;
903
        }
904
    } while (!_Py_GEN_TRY_SET_FRAME_STATE(gen, frame_state, FRAME_SUSPENDED_YIELD_FROM_LOCKED));
905
906
    PyObject *result = PyStackRef_AsPyObjectNew(_PyFrame_StackPeek(&gen->gi_iframe, 2));
907
    _Py_atomic_store_int8_release(&gen->gi_frame_state, FRAME_SUSPENDED_YIELD_FROM);
908
    return result;
909
#else
910
0
    int8_t frame_state = gen->gi_frame_state;
911
0
    if (frame_state != FRAME_SUSPENDED_YIELD_FROM) {
912
0
        Py_RETURN_NONE;
913
0
    }
914
0
    return PyStackRef_AsPyObjectNew(_PyFrame_StackPeek(&gen->gi_iframe, 2));
915
0
#endif
916
0
}
917
918
919
static PyObject *
920
gen_getrunning(PyObject *self, void *Py_UNUSED(ignored))
921
0
{
922
0
    PyGenObject *gen = _PyGen_CAST(self);
923
0
    int8_t frame_state = FT_ATOMIC_LOAD_INT8_RELAXED(gen->gi_frame_state);
924
0
    return frame_state == FRAME_EXECUTING ? Py_True : Py_False;
925
0
}
926
927
static PyObject *
928
gen_getsuspended(PyObject *self, void *Py_UNUSED(ignored))
929
0
{
930
0
    PyGenObject *gen = _PyGen_CAST(self);
931
0
    int8_t frame_state = FT_ATOMIC_LOAD_INT8_RELAXED(gen->gi_frame_state);
932
0
    return FRAME_STATE_SUSPENDED(frame_state) ? Py_True : Py_False;
933
0
}
934
935
static PyObject *
936
gen_getstate(PyObject *self, void *Py_UNUSED(ignored))
937
0
{
938
0
    PyGenObject *gen = _PyGen_CAST(self);
939
0
    int8_t frame_state = FT_ATOMIC_LOAD_INT8_RELAXED(gen->gi_frame_state);
940
941
0
    static PyObject *const state_strings[] = {
942
0
        [FRAME_CREATED] = &_Py_ID(GEN_CREATED),
943
0
        [FRAME_SUSPENDED] = &_Py_ID(GEN_SUSPENDED),
944
0
        [FRAME_SUSPENDED_YIELD_FROM] = &_Py_ID(GEN_SUSPENDED),
945
0
        [FRAME_SUSPENDED_YIELD_FROM_LOCKED] = &_Py_ID(GEN_SUSPENDED),
946
0
        [FRAME_EXECUTING] = &_Py_ID(GEN_RUNNING),
947
0
        [FRAME_CLEARED] = &_Py_ID(GEN_CLOSED),
948
0
    };
949
950
0
    assert(frame_state >= 0 &&
951
0
           (size_t)frame_state < Py_ARRAY_LENGTH(state_strings));
952
0
    return state_strings[frame_state];
953
0
}
954
955
static PyObject *
956
_gen_getframe(PyGenObject *gen, const char *const name)
957
0
{
958
0
    if (PySys_Audit("object.__getattr__", "Os", gen, name) < 0) {
959
0
        return NULL;
960
0
    }
961
0
    int8_t frame_state = FT_ATOMIC_LOAD_INT8_RELAXED(gen->gi_frame_state);
962
0
    if (FRAME_STATE_FINISHED(frame_state)) {
963
0
        Py_RETURN_NONE;
964
0
    }
965
0
    PyObject *frame = NULL;
966
0
    Py_BEGIN_CRITICAL_SECTION(gen);
967
0
    frame_state = FT_ATOMIC_LOAD_INT8_RELAXED(gen->gi_frame_state);
968
0
    if (FRAME_STATE_FINISHED(frame_state)) {
969
0
        frame = Py_None;
970
0
    }
971
0
    else {
972
0
        frame = _Py_XNewRef((PyObject *)_PyFrame_GetFrameObject(&gen->gi_iframe));
973
0
    }
974
0
    Py_END_CRITICAL_SECTION();
975
0
    return frame;
976
0
}
977
978
static PyObject *
979
gen_getframe(PyObject *self, void *Py_UNUSED(ignored))
980
0
{
981
0
    PyGenObject *gen = _PyGen_CAST(self);
982
0
    return _gen_getframe(gen, "gi_frame");
983
0
}
984
985
static PyObject *
986
_gen_getcode(PyGenObject *gen, const char *const name)
987
0
{
988
0
    if (PySys_Audit("object.__getattr__", "Os", gen, name) < 0) {
989
0
        return NULL;
990
0
    }
991
0
    return Py_NewRef(_PyGen_GetCode(gen));
992
0
}
993
994
static PyObject *
995
gen_getcode(PyObject *self, void *Py_UNUSED(ignored))
996
0
{
997
0
    PyGenObject *gen = _PyGen_CAST(self);
998
0
    return _gen_getcode(gen, "gi_code");
999
0
}
1000
1001
static PyGetSetDef gen_getsetlist[] = {
1002
    {"__name__", gen_get_name, gen_set_name,
1003
     PyDoc_STR("name of the generator")},
1004
    {"__qualname__", gen_get_qualname, gen_set_qualname,
1005
     PyDoc_STR("qualified name of the generator")},
1006
    {"gi_yieldfrom", gen_getyieldfrom, NULL,
1007
     PyDoc_STR("object being iterated by yield from, or None")},
1008
    {"gi_running", gen_getrunning, NULL, NULL},
1009
    {"gi_frame", gen_getframe,  NULL, NULL},
1010
    {"gi_suspended", gen_getsuspended,  NULL, NULL},
1011
    {"gi_code", gen_getcode,  NULL, NULL},
1012
    {"gi_state", gen_getstate, NULL,
1013
     PyDoc_STR("state of the generator")},
1014
    {NULL} /* Sentinel */
1015
};
1016
1017
static PyMemberDef gen_memberlist[] = {
1018
    {NULL}      /* Sentinel */
1019
};
1020
1021
static PyObject *
1022
gen_sizeof(PyObject *op, PyObject *Py_UNUSED(ignored))
1023
0
{
1024
0
    PyGenObject *gen = _PyGen_CAST(op);
1025
0
    Py_ssize_t res;
1026
0
    res = offsetof(PyGenObject, gi_iframe) + offsetof(_PyInterpreterFrame, localsplus);
1027
0
    PyCodeObject *code = _PyGen_GetCode(gen);
1028
0
    res += _PyFrame_NumSlotsForCodeObject(code) * sizeof(PyObject *);
1029
0
    return PyLong_FromSsize_t(res);
1030
0
}
1031
1032
PyDoc_STRVAR(sizeof__doc__,
1033
"gen.__sizeof__() -> size of gen in memory, in bytes");
1034
1035
static PyMethodDef gen_methods[] = {
1036
    {"send", gen_send, METH_O, send_doc},
1037
    {"throw", _PyCFunction_CAST(gen_throw), METH_FASTCALL, throw_doc},
1038
    {"close", gen_close, METH_NOARGS, close_doc},
1039
    {"__sizeof__", gen_sizeof, METH_NOARGS, sizeof__doc__},
1040
    {"__class_getitem__", Py_GenericAlias, METH_O|METH_CLASS,
1041
     PyDoc_STR("generators are generic over the types of their yield, send, and return values")},
1042
    {NULL, NULL}        /* Sentinel */
1043
};
1044
1045
static PyAsyncMethods gen_as_async = {
1046
    0,                                          /* am_await */
1047
    0,                                          /* am_aiter */
1048
    0,                                          /* am_anext */
1049
    PyGen_am_send,                              /* am_send  */
1050
};
1051
1052
1053
PyTypeObject PyGen_Type = {
1054
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
1055
    "generator",                                /* tp_name */
1056
    offsetof(PyGenObject, gi_iframe.localsplus), /* tp_basicsize */
1057
    sizeof(PyObject *),                         /* tp_itemsize */
1058
    /* methods */
1059
    gen_dealloc,                                /* tp_dealloc */
1060
    0,                                          /* tp_vectorcall_offset */
1061
    0,                                          /* tp_getattr */
1062
    0,                                          /* tp_setattr */
1063
    &gen_as_async,                              /* tp_as_async */
1064
    gen_repr,                                   /* tp_repr */
1065
    0,                                          /* tp_as_number */
1066
    0,                                          /* tp_as_sequence */
1067
    0,                                          /* tp_as_mapping */
1068
    0,                                          /* tp_hash */
1069
    0,                                          /* tp_call */
1070
    0,                                          /* tp_str */
1071
    PyObject_GenericGetAttr,                    /* tp_getattro */
1072
    0,                                          /* tp_setattro */
1073
    0,                                          /* tp_as_buffer */
1074
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,    /* tp_flags */
1075
    0,                                          /* tp_doc */
1076
    gen_traverse,                               /* tp_traverse */
1077
    0,                                          /* tp_clear */
1078
    0,                                          /* tp_richcompare */
1079
    offsetof(PyGenObject, gi_weakreflist),      /* tp_weaklistoffset */
1080
    PyObject_SelfIter,                          /* tp_iter */
1081
    gen_iternext,                               /* tp_iternext */
1082
    gen_methods,                                /* tp_methods */
1083
    gen_memberlist,                             /* tp_members */
1084
    gen_getsetlist,                             /* tp_getset */
1085
    0,                                          /* tp_base */
1086
    0,                                          /* tp_dict */
1087
1088
    0,                                          /* tp_descr_get */
1089
    0,                                          /* tp_descr_set */
1090
    0,                                          /* tp_dictoffset */
1091
    0,                                          /* tp_init */
1092
    0,                                          /* tp_alloc */
1093
    0,                                          /* tp_new */
1094
    0,                                          /* tp_free */
1095
    0,                                          /* tp_is_gc */
1096
    0,                                          /* tp_bases */
1097
    0,                                          /* tp_mro */
1098
    0,                                          /* tp_cache */
1099
    0,                                          /* tp_subclasses */
1100
    0,                                          /* tp_weaklist */
1101
    0,                                          /* tp_del */
1102
    0,                                          /* tp_version_tag */
1103
    gen_finalize,                               /* tp_finalize */
1104
};
1105
1106
static PyObject *
1107
make_gen(PyTypeObject *type, PyFunctionObject *func)
1108
42.4M
{
1109
42.4M
    PyCodeObject *code = (PyCodeObject *)func->func_code;
1110
42.4M
    int slots = _PyFrame_NumSlotsForCodeObject(code);
1111
42.4M
    PyGenObject *gen = PyObject_GC_NewVar(PyGenObject, type, slots);
1112
42.4M
    if (gen == NULL) {
1113
0
        return NULL;
1114
0
    }
1115
42.4M
    gen->gi_frame_state = FRAME_CLEARED;
1116
42.4M
    gen->gi_weakreflist = NULL;
1117
42.4M
    gen->gi_exc_state.exc_value = NULL;
1118
42.4M
    gen->gi_exc_state.previous_item = NULL;
1119
42.4M
    gen->gi_iframe.f_executable = PyStackRef_None;
1120
42.4M
    PyObject *name = FT_ATOMIC_LOAD_PTR_ACQUIRE(func->func_name);
1121
42.4M
    assert(name != NULL);
1122
42.4M
    gen->gi_name = Py_NewRef(name);
1123
42.4M
    PyObject *qualname = FT_ATOMIC_LOAD_PTR_ACQUIRE(func->func_qualname);
1124
42.4M
    assert(qualname != NULL);
1125
42.4M
    gen->gi_qualname = Py_NewRef(qualname);
1126
42.4M
    _PyObject_GC_TRACK(gen);
1127
42.4M
    return (PyObject *)gen;
1128
42.4M
}
1129
1130
PyObject *
1131
_Py_MakeCoro(PyFunctionObject *func)
1132
42.4M
{
1133
42.4M
    int coro_flags = ((PyCodeObject *)func->func_code)->co_flags &
1134
42.4M
        (CO_GENERATOR | CO_COROUTINE | CO_ASYNC_GENERATOR);
1135
42.4M
    assert(coro_flags);
1136
42.4M
    if (coro_flags == CO_GENERATOR) {
1137
42.4M
        return make_gen(&PyGen_Type, func);
1138
42.4M
    }
1139
74
    if (coro_flags == CO_ASYNC_GENERATOR) {
1140
37
        PyAsyncGenObject *ag;
1141
37
        ag = (PyAsyncGenObject *)make_gen(&PyAsyncGen_Type, func);
1142
37
        if (ag == NULL) {
1143
0
            return NULL;
1144
0
        }
1145
37
        ag->ag_origin_or_finalizer = NULL;
1146
37
        ag->ag_closed = 0;
1147
37
        ag->ag_hooks_inited = 0;
1148
37
        ag->ag_running_async = 0;
1149
37
        return (PyObject*)ag;
1150
37
    }
1151
1152
74
    assert (coro_flags == CO_COROUTINE);
1153
37
    PyObject *coro = make_gen(&PyCoro_Type, func);
1154
37
    if (!coro) {
1155
0
        return NULL;
1156
0
    }
1157
37
    PyThreadState *tstate = _PyThreadState_GET();
1158
37
    int origin_depth = tstate->coroutine_origin_tracking_depth;
1159
1160
37
    if (origin_depth == 0) {
1161
37
        ((PyCoroObject *)coro)->cr_origin_or_finalizer = NULL;
1162
37
    } else {
1163
0
        _PyInterpreterFrame *frame = tstate->current_frame;
1164
0
        assert(frame);
1165
0
        assert(_PyFrame_IsIncomplete(frame));
1166
0
        frame = _PyFrame_GetFirstComplete(frame->previous);
1167
0
        PyObject *cr_origin = _PyCoro_ComputeOrigin(origin_depth, frame);
1168
0
        ((PyCoroObject *)coro)->cr_origin_or_finalizer = cr_origin;
1169
0
        if (!cr_origin) {
1170
0
            Py_DECREF(coro);
1171
0
            return NULL;
1172
0
        }
1173
0
    }
1174
37
    return coro;
1175
37
}
1176
1177
static PyObject *
1178
gen_new_with_qualname(PyTypeObject *type, PyFrameObject *f,
1179
                      PyObject *name, PyObject *qualname)
1180
0
{
1181
0
    PyCodeObject *code = _PyFrame_GetCode(f->f_frame);
1182
0
    int size = code->co_nlocalsplus + code->co_stacksize;
1183
0
    PyGenObject *gen = PyObject_GC_NewVar(PyGenObject, type, size);
1184
0
    if (gen == NULL) {
1185
0
        Py_DECREF(f);
1186
0
        return NULL;
1187
0
    }
1188
    /* Copy the frame */
1189
0
    assert(f->f_frame->frame_obj == NULL);
1190
0
    assert(f->f_frame->owner == FRAME_OWNED_BY_FRAME_OBJECT);
1191
0
    _PyInterpreterFrame *frame = &gen->gi_iframe;
1192
0
    _PyFrame_Copy((_PyInterpreterFrame *)f->_f_frame_data, frame);
1193
0
    gen->gi_frame_state = FRAME_CREATED;
1194
0
    assert(frame->frame_obj == f);
1195
0
    f->f_frame = frame;
1196
0
    frame->owner = FRAME_OWNED_BY_GENERATOR;
1197
0
    assert(PyObject_GC_IsTracked((PyObject *)f));
1198
0
    Py_DECREF(f);
1199
0
    gen->gi_weakreflist = NULL;
1200
0
    gen->gi_exc_state.exc_value = NULL;
1201
0
    gen->gi_exc_state.previous_item = NULL;
1202
0
    if (name != NULL)
1203
0
        gen->gi_name = Py_NewRef(name);
1204
0
    else
1205
0
        gen->gi_name = Py_NewRef(_PyGen_GetCode(gen)->co_name);
1206
0
    if (qualname != NULL)
1207
0
        gen->gi_qualname = Py_NewRef(qualname);
1208
0
    else
1209
0
        gen->gi_qualname = Py_NewRef(_PyGen_GetCode(gen)->co_qualname);
1210
0
    _PyObject_GC_TRACK(gen);
1211
0
    return (PyObject *)gen;
1212
0
}
1213
1214
PyObject *
1215
PyGen_NewWithQualName(PyFrameObject *f, PyObject *name, PyObject *qualname)
1216
0
{
1217
0
    return gen_new_with_qualname(&PyGen_Type, f, name, qualname);
1218
0
}
1219
1220
PyObject *
1221
PyGen_New(PyFrameObject *f)
1222
0
{
1223
0
    return gen_new_with_qualname(&PyGen_Type, f, NULL, NULL);
1224
0
}
1225
1226
/* Coroutine Object */
1227
1228
typedef struct {
1229
    PyObject_HEAD
1230
    PyCoroObject *cw_coroutine;
1231
} PyCoroWrapper;
1232
1233
#define _PyCoroWrapper_CAST(op) \
1234
0
    (assert(Py_IS_TYPE((op), &_PyCoroWrapper_Type)), \
1235
0
     _Py_CAST(PyCoroWrapper*, (op)))
1236
1237
1238
static int
1239
gen_is_coroutine(PyObject *o)
1240
0
{
1241
0
    if (PyGen_CheckExact(o)) {
1242
0
        PyCodeObject *code = _PyGen_GetCode((PyGenObject*)o);
1243
0
        if (code->co_flags & CO_ITERABLE_COROUTINE) {
1244
0
            return 1;
1245
0
        }
1246
0
    }
1247
0
    return 0;
1248
0
}
1249
1250
/*
1251
 *   This helper function returns an awaitable for `o`:
1252
 *     - `o` if `o` is a coroutine-object;
1253
 *     - `type(o)->tp_as_async->am_await(o)`
1254
 *
1255
 *   Raises a TypeError if it's not possible to return
1256
 *   an awaitable and returns NULL.
1257
 */
1258
PyObject *
1259
_PyCoro_GetAwaitableIter(PyObject *o)
1260
0
{
1261
0
    unaryfunc getter = NULL;
1262
0
    PyTypeObject *ot;
1263
1264
0
    if (PyCoro_CheckExact(o) || gen_is_coroutine(o)) {
1265
        /* 'o' is a coroutine. */
1266
0
        return Py_NewRef(o);
1267
0
    }
1268
1269
0
    ot = Py_TYPE(o);
1270
0
    if (ot->tp_as_async != NULL) {
1271
0
        getter = ot->tp_as_async->am_await;
1272
0
    }
1273
0
    if (getter != NULL) {
1274
0
        PyObject *res = (*getter)(o);
1275
0
        if (res != NULL) {
1276
0
            if (PyCoro_CheckExact(res) || gen_is_coroutine(res)) {
1277
                /* __await__ must return an *iterator*, not
1278
                   a coroutine or another awaitable (see PEP 492) */
1279
0
                PyErr_Format(PyExc_TypeError,
1280
0
                             "%T.__await__() must return an iterator, "
1281
0
                             "not coroutine", o);
1282
0
                Py_CLEAR(res);
1283
0
            } else if (!PyIter_Check(res)) {
1284
0
                PyErr_Format(PyExc_TypeError,
1285
0
                             "%T.__await__() must return an iterator, "
1286
0
                             "not %T", o, res);
1287
0
                Py_CLEAR(res);
1288
0
            }
1289
0
        }
1290
0
        return res;
1291
0
    }
1292
1293
0
    PyErr_Format(PyExc_TypeError,
1294
0
                 "'%.100s' object can't be awaited",
1295
0
                 ot->tp_name);
1296
0
    return NULL;
1297
0
}
1298
1299
static PyObject *
1300
coro_repr(PyObject *self)
1301
0
{
1302
0
    PyCoroObject *coro = _PyCoroObject_CAST(self);
1303
0
    return PyUnicode_FromFormat("<coroutine object %S at %p>",
1304
0
                                coro->cr_qualname, coro);
1305
0
}
1306
1307
static PyObject *
1308
coro_await(PyObject *coro)
1309
0
{
1310
0
    PyCoroWrapper *cw = PyObject_GC_New(PyCoroWrapper, &_PyCoroWrapper_Type);
1311
0
    if (cw == NULL) {
1312
0
        return NULL;
1313
0
    }
1314
0
    cw->cw_coroutine = (PyCoroObject*)Py_NewRef(coro);
1315
0
    _PyObject_GC_TRACK(cw);
1316
0
    return (PyObject *)cw;
1317
0
}
1318
1319
static PyObject *
1320
cr_getframe(PyObject *coro, void *Py_UNUSED(ignored))
1321
0
{
1322
0
    return _gen_getframe(_PyGen_CAST(coro), "cr_frame");
1323
0
}
1324
1325
static PyObject *
1326
cr_getcode(PyObject *coro, void *Py_UNUSED(ignored))
1327
0
{
1328
0
    return _gen_getcode(_PyGen_CAST(coro), "cr_code");
1329
0
}
1330
1331
static PyObject *
1332
cr_getstate(PyObject *self, void *Py_UNUSED(ignored))
1333
0
{
1334
0
    PyGenObject *gen = _PyGen_CAST(self);
1335
0
    int8_t frame_state = FT_ATOMIC_LOAD_INT8_RELAXED(gen->gi_frame_state);
1336
1337
0
    static PyObject *const state_strings[] = {
1338
0
        [FRAME_CREATED] = &_Py_ID(CORO_CREATED),
1339
0
        [FRAME_SUSPENDED] = &_Py_ID(CORO_SUSPENDED),
1340
0
        [FRAME_SUSPENDED_YIELD_FROM] = &_Py_ID(CORO_SUSPENDED),
1341
0
        [FRAME_SUSPENDED_YIELD_FROM_LOCKED] = &_Py_ID(CORO_SUSPENDED),
1342
0
        [FRAME_EXECUTING] = &_Py_ID(CORO_RUNNING),
1343
0
        [FRAME_CLEARED] = &_Py_ID(CORO_CLOSED),
1344
0
    };
1345
1346
0
    assert(frame_state >= 0 &&
1347
0
           (size_t)frame_state < Py_ARRAY_LENGTH(state_strings));
1348
0
    return state_strings[frame_state];
1349
0
}
1350
1351
static PyGetSetDef coro_getsetlist[] = {
1352
    {"__name__", gen_get_name, gen_set_name,
1353
     PyDoc_STR("name of the coroutine")},
1354
    {"__qualname__", gen_get_qualname, gen_set_qualname,
1355
     PyDoc_STR("qualified name of the coroutine")},
1356
    {"cr_await", gen_getyieldfrom, NULL,
1357
     PyDoc_STR("object being awaited on, or None")},
1358
    {"cr_running", gen_getrunning, NULL, NULL},
1359
    {"cr_frame", cr_getframe, NULL, NULL},
1360
    {"cr_code", cr_getcode, NULL, NULL},
1361
    {"cr_suspended", gen_getsuspended, NULL, NULL},
1362
    {"cr_state", cr_getstate, NULL,
1363
     PyDoc_STR("state of the coroutine")},
1364
    {NULL} /* Sentinel */
1365
};
1366
1367
static PyMemberDef coro_memberlist[] = {
1368
    {"cr_origin",    _Py_T_OBJECT, offsetof(PyCoroObject, cr_origin_or_finalizer),   Py_READONLY},
1369
    {NULL}      /* Sentinel */
1370
};
1371
1372
PyDoc_STRVAR(coro_send_doc,
1373
"send(arg) -> send 'arg' into coroutine,\n\
1374
return next iterated value or raise StopIteration.");
1375
1376
PyDoc_STRVAR(coro_throw_doc,
1377
"throw(value)\n\
1378
throw(type[,value[,traceback]])\n\
1379
\n\
1380
Raise exception in coroutine, return next iterated value or raise\n\
1381
StopIteration.\n\
1382
the (type, val, tb) signature is deprecated, \n\
1383
and may be removed in a future version of Python.");
1384
1385
1386
PyDoc_STRVAR(coro_close_doc,
1387
"close() -> raise GeneratorExit inside coroutine.");
1388
1389
static PyMethodDef coro_methods[] = {
1390
    {"send", gen_send, METH_O, coro_send_doc},
1391
    {"throw",_PyCFunction_CAST(gen_throw), METH_FASTCALL, coro_throw_doc},
1392
    {"close", gen_close, METH_NOARGS, coro_close_doc},
1393
    {"__sizeof__", gen_sizeof, METH_NOARGS, sizeof__doc__},
1394
    {"__class_getitem__", Py_GenericAlias, METH_O|METH_CLASS,
1395
     PyDoc_STR("coroutines are generic over the types of their yield, send, and return values")},
1396
    {NULL, NULL}        /* Sentinel */
1397
};
1398
1399
static PyAsyncMethods coro_as_async = {
1400
    coro_await,                                 /* am_await */
1401
    0,                                          /* am_aiter */
1402
    0,                                          /* am_anext */
1403
    PyGen_am_send,                              /* am_send  */
1404
};
1405
1406
PyTypeObject PyCoro_Type = {
1407
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
1408
    "coroutine",                                /* tp_name */
1409
    offsetof(PyCoroObject, cr_iframe.localsplus),/* tp_basicsize */
1410
    sizeof(PyObject *),                         /* tp_itemsize */
1411
    /* methods */
1412
    gen_dealloc,                                /* tp_dealloc */
1413
    0,                                          /* tp_vectorcall_offset */
1414
    0,                                          /* tp_getattr */
1415
    0,                                          /* tp_setattr */
1416
    &coro_as_async,                             /* tp_as_async */
1417
    coro_repr,                                  /* tp_repr */
1418
    0,                                          /* tp_as_number */
1419
    0,                                          /* tp_as_sequence */
1420
    0,                                          /* tp_as_mapping */
1421
    0,                                          /* tp_hash */
1422
    0,                                          /* tp_call */
1423
    0,                                          /* tp_str */
1424
    PyObject_GenericGetAttr,                    /* tp_getattro */
1425
    0,                                          /* tp_setattro */
1426
    0,                                          /* tp_as_buffer */
1427
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,    /* tp_flags */
1428
    0,                                          /* tp_doc */
1429
    gen_traverse,                               /* tp_traverse */
1430
    0,                                          /* tp_clear */
1431
    0,                                          /* tp_richcompare */
1432
    offsetof(PyCoroObject, cr_weakreflist),     /* tp_weaklistoffset */
1433
    0,                                          /* tp_iter */
1434
    0,                                          /* tp_iternext */
1435
    coro_methods,                               /* tp_methods */
1436
    coro_memberlist,                            /* tp_members */
1437
    coro_getsetlist,                            /* tp_getset */
1438
    0,                                          /* tp_base */
1439
    0,                                          /* tp_dict */
1440
    0,                                          /* tp_descr_get */
1441
    0,                                          /* tp_descr_set */
1442
    0,                                          /* tp_dictoffset */
1443
    0,                                          /* tp_init */
1444
    0,                                          /* tp_alloc */
1445
    0,                                          /* tp_new */
1446
    0,                                          /* tp_free */
1447
    0,                                          /* tp_is_gc */
1448
    0,                                          /* tp_bases */
1449
    0,                                          /* tp_mro */
1450
    0,                                          /* tp_cache */
1451
    0,                                          /* tp_subclasses */
1452
    0,                                          /* tp_weaklist */
1453
    0,                                          /* tp_del */
1454
    0,                                          /* tp_version_tag */
1455
    gen_finalize,                               /* tp_finalize */
1456
};
1457
1458
static void
1459
coro_wrapper_dealloc(PyObject *self)
1460
0
{
1461
0
    PyCoroWrapper *cw = _PyCoroWrapper_CAST(self);
1462
0
    _PyObject_GC_UNTRACK((PyObject *)cw);
1463
0
    Py_CLEAR(cw->cw_coroutine);
1464
0
    PyObject_GC_Del(cw);
1465
0
}
1466
1467
static PyObject *
1468
coro_wrapper_iternext(PyObject *self)
1469
0
{
1470
0
    PyCoroWrapper *cw = _PyCoroWrapper_CAST(self);
1471
0
    return gen_iternext((PyObject *)cw->cw_coroutine);
1472
0
}
1473
1474
static PyObject *
1475
coro_wrapper_send(PyObject *self, PyObject *arg)
1476
0
{
1477
0
    PyCoroWrapper *cw = _PyCoroWrapper_CAST(self);
1478
0
    return gen_send((PyObject *)cw->cw_coroutine, arg);
1479
0
}
1480
1481
static PyObject *
1482
coro_wrapper_throw(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
1483
0
{
1484
0
    PyCoroWrapper *cw = _PyCoroWrapper_CAST(self);
1485
0
    return gen_throw((PyObject*)cw->cw_coroutine, args, nargs);
1486
0
}
1487
1488
static PyObject *
1489
coro_wrapper_close(PyObject *self, PyObject *args)
1490
0
{
1491
0
    PyCoroWrapper *cw = _PyCoroWrapper_CAST(self);
1492
0
    return gen_close((PyObject *)cw->cw_coroutine, args);
1493
0
}
1494
1495
static int
1496
coro_wrapper_traverse(PyObject *self, visitproc visit, void *arg)
1497
0
{
1498
0
    PyCoroWrapper *cw = _PyCoroWrapper_CAST(self);
1499
0
    Py_VISIT((PyObject *)cw->cw_coroutine);
1500
0
    return 0;
1501
0
}
1502
1503
static PyMethodDef coro_wrapper_methods[] = {
1504
    {"send", coro_wrapper_send, METH_O, coro_send_doc},
1505
    {"throw", _PyCFunction_CAST(coro_wrapper_throw), METH_FASTCALL,
1506
     coro_throw_doc},
1507
    {"close", coro_wrapper_close, METH_NOARGS, coro_close_doc},
1508
    {NULL, NULL}        /* Sentinel */
1509
};
1510
1511
PyTypeObject _PyCoroWrapper_Type = {
1512
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
1513
    "coroutine_wrapper",
1514
    sizeof(PyCoroWrapper),                      /* tp_basicsize */
1515
    0,                                          /* tp_itemsize */
1516
    coro_wrapper_dealloc,                       /* destructor tp_dealloc */
1517
    0,                                          /* tp_vectorcall_offset */
1518
    0,                                          /* tp_getattr */
1519
    0,                                          /* tp_setattr */
1520
    0,                                          /* tp_as_async */
1521
    0,                                          /* tp_repr */
1522
    0,                                          /* tp_as_number */
1523
    0,                                          /* tp_as_sequence */
1524
    0,                                          /* tp_as_mapping */
1525
    0,                                          /* tp_hash */
1526
    0,                                          /* tp_call */
1527
    0,                                          /* tp_str */
1528
    PyObject_GenericGetAttr,                    /* tp_getattro */
1529
    0,                                          /* tp_setattro */
1530
    0,                                          /* tp_as_buffer */
1531
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,    /* tp_flags */
1532
    "A wrapper object implementing __await__ for coroutines.",
1533
    coro_wrapper_traverse,                      /* tp_traverse */
1534
    0,                                          /* tp_clear */
1535
    0,                                          /* tp_richcompare */
1536
    0,                                          /* tp_weaklistoffset */
1537
    PyObject_SelfIter,                          /* tp_iter */
1538
    coro_wrapper_iternext,                      /* tp_iternext */
1539
    coro_wrapper_methods,                       /* tp_methods */
1540
    0,                                          /* tp_members */
1541
    0,                                          /* tp_getset */
1542
    0,                                          /* tp_base */
1543
    0,                                          /* tp_dict */
1544
    0,                                          /* tp_descr_get */
1545
    0,                                          /* tp_descr_set */
1546
    0,                                          /* tp_dictoffset */
1547
    0,                                          /* tp_init */
1548
    0,                                          /* tp_alloc */
1549
    0,                                          /* tp_new */
1550
    0,                                          /* tp_free */
1551
};
1552
1553
PyObject *
1554
_PyCoro_ComputeOrigin(int origin_depth, _PyInterpreterFrame *current_frame)
1555
0
{
1556
0
    _PyInterpreterFrame *frame = current_frame;
1557
    /* First count how many frames we have */
1558
0
    int frame_count = 0;
1559
0
    for (; frame && frame_count < origin_depth; ++frame_count) {
1560
0
        frame = _PyFrame_GetFirstComplete(frame->previous);
1561
0
    }
1562
1563
    /* Now collect them */
1564
0
    PyObject *cr_origin = PyTuple_New(frame_count);
1565
0
    if (cr_origin == NULL) {
1566
0
        return NULL;
1567
0
    }
1568
0
    frame = current_frame;
1569
0
    for (int i = 0; i < frame_count; ++i) {
1570
0
        PyCodeObject *code = _PyFrame_GetCode(frame);
1571
0
        int line = PyUnstable_InterpreterFrame_GetLine(frame);
1572
0
        PyObject *frameinfo = Py_BuildValue("OiO", code->co_filename, line,
1573
0
                                            code->co_name);
1574
0
        if (!frameinfo) {
1575
0
            Py_DECREF(cr_origin);
1576
0
            return NULL;
1577
0
        }
1578
0
        PyTuple_SET_ITEM(cr_origin, i, frameinfo);
1579
0
        frame = _PyFrame_GetFirstComplete(frame->previous);
1580
0
    }
1581
1582
0
    return cr_origin;
1583
0
}
1584
1585
PyObject *
1586
PyCoro_New(PyFrameObject *f, PyObject *name, PyObject *qualname)
1587
0
{
1588
0
    PyObject *coro = gen_new_with_qualname(&PyCoro_Type, f, name, qualname);
1589
0
    if (!coro) {
1590
0
        return NULL;
1591
0
    }
1592
1593
0
    PyThreadState *tstate = _PyThreadState_GET();
1594
0
    int origin_depth = tstate->coroutine_origin_tracking_depth;
1595
1596
0
    if (origin_depth == 0) {
1597
0
        ((PyCoroObject *)coro)->cr_origin_or_finalizer = NULL;
1598
0
    } else {
1599
0
        PyObject *cr_origin = _PyCoro_ComputeOrigin(origin_depth, _PyEval_GetFrame());
1600
0
        ((PyCoroObject *)coro)->cr_origin_or_finalizer = cr_origin;
1601
0
        if (!cr_origin) {
1602
0
            Py_DECREF(coro);
1603
0
            return NULL;
1604
0
        }
1605
0
    }
1606
1607
0
    return coro;
1608
0
}
1609
1610
1611
/* ========= Asynchronous Generators ========= */
1612
1613
1614
typedef enum {
1615
    AWAITABLE_STATE_INIT,   /* new awaitable, has not yet been iterated */
1616
    AWAITABLE_STATE_ITER,   /* being iterated */
1617
    AWAITABLE_STATE_CLOSED, /* closed */
1618
} AwaitableState;
1619
1620
#ifdef Py_GIL_DISABLED
1621
static bool
1622
async_gen_try_set_state(int8_t *state, int8_t *expected, int8_t new_state)
1623
{
1624
    return _Py_atomic_compare_exchange_int8(state, expected, new_state);
1625
}
1626
1627
# define _Py_ASYNC_GEN_TRY_SET_STATE(state, expected, new_state) \
1628
    async_gen_try_set_state(&(state), &(expected), (new_state))
1629
#else
1630
# define _Py_ASYNC_GEN_TRY_SET_STATE(state, expected, new_state) \
1631
0
    ((state) = (new_state), true)
1632
#endif
1633
1634
// Try to transition the async generator to the running state.
1635
// Returns false if it is already running.
1636
//
1637
// There are two ways to concurrently iterate an async generator: by
1638
// sharing a single asend()/athrow() object across threads, or with
1639
// multiple asend()/athrow() objects sending to the same generator.
1640
// The CAS on ags_state/agt_state handles the first case; the CAS on
1641
// ag_running_async here handles the second.
1642
static bool
1643
async_gen_try_claim_running(PyAsyncGenObject *agen)
1644
0
{
1645
#ifdef Py_GIL_DISABLED
1646
    int8_t expected = 0;
1647
    return _Py_atomic_compare_exchange_int8(&agen->ag_running_async,
1648
                                            &expected, 1);
1649
#else
1650
0
    if (agen->ag_running_async) {
1651
0
        return false;
1652
0
    }
1653
0
    agen->ag_running_async = 1;
1654
0
    return true;
1655
0
#endif
1656
0
}
1657
1658
1659
typedef struct PyAsyncGenASend {
1660
    PyObject_HEAD
1661
    PyAsyncGenObject *ags_gen;
1662
1663
    /* Can be NULL, when in the __anext__() mode
1664
       (equivalent of "asend(None)") */
1665
    PyObject *ags_sendval;
1666
1667
    int8_t ags_state;
1668
} PyAsyncGenASend;
1669
1670
#define _PyAsyncGenASend_CAST(op) \
1671
0
    _Py_CAST(PyAsyncGenASend*, (op))
1672
1673
1674
typedef struct PyAsyncGenAThrow {
1675
    PyObject_HEAD
1676
    PyAsyncGenObject *agt_gen;
1677
1678
    /* Can be NULL, when in the "aclose()" mode
1679
       (equivalent of "athrow(GeneratorExit)") */
1680
    PyObject *agt_typ;
1681
    PyObject *agt_tb;
1682
    PyObject *agt_val;
1683
1684
    int8_t agt_state;
1685
} PyAsyncGenAThrow;
1686
1687
1688
typedef struct _PyAsyncGenWrappedValue {
1689
    PyObject_HEAD
1690
    PyObject *agw_val;
1691
} _PyAsyncGenWrappedValue;
1692
1693
1694
#define _PyAsyncGenWrappedValue_CheckExact(o) \
1695
0
                    Py_IS_TYPE(o, &_PyAsyncGenWrappedValue_Type)
1696
#define _PyAsyncGenWrappedValue_CAST(op) \
1697
0
    (assert(_PyAsyncGenWrappedValue_CheckExact(op)), \
1698
0
     _Py_CAST(_PyAsyncGenWrappedValue*, (op)))
1699
1700
1701
static int
1702
async_gen_traverse(PyObject *self, visitproc visit, void *arg)
1703
0
{
1704
0
    PyAsyncGenObject *ag = _PyAsyncGenObject_CAST(self);
1705
0
    Py_VISIT(ag->ag_origin_or_finalizer);
1706
0
    return gen_traverse((PyObject*)ag, visit, arg);
1707
0
}
1708
1709
1710
static PyObject *
1711
async_gen_repr(PyObject *self)
1712
0
{
1713
0
    PyAsyncGenObject *o = _PyAsyncGenObject_CAST(self);
1714
0
    return PyUnicode_FromFormat("<async_generator object %S at %p>",
1715
0
                                o->ag_qualname, o);
1716
0
}
1717
1718
1719
static int
1720
async_gen_init_hooks(PyAsyncGenObject *o)
1721
0
{
1722
0
    PyThreadState *tstate;
1723
0
    PyObject *finalizer;
1724
0
    PyObject *firstiter;
1725
1726
#ifdef Py_GIL_DISABLED
1727
    if (_Py_atomic_exchange_int8(&o->ag_hooks_inited, 1)) {
1728
        return 0;
1729
    }
1730
#else
1731
0
    if (o->ag_hooks_inited) {
1732
0
        return 0;
1733
0
    }
1734
1735
0
    o->ag_hooks_inited = 1;
1736
0
#endif
1737
1738
0
    tstate = _PyThreadState_GET();
1739
1740
0
    finalizer = tstate->async_gen_finalizer;
1741
0
    if (finalizer) {
1742
0
        o->ag_origin_or_finalizer = Py_NewRef(finalizer);
1743
0
    }
1744
1745
0
    firstiter = tstate->async_gen_firstiter;
1746
0
    if (firstiter) {
1747
0
        PyObject *res;
1748
1749
0
        Py_INCREF(firstiter);
1750
0
        res = PyObject_CallOneArg(firstiter, (PyObject *)o);
1751
0
        Py_DECREF(firstiter);
1752
0
        if (res == NULL) {
1753
0
            return 1;
1754
0
        }
1755
0
        Py_DECREF(res);
1756
0
    }
1757
1758
0
    return 0;
1759
0
}
1760
1761
1762
static PyObject *
1763
async_gen_anext(PyObject *self)
1764
0
{
1765
0
    PyAsyncGenObject *ag = _PyAsyncGenObject_CAST(self);
1766
0
    if (async_gen_init_hooks(ag)) {
1767
0
        return NULL;
1768
0
    }
1769
0
    return async_gen_asend_new(ag, NULL);
1770
0
}
1771
1772
1773
static PyObject *
1774
async_gen_asend(PyObject *op, PyObject *arg)
1775
0
{
1776
0
    PyAsyncGenObject *o = (PyAsyncGenObject*)op;
1777
0
    if (async_gen_init_hooks(o)) {
1778
0
        return NULL;
1779
0
    }
1780
0
    return async_gen_asend_new(o, arg);
1781
0
}
1782
1783
1784
static PyObject *
1785
async_gen_aclose(PyObject *op, PyObject *arg)
1786
0
{
1787
0
    PyAsyncGenObject *o = (PyAsyncGenObject*)op;
1788
0
    if (async_gen_init_hooks(o)) {
1789
0
        return NULL;
1790
0
    }
1791
0
    return async_gen_athrow_new(o, NULL);
1792
0
}
1793
1794
static PyObject *
1795
async_gen_athrow(PyObject *op, PyObject *args)
1796
0
{
1797
0
    PyAsyncGenObject *o = (PyAsyncGenObject*)op;
1798
0
    if (PyTuple_GET_SIZE(args) > 1) {
1799
0
        if (PyErr_WarnEx(PyExc_DeprecationWarning,
1800
0
                            "the (type, exc, tb) signature of athrow() is deprecated, "
1801
0
                            "use the single-arg signature instead.",
1802
0
                            1) < 0) {
1803
0
            return NULL;
1804
0
        }
1805
0
    }
1806
0
    if (async_gen_init_hooks(o)) {
1807
0
        return NULL;
1808
0
    }
1809
0
    return async_gen_athrow_new(o, args);
1810
0
}
1811
1812
static PyObject *
1813
ag_getframe(PyObject *ag, void *Py_UNUSED(ignored))
1814
0
{
1815
0
    return _gen_getframe((PyGenObject *)ag, "ag_frame");
1816
0
}
1817
1818
static PyObject *
1819
ag_getcode(PyObject *gen, void *Py_UNUSED(ignored))
1820
0
{
1821
0
    return _gen_getcode((PyGenObject*)gen, "ag_code");
1822
0
}
1823
1824
static PyObject *
1825
ag_getstate(PyObject *self, void *Py_UNUSED(ignored))
1826
0
{
1827
0
    PyGenObject *gen = _PyGen_CAST(self);
1828
0
    int8_t frame_state = FT_ATOMIC_LOAD_INT8_RELAXED(gen->gi_frame_state);
1829
1830
0
    static PyObject *const state_strings[] = {
1831
0
        [FRAME_CREATED] = &_Py_ID(AGEN_CREATED),
1832
0
        [FRAME_SUSPENDED] = &_Py_ID(AGEN_SUSPENDED),
1833
0
        [FRAME_SUSPENDED_YIELD_FROM] = &_Py_ID(AGEN_SUSPENDED),
1834
0
        [FRAME_SUSPENDED_YIELD_FROM_LOCKED] = &_Py_ID(AGEN_SUSPENDED),
1835
0
        [FRAME_EXECUTING] = &_Py_ID(AGEN_RUNNING),
1836
0
        [FRAME_CLEARED] = &_Py_ID(AGEN_CLOSED),
1837
0
    };
1838
1839
0
    assert(frame_state >= 0 &&
1840
0
           (size_t)frame_state < Py_ARRAY_LENGTH(state_strings));
1841
0
    return state_strings[frame_state];
1842
0
}
1843
1844
static PyGetSetDef async_gen_getsetlist[] = {
1845
    {"__name__", gen_get_name, gen_set_name,
1846
     PyDoc_STR("name of the async generator")},
1847
    {"__qualname__", gen_get_qualname, gen_set_qualname,
1848
     PyDoc_STR("qualified name of the async generator")},
1849
    {"ag_await", gen_getyieldfrom, NULL,
1850
     PyDoc_STR("object being awaited on, or None")},
1851
     {"ag_frame", ag_getframe, NULL, NULL},
1852
     {"ag_code", ag_getcode, NULL, NULL},
1853
     {"ag_suspended", gen_getsuspended, NULL, NULL},
1854
     {"ag_state", ag_getstate, NULL,
1855
      PyDoc_STR("state of the async generator")},
1856
    {NULL} /* Sentinel */
1857
};
1858
1859
static PyMemberDef async_gen_memberlist[] = {
1860
    {"ag_running", Py_T_BOOL,   offsetof(PyAsyncGenObject, ag_running_async),
1861
        Py_READONLY},
1862
    {NULL}      /* Sentinel */
1863
};
1864
1865
PyDoc_STRVAR(async_aclose_doc,
1866
"aclose() -> raise GeneratorExit inside generator.");
1867
1868
PyDoc_STRVAR(async_asend_doc,
1869
"asend(v) -> send 'v' in generator.");
1870
1871
PyDoc_STRVAR(async_athrow_doc,
1872
"athrow(value)\n\
1873
athrow(type[,value[,tb]])\n\
1874
\n\
1875
raise exception in generator.\n\
1876
the (type, val, tb) signature is deprecated, \n\
1877
and may be removed in a future version of Python.");
1878
1879
static PyMethodDef async_gen_methods[] = {
1880
    {"asend", async_gen_asend, METH_O, async_asend_doc},
1881
    {"athrow", async_gen_athrow, METH_VARARGS, async_athrow_doc},
1882
    {"aclose", async_gen_aclose, METH_NOARGS, async_aclose_doc},
1883
    {"__sizeof__", gen_sizeof, METH_NOARGS, sizeof__doc__},
1884
    {"__class_getitem__",    Py_GenericAlias,
1885
    METH_O|METH_CLASS,       PyDoc_STR("async generators are generic over the types of their yield and send values")},
1886
    {NULL, NULL}        /* Sentinel */
1887
};
1888
1889
1890
static PyAsyncMethods async_gen_as_async = {
1891
    0,                                          /* am_await */
1892
    PyObject_SelfIter,                          /* am_aiter */
1893
    async_gen_anext,                            /* am_anext */
1894
    PyGen_am_send,                              /* am_send  */
1895
};
1896
1897
1898
PyTypeObject PyAsyncGen_Type = {
1899
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
1900
    "async_generator",                          /* tp_name */
1901
    offsetof(PyAsyncGenObject, ag_iframe.localsplus), /* tp_basicsize */
1902
    sizeof(PyObject *),                         /* tp_itemsize */
1903
    /* methods */
1904
    gen_dealloc,                                /* tp_dealloc */
1905
    0,                                          /* tp_vectorcall_offset */
1906
    0,                                          /* tp_getattr */
1907
    0,                                          /* tp_setattr */
1908
    &async_gen_as_async,                        /* tp_as_async */
1909
    async_gen_repr,                             /* tp_repr */
1910
    0,                                          /* tp_as_number */
1911
    0,                                          /* tp_as_sequence */
1912
    0,                                          /* tp_as_mapping */
1913
    0,                                          /* tp_hash */
1914
    0,                                          /* tp_call */
1915
    0,                                          /* tp_str */
1916
    PyObject_GenericGetAttr,                    /* tp_getattro */
1917
    0,                                          /* tp_setattro */
1918
    0,                                          /* tp_as_buffer */
1919
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,    /* tp_flags */
1920
    0,                                          /* tp_doc */
1921
    async_gen_traverse,                         /* tp_traverse */
1922
    0,                                          /* tp_clear */
1923
    0,                                          /* tp_richcompare */
1924
    offsetof(PyAsyncGenObject, ag_weakreflist), /* tp_weaklistoffset */
1925
    0,                                          /* tp_iter */
1926
    0,                                          /* tp_iternext */
1927
    async_gen_methods,                          /* tp_methods */
1928
    async_gen_memberlist,                       /* tp_members */
1929
    async_gen_getsetlist,                       /* tp_getset */
1930
    0,                                          /* tp_base */
1931
    0,                                          /* tp_dict */
1932
    0,                                          /* tp_descr_get */
1933
    0,                                          /* tp_descr_set */
1934
    0,                                          /* tp_dictoffset */
1935
    0,                                          /* tp_init */
1936
    0,                                          /* tp_alloc */
1937
    0,                                          /* tp_new */
1938
    0,                                          /* tp_free */
1939
    0,                                          /* tp_is_gc */
1940
    0,                                          /* tp_bases */
1941
    0,                                          /* tp_mro */
1942
    0,                                          /* tp_cache */
1943
    0,                                          /* tp_subclasses */
1944
    0,                                          /* tp_weaklist */
1945
    0,                                          /* tp_del */
1946
    0,                                          /* tp_version_tag */
1947
    gen_finalize,                               /* tp_finalize */
1948
};
1949
1950
1951
PyObject *
1952
PyAsyncGen_New(PyFrameObject *f, PyObject *name, PyObject *qualname)
1953
0
{
1954
0
    PyAsyncGenObject *ag;
1955
0
    ag = (PyAsyncGenObject *)gen_new_with_qualname(&PyAsyncGen_Type, f,
1956
0
                                                   name, qualname);
1957
0
    if (ag == NULL) {
1958
0
        return NULL;
1959
0
    }
1960
1961
0
    ag->ag_origin_or_finalizer = NULL;
1962
0
    ag->ag_closed = 0;
1963
0
    ag->ag_hooks_inited = 0;
1964
0
    ag->ag_running_async = 0;
1965
0
    return (PyObject*)ag;
1966
0
}
1967
1968
static PyObject *
1969
async_gen_unwrap_value(PyAsyncGenObject *gen, PyObject *result)
1970
0
{
1971
0
    if (result == NULL) {
1972
0
        if (!PyErr_Occurred()) {
1973
0
            PyErr_SetNone(PyExc_StopAsyncIteration);
1974
0
        }
1975
1976
0
        if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration)
1977
0
            || PyErr_ExceptionMatches(PyExc_GeneratorExit)
1978
0
        ) {
1979
0
            FT_ATOMIC_STORE_INT8_RELAXED(gen->ag_closed, 1);
1980
0
        }
1981
1982
0
        return NULL;
1983
0
    }
1984
1985
0
    if (_PyAsyncGenWrappedValue_CheckExact(result)) {
1986
        /* async yield */
1987
0
        _PyGen_SetStopIterationValue(((_PyAsyncGenWrappedValue*)result)->agw_val);
1988
0
        Py_DECREF(result);
1989
0
        return NULL;
1990
0
    }
1991
1992
0
    return result;
1993
0
}
1994
1995
1996
/* ---------- Async Generator ASend Awaitable ------------ */
1997
1998
1999
static void
2000
async_gen_asend_dealloc(PyObject *self)
2001
0
{
2002
0
    assert(PyAsyncGenASend_CheckExact(self));
2003
0
    PyAsyncGenASend *ags = _PyAsyncGenASend_CAST(self);
2004
2005
0
    if (PyObject_CallFinalizerFromDealloc(self)) {
2006
0
        return;
2007
0
    }
2008
2009
0
    _PyObject_GC_UNTRACK(self);
2010
0
    Py_CLEAR(ags->ags_gen);
2011
0
    Py_CLEAR(ags->ags_sendval);
2012
2013
0
    _PyGC_CLEAR_FINALIZED(self);
2014
2015
0
    _Py_FREELIST_FREE(async_gen_asends, self, PyObject_GC_Del);
2016
0
}
2017
2018
static int
2019
async_gen_asend_traverse(PyObject *self, visitproc visit, void *arg)
2020
0
{
2021
0
    PyAsyncGenASend *ags = _PyAsyncGenASend_CAST(self);
2022
0
    Py_VISIT(ags->ags_gen);
2023
0
    Py_VISIT(ags->ags_sendval);
2024
0
    return 0;
2025
0
}
2026
2027
2028
static PyObject *
2029
async_gen_asend_send(PyObject *self, PyObject *arg)
2030
0
{
2031
0
    PyAsyncGenASend *o = _PyAsyncGenASend_CAST(self);
2032
2033
0
    int8_t state = FT_ATOMIC_LOAD_INT8_RELAXED(o->ags_state);
2034
0
    do {
2035
0
        if (state == AWAITABLE_STATE_CLOSED) {
2036
0
            PyErr_SetString(
2037
0
                PyExc_RuntimeError,
2038
0
                "cannot reuse already awaited __anext__()/asend()");
2039
0
            return NULL;
2040
0
        }
2041
0
        if (state == AWAITABLE_STATE_ITER) {
2042
0
            goto do_send;
2043
0
        }
2044
0
        assert(state == AWAITABLE_STATE_INIT);
2045
0
    } while (!_Py_ASYNC_GEN_TRY_SET_STATE(o->ags_state, state,
2046
0
                                          AWAITABLE_STATE_ITER));
2047
2048
    // The transition above only guards this object, the generator may
2049
    // still be running through another asend()/athrow() object so
2050
    // try to claim it before running.
2051
0
    if (!async_gen_try_claim_running(o->ags_gen)) {
2052
0
        FT_ATOMIC_STORE_INT8_RELAXED(o->ags_state, AWAITABLE_STATE_CLOSED);
2053
0
        PyErr_SetString(
2054
0
            PyExc_RuntimeError,
2055
0
            "anext(): asynchronous generator is already running");
2056
0
        return NULL;
2057
0
    }
2058
2059
0
    if (arg == NULL || arg == Py_None) {
2060
0
        arg = o->ags_sendval;
2061
0
    }
2062
2063
0
    PyObject *result;
2064
0
do_send:
2065
0
    result = gen_send((PyObject*)o->ags_gen, arg);
2066
0
    result = async_gen_unwrap_value(o->ags_gen, result);
2067
2068
0
    if (result == NULL) {
2069
0
        FT_ATOMIC_STORE_INT8_RELAXED(o->ags_state, AWAITABLE_STATE_CLOSED);
2070
0
        FT_ATOMIC_STORE_INT8_RELEASE(o->ags_gen->ag_running_async, 0);
2071
0
    }
2072
2073
0
    return result;
2074
0
}
2075
2076
PySendResult
2077
_PyAsyncGenASend_Send(PyObject *iter, PyObject *arg, PyObject **result)
2078
0
{
2079
0
    *result = async_gen_asend_send(iter, arg);
2080
0
    if (*result != NULL) {
2081
0
        return PYGEN_NEXT;
2082
0
    }
2083
0
    if (_PyGen_FetchStopIterationValue(result) == 0) {
2084
0
        return PYGEN_RETURN;
2085
0
    }
2086
0
    return PYGEN_ERROR;
2087
0
}
2088
2089
2090
static PyObject *
2091
async_gen_asend_iternext(PyObject *ags)
2092
0
{
2093
0
    return async_gen_asend_send(ags, NULL);
2094
0
}
2095
2096
2097
static PyObject *
2098
async_gen_asend_throw(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
2099
0
{
2100
0
    PyAsyncGenASend *o = _PyAsyncGenASend_CAST(self);
2101
2102
0
    int8_t state = FT_ATOMIC_LOAD_INT8_RELAXED(o->ags_state);
2103
0
    do {
2104
0
        if (state == AWAITABLE_STATE_CLOSED) {
2105
0
            PyErr_SetString(
2106
0
                PyExc_RuntimeError,
2107
0
                "cannot reuse already awaited __anext__()/asend()");
2108
0
            return NULL;
2109
0
        }
2110
0
        if (state == AWAITABLE_STATE_ITER) {
2111
0
            goto do_throw;
2112
0
        }
2113
0
        assert(state == AWAITABLE_STATE_INIT);
2114
0
    } while (!_Py_ASYNC_GEN_TRY_SET_STATE(o->ags_state, state,
2115
0
                                          AWAITABLE_STATE_ITER));
2116
2117
    // The transition above only guards this object, the generator may
2118
    // still be running through another asend()/athrow() object so
2119
    // try to claim it before running.
2120
0
    if (!async_gen_try_claim_running(o->ags_gen)) {
2121
0
        FT_ATOMIC_STORE_INT8_RELAXED(o->ags_state, AWAITABLE_STATE_CLOSED);
2122
0
        PyErr_SetString(
2123
0
            PyExc_RuntimeError,
2124
0
            "anext(): asynchronous generator is already running");
2125
0
        return NULL;
2126
0
    }
2127
2128
0
    PyObject *result;
2129
0
do_throw:
2130
0
    result = gen_throw((PyObject*)o->ags_gen, args, nargs);
2131
0
    result = async_gen_unwrap_value(o->ags_gen, result);
2132
2133
0
    if (result == NULL) {
2134
0
        FT_ATOMIC_STORE_INT8_RELAXED(o->ags_state, AWAITABLE_STATE_CLOSED);
2135
0
        FT_ATOMIC_STORE_INT8_RELEASE(o->ags_gen->ag_running_async, 0);
2136
0
    }
2137
2138
0
    return result;
2139
0
}
2140
2141
2142
static PyObject *
2143
async_gen_asend_close(PyObject *self, PyObject *args)
2144
0
{
2145
0
    PyAsyncGenASend *o = _PyAsyncGenASend_CAST(self);
2146
0
    if (FT_ATOMIC_LOAD_INT8_RELAXED(o->ags_state) == AWAITABLE_STATE_CLOSED) {
2147
0
        Py_RETURN_NONE;
2148
0
    }
2149
2150
0
    PyObject *result = async_gen_asend_throw(self, &PyExc_GeneratorExit, 1);
2151
0
    if (result == NULL) {
2152
0
        if (PyErr_ExceptionMatches(PyExc_StopIteration) ||
2153
0
            PyErr_ExceptionMatches(PyExc_StopAsyncIteration) ||
2154
0
            PyErr_ExceptionMatches(PyExc_GeneratorExit))
2155
0
        {
2156
0
            PyErr_Clear();
2157
0
            Py_RETURN_NONE;
2158
0
        }
2159
0
        return result;
2160
0
    }
2161
2162
0
    Py_DECREF(result);
2163
0
    PyErr_SetString(PyExc_RuntimeError, "coroutine ignored GeneratorExit");
2164
0
    return NULL;
2165
0
}
2166
2167
static void
2168
async_gen_asend_finalize(PyObject *self)
2169
0
{
2170
0
    PyAsyncGenASend *ags = _PyAsyncGenASend_CAST(self);
2171
0
    if (ags->ags_state == AWAITABLE_STATE_INIT) {
2172
0
        _PyErr_WarnUnawaitedAgenMethod(ags->ags_gen, &_Py_ID(asend));
2173
0
    }
2174
0
}
2175
2176
static PyMethodDef async_gen_asend_methods[] = {
2177
    {"send", async_gen_asend_send, METH_O, send_doc},
2178
    {"throw", _PyCFunction_CAST(async_gen_asend_throw), METH_FASTCALL, throw_doc},
2179
    {"close", async_gen_asend_close, METH_NOARGS, close_doc},
2180
    {NULL, NULL}        /* Sentinel */
2181
};
2182
2183
2184
static PyAsyncMethods async_gen_asend_as_async = {
2185
    .am_await = PyObject_SelfIter,
2186
    .am_send = _PyAsyncGenASend_Send,
2187
};
2188
2189
2190
PyTypeObject _PyAsyncGenASend_Type = {
2191
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
2192
    "async_generator_asend",                    /* tp_name */
2193
    sizeof(PyAsyncGenASend),                    /* tp_basicsize */
2194
    0,                                          /* tp_itemsize */
2195
    /* methods */
2196
    async_gen_asend_dealloc,                    /* tp_dealloc */
2197
    0,                                          /* tp_vectorcall_offset */
2198
    0,                                          /* tp_getattr */
2199
    0,                                          /* tp_setattr */
2200
    &async_gen_asend_as_async,                  /* tp_as_async */
2201
    0,                                          /* tp_repr */
2202
    0,                                          /* tp_as_number */
2203
    0,                                          /* tp_as_sequence */
2204
    0,                                          /* tp_as_mapping */
2205
    0,                                          /* tp_hash */
2206
    0,                                          /* tp_call */
2207
    0,                                          /* tp_str */
2208
    PyObject_GenericGetAttr,                    /* tp_getattro */
2209
    0,                                          /* tp_setattro */
2210
    0,                                          /* tp_as_buffer */
2211
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,    /* tp_flags */
2212
    0,                                          /* tp_doc */
2213
    async_gen_asend_traverse,                   /* tp_traverse */
2214
    0,                                          /* tp_clear */
2215
    0,                                          /* tp_richcompare */
2216
    0,                                          /* tp_weaklistoffset */
2217
    PyObject_SelfIter,                          /* tp_iter */
2218
    async_gen_asend_iternext,                   /* tp_iternext */
2219
    async_gen_asend_methods,                    /* tp_methods */
2220
    0,                                          /* tp_members */
2221
    0,                                          /* tp_getset */
2222
    0,                                          /* tp_base */
2223
    0,                                          /* tp_dict */
2224
    0,                                          /* tp_descr_get */
2225
    0,                                          /* tp_descr_set */
2226
    0,                                          /* tp_dictoffset */
2227
    0,                                          /* tp_init */
2228
    0,                                          /* tp_alloc */
2229
    0,                                          /* tp_new */
2230
    .tp_finalize = async_gen_asend_finalize,
2231
};
2232
2233
2234
static PyObject *
2235
async_gen_asend_new(PyAsyncGenObject *gen, PyObject *sendval)
2236
0
{
2237
0
    PyAsyncGenASend *ags = _Py_FREELIST_POP(PyAsyncGenASend, async_gen_asends);
2238
0
    if (ags == NULL) {
2239
0
        ags = PyObject_GC_New(PyAsyncGenASend, &_PyAsyncGenASend_Type);
2240
0
        if (ags == NULL) {
2241
0
            return NULL;
2242
0
        }
2243
0
    }
2244
2245
0
    ags->ags_gen = (PyAsyncGenObject*)Py_NewRef(gen);
2246
0
    ags->ags_sendval = Py_XNewRef(sendval);
2247
0
    ags->ags_state = AWAITABLE_STATE_INIT;
2248
2249
0
    _PyObject_GC_TRACK((PyObject*)ags);
2250
0
    return (PyObject*)ags;
2251
0
}
2252
2253
2254
/* ---------- Async Generator Value Wrapper ------------ */
2255
2256
2257
static void
2258
async_gen_wrapped_val_dealloc(PyObject *self)
2259
0
{
2260
0
    _PyAsyncGenWrappedValue *agw = _PyAsyncGenWrappedValue_CAST(self);
2261
0
    _PyObject_GC_UNTRACK(self);
2262
0
    Py_CLEAR(agw->agw_val);
2263
0
    _Py_FREELIST_FREE(async_gens, self, PyObject_GC_Del);
2264
0
}
2265
2266
2267
static int
2268
async_gen_wrapped_val_traverse(PyObject *self, visitproc visit, void *arg)
2269
0
{
2270
0
    _PyAsyncGenWrappedValue *agw = _PyAsyncGenWrappedValue_CAST(self);
2271
0
    Py_VISIT(agw->agw_val);
2272
0
    return 0;
2273
0
}
2274
2275
2276
PyTypeObject _PyAsyncGenWrappedValue_Type = {
2277
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
2278
    "async_generator_wrapped_value",            /* tp_name */
2279
    sizeof(_PyAsyncGenWrappedValue),            /* tp_basicsize */
2280
    0,                                          /* tp_itemsize */
2281
    /* methods */
2282
    async_gen_wrapped_val_dealloc,              /* tp_dealloc */
2283
    0,                                          /* tp_vectorcall_offset */
2284
    0,                                          /* tp_getattr */
2285
    0,                                          /* tp_setattr */
2286
    0,                                          /* tp_as_async */
2287
    0,                                          /* tp_repr */
2288
    0,                                          /* tp_as_number */
2289
    0,                                          /* tp_as_sequence */
2290
    0,                                          /* tp_as_mapping */
2291
    0,                                          /* tp_hash */
2292
    0,                                          /* tp_call */
2293
    0,                                          /* tp_str */
2294
    PyObject_GenericGetAttr,                    /* tp_getattro */
2295
    0,                                          /* tp_setattro */
2296
    0,                                          /* tp_as_buffer */
2297
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,    /* tp_flags */
2298
    0,                                          /* tp_doc */
2299
    async_gen_wrapped_val_traverse,             /* tp_traverse */
2300
    0,                                          /* tp_clear */
2301
    0,                                          /* tp_richcompare */
2302
    0,                                          /* tp_weaklistoffset */
2303
    0,                                          /* tp_iter */
2304
    0,                                          /* tp_iternext */
2305
    0,                                          /* tp_methods */
2306
    0,                                          /* tp_members */
2307
    0,                                          /* tp_getset */
2308
    0,                                          /* tp_base */
2309
    0,                                          /* tp_dict */
2310
    0,                                          /* tp_descr_get */
2311
    0,                                          /* tp_descr_set */
2312
    0,                                          /* tp_dictoffset */
2313
    0,                                          /* tp_init */
2314
    0,                                          /* tp_alloc */
2315
    0,                                          /* tp_new */
2316
};
2317
2318
2319
PyObject *
2320
_PyAsyncGenValueWrapperNew(PyThreadState *tstate, PyObject *val)
2321
0
{
2322
0
    assert(val);
2323
2324
0
    _PyAsyncGenWrappedValue *o = _Py_FREELIST_POP(_PyAsyncGenWrappedValue, async_gens);
2325
0
    if (o == NULL) {
2326
0
        o = PyObject_GC_New(_PyAsyncGenWrappedValue,
2327
0
                            &_PyAsyncGenWrappedValue_Type);
2328
0
        if (o == NULL) {
2329
0
            return NULL;
2330
0
        }
2331
0
    }
2332
0
    assert(_PyAsyncGenWrappedValue_CheckExact(o));
2333
0
    o->agw_val = Py_NewRef(val);
2334
0
    _PyObject_GC_TRACK((PyObject*)o);
2335
0
    return (PyObject*)o;
2336
0
}
2337
2338
2339
/* ---------- Async Generator AThrow awaitable ------------ */
2340
2341
#define _PyAsyncGenAThrow_CAST(op) \
2342
0
    (assert(Py_IS_TYPE((op), &_PyAsyncGenAThrow_Type)), \
2343
0
     _Py_CAST(PyAsyncGenAThrow*, (op)))
2344
2345
static void
2346
async_gen_athrow_dealloc(PyObject *self)
2347
0
{
2348
0
    PyAsyncGenAThrow *agt = _PyAsyncGenAThrow_CAST(self);
2349
0
    if (PyObject_CallFinalizerFromDealloc(self)) {
2350
0
        return;
2351
0
    }
2352
2353
0
    _PyObject_GC_UNTRACK(self);
2354
0
    Py_CLEAR(agt->agt_gen);
2355
0
    Py_XDECREF(agt->agt_typ);
2356
0
    Py_XDECREF(agt->agt_tb);
2357
0
    Py_XDECREF(agt->agt_val);
2358
0
    PyObject_GC_Del(self);
2359
0
}
2360
2361
2362
static int
2363
async_gen_athrow_traverse(PyObject *self, visitproc visit, void *arg)
2364
0
{
2365
0
    PyAsyncGenAThrow *agt = _PyAsyncGenAThrow_CAST(self);
2366
0
    Py_VISIT(agt->agt_gen);
2367
0
    Py_VISIT(agt->agt_typ);
2368
0
    Py_VISIT(agt->agt_tb);
2369
0
    Py_VISIT(agt->agt_val);
2370
0
    return 0;
2371
0
}
2372
2373
2374
static PyObject *
2375
async_gen_athrow_send(PyObject *self, PyObject *arg)
2376
0
{
2377
0
    PyAsyncGenAThrow *o = _PyAsyncGenAThrow_CAST(self);
2378
0
    PyGenObject *gen = _PyGen_CAST(o->agt_gen);
2379
0
    PyObject *retval;
2380
2381
0
    int8_t state = FT_ATOMIC_LOAD_INT8_RELAXED(o->agt_state);
2382
0
    if (state == AWAITABLE_STATE_CLOSED) {
2383
0
        PyErr_SetString(
2384
0
            PyExc_RuntimeError,
2385
0
            "cannot reuse already awaited aclose()/athrow()");
2386
0
        return NULL;
2387
0
    }
2388
2389
0
    if (FRAME_STATE_FINISHED(FT_ATOMIC_LOAD_INT8_RELAXED(gen->gi_frame_state))) {
2390
        // Close the awaitable, unless another thread transitioned it
2391
        // to a different state in the meantime.
2392
0
        (void)_Py_ASYNC_GEN_TRY_SET_STATE(o->agt_state, state,
2393
0
                                          AWAITABLE_STATE_CLOSED);
2394
0
        PyErr_SetNone(PyExc_StopIteration);
2395
0
        return NULL;
2396
0
    }
2397
2398
0
    do {
2399
0
        if (state == AWAITABLE_STATE_CLOSED) {
2400
0
            PyErr_SetString(
2401
0
                PyExc_RuntimeError,
2402
0
                "cannot reuse already awaited aclose()/athrow()");
2403
0
            return NULL;
2404
0
        }
2405
0
        if (state == AWAITABLE_STATE_ITER) {
2406
0
            goto do_send;
2407
0
        }
2408
0
        assert(state == AWAITABLE_STATE_INIT);
2409
0
        if (arg != Py_None) {
2410
0
            PyErr_SetString(PyExc_RuntimeError, NON_INIT_CORO_MSG);
2411
0
            return NULL;
2412
0
        }
2413
0
    } while (!_Py_ASYNC_GEN_TRY_SET_STATE(o->agt_state, state,
2414
0
                                          AWAITABLE_STATE_ITER));
2415
2416
    // The transition above only guards this object, the generator may
2417
    // still be running through another asend()/athrow() object so
2418
    // try to claim it before running.
2419
0
    if (!async_gen_try_claim_running(o->agt_gen)) {
2420
0
        FT_ATOMIC_STORE_INT8_RELAXED(o->agt_state, AWAITABLE_STATE_CLOSED);
2421
0
        if (o->agt_typ == NULL) {
2422
0
            PyErr_SetString(
2423
0
                PyExc_RuntimeError,
2424
0
                "aclose(): asynchronous generator is already running");
2425
0
        }
2426
0
        else {
2427
0
            PyErr_SetString(
2428
0
                PyExc_RuntimeError,
2429
0
                "athrow(): asynchronous generator is already running");
2430
0
        }
2431
0
        return NULL;
2432
0
    }
2433
2434
0
    if (FT_ATOMIC_LOAD_INT8_RELAXED(o->agt_gen->ag_closed)) {
2435
0
        FT_ATOMIC_STORE_INT8_RELAXED(o->agt_state, AWAITABLE_STATE_CLOSED);
2436
0
        FT_ATOMIC_STORE_INT8_RELEASE(o->agt_gen->ag_running_async, 0);
2437
0
        PyErr_SetNone(PyExc_StopAsyncIteration);
2438
0
        return NULL;
2439
0
    }
2440
2441
0
    if (o->agt_typ == NULL) {
2442
        /* aclose() mode */
2443
0
        FT_ATOMIC_STORE_INT8_RELAXED(o->agt_gen->ag_closed, 1);
2444
2445
0
        retval = _gen_throw((PyGenObject *)gen,
2446
0
                            0,  /* Do not close generator when
2447
                                   PyExc_GeneratorExit is passed */
2448
0
                            PyExc_GeneratorExit, NULL, NULL);
2449
2450
0
        if (retval && _PyAsyncGenWrappedValue_CheckExact(retval)) {
2451
0
            Py_DECREF(retval);
2452
0
            goto yield_close;
2453
0
        }
2454
0
    } else {
2455
0
        retval = _gen_throw((PyGenObject *)gen,
2456
0
                            0,  /* Do not close generator when
2457
                                   PyExc_GeneratorExit is passed */
2458
0
                            o->agt_typ, o->agt_val, o->agt_tb);
2459
0
        retval = async_gen_unwrap_value(o->agt_gen, retval);
2460
0
    }
2461
0
    if (retval == NULL) {
2462
0
        goto check_error;
2463
0
    }
2464
0
    return retval;
2465
2466
0
do_send:
2467
0
    retval = gen_send((PyObject *)gen, arg);
2468
0
    if (o->agt_typ) {
2469
0
        retval = async_gen_unwrap_value(o->agt_gen, retval);
2470
0
        if (retval == NULL) {
2471
0
            FT_ATOMIC_STORE_INT8_RELAXED(o->agt_state, AWAITABLE_STATE_CLOSED);
2472
0
            FT_ATOMIC_STORE_INT8_RELEASE(o->agt_gen->ag_running_async, 0);
2473
0
        }
2474
0
        return retval;
2475
0
    } else {
2476
        /* aclose() mode */
2477
0
        if (retval) {
2478
0
            if (_PyAsyncGenWrappedValue_CheckExact(retval)) {
2479
0
                Py_DECREF(retval);
2480
0
                goto yield_close;
2481
0
            }
2482
0
            else {
2483
0
                return retval;
2484
0
            }
2485
0
        }
2486
0
        else {
2487
0
            goto check_error;
2488
0
        }
2489
0
    }
2490
2491
0
yield_close:
2492
0
    FT_ATOMIC_STORE_INT8_RELAXED(o->agt_state, AWAITABLE_STATE_CLOSED);
2493
0
    FT_ATOMIC_STORE_INT8_RELEASE(o->agt_gen->ag_running_async, 0);
2494
0
    PyErr_SetString(
2495
0
        PyExc_RuntimeError, ASYNC_GEN_IGNORED_EXIT_MSG);
2496
0
    return NULL;
2497
2498
0
check_error:
2499
0
    FT_ATOMIC_STORE_INT8_RELAXED(o->agt_state, AWAITABLE_STATE_CLOSED);
2500
0
    FT_ATOMIC_STORE_INT8_RELEASE(o->agt_gen->ag_running_async, 0);
2501
0
    if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration) ||
2502
0
            PyErr_ExceptionMatches(PyExc_GeneratorExit))
2503
0
    {
2504
0
        if (o->agt_typ == NULL) {
2505
            /* when aclose() is called we don't want to propagate
2506
               StopAsyncIteration or GeneratorExit; just raise
2507
               StopIteration, signalling that this 'aclose()' await
2508
               is done.
2509
            */
2510
0
            PyErr_Clear();
2511
0
            PyErr_SetNone(PyExc_StopIteration);
2512
0
        }
2513
0
    }
2514
0
    return NULL;
2515
0
}
2516
2517
2518
static PyObject *
2519
async_gen_athrow_throw(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
2520
0
{
2521
0
    PyAsyncGenAThrow *o = _PyAsyncGenAThrow_CAST(self);
2522
2523
0
    int8_t state = FT_ATOMIC_LOAD_INT8_RELAXED(o->agt_state);
2524
0
    do {
2525
0
        if (state == AWAITABLE_STATE_CLOSED) {
2526
0
            PyErr_SetString(
2527
0
                PyExc_RuntimeError,
2528
0
                "cannot reuse already awaited aclose()/athrow()");
2529
0
            return NULL;
2530
0
        }
2531
0
        if (state == AWAITABLE_STATE_ITER) {
2532
0
            goto do_throw;
2533
0
        }
2534
0
        assert(state == AWAITABLE_STATE_INIT);
2535
0
    } while (!_Py_ASYNC_GEN_TRY_SET_STATE(o->agt_state, state,
2536
0
                                          AWAITABLE_STATE_ITER));
2537
2538
    // The transition above only guards this object, the generator may
2539
    // still be running through another asend()/athrow() object so
2540
    // try to claim it before running.
2541
0
    if (!async_gen_try_claim_running(o->agt_gen)) {
2542
0
        FT_ATOMIC_STORE_INT8_RELAXED(o->agt_state, AWAITABLE_STATE_CLOSED);
2543
0
        if (o->agt_typ == NULL) {
2544
0
            PyErr_SetString(
2545
0
                PyExc_RuntimeError,
2546
0
                "aclose(): asynchronous generator is already running");
2547
0
        }
2548
0
        else {
2549
0
            PyErr_SetString(
2550
0
                PyExc_RuntimeError,
2551
0
                "athrow(): asynchronous generator is already running");
2552
0
        }
2553
0
        return NULL;
2554
0
    }
2555
2556
0
    PyObject *retval;
2557
0
do_throw:
2558
0
    retval = gen_throw((PyObject*)o->agt_gen, args, nargs);
2559
0
    if (o->agt_typ) {
2560
0
        retval = async_gen_unwrap_value(o->agt_gen, retval);
2561
0
        if (retval == NULL) {
2562
0
            FT_ATOMIC_STORE_INT8_RELAXED(o->agt_state, AWAITABLE_STATE_CLOSED);
2563
0
            FT_ATOMIC_STORE_INT8_RELEASE(o->agt_gen->ag_running_async, 0);
2564
0
        }
2565
0
        return retval;
2566
0
    }
2567
0
    else {
2568
        /* aclose() mode */
2569
0
        if (retval && _PyAsyncGenWrappedValue_CheckExact(retval)) {
2570
0
            FT_ATOMIC_STORE_INT8_RELAXED(o->agt_state, AWAITABLE_STATE_CLOSED);
2571
0
            FT_ATOMIC_STORE_INT8_RELEASE(o->agt_gen->ag_running_async, 0);
2572
0
            Py_DECREF(retval);
2573
0
            PyErr_SetString(PyExc_RuntimeError, ASYNC_GEN_IGNORED_EXIT_MSG);
2574
0
            return NULL;
2575
0
        }
2576
0
        if (retval == NULL) {
2577
0
            FT_ATOMIC_STORE_INT8_RELAXED(o->agt_state, AWAITABLE_STATE_CLOSED);
2578
0
            FT_ATOMIC_STORE_INT8_RELEASE(o->agt_gen->ag_running_async, 0);
2579
0
        }
2580
0
        if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration) ||
2581
0
            PyErr_ExceptionMatches(PyExc_GeneratorExit))
2582
0
        {
2583
            /* when aclose() is called we don't want to propagate
2584
               StopAsyncIteration or GeneratorExit; just raise
2585
               StopIteration, signalling that this 'aclose()' await
2586
               is done.
2587
            */
2588
0
            PyErr_Clear();
2589
0
            PyErr_SetNone(PyExc_StopIteration);
2590
0
        }
2591
0
        return retval;
2592
0
    }
2593
0
}
2594
2595
2596
static PyObject *
2597
async_gen_athrow_iternext(PyObject *agt)
2598
0
{
2599
0
    return async_gen_athrow_send(agt, Py_None);
2600
0
}
2601
2602
2603
static PyObject *
2604
async_gen_athrow_close(PyObject *self, PyObject *args)
2605
0
{
2606
0
    PyAsyncGenAThrow *agt = _PyAsyncGenAThrow_CAST(self);
2607
0
    if (FT_ATOMIC_LOAD_INT8_RELAXED(agt->agt_state) == AWAITABLE_STATE_CLOSED) {
2608
0
        Py_RETURN_NONE;
2609
0
    }
2610
0
    PyObject *result = async_gen_athrow_throw((PyObject*)agt,
2611
0
                                              &PyExc_GeneratorExit, 1);
2612
0
    if (result == NULL) {
2613
0
        if (PyErr_ExceptionMatches(PyExc_StopIteration) ||
2614
0
            PyErr_ExceptionMatches(PyExc_StopAsyncIteration) ||
2615
0
            PyErr_ExceptionMatches(PyExc_GeneratorExit))
2616
0
        {
2617
0
            PyErr_Clear();
2618
0
            Py_RETURN_NONE;
2619
0
        }
2620
0
        return result;
2621
0
    } else {
2622
0
        Py_DECREF(result);
2623
0
        PyErr_SetString(PyExc_RuntimeError, "coroutine ignored GeneratorExit");
2624
0
        return NULL;
2625
0
    }
2626
0
}
2627
2628
2629
static void
2630
async_gen_athrow_finalize(PyObject *op)
2631
0
{
2632
0
    PyAsyncGenAThrow *o = (PyAsyncGenAThrow*)op;
2633
0
    if (o->agt_state == AWAITABLE_STATE_INIT) {
2634
0
        PyObject *method = o->agt_typ ? &_Py_ID(athrow) : &_Py_ID(aclose);
2635
0
        _PyErr_WarnUnawaitedAgenMethod(o->agt_gen, method);
2636
0
    }
2637
0
}
2638
2639
static PyMethodDef async_gen_athrow_methods[] = {
2640
    {"send", async_gen_athrow_send, METH_O, send_doc},
2641
    {"throw", _PyCFunction_CAST(async_gen_athrow_throw),
2642
    METH_FASTCALL, throw_doc},
2643
    {"close", async_gen_athrow_close, METH_NOARGS, close_doc},
2644
    {NULL, NULL}        /* Sentinel */
2645
};
2646
2647
2648
static PyAsyncMethods async_gen_athrow_as_async = {
2649
    PyObject_SelfIter,                          /* am_await */
2650
    0,                                          /* am_aiter */
2651
    0,                                          /* am_anext */
2652
    0,                                          /* am_send  */
2653
};
2654
2655
2656
PyTypeObject _PyAsyncGenAThrow_Type = {
2657
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
2658
    "async_generator_athrow",                   /* tp_name */
2659
    sizeof(PyAsyncGenAThrow),                   /* tp_basicsize */
2660
    0,                                          /* tp_itemsize */
2661
    /* methods */
2662
    async_gen_athrow_dealloc,                   /* tp_dealloc */
2663
    0,                                          /* tp_vectorcall_offset */
2664
    0,                                          /* tp_getattr */
2665
    0,                                          /* tp_setattr */
2666
    &async_gen_athrow_as_async,                 /* tp_as_async */
2667
    0,                                          /* tp_repr */
2668
    0,                                          /* tp_as_number */
2669
    0,                                          /* tp_as_sequence */
2670
    0,                                          /* tp_as_mapping */
2671
    0,                                          /* tp_hash */
2672
    0,                                          /* tp_call */
2673
    0,                                          /* tp_str */
2674
    PyObject_GenericGetAttr,                    /* tp_getattro */
2675
    0,                                          /* tp_setattro */
2676
    0,                                          /* tp_as_buffer */
2677
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,    /* tp_flags */
2678
    0,                                          /* tp_doc */
2679
    async_gen_athrow_traverse,                  /* tp_traverse */
2680
    0,                                          /* tp_clear */
2681
    0,                                          /* tp_richcompare */
2682
    0,                                          /* tp_weaklistoffset */
2683
    PyObject_SelfIter,                          /* tp_iter */
2684
    async_gen_athrow_iternext,                  /* tp_iternext */
2685
    async_gen_athrow_methods,                   /* tp_methods */
2686
    0,                                          /* tp_members */
2687
    0,                                          /* tp_getset */
2688
    0,                                          /* tp_base */
2689
    0,                                          /* tp_dict */
2690
    0,                                          /* tp_descr_get */
2691
    0,                                          /* tp_descr_set */
2692
    0,                                          /* tp_dictoffset */
2693
    0,                                          /* tp_init */
2694
    0,                                          /* tp_alloc */
2695
    0,                                          /* tp_new */
2696
    .tp_finalize = async_gen_athrow_finalize,
2697
};
2698
2699
2700
static PyObject *
2701
async_gen_athrow_new(PyAsyncGenObject *gen, PyObject *args)
2702
0
{
2703
0
    PyObject *typ = NULL;
2704
0
    PyObject *tb = NULL;
2705
0
    PyObject *val = NULL;
2706
0
    if (args && !PyArg_UnpackTuple(args, "athrow", 1, 3, &typ, &val, &tb)) {
2707
0
        return NULL;
2708
0
    }
2709
2710
0
    PyAsyncGenAThrow *o;
2711
0
    o = PyObject_GC_New(PyAsyncGenAThrow, &_PyAsyncGenAThrow_Type);
2712
0
    if (o == NULL) {
2713
0
        return NULL;
2714
0
    }
2715
0
    o->agt_gen = (PyAsyncGenObject*)Py_NewRef(gen);
2716
0
    o->agt_typ = Py_XNewRef(typ);
2717
0
    o->agt_tb = Py_XNewRef(tb);
2718
0
    o->agt_val = Py_XNewRef(val);
2719
2720
0
    o->agt_state = AWAITABLE_STATE_INIT;
2721
0
    _PyObject_GC_TRACK((PyObject*)o);
2722
0
    return (PyObject*)o;
2723
0
}