rustpython-vm 0.5.0

RustPython virtual machine.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
use super::{PyCode, PyGenerator, PyGenericAlias, PyStrRef, PyType, PyTypeRef};
use crate::{
    AsObject, Context, Py, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine,
    builtins::PyBaseExceptionRef,
    class::PyClassImpl,
    common::lock::PyMutex,
    coroutine::{Coro, warn_deprecated_throw_signature},
    frame::FrameRef,
    function::OptionalArg,
    object::{Traverse, TraverseFn},
    protocol::PyIterReturn,
    types::{Destructor, IterNext, Iterable, Representable, SelfIter},
};

use crossbeam_utils::atomic::AtomicCell;

#[pyclass(name = "async_generator", module = false, traverse = "manual")]
#[derive(Debug)]
pub struct PyAsyncGen {
    inner: Coro,
    running_async: AtomicCell<bool>,
    // whether hooks have been initialized
    ag_hooks_inited: AtomicCell<bool>,
    // ag_origin_or_finalizer - stores the finalizer callback
    ag_finalizer: PyMutex<Option<PyObjectRef>>,
}

unsafe impl Traverse for PyAsyncGen {
    fn traverse(&self, tracer_fn: &mut TraverseFn<'_>) {
        self.inner.traverse(tracer_fn);
        self.ag_finalizer.traverse(tracer_fn);
    }
}
type PyAsyncGenRef = PyRef<PyAsyncGen>;

impl PyPayload for PyAsyncGen {
    #[inline]
    fn class(ctx: &Context) -> &'static Py<PyType> {
        ctx.types.async_generator
    }
}

#[pyclass(
    flags(DISALLOW_INSTANTIATION, HAS_WEAKREF),
    with(PyRef, Representable, Destructor)
)]
impl PyAsyncGen {
    pub const fn as_coro(&self) -> &Coro {
        &self.inner
    }

    pub fn new(frame: FrameRef, name: PyStrRef, qualname: PyStrRef) -> Self {
        Self {
            inner: Coro::new(frame, name, qualname),
            running_async: AtomicCell::new(false),
            ag_hooks_inited: AtomicCell::new(false),
            ag_finalizer: PyMutex::new(None),
        }
    }

    /// Initialize async generator hooks.
    /// Returns Ok(()) if successful, Err if firstiter hook raised an exception.
    fn init_hooks(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<()> {
        // = async_gen_init_hooks
        if zelf.ag_hooks_inited.load() {
            return Ok(());
        }

        zelf.ag_hooks_inited.store(true);

        // Get and store finalizer from VM
        let finalizer = vm.async_gen_finalizer.borrow().clone();
        if let Some(finalizer) = finalizer {
            *zelf.ag_finalizer.lock() = Some(finalizer);
        }

        // Call firstiter hook
        let firstiter = vm.async_gen_firstiter.borrow().clone();
        if let Some(firstiter) = firstiter {
            let obj: PyObjectRef = zelf.to_owned().into();
            firstiter.call((obj,), vm)?;
        }

        Ok(())
    }

    /// Call finalizer hook if set.
    fn call_finalizer(zelf: &Py<Self>, vm: &VirtualMachine) {
        let finalizer = zelf.ag_finalizer.lock().clone();
        if let Some(finalizer) = finalizer
            && !zelf.inner.closed.load()
        {
            // Create a strong reference for the finalizer call.
            // This keeps the object alive during the finalizer execution.
            let obj: PyObjectRef = zelf.to_owned().into();

            // Call the finalizer. Any exceptions are handled as unraisable.
            if let Err(e) = finalizer.call((obj,), vm) {
                vm.run_unraisable(e, Some("async generator finalizer".to_owned()), finalizer);
            }
        }
    }

    #[pygetset]
    fn __name__(&self) -> PyStrRef {
        self.inner.name()
    }

    #[pygetset(setter)]
    fn set___name__(&self, name: PyStrRef) {
        self.inner.set_name(name)
    }

    #[pygetset]
    fn __qualname__(&self) -> PyStrRef {
        self.inner.qualname()
    }

    #[pygetset(setter)]
    fn set___qualname__(&self, qualname: PyStrRef) {
        self.inner.set_qualname(qualname)
    }

    #[pygetset]
    fn ag_await(&self, _vm: &VirtualMachine) -> Option<PyObjectRef> {
        self.inner.frame().yield_from_target()
    }
    #[pygetset]
    fn ag_frame(&self, _vm: &VirtualMachine) -> Option<FrameRef> {
        if self.inner.closed() {
            None
        } else {
            Some(self.inner.frame())
        }
    }
    #[pygetset]
    fn ag_running(&self, _vm: &VirtualMachine) -> bool {
        self.inner.running()
    }
    #[pygetset]
    fn ag_code(&self, _vm: &VirtualMachine) -> PyRef<PyCode> {
        self.inner.frame().code.clone()
    }

    #[pyclassmethod]
    fn __class_getitem__(cls: PyTypeRef, args: PyObjectRef, vm: &VirtualMachine) -> PyGenericAlias {
        PyGenericAlias::from_args(cls, args, vm)
    }
}

#[pyclass]
impl PyRef<PyAsyncGen> {
    #[pymethod]
    const fn __aiter__(self, _vm: &VirtualMachine) -> Self {
        self
    }

