-
Notifications
You must be signed in to change notification settings - Fork 188
Start a fuzzing suite to test for consistency of lints #2818
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
Merged
Merged
Changes from all commits
Commits
Show all changes
34 commits
Select commit
Hold shift + click to select a range
3882350
use maybe_write_content for easier 'mocking'
MichaelChirico c392c53
initial progress
MichaelChirico 5cef281
getting very close i think...
MichaelChirico a4e4a66
skip Rmd files
MichaelChirico 0b1eaf5
caught a live one!
MichaelChirico 868ad30
need to match original file extension?
MichaelChirico 0ed5cc0
caught another one!
MichaelChirico 99d00a3
simpler approach, avoid rex() due to bug
MichaelChirico d3cca7a
also ignore warnings
MichaelChirico 59dc1b0
finally getting somewhere...
MichaelChirico a25065f
progressively more complicated :(
MichaelChirico 491a340
round of fixes & first working nofuzz
MichaelChirico 92f0628
looks like we got another live one... break time
MichaelChirico d387a71
another true positive
MichaelChirico e150ffe
more ignores, need '.' in file extension, restore test
MichaelChirico 3d1fc0e
wrapping up
MichaelChirico b69b7cd
Write up the GHA config
MichaelChirico b8a06e3
annotation
MichaelChirico a3dbf27
comment for future work
MichaelChirico 5a22050
vestigial
MichaelChirico 76b869f
skips on old R
MichaelChirico afec743
expect_no_lint
MichaelChirico 51593e4
new tests
MichaelChirico f4b9481
NEWS
MichaelChirico 6389d55
bad copy-paste
MichaelChirico 1550ead
need stop_on_failure for batch?
MichaelChirico bbdac43
delint, fix last skip for R<4.1.0
MichaelChirico 523c218
more extensible structure
MichaelChirico 7186992
Add a comment
MichaelChirico 89ef5d2
move to end-of-line
MichaelChirico f9e1a9d
Merge branch 'main' into fuzz
MichaelChirico 2f47853
explicit encoding
MichaelChirico aafc693
Merge remote-tracking branch 'origin/fuzz' into fuzz
MichaelChirico 800ba3f
Merge branch 'main' into fuzz
MichaelChirico File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,130 @@ | ||
# Fuzz testing for lint consistency | ||
# | ||
# We have often encountered issues where we handle | ||
# equivalent R constructs inconsistently, e.g., | ||
# function(...) should almost always match the same | ||
# rules as \(...), and '<-' assignment should almost | ||
# always be equivalent to '='. | ||
# | ||
# Here, we seek to enforce that (under eventual consistency) | ||
# by randomly altering the contents of files encountered | ||
# under expect_lint() to swap known equivalencies. | ||
|
||
library(xml2) | ||
|
||
expect_lint_file <- "R/expect_lint.R" | ||
|
||
original <- readLines(expect_lint_file) | ||
expected_line <- "file <- maybe_write_content(file, content)" | ||
expected_line_idx <- grep(expected_line, original, fixed = TRUE) | ||
if (length(expected_line_idx) != 1L) { | ||
stop(sprintf( | ||
"Please update this workflow -- need exactly one hit for line '%s' in file '%s'.", | ||
expected_line, expect_lint_file | ||
)) | ||
} | ||
writeLines( | ||
c( | ||
head(original, expected_line_idx-1L), | ||
# overwrite original exit hook to always delete the fuzzed file | ||
" on.exit({reset_lang(old_lang); unlink(file)})", | ||
" file <- maybe_fuzz_content(file, content)", | ||
tail(original, -expected_line_idx), | ||
readLines(".dev/maybe_fuzz_content.R") | ||
), | ||
expect_lint_file | ||
) | ||
# Not useful in CI but good when running locally. | ||
withr::defer({ | ||
writeLines(original, expect_lint_file) | ||
pkgload::load_all() | ||
}) | ||
|
||
pkgload::load_all() | ||
|
||
# beware lazy eval: originally tried adding a withr::defer() in each iteration, but | ||
# this effectively only runs the last 'defer' expression as the names are only | ||
# evaluated at run-time. So instead keep track of all edits in this object. | ||
# this approach to implementing 'nofuzz' feels painfully manual, but I couldn't | ||
# figure out how else to get 'testthat' to give us what we need -- the failures | ||
# object in the reporter is frustratingly inconsistent in whether the trace | ||
# exists, and even if it does, we'd have to text-mangle to get the corresponding | ||
# file names out. Also, the trace 'srcref' happens under keep.source=FALSE, | ||
# so we lose any associated comments anyway. even that would not solve the issue | ||
# of getting top-level exclusions done for 'nofuzz start|end' ranges, except | ||
# maybe if it enabled us to reuse lintr's own exclude() system. | ||
# therefore we take this approach: pass over the test suite first and comment out | ||
# any tests/units that have been marked 'nofuzz'. restore later. | ||
test_restorations <- list() | ||
for (test_file in list.files("tests/testthat", pattern = "^test-", full.names = TRUE)) { | ||
xml <- read_xml(xmlparsedata::xml_parse_data(parse(test_file, keep.source = TRUE))) | ||
# parent::* to catch top-level comments (exprlist). matches one-line nofuzz and start/end ranges. | ||
nofuzz_lines <- xml_find_all(xml, "//COMMENT[contains(text(), 'nofuzz')]/parent::*") | ||
if (length(nofuzz_lines) == 0L) next | ||
|
||
test_original <- test_lines <- readLines(test_file) | ||
|
||
for (nofuzz_line in nofuzz_lines) { | ||
comments <- xml_find_all(nofuzz_line, "COMMENT[contains(text(), 'nofuzz')]") | ||
comment_text <- xml_text(comments) | ||
# handle start/end ranges first. | ||
start_idx <- grep("nofuzz start", comment_text, fixed = TRUE) | ||
end_idx <- grep("nofuzz end", comment_text, fixed = TRUE) | ||
if (length(start_idx) != length(end_idx) || any(end_idx < start_idx)) { | ||
stop(sprintf( | ||
"Mismatched '# nofuzz start' (%s), '# nofuzz end' (%s) in %s", | ||
toString(start_idx), toString(end_idx), test_file | ||
)) | ||
} | ||
|
||
comment_ranges <- Map(`:`, | ||
as.integer(xml_attr(comments[start_idx], "line1")), | ||
as.integer(xml_attr(comments[end_idx], "line1")) | ||
) | ||
for (comment_range in comment_ranges) { | ||
test_lines[comment_range] <- paste("#", test_lines[comment_range]) | ||
} | ||
|
||
if (length(start_idx) > 0L && !any(!start_idx & !end_idx)) next | ||
|
||
# NB: one-line tests line expect_lint(...) # nofuzz are not supported, | ||
# since the comment will attach to the parent test_that() & thus comment | ||
# out the whole unit. Easiest solution is just to spread out those few tests for now. | ||
comment_range <- as.integer(xml_attr(nofuzz_line, "line1")):as.integer(xml_attr(nofuzz_line, "line2")) | ||
test_lines[comment_range] <- paste("#", test_lines[comment_range]) | ||
} | ||
|
||
writeLines(test_lines, test_file) | ||
test_restorations <- c(test_restorations, list(list(file = test_file, lines = test_original))) | ||
} | ||
withr::defer(for (restoration in test_restorations) writeLines(restoration$lines, restoration$file)) | ||
|
||
# for some reason, 'report <- test_dir(...)' did not work -- the resulting object is ~empty. | ||
# even 'report <- test_local(...)', which does return an object, lacks any information about | ||
# which tests failed (all reports are about successful or skipped tests). probably this is not | ||
# the best approach but documentation was not very helpful. | ||
reporter <- testthat::SummaryReporter$new() | ||
testthat::test_local(reporter = reporter, stop_on_failure = FALSE) | ||
|
||
failures <- reporter$failures$as_list() | ||
# ignore any test that failed for expected reasons, e.g. some known lint metadata changes | ||
# about line numbers or the contents of the line. this saves us having to pepper tons of | ||
# 'nofuzz' comments throughout the suite, as well as getting around the difficulty of injecting | ||
# 'expect_lint()' with new code to ignore these attributes (this latter we might explore later). | ||
valid_failure <- vapply( | ||
failures, | ||
function(failure) { | ||
if (grepl('(column_number|ranges|line) .* did not match', failure$message)) { | ||
return(TRUE) | ||
} | ||
FALSE | ||
}, | ||
logical(1L) | ||
) | ||
if (!all(valid_failure)) { | ||
failures <- failures[!valid_failure] | ||
names(failures) <- vapply(failures, `[[`, "test", FUN.VALUE = character(1L)) | ||
cat("Some fuzzed tests failed unexpectedly!\n") | ||
print(failures) | ||
stop("Use # nofuzz [start|end] to mark false positives or fix any bugs.") | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,62 @@ | ||
maybe_fuzz_content <- function(file, lines) { | ||
if (is.null(file)) { | ||
new_file <- tempfile() | ||
con <- file(new_file, encoding = "UTF-8") | ||
writeLines(lines, con = con, sep = "\n") | ||
close(con) | ||
} else { | ||
new_file <- tempfile(fileext = paste0(".", tools::file_ext(file))) | ||
file.copy(file, new_file, copy.mode = FALSE) | ||
} | ||
|
||
apply_fuzzers(new_file) | ||
|
||
new_file | ||
} | ||
|
||
function_lambda_fuzzer <- function(pd, lines) { | ||
fun_tokens <- c(`'\\\\'` = "\\", `FUNCTION` = "function") | ||
fun_idx <- which(pd$token %in% names(fun_tokens)) | ||
n_fun <- length(fun_idx) | ||
|
||
if (n_fun == 0L) { | ||
return(invisible()) | ||
} | ||
|
||
pd$new_text <- NA_character_ | ||
pd$new_text[fun_idx] <- sample(fun_tokens, n_fun, replace = TRUE) | ||
|
||
for (ii in rev(fun_idx)) { | ||
if (pd$text[ii] == pd$new_text[ii]) next | ||
# Tried, with all rex(), hit a bug: https://github.com/r-lib/rex/issues/96 | ||
ptn = paste0("^(.{", pd$col1[ii] - 1L, "})", rex::rex(pd$text[ii])) | ||
lines[pd$line1[ii]] <- rex::re_substitutes(lines[pd$line1[ii]], ptn, paste0("\\1", rex::rex(pd$new_text[ii]))) | ||
} | ||
lines | ||
} | ||
|
||
# we could also consider just passing any test where no fuzzing takes place, | ||
# i.e. letting the other GHA handle whether unfuzzed tests pass as expected. | ||
apply_fuzzers <- function(f) { | ||
# skip errors for e.g. Rmd files, and ignore warnings. | ||
# We could use get_source_expressions(), but with little benefit & much slower. | ||
pd <- tryCatch(getParseData(suppressWarnings(parse(f, keep.source = TRUE, encoding = "UTF-8"))), error = identity) | ||
if (inherits(pd, "error")) { | ||
return(invisible()) | ||
} | ||
|
||
reparse <- FALSE | ||
lines <- readLines(f) | ||
for (fuzzer in list(function_lambda_fuzzer)) { | ||
if (reparse) { | ||
pd <- getParseData(parse(f, keep.source = TRUE)) | ||
lines <- readLines(f) | ||
} | ||
updated_lines <- fuzzer(pd, lines) | ||
reparse <- !is.null(updated_lines) | ||
if (!reparse) next # skip some I/O if we can | ||
writeLines(updated_lines, f) | ||
} | ||
|
||
invisible() | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
# Randomly change some code & ensure lint equivalency is maintained | ||
on: | ||
push: | ||
branches: [main] | ||
# TODO before merging: remove this. Only kept to demonstrate during review. | ||
pull_request: | ||
branches: [main] | ||
|
||
name: ast-fuzz | ||
|
||
jobs: | ||
repo-meta-tests: | ||
runs-on: ubuntu-latest | ||
env: | ||
GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }} | ||
|
||
steps: | ||
- uses: actions/checkout@v4 | ||
|
||
- uses: r-lib/actions/setup-r@v2 | ||
with: | ||
r-version: "release" | ||
use-public-rspm: true | ||
|
||
- uses: r-lib/actions/setup-r-dependencies@v2 | ||
|
||
- name: Ensure equivalent code generates equivalent lints | ||
run: | | ||
callr::rscript(".dev/ast_fuzz_test.R") | ||
MichaelChirico marked this conversation as resolved.
Show resolved
Hide resolved
|
||
shell: Rscript {0} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.