Debian Codegraph @

R/local_.R

raw
1 #' @include aaa.R
2 NULL
3
4 #' @rdname with_
5 #' @export
6 local_ <- function(
7 set,
8 reset = set,
9 get = NULL,
10 ...,
11 envir = parent.frame(),
12 new = TRUE,
13 dots = FALSE
14 ) {
15 if (!missing(...)) {
16 stop("`...` must be empty.")
17 }
18
19 fmls <- formals(set)
20
21 if (length(fmls) > 0L) {
22 # Called pass all extra formals on
23 called_fmls <- setNames(lapply(names(fmls), as.symbol), names(fmls))
24
25 # Special case for dots. If `set()` and/or `get()` take dots, it
26 # is assumed they implement `options()`-like semantic: a list
27 # passed as first argument is automatically spliced in the dots.
28 names(called_fmls)[names(called_fmls) == "..."] <- ""
29
30 if (new) {
31 if (dots) {
32 called_fmls[[1]] <- as.symbol(".new")
33 fun_args <- c(alist(.new = list(), ... = ), fmls[-1L])
34 } else {
35 called_fmls[[1]] <- as.symbol("new")
36 fun_args <- c(alist(new = list()), fmls[-1L])
37 }
38 } else {
39 fun_args <- fmls
40 }
41 } else {
42 # no formals
43 called_fmls <- NULL
44
45 fun_args <- alist()
46 }
47
48 set_call <- as.call(c(substitute(set), called_fmls))
49 reset <- if (missing(reset)) substitute(set) else substitute(reset)
50
51 if (dots) {
52 modify_call <- quote(.new <- list_combine(as.list(.new), list(...)))
53 } else {
54 modify_call <- NULL
55 }
56
57 if (is.null(get)) {
58 fun <- eval(bquote(function(args) {
59 .(modify_call)
60 old <- .(set_call)
61 withr::defer(.(reset)(old), envir = .local_envir)
62 invisible(old)
63 }))
64 } else {
65 get_call <- as.call(c(substitute(get), called_fmls))
66 fun <- eval(bquote(function(args) {
67 .(modify_call)
68 old <- .(get_call)
69 withr::defer(.(reset)(old), envir = .local_envir)
70 .(set_call)
71 invisible(old)
72 }))
73 }
74
75 # substitute does not work on arguments, so we need to fix them manually
76 formals(fun) <- c(fun_args, alist(.local_envir = parent.frame()))
77 environment(fun) <- envir
78
79 fun
80 }