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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
use crate::{
    function::IntoJsFunc, qjs, Ctx, Function, IntoAtom, IntoJs, Object, Result, Undefined, Value,
};

impl<'js> Object<'js> {
    /// Define a property of an object
    ///
    /// ```
    /// # use rquickjs::{Runtime, Context, Object, object::{Property, Accessor}};
    /// # let rt = Runtime::new().unwrap();
    /// # let ctx = Context::full(&rt).unwrap();
    /// # ctx.with(|ctx| {
    /// # let obj = Object::new(ctx).unwrap();
    /// // Define readonly property without value
    /// obj.prop("no_val", ()).unwrap();
    /// // Define readonly property with value
    /// obj.prop("ro_str", "Some const text").unwrap();
    /// // Define readonly property with value and make it to be writable
    /// obj.prop("ro_str2", Property::from("Some const text").writable()).unwrap();
    /// // Define readonly property using getter and make it to be enumerable
    /// obj.prop("ro_str_get", Accessor::from(|| "Some readable text").enumerable()).unwrap();
    /// // Define readonly property using getter and setter
    /// obj.prop("ro_str_get_set",
    ///     Accessor::from(|| "Some text")
    ///         .set(|new_val: String| { /* do something */ })
    /// ).unwrap();
    /// # })
    /// ```
    #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "properties")))]
    pub fn prop<K, V, P>(&self, key: K, prop: V) -> Result<()>
    where
        K: IntoAtom<'js>,
        V: AsProperty<'js, P>,
    {
        let ctx = self.ctx();
        let key = key.into_atom(ctx)?;
        let (flags, value, getter, setter) = prop.config(ctx)?;
        let flags = flags | (qjs::JS_PROP_THROW as PropertyFlags);
        unsafe {
            let res = qjs::JS_DefineProperty(
                ctx.as_ptr(),
                self.0.as_js_value(),
                key.atom,
                value.as_js_value(),
                getter.as_js_value(),
                setter.as_js_value(),
                flags,
            );
            if res < 0 {
                return Err(self.0.ctx.raise_exception());
            }
        }
        Ok(())
    }
}

pub type PropertyFlags = qjs::c_int;

/// The property interface
#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "properties")))]
pub trait AsProperty<'js, P> {
    /// Property configuration
    ///
    /// Returns the tuple which includes the following:
    /// - flags
    /// - value or undefined when no value is here
    /// - getter or undefined if the property hasn't getter
    /// - setter or undefined if the property hasn't setter
    fn config(self, ctx: &Ctx<'js>) -> Result<(PropertyFlags, Value<'js>, Value<'js>, Value<'js>)>;
}

