Skip to main content

nsh_core/element/
js.rs

1//! JS values as Rust reads and makes them directly, without JSON: what
2//! every call into Rust converts its arguments and results with, and Rust
3//! components their props and events ([`super::JsValue::from_js`],
4//! [`super::JsValue::to_js`]).
5//!
6//! The values are the JS host's (`nsh-js`: QuickJS's), opaque here
7//! ([`JsRaw`]); a [`JsHost`] reads and makes them. A [`JsIn`] is a value
8//! borrowed for a call, a [`JsOwned`] one Rust holds a reference to (freed
9//! when dropped).
10
11use std::{fmt, rc::Rc};
12
13use super::{PropError, callback::CallbackHandle, class::ClassInstance};
14use crate::JsonValue;
15
16/// A JS value as the host holds it, copied in: meaningful to the host
17/// only.
18#[doc(hidden)]
19#[derive(Clone, Copy)]
20#[repr(C, align(8))]
21pub struct JsRaw(pub [u64; 2]);
22
23impl fmt::Debug for JsRaw {
24    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
25        f.write_str("JsRaw")
26    }
27}
28
29/// What kind of value a JS value is.
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub enum JsKind {
32    /// `undefined`.
33    Undefined,
34    /// `null`.
35    Null,
36    /// `true` or `false`.
37    Bool,
38    /// A number.
39    Number,
40    /// A string.
41    String,
42    /// An array.
43    Array,
44    /// A function.
45    Function,
46    /// Any other object.
47    Object,
48    /// A symbol, a big integer, ...
49    Other,
50}
51
52/// What class of object a JS object is, as `Object.prototype.toString`
53/// tells built-in objects apart ([`JsIn::class`]): what checks of equality
54/// compare by (`nsh/test`'s `toEqual`).
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56#[non_exhaustive]
57pub enum JsClass {
58    /// An array.
59    Array,
60    /// A function.
61    Function,
62    /// A `Date`.
63    Date,
64    /// A `RegExp`.
65    RegExp,
66    /// A `Map`.
67    Map,
68    /// A `Set`.
69    Set,
70    /// An error (an `Error` or one of its subclasses).
71    Error,
72    /// An `ArrayBuffer`.
73    ArrayBuffer,
74    /// A typed array or a `DataView`, named by its class (`"Uint8Array"`,
75    /// `"DataView"`).
76    View(&'static str),
77    /// Any other object: a plain object, an instance of a class, ...
78    Object,
79}
80
81/// Whether `a` and `b` are the same primitive, as `Object.is` says (`NaN`
82/// is `NaN`, `0` is not `-0`); objects are never the same here.
83fn same_primitive<H: JsHost + ?Sized>(host: &H, a: JsRaw, b: JsRaw) -> bool {
84    match (host.kind(a), host.kind(b)) {
85        (JsKind::Undefined, JsKind::Undefined) | (JsKind::Null, JsKind::Null) => true,
86        (JsKind::Bool, JsKind::Bool) => host.bool(a) == host.bool(b),
87        (JsKind::String, JsKind::String) => host.string(a) == host.string(b),
88        (JsKind::Number, JsKind::Number) => match (host.number(a), host.number(b)) {
89            (Some(a), Some(b)) if a.is_nan() => b.is_nan(),
90            (Some(a), Some(b)) => a == b && a.is_sign_negative() == b.is_sign_negative(),
91            _ => false,
92        },
93        _ => false,
94    }
95}
96
97/// A value of an array or object read in bulk ([`JsIn::primitives`],
98/// [`JsIn::primitive_entries`]).
99#[derive(Debug, Clone, PartialEq)]
100pub enum JsPrimitive {
101    /// Anything else: `undefined`, `null`, an object, a function, ...
102    Other,
103    /// `true` or `false`.
104    Bool(bool),
105    /// A number.
106    Number(f64),
107    /// A string.
108    String(String),
109    /// A `Date`, as milliseconds since the Unix epoch.
110    Date(f64),
111}
112
113/// Value `raw` of `host` as a [`JsPrimitive`].
114fn primitive_of<H: JsHost + ?Sized>(host: &H, raw: JsRaw) -> JsPrimitive {
115    match host.kind(raw) {
116        JsKind::Bool => host.bool(raw).map_or(JsPrimitive::Other, JsPrimitive::Bool),
117        JsKind::Number => host
118            .number(raw)
119            .map_or(JsPrimitive::Other, JsPrimitive::Number),
120        JsKind::String => host
121            .string(raw)
122            .map_or(JsPrimitive::Other, JsPrimitive::String),
123        JsKind::Object => host.date(raw).map_or(JsPrimitive::Other, JsPrimitive::Date),
124        _ => JsPrimitive::Other,
125    }
126}
127
128/// The JS host's side of the direct conversions (`nsh-js` implements it):
129/// reads and makes values of its VM, and the call being made (its
130/// arguments, `this`). Values it returns are owned (one reference the
131/// caller frees); values it takes are borrowed unless named otherwise.
132#[doc(hidden)]
133pub trait JsHost {
134    /// The kind of `v`.
135    fn kind(&self, v: JsRaw) -> JsKind;
136    /// `v` as a boolean (`None`: not one).
137    fn bool(&self, v: JsRaw) -> Option<bool>;
138    /// `v` as a number (`None`: not one).
139    fn number(&self, v: JsRaw) -> Option<f64>;
140    /// `v` as a string (`None`: not one).
141    fn string(&self, v: JsRaw) -> Option<String>;
142    /// The bytes of `Uint8Array` `v`, copied (`None`: not one).
143    fn bytes(&self, v: JsRaw) -> Option<Vec<u8>>;
144    /// The length of array `v` (`None`: not an array; an error when it is
145    /// more than the host reads in one call).
146    fn len(&self, v: JsRaw) -> Result<Option<usize>, PropError>;
147    /// Item `i` of array `v`, owned.
148    fn index(&self, v: JsRaw, i: usize) -> Result<JsRaw, PropError>;
149    /// Field `key` of object `v` (`undefined` when it has none), owned.
150    fn field(&self, v: JsRaw, key: &str) -> Result<JsRaw, PropError>;
151    /// The own enumerable string keys of object `v` (none when it is not
152    /// one).
153    fn keys(&self, v: JsRaw) -> Result<Vec<String>, PropError>;
154    /// The time `Date` `v` stands for, in milliseconds since the Unix
155    /// epoch (`None`: not a `Date`).
156    fn date(&self, v: JsRaw) -> Option<f64>;
157    /// The items of array `v` as primitives (`None`: not an array). One
158    /// call for the whole array where a host crosses a boundary for each
159    /// value it reads (the browser's): tables read many rows of them.
160    fn primitives(&self, v: JsRaw) -> Result<Option<Vec<JsPrimitive>>, PropError> {
161        let Some(len) = self.len(v)? else {
162            return Ok(None);
163        };
164        let mut items = Vec::with_capacity(len);
165        for i in 0..len {
166            let item = self.index(v, i)?;
167            items.push(primitive_of(self, item));
168            self.free(item);
169        }
170        Ok(Some(items))
171    }
172    /// The own enumerable string-keyed fields of object `v` as primitives
173    /// (none when it is not one), in one call as [`JsHost::primitives`].
174    fn primitive_entries(&self, v: JsRaw) -> Result<Vec<(String, JsPrimitive)>, PropError> {
175        let mut entries = Vec::new();
176        for key in self.keys(v)? {
177            let field = self.field(v, &key)?;
178            entries.push((key, primitive_of(self, field)));
179            self.free(field);
180        }
181        Ok(entries)
182    }
183    /// The class of object `v` (`None`: not an object). A host that tells
184    /// only arrays, functions and dates apart says `Object` for the rest.
185    fn class(&self, v: JsRaw) -> Option<JsClass> {
186        match self.kind(v) {
187            JsKind::Array => Some(JsClass::Array),
188            JsKind::Function => Some(JsClass::Function),
189            JsKind::Object if self.date(v).is_some() => Some(JsClass::Date),
190            JsKind::Object => Some(JsClass::Object),
191            _ => None,
192        }
193    }
194    /// Whether `a` and `b` are the same value, as `Object.is` says: the
195    /// same primitive, or the same object. A host that cannot tell objects
196    /// apart says no for any two.
197    fn same_value(&self, a: JsRaw, b: JsRaw) -> bool {
198        same_primitive(self, a, b)
199    }
200    /// The bytes of `ArrayBuffer`, typed array or `DataView` `v`, copied
201    /// (`None`: none of those). A host that reads only `Uint8Array`s reads
202    /// [`JsHost::bytes`].
203    fn buffer(&self, v: JsRaw) -> Option<Vec<u8>> {
204        self.bytes(v)
205    }
206    /// The values iterable `v` yields, as `for...of` reads them (a `Map`'s
207    /// `[key, value]` pairs, a `Set`'s values), owned (`None`: not
208    /// iterable). A host without the iteration protocol reads arrays.
209    fn iterate(&self, v: JsRaw) -> Result<Option<Vec<JsRaw>>, PropError> {
210        let Some(len) = self.len(v)? else {
211            return Ok(None);
212        };
213        let mut items = Vec::with_capacity(len);
214        for i in 0..len {
215            match self.index(v, i) {
216                Ok(item) => items.push(item),
217                Err(e) => {
218                    for item in items {
219                        self.free(item);
220                    }
221                    return Err(e);
222                }
223            }
224        }
225        Ok(Some(items))
226    }
227    /// Calls method `name` of `v` (a primitive's, as JS does: `"a".search(…)`)
228    /// with `args` (borrowed): its result, owned. A host without calls
229    /// refuses.
230    fn invoke(&self, v: JsRaw, name: &str, args: &[JsRaw]) -> Result<JsRaw, PropError> {
231        let _ = (v, args);
232        Err(PropError(format!("`{name}` cannot be called here")))
233    }
234    /// `v` as JSON (as `JSON.stringify` sees it).
235    fn to_json(&self, v: JsRaw) -> Result<JsonValue, PropError>;
236    /// A short text showing `v`, for errors (`"abc"`, `{}`).
237    fn describe(&self, v: JsRaw) -> String;
238    /// Style `v` (an object or an array of them), decoded as a host
239    /// element's `style` is; what it does not take is logged as there.
240    fn style(&self, v: JsRaw) -> Result<crate::StylePatch, PropError>;
241    /// The node `v` is (an element, a `ref`: TS `ViewRef`).
242    fn node(&self, v: JsRaw) -> Option<crate::NodeId>;
243    /// Node `id`'s JS object (`null` when JS let it go), owned.
244    fn node_value(&self, id: crate::NodeId) -> JsRaw;
245    /// The instance of a class `v` holds (any class's).
246    fn instance(&self, v: JsRaw) -> Option<Rc<dyn ClassInstance>>;
247    /// The JS function `v` is, as a callback Rust keeps.
248    fn callback(&self, v: JsRaw) -> Option<Rc<dyn CallbackHandle>>;
249    /// Any value `v`, kept alive until the handle goes, to give back to JS
250    /// later ([`CallbackHandle::value`]): the rows a component reads, to
251    /// hand them to the app's functions one by one; a promise a
252    /// [`super::Callback::settling`] answers with. `None` where the host
253    /// keeps no values.
254    fn retain(&self, _v: JsRaw) -> Option<Rc<dyn CallbackHandle>> {
255        None
256    }
257
258    /// Frees owned value `v`.
259    fn free(&self, v: JsRaw);
260    /// `undefined`.
261    fn undefined(&self) -> JsRaw;
262    /// `null`.
263    fn null(&self) -> JsRaw;
264    /// A boolean.
265    fn new_bool(&self, b: bool) -> JsRaw;
266    /// A number.
267    fn new_number(&self, n: f64) -> JsRaw;
268    /// A string.
269    fn new_string(&self, s: &str) -> Result<JsRaw, PropError>;
270    /// A `Uint8Array` of `bytes` (copied).
271    fn new_bytes(&self, bytes: &[u8]) -> Result<JsRaw, PropError>;
272    /// A `Date` of `millis` since the Unix epoch.
273    fn new_date(&self, millis: f64) -> Result<JsRaw, PropError>;
274    /// An array of `items` (taken).
275    fn new_array(&self, items: Vec<JsRaw>) -> Result<JsRaw, PropError>;
276    /// An empty object.
277    fn new_object(&self) -> Result<JsRaw, PropError>;
278    /// Sets field `key` of object `obj` to `value` (taken).
279    fn set_field(&self, obj: JsRaw, key: &str, value: JsRaw) -> Result<(), PropError>;
280    /// JSON as a JS value.
281    fn json(&self, v: &JsonValue) -> Result<JsRaw, PropError>;
282    /// A `File` named `name` of type `mime` holding `data` (shared, not
283    /// copied), last changed at `last_modified` (`None`: now). A host
284    /// without `File` refuses.
285    fn new_file(
286        &self,
287        data: &crate::ImageData,
288        mime: &str,
289        name: &str,
290        last_modified: Option<std::time::SystemTime>,
291    ) -> Result<JsRaw, PropError> {
292        let _ = (data, mime, name, last_modified);
293        Err(PropError("a `File` cannot be made here".into()))
294    }
295    /// A `Blob` of type `mime` holding `data` (shared, not copied). A host
296    /// without `Blob` refuses.
297    fn new_blob(&self, data: &crate::ImageData, mime: &str) -> Result<JsRaw, PropError> {
298        let _ = (data, mime);
299        Err(PropError("a `Blob` cannot be made here".into()))
300    }
301    /// A function taking nothing and returning `undefined` that runs `f`
302    /// each time it is called ([`super::Stop`]'s). A host without
303    /// functions refuses.
304    fn new_function(&self, f: Box<dyn Fn()>) -> Result<JsRaw, PropError> {
305        drop(f);
306        Err(PropError("a function cannot be made here".into()))
307    }
308    /// A signal of JS's reactive graph holding `value` (taken), and a
309    /// function writing it (`(value) => boolean`: `false` once JS let the
310    /// signal go; it does not keep the signal alive): what a Rust
311    /// [`super::Signal`] returned to JS reads as. A host without a reactive
312    /// graph refuses.
313    #[doc(hidden)]
314    fn new_signal(&self, value: JsRaw) -> Result<(JsRaw, JsRaw), PropError> {
315        self.free(value);
316        Err(PropError("a reactive value cannot cross to JS here".into()))
317    }
318    /// The JS object of `instance`: the one it has, or a new one of its
319    /// class.
320    fn wrap(&self, instance: Rc<dyn ClassInstance>) -> Result<JsRaw, PropError>;
321
322    /// Argument `i` of the call (`undefined` past the last), borrowed.
323    fn arg(&self, i: usize) -> JsRaw;
324    /// `this` of the call, borrowed.
325    fn this(&self) -> JsRaw;
326    /// The object a constructor makes for `instance` (with `new.target`'s
327    /// prototype).
328    fn construct(&self, instance: Rc<dyn ClassInstance>) -> Result<JsRaw, PropError>;
329
330    /// The VM the call comes from ([`super::System`]); one granting nothing
331    /// where the host configured none.
332    fn system(&self) -> super::System {
333        super::System::default()
334    }
335
336    /// Starts `task` as a task of the core, in order with the ops JS sent
337    /// before the call (`CallCx::start`); a host without a core drops it.
338    fn start_task(&self, task: super::TaskStart) {
339        drop(task);
340    }
341
342    /// The image `blob:` URL `url` names in this VM (`URL.createObjectURL`):
343    /// the key it goes by and its bytes, as `<Image>`'s `src` resolves one,
344    /// so an image prop of a Rust component shows what `<Image>` would.
345    /// `None` for a URL no blob has (revoked, never made) or a host without
346    /// blobs: the image then fails to load.
347    fn image_blob(&self, url: &str) -> Option<(std::sync::Arc<str>, crate::ImageData)> {
348        let _ = url;
349        None
350    }
351
352    /// Runs `f` when what owns the call in JS goes (`CallCx::on_cleanup`);
353    /// a host without owners keeps it until it goes itself. Returns what
354    /// unregisters `f` without running it.
355    fn on_cleanup(&self, f: Box<dyn FnOnce()>) -> Box<dyn FnOnce()> {
356        drop(f);
357        Box::new(|| {})
358    }
359}
360
361/// A JS value borrowed for a call: read it with its methods, convert it
362/// with [`super::JsValue::from_js`].
363#[derive(Clone, Copy)]
364pub struct JsIn<'a> {
365    host: &'a dyn JsHost,
366    raw: JsRaw,
367}
368
369impl fmt::Debug for JsIn<'_> {
370    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
371        f.write_str(&self.describe())
372    }
373}
374
375impl<'a> JsIn<'a> {
376    /// Value `raw` of `host`, borrowed.
377    #[doc(hidden)]
378    pub fn new(host: &'a dyn JsHost, raw: JsRaw) -> Self {
379        Self { host, raw }
380    }
381
382    /// The host the value belongs to.
383    #[doc(hidden)]
384    pub fn host(&self) -> &'a dyn JsHost {
385        self.host
386    }
387
388    /// The value as the host holds it.
389    #[doc(hidden)]
390    pub fn raw(&self) -> JsRaw {
391        self.raw
392    }
393
394    /// What kind of value it is.
395    pub fn kind(&self) -> JsKind {
396        self.host.kind(self.raw)
397    }
398
399    /// The bytes of a `Uint8Array`, copied.
400    pub fn as_bytes(&self) -> Option<Vec<u8>> {
401        self.host.bytes(self.raw)
402    }
403
404    /// `undefined` or `null`.
405    pub fn is_nullish(&self) -> bool {
406        matches!(self.kind(), JsKind::Undefined | JsKind::Null)
407    }
408
409    /// The boolean it is.
410    pub fn as_bool(&self) -> Option<bool> {
411        self.host.bool(self.raw)
412    }
413
414    /// The number it is.
415    pub fn as_number(&self) -> Option<f64> {
416        self.host.number(self.raw)
417    }
418
419    /// The string it is.
420    pub fn as_string(&self) -> Option<String> {
421        self.host.string(self.raw)
422    }
423
424    /// Its length, if it is an array (an error when it is longer than the
425    /// host reads in one call).
426    pub fn array_len(&self) -> Result<Option<usize>, PropError> {
427        self.host.len(self.raw)
428    }
429
430    /// Item `i` of the array it is.
431    pub fn index(&self, i: usize) -> Result<JsOwned<'a>, PropError> {
432        let raw = self.host.index(self.raw, i)?;
433        Ok(JsOwned::new(self.host, raw))
434    }
435
436    /// Its field `key` (`undefined` when it has none).
437    pub fn field(&self, key: &str) -> Result<JsOwned<'a>, PropError> {
438        let raw = self.host.field(self.raw, key)?;
439        Ok(JsOwned::new(self.host, raw))
440    }
441
442    /// Its own enumerable string keys (none when it is not an object).
443    pub fn keys(&self) -> Result<Vec<String>, PropError> {
444        self.host.keys(self.raw)
445    }
446
447    /// The items of the array it is, as primitives (`None`: not an array),
448    /// read in one call.
449    pub fn primitives(&self) -> Result<Option<Vec<JsPrimitive>>, PropError> {
450        self.host.primitives(self.raw)
451    }
452
453    /// Its own enumerable string-keyed fields, as primitives (none when it
454    /// is not an object), read in one call.
455    pub fn primitive_entries(&self) -> Result<Vec<(String, JsPrimitive)>, PropError> {
456        self.host.primitive_entries(self.raw)
457    }
458
459    /// The milliseconds since the Unix epoch of the `Date` it is.
460    pub fn as_date(&self) -> Option<f64> {
461        self.host.date(self.raw)
462    }
463
464    /// The class of the object it is (`None`: not an object).
465    pub fn class(&self) -> Option<JsClass> {
466        self.host.class(self.raw)
467    }
468
469    /// Whether it is `other`, as `Object.is` says (the same object, or
470    /// the same primitive: `NaN` is `NaN`, `0` is not `-0`).
471    pub fn same_value(&self, other: JsIn<'_>) -> bool {
472        self.host.same_value(self.raw, other.raw)
473    }
474
475    /// The bytes of the `ArrayBuffer`, typed array or `DataView` it is,
476    /// copied.
477    pub fn as_buffer(&self) -> Option<Vec<u8>> {
478        self.host.buffer(self.raw)
479    }
480
481    /// The values it yields as an iterable, as `for...of` reads them (a
482    /// `Map`'s `[key, value]` pairs, a `Set`'s values; `None`: not
483    /// iterable).
484    pub fn iterate(&self) -> Result<Option<Vec<JsOwned<'a>>>, PropError> {
485        Ok(self.host.iterate(self.raw)?.map(|items| {
486            items
487                .into_iter()
488                .map(|raw| JsOwned::new(self.host, raw))
489                .collect()
490        }))
491    }
492
493    /// Calls its method `name` with `args`: what it returns (a
494    /// primitive's methods too: `"a".search(re)`).
495    pub fn invoke(&self, name: &str, args: &[JsIn<'_>]) -> Result<JsOwned<'a>, PropError> {
496        let args: Vec<JsRaw> = args.iter().map(|a| a.raw).collect();
497        let raw = self.host.invoke(self.raw, name, &args)?;
498        Ok(JsOwned::new(self.host, raw))
499    }
500
501    /// The value as JSON.
502    pub fn to_json(&self) -> Result<JsonValue, PropError> {
503        self.host.to_json(self.raw)
504    }
505
506    /// A short text showing it, for errors.
507    pub fn describe(&self) -> String {
508        self.host.describe(self.raw)
509    }
510
511    /// "expected `what`, got <the value>".
512    pub fn expected(&self, what: &str) -> PropError {
513        PropError(format!("expected {what}, got {}", self.describe()))
514    }
515}
516
517/// A JS value Rust holds a reference to, freed when dropped.
518pub struct JsOwned<'a> {
519    host: &'a dyn JsHost,
520    raw: JsRaw,
521}
522
523impl<'a> JsOwned<'a> {
524    /// Owned value `raw` of `host`.
525    #[doc(hidden)]
526    pub fn new(host: &'a dyn JsHost, raw: JsRaw) -> Self {
527        Self { host, raw }
528    }
529
530    /// The value, to read.
531    pub fn get(&self) -> JsIn<'a> {
532        JsIn {
533            host: self.host,
534            raw: self.raw,
535        }
536    }
537
538    /// The reference, for the host to take.
539    #[doc(hidden)]
540    pub fn into_raw(self) -> JsRaw {
541        let raw = self.raw;
542        std::mem::forget(self);
543        raw
544    }
545}
546
547impl Drop for JsOwned<'_> {
548    fn drop(&mut self) {
549        self.host.free(self.raw);
550    }
551}
552
553impl fmt::Debug for JsOwned<'_> {
554    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
555        self.get().fmt(f)
556    }
557}
558
559#[cfg(test)]
560mod tests {
561    use serde_json::json;
562
563    use super::*;
564    use crate::element::json_host::JsonHost;
565
566    #[test]
567    fn hosts_without_their_own_compare_primitives_and_read_arrays() {
568        let host = JsonHost::default();
569        let value = |json| JsIn::new(&host, host.value(json));
570        let undefined = JsIn::new(&host, host.undefined());
571        assert!(value(json!(1)).same_value(value(json!(1.0))));
572        assert!(value(json!("a")).same_value(value(json!("a"))));
573        assert!(undefined.same_value(undefined));
574        assert!(!undefined.same_value(value(json!(null))));
575        assert!(!value(json!(1)).same_value(value(json!("1"))));
576        assert!(!value(json!(0.0)).same_value(value(json!(-0.0))));
577        // Two objects are never the same here.
578        assert!(!value(json!({})).same_value(value(json!({}))));
579        assert_eq!(value(json!([1])).class(), Some(JsClass::Array));
580        assert_eq!(value(json!({})).class(), Some(JsClass::Object));
581        assert_eq!(value(json!("a")).class(), None);
582        let items = value(json!(["a", 2])).iterate().unwrap().unwrap();
583        let items: Vec<_> = items.iter().map(|i| i.get().to_json().unwrap()).collect();
584        assert_eq!(items, [json!("a"), json!(2)]);
585        assert!(value(json!({})).iterate().unwrap().is_none());
586        assert!(value(json!("a")).invoke("search", &[]).is_err());
587    }
588}