2021-03-12 15:42:43 +00:00
|
|
|
use rustc_errors::Applicability;
|
|
|
|
use rustc_hir::{
|
|
|
|
intravisit::{walk_expr, NestedVisitorMap, Visitor},
|
|
|
|
Expr, ExprKind, Stmt, StmtKind,
|
|
|
|
};
|
|
|
|
use rustc_lint::{LateContext, LateLintPass};
|
|
|
|
use rustc_middle::hir::map::Map;
|
|
|
|
use rustc_session::{declare_lint_pass, declare_tool_lint};
|
|
|
|
use rustc_span::{source_map::Span, sym, Symbol};
|
|
|
|
|
|
|
|
use if_chain::if_chain;
|
|
|
|
|
2021-03-15 03:01:39 +00:00
|
|
|
use clippy_utils::diagnostics::span_lint_and_then;
|
|
|
|
use clippy_utils::is_trait_method;
|
|
|
|
use clippy_utils::source::snippet_with_applicability;
|
|
|
|
use clippy_utils::ty::has_iter_method;
|
2021-03-12 15:42:43 +00:00
|
|
|
|
|
|
|
declare_clippy_lint! {
|
2021-07-02 18:37:11 +00:00
|
|
|
/// ### What it does
|
|
|
|
/// Checks for usage of `for_each` that would be more simply written as a
|
2021-03-12 15:42:43 +00:00
|
|
|
/// `for` loop.
|
|
|
|
///
|
2021-07-02 18:37:11 +00:00
|
|
|
/// ### Why is this bad?
|
|
|
|
/// `for_each` may be used after applying iterator transformers like
|
2021-03-12 15:42:43 +00:00
|
|
|
/// `filter` for better readability and performance. It may also be used to fit a simple
|
|
|
|
/// operation on one line.
|
|
|
|
/// But when none of these apply, a simple `for` loop is more idiomatic.
|
|
|
|
///
|
2021-07-02 18:37:11 +00:00
|
|
|
/// ### Example
|
2021-03-12 15:42:43 +00:00
|
|
|
/// ```rust
|
|
|
|
/// let v = vec![0, 1, 2];
|
|
|
|
/// v.iter().for_each(|elem| {
|
|
|
|
/// println!("{}", elem);
|
|
|
|
/// })
|
|
|
|
/// ```
|
|
|
|
/// Use instead:
|
|
|
|
/// ```rust
|
|
|
|
/// let v = vec![0, 1, 2];
|
|
|
|
/// for elem in v.iter() {
|
|
|
|
/// println!("{}", elem);
|
|
|
|
/// }
|
|
|
|
/// ```
|
Added `clippy::version` attribute to all normal lints
So, some context for this, well, more a story. I'm not used to scripting, I've never really scripted anything, even if it's a valuable skill. I just never really needed it. Now, `@flip1995` correctly suggested using a script for this in `rust-clippy#7813`...
And I decided to write a script using nushell because why not? This was a mistake... I spend way more time on this than I would like to admit. It has definitely been more than 4 hours. It shouldn't take that long, but me being new to scripting and nushell just wasn't a good mixture... Anyway, here is the script that creates another script which adds the versions. Fun...
Just execute this on the `gh-pages` branch and the resulting `replacer.sh` in `clippy_lints` and it should all work.
```nu
mv v0.0.212 rust-1.00.0;
mv beta rust-1.57.0;
mv master rust-1.58.0;
let paths = (open ./rust-1.58.0/lints.json | select id id_span | flatten | select id path);
let versions = (
ls | where name =~ "rust-" | select name | format {name}/lints.json |
each { open $it | select id | insert version $it | str substring "5,11" version} |
group-by id | rotate counter-clockwise id version |
update version {get version | first 1} | flatten | select id version);
$paths | each { |row|
let version = ($versions | where id == ($row.id) | format {version})
let idu = ($row.id | str upcase)
$"sed -i '0,/($idu),/{s/pub ($idu),/#[clippy::version = "($version)"]\n pub ($idu),/}' ($row.path)"
} | str collect ";" | str find-replace --all '1.00.0' 'pre 1.29.0' | save "replacer.sh";
```
And this still has some problems, but at this point I just want to be done -.-
2021-10-21 19:06:26 +00:00
|
|
|
#[clippy::version = "1.53.0"]
|
2021-03-12 15:42:43 +00:00
|
|
|
pub NEEDLESS_FOR_EACH,
|
2021-03-13 06:11:39 +00:00
|
|
|
pedantic,
|
2021-03-12 15:42:43 +00:00
|
|
|
"using `for_each` where a `for` loop would be simpler"
|
|
|
|
}
|
|
|
|
|
|
|
|
declare_lint_pass!(NeedlessForEach => [NEEDLESS_FOR_EACH]);
|
|
|
|
|
2022-01-11 15:52:23 +00:00
|
|
|
impl<'tcx> LateLintPass<'tcx> for NeedlessForEach {
|
2021-03-12 15:42:43 +00:00
|
|
|
fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) {
|
|
|
|
let expr = match stmt.kind {
|
|
|
|
StmtKind::Expr(expr) | StmtKind::Semi(expr) => expr,
|
|
|
|
_ => return,
|
|
|
|
};
|
|
|
|
|
|
|
|
if_chain! {
|
2021-03-13 06:11:39 +00:00
|
|
|
// Check the method name is `for_each`.
|
2021-03-14 01:22:28 +00:00
|
|
|
if let ExprKind::MethodCall(method_name, _, [for_each_recv, for_each_arg], _) = expr.kind;
|
2021-03-13 06:11:39 +00:00
|
|
|
if method_name.ident.name == Symbol::intern("for_each");
|
|
|
|
// Check `for_each` is an associated function of `Iterator`.
|
|
|
|
if is_trait_method(cx, expr, sym::Iterator);
|
|
|
|
// Checks the receiver of `for_each` is also a method call.
|
2021-03-14 01:22:28 +00:00
|
|
|
if let ExprKind::MethodCall(_, _, [iter_recv], _) = for_each_recv.kind;
|
2021-03-13 06:11:39 +00:00
|
|
|
// Skip the lint if the call chain is too long. e.g. `v.field.iter().for_each()` or
|
|
|
|
// `v.foo().iter().for_each()` must be skipped.
|
|
|
|
if matches!(
|
2021-03-14 01:22:28 +00:00
|
|
|
iter_recv.kind,
|
2021-03-13 06:11:39 +00:00
|
|
|
ExprKind::Array(..) | ExprKind::Call(..) | ExprKind::Path(..)
|
|
|
|
);
|
|
|
|
// Checks the type of the `iter` method receiver is NOT a user defined type.
|
2021-04-02 21:35:32 +00:00
|
|
|
if has_iter_method(cx, cx.typeck_results().expr_ty(iter_recv)).is_some();
|
2021-03-12 15:42:43 +00:00
|
|
|
// Skip the lint if the body is not block because this is simpler than `for` loop.
|
|
|
|
// e.g. `v.iter().for_each(f)` is simpler and clearer than using `for` loop.
|
2021-03-14 01:22:28 +00:00
|
|
|
if let ExprKind::Closure(_, _, body_id, ..) = for_each_arg.kind;
|
2021-03-13 06:11:39 +00:00
|
|
|
let body = cx.tcx.hir().body(body_id);
|
2021-03-12 15:42:43 +00:00
|
|
|
if let ExprKind::Block(..) = body.value.kind;
|
|
|
|
then {
|
|
|
|
let mut ret_collector = RetCollector::default();
|
|
|
|
ret_collector.visit_expr(&body.value);
|
|
|
|
|
|
|
|
// Skip the lint if `return` is used in `Loop` in order not to suggest using `'label`.
|
|
|
|
if ret_collector.ret_in_loop {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2021-03-14 01:22:28 +00:00
|
|
|
let (mut applicability, ret_suggs) = if ret_collector.spans.is_empty() {
|
|
|
|
(Applicability::MachineApplicable, None)
|
2021-03-12 15:42:43 +00:00
|
|
|
} else {
|
2021-03-14 01:22:28 +00:00
|
|
|
(
|
|
|
|
Applicability::MaybeIncorrect,
|
|
|
|
Some(
|
|
|
|
ret_collector
|
|
|
|
.spans
|
|
|
|
.into_iter()
|
|
|
|
.map(|span| (span, "continue".to_string()))
|
|
|
|
.collect(),
|
|
|
|
),
|
|
|
|
)
|
2021-03-12 15:42:43 +00:00
|
|
|
};
|
|
|
|
|
2021-03-14 01:22:28 +00:00
|
|
|
let sugg = format!(
|
2021-03-12 15:42:43 +00:00
|
|
|
"for {} in {} {}",
|
|
|
|
snippet_with_applicability(cx, body.params[0].pat.span, "..", &mut applicability),
|
2021-03-14 01:22:28 +00:00
|
|
|
snippet_with_applicability(cx, for_each_recv.span, "..", &mut applicability),
|
2021-03-12 15:42:43 +00:00
|
|
|
snippet_with_applicability(cx, body.value.span, "..", &mut applicability),
|
2021-03-14 01:22:28 +00:00
|
|
|
);
|
2021-03-12 15:42:43 +00:00
|
|
|
|
2021-03-15 03:01:39 +00:00
|
|
|
span_lint_and_then(cx, NEEDLESS_FOR_EACH, stmt.span, "needless use of `for_each`", |diag| {
|
|
|
|
diag.span_suggestion(stmt.span, "try", sugg, applicability);
|
|
|
|
if let Some(ret_suggs) = ret_suggs {
|
|
|
|
diag.multipart_suggestion("...and replace `return` with `continue`", ret_suggs, applicability);
|
2021-03-12 15:42:43 +00:00
|
|
|
}
|
2021-03-15 03:01:39 +00:00
|
|
|
})
|
2021-03-12 15:42:43 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// This type plays two roles.
|
|
|
|
/// 1. Collect spans of `return` in the closure body.
|
|
|
|
/// 2. Detect use of `return` in `Loop` in the closure body.
|
|
|
|
///
|
|
|
|
/// NOTE: The functionality of this type is similar to
|
2021-08-06 02:46:26 +00:00
|
|
|
/// [`clippy_utils::visitors::find_all_ret_expressions`], but we can't use
|
2021-03-12 15:42:43 +00:00
|
|
|
/// `find_all_ret_expressions` instead of this type. The reasons are:
|
|
|
|
/// 1. `find_all_ret_expressions` passes the argument of `ExprKind::Ret` to a callback, but what we
|
|
|
|
/// need here is `ExprKind::Ret` itself.
|
|
|
|
/// 2. We can't trace current loop depth with `find_all_ret_expressions`.
|
|
|
|
#[derive(Default)]
|
|
|
|
struct RetCollector {
|
|
|
|
spans: Vec<Span>,
|
|
|
|
ret_in_loop: bool,
|
|
|
|
loop_depth: u16,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<'tcx> Visitor<'tcx> for RetCollector {
|
|
|
|
type Map = Map<'tcx>;
|
|
|
|
|
|
|
|
fn visit_expr(&mut self, expr: &Expr<'_>) {
|
|
|
|
match expr.kind {
|
|
|
|
ExprKind::Ret(..) => {
|
|
|
|
if self.loop_depth > 0 && !self.ret_in_loop {
|
2021-05-25 02:06:45 +00:00
|
|
|
self.ret_in_loop = true;
|
2021-03-12 15:42:43 +00:00
|
|
|
}
|
|
|
|
|
2021-05-25 00:54:50 +00:00
|
|
|
self.spans.push(expr.span);
|
2021-03-12 15:42:43 +00:00
|
|
|
},
|
|
|
|
|
|
|
|
ExprKind::Loop(..) => {
|
|
|
|
self.loop_depth += 1;
|
|
|
|
walk_expr(self, expr);
|
|
|
|
self.loop_depth -= 1;
|
|
|
|
return;
|
|
|
|
},
|
|
|
|
|
|
|
|
_ => {},
|
|
|
|
}
|
|
|
|
|
|
|
|
walk_expr(self, expr);
|
|
|
|
}
|
|
|
|
|
|
|
|
fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
|
|
|
|
NestedVisitorMap::None
|
|
|
|
}
|
|
|
|
}
|