1 //! Checks for usage of `&Vec[_]` and `&String`.
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_allowed, match_any_def_paths, paths};
8 use if_chain::if_chain;
9 use rustc_errors::Applicability;
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,
14 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};
22 declare_clippy_lint! {
23 /// **What it does:** This lint checks for function arguments of type `&String`
24 /// or `&Vec` unless the references are mutable. It will also suggest you
25 /// replace `.clone()` calls with the appropriate `.to_owned()`/`to_string()`
28 /// **Why is this bad?** Requiring the argument to be of the specific size
29 /// makes the function less useful for no benefit; slices in the form of `&[T]`
30 /// or `&str` usually suffice and can be obtained from other types, too.
32 /// **Known problems:** The lint does not follow data. So if you have an
33 /// argument `x` and write `let y = x; y.clone()` the lint will not suggest
34 /// changing that `.clone()` to `.to_owned()`.
36 /// Other functions called from this function taking a `&String` or `&Vec`
37 /// argument may also fail to compile if you change the argument. Applying
38 /// this lint on them will fix the problem, but they may be in other crates.
40 /// One notable example of a function that may cause issues, and which cannot
41 /// easily be changed due to being in the standard library is `Vec::contains`.
42 /// when called on a `Vec<Vec<T>>`. If a `&Vec` is passed to that method then
43 /// it will compile, but if a `&[T]` is passed then it will not compile.
46 /// fn cannot_take_a_slice(v: &Vec<u8>) -> bool {
47 /// let vec_of_vecs: Vec<Vec<u8>> = some_other_fn();
49 /// vec_of_vecs.contains(v)
53 /// Also there may be `fn(&Vec)`-typed references pointing to your function.
54 /// If you have them, you will get a compiler error after applying this lint's
55 /// suggestions. You then have the choice to undo your changes or change the
56 /// type of the reference.
58 /// Note that if the function is part of your public interface, there may be
59 /// other crates referencing it, of which you may not be aware. Carefully
60 /// deprecate the function before applying the lint suggestions in this case.
65 /// fn foo(&Vec<u32>) { .. }
68 /// fn foo(&[u32]) { .. }
72 "fn arguments of the type `&Vec<...>` or `&String`, suggesting to use `&[...]` or `&str` instead, respectively"
75 declare_clippy_lint! {
76 /// **What it does:** This lint checks for equality comparisons with `ptr::null`
78 /// **Why is this bad?** It's easier and more readable to use the inherent
82 /// **Known problems:** None.
87 /// if x == ptr::null {
98 "comparing a pointer to a null pointer, suggesting to use `.is_null()` instead"
101 declare_clippy_lint! {
102 /// **What it does:** This lint checks for functions that take immutable
103 /// references and return mutable ones.
105 /// **Why is this bad?** This is trivially unsound, as one can create two
106 /// mutable references from the same (immutable!) source.
107 /// This [error](https://github.com/rust-lang/rust/issues/39465)
108 /// actually lead to an interim Rust release 1.15.1.
110 /// **Known problems:** To be on the conservative side, if there's at least one
111 /// mutable reference with the output lifetime, this lint will not trigger.
112 /// In practice, this case is unlikely anyway.
116 /// fn foo(&Foo) -> &mut Bar { .. }
120 "fns that create mutable refs from immutable ref args"
123 declare_clippy_lint! {
124 /// **What it does:** This lint checks for invalid usages of `ptr::null`.
126 /// **Why is this bad?** This causes undefined behavior.
128 /// **Known problems:** None.
132 /// // Bad. Undefined behavior
133 /// unsafe { std::slice::from_raw_parts(ptr::null(), 0); }
137 /// unsafe { std::slice::from_raw_parts(NonNull::dangling().as_ptr(), 0); }
139 pub INVALID_NULL_PTR_USAGE,
141 "invalid usage of a null pointer, suggesting `NonNull::dangling()` instead"
144 declare_lint_pass!(Ptr => [PTR_ARG, CMP_NULL, MUT_FROM_REF, INVALID_NULL_PTR_USAGE]);
146 impl<'tcx> LateLintPass<'tcx> for Ptr {
147 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
148 if let ItemKind::Fn(ref sig, _, body_id) = item.kind {
149 check_fn(cx, sig.decl, item.hir_id(), Some(body_id));
153 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx ImplItem<'_>) {
154 if let ImplItemKind::Fn(ref sig, body_id) = item.kind {
155 let parent_item = cx.tcx.hir().get_parent_item(item.hir_id());
156 if let Some(Node::Item(it)) = cx.tcx.hir().find(parent_item) {
157 if let ItemKind::Impl(Impl { of_trait: Some(_), .. }) = it.kind {
158 return; // ignore trait impls
161 check_fn(cx, sig.decl, item.hir_id(), Some(body_id));
165 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
166 if let TraitItemKind::Fn(ref sig, ref trait_method) = item.kind {
167 let body_id = if let TraitFn::Provided(b) = *trait_method {
172 check_fn(cx, sig.decl, item.hir_id(), body_id);
176 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
177 if let ExprKind::Binary(ref op, l, r) = expr.kind {
178 if (op.node == BinOpKind::Eq || op.node == BinOpKind::Ne) && (is_null_path(cx, l) || is_null_path(cx, r)) {
183 "comparing with null is better expressed by the `.is_null()` method",
187 check_invalid_ptr_usage(cx, expr);
192 fn check_invalid_ptr_usage<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
193 // (fn_path, arg_indices) - `arg_indices` are the `arg` positions where null would cause U.B.
194 const INVALID_NULL_PTR_USAGE_TABLE: [(&[&str], &[usize]); 16] = [
195 (&paths::SLICE_FROM_RAW_PARTS, &[0]),
196 (&paths::SLICE_FROM_RAW_PARTS_MUT, &[0]),
197 (&paths::PTR_COPY, &[0, 1]),
198 (&paths::PTR_COPY_NONOVERLAPPING, &[0, 1]),
199 (&paths::PTR_READ, &[0]),
200 (&paths::PTR_READ_UNALIGNED, &[0]),
201 (&paths::PTR_READ_VOLATILE, &[0]),
202 (&paths::PTR_REPLACE, &[0]),
203 (&paths::PTR_SLICE_FROM_RAW_PARTS, &[0]),
204 (&paths::PTR_SLICE_FROM_RAW_PARTS_MUT, &[0]),
205 (&paths::PTR_SWAP, &[0, 1]),
206 (&paths::PTR_SWAP_NONOVERLAPPING, &[0, 1]),
207 (&paths::PTR_WRITE, &[0]),
208 (&paths::PTR_WRITE_UNALIGNED, &[0]),
209 (&paths::PTR_WRITE_VOLATILE, &[0]),
210 (&paths::PTR_WRITE_BYTES, &[0]),
214 if let ExprKind::Call(ref fun, ref args) = expr.kind;
215 if let ExprKind::Path(ref qpath) = fun.kind;
216 if let Some(fun_def_id) = cx.qpath_res(qpath, fun.hir_id).opt_def_id();
217 let fun_def_path = cx.get_def_path(fun_def_id).into_iter().map(Symbol::to_ident_string).collect::<Vec<_>>();
218 if let Some(&(_, arg_indices)) = INVALID_NULL_PTR_USAGE_TABLE
220 .find(|&&(fn_path, _)| fn_path == fun_def_path);
222 for &arg_idx in arg_indices {
223 if let Some(arg) = args.get(arg_idx).filter(|arg| is_null_path(cx, arg)) {
226 INVALID_NULL_PTR_USAGE,
228 "pointer must be non-null",
230 "core::ptr::NonNull::dangling().as_ptr()".to_string(),
231 Applicability::MachineApplicable,
239 #[allow(clippy::too_many_lines)]
240 fn check_fn(cx: &LateContext<'_>, decl: &FnDecl<'_>, fn_id: HirId, opt_body_id: Option<BodyId>) {
241 let fn_def_id = cx.tcx.hir().local_def_id(fn_id);
242 let sig = cx.tcx.fn_sig(fn_def_id);
243 let fn_ty = sig.skip_binder();
244 let body = opt_body_id.map(|id| cx.tcx.hir().body(id));
246 for (idx, (arg, ty)) in decl.inputs.iter().zip(fn_ty.inputs()).enumerate() {
247 // Honor the allow attribute on parameters. See issue 5644.
248 if let Some(body) = &body {
249 if is_allowed(cx, PTR_ARG, body.params[idx].hir_id) {
254 if let ty::Ref(_, ty, Mutability::Not) = ty.kind() {
255 if is_type_diagnostic_item(cx, ty, sym::vec_type) {
256 if let Some(spans) = get_spans(cx, opt_body_id, idx, &[("clone", ".to_owned()")]) {
261 "writing `&Vec<_>` instead of `&[_]` involves one more reference and cannot be used \
262 with non-Vec-based slices",
264 if let Some(ref snippet) = get_only_generic_arg_snippet(cx, arg) {
265 diag.span_suggestion(
268 format!("&[{}]", snippet),
269 Applicability::Unspecified,
272 for (clonespan, suggestion) in spans {
273 diag.span_suggestion(
275 &snippet_opt(cx, clonespan).map_or("change the call to".into(), |x| {
276 Cow::Owned(format!("change `{}` to", x))
279 Applicability::Unspecified,
285 } else if is_type_diagnostic_item(cx, ty, sym::string_type) {
286 if let Some(spans) = get_spans(cx, opt_body_id, idx, &[("clone", ".to_string()"), ("as_str", "")]) {
291 "writing `&String` instead of `&str` involves a new object where a slice will do",
293 diag.span_suggestion(arg.span, "change this to", "&str".into(), Applicability::Unspecified);
294 for (clonespan, suggestion) in spans {
295 diag.span_suggestion_short(
297 &snippet_opt(cx, clonespan).map_or("change the call to".into(), |x| {
298 Cow::Owned(format!("change `{}` to", x))
301 Applicability::Unspecified,
307 } else if is_type_diagnostic_item(cx, ty, sym::PathBuf) {
308 if let Some(spans) = get_spans(cx, opt_body_id, idx, &[("clone", ".to_path_buf()"), ("as_path", "")]) {
313 "writing `&PathBuf` instead of `&Path` involves a new object where a slice will do",
315 diag.span_suggestion(
319 Applicability::Unspecified,
321 for (clonespan, suggestion) in spans {
322 diag.span_suggestion_short(
324 &snippet_opt(cx, clonespan).map_or("change the call to".into(), |x| {
325 Cow::Owned(format!("change `{}` to", x))
328 Applicability::Unspecified,
334 } else if match_type(cx, ty, &paths::COW) {
336 if let TyKind::Rptr(_, MutTy { ty, ..} ) = arg.kind;
337 if let TyKind::Path(QPath::Resolved(None, pp)) = ty.kind;
338 if let [ref bx] = *pp.segments;
339 if let Some(params) = bx.args;
340 if !params.parenthesized;
341 if let Some(inner) = params.args.iter().find_map(|arg| match arg {
342 GenericArg::Type(ty) => Some(ty),
345 let replacement = snippet_opt(cx, inner.span);
346 if let Some(r) = replacement;
352 "using a reference to `Cow` is not recommended",
355 Applicability::Unspecified,
363 if let FnRetTy::Return(ty) = decl.output {
364 if let Some((out, Mutability::Mut, _)) = get_rptr_lm(ty) {
365 let mut immutables = vec![];
366 for (_, ref mutbl, ref argspan) in decl
369 .filter_map(|ty| get_rptr_lm(ty))
370 .filter(|&(lt, _, _)| lt.name == out.name)
372 if *mutbl == Mutability::Mut {
375 immutables.push(*argspan);
377 if immutables.is_empty() {
384 "mutable borrow from immutable input(s)",
386 let ms = MultiSpan::from_spans(immutables);
387 diag.span_note(ms, "immutable borrow here");
394 fn get_only_generic_arg_snippet(cx: &LateContext<'_>, arg: &Ty<'_>) -> Option<String> {
396 if let TyKind::Path(QPath::Resolved(_, path)) = walk_ptrs_hir_ty(arg).kind;
397 if let Some(&PathSegment{args: Some(parameters), ..}) = path.segments.last();
398 let types: Vec<_> = parameters.args.iter().filter_map(|arg| match arg {
399 GenericArg::Type(ty) => Some(ty),
404 snippet_opt(cx, types[0].span)
411 fn get_rptr_lm<'tcx>(ty: &'tcx Ty<'tcx>) -> Option<(&'tcx Lifetime, Mutability, Span)> {
412 if let TyKind::Rptr(ref lt, ref m) = ty.kind {
413 Some((lt, m.mutbl, ty.span))
419 fn is_null_path(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
420 if let ExprKind::Call(pathexp, []) = expr.kind {
421 expr_path_res(cx, pathexp).opt_def_id().map_or(false, |id| {
422 match_any_def_paths(cx, id, &[&paths::PTR_NULL, &paths::PTR_NULL_MUT]).is_some()