diff --git a/R/model.R b/R/model.R index 47d027c8c..2a7b4623f 100644 --- a/R/model.R +++ b/R/model.R @@ -519,6 +519,7 @@ compile <- function(quiet = TRUE, private$precompile_cpp_options_ <- NULL private$precompile_stanc_options_ <- NULL private$precompile_include_paths_ <- NULL + self$functions$existing_exe <- TRUE self$exe_file(exe) return(invisible(self)) } else { @@ -586,6 +587,7 @@ compile <- function(quiet = TRUE, stancflags_standalone <- c("--standalone-functions", stancflags_val, stancflags_combined) self$functions$hpp_code <- get_standalone_hpp(temp_stan_file, stancflags_standalone) self$functions$external <- !is.null(user_header) + self$functions$existing_exe <- FALSE if (compile_standalone) { expose_stan_functions(self$functions, !quiet) } diff --git a/R/utils.R b/R/utils.R index bf65b513d..96c7739cf 100644 --- a/R/utils.R +++ b/R/utils.R @@ -914,6 +914,10 @@ expose_stan_functions <- function(function_env, global = FALSE, verbose = FALSE) "WSL CmdStan and will not be compiled", call. = FALSE) } + if (function_env$existing_exe) { + stop("Exporting standalone functions is not possible with a pre-compiled Stan model!", + call. = FALSE) + } if (function_env$external && cmdstan_version() < "2.32") { stop("Exporting standalone functions with external C++ is not available before CmdStan 2.32", call. = FALSE) diff --git a/tests/testthat/test-model-expose-functions.R b/tests/testthat/test-model-expose-functions.R index 39f01359b..9836d4065 100644 --- a/tests/testthat/test-model-expose-functions.R +++ b/tests/testthat/test-model-expose-functions.R @@ -175,3 +175,24 @@ test_that("Exposing external functions errors before v2.32", { reset_cmdstan_version() }) + +test_that("Exposing functions with precompiled model gives meaningful error", { + skip_if(os_is_wsl()) + + stan_file <- write_stan_file(" + functions { + real a_plus_b(real a, real b) { return a + b; } + } + parameters { real x; } + model { x ~ std_normal(); } + ") + mod1 <- cmdstan_model(stan_file, compile_standalone = TRUE) + expect_equal(7.5, mod1$functions$a_plus_b(5, 2.5)) + + mod2 <- cmdstan_model(stan_file) + expect_error( + mod2$expose_functions(), + "Exporting standalone functions is not possible with a pre-compiled Stan model!", + fixed = TRUE + ) +})