Block unreachable code and comments following return statements
Source:R/unreachable_code_linter.R
unreachable_code_linter.Rd
Code after e.g. a return()
or stop()
or in deterministically false conditional loops like if (FALSE)
can't be reached;
typically this is vestigial code left after refactoring or sandboxing code, which
is fine for exploration, but shouldn't ultimately be checked in. Comments
meant for posterity should be placed before the final return()
.
See also
linters for a complete list of linters available in lintr.
Examples
# will produce lints
code_lines <- "f <- function() {\n return(1 + 1)\n 2 + 2\n}"
writeLines(code_lines)
#> f <- function() {
#> return(1 + 1)
#> 2 + 2
#> }
lint(
text = code_lines,
linters = unreachable_code_linter()
)
#> ::warning file=<text>,line=3,col=3::file=<text>,line=3,col=3,[unreachable_code_linter] Code and comments coming after a return() or stop() should be removed.
code_lines <- "f <- if (FALSE) {\n 2 + 2\n}"
writeLines(code_lines)
#> f <- if (FALSE) {
#> 2 + 2
#> }
lint(
text = code_lines,
linters = unreachable_code_linter()
)
#> ::warning file=<text>,line=2,col=2::file=<text>,line=2,col=2,[unreachable_code_linter] Code inside a conditional loop with a deterministically false condition should be removed.
code_lines <- "f <- while (FALSE) {\n 2 + 2\n}"
writeLines(code_lines)
#> f <- while (FALSE) {
#> 2 + 2
#> }
lint(
text = code_lines,
linters = unreachable_code_linter()
)
#> ::warning file=<text>,line=2,col=2::file=<text>,line=2,col=2,[unreachable_code_linter] Code inside a conditional loop with a deterministically false condition should be removed.
# okay
code_lines <- "f <- function() {\n return(1 + 1)\n}"
writeLines(code_lines)
#> f <- function() {
#> return(1 + 1)
#> }
lint(
text = code_lines,
linters = unreachable_code_linter()
)
code_lines <- "f <- if (foo) {\n 2 + 2\n}"
writeLines(code_lines)
#> f <- if (foo) {
#> 2 + 2
#> }
lint(
text = code_lines,
linters = unreachable_code_linter()
)
code_lines <- "f <- while (foo) {\n 2 + 2\n}"
writeLines(code_lines)
#> f <- while (foo) {
#> 2 + 2
#> }
lint(
text = code_lines,
linters = unreachable_code_linter()
)