rustpython-vm 0.6.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
use crate::{
    AsObject, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, VirtualMachine,
    builtins::{PyCode, PyStrRef, PyTraceback, PyTupleRef},
    common::lock::PyMutex,
    exceptions::types::PyBaseException,
    frame::{ExecutionResult, FrameObject, FrameObjectRef, FrameOwner, InterpreterFrame},
    function::OptionalArg,
    object::{PyAtomicRef, Traverse, TraverseFn},
    protocol::PyIterReturn,
    vm::GenFrameLink,
};
use crossbeam_utils::atomic::AtomicCell;

impl ExecutionResult {
    /// Turn an ExecutionResult into a PyResult that would be returned from a generator or coroutine
    fn into_iter_return(self, vm: &VirtualMachine) -> PyIterReturn {
        match self {
            Self::Yield(value) => PyIterReturn::Return(value),
            Self::Return(value) => {
                let arg = if vm.is_none(&value) {
                    None
                } else {
                    Some(value)
                };
                PyIterReturn::StopIteration(arg)
            }
            Self::TailCall | Self::GenResume => {
                unreachable!("unfinished frame result in generator/coroutine")
            }
        }
    }
}

#[derive(Debug)]
pub struct Coro {
    /// Generator iframe, like `gi_iframe`. Cleared to `None` by take_ownership
    /// the same way `frame_obj` is stolen from the iframe.
    frame: PyAtomicRef<Option<FrameObject>>,
    /// `f_executable`; survives `_PyFrame_ClearExceptCode`.
    code: PyRef<PyCode>,
    pub closed: AtomicCell<bool>, // TODO: https://github.com/RustPython/RustPython/pull/3183#discussion_r720560652
    running: AtomicCell<bool>,
    // _weakreflist
    name: PyMutex<PyStrRef>,
    qualname: PyMutex<PyStrRef>,
    exception: PyAtomicRef<Option<PyBaseException>>, // exc_state
}

unsafe impl Traverse for Coro {
    fn traverse(&self, tracer_fn: &mut TraverseFn<'_>) {
        if let Some(frame) = self.frame.deref() {
            tracer_fn(frame.as_object());
        }
        self.code.traverse(tracer_fn);
        self.name.traverse(tracer_fn);
        self.qualname.traverse(tracer_fn);
        if let Some(exc) = self.exception.deref() {
            exc.traverse(tracer_fn);
        }
    }
}

/// An exclusive claim on a generator's frame, released when dropped.
///
/// Only the holder may look at the frame or resume it. Resuming decides from
/// the frame state whether the sent value goes on the value stack, so a state
/// read taken before the claim can be answered by a frame that another thread
/// then advances: resuming it leaves the stack short of what the code after
/// the yield pops.
struct RunningGuard<'a>(&'a Coro);

impl Drop for RunningGuard<'_> {
    fn drop(&mut self) {
        self.0.running.store(false);
    }
}

/// The `Coro` inside a builtin generator or coroutine object, if it is one.
#[inline]
pub(crate) fn as_builtin_coro(obj: &PyObject) -> Option<&Coro> {
    use crate::builtins::{PyCoroutine, PyGenerator};
    crate::match_class!(match obj {
        ref g @ PyGenerator => Some(g.as_coro()),
        ref c @ PyCoroutine => Some(c.as_coro()),
        _ => None,
    })
}

/// A generator or coroutine being resumed by the call trampoline instead of
/// by a nested `Coro::send`: its frame runs in the delegating frame's own
/// eval loop, so the work `send` does around a resume is split in two, with
/// the frame's whole run in between.
///
/// The halves must stay in step with `Coro::send` / `Coro::send_none`, which
/// do the same things around a recursive resume, in this order:
///
/// 1. take the running claim, then re-read `closed` under it;
/// 2. decide what to push as the value the `yield` produces;
/// 3. take `gi_exc_state` out of the generator;
/// 4. link the frame onto the thread's frame chain (`gen_frame_link`);
/// 5. **run the frame**;
/// 6. store the handled exception back into `gi_exc_state`;
/// 7. unlink the frame (`gen_frame_unlink`);
/// 8. retire the generator if the frame came to an end;
/// 9. release the claim and map the outcome (PEP 479).
///
/// Steps 1-4 are `flat_resume_enter`, steps 6-9 are `flat_resume_exit`.
pub(crate) struct FlatResume {
    /// The generator or coroutine being run: owner of the frame below, of
    /// the claim released on the way out, and of `gi_exc_state`.
    jen: PyObjectRef,
    /// The frame `jen` runs. Borrowed from `jen`, which outlives this record.
    frame: *const Py<FrameObject>,
    link: GenFrameLink,
}

