use std::cell::{Cell, RefCell};
use std::collections::{HashMap, VecDeque};
use std::rc::Rc;
use std::sync::Arc;
use std::sync::atomic::{AtomicI64, Ordering};
use crate::async_state::{ResumeContinuation, Task};
use crate::class::BridgedClassDef;
use crate::env::Environment;
use crate::value::Value;
static NEXT_CONTEXT_ID: AtomicI64 = AtomicI64::new(1);
pub type RawPort = (Value, Rc<RefCell<bool>>);
pub struct ContextState {
pub id: i64,
pub libraries: RefCell<HashMap<String, Rc<RefCell<Environment>>>>,
pub bridged: RefCell<HashMap<String, Arc<BridgedClassDef>>>,
pub receive_ports: RefCell<HashMap<i64, Value>>,
pub raw_ports: RefCell<HashMap<i64, RawPort>>,
pub yield_star_resumes: RefCell<HashMap<usize, ResumeContinuation>>,
pub tasks: RefCell<VecDeque<Task>>,
pub clock: Cell<i64>,
pub permissions: crate::permission::PermissionSet,
pub virtual_modules: RefCell<HashMap<String, String>>,
pub module_libraries: RefCell<HashMap<String, Vec<Arc<BridgedClassDef>>>>,
}
impl ContextState {
pub fn new() -> Rc<Self> {
Rc::new(Self {
id: NEXT_CONTEXT_ID.fetch_add(1, Ordering::Relaxed),
libraries: RefCell::new(HashMap::new()),
bridged: RefCell::new(HashMap::new()),
receive_ports: RefCell::new(HashMap::new()),
raw_ports: RefCell::new(HashMap::new()),
yield_star_resumes: RefCell::new(HashMap::new()),
tasks: RefCell::new(VecDeque::new()),
clock: Cell::new(0),
permissions: crate::permission::PermissionSet::new(),
virtual_modules: RefCell::new(HashMap::new()),
module_libraries: RefCell::new(HashMap::new()),
})
}
}
thread_local! {
static CURRENT: RefCell<Vec<Rc<ContextState>>> = const { RefCell::new(Vec::new()) };
}
pub fn try_current() -> Option<Rc<ContextState>> {
CURRENT.with(|c| c.borrow().last().cloned())
}
pub fn current() -> Rc<ContextState> {
try_current().unwrap_or_else(|| {
panic!("d4rt: stdlib state accessed outside of a Context (missing with_current scope)")
})
}
pub fn with_current<T>(state: &Rc<ContextState>, f: impl FnOnce() -> T) -> T {
CURRENT.with(|c| c.borrow_mut().push(state.clone()));
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f));
CURRENT.with(|c| {
c.borrow_mut().pop();
});
match result {
Ok(v) => v,
Err(payload) => std::panic::resume_unwind(payload),
}
}