pythonrs 0.1.15

Python as a fusevm frontend: lexer, parser, and compiler to fusevm::Chunk on a PyHost heap — the first compiled standalone Python runtime
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
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
//! Native `asyncio` runtime for pythonrs: a single-thread, cooperative event
//! loop (ready-queue + timer-heap) that drives `async def` coroutines, plus the
//! Future/Task machinery and the `asyncio.*` module surface.
//!
//! Design (faithful to CPython's asyncio, adapted to the fusevm generator infra):
//!   - An `async def` call returns a *coroutine object* — a stackful `corosensei`
//!     coroutine that suspends at each `await` (see `host::make_coroutine`). The
//!     body does NOT run until the loop drives it.
//!   - `await x` (see [`await_value`]) drives `x`: an `asyncio.Future`/`Task`
//!     suspends the running coroutine (yielding the future up to its Task) until
//!     the future settles; a coroutine or a `__await__` iterator is delegated
//!     into (yield-from), forwarding whatever *it* yields (ultimately a Future)
//!     up to the loop. Futures are the only leaves that reach the loop.
//!   - A `Task` wraps a coroutine and steps it: `gen_resume` runs the body to the
//!     next awaited Future; the Task registers a done-callback that re-steps it
//!     when the Future settles. When the body returns/raises, the Task's own
//!     Future is fulfilled/failed.
//!   - The loop's virtual clock jumps to the earliest pending timer when the
//!     ready-queue empties, so `asyncio.sleep` ordering matches CPython without
//!     real waiting.
//!
//! Everything is thread-local (matching the thread-local `PyHost`); no locks, no
//! real threads — `asyncio` semantics are single-threaded by construction.

use crate::host::{self, with_host, PyObj};
use fusevm::Value;
use std::cell::RefCell;
use std::collections::VecDeque;
use std::rc::Rc;

// ── future / task cells ──────────────────────────────────────────────────────

/// One `asyncio.Future` (or `Task`, which is a Future that also drives a
/// coroutine). Indexed by `PyObj::Future.id`.
struct FutureCell {
    done: bool,
    cancelled: bool,
    /// The fulfilled result (`set_result`), `Undef` until done.
    result: Value,
    /// The failing exception object (`set_exception` / a coroutine raised).
    exc: Option<Value>,
    /// User `add_done_callback` callables (invoked with the future).
    py_callbacks: Vec<Value>,
    /// Native continuations (Task wakeups, gather joins) run on settlement.
    native_callbacks: Vec<Box<dyn FnOnce()>>,
    /// A Task's driven coroutine object (`None` for a plain Future).
    coro: Option<Value>,
    is_task: bool,
    /// Whether a Task's next step has been scheduled (guards double-step).
    step_scheduled: bool,
    /// A pending `Task.cancel()` request: the next `task_step` throws
    /// `CancelledError` into the coroutine at its current `await` point.
    must_cancel: bool,
    name: String,
    /// The one object standing for this cell, so `current_task() is task`
    /// and a Task is one key in a set (`TaskGroup._tasks`).
    obj: Value,
    /// The CPython context a Task's steps run in, copied when it was
    /// created (dropped once it settles).
    #[cfg(feature = "stdlib-ffi")]
    context: Option<crate::ffi::TaskContext>,
}

// ── event loop ───────────────────────────────────────────────────────────────

/// A queued unit of work: a native continuation or a scheduled Python callback.
enum Callback {
    Native(Box<dyn FnOnce()>),
    Py { func: Value, args: Vec<Value> },
}

/// A `call_later`/`call_at` timer. Fires when the virtual clock reaches `when`;
/// ties broken by insertion `seq` (FIFO), matching CPython's timer heap.
struct Timer {
    when: f64,
    seq: u64,
    cancelled: bool,
    cb: Callback,
}

/// An `asyncio` synchronization primitive, backed by `PyObj::AsyncObj.id`.
enum AsyncObj {
    /// A one-shot flag: `wait()` blocks until `set()`; `clear()` resets it.
    Event {
        flag: bool,
        waiters: Vec<u32>, // future ids to complete on `set()`
    },
    /// A mutual-exclusion lock: `acquire()` blocks while held; `release()` hands
    /// off to the next waiter (staying locked) or unlocks.
    Lock {
        locked: bool,
        waiters: VecDeque<u32>, // future ids waiting to acquire
    },
    /// A FIFO queue: `get()` blocks while empty; bounded `put()` (a non-zero
    /// `maxsize`) blocks while the queue is full, resuming when a `get()` frees a
    /// slot. `maxsize == 0` is unbounded.
    Queue {
        items: VecDeque<Value>,
        maxsize: usize, // 0 = unbounded
        getters: VecDeque<u32>,
        /// Blocked `put()`s awaiting a free slot: `(future id, item)`.
        putters: VecDeque<(u32, Value)>,
    },
}

#[derive(Default)]
struct EventLoop {
    futures: Vec<FutureCell>,
    async_objs: Vec<AsyncObj>,
    ready: VecDeque<Callback>,
    timers: Vec<Timer>,
    time: f64,
    seq: u64,
    running: bool,
    /// The Task whose coroutine is being stepped (`asyncio.current_task()`).
    current: Option<u32>,
}

thread_local! {
    static LOOP: RefCell<EventLoop> = RefCell::new(EventLoop::default());
}

fn with_loop<R>(f: impl FnOnce(&mut EventLoop) -> R) -> R {
    LOOP.with(|l| f(&mut l.borrow_mut()))
}

/// Reset the async runtime (called from `host::reset_host`).
pub fn reset() {
    with_loop(|l| *l = EventLoop::default());
}

// ── future primitives ────────────────────────────────────────────────────────

fn new_cell(is_task: bool, coro: Option<Value>, name: String) -> Value {
    let id = with_loop(|l| {
        let id = l.futures.len() as u32;
        l.futures.push(FutureCell {
            done: false,
            cancelled: false,
            result: Value::Undef,
            exc: None,
            py_callbacks: Vec::new(),
            native_callbacks: Vec::new(),
            coro,
            is_task,
            step_scheduled: false,
            must_cancel: false,
            name,
            obj: Value::Undef,
            #[cfg(feature = "stdlib-ffi")]
            context: if is_task {
                crate::ffi::TaskContext::copy_current()
            } else {
                None
            },
        });
        id
    });
    let obj = with_host(|h| h.alloc(PyObj::Future { id }));
    with_loop(|l| l.futures[id as usize].obj = obj.clone());
    obj
}