/// Outcome of `flat_resume_enter`.
pub(crate) enum FlatEnter {
    /// The frame is linked and its claim held. Push `value` as the result of
    /// the `yield` it stopped at (or forward it down a `yield from` chain),
    /// run the frame, then hand `state` back to `flat_resume_exit`.
    Entered {
        state: FlatResume,
        /// `None` only for a generator that had not started, which has no
        /// `yield` to give a value to.
        value: Option<PyObjectRef>,
    },
    /// The generator was already exhausted; nothing was claimed or linked,
    /// and the resume yields `StopIteration(None)`.
    Exhausted,
}

impl FlatResume {
    /// The frame to run. Valid until `flat_resume_exit` consumes this record.
    pub(crate) fn iframe_ptr(&self) -> *mut InterpreterFrame {
        // SAFETY: `jen` holds the frame alive, and the claim taken in
        // `flat_resume_enter` makes this thread its only executor.
        unsafe { (*self.frame).iframe_mut() as *mut InterpreterFrame }
    }
}

/// Start a flattened resume of `jen` with `value` as the result of the
/// `yield` it is suspended at (`None` for a generator that has not started).
///
/// `jen` must be an exact builtin generator or coroutine that is neither
/// running nor closed — what `SEND`/`FOR_ITER` check before parking it.
#[inline]
pub(crate) fn flat_resume_enter(
    jen: PyObjectRef,
    value: PyObjectRef,
    vm: &VirtualMachine,
) -> PyResult<FlatEnter> {
    let coro = as_builtin_coro(&jen).expect("flat resume of a non-generator");
    if coro.closed.load() {
        return Ok(FlatEnter::Exhausted);
    }
    let _claim = coro.claim(&jen, vm)?;
    // The generator can have run to its end in the meantime.
    if coro.closed.load() {
        return Ok(FlatEnter::Exhausted);
    }
    let value = if coro.frame_opt().is_some_and(|f| f.lasti() > 0) {
        Some(value)
    } else if !vm.is_none(&value) {
        return Err(vm.new_type_error(format!(
            "can't send non-None value to a just-started {}",
            gen_name(&jen, vm),
        )));
    } else {
        None
    };
    // SAFETY: exclusive access guaranteed by the claim
    let gen_exc = unsafe { coro.exception.swap(None) };
    let frame_ref = coro.frame();
    let frame: *const Py<FrameObject> = &*frame_ref;
    let link = match vm.gen_frame_link(&frame_ref, gen_exc) {
        Ok(link) => link,
        Err(exc) => {
            // A resume that fails before the frame runs retires the
            // generator, the same as one whose frame raises: `Coro::send`
            // reaches `maybe_close` with the `Err` that `resume_gen_frame`
            // returned for exactly these two checks.
            coro.retire(&_claim);
            return Err(exc);
        }
    };
    // The claim outlives this scope; `flat_resume_exit` drops it.
    core::mem::forget(_claim);
    Ok(FlatEnter::Entered {
        state: FlatResume { jen, frame, link },
        value,
    })
}

/// Finish a flattened resume with what the frame produced, giving back what
/// `Coro::send` would have returned for the same run.
#[inline]
pub(crate) fn flat_resume_exit(
    state: FlatResume,
    result: PyResult<ExecutionResult>,
    vm: &VirtualMachine,
) -> PyResult<PyIterReturn> {
    let FlatResume { jen, frame, link } = state;
    let coro = as_builtin_coro(&jen).expect("flat resume of a non-generator");
    // SAFETY: exclusive access guaranteed by the claim taken on the way in.
    let _old = unsafe { coro.exception.swap(vm.current_exception()) };
    // SAFETY: `jen` still holds the frame alive.
    vm.gen_frame_unlink(unsafe { &*frame }, link);
    // Re-take the guard the enter half leaked, so the claim is released
    // here whatever the outcome.
    let claim = RunningGuard(coro);
    coro.maybe_close(&result, &claim);
    drop(claim);
    coro.finalize_send_result(result, &jen, vm)
}

