]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/ptr.rs
Rollup merge of #75994 - mental32:impl-rc-new-cyclic, r=KodrAus
[rust.git] / src / tools / clippy / 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_allowed, 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     /// One notable example of a function that may cause issues, and which cannot
40     /// easily be changed due to being in the standard library is `Vec::contains`.
41     /// when called on a `Vec<Vec<T>>`. If a `&Vec` is passed to that method then
42     /// it will compile, but if a `&[T]` is passed then it will not compile.
43     ///
44     /// ```ignore
45     /// fn cannot_take_a_slice(v: &Vec<u8>) -> bool {
46     ///     let vec_of_vecs: Vec<Vec<u8>> = some_other_fn();
47     ///
48     ///     vec_of_vecs.contains(v)
49     /// }
50     /// ```
51     ///
52     /// Also there may be `fn(&Vec)`-typed references pointing to your function.
53     /// If you have them, you will get a compiler error after applying this lint's
54     /// suggestions. You then have the choice to undo your changes or change the
55     /// type of the reference.
56     ///
57     /// Note that if the function is part of your public interface, there may be
58     /// other crates referencing it, of which you may not be aware. Carefully
59     /// deprecate the function before applying the lint suggestions in this case.
60     ///
61     /// **Example:**
62     /// ```ignore
63     /// // Bad
64     /// fn foo(&Vec<u32>) { .. }
65     ///
66     /// // Good
67     /// fn foo(&[u32]) { .. }
68     /// ```
69     pub PTR_ARG,
70     style,
71     "fn arguments of the type `&Vec<...>` or `&String`, suggesting to use `&[...]` or `&str` instead, respectively"
72 }
73
74 declare_clippy_lint! {
75     /// **What it does:** This lint checks for equality comparisons with `ptr::null`
76     ///
77     /// **Why is this bad?** It's easier and more readable to use the inherent
78     /// `.is_null()`
79     /// method instead
80     ///
81     /// **Known problems:** None.
82     ///
83     /// **Example:**
84     /// ```ignore
85     /// // Bad
86     /// if x == ptr::null {
87     ///     ..
88     /// }
89     ///
90     /// // Good
91     /// if x.is_null() {
92     ///     ..
93     /// }
94     /// ```
95     pub CMP_NULL,
96     style,
97     "comparing a pointer to a null pointer, suggesting to use `.is_null()` instead."
98 }
99
100 declare_clippy_lint! {
101     /// **What it does:** This lint checks for functions that take immutable
102     /// references and return mutable ones.
103     ///
104     /// **Why is this bad?** This is trivially unsound, as one can create two
105     /// mutable references from the same (immutable!) source.
106     /// This [error](https://github.com/rust-lang/rust/issues/39465)
107     /// actually lead to an interim Rust release 1.15.1.
108     ///
109     /// **Known problems:** To be on the conservative side, if there's at least one
110     /// mutable reference with the output lifetime, this lint will not trigger.
111     /// In practice, this case is unlikely anyway.
112     ///
113     /// **Example:**
114     /// ```ignore
115     /// fn foo(&Foo) -> &mut Bar { .. }
116     /// ```
117     pub MUT_FROM_REF,
118     correctness,
119     "fns that create mutable refs from immutable ref args"
120 }
121
122 declare_lint_pass!(Ptr => [PTR_ARG, CMP_NULL, MUT_FROM_REF]);
123
124 impl<'tcx> LateLintPass<'tcx> for Ptr {
125     fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
126         if let ItemKind::Fn(ref sig, _, body_id) = item.kind {
127             check_fn(cx, &sig.decl, item.hir_id, Some(body_id));
128         }
129     }
130
131     fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx ImplItem<'_>) {
132         if let ImplItemKind::Fn(ref sig, body_id) = item.kind {
133             let parent_item = cx.tcx.hir().get_parent_item(item.hir_id);
134             if let Some(Node::Item(it)) = cx.tcx.hir().find(parent_item) {
135                 if let ItemKind::Impl { of_trait: Some(_), .. } = it.kind {
136                     return; // ignore trait impls
137                 }
138             }
139             check_fn(cx, &sig.decl, item.hir_id, Some(body_id));
140         }
141     }
142
143     fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
144         if let TraitItemKind::Fn(ref sig, ref trait_method) = item.kind {
145             let body_id = if let TraitFn::Provided(b) = *trait_method {
146                 Some(b)
147             } else {
148                 None
149             };
150             check_fn(cx, &sig.decl, item.hir_id, body_id);
151         }
152     }
153
154     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
155         if let ExprKind::Binary(ref op, ref l, ref r) = expr.kind {
156             if (op.node == BinOpKind::Eq || op.node == BinOpKind::Ne) && (is_null_path(l) || is_null_path(r)) {
157                 span_lint(
158                     cx,
159                     CMP_NULL,
160                     expr.span,
161                     "comparing with null is better expressed by the `.is_null()` method",
162                 );
163             }
164         }
165     }
166 }
167
168 #[allow(clippy::too_many_lines)]
169 fn check_fn(cx: &LateContext<'_>, decl: &FnDecl<'_>, fn_id: HirId, opt_body_id: Option<BodyId>) {
170     let fn_def_id = cx.tcx.hir().local_def_id(fn_id);
171     let sig = cx.tcx.fn_sig(fn_def_id);
172     let fn_ty = sig.skip_binder();
173     let body = opt_body_id.map(|id| cx.tcx.hir().body(id));
174
175     for (idx, (arg, ty)) in decl.inputs.iter().zip(fn_ty.inputs()).enumerate() {
176         // Honor the allow attribute on parameters. See issue 5644.
177         if let Some(body) = &body {
178             if is_allowed(cx, PTR_ARG, body.params[idx].hir_id) {
179                 continue;
180             }
181         }
182
183         if let ty::Ref(_, ty, Mutability::Not) = ty.kind() {
184             if is_type_diagnostic_item(cx, ty, sym!(vec_type)) {
185                 let mut ty_snippet = None;
186                 if_chain! {
187                     if let TyKind::Path(QPath::Resolved(_, ref path)) = walk_ptrs_hir_ty(arg).kind;
188                     if let Some(&PathSegment{args: Some(ref parameters), ..}) = path.segments.last();
189                     then {
190                         let types: Vec<_> = parameters.args.iter().filter_map(|arg| match arg {
191                             GenericArg::Type(ty) => Some(ty),
192                             _ => None,
193                         }).collect();
194                         if types.len() == 1 {
195                             ty_snippet = snippet_opt(cx, types[0].span);
196                         }
197                     }
198                 };
199                 if let Some(spans) = get_spans(cx, opt_body_id, idx, &[("clone", ".to_owned()")]) {
200                     span_lint_and_then(
201                         cx,
202                         PTR_ARG,
203                         arg.span,
204                         "writing `&Vec<_>` instead of `&[_]` involves one more reference and cannot be used \
205                          with non-Vec-based slices.",
206                         |diag| {
207                             if let Some(ref snippet) = ty_snippet {
208                                 diag.span_suggestion(
209                                     arg.span,
210                                     "change this to",
211                                     format!("&[{}]", snippet),
212                                     Applicability::Unspecified,
213                                 );
214                             }
215                             for (clonespan, suggestion) in spans {
216                                 diag.span_suggestion(
217                                     clonespan,
218                                     &snippet_opt(cx, clonespan).map_or("change the call to".into(), |x| {
219                                         Cow::Owned(format!("change `{}` to", x))
220                                     }),
221                                     suggestion.into(),
222                                     Applicability::Unspecified,
223                                 );
224                             }
225                         },
226                     );
227                 }
228             } else if is_type_diagnostic_item(cx, ty, sym!(string_type)) {
229                 if let Some(spans) = get_spans(cx, opt_body_id, idx, &[("clone", ".to_string()"), ("as_str", "")]) {
230                     span_lint_and_then(
231                         cx,
232                         PTR_ARG,
233                         arg.span,
234                         "writing `&String` instead of `&str` involves a new object where a slice will do.",
235                         |diag| {
236                             diag.span_suggestion(arg.span, "change this to", "&str".into(), Applicability::Unspecified);
237                             for (clonespan, suggestion) in spans {
238                                 diag.span_suggestion_short(
239                                     clonespan,
240                                     &snippet_opt(cx, clonespan).map_or("change the call to".into(), |x| {
241                                         Cow::Owned(format!("change `{}` to", x))
242                                     }),
243                                     suggestion.into(),
244                                     Applicability::Unspecified,
245                                 );
246                             }
247                         },
248                     );
249                 }
250             } else if match_type(cx, ty, &paths::COW) {
251                 if_chain! {
252                     if let TyKind::Rptr(_, MutTy { ref ty, ..} ) = arg.kind;
253                     if let TyKind::Path(ref path) = ty.kind;
254                     if let QPath::Resolved(None, ref pp) = *path;
255                     if let [ref bx] = *pp.segments;
256                     if let Some(ref params) = bx.args;
257                     if !params.parenthesized;
258                     if let Some(inner) = params.args.iter().find_map(|arg| match arg {
259                         GenericArg::Type(ty) => Some(ty),
260                         _ => None,
261                     });
262                     then {
263                         let replacement = snippet_opt(cx, inner.span);
264                         if let Some(r) = replacement {
265                             span_lint_and_sugg(
266                                 cx,
267                                 PTR_ARG,
268                                 arg.span,
269                                 "using a reference to `Cow` is not recommended.",
270                                 "change this to",
271                                 "&".to_owned() + &r,
272                                 Applicability::Unspecified,
273                             );
274                         }
275                     }
276                 }
277             }
278         }
279     }
280
281     if let FnRetTy::Return(ref ty) = decl.output {
282         if let Some((out, Mutability::Mut, _)) = get_rptr_lm(ty) {
283             let mut immutables = vec![];
284             for (_, ref mutbl, ref argspan) in decl
285                 .inputs
286                 .iter()
287                 .filter_map(|ty| get_rptr_lm(ty))
288                 .filter(|&(lt, _, _)| lt.name == out.name)
289             {
290                 if *mutbl == Mutability::Mut {
291                     return;
292                 }
293                 immutables.push(*argspan);
294             }
295             if immutables.is_empty() {
296                 return;
297             }
298             span_lint_and_then(
299                 cx,
300                 MUT_FROM_REF,
301                 ty.span,
302                 "mutable borrow from immutable input(s)",
303                 |diag| {
304                     let ms = MultiSpan::from_spans(immutables);
305                     diag.span_note(ms, "immutable borrow here");
306                 },
307             );
308         }
309     }
310 }
311
312 fn get_rptr_lm<'tcx>(ty: &'tcx Ty<'tcx>) -> Option<(&'tcx Lifetime, Mutability, Span)> {
313     if let TyKind::Rptr(ref lt, ref m) = ty.kind {
314         Some((lt, m.mutbl, ty.span))
315     } else {
316         None
317     }
318 }
319
320 fn is_null_path(expr: &Expr<'_>) -> bool {
321     if let ExprKind::Call(ref pathexp, ref args) = expr.kind {
322         if args.is_empty() {
323             if let ExprKind::Path(ref path) = pathexp.kind {
324                 return match_qpath(path, &paths::PTR_NULL) || match_qpath(path, &paths::PTR_NULL_MUT);
325             }
326         }
327     }
328     false
329 }