]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/attrs.rs
Fix merge issues.
[rust.git] / clippy_lints / src / attrs.rs
1 //! checks for attributes
2
3 use reexport::*;
4 use rustc::lint::*;
5 use rustc::hir::*;
6 use rustc::ty::{self, TyCtxt};
7 use semver::Version;
8 use syntax::ast::{Attribute, Lit, LitKind, MetaItemKind, NestedMetaItem, NestedMetaItemKind};
9 use syntax::codemap::Span;
10 use utils::{in_macro, match_def_path, opt_def_id, paths, snippet_opt, span_lint, span_lint_and_then};
11
12 /// **What it does:** Checks for items annotated with `#[inline(always)]`,
13 /// unless the annotated function is empty or simply panics.
14 ///
15 /// **Why is this bad?** While there are valid uses of this annotation (and once
16 /// you know when to use it, by all means `allow` this lint), it's a common
17 /// newbie-mistake to pepper one's code with it.
18 ///
19 /// As a rule of thumb, before slapping `#[inline(always)]` on a function,
20 /// measure if that additional function call really affects your runtime profile
21 /// sufficiently to make up for the increase in compile time.
22 ///
23 /// **Known problems:** False positives, big time. This lint is meant to be
24 /// deactivated by everyone doing serious performance work. This means having
25 /// done the measurement.
26 ///
27 /// **Example:**
28 /// ```rust
29 /// #[inline(always)]
30 /// fn not_quite_hot_code(..) { ... }
31 /// ```
32 declare_lint! {
33     pub INLINE_ALWAYS,
34     Warn,
35     "use of `#[inline(always)]`"
36 }
37
38 /// **What it does:** Checks for `extern crate` and `use` items annotated with
39 /// lint attributes
40 ///
41 /// **Why is this bad?** Lint attributes have no effect on crate imports. Most
42 /// likely a `!` was
43 /// forgotten
44 ///
45 /// **Known problems:** Technically one might allow `unused_import` on a `use`
46 /// item,
47 /// but it's easier to remove the unused item.
48 ///
49 /// **Example:**
50 /// ```rust
51 /// #[deny(dead_code)]
52 /// extern crate foo;
53 /// #[allow(unused_import)]
54 /// use foo::bar;
55 /// ```
56 declare_lint! {
57     pub USELESS_ATTRIBUTE,
58     Warn,
59     "use of lint attributes on `extern crate` items"
60 }
61
62 /// **What it does:** Checks for `#[deprecated]` annotations with a `since`
63 /// field that is not a valid semantic version.
64 ///
65 /// **Why is this bad?** For checking the version of the deprecation, it must be
66 /// a valid semver. Failing that, the contained information is useless.
67 ///
68 /// **Known problems:** None.
69 ///
70 /// **Example:**
71 /// ```rust
72 /// #[deprecated(since = "forever")]
73 /// fn something_else(..) { ... }
74 /// ```
75 declare_lint! {
76     pub DEPRECATED_SEMVER,
77     Warn,
78     "use of `#[deprecated(since = \"x\")]` where x is not semver"
79 }
80
81 #[derive(Copy, Clone)]
82 pub struct AttrPass;
83
84 impl LintPass for AttrPass {
85     fn get_lints(&self) -> LintArray {
86         lint_array!(INLINE_ALWAYS, DEPRECATED_SEMVER, USELESS_ATTRIBUTE)
87     }
88 }
89
90 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AttrPass {
91     fn check_attribute(&mut self, cx: &LateContext<'a, 'tcx>, attr: &'tcx Attribute) {
92         if let Some(ref items) = attr.meta_item_list() {
93             if items.is_empty() || attr.name().map_or(true, |n| n != "deprecated") {
94                 return;
95             }
96             for item in items {
97                 if_chain! {
98                     if let NestedMetaItemKind::MetaItem(ref mi) = item.node;
99                     if let MetaItemKind::NameValue(ref lit) = mi.node;
100                     if mi.name() == "since";
101                     then {
102                         check_semver(cx, item.span, lit);
103                     }
104                 }
105             }
106         }
107     }
108
109     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
110         if is_relevant_item(cx.tcx, item) {
111             check_attrs(cx, item.span, &item.name, &item.attrs)
112         }
113         match item.node {
114             ItemExternCrate(_) | ItemUse(_, _) => {
115                 for attr in &item.attrs {
116                     if let Some(ref lint_list) = attr.meta_item_list() {
117                         if let Some(name) = attr.name() {
118                             match &*name.as_str() {
119                                 "allow" | "warn" | "deny" | "forbid" => {
120                                     // whitelist `unused_imports` and `deprecated`
121                                     for lint in lint_list {
122                                         if is_word(lint, "unused_imports") || is_word(lint, "deprecated") {
123                                             if let ItemUse(_, _) = item.node {
124                                                 return;
125                                             }
126                                         }
127                                     }
128                                     if let Some(mut sugg) = snippet_opt(cx, attr.span) {
129                                         if sugg.len() > 1 {
130                                             span_lint_and_then(
131                                                 cx,
132                                                 USELESS_ATTRIBUTE,
133                                                 attr.span,
134                                                 "useless lint attribute",
135                                                 |db| {
136                                                     sugg.insert(1, '!');
137                                                     db.span_suggestion(
138                                                         attr.span,
139                                                         "if you just forgot a `!`, use",
140                                                         sugg,
141                                                     );
142                                                 },
143                                             );
144                                         }
145                                     }
146                                 },
147                                 _ => {},
148                             }
149                         }
150                     }
151                 }
152             },
153             _ => {},
154         }
155     }
156
157     fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx ImplItem) {
158         if is_relevant_impl(cx.tcx, item) {
159             check_attrs(cx, item.span, &item.name, &item.attrs)
160         }
161     }
162
163     fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx TraitItem) {
164         if is_relevant_trait(cx.tcx, item) {
165             check_attrs(cx, item.span, &item.name, &item.attrs)
166         }
167     }
168 }
169
170 fn is_relevant_item(tcx: TyCtxt, item: &Item) -> bool {
171     if let ItemFn(_, _, _, _, _, eid) = item.node {
172         is_relevant_expr(tcx, tcx.body_tables(eid), &tcx.hir.body(eid).value)
173     } else {
174         false
175     }
176 }
177
178 fn is_relevant_impl(tcx: TyCtxt, item: &ImplItem) -> bool {
179     match item.node {
180         ImplItemKind::Method(_, eid) => is_relevant_expr(tcx, tcx.body_tables(eid), &tcx.hir.body(eid).value),
181         _ => false,
182     }
183 }
184
185 fn is_relevant_trait(tcx: TyCtxt, item: &TraitItem) -> bool {
186     match item.node {
187         TraitItemKind::Method(_, TraitMethod::Required(_)) => true,
188         TraitItemKind::Method(_, TraitMethod::Provided(eid)) => {
189             is_relevant_expr(tcx, tcx.body_tables(eid), &tcx.hir.body(eid).value)
190         },
191         _ => false,
192     }
193 }
194
195 fn is_relevant_block(tcx: TyCtxt, tables: &ty::TypeckTables, block: &Block) -> bool {
196     if let Some(stmt) = block.stmts.first() {
197         match stmt.node {
198             StmtDecl(_, _) => true,
199             StmtExpr(ref expr, _) | StmtSemi(ref expr, _) => is_relevant_expr(tcx, tables, expr),
200         }
201     } else {
202         block
203             .expr
204             .as_ref()
205             .map_or(false, |e| is_relevant_expr(tcx, tables, e))
206     }
207 }
208
209 fn is_relevant_expr(tcx: TyCtxt, tables: &ty::TypeckTables, expr: &Expr) -> bool {
210     match expr.node {
211         ExprBlock(ref block) => is_relevant_block(tcx, tables, block),
212         ExprRet(Some(ref e)) => is_relevant_expr(tcx, tables, e),
213         ExprRet(None) | ExprBreak(_, None) => false,
214         ExprCall(ref path_expr, _) => if let ExprPath(ref qpath) = path_expr.node {
215             if let Some(fun_id) = opt_def_id(tables.qpath_def(qpath, path_expr.hir_id)) {
216                 !match_def_path(tcx, fun_id, &paths::BEGIN_PANIC)
217             } else {
218                 true
219             }
220         } else {
221             true
222         },
223         _ => true,
224     }
225 }
226
227 fn check_attrs(cx: &LateContext, span: Span, name: &Name, attrs: &[Attribute]) {
228     if in_macro(span) {
229         return;
230     }
231
232     for attr in attrs {
233         if let Some(ref values) = attr.meta_item_list() {
234             if values.len() != 1 || attr.name().map_or(true, |n| n != "inline") {
235                 continue;
236             }
237             if is_word(&values[0], "always") {
238                 span_lint(
239                     cx,
240                     INLINE_ALWAYS,
241                     attr.span,
242                     &format!(
243                         "you have declared `#[inline(always)]` on `{}`. This is usually a bad idea",
244                         name
245                     ),
246                 );
247             }
248         }
249     }
250 }
251
252 fn check_semver(cx: &LateContext, span: Span, lit: &Lit) {
253     if let LitKind::Str(ref is, _) = lit.node {
254         if Version::parse(&is.as_str()).is_ok() {
255             return;
256         }
257     }
258     span_lint(
259         cx,
260         DEPRECATED_SEMVER,
261         span,
262         "the since field must contain a semver-compliant version",
263     );
264 }
265
266 fn is_word(nmi: &NestedMetaItem, expected: &str) -> bool {
267     if let NestedMetaItemKind::MetaItem(ref mi) = nmi.node {
268         mi.is_word() && mi.name() == expected
269     } else {
270         false
271     }
272 }