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