1use crate::{
4 atom::PredefinedAtom,
5 class::{Class, JsClass},
6 function::ffi::RustFunc,
7 qjs, Ctx, Error, FromJs, IntoJs, Object, Result, Value,
8};
9
10mod args;
11mod ffi;
12mod into_func;
13mod params;
14mod types;
15
16use alloc::{borrow::ToOwned as _, boxed::Box};
17pub use args::{Args, IntoArg, IntoArgs};
18pub use ffi::RustFunction;
19pub use params::{FromParam, FromParams, ParamRequirement, Params, ParamsAccessor};
20#[cfg(feature = "futures")]
21pub use types::Async;
22pub use types::{Exhaustive, Flat, Func, FuncArg, MutFn, Null, OnceFn, Opt, Rest, This};
23
24pub trait IntoJsFunc<'js, P> {
26 fn param_requirements() -> ParamRequirement;
29
30 fn call<'a>(&self, params: Params<'a, 'js>) -> Result<Value<'js>>;
32}
33
34#[derive(Clone, Debug, PartialEq, Eq, Hash)]
36#[repr(transparent)]
37pub struct Function<'js>(pub(crate) Object<'js>);
38
39impl<'js> Function<'js> {
40 pub fn new<P, F>(ctx: Ctx<'js>, f: F) -> Result<Self>
42 where
43 F: IntoJsFunc<'js, P> + 'js,
44 {
45 let func = Box::new(move |params: Params<'_, 'js>| {
46 params.check_params(F::param_requirements())?;
47 f.call(params)
48 }) as Box<dyn RustFunc<'js> + 'js>;
49
50 let cls = Class::instance(ctx, RustFunction(func))?;
51 debug_assert!(cls.is_function());
52 Function(cls.into_inner()).with_length(F::param_requirements().min())
53 }
54
55 pub fn call<A, R>(&self, args: A) -> Result<R>
57 where
58 A: IntoArgs<'js>,
59 R: FromJs<'js>,
60 {
61 let ctx = self.ctx();
62 let num = args.num_args();
63 let mut accum_args = Args::new(ctx.clone(), num);
64 args.into_args(&mut accum_args)?;
65 self.call_arg(accum_args)
66 }
67
68 pub fn call_arg<R>(&self, args: Args<'js>) -> Result<R>
70 where
71 R: FromJs<'js>,
72 {
73 args.apply(self)
74 }
75
76 pub fn defer<A>(&self, args: A) -> Result<()>
81 where
82 A: IntoArgs<'js>,
83 {
84 let ctx = self.ctx();
85 let num = args.num_args();
86 let mut accum_args = Args::new(ctx.clone(), num);
87 args.into_args(&mut accum_args)?;
88 self.defer_arg(accum_args)?;
89 Ok(())
90 }
91
92 pub fn defer_arg(&self, args: Args<'js>) -> Result<()> {
94 args.defer(self.clone())
95 }
96
97 pub fn set_name<S: AsRef<str>>(&self, name: S) -> Result<()> {
99 let name = name.as_ref().into_js(self.ctx())?;
100 unsafe {
101 let res = qjs::JS_DefinePropertyValue(
102 self.0.ctx.as_ptr(),
103 self.0.as_js_value(),
104 PredefinedAtom::Name as qjs::JSAtom,
105 name.into_js_value(),
106 (qjs::JS_PROP_CONFIGURABLE | qjs::JS_PROP_THROW) as _,
107 );
108 if res < 0 {
109 return Err(self.0.ctx.raise_exception());
110 }
111 };
112 Ok(())
113 }
114
115 pub fn with_name<S: AsRef<str>>(self, name: S) -> Result<Self> {
117 self.set_name(name)?;
118 Ok(self)
119 }
120
121 pub fn set_length(&self, len: usize) -> Result<()> {
123 let len = len.into_js(self.ctx())?;
124 unsafe {
125 let res = qjs::JS_DefinePropertyValue(
126 self.0.ctx.as_ptr(),
127 self.0.as_js_value(),
128 PredefinedAtom::Length as qjs::JSAtom,
129 len.into_js_value(),
130 (qjs::JS_PROP_CONFIGURABLE | qjs::JS_PROP_THROW) as _,
131 );
132 if res < 0 {
133 return Err(self.0.ctx.raise_exception());
134 }
135 };
136 Ok(())
137 }
138
139 pub fn with_length(self, len: usize) -> Result<Self> {
141 self.set_length(len)?;
142 Ok(self)
143 }
144
145 pub fn prototype(ctx: Ctx<'js>) -> Object<'js> {
148 let res = unsafe {
149 let v = qjs::JS_GetFunctionProto(ctx.as_ptr());
150 Value::from_js_value(ctx, v)
151 };
152 res.into_object()
154 .expect("`Function.prototype` wasn't an object")
155 }
156
157 pub fn is_constructor(&self) -> bool {
159 unsafe { qjs::JS_IsConstructor(self.ctx().as_ptr(), self.0.as_js_value()) }
160 }
161
162 pub fn set_constructor(&self, is_constructor: bool) {
164 unsafe {
165 qjs::JS_SetConstructorBit(self.ctx().as_ptr(), self.0.as_js_value(), is_constructor)
166 };
167 }
168
169 pub fn with_constructor(self, is_constructor: bool) -> Self {
171 self.set_constructor(is_constructor);
172 self
173 }
174}
175
176#[derive(Debug, Clone)]
180#[repr(transparent)]
181pub struct Constructor<'js>(pub(crate) Function<'js>);
182
183impl<'js> Constructor<'js> {
184 pub fn new_class<C, F, P>(ctx: Ctx<'js>, f: F) -> Result<Self>
189 where
190 F: IntoJsFunc<'js, P> + 'js,
191 C: JsClass<'js>,
192 {
193 let func = Box::new(move |params: Params<'_, 'js>| -> Result<Value<'js>> {
194 params.check_params(F::param_requirements())?;
195 let this = params.this();
196 let ctx = params.ctx().clone();
197
198 let proto = this
200 .into_function()
201 .map(|func| func.get(PredefinedAtom::Prototype))
202 .unwrap_or_else(|| Class::<C>::prototype(&ctx))?;
203
204 let res = f.call(params)?;
205 res.as_object()
206 .ok_or_else(|| Error::IntoJs {
207 from: res.type_of().as_str(),
208 to: "object",
209 message: Some("rust constructor function did not return a object".to_owned()),
210 })?
211 .set_prototype(proto.as_ref())?;
212 Ok(res)
213 });
214 let func = Function(Class::instance(ctx.clone(), RustFunction(func))?.into_inner())
215 .with_name(C::NAME)?
216 .with_constructor(true);
217 unsafe {
218 qjs::JS_SetConstructor(
219 ctx.as_ptr(),
220 func.as_js_value(),
221 Class::<C>::prototype(&ctx)?
222 .as_ref()
223 .map(|x| x.as_js_value())
224 .unwrap_or(qjs::JS_NULL),
225 )
226 };
227 Ok(Constructor(func))
228 }
229
230 pub fn new_prototype<F, P>(ctx: &Ctx<'js>, prototype: Object<'js>, f: F) -> Result<Self>
234 where
235 F: IntoJsFunc<'js, P> + 'js,
236 {
237 let func = Box::new(move |params: Params<'_, 'js>| -> Result<Value<'js>> {
238 params.check_params(F::param_requirements())?;
239 let this = params.this();
240
241 let proto = this
242 .into_function()
243 .or_else(|| params.function().into_function())
244 .map(|func| func.get(PredefinedAtom::Prototype))
245 .transpose()?
246 .flatten();
247
248 let res = f.call(params)?;
249 res.as_object()
250 .ok_or_else(|| Error::IntoJs {
251 from: res.type_of().as_str(),
252 to: "object",
253 message: Some("rust constructor function did not return a object".to_owned()),
254 })?
255 .set_prototype(proto.as_ref())?;
256 Ok(res)
257 });
258 let func = Function(Class::instance(ctx.clone(), RustFunction(func))?.into_inner())
259 .with_constructor(true);
260 unsafe {
261 qjs::JS_SetConstructor(ctx.as_ptr(), func.as_js_value(), prototype.as_js_value())
262 };
263 Ok(Constructor(func))
264 }
265
266 pub fn construct<A, R>(&self, args: A) -> Result<R>
270 where
271 A: IntoArgs<'js>,
272 R: FromJs<'js>,
273 {
274 let ctx = self.ctx();
275 let num = args.num_args();
276 let mut accum_args = Args::new(ctx.clone(), num);
277 args.into_args(&mut accum_args)?;
278 self.construct_args(accum_args)
279 }
280
281 pub fn construct_args<R>(&self, args: Args<'js>) -> Result<R>
285 where
286 R: FromJs<'js>,
287 {
288 args.construct(self)
289 }
290}
291
292#[cfg(test)]
293mod test {
294 use crate::{function::Args, prelude::*, *};
295 use approx::assert_abs_diff_eq as assert_approx_eq;
296
297 #[test]
298 fn call_js_fn_with_no_args_and_no_return() {
299 test_with(|ctx| {
300 let f: Function = ctx.eval("() => {}").unwrap();
301
302 let _: () = ().apply(&f).unwrap();
303 let _: () = f.call(()).unwrap();
304 })
305 }
306
307 #[test]
308 fn call_js_fn_with_no_args_and_return() {
309 test_with(|ctx| {
310 let f: Function = ctx.eval("() => 42").unwrap();
311
312 let res: i32 = ().apply(&f).unwrap();
313 assert_eq!(res, 42);
314
315 let res: i32 = f.call(()).unwrap();
316 assert_eq!(res, 42);
317 })
318 }
319
320 #[test]
321 fn call_js_fn_with_1_arg_and_return() {
322 test_with(|ctx| {
323 let f: Function = ctx.eval("a => a + 4").unwrap();
324
325 let res: i32 = (3,).apply(&f).unwrap();
326 assert_eq!(res, 7);
327
328 let res: i32 = f.call((1,)).unwrap();
329 assert_eq!(res, 5);
330 })
331 }
332
333 #[test]
334 fn call_js_fn_with_2_args_and_return() {
335 test_with(|ctx| {
336 let f: Function = ctx.eval("(a, b) => a * b + 4").unwrap();
337
338 let res: i32 = (3, 4).apply(&f).unwrap();
339 assert_eq!(res, 16);
340
341 let res: i32 = f.call((5, 1)).unwrap();
342 assert_eq!(res, 9);
343 })
344 }
345
346 #[test]
347 fn call_js_fn_with_var_args_and_return() {
348 let res: Vec<i8> = test_with(|ctx| {
349 let func: Function = ctx
350 .eval(
351 r#"
352 (...x) => [x.length, ...x]
353 "#,
354 )
355 .unwrap();
356 func.call((Rest(vec![1, 2, 3]),)).unwrap()
357 });
358 assert_eq!(res.len(), 4);
359 assert_eq!(res[0], 3);
360 assert_eq!(res[1], 1);
361 assert_eq!(res[2], 2);
362 assert_eq!(res[3], 3);
363 }
364
365 #[test]
366 fn call_js_fn_with_rest_args_and_return() {
367 let res: Vec<i8> = test_with(|ctx| {
368 let func: Function = ctx
369 .eval(
370 r#"
371 (a, b, ...x) => [a, b, x.length, ...x]
372 "#,
373 )
374 .unwrap();
375 func.call((-2, -1, Rest(vec![1, 2]))).unwrap()
376 });
377 assert_eq!(res.len(), 5);
378 assert_eq!(res[0], -2);
379 assert_eq!(res[1], -1);
380 assert_eq!(res[2], 2);
381 assert_eq!(res[3], 1);
382 assert_eq!(res[4], 2);
383 }
384
385 #[test]
386 fn call_js_fn_with_no_args_and_throw() {
387 test_with(|ctx| {
388 let f: Function = ctx
389 .eval("() => { throw new Error('unimplemented'); }")
390 .unwrap();
391
392 if let Err(Error::Exception) = f.call::<_, ()>(()) {
393 let exception = Exception::from_js(&ctx, ctx.catch()).unwrap();
394 assert_eq!(exception.message().as_deref(), Some("unimplemented"));
395 } else {
396 panic!("Should throws");
397 }
398 })
399 }
400
401 #[test]
402 fn call_js_fn_with_this_and_no_args_and_return() {
403 test_with(|ctx| {
404 let f: Function = ctx.eval("function f() { return this.val; } f").unwrap();
405 let obj = Object::new(ctx).unwrap();
406 obj.set("val", 42).unwrap();
407
408 let res: i32 = (This(obj.clone()),).apply(&f).unwrap();
409 assert_eq!(res, 42);
410 let res: i32 = f.call((This(obj),)).unwrap();
411 assert_eq!(res, 42);
412 })
413 }
414
415 #[test]
416 fn call_js_fn_with_this_and_1_arg_and_return() {
417 test_with(|ctx| {
418 let f: Function = ctx
419 .eval("function f(a) { return this.val * a; } f")
420 .unwrap();
421 let obj = Object::new(ctx).unwrap();
422 obj.set("val", 3).unwrap();
423
424 let res: i32 = (This(obj.clone()), 2).apply(&f).unwrap();
425 assert_eq!(res, 6);
426 let res: i32 = f.call((This(obj), 3)).unwrap();
427 assert_eq!(res, 9);
428 })
429 }
430
431 #[test]
432 fn call_js_fn_with_1_arg_deferred() {
433 let rt = Runtime::new().unwrap();
434 let ctx = Context::full(&rt).unwrap();
435 assert!(!rt.is_job_pending());
436 ctx.with(|ctx| {
437 let g = ctx.globals();
438 let f: Function = ctx.eval("(obj) => { obj.called = true; }").unwrap();
439 f.defer((g.clone(),)).unwrap();
440 let c: Value = g.get("called").unwrap();
441 assert_eq!(c.type_of(), Type::Undefined);
442 });
443 assert!(rt.is_job_pending());
444 ctx.with(|ctx| ctx.drain_jobs().unwrap());
445 ctx.with(|ctx| {
446 let g = ctx.globals();
447 let c: Value = g.get("called").unwrap();
448 assert_eq!(c.type_of(), Type::Bool);
449 });
450 }
451
452 fn check_deferred_calls(defer: impl for<'js> Fn(&Function<'js>, &Object<'js>, usize)) {
455 test_with(|ctx| {
456 let f: Function = ctx
457 .eval("var calls = []; (function (...args) { calls.push([this, ...args]); })")
458 .unwrap();
459 let this = Object::new(ctx.clone()).unwrap();
460 for n in 0..=6 {
461 defer(&f, &this, n);
462 }
463 ctx.drain_jobs().unwrap();
464
465 let calls: Vec<Vec<Value>> = ctx.globals().get("calls").unwrap();
466 assert_eq!(calls.len(), 7);
467 for (n, call) in calls.iter().enumerate() {
468 assert_eq!(call[0], *this.as_value());
469 let args: Vec<i32> = call[1..].iter().map(|v| v.as_int().unwrap()).collect();
470 assert_eq!(args, (1..=n as i32).collect::<Vec<_>>());
471 }
472 })
473 }
474
475 #[test]
476 fn call_js_fn_with_0_to_6_args_deferred() {
477 check_deferred_calls(|f, this, n| {
478 let this = This(this.clone());
479 match n {
480 0 => f.defer((this,)),
481 1 => f.defer((this, 1)),
482 2 => f.defer((this, 1, 2)),
483 3 => f.defer((this, 1, 2, 3)),
484 4 => f.defer((this, 1, 2, 3, 4)),
485 5 => f.defer((this, 1, 2, 3, 4, 5)),
486 6 => f.defer((this, 1, 2, 3, 4, 5, 6)),
487 _ => unreachable!(),
488 }
489 .unwrap()
490 });
491 }
492
493 #[test]
494 fn call_js_fn_with_0_to_6_sized_args_deferred() {
495 check_deferred_calls(|f, this, n| {
496 let mut args = Args::new(f.ctx().clone(), n);
497 args.this(this.clone()).unwrap();
498 args.push_args(1..=n as i32).unwrap();
499 f.defer_arg(args).unwrap();
500 });
501 }
502
503 #[test]
504 fn call_js_fn_with_more_args_than_reserved() {
505 test_with(|ctx| {
506 let f: Function = ctx.eval("(...args) => args").unwrap();
507 let objs: Vec<Object> = (0..6).map(|_| Object::new(ctx.clone()).unwrap()).collect();
508 let mut args = Args::new(ctx.clone(), 2);
509 args.push_args(objs.iter().cloned()).unwrap();
510 let res: Vec<Object> = f.call_arg(args).unwrap();
511 assert_eq!(res, objs);
512 })
513 }
514
515 fn test() {
516 println!("test");
517 }
518
519 #[test]
520 fn static_callback() {
521 test_with(|ctx| {
522 let f = Function::new(ctx.clone(), test).unwrap();
523 f.set_name("test").unwrap();
524 let eval: Function = ctx.eval("a => { a() }").unwrap();
525 (f.clone(),).apply::<()>(&eval).unwrap();
526 f.call::<_, ()>(()).unwrap();
527
528 let name: StdString = f.clone().into_inner().get("name").unwrap();
529 assert_eq!(name, "test");
530
531 let get_name: Function = ctx.eval("a => a.name").unwrap();
532 let name: StdString = get_name.call((f.clone(),)).unwrap();
533 assert_eq!(name, "test");
534 })
535 }
536
537 #[test]
538 fn const_callback() {
539 use std::sync::{Arc, Mutex};
540 test_with(|ctx| {
541 #[allow(clippy::mutex_atomic)]
542 let called = Arc::new(Mutex::new(false));
543 let called_clone = called.clone();
544 let f = Function::new(ctx.clone(), move || {
545 (*called_clone.lock().unwrap()) = true;
546 })
547 .unwrap();
548 f.set_name("test").unwrap();
549
550 let eval: Function = ctx.eval("a => { a() }").unwrap();
551 eval.call::<_, ()>((f.clone(),)).unwrap();
552 f.call::<_, ()>(()).unwrap();
553 assert!(*called.lock().unwrap());
554
555 let name: StdString = f.clone().into_inner().get("name").unwrap();
556 assert_eq!(name, "test");
557
558 let get_name: Function = ctx.eval("a => a.name").unwrap();
559 let name: StdString = get_name.call((f.clone(),)).unwrap();
560 assert_eq!(name, "test");
561 })
562 }
563
564 #[test]
565 fn mutable_callback() {
566 test_with(|ctx| {
567 let mut v = 0;
568 let f = Function::new(
569 ctx.clone(),
570 MutFn::new(move || {
571 v += 1;
572 v
573 }),
574 )
575 .unwrap();
576 f.set_name("test").unwrap();
577
578 let eval: Function = ctx.eval("a => a()").unwrap();
579 assert_eq!(eval.call::<_, i32>((f.clone(),)).unwrap(), 1);
580 assert_eq!(eval.call::<_, i32>((f.clone(),)).unwrap(), 2);
581 assert_eq!(eval.call::<_, i32>((f.clone(),)).unwrap(), 3);
582
583 let name: StdString = f.clone().into_inner().get("name").unwrap();
584 assert_eq!(name, "test");
585
586 let get_name: Function = ctx.eval("a => a.name").unwrap();
587 let name: StdString = get_name.call((f.clone(),)).unwrap();
588 assert_eq!(name, "test");
589 })
590 }
591
592 #[test]
593 #[should_panic(
594 expected = "Error borrowing function: can't borrow a value as it is already borrowed"
595 )]
596 fn recursively_called_mutable_callback() {
597 test_with(|ctx| {
598 let mut v = 0;
599 let f = Function::new(
600 ctx.clone(),
601 MutFn::new(move |ctx: Ctx| {
602 v += 1;
603 ctx.globals()
604 .get::<_, Function>("foo")
605 .unwrap()
606 .call::<_, ()>(())
607 .catch(&ctx)
608 .unwrap();
609 v
610 }),
611 )
612 .unwrap();
613 ctx.globals().set("foo", f.clone()).unwrap();
614 f.call::<_, ()>(()).unwrap();
615 })
616 }
617
618 #[test]
619 #[should_panic(
620 expected = "Error borrowing function: tried to use a value, which can only be used once, again."
621 )]
622 fn repeatedly_called_once_callback() {
623 test_with(|ctx| {
624 let mut v = 0;
625 let f = Function::new(
626 ctx.clone(),
627 OnceFn::from(move || {
628 v += 1;
629 v
630 }),
631 )
632 .unwrap();
633 ctx.globals().set("foo", f.clone()).unwrap();
634 f.call::<_, ()>(()).catch(&ctx).unwrap();
635 f.call::<_, ()>(()).catch(&ctx).unwrap();
636 })
637 }
638
639 #[test]
640 fn multiple_const_callbacks() {
641 test_with(|ctx| {
642 let globals = ctx.globals();
643 globals.set("one", Func::new(|| 1f64)).unwrap();
644 globals.set("neg", Func::new(|a: f64| -a)).unwrap();
645 globals
646 .set("add", Func::new(|a: f64, b: f64| a + b))
647 .unwrap();
648
649 let r: f64 = ctx.eval("neg(add(one(), 2))").unwrap();
650 assert_approx_eq!(r, -3.0);
651 })
652 }
653
654 #[test]
655 fn mutable_callback_which_can_fail() {
656 test_with(|ctx| {
657 let globals = ctx.globals();
658 let mut id_alloc = 0;
659 globals
660 .set(
661 "new_id",
662 Func::from(MutFn::from(move || {
663 id_alloc += 1;
664 if id_alloc < 4 {
665 Ok(id_alloc)
666 } else {
667 Err(Error::Unknown)
668 }
669 })),
670 )
671 .unwrap();
672
673 let id: u32 = ctx.eval("new_id()").unwrap();
674 assert_eq!(id, 1);
675 let id: u32 = ctx.eval("new_id()").unwrap();
676 assert_eq!(id, 2);
677 let id: u32 = ctx.eval("new_id()").unwrap();
678 assert_eq!(id, 3);
679 let _err = ctx.eval::<u32, _>("new_id()").unwrap_err();
680 })
681 }
682
683 #[test]
684 fn mutable_callback_with_ctx_which_reads_globals() {
685 test_with(|ctx| {
686 let globals = ctx.globals();
687 let mut id_alloc = 0;
688 globals
689 .set(
690 "new_id",
691 Func::from(MutFn::from(move |ctx: Ctx| {
692 let initial: Option<u32> = ctx.globals().get("initial_id")?;
693 if let Some(initial) = initial {
694 id_alloc += 1;
695 Ok(id_alloc + initial)
696 } else {
697 Err(Error::Unknown)
698 }
699 })),
700 )
701 .unwrap();
702
703 let _err = ctx.eval::<u32, _>("new_id()").unwrap_err();
704 globals.set("initial_id", 10).unwrap();
705
706 let id: u32 = ctx.eval("new_id()").unwrap();
707 assert_eq!(id, 11);
708 let id: u32 = ctx.eval("new_id()").unwrap();
709 assert_eq!(id, 12);
710 let id: u32 = ctx.eval("new_id()").unwrap();
711 assert_eq!(id, 13);
712 })
713 }
714
715 #[test]
716 fn call_rust_fn_with_ctx_and_value() {
717 test_with(|ctx| {
718 let func = Func::from(|ctx, val| {
719 struct Args<'js>(Ctx<'js>, Value<'js>);
720 let Args(ctx, val) = Args(ctx, val);
721 ctx.globals().set("test_str", val).unwrap();
722 });
723 ctx.globals().set("test_fn", func).unwrap();
724 ctx.eval::<(), _>(
725 r#"
726 test_fn("test_str")
727 "#,
728 )
729 .unwrap();
730 let val: StdString = ctx.globals().get("test_str").unwrap();
731 assert_eq!(val, "test_str");
732 });
733 }
734
735 #[test]
736 fn call_rust_fn_with_this_and_args() {
737 let res: f64 = test_with(|ctx| {
738 let func = Function::new(ctx.clone(), |this: This<Object>, a: f64, b: f64| {
739 let x: f64 = this.get("x").unwrap();
740 let y: f64 = this.get("y").unwrap();
741 this.set("r", a * x + b * y).unwrap();
742 })
743 .unwrap();
744 ctx.globals().set("test_fn", func).unwrap();
745 ctx.eval(
746 r#"
747 let test_obj = { x: 1, y: 2 };
748 test_fn.call(test_obj, 3, 4);
749 test_obj.r
750 "#,
751 )
752 .unwrap()
753 });
754 assert_eq!(res, 11.0);
755 }
756
757 #[test]
758 fn apply_rust_fn_with_this_and_args() {
759 let res: f32 = test_with(|ctx| {
760 let func = Function::new(ctx.clone(), |this: This<Object>, x: f32, y: f32| {
761 let a: f32 = this.get("a").unwrap();
762 let b: f32 = this.get("b").unwrap();
763 a * x + b * y
764 })
765 .unwrap();
766 ctx.globals().set("test_fn", func).unwrap();
767 ctx.eval(
768 r#"
769 let test_obj = { a: 1, b: 2 };
770 test_fn.apply(test_obj, [3, 4])
771 "#,
772 )
773 .unwrap()
774 });
775 assert_eq!(res, 11.0);
776 }
777
778 #[test]
779 fn bind_rust_fn_with_this_and_call_with_args() {
780 let res: f32 = test_with(|ctx| {
781 let func = Function::new(ctx.clone(), |this: This<Object>, x: f32, y: f32| {
782 let a: f32 = this.get("a").unwrap();
783 let b: f32 = this.get("b").unwrap();
784 a * x + b * y
785 })
786 .unwrap();
787 ctx.globals().set("test_fn", func).unwrap();
788 ctx.eval(
789 r#"
790 let test_obj = { a: 1, b: 2 };
791 test_fn.bind(test_obj)(3, 4)
792 "#,
793 )
794 .unwrap()
795 });
796 assert_eq!(res, 11.0);
797 }
798
799 #[test]
800 fn call_rust_fn_with_var_args() {
801 let res: Vec<i8> = test_with(|ctx| {
802 let func = Function::new(ctx.clone(), |args: Rest<i8>| {
803 use std::iter::once;
804 once(args.len() as i8)
805 .chain(args.iter().cloned())
806 .collect::<Vec<_>>()
807 })
808 .unwrap();
809 ctx.globals().set("test_fn", func).unwrap();
810 ctx.eval(
811 r#"
812 test_fn(1, 2, 3)
813 "#,
814 )
815 .unwrap()
816 });
817 assert_eq!(res.len(), 4);
818 assert_eq!(res[0], 3);
819 assert_eq!(res[1], 1);
820 assert_eq!(res[2], 2);
821 assert_eq!(res[3], 3);
822 }
823
824 #[test]
825 fn call_rust_fn_with_rest_args() {
826 let res: Vec<i8> = test_with(|ctx| {
827 let func = Function::new(ctx.clone(), |arg1: i8, arg2: i8, args: Rest<i8>| {
828 use std::iter::once;
829 once(arg1)
830 .chain(once(arg2))
831 .chain(once(args.len() as i8))
832 .chain(args.iter().cloned())
833 .collect::<Vec<_>>()
834 })
835 .unwrap();
836 ctx.globals().set("test_fn", func).unwrap();
837 ctx.eval(
838 r#"
839 test_fn(-2, -1, 1, 2)
840 "#,
841 )
842 .unwrap()
843 });
844 assert_eq!(res.len(), 5);
845 assert_eq!(res[0], -2);
846 assert_eq!(res[1], -1);
847 assert_eq!(res[2], 2);
848 assert_eq!(res[3], 1);
849 assert_eq!(res[4], 2);
850 }
851
852 #[test]
853 fn js_fn_wrappers() {
854 test_with(|ctx| {
855 let global = ctx.globals();
856 global
857 .set(
858 "cat",
859 Func::from(|a: StdString, b: StdString| format!("{a}{b}")),
860 )
861 .unwrap();
862 let res: StdString = ctx.eval("cat(\"foo\", \"bar\")").unwrap();
863 assert_eq!(res, "foobar");
864
865 let mut log = Vec::<StdString>::new();
866 global
867 .set(
868 "log",
869 Func::from(MutFn::from(move |msg: StdString| {
870 log.push(msg);
871 log.len() as u32
872 })),
873 )
874 .unwrap();
875 let n: u32 = ctx.eval("log(\"foo\") + log(\"bar\")").unwrap();
876 assert_eq!(n, 3);
877 });
878 }
879
880 #[test]
881 fn constructor_new_prototype_no_leak() {
882 use crate::function::Constructor;
883
884 test_with(|ctx| {
892 fn make<'js>(ctx: Ctx<'js>) -> Result<Object<'js>> {
893 Object::new(ctx)
894 }
895 let proto = Object::new(ctx.clone()).unwrap();
896 let ctor = Constructor::new_prototype(&ctx, proto, make).unwrap();
897 ctx.globals().set("Foo", ctor).unwrap();
898
899 let is_instance: bool = ctx.eval("var f = new Foo(); f instanceof Foo").unwrap();
902 assert!(is_instance);
903 });
904 }
905}