fn gen_name(jen: &PyObject, vm: &VirtualMachine) -> &'static str {
    let typ = jen.class();
    if typ.is(vm.ctx.types.coroutine_type) {
        "coroutine"
    } else if typ.is(vm.ctx.types.async_generator) {
        "async generator"
    } else {
        "generator"
    }
}

impl Coro {
    pub fn new(frame: FrameObjectRef, name: PyStrRef, qualname: PyStrRef) -> Self {
        let code = frame.iframe().code().to_owned();
        frame.as_object().mark_cache_published();
        Self {
            frame: Some(frame).into(),
            code,
            closed: AtomicCell::new(false),
            running: AtomicCell::new(false),
            exception: PyAtomicRef::from(None),
            name: PyMutex::new(name),
            qualname: PyMutex::new(qualname),
        }
    }

    /// `_PyFrame_ClearExceptCode`. Steal the frame slot first, then
    /// clear locals only if this was the last reference.
    fn clear_except_code(&self) {
        let Some(frame) = (unsafe { self.frame.swap(None) }) else {
            return;
        };
        frame.clear_generator();
        if frame.as_object().strong_count() == 1 {
            frame.clear_locals_and_stack();
        } else {
            frame.iframe().owner.store(
                FrameOwner::FrameObject as i8,
                core::sync::atomic::Ordering::Release,
            );
        }
    }

    /// Retire the generator if the frame it just ran came to an end. The claim
    /// is still held, so a thread waiting for it cannot resume a frame that has
    /// already finished.
    fn maybe_close(&self, res: &PyResult<ExecutionResult>, _claim: &RunningGuard<'_>) {
        match res {
            Ok(ExecutionResult::Return(_)) | Err(_) => {
                self.closed.store(true);
                self.clear_except_code();
            }
            Ok(ExecutionResult::Yield(_)) => {}
            Ok(ExecutionResult::TailCall | ExecutionResult::GenResume) => {
                unreachable!("unfinished frame result in generator/coroutine")
            }
        }
    }

    /// Retire the generator without having run its frame: the resume failed
    /// before the frame started, which `Coro::send` treats the same as a
    /// frame that raised.
    fn retire(&self, _claim: &RunningGuard<'_>) {
        self.closed.store(true);
        self.clear_except_code();
    }

