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