]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/ptr.rs
Auto merge of #4930 - flip1995:unused_label, r=phansch
[rust.git] / clippy_lints / src / ptr.rs
1 //! Checks for usage of  `&Vec[_]` and `&String`.
2
3 use crate::utils::ptr::get_spans;
4 use crate::utils::{
5     is_type_diagnostic_item, match_qpath, match_type, paths, snippet_opt, span_lint, span_lint_and_then,
6     walk_ptrs_hir_ty,
7 };
8 use if_chain::if_chain;
9 use rustc::declare_lint_pass;
10 use rustc::hir::QPath;
11 use rustc::hir::*;
12 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
13 use rustc::ty;
14 use rustc_errors::Applicability;
15 use rustc_session::declare_tool_lint;
16 use std::borrow::Cow;
17 use syntax::source_map::Span;
18 use syntax_pos::{MultiSpan, Symbol};
19
20 declare_clippy_lint! {
21     /// **What it does:** This lint checks for function arguments of type `&String`
22     /// or `&Vec` unless the references are mutable. It will also suggest you
23     /// replace `.clone()` calls with the appropriate `.to_owned()`/`to_string()`
24     /// calls.
25     ///
26     /// **Why is this bad?** Requiring the argument to be of the specific size
27     /// makes the function less useful for no benefit; slices in the form of `&[T]`
28     /// or `&str` usually suffice and can be obtained from other types, too.
29     ///
30     /// **Known problems:** The lint does not follow data. So if you have an
31     /// argument `x` and write `let y = x; y.clone()` the lint will not suggest
32     /// changing that `.clone()` to `.to_owned()`.
33     ///
34     /// Other functions called from this function taking a `&String` or `&Vec`
35     /// argument may also fail to compile if you change the argument. Applying
36     /// this lint on them will fix the problem, but they may be in other crates.
37     ///
38     /// Also there may be `fn(&Vec)`-typed references pointing to your function.
39     /// If you have them, you will get a compiler error after applying this lint's
40     /// suggestions. You then have the choice to undo your changes or change the
41     /// type of the reference.
42     ///
43     /// Note that if the function is part of your public interface, there may be
44     /// other crates referencing it you may not be aware. Carefully deprecate the
45     /// function before applying the lint suggestions in this case.
46     ///
47     /// **Example:**
48     /// ```ignore
49     /// fn foo(&Vec<u32>) { .. }
50     /// ```
51     pub PTR_ARG,
52     style,
53     "fn arguments of the type `&Vec<...>` or `&String`, suggesting to use `&[...]` or `&str` instead, respectively"
54 }
55
56 declare_clippy_lint! {
57     /// **What it does:** This lint checks for equality comparisons with `ptr::null`
58     ///
59     /// **Why is this bad?** It's easier and more readable to use the inherent
60     /// `.is_null()`
61     /// method instead
62     ///
63     /// **Known problems:** None.
64     ///
65     /// **Example:**
66     /// ```ignore
67     /// if x == ptr::null {
68     ///     ..
69     /// }
70     /// ```
71     pub CMP_NULL,
72     style,
73     "comparing a pointer to a null pointer, suggesting to use `.is_null()` instead."
74 }
75
76 declare_clippy_lint! {
77     /// **What it does:** This lint checks for functions that take immutable
78     /// references and return
79     /// mutable ones.
80     ///
81     /// **Why is this bad?** This is trivially unsound, as one can create two
82     /// mutable references
83     /// from the same (immutable!) source. This
84     /// [error](https://github.com/rust-lang/rust/issues/39465)
85     /// actually lead to an interim Rust release 1.15.1.
86     ///
87     /// **Known problems:** To be on the conservative side, if there's at least one
88     /// mutable reference
89     /// with the output lifetime, this lint will not trigger. In practice, this
90     /// case is unlikely anyway.
91     ///
92     /// **Example:**
93     /// ```ignore
94     /// fn foo(&Foo) -> &mut Bar { .. }
95     /// ```
96     pub MUT_FROM_REF,
97     correctness,
98     "fns that create mutable refs from immutable ref args"
99 }
100
101 declare_lint_pass!(Ptr => [PTR_ARG, CMP_NULL, MUT_FROM_REF]);
102
103 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Ptr {
104     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
105         if let ItemKind::Fn(ref sig, _, body_id) = item.kind {
106             check_fn(cx, &sig.decl, item.hir_id, Some(body_id));
107         }
108     }
109
110     fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx ImplItem) {
111         if let ImplItemKind::Method(ref sig, body_id) = item.kind {
112             let parent_item = cx.tcx.hir().get_parent_item(item.hir_id);
113             if let Some(Node::Item(it)) = cx.tcx.hir().find(parent_item) {
114                 if let ItemKind::Impl(_, _, _, _, Some(_), _, _) = it.kind {
115                     return; // ignore trait impls
116                 }
117             }
118             check_fn(cx, &sig.decl, item.hir_id, Some(body_id));
119         }
120     }
121
122     fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx TraitItem) {
123         if let TraitItemKind::Method(ref sig, ref trait_method) = item.kind {
124             let body_id = if let TraitMethod::Provided(b) = *trait_method {
125                 Some(b)
126             } else {
127                 None
128             };
129             check_fn(cx, &sig.decl, item.hir_id, body_id);
130         }
131     }
132
133     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
134         if let ExprKind::Binary(ref op, ref l, ref r) = expr.kind {
135             if (op.node == BinOpKind::Eq || op.node == BinOpKind::Ne) && (is_null_path(l) || is_null_path(r)) {
136                 span_lint(
137                     cx,
138                     CMP_NULL,
139                     expr.span,
140                     "Comparing with null is better expressed by the .is_null() method",
141                 );
142             }
143         }
144     }
145 }
146
147 #[allow(clippy::too_many_lines)]
148 fn check_fn(cx: &LateContext<'_, '_>, decl: &FnDecl, fn_id: HirId, opt_body_id: Option<BodyId>) {
149     let fn_def_id = cx.tcx.hir().local_def_id(fn_id);
150     let sig = cx.tcx.fn_sig(fn_def_id);
151     let fn_ty = sig.skip_binder();
152
153     for (idx, (arg, ty)) in decl.inputs.iter().zip(fn_ty.inputs()).enumerate() {
154         if let ty::Ref(_, ty, Mutability::Not) = ty.kind {
155             if is_type_diagnostic_item(cx, ty, Symbol::intern("vec_type")) {
156                 let mut ty_snippet = None;
157                 if_chain! {
158                     if let TyKind::Path(QPath::Resolved(_, ref path)) = walk_ptrs_hir_ty(arg).kind;
159                     if let Some(&PathSegment{args: Some(ref parameters), ..}) = path.segments.last();
160                     then {
161                         let types: Vec<_> = parameters.args.iter().filter_map(|arg| match arg {
162                             GenericArg::Type(ty) => Some(ty),
163                             _ => None,
164                         }).collect();
165                         if types.len() == 1 {
166                             ty_snippet = snippet_opt(cx, types[0].span);
167                         }
168                     }
169                 };
170                 if let Some(spans) = get_spans(cx, opt_body_id, idx, &[("clone", ".to_owned()")]) {
171                     span_lint_and_then(
172                         cx,
173                         PTR_ARG,
174                         arg.span,
175                         "writing `&Vec<_>` instead of `&[_]` involves one more reference and cannot be used \
176                          with non-Vec-based slices.",
177                         |db| {
178                             if let Some(ref snippet) = ty_snippet {
179                                 db.span_suggestion(
180                                     arg.span,
181                                     "change this to",
182                                     format!("&[{}]", snippet),
183                                     Applicability::Unspecified,
184                                 );
185                             }
186                             for (clonespan, suggestion) in spans {
187                                 db.span_suggestion(
188                                     clonespan,
189                                     &snippet_opt(cx, clonespan).map_or("change the call to".into(), |x| {
190                                         Cow::Owned(format!("change `{}` to", x))
191                                     }),
192                                     suggestion.into(),
193                                     Applicability::Unspecified,
194                                 );
195                             }
196                         },
197                     );
198                 }
199             } else if match_type(cx, ty, &paths::STRING) {
200                 if let Some(spans) = get_spans(cx, opt_body_id, idx, &[("clone", ".to_string()"), ("as_str", "")]) {
201                     span_lint_and_then(
202                         cx,
203                         PTR_ARG,
204                         arg.span,
205                         "writing `&String` instead of `&str` involves a new object where a slice will do.",
206                         |db| {
207                             db.span_suggestion(arg.span, "change this to", "&str".into(), Applicability::Unspecified);
208                             for (clonespan, suggestion) in spans {
209                                 db.span_suggestion_short(
210                                     clonespan,
211                                     &snippet_opt(cx, clonespan).map_or("change the call to".into(), |x| {
212                                         Cow::Owned(format!("change `{}` to", x))
213                                     }),
214                                     suggestion.into(),
215                                     Applicability::Unspecified,
216                                 );
217                             }
218                         },
219                     );
220                 }
221             } else if match_type(cx, ty, &paths::COW) {
222                 if_chain! {
223                     if let TyKind::Rptr(_, MutTy { ref ty, ..} ) = arg.kind;
224                     if let TyKind::Path(ref path) = ty.kind;
225                     if let QPath::Resolved(None, ref pp) = *path;
226                     if let [ref bx] = *pp.segments;
227                     if let Some(ref params) = bx.args;
228                     if !params.parenthesized;
229                     if let Some(inner) = params.args.iter().find_map(|arg| match arg {
230                         GenericArg::Type(ty) => Some(ty),
231                         _ => None,
232                     });
233                     then {
234                         let replacement = snippet_opt(cx, inner.span);
235                         if let Some(r) = replacement {
236                             span_lint_and_then(
237                                 cx,
238                                 PTR_ARG,
239                                 arg.span,
240                                 "using a reference to `Cow` is not recommended.",
241                                 |db| {
242                                     db.span_suggestion(
243                                         arg.span,
244                                         "change this to",
245                                         "&".to_owned() + &r,
246                                         Applicability::Unspecified,
247                                     );
248                                 },
249                             );
250                         }
251                     }
252                 }
253             }
254         }
255     }
256
257     if let FunctionRetTy::Return(ref ty) = decl.output {
258         if let Some((out, Mutability::Mut, _)) = get_rptr_lm(ty) {
259             let mut immutables = vec![];
260             for (_, ref mutbl, ref argspan) in decl
261                 .inputs
262                 .iter()
263                 .filter_map(|ty| get_rptr_lm(ty))
264                 .filter(|&(lt, _, _)| lt.name == out.name)
265             {
266                 if *mutbl == Mutability::Mut {
267                     return;
268                 }
269                 immutables.push(*argspan);
270             }
271             if immutables.is_empty() {
272                 return;
273             }
274             span_lint_and_then(
275                 cx,
276                 MUT_FROM_REF,
277                 ty.span,
278                 "mutable borrow from immutable input(s)",
279                 |db| {
280                     let ms = MultiSpan::from_spans(immutables);
281                     db.span_note(ms, "immutable borrow here");
282                 },
283             );
284         }
285     }
286 }
287
288 fn get_rptr_lm(ty: &Ty) -> Option<(&Lifetime, Mutability, Span)> {
289     if let TyKind::Rptr(ref lt, ref m) = ty.kind {
290         Some((lt, m.mutbl, ty.span))
291     } else {
292         None
293     }
294 }
295
296 fn is_null_path(expr: &Expr) -> bool {
297     if let ExprKind::Call(ref pathexp, ref args) = expr.kind {
298         if args.is_empty() {
299             if let ExprKind::Path(ref path) = pathexp.kind {
300                 return match_qpath(path, &paths::PTR_NULL) || match_qpath(path, &paths::PTR_NULL_MUT);
301             }
302         }
303     }
304     false
305 }