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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
//! Call Julia functions.
//!
//! This module provides the [`Call`], [`CallAsync`] and [`ProvideKeywords`] traits. Their methods
//! can be used to call Julia functions, including inner and outer constructors, schedule and
//! await tasks, and provide keyword argumentes respectively
//!
//! The methods provided by `Call` and `CallAsync` call the implementor as a Julia function with
//! some number of positional arguments. These methods have two variants, either the returned data
//! is rooted or it isn't. It's fine to leave the return value unrooted if you never use it or if
//! you can guarantee that it's reachable from some GC root while you do. Keyword arguments can be
//! provided by calling [`ProvideKeywords::provide_keywords`].

use crate::{
    error::{JlrsResult, JuliaResult, JuliaResultRef},
    memory::{global::Global, scope::PartialScope},
    private::Private,
    wrappers::ptr::{
        private::WrapperPriv as _,
        value::ValueRef,
        value::{Value, MAX_SIZE},
    },
};
use jl_sys::{jl_call, jl_exception_occurred, jl_get_kwsorter};
use smallvec::SmallVec;
use std::ptr::NonNull;

/// A function and its keyword arguments.
pub struct WithKeywords<'scope, 'data> {
    func: Value<'scope, 'data>,
    keywords: Value<'scope, 'data>,
}

impl<'scope, 'data> WithKeywords<'scope, 'data> {
    pub(crate) fn new(func: Value<'scope, 'data>, keywords: Value<'scope, 'data>) -> Self {
        WithKeywords { func, keywords }
    }

    /// Returns the function.
    pub fn function(&self) -> Value<'scope, 'data> {
        self.func
    }

    /// Returns the keywords.
    pub fn keywords(&self) -> Value<'scope, 'data> {
        self.keywords
    }
}

