Skip to main content

blitz_script/native/
mod.rs

1//! Bounded Rust script guest operating directly on a borrowed Blitz document.
2//!
3//! Source is parsed into retained syntax trees. Embedder resources cross the
4//! typed bridge; no source strings are synthesized for host operations.
5
6use std::collections::{BTreeMap, VecDeque};
7use std::rc::Rc;
8use std::sync::atomic::{AtomicU64, Ordering};
9use std::task::Waker;
10
11use crate::DiagnosticEntry;
12use crate::native_host::NativeIntrinsic;
13use blitz_dom::{BaseDocument, NodeId};
14
15mod buffer;
16mod builtins;
17mod dom;
18mod events;
19mod exec;
20mod message;
21mod proxy;
22mod regexp;
23mod runtime;
24pub mod syntax;
25mod value;
26mod web;
27pub use runtime::NativeStorageBridge;
28pub use value::{Env, Environment, Error, Function, Object, Property, Result, Value};
29
30/// A rooted, already parsed callback ready for execution on its owning realm.
31#[derive(Clone)]
32pub struct HostJob {
33    pub callback: Value,
34    pub this: Value,
35    pub args: Vec<Value>,
36}
37
38/// Embedder-owned resources used by one guest and its live document.
39///
40/// Returning `None` leaves an operation to the standard guest bindings. The
41/// embedder queues callbacks instead of re-entering an already borrowed guest.
42pub trait RuntimeBridge: 'static {
43    fn install(&mut self, _global: &Value) -> Result<()> {
44        Ok(())
45    }
46    fn get(
47        &mut self,
48        _document: &mut BaseDocument,
49        _receiver: &Value,
50        _key: &str,
51    ) -> Result<Option<Value>> {
52        Ok(None)
53    }
54    fn set(
55        &mut self,
56        _document: &mut BaseDocument,
57        _receiver: &Value,
58        _key: &str,
59        _value: Value,
60    ) -> Result<bool> {
61        Ok(false)
62    }
63    fn call(
64        &mut self,
65        _document: &mut BaseDocument,
66        _name: &str,
67        _this: Value,
68        _arguments: Vec<Value>,
69        _construct: bool,
70    ) -> Result<Option<Value>> {
71        Ok(None)
72    }
73    fn poll(
74        &mut self,
75        _document: &mut BaseDocument,
76        _waker: Option<&Waker>,
77        _run_timers: bool,
78    ) -> Result<Vec<HostJob>> {
79        Ok(Vec::new())
80    }
81    fn has_pending_jobs(&self) -> bool {
82        false
83    }
84    fn pending_task_count(&self) -> u64 {
85        u64::from(self.has_pending_jobs())
86    }
87    fn wait_for_work(&mut self) -> Result<()> {
88        Ok(())
89    }
90    fn teardown(&mut self) {}
91}
92
93/// A persistent realm with bounded script entry and typed embedder bindings.
94pub struct Guest<B: RuntimeBridge> {
95    heap: Rc<std::cell::RefCell<value::RealmHeap>>,
96    pub bridge: B,
97    pub global: Value,
98    pub env: Env,
99    pub nodes: BTreeMap<NodeId, Value>,
100    pub jobs: VecDeque<HostJob>,
101    pub callbacks: BTreeMap<u64, Value>,
102    pub next_callback: u64,
103    pub scope_id: u64,
104    pub generation: u64,
105    pub steps: usize,
106    await_resumptions: usize,
107    message_clone_depth: usize,
108    pending_message_bytes: Rc<std::cell::Cell<usize>>,
109    pub depth: usize,
110    call_stack: Vec<String>,
111    pub disposed: bool,
112    pub visible: bool,
113    pub frozen: bool,
114    pub ready_state: String,
115    pub console: Vec<DiagnosticEntry>,
116    pub errors: Vec<DiagnosticEntry>,
117    pub ipc_handler: Option<Box<dyn Fn(String)>>,
118    pub intrinsics: BTreeMap<String, NativeIntrinsic<Self>>,
119}
120
121/// A statically typed owner used by the document runtime driver.
122pub struct GuestHost<B: RuntimeBridge>(pub Guest<B>);
123
124static NEXT_REALM: AtomicU64 = AtomicU64::new(1);
125impl<B: RuntimeBridge> Guest<B> {
126    pub fn new(bridge: B) -> Self {
127        let scope_id = NEXT_REALM.fetch_add(1, Ordering::Relaxed);
128        let heap = Rc::new(std::cell::RefCell::new(value::RealmHeap::default()));
129        heap.borrow_mut().realm = scope_id;
130        let _scope = value::HeapScope::enter(&heap);
131        let global = Value::object("Global");
132        let mut guest = Self {
133            heap,
134            bridge,
135            global: global.clone(),
136            env: Environment::new(None),
137            nodes: BTreeMap::new(),
138            jobs: VecDeque::new(),
139            callbacks: BTreeMap::new(),
140            next_callback: 1,
141            scope_id,
142            generation: 1,
143            steps: 0,
144            await_resumptions: 0,
145            message_clone_depth: 0,
146            pending_message_bytes: Rc::default(),
147            depth: 0,
148            call_stack: Vec::new(),
149            disposed: false,
150            visible: true,
151            frozen: false,
152            ready_state: "loading".into(),
153            console: Vec::new(),
154            errors: Vec::new(),
155            ipc_handler: None,
156            intrinsics: BTreeMap::new(),
157        };
158        for name in ["globalThis", "window", "self", "top", "parent"] {
159            global.put(name, global.clone());
160        }
161        global.put("frameElement", Value::Null);
162        global.put("undefined", Value::Undefined);
163        global.put("NaN", Value::Number(f64::NAN));
164        global.put("Infinity", Value::Number(f64::INFINITY));
165        guest.install_builtins();
166        guest.install_web();
167        guest.install_dom();
168        guest.install_events();
169        guest.global.put("RegExp", Value::native("RegExp"));
170        guest.global.put("WeakMap", Value::native("WeakMap"));
171        guest.global.put("WeakSet", Value::native("WeakSet"));
172        guest
173            .global
174            .put("queueMicrotask", Value::native("Guest.queueMicrotask"));
175        let console = Value::object("Console");
176        for method in ["log", "info", "warn", "error", "debug"] {
177            console.put(method, Value::native(format!("Console.{method}")));
178        }
179        guest.global.put("console", console);
180        guest
181    }
182    pub(super) fn begin_execution(&mut self) {
183        self.steps = 0;
184        self.await_resumptions = 0;
185    }
186    pub(super) fn resume_after_await(&mut self) -> Result<()> {
187        // A settled await resumes a new turn, bounded separately from the
188        // synchronous instruction limit so repeated awaits cannot renew it forever.
189        if self.await_resumptions >= 1_024 {
190            return Err(Error::new(
191                "RangeError",
192                "await resumption budget exhausted",
193            ));
194        }
195        self.await_resumptions += 1;
196        self.steps = 0;
197        Ok(())
198    }
199    pub fn tick(&mut self) -> Result<()> {
200        if self.heap.borrow_mut().exhausted() {
201            return Err(Error::new(
202                "QuotaExceededError",
203                "realm allocation limit exceeded",
204            ));
205        }
206        if self.disposed {
207            return Err(Error::new(
208                "InvalidStateError",
209                "script realm has been retired",
210            ));
211        }
212        self.steps = self.steps.saturating_add(1);
213        if self.steps > 2_000_000 {
214            return Err(Error::new(
215                "RangeError",
216                "script instruction budget exhausted",
217            ));
218        }
219        Ok(())
220    }
221    pub fn node(&mut self, id: NodeId) -> Value {
222        self.nodes
223            .entry(id)
224            .or_insert_with(|| {
225                let node = Value::object("Node");
226                if let Some(object) = node.as_object() {
227                    let mut object = object.borrow_mut();
228                    object.payload = Some(Rc::new(id));
229                    object.props.insert(
230                        "__node".into(),
231                        Property {
232                            value: Value::string(id.as_u64().to_string()),
233                            get: None,
234                            set: None,
235                            enumerable: false,
236                        },
237                    );
238                }
239                node
240            })
241            .clone()
242    }
243    pub fn queue(&mut self, callback: Value, this: Value, args: Vec<Value>) {
244        self.jobs.push_back(HostJob {
245            callback,
246            this,
247            args,
248        });
249    }
250    pub fn get_property(
251        &mut self,
252        document: &mut BaseDocument,
253        receiver: &Value,
254        key: &str,
255    ) -> Result<Value> {
256        self.tick()?;
257        if let Some(value) = self.proxy_get(document, receiver, key)? {
258            return Ok(value);
259        }
260        if let Some(object) = receiver.as_object() {
261            let property = {
262                let object = object.borrow();
263                if let Some(value) = object.binary_property(key) {
264                    return Ok(value);
265                }
266                object.props.get(key).cloned()
267            };
268            if let Some(property) = property {
269                if let Some(get) = property.get {
270                    return self.call(document, get, receiver.clone(), Vec::new(), false);
271                }
272                return Ok(property.value);
273            }
274        }
275        if key.parse::<usize>().is_ok() {
276            match receiver {
277                Value::String(units) => {
278                    let index = key.parse::<usize>().unwrap_or(usize::MAX);
279                    return Ok(units
280                        .get(index)
281                        .map_or(Value::Undefined, |unit| Value::String(Rc::from([*unit]))));
282                }
283                Value::Object(object)
284                    if !object.borrow().indexed.is_empty()
285                        || matches!(object.borrow().kind.as_str(), "Array" | "NodeList") =>
286                {
287                    return Ok(receiver.get(key));
288                }
289                _ => {}
290            }
291        }
292        if let Some(value) = self.bridge.get(document, receiver, key)? {
293            return Ok(value);
294        }
295        if let Some(value) = self.dom_get(document, receiver, key)? {
296            return Ok(value);
297        }
298        if let Some(value) = self.web_get(document, receiver, key)? {
299            return Ok(value);
300        }
301        if let Some(value) = self.events_get(document, receiver, key)? {
302            return Ok(value);
303        }
304        if let Some(value) = self.regexp_get(receiver, key) {
305            return Ok(value);
306        }
307        if let Some(value) = self.weak_get(receiver, key) {
308            return Ok(value);
309        }
310        if let Some(value) = self.builtin_get(document, receiver, key)? {
311            return Ok(value);
312        }
313        if let Some(object) = receiver.as_object() {
314            let mut prototype = object.borrow().prototype.clone();
315            let mut remaining = 256usize;
316            while let Some(value) = prototype {
317                if remaining == 0 {
318                    return Err(Error::new("RangeError", "prototype chain limit exceeded"));
319                }
320                remaining -= 1;
321                let Some(object) = value.as_object() else {
322                    break;
323                };
324                let property = object.borrow().props.get(key).cloned();
325                if let Some(property) = property {
326                    return if let Some(get) = property.get {
327                        self.call(document, get, receiver.clone(), Vec::new(), false)
328                    } else {
329                        Ok(property.value)
330                    };
331                }
332                prototype = object.borrow().prototype.clone();
333            }
334        }
335        if matches!(receiver, Value::Null | Value::Undefined) {
336            return Err(Error::type_error(format!(
337                "cannot read {key} of {}",
338                receiver.text()
339            )));
340        }
341        Ok(Value::Undefined)
342    }
343    pub fn set_property(
344        &mut self,
345        document: &mut BaseDocument,
346        receiver: &Value,
347        key: &str,
348        value: Value,
349    ) -> Result<()> {
350        self.tick()?;
351        if receiver.kind() == "Proxy" {
352            if !self.proxy_set(document, receiver, key, value)? {
353                return Err(Error::type_error("Proxy set trap rejected assignment"));
354            }
355            return Ok(());
356        }
357        if let Some(object) = receiver.as_object() {
358            let property = object.borrow().props.get(key).cloned();
359            if let Some(property) = property {
360                if let Some(set) = property.set {
361                    self.call(document, set, receiver.clone(), vec![value], false)?;
362                    return Ok(());
363                }
364                if property.get.is_some() {
365                    return Err(Error::type_error("property has no setter"));
366                }
367            }
368        }
369        if self.bridge.set(document, receiver, key, value.clone())?
370            || self.dom_set(document, receiver, key, value.clone())?
371            || self.web_set(document, receiver, key, value.clone())?
372            || self.events_set(document, receiver, key, value.clone())?
373        {
374            return Ok(());
375        }
376        if let Some(object) = receiver.as_object() {
377            let prototype = object.borrow().prototype.clone();
378            if let Some(prototype) = prototype {
379                if let Some(object) = prototype.as_object() {
380                    let setter = object.borrow().props.get(key).and_then(|p| p.set.clone());
381                    if let Some(setter) = setter {
382                        self.call(document, setter, receiver.clone(), vec![value], false)?;
383                        return Ok(());
384                    }
385                }
386            }
387            receiver.put(key, value.clone());
388            if receiver.same(&self.global) && self.env.borrow().bindings.contains_key(key) {
389                self.env.borrow_mut().bindings.insert(key.into(), value);
390            }
391            return Ok(());
392        }
393        Err(Error::type_error("property assignment requires an object"))
394    }
395    pub fn call(
396        &mut self,
397        document: &mut BaseDocument,
398        callee: Value,
399        this: Value,
400        args: Vec<Value>,
401        construct: bool,
402    ) -> Result<Value> {
403        let label = if callee.kind() == "Native" {
404            callee.get("__native").text()
405        } else {
406            let name = callee.get("name").text();
407            let location = callee
408                .as_object()
409                .and_then(|object| object.borrow().function.clone())
410                .and_then(|function| function.source_offset);
411            match location {
412                Some(offset) => format!(
413                    "{} at byte {offset}",
414                    if name == "undefined" || name.is_empty() {
415                        "<anonymous>"
416                    } else {
417                        &name
418                    }
419                ),
420                None => name,
421            }
422        };
423        self.call_stack.push(label.clone());
424        let result = self.call_inner(document, callee, this, args, construct);
425        if let Ok(value) = &result {
426            if matches!(
427                label.as_str(),
428                "Error" | "TypeError" | "RangeError" | "ReferenceError" | "SyntaxError"
429            ) {
430                value.put_hidden(
431                    "\0error_stack",
432                    Value::array(
433                        self.call_stack
434                            .iter()
435                            .rev()
436                            .take(64)
437                            .map(Value::string)
438                            .collect(),
439                    ),
440                );
441            }
442        }
443        self.call_stack.pop();
444        result.map_err(|mut error| {
445            if error.stack.len() < 64 {
446                error
447                    .stack
448                    .push(if label == "undefined" || label.is_empty() {
449                        String::from("<anonymous>")
450                    } else {
451                        label
452                    });
453            }
454            error
455        })
456    }
457
458    fn call_inner(
459        &mut self,
460        document: &mut BaseDocument,
461        callee: Value,
462        this: Value,
463        args: Vec<Value>,
464        construct: bool,
465    ) -> Result<Value> {
466        let _scope = value::HeapScope::enter(&self.heap);
467        self.tick()?;
468        if let Some(value) =
469            self.proxy_apply(document, &callee, this.clone(), args.clone(), construct)?
470        {
471            return Ok(value);
472        }
473        if callee.get("__native").text() == "Function.bound" {
474            let target = callee.get("__bound_target");
475            let mut arguments = callee.get("__bound_args").items();
476            arguments.extend(args);
477            return self.call(
478                document,
479                target,
480                callee.get("__bound_this"),
481                arguments,
482                construct,
483            );
484        }
485        let function = callee
486            .as_object()
487            .and_then(|object| object.borrow().function.clone());
488        if let Some(function) = function {
489            if callee
490                .as_object()
491                .and_then(|object| object.borrow().realm)
492                .is_some_and(|realm| realm != self.scope_id)
493            {
494                return Err(Error::new(
495                    "InvalidStateError",
496                    "function belongs to another realm",
497                ));
498            }
499            let this = if construct {
500                let instance = Value::object("Object");
501                if let Some(object) = instance.as_object() {
502                    let prototype = callee.get("prototype");
503                    if matches!(prototype, Value::Object(_)) {
504                        object.borrow_mut().prototype = Some(prototype);
505                    }
506                }
507                instance
508            } else {
509                this
510            };
511            return self.call_function(document, function, this, args, construct);
512        }
513        let name = callee.get("__native");
514        if matches!(name, Value::String(_)) {
515            let name = name.text();
516            if let Some(level) = name.strip_prefix("Console.") {
517                self.record_console(
518                    level,
519                    args.iter().map(Value::text).collect::<Vec<_>>().join(" "),
520                );
521                return Ok(Value::Undefined);
522            }
523            if name == "Guest.queueMicrotask" {
524                let callback = args.first().cloned().unwrap_or(Value::Undefined);
525                if !matches!(callback.kind().as_str(), "Function" | "Native") {
526                    return Err(Error::type_error("microtask callback must be callable"));
527                }
528                self.queue(callback, self.global.clone(), Vec::new());
529                return Ok(Value::Undefined);
530            }
531            if name == "Guest.deliverMessagePort" && callee.kind() == "Native" {
532                self.deliver_message_port(document, this)?;
533                return Ok(Value::Undefined);
534            }
535            if name == "IPC.postMessage" {
536                let Some(Value::String(message)) = args.first() else {
537                    return Err(Error::type_error("IPC message must be a string"));
538                };
539                let handler = self
540                    .ipc_handler
541                    .as_ref()
542                    .ok_or_else(|| Error::new("InvalidStateError", "IPC is not attached"))?;
543                handler(String::from_utf16_lossy(message));
544                return Ok(Value::Undefined);
545            }
546            if let Some(intrinsic) = self.intrinsics.get(&name).copied() {
547                return intrinsic(self, &args);
548            }
549            if let Some(value) =
550                self.bridge
551                    .call(document, &name, this.clone(), args.clone(), construct)?
552            {
553                return Ok(value);
554            }
555            if let Some(value) =
556                self.dom_call(document, &name, this.clone(), args.clone(), construct)?
557            {
558                return Ok(value);
559            }
560            if let Some(value) =
561                self.web_call(document, &name, this.clone(), args.clone(), construct)?
562            {
563                return Ok(value);
564            }
565            if let Some(value) =
566                self.events_call(document, &name, this.clone(), args.clone(), construct)?
567            {
568                return Ok(value);
569            }
570            if let Some(value) = self.regexp_call(document, &name, this.clone(), args.clone())? {
571                return Ok(value);
572            }
573            if let Some(value) = self.weak_call(&name, this.clone(), args.clone())? {
574                return Ok(value);
575            }
576            if let Some(value) = self.builtin_call(document, &name, this, args, construct)? {
577                return Ok(value);
578            }
579            return Err(Error::type_error(format!(
580                "native operation {name} is not admitted"
581            )));
582        }
583        Err(Error::type_error(format!(
584            "{} is not callable",
585            callee.text()
586        )))
587    }
588    pub fn report_error(&mut self, error: Error) {
589        let sequence = self.errors.last().map_or(1, |entry| entry.sequence + 1);
590        self.errors.push(DiagnosticEntry {
591            sequence,
592            order: sequence,
593            level: "error".into(),
594            message: format!("{}: {}", error.name, error.message),
595            stack: error.stack.join("\n"),
596        });
597        if self.errors.len() > 1024 {
598            self.errors.remove(0);
599        }
600    }
601    pub fn record_console(&mut self, level: &str, message: String) {
602        let sequence = self.console.last().map_or(1, |entry| entry.sequence + 1);
603        self.console.push(DiagnosticEntry {
604            sequence,
605            order: sequence,
606            level: level.into(),
607            message,
608            stack: String::new(),
609        });
610        if self.console.len() > 1024 {
611            self.console.remove(0);
612        }
613    }
614}
615
616impl<B: RuntimeBridge> Drop for Guest<B> {
617    fn drop(&mut self) {
618        self.bridge.teardown();
619        self.jobs.clear();
620        self.callbacks.clear();
621        self.nodes.clear();
622        self.heap.borrow_mut().release();
623    }
624}