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