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

New object_overwrite_linter #2307

Merged
merged 21 commits into from
Nov 19, 2023
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions DESCRIPTION
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,7 @@ Collate:
'numeric_leading_zero_linter.R'
'object_length_linter.R'
'object_name_linter.R'
'object_overwrite_linter.R'
'object_usage_linter.R'
'outer_negation_linter.R'
'package_hooks_linter.R'
Expand Down
1 change: 1 addition & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ export(nonportable_path_linter)
export(numeric_leading_zero_linter)
export(object_length_linter)
export(object_name_linter)
export(object_overwrite_linter)
export(object_usage_linter)
export(open_curly_linter)
export(outer_negation_linter)
Expand Down
94 changes: 94 additions & 0 deletions R/object_overwrite_linter.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
#' Block assigning any variables whose name clashes with a `base` R function
#'
#' Re-using existing names creates a risk of subtle error best avoided.
#' Avoiding this practice also encourages using better, more descriptive names.
#'
#' @param packages Character vector of packages to search for names that should
#' be avoided. Defaults to the most common default packages: base, stats,
#' utils, tools, methods, graphics, and grDevices.
#'
#' @examples
#' # will produce lints
#' code <- "function(x) {\n data <- x\n data\n}"
#' writeLines(code)
#' lint(
#' text = code,
#' linters = object_overwrite_linter()
#' )
#'
#' code <- "function(x) {\n lint <- 'fun'\n lint\n}"
#' writeLines(code)
#' lint(
#' text = code,
#' linters = object_overwrite_linter(packages = "lintr")
#' )
#'
#' # okay
#' code <- "function(x) {\n data('mtcars')\n}"
#' writeLines(code)
#' lint(
#' text = code,
#' linters = object_overwrite_linter()
#' )
#'
#' code <- "function(x) {\n data <- x\n data\n}"
#' writeLines(code)
#' lint(
#' text = code,
#' linters = object_overwrite_linter(packages = "base")
#' )
#'
#' @evalRd rd_tags("object_overwrite_linter")
#' @seealso
#' - [linters] for a complete list of linters available in lintr.
#' - <https://style.tidyverse.org/syntax.html#object-names>
#' @export
object_overwrite_linter <- function(
packages = c("base", "stats", "utils", "tools", "methods", "graphics", "grDevices")) {
for (package in packages) {
if (!requireNamespace(package, quietly = TRUE)) {
stop("Package '", package, "' is not available.")
}
}
pkg_exports <- lapply(packages, getNamespaceExports)
pkg_exports <- data.frame(
package = rep(packages, lengths(pkg_exports)),
name = unlist(pkg_exports),
stringsAsFactors = FALSE
)

# test that the symbol doesn't match an argument name in the function
MichaelChirico marked this conversation as resolved.
Show resolved Hide resolved
# NB: data.table := has parse token LEFT_ASSIGN as well
xpath <- glue("
//SYMBOL[
not(text() = ancestor::expr/preceding-sibling::SYMBOL_FORMALS/text())
and ({ xp_text_in_table(pkg_exports$name) })
]/
parent::expr[
count(*) = 1
and following-sibling::LEFT_ASSIGN[text() = '<-']
MichaelChirico marked this conversation as resolved.
Show resolved Hide resolved
and ancestor::expr/preceding-sibling::FUNCTION
]
")

Linter(function(source_expression) {
if (!is_lint_level(source_expression, "expression")) {
return(list())
}

xml <- source_expression$xml_parsed_content

bad_expr <- xml_find_all(xml, xpath)
bad_symbol <- xml_text(xml_find_first(bad_expr, "SYMBOL"))
source_pkg <- pkg_exports$package[match(bad_symbol, pkg_exports$name)]
lint_message <-
sprintf("'%s' is an exported object from package '%s'. Avoid re-using such symbols.", bad_symbol, source_pkg)

xml_nodes_to_lints(
bad_expr,
source_expression = source_expression,
lint_message = lint_message,
type = "warning"
)
})
}
1 change: 1 addition & 0 deletions inst/lintr/linters.csv
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ nonportable_path_linter,robustness best_practices configurable
numeric_leading_zero_linter,style consistency readability
object_length_linter,style readability default configurable executing
object_name_linter,style consistency default configurable executing
object_overwrite_linter,best_practices robustness readability configurable executing
object_usage_linter,style readability correctness default executing configurable
open_curly_linter,style readability deprecated configurable
outer_negation_linter,readability efficiency best_practices
Expand Down
1 change: 1 addition & 0 deletions man/best_practices_linters.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions man/configurable_linters.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions man/executing_linters.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 6 additions & 5 deletions man/linters.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

60 changes: 60 additions & 0 deletions man/object_overwrite_linter.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions man/readability_linters.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions man/robustness_linters.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

83 changes: 83 additions & 0 deletions tests/testthat/test-object_overwrite_linter
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
test_that("object_overwrite_linter skips allowed usages", {
MichaelChirico marked this conversation as resolved.
Show resolved Hide resolved
linter <- object_overwrite_linter()

expect_lint("function() DT <- data.frame(a = 1)", NULL, linter)

# don't block names subassigned e.g. as columns or list elements
expect_lint("function() x$sd <- sd(rnorm(100))", NULL, linter)
})

test_that("object_overwrite_linter blocks simple disallowed usages", {
linter <- object_overwrite_linter()

expect_lint(
"foo <- function() data <- mtcars",
rex::rex("'data' is an exported object from package 'utils'."),
linter
)

expect_lint(
trim_some("
foo <- function() {
sigma <- sd(rnorm(100))
}
"),
rex::rex("'sigma' is an exported object from package 'stats'."),
linter
)

# not just the top level of the function
expect_lint(
trim_some("
foo <- function() {
if (TRUE) {
sigma <- sd(rnorm(100))
} else {
all <- FALSE
}
}
"),
list(
rex::rex("'sigma' is an exported object from package 'stats'."),
rex::rex("'all' is an exported object from package 'base'.")
),
linter
)
})

test_that("object_overwrite_linter skips any name assigned at the top level", {
linter <- object_overwrite_linter()

expect_lint("data <- mtcars", NULL, linter)
expect_lint("sigma <- sd(rnorm(100))", NULL, linter)
})

test_that("object_overwrite_linter skips argument names", {
linter <- object_overwrite_linter()

expect_lint("foo <- function(data) data <- data + 1", NULL, linter)

expect_lint(
trim_some("
bar <- function(a, b, c, sigma) {
sigma <- a * b * c ^ sigma
}
"),
NULL,
linter
)
})

test_that("object_overwrite_linter skips data.table assignments with :=", {
expect_lint("foo <- function() x[, title := 4]", NULL, object_overwrite_linter())
})

test_that("object_overwrite_linter optionally accepts package names", {
expect_lint("function() data <- 1", NULL, object_overwrite_linter(packages = "base"))

expect_lint(
"function() lint <- TRUE",
rex::rex("'lint' is an exported object from package 'lintr'."),
object_overwrite_linter(packages = "lintr")
)
})
Loading