Coverage Report

Created: 2026-03-23 06:45

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
70.7M
    _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
47.6M
    ((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
157k
_PyGen_GetCode(PyGenObject *gen) {
70
157k
    return _PyFrame_GetCode(&gen->gi_iframe);
71
157k
}
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
784k
{
84
784k
    PyGenObject *gen = _PyGen_CAST(self);
85
784k
    Py_VISIT(gen->gi_name);
86
784k
    Py_VISIT(gen->gi_qualname);
87
784k
    if (gen->gi_frame_state != FRAME_CLEARED) {
88
783k
        _PyInterpreterFrame *frame = &gen->gi_iframe;
89
783k
        assert(frame->frame_obj == NULL ||
90
783k
               frame->frame_obj->f_frame->owner == FRAME_OWNED_BY_GENERATOR);
91
783k
        int err = _PyFrame_Traverse(frame, visit, arg);
92
783k
        if (err) {
93
0
            return err;
94
0
        }
95
783k
    }
96
266
    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
266
        _Py_VISIT_STACKREF(gen->gi_iframe.f_executable);
100
266
    }
101
    /* No need to visit cr_origin, because it's just tuples/str/int, so can't
102
       participate in a reference cycle. */
103
784k
    Py_VISIT(gen->gi_exc_state.exc_value);
104
784k
    return 0;
105
784k
}
106
107
static void
108
gen_finalize(PyObject *self)
109
22.4M
{
110
22.4M
    PyGenObject *gen = (PyGenObject *)self;
111
112
22.4M
    if (FRAME_STATE_FINISHED(gen->gi_frame_state)) {
113
        /* Generator isn't paused, so no need to close */
114
22.3M
        return;
115
22.3M
    }
116
117
157k
    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
157k
    PyObject *exc = PyErr_GetRaisedException();
140
141
    /* If `gen` is a coroutine, and if it was never awaited on,
142
       issue a RuntimeWarning. */
143
157k
    assert(_PyGen_GetCode(gen) != NULL);
144
157k
    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
157k
    else {
150
157k
        PyObject *res = gen_close((PyObject*)gen, NULL);
151
157k
        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
157k
        else {
158
157k
            Py_DECREF(res);
159
157k
        }
160
157k
    }
161
162
    /* Restore the saved exception. */
163
157k
    PyErr_SetRaisedException(exc);
164
157k
}
165
166
static void
167
gen_clear_frame(PyGenObject *gen)
168
157k
{
169
157k
    assert(FT_ATOMIC_LOAD_INT8_RELAXED(gen->gi_frame_state) == FRAME_CLEARED);
170
157k
    _PyInterpreterFrame *frame = &gen->gi_iframe;
171
157k
    frame->previous = NULL;
172
157k
    _PyFrame_ClearExceptCode(frame);
173
157k
    _PyErr_ClearExcState(&gen->gi_exc_state);
174
157k
}
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
22.4M
{
207
22.4M
    PyGenObject *gen = _PyGen_CAST(self);
208
209
22.4M
    _PyObject_GC_UNTRACK(gen);
210
211
22.4M
    FT_CLEAR_WEAKREFS(self, gen->gi_weakreflist);
212
213
22.4M
    _PyObject_GC_TRACK(self);
214
215
22.4M
    if (PyObject_CallFinalizerFromDealloc(self))
216
0
        return;                     /* resurrected.  :( */
217
218
22.4M
    _PyObject_GC_UNTRACK(self);
219
22.4M
    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
22.4M
    if (PyCoro_CheckExact(gen)) {
226
36
        Py_CLEAR(((PyCoroObject *)gen)->cr_origin_or_finalizer);
227
36
    }
228
22.4M
    if (gen->gi_frame_state != FRAME_CLEARED) {
229
0
        gen->gi_frame_state = FRAME_CLEARED;
230
0
        gen_clear_frame(gen);
231
0
    }
232
22.4M
    assert(gen->gi_exc_state.exc_value == NULL);
233
22.4M
    PyStackRef_CLEAR(gen->gi_iframe.f_executable);
234
22.4M
    Py_CLEAR(gen->gi_name);
235
22.4M
    Py_CLEAR(gen->gi_qualname);
236
237
22.4M
    PyObject_GC_Del(gen);
238
22.4M
}
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
47.3M
{
261
47.3M
    assert(FT_ATOMIC_LOAD_INT8_RELAXED(gen->gi_frame_state) == FRAME_EXECUTING);
262
263
47.3M
    PyThreadState *tstate = _PyThreadState_GET();
264
47.3M
    _PyInterpreterFrame *frame = &gen->gi_iframe;
265
266
    /* Push arg onto the frame's value stack */
267
47.3M
    PyObject *arg_obj = arg ? arg : Py_None;
268
47.3M
    _PyFrame_StackPush(frame, PyStackRef_FromPyObjectNew(arg_obj));
269
270
47.3M
    _PyErr_StackItem *prev_exc_info = tstate->exc_info;
271
47.3M
    gen->gi_exc_state.previous_item = prev_exc_info;
272
47.3M
    tstate->exc_info = &gen->gi_exc_state;
273
274
47.3M
    if (exc) {
275
42.2k
        assert(_PyErr_Occurred(tstate));
276
42.2k
        _PyErr_ChainStackItem();
277
42.2k
    }
278
279
47.3M
    EVAL_CALL_STAT_INC(EVAL_CALL_GENERATOR);
280
47.3M
    PyObject *result = _PyEval_EvalFrame(tstate, frame, exc);
281
47.3M
    assert(tstate->exc_info == prev_exc_info);
282
47.3M
#ifndef Py_GIL_DISABLED
283
47.3M
    assert(gen->gi_exc_state.previous_item == NULL);
284
47.3M
    assert(frame->previous == NULL);
285
47.3M
    assert(gen->gi_frame_state != FRAME_EXECUTING);
286
47.3M
#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
47.3M
    int return_kind = ((_PyThreadStateImpl *)tstate)->generator_return_kind;
293
294
47.3M
    if (return_kind == GENERATOR_YIELD) {
295
35.6M
        assert(result != NULL && !_PyErr_Occurred(tstate));
296
35.6M
#ifndef Py_GIL_DISABLED
297
35.6M
        assert(FRAME_STATE_SUSPENDED(gen->gi_frame_state));
298
35.6M
#endif
299
35.6M
        *presult = result;
300
35.6M
        return PYGEN_NEXT;
301
35.6M
    }
302
303
47.3M
    assert(return_kind == GENERATOR_RETURN);
304
11.7M
    assert(gen->gi_exc_state.exc_value == NULL);
305
11.7M
    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.7M
    if (result) {
310
11.6M
        assert(result == Py_None || !PyAsyncGen_CheckExact(gen));
311
11.6M
        if (result == Py_None && !PyAsyncGen_CheckExact(gen) && !arg) {
312
            /* Return NULL if called by gen_iternext() */
313
11.6M
            Py_CLEAR(result);
314
11.6M
        }
315
11.6M
    }
316
61.5k
    else {
317
61.5k
        assert(!PyErr_ExceptionMatches(PyExc_StopIteration));
318
61.5k
        assert(!PyAsyncGen_CheckExact(gen) ||
319
61.5k
            !PyErr_ExceptionMatches(PyExc_StopAsyncIteration));
320
61.5k
    }
321
322
11.7M
    *presult = result;
323
11.7M
    return result ? PYGEN_RETURN : PYGEN_ERROR;
324
47.3M
}
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
47.3M
{
331
47.3M
    *presult = NULL;
332
47.3M
    int8_t frame_state = FT_ATOMIC_LOAD_INT8_RELAXED(gen->gi_frame_state);
333
47.3M
    do {
334
47.3M
        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
47.3M
        if (frame_state == FRAME_EXECUTING) {
348
0
            gen_raise_already_executing_error(gen);
349
0
            return PYGEN_ERROR;
350
0
        }
351
47.3M
        if (FRAME_STATE_FINISHED(frame_state)) {
352
17.4k
            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
17.4k
            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
17.4k
            return PYGEN_ERROR;
367
17.4k
        }
368
369
47.3M
        assert((frame_state == FRAME_CREATED) ||
370
47.2M
               FRAME_STATE_SUSPENDED(frame_state));
371
47.2M
    } while (!_Py_GEN_TRY_SET_FRAME_STATE(gen, frame_state, FRAME_EXECUTING));
372
373
47.2M
    return gen_send_ex2(gen, arg, presult, 0);
374
47.3M
}
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
22.1k
{
453
22.1k
    uint8_t code = FT_ATOMIC_LOAD_UINT8_RELAXED(instr->op.code);
454
22.1k
    return (
455
22.1k
        code == RESUME ||
456
20.1k
        code == RESUME_CHECK ||
457
0
        code == RESUME_CHECK_JIT ||
458
0
        code == INSTRUMENTED_RESUME
459
22.1k
    );
460
22.1k
}
461
462
static PyObject *
463
gen_close(PyObject *self, PyObject *args)
464
157k
{
465
157k
    PyGenObject *gen = _PyGen_CAST(self);
466
467
157k
    int8_t frame_state = FT_ATOMIC_LOAD_INT8_RELAXED(gen->gi_frame_state);
468
157k
    do {
469
157k
        if (frame_state == FRAME_CREATED) {
470
            // && (1) to avoid -Wunreachable-code warning on Clang
471
135k
            if (!_Py_GEN_TRY_SET_FRAME_STATE(gen, frame_state, FRAME_CLEARED) && (1)) {
472
0
                continue;
473
0
            }
474
135k
            gen_clear_frame(gen);
475
135k
            Py_RETURN_NONE;
476
135k
        }
477
478
22.1k
        if (FRAME_STATE_FINISHED(frame_state)) {
479
0
            Py_RETURN_NONE;
480
0
        }
481
482
22.1k
        if (frame_state == FRAME_EXECUTING) {
483
0
            gen_raise_already_executing_error(gen);
484
0
            return NULL;
485
0
        }
486
487
22.1k
        assert(FRAME_STATE_SUSPENDED(frame_state));
488
22.1k
    } while (!_Py_GEN_TRY_SET_FRAME_STATE(gen, frame_state, FRAME_EXECUTING));
489
490
22.1k
    int err = 0;
491
22.1k
    _PyInterpreterFrame *frame = &gen->gi_iframe;
492
22.1k
    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
22.1k
    if (is_resume(frame->instr_ptr)) {
499
22.1k
        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
22.1k
        int oparg = frame->instr_ptr->op.arg;
504
22.1k
        if (oparg & RESUME_OPARG_DEPTH1_MASK && no_unwind_tools) {
505
            // RESUME after YIELD_VALUE and exception depth is 1
506
21.7k
            assert((oparg & RESUME_OPARG_LOCATION_MASK) != RESUME_AT_FUNC_START);
507
21.7k
            FT_ATOMIC_STORE_INT8_RELEASE(gen->gi_frame_state, FRAME_CLEARED);
508
21.7k
            gen_clear_frame(gen);
509
21.7k
            Py_RETURN_NONE;
510
21.7k
        }
511
22.1k
    }
512
443
    if (err == 0) {
513
443
        PyErr_SetNone(PyExc_GeneratorExit);
514
443
    }
515
516
443
    PyObject *retval;
517
443
    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
443
    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
443
    assert(PyErr_Occurred());
534
535
443
    if (PyErr_ExceptionMatches(PyExc_GeneratorExit)) {
536
443
        PyErr_Clear();          /* ignore this error */
537
443
        Py_RETURN_NONE;
538
443
    }
539
0
    return NULL;
540
443
}
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
41.7k
{
547
    /* First, check the traceback argument, replacing None with
548
       NULL. */
549
41.7k
    if (tb == Py_None) {
550
0
        tb = NULL;
551
0
    }
552
41.7k
    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
41.7k
    Py_INCREF(typ);
559
41.7k
    Py_XINCREF(val);
560
41.7k
    Py_XINCREF(tb);
561
562
41.7k
    if (PyExceptionClass_Check(typ)) {
563
0
        PyErr_NormalizeException(&typ, &val, &tb);
564
0
    }
565
41.7k
    else if (PyExceptionInstance_Check(typ)) {
566
        /* Raising an instance.  The value should be a dummy. */
567
41.7k
        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
41.7k
        else {
573
            /* Normalize to raise <class>, <instance> */
574
41.7k
            Py_XSETREF(val, typ);
575
41.7k
            typ = Py_NewRef(PyExceptionInstance_Class(typ));
576
577
41.7k
            if (tb == NULL)
578
                /* Returns NULL if there's no traceback */
579
41.7k
                tb = PyException_GetTraceback(val);
580
41.7k
        }
581
41.7k
    }
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
41.7k
    PyErr_Restore(typ, val, tb);
592
41.7k
    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
41.7k
}
601
602
static PyObject *
603
gen_throw_current_exception(PyGenObject *gen)
604
41.7k
{
605
41.7k
    assert(FT_ATOMIC_LOAD_INT8_RELAXED(gen->gi_frame_state) == FRAME_EXECUTING);
606
607
41.7k
    PyObject *result;
608
41.7k
    if (gen_send_ex2(gen, Py_None, &result, 1) == PYGEN_RETURN) {
609
0
        return gen_set_stop_iteration(gen, result);
610
0
    }
611
41.7k
    return result;
612
41.7k
}
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
41.7k
{
627
41.7k
    int8_t frame_state = FT_ATOMIC_LOAD_INT8_RELAXED(gen->gi_frame_state);
628
41.7k
    do {
629
41.7k
        if (frame_state == FRAME_EXECUTING) {
630
0
            gen_raise_already_executing_error(gen);
631
0
            return NULL;
632
0
        }
633
634
41.7k
        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
41.7k
        assert((frame_state == FRAME_CREATED) ||
647
41.7k
               FRAME_STATE_SUSPENDED(frame_state));
648
41.7k
    } while (!_Py_GEN_TRY_SET_FRAME_STATE(gen, frame_state, FRAME_EXECUTING));
649
650
41.7k
    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
41.7k
throw_here:
717
41.7k
    assert(FT_ATOMIC_LOAD_INT8_RELAXED(gen->gi_frame_state) == FRAME_EXECUTING);
718
41.7k
    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
41.7k
    return gen_throw_current_exception(gen);
723
41.7k
}
724
725
726
static PyObject *
727
gen_throw(PyObject *op, PyObject *const *args, Py_ssize_t nargs)
728
41.7k
{
729
41.7k
    PyGenObject *gen = _PyGen_CAST(op);
730
41.7k
    PyObject *typ;
731
41.7k
    PyObject *tb = NULL;
732
41.7k
    PyObject *val = NULL;
733
734
41.7k
    if (!_PyArg_CheckPositional("throw", nargs, 1, 3)) {
735
0
        return NULL;
736
0
    }
737
41.7k
    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
41.7k
    typ = args[0];
746
41.7k
    if (nargs == 3) {
747
0
        val = args[1];
748
0
        tb = args[2];
749
0
    }
750
41.7k
    else if (nargs == 2) {
751
0
        val = args[1];
752
0
    }
753
41.7k
    return _gen_throw(gen, 1, typ, val, tb);
754
41.7k
}
755
756
757
static PyObject *
758
gen_iternext(PyObject *self)
759
47.3M
{
760
47.3M
    assert(PyGen_CheckExact(self) || PyCoro_CheckExact(self));
761
47.3M
    PyGenObject *gen = _PyGen_CAST(self);
762
763
47.3M
    PyObject *result;
764
47.3M
    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
47.3M
    return result;
771
47.3M
}
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
22.4M
{
1094
22.4M
    PyCodeObject *code = (PyCodeObject *)func->func_code;
1095
22.4M
    int slots = _PyFrame_NumSlotsForCodeObject(code);
1096
22.4M
    PyGenObject *gen = PyObject_GC_NewVar(PyGenObject, type, slots);
1097
22.4M
    if (gen == NULL) {
1098
0
        return NULL;
1099
0
    }
1100
22.4M
    gen->gi_frame_state = FRAME_CLEARED;
1101
22.4M
    gen->gi_weakreflist = NULL;
1102
22.4M
    gen->gi_exc_state.exc_value = NULL;
1103
22.4M
    gen->gi_exc_state.previous_item = NULL;
1104
22.4M
    gen->gi_iframe.f_executable = PyStackRef_None;
1105
22.4M
    assert(func->func_name != NULL);
1106
22.4M
    gen->gi_name = Py_NewRef(func->func_name);
1107
22.4M
    assert(func->func_qualname != NULL);
1108
22.4M
    gen->gi_qualname = Py_NewRef(func->func_qualname);
1109
22.4M
    _PyObject_GC_TRACK(gen);
1110
22.4M
    return (PyObject *)gen;
1111
22.4M
}
1112
1113
static PyObject *
1114
compute_cr_origin(int origin_depth, _PyInterpreterFrame *current_frame);
1115
1116
PyObject *
1117
_Py_MakeCoro(PyFunctionObject *func)
1118
22.4M
{
1119
22.4M
    int coro_flags = ((PyCodeObject *)func->func_code)->co_flags &
1120
22.4M
        (CO_GENERATOR | CO_COROUTINE | CO_ASYNC_GENERATOR);
1121
22.4M
    assert(coro_flags);
1122
22.4M
    if (coro_flags == CO_GENERATOR) {
1123
22.4M
        return make_gen(&PyGen_Type, func);
1124
22.4M
    }
1125
72
    if (coro_flags == CO_ASYNC_GENERATOR) {
1126
36
        PyAsyncGenObject *ag;
1127
36
        ag = (PyAsyncGenObject *)make_gen(&PyAsyncGen_Type, func);
1128
36
        if (ag == NULL) {
1129
0
            return NULL;
1130
0
        }
1131
36
        ag->ag_origin_or_finalizer = NULL;
1132
36
        ag->ag_closed = 0;
1133
36
        ag->ag_hooks_inited = 0;
1134
36
        ag->ag_running_async = 0;
1135
36
        return (PyObject*)ag;
1136
36
    }
1137
1138
72
    assert (coro_flags == CO_COROUTINE);
1139
36
    PyObject *coro = make_gen(&PyCoro_Type, func);
1140
36
    if (!coro) {
1141
0
        return NULL;
1142
0
    }
1143
36
    PyThreadState *tstate = _PyThreadState_GET();
1144
36
    int origin_depth = tstate->coroutine_origin_tracking_depth;
1145
1146
36
    if (origin_depth == 0) {
1147
36
        ((PyCoroObject *)coro)->cr_origin_or_finalizer = NULL;
1148
36
    } else {
1149
0
        _PyInterpreterFrame *frame = tstate->current_frame;
1150
0
        assert(frame);
1151
0
        assert(_PyFrame_IsIncomplete(frame));
1152
0
        frame = _PyFrame_GetFirstComplete(frame->previous);
1153
0
        PyObject *cr_origin = compute_cr_origin(origin_depth, frame);
1154
0
        ((PyCoroObject *)coro)->cr_origin_or_finalizer = cr_origin;
1155
0
        if (!cr_origin) {
1156
0
            Py_DECREF(coro);
1157
0
            return NULL;
1158
0
        }
1159
0
    }
1160
36
    return coro;
1161
36
}
1162
1163
static PyObject *
1164
gen_new_with_qualname(PyTypeObject *type, PyFrameObject *f,
1165
                      PyObject *name, PyObject *qualname)
1166
0
{
1167
0
    PyCodeObject *code = _PyFrame_GetCode(f->f_frame);
1168
0
    int size = code->co_nlocalsplus + code->co_stacksize;
1169
0
    PyGenObject *gen = PyObject_GC_NewVar(PyGenObject, type, size);
1170
0
    if (gen == NULL) {
1171
0
        Py_DECREF(f);
1172
0
        return NULL;
1173
0
    }
1174
    /* Copy the frame */
1175
0
    assert(f->f_frame->frame_obj == NULL);
1176
0
    assert(f->f_frame->owner == FRAME_OWNED_BY_FRAME_OBJECT);
1177
0
    _PyInterpreterFrame *frame = &gen->gi_iframe;
1178
0
    _PyFrame_Copy((_PyInterpreterFrame *)f->_f_frame_data, frame);
1179
0
    gen->gi_frame_state = FRAME_CREATED;
1180
0
    assert(frame->frame_obj == f);
1181
0
    f->f_frame = frame;
1182
0
    frame->owner = FRAME_OWNED_BY_GENERATOR;
1183
0
    assert(PyObject_GC_IsTracked((PyObject *)f));
1184
0
    Py_DECREF(f);
1185
0
    gen->gi_weakreflist = NULL;
1186
0
    gen->gi_exc_state.exc_value = NULL;
1187
0
    gen->gi_exc_state.previous_item = NULL;
1188
0
    if (name != NULL)
1189
0
        gen->gi_name = Py_NewRef(name);
1190
0
    else
1191
0
        gen->gi_name = Py_NewRef(_PyGen_GetCode(gen)->co_name);
1192
0
    if (qualname != NULL)
1193
0
        gen->gi_qualname = Py_NewRef(qualname);
1194
0
    else
1195
0
        gen->gi_qualname = Py_NewRef(_PyGen_GetCode(gen)->co_qualname);
1196
0
    _PyObject_GC_TRACK(gen);
1197
0
    return (PyObject *)gen;
1198
0
}
1199
1200
PyObject *
1201
PyGen_NewWithQualName(PyFrameObject *f, PyObject *name, PyObject *qualname)
1202
0
{
1203
0
    return gen_new_with_qualname(&PyGen_Type, f, name, qualname);
1204
0
}
1205
1206
PyObject *
1207
PyGen_New(PyFrameObject *f)
1208
0
{
1209
0
    return gen_new_with_qualname(&PyGen_Type, f, NULL, NULL);
1210
0
}
1211
1212
/* Coroutine Object */
1213
1214
typedef struct {
1215
    PyObject_HEAD
1216
    PyCoroObject *cw_coroutine;
1217
} PyCoroWrapper;
1218
1219
#define _PyCoroWrapper_CAST(op) \
1220
0
    (assert(Py_IS_TYPE((op), &_PyCoroWrapper_Type)), \
1221
0
     _Py_CAST(PyCoroWrapper*, (op)))
1222
1223
1224
static int
1225
gen_is_coroutine(PyObject *o)
1226
0
{
1227
0
    if (PyGen_CheckExact(o)) {
1228
0
        PyCodeObject *code = _PyGen_GetCode((PyGenObject*)o);
1229
0
        if (code->co_flags & CO_ITERABLE_COROUTINE) {
1230
0
            return 1;
1231
0
        }
1232
0
    }
1233
0
    return 0;
1234
0
}
1235
1236
/*
1237
 *   This helper function returns an awaitable for `o`:
1238
 *     - `o` if `o` is a coroutine-object;
1239
 *     - `type(o)->tp_as_async->am_await(o)`
1240
 *
1241
 *   Raises a TypeError if it's not possible to return
1242
 *   an awaitable and returns NULL.
1243
 */
1244
PyObject *
1245
_PyCoro_GetAwaitableIter(PyObject *o)
1246
0
{
1247
0
    unaryfunc getter = NULL;
1248
0
    PyTypeObject *ot;
1249
1250
0
    if (PyCoro_CheckExact(o) || gen_is_coroutine(o)) {
1251
        /* 'o' is a coroutine. */
1252
0
        return Py_NewRef(o);
1253
0
    }
1254
1255
0
    ot = Py_TYPE(o);
1256
0
    if (ot->tp_as_async != NULL) {
1257
0
        getter = ot->tp_as_async->am_await;
1258
0
    }
1259
0
    if (getter != NULL) {
1260
0
        PyObject *res = (*getter)(o);
1261
0
        if (res != NULL) {
1262
0
            if (PyCoro_CheckExact(res) || gen_is_coroutine(res)) {
1263
                /* __await__ must return an *iterator*, not
1264
                   a coroutine or another awaitable (see PEP 492) */
1265
0
                PyErr_Format(PyExc_TypeError,
1266
0
                             "%T.__await__() must return an iterator, "
1267
0
                             "not coroutine", o);
1268
0
                Py_CLEAR(res);
1269
0
            } else if (!PyIter_Check(res)) {
1270
0
                PyErr_Format(PyExc_TypeError,
1271
0
                             "%T.__await__() must return an iterator, "
1272
0
                             "not %T", o, res);
1273
0
                Py_CLEAR(res);
1274
0
            }
1275
0
        }
1276
0
        return res;
1277
0
    }
1278
1279
0
    PyErr_Format(PyExc_TypeError,
1280
0
                 "'%.100s' object can't be awaited",
1281
0
                 ot->tp_name);
1282
0
    return NULL;
1283
0
}
1284
1285
static PyObject *
1286
coro_repr(PyObject *self)
1287
0
{
1288
0
    PyCoroObject *coro = _PyCoroObject_CAST(self);
1289
0
    return PyUnicode_FromFormat("<coroutine object %S at %p>",
1290
0
                                coro->cr_qualname, coro);
1291
0
}
1292
1293
static PyObject *
1294
coro_await(PyObject *coro)
1295
0
{
1296
0
    PyCoroWrapper *cw = PyObject_GC_New(PyCoroWrapper, &_PyCoroWrapper_Type);
1297
0
    if (cw == NULL) {
1298
0
        return NULL;
1299
0
    }
1300
0
    cw->cw_coroutine = (PyCoroObject*)Py_NewRef(coro);
1301
0
    _PyObject_GC_TRACK(cw);
1302
0
    return (PyObject *)cw;
1303
0
}
1304
1305
static PyObject *
1306
cr_getframe(PyObject *coro, void *Py_UNUSED(ignored))
1307
0
{
1308
0
    return _gen_getframe(_PyGen_CAST(coro), "cr_frame");
1309
0
}
1310
1311
static PyObject *
1312
cr_getcode(PyObject *coro, void *Py_UNUSED(ignored))
1313
0
{
1314
0
    return _gen_getcode(_PyGen_CAST(coro), "cr_code");
1315
0
}
1316
1317
static PyObject *
1318
cr_getstate(PyObject *self, void *Py_UNUSED(ignored))
1319
0
{
1320
0
    PyGenObject *gen = _PyGen_CAST(self);
1321
0
    int8_t frame_state = FT_ATOMIC_LOAD_INT8_RELAXED(gen->gi_frame_state);
1322
1323
0
    static PyObject *const state_strings[] = {
1324
0
        [FRAME_CREATED] = &_Py_ID(CORO_CREATED),
1325
0
        [FRAME_SUSPENDED] = &_Py_ID(CORO_SUSPENDED),
1326
0
        [FRAME_SUSPENDED_YIELD_FROM] = &_Py_ID(CORO_SUSPENDED),
1327
0
        [FRAME_SUSPENDED_YIELD_FROM_LOCKED] = &_Py_ID(CORO_SUSPENDED),
1328
0
        [FRAME_EXECUTING] = &_Py_ID(CORO_RUNNING),
1329
0
        [FRAME_CLEARED] = &_Py_ID(CORO_CLOSED),
1330
0
    };
1331
1332
0
    assert(frame_state >= 0 &&
1333
0
           (size_t)frame_state < Py_ARRAY_LENGTH(state_strings));
1334
0
    return state_strings[frame_state];
1335
0
}
1336
1337
static PyGetSetDef coro_getsetlist[] = {
1338
    {"__name__", gen_get_name, gen_set_name,
1339
     PyDoc_STR("name of the coroutine")},
1340
    {"__qualname__", gen_get_qualname, gen_set_qualname,
1341
     PyDoc_STR("qualified name of the coroutine")},
1342
    {"cr_await", gen_getyieldfrom, NULL,
1343
     PyDoc_STR("object being awaited on, or None")},
1344
    {"cr_running", gen_getrunning, NULL, NULL},
1345
    {"cr_frame", cr_getframe, NULL, NULL},
1346
    {"cr_code", cr_getcode, NULL, NULL},
1347
    {"cr_suspended", gen_getsuspended, NULL, NULL},
1348
    {"cr_state", cr_getstate, NULL,
1349
     PyDoc_STR("state of the coroutine")},
1350
    {NULL} /* Sentinel */
1351
};
1352
1353
static PyMemberDef coro_memberlist[] = {
1354
    {"cr_origin",    _Py_T_OBJECT, offsetof(PyCoroObject, cr_origin_or_finalizer),   Py_READONLY},
1355
    {NULL}      /* Sentinel */
1356
};
1357
1358
PyDoc_STRVAR(coro_send_doc,
1359
"send(arg) -> send 'arg' into coroutine,\n\
1360
return next iterated value or raise StopIteration.");
1361
1362
PyDoc_STRVAR(coro_throw_doc,
1363
"throw(value)\n\
1364
throw(type[,value[,traceback]])\n\
1365
\n\
1366
Raise exception in coroutine, return next iterated value or raise\n\
1367
StopIteration.\n\
1368
the (type, val, tb) signature is deprecated, \n\
1369
and may be removed in a future version of Python.");
1370
1371
1372
PyDoc_STRVAR(coro_close_doc,
1373
"close() -> raise GeneratorExit inside coroutine.");
1374
1375
static PyMethodDef coro_methods[] = {
1376
    {"send", gen_send, METH_O, coro_send_doc},
1377
    {"throw",_PyCFunction_CAST(gen_throw), METH_FASTCALL, coro_throw_doc},
1378
    {"close", gen_close, METH_NOARGS, coro_close_doc},
1379
    {"__sizeof__", gen_sizeof, METH_NOARGS, sizeof__doc__},
1380
    {"__class_getitem__", Py_GenericAlias, METH_O|METH_CLASS, PyDoc_STR("See PEP 585")},
1381
    {NULL, NULL}        /* Sentinel */
1382
};
1383
1384
static PyAsyncMethods coro_as_async = {
1385
    coro_await,                                 /* am_await */
1386
    0,                                          /* am_aiter */
1387
    0,                                          /* am_anext */
1388
    PyGen_am_send,                              /* am_send  */
1389
};
1390
1391
PyTypeObject PyCoro_Type = {
1392
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
1393
    "coroutine",                                /* tp_name */
1394
    offsetof(PyCoroObject, cr_iframe.localsplus),/* tp_basicsize */
1395
    sizeof(PyObject *),                         /* tp_itemsize */
1396
    /* methods */
1397
    gen_dealloc,                                /* tp_dealloc */
1398
    0,                                          /* tp_vectorcall_offset */
1399
    0,                                          /* tp_getattr */
1400
    0,                                          /* tp_setattr */
1401
    &coro_as_async,                             /* tp_as_async */
1402
    coro_repr,                                  /* tp_repr */
1403
    0,                                          /* tp_as_number */
1404
    0,                                          /* tp_as_sequence */
1405
    0,                                          /* tp_as_mapping */
1406
    0,                                          /* tp_hash */
1407
    0,                                          /* tp_call */
1408
    0,                                          /* tp_str */
1409
    PyObject_GenericGetAttr,                    /* tp_getattro */
1410
    0,                                          /* tp_setattro */
1411
    0,                                          /* tp_as_buffer */
1412
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,    /* tp_flags */
1413
    0,                                          /* tp_doc */
1414
    gen_traverse,                               /* tp_traverse */
1415
    0,                                          /* tp_clear */
1416
    0,                                          /* tp_richcompare */
1417
    offsetof(PyCoroObject, cr_weakreflist),     /* tp_weaklistoffset */
1418
    0,                                          /* tp_iter */
1419
    0,                                          /* tp_iternext */
1420
    coro_methods,                               /* tp_methods */
1421
    coro_memberlist,                            /* tp_members */
1422
    coro_getsetlist,                            /* tp_getset */
1423
    0,                                          /* tp_base */
1424
    0,                                          /* tp_dict */
1425
    0,                                          /* tp_descr_get */
1426
    0,                                          /* tp_descr_set */
1427
    0,                                          /* tp_dictoffset */
1428
    0,                                          /* tp_init */
1429
    0,                                          /* tp_alloc */
1430
    0,                                          /* tp_new */
1431
    0,                                          /* tp_free */
1432
    0,                                          /* tp_is_gc */
1433
    0,                                          /* tp_bases */
1434
    0,                                          /* tp_mro */
1435
    0,                                          /* tp_cache */
1436
    0,                                          /* tp_subclasses */
1437
    0,                                          /* tp_weaklist */
1438
    0,                                          /* tp_del */
1439
    0,                                          /* tp_version_tag */
1440
    gen_finalize,                               /* tp_finalize */
1441
};
1442
1443
static void
1444
coro_wrapper_dealloc(PyObject *self)
1445
0
{
1446
0
    PyCoroWrapper *cw = _PyCoroWrapper_CAST(self);
1447
0
    _PyObject_GC_UNTRACK((PyObject *)cw);
1448
0
    Py_CLEAR(cw->cw_coroutine);
1449
0
    PyObject_GC_Del(cw);
1450
0
}
1451
1452
static PyObject *
1453
coro_wrapper_iternext(PyObject *self)
1454
0
{
1455
0
    PyCoroWrapper *cw = _PyCoroWrapper_CAST(self);
1456
0
    return gen_iternext((PyObject *)cw->cw_coroutine);
1457
0
}
1458
1459
static PyObject *
1460
coro_wrapper_send(PyObject *self, PyObject *arg)
1461
0
{
1462
0
    PyCoroWrapper *cw = _PyCoroWrapper_CAST(self);
1463
0
    return gen_send((PyObject *)cw->cw_coroutine, arg);
1464
0
}
1465
1466
static PyObject *
1467
coro_wrapper_throw(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
1468
0
{
1469
0
    PyCoroWrapper *cw = _PyCoroWrapper_CAST(self);
1470
0
    return gen_throw((PyObject*)cw->cw_coroutine, args, nargs);
1471
0
}
1472
1473
static PyObject *
1474
coro_wrapper_close(PyObject *self, PyObject *args)
1475
0
{
1476
0
    PyCoroWrapper *cw = _PyCoroWrapper_CAST(self);
1477
0
    return gen_close((PyObject *)cw->cw_coroutine, args);
1478
0
}
1479
1480
static int
1481
coro_wrapper_traverse(PyObject *self, visitproc visit, void *arg)
1482
0
{
1483
0
    PyCoroWrapper *cw = _PyCoroWrapper_CAST(self);
1484
0
    Py_VISIT((PyObject *)cw->cw_coroutine);
1485
0
    return 0;
1486
0
}
1487
1488
static PyMethodDef coro_wrapper_methods[] = {
1489
    {"send", coro_wrapper_send, METH_O, coro_send_doc},
1490
    {"throw", _PyCFunction_CAST(coro_wrapper_throw), METH_FASTCALL,
1491
     coro_throw_doc},
1492
    {"close", coro_wrapper_close, METH_NOARGS, coro_close_doc},
1493
    {NULL, NULL}        /* Sentinel */
1494
};
1495
1496
PyTypeObject _PyCoroWrapper_Type = {
1497
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
1498
    "coroutine_wrapper",
1499
    sizeof(PyCoroWrapper),                      /* tp_basicsize */
1500
    0,                                          /* tp_itemsize */
1501
    coro_wrapper_dealloc,                       /* destructor tp_dealloc */
1502
    0,                                          /* tp_vectorcall_offset */
1503
    0,                                          /* tp_getattr */
1504
    0,                                          /* tp_setattr */
1505
    0,                                          /* tp_as_async */
1506
    0,                                          /* tp_repr */
1507
    0,                                          /* tp_as_number */
1508
    0,                                          /* tp_as_sequence */
1509
    0,                                          /* tp_as_mapping */
1510
    0,                                          /* tp_hash */
1511
    0,                                          /* tp_call */
1512
    0,                                          /* tp_str */
1513
    PyObject_GenericGetAttr,                    /* tp_getattro */
1514
    0,                                          /* tp_setattro */
1515
    0,                                          /* tp_as_buffer */
1516
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,    /* tp_flags */
1517
    "A wrapper object implementing __await__ for coroutines.",
1518
    coro_wrapper_traverse,                      /* tp_traverse */
1519
    0,                                          /* tp_clear */
1520
    0,                                          /* tp_richcompare */
1521
    0,                                          /* tp_weaklistoffset */
1522
    PyObject_SelfIter,                          /* tp_iter */
1523
    coro_wrapper_iternext,                      /* tp_iternext */
1524
    coro_wrapper_methods,                       /* tp_methods */
1525
    0,                                          /* tp_members */
1526
    0,                                          /* tp_getset */
1527
    0,                                          /* tp_base */
1528
    0,                                          /* tp_dict */
1529
    0,                                          /* tp_descr_get */
1530
    0,                                          /* tp_descr_set */
1531
    0,                                          /* tp_dictoffset */
1532
    0,                                          /* tp_init */
1533
    0,                                          /* tp_alloc */
1534
    0,                                          /* tp_new */
1535
    0,                                          /* tp_free */
1536
};
1537
1538
static PyObject *
1539
compute_cr_origin(int origin_depth, _PyInterpreterFrame *current_frame)
1540
0
{
1541
0
    _PyInterpreterFrame *frame = current_frame;
1542
    /* First count how many frames we have */
1543
0
    int frame_count = 0;
1544
0
    for (; frame && frame_count < origin_depth; ++frame_count) {
1545
0
        frame = _PyFrame_GetFirstComplete(frame->previous);
1546
0
    }
1547
1548
    /* Now collect them */
1549
0
    PyObject *cr_origin = PyTuple_New(frame_count);
1550
0
    if (cr_origin == NULL) {
1551
0
        return NULL;
1552
0
    }
1553
0
    frame = current_frame;
1554
0
    for (int i = 0; i < frame_count; ++i) {
1555
0
        PyCodeObject *code = _PyFrame_GetCode(frame);
1556
0
        int line = PyUnstable_InterpreterFrame_GetLine(frame);
1557
0
        PyObject *frameinfo = Py_BuildValue("OiO", code->co_filename, line,
1558
0
                                            code->co_name);
1559
0
        if (!frameinfo) {
1560
0
            Py_DECREF(cr_origin);
1561
0
            return NULL;
1562
0
        }
1563
0
        PyTuple_SET_ITEM(cr_origin, i, frameinfo);
1564
0
        frame = _PyFrame_GetFirstComplete(frame->previous);
1565
0
    }
1566
1567
0
    return cr_origin;
1568
0
}
1569
1570
PyObject *
1571
PyCoro_New(PyFrameObject *f, PyObject *name, PyObject *qualname)
1572
0
{
1573
0
    PyObject *coro = gen_new_with_qualname(&PyCoro_Type, f, name, qualname);
1574
0
    if (!coro) {
1575
0
        return NULL;
1576
0
    }
1577
1578
0
    PyThreadState *tstate = _PyThreadState_GET();
1579
0
    int origin_depth = tstate->coroutine_origin_tracking_depth;
1580
1581
0
    if (origin_depth == 0) {
1582
0
        ((PyCoroObject *)coro)->cr_origin_or_finalizer = NULL;
1583
0
    } else {
1584
0
        PyObject *cr_origin = compute_cr_origin(origin_depth, _PyEval_GetFrame());
1585
0
        ((PyCoroObject *)coro)->cr_origin_or_finalizer = cr_origin;
1586
0
        if (!cr_origin) {
1587
0
            Py_DECREF(coro);
1588
0
            return NULL;
1589
0
        }
1590
0
    }
1591
1592
0
    return coro;
1593
0
}
1594
1595
1596
/* ========= Asynchronous Generators ========= */
1597
1598
1599
typedef enum {
1600
    AWAITABLE_STATE_INIT,   /* new awaitable, has not yet been iterated */
1601
    AWAITABLE_STATE_ITER,   /* being iterated */
1602
    AWAITABLE_STATE_CLOSED, /* closed */
1603
} AwaitableState;
1604
1605
1606
typedef struct PyAsyncGenASend {
1607
    PyObject_HEAD
1608
    PyAsyncGenObject *ags_gen;
1609
1610
    /* Can be NULL, when in the __anext__() mode
1611
       (equivalent of "asend(None)") */
1612
    PyObject *ags_sendval;
1613
1614
    AwaitableState ags_state;
1615
} PyAsyncGenASend;
1616
1617
#define _PyAsyncGenASend_CAST(op) \
1618
0
    _Py_CAST(PyAsyncGenASend*, (op))
1619
1620
1621
typedef struct PyAsyncGenAThrow {
1622
    PyObject_HEAD
1623
    PyAsyncGenObject *agt_gen;
1624
1625
    /* Can be NULL, when in the "aclose()" mode
1626
       (equivalent of "athrow(GeneratorExit)") */
1627
    PyObject *agt_typ;
1628
    PyObject *agt_tb;
1629
    PyObject *agt_val;
1630
1631
    AwaitableState agt_state;
1632
} PyAsyncGenAThrow;
1633
1634
1635
typedef struct _PyAsyncGenWrappedValue {
1636
    PyObject_HEAD
1637
    PyObject *agw_val;
1638
} _PyAsyncGenWrappedValue;
1639
1640
1641
#define _PyAsyncGenWrappedValue_CheckExact(o) \
1642
0
                    Py_IS_TYPE(o, &_PyAsyncGenWrappedValue_Type)
1643
#define _PyAsyncGenWrappedValue_CAST(op) \
1644
0
    (assert(_PyAsyncGenWrappedValue_CheckExact(op)), \
1645
0
     _Py_CAST(_PyAsyncGenWrappedValue*, (op)))
1646
1647
1648
static int
1649
async_gen_traverse(PyObject *self, visitproc visit, void *arg)
1650
0
{
1651
0
    PyAsyncGenObject *ag = _PyAsyncGenObject_CAST(self);
1652
0
    Py_VISIT(ag->ag_origin_or_finalizer);
1653
0
    return gen_traverse((PyObject*)ag, visit, arg);
1654
0
}
1655
1656
1657
static PyObject *
1658
async_gen_repr(PyObject *self)
1659
0
{
1660
0
    PyAsyncGenObject *o = _PyAsyncGenObject_CAST(self);
1661
0
    return PyUnicode_FromFormat("<async_generator object %S at %p>",
1662
0
                                o->ag_qualname, o);
1663
0
}
1664
1665
1666
static int
1667
async_gen_init_hooks(PyAsyncGenObject *o)
1668
0
{
1669
0
    PyThreadState *tstate;
1670
0
    PyObject *finalizer;
1671
0
    PyObject *firstiter;
1672
1673
0
    if (o->ag_hooks_inited) {
1674
0
        return 0;
1675
0
    }
1676
1677
0
    o->ag_hooks_inited = 1;
1678
1679
0
    tstate = _PyThreadState_GET();
1680
1681
0
    finalizer = tstate->async_gen_finalizer;
1682
0
    if (finalizer) {
1683
0
        o->ag_origin_or_finalizer = Py_NewRef(finalizer);
1684
0
    }
1685
1686
0
    firstiter = tstate->async_gen_firstiter;
1687
0
    if (firstiter) {
1688
0
        PyObject *res;
1689
1690
0
        Py_INCREF(firstiter);
1691
0
        res = PyObject_CallOneArg(firstiter, (PyObject *)o);
1692
0
        Py_DECREF(firstiter);
1693
0
        if (res == NULL) {
1694
0
            return 1;
1695
0
        }
1696
0
        Py_DECREF(res);
1697
0
    }
1698
1699
0
    return 0;
1700
0
}
1701
1702
1703
static PyObject *
1704
async_gen_anext(PyObject *self)
1705
0
{
1706
0
    PyAsyncGenObject *ag = _PyAsyncGenObject_CAST(self);
1707
0
    if (async_gen_init_hooks(ag)) {
1708
0
        return NULL;
1709
0
    }
1710
0
    return async_gen_asend_new(ag, NULL);
1711
0
}
1712
1713
1714
static PyObject *
1715
async_gen_asend(PyObject *op, PyObject *arg)
1716
0
{
1717
0
    PyAsyncGenObject *o = (PyAsyncGenObject*)op;
1718
0
    if (async_gen_init_hooks(o)) {
1719
0
        return NULL;
1720
0
    }
1721
0
    return async_gen_asend_new(o, arg);
1722
0
}
1723
1724
1725
static PyObject *
1726
async_gen_aclose(PyObject *op, PyObject *arg)
1727
0
{
1728
0
    PyAsyncGenObject *o = (PyAsyncGenObject*)op;
1729
0
    if (async_gen_init_hooks(o)) {
1730
0
        return NULL;
1731
0
    }
1732
0
    return async_gen_athrow_new(o, NULL);
1733
0
}
1734
1735
static PyObject *
1736
async_gen_athrow(PyObject *op, PyObject *args)
1737
0
{
1738
0
    PyAsyncGenObject *o = (PyAsyncGenObject*)op;
1739
0
    if (PyTuple_GET_SIZE(args) > 1) {
1740
0
        if (PyErr_WarnEx(PyExc_DeprecationWarning,
1741
0
                            "the (type, exc, tb) signature of athrow() is deprecated, "
1742
0
                            "use the single-arg signature instead.",
1743
0
                            1) < 0) {
1744
0
            return NULL;
1745
0
        }
1746
0
    }
1747
0
    if (async_gen_init_hooks(o)) {
1748
0
        return NULL;
1749
0
    }
1750
0
    return async_gen_athrow_new(o, args);
1751
0
}
1752
1753
static PyObject *
1754
ag_getframe(PyObject *ag, void *Py_UNUSED(ignored))
1755
0
{
1756
0
    return _gen_getframe((PyGenObject *)ag, "ag_frame");
1757
0
}
1758
1759
static PyObject *
1760
ag_getcode(PyObject *gen, void *Py_UNUSED(ignored))
1761
0
{
1762
0
    return _gen_getcode((PyGenObject*)gen, "ag_code");
1763
0
}
1764
1765
static PyObject *
1766
ag_getstate(PyObject *self, void *Py_UNUSED(ignored))
1767
0
{
1768
0
    PyGenObject *gen = _PyGen_CAST(self);
1769
0
    int8_t frame_state = FT_ATOMIC_LOAD_INT8_RELAXED(gen->gi_frame_state);
1770
1771
0
    static PyObject *const state_strings[] = {
1772
0
        [FRAME_CREATED] = &_Py_ID(AGEN_CREATED),
1773
0
        [FRAME_SUSPENDED] = &_Py_ID(AGEN_SUSPENDED),
1774
0
        [FRAME_SUSPENDED_YIELD_FROM] = &_Py_ID(AGEN_SUSPENDED),
1775
0
        [FRAME_SUSPENDED_YIELD_FROM_LOCKED] = &_Py_ID(AGEN_SUSPENDED),
1776
0
        [FRAME_EXECUTING] = &_Py_ID(AGEN_RUNNING),
1777
0
        [FRAME_CLEARED] = &_Py_ID(AGEN_CLOSED),
1778
0
    };
1779
1780
0
    assert(frame_state >= 0 &&
1781
0
           (size_t)frame_state < Py_ARRAY_LENGTH(state_strings));
1782
0
    return state_strings[frame_state];
1783
0
}
1784
1785
static PyGetSetDef async_gen_getsetlist[] = {
1786
    {"__name__", gen_get_name, gen_set_name,
1787
     PyDoc_STR("name of the async generator")},
1788
    {"__qualname__", gen_get_qualname, gen_set_qualname,
1789
     PyDoc_STR("qualified name of the async generator")},
1790
    {"ag_await", gen_getyieldfrom, NULL,
1791
     PyDoc_STR("object being awaited on, or None")},
1792
     {"ag_frame", ag_getframe, NULL, NULL},
1793
     {"ag_code", ag_getcode, NULL, NULL},
1794
     {"ag_suspended", gen_getsuspended, NULL, NULL},
1795
     {"ag_state", ag_getstate, NULL,
1796
      PyDoc_STR("state of the async generator")},
1797
    {NULL} /* Sentinel */
1798
};
1799
1800
static PyMemberDef async_gen_memberlist[] = {
1801
    {"ag_running", Py_T_BOOL,   offsetof(PyAsyncGenObject, ag_running_async),
1802
        Py_READONLY},
1803
    {NULL}      /* Sentinel */
1804
};
1805
1806
PyDoc_STRVAR(async_aclose_doc,
1807
"aclose() -> raise GeneratorExit inside generator.");
1808
1809
PyDoc_STRVAR(async_asend_doc,
1810
"asend(v) -> send 'v' in generator.");
1811
1812
PyDoc_STRVAR(async_athrow_doc,
1813
"athrow(value)\n\
1814
athrow(type[,value[,tb]])\n\
1815
\n\
1816
raise exception in generator.\n\
1817
the (type, val, tb) signature is deprecated, \n\
1818
and may be removed in a future version of Python.");
1819
1820
static PyMethodDef async_gen_methods[] = {
1821
    {"asend", async_gen_asend, METH_O, async_asend_doc},
1822
    {"athrow", async_gen_athrow, METH_VARARGS, async_athrow_doc},
1823
    {"aclose", async_gen_aclose, METH_NOARGS, async_aclose_doc},
1824
    {"__sizeof__", gen_sizeof, METH_NOARGS, sizeof__doc__},
1825
    {"__class_getitem__",    Py_GenericAlias,
1826
    METH_O|METH_CLASS,       PyDoc_STR("See PEP 585")},
1827
    {NULL, NULL}        /* Sentinel */
1828
};
1829
1830
1831
static PyAsyncMethods async_gen_as_async = {
1832
    0,                                          /* am_await */
1833
    PyObject_SelfIter,                          /* am_aiter */
1834
    async_gen_anext,                            /* am_anext */
1835
    PyGen_am_send,                              /* am_send  */
1836
};
1837
1838
1839
PyTypeObject PyAsyncGen_Type = {
1840
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
1841
    "async_generator",                          /* tp_name */
1842
    offsetof(PyAsyncGenObject, ag_iframe.localsplus), /* tp_basicsize */
1843
    sizeof(PyObject *),                         /* tp_itemsize */
1844
    /* methods */
1845
    gen_dealloc,                                /* tp_dealloc */
1846
    0,                                          /* tp_vectorcall_offset */
1847
    0,                                          /* tp_getattr */
1848
    0,                                          /* tp_setattr */
1849
    &async_gen_as_async,                        /* tp_as_async */
1850
    async_gen_repr,                             /* tp_repr */
1851
    0,                                          /* tp_as_number */
1852
    0,                                          /* tp_as_sequence */
1853
    0,                                          /* tp_as_mapping */
1854
    0,                                          /* tp_hash */
1855
    0,                                          /* tp_call */
1856
    0,                                          /* tp_str */
1857
    PyObject_GenericGetAttr,                    /* tp_getattro */
1858
    0,                                          /* tp_setattro */
1859
    0,                                          /* tp_as_buffer */
1860
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,    /* tp_flags */
1861
    0,                                          /* tp_doc */
1862
    async_gen_traverse,                         /* tp_traverse */
1863
    0,                                          /* tp_clear */
1864
    0,                                          /* tp_richcompare */
1865
    offsetof(PyAsyncGenObject, ag_weakreflist), /* tp_weaklistoffset */
1866
    0,                                          /* tp_iter */
1867
    0,                                          /* tp_iternext */
1868
    async_gen_methods,                          /* tp_methods */
1869
    async_gen_memberlist,                       /* tp_members */
1870
    async_gen_getsetlist,                       /* tp_getset */
1871
    0,                                          /* tp_base */
1872
    0,                                          /* tp_dict */
1873
    0,                                          /* tp_descr_get */
1874
    0,                                          /* tp_descr_set */
1875
    0,                                          /* tp_dictoffset */
1876
    0,                                          /* tp_init */
1877
    0,                                          /* tp_alloc */
1878
    0,                                          /* tp_new */
1879
    0,                                          /* tp_free */
1880
    0,                                          /* tp_is_gc */
1881
    0,                                          /* tp_bases */
1882
    0,                                          /* tp_mro */
1883
    0,                                          /* tp_cache */
1884
    0,                                          /* tp_subclasses */
1885
    0,                                          /* tp_weaklist */
1886
    0,                                          /* tp_del */
1887
    0,                                          /* tp_version_tag */
1888
    gen_finalize,                               /* tp_finalize */
1889
};
1890
1891
1892
PyObject *
1893
PyAsyncGen_New(PyFrameObject *f, PyObject *name, PyObject *qualname)
1894
0
{
1895
0
    PyAsyncGenObject *ag;
1896
0
    ag = (PyAsyncGenObject *)gen_new_with_qualname(&PyAsyncGen_Type, f,
1897
0
                                                   name, qualname);
1898
0
    if (ag == NULL) {
1899
0
        return NULL;
1900
0
    }
1901
1902
0
    ag->ag_origin_or_finalizer = NULL;
1903
0
    ag->ag_closed = 0;
1904
0
    ag->ag_hooks_inited = 0;
1905
0
    ag->ag_running_async = 0;
1906
0
    return (PyObject*)ag;
1907
0
}
1908
1909
static PyObject *
1910
async_gen_unwrap_value(PyAsyncGenObject *gen, PyObject *result)
1911
0
{
1912
0
    if (result == NULL) {
1913
0
        if (!PyErr_Occurred()) {
1914
0
            PyErr_SetNone(PyExc_StopAsyncIteration);
1915
0
        }
1916
1917
0
        if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration)
1918
0
            || PyErr_ExceptionMatches(PyExc_GeneratorExit)
1919
0
        ) {
1920
0
            gen->ag_closed = 1;
1921
0
        }
1922
1923
0
        gen->ag_running_async = 0;
1924
0
        return NULL;
1925
0
    }
1926
1927
0
    if (_PyAsyncGenWrappedValue_CheckExact(result)) {
1928
        /* async yield */
1929
0
        _PyGen_SetStopIterationValue(((_PyAsyncGenWrappedValue*)result)->agw_val);
1930
0
        Py_DECREF(result);
1931
0
        gen->ag_running_async = 0;
1932
0
        return NULL;
1933
0
    }
1934
1935
0
    return result;
1936
0
}
1937
1938
1939
/* ---------- Async Generator ASend Awaitable ------------ */
1940
1941
1942
static void
1943
async_gen_asend_dealloc(PyObject *self)
1944
0
{
1945
0
    assert(PyAsyncGenASend_CheckExact(self));
1946
0
    PyAsyncGenASend *ags = _PyAsyncGenASend_CAST(self);
1947
1948
0
    if (PyObject_CallFinalizerFromDealloc(self)) {
1949
0
        return;
1950
0
    }
1951
1952
0
    _PyObject_GC_UNTRACK(self);
1953
0
    Py_CLEAR(ags->ags_gen);
1954
0
    Py_CLEAR(ags->ags_sendval);
1955
1956
0
    _PyGC_CLEAR_FINALIZED(self);
1957
1958
0
    _Py_FREELIST_FREE(async_gen_asends, self, PyObject_GC_Del);
1959
0
}
1960
1961
static int
1962
async_gen_asend_traverse(PyObject *self, visitproc visit, void *arg)
1963
0
{
1964
0
    PyAsyncGenASend *ags = _PyAsyncGenASend_CAST(self);
1965
0
    Py_VISIT(ags->ags_gen);
1966
0
    Py_VISIT(ags->ags_sendval);
1967
0
    return 0;
1968
0
}
1969
1970
1971
static PyObject *
1972
async_gen_asend_send(PyObject *self, PyObject *arg)
1973
0
{
1974
0
    PyAsyncGenASend *o = _PyAsyncGenASend_CAST(self);
1975
0
    if (o->ags_state == AWAITABLE_STATE_CLOSED) {
1976
0
        PyErr_SetString(
1977
0
            PyExc_RuntimeError,
1978
0
            "cannot reuse already awaited __anext__()/asend()");
1979
0
        return NULL;
1980
0
    }
1981
1982
0
    if (o->ags_state == AWAITABLE_STATE_INIT) {
1983
0
        if (o->ags_gen->ag_running_async) {
1984
0
            o->ags_state = AWAITABLE_STATE_CLOSED;
1985
0
            PyErr_SetString(
1986
0
                PyExc_RuntimeError,
1987
0
                "anext(): asynchronous generator is already running");
1988
0
            return NULL;
1989
0
        }
1990
1991
0
        if (arg == NULL || arg == Py_None) {
1992
0
            arg = o->ags_sendval;
1993
0
        }
1994
0
        o->ags_state = AWAITABLE_STATE_ITER;
1995
0
    }
1996
1997
0
    o->ags_gen->ag_running_async = 1;
1998
0
    PyObject *result = gen_send((PyObject*)o->ags_gen, arg);
1999
0
    result = async_gen_unwrap_value(o->ags_gen, result);
2000
2001
0
    if (result == NULL) {
2002
0
        o->ags_state = AWAITABLE_STATE_CLOSED;
2003
0
    }
2004
2005
0
    return result;
2006
0
}
2007
2008
2009
static PyObject *
2010
async_gen_asend_iternext(PyObject *ags)
2011
0
{
2012
0
    return async_gen_asend_send(ags, NULL);
2013
0
}
2014
2015
2016
static PyObject *
2017
async_gen_asend_throw(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
2018
0
{
2019
0
    PyAsyncGenASend *o = _PyAsyncGenASend_CAST(self);
2020
2021
0
    if (o->ags_state == AWAITABLE_STATE_CLOSED) {
2022
0
        PyErr_SetString(
2023
0
            PyExc_RuntimeError,
2024
0
            "cannot reuse already awaited __anext__()/asend()");
2025
0
        return NULL;
2026
0
    }
2027
2028
0
    if (o->ags_state == AWAITABLE_STATE_INIT) {
2029
0
        if (o->ags_gen->ag_running_async) {
2030
0
            o->ags_state = AWAITABLE_STATE_CLOSED;
2031
0
            PyErr_SetString(
2032
0
                PyExc_RuntimeError,
2033
0
                "anext(): asynchronous generator is already running");
2034
0
            return NULL;
2035
0
        }
2036
2037
0
        o->ags_state = AWAITABLE_STATE_ITER;
2038
0
        o->ags_gen->ag_running_async = 1;
2039
0
    }
2040
2041
0
    PyObject *result = gen_throw((PyObject*)o->ags_gen, args, nargs);
2042
0
    result = async_gen_unwrap_value(o->ags_gen, result);
2043
2044
0
    if (result == NULL) {
2045
0
        o->ags_gen->ag_running_async = 0;
2046
0
        o->ags_state = AWAITABLE_STATE_CLOSED;
2047
0
    }
2048
2049
0
    return result;
2050
0
}
2051
2052
2053
static PyObject *
2054
async_gen_asend_close(PyObject *self, PyObject *args)
2055
0
{
2056
0
    PyAsyncGenASend *o = _PyAsyncGenASend_CAST(self);
2057
0
    if (o->ags_state == AWAITABLE_STATE_CLOSED) {
2058
0
        Py_RETURN_NONE;
2059
0
    }
2060
2061
0
    PyObject *result = async_gen_asend_throw(self, &PyExc_GeneratorExit, 1);
2062
0
    if (result == NULL) {
2063
0
        if (PyErr_ExceptionMatches(PyExc_StopIteration) ||
2064
0
            PyErr_ExceptionMatches(PyExc_StopAsyncIteration) ||
2065
0
            PyErr_ExceptionMatches(PyExc_GeneratorExit))
2066
0
        {
2067
0
            PyErr_Clear();
2068
0
            Py_RETURN_NONE;
2069
0
        }
2070
0
        return result;
2071
0
    }
2072
2073
0
    Py_DECREF(result);
2074
0
    PyErr_SetString(PyExc_RuntimeError, "coroutine ignored GeneratorExit");
2075
0
    return NULL;
2076
0
}
2077
2078
static void
2079
async_gen_asend_finalize(PyObject *self)
2080
0
{
2081
0
    PyAsyncGenASend *ags = _PyAsyncGenASend_CAST(self);
2082
0
    if (ags->ags_state == AWAITABLE_STATE_INIT) {
2083
0
        _PyErr_WarnUnawaitedAgenMethod(ags->ags_gen, &_Py_ID(asend));
2084
0
    }
2085
0
}
2086
2087
static PyMethodDef async_gen_asend_methods[] = {
2088
    {"send", async_gen_asend_send, METH_O, send_doc},
2089
    {"throw", _PyCFunction_CAST(async_gen_asend_throw), METH_FASTCALL, throw_doc},
2090
    {"close", async_gen_asend_close, METH_NOARGS, close_doc},
2091
    {NULL, NULL}        /* Sentinel */
2092
};
2093
2094
2095
static PyAsyncMethods async_gen_asend_as_async = {
2096
    PyObject_SelfIter,                          /* am_await */
2097
    0,                                          /* am_aiter */
2098
    0,                                          /* am_anext */
2099
    0,                                          /* am_send  */
2100
};
2101
2102
2103
PyTypeObject _PyAsyncGenASend_Type = {
2104
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
2105
    "async_generator_asend",                    /* tp_name */
2106
    sizeof(PyAsyncGenASend),                    /* tp_basicsize */
2107
    0,                                          /* tp_itemsize */
2108
    /* methods */
2109
    async_gen_asend_dealloc,                    /* tp_dealloc */
2110
    0,                                          /* tp_vectorcall_offset */
2111
    0,                                          /* tp_getattr */
2112
    0,                                          /* tp_setattr */
2113
    &async_gen_asend_as_async,                  /* tp_as_async */
2114
    0,                                          /* tp_repr */
2115
    0,                                          /* tp_as_number */
2116
    0,                                          /* tp_as_sequence */
2117
    0,                                          /* tp_as_mapping */
2118
    0,                                          /* tp_hash */
2119
    0,                                          /* tp_call */
2120
    0,                                          /* tp_str */
2121
    PyObject_GenericGetAttr,                    /* tp_getattro */
2122
    0,                                          /* tp_setattro */
2123
    0,                                          /* tp_as_buffer */
2124
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,    /* tp_flags */
2125
    0,                                          /* tp_doc */
2126
    async_gen_asend_traverse,                   /* tp_traverse */
2127
    0,                                          /* tp_clear */
2128
    0,                                          /* tp_richcompare */
2129
    0,                                          /* tp_weaklistoffset */
2130
    PyObject_SelfIter,                          /* tp_iter */
2131
    async_gen_asend_iternext,                   /* tp_iternext */
2132
    async_gen_asend_methods,                    /* tp_methods */
2133
    0,                                          /* tp_members */
2134
    0,                                          /* tp_getset */
2135
    0,                                          /* tp_base */
2136
    0,                                          /* tp_dict */
2137
    0,                                          /* tp_descr_get */
2138
    0,                                          /* tp_descr_set */
2139
    0,                                          /* tp_dictoffset */
2140
    0,                                          /* tp_init */
2141
    0,                                          /* tp_alloc */
2142
    0,                                          /* tp_new */
2143
    .tp_finalize = async_gen_asend_finalize,
2144
};
2145
2146
2147
static PyObject *
2148
async_gen_asend_new(PyAsyncGenObject *gen, PyObject *sendval)
2149
0
{
2150
0
    PyAsyncGenASend *ags = _Py_FREELIST_POP(PyAsyncGenASend, async_gen_asends);
2151
0
    if (ags == NULL) {
2152
0
        ags = PyObject_GC_New(PyAsyncGenASend, &_PyAsyncGenASend_Type);
2153
0
        if (ags == NULL) {
2154
0
            return NULL;
2155
0
        }
2156
0
    }
2157
2158
0
    ags->ags_gen = (PyAsyncGenObject*)Py_NewRef(gen);
2159
0
    ags->ags_sendval = Py_XNewRef(sendval);
2160
0
    ags->ags_state = AWAITABLE_STATE_INIT;
2161
2162
0
    _PyObject_GC_TRACK((PyObject*)ags);
2163
0
    return (PyObject*)ags;
2164
0
}
2165
2166
2167
/* ---------- Async Generator Value Wrapper ------------ */
2168
2169
2170
static void
2171
async_gen_wrapped_val_dealloc(PyObject *self)
2172
0
{
2173
0
    _PyAsyncGenWrappedValue *agw = _PyAsyncGenWrappedValue_CAST(self);
2174
0
    _PyObject_GC_UNTRACK(self);
2175
0
    Py_CLEAR(agw->agw_val);
2176
0
    _Py_FREELIST_FREE(async_gens, self, PyObject_GC_Del);
2177
0
}
2178
2179
2180
static int
2181
async_gen_wrapped_val_traverse(PyObject *self, visitproc visit, void *arg)
2182
0
{
2183
0
    _PyAsyncGenWrappedValue *agw = _PyAsyncGenWrappedValue_CAST(self);
2184
0
    Py_VISIT(agw->agw_val);
2185
0
    return 0;
2186
0
}
2187
2188
2189
PyTypeObject _PyAsyncGenWrappedValue_Type = {
2190
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
2191
    "async_generator_wrapped_value",            /* tp_name */
2192
    sizeof(_PyAsyncGenWrappedValue),            /* tp_basicsize */
2193
    0,                                          /* tp_itemsize */
2194
    /* methods */
2195
    async_gen_wrapped_val_dealloc,              /* tp_dealloc */
2196
    0,                                          /* tp_vectorcall_offset */
2197
    0,                                          /* tp_getattr */
2198
    0,                                          /* tp_setattr */
2199
    0,                                          /* tp_as_async */
2200
    0,                                          /* tp_repr */
2201
    0,                                          /* tp_as_number */
2202
    0,                                          /* tp_as_sequence */
2203
    0,                                          /* tp_as_mapping */
2204
    0,                                          /* tp_hash */
2205
    0,                                          /* tp_call */
2206
    0,                                          /* tp_str */
2207
    PyObject_GenericGetAttr,                    /* tp_getattro */
2208
    0,                                          /* tp_setattro */
2209
    0,                                          /* tp_as_buffer */
2210
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,    /* tp_flags */
2211
    0,                                          /* tp_doc */
2212
    async_gen_wrapped_val_traverse,             /* tp_traverse */
2213
    0,                                          /* tp_clear */
2214
    0,                                          /* tp_richcompare */
2215
    0,                                          /* tp_weaklistoffset */
2216
    0,                                          /* tp_iter */
2217
    0,                                          /* tp_iternext */
2218
    0,                                          /* tp_methods */
2219
    0,                                          /* tp_members */
2220
    0,                                          /* tp_getset */
2221
    0,                                          /* tp_base */
2222
    0,                                          /* tp_dict */
2223
    0,                                          /* tp_descr_get */
2224
    0,                                          /* tp_descr_set */
2225
    0,                                          /* tp_dictoffset */
2226
    0,                                          /* tp_init */
2227
    0,                                          /* tp_alloc */
2228
    0,                                          /* tp_new */
2229
};
2230
2231
2232
PyObject *
2233
_PyAsyncGenValueWrapperNew(PyThreadState *tstate, PyObject *val)
2234
0
{
2235
0
    assert(val);
2236
2237
0
    _PyAsyncGenWrappedValue *o = _Py_FREELIST_POP(_PyAsyncGenWrappedValue, async_gens);
2238
0
    if (o == NULL) {
2239
0
        o = PyObject_GC_New(_PyAsyncGenWrappedValue,
2240
0
                            &_PyAsyncGenWrappedValue_Type);
2241
0
        if (o == NULL) {
2242
0
            return NULL;
2243
0
        }
2244
0
    }
2245
0
    assert(_PyAsyncGenWrappedValue_CheckExact(o));
2246
0
    o->agw_val = Py_NewRef(val);
2247
0
    _PyObject_GC_TRACK((PyObject*)o);
2248
0
    return (PyObject*)o;
2249
0
}
2250
2251
2252
/* ---------- Async Generator AThrow awaitable ------------ */
2253
2254
#define _PyAsyncGenAThrow_CAST(op) \
2255
0
    (assert(Py_IS_TYPE((op), &_PyAsyncGenAThrow_Type)), \
2256
0
     _Py_CAST(PyAsyncGenAThrow*, (op)))
2257
2258
static void
2259
async_gen_athrow_dealloc(PyObject *self)
2260
0
{
2261
0
    PyAsyncGenAThrow *agt = _PyAsyncGenAThrow_CAST(self);
2262
0
    if (PyObject_CallFinalizerFromDealloc(self)) {
2263
0
        return;
2264
0
    }
2265
2266
0
    _PyObject_GC_UNTRACK(self);
2267
0
    Py_CLEAR(agt->agt_gen);
2268
0
    Py_XDECREF(agt->agt_typ);
2269
0
    Py_XDECREF(agt->agt_tb);
2270
0
    Py_XDECREF(agt->agt_val);
2271
0
    PyObject_GC_Del(self);
2272
0
}
2273
2274
2275
static int
2276
async_gen_athrow_traverse(PyObject *self, visitproc visit, void *arg)
2277
0
{
2278
0
    PyAsyncGenAThrow *agt = _PyAsyncGenAThrow_CAST(self);
2279
0
    Py_VISIT(agt->agt_gen);
2280
0
    Py_VISIT(agt->agt_typ);
2281
0
    Py_VISIT(agt->agt_tb);
2282
0
    Py_VISIT(agt->agt_val);
2283
0
    return 0;
2284
0
}
2285
2286
2287
static PyObject *
2288
async_gen_athrow_send(PyObject *self, PyObject *arg)
2289
0
{
2290
0
    PyAsyncGenAThrow *o = _PyAsyncGenAThrow_CAST(self);
2291
0
    PyGenObject *gen = _PyGen_CAST(o->agt_gen);
2292
0
    PyObject *retval;
2293
2294
0
    if (o->agt_state == AWAITABLE_STATE_CLOSED) {
2295
0
        PyErr_SetString(
2296
0
            PyExc_RuntimeError,
2297
0
            "cannot reuse already awaited aclose()/athrow()");
2298
0
        return NULL;
2299
0
    }
2300
2301
0
    if (FRAME_STATE_FINISHED(gen->gi_frame_state)) {
2302
0
        o->agt_state = AWAITABLE_STATE_CLOSED;
2303
0
        PyErr_SetNone(PyExc_StopIteration);
2304
0
        return NULL;
2305
0
    }
2306
2307
0
    if (o->agt_state == AWAITABLE_STATE_INIT) {
2308
0
        if (o->agt_gen->ag_running_async) {
2309
0
            o->agt_state = AWAITABLE_STATE_CLOSED;
2310
0
            if (o->agt_typ == NULL) {
2311
0
                PyErr_SetString(
2312
0
                    PyExc_RuntimeError,
2313
0
                    "aclose(): asynchronous generator is already running");
2314
0
            }
2315
0
            else {
2316
0
                PyErr_SetString(
2317
0
                    PyExc_RuntimeError,
2318
0
                    "athrow(): asynchronous generator is already running");
2319
0
            }
2320
0
            return NULL;
2321
0
        }
2322
2323
0
        if (o->agt_gen->ag_closed) {
2324
0
            o->agt_state = AWAITABLE_STATE_CLOSED;
2325
0
            PyErr_SetNone(PyExc_StopAsyncIteration);
2326
0
            return NULL;
2327
0
        }
2328
2329
0
        if (arg != Py_None) {
2330
0
            PyErr_SetString(PyExc_RuntimeError, NON_INIT_CORO_MSG);
2331
0
            return NULL;
2332
0
        }
2333
2334
0
        o->agt_state = AWAITABLE_STATE_ITER;
2335
0
        o->agt_gen->ag_running_async = 1;
2336
2337
0
        if (o->agt_typ == NULL) {
2338
            /* aclose() mode */
2339
0
            o->agt_gen->ag_closed = 1;
2340
2341
0
            retval = _gen_throw((PyGenObject *)gen,
2342
0
                                0,  /* Do not close generator when
2343
                                       PyExc_GeneratorExit is passed */
2344
0
                                PyExc_GeneratorExit, NULL, NULL);
2345
2346
0
            if (retval && _PyAsyncGenWrappedValue_CheckExact(retval)) {
2347
0
                Py_DECREF(retval);
2348
0
                goto yield_close;
2349
0
            }
2350
0
        } else {
2351
0
            retval = _gen_throw((PyGenObject *)gen,
2352
0
                                0,  /* Do not close generator when
2353
                                       PyExc_GeneratorExit is passed */
2354
0
                                o->agt_typ, o->agt_val, o->agt_tb);
2355
0
            retval = async_gen_unwrap_value(o->agt_gen, retval);
2356
0
        }
2357
0
        if (retval == NULL) {
2358
0
            goto check_error;
2359
0
        }
2360
0
        return retval;
2361
0
    }
2362
2363
0
    assert(o->agt_state == AWAITABLE_STATE_ITER);
2364
2365
0
    retval = gen_send((PyObject *)gen, arg);
2366
0
    if (o->agt_typ) {
2367
0
        return async_gen_unwrap_value(o->agt_gen, retval);
2368
0
    } else {
2369
        /* aclose() mode */
2370
0
        if (retval) {
2371
0
            if (_PyAsyncGenWrappedValue_CheckExact(retval)) {
2372
0
                Py_DECREF(retval);
2373
0
                goto yield_close;
2374
0
            }
2375
0
            else {
2376
0
                return retval;
2377
0
            }
2378
0
        }
2379
0
        else {
2380
0
            goto check_error;
2381
0
        }
2382
0
    }
2383
2384
0
yield_close:
2385
0
    o->agt_gen->ag_running_async = 0;
2386
0
    o->agt_state = AWAITABLE_STATE_CLOSED;
2387
0
    PyErr_SetString(
2388
0
        PyExc_RuntimeError, ASYNC_GEN_IGNORED_EXIT_MSG);
2389
0
    return NULL;
2390
2391
0
check_error:
2392
0
    o->agt_gen->ag_running_async = 0;
2393
0
    o->agt_state = AWAITABLE_STATE_CLOSED;
2394
0
    if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration) ||
2395
0
            PyErr_ExceptionMatches(PyExc_GeneratorExit))
2396
0
    {
2397
0
        if (o->agt_typ == NULL) {
2398
            /* when aclose() is called we don't want to propagate
2399
               StopAsyncIteration or GeneratorExit; just raise
2400
               StopIteration, signalling that this 'aclose()' await
2401
               is done.
2402
            */
2403
0
            PyErr_Clear();
2404
0
            PyErr_SetNone(PyExc_StopIteration);
2405
0
        }
2406
0
    }
2407
0
    return NULL;
2408
0
}
2409
2410
2411
static PyObject *
2412
async_gen_athrow_throw(PyObject *self, PyObject *const *args, Py_ssize_t nargs)
2413
0
{
2414
0
    PyAsyncGenAThrow *o = _PyAsyncGenAThrow_CAST(self);
2415
2416
0
    if (o->agt_state == AWAITABLE_STATE_CLOSED) {
2417
0
        PyErr_SetString(
2418
0
            PyExc_RuntimeError,
2419
0
            "cannot reuse already awaited aclose()/athrow()");
2420
0
        return NULL;
2421
0
    }
2422
2423
0
    if (o->agt_state == AWAITABLE_STATE_INIT) {
2424
0
        if (o->agt_gen->ag_running_async) {
2425
0
            o->agt_state = AWAITABLE_STATE_CLOSED;
2426
0
            if (o->agt_typ == NULL) {
2427
0
                PyErr_SetString(
2428
0
                    PyExc_RuntimeError,
2429
0
                    "aclose(): asynchronous generator is already running");
2430
0
            }
2431
0
            else {
2432
0
                PyErr_SetString(
2433
0
                    PyExc_RuntimeError,
2434
0
                    "athrow(): asynchronous generator is already running");
2435
0
            }
2436
0
            return NULL;
2437
0
        }
2438
2439
0
        o->agt_state = AWAITABLE_STATE_ITER;
2440
0
        o->agt_gen->ag_running_async = 1;
2441
0
    }
2442
2443
0
    PyObject *retval = gen_throw((PyObject*)o->agt_gen, args, nargs);
2444
0
    if (o->agt_typ) {
2445
0
        retval = async_gen_unwrap_value(o->agt_gen, retval);
2446
0
        if (retval == NULL) {
2447
0
            o->agt_gen->ag_running_async = 0;
2448
0
            o->agt_state = AWAITABLE_STATE_CLOSED;
2449
0
        }
2450
0
        return retval;
2451
0
    }
2452
0
    else {
2453
        /* aclose() mode */
2454
0
        if (retval && _PyAsyncGenWrappedValue_CheckExact(retval)) {
2455
0
            o->agt_gen->ag_running_async = 0;
2456
0
            o->agt_state = AWAITABLE_STATE_CLOSED;
2457
0
            Py_DECREF(retval);
2458
0
            PyErr_SetString(PyExc_RuntimeError, ASYNC_GEN_IGNORED_EXIT_MSG);
2459
0
            return NULL;
2460
0
        }
2461
0
        if (retval == NULL) {
2462
0
            o->agt_gen->ag_running_async = 0;
2463
0
            o->agt_state = AWAITABLE_STATE_CLOSED;
2464
0
        }
2465
0
        if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration) ||
2466
0
            PyErr_ExceptionMatches(PyExc_GeneratorExit))
2467
0
        {
2468
            /* when aclose() is called we don't want to propagate
2469
               StopAsyncIteration or GeneratorExit; just raise
2470
               StopIteration, signalling that this 'aclose()' await
2471
               is done.
2472
            */
2473
0
            PyErr_Clear();
2474
0
            PyErr_SetNone(PyExc_StopIteration);
2475
0
        }
2476
0
        return retval;
2477
0
    }
2478
0
}
2479
2480
2481
static PyObject *
2482
async_gen_athrow_iternext(PyObject *agt)
2483
0
{
2484
0
    return async_gen_athrow_send(agt, Py_None);
2485
0
}
2486
2487
2488
static PyObject *
2489
async_gen_athrow_close(PyObject *self, PyObject *args)
2490
0
{
2491
0
    PyAsyncGenAThrow *agt = _PyAsyncGenAThrow_CAST(self);
2492
0
    if (agt->agt_state == AWAITABLE_STATE_CLOSED) {
2493
0
        Py_RETURN_NONE;
2494
0
    }
2495
0
    PyObject *result = async_gen_athrow_throw((PyObject*)agt,
2496
0
                                              &PyExc_GeneratorExit, 1);
2497
0
    if (result == NULL) {
2498
0
        if (PyErr_ExceptionMatches(PyExc_StopIteration) ||
2499
0
            PyErr_ExceptionMatches(PyExc_StopAsyncIteration) ||
2500
0
            PyErr_ExceptionMatches(PyExc_GeneratorExit))
2501
0
        {
2502
0
            PyErr_Clear();
2503
0
            Py_RETURN_NONE;
2504
0
        }
2505
0
        return result;
2506
0
    } else {
2507
0
        Py_DECREF(result);
2508
0
        PyErr_SetString(PyExc_RuntimeError, "coroutine ignored GeneratorExit");
2509
0
        return NULL;
2510
0
    }
2511
0
}
2512
2513
2514
static void
2515
async_gen_athrow_finalize(PyObject *op)
2516
0
{
2517
0
    PyAsyncGenAThrow *o = (PyAsyncGenAThrow*)op;
2518
0
    if (o->agt_state == AWAITABLE_STATE_INIT) {
2519
0
        PyObject *method = o->agt_typ ? &_Py_ID(athrow) : &_Py_ID(aclose);
2520
0
        _PyErr_WarnUnawaitedAgenMethod(o->agt_gen, method);
2521
0
    }
2522
0
}
2523
2524
static PyMethodDef async_gen_athrow_methods[] = {
2525
    {"send", async_gen_athrow_send, METH_O, send_doc},
2526
    {"throw", _PyCFunction_CAST(async_gen_athrow_throw),
2527
    METH_FASTCALL, throw_doc},
2528
    {"close", async_gen_athrow_close, METH_NOARGS, close_doc},
2529
    {NULL, NULL}        /* Sentinel */
2530
};
2531
2532
2533
static PyAsyncMethods async_gen_athrow_as_async = {
2534
    PyObject_SelfIter,                          /* am_await */
2535
    0,                                          /* am_aiter */
2536
    0,                                          /* am_anext */
2537
    0,                                          /* am_send  */
2538
};
2539
2540
2541
PyTypeObject _PyAsyncGenAThrow_Type = {
2542
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
2543
    "async_generator_athrow",                   /* tp_name */
2544
    sizeof(PyAsyncGenAThrow),                   /* tp_basicsize */
2545
    0,                                          /* tp_itemsize */
2546
    /* methods */
2547
    async_gen_athrow_dealloc,                   /* tp_dealloc */
2548
    0,                                          /* tp_vectorcall_offset */
2549
    0,                                          /* tp_getattr */
2550
    0,                                          /* tp_setattr */
2551
    &async_gen_athrow_as_async,                 /* tp_as_async */
2552
    0,                                          /* tp_repr */
2553
    0,                                          /* tp_as_number */
2554
    0,                                          /* tp_as_sequence */
2555
    0,                                          /* tp_as_mapping */
2556
    0,                                          /* tp_hash */
2557
    0,                                          /* tp_call */
2558
    0,                                          /* tp_str */
2559
    PyObject_GenericGetAttr,                    /* tp_getattro */
2560
    0,                                          /* tp_setattro */
2561
    0,                                          /* tp_as_buffer */
2562
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,    /* tp_flags */
2563
    0,                                          /* tp_doc */
2564
    async_gen_athrow_traverse,                  /* tp_traverse */
2565
    0,                                          /* tp_clear */
2566
    0,                                          /* tp_richcompare */
2567
    0,                                          /* tp_weaklistoffset */
2568
    PyObject_SelfIter,                          /* tp_iter */
2569
    async_gen_athrow_iternext,                  /* tp_iternext */
2570
    async_gen_athrow_methods,                   /* tp_methods */
2571
    0,                                          /* tp_members */
2572
    0,                                          /* tp_getset */
2573
    0,                                          /* tp_base */
2574
    0,                                          /* tp_dict */
2575
    0,                                          /* tp_descr_get */
2576
    0,                                          /* tp_descr_set */
2577
    0,                                          /* tp_dictoffset */
2578
    0,                                          /* tp_init */
2579
    0,                                          /* tp_alloc */
2580
    0,                                          /* tp_new */
2581
    .tp_finalize = async_gen_athrow_finalize,
2582
};
2583
2584
2585
static PyObject *
2586
async_gen_athrow_new(PyAsyncGenObject *gen, PyObject *args)
2587
0
{
2588
0
    PyObject *typ = NULL;
2589
0
    PyObject *tb = NULL;
2590
0
    PyObject *val = NULL;
2591
0
    if (args && !PyArg_UnpackTuple(args, "athrow", 1, 3, &typ, &val, &tb)) {
2592
0
        return NULL;
2593
0
    }
2594
2595
0
    PyAsyncGenAThrow *o;
2596
0
    o = PyObject_GC_New(PyAsyncGenAThrow, &_PyAsyncGenAThrow_Type);
2597
0
    if (o == NULL) {
2598
0
        return NULL;
2599
0
    }
2600
0
    o->agt_gen = (PyAsyncGenObject*)Py_NewRef(gen);
2601
0
    o->agt_typ = Py_XNewRef(typ);
2602
0
    o->agt_tb = Py_XNewRef(tb);
2603
0
    o->agt_val = Py_XNewRef(val);
2604
2605
0
    o->agt_state = AWAITABLE_STATE_INIT;
2606
0
    _PyObject_GC_TRACK((PyObject*)o);
2607
0
    return (PyObject*)o;
2608
0
}