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.
11 use crate::consts::constant;
12 use crate::rustc::hir::*;
13 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
14 use crate::rustc::ty::{self, Ty};
15 use crate::rustc::{declare_tool_lint, lint_array};
16 use crate::rustc_errors::Applicability;
17 use crate::syntax::source_map::Span;
18 use crate::utils::{higher, is_copy, snippet_with_applicability, span_lint_and_sugg};
19 use if_chain::if_chain;
21 /// **What it does:** Checks for usage of `&vec![..]` when using `&[..]` would
24 /// **Why is this bad?** This is less efficient.
26 /// **Known problems:** None.
32 declare_clippy_lint! {
38 #[derive(Copy, Clone, Debug)]
41 impl LintPass for Pass {
42 fn get_lints(&self) -> LintArray {
43 lint_array!(USELESS_VEC)
47 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
48 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
49 // search for `&vec![_]` expressions where the adjusted type is `&[_]`
51 if let ty::Ref(_, ty, _) = cx.tables.expr_ty_adjusted(expr).sty;
52 if let ty::Slice(..) = ty.sty;
53 if let ExprKind::AddrOf(_, ref addressee) = expr.node;
54 if let Some(vec_args) = higher::vec_macro(cx, addressee);
56 check_vec_macro(cx, &vec_args, expr.span);
60 // search for `for _ in vec![…]`
62 if let Some((_, arg, _)) = higher::for_loop(expr);
63 if let Some(vec_args) = higher::vec_macro(cx, arg);
64 if is_copy(cx, vec_type(cx.tables.expr_ty_adjusted(arg)));
66 // report the error around the `vec!` not inside `<std macros>:`
71 .map(|info| info.call_site)
72 .expect("unable to get call_site");
73 check_vec_macro(cx, &vec_args, span);
79 fn check_vec_macro<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, vec_args: &higher::VecArgs<'tcx>, span: Span) {
80 let mut applicability = Applicability::MachineApplicable;
81 let snippet = match *vec_args {
82 higher::VecArgs::Repeat(elem, len) => {
83 if constant(cx, cx.tables, len).is_some() {
86 snippet_with_applicability(cx, elem.span, "elem", &mut applicability),
87 snippet_with_applicability(cx, len.span, "len", &mut applicability)
93 higher::VecArgs::Vec(args) => 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))
106 "useless use of `vec!`",
107 "you can use a slice directly",
113 /// Return the item type of the vector (ie. the `T` in `Vec<T>`).
114 fn vec_type(ty: Ty<'_>) -> Ty<'_> {
115 if let ty::Adt(_, substs) = ty.sty {
118 panic!("The type of `vec!` is a not a struct?");