-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathstring_interpolation.R
More file actions
252 lines (243 loc) · 7.54 KB
/
string_interpolation.R
File metadata and controls
252 lines (243 loc) · 7.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
#' Split a string, keeping separator regions
#'
#' @param x character string to split (length 1 vector)
#' @param split split pattern
#' @param ... force later arguments to bind by name
#' @param ignore.case passed to \code{gregexpr}
#' @param perl passed to \code{gregexpr}
#' @param fixed passed to \code{gregexpr}
#' @param useBytes passed to \code{gregexpr}
#' @return list of string segments annotated with is_sep.
#'
#' @seealso \code{\link{sinterp}}, \code{\link{si}}
#'
#' @examples
#'
#' strsplit_capture("x is .(x) and x+1 is .(x+1)", "\\.\\([^()]+\\)")
#'
#' @export
#'
strsplit_capture <- function(x, split,
...,
ignore.case = FALSE,
fixed = FALSE,
perl = FALSE,
useBytes = FALSE) {
if(!is.character(x)) {
stop("wrapr::strsplit_capture x must be character")
}
if(length(x)!=1) {
stop("wrapr::strsplit_capture x must be length 1")
}
wrapr::stop_if_dot_args(substitute(list(...)), "wrapr::strsplit_capture")
matches <- gregexpr(split, x,
ignore.case = ignore.case,
perl = perl,
fixed = fixed,
useBytes = useBytes)[[1]]
lens <- attr(matches, "match.length", exact = TRUE)
idxs <- as.integer(matches)
if((length(idxs)<1) || (idxs[[1]]<1)) {
attr(x, "is_sep") <- FALSE
return(list(x))
}
match_posns <- logical(nchar(x)+1)
match_posns[idxs] <- TRUE
intervals <- sort(unique(c(1, nchar(x)+1, idxs, idxs+lens)))
pieces <- lapply(
seq_len(length(intervals)-1),
function(i) {
is_match <- match_posns[[intervals[[i]]]]
pi <- substr(x, intervals[[i]], intervals[[i+1]]-1)
attr(pi, "is_sep") <- is_match
pi
})
pieces
}
#' Dot substitution string interpolation.
#'
#' String interpolation using \code{bquote}-stype .() notation. Pure R, no C/C++ code called.
#'
#' See also
#' \url{https://CRAN.R-project.org/package=R.utils},
#' \url{https://CRAN.R-project.org/package=rprintf},
#' and \url{https://CRAN.R-project.org/package=glue}.
#'
#'
#' @param str charater string(s) to be substituted into
#' @param ... force later arguments to bind by name
#' @param envir environemnt to look for values
#' @param enclos enclosing evaluation environment
#' @param match_pattern regexp to find substitution targets.
#' @param removal_patterns regexps to remove markers from substitution targets.
#' @return modified strings
#'
#' @seealso \code{\link{strsplit_capture}}, \code{\link{si}}
#'
#' @examples
#'
#' x <- 7
#' sinterp("x is .(x), x+1 is .(x+1)\n.(x) is odd is .(x%%2 == 1)")
#'
#' # Because matching is done by a regular expression we
#' # can not use arbitrary depths of nested parenthesis inside
#' # the interpolation region. The default regexp allows
#' # one level of nesting (and one can use {} in place
#' # of parens in many places).
#' sinterp("sin(x*(x+1)) is .(sin(x*{x+1}))")
#'
#' # We can also change the delimiters,
#' # in this case to !! through the first whitespace.
#' sinterp(c("x is !!x , x+1 is !!x+1 \n!!x is odd is !!x%%2==1"),
#' match_pattern = '!![^[:space:]]+[[:space:]]?',
#' removal_patterns = c("^!!", "[[:space:]]?$"))
#'
#' @export
#'
sinterp <- function(str,
...,
envir = parent.frame(),
enclos = parent.frame(),
match_pattern = "\\.\\((([^()]+)|(\\([^()]*\\)))+\\)",
removal_patterns = c("^\\.\\(", "\\)$")) {
force(envir)
if(!is.environment(envir)) {
envir <- list2env(as.list(envir), parent = parent.frame())
}
force(enclos)
if(!is.environment(enclos)) {
enclos <- list2env(as.list(enclos), parent = parent.frame())
}
wrapr::stop_if_dot_args(substitute(list(...)), "wrapr::sinterp")
if(!is.character(str)) {
stop("wrapr::sinterp str must be of class character")
}
if(length(str) <= 0) {
stop("wrapr::sinterp str must be of length at least 1")
}
orig_names <- names(str)
res <- vapply(
str,
function(stri) {
pi <- strsplit_capture(stri, match_pattern)
npi <- length(pi)
xlated <- list()
for(j in seq_len(npi)) {
pij <- pi[[j]]
if(!isTRUE(attr(pij, "is_sep", exact = TRUE))) {
xlated <- c(xlated, list(as.character(pij))) # strip attributes.
} else {
expr <- as.character(pij) # strip attributes.
for(rp in removal_patterns) {
expr <- as.character(gsub(rp, "", expr))
}
val <- eval(parse(text = expr), envir = envir, enclos = enclos)
val <- deparse(val)
xlated <- c(xlated, list(val))
}
}
do.call(paste0, xlated)
},
character(1))
if(length(orig_names) <= 0) {
names(res) <- NULL
}
return(res)
}
#' Dot substitution string interpolation.
#'
#' String interpolation using \code{bquote}-stype .() notation. Pure R, no C/C++ code called.
#' \code{sinterp} and \code{si} are synonyms.
#'
#' See also
#' \url{https://CRAN.R-project.org/package=R.utils},
#' \url{https://CRAN.R-project.org/package=rprintf},
#' and \url{https://CRAN.R-project.org/package=glue}.
#'
#'
#' @param str charater string to be substituted into
#' @param ... force later arguments to bind by name
#' @param envir environemnt to look for values
#' @param enclos enclosing evaluation environment
#' @param match_pattern regexp to find substitution targets.
#' @param removal_patterns regexps to remove markers from substitution targets.
#' @return modified strings
#'
#' @seealso \code{\link{strsplit_capture}}, \code{\link{sinterp}}
#'
#' @examples
#'
#' x <- 7
#' si("x is .(x), x+1 is .(x+1)\n.(x) is odd is .(x%%2 == 1)")
#'
#' # Because matching is done by a regular expression we
#' # can not use arbitrary depths of nested parenthesis inside
#' # the interpolation region. The default regexp allows
#' # one level of nesting (and one can use {} in place
#' # of parens in many places).
#' si("sin(x*(x+1)) is .(sin(x*{x+1}))")
#'
#' # We can also change the delimiters,
#' # in this case to !! through the first whitespace.
#' si(c("x is !!x , x+1 is !!x+1 \n!!x is odd is !!x%%2==1"),
#' match_pattern = '!![^[:space:]]+[[:space:]]?',
#' removal_patterns = c("^!!", "[[:space:]]?$"))
#'
#'
#' @export
#'
si <- sinterp
#' Dot substitution string interpolation.
#'
#' String interpolation using \code{bquote}-stype .() notation. Pure R, no C/C++ code called.
#'
#' See also
#' \url{https://CRAN.R-project.org/package=R.utils},
#' \url{https://CRAN.R-project.org/package=rprintf},
#' and \url{https://CRAN.R-project.org/package=glue}.
#'
#'
#' @param str charater string to be substituted into
#' @param envir environemnt to look for values
#' @return modified strings
#'
#' @seealso \code{\link{strsplit_capture}}, \code{\link{si}}
#'
#' @examples
#'
#' "x is .(x)" %<s% list(x = 7)
#'
#'
#' @export
#'
`%<s%` <- function(str, envir) {
force(envir)
sinterp(str, envir = envir, enclos = envir)
}
#' Dot substitution string interpolation.
#'
#' String interpolation using \code{bquote}-stype .() notation. Pure R, no C/C++ code called.
#'
#' See also
#' \url{https://CRAN.R-project.org/package=R.utils},
#' \url{https://CRAN.R-project.org/package=rprintf},
#' and \url{https://CRAN.R-project.org/package=glue}.
#'
#'
#' @param envir environemnt to look for values
#' @param str charater string to be substituted into
#' @return modified strings
#'
#' @seealso \code{\link{strsplit_capture}}, \code{\link{si}}
#'
#' @examples
#'
#' list(x = 7) %s>% "x is .(x)"
#'
#'
#' @export
#'
`%s>%` <- function(envir, str) {
force(envir)
sinterp(str, envir = envir, enclos = envir)
}