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