1 //! Checks for usage of `&Vec[_]` and `&String`.
3 use crate::utils::ptr::get_spans;
5 is_type_diagnostic_item, match_qpath, match_type, paths, snippet_opt, span_lint, span_lint_and_sugg,
6 span_lint_and_then, walk_ptrs_hir_ty,
8 use if_chain::if_chain;
9 use rustc_errors::Applicability;
11 BinOpKind, BodyId, Expr, ExprKind, FnDecl, FnRetTy, GenericArg, HirId, ImplItem, ImplItemKind, Item, ItemKind,
12 Lifetime, MutTy, Mutability, Node, PathSegment, QPath, TraitFn, TraitItem, TraitItemKind, Ty, TyKind,
14 use rustc_lint::{LateContext, LateLintPass};
16 use rustc_session::{declare_lint_pass, declare_tool_lint};
17 use rustc_span::source_map::Span;
18 use rustc_span::MultiSpan;
21 declare_clippy_lint! {
22 /// **What it does:** This lint checks for function arguments of type `&String`
23 /// or `&Vec` unless the references are mutable. It will also suggest you
24 /// replace `.clone()` calls with the appropriate `.to_owned()`/`to_string()`
27 /// **Why is this bad?** Requiring the argument to be of the specific size
28 /// makes the function less useful for no benefit; slices in the form of `&[T]`
29 /// or `&str` usually suffice and can be obtained from other types, too.
31 /// **Known problems:** The lint does not follow data. So if you have an
32 /// argument `x` and write `let y = x; y.clone()` the lint will not suggest
33 /// changing that `.clone()` to `.to_owned()`.
35 /// Other functions called from this function taking a `&String` or `&Vec`
36 /// argument may also fail to compile if you change the argument. Applying
37 /// this lint on them will fix the problem, but they may be in other crates.
39 /// Also there may be `fn(&Vec)`-typed references pointing to your function.
40 /// If you have them, you will get a compiler error after applying this lint's
41 /// suggestions. You then have the choice to undo your changes or change the
42 /// type of the reference.
44 /// Note that if the function is part of your public interface, there may be
45 /// other crates referencing it you may not be aware. Carefully deprecate the
46 /// function before applying the lint suggestions in this case.
50 /// fn foo(&Vec<u32>) { .. }
54 "fn arguments of the type `&Vec<...>` or `&String`, suggesting to use `&[...]` or `&str` instead, respectively"
57 declare_clippy_lint! {
58 /// **What it does:** This lint checks for equality comparisons with `ptr::null`
60 /// **Why is this bad?** It's easier and more readable to use the inherent
64 /// **Known problems:** None.
68 /// if x == ptr::null {
74 "comparing a pointer to a null pointer, suggesting to use `.is_null()` instead."
77 declare_clippy_lint! {
78 /// **What it does:** This lint checks for functions that take immutable
79 /// references and return
82 /// **Why is this bad?** This is trivially unsound, as one can create two
83 /// mutable references
84 /// from the same (immutable!) source. This
85 /// [error](https://github.com/rust-lang/rust/issues/39465)
86 /// actually lead to an interim Rust release 1.15.1.
88 /// **Known problems:** To be on the conservative side, if there's at least one
90 /// with the output lifetime, this lint will not trigger. In practice, this
91 /// case is unlikely anyway.
95 /// fn foo(&Foo) -> &mut Bar { .. }
99 "fns that create mutable refs from immutable ref args"
102 declare_lint_pass!(Ptr => [PTR_ARG, CMP_NULL, MUT_FROM_REF]);
104 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Ptr {
105 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item<'_>) {
106 if let ItemKind::Fn(ref sig, _, body_id) = item.kind {
107 check_fn(cx, &sig.decl, item.hir_id, Some(body_id));
111 fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx ImplItem<'_>) {
112 if let ImplItemKind::Fn(ref sig, body_id) = item.kind {
113 let parent_item = cx.tcx.hir().get_parent_item(item.hir_id);
114 if let Some(Node::Item(it)) = cx.tcx.hir().find(parent_item) {
115 if let ItemKind::Impl { of_trait: Some(_), .. } = it.kind {
116 return; // ignore trait impls
119 check_fn(cx, &sig.decl, item.hir_id, Some(body_id));
123 fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx TraitItem<'_>) {
124 if let TraitItemKind::Fn(ref sig, ref trait_method) = item.kind {
125 let body_id = if let TraitFn::Provided(b) = *trait_method {
130 check_fn(cx, &sig.decl, item.hir_id, body_id);
134 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
135 if let ExprKind::Binary(ref op, ref l, ref r) = expr.kind {
136 if (op.node == BinOpKind::Eq || op.node == BinOpKind::Ne) && (is_null_path(l) || is_null_path(r)) {
141 "Comparing with null is better expressed by the `.is_null()` method",
148 #[allow(clippy::too_many_lines)]
149 fn check_fn(cx: &LateContext<'_, '_>, decl: &FnDecl<'_>, fn_id: HirId, opt_body_id: Option<BodyId>) {
150 let fn_def_id = cx.tcx.hir().local_def_id(fn_id);
151 let sig = cx.tcx.fn_sig(fn_def_id);
152 let fn_ty = sig.skip_binder();
154 for (idx, (arg, ty)) in decl.inputs.iter().zip(fn_ty.inputs()).enumerate() {
155 if let ty::Ref(_, ty, Mutability::Not) = ty.kind {
156 if is_type_diagnostic_item(cx, ty, sym!(vec_type)) {
157 let mut ty_snippet = None;
159 if let TyKind::Path(QPath::Resolved(_, ref path)) = walk_ptrs_hir_ty(arg).kind;
160 if let Some(&PathSegment{args: Some(ref parameters), ..}) = path.segments.last();
162 let types: Vec<_> = parameters.args.iter().filter_map(|arg| match arg {
163 GenericArg::Type(ty) => Some(ty),
166 if types.len() == 1 {
167 ty_snippet = snippet_opt(cx, types[0].span);
171 if let Some(spans) = get_spans(cx, opt_body_id, idx, &[("clone", ".to_owned()")]) {
176 "writing `&Vec<_>` instead of `&[_]` involves one more reference and cannot be used \
177 with non-Vec-based slices.",
179 if let Some(ref snippet) = ty_snippet {
180 diag.span_suggestion(
183 format!("&[{}]", snippet),
184 Applicability::Unspecified,
187 for (clonespan, suggestion) in spans {
188 diag.span_suggestion(
190 &snippet_opt(cx, clonespan).map_or("change the call to".into(), |x| {
191 Cow::Owned(format!("change `{}` to", x))
194 Applicability::Unspecified,
200 } else if is_type_diagnostic_item(cx, ty, sym!(string_type)) {
201 if let Some(spans) = get_spans(cx, opt_body_id, idx, &[("clone", ".to_string()"), ("as_str", "")]) {
206 "writing `&String` instead of `&str` involves a new object where a slice will do.",
208 diag.span_suggestion(arg.span, "change this to", "&str".into(), Applicability::Unspecified);
209 for (clonespan, suggestion) in spans {
210 diag.span_suggestion_short(
212 &snippet_opt(cx, clonespan).map_or("change the call to".into(), |x| {
213 Cow::Owned(format!("change `{}` to", x))
216 Applicability::Unspecified,
222 } else if match_type(cx, ty, &paths::COW) {
224 if let TyKind::Rptr(_, MutTy { ref ty, ..} ) = arg.kind;
225 if let TyKind::Path(ref path) = ty.kind;
226 if let QPath::Resolved(None, ref pp) = *path;
227 if let [ref bx] = *pp.segments;
228 if let Some(ref params) = bx.args;
229 if !params.parenthesized;
230 if let Some(inner) = params.args.iter().find_map(|arg| match arg {
231 GenericArg::Type(ty) => Some(ty),
235 let replacement = snippet_opt(cx, inner.span);
236 if let Some(r) = replacement {
241 "using a reference to `Cow` is not recommended.",
244 Applicability::Unspecified,
253 if let FnRetTy::Return(ref ty) = decl.output {
254 if let Some((out, Mutability::Mut, _)) = get_rptr_lm(ty) {
255 let mut immutables = vec![];
256 for (_, ref mutbl, ref argspan) in decl
259 .filter_map(|ty| get_rptr_lm(ty))
260 .filter(|&(lt, _, _)| lt.name == out.name)
262 if *mutbl == Mutability::Mut {
265 immutables.push(*argspan);
267 if immutables.is_empty() {
274 "mutable borrow from immutable input(s)",
276 let ms = MultiSpan::from_spans(immutables);
277 diag.span_note(ms, "immutable borrow here");
284 fn get_rptr_lm<'tcx>(ty: &'tcx Ty<'tcx>) -> Option<(&'tcx Lifetime, Mutability, Span)> {
285 if let TyKind::Rptr(ref lt, ref m) = ty.kind {
286 Some((lt, m.mutbl, ty.span))
292 fn is_null_path(expr: &Expr<'_>) -> bool {
293 if let ExprKind::Call(ref pathexp, ref args) = expr.kind {
295 if let ExprKind::Path(ref path) = pathexp.kind {
296 return match_qpath(path, &paths::PTR_NULL) || match_qpath(path, &paths::PTR_NULL_MUT);