@@ -453,6 +453,31 @@ declare_clippy_lint! {
453453 "the same item is pushed inside of a for loop"
454454}
455455
456+ declare_clippy_lint ! {
457+ /// **What it does:** Checks whether a for loop has a single element.
458+ ///
459+ /// **Why is this bad?** There is no reason to have a loop of a
460+ /// single element.
461+ /// **Known problems:** None
462+ ///
463+ /// **Example:**
464+ /// ```rust
465+ /// let item1 = 2;
466+ /// for item in &[item1] {
467+ /// println!("{}", item);
468+ /// }
469+ /// ```
470+ /// could be written as
471+ /// ```rust
472+ /// let item1 = 2;
473+ /// let item = &item1;
474+ /// println!("{}", item);
475+ /// ```
476+ pub SINGLE_ELEMENT_LOOP ,
477+ style,
478+ "there is no reason to have a single element loop"
479+ }
480+
456481declare_lint_pass ! ( Loops => [
457482 MANUAL_MEMCPY ,
458483 NEEDLESS_RANGE_LOOP ,
@@ -470,6 +495,7 @@ declare_lint_pass!(Loops => [
470495 MUT_RANGE_BOUND ,
471496 WHILE_IMMUTABLE_CONDITION ,
472497 SAME_ITEM_PUSH ,
498+ SINGLE_ELEMENT_LOOP ,
473499] ) ;
474500
475501impl < ' tcx > LateLintPass < ' tcx > for Loops {
@@ -774,6 +800,7 @@ fn check_for_loop<'tcx>(
774800 check_for_loop_explicit_counter ( cx, pat, arg, body, expr) ;
775801 check_for_loop_over_map_kv ( cx, pat, arg, body, expr) ;
776802 check_for_mut_range_bound ( cx, arg, body) ;
803+ check_for_single_element_loop ( cx, pat, arg, body, expr) ;
777804 detect_manual_memcpy ( cx, pat, arg, body, expr) ;
778805 detect_same_item_push ( cx, pat, arg, body, expr) ;
779806}
@@ -1684,6 +1711,27 @@ fn check_for_loop_over_map_kv<'tcx>(
16841711 }
16851712}
16861713
1714+ fn check_for_single_element_loop < ' tcx > (
1715+ cx : & LateContext < ' tcx > ,
1716+ _: & ' tcx Pat < ' _ > ,
1717+ arg : & ' tcx Expr < ' _ > ,
1718+ _: & ' tcx Expr < ' _ > ,
1719+ _: & ' tcx Expr < ' _ > ,
1720+ ) {
1721+ if let ExprKind :: AddrOf ( BorrowKind :: Ref , _, ref expr) = arg. kind {
1722+ if let ExprKind :: Array ( ref expr_list) = expr. kind {
1723+ if expr_list. len ( ) == 1 {
1724+ span_lint (
1725+ cx,
1726+ SINGLE_ELEMENT_LOOP ,
1727+ expr. span ,
1728+ "Do not iterate over a single element array." ,
1729+ ) ;
1730+ }
1731+ }
1732+ }
1733+ }
1734+
16871735struct MutatePairDelegate < ' a , ' tcx > {
16881736 cx : & ' a LateContext < ' tcx > ,
16891737 hir_id_low : Option < HirId > ,
0 commit comments