1 //! Checks for usage of `&Vec[_]` and `&String`.
3 use crate::utils::ptr::get_spans;
5 use crate::utils::{match_qpath, match_type, paths, snippet_opt, span_lint, span_lint_and_then, walk_ptrs_hir_ty};
6 use if_chain::if_chain;
9 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
11 use rustc::{declare_lint_pass, declare_tool_lint};
12 use rustc_errors::Applicability;
14 use syntax::source_map::Span;
15 use syntax_pos::MultiSpan;
17 declare_clippy_lint! {
18 /// **What it does:** This lint checks for function arguments of type `&String`
19 /// or `&Vec` unless the references are mutable. It will also suggest you
20 /// replace `.clone()` calls with the appropriate `.to_owned()`/`to_string()`
23 /// **Why is this bad?** Requiring the argument to be of the specific size
24 /// makes the function less useful for no benefit; slices in the form of `&[T]`
25 /// or `&str` usually suffice and can be obtained from other types, too.
27 /// **Known problems:** The lint does not follow data. So if you have an
28 /// argument `x` and write `let y = x; y.clone()` the lint will not suggest
29 /// changing that `.clone()` to `.to_owned()`.
31 /// Other functions called from this function taking a `&String` or `&Vec`
32 /// argument may also fail to compile if you change the argument. Applying
33 /// this lint on them will fix the problem, but they may be in other crates.
35 /// Also there may be `fn(&Vec)`-typed references pointing to your function.
36 /// If you have them, you will get a compiler error after applying this lint's
37 /// suggestions. You then have the choice to undo your changes or change the
38 /// type of the reference.
40 /// Note that if the function is part of your public interface, there may be
41 /// other crates referencing it you may not be aware. Carefully deprecate the
42 /// function before applying the lint suggestions in this case.
46 /// fn foo(&Vec<u32>) { .. }
50 "fn arguments of the type `&Vec<...>` or `&String`, suggesting to use `&[...]` or `&str` instead, respectively"
53 declare_clippy_lint! {
54 /// **What it does:** This lint checks for equality comparisons with `ptr::null`
56 /// **Why is this bad?** It's easier and more readable to use the inherent
60 /// **Known problems:** None.
64 /// if x == ptr::null {
70 "comparing a pointer to a null pointer, suggesting to use `.is_null()` instead."
73 declare_clippy_lint! {
74 /// **What it does:** This lint checks for functions that take immutable
75 /// references and return
78 /// **Why is this bad?** This is trivially unsound, as one can create two
79 /// mutable references
80 /// from the same (immutable!) source. This
81 /// [error](https://github.com/rust-lang/rust/issues/39465)
82 /// actually lead to an interim Rust release 1.15.1.
84 /// **Known problems:** To be on the conservative side, if there's at least one
86 /// with the output lifetime, this lint will not trigger. In practice, this
87 /// case is unlikely anyway.
91 /// fn foo(&Foo) -> &mut Bar { .. }
95 "fns that create mutable refs from immutable ref args"
98 declare_lint_pass!(Ptr => [PTR_ARG, CMP_NULL, MUT_FROM_REF]);
100 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Ptr {
101 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
102 if let ItemKind::Fn(ref decl, _, _, body_id) = item.node {
103 check_fn(cx, decl, item.hir_id, Some(body_id));
107 fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx ImplItem) {
108 if let ImplItemKind::Method(ref sig, body_id) = item.node {
109 let parent_item = cx.tcx.hir().get_parent_item(item.hir_id);
110 if let Some(Node::Item(it)) = cx.tcx.hir().find_by_hir_id(parent_item) {
111 if let ItemKind::Impl(_, _, _, _, Some(_), _, _) = it.node {
112 return; // ignore trait impls
115 check_fn(cx, &sig.decl, item.hir_id, Some(body_id));
119 fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx TraitItem) {
120 if let TraitItemKind::Method(ref sig, ref trait_method) = item.node {
121 let body_id = if let TraitMethod::Provided(b) = *trait_method {
126 check_fn(cx, &sig.decl, item.hir_id, body_id);
130 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
131 if let ExprKind::Binary(ref op, ref l, ref r) = expr.node {
132 if (op.node == BinOpKind::Eq || op.node == BinOpKind::Ne) && (is_null_path(l) || is_null_path(r)) {
137 "Comparing with null is better expressed by the .is_null() method",
144 #[allow(clippy::too_many_lines)]
145 fn check_fn(cx: &LateContext<'_, '_>, decl: &FnDecl, fn_id: HirId, opt_body_id: Option<BodyId>) {
146 let fn_def_id = cx.tcx.hir().local_def_id_from_hir_id(fn_id);
147 let sig = cx.tcx.fn_sig(fn_def_id);
148 let fn_ty = sig.skip_binder();
150 for (idx, (arg, ty)) in decl.inputs.iter().zip(fn_ty.inputs()).enumerate() {
151 if let ty::Ref(_, ty, MutImmutable) = ty.sty {
152 if match_type(cx, ty, &*paths::VEC) {
153 let mut ty_snippet = None;
155 if let TyKind::Path(QPath::Resolved(_, ref path)) = walk_ptrs_hir_ty(arg).node;
156 if let Some(&PathSegment{args: Some(ref parameters), ..}) = path.segments.last();
158 let types: Vec<_> = parameters.args.iter().filter_map(|arg| match arg {
159 GenericArg::Type(ty) => Some(ty),
162 if types.len() == 1 {
163 ty_snippet = snippet_opt(cx, types[0].span);
167 if let Some(spans) = get_spans(cx, opt_body_id, idx, &[(*sym::clone, ".to_owned()")]) {
172 "writing `&Vec<_>` instead of `&[_]` involves one more reference and cannot be used \
173 with non-Vec-based slices.",
175 if let Some(ref snippet) = ty_snippet {
179 format!("&[{}]", snippet),
180 Applicability::Unspecified,
183 for (clonespan, suggestion) in spans {
186 &snippet_opt(cx, clonespan).map_or("change the call to".into(), |x| {
187 Cow::Owned(format!("change `{}` to", x))
190 Applicability::Unspecified,
196 } else if match_type(cx, ty, &*paths::STRING) {
197 if let Some(spans) = get_spans(cx, opt_body_id, idx, &[(*sym::clone, ".to_string()"), (*sym::as_str, "")]) {
202 "writing `&String` instead of `&str` involves a new object where a slice will do.",
204 db.span_suggestion(arg.span, "change this to", "&str".into(), Applicability::Unspecified);
205 for (clonespan, suggestion) in spans {
206 db.span_suggestion_short(
208 &snippet_opt(cx, clonespan).map_or("change the call to".into(), |x| {
209 Cow::Owned(format!("change `{}` to", x))
212 Applicability::Unspecified,
218 } else if match_type(cx, ty, &*paths::COW) {
220 if let TyKind::Rptr(_, MutTy { ref ty, ..} ) = arg.node;
221 if let TyKind::Path(ref path) = ty.node;
222 if let QPath::Resolved(None, ref pp) = *path;
223 if let [ref bx] = *pp.segments;
224 if let Some(ref params) = bx.args;
225 if !params.parenthesized;
226 if let Some(inner) = params.args.iter().find_map(|arg| match arg {
227 GenericArg::Type(ty) => Some(ty),
231 let replacement = snippet_opt(cx, inner.span);
232 if let Some(r) = replacement {
237 "using a reference to `Cow` is not recommended.",
243 Applicability::Unspecified,
254 if let FunctionRetTy::Return(ref ty) = decl.output {
255 if let Some((out, MutMutable, _)) = get_rptr_lm(ty) {
256 let mut immutables = vec![];
257 for (_, ref mutbl, ref argspan) in decl
260 .filter_map(|ty| get_rptr_lm(ty))
261 .filter(|&(lt, _, _)| lt.name == out.name)
263 if *mutbl == MutMutable {
266 immutables.push(*argspan);
268 if immutables.is_empty() {
275 "mutable borrow from immutable input(s)",
277 let ms = MultiSpan::from_spans(immutables);
278 db.span_note(ms, "immutable borrow here");
285 fn get_rptr_lm(ty: &Ty) -> Option<(&Lifetime, Mutability, Span)> {
286 if let TyKind::Rptr(ref lt, ref m) = ty.node {
287 Some((lt, m.mutbl, ty.span))
293 fn is_null_path(expr: &Expr) -> bool {
294 if let ExprKind::Call(ref pathexp, ref args) = expr.node {
296 if let ExprKind::Path(ref path) = pathexp.node {
297 return match_qpath(path, &*paths::PTR_NULL) || match_qpath(path, &*paths::PTR_NULL_MUT);