wolfram-library-link 0.6.0-alpha.3

Bindings to Wolfram LibraryLink
Documentation
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
923
924
925
926
927
928
929
930
931
//! Traits for working with data types that can be passed natively via LibraryLink
//! [`MArgument`]s.

use std::{
    cell::RefCell,
    ffi::{CStr, CString},
    os::raw::c_char,
};

use ref_cast::RefCast;

#[cfg(feature = "wstp")]
use crate::wstp::Link;
use crate::{
    expr::{expr, Expr, Symbol},
    rtl,
    sys::{self, mint, mreal, MArgument},
    DataStore, Image, NumericArray,
};

/// Trait implemented for types that can be passed via an [`MArgument`].
pub trait FromArg<'a> {
    #[allow(missing_docs)]
    unsafe fn from_arg(arg: &'a MArgument) -> Self;

    /// Return the *LibraryLink* parameter type as a Wolfram Language expression.
    ///
    /// ```
    /// use wolfram_library_link::{FromArg, NumericArray};
    ///
    /// assert_eq!(&bool::parameter_type().to_string(), "\"Boolean\"");
    /// assert_eq!(&i64::parameter_type().to_string(), "System`Integer");
    /// assert_eq!(
    ///     &<&NumericArray<i8>>::parameter_type().to_string(),
    ///     r#"System`List[System`LibraryDataType["NumericArray", "Integer8"], "Constant"]"#
    /// );
    /// ```
    ///
    /// See also [`IntoArg::return_type()`] and [`NativeFunction::signature()`].
    fn parameter_type() -> Expr;
}

/// Trait implemented for types that can be returned via an [`MArgument`].
///
/// The [`MArgument`] that this trait is used to modify must be the return value of a
/// LibraryLink function. It is not valid to modify [`MArgument`]s that contain
/// LibraryLink function arguments.
pub trait IntoArg {
    /// Move `self` into `arg`.
    ///
    /// # Safety
    ///
    /// `arg` must be an uninitialized [`MArgument`] that is used to store the return
    /// value of a LibraryLink function. The return type of that function must match
    /// the type of `self.`
    ///
    /// This function must only be called immediately before returning from a LibraryLink
    /// function. Each native LibraryLink function must perform at most one call to this
    /// method per invocation.
    //
    // Private implementation note:
    //   the "at most one call to this method per invocation" constraint is necessary to
    //   maintain the safety invariants of `impl IntoArg for CString`.
    unsafe fn into_arg(self, arg: MArgument);

    /// Return the *LibraryLink* return type as a Wolfram Language expression.
    ///
    /// See also [`FromArg::parameter_type()`] and [`NativeFunction::signature()`].
    fn return_type() -> Expr;
}

/// Trait implemented for any function whose parameters and return type are native
/// LibraryLink [`MArgument`] types.
///
/// [`#[export]`][crate::export] can only be used with functions that implement this trait.
///
/// A function implements this trait if all of its parameters implement [`FromArg`] and
/// its return type implements [`IntoArg`].
///
/// Functions that pass their arguments and return value using a [`wstp::Link`] do not
/// implement this trait. See [`WstpFunction`].
pub trait NativeFunction<'a> {
    /// Call the function using the raw LibraryLink [`MArgument`] fields.
    unsafe fn call(&self, args: &'a [MArgument], ret: MArgument);

    /// Get the type signature of this function, suitable for use in
    /// [`LibraryFunctionLoad`][ref/LibraryFunctionLoad]<code>[_, _, <i>parameters</i>, <i>ret</i>]</code>.
    ///
    /// [ref/LibraryFunctionLoad]: https://reference.wolfram.com/language/ref/LibraryFunctionLoad.html
    ///
    /// See also [`FromArg::parameter_type()`] and [`IntoArg::return_type()`].
    ///
    /// The function generated by [`generate_loader!`] uses this method to generate the
    /// type signature for functions exported by [`#[export]`][crate::export].
    // Note: This method takes `self` so that it is object safe.
    fn signature(&self) -> Result<(Vec<Expr>, Expr), String>;
}

