-
Notifications
You must be signed in to change notification settings - Fork 46
/
register.R
232 lines (182 loc) · 6.9 KB
/
register.R
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
#' Generates wrappers for registered C++ functions
#'
#' Functions decorated with `[[cpp11::register]]` in files ending in `.cc`,
#' `.cpp`, `.h` or `.hpp` will be wrapped in generated code and registered to
#' be called from R.
#'
#' In order to use `cpp_register()` the `cli`, `decor`, `desc`, `glue`,
#' `tibble` and `vctrs` packages must also be installed.
#' @param path The path to the package root directory
#' @return The paths to the generated R and C++ source files (in that order).
#' @export
cpp_register <- function(path = ".") {
stop_unless_installed(c("brio", "cli", "decor", "desc", "glue", "tibble", "vctrs"))
r_path <- file.path(path, "R", "cpp11.R")
cpp_path <- file.path(path, "src", "cpp11.cpp")
unlink(c(r_path, cpp_path))
suppressWarnings(
all_decorations <- decor::cpp_decorations(path, is_attribute = TRUE)
)
if (nrow(all_decorations) == 0) {
return(invisible(character()))
}
funs <- get_registered_functions(all_decorations, "cpp11::register")
package <- desc::desc_get("Package", file = file.path(path, "DESCRIPTION"))
cpp_functions_definitions <- generate_cpp_functions(funs, package)
init <- generate_init_functions(get_registered_functions(all_decorations, "cpp11::init"))
r_functions <- generate_r_functions(funs, package)
dir.create(dirname(r_path), recursive = TRUE, showWarnings = FALSE)
brio::write_lines(path = r_path, glue::glue('
# Generated by cpp11: do not edit by hand
{r_functions}
'
))
cli::cli_alert_success("generated file {.file {basename(r_path)}}")
call_entries <- get_call_entries(path)
cpp_function_registration <- glue::glue_data(funs, ' {{
"_cpp11_{name}", (DL_FUNC) &_{package}_{name}, {n_args}}}, ',
n_args = viapply(funs$args, nrow)
)
cpp_function_registration <- glue::glue_collapse(cpp_function_registration, sep = "\n")
extra_includes <- character()
if (pkg_links_to_rcpp(path)) {
extra_includes <- c(extra_includes, "#include <cpp11/R.hpp>", "#include <Rcpp.h>", "using namespace Rcpp;")
}
pkg_types <- file.path(path, "src", paste0(package, "_types.h"))
if (file.exists(pkg_types)) {
extra_includes <- c(
sprintf('#include "%s"', basename(pkg_types)),
extra_includes
)
}
extra_includes <- paste0(extra_includes, collapse = "\n")
brio::write_lines(path = cpp_path, glue::glue('
// Generated by cpp11: do not edit by hand
{extra_includes}
#include "cpp11/declarations.hpp"
{cpp_functions_definitions}
extern "C" {{
{call_entries}
}}
{init$declarations}
extern "C" void R_init_{package}(DllInfo* dll){{
R_registerRoutines(dll, NULL, CallEntries, NULL, NULL);
R_useDynamicSymbols(dll, FALSE);{init$calls}
}}
',
call_entries = glue::glue_collapse(call_entries, "\n")
))
cli::cli_alert_success("generated file {.file {basename(cpp_path)}}")
invisible(c(r_path, cpp_path))
}
utils::globalVariables(c("name", "return_type", "line", "decoration", "context", ".", "functions", "res"))
get_registered_functions <- function(decorations, tag) {
if (NROW(decorations) == 0) {
return(tibble::tibble(file = character(), line = integer(), decoration = character(), params = list(), context = list(), name = character(), return_type = character(), args = list()))
}
out <- decorations[decorations$decoration == tag, ]
out$functions <- lapply(out$context, decor::parse_cpp_function, is_attribute = TRUE)
out <- vctrs::vec_cbind(out, vctrs::vec_rbind(!!!out$functions))
out <- out[!(names(out) %in% "functions")]
out$decoration <- sub("::[[:alpha:]]+", "", out$decoration)
cli::cli_alert_info(glue::glue("{n} functions decorated with [[{tag}]]", n = nrow(out)))
out
}
generate_cpp_functions <- function(funs, package = "cpp11") {
funs <- funs[c("name", "return_type", "args", "file", "line", "decoration")]
funs$real_params <- vcapply(funs$args, glue_collapse_data, "{type} {name}")
funs$sexp_params <- vcapply(funs$args, glue_collapse_data, "SEXP {name}")
funs$calls <- mapply(wrap_call, funs$name, funs$return_type, funs$args, SIMPLIFY = TRUE)
funs$package <- package
out <- glue::glue_data(funs,
'
// {basename(file)}
{return_type} {name}({real_params});
extern "C" SEXP _{package}_{name}({sexp_params}) {{
BEGIN_CPP11
{calls}
END_CPP11
}}
'
)
out <- glue::glue_collapse(out, sep = "\n")
unclass(out)
}
generate_init_functions <- function(funs) {
if (nrow(funs) == 0) {
return(list(declarations = "", calls = ""))
}
funs <- funs[c("name", "return_type", "args", "file", "line", "decoration")]
funs$declaration_params <- vcapply(funs$args, glue_collapse_data, "{type} {name}")
funs$call_params <- vcapply(funs$args, `[[`, "name")
declarations <- glue::glue_data(funs,
'
{return_type} {name}({declaration_params});
'
)
declarations <- paste0("\n", glue::glue_collapse(declarations, "\n"), "\n")
calls <- glue::glue_data(funs,
'
{name}({call_params});
'
)
calls <- paste0("\n", glue::glue_collapse(calls, "\n"));
list(
declarations = declarations,
calls = calls
)
}
generate_r_functions <- function(funs, package = "cpp11", use_package = FALSE) {
if (use_package) {
package_call <- glue::glue(', PACKAGE = "{package}"')
} else {
package_call <- ""
}
funs <- funs[c("name", "return_type", "args")]
funs$package <- package
funs$package_call <- package_call
funs$list_params <- vcapply(funs$args, glue_collapse_data, "{name}")
funs$params <- vcapply(funs$list_params, function(x) if (nzchar(x)) paste0(", ", x) else x)
is_void <- funs$return_type == "void"
funs$calls <- ifelse(is_void,
glue::glue_data(funs, 'invisible(.Call("_{package}_{name}"{params}{package_call}))'),
glue::glue_data(funs, '.Call("_{package}_{name}"{params}{package_call})')
)
out <- glue::glue_data(funs, '
{name} <- function({list_params}) {{
{calls}
}}
')
out <- glue::glue_collapse(out, sep = "\n\n")
unclass(out)
}
wrap_call <- function(name, return_type, args) {
call <- glue::glue('{name}({list_params})', list_params = glue_collapse_data(args, "cpp11::unmove(cpp11::as_cpp<{type}>({name}))"))
if (return_type == "void") {
unclass(glue::glue(" {call};\n return R_NilValue;", .trim = FALSE))
} else {
unclass(glue::glue(" return cpp11::as_sexp({call});"))
}
}
get_call_entries <- function(path) {
con <- textConnection("res", open = "w")
try(
tools::package_native_routine_registration_skeleton(path,
con,
character_only = FALSE,
include_declarations = TRUE
),
silent = TRUE
)
close(con)
start <- grep("/* .Call calls */", res, fixed = TRUE)
end <- grep("};", res, fixed = TRUE)
if (length(start) == 0) {
return("")
}
res[seq(start, end)]
}
pkg_links_to_rcpp <- function(path) {
deps <- desc::desc_get_deps(file.path(path, "DESCRIPTION"))
any(deps$type == "LinkingTo" & deps$package == "Rcpp")
}