/// Call the implementor as a Julia function.
///
/// There are currently four types that implement this trait: [`Value`], [`Function`],
/// [`WithKeywords`], and [`OpaqueClosure`] if the `internal-types` feature is enabled. Because
/// `Value` implements this trait it's not necessary to cast it before calling it.
///
/// Constructors can be called with the methods defined by this trait, both the inner and outer
/// constructors of a `DataType` can be called by converting the `DataType` to a `Value` and
/// calling it.
///
/// Note that all of these methods are unsafe. There are several reasons for this. First and
/// foremost these methods let you call arbitrary Julia functions which can't be checked for
/// correctness. If the second lifetime of an argument is not `'static`, it must never be assigned
/// to a global. More information can be found in the [`safety`] module.
///
/// [`Function`]: crate::wrappers::ptr::function::Function
/// [`OpaqueClosure`]: crate::wrappers::ptr::internal::opaque_closure::OpaqueClosure
/// [`safety`]: crate::safety
pub trait Call<'data>: private::CallPriv {
    /// Call a function with no arguments and root the result in `scope`.
    ///
    /// Safety: this method lets you call arbitrary Julia functions which can't be checked for
    /// correctness. More information can be found in the [`safety`] module.
    ///
    /// [`safety`]: crate::safety
    unsafe fn call0<'target, S>(self, scope: S) -> JlrsResult<JuliaResult<'target, 'data>>
    where
        S: PartialScope<'target>;

    /// Call a function with one argument and root the result in `scope`.
    ///
    /// Safety: this method lets you call arbitrary Julia functions which can't be checked for
    /// correctness. More information can be found in the [`safety`] module.
    ///
    /// [`safety`]: crate::safety
    unsafe fn call1<'target, S>(
        self,
        scope: S,
        arg0: Value<'_, 'data>,
    ) -> JlrsResult<JuliaResult<'target, 'data>>
    where
        S: PartialScope<'target>;

    /// Call a function with two arguments and root the result in `scope`.
    ///
    /// Safety: this method lets you call arbitrary Julia functions which can't be checked for
    /// correctness. More information can be found in the [`safety`] module.
    ///
    /// [`safety`]: crate::safety
    unsafe fn call2<'target, S>(
        self,
        scope: S,
        arg0: Value<'_, 'data>,
        arg1: Value<'_, 'data>,
    ) -> JlrsResult<JuliaResult<'target, 'data>>
    where
        S: PartialScope<'target>;

    /// Call a function with three arguments and root the result in `scope`.
    ///
    /// Safety: this method lets you call arbitrary Julia functions which can't be checked for
    /// correctness. More information can be found in the [`safety`] module.
    ///
    /// [`safety`]: crate::safety
    unsafe fn call3<'target, S>(
        self,
        scope: S,
        arg0: Value<'_, 'data>,
        arg1: Value<'_, 'data>,
        arg2: Value<'_, 'data>,
    ) -> JlrsResult<JuliaResult<'target, 'data>>
    where
        S: PartialScope<'target>;

    /// Call a function with an arbitrary number arguments and root the result in `scope`.
    ///
    /// Safety: this method lets you call arbitrary Julia functions which can't be checked for
    /// correctness. More information can be found in the [`safety`] module.
    ///
    /// [`safety`]: crate::safety
    unsafe fn call<'target, 'value, V, S>(
        self,
        scope: S,
        args: V,
    ) -> JlrsResult<JuliaResult<'target, 'data>>
    where
        V: AsRef<[Value<'value, 'data>]>,
        S: PartialScope<'target>;

    /// Call a function with no arguments without rooting the result.
    ///
    /// Safety: this method lets you call arbitrary Julia functions which can't be checked for
    /// correctness. More information can be found in the [`safety`] module.
    ///
    /// [`safety`]: crate::safety
    unsafe fn call0_unrooted<'target>(self, _: Global<'target>) -> JuliaResultRef<'target, 'data>;

    /// Call a function with one argument without rooting the result.
    ///
    /// Safety: this method lets you call arbitrary Julia functions which can't be checked for
    /// correctness. More information can be found in the [`safety`] module.
    ///
    /// [`safety`]: crate::safety
    unsafe fn call1_unrooted<'target>(
        self,
        _: Global<'target>,
        arg0: Value<'_, 'data>,
    ) -> JuliaResultRef<'target, 'data>;

    /// Call a function with two arguments without rooting the result.
    ///
    /// Safety: this method lets you call arbitrary Julia functions which can't be checked for
    /// correctness. More information can be found in the [`safety`] module.
    ///
    /// [`safety`]: crate::safety
    unsafe fn call2_unrooted<'target>(
        self,
        _: Global<'target>,
        arg0: Value<'_, 'data>,
        arg1: Value<'_, 'data>,
    ) -> JuliaResultRef<'target, 'data>;

    /// Call a function with three arguments without rooting the result.
    ///
    /// Safety: this method lets you call arbitrary Julia functions which can't be checked for
    /// correctness. More information can be found in the [`safety`] module.
    ///
    /// [`safety`]: crate::safety
    unsafe fn call3_unrooted<'target>(
        self,
        _: Global<'target>,
        arg0: Value<'_, 'data>,
        arg1: Value<'_, 'data>,
        arg2: Value<'_, 'data>,
    ) -> JuliaResultRef<'target, 'data>;

    /// Call a function with an abitrary number of arguments without rooting the result.
    ///
    /// Safety: this method lets you call arbitrary Julia functions which can't be checked for
    /// correctness. More information can be found in the [`safety`] module.
    ///
    /// [`safety`]: crate::safety
    unsafe fn call_unrooted<'target, 'value, V>(
        self,
        _: Global<'target>,
        args: V,
    ) -> JuliaResultRef<'target, 'data>
    where
        V: AsRef<[Value<'value, 'data>]>;
}

