]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/ptr.rs
Rollup merge of #92586 - esp-rs:bugfix/allocation-alignment-espidf, r=yaahc
[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::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::def::Res;
11 use rustc_hir::{
12     BinOpKind, BodyId, Expr, ExprKind, FnDecl, FnRetTy, GenericArg, Impl, ImplItem, ImplItemKind, Item, ItemKind,
13     Lifetime, MutTy, Mutability, Node, PathSegment, QPath, TraitFn, TraitItem, TraitItemKind, Ty, TyKind,
14 };
15 use rustc_lint::{LateContext, LateLintPass};
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     #[clippy::version = "pre 1.29.0"]
74     pub PTR_ARG,
75     style,
76     "fn arguments of the type `&Vec<...>` or `&String`, suggesting to use `&[...]` or `&str` instead, respectively"
77 }
78
79 declare_clippy_lint! {
80     /// ### What it does
81     /// This lint checks for equality comparisons with `ptr::null`
82     ///
83     /// ### Why is this bad?
84     /// It's easier and more readable to use the inherent
85     /// `.is_null()`
86     /// method instead
87     ///
88     /// ### Example
89     /// ```ignore
90     /// // Bad
91     /// if x == ptr::null {
92     ///     ..
93     /// }
94     ///
95     /// // Good
96     /// if x.is_null() {
97     ///     ..
98     /// }
99     /// ```
100     #[clippy::version = "pre 1.29.0"]
101     pub CMP_NULL,
102     style,
103     "comparing a pointer to a null pointer, suggesting to use `.is_null()` instead"
104 }
105
106 declare_clippy_lint! {
107     /// ### What it does
108     /// This lint checks for functions that take immutable
109     /// references and return mutable ones.
110     ///
111     /// ### Why is this bad?
112     /// This is trivially unsound, as one can create two
113     /// mutable references from the same (immutable!) source.
114     /// This [error](https://github.com/rust-lang/rust/issues/39465)
115     /// actually lead to an interim Rust release 1.15.1.
116     ///
117     /// ### Known problems
118     /// To be on the conservative side, if there's at least one
119     /// mutable reference with the output lifetime, this lint will not trigger.
120     /// In practice, this case is unlikely anyway.
121     ///
122     /// ### Example
123     /// ```ignore
124     /// fn foo(&Foo) -> &mut Bar { .. }
125     /// ```
126     #[clippy::version = "pre 1.29.0"]
127     pub MUT_FROM_REF,
128     correctness,
129     "fns that create mutable refs from immutable ref args"
130 }
131
132 declare_clippy_lint! {
133     /// ### What it does
134     /// This lint checks for invalid usages of `ptr::null`.
135     ///
136     /// ### Why is this bad?
137     /// This causes undefined behavior.
138     ///
139     /// ### Example
140     /// ```ignore
141     /// // Bad. Undefined behavior
142     /// unsafe { std::slice::from_raw_parts(ptr::null(), 0); }
143     /// ```
144     ///
145     /// ```ignore
146     /// // Good
147     /// unsafe { std::slice::from_raw_parts(NonNull::dangling().as_ptr(), 0); }
148     /// ```
149     #[clippy::version = "1.53.0"]
150     pub INVALID_NULL_PTR_USAGE,
151     correctness,
152     "invalid usage of a null pointer, suggesting `NonNull::dangling()` instead"
153 }
154
155 declare_lint_pass!(Ptr => [PTR_ARG, CMP_NULL, MUT_FROM_REF, INVALID_NULL_PTR_USAGE]);
156
157 impl<'tcx> LateLintPass<'tcx> for Ptr {
158     fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
159         if let ItemKind::Fn(ref sig, _, body_id) = item.kind {
160             check_fn(cx, sig.decl, Some(body_id));
161         }
162     }
163
164     fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx ImplItem<'_>) {
165         if let ImplItemKind::Fn(ref sig, body_id) = item.kind {
166             let parent_item = cx.tcx.hir().get_parent_item(item.hir_id());
167             if let Some(Node::Item(it)) = cx.tcx.hir().find_by_def_id(parent_item) {
168                 if let ItemKind::Impl(Impl { of_trait: Some(_), .. }) = it.kind {
169                     return; // ignore trait impls
170                 }
171             }
172             check_fn(cx, sig.decl, Some(body_id));
173         }
174     }
175
176     fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
177         if let TraitItemKind::Fn(ref sig, ref trait_method) = item.kind {
178             let body_id = if let TraitFn::Provided(b) = *trait_method {
179                 Some(b)
180             } else {
181                 None
182             };
183             check_fn(cx, sig.decl, body_id);
184         }
185     }
186
187     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
188         if let ExprKind::Binary(ref op, l, r) = expr.kind {
189             if (op.node == BinOpKind::Eq || op.node == BinOpKind::Ne) && (is_null_path(cx, l) || is_null_path(cx, r)) {
190                 span_lint(
191                     cx,
192                     CMP_NULL,
193                     expr.span,
194                     "comparing with null is better expressed by the `.is_null()` method",
195                 );
196             }
197         } else {
198             check_invalid_ptr_usage(cx, expr);
199         }
200     }
201 }
202
203 fn check_invalid_ptr_usage<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
204     // (fn_path, arg_indices) - `arg_indices` are the `arg` positions where null would cause U.B.
205     const INVALID_NULL_PTR_USAGE_TABLE: [(&[&str], &[usize]); 16] = [
206         (&paths::SLICE_FROM_RAW_PARTS, &[0]),
207         (&paths::SLICE_FROM_RAW_PARTS_MUT, &[0]),
208         (&paths::PTR_COPY, &[0, 1]),
209         (&paths::PTR_COPY_NONOVERLAPPING, &[0, 1]),
210         (&paths::PTR_READ, &[0]),
211         (&paths::PTR_READ_UNALIGNED, &[0]),
212         (&paths::PTR_READ_VOLATILE, &[0]),
213         (&paths::PTR_REPLACE, &[0]),
214         (&paths::PTR_SLICE_FROM_RAW_PARTS, &[0]),
215         (&paths::PTR_SLICE_FROM_RAW_PARTS_MUT, &[0]),
216         (&paths::PTR_SWAP, &[0, 1]),
217         (&paths::PTR_SWAP_NONOVERLAPPING, &[0, 1]),
218         (&paths::PTR_WRITE, &[0]),
219         (&paths::PTR_WRITE_UNALIGNED, &[0]),
220         (&paths::PTR_WRITE_VOLATILE, &[0]),
221         (&paths::PTR_WRITE_BYTES, &[0]),
222     ];
223
224     if_chain! {
225         if let ExprKind::Call(fun, args) = expr.kind;
226         if let ExprKind::Path(ref qpath) = fun.kind;
227         if let Some(fun_def_id) = cx.qpath_res(qpath, fun.hir_id).opt_def_id();
228         let fun_def_path = cx.get_def_path(fun_def_id).into_iter().map(Symbol::to_ident_string).collect::<Vec<_>>();
229         if let Some(&(_, arg_indices)) = INVALID_NULL_PTR_USAGE_TABLE
230             .iter()
231             .find(|&&(fn_path, _)| fn_path == fun_def_path);
232         then {
233             for &arg_idx in arg_indices {
234                 if let Some(arg) = args.get(arg_idx).filter(|arg| is_null_path(cx, arg)) {
235                     span_lint_and_sugg(
236                         cx,
237                         INVALID_NULL_PTR_USAGE,
238                         arg.span,
239                         "pointer must be non-null",
240                         "change this to",
241                         "core::ptr::NonNull::dangling().as_ptr()".to_string(),
242                         Applicability::MachineApplicable,
243                     );
244                 }
245             }
246         }
247     }
248 }
249
250 #[allow(clippy::too_many_lines)]
251 fn check_fn(cx: &LateContext<'_>, decl: &FnDecl<'_>, opt_body_id: Option<BodyId>) {
252     let body = opt_body_id.map(|id| cx.tcx.hir().body(id));
253
254     for (idx, arg) in decl.inputs.iter().enumerate() {
255         // Honor the allow attribute on parameters. See issue 5644.
256         if let Some(body) = &body {
257             if is_lint_allowed(cx, PTR_ARG, body.params[idx].hir_id) {
258                 continue;
259             }
260         }
261
262         let (item_name, path) = if_chain! {
263             if let TyKind::Rptr(_, MutTy { ty, mutbl: Mutability::Not }) = arg.kind;
264             if let TyKind::Path(QPath::Resolved(_, path)) = ty.kind;
265             if let Res::Def(_, did) = path.res;
266             if let Some(item_name) = cx.tcx.get_diagnostic_name(did);
267             then {
268                 (item_name, path)
269             } else {
270                 continue
271             }
272         };
273
274         match item_name {
275             sym::Vec => {
276                 if let Some(spans) = get_spans(cx, opt_body_id, idx, &[("clone", ".to_owned()")]) {
277                     span_lint_and_then(
278                         cx,
279                         PTR_ARG,
280                         arg.span,
281                         "writing `&Vec<_>` instead of `&[_]` involves one more reference and cannot be used \
282                          with non-Vec-based slices",
283                         |diag| {
284                             if let Some(ref snippet) = get_only_generic_arg_snippet(cx, arg) {
285                                 diag.span_suggestion(
286                                     arg.span,
287                                     "change this to",
288                                     format!("&[{}]", snippet),
289                                     Applicability::Unspecified,
290                                 );
291                             }
292                             for (clonespan, suggestion) in spans {
293                                 diag.span_suggestion(
294                                     clonespan,
295                                     &snippet_opt(cx, clonespan).map_or("change the call to".into(), |x| {
296                                         Cow::Owned(format!("change `{}` to", x))
297                                     }),
298                                     suggestion.into(),
299                                     Applicability::Unspecified,
300                                 );
301                             }
302                         },
303                     );
304                 }
305             },
306             sym::String => {
307                 if let Some(spans) = get_spans(cx, opt_body_id, idx, &[("clone", ".to_string()"), ("as_str", "")]) {
308                     span_lint_and_then(
309                         cx,
310                         PTR_ARG,
311                         arg.span,
312                         "writing `&String` instead of `&str` involves a new object where a slice will do",
313                         |diag| {
314                             diag.span_suggestion(arg.span, "change this to", "&str".into(), Applicability::Unspecified);
315                             for (clonespan, suggestion) in spans {
316                                 diag.span_suggestion_short(
317                                     clonespan,
318                                     &snippet_opt(cx, clonespan).map_or("change the call to".into(), |x| {
319                                         Cow::Owned(format!("change `{}` to", x))
320                                     }),
321                                     suggestion.into(),
322                                     Applicability::Unspecified,
323                                 );
324                             }
325                         },
326                     );
327                 }
328             },
329             sym::PathBuf => {
330                 if let Some(spans) = get_spans(cx, opt_body_id, idx, &[("clone", ".to_path_buf()"), ("as_path", "")]) {
331                     span_lint_and_then(
332                         cx,
333                         PTR_ARG,
334                         arg.span,
335                         "writing `&PathBuf` instead of `&Path` involves a new object where a slice will do",
336                         |diag| {
337                             diag.span_suggestion(
338                                 arg.span,
339                                 "change this to",
340                                 "&Path".into(),
341                                 Applicability::Unspecified,
342                             );
343                             for (clonespan, suggestion) in spans {
344                                 diag.span_suggestion_short(
345                                     clonespan,
346                                     &snippet_opt(cx, clonespan).map_or("change the call to".into(), |x| {
347                                         Cow::Owned(format!("change `{}` to", x))
348                                     }),
349                                     suggestion.into(),
350                                     Applicability::Unspecified,
351                                 );
352                             }
353                         },
354                     );
355                 }
356             },
357             sym::Cow => {
358                 if_chain! {
359                     if let [ref bx] = *path.segments;
360                     if let Some(params) = bx.args;
361                     if !params.parenthesized;
362                     if let Some(inner) = params.args.iter().find_map(|arg| match arg {
363                         GenericArg::Type(ty) => Some(ty),
364                         _ => None,
365                     });
366                     let replacement = snippet_opt(cx, inner.span);
367                     if let Some(r) = replacement;
368                     then {
369                         span_lint_and_sugg(
370                             cx,
371                             PTR_ARG,
372                             arg.span,
373                             "using a reference to `Cow` is not recommended",
374                             "change this to",
375                             "&".to_owned() + &r,
376                             Applicability::Unspecified,
377                         );
378                     }
379                 }
380             },
381             _ => {},
382         }
383     }
384
385     if let FnRetTy::Return(ty) = decl.output {
386         if let Some((out, Mutability::Mut, _)) = get_rptr_lm(ty) {
387             let mut immutables = vec![];
388             for (_, ref mutbl, ref argspan) in decl
389                 .inputs
390                 .iter()
391                 .filter_map(get_rptr_lm)
392                 .filter(|&(lt, _, _)| lt.name == out.name)
393             {
394                 if *mutbl == Mutability::Mut {
395                     return;
396                 }
397                 immutables.push(*argspan);
398             }
399             if immutables.is_empty() {
400                 return;
401             }
402             span_lint_and_then(
403                 cx,
404                 MUT_FROM_REF,
405                 ty.span,
406                 "mutable borrow from immutable input(s)",
407                 |diag| {
408                     let ms = MultiSpan::from_spans(immutables);
409                     diag.span_note(ms, "immutable borrow here");
410                 },
411             );
412         }
413     }
414 }
415
416 fn get_only_generic_arg_snippet(cx: &LateContext<'_>, arg: &Ty<'_>) -> Option<String> {
417     if_chain! {
418         if let TyKind::Path(QPath::Resolved(_, path)) = walk_ptrs_hir_ty(arg).kind;
419         if let Some(&PathSegment{args: Some(parameters), ..}) = path.segments.last();
420         let types: Vec<_> = parameters.args.iter().filter_map(|arg| match arg {
421             GenericArg::Type(ty) => Some(ty),
422             _ => None,
423         }).collect();
424         if types.len() == 1;
425         then {
426             snippet_opt(cx, types[0].span)
427         } else {
428             None
429         }
430     }
431 }
432
433 fn get_rptr_lm<'tcx>(ty: &'tcx Ty<'tcx>) -> Option<(&'tcx Lifetime, Mutability, Span)> {
434     if let TyKind::Rptr(ref lt, ref m) = ty.kind {
435         Some((lt, m.mutbl, ty.span))
436     } else {
437         None
438     }
439 }
440
441 fn is_null_path(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
442     if let ExprKind::Call(pathexp, []) = expr.kind {
443         expr_path_res(cx, pathexp).opt_def_id().map_or(false, |id| {
444             match_any_diagnostic_items(cx, id, &[sym::ptr_null, sym::ptr_null_mut]).is_some()
445         })
446     } else {
447         false
448     }
449 }