Skip to main content

nsh_core/element/
value.rs

1//! Values crossing between JS and Rust: shared strings, and the direct
2//! conversion of props, event data, arguments and results from and to JS
3//! values ([`JsValue`]) with their TypeScript types.
4
5use std::{borrow::Borrow, fmt, ops::Deref, sync::Arc};
6
7use super::js::{JsHost, JsIn, JsKind, JsOwned};
8use crate::{JsonValue, style::Color};
9
10/// A cheaply cloned string: a static string or a shared one.
11#[derive(Clone)]
12pub struct SharedString(Repr);
13
14#[derive(Clone)]
15enum Repr {
16    Static(&'static str),
17    Shared(Arc<str>),
18}
19
20impl SharedString {
21    /// A static string, without allocating.
22    pub const fn new_static(s: &'static str) -> Self {
23        Self(Repr::Static(s))
24    }
25
26    /// The string.
27    pub fn as_str(&self) -> &str {
28        match &self.0 {
29            Repr::Static(s) => s,
30            Repr::Shared(s) => s,
31        }
32    }
33
34    pub(crate) fn to_arc(&self) -> Arc<str> {
35        match &self.0 {
36            Repr::Static(s) => Arc::from(*s),
37            Repr::Shared(s) => s.clone(),
38        }
39    }
40}
41
42impl Default for SharedString {
43    fn default() -> Self {
44        Self::new_static("")
45    }
46}
47
48impl Deref for SharedString {
49    type Target = str;
50
51    fn deref(&self) -> &str {
52        self.as_str()
53    }
54}
55
56impl AsRef<str> for SharedString {
57    fn as_ref(&self) -> &str {
58        self.as_str()
59    }
60}
61
62impl Borrow<str> for SharedString {
63    fn borrow(&self) -> &str {
64        self.as_str()
65    }
66}
67
68impl PartialEq for SharedString {
69    fn eq(&self, other: &Self) -> bool {
70        let (a, b) = (self.as_str(), other.as_str());
71        std::ptr::eq(a, b) || a == b
72    }
73}
74
75impl Eq for SharedString {}
76
77impl std::hash::Hash for SharedString {
78    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
79        self.as_str().hash(state)
80    }
81}
82
83impl PartialEq<str> for SharedString {
84    fn eq(&self, other: &str) -> bool {
85        self.as_str() == other
86    }
87}
88
89impl PartialEq<&str> for SharedString {
90    fn eq(&self, other: &&str) -> bool {
91        self.as_str() == *other
92    }
93}
94
95impl fmt::Debug for SharedString {
96    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
97        fmt::Debug::fmt(self.as_str(), f)
98    }
99}
100
101impl fmt::Display for SharedString {
102    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
103        f.write_str(self.as_str())
104    }
105}
106
107impl From<&'static str> for SharedString {
108    fn from(s: &'static str) -> Self {
109        Self::new_static(s)
110    }
111}
112
113impl From<String> for SharedString {
114    fn from(s: String) -> Self {
115        Self(Repr::Shared(s.into()))
116    }
117}
118
119impl From<Arc<str>> for SharedString {
120    fn from(s: Arc<str>) -> Self {
121        Self(Repr::Shared(s))
122    }
123}
124
125impl From<&SharedString> for SharedString {
126    fn from(s: &SharedString) -> Self {
127        s.clone()
128    }
129}
130
131/// A prop value JS sent that does not fit the prop's type.
132#[derive(Debug, Clone, PartialEq)]
133pub struct PropError(pub String);
134
135impl PropError {
136    /// "expected `ty`, got `value`".
137    pub fn expected(ty: &str, value: &JsonValue) -> Self {
138        let mut got = value.to_string();
139        if got.len() > 40 {
140            got.truncate(40);
141            got.push('…');
142        }
143        Self(format!("expected {ty}, got {got}"))
144    }
145}
146
147impl fmt::Display for PropError {
148    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
149        f.write_str(&self.0)
150    }
151}
152
153impl std::error::Error for PropError {}
154
155/// The named TypeScript types the declarations use (`AlertButton`,
156/// `BarStyle`), declared once each.
157#[derive(Debug, Clone, Default)]
158pub struct TsTypes {
159    types: std::collections::BTreeMap<&'static str, String>,
160}
161
162impl TsTypes {
163    /// Type `name`, declared by `declaration` (`interface ... {}` or
164    /// `type ... = ...;`, with its doc comment) the first time.
165    pub fn declare(
166        &mut self,
167        name: &'static str,
168        declaration: impl FnOnce(&mut TsTypes) -> String,
169    ) -> String {
170        if !self.types.contains_key(name) {
171            // Present while it is built: a type naming itself stops here.
172            self.types.insert(name, String::new());
173            let text = declaration(self);
174            self.types.insert(name, text);
175        }
176        name.to_owned()
177    }
178
179    /// Class `def`'s type: its name (the class is declared with the set's
180    /// classes, which include every class a registered signature names:
181    /// [`super::Registry::class`]).
182    pub fn class(&mut self, def: &'static super::ClassDef) -> String {
183        def.name.to_owned()
184    }
185
186    /// Adds `other`'s types.
187    pub(crate) fn merge(&mut self, other: &TsTypes) {
188        for (name, text) in &other.types {
189            self.types.entry(name).or_insert_with(|| text.clone());
190        }
191    }
192
193    pub(crate) fn declarations(&self) -> impl Iterator<Item = &str> {
194        self.types.values().map(String::as_str)
195    }
196}
197
198/// A function giving a TypeScript type (declaring the named types it uses).
199pub type TsType = fn(&mut TsTypes) -> String;
200
201/// `T`'s [`JsValue::ts_type`], or one giving nothing in builds without
202/// declarations ([`super::DECLARATIONS`]): what generated code calls, so
203/// runtimes link none of the TypeScript.
204#[doc(hidden)]
205pub const fn ts_of<T: JsValue>() -> TsType {
206    if super::DECLARATIONS {
207        T::ts_type
208    } else {
209        |_| String::new()
210    }
211}
212
213/// An enum of unit variants that is a string union in JS
214/// (`#[derive(PropEnum)]` implements it).
215pub trait PropEnum: JsValue {
216    /// The variant's JS name (`SemiBold` is `"semiBold"`).
217    fn js_name(&self) -> &'static str;
218}
219
220/// A type props, event data, and the arguments and results of classes and
221/// functions can have: how it converts from and to JS values (directly,
222/// in the JS call or when JS receives it) and its TypeScript type.
223/// `#[derive(PropEnum)]` implements it for enums of unit variants,
224/// `#[derive(JsObject)]` for structs.
225pub trait JsValue: Sized {
226    /// Its TypeScript type (`string`, `AlertButton`), declaring the named
227    /// types it uses in `types`.
228    fn ts_type(types: &mut TsTypes) -> String;
229
230    /// The value of JS value `value`.
231    fn from_js(value: JsIn<'_>) -> Result<Self, PropError>;
232
233    /// The value as a JS value of `host`.
234    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError>;
235}
236
237impl JsValue for bool {
238    fn ts_type(_types: &mut TsTypes) -> String {
239        "boolean".into()
240    }
241
242    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
243        value.as_bool().ok_or_else(|| value.expected("a boolean"))
244    }
245
246    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
247        Ok(JsOwned::new(host, host.new_bool(*self)))
248    }
249}
250
251/// Whether `n` is a whole number in the range of a `bits`-bit integer: what
252/// an integer parameter, prop or field takes (a fraction, `NaN`,
253/// `Infinity` or a value out of range is a mistake, not something to round
254/// or clamp).
255pub(crate) fn fits(n: f64, signed: bool, bits: u32) -> bool {
256    if !n.is_finite() || n.fract() != 0.0 {
257        return false;
258    }
259    let (lo, hi) = if signed {
260        let half = 2f64.powi(bits as i32 - 1);
261        (-half, half)
262    } else {
263        (0.0, 2f64.powi(bits as i32))
264    };
265    n >= lo && n < hi
266}
267
268macro_rules! number {
269    ($check:ident: $($ty:ty),*) => {$(
270        impl JsValue for $ty {
271            fn ts_type(_types: &mut TsTypes) -> String {
272                "number".into()
273            }
274
275            fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
276                let n = value.as_number().ok_or_else(|| value.expected("a number"))?;
277                number!(@$check $ty, n, value);
278                Ok(n as $ty)
279            }
280
281            /// Above 2^53 an integer is the nearest number JS has.
282            fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
283                Ok(JsOwned::new(host, host.new_number(*self as f64)))
284            }
285        }
286    )*};
287    // A float takes any number.
288    (@any $ty:ty, $n:ident, $value:ident) => {};
289    (@whole $ty:ty, $n:ident, $value:ident) => {
290        if !fits($n, <$ty>::MIN != 0, <$ty>::BITS) {
291            return Err($value.expected(concat!("an integer that fits ", stringify!($ty))));
292        }
293    };
294}
295
296number!(any: f32, f64);
297
298/// A number of points.
299impl JsValue for crate::geometry::Points {
300    fn ts_type(_types: &mut TsTypes) -> String {
301        "number".into()
302    }
303
304    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
305        f32::from_js(value).map(Self)
306    }
307
308    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
309        self.0.to_js(host)
310    }
311}
312number!(whole: i16, i32, i64, u16, u32, u64, usize);
313
314/// A whole number of pixels (an image's size).
315impl JsValue for crate::geometry::DevicePixels {
316    fn ts_type(types: &mut TsTypes) -> String {
317        i32::ts_type(types)
318    }
319
320    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
321        i32::from_js(value).map(Self)
322    }
323
324    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
325        self.0.to_js(host)
326    }
327}
328
329/// A size in pixels: TS's `Size` (`{ width, height }`).
330impl JsValue for crate::geometry::Size<crate::geometry::DevicePixels> {
331    fn ts_type(_types: &mut TsTypes) -> String {
332        "Size".into()
333    }
334
335    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
336        if value.kind() != JsKind::Object {
337            return Err(value.expected("an object with width and height"));
338        }
339        let side = |key: &str| -> Result<crate::geometry::DevicePixels, PropError> {
340            let v = value.field(key)?;
341            crate::geometry::DevicePixels::from_js(v.get())
342                .map_err(|e| PropError(format!("`{key}`: {e}")))
343        };
344        Ok(Self::new(side("width")?, side("height")?))
345    }
346
347    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
348        let owned = JsOwned::new(host, host.new_object()?);
349        let object = owned.get().raw();
350        host.set_field(object, "width", self.width.to_js(host)?.into_raw())?;
351        host.set_field(object, "height", self.height.to_js(host)?.into_raw())?;
352        Ok(owned)
353    }
354}
355
356/// A field of a JS object, its key named in the error.
357fn field_of<T: JsValue>(value: JsIn<'_>, key: &str) -> Result<T, PropError> {
358    let v = value.field(key)?;
359    T::from_js(v.get()).map_err(|e| PropError(format!("`{key}`: {e}")))
360}
361
362/// A position in points: TS's `Point` (`{ x, y }`), as events carry it.
363impl JsValue for crate::geometry::Point<crate::geometry::Points> {
364    fn ts_type(_types: &mut TsTypes) -> String {
365        "Point".into()
366    }
367
368    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
369        if value.kind() != JsKind::Object {
370            return Err(value.expected("an object with x and y"));
371        }
372        Ok(Self::new(field_of(value, "x")?, field_of(value, "y")?))
373    }
374
375    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
376        let owned = JsOwned::new(host, host.new_object()?);
377        let object = owned.get().raw();
378        host.set_field(object, "x", self.x.to_js(host)?.into_raw())?;
379        host.set_field(object, "y", self.y.to_js(host)?.into_raw())?;
380        Ok(owned)
381    }
382}
383
384/// A size in points: TS's `Size` (`{ width, height }`).
385impl JsValue for crate::geometry::Size<crate::geometry::Points> {
386    fn ts_type(_types: &mut TsTypes) -> String {
387        "Size".into()
388    }
389
390    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
391        if value.kind() != JsKind::Object {
392            return Err(value.expected("an object with width and height"));
393        }
394        Ok(Self::new(
395            field_of(value, "width")?,
396            field_of(value, "height")?,
397        ))
398    }
399
400    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
401        let owned = JsOwned::new(host, host.new_object()?);
402        let object = owned.get().raw();
403        host.set_field(object, "width", self.width.to_js(host)?.into_raw())?;
404        host.set_field(object, "height", self.height.to_js(host)?.into_raw())?;
405        Ok(owned)
406    }
407}
408
409/// A rectangle in points: TS's `Bounds` (`{ origin, size }`), as events
410/// carry it.
411impl JsValue for crate::geometry::Bounds<crate::geometry::Points> {
412    fn ts_type(_types: &mut TsTypes) -> String {
413        "Bounds".into()
414    }
415
416    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
417        if value.kind() != JsKind::Object {
418            return Err(value.expected("an object with origin and size"));
419        }
420        Ok(Self::new(
421            field_of(value, "origin")?,
422            field_of(value, "size")?,
423        ))
424    }
425
426    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
427        let owned = JsOwned::new(host, host.new_object()?);
428        let object = owned.get().raw();
429        host.set_field(object, "origin", self.origin.to_js(host)?.into_raw())?;
430        host.set_field(object, "size", self.size.to_js(host)?.into_raw())?;
431        Ok(owned)
432    }
433}
434
435/// The modifier keys held: TS's `Modifiers` (`{ control, alt, shift,
436/// platform }`, GPUI's names), as press events carry them. A missing key
437/// is not held.
438impl JsValue for crate::keymap::Modifiers {
439    fn ts_type(_types: &mut TsTypes) -> String {
440        "Modifiers".into()
441    }
442
443    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
444        if value.kind() != JsKind::Object {
445            return Err(value.expected("an object of modifier keys"));
446        }
447        let held = |key: &str| -> Result<bool, PropError> {
448            Ok(field_of::<Option<bool>>(value, key)?.unwrap_or(false))
449        };
450        Ok(Self {
451            ctrl: held("control")?,
452            alt: held("alt")?,
453            shift: held("shift")?,
454            cmd: held("platform")?,
455        })
456    }
457
458    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
459        let owned = JsOwned::new(host, host.new_object()?);
460        let object = owned.get().raw();
461        for (key, held) in [
462            ("control", self.ctrl),
463            ("alt", self.alt),
464            ("shift", self.shift),
465            ("platform", self.cmd),
466        ] {
467            host.set_field(object, key, held.to_js(host)?.into_raw())?;
468        }
469        Ok(owned)
470    }
471}
472
473impl JsValue for SharedString {
474    fn ts_type(_types: &mut TsTypes) -> String {
475        "string".into()
476    }
477
478    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
479        value
480            .as_string()
481            .map(Into::into)
482            .ok_or_else(|| value.expected("a string"))
483    }
484
485    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
486        Ok(JsOwned::new(host, host.new_string(self.as_str())?))
487    }
488}
489
490impl JsValue for String {
491    fn ts_type(_types: &mut TsTypes) -> String {
492        "string".into()
493    }
494
495    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
496        value.as_string().ok_or_else(|| value.expected("a string"))
497    }
498
499    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
500        Ok(JsOwned::new(host, host.new_string(self)?))
501    }
502}
503
504/// A CSS color string from JS (`"#2563eb"`, `"rgb(0 0 0 / 0.5)"`), as
505/// [`Color`] takes it: the color of Rust components' props.
506impl JsValue for crate::Hsla {
507    fn ts_type(types: &mut TsTypes) -> String {
508        Color::ts_type(types)
509    }
510
511    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
512        Color::from_js(value).map(Into::into)
513    }
514
515    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
516        Color::from(*self).to_js(host)
517    }
518}
519
520/// A CSS color string from JS (`"#2563eb"`, `"rgb(0 0 0 / 0.5)"`).
521impl JsValue for Color {
522    fn ts_type(_types: &mut TsTypes) -> String {
523        "string".into()
524    }
525
526    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
527        value
528            .as_string()
529            .as_deref()
530            .and_then(Color::parse)
531            .ok_or_else(|| value.expected("a color"))
532    }
533
534    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
535        Ok(JsOwned::new(
536            host,
537            host.new_string(&format!("#{:08x}", self.0))?,
538        ))
539    }
540}
541
542/// A node JS passes (a `YNode`, a `ref`).
543#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
544pub struct NodeRef(pub crate::NodeId);
545
546impl JsValue for NodeRef {
547    fn ts_type(_types: &mut TsTypes) -> String {
548        "YNode".into()
549    }
550
551    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
552        value
553            .host()
554            .node(value.raw())
555            .map(NodeRef)
556            .ok_or_else(|| value.expected("a node"))
557    }
558
559    /// The node's JS object (`null` once JS let it go).
560    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
561        Ok(JsOwned::new(host, host.node_value(self.0)))
562    }
563}
564
565/// Any value, as JSON (a real JSON API's data: `JSON.stringify`'s view of
566/// the value).
567impl JsValue for JsonValue {
568    fn ts_type(_types: &mut TsTypes) -> String {
569        "unknown".into()
570    }
571
572    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
573        match value.kind() {
574            JsKind::Undefined => Ok(JsonValue::Null),
575            _ => value.to_json(),
576        }
577    }
578
579    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
580        Ok(JsOwned::new(host, host.json(self)?))
581    }
582}
583
584/// `null` (and `undefined`) is `None`.
585impl<T: JsValue> JsValue for Option<T> {
586    fn ts_type(types: &mut TsTypes) -> String {
587        format!("{} | null", T::ts_type(types))
588    }
589
590    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
591        if value.is_nullish() {
592            Ok(None)
593        } else {
594            T::from_js(value).map(Some)
595        }
596    }
597
598    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
599        match self {
600            Some(v) => v.to_js(host),
601            None => Ok(JsOwned::new(host, host.null())),
602        }
603    }
604}
605
606/// Bytes are a `Uint8Array` (a `Buffer` is one too), not an array of
607/// numbers: `u8` is no [`JsValue`], so this and the arrays below never
608/// overlap.
609impl JsValue for Vec<u8> {
610    fn ts_type(_types: &mut TsTypes) -> String {
611        "Uint8Array".into()
612    }
613
614    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
615        value
616            .as_bytes()
617            .ok_or_else(|| value.expected("a Uint8Array"))
618    }
619
620    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
621        Ok(JsOwned::new(host, host.new_bytes(self)?))
622    }
623}
624
625/// An object of strings by name (`process.env`): `Record<string, string>`.
626impl JsValue for std::collections::BTreeMap<String, String> {
627    fn ts_type(_types: &mut TsTypes) -> String {
628        "Record<string, string>".into()
629    }
630
631    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
632        if value.kind() != JsKind::Object {
633            return Err(value.expected("an object of strings"));
634        }
635        let JsonValue::Object(fields) = value.to_json()? else {
636            return Err(value.expected("an object of strings"));
637        };
638        fields
639            .into_iter()
640            .map(|(key, v)| match v {
641                JsonValue::String(s) => Ok((key, s)),
642                other => Err(PropError::expected("a string", &other)),
643            })
644            .collect()
645    }
646
647    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
648        let object = JsOwned::new(host, host.new_object()?);
649        for (key, value) in self {
650            host.set_field(object.get().raw(), key, host.new_string(value)?)?;
651        }
652        Ok(object)
653    }
654}
655
656/// A time is a `Date` (its milliseconds since the Unix epoch).
657impl JsValue for std::time::SystemTime {
658    fn ts_type(_types: &mut TsTypes) -> String {
659        "Date".into()
660    }
661
662    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
663        let millis = value
664            .as_date()
665            .filter(|m| m.is_finite())
666            .ok_or_else(|| value.expected("a valid Date"))?;
667        let since = std::time::Duration::from_secs_f64(millis.abs() / 1000.0);
668        let time = if millis < 0.0 {
669            std::time::UNIX_EPOCH.checked_sub(since)
670        } else {
671            std::time::UNIX_EPOCH.checked_add(since)
672        };
673        time.ok_or_else(|| value.expected("a Date in range"))
674    }
675
676    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
677        let millis = match self.duration_since(std::time::UNIX_EPOCH) {
678            Ok(since) => since.as_secs_f64() * 1000.0,
679            Err(before) => -before.duration().as_secs_f64() * 1000.0,
680        };
681        Ok(JsOwned::new(host, host.new_date(millis)?))
682    }
683}
684
685impl<T: JsValue> JsValue for Vec<T> {
686    fn ts_type(types: &mut TsTypes) -> String {
687        format!("({})[]", T::ts_type(types))
688    }
689
690    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
691        let len = value
692            .array_len()?
693            .ok_or_else(|| value.expected("an array"))?;
694        // The length is JS's (the host limits what it reads): reserve a
695        // bounded amount up front.
696        let mut out = Vec::with_capacity(len.min(1024));
697        for i in 0..len {
698            let item = value.index(i)?;
699            out.push(T::from_js(item.get()).map_err(|e| PropError(format!("[{i}]: {e}")))?);
700        }
701        Ok(out)
702    }
703
704    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
705        // Owned until the array takes them: an item failing frees the
706        // ones made before.
707        let mut items = Vec::with_capacity(self.len());
708        for item in self {
709            items.push(item.to_js(host)?);
710        }
711        let raws = items.into_iter().map(JsOwned::into_raw).collect();
712        Ok(JsOwned::new(host, host.new_array(raws)?))
713    }
714}