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
extern crate proc_macro;
use proc_macro::TokenStream;
use quote::{format_ident, quote};
use syn::{ItemFn, ItemImpl};

use crate::wrappers::{self, ExtendrOptions};

/// Make inherent implementations available to R
///
/// The extendr_impl function is used to make inherent implementations
/// avaialble to R as an environment. By adding the [`extendr`] attribute
/// macro to an `impl` block (supported with `enum`s and `struct`s), the
/// methods in the impl block are made available as functions in an
/// environment.
///
/// On the R side, an environment with the same name of the inherent
/// implementation is created. The environment has functions within it
/// that correspond to each method in the impl block. Note that in order
/// for an impl block to be compatible with extendr (and thus R), its return
/// type must be able to be returned to R. For example, any struct that might
/// be returned must _also_ have an `#[extendr]` annotated impl block.
///
/// Example:
/// ```ignore
/// use extendr_api::prelude::*;
///
/// // a struct that will be used internal the People struct
/// #[derive(Clone, Debug, IntoDataFrameRow)]
/// struct Person {
///     name: String,
///     age: i32,
/// }
///
/// // This will collect people in the struct
/// #[extendr]
/// #[derive(Clone, Debug)]
/// struct People(Vec<Person>);
///
/// #[extendr]
/// /// @export
/// impl People {
///
///     // instantiate a new struct with an empty vector
///     fn new() -> Self {
///         let vec: Vec<Person> = Vec::new();
///         Self(vec)
///     }
///
///     // add a person to the internal vector
///     fn add_person(&mut self, name: &str, age: i32) -> &mut Self {
///         let person = Person {
///             name: String::from(name),
///             age: age,
///         };
///
///         self.0.push(person);
///
///         // return self
///         self
///     }
///     
///     // Convert the struct into a data.frame
///     fn into_df(&self) -> Robj {
///         let df = self.0.clone().into_dataframe();
///
///         match df {
///             Ok(df) => df.as_robj().clone(),
///             Err(_) => data_frame!(),
///         }
///     }
///
///     // add another `People` struct to self
///     fn add_people(&mut self, others: &People) -> &mut Self {
///         self.0.extend(others.0.clone().into_iter());
///         self
///     }
///
///     // create a function to print the self which can be called
///     // from an R print method
///     fn print_self(&self) -> String {
///         format!("{:?}", self.0)
///     }
///
/// }
///
/// // Macro to generate exports.
/// // This ensures exported functions are registered with R.
/// // See corresponding C code in `entrypoint.c`.
/// extendr_module! {
///     mod testself;
///     impl People;
/// }
/// ```
///     
/// **Known limitation**: if you return `&Self` or `&mut Self` or a reference
/// to the same type, the resultant R object will _always_ be the original
/// self. For example the below method **will not** return `other`.
///
/// ```ignore
///  // This is not possible today
/// #[extendr]
/// impl People {
///   fn return_other(&self, other: &'static T) -> &Self {
///     other
///   }
/// }
/// ```
pub fn extendr_impl(mut item_impl: ItemImpl, opts: &ExtendrOptions) -> syn::Result<TokenStream> {
    // Only `impl name { }` allowed
    if item_impl.defaultness.is_some() {
        return Err(syn::Error::new_spanned(
            item_impl,
            "default not allowed in #[extendr] impl",
        ));
    }

    if item_impl.unsafety.is_some() {
        return Err(syn::Error::new_spanned(
            item_impl,
            "unsafe not allowed in #[extendr] impl",
        ));
    }

    if item_impl.generics.const_params().count() != 0 {
        return Err(syn::Error::new_spanned(
            item_impl,
            "const params not allowed in #[extendr] impl",
        ));
    }

    if item_impl.generics.type_params().count() != 0 {
        return Err(syn::Error::new_spanned(
            item_impl,
            "type params not allowed in #[extendr] impl",
        ));
    }

    // if item_impl.generics.lifetimes().count() != 0 {
    //     return quote! { compile_error!("lifetime params not allowed in #[extendr] impl"); }.into();
    // }

    if item_impl.generics.where_clause.is_some() {
        return Err(syn::Error::new_spanned(
            item_impl,
            "where clause not allowed in #[extendr] impl",
        ));
    }

    let self_ty = item_impl.self_ty.as_ref();
    let self_ty_name = wrappers::type_name(self_ty);
    let prefix = format!("{}__", self_ty_name);
    let mut method_meta_names = Vec::new();
    let doc_string = wrappers::get_doc_string(&item_impl.attrs);

    // Generate wrappers for methods.
    // eg.
    // ```
    // #[no_mangle]
    // #[allow(non_snake_case)]
    // pub extern "C" fn wrap__Person__new() -> extendr_api::SEXP {
    //     unsafe {
    //         use extendr_api::FromRobj;
    //         extendr_api::Robj::from(<Person>::new()).get()
    //     }
    // }
    // ```
    let mut wrappers: Vec<ItemFn> = Vec::new();
    for impl_item in &mut item_impl.items {
        if let syn::ImplItem::Fn(ref mut method) = impl_item {
            method_meta_names.push(format_ident!(
                "{}{}__{}",
                wrappers::META_PREFIX,
                self_ty_name,
                method.sig.ident
            ));
            wrappers::make_function_wrappers(
                opts,
                &mut wrappers,
                prefix.as_str(),
                &method.attrs,
                &mut method.sig,
                Some(self_ty),
            )?;
        }
    }

    let meta_name = format_ident!("{}{}", wrappers::META_PREFIX, self_ty_name);
    let finalizer_name = format_ident!("__finalize__{}", self_ty_name);

    let conversion_impls = if opts.use_try_from {
        quote! {
            // Output conversion function for this type.

            impl TryFrom<Robj> for &#self_ty {
                type Error = Error;

                fn try_from(robj: Robj) -> Result<Self> {
                    Self::try_from(&robj)
                }
            }

            impl TryFrom<Robj> for &mut #self_ty {
                type Error = Error;

                fn try_from(mut robj: Robj) -> Result<Self> {
                    Self::try_from(&mut robj)
                }
            }

            // Output conversion function for this type.
            impl TryFrom<&Robj> for &#self_ty {
                type Error = Error;
                fn try_from(robj: &Robj) -> Result<Self> {
                    use libR_sys::R_ExternalPtrAddr;
                    unsafe {
                        let ptr = R_ExternalPtrAddr(robj.get()).cast::<#self_ty>();
                        ptr.as_ref().ok_or_else(|| Error::ExpectedExternalNonNullPtr(robj.clone()))
                    }
                }
            }

            // Input conversion function for a mutable reference to this type.
            impl TryFrom<&mut Robj> for &mut #self_ty {
                type Error = Error;
                fn try_from(robj: &mut Robj) -> Result<Self> {
                    use libR_sys::R_ExternalPtrAddr;
                    unsafe {
                        let ptr = R_ExternalPtrAddr(robj.get_mut()).cast::<#self_ty>();
                        ptr.as_mut().ok_or_else(|| Error::ExpectedExternalNonNullPtr(robj.clone()))
                    }
                }
            }
        }
    } else {
        quote! {
            // Input conversion function for this type.
            impl<'a> extendr_api::FromRobj<'a> for &#self_ty {
                fn from_robj(robj: &'a Robj) -> std::result::Result<Self, &'static str> {
                    if robj.check_external_ptr_type::<#self_ty>() {
                        #[allow(clippy::transmute_ptr_to_ref)]
                        Ok(unsafe { std::mem::transmute(robj.external_ptr_addr::<#self_ty>()) })
                    } else {
                        Err(concat!("expected ", #self_ty_name))
                    }
                }
            }

            // Input conversion function for a reference to this type.
            impl<'a> extendr_api::FromRobj<'a> for &mut #self_ty {
                fn from_robj(robj: &'a Robj) -> std::result::Result<Self, &'static str> {
                    if robj.check_external_ptr_type::<#self_ty>() {
                        #[allow(clippy::transmute_ptr_to_ref)]
                        Ok(unsafe { std::mem::transmute(robj.external_ptr_addr::<#self_ty>()) })
                    } else {
                        Err(concat!("expected ", #self_ty_name))
                    }
                }
            }

            // Output conversion function for this type.
                impl<'a> From<&'a #self_ty> for Robj {
                fn from(value: &'a #self_ty) -> Self {
                    unsafe {
                        let ptr = Box::into_raw(Box::new(value));
                        let mut res = Robj::make_external_ptr(ptr, Robj::from(()));
                        res.set_attrib(class_symbol(), #self_ty_name).unwrap();
                        res.register_c_finalizer(Some(#finalizer_name));
                        res
                    }
                }
            }
        }
    };

    let expanded = TokenStream::from(quote! {
        // The impl itself copied from the source.
        #item_impl

        // Function wrappers
        #( #wrappers )*

        #conversion_impls

        // Output conversion function for this type.
        impl From<#self_ty> for Robj {
            fn from(value: #self_ty) -> Self {
                unsafe {
                    let ptr = Box::into_raw(Box::new(value));
                    let mut res = Robj::make_external_ptr(ptr, Robj::from(()));
                    res.set_attrib(class_symbol(), #self_ty_name).unwrap();
                    res.register_c_finalizer(Some(#finalizer_name));
                    res
                }
            }
        }

        // Function to free memory for this type.
        extern "C" fn #finalizer_name (sexp: extendr_api::SEXP) {
            unsafe {
                let robj = extendr_api::robj::Robj::from_sexp(sexp);
                if robj.check_external_ptr_type::<#self_ty>() {
                    //eprintln!("finalize {}", #self_ty_name);
                    let ptr = robj.external_ptr_addr::<#self_ty>();
                    drop(Box::from_raw(ptr));
                }
            }
        }

        #[allow(non_snake_case)]
        fn #meta_name(impls: &mut Vec<extendr_api::metadata::Impl>) {
            let mut methods = Vec::new();
            #( #method_meta_names(&mut methods); )*
            impls.push(extendr_api::metadata::Impl {
                doc: #doc_string,
                name: #self_ty_name,
                methods,
            });
        }
    });

    //eprintln!("{}", expanded);
    Ok(expanded)
}

// This structure contains parameters parsed from the #[extendr_module] definition.