Skip to content

Use evaluate #258

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 14 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion .lintr
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
linters: linters_with_defaults(
line_length_linter = line_length_linter(120),
cyclocomp_linter = NULL,
object_usage_linter = NULL
)
2 changes: 2 additions & 0 deletions DESCRIPTION
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ Depends:
Imports:
checkmate (>= 2.1.0),
cli (>= 3.4.0),
evaluate (>= 1.0.0),
grDevices,
lifecycle (>= 0.2.0),
rlang (>= 1.1.0),
Expand Down Expand Up @@ -64,6 +65,7 @@ Collate:
'qenv-get_code.R'
'qenv-get_env.R'
'qenv-get_messages.r'
'qenv-get_outputs.R'
'qenv-get_var.R'
'qenv-get_warnings.R'
'qenv-join.R'
Expand Down
1 change: 1 addition & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export(eval_code)
export(get_code)
export(get_env)
export(get_messages)
export(get_outputs)
export(get_var)
export(get_warnings)
export(join)
Expand Down
5 changes: 5 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
# teal.code 0.6.1.9003

### Enhancements

* Introduced `get_outputs` function to fetch objects which have been printed or plotted in the `qenv` code.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we add a small section on the vignette as well? in addition to "### Warnings and messages in qenv objects"

diff --git a/vignettes/qenv.Rmd b/vignettes/qenv.Rmd
index 4859e32c..302b6846 100644
--- a/vignettes/qenv.Rmd
+++ b/vignettes/qenv.Rmd
@@ -126,7 +126,7 @@ The feasibility of joining `qenv` objects hinges on the contents of the environm
 
 ### Warnings and messages in `qenv` objects
 
-In cases where warnings or messages arise while evaluating code within a `qenv` environment, these are captured and stored within the `qenv` object. Access these messages and warnings using below
+In cases where warnings or messages arise while evaluating code within a `qenv` environment, these are captured and stored within the `qenv` object. Access these messages and warnings using `get_messages()` and `get_warnings()` functions as shown below.
 
 ```{r}
 q_message <- eval_code(qenv(), quote(message("this is a message")))
@@ -138,6 +138,15 @@ get_warnings(q_warning)
 
 If any of above returns `NULL`m then no warnings nor messages were present.
 
+### Outputs in `qenv` objects
+
+When evaluating code in a `qenv`, the outputs are captured and stored in a list. This includes printed objects, plots, warnings, and messages. You can retrieve these outputs using the `get_outputs()` function.
+
+```{r}
+q_output <- eval_code(qenv(), quote(plot(1:10)))
+get_outputs(q_output)
+```
+
 ## Utilizing `qenv` inside `shiny` applications
 
 These functions can be seamlessly integrated into `shiny` applications to produce reproducible outputs. In the example below, the `rcode` section showcases the code employed for generating the output.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've included some info about get_outputs(). Please have a look once again before I merge


### Bug fixes

* Fix a problem detecting co-occurrences when expression has multiple lines.

### Miscellaneous

* `eval_code` uses `evaluate::evaluate` and stores returned outputs in the code's attribute.
* Refactor `eval_code` method signature to allow for more flexibility when extending the `eval_code`/`within` functions.

# teal.code 0.6.1
Expand Down
5 changes: 3 additions & 2 deletions R/qenv-class.R
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,12 @@ setMethod(
"initialize",
"qenv",
function(.Object, .xData, code = list(), ...) { # nolint: object_name.
parent <- parent.env(.GlobalEnv)
new_xdata <- if (rlang::is_missing(.xData)) {
new.env(parent = parent.env(.GlobalEnv))
new.env(parent = parent)
} else {
checkmate::assert_environment(.xData)
rlang::env_clone(.xData, parent = parent.env(.GlobalEnv))
rlang::env_clone(.xData, parent = parent)
}
lockEnvironment(new_xdata, bindings = TRUE)

Expand Down
83 changes: 40 additions & 43 deletions R/qenv-eval_code.R
Original file line number Diff line number Diff line change
Expand Up @@ -44,60 +44,57 @@ setMethod("eval_code", signature = c(object = "qenv.error"), function(object, co
if (identical(trimws(code), "") || length(code) == 0) {
return(object)
}
code <- paste(split_code(code), collapse = "\n")

[email protected] <- rlang::env_clone([email protected], parent = parent.env([email protected]))
parsed_code <- parse(text = code, keep.source = TRUE)
[email protected] <- rlang::env_clone([email protected], parent = parent.env(.GlobalEnv))
if (length(parsed_code) == 0) {
# empty code, or just comments
attr(code, "dependency") <- extract_dependency(parsed_code) # in case comment contains @linksto tag
object@code <- c(object@code, stats::setNames(list(code), sample.int(.Machine$integer.max, size = 1)))
return(object)
}
code_split <- split_code(paste(code, collapse = "\n"))
for (i in seq_along(code_split)) {
current_code <- code_split[[i]]
current_call <- parse(text = current_code, keep.source = TRUE)
# Using withCallingHandlers to capture warnings and messages.
# Using tryCatch to capture the error and abort further evaluation.
x <- withCallingHandlers(
tryCatch(
{
eval(current_call, envir = [email protected])
if (!identical(parent.env([email protected]), parent.env(.GlobalEnv))) {
# needed to make sure that @.xData is always a sibling of .GlobalEnv
# could be changed when any new package is added to search path (through library or require call)
parent.env([email protected]) <- parent.env(.GlobalEnv)
}
NULL
},
error = function(e) {

old <- evaluate::inject_funs(
library = function(...) {
x <- library(...)
if (!identical(parent.env([email protected]), parent.env(.GlobalEnv))) {
parent.env([email protected]) <- parent.env(.GlobalEnv)
}
invisible(x)
}
)
out <- evaluate::evaluate(
code,
envir = [email protected],
stop_on_error = 1,
output_handler = evaluate::new_output_handler(value = identity)
)
out <- evaluate::trim_intermediate_plots(out)

evaluate::inject_funs(old) # remove library() override

new_code <- list()
for (this in out) {
if (inherits(this, "source")) {
this_code <- gsub("\n$", "", this$src)
attr(this_code, "dependency") <- extract_dependency(parse(text = this_code, keep.source = TRUE))
new_code <- c(new_code, stats::setNames(list(this_code), sample.int(.Machine$integer.max, size = 1)))
} else {
last_code <- new_code[[length(new_code)]]
if (inherits(this, "error")) {
return(
errorCondition(
message = sprintf(
"%s \n when evaluating qenv code:\n%s",
cli::ansi_strip(conditionMessage(e)),
current_code
cli::ansi_strip(conditionMessage(this)),
last_code
),
class = c("qenv.error", "try-error", "simpleError"),
trace = unlist(c(object@code, list(current_code)))
trace = unlist(c(object@code, list(new_code)))
)
}
),
warning = function(w) {
attr(current_code, "warning") <<- cli::ansi_strip(sprintf("> %s\n", conditionMessage(w)))
invokeRestart("muffleWarning")
},
message = function(m) {
attr(current_code, "message") <<- cli::ansi_strip(sprintf("> %s", conditionMessage(m)))
invokeRestart("muffleMessage")
)
}
)

if (!is.null(x)) {
return(x)
attr(last_code, "outputs") <- c(attr(last_code, "outputs"), list(this))
new_code[[length(new_code)]] <- last_code
}
attr(current_code, "dependency") <- extract_dependency(current_call)
object@code <- c(object@code, stats::setNames(list(current_code), sample.int(.Machine$integer.max, size = 1)))
}

object@code <- c(object@code, new_code)
lockEnvironment([email protected], bindings = TRUE)
object
}
Expand Down
30 changes: 30 additions & 0 deletions R/qenv-get_outputs.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
#' Get outputs
#'
#' @description
#' `eval_code` evaluates code silently so plots and prints don't show up in the console or graphic devices.
#' If one wants to use an output outside of the `qenv` (e.g. use a graph in `renderPlot`) then use `get_outputs`.
#' @param object (`qenv`)
#' @return list of outputs generated in a `qenv``
#' @examples
#' q <- eval_code(
#' qenv(),
#' quote({
#' a <- 1
#' print("I'm an output")
#' plot(1)
#' })
#' )
#' get_outputs(q)
#'
#' @aliases get_outputs,qenv-method
#'
#' @export
setGeneric("get_outputs", function(object) standardGeneric("get_outputs"))

