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