]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/ptr.rs
Merge pull request #3212 from matthiaskrgr/clippy_dev_ed2018
[rust.git] / clippy_lints / src / ptr.rs
1 //! Checks for usage of  `&Vec[_]` and `&String`.
2
3 use std::borrow::Cow;
4 use crate::rustc::hir::*;
5 use crate::rustc::hir::QPath;
6 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
7 use crate::rustc::{declare_tool_lint, lint_array};
8 use if_chain::if_chain;
9 use crate::rustc::ty;
10 use crate::syntax::ast::NodeId;
11 use crate::syntax::source_map::Span;
12 use crate::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 use crate::rustc_errors::Applicability;
16
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 /// ```rust
45 /// fn foo(&Vec<u32>) { .. }
46 /// ```
47 declare_clippy_lint! {
48     pub PTR_ARG,
49     style,
50     "fn arguments of the type `&Vec<...>` or `&String`, suggesting to use `&[...]` or `&str` \
51      instead, respectively"
52 }
53
54 /// **What it does:** This lint checks for equality comparisons with `ptr::null`
55 ///
56 /// **Why is this bad?** It's easier and more readable to use the inherent
57 /// `.is_null()`
58 /// method instead
59 ///
60 /// **Known problems:** None.
61 ///
62 /// **Example:**
63 /// ```rust
64 /// if x == ptr::null { .. }
65 /// ```
66 declare_clippy_lint! {
67     pub CMP_NULL,
68     style,
69     "comparing a pointer to a null pointer, suggesting to use `.is_null()` instead."
70 }
71
72 /// **What it does:** This lint checks for functions that take immutable
73 /// references and return
74 /// mutable ones.
75 ///
76 /// **Why is this bad?** This is trivially unsound, as one can create two
77 /// mutable references
78 /// from the same (immutable!) source. This
79 /// [error](https://github.com/rust-lang/rust/issues/39465)
80 /// actually lead to an interim Rust release 1.15.1.
81 ///
82 /// **Known problems:** To be on the conservative side, if there's at least one
83 /// mutable reference
84 /// with the output lifetime, this lint will not trigger. In practice, this
85 /// case is unlikely anyway.
86 ///
87 /// **Example:**
88 /// ```rust
89 /// fn foo(&Foo) -> &mut Bar { .. }
90 /// ```
91 declare_clippy_lint! {
92     pub MUT_FROM_REF,
93     correctness,
94     "fns that create mutable refs from immutable ref args"
95 }
96
97 #[derive(Copy, Clone)]
98 pub struct PointerPass;
99
100 impl LintPass for PointerPass {
101     fn get_lints(&self) -> LintArray {
102         lint_array!(PTR_ARG, CMP_NULL, MUT_FROM_REF)
103     }
104 }
105
106 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for PointerPass {
107     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
108         if let ItemKind::Fn(ref decl, _, _, body_id) = item.node {
109             check_fn(cx, decl, item.id, Some(body_id));
110         }
111     }
112
113     fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx ImplItem) {
114         if let ImplItemKind::Method(ref sig, body_id) = item.node {
115             if let Some(Node::Item(it)) = cx.tcx.hir.find(cx.tcx.hir.get_parent(item.id)) {
116                 if let ItemKind::Impl(_, _, _, _, Some(_), _, _) = it.node {
117                     return; // ignore trait impls
118                 }
119             }
120             check_fn(cx, &sig.decl, item.id, Some(body_id));
121         }
122     }
123
124     fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx TraitItem) {
125         if let TraitItemKind::Method(ref sig, ref trait_method) = item.node {
126             let body_id = if let TraitMethod::Provided(b) = *trait_method {
127                 Some(b)
128             } else {
129                 None
130             };
131             check_fn(cx, &sig.decl, item.id, body_id);
132         }
133     }
134
135     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
136         if let ExprKind::Binary(ref op, ref l, ref r) = expr.node {
137             if (op.node == BinOpKind::Eq || op.node == BinOpKind::Ne) && (is_null_path(l) || is_null_path(r)) {
138                 span_lint(
139                     cx,
140                     CMP_NULL,
141                     expr.span,
142                     "Comparing with null is better expressed by the .is_null() method",
143                 );
144             }
145         }
146     }
147 }
148
149 fn check_fn(cx: &LateContext<'_, '_>, decl: &FnDecl, fn_id: NodeId, opt_body_id: Option<BodyId>) {
150     let fn_def_id = cx.tcx.hir.local_def_id(fn_id);
151     let sig = cx.tcx.fn_sig(fn_def_id);
152     let fn_ty = sig.skip_binder();
153
154     for (idx, (arg, ty)) in decl.inputs.iter().zip(fn_ty.inputs()).enumerate() {
155         if let ty::Ref(
156             _,
157             ty,
158             MutImmutable
159         ) = ty.sty
160         {
161             if match_type(cx, ty, &paths::VEC) {
162                 let mut ty_snippet = None;
163                 if_chain! {
164                     if let TyKind::Path(QPath::Resolved(_, ref path)) = walk_ptrs_hir_ty(arg).node;
165                     if let Some(&PathSegment{args: Some(ref parameters), ..}) = path.segments.last();
166                     then {
167                         let types: Vec<_> = parameters.args.iter().filter_map(|arg| match arg {
168                             GenericArg::Type(ty) => Some(ty),
169                             _ => None,
170                         }).collect();
171                         if types.len() == 1 {
172                             ty_snippet = snippet_opt(cx, types[0].span);
173                         }
174                     }
175                 };
176                 if let Some(spans) = get_spans(cx, opt_body_id, idx, &[("clone", ".to_owned()")]) {
177                     span_lint_and_then(
178                         cx,
179                         PTR_ARG,
180                         arg.span,
181                         "writing `&Vec<_>` instead of `&[_]` involves one more reference and cannot be used \
182                          with non-Vec-based slices.",
183                         |db| {
184                             if let Some(ref snippet) = ty_snippet {
185                                 db.span_suggestion_with_applicability(
186                                             arg.span,
187                                             "change this to",
188                                             format!("&[{}]", snippet),
189                                             Applicability::Unspecified,
190                                             );
191                             }
192                             for (clonespan, suggestion) in spans {
193                                 db.span_suggestion_with_applicability(
194                                     clonespan,
195                                     &snippet_opt(cx, clonespan).map_or(
196                                         "change the call to".into(),
197                                         |x| Cow::Owned(format!("change `{}` to", x)),
198                                     ),
199                                     suggestion.into(),
200                                     Applicability::Unspecified,
201                                 );
202                             }
203                         },
204                     );
205                 }
206             } else if match_type(cx, ty, &paths::STRING) {
207                 if let Some(spans) = get_spans(cx, opt_body_id, idx, &[("clone", ".to_string()"), ("as_str", "")]) {
208                     span_lint_and_then(
209                         cx,
210                         PTR_ARG,
211                         arg.span,
212                         "writing `&String` instead of `&str` involves a new object where a slice will do.",
213                         |db| {
214                             db.span_suggestion_with_applicability(
215                                 arg.span,
216                                 "change this to",
217                                 "&str".into(),
218                                 Applicability::Unspecified,
219                             );
220                             for (clonespan, suggestion) in spans {
221                                 db.span_suggestion_short_with_applicability(
222                                     clonespan,
223                                     &snippet_opt(cx, clonespan).map_or(
224                                         "change the call to".into(),
225                                         |x| Cow::Owned(format!("change `{}` to", x)),
226                                     ),
227                                     suggestion.into(),
228                                     Applicability::Unspecified,
229                                 );
230                             }
231                         },
232                     );
233                 }
234             } else if match_type(cx, ty, &paths::COW) {
235                 if_chain! {
236                     if let TyKind::Rptr(_, MutTy { ref ty, ..} ) = arg.node;
237                     if let TyKind::Path(ref path) = ty.node;
238                     if let QPath::Resolved(None, ref pp) = *path;
239                     if let [ref bx] = *pp.segments;
240                     if let Some(ref params) = bx.args;
241                     if !params.parenthesized;
242                     if let Some(inner) = params.args.iter().find_map(|arg| match arg {
243                         GenericArg::Type(ty) => Some(ty),
244                         GenericArg::Lifetime(_) => None,
245                     });
246                     then {
247                         let replacement = snippet_opt(cx, inner.span);
248                         if let Some(r) = replacement {
249                             span_lint_and_then(
250                                 cx,
251                                 PTR_ARG,
252                                 arg.span,
253                                 "using a reference to `Cow` is not recommended.",
254                                 |db| {
255                                     db.span_suggestion_with_applicability(
256                                         arg.span,
257                                         "change this to",
258                                         "&".to_owned() + &r,
259                                         Applicability::Unspecified,
260                                     );
261                                 },
262                             );
263                         }
264                     }
265                 }
266             }
267         }
268     }
269
270     if let FunctionRetTy::Return(ref ty) = decl.output {
271         if let Some((out, MutMutable, _)) = get_rptr_lm(ty) {
272             let mut immutables = vec![];
273             for (_, ref mutbl, ref argspan) in decl.inputs
274                 .iter()
275                 .filter_map(|ty| get_rptr_lm(ty))
276                 .filter(|&(lt, _, _)| lt.name == out.name)
277             {
278                 if *mutbl == MutMutable {
279                     return;
280                 }
281                 immutables.push(*argspan);
282             }
283             if immutables.is_empty() {
284                 return;
285             }
286             span_lint_and_then(cx, MUT_FROM_REF, ty.span, "mutable borrow from immutable input(s)", |db| {
287                 let ms = MultiSpan::from_spans(immutables);
288                 db.span_note(ms, "immutable borrow here");
289             });
290         }
291     }
292 }
293
294 fn get_rptr_lm(ty: &Ty) -> Option<(&Lifetime, Mutability, Span)> {
295     if let TyKind::Rptr(ref lt, ref m) = ty.node {
296         Some((lt, m.mutbl, ty.span))
297     } else {
298         None
299     }
300 }
301
302 fn is_null_path(expr: &Expr) -> bool {
303     if let ExprKind::Call(ref pathexp, ref args) = expr.node {
304         if args.is_empty() {
305             if let ExprKind::Path(ref path) = pathexp.node {
306                 return match_qpath(path, &paths::PTR_NULL) || match_qpath(path, &paths::PTR_NULL_MUT);
307             }
308         }
309     }
310     false
311 }