Skip to main content

rust_css_parser/
host.rs

1//! Host (javascript) interface: callbacks, values exchanged with the host, and the executor of the async ports.
2//!
3//! The typescript pipeline awaits host promises (visitors, loaders, scoped name generators). The rust ports are
4//! `async fn`s: a [`HostPromise`] future is pending until the host settles the promise ([`settle_promise`]). The host
5//! drives a [`Task`]: `poll()` returns the ids of the pending promises, the host awaits them, settles them and polls
6//! again. The same mechanism serves the N-API and the WASM bindings: no thread, no runtime.
7
8use 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/// a value exchanged with the host
18#[derive(Clone, Debug, Default)]
19pub enum HostValue {
20    #[default]
21    Undefined,
22    Null,
23    Bool(bool),
24    Number(f64),
25    Str(Rc<str>),
26    /// utf-8 bytes (`ArrayBuffer`, `Uint8Array`), not copied by the host
27    Bytes(Rc<[u8]>),
28    /// a view (`AstArenaNode`) of another arena: the arena handle and the node id
29    ForeignNode(u32, u32),
30    /// a plain object (`PlainAstNode`, `PlainToken`, json data)
31    Plain(Plain),
32    Array(Vec<HostValue>),
33    /// a pending host promise
34    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/// a host definition: the javascript visitor maps and options, with the functions replaced by callback ids
51#[derive(Clone, Debug)]
52pub enum HostDef {
53    /// a function: its callback id and its name (`Function.prototype.name`)
54    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    /// `Object.entries()`: the keys of an object, the indexes of an array
65    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    /// `typeof value === "object"` (arrays included, null excluded)
85    pub fn is_object(&self) -> bool {
86        matches!(self, HostDef::Object(_) | HostDef::Array(_))
87    }
88}
89
90/// error raised by the host or by the port (`throw new Error(message)`)
91#[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
112/// the host: calls the javascript callbacks
113pub trait Host {
114    /// call a callback. the arena is the arena being processed (the callbacks receive it as their first argument)
115    fn call(&self, callback: u32, arena: Option<&Rc<AstArena>>, args: Vec<HostValue>) -> Result<HostValue, HostError>;
116
117    /// the arena of a handle (views of other arenas returned by the callbacks)
118    fn arena(&self, handle: u32) -> Option<Rc<AstArena>>;
119}
120
121/// a host without callbacks (rust callers)
122pub 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    /// the settled promises, by id
136    static SETTLED: RefCell<HashMap<u32, Result<HostValue, HostError>>> = RefCell::new(HashMap::default());
137    /// the promises awaited by the task being polled
138    static PENDING: RefCell<Vec<u32>> = const { RefCell::new(Vec::new()) };
139}
140
141/// settle a host promise: the task that awaits it is polled again by the host
142pub fn settle_promise(id: u32, result: Result<HostValue, HostError>) {
143    SETTLED.with(|s| s.borrow_mut().insert(id, result));
144}
145
146/// a host promise awaited by the rust code
147pub 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
168/// await a host value: a promise is awaited, the other values are returned
169pub 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    // SAFETY: the vtable functions do nothing
183    unsafe { Waker::from_raw(RawWaker::new(std::ptr::null(), &VTABLE)) }
184}
185
186/// an async computation driven by the host
187pub struct Task<T> {
188    future: Pin<Box<dyn Future<Output = T>>>,
189}
190
191/// state of a task after a poll
192pub enum TaskState<T> {
193    Done(T),
194    /// the ids of the host promises the task waits for
195    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    /// run the task until it completes or waits for host promises
204    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
215/// run a future synchronously: the sync api (`parseSync()`). a pending host promise is an error, like the typescript
216/// sync functions that do not await
217pub 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}