Skip to content

Commit

Permalink
crate always compiles when input function was compiled
Browse files Browse the repository at this point in the history
  • Loading branch information
sebffischer committed Oct 31, 2023
1 parent 4d681bf commit 0cbc314
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 2 deletions.
12 changes: 11 additions & 1 deletion R/crate.R
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
}
4 changes: 3 additions & 1 deletion man/crate.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions tests/testthat/test_crate.R
Original file line number Diff line number Diff line change
Expand Up @@ -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))
})

0 comments on commit 0cbc314

Please sign in to comment.