Skip to content
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

Detection of variable usage prior to assignment in function scope #2739

Open
immanuelazn opened this issue Feb 12, 2025 · 1 comment
Open

Comments

@immanuelazn
Copy link

immanuelazn commented Feb 12, 2025

I've noticed that when a variable is being used in a function without assignment, we can expect that object_usage_linter can detect it. For instance variable bar here:

foo <- function() {
  # bar gets tagged with object_usage_linter
  if (bar == "5") return(TRUE)
  return(FALSE)
}

However, if we declare this variable after usage, either independently or as a name within an iterator, the object_usage_linter no longer thinks it is an issue.

foo <- function() {
  # bar doesn't get tagged with object_usage_linter
  if (bar == "5") return(TRUE)
  bar <- "1"
  return(FALSE)
}
foo <- function(test_vec) {
  # bar doesn't get tagged with object_usage_linter
  if (bar == "5") return(TRUE)
  for (bar in test_vec) next
  return(FALSE)
}

I have all linters on and I can't seem to get something that would flag variable usage before declaration. Would it be possible to build something that does this?

@AshesITR
Copy link
Collaborator

This is doable in principle using static code analysis and assuming well behaved R code. However, object_usage_linter() wraps codetools::checkUsage, so that would be a better place for this enhancement.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants