1use crate::ast::arena::AstArena;
9use crate::plain::Plain;
10use std::cell::RefCell;
11use crate::utils::fx::HashMap;
12use std::future::Future;
13use std::pin::Pin;
14use std::rc::Rc;
15use std::task::{Context, Poll, RawWaker, RawWakerVTable, Waker};
16
17#[derive(Clone, Debug, Default)]
19pub enum HostValue {
20 #[default]
21 Undefined,
22 Null,
23 Bool(bool),
24 Number(f64),
25 Str(Rc<str>),
26 Bytes(Rc<[u8]>),
28 ForeignNode(u32, u32),
30 Plain(Plain),
32 Array(Vec<HostValue>),
33 Promise(u32),
35}
36
37impl HostValue {
38 pub fn is_nullish(&self) -> bool {
39 matches!(self, HostValue::Undefined | HostValue::Null)
40 }
41
42 pub fn as_str(&self) -> Option<&str> {
43 match self {
44 HostValue::Str(s) => Some(s),
45 _ => None,
46 }
47 }
48}
49
50#[derive(Clone, Debug)]
52pub enum HostDef {
53 Fn { id: u32, name: Rc<str> },
55 Object(Vec<(Rc<str>, HostDef)>),
56 Array(Vec<HostDef>),
57 Number(f64),
58 Str(Rc<str>),
59 Bool(bool),
60 Null,
61}
62
63impl HostDef {
64 pub fn entries(&self) -> Vec<(Rc<str>, HostDef)> {
66 match self {
67 HostDef::Object(entries) => entries.clone(),
68 HostDef::Array(items) => items.iter().enumerate().map(|(i, v)| (Rc::from(i.to_string().as_str()), v.clone())).collect(),
69 _ => Vec::new(),
70 }
71 }
72
73 pub fn get(&self, key: &str) -> Option<&HostDef> {
74 match self {
75 HostDef::Object(entries) => entries.iter().find(|(k, _)| &**k == key).map(|(_, v)| v),
76 _ => None,
77 }
78 }
79
80 pub fn is_fn(&self) -> bool {
81 matches!(self, HostDef::Fn { .. })
82 }
83
84 pub fn is_object(&self) -> bool {
86 matches!(self, HostDef::Object(_) | HostDef::Array(_))
87 }
88}
89
90#[derive(Clone, Debug, PartialEq)]
92pub struct HostError(pub String);
93
94impl std::fmt::Display for HostError {
95 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
96 f.write_str(&self.0)
97 }
98}
99
100impl From<String> for HostError {
101 fn from(s: String) -> Self {
102 HostError(s)
103 }
104}
105
106impl From<&str> for HostError {
107 fn from(s: &str) -> Self {
108 HostError(s.to_string())
109 }
110}
111
112pub trait Host {
114 fn call(&self, callback: u32, arena: Option<&Rc<AstArena>>, args: Vec<HostValue>) -> Result<HostValue, HostError>;
116
117 fn arena(&self, handle: u32) -> Option<Rc<AstArena>>;
119}
120
121pub struct NoHost;
123
124impl Host for NoHost {
125 fn call(&self, _callback: u32, _arena: Option<&Rc<AstArena>>, _args: Vec<HostValue>) -> Result<HostValue, HostError> {
126 Err(HostError("no host".into()))
127 }
128
129 fn arena(&self, _handle: u32) -> Option<Rc<AstArena>> {
130 None
131 }
132}
133
134thread_local! {
135 static SETTLED: RefCell<HashMap<u32, Result<HostValue, HostError>>> = RefCell::new(HashMap::default());
137 static PENDING: RefCell<Vec<u32>> = const { RefCell::new(Vec::new()) };
139}
140
141pub fn settle_promise(id: u32, result: Result<HostValue, HostError>) {
143 SETTLED.with(|s| s.borrow_mut().insert(id, result));
144}
145
146pub struct HostPromise(pub u32);
148
149impl Future for HostPromise {
150 type Output = Result<HostValue, HostError>;
151
152 fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Self::Output> {
153 match SETTLED.with(|s| s.borrow_mut().remove(&self.0)) {
154 Some(result) => Poll::Ready(result),
155 None => {
156 PENDING.with(|p| {
157 let mut p = p.borrow_mut();
158 if !p.contains(&self.0) {
159 p.push(self.0);
160 }
161 });
162 Poll::Pending
163 }
164 }
165 }
166}
167
168pub async fn resolve(value: Result<HostValue, HostError>) -> Result<HostValue, HostError> {
170 match value? {
171 HostValue::Promise(id) => HostPromise(id).await,
172 value => Ok(value),
173 }
174}
175
176fn noop_waker() -> Waker {
177 fn clone(_: *const ()) -> RawWaker {
178 RawWaker::new(std::ptr::null(), &VTABLE)
179 }
180 fn noop(_: *const ()) {}
181 static VTABLE: RawWakerVTable = RawWakerVTable::new(clone, noop, noop, noop);
182 unsafe { Waker::from_raw(RawWaker::new(std::ptr::null(), &VTABLE)) }
184}
185
186pub struct Task<T> {
188 future: Pin<Box<dyn Future<Output = T>>>,
189}
190
191pub enum TaskState<T> {
193 Done(T),
194 Pending(Vec<u32>),
196}
197
198impl<T> Task<T> {
199 pub fn new(future: impl Future<Output = T> + 'static) -> Self {
200 Self { future: Box::pin(future) }
201 }
202
203 pub fn poll(&mut self) -> TaskState<T> {
205 PENDING.with(|p| p.borrow_mut().clear());
206 let waker = noop_waker();
207 let mut cx = Context::from_waker(&waker);
208 match self.future.as_mut().poll(&mut cx) {
209 Poll::Ready(value) => TaskState::Done(value),
210 Poll::Pending => TaskState::Pending(PENDING.with(|p| std::mem::take(&mut *p.borrow_mut()))),
211 }
212 }
213}
214
215pub fn block_on<T>(future: impl Future<Output = Result<T, HostError>> + 'static) -> Result<T, HostError> {
218 let mut task = Task::new(future);
219 match task.poll() {
220 TaskState::Done(value) => value,
221 TaskState::Pending(_) => Err(HostError("a promise was returned to a synchronous call".into())),
222 }
223}