/// Provide keyword arguments to a Julia function.
pub trait ProvideKeywords<'value, 'data>: Call<'data> {
    /// Provide keyword arguments to the function. The keyword arguments must be a `NamedTuple`.
    ///
    /// Example:
    ///
    /// ```
    /// # use jlrs::prelude::*;
    /// # use jlrs::util::JULIA;
    /// # fn main() {
    /// # JULIA.with(|j| {
    /// # let mut julia = j.borrow_mut();
    /// julia.scope(|global, mut frame| unsafe {
    ///     // The code we evaluate is a simple function definition, which is safe.
    ///     let func = unsafe {
    ///         Value::eval_string(&mut frame, "func(; a=3, b=4, c=5) = a + b + c")?
    ///         .into_jlrs_result()?
    ///     };
    ///
    ///     let a = Value::new(&mut frame, 1isize)?;
    ///     let b = Value::new(&mut frame, 2isize)?;
    ///     let nt = named_tuple!(&mut frame, "a" => a, "b" => b)?;
    ///
    ///     // Call the previously defined function. This function simply sums its three
    ///     // keyword arguments and has no side effects, so it's safe to call.
    ///     let res = unsafe {
    ///         func.provide_keywords(nt)?
    ///             .call0(&mut frame)?
    ///             .into_jlrs_result()?
    ///             .unbox::<isize>()?
    ///     };
    ///
    ///     assert_eq!(res, 8);
    ///
    ///     Ok(())
    /// })
    /// # .unwrap();
    /// # });
    /// # }
    fn provide_keywords(
        self,
        keywords: Value<'value, 'data>,
    ) -> JlrsResult<WithKeywords<'value, 'data>>;
}

impl<'data> Call<'data> for WithKeywords<'_, 'data> {
    unsafe fn call0<'target, S>(self, scope: S) -> JlrsResult<JuliaResult<'target, 'data>>
    where
        S: PartialScope<'target>,
    {
        let func = jl_get_kwsorter(self.func.datatype().unwrap(Private).cast());
        let args = &mut [self.keywords, self.func];
        let n = args.len();

        let res = jl_call(func, args.as_mut_ptr().cast(), n as _);
        let exc = jl_exception_occurred();

        if exc.is_null() {
            scope.call_result(Ok(NonNull::new_unchecked(res)), Private)
        } else {
            scope.call_result(Err(NonNull::new_unchecked(exc)), Private)
        }
    }