    #[pymethod]
    fn __anext__(self, vm: &VirtualMachine) -> PyResult<PyAsyncGenASend> {
        PyAsyncGen::init_hooks(&self, vm)?;
        Ok(PyAsyncGenASend {
            ag: self,
            state: AtomicCell::new(AwaitableState::Init),
            value: vm.ctx.none(),
        })
    }

    #[pymethod]
    fn asend(self, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyAsyncGenASend> {
        PyAsyncGen::init_hooks(&self, vm)?;
        Ok(PyAsyncGenASend {
            ag: self,
            state: AtomicCell::new(AwaitableState::Init),
            value,
        })
    }

    #[pymethod]
    fn athrow(
        self,
        exc_type: PyObjectRef,
        exc_val: OptionalArg,
        exc_tb: OptionalArg,
        vm: &VirtualMachine,
    ) -> PyResult<PyAsyncGenAThrow> {
        warn_deprecated_throw_signature(&exc_val, &exc_tb, vm)?;
        PyAsyncGen::init_hooks(&self, vm)?;
        Ok(PyAsyncGenAThrow {
            ag: self,
            aclose: false,
            state: AtomicCell::new(AwaitableState::Init),
            value: (
                exc_type,
                exc_val.unwrap_or_none(vm),
                exc_tb.unwrap_or_none(vm),
            ),
        })
    }

    #[pymethod]
    fn aclose(self, vm: &VirtualMachine) -> PyResult<PyAsyncGenAThrow> {
        PyAsyncGen::init_hooks(&self, vm)?;
        Ok(PyAsyncGenAThrow {
            ag: self,
            aclose: true,
            state: AtomicCell::new(AwaitableState::Init),
            value: (
                vm.ctx.exceptions.generator_exit.to_owned().into(),
                vm.ctx.none(),
                vm.ctx.none(),
            ),
        })
    }
}

impl Representable for PyAsyncGen {
    #[inline]
    fn repr_str(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<String> {
        Ok(zelf.inner.repr(zelf.as_object(), zelf.get_id(), vm))
    }
}

#[pyclass(
    module = false,
    name = "async_generator_wrapped_value",
    traverse = "manual"
)]
#[derive(Debug)]
pub(crate) struct PyAsyncGenWrappedValue(pub PyObjectRef);

unsafe impl Traverse for PyAsyncGenWrappedValue {
    fn traverse(&self, tracer_fn: &mut TraverseFn<'_>) {
        self.0.traverse(tracer_fn);
    }
}

impl PyPayload for PyAsyncGenWrappedValue {
    #[inline]
    fn class(ctx: &Context) -> &'static Py<PyType> {
        ctx.types.async_generator_wrapped_value
    }
}