/// Trait implemented for any function whose parameters and return type can be passed
/// over a WSTP [`Link`][crate::wstp::Link].
///
/// [`#[export(wstp)]`][crate::export#exportwstp] can only be used with functions that implement
/// this trait.
///
/// A function implements this trait if its type signature is one of:
///
/// * `fn(_: &mut Link)`
/// * `fn(_: Vec<Expr>) -> Expr`
/// * `fn(_: Vec<Expr>)`
#[cfg(feature = "wstp")]
pub trait WstpFunction {
    /// Call the function using the [`Link`] object passed by the Kernel.
    unsafe fn call(&self, link: &mut Link);
}

//======================================
// FromArg Impls
//======================================

impl FromArg<'_> for bool {
    unsafe fn from_arg(arg: &MArgument) -> Self {
        crate::bool_from_mbool(*arg.boolean)
    }

    fn parameter_type() -> Expr {
        Expr::string("Boolean")
    }
}

impl FromArg<'_> for mint {
    unsafe fn from_arg(arg: &MArgument) -> Self {
        *arg.integer
    }

    fn parameter_type() -> Expr {
        expr!(System::Integer)
    }
}

impl FromArg<'_> for mreal {
    unsafe fn from_arg(arg: &MArgument) -> Self {
        *arg.real
    }

    fn parameter_type() -> Expr {
        expr!(System::Real)
    }
}

impl FromArg<'_> for sys::mcomplex {
    unsafe fn from_arg(arg: &MArgument) -> Self {
        *arg.cmplex
    }

    fn parameter_type() -> Expr {
        expr!(System::Complex)
    }
}

//--------------------------------------
// Strings
//--------------------------------------

unsafe fn c_str_from_arg<'a>(arg: &'a MArgument) -> &'a CStr {
    let cstr: *mut c_char = *arg.utf8string;
    CStr::from_ptr(cstr)
}

impl<'a> FromArg<'a> for CString {
    unsafe fn from_arg(arg: &'a MArgument) -> CString {
        let owned = {
            let cstr: &'a CStr = c_str_from_arg(arg);
            CString::from(cstr)
        };

        // Now that we own our own copy of the string, disown the Kernel's copy.
        rtl::UTF8String_disown(*arg.utf8string);

        owned
    }

    fn parameter_type() -> Expr {
        expr!(System::String)
    }
}

/// # Panics
///
/// This conversion will panic if the [`MArgument::utf8string`] field is not valid UTF-8.
impl<'a> FromArg<'a> for String {
    unsafe fn from_arg(arg: &'a MArgument) -> String {
        let owned = {
            let cstr: &'a CStr = c_str_from_arg(arg);
            let str: &'a str = cstr
                .to_str()
                .expect("FromArg for &str: string was not valid UTF-8");
            str.to_owned()
        };

        // Now that we own our own copy of the string, disown the Kernel's copy.
        rtl::UTF8String_disown(*arg.utf8string);

        owned
    }

    fn parameter_type() -> Expr {
        expr!(System::String)
    }
}

// TODO: Supported borrowed &CStr and &str's using some kind of wrapper that ensures we
//       disown the Kernel string.

/// # Safety
///
/// The lifetime of the returned `&CStr` must be the same as the lifetime of `arg`.
///
/// # Warning
///
/// Using `&CStr` as the parameter type of a *LibraryLink* function will result in a
/// memory leak. Use [`String`] or [`CString`] instead.
impl<'a> FromArg<'a> for &'a CStr {
    unsafe fn from_arg(arg: &'a MArgument) -> &'a CStr {
        c_str_from_arg(arg)
    }

    fn parameter_type() -> Expr {
        // This type implements `FromArg` purely for usage in DataStoreNode::value()
        // (via `FromArg for &str`).
        panic!("&CStr cannot be used as a LibraryLink function parameter type")
    }
}

/// # Panics
///
/// This conversion will panic if the [`MArgument::utf8string`] field is not valid UTF-8.
///
/// # Safety
///
/// The lifetime of the returned `&str` must be the same as the lifetime of `arg`.
///
/// # Warning
///
/// Using `&str` as the parameter type of a *LibraryLink* function will result in a
/// memory leak. Use [`String`] or [`CString`] instead.
impl<'a> FromArg<'a> for &'a str {
    unsafe fn from_arg(arg: &'a MArgument) -> &'a str {
        let cstr: &'a CStr = FromArg::<'a>::from_arg(arg);
        cstr.to_str()
            .expect("FromArg for &str: string was not valid UTF-8")
    }

    fn parameter_type() -> Expr {
        // This type implements `FromArg` purely for usage in DataStoreNode::value().
        panic!("&str cannot be used as a LibraryLink function parameter type")
    }
}

