Type: | Package |
Title: | Parsing and Evaluation Tools that Provide More Details than the Default |
Version: | 1.0.3 |
Description: | Parsing and evaluation tools that make it easy to recreate the command line behaviour of R. |
License: | MIT + file LICENSE |
URL: | https://evaluate.r-lib.org/, https://github.com/r-lib/evaluate |
BugReports: | https://github.com/r-lib/evaluate/issues |
Depends: | R (≥ 3.6.0) |
Suggests: | callr, covr, ggplot2 (≥ 3.3.6), lattice, methods, pkgload, rlang, knitr, testthat (≥ 3.0.0), withr |
Config/Needs/website: | tidyverse/tidytemplate |
Config/testthat/edition: | 3 |
Encoding: | UTF-8 |
RoxygenNote: | 7.3.2 |
NeedsCompilation: | no |
Packaged: | 2025-01-10 22:27:28 UTC; hadleywickham |
Author: | Hadley Wickham [aut, cre],
Yihui Xie |
Maintainer: | Hadley Wickham <hadley@posit.co> |
Repository: | CRAN |
Date/Publication: | 2025-01-10 23:00:02 UTC |
evaluate: Parsing and Evaluation Tools that Provide More Details than the Default
Description
Parsing and evaluation tools that make it easy to recreate the command line behaviour of R.
Author(s)
Maintainer: Hadley Wickham hadley@posit.co
Authors:
Yihui Xie (ORCID)
Other contributors:
Michael Lawrence [contributor]
Thomas Kluyver [contributor]
Jeroen Ooms [contributor]
Barret Schloerke [contributor]
Adam Ryczkowski [contributor]
Hiroaki Yutani [contributor]
Michel Lang [contributor]
Karolis Koncevičius [contributor]
Posit Software, PBC [copyright holder, funder]
See Also
Useful links:
Report bugs at https://github.com/r-lib/evaluate/issues
Generate a traceback from a list of calls
Description
Generate a traceback from a list of calls
Usage
create_traceback(callstack)
Arguments
callstack |
stack of calls, as generated by (e.g.)
|
Evaluate input and return all details of evaluation
Description
Compare to eval()
, evaluate
captures all of the
information necessary to recreate the output as if you had copied and pasted
the code into a R terminal. It captures messages, warnings, errors and
output, all correctly interleaved in the order in which they occured. It
stores the final result, whether or not it should be visible, and the
contents of the current graphics device.
Usage
evaluate(
input,
envir = parent.frame(),
enclos = NULL,
debug = FALSE,
stop_on_error = 0L,
keep_warning = TRUE,
keep_message = TRUE,
log_echo = FALSE,
log_warning = FALSE,
new_device = TRUE,
output_handler = NULL,
filename = NULL,
include_timing = FALSE
)
Arguments
input |
input object to be parsed and evaluated. May be a string, file
connection or function. Passed on to |
envir |
environment in which to evaluate expressions. |
enclos |
when |
debug |
if |
stop_on_error |
A number between 0 and 2 that controls what happens when the code errors:
|
keep_warning , keep_message |
A single logical value that controls what happens to warnings and messages.
Note that setting the envvar |
log_echo , log_warning |
If This will be force to |
new_device |
if |
output_handler |
an instance of |
filename |
string overrriding the |
include_timing |
Deprecated. |
Examples
evaluate(c(
"1 + 1",
"2 + 2"
))
# Not that's there's a difference in output between putting multiple
# expressions on one line vs spreading them across multiple lines
evaluate("1;2;3")
evaluate(c("1", "2", "3"))
# This also affects how errors propagate, matching the behaviour
# of the R console
evaluate("1;stop(2);3")
evaluate(c("1", "stop(2)", "3"))
An emulation of flush.console()
in evaluate()
Description
When evaluate()
is evaluating code, the text output is diverted into
an internal connection, and there is no way to flush that connection. This
function provides a way to "flush" the connection so that any text output can
be immediately written out, and more importantly, the text
handler
(specified in the output_handler
argument of evaluate()
) will
be called, which makes it possible for users to know it when the code
produces text output using the handler.
This function is supposed to be called inside evaluate()
(e.g.
either a direct evaluate()
call or in knitr code chunks).
Usage
flush_console()
Inject functions into the environment of evaluate()
Description
Create functions in the environment specified in the envir
argument of
evaluate()
. This can be helpful if you want to substitute certain
functions when evaluating the code. To make sure it does not wipe out
existing functions in the environment, only functions that do not exist in
the environment are injected.
Usage
inject_funs(...)
Arguments
... |
Named arguments of functions. If empty, previously injected functions will be emptied. |
Value
Invisibly returns previous values.
Note
For expert use only. Do not use it unless you clearly understand it.
Examples
library(evaluate)
# normally you cannot capture the output of system
evaluate("system('R --version')")
# replace the system() function
old <- inject_funs(system = function(...) {
cat(base::system(..., intern = TRUE), sep = "\n")
})
evaluate("system('R --version')")
# restore previously injected functions
inject_funs(old)
Object class tests
Description
Object class tests
Usage
is.message(x)
is.warning(x)
is.error(x)
is.source(x)
is.recordedplot(x)
Line prompt.
Description
Format a single expression as if it had been entered at the command prompt.
Usage
line_prompt(x, prompt = getOption("prompt"), continue = getOption("continue"))
Arguments
x |
string representing a single expression |
prompt |
prompt for first line |
continue |
prompt for subsequent lines |
Value
a string
Control common output options
Description
Often when using evaluate()
you are running R code with a specific output
context in mind. But there are many options and env vars that packages
will take from the current environment, meaning that output depends on
the current state in undesirable ways.
This function allows you to describe the characteristics of the desired output and takes care of setting the options and environment variables for you.
Usage
local_reproducible_output(
width = 80,
color = FALSE,
unicode = FALSE,
hyperlinks = FALSE,
rstudio = FALSE,
frame = parent.frame()
)
Arguments
width |
Value of the |
color |
Determines whether or not cli/crayon colour should be used. |
unicode |
Should we use unicode characaters where possible? |
hyperlinks |
Should we use ANSI hyperlinks? |
rstudio |
Should we pretend that we're running inside of RStudio? |
frame |
Scope of the changes; when this calling frame terminates the changes will be undone. For expert use only. |
Custom output handlers
Description
An output_handler
handles the results of evaluate()
,
including the values, graphics, conditions. Each type of output is handled by
a particular function in the handler object.
Usage
new_output_handler(
source = identity,
text = identity,
graphics = identity,
message = identity,
warning = identity,
error = identity,
value = render,
calling_handlers = list()
)
Arguments
source |
Function to handle the echoed source code under evaluation.
This function should take two arguments ( Return |
text |
Function to handle any textual console output. |
graphics |
Function to handle graphics, as returned by
|
message |
Function to handle |
warning |
Function to handle |
error |
Function to handle |
value |
Function to handle the values returned from evaluation.
|
calling_handlers |
List of calling handlers.
These handlers have precedence over the exiting handler installed
by |
Details
The handler functions should accept an output object as their first argument.
The return value of the handlers is ignored, except in the case of the
value
handler, where a visible return value is saved in the output
list.
Calling the constructor with no arguments results in the default handler, which mimics the behavior of the console by printing visible values.
Note that recursion is common: for example, if value
does any
printing, then the text
or graphics
handlers may be called.
Value
A new output_handler
object
Parse, retaining comments
Description
Works very similarly to parse, but also keeps original formatting and comments.
Usage
parse_all(x, filename = NULL, allow_error = FALSE)
Arguments
x |
object to parse. Can be a string, a file connection, or a function. If a connection, will be opened and closed only if it was closed initially. |
filename |
string overriding the file name |
allow_error |
whether to allow syntax errors in |
Value
A data frame two columns, src
and expr
, and one row for each complete
input in x
. A complete input is R code that would trigger execution when
typed at the console. This might consist of multiple expressions separated
by ;
or one expression spread over multiple lines (like a function
definition).
src
is a character vector of source code. Each element represents a
complete input expression (which might span multiple line) and always has a
terminal \n
.
expr
is a list-column of expressions. The expressions can be of any
length, depending on the structure of the complete input source:
If
src
consists of only only whitespace and/or comments,expr
will be length 0.If
src
a single scalar (likeTRUE
,1
, or"x"
), name, or function call,expr
will be length 1.If
src
contains multiple expressions separated by;
,expr
will have length two or more.
The expressions have their srcrefs removed.
If there are syntax errors in x
and allow_error = TRUE
, the data
frame will have an attribute PARSE_ERROR
that stores the error object.
Examples
# Each of these inputs are single line, but generate different numbers of
# expressions
source <- c(
"# a comment",
"x",
"x;y",
"x;y;z"
)
parsed <- parse_all(source)
lengths(parsed$expr)
str(parsed$expr)
# Each of these inputs are a single expression, but span different numbers
# of lines
source <- c(
"function() {}",
"function() {",
" # Hello!",
"}",
"function() {",
" # Hello!",
" # Goodbye!",
"}"
)
parsed <- parse_all(source)
lengths(parsed$expr)
parsed$src
Replay a list of evaluated results
Description
Replay a list of evaluated results, as if you'd run them in an R terminal.
Usage
replay(x)
Arguments
x |
result from |
Examples
f1 <- function() {
cat("1\n")
print("2")
warning("3")
print("4")
message("5")
stop("6")
}
replay(evaluate("f1()"))
f2 <- function() {
message("Hello")
plot(1:10)
message("Goodbye")
}
replay(evaluate("f2()"))
Set and remove hooks
Description
This interface wraps the base setHook()
function to provide a return
value that makes it easy to undo.
Usage
set_hooks(hooks, action = "append")
remove_hooks(hooks)
Arguments
hooks |
a named list of hooks - each hook can either be a function or a list of functions. |
action |
|
Examples
new1 <- list(before.plot.new = function() print("Plotted!"))
new2 <- list(before.plot.new = function() print("Plotted Again!"))
set_hooks(new1)
set_hooks(new2)
plot(1)
remove_hooks(new1)
plot(1)
remove_hooks(new2)
plot(1)
Trim away intermediate plots
Description
Trim off plots that are modified by subsequent lines to only show the "final" plot.
Usage
trim_intermediate_plots(x)
Arguments
x |
An evaluation object produced by |
Value
A modified evaluation object.
Examples
ev <- evaluate(c(
"plot(1:3)",
"text(1, 1, 'x')",
"text(1, 1, 'y')"
))
# All intermediate plots are captured
ev
# Only the final plot is shown
trim_intermediate_plots(ev)
Try, capturing stack on error
Description
This is a variant of tryCatch()
that also captures the call
stack if an error occurs.
Usage
try_capture_stack(quoted_code, env)
Arguments
quoted_code |
code to evaluate, in quoted form |
env |
environment in which to execute code |