Skip to content
Merged
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: 1 addition & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

* Fixed a problem parsing expression referring to the same object (#293).
* Fixed a problem when a symbol appears alone inside an expression (#299).
* `get_code()` now detects all objects created by a single call with multiple assignments, e.g. `a <- b <- 1`, `1 -> a -> b` or `a <- 1 -> b`. Previously only the first object was detected and mixing assignment operators in one call made `eval_code()` fail (#251).

### Miscellaneous

Expand Down
76 changes: 42 additions & 34 deletions R/utils-get_code_dependency.R
Original file line number Diff line number Diff line change
Expand Up @@ -296,50 +296,58 @@ extract_occurrence <- function(pd) {
# For cases like 'eval(expression(c <- b + 2))' removes 'eval(expression('.
sym_cond <- sym_cond[!(sym_cond < min(assign_cond) & sym_cond %in% sym_fc_cond)]

# If there was an assignment operation detect direction of it.
if (unique(x$text[assign_cond]) == "->") { # What if there are 2 assignments: e.g. a <- b -> c.
sym_cond <- rev(sym_cond)
}
is_target <- is_assignment_target(x, sym_cond, assign_cond)

after <- match(min(x$id[assign_cond]), sort(x$id[c(min(assign_cond), sym_cond)])) - 1
ans <- append(x[sym_cond, "text"], "<-", after = max(1, after))
ans <- move_functions_after_arrow(ans, unique(x[sym_fc_cond, "text"]))
# Function names on the target side are not assigned, e.g. `attributes` in `attributes(a) <- b`.
is_fun <- sym_cond %in% sym_fc_cond
ans <- c(x[sym_cond[is_target & !is_fun], "text"], "<-", x[sym_cond[!is_target], "text"])
c(ans, unique(in_parenthesis(pd)))
}

#' Moves function names to the right side of dependency graph
#' Detect symbols located on the target side of assignment operators
#'
#' Changes status of the function call from dependent to dependency if occurs in the lhs.
#' Technically, it means to move function names after the dependency operator.
#' For example, for `attributes(a) <- b` the dependency graph should look like `c("a", "<-", "b", "attributes")`.
#' Symbols located on the target side of any assignment operator are assigned (lhs),
#' all the others are dependencies (rhs). Handles multiple assignments in a single call,
#' e.g. `a <- b <- 1`, `1 -> a -> b` or `a <- 1 -> b`.
#'
#' @param ans `character` vector of object names in dependency graph.
#' @param functions `character` vector of function names.
#' Assignments within quoted code (e.g. `expr <- quote(x <- 1)`) are not evaluated, so they are skipped,
#' unless all the assignments are quoted (e.g. `eval(expression(x <- 1))`).
#'
#' @param pd `data.frame`; parse data of a single call, see `extract_calls()`.
#' @param sym_cond `integer` row indices of the symbols in `pd`.
#' @param assign_cond `integer` row indices of the assignment operators in `pd`.
#'
#' @return `logical` vector of the same length as `sym_cond`, `TRUE` for assigned symbols.
#'
#' @return
#' A character vector.
#' @keywords internal
#' @noRd
move_functions_after_arrow <- function(ans, functions) {
arrow_pos <- which(ans == "<-")
if (length(arrow_pos) == 0) {
return(ans)
}
if (length(functions) == 0) {
return(ans)
is_assignment_target <- function(pd, sym_cond, assign_cond) {
assign_ids <- pd$id[assign_cond]
quoting_funs <- pd$parent[
pd$token == "SYMBOL_FUNCTION_CALL" & pd$text %in% c("quote", "bquote", "expression", "substitute")
]
Comment thread
averissimo marked this conversation as resolved.
Resolved
quoted_ids <- unlist(lapply(pd$parent[pd$id %in% quoting_funs], function(id) get_children(pd, id)$id))
quoted <- assign_ids %in% quoted_ids
if (!all(quoted)) {
assign_ids <- assign_ids[!quoted]
}
ans_pre <- ans[1:arrow_pos]
# it's setdiff but without the removal of duplicates
# do not use setdiff(ans_pre, functions)
# as it removes duplicates from ans_pre even if they do not appear in functions
# check setdiff(c("A", "A"), "B") - gives "A", where we want to keep c("A", "A")
for (fun in functions) {
if (any(ans_pre == fun)) ans_pre <- ans_pre[-match(fun, ans_pre)]
}
after_arrow <- if (arrow_pos < length(ans)) {
ans[(arrow_pos + 1):length(ans)]
}
c(ans_pre, after_arrow)
# Target side is the lhs for `<-`, `<<-` and `=`, the rhs for `->` and `->>`,
# and the first argument for the functional form, e.g. `<-`(y, x).
target_roots <- unlist(lapply(assign_ids, function(id) {
op <- pd[pd$id == id, ]
operands <- pd[pd$parent == op$parent & pd$id != id & pd$token == "expr", ]
if (nrow(operands) == 0) {
# Functional form: the operator is the only child of the function expression.
operands <- pd[pd$parent %in% pd$parent[pd$id == op$parent] & pd$id != op$parent & pd$token == "expr", ]
if (nrow(operands) == 0) {
return(NULL)
}
}
operands <- operands[order(operands$line1, operands$col1), ]
operands$id[if (op$token == "RIGHT_ASSIGN") nrow(operands) else 1L]
}))
target_ids <- unlist(lapply(target_roots, function(root) c(root, get_children(pd, root)$id)))
pd$id[sym_cond] %in% target_ids
}

#' Extract side effects
Expand Down
96 changes: 96 additions & 0 deletions tests/testthat/test-qenv_get_code.R
Original file line number Diff line number Diff line change
Expand Up @@ -387,6 +387,10 @@ test_that("detects function usage of the assignment operator", {
get_code(q2, names = "y"),
pasten(code2)
)
expect_identical(
get_code(q2, names = "x"),
pasten(code2)
)
})


Expand Down Expand Up @@ -975,3 +979,95 @@ test_that("extracting code doesn't fail when lhs contains two or more symbols oc
q <- eval_code(qenv(), code)
expect_silent(get_code(q, names = "l"))
})

describe("detects multiple assignments in a single call", {
it("<-", {
code <- "var1 <- var2 <- 1"
q <- eval_code(qenv(), code)

expect_identical(get_code(q, names = "var1"), code)
expect_identical(get_code(q, names = "var2"), code)
})

it("->", {
code <- "1 -> var1 -> var2" # nolint: assignment.
q <- eval_code(qenv(), code)

expect_identical(get_code(q, names = "var1"), code)
expect_identical(get_code(q, names = "var2"), code)
})

it("<- and ->", {
code <- "var1 <- 1 -> var2" # nolint: assignment.
q <- eval_code(qenv(), code)

expect_identical(get_code(q, names = "var1"), code)
expect_identical(get_code(q, names = "var2"), code)
})

it("= and <-", {
code <- "var1 = var2 <- 1" # nolint: assignment.
q <- eval_code(qenv(), code)

expect_identical(get_code(q, names = "var1"), code)
expect_identical(get_code(q, names = "var2"), code)
})

it("<<- and ->>", {
code <- "1 ->> var1 ->> var2" # nolint: assignment.
q <- eval_code(qenv(), code)

expect_identical(get_code(q, names = "var1"), code)
expect_identical(get_code(q, names = "var2"), code)
})

it("more than two assignments", {
code <- "var1 <- var2 <- var3 <- 1"
q <- eval_code(qenv(), code)

expect_identical(get_code(q, names = "var3"), code)
})

it("with dependencies on the right-hand side", {
code <- c("x <- 1", "y <- 2", "var1 <- var2 <- x + 1")
q <- eval_code(qenv(), code)

expect_identical(get_code(q, names = "var2"), paste(code[c(1, 3)], collapse = "\n"))
})

it("with subassignment", {
code <- c("x <- 1", "a <- 1:3", "a[2] <- var2 <- x")
q <- eval_code(qenv(), code)

expect_identical(get_code(q, names = "a"), paste(code, collapse = "\n"))
expect_identical(get_code(q, names = "var2"), paste(code[c(1, 3)], collapse = "\n"))
})

it("does not treat replacement functions as assigned objects", {
code <- c("a <- 1", "b <- 1", "names(a) <- var2 <- \"x\"", "y <- names(b)")
q <- eval_code(qenv(), code)

expect_identical(get_code(q, names = "y"), paste(code[c(2, 4)], collapse = "\n"))
})

it("returns the latest assignment of a reassigned object", {
code <- c("var2 <- 0", "var1 <- var2 <- 1")
q <- eval_code(qenv(), code)

expect_identical(get_code(q, names = "var2"), paste(code, collapse = "\n"))
})

it("tracks objects depending on any of the assigned objects", {
code <- c("var1 <- var2 <- 1", "z <- var2 + 1")
q <- eval_code(qenv(), code)

expect_identical(get_code(q, names = "z"), paste(code, collapse = "\n"))
})

it("ignores assignments within quoted code", {
code <- c("x <- 0", "var1 <- expr <- quote(x <- 1)")
q <- eval_code(qenv(), code)

expect_identical(get_code(q, names = "x"), code[1])
})
})
Loading