//--------------------------------------
// NumericArray
//--------------------------------------

// TODO: Add FromArg for NumericArray which just clones the numeric array? Or disclaims
//       ownership in another way?

/// # Safety
///
/// `FromArg for NumericArray<T>` MUST be constrained by `T: NumericArrayType` to prevent
/// accidental creation of invalid `NumericArray` conversions. Without this constraint,
/// it would be possible to write code like:
///
/// ```compile_fail
/// # mod scope {
/// # use wolfram_library_link::{export, NumericArray};
/// #[export] // Unsafe!
/// fn and(bools: NumericArray<bool>) -> bool {
///     // ...
/// #   todo!()
/// }
/// # }
/// ```
///
/// which is not valid because `bool` is not a valid numeric array type.
impl<'a, T: crate::NumericArrayType> FromArg<'a> for &'a NumericArray<T> {
    unsafe fn from_arg(arg: &'a MArgument) -> &'a NumericArray<T> {
        NumericArray::ref_cast(&*arg.numeric)
    }

    fn parameter_type() -> Expr {
        // NOTE:
        //   We use "Constant" instead of Automatic as the default memory management
        //   strategy for &NumericArray<T> (and &Image<T> as well). This is because, for
        //   both Automatic and "Constant", the fact remains that on the Rust side we have
        //   an immutable reference to a NumericArray -- we're not going to free the array,
        //   and we're not going to mutate. Using Automatic would behave correctly, but
        //   would incur an unnecessary deep clone of the array contents as Automatic
        //   doesn't imply any explicit promise from the programmer that they will not
        //   mutate the array (unlike "Constant", which *is* an explicit promise that we
        //   won't mutate the array the Kernel passes in).

        // {LibraryDataType[NumericArray, "<T>"], "Constant"}
        let type_name = T::TYPE.name();
        let ldt = crate::expr::expr!(System::LibraryDataType["NumericArray", type_name]);
        crate::expr::expr!(System::List[ldt, "Constant"])
    }
}

impl<'a, T: crate::NumericArrayType> FromArg<'a> for NumericArray<T> {
    unsafe fn from_arg(arg: &'a MArgument) -> NumericArray<T> {
        NumericArray::from_raw(*arg.numeric)
    }

    fn parameter_type() -> Expr {
        // {LibraryDataType[NumericArray, "<T>"], "Shared"}
        let type_name = T::TYPE.name();
        let ldt = crate::expr::expr!(System::LibraryDataType["NumericArray", type_name]);
        crate::expr::expr!(System::List[ldt, "Shared"])
    }
}

impl<'a> FromArg<'a> for &'a NumericArray<()> {
    unsafe fn from_arg(arg: &'a MArgument) -> &'a NumericArray<()> {
        NumericArray::ref_cast(&*arg.numeric)
    }

    fn parameter_type() -> Expr {
        // {NumericArray, "Constant"}
        crate::expr::expr!(System::List["NumericArray", "Constant"])
    }
}

impl<'a> FromArg<'a> for NumericArray<()> {
    unsafe fn from_arg(arg: &'a MArgument) -> NumericArray<()> {
        NumericArray::from_raw(*arg.numeric)
    }

    fn parameter_type() -> Expr {
        // {NumericArray, "Shared"}
        crate::expr::expr!(System::List["NumericArray", "Shared"])
    }
}

//--------------------------------------
// Image
//--------------------------------------

impl<'a, T: crate::ImageData> FromArg<'a> for &'a Image<T> {
    unsafe fn from_arg(arg: &'a MArgument) -> &'a Image<T> {
        Image::ref_cast(&*arg.image)
    }

    fn parameter_type() -> Expr {
        // {LibraryDataType[Image | Image3D, "<T>"], "Constant"}
        let type_name = T::TYPE.name();
        let alts = crate::expr::expr!(System::Alternatives["Image", "Image3D"]);
        let ldt = crate::expr::expr!(System::LibraryDataType[alts, type_name]);
        crate::expr::expr!(System::List[ldt, "Constant"])
    }
}

