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
//! Module metadata
//!
//! This data is returned by get_module_metadata()
//! which is generated by [extendr_module!].
use crate::robj::IntoRobj;
use crate::*;
use std::io::Write;

/// Metadata function argument.
#[derive(Debug, PartialEq)]
pub struct Arg {
    pub name: &'static str,
    pub arg_type: &'static str,
    pub default: Option<&'static str>,
}

/// Metadata function.
#[derive(Debug, PartialEq)]
pub struct Func {
    pub doc: &'static str,
    pub rust_name: &'static str,
    pub mod_name: &'static str,
    pub r_name: &'static str,
    pub args: Vec<Arg>,
    pub return_type: &'static str,
    pub func_ptr: *const u8,
    pub hidden: bool,
}

/// Metadata Impl.
#[derive(Debug, PartialEq)]
pub struct Impl {
    pub doc: &'static str,
    pub name: &'static str,
    pub methods: Vec<Func>,
}

/// Module metadata.
#[derive(Debug, PartialEq)]
pub struct Metadata {
    pub name: &'static str,
    pub functions: Vec<Func>,
    pub impls: Vec<Impl>,
}

struct RArg {
    name: String,
    default: Option<&'static str>,
}

impl RArg {
    fn is_self(&self) -> bool {
        self.name == "self"
    }

    fn to_actual_arg(&self) -> String {
        self.name.clone()
    }

    fn to_formal_arg(&self) -> String {
        match self.default {
            Some(default_val) => format!("{} = {}", self.name, default_val),
            None => self.name.clone(),
        }
    }
}

impl From<&Arg> for RArg {
    fn from(arg: &Arg) -> Self {
        Self {
            name: sanitize_identifier(arg.name),
            default: arg.default,
        }
    }
}

impl From<Arg> for Robj {
    fn from(val: Arg) -> Self {
        List::from_values(&[r!(val.name), r!(val.arg_type)])
            .into_robj()
            .set_names(&["name", "arg_type"])
            .expect("From<Arg> failed")
    }
}

impl From<Func> for Robj {
    fn from(val: Func) -> Self {
        List::from_values(&[
            r!(val.doc),
            r!(val.rust_name),
            r!(val.mod_name),
            r!(val.r_name),
            r!(List::from_values(val.args)),
            r!(val.return_type),
            r!(val.hidden),
        ])
        .into_robj()
        .set_names(&[
            "doc",
            "rust_name",
            "mod_name",
            "r_name",
            "args",
            "return.type",
            "hidden",
        ])
        .expect("From<Func> failed")
    }
}

impl From<Impl> for Robj {
    fn from(val: Impl) -> Self {
        List::from_values(&[
            r!(val.doc),
            r!(val.name),
            r!(List::from_values(val.methods)),
        ])
        .into_robj()
        .set_names(&["doc", "name", "methods"])
        .expect("From<Impl> failed")
    }
}

impl From<Metadata> for Robj {
    fn from(val: Metadata) -> Self {
        List::from_values(&[
            r!(val.name),
            r!(List::from_values(val.functions)),
            r!(List::from_values(val.impls)),
        ])
        .into_robj()
        .set_names(&["name", "functions", "impls"])
        .expect("From<Metadata> failed")
    }
}

fn write_doc(w: &mut Vec<u8>, doc: &str) -> std::io::Result<()> {
    if !doc.is_empty() {
        write!(w, "#'")?;
        for c in doc.chars() {
            if c == '\n' {
                write!(w, "\n#'")?;
            } else {
                write!(w, "{}", c)?;
            }
        }
        writeln!(w)?;
    }
    Ok(())
}

/// Wraps invalid R identifiers, like `_function_name`, into backticks.
/// Removes raw identifiers (`r#`).
fn sanitize_identifier(name: &str) -> String {
    if name.starts_with('_') {
        format!("`{}`", name)
    } else if name.starts_with("r#") {
        name.strip_prefix("r#").unwrap().into()
    } else {
        name.to_string()
    }
}

fn join_str(input: impl Iterator<Item = String>, sep: &str) -> String {
    input.collect::<Vec<String>>().join(sep)
}

/// Generate a wrapper for a non-method function.
fn write_function_wrapper(
    w: &mut Vec<u8>,
    func: &Func,
    package_name: &str,
    use_symbols: bool,
) -> std::io::Result<()> {
    if func.hidden {
        return Ok(());
    }

    write_doc(w, func.doc)?;

    let r_args: Vec<RArg> = func.args.iter().map(Into::into).collect();
    let actual_args = r_args.iter().map(|a| a.to_actual_arg());
    let formal_args = r_args.iter().map(|a| a.to_formal_arg());

    if func.return_type == "()" {
        write!(
            w,
            "{} <- function({}) invisible(.Call(",
            sanitize_identifier(func.r_name),
            join_str(formal_args, ", ")
        )?;
    } else {
        write!(
            w,
            "{} <- function({}) .Call(",
            sanitize_identifier(func.r_name),
            join_str(formal_args, ", ")
        )?;
    }

    if use_symbols {
        write!(w, "wrap__{}", func.mod_name)?;
    } else {
        write!(w, "\"wrap__{}\"", func.mod_name)?;
    }

    if !func.args.is_empty() {
        write!(w, ", {}", join_str(actual_args, ", "))?;
    }

    if !use_symbols {
        write!(w, ", PACKAGE = \"{}\"", package_name)?;
    }

    if func.return_type == "()" {
        writeln!(w, "))\n")?;
    } else {
        writeln!(w, ")\n")?;
    }

    Ok(())
}