#[pyclass]
impl PyAsyncGenWrappedValue {}

impl PyAsyncGenWrappedValue {
    fn unbox(ag: &PyAsyncGen, val: PyResult<PyIterReturn>, vm: &VirtualMachine) -> PyResult {
        let (closed, async_done) = match &val {
            Ok(PyIterReturn::StopIteration(_)) => (true, true),
            Err(e) if e.fast_isinstance(vm.ctx.exceptions.generator_exit) => (true, true),
            Err(_) => (false, true),
            _ => (false, false),
        };
        if closed {
            ag.inner.closed.store(true);
        }
        if async_done {
            ag.running_async.store(false);
        }
        let val = val?.into_async_pyresult(vm)?;
        match_class!(match val {
            val @ Self => {
                ag.running_async.store(false);
                Err(vm.new_stop_iteration(Some(val.0.clone())))
            }
            val => Ok(val),
        })
    }
}

#[derive(Debug, Clone, Copy)]
enum AwaitableState {
    Init,
    Iter,
    Closed,
}

#[pyclass(module = false, name = "async_generator_asend", traverse = "manual")]
#[derive(Debug)]
pub(crate) struct PyAsyncGenASend {
    ag: PyAsyncGenRef,
    state: AtomicCell<AwaitableState>,
    value: PyObjectRef,
}

unsafe impl Traverse for PyAsyncGenASend {
    fn traverse(&self, tracer_fn: &mut TraverseFn<'_>) {
        self.ag.traverse(tracer_fn);
        self.value.traverse(tracer_fn);
    }
}

impl PyPayload for PyAsyncGenASend {
    #[inline]
    fn class(ctx: &Context) -> &'static Py<PyType> {
        ctx.types.async_generator_asend
    }
}

#[pyclass(with(IterNext, Iterable))]
impl PyAsyncGenASend {
    #[pymethod(name = "__await__")]
    const fn r#await(zelf: PyRef<Self>, _vm: &VirtualMachine) -> PyRef<Self> {
        zelf
    }

    #[pymethod]
    fn send(&self, val: PyObjectRef, vm: &VirtualMachine) -> PyResult {
        let val = match self.state.load() {
            AwaitableState::Closed => {
                return Err(
                    vm.new_runtime_error("cannot reuse already awaited __anext__()/asend()")
                );
            }
            AwaitableState::Iter => val, // already running, all good
            AwaitableState::Init => {
                if self.ag.running_async.load() {
                    return Err(
                        vm.new_runtime_error("anext(): asynchronous generator is already running")
                    );
                }
                self.ag.running_async.store(true);
                self.state.store(AwaitableState::Iter);
                if vm.is_none(&val) {
                    self.value.clone()
                } else {
                    val
                }
            }
        };
        let res = self.ag.inner.send(self.ag.as_object(), val, vm);
        let res = PyAsyncGenWrappedValue::unbox(&self.ag, res, vm);
        if res.is_err() {
            self.set_closed();
        }
        res
    }

    #[pymethod]
    fn throw(
        &self,
        exc_type: PyObjectRef,
        exc_val: OptionalArg,
        exc_tb: OptionalArg,
        vm: &VirtualMachine,
    ) -> PyResult {
        match self.state.load() {
            AwaitableState::Closed => {
                return Err(
                    vm.new_runtime_error("cannot reuse already awaited __anext__()/asend()")
                );
            }
            AwaitableState::Init => {
                if self.ag.running_async.load() {
                    self.state.store(AwaitableState::Closed);
                    return Err(
                        vm.new_runtime_error("anext(): asynchronous generator is already running")
                    );
                }
                self.ag.running_async.store(true);
                self.state.store(AwaitableState::Iter);
            }
            AwaitableState::Iter => {}
        }

        warn_deprecated_throw_signature(&exc_val, &exc_tb, vm)?;
        let res = self.ag.inner.throw(
            self.ag.as_object(),
            exc_type,
            exc_val.unwrap_or_none(vm),
            exc_tb.unwrap_or_none(vm),
            vm,
        );
        let res = PyAsyncGenWrappedValue::unbox(&self.ag, res, vm);
        if res.is_err() {
            self.set_closed();
        }
        res
    }

    #[pymethod]
    fn close(&self, vm: &VirtualMachine) -> PyResult<()> {
        if matches!(self.state.load(), AwaitableState::Closed) {
            return Ok(());
        }
        let result = self.throw(
            vm.ctx.exceptions.generator_exit.to_owned().into(),
            OptionalArg::Missing,
            OptionalArg::Missing,
            vm,
        );
        match result {
            Ok(_) => Err(vm.new_runtime_error("coroutine ignored GeneratorExit")),
            Err(e)
                if e.fast_isinstance(vm.ctx.exceptions.stop_iteration)
                    || e.fast_isinstance(vm.ctx.exceptions.stop_async_iteration)
                    || e.fast_isinstance(vm.ctx.exceptions.generator_exit) =>
            {
                Ok(())
            }
            Err(e) => Err(e),
        }
    }

    fn set_closed(&self) {
        self.state.store(AwaitableState::Closed);
    }
}

