Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

## Development

### Features

- Add support for `list2df` rule (#179).

### Fixes

- (Hopefully) Fixed wrong printing of ANSI characters in multiple terminals on Windows (#179, thanks @novica for the report).
Expand Down
4 changes: 4 additions & 0 deletions crates/jarl-core/src/analyze/call.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use crate::lints::grepv::grepv::grepv;
use crate::lints::length_levels::length_levels::length_levels;
use crate::lints::length_test::length_test::length_test;
use crate::lints::lengths::lengths::lengths;
use crate::lints::list2df::list2df::list2df;
use crate::lints::matrix_apply::matrix_apply::matrix_apply;
use crate::lints::outer_negation::outer_negation::outer_negation;
use crate::lints::sample_int::sample_int::sample_int;
Expand Down Expand Up @@ -52,6 +53,9 @@ pub fn call(r_expr: &RCall, checker: &mut Checker) -> anyhow::Result<()> {
if checker.is_rule_enabled("lengths") && !checker.should_skip_rule(node, "lengths") {
checker.report_diagnostic(lengths(r_expr)?);
}
if checker.is_rule_enabled("list2df") && !checker.should_skip_rule(node, "list2df") {
checker.report_diagnostic(list2df(r_expr)?);
}
if checker.is_rule_enabled("matrix_apply") && !checker.should_skip_rule(node, "matrix_apply") {
checker.report_diagnostic(matrix_apply(r_expr)?);
}
Expand Down
109 changes: 109 additions & 0 deletions crates/jarl-core/src/lints/list2df/list2df.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
use crate::diagnostic::*;
use crate::utils::{get_arg_by_name_then_position, get_arg_by_position, node_contains_comments};
use air_r_syntax::*;
use biome_rowan::AstNode;

pub struct List2Df;

/// ## What it does
///
/// Checks for usage of `do.call(cbind.data.frame, x)`.
///
/// ## Why is this bad?
///
/// The goal of `do.call(cbind.data.frame, x)` is to concatenate multiple lists
/// elements of the same length into a `data.frame`. Since R 4.0.0, it is
/// possible to do this with `list2DF(x)`, which is more efficient and easier
/// to read than `do.call(cbind.data.frame, x)`.
///
/// This rule comes with a safe fix but is only enabled if the project
/// explicitly uses R >= 4.0.0 (or if the argument `--min-r-version` is passed
/// with a version >= 4.0.0).
///
/// ## Example
///
/// ```r
/// x <- list(a = 1:10, b = 11:20)
/// do.call(cbind.data.frame, x)
/// ```
///
/// Use instead:
/// ```r
/// x <- list(a = 1:10, b = 11:20)
/// list2DF(x)
/// ```
///
/// ## References
///
/// See `?list2DF`
impl Violation for List2Df {
fn name(&self) -> String {
"list2df".to_string()
}
fn body(&self) -> String {
"`do.call(cbind.data.frame, x)` is inefficient and can be hard to read.".to_string()
}
fn suggestion(&self) -> Option<String> {
Some("Use `list2DF(x)` instead.".to_string())
}
}

pub fn list2df(ast: &RCall) -> anyhow::Result<Option<Diagnostic>> {
let RCallFields { function, arguments } = ast.as_fields();

let function = function?;
let arguments = arguments?.items();

if function.to_trimmed_text() != "do.call" {
return Ok(None);
}

let what = get_arg_by_name_then_position(&arguments, "what", 1);
let args = get_arg_by_name_then_position(&arguments, "args", 2);

// Ensure there's not more than two arguments, don't know how to handle
// `quote` and `envir` in `do.call()`.
if get_arg_by_position(&arguments, 3).is_some() {
return Ok(None);
}

if args.is_none() {
return Ok(None);
}

if let Some(what) = what
&& let Some(what_value) = what.value()
{
let txt = what_value.to_trimmed_text();
// `do.call()` accepts quoted function names.
if txt != "cbind.data.frame"
&& txt != "\"cbind.data.frame\""
&& txt != "\'cbind.data.frame\'"
{
return Ok(None);
}
} else {
return Ok(None);
};

// Safety: we checked above that args is not None.
let args = args.unwrap().value();
if args.is_none() {
return Ok(None);
}
let fix_content = args.unwrap();

let range = ast.syntax().text_trimmed_range();
let diagnostic = Diagnostic::new(
List2Df,
range,
Fix {
content: format!("list2DF({})", fix_content.to_trimmed_text()),
start: range.start().into(),
end: range.end().into(),
to_skip: node_contains_comments(ast.syntax()),
},
);

Ok(Some(diagnostic))
}
115 changes: 115 additions & 0 deletions crates/jarl-core/src/lints/list2df/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
pub(crate) mod list2df;

#[cfg(test)]
mod tests {
use crate::utils_test::*;

#[test]
fn test_no_lint_list2df() {
expect_no_lint("cbind.data.frame(x, x)", "list2df", Some("4.0"));
expect_no_lint("do.call(mean, x)", "list2df", Some("4.0"));
expect_no_lint("do.call('c', x)", "list2df", Some("4.0"));
expect_no_lint("do.call(cbind, x)", "list2df", Some("4.0"));
expect_no_lint("do.call(function(x) x, l)", "list2df", Some("4.0"));
// Ignored if R version unknown or below 4.0.0
expect_no_lint("do.call(cbind.data.frame, x)", "list2df", Some("3.5"));
expect_no_lint("do.call(cbind.data.frame, x)", "list2df", None);

// Don't know how to handle additional comments
expect_no_lint(
"do.call(cbind.data.frame, x, quote = TRUE)",
"list2df",
Some("4.0"),
);

// Ensure that wrong calls are not reported
expect_no_lint("do.call(cbind.data.frame)", "list2df", Some("4.0"));
expect_no_lint("do.call(cbind.data.frame, args =)", "list2df", Some("4.0"));
expect_no_lint("do.call(what =, x)", "list2df", Some("4.0"));
}

#[test]
fn test_lint_list2df() {
use insta::assert_snapshot;

let expected_message = "Use `list2DF(x)` instead";
expect_lint(
"do.call(cbind.data.frame, x)",
expected_message,
"list2df",
Some("4.0"),
);
expect_lint(
"do.call(args = x, what = cbind.data.frame)",
expected_message,
"list2df",
Some("4.0"),
);
expect_lint(
"do.call(cbind.data.frame, args = x)",
expected_message,
"list2df",
Some("4.0"),
);
expect_lint(
"do.call(cbind.data.frame, foo(bar(x)))",
expected_message,
"list2df",
Some("4.0"),
);

// Quoted function names
expect_lint(
"do.call('cbind.data.frame', x)",
expected_message,
"list2df",
Some("4.0"),
);
expect_lint(
"do.call(\"cbind.data.frame\", x)",
expected_message,
"list2df",
Some("4.0"),
);

assert_snapshot!(
"fix_output",
get_fixed_text(
vec![
"do.call(cbind.data.frame, x)",
"do.call('cbind.data.frame', x)",
"do.call(\"cbind.data.frame\", x)",
"do.call(args = x, what = cbind.data.frame)",
"do.call(cbind.data.frame, args = x)",
"do.call(cbind.data.frame, foo(bar(x)))",
],
"list2df",
Some("4.0")
)
);
}

#[test]
fn test_list2df_with_comments_no_fix() {
use insta::assert_snapshot;
// Should detect lint but skip fix when comments are present to avoid destroying them
expect_lint(
"do.call(\n # a comment\ncbind.data.frame, x)",
"Use `list2DF(x)` instead",
"list2df",
Some("4.0"),
);
assert_snapshot!(
"no_fix_with_comments",
get_fixed_text(
vec![
"# leading comment\ndo.call(cbind.data.frame, x)",
"do.call(\n # a comment\ncbind.data.frame, x)",
"do.call(cbind.data.frame, x) # trailing comment",
],
"list2df",
Some("4.0")
)
);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
---
source: crates/jarl-core/src/lints/list2df/mod.rs
expression: "get_fixed_text(vec![\"do.call(cbind.data.frame, x)\",\n\"do.call('cbind.data.frame', x)\", \"do.call(\\\"cbind.data.frame\\\", x)\",\n\"do.call(args = x, what = cbind.data.frame)\",\n\"do.call(cbind.data.frame, args = x)\",\n\"do.call(cbind.data.frame, foo(bar(x)))\",], \"list2df\", Some(\"4.0\"))"
---
OLD:
====
do.call(cbind.data.frame, x)
NEW:
====
list2DF(x)

OLD:
====
do.call('cbind.data.frame', x)
NEW:
====
list2DF(x)

OLD:
====
do.call("cbind.data.frame", x)
NEW:
====
list2DF(x)

OLD:
====
do.call(args = x, what = cbind.data.frame)
NEW:
====
list2DF(x)

OLD:
====
do.call(cbind.data.frame, args = x)
NEW:
====
list2DF(x)

OLD:
====
do.call(cbind.data.frame, foo(bar(x)))
NEW:
====
list2DF(foo(bar(x)))
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
---
source: crates/jarl-core/src/lints/list2df/mod.rs
expression: "get_fixed_text(vec![\"# leading comment\\ndo.call(cbind.data.frame, x)\",\n\"do.call(\\n # a comment\\ncbind.data.frame, x)\",\n\"do.call(cbind.data.frame, x) # trailing comment\",], \"list2df\", Some(\"4.0\"))"
---
OLD:
====
# leading comment
do.call(cbind.data.frame, x)
NEW:
====
# leading comment
list2DF(x)

OLD:
====
do.call(
# a comment
cbind.data.frame, x)
NEW:
====
do.call(
# a comment
cbind.data.frame, x)

OLD:
====
do.call(cbind.data.frame, x) # trailing comment
NEW:
====
list2DF(x) # trailing comment
2 changes: 2 additions & 0 deletions crates/jarl-core/src/lints/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ pub(crate) mod is_numeric;
pub(crate) mod length_levels;
pub(crate) mod length_test;
pub(crate) mod lengths;
pub(crate) mod list2df;
pub(crate) mod matrix_apply;
pub(crate) mod numeric_leading_zero;
pub(crate) mod outer_negation;
Expand Down Expand Up @@ -60,6 +61,7 @@ pub fn all_rules_and_safety() -> RuleTable {
rule_table.enable("length_levels", "READ", FixStatus::Safe, None);
rule_table.enable("length_test", "CORR", FixStatus::Safe, None);
rule_table.enable("lengths", "PERF,READ", FixStatus::Safe, None);
rule_table.enable("list2df", "PERF,READ", FixStatus::Safe, Some((4, 0, 0)));
rule_table.enable("matrix_apply", "PERF", FixStatus::Safe, None);
rule_table.enable("numeric_leading_zero", "READ", FixStatus::Safe, None);
rule_table.enable("outer_negation", "PERF,READ", FixStatus::Safe, None);
Expand Down
1 change: 1 addition & 0 deletions docs/_quarto.yml
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ website:
- rules/length_levels.md
- rules/length_test.md
- rules/lengths.md
- rules/list2df.md
- rules/matrix_apply.md
- rules/numeric_leading_zero.md
- rules/outer_negation.md
Expand Down
1 change: 1 addition & 0 deletions docs/rules.qmd
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ dat <- as.data.frame(
c("length_levels", "Readability", "✅", ""),
c("length_test", "Correctness", "✅", ""),
c("lengths", "Performance, readability", "✅", ""),
c("list2df", "Performance, readability", "✅", "R >= 4.0"),
c("matrix_apply", "Performance", "✅", ""),
c("numeric_leading_zero", "Readability", "✅", ""),
c("outer_negation", "Performance, readability", "✅", ""),
Expand Down
32 changes: 32 additions & 0 deletions docs/rules/list2df.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# list2df
## What it does

Checks for usage of `do.call(cbind.data.frame, x)`.

## Why is this bad?

The goal of `do.call(cbind.data.frame, x)` is to concatenate multiple lists
elements of the same length into a `data.frame`. Since R 4.0.0, it is
possible to do this with `list2DF(x)`, which is more efficient and easier
to read than `do.call(cbind.data.frame, x)`.

This rule comes with a safe fix but is only enabled if the project
explicitly uses R >= 4.0.0 (or if the argument `--min-r-version` is passed
with a version >= 4.0.0).

## Example

```r
x <- list(a = 1:10, b = 11:20)
do.call(cbind.data.frame, x)
```

Use instead:
```r
x <- list(a = 1:10, b = 11:20)
list2DF(x)
```

## References

See `?list2DF`