Coverage Report

Created: 2026-10-31 06:21

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
112M
    _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
71.2M
    ((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
195k
_PyGen_GetCode(PyGenObject *gen) {
70
195k
    return _PyFrame_GetCode(&gen->gi_iframe);
71
195k
}
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
554k
{
84
554k
    PyGenObject *gen = _PyGen_CAST(self);
85
554k
    Py_VISIT(gen->gi_name);
86
554k
    Py_VISIT(gen->gi_qualname);
87
554k
    if (gen->gi_frame_state != FRAME_CLEARED) {
88
553k
        _PyInterpreterFrame *frame = &gen->gi_iframe;
89
553k
        assert(frame->frame_obj == NULL ||
90
553k
               frame->frame_obj->f_frame->owner == FRAME_OWNED_BY_GENERATOR);
91
553k
        int err = _PyFrame_Traverse(frame, visit, arg);
92
553k
        if (err) {
93
0
            return err;
94
0
        }
95
553k
    }
96
1.15k
    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
1.15k
        _Py_VISIT_STACKREF(gen->gi_iframe.f_executable);
100
1.15k
    }
101
    /* No need to visit cr_origin, because it's just tuples/str/int, so can't
102
       participate in a reference cycle. */
103
554k
    Py_VISIT(gen->gi_exc_state.exc_value);
104
554k
    return 0;
105
554k
}
106
107
static void
108
gen_finalize(PyObject *self)
109
40.6M
{
110
40.6M
    PyGenObject *gen = (PyGenObject *)self;
111
112
40.6M
    if (FRAME_STATE_FINISHED(gen->gi_frame_state)) {
113
        /* Generator isn't paused, so no need to close */
114
40.5M
        return;
115
40.5M
    }
116
117
195k
    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
195k
    PyObject *exc = PyErr_GetRaisedException();
140
141
    /* If `gen` is a coroutine, and if it was never awaited on,
142
       issue a RuntimeWarning. */
143
195k
    assert(_PyGen_GetCode(gen) != NULL);
144
195k
    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
195k
    else {
150
195k
        PyObject *res = gen_close((PyObject*)gen, NULL);
151
195k
        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
195k
        else {
158
195k
            Py_DECREF(res);
159
195k
        }
160
195k
    }
161
162
    /* Restore the saved exception. */
163
195k
    PyErr_SetRaisedException(exc);
164
195k
}
165
166
static void
167
gen_clear_frame(PyGenObject *gen)
168
195k
{
169
195k
    assert(FT_ATOMIC_LOAD_INT8_RELAXED(gen->gi_frame_state) == FRAME_CLEARED);
170
195k
    _PyInterpreterFrame *frame = &gen->gi_iframe;
171
195k
    _PyThreadState_UpdateLastProfiledFrame(_PyThreadState_GET(), frame, frame->previous);
172
195k
    frame->previous = NULL;
173
195k
    Py_BEGIN_CRITICAL_SECTION(gen);
174
195k
    _PyFrame_ClearExceptCode(frame);
175
195k
    Py_END_CRITICAL_SECTION();
176
195k
    _PyErr_ClearExcState(&gen->gi_exc_state);
177
195k
}
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
40.6M
{
210
40.6M
    PyGenObject *gen = _PyGen_CAST(self);
211
212
40.6M
    _PyObject_GC_UNTRACK(gen);
213
214
40.6M
    FT_CLEAR_WEAKREFS(self, gen->gi_weakreflist);
215
216
40.6M
    _PyObject_GC_TRACK(self);
217
218
40.6M
    if (PyObject_CallFinalizerFromDealloc(self))
219
0
        return;                     /* resurrected.  :( */
220
221
40.6M
    _PyObject_GC_UNTRACK(self);
222
40.6M
    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
40.6M
    if (PyCoro_CheckExact(gen)) {
229
37
        Py_CLEAR(((PyCoroObject *)gen)->cr_origin_or_finalizer);
230
37
    }
231
40.6M
    if (gen->gi_frame_state != FRAME_CLEARED) {
232
0
        gen->gi_frame_state = FRAME_CLEARED;
233
0
        gen_clear_frame(gen);
234
0
    }
235
40.6M
    assert(gen->gi_exc_state.exc_value == NULL);
236
40.6M
    PyStackRef_CLEAR(gen->gi_iframe.f_executable);
237
40.6M
    Py_CLEAR(gen->gi_name);
238
40.6M
    Py_CLEAR(gen->gi_qualname);
239
240
40.6M
    PyObject_GC_Del(gen);
241
40.6M
}
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
70.9M
{
264
70.9M
    assert(FT_ATOMIC_LOAD_INT8_RELAXED(gen->gi_frame_state) == FRAME_EXECUTING);
265
266
70.9M
    PyThreadState *tstate = _PyThreadState_GET();
267
70.9M
    _PyInterpreterFrame *frame = &gen->gi_iframe;
268
269
    /* Push arg onto the frame's value stack */
270
70.9M
    PyObject *arg_obj = arg ? arg : Py_None;
271
70.9M
    _PyFrame_StackPush(frame, PyStackRef_FromPyObjectNew(arg_obj));
272
273
70.9M
    _PyErr_StackItem *prev_exc_info = tstate->exc_info;
274
70.9M
    gen->gi_exc_state.previous_item = prev_exc_info;
275
70.9M
    tstate->exc_info = &gen->gi_exc_state;
276
277
70.9M
    if (exc) {
278
38.3k
        assert(_PyErr_Occurred(tstate));
279
38.3k
        _PyErr_ChainStackItem();
280
38.3k
    }
281
282
70.9M
    EVAL_CALL_STAT_INC(EVAL_CALL_GENERATOR);
283
70.9M
    PyObject *result = _PyEval_EvalFrame(tstate, frame, exc);
284
70.9M
    assert(tstate->exc_info == prev_exc_info);
285
70.9M
#ifndef Py_GIL_DISABLED
286
70.9M
    assert(gen->gi_exc_state.previous_item == NULL);
287
70.9M
    assert(frame->previous == NULL);
288
70.9M
    assert(gen->gi_frame_state != FRAME_EXECUTING);
289
70.9M
#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
70.9M
    int return_kind = ((_PyThreadStateImpl *)tstate)->generator_return_kind;
296
297
70.9M
    if (return_kind == GENERATOR_YIELD) {
298
57.4M
        assert(result != NULL && !_PyErr_Occurred(tstate));
299
57.4M
#ifndef Py_GIL_DISABLED
300
57.4M
        assert(FRAME_STATE_SUSPENDED(gen->gi_frame_state));
301
57.4M
#endif
302
57.4M
        *presult = result;
303
57.4M
        return PYGEN_NEXT;
304
57.4M
    }
305
306
70.9M
    assert(return_kind == GENERATOR_RETURN);
307
13.4M
    assert(gen->gi_exc_state.exc_value == NULL);
308
13.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
13.4M
    if (result) {
313
13.4M
        assert(result == Py_None || !PyAsyncGen_CheckExact(gen));
314
13.4M
        if (result == Py_None && !PyAsyncGen_CheckExact(gen) && !arg) {
315
            /* Return NULL if called by gen_iternext() */
316
13.4M
            Py_CLEAR(result);
317
13.4M
        }
318
13.4M
    }
319
55.6k
    else {
320
55.6k
        assert(!PyErr_ExceptionMatches(PyExc_StopIteration));
321
55.6k
        assert(!PyAsyncGen_CheckExact(gen) ||
322
55.6k
            !PyErr_ExceptionMatches(PyExc_StopAsyncIteration));
323
55.6k
    }
324
325
13.4M
    *presult = result;
326
13.4M
    return result ? PYGEN_RETURN : PYGEN_ERROR;
327
70.9M
}
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
70.8M
{
334
70.8M
    *presult = NULL;
335
70.8M
    int8_t frame_state = FT_ATOMIC_LOAD_INT8_RELAXED(gen->gi_frame_state);
336
70.8M
    do {
337
70.8M
        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
70.8M
        if (frame_state == FRAME_EXECUTING) {
351
0
            gen_raise_already_executing_error(gen);
352
0
            return PYGEN_ERROR;
353
0
        }
354
70.8M
        if (FRAME_STATE_FINISHED(frame_state)) {
355
20.7k
            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.7k
            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.7k
            return PYGEN_ERROR;
370
20.7k
        }
371
372
70.8M
        assert((frame_state == FRAME_CREATED) ||
373
70.8M
               FRAME_STATE_SUSPENDED(frame_state));
374
70.8M
    } while (!_Py_GEN_TRY_SET_FRAME_STATE(gen, frame_state, FRAME_EXECUTING));
375
376
70.8M
    return gen_send_ex2(gen, arg, presult, 0);
377
70.8M
}
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
32.0k
{
456
32.0k
    uint8_t code = FT_ATOMIC_LOAD_UINT8_RELAXED(instr->op.code);
457
32.0k
    return (
458
32.0k
        code == RESUME ||
459
30.5k
        code == RESUME_CHECK ||
460
0
        code == RESUME_CHECK_JIT ||
461
0
        code == INSTRUMENTED_RESUME
462
32.0k
    );
463
32.0k
}
464
465
static PyObject *
466
gen_close(PyObject *self, PyObject *args)
467
195k
{
468
195k
    PyGenObject *gen = _PyGen_CAST(self);
469
470
195k
    int8_t frame_state = FT_ATOMIC_LOAD_INT8_RELAXED(gen->gi_frame_state);
471
195k
    do {
472
195k
        if (frame_state == FRAME_CREATED) {
473
            // && (1) to avoid -Wunreachable-code warning on Clang
474
163k
            if (!_Py_GEN_TRY_SET_FRAME_STATE(gen, frame_state, FRAME_CLEARED) && (1)) {
475
0
                continue;
476
0
            }
477
163k
            gen_clear_frame(gen);
478
163k
            Py_RETURN_NONE;
479
163k
        }
480
481
32.0k
        if (FRAME_STATE_FINISHED(frame_state)) {
482
0
            Py_RETURN_NONE;
483
0
        }
484
485
32.0k
        if (frame_state == FRAME_EXECUTING) {
486
0
            gen_raise_already_executing_error(gen);
487
0
            return NULL;
488
0
        }
489
490
32.0k
        assert(FRAME_STATE_SUSPENDED(frame_state));
491
32.0k
    } while (!_Py_GEN_TRY_SET_FRAME_STATE(gen, frame_state, FRAME_EXECUTING));
492
493
32.0k
    int err = 0;
494
32.0k
    _PyInterpreterFrame *frame = &gen->gi_iframe;
495
32.0k
    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
32.0k
    if (is_resume(frame->instr_ptr)) {
502
32.0k
        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
32.0k
        int oparg = frame->instr_ptr->op.arg;
507
32.0k
        if (oparg & RESUME_OPARG_DEPTH1_MASK && no_unwind_tools) {
508
            // RESUME after YIELD_VALUE and exception depth is 1
509
31.9k
            assert((oparg & RESUME_OPARG_LOCATION_MASK) != RESUME_AT_FUNC_START);
510
31.9k
            FT_ATOMIC_STORE_INT8_RELEASE(gen->gi_frame_state, FRAME_CLEARED);
511
31.9k
            gen_clear_frame(gen);
512
31.9k
            Py_RETURN_NONE;
513
31.9k
        }
514
32.0k
    }
515
168
    if (err == 0) {
516
168
        PyErr_SetNone(PyExc_GeneratorExit);
517
168
    }
518
519
168
    PyObject *retval;
520
168
    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
168
    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
168
    assert(PyErr_Occurred());
537
538
168
    if (PyErr_ExceptionMatches(PyExc_GeneratorExit)) {
539
168
        PyErr_Clear();          /* ignore this error */
540
168
        Py_RETURN_NONE;
541
168
    }
542
0
    return NULL;
543
168
}
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
38.1k
{
550
    /* First, check the traceback argument, replacing None with
551
       NULL. */
552
38.1k
    if (tb == Py_None) {
553
0
        tb = NULL;
554
0
    }
555
38.1k
    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
38.1k
    Py_INCREF(typ);
562
38.1k
    Py_XINCREF(val);
563
38.1k
    Py_XINCREF(tb);
564
565
38.1k
    if (PyExceptionClass_Check(typ)) {
566
0
        PyErr_NormalizeException(&typ, &val, &tb);
567
0
    }
568
38.1k
    else if (PyExceptionInstance_Check(typ)) {
569
        /* Raising an instance.  The value should be a dummy. */
570
38.1k
        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
38.1k
        else {
576
            /* Normalize to raise <class>, <instance> */
577
38.1k
            Py_XSETREF(val, typ);
578
38.1k
            typ = Py_NewRef(PyExceptionInstance_Class(typ));
579
580
38.1k
            if (tb == NULL)
581
                /* Returns NULL if there's no traceback */
582
38.1k
                tb = PyException_GetTraceback(val);
583
38.1k
        }
584
38.1k
    }
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
38.1k
    PyErr_Restore(typ, val, tb);
595
38.1k
    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
38.1k
}
604
605
static PyObject *
606
gen_throw_current_exception(PyGenObject *gen)
607
38.1k
{
608
38.1k
    assert(FT_ATOMIC_LOAD_INT8_RELAXED(gen->gi_frame_state) == FRAME_EXECUTING);
609
610
38.1k
    PyObject *result;
611
38.1k
    if (gen_send_ex2(gen, Py_None, &result, 1) == PYGEN_RETURN) {
612
0
        return gen_set_stop_iteration(gen, result);
613
0
    }
614
38.1k
    return result;
615
38.1k
}
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
38.1k
{
630
38.1k
    int8_t frame_state = FT_ATOMIC_LOAD_INT8_RELAXED(gen->gi_frame_state);
631
38.1k
    do {
632
38.1k
        if (frame_state == FRAME_EXECUTING) {
633
0
            gen_raise_already_executing_error(gen);
634
0
            return NULL;
635
0
        }
636
637
38.1k
        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
38.1k
        assert((frame_state == FRAME_CREATED) ||
650
38.1k
               FRAME_STATE_SUSPENDED(frame_state));
651
38.1k
    } while (!_Py_GEN_TRY_SET_FRAME_STATE(gen, frame_state, FRAME_EXECUTING));
652
653
38.1k
    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
38.1k
throw_here:
722
38.1k
    assert(FT_ATOMIC_LOAD_INT8_RELAXED(gen->gi_frame_state) == FRAME_EXECUTING);
723
38.1k
    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
38.1k
    return gen_throw_current_exception(gen);
728
38.1k
}
729
730
731
static PyObject *
732
gen_throw(PyObject *op, PyObject *const *args, Py_ssize_t nargs)
733
38.1k
{
734
38.1k
    PyGenObject *gen = _PyGen_CAST(op);
735
38.1k
    PyObject *typ;
736
38.1k
    PyObject *tb = NULL;
737
38.1k
    PyObject *val = NULL;
738
739
38.1k
    if (!_PyArg_CheckPositional("throw", nargs, 1, 3)) {
740
0
        return NULL;
741
0
    }
742
38.1k
    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
38.1k
    typ = args[0];
751
38.1k
    if (nargs == 3) {
752
0
        val = args[1];
753
0
        tb = args[2];
754
0
    }
755
38.1k
    else if (nargs == 2) {
756
0
        val = args[1];
757
0
    }
758
38.1k
    return _gen_throw(gen, 1, typ, val, tb);
759
38.1k
}
760
761
762
static PyObject *
763
gen_iternext(PyObject *self)
764
70.8M
{
765
70.8M
    assert(PyGen_CheckExact(self) || PyCoro_CheckExact(self));
766
70.8M
    PyGenObject *gen = _PyGen_CAST(self);
767
768
70.8M
    PyObject *result;
769
70.8M
    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
70.8M
    return result;
776
70.8M
}
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
40.6M
{
1109
40.6M
    PyCodeObject *code = (PyCodeObject *)func->func_code;
1110
40.6M
    int slots = _PyFrame_NumSlotsForCodeObject(code);
1111
40.6M
    PyGenObject *gen = PyObject_GC_NewVar(PyGenObject, type, slots);
1112
40.6M
    if (gen == NULL) {
1113
0
        return NULL;
1114
0
    }
1115
40.6M
    gen->gi_frame_state = FRAME_CLEARED;
1116
40.6M
    gen->gi_weakreflist = NULL;
1117
40.6M
    gen->gi_exc_state.exc_value = NULL;
1118
40.6M
    gen->gi_exc_state.previous_item = NULL;
1119
40.6M
    gen->gi_iframe.f_executable = PyStackRef_None;
1120
40.6M
    PyObject *name = FT_ATOMIC_LOAD_PTR_ACQUIRE(func->func_name);
1121
40.6M
    assert(name != NULL);
1122
40.6M
    gen->gi_name = Py_NewRef(name);
1123
40.6M
    PyObject *qualname = FT_ATOMIC_LOAD_PTR_ACQUIRE(func->func_qualname);
1124
40.6M
    assert(qualname != NULL);
1125
40.6M
    gen->gi_qualname = Py_NewRef(qualname);
1126
40.6M
    _PyObject_GC_TRACK(gen);
1127
40.6M
    return (PyObject *)gen;
1128
40.6M
}
1129
1130
PyObject *
1131
_Py_MakeCoro(PyFunctionObject *func)
1132
40.6M
{
1133
40.6M
    int coro_flags = ((PyCodeObject *)func->func_code)->co_flags &
1134
40.6M
        (CO_GENERATOR | CO_COROUTINE | CO_ASYNC_GENERATOR);
1135
40.6M
    assert(coro_flags);
1136
40.6M
    if (coro_flags == CO_GENERATOR) {
1137
40.6M
        return make_gen(&PyGen_Type, func);
1138
40.6M
    }
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
// Report an async yield as PYGEN_RETURN with the yielded value.
1969
static PySendResult
1970
async_gen_unwrap_send(PyAsyncGenObject *gen, PyObject *result,
1971
                      PyObject **presult)
1972
0
{
1973
0
    if (result == NULL) {
1974
0
        if (!PyErr_Occurred()) {
1975
0
            PyErr_SetNone(PyExc_StopAsyncIteration);
1976
0
        }
1977
1978
0
        if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration)
1979
0
            || PyErr_ExceptionMatches(PyExc_GeneratorExit)
1980
0
        ) {
1981
0
            FT_ATOMIC_STORE_INT8_RELAXED(gen->ag_closed, 1);
1982
0
        }
1983
1984
0
        *presult = NULL;
1985
0
        return PYGEN_ERROR;
1986
0
    }
1987
1988
0
    if (_PyAsyncGenWrappedValue_CheckExact(result)) {
1989
        /* async yield */
1990
0
        *presult = Py_NewRef(((_PyAsyncGenWrappedValue*)result)->agw_val);
1991
0
        Py_DECREF(result);
1992
0
        return PYGEN_RETURN;
1993
0
    }
1994
1995
0
    *presult = result;
1996
0
    return PYGEN_NEXT;
1997
0
}
1998
1999
static PyObject *
2000
async_gen_unwrap_value(PyAsyncGenObject *gen, PyObject *result)
2001
0
{
2002
0
    PyObject *value;
2003
0
    if (async_gen_unwrap_send(gen, result, &value) == PYGEN_RETURN) {
2004
0
        _PyGen_SetStopIterationValue(value);
2005
0
        Py_DECREF(value);
2006
0
        return NULL;
2007
0
    }
2008
0
    return value;
2009
0
}
2010
2011
2012
/* ---------- Async Generator ASend Awaitable ------------ */
2013
2014
2015
static void
2016
async_gen_asend_dealloc(PyObject *self)
2017
0
{
2018
0
    assert(PyAsyncGenASend_CheckExact(self));
2019
0
    PyAsyncGenASend *ags = _PyAsyncGenASend_CAST(self);
2020
2021
    // The finalizer only warns about an asend() that was never awaited.
2022
0
    if (ags->ags_state == AWAITABLE_STATE_INIT
2023
0
        && PyObject_CallFinalizerFromDealloc(self))
2024
0
    {
2025
0
        return;
2026
0
    }
2027
2028
0
    _PyObject_GC_UNTRACK(self);
2029
0
    Py_CLEAR(ags->ags_gen);
2030
0
    Py_CLEAR(ags->ags_sendval);
2031
2032
0
    _PyGC_CLEAR_FINALIZED(self);
2033
2034
0
    _Py_FREELIST_FREE(async_gen_asends, self, PyObject_GC_Del);
2035
0
}
2036
2037
static int
2038
async_gen_asend_traverse(PyObject *self, visitproc visit, void *arg)
2039
0
{
2040
0
    PyAsyncGenASend *ags = _PyAsyncGenASend_CAST(self);
2041
0
    Py_VISIT(ags->ags_gen);
2042
0
    Py_VISIT(ags->ags_sendval);
2043
0
    return 0;
2044
0
}
2045
2046
2047
PySendResult
2048
_PyAsyncGenASend_Send(PyObject *self, PyObject *arg, PyObject **presult)
2049
0
{
2050
0
    PyAsyncGenASend *o = _PyAsyncGenASend_CAST(self);
2051
2052
0
    *presult = NULL;
2053
0
    int8_t state = FT_ATOMIC_LOAD_INT8_RELAXED(o->ags_state);
2054
0
    do {
2055
0
        if (state == AWAITABLE_STATE_CLOSED) {
2056
0
            PyErr_SetString(
2057
0
                PyExc_RuntimeError,
2058
0
                "cannot reuse already awaited __anext__()/asend()");
2059
0
            return PYGEN_ERROR;
2060
0
        }
2061
0
        if (state == AWAITABLE_STATE_ITER) {
2062
0
            goto do_send;
2063
0
        }
2064
0
        assert(state == AWAITABLE_STATE_INIT);
2065
0
    } while (!_Py_ASYNC_GEN_TRY_SET_STATE(o->ags_state, state,
2066
0
                                          AWAITABLE_STATE_ITER));
2067
2068
    // The transition above only guards this object, the generator may
2069
    // still be running through another asend()/athrow() object so
2070
    // try to claim it before running.
2071
0
    if (!async_gen_try_claim_running(o->ags_gen)) {
2072
0
        FT_ATOMIC_STORE_INT8_RELAXED(o->ags_state, AWAITABLE_STATE_CLOSED);
2073
0
        PyErr_SetString(
2074
0
            PyExc_RuntimeError,
2075
0
            "anext(): asynchronous generator is already running");
2076
0
        return PYGEN_ERROR;
2077
0
    }
2078
2079
0
    if (arg == NULL || arg == Py_None) {
2080
0
        arg = o->ags_sendval;
2081
0
    }
2082
2083
0
    PyObject *result;
2084
0
    PySendResult res;
2085
0
do_send:
2086
0
    result = gen_send((PyObject*)o->ags_gen, arg);
2087
0
    res = async_gen_unwrap_send(o->ags_gen, result, presult);
2088
2089
0
    if (res != PYGEN_NEXT) {
2090
0
        FT_ATOMIC_STORE_INT8_RELAXED(o->ags_state, AWAITABLE_STATE_CLOSED);
2091
0
        FT_ATOMIC_STORE_INT8_RELEASE(o->ags_gen->ag_running_async, 0);
2092
0
    }
2093
2094
0
    return res;
2095
0
}
2096
2097
static PyObject *
2098
async_gen_asend_send(PyObject *self, PyObject *arg)
2099
0
{
2100
0
    PyObject *result;
2101
0
    if (_PyAsyncGenASend_Send(self, arg, &result) == PYGEN_RETURN) {
2102
0
        _PyGen_SetStopIterationValue(result);
2103
0
        Py_DECREF(result);
2104
0
        return NULL;
2105
0
    }
2106
0
    return result;
2107
0
}
2108
2109
2110
static PyObject *
2111
async_gen_asend_iternext(PyObject *ags)
2112
0
{
2113
0
    return async_gen_asend_send(ags, NULL);
2114
0
}
2115
2116
2117
static PyObject *
2118
async_gen_asend_throw(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
2119
0
{
2120
0
    PyAsyncGenASend *o = _PyAsyncGenASend_CAST(self);
2121
2122
0
    int8_t state = FT_ATOMIC_LOAD_INT8_RELAXED(o->ags_state);
2123
0
    do {
2124
0
        if (state == AWAITABLE_STATE_CLOSED) {
2125
0
            PyErr_SetString(
2126
0
                PyExc_RuntimeError,
2127
0
                "cannot reuse already awaited __anext__()/asend()");
2128
0
            return NULL;
2129
0
        }
2130
0
        if (state == AWAITABLE_STATE_ITER) {
2131
0
            goto do_throw;
2132
0
        }
2133
0
        assert(state == AWAITABLE_STATE_INIT);
2134
0
    } while (!_Py_ASYNC_GEN_TRY_SET_STATE(o->ags_state, state,
2135
0
                                          AWAITABLE_STATE_ITER));
2136
2137
    // The transition above only guards this object, the generator may
2138
    // still be running through another asend()/athrow() object so
2139
    // try to claim it before running.
2140
0
    if (!async_gen_try_claim_running(o->ags_gen)) {
2141
0
        FT_ATOMIC_STORE_INT8_RELAXED(o->ags_state, AWAITABLE_STATE_CLOSED);
2142
0
        PyErr_SetString(
2143
0
            PyExc_RuntimeError,
2144
0
            "anext(): asynchronous generator is already running");
2145
0
        return NULL;
2146
0
    }
2147
2148
0
    PyObject *result;
2149
0
do_throw:
2150
0
    result = gen_throw((PyObject*)o->ags_gen, args, nargs);
2151
0
    result = async_gen_unwrap_value(o->ags_gen, result);
2152
2153
0
    if (result == NULL) {
2154
0
        FT_ATOMIC_STORE_INT8_RELAXED(o->ags_state, AWAITABLE_STATE_CLOSED);
2155
0
        FT_ATOMIC_STORE_INT8_RELEASE(o->ags_gen->ag_running_async, 0);
2156
0
    }
2157
2158
0
    return result;
2159
0
}
2160
2161
2162
static PyObject *
2163
async_gen_asend_close(PyObject *self, PyObject *args)
2164
0
{
2165
0
    PyAsyncGenASend *o = _PyAsyncGenASend_CAST(self);
2166
0
    if (FT_ATOMIC_LOAD_INT8_RELAXED(o->ags_state) == AWAITABLE_STATE_CLOSED) {
2167
0
        Py_RETURN_NONE;
2168
0
    }
2169
2170
0
    PyObject *result = async_gen_asend_throw(self, &PyExc_GeneratorExit, 1);
2171
0
    if (result == NULL) {
2172
0
        if (PyErr_ExceptionMatches(PyExc_StopIteration) ||
2173
0
            PyErr_ExceptionMatches(PyExc_StopAsyncIteration) ||
2174
0
            PyErr_ExceptionMatches(PyExc_GeneratorExit))
2175
0
        {
2176
0
            PyErr_Clear();
2177
0
            Py_RETURN_NONE;
2178
0
        }
2179
0
        return result;
2180
0
    }
2181
2182
0
    Py_DECREF(result);
2183
0
    PyErr_SetString(PyExc_RuntimeError, "coroutine ignored GeneratorExit");
2184
0
    return NULL;
2185
0
}
2186
2187
static void
2188
async_gen_asend_finalize(PyObject *self)
2189
0
{
2190
0
    PyAsyncGenASend *ags = _PyAsyncGenASend_CAST(self);
2191
    // async_gen_asend_dealloc() calls this only in the INIT state.
2192
0
    if (ags->ags_state == AWAITABLE_STATE_INIT) {
2193
0
        _PyErr_WarnUnawaitedAgenMethod(ags->ags_gen, &_Py_ID(asend));
2194
0
    }
2195
0
}
2196
2197
static PyMethodDef async_gen_asend_methods[] = {
2198
    {"send", async_gen_asend_send, METH_O, send_doc},
2199
    {"throw", _PyCFunction_CAST(async_gen_asend_throw), METH_FASTCALL, throw_doc},
2200
    {"close", async_gen_asend_close, METH_NOARGS, close_doc},
2201
    {NULL, NULL}        /* Sentinel */
2202
};
2203
2204
2205
static PyAsyncMethods async_gen_asend_as_async = {
2206
    .am_await = PyObject_SelfIter,
2207
    .am_send = _PyAsyncGenASend_Send,
2208
};
2209
2210
2211
PyTypeObject _PyAsyncGenASend_Type = {
2212
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
2213
    "async_generator_asend",                    /* tp_name */
2214
    sizeof(PyAsyncGenASend),                    /* tp_basicsize */
2215
    0,                                          /* tp_itemsize */
2216
    /* methods */
2217
    async_gen_asend_dealloc,                    /* tp_dealloc */
2218
    0,                                          /* tp_vectorcall_offset */
2219
    0,                                          /* tp_getattr */
2220
    0,                                          /* tp_setattr */
2221
    &async_gen_asend_as_async,                  /* tp_as_async */
2222
    0,                                          /* tp_repr */
2223
    0,                                          /* tp_as_number */
2224
    0,                                          /* tp_as_sequence */
2225
    0,                                          /* tp_as_mapping */
2226
    0,                                          /* tp_hash */
2227
    0,                                          /* tp_call */
2228
    0,                                          /* tp_str */
2229
    PyObject_GenericGetAttr,                    /* tp_getattro */
2230
    0,                                          /* tp_setattro */
2231
    0,                                          /* tp_as_buffer */
2232
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,    /* tp_flags */
2233
    0,                                          /* tp_doc */
2234
    async_gen_asend_traverse,                   /* tp_traverse */
2235
    0,                                          /* tp_clear */
2236
    0,                                          /* tp_richcompare */
2237
    0,                                          /* tp_weaklistoffset */
2238
    PyObject_SelfIter,                          /* tp_iter */
2239
    async_gen_asend_iternext,                   /* tp_iternext */
2240
    async_gen_asend_methods,                    /* tp_methods */
2241
    0,                                          /* tp_members */
2242
    0,                                          /* tp_getset */
2243
    0,                                          /* tp_base */
2244
    0,                                          /* tp_dict */
2245
    0,                                          /* tp_descr_get */
2246
    0,                                          /* tp_descr_set */
2247
    0,                                          /* tp_dictoffset */
2248
    0,                                          /* tp_init */
2249
    0,                                          /* tp_alloc */
2250
    0,                                          /* tp_new */
2251
    .tp_finalize = async_gen_asend_finalize,
2252
};
2253
2254
2255
static PyObject *
2256
async_gen_asend_new(PyAsyncGenObject *gen, PyObject *sendval)
2257
0
{
2258
0
    PyAsyncGenASend *ags = _Py_FREELIST_POP(PyAsyncGenASend, async_gen_asends);
2259
0
    if (ags == NULL) {
2260
0
        ags = PyObject_GC_New(PyAsyncGenASend, &_PyAsyncGenASend_Type);
2261
0
        if (ags == NULL) {
2262
0
            return NULL;
2263
0
        }
2264
0
    }
2265
2266
0
    ags->ags_gen = (PyAsyncGenObject*)Py_NewRef(gen);
2267
0
    ags->ags_sendval = Py_XNewRef(sendval);
2268
0
    ags->ags_state = AWAITABLE_STATE_INIT;
2269
2270
0
    _PyObject_GC_TRACK((PyObject*)ags);
2271
0
    return (PyObject*)ags;
2272
0
}
2273
2274
2275
/* ---------- Async Generator Value Wrapper ------------ */
2276
2277
2278
static void
2279
async_gen_wrapped_val_dealloc(PyObject *self)
2280
0
{
2281
0
    _PyAsyncGenWrappedValue *agw = _PyAsyncGenWrappedValue_CAST(self);
2282
0
    _PyObject_GC_UNTRACK(self);
2283
0
    Py_CLEAR(agw->agw_val);
2284
0
    _Py_FREELIST_FREE(async_gens, self, PyObject_GC_Del);
2285
0
}
2286
2287
2288
static int
2289
async_gen_wrapped_val_traverse(PyObject *self, visitproc visit, void *arg)
2290
0
{
2291
0
    _PyAsyncGenWrappedValue *agw = _PyAsyncGenWrappedValue_CAST(self);
2292
0
    Py_VISIT(agw->agw_val);
2293
0
    return 0;
2294
0
}
2295
2296
2297
PyTypeObject _PyAsyncGenWrappedValue_Type = {
2298
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
2299
    "async_generator_wrapped_value",            /* tp_name */
2300
    sizeof(_PyAsyncGenWrappedValue),            /* tp_basicsize */
2301
    0,                                          /* tp_itemsize */
2302
    /* methods */
2303
    async_gen_wrapped_val_dealloc,              /* tp_dealloc */
2304
    0,                                          /* tp_vectorcall_offset */
2305
    0,                                          /* tp_getattr */
2306
    0,                                          /* tp_setattr */
2307
    0,                                          /* tp_as_async */
2308
    0,                                          /* tp_repr */
2309
    0,                                          /* tp_as_number */
2310
    0,                                          /* tp_as_sequence */
2311
    0,                                          /* tp_as_mapping */
2312
    0,                                          /* tp_hash */
2313
    0,                                          /* tp_call */
2314
    0,                                          /* tp_str */
2315
    PyObject_GenericGetAttr,                    /* tp_getattro */
2316
    0,                                          /* tp_setattro */
2317
    0,                                          /* tp_as_buffer */
2318
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,    /* tp_flags */
2319
    0,                                          /* tp_doc */
2320
    async_gen_wrapped_val_traverse,             /* tp_traverse */
2321
    0,                                          /* tp_clear */
2322
    0,                                          /* tp_richcompare */
2323
    0,                                          /* tp_weaklistoffset */
2324
    0,                                          /* tp_iter */
2325
    0,                                          /* tp_iternext */
2326
    0,                                          /* tp_methods */
2327
    0,                                          /* tp_members */
2328
    0,                                          /* tp_getset */
2329
    0,                                          /* tp_base */
2330
    0,                                          /* tp_dict */
2331
    0,                                          /* tp_descr_get */
2332
    0,                                          /* tp_descr_set */
2333
    0,                                          /* tp_dictoffset */
2334
    0,                                          /* tp_init */
2335
    0,                                          /* tp_alloc */
2336
    0,                                          /* tp_new */
2337
};
2338
2339
2340
PyObject *
2341
_PyAsyncGenValueWrapperNew(PyThreadState *tstate, PyObject *val)
2342
0
{
2343
0
    assert(val);
2344
2345
0
    _PyAsyncGenWrappedValue *o = _Py_FREELIST_POP(_PyAsyncGenWrappedValue, async_gens);
2346
0
    if (o == NULL) {
2347
0
        o = PyObject_GC_New(_PyAsyncGenWrappedValue,
2348
0
                            &_PyAsyncGenWrappedValue_Type);
2349
0
        if (o == NULL) {
2350
0
            return NULL;
2351
0
        }
2352
0
    }
2353
0
    assert(_PyAsyncGenWrappedValue_CheckExact(o));
2354
0
    o->agw_val = Py_NewRef(val);
2355
0
    _PyObject_GC_TRACK((PyObject*)o);
2356
0
    return (PyObject*)o;
2357
0
}
2358
2359
2360
/* ---------- Async Generator AThrow awaitable ------------ */
2361
2362
#define _PyAsyncGenAThrow_CAST(op) \
2363
0
    (assert(Py_IS_TYPE((op), &_PyAsyncGenAThrow_Type)), \
2364
0
     _Py_CAST(PyAsyncGenAThrow*, (op)))
2365
2366
static void
2367
async_gen_athrow_dealloc(PyObject *self)
2368
0
{
2369
0
    PyAsyncGenAThrow *agt = _PyAsyncGenAThrow_CAST(self);
2370
0
    if (PyObject_CallFinalizerFromDealloc(self)) {
2371
0
        return;
2372
0
    }
2373
2374
0
    _PyObject_GC_UNTRACK(self);
2375
0
    Py_CLEAR(agt->agt_gen);
2376
0
    Py_XDECREF(agt->agt_typ);
2377
0
    Py_XDECREF(agt->agt_tb);
2378
0
    Py_XDECREF(agt->agt_val);
2379
0
    PyObject_GC_Del(self);
2380
0
}
2381
2382
2383
static int
2384
async_gen_athrow_traverse(PyObject *self, visitproc visit, void *arg)
2385
0
{
2386
0
    PyAsyncGenAThrow *agt = _PyAsyncGenAThrow_CAST(self);
2387
0
    Py_VISIT(agt->agt_gen);
2388
0
    Py_VISIT(agt->agt_typ);
2389
0
    Py_VISIT(agt->agt_tb);
2390
0
    Py_VISIT(agt->agt_val);
2391
0
    return 0;
2392
0
}
2393
2394
2395
static PyObject *
2396
async_gen_athrow_send(PyObject *self, PyObject *arg)
2397
0
{
2398
0
    PyAsyncGenAThrow *o = _PyAsyncGenAThrow_CAST(self);
2399
0
    PyGenObject *gen = _PyGen_CAST(o->agt_gen);
2400
0
    PyObject *retval;
2401
2402
0
    int8_t state = FT_ATOMIC_LOAD_INT8_RELAXED(o->agt_state);
2403
0
    if (state == AWAITABLE_STATE_CLOSED) {
2404
0
        PyErr_SetString(
2405
0
            PyExc_RuntimeError,
2406
0
            "cannot reuse already awaited aclose()/athrow()");
2407
0
        return NULL;
2408
0
    }
2409
2410
0
    if (FRAME_STATE_FINISHED(FT_ATOMIC_LOAD_INT8_RELAXED(gen->gi_frame_state))) {
2411
        // Close the awaitable, unless another thread transitioned it
2412
        // to a different state in the meantime.
2413
0
        (void)_Py_ASYNC_GEN_TRY_SET_STATE(o->agt_state, state,
2414
0
                                          AWAITABLE_STATE_CLOSED);
2415
0
        PyErr_SetNone(PyExc_StopIteration);
2416
0
        return NULL;
2417
0
    }
2418
2419
0
    do {
2420
0
        if (state == AWAITABLE_STATE_CLOSED) {
2421
0
            PyErr_SetString(
2422
0
                PyExc_RuntimeError,
2423
0
                "cannot reuse already awaited aclose()/athrow()");
2424
0
            return NULL;
2425
0
        }
2426
0
        if (state == AWAITABLE_STATE_ITER) {
2427
0
            goto do_send;
2428
0
        }
2429
0
        assert(state == AWAITABLE_STATE_INIT);
2430
0
        if (arg != Py_None) {
2431
0
            PyErr_SetString(PyExc_RuntimeError, NON_INIT_CORO_MSG);
2432
0
            return NULL;
2433
0
        }
2434
0
    } while (!_Py_ASYNC_GEN_TRY_SET_STATE(o->agt_state, state,
2435
0
                                          AWAITABLE_STATE_ITER));
2436
2437
    // The transition above only guards this object, the generator may
2438
    // still be running through another asend()/athrow() object so
2439
    // try to claim it before running.
2440
0
    if (!async_gen_try_claim_running(o->agt_gen)) {
2441
0
        FT_ATOMIC_STORE_INT8_RELAXED(o->agt_state, AWAITABLE_STATE_CLOSED);
2442
0
        if (o->agt_typ == NULL) {
2443
0
            PyErr_SetString(
2444
0
                PyExc_RuntimeError,
2445
0
                "aclose(): asynchronous generator is already running");
2446
0
        }
2447
0
        else {
2448
0
            PyErr_SetString(
2449
0
                PyExc_RuntimeError,
2450
0
                "athrow(): asynchronous generator is already running");
2451
0
        }
2452
0
        return NULL;
2453
0
    }
2454
2455
0
    if (FT_ATOMIC_LOAD_INT8_RELAXED(o->agt_gen->ag_closed)) {
2456
0
        FT_ATOMIC_STORE_INT8_RELAXED(o->agt_state, AWAITABLE_STATE_CLOSED);
2457
0
        FT_ATOMIC_STORE_INT8_RELEASE(o->agt_gen->ag_running_async, 0);
2458
0
        PyErr_SetNone(PyExc_StopAsyncIteration);
2459
0
        return NULL;
2460
0
    }
2461
2462
0
    if (o->agt_typ == NULL) {
2463
        /* aclose() mode */
2464
0
        FT_ATOMIC_STORE_INT8_RELAXED(o->agt_gen->ag_closed, 1);
2465
2466
0
        retval = _gen_throw((PyGenObject *)gen,
2467
0
                            0,  /* Do not close generator when
2468
                                   PyExc_GeneratorExit is passed */
2469
0
                            PyExc_GeneratorExit, NULL, NULL);
2470
2471
0
        if (retval && _PyAsyncGenWrappedValue_CheckExact(retval)) {
2472
0
            Py_DECREF(retval);
2473
0
            goto yield_close;
2474
0
        }
2475
0
    } else {
2476
0
        retval = _gen_throw((PyGenObject *)gen,
2477
0
                            0,  /* Do not close generator when
2478
                                   PyExc_GeneratorExit is passed */
2479
0
                            o->agt_typ, o->agt_val, o->agt_tb);
2480
0
        retval = async_gen_unwrap_value(o->agt_gen, retval);
2481
0
    }
2482
0
    if (retval == NULL) {
2483
0
        goto check_error;
2484
0
    }
2485
0
    return retval;
2486
2487
0
do_send:
2488
0
    retval = gen_send((PyObject *)gen, arg);
2489
0
    if (o->agt_typ) {
2490
0
        retval = async_gen_unwrap_value(o->agt_gen, retval);
2491
0
        if (retval == NULL) {
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
        }
2495
0
        return retval;
2496
0
    } else {
2497
        /* aclose() mode */
2498
0
        if (retval) {
2499
0
            if (_PyAsyncGenWrappedValue_CheckExact(retval)) {
2500
0
                Py_DECREF(retval);
2501
0
                goto yield_close;
2502
0
            }
2503
0
            else {
2504
0
                return retval;
2505
0
            }
2506
0
        }
2507
0
        else {
2508
0
            goto check_error;
2509
0
        }
2510
0
    }
2511
2512
0
yield_close:
2513
0
    FT_ATOMIC_STORE_INT8_RELAXED(o->agt_state, AWAITABLE_STATE_CLOSED);
2514
0
    FT_ATOMIC_STORE_INT8_RELEASE(o->agt_gen->ag_running_async, 0);
2515
0
    PyErr_SetString(
2516
0
        PyExc_RuntimeError, ASYNC_GEN_IGNORED_EXIT_MSG);
2517
0
    return NULL;
2518
2519
0
check_error:
2520
0
    FT_ATOMIC_STORE_INT8_RELAXED(o->agt_state, AWAITABLE_STATE_CLOSED);
2521
0
    FT_ATOMIC_STORE_INT8_RELEASE(o->agt_gen->ag_running_async, 0);
2522
0
    if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration) ||
2523
0
            PyErr_ExceptionMatches(PyExc_GeneratorExit))