    /// Take the frame for this thread, or report that another thread holds it.
    ///
    /// What the resume depends on -- whether the generator is closed, and
    /// whether it has started -- has to be read from here onwards.
    fn claim(&self, jen: &PyObject, vm: &VirtualMachine) -> PyResult<RunningGuard<'_>> {
        if self.running.compare_exchange(false, true).is_err() {
            return Err(vm.new_value_error(format!("{} already executing", gen_name(jen, vm))));
        }
        Ok(RunningGuard(self))
    }

    fn run_claimed<F>(
        &self,
        _claim: &RunningGuard<'_>,
        vm: &VirtualMachine,
        func: F,
    ) -> PyResult<ExecutionResult>
    where
        F: FnOnce(&Py<FrameObject>) -> PyResult<ExecutionResult>,
    {
        // SAFETY: the claim guarantees exclusive access
        let gen_exc = unsafe { self.exception.swap(None) };
        let exception_ptr = &self.exception as *const PyAtomicRef<Option<PyBaseException>>;

        let frame = self.frame();
        vm.resume_gen_frame(&frame, gen_exc, |f| {
            let result = func(f);
            // SAFETY: exclusive access guaranteed by the claim
            let _old = unsafe { (*exception_ptr).swap(vm.current_exception()) };
            result
        })
    }

    fn finalize_send_result(
        &self,
        result: PyResult<ExecutionResult>,
        jen: &PyObject,
        vm: &VirtualMachine,
    ) -> PyResult<PyIterReturn> {
        match result {
            Ok(exec_res) => Ok(exec_res.into_iter_return(vm)),
            Err(e) => {
                if e.fast_isinstance(vm.ctx.exceptions.stop_iteration) {
                    let err =
                        vm.new_runtime_error(format!("{} raised StopIteration", gen_name(jen, vm)));
                    // PEP 479: chain __context__ as well as __cause__ to the
                    // original StopIteration.
                    err.set_context(Some(e.clone()));
                    err.set_cause(Some(e));
                    Err(err)
                } else if jen.class().is(vm.ctx.types.async_generator)
                    && e.fast_isinstance(vm.ctx.exceptions.stop_async_iteration)
                {
                    let err = vm.new_runtime_error("async generator raised StopAsyncIteration");
                    err.set_context(Some(e.clone()));
                    err.set_cause(Some(e));
                    Err(err)
                } else {
                    Err(e)
                }
            }
        }
    }

    pub(crate) fn send_none(&self, jen: &PyObject, vm: &VirtualMachine) -> PyResult<PyIterReturn> {
        if self.closed.load() {
            return Self::send_when_closed(jen, vm);
        }
        let claim = self.claim(jen, vm)?;
        // The generator can have run to its end in the meantime.
        if self.closed.load() {
            return Self::send_when_closed(jen, vm);
        }
        let value = if self.frame_opt().is_some_and(|f| f.lasti() > 0) {
            Some(vm.ctx.none())
        } else {
            None
        };
        let result = self.run_claimed(&claim, vm, |f| f.resume(value, vm));
        self.maybe_close(&result, &claim);
        drop(claim);
        self.finalize_send_result(result, jen, vm)
    }

    fn send_when_closed(jen: &PyObject, vm: &VirtualMachine) -> PyResult<PyIterReturn> {
        if jen.class().is(vm.ctx.types.coroutine_type) {
            Err(vm.new_runtime_error("cannot reuse already awaited coroutine"))
        } else {
            Ok(PyIterReturn::StopIteration(None))
        }
    }

    fn throw_when_closed(
        jen: &PyObject,
        exc_type: PyObjectRef,
        exc_val: PyObjectRef,
        exc_tb: PyObjectRef,
        vm: &VirtualMachine,
    ) -> PyResult<PyIterReturn> {
        if jen.class().is(vm.ctx.types.coroutine_type) {
            Err(vm.new_runtime_error("cannot reuse already awaited coroutine"))
        } else {
            Err(vm.normalize_exception(exc_type, exc_val, exc_tb)?)
        }
    }

    pub fn send(
        &self,
        jen: &PyObject,
        value: PyObjectRef,
        vm: &VirtualMachine,
    ) -> PyResult<PyIterReturn> {
        if self.closed.load() {
            return Self::send_when_closed(jen, vm);
        }
        let claim = self.claim(jen, vm)?;
        // The generator can have run to its end in the meantime.
        if self.closed.load() {
            return Self::send_when_closed(jen, vm);
        }
        let value = if self.frame_opt().is_some_and(|f| f.lasti() > 0) {
            Some(value)
        } else if !vm.is_none(&value) {
            return Err(vm.new_type_error(format!(
                "can't send non-None value to a just-started {}",
                gen_name(jen, vm),
            )));
        } else {
            None
        };
        let result = self.run_claimed(&claim, vm, |f| f.resume(value, vm));
        self.maybe_close(&result, &claim);
        drop(claim);
        self.finalize_send_result(result, jen, vm)
    }

    pub fn throw(
        &self,
        jen: &PyObject,
        exc_type: PyObjectRef,
        exc_val: PyObjectRef,
        exc_tb: PyObjectRef,
        vm: &VirtualMachine,
    ) -> PyResult<PyIterReturn> {
        // Validate throw arguments (_gen_throw)
        if exc_type.fast_isinstance(vm.ctx.exceptions.base_exception_type) && !vm.is_none(&exc_val)
        {
            return Err(vm.new_type_error("instance exception may not have a separate value"));
        }
        if !vm.is_none(&exc_tb) && !exc_tb.fast_isinstance(vm.ctx.types.traceback_type) {
            return Err(vm.new_type_error("throw() third argument must be a traceback object"));
        }
        if self.closed.load() {
            return Self::throw_when_closed(jen, exc_type, exc_val, exc_tb, vm);
        }
        // Validate exception type before entering generator context.
        // Invalid types propagate to caller without closing the generator.
        crate::exceptions::ExceptionCtor::try_from_object(vm, exc_type.clone())?;
        let claim = self.claim(jen, vm)?;
        // The generator can have run to its end in the meantime. Normalizing
        // runs the exception's constructor, so let the claim go first.
        if self.closed.load() {
            drop(claim);
            return Self::throw_when_closed(jen, exc_type, exc_val, exc_tb, vm);
        }
        let result = self.run_claimed(&claim, vm, |f| f.gen_throw(vm, exc_type, exc_val, exc_tb));
        self.maybe_close(&result, &claim);
        drop(claim);
        self.finalize_send_result(result, jen, vm)
    }

    pub fn close(&self, jen: &PyObject, vm: &VirtualMachine) -> PyResult<PyObjectRef> {
        if self.closed.load() {
            return Ok(vm.ctx.none());
        }
        let claim = self.claim(jen, vm)?;
        // The generator can have run to its end in the meantime.
        if self.closed.load() {
            return Ok(vm.ctx.none());
        }
        // FRAME_CREATED: mark finished and clear the iframe.
        if self.frame_opt().is_none_or(|f| f.lasti() == 0) {
            self.closed.store(true);
            self.clear_except_code();
            return Ok(vm.ctx.none());
        }
        let result = self.run_claimed(&claim, vm, |f| {
            f.gen_throw(
                vm,
                vm.ctx.exceptions.generator_exit.to_owned().into(),
                vm.ctx.none(),
                vm.ctx.none(),
            )
        });
        if !matches!(&result, Ok(ExecutionResult::Yield(_))) {
            self.closed.store(true);
            self.clear_except_code();
        }
        drop(claim);
        match result {
            Ok(ExecutionResult::Yield(_)) => {
                Err(vm.new_runtime_error(format!("{} ignored GeneratorExit", gen_name(jen, vm))))
            }
            Err(e) if !is_gen_exit(&e, vm) => Err(e),
            Ok(ExecutionResult::Return(value)) => Ok(value),
            _ => Ok(vm.ctx.none()),
        }
    }

    /// Whether the frame has run at all, i.e. is stopped at a `yield` rather
    /// than at its start.
    pub(crate) fn started(&self) -> bool {
        self.frame_opt().is_some_and(|f| f.lasti() > 0)
    }

    pub fn suspended(&self) -> bool {
        !self.closed.load()
            && !self.running.load()
            && self.frame_opt().is_some_and(|f| f.lasti() > 0)
    }

    pub fn running(&self) -> bool {
        self.running.load()
    }

    pub fn closed(&self) -> bool {
        self.closed.load()
    }

    /// The frame this generator runs, without the reference count a clone of
    /// it would cost.
    pub(crate) fn frame_ref(&self) -> &Py<FrameObject> {
        self.frame.deref().expect("generator frame")
    }

    pub fn frame(&self) -> FrameObjectRef {
        self.frame_opt().expect("generator frame")
    }

    pub fn frame_opt(&self) -> Option<FrameObjectRef> {
        self.frame.load_owned()
    }

    pub fn code(&self) -> PyRef<PyCode> {
        self.code.clone()
    }

    pub fn name(&self) -> PyStrRef {
        self.name.lock().clone()
    }

    pub fn set_name(&self, name: PyStrRef) {
        *self.name.lock() = name;
    }

    pub fn qualname(&self) -> PyStrRef {
        self.qualname.lock().clone()
    }

    pub fn set_qualname(&self, qualname: PyStrRef) {
        *self.qualname.lock() = qualname;
    }

    pub fn repr(&self, jen: &PyObject, id: usize, vm: &VirtualMachine) -> String {
        let qualname = self.qualname();
        format!(
            "<{} object {} at {:#x}>",
            gen_name(jen, vm),
            qualname.as_wtf8(),
            id
        )
    }
}

