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