/// A fresh pending `asyncio.Future`.
pub fn new_future() -> Value {
    new_cell(false, None, "Future".to_string())
}

/// The object standing for future cell `id`.
fn future_obj(id: u32) -> Value {
    with_loop(|l| l.futures[id as usize].obj.clone())
}

fn future_id(v: &Value) -> Option<u32> {
    match with_host(|h| h.get(v).cloned()) {
        Some(PyObj::Future { id }) => Some(id),
        _ => None,
    }
}

/// Whether `v` is an `asyncio` Future or Task.
pub fn is_future(v: &Value) -> bool {
    future_id(v).is_some()
}

fn future_done(id: u32) -> bool {
    with_loop(|l| l.futures[id as usize].done)
}

fn future_coro(id: u32) -> Option<Value> {
    with_loop(|l| l.futures[id as usize].coro.clone())
}

/// The exception a settled future failed with (`None` if it fulfilled cleanly).
fn future_exc(id: u32) -> Option<Value> {
    with_loop(|l| l.futures[id as usize].exc.clone())
}

fn future_result(id: u32) -> Value {
    with_loop(|l| l.futures[id as usize].result.clone())
}

/// Settle a future (fulfill or fail) and schedule its done-callbacks. A second
/// settlement is ignored (a Task whose coroutine ends after cancellation, etc.).
fn settle(id: u32, result: Value, exc: Option<Value>, cancelled: bool) -> bool {
    let already = with_loop(|l| l.futures[id as usize].done);
    if already {
        return false;
    }
    let (pys, natives) = with_loop(|l| {
        let f = &mut l.futures[id as usize];
        f.done = true;
        f.result = result;
        f.exc = exc;
        f.cancelled = cancelled;
        #[cfg(feature = "stdlib-ffi")]
        {
            f.context = None;
        }
        (
            std::mem::take(&mut f.py_callbacks),
            std::mem::take(&mut f.native_callbacks),
        )
    });
    // Native continuations first (Task wakeups) then user callbacks, each via
    // call_soon so they run on a later loop turn (CPython schedules them all).
    for n in natives {
        call_soon_native(n);
    }
    let fut = future_obj(id);
    for cb in pys {
        call_soon_py(cb, vec![fut.clone()]);
    }
    true
}

/// `future.set_result(v)`.
pub fn set_result(fut: &Value, v: Value) -> Result<Value, String> {
    let id = future_id(fut).ok_or_else(|| host::type_error("set_result on non-future"))?;
    if future_done(id) {
        return Err("InvalidStateError: invalid state".to_string());
    }
    settle(id, v, None, false);
    Ok(Value::Undef)
}

/// `future.set_exception(exc)`.
pub fn set_exception(fut: &Value, exc: Value) -> Result<Value, String> {
    let id = future_id(fut).ok_or_else(|| host::type_error("set_exception on non-future"))?;
    if future_done(id) {
        return Err("InvalidStateError: invalid state".to_string());
    }
    settle(id, Value::Undef, Some(exc), false);
    Ok(Value::Undef)
}

/// Fail a future without raising if it is already settled (used by gather/join).
fn fail_quietly(id: u32, exc: Value) {
    settle(id, Value::Undef, Some(exc), false);
}

/// Register a native continuation, firing immediately (via call_soon) if the
/// future is already settled.
fn add_done_native(id: u32, f: Box<dyn FnOnce()>) {
    if future_done(id) {
        call_soon_native(f);
    } else {
        with_loop(|l| l.futures[id as usize].native_callbacks.push(f));
    }
}

// ── event-loop scheduling ────────────────────────────────────────────────────

fn call_soon_native(f: Box<dyn FnOnce()>) {
    with_loop(|l| l.ready.push_back(Callback::Native(f)));
}

fn call_soon_py(func: Value, args: Vec<Value>) {
    with_loop(|l| l.ready.push_back(Callback::Py { func, args }));
}

fn call_later(delay: f64, cb: Callback) {
    with_loop(|l| {
        let when = l.time + delay.max(0.0);
        let seq = l.seq;
        l.seq += 1;
        l.timers.push(Timer {
            when,
            seq,
            cancelled: false,
            cb,
        });
    });
}

fn run_callback(cb: Callback) -> Result<(), String> {
    match cb {
        Callback::Native(f) => {
            f();
            Ok(())
        }
        Callback::Py { func, args } => host::invoke(&func, args, vec![]).map(|_| ()),
    }
}

/// One turn of the loop: advance the virtual clock to the earliest due timer if
/// nothing is immediately ready, move due timers into the ready-queue in
/// `(when, seq)` order, then run a snapshot of the ready callbacks.
fn run_once() -> Result<(), String> {
    // If nothing is ready, jump the clock to the next timer deadline.
    let jump = with_loop(|l| {
        if !l.ready.is_empty() {
            return None;
        }
        l.timers
            .iter()
            .filter(|t| !t.cancelled)
            .map(|t| t.when)
            .fold(None, |acc: Option<f64>, w| {
                Some(acc.map_or(w, |a| a.min(w)))
            })
    });
    if let Some(w) = jump {
        with_loop(|l| l.time = l.time.max(w));
    }
    // Move all due timers into ready (ordered by when, then seq).
    let due: Vec<Callback> = with_loop(|l| {
        let now = l.time;
        // Partition: keep future/cancelled timers, collect due ones.
        let mut due: Vec<Timer> = Vec::new();
        let mut kept: Vec<Timer> = Vec::new();
        for t in l.timers.drain(..) {
            if !t.cancelled && t.when <= now {
                due.push(t);
            } else {
                kept.push(t);
            }
        }
        l.timers = kept;
        due.sort_by(|a, b| {
            (a.when, a.seq)
                .partial_cmp(&(b.when, b.seq))
                .unwrap_or(std::cmp::Ordering::Equal)
        });
        due.into_iter().map(|t| t.cb).collect()
    });
    for cb in due {
        with_loop(|l| l.ready.push_back(cb));
    }
    // Run a snapshot of ready callbacks (new call_soons go to the next turn).
    let ntodo = with_loop(|l| l.ready.len());
    for _ in 0..ntodo {
        let cb = with_loop(|l| l.ready.pop_front());
        if let Some(cb) = cb {
            run_callback(cb)?;
        }
    }
    Ok(())
}

/// Whether the loop still has work (ready callbacks or live timers).
fn has_work() -> bool {
    with_loop(|l| !l.ready.is_empty() || l.timers.iter().any(|t| !t.cancelled))
}

