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
use error::{Error, Result};
use ffi;
use std::marker::PhantomData;
use types::Ref;
use util::{protect_duktape_closure, StackGuard};
use function::Function;
use value::{FromValue, ToValue, ToValues, Value};
/// Reference to a JavaScript object (guaranteed to not be an array or function).
#[derive(Clone, Debug)]
pub struct Object<'ducc>(pub(crate) Ref<'ducc>);
impl<'ducc> Object<'ducc> {
/// Get an object property value using the given key. Returns `Value::Undefined` if no property
/// with the key exists.
///
/// # Errors
///
/// This function returns an error if:
///
/// * `ToValue::to_value` fails for the key
/// * The `ToPropertyKey` implementation for the key fails
pub fn get<K: ToValue<'ducc>, V: FromValue<'ducc>>(&self, key: K) -> Result<V> {
let ducc = self.0.ducc;
let key = key.to_value(ducc)?;
let value = unsafe {
assert_stack!(ducc.ctx, 0, {
ducc.push_ref(&self.0);
ducc.push_value(key);
protect_duktape_closure(ducc.ctx, 2, 1, |ctx| {
ffi::duk_get_prop(ctx, -2);
})?;
ducc.pop_value()
})
};
V::from_value(value, ducc)
}
/// Sets an object property using the given key and value.
///
/// # Errors
///
/// This function returns an error if:
///
/// * `ToValue::to_value` fails for either the key or the value
/// * The `ToPropertyKey` implementation for the key fails
pub fn set<K: ToValue<'ducc>, V: ToValue<'ducc>>(&self, key: K, value: V) -> Result<()> {
let ducc = self.0.ducc;
let key = key.to_value(ducc)?;
let value = value.to_value(ducc)?;
unsafe {
assert_stack!(ducc.ctx, 0, {
ducc.push_ref(&self.0);
ducc.push_value(key);
ducc.push_value(value);
protect_duktape_closure(ducc.ctx, 3, 0, |ctx| {
ffi::duk_put_prop(ctx, -3);
})
})
}
}
/// Defines a property using given key and descriptor
///
/// # Example
///
/// ```
/// # use ducc::{Ducc, PropertyDescriptor};
/// # let ducc = Ducc::new();
/// let obj = ducc.create_object();
/// let get = ducc.create_function(|inv| Ok(24));
/// obj.define_prop("prop", PropertyDescriptor::new().getter(get)).unwrap();
/// ```
pub fn define_prop<K: ToValue<'ducc>>(&self, key: K, desc: PropertyDescriptor<'ducc>) -> Result<()> {
let ducc = self.0.ducc;
let key = key.to_value(ducc)?;
let mut flags = 0;
flags |= match desc.writable {
Some(true) => ffi::DUK_DEFPROP_HAVE_WRITABLE | ffi::DUK_DEFPROP_WRITABLE,
Some(false) => ffi::DUK_DEFPROP_HAVE_WRITABLE,
None => 0
};
flags |= match desc.enumerable {
Some(true) => ffi::DUK_DEFPROP_HAVE_ENUMERABLE | ffi::DUK_DEFPROP_ENUMERABLE,
Some(false) => ffi::DUK_DEFPROP_HAVE_ENUMERABLE,
None => 0
};
flags |= match desc.configurable {
Some(true) => ffi::DUK_DEFPROP_HAVE_CONFIGURABLE | ffi::DUK_DEFPROP_CONFIGURABLE,
Some(false) => ffi::DUK_DEFPROP_HAVE_CONFIGURABLE,
None => 0
};
unsafe {
assert_stack!(ducc.ctx, 0, {
ducc.push_ref(&self.0);
ducc.push_value(key);
let mut num_args = 2;
match desc.source {
PropertySource::Undefined => {},
PropertySource::Value(val) => {
ducc.push_value(val);
flags |= ffi::DUK_DEFPROP_HAVE_VALUE;
num_args += 1;
},
PropertySource::GetSet(get, set) => {
ducc.push_value(get.to_value(ducc)?);
ducc.push_value(set.to_value(ducc)?);
flags |=
ffi::DUK_DEFPROP_HAVE_GETTER | ffi::DUK_DEFPROP_HAVE_SETTER;
num_args += 2;
},
PropertySource::Get(get) => {
ducc.push_value(get.to_value(ducc)?);
flags |= ffi::DUK_DEFPROP_HAVE_GETTER;
num_args += 1;
},
PropertySource::Set(set) => {
ducc.push_value(set.to_value(ducc)?);
flags |= ffi::DUK_DEFPROP_HAVE_SETTER;
num_args += 1;
}
}
protect_duktape_closure(ducc.ctx, num_args, 0, |ctx| {
ffi::duk_def_prop(ctx, -num_args, flags);
})
})
}
}
/// Removes the given key from the object. This function does nothing if the property does not
/// exist.
///
/// # Errors
///
/// This function returns an error if:
///
/// * `ToValue::to_value` fails for the key
/// * The `ToPropertyKey` implementation for the key fails
pub fn remove<K: ToValue<'ducc>>(&self, key: K) -> Result<()> {
let ducc = self.0.ducc;
let key = key.to_value(ducc)?;
unsafe {
assert_stack!(ducc.ctx, 0, {
ducc.push_ref(&self.0);
ducc.push_value(key);
protect_duktape_closure(ducc.ctx, 2, 0, |ctx| {
ffi::duk_del_prop(ctx, -2);
})
})
}
}
/// Returns `true` if the given key is a property of the object, `false` otherwise.
///
/// # Errors
///
/// This function returns an error if:
///
/// * `ToValue::to_value` fails for the key
/// * The `ToPropertyKey` implementation for the key fails
pub fn contains_key<K: ToValue<'ducc>>(&self, key: K) -> Result<bool> {
let ducc = self.0.ducc;
let key = key.to_value(ducc)?;
unsafe {
assert_stack!(ducc.ctx, 0, {
ducc.push_ref(&self.0);
ducc.push_value(key);
protect_duktape_closure(ducc.ctx, 2, 0, |ctx| {
ffi::duk_has_prop(ctx, -2) != 0
})
})
}
}
/// Returns the number of elements in the object using the calculation
/// `Math.floor(ToNumber(obj.length))`. This function can return an error if the `ToNumber`
/// implementation fails or if the `length` getter fails. Returns `Ok(0)` if the calculation
/// returns a number (a floating point in JavaScript land) outside of the range of `usize`.
pub fn len(&self) -> Result<usize> {
let ducc = self.0.ducc;
unsafe {
assert_stack!(ducc.ctx, 0, {
ducc.push_ref(&self.0);
protect_duktape_closure(ducc.ctx, 1, 0, |ctx| {
ffi::duk_get_length(ctx, -1)
})
})
}
}
/// Calls the function at the key with the given arguments, with `this` set to the object.
/// Returns an error if the value at the key is not a function.
pub fn call_prop<K, A, R>(&self, key: K, args: A) -> Result<R>
where
K: ToValue<'ducc>,
A: ToValues<'ducc>,
R: FromValue<'ducc>,
{
let value: Value = self.get(key)?;
if let Some(func) = value.as_function() {
func.call_method(self.clone(), args)
} else {
Err(Error::not_a_function())
}
}
/// Returns an iterator over the object's keys and values, acting like a `for-in` loop: own and
/// inherited enumerable properties are included, and enumeration order follows the ES2015
/// `OwnPropertyKeys` enumeration order, applied for each inheritance level.
pub fn properties<K: FromValue<'ducc>, V: FromValue<'ducc>>(self) -> Properties<'ducc, K, V> {
let ducc = self.0.ducc;
unsafe {
let _sg = StackGuard::new(ducc.ctx);
ducc.push_ref(&self.0);
ffi::duk_require_stack(ducc.ctx, 1);
ffi::duk_enum(ducc.ctx, -1, 0);
Properties {
object_enum: ducc.pop_ref(),
_phantom: PhantomData,
}
}
}
}
enum PropertySource<'ducc> {
Undefined,
Value(Value<'ducc>),
GetSet(Function<'ducc>, Function<'ducc>),
Get(Function<'ducc>),
Set(Function<'ducc>),
}
pub struct PropertyDescriptor<'ducc> {
enumerable: Option<bool>,
configurable: Option<bool>,
writable: Option<bool>,
source: PropertySource<'ducc>
}
impl <'ducc> PropertyDescriptor<'ducc> {
pub fn new() -> PropertyDescriptor<'ducc> {
PropertyDescriptor {
enumerable: None,
configurable: None,
writable: None,
source: PropertySource::Undefined
}
}
/// Whether this property shows up during enumeration of the
/// properties on the corresponding object.
///
/// Defaults to `false`
pub fn enumerable(mut self, b: bool) -> Self {
self.enumerable = Some(b);
self
}
/// Whether the type of this property descriptor may be changed and
/// the property may be deleted from the corresponding object.
///
/// Defaults to `false`
pub fn configurable(mut self, b: bool) -> Self {
self.configurable = Some(b);
self
}
/// Whether the value associated with the property may be changed with
/// an assignment operator. Must not be set when using getters or setters.
///
/// Defaults to `false`
pub fn writable(mut self, b: bool) -> Self {
self.writable = Some(b);
self
}
/// Builds the descriptor with given value for the property
pub fn value(mut self, value: Value<'ducc>) -> Self {
self.source = PropertySource::Value(value);
self
}
/// Builds the descriptor with a getter and a setter
pub fn getter_setter(mut self, get: Function<'ducc>, set: Function<'ducc>) -> Self {
self.source = PropertySource::GetSet(get, set);
self
}
/// Builds the descriptor with a getter
pub fn getter(mut self, get: Function<'ducc>) -> Self {
self.source = PropertySource::Get(get);
self
}
/// Builds the descriptor with a setter
pub fn setter(mut self, set: Function<'ducc>) -> Self {
self.source = PropertySource::Set(set);
self
}
}
pub struct Properties<'ducc, K, V> {
object_enum: Ref<'ducc>,
_phantom: PhantomData<(K, V)>,
}
impl<'ducc, K, V> Iterator for Properties<'ducc, K, V>
where
K: FromValue<'ducc>,
V: FromValue<'ducc>,
{
type Item = Result<(K, V)>;
fn next(&mut self) -> Option<Self::Item> {
let ducc = self.object_enum.ducc;
unsafe {
let _sg = StackGuard::new(ducc.ctx);
ducc.push_ref(&self.object_enum);
ffi::duk_require_stack(ducc.ctx, 2);
if ffi::duk_next(ducc.ctx, -1, 1) != 0 {
let value = match ducc.pop_value().into(ducc) {
Ok(value) => value,
Err(err) => return Some(Err(err)),
};
let key = match ducc.pop_value().into(ducc) {
Ok(key) => key,
Err(err) => return Some(Err(err)),
};
Some(Ok((key, value)))
} else {
None
}
}
}
}