impl<'a, T: crate::ImageData> FromArg<'a> for Image<T> {
    unsafe fn from_arg(arg: &'a MArgument) -> Image<T> {
        Image::from_raw(*arg.image)
    }

    fn parameter_type() -> Expr {
        // {LibraryDataType[Image | Image3D, "<T>"], "Shared"}
        let type_name = T::TYPE.name();
        let alts = crate::expr::expr!(System::Alternatives["Image", "Image3D"]);
        let ldt = crate::expr::expr!(System::LibraryDataType[alts, type_name]);
        crate::expr::expr!(System::List[ldt, "Shared"])
    }
}

impl<'a> FromArg<'a> for &'a Image<()> {
    unsafe fn from_arg(arg: &'a MArgument) -> &'a Image<()> {
        Image::ref_cast(&*arg.image)
    }

    fn parameter_type() -> Expr {
        // {Image | Image3D, "Constant"}
        let alts = crate::expr::expr!(System::Alternatives["Image", "Image3D"]);
        crate::expr::expr!(System::List[alts, "Constant"])
    }
}

impl<'a> FromArg<'a> for Image<()> {
    unsafe fn from_arg(arg: &'a MArgument) -> Image<()> {
        Image::from_raw(*arg.image)
    }

    fn parameter_type() -> Expr {
        // {Image | Image3D, "Shared"}
        let alts = crate::expr::expr!(System::Alternatives["Image", "Image3D"]);
        crate::expr::expr!(System::List[alts, "Shared"])
    }
}

//--------------------------------------
// DataStore
//--------------------------------------

impl FromArg<'_> for DataStore {
    unsafe fn from_arg(arg: &MArgument) -> DataStore {
        DataStore::from_raw(*arg.tensor as sys::DataStore)
    }

    fn parameter_type() -> Expr {
        Expr::string("DataStore")
    }
}

impl<'a> FromArg<'a> for &'a DataStore {
    unsafe fn from_arg(arg: &MArgument) -> &'a DataStore {
        DataStore::ref_cast(&*(arg.tensor as *mut sys::DataStore))
    }

    fn parameter_type() -> Expr {
        // This type implements `FromArg` purely for usage in DataStoreNode::value().
        panic!("&DataStore cannot be used as a LibraryLink function parameter type")
    }
}

//======================================
// impl IntoArg
//======================================

impl IntoArg for () {
    unsafe fn into_arg(self, _arg: MArgument) {
        // Do nothing.
    }

    fn return_type() -> Expr {
        Expr::string("Void")
    }
}

//---------------------
// Primitive data types
//---------------------

impl IntoArg for bool {
    unsafe fn into_arg(self, arg: MArgument) {
        let boole: u32 = if self { sys::True } else { sys::False };
        *arg.boolean = boole as sys::mbool;
    }

    fn return_type() -> Expr {
        Expr::string("Boolean")
    }
}

impl IntoArg for mint {
    unsafe fn into_arg(self, arg: MArgument) {
        *arg.integer = self;
    }

    fn return_type() -> Expr {
        expr!(System::Integer)
    }
}

impl IntoArg for mreal {
    unsafe fn into_arg(self, arg: MArgument) {
        *arg.real = self;
    }

    fn return_type() -> Expr {
        expr!(System::Real)
    }
}

impl IntoArg for sys::mcomplex {
    unsafe fn into_arg(self, arg: MArgument) {
        *arg.cmplex = self;
    }

    fn return_type() -> Expr {
        expr!(System::Complex)
    }
}

//--------------------------------------------------
// Convenience conversions for narrow integer sizes.
//--------------------------------------------------

impl IntoArg for i8 {
    unsafe fn into_arg(self, arg: MArgument) {
        *arg.integer = mint::from(self);
    }

    fn return_type() -> Expr {
        expr!(System::Integer)
    }
}

impl IntoArg for i16 {
    unsafe fn into_arg(self, arg: MArgument) {
        *arg.integer = mint::from(self);
    }

    fn return_type() -> Expr {
        expr!(System::Integer)
    }
}

impl IntoArg for i32 {
    unsafe fn into_arg(self, arg: MArgument) {
        *arg.integer = mint::from(self);
    }