impl SelfIter for PyAsyncGenASend {}
impl IterNext for PyAsyncGenASend {
    fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> {
        PyIterReturn::from_pyresult(zelf.send(vm.ctx.none(), vm), vm)
    }
}

#[pyclass(module = false, name = "async_generator_athrow", traverse = "manual")]
#[derive(Debug)]
pub(crate) struct PyAsyncGenAThrow {
    ag: PyAsyncGenRef,
    aclose: bool,
    state: AtomicCell<AwaitableState>,
    value: (PyObjectRef, PyObjectRef, PyObjectRef),
}

unsafe impl Traverse for PyAsyncGenAThrow {
    fn traverse(&self, tracer_fn: &mut TraverseFn<'_>) {
        self.ag.traverse(tracer_fn);
        self.value.traverse(tracer_fn);
    }
}

impl PyPayload for PyAsyncGenAThrow {
    #[inline]
    fn class(ctx: &Context) -> &'static Py<PyType> {
        ctx.types.async_generator_athrow
    }
}

#[pyclass(with(IterNext, Iterable))]
impl PyAsyncGenAThrow {
    #[pymethod(name = "__await__")]
    const fn r#await(zelf: PyRef<Self>, _vm: &VirtualMachine) -> PyRef<Self> {
        zelf
    }

    #[pymethod]
    fn send(&self, val: PyObjectRef, vm: &VirtualMachine) -> PyResult {
        match self.state.load() {
            AwaitableState::Closed => {
                Err(vm.new_runtime_error("cannot reuse already awaited aclose()/athrow()"))
            }
            AwaitableState::Init => {
                if self.ag.running_async.load() {
                    self.state.store(AwaitableState::Closed);
                    let msg = if self.aclose {
                        "aclose(): asynchronous generator is already running"
                    } else {
                        "athrow(): asynchronous generator is already running"
                    };
                    return Err(vm.new_runtime_error(msg.to_owned()));
                }
                if self.ag.inner.closed() {
                    self.state.store(AwaitableState::Closed);
                    return Err(vm.new_stop_iteration(None));
                }
                if !vm.is_none(&val) {
                    return Err(vm.new_runtime_error(
                        "can't send non-None value to a just-started async generator",
                    ));
                }
                self.state.store(AwaitableState::Iter);
                self.ag.running_async.store(true);

                let (ty, val, tb) = self.value.clone();
                let ret = self.ag.inner.throw(self.ag.as_object(), ty, val, tb, vm);
                let ret = if self.aclose {
                    if self.ignored_close(&ret) {
                        Err(self.yield_close(vm))
                    } else {
                        ret.and_then(|o| o.into_async_pyresult(vm))
                    }
                } else {
                    PyAsyncGenWrappedValue::unbox(&self.ag, ret, vm)
                };
                ret.map_err(|e| self.check_error(e, vm))
            }
            AwaitableState::Iter => {
                let ret = self.ag.inner.send(self.ag.as_object(), val, vm);
                if self.aclose {
                    match ret {
                        Ok(PyIterReturn::Return(v))
                            if v.downcastable::<PyAsyncGenWrappedValue>() =>
                        {
                            Err(self.yield_close(vm))
                        }
                        other => other
                            .and_then(|o| o.into_async_pyresult(vm))
                            .map_err(|e| self.check_error(e, vm)),
                    }
                } else {
                    PyAsyncGenWrappedValue::unbox(&self.ag, ret, vm)
                }
            }
        }
    }

    #[pymethod]
    fn throw(
        &self,
        exc_type: PyObjectRef,
        exc_val: OptionalArg,
        exc_tb: OptionalArg,
        vm: &VirtualMachine,
    ) -> PyResult {
        match self.state.load() {
            AwaitableState::Closed => {
                return Err(vm.new_runtime_error("cannot reuse already awaited aclose()/athrow()"));
            }
            AwaitableState::Init => {
                if self.ag.running_async.load() {
                    self.state.store(AwaitableState::Closed);
                    let msg = if self.aclose {
                        "aclose(): asynchronous generator is already running"
                    } else {
                        "athrow(): asynchronous generator is already running"
                    };
                    return Err(vm.new_runtime_error(msg.to_owned()));
                }
                if self.ag.inner.closed() {
                    self.state.store(AwaitableState::Closed);
                    return Err(vm.new_stop_iteration(None));
                }
                self.ag.running_async.store(true);
                self.state.store(AwaitableState::Iter);
            }
            AwaitableState::Iter => {}
        }

        warn_deprecated_throw_signature(&exc_val, &exc_tb, vm)?;
        let ret = self.ag.inner.throw(
            self.ag.as_object(),
            exc_type,
            exc_val.unwrap_or_none(vm),
            exc_tb.unwrap_or_none(vm),
            vm,
        );
        let res = if self.aclose {
            if self.ignored_close(&ret) {
                Err(self.yield_close(vm))
            } else {
                ret.and_then(|o| o.into_async_pyresult(vm))
            }
        } else {
            PyAsyncGenWrappedValue::unbox(&self.ag, ret, vm)
        };
        res.map_err(|e| self.check_error(e, vm))
    }

    #[pymethod]
    fn close(&self, vm: &VirtualMachine) -> PyResult<()> {
        if matches!(self.state.load(), AwaitableState::Closed) {
            return Ok(());
        }
        let result = self.throw(
            vm.ctx.exceptions.generator_exit.to_owned().into(),
            OptionalArg::Missing,
            OptionalArg::Missing,
            vm,
        );
        match result {
            Ok(_) => Err(vm.new_runtime_error("coroutine ignored GeneratorExit")),
            Err(e)
                if e.fast_isinstance(vm.ctx.exceptions.stop_iteration)
                    || e.fast_isinstance(vm.ctx.exceptions.stop_async_iteration)
                    || e.fast_isinstance(vm.ctx.exceptions.generator_exit) =>
            {
                Ok(())
            }
            Err(e) => Err(e),
        }
    }

    fn ignored_close(&self, res: &PyResult<PyIterReturn>) -> bool {
        res.as_ref().is_ok_and(|v| match v {
            PyIterReturn::Return(obj) => obj.downcastable::<PyAsyncGenWrappedValue>(),
            PyIterReturn::StopIteration(_) => false,
        })
    }
    fn yield_close(&self, vm: &VirtualMachine) -> PyBaseExceptionRef {
        self.ag.running_async.store(false);
        self.ag.inner.closed.store(true);
        self.state.store(AwaitableState::Closed);
        vm.new_runtime_error("async generator ignored GeneratorExit")
    }
    fn check_error(&self, exc: PyBaseExceptionRef, vm: &VirtualMachine) -> PyBaseExceptionRef {
        self.ag.running_async.store(false);
        self.ag.inner.closed.store(true);
        self.state.store(AwaitableState::Closed);
        if self.aclose
            && (exc.fast_isinstance(vm.ctx.exceptions.stop_async_iteration)
                || exc.fast_isinstance(vm.ctx.exceptions.generator_exit))
        {
            vm.new_stop_iteration(None)
        } else {
            exc
        }
    }
}