/// Drive the loop until `fut` completes, then return its result (or raise its
/// exception). This is `loop.run_until_complete`.
pub fn run_until_complete(aw: Value) -> Result<Value, String> {
    if with_loop(|l| l.running) {
        return Err("RuntimeError: This event loop is already running".to_string());
    }
    let fut = ensure_future(aw)?;
    let id = future_id(&fut).ok_or_else(|| host::type_error("run_until_complete: not a future"))?;
    with_loop(|l| l.running = true);
    let result = loop {
        if future_done(id) {
            break Ok(());
        }
        if !has_work() {
            break Err("RuntimeError: Event loop stopped before Future completed.".to_string());
        }
        if let Err(e) = run_once() {
            with_loop(|l| l.running = false);
            return Err(e);
        }
    };
    with_loop(|l| l.running = false);
    result?;
    // Fulfilled → return result; failed → re-raise the exception at the caller.
    if let Some(exc) = future_exc(id) {
        return Err(host::raise_value(&exc).unwrap_or_else(|e| e));
    }
    Ok(future_result(id))
}

// ── task creation / stepping ─────────────────────────────────────────────────

/// Wrap a coroutine in a Task and schedule its first step; return the Task.
pub fn create_task(coro: Value, name: Option<String>) -> Result<Value, String> {
    if !host::is_coroutine(&coro) {
        return Err(host::type_error("a coroutine was expected"));
    }
    let name = name.unwrap_or_else(|| "Task".to_string());
    let task = new_cell(true, Some(coro), name);
    schedule_step(task.clone());
    Ok(task)
}

/// Coerce an awaitable to a Future: a coroutine becomes a Task; a Future passes
/// through; anything else is an error.
pub fn ensure_future(aw: Value) -> Result<Value, String> {
    if is_future(&aw) {
        Ok(aw)
    } else if host::is_coroutine(&aw) {
        create_task(aw, None)
    } else {
        Err(host::type_error(&format!(
            "An asyncio.Future, a coroutine or an awaitable is required (got {})",
            with_host(|h| h.type_name(&aw))
        )))
    }
}

fn schedule_step(task: Value) {
    let id = match future_id(&task) {
        Some(id) => id,
        None => return,
    };
    let already = with_loop(|l| l.futures[id as usize].step_scheduled);
    if already {
        return;
    }
    with_loop(|l| l.futures[id as usize].step_scheduled = true);
    call_soon_native(Box::new(move || task_step(task)));
}

/// Request cancellation of a Future/Task (`Future.cancel()` / `Task.cancel()`).
/// Returns `False` if it was already done. A plain Future is settled as cancelled
/// immediately; a Task instead injects `CancelledError` into its coroutine at the
/// next step (so `try/except CancelledError` inside the task runs).
fn cancel_future(id: u32) -> bool {
    if future_done(id) {
        return false;
    }
    let is_task = with_loop(|l| l.futures[id as usize].is_task);
    if is_task {
        with_loop(|l| l.futures[id as usize].must_cancel = true);
        // Schedule a step now; whatever inner Future the coroutine is suspended on
        // is simply abandoned (its later settlement no-ops on the done Task).
        let task = future_obj(id);
        schedule_step(task);
    } else {
        settle(id, Value::Undef, Some(make_cancelled_error()), true);
    }
    true
}

/// A fresh `asyncio.CancelledError` exception object.
fn make_cancelled_error() -> Value {
    with_host(|h| {
        h.alloc(PyObj::Exception {
            class: "CancelledError".into(),
            args: vec![],
        })
    })
}

/// Whether an abort string / exception object denotes a `CancelledError`.
fn is_cancelled_exc(exc: &Value) -> bool {
    matches!(
        with_host(|h| h.get(exc).cloned()),
        Some(PyObj::Exception { class, .. }) if class == "CancelledError"
    )
}

/// Resume a Task's coroutine to its next awaited Future (or to completion). A
/// pending `must_cancel` throws `CancelledError` into the coroutine instead of
/// resuming it normally, so the body's `try/except CancelledError` can run.
fn task_step(task: Value) {
    let id = match future_id(&task) {
        Some(id) => id,
        None => return,
    };
    with_loop(|l| l.futures[id as usize].step_scheduled = false);
    if future_done(id) {
        return;
    }
    let coro = match future_coro(id) {
        Some(c) => c,
        None => return,
    };
    let must_cancel = with_loop(|l| std::mem::take(&mut l.futures[id as usize].must_cancel));
    let prev = with_loop(|l| l.current.replace(id));
    let step = || {
        if must_cancel {
            host::gen_throw(&coro, make_cancelled_error())
        } else {
            host::gen_resume(&coro, Value::Undef)
        }
    };
    // `self._context.run(self.__step)`. The context is taken out of the cell
    // for the step, which may settle the Task, and put back unless it did.
    #[cfg(feature = "stdlib-ffi")]
    let stepped = match with_loop(|l| l.futures[id as usize].context.take()) {
        Some(ctx) => {
            let stepped = ctx.run(step);
            with_loop(|l| {
                let f = &mut l.futures[id as usize];
                if !f.done {
                    f.context = Some(ctx);
                }
            });
            stepped
        }
        None => step(),
    };
    #[cfg(not(feature = "stdlib-ffi"))]
    let stepped = step();
    with_loop(|l| l.current = prev);
    match stepped {
        Ok(Some(awaited)) => {
            // The coroutine yielded a Future it is waiting on. Re-step this Task
            // when that Future settles.
            match future_id(&awaited) {
                Some(aid) => {
                    let task2 = task.clone();
                    add_done_native(aid, Box::new(move || schedule_step(task2)));
                }
                None => {
                    // A coroutine yielded a non-Future to the loop (e.g. a bare
                    // `yield` in an async context) — asyncio rejects this.
                    let e = with_host(|h| {
                        let msg = h.new_str("Task got bad yield: awaited a non-future".to_string());
                        h.alloc(PyObj::Exception {
                            class: "RuntimeError".into(),
                            args: vec![msg],
                        })
                    });
                    fail_quietly(id, e);
                }
            }
        }
        Ok(None) => {
            let rv = host::coro_return_value(&coro);
            settle(id, rv, None, false);
        }
        Err(e) => {
            let exc = take_pending_exc(&e);
            // A `CancelledError` propagating out of the coroutine settles the Task
            // as *cancelled* (so `task.cancelled()` is True and awaiting it raises
            // `CancelledError`); any other exception is a normal failure.
            if is_cancelled_exc(&exc) {
                settle(id, Value::Undef, Some(exc), true);
            } else {
                fail_quietly(id, exc);
            }
        }
    }
}

