2017-09-05 00:16:34 +00:00
|
|
|
|
use itertools::Itertools;
|
2016-02-07 17:10:03 +00:00
|
|
|
|
use reexport::*;
|
2016-04-07 15:46:48 +00:00
|
|
|
|
use rustc::hir::*;
|
|
|
|
|
use rustc::hir::def::Def;
|
2017-10-25 19:41:31 +00:00
|
|
|
|
use rustc::hir::def_id;
|
2017-09-05 09:33:04 +00:00
|
|
|
|
use rustc::hir::intravisit::{walk_block, walk_decl, walk_expr, walk_pat, walk_stmt, NestedVisitorMap, Visitor};
|
2017-08-02 22:41:46 +00:00
|
|
|
|
use rustc::hir::map::Node::{NodeBlock, NodeExpr, NodeStmt};
|
2015-08-12 19:56:27 +00:00
|
|
|
|
use rustc::lint::*;
|
2017-09-04 14:10:36 +00:00
|
|
|
|
use rustc::middle::region;
|
2017-09-19 00:10:33 +00:00
|
|
|
|
// use rustc::middle::region::CodeExtent;
|
2017-08-30 14:38:13 +00:00
|
|
|
|
use rustc::middle::expr_use_visitor::*;
|
2017-09-19 00:10:33 +00:00
|
|
|
|
use rustc::middle::mem_categorization::Categorization;
|
2018-05-06 12:05:41 +00:00
|
|
|
|
use rustc::middle::mem_categorization::cmt_;
|
2017-06-11 02:57:25 +00:00
|
|
|
|
use rustc::ty::{self, Ty};
|
2018-03-13 10:38:11 +00:00
|
|
|
|
use rustc::ty::subst::Subst;
|
2017-07-10 13:30:28 +00:00
|
|
|
|
use std::collections::{HashMap, HashSet};
|
2017-11-04 19:55:56 +00:00
|
|
|
|
use std::iter::{once, Iterator};
|
2016-03-07 15:55:12 +00:00
|
|
|
|
use syntax::ast;
|
2017-08-30 14:38:13 +00:00
|
|
|
|
use syntax::codemap::Span;
|
2018-03-13 10:38:11 +00:00
|
|
|
|
use utils::{sugg, sext};
|
|
|
|
|
use consts::{constant, Constant};
|
2018-03-07 17:24:36 +00:00
|
|
|
|
|
2017-09-05 09:33:04 +00:00
|
|
|
|
use utils::{get_enclosing_block, get_parent_expr, higher, in_external_macro, is_integer_literal, is_refutable,
|
2017-09-16 07:10:26 +00:00
|
|
|
|
last_path_segment, match_trait_method, match_type, match_var, multispan_sugg, snippet, snippet_opt,
|
2017-09-05 00:16:34 +00:00
|
|
|
|
span_help_and_lint, span_lint, span_lint_and_sugg, span_lint_and_then};
|
2016-04-14 16:13:15 +00:00
|
|
|
|
use utils::paths;
|
2015-08-12 19:56:27 +00:00
|
|
|
|
|
2017-09-05 19:10:53 +00:00
|
|
|
|
/// **What it does:** Checks for for-loops that manually copy items between
|
2017-09-05 00:16:34 +00:00
|
|
|
|
/// 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:**
|
|
|
|
|
/// ```rust
|
|
|
|
|
/// for i in 0..src.len() {
|
|
|
|
|
/// dst[i + 64] = src[i];
|
|
|
|
|
/// }
|
|
|
|
|
/// ```
|
2018-03-28 13:24:26 +00:00
|
|
|
|
declare_clippy_lint! {
|
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"
|
|
|
|
|
}
|
|
|
|
|
|
2016-08-06 07:55:04 +00:00
|
|
|
|
/// **What it does:** Checks for looping over the range of `0..len` of some
|
|
|
|
|
/// collection just to get the values by index.
|
2015-12-11 00:22:27 +00:00
|
|
|
|
///
|
2016-08-06 07:55:04 +00:00
|
|
|
|
/// **Why is this bad?** Just iterating the collection itself makes the intent
|
|
|
|
|
/// more clear and is probably faster.
|
2015-12-11 00:22:27 +00:00
|
|
|
|
///
|
2016-08-06 07:55:04 +00:00
|
|
|
|
/// **Known problems:** None.
|
2015-12-11 00:22:27 +00:00
|
|
|
|
///
|
|
|
|
|
/// **Example:**
|
2016-07-15 22:25:44 +00:00
|
|
|
|
/// ```rust
|
2015-12-11 00:22:27 +00:00
|
|
|
|
/// for i in 0..vec.len() {
|
|
|
|
|
/// println!("{}", vec[i]);
|
|
|
|
|
/// }
|
|
|
|
|
/// ```
|
2018-03-28 13:24:26 +00:00
|
|
|
|
declare_clippy_lint! {
|
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
|
|
|
|
|
2016-08-06 07:55:04 +00:00
|
|
|
|
/// **What it does:** Checks for loops on `x.iter()` where `&x` will do, and
|
|
|
|
|
/// suggests the latter.
|
2015-12-11 00:22:27 +00:00
|
|
|
|
///
|
|
|
|
|
/// **Why is this bad?** Readability.
|
|
|
|
|
///
|
2016-08-06 07:55:04 +00:00
|
|
|
|
/// **Known problems:** False negatives. We currently only warn on some known
|
|
|
|
|
/// types.
|
2015-12-11 00:22:27 +00:00
|
|
|
|
///
|
2016-07-15 22:25:44 +00:00
|
|
|
|
/// **Example:**
|
|
|
|
|
/// ```rust
|
|
|
|
|
/// // with `y` a `Vec` or slice:
|
|
|
|
|
/// for x in y.iter() { .. }
|
|
|
|
|
/// ```
|
2018-03-28 13:24:26 +00:00
|
|
|
|
declare_clippy_lint! {
|
2016-02-05 23:13:29 +00:00
|
|
|
|
pub EXPLICIT_ITER_LOOP,
|
2018-03-28 13:24:26 +00:00
|
|
|
|
style,
|
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
|
|
|
|
|
2016-10-01 00:01:30 +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:**
|
|
|
|
|
/// ```rust
|
|
|
|
|
/// // with `y` a `Vec` or slice:
|
|
|
|
|
/// for x in y.into_iter() { .. }
|
|
|
|
|
/// ```
|
2018-03-28 13:24:26 +00:00
|
|
|
|
declare_clippy_lint! {
|
2016-10-01 00:01:30 +00:00
|
|
|
|
pub EXPLICIT_INTO_ITER_LOOP,
|
2018-03-28 13:24:26 +00:00
|
|
|
|
style,
|
2016-10-01 00:01:30 +00:00
|
|
|
|
"for-looping over `_.into_iter()` when `_` would do"
|
|
|
|
|
}
|
|
|
|
|
|
2016-08-06 07:55:04 +00:00
|
|
|
|
/// **What it does:** Checks for loops on `x.next()`.
|
2015-12-11 00:22:27 +00:00
|
|
|
|
///
|
2016-08-06 07:55:04 +00:00
|
|
|
|
/// **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
|
2018-04-14 09:35:52 +00:00
|
|
|
|
/// Contest](https://www.reddit.com/r/rust/comments/3hb0wm/underhanded_rust_contest/cu5yuhr).
|
2015-12-11 00:22:27 +00:00
|
|
|
|
///
|
2016-08-06 07:55:04 +00:00
|
|
|
|
/// **Known problems:** None.
|
2015-12-11 00:22:27 +00:00
|
|
|
|
///
|
2016-07-15 22:25:44 +00:00
|
|
|
|
/// **Example:**
|
|
|
|
|
/// ```rust
|
|
|
|
|
/// for x in y.next() { .. }
|
|
|
|
|
/// ```
|
2018-03-28 13:24:26 +00:00
|
|
|
|
declare_clippy_lint! {
|
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
|
|
|
|
|
2016-08-06 07:55:04 +00:00
|
|
|
|
/// **What it does:** Checks for `for` loops over `Option` values.
|
2016-01-29 07:34:09 +00:00
|
|
|
|
///
|
2017-08-09 07:30:56 +00:00
|
|
|
|
/// **Why is this bad?** Readability. This is more clearly expressed as an `if
|
|
|
|
|
/// let`.
|
2016-01-29 07:34:09 +00:00
|
|
|
|
///
|
2016-08-06 07:55:04 +00:00
|
|
|
|
/// **Known problems:** None.
|
2016-01-29 07:34:09 +00:00
|
|
|
|
///
|
2016-07-15 22:25:44 +00:00
|
|
|
|
/// **Example:**
|
|
|
|
|
/// ```rust
|
|
|
|
|
/// for x in option { .. }
|
|
|
|
|
/// ```
|
|
|
|
|
///
|
|
|
|
|
/// This should be
|
|
|
|
|
/// ```rust
|
|
|
|
|
/// if let Some(x) = option { .. }
|
|
|
|
|
/// ```
|
2018-03-28 13:24:26 +00:00
|
|
|
|
declare_clippy_lint! {
|
2016-02-05 23:13:29 +00:00
|
|
|
|
pub FOR_LOOP_OVER_OPTION,
|
2018-03-29 11:41:53 +00:00
|
|
|
|
correctness,
|
2016-02-05 23:13:29 +00:00
|
|
|
|
"for-looping over an `Option`, which is more clearly expressed as an `if let`"
|
|
|
|
|
}
|
2016-01-29 23:15:57 +00:00
|
|
|
|
|
2016-08-06 07:55:04 +00:00
|
|
|
|
/// **What it does:** Checks for `for` loops over `Result` values.
|
2016-01-29 23:15:57 +00:00
|
|
|
|
///
|
2017-08-09 07:30:56 +00:00
|
|
|
|
/// **Why is this bad?** Readability. This is more clearly expressed as an `if
|
|
|
|
|
/// let`.
|
2016-01-29 23:15:57 +00:00
|
|
|
|
///
|
2016-08-06 07:55:04 +00:00
|
|
|
|
/// **Known problems:** None.
|
2016-01-29 23:15:57 +00:00
|
|
|
|
///
|
2016-07-15 22:25:44 +00:00
|
|
|
|
/// **Example:**
|
|
|
|
|
/// ```rust
|
|
|
|
|
/// for x in result { .. }
|
|
|
|
|
/// ```
|
|
|
|
|
///
|
|
|
|
|
/// This should be
|
|
|
|
|
/// ```rust
|
|
|
|
|
/// if let Ok(x) = result { .. }
|
|
|
|
|
/// ```
|
2018-03-28 13:24:26 +00:00
|
|
|
|
declare_clippy_lint! {
|
2016-02-05 23:13:29 +00:00
|
|
|
|
pub FOR_LOOP_OVER_RESULT,
|
2018-03-29 11:41:53 +00:00
|
|
|
|
correctness,
|
2016-02-05 23:13:29 +00:00
|
|
|
|
"for-looping over a `Result`, which is more clearly expressed as an `if let`"
|
|
|
|
|
}
|
2016-01-29 07:34:09 +00:00
|
|
|
|
|
2016-08-06 07:55:04 +00:00
|
|
|
|
/// **What it does:** Detects `loop + match` combinations that are easier
|
|
|
|
|
/// written as a `while let` loop.
|
2015-12-11 00:22:27 +00:00
|
|
|
|
///
|
2017-08-09 07:30:56 +00:00
|
|
|
|
/// **Why is this bad?** The `while let` loop is usually shorter and more
|
|
|
|
|
/// readable.
|
2015-12-11 00:22:27 +00:00
|
|
|
|
///
|
2016-08-06 07:55:04 +00:00
|
|
|
|
/// **Known problems:** Sometimes the wrong binding is displayed (#383).
|
2015-12-11 00:22:27 +00:00
|
|
|
|
///
|
|
|
|
|
/// **Example:**
|
2016-07-15 22:25:44 +00:00
|
|
|
|
/// ```rust
|
2015-12-11 00:22:27 +00:00
|
|
|
|
/// loop {
|
|
|
|
|
/// let x = match y {
|
|
|
|
|
/// Some(x) => x,
|
|
|
|
|
/// None => break,
|
|
|
|
|
/// }
|
|
|
|
|
/// // .. do something with x
|
|
|
|
|
/// }
|
|
|
|
|
/// // is easier written as
|
|
|
|
|
/// while let Some(x) = y {
|
|
|
|
|
/// // .. do something with x
|
|
|
|
|
/// }
|
|
|
|
|
/// ```
|
2018-03-28 13:24:26 +00:00
|
|
|
|
declare_clippy_lint! {
|
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
|
|
|
|
|
2016-08-06 07:55:04 +00:00
|
|
|
|
/// **What it does:** Checks for using `collect()` on an iterator without using
|
|
|
|
|
/// the result.
|
2015-12-11 00:22:27 +00:00
|
|
|
|
///
|
2016-08-06 07:55:04 +00:00
|
|
|
|
/// **Why is this bad?** It is more idiomatic to use a `for` loop over the
|
|
|
|
|
/// iterator instead.
|
2015-12-11 00:22:27 +00:00
|
|
|
|
///
|
2016-08-06 07:55:04 +00:00
|
|
|
|
/// **Known problems:** None.
|
2015-12-11 00:22:27 +00:00
|
|
|
|
///
|
2016-07-15 22:25:44 +00:00
|
|
|
|
/// **Example:**
|
|
|
|
|
/// ```rust
|
|
|
|
|
/// vec.iter().map(|x| /* some operation returning () */).collect::<Vec<_>>();
|
|
|
|
|
/// ```
|
2018-03-28 13:24:26 +00:00
|
|
|
|
declare_clippy_lint! {
|
2016-02-05 23:13:29 +00:00
|
|
|
|
pub UNUSED_COLLECT,
|
2018-03-29 11:41:53 +00:00
|
|
|
|
perf,
|
2016-02-05 23:13:29 +00:00
|
|
|
|
"`collect()`ing an iterator without using the result; this is usually better \
|
|
|
|
|
written as a for loop"
|
|
|
|
|
}
|
2015-08-30 11:10:59 +00:00
|
|
|
|
|
2016-08-06 07:55:04 +00:00
|
|
|
|
/// **What it does:** Checks for loops over ranges `x..y` where both `x` and `y`
|
|
|
|
|
/// are constant and `x` is greater or equal to `y`, unless the range is
|
|
|
|
|
/// reversed or has a negative `.step_by(_)`.
|
2015-12-11 00:22:27 +00:00
|
|
|
|
///
|
2016-08-06 07:55:04 +00:00
|
|
|
|
/// **Why is it bad?** Such loops will either be skipped or loop until
|
|
|
|
|
/// wrap-around (in debug code, this may `panic!()`). Both options are probably
|
|
|
|
|
/// not intended.
|
2015-12-11 00:22:27 +00:00
|
|
|
|
///
|
2016-08-06 07:55:04 +00:00
|
|
|
|
/// **Known problems:** The lint cannot catch loops over dynamically defined
|
|
|
|
|
/// ranges. Doing this would require simulating all possible inputs and code
|
|
|
|
|
/// paths through the program, which would be complex and error-prone.
|
2015-12-11 00:22:27 +00:00
|
|
|
|
///
|
2016-08-06 07:55:04 +00:00
|
|
|
|
/// **Example:**
|
2016-07-15 22:25:44 +00:00
|
|
|
|
/// ```rust
|
|
|
|
|
/// for x in 5..10-5 { .. } // oops, stray `-`
|
|
|
|
|
/// ```
|
2018-03-28 13:24:26 +00:00
|
|
|
|
declare_clippy_lint! {
|
2016-02-05 23:13:29 +00:00
|
|
|
|
pub REVERSE_RANGE_LOOP,
|
2018-03-28 13:24:26 +00:00
|
|
|
|
correctness,
|
2016-08-06 08:18:36 +00:00
|
|
|
|
"iteration over an empty range, such as `10..0` or `5..5`"
|
2016-02-05 23:13:29 +00:00
|
|
|
|
}
|
2015-09-15 00:19:05 +00:00
|
|
|
|
|
2016-08-06 07:55:04 +00:00
|
|
|
|
/// **What it does:** Checks `for` loops over slices with an explicit counter
|
|
|
|
|
/// and suggests the use of `.enumerate()`.
|
2015-12-11 00:22:27 +00:00
|
|
|
|
///
|
2016-08-06 07:55:04 +00:00
|
|
|
|
/// **Why is it bad?** Not only is the version using `.enumerate()` more
|
|
|
|
|
/// readable, the compiler is able to remove bounds checks which can lead to
|
|
|
|
|
/// faster code in some instances.
|
2015-12-11 00:22:27 +00:00
|
|
|
|
///
|
|
|
|
|
/// **Known problems:** None.
|
|
|
|
|
///
|
2016-07-15 22:25:44 +00:00
|
|
|
|
/// **Example:**
|
|
|
|
|
/// ```rust
|
|
|
|
|
/// for i in 0..v.len() { foo(v[i]);
|
|
|
|
|
/// for i in 0..v.len() { bar(i, v[i]); }
|
|
|
|
|
/// ```
|
2018-03-28 13:24:26 +00:00
|
|
|
|
declare_clippy_lint! {
|
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
|
|
|
|
|
2016-08-06 07:55:04 +00:00
|
|
|
|
/// **What it does:** Checks for empty `loop` expressions.
|
2015-12-11 00:22:27 +00:00
|
|
|
|
///
|
2016-08-06 07:55:04 +00:00
|
|
|
|
/// **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.
|
2015-12-11 00:22:27 +00:00
|
|
|
|
///
|
2016-08-06 07:55:04 +00:00
|
|
|
|
/// **Known problems:** None.
|
2015-12-11 00:22:27 +00:00
|
|
|
|
///
|
2016-07-15 22:25:44 +00:00
|
|
|
|
/// **Example:**
|
|
|
|
|
/// ```rust
|
|
|
|
|
/// loop {}
|
|
|
|
|
/// ```
|
2018-03-28 13:24:26 +00:00
|
|
|
|
declare_clippy_lint! {
|
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
|
|
|
|
|
2016-08-06 07:55:04 +00:00
|
|
|
|
/// **What it does:** Checks for `while let` expressions on iterators.
|
2015-12-14 21:16:56 +00:00
|
|
|
|
///
|
2016-08-06 07:55:04 +00:00
|
|
|
|
/// **Why is this bad?** Readability. A simple `for` loop is shorter and conveys
|
|
|
|
|
/// the intent better.
|
2015-12-14 21:16:56 +00:00
|
|
|
|
///
|
2016-08-06 07:55:04 +00:00
|
|
|
|
/// **Known problems:** None.
|
2015-12-14 21:16:56 +00:00
|
|
|
|
///
|
2016-07-15 22:25:44 +00:00
|
|
|
|
/// **Example:**
|
|
|
|
|
/// ```rust
|
|
|
|
|
/// while let Some(val) = iter() { .. }
|
|
|
|
|
/// ```
|
2018-03-28 13:24:26 +00:00
|
|
|
|
declare_clippy_lint! {
|
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
|
|
|
|
|
2016-08-06 07:55:04 +00:00
|
|
|
|
/// **What it does:** Checks for iterating a map (`HashMap` or `BTreeMap`) and
|
|
|
|
|
/// ignoring either the keys or values.
|
2016-01-19 20:10:00 +00:00
|
|
|
|
///
|
2016-08-06 07:55:04 +00:00
|
|
|
|
/// **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.
|
2016-01-19 20:10:00 +00:00
|
|
|
|
///
|
2016-08-06 07:55:04 +00:00
|
|
|
|
/// **Known problems:** None.
|
2016-01-19 20:10:00 +00:00
|
|
|
|
///
|
|
|
|
|
/// **Example:**
|
|
|
|
|
/// ```rust
|
|
|
|
|
/// for (k, _) in &map { .. }
|
|
|
|
|
/// ```
|
2016-07-15 22:25:44 +00:00
|
|
|
|
///
|
2016-01-19 20:10:00 +00:00
|
|
|
|
/// could be replaced by
|
2016-07-15 22:25:44 +00:00
|
|
|
|
///
|
2016-01-19 20:10:00 +00:00
|
|
|
|
/// ```rust
|
|
|
|
|
/// for k in map.keys() { .. }
|
|
|
|
|
/// ```
|
2018-03-28 13:24:26 +00:00
|
|
|
|
declare_clippy_lint! {
|
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
|
|
|
|
|
2017-05-31 01:44:01 +00:00
|
|
|
|
/// **What it does:** Checks for loops that will always `break`, `return` or
|
|
|
|
|
/// `continue` an outer loop.
|
2017-02-17 03:53:14 +00:00
|
|
|
|
///
|
|
|
|
|
/// **Why is this bad?** This loop never loops, all it does is obfuscating the
|
|
|
|
|
/// code.
|
|
|
|
|
///
|
2017-05-31 01:44:01 +00:00
|
|
|
|
/// **Known problems:** None
|
2017-02-17 03:53:14 +00:00
|
|
|
|
///
|
|
|
|
|
/// **Example:**
|
|
|
|
|
/// ```rust
|
|
|
|
|
/// loop { ..; break; }
|
|
|
|
|
/// ```
|
2018-03-28 13:24:26 +00:00
|
|
|
|
declare_clippy_lint! {
|
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
|
|
|
|
/// **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
|
|
|
|
|
/// }
|
|
|
|
|
/// ```
|
|
|
|
|
declare_clippy_lint! {
|
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-02-25 17:25:31 +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.
|
|
|
|
|
///
|
2018-03-26 10:32:21 +00:00
|
|
|
|
/// **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.
|
2018-02-25 17:25:31 +00:00
|
|
|
|
///
|
|
|
|
|
/// **Example:**
|
|
|
|
|
/// ```rust
|
|
|
|
|
/// let i = 0;
|
|
|
|
|
/// while i > 10 {
|
|
|
|
|
/// println!("let me loop forever!");
|
|
|
|
|
/// }
|
|
|
|
|
/// ```
|
2018-03-28 13:24:26 +00:00
|
|
|
|
declare_clippy_lint! {
|
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"
|
|
|
|
|
}
|
|
|
|
|
|
2017-07-31 22:58:26 +00:00
|
|
|
|
#[derive(Copy, Clone)]
|
|
|
|
|
pub struct Pass;
|
2015-08-12 19:56:27 +00:00
|
|
|
|
|
2016-06-10 14:17:20 +00:00
|
|
|
|
impl LintPass for Pass {
|
2015-08-12 19:56:27 +00:00
|
|
|
|
fn get_lints(&self) -> LintArray {
|
2017-08-09 07:30:56 +00:00
|
|
|
|
lint_array!(
|
2017-09-05 00:16:34 +00:00
|
|
|
|
MANUAL_MEMCPY,
|
2017-08-09 07:30:56 +00:00
|
|
|
|
NEEDLESS_RANGE_LOOP,
|
|
|
|
|
EXPLICIT_ITER_LOOP,
|
|
|
|
|
EXPLICIT_INTO_ITER_LOOP,
|
|
|
|
|
ITER_NEXT_LOOP,
|
|
|
|
|
FOR_LOOP_OVER_RESULT,
|
|
|
|
|
FOR_LOOP_OVER_OPTION,
|
|
|
|
|
WHILE_LET_LOOP,
|
|
|
|
|
UNUSED_COLLECT,
|
|
|
|
|
REVERSE_RANGE_LOOP,
|
|
|
|
|
EXPLICIT_COUNTER_LOOP,
|
|
|
|
|
EMPTY_LOOP,
|
|
|
|
|
WHILE_LET_ON_ITERATOR,
|
|
|
|
|
FOR_KV_MAP,
|
2017-10-25 19:41:31 +00:00
|
|
|
|
NEVER_LOOP,
|
2018-02-25 17:25:31 +00:00
|
|
|
|
MUT_RANGE_BOUND,
|
|
|
|
|
WHILE_IMMUTABLE_CONDITION,
|
2017-08-09 07:30:56 +00:00
|
|
|
|
)
|
2015-08-12 19:56:27 +00:00
|
|
|
|
}
|
2015-09-19 02:53:04 +00:00
|
|
|
|
}
|
2015-08-12 19:56:27 +00:00
|
|
|
|
|
2016-12-07 12:13:40 +00:00
|
|
|
|
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
|
|
|
|
|
fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
|
2016-06-29 22:08:43 +00:00
|
|
|
|
if let Some((pat, arg, body)) = higher::for_loop(expr) {
|
2015-11-18 11:35:18 +00:00
|
|
|
|
check_for_loop(cx, pat, arg, body, expr);
|
2015-08-12 19:56:27 +00:00
|
|
|
|
}
|
2017-06-01 04:22:15 +00:00
|
|
|
|
|
|
|
|
|
// check for never_loop
|
|
|
|
|
match expr.node {
|
2017-11-04 19:55:56 +00:00
|
|
|
|
ExprWhile(_, ref block, _) | ExprLoop(ref block, _, _) => {
|
2017-11-05 14:43:28 +00:00
|
|
|
|
match never_loop_block(block, &expr.id) {
|
|
|
|
|
NeverLoopResult::AlwaysBreak =>
|
|
|
|
|
span_lint(cx, NEVER_LOOP, expr.span, "this loop never actually loops"),
|
|
|
|
|
NeverLoopResult::MayContinueMainLoop | NeverLoopResult::Otherwise => (),
|
2017-09-16 22:45:28 +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)
|
2016-11-25 18:24:55 +00:00
|
|
|
|
if let ExprLoop(ref block, _, LoopSource::Loop) = expr.node {
|
2015-10-12 11:38:18 +00:00
|
|
|
|
// also check for empty `loop {}` statements
|
|
|
|
|
if block.stmts.is_empty() && block.expr.is_none() {
|
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)) {
|
2015-08-29 09:41:06 +00:00
|
|
|
|
if let ExprMatch(ref matchexpr, ref arms, ref source) = inner.node {
|
|
|
|
|
// ensure "if let" compatible match structure
|
|
|
|
|
match *source {
|
2017-11-04 19:55:56 +00:00
|
|
|
|
MatchSource::Normal | MatchSource::IfLetDesugar { .. } => {
|
|
|
|
|
if arms.len() == 2 && arms[0].pats.len() == 1 && arms[0].guard.is_none()
|
|
|
|
|
&& arms[1].pats.len() == 1 && arms[1].guard.is_none()
|
|
|
|
|
&& is_simple_break_expr(&arms[1].body)
|
2017-08-09 07:30:56 +00:00
|
|
|
|
{
|
2016-01-04 04:26:12 +00:00
|
|
|
|
if in_external_macro(cx, expr.span) {
|
|
|
|
|
return;
|
|
|
|
|
}
|
2016-02-27 21:59:15 +00:00
|
|
|
|
|
|
|
|
|
// NOTE: we used to make build a body here instead of using
|
|
|
|
|
// 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).
|
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 {} = {} {{ .. }}",
|
|
|
|
|
snippet(cx, arms[0].pats[0].span, ".."),
|
|
|
|
|
snippet(cx, matchexpr.span, "..")
|
|
|
|
|
),
|
|
|
|
|
);
|
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
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
2015-10-22 21:16:58 +00:00
|
|
|
|
if let ExprMatch(ref match_expr, ref arms, MatchSource::WhileLetDesugar) = expr.node {
|
2015-10-16 18:27:13 +00:00
|
|
|
|
let pat = &arms[0].pats[0].node;
|
2017-11-04 19:55:56 +00:00
|
|
|
|
if let (
|
|
|
|
|
&PatKind::TupleStruct(ref qpath, ref pat_args, _),
|
|
|
|
|
&ExprMethodCall(ref method_path, _, ref method_args),
|
|
|
|
|
) = (pat, &match_expr.node)
|
2017-08-09 07:30:56 +00:00
|
|
|
|
{
|
2015-10-26 22:49:37 +00:00
|
|
|
|
let iter_expr = &method_args[0];
|
2016-12-02 16:38:31 +00:00
|
|
|
|
let lhs_constructor = last_path_segment(qpath);
|
2017-11-04 19:55:56 +00:00
|
|
|
|
if method_path.name == "next" && match_trait_method(cx, match_expr, &paths::ITERATOR)
|
|
|
|
|
&& lhs_constructor.name == "Some" && !is_refutable(cx, &pat_args[0])
|
|
|
|
|
&& !is_iterator_used_after_while_let(cx, iter_expr)
|
|
|
|
|
&& !is_nested(cx, expr, &method_args[0])
|
2017-08-09 07:30:56 +00:00
|
|
|
|
{
|
2016-12-02 16:38:31 +00:00
|
|
|
|
let iterator = snippet(cx, method_args[0].span, "_");
|
|
|
|
|
let loop_var = snippet(cx, pat_args[0].span, "_");
|
2017-08-09 07:30:56 +00:00
|
|
|
|
span_lint_and_sugg(
|
|
|
|
|
cx,
|
|
|
|
|
WHILE_LET_ON_ITERATOR,
|
|
|
|
|
expr.span,
|
|
|
|
|
"this loop could be written as a `for` loop",
|
|
|
|
|
"try",
|
|
|
|
|
format!("for {} in {} {{ .. }}", loop_var, iterator),
|
|
|
|
|
);
|
2015-10-16 18:27:13 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
2018-02-25 17:25:31 +00:00
|
|
|
|
|
|
|
|
|
// check for while loops which conditions never change
|
|
|
|
|
if let ExprWhile(ref cond, ref block, _) = expr.node {
|
|
|
|
|
check_infinite_loop(cx, cond, block, expr);
|
|
|
|
|
}
|
2015-08-12 19:56:27 +00:00
|
|
|
|
}
|
2015-08-30 11:10:59 +00:00
|
|
|
|
|
2016-12-07 12:13:40 +00:00
|
|
|
|
fn check_stmt(&mut self, cx: &LateContext<'a, 'tcx>, stmt: &'tcx Stmt) {
|
2015-08-30 11:10:59 +00:00
|
|
|
|
if let StmtSemi(ref expr, _) = stmt.node {
|
|
|
|
|
if let ExprMethodCall(ref method, _, ref args) = expr.node {
|
2017-07-10 08:17:40 +00:00
|
|
|
|
if args.len() == 1 && method.name == "collect" && match_trait_method(cx, expr, &paths::ITERATOR) {
|
2017-08-09 07:30:56 +00:00
|
|
|
|
span_lint(
|
|
|
|
|
cx,
|
|
|
|
|
UNUSED_COLLECT,
|
|
|
|
|
expr.span,
|
|
|
|
|
"you are collect()ing an iterator and throwing away the result. \
|
2017-09-05 09:33:04 +00:00
|
|
|
|
Consider using an explicit for loop to exhaust the iterator",
|
2017-08-09 07:30:56 +00:00
|
|
|
|
);
|
2015-08-30 11:10:59 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
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,
|
|
|
|
|
}
|
|
|
|
|
|
2017-11-05 15:17:28 +00:00
|
|
|
|
fn absorb_break(arg: &NeverLoopResult) -> NeverLoopResult {
|
|
|
|
|
match *arg {
|
2017-11-05 14:43:28 +00:00
|
|
|
|
NeverLoopResult::AlwaysBreak |
|
|
|
|
|
NeverLoopResult::Otherwise => NeverLoopResult::Otherwise,
|
|
|
|
|
NeverLoopResult::MayContinueMainLoop => NeverLoopResult::MayContinueMainLoop,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Combine two results for parts that are called in order.
|
|
|
|
|
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.
|
|
|
|
|
fn combine_both(left: NeverLoopResult, right: NeverLoopResult) -> NeverLoopResult {
|
|
|
|
|
match (left, right) {
|
|
|
|
|
(NeverLoopResult::MayContinueMainLoop, _) | (_, NeverLoopResult::MayContinueMainLoop) =>
|
|
|
|
|
NeverLoopResult::MayContinueMainLoop,
|
|
|
|
|
(NeverLoopResult::AlwaysBreak, _) | (_, NeverLoopResult::AlwaysBreak) =>
|
|
|
|
|
NeverLoopResult::AlwaysBreak,
|
|
|
|
|
(NeverLoopResult::Otherwise, NeverLoopResult::Otherwise) =>
|
|
|
|
|
NeverLoopResult::Otherwise,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Combine two results where only one of the part may have been executed.
|
|
|
|
|
fn combine_branches(b1: NeverLoopResult, b2: NeverLoopResult) -> NeverLoopResult {
|
|
|
|
|
match (b1, b2) {
|
|
|
|
|
(NeverLoopResult::AlwaysBreak, NeverLoopResult::AlwaysBreak) =>
|
|
|
|
|
NeverLoopResult::AlwaysBreak,
|
|
|
|
|
(NeverLoopResult::MayContinueMainLoop, _) | (_, NeverLoopResult::MayContinueMainLoop) =>
|
|
|
|
|
NeverLoopResult::MayContinueMainLoop,
|
|
|
|
|
(NeverLoopResult::Otherwise, _) | (_, NeverLoopResult::Otherwise) =>
|
|
|
|
|
NeverLoopResult::Otherwise,
|
|
|
|
|
}
|
2017-05-31 01:44:01 +00:00
|
|
|
|
}
|
|
|
|
|
|
2017-11-05 14:43:28 +00:00
|
|
|
|
fn never_loop_block(block: &Block, main_loop_id: &NodeId) -> NeverLoopResult {
|
2017-10-08 22:26:39 +00:00
|
|
|
|
let stmts = block.stmts.iter().map(stmt_to_expr);
|
|
|
|
|
let expr = once(block.expr.as_ref().map(|p| &**p));
|
|
|
|
|
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
|
|
|
|
}
|
|
|
|
|
|
2017-10-08 22:26:39 +00:00
|
|
|
|
fn stmt_to_expr(stmt: &Stmt) -> Option<&Expr> {
|
2017-02-17 03:53:14 +00:00
|
|
|
|
match stmt.node {
|
2017-11-04 19:55:56 +00:00
|
|
|
|
StmtSemi(ref e, ..) | StmtExpr(ref e, ..) => Some(e),
|
2017-10-08 22:26:39 +00:00
|
|
|
|
StmtDecl(ref d, ..) => decl_to_expr(d),
|
2017-02-17 03:53:14 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2017-10-08 22:26:39 +00:00
|
|
|
|
fn decl_to_expr(decl: &Decl) -> Option<&Expr> {
|
2017-05-31 01:44:01 +00:00
|
|
|
|
match decl.node {
|
2017-10-08 22:26:39 +00:00
|
|
|
|
DeclLocal(ref local) => local.init.as_ref().map(|p| &**p),
|
|
|
|
|
_ => None,
|
2017-02-17 03:53:14 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2017-11-05 14:43:28 +00:00
|
|
|
|
fn never_loop_expr(expr: &Expr, main_loop_id: &NodeId) -> NeverLoopResult {
|
2017-02-17 03:53:14 +00:00
|
|
|
|
match expr.node {
|
|
|
|
|
ExprBox(ref e) |
|
|
|
|
|
ExprUnary(_, ref e) |
|
|
|
|
|
ExprCast(ref e, _) |
|
|
|
|
|
ExprType(ref e, _) |
|
|
|
|
|
ExprField(ref e, _) |
|
2017-05-31 01:44:01 +00:00
|
|
|
|
ExprAddrOf(_, ref e) |
|
2017-11-05 14:43:28 +00:00
|
|
|
|
ExprStruct(_, _, Some(ref e)) |
|
|
|
|
|
ExprRepeat(ref e, _) => never_loop_expr(e, main_loop_id),
|
2017-11-04 19:55:56 +00:00
|
|
|
|
ExprArray(ref es) | ExprMethodCall(_, _, ref es) | ExprTup(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
|
|
|
|
},
|
2017-11-05 14:43:28 +00:00
|
|
|
|
ExprCall(ref e, ref es) => never_loop_expr_all(&mut once(&**e).chain(es.iter()), main_loop_id),
|
2017-05-31 01:44:01 +00:00
|
|
|
|
ExprBinary(_, ref e1, ref e2) |
|
2017-02-17 03:53:14 +00:00
|
|
|
|
ExprAssign(ref e1, ref e2) |
|
|
|
|
|
ExprAssignOp(_, ref e1, ref e2) |
|
2017-11-05 14:43:28 +00:00
|
|
|
|
ExprIndex(ref e1, ref e2) => never_loop_expr_all(&mut [&**e1, &**e2].iter().cloned(), main_loop_id),
|
2017-09-16 22:45:28 +00:00
|
|
|
|
ExprIf(ref e, ref e2, ref e3) => {
|
2017-11-05 14:43:28 +00:00
|
|
|
|
let e1 = never_loop_expr(e, main_loop_id);
|
|
|
|
|
let e2 = never_loop_expr(e2, main_loop_id);
|
2017-11-05 15:45:23 +00:00
|
|
|
|
let e3 = e3.as_ref().map_or(NeverLoopResult::Otherwise, |e| never_loop_expr(e, main_loop_id));
|
2017-11-05 14:43:28 +00:00
|
|
|
|
combine_seq(e1, combine_branches(e2, e3))
|
2017-10-08 22:26:39 +00:00
|
|
|
|
},
|
2017-10-06 05:04:39 +00:00
|
|
|
|
ExprLoop(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
|
|
|
|
},
|
|
|
|
|
ExprWhile(ref e, ref b, _) => {
|
2017-11-05 14:43:28 +00:00
|
|
|
|
let e = never_loop_expr(e, main_loop_id);
|
|
|
|
|
let result = never_loop_block(b, main_loop_id);
|
|
|
|
|
// Break can come from the inner loop so remove them.
|
2017-11-05 15:17:28 +00:00
|
|
|
|
combine_seq(e, absorb_break(&result))
|
2017-09-16 22:45:28 +00:00
|
|
|
|
},
|
2017-06-29 14:07:43 +00:00
|
|
|
|
ExprMatch(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
|
|
|
|
},
|
2017-11-05 14:43:28 +00:00
|
|
|
|
ExprBlock(ref b) => never_loop_block(b, main_loop_id),
|
2017-10-08 22:26:39 +00:00
|
|
|
|
ExprAgain(d) => {
|
2017-11-04 19:55:56 +00:00
|
|
|
|
let id = d.target_id
|
|
|
|
|
.opt_id()
|
|
|
|
|
.expect("target id can only be missing in the presence of compilation errors");
|
2017-11-05 14:43:28 +00:00
|
|
|
|
if id == *main_loop_id {
|
|
|
|
|
NeverLoopResult::MayContinueMainLoop
|
|
|
|
|
} else {
|
|
|
|
|
NeverLoopResult::AlwaysBreak
|
|
|
|
|
}
|
2017-09-16 22:45:28 +00:00
|
|
|
|
},
|
2017-11-05 14:43:28 +00:00
|
|
|
|
ExprBreak(_, _) => {
|
|
|
|
|
NeverLoopResult::AlwaysBreak
|
2017-10-08 22:26:39 +00:00
|
|
|
|
},
|
|
|
|
|
ExprRet(ref e) => {
|
|
|
|
|
if let Some(ref e) = *e {
|
2017-11-05 14:43:28 +00:00
|
|
|
|
combine_seq(never_loop_expr(e, main_loop_id), NeverLoopResult::AlwaysBreak)
|
|
|
|
|
} else {
|
|
|
|
|
NeverLoopResult::AlwaysBreak
|
2017-10-08 22:26:39 +00:00
|
|
|
|
}
|
|
|
|
|
},
|
2017-11-05 14:43:28 +00:00
|
|
|
|
ExprStruct(_, _, None) |
|
|
|
|
|
ExprYield(_) |
|
|
|
|
|
ExprClosure(_, _, _, _, _) |
|
|
|
|
|
ExprInlineAsm(_, _, _) |
|
|
|
|
|
ExprPath(_) |
|
|
|
|
|
ExprLit(_) => NeverLoopResult::Otherwise,
|
2017-05-31 01:44:01 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2017-11-05 14:43:28 +00:00
|
|
|
|
fn never_loop_expr_seq<'a, T: Iterator<Item=&'a Expr>>(es: &mut T, main_loop_id: &NodeId) -> 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
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn never_loop_expr_all<'a, T: Iterator<Item=&'a Expr>>(es: &mut T, main_loop_id: &NodeId) -> 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
|
|
|
|
}
|
|
|
|
|
|
2017-11-05 14:43:28 +00:00
|
|
|
|
fn never_loop_expr_branch<'a, T: Iterator<Item=&'a Expr>>(e: &mut T, main_loop_id: &NodeId) -> 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
|
|
|
|
}
|
|
|
|
|
|
2016-12-21 11:14:54 +00:00
|
|
|
|
fn check_for_loop<'a, 'tcx>(
|
|
|
|
|
cx: &LateContext<'a, 'tcx>,
|
|
|
|
|
pat: &'tcx Pat,
|
|
|
|
|
arg: &'tcx Expr,
|
|
|
|
|
body: &'tcx Expr,
|
2017-08-09 07:30:56 +00:00
|
|
|
|
expr: &'tcx Expr,
|
2016-12-21 11:14:54 +00:00
|
|
|
|
) {
|
2016-01-14 19:58:32 +00:00
|
|
|
|
check_for_loop_range(cx, pat, arg, body, expr);
|
|
|
|
|
check_for_loop_reverse_range(cx, arg, expr);
|
2016-01-29 07:34:09 +00:00
|
|
|
|
check_for_loop_arg(cx, pat, arg, expr);
|
2016-01-14 19:58:32 +00:00
|
|
|
|
check_for_loop_explicit_counter(cx, arg, body, 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);
|
2017-09-05 00:16:34 +00:00
|
|
|
|
detect_manual_memcpy(cx, pat, arg, body, expr);
|
|
|
|
|
}
|
|
|
|
|
|
2017-09-12 12:26:40 +00:00
|
|
|
|
fn same_var<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &Expr, var: ast::NodeId) -> bool {
|
2017-10-23 19:18:02 +00:00
|
|
|
|
if_chain! {
|
|
|
|
|
if let ExprPath(ref qpath) = expr.node;
|
|
|
|
|
if let QPath::Resolved(None, ref path) = *qpath;
|
|
|
|
|
if path.segments.len() == 1;
|
|
|
|
|
if let Def::Local(local_id) = cx.tables.qpath_def(qpath, expr.hir_id);
|
2017-09-05 00:16:34 +00:00
|
|
|
|
// our variable!
|
2017-10-23 19:18:02 +00:00
|
|
|
|
if local_id == var;
|
|
|
|
|
then {
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
}
|
2017-09-05 00:16:34 +00:00
|
|
|
|
|
|
|
|
|
false
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
struct Offset {
|
|
|
|
|
value: String,
|
|
|
|
|
negate: bool,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl Offset {
|
|
|
|
|
fn negative(s: String) -> Self {
|
|
|
|
|
Self {
|
|
|
|
|
value: s,
|
|
|
|
|
negate: true,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn positive(s: String) -> Self {
|
|
|
|
|
Self {
|
|
|
|
|
value: s,
|
|
|
|
|
negate: false,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
struct FixedOffsetVar {
|
|
|
|
|
var_name: String,
|
|
|
|
|
offset: Offset,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn is_slice_like<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty) -> bool {
|
|
|
|
|
let is_slice = match ty.sty {
|
2018-05-11 06:37:48 +00:00
|
|
|
|
ty::TyRef(_, subty, _) => is_slice_like(cx, subty),
|
2017-09-05 00:16:34 +00:00
|
|
|
|
ty::TySlice(..) | ty::TyArray(..) => true,
|
|
|
|
|
_ => false,
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
is_slice || match_type(cx, ty, &paths::VEC) || match_type(cx, ty, &paths::VEC_DEQUE)
|
|
|
|
|
}
|
|
|
|
|
|
2017-09-12 12:26:40 +00:00
|
|
|
|
fn get_fixed_offset_var<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &Expr, var: ast::NodeId) -> Option<FixedOffsetVar> {
|
|
|
|
|
fn extract_offset<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, e: &Expr, var: ast::NodeId) -> Option<String> {
|
2017-09-05 00:16:34 +00:00
|
|
|
|
match e.node {
|
2017-11-04 19:55:56 +00:00
|
|
|
|
ExprLit(ref l) => match l.node {
|
|
|
|
|
ast::LitKind::Int(x, _ty) => Some(x.to_string()),
|
|
|
|
|
_ => None,
|
2017-09-05 00:16:34 +00:00
|
|
|
|
},
|
|
|
|
|
ExprPath(..) if !same_var(cx, e, var) => Some(snippet_opt(cx, e.span).unwrap_or_else(|| "??".into())),
|
|
|
|
|
_ => None,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if let ExprIndex(ref seqexpr, ref idx) = expr.node {
|
|
|
|
|
let ty = cx.tables.expr_ty(seqexpr);
|
|
|
|
|
if !is_slice_like(cx, ty) {
|
|
|
|
|
return None;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
let offset = match idx.node {
|
2017-11-04 19:55:56 +00:00
|
|
|
|
ExprBinary(op, ref lhs, ref rhs) => match op.node {
|
|
|
|
|
BinOp_::BiAdd => {
|
|
|
|
|
let offset_opt = if same_var(cx, lhs, var) {
|
|
|
|
|
extract_offset(cx, rhs, var)
|
|
|
|
|
} else if same_var(cx, rhs, var) {
|
|
|
|
|
extract_offset(cx, lhs, var)
|
|
|
|
|
} else {
|
|
|
|
|
None
|
|
|
|
|
};
|
2017-09-05 00:16:34 +00:00
|
|
|
|
|
2017-11-04 19:55:56 +00:00
|
|
|
|
offset_opt.map(Offset::positive)
|
|
|
|
|
},
|
|
|
|
|
BinOp_::BiSub if same_var(cx, lhs, var) => extract_offset(cx, rhs, var).map(Offset::negative),
|
|
|
|
|
_ => None,
|
2017-09-05 00:16:34 +00:00
|
|
|
|
},
|
2017-11-04 19:55:56 +00:00
|
|
|
|
ExprPath(..) => if same_var(cx, idx, var) {
|
|
|
|
|
Some(Offset::positive("0".into()))
|
|
|
|
|
} else {
|
|
|
|
|
None
|
2017-09-05 00:16:34 +00:00
|
|
|
|
},
|
|
|
|
|
_ => None,
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
offset.map(|o| {
|
|
|
|
|
FixedOffsetVar {
|
|
|
|
|
var_name: snippet_opt(cx, seqexpr.span).unwrap_or_else(|| "???".into()),
|
|
|
|
|
offset: o,
|
|
|
|
|
}
|
|
|
|
|
})
|
|
|
|
|
} else {
|
|
|
|
|
None
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2017-09-16 23:17:22 +00:00
|
|
|
|
fn fetch_cloned_fixed_offset_var<'a, 'tcx>(
|
|
|
|
|
cx: &LateContext<'a, 'tcx>,
|
|
|
|
|
expr: &Expr,
|
|
|
|
|
var: ast::NodeId,
|
|
|
|
|
) -> Option<FixedOffsetVar> {
|
2017-10-23 19:18:02 +00:00
|
|
|
|
if_chain! {
|
|
|
|
|
if let ExprMethodCall(ref method, _, ref args) = expr.node;
|
|
|
|
|
if method.name == "clone";
|
|
|
|
|
if args.len() == 1;
|
|
|
|
|
if let Some(arg) = args.get(0);
|
|
|
|
|
then {
|
|
|
|
|
return get_fixed_offset_var(cx, arg, var);
|
|
|
|
|
}
|
|
|
|
|
}
|
2017-09-16 23:17:22 +00:00
|
|
|
|
|
|
|
|
|
get_fixed_offset_var(cx, expr, var)
|
|
|
|
|
}
|
|
|
|
|
|
2017-09-05 00:16:34 +00:00
|
|
|
|
fn get_indexed_assignments<'a, 'tcx>(
|
|
|
|
|
cx: &LateContext<'a, 'tcx>,
|
|
|
|
|
body: &Expr,
|
2017-09-12 12:26:40 +00:00
|
|
|
|
var: ast::NodeId,
|
2017-09-05 00:16:34 +00:00
|
|
|
|
) -> Vec<(FixedOffsetVar, FixedOffsetVar)> {
|
|
|
|
|
fn get_assignment<'a, 'tcx>(
|
|
|
|
|
cx: &LateContext<'a, 'tcx>,
|
|
|
|
|
e: &Expr,
|
2017-09-12 12:26:40 +00:00
|
|
|
|
var: ast::NodeId,
|
2017-09-05 00:16:34 +00:00
|
|
|
|
) -> Option<(FixedOffsetVar, FixedOffsetVar)> {
|
|
|
|
|
if let Expr_::ExprAssign(ref lhs, ref rhs) = e.node {
|
2017-09-16 23:17:22 +00:00
|
|
|
|
match (get_fixed_offset_var(cx, lhs, var), fetch_cloned_fixed_offset_var(cx, rhs, var)) {
|
2017-10-17 20:04:35 +00:00
|
|
|
|
(Some(offset_left), Some(offset_right)) => {
|
|
|
|
|
// Source and destination must be different
|
2017-10-20 14:13:50 +00:00
|
|
|
|
if offset_left.var_name == offset_right.var_name {
|
2017-10-17 20:04:35 +00:00
|
|
|
|
None
|
2017-10-20 14:13:50 +00:00
|
|
|
|
} else {
|
|
|
|
|
Some((offset_left, offset_right))
|
2017-10-17 20:04:35 +00:00
|
|
|
|
}
|
|
|
|
|
},
|
2017-09-05 00:16:34 +00:00
|
|
|
|
_ => None,
|
|
|
|
|
}
|
|
|
|
|
} else {
|
|
|
|
|
None
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if let Expr_::ExprBlock(ref b) = body.node {
|
|
|
|
|
let Block {
|
|
|
|
|
ref stmts,
|
|
|
|
|
ref expr,
|
|
|
|
|
..
|
|
|
|
|
} = **b;
|
|
|
|
|
|
|
|
|
|
stmts
|
|
|
|
|
.iter()
|
|
|
|
|
.map(|stmt| match stmt.node {
|
|
|
|
|
Stmt_::StmtDecl(..) => None,
|
2017-11-04 19:55:56 +00:00
|
|
|
|
Stmt_::StmtExpr(ref e, _node_id) | Stmt_::StmtSemi(ref e, _node_id) => Some(get_assignment(cx, e, var)),
|
2017-09-05 00:16:34 +00:00
|
|
|
|
})
|
2017-11-04 19:55:56 +00:00
|
|
|
|
.chain(
|
|
|
|
|
expr.as_ref()
|
|
|
|
|
.into_iter()
|
|
|
|
|
.map(|e| Some(get_assignment(cx, &*e, var))),
|
|
|
|
|
)
|
2017-09-05 00:16:34 +00:00
|
|
|
|
.filter_map(|op| op)
|
|
|
|
|
.collect::<Option<Vec<_>>>()
|
|
|
|
|
.unwrap_or_else(|| vec![])
|
|
|
|
|
} else {
|
|
|
|
|
get_assignment(cx, body, var).into_iter().collect()
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Check for for loops that sequentially copy items from one slice-like
|
|
|
|
|
/// object to another.
|
|
|
|
|
fn detect_manual_memcpy<'a, 'tcx>(
|
|
|
|
|
cx: &LateContext<'a, 'tcx>,
|
|
|
|
|
pat: &'tcx Pat,
|
|
|
|
|
arg: &'tcx Expr,
|
|
|
|
|
body: &'tcx Expr,
|
|
|
|
|
expr: &'tcx Expr,
|
|
|
|
|
) {
|
|
|
|
|
if let Some(higher::Range {
|
2017-11-04 19:55:56 +00:00
|
|
|
|
start: Some(start),
|
|
|
|
|
ref end,
|
|
|
|
|
limits,
|
2018-05-08 15:16:01 +00:00
|
|
|
|
}) = higher::range(cx, arg)
|
2017-09-05 00:16:34 +00:00
|
|
|
|
{
|
|
|
|
|
// the var must be a single name
|
2017-09-12 12:26:40 +00:00
|
|
|
|
if let PatKind::Binding(_, canonical_id, _, _) = pat.node {
|
2017-09-05 00:16:34 +00:00
|
|
|
|
let print_sum = |arg1: &Offset, arg2: &Offset| -> String {
|
|
|
|
|
match (&arg1.value[..], arg1.negate, &arg2.value[..], arg2.negate) {
|
|
|
|
|
("0", _, "0", _) => "".into(),
|
2017-11-04 19:55:56 +00:00
|
|
|
|
("0", _, x, false) | (x, false, "0", false) => x.into(),
|
|
|
|
|
("0", _, x, true) | (x, false, "0", true) => format!("-{}", x),
|
2017-09-05 00:16:34 +00:00
|
|
|
|
(x, false, y, false) => format!("({} + {})", x, y),
|
|
|
|
|
(x, false, y, true) => format!("({} - {})", x, y),
|
|
|
|
|
(x, true, y, false) => format!("({} - {})", y, x),
|
|
|
|
|
(x, true, y, true) => format!("-({} + {})", x, y),
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
let print_limit = |end: &Option<&Expr>, offset: Offset, var_name: &str| if let Some(end) = *end {
|
2017-10-23 19:18:02 +00:00
|
|
|
|
if_chain! {
|
|
|
|
|
if let ExprMethodCall(ref method, _, ref len_args) = end.node;
|
|
|
|
|
if method.name == "len";
|
|
|
|
|
if len_args.len() == 1;
|
|
|
|
|
if let Some(arg) = len_args.get(0);
|
|
|
|
|
if snippet(cx, arg.span, "??") == var_name;
|
|
|
|
|
then {
|
|
|
|
|
return if offset.negate {
|
|
|
|
|
format!("({} - {})", snippet(cx, end.span, "<src>.len()"), offset.value)
|
|
|
|
|
} else {
|
|
|
|
|
"".to_owned()
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
}
|
2017-09-05 00:16:34 +00:00
|
|
|
|
|
|
|
|
|
let end_str = match limits {
|
|
|
|
|
ast::RangeLimits::Closed => {
|
|
|
|
|
let end = sugg::Sugg::hir(cx, end, "<count>");
|
|
|
|
|
format!("{}", end + sugg::ONE)
|
|
|
|
|
},
|
|
|
|
|
ast::RangeLimits::HalfOpen => format!("{}", snippet(cx, end.span, "..")),
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
print_sum(&Offset::positive(end_str), &offset)
|
|
|
|
|
} else {
|
|
|
|
|
"..".into()
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
// The only statements in the for loops can be indexed assignments from
|
|
|
|
|
// indexed retrievals.
|
2017-09-12 12:26:40 +00:00
|
|
|
|
let manual_copies = get_indexed_assignments(cx, body, canonical_id);
|
2017-09-05 00:16:34 +00:00
|
|
|
|
|
|
|
|
|
let big_sugg = manual_copies
|
|
|
|
|
.into_iter()
|
|
|
|
|
.map(|(dst_var, src_var)| {
|
|
|
|
|
let start_str = Offset::positive(snippet_opt(cx, start.span).unwrap_or_else(|| "".into()));
|
|
|
|
|
let dst_offset = print_sum(&start_str, &dst_var.offset);
|
|
|
|
|
let dst_limit = print_limit(end, dst_var.offset, &dst_var.var_name);
|
|
|
|
|
let src_offset = print_sum(&start_str, &src_var.offset);
|
|
|
|
|
let src_limit = print_limit(end, src_var.offset, &src_var.var_name);
|
|
|
|
|
let dst = if dst_offset == "" && dst_limit == "" {
|
|
|
|
|
dst_var.var_name
|
|
|
|
|
} else {
|
|
|
|
|
format!("{}[{}..{}]", dst_var.var_name, dst_offset, dst_limit)
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
format!("{}.clone_from_slice(&{}[{}..{}])", dst, src_var.var_name, src_offset, src_limit)
|
|
|
|
|
})
|
|
|
|
|
.join("\n ");
|
|
|
|
|
|
|
|
|
|
if !big_sugg.is_empty() {
|
|
|
|
|
span_lint_and_sugg(
|
|
|
|
|
cx,
|
|
|
|
|
MANUAL_MEMCPY,
|
|
|
|
|
expr.span,
|
|
|
|
|
"it looks like you're manually copying between slices",
|
|
|
|
|
"try replacing the loop by",
|
|
|
|
|
big_sugg,
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
2016-01-14 19:58:32 +00:00
|
|
|
|
}
|
2015-11-18 11:35:18 +00:00
|
|
|
|
|
2016-01-14 19:58:32 +00:00
|
|
|
|
/// Check for looping over a range and then indexing a sequence with it.
|
|
|
|
|
/// The iteratee must be a range literal.
|
2016-12-21 11:14:54 +00:00
|
|
|
|
fn check_for_loop_range<'a, 'tcx>(
|
|
|
|
|
cx: &LateContext<'a, 'tcx>,
|
|
|
|
|
pat: &'tcx Pat,
|
|
|
|
|
arg: &'tcx Expr,
|
|
|
|
|
body: &'tcx Expr,
|
2017-08-09 07:30:56 +00:00
|
|
|
|
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,
|
2018-05-08 15:16:01 +00:00
|
|
|
|
}) = higher::range(cx, arg)
|
2017-08-09 07:30:56 +00:00
|
|
|
|
{
|
2016-01-14 19:58:32 +00:00
|
|
|
|
// the var must be a single name
|
2017-09-12 12:26:40 +00:00
|
|
|
|
if let PatKind::Binding(_, canonical_id, ref ident, _) = pat.node {
|
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,
|
2017-11-07 13:41:54 +00:00
|
|
|
|
indexed_mut: HashSet::new(),
|
2017-11-07 14:32:52 +00:00
|
|
|
|
indexed_indirectly: HashMap::new(),
|
2017-10-08 15:34:31 +00:00
|
|
|
|
indexed_directly: HashMap::new(),
|
2017-07-10 13:30:28 +00:00
|
|
|
|
referenced: HashSet::new(),
|
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 {
|
2017-11-04 19:55:56 +00:00
|
|
|
|
let (indexed, indexed_extent) = visitor
|
|
|
|
|
.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 {
|
2017-05-03 10:51:47 +00:00
|
|
|
|
let parent_id = cx.tcx.hir.get_parent(expr.id);
|
|
|
|
|
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
|
|
|
|
}
|
|
|
|
|
|
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;
|
|
|
|
|
}
|
|
|
|
|
|
2016-03-07 15:31:38 +00:00
|
|
|
|
let starts_at_zero = is_integer_literal(start, 0);
|
2016-01-14 19:58:32 +00:00
|
|
|
|
|
2016-07-01 17:31:14 +00:00
|
|
|
|
let skip = if starts_at_zero {
|
|
|
|
|
"".to_owned()
|
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
|
|
|
|
};
|
|
|
|
|
|
2016-08-01 14:59:14 +00:00
|
|
|
|
let take = if let Some(end) = *end {
|
2016-04-26 15:05:39 +00:00
|
|
|
|
if is_len_call(end, &indexed) {
|
2016-07-01 17:31:14 +00:00
|
|
|
|
"".to_owned()
|
2016-02-29 08:45:36 +00:00
|
|
|
|
} else {
|
2016-07-01 17:31:14 +00:00
|
|
|
|
match limits {
|
|
|
|
|
ast::RangeLimits::Closed => {
|
|
|
|
|
let end = sugg::Sugg::hir(cx, end, "<count>");
|
|
|
|
|
format!(".take({})", end + sugg::ONE)
|
2016-12-20 17:21:30 +00:00
|
|
|
|
},
|
|
|
|
|
ast::RangeLimits::HalfOpen => format!(".take({})", snippet(cx, end.span, "..")),
|
2016-07-01 17:31:14 +00:00
|
|
|
|
}
|
2016-01-14 19:58:32 +00:00
|
|
|
|
}
|
|
|
|
|
} else {
|
2016-07-01 17:31:14 +00:00
|
|
|
|
"".to_owned()
|
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")
|
|
|
|
|
};
|
|
|
|
|
|
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,
|
|
|
|
|
&format!("the loop variable `{}` is used to index `{}`", ident.node, indexed),
|
|
|
|
|
|db| {
|
|
|
|
|
multispan_sugg(
|
|
|
|
|
db,
|
|
|
|
|
"consider using an iterator".to_string(),
|
|
|
|
|
vec![
|
|
|
|
|
(pat.span, format!("({}, <item>)", ident.node)),
|
2017-11-07 13:41:54 +00:00
|
|
|
|
(arg.span, format!("{}.{}().enumerate(){}{}", indexed, method, take, skip)),
|
2017-09-05 09:33:04 +00:00
|
|
|
|
],
|
|
|
|
|
);
|
|
|
|
|
},
|
|
|
|
|
);
|
2016-01-14 19:58:32 +00:00
|
|
|
|
} else {
|
|
|
|
|
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 {
|
2017-11-07 13:41:54 +00:00
|
|
|
|
format!("{}.{}(){}{}", indexed, method, take, skip)
|
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,
|
|
|
|
|
&format!("the loop variable `{}` is only used to index `{}`.", ident.node, indexed),
|
|
|
|
|
|db| {
|
|
|
|
|
multispan_sugg(
|
|
|
|
|
db,
|
|
|
|
|
"consider using an iterator".to_string(),
|
|
|
|
|
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
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn is_len_call(expr: &Expr, var: &Name) -> bool {
|
2017-10-23 19:18:02 +00:00
|
|
|
|
if_chain! {
|
|
|
|
|
if let ExprMethodCall(ref method, _, ref len_args) = expr.node;
|
|
|
|
|
if len_args.len() == 1;
|
|
|
|
|
if method.name == "len";
|
|
|
|
|
if let ExprPath(QPath::Resolved(_, ref path)) = len_args[0].node;
|
|
|
|
|
if path.segments.len() == 1;
|
|
|
|
|
if path.segments[0].name == *var;
|
|
|
|
|
then {
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
}
|
2015-11-18 11:35:18 +00:00
|
|
|
|
|
2016-01-14 19:58:32 +00:00
|
|
|
|
false
|
|
|
|
|
}
|
|
|
|
|
|
2017-09-13 13:34:04 +00:00
|
|
|
|
fn check_for_loop_reverse_range<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, arg: &'tcx Expr, expr: &'tcx Expr) {
|
2015-11-18 11:35:18 +00:00
|
|
|
|
// if this for loop is iterating over a two-sided range...
|
2017-08-09 07:30:56 +00:00
|
|
|
|
if let Some(higher::Range {
|
2017-11-04 19:55:56 +00:00
|
|
|
|
start: Some(start),
|
|
|
|
|
end: Some(end),
|
|
|
|
|
limits,
|
2018-05-08 15:16:01 +00:00
|
|
|
|
}) = higher::range(cx, arg)
|
2017-08-09 07:30:56 +00:00
|
|
|
|
{
|
2015-11-18 11:35:18 +00:00
|
|
|
|
// ...and both sides are compile-time constant integers...
|
2018-03-13 10:38:11 +00:00
|
|
|
|
if let Some((start_idx, _)) = constant(cx, start) {
|
|
|
|
|
if let Some((end_idx, _)) = constant(cx, end) {
|
2016-03-07 15:31:38 +00:00
|
|
|
|
// ...and the start index is greater than the end index,
|
2015-11-18 11:35:18 +00:00
|
|
|
|
// this loop will never run. This is often confusing for developers
|
|
|
|
|
// who think that this will iterate from the larger value to the
|
|
|
|
|
// smaller value.
|
2018-03-13 10:38:11 +00:00
|
|
|
|
let ty = cx.tables.expr_ty(start);
|
2016-03-07 15:31:38 +00:00
|
|
|
|
let (sup, eq) = match (start_idx, end_idx) {
|
2017-11-04 19:55:56 +00:00
|
|
|
|
(
|
2018-03-13 10:38:11 +00:00
|
|
|
|
Constant::Int(start_idx),
|
|
|
|
|
Constant::Int(end_idx),
|
|
|
|
|
) => (match ty.sty {
|
|
|
|
|
ty::TyInt(ity) => sext(cx.tcx, start_idx, ity) > sext(cx.tcx, end_idx, ity),
|
|
|
|
|
ty::TyUint(_) => start_idx > end_idx,
|
|
|
|
|
_ => false,
|
|
|
|
|
}, start_idx == end_idx),
|
2016-02-07 17:10:03 +00:00
|
|
|
|
_ => (false, false),
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
if sup {
|
2016-03-07 15:31:38 +00:00
|
|
|
|
let start_snippet = snippet(cx, start.span, "_");
|
|
|
|
|
let end_snippet = snippet(cx, end.span, "_");
|
2016-06-09 21:05:48 +00:00
|
|
|
|
let dots = if limits == ast::RangeLimits::Closed {
|
|
|
|
|
"..."
|
|
|
|
|
} else {
|
|
|
|
|
".."
|
|
|
|
|
};
|
2016-02-07 17:10:03 +00:00
|
|
|
|
|
2017-09-05 09:33:04 +00:00
|
|
|
|
span_lint_and_then(
|
|
|
|
|
cx,
|
|
|
|
|
REVERSE_RANGE_LOOP,
|
|
|
|
|
expr.span,
|
|
|
|
|
"this range is empty so this for loop will never run",
|
|
|
|
|
|db| {
|
|
|
|
|
db.span_suggestion(
|
|
|
|
|
arg.span,
|
|
|
|
|
"consider using the following if you are attempting to iterate over this \
|
|
|
|
|
range in reverse",
|
|
|
|
|
format!(
|
|
|
|
|
"({end}{dots}{start}).rev()",
|
|
|
|
|
end = end_snippet,
|
|
|
|
|
dots = dots,
|
|
|
|
|
start = start_snippet
|
|
|
|
|
),
|
|
|
|
|
);
|
|
|
|
|
},
|
|
|
|
|
);
|
2016-03-07 15:55:12 +00:00
|
|
|
|
} else if eq && limits != ast::RangeLimits::Closed {
|
2015-11-18 11:35:18 +00:00
|
|
|
|
// if they are equal, it's also problematic - this loop
|
|
|
|
|
// will never run.
|
2017-08-09 07:30:56 +00:00
|
|
|
|
span_lint(
|
|
|
|
|
cx,
|
|
|
|
|
REVERSE_RANGE_LOOP,
|
|
|
|
|
expr.span,
|
|
|
|
|
"this range is empty so this for loop will never run",
|
|
|
|
|
);
|
2015-11-18 11:35:18 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
2016-01-14 19:58:32 +00:00
|
|
|
|
}
|
2015-11-18 11:35:18 +00:00
|
|
|
|
|
2017-01-30 11:43:27 +00:00
|
|
|
|
fn lint_iter_method(cx: &LateContext, args: &[Expr], arg: &Expr, method_name: &str) {
|
2017-01-09 15:59:55 +00:00
|
|
|
|
let object = snippet(cx, args[0].span, "_");
|
2017-01-30 11:43:27 +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,
|
|
|
|
|
"it is more idiomatic 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),
|
|
|
|
|
)
|
2017-01-09 15:59:55 +00:00
|
|
|
|
}
|
|
|
|
|
|
2016-01-29 07:34:09 +00:00
|
|
|
|
fn check_for_loop_arg(cx: &LateContext, pat: &Pat, arg: &Expr, expr: &Expr) {
|
|
|
|
|
let mut next_loop_linted = false; // whether or not ITER_NEXT_LOOP lint was used
|
2015-11-18 11:35:18 +00:00
|
|
|
|
if let ExprMethodCall(ref method, _, ref args) = arg.node {
|
|
|
|
|
// just the receiver, no arguments
|
|
|
|
|
if args.len() == 1 {
|
2017-07-10 08:17:40 +00:00
|
|
|
|
let method_name = &*method.name.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
|
|
|
|
}
|
|
|
|
|
} else if method_name == "into_iter" && match_trait_method(cx, arg, &paths::INTO_ITERATOR) {
|
2017-08-15 09:10:49 +00:00
|
|
|
|
let def_id = cx.tables.type_dependent_defs()[arg.hir_id].def_id();
|
|
|
|
|
let substs = cx.tables.node_substs(arg.hir_id);
|
2017-06-04 21:28:01 +00:00
|
|
|
|
let method_type = cx.tcx.type_of(def_id).subst(cx.tcx, substs);
|
|
|
|
|
|
2017-06-29 13:38:25 +00:00
|
|
|
|
let fn_arg_tys = method_type.fn_sig(cx.tcx).inputs();
|
2017-01-09 15:59:55 +00:00
|
|
|
|
assert_eq!(fn_arg_tys.skip_binder().len(), 1);
|
|
|
|
|
if fn_arg_tys.skip_binder()[0].is_region_ptr() {
|
2017-10-25 19:41:31 +00:00
|
|
|
|
match cx.tables.expr_ty(&args[0]).sty {
|
|
|
|
|
// If the length is greater than 32 no traits are implemented for array and
|
|
|
|
|
// therefore we cannot use `&`.
|
2018-05-13 08:44:57 +00:00
|
|
|
|
ty::TypeVariants::TyArray(_, size) if size.assert_usize(cx.tcx).expect("array size") > 32 => (),
|
2017-11-04 19:55:56 +00:00
|
|
|
|
_ => lint_iter_method(cx, args, arg, method_name),
|
2017-10-25 19:41:31 +00:00
|
|
|
|
};
|
2017-01-09 15:59:55 +00:00
|
|
|
|
} else {
|
2015-11-18 11:35:18 +00:00
|
|
|
|
let object = snippet(cx, args[0].span, "_");
|
2017-08-09 07:30:56 +00:00
|
|
|
|
span_lint_and_sugg(
|
|
|
|
|
cx,
|
|
|
|
|
EXPLICIT_INTO_ITER_LOOP,
|
|
|
|
|
arg.span,
|
|
|
|
|
"it is more idiomatic to loop over 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",
|
|
|
|
|
object.to_string(),
|
|
|
|
|
);
|
2015-11-18 11:35:18 +00:00
|
|
|
|
}
|
2017-01-09 15:59:55 +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 \
|
2017-09-05 09:33:04 +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
|
|
|
|
|
2016-01-29 23:15:57 +00:00
|
|
|
|
/// Check for `for` loops over `Option`s and `Results`
|
|
|
|
|
fn check_arg_type(cx: &LateContext, pat: &Pat, arg: &Expr) {
|
2017-01-13 16:04:56 +00:00
|
|
|
|
let ty = cx.tables.expr_ty(arg);
|
2016-04-14 16:13:15 +00:00
|
|
|
|
if match_type(cx, ty, &paths::OPTION) {
|
2017-08-09 07:30:56 +00:00
|
|
|
|
span_help_and_lint(
|
|
|
|
|
cx,
|
|
|
|
|
FOR_LOOP_OVER_OPTION,
|
|
|
|
|
arg.span,
|
|
|
|
|
&format!(
|
|
|
|
|
"for loop over `{0}`, which is an `Option`. This is more readably written as an \
|
2017-09-05 09:33:04 +00:00
|
|
|
|
`if let` statement.",
|
2017-08-09 07:30:56 +00:00
|
|
|
|
snippet(cx, arg.span, "_")
|
|
|
|
|
),
|
|
|
|
|
&format!(
|
|
|
|
|
"consider replacing `for {0} in {1}` with `if let Some({0}) = {1}`",
|
|
|
|
|
snippet(cx, pat.span, "_"),
|
|
|
|
|
snippet(cx, arg.span, "_")
|
|
|
|
|
),
|
|
|
|
|
);
|
2016-04-14 16:13:15 +00:00
|
|
|
|
} else if match_type(cx, ty, &paths::RESULT) {
|
2017-08-09 07:30:56 +00:00
|
|
|
|
span_help_and_lint(
|
|
|
|
|
cx,
|
|
|
|
|
FOR_LOOP_OVER_RESULT,
|
|
|
|
|
arg.span,
|
|
|
|
|
&format!(
|
|
|
|
|
"for loop over `{0}`, which is a `Result`. This is more readably written as an \
|
2017-09-05 09:33:04 +00:00
|
|
|
|
`if let` statement.",
|
2017-08-09 07:30:56 +00:00
|
|
|
|
snippet(cx, arg.span, "_")
|
|
|
|
|
),
|
|
|
|
|
&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
|
|
|
|
}
|
|
|
|
|
|
2016-12-21 11:14:54 +00:00
|
|
|
|
fn check_for_loop_explicit_counter<'a, 'tcx>(
|
|
|
|
|
cx: &LateContext<'a, 'tcx>,
|
|
|
|
|
arg: &'tcx Expr,
|
|
|
|
|
body: &'tcx Expr,
|
2017-08-09 07:30:56 +00:00
|
|
|
|
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.
|
2016-01-04 04:26:12 +00:00
|
|
|
|
let mut visitor = IncrementVisitor {
|
2018-03-15 15:07:15 +00:00
|
|
|
|
cx,
|
2016-01-04 04:26:12 +00:00
|
|
|
|
states: HashMap::new(),
|
|
|
|
|
depth: 0,
|
|
|
|
|
done: false,
|
|
|
|
|
};
|
2015-11-18 11:35:18 +00:00
|
|
|
|
walk_expr(&mut visitor, body);
|
|
|
|
|
|
|
|
|
|
// For each candidate, check the parent block to see if
|
|
|
|
|
// it's initialized to zero at the start of the loop.
|
2017-02-02 16:53:28 +00:00
|
|
|
|
let map = &cx.tcx.hir;
|
2017-11-04 19:55:56 +00:00
|
|
|
|
let parent_scope = map.get_enclosing_scope(expr.id)
|
|
|
|
|
.and_then(|id| map.get_enclosing_scope(id));
|
2015-11-18 11:35:18 +00:00
|
|
|
|
if let Some(parent_id) = parent_scope {
|
|
|
|
|
if let NodeBlock(block) = map.get(parent_id) {
|
2017-11-04 19:55:56 +00:00
|
|
|
|
for (id, _) in visitor
|
|
|
|
|
.states
|
|
|
|
|
.iter()
|
|
|
|
|
.filter(|&(_, v)| *v == VarState::IncrOnce)
|
2017-08-09 07:30:56 +00:00
|
|
|
|
{
|
2016-01-04 04:26:12 +00:00
|
|
|
|
let mut visitor2 = InitializeVisitor {
|
2018-03-15 15:07:15 +00:00
|
|
|
|
cx,
|
2016-01-04 04:26:12 +00:00
|
|
|
|
end_expr: expr,
|
2016-02-02 21:35:01 +00:00
|
|
|
|
var_id: *id,
|
2016-01-04 04:26:12 +00:00
|
|
|
|
state: VarState::IncrOnce,
|
|
|
|
|
name: None,
|
|
|
|
|
depth: 0,
|
|
|
|
|
past_loop: false,
|
|
|
|
|
};
|
2015-11-18 11:35:18 +00:00
|
|
|
|
walk_block(&mut visitor2, block);
|
|
|
|
|
|
|
|
|
|
if visitor2.state == VarState::Warn {
|
|
|
|
|
if let Some(name) = visitor2.name {
|
2017-08-09 07:30:56 +00:00
|
|
|
|
span_lint(
|
|
|
|
|
cx,
|
|
|
|
|
EXPLICIT_COUNTER_LOOP,
|
|
|
|
|
expr.span,
|
|
|
|
|
&format!(
|
|
|
|
|
"the variable `{0}` is used as a loop counter. Consider using `for ({0}, \
|
2017-09-05 09:33:04 +00:00
|
|
|
|
item) in {1}.enumerate()` or similar iterators",
|
2017-08-09 07:30:56 +00:00
|
|
|
|
name,
|
|
|
|
|
snippet(cx, arg.span, "_")
|
|
|
|
|
),
|
|
|
|
|
);
|
2015-11-18 11:35:18 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2016-03-19 16:48:29 +00:00
|
|
|
|
/// Check for the `FOR_KV_MAP` lint.
|
2016-12-21 11:14:54 +00:00
|
|
|
|
fn check_for_loop_over_map_kv<'a, 'tcx>(
|
|
|
|
|
cx: &LateContext<'a, 'tcx>,
|
|
|
|
|
pat: &'tcx Pat,
|
|
|
|
|
arg: &'tcx Expr,
|
|
|
|
|
body: &'tcx Expr,
|
2017-08-09 07:30:56 +00:00
|
|
|
|
expr: &'tcx Expr,
|
2016-12-21 11:14:54 +00:00
|
|
|
|
) {
|
2016-07-01 18:55:45 +00:00
|
|
|
|
let pat_span = pat.span;
|
|
|
|
|
|
2016-05-27 12:24:28 +00:00
|
|
|
|
if let PatKind::Tuple(ref pat, _) = pat.node {
|
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;
|
2017-01-13 16:04:56 +00:00
|
|
|
|
let (new_pat_span, kind, ty, mutbl) = match cx.tables.expr_ty(arg).sty {
|
2018-05-11 06:37:48 +00:00
|
|
|
|
ty::TyRef(_, ty, mutbl) => match (&pat[0].node, &pat[1].node) {
|
|
|
|
|
(key, _) if pat_is_wild(key, body) => (pat[1].span, "value", ty, mutbl),
|
|
|
|
|
(_, value) if pat_is_wild(value, body) => (pat[0].span, "key", ty, MutImmutable),
|
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 {
|
|
|
|
|
MutImmutable => "",
|
|
|
|
|
MutMutable => "_mut",
|
|
|
|
|
};
|
|
|
|
|
let arg = match arg.node {
|
|
|
|
|
ExprAddrOf(_, ref expr) => &**expr,
|
|
|
|
|
_ => arg,
|
2016-01-19 20:10:00 +00:00
|
|
|
|
};
|
|
|
|
|
|
2016-04-14 16:13:15 +00:00
|
|
|
|
if match_type(cx, ty, &paths::HASHMAP) || 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),
|
|
|
|
|
|db| {
|
|
|
|
|
let map = sugg::Sugg::hir(cx, arg, "map");
|
|
|
|
|
multispan_sugg(
|
|
|
|
|
db,
|
|
|
|
|
"use the corresponding method".into(),
|
|
|
|
|
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
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2018-03-05 21:20:28 +00:00
|
|
|
|
struct MutatePairDelegate {
|
2017-09-19 00:10:33 +00:00
|
|
|
|
node_id_low: Option<NodeId>,
|
|
|
|
|
node_id_high: Option<NodeId>,
|
|
|
|
|
span_low: Option<Span>,
|
|
|
|
|
span_high: Option<Span>,
|
2017-08-30 14:38:13 +00:00
|
|
|
|
}
|
|
|
|
|
|
2018-03-05 21:20:28 +00:00
|
|
|
|
impl<'tcx> Delegate<'tcx> for MutatePairDelegate {
|
2018-05-06 12:05:41 +00:00
|
|
|
|
fn consume(&mut self, _: NodeId, _: Span, _: &cmt_<'tcx>, _: ConsumeMode) {}
|
2017-10-25 19:41:31 +00:00
|
|
|
|
|
2018-05-06 12:05:41 +00:00
|
|
|
|
fn matched_pat(&mut self, _: &Pat, _: &cmt_<'tcx>, _: MatchMode) {}
|
2017-08-30 14:38:13 +00:00
|
|
|
|
|
2018-05-06 12:05:41 +00:00
|
|
|
|
fn consume_pat(&mut self, _: &Pat, _: &cmt_<'tcx>, _: ConsumeMode) {}
|
2017-08-30 14:38:13 +00:00
|
|
|
|
|
2018-05-06 12:05:41 +00:00
|
|
|
|
fn borrow(&mut self, _: NodeId, sp: Span, cmt: &cmt_<'tcx>, _: ty::Region, bk: ty::BorrowKind, _: LoanCause) {
|
2017-09-26 01:39:50 +00:00
|
|
|
|
if let ty::BorrowKind::MutBorrow = bk {
|
|
|
|
|
if let Categorization::Local(id) = cmt.cat {
|
|
|
|
|
if Some(id) == self.node_id_low {
|
|
|
|
|
self.span_low = Some(sp)
|
2017-09-25 06:00:21 +00:00
|
|
|
|
}
|
2017-09-26 01:39:50 +00:00
|
|
|
|
if Some(id) == self.node_id_high {
|
|
|
|
|
self.span_high = Some(sp)
|
|
|
|
|
}
|
|
|
|
|
}
|
2017-09-25 06:00:21 +00:00
|
|
|
|
}
|
2017-08-30 14:38:13 +00:00
|
|
|
|
}
|
|
|
|
|
|
2018-05-06 12:05:41 +00:00
|
|
|
|
fn mutate(&mut self, _: NodeId, sp: Span, cmt: &cmt_<'tcx>, _: MutateMode) {
|
2017-09-19 00:10:33 +00:00
|
|
|
|
if let Categorization::Local(id) = cmt.cat {
|
|
|
|
|
if Some(id) == self.node_id_low {
|
|
|
|
|
self.span_low = Some(sp)
|
|
|
|
|
}
|
|
|
|
|
if Some(id) == self.node_id_high {
|
|
|
|
|
self.span_high = Some(sp)
|
|
|
|
|
}
|
2017-08-30 14:38:13 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2017-11-04 19:55:56 +00:00
|
|
|
|
fn decl_without_init(&mut self, _: NodeId, _: Span) {}
|
2017-08-30 14:38:13 +00:00
|
|
|
|
}
|
|
|
|
|
|
2018-03-05 21:20:28 +00:00
|
|
|
|
impl<'tcx> 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
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2017-09-24 19:40:10 +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),
|
|
|
|
|
..
|
2018-05-08 15:16:01 +00:00
|
|
|
|
}) = higher::range(cx, arg)
|
2017-11-04 19:55:56 +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
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2017-09-19 00:10:33 +00:00
|
|
|
|
fn mut_warn_with_span(cx: &LateContext, span: Option<Span>) {
|
|
|
|
|
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
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn check_for_mutability(cx: &LateContext, bound: &Expr) -> Option<NodeId> {
|
2017-10-23 19:18:02 +00:00
|
|
|
|
if_chain! {
|
|
|
|
|
if let ExprPath(ref qpath) = bound.node;
|
|
|
|
|
if let QPath::Resolved(None, _) = *qpath;
|
|
|
|
|
then {
|
|
|
|
|
let def = cx.tables.qpath_def(qpath, bound.hir_id);
|
|
|
|
|
if let Def::Local(node_id) = def {
|
|
|
|
|
let node_str = cx.tcx.hir.get(node_id);
|
|
|
|
|
if_chain! {
|
|
|
|
|
if let map::Node::NodeBinding(pat) = node_str;
|
|
|
|
|
if let PatKind::Binding(bind_ann, _, _, _) = pat.node;
|
|
|
|
|
if let BindingAnnotation::Mutable = bind_ann;
|
|
|
|
|
then {
|
|
|
|
|
return Some(node_id);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
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
|
|
|
|
}
|
|
|
|
|
|
2017-09-26 01:39:50 +00:00
|
|
|
|
fn check_for_mutation(cx: &LateContext, body: &Expr, bound_ids: &[Option<NodeId>]) -> (Option<Span>, Option<Span>) {
|
2018-03-05 21:20:28 +00:00
|
|
|
|
let mut delegate = MutatePairDelegate {
|
2017-11-04 19:55:56 +00:00
|
|
|
|
node_id_low: bound_ids[0],
|
|
|
|
|
node_id_high: bound_ids[1],
|
|
|
|
|
span_low: None,
|
|
|
|
|
span_high: None,
|
|
|
|
|
};
|
2017-09-25 06:00:21 +00:00
|
|
|
|
let def_id = def_id::DefId::local(body.hir_id.owner);
|
|
|
|
|
let region_scope_tree = &cx.tcx.region_scope_tree(def_id);
|
2017-10-19 16:27:58 +00:00
|
|
|
|
ExprUseVisitor::new(&mut delegate, cx.tcx, cx.param_env, region_scope_tree, cx.tables, None).walk_expr(body);
|
2017-09-26 01:39:50 +00:00
|
|
|
|
delegate.mutation_span()
|
2017-08-15 16:41:59 +00:00
|
|
|
|
}
|
|
|
|
|
|
2016-03-19 16:48:29 +00:00
|
|
|
|
/// Return true if the pattern is a `PatWild` or an ident prefixed with `'_'`.
|
2017-05-12 10:02:42 +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,
|
2016-12-01 21:31:56 +00:00
|
|
|
|
PatKind::Binding(_, _, ident, None) if ident.node.as_str().starts_with('_') => {
|
2016-02-05 18:14:02 +00:00
|
|
|
|
let mut visitor = UsedVisitor {
|
|
|
|
|
var: ident.node,
|
|
|
|
|
used: false,
|
|
|
|
|
};
|
|
|
|
|
walk_expr(&mut visitor, body);
|
|
|
|
|
!visitor.used
|
2016-12-20 17:21:30 +00:00
|
|
|
|
},
|
2016-01-19 20:10:00 +00:00
|
|
|
|
_ => false,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2017-05-12 10:02:42 +00:00
|
|
|
|
struct UsedVisitor {
|
2016-05-19 21:14:34 +00:00
|
|
|
|
var: ast::Name, // var to look for
|
2017-11-04 19:55:56 +00:00
|
|
|
|
used: bool, // has the var been used otherwise?
|
2016-02-05 18:14:02 +00:00
|
|
|
|
}
|
|
|
|
|
|
2017-05-12 10:02:42 +00:00
|
|
|
|
impl<'tcx> Visitor<'tcx> for UsedVisitor {
|
2016-12-06 10:32:21 +00:00
|
|
|
|
fn visit_expr(&mut self, expr: &'tcx Expr) {
|
2017-07-31 22:58:26 +00:00
|
|
|
|
if match_var(expr, self.var) {
|
|
|
|
|
self.used = true;
|
2017-09-05 00:16:34 +00:00
|
|
|
|
} else {
|
|
|
|
|
walk_expr(self, expr);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
|
|
|
|
|
NestedVisitorMap::None
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2017-09-16 22:45:28 +00:00
|
|
|
|
struct LocalUsedVisitor<'a, 'tcx: 'a> {
|
2017-09-05 00:16:34 +00:00
|
|
|
|
cx: &'a LateContext<'a, 'tcx>,
|
2017-09-12 12:26:40 +00:00
|
|
|
|
local: ast::NodeId,
|
2017-09-05 00:16:34 +00:00
|
|
|
|
used: bool,
|
|
|
|
|
}
|
|
|
|
|
|
2017-09-12 12:26:40 +00:00
|
|
|
|
impl<'a, 'tcx: 'a> Visitor<'tcx> for LocalUsedVisitor<'a, 'tcx> {
|
2017-09-05 00:16:34 +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
|
|
|
|
|
2016-12-06 10:32:21 +00:00
|
|
|
|
fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
|
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
|
|
|
|
}
|
|
|
|
|
|
2016-12-06 10:32:21 +00:00
|
|
|
|
struct VarVisitor<'a, 'tcx: 'a> {
|
2017-07-10 13:30:28 +00:00
|
|
|
|
/// context reference
|
|
|
|
|
cx: &'a LateContext<'a, 'tcx>,
|
|
|
|
|
/// var name to look for as index
|
2017-09-12 12:26:40 +00:00
|
|
|
|
var: ast::NodeId,
|
2017-11-07 13:41:54 +00:00
|
|
|
|
/// indexed variables that are used mutably
|
|
|
|
|
indexed_mut: HashSet<Name>,
|
2017-11-07 14:32:52 +00:00
|
|
|
|
/// indirectly indexed variables (`v[(i + 4) % N]`), the extend is `None` for global
|
|
|
|
|
indexed_indirectly: HashMap<Name, 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]`
|
|
|
|
|
indexed_directly: HashMap<Name, Option<region::Scope>>,
|
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]`
|
|
|
|
|
referenced: HashSet<Name>,
|
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> {
|
|
|
|
|
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
|
2017-10-23 19:18:02 +00:00
|
|
|
|
if let ExprPath(ref seqpath) = seqexpr.node;
|
|
|
|
|
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 {
|
|
|
|
|
self.indexed_mut.insert(seqvar.segments[0].name);
|
|
|
|
|
}
|
2017-10-23 19:18:02 +00:00
|
|
|
|
let def = self.cx.tables.qpath_def(seqpath, seqexpr.hir_id);
|
|
|
|
|
match def {
|
|
|
|
|
Def::Local(node_id) | Def::Upvar(node_id, ..) => {
|
|
|
|
|
let hir_id = self.cx.tcx.hir.node_to_hir_id(node_id);
|
2017-10-25 19:41:31 +00:00
|
|
|
|
|
2017-10-23 19:18:02 +00:00
|
|
|
|
let parent_id = self.cx.tcx.hir.get_parent(expr.id);
|
|
|
|
|
let parent_def_id = self.cx.tcx.hir.local_def_id(parent_id);
|
|
|
|
|
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 {
|
|
|
|
|
self.indexed_indirectly.insert(seqvar.segments[0].name, Some(extent));
|
|
|
|
|
}
|
2017-10-23 19:18:02 +00:00
|
|
|
|
if index_used_directly {
|
|
|
|
|
self.indexed_directly.insert(seqvar.segments[0].name, Some(extent));
|
|
|
|
|
}
|
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
|
|
|
|
Def::Static(..) | Def::Const(..) => {
|
2017-11-07 14:32:52 +00:00
|
|
|
|
if indexed_indirectly {
|
|
|
|
|
self.indexed_indirectly.insert(seqvar.segments[0].name, None);
|
|
|
|
|
}
|
2017-10-23 19:18:02 +00:00
|
|
|
|
if index_used_directly {
|
|
|
|
|
self.indexed_directly.insert(seqvar.segments[0].name, None);
|
|
|
|
|
}
|
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> {
|
|
|
|
|
fn visit_expr(&mut self, expr: &'tcx Expr) {
|
|
|
|
|
if_chain! {
|
|
|
|
|
// a range index op
|
|
|
|
|
if let ExprMethodCall(ref meth, _, ref args) = expr.node;
|
2018-03-05 03:56:03 +00:00
|
|
|
|
if (meth.name == "index" && match_trait_method(self.cx, expr, &paths::INDEX))
|
|
|
|
|
|| (meth.name == "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
|
|
|
|
|
if let ExprIndex(ref seqexpr, ref idx) = expr.node;
|
|
|
|
|
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
|
2017-10-23 19:18:02 +00:00
|
|
|
|
if let ExprPath(ref qpath) = expr.node;
|
|
|
|
|
if let QPath::Resolved(None, ref path) = *qpath;
|
|
|
|
|
if path.segments.len() == 1;
|
|
|
|
|
if let Def::Local(local_id) = self.cx.tables.qpath_def(qpath, expr.hir_id);
|
|
|
|
|
then {
|
|
|
|
|
if local_id == self.var {
|
|
|
|
|
// we are not indexing anything, record that
|
|
|
|
|
self.nonindex = true;
|
|
|
|
|
} else {
|
|
|
|
|
// not the correct variable, but still a variable
|
|
|
|
|
self.referenced.insert(path.segments[0].name);
|
|
|
|
|
}
|
2017-07-10 13:30:28 +00:00
|
|
|
|
}
|
2017-10-23 19:18:02 +00:00
|
|
|
|
}
|
2017-11-07 13:41:54 +00:00
|
|
|
|
let old = self.prefer_mutable;
|
|
|
|
|
match expr.node {
|
|
|
|
|
ExprAssignOp(_, ref lhs, ref rhs) |
|
|
|
|
|
ExprAssign(ref lhs, ref rhs) => {
|
|
|
|
|
self.prefer_mutable = true;
|
|
|
|
|
self.visit_expr(lhs);
|
|
|
|
|
self.prefer_mutable = false;
|
|
|
|
|
self.visit_expr(rhs);
|
|
|
|
|
},
|
|
|
|
|
ExprAddrOf(mutbl, ref expr) => {
|
|
|
|
|
if mutbl == MutMutable {
|
|
|
|
|
self.prefer_mutable = true;
|
|
|
|
|
}
|
|
|
|
|
self.visit_expr(expr);
|
|
|
|
|
},
|
|
|
|
|
ExprCall(ref f, ref args) => {
|
2017-11-29 14:52:57 +00:00
|
|
|
|
self.visit_expr(f);
|
|
|
|
|
for expr in args {
|
|
|
|
|
let ty = self.cx.tables.expr_ty_adjusted(expr);
|
2017-11-07 13:41:54 +00:00
|
|
|
|
self.prefer_mutable = false;
|
2018-05-11 06:37:48 +00:00
|
|
|
|
if let ty::TyRef(_, _, mutbl) = ty.sty {
|
|
|
|
|
if mutbl == MutMutable {
|
2017-11-07 13:41:54 +00:00
|
|
|
|
self.prefer_mutable = true;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
self.visit_expr(expr);
|
|
|
|
|
}
|
|
|
|
|
},
|
|
|
|
|
ExprMethodCall(_, _, ref args) => {
|
|
|
|
|
let def_id = self.cx.tables.type_dependent_defs()[expr.hir_id].def_id();
|
|
|
|
|
for (ty, expr) in self.cx.tcx.fn_sig(def_id).inputs().skip_binder().iter().zip(args) {
|
|
|
|
|
self.prefer_mutable = false;
|
2018-05-11 06:37:48 +00:00
|
|
|
|
if let ty::TyRef(_, _, mutbl) = ty.sty {
|
|
|
|
|
if mutbl == MutMutable {
|
2017-11-07 13:41:54 +00:00
|
|
|
|
self.prefer_mutable = true;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
self.visit_expr(expr);
|
|
|
|
|
}
|
|
|
|
|
},
|
|
|
|
|
_ => walk_expr(self, expr),
|
|
|
|
|
}
|
|
|
|
|
self.prefer_mutable = old;
|
2015-08-12 19:56:27 +00:00
|
|
|
|
}
|
2016-12-06 10:32:21 +00:00
|
|
|
|
fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
|
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
|
|
|
|
|
2016-12-06 10:32:21 +00:00
|
|
|
|
fn is_iterator_used_after_while_let<'a, 'tcx: 'a>(cx: &LateContext<'a, '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,
|
2015-10-26 22:49:37 +00:00
|
|
|
|
iter_expr_id: iter_expr.id,
|
|
|
|
|
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
|
|
|
|
};
|
|
|
|
|
if let Some(enclosing_block) = get_enclosing_block(cx, def_id) {
|
|
|
|
|
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
|
|
|
|
}
|
|
|
|
|
|
2016-12-06 10:32:21 +00:00
|
|
|
|
struct VarUsedAfterLoopVisitor<'a, 'tcx: 'a> {
|
|
|
|
|
cx: &'a LateContext<'a, 'tcx>,
|
2015-10-19 23:04:21 +00:00
|
|
|
|
def_id: NodeId,
|
2015-10-26 22:49:37 +00:00
|
|
|
|
iter_expr_id: NodeId,
|
|
|
|
|
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> {
|
|
|
|
|
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;
|
|
|
|
|
}
|
|
|
|
|
} else if self.iter_expr_id == expr.id {
|
|
|
|
|
self.past_while_let = true;
|
2015-10-19 23:04:21 +00:00
|
|
|
|
}
|
|
|
|
|
walk_expr(self, expr);
|
|
|
|
|
}
|
2016-12-06 10:32:21 +00:00
|
|
|
|
fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
|
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
|
|
|
|
}
|
|
|
|
|
|
2015-10-26 22:49:37 +00:00
|
|
|
|
|
2016-03-19 16:48:29 +00:00
|
|
|
|
/// Return true if the type of expr is one that provides `IntoIterator` impls
|
|
|
|
|
/// for `&T` and `&mut T`, such as `Vec`.
|
2016-02-29 11:19:32 +00:00
|
|
|
|
#[cfg_attr(rustfmt, rustfmt_skip)]
|
2015-09-19 02:53:04 +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
|
2017-01-13 16:04:56 +00:00
|
|
|
|
let ty = cx.tables.expr_ty(e);
|
2018-05-13 08:44:57 +00:00
|
|
|
|
is_iterable_array(ty, cx) ||
|
2016-04-14 16:13:15 +00:00
|
|
|
|
match_type(cx, ty, &paths::VEC) ||
|
2016-04-14 16:41:38 +00:00
|
|
|
|
match_type(cx, ty, &paths::LINKED_LIST) ||
|
2016-04-14 16:13:15 +00:00
|
|
|
|
match_type(cx, ty, &paths::HASHMAP) ||
|
2016-04-26 11:31:52 +00:00
|
|
|
|
match_type(cx, ty, &paths::HASHSET) ||
|
|
|
|
|
match_type(cx, ty, &paths::VEC_DEQUE) ||
|
|
|
|
|
match_type(cx, ty, &paths::BINARY_HEAP) ||
|
2016-04-14 16:13:15 +00:00
|
|
|
|
match_type(cx, ty, &paths::BTREEMAP) ||
|
2016-04-26 11:31:52 +00:00
|
|
|
|
match_type(cx, ty, &paths::BTREESET)
|
2015-08-25 16:26:20 +00:00
|
|
|
|
}
|
|
|
|
|
|
2018-05-13 08:44:57 +00:00
|
|
|
|
fn is_iterable_array(ty: Ty, cx: &LateContext) -> bool {
|
2015-09-27 07:39:42 +00:00
|
|
|
|
// IntoIterator is currently only implemented for array sizes <= 32 in rustc
|
2015-08-25 16:26:20 +00:00
|
|
|
|
match ty.sty {
|
2018-05-13 08:44:57 +00:00
|
|
|
|
ty::TyArray(_, n) => (0..=32).contains(&n.assert_usize(cx.tcx).expect("array length")),
|
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.
|
2015-09-27 07:39:42 +00:00
|
|
|
|
fn extract_expr_from_first_stmt(block: &Block) -> Option<&Expr> {
|
2016-01-04 04:26:12 +00:00
|
|
|
|
if block.stmts.is_empty() {
|
|
|
|
|
return None;
|
|
|
|
|
}
|
2015-10-14 09:44:09 +00:00
|
|
|
|
if let StmtDecl(ref decl, _) = block.stmts[0].node {
|
|
|
|
|
if let DeclLocal(ref local) = decl.node {
|
2016-01-04 04:26:12 +00:00
|
|
|
|
if let Some(ref expr) = local.init {
|
|
|
|
|
Some(expr)
|
|
|
|
|
} else {
|
|
|
|
|
None
|
|
|
|
|
}
|
|
|
|
|
} else {
|
|
|
|
|
None
|
|
|
|
|
}
|
|
|
|
|
} else {
|
|
|
|
|
None
|
|
|
|
|
}
|
2015-09-27 07:39:42 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// If a block begins with an expression (with or without semicolon), return it.
|
|
|
|
|
fn extract_first_expr(block: &Block) -> Option<&Expr> {
|
|
|
|
|
match block.expr {
|
2016-06-16 14:19:17 +00:00
|
|
|
|
Some(ref expr) if block.stmts.is_empty() => Some(expr),
|
2017-11-04 19:55:56 +00:00
|
|
|
|
None if !block.stmts.is_empty() => match block.stmts[0].node {
|
|
|
|
|
StmtExpr(ref expr, _) | StmtSemi(ref expr, _) => Some(expr),
|
|
|
|
|
StmtDecl(..) => 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
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2017-09-16 22:45:28 +00:00
|
|
|
|
/// Return true if expr contains a single break expr without destination label
|
|
|
|
|
/// and
|
2017-09-05 20:28:30 +00:00
|
|
|
|
/// passed expression. The expression may be within a block.
|
|
|
|
|
fn is_simple_break_expr(expr: &Expr) -> bool {
|
2015-08-29 09:41:06 +00:00
|
|
|
|
match expr.node {
|
2018-01-27 12:57:31 +00:00
|
|
|
|
ExprBreak(dest, ref passed_expr) if dest.label.is_none() && passed_expr.is_none() => true,
|
2017-11-04 19:55:56 +00:00
|
|
|
|
ExprBlock(ref b) => match extract_first_expr(b) {
|
|
|
|
|
Some(subexpr) => is_simple_break_expr(subexpr),
|
|
|
|
|
None => false,
|
2016-12-20 17:21:30 +00:00
|
|
|
|
},
|
2015-08-29 09:41:06 +00:00
|
|
|
|
_ => false,
|
|
|
|
|
}
|
|
|
|
|
}
|
2015-08-23 17:25:45 +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.
|
|
|
|
|
#[derive(PartialEq)]
|
|
|
|
|
enum VarState {
|
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
|
|
|
|
|
Declared, // Declared but not (yet) initialized to zero
|
2015-08-23 17:25:45 +00:00
|
|
|
|
Warn,
|
2016-01-04 04:26:12 +00:00
|
|
|
|
DontWarn,
|
2015-08-23 17:25:45 +00:00
|
|
|
|
}
|
|
|
|
|
|
2016-02-26 11:45:55 +00:00
|
|
|
|
/// Scan a for loop for variables that are incremented exactly once.
|
2016-12-06 10:32:21 +00:00
|
|
|
|
struct IncrementVisitor<'a, 'tcx: 'a> {
|
2017-11-04 19:55:56 +00:00
|
|
|
|
cx: &'a LateContext<'a, 'tcx>, // context reference
|
2016-01-04 04:26:12 +00:00
|
|
|
|
states: HashMap<NodeId, VarState>, // incremented variables
|
2017-11-04 19:55:56 +00:00
|
|
|
|
depth: u32, // depth of conditional expressions
|
2016-01-04 04:26:12 +00:00
|
|
|
|
done: bool,
|
2015-08-23 17:25:45 +00:00
|
|
|
|
}
|
|
|
|
|
|
2016-12-06 10:32:21 +00:00
|
|
|
|
impl<'a, 'tcx> Visitor<'tcx> for IncrementVisitor<'a, 'tcx> {
|
|
|
|
|
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) {
|
|
|
|
|
let state = self.states.entry(def_id).or_insert(VarState::Initial);
|
|
|
|
|
|
|
|
|
|
match parent.node {
|
2016-01-04 04:26:12 +00:00
|
|
|
|
ExprAssignOp(op, ref lhs, ref rhs) => {
|
2015-08-23 17:25:45 +00:00
|
|
|
|
if lhs.id == expr.id {
|
2015-09-04 13:26:58 +00:00
|
|
|
|
if op.node == BiAdd && is_integer_literal(rhs, 1) {
|
2015-08-23 17:25:45 +00:00
|
|
|
|
*state = match *state {
|
|
|
|
|
VarState::Initial if self.depth == 0 => VarState::IncrOnce,
|
2016-01-04 04:26:12 +00:00
|
|
|
|
_ => VarState::DontWarn,
|
2015-08-23 17:25:45 +00:00
|
|
|
|
};
|
2016-01-04 04:26:12 +00:00
|
|
|
|
} else {
|
2015-08-23 17:25:45 +00:00
|
|
|
|
// Assigned some other value
|
|
|
|
|
*state = VarState::DontWarn;
|
|
|
|
|
}
|
2016-01-04 04:26:12 +00:00
|
|
|
|
}
|
2016-12-20 17:21:30 +00:00
|
|
|
|
},
|
2015-08-23 17:25:45 +00:00
|
|
|
|
ExprAssign(ref lhs, _) if lhs.id == expr.id => *state = VarState::DontWarn,
|
2016-01-04 04:26:12 +00:00
|
|
|
|
ExprAddrOf(mutability, _) if mutability == MutMutable => *state = VarState::DontWarn,
|
|
|
|
|
_ => (),
|
2015-08-23 17:25:45 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
2016-01-04 04:26:12 +00:00
|
|
|
|
} else if is_loop(expr) {
|
2015-08-23 17:25:45 +00:00
|
|
|
|
self.states.clear();
|
|
|
|
|
self.done = true;
|
|
|
|
|
return;
|
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;
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
walk_expr(self, expr);
|
|
|
|
|
}
|
2016-12-06 10:32:21 +00:00
|
|
|
|
fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
|
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
|
|
|
|
}
|
|
|
|
|
|
2016-02-26 11:45:55 +00:00
|
|
|
|
/// Check whether a variable is initialized to zero at the start of a loop.
|
2016-12-06 10:32:21 +00:00
|
|
|
|
struct InitializeVisitor<'a, 'tcx: 'a> {
|
|
|
|
|
cx: &'a LateContext<'a, 'tcx>, // context reference
|
2017-11-04 19:55:56 +00:00
|
|
|
|
end_expr: &'tcx Expr, // the for loop. Stop scanning here.
|
2015-08-23 17:25:45 +00:00
|
|
|
|
var_id: NodeId,
|
|
|
|
|
state: VarState,
|
|
|
|
|
name: Option<Name>,
|
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
|
|
|
|
}
|
|
|
|
|
|
2016-12-06 10:32:21 +00:00
|
|
|
|
impl<'a, 'tcx> Visitor<'tcx> for InitializeVisitor<'a, 'tcx> {
|
|
|
|
|
fn visit_decl(&mut self, decl: &'tcx Decl) {
|
2015-08-23 17:25:45 +00:00
|
|
|
|
// Look for declarations of the variable
|
|
|
|
|
if let DeclLocal(ref local) = decl.node {
|
|
|
|
|
if local.pat.id == self.var_id {
|
2016-12-01 21:31:56 +00:00
|
|
|
|
if let PatKind::Binding(_, _, ref ident, _) = local.pat.node {
|
2016-05-19 21:14:34 +00:00
|
|
|
|
self.name = Some(ident.node);
|
2015-08-23 17:25:45 +00:00
|
|
|
|
|
|
|
|
|
self.state = if let Some(ref init) = local.init {
|
2015-09-04 13:26:58 +00:00
|
|
|
|
if is_integer_literal(init, 0) {
|
2015-08-23 17:25:45 +00:00
|
|
|
|
VarState::Warn
|
|
|
|
|
} else {
|
|
|
|
|
VarState::Declared
|
|
|
|
|
}
|
2016-01-04 04:26:12 +00:00
|
|
|
|
} else {
|
2015-08-23 17:25:45 +00:00
|
|
|
|
VarState::Declared
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
walk_decl(self, decl);
|
|
|
|
|
}
|
|
|
|
|
|
2016-12-06 10:32:21 +00:00
|
|
|
|
fn visit_expr(&mut self, expr: &'tcx Expr) {
|
2015-11-25 23:09:01 +00:00
|
|
|
|
if self.state == VarState::DontWarn {
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
if expr == self.end_expr {
|
|
|
|
|
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
|
|
|
|
|
if self.state == VarState::IncrOnce {
|
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) {
|
|
|
|
|
if let Some(parent) = get_parent_expr(self.cx, expr) {
|
|
|
|
|
match parent.node {
|
|
|
|
|
ExprAssignOp(_, ref lhs, _) if lhs.id == expr.id => {
|
|
|
|
|
self.state = VarState::DontWarn;
|
2016-12-20 17:21:30 +00:00
|
|
|
|
},
|
2015-08-23 17:25:45 +00:00
|
|
|
|
ExprAssign(ref lhs, ref rhs) if lhs.id == expr.id => {
|
2015-09-04 13:26:58 +00:00
|
|
|
|
self.state = if is_integer_literal(rhs, 0) && self.depth == 0 {
|
2015-08-23 17:25:45 +00:00
|
|
|
|
VarState::Warn
|
|
|
|
|
} else {
|
|
|
|
|
VarState::DontWarn
|
2016-01-04 04:26:12 +00:00
|
|
|
|
}
|
2016-12-20 17:21:30 +00:00
|
|
|
|
},
|
2016-01-04 04:26:12 +00:00
|
|
|
|
ExprAddrOf(mutability, _) if mutability == MutMutable => self.state = VarState::DontWarn,
|
|
|
|
|
_ => (),
|
2015-08-23 17:25:45 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
2015-11-25 23:09:01 +00:00
|
|
|
|
|
|
|
|
|
if self.past_loop {
|
|
|
|
|
self.state = VarState::DontWarn;
|
|
|
|
|
return;
|
|
|
|
|
}
|
2016-01-04 04:26:12 +00:00
|
|
|
|
} else if !self.past_loop && is_loop(expr) {
|
2015-08-23 17:25:45 +00:00
|
|
|
|
self.state = VarState::DontWarn;
|
|
|
|
|
return;
|
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;
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
walk_expr(self, expr);
|
|
|
|
|
}
|
2016-12-06 10:32:21 +00:00
|
|
|
|
fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
|
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
|
|
|
|
}
|
|
|
|
|
|
2015-09-19 02:53:04 +00:00
|
|
|
|
fn var_def_id(cx: &LateContext, expr: &Expr) -> Option<NodeId> {
|
2016-12-01 21:31:56 +00:00
|
|
|
|
if let ExprPath(ref qpath) = expr.node {
|
2017-08-15 09:10:49 +00:00
|
|
|
|
let path_res = cx.tables.qpath_def(qpath, expr.hir_id);
|
2017-09-12 12:26:40 +00:00
|
|
|
|
if let Def::Local(node_id) = path_res {
|
2016-01-04 04:26:12 +00:00
|
|
|
|
return Some(node_id);
|
2015-08-23 17:25:45 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
None
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn is_loop(expr: &Expr) -> bool {
|
|
|
|
|
match expr.node {
|
2016-01-04 04:26:12 +00:00
|
|
|
|
ExprLoop(..) | ExprWhile(..) => true,
|
|
|
|
|
_ => false,
|
2015-08-23 17:25:45 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn is_conditional(expr: &Expr) -> bool {
|
|
|
|
|
match expr.node {
|
|
|
|
|
ExprIf(..) | ExprMatch(..) => true,
|
2016-01-04 04:26:12 +00:00
|
|
|
|
_ => false,
|
2015-08-23 17:25:45 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
2017-07-31 22:58:26 +00:00
|
|
|
|
|
|
|
|
|
fn is_nested(cx: &LateContext, match_expr: &Expr, iter_expr: &Expr) -> bool {
|
2017-10-23 19:18:02 +00:00
|
|
|
|
if_chain! {
|
|
|
|
|
if let Some(loop_block) = get_enclosing_block(cx, match_expr.id);
|
|
|
|
|
if let Some(map::Node::NodeExpr(loop_expr)) = cx.tcx.hir.find(cx.tcx.hir.get_parent_node(loop_block.id));
|
|
|
|
|
then {
|
|
|
|
|
return is_loop_nested(cx, loop_expr, iter_expr)
|
|
|
|
|
}
|
|
|
|
|
}
|
2017-07-31 22:58:26 +00:00
|
|
|
|
false
|
|
|
|
|
}
|
|
|
|
|
|
2017-08-02 22:41:46 +00:00
|
|
|
|
fn is_loop_nested(cx: &LateContext, loop_expr: &Expr, iter_expr: &Expr) -> bool {
|
|
|
|
|
let mut id = loop_expr.id;
|
|
|
|
|
let iter_name = if let Some(name) = path_name(iter_expr) {
|
|
|
|
|
name
|
|
|
|
|
} else {
|
|
|
|
|
return true;
|
|
|
|
|
};
|
|
|
|
|
loop {
|
|
|
|
|
let parent = cx.tcx.hir.get_parent_node(id);
|
|
|
|
|
if parent == id {
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
match cx.tcx.hir.find(parent) {
|
2017-11-04 19:55:56 +00:00
|
|
|
|
Some(NodeExpr(expr)) => match expr.node {
|
|
|
|
|
ExprLoop(..) | ExprWhile(..) => {
|
|
|
|
|
return true;
|
|
|
|
|
},
|
|
|
|
|
_ => (),
|
2017-08-02 22:41:46 +00:00
|
|
|
|
},
|
|
|
|
|
Some(NodeBlock(block)) => {
|
|
|
|
|
let mut block_visitor = LoopNestVisitor {
|
2018-03-15 15:07:15 +00:00
|
|
|
|
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
|
|
|
|
},
|
|
|
|
|
Some(NodeStmt(_)) => (),
|
|
|
|
|
_ => {
|
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 {
|
|
|
|
|
id: NodeId,
|
|
|
|
|
iterator: Name,
|
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 {
|
|
|
|
|
fn visit_stmt(&mut self, stmt: &'tcx Stmt) {
|
|
|
|
|
if stmt.node.id() == self.id {
|
|
|
|
|
self.nesting = LookFurther;
|
|
|
|
|
} else if self.nesting == Unknown {
|
|
|
|
|
walk_stmt(self, stmt);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2017-07-31 22:58:26 +00:00
|
|
|
|
fn visit_expr(&mut self, expr: &'tcx Expr) {
|
2017-08-09 07:30:56 +00:00
|
|
|
|
if self.nesting != Unknown {
|
|
|
|
|
return;
|
|
|
|
|
}
|
2017-08-02 22:41:46 +00:00
|
|
|
|
if expr.id == self.id {
|
|
|
|
|
self.nesting = LookFurther;
|
|
|
|
|
return;
|
|
|
|
|
}
|
2017-07-31 22:58:26 +00:00
|
|
|
|
match expr.node {
|
2017-11-04 19:55:56 +00:00
|
|
|
|
ExprAssign(ref path, _) | ExprAssignOp(_, ref path, _) => 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
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2017-08-02 22:41:46 +00:00
|
|
|
|
fn visit_pat(&mut self, pat: &'tcx Pat) {
|
2017-08-09 07:30:56 +00:00
|
|
|
|
if self.nesting != Unknown {
|
|
|
|
|
return;
|
|
|
|
|
}
|
2017-08-02 22:41:46 +00:00
|
|
|
|
if let PatKind::Binding(_, _, span_name, _) = pat.node {
|
|
|
|
|
if self.iterator == span_name.node {
|
|
|
|
|
self.nesting = RuledOut;
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
walk_pat(self, pat)
|
2017-07-31 22:58:26 +00:00
|
|
|
|
}
|
|
|
|
|
|
2017-08-02 22:41:46 +00:00
|
|
|
|
fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
|
|
|
|
|
NestedVisitorMap::None
|
2017-07-31 22:58:26 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2017-08-02 22:41:46 +00:00
|
|
|
|
fn path_name(e: &Expr) -> Option<Name> {
|
|
|
|
|
if let ExprPath(QPath::Resolved(_, ref path)) = e.node {
|
|
|
|
|
let segments = &path.segments;
|
|
|
|
|
if segments.len() == 1 {
|
|
|
|
|
return Some(segments[0].name);
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
None
|
2017-07-31 22:58:26 +00:00
|
|
|
|
}
|
2018-03-01 21:00:43 +00:00
|
|
|
|
|
2018-03-01 22:23:41 +00:00
|
|
|
|
fn check_infinite_loop<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, cond: &'tcx Expr, block: &'tcx Block, expr: &'tcx Expr) {
|
2018-03-07 17:24:36 +00:00
|
|
|
|
if constant(cx, cond).is_some() {
|
|
|
|
|
// A pure constant condition (e.g. while false) is not linted.
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2018-03-26 18:37:34 +00:00
|
|
|
|
let mut mut_var_visitor = VarCollectorVisitor {
|
2018-03-01 21:00:43 +00:00
|
|
|
|
cx,
|
2018-03-05 21:20:28 +00:00
|
|
|
|
ids: HashMap::new(),
|
2018-03-01 21:00:43 +00:00
|
|
|
|
skip: false,
|
|
|
|
|
};
|
2018-03-01 22:23:41 +00:00
|
|
|
|
walk_expr(&mut mut_var_visitor, expr);
|
|
|
|
|
if mut_var_visitor.skip {
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2018-03-05 21:20:28 +00:00
|
|
|
|
let mut delegate = MutVarsDelegate {
|
2018-03-26 18:37:34 +00:00
|
|
|
|
used_mutably: mut_var_visitor.ids,
|
2018-03-25 15:23:31 +00:00
|
|
|
|
skip: false,
|
2018-03-01 22:23:41 +00:00
|
|
|
|
};
|
2018-03-05 21:20:28 +00:00
|
|
|
|
let def_id = def_id::DefId::local(block.hir_id.owner);
|
|
|
|
|
let region_scope_tree = &cx.tcx.region_scope_tree(def_id);
|
|
|
|
|
ExprUseVisitor::new(&mut delegate, cx.tcx, cx.param_env, region_scope_tree, cx.tables, None).walk_expr(expr);
|
|
|
|
|
|
2018-03-26 10:32:21 +00:00
|
|
|
|
if delegate.skip {
|
|
|
|
|
return;
|
|
|
|
|
}
|
2018-03-26 18:37:34 +00:00
|
|
|
|
if !delegate.used_mutably.iter().any(|(_, v)| *v) {
|
2018-03-01 22:23:41 +00:00
|
|
|
|
span_lint(
|
|
|
|
|
cx,
|
|
|
|
|
WHILE_IMMUTABLE_CONDITION,
|
2018-03-26 21:24:57 +00:00
|
|
|
|
cond.span,
|
2018-03-07 17:24:36 +00:00
|
|
|
|
"Variable in the condition are not mutated in the loop body. This either leads to an infinite or to a never running loop.",
|
2018-03-01 22:23:41 +00:00
|
|
|
|
);
|
2018-03-01 21:00:43 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
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
|
|
|
|
|
struct VarCollectorVisitor<'a, 'tcx: 'a> {
|
2018-03-01 21:00:43 +00:00
|
|
|
|
cx: &'a LateContext<'a, 'tcx>,
|
2018-03-26 18:37:34 +00:00
|
|
|
|
ids: HashMap<NodeId, 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> {
|
|
|
|
|
fn insert_def_id(&mut self, ex: &'tcx Expr) {
|
|
|
|
|
if_chain! {
|
|
|
|
|
if let ExprPath(ref qpath) = ex.node;
|
|
|
|
|
if let QPath::Resolved(None, _) = *qpath;
|
|
|
|
|
let def = self.cx.tables.qpath_def(qpath, ex.hir_id);
|
|
|
|
|
then {
|
2018-03-26 10:32:21 +00:00
|
|
|
|
match def {
|
|
|
|
|
Def::Local(node_id) | Def::Upvar(node_id, ..) => {
|
|
|
|
|
self.ids.insert(node_id, false);
|
|
|
|
|
},
|
|
|
|
|
_ => {},
|
|
|
|
|
}
|
2018-03-26 18:37:34 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl<'a, 'tcx> Visitor<'tcx> for VarCollectorVisitor<'a, 'tcx> {
|
2018-03-01 21:00:43 +00:00
|
|
|
|
fn visit_expr(&mut self, ex: &'tcx Expr) {
|
|
|
|
|
match ex.node {
|
2018-03-26 10:32:21 +00:00
|
|
|
|
ExprPath(_) => self.insert_def_id(ex),
|
2018-03-01 21:00:43 +00:00
|
|
|
|
// If there is any fuction/method call… we just stop analysis
|
2018-03-01 22:23:41 +00:00
|
|
|
|
ExprCall(..) | ExprMethodCall(..) => self.skip = true,
|
2018-03-01 21:00:43 +00:00
|
|
|
|
|
|
|
|
|
_ => walk_expr(self, ex),
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2018-03-01 22:23:41 +00:00
|
|
|
|
fn visit_block(&mut self, _b: &'tcx Block) {}
|
|
|
|
|
|
|
|
|
|
fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
|
|
|
|
|
NestedVisitorMap::None
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2018-03-05 21:20:28 +00:00
|
|
|
|
struct MutVarsDelegate {
|
2018-03-26 18:37:34 +00:00
|
|
|
|
used_mutably: HashMap<NodeId, bool>,
|
2018-03-25 15:23:31 +00:00
|
|
|
|
skip: bool,
|
2018-03-01 22:23:41 +00:00
|
|
|
|
}
|
|
|
|
|
|
2018-03-05 21:20:28 +00:00
|
|
|
|
impl<'tcx> MutVarsDelegate {
|
2018-04-03 14:41:30 +00:00
|
|
|
|
fn update(&mut self, cat: &'tcx Categorization) {
|
2018-03-26 18:37:34 +00:00
|
|
|
|
match *cat {
|
|
|
|
|
Categorization::Local(id) =>
|
|
|
|
|
if let Some(used) = self.used_mutably.get_mut(&id) {
|
|
|
|
|
*used = true;
|
|
|
|
|
},
|
2018-03-26 10:32:21 +00:00
|
|
|
|
Categorization::Upvar(_) => {
|
|
|
|
|
//FIXME: This causes false negatives. We can't get the `NodeId` from
|
|
|
|
|
//`Categorization::Upvar(_)`. So we search for any `Upvar`s in the
|
|
|
|
|
//`while`-body, not just the ones in the condition.
|
|
|
|
|
self.skip = true
|
|
|
|
|
},
|
2018-04-03 14:41:30 +00:00
|
|
|
|
Categorization::Deref(ref cmt, _) | Categorization::Interior(ref cmt, _) => self.update(&cmt.cat),
|
2018-03-26 18:37:34 +00:00
|
|
|
|
_ => {}
|
2018-03-01 22:23:41 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
2018-03-05 21:20:28 +00:00
|
|
|
|
}
|
|
|
|
|
|
2018-03-01 22:23:41 +00:00
|
|
|
|
|
2018-03-05 21:20:28 +00:00
|
|
|
|
impl<'tcx> Delegate<'tcx> for MutVarsDelegate {
|
2018-05-06 12:05:41 +00:00
|
|
|
|
fn consume(&mut self, _: NodeId, _: Span, _: &cmt_<'tcx>, _: ConsumeMode) {}
|
2018-03-05 21:20:28 +00:00
|
|
|
|
|
2018-05-06 12:05:41 +00:00
|
|
|
|
fn matched_pat(&mut self, _: &Pat, _: &cmt_<'tcx>, _: MatchMode) {}
|
2018-03-05 21:20:28 +00:00
|
|
|
|
|
2018-05-06 12:05:41 +00:00
|
|
|
|
fn consume_pat(&mut self, _: &Pat, _: &cmt_<'tcx>, _: ConsumeMode) {}
|
2018-03-05 21:20:28 +00:00
|
|
|
|
|
2018-05-06 12:05:41 +00:00
|
|
|
|
fn borrow(&mut self, _: NodeId, _: Span, cmt: &cmt_<'tcx>, _: ty::Region, bk: ty::BorrowKind, _: LoanCause) {
|
2018-03-05 21:20:28 +00:00
|
|
|
|
if let ty::BorrowKind::MutBorrow = bk {
|
2018-04-03 14:41:30 +00:00
|
|
|
|
self.update(&cmt.cat)
|
2018-03-01 22:23:41 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2018-05-06 12:05:41 +00:00
|
|
|
|
fn mutate(&mut self, _: NodeId, _: Span, cmt: &cmt_<'tcx>, _: MutateMode) {
|
2018-04-03 14:41:30 +00:00
|
|
|
|
self.update(&cmt.cat)
|
2018-03-01 21:00:43 +00:00
|
|
|
|
}
|
2018-03-05 21:20:28 +00:00
|
|
|
|
|
|
|
|
|
fn decl_without_init(&mut self, _: NodeId, _: Span) {}
|
2018-03-13 10:38:11 +00:00
|
|
|
|
}
|