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