Skip to content

Commit 0ea4a64

Browse files
committed
fix code parser for := operator
1 parent 777e087 commit 0ea4a64

File tree

3 files changed

+29
-1
lines changed

3 files changed

+29
-1
lines changed

DESCRIPTION

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ Imports:
3535
utils
3636
Suggests:
3737
cli (>= 3.4.0),
38+
data.table (>= 1.16.2),
3839
knitr (>= 1.42),
3940
rmarkdown (>= 2.23),
4041
shiny (>= 1.6.0),
@@ -47,7 +48,7 @@ RdMacros:
4748
lifecycle
4849
Config/Needs/verdepcheck: mllg/checkmate, r-lib/lifecycle, r-lib/rlang,
4950
r-lib/cli, yihui/knitr, rstudio/rmarkdown, rstudio/shiny,
50-
r-lib/testthat, r-lib/withr
51+
r-lib/testthat, r-lib/withr, Rdatatable/data.table
5152
Config/Needs/website: insightsengineering/nesttemplate
5253
Encoding: UTF-8
5354
Language: en-US

R/utils-get_code_dependency.R

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,7 @@ extract_calls <- function(pd) {
106106
calls <- Filter(function(call) !(nrow(call) == 1 && call$token == "';'"), calls)
107107
calls <- Filter(Negate(is.null), calls)
108108
calls <- fix_shifted_comments(calls)
109+
calls <- remove_dt_assign(calls)
109110
fix_arrows(calls)
110111
}
111112

@@ -148,6 +149,22 @@ fix_shifted_comments <- function(calls) {
148149
#' which is \code{`<-`(y,x)} instead of traditional `y <- x`.
149150
#' @keywords internal
150151
#' @noRd
152+
remove_dt_assign <- function(calls) {
153+
checkmate::assert_list(calls)
154+
lapply(calls, function(call) {
155+
dt_assign <-
156+
which(call$token == "LEFT_ASSIGN" & call$text == ":=")
157+
if (length(dt_assign) > 0) {
158+
call[-dt_assign, ]
159+
} else {
160+
call
161+
}
162+
})
163+
}
164+
165+
#' Fixes edge case of `:=` assignment operator being treated as assignemnt.
166+
#' @keywords internal
167+
#' @noRd
151168
fix_arrows <- function(calls) {
152169
checkmate::assert_list(calls)
153170
lapply(calls, function(call) {

tests/testthat/test-qenv_eval_code.R

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,16 @@ testthat::test_that("eval_code accepts calls containing only comments and empty
105105
testthat::expect_identical(get_code(eval_code(qenv(), code)), code)
106106
})
107107

108+
testthat::test_that("eval_code does not treat := as an assignment operator", {
109+
testthat::skip_if_not_installed("data.table")
110+
code <- "
111+
iris <- data.table::data.table(iris) %>%
112+
.[, NewSpecies := factor(Species)]
113+
"
114+
q <- eval_code(qenv(), code)
115+
testthat::expect_identical(get_code(q), code)
116+
})
117+
108118
# comments ----------
109119
testthat::test_that("comments fall into proper calls", {
110120
# If comment is on top, it gets moved to the first call.

0 commit comments

Comments
 (0)