]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_lint/src/array_into_iter.rs
ea5975ed4f0b3deab02f38ea118a8cff10315bf2
[rust.git] / compiler / rustc_lint / src / array_into_iter.rs
1 #![deny(rustc::untranslatable_diagnostic)]
2 #![deny(rustc::diagnostic_outside_of_impl)]
3 use crate::lints::{ArrayIntoIterDiag, ArrayIntoIterDiagSub};
4 use crate::{LateContext, LateLintPass, LintContext};
5 use rustc_hir as hir;
6 use rustc_middle::ty;
7 use rustc_middle::ty::adjustment::{Adjust, Adjustment};
8 use rustc_session::lint::FutureIncompatibilityReason;
9 use rustc_span::edition::Edition;
10 use rustc_span::symbol::sym;
11 use rustc_span::Span;
12
13 declare_lint! {
14     /// The `array_into_iter` lint detects calling `into_iter` on arrays.
15     ///
16     /// ### Example
17     ///
18     /// ```rust,edition2018
19     /// # #![allow(unused)]
20     /// [1, 2, 3].into_iter().for_each(|n| { *n; });
21     /// ```
22     ///
23     /// {{produces}}
24     ///
25     /// ### Explanation
26     ///
27     /// Since Rust 1.53, arrays implement `IntoIterator`. However, to avoid
28     /// breakage, `array.into_iter()` in Rust 2015 and 2018 code will still
29     /// behave as `(&array).into_iter()`, returning an iterator over
30     /// references, just like in Rust 1.52 and earlier.
31     /// This only applies to the method call syntax `array.into_iter()`, not to
32     /// any other syntax such as `for _ in array` or `IntoIterator::into_iter(array)`.
33     pub ARRAY_INTO_ITER,
34     Warn,
35     "detects calling `into_iter` on arrays in Rust 2015 and 2018",
36     @future_incompatible = FutureIncompatibleInfo {
37         reference: "<https://doc.rust-lang.org/nightly/edition-guide/rust-2021/IntoIterator-for-arrays.html>",
38         reason: FutureIncompatibilityReason::EditionSemanticsChange(Edition::Edition2021),
39     };
40 }
41
42 #[derive(Copy, Clone, Default)]
43 pub struct ArrayIntoIter {
44     for_expr_span: Span,
45 }
46
47 impl_lint_pass!(ArrayIntoIter => [ARRAY_INTO_ITER]);
48
49 impl<'tcx> LateLintPass<'tcx> for ArrayIntoIter {
50     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'tcx>) {
51         // Save the span of expressions in `for _ in expr` syntax,
52         // so we can give a better suggestion for those later.
53         if let hir::ExprKind::Match(arg, [_], hir::MatchSource::ForLoopDesugar) = &expr.kind {
54             if let hir::ExprKind::Call(path, [arg]) = &arg.kind {
55                 if let hir::ExprKind::Path(hir::QPath::LangItem(
56                     hir::LangItem::IntoIterIntoIter,
57                     ..,
58                 )) = &path.kind
59                 {
60                     self.for_expr_span = arg.span;
61                 }
62             }
63         }
64
65         // We only care about method call expressions.
66         if let hir::ExprKind::MethodCall(call, receiver_arg, ..) = &expr.kind {
67             if call.ident.name != sym::into_iter {
68                 return;
69             }
70
71             // Check if the method call actually calls the libcore
72             // `IntoIterator::into_iter`.
73             let def_id = cx.typeck_results().type_dependent_def_id(expr.hir_id).unwrap();
74             match cx.tcx.trait_of_item(def_id) {
75                 Some(trait_id) if cx.tcx.is_diagnostic_item(sym::IntoIterator, trait_id) => {}
76                 _ => return,
77             };
78
79             // As this is a method call expression, we have at least one argument.
80             let receiver_ty = cx.typeck_results().expr_ty(receiver_arg);
81             let adjustments = cx.typeck_results().expr_adjustments(receiver_arg);
82
83             let Some(Adjustment { kind: Adjust::Borrow(_), target }) = adjustments.last() else {
84                 return
85             };
86
87             let types =
88                 std::iter::once(receiver_ty).chain(adjustments.iter().map(|adj| adj.target));
89
90             let mut found_array = false;
91
92             for ty in types {
93                 match ty.kind() {
94                     // If we run into a &[T; N] or &[T] first, there's nothing to warn about.
95                     // It'll resolve to the reference version.
96                     ty::Ref(_, inner_ty, _) if inner_ty.is_array() => return,
97                     ty::Ref(_, inner_ty, _) if matches!(inner_ty.kind(), ty::Slice(..)) => return,
98                     // Found an actual array type without matching a &[T; N] first.
99                     // This is the problematic case.
100                     ty::Array(..) => {
101                         found_array = true;
102                         break;
103                     }
104                     _ => {}
105                 }
106             }
107
108             if !found_array {
109                 return;
110             }
111
112             // Emit lint diagnostic.
113             let target = match *target.kind() {
114                 ty::Ref(_, inner_ty, _) if inner_ty.is_array() => "[T; N]",
115                 ty::Ref(_, inner_ty, _) if matches!(inner_ty.kind(), ty::Slice(..)) => "[T]",
116                 // We know the original first argument type is an array type,
117                 // we know that the first adjustment was an autoref coercion
118                 // and we know that `IntoIterator` is the trait involved. The
119                 // array cannot be coerced to something other than a reference
120                 // to an array or to a slice.
121                 _ => bug!("array type coerced to something other than array or slice"),
122             };
123             let sub = if self.for_expr_span == expr.span {
124                 Some(ArrayIntoIterDiagSub::RemoveIntoIter {
125                     span: receiver_arg.span.shrink_to_hi().to(expr.span.shrink_to_hi()),
126                 })
127             } else if receiver_ty.is_array() {
128                 Some(ArrayIntoIterDiagSub::UseExplicitIntoIter {
129                     start_span: expr.span.shrink_to_lo(),
130                     end_span: receiver_arg.span.shrink_to_hi().to(expr.span.shrink_to_hi()),
131                 })
132             } else {
133                 None
134             };
135             cx.emit_spanned_lint(
136                 ARRAY_INTO_ITER,
137                 call.ident.span,
138                 ArrayIntoIterDiag { target, suggestion: call.ident.span, sub },
139             );
140         }
141     }
142 }