    fn return_type() -> Expr {
        expr!(System::Integer)
    }
}

impl IntoArg for u8 {
    unsafe fn into_arg(self, arg: MArgument) {
        *arg.integer = mint::from(self);
    }

    fn return_type() -> Expr {
        expr!(System::Integer)
    }
}

impl IntoArg for u16 {
    unsafe fn into_arg(self, arg: MArgument) {
        *arg.integer = mint::from(self);
    }

    fn return_type() -> Expr {
        expr!(System::Integer)
    }
}

// If we're on a 32 bit platform, mint might be an alias for i32. Avoid providing this
// conversion on those platforms.
#[cfg(target_pointer_width = "64")]
impl IntoArg for u32 {
    unsafe fn into_arg(self, arg: MArgument) {
        *arg.integer = mint::from(self);
    }

    fn return_type() -> Expr {
        expr!(System::Integer)
    }
}

//--------------------
// Strings
//--------------------

thread_local! {
    /// See [`<CString as IntoArg>::into_arg()`] for information about how this static is
    /// used.
    static RETURNED_STRING: RefCell<Option<CString>> = RefCell::new(None);
}

impl IntoArg for CString {
    unsafe fn into_arg(self, arg: MArgument) {
        // Extend the lifetime of `self.as_ptr()` by storing `self` in `RETURNED_STRING`.
        //
        // This will keep `raw` valid past the point that the current LibraryLink
        // function returns, at which point it will be copied by the Kernel and is no
        // longer used. We'll drop `self` the next time this function is called.
        //
        // This implementation limits the maximum number of "leaked" strings to just one.
        //
        // For more information on management of string memory when passed via
        // LibraryLink, see:
        //
        // <https://reference.wolfram.com/language/LibraryLink/tutorial/InteractionWithWolframLanguage.html#262826222>
        let raw: *const c_char = RETURNED_STRING.with(|stored| {
            // Drop the previously returned string, if any.
            if let Some(prev) = stored.replace(None) {
                drop(prev);
            }

            let raw: *const c_char = self.as_ptr();

            *stored.borrow_mut() = Some(self);

            raw
        });

        // Return `raw` via this MArgument.
        *arg.utf8string = raw as *mut c_char;
    }

    fn return_type() -> Expr {
        expr!(System::String)
    }
}

impl IntoArg for String {
    /// # Panics
    ///
    /// This function will panic if `self` cannot be converted into a [`CString`].
    unsafe fn into_arg(self, arg: MArgument) {
        let cstring = CString::new(self)
            .expect("IntoArg for String: could not convert String to CString");

        <CString as IntoArg>::into_arg(cstring, arg)
    }

    fn return_type() -> Expr {
        expr!(System::String)
    }
}

//---------------------------------------
// NumericArray, Image, DataStore
//---------------------------------------

impl<T: crate::NumericArrayType> IntoArg for NumericArray<T> {
    unsafe fn into_arg(self, arg: MArgument) {
        *arg.numeric = self.into_raw();
    }

    fn return_type() -> Expr {
        // LibraryDataType[NumericArray, "<T>"]
        let type_name = T::TYPE.name();
        crate::expr::expr!(System::LibraryDataType["NumericArray", type_name])
    }
}

impl IntoArg for NumericArray<()> {
    unsafe fn into_arg(self, arg: MArgument) {
        *arg.numeric = self.into_raw();
    }

    fn return_type() -> Expr {
        // NumericArray
        crate::expr::expr!("NumericArray")
    }
}

impl<T: crate::ImageData> IntoArg for Image<T> {
    unsafe fn into_arg(self, arg: MArgument) {
        *arg.image = self.into_raw();
    }

    fn return_type() -> Expr {
        // LibraryDataType[Image | Image3D, "<T>"]
        let type_name = T::TYPE.name();
        let alts = crate::expr::expr!(System::Alternatives["Image", "Image3D"]);
        let ldt = crate::expr::expr!(System::LibraryDataType[alts, type_name]);
        crate::expr::expr!(System::List[ldt, "Shared"])
    }
}

impl IntoArg for DataStore {
    unsafe fn into_arg(self, arg: MArgument) {
        *arg.tensor = self.into_raw() as *mut _;
    }