/// Pull the in-flight exception object off the host (set by `raise`), or
/// synthesize one from the abort string if none is live.
fn take_pending_exc(err: &str) -> Value {
    with_host(|h| {
        if let Some(e) = h.exc.take() {
            e
        } else {
            // Split "Class: message" into an exception object.
            let (class, msg) = match err.split_once(": ") {
                Some((c, m)) => (c.to_string(), m.to_string()),
                None => (err.to_string(), String::new()),
            };
            let args = if msg.is_empty() {
                vec![]
            } else {
                vec![h.new_str(msg)]
            };
            let class = if crate::builtins::is_exception_class(&class) {
                class
            } else {
                "Exception".to_string()
            };
            h.alloc(PyObj::Exception { class, args })
        }
    })
}

// ── await ────────────────────────────────────────────────────────────────────

/// The `AWAIT` op body (runs inside an async coroutine). Drive `x` to its
/// result, suspending the coroutine (up to the driving Task) as needed.
pub fn await_value(x: Value) -> Result<Value, String> {
    // An asyncio Future/Task: suspend until it settles, then return / raise.
    if let Some(id) = future_id(&x) {
        loop {
            if future_done(id) {
                if let Some(exc) = future_exc(id) {
                    return Err(host::raise_value(&exc).unwrap_or_else(|e| e));
                }
                return Ok(future_result(id));
            }
            // Yield the future up to the Task driving this coroutine; the Task
            // re-steps us (send value ignored) once the future is settled. Mark
            // it as an `await` suspension so an enclosing async generator's
            // `__anext__` driver tells it apart from a produced `yield` value.
            host::gen_yield_awaiting(x.clone())?;
        }
    }
    // An async generator's `__anext__` returns the generator itself; awaiting it
    // drives one step: forward each `await` suspension to the loop, and return
    // the next produced value (or raise `StopAsyncIteration` when exhausted).
    if host::is_async_generator(&x) {
        return drive_async_gen(&x);
    }
    // A coroutine: delegate into it (yield-from), forwarding its yields up.
    if host::is_coroutine(&x) {
        return drive_delegate(&x);
    }
    // A custom awaitable: `__await__()` returns an iterator/generator to drive.
    let has_await = with_host(|h| match h.get(&x) {
        Some(PyObj::Instance(i)) => h.class_lookup(&i.class, "__await__").is_some(),
        _ => false,
    });
    if has_await {
        let it = host::call_method(&x, "__await__", vec![], vec![])?;
        return drive_delegate(&it);
    }
    Err(host::type_error(&format!(
        "object {} can't be used in 'await' expression",
        with_host(|h| h.type_name(&x))
    )))
}

/// Drive an async generator one step, per the pending op (`__anext__`/`asend` →
/// resume sending a value; `athrow` → raise at the current `yield`; `aclose` →
/// raise `GeneratorExit` and expect the body to finish). Resumes until the body
/// produces a value (a `yield`) or finishes; an intervening `await` suspension
/// yields its Future up to the loop and the driver resumes on wake.
fn drive_async_gen(agen: &Value) -> Result<Value, String> {
    // The first resume performs the queued op; later resumes (after forwarding an
    // `await`) always send `None`.
    let mut pending = Some(host::take_agen_op(agen).unwrap_or(host::AGenOp::Send(Value::Undef)));
    let closing = matches!(pending, Some(host::AGenOp::Close));
    loop {
        let stepped = match pending.take() {
            Some(host::AGenOp::Send(v)) => host::gen_resume(agen, v),
            Some(host::AGenOp::Throw(exc)) => host::gen_throw(agen, exc),
            Some(host::AGenOp::Close) => {
                let ge = with_host(|h| {
                    h.alloc(PyObj::Exception {
                        class: "GeneratorExit".into(),
                        args: vec![],
                    })
                });
                host::gen_throw(agen, ge)
            }
            // Resumes after the first always send `None`.
            None => host::gen_resume(agen, Value::Undef),
        };
        match stepped {
            Ok(Some(y)) => {
                if host::cur_gen_awaiting(agen) {
                    // `await` inside the async gen: `y` is a Future — forward it
                    // up to the loop (suspending the outer coroutine), then retry.
                    host::gen_yield_awaiting(y)?;
                } else if closing {
                    // The body `yield`ed while being closed — that is an error.
                    return Err("RuntimeError: async generator ignored GeneratorExit".to_string());
                } else {
                    // A `yield`ed value: this `__anext__`/`asend`/`athrow` result.
                    return Ok(y);
                }
            }
            Ok(None) => {
                if closing {
                    // `aclose()` completes with `None` once the body finishes.
                    return Ok(Value::Undef);
                }
                // Exhausted → `StopAsyncIteration`.
                let e = with_host(|h| {
                    h.alloc(PyObj::Exception {
                        class: "StopAsyncIteration".into(),
                        args: vec![],
                    })
                });
                return Err(host::raise_value(&e).unwrap_or_else(|e| e));
            }
            Err(e) => {
                // `aclose()` swallows the expected `GeneratorExit`/`StopAsyncIteration`.
                if closing && (e.contains("GeneratorExit") || e.contains("StopAsyncIteration")) {
                    with_host(|h| {
                        h.error = None;
                        h.exc = None;
                    });
                    return Ok(Value::Undef);
                }
                return Err(e);
            }
        }
    }
}

/// The `agen.asend`/`athrow`/`aclose` awaitables. Each records the op on the
/// generator cell and returns the generator itself as the awaitable; the actual
/// drive happens when it is `await`ed (see `drive_async_gen`).
pub fn async_gen_method(recv: &Value, name: &str, args: Vec<Value>) -> Result<Value, String> {
    match name {
        "asend" => {
            host::set_agen_op(
                recv,
                host::AGenOp::Send(args.into_iter().next().unwrap_or(Value::Undef)),
            );
            Ok(recv.clone())
        }
        "athrow" => {
            let a0 = args.first().cloned().unwrap_or(Value::Undef);
            // `athrow(ExcType, ...)` instantiates; `athrow(exc_instance)` passes through.
            let exc = with_host(|h| match h.get(&a0) {
                Some(PyObj::Builtin(n)) if crate::builtins::is_exception_class(n) => {
                    let n = n.clone();
                    let rest = args.get(1..).unwrap_or(&[]).to_vec();
                    h.alloc(PyObj::Exception {
                        class: n,
                        args: rest,
                    })
                }
                _ => a0.clone(),
            });
            host::set_agen_op(recv, host::AGenOp::Throw(exc));
            Ok(recv.clone())
        }
        "aclose" => {
            host::set_agen_op(recv, host::AGenOp::Close);
            Ok(recv.clone())
        }
        _ => Err(format!(
            "AttributeError: 'async_generator' object has no attribute '{name}'"
        )),
    }
}

