2020-05-17 15:36:26 +00:00
|
|
|
|
use crate::consts::constant;
|
2020-01-10 16:14:17 +00:00
|
|
|
|
use crate::utils::paths;
|
2020-08-11 13:43:21 +00:00
|
|
|
|
use crate::utils::sugg::Sugg;
|
2020-01-10 16:14:17 +00:00
|
|
|
|
use crate::utils::usage::{is_unused, mutated_variables};
|
|
|
|
|
use crate::utils::{
|
2020-10-09 10:45:29 +00:00
|
|
|
|
contains_name, get_enclosing_block, get_parent_expr, get_trait_def_id, has_iter_method, higher, implements_trait,
|
2020-08-11 13:43:21 +00:00
|
|
|
|
is_integer_const, is_no_std_crate, is_refutable, is_type_diagnostic_item, last_path_segment, match_trait_method,
|
2020-10-23 20:16:59 +00:00
|
|
|
|
match_type, match_var, multispan_sugg, qpath_res, snippet, snippet_with_applicability, snippet_with_macro_callsite,
|
|
|
|
|
span_lint, span_lint_and_help, span_lint_and_sugg, span_lint_and_then, sugg, SpanlessEq,
|
2020-01-10 16:14:17 +00:00
|
|
|
|
};
|
2018-07-19 08:00:54 +00:00
|
|
|
|
use if_chain::if_chain;
|
2020-03-01 03:23:33 +00:00
|
|
|
|
use rustc_ast::ast;
|
2020-01-10 16:14:17 +00:00
|
|
|
|
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
|
|
|
|
|
use rustc_errors::Applicability;
|
2020-01-06 16:39:50 +00:00
|
|
|
|
use rustc_hir::def::{DefKind, Res};
|
2020-01-09 07:13:22 +00:00
|
|
|
|
use rustc_hir::intravisit::{walk_block, walk_expr, walk_pat, walk_stmt, NestedVisitorMap, Visitor};
|
2020-02-21 08:39:38 +00:00
|
|
|
|
use rustc_hir::{
|
2020-05-06 14:03:53 +00:00
|
|
|
|
def_id, BinOpKind, BindingAnnotation, Block, BorrowKind, Expr, ExprKind, GenericArg, HirId, InlineAsmOperand,
|
2020-08-11 13:43:21 +00:00
|
|
|
|
Local, LoopSource, MatchSource, Mutability, Node, Pat, PatKind, QPath, Stmt, StmtKind,
|
2020-02-21 08:39:38 +00:00
|
|
|
|
};
|
2020-02-17 02:07:26 +00:00
|
|
|
|
use rustc_infer::infer::TyCtxtInferExt;
|
2020-01-12 06:08:41 +00:00
|
|
|
|
use rustc_lint::{LateContext, LateLintPass, LintContext};
|
2020-03-30 09:02:14 +00:00
|
|
|
|
use rustc_middle::hir::map::Map;
|
|
|
|
|
use rustc_middle::lint::in_external_macro;
|
|
|
|
|
use rustc_middle::middle::region;
|
2020-06-09 14:36:01 +00:00
|
|
|
|
use rustc_middle::ty::{self, Ty, TyS};
|
2020-01-11 11:37:08 +00:00
|
|
|
|
use rustc_session::{declare_lint_pass, declare_tool_lint};
|
2020-01-04 10:00:00 +00:00
|
|
|
|
use rustc_span::source_map::Span;
|
2020-08-11 13:43:21 +00:00
|
|
|
|
use rustc_span::symbol::{sym, Ident, Symbol};
|
2020-06-23 15:05:22 +00:00
|
|
|
|
use rustc_typeck::expr_use_visitor::{ConsumeMode, Delegate, ExprUseVisitor, PlaceBase, PlaceWithHirId};
|
2018-11-27 20:14:15 +00:00
|
|
|
|
use std::iter::{once, Iterator};
|
|
|
|
|
use std::mem;
|
2018-03-07 17:24:36 +00:00
|
|
|
|
|
2018-03-28 13:24:26 +00:00
|
|
|
|
declare_clippy_lint! {
|
2019-03-05 16:50:33 +00:00
|
|
|
|
/// **What it does:** Checks for for-loops that manually copy items between
|
|
|
|
|
/// slices that could be optimized by having a memcpy.
|
|
|
|
|
///
|
|
|
|
|
/// **Why is this bad?** It is not as fast as a memcpy.
|
|
|
|
|
///
|
|
|
|
|
/// **Known problems:** None.
|
|
|
|
|
///
|
|
|
|
|
/// **Example:**
|
2019-08-03 06:01:27 +00:00
|
|
|
|
/// ```rust
|
|
|
|
|
/// # let src = vec![1];
|
|
|
|
|
/// # let mut dst = vec![0; 65];
|
2019-03-05 16:50:33 +00:00
|
|
|
|
/// for i in 0..src.len() {
|
|
|
|
|
/// dst[i + 64] = src[i];
|
|
|
|
|
/// }
|
|
|
|
|
/// ```
|
2019-08-17 13:09:03 +00:00
|
|
|
|
/// Could be written as:
|
|
|
|
|
/// ```rust
|
|
|
|
|
/// # let src = vec![1];
|
|
|
|
|
/// # let mut dst = vec![0; 65];
|
|
|
|
|
/// dst[64..(src.len() + 64)].clone_from_slice(&src[..]);
|
|
|
|
|
/// ```
|
2017-09-05 00:16:34 +00:00
|
|
|
|
pub MANUAL_MEMCPY,
|
2018-03-29 11:41:53 +00:00
|
|
|
|
perf,
|
2017-09-05 00:16:34 +00:00
|
|
|
|
"manually copying items between slices"
|
|
|
|
|
}
|
|
|
|
|
|
2018-03-28 13:24:26 +00:00
|
|
|
|
declare_clippy_lint! {
|
2019-03-05 16:50:33 +00:00
|
|
|
|
/// **What it does:** Checks for looping over the range of `0..len` of some
|
|
|
|
|
/// collection just to get the values by index.
|
|
|
|
|
///
|
|
|
|
|
/// **Why is this bad?** Just iterating the collection itself makes the intent
|
|
|
|
|
/// more clear and is probably faster.
|
|
|
|
|
///
|
|
|
|
|
/// **Known problems:** None.
|
|
|
|
|
///
|
|
|
|
|
/// **Example:**
|
2019-06-02 18:06:50 +00:00
|
|
|
|
/// ```rust
|
|
|
|
|
/// let vec = vec!['a', 'b', 'c'];
|
2019-03-05 16:50:33 +00:00
|
|
|
|
/// for i in 0..vec.len() {
|
|
|
|
|
/// println!("{}", vec[i]);
|
|
|
|
|
/// }
|
|
|
|
|
/// ```
|
2019-06-02 13:28:32 +00:00
|
|
|
|
/// Could be written as:
|
2019-06-02 18:06:50 +00:00
|
|
|
|
/// ```rust
|
|
|
|
|
/// let vec = vec!['a', 'b', 'c'];
|
2019-06-02 13:28:32 +00:00
|
|
|
|
/// for i in vec {
|
|
|
|
|
/// println!("{}", i);
|
|
|
|
|
/// }
|
|
|
|
|
/// ```
|
2016-02-05 23:13:29 +00:00
|
|
|
|
pub NEEDLESS_RANGE_LOOP,
|
2018-03-28 13:24:26 +00:00
|
|
|
|
style,
|
2016-02-05 23:13:29 +00:00
|
|
|
|
"for-looping over a range of indices where an iterator over items would do"
|
|
|
|
|
}
|
2015-08-12 19:56:27 +00:00
|
|
|
|
|
2018-03-28 13:24:26 +00:00
|
|
|
|
declare_clippy_lint! {
|
2019-03-05 16:50:33 +00:00
|
|
|
|
/// **What it does:** Checks for loops on `x.iter()` where `&x` will do, and
|
|
|
|
|
/// suggests the latter.
|
|
|
|
|
///
|
|
|
|
|
/// **Why is this bad?** Readability.
|
|
|
|
|
///
|
|
|
|
|
/// **Known problems:** False negatives. We currently only warn on some known
|
|
|
|
|
/// types.
|
|
|
|
|
///
|
|
|
|
|
/// **Example:**
|
2019-08-03 16:42:05 +00:00
|
|
|
|
/// ```rust
|
2019-03-05 16:50:33 +00:00
|
|
|
|
/// // with `y` a `Vec` or slice:
|
2019-08-03 16:42:05 +00:00
|
|
|
|
/// # let y = vec![1];
|
2019-03-05 16:50:33 +00:00
|
|
|
|
/// for x in y.iter() {
|
2019-08-03 16:42:05 +00:00
|
|
|
|
/// // ..
|
2019-03-05 16:50:33 +00:00
|
|
|
|
/// }
|
|
|
|
|
/// ```
|
|
|
|
|
/// can be rewritten to
|
|
|
|
|
/// ```rust
|
2019-08-03 16:42:05 +00:00
|
|
|
|
/// # let y = vec![1];
|
2019-03-05 16:50:33 +00:00
|
|
|
|
/// for x in &y {
|
2019-08-03 16:42:05 +00:00
|
|
|
|
/// // ..
|
2019-03-05 16:50:33 +00:00
|
|
|
|
/// }
|
|
|
|
|
/// ```
|
2016-02-05 23:13:29 +00:00
|
|
|
|
pub EXPLICIT_ITER_LOOP,
|
2018-09-03 07:19:59 +00:00
|
|
|
|
pedantic,
|
2016-02-05 23:13:29 +00:00
|
|
|
|
"for-looping over `_.iter()` or `_.iter_mut()` when `&_` or `&mut _` would do"
|
|
|
|
|
}
|
2015-08-13 13:36:31 +00:00
|
|
|
|
|
2018-03-28 13:24:26 +00:00
|
|
|
|
declare_clippy_lint! {
|
2019-03-05 16:50:33 +00:00
|
|
|
|
/// **What it does:** Checks for loops on `y.into_iter()` where `y` will do, and
|
|
|
|
|
/// suggests the latter.
|
|
|
|
|
///
|
|
|
|
|
/// **Why is this bad?** Readability.
|
|
|
|
|
///
|
|
|
|
|
/// **Known problems:** None
|
|
|
|
|
///
|
|
|
|
|
/// **Example:**
|
2019-08-03 16:42:05 +00:00
|
|
|
|
/// ```rust
|
|
|
|
|
/// # let y = vec![1];
|
2019-03-05 16:50:33 +00:00
|
|
|
|
/// // with `y` a `Vec` or slice:
|
|
|
|
|
/// for x in y.into_iter() {
|
2019-08-03 16:42:05 +00:00
|
|
|
|
/// // ..
|
2019-03-05 16:50:33 +00:00
|
|
|
|
/// }
|
|
|
|
|
/// ```
|
|
|
|
|
/// can be rewritten to
|
2019-08-03 16:42:05 +00:00
|
|
|
|
/// ```rust
|
|
|
|
|
/// # let y = vec![1];
|
2019-03-05 16:50:33 +00:00
|
|
|
|
/// for x in y {
|
2019-08-03 16:42:05 +00:00
|
|
|
|
/// // ..
|
2019-03-05 16:50:33 +00:00
|
|
|
|
/// }
|
|
|
|
|
/// ```
|
2016-10-01 00:01:30 +00:00
|
|
|
|
pub EXPLICIT_INTO_ITER_LOOP,
|
2018-09-03 07:19:59 +00:00
|
|
|
|
pedantic,
|
2016-10-01 00:01:30 +00:00
|
|
|
|
"for-looping over `_.into_iter()` when `_` would do"
|
|
|
|
|
}
|
|
|
|
|
|
2018-03-28 13:24:26 +00:00
|
|
|
|
declare_clippy_lint! {
|
2019-03-05 16:50:33 +00:00
|
|
|
|
/// **What it does:** Checks for loops on `x.next()`.
|
|
|
|
|
///
|
|
|
|
|
/// **Why is this bad?** `next()` returns either `Some(value)` if there was a
|
|
|
|
|
/// value, or `None` otherwise. The insidious thing is that `Option<_>`
|
|
|
|
|
/// implements `IntoIterator`, so that possibly one value will be iterated,
|
|
|
|
|
/// leading to some hard to find bugs. No one will want to write such code
|
|
|
|
|
/// [except to win an Underhanded Rust
|
|
|
|
|
/// Contest](https://www.reddit.com/r/rust/comments/3hb0wm/underhanded_rust_contest/cu5yuhr).
|
|
|
|
|
///
|
|
|
|
|
/// **Known problems:** None.
|
|
|
|
|
///
|
|
|
|
|
/// **Example:**
|
2019-03-05 22:23:50 +00:00
|
|
|
|
/// ```ignore
|
2019-03-05 16:50:33 +00:00
|
|
|
|
/// for x in y.next() {
|
|
|
|
|
/// ..
|
|
|
|
|
/// }
|
|
|
|
|
/// ```
|
2016-02-05 23:13:29 +00:00
|
|
|
|
pub ITER_NEXT_LOOP,
|
2018-03-29 11:41:53 +00:00
|
|
|
|
correctness,
|
2016-02-05 23:13:29 +00:00
|
|
|
|
"for-looping over `_.next()` which is probably not intended"
|
|
|
|
|
}
|
2015-08-17 05:23:57 +00:00
|
|
|
|
|
2018-03-28 13:24:26 +00:00
|
|
|
|
declare_clippy_lint! {
|
2020-05-17 15:36:26 +00:00
|
|
|
|
/// **What it does:** Checks for `for` loops over `Option` or `Result` values.
|
2019-03-05 16:50:33 +00:00
|
|
|
|
///
|
|
|
|
|
/// **Why is this bad?** Readability. This is more clearly expressed as an `if
|
|
|
|
|
/// let`.
|
|
|
|
|
///
|
|
|
|
|
/// **Known problems:** None.
|
|
|
|
|
///
|
|
|
|
|
/// **Example:**
|
2020-05-17 15:36:26 +00:00
|
|
|
|
/// ```rust
|
|
|
|
|
/// # let opt = Some(1);
|
|
|
|
|
///
|
|
|
|
|
/// // Bad
|
|
|
|
|
/// for x in opt {
|
|
|
|
|
/// // ..
|
2019-03-05 16:50:33 +00:00
|
|
|
|
/// }
|
|
|
|
|
///
|
2020-05-17 15:36:26 +00:00
|
|
|
|
/// // Good
|
|
|
|
|
/// if let Some(x) = opt {
|
|
|
|
|
/// // ..
|
2019-03-05 16:50:33 +00:00
|
|
|
|
/// }
|
|
|
|
|
/// ```
|
|
|
|
|
///
|
2020-05-17 15:36:26 +00:00
|
|
|
|
/// // or
|
2019-03-05 16:50:33 +00:00
|
|
|
|
///
|
2020-05-17 15:36:26 +00:00
|
|
|
|
/// ```rust
|
|
|
|
|
/// # let res: Result<i32, std::io::Error> = Ok(1);
|
2019-03-05 16:50:33 +00:00
|
|
|
|
///
|
2020-05-17 15:36:26 +00:00
|
|
|
|
/// // Bad
|
|
|
|
|
/// for x in &res {
|
|
|
|
|
/// // ..
|
2019-03-05 16:50:33 +00:00
|
|
|
|
/// }
|
|
|
|
|
///
|
2020-05-17 15:36:26 +00:00
|
|
|
|
/// // Good
|
|
|
|
|
/// if let Ok(x) = res {
|
|
|
|
|
/// // ..
|
2019-03-05 16:50:33 +00:00
|
|
|
|
/// }
|
|
|
|
|
/// ```
|
2020-05-17 15:36:26 +00:00
|
|
|
|
pub FOR_LOOPS_OVER_FALLIBLES,
|
2018-03-29 11:41:53 +00:00
|
|
|
|
correctness,
|
2020-05-17 15:36:26 +00:00
|
|
|
|
"for-looping over an `Option` or a `Result`, which is more clearly expressed as an `if let`"
|
2016-02-05 23:13:29 +00:00
|
|
|
|
}
|
2016-01-29 07:34:09 +00:00
|
|
|
|
|
2018-03-28 13:24:26 +00:00
|
|
|
|
declare_clippy_lint! {
|
2019-03-05 16:50:33 +00:00
|
|
|
|
/// **What it does:** Detects `loop + match` combinations that are easier
|
|
|
|
|
/// written as a `while let` loop.
|
|
|
|
|
///
|
|
|
|
|
/// **Why is this bad?** The `while let` loop is usually shorter and more
|
|
|
|
|
/// readable.
|
|
|
|
|
///
|
|
|
|
|
/// **Known problems:** Sometimes the wrong binding is displayed (#383).
|
|
|
|
|
///
|
|
|
|
|
/// **Example:**
|
2019-08-02 06:13:54 +00:00
|
|
|
|
/// ```rust,no_run
|
|
|
|
|
/// # let y = Some(1);
|
2019-03-05 16:50:33 +00:00
|
|
|
|
/// loop {
|
|
|
|
|
/// let x = match y {
|
|
|
|
|
/// Some(x) => x,
|
|
|
|
|
/// None => break,
|
2019-08-02 06:13:54 +00:00
|
|
|
|
/// };
|
2019-03-05 16:50:33 +00:00
|
|
|
|
/// // .. do something with x
|
|
|
|
|
/// }
|
|
|
|
|
/// // is easier written as
|
|
|
|
|
/// while let Some(x) = y {
|
|
|
|
|
/// // .. do something with x
|
2019-08-02 06:13:54 +00:00
|
|
|
|
/// };
|
2019-03-05 16:50:33 +00:00
|
|
|
|
/// ```
|
2016-02-05 23:13:29 +00:00
|
|
|
|
pub WHILE_LET_LOOP,
|
2018-03-29 11:41:53 +00:00
|
|
|
|
complexity,
|
2016-08-06 08:18:36 +00:00
|
|
|
|
"`loop { if let { ... } else break }`, which can be written as a `while let` loop"
|
2016-02-05 23:13:29 +00:00
|
|
|
|
}
|
2015-08-29 09:41:06 +00:00
|
|
|
|
|
2018-08-30 03:01:24 +00:00
|
|
|
|
declare_clippy_lint! {
|
2019-03-05 16:50:33 +00:00
|
|
|
|
/// **What it does:** Checks for functions collecting an iterator when collect
|
|
|
|
|
/// is not needed.
|
|
|
|
|
///
|
|
|
|
|
/// **Why is this bad?** `collect` causes the allocation of a new data structure,
|
|
|
|
|
/// when this allocation may not be needed.
|
|
|
|
|
///
|
|
|
|
|
/// **Known problems:**
|
|
|
|
|
/// None
|
|
|
|
|
///
|
|
|
|
|
/// **Example:**
|
2019-08-03 06:01:27 +00:00
|
|
|
|
/// ```rust
|
|
|
|
|
/// # let iterator = vec![1].into_iter();
|
|
|
|
|
/// let len = iterator.clone().collect::<Vec<_>>().len();
|
2019-03-05 16:50:33 +00:00
|
|
|
|
/// // should be
|
|
|
|
|
/// let len = iterator.count();
|
|
|
|
|
/// ```
|
2018-08-30 03:01:24 +00:00
|
|
|
|
pub NEEDLESS_COLLECT,
|
|
|
|
|
perf,
|
|
|
|
|
"collecting an iterator when collect is not needed"
|
|
|
|
|
}
|
|
|
|
|
|
2018-03-28 13:24:26 +00:00
|
|
|
|
declare_clippy_lint! {
|
2019-03-05 16:50:33 +00:00
|
|
|
|
/// **What it does:** Checks `for` loops over slices with an explicit counter
|
|
|
|
|
/// and suggests the use of `.enumerate()`.
|
|
|
|
|
///
|
2019-09-01 17:59:14 +00:00
|
|
|
|
/// **Why is it bad?** Using `.enumerate()` makes the intent more clear,
|
|
|
|
|
/// declutters the code and may be faster in some instances.
|
2019-03-05 16:50:33 +00:00
|
|
|
|
///
|
|
|
|
|
/// **Known problems:** None.
|
|
|
|
|
///
|
|
|
|
|
/// **Example:**
|
2019-08-02 06:13:54 +00:00
|
|
|
|
/// ```rust
|
|
|
|
|
/// # let v = vec![1];
|
|
|
|
|
/// # fn bar(bar: usize, baz: usize) {}
|
2019-09-01 17:59:14 +00:00
|
|
|
|
/// let mut i = 0;
|
|
|
|
|
/// for item in &v {
|
|
|
|
|
/// bar(i, *item);
|
|
|
|
|
/// i += 1;
|
|
|
|
|
/// }
|
2019-03-05 16:50:33 +00:00
|
|
|
|
/// ```
|
2019-08-20 14:55:17 +00:00
|
|
|
|
/// Could be written as
|
|
|
|
|
/// ```rust
|
|
|
|
|
/// # let v = vec![1];
|
|
|
|
|
/// # fn bar(bar: usize, baz: usize) {}
|
|
|
|
|
/// for (i, item) in v.iter().enumerate() { bar(i, *item); }
|
|
|
|
|
/// ```
|
2016-02-05 23:13:29 +00:00
|
|
|
|
pub EXPLICIT_COUNTER_LOOP,
|
2018-03-29 11:41:53 +00:00
|
|
|
|
complexity,
|
2016-02-05 23:13:29 +00:00
|
|
|
|
"for-looping with an explicit counter when `_.enumerate()` would do"
|
|
|
|
|
}
|
2015-08-23 17:25:45 +00:00
|
|
|
|
|
2018-03-28 13:24:26 +00:00
|
|
|
|
declare_clippy_lint! {
|
2019-03-05 16:50:33 +00:00
|
|
|
|
/// **What it does:** Checks for empty `loop` expressions.
|
|
|
|
|
///
|
|
|
|
|
/// **Why is this bad?** Those busy loops burn CPU cycles without doing
|
|
|
|
|
/// anything. Think of the environment and either block on something or at least
|
|
|
|
|
/// make the thread sleep for some microseconds.
|
|
|
|
|
///
|
|
|
|
|
/// **Known problems:** None.
|
|
|
|
|
///
|
|
|
|
|
/// **Example:**
|
2019-03-05 22:23:50 +00:00
|
|
|
|
/// ```no_run
|
2019-03-05 16:50:33 +00:00
|
|
|
|
/// loop {}
|
|
|
|
|
/// ```
|
2016-02-05 23:13:29 +00:00
|
|
|
|
pub EMPTY_LOOP,
|
2018-03-28 13:24:26 +00:00
|
|
|
|
style,
|
2016-08-06 08:18:36 +00:00
|
|
|
|
"empty `loop {}`, which should block or sleep"
|
2016-02-05 23:13:29 +00:00
|
|
|
|
}
|
2015-10-12 11:38:18 +00:00
|
|
|
|
|
2018-03-28 13:24:26 +00:00
|
|
|
|
declare_clippy_lint! {
|
2019-03-05 16:50:33 +00:00
|
|
|
|
/// **What it does:** Checks for `while let` expressions on iterators.
|
|
|
|
|
///
|
|
|
|
|
/// **Why is this bad?** Readability. A simple `for` loop is shorter and conveys
|
|
|
|
|
/// the intent better.
|
|
|
|
|
///
|
|
|
|
|
/// **Known problems:** None.
|
|
|
|
|
///
|
|
|
|
|
/// **Example:**
|
2019-03-05 22:23:50 +00:00
|
|
|
|
/// ```ignore
|
2019-03-05 16:50:33 +00:00
|
|
|
|
/// while let Some(val) = iter() {
|
|
|
|
|
/// ..
|
|
|
|
|
/// }
|
|
|
|
|
/// ```
|
2016-02-05 23:13:29 +00:00
|
|
|
|
pub WHILE_LET_ON_ITERATOR,
|
2018-03-28 13:24:26 +00:00
|
|
|
|
style,
|
2016-02-05 23:13:29 +00:00
|
|
|
|
"using a while-let loop instead of a for loop on an iterator"
|
|
|
|
|
}
|
2015-10-16 18:27:13 +00:00
|
|
|
|
|
2018-03-28 13:24:26 +00:00
|
|
|
|
declare_clippy_lint! {
|
2019-03-05 16:50:33 +00:00
|
|
|
|
/// **What it does:** Checks for iterating a map (`HashMap` or `BTreeMap`) and
|
|
|
|
|
/// ignoring either the keys or values.
|
|
|
|
|
///
|
|
|
|
|
/// **Why is this bad?** Readability. There are `keys` and `values` methods that
|
|
|
|
|
/// can be used to express that don't need the values or keys.
|
|
|
|
|
///
|
|
|
|
|
/// **Known problems:** None.
|
|
|
|
|
///
|
|
|
|
|
/// **Example:**
|
2019-03-05 22:23:50 +00:00
|
|
|
|
/// ```ignore
|
2019-03-05 16:50:33 +00:00
|
|
|
|
/// for (k, _) in &map {
|
|
|
|
|
/// ..
|
|
|
|
|
/// }
|
|
|
|
|
/// ```
|
|
|
|
|
///
|
|
|
|
|
/// could be replaced by
|
|
|
|
|
///
|
2019-03-05 22:23:50 +00:00
|
|
|
|
/// ```ignore
|
2019-03-05 16:50:33 +00:00
|
|
|
|
/// for k in map.keys() {
|
|
|
|
|
/// ..
|
|
|
|
|
/// }
|
|
|
|
|
/// ```
|
2016-02-05 23:13:29 +00:00
|
|
|
|
pub FOR_KV_MAP,
|
2018-03-28 13:24:26 +00:00
|
|
|
|
style,
|
2016-02-05 23:13:29 +00:00
|
|
|
|
"looping on a map using `iter` when `keys` or `values` would do"
|
|
|
|
|
}
|
2016-01-19 20:10:00 +00:00
|
|
|
|
|
2018-03-28 13:24:26 +00:00
|
|
|
|
declare_clippy_lint! {
|
2019-03-05 16:50:33 +00:00
|
|
|
|
/// **What it does:** Checks for loops that will always `break`, `return` or
|
|
|
|
|
/// `continue` an outer loop.
|
|
|
|
|
///
|
|
|
|
|
/// **Why is this bad?** This loop never loops, all it does is obfuscating the
|
|
|
|
|
/// code.
|
|
|
|
|
///
|
|
|
|
|
/// **Known problems:** None
|
|
|
|
|
///
|
|
|
|
|
/// **Example:**
|
|
|
|
|
/// ```rust
|
|
|
|
|
/// loop {
|
|
|
|
|
/// ..;
|
|
|
|
|
/// break;
|
|
|
|
|
/// }
|
|
|
|
|
/// ```
|
2017-02-17 03:53:14 +00:00
|
|
|
|
pub NEVER_LOOP,
|
2018-03-29 11:41:53 +00:00
|
|
|
|
correctness,
|
2017-05-31 01:44:01 +00:00
|
|
|
|
"any loop that will always `break` or `return`"
|
2017-02-17 03:53:14 +00:00
|
|
|
|
}
|
|
|
|
|
|
2018-03-28 13:24:26 +00:00
|
|
|
|
declare_clippy_lint! {
|
2019-03-05 16:50:33 +00:00
|
|
|
|
/// **What it does:** Checks for loops which have a range bound that is a mutable variable
|
|
|
|
|
///
|
|
|
|
|
/// **Why is this bad?** One might think that modifying the mutable variable changes the loop bounds
|
|
|
|
|
///
|
|
|
|
|
/// **Known problems:** None
|
|
|
|
|
///
|
|
|
|
|
/// **Example:**
|
|
|
|
|
/// ```rust
|
|
|
|
|
/// let mut foo = 42;
|
|
|
|
|
/// for i in 0..foo {
|
|
|
|
|
/// foo -= 1;
|
|
|
|
|
/// println!("{}", i); // prints numbers from 0 to 42, not 0 to 21
|
|
|
|
|
/// }
|
|
|
|
|
/// ```
|
2017-08-10 23:21:43 +00:00
|
|
|
|
pub MUT_RANGE_BOUND,
|
2018-03-28 13:24:26 +00:00
|
|
|
|
complexity,
|
2017-08-10 23:21:43 +00:00
|
|
|
|
"for loop over a range where one of the bounds is a mutable variable"
|
|
|
|
|
}
|
|
|
|
|
|
2018-03-28 13:24:26 +00:00
|
|
|
|
declare_clippy_lint! {
|
2019-03-05 16:50:33 +00:00
|
|
|
|
/// **What it does:** Checks whether variables used within while loop condition
|
|
|
|
|
/// can be (and are) mutated in the body.
|
|
|
|
|
///
|
|
|
|
|
/// **Why is this bad?** If the condition is unchanged, entering the body of the loop
|
|
|
|
|
/// will lead to an infinite loop.
|
|
|
|
|
///
|
|
|
|
|
/// **Known problems:** If the `while`-loop is in a closure, the check for mutation of the
|
|
|
|
|
/// condition variables in the body can cause false negatives. For example when only `Upvar` `a` is
|
|
|
|
|
/// in the condition and only `Upvar` `b` gets mutated in the body, the lint will not trigger.
|
|
|
|
|
///
|
|
|
|
|
/// **Example:**
|
|
|
|
|
/// ```rust
|
|
|
|
|
/// let i = 0;
|
|
|
|
|
/// while i > 10 {
|
|
|
|
|
/// println!("let me loop forever!");
|
|
|
|
|
/// }
|
|
|
|
|
/// ```
|
2018-02-25 17:25:31 +00:00
|
|
|
|
pub WHILE_IMMUTABLE_CONDITION,
|
2018-03-28 13:24:26 +00:00
|
|
|
|
correctness,
|
2018-02-25 17:25:31 +00:00
|
|
|
|
"variables used within while expression are not mutated in the body"
|
|
|
|
|
}
|
|
|
|
|
|
2020-08-11 13:43:21 +00:00
|
|
|
|
declare_clippy_lint! {
|
|
|
|
|
/// **What it does:** Checks whether a for loop is being used to push a constant
|
|
|
|
|
/// value into a Vec.
|
|
|
|
|
///
|
|
|
|
|
/// **Why is this bad?** This kind of operation can be expressed more succinctly with
|
|
|
|
|
/// `vec![item;SIZE]` or `vec.resize(NEW_SIZE, item)` and using these alternatives may also
|
|
|
|
|
/// have better performance.
|
|
|
|
|
/// **Known problems:** None
|
|
|
|
|
///
|
|
|
|
|
/// **Example:**
|
|
|
|
|
/// ```rust
|
|
|
|
|
/// let item1 = 2;
|
|
|
|
|
/// let item2 = 3;
|
|
|
|
|
/// let mut vec: Vec<u8> = Vec::new();
|
|
|
|
|
/// for _ in 0..20 {
|
|
|
|
|
/// vec.push(item1);
|
|
|
|
|
/// }
|
|
|
|
|
/// for _ in 0..30 {
|
|
|
|
|
/// vec.push(item2);
|
|
|
|
|
/// }
|
|
|
|
|
/// ```
|
|
|
|
|
/// could be written as
|
|
|
|
|
/// ```rust
|
|
|
|
|
/// let item1 = 2;
|
|
|
|
|
/// let item2 = 3;
|
|
|
|
|
/// let mut vec: Vec<u8> = vec![item1; 20];
|
|
|
|
|
/// vec.resize(20 + 30, item2);
|
|
|
|
|
/// ```
|
|
|
|
|
pub SAME_ITEM_PUSH,
|
|
|
|
|
style,
|
|
|
|
|
"the same item is pushed inside of a for loop"
|
|
|
|
|
}
|
|
|
|
|
|
2019-04-08 20:43:55 +00:00
|
|
|
|
declare_lint_pass!(Loops => [
|
|
|
|
|
MANUAL_MEMCPY,
|
|
|
|
|
NEEDLESS_RANGE_LOOP,
|
|
|
|
|
EXPLICIT_ITER_LOOP,
|
|
|
|
|
EXPLICIT_INTO_ITER_LOOP,
|
|
|
|
|
ITER_NEXT_LOOP,
|
2020-05-17 15:36:26 +00:00
|
|
|
|
FOR_LOOPS_OVER_FALLIBLES,
|
2019-04-08 20:43:55 +00:00
|
|
|
|
WHILE_LET_LOOP,
|
|
|
|
|
NEEDLESS_COLLECT,
|
|
|
|
|
EXPLICIT_COUNTER_LOOP,
|
|
|
|
|
EMPTY_LOOP,
|
|
|
|
|
WHILE_LET_ON_ITERATOR,
|
|
|
|
|
FOR_KV_MAP,
|
|
|
|
|
NEVER_LOOP,
|
|
|
|
|
MUT_RANGE_BOUND,
|
|
|
|
|
WHILE_IMMUTABLE_CONDITION,
|
2020-08-11 13:43:21 +00:00
|
|
|
|
SAME_ITEM_PUSH,
|
2019-04-08 20:43:55 +00:00
|
|
|
|
]);
|
2015-08-12 19:56:27 +00:00
|
|
|
|
|
2020-06-25 20:41:36 +00:00
|
|
|
|
impl<'tcx> LateLintPass<'tcx> for Loops {
|
2019-01-13 15:19:02 +00:00
|
|
|
|
#[allow(clippy::too_many_lines)]
|
2020-06-25 20:41:36 +00:00
|
|
|
|
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
|
2019-10-01 17:14:15 +00:00
|
|
|
|
if let Some((pat, arg, body)) = higher::for_loop(expr) {
|
|
|
|
|
// we don't want to check expanded macros
|
|
|
|
|
// this check is not at the top of the function
|
|
|
|
|
// since higher::for_loop expressions are marked as expansions
|
|
|
|
|
if body.span.from_expansion() {
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
check_for_loop(cx, pat, arg, body, expr);
|
|
|
|
|
}
|
|
|
|
|
|
2018-12-24 21:06:08 +00:00
|
|
|
|
// we don't want to check expanded macros
|
2019-08-19 16:30:32 +00:00
|
|
|
|
if expr.span.from_expansion() {
|
2018-12-24 21:06:08 +00:00
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2017-06-01 04:22:15 +00:00
|
|
|
|
// check for never_loop
|
2019-09-27 15:16:06 +00:00
|
|
|
|
if let ExprKind::Loop(ref block, _, _) = expr.kind {
|
2019-07-06 17:06:49 +00:00
|
|
|
|
match never_loop_block(block, expr.hir_id) {
|
2019-07-06 17:43:34 +00:00
|
|
|
|
NeverLoopResult::AlwaysBreak => span_lint(cx, NEVER_LOOP, expr.span, "this loop never actually loops"),
|
2019-07-06 17:06:49 +00:00
|
|
|
|
NeverLoopResult::MayContinueMainLoop | NeverLoopResult::Otherwise => (),
|
|
|
|
|
}
|
2019-07-06 17:35:08 +00:00
|
|
|
|
}
|
2017-06-01 04:22:15 +00:00
|
|
|
|
|
2015-08-29 09:41:06 +00:00
|
|
|
|
// check for `loop { if let {} else break }` that could be `while let`
|
2015-09-27 07:39:42 +00:00
|
|
|
|
// (also matches an explicit "match" instead of "if let")
|
|
|
|
|
// (even if the "match" or "if let" is used for declaration)
|
2019-09-27 15:16:06 +00:00
|
|
|
|
if let ExprKind::Loop(ref block, _, LoopSource::Loop) = expr.kind {
|
2015-10-12 11:38:18 +00:00
|
|
|
|
// also check for empty `loop {}` statements
|
2020-01-24 10:50:03 +00:00
|
|
|
|
if block.stmts.is_empty() && block.expr.is_none() && !is_no_std_crate(cx.tcx.hir().krate()) {
|
2017-08-09 07:30:56 +00:00
|
|
|
|
span_lint(
|
|
|
|
|
cx,
|
|
|
|
|
EMPTY_LOOP,
|
|
|
|
|
expr.span,
|
|
|
|
|
"empty `loop {}` detected. You may want to either use `panic!()` or add \
|
2017-09-05 09:33:04 +00:00
|
|
|
|
`std::thread::sleep(..);` to the loop body.",
|
2017-08-09 07:30:56 +00:00
|
|
|
|
);
|
2015-10-12 11:38:18 +00:00
|
|
|
|
}
|
2015-10-14 09:44:09 +00:00
|
|
|
|
|
2015-10-11 16:49:01 +00:00
|
|
|
|
// extract the expression from the first statement (if any) in a block
|
|
|
|
|
let inner_stmt_expr = extract_expr_from_first_stmt(block);
|
2015-12-14 13:30:09 +00:00
|
|
|
|
// or extract the first expression (if any) from the block
|
|
|
|
|
if let Some(inner) = inner_stmt_expr.or_else(|| extract_first_expr(block)) {
|
2019-09-27 15:16:06 +00:00
|
|
|
|
if let ExprKind::Match(ref matchexpr, ref arms, ref source) = inner.kind {
|
2015-08-29 09:41:06 +00:00
|
|
|
|
// ensure "if let" compatible match structure
|
|
|
|
|
match *source {
|
2017-11-04 19:55:56 +00:00
|
|
|
|
MatchSource::Normal | MatchSource::IfLetDesugar { .. } => {
|
2018-11-27 20:14:15 +00:00
|
|
|
|
if arms.len() == 2
|
|
|
|
|
&& arms[0].guard.is_none()
|
|
|
|
|
&& arms[1].guard.is_none()
|
2017-11-04 19:55:56 +00:00
|
|
|
|
&& is_simple_break_expr(&arms[1].body)
|
2017-08-09 07:30:56 +00:00
|
|
|
|
{
|
2018-07-24 06:55:38 +00:00
|
|
|
|
if in_external_macro(cx.sess(), expr.span) {
|
2016-01-04 04:26:12 +00:00
|
|
|
|
return;
|
|
|
|
|
}
|
2016-02-27 21:59:15 +00:00
|
|
|
|
|
2019-04-16 18:05:16 +00:00
|
|
|
|
// NOTE: we used to build a body here instead of using
|
2016-02-27 21:59:15 +00:00
|
|
|
|
// ellipsis, this was removed because:
|
|
|
|
|
// 1) it was ugly with big bodies;
|
|
|
|
|
// 2) it was not indented properly;
|
|
|
|
|
// 3) it wasn’t very smart (see #675).
|
2019-04-16 18:05:16 +00:00
|
|
|
|
let mut applicability = Applicability::HasPlaceholders;
|
2017-08-09 07:30:56 +00:00
|
|
|
|
span_lint_and_sugg(
|
|
|
|
|
cx,
|
|
|
|
|
WHILE_LET_LOOP,
|
|
|
|
|
expr.span,
|
|
|
|
|
"this loop could be written as a `while let` loop",
|
|
|
|
|
"try",
|
|
|
|
|
format!(
|
|
|
|
|
"while let {} = {} {{ .. }}",
|
2019-09-25 19:00:17 +00:00
|
|
|
|
snippet_with_applicability(cx, arms[0].pat.span, "..", &mut applicability),
|
2018-11-27 14:13:57 +00:00
|
|
|
|
snippet_with_applicability(cx, matchexpr.span, "..", &mut applicability),
|
2017-08-09 07:30:56 +00:00
|
|
|
|
),
|
2018-11-27 14:13:57 +00:00
|
|
|
|
applicability,
|
2017-08-09 07:30:56 +00:00
|
|
|
|
);
|
2016-01-04 04:26:12 +00:00
|
|
|
|
}
|
2016-12-20 17:21:30 +00:00
|
|
|
|
},
|
2016-01-04 04:26:12 +00:00
|
|
|
|
_ => (),
|
2015-08-29 09:41:06 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
2019-09-27 15:16:06 +00:00
|
|
|
|
if let ExprKind::Match(ref match_expr, ref arms, MatchSource::WhileLetDesugar) = expr.kind {
|
|
|
|
|
let pat = &arms[0].pat.kind;
|
2017-11-04 19:55:56 +00:00
|
|
|
|
if let (
|
|
|
|
|
&PatKind::TupleStruct(ref qpath, ref pat_args, _),
|
2020-06-09 21:44:04 +00:00
|
|
|
|
&ExprKind::MethodCall(ref method_path, _, ref method_args, _),
|
2019-09-27 15:16:06 +00:00
|
|
|
|
) = (pat, &match_expr.kind)
|
2017-08-09 07:30:56 +00:00
|
|
|
|
{
|
2015-10-26 22:49:37 +00:00
|
|
|
|
let iter_expr = &method_args[0];
|
2020-04-25 18:51:02 +00:00
|
|
|
|
|
|
|
|
|
// Don't lint when the iterator is recreated on every iteration
|
|
|
|
|
if_chain! {
|
|
|
|
|
if let ExprKind::MethodCall(..) | ExprKind::Call(..) = iter_expr.kind;
|
|
|
|
|
if let Some(iter_def_id) = get_trait_def_id(cx, &paths::ITERATOR);
|
2020-07-17 08:47:04 +00:00
|
|
|
|
if implements_trait(cx, cx.typeck_results().expr_ty(iter_expr), iter_def_id, &[]);
|
2020-04-25 18:51:02 +00:00
|
|
|
|
then {
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2016-12-02 16:38:31 +00:00
|
|
|
|
let lhs_constructor = last_path_segment(qpath);
|
2019-05-17 21:53:54 +00:00
|
|
|
|
if method_path.ident.name == sym!(next)
|
|
|
|
|
&& match_trait_method(cx, match_expr, &paths::ITERATOR)
|
|
|
|
|
&& lhs_constructor.ident.name == sym!(Some)
|
2018-11-27 20:14:15 +00:00
|
|
|
|
&& (pat_args.is_empty()
|
2018-07-28 09:51:46 +00:00
|
|
|
|
|| !is_refutable(cx, &pat_args[0])
|
2019-01-19 09:36:27 +00:00
|
|
|
|
&& !is_used_inside(cx, iter_expr, &arms[0].body)
|
2018-11-27 20:14:15 +00:00
|
|
|
|
&& !is_iterator_used_after_while_let(cx, iter_expr)
|
|
|
|
|
&& !is_nested(cx, expr, &method_args[0]))
|
2017-08-09 07:30:56 +00:00
|
|
|
|
{
|
2020-04-25 18:00:00 +00:00
|
|
|
|
let mut applicability = Applicability::MachineApplicable;
|
|
|
|
|
let iterator = snippet_with_applicability(cx, method_args[0].span, "_", &mut applicability);
|
2018-07-28 09:51:46 +00:00
|
|
|
|
let loop_var = if pat_args.is_empty() {
|
|
|
|
|
"_".to_string()
|
|
|
|
|
} else {
|
2020-04-25 18:00:00 +00:00
|
|
|
|
snippet_with_applicability(cx, pat_args[0].span, "_", &mut applicability).into_owned()
|
2018-07-28 09:51:46 +00:00
|
|
|
|
};
|
2017-08-09 07:30:56 +00:00
|
|
|
|
span_lint_and_sugg(
|
|
|
|
|
cx,
|
|
|
|
|
WHILE_LET_ON_ITERATOR,
|
2020-04-25 18:00:00 +00:00
|
|
|
|
expr.span.with_hi(match_expr.span.hi()),
|
2017-08-09 07:30:56 +00:00
|
|
|
|
"this loop could be written as a `for` loop",
|
|
|
|
|
"try",
|
2020-04-25 18:00:00 +00:00
|
|
|
|
format!("for {} in {}", loop_var, iterator),
|
|
|
|
|
applicability,
|
2017-08-09 07:30:56 +00:00
|
|
|
|
);
|
2015-10-16 18:27:13 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
2018-02-25 17:25:31 +00:00
|
|
|
|
|
2019-07-06 17:35:08 +00:00
|
|
|
|
if let Some((cond, body)) = higher::while_loop(&expr) {
|
|
|
|
|
check_infinite_loop(cx, cond, body);
|
2018-02-25 17:25:31 +00:00
|
|
|
|
}
|
2018-08-30 03:01:24 +00:00
|
|
|
|
|
|
|
|
|
check_needless_collect(expr, cx);
|
2015-08-12 19:56:27 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2017-11-05 14:43:28 +00:00
|
|
|
|
enum NeverLoopResult {
|
|
|
|
|
// A break/return always get triggered but not necessarily for the main loop.
|
|
|
|
|
AlwaysBreak,
|
|
|
|
|
// A continue may occur for the main loop.
|
|
|
|
|
MayContinueMainLoop,
|
|
|
|
|
Otherwise,
|
|
|
|
|
}
|
|
|
|
|
|
2019-09-18 06:37:41 +00:00
|
|
|
|
#[must_use]
|
2017-11-05 15:17:28 +00:00
|
|
|
|
fn absorb_break(arg: &NeverLoopResult) -> NeverLoopResult {
|
|
|
|
|
match *arg {
|
2018-11-27 20:14:15 +00:00
|
|
|
|
NeverLoopResult::AlwaysBreak | NeverLoopResult::Otherwise => NeverLoopResult::Otherwise,
|
2017-11-05 14:43:28 +00:00
|
|
|
|
NeverLoopResult::MayContinueMainLoop => NeverLoopResult::MayContinueMainLoop,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Combine two results for parts that are called in order.
|
2019-09-18 06:37:41 +00:00
|
|
|
|
#[must_use]
|
2017-11-05 14:43:28 +00:00
|
|
|
|
fn combine_seq(first: NeverLoopResult, second: NeverLoopResult) -> NeverLoopResult {
|
|
|
|
|
match first {
|
|
|
|
|
NeverLoopResult::AlwaysBreak | NeverLoopResult::MayContinueMainLoop => first,
|
|
|
|
|
NeverLoopResult::Otherwise => second,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Combine two results where both parts are called but not necessarily in order.
|
2019-09-18 06:37:41 +00:00
|
|
|
|
#[must_use]
|
2017-11-05 14:43:28 +00:00
|
|
|
|
fn combine_both(left: NeverLoopResult, right: NeverLoopResult) -> NeverLoopResult {
|
|
|
|
|
match (left, right) {
|
2018-11-27 20:14:15 +00:00
|
|
|
|
(NeverLoopResult::MayContinueMainLoop, _) | (_, NeverLoopResult::MayContinueMainLoop) => {
|
|
|
|
|
NeverLoopResult::MayContinueMainLoop
|
|
|
|
|
},
|
|
|
|
|
(NeverLoopResult::AlwaysBreak, _) | (_, NeverLoopResult::AlwaysBreak) => NeverLoopResult::AlwaysBreak,
|
|
|
|
|
(NeverLoopResult::Otherwise, NeverLoopResult::Otherwise) => NeverLoopResult::Otherwise,
|
2017-11-05 14:43:28 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Combine two results where only one of the part may have been executed.
|
2019-09-18 06:37:41 +00:00
|
|
|
|
#[must_use]
|
2017-11-05 14:43:28 +00:00
|
|
|
|
fn combine_branches(b1: NeverLoopResult, b2: NeverLoopResult) -> NeverLoopResult {
|
|
|
|
|
match (b1, b2) {
|
2018-11-27 20:14:15 +00:00
|
|
|
|
(NeverLoopResult::AlwaysBreak, NeverLoopResult::AlwaysBreak) => NeverLoopResult::AlwaysBreak,
|
|
|
|
|
(NeverLoopResult::MayContinueMainLoop, _) | (_, NeverLoopResult::MayContinueMainLoop) => {
|
|
|
|
|
NeverLoopResult::MayContinueMainLoop
|
|
|
|
|
},
|
|
|
|
|
(NeverLoopResult::Otherwise, _) | (_, NeverLoopResult::Otherwise) => NeverLoopResult::Otherwise,
|
2017-11-05 14:43:28 +00:00
|
|
|
|
}
|
2017-05-31 01:44:01 +00:00
|
|
|
|
}
|
|
|
|
|
|
2019-12-27 07:12:26 +00:00
|
|
|
|
fn never_loop_block(block: &Block<'_>, main_loop_id: HirId) -> NeverLoopResult {
|
2017-10-08 22:26:39 +00:00
|
|
|
|
let stmts = block.stmts.iter().map(stmt_to_expr);
|
2020-04-06 13:48:38 +00:00
|
|
|
|
let expr = once(block.expr.as_deref());
|
2017-10-08 22:26:39 +00:00
|
|
|
|
let mut iter = stmts.chain(expr).filter_map(|e| e);
|
2017-11-05 14:43:28 +00:00
|
|
|
|
never_loop_expr_seq(&mut iter, main_loop_id)
|
2017-02-17 03:53:14 +00:00
|
|
|
|
}
|
|
|
|
|
|
2019-12-27 07:12:26 +00:00
|
|
|
|
fn stmt_to_expr<'tcx>(stmt: &Stmt<'tcx>) -> Option<&'tcx Expr<'tcx>> {
|
2019-09-27 15:16:06 +00:00
|
|
|
|
match stmt.kind {
|
2018-07-12 08:53:53 +00:00
|
|
|
|
StmtKind::Semi(ref e, ..) | StmtKind::Expr(ref e, ..) => Some(e),
|
2020-04-06 13:48:38 +00:00
|
|
|
|
StmtKind::Local(ref local) => local.init.as_deref(),
|
2017-10-08 22:26:39 +00:00
|
|
|
|
_ => None,
|
2017-02-17 03:53:14 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2019-12-27 07:12:26 +00:00
|
|
|
|
fn never_loop_expr(expr: &Expr<'_>, main_loop_id: HirId) -> NeverLoopResult {
|
2019-09-27 15:16:06 +00:00
|
|
|
|
match expr.kind {
|
2018-11-27 20:14:15 +00:00
|
|
|
|
ExprKind::Box(ref e)
|
|
|
|
|
| ExprKind::Unary(_, ref e)
|
|
|
|
|
| ExprKind::Cast(ref e, _)
|
|
|
|
|
| ExprKind::Type(ref e, _)
|
|
|
|
|
| ExprKind::Field(ref e, _)
|
2019-11-27 22:43:22 +00:00
|
|
|
|
| ExprKind::AddrOf(_, _, ref e)
|
2018-11-27 20:14:15 +00:00
|
|
|
|
| ExprKind::Struct(_, _, Some(ref e))
|
2019-04-28 07:11:20 +00:00
|
|
|
|
| ExprKind::Repeat(ref e, _)
|
2019-05-01 20:18:05 +00:00
|
|
|
|
| ExprKind::DropTemps(ref e) => never_loop_expr(e, main_loop_id),
|
2020-06-09 21:44:04 +00:00
|
|
|
|
ExprKind::Array(ref es) | ExprKind::MethodCall(_, _, ref es, _) | ExprKind::Tup(ref es) => {
|
2017-11-06 23:22:19 +00:00
|
|
|
|
never_loop_expr_all(&mut es.iter(), main_loop_id)
|
2017-11-04 19:55:56 +00:00
|
|
|
|
},
|
2018-07-12 07:30:57 +00:00
|
|
|
|
ExprKind::Call(ref e, ref es) => never_loop_expr_all(&mut once(&**e).chain(es.iter()), main_loop_id),
|
2018-11-27 20:14:15 +00:00
|
|
|
|
ExprKind::Binary(_, ref e1, ref e2)
|
2019-12-24 04:16:04 +00:00
|
|
|
|
| ExprKind::Assign(ref e1, ref e2, _)
|
2018-11-27 20:14:15 +00:00
|
|
|
|
| ExprKind::AssignOp(_, ref e1, ref e2)
|
|
|
|
|
| ExprKind::Index(ref e1, ref e2) => never_loop_expr_all(&mut [&**e1, &**e2].iter().cloned(), main_loop_id),
|
2018-07-12 07:30:57 +00:00
|
|
|
|
ExprKind::Loop(ref b, _, _) => {
|
2017-11-05 14:43:28 +00:00
|
|
|
|
// Break can come from the inner loop so remove them.
|
2017-11-05 15:17:28 +00:00
|
|
|
|
absorb_break(&never_loop_block(b, main_loop_id))
|
2017-10-06 05:04:39 +00:00
|
|
|
|
},
|
2018-07-12 07:30:57 +00:00
|
|
|
|
ExprKind::Match(ref e, ref arms, _) => {
|
2017-11-05 14:43:28 +00:00
|
|
|
|
let e = never_loop_expr(e, main_loop_id);
|
|
|
|
|
if arms.is_empty() {
|
2017-11-05 14:56:15 +00:00
|
|
|
|
e
|
2017-11-05 14:43:28 +00:00
|
|
|
|
} else {
|
|
|
|
|
let arms = never_loop_expr_branch(&mut arms.iter().map(|a| &*a.body), main_loop_id);
|
|
|
|
|
combine_seq(e, arms)
|
|
|
|
|
}
|
2017-06-29 14:07:43 +00:00
|
|
|
|
},
|
2018-07-12 07:30:57 +00:00
|
|
|
|
ExprKind::Block(ref b, _) => never_loop_block(b, main_loop_id),
|
|
|
|
|
ExprKind::Continue(d) => {
|
2018-11-27 20:14:15 +00:00
|
|
|
|
let id = d
|
|
|
|
|
.target_id
|
2019-01-31 01:15:29 +00:00
|
|
|
|
.expect("target ID can only be missing in the presence of compilation errors");
|
2018-05-31 18:15:48 +00:00
|
|
|
|
if id == main_loop_id {
|
2017-11-05 14:43:28 +00:00
|
|
|
|
NeverLoopResult::MayContinueMainLoop
|
|
|
|
|
} else {
|
|
|
|
|
NeverLoopResult::AlwaysBreak
|
|
|
|
|
}
|
2017-09-16 22:45:28 +00:00
|
|
|
|
},
|
2020-07-14 12:59:59 +00:00
|
|
|
|
ExprKind::Break(_, ref e) | ExprKind::Ret(ref e) => e.as_ref().map_or(NeverLoopResult::AlwaysBreak, |e| {
|
|
|
|
|
combine_seq(never_loop_expr(e, main_loop_id), NeverLoopResult::AlwaysBreak)
|
|
|
|
|
}),
|
2020-05-06 14:03:53 +00:00
|
|
|
|
ExprKind::InlineAsm(ref asm) => asm
|
|
|
|
|
.operands
|
|
|
|
|
.iter()
|
|
|
|
|
.map(|o| match o {
|
|
|
|
|
InlineAsmOperand::In { expr, .. }
|
|
|
|
|
| InlineAsmOperand::InOut { expr, .. }
|
|
|
|
|
| InlineAsmOperand::Const { expr }
|
|
|
|
|
| InlineAsmOperand::Sym { expr } => never_loop_expr(expr, main_loop_id),
|
|
|
|
|
InlineAsmOperand::Out { expr, .. } => never_loop_expr_all(&mut expr.iter(), main_loop_id),
|
|
|
|
|
InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
|
|
|
|
|
never_loop_expr_all(&mut once(in_expr).chain(out_expr.iter()), main_loop_id)
|
|
|
|
|
},
|
|
|
|
|
})
|
|
|
|
|
.fold(NeverLoopResult::Otherwise, combine_both),
|
2018-11-27 20:14:15 +00:00
|
|
|
|
ExprKind::Struct(_, _, None)
|
2019-06-19 09:59:25 +00:00
|
|
|
|
| ExprKind::Yield(_, _)
|
2018-11-27 20:14:15 +00:00
|
|
|
|
| ExprKind::Closure(_, _, _, _, _)
|
2020-03-27 14:41:56 +00:00
|
|
|
|
| ExprKind::LlvmInlineAsm(_)
|
2018-11-27 20:14:15 +00:00
|
|
|
|
| ExprKind::Path(_)
|
2020-10-06 21:51:31 +00:00
|
|
|
|
| ExprKind::ConstBlock(_)
|
2018-12-28 11:29:34 +00:00
|
|
|
|
| ExprKind::Lit(_)
|
|
|
|
|
| ExprKind::Err => NeverLoopResult::Otherwise,
|
2017-05-31 01:44:01 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2019-12-27 07:12:26 +00:00
|
|
|
|
fn never_loop_expr_seq<'a, T: Iterator<Item = &'a Expr<'a>>>(es: &mut T, main_loop_id: HirId) -> NeverLoopResult {
|
2017-11-06 23:22:19 +00:00
|
|
|
|
es.map(|e| never_loop_expr(e, main_loop_id))
|
|
|
|
|
.fold(NeverLoopResult::Otherwise, combine_seq)
|
2017-11-05 14:43:28 +00:00
|
|
|
|
}
|
|
|
|
|
|
2019-12-27 07:12:26 +00:00
|
|
|
|
fn never_loop_expr_all<'a, T: Iterator<Item = &'a Expr<'a>>>(es: &mut T, main_loop_id: HirId) -> NeverLoopResult {
|
2017-11-06 23:22:19 +00:00
|
|
|
|
es.map(|e| never_loop_expr(e, main_loop_id))
|
|
|
|
|
.fold(NeverLoopResult::Otherwise, combine_both)
|
2017-05-31 01:44:01 +00:00
|
|
|
|
}
|
|
|
|
|
|
2019-12-27 07:12:26 +00:00
|
|
|
|
fn never_loop_expr_branch<'a, T: Iterator<Item = &'a Expr<'a>>>(e: &mut T, main_loop_id: HirId) -> NeverLoopResult {
|
2017-11-06 23:22:19 +00:00
|
|
|
|
e.map(|e| never_loop_expr(e, main_loop_id))
|
|
|
|
|
.fold(NeverLoopResult::AlwaysBreak, combine_branches)
|
2017-02-17 03:53:14 +00:00
|
|
|
|
}
|
|
|
|
|
|
2020-06-25 20:41:36 +00:00
|
|
|
|
fn check_for_loop<'tcx>(
|
|
|
|
|
cx: &LateContext<'tcx>,
|
2019-12-27 07:12:26 +00:00
|
|
|
|
pat: &'tcx Pat<'_>,
|
|
|
|
|
arg: &'tcx Expr<'_>,
|
|
|
|
|
body: &'tcx Expr<'_>,
|
|
|
|
|
expr: &'tcx Expr<'_>,
|
2016-12-21 11:14:54 +00:00
|
|
|
|
) {
|
2020-10-23 20:16:59 +00:00
|
|
|
|
let is_manual_memcpy_triggered = detect_manual_memcpy(cx, pat, arg, body, expr);
|
|
|
|
|
if !is_manual_memcpy_triggered {
|
|
|
|
|
check_for_loop_range(cx, pat, arg, body, expr);
|
|
|
|
|
check_for_loop_explicit_counter(cx, pat, arg, body, expr);
|
|
|
|
|
}
|
2016-01-29 07:34:09 +00:00
|
|
|
|
check_for_loop_arg(cx, pat, arg, expr);
|
2016-02-05 18:14:02 +00:00
|
|
|
|
check_for_loop_over_map_kv(cx, pat, arg, body, expr);
|
2017-09-24 19:40:10 +00:00
|
|
|
|
check_for_mut_range_bound(cx, arg, body);
|
2020-08-11 13:43:21 +00:00
|
|
|
|
detect_same_item_push(cx, pat, arg, body, expr);
|
2017-09-05 00:16:34 +00:00
|
|
|
|
}
|
|
|
|
|
|
2020-10-23 20:16:59 +00:00
|
|
|
|
// this function assumes the given expression is a `for` loop.
|
|
|
|
|
fn get_span_of_entire_for_loop(expr: &Expr<'_>) -> Span {
|
|
|
|
|
// for some reason this is the only way to get the `Span`
|
|
|
|
|
// of the entire `for` loop
|
|
|
|
|
if let ExprKind::Match(_, arms, _) = &expr.kind {
|
|
|
|
|
arms[0].body.span
|
|
|
|
|
} else {
|
|
|
|
|
unreachable!()
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2020-06-25 20:41:36 +00:00
|
|
|
|
fn same_var<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>, var: HirId) -> bool {
|
2017-10-23 19:18:02 +00:00
|
|
|
|
if_chain! {
|
2020-05-11 18:23:47 +00:00
|
|
|
|
if let ExprKind::Path(qpath) = &expr.kind;
|
|
|
|
|
if let QPath::Resolved(None, path) = qpath;
|
2017-10-23 19:18:02 +00:00
|
|
|
|
if path.segments.len() == 1;
|
2019-09-18 17:29:04 +00:00
|
|
|
|
if let Res::Local(local_id) = qpath_res(cx, qpath, expr.hir_id);
|
2017-10-23 19:18:02 +00:00
|
|
|
|
then {
|
2020-05-11 18:23:47 +00:00
|
|
|
|
// our variable!
|
|
|
|
|
local_id == var
|
|
|
|
|
} else {
|
|
|
|
|
false
|
2017-10-23 19:18:02 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
2020-05-11 18:23:47 +00:00
|
|
|
|
}
|
2017-09-05 00:16:34 +00:00
|
|
|
|
|
2020-10-23 20:16:59 +00:00
|
|
|
|
/// a wrapper of `Sugg`. Besides what `Sugg` do, this removes unnecessary `0`;
|
|
|
|
|
/// and also, it avoids subtracting a variable from the same one by replacing it with `0`.
|
|
|
|
|
/// it exists for the convenience of the overloaded operators while normal functions can do the
|
|
|
|
|
/// same.
|
|
|
|
|
#[derive(Clone)]
|
|
|
|
|
struct MinifyingSugg<'a>(Sugg<'a>);
|
|
|
|
|
|
|
|
|
|
impl<'a> MinifyingSugg<'a> {
|
|
|
|
|
fn as_str(&self) -> &str {
|
|
|
|
|
let Sugg::NonParen(s) | Sugg::MaybeParen(s) | Sugg::BinOp(_, s) = &self.0;
|
|
|
|
|
s.as_ref()
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn into_sugg(self) -> Sugg<'a> {
|
|
|
|
|
self.0
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl<'a> From<Sugg<'a>> for MinifyingSugg<'a> {
|
|
|
|
|
fn from(sugg: Sugg<'a>) -> Self {
|
|
|
|
|
Self(sugg)
|
|
|
|
|
}
|
2017-09-05 00:16:34 +00:00
|
|
|
|
}
|
|
|
|
|
|
2020-10-23 20:16:59 +00:00
|
|
|
|
impl std::ops::Add for &MinifyingSugg<'static> {
|
|
|
|
|
type Output = MinifyingSugg<'static>;
|
|
|
|
|
fn add(self, rhs: &MinifyingSugg<'static>) -> MinifyingSugg<'static> {
|
|
|
|
|
match (self.as_str(), rhs.as_str()) {
|
|
|
|
|
("0", _) => rhs.clone(),
|
|
|
|
|
(_, "0") => self.clone(),
|
|
|
|
|
(_, _) => (&self.0 + &rhs.0).into(),
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl std::ops::Sub for &MinifyingSugg<'static> {
|
|
|
|
|
type Output = MinifyingSugg<'static>;
|
|
|
|
|
fn sub(self, rhs: &MinifyingSugg<'static>) -> MinifyingSugg<'static> {
|
|
|
|
|
match (self.as_str(), rhs.as_str()) {
|
|
|
|
|
(_, "0") => self.clone(),
|
|
|
|
|
("0", _) => (-rhs.0.clone()).into(),
|
|
|
|
|
(x, y) if x == y => sugg::ZERO.into(),
|
|
|
|
|
(_, _) => (&self.0 - &rhs.0).into(),
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl std::ops::Add<&MinifyingSugg<'static>> for MinifyingSugg<'static> {
|
|
|
|
|
type Output = MinifyingSugg<'static>;
|
|
|
|
|
fn add(self, rhs: &MinifyingSugg<'static>) -> MinifyingSugg<'static> {
|
|
|
|
|
match (self.as_str(), rhs.as_str()) {
|
|
|
|
|
("0", _) => rhs.clone(),
|
|
|
|
|
(_, "0") => self,
|
|
|
|
|
(_, _) => (self.0 + &rhs.0).into(),
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl std::ops::Sub<&MinifyingSugg<'static>> for MinifyingSugg<'static> {
|
|
|
|
|
type Output = MinifyingSugg<'static>;
|
|
|
|
|
fn sub(self, rhs: &MinifyingSugg<'static>) -> MinifyingSugg<'static> {
|
|
|
|
|
match (self.as_str(), rhs.as_str()) {
|
|
|
|
|
(_, "0") => self,
|
|
|
|
|
("0", _) => (-rhs.0.clone()).into(),
|
|
|
|
|
(x, y) if x == y => sugg::ZERO.into(),
|
|
|
|
|
(_, _) => (self.0 - &rhs.0).into(),
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// a wrapper around `MinifyingSugg`, which carries a operator like currying
|
|
|
|
|
/// so that the suggested code become more efficient (e.g. `foo + -bar` `foo - bar`).
|
2017-09-05 00:16:34 +00:00
|
|
|
|
struct Offset {
|
2020-10-23 20:16:59 +00:00
|
|
|
|
value: MinifyingSugg<'static>,
|
2020-05-11 18:23:47 +00:00
|
|
|
|
sign: OffsetSign,
|
2017-09-05 00:16:34 +00:00
|
|
|
|
}
|
|
|
|
|
|
2020-10-23 20:16:59 +00:00
|
|
|
|
#[derive(Clone, Copy)]
|
|
|
|
|
enum OffsetSign {
|
|
|
|
|
Positive,
|
|
|
|
|
Negative,
|
|
|
|
|
}
|
|
|
|
|
|
2017-09-05 00:16:34 +00:00
|
|
|
|
impl Offset {
|
2020-10-23 20:16:59 +00:00
|
|
|
|
fn negative(value: Sugg<'static>) -> Self {
|
2020-05-11 18:23:47 +00:00
|
|
|
|
Self {
|
2020-10-23 20:16:59 +00:00
|
|
|
|
value: value.into(),
|
2020-05-11 18:23:47 +00:00
|
|
|
|
sign: OffsetSign::Negative,
|
|
|
|
|
}
|
2017-09-05 00:16:34 +00:00
|
|
|
|
}
|
|
|
|
|
|
2020-10-23 20:16:59 +00:00
|
|
|
|
fn positive(value: Sugg<'static>) -> Self {
|
2017-09-05 00:16:34 +00:00
|
|
|
|
Self {
|
2020-10-23 20:16:59 +00:00
|
|
|
|
value: value.into(),
|
2020-05-11 18:23:47 +00:00
|
|
|
|
sign: OffsetSign::Positive,
|
2017-09-05 00:16:34 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
2020-10-23 20:16:59 +00:00
|
|
|
|
|
|
|
|
|
fn empty() -> Self {
|
|
|
|
|
Self::positive(sugg::ZERO)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn apply_offset(lhs: &MinifyingSugg<'static>, rhs: &Offset) -> MinifyingSugg<'static> {
|
|
|
|
|
match rhs.sign {
|
|
|
|
|
OffsetSign::Positive => lhs + &rhs.value,
|
|
|
|
|
OffsetSign::Negative => lhs - &rhs.value,
|
|
|
|
|
}
|
2017-09-05 00:16:34 +00:00
|
|
|
|
}
|
|
|
|
|
|
2020-10-23 20:16:59 +00:00
|
|
|
|
#[derive(Debug, Clone, Copy)]
|
|
|
|
|
enum StartKind<'hir> {
|
|
|
|
|
Range,
|
|
|
|
|
Counter { initializer: &'hir Expr<'hir> },
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
struct IndexExpr<'hir> {
|
|
|
|
|
base: &'hir Expr<'hir>,
|
|
|
|
|
idx: StartKind<'hir>,
|
|
|
|
|
idx_offset: Offset,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
struct Start<'hir> {
|
|
|
|
|
id: HirId,
|
|
|
|
|
kind: StartKind<'hir>,
|
2017-09-05 00:16:34 +00:00
|
|
|
|
}
|
|
|
|
|
|
2020-06-25 20:41:36 +00:00
|
|
|
|
fn is_slice_like<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'_>) -> bool {
|
2020-08-03 22:18:29 +00:00
|
|
|
|
let is_slice = match ty.kind() {
|
2018-08-22 21:34:52 +00:00
|
|
|
|
ty::Ref(_, subty, _) => is_slice_like(cx, subty),
|
|
|
|
|
ty::Slice(..) | ty::Array(..) => true,
|
2017-09-05 00:16:34 +00:00
|
|
|
|
_ => false,
|
|
|
|
|
};
|
|
|
|
|
|
2020-04-23 06:09:42 +00:00
|
|
|
|
is_slice || is_type_diagnostic_item(cx, ty, sym!(vec_type)) || is_type_diagnostic_item(cx, ty, sym!(vecdeque_type))
|
2017-09-05 00:16:34 +00:00
|
|
|
|
}
|
|
|
|
|
|
2020-05-11 18:23:47 +00:00
|
|
|
|
fn fetch_cloned_expr<'tcx>(expr: &'tcx Expr<'tcx>) -> &'tcx Expr<'tcx> {
|
|
|
|
|
if_chain! {
|
2020-06-09 21:44:04 +00:00
|
|
|
|
if let ExprKind::MethodCall(method, _, args, _) = expr.kind;
|
2020-05-11 18:23:47 +00:00
|
|
|
|
if method.ident.name == sym!(clone);
|
|
|
|
|
if args.len() == 1;
|
|
|
|
|
if let Some(arg) = args.get(0);
|
|
|
|
|
then { arg } else { expr }
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2020-10-23 20:16:59 +00:00
|
|
|
|
fn get_details_from_idx<'tcx>(
|
|
|
|
|
cx: &LateContext<'tcx>,
|
|
|
|
|
idx: &Expr<'_>,
|
|
|
|
|
starts: &[Start<'tcx>],
|
|
|
|
|
) -> Option<(StartKind<'tcx>, Offset)> {
|
|
|
|
|
fn get_start<'tcx>(cx: &LateContext<'tcx>, e: &Expr<'_>, starts: &[Start<'tcx>]) -> Option<StartKind<'tcx>> {
|
|
|
|
|
starts.iter().find_map(|start| {
|
|
|
|
|
if same_var(cx, e, start.id) {
|
|
|
|
|
Some(start.kind)
|
|
|
|
|
} else {
|
|
|
|
|
None
|
|
|
|
|
}
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn get_offset<'tcx>(cx: &LateContext<'tcx>, e: &Expr<'_>, starts: &[Start<'tcx>]) -> Option<Sugg<'static>> {
|
2020-05-11 18:23:47 +00:00
|
|
|
|
match &e.kind {
|
|
|
|
|
ExprKind::Lit(l) => match l.node {
|
2020-10-23 20:16:59 +00:00
|
|
|
|
ast::LitKind::Int(x, _ty) => Some(Sugg::NonParen(x.to_string().into())),
|
2017-11-04 19:55:56 +00:00
|
|
|
|
_ => None,
|
2017-09-05 00:16:34 +00:00
|
|
|
|
},
|
2020-10-23 20:16:59 +00:00
|
|
|
|
ExprKind::Path(..) if get_start(cx, e, starts).is_none() => Some(Sugg::hir(cx, e, "???")),
|
2017-09-05 00:16:34 +00:00
|
|
|
|
_ => None,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2020-05-11 18:23:47 +00:00
|
|
|
|
match idx.kind {
|
|
|
|
|
ExprKind::Binary(op, lhs, rhs) => match op.node {
|
|
|
|
|
BinOpKind::Add => {
|
2020-10-23 20:16:59 +00:00
|
|
|
|
let offset_opt = get_start(cx, lhs, starts)
|
|
|
|
|
.and_then(|s| get_offset(cx, rhs, starts).map(|o| (s, o)))
|
|
|
|
|
.or_else(|| get_start(cx, rhs, starts).and_then(|s| get_offset(cx, lhs, starts).map(|o| (s, o))));
|
2020-05-11 18:23:47 +00:00
|
|
|
|
|
2020-10-23 20:16:59 +00:00
|
|
|
|
offset_opt.map(|(s, o)| (s, Offset::positive(o)))
|
|
|
|
|
},
|
|
|
|
|
BinOpKind::Sub => {
|
|
|
|
|
get_start(cx, lhs, starts).and_then(|s| get_offset(cx, rhs, starts).map(|o| (s, Offset::negative(o))))
|
2017-09-05 00:16:34 +00:00
|
|
|
|
},
|
|
|
|
|
_ => None,
|
2020-05-11 18:23:47 +00:00
|
|
|
|
},
|
2020-10-23 20:16:59 +00:00
|
|
|
|
ExprKind::Path(..) => get_start(cx, idx, starts).map(|s| (s, Offset::empty())),
|
2020-05-11 18:23:47 +00:00
|
|
|
|
_ => None,
|
2017-10-23 19:18:02 +00:00
|
|
|
|
}
|
2017-09-16 23:17:22 +00:00
|
|
|
|
}
|
|
|
|
|
|
2020-10-23 20:16:59 +00:00
|
|
|
|
fn get_assignment<'tcx>(e: &'tcx Expr<'tcx>) -> Option<(&'tcx Expr<'tcx>, &'tcx Expr<'tcx>)> {
|
|
|
|
|
if let ExprKind::Assign(lhs, rhs, _) = e.kind {
|
|
|
|
|
Some((lhs, rhs))
|
|
|
|
|
} else {
|
|
|
|
|
None
|
2017-09-05 00:16:34 +00:00
|
|
|
|
}
|
2020-10-23 20:16:59 +00:00
|
|
|
|
}
|
2017-09-05 00:16:34 +00:00
|
|
|
|
|
2020-10-23 20:16:59 +00:00
|
|
|
|
/// Get assignments from the given block.
|
|
|
|
|
/// The returned iterator yields `None` if no assignment expressions are there,
|
|
|
|
|
/// filtering out the increments of the given whitelisted loop counters;
|
|
|
|
|
/// because its job is to make sure there's nothing other than assignments and the increments.
|
|
|
|
|
fn get_assignments<'a: 'c, 'tcx: 'c, 'c>(
|
|
|
|
|
cx: &'a LateContext<'tcx>,
|
|
|
|
|
Block { stmts, expr, .. }: &'tcx Block<'tcx>,
|
|
|
|
|
loop_counters: &'c [Start<'tcx>],
|
|
|
|
|
) -> impl Iterator<Item = Option<(&'tcx Expr<'tcx>, &'tcx Expr<'tcx>)>> + 'c {
|
|
|
|
|
// As the `filter` and `map` below do different things, I think putting together
|
|
|
|
|
// just increases complexity. (cc #3188 and #4193)
|
|
|
|
|
#[allow(clippy::filter_map)]
|
|
|
|
|
stmts
|
|
|
|
|
.iter()
|
|
|
|
|
.filter_map(move |stmt| match stmt.kind {
|
|
|
|
|
StmtKind::Local(..) | StmtKind::Item(..) => None,
|
|
|
|
|
StmtKind::Expr(e) | StmtKind::Semi(e) => Some(e),
|
|
|
|
|
})
|
|
|
|
|
.chain((*expr).into_iter())
|
|
|
|
|
.filter(move |e| {
|
|
|
|
|
if let ExprKind::AssignOp(_, place, _) = e.kind {
|
|
|
|
|
!loop_counters
|
|
|
|
|
.iter()
|
|
|
|
|
// skip the first item which should be `StartKind::Range`
|
|
|
|
|
// this makes it possible to use the slice with `StartKind::Range` in the same iterator loop.
|
|
|
|
|
.skip(1)
|
|
|
|
|
.any(|counter| same_var(cx, place, counter.id))
|
|
|
|
|
} else {
|
|
|
|
|
true
|
|
|
|
|
}
|
|
|
|
|
})
|
|
|
|
|
.map(get_assignment)
|
|
|
|
|
}
|
2020-05-11 18:23:47 +00:00
|
|
|
|
|
2020-10-23 20:16:59 +00:00
|
|
|
|
fn get_loop_counters<'a, 'tcx>(
|
|
|
|
|
cx: &'a LateContext<'tcx>,
|
|
|
|
|
body: &'tcx Block<'tcx>,
|
|
|
|
|
expr: &'tcx Expr<'_>,
|
|
|
|
|
) -> Option<impl Iterator<Item = Start<'tcx>> + 'a> {
|
|
|
|
|
// Look for variables that are incremented once per loop iteration.
|
|
|
|
|
let mut increment_visitor = IncrementVisitor::new(cx);
|
|
|
|
|
walk_block(&mut increment_visitor, body);
|
2017-09-05 00:16:34 +00:00
|
|
|
|
|
2020-10-23 20:16:59 +00:00
|
|
|
|
// For each candidate, check the parent block to see if
|
|
|
|
|
// it's initialized to zero at the start of the loop.
|
|
|
|
|
get_enclosing_block(&cx, expr.hir_id).and_then(|block| {
|
|
|
|
|
increment_visitor
|
|
|
|
|
.into_results()
|
|
|
|
|
.filter_map(move |var_id| {
|
|
|
|
|
let mut initialize_visitor = InitializeVisitor::new(cx, expr, var_id);
|
|
|
|
|
walk_block(&mut initialize_visitor, block);
|
|
|
|
|
|
|
|
|
|
initialize_visitor.get_result().map(|(_, initializer)| Start {
|
|
|
|
|
id: var_id,
|
|
|
|
|
kind: StartKind::Counter { initializer },
|
|
|
|
|
})
|
2017-09-05 00:16:34 +00:00
|
|
|
|
})
|
2020-05-11 18:23:47 +00:00
|
|
|
|
.into()
|
2020-10-23 20:16:59 +00:00
|
|
|
|
})
|
2017-09-05 00:16:34 +00:00
|
|
|
|
}
|
|
|
|
|
|
2020-06-25 20:41:36 +00:00
|
|
|
|
fn build_manual_memcpy_suggestion<'tcx>(
|
|
|
|
|
cx: &LateContext<'tcx>,
|
2020-05-11 18:23:47 +00:00
|
|
|
|
start: &Expr<'_>,
|
|
|
|
|
end: &Expr<'_>,
|
|
|
|
|
limits: ast::RangeLimits,
|
2020-10-23 20:16:59 +00:00
|
|
|
|
dst: &IndexExpr<'_>,
|
|
|
|
|
src: &IndexExpr<'_>,
|
2020-05-11 18:23:47 +00:00
|
|
|
|
) -> String {
|
2020-10-23 20:16:59 +00:00
|
|
|
|
fn print_offset(offset: MinifyingSugg<'static>) -> MinifyingSugg<'static> {
|
2020-05-11 18:23:47 +00:00
|
|
|
|
if offset.as_str() == "0" {
|
2020-10-23 20:16:59 +00:00
|
|
|
|
sugg::EMPTY.into()
|
2020-05-11 18:23:47 +00:00
|
|
|
|
} else {
|
|
|
|
|
offset
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2020-10-23 20:16:59 +00:00
|
|
|
|
let print_limit = |end: &Expr<'_>, end_str: &str, base: &Expr<'_>, sugg: MinifyingSugg<'static>| {
|
2020-05-11 18:23:47 +00:00
|
|
|
|
if_chain! {
|
2020-06-09 21:44:04 +00:00
|
|
|
|
if let ExprKind::MethodCall(method, _, len_args, _) = end.kind;
|
2020-05-11 18:23:47 +00:00
|
|
|
|
if method.ident.name == sym!(len);
|
|
|
|
|
if len_args.len() == 1;
|
|
|
|
|
if let Some(arg) = len_args.get(0);
|
2020-10-23 20:16:59 +00:00
|
|
|
|
if var_def_id(cx, arg) == var_def_id(cx, base);
|
2020-05-11 18:23:47 +00:00
|
|
|
|
then {
|
2020-10-23 20:16:59 +00:00
|
|
|
|
if sugg.as_str() == end_str {
|
|
|
|
|
sugg::EMPTY.into()
|
|
|
|
|
} else {
|
|
|
|
|
sugg
|
2020-05-11 18:23:47 +00:00
|
|
|
|
}
|
|
|
|
|
} else {
|
2020-10-23 20:16:59 +00:00
|
|
|
|
match limits {
|
2020-05-11 18:23:47 +00:00
|
|
|
|
ast::RangeLimits::Closed => {
|
2020-10-23 20:16:59 +00:00
|
|
|
|
sugg + &sugg::ONE.into()
|
2020-05-11 18:23:47 +00:00
|
|
|
|
},
|
2020-10-23 20:16:59 +00:00
|
|
|
|
ast::RangeLimits::HalfOpen => sugg,
|
|
|
|
|
}
|
2020-05-11 18:23:47 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
2020-10-23 20:16:59 +00:00
|
|
|
|
let start_str = Sugg::hir(cx, start, "").into();
|
|
|
|
|
let end_str: MinifyingSugg<'_> = Sugg::hir(cx, end, "").into();
|
|
|
|
|
|
|
|
|
|
let print_offset_and_limit = |idx_expr: &IndexExpr<'_>| match idx_expr.idx {
|
|
|
|
|
StartKind::Range => (
|
|
|
|
|
print_offset(apply_offset(&start_str, &idx_expr.idx_offset)).into_sugg(),
|
|
|
|
|
print_limit(
|
|
|
|
|
end,
|
|
|
|
|
end_str.as_str(),
|
|
|
|
|
idx_expr.base,
|
|
|
|
|
apply_offset(&end_str, &idx_expr.idx_offset),
|
|
|
|
|
)
|
|
|
|
|
.into_sugg(),
|
|
|
|
|
),
|
|
|
|
|
StartKind::Counter { initializer } => {
|
|
|
|
|
let counter_start = Sugg::hir(cx, initializer, "").into();
|
|
|
|
|
(
|
|
|
|
|
print_offset(apply_offset(&counter_start, &idx_expr.idx_offset)).into_sugg(),
|
|
|
|
|
print_limit(
|
|
|
|
|
end,
|
|
|
|
|
end_str.as_str(),
|
|
|
|
|
idx_expr.base,
|
|
|
|
|
apply_offset(&end_str, &idx_expr.idx_offset) + &counter_start - &start_str,
|
|
|
|
|
)
|
|
|
|
|
.into_sugg(),
|
|
|
|
|
)
|
|
|
|
|
},
|
|
|
|
|
};
|
2020-05-11 18:23:47 +00:00
|
|
|
|
|
2020-10-23 20:16:59 +00:00
|
|
|
|
let (dst_offset, dst_limit) = print_offset_and_limit(&dst);
|
|
|
|
|
let (src_offset, src_limit) = print_offset_and_limit(&src);
|
2020-05-11 18:23:47 +00:00
|
|
|
|
|
2020-10-23 20:16:59 +00:00
|
|
|
|
let dst_base_str = snippet(cx, dst.base.span, "???");
|
|
|
|
|
let src_base_str = snippet(cx, src.base.span, "???");
|
|
|
|
|
|
|
|
|
|
let dst = if dst_offset == sugg::EMPTY && dst_limit == sugg::EMPTY {
|
|
|
|
|
dst_base_str
|
2020-05-11 18:23:47 +00:00
|
|
|
|
} else {
|
2020-10-23 20:16:59 +00:00
|
|
|
|
format!(
|
|
|
|
|
"{}[{}..{}]",
|
|
|
|
|
dst_base_str,
|
|
|
|
|
dst_offset.maybe_par(),
|
|
|
|
|
dst_limit.maybe_par()
|
|
|
|
|
)
|
|
|
|
|
.into()
|
2020-05-11 18:23:47 +00:00
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
format!(
|
2020-10-23 20:16:59 +00:00
|
|
|
|
"{}.clone_from_slice(&{}[{}..{}]);",
|
|
|
|
|
dst,
|
|
|
|
|
src_base_str,
|
|
|
|
|
src_offset.maybe_par(),
|
|
|
|
|
src_limit.maybe_par()
|
2020-05-11 18:23:47 +00:00
|
|
|
|
)
|
|
|
|
|
}
|
2020-10-23 20:16:59 +00:00
|
|
|
|
|
2019-01-31 01:15:29 +00:00
|
|
|
|
/// Checks for for loops that sequentially copy items from one slice-like
|
2017-09-05 00:16:34 +00:00
|
|
|
|
/// object to another.
|
2020-06-25 20:41:36 +00:00
|
|
|
|
fn detect_manual_memcpy<'tcx>(
|
|
|
|
|
cx: &LateContext<'tcx>,
|
2019-12-27 07:12:26 +00:00
|
|
|
|
pat: &'tcx Pat<'_>,
|
|
|
|
|
arg: &'tcx Expr<'_>,
|
|
|
|
|
body: &'tcx Expr<'_>,
|
|
|
|
|
expr: &'tcx Expr<'_>,
|
2020-10-23 20:16:59 +00:00
|
|
|
|
) -> bool {
|
2017-09-05 00:16:34 +00:00
|
|
|
|
if let Some(higher::Range {
|
2017-11-04 19:55:56 +00:00
|
|
|
|
start: Some(start),
|
2020-05-11 18:23:47 +00:00
|
|
|
|
end: Some(end),
|
2017-11-04 19:55:56 +00:00
|
|
|
|
limits,
|
2020-08-04 13:24:13 +00:00
|
|
|
|
}) = higher::range(arg)
|
2017-09-05 00:16:34 +00:00
|
|
|
|
{
|
|
|
|
|
// the var must be a single name
|
2019-09-27 15:16:06 +00:00
|
|
|
|
if let PatKind::Binding(_, canonical_id, _, _) = pat.kind {
|
2020-10-23 20:16:59 +00:00
|
|
|
|
let mut starts = vec![Start {
|
|
|
|
|
id: canonical_id,
|
|
|
|
|
kind: StartKind::Range,
|
|
|
|
|
}];
|
|
|
|
|
|
|
|
|
|
// This is one of few ways to return different iterators
|
|
|
|
|
// derived from: https://stackoverflow.com/questions/29760668/conditionally-iterate-over-one-of-several-possible-iterators/52064434#52064434
|
|
|
|
|
let mut iter_a = None;
|
|
|
|
|
let mut iter_b = None;
|
|
|
|
|
|
|
|
|
|
if let ExprKind::Block(block, _) = body.kind {
|
|
|
|
|
if let Some(loop_counters) = get_loop_counters(cx, block, expr) {
|
|
|
|
|
starts.extend(loop_counters);
|
|
|
|
|
}
|
|
|
|
|
iter_a = Some(get_assignments(cx, block, &starts));
|
|
|
|
|
} else {
|
|
|
|
|
iter_b = Some(get_assignment(body));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
let assignments = iter_a.into_iter().flatten().chain(iter_b.into_iter());
|
|
|
|
|
|
|
|
|
|
let big_sugg = assignments
|
|
|
|
|
// The only statements in the for loops can be indexed assignments from
|
|
|
|
|
// indexed retrievals (except increments of loop counters).
|
2020-05-11 18:23:47 +00:00
|
|
|
|
.map(|o| {
|
|
|
|
|
o.and_then(|(lhs, rhs)| {
|
|
|
|
|
let rhs = fetch_cloned_expr(rhs);
|
|
|
|
|
if_chain! {
|
2020-10-23 20:16:59 +00:00
|
|
|
|
if let ExprKind::Index(base_left, idx_left) = lhs.kind;
|
|
|
|
|
if let ExprKind::Index(base_right, idx_right) = rhs.kind;
|
|
|
|
|
if is_slice_like(cx, cx.typeck_results().expr_ty(base_left))
|
|
|
|
|
&& is_slice_like(cx, cx.typeck_results().expr_ty(base_right));
|
|
|
|
|
if let Some((start_left, offset_left)) = get_details_from_idx(cx, &idx_left, &starts);
|
|
|
|
|
if let Some((start_right, offset_right)) = get_details_from_idx(cx, &idx_right, &starts);
|
2020-05-11 18:23:47 +00:00
|
|
|
|
|
|
|
|
|
// Source and destination must be different
|
2020-10-23 20:16:59 +00:00
|
|
|
|
if var_def_id(cx, base_left) != var_def_id(cx, base_right);
|
2020-05-11 18:23:47 +00:00
|
|
|
|
then {
|
2020-10-23 20:16:59 +00:00
|
|
|
|
Some((IndexExpr { base: base_left, idx: start_left, idx_offset: offset_left },
|
|
|
|
|
IndexExpr { base: base_right, idx: start_right, idx_offset: offset_right }))
|
2020-05-11 18:23:47 +00:00
|
|
|
|
} else {
|
|
|
|
|
None
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
})
|
2017-09-05 00:16:34 +00:00
|
|
|
|
})
|
2020-10-23 20:16:59 +00:00
|
|
|
|
.map(|o| o.map(|(dst, src)| build_manual_memcpy_suggestion(cx, start, end, limits, &dst, &src)))
|
2020-05-11 18:23:47 +00:00
|
|
|
|
.collect::<Option<Vec<_>>>()
|
|
|
|
|
.filter(|v| !v.is_empty())
|
|
|
|
|
.map(|v| v.join("\n "));
|
2017-09-05 00:16:34 +00:00
|
|
|
|
|
2020-05-11 18:23:47 +00:00
|
|
|
|
if let Some(big_sugg) = big_sugg {
|
2017-09-05 00:16:34 +00:00
|
|
|
|
span_lint_and_sugg(
|
|
|
|
|
cx,
|
|
|
|
|
MANUAL_MEMCPY,
|
2020-10-23 20:16:59 +00:00
|
|
|
|
get_span_of_entire_for_loop(expr),
|
2017-09-05 00:16:34 +00:00
|
|
|
|
"it looks like you're manually copying between slices",
|
|
|
|
|
"try replacing the loop by",
|
|
|
|
|
big_sugg,
|
2018-11-20 13:06:29 +00:00
|
|
|
|
Applicability::Unspecified,
|
2017-09-05 00:16:34 +00:00
|
|
|
|
);
|
2020-10-23 20:16:59 +00:00
|
|
|
|
return true;
|
2017-09-05 00:16:34 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
2020-10-23 20:16:59 +00:00
|
|
|
|
false
|
2016-01-14 19:58:32 +00:00
|
|
|
|
}
|
2015-11-18 11:35:18 +00:00
|
|
|
|
|
2020-08-11 13:43:21 +00:00
|
|
|
|
// Scans the body of the for loop and determines whether lint should be given
|
|
|
|
|
struct SameItemPushVisitor<'a, 'tcx> {
|
|
|
|
|
should_lint: bool,
|
|
|
|
|
// this field holds the last vec push operation visited, which should be the only push seen
|
|
|
|
|
vec_push: Option<(&'tcx Expr<'tcx>, &'tcx Expr<'tcx>)>,
|
|
|
|
|
cx: &'a LateContext<'tcx>,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl<'a, 'tcx> Visitor<'tcx> for SameItemPushVisitor<'a, 'tcx> {
|
|
|
|
|
type Map = Map<'tcx>;
|
|
|
|
|
|
|
|
|
|
fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
|
|
|
|
|
match &expr.kind {
|
|
|
|
|
// Non-determinism may occur ... don't give a lint
|
|
|
|
|
ExprKind::Loop(_, _, _) | ExprKind::Match(_, _, _) => self.should_lint = false,
|
|
|
|
|
ExprKind::Block(block, _) => self.visit_block(block),
|
|
|
|
|
_ => {},
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn visit_block(&mut self, b: &'tcx Block<'_>) {
|
|
|
|
|
for stmt in b.stmts.iter() {
|
|
|
|
|
self.visit_stmt(stmt);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn visit_stmt(&mut self, s: &'tcx Stmt<'_>) {
|
|
|
|
|
let vec_push_option = get_vec_push(self.cx, s);
|
|
|
|
|
if vec_push_option.is_none() {
|
|
|
|
|
// Current statement is not a push so visit inside
|
|
|
|
|
match &s.kind {
|
|
|
|
|
StmtKind::Expr(expr) | StmtKind::Semi(expr) => self.visit_expr(&expr),
|
|
|
|
|
_ => {},
|
|
|
|
|
}
|
|
|
|
|
} else {
|
|
|
|
|
// Current statement is a push ...check whether another
|
|
|
|
|
// push had been previously done
|
|
|
|
|
if self.vec_push.is_none() {
|
|
|
|
|
self.vec_push = vec_push_option;
|
|
|
|
|
} else {
|
|
|
|
|
// There are multiple pushes ... don't lint
|
|
|
|
|
self.should_lint = false;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
|
|
|
|
|
NestedVisitorMap::None
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Given some statement, determine if that statement is a push on a Vec. If it is, return
|
|
|
|
|
// the Vec being pushed into and the item being pushed
|
|
|
|
|
fn get_vec_push<'tcx>(cx: &LateContext<'tcx>, stmt: &'tcx Stmt<'_>) -> Option<(&'tcx Expr<'tcx>, &'tcx Expr<'tcx>)> {
|
|
|
|
|
if_chain! {
|
|
|
|
|
// Extract method being called
|
|
|
|
|
if let StmtKind::Semi(semi_stmt) = &stmt.kind;
|
|
|
|
|
if let ExprKind::MethodCall(path, _, args, _) = &semi_stmt.kind;
|
|
|
|
|
// Figure out the parameters for the method call
|
|
|
|
|
if let Some(self_expr) = args.get(0);
|
|
|
|
|
if let Some(pushed_item) = args.get(1);
|
|
|
|
|
// Check that the method being called is push() on a Vec
|
2020-09-24 12:49:22 +00:00
|
|
|
|
if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(self_expr), sym!(vec_type));
|
2020-08-11 13:43:21 +00:00
|
|
|
|
if path.ident.name.as_str() == "push";
|
|
|
|
|
then {
|
|
|
|
|
return Some((self_expr, pushed_item))
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
None
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Detects for loop pushing the same item into a Vec
|
|
|
|
|
fn detect_same_item_push<'tcx>(
|
|
|
|
|
cx: &LateContext<'tcx>,
|
|
|
|
|
pat: &'tcx Pat<'_>,
|
|
|
|
|
_: &'tcx Expr<'_>,
|
|
|
|
|
body: &'tcx Expr<'_>,
|
|
|
|
|
_: &'tcx Expr<'_>,
|
|
|
|
|
) {
|
2020-09-10 15:47:07 +00:00
|
|
|
|
fn emit_lint(cx: &LateContext<'_>, vec: &Expr<'_>, pushed_item: &Expr<'_>) {
|
|
|
|
|
let vec_str = snippet_with_macro_callsite(cx, vec.span, "");
|
|
|
|
|
let item_str = snippet_with_macro_callsite(cx, pushed_item.span, "");
|
|
|
|
|
|
|
|
|
|
span_lint_and_help(
|
|
|
|
|
cx,
|
|
|
|
|
SAME_ITEM_PUSH,
|
|
|
|
|
vec.span,
|
|
|
|
|
"it looks like the same item is being pushed into this Vec",
|
|
|
|
|
None,
|
|
|
|
|
&format!(
|
|
|
|
|
"try using vec![{};SIZE] or {}.resize(NEW_SIZE, {})",
|
|
|
|
|
item_str, vec_str, item_str
|
|
|
|
|
),
|
|
|
|
|
)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if !matches!(pat.kind, PatKind::Wild) {
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2020-08-11 13:43:21 +00:00
|
|
|
|
// Determine whether it is safe to lint the body
|
|
|
|
|
let mut same_item_push_visitor = SameItemPushVisitor {
|
|
|
|
|
should_lint: true,
|
|
|
|
|
vec_push: None,
|
|
|
|
|
cx,
|
|
|
|
|
};
|
|
|
|
|
walk_expr(&mut same_item_push_visitor, body);
|
|
|
|
|
if same_item_push_visitor.should_lint {
|
|
|
|
|
if let Some((vec, pushed_item)) = same_item_push_visitor.vec_push {
|
2020-09-10 15:47:07 +00:00
|
|
|
|
let vec_ty = cx.typeck_results().expr_ty(vec);
|
|
|
|
|
let ty = vec_ty.walk().nth(1).unwrap().expect_ty();
|
|
|
|
|
if cx
|
|
|
|
|
.tcx
|
|
|
|
|
.lang_items()
|
|
|
|
|
.clone_trait()
|
|
|
|
|
.map_or(false, |id| implements_trait(cx, ty, id, &[]))
|
|
|
|
|
{
|
|
|
|
|
// Make sure that the push does not involve possibly mutating values
|
|
|
|
|
match pushed_item.kind {
|
|
|
|
|
ExprKind::Path(ref qpath) => {
|
|
|
|
|
match qpath_res(cx, qpath, pushed_item.hir_id) {
|
|
|
|
|
// immutable bindings that are initialized with literal or constant
|
|
|
|
|
Res::Local(hir_id) => {
|
|
|
|
|
if_chain! {
|
|
|
|
|
let node = cx.tcx.hir().get(hir_id);
|
|
|
|
|
if let Node::Binding(pat) = node;
|
|
|
|
|
if let PatKind::Binding(bind_ann, ..) = pat.kind;
|
|
|
|
|
if !matches!(bind_ann, BindingAnnotation::RefMut | BindingAnnotation::Mutable);
|
|
|
|
|
let parent_node = cx.tcx.hir().get_parent_node(hir_id);
|
|
|
|
|
if let Some(Node::Local(parent_let_expr)) = cx.tcx.hir().find(parent_node);
|
|
|
|
|
if let Some(init) = parent_let_expr.init;
|
|
|
|
|
then {
|
|
|
|
|
match init.kind {
|
|
|
|
|
// immutable bindings that are initialized with literal
|
|
|
|
|
ExprKind::Lit(..) => emit_lint(cx, vec, pushed_item),
|
|
|
|
|
// immutable bindings that are initialized with constant
|
|
|
|
|
ExprKind::Path(ref path) => {
|
|
|
|
|
if let Res::Def(DefKind::Const, ..) = qpath_res(cx, path, init.hir_id) {
|
|
|
|
|
emit_lint(cx, vec, pushed_item);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
_ => {},
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
},
|
|
|
|
|
// constant
|
|
|
|
|
Res::Def(DefKind::Const, ..) => emit_lint(cx, vec, pushed_item),
|
|
|
|
|
_ => {},
|
2020-08-28 14:10:16 +00:00
|
|
|
|
}
|
2020-09-10 15:47:07 +00:00
|
|
|
|
},
|
|
|
|
|
ExprKind::Lit(..) => emit_lint(cx, vec, pushed_item),
|
|
|
|
|
_ => {},
|
2020-08-11 13:43:21 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2019-01-31 01:15:29 +00:00
|
|
|
|
/// Checks for looping over a range and then indexing a sequence with it.
|
2016-01-14 19:58:32 +00:00
|
|
|
|
/// The iteratee must be a range literal.
|
2019-01-13 15:19:02 +00:00
|
|
|
|
#[allow(clippy::too_many_lines)]
|
2020-06-25 20:41:36 +00:00
|
|
|
|
fn check_for_loop_range<'tcx>(
|
|
|
|
|
cx: &LateContext<'tcx>,
|
2019-12-27 07:12:26 +00:00
|
|
|
|
pat: &'tcx Pat<'_>,
|
|
|
|
|
arg: &'tcx Expr<'_>,
|
|
|
|
|
body: &'tcx Expr<'_>,
|
|
|
|
|
expr: &'tcx Expr<'_>,
|
2016-12-21 11:14:54 +00:00
|
|
|
|
) {
|
2017-08-09 07:30:56 +00:00
|
|
|
|
if let Some(higher::Range {
|
2017-11-04 19:55:56 +00:00
|
|
|
|
start: Some(start),
|
|
|
|
|
ref end,
|
|
|
|
|
limits,
|
2020-08-04 13:24:13 +00:00
|
|
|
|
}) = higher::range(arg)
|
2017-08-09 07:30:56 +00:00
|
|
|
|
{
|
2016-01-14 19:58:32 +00:00
|
|
|
|
// the var must be a single name
|
2019-09-27 15:16:06 +00:00
|
|
|
|
if let PatKind::Binding(_, canonical_id, ident, _) = pat.kind {
|
2016-01-14 19:58:32 +00:00
|
|
|
|
let mut visitor = VarVisitor {
|
2018-03-15 15:07:15 +00:00
|
|
|
|
cx,
|
2017-09-12 12:26:40 +00:00
|
|
|
|
var: canonical_id,
|
2018-09-11 23:34:52 +00:00
|
|
|
|
indexed_mut: FxHashSet::default(),
|
|
|
|
|
indexed_indirectly: FxHashMap::default(),
|
|
|
|
|
indexed_directly: FxHashMap::default(),
|
|
|
|
|
referenced: FxHashSet::default(),
|
2016-01-14 19:58:32 +00:00
|
|
|
|
nonindex: false,
|
2017-11-07 13:41:54 +00:00
|
|
|
|
prefer_mutable: false,
|
2016-01-14 19:58:32 +00:00
|
|
|
|
};
|
|
|
|
|
walk_expr(&mut visitor, body);
|
2016-02-13 21:09:17 +00:00
|
|
|
|
|
2017-10-08 15:34:31 +00:00
|
|
|
|
// linting condition: we only indexed one variable, and indexed it directly
|
2017-11-07 14:32:52 +00:00
|
|
|
|
if visitor.indexed_indirectly.is_empty() && visitor.indexed_directly.len() == 1 {
|
2018-10-19 20:34:16 +00:00
|
|
|
|
let (indexed, (indexed_extent, indexed_ty)) = visitor
|
2017-11-04 19:55:56 +00:00
|
|
|
|
.indexed_directly
|
|
|
|
|
.into_iter()
|
|
|
|
|
.next()
|
|
|
|
|
.expect("already checked that we have exactly 1 element");
|
2016-01-14 19:58:32 +00:00
|
|
|
|
|
2016-02-13 21:09:17 +00:00
|
|
|
|
// ensure that the indexed variable was declared before the loop, see #601
|
2016-03-07 22:24:11 +00:00
|
|
|
|
if let Some(indexed_extent) = indexed_extent {
|
2019-02-24 18:43:15 +00:00
|
|
|
|
let parent_id = cx.tcx.hir().get_parent_item(expr.hir_id);
|
2019-07-06 03:52:51 +00:00
|
|
|
|
let parent_def_id = cx.tcx.hir().local_def_id(parent_id);
|
2017-09-04 14:10:36 +00:00
|
|
|
|
let region_scope_tree = cx.tcx.region_scope_tree(parent_def_id);
|
|
|
|
|
let pat_extent = region_scope_tree.var_scope(pat.hir_id.local_id);
|
|
|
|
|
if region_scope_tree.is_subscope_of(indexed_extent, pat_extent) {
|
2016-03-07 22:24:11 +00:00
|
|
|
|
return;
|
|
|
|
|
}
|
2016-02-13 21:09:17 +00:00
|
|
|
|
}
|
2019-02-20 08:10:25 +00:00
|
|
|
|
|
|
|
|
|
// don't lint if the container that is indexed does not have .iter() method
|
|
|
|
|
let has_iter = has_iter_method(cx, indexed_ty);
|
|
|
|
|
if has_iter.is_none() {
|
|
|
|
|
return;
|
|
|
|
|
}
|
2016-02-13 21:09:17 +00:00
|
|
|
|
|
2017-08-09 07:30:56 +00:00
|
|
|
|
// don't lint if the container that is indexed into is also used without
|
|
|
|
|
// indexing
|
2017-07-10 13:30:28 +00:00
|
|
|
|
if visitor.referenced.contains(&indexed) {
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2019-09-09 15:01:01 +00:00
|
|
|
|
let starts_at_zero = is_integer_const(cx, start, 0);
|
2016-01-14 19:58:32 +00:00
|
|
|
|
|
2016-07-01 17:31:14 +00:00
|
|
|
|
let skip = if starts_at_zero {
|
2018-08-21 10:46:18 +00:00
|
|
|
|
String::new()
|
2020-10-09 10:45:29 +00:00
|
|
|
|
} else if visitor.indexed_mut.contains(&indexed) && contains_name(indexed, start) {
|
|
|
|
|
return;
|
2016-01-30 12:48:39 +00:00
|
|
|
|
} else {
|
2016-07-01 17:31:14 +00:00
|
|
|
|
format!(".skip({})", snippet(cx, start.span, ".."))
|
2016-01-14 19:58:32 +00:00
|
|
|
|
};
|
|
|
|
|
|
2018-10-15 03:07:21 +00:00
|
|
|
|
let mut end_is_start_plus_val = false;
|
|
|
|
|
|
2016-08-01 14:59:14 +00:00
|
|
|
|
let take = if let Some(end) = *end {
|
2018-10-15 03:07:21 +00:00
|
|
|
|
let mut take_expr = end;
|
|
|
|
|
|
2019-09-27 15:16:06 +00:00
|
|
|
|
if let ExprKind::Binary(ref op, ref left, ref right) = end.kind {
|
2018-10-15 03:07:21 +00:00
|
|
|
|
if let BinOpKind::Add = op.node {
|
|
|
|
|
let start_equal_left = SpanlessEq::new(cx).eq_expr(start, left);
|
|
|
|
|
let start_equal_right = SpanlessEq::new(cx).eq_expr(start, right);
|
|
|
|
|
|
|
|
|
|
if start_equal_left {
|
|
|
|
|
take_expr = right;
|
|
|
|
|
} else if start_equal_right {
|
|
|
|
|
take_expr = left;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
end_is_start_plus_val = start_equal_left | start_equal_right;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2018-10-19 20:34:16 +00:00
|
|
|
|
if is_len_call(end, indexed) || is_end_eq_array_len(cx, end, limits, indexed_ty) {
|
2018-08-21 10:46:18 +00:00
|
|
|
|
String::new()
|
2020-10-09 10:45:29 +00:00
|
|
|
|
} else if visitor.indexed_mut.contains(&indexed) && contains_name(indexed, take_expr) {
|
|
|
|
|
return;
|
2016-02-29 08:45:36 +00:00
|
|
|
|
} else {
|
2016-07-01 17:31:14 +00:00
|
|
|
|
match limits {
|
|
|
|
|
ast::RangeLimits::Closed => {
|
2018-10-15 03:07:21 +00:00
|
|
|
|
let take_expr = sugg::Sugg::hir(cx, take_expr, "<count>");
|
|
|
|
|
format!(".take({})", take_expr + sugg::ONE)
|
2016-12-20 17:21:30 +00:00
|
|
|
|
},
|
2018-10-15 03:07:21 +00:00
|
|
|
|
ast::RangeLimits::HalfOpen => format!(".take({})", snippet(cx, take_expr.span, "..")),
|
2016-07-01 17:31:14 +00:00
|
|
|
|
}
|
2016-01-14 19:58:32 +00:00
|
|
|
|
}
|
|
|
|
|
} else {
|
2018-08-21 10:46:18 +00:00
|
|
|
|
String::new()
|
2016-01-14 19:58:32 +00:00
|
|
|
|
};
|
|
|
|
|
|
2017-11-07 13:41:54 +00:00
|
|
|
|
let (ref_mut, method) = if visitor.indexed_mut.contains(&indexed) {
|
|
|
|
|
("mut ", "iter_mut")
|
|
|
|
|
} else {
|
|
|
|
|
("", "iter")
|
|
|
|
|
};
|
|
|
|
|
|
2018-10-15 03:07:21 +00:00
|
|
|
|
let take_is_empty = take.is_empty();
|
|
|
|
|
let mut method_1 = take;
|
|
|
|
|
let mut method_2 = skip;
|
|
|
|
|
|
|
|
|
|
if end_is_start_plus_val {
|
|
|
|
|
mem::swap(&mut method_1, &mut method_2);
|
|
|
|
|
}
|
|
|
|
|
|
2016-01-14 19:58:32 +00:00
|
|
|
|
if visitor.nonindex {
|
2017-09-05 09:33:04 +00:00
|
|
|
|
span_lint_and_then(
|
|
|
|
|
cx,
|
|
|
|
|
NEEDLESS_RANGE_LOOP,
|
|
|
|
|
expr.span,
|
2018-06-28 13:46:58 +00:00
|
|
|
|
&format!("the loop variable `{}` is used to index `{}`", ident.name, indexed),
|
2020-04-17 06:08:00 +00:00
|
|
|
|
|diag| {
|
2017-09-05 09:33:04 +00:00
|
|
|
|
multispan_sugg(
|
2020-04-17 06:08:00 +00:00
|
|
|
|
diag,
|
2020-05-17 15:36:26 +00:00
|
|
|
|
"consider using an iterator",
|
2017-09-05 09:33:04 +00:00
|
|
|
|
vec![
|
2018-06-28 13:46:58 +00:00
|
|
|
|
(pat.span, format!("({}, <item>)", ident.name)),
|
2018-11-27 20:14:15 +00:00
|
|
|
|
(
|
|
|
|
|
arg.span,
|
|
|
|
|
format!("{}.{}().enumerate(){}{}", indexed, method, method_1, method_2),
|
|
|
|
|
),
|
2017-09-05 09:33:04 +00:00
|
|
|
|
],
|
|
|
|
|
);
|
|
|
|
|
},
|
|
|
|
|
);
|
2016-01-14 19:58:32 +00:00
|
|
|
|
} else {
|
2018-10-15 03:07:21 +00:00
|
|
|
|
let repl = if starts_at_zero && take_is_empty {
|
2017-11-07 13:41:54 +00:00
|
|
|
|
format!("&{}{}", ref_mut, indexed)
|
2016-01-30 12:48:39 +00:00
|
|
|
|
} else {
|
2018-10-15 03:07:21 +00:00
|
|
|
|
format!("{}.{}(){}{}", indexed, method, method_1, method_2)
|
2016-01-14 19:58:32 +00:00
|
|
|
|
};
|
|
|
|
|
|
2017-09-05 09:33:04 +00:00
|
|
|
|
span_lint_and_then(
|
|
|
|
|
cx,
|
|
|
|
|
NEEDLESS_RANGE_LOOP,
|
|
|
|
|
expr.span,
|
2018-11-27 20:14:15 +00:00
|
|
|
|
&format!(
|
|
|
|
|
"the loop variable `{}` is only used to index `{}`.",
|
|
|
|
|
ident.name, indexed
|
|
|
|
|
),
|
2020-04-17 06:08:00 +00:00
|
|
|
|
|diag| {
|
2017-09-05 09:33:04 +00:00
|
|
|
|
multispan_sugg(
|
2020-04-17 06:08:00 +00:00
|
|
|
|
diag,
|
2020-05-17 15:36:26 +00:00
|
|
|
|
"consider using an iterator",
|
2017-09-05 09:33:04 +00:00
|
|
|
|
vec![(pat.span, "<item>".to_string()), (arg.span, repl)],
|
|
|
|
|
);
|
|
|
|
|
},
|
|
|
|
|
);
|
2015-11-18 11:35:18 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
2016-01-14 19:58:32 +00:00
|
|
|
|
}
|
|
|
|
|
|
2020-08-11 13:43:21 +00:00
|
|
|
|
fn is_len_call(expr: &Expr<'_>, var: Symbol) -> bool {
|
2017-10-23 19:18:02 +00:00
|
|
|
|
if_chain! {
|
2020-06-09 21:44:04 +00:00
|
|
|
|
if let ExprKind::MethodCall(ref method, _, ref len_args, _) = expr.kind;
|
2017-10-23 19:18:02 +00:00
|
|
|
|
if len_args.len() == 1;
|
2019-05-17 21:53:54 +00:00
|
|
|
|
if method.ident.name == sym!(len);
|
2019-09-27 15:16:06 +00:00
|
|
|
|
if let ExprKind::Path(QPath::Resolved(_, ref path)) = len_args[0].kind;
|
2017-10-23 19:18:02 +00:00
|
|
|
|
if path.segments.len() == 1;
|
2018-06-28 13:46:58 +00:00
|
|
|
|
if path.segments[0].ident.name == var;
|
2017-10-23 19:18:02 +00:00
|
|
|
|
then {
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
}
|
2015-11-18 11:35:18 +00:00
|
|
|
|
|
2016-01-14 19:58:32 +00:00
|
|
|
|
false
|
|
|
|
|
}
|
|
|
|
|
|
2019-06-19 10:16:42 +00:00
|
|
|
|
fn is_end_eq_array_len<'tcx>(
|
2020-06-25 20:41:36 +00:00
|
|
|
|
cx: &LateContext<'tcx>,
|
2019-12-27 07:12:26 +00:00
|
|
|
|
end: &Expr<'_>,
|
2019-06-19 10:16:42 +00:00
|
|
|
|
limits: ast::RangeLimits,
|
|
|
|
|
indexed_ty: Ty<'tcx>,
|
|
|
|
|
) -> bool {
|
2018-10-19 20:34:16 +00:00
|
|
|
|
if_chain! {
|
2019-09-27 15:16:06 +00:00
|
|
|
|
if let ExprKind::Lit(ref lit) = end.kind;
|
2018-10-19 20:34:16 +00:00
|
|
|
|
if let ast::LitKind::Int(end_int, _) = lit.node;
|
2020-08-03 22:18:29 +00:00
|
|
|
|
if let ty::Array(_, arr_len_const) = indexed_ty.kind();
|
2019-08-06 12:20:41 +00:00
|
|
|
|
if let Some(arr_len) = arr_len_const.try_eval_usize(cx.tcx, cx.param_env);
|
2018-10-19 20:34:16 +00:00
|
|
|
|
then {
|
|
|
|
|
return match limits {
|
|
|
|
|
ast::RangeLimits::Closed => end_int + 1 >= arr_len.into(),
|
|
|
|
|
ast::RangeLimits::HalfOpen => end_int >= arr_len.into(),
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
false
|
|
|
|
|
}
|
|
|
|
|
|
2020-06-25 20:41:36 +00:00
|
|
|
|
fn lint_iter_method(cx: &LateContext<'_>, args: &[Expr<'_>], arg: &Expr<'_>, method_name: &str) {
|
2018-11-27 14:13:57 +00:00
|
|
|
|
let mut applicability = Applicability::MachineApplicable;
|
|
|
|
|
let object = snippet_with_applicability(cx, args[0].span, "_", &mut applicability);
|
2018-11-27 20:14:15 +00:00
|
|
|
|
let muta = if method_name == "iter_mut" { "mut " } else { "" };
|
2017-08-09 07:30:56 +00:00
|
|
|
|
span_lint_and_sugg(
|
|
|
|
|
cx,
|
|
|
|
|
EXPLICIT_ITER_LOOP,
|
|
|
|
|
arg.span,
|
2018-09-03 07:19:59 +00:00
|
|
|
|
"it is more concise to loop over references to containers instead of using explicit \
|
2017-09-05 09:33:04 +00:00
|
|
|
|
iteration methods",
|
2017-08-09 07:30:56 +00:00
|
|
|
|
"to write this more concisely, try",
|
|
|
|
|
format!("&{}{}", muta, object),
|
2018-11-27 14:13:57 +00:00
|
|
|
|
applicability,
|
2017-08-09 07:30:56 +00:00
|
|
|
|
)
|
2017-01-09 15:59:55 +00:00
|
|
|
|
}
|
|
|
|
|
|
2020-06-25 20:41:36 +00:00
|
|
|
|
fn check_for_loop_arg(cx: &LateContext<'_>, pat: &Pat<'_>, arg: &Expr<'_>, expr: &Expr<'_>) {
|
2016-01-29 07:34:09 +00:00
|
|
|
|
let mut next_loop_linted = false; // whether or not ITER_NEXT_LOOP lint was used
|
2020-06-09 21:44:04 +00:00
|
|
|
|
if let ExprKind::MethodCall(ref method, _, ref args, _) = arg.kind {
|
2015-11-18 11:35:18 +00:00
|
|
|
|
// just the receiver, no arguments
|
|
|
|
|
if args.len() == 1 {
|
2018-06-28 13:46:58 +00:00
|
|
|
|
let method_name = &*method.ident.as_str();
|
2015-11-18 11:35:18 +00:00
|
|
|
|
// check for looping over x.iter() or x.iter_mut(), could use &x or &mut x
|
2017-01-09 15:59:55 +00:00
|
|
|
|
if method_name == "iter" || method_name == "iter_mut" {
|
2015-11-18 11:35:18 +00:00
|
|
|
|
if is_ref_iterable_type(cx, &args[0]) {
|
2017-07-10 08:17:40 +00:00
|
|
|
|
lint_iter_method(cx, args, arg, method_name);
|
2017-01-09 15:59:55 +00:00
|
|
|
|
}
|
2019-05-17 21:53:54 +00:00
|
|
|
|
} else if method_name == "into_iter" && match_trait_method(cx, arg, &paths::INTO_ITERATOR) {
|
2020-07-17 08:47:04 +00:00
|
|
|
|
let receiver_ty = cx.typeck_results().expr_ty(&args[0]);
|
|
|
|
|
let receiver_ty_adjusted = cx.typeck_results().expr_ty_adjusted(&args[0]);
|
2020-06-09 14:36:01 +00:00
|
|
|
|
if TyS::same_type(receiver_ty, receiver_ty_adjusted) {
|
2018-11-27 14:13:57 +00:00
|
|
|
|
let mut applicability = Applicability::MachineApplicable;
|
|
|
|
|
let object = snippet_with_applicability(cx, args[0].span, "_", &mut applicability);
|
2017-08-09 07:30:56 +00:00
|
|
|
|
span_lint_and_sugg(
|
|
|
|
|
cx,
|
|
|
|
|
EXPLICIT_INTO_ITER_LOOP,
|
|
|
|
|
arg.span,
|
2018-09-03 07:19:59 +00:00
|
|
|
|
"it is more concise to loop over containers instead of using explicit \
|
2020-01-06 06:30:43 +00:00
|
|
|
|
iteration methods",
|
2017-08-09 07:30:56 +00:00
|
|
|
|
"to write this more concisely, try",
|
|
|
|
|
object.to_string(),
|
2018-11-27 14:13:57 +00:00
|
|
|
|
applicability,
|
2017-08-09 07:30:56 +00:00
|
|
|
|
);
|
2020-01-01 05:09:09 +00:00
|
|
|
|
} else {
|
|
|
|
|
let ref_receiver_ty = cx.tcx.mk_ref(
|
|
|
|
|
cx.tcx.lifetimes.re_erased,
|
|
|
|
|
ty::TypeAndMut {
|
|
|
|
|
ty: receiver_ty,
|
|
|
|
|
mutbl: Mutability::Not,
|
|
|
|
|
},
|
|
|
|
|
);
|
2020-06-09 14:36:01 +00:00
|
|
|
|
if TyS::same_type(receiver_ty_adjusted, ref_receiver_ty) {
|
2020-01-01 05:09:09 +00:00
|
|
|
|
lint_iter_method(cx, args, arg, method_name)
|
|
|
|
|
}
|
2015-11-18 11:35:18 +00:00
|
|
|
|
}
|
2019-05-17 21:53:54 +00:00
|
|
|
|
} else if method_name == "next" && match_trait_method(cx, arg, &paths::ITERATOR) {
|
2017-08-09 07:30:56 +00:00
|
|
|
|
span_lint(
|
|
|
|
|
cx,
|
|
|
|
|
ITER_NEXT_LOOP,
|
|
|
|
|
expr.span,
|
|
|
|
|
"you are iterating over `Iterator::next()` which is an Option; this will compile but is \
|
2020-05-17 15:36:26 +00:00
|
|
|
|
probably not what you want",
|
2017-08-09 07:30:56 +00:00
|
|
|
|
);
|
2016-01-29 07:34:09 +00:00
|
|
|
|
next_loop_linted = true;
|
2015-11-18 11:35:18 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
2016-01-29 07:34:09 +00:00
|
|
|
|
if !next_loop_linted {
|
2016-01-29 23:15:57 +00:00
|
|
|
|
check_arg_type(cx, pat, arg);
|
2016-01-29 07:34:09 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
2015-11-18 11:35:18 +00:00
|
|
|
|
|
2019-03-10 17:19:47 +00:00
|
|
|
|
/// Checks for `for` loops over `Option`s and `Result`s.
|
2020-06-25 20:41:36 +00:00
|
|
|
|
fn check_arg_type(cx: &LateContext<'_>, pat: &Pat<'_>, arg: &Expr<'_>) {
|
2020-07-17 08:47:04 +00:00
|
|
|
|
let ty = cx.typeck_results().expr_ty(arg);
|
2020-04-12 13:23:07 +00:00
|
|
|
|
if is_type_diagnostic_item(cx, ty, sym!(option_type)) {
|
2020-01-27 01:56:22 +00:00
|
|
|
|
span_lint_and_help(
|
2017-08-09 07:30:56 +00:00
|
|
|
|
cx,
|
2020-05-17 15:36:26 +00:00
|
|
|
|
FOR_LOOPS_OVER_FALLIBLES,
|
2017-08-09 07:30:56 +00:00
|
|
|
|
arg.span,
|
|
|
|
|
&format!(
|
|
|
|
|
"for loop over `{0}`, which is an `Option`. This is more readably written as an \
|
2020-05-17 15:36:26 +00:00
|
|
|
|
`if let` statement.",
|
2017-08-09 07:30:56 +00:00
|
|
|
|
snippet(cx, arg.span, "_")
|
|
|
|
|
),
|
2020-04-18 10:28:29 +00:00
|
|
|
|
None,
|
2017-08-09 07:30:56 +00:00
|
|
|
|
&format!(
|
|
|
|
|
"consider replacing `for {0} in {1}` with `if let Some({0}) = {1}`",
|
|
|
|
|
snippet(cx, pat.span, "_"),
|
|
|
|
|
snippet(cx, arg.span, "_")
|
|
|
|
|
),
|
|
|
|
|
);
|
2020-04-12 13:23:07 +00:00
|
|
|
|
} else if is_type_diagnostic_item(cx, ty, sym!(result_type)) {
|
2020-01-27 01:56:22 +00:00
|
|
|
|
span_lint_and_help(
|
2017-08-09 07:30:56 +00:00
|
|
|
|
cx,
|
2020-05-17 15:36:26 +00:00
|
|
|
|
FOR_LOOPS_OVER_FALLIBLES,
|
2017-08-09 07:30:56 +00:00
|
|
|
|
arg.span,
|
|
|
|
|
&format!(
|
|
|
|
|
"for loop over `{0}`, which is a `Result`. This is more readably written as an \
|
2020-05-17 15:36:26 +00:00
|
|
|
|
`if let` statement.",
|
2017-08-09 07:30:56 +00:00
|
|
|
|
snippet(cx, arg.span, "_")
|
|
|
|
|
),
|
2020-04-18 10:28:29 +00:00
|
|
|
|
None,
|
2017-08-09 07:30:56 +00:00
|
|
|
|
&format!(
|
|
|
|
|
"consider replacing `for {0} in {1}` with `if let Ok({0}) = {1}`",
|
|
|
|
|
snippet(cx, pat.span, "_"),
|
|
|
|
|
snippet(cx, arg.span, "_")
|
|
|
|
|
),
|
|
|
|
|
);
|
2016-01-29 23:15:57 +00:00
|
|
|
|
}
|
2016-01-14 19:58:32 +00:00
|
|
|
|
}
|
|
|
|
|
|
2020-10-23 20:16:59 +00:00
|
|
|
|
// To trigger the EXPLICIT_COUNTER_LOOP lint, a variable must be
|
|
|
|
|
// incremented exactly once in the loop body, and initialized to zero
|
|
|
|
|
// at the start of the loop.
|
2020-06-25 20:41:36 +00:00
|
|
|
|
fn check_for_loop_explicit_counter<'tcx>(
|
|
|
|
|
cx: &LateContext<'tcx>,
|
2019-12-27 07:12:26 +00:00
|
|
|
|
pat: &'tcx Pat<'_>,
|
|
|
|
|
arg: &'tcx Expr<'_>,
|
|
|
|
|
body: &'tcx Expr<'_>,
|
|
|
|
|
expr: &'tcx Expr<'_>,
|
2016-12-21 11:14:54 +00:00
|
|
|
|
) {
|
2015-11-18 11:35:18 +00:00
|
|
|
|
// Look for variables that are incremented once per loop iteration.
|
2020-10-23 20:16:59 +00:00
|
|
|
|
let mut increment_visitor = IncrementVisitor::new(cx);
|
|
|
|
|
walk_expr(&mut increment_visitor, body);
|
2015-11-18 11:35:18 +00:00
|
|
|
|
|
|
|
|
|
// For each candidate, check the parent block to see if
|
|
|
|
|
// it's initialized to zero at the start of the loop.
|
2019-04-28 07:11:20 +00:00
|
|
|
|
if let Some(block) = get_enclosing_block(&cx, expr.hir_id) {
|
2020-10-23 20:16:59 +00:00
|
|
|
|
for id in increment_visitor.into_results() {
|
|
|
|
|
let mut initialize_visitor = InitializeVisitor::new(cx, expr, id);
|
|
|
|
|
walk_block(&mut initialize_visitor, block);
|
|
|
|
|
|
|
|
|
|
if_chain! {
|
|
|
|
|
if let Some((name, initializer)) = initialize_visitor.get_result();
|
|
|
|
|
if is_integer_const(cx, initializer, 0);
|
|
|
|
|
then {
|
2019-04-28 07:11:20 +00:00
|
|
|
|
let mut applicability = Applicability::MachineApplicable;
|
2019-10-18 05:15:54 +00:00
|
|
|
|
|
2020-10-23 20:16:59 +00:00
|
|
|
|
let for_span = get_span_of_entire_for_loop(expr);
|
2019-10-18 05:15:54 +00:00
|
|
|
|
|
2019-04-28 07:11:20 +00:00
|
|
|
|
span_lint_and_sugg(
|
|
|
|
|
cx,
|
|
|
|
|
EXPLICIT_COUNTER_LOOP,
|
2019-10-18 05:15:54 +00:00
|
|
|
|
for_span.with_hi(arg.span.hi()),
|
2019-04-28 07:11:20 +00:00
|
|
|
|
&format!("the variable `{}` is used as a loop counter.", name),
|
|
|
|
|
"consider using",
|
|
|
|
|
format!(
|
|
|
|
|
"for ({}, {}) in {}.enumerate()",
|
|
|
|
|
name,
|
|
|
|
|
snippet_with_applicability(cx, pat.span, "item", &mut applicability),
|
2019-10-18 04:03:27 +00:00
|
|
|
|
make_iterator_snippet(cx, arg, &mut applicability),
|
2019-04-28 07:11:20 +00:00
|
|
|
|
),
|
|
|
|
|
applicability,
|
|
|
|
|
);
|
2015-11-18 11:35:18 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2019-10-18 04:03:27 +00:00
|
|
|
|
/// If `arg` was the argument to a `for` loop, return the "cleanest" way of writing the
|
|
|
|
|
/// actual `Iterator` that the loop uses.
|
2020-06-25 20:41:36 +00:00
|
|
|
|
fn make_iterator_snippet(cx: &LateContext<'_>, arg: &Expr<'_>, applic_ref: &mut Applicability) -> String {
|
2020-07-17 08:47:04 +00:00
|
|
|
|
let impls_iterator = get_trait_def_id(cx, &paths::ITERATOR).map_or(false, |id| {
|
|
|
|
|
implements_trait(cx, cx.typeck_results().expr_ty(arg), id, &[])
|
|
|
|
|
});
|
2019-10-18 04:03:27 +00:00
|
|
|
|
if impls_iterator {
|
|
|
|
|
format!(
|
|
|
|
|
"{}",
|
|
|
|
|
sugg::Sugg::hir_with_applicability(cx, arg, "_", applic_ref).maybe_par()
|
|
|
|
|
)
|
|
|
|
|
} else {
|
|
|
|
|
// (&x).into_iter() ==> x.iter()
|
|
|
|
|
// (&mut x).into_iter() ==> x.iter_mut()
|
|
|
|
|
match &arg.kind {
|
2019-11-27 22:30:10 +00:00
|
|
|
|
ExprKind::AddrOf(BorrowKind::Ref, mutability, arg_inner)
|
2020-07-17 08:47:04 +00:00
|
|
|
|
if has_iter_method(cx, cx.typeck_results().expr_ty(&arg_inner)).is_some() =>
|
2019-11-25 14:20:10 +00:00
|
|
|
|
{
|
2019-10-18 04:03:27 +00:00
|
|
|
|
let meth_name = match mutability {
|
2019-12-21 18:38:45 +00:00
|
|
|
|
Mutability::Mut => "iter_mut",
|
|
|
|
|
Mutability::Not => "iter",
|
2019-10-18 04:03:27 +00:00
|
|
|
|
};
|
|
|
|
|
format!(
|
|
|
|
|
"{}.{}()",
|
|
|
|
|
sugg::Sugg::hir_with_applicability(cx, &arg_inner, "_", applic_ref).maybe_par(),
|
|
|
|
|
meth_name,
|
|
|
|
|
)
|
2019-11-25 14:20:10 +00:00
|
|
|
|
}
|
2019-10-18 04:03:27 +00:00
|
|
|
|
_ => format!(
|
|
|
|
|
"{}.into_iter()",
|
|
|
|
|
sugg::Sugg::hir_with_applicability(cx, arg, "_", applic_ref).maybe_par()
|
|
|
|
|
),
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2019-01-31 01:15:29 +00:00
|
|
|
|
/// Checks for the `FOR_KV_MAP` lint.
|
2020-06-25 20:41:36 +00:00
|
|
|
|
fn check_for_loop_over_map_kv<'tcx>(
|
|
|
|
|
cx: &LateContext<'tcx>,
|
2019-12-27 07:12:26 +00:00
|
|
|
|
pat: &'tcx Pat<'_>,
|
|
|
|
|
arg: &'tcx Expr<'_>,
|
|
|
|
|
body: &'tcx Expr<'_>,
|
|
|
|
|
expr: &'tcx Expr<'_>,
|
2016-12-21 11:14:54 +00:00
|
|
|
|
) {
|
2016-07-01 18:55:45 +00:00
|
|
|
|
let pat_span = pat.span;
|
|
|
|
|
|
2019-09-27 15:16:06 +00:00
|
|
|
|
if let PatKind::Tuple(ref pat, _) = pat.kind {
|
2016-01-19 20:10:00 +00:00
|
|
|
|
if pat.len() == 2 {
|
2017-01-10 07:33:20 +00:00
|
|
|
|
let arg_span = arg.span;
|
2020-08-03 22:18:29 +00:00
|
|
|
|
let (new_pat_span, kind, ty, mutbl) = match *cx.typeck_results().expr_ty(arg).kind() {
|
2019-09-27 15:16:06 +00:00
|
|
|
|
ty::Ref(_, ty, mutbl) => match (&pat[0].kind, &pat[1].kind) {
|
2018-05-11 06:37:48 +00:00
|
|
|
|
(key, _) if pat_is_wild(key, body) => (pat[1].span, "value", ty, mutbl),
|
2019-12-21 18:38:45 +00:00
|
|
|
|
(_, value) if pat_is_wild(value, body) => (pat[0].span, "key", ty, Mutability::Not),
|
2017-11-04 19:55:56 +00:00
|
|
|
|
_ => return,
|
2017-01-10 07:33:20 +00:00
|
|
|
|
},
|
2016-02-24 16:38:57 +00:00
|
|
|
|
_ => return,
|
2016-01-19 20:10:00 +00:00
|
|
|
|
};
|
2017-01-10 07:33:20 +00:00
|
|
|
|
let mutbl = match mutbl {
|
2019-12-21 18:38:45 +00:00
|
|
|
|
Mutability::Not => "",
|
|
|
|
|
Mutability::Mut => "_mut",
|
2017-01-10 07:33:20 +00:00
|
|
|
|
};
|
2019-09-27 15:16:06 +00:00
|
|
|
|
let arg = match arg.kind {
|
2019-11-27 22:30:10 +00:00
|
|
|
|
ExprKind::AddrOf(BorrowKind::Ref, _, ref expr) => &**expr,
|
2017-01-10 07:33:20 +00:00
|
|
|
|
_ => arg,
|
2016-01-19 20:10:00 +00:00
|
|
|
|
};
|
|
|
|
|
|
2020-04-23 06:09:42 +00:00
|
|
|
|
if is_type_diagnostic_item(cx, ty, sym!(hashmap_type)) || match_type(cx, ty, &paths::BTREEMAP) {
|
2017-09-05 09:33:04 +00:00
|
|
|
|
span_lint_and_then(
|
|
|
|
|
cx,
|
|
|
|
|
FOR_KV_MAP,
|
|
|
|
|
expr.span,
|
|
|
|
|
&format!("you seem to want to iterate on a map's {}s", kind),
|
2020-04-17 06:08:00 +00:00
|
|
|
|
|diag| {
|
2017-09-05 09:33:04 +00:00
|
|
|
|
let map = sugg::Sugg::hir(cx, arg, "map");
|
|
|
|
|
multispan_sugg(
|
2020-04-17 06:08:00 +00:00
|
|
|
|
diag,
|
2020-05-17 15:36:26 +00:00
|
|
|
|
"use the corresponding method",
|
2017-09-05 09:33:04 +00:00
|
|
|
|
vec![
|
|
|
|
|
(pat_span, snippet(cx, new_pat_span, kind).into_owned()),
|
|
|
|
|
(arg_span, format!("{}.{}s{}()", map.maybe_par(), kind, mutbl)),
|
|
|
|
|
],
|
|
|
|
|
);
|
|
|
|
|
},
|
|
|
|
|
);
|
2016-01-19 20:10:00 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2020-06-17 22:13:05 +00:00
|
|
|
|
struct MutatePairDelegate<'a, 'tcx> {
|
2020-06-25 20:41:36 +00:00
|
|
|
|
cx: &'a LateContext<'tcx>,
|
2019-03-01 12:26:06 +00:00
|
|
|
|
hir_id_low: Option<HirId>,
|
|
|
|
|
hir_id_high: Option<HirId>,
|
2017-09-19 00:10:33 +00:00
|
|
|
|
span_low: Option<Span>,
|
|
|
|
|
span_high: Option<Span>,
|
2017-08-30 14:38:13 +00:00
|
|
|
|
}
|
|
|
|
|
|
2020-06-23 15:05:22 +00:00
|
|
|
|
impl<'tcx> Delegate<'tcx> for MutatePairDelegate<'_, 'tcx> {
|
2020-06-17 22:13:05 +00:00
|
|
|
|
fn consume(&mut self, _: &PlaceWithHirId<'tcx>, _: ConsumeMode) {}
|
2017-10-25 19:41:31 +00:00
|
|
|
|
|
2020-06-17 22:13:05 +00:00
|
|
|
|
fn borrow(&mut self, cmt: &PlaceWithHirId<'tcx>, bk: ty::BorrowKind) {
|
2017-09-26 01:39:50 +00:00
|
|
|
|
if let ty::BorrowKind::MutBorrow = bk {
|
2020-06-17 22:13:05 +00:00
|
|
|
|
if let PlaceBase::Local(id) = cmt.place.base {
|
2019-03-01 12:26:06 +00:00
|
|
|
|
if Some(id) == self.hir_id_low {
|
2020-06-17 22:13:05 +00:00
|
|
|
|
self.span_low = Some(self.cx.tcx.hir().span(cmt.hir_id))
|
2017-09-25 06:00:21 +00:00
|
|
|
|
}
|
2019-03-01 12:26:06 +00:00
|
|
|
|
if Some(id) == self.hir_id_high {
|
2020-06-17 22:13:05 +00:00
|
|
|
|
self.span_high = Some(self.cx.tcx.hir().span(cmt.hir_id))
|
2017-09-26 01:39:50 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
2017-09-25 06:00:21 +00:00
|
|
|
|
}
|
2017-08-30 14:38:13 +00:00
|
|
|
|
}
|
|
|
|
|
|
2020-06-17 22:13:05 +00:00
|
|
|
|
fn mutate(&mut self, cmt: &PlaceWithHirId<'tcx>) {
|
|
|
|
|
if let PlaceBase::Local(id) = cmt.place.base {
|
2019-03-01 12:26:06 +00:00
|
|
|
|
if Some(id) == self.hir_id_low {
|
2020-06-17 22:13:05 +00:00
|
|
|
|
self.span_low = Some(self.cx.tcx.hir().span(cmt.hir_id))
|
2017-09-19 00:10:33 +00:00
|
|
|
|
}
|
2019-03-01 12:26:06 +00:00
|
|
|
|
if Some(id) == self.hir_id_high {
|
2020-06-17 22:13:05 +00:00
|
|
|
|
self.span_high = Some(self.cx.tcx.hir().span(cmt.hir_id))
|
2017-09-19 00:10:33 +00:00
|
|
|
|
}
|
2017-08-30 14:38:13 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2020-06-23 15:05:22 +00:00
|
|
|
|
impl MutatePairDelegate<'_, '_> {
|
2017-09-19 00:10:33 +00:00
|
|
|
|
fn mutation_span(&self) -> (Option<Span>, Option<Span>) {
|
|
|
|
|
(self.span_low, self.span_high)
|
2017-08-30 14:38:13 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2020-06-25 20:41:36 +00:00
|
|
|
|
fn check_for_mut_range_bound(cx: &LateContext<'_>, arg: &Expr<'_>, body: &Expr<'_>) {
|
2017-11-04 19:55:56 +00:00
|
|
|
|
if let Some(higher::Range {
|
|
|
|
|
start: Some(start),
|
|
|
|
|
end: Some(end),
|
|
|
|
|
..
|
2020-08-04 13:24:13 +00:00
|
|
|
|
}) = higher::range(arg)
|
2017-11-04 19:55:56 +00:00
|
|
|
|
{
|
2018-11-27 20:14:15 +00:00
|
|
|
|
let mut_ids = vec![check_for_mutability(cx, start), check_for_mutability(cx, end)];
|
2017-09-19 00:10:33 +00:00
|
|
|
|
if mut_ids[0].is_some() || mut_ids[1].is_some() {
|
2017-09-26 01:39:50 +00:00
|
|
|
|
let (span_low, span_high) = check_for_mutation(cx, body, &mut_ids);
|
2017-09-19 00:10:33 +00:00
|
|
|
|
mut_warn_with_span(cx, span_low);
|
|
|
|
|
mut_warn_with_span(cx, span_high);
|
2017-08-15 16:41:59 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2020-06-25 20:41:36 +00:00
|
|
|
|
fn mut_warn_with_span(cx: &LateContext<'_>, span: Option<Span>) {
|
2017-09-19 00:10:33 +00:00
|
|
|
|
if let Some(sp) = span {
|
2017-11-04 19:55:56 +00:00
|
|
|
|
span_lint(
|
|
|
|
|
cx,
|
|
|
|
|
MUT_RANGE_BOUND,
|
|
|
|
|
sp,
|
|
|
|
|
"attempt to mutate range bound within loop; note that the range of the loop is unchanged",
|
|
|
|
|
);
|
2017-09-19 00:10:33 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2020-06-25 20:41:36 +00:00
|
|
|
|
fn check_for_mutability(cx: &LateContext<'_>, bound: &Expr<'_>) -> Option<HirId> {
|
2017-10-23 19:18:02 +00:00
|
|
|
|
if_chain! {
|
2019-09-27 15:16:06 +00:00
|
|
|
|
if let ExprKind::Path(ref qpath) = bound.kind;
|
2017-10-23 19:18:02 +00:00
|
|
|
|
if let QPath::Resolved(None, _) = *qpath;
|
|
|
|
|
then {
|
2019-09-18 17:29:04 +00:00
|
|
|
|
let res = qpath_res(cx, qpath, bound.hir_id);
|
2020-04-19 12:19:11 +00:00
|
|
|
|
if let Res::Local(hir_id) = res {
|
|
|
|
|
let node_str = cx.tcx.hir().get(hir_id);
|
2017-10-23 19:18:02 +00:00
|
|
|
|
if_chain! {
|
2018-08-28 11:13:42 +00:00
|
|
|
|
if let Node::Binding(pat) = node_str;
|
2019-09-27 15:16:06 +00:00
|
|
|
|
if let PatKind::Binding(bind_ann, ..) = pat.kind;
|
2017-10-23 19:18:02 +00:00
|
|
|
|
if let BindingAnnotation::Mutable = bind_ann;
|
|
|
|
|
then {
|
2020-04-19 12:19:11 +00:00
|
|
|
|
return Some(hir_id);
|
2017-10-23 19:18:02 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
2017-09-19 00:10:33 +00:00
|
|
|
|
}
|
2017-10-23 19:18:02 +00:00
|
|
|
|
}
|
2017-09-26 01:39:50 +00:00
|
|
|
|
None
|
2017-09-19 00:10:33 +00:00
|
|
|
|
}
|
|
|
|
|
|
2020-06-25 20:41:36 +00:00
|
|
|
|
fn check_for_mutation<'tcx>(
|
|
|
|
|
cx: &LateContext<'tcx>,
|
2019-12-27 07:12:26 +00:00
|
|
|
|
body: &Expr<'_>,
|
2019-03-01 12:26:06 +00:00
|
|
|
|
bound_ids: &[Option<HirId>],
|
2018-11-27 20:14:15 +00:00
|
|
|
|
) -> (Option<Span>, Option<Span>) {
|
2018-03-05 21:20:28 +00:00
|
|
|
|
let mut delegate = MutatePairDelegate {
|
2020-06-23 15:05:22 +00:00
|
|
|
|
cx,
|
2019-03-01 12:26:06 +00:00
|
|
|
|
hir_id_low: bound_ids[0],
|
|
|
|
|
hir_id_high: bound_ids[1],
|
2017-11-04 19:55:56 +00:00
|
|
|
|
span_low: None,
|
|
|
|
|
span_high: None,
|
|
|
|
|
};
|
2020-03-19 13:33:10 +00:00
|
|
|
|
let def_id = body.hir_id.owner.to_def_id();
|
2019-11-29 10:12:19 +00:00
|
|
|
|
cx.tcx.infer_ctxt().enter(|infcx| {
|
2020-07-17 08:47:04 +00:00
|
|
|
|
ExprUseVisitor::new(
|
|
|
|
|
&mut delegate,
|
|
|
|
|
&infcx,
|
|
|
|
|
def_id.expect_local(),
|
|
|
|
|
cx.param_env,
|
|
|
|
|
cx.typeck_results(),
|
|
|
|
|
)
|
|
|
|
|
.walk_expr(body);
|
2019-11-29 10:12:19 +00:00
|
|
|
|
});
|
2017-09-26 01:39:50 +00:00
|
|
|
|
delegate.mutation_span()
|
2017-08-15 16:41:59 +00:00
|
|
|
|
}
|
|
|
|
|
|
2019-03-10 17:19:47 +00:00
|
|
|
|
/// Returns `true` if the pattern is a `PatWild` or an ident prefixed with `_`.
|
2019-12-27 07:12:26 +00:00
|
|
|
|
fn pat_is_wild<'tcx>(pat: &'tcx PatKind<'_>, body: &'tcx Expr<'_>) -> bool {
|
2016-01-19 20:10:00 +00:00
|
|
|
|
match *pat {
|
2016-02-18 20:16:39 +00:00
|
|
|
|
PatKind::Wild => true,
|
2020-01-10 16:14:17 +00:00
|
|
|
|
PatKind::Binding(.., ident, None) if ident.as_str().starts_with('_') => is_unused(&ident, body),
|
2016-01-19 20:10:00 +00:00
|
|
|
|
_ => false,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2019-06-19 18:36:23 +00:00
|
|
|
|
struct LocalUsedVisitor<'a, 'tcx> {
|
2020-06-25 20:41:36 +00:00
|
|
|
|
cx: &'a LateContext<'tcx>,
|
2019-03-07 20:51:05 +00:00
|
|
|
|
local: HirId,
|
2017-09-05 00:16:34 +00:00
|
|
|
|
used: bool,
|
|
|
|
|
}
|
|
|
|
|
|
2019-06-19 18:36:23 +00:00
|
|
|
|
impl<'a, 'tcx> Visitor<'tcx> for LocalUsedVisitor<'a, 'tcx> {
|
2020-01-09 07:13:22 +00:00
|
|
|
|
type Map = Map<'tcx>;
|
|
|
|
|
|
2019-12-27 07:12:26 +00:00
|
|
|
|
fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
|
2017-09-12 12:26:40 +00:00
|
|
|
|
if same_var(self.cx, expr, self.local) {
|
2017-09-05 00:16:34 +00:00
|
|
|
|
self.used = true;
|
|
|
|
|
} else {
|
|
|
|
|
walk_expr(self, expr);
|
2016-02-05 18:14:02 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
2017-07-31 22:58:26 +00:00
|
|
|
|
|
2020-03-15 22:41:20 +00:00
|
|
|
|
fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
|
2017-05-12 10:02:42 +00:00
|
|
|
|
NestedVisitorMap::None
|
2016-12-06 10:32:21 +00:00
|
|
|
|
}
|
2016-02-05 18:14:02 +00:00
|
|
|
|
}
|
|
|
|
|
|
2019-06-19 18:36:23 +00:00
|
|
|
|
struct VarVisitor<'a, 'tcx> {
|
2017-07-10 13:30:28 +00:00
|
|
|
|
/// context reference
|
2020-06-25 20:41:36 +00:00
|
|
|
|
cx: &'a LateContext<'tcx>,
|
2017-07-10 13:30:28 +00:00
|
|
|
|
/// var name to look for as index
|
2019-03-07 20:51:05 +00:00
|
|
|
|
var: HirId,
|
2017-11-07 13:41:54 +00:00
|
|
|
|
/// indexed variables that are used mutably
|
2020-08-11 13:43:21 +00:00
|
|
|
|
indexed_mut: FxHashSet<Symbol>,
|
2017-11-07 14:32:52 +00:00
|
|
|
|
/// indirectly indexed variables (`v[(i + 4) % N]`), the extend is `None` for global
|
2020-08-11 13:43:21 +00:00
|
|
|
|
indexed_indirectly: FxHashMap<Symbol, Option<region::Scope>>,
|
2017-10-08 15:34:31 +00:00
|
|
|
|
/// subset of `indexed` of vars that are indexed directly: `v[i]`
|
|
|
|
|
/// this will not contain cases like `v[calc_index(i)]` or `v[(i + 4) % N]`
|
2020-08-11 13:43:21 +00:00
|
|
|
|
indexed_directly: FxHashMap<Symbol, (Option<region::Scope>, Ty<'tcx>)>,
|
2017-07-10 13:30:28 +00:00
|
|
|
|
/// Any names that are used outside an index operation.
|
|
|
|
|
/// Used to detect things like `&mut vec` used together with `vec[i]`
|
2020-08-11 13:43:21 +00:00
|
|
|
|
referenced: FxHashSet<Symbol>,
|
2017-08-09 07:30:56 +00:00
|
|
|
|
/// has the loop variable been used in expressions other than the index of
|
|
|
|
|
/// an index op?
|
2017-07-10 13:30:28 +00:00
|
|
|
|
nonindex: bool,
|
2017-11-07 13:41:54 +00:00
|
|
|
|
/// Whether we are inside the `$` in `&mut $` or `$ = foo` or `$.bar`, where bar
|
|
|
|
|
/// takes `&mut self`
|
|
|
|
|
prefer_mutable: bool,
|
2015-08-12 19:56:27 +00:00
|
|
|
|
}
|
|
|
|
|
|
2017-11-07 14:32:52 +00:00
|
|
|
|
impl<'a, 'tcx> VarVisitor<'a, 'tcx> {
|
2019-12-27 07:12:26 +00:00
|
|
|
|
fn check(&mut self, idx: &'tcx Expr<'_>, seqexpr: &'tcx Expr<'_>, expr: &'tcx Expr<'_>) -> bool {
|
2017-10-23 19:18:02 +00:00
|
|
|
|
if_chain! {
|
2017-07-10 13:30:28 +00:00
|
|
|
|
// the indexed container is referenced by a name
|
2019-09-27 15:16:06 +00:00
|
|
|
|
if let ExprKind::Path(ref seqpath) = seqexpr.kind;
|
2017-10-23 19:18:02 +00:00
|
|
|
|
if let QPath::Resolved(None, ref seqvar) = *seqpath;
|
|
|
|
|
if seqvar.segments.len() == 1;
|
|
|
|
|
then {
|
|
|
|
|
let index_used_directly = same_var(self.cx, idx, self.var);
|
2017-11-07 14:32:52 +00:00
|
|
|
|
let indexed_indirectly = {
|
2017-10-23 19:18:02 +00:00
|
|
|
|
let mut used_visitor = LocalUsedVisitor {
|
|
|
|
|
cx: self.cx,
|
|
|
|
|
local: self.var,
|
|
|
|
|
used: false,
|
|
|
|
|
};
|
|
|
|
|
walk_expr(&mut used_visitor, idx);
|
|
|
|
|
used_visitor.used
|
2017-09-05 00:16:34 +00:00
|
|
|
|
};
|
2017-10-25 19:41:31 +00:00
|
|
|
|
|
2017-11-07 14:32:52 +00:00
|
|
|
|
if indexed_indirectly || index_used_directly {
|
2017-11-07 13:41:54 +00:00
|
|
|
|
if self.prefer_mutable {
|
2018-06-28 13:46:58 +00:00
|
|
|
|
self.indexed_mut.insert(seqvar.segments[0].ident.name);
|
2017-11-07 13:41:54 +00:00
|
|
|
|
}
|
2019-09-18 17:29:04 +00:00
|
|
|
|
let res = qpath_res(self.cx, seqpath, seqexpr.hir_id);
|
2019-05-04 00:03:12 +00:00
|
|
|
|
match res {
|
2019-06-02 16:30:40 +00:00
|
|
|
|
Res::Local(hir_id) => {
|
2019-02-24 18:43:15 +00:00
|
|
|
|
let parent_id = self.cx.tcx.hir().get_parent_item(expr.hir_id);
|
2019-07-06 03:52:51 +00:00
|
|
|
|
let parent_def_id = self.cx.tcx.hir().local_def_id(parent_id);
|
2017-10-23 19:18:02 +00:00
|
|
|
|
let extent = self.cx.tcx.region_scope_tree(parent_def_id).var_scope(hir_id.local_id);
|
2017-11-07 14:32:52 +00:00
|
|
|
|
if indexed_indirectly {
|
2018-06-28 13:46:58 +00:00
|
|
|
|
self.indexed_indirectly.insert(seqvar.segments[0].ident.name, Some(extent));
|
2017-11-07 14:32:52 +00:00
|
|
|
|
}
|
2017-10-23 19:18:02 +00:00
|
|
|
|
if index_used_directly {
|
2018-10-19 20:34:16 +00:00
|
|
|
|
self.indexed_directly.insert(
|
|
|
|
|
seqvar.segments[0].ident.name,
|
2020-07-17 08:47:04 +00:00
|
|
|
|
(Some(extent), self.cx.typeck_results().node_type(seqexpr.hir_id)),
|
2018-10-19 20:34:16 +00:00
|
|
|
|
);
|
2017-10-23 19:18:02 +00:00
|
|
|
|
}
|
2017-11-07 14:32:52 +00:00
|
|
|
|
return false; // no need to walk further *on the variable*
|
2017-10-08 15:34:31 +00:00
|
|
|
|
}
|
2020-03-16 06:23:03 +00:00
|
|
|
|
Res::Def(DefKind::Static | DefKind::Const, ..) => {
|
2017-11-07 14:32:52 +00:00
|
|
|
|
if indexed_indirectly {
|
2018-06-28 13:46:58 +00:00
|
|
|
|
self.indexed_indirectly.insert(seqvar.segments[0].ident.name, None);
|
2017-11-07 14:32:52 +00:00
|
|
|
|
}
|
2017-10-23 19:18:02 +00:00
|
|
|
|
if index_used_directly {
|
2018-10-19 20:34:16 +00:00
|
|
|
|
self.indexed_directly.insert(
|
|
|
|
|
seqvar.segments[0].ident.name,
|
2020-07-17 08:47:04 +00:00
|
|
|
|
(None, self.cx.typeck_results().node_type(seqexpr.hir_id)),
|
2018-10-19 20:34:16 +00:00
|
|
|
|
);
|
2017-10-23 19:18:02 +00:00
|
|
|
|
}
|
2017-11-07 14:32:52 +00:00
|
|
|
|
return false; // no need to walk further *on the variable*
|
2017-10-08 15:34:31 +00:00
|
|
|
|
}
|
2017-10-23 19:18:02 +00:00
|
|
|
|
_ => (),
|
2017-09-05 00:16:34 +00:00
|
|
|
|
}
|
2016-12-01 21:31:56 +00:00
|
|
|
|
}
|
2015-08-12 19:56:27 +00:00
|
|
|
|
}
|
2017-10-23 19:18:02 +00:00
|
|
|
|
}
|
2017-11-07 14:32:52 +00:00
|
|
|
|
true
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl<'a, 'tcx> Visitor<'tcx> for VarVisitor<'a, 'tcx> {
|
2020-01-09 07:13:22 +00:00
|
|
|
|
type Map = Map<'tcx>;
|
|
|
|
|
|
2019-12-27 07:12:26 +00:00
|
|
|
|
fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
|
2017-11-07 14:32:52 +00:00
|
|
|
|
if_chain! {
|
|
|
|
|
// a range index op
|
2020-06-09 21:44:04 +00:00
|
|
|
|
if let ExprKind::MethodCall(ref meth, _, ref args, _) = expr.kind;
|
2019-05-17 21:53:54 +00:00
|
|
|
|
if (meth.ident.name == sym!(index) && match_trait_method(self.cx, expr, &paths::INDEX))
|
|
|
|
|
|| (meth.ident.name == sym!(index_mut) && match_trait_method(self.cx, expr, &paths::INDEX_MUT));
|
2017-11-07 14:32:52 +00:00
|
|
|
|
if !self.check(&args[1], &args[0], expr);
|
|
|
|
|
then { return }
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if_chain! {
|
|
|
|
|
// an index op
|
2019-09-27 15:16:06 +00:00
|
|
|
|
if let ExprKind::Index(ref seqexpr, ref idx) = expr.kind;
|
2017-11-07 14:32:52 +00:00
|
|
|
|
if !self.check(idx, seqexpr, expr);
|
|
|
|
|
then { return }
|
|
|
|
|
}
|
2017-07-10 13:30:28 +00:00
|
|
|
|
|
2017-10-23 19:18:02 +00:00
|
|
|
|
if_chain! {
|
2017-09-05 00:16:34 +00:00
|
|
|
|
// directly using a variable
|
2019-09-27 15:16:06 +00:00
|
|
|
|
if let ExprKind::Path(ref qpath) = expr.kind;
|
2017-10-23 19:18:02 +00:00
|
|
|
|
if let QPath::Resolved(None, ref path) = *qpath;
|
|
|
|
|
if path.segments.len() == 1;
|
|
|
|
|
then {
|
2019-09-18 17:29:04 +00:00
|
|
|
|
if let Res::Local(local_id) = qpath_res(self.cx, qpath, expr.hir_id) {
|
2019-06-02 16:30:40 +00:00
|
|
|
|
if local_id == self.var {
|
|
|
|
|
self.nonindex = true;
|
|
|
|
|
} else {
|
|
|
|
|
// not the correct variable, but still a variable
|
|
|
|
|
self.referenced.insert(path.segments[0].ident.name);
|
2019-02-11 05:03:12 +00:00
|
|
|
|
}
|
2017-10-23 19:18:02 +00:00
|
|
|
|
}
|
2017-07-10 13:30:28 +00:00
|
|
|
|
}
|
2017-10-23 19:18:02 +00:00
|
|
|
|
}
|
2019-02-11 05:03:12 +00:00
|
|
|
|
|
2017-11-07 13:41:54 +00:00
|
|
|
|
let old = self.prefer_mutable;
|
2019-09-27 15:16:06 +00:00
|
|
|
|
match expr.kind {
|
2019-12-24 04:16:04 +00:00
|
|
|
|
ExprKind::AssignOp(_, ref lhs, ref rhs) | ExprKind::Assign(ref lhs, ref rhs, _) => {
|
2017-11-07 13:41:54 +00:00
|
|
|
|
self.prefer_mutable = true;
|
|
|
|
|
self.visit_expr(lhs);
|
|
|
|
|
self.prefer_mutable = false;
|
|
|
|
|
self.visit_expr(rhs);
|
|
|
|
|
},
|
2019-11-27 22:30:10 +00:00
|
|
|
|
ExprKind::AddrOf(BorrowKind::Ref, mutbl, ref expr) => {
|
2019-12-21 18:38:45 +00:00
|
|
|
|
if mutbl == Mutability::Mut {
|
2017-11-07 13:41:54 +00:00
|
|
|
|
self.prefer_mutable = true;
|
|
|
|
|
}
|
|
|
|
|
self.visit_expr(expr);
|
|
|
|
|
},
|
2019-12-27 07:12:26 +00:00
|
|
|
|
ExprKind::Call(ref f, args) => {
|
2017-11-29 14:52:57 +00:00
|
|
|
|
self.visit_expr(f);
|
|
|
|
|
for expr in args {
|
2020-07-17 08:47:04 +00:00
|
|
|
|
let ty = self.cx.typeck_results().expr_ty_adjusted(expr);
|
2017-11-07 13:41:54 +00:00
|
|
|
|
self.prefer_mutable = false;
|
2020-08-03 22:18:29 +00:00
|
|
|
|
if let ty::Ref(_, _, mutbl) = *ty.kind() {
|
2019-12-21 18:38:45 +00:00
|
|
|
|
if mutbl == Mutability::Mut {
|
2017-11-07 13:41:54 +00:00
|
|
|
|
self.prefer_mutable = true;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
self.visit_expr(expr);
|
|
|
|
|
}
|
|
|
|
|
},
|
2020-06-09 21:44:04 +00:00
|
|
|
|
ExprKind::MethodCall(_, _, args, _) => {
|
2020-07-17 08:47:04 +00:00
|
|
|
|
let def_id = self.cx.typeck_results().type_dependent_def_id(expr.hir_id).unwrap();
|
2017-11-07 13:41:54 +00:00
|
|
|
|
for (ty, expr) in self.cx.tcx.fn_sig(def_id).inputs().skip_binder().iter().zip(args) {
|
|
|
|
|
self.prefer_mutable = false;
|
2020-08-03 22:18:29 +00:00
|
|
|
|
if let ty::Ref(_, _, mutbl) = *ty.kind() {
|
2019-12-21 18:38:45 +00:00
|
|
|
|
if mutbl == Mutability::Mut {
|
2017-11-07 13:41:54 +00:00
|
|
|
|
self.prefer_mutable = true;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
self.visit_expr(expr);
|
|
|
|
|
}
|
|
|
|
|
},
|
2019-02-11 05:03:12 +00:00
|
|
|
|
ExprKind::Closure(_, _, body_id, ..) => {
|
|
|
|
|
let body = self.cx.tcx.hir().body(body_id);
|
|
|
|
|
self.visit_expr(&body.value);
|
|
|
|
|
},
|
2017-11-07 13:41:54 +00:00
|
|
|
|
_ => walk_expr(self, expr),
|
|
|
|
|
}
|
|
|
|
|
self.prefer_mutable = old;
|
2015-08-12 19:56:27 +00:00
|
|
|
|
}
|
2020-03-15 22:41:20 +00:00
|
|
|
|
fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
|
2017-05-12 10:02:42 +00:00
|
|
|
|
NestedVisitorMap::None
|
2016-12-06 10:32:21 +00:00
|
|
|
|
}
|
2015-08-12 19:56:27 +00:00
|
|
|
|
}
|
2015-08-25 16:26:20 +00:00
|
|
|
|
|
2020-06-25 20:41:36 +00:00
|
|
|
|
fn is_used_inside<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, container: &'tcx Expr<'_>) -> bool {
|
2019-01-19 09:36:27 +00:00
|
|
|
|
let def_id = match var_def_id(cx, expr) {
|
|
|
|
|
Some(id) => id,
|
|
|
|
|
None => return false,
|
|
|
|
|
};
|
|
|
|
|
if let Some(used_mutably) = mutated_variables(container, cx) {
|
|
|
|
|
if used_mutably.contains(&def_id) {
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
false
|
|
|
|
|
}
|
|
|
|
|
|
2020-06-25 20:41:36 +00:00
|
|
|
|
fn is_iterator_used_after_while_let<'tcx>(cx: &LateContext<'tcx>, iter_expr: &'tcx Expr<'_>) -> bool {
|
2015-10-26 22:49:37 +00:00
|
|
|
|
let def_id = match var_def_id(cx, iter_expr) {
|
|
|
|
|
Some(id) => id,
|
2016-01-04 04:26:12 +00:00
|
|
|
|
None => return false,
|
2015-10-26 22:49:37 +00:00
|
|
|
|
};
|
|
|
|
|
let mut visitor = VarUsedAfterLoopVisitor {
|
2018-03-15 15:07:15 +00:00
|
|
|
|
cx,
|
|
|
|
|
def_id,
|
2019-02-24 18:43:15 +00:00
|
|
|
|
iter_expr_id: iter_expr.hir_id,
|
2015-10-26 22:49:37 +00:00
|
|
|
|
past_while_let: false,
|
2016-01-04 04:26:12 +00:00
|
|
|
|
var_used_after_while_let: false,
|
2015-10-26 22:49:37 +00:00
|
|
|
|
};
|
2019-03-01 12:26:06 +00:00
|
|
|
|
if let Some(enclosing_block) = get_enclosing_block(cx, def_id) {
|
2015-10-26 22:49:37 +00:00
|
|
|
|
walk_block(&mut visitor, enclosing_block);
|
2015-10-19 23:04:21 +00:00
|
|
|
|
}
|
2015-10-26 22:49:37 +00:00
|
|
|
|
visitor.var_used_after_while_let
|
2015-10-19 23:04:21 +00:00
|
|
|
|
}
|
|
|
|
|
|
2019-06-19 18:36:23 +00:00
|
|
|
|
struct VarUsedAfterLoopVisitor<'a, 'tcx> {
|
2020-06-25 20:41:36 +00:00
|
|
|
|
cx: &'a LateContext<'tcx>,
|
2019-03-01 12:26:06 +00:00
|
|
|
|
def_id: HirId,
|
2019-02-24 18:43:15 +00:00
|
|
|
|
iter_expr_id: HirId,
|
2015-10-26 22:49:37 +00:00
|
|
|
|
past_while_let: bool,
|
2016-01-04 04:26:12 +00:00
|
|
|
|
var_used_after_while_let: bool,
|
2015-10-19 23:04:21 +00:00
|
|
|
|
}
|
|
|
|
|
|
2016-12-06 10:32:21 +00:00
|
|
|
|
impl<'a, 'tcx> Visitor<'tcx> for VarUsedAfterLoopVisitor<'a, 'tcx> {
|
2020-01-09 07:13:22 +00:00
|
|
|
|
type Map = Map<'tcx>;
|
|
|
|
|
|
2019-12-27 07:12:26 +00:00
|
|
|
|
fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
|
2015-10-26 22:49:37 +00:00
|
|
|
|
if self.past_while_let {
|
|
|
|
|
if Some(self.def_id) == var_def_id(self.cx, expr) {
|
|
|
|
|
self.var_used_after_while_let = true;
|
|
|
|
|
}
|
2019-02-24 18:43:15 +00:00
|
|
|
|
} else if self.iter_expr_id == expr.hir_id {
|
2015-10-26 22:49:37 +00:00
|
|
|
|
self.past_while_let = true;
|
2015-10-19 23:04:21 +00:00
|
|
|
|
}
|
|
|
|
|
walk_expr(self, expr);
|
|
|
|
|
}
|
2020-03-15 22:41:20 +00:00
|
|
|
|
fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
|
2017-05-12 10:02:42 +00:00
|
|
|
|
NestedVisitorMap::None
|
2016-12-06 10:32:21 +00:00
|
|
|
|
}
|
2015-10-19 23:04:21 +00:00
|
|
|
|
}
|
|
|
|
|
|
2019-01-31 01:15:29 +00:00
|
|
|
|
/// Returns `true` if the type of expr is one that provides `IntoIterator` impls
|
2016-03-19 16:48:29 +00:00
|
|
|
|
/// for `&T` and `&mut T`, such as `Vec`.
|
2018-05-30 16:24:44 +00:00
|
|
|
|
#[rustfmt::skip]
|
2020-06-25 20:41:36 +00:00
|
|
|
|
fn is_ref_iterable_type(cx: &LateContext<'_>, e: &Expr<'_>) -> bool {
|
2015-08-31 06:29:34 +00:00
|
|
|
|
// no walk_ptrs_ty: calling iter() on a reference can make sense because it
|
|
|
|
|
// will allow further borrows afterwards
|
2020-07-17 08:47:04 +00:00
|
|
|
|
let ty = cx.typeck_results().expr_ty(e);
|
2018-05-13 08:44:57 +00:00
|
|
|
|
is_iterable_array(ty, cx) ||
|
2020-04-13 06:57:34 +00:00
|
|
|
|
is_type_diagnostic_item(cx, ty, sym!(vec_type)) ||
|
2019-05-17 21:53:54 +00:00
|
|
|
|
match_type(cx, ty, &paths::LINKED_LIST) ||
|
2020-04-23 06:09:42 +00:00
|
|
|
|
is_type_diagnostic_item(cx, ty, sym!(hashmap_type)) ||
|
|
|
|
|
is_type_diagnostic_item(cx, ty, sym!(hashset_type)) ||
|
|
|
|
|
is_type_diagnostic_item(cx, ty, sym!(vecdeque_type)) ||
|
2019-05-17 21:53:54 +00:00
|
|
|
|
match_type(cx, ty, &paths::BINARY_HEAP) ||
|
|
|
|
|
match_type(cx, ty, &paths::BTREEMAP) ||
|
|
|
|
|
match_type(cx, ty, &paths::BTREESET)
|
2015-08-25 16:26:20 +00:00
|
|
|
|
}
|
|
|
|
|
|
2020-06-25 20:41:36 +00:00
|
|
|
|
fn is_iterable_array<'tcx>(ty: Ty<'tcx>, cx: &LateContext<'tcx>) -> bool {
|
2015-09-27 07:39:42 +00:00
|
|
|
|
// IntoIterator is currently only implemented for array sizes <= 32 in rustc
|
2020-08-03 22:18:29 +00:00
|
|
|
|
match ty.kind() {
|
2020-07-14 12:59:59 +00:00
|
|
|
|
ty::Array(_, n) => n
|
|
|
|
|
.try_eval_usize(cx.tcx, cx.param_env)
|
|
|
|
|
.map_or(false, |val| (0..=32).contains(&val)),
|
2016-01-04 04:26:12 +00:00
|
|
|
|
_ => false,
|
2015-08-25 16:26:20 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
2015-08-29 09:41:06 +00:00
|
|
|
|
|
2017-08-09 07:30:56 +00:00
|
|
|
|
/// If a block begins with a statement (possibly a `let` binding) and has an
|
|
|
|
|
/// expression, return it.
|
2019-12-27 07:12:26 +00:00
|
|
|
|
fn extract_expr_from_first_stmt<'tcx>(block: &Block<'tcx>) -> Option<&'tcx Expr<'tcx>> {
|
2016-01-04 04:26:12 +00:00
|
|
|
|
if block.stmts.is_empty() {
|
|
|
|
|
return None;
|
|
|
|
|
}
|
2019-09-27 15:16:06 +00:00
|
|
|
|
if let StmtKind::Local(ref local) = block.stmts[0].kind {
|
2020-07-14 12:59:59 +00:00
|
|
|
|
local.init //.map(|expr| expr)
|
2016-01-04 04:26:12 +00:00
|
|
|
|
} else {
|
|
|
|
|
None
|
|
|
|
|
}
|
2015-09-27 07:39:42 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// If a block begins with an expression (with or without semicolon), return it.
|
2019-12-27 07:12:26 +00:00
|
|
|
|
fn extract_first_expr<'tcx>(block: &Block<'tcx>) -> Option<&'tcx Expr<'tcx>> {
|
2015-09-27 07:39:42 +00:00
|
|
|
|
match block.expr {
|
2016-06-16 14:19:17 +00:00
|
|
|
|
Some(ref expr) if block.stmts.is_empty() => Some(expr),
|
2019-09-27 15:16:06 +00:00
|
|
|
|
None if !block.stmts.is_empty() => match block.stmts[0].kind {
|
2019-01-20 10:21:30 +00:00
|
|
|
|
StmtKind::Expr(ref expr) | StmtKind::Semi(ref expr) => Some(expr),
|
|
|
|
|
StmtKind::Local(..) | StmtKind::Item(..) => None,
|
2016-12-20 17:21:30 +00:00
|
|
|
|
},
|
2015-10-02 07:55:34 +00:00
|
|
|
|
_ => None,
|
2015-08-29 09:41:06 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2019-01-31 01:15:29 +00:00
|
|
|
|
/// Returns `true` if expr contains a single break expr without destination label
|
2017-09-16 22:45:28 +00:00
|
|
|
|
/// and
|
2017-09-05 20:28:30 +00:00
|
|
|
|
/// passed expression. The expression may be within a block.
|
2019-12-27 07:12:26 +00:00
|
|
|
|
fn is_simple_break_expr(expr: &Expr<'_>) -> bool {
|
2019-09-27 15:16:06 +00:00
|
|
|
|
match expr.kind {
|
2018-07-12 07:30:57 +00:00
|
|
|
|
ExprKind::Break(dest, ref passed_expr) if dest.label.is_none() && passed_expr.is_none() => true,
|
2019-09-04 14:19:59 +00:00
|
|
|
|
ExprKind::Block(ref b, _) => extract_first_expr(b).map_or(false, |subexpr| is_simple_break_expr(subexpr)),
|
2015-08-29 09:41:06 +00:00
|
|
|
|
_ => false,
|
|
|
|
|
}
|
|
|
|
|
}
|
2015-08-23 17:25:45 +00:00
|
|
|
|
|
2019-04-28 07:11:20 +00:00
|
|
|
|
#[derive(Debug, PartialEq)]
|
2020-10-23 20:16:59 +00:00
|
|
|
|
enum IncrementVisitorVarState {
|
2017-11-04 19:55:56 +00:00
|
|
|
|
Initial, // Not examined yet
|
2016-01-04 04:26:12 +00:00
|
|
|
|
IncrOnce, // Incremented exactly once, may be a loop counter
|
|
|
|
|
DontWarn,
|
2015-08-23 17:25:45 +00:00
|
|
|
|
}
|
|
|
|
|
|
2020-10-09 10:45:29 +00:00
|
|
|
|
/// Scan a for loop for variables that are incremented exactly once and not used after that.
|
2019-06-19 18:36:23 +00:00
|
|
|
|
struct IncrementVisitor<'a, 'tcx> {
|
2020-10-23 20:16:59 +00:00
|
|
|
|
cx: &'a LateContext<'tcx>, // context reference
|
|
|
|
|
states: FxHashMap<HirId, IncrementVisitorVarState>, // incremented variables
|
|
|
|
|
depth: u32, // depth of conditional expressions
|
2016-01-04 04:26:12 +00:00
|
|
|
|
done: bool,
|
2015-08-23 17:25:45 +00:00
|
|
|
|
}
|
|
|
|
|
|
2020-10-23 20:16:59 +00:00
|
|
|
|
impl<'a, 'tcx> IncrementVisitor<'a, 'tcx> {
|
|
|
|
|
fn new(cx: &'a LateContext<'tcx>) -> Self {
|
|
|
|
|
Self {
|
|
|
|
|
cx,
|
|
|
|
|
states: FxHashMap::default(),
|
|
|
|
|
depth: 0,
|
|
|
|
|
done: false,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn into_results(self) -> impl Iterator<Item = HirId> {
|
|
|
|
|
self.states.into_iter().filter_map(|(id, state)| {
|
|
|
|
|
if state == IncrementVisitorVarState::IncrOnce {
|
|
|
|
|
Some(id)
|
|
|
|
|
} else {
|
|
|
|
|
None
|
|
|
|
|
}
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2016-12-06 10:32:21 +00:00
|
|
|
|
impl<'a, 'tcx> Visitor<'tcx> for IncrementVisitor<'a, 'tcx> {
|
2020-01-09 07:13:22 +00:00
|
|
|
|
type Map = Map<'tcx>;
|
|
|
|
|
|
2019-12-27 07:12:26 +00:00
|
|
|
|
fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
|
2015-08-23 17:25:45 +00:00
|
|
|
|
if self.done {
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// If node is a variable
|
|
|
|
|
if let Some(def_id) = var_def_id(self.cx, expr) {
|
|
|
|
|
if let Some(parent) = get_parent_expr(self.cx, expr) {
|
2020-10-23 20:16:59 +00:00
|
|
|
|
let state = self.states.entry(def_id).or_insert(IncrementVisitorVarState::Initial);
|
|
|
|
|
if *state == IncrementVisitorVarState::IncrOnce {
|
|
|
|
|
*state = IncrementVisitorVarState::DontWarn;
|
2020-10-09 10:45:29 +00:00
|
|
|
|
return;
|
|
|
|
|
}
|
2015-08-23 17:25:45 +00:00
|
|
|
|
|
2019-09-27 15:16:06 +00:00
|
|
|
|
match parent.kind {
|
2018-07-12 07:30:57 +00:00
|
|
|
|
ExprKind::AssignOp(op, ref lhs, ref rhs) => {
|
2019-02-24 18:43:15 +00:00
|
|
|
|
if lhs.hir_id == expr.hir_id {
|
2020-10-23 20:16:59 +00:00
|
|
|
|
*state = if op.node == BinOpKind::Add
|
|
|
|
|
&& is_integer_const(self.cx, rhs, 1)
|
|
|
|
|
&& *state == IncrementVisitorVarState::Initial
|
|
|
|
|
&& self.depth == 0
|
|
|
|
|
{
|
|
|
|
|
IncrementVisitorVarState::IncrOnce
|
2016-01-04 04:26:12 +00:00
|
|
|
|
} else {
|
2020-10-23 20:16:59 +00:00
|
|
|
|
// Assigned some other value or assigned multiple times
|
|
|
|
|
IncrementVisitorVarState::DontWarn
|
|
|
|
|
};
|
2016-01-04 04:26:12 +00:00
|
|
|
|
}
|
2016-12-20 17:21:30 +00:00
|
|
|
|
},
|
2020-10-23 20:16:59 +00:00
|
|
|
|
ExprKind::Assign(ref lhs, _, _) if lhs.hir_id == expr.hir_id => {
|
|
|
|
|
*state = IncrementVisitorVarState::DontWarn
|
|
|
|
|
},
|
2019-12-21 18:38:45 +00:00
|
|
|
|
ExprKind::AddrOf(BorrowKind::Ref, mutability, _) if mutability == Mutability::Mut => {
|
2020-10-23 20:16:59 +00:00
|
|
|
|
*state = IncrementVisitorVarState::DontWarn
|
2019-11-25 14:20:10 +00:00
|
|
|
|
},
|
2016-01-04 04:26:12 +00:00
|
|
|
|
_ => (),
|
2015-08-23 17:25:45 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
2020-10-23 20:16:59 +00:00
|
|
|
|
|
|
|
|
|
walk_expr(self, expr);
|
2018-10-13 13:57:52 +00:00
|
|
|
|
} else if is_loop(expr) || is_conditional(expr) {
|
2015-08-23 17:25:45 +00:00
|
|
|
|
self.depth += 1;
|
|
|
|
|
walk_expr(self, expr);
|
|
|
|
|
self.depth -= 1;
|
2019-09-27 15:16:06 +00:00
|
|
|
|
} else if let ExprKind::Continue(_) = expr.kind {
|
2018-09-08 02:58:19 +00:00
|
|
|
|
self.done = true;
|
2020-10-23 20:16:59 +00:00
|
|
|
|
} else {
|
|
|
|
|
walk_expr(self, expr);
|
2015-08-23 17:25:45 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
2020-03-15 22:41:20 +00:00
|
|
|
|
fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
|
2017-05-12 10:02:42 +00:00
|
|
|
|
NestedVisitorMap::None
|
2016-12-06 10:32:21 +00:00
|
|
|
|
}
|
2015-08-23 17:25:45 +00:00
|
|
|
|
}
|
|
|
|
|
|
2020-10-23 20:16:59 +00:00
|
|
|
|
enum InitializeVisitorState<'hir> {
|
|
|
|
|
Initial, // Not examined yet
|
|
|
|
|
Declared(Symbol), // Declared but not (yet) initialized
|
|
|
|
|
Initialized {
|
|
|
|
|
name: Symbol,
|
|
|
|
|
initializer: &'hir Expr<'hir>,
|
|
|
|
|
},
|
|
|
|
|
DontWarn,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Checks whether a variable is initialized at the start of a loop and not modified
|
|
|
|
|
/// and used after the loop.
|
2019-06-19 18:36:23 +00:00
|
|
|
|
struct InitializeVisitor<'a, 'tcx> {
|
2020-06-25 20:41:36 +00:00
|
|
|
|
cx: &'a LateContext<'tcx>, // context reference
|
|
|
|
|
end_expr: &'tcx Expr<'tcx>, // the for loop. Stop scanning here.
|
2019-03-01 12:26:06 +00:00
|
|
|
|
var_id: HirId,
|
2020-10-23 20:16:59 +00:00
|
|
|
|
state: InitializeVisitorState<'tcx>,
|
2016-01-04 04:26:12 +00:00
|
|
|
|
depth: u32, // depth of conditional expressions
|
|
|
|
|
past_loop: bool,
|
2015-08-23 17:25:45 +00:00
|
|
|
|
}
|
|
|
|
|
|
2020-10-23 20:16:59 +00:00
|
|
|
|
impl<'a, 'tcx> InitializeVisitor<'a, 'tcx> {
|
|
|
|
|
fn new(cx: &'a LateContext<'tcx>, end_expr: &'tcx Expr<'tcx>, var_id: HirId) -> Self {
|
|
|
|
|
Self {
|
|
|
|
|
cx,
|
|
|
|
|
end_expr,
|
|
|
|
|
var_id,
|
|
|
|
|
state: InitializeVisitorState::Initial,
|
|
|
|
|
depth: 0,
|
|
|
|
|
past_loop: false,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn get_result(&self) -> Option<(Symbol, &'tcx Expr<'tcx>)> {
|
|
|
|
|
if let InitializeVisitorState::Initialized { name, initializer } = self.state {
|
|
|
|
|
Some((name, initializer))
|
|
|
|
|
} else {
|
|
|
|
|
None
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2016-12-06 10:32:21 +00:00
|
|
|
|
impl<'a, 'tcx> Visitor<'tcx> for InitializeVisitor<'a, 'tcx> {
|
2020-01-09 07:13:22 +00:00
|
|
|
|
type Map = Map<'tcx>;
|
|
|
|
|
|
2019-12-27 07:12:26 +00:00
|
|
|
|
fn visit_stmt(&mut self, stmt: &'tcx Stmt<'_>) {
|
2015-08-23 17:25:45 +00:00
|
|
|
|
// Look for declarations of the variable
|
2020-10-23 20:16:59 +00:00
|
|
|
|
if_chain! {
|
|
|
|
|
if let StmtKind::Local(ref local) = stmt.kind;
|
|
|
|
|
if local.pat.hir_id == self.var_id;
|
|
|
|
|
if let PatKind::Binding(.., ident, _) = local.pat.kind;
|
|
|
|
|
then {
|
|
|
|
|
self.state = local.init.map_or(InitializeVisitorState::Declared(ident.name), |init| {
|
|
|
|
|
InitializeVisitorState::Initialized {
|
|
|
|
|
initializer: init,
|
|
|
|
|
name: ident.name,
|
|
|
|
|
}
|
|
|
|
|
})
|
2015-08-23 17:25:45 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
2019-01-20 10:21:30 +00:00
|
|
|
|
walk_stmt(self, stmt);
|
2015-08-23 17:25:45 +00:00
|
|
|
|
}
|
|
|
|
|
|
2019-12-27 07:12:26 +00:00
|
|
|
|
fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
|
2020-10-23 20:16:59 +00:00
|
|
|
|
if matches!(self.state, InitializeVisitorState::DontWarn) {
|
2015-11-25 23:09:01 +00:00
|
|
|
|
return;
|
|
|
|
|
}
|
2020-06-23 15:05:22 +00:00
|
|
|
|
if expr.hir_id == self.end_expr.hir_id {
|
2015-11-25 23:09:01 +00:00
|
|
|
|
self.past_loop = true;
|
|
|
|
|
return;
|
2015-08-23 17:25:45 +00:00
|
|
|
|
}
|
|
|
|
|
// No need to visit expressions before the variable is
|
2015-11-25 23:09:01 +00:00
|
|
|
|
// declared
|
2020-10-23 20:16:59 +00:00
|
|
|
|
if matches!(self.state, InitializeVisitorState::Initial) {
|
2015-08-23 17:25:45 +00:00
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// If node is the desired variable, see how it's used
|
|
|
|
|
if var_def_id(self.cx, expr) == Some(self.var_id) {
|
2020-10-23 20:16:59 +00:00
|
|
|
|
if self.past_loop {
|
|
|
|
|
self.state = InitializeVisitorState::DontWarn;
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2015-08-23 17:25:45 +00:00
|
|
|
|
if let Some(parent) = get_parent_expr(self.cx, expr) {
|
2019-09-27 15:16:06 +00:00
|
|
|
|
match parent.kind {
|
2019-02-24 18:43:15 +00:00
|
|
|
|
ExprKind::AssignOp(_, ref lhs, _) if lhs.hir_id == expr.hir_id => {
|
2020-10-23 20:16:59 +00:00
|
|
|
|
self.state = InitializeVisitorState::DontWarn;
|
2016-12-20 17:21:30 +00:00
|
|
|
|
},
|
2019-12-24 04:16:04 +00:00
|
|
|
|
ExprKind::Assign(ref lhs, ref rhs, _) if lhs.hir_id == expr.hir_id => {
|
2020-10-23 20:16:59 +00:00
|
|
|
|
self.state = if_chain! {
|
|
|
|
|
if self.depth == 0;
|
|
|
|
|
if let InitializeVisitorState::Declared(name)
|
|
|
|
|
| InitializeVisitorState::Initialized { name, ..} = self.state;
|
|
|
|
|
then {
|
|
|
|
|
InitializeVisitorState::Initialized { initializer: rhs, name }
|
|
|
|
|
} else {
|
|
|
|
|
InitializeVisitorState::DontWarn
|
|
|
|
|
}
|
2016-01-04 04:26:12 +00:00
|
|
|
|
}
|
2016-12-20 17:21:30 +00:00
|
|
|
|
},
|
2019-12-21 18:38:45 +00:00
|
|
|
|
ExprKind::AddrOf(BorrowKind::Ref, mutability, _) if mutability == Mutability::Mut => {
|
2020-10-23 20:16:59 +00:00
|
|
|
|
self.state = InitializeVisitorState::DontWarn
|
2019-11-11 17:24:12 +00:00
|
|
|
|
},
|
2016-01-04 04:26:12 +00:00
|
|
|
|
_ => (),
|
2015-08-23 17:25:45 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
2018-09-07 12:32:56 +00:00
|
|
|
|
|
2020-10-23 20:16:59 +00:00
|
|
|
|
walk_expr(self, expr);
|
2018-09-07 12:32:56 +00:00
|
|
|
|
} else if !self.past_loop && is_loop(expr) {
|
2020-10-23 20:16:59 +00:00
|
|
|
|
self.state = InitializeVisitorState::DontWarn;
|
2016-01-04 04:26:12 +00:00
|
|
|
|
} else if is_conditional(expr) {
|
2015-08-23 17:25:45 +00:00
|
|
|
|
self.depth += 1;
|
|
|
|
|
walk_expr(self, expr);
|
|
|
|
|
self.depth -= 1;
|
2020-10-23 20:16:59 +00:00
|
|
|
|
} else {
|
|
|
|
|
walk_expr(self, expr);
|
2015-08-23 17:25:45 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
2019-11-11 10:27:18 +00:00
|
|
|
|
|
2020-03-15 22:41:20 +00:00
|
|
|
|
fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
|
|
|
|
|
NestedVisitorMap::OnlyBodies(self.cx.tcx.hir())
|
2016-12-06 10:32:21 +00:00
|
|
|
|
}
|
2015-08-23 17:25:45 +00:00
|
|
|
|
}
|
|
|
|
|
|
2020-06-25 20:41:36 +00:00
|
|
|
|
fn var_def_id(cx: &LateContext<'_>, expr: &Expr<'_>) -> Option<HirId> {
|
2019-09-27 15:16:06 +00:00
|
|
|
|
if let ExprKind::Path(ref qpath) = expr.kind {
|
2019-09-18 17:29:04 +00:00
|
|
|
|
let path_res = qpath_res(cx, qpath, expr.hir_id);
|
2020-04-19 12:19:11 +00:00
|
|
|
|
if let Res::Local(hir_id) = path_res {
|
|
|
|
|
return Some(hir_id);
|
2015-08-23 17:25:45 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
None
|
|
|
|
|
}
|
|
|
|
|
|
2019-12-27 07:12:26 +00:00
|
|
|
|
fn is_loop(expr: &Expr<'_>) -> bool {
|
2020-07-14 12:59:59 +00:00
|
|
|
|
matches!(expr.kind, ExprKind::Loop(..))
|
2015-08-23 17:25:45 +00:00
|
|
|
|
}
|
|
|
|
|
|
2019-12-27 07:12:26 +00:00
|
|
|
|
fn is_conditional(expr: &Expr<'_>) -> bool {
|
2020-07-14 12:59:59 +00:00
|
|
|
|
matches!(expr.kind, ExprKind::Match(..))
|
2015-08-23 17:25:45 +00:00
|
|
|
|
}
|
2017-07-31 22:58:26 +00:00
|
|
|
|
|
2020-06-25 20:41:36 +00:00
|
|
|
|
fn is_nested(cx: &LateContext<'_>, match_expr: &Expr<'_>, iter_expr: &Expr<'_>) -> bool {
|
2017-10-23 19:18:02 +00:00
|
|
|
|
if_chain! {
|
2019-02-24 18:43:15 +00:00
|
|
|
|
if let Some(loop_block) = get_enclosing_block(cx, match_expr.hir_id);
|
2019-06-25 21:33:51 +00:00
|
|
|
|
let parent_node = cx.tcx.hir().get_parent_node(loop_block.hir_id);
|
2019-06-25 21:34:07 +00:00
|
|
|
|
if let Some(Node::Expr(loop_expr)) = cx.tcx.hir().find(parent_node);
|
2017-10-23 19:18:02 +00:00
|
|
|
|
then {
|
|
|
|
|
return is_loop_nested(cx, loop_expr, iter_expr)
|
|
|
|
|
}
|
|
|
|
|
}
|
2017-07-31 22:58:26 +00:00
|
|
|
|
false
|
|
|
|
|
}
|
|
|
|
|
|
2020-06-25 20:41:36 +00:00
|
|
|
|
fn is_loop_nested(cx: &LateContext<'_>, loop_expr: &Expr<'_>, iter_expr: &Expr<'_>) -> bool {
|
2019-02-24 18:43:15 +00:00
|
|
|
|
let mut id = loop_expr.hir_id;
|
2017-08-02 22:41:46 +00:00
|
|
|
|
let iter_name = if let Some(name) = path_name(iter_expr) {
|
|
|
|
|
name
|
|
|
|
|
} else {
|
|
|
|
|
return true;
|
|
|
|
|
};
|
|
|
|
|
loop {
|
2019-06-25 21:33:51 +00:00
|
|
|
|
let parent = cx.tcx.hir().get_parent_node(id);
|
2017-08-02 22:41:46 +00:00
|
|
|
|
if parent == id {
|
|
|
|
|
return false;
|
|
|
|
|
}
|
2019-06-25 21:34:07 +00:00
|
|
|
|
match cx.tcx.hir().find(parent) {
|
2019-07-06 17:06:49 +00:00
|
|
|
|
Some(Node::Expr(expr)) => {
|
2019-09-27 15:16:06 +00:00
|
|
|
|
if let ExprKind::Loop(..) = expr.kind {
|
2017-11-04 19:55:56 +00:00
|
|
|
|
return true;
|
2019-07-06 17:06:49 +00:00
|
|
|
|
};
|
2017-08-02 22:41:46 +00:00
|
|
|
|
},
|
2018-08-28 11:13:42 +00:00
|
|
|
|
Some(Node::Block(block)) => {
|
2017-08-02 22:41:46 +00:00
|
|
|
|
let mut block_visitor = LoopNestVisitor {
|
2019-02-24 18:43:15 +00:00
|
|
|
|
hir_id: id,
|
2017-08-09 07:30:56 +00:00
|
|
|
|
iterator: iter_name,
|
|
|
|
|
nesting: Unknown,
|
|
|
|
|
};
|
2017-08-02 22:41:46 +00:00
|
|
|
|
walk_block(&mut block_visitor, block);
|
|
|
|
|
if block_visitor.nesting == RuledOut {
|
2017-07-31 22:58:26 +00:00
|
|
|
|
return false;
|
|
|
|
|
}
|
2017-08-02 22:41:46 +00:00
|
|
|
|
},
|
2018-08-28 11:13:42 +00:00
|
|
|
|
Some(Node::Stmt(_)) => (),
|
2017-08-02 22:41:46 +00:00
|
|
|
|
_ => {
|
2017-07-31 22:58:26 +00:00
|
|
|
|
return false;
|
2017-08-09 07:30:56 +00:00
|
|
|
|
},
|
2017-07-31 22:58:26 +00:00
|
|
|
|
}
|
2017-08-02 22:41:46 +00:00
|
|
|
|
id = parent;
|
2017-07-31 22:58:26 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2017-08-02 22:41:46 +00:00
|
|
|
|
#[derive(PartialEq, Eq)]
|
|
|
|
|
enum Nesting {
|
2017-11-04 19:55:56 +00:00
|
|
|
|
Unknown, // no nesting detected yet
|
|
|
|
|
RuledOut, // the iterator is initialized or assigned within scope
|
2017-08-09 07:30:56 +00:00
|
|
|
|
LookFurther, // no nesting detected, no further walk required
|
2017-07-31 22:58:26 +00:00
|
|
|
|
}
|
|
|
|
|
|
2017-09-05 09:33:04 +00:00
|
|
|
|
use self::Nesting::{LookFurther, RuledOut, Unknown};
|
2017-07-31 22:58:26 +00:00
|
|
|
|
|
2017-08-02 22:41:46 +00:00
|
|
|
|
struct LoopNestVisitor {
|
2019-02-24 18:43:15 +00:00
|
|
|
|
hir_id: HirId,
|
2020-08-11 13:43:21 +00:00
|
|
|
|
iterator: Symbol,
|
2017-08-09 07:30:56 +00:00
|
|
|
|
nesting: Nesting,
|
2017-07-31 22:58:26 +00:00
|
|
|
|
}
|
|
|
|
|
|
2017-08-02 22:41:46 +00:00
|
|
|
|
impl<'tcx> Visitor<'tcx> for LoopNestVisitor {
|
2020-01-09 07:13:22 +00:00
|
|
|
|
type Map = Map<'tcx>;
|
|
|
|
|
|
2019-12-27 07:12:26 +00:00
|
|
|
|
fn visit_stmt(&mut self, stmt: &'tcx Stmt<'_>) {
|
2019-02-24 18:43:15 +00:00
|
|
|
|
if stmt.hir_id == self.hir_id {
|
2017-08-02 22:41:46 +00:00
|
|
|
|
self.nesting = LookFurther;
|
|
|
|
|
} else if self.nesting == Unknown {
|
|
|
|
|
walk_stmt(self, stmt);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2019-12-27 07:12:26 +00:00
|
|
|
|
fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
|
2017-08-09 07:30:56 +00:00
|
|
|
|
if self.nesting != Unknown {
|
|
|
|
|
return;
|
|
|
|
|
}
|
2019-02-24 18:43:15 +00:00
|
|
|
|
if expr.hir_id == self.hir_id {
|
2017-08-02 22:41:46 +00:00
|
|
|
|
self.nesting = LookFurther;
|
|
|
|
|
return;
|
|
|
|
|
}
|
2019-09-27 15:16:06 +00:00
|
|
|
|
match expr.kind {
|
2019-12-24 04:16:04 +00:00
|
|
|
|
ExprKind::Assign(ref path, _, _) | ExprKind::AssignOp(_, ref path, _) => {
|
2018-11-27 20:14:15 +00:00
|
|
|
|
if match_var(path, self.iterator) {
|
|
|
|
|
self.nesting = RuledOut;
|
|
|
|
|
}
|
2017-08-02 22:41:46 +00:00
|
|
|
|
},
|
2017-08-09 07:30:56 +00:00
|
|
|
|
_ => walk_expr(self, expr),
|
2017-07-31 22:58:26 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2019-12-27 07:12:26 +00:00
|
|
|
|
fn visit_pat(&mut self, pat: &'tcx Pat<'_>) {
|
2017-08-09 07:30:56 +00:00
|
|
|
|
if self.nesting != Unknown {
|
|
|
|
|
return;
|
|
|
|
|
}
|
2019-09-27 15:16:06 +00:00
|
|
|
|
if let PatKind::Binding(.., span_name, _) = pat.kind {
|
2018-06-28 13:46:58 +00:00
|
|
|
|
if self.iterator == span_name.name {
|
2017-08-02 22:41:46 +00:00
|
|
|
|
self.nesting = RuledOut;
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
walk_pat(self, pat)
|
2017-07-31 22:58:26 +00:00
|
|
|
|
}
|
|
|
|
|
|
2020-03-15 22:41:20 +00:00
|
|
|
|
fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
|
2017-08-02 22:41:46 +00:00
|
|
|
|
NestedVisitorMap::None
|
2017-07-31 22:58:26 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2020-08-11 13:43:21 +00:00
|
|
|
|
fn path_name(e: &Expr<'_>) -> Option<Symbol> {
|
2019-09-27 15:16:06 +00:00
|
|
|
|
if let ExprKind::Path(QPath::Resolved(_, ref path)) = e.kind {
|
2017-08-02 22:41:46 +00:00
|
|
|
|
let segments = &path.segments;
|
|
|
|
|
if segments.len() == 1 {
|
2018-06-28 13:46:58 +00:00
|
|
|
|
return Some(segments[0].ident.name);
|
2017-08-02 22:41:46 +00:00
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
None
|
2017-07-31 22:58:26 +00:00
|
|
|
|
}
|
2018-03-01 21:00:43 +00:00
|
|
|
|
|
2020-06-25 20:41:36 +00:00
|
|
|
|
fn check_infinite_loop<'tcx>(cx: &LateContext<'tcx>, cond: &'tcx Expr<'_>, expr: &'tcx Expr<'_>) {
|
2020-07-17 08:47:04 +00:00
|
|
|
|
if constant(cx, cx.typeck_results(), cond).is_some() {
|
2019-03-10 17:19:47 +00:00
|
|
|
|
// A pure constant condition (e.g., `while false`) is not linted.
|
2018-03-07 17:24:36 +00:00
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2018-05-27 22:02:38 +00:00
|
|
|
|
let mut var_visitor = VarCollectorVisitor {
|
2018-03-01 21:00:43 +00:00
|
|
|
|
cx,
|
2018-09-11 23:34:52 +00:00
|
|
|
|
ids: FxHashSet::default(),
|
|
|
|
|
def_ids: FxHashMap::default(),
|
2018-03-01 21:00:43 +00:00
|
|
|
|
skip: false,
|
|
|
|
|
};
|
2018-05-27 22:02:38 +00:00
|
|
|
|
var_visitor.visit_expr(cond);
|
|
|
|
|
if var_visitor.skip {
|
2018-03-01 22:23:41 +00:00
|
|
|
|
return;
|
|
|
|
|
}
|
2018-05-27 22:02:38 +00:00
|
|
|
|
let used_in_condition = &var_visitor.ids;
|
|
|
|
|
let no_cond_variable_mutated = if let Some(used_mutably) = mutated_variables(expr, cx) {
|
|
|
|
|
used_in_condition.is_disjoint(&used_mutably)
|
|
|
|
|
} else {
|
2018-11-27 20:14:15 +00:00
|
|
|
|
return;
|
2018-03-01 22:23:41 +00:00
|
|
|
|
};
|
2018-05-27 22:02:38 +00:00
|
|
|
|
let mutable_static_in_cond = var_visitor.def_ids.iter().any(|(_, v)| *v);
|
2019-10-25 06:46:25 +00:00
|
|
|
|
|
|
|
|
|
let mut has_break_or_return_visitor = HasBreakOrReturnVisitor {
|
|
|
|
|
has_break_or_return: false,
|
|
|
|
|
};
|
|
|
|
|
has_break_or_return_visitor.visit_expr(expr);
|
|
|
|
|
let has_break_or_return = has_break_or_return_visitor.has_break_or_return;
|
|
|
|
|
|
2018-05-27 22:02:38 +00:00
|
|
|
|
if no_cond_variable_mutated && !mutable_static_in_cond {
|
2019-10-25 06:46:25 +00:00
|
|
|
|
span_lint_and_then(
|
2018-03-01 22:23:41 +00:00
|
|
|
|
cx,
|
|
|
|
|
WHILE_IMMUTABLE_CONDITION,
|
2018-03-26 21:24:57 +00:00
|
|
|
|
cond.span,
|
2019-10-25 06:46:25 +00:00
|
|
|
|
"variables in the condition are not mutated in the loop body",
|
2020-04-17 06:08:00 +00:00
|
|
|
|
|diag| {
|
|
|
|
|
diag.note("this may lead to an infinite or to a never running loop");
|
2019-10-25 06:46:25 +00:00
|
|
|
|
|
|
|
|
|
if has_break_or_return {
|
2020-04-17 06:08:00 +00:00
|
|
|
|
diag.note("this loop contains `return`s or `break`s");
|
|
|
|
|
diag.help("rewrite it as `if cond { loop { } }`");
|
2019-10-25 06:46:25 +00:00
|
|
|
|
}
|
|
|
|
|
},
|
2018-03-01 22:23:41 +00:00
|
|
|
|
);
|
2018-03-01 21:00:43 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2019-10-25 06:46:25 +00:00
|
|
|
|
struct HasBreakOrReturnVisitor {
|
|
|
|
|
has_break_or_return: bool,
|
|
|
|
|
}
|
|
|
|
|
|
2020-06-23 15:05:22 +00:00
|
|
|
|
impl<'tcx> Visitor<'tcx> for HasBreakOrReturnVisitor {
|
2020-01-09 07:13:22 +00:00
|
|
|
|
type Map = Map<'tcx>;
|
|
|
|
|
|
2019-12-27 07:12:26 +00:00
|
|
|
|
fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
|
2019-10-25 06:46:25 +00:00
|
|
|
|
if self.has_break_or_return {
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
match expr.kind {
|
|
|
|
|
ExprKind::Ret(_) | ExprKind::Break(_, _) => {
|
|
|
|
|
self.has_break_or_return = true;
|
|
|
|
|
return;
|
|
|
|
|
},
|
|
|
|
|
_ => {},
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
walk_expr(self, expr);
|
|
|
|
|
}
|
|
|
|
|
|
2020-03-15 22:41:20 +00:00
|
|
|
|
fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
|
2019-10-25 06:46:25 +00:00
|
|
|
|
NestedVisitorMap::None
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2018-03-26 18:37:34 +00:00
|
|
|
|
/// Collects the set of variables in an expression
|
2018-03-01 22:23:41 +00:00
|
|
|
|
/// Stops analysis if a function call is found
|
2018-03-26 18:37:34 +00:00
|
|
|
|
/// Note: In some cases such as `self`, there are no mutable annotation,
|
|
|
|
|
/// All variables definition IDs are collected
|
2019-06-19 18:36:23 +00:00
|
|
|
|
struct VarCollectorVisitor<'a, 'tcx> {
|
2020-06-25 20:41:36 +00:00
|
|
|
|
cx: &'a LateContext<'tcx>,
|
2019-03-01 12:26:06 +00:00
|
|
|
|
ids: FxHashSet<HirId>,
|
2018-09-11 23:34:52 +00:00
|
|
|
|
def_ids: FxHashMap<def_id::DefId, bool>,
|
2018-03-01 21:00:43 +00:00
|
|
|
|
skip: bool,
|
|
|
|
|
}
|
|
|
|
|
|
2018-03-26 18:37:34 +00:00
|
|
|
|
impl<'a, 'tcx> VarCollectorVisitor<'a, 'tcx> {
|
2019-12-27 07:12:26 +00:00
|
|
|
|
fn insert_def_id(&mut self, ex: &'tcx Expr<'_>) {
|
2018-03-26 18:37:34 +00:00
|
|
|
|
if_chain! {
|
2019-09-27 15:16:06 +00:00
|
|
|
|
if let ExprKind::Path(ref qpath) = ex.kind;
|
2018-03-26 18:37:34 +00:00
|
|
|
|
if let QPath::Resolved(None, _) = *qpath;
|
2019-09-18 17:29:04 +00:00
|
|
|
|
let res = qpath_res(self.cx, qpath, ex.hir_id);
|
2018-03-26 18:37:34 +00:00
|
|
|
|
then {
|
2019-05-04 00:03:12 +00:00
|
|
|
|
match res {
|
2020-04-19 12:19:11 +00:00
|
|
|
|
Res::Local(hir_id) => {
|
|
|
|
|
self.ids.insert(hir_id);
|
2018-03-26 10:32:21 +00:00
|
|
|
|
},
|
2019-05-04 00:03:12 +00:00
|
|
|
|
Res::Def(DefKind::Static, def_id) => {
|
2019-04-21 19:00:52 +00:00
|
|
|
|
let mutable = self.cx.tcx.is_mutable_static(def_id);
|
2018-05-27 21:59:07 +00:00
|
|
|
|
self.def_ids.insert(def_id, mutable);
|
|
|
|
|
},
|
2018-03-26 10:32:21 +00:00
|
|
|
|
_ => {},
|
|
|
|
|
}
|
2018-03-26 18:37:34 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl<'a, 'tcx> Visitor<'tcx> for VarCollectorVisitor<'a, 'tcx> {
|
2020-01-09 07:13:22 +00:00
|
|
|
|
type Map = Map<'tcx>;
|
|
|
|
|
|
2019-12-27 07:12:26 +00:00
|
|
|
|
fn visit_expr(&mut self, ex: &'tcx Expr<'_>) {
|
2019-09-27 15:16:06 +00:00
|
|
|
|
match ex.kind {
|
2018-07-12 07:30:57 +00:00
|
|
|
|
ExprKind::Path(_) => self.insert_def_id(ex),
|
2018-07-25 18:02:52 +00:00
|
|
|
|
// If there is any function/method call… we just stop analysis
|
2018-07-12 07:30:57 +00:00
|
|
|
|
ExprKind::Call(..) | ExprKind::MethodCall(..) => self.skip = true,
|
2018-03-01 21:00:43 +00:00
|
|
|
|
|
|
|
|
|
_ => walk_expr(self, ex),
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2020-03-15 22:41:20 +00:00
|
|
|
|
fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
|
2018-03-01 22:23:41 +00:00
|
|
|
|
NestedVisitorMap::None
|
|
|
|
|
}
|
|
|
|
|
}
|
2018-08-30 03:01:24 +00:00
|
|
|
|
|
2018-08-31 22:26:04 +00:00
|
|
|
|
const NEEDLESS_COLLECT_MSG: &str = "avoid using `collect()` when not needed";
|
|
|
|
|
|
2020-06-25 20:41:36 +00:00
|
|
|
|
fn check_needless_collect<'tcx>(expr: &'tcx Expr<'_>, cx: &LateContext<'tcx>) {
|
2020-08-11 13:43:21 +00:00
|
|
|
|
check_needless_collect_direct_usage(expr, cx);
|
|
|
|
|
check_needless_collect_indirect_usage(expr, cx);
|
|
|
|
|
}
|
|
|
|
|
fn check_needless_collect_direct_usage<'tcx>(expr: &'tcx Expr<'_>, cx: &LateContext<'tcx>) {
|
2018-09-04 03:58:10 +00:00
|
|
|
|
if_chain! {
|
2020-06-09 21:44:04 +00:00
|
|
|
|
if let ExprKind::MethodCall(ref method, _, ref args, _) = expr.kind;
|
|
|
|
|
if let ExprKind::MethodCall(ref chain_method, _, _, _) = args[0].kind;
|
2019-05-17 21:53:54 +00:00
|
|
|
|
if chain_method.ident.name == sym!(collect) && match_trait_method(cx, &args[0], &paths::ITERATOR);
|
2018-09-04 03:58:10 +00:00
|
|
|
|
if let Some(ref generic_args) = chain_method.args;
|
|
|
|
|
if let Some(GenericArg::Type(ref ty)) = generic_args.args.get(0);
|
|
|
|
|
then {
|
2020-07-17 08:47:04 +00:00
|
|
|
|
let ty = cx.typeck_results().node_type(ty.hir_id);
|
2020-04-13 06:57:34 +00:00
|
|
|
|
if is_type_diagnostic_item(cx, ty, sym!(vec_type)) ||
|
2020-04-23 06:09:42 +00:00
|
|
|
|
is_type_diagnostic_item(cx, ty, sym!(vecdeque_type)) ||
|
2019-05-17 21:53:54 +00:00
|
|
|
|
match_type(cx, ty, &paths::BTREEMAP) ||
|
2020-04-23 06:09:42 +00:00
|
|
|
|
is_type_diagnostic_item(cx, ty, sym!(hashmap_type)) {
|
2019-05-17 21:53:54 +00:00
|
|
|
|
if method.ident.name == sym!(len) {
|
2020-08-11 13:43:21 +00:00
|
|
|
|
let span = shorten_needless_collect_span(expr);
|
2020-04-19 18:38:07 +00:00
|
|
|
|
span_lint_and_sugg(
|
|
|
|
|
cx,
|
2020-04-17 14:01:25 +00:00
|
|
|
|
NEEDLESS_COLLECT,
|
|
|
|
|
span,
|
|
|
|
|
NEEDLESS_COLLECT_MSG,
|
2020-04-19 18:38:07 +00:00
|
|
|
|
"replace with",
|
2020-06-09 14:36:01 +00:00
|
|
|
|
"count()".to_string(),
|
2020-04-19 18:38:07 +00:00
|
|
|
|
Applicability::MachineApplicable,
|
|
|
|
|
);
|
2018-09-04 03:58:10 +00:00
|
|
|
|
}
|
2019-05-17 21:53:54 +00:00
|
|
|
|
if method.ident.name == sym!(is_empty) {
|
2020-08-11 13:43:21 +00:00
|
|
|
|
let span = shorten_needless_collect_span(expr);
|
2020-04-19 18:38:07 +00:00
|
|
|
|
span_lint_and_sugg(
|
|
|
|
|
cx,
|
2020-04-17 14:01:25 +00:00
|
|
|
|
NEEDLESS_COLLECT,
|
|
|
|
|
span,
|
|
|
|
|
NEEDLESS_COLLECT_MSG,
|
|
|
|
|
"replace with",
|
2020-08-11 13:43:21 +00:00
|
|
|
|
"next().is_none()".to_string(),
|
2020-04-17 14:01:25 +00:00
|
|
|
|
Applicability::MachineApplicable,
|
2020-04-19 18:38:07 +00:00
|
|
|
|
);
|
2018-09-04 03:58:10 +00:00
|
|
|
|
}
|
2019-05-17 21:53:54 +00:00
|
|
|
|
if method.ident.name == sym!(contains) {
|
2018-09-04 03:58:10 +00:00
|
|
|
|
let contains_arg = snippet(cx, args[1].span, "??");
|
2020-08-11 13:43:21 +00:00
|
|
|
|
let span = shorten_needless_collect_span(expr);
|
2020-04-19 18:38:07 +00:00
|
|
|
|
span_lint_and_then(
|
|
|
|
|
cx,
|
2020-04-17 14:01:25 +00:00
|
|
|
|
NEEDLESS_COLLECT,
|
|
|
|
|
span,
|
|
|
|
|
NEEDLESS_COLLECT_MSG,
|
2020-04-19 18:40:25 +00:00
|
|
|
|
|diag| {
|
2020-09-24 12:49:22 +00:00
|
|
|
|
let (arg, pred) = contains_arg
|
|
|
|
|
.strip_prefix('&')
|
|
|
|
|
.map_or(("&x", &*contains_arg), |s| ("x", s));
|
2020-04-19 18:40:25 +00:00
|
|
|
|
diag.span_suggestion(
|
2020-04-17 14:01:25 +00:00
|
|
|
|
span,
|
|
|
|
|
"replace with",
|
|
|
|
|
format!(
|
2020-06-09 14:36:01 +00:00
|
|
|
|
"any(|{}| x == {})",
|
2020-04-17 14:01:25 +00:00
|
|
|
|
arg, pred
|
|
|
|
|
),
|
|
|
|
|
Applicability::MachineApplicable,
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
);
|
2018-08-30 03:01:24 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2020-08-11 13:43:21 +00:00
|
|
|
|
fn check_needless_collect_indirect_usage<'tcx>(expr: &'tcx Expr<'_>, cx: &LateContext<'tcx>) {
|
|
|
|
|
if let ExprKind::Block(ref block, _) = expr.kind {
|
|
|
|
|
for ref stmt in block.stmts {
|
|
|
|
|
if_chain! {
|
|
|
|
|
if let StmtKind::Local(
|
|
|
|
|
Local { pat: Pat { kind: PatKind::Binding(_, _, ident, .. ), .. },
|
|
|
|
|
init: Some(ref init_expr), .. }
|
|
|
|
|
) = stmt.kind;
|
|
|
|
|
if let ExprKind::MethodCall(ref method_name, _, &[ref iter_source], ..) = init_expr.kind;
|
|
|
|
|
if method_name.ident.name == sym!(collect) && match_trait_method(cx, &init_expr, &paths::ITERATOR);
|
|
|
|
|
if let Some(ref generic_args) = method_name.args;
|
|
|
|
|
if let Some(GenericArg::Type(ref ty)) = generic_args.args.get(0);
|
|
|
|
|
if let ty = cx.typeck_results().node_type(ty.hir_id);
|
|
|
|
|
if is_type_diagnostic_item(cx, ty, sym::vec_type) ||
|
|
|
|
|
is_type_diagnostic_item(cx, ty, sym!(vecdeque_type)) ||
|
|
|
|
|
match_type(cx, ty, &paths::LINKED_LIST);
|
|
|
|
|
if let Some(iter_calls) = detect_iter_and_into_iters(block, *ident);
|
|
|
|
|
if iter_calls.len() == 1;
|
|
|
|
|
then {
|
|
|
|
|
// Suggest replacing iter_call with iter_replacement, and removing stmt
|
|
|
|
|
let iter_call = &iter_calls[0];
|
|
|
|
|
span_lint_and_then(
|
|
|
|
|
cx,
|
|
|
|
|
NEEDLESS_COLLECT,
|
|
|
|
|
stmt.span.until(iter_call.span),
|
|
|
|
|
NEEDLESS_COLLECT_MSG,
|
|
|
|
|
|diag| {
|
|
|
|
|
let iter_replacement = format!("{}{}", Sugg::hir(cx, iter_source, ".."), iter_call.get_iter_method(cx));
|
|
|
|
|
diag.multipart_suggestion(
|
|
|
|
|
iter_call.get_suggestion_text(),
|
|
|
|
|
vec![
|
|
|
|
|
(stmt.span, String::new()),
|
|
|
|
|
(iter_call.span, iter_replacement)
|
|
|
|
|
],
|
|
|
|
|
Applicability::MachineApplicable,// MaybeIncorrect,
|
|
|
|
|
).emit();
|
|
|
|
|
},
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
struct IterFunction {
|
|
|
|
|
func: IterFunctionKind,
|
|
|
|
|
span: Span,
|
|
|
|
|
}
|
|
|
|
|
impl IterFunction {
|
|
|
|
|
fn get_iter_method(&self, cx: &LateContext<'_>) -> String {
|
|
|
|
|
match &self.func {
|
|
|
|
|
IterFunctionKind::IntoIter => String::new(),
|
|
|
|
|
IterFunctionKind::Len => String::from(".count()"),
|
|
|
|
|
IterFunctionKind::IsEmpty => String::from(".next().is_none()"),
|
|
|
|
|
IterFunctionKind::Contains(span) => format!(".any(|x| x == {})", snippet(cx, *span, "..")),
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
fn get_suggestion_text(&self) -> &'static str {
|
|
|
|
|
match &self.func {
|
|
|
|
|
IterFunctionKind::IntoIter => {
|
|
|
|
|
"Use the original Iterator instead of collecting it and then producing a new one"
|
|
|
|
|
},
|
|
|
|
|
IterFunctionKind::Len => {
|
|
|
|
|
"Take the original Iterator's count instead of collecting it and finding the length"
|
|
|
|
|
},
|
|
|
|
|
IterFunctionKind::IsEmpty => {
|
|
|
|
|
"Check if the original Iterator has anything instead of collecting it and seeing if it's empty"
|
|
|
|
|
},
|
|
|
|
|
IterFunctionKind::Contains(_) => {
|
|
|
|
|
"Check if the original Iterator contains an element instead of collecting then checking"
|
|
|
|
|
},
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
enum IterFunctionKind {
|
|
|
|
|
IntoIter,
|
|
|
|
|
Len,
|
|
|
|
|
IsEmpty,
|
|
|
|
|
Contains(Span),
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
struct IterFunctionVisitor {
|
|
|
|
|
uses: Vec<IterFunction>,
|
|
|
|
|
seen_other: bool,
|
|
|
|
|
target: Ident,
|
|
|
|
|
}
|
|
|
|
|
impl<'tcx> Visitor<'tcx> for IterFunctionVisitor {
|
|
|
|
|
fn visit_expr(&mut self, expr: &'tcx Expr<'tcx>) {
|
|
|
|
|
// Check function calls on our collection
|
|
|
|
|
if_chain! {
|
|
|
|
|
if let ExprKind::MethodCall(method_name, _, ref args, _) = &expr.kind;
|
|
|
|
|
if let Some(Expr { kind: ExprKind::Path(QPath::Resolved(_, ref path)), .. }) = args.get(0);
|
|
|
|
|
if let &[name] = &path.segments;
|
|
|
|
|
if name.ident == self.target;
|
|
|
|
|
then {
|
|
|
|
|
let len = sym!(len);
|
|
|
|
|
let is_empty = sym!(is_empty);
|
|
|
|
|
let contains = sym!(contains);
|
|
|
|
|
match method_name.ident.name {
|
|
|
|
|
sym::into_iter => self.uses.push(
|
|
|
|
|
IterFunction { func: IterFunctionKind::IntoIter, span: expr.span }
|
|
|
|
|
),
|
|
|
|
|
name if name == len => self.uses.push(
|
|
|
|
|
IterFunction { func: IterFunctionKind::Len, span: expr.span }
|
|
|
|
|
),
|
|
|
|
|
name if name == is_empty => self.uses.push(
|
|
|
|
|
IterFunction { func: IterFunctionKind::IsEmpty, span: expr.span }
|
|
|
|
|
),
|
|
|
|
|
name if name == contains => self.uses.push(
|
|
|
|
|
IterFunction { func: IterFunctionKind::Contains(args[1].span), span: expr.span }
|
|
|
|
|
),
|
|
|
|
|
_ => self.seen_other = true,
|
|
|
|
|
}
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
// Check if the collection is used for anything else
|
|
|
|
|
if_chain! {
|
|
|
|
|
if let Expr { kind: ExprKind::Path(QPath::Resolved(_, ref path)), .. } = expr;
|
|
|
|
|
if let &[name] = &path.segments;
|
|
|
|
|
if name.ident == self.target;
|
|
|
|
|
then {
|
|
|
|
|
self.seen_other = true;
|
|
|
|
|
} else {
|
|
|
|
|
walk_expr(self, expr);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
type Map = Map<'tcx>;
|
|
|
|
|
fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
|
|
|
|
|
NestedVisitorMap::None
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Detect the occurences of calls to `iter` or `into_iter` for the
|
|
|
|
|
/// given identifier
|
|
|
|
|
fn detect_iter_and_into_iters<'tcx>(block: &'tcx Block<'tcx>, identifier: Ident) -> Option<Vec<IterFunction>> {
|
|
|
|
|
let mut visitor = IterFunctionVisitor {
|
|
|
|
|
uses: Vec::new(),
|
|
|
|
|
target: identifier,
|
|
|
|
|
seen_other: false,
|
|
|
|
|
};
|
|
|
|
|
visitor.visit_block(block);
|
|
|
|
|
if visitor.seen_other {
|
|
|
|
|
None
|
|
|
|
|
} else {
|
|
|
|
|
Some(visitor.uses)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn shorten_needless_collect_span(expr: &Expr<'_>) -> Span {
|
|
|
|
|
if_chain! {
|
|
|
|
|
if let ExprKind::MethodCall(.., args, _) = &expr.kind;
|
|
|
|
|
if let ExprKind::MethodCall(_, span, ..) = &args[0].kind;
|
|
|
|
|
then {
|
2020-06-09 14:36:01 +00:00
|
|
|
|
return expr.span.with_lo(span.lo());
|
2018-08-31 22:14:33 +00:00
|
|
|
|
}
|
2018-08-30 03:01:24 +00:00
|
|
|
|
}
|
2020-08-11 13:43:21 +00:00
|
|
|
|
unreachable!();
|
2018-08-30 03:01:24 +00:00
|
|
|
|
}
|