pub(crate) fn is_gen_exit(exc: &Py<PyBaseException>, vm: &VirtualMachine) -> bool {
    exc.fast_isinstance(vm.ctx.exceptions.generator_exit)
}

fn iframe_origin_lineno(frame: &InterpreterFrame) -> usize {
    // `prev_line` is only updated on the tracing path, so origin capture
    // has to derive the line from lasti the same way `f_lineno` does.
    let lasti = frame.get_lasti();
    if lasti == 0 {
        return frame.code().first_line_number.map_or(1, |n| n.get());
    }
    frame.code().locations[lasti as usize - 1].0.line.get()
}

/// Capture the current call stack as a coroutine `cr_origin` tuple.
///
/// Each entry is `(filename, lineno, funcname)`, innermost first. Depth 0
/// disables tracking and returns `None`.
pub(crate) fn compute_cr_origin(vm: &VirtualMachine) -> Option<PyTupleRef> {
    let depth = crate::vm::thread::COROUTINE_ORIGIN_TRACKING_DEPTH.get();
    if depth == 0 {
        return None;
    }
    let mut items = Vec::new();
    let mut iframe = crate::frame::current_thread_iframe();
    while !iframe.is_null() && items.len() < depth as usize {
        // SAFETY: TLS iframe chain entries stay alive while this thread runs.
        let frame = unsafe { &*iframe };
        let code = frame.code();
        items.push(
            vm.ctx
                .new_tuple(vec![
                    code.source_path().to_owned().into(),
                    vm.ctx.new_int(iframe_origin_lineno(frame)).into(),
                    code.obj_name.to_owned().into(),
                ])
                .into(),
        );
        iframe = frame.previous();
    }
    if items.is_empty() {
        None
    } else {
        Some(vm.ctx.new_tuple(items))
    }
}

