Coverage Report

Created: 2026-04-20 06:11

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