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