impl SelfIter for PyAsyncGenAThrow {}
impl IterNext for PyAsyncGenAThrow {
    fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> {
        PyIterReturn::from_pyresult(zelf.send(vm.ctx.none(), vm), vm)
    }
}

/// Awaitable wrapper for anext() builtin with default value.
/// When StopAsyncIteration is raised, it converts it to StopIteration(default).
#[pyclass(module = false, name = "anext_awaitable", traverse = "manual")]
#[derive(Debug)]
pub struct PyAnextAwaitable {
    wrapped: PyObjectRef,
    default_value: PyObjectRef,
    state: AtomicCell<AwaitableState>,
}

unsafe impl Traverse for PyAnextAwaitable {
    fn traverse(&self, tracer_fn: &mut TraverseFn<'_>) {
        self.wrapped.traverse(tracer_fn);
        self.default_value.traverse(tracer_fn);
    }
}

impl PyPayload for PyAnextAwaitable {
    #[inline]
    fn class(ctx: &Context) -> &'static Py<PyType> {
        ctx.types.anext_awaitable
    }
}

#[pyclass(with(IterNext, Iterable))]
impl PyAnextAwaitable {
    pub fn new(wrapped: PyObjectRef, default_value: PyObjectRef) -> Self {
        Self {
            wrapped,
            default_value,
            state: AtomicCell::new(AwaitableState::Init),
        }
    }

