Skip to content

Commit

Permalink
feat: add .compile argument to crate function
Browse files Browse the repository at this point in the history
  • Loading branch information
sebffischer authored Jan 17, 2024
2 parents 8344be9 + 691186c commit 74e1661
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 3 deletions.
2 changes: 2 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# mlr3misc 0.13.0-9000

* Added argument `.compile` to function `crate()` because R disables byte-code
compilation of functions when changing their enclosing environment
* Added the possibility to include prototype arguments when adding elements to a `Dictionary`
* Removed unused argument `required_args` from `Dictionary` class
* Disable leanification when `ROXYGEN_PKG` environment variable is set
Expand Down
20 changes: 18 additions & 2 deletions R/crate.R
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@
#' The objects, which should be visible inside `.fn`.
#' @param .parent (`environment`)\cr
#' 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 @@ -24,8 +28,20 @@
#' z = 300
#' f = meta_f(1)
#' f()
crate = function(.fn, ..., .parent = topenv()) {
crate = function(.fn, ..., .parent = topenv(), .compile = TRUE) {
assert_flag(.compile)
.compile = .compile || is_compiled(.fn)
nn = map_chr(substitute(list(...)), as.character)[-1L]
environment(.fn) = list2env(setNames(list(...), nn), parent = .parent)
.fn
if (.compile) {
.fn = compiler::cmpfun(.fn)
}
return(.fn)
}

is_compiled = function(x) {
tryCatch({
capture.output(compiler::disassemble(x))
TRUE
}, error = function(e) FALSE)
}
7 changes: 6 additions & 1 deletion man/crate.Rd

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

6 changes: 6 additions & 0 deletions tests/testthat/test_crate.R
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,9 @@ test_that("crate", {
f = meta_f(1)
expect_equal(f(), c(1, 200, 300))
})

test_that("compilation works", {
expect_false(is_compiled(crate(function() NULL, .compile = FALSE)))
expect_true(is_compiled(crate(function() NULL, .compile = TRUE)))
expect_true(is_compiled(crate(compiler::cmpfun(function() NULL), .compile = FALSE)))
})

0 comments on commit 74e1661

Please sign in to comment.