1 use crate::lint::{LateContext, LateLintPass, LintArray, LintContext, LintPass};
4 lint::FutureIncompatibleInfo,
7 adjustment::{Adjust, Adjustment},
10 use syntax::{errors::Applicability, symbol::sym};
15 "detects calling `into_iter` on arrays",
16 @future_incompatible = FutureIncompatibleInfo {
17 reference: "issue #66145 <https://github.com/rust-lang/rust/issues/66145>",
23 /// Checks for instances of calling `into_iter` on arrays.
24 ArrayIntoIter => [ARRAY_INTO_ITER]
27 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ArrayIntoIter {
28 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr) {
29 // We only care about method call expressions.
30 if let hir::ExprKind::MethodCall(call, span, args) = &expr.kind {
31 if call.ident.name != sym::into_iter {
35 // Check if the method call actually calls the libcore
36 // `IntoIterator::into_iter`.
37 let def_id = cx.tables.type_dependent_def_id(expr.hir_id).unwrap();
38 match cx.tcx.trait_of_item(def_id) {
39 Some(trait_id) if cx.tcx.is_diagnostic_item(sym::IntoIterator, trait_id) => {}
43 // As this is a method call expression, we have at least one
45 let receiver_arg = &args[0];
47 // Test if the original `self` type is an array type.
48 match cx.tables.expr_ty(receiver_arg).kind {
53 // Make sure that the first adjustment is an autoref coercion.
54 match cx.tables.expr_adjustments(receiver_arg).get(0) {
55 Some(Adjustment { kind: Adjust::Borrow(_), .. }) => {}
59 // Emit lint diagnostic.
60 let target = match cx.tables.expr_ty_adjusted(receiver_arg).kind {
61 ty::Ref(_, ty::TyS { kind: ty::Array(..), .. }, _) => "[T; N]",
62 ty::Ref(_, ty::TyS { kind: ty::Slice(..), .. }, _) => "[T]",
64 // We know the original first argument type is an array type,
65 // we know that the first adjustment was an autoref coercion
66 // and we know that `IntoIterator` is the trait involved. The
67 // array cannot be coerced to something other than a reference
68 // to an array or to a slice.
69 _ => bug!("array type coerced to something other than array or slice"),
72 "this method call currently resolves to `<&{} as IntoIterator>::into_iter` (due \
73 to autoref coercions), but that might change in the future when \
74 `IntoIterator` impls for arrays are added.",
77 cx.struct_span_lint(ARRAY_INTO_ITER, *span, &msg)
80 "use `.iter()` instead of `.into_iter()` to avoid ambiguity",
82 Applicability::MachineApplicable,