r-lib / lintr

Static Code Analysis for R
https://lintr.r-lib.org
Other
1.2k stars 187 forks source link

false positive in `object_usage_linter()` with `substitute()` in function #2255

Open jmbarbone opened 1 year ago

jmbarbone commented 1 year ago

Something funny seems to be happening with using substitute() when assigning a function definition:

library(lintr)
packageVersion("lintr")
#> [1] '3.1.0.9000'

code_ok1 <- "
substitute({
  a <- 1
  a
})
"

code_ok2 <- "
function() {
  substitute({
    a <- 1
    a
  })
}
"

code_bad <- "
foo <- function() {
  substitute({
    a <- 1
    a
  })
}
"

lint(text = code_ok1, linters = object_usage_linter())
lint(text = code_ok2, linters = object_usage_linter())
lint(text = code_bad, linters = object_usage_linter())
#> <text>:4:5: warning: [object_usage_linter] local variable 'a' assigned but may not be used
#>     a <- 1
#>     ^

Created on 2023-11-06 with reprex v2.0.2

AshesITR commented 1 year ago

IINM the first two are not linted at all by object_usage_linter(). The last one appears to be a bug in codetools::checkUsage().

travis-leith commented 1 year ago

Here is another case where object_usage_linter gives a false positive


object_linter_fail <- function(){
  a <- 1

  b <- case_when(
    FALSE ~ "",
    TRUE ~ paste0("", a, "")
  )

  b
}

It claims that a is not used.

AshesITR commented 1 year ago

dplyr::case_when() uses NSE, making this hard for codetools::checkUsage() to detect. Syntactically, formulae such as TRUE ~ paste0("", a, "") are not evaluated and thus their contained code not "used".

travis-leith commented 1 year ago

@AshesITR is it worth raising an issue in the code tools repo? https://gitlab.com/luke-tierney/codetools/-/issues or is this already a well known limitation?

AshesITR commented 1 year ago

Feel free to raise an issue. My experience with issues regarding codetools is they probably won't be fixed unless you provide a patch.

travis-leith commented 12 months ago

I tried to raise an issue but gitlab wants a credit card number to create an account, and I am not willing to provide it.

AshesITR commented 12 months ago

I had no problem logging into GitLab using GitHub as an identity provider. But your mileage may vary.