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
use std::ffi::CString;

use savvy_ffi::{
    R_NilValue, Rf_cons, Rf_eval, Rf_install, Rf_lcons, Rf_protect, Rf_unprotect, CDR, SETCAR,
    SETCDR, SET_TAG, SEXP,
};

use crate::{protect, unwind_protect, ListSexp};

use super::Sexp;

/// An external SEXP of a function.
pub struct FunctionSexp(pub SEXP);

/// A pairlist for function arguments
pub struct FunctionArgs {
    head: SEXP,
    tail: SEXP,
    token: SEXP,
    len: usize,
}

impl FunctionArgs {
    pub fn inner(&self) -> SEXP {
        self.head
    }

    pub fn len(&self) -> usize {
        self.len
    }

    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    #[allow(clippy::new_without_default)]
    pub fn new() -> Self {
        unsafe {
            let head = Rf_cons(R_NilValue, R_NilValue);
            let token = protect::insert_to_preserved_list(head);
            let tail = head;

            Self {
                head,
                tail,
                token,
                len: 0,
            }
        }
    }

    pub fn add<K, V, E>(&mut self, arg_name: K, arg_value: V) -> crate::error::Result<()>
    where
        K: AsRef<str>,
        V: TryInto<Sexp, Error = E>,
        E: Into<crate::error::Error>,
    {
        // Set the arg value
        let v: Sexp = match arg_value.try_into() {
            Ok(sexp) => sexp,
            Err(e) => return Err(e.into()),
        };
        unsafe {
            // As a pairlist is a linked list, a pairlist is not empty, but has
            // one element filled with NULL. If it's the first time, replace the
            // NULL with the value. If not, append the value to the tail.
            if self.len == 0 {
                SETCAR(self.tail, v.0);
            } else {
                SETCDR(self.tail, Rf_cons(v.0, R_NilValue));
                self.tail = CDR(self.tail);
            }
        }

        // Set the arg name
        let arg_name = arg_name.as_ref();
        if !arg_name.is_empty() {
            let arg_name_cstr = match CString::new(arg_name) {
                Ok(cstr) => cstr,
                Err(e) => return Err(crate::error::Error::new(&e.to_string())),
            };
            unsafe {
                SET_TAG(self.tail, Rf_install(arg_name_cstr.as_ptr()));
            }
        }

        self.len += 1;

        Ok(())
    }

    pub fn from_list<L: Into<ListSexp>>(list: L) -> crate::error::Result<Self> {
        let list: ListSexp = list.into();
        let mut args = Self::new();
        for (k, v) in list.iter() {
            args.add(k, v)?;
        }
        Ok(args)
    }
}

impl Drop for FunctionArgs {
    fn drop(&mut self) {
        protect::release_from_preserved_list(self.token);
    }
}

/// A result of a function call. Since the result does not yet belong to any
/// environemnt or object, so it needs protection and unprotection. This struct
/// is solely for handling the unprotection in `Drop`.
pub struct FunctionCallResult {
    inner: SEXP,
    token: SEXP,
}

impl FunctionCallResult {
    pub fn inner(&self) -> SEXP {
        self.inner
    }
}

impl Drop for FunctionCallResult {
    fn drop(&mut self) {
        protect::release_from_preserved_list(self.token);
    }
}

impl From<FunctionCallResult> for Sexp {
    fn from(value: FunctionCallResult) -> Self {
        Self(value.inner())
    }
}

impl From<FunctionCallResult> for crate::error::Result<Sexp> {
    fn from(value: FunctionCallResult) -> Self {
        Ok(<Sexp>::from(value))
    }
}

impl FunctionSexp {
    #[inline]
    pub fn inner(&self) -> savvy_ffi::SEXP {
        self.0
    }

    /// Execute an R function
    pub fn call(&self, args: FunctionArgs) -> crate::error::Result<FunctionCallResult> {
        unsafe {
            let call = if args.is_empty() {
                Rf_protect(Rf_lcons(self.inner(), R_NilValue))
            } else {
                Rf_protect(Rf_lcons(self.inner(), args.inner()))
            };

            // Note: here, probably the environment doesn't matter at all
            // because the first argument is the function, which preserves the
            // releated environments, itself.
            let res = unwind_protect(|| Rf_eval(call, savvy_ffi::R_GlobalEnv))?;
            let token = protect::insert_to_preserved_list(res);

            Rf_unprotect(1);

            Ok(FunctionCallResult { inner: res, token })
        }
    }
}

// conversions from/to FunctionSexp ***************

impl TryFrom<Sexp> for FunctionSexp {
    type Error = crate::error::Error;

    fn try_from(value: Sexp) -> crate::error::Result<Self> {
        value.assert_function()?;
        Ok(Self(value.0))
    }
}

impl From<FunctionSexp> for Sexp {
    fn from(value: FunctionSexp) -> Self {
        Self(value.inner())
    }
}

impl From<FunctionSexp> for crate::error::Result<Sexp> {
    fn from(value: FunctionSexp) -> Self {
        Ok(<Sexp>::from(value))
    }
}