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