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.
28 declare_lint_pass!(UselessVec => [USELESS_VEC]);
30 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UselessVec {
31 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
32 // search for `&vec![_]` expressions where the adjusted type is `&[_]`
34 if let ty::Ref(_, ty, _) = cx.tables.expr_ty_adjusted(expr).kind;
35 if let ty::Slice(..) = ty.kind;
36 if let ExprKind::AddrOf(BorrowKind::Ref, _, ref addressee) = expr.kind;
37 if let Some(vec_args) = higher::vec_macro(cx, addressee);
39 check_vec_macro(cx, &vec_args, expr.span);
43 // search for `for _ in vec![…]`
45 if let Some((_, arg, _)) = higher::for_loop(expr);
46 if let Some(vec_args) = higher::vec_macro(cx, arg);
47 if is_copy(cx, vec_type(cx.tables.expr_ty_adjusted(arg)));
49 // report the error around the `vec!` not inside `<std macros>:`
57 check_vec_macro(cx, &vec_args, span);
63 fn check_vec_macro<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, vec_args: &higher::VecArgs<'tcx>, span: Span) {
64 let mut applicability = Applicability::MachineApplicable;
65 let snippet = match *vec_args {
66 higher::VecArgs::Repeat(elem, len) => {
67 if constant(cx, cx.tables, len).is_some() {
70 snippet_with_applicability(cx, elem.span, "elem", &mut applicability),
71 snippet_with_applicability(cx, len.span, "len", &mut applicability)
77 higher::VecArgs::Vec(args) => {
78 if let Some(last) = args.iter().last() {
79 let span = args[0].span.to(last.span);
81 format!("&[{}]", snippet_with_applicability(cx, span, "..", &mut applicability))
92 "useless use of `vec!`",
93 "you can use a slice directly",
99 /// Returns the item type of the vector (i.e., the `T` in `Vec<T>`).
100 fn vec_type(ty: Ty<'_>) -> Ty<'_> {
101 if let ty::Adt(_, substs) = ty.kind {
104 panic!("The type of `vec!` is a not a struct?");