Skip to content

Fix exposing functions under 2.33+ #847

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 17 additions & 2 deletions R/utils.R
Original file line number Diff line number Diff line change
Expand Up @@ -816,7 +816,20 @@ get_standalone_hpp <- function(stan_file, stancflags) {

get_function_name <- function(fun_start, fun_end, model_lines) {
fun_string <- paste(model_lines[(fun_start+1):fun_end], collapse = " ")
fun_name <- gsub("auto ", "", fun_string, fixed = TRUE)
types <- c(
"auto",
"int",
"double",
"Eigen::Matrix<(.*)>",
"std::vector<(.*)>"
)
pattern <- paste0(
# Only match if the type occurs at start of string
"^(\\s*)?(",
paste0(types, collapse="|"),
# Only match if type followed by a function name and opening bracket
")\\s*(?=\\w*\\()")
fun_name <- gsub(pattern, "", fun_string, perl = TRUE)
sub("\\(.*", "", fun_name, perl = TRUE)
}

Expand Down Expand Up @@ -864,7 +877,9 @@ get_plain_rtn <- function(fun_start, fun_end, model_lines) {
# that instantiates an RNG
prep_fun_cpp <- function(fun_start, fun_end, model_lines) {
fun_body <- paste(model_lines[fun_start:fun_end], collapse = " ")
fun_body <- gsub("auto", get_plain_rtn(fun_start, fun_end, model_lines), fun_body)
if (cmdstan_version() < "2.33") {
fun_body <- gsub("auto", get_plain_rtn(fun_start, fun_end, model_lines), fun_body)
}
fun_body <- gsub("// [[stan::function]]", "// [[Rcpp::export]]\n", fun_body, fixed = TRUE)
fun_body <- gsub("std::ostream\\*\\s*pstream__\\s*=\\s*nullptr", "", fun_body)
fun_body <- gsub("boost::ecuyer1988&\\s*base_rng__", "SEXP base_rng_ptr", fun_body)
Expand Down
3 changes: 2 additions & 1 deletion tests/testthat/test-model-expose-functions.R
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,8 @@ test_that("Exposing functions with precompiled model gives meaningful error", {
parameters { real x; }
model { x ~ std_normal(); }
")
mod1 <- cmdstan_model(stan_file, compile_standalone = TRUE)
mod1 <- cmdstan_model(stan_file, compile_standalone = TRUE,
force_recompile = TRUE)
expect_equal(7.5, mod1$functions$a_plus_b(5, 2.5))

mod2 <- cmdstan_model(stan_file)
Expand Down