]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/vec.rs
Add applicability level to (nearly) every span_lint_and_sugg function
[rust.git] / clippy_lints / src / vec.rs
1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
3 //
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.
9
10
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;
20
21 /// **What it does:** Checks for usage of `&vec![..]` when using `&[..]` would
22 /// be possible.
23 ///
24 /// **Why is this bad?** This is less efficient.
25 ///
26 /// **Known problems:** None.
27 ///
28 /// **Example:**
29 /// ```rust,ignore
30 /// foo(&vec![1, 2])
31 /// ```
32 declare_clippy_lint! {
33     pub USELESS_VEC,
34     perf,
35     "useless `vec!`"
36 }
37
38 #[derive(Copy, Clone, Debug)]
39 pub struct Pass;
40
41 impl LintPass for Pass {
42     fn get_lints(&self) -> LintArray {
43         lint_array!(USELESS_VEC)
44     }
45 }
46
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 `&[_]`
50         if_chain! {
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);
55             then {
56                 check_vec_macro(cx, &vec_args, expr.span);
57             }
58         }
59
60         // search for `for _ in vec![…]`
61         if_chain! {
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)));
65             then {
66                 // report the error around the `vec!` not inside `<std macros>:`
67                 let span = arg.span
68                     .ctxt()
69                     .outer()
70                     .expn_info()
71                     .map(|info| info.call_site)
72                     .expect("unable to get call_site");
73                 check_vec_macro(cx, &vec_args, span);
74             }
75         }
76     }
77 }
78
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() {
84                 format!(
85                     "&[{}; {}]",
86                     snippet_with_applicability(cx, elem.span, "elem", &mut applicability),
87                     snippet_with_applicability(cx, len.span, "len", &mut applicability)
88                 )
89             } else {
90                 return;
91             }
92         },
93         higher::VecArgs::Vec(args) => if let Some(last) = args.iter().last() {
94             let span = args[0].span.to(last.span);
95
96             format!("&[{}]", snippet_with_applicability(cx, span, "..", &mut applicability))
97         } else {
98             "&[]".into()
99         },
100     };
101
102     span_lint_and_sugg(
103         cx,
104         USELESS_VEC,
105         span,
106         "useless use of `vec!`",
107         "you can use a slice directly",
108         snippet,
109         applicability,
110     );
111 }
112
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 {
116         substs.type_at(0)
117     } else {
118         panic!("The type of `vec!` is a not a struct?");
119     }
120 }