Skip to main content

rust_css_parser/bindings/
mod.rs

1//! Javascript bindings: one call interface shared by the N-API addon (`extensions/css-parser-napi`) and the WASM
2//! module (`extensions/css-parser-wasm`). The backends are separate crates of the workspace: this crate only
3//! provides the exchange buffer, the arena handles and the dispatch of the calls.
4//!
5//! Javascript encodes a call (`[method, ...arguments]`, see [`value`]) into the exchange buffer and calls `call()`;
6//! the result is encoded back into the exchange buffer. The arena columns are not exchanged: javascript reads and
7//! writes them through typed array views of the rust memory (see `column()` in the backends), refreshed when the
8//! arena generation changes. The callbacks (visitors, `load`, `generateScopedName`, walk filters, ...) are called
9//! through the backend `host_call()`: the arguments and the result go through the exchange buffer too. The buffer is
10//! decoded before the work starts and encoded when it ends, so the reentrant calls (a visitor that calls the arena)
11//! share it safely.
12
13pub mod api;
14pub mod value;
15
16use crate::ast::arena::AstArena;
17use crate::host::{Host, HostError, HostValue};
18use std::cell::RefCell;
19use std::rc::Rc;
20use value::Val;
21
22thread_local! {
23    /// the exchange buffer
24    pub static EXCHANGE: RefCell<Vec<u8>> = RefCell::new(Vec::with_capacity(1 << 16));
25    /// the arenas used by javascript, by handle (1 based). a handle is released by `freeArena`
26    static ARENAS: RefCell<Vec<Option<Rc<AstArena>>>> = const { RefCell::new(Vec::new()) };
27    /// the backend callback function: encoded request -> encoded result (`None` outside of a binding)
28    static HOST_CALL: RefCell<Option<fn(&[u8]) -> Vec<u8>>> = const { RefCell::new(None) };
29}
30
31/// write bytes at the start of the exchange buffer. the buffer never shrinks: javascript keeps a view of its whole
32/// length and writes the next request anywhere in it
33pub fn write_exchange(bytes: &[u8]) {
34    EXCHANGE.with(|e| {
35        let mut buffer = e.borrow_mut();
36        if buffer.len() < bytes.len() {
37            buffer.resize(bytes.len(), 0);
38        }
39        buffer[..bytes.len()].copy_from_slice(bytes);
40    });
41}
42
43thread_local! {
44    /// the buffers given to javascript, by id (1 based), until javascript takes them
45    static OUTPUTS: RefCell<Vec<Option<Vec<u8>>>> = const { RefCell::new(Vec::new()) };
46}
47
48/// give a buffer to javascript without a copy: its whole capacity becomes the `ArrayBuffer`, the content is a view
49/// of its length (like the output buffer of the typescript writer)
50pub fn give_output(mut bytes: Vec<u8>) -> Val {
51    let len = bytes.len() as u32;
52    // the spare capacity is part of the ArrayBuffer: initialized
53    bytes.resize(bytes.capacity(), 0);
54    OUTPUTS.with(|o| {
55        let mut outputs = o.borrow_mut();
56        let entry = Some(bytes);
57        let id = match outputs.iter().position(|x| x.is_none()) {
58            Some(i) => {
59                outputs[i] = entry;
60                i + 1
61            }
62            None => {
63                outputs.push(entry);
64                outputs.len()
65            }
66        };
67        Val::Output(id as u32, len)
68    })
69}
70
71/// take a buffer given to javascript
72pub fn take_output(id: u32) -> Option<Vec<u8>> {
73    OUTPUTS.with(|o| o.borrow_mut().get_mut((id as usize).wrapping_sub(1)).and_then(|x| x.take()))
74}
75
76/// install the backend callback function
77pub fn set_host_call(f: fn(&[u8]) -> Vec<u8>) {
78    HOST_CALL.with(|h| *h.borrow_mut() = Some(f));
79}
80
81/// the handle of an arena: an arena already known keeps its handle
82pub fn arena_handle(arena: &Rc<AstArena>) -> u32 {
83    ARENAS.with(|a| {
84        let mut arenas = a.borrow_mut();
85        if let Some(index) = arenas.iter().position(|x| x.as_ref().is_some_and(|x| Rc::ptr_eq(x, arena))) {
86            return index as u32 + 1;
87        }
88        if let Some(index) = arenas.iter().position(|x| x.is_none()) {
89            arenas[index] = Some(arena.clone());
90            return index as u32 + 1;
91        }
92        arenas.push(Some(arena.clone()));
93        arenas.len() as u32
94    })
95}
96
97/// the arena of a handle
98pub fn arena_of(handle: u32) -> Result<Rc<AstArena>, HostError> {
99    ARENAS.with(|a| a.borrow().get((handle as usize).wrapping_sub(1)).cloned().flatten()).ok_or_else(|| HostError(format!("invalid arena handle {}", handle)))
100}
101
102/// release a handle: the arena is dropped when no other reference remains
103pub fn free_arena(handle: u32) {
104    ARENAS.with(|a| {
105        if let Some(slot) = a.borrow_mut().get_mut((handle as usize).wrapping_sub(1)) {
106            *slot = None;
107        }
108    });
109}
110
111/// call a javascript callback: `[callback id, arena, ...arguments]` -> result
112pub fn call_js(callback: u32, arena: Option<&Rc<AstArena>>, args: Vec<Val>) -> Result<Val, HostError> {
113    let mut request = Vec::with_capacity(64);
114    let mut list = vec![Val::Num(callback as f64), arena.map_or(Val::Undefined, |a| Val::Arena(arena_handle(a)))];
115    list.extend(args);
116    Val::Array(list).encode(&mut request);
117    let f = HOST_CALL.with(|h| *h.borrow()).ok_or_else(|| HostError("no javascript host".into()))?;
118    let response = f(&request);
119    match Val::decode(&response, &mut 0) {
120        Val::Error(message) => Err(HostError(message.to_string())),
121        value => Ok(value),
122    }
123}
124
125/// the javascript host of the parser: the callbacks of the options (visitors, loaders, ...)
126pub struct JsHost;
127
128impl Host for JsHost {
129    fn call(&self, callback: u32, arena: Option<&Rc<AstArena>>, args: Vec<HostValue>) -> Result<HostValue, HostError> {
130        let handle = arena.map_or(0, arena_handle);
131        let args = args.iter().map(|a| Val::from_host(a, handle)).collect();
132        call_js(callback, arena, args).map(|v| v.to_host())
133    }
134
135    fn arena(&self, handle: u32) -> Option<Rc<AstArena>> {
136        arena_of(handle).ok()
137    }
138}
139
140/// run the call encoded in the exchange buffer (`[method, ...arguments]`) and encode its result in place. a panic
141/// is returned as an error
142pub fn call(length: usize) -> usize {
143    let request = EXCHANGE.with(|e| {
144        let buffer = e.borrow();
145        Val::decode(&buffer[..length.min(buffer.len())], &mut 0)
146    });
147    let (method, args) = match request {
148        Val::Array(mut items) if !items.is_empty() => {
149            let method = items.remove(0);
150            (method.as_str().unwrap_or("").to_string(), items)
151        }
152        _ => (String::new(), Vec::new()),
153    };
154    let result = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| api::dispatch(&method, args))) {
155        Ok(Ok(value)) => value,
156        Ok(Err(error)) => Val::Error(Rc::from(error.0.as_str())),
157        Err(panic) => {
158            let message = panic.downcast_ref::<String>().cloned().or_else(|| panic.downcast_ref::<&str>().map(|s| s.to_string())).unwrap_or_default();
159            Val::Error(Rc::from(format!("internal error in {}: {}", method, message).as_str()))
160        }
161    };
162    let mut out = Vec::with_capacity(256);
163    result.encode(&mut out);
164    write_exchange(&out);
165    out.len()
166}