macro_rules! wrapper_impls {
	  ($($(#[$type_meta:meta])* $type:ident<$($param:ident),*>($($field:ident)*; $($flag:ident)*))*) => {
        $(
            $(#[$type_meta])*
            #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "properties")))]
            #[derive(Debug, Clone, Copy)]
            pub struct $type<$($param),*> {
                flags: PropertyFlags,
                $($field: $param,)*
            }

            impl<$($param),*> $type<$($param),*> {
                $(wrapper_impls!{@flag $flag concat!("Make the property to be ", stringify!($flag))})*
            }
        )*
	  };

    (@flag $flag:ident $doc:expr) => {
        #[doc = $doc]
        #[must_use]
        pub fn $flag(mut self) -> Self {
            self.flags |= wrapper_impls!(@flag $flag);
            self
        }
    };

    (@flag $flag:ident) => { wrapper_impls!{@_flag $flag} as PropertyFlags };
    (@_flag configurable) => { qjs::JS_PROP_CONFIGURABLE };
    (@_flag enumerable) => { qjs::JS_PROP_ENUMERABLE };
    (@_flag writable) => { qjs::JS_PROP_WRITABLE };
    (@_flag value) => { qjs::JS_PROP_HAS_VALUE };
    (@_flag get) => { qjs::JS_PROP_HAS_GET };
    (@_flag set) => { qjs::JS_PROP_HAS_SET };
}

impl<'js, T> AsProperty<'js, T> for T
where
    T: IntoJs<'js>,
{
    fn config(self, ctx: &Ctx<'js>) -> Result<(PropertyFlags, Value<'js>, Value<'js>, Value<'js>)> {
        Ok((
            wrapper_impls!(@flag value),
            self.into_js(ctx)?,
            Undefined.into_js(ctx)?,
            Undefined.into_js(ctx)?,
        ))
    }
}

wrapper_impls! {
    /// The data descriptor of a property
    Property<T>(value; writable configurable enumerable)
    /// The accessor descriptor of a readonly property
    Accessor<G, S>(get set; configurable enumerable)
}

/// Create property data descriptor from value
impl<T> From<T> for Property<T> {
    fn from(value: T) -> Self {
        Self {
            flags: wrapper_impls!(@flag value),
            value,
        }
    }
}

impl<'js, T> AsProperty<'js, T> for Property<T>
where
    T: IntoJs<'js>,
{
    fn config(self, ctx: &Ctx<'js>) -> Result<(PropertyFlags, Value<'js>, Value<'js>, Value<'js>)> {
        Ok((
            self.flags,
            self.value.into_js(ctx)?,
            Undefined.into_js(ctx)?,
            Undefined.into_js(ctx)?,
        ))
    }
}

impl<G> From<G> for Accessor<G, ()> {
    fn from(get: G) -> Self {
        Self {
            get,
            set: (),
            flags: wrapper_impls!(@flag get),
        }
    }
}

impl<G> Accessor<G, ()> {
    /// Create accessor from getter
    pub fn new_get(get: G) -> Self {
        Self {
            flags: wrapper_impls!(@flag get),
            get,
            set: (),
        }
    }

    /// Add setter to accessor
    pub fn set<S>(self, set: S) -> Accessor<G, S> {
        Accessor {
            flags: self.flags | wrapper_impls!(@flag set),
            get: self.get,
            set,
        }
    }
}

impl<S> Accessor<(), S> {
    /// Create accessor from setter
    pub fn new_set(set: S) -> Self {
        Self {
            flags: wrapper_impls!(@flag set),
            get: (),
            set,
        }
    }

    /// Add getter to accessor
    pub fn get<G>(self, get: G) -> Accessor<G, S> {
        Accessor {
            flags: self.flags | wrapper_impls!(@flag get),
            get,
            set: self.set,
        }
    }
}

impl<G, S> Accessor<G, S> {
    /// Create accessor from getter and setter
    pub fn new(get: G, set: S) -> Self {
        Self {
            flags: wrapper_impls!(@flag get) | wrapper_impls!(@flag set),
            get,
            set,
        }
    }
}

/// A property with getter only
impl<'js, G, GA> AsProperty<'js, (GA, (), ())> for Accessor<G, ()>
where
    G: IntoJsFunc<'js, GA> + 'js,
{
    fn config(self, ctx: &Ctx<'js>) -> Result<(PropertyFlags, Value<'js>, Value<'js>, Value<'js>)> {
        Ok((
            self.flags,
            Undefined.into_js(ctx)?,
            Function::new(ctx.clone(), self.get)?.into_value(),
            Undefined.into_js(ctx)?,
        ))
    }
}

/// A property with setter only
impl<'js, S, SA> AsProperty<'js, ((), (), SA)> for Accessor<(), S>
where
    S: IntoJsFunc<'js, SA> + 'js,
{
    fn config(self, ctx: &Ctx<'js>) -> Result<(PropertyFlags, Value<'js>, Value<'js>, Value<'js>)> {
        Ok((
            self.flags,
            Undefined.into_js(ctx)?,
            Undefined.into_js(ctx)?,
            Function::new(ctx.clone(), self.set)?.into_value(),
        ))
    }
}

/// A property with getter and setter
impl<'js, G, GA, S, SA> AsProperty<'js, (GA, SA)> for Accessor<G, S>
where
    G: IntoJsFunc<'js, GA> + 'js,
    S: IntoJsFunc<'js, SA> + 'js,
{
    fn config(self, ctx: &Ctx<'js>) -> Result<(PropertyFlags, Value<'js>, Value<'js>, Value<'js>)> {
        Ok((
            self.flags,
            Undefined.into_js(ctx)?,
            Function::new(ctx.clone(), self.get)?.into_value(),
            Function::new(ctx.clone(), self.set)?.into_value(),
        ))
    }
}

#[cfg(test)]
mod test {
    use crate::{object::*, *};

    #[test]
    fn property_with_undefined() {
        test_with(|ctx| {
            let obj = Object::new(ctx.clone()).unwrap();
            obj.prop("key", ()).unwrap();

            let _: () = obj.get("key").unwrap();

            if let Err(Error::Exception) = obj.set("key", "") {
                let exception = Exception::from_js(&ctx, ctx.catch()).unwrap();
                assert_eq!(exception.message().as_deref(), Some("'key' is read-only"));
            } else {
                panic!("Should fail");
            }
        });
    }

    #[test]
    fn property_with_value() {
        test_with(|ctx| {
            let obj = Object::new(ctx.clone()).unwrap();
            obj.prop("key", "str").unwrap();

            let s: StdString = obj.get("key").unwrap();
            assert_eq!(s, "str");

            if let Err(Error::Exception) = obj.set("key", "") {
                let exception = Exception::from_js(&ctx, ctx.catch()).unwrap();
                assert_eq!(exception.message().as_deref(), Some("'key' is read-only"));
            } else {
                panic!("Should fail");
            }
        });
    }

    #[test]
    fn property_with_data_descriptor() {
        test_with(|ctx| {
            let obj = Object::new(ctx).unwrap();
            obj.prop("key", Property::from("str")).unwrap();

            let s: StdString = obj.get("key").unwrap();
            assert_eq!(s, "str");
        });
    }

    #[test]
    #[should_panic(expected = "Error: 'key' is read-only")]
    fn property_with_data_descriptor_readonly() {
        test_with(|ctx| {
            let obj = Object::new(ctx.clone()).unwrap();
            obj.prop("key", Property::from("str")).unwrap();
            obj.set("key", "text")
                .catch(&ctx)
                .map_err(|error| panic!("{}", error))
                .unwrap();
        });
    }

    #[test]
    fn property_with_data_descriptor_writable() {
        test_with(|ctx| {
            let obj = Object::new(ctx).unwrap();
            obj.prop("key", Property::from("str").writable()).unwrap();
            obj.set("key", "text").unwrap();
        });
    }

    #[test]
    #[should_panic(expected = "Error: property is not configurable")]
    fn property_with_data_descriptor_not_configurable() {
        test_with(|ctx| {
            let obj = Object::new(ctx.clone()).unwrap();
            obj.prop("key", Property::from("str")).unwrap();
            obj.prop("key", Property::from(39))
                .catch(&ctx)
                .map_err(|error| panic!("{}", error))
                .unwrap();
        });
    }

    #[test]
    fn property_with_data_descriptor_configurable() {
        test_with(|ctx| {
            let obj = Object::new(ctx).unwrap();
            obj.prop("key", Property::from("str").configurable())
                .unwrap();
            obj.prop("key", Property::from(39)).unwrap();
        });
    }

    #[test]
    fn property_with_data_descriptor_not_enumerable() {
        test_with(|ctx| {
            let obj = Object::new(ctx).unwrap();
            obj.prop("key", Property::from("str")).unwrap();
            let keys: Vec<StdString> = obj
                .own_keys(object::Filter::new().string())
                .collect::<Result<_>>()
                .unwrap();
            assert_eq!(keys.len(), 1);
            assert_eq!(&keys[0], "key");
            let keys: Vec<StdString> = obj.keys().collect::<Result<_>>().unwrap();
            assert_eq!(keys.len(), 0);
        });
    }

    #[test]
    fn property_with_data_descriptor_enumerable() {
        test_with(|ctx| {
            let obj = Object::new(ctx).unwrap();
            obj.prop("key", Property::from("str").enumerable()).unwrap();
            let keys: Vec<StdString> = obj.keys().collect::<Result<_>>().unwrap();
            assert_eq!(keys.len(), 1);
            assert_eq!(&keys[0], "key");
        });
    }

    #[test]
    fn property_with_getter_only() {
        test_with(|ctx| {
            let obj = Object::new(ctx.clone()).unwrap();
            obj.prop("key", Accessor::from(|| "str")).unwrap();

            let s: StdString = obj.get("key").unwrap();
            assert_eq!(s, "str");

            if let Err(Error::Exception) = obj.set("key", "") {
                let exception = Exception::from_js(&ctx, ctx.catch()).unwrap();
                assert_eq!(
                    exception.message().as_deref(),
                    Some("no setter for property")
                );
            } else {
                panic!("Should fail");
            }
        });
    }

    #[test]
    fn property_with_getter_and_setter() {
        test_with(|ctx| {
            let val = Ref::new(Mut::new(StdString::new()));
            let obj = Object::new(ctx).unwrap();
            obj.prop(
                "key",
                Accessor::from({
                    let val = val.clone();
                    move || val.lock().clone()
                })
                .set({
                    let val = val.clone();
                    move |s| {
                        *val.lock() = s;
                    }
                }),
            )
            .unwrap();

            let s: StdString = obj.get("key").unwrap();
            assert_eq!(s, "");

            obj.set("key", "str").unwrap();
            assert_eq!(val.lock().clone(), "str");

            let s: StdString = obj.get("key").unwrap();
            assert_eq!(s, "str");

            obj.set("key", "").unwrap();
            let s: StdString = obj.get("key").unwrap();
            assert_eq!(s, "");
            assert_eq!(val.lock().clone(), "");
        });
    }
}