/// Generate a wrapper for a method.
fn write_method_wrapper(
    w: &mut Vec<u8>,
    func: &Func,
    package_name: &str,
    use_symbols: bool,
    class_name: &str,
) -> std::io::Result<()> {
    if func.hidden {
        return Ok(());
    }

    let r_args: Vec<RArg> = func.args.iter().map(Into::into).collect();
    let actual_args = r_args.iter().map(|a| a.to_actual_arg());

    // Skip a leading "self" argument.
    // This is supplied by the environment.
    let formal_args = r_args
        .iter()
        .skip_while(|a| a.is_self())
        .map(|a| a.to_formal_arg());

    // Both `class_name` and `func.name` should be processed
    // because they are exposed to R
    if func.return_type == "()" {
        write!(
            w,
            "{}${} <- function({}) invisible(.Call(",
            sanitize_identifier(class_name),
            sanitize_identifier(func.r_name),
            join_str(formal_args, ", ")
        )?;
    } else {
        write!(
            w,
            "{}${} <- function({}) .Call(",
            sanitize_identifier(class_name),
            sanitize_identifier(func.r_name),
            join_str(formal_args, ", ")
        )?;
    }

    // Here no processing is needed because of `wrap__` prefix
    if use_symbols {
        write!(w, "wrap__{}__{}", class_name, func.mod_name)?;
    } else {
        write!(w, "\"wrap__{}__{}\"", class_name, func.mod_name)?;
    }

    if actual_args.len() != 0 {
        write!(w, ", {}", join_str(actual_args, ", "))?;
    }

    if !use_symbols {
        write!(w, ", PACKAGE = \"{}\"", package_name)?;
    }

    if func.return_type == "()" {
        writeln!(w, "))\n")?;
    } else {
        writeln!(w, ")\n")?;
    }

    Ok(())
}

/// Generate a wrapper for an implementation block.
fn write_impl_wrapper(
    w: &mut Vec<u8>,
    imp: &Impl,
    package_name: &str,
    use_symbols: bool,
) -> std::io::Result<()> {
    let exported = imp.doc.contains("@export");

    write_doc(w, imp.doc)?;

    let imp_name_fixed = sanitize_identifier(imp.name);

    // Using fixed name because it is exposed to R
    writeln!(w, "{} <- new.env(parent = emptyenv())\n", imp_name_fixed)?;

    for func in &imp.methods {
        // write_doc(& mut w, func.doc)?;
        // `imp.name` is passed as is and sanitized within the function
        write_method_wrapper(w, func, package_name, use_symbols, imp.name)?;
    }

    if exported {
        writeln!(w, "#' @rdname {}", imp.name)?;
        writeln!(w, "#' @usage NULL")?;
    }

    // This is needed no matter whether the user added `@export` or
    // not; even if we don't export the class itself and its
    // initializers, we always export the `$` method so the method is
    // correctly added to the NAMESPACE.
    writeln!(w, "#' @export")?;

    // LHS with dollar operator is wrapped in ``, so pass name as is,
    // but in the body `imp_name_fixed` is called as valid R function,
    // so we pass preprocessed value
    writeln!(w, "`$.{}` <- function (self, name) {{ func <- {}[[name]]; environment(func) <- environment(); func }}\n", imp.name, imp_name_fixed)?;

    writeln!(w, "#' @export")?;
    writeln!(w, "`[[.{}` <- `$.{}`\n", imp.name, imp.name)?;

    Ok(())
}

impl Metadata {
    pub fn make_r_wrappers(
        &self,
        use_symbols: bool,
        package_name: &str,
    ) -> std::io::Result<String> {
        let mut w = Vec::new();

        writeln!(
            w,
            r#"# Generated by extendr: Do not edit by hand
#
# This file was created with the following call:
#   .Call("wrap__make_{}_wrappers", use_symbols = {}, package_name = "{}")
"#,
            self.name,
            if use_symbols { "TRUE" } else { "FALSE" },
            package_name
        )?;

        if use_symbols {
            writeln!(w, "#' @usage NULL")?;
            writeln!(w, "#' @useDynLib {}, .registration = TRUE", package_name)?;
            writeln!(w, "NULL")?;
            writeln!(w)?;
        }

        for func in &self.functions {
            write_function_wrapper(&mut w, func, package_name, use_symbols)?;
        }

        for imp in &self.impls {
            write_impl_wrapper(&mut w, imp, package_name, use_symbols)?;
        }
        unsafe { Ok(String::from_utf8_unchecked(w)) }
    }
}