]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/ptr.rs
Merge remote-tracking branch 'origin/rust-1.31.0' into HEAD
[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::sym;
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;
7 use rustc::hir::QPath;
8 use rustc::hir::*;
9 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
10 use rustc::ty;
11 use rustc::{declare_lint_pass, declare_tool_lint};
12 use rustc_errors::Applicability;
13 use std::borrow::Cow;
14 use syntax::source_map::Span;
15 use syntax_pos::MultiSpan;
16
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()`
21     /// calls.
22     ///
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.
26     ///
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()`.
30     ///
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.
34     ///
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.
39     ///
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.
43     ///
44     /// **Example:**
45     /// ```ignore
46     /// fn foo(&Vec<u32>) { .. }
47     /// ```
48     pub PTR_ARG,
49     style,
50     "fn arguments of the type `&Vec<...>` or `&String`, suggesting to use `&[...]` or `&str` instead, respectively"
51 }
52
53 declare_clippy_lint! {
54     /// **What it does:** This lint checks for equality comparisons with `ptr::null`
55     ///
56     /// **Why is this bad?** It's easier and more readable to use the inherent
57     /// `.is_null()`
58     /// method instead
59     ///
60     /// **Known problems:** None.
61     ///
62     /// **Example:**
63     /// ```ignore
64     /// if x == ptr::null {
65     ///     ..
66     /// }
67     /// ```
68     pub CMP_NULL,
69     style,
70     "comparing a pointer to a null pointer, suggesting to use `.is_null()` instead."
71 }
72
73 declare_clippy_lint! {
74     /// **What it does:** This lint checks for functions that take immutable
75     /// references and return
76     /// mutable ones.
77     ///
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.
83     ///
84     /// **Known problems:** To be on the conservative side, if there's at least one
85     /// mutable reference
86     /// with the output lifetime, this lint will not trigger. In practice, this
87     /// case is unlikely anyway.
88     ///
89     /// **Example:**
90     /// ```ignore
91     /// fn foo(&Foo) -> &mut Bar { .. }
92     /// ```
93     pub MUT_FROM_REF,
94     correctness,
95     "fns that create mutable refs from immutable ref args"
96 }
97
98 declare_lint_pass!(Ptr => [PTR_ARG, CMP_NULL, MUT_FROM_REF]);
99
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));
104         }
105     }
106
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
113                 }
114             }
115             check_fn(cx, &sig.decl, item.hir_id, Some(body_id));
116         }
117     }
118
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 {
122                 Some(b)
123             } else {
124                 None
125             };
126             check_fn(cx, &sig.decl, item.hir_id, body_id);
127         }
128     }
129
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)) {
133                 span_lint(
134                     cx,
135                     CMP_NULL,
136                     expr.span,
137                     "Comparing with null is better expressed by the .is_null() method",
138                 );
139             }
140         }
141     }
142 }
143
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();
149
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;
154                 if_chain! {
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();
157                     then {
158                         let types: Vec<_> = parameters.args.iter().filter_map(|arg| match arg {
159                             GenericArg::Type(ty) => Some(ty),
160                             _ => None,
161                         }).collect();
162                         if types.len() == 1 {
163                             ty_snippet = snippet_opt(cx, types[0].span);
164                         }
165                     }
166                 };
167                 if let Some(spans) = get_spans(cx, opt_body_id, idx, &[(*sym::clone, ".to_owned()")]) {
168                     span_lint_and_then(
169                         cx,
170                         PTR_ARG,
171                         arg.span,
172                         "writing `&Vec<_>` instead of `&[_]` involves one more reference and cannot be used \
173                          with non-Vec-based slices.",
174                         |db| {
175                             if let Some(ref snippet) = ty_snippet {
176                                 db.span_suggestion(
177                                     arg.span,
178                                     "change this to",
179                                     format!("&[{}]", snippet),
180                                     Applicability::Unspecified,
181                                 );
182                             }
183                             for (clonespan, suggestion) in spans {
184                                 db.span_suggestion(
185                                     clonespan,
186                                     &snippet_opt(cx, clonespan).map_or("change the call to".into(), |x| {
187                                         Cow::Owned(format!("change `{}` to", x))
188                                     }),
189                                     suggestion.into(),
190                                     Applicability::Unspecified,
191                                 );
192                             }
193                         },
194                     );
195                 }
196             } else if match_type(cx, ty, &*paths::STRING) {
197                 if let Some(spans) = get_spans(
198                     cx,
199                     opt_body_id,
200                     idx,
201                     &[(*sym::clone, ".to_string()"), (*sym::as_str, "")],
202                 ) {
203                     span_lint_and_then(
204                         cx,
205                         PTR_ARG,
206                         arg.span,
207                         "writing `&String` instead of `&str` involves a new object where a slice will do.",
208                         |db| {
209                             db.span_suggestion(arg.span, "change this to", "&str".into(), Applicability::Unspecified);
210                             for (clonespan, suggestion) in spans {
211                                 db.span_suggestion_short(
212                                     clonespan,
213                                     &snippet_opt(cx, clonespan).map_or("change the call to".into(), |x| {
214                                         Cow::Owned(format!("change `{}` to", x))
215                                     }),
216                                     suggestion.into(),
217                                     Applicability::Unspecified,
218                                 );
219                             }
220                         },
221                     );
222                 }
223             } else if match_type(cx, ty, &*paths::COW) {
224                 if_chain! {
225                     if let TyKind::Rptr(_, MutTy { ref ty, ..} ) = arg.node;
226                     if let TyKind::Path(ref path) = ty.node;
227                     if let QPath::Resolved(None, ref pp) = *path;
228                     if let [ref bx] = *pp.segments;
229                     if let Some(ref params) = bx.args;
230                     if !params.parenthesized;
231                     if let Some(inner) = params.args.iter().find_map(|arg| match arg {
232                         GenericArg::Type(ty) => Some(ty),
233                         _ => None,
234                     });
235                     then {
236                         let replacement = snippet_opt(cx, inner.span);
237                         if let Some(r) = replacement {
238                             span_lint_and_then(
239                                 cx,
240                                 PTR_ARG,
241                                 arg.span,
242                                 "using a reference to `Cow` is not recommended.",
243                                 |db| {
244                                     db.span_suggestion(
245                                         arg.span,
246                                         "change this to",
247                                         "&".to_owned() + &r,
248                                         Applicability::Unspecified,
249                                     );
250                                 },
251                             );
252                         }
253                     }
254                 }
255             }
256         }
257     }
258
259     if let FunctionRetTy::Return(ref ty) = decl.output {
260         if let Some((out, MutMutable, _)) = get_rptr_lm(ty) {
261             let mut immutables = vec![];
262             for (_, ref mutbl, ref argspan) in decl
263                 .inputs
264                 .iter()
265                 .filter_map(|ty| get_rptr_lm(ty))
266                 .filter(|&(lt, _, _)| lt.name == out.name)
267             {
268                 if *mutbl == MutMutable {
269                     return;
270                 }
271                 immutables.push(*argspan);
272             }
273             if immutables.is_empty() {
274                 return;
275             }
276             span_lint_and_then(
277                 cx,
278                 MUT_FROM_REF,
279                 ty.span,
280                 "mutable borrow from immutable input(s)",
281                 |db| {
282                     let ms = MultiSpan::from_spans(immutables);
283                     db.span_note(ms, "immutable borrow here");
284                 },
285             );
286         }
287     }
288 }
289
290 fn get_rptr_lm(ty: &Ty) -> Option<(&Lifetime, Mutability, Span)> {
291     if let TyKind::Rptr(ref lt, ref m) = ty.node {
292         Some((lt, m.mutbl, ty.span))
293     } else {
294         None
295     }
296 }
297
298 fn is_null_path(expr: &Expr) -> bool {
299     if let ExprKind::Call(ref pathexp, ref args) = expr.node {
300         if args.is_empty() {
301             if let ExprKind::Path(ref path) = pathexp.node {
302                 return match_qpath(path, &*paths::PTR_NULL) || match_qpath(path, &*paths::PTR_NULL_MUT);
303             }
304         }
305     }
306     false
307 }