1 use crate::lint::{LateContext, LateLintPass, LintArray, LintContext, LintPass};
3 lint::FutureIncompatibleInfo,
7 adjustment::{Adjust, Adjustment},
11 errors::Applicability,
19 "detects calling `into_iter` on arrays",
20 @future_incompatible = FutureIncompatibleInfo {
21 reference: "issue #66145 <https://github.com/rust-lang/rust/issues/66145>",
27 /// Checks for instances of calling `into_iter` on arrays.
28 ArrayIntoIter => [ARRAY_INTO_ITER]
31 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ArrayIntoIter {
32 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr) {
33 // We only care about method call expressions.
34 if let hir::ExprKind::MethodCall(call, span, args) = &expr.kind {
35 if call.ident.name != sym::into_iter {
39 // Check if the method call actually calls the libcore
40 // `IntoIterator::into_iter`.
41 let def_id = cx.tables.type_dependent_def_id(expr.hir_id).unwrap();
42 match cx.tcx.trait_of_item(def_id) {
43 Some(trait_id) if cx.tcx.is_diagnostic_item(sym::IntoIterator, trait_id) => {},
47 // As this is a method call expression, we have at least one
49 let receiver_arg = &args[0];
51 // Test if the original `self` type is an array type.
52 match cx.tables.expr_ty(receiver_arg).kind {
57 // Make sure that the first adjustment is an autoref coercion.
58 match cx.tables.expr_adjustments(receiver_arg).get(0) {
59 Some(Adjustment { kind: Adjust::Borrow(_), .. }) => {}
63 // Emit lint diagnostic.
64 let target = match cx.tables.expr_ty_adjusted(receiver_arg).kind {
65 ty::Ref(_, ty::TyS { kind: ty::Array(..), ..}, _) => "[T; N]",
66 ty::Ref(_, ty::TyS { kind: ty::Slice(..), ..}, _) => "[T]",
68 // We know the original first argument type is an array type,
69 // we know that the first adjustment was an autoref coercion
70 // and we know that `IntoIterator` is the trait involved. The
71 // array cannot be coerced to something other than a reference
72 // to an array or to a slice.
73 _ => bug!("array type coerced to something other than array or slice"),
76 "this method call currently resolves to `<&{} as IntoIterator>::into_iter` (due \
77 to autoref coercions), but that might change in the future when \
78 `IntoIterator` impls for arrays are added.",
81 cx.struct_span_lint(ARRAY_INTO_ITER, *span, &msg)
84 "use `.iter()` instead of `.into_iter()` to avoid ambiguity",
86 Applicability::MachineApplicable,