|
| 1 | +use clippy_utils::diagnostics::span_lint_and_then; |
| 2 | +use clippy_utils::higher::ForLoop; |
| 3 | +use clippy_utils::source::snippet_opt; |
| 4 | +use clippy_utils::ty::{get_associated_type, get_iterator_item_ty, implements_trait}; |
| 5 | +use clippy_utils::{fn_def_id, get_parent_expr, path_to_local_id, usage}; |
| 6 | +use rustc_errors::Applicability; |
| 7 | +use rustc_hir::intravisit::{walk_expr, NestedVisitorMap, Visitor}; |
| 8 | +use rustc_hir::{def_id::DefId, BorrowKind, Expr, ExprKind, HirId, LangItem, Mutability, Pat}; |
| 9 | +use rustc_lint::LateContext; |
| 10 | +use rustc_middle::{hir::map::Map, ty}; |
| 11 | +use rustc_span::{sym, Symbol}; |
| 12 | + |
| 13 | +use super::UNNECESSARY_TO_OWNED; |
| 14 | + |
| 15 | +pub fn check(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>, method_name: Symbol, receiver: &'tcx Expr<'tcx>) -> bool { |
| 16 | + if_chain! { |
| 17 | + if let Some(parent) = get_parent_expr(cx, expr); |
| 18 | + if let Some(callee_def_id) = fn_def_id(cx, parent); |
| 19 | + if is_into_iter(cx, callee_def_id); |
| 20 | + then { |
| 21 | + check_for_loop_iter(cx, parent, method_name, receiver) |
| 22 | + } else { |
| 23 | + false |
| 24 | + } |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +/// Checks whether `expr` is an iterator in a `for` loop and, if so, determines whether the |
| 29 | +/// iterated-over items could be iterated over by reference. The reason why `check` above does not |
| 30 | +/// include this code directly is so that it can be called from |
| 31 | +/// `unnecessary_into_owned::check_into_iter_call_arg`. |
| 32 | +pub fn check_for_loop_iter( |
| 33 | + cx: &LateContext<'tcx>, |
| 34 | + expr: &'tcx Expr<'tcx>, |
| 35 | + method_name: Symbol, |
| 36 | + receiver: &'tcx Expr<'tcx>, |
| 37 | +) -> bool { |
| 38 | + if_chain! { |
| 39 | + if let Some(grandparent) = get_parent_expr(cx, expr).and_then(|parent| get_parent_expr(cx, parent)); |
| 40 | + if let Some(ForLoop { pat, body, .. }) = ForLoop::hir(grandparent); |
| 41 | + let (clone_or_copy_needed, addr_of_exprs) = clone_or_copy_needed(cx, pat, body); |
| 42 | + if !clone_or_copy_needed; |
| 43 | + if let Some(receiver_snippet) = snippet_opt(cx, receiver.span); |
| 44 | + then { |
| 45 | + let snippet = if_chain! { |
| 46 | + if let ExprKind::MethodCall(maybe_iter_method_name, _, [collection], _) = receiver.kind; |
| 47 | + if maybe_iter_method_name.ident.name == sym::iter; |
| 48 | + |
| 49 | + if let Some(iterator_trait_id) = cx.tcx.get_diagnostic_item(sym::Iterator); |
| 50 | + let receiver_ty = cx.typeck_results().expr_ty(receiver); |
| 51 | + if implements_trait(cx, receiver_ty, iterator_trait_id, &[]); |
| 52 | + if let Some(iter_item_ty) = get_iterator_item_ty(cx, receiver_ty); |
| 53 | + |
| 54 | + if let Some(into_iterator_trait_id) = cx.tcx.get_diagnostic_item(sym::IntoIterator); |
| 55 | + let collection_ty = cx.typeck_results().expr_ty(collection); |
| 56 | + if implements_trait(cx, collection_ty, into_iterator_trait_id, &[]); |
| 57 | + if let Some(into_iter_item_ty) = get_associated_type(cx, collection_ty, into_iterator_trait_id, "Item"); |
| 58 | + |
| 59 | + if iter_item_ty == into_iter_item_ty; |
| 60 | + if let Some(collection_snippet) = snippet_opt(cx, collection.span); |
| 61 | + then { |
| 62 | + collection_snippet |
| 63 | + } else { |
| 64 | + receiver_snippet |
| 65 | + } |
| 66 | + }; |
| 67 | + span_lint_and_then( |
| 68 | + cx, |
| 69 | + UNNECESSARY_TO_OWNED, |
| 70 | + expr.span, |
| 71 | + &format!("unnecessary use of `{}`", method_name), |
| 72 | + |diag| { |
| 73 | + diag.span_suggestion(expr.span, "use", snippet, Applicability::MachineApplicable); |
| 74 | + for addr_of_expr in addr_of_exprs { |
| 75 | + match addr_of_expr.kind { |
| 76 | + ExprKind::AddrOf(_, _, referent) => { |
| 77 | + let span = addr_of_expr.span.with_hi(referent.span.lo()); |
| 78 | + diag.span_suggestion(span, "remove this `&`", String::new(), Applicability::MachineApplicable); |
| 79 | + } |
| 80 | + _ => unreachable!(), |
| 81 | + } |
| 82 | + } |
| 83 | + } |
| 84 | + ); |
| 85 | + return true; |
| 86 | + } |
| 87 | + } |
| 88 | + false |
| 89 | +} |
| 90 | + |
| 91 | +/// The core logic of `check_for_loop_iter` above, this function wraps a use of |
| 92 | +/// `CloneOrCopyVisitor`. |
| 93 | +fn clone_or_copy_needed( |
| 94 | + cx: &LateContext<'tcx>, |
| 95 | + pat: &Pat<'tcx>, |
| 96 | + body: &'tcx Expr<'tcx>, |
| 97 | +) -> (bool, Vec<&'tcx Expr<'tcx>>) { |
| 98 | + let mut visitor = CloneOrCopyVisitor { |
| 99 | + cx, |
| 100 | + binding_hir_ids: pat_bindings(pat), |
| 101 | + clone_or_copy_needed: false, |
| 102 | + addr_of_exprs: Vec::new(), |
| 103 | + }; |
| 104 | + visitor.visit_expr(body); |
| 105 | + (visitor.clone_or_copy_needed, visitor.addr_of_exprs) |
| 106 | +} |
| 107 | + |
| 108 | +/// Returns a vector of all `HirId`s bound by the pattern. |
| 109 | +fn pat_bindings(pat: &Pat<'_>) -> Vec<HirId> { |
| 110 | + let mut collector = usage::ParamBindingIdCollector { |
| 111 | + binding_hir_ids: Vec::new(), |
| 112 | + }; |
| 113 | + collector.visit_pat(pat); |
| 114 | + collector.binding_hir_ids |
| 115 | +} |
| 116 | + |
| 117 | +/// `clone_or_copy_needed` will be false when `CloneOrCopyVisitor` is done visiting if the only |
| 118 | +/// operations performed on `binding_hir_ids` are: |
| 119 | +/// * to take non-mutable references to them |
| 120 | +/// * to use them as non-mutable `&self` in method calls |
| 121 | +/// If any of `binding_hir_ids` is used in any other way, then `clone_or_copy_needed` will be true |
| 122 | +/// when `CloneOrCopyVisitor` is done visiting. |
| 123 | +struct CloneOrCopyVisitor<'cx, 'tcx> { |
| 124 | + cx: &'cx LateContext<'tcx>, |
| 125 | + binding_hir_ids: Vec<HirId>, |
| 126 | + clone_or_copy_needed: bool, |
| 127 | + addr_of_exprs: Vec<&'tcx Expr<'tcx>>, |
| 128 | +} |
| 129 | + |
| 130 | +impl<'cx, 'tcx> Visitor<'tcx> for CloneOrCopyVisitor<'cx, 'tcx> { |
| 131 | + type Map = Map<'tcx>; |
| 132 | + |
| 133 | + fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> { |
| 134 | + NestedVisitorMap::OnlyBodies(self.cx.tcx.hir()) |
| 135 | + } |
| 136 | + |
| 137 | + fn visit_expr(&mut self, expr: &'tcx Expr<'tcx>) { |
| 138 | + walk_expr(self, expr); |
| 139 | + if self.is_binding(expr) { |
| 140 | + if let Some(parent) = get_parent_expr(self.cx, expr) { |
| 141 | + match parent.kind { |
| 142 | + ExprKind::AddrOf(BorrowKind::Ref, Mutability::Not, _) => { |
| 143 | + self.addr_of_exprs.push(parent); |
| 144 | + return; |
| 145 | + }, |
| 146 | + ExprKind::MethodCall(_, _, args, _) => { |
| 147 | + if_chain! { |
| 148 | + if args.iter().skip(1).all(|arg| !self.is_binding(arg)); |
| 149 | + if let Some(method_def_id) = self.cx.typeck_results().type_dependent_def_id(parent.hir_id); |
| 150 | + let method_ty = self.cx.tcx.type_of(method_def_id); |
| 151 | + let self_ty = method_ty.fn_sig(self.cx.tcx).input(0).skip_binder(); |
| 152 | + if matches!(self_ty.kind(), ty::Ref(_, _, Mutability::Not)); |
| 153 | + then { |
| 154 | + return; |
| 155 | + } |
| 156 | + } |
| 157 | + }, |
| 158 | + _ => {}, |
| 159 | + } |
| 160 | + } |
| 161 | + self.clone_or_copy_needed = true; |
| 162 | + } |
| 163 | + } |
| 164 | +} |
| 165 | + |
| 166 | +impl<'cx, 'tcx> CloneOrCopyVisitor<'cx, 'tcx> { |
| 167 | + fn is_binding(&self, expr: &Expr<'tcx>) -> bool { |
| 168 | + self.binding_hir_ids |
| 169 | + .iter() |
| 170 | + .any(|hir_id| path_to_local_id(expr, *hir_id)) |
| 171 | + } |
| 172 | +} |
| 173 | + |
| 174 | +/// Returns true if the named method is `IntoIterator::into_iter`. |
| 175 | +pub fn is_into_iter(cx: &LateContext<'_>, callee_def_id: DefId) -> bool { |
| 176 | + cx.tcx.lang_items().require(LangItem::IntoIterIntoIter) == Ok(callee_def_id) |
| 177 | +} |
0 commit comments