1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
10 use crate::consts::constant;
11 use crate::rustc::hir::*;
12 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
13 use crate::rustc::ty::{self, Ty};
14 use crate::rustc::{declare_tool_lint, lint_array};
15 use crate::rustc_errors::Applicability;
16 use crate::syntax::source_map::Span;
17 use crate::utils::{higher, is_copy, snippet_with_applicability, span_lint_and_sugg};
18 use if_chain::if_chain;
20 /// **What it does:** Checks for usage of `&vec![..]` when using `&[..]` would
23 /// **Why is this bad?** This is less efficient.
25 /// **Known problems:** None.
31 declare_clippy_lint! {
37 #[derive(Copy, Clone, Debug)]
40 impl LintPass for Pass {
41 fn get_lints(&self) -> LintArray {
42 lint_array!(USELESS_VEC)
46 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
47 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
48 // search for `&vec![_]` expressions where the adjusted type is `&[_]`
50 if let ty::Ref(_, ty, _) = cx.tables.expr_ty_adjusted(expr).sty;
51 if let ty::Slice(..) = ty.sty;
52 if let ExprKind::AddrOf(_, ref addressee) = expr.node;
53 if let Some(vec_args) = higher::vec_macro(cx, addressee);
55 check_vec_macro(cx, &vec_args, expr.span);
59 // search for `for _ in vec![…]`
61 if let Some((_, arg, _)) = higher::for_loop(expr);
62 if let Some(vec_args) = higher::vec_macro(cx, arg);
63 if is_copy(cx, vec_type(cx.tables.expr_ty_adjusted(arg)));
65 // report the error around the `vec!` not inside `<std macros>:`
70 .map(|info| info.call_site)
71 .expect("unable to get call_site");
72 check_vec_macro(cx, &vec_args, span);
78 fn check_vec_macro<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, vec_args: &higher::VecArgs<'tcx>, span: Span) {
79 let mut applicability = Applicability::MachineApplicable;
80 let snippet = match *vec_args {
81 higher::VecArgs::Repeat(elem, len) => {
82 if constant(cx, cx.tables, len).is_some() {
85 snippet_with_applicability(cx, elem.span, "elem", &mut applicability),
86 snippet_with_applicability(cx, len.span, "len", &mut applicability)
92 higher::VecArgs::Vec(args) => {
93 if let Some(last) = args.iter().last() {
94 let span = args[0].span.to(last.span);
96 format!("&[{}]", snippet_with_applicability(cx, span, "..", &mut applicability))
107 "useless use of `vec!`",
108 "you can use a slice directly",
114 /// Return the item type of the vector (ie. the `T` in `Vec<T>`).
115 fn vec_type(ty: Ty<'_>) -> Ty<'_> {
116 if let ty::Adt(_, substs) = ty.sty {
119 panic!("The type of `vec!` is a not a struct?");