/// Get an awaitable iterator from an object.
///
/// Returns the object itself if it's a coroutine or iterable coroutine (generator with
/// CO_ITERABLE_COROUTINE flag). Otherwise calls `__await__()` and validates the result.
pub(crate) fn get_awaitable_iter(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult {
    use crate::builtins::{PyCoroutine, PyGenerator};
    use crate::protocol::PyIter;

    if obj.downcastable::<PyCoroutine>()
        || obj.downcast_ref::<PyGenerator>().is_some_and(|g| {
            g.as_coro()
                .code()
                .flags
                .contains(crate::bytecode::CodeFlags::ITERABLE_COROUTINE)
        })
    {
        return Ok(obj);
    }

    if let Some(await_method) = vm.get_method(obj.clone(), identifier!(vm, __await__)) {
        let result = await_method?.call((), vm)?;
        // __await__() must NOT return a coroutine (PEP 492)
        if result.downcastable::<PyCoroutine>()
            || result.downcast_ref::<PyGenerator>().is_some_and(|g| {
                g.as_coro()
                    .code()
                    .flags
                    .contains(crate::bytecode::CodeFlags::ITERABLE_COROUTINE)
            })
        {
            return Err(vm.new_type_error("__await__() returned a coroutine"));
        }
        if !PyIter::check(&result) {
            return Err(vm.new_type_error(format!(
                "__await__() returned non-iterator of type '{}'",
                result.class().name()
            )));
        }
        return Ok(result);
    }

    Err(vm.new_type_error(format!("'{}' object can't be awaited", obj.class().name())))
}

pub(crate) fn unraisable_while_closing(
    jen: &PyObject,
    coro: &Coro,
    e: crate::builtins::PyBaseExceptionRef,
    vm: &VirtualMachine,
) {
    // Explicit close() leaves the traceback to the caller frame.
    // Finalize has no caller frame, so attach the generator site here.
    if e.traceback().is_none()
        && let Some(frame) = coro.frame_opt()
    {
        let lasti = frame.lasti().saturating_mul(2) as i32;
        let lineno = rustpython_compiler_core::OneIndexed::new(frame.lineno().max(1) as usize)
            .unwrap_or(rustpython_compiler_core::OneIndexed::MIN);
        let tb = PyTraceback::new(None, frame, lasti, lineno);
        e.set_traceback(Some(tb.into_ref(&vm.ctx)));
    }
    let msg = jen
        .repr(vm)
        .ok()
        .map(|r| format!("Exception ignored while closing generator {r}"));
    vm.run_unraisable(e, msg, vm.ctx.none());
}

/// Emit DeprecationWarning for the deprecated 3-argument throw() signature.
pub(crate) fn warn_deprecated_throw_signature(
    exc_val: &OptionalArg,
    exc_tb: &OptionalArg,
    vm: &VirtualMachine,
) -> PyResult<()> {
    if exc_val.is_present() || exc_tb.is_present() {
        crate::warn::warn(
            vm.ctx
                .new_str(
                    "the (type, val, tb) signature of throw() is deprecated, \
                 use throw(val) instead",
                )
                .into(),
            Some(vm.ctx.exceptions.deprecation_warning.to_owned()),
            1,
            None,
            vm,
        )?;
    }
    Ok(())
}