1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
use crate::{
    handle_exception, Array, Ctx, Error, FromAtom, FromJs, Object, Result, StdString, String, Type,
    Value,
};
use std::{
    cell::{Cell, RefCell},
    collections::{BTreeMap, BTreeSet, HashMap, HashSet, LinkedList, VecDeque},
    hash::{BuildHasher, Hash},
    rc::Rc,
    sync::{Arc, Mutex, RwLock},
};

#[cfg(feature = "either")]
use either::{Either, Left, Right};

#[cfg(feature = "indexmap")]
use indexmap::{IndexMap, IndexSet};

impl<'js> FromJs<'js> for Value<'js> {
    fn from_js(_: Ctx<'js>, value: Value<'js>) -> Result<Self> {
        Ok(value)
    }
}

impl<'js> FromJs<'js> for StdString {
    fn from_js(_ctx: Ctx<'js>, value: Value<'js>) -> Result<Self> {
        String::from_value(value).and_then(|string| string.to_string())
    }
}

/// Convert from JS as any
impl<'js> FromJs<'js> for () {
    fn from_js(_: Ctx<'js>, _: Value<'js>) -> Result<Self> {
        Ok(())
    }
}

/// Convert from JS as optional
impl<'js, T> FromJs<'js> for Option<T>
where
    T: FromJs<'js>,
{
    fn from_js(ctx: Ctx<'js>, value: Value<'js>) -> Result<Self> {
        if value.type_of().is_void() {
            Ok(None)
        } else {
            T::from_js(ctx, value).map(Some)
        }
    }
}

/// Convert from JS as result
impl<'js, T> FromJs<'js> for Result<T>
where
    T: FromJs<'js>,
{
    //TODO this function seems a bit hacky.
    //Expections are generally handled when returned from a function
    fn from_js(ctx: Ctx<'js>, value: Value<'js>) -> Result<Self> {
        unsafe {
            match handle_exception(ctx, value.into_js_value()) {
                Ok(val) => T::from_js(ctx, Value::from_js_value(ctx, val)).map(Ok),
                Err(error) => Ok(Err(error)),
            }
        }
    }
}

/// Convert from JS to either
#[cfg(feature = "either")]
#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "either")))]
impl<'js, L, R> FromJs<'js> for Either<L, R>
where
    L: FromJs<'js>,
    R: FromJs<'js>,
{
    fn from_js(ctx: Ctx<'js>, value: Value<'js>) -> Result<Self> {
        L::from_js(ctx, value.clone()).map(Left).or_else(|error| {
            if error.is_from_js() {
                R::from_js(ctx, value).map(Right)
            } else {
                Err(error)
            }
        })
    }
}

fn tuple_match_size(actual: usize, expected: usize) -> Result<()> {
    if actual == expected {
        Ok(())
    } else {
        Err(Error::new_from_js_message(
            "array",
            "tuple",
            if actual < expected {
                "Not enough values"
            } else {
                "Too many values"
            },
        ))
    }
}

fn number_match_range<T: PartialOrd>(
    val: T,
    min: T,
    max: T,
    from: &'static str,
    to: &'static str,
) -> Result<()> {
    if val < min {
        Err(Error::new_from_js_message(from, to, "Underflow"))
    } else if val > max {
        Err(Error::new_from_js_message(from, to, "Overflow"))
    } else {
        Ok(())
    }
}

