1 use crate::rustc::hir::*;
2 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
3 use crate::rustc::{declare_tool_lint, lint_array};
4 use if_chain::if_chain;
5 use crate::rustc::ty::{self, Ty};
6 use crate::syntax::source_map::Span;
7 use crate::utils::{higher, is_copy, snippet, span_lint_and_sugg};
8 use crate::consts::constant;
10 /// **What it does:** Checks for usage of `&vec![..]` when using `&[..]` would
13 /// **Why is this bad?** This is less efficient.
15 /// **Known problems:** None.
21 declare_clippy_lint! {
27 #[derive(Copy, Clone, Debug)]
30 impl LintPass for Pass {
31 fn get_lints(&self) -> LintArray {
32 lint_array!(USELESS_VEC)
36 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
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).sty;
41 if let ty::Slice(..) = ty.sty;
42 if let ExprKind::AddrOf(_, ref addressee) = expr.node;
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>:`
60 .map(|info| info.call_site)
61 .expect("unable to get call_site");
62 check_vec_macro(cx, &vec_args, span);
68 fn check_vec_macro<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, vec_args: &higher::VecArgs<'tcx>, span: Span) {
69 let snippet = match *vec_args {
70 higher::VecArgs::Repeat(elem, len) => {
71 if constant(cx, cx.tables, len).is_some() {
72 format!("&[{}; {}]", snippet(cx, elem.span, "elem"), snippet(cx, len.span, "len"))
77 higher::VecArgs::Vec(args) => if let Some(last) = args.iter().last() {
78 let span = args[0].span.to(last.span);
80 format!("&[{}]", snippet(cx, span, ".."))
90 "useless use of `vec!`",
91 "you can use a slice directly",
96 /// Return the item type of the vector (ie. the `T` in `Vec<T>`).
97 fn vec_type(ty: Ty<'_>) -> Ty<'_> {
98 if let ty::Adt(_, substs) = ty.sty {
101 panic!("The type of `vec!` is a not a struct?");