]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/attrs.rs
Make lint work on all members of ast::Item_
[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, AttrStyle, 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 /// **What it does:** Checks for empty lines after outer attributes
82 ///
83 /// **Why is this bad?**
84 /// Most likely the attribute was meant to be an inner attribute using a '!'.
85 /// If it was meant to be an outer attribute, then the following item
86 /// should not be separated by empty lines.
87 ///
88 /// **Known problems:** None
89 ///
90 /// **Example:**
91 /// ```rust
92 /// // Bad
93 /// #[inline(always)]
94 ///
95 /// fn not_quite_good_code(..) { ... }
96 ///
97 /// // Good (as inner attribute)
98 /// #![inline(always)]
99 ///
100 /// fn this_is_fine_too(..) { ... }
101 ///
102 /// // Good (as outer attribute)
103 /// #[inline(always)]
104 /// fn this_is_fine(..) { ... }
105 ///
106 /// ```
107 declare_lint! {
108     pub EMPTY_LINE_AFTER_OUTER_ATTR,
109     Warn,
110     "empty line after outer attribute"
111 }
112
113 #[derive(Copy, Clone)]
114 pub struct AttrPass;
115
116 impl LintPass for AttrPass {
117     fn get_lints(&self) -> LintArray {
118         lint_array!(INLINE_ALWAYS, DEPRECATED_SEMVER, USELESS_ATTRIBUTE, EMPTY_LINE_AFTER_OUTER_ATTR)
119     }
120 }
121
122 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AttrPass {
123     fn check_attribute(&mut self, cx: &LateContext<'a, 'tcx>, attr: &'tcx Attribute) {
124         if let Some(ref items) = attr.meta_item_list() {
125             if items.is_empty() || attr.name().map_or(true, |n| n != "deprecated") {
126                 return;
127             }
128             for item in items {
129                 if_chain! {
130                     if let NestedMetaItemKind::MetaItem(ref mi) = item.node;
131                     if let MetaItemKind::NameValue(ref lit) = mi.node;
132                     if mi.name() == "since";
133                     then {
134                         check_semver(cx, item.span, lit);
135                     }
136                 }
137             }
138         }
139     }
140
141     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
142         if is_relevant_item(cx.tcx, item) {
143             check_attrs(cx, item.span, &item.name, &item.attrs)
144         }
145         match item.node {
146             ItemExternCrate(_) | ItemUse(_, _) => {
147                 for attr in &item.attrs {
148                     if let Some(ref lint_list) = attr.meta_item_list() {
149                         if let Some(name) = attr.name() {
150                             match &*name.as_str() {
151                                 "allow" | "warn" | "deny" | "forbid" => {
152                                     // whitelist `unused_imports` and `deprecated`
153                                     for lint in lint_list {
154                                         if is_word(lint, "unused_imports") || is_word(lint, "deprecated") {
155                                             if let ItemUse(_, _) = item.node {
156                                                 return;
157                                             }
158                                         }
159                                     }
160                                     if let Some(mut sugg) = snippet_opt(cx, attr.span) {
161                                         if sugg.len() > 1 {
162                                             span_lint_and_then(
163                                                 cx,
164                                                 USELESS_ATTRIBUTE,
165                                                 attr.span,
166                                                 "useless lint attribute",
167                                                 |db| {
168                                                     sugg.insert(1, '!');
169                                                     db.span_suggestion(
170                                                         attr.span,
171                                                         "if you just forgot a `!`, use",
172                                                         sugg,
173                                                     );
174                                                 },
175                                             );
176                                         }
177                                     }
178                                 },
179                                 _ => {},
180                             }
181                         }
182                     }
183                 }
184             },
185             _ => {},
186         }
187     }
188
189     fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx ImplItem) {
190         if is_relevant_impl(cx.tcx, item) {
191             check_attrs(cx, item.span, &item.name, &item.attrs)
192         }
193     }
194
195     fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx TraitItem) {
196         if is_relevant_trait(cx.tcx, item) {
197             check_attrs(cx, item.span, &item.name, &item.attrs)
198         }
199     }
200 }
201
202 fn is_relevant_item(tcx: TyCtxt, item: &Item) -> bool {
203     if let ItemFn(_, _, _, _, _, eid) = item.node {
204         is_relevant_expr(tcx, tcx.body_tables(eid), &tcx.hir.body(eid).value)
205     } else {
206         true
207     }
208 }
209
210 fn is_relevant_impl(tcx: TyCtxt, item: &ImplItem) -> bool {
211     match item.node {
212         ImplItemKind::Method(_, eid) => is_relevant_expr(tcx, tcx.body_tables(eid), &tcx.hir.body(eid).value),
213         _ => false,
214     }
215 }
216
217 fn is_relevant_trait(tcx: TyCtxt, item: &TraitItem) -> bool {
218     match item.node {
219         TraitItemKind::Method(_, TraitMethod::Required(_)) => true,
220         TraitItemKind::Method(_, TraitMethod::Provided(eid)) => {
221             is_relevant_expr(tcx, tcx.body_tables(eid), &tcx.hir.body(eid).value)
222         },
223         _ => false,
224     }
225 }
226
227 fn is_relevant_block(tcx: TyCtxt, tables: &ty::TypeckTables, block: &Block) -> bool {
228     if let Some(stmt) = block.stmts.first() {
229         match stmt.node {
230             StmtDecl(_, _) => true,
231             StmtExpr(ref expr, _) | StmtSemi(ref expr, _) => is_relevant_expr(tcx, tables, expr),
232         }
233     } else {
234         block
235             .expr
236             .as_ref()
237             .map_or(false, |e| is_relevant_expr(tcx, tables, e))
238     }
239 }
240
241 fn is_relevant_expr(tcx: TyCtxt, tables: &ty::TypeckTables, expr: &Expr) -> bool {
242     match expr.node {
243         ExprBlock(ref block) => is_relevant_block(tcx, tables, block),
244         ExprRet(Some(ref e)) => is_relevant_expr(tcx, tables, e),
245         ExprRet(None) | ExprBreak(_, None) => false,
246         ExprCall(ref path_expr, _) => if let ExprPath(ref qpath) = path_expr.node {
247             if let Some(fun_id) = opt_def_id(tables.qpath_def(qpath, path_expr.hir_id)) {
248                 !match_def_path(tcx, fun_id, &paths::BEGIN_PANIC)
249             } else {
250                 true
251             }
252         } else {
253             true
254         },
255         _ => true,
256     }
257 }
258
259 fn check_attrs(cx: &LateContext, span: Span, name: &Name, attrs: &[Attribute]) {
260     if in_macro(span) {
261         return;
262     }
263
264     for attr in attrs {
265         if attr.style == AttrStyle::Outer {
266             let attr_to_item_span = Span::new(attr.span.lo(), span.lo(), span.ctxt());
267
268             if let Some(snippet) = snippet_opt(cx, attr_to_item_span) {
269                 let lines = snippet.split('\n').collect::<Vec<_>>();
270                 if lines.iter().filter(|l| l.trim().is_empty()).count() > 1 {
271                     span_lint(
272                         cx,
273                         EMPTY_LINE_AFTER_OUTER_ATTR,
274                         attr_to_item_span,
275                         &format!("Found an empty line after an outer attribute. Perhaps you forgot to add a '!' to make it an inner attribute?")
276                         );
277
278                 }
279             }
280         }
281
282         if let Some(ref values) = attr.meta_item_list() {
283             if values.len() != 1 || attr.name().map_or(true, |n| n != "inline") {
284                 continue;
285             }
286             if is_word(&values[0], "always") {
287                 span_lint(
288                     cx,
289                     INLINE_ALWAYS,
290                     attr.span,
291                     &format!(
292                         "you have declared `#[inline(always)]` on `{}`. This is usually a bad idea",
293                         name
294                     ),
295                 );
296             }
297         }
298     }
299 }
300
301 fn check_semver(cx: &LateContext, span: Span, lit: &Lit) {
302     if let LitKind::Str(ref is, _) = lit.node {
303         if Version::parse(&is.as_str()).is_ok() {
304             return;
305         }
306     }
307     span_lint(
308         cx,
309         DEPRECATED_SEMVER,
310         span,
311         "the since field must contain a semver-compliant version",
312     );
313 }
314
315 fn is_word(nmi: &NestedMetaItem, expected: &str) -> bool {
316     if let NestedMetaItemKind::MetaItem(ref mi) = nmi.node {
317         mi.is_word() && mi.name() == expected
318     } else {
319         false
320     }
321 }