    unsafe fn call1<'target, S>(
        self,
        scope: S,
        arg0: Value<'_, 'data>,
    ) -> JlrsResult<JuliaResult<'target, 'data>>
    where
        S: PartialScope<'target>,
    {
        let func = jl_get_kwsorter(self.func.datatype().unwrap(Private).cast());
        let args = &mut [self.keywords, self.func, arg0];
        let n = args.len();

        let res = jl_call(func, args.as_mut_ptr().cast(), n as _);
        let exc = jl_exception_occurred();

        if exc.is_null() {
            scope.call_result(Ok(NonNull::new_unchecked(res)), Private)
        } else {
            scope.call_result(Err(NonNull::new_unchecked(exc)), Private)
        }
    }

    unsafe fn call2<'target, S>(
        self,
        scope: S,
        arg0: Value<'_, 'data>,
        arg1: Value<'_, 'data>,
    ) -> JlrsResult<JuliaResult<'target, 'data>>
    where
        S: PartialScope<'target>,
    {
        let func = jl_get_kwsorter(self.func.datatype().unwrap(Private).cast());
        let args = &mut [self.keywords, self.func, arg0, arg1];
        let n = args.len();

        let res = jl_call(func, args.as_mut_ptr().cast(), n as _);
        let exc = jl_exception_occurred();

        if exc.is_null() {
            scope.call_result(Ok(NonNull::new_unchecked(res)), Private)
        } else {
            scope.call_result(Err(NonNull::new_unchecked(exc)), Private)
        }
    }

    unsafe fn call3<'target, S>(
        self,
        scope: S,
        arg0: Value<'_, 'data>,
        arg1: Value<'_, 'data>,
        arg2: Value<'_, 'data>,
    ) -> JlrsResult<JuliaResult<'target, 'data>>
    where
        S: PartialScope<'target>,
    {
        let func = jl_get_kwsorter(self.func.datatype().unwrap(Private).cast());
        let args = &mut [self.keywords, self.func, arg0, arg1, arg2];
        let n = args.len();

        let res = jl_call(func, args.as_mut_ptr().cast(), n as _);
        let exc = jl_exception_occurred();

        if exc.is_null() {
            scope.call_result(Ok(NonNull::new_unchecked(res)), Private)
        } else {
            scope.call_result(Err(NonNull::new_unchecked(exc)), Private)
        }
    }

    unsafe fn call<'target, 'value, V, S>(
        self,
        scope: S,
        args: V,
    ) -> JlrsResult<JuliaResult<'target, 'data>>
    where
        V: AsRef<[Value<'value, 'data>]>,
        S: PartialScope<'target>,
    {
        let func = jl_get_kwsorter(self.func.datatype().unwrap(Private).cast());
        let args = args.as_ref();
        let mut vals: SmallVec<[Value; MAX_SIZE]> = SmallVec::with_capacity(2 + args.len());
        vals.push(self.keywords);
        vals.push(self.func);

        for arg in args.iter().copied() {
            vals.push(arg);
        }

        let n = vals.len();
        let res = jl_call(func, vals.as_mut_ptr().cast(), n as _);
        let exc = jl_exception_occurred();

        if exc.is_null() {
            scope.call_result(Ok(NonNull::new_unchecked(res)), Private)
        } else {
            scope.call_result(Err(NonNull::new_unchecked(exc)), Private)
        }
    }

    unsafe fn call0_unrooted<'target>(self, _: Global<'target>) -> JuliaResultRef<'target, 'data> {
        let func = jl_get_kwsorter(self.func.datatype().unwrap(Private).cast());
        let args = &mut [self.keywords, self.func];

        let res = jl_call(func, args.as_mut_ptr().cast(), 2);
        let exc = jl_exception_occurred();

        if exc.is_null() {
            Ok(ValueRef::wrap(res))
        } else {
            Err(ValueRef::wrap(exc))
        }
    }

    unsafe fn call1_unrooted<'target>(
        self,
        _: Global<'target>,
        arg0: Value<'_, 'data>,
    ) -> JuliaResultRef<'target, 'data> {
        let func = jl_get_kwsorter(self.func.datatype().unwrap(Private).cast());
        let args = &mut [self.keywords, self.func, arg0];

        let res = jl_call(func, args.as_mut_ptr().cast(), 3);
        let exc = jl_exception_occurred();

        if exc.is_null() {
            Ok(ValueRef::wrap(res))
        } else {
            Err(ValueRef::wrap(exc))
        }
    }

    unsafe fn call2_unrooted<'target>(
        self,
        _: Global<'target>,
        arg0: Value<'_, 'data>,
        arg1: Value<'_, 'data>,
    ) -> JuliaResultRef<'target, 'data> {
        let func = jl_get_kwsorter(self.func.datatype().unwrap(Private).cast());
        let args = &mut [self.keywords, self.func, arg0, arg1];

        let res = jl_call(func, args.as_mut_ptr().cast(), 4);
        let exc = jl_exception_occurred();

        if exc.is_null() {
            Ok(ValueRef::wrap(res))
        } else {
            Err(ValueRef::wrap(exc))
        }
    }

    unsafe fn call3_unrooted<'target>(
        self,
        _: Global<'target>,
        arg0: Value<'_, 'data>,
        arg1: Value<'_, 'data>,
        arg2: Value<'_, 'data>,
    ) -> JuliaResultRef<'target, 'data> {
        let func = jl_get_kwsorter(self.func.datatype().unwrap(Private).cast());
        let args = &mut [self.keywords, self.func, arg0, arg1, arg2];

        let res = jl_call(func, args.as_mut_ptr().cast(), 5);
        let exc = jl_exception_occurred();

        if exc.is_null() {
            Ok(ValueRef::wrap(res))
        } else {
            Err(ValueRef::wrap(exc))
        }
    }

    unsafe fn call_unrooted<'target, 'value, V>(
        self,
        _: Global<'target>,
        args: V,
    ) -> JuliaResultRef<'target, 'data>
    where
        V: AsRef<[Value<'value, 'data>]>,
    {
        let func = jl_get_kwsorter(self.func.datatype().unwrap(Private).cast());
        let args = args.as_ref();
        let mut vals: SmallVec<[Value; MAX_SIZE]> = SmallVec::with_capacity(2 + args.len());
        vals.push(self.keywords);
        vals.push(self.func);

        for arg in args.iter().copied() {
            vals.push(arg);
        }

        let n = vals.len();
        let res = jl_call(func, vals.as_mut_ptr().cast(), n as _);
        let exc = jl_exception_occurred();

        if exc.is_null() {
            Ok(ValueRef::wrap(res))
        } else {
            Err(ValueRef::wrap(exc))
        }
    }
}