2524
0
    {
2525
0
        if (o->agt_typ == NULL) {
2526
            /* when aclose() is called we don't want to propagate
2527
               StopAsyncIteration or GeneratorExit; just raise
2528
               StopIteration, signalling that this 'aclose()' await
2529
               is done.
2530
            */
2531
0
            PyErr_Clear();
2532
0
            PyErr_SetNone(PyExc_StopIteration);
2533
0
        }
2534
0
    }
2535
0
    return NULL;
2536
0
}
2537
2538
2539
static PyObject *
2540
async_gen_athrow_throw(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
2541
0
{
2542
0
    PyAsyncGenAThrow *o = _PyAsyncGenAThrow_CAST(self);
2543
2544
0
    int8_t state = FT_ATOMIC_LOAD_INT8_RELAXED(o->agt_state);
2545
0
    do {
2546
0
        if (state == AWAITABLE_STATE_CLOSED) {
2547
0
            PyErr_SetString(
2548
0
                PyExc_RuntimeError,
2549
0
                "cannot reuse already awaited aclose()/athrow()");
2550
0
            return NULL;
2551
0
        }
2552
0
        if (state == AWAITABLE_STATE_ITER) {
2553
0
            goto do_throw;
2554
0
        }
2555
0
        assert(state == AWAITABLE_STATE_INIT);
2556
0
    } while (!_Py_ASYNC_GEN_TRY_SET_STATE(o->agt_state, state,
2557
0
                                          AWAITABLE_STATE_ITER));
2558
2559
    // The transition above only guards this object, the generator may
2560
    // still be running through another asend()/athrow() object so
2561
    // try to claim it before running.
2562
0
    if (!async_gen_try_claim_running(o->agt_gen)) {
2563
0
        FT_ATOMIC_STORE_INT8_RELAXED(o->agt_state, AWAITABLE_STATE_CLOSED);
2564
0
        if (o->agt_typ == NULL) {
2565
0
            PyErr_SetString(
2566
0
                PyExc_RuntimeError,
2567
0
                "aclose(): asynchronous generator is already running");
2568
0
        }
2569
0
        else {
2570
0
            PyErr_SetString(
2571
0
                PyExc_RuntimeError,
2572
0
                "athrow(): asynchronous generator is already running");
2573
0
        }
2574
0
        return NULL;
2575
0
    }
2576
2577
0
    PyObject *retval;
2578
0
do_throw:
2579
0
    retval = gen_throw((PyObject*)o->agt_gen, args, nargs);
2580
0
    if (o->agt_typ) {
2581
0
        retval = async_gen_unwrap_value(o->agt_gen, retval);
2582
0
        if (retval == NULL) {
2583
0
            FT_ATOMIC_STORE_INT8_RELAXED(o->agt_state, AWAITABLE_STATE_CLOSED);
2584
0
            FT_ATOMIC_STORE_INT8_RELEASE(o->agt_gen->ag_running_async, 0);
2585
0
        }
2586
0
        return retval;
2587
0
    }
2588
0
    else {
2589
        /* aclose() mode */
2590
0
        if (retval && _PyAsyncGenWrappedValue_CheckExact(retval)) {
2591
0
            FT_ATOMIC_STORE_INT8_RELAXED(o->agt_state, AWAITABLE_STATE_CLOSED);
2592
0
            FT_ATOMIC_STORE_INT8_RELEASE(o->agt_gen->ag_running_async, 0);
2593
0
            Py_DECREF(retval);
2594
0
            PyErr_SetString(PyExc_RuntimeError, ASYNC_GEN_IGNORED_EXIT_MSG);
2595
0
            return NULL;
2596
0
        }
2597
0
        if (retval == NULL) {
2598
0
            FT_ATOMIC_STORE_INT8_RELAXED(o->agt_state, AWAITABLE_STATE_CLOSED);
2599
0
            FT_ATOMIC_STORE_INT8_RELEASE(o->agt_gen->ag_running_async, 0);
2600
0
        }
2601
0
        if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration) ||
2602
0
            PyErr_ExceptionMatches(PyExc_GeneratorExit))
2603
0
        {
2604
            /* when aclose() is called we don't want to propagate
2605
               StopAsyncIteration or GeneratorExit; just raise
2606
               StopIteration, signalling that this 'aclose()' await
2607
               is done.
2608
            */
2609
0
            PyErr_Clear();
2610
0
            PyErr_SetNone(PyExc_StopIteration);
2611
0
        }
2612
0
        return retval;
2613
0
    }