    fn return_type() -> Expr {
        Expr::string("DataStore")
    }
}

//======================================
// impl NativeFunction
//======================================

/// Implement `NativeFunction` for functions that use raw [`MArgument`]s for their
/// arguments and return value.
///
/// # Example
///
/// ```
/// # mod scope {
/// use wolfram_library_link::{self as wll, sys::MArgument, FromArg};
///
/// #[wll::export]
/// fn raw_add2(args: &[MArgument], ret: MArgument) {
///     let x = unsafe { i64::from_arg(&args[0]) };
///     let y = unsafe { i64::from_arg(&args[1]) };
///
///     unsafe {
///         *ret.integer = x + y;
///     }
/// }
/// # }
/// ```
///
/// ```wolfram
/// LibraryFunctionLoad["...", "raw_add2", {Integer, Integer}, Integer]
/// ```
impl<'a: 'b, 'b> NativeFunction<'a> for fn(&'b [MArgument], MArgument) {
    unsafe fn call(&self, args: &'a [MArgument], ret: MArgument) {
        self(args, ret)
    }

    fn signature(&self) -> Result<(Vec<Expr>, Expr), String> {
        Err(
            "fn(&[MArgument], MArgument) function cannot be loaded automatically: \
            parameter and return types are unknown."
                .to_owned(),
        )
    }
}

//--------------------
// impl NativeFunction
//--------------------

