Debian Codegraph @

R/defer.R

raw
1 # Include standalone defer to overwrite it:
2 #' @include standalone-defer.R
3 NULL
4
5 #' Defer Evaluation of an Expression
6 #'
7 #' Similar to [on.exit()], but allows one to attach
8 #' an expression to be evaluated when exiting any frame currently
9 #' on the stack. This provides a nice mechanism for scoping side
10 #' effects for the duration of a function's execution.
11 #'
12 #' @param expr `[expression]`\cr An expression to be evaluated.
13 #' @param envir `[environment]`\cr Attach exit handlers to this environment.
14 #' Typically, this should be either the current environment or
15 #' a parent frame (accessed through [parent.frame()]).
16 #' @param priority `[character(1)]`\cr Specify whether this handler should
17 #' be executed `"first"` or `"last"`, relative to any other
18 #' registered handlers on this environment.
19 #'
20 #' @section Running handlers within `source()`:
21 #' withr handlers run within `source()` are run when `source()` exits
22 #' rather than line by line.
23 #'
24 #' This is only the case when the script is sourced in `globalenv()`.
25 #' For a local environment, the caller needs to set
26 #' `options(withr.hook_source = TRUE)`. This is to avoid paying the
27 #' penalty of detecting `source()` in the normal usage of `defer()`.
28 #'
29 #' @details
30 #' `defer()` works by attaching handlers to the requested environment (as an
31 #' attribute called `"handlers"`), and registering an exit handler that
32 #' executes the registered handler when the function associated with the
33 #' requested environment finishes execution.
34 #'
35 #' Deferred events can be set on the global environment, primarily to facilitate
36 #' the interactive development of code that is intended to be executed inside a
37 #' function or test. A message alerts the user to the fact that an explicit
38 #' `deferred_run()` is the only way to trigger these deferred events. Use
39 #' `deferred_clear()` to clear them without evaluation. The global environment
40 #' scenario is the main motivation for these functions.
41 #'
42 #' @family local-related functions
43 #' @export
44 #' @examples
45 #' # define a 'local' function that creates a file, and
46 #' # removes it when the parent function has finished executing
47 #' local_file <- function(path) {
48 #' file.create(path)
49 #' defer_parent(unlink(path))
50 #' }
51 #'
52 #' # create tempfile path
53 #' path <- tempfile()
54 #'
55 #' # use 'local_file' in a function
56 #' local({
57 #' local_file(path)
58 #' stopifnot(file.exists(path))
59 #' })
60 #'
61 #' # file is deleted as we leave 'local' local
62 #' stopifnot(!file.exists(path))
63 #'
64 #' # investigate how 'defer' modifies the
65 #' # executing function's environment
66 #' local({
67 #' local_file(path)
68 #' print(attributes(environment()))
69 #' })
70 #'
71 #' # Note that examples lack function scoping so deferred calls are
72 #' # generally executed immediately
73 #' defer(print("one"))
74 #' defer(print("two"))
75 defer <- function(expr, envir = parent.frame(), priority = c("first", "last")) {
76 if (identical(envir, globalenv())) {
77 source_frame <- source_exit_frame_option(envir)
78 if (!is.null(source_frame)) {
79 # Automatically enable `source()` special-casing for the global
80 # environment. This is the default for `source()` and the normal
81 # case when users run scripts. This also happens in R CMD check
82 # when withr is used inside an example because an R example is
83 # run inside `withAutoprint()` which uses `source()`.
84 local_options(withr.hook_source = TRUE)
85 # And fallthrough to the default `defer()` handling. Within
86 # `source()` we don't require manual calling of
87 # `deferred_run()`.
88 } else if (is_top_level_global_env(envir)) {
89 global_defer(expr, priority = priority)
90 return(invisible(NULL))
91 }
92 }
93
94 priority <- match.arg(priority, choices = c("first", "last"))
95
96 if (knitr_in_progress() && identical(envir, knitr::knit_global())) {
97 return(defer_knitr(expr, envir, priority = priority))
98 }
99
100 # Don't handle `source()` by default to avoid a performance hit
101 if (!is.null(getOption("withr.hook_source"))) {
102 envir <- source_exit_frame(envir)
103 }
104
105 thunk <- as.call(list(function() expr))
106 after <- priority == "last"
107
108 do.call(
109 base::on.exit,
110 list(thunk, TRUE, after),
111 envir = envir
112 )
113 }
114
115 # Inline formals for performance
116 formals(defer)[["priority"]] <- eval(formals(defer)[["priority"]])
117
118
119 #' @rdname defer
120 #' @export
121 defer_parent <- function(expr, priority = c("first", "last")) {
122 defer(expr, parent.frame(2), priority = priority)
123 }
124
125 #' @rdname defer
126 #' @export
127 deferred_run <- function(envir = parent.frame()) {
128 if (knitr_in_progress() && identical(envir, knitr::knit_global())) {
129 # The handlers are thunks so we don't need to clear them.
130 # They will only be run once.
131 frame <- knitr_exit_frame(envir)
132 handlers <- knitr_handlers(frame)
133 } else {
134 if (is_top_level_global_env(envir)) {
135 handlers <- the$global_exits
136 } else {
137 handlers <- frame_exits(envir)
138 }
139 deferred_clear(envir)
140 }
141
142 n <- length(handlers)
143 i <- 0L
144
145 if (!n) {
146 message("No deferred expressions to run")
147 return(invisible(NULL))
148 }
149
150 defer(message(
151 sprintf("Ran %s/%s deferred expressions", i, n)
152 ))
153
154 for (expr in handlers) {
155 eval(expr, envir)
156 i <- i + 1L
157 }
158 }
159
160 frame_exits <- function(frame = parent.frame()) {
161 exits <- do.call(sys.on.exit, list(), envir = frame)
162
163 # The exit expressions are stored in a single object that is
164 # evaluated on exit. This can be NULL, an expression, or multiple
165 # expressions wrapped in {. We convert this data structure to a list
166 # of expressions.
167 if (is.null(exits)) {
168 list()
169 } else if (identical(exits[[1]], quote(`{`))) {
170 as.list(exits[-1])
171 } else {
172 list(exits)
173 }
174 }
175 frame_clear_exits <- function(frame = parent.frame()) {
176 do.call(on.exit, list(), envir = frame)
177 }
178
179 #' @rdname defer
180 #' @export
181 deferred_clear <- function(envir = parent.frame()) {
182 if (is_top_level_global_env(envir)) {
183 the$global_exits <- list()
184 } else {
185 frame_clear_exits(envir)
186 }
187 invisible()
188 }
189
190 #' Defer expression globally
191 #'
192 #' This function is mostly internal. It is exported to be called in
193 #' standalone `defer()` implementations to defer expressions from the
194 #' global environment.
195 #'
196 #' @inheritParams defer
197 #' @keywords internal
198 #' @export
199 global_defer <- function(expr, priority = c("first", "last")) {
200 priority <- match.arg(priority, choices = c("first", "last"))
201
202 env <- globalenv()
203 handlers <- the$global_exits
204
205 if (!length(handlers)) {
206 # For session scopes we use reg.finalizer()
207 if (is_interactive()) {
208 message(
209 sprintf("Setting global deferred event(s).\n"),
210 "i These will be run:\n",
211 " * Automatically, when the R session ends.\n",
212 " * On demand, if you call `withr::deferred_run()`.\n",
213 "i Use `withr::deferred_clear()` to clear them without executing."
214 )
215 }
216 reg.finalizer(env, function(env) deferred_run(env), onexit = TRUE)
217 }
218
219 handler <- as.call(list(function() expr))
220
221 if (priority == "first") {
222 the$global_exits <- c(list(handler), handlers)
223 } else {
224 the$global_exits <- c(handlers, list(handler))
225 }
226
227 invisible(NULL)
228 }
229
230 the$global_exits <- list()
231
232 # Evaluate `frames` lazily to avoid expensive `sys.frames()`
233 # call for the default case of a local environment
234 is_top_level_global_env <- function(envir, frames = sys.frames()) {
235 if (!identical(envir, globalenv())) {
236 return(FALSE)
237 }
238
239 # Check if another global environment is on the stack
240 !any(vapply(frames, identical, NA, globalenv()))
241 }
242
243
244 # This picks up knitr's first frame on the stack and registers the
245 # handler there. To avoid mixing up knitr's own exit handlers with
246 # ours, we don't hook directly but instead save the list of handlers
247 # as an attribute on the frame environment. This allows `deferred_run()`
248 # to run our handlers without running the knitr ones.
249 defer_knitr <- function(expr, envir, priority = c("first", "last")) {
250 priority <- match.arg(priority, choices = c("first", "last"))
251
252 envir <- knitr_exit_frame(envir)
253 handler <- as.call(list(function() expr))
254
255 handlers <- knitr_handlers(envir)
256
257 # Add `on.exit` hook if run for first time
258 if (!length(handlers)) {
259 defer_knitr_run(envir)
260 }
261
262 if (priority == "first") {
263 handlers <- c(list(handler), handlers)
264 } else {
265 handlers <- c(handlers, list(handler))
266 }
267 attr(envir, "withr_knitr_handlers") <- handlers
268
269 invisible(NULL)
270 }
271
272 knitr_handlers <- function(envir) {
273 attr(envir, "withr_knitr_handlers") %||% list()
274 }
275
276 # Evaluate `handlers` lazily so we get the latest version
277 defer_knitr_run <- function(
278 envir,
279 handlers = knitr_handlers(envir)
280 ) {
281 defer(envir = envir, {
282 for (expr in handlers) {
283 eval(expr, envir)
284 }
285 })
286 }