macro_rules! from_js_impls {
    // for reference types
    (ref: $($(#[$meta:meta])* $type:ident,)*) => {
        $(
            $(#[$meta])*
            impl<'js, T> FromJs<'js> for $type<T>
            where
                T: FromJs<'js>,
            {
                fn from_js(ctx: Ctx<'js>, value: Value<'js>) -> Result<Self> {
                    T::from_js(ctx, value).map($type::new)
                }
            }
        )*
    };

    // for tuple types
    (tup: $($($type:ident)*,)*) => {
        $(
            impl<'js, $($type,)*> FromJs<'js> for ($($type,)*)
            where
                $($type: FromJs<'js>,)*
            {
                fn from_js(_ctx: Ctx<'js>, value: Value<'js>) -> Result<Self> {
                    let array = Array::from_value(value)?;

                    let tuple_len = 0 $(+ from_js_impls!(@one $type))*;
                    let array_len = array.len();
                    tuple_match_size(array_len, tuple_len)?;

                    Ok((
                        $(array.get::<$type>(from_js_impls!(@idx $type))?,)*
                    ))
                }
            }
        )*
    };

    // for list-like Rust types
    (list: $($(#[$meta:meta])* $type:ident $({$param:ident: $($pguard:tt)*})* $(($($guard:tt)*))*,)*) => {
        $(
            $(#[$meta])*
            impl<'js, T $(,$param)*> FromJs<'js> for $type<T $(,$param)*>
            where
                T: FromJs<'js> $(+ $($guard)*)*,
                $($param: $($pguard)*,)*
            {
                fn from_js(_ctx: Ctx<'js>, value: Value<'js>) -> Result<Self> {
                    let array = Array::from_value(value)?;
                    array.iter().collect::<Result<_>>()
                }
            }
        )*
    };

    // for map-like Rust types
    (map: $($(#[$meta:meta])* $type:ident $({$param:ident: $($pguard:tt)*})* $(($($guard:tt)*))*,)*) => {
        $(
            $(#[$meta])*
            impl<'js, K, V $(,$param)*> FromJs<'js> for $type<K, V $(,$param)*>
            where
                K: FromAtom<'js> $(+ $($guard)*)*,
                V: FromJs<'js>,
                $($param: $($pguard)*,)*
            {
                fn from_js(_ctx: Ctx<'js>, value: Value<'js>) -> Result<Self> {
                    let object = Object::from_value(value)?;
                    object.props().collect::<Result<_>>()
                }
            }
        )*
    };

    // for basic primitive types (int and float)
    // (ex. f64 => Float as_float Int as_int)
    (val: $($type:ty => $($jstype:ident $getfn:ident)*,)*) => {
        $(
            impl<'js> FromJs<'js> for $type {
                fn from_js(_ctx: Ctx<'js>, value: Value<'js>) -> Result<Self> {
                    let type_ = value.type_of();
                    match type_ {
                        $(Type::$jstype => Ok(unsafe { value.$getfn() } as _),)*
                        _ => Err(Error::new_from_js(type_.as_str(), stringify!($type))),
                    }
                }
            }
        )*
    };

    // for other primitive types
    (val: $($base:ident: $($type:ident)*,)*) => {
        $(
            $(
                impl<'js> FromJs<'js> for $type {
                    fn from_js(ctx: Ctx<'js>, value: Value<'js>) -> Result<Self> {
                        let num = <$base>::from_js(ctx, value)?;
                        number_match_range(num, $type::MIN as $base, $type::MAX as $base, stringify!($base), stringify!($type))?;
                        Ok(num as $type)
                    }
                }
            )*
        )*
    };

    (@one $($t:tt)*) => { 1 };

    (@idx A) => { 0 };
    (@idx B) => { 1 };
    (@idx C) => { 2 };
    (@idx D) => { 3 };
    (@idx E) => { 4 };
    (@idx F) => { 5 };
    (@idx G) => { 6 };
    (@idx H) => { 7 };
    (@idx I) => { 8 };
    (@idx J) => { 9 };
    (@idx K) => { 10 };
    (@idx L) => { 11 };
    (@idx M) => { 12 };
    (@idx N) => { 13 };
    (@idx O) => { 14 };
    (@idx P) => { 15 };
}

from_js_impls! {
    val:
    i32: i8 u8 i16 u16,
    f64: u32 u64 i64 usize isize,
}

from_js_impls! {
    val:
    bool => Bool get_bool,
    i32 => Int get_int,
    f64 => Float get_float Int get_int,
}

from_js_impls! {
    ref:
    Box,
    Rc,
    Arc,
    Cell,
    RefCell,
    Mutex,
    RwLock,
}

from_js_impls! {
    tup:
    A,
    A B,
    A B C,
    A B C D,
    A B C D E,
    A B C D E F,
    A B C D E F G,
    A B C D E F G H,
    A B C D E F G H I,
    A B C D E F G H I J,
    A B C D E F G H I J K,
    A B C D E F G H I J K L,
    A B C D E F G H I J K L M,
    A B C D E F G H I J K L M N,
    A B C D E F G H I J K L M N O,
    A B C D E F G H I J K L M N O P,
}

from_js_impls! {
    list:
    /// Convert from JS array to Rust vector
    Vec,
    /// Convert from JS array to Rust vector deque
    VecDeque,
    /// Convert from JS array to Rust linked list
    LinkedList,
    /// Convert from JS array to Rust hash set
    HashSet {S: Default + BuildHasher} (Eq + Hash),
    /// Convert from JS array to Rust btree set
    BTreeSet (Eq + Ord),
    /// Convert from JS array to Rust index set
    #[cfg(feature = "indexmap")]
    #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "indexmap")))]
    IndexSet {S: Default + BuildHasher} (Eq + Hash),
}

from_js_impls! {
    map:
    /// Convert from JS object to Rust hash map
    HashMap {S: Default + BuildHasher} (Eq + Hash),
    /// Convert from JS object to Rust btree map
    BTreeMap (Eq + Ord),
    /// Convert from JS object to Rust index map
    #[cfg(feature = "indexmap")]
    #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "indexmap")))]
    IndexMap {S: Default + BuildHasher} (Eq + Hash),
}

impl<'js> FromJs<'js> for f32 {
    fn from_js(ctx: Ctx<'js>, value: Value<'js>) -> Result<Self> {
        f64::from_js(ctx, value).map(|value| value as _)
    }
}