macro_rules! impl_NativeFunction {
    ($($type:ident),*) => {
        impl<'a, $($type,)* R> NativeFunction<'a> for fn($($type),*) -> R
        where
            R: IntoArg,
            $($type: FromArg<'a>),*
        {
            unsafe fn call(&self, args: &'a [MArgument], ret: MArgument) {
                // Re-use the $type name as the local variable names. E.g.
                //     let A1 = A1::from_arg(..);
                // This works because types and variable names are different namespaces.
                #[allow(non_snake_case)]
                let [$($type,)*] = match args {
                    [$($type,)*] => [$($type,)*],
                    _ => panic!(
                        "LibraryLink function number of arguments ({}) does not match \
                        number of parameters",
                        args.len()
                    ),
                };

                $(
                    #[allow(non_snake_case)]
                    let $type: $type = $type::from_arg($type);
                )*

                let result: R = self($($type,)*);

                result.into_arg(ret);
            }

            fn signature(&self) -> Result<(Vec<Expr>, Expr), String> {
                let mut param_tys = Vec::new();

                $(
                    param_tys.push($type::parameter_type());
                )*

                Ok((param_tys, R::return_type()))
            }
        }
    }
}

// Handle the zero-arguments case specially.
impl<'a, R> NativeFunction<'a> for fn() -> R
where
    R: IntoArg,
{
    unsafe fn call(&self, args: &[MArgument], ret: MArgument) {
        if args.len() != 0 {
            panic!(
                "LibraryLink function number of arguments ({}) does not match number of \
                parameters",
                args.len()
            );
        }

        let result = self();

        result.into_arg(ret);
    }

    fn signature(&self) -> Result<(Vec<Expr>, Expr), String> {
        Ok((Vec::new(), R::return_type()))
    }
}

impl_NativeFunction!(A1);
impl_NativeFunction!(A1, A2);
impl_NativeFunction!(A1, A2, A3);
impl_NativeFunction!(A1, A2, A3, A4);
impl_NativeFunction!(A1, A2, A3, A4, A5);
impl_NativeFunction!(A1, A2, A3, A4, A5, A6);
impl_NativeFunction!(A1, A2, A3, A4, A5, A6, A7);
impl_NativeFunction!(A1, A2, A3, A4, A5, A6, A7, A8);
impl_NativeFunction!(A1, A2, A3, A4, A5, A6, A7, A8, A9);
impl_NativeFunction!(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10);
impl_NativeFunction!(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11);
impl_NativeFunction!(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12);

//======================================
// impl WstpFunction
//======================================

// Everything from this point on is WSTP-specific: trait impls + helper fns
// that read/write Expr values through a WSTP `Link`.
#[cfg(feature = "wstp")]
mod wstp_impls {
    use super::*;

    /// Implement [`WstpFunction`] for functions that use a [`Link`] for their arguments and
    /// return value.
    ///
    /// # Example
    ///
    /// ```
    /// # mod scope {
    /// use wolfram_library_link::{self as wll, wstp::Link};
    ///
    /// #[wll::export(wstp)]
    /// fn add2_link(link: &mut Link) {
    ///     let argc: usize = link.test_head("List").unwrap();
    ///
    ///     if argc != 2 {
    ///         panic!("expected 2 arguments, got {}", argc);
    ///     }
    ///
    ///     let x = link.get_i64().unwrap();
    ///     let y = link.get_i64().unwrap();
    ///
    ///     link.put_i64(x + y).unwrap();
    /// }
    /// # }
    /// ```
    ///
    /// ```wolfram
    /// LibraryFunctionLoad["...", "add2_link", LinkObject, LinkObject]
    /// ```
    impl WstpFunction for fn(&mut Link) {
        unsafe fn call(&self, link: &mut Link) {
            self(link)
        }
    }

    /// Implement [`WstpFunction`] for functions that use [`Expr`] for their arguments and
    /// return value.
    ///
    /// # Example
    ///
    /// ```
    /// # mod scope {
    /// use wolfram_library_link::{self as wll, wstp::Link, expr::{Expr, ExprKind}};
    ///
    /// #[wll::export(wstp)]
    /// fn add2(args: Vec<Expr>) -> Expr {
    ///     if args.len() != 2 {
    ///         panic!("expected 2 arguments, got {}", args.len());
    ///     }
    ///
    ///     let x: i64 = match *args[0].kind() {
    ///         ExprKind::Integer(value) => value,
    ///         _ => panic!("expected 1st argument to be Integer, got: {}", args[0])
    ///     };
    ///     let y: i64 = match *args[1].kind() {
    ///         ExprKind::Integer(value) => value,
    ///         _ => panic!("expected 2nd argument to be Integer, got: {}", args[1])
    ///     };
    ///
    ///     Expr::from(x + y)
    /// }
    /// # }
    /// ```
    ///
    /// ```wolfram
    /// LibraryFunctionLoad["...", "add2", LinkObject, LinkObject]
    /// ```
    impl WstpFunction for fn(Vec<Expr>) -> Expr {
        unsafe fn call(&self, link: &mut Link) {
            let args: Vec<Expr> = match get_args_list(link) {
                Ok(args) => args,
                Err(err) => return write_arg_failure(link, err),
            };

            let result: Expr = self(args);

            if let Err(err) = link.put_expr(&result) {
                write_arg_failure(link, err.into());
            }
        }
    }

    impl WstpFunction for fn(Vec<Expr>) {
        unsafe fn call(&self, link: &mut Link) {
            let args: Vec<Expr> = match get_args_list(link) {
                Ok(args) => args,
                Err(err) => return write_arg_failure(link, err),
            };

            let _null: () = self(args);

            if let Err(err) = link.put_symbol("System`Null") {
                write_arg_failure(link, err.into());
            }
        }
    }

    /// Write a structured `Failure[...]` to the link for an argument read /
    /// result write failure, instead of panicking into a generic RustPanic.
    fn write_arg_failure(link: &mut Link, err: crate::LibraryError) {
        let _ = crate::macro_utils::write_failure_to_link(link, &err);
    }

    //----------------------------
    // Utilities
    //----------------------------

    fn get_args_list(link: &mut Link) -> Result<Vec<Expr>, crate::LibraryError> {
        Ok(get_args_list_impl(link)?)
    }

    fn get_args_list_impl(link: &mut Link) -> Result<Vec<Expr>, wstp::Error> {
        let arg_count: usize = match link.test_head("List") {
            Ok(count) => Ok(count),
            Err(err) if err.code() == Some(wstp::sys::WSEGSEQ) => {
                link.clear_error();
                link.test_head("System`List")
            },
            Err(err) => Err(err),
        }?;

        let mut elements: Vec<Expr> = Vec::new();

        for _ in 0..arg_count {
            let elem = link.get_expr_with_resolver(&mut |name| {
                Symbol::try_new(&format!("System`{name}"))
            })?;
            elements.push(elem);
        }

        Ok(elements)
    }
} // end of #[cfg(feature = "wstp")] mod wstp_impls