|
| 1 | +use clippy_utils::diagnostics::span_lint_and_then; |
| 2 | +use clippy_utils::get_parent_as_impl; |
| 3 | +use clippy_utils::ty::{implements_trait, make_normalized_projection}; |
| 4 | +use rustc_errors::Applicability; |
| 5 | +use rustc_hir::{FnRetTy, ImplItemKind, ImplicitSelfKind, Mutability, QPath, TyKind}; |
| 6 | +use rustc_hir_analysis::hir_ty_to_ty; |
| 7 | +use rustc_lint::{LateContext, LateLintPass}; |
| 8 | +use rustc_middle::ty::print::with_forced_trimmed_paths; |
| 9 | +use rustc_middle::ty::{self}; |
| 10 | +use rustc_session::{declare_lint_pass, declare_tool_lint}; |
| 11 | +use rustc_span::sym; |
| 12 | + |
| 13 | +declare_clippy_lint! { |
| 14 | + /// ### What it does |
| 15 | + /// Looks for `iter` and `iter_mut` methods without an associated `IntoIterator for (&|&mut) Type` implementation. |
| 16 | + /// |
| 17 | + /// ### Why is this bad? |
| 18 | + /// It's not bad, but having them is idiomatic and allows the type to be used in for loops directly |
| 19 | + /// (`for val in &iter {}`), without having to first call `iter()` or `iter_mut()`. |
| 20 | + /// |
| 21 | + /// ### Example |
| 22 | + /// ```rust |
| 23 | + /// struct MySlice<'a>(&'a [u8]); |
| 24 | + /// impl<'a> MySlice<'a> { |
| 25 | + /// pub fn iter(&self) -> std::slice::Iter<'a, u8> { |
| 26 | + /// self.0.iter() |
| 27 | + /// } |
| 28 | + /// } |
| 29 | + /// ``` |
| 30 | + /// Use instead: |
| 31 | + /// ```rust |
| 32 | + /// struct MySlice<'a>(&'a [u8]); |
| 33 | + /// impl<'a> MySlice<'a> { |
| 34 | + /// pub fn iter(&self) -> std::slice::Iter<'a, u8> { |
| 35 | + /// self.0.iter() |
| 36 | + /// } |
| 37 | + /// } |
| 38 | + /// impl<'a> IntoIterator for &MySlice<'a> { |
| 39 | + /// type Item = &'a u8; |
| 40 | + /// type IntoIter = std::slice::Iter<'a, u8>; |
| 41 | + /// fn into_iter(self) -> Self::IntoIter { |
| 42 | + /// self.iter() |
| 43 | + /// } |
| 44 | + /// } |
| 45 | + /// ``` |
| 46 | + #[clippy::version = "1.74.0"] |
| 47 | + pub ITER_WITHOUT_INTO_ITER, |
| 48 | + pedantic, |
| 49 | + "implementing `iter(_mut)` without an associated `IntoIterator for (&|&mut) Type` impl" |
| 50 | +} |
| 51 | +declare_lint_pass!(IterWithoutIntoIter => [ITER_WITHOUT_INTO_ITER]); |
| 52 | + |
| 53 | +/// Checks if a given type is nameable in a trait (impl). |
| 54 | +/// RPIT is stable, but impl Trait in traits is not (yet), so when we have |
| 55 | +/// a function such as `fn iter(&self) -> impl IntoIterator`, we can't |
| 56 | +/// suggest `type IntoIter = impl IntoIterator`. |
| 57 | +fn is_nameable_in_impl_trait(ty: &rustc_hir::Ty<'_>) -> bool { |
| 58 | + !matches!(ty.kind, TyKind::OpaqueDef(..)) |
| 59 | +} |
| 60 | + |
| 61 | +fn check_for_mutability(cx: &LateContext<'_>, item: &rustc_hir::ImplItem<'_>, expected_mtbl: Mutability) { |
| 62 | + let (borrow_prefix, name, expected_implicit_self) = match expected_mtbl { |
| 63 | + Mutability::Not => ("&", "iter", ImplicitSelfKind::ImmRef), |
| 64 | + Mutability::Mut => ("&mut ", "iter_mut", ImplicitSelfKind::MutRef), |
| 65 | + }; |
| 66 | + |
| 67 | + if let ImplItemKind::Fn(sig, _) = item.kind |
| 68 | + && let FnRetTy::Return(ret) = sig.decl.output |
| 69 | + && is_nameable_in_impl_trait(ret) |
| 70 | + && cx.tcx.generics_of(item.owner_id.def_id).params.is_empty() |
| 71 | + && sig.decl.implicit_self == expected_implicit_self |
| 72 | + && sig.decl.inputs.len() == 1 |
| 73 | + && let Some(imp) = get_parent_as_impl(cx.tcx, item.hir_id()) |
| 74 | + && imp.of_trait.is_none() |
| 75 | + && let TyKind::Path(QPath::Resolved(_, path)) = imp.self_ty.kind |
| 76 | + && let Some(ty_did) = path.res.opt_def_id() |
| 77 | + && let middle_ty = cx.tcx.type_of(ty_did).skip_binder() |
| 78 | + && let ref_ty = cx.tcx.mk_ty_from_kind(ty::Ref(cx.tcx.lifetimes.re_erased, middle_ty, expected_mtbl)) |
| 79 | + && let Some(into_iter_did) = cx.tcx.get_diagnostic_item(sym::IntoIterator) |
| 80 | + && let bound_vars = cx.tcx.late_bound_vars(item.hir_id()) |
| 81 | + // We need to erase late bounds regions so that `-> Iter<'_, T>` works |
| 82 | + && let ret_middle_ty = cx.tcx.erase_late_bound_regions( |
| 83 | + ty::Binder::bind_with_vars(hir_ty_to_ty(cx.tcx, ret), bound_vars) |
| 84 | + ) |
| 85 | + // Order is important here, we need to check that the `fn iter` return type actually implements `IntoIterator` |
| 86 | + // *before* normalizing `<_ as IntoIterator>::Item` (otherwise make_normalized_projection ICEs) |
| 87 | + && implements_trait(cx, ret_middle_ty, into_iter_did, &[]) |
| 88 | + && let Some(ret_iter_ty) = make_normalized_projection( |
| 89 | + cx.tcx, |
| 90 | + cx.param_env, |
| 91 | + into_iter_did, |
| 92 | + sym!(Item), |
| 93 | + [ret_middle_ty] |
| 94 | + ) |
| 95 | + // Only lint if the `IntoIterator` impl doesn't actually exist |
| 96 | + && !implements_trait(cx, ref_ty, into_iter_did, &[]) |
| 97 | + { |
| 98 | + let (self_ty_snippet, into_iter_snippet) = with_forced_trimmed_paths!(( |
| 99 | + format!("{borrow_prefix}{}", cx.tcx.def_path_str(ty_did)), |
| 100 | + cx.tcx.def_path_str(into_iter_did) |
| 101 | + )); |
| 102 | + |
| 103 | + span_lint_and_then( |
| 104 | + cx, |
| 105 | + ITER_WITHOUT_INTO_ITER, |
| 106 | + item.span, |
| 107 | + &format!("`{name}` method without an `IntoIterator` impl for `{self_ty_snippet}`"), |
| 108 | + |diag| { |
| 109 | + // Get the lower span of the `impl` block, and insert the suggestion right before it: |
| 110 | + // impl X { |
| 111 | + // ^ fn iter(&self) -> impl IntoIterator { ... } |
| 112 | + // } |
| 113 | + let span_behind_impl = cx.tcx |
| 114 | + .def_span(cx.tcx.hir().parent_id(item.hir_id()).owner.def_id) |
| 115 | + .shrink_to_lo(); |
| 116 | + |
| 117 | + let sugg = format!( |
| 118 | +" |
| 119 | +impl {into_iter_snippet} for {self_ty_snippet} {{ |
| 120 | + type IntoIter = {ret_middle_ty}; |
| 121 | + type Iter = {ret_iter_ty}; |
| 122 | + fn into_iter() -> Self::IntoIter {{ |
| 123 | + self.iter() |
| 124 | + }} |
| 125 | +}} |
| 126 | +" |
| 127 | + ); |
| 128 | + |
| 129 | + diag.span_suggestion_verbose( |
| 130 | + span_behind_impl, |
| 131 | + format!("consider implementing `IntoIterator` for `{self_ty_snippet}`"), |
| 132 | + sugg, |
| 133 | + // Suggestion is on a best effort basis, might need some adjustments by the user |
| 134 | + // such as adding some lifetimes in the associated types, or importing types. |
| 135 | + Applicability::Unspecified, |
| 136 | + ); |
| 137 | + }); |
| 138 | + } |
| 139 | +} |
| 140 | + |
| 141 | +impl LateLintPass<'_> for IterWithoutIntoIter { |
| 142 | + fn check_impl_item(&mut self, cx: &LateContext<'_>, item: &rustc_hir::ImplItem<'_>) { |
| 143 | + match item.ident.name { |
| 144 | + sym::iter => check_for_mutability(cx, item, Mutability::Not), |
| 145 | + sym::iter_mut => check_for_mutability(cx, item, Mutability::Mut), |
| 146 | + _ => {}, |
| 147 | + }; |
| 148 | + } |
| 149 | +} |
0 commit comments