use crate::host::{self, with_host, PyObj};
use fusevm::Value;
use std::cell::RefCell;
use std::collections::VecDeque;
use std::rc::Rc;
struct FutureCell {
done: bool,
cancelled: bool,
result: Value,
exc: Option<Value>,
py_callbacks: Vec<Value>,
native_callbacks: Vec<Box<dyn FnOnce()>>,
coro: Option<Value>,
is_task: bool,
step_scheduled: bool,
must_cancel: bool,
name: String,
obj: Value,
#[cfg(feature = "stdlib-ffi")]
context: Option<crate::ffi::TaskContext>,
}
enum Callback {
Native(Box<dyn FnOnce()>),
Py { func: Value, args: Vec<Value> },
}
struct Timer {
when: f64,
seq: u64,
cancelled: bool,
cb: Callback,
}
enum AsyncObj {
Event {
flag: bool,
waiters: Vec<u32>, },
Lock {
locked: bool,
waiters: VecDeque<u32>, },
Queue {
items: VecDeque<Value>,
maxsize: usize, getters: VecDeque<u32>,
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,
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()))
}
pub fn reset() {
with_loop(|l| *l = EventLoop::default());
}
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
}
pub fn new_future() -> Value {
new_cell(false, None, "Future".to_string())
}
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,
}
}
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())
}
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())
}
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),
)
});
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
}
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)
}
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)
}
fn fail_quietly(id: u32, exc: Value) {
settle(id, Value::Undef, Some(exc), false);
}
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));
}
}
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(|_| ()),
}
}
fn run_once() -> Result<(), String> {
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));
}
let due: Vec<Callback> = with_loop(|l| {
let now = l.time;
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));
}
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(())
}
fn has_work() -> bool {
with_loop(|l| !l.ready.is_empty() || l.timers.iter().any(|t| !t.cancelled))
}
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?;
if let Some(exc) = future_exc(id) {
return Err(host::raise_value(&exc).unwrap_or_else(|e| e));
}
Ok(future_result(id))
}
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)
}
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)));
}
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);
let task = future_obj(id);
schedule_step(task);
} else {
settle(id, Value::Undef, Some(make_cancelled_error()), true);
}
true
}
fn make_cancelled_error() -> Value {
with_host(|h| {
h.alloc(PyObj::Exception {
class: "CancelledError".into(),
args: vec![],
})
})
}
fn is_cancelled_exc(exc: &Value) -> bool {
matches!(
with_host(|h| h.get(exc).cloned()),
Some(PyObj::Exception { class, .. }) if class == "CancelledError"
)
}
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)
}
};
#[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)) => {
match future_id(&awaited) {
Some(aid) => {
let task2 = task.clone();
add_done_native(aid, Box::new(move || schedule_step(task2)));
}
None => {
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);
if is_cancelled_exc(&exc) {
settle(id, Value::Undef, Some(exc), true);
} else {
fail_quietly(id, exc);
}
}
}
}
fn take_pending_exc(err: &str) -> Value {
with_host(|h| {
if let Some(e) = h.exc.take() {
e
} else {
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 })
}
})
}
pub fn await_value(x: Value) -> Result<Value, String> {
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));
}
host::gen_yield_awaiting(x.clone())?;
}
}
if host::is_async_generator(&x) {
return drive_async_gen(&x);
}
if host::is_coroutine(&x) {
return drive_delegate(&x);
}
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))
)))
}
fn drive_async_gen(agen: &Value) -> Result<Value, String> {
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)
}
None => host::gen_resume(agen, Value::Undef),
};
match stepped {
Ok(Some(y)) => {
if host::cur_gen_awaiting(agen) {
host::gen_yield_awaiting(y)?;
} else if closing {
return Err("RuntimeError: async generator ignored GeneratorExit".to_string());
} else {
return Ok(y);
}
}
Ok(None) => {
if closing {
return Ok(Value::Undef);
}
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) => {
if closing && (e.contains("GeneratorExit") || e.contains("StopAsyncIteration")) {
with_host(|h| {
h.error = None;
h.exc = None;
});
return Ok(Value::Undef);
}
return Err(e);
}
}
}
}
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);
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}'"
)),
}
}
fn drive_delegate(sub: &Value) -> Result<Value, String> {
let mut send = Value::Undef;
loop {
match host::gen_resume(sub, send) {
Ok(Some(y)) => {
send = host::gen_yield_awaiting(y)?;
}
Ok(None) => return Ok(host::coro_return_value(sub)),
Err(e) => return Err(e),
}
}
}
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)
}
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
}
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, 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)
}
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();
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_future(iid);
let e = with_host(|h| {
h.alloc(PyObj::Exception {
class: "TimeoutError".into(),
args: vec![],
})
});
fail_quietly(oid, e);
}
})),
);
}
Ok(outer)
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum ReturnWhen {
FirstCompleted,
FirstException,
AllCompleted,
}
impl ReturnWhen {
pub fn parse(s: &str) -> ReturnWhen {
match s {
"FIRST_COMPLETED" => ReturnWhen::FirstCompleted,
"FIRST_EXCEPTION" => ReturnWhen::FirstException,
_ => ReturnWhen::AllCompleted,
}
}
}
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);
}
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)
}
pub fn as_completed(aws: Vec<Value>) -> Result<Value, String> {
let tasks: Vec<Value> = aws
.into_iter()
.map(ensure_future)
.collect::<Result<_, _>>()?;
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() {
m.insert(crate::host::PKey::Int(i as i64), v.clone());
}
m
}
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 }))
}
pub fn new_event() -> Value {
new_async_obj(AsyncObj::Event {
flag: false,
waiters: Vec::new(),
})
}
pub fn new_lock() -> Value {
new_async_obj(AsyncObj::Lock {
locked: false,
waiters: VecDeque::new(),
})
}
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,
}
}
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",
})
}
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())
}
})
}
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) {
(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)
}
(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);
let fut = new_future();
settle(future_id(&fut).unwrap(), Value::Bool(false), None, false);
Ok(fut)
}
(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();
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();
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)
)),
}
}
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), None => {
*locked = false;
None
}
}
} else {
None
}
});
if let Some(w) = next {
settle(w, Value::Bool(true), None, false);
}
}
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,
})
}
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);
}
}
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();
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()),
}
}
pub fn event_loop() -> Value {
with_host(|h| h.alloc(PyObj::EventLoop))
}
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,
})
}
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}'"
)),
}
}
fn handle_obj() -> Value {
new_future()
}
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)
)),
}
}
pub fn future_type_name(id: u32) -> &'static str {
if with_loop(|l| l.futures[id as usize].is_task) {
"Task"
} else {
"Future"
}
}
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,
}
}
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()
})
}