1 use crate::consts::constant;
2 use crate::utils::{higher, is_copy, snippet_with_applicability, span_lint_and_sugg};
3 use if_chain::if_chain;
4 use rustc_errors::Applicability;
5 use rustc_hir::{BorrowKind, Expr, ExprKind};
6 use rustc_lint::{LateContext, LateLintPass};
7 use rustc_middle::ty::{self, Ty};
8 use rustc_session::{declare_lint_pass, declare_tool_lint};
9 use rustc_span::source_map::Span;
11 declare_clippy_lint! {
12 /// **What it does:** Checks for usage of `&vec![..]` when using `&[..]` would
15 /// **Why is this bad?** This is less efficient.
17 /// **Known problems:** None.
21 /// # fn foo(my_vec: &[u8]) {}
34 declare_lint_pass!(UselessVec => [USELESS_VEC]);
36 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UselessVec {
37 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
38 // search for `&vec![_]` expressions where the adjusted type is `&[_]`
40 if let ty::Ref(_, ty, _) = cx.tables.expr_ty_adjusted(expr).kind;
41 if let ty::Slice(..) = ty.kind;
42 if let ExprKind::AddrOf(BorrowKind::Ref, _, ref addressee) = expr.kind;
43 if let Some(vec_args) = higher::vec_macro(cx, addressee);
45 check_vec_macro(cx, &vec_args, expr.span);
49 // search for `for _ in vec![…]`
51 if let Some((_, arg, _)) = higher::for_loop(expr);
52 if let Some(vec_args) = higher::vec_macro(cx, arg);
53 if is_copy(cx, vec_type(cx.tables.expr_ty_adjusted(arg)));
55 // report the error around the `vec!` not inside `<std macros>:`
63 check_vec_macro(cx, &vec_args, span);
69 fn check_vec_macro<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, vec_args: &higher::VecArgs<'tcx>, span: Span) {
70 let mut applicability = Applicability::MachineApplicable;
71 let snippet = match *vec_args {
72 higher::VecArgs::Repeat(elem, len) => {
73 if constant(cx, cx.tables, len).is_some() {
76 snippet_with_applicability(cx, elem.span, "elem", &mut applicability),
77 snippet_with_applicability(cx, len.span, "len", &mut applicability)
83 higher::VecArgs::Vec(args) => {
84 if let Some(last) = args.iter().last() {
85 let span = args[0].span.to(last.span);
87 format!("&[{}]", snippet_with_applicability(cx, span, "..", &mut applicability))
98 "useless use of `vec!`",
99 "you can use a slice directly",
105 /// Returns the item type of the vector (i.e., the `T` in `Vec<T>`).
106 fn vec_type(ty: Ty<'_>) -> Ty<'_> {
107 if let ty::Adt(_, substs) = ty.kind {
110 panic!("The type of `vec!` is a not a struct?");