-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy path_asyncio.rs
More file actions
2766 lines (2460 loc) · 102 KB
/
_asyncio.rs
File metadata and controls
2766 lines (2460 loc) · 102 KB
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
//! _asyncio module - provides native asyncio support
//!
//! This module provides native implementations of Future and Task classes,
pub(crate) use _asyncio::module_def;
#[pymodule]
pub(crate) mod _asyncio {
use crate::common::wtf8::{Wtf8Buf, wtf8_concat};
use crate::{
common::lock::PyRwLock,
vm::{
AsObject, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine,
builtins::{
PyBaseException, PyBaseExceptionRef, PyDict, PyDictRef, PyGenericAlias, PyList,
PyListRef, PyModule, PySet, PyTuple, PyType, PyTypeRef,
},
extend_module,
function::{FuncArgs, KwArgs, OptionalArg, OptionalOption, PySetterValue},
protocol::PyIterReturn,
recursion::ReprGuard,
types::{
Callable, Constructor, Destructor, Initializer, IterNext, Iterable, Representable,
SelfIter,
},
warn,
},
};
use core::sync::atomic::{AtomicBool, AtomicI32, AtomicU64, Ordering};
use crossbeam_utils::atomic::AtomicCell;
pub(crate) fn module_exec(vm: &VirtualMachine, module: &Py<PyModule>) -> PyResult<()> {
__module_exec(vm, module);
// Initialize module-level state
let weakref_module = vm.import("weakref", 0)?;
let weak_set_class = vm
.get_attribute_opt(weakref_module, vm.ctx.intern_str("WeakSet"))?
.ok_or_else(|| vm.new_attribute_error("WeakSet not found"))?;
let scheduled_tasks = weak_set_class.call((), vm)?;
let eager_tasks = PySet::default().into_ref(&vm.ctx);
let current_tasks = PyDict::default().into_ref(&vm.ctx);
extend_module!(vm, module, {
"_scheduled_tasks" => scheduled_tasks,
"_eager_tasks" => eager_tasks,
"_current_tasks" => current_tasks,
});
// Register fork handler to clear task state in child process
#[cfg(unix)]
{
let on_fork = vm
.get_attribute_opt(module.to_owned().into(), vm.ctx.intern_str("_on_fork"))?
.expect("_on_fork not found in _asyncio module");
vm.state.after_forkers_child.lock().push(on_fork);
}
Ok(())
}
#[derive(FromArgs)]
struct AddDoneCallbackArgs {
#[pyarg(positional)]
func: PyObjectRef,
#[pyarg(named, optional)]
context: OptionalOption<PyObjectRef>,
}
#[derive(FromArgs)]
struct CancelArgs {
#[pyarg(any, optional)]
msg: OptionalOption<PyObjectRef>,
}
#[derive(FromArgs)]
struct LoopArg {
#[pyarg(any, name = "loop", optional)]
loop_: OptionalOption<PyObjectRef>,
}
#[derive(FromArgs)]
struct GetStackArgs {
#[pyarg(named, optional)]
limit: OptionalOption<PyObjectRef>,
}
#[derive(FromArgs)]
struct PrintStackArgs {
#[pyarg(named, optional)]
limit: OptionalOption<PyObjectRef>,
#[pyarg(named, optional)]
file: OptionalOption<PyObjectRef>,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum FutureState {
Pending,
Cancelled,
Finished,
}
impl FutureState {
fn as_str(&self) -> &'static str {
match self {
FutureState::Pending => "PENDING",
FutureState::Cancelled => "CANCELLED",
FutureState::Finished => "FINISHED",
}
}
}
/// asyncio.Future implementation
#[pyattr]
#[pyclass(name = "Future", module = "_asyncio", traverse)]
#[derive(Debug, PyPayload)]
#[repr(C)] // Required for inheritance - ensures base field is at offset 0 in subclasses
struct PyFuture {
fut_loop: PyRwLock<Option<PyObjectRef>>,
fut_callback0: PyRwLock<Option<PyObjectRef>>,
fut_context0: PyRwLock<Option<PyObjectRef>>,
fut_callbacks: PyRwLock<Option<PyObjectRef>>,
fut_exception: PyRwLock<Option<PyObjectRef>>,
fut_exception_tb: PyRwLock<Option<PyObjectRef>>,
fut_result: PyRwLock<Option<PyObjectRef>>,
fut_source_tb: PyRwLock<Option<PyObjectRef>>,
fut_cancel_msg: PyRwLock<Option<PyObjectRef>>,
fut_cancelled_exc: PyRwLock<Option<PyObjectRef>>,
fut_awaited_by: PyRwLock<Option<PyObjectRef>>,
#[pytraverse(skip)]
fut_state: AtomicCell<FutureState>,
#[pytraverse(skip)]
fut_awaited_by_is_set: AtomicBool,
#[pytraverse(skip)]
fut_log_tb: AtomicBool,
#[pytraverse(skip)]
fut_blocking: AtomicBool,
}
impl Constructor for PyFuture {
type Args = FuncArgs;
fn py_new(_cls: &Py<PyType>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<Self> {
Ok(PyFuture::new_empty())
}
}
impl Initializer for PyFuture {
type Args = FuncArgs;
fn init(zelf: PyRef<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
// Future does not accept positional arguments
if !args.args.is_empty() {
return Err(vm.new_type_error("Future() takes no positional arguments"));
}
// Extract only 'loop' keyword argument
let loop_ = args.kwargs.get("loop").cloned();
PyFuture::py_init(&zelf, loop_, vm)
}
}
#[pyclass(
flags(BASETYPE, HAS_DICT, HAS_WEAKREF),
with(Constructor, Initializer, Destructor, Representable, Iterable)
)]
impl PyFuture {
fn new_empty() -> Self {
Self {
fut_loop: PyRwLock::new(None),
fut_callback0: PyRwLock::new(None),
fut_context0: PyRwLock::new(None),
fut_callbacks: PyRwLock::new(None),
fut_exception: PyRwLock::new(None),
fut_exception_tb: PyRwLock::new(None),
fut_result: PyRwLock::new(None),
fut_source_tb: PyRwLock::new(None),
fut_cancel_msg: PyRwLock::new(None),
fut_cancelled_exc: PyRwLock::new(None),
fut_awaited_by: PyRwLock::new(None),
fut_state: AtomicCell::new(FutureState::Pending),
fut_awaited_by_is_set: AtomicBool::new(false),
fut_log_tb: AtomicBool::new(false),
fut_blocking: AtomicBool::new(false),
}
}
fn py_init(
zelf: &PyRef<Self>,
loop_: Option<PyObjectRef>,
vm: &VirtualMachine,
) -> PyResult<()> {
// Get the event loop
let loop_obj = match loop_ {
Some(l) if !vm.is_none(&l) => l,
_ => get_event_loop(vm)?,
};
*zelf.fut_loop.write() = Some(loop_obj.clone());
// Check if loop has get_debug method and call it
if let Ok(Some(get_debug)) =
vm.get_attribute_opt(loop_obj.clone(), vm.ctx.intern_str("get_debug"))
&& let Ok(debug) = get_debug.call((), vm)
&& debug.try_to_bool(vm).unwrap_or(false)
{
// Get source traceback
if let Ok(tb_module) = vm.import("traceback", 0)
&& let Ok(Some(extract_stack)) =
vm.get_attribute_opt(tb_module, vm.ctx.intern_str("extract_stack"))
&& let Ok(tb) = extract_stack.call((), vm)
{
*zelf.fut_source_tb.write() = Some(tb);
}
}
Ok(())
}
#[pymethod]
fn result(&self, vm: &VirtualMachine) -> PyResult {
match self.fut_state.load() {
FutureState::Pending => Err(new_invalid_state_error(vm, "Result is not ready.")),
FutureState::Cancelled => {
let exc = self.make_cancelled_error_impl(vm);
Err(exc)
}
FutureState::Finished => {
self.fut_log_tb.store(false, Ordering::Relaxed);
if let Some(exc) = self.fut_exception.read().clone() {
let exc: PyBaseExceptionRef = exc.downcast().unwrap();
// Restore the original traceback to prevent traceback accumulation
if let Some(tb) = self.fut_exception_tb.read().clone() {
let _ = exc.set___traceback__(tb, vm);
}
Err(exc)
} else {
Ok(self
.fut_result
.read()
.clone()
.unwrap_or_else(|| vm.ctx.none()))
}
}
}
}
#[pymethod]
fn exception(&self, vm: &VirtualMachine) -> PyResult {
match self.fut_state.load() {
FutureState::Pending => Err(new_invalid_state_error(vm, "Exception is not set.")),
FutureState::Cancelled => {
let exc = self.make_cancelled_error_impl(vm);
Err(exc)
}
FutureState::Finished => {
self.fut_log_tb.store(false, Ordering::Relaxed);
Ok(self
.fut_exception
.read()
.clone()
.unwrap_or_else(|| vm.ctx.none()))
}
}
}
#[pymethod]
fn set_result(zelf: PyRef<Self>, result: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
if zelf.fut_loop.read().is_none() {
return Err(vm.new_runtime_error("Future object is not initialized."));
}
if zelf.fut_state.load() != FutureState::Pending {
return Err(new_invalid_state_error(vm, "invalid state"));
}
*zelf.fut_result.write() = Some(result);
zelf.fut_state.store(FutureState::Finished);
Self::schedule_callbacks(&zelf, vm)?;
Ok(())
}
#[pymethod]
fn set_exception(
zelf: PyRef<Self>,
exception: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult<()> {
if zelf.fut_loop.read().is_none() {
return Err(vm.new_runtime_error("Future object is not initialized."));
}
if zelf.fut_state.load() != FutureState::Pending {
return Err(new_invalid_state_error(vm, "invalid state"));
}
// Normalize the exception
let exc = if exception.fast_isinstance(vm.ctx.types.type_type) {
exception.call((), vm)?
} else {
exception
};
if !exc.fast_isinstance(vm.ctx.exceptions.base_exception_type) {
return Err(vm.new_type_error(format!(
"exception must be a BaseException, not {}",
exc.class().name()
)));
}
// Wrap StopIteration in RuntimeError
let exc = if exc.fast_isinstance(vm.ctx.exceptions.stop_iteration) {
let msg = "StopIteration interacts badly with generators and cannot be raised into a Future";
let runtime_err = vm.new_runtime_error(msg.to_string());
// Set cause and context to the original StopIteration
let stop_iter: PyRef<PyBaseException> = exc.downcast().unwrap();
runtime_err.set___cause__(Some(stop_iter.clone()));
runtime_err.set___context__(Some(stop_iter));
runtime_err.into()
} else {
exc
};
// Save the original traceback for later restoration
if let Ok(exc_ref) = exc.clone().downcast::<PyBaseException>() {
let tb = exc_ref.__traceback__().map(|tb| tb.into());
*zelf.fut_exception_tb.write() = tb;
}
*zelf.fut_exception.write() = Some(exc);
zelf.fut_state.store(FutureState::Finished);
zelf.fut_log_tb.store(true, Ordering::Relaxed);
Self::schedule_callbacks(&zelf, vm)?;
Ok(())
}
#[pymethod]
fn add_done_callback(
zelf: PyRef<Self>,
args: AddDoneCallbackArgs,
vm: &VirtualMachine,
) -> PyResult<()> {
if zelf.fut_loop.read().is_none() {
return Err(vm.new_runtime_error("Future object is not initialized."));
}
let ctx = match args.context.flatten() {
Some(c) => c,
None => get_copy_context(vm)?,
};
if zelf.fut_state.load() != FutureState::Pending {
Self::call_soon_with_context(&zelf, args.func, Some(ctx), vm)?;
} else if zelf.fut_callback0.read().is_none() {
*zelf.fut_callback0.write() = Some(args.func);
*zelf.fut_context0.write() = Some(ctx);
} else {
let tuple = vm.ctx.new_tuple(vec![args.func, ctx]);
let mut callbacks = zelf.fut_callbacks.write();
if callbacks.is_none() {
*callbacks = Some(vm.ctx.new_list(vec![tuple.into()]).into());
} else {
let list = callbacks.as_ref().unwrap();
vm.call_method(list, "append", (tuple,))?;
}
}
Ok(())
}
#[pymethod]
fn remove_done_callback(&self, func: PyObjectRef, vm: &VirtualMachine) -> PyResult<usize> {
if self.fut_loop.read().is_none() {
return Err(vm.new_runtime_error("Future object is not initialized."));
}
let mut cleared_callback0 = 0usize;
// Check fut_callback0 first
// Clone to release lock before comparison (which may run Python code)
let cb0 = self.fut_callback0.read().clone();
if let Some(cb0) = cb0 {
let cmp = vm.identical_or_equal(&cb0, &func)?;
if cmp {
*self.fut_callback0.write() = None;
*self.fut_context0.write() = None;
cleared_callback0 = 1;
}
}
// Check if fut_callbacks exists
let callbacks = self.fut_callbacks.read().clone();
let callbacks = match callbacks {
Some(c) => c,
None => return Ok(cleared_callback0),
};
let list: PyListRef = callbacks.downcast().unwrap();
let len = list.borrow_vec().len();
if len == 0 {
*self.fut_callbacks.write() = None;
return Ok(cleared_callback0);
}
// Special case for single callback
if len == 1 {
let item = list.borrow_vec().first().cloned();
if let Some(item) = item {
let tuple: &PyTuple = item.downcast_ref().unwrap();
let cb = tuple.first().unwrap().clone();
let cmp = vm.identical_or_equal(&cb, &func)?;
if cmp {
*self.fut_callbacks.write() = None;
return Ok(1 + cleared_callback0);
}
}
return Ok(cleared_callback0);
}
// Multiple callbacks - iterate with index, checking validity each time
// to handle evil comparisons
let mut new_callbacks = Vec::with_capacity(len);
let mut i = 0usize;
let mut removed = 0usize;
loop {
// Re-check fut_callbacks on each iteration (evil code may have cleared it)
let callbacks = self.fut_callbacks.read().clone();
let callbacks = match callbacks {
Some(c) => c,
None => break,
};
let list: PyListRef = callbacks.downcast().unwrap();
let current_len = list.borrow_vec().len();
if i >= current_len {
break;
}
// Get item and release lock before comparison
let item = list.borrow_vec().get(i).cloned();
let item = match item {
Some(item) => item,
None => break,
};
let tuple: &PyTuple = item.downcast_ref().unwrap();
let cb = tuple.first().unwrap().clone();
let cmp = vm.identical_or_equal(&cb, &func)?;
if !cmp {
new_callbacks.push(item);
} else {
removed += 1;
}
i += 1;
}
// Update fut_callbacks with filtered list
if new_callbacks.is_empty() {
*self.fut_callbacks.write() = None;
} else {
*self.fut_callbacks.write() = Some(vm.ctx.new_list(new_callbacks).into());
}
Ok(removed + cleared_callback0)
}
#[pymethod]
fn cancel(zelf: PyRef<Self>, args: CancelArgs, vm: &VirtualMachine) -> PyResult<bool> {
if zelf.fut_loop.read().is_none() {
return Err(vm.new_runtime_error("Future object is not initialized."));
}
if zelf.fut_state.load() != FutureState::Pending {
// Clear log_tb even when cancel fails
zelf.fut_log_tb.store(false, Ordering::Relaxed);
return Ok(false);
}
*zelf.fut_cancel_msg.write() = args.msg.flatten();
zelf.fut_state.store(FutureState::Cancelled);
Self::schedule_callbacks(&zelf, vm)?;
Ok(true)
}
#[pymethod]
fn cancelled(&self) -> bool {
self.fut_state.load() == FutureState::Cancelled
}
#[pymethod]
fn done(&self) -> bool {
self.fut_state.load() != FutureState::Pending
}
#[pymethod]
fn get_loop(&self, vm: &VirtualMachine) -> PyResult {
self.fut_loop
.read()
.clone()
.ok_or_else(|| vm.new_runtime_error("Future object is not initialized."))
}
#[pymethod]
fn _make_cancelled_error(&self, vm: &VirtualMachine) -> PyBaseExceptionRef {
self.make_cancelled_error_impl(vm)
}
fn make_cancelled_error_impl(&self, vm: &VirtualMachine) -> PyBaseExceptionRef {
// If a saved CancelledError exists, take it (clearing the stored reference)
if let Some(exc) = self.fut_cancelled_exc.write().take()
&& let Ok(exc) = exc.downcast::<PyBaseException>()
{
return exc;
}
let msg = self.fut_cancel_msg.read().clone();
let args = if let Some(m) = msg { vec![m] } else { vec![] };
match get_cancelled_error_type(vm) {
Ok(cancelled_error) => vm.new_exception(cancelled_error, args),
Err(_) => vm.new_runtime_error("cancelled"),
}
}
fn schedule_callbacks(zelf: &PyRef<Self>, vm: &VirtualMachine) -> PyResult<()> {
// Collect all callbacks first to avoid holding locks during callback execution
// This prevents deadlock when callbacks access the future's properties
let mut callbacks_to_call: Vec<(PyObjectRef, Option<PyObjectRef>)> = Vec::new();
// Take callback0 - release lock before collecting from list
let cb0 = zelf.fut_callback0.write().take();
let ctx0 = zelf.fut_context0.write().take();
if let Some(cb) = cb0 {
callbacks_to_call.push((cb, ctx0));
}
// Take callbacks list and collect items
let callbacks_list = zelf.fut_callbacks.write().take();
if let Some(callbacks) = callbacks_list
&& let Ok(list) = callbacks.downcast::<PyList>()
{
// Clone the items while holding the list lock, then release
let items: Vec<_> = list.borrow_vec().iter().cloned().collect();
for item in items {
if let Some(tuple) = item.downcast_ref::<PyTuple>()
&& let (Some(cb), Some(ctx)) = (tuple.first(), tuple.get(1))
{
callbacks_to_call.push((cb.clone(), Some(ctx.clone())));
}
}
}
// Now call all callbacks without holding any locks
for (cb, ctx) in callbacks_to_call {
Self::call_soon_with_context(zelf, cb, ctx, vm)?;
}
Ok(())
}
fn call_soon_with_context(
zelf: &PyRef<Self>,
callback: PyObjectRef,
context: Option<PyObjectRef>,
vm: &VirtualMachine,
) -> PyResult<()> {
let loop_obj = zelf.fut_loop.read().clone();
if let Some(loop_obj) = loop_obj {
// call_soon(callback, *args, context=context)
// callback receives the future as its argument
let future_arg: PyObjectRef = zelf.clone().into();
let args = if let Some(ctx) = context {
FuncArgs::new(
vec![callback, future_arg],
KwArgs::new([("context".to_owned(), ctx)].into_iter().collect()),
)
} else {
FuncArgs::new(vec![callback, future_arg], KwArgs::default())
};
vm.call_method(&loop_obj, "call_soon", args)?;
}
Ok(())
}
// Properties
#[pygetset]
fn _state(&self) -> &'static str {
self.fut_state.load().as_str()
}
#[pygetset]
fn _asyncio_future_blocking(&self) -> bool {
self.fut_blocking.load(Ordering::Relaxed)
}
#[pygetset(setter)]
fn set__asyncio_future_blocking(
&self,
value: PySetterValue<bool>,
vm: &VirtualMachine,
) -> PyResult<()> {
match value {
PySetterValue::Assign(v) => {
self.fut_blocking.store(v, Ordering::Relaxed);
Ok(())
}
PySetterValue::Delete => Err(vm.new_attribute_error("cannot delete attribute")),
}
}
#[pygetset]
fn _loop(&self, vm: &VirtualMachine) -> PyObjectRef {
self.fut_loop
.read()
.clone()
.unwrap_or_else(|| vm.ctx.none())
}
#[pygetset]
fn _callbacks(&self, vm: &VirtualMachine) -> PyResult<PyObjectRef> {
let mut result = Vec::new();
if let Some(cb0) = self.fut_callback0.read().clone() {
let ctx0 = self
.fut_context0
.read()
.clone()
.unwrap_or_else(|| vm.ctx.none());
result.push(vm.ctx.new_tuple(vec![cb0, ctx0]).into());
}
if let Some(callbacks) = self.fut_callbacks.read().clone() {
let list: PyListRef = callbacks.downcast().unwrap();
for item in list.borrow_vec().iter() {
result.push(item.clone());
}
}
// Return None if no callbacks
if result.is_empty() {
Ok(vm.ctx.none())
} else {
Ok(vm.ctx.new_list(result).into())
}
}
#[pygetset]
fn _result(&self, vm: &VirtualMachine) -> PyObjectRef {
self.fut_result
.read()
.clone()
.unwrap_or_else(|| vm.ctx.none())
}
#[pygetset]
fn _exception(&self, vm: &VirtualMachine) -> PyObjectRef {
self.fut_exception
.read()
.clone()
.unwrap_or_else(|| vm.ctx.none())
}
#[pygetset]
fn _log_traceback(&self) -> bool {
self.fut_log_tb.load(Ordering::Relaxed)
}
#[pygetset(setter)]
fn set__log_traceback(
&self,
value: PySetterValue<bool>,
vm: &VirtualMachine,
) -> PyResult<()> {
match value {
PySetterValue::Assign(v) => {
if v {
return Err(vm.new_value_error("_log_traceback can only be set to False"));
}
self.fut_log_tb.store(false, Ordering::Relaxed);
Ok(())
}
PySetterValue::Delete => Err(vm.new_attribute_error("cannot delete attribute")),
}
}
#[pygetset]
fn _source_traceback(&self, vm: &VirtualMachine) -> PyObjectRef {
self.fut_source_tb
.read()
.clone()
.unwrap_or_else(|| vm.ctx.none())
}
#[pygetset]
fn _cancel_message(&self, vm: &VirtualMachine) -> PyObjectRef {
self.fut_cancel_msg
.read()
.clone()
.unwrap_or_else(|| vm.ctx.none())
}
#[pygetset(setter)]
fn set__cancel_message(&self, value: PySetterValue) {
match value {
PySetterValue::Assign(v) => *self.fut_cancel_msg.write() = Some(v),
PySetterValue::Delete => *self.fut_cancel_msg.write() = None,
}
}
#[pygetset]
fn _asyncio_awaited_by(&self, vm: &VirtualMachine) -> PyResult<PyObjectRef> {
let awaited_by = self.fut_awaited_by.read().clone();
match awaited_by {
None => Ok(vm.ctx.none()),
Some(obj) => {
if self.fut_awaited_by_is_set.load(Ordering::Relaxed) {
// Already a Set
Ok(obj)
} else {
// Single object - create a Set for the return value
let new_set = PySet::default().into_ref(&vm.ctx);
new_set.add(obj, vm)?;
Ok(new_set.into())
}
}
}
}
/// Add waiter to fut_awaited_by with single-object optimization
fn awaited_by_add(&self, waiter: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
let mut awaited_by = self.fut_awaited_by.write();
if awaited_by.is_none() {
// First waiter - store directly
*awaited_by = Some(waiter);
return Ok(());
}
if self.fut_awaited_by_is_set.load(Ordering::Relaxed) {
// Already a Set - add to it
let set = awaited_by.as_ref().unwrap();
vm.call_method(set, "add", (waiter,))?;
} else {
// Single object - convert to Set
let existing = awaited_by.take().unwrap();
let new_set = PySet::default().into_ref(&vm.ctx);
new_set.add(existing, vm)?;
new_set.add(waiter, vm)?;
*awaited_by = Some(new_set.into());
self.fut_awaited_by_is_set.store(true, Ordering::Relaxed);
}
Ok(())
}
/// Discard waiter from fut_awaited_by with single-object optimization
fn awaited_by_discard(&self, waiter: &PyObject, vm: &VirtualMachine) -> PyResult<()> {
let mut awaited_by = self.fut_awaited_by.write();
if awaited_by.is_none() {
return Ok(());
}
let obj = awaited_by.as_ref().unwrap();
if !self.fut_awaited_by_is_set.load(Ordering::Relaxed) {
// Single object - check if it matches
if obj.is(waiter) {
*awaited_by = None;
}
} else {
// It's a Set - use discard
vm.call_method(obj, "discard", (waiter.to_owned(),))?;
}
Ok(())
}
#[pymethod]
fn __await__(zelf: PyRef<Self>, _vm: &VirtualMachine) -> PyResult<PyFutureIter> {
Ok(PyFutureIter {
future: PyRwLock::new(Some(zelf.into())),
})
}
#[pyclassmethod]
fn __class_getitem__(
cls: PyTypeRef,
args: PyObjectRef,
vm: &VirtualMachine,
) -> PyGenericAlias {
PyGenericAlias::from_args(cls, args, vm)
}
}
impl Destructor for PyFuture {
fn del(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<()> {
// Check if we should log the traceback
// Don't log if log_tb is false or if the future was cancelled
if !zelf.fut_log_tb.load(Ordering::Relaxed) {
return Ok(());
}
if zelf.fut_state.load() == FutureState::Cancelled {
return Ok(());
}
let exc = zelf.fut_exception.read().clone();
let exc = match exc {
Some(e) => e,
None => return Ok(()),
};
let loop_obj = zelf.fut_loop.read().clone();
let loop_obj = match loop_obj {
Some(l) => l,
None => return Ok(()),
};
// Create context dict for call_exception_handler
let context = PyDict::default().into_ref(&vm.ctx);
let class_name = zelf.class().name().to_string();
let message = format!("{} exception was never retrieved", class_name);
context.set_item(
vm.ctx.intern_str("message"),
vm.ctx.new_str(message).into(),
vm,
)?;
context.set_item(vm.ctx.intern_str("exception"), exc, vm)?;
context.set_item(vm.ctx.intern_str("future"), zelf.to_owned().into(), vm)?;
if let Some(tb) = zelf.fut_source_tb.read().clone() {
context.set_item(vm.ctx.intern_str("source_traceback"), tb, vm)?;
}
// Call loop.call_exception_handler(context)
let _ = vm.call_method(&loop_obj, "call_exception_handler", (context,));
Ok(())
}
}
impl Representable for PyFuture {
fn repr_str(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<String> {
let class_name = zelf.class().name().to_string();
if let Some(_guard) = ReprGuard::enter(vm, zelf.as_object()) {
let info = get_future_repr_info(zelf.as_object(), vm)?;
Ok(format!("<{} {}>", class_name, info))
} else {
Ok(format!("<{} ...>", class_name))
}
}
}
impl Iterable for PyFuture {
fn iter(zelf: PyRef<Self>, _vm: &VirtualMachine) -> PyResult {
Ok(PyFutureIter {
future: PyRwLock::new(Some(zelf.into())),
}
.into_pyobject(_vm))
}
}
fn get_future_repr_info(future: &PyObject, vm: &VirtualMachine) -> PyResult<Wtf8Buf> {
// Try to use asyncio.base_futures._future_repr_info
// Import from sys.modules if available, otherwise try regular import
let sys_modules = vm.sys_module.get_attr("modules", vm)?;
let module =
if let Ok(m) = sys_modules.get_item(&*vm.ctx.new_str("asyncio.base_futures"), vm) {
m
} else {
// vm.import returns the top-level module, get base_futures submodule
match vm
.import("asyncio.base_futures", 0)
.and_then(|asyncio| asyncio.get_attr(vm.ctx.intern_str("base_futures"), vm))
{
Ok(m) => m,
Err(_) => return get_future_repr_info_fallback(future, vm),
}
};
let func = match vm.get_attribute_opt(module, vm.ctx.intern_str("_future_repr_info")) {
Ok(Some(f)) => f,
_ => return get_future_repr_info_fallback(future, vm),
};
let info = match func.call((future.to_owned(),), vm) {
Ok(i) => i,
Err(_) => return get_future_repr_info_fallback(future, vm),
};
let list: PyListRef = match info.downcast() {
Ok(l) => l,
Err(_) => return get_future_repr_info_fallback(future, vm),
};
let mut result = Wtf8Buf::new();
let parts = list.borrow_vec();
for (i, x) in parts.iter().enumerate() {
if i > 0 {
result.push_str(" ");
}
if let Ok(s) = x.str(vm) {
result.push_wtf8(s.as_wtf8());
}
}
Ok(result)
}
fn get_future_repr_info_fallback(future: &PyObject, vm: &VirtualMachine) -> PyResult<Wtf8Buf> {
// Fallback: build repr from properties directly
if let Ok(Some(state)) =
vm.get_attribute_opt(future.to_owned(), vm.ctx.intern_str("_state"))
{
let s = state
.str(vm)
.map(|s| s.as_wtf8().to_lowercase())
.unwrap_or_else(|_| Wtf8Buf::from("unknown"));
return Ok(s);
}
Ok(Wtf8Buf::from("state=unknown"))
}
fn get_task_repr_info(task: &PyObject, vm: &VirtualMachine) -> PyResult<Wtf8Buf> {
// vm.import returns the top-level module, get base_tasks submodule
match vm
.import("asyncio.base_tasks", 0)
.and_then(|asyncio| asyncio.get_attr(vm.ctx.intern_str("base_tasks"), vm))
{
Ok(base_tasks) => {
match vm.get_attribute_opt(base_tasks, vm.ctx.intern_str("_task_repr_info")) {
Ok(Some(func)) => {
let info: PyObjectRef = func.call((task.to_owned(),), vm)?;
let list: PyListRef = info.downcast().map_err(|_| {
vm.new_type_error("_task_repr_info should return a list")
})?;
let mut result = Wtf8Buf::new();
let parts = list.borrow_vec();
for (i, x) in parts.iter().enumerate() {
if i > 0 {
result.push_str(" ");
}
result.push_wtf8(x.str(vm)?.as_wtf8());
}
Ok(result)
}
_ => get_future_repr_info(task, vm),
}
}
Err(_) => get_future_repr_info(task, vm),
}
}
#[pyattr]
#[pyclass(name = "FutureIter", module = "_asyncio", traverse)]
#[derive(Debug, PyPayload)]
struct PyFutureIter {
future: PyRwLock<Option<PyObjectRef>>,
}
#[pyclass(with(IterNext, Iterable))]
impl PyFutureIter {
#[pymethod]
fn send(&self, _value: PyObjectRef, vm: &VirtualMachine) -> PyResult {
let future = self.future.read().clone();
let future = match future {
Some(f) => f,
None => return Err(vm.new_stop_iteration(None)),
};
// Try to get blocking flag (check Task first since it inherits from Future)
let blocking = if let Some(task) = future.downcast_ref::<PyTask>() {
task.base.fut_blocking.load(Ordering::Relaxed)
} else if let Some(fut) = future.downcast_ref::<PyFuture>() {
fut.fut_blocking.load(Ordering::Relaxed)
} else {
// For non-native futures, check the attribute
vm.get_attribute_opt(
future.clone(),
vm.ctx.intern_str("_asyncio_future_blocking"),
)?
.map(|v| v.try_to_bool(vm))
.transpose()?
.unwrap_or(false)
};
// Check if future is done
let done = vm.call_method(&future, "done", ())?;
if done.try_to_bool(vm)? {
*self.future.write() = None;
let result = vm.call_method(&future, "result", ())?;
return Err(vm.new_stop_iteration(Some(result)));
}
// If still pending and blocking is already set, raise RuntimeError
// This means await wasn't used with future
if blocking {
return Err(vm.new_runtime_error("await wasn't used with future"));
}
// First call: set blocking flag and yield the future (check Task first)
if let Some(task) = future.downcast_ref::<PyTask>() {
task.base.fut_blocking.store(true, Ordering::Relaxed);
} else if let Some(fut) = future.downcast_ref::<PyFuture>() {
fut.fut_blocking.store(true, Ordering::Relaxed);
} else {
future.set_attr(
vm.ctx.intern_str("_asyncio_future_blocking"),
vm.ctx.true_value.clone(),
vm,
)?;
}
Ok(future)