From 0cbc314e746420de0affe35afa2d8f8a96c0785d Mon Sep 17 00:00:00 2001 From: Sebastian Fischer Date: Tue, 31 Oct 2023 18:34:16 +0100 Subject: [PATCH] crate always compiles when input function was compiled --- R/crate.R | 12 +++++++++++- man/crate.Rd | 4 +++- tests/testthat/test_crate.R | 5 +++++ 3 files changed, 19 insertions(+), 2 deletions(-) diff --git a/R/crate.R b/R/crate.R index 9c950056..59a21186 100644 --- a/R/crate.R +++ b/R/crate.R @@ -11,6 +11,8 @@ #' Parent environment to look up names. Default to [topenv()]. #' @param .compile (`logical(1)`)\cr #' Whether to jit-compile the function. +#' In case the function is already compiled. +#' If the input function `.fn` is compiled, this has no effect, and the output function will always be compiled. #' #' @export #' @examples @@ -27,10 +29,18 @@ #' f = meta_f(1) #' f() crate = function(.fn, ..., .parent = topenv(), .compile = TRUE) { + assert_flag(.compile) nn = map_chr(substitute(list(...)), as.character)[-1L] environment(.fn) = list2env(setNames(list(...), nn), parent = .parent) - if (.compile) { + if (.compile || is_compiled(.fn)) { .fn = compiler::cmpfun(.fn) } return(.fn) } + +is_compiled = function(x) { + tryCatch({ + capture.output(compiler::disassemble(x)) + TRUE + }, error = function(e) FALSE) +} diff --git a/man/crate.Rd b/man/crate.Rd index d06c672e..a84039ff 100644 --- a/man/crate.Rd +++ b/man/crate.Rd @@ -17,7 +17,9 @@ The objects, which should be visible inside \code{.fn}.} Parent environment to look up names. Default to \code{\link[=topenv]{topenv()}}.} \item{.compile}{(\code{logical(1)})\cr -Whether to jit-compile the function.} +Whether to jit-compile the function. +In case the function is already compiled. +If the input function \code{.fn} is compiled, this has no effect, and the output function will always be compiled.} } \description{ Put a function in a "lean" environment that does not carry unnecessary baggage with it (e.g. references to datasets). diff --git a/tests/testthat/test_crate.R b/tests/testthat/test_crate.R index 4e692543..d0bbb90e 100644 --- a/tests/testthat/test_crate.R +++ b/tests/testthat/test_crate.R @@ -16,4 +16,9 @@ test_that("crate", { test_that("compilation works", { expect_error(compiler::disassemble(crate(function() NULL, .compile = FALSE)), regexp = "function is not compiled") expect_error(compiler::disassemble(crate(function() NULL, .compile = TRUE)), regexp = NA) + + f = function() NULL + fc = compiler::cmpfun(f) + + expect_true(is_compiled(fc)) })