]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_lint/src/array_into_iter.rs
Auto merge of #86492 - hyd-dev:no-mangle-method, r=petrochenkov
[rust.git] / compiler / rustc_lint / src / array_into_iter.rs
1 use crate::{LateContext, LateLintPass, LintContext};
2 use rustc_errors::Applicability;
3 use rustc_hir as hir;
4 use rustc_middle::ty;
5 use rustc_middle::ty::adjustment::{Adjust, Adjustment};
6 use rustc_session::lint::FutureIncompatibilityReason;
7 use rustc_span::edition::Edition;
8 use rustc_span::symbol::sym;
9 use rustc_span::Span;
10
11 declare_lint! {
12     /// The `array_into_iter` lint detects calling `into_iter` on arrays.
13     ///
14     /// ### Example
15     ///
16     /// ```rust
17     /// # #![allow(unused)]
18     /// [1, 2, 3].into_iter().for_each(|n| { *n; });
19     /// ```
20     ///
21     /// {{produces}}
22     ///
23     /// ### Explanation
24     ///
25     /// Since Rust 1.53, arrays implement `IntoIterator`. However, to avoid
26     /// breakage, `array.into_iter()` in Rust 2015 and 2018 code will still
27     /// behave as `(&array).into_iter()`, returning an iterator over
28     /// references, just like in Rust 1.52 and earlier.
29     /// This only applies to the method call syntax `array.into_iter()`, not to
30     /// any other syntax such as `for _ in array` or `IntoIterator::into_iter(array)`.
31     pub ARRAY_INTO_ITER,
32     Warn,
33     "detects calling `into_iter` on arrays in Rust 2015 and 2018",
34     @future_incompatible = FutureIncompatibleInfo {
35         reference: "<https://doc.rust-lang.org/nightly/edition-guide/rust-2021/IntoIterator-for-arrays.html>",
36         reason: FutureIncompatibilityReason::EditionSemanticsChange(Edition::Edition2021),
37     };
38 }
39
40 #[derive(Copy, Clone, Default)]
41 pub struct ArrayIntoIter {
42     for_expr_span: Span,
43 }
44
45 impl_lint_pass!(ArrayIntoIter => [ARRAY_INTO_ITER]);
46
47 impl<'tcx> LateLintPass<'tcx> for ArrayIntoIter {
48     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'tcx>) {
49         // Save the span of expressions in `for _ in expr` syntax,
50         // so we can give a better suggestion for those later.
51         if let hir::ExprKind::Match(arg, [_], hir::MatchSource::ForLoopDesugar) = &expr.kind {
52             if let hir::ExprKind::Call(path, [arg]) = &arg.kind {
53                 if let hir::ExprKind::Path(hir::QPath::LangItem(
54                     hir::LangItem::IntoIterIntoIter,
55                     _,
56                 )) = &path.kind
57                 {
58                     self.for_expr_span = arg.span;
59                 }
60             }
61         }
62
63         // We only care about method call expressions.
64         if let hir::ExprKind::MethodCall(call, span, args, _) = &expr.kind {
65             if call.ident.name != sym::into_iter {
66                 return;
67             }
68
69             // Check if the method call actually calls the libcore
70             // `IntoIterator::into_iter`.
71             let def_id = cx.typeck_results().type_dependent_def_id(expr.hir_id).unwrap();
72             match cx.tcx.trait_of_item(def_id) {
73                 Some(trait_id) if cx.tcx.is_diagnostic_item(sym::IntoIterator, trait_id) => {}
74                 _ => return,
75             };
76
77             // As this is a method call expression, we have at least one
78             // argument.
79             let receiver_arg = &args[0];
80
81             // Peel all `Box<_>` layers. We have to special case `Box` here as
82             // `Box` is the only thing that values can be moved out of via
83             // method call. `Box::new([1]).into_iter()` should trigger this
84             // lint.
85             let mut recv_ty = cx.typeck_results().expr_ty(receiver_arg);
86             let mut num_box_derefs = 0;
87             while recv_ty.is_box() {
88                 num_box_derefs += 1;
89                 recv_ty = recv_ty.boxed_ty();
90             }
91
92             // Make sure we found an array after peeling the boxes.
93             if !matches!(recv_ty.kind(), ty::Array(..)) {
94                 return;
95             }
96
97             // Make sure that there is an autoref coercion at the expected
98             // position. The first `num_box_derefs` adjustments are the derefs
99             // of the box.
100             match cx.typeck_results().expr_adjustments(receiver_arg).get(num_box_derefs) {
101                 Some(Adjustment { kind: Adjust::Borrow(_), .. }) => {}
102                 _ => return,
103             }
104
105             // Emit lint diagnostic.
106             let target = match *cx.typeck_results().expr_ty_adjusted(receiver_arg).kind() {
107                 ty::Ref(_, inner_ty, _) if inner_ty.is_array() => "[T; N]",
108                 ty::Ref(_, inner_ty, _) if matches!(inner_ty.kind(), ty::Slice(..)) => "[T]",
109
110                 // We know the original first argument type is an array type,
111                 // we know that the first adjustment was an autoref coercion
112                 // and we know that `IntoIterator` is the trait involved. The
113                 // array cannot be coerced to something other than a reference
114                 // to an array or to a slice.
115                 _ => bug!("array type coerced to something other than array or slice"),
116             };
117             cx.struct_span_lint(ARRAY_INTO_ITER, *span, |lint| {
118                 let mut diag = lint.build(&format!(
119                     "this method call resolves to `<&{} as IntoIterator>::into_iter` \
120                     (due to backwards compatibility), \
121                     but will resolve to <{} as IntoIterator>::into_iter in Rust 2021.",
122                     target, target,
123                 ));
124                 diag.span_suggestion(
125                     call.ident.span,
126                     "use `.iter()` instead of `.into_iter()` to avoid ambiguity",
127                     "iter".into(),
128                     Applicability::MachineApplicable,
129                 );
130                 if self.for_expr_span == expr.span {
131                     let expr_span = expr.span.ctxt().outer_expn_data().call_site;
132                     diag.span_suggestion(
133                         receiver_arg.span.shrink_to_hi().to(expr_span.shrink_to_hi()),
134                         "or remove `.into_iter()` to iterate by value",
135                         String::new(),
136                         Applicability::MaybeIncorrect,
137                     );
138                 } else {
139                     diag.multipart_suggestion(
140                         "or use `IntoIterator::into_iter(..)` instead of `.into_iter()` to explicitly iterate by value",
141                         vec![
142                             (expr.span.shrink_to_lo(), "IntoIterator::into_iter(".into()),
143                             (receiver_arg.span.shrink_to_hi().to(expr.span.shrink_to_hi()), ")".into()),
144                         ],
145                         Applicability::MaybeIncorrect,
146                     );
147                 }
148                 diag.emit();
149             })
150         }
151     }
152 }