Debian Codegraph @

R/with_.R

raw
1 #' @include local_.R
2 NULL
3
4 #' Create a new "with" or "local" function
5 #'
6 #' These are constructors for `with_...` or `local_...` functions.
7 #' They are only needed if you want to alter some global state which is not
8 #' covered by the existing `with_...` functions, see \link{withr}
9 #' for an overview.
10 #'
11 #' The `with_...` functions reset the state immediately after the
12 #' `code` argument has been evaluated. The `local_...` functions
13 #' reset their arguments after they go out of scope, usually at the end of the
14 #' function body.
15 #'
16 #' @inheritParams rlang::args_dots_empty
17 #'
18 #' @param set `[function(...)]`\cr Function used to set the state.
19 #' The return value from this function should be the old state, which will
20 #' then be passed back into the `reset()` function to clean up the state.
21 #' The function can have arbitrarily many arguments, they will be replicated
22 #' in the formals of the returned function.
23 #' @param reset `[function(x)]`\cr Function used to reset the state.
24 #' The first argument can be named arbitrarily, further arguments with default
25 #' values, or a "dots" argument, are supported but not used: The function will
26 #' be called as `reset(old)`.
27 #' @param get `[function(...)]`\cr Optionally, a getter function. If
28 #' supplied, the `on.exit()` restoration is set up _before_ calling
29 #' `set`. This is more robust in edge cases.
30 #'
31 #' For technical reasons, this getter function must have the same
32 #' interface as `set`, which means it is passed the new values as
33 #' well. These can be safely ignored.
34 #' @param envir `[environment]`\cr Environment of the returned function.
35 #' @param new `[logical(1)]`\cr Replace the first argument of the `set` function
36 #' by `new`? Set to `FALSE` if the `set` function only has optional arguments.
37 #' @return `[function(new, code, ...)]` A function with at least two arguments,
38 #' \itemize{
39 #' \item `new`: New state to use
40 #' \item `code`: Code to run in that state.
41 #' }
42 #' If there are more arguments to the function passed in `set` they are
43 #' added to the returned function. If `set` does not have arguments,
44 #' or `new` is `FALSE`, the returned function does not have a `code` argument.
45 #' @keywords internal
46 #' @examples
47 #' with_(setwd)
48 #'
49 #' global_stack <- list()
50 #' set_global_state <- function(state, msg = "Changing global state.") {
51 #' global_stack <- c(list(state), global_stack)
52 #' message(msg)
53 #' state
54 #' }
55 #' reset_global_state <- function(state) {
56 #' old_state <- global_stack[[1]]
57 #' global_stack <- global_stack[-1]
58 #' stopifnot(identical(state, old_state))
59 #' }
60 #' with_(set_global_state, reset_global_state)
61 #' @export
62 with_ <- function(
63 set,
64 reset = set,
65 get = NULL,
66 ...,
67 envir = parent.frame(),
68 new = TRUE
69 ) {
70 if (!missing(...)) {
71 stop("`...` must be empty.")
72 }
73
74 fmls <- formals(set)
75
76 if (length(fmls) > 0L) {
77 # Called pass all extra formals on
78 called_fmls <- setNames(lapply(names(fmls), as.symbol), names(fmls))
79
80 # Special case for dots. If `set()` and/or `get()` take dots, it
81 # is assumed they implement `options()`-like semantic: a list
82 # passed as first argument is automatically spliced in the dots.
83 names(called_fmls)[names(called_fmls) == "..."] <- ""
84
85 if (new) {
86 # rename first formal to new
87 called_fmls[[1]] <- as.symbol("new")
88
89 fun_args <- c(alist(new = , code = ), fmls[-1L])
90 } else {
91 fun_args <- c(alist(code = ), fmls)
92 }
93 } else {
94 # no formals -- only have code
95 called_fmls <- NULL
96
97 fun_args <- alist(code = )
98 }
99
100 set_call <- as.call(c(substitute(set), called_fmls))
101 reset <- if (missing(reset)) substitute(set) else substitute(reset)
102
103 if (is.null(get)) {
104 fun <- eval(bquote(function(args) {
105 old <- .(set_call)
106 on.exit(.(reset)(old))
107 force(code)
108 }))
109 } else {
110 get_call <- as.call(c(substitute(get), called_fmls))
111 fun <- eval(bquote(function(args) {
112 old <- .(get_call)
113 on.exit(.(reset)(old))
114 .(set_call)
115 force(code)
116 }))
117 }
118
119 # substitute does not work on arguments, so we need to fix them manually
120 formals(fun) <- fun_args
121 environment(fun) <- envir
122
123 fun
124 }
125
126 merge_new <- function(old, new, action, merge_fun = c) {
127 action <- match.arg(action, c("replace", "prefix", "suffix"))
128
129 if (action == "suffix") {
130 new <- merge_fun(old, new)
131 } else if (action == "prefix") {
132 new <- merge_fun(new, old)
133 }
134 new
135 }
136
137 is.named <- function(x) {
138 !is.null(names(x)) && all(names(x) != "")
139 }