setMethod("get_outputs", signature = "qenv", function(object) {
Reduce(
function(x, y) c(x, attr(y, "outputs")),
init = list(),
x = object@code
)
})
3 changes: 3 additions & 0 deletions R/utils-get_code_dependency.R
Original file line number Diff line number Diff line change
Expand Up @@ -521,6 +521,9 @@ get_call_breaks <- function(code) {
}
))
call_breaks <- call_breaks[-nrow(call_breaks), , drop = FALSE] # breaks in between needed only
if (nrow(call_breaks) == 0L) {
call_breaks <- matrix(numeric(0), ncol = 2)
}
colnames(call_breaks) <- c("line", "col")
call_breaks
}
Expand Down
19 changes: 16 additions & 3 deletions R/utils.R
Original file line number Diff line number Diff line change
Expand Up @@ -57,12 +57,25 @@ lang2calls <- function(x) {
#' Obtain warnings or messages from code slot
#'
#' @param object (`qenv`)
#' @param what (`"warning"` or `"message"`)
#' @param what (`warning` or `message`)
#' @return `character(1)` containing combined message or `NULL` when no warnings/messages
#' @keywords internal
get_warn_message_util <- function(object, what) {
checkmate::matchArg(what, choices = c("warning", "message"))
messages <- lapply(object@code, "attr", what)
messages <- lapply(
object@code,
function(x) {
unlist(lapply(
attr(x, "outputs"),
function(el) {
if (inherits(el, what)) {
sprintf("> %s", conditionMessage(el))
}
}
))
}
)

idx_warn <- which(sapply(messages, function(x) !is.null(x) && !identical(x, "")))
if (!any(idx_warn)) {
return(NULL)
Expand All @@ -74,7 +87,7 @@ get_warn_message_util <- function(object, what) {
warn = messages,
expr = code,
function(warn, expr) {
sprintf("%swhen running code:\n%s", warn, expr)
sprintf("%s\nwhen running code:\n%s", trimws(warn), trimws(expr))
}
)

Expand Down
1 change: 1 addition & 0 deletions _pkgdown.yml
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ reference:
- eval_code
- get_code
- get_env
- get_outputs
- get_var
- get_messages
- get_warnings
Expand Down
31 changes: 31 additions & 0 deletions man/get_outputs.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion man/get_warn_message_util.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading