]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/ptr.rs
Merge pull request #3269 from rust-lang-nursery/relicense
[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
11 //! Checks for usage of  `&Vec[_]` and `&String`.
12
13 use std::borrow::Cow;
14 use crate::rustc::hir::*;
15 use crate::rustc::hir::QPath;
16 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
17 use crate::rustc::{declare_tool_lint, lint_array};
18 use if_chain::if_chain;
19 use crate::rustc::ty;
20 use crate::syntax::ast::NodeId;
21 use crate::syntax::source_map::Span;
22 use crate::syntax_pos::MultiSpan;
23 use crate::utils::{match_qpath, match_type, paths, snippet_opt, span_lint, span_lint_and_then, walk_ptrs_hir_ty};
24 use crate::utils::ptr::get_spans;
25 use crate::rustc_errors::Applicability;
26
27 /// **What it does:** This lint checks for function arguments of type `&String`
28 /// or `&Vec` unless the references are mutable. It will also suggest you
29 /// replace `.clone()` calls with the appropriate `.to_owned()`/`to_string()`
30 /// calls.
31 ///
32 /// **Why is this bad?** Requiring the argument to be of the specific size
33 /// makes the function less useful for no benefit; slices in the form of `&[T]`
34 /// or `&str` usually suffice and can be obtained from other types, too.
35 ///
36 /// **Known problems:** The lint does not follow data. So if you have an
37 /// argument `x` and write `let y = x; y.clone()` the lint will not suggest
38 /// changing that `.clone()` to `.to_owned()`.
39 ///
40 /// Other functions called from this function taking a `&String` or `&Vec`
41 /// argument may also fail to compile if you change the argument. Applying
42 /// this lint on them will fix the problem, but they may be in other crates.
43 ///
44 /// Also there may be `fn(&Vec)`-typed references pointing to your function.
45 /// If you have them, you will get a compiler error after applying this lint's
46 /// suggestions. You then have the choice to undo your changes or change the
47 /// type of the reference.
48 ///
49 /// Note that if the function is part of your public interface, there may be
50 /// other crates referencing it you may not be aware. Carefully deprecate the
51 /// function before applying the lint suggestions in this case.
52 ///
53 /// **Example:**
54 /// ```rust
55 /// fn foo(&Vec<u32>) { .. }
56 /// ```
57 declare_clippy_lint! {
58     pub PTR_ARG,
59     style,
60     "fn arguments of the type `&Vec<...>` or `&String`, suggesting to use `&[...]` or `&str` \
61      instead, respectively"
62 }
63
64 /// **What it does:** This lint checks for equality comparisons with `ptr::null`
65 ///
66 /// **Why is this bad?** It's easier and more readable to use the inherent
67 /// `.is_null()`
68 /// method instead
69 ///
70 /// **Known problems:** None.
71 ///
72 /// **Example:**
73 /// ```rust
74 /// if x == ptr::null { .. }
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(
166             _,
167             ty,
168             MutImmutable
169         ) = ty.sty
170         {
171             if match_type(cx, ty, &paths::VEC) {
172                 let mut ty_snippet = None;
173                 if_chain! {
174                     if let TyKind::Path(QPath::Resolved(_, ref path)) = walk_ptrs_hir_ty(arg).node;
175                     if let Some(&PathSegment{args: Some(ref parameters), ..}) = path.segments.last();
176                     then {
177                         let types: Vec<_> = parameters.args.iter().filter_map(|arg| match arg {
178                             GenericArg::Type(ty) => Some(ty),
179                             _ => None,
180                         }).collect();
181                         if types.len() == 1 {
182                             ty_snippet = snippet_opt(cx, types[0].span);
183                         }
184                     }
185                 };
186                 if let Some(spans) = get_spans(cx, opt_body_id, idx, &[("clone", ".to_owned()")]) {
187                     span_lint_and_then(
188                         cx,
189                         PTR_ARG,
190                         arg.span,
191                         "writing `&Vec<_>` instead of `&[_]` involves one more reference and cannot be used \
192                          with non-Vec-based slices.",
193                         |db| {
194                             if let Some(ref snippet) = ty_snippet {
195                                 db.span_suggestion_with_applicability(
196                                             arg.span,
197                                             "change this to",
198                                             format!("&[{}]", snippet),
199                                             Applicability::Unspecified,
200                                             );
201                             }
202                             for (clonespan, suggestion) in spans {
203                                 db.span_suggestion_with_applicability(
204                                     clonespan,
205                                     &snippet_opt(cx, clonespan).map_or(
206                                         "change the call to".into(),
207                                         |x| Cow::Owned(format!("change `{}` to", x)),
208                                     ),
209                                     suggestion.into(),
210                                     Applicability::Unspecified,
211                                 );
212                             }
213                         },
214                     );
215                 }
216             } else if match_type(cx, ty, &paths::STRING) {
217                 if let Some(spans) = get_spans(cx, opt_body_id, idx, &[("clone", ".to_string()"), ("as_str", "")]) {
218                     span_lint_and_then(
219                         cx,
220                         PTR_ARG,
221                         arg.span,
222                         "writing `&String` instead of `&str` involves a new object where a slice will do.",
223                         |db| {
224                             db.span_suggestion_with_applicability(
225                                 arg.span,
226                                 "change this to",
227                                 "&str".into(),
228                                 Applicability::Unspecified,
229                             );
230                             for (clonespan, suggestion) in spans {
231                                 db.span_suggestion_short_with_applicability(
232                                     clonespan,
233                                     &snippet_opt(cx, clonespan).map_or(
234                                         "change the call to".into(),
235                                         |x| Cow::Owned(format!("change `{}` to", x)),
236                                     ),
237                                     suggestion.into(),
238                                     Applicability::Unspecified,
239                                 );
240                             }
241                         },
242                     );
243                 }
244             } else if match_type(cx, ty, &paths::COW) {
245                 if_chain! {
246                     if let TyKind::Rptr(_, MutTy { ref ty, ..} ) = arg.node;
247                     if let TyKind::Path(ref path) = ty.node;
248                     if let QPath::Resolved(None, ref pp) = *path;
249                     if let [ref bx] = *pp.segments;
250                     if let Some(ref params) = bx.args;
251                     if !params.parenthesized;
252                     if let Some(inner) = params.args.iter().find_map(|arg| match arg {
253                         GenericArg::Type(ty) => Some(ty),
254                         GenericArg::Lifetime(_) => None,
255                     });
256                     then {
257                         let replacement = snippet_opt(cx, inner.span);
258                         if let Some(r) = replacement {
259                             span_lint_and_then(
260                                 cx,
261                                 PTR_ARG,
262                                 arg.span,
263                                 "using a reference to `Cow` is not recommended.",
264                                 |db| {
265                                     db.span_suggestion_with_applicability(
266                                         arg.span,
267                                         "change this to",
268                                         "&".to_owned() + &r,
269                                         Applicability::Unspecified,
270                                     );
271                                 },
272                             );
273                         }
274                     }
275                 }
276             }
277         }
278     }
279
280     if let FunctionRetTy::Return(ref ty) = decl.output {
281         if let Some((out, MutMutable, _)) = get_rptr_lm(ty) {
282             let mut immutables = vec![];
283             for (_, ref mutbl, ref argspan) in decl.inputs
284                 .iter()
285                 .filter_map(|ty| get_rptr_lm(ty))
286                 .filter(|&(lt, _, _)| lt.name == out.name)
287             {
288                 if *mutbl == MutMutable {
289                     return;
290                 }
291                 immutables.push(*argspan);
292             }
293             if immutables.is_empty() {
294                 return;
295             }
296             span_lint_and_then(cx, MUT_FROM_REF, ty.span, "mutable borrow from immutable input(s)", |db| {
297                 let ms = MultiSpan::from_spans(immutables);
298                 db.span_note(ms, "immutable borrow here");
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 }