Debian Codegraph @

R/dynamic.R

raw
1
2 #
3 # Tools for so-called 'dynamic' values. These are values which are computed
4 # once, and then memoized for the rest of the currently-executing call.
5 #
6 # An exit handler placed in the top-most (renv) environment is then responsible
7 # for cleaning up any objects cached for the duration of that frame.
8 #
9 # This is a useful way to cache results for repeatedly-computed values
10 # that one can reasonably expect not to change in the duration of a
11 # particular call.
12 #
13
14 the$dynamic_envir <- NULL
15 the$dynamic_objects <- new.env(parent = emptyenv())
16
17 dynamic <- function(key, value, envir = NULL, force = FALSE) {
18
19 # allow opt-out just in case
20 enabled <- getOption("renv.dynamic.enabled", default = TRUE)
21 if (!enabled)
22 return(value)
23
24 # get a unique id for the scope where this function was invoked
25 caller <- sys.call(sys.parent())[[1L]]
26 if (renv_call_matches(caller, ":::"))
27 caller <- caller[[3L]]
28
29 # handle cases like FUN
30 if (is.null(the$envir_self[[as.character(caller)]])) {
31 if (!renv_tests_running()) {
32 fmt <- "internal error: dynamic() received unexpected call '%s'"
33 stopf(fmt, stringify(sys.call(sys.parent())))
34 }
35 }
36
37 # just return value if this isn't a valid dynamic scope
38 if (!is.symbol(caller)) {
39 dlog("dynamic", "invalid dynamic scope '%s'", stringify(sys.call(sys.parent())))
40 return(value)
41 }
42
43 # make sure we have a dynamic scope active
44 the$dynamic_envir <- the$dynamic_envir %||% renv_dynamic_envir(envir)
45
46 # resolve key from variables in the parent frame
47 key <- paste(names(key), map_chr(key, stringify), sep = " = ", collapse = ", ")
48
49 # put it together
50 id <- sprintf("%s(%s)", as.character(caller), key)
51
52 # if we're forcing, clear the memoized value
53 if (force)
54 the$dynamic_objects[[id]] <- NULL
55
56 # memoize the result of the expression
57 the$dynamic_objects[[id]] <- the$dynamic_objects[[id]] %||% {
58 dlog("dynamic", "memoizing dynamic value for '%s'", id)
59 value
60 }
61
62 }
63
64 renv_dynamic_envir <- function(envir = NULL) {
65
66 envir <- envir %||% renv_dynamic_envir_impl()
67 defer(renv_dynamic_reset(), scope = envir)
68
69 dlog("dynamic", "using dynamic environment '%s'", format(envir))
70 envir
71 }
72
73 renv_dynamic_envir_impl <- function() {
74
75 frames <- sys.frames()
76 for (i in seq_along(frames)) {
77 envir <- frames[[i]]
78 if (identical(parent.env(envir), the$envir_self))
79 return(envir)
80 }
81
82 stop("internal error: no renv frame available for dynamic call")
83
84 }
85
86 renv_dynamic_reset <- function() {
87 dlog("dynamic", "resetting dynamic objects")
88 the$dynamic_envir <- NULL
89 renv_envir_clear(the$dynamic_objects)
90 }