]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/ptr.rs
Auto merge of #6828 - mgacek8:issue_6758_enhance_wrong_self_convention, 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::{is_allowed, match_qpath, paths, snippet_opt, span_lint, span_lint_and_sugg, span_lint_and_then};
5 use clippy_utils::ty::{is_type_diagnostic_item, match_type, walk_ptrs_hir_ty};
6 use if_chain::if_chain;
7 use rustc_errors::Applicability;
8 use rustc_hir::{
9     BinOpKind, BodyId, Expr, ExprKind, FnDecl, FnRetTy, GenericArg, HirId, Impl, ImplItem, ImplItemKind, Item,
10     ItemKind, Lifetime, MutTy, Mutability, Node, PathSegment, QPath, TraitFn, TraitItem, TraitItemKind, Ty, TyKind,
11 };
12 use rustc_lint::{LateContext, LateLintPass};
13 use rustc_middle::ty;
14 use rustc_session::{declare_lint_pass, declare_tool_lint};
15 use rustc_span::source_map::Span;
16 use rustc_span::{sym, MultiSpan};
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     /// One notable example of a function that may cause issues, and which cannot
38     /// easily be changed due to being in the standard library is `Vec::contains`.
39     /// when called on a `Vec<Vec<T>>`. If a `&Vec` is passed to that method then
40     /// it will compile, but if a `&[T]` is passed then it will not compile.
41     ///
42     /// ```ignore
43     /// fn cannot_take_a_slice(v: &Vec<u8>) -> bool {
44     ///     let vec_of_vecs: Vec<Vec<u8>> = some_other_fn();
45     ///
46     ///     vec_of_vecs.contains(v)
47     /// }
48     /// ```
49     ///
50     /// Also there may be `fn(&Vec)`-typed references pointing to your function.
51     /// If you have them, you will get a compiler error after applying this lint's
52     /// suggestions. You then have the choice to undo your changes or change the
53     /// type of the reference.
54     ///
55     /// Note that if the function is part of your public interface, there may be
56     /// other crates referencing it, of which you may not be aware. Carefully
57     /// deprecate the function before applying the lint suggestions in this case.
58     ///
59     /// **Example:**
60     /// ```ignore
61     /// // Bad
62     /// fn foo(&Vec<u32>) { .. }
63     ///
64     /// // Good
65     /// fn foo(&[u32]) { .. }
66     /// ```
67     pub PTR_ARG,
68     style,
69     "fn arguments of the type `&Vec<...>` or `&String`, suggesting to use `&[...]` or `&str` instead, respectively"
70 }
71
72 declare_clippy_lint! {
73     /// **What it does:** This lint checks for equality comparisons with `ptr::null`
74     ///
75     /// **Why is this bad?** It's easier and more readable to use the inherent
76     /// `.is_null()`
77     /// method instead
78     ///
79     /// **Known problems:** None.
80     ///
81     /// **Example:**
82     /// ```ignore
83     /// // Bad
84     /// if x == ptr::null {
85     ///     ..
86     /// }
87     ///
88     /// // Good
89     /// if x.is_null() {
90     ///     ..
91     /// }
92     /// ```
93     pub CMP_NULL,
94     style,
95     "comparing a pointer to a null pointer, suggesting to use `.is_null()` instead."
96 }
97
98 declare_clippy_lint! {
99     /// **What it does:** This lint checks for functions that take immutable
100     /// references and return mutable ones.
101     ///
102     /// **Why is this bad?** This is trivially unsound, as one can create two
103     /// mutable references from the same (immutable!) source.
104     /// This [error](https://github.com/rust-lang/rust/issues/39465)
105     /// actually lead to an interim Rust release 1.15.1.
106     ///
107     /// **Known problems:** To be on the conservative side, if there's at least one
108     /// mutable reference with the output lifetime, this lint will not trigger.
109     /// In practice, this case is unlikely anyway.
110     ///
111     /// **Example:**
112     /// ```ignore
113     /// fn foo(&Foo) -> &mut Bar { .. }
114     /// ```
115     pub MUT_FROM_REF,
116     correctness,
117     "fns that create mutable refs from immutable ref args"
118 }
119
120 declare_lint_pass!(Ptr => [PTR_ARG, CMP_NULL, MUT_FROM_REF]);
121
122 impl<'tcx> LateLintPass<'tcx> for Ptr {
123     fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
124         if let ItemKind::Fn(ref sig, _, body_id) = item.kind {
125             check_fn(cx, &sig.decl, item.hir_id(), Some(body_id));
126         }
127     }
128
129     fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx ImplItem<'_>) {
130         if let ImplItemKind::Fn(ref sig, body_id) = item.kind {
131             let parent_item = cx.tcx.hir().get_parent_item(item.hir_id());
132             if let Some(Node::Item(it)) = cx.tcx.hir().find(parent_item) {
133                 if let ItemKind::Impl(Impl { of_trait: Some(_), .. }) = it.kind {
134                     return; // ignore trait impls
135                 }
136             }
137             check_fn(cx, &sig.decl, item.hir_id(), Some(body_id));
138         }
139     }
140
141     fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
142         if let TraitItemKind::Fn(ref sig, ref trait_method) = item.kind {
143             let body_id = if let TraitFn::Provided(b) = *trait_method {
144                 Some(b)
145             } else {
146                 None
147             };
148             check_fn(cx, &sig.decl, item.hir_id(), body_id);
149         }
150     }
151
152     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
153         if let ExprKind::Binary(ref op, ref l, ref r) = expr.kind {
154             if (op.node == BinOpKind::Eq || op.node == BinOpKind::Ne) && (is_null_path(l) || is_null_path(r)) {
155                 span_lint(
156                     cx,
157                     CMP_NULL,
158                     expr.span,
159                     "comparing with null is better expressed by the `.is_null()` method",
160                 );
161             }
162         }
163     }
164 }
165
166 #[allow(clippy::too_many_lines)]
167 fn check_fn(cx: &LateContext<'_>, decl: &FnDecl<'_>, fn_id: HirId, opt_body_id: Option<BodyId>) {
168     let fn_def_id = cx.tcx.hir().local_def_id(fn_id);
169     let sig = cx.tcx.fn_sig(fn_def_id);
170     let fn_ty = sig.skip_binder();
171     let body = opt_body_id.map(|id| cx.tcx.hir().body(id));
172
173     for (idx, (arg, ty)) in decl.inputs.iter().zip(fn_ty.inputs()).enumerate() {
174         // Honor the allow attribute on parameters. See issue 5644.
175         if let Some(body) = &body {
176             if is_allowed(cx, PTR_ARG, body.params[idx].hir_id) {
177                 continue;
178             }
179         }
180
181         if let ty::Ref(_, ty, Mutability::Not) = ty.kind() {
182             if is_type_diagnostic_item(cx, ty, sym::vec_type) {
183                 if let Some(spans) = get_spans(cx, opt_body_id, idx, &[("clone", ".to_owned()")]) {
184                     span_lint_and_then(
185                         cx,
186                         PTR_ARG,
187                         arg.span,
188                         "writing `&Vec<_>` instead of `&[_]` involves one more reference and cannot be used \
189                          with non-Vec-based slices",
190                         |diag| {
191                             if let Some(ref snippet) = get_only_generic_arg_snippet(cx, arg) {
192                                 diag.span_suggestion(
193                                     arg.span,
194                                     "change this to",
195                                     format!("&[{}]", snippet),
196                                     Applicability::Unspecified,
197                                 );
198                             }
199                             for (clonespan, suggestion) in spans {
200                                 diag.span_suggestion(
201                                     clonespan,
202                                     &snippet_opt(cx, clonespan).map_or("change the call to".into(), |x| {
203                                         Cow::Owned(format!("change `{}` to", x))
204                                     }),
205                                     suggestion.into(),
206                                     Applicability::Unspecified,
207                                 );
208                             }
209                         },
210                     );
211                 }
212             } else if is_type_diagnostic_item(cx, ty, sym::string_type) {
213                 if let Some(spans) = get_spans(cx, opt_body_id, idx, &[("clone", ".to_string()"), ("as_str", "")]) {
214                     span_lint_and_then(
215                         cx,
216                         PTR_ARG,
217                         arg.span,
218                         "writing `&String` instead of `&str` involves a new object where a slice will do",
219                         |diag| {
220                             diag.span_suggestion(arg.span, "change this to", "&str".into(), Applicability::Unspecified);
221                             for (clonespan, suggestion) in spans {
222                                 diag.span_suggestion_short(
223                                     clonespan,
224                                     &snippet_opt(cx, clonespan).map_or("change the call to".into(), |x| {
225                                         Cow::Owned(format!("change `{}` to", x))
226                                     }),
227                                     suggestion.into(),
228                                     Applicability::Unspecified,
229                                 );
230                             }
231                         },
232                     );
233                 }
234             } else if is_type_diagnostic_item(cx, ty, sym::PathBuf) {
235                 if let Some(spans) = get_spans(cx, opt_body_id, idx, &[("clone", ".to_path_buf()"), ("as_path", "")]) {
236                     span_lint_and_then(
237                         cx,
238                         PTR_ARG,
239                         arg.span,
240                         "writing `&PathBuf` instead of `&Path` involves a new object where a slice will do",
241                         |diag| {
242                             diag.span_suggestion(
243                                 arg.span,
244                                 "change this to",
245                                 "&Path".into(),
246                                 Applicability::Unspecified,
247                             );
248                             for (clonespan, suggestion) in spans {
249                                 diag.span_suggestion_short(
250                                     clonespan,
251                                     &snippet_opt(cx, clonespan).map_or("change the call to".into(), |x| {
252                                         Cow::Owned(format!("change `{}` to", x))
253                                     }),
254                                     suggestion.into(),
255                                     Applicability::Unspecified,
256                                 );
257                             }
258                         },
259                     );
260                 }
261             } else if match_type(cx, ty, &paths::COW) {
262                 if_chain! {
263                     if let TyKind::Rptr(_, MutTy { ref ty, ..} ) = arg.kind;
264                     if let TyKind::Path(QPath::Resolved(None, ref pp)) = ty.kind;
265                     if let [ref bx] = *pp.segments;
266                     if let Some(ref params) = bx.args;
267                     if !params.parenthesized;
268                     if let Some(inner) = params.args.iter().find_map(|arg| match arg {
269                         GenericArg::Type(ty) => Some(ty),
270                         _ => None,
271                     });
272                     then {
273                         let replacement = snippet_opt(cx, inner.span);
274                         if let Some(r) = replacement {
275                             span_lint_and_sugg(
276                                 cx,
277                                 PTR_ARG,
278                                 arg.span,
279                                 "using a reference to `Cow` is not recommended",
280                                 "change this to",
281                                 "&".to_owned() + &r,
282                                 Applicability::Unspecified,
283                             );
284                         }
285                     }
286                 }
287             }
288         }
289     }
290
291     if let FnRetTy::Return(ref ty) = decl.output {
292         if let Some((out, Mutability::Mut, _)) = get_rptr_lm(ty) {
293             let mut immutables = vec![];
294             for (_, ref mutbl, ref argspan) in decl
295                 .inputs
296                 .iter()
297                 .filter_map(|ty| get_rptr_lm(ty))
298                 .filter(|&(lt, _, _)| lt.name == out.name)
299             {
300                 if *mutbl == Mutability::Mut {
301                     return;
302                 }
303                 immutables.push(*argspan);
304             }
305             if immutables.is_empty() {
306                 return;
307             }
308             span_lint_and_then(
309                 cx,
310                 MUT_FROM_REF,
311                 ty.span,
312                 "mutable borrow from immutable input(s)",
313                 |diag| {
314                     let ms = MultiSpan::from_spans(immutables);
315                     diag.span_note(ms, "immutable borrow here");
316                 },
317             );
318         }
319     }
320 }
321
322 fn get_only_generic_arg_snippet(cx: &LateContext<'_>, arg: &Ty<'_>) -> Option<String> {
323     if_chain! {
324         if let TyKind::Path(QPath::Resolved(_, ref path)) = walk_ptrs_hir_ty(arg).kind;
325         if let Some(&PathSegment{args: Some(ref parameters), ..}) = path.segments.last();
326         let types: Vec<_> = parameters.args.iter().filter_map(|arg| match arg {
327             GenericArg::Type(ty) => Some(ty),
328             _ => None,
329         }).collect();
330         if types.len() == 1;
331         then {
332             snippet_opt(cx, types[0].span)
333         } else {
334             None
335         }
336     }
337 }
338
339 fn get_rptr_lm<'tcx>(ty: &'tcx Ty<'tcx>) -> Option<(&'tcx Lifetime, Mutability, Span)> {
340     if let TyKind::Rptr(ref lt, ref m) = ty.kind {
341         Some((lt, m.mutbl, ty.span))
342     } else {
343         None
344     }
345 }
346
347 fn is_null_path(expr: &Expr<'_>) -> bool {
348     if let ExprKind::Call(ref pathexp, ref args) = expr.kind {
349         if args.is_empty() {
350             if let ExprKind::Path(ref path) = pathexp.kind {
351                 return match_qpath(path, &paths::PTR_NULL) || match_qpath(path, &paths::PTR_NULL_MUT);
352             }
353         }
354     }
355     false
356 }