2614
0
}
2615
2616
2617
static PyObject *
2618
async_gen_athrow_iternext(PyObject *agt)
2619
0
{
2620
0
    return async_gen_athrow_send(agt, Py_None);
2621
0
}
2622
2623
2624
static PyObject *
2625
async_gen_athrow_close(PyObject *self, PyObject *args)
2626
0
{
2627
0
    PyAsyncGenAThrow *agt = _PyAsyncGenAThrow_CAST(self);
2628
0
    if (FT_ATOMIC_LOAD_INT8_RELAXED(agt->agt_state) == AWAITABLE_STATE_CLOSED) {
2629
0
        Py_RETURN_NONE;
2630
0
    }
2631
0
    PyObject *result = async_gen_athrow_throw((PyObject*)agt,
2632
0
                                              &PyExc_GeneratorExit, 1);
2633
0
    if (result == NULL) {
2634
0
        if (PyErr_ExceptionMatches(PyExc_StopIteration) ||
2635
0
            PyErr_ExceptionMatches(PyExc_StopAsyncIteration) ||
2636
0
            PyErr_ExceptionMatches(PyExc_GeneratorExit))
2637
0
        {
2638
0
            PyErr_Clear();
2639
0
            Py_RETURN_NONE;
2640
0
        }
2641
0
        return result;
2642
0
    } else {
2643
0
        Py_DECREF(result);
2644
0
        PyErr_SetString(PyExc_RuntimeError, "coroutine ignored GeneratorExit");
2645
0
        return NULL;
2646
0
    }
2647
0
}
2648
2649
2650
static void
2651
async_gen_athrow_finalize(PyObject *op)
2652
0
{
2653
0
    PyAsyncGenAThrow *o = (PyAsyncGenAThrow*)op;
2654
0
    if (o->agt_state == AWAITABLE_STATE_INIT) {
2655
0
        PyObject *method = o->agt_typ ? &_Py_ID(athrow) : &_Py_ID(aclose);
2656
0
        _PyErr_WarnUnawaitedAgenMethod(o->agt_gen, method);
2657
0
    }
2658
0
}
2659
2660
static PyMethodDef async_gen_athrow_methods[] = {
2661
    {"send", async_gen_athrow_send, METH_O, send_doc},
2662
    {"throw", _PyCFunction_CAST(async_gen_athrow_throw),
2663
    METH_FASTCALL, throw_doc},
2664
    {"close", async_gen_athrow_close, METH_NOARGS, close_doc},
2665
    {NULL, NULL}        /* Sentinel */
2666
};
2667
2668
2669
static PyAsyncMethods async_gen_athrow_as_async = {
2670
    PyObject_SelfIter,                          /* am_await */
2671
    0,                                          /* am_aiter */
2672
    0,                                          /* am_anext */
2673
    0,                                          /* am_send  */
2674
};
2675
2676
2677
PyTypeObject _PyAsyncGenAThrow_Type = {
2678
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
2679
    "async_generator_athrow",                   /* tp_name */
2680
    sizeof(PyAsyncGenAThrow),                   /* tp_basicsize */
2681
    0,                                          /* tp_itemsize */
2682
    /* methods */
2683
    async_gen_athrow_dealloc,                   /* tp_dealloc */
2684
    0,                                          /* tp_vectorcall_offset */
2685
    0,                                          /* tp_getattr */
2686
    0,                                          /* tp_setattr */
2687
    &async_gen_athrow_as_async,                 /* tp_as_async */
2688
    0,                                          /* tp_repr */
2689
    0,                                          /* tp_as_number */
2690
    0,                                          /* tp_as_sequence */
2691
    0,                                          /* tp_as_mapping */
2692
    0,                                          /* tp_hash */
2693
    0,                                          /* tp_call */
2694
    0,                                          /* tp_str */
2695
    PyObject_GenericGetAttr,                    /* tp_getattro */
2696
    0,                                          /* tp_setattro */
2697
    0,                                          /* tp_as_buffer */
2698
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,    /* tp_flags */
2699
    0,                                          /* tp_doc */
2700
    async_gen_athrow_traverse,                  /* tp_traverse */
2701
    0,                                          /* tp_clear */
2702
    0,                                          /* tp_richcompare */
2703
    0,                                          /* tp_weaklistoffset */
2704
    PyObject_SelfIter,                          /* tp_iter */
2705
    async_gen_athrow_iternext,                  /* tp_iternext */
2706
    async_gen_athrow_methods,                   /* tp_methods */
2707
    0,                                          /* tp_members */
2708
    0,                                          /* tp_getset */
2709
    0,                                          /* tp_base */
2710
    0,                                          /* tp_dict */
2711
    0,                                          /* tp_descr_get */
2712
    0,                                          /* tp_descr_set */
2713
    0,                                          /* tp_dictoffset */
2714
    0,                                          /* tp_init */
2715
    0,                                          /* tp_alloc */
2716
    0,                                          /* tp_new */
2717
    .tp_finalize = async_gen_athrow_finalize,
2718
};
2719
2720
2721
static PyObject *
2722
async_gen_athrow_new(PyAsyncGenObject *gen, PyObject *args)
2723
0
{
2724
0
    PyObject *typ = NULL;
2725
0
    PyObject *tb = NULL;
2726
0
    PyObject *val = NULL;
2727
0
    if (args && !PyArg_UnpackTuple(args, "athrow", 1, 3, &typ, &val, &tb)) {
2728
0
        return NULL;
2729
0
    }
2730
2731
0
    PyAsyncGenAThrow *o;
2732
0
    o = PyObject_GC_New(PyAsyncGenAThrow, &_PyAsyncGenAThrow_Type);
2733
0
    if (o == NULL) {
2734
0
        return NULL;
2735
0
    }
2736
0
    o->agt_gen = (PyAsyncGenObject*)Py_NewRef(gen);
2737
0
    o->agt_typ = Py_XNewRef(typ);
2738
0
    o->agt_tb = Py_XNewRef(tb);
2739
0
    o->agt_val = Py_XNewRef(val);
2740
2741
0
    o->agt_state = AWAITABLE_STATE_INIT;
2742
0
    _PyObject_GC_TRACK((PyObject*)o);
2743
0
    return (PyObject*)o;
2744
0
}