]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/ptr.rs
Rollup merge of #90202 - matthewjasper:xcrate-hygiene, r=petrochenkov
[rust.git] / src / tools / clippy / clippy_lints / src / ptr.rs
1 //! Checks for usage of  `&Vec[_]` and `&String`.
2
3 use clippy_utils::diagnostics::{span_lint, span_lint_and_sugg, span_lint_and_then};
4 use clippy_utils::ptr::get_spans;
5 use clippy_utils::source::snippet_opt;
6 use clippy_utils::ty::{is_type_diagnostic_item, match_type, walk_ptrs_hir_ty};
7 use clippy_utils::{expr_path_res, is_lint_allowed, match_any_diagnostic_items, paths};
8 use if_chain::if_chain;
9 use rustc_errors::Applicability;
10 use rustc_hir::{
11     BinOpKind, BodyId, Expr, ExprKind, FnDecl, FnRetTy, GenericArg, HirId, Impl, ImplItem, ImplItemKind, Item,
12     ItemKind, 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::symbol::Symbol;
19 use rustc_span::{sym, MultiSpan};
20 use std::borrow::Cow;
21
22 declare_clippy_lint! {
23     /// ### What it does
24     /// This lint checks for function arguments of type `&String`
25     /// or `&Vec` unless the references are mutable. It will also suggest you
26     /// replace `.clone()` calls with the appropriate `.to_owned()`/`to_string()`
27     /// calls.
28     ///
29     /// ### Why is this bad?
30     /// Requiring the argument to be of the specific size
31     /// makes the function less useful for no benefit; slices in the form of `&[T]`
32     /// or `&str` usually suffice and can be obtained from other types, too.
33     ///
34     /// ### Known problems
35     /// The lint does not follow data. So if you have an
36     /// argument `x` and write `let y = x; y.clone()` the lint will not suggest
37     /// changing that `.clone()` to `.to_owned()`.
38     ///
39     /// Other functions called from this function taking a `&String` or `&Vec`
40     /// argument may also fail to compile if you change the argument. Applying
41     /// this lint on them will fix the problem, but they may be in other crates.
42     ///
43     /// One notable example of a function that may cause issues, and which cannot
44     /// easily be changed due to being in the standard library is `Vec::contains`.
45     /// when called on a `Vec<Vec<T>>`. If a `&Vec` is passed to that method then
46     /// it will compile, but if a `&[T]` is passed then it will not compile.
47     ///
48     /// ```ignore
49     /// fn cannot_take_a_slice(v: &Vec<u8>) -> bool {
50     ///     let vec_of_vecs: Vec<Vec<u8>> = some_other_fn();
51     ///
52     ///     vec_of_vecs.contains(v)
53     /// }
54     /// ```
55     ///
56     /// Also there may be `fn(&Vec)`-typed references pointing to your function.
57     /// If you have them, you will get a compiler error after applying this lint's
58     /// suggestions. You then have the choice to undo your changes or change the
59     /// type of the reference.
60     ///
61     /// Note that if the function is part of your public interface, there may be
62     /// other crates referencing it, of which you may not be aware. Carefully
63     /// deprecate the function before applying the lint suggestions in this case.
64     ///
65     /// ### Example
66     /// ```ignore
67     /// // Bad
68     /// fn foo(&Vec<u32>) { .. }
69     ///
70     /// // Good
71     /// fn foo(&[u32]) { .. }
72     /// ```
73     pub PTR_ARG,
74     style,
75     "fn arguments of the type `&Vec<...>` or `&String`, suggesting to use `&[...]` or `&str` instead, respectively"
76 }
77
78 declare_clippy_lint! {
79     /// ### What it does
80     /// This lint checks for equality comparisons with `ptr::null`
81     ///
82     /// ### Why is this bad?
83     /// It's easier and more readable to use the inherent
84     /// `.is_null()`
85     /// method instead
86     ///
87     /// ### Example
88     /// ```ignore
89     /// // Bad
90     /// if x == ptr::null {
91     ///     ..
92     /// }
93     ///
94     /// // Good
95     /// if x.is_null() {
96     ///     ..
97     /// }
98     /// ```
99     pub CMP_NULL,
100     style,
101     "comparing a pointer to a null pointer, suggesting to use `.is_null()` instead"
102 }
103
104 declare_clippy_lint! {
105     /// ### What it does
106     /// This lint checks for functions that take immutable
107     /// references and return mutable ones.
108     ///
109     /// ### Why is this bad?
110     /// This is trivially unsound, as one can create two
111     /// mutable references from the same (immutable!) source.
112     /// This [error](https://github.com/rust-lang/rust/issues/39465)
113     /// actually lead to an interim Rust release 1.15.1.
114     ///
115     /// ### Known problems
116     /// To be on the conservative side, if there's at least one
117     /// mutable reference with the output lifetime, this lint will not trigger.
118     /// In practice, this case is unlikely anyway.
119     ///
120     /// ### Example
121     /// ```ignore
122     /// fn foo(&Foo) -> &mut Bar { .. }
123     /// ```
124     pub MUT_FROM_REF,
125     correctness,
126     "fns that create mutable refs from immutable ref args"
127 }
128
129 declare_clippy_lint! {
130     /// ### What it does
131     /// This lint checks for invalid usages of `ptr::null`.
132     ///
133     /// ### Why is this bad?
134     /// This causes undefined behavior.
135     ///
136     /// ### Example
137     /// ```ignore
138     /// // Bad. Undefined behavior
139     /// unsafe { std::slice::from_raw_parts(ptr::null(), 0); }
140     /// ```
141     ///
142     /// ```ignore
143     /// // Good
144     /// unsafe { std::slice::from_raw_parts(NonNull::dangling().as_ptr(), 0); }
145     /// ```
146     pub INVALID_NULL_PTR_USAGE,
147     correctness,
148     "invalid usage of a null pointer, suggesting `NonNull::dangling()` instead"
149 }
150
151 declare_lint_pass!(Ptr => [PTR_ARG, CMP_NULL, MUT_FROM_REF, INVALID_NULL_PTR_USAGE]);
152
153 impl<'tcx> LateLintPass<'tcx> for Ptr {
154     fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
155         if let ItemKind::Fn(ref sig, _, body_id) = item.kind {
156             check_fn(cx, sig.decl, item.hir_id(), Some(body_id));
157         }
158     }
159
160     fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx ImplItem<'_>) {
161         if let ImplItemKind::Fn(ref sig, body_id) = item.kind {
162             let parent_item = cx.tcx.hir().get_parent_item(item.hir_id());
163             if let Some(Node::Item(it)) = cx.tcx.hir().find(parent_item) {
164                 if let ItemKind::Impl(Impl { of_trait: Some(_), .. }) = it.kind {
165                     return; // ignore trait impls
166                 }
167             }
168             check_fn(cx, sig.decl, item.hir_id(), Some(body_id));
169         }
170     }
171
172     fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
173         if let TraitItemKind::Fn(ref sig, ref trait_method) = item.kind {
174             let body_id = if let TraitFn::Provided(b) = *trait_method {
175                 Some(b)
176             } else {
177                 None
178             };
179             check_fn(cx, sig.decl, item.hir_id(), body_id);
180         }
181     }
182
183     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
184         if let ExprKind::Binary(ref op, l, r) = expr.kind {
185             if (op.node == BinOpKind::Eq || op.node == BinOpKind::Ne) && (is_null_path(cx, l) || is_null_path(cx, r)) {
186                 span_lint(
187                     cx,
188                     CMP_NULL,
189                     expr.span,
190                     "comparing with null is better expressed by the `.is_null()` method",
191                 );
192             }
193         } else {
194             check_invalid_ptr_usage(cx, expr);
195         }
196     }
197 }
198
199 fn check_invalid_ptr_usage<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
200     // (fn_path, arg_indices) - `arg_indices` are the `arg` positions where null would cause U.B.
201     const INVALID_NULL_PTR_USAGE_TABLE: [(&[&str], &[usize]); 16] = [
202         (&paths::SLICE_FROM_RAW_PARTS, &[0]),
203         (&paths::SLICE_FROM_RAW_PARTS_MUT, &[0]),
204         (&paths::PTR_COPY, &[0, 1]),
205         (&paths::PTR_COPY_NONOVERLAPPING, &[0, 1]),
206         (&paths::PTR_READ, &[0]),
207         (&paths::PTR_READ_UNALIGNED, &[0]),
208         (&paths::PTR_READ_VOLATILE, &[0]),
209         (&paths::PTR_REPLACE, &[0]),
210         (&paths::PTR_SLICE_FROM_RAW_PARTS, &[0]),
211         (&paths::PTR_SLICE_FROM_RAW_PARTS_MUT, &[0]),
212         (&paths::PTR_SWAP, &[0, 1]),
213         (&paths::PTR_SWAP_NONOVERLAPPING, &[0, 1]),
214         (&paths::PTR_WRITE, &[0]),
215         (&paths::PTR_WRITE_UNALIGNED, &[0]),
216         (&paths::PTR_WRITE_VOLATILE, &[0]),
217         (&paths::PTR_WRITE_BYTES, &[0]),
218     ];
219
220     if_chain! {
221         if let ExprKind::Call(fun, args) = expr.kind;
222         if let ExprKind::Path(ref qpath) = fun.kind;
223         if let Some(fun_def_id) = cx.qpath_res(qpath, fun.hir_id).opt_def_id();
224         let fun_def_path = cx.get_def_path(fun_def_id).into_iter().map(Symbol::to_ident_string).collect::<Vec<_>>();
225         if let Some(&(_, arg_indices)) = INVALID_NULL_PTR_USAGE_TABLE
226             .iter()
227             .find(|&&(fn_path, _)| fn_path == fun_def_path);
228         then {
229             for &arg_idx in arg_indices {
230                 if let Some(arg) = args.get(arg_idx).filter(|arg| is_null_path(cx, arg)) {
231                     span_lint_and_sugg(
232                         cx,
233                         INVALID_NULL_PTR_USAGE,
234                         arg.span,
235                         "pointer must be non-null",
236                         "change this to",
237                         "core::ptr::NonNull::dangling().as_ptr()".to_string(),
238                         Applicability::MachineApplicable,
239                     );
240                 }
241             }
242         }
243     }
244 }
245
246 #[allow(clippy::too_many_lines)]
247 fn check_fn(cx: &LateContext<'_>, decl: &FnDecl<'_>, fn_id: HirId, opt_body_id: Option<BodyId>) {
248     let fn_def_id = cx.tcx.hir().local_def_id(fn_id);
249     let sig = cx.tcx.fn_sig(fn_def_id);
250     let fn_ty = sig.skip_binder();
251     let body = opt_body_id.map(|id| cx.tcx.hir().body(id));
252
253     for (idx, (arg, ty)) in decl.inputs.iter().zip(fn_ty.inputs()).enumerate() {
254         // Honor the allow attribute on parameters. See issue 5644.
255         if let Some(body) = &body {
256             if is_lint_allowed(cx, PTR_ARG, body.params[idx].hir_id) {
257                 continue;
258             }
259         }
260
261         if let ty::Ref(_, ty, Mutability::Not) = ty.kind() {
262             if is_type_diagnostic_item(cx, ty, sym::Vec) {
263                 if let Some(spans) = get_spans(cx, opt_body_id, idx, &[("clone", ".to_owned()")]) {
264                     span_lint_and_then(
265                         cx,
266                         PTR_ARG,
267                         arg.span,
268                         "writing `&Vec<_>` instead of `&[_]` involves one more reference and cannot be used \
269                          with non-Vec-based slices",
270                         |diag| {
271                             if let Some(ref snippet) = get_only_generic_arg_snippet(cx, arg) {
272                                 diag.span_suggestion(
273                                     arg.span,
274                                     "change this to",
275                                     format!("&[{}]", snippet),
276                                     Applicability::Unspecified,
277                                 );
278                             }
279                             for (clonespan, suggestion) in spans {
280                                 diag.span_suggestion(
281                                     clonespan,
282                                     &snippet_opt(cx, clonespan).map_or("change the call to".into(), |x| {
283                                         Cow::Owned(format!("change `{}` to", x))
284                                     }),
285                                     suggestion.into(),
286                                     Applicability::Unspecified,
287                                 );
288                             }
289                         },
290                     );
291                 }
292             } else if is_type_diagnostic_item(cx, ty, sym::String) {
293                 if let Some(spans) = get_spans(cx, opt_body_id, idx, &[("clone", ".to_string()"), ("as_str", "")]) {
294                     span_lint_and_then(
295                         cx,
296                         PTR_ARG,
297                         arg.span,
298                         "writing `&String` instead of `&str` involves a new object where a slice will do",
299                         |diag| {
300                             diag.span_suggestion(arg.span, "change this to", "&str".into(), Applicability::Unspecified);
301                             for (clonespan, suggestion) in spans {
302                                 diag.span_suggestion_short(
303                                     clonespan,
304                                     &snippet_opt(cx, clonespan).map_or("change the call to".into(), |x| {
305                                         Cow::Owned(format!("change `{}` to", x))
306                                     }),
307                                     suggestion.into(),
308                                     Applicability::Unspecified,
309                                 );
310                             }
311                         },
312                     );
313                 }
314             } else if is_type_diagnostic_item(cx, ty, sym::PathBuf) {
315                 if let Some(spans) = get_spans(cx, opt_body_id, idx, &[("clone", ".to_path_buf()"), ("as_path", "")]) {
316                     span_lint_and_then(
317                         cx,
318                         PTR_ARG,
319                         arg.span,
320                         "writing `&PathBuf` instead of `&Path` involves a new object where a slice will do",
321                         |diag| {
322                             diag.span_suggestion(
323                                 arg.span,
324                                 "change this to",
325                                 "&Path".into(),
326                                 Applicability::Unspecified,
327                             );
328                             for (clonespan, suggestion) in spans {
329                                 diag.span_suggestion_short(
330                                     clonespan,
331                                     &snippet_opt(cx, clonespan).map_or("change the call to".into(), |x| {
332                                         Cow::Owned(format!("change `{}` to", x))
333                                     }),
334                                     suggestion.into(),
335                                     Applicability::Unspecified,
336                                 );
337                             }
338                         },
339                     );
340                 }
341             } else if match_type(cx, ty, &paths::COW) {
342                 if_chain! {
343                     if let TyKind::Rptr(_, MutTy { ty, ..} ) = arg.kind;
344                     if let TyKind::Path(QPath::Resolved(None, pp)) = ty.kind;
345                     if let [ref bx] = *pp.segments;
346                     if let Some(params) = bx.args;
347                     if !params.parenthesized;
348                     if let Some(inner) = params.args.iter().find_map(|arg| match arg {
349                         GenericArg::Type(ty) => Some(ty),
350                         _ => None,
351                     });
352                     let replacement = snippet_opt(cx, inner.span);
353                     if let Some(r) = replacement;
354                     then {
355                         span_lint_and_sugg(
356                             cx,
357                             PTR_ARG,
358                             arg.span,
359                             "using a reference to `Cow` is not recommended",
360                             "change this to",
361                             "&".to_owned() + &r,
362                             Applicability::Unspecified,
363                         );
364                     }
365                 }
366             }
367         }
368     }
369
370     if let FnRetTy::Return(ty) = decl.output {
371         if let Some((out, Mutability::Mut, _)) = get_rptr_lm(ty) {
372             let mut immutables = vec![];
373             for (_, ref mutbl, ref argspan) in decl
374                 .inputs
375                 .iter()
376                 .filter_map(get_rptr_lm)
377                 .filter(|&(lt, _, _)| lt.name == out.name)
378             {
379                 if *mutbl == Mutability::Mut {
380                     return;
381                 }
382                 immutables.push(*argspan);
383             }
384             if immutables.is_empty() {
385                 return;
386             }
387             span_lint_and_then(
388                 cx,
389                 MUT_FROM_REF,
390                 ty.span,
391                 "mutable borrow from immutable input(s)",
392                 |diag| {
393                     let ms = MultiSpan::from_spans(immutables);
394                     diag.span_note(ms, "immutable borrow here");
395                 },
396             );
397         }
398     }
399 }
400
401 fn get_only_generic_arg_snippet(cx: &LateContext<'_>, arg: &Ty<'_>) -> Option<String> {
402     if_chain! {
403         if let TyKind::Path(QPath::Resolved(_, path)) = walk_ptrs_hir_ty(arg).kind;
404         if let Some(&PathSegment{args: Some(parameters), ..}) = path.segments.last();
405         let types: Vec<_> = parameters.args.iter().filter_map(|arg| match arg {
406             GenericArg::Type(ty) => Some(ty),
407             _ => None,
408         }).collect();
409         if types.len() == 1;
410         then {
411             snippet_opt(cx, types[0].span)
412         } else {
413             None
414         }
415     }
416 }
417
418 fn get_rptr_lm<'tcx>(ty: &'tcx Ty<'tcx>) -> Option<(&'tcx Lifetime, Mutability, Span)> {
419     if let TyKind::Rptr(ref lt, ref m) = ty.kind {
420         Some((lt, m.mutbl, ty.span))
421     } else {
422         None
423     }
424 }
425
426 fn is_null_path(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
427     if let ExprKind::Call(pathexp, []) = expr.kind {
428         expr_path_res(cx, pathexp).opt_def_id().map_or(false, |id| {
429             match_any_diagnostic_items(cx, id, &[sym::ptr_null, sym::ptr_null_mut]).is_some()
430         })
431     } else {
432         false
433     }
434 }