/// Delegate into a sub-coroutine / `__await__` iterator: pump it, forwarding
/// each yielded value (ultimately a Future) up to our own resumer.
fn drive_delegate(sub: &Value) -> Result<Value, String> {
    let mut send = Value::Undef;
    loop {
        match host::gen_resume(sub, send) {
            Ok(Some(y)) => {
                // Forward the yield up to the loop; the sent value is ignored
                // (Futures publish their result on the object, not via send).
                send = host::gen_yield_awaiting(y)?;
            }
            Ok(None) => return Ok(host::coro_return_value(sub)),
            Err(e) => return Err(e),
        }
    }
}

// ── asyncio module surface ───────────────────────────────────────────────────

/// `asyncio.run(coro)` — run `coro` on a fresh loop turn to completion.
pub fn run(coro: Value) -> Result<Value, String> {
    if !host::is_coroutine(&coro) {
        return Err(host::type_error(&format!(
            "asyncio.run() requires a coroutine, got {}",
            with_host(|h| h.type_name(&coro))
        )));
    }
    run_until_complete(coro)
}

/// `asyncio.sleep(delay[, result])` — an awaitable that completes with `result`
/// after `delay` seconds of virtual time (a single loop turn for `delay <= 0`).
pub fn sleep(delay: f64, result: Value) -> Value {
    let fut = new_future();
    let id = future_id(&fut).unwrap();
    if delay <= 0.0 {
        call_soon_native(Box::new(move || {
            settle(id, result, None, false);
        }));
    } else {
        call_later(
            delay,
            Callback::Native(Box::new(move || {
                settle(id, result, None, false);
            })),
        );
    }
    fut
}

/// `asyncio.gather(*aws)` — run all awaitables concurrently; the returned Future
/// completes with the list of results in argument order, or fails on the first
/// exception (default `return_exceptions=False`).
pub fn gather(aws: Vec<Value>, return_exceptions: bool) -> Result<Value, String> {
    let outer = new_future();
    let oid = future_id(&outer).unwrap();
    let n = aws.len();
    if n == 0 {
        let empty = with_host(|h| h.new_list(vec![]));
        settle(oid, empty, None, false);
        return Ok(outer);
    }
    let results: Rc<RefCell<Vec<Value>>> = Rc::new(RefCell::new(vec![Value::Undef; n]));
    let remaining = Rc::new(std::cell::Cell::new(n));
    for (i, aw) in aws.into_iter().enumerate() {
        let child = ensure_future(aw)?;
        let cid = future_id(&child).unwrap();
        let results_c = results.clone();
        let remaining_c = remaining.clone();
        add_done_native(
            cid,
            Box::new(move || {
                let exc = future_exc(cid);
                let value = match exc {
                    Some(e) if !return_exceptions => {
                        fail_quietly(oid, e);
                        return;
                    }
                    Some(e) => e, // return_exceptions: store the exception itself
                    None => future_result(cid),
                };
                results_c.borrow_mut()[i] = value;
                let rem = remaining_c.get() - 1;
                remaining_c.set(rem);
                if rem == 0 {
                    let list = with_host(|h| h.new_list(results_c.borrow().clone()));
                    settle(oid, list, None, false);
                }
            }),
        );
    }
    Ok(outer)
}

/// `asyncio.wait_for(aw, timeout)` — await `aw`, raising `TimeoutError` if it is
/// not done within `timeout` seconds. `timeout=None` just awaits.
pub fn wait_for(aw: Value, timeout: Option<f64>) -> Result<Value, String> {
    let inner = ensure_future(aw)?;
    let iid = future_id(&inner).unwrap();
    let outer = new_future();
    let oid = future_id(&outer).unwrap();
    // Propagate the inner result/exception to the outer future.
    add_done_native(
        iid,
        Box::new(move || {
            if let Some(e) = future_exc(iid) {
                fail_quietly(oid, e);
            } else {
                settle(oid, future_result(iid), None, false);
            }
        }),
    );
    if let Some(t) = timeout {
        call_later(
            t,
            Callback::Native(Box::new(move || {
                if !future_done(oid) {
                    // Cancel the still-running inner task (CPython cancels + awaits
                    // it), then fail the outer future with `TimeoutError`.
                    cancel_future(iid);
                    let e = with_host(|h| {
                        h.alloc(PyObj::Exception {
                            class: "TimeoutError".into(),
                            args: vec![],
                        })
                    });
                    fail_quietly(oid, e);
                }
            })),
        );
    }
    Ok(outer)
}

/// `return_when` selector for [`wait`].
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum ReturnWhen {
    FirstCompleted,
    FirstException,
    AllCompleted,
}

impl ReturnWhen {
    /// Parse the `asyncio.FIRST_COMPLETED`/`FIRST_EXCEPTION`/`ALL_COMPLETED`
    /// string constants (defaulting to `ALL_COMPLETED`).
    pub fn parse(s: &str) -> ReturnWhen {
        match s {
            "FIRST_COMPLETED" => ReturnWhen::FirstCompleted,
            "FIRST_EXCEPTION" => ReturnWhen::FirstException,
            _ => ReturnWhen::AllCompleted,
        }
    }
}