    #[pymethod(name = "__await__")]
    fn r#await(zelf: PyRef<Self>, _vm: &VirtualMachine) -> PyRef<Self> {
        zelf
    }

    fn check_closed(&self, vm: &VirtualMachine) -> PyResult<()> {
        if let AwaitableState::Closed = self.state.load() {
            return Err(vm.new_runtime_error("cannot reuse already awaited __anext__()/asend()"));
        }
        Ok(())
    }

    /// Get the awaitable iterator from wrapped object.
    // = anextawaitable_getiter.
    fn get_awaitable_iter(&self, vm: &VirtualMachine) -> PyResult {
        use crate::builtins::PyCoroutine;
        use crate::protocol::PyIter;

        let wrapped = &self.wrapped;

        // If wrapped is already an async_generator_asend, it's an iterator
        if wrapped.class().is(vm.ctx.types.async_generator_asend)
            || wrapped.class().is(vm.ctx.types.async_generator_athrow)
        {
            return Ok(wrapped.clone());
        }

        // _PyCoro_GetAwaitableIter equivalent
        let awaitable = if wrapped.class().is(vm.ctx.types.coroutine_type) {
            // Coroutine - get __await__ later
            wrapped.clone()
        } else {
            // Check for generator with CO_ITERABLE_COROUTINE flag
            if let Some(generator) = wrapped.downcast_ref::<PyGenerator>()
                && generator
                    .as_coro()
                    .frame()
                    .code
                    .flags
                    .contains(crate::bytecode::CodeFlags::ITERABLE_COROUTINE)
            {
                // Return the generator itself as the iterator
                return Ok(wrapped.clone());
            }
            // Try to get __await__ method
            if let Some(await_method) = vm.get_method(wrapped.clone(), identifier!(vm, __await__)) {
                await_method?.call((), vm)?
            } else {
                return Err(vm.new_type_error(format!(
                    "'{}' object can't be awaited",
                    wrapped.class().name()
                )));
            }
        };

        // If awaitable is a coroutine, get its __await__
        if awaitable.class().is(vm.ctx.types.coroutine_type) {
            let coro_await = vm.call_method(&awaitable, "__await__", ())?;
            // Check that __await__ returned an iterator
            if !PyIter::check(&coro_await) {
                return Err(vm.new_type_error("__await__ returned a non-iterable"));
            }
            return Ok(coro_await);
        }

        // Check the result is an iterator, not a coroutine
        if awaitable.downcast_ref::<PyCoroutine>().is_some() {
            return Err(vm.new_type_error("__await__() returned a coroutine"));
        }

        // Check that the result is an iterator
        if !PyIter::check(&awaitable) {
            return Err(vm.new_type_error(format!(
                "__await__() returned non-iterator of type '{}'",
                awaitable.class().name()
            )));
        }

        Ok(awaitable)
    }

    #[pymethod]
    fn send(&self, val: PyObjectRef, vm: &VirtualMachine) -> PyResult {
        self.check_closed(vm)?;
        self.state.store(AwaitableState::Iter);
        let awaitable = self.get_awaitable_iter(vm)?;
        let result = vm.call_method(&awaitable, "send", (val,));
        self.handle_result(result, vm)
    }

    #[pymethod]
    fn throw(
        &self,
        exc_type: PyObjectRef,
        exc_val: OptionalArg,
        exc_tb: OptionalArg,
        vm: &VirtualMachine,
    ) -> PyResult {
        self.check_closed(vm)?;
        warn_deprecated_throw_signature(&exc_val, &exc_tb, vm)?;
        self.state.store(AwaitableState::Iter);
        let awaitable = self.get_awaitable_iter(vm)?;
        let result = vm.call_method(
            &awaitable,
            "throw",
            (
                exc_type,
                exc_val.unwrap_or_none(vm),
                exc_tb.unwrap_or_none(vm),
            ),
        );
        self.handle_result(result, vm)
    }

    #[pymethod]
    fn close(&self, vm: &VirtualMachine) -> PyResult<()> {
        self.state.store(AwaitableState::Closed);
        if let Ok(awaitable) = self.get_awaitable_iter(vm) {
            let _ = vm.call_method(&awaitable, "close", ());
        }
        Ok(())
    }

    /// Convert StopAsyncIteration to StopIteration(default_value)
    fn handle_result(&self, result: PyResult, vm: &VirtualMachine) -> PyResult {
        match result {
            Ok(value) => Ok(value),
            Err(exc) if exc.fast_isinstance(vm.ctx.exceptions.stop_async_iteration) => {
                Err(vm.new_stop_iteration(Some(self.default_value.clone())))
            }
            Err(exc) => Err(exc),
        }
    }
}

impl SelfIter for PyAnextAwaitable {}
impl IterNext for PyAnextAwaitable {
    fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> {
        PyIterReturn::from_pyresult(zelf.send(vm.ctx.none(), vm), vm)
    }
}

/// _PyGen_Finalize for async generators
impl Destructor for PyAsyncGen {
    fn del(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<()> {
        // Generator is already closed, nothing to do
        if zelf.inner.closed.load() {
            return Ok(());
        }

        // Call the async generator finalizer hook if set.
        Self::call_finalizer(zelf, vm);

        Ok(())
    }
}

impl Drop for PyAsyncGen {
    fn drop(&mut self) {
        self.inner.frame().clear_generator();
    }
}

pub fn init(ctx: &'static Context) {
    PyAsyncGen::extend_class(ctx, ctx.types.async_generator);
    PyAsyncGenASend::extend_class(ctx, ctx.types.async_generator_asend);
    PyAsyncGenAThrow::extend_class(ctx, ctx.types.async_generator_athrow);
    PyAnextAwaitable::extend_class(ctx, ctx.types.anext_awaitable);
}