]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_lint/src/array_into_iter.rs
Merge commit 'b40ea209e7f14c8193ddfc98143967b6a2f4f5c9' into clippyup
[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::FutureBreakage;
7 use rustc_span::symbol::sym;
8
9 declare_lint! {
10     /// The `array_into_iter` lint detects calling `into_iter` on arrays.
11     ///
12     /// ### Example
13     ///
14     /// ```rust
15     /// # #![allow(unused)]
16     /// [1, 2, 3].into_iter().for_each(|n| { *n; });
17     /// ```
18     ///
19     /// {{produces}}
20     ///
21     /// ### Explanation
22     ///
23     /// In the future, it is planned to add an `IntoIter` implementation for
24     /// arrays such that it will iterate over *values* of the array instead of
25     /// references. Due to how method resolution works, this will change
26     /// existing code that uses `into_iter` on arrays. The solution to avoid
27     /// this warning is to use `iter()` instead of `into_iter()`.
28     ///
29     /// This is a [future-incompatible] lint to transition this to a hard error
30     /// in the future. See [issue #66145] for more details and a more thorough
31     /// description of the lint.
32     ///
33     /// [issue #66145]: https://github.com/rust-lang/rust/issues/66145
34     /// [future-incompatible]: ../index.md#future-incompatible-lints
35     pub ARRAY_INTO_ITER,
36     Warn,
37     "detects calling `into_iter` on arrays",
38     @future_incompatible = FutureIncompatibleInfo {
39         reference: "issue #66145 <https://github.com/rust-lang/rust/issues/66145>",
40         edition: None,
41         future_breakage: Some(FutureBreakage {
42             date: None
43         })
44     };
45 }
46
47 declare_lint_pass!(
48     /// Checks for instances of calling `into_iter` on arrays.
49     ArrayIntoIter => [ARRAY_INTO_ITER]
50 );
51
52 impl<'tcx> LateLintPass<'tcx> for ArrayIntoIter {
53     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'tcx>) {
54         // We only care about method call expressions.
55         if let hir::ExprKind::MethodCall(call, span, args, _) = &expr.kind {
56             if call.ident.name != sym::into_iter {
57                 return;
58             }
59
60             // Check if the method call actually calls the libcore
61             // `IntoIterator::into_iter`.
62             let def_id = cx.typeck_results().type_dependent_def_id(expr.hir_id).unwrap();
63             match cx.tcx.trait_of_item(def_id) {
64                 Some(trait_id) if cx.tcx.is_diagnostic_item(sym::IntoIterator, trait_id) => {}
65                 _ => return,
66             };
67
68             // As this is a method call expression, we have at least one
69             // argument.
70             let receiver_arg = &args[0];
71
72             // Peel all `Box<_>` layers. We have to special case `Box` here as
73             // `Box` is the only thing that values can be moved out of via
74             // method call. `Box::new([1]).into_iter()` should trigger this
75             // lint.
76             let mut recv_ty = cx.typeck_results().expr_ty(receiver_arg);
77             let mut num_box_derefs = 0;
78             while recv_ty.is_box() {
79                 num_box_derefs += 1;
80                 recv_ty = recv_ty.boxed_ty();
81             }
82
83             // Make sure we found an array after peeling the boxes.
84             if !matches!(recv_ty.kind(), ty::Array(..)) {
85                 return;
86             }
87
88             // Make sure that there is an autoref coercion at the expected
89             // position. The first `num_box_derefs` adjustments are the derefs
90             // of the box.
91             match cx.typeck_results().expr_adjustments(receiver_arg).get(num_box_derefs) {
92                 Some(Adjustment { kind: Adjust::Borrow(_), .. }) => {}
93                 _ => return,
94             }
95
96             // Emit lint diagnostic.
97             let target = match *cx.typeck_results().expr_ty_adjusted(receiver_arg).kind() {
98                 ty::Ref(_, inner_ty, _) if inner_ty.is_array() => "[T; N]",
99                 ty::Ref(_, inner_ty, _) if matches!(inner_ty.kind(), ty::Slice(..)) => "[T]",
100
101                 // We know the original first argument type is an array type,
102                 // we know that the first adjustment was an autoref coercion
103                 // and we know that `IntoIterator` is the trait involved. The
104                 // array cannot be coerced to something other than a reference
105                 // to an array or to a slice.
106                 _ => bug!("array type coerced to something other than array or slice"),
107             };
108             cx.struct_span_lint(ARRAY_INTO_ITER, *span, |lint| {
109                 lint.build(&format!(
110                 "this method call currently resolves to `<&{} as IntoIterator>::into_iter` (due \
111                     to autoref coercions), but that might change in the future when \
112                     `IntoIterator` impls for arrays are added.",
113                 target,
114                 ))
115                 .span_suggestion(
116                     call.ident.span,
117                     "use `.iter()` instead of `.into_iter()` to avoid ambiguity",
118                     "iter".into(),
119                     Applicability::MachineApplicable,
120                 )
121                 .emit();
122             })
123         }
124     }
125 }