cfg_if::cfg_if! {
    if #[cfg(feature = "async")] {
        use async_trait::async_trait;
        use crate::{memory::frame::AsyncGcFrame, wrappers::ptr::{Wrapper, task::Task, module::Module, function::Function}, async_util::{future::JuliaFuture, task::yield_task}};
        /// This trait provides async methods to create and schedule `Task`s that resolve when the
        /// `Task` has completed. Sync methods are also provided which only schedule the `Task`,
        /// those methods should only be used from [`PersistentTask::init`].
        ///
        /// [`PersistentTask::init`]: crate::async_util::task::PersistentTask::init
        #[async_trait(?Send)]
        pub trait CallAsync<'data>: Call<'data> {
            /// Call a function on another thread with the given arguments. This method uses
            /// `Base.Threads.@spawn` to call the given function on another thread but return immediately.
            /// While `await`ing the result the async runtime can work on other tasks, the current task
            /// resumes after the function call on the other thread completes.
            ///
            /// Safety: this method lets you call arbitrary Julia functions which can't be checked for
            /// correctness. More information can be found in the [`safety`] module.
            ///
            /// [`safety`]: crate::safety
            async unsafe fn call_async<'frame, 'value, V>(
                self,
                frame: &mut AsyncGcFrame<'frame>,
                args: V,
            ) -> JlrsResult<JuliaResult<'frame, 'data>>
            where
                V: AsRef<[Value<'value, 'data>]>;

            /// Does the same thing as [`CallAsync::call_async`], but the task is returned rather than an
            /// awaitable `Future`. This method should only be called in [`PersistentTask::init`],
            /// otherwise it's not guaranteed this task can make progress.
            ///
            /// Safety: this method lets you call arbitrary Julia functions which can't be checked for
            /// correctness. More information can be found in the [`safety`] module.
            ///
            /// [`safety`]: crate::safety
            /// [`PersistentTask::init`]: crate::async_util::task::PersistentTask::init
            unsafe fn schedule_async<'frame, 'value, V>(
                self,
                frame: &mut AsyncGcFrame<'frame>,
                args: V,
            ) -> JlrsResult<JuliaResult<Task<'frame>, 'frame, 'data>>
            where
                V: AsRef<[Value<'value, 'data>]>;

            /// Call a function with the given arguments in an `@async` block. Like `call_async`, the
            /// function is not called on the main thread, but on a separate thread that handles all
            /// tasks created by this method. This method should only be used with functions that do very
            /// little computational work but mostly spend their time waiting on IO.
            ///
            /// Safety: this method lets you call arbitrary Julia functions which can't be checked for
            /// correctness. More information can be found in the [`safety`] module.
            ///
            /// [`safety`]: crate::safety
            async unsafe fn call_async_local<'frame, 'value, V>(
                self,
                frame: &mut AsyncGcFrame<'frame>,
                args: V,
            ) -> JlrsResult<JuliaResult<'frame, 'data>>
            where
                V: AsRef<[Value<'value, 'data>]>;

            /// Does the same thing as [`CallAsync::call_async_local`], but the task is returned rather
            /// than an awaitable `Future`. This method should only be called in [`PersistentTask::init`],
            /// otherwise it's not guaranteed this task can make progress.
            ///
            /// Safety: this method lets you call arbitrary Julia functions which can't be checked for
            /// correctness. More information can be found in the [`safety`] module.
            ///
            /// [`safety`]: crate::safety
            /// [`PersistentTask::init`]: crate::async_util::task::PersistentTask::init
            unsafe fn schedule_async_local<'frame, 'value, V>(
                self,
                frame: &mut AsyncGcFrame<'frame>,
                args: V,
            ) -> JlrsResult<JuliaResult<Task<'frame>, 'frame, 'data>>
            where
                V: AsRef<[Value<'value, 'data>]>;

            /// Call a function with the given arguments in an `@async` block. The task is scheduled on
            /// the main thread. This method should only be used with functions that must run on the main
            /// thread. The runtime is blocked while this task is active.
            ///
            /// Safety: this method lets you call arbitrary Julia functions which can't be checked for
            /// correctness. More information can be found in the [`safety`] module.
            ///
            /// [`safety`]: crate::safety
            async unsafe fn call_async_main<'frame, 'value, V>(
                self,
                frame: &mut AsyncGcFrame<'frame>,
                args: V,
            ) -> JlrsResult<JuliaResult<'frame, 'data>>
            where
                V: AsRef<[Value<'value, 'data>]>;

            /// Does the same thing as [`CallAsync::call_async_main`], but the task is returned rather
            /// than an awaitable `Future`. This method should only be called in [`PersistentTask::init`],
            /// otherwise it's not guaranteed this task can make progress.
            ///
            /// Safety: this method lets you call arbitrary Julia functions which can't be checked for
            /// correctness. More information can be found in the [`safety`] module.
            ///
            /// [`safety`]: crate::safety
            /// [`PersistentTask::init`]: crate::async_util::task::PersistentTask::init
            unsafe fn schedule_async_main<'frame, 'value, V>(
                self,
                frame: &mut AsyncGcFrame<'frame>,
                args: V,
            ) -> JlrsResult<JuliaResult<Task<'frame>, 'frame, 'data>>
            where
                V: AsRef<[Value<'value, 'data>]>;
        }

        #[async_trait(?Send)]
        impl<'data> CallAsync<'data> for Value<'_, 'data> {
            async unsafe fn call_async<'frame, 'value, V>(
                self,
                frame: &mut AsyncGcFrame<'frame>,
                args: V,
            ) -> JlrsResult<JuliaResult<'frame, 'data>>
            where
                V: AsRef<[Value<'value, 'data>]>,
            {
                Ok(JuliaFuture::new(frame, self, args)?.await)
            }

            unsafe fn schedule_async<'frame, 'value, V>(
                self,
                frame: &mut AsyncGcFrame<'frame>,
                args: V,
            ) -> JlrsResult<JuliaResult<Task<'frame>, 'frame, 'data>>
            where
                V: AsRef<[Value<'value, 'data>]>,
            {
                let values = args.as_ref();
                let mut vals: SmallVec<[Value; MAX_SIZE]> = SmallVec::with_capacity(1 + values.len());

                vals.push(self);
                vals.extend_from_slice(values);

                let global = Global::new();
                let task = Module::main(global)
                    .submodule_ref("JlrsMultitask")?
                    .wrapper_unchecked()
                    .function_ref("asynccall")?
                    .wrapper_unchecked()
                    .call(&mut *frame, &mut vals)?;

                yield_task(frame);

                match task {
                    Ok(t) => Ok(Ok(t.cast_unchecked::<Task>())),
                    Err(e) => Ok(Err(e)),
                }
            }

            async unsafe fn call_async_local<'frame, 'value, V>(
                self,
                frame: &mut AsyncGcFrame<'frame>,
                args: V,
            ) -> JlrsResult<JuliaResult<'frame, 'data>>
            where
                V: AsRef<[Value<'value, 'data>]>,
            {
                Ok(JuliaFuture::new_local(frame, self, args)?.await)
            }

            unsafe fn schedule_async_local<'frame, 'value, V>(
                self,
                frame: &mut AsyncGcFrame<'frame>,
                args: V,
            ) -> JlrsResult<JuliaResult<Task<'frame>, 'frame, 'data>>
            where
                V: AsRef<[Value<'value, 'data>]>,
            {
                let values = args.as_ref();
                let mut vals: SmallVec<[Value; MAX_SIZE]> = SmallVec::with_capacity(1 + values.len());

                vals.push(self);
                vals.extend_from_slice(values);

                let global = Global::new();
                let task = Module::main(global)
                    .submodule_ref("JlrsMultitask")?
                    .wrapper_unchecked()
                    .function_ref("scheduleasynclocal")?
                    .wrapper_unchecked()
                    .call(&mut *frame, &mut vals)?;

                yield_task(frame);

                match task {
                    Ok(t) => Ok(Ok(t.cast_unchecked::<Task>())),
                    Err(e) => Ok(Err(e)),
                }
            }

            async unsafe fn call_async_main<'frame, 'value, V>(
                self,
                frame: &mut AsyncGcFrame<'frame>,
                args: V,
            ) -> JlrsResult<JuliaResult<'frame, 'data>>
            where
                V: AsRef<[Value<'value, 'data>]>,
            {
                Ok(JuliaFuture::new_main(frame, self, args)?.await)
            }

            unsafe fn schedule_async_main<'frame, 'value, V>(
                self,
                frame: &mut AsyncGcFrame<'frame>,
                args: V,
            ) -> JlrsResult<JuliaResult<Task<'frame>, 'frame, 'data>>
            where
                V: AsRef<[Value<'value, 'data>]>,
            {
                let values = args.as_ref();
                let mut vals: SmallVec<[Value; MAX_SIZE]> = SmallVec::with_capacity(1 + values.len());

                vals.push(self);
                vals.extend_from_slice(values);

                let global = Global::new();
                let task = Module::main(global)
                    .submodule_ref("JlrsMultitask")?
                    .wrapper_unchecked()
                    .function_ref("scheduleasync")?
                    .wrapper_unchecked()
                    .call(&mut *frame, &mut vals)?;

                yield_task(frame);

                match task {
                    Ok(t) => Ok(Ok(t.cast_unchecked::<Task>())),
                    Err(e) => Ok(Err(e)),
                }
            }
        }

        #[async_trait(?Send)]
        impl<'data> CallAsync<'data> for Function<'_, 'data> {
            async unsafe fn call_async<'frame, 'value, V>(
                self,
                frame: &mut AsyncGcFrame<'frame>,
                args: V,
            ) -> JlrsResult<JuliaResult<'frame, 'data>>
            where
                V: AsRef<[Value<'value, 'data>]>,
            {
                Ok(JuliaFuture::new(frame, self.as_value(), args)?.await)
            }

            unsafe fn schedule_async<'frame, 'value, V>(
                self,
                frame: &mut AsyncGcFrame<'frame>,
                args: V,
            ) -> JlrsResult<JuliaResult<Task<'frame>, 'frame, 'data>>
            where
                V: AsRef<[Value<'value, 'data>]>,
            {
                self.as_value().schedule_async(frame, args)
            }

            async unsafe fn call_async_local<'frame, 'value, V>(
                self,
                frame: &mut AsyncGcFrame<'frame>,
                args: V,
            ) -> JlrsResult<JuliaResult<'frame, 'data>>
            where
                V: AsRef<[Value<'value, 'data>]>,
            {
                Ok(JuliaFuture::new_local(frame, self.as_value(), args)?.await)
            }

            unsafe fn schedule_async_local<'frame, 'value, V>(
                self,
                frame: &mut AsyncGcFrame<'frame>,
                args: V,
            ) -> JlrsResult<JuliaResult<Task<'frame>, 'frame, 'data>>
            where
                V: AsRef<[Value<'value, 'data>]>,
            {
                self.as_value().schedule_async_local(frame, args)
            }

            async unsafe fn call_async_main<'frame, 'value, V>(
                self,
                frame: &mut AsyncGcFrame<'frame>,
                args: V,
            ) -> JlrsResult<JuliaResult<'frame, 'data>>
            where
                V: AsRef<[Value<'value, 'data>]>,
            {
                Ok(JuliaFuture::new_main(frame, self.as_value(), args)?.await)
            }

            unsafe fn schedule_async_main<'frame, 'value, V>(
                self,
                frame: &mut AsyncGcFrame<'frame>,
                args: V,
            ) -> JlrsResult<JuliaResult<Task<'frame>, 'frame, 'data>>
            where
                V: AsRef<[Value<'value, 'data>]>,
            {
                self.as_value().schedule_async_main(frame, args)
            }
        }

        #[async_trait(?Send)]
        impl<'data> CallAsync<'data> for WithKeywords<'_, 'data> {
            async unsafe fn call_async<'frame, 'value, V>(
                self,
                frame: &mut AsyncGcFrame<'frame>,
                args: V,
            ) -> JlrsResult<JuliaResult<'frame, 'data>>
            where
                V: AsRef<[Value<'value, 'data>]>,
            {
                Ok(JuliaFuture::new_with_keywords(frame, self, args)?.await)
            }

            unsafe fn schedule_async<'frame, 'value, V>(
                self,
                frame: &mut AsyncGcFrame<'frame>,
                args: V,
            ) -> JlrsResult<JuliaResult<Task<'frame>, 'frame, 'data>>
            where
                V: AsRef<[Value<'value, 'data>]>,
            {
                let values = args.as_ref();
                let mut vals: SmallVec<[Value; MAX_SIZE]> = SmallVec::with_capacity(1 + values.len());

                vals.push(self.function());
                vals.extend_from_slice(values);

                let global = Global::new();
                let task = Module::main(global)
                    .submodule_ref("JlrsMultitask")?
                    .wrapper_unchecked()
                    .function_ref("asynccall")?
                    .wrapper_unchecked()
                    .provide_keywords(self.keywords())?
                    .call(&mut *frame, &mut vals)?;

                yield_task(frame);

                match task {
                    Ok(t) => Ok(Ok(t.cast_unchecked::<Task>())),
                    Err(e) => Ok(Err(e)),
                }
            }

            async unsafe fn call_async_local<'frame, 'value, V>(
                self,
                frame: &mut AsyncGcFrame<'frame>,
                args: V,
            ) -> JlrsResult<JuliaResult<'frame, 'data>>
            where
                V: AsRef<[Value<'value, 'data>]>,
            {
                Ok(JuliaFuture::new_local_with_keywords(frame, self, args)?.await)
            }

            unsafe fn schedule_async_local<'frame, 'value, V>(
                self,
                frame: &mut AsyncGcFrame<'frame>,
                args: V,
            ) -> JlrsResult<JuliaResult<Task<'frame>, 'frame, 'data>>
            where
                V: AsRef<[Value<'value, 'data>]>,
            {
                let values = args.as_ref();
                let mut vals: SmallVec<[Value; MAX_SIZE]> = SmallVec::with_capacity(1 + values.len());

                vals.push(self.function());
                vals.extend_from_slice(values);

                let global = Global::new();
                let task = Module::main(global)
                    .submodule_ref("JlrsMultitask")?
                    .wrapper_unchecked()
                    .function_ref("scheduleasynclocal")?
                    .wrapper_unchecked()
                    .provide_keywords(self.keywords())?
                    .call(&mut *frame, &mut vals)?;

                yield_task(frame);

                match task {
                    Ok(t) => Ok(Ok(t.cast_unchecked::<Task>())),
                    Err(e) => Ok(Err(e)),
                }
            }

            async unsafe fn call_async_main<'frame, 'value, V>(
                self,
                frame: &mut AsyncGcFrame<'frame>,
                args: V,
            ) -> JlrsResult<JuliaResult<'frame, 'data>>
            where
                V: AsRef<[Value<'value, 'data>]>,
            {
                Ok(JuliaFuture::new_main_with_keywords(frame, self, args)?.await)
            }

            unsafe fn schedule_async_main<'frame, 'value, V>(
                self,
                frame: &mut AsyncGcFrame<'frame>,
                args: V,
            ) -> JlrsResult<JuliaResult<Task<'frame>, 'frame, 'data>>
            where
                V: AsRef<[Value<'value, 'data>]>,
            {
                let values = args.as_ref();
                let mut vals: SmallVec<[Value; MAX_SIZE]> = SmallVec::with_capacity(1 + values.len());

                vals.push(self.function());
                vals.extend_from_slice(values);

                let global = Global::new();
                let task = Module::main(global)
                    .submodule_ref("JlrsMultitask")?
                    .wrapper_unchecked()
                    .function_ref("scheduleasync")?
                    .wrapper_unchecked()
                    .provide_keywords(self.keywords())?
                    .call(&mut *frame, &mut vals)?;

                yield_task(frame);

                match task {
                    Ok(t) => Ok(Ok(t.cast_unchecked::<Task>())),
                    Err(e) => Ok(Err(e)),
                }
            }
        }
    }
}

mod private {
    use crate::wrappers::ptr::{function::Function, value::Value};

    #[cfg(all(
        any(not(feature = "lts"), feature = "all-features-override"),
        feature = "internal-types"
    ))]
    use crate::wrappers::ptr::internal::opaque_closure::OpaqueClosure;

    use super::WithKeywords;
    pub trait CallPriv {}
    impl CallPriv for WithKeywords<'_, '_> {}
    impl CallPriv for Function<'_, '_> {}
    #[cfg(all(
        any(not(feature = "lts"), feature = "all-features-override"),
        feature = "internal-types"
    ))]
    impl CallPriv for OpaqueClosure<'_> {}
    impl CallPriv for Value<'_, '_> {}
}