diff --git a/R/parse.R b/R/parse.R index f93bbf79..9f8e8052 100644 --- a/R/parse.R +++ b/R/parse.R @@ -184,6 +184,19 @@ parse_check_consistent_dimensions_rhs <- function(eq, dat, call, src = eq$src) { "E2019", src, call) } + throw_array_as_scalar <- function(var, rank) { + what <- rank_description(rank) + if (rank == 1) { + dummy_index <- "..." + } else { + dummy_index <- paste(rep(".", rank), collapse = ", ") + } + odin_parse_error( + c("Trying to use {what} '{var}' without index", + i = sprintf("Did you mean '{var}[%s]'", dummy_index)), + "E2022", src, call) + } + fn_use_whole_array <- c("length", "nrow", "ncol", "OdinReduce", "OdinInterpolate") @@ -233,6 +246,11 @@ parse_check_consistent_dimensions_rhs <- function(eq, dat, call, src = eq$src) { } else { lapply(expr[-1], check) } + } else if (is.symbol(expr)) { + nm <- as.character(expr) + if (nm %in% dat$storage$arrays$name) { + throw_array_as_scalar(nm, dim_ranks[[nm]]) + } } } check(eq$rhs$expr) diff --git a/R/sysdata.rda b/R/sysdata.rda index a4ac7eb3..fbb5e6b9 100644 Binary files a/R/sysdata.rda and b/R/sysdata.rda differ diff --git a/tests/testthat/test-parse.R b/tests/testthat/test-parse.R index 82d63bd6..cb5d46b7 100644 --- a/tests/testthat/test-parse.R +++ b/tests/testthat/test-parse.R @@ -1060,3 +1060,30 @@ test_that("don't duplicate offsets when boundary condition used in initial", { expect_equal(dat$variables, "x") expect_equal(nrow(dat$storage$packing$state), 1) }) + + +test_that("prevent use of arrays without braces", { + err <- expect_error( + odin_parse({ + initial(x[]) <- 0 + update(x[]) <- b + b[] <- x[i] + dim(x) <- 5 + dim(b) <- 5 + }), + "Trying to use vector 'b' without index") + expect_match(conditionMessage(err), + "Did you mean 'b[...]'", fixed = TRUE) + + err <- expect_error( + odin_parse({ + initial(x[]) <- 0 + update(x[]) <- b + b[, ] <- 1 + dim(x) <- 5 + dim(b) <- c(5, 5) + }), + "Trying to use matrix 'b' without index") + expect_match(conditionMessage(err), + "Did you mean 'b[., .]'", fixed = TRUE) +}) diff --git a/vignettes/errors.Rmd b/vignettes/errors.Rmd index bfa8415a..7b4361cb 100644 --- a/vignettes/errors.Rmd +++ b/vignettes/errors.Rmd @@ -1097,6 +1097,17 @@ You have tried to set the dimensions of the same variable more than once. For ex dim(a, b) <- 2 dim(b, c) <- 3 +# `E2022` + +Trying to access an array without using square bracket indexes. For example if you write: + +```r +dim(b) <- 10 +a[] <- b +``` + +you would see this error, as you should have used `b[i]` on the right hand side (*probably!*; you might have meant `a[] <- b[1]`, too). + # `E3001` An array access would be out of bounds. This error is thrown where your code would result in you reading or writing out of bounds on an array (or a dimension of an array). Currently, we throw this error if we are certain that your access is invalid. For example, we would error if your code contains: