roxyglobals icon indicating copy to clipboard operation
roxyglobals copied to clipboard

Automation

Open krlmlr opened this issue 3 years ago • 2 comments

Would you support a new tag @globalsAuto that would inspect the code in the function and automatically add everything to globalVariables()?

krlmlr avatar Sep 29 '20 09:09 krlmlr

Cool idea! Yeah I think this should be achievable.

anthonynorth avatar Sep 30 '20 10:09 anthonynorth

I've implemented a workable solution v0.2.1, but it has limitations.

The current implementation cannot tell the difference between assigning a global to a local name, and a nse name. Any variable referencing a global that is not in baseenv() or package env is added to utils::globalVariables(). This results in the possibility of hiding errors reported by devtools::check() where a local is assigned a non-existent global (see foo example). I feel like the cases where this implementation fails (like below) will be flagged by a lint program or testing anyway, so it probably doesn't matter a lot.

A cheap solution might be to look for variable assignments with <- and ignoring any globals there? It's an assumption that tidy-developers are following the tidy style guide and not using = for variable assignment, so maybe it's fine. Another option is to ignore variables at the top level inside a closure; this probably requires hand-rolling a code walker though so it's less appealing.

In both of these examples, i_dont_exist is an undeclared global that is added to utils::globalVariables(). The first case is clearly not desirable.

#' @autoglobal
foo_bad <- function(data) {
  some_var <- i_dont_exist
}

#' @autoglobal
foo_good <- function(data) {
  dplyr::mutate(data, i_dont_exist = 1)
}

anthonynorth avatar Oct 03 '20 02:10 anthonynorth