/// `asyncio.wait(aws, timeout=None, return_when=ALL_COMPLETED)` — wait for the
/// awaitables per `return_when`; the result future resolves to `(done, pending)`
/// sets partitioned by completion at settle time. A `timeout` settles early with
/// whatever is done so far (the rest go to `pending`).
pub fn wait(
    aws: Vec<Value>,
    timeout: Option<f64>,
    return_when: ReturnWhen,
) -> Result<Value, String> {
    let tasks: Vec<Value> = aws
        .into_iter()
        .map(ensure_future)
        .collect::<Result<_, _>>()?;
    let outer = new_future();
    let oid = future_id(&outer).unwrap();
    if tasks.is_empty() {
        let done = with_host(|h| h.alloc(PyObj::Set(Default::default())));
        let pending = with_host(|h| h.alloc(PyObj::Set(Default::default())));
        let tup = with_host(|h| h.new_tuple(vec![done, pending]));
        settle(oid, tup, None, false);
        return Ok(outer);
    }
    // Partition `tasks` into (done, pending) by each task's current done state and
    // settle `outer` with that snapshot.
    let build_and_settle = {
        let tasks = tasks.clone();
        move || {
            if future_done(oid) {
                return;
            }
            let (mut done, mut pending) = (Vec::new(), Vec::new());
            for t in &tasks {
                let tid = future_id(t).unwrap();
                if future_done(tid) {
                    done.push(t.clone());
                } else {
                    pending.push(t.clone());
                }
            }
            let done = with_host(|h| h.alloc(PyObj::Set(build_set(&done))));
            let pending = with_host(|h| h.alloc(PyObj::Set(build_set(&pending))));
            let tup = with_host(|h| h.new_tuple(vec![done, pending]));
            settle(oid, tup, None, false);
        }
    };
    let build_and_settle = Rc::new(build_and_settle);
    let n = tasks.len();
    let remaining = Rc::new(std::cell::Cell::new(n));
    for t in &tasks {
        let tid = future_id(t).unwrap();
        let remaining_c = remaining.clone();
        let settle_c = build_and_settle.clone();
        add_done_native(
            tid,
            Box::new(move || {
                let rem = remaining_c.get() - 1;
                remaining_c.set(rem);
                let trigger = match return_when {
                    ReturnWhen::FirstCompleted => true,
                    ReturnWhen::FirstException => future_exc(tid).is_some() || rem == 0,
                    ReturnWhen::AllCompleted => rem == 0,
                };
                if trigger {
                    settle_c();
                }
            }),
        );
    }
    if let Some(t) = timeout {
        let settle_c = build_and_settle.clone();
        call_later(t, Callback::Native(Box::new(move || settle_c())));
    }
    Ok(outer)
}

/// `asyncio.as_completed(aws)` — returns a list of awaitables (one per input)
/// that resolve in completion order. Awaiting them in list order yields results
/// as the underlying tasks finish, matching CPython's iteration semantics.
pub fn as_completed(aws: Vec<Value>) -> Result<Value, String> {
    let tasks: Vec<Value> = aws
        .into_iter()
        .map(ensure_future)
        .collect::<Result<_, _>>()?;
    // One output future per input; the k-th input to complete fulfills the k-th
    // output future (in completion order).
    let outs: Vec<Value> = (0..tasks.len()).map(|_| new_future()).collect();
    let next_slot = Rc::new(std::cell::Cell::new(0usize));
    let outs_rc = Rc::new(outs.clone());
    for t in &tasks {
        let tid = future_id(t).unwrap();
        let next_slot = next_slot.clone();
        let outs_rc = outs_rc.clone();
        add_done_native(
            tid,
            Box::new(move || {
                let k = next_slot.get();
                next_slot.set(k + 1);
                let oid = future_id(&outs_rc[k]).unwrap();
                if let Some(e) = future_exc(tid) {
                    fail_quietly(oid, e);
                } else {
                    settle(oid, future_result(tid), None, false);
                }
            }),
        );
    }
    Ok(with_host(|h| h.new_list(outs)))
}

fn build_set(items: &[Value]) -> crate::host::SetMap {
    let mut m = crate::host::SetMap::default();
    for (i, v) in items.iter().enumerate() {
        // Futures aren't hashable by value; key by heap identity via a synthetic
        // int key so the set holds each distinct task once.
        m.insert(crate::host::PKey::Int(i as i64), v.clone());
    }
    m
}

// ── synchronization primitives (Event / Lock / Queue) ────────────────────────

fn new_async_obj(obj: AsyncObj) -> Value {
    let id = with_loop(|l| {
        let id = l.async_objs.len() as u32;
        l.async_objs.push(obj);
        id
    });
    with_host(|h| h.alloc(PyObj::AsyncObj { id }))
}

/// `asyncio.Event()`.
pub fn new_event() -> Value {
    new_async_obj(AsyncObj::Event {
        flag: false,
        waiters: Vec::new(),
    })
}

/// `asyncio.Lock()`.
pub fn new_lock() -> Value {
    new_async_obj(AsyncObj::Lock {
        locked: false,
        waiters: VecDeque::new(),
    })
}

/// `asyncio.Queue(maxsize=0)`.
pub fn new_queue(maxsize: usize) -> Value {
    new_async_obj(AsyncObj::Queue {
        items: VecDeque::new(),
        maxsize,
        getters: VecDeque::new(),
        putters: VecDeque::new(),
    })
}

fn async_obj_id(v: &Value) -> Option<u32> {
    match with_host(|h| h.get(v).cloned()) {
        Some(PyObj::AsyncObj { id }) => Some(id),
        _ => None,
    }
}

/// Type name for an `AsyncObj` cell.
pub fn async_obj_type_name(id: u32) -> &'static str {
    with_loop(|l| match &l.async_objs[id as usize] {
        AsyncObj::Event { .. } => "Event",
        AsyncObj::Lock { .. } => "Lock",
        AsyncObj::Queue { .. } => "Queue",
    })
}

/// `repr` for an `AsyncObj` cell.
pub fn async_obj_repr(id: u32) -> String {
    with_loop(|l| match &l.async_objs[id as usize] {
        AsyncObj::Event { flag, .. } => {
            format!(
                "<asyncio.locks.Event object [{}]>",
                if *flag { "set" } else { "unset" }
            )
        }
        AsyncObj::Lock { locked, .. } => format!(
            "<asyncio.locks.Lock object [{}]>",
            if *locked { "locked" } else { "unlocked" }
        ),
        AsyncObj::Queue { items, maxsize, .. } => {
            format!("<Queue maxsize={maxsize} _queue={}>", items.len())
        }
    })
}

/// Dispatch a method call on an `Event`/`Lock`/`Queue`.
pub fn async_obj_method(recv: &Value, name: &str, args: Vec<Value>) -> Result<Value, String> {
    let id = async_obj_id(recv).ok_or_else(|| host::type_error("not an async primitive"))?;
    let kind = with_loop(|l| match &l.async_objs[id as usize] {
        AsyncObj::Event { .. } => 0u8,
        AsyncObj::Lock { .. } => 1,
        AsyncObj::Queue { .. } => 2,
    });
    match (kind, name) {
        // ── Event ──
        (0, "set") => {
            let waiters = with_loop(|l| {
                if let AsyncObj::Event { flag, waiters } = &mut l.async_objs[id as usize] {
                    *flag = true;
                    std::mem::take(waiters)
                } else {
                    Vec::new()
                }
            });
            for w in waiters {
                settle(w, Value::Bool(true), None, false);
            }
            Ok(Value::Undef)
        }
        (0, "clear") => {
            with_loop(|l| {
                if let AsyncObj::Event { flag, .. } = &mut l.async_objs[id as usize] {
                    *flag = false;
                }
            });
            Ok(Value::Undef)
        }
        (0, "is_set") => Ok(Value::Bool(with_loop(|l| {
            matches!(
                &l.async_objs[id as usize],
                AsyncObj::Event { flag: true, .. }
            )
        }))),
        (0, "wait") => {
            let flag = with_loop(|l| {
                matches!(
                    &l.async_objs[id as usize],
                    AsyncObj::Event { flag: true, .. }
                )
            });
            let fut = new_future();
            let fid = future_id(&fut).unwrap();
            if flag {
                settle(fid, Value::Bool(true), None, false);
            } else {
                with_loop(|l| {
                    if let AsyncObj::Event { waiters, .. } = &mut l.async_objs[id as usize] {
                        waiters.push(fid);
                    }
                });
            }
            Ok(fut)
        }
        // ── Lock ──
        (1, "locked") => Ok(Value::Bool(with_loop(|l| {
            matches!(
                &l.async_objs[id as usize],
                AsyncObj::Lock { locked: true, .. }
            )
        }))),
        (1, "acquire") | (1, "__aenter__") => {
            let fut = new_future();
            let fid = future_id(&fut).unwrap();
            let acquired = with_loop(|l| {
                if let AsyncObj::Lock { locked, waiters } = &mut l.async_objs[id as usize] {
                    if *locked {
                        waiters.push_back(fid);
                        false
                    } else {
                        *locked = true;
                        true
                    }
                } else {
                    true
                }
            });
            if acquired {
                settle(fid, Value::Bool(true), None, false);
            }
            Ok(fut)
        }
        (1, "release") => {
            release_lock(id);
            Ok(Value::Undef)
        }
        (1, "__aexit__") => {
            release_lock(id);
            // __aexit__ must be awaitable and return False (don't suppress).
            let fut = new_future();
            settle(future_id(&fut).unwrap(), Value::Bool(false), None, false);
            Ok(fut)
        }
        // ── Queue ──
        (2, "qsize") => Ok(Value::Int(with_loop(|l| {
            match &l.async_objs[id as usize] {
                AsyncObj::Queue { items, .. } => items.len() as i64,
                _ => 0,
            }
        }))),
        (2, "empty") => Ok(Value::Bool(with_loop(|l| {
            match &l.async_objs[id as usize] {
                AsyncObj::Queue { items, .. } => items.is_empty(),
                _ => true,
            }
        }))),
        (2, "full") => Ok(Value::Bool(with_loop(|l| {
            match &l.async_objs[id as usize] {
                AsyncObj::Queue { items, maxsize, .. } => *maxsize > 0 && items.len() >= *maxsize,
                _ => false,
            }
        }))),
        (2, "put_nowait") => {
            let v = args.into_iter().next().unwrap_or(Value::Undef);
            if queue_is_full(id) {
                return Err("QueueFull: ".to_string());
            }
            queue_put(id, v);
            Ok(Value::Undef)
        }
        (2, "put") => {
            let v = args.into_iter().next().unwrap_or(Value::Undef);
            let fut = new_future();
            let fid = future_id(&fut).unwrap();
            // A full bounded queue blocks the `put`: park `(fid, v)` and complete
            // it when a `get()` frees a slot. Otherwise the put completes at once.
            if queue_is_full(id) {
                with_loop(|l| {
                    if let AsyncObj::Queue { putters, .. } = &mut l.async_objs[id as usize] {
                        putters.push_back((fid, v));
                    }
                });
            } else {
                queue_put(id, v);
                settle(fid, Value::Undef, None, false);
            }
            Ok(fut)
        }
        (2, "get_nowait") => queue_get_now(id),
        (2, "get") => {
            let fut = new_future();
            let fid = future_id(&fut).unwrap();
            // If an item is ready, fulfill immediately (waking a blocked putter);
            // else queue the getter.
            match queue_take(id) {
                Some(v) => settle(fid, v, None, false),
                None => {
                    with_loop(|l| {
                        if let AsyncObj::Queue { getters, .. } = &mut l.async_objs[id as usize] {
                            getters.push_back(fid);
                        }
                    });
                    false
                }
            };
            Ok(fut)
        }
        _ => Err(format!(
            "AttributeError: '{}' object has no attribute '{name}'",
            async_obj_type_name(id)
        )),
    }
}

/// Hand a lock to the next waiter (staying locked) or release it.
fn release_lock(id: u32) {
    let next = with_loop(|l| {
        if let AsyncObj::Lock { locked, waiters } = &mut l.async_objs[id as usize] {
            match waiters.pop_front() {
                Some(w) => Some(w), // stays locked, handed to `w`
                None => {
                    *locked = false;
                    None
                }
            }
        } else {
            None
        }
    });
    if let Some(w) = next {
        settle(w, Value::Bool(true), None, false);
    }
}

/// Whether a bounded queue is at capacity (a full `put` blocks).
fn queue_is_full(id: u32) -> bool {
    with_loop(|l| match &l.async_objs[id as usize] {
        AsyncObj::Queue { items, maxsize, .. } => *maxsize > 0 && items.len() >= *maxsize,
        _ => false,
    })
}

/// Put an item, waking a pending getter if one is waiting (item handed over
/// directly, bypassing the buffer). Only called when the queue has room.
fn queue_put(id: u32, v: Value) {
    let getter = with_loop(|l| {
        if let AsyncObj::Queue { items, getters, .. } = &mut l.async_objs[id as usize] {
            if let Some(g) = getters.pop_front() {
                Some(g)
            } else {
                items.push_back(v.clone());
                None
            }
        } else {
            None
        }
    });
    if let Some(g) = getter {
        settle(g, v, None, false);
    }
}

/// Take one buffered item and, if a blocked putter is waiting, admit its item
/// into the freed slot (completing that put). Returns `None` if empty.
fn queue_take(id: u32) -> Option<Value> {
    let (item, putter) = with_loop(|l| {
        if let AsyncObj::Queue { items, putters, .. } = &mut l.async_objs[id as usize] {
            let item = items.pop_front();
            // A slot just freed → admit the next blocked put into the buffer.
            let putter = if item.is_some() {
                putters.pop_front()
            } else {
                None
            };
            if let Some((_, ref pv)) = putter {
                items.push_back(pv.clone());
            }
            (item, putter)
        } else {
            (None, None)
        }
    });
    if let Some((pfid, _)) = putter {
        settle(pfid, Value::Undef, None, false);
    }
    item
}

fn queue_get_now(id: u32) -> Result<Value, String> {
    match queue_take(id) {
        Some(v) => Ok(v),
        None => Err("QueueEmpty: ".to_string()),
    }
}

// ── event-loop object ────────────────────────────────────────────────────────

/// The singleton `asyncio` event loop object (`get_event_loop`/`get_running_loop`).
pub fn event_loop() -> Value {
    with_host(|h| h.alloc(PyObj::EventLoop))
}

/// `asyncio.current_task()`: the Task whose coroutine is running, or `None`.
pub fn current_task() -> Result<Value, String> {
    if !with_loop(|l| l.running) {
        return Err("RuntimeError: no running event loop".to_string());
    }
    Ok(match with_loop(|l| l.current) {
        Some(id) => future_obj(id),
        None => Value::Undef,
    })
}

/// Dispatch a method call on the event-loop object.
pub fn loop_method(name: &str, args: Vec<Value>) -> Result<Value, String> {
    match name {
        "run_until_complete" => {
            let aw = args.into_iter().next().unwrap_or(Value::Undef);
            run_until_complete(aw)
        }
        "create_task" => {
            let coro = args.into_iter().next().unwrap_or(Value::Undef);
            create_task(coro, None)
        }
        "create_future" => Ok(new_future()),
        "call_soon" => {
            let mut it = args.into_iter();
            let func = it.next().unwrap_or(Value::Undef);
            call_soon_py(func, it.collect());
            Ok(handle_obj())
        }
        "call_later" => {
            let mut it = args.into_iter();
            let delay = it.next().and_then(as_f).unwrap_or(0.0);
            let func = it.next().unwrap_or(Value::Undef);
            let rest: Vec<Value> = it.collect();
            call_later(delay, Callback::Py { func, args: rest });
            Ok(handle_obj())
        }
        "time" => Ok(Value::Float(with_loop(|l| l.time))),
        "is_running" => Ok(Value::Bool(with_loop(|l| l.running))),
        "is_closed" => Ok(Value::Bool(false)),
        "stop" | "close" | "run_forever" => Ok(Value::Undef),
        "get_debug" => Ok(Value::Bool(false)),
        "set_debug" => Ok(Value::Undef),
        _ => Err(format!(
            "AttributeError: '_UnixSelectorEventLoop' object has no attribute '{name}'"
        )),
    }
}

/// A minimal `TimerHandle`/`Handle` stand-in (`call_soon`/`call_later` return
/// something with a `.cancel()`); we return a fresh Future used only as an
/// opaque handle whose `cancel()` is a harmless no-op.
fn handle_obj() -> Value {
    new_future()
}

// ── future object surface ────────────────────────────────────────────────────

/// Dispatch a method call on a Future/Task object.
pub fn future_method(recv: &Value, name: &str, args: Vec<Value>) -> Result<Value, String> {
    let id = future_id(recv).ok_or_else(|| host::type_error("not a future"))?;
    match name {
        "set_result" => set_result(recv, args.into_iter().next().unwrap_or(Value::Undef)),
        "set_exception" => set_exception(recv, args.into_iter().next().unwrap_or(Value::Undef)),
        "result" => {
            if !future_done(id) {
                return Err("InvalidStateError: Result is not set.".to_string());
            }
            if let Some(exc) = future_exc(id) {
                return Err(host::raise_value(&exc).unwrap_or_else(|e| e));
            }
            Ok(future_result(id))
        }
        "exception" => {
            if !future_done(id) {
                return Err("InvalidStateError: Exception is not set.".to_string());
            }
            Ok(future_exc(id).unwrap_or(Value::Undef))
        }
        "done" => Ok(Value::Bool(future_done(id))),
        "cancelled" => Ok(Value::Bool(with_loop(|l| l.futures[id as usize].cancelled))),
        "add_done_callback" => {
            let cb = args.into_iter().next().unwrap_or(Value::Undef);
            if future_done(id) {
                let fut = recv.clone();
                call_soon_py(cb, vec![fut]);
            } else {
                with_loop(|l| l.futures[id as usize].py_callbacks.push(cb));
            }
            Ok(Value::Undef)
        }
        "cancel" => Ok(Value::Bool(cancel_future(id))),
        "get_name" => Ok(with_host(|h| {
            let nm = with_loop(|l| l.futures[id as usize].name.clone());
            h.new_str(nm)
        })),
        "__await__" | "__iter__" => Ok(recv.clone()),
        _ => Err(format!(
            "AttributeError: '{}' object has no attribute '{name}'",
            future_type_name(id)
        )),
    }
}

/// The type name for a Future cell (`Task` vs `Future`).
pub fn future_type_name(id: u32) -> &'static str {
    if with_loop(|l| l.futures[id as usize].is_task) {
        "Task"
    } else {
        "Future"
    }
}

/// `repr` of a Future/Task: `<Task pending name='…'>` / `<Future finished result=…>`.
pub fn future_repr(id: u32) -> String {
    let (is_task, done, cancelled, name) = with_loop(|l| {
        let f = &l.futures[id as usize];
        (f.is_task, f.done, f.cancelled, f.name.clone())
    });
    let kind = if is_task { "Task" } else { "Future" };
    let state = if cancelled {
        "cancelled".to_string()
    } else if done {
        if let Some(exc) = future_exc(id) {
            format!("finished exception={}", with_host(|h| h.repr_of(&exc)))
        } else {
            format!(
                "finished result={}",
                with_host(|h| h.repr_of(&future_result(id)))
            )
        }
    } else {
        "pending".to_string()
    };
    if is_task {
        format!("<{kind} {state} name='{name}'>")
    } else {
        format!("<{kind} {state}>")
    }
}

fn as_f(v: Value) -> Option<f64> {
    match v {
        Value::Int(n) => Some(n as f64),
        Value::Float(f) => Some(f),
        Value::Bool(b) => Some(if b { 1.0 } else { 0.0 }),
        _ => None,
    }
}

/// Whether the event loop holds nothing: no future, task or coroutine object,
/// queued callback or timer. The collector runs only then, since what the
/// loop holds is not among its roots (`host::gc`).
pub(crate) fn loop_is_idle() -> bool {
    LOOP.with(|l| {
        let l = l.borrow();
        l.futures.is_empty() && l.async_objs.is_empty() && l.ready.is_empty() && l.timers.is_empty()
    })
}