]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/attrs.rs
Merge branch 'master' into dogfood_target_dir
[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, last_line_of_span, match_def_path, opt_def_id, paths, snippet_opt, span_lint, span_lint_and_then, without_block_comments};
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_clippy_lint! {
33     pub INLINE_ALWAYS,
34     pedantic,
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_clippy_lint! {
57     pub USELESS_ATTRIBUTE,
58     correctness,
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_clippy_lint! {
76     pub DEPRECATED_SEMVER,
77     correctness,
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:** Can cause false positives.
89 ///
90 /// From the clippy side it's difficult to detect empty lines between an attributes and the
91 /// following item because empty lines and comments are not part of the AST. The parsing
92 /// currently works for basic cases but is not perfect.
93 ///
94 /// **Example:**
95 /// ```rust
96 /// // Bad
97 /// #[inline(always)]
98 ///
99 /// fn not_quite_good_code(..) { ... }
100 ///
101 /// // Good (as inner attribute)
102 /// #![inline(always)]
103 ///
104 /// fn this_is_fine(..) { ... }
105 ///
106 /// // Good (as outer attribute)
107 /// #[inline(always)]
108 /// fn this_is_fine_too(..) { ... }
109 /// ```
110 declare_clippy_lint! {
111     pub EMPTY_LINE_AFTER_OUTER_ATTR,
112     nursery,
113     "empty line after outer attribute"
114 }
115
116 #[derive(Copy, Clone)]
117 pub struct AttrPass;
118
119 impl LintPass for AttrPass {
120     fn get_lints(&self) -> LintArray {
121         lint_array!(INLINE_ALWAYS, DEPRECATED_SEMVER, USELESS_ATTRIBUTE, EMPTY_LINE_AFTER_OUTER_ATTR)
122     }
123 }
124
125 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AttrPass {
126     fn check_attribute(&mut self, cx: &LateContext<'a, 'tcx>, attr: &'tcx Attribute) {
127         if let Some(ref items) = attr.meta_item_list() {
128             if items.is_empty() || attr.name().map_or(true, |n| n != "deprecated") {
129                 return;
130             }
131             for item in items {
132                 if_chain! {
133                     if let NestedMetaItemKind::MetaItem(ref mi) = item.node;
134                     if let MetaItemKind::NameValue(ref lit) = mi.node;
135                     if mi.name() == "since";
136                     then {
137                         check_semver(cx, item.span, lit);
138                     }
139                 }
140             }
141         }
142     }
143
144     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
145         if is_relevant_item(cx.tcx, item) {
146             check_attrs(cx, item.span, &item.name, &item.attrs)
147         }
148         match item.node {
149             ItemExternCrate(_) | ItemUse(_, _) => {
150                 for attr in &item.attrs {
151                     if let Some(ref lint_list) = attr.meta_item_list() {
152                         if let Some(name) = attr.name() {
153                             match &*name.as_str() {
154                                 "allow" | "warn" | "deny" | "forbid" => {
155                                     // whitelist `unused_imports` and `deprecated`
156                                     for lint in lint_list {
157                                         if is_word(lint, "unused_imports") || is_word(lint, "deprecated") {
158                                             if let ItemUse(_, _) = item.node {
159                                                 return;
160                                             }
161                                         }
162                                     }
163                                     let line_span = last_line_of_span(cx, attr.span);
164
165                                     if let Some(mut sugg) = snippet_opt(cx, line_span) {
166                                         if sugg.contains("#[") {
167                                             span_lint_and_then(
168                                                 cx,
169                                                 USELESS_ATTRIBUTE,
170                                                 line_span,
171                                                 "useless lint attribute",
172                                                 |db| {
173                                                     sugg = sugg.replacen("#[", "#![", 1);
174                                                     db.span_suggestion(
175                                                         line_span,
176                                                         "if you just forgot a `!`, use",
177                                                         sugg,
178                                                     );
179                                                 },
180                                             );
181                                         }
182                                     }
183                                 },
184                                 _ => {},
185                             }
186                         }
187                     }
188                 }
189             },
190             _ => {},
191         }
192     }
193
194     fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx ImplItem) {
195         if is_relevant_impl(cx.tcx, item) {
196             check_attrs(cx, item.span, &item.name, &item.attrs)
197         }
198     }
199
200     fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx TraitItem) {
201         if is_relevant_trait(cx.tcx, item) {
202             check_attrs(cx, item.span, &item.name, &item.attrs)
203         }
204     }
205 }
206
207 fn is_relevant_item(tcx: TyCtxt, item: &Item) -> bool {
208     if let ItemFn(_, _, _, _, _, eid) = item.node {
209         is_relevant_expr(tcx, tcx.body_tables(eid), &tcx.hir.body(eid).value)
210     } else {
211         true
212     }
213 }
214
215 fn is_relevant_impl(tcx: TyCtxt, item: &ImplItem) -> bool {
216     match item.node {
217         ImplItemKind::Method(_, eid) => is_relevant_expr(tcx, tcx.body_tables(eid), &tcx.hir.body(eid).value),
218         _ => false,
219     }
220 }
221
222 fn is_relevant_trait(tcx: TyCtxt, item: &TraitItem) -> bool {
223     match item.node {
224         TraitItemKind::Method(_, TraitMethod::Required(_)) => true,
225         TraitItemKind::Method(_, TraitMethod::Provided(eid)) => {
226             is_relevant_expr(tcx, tcx.body_tables(eid), &tcx.hir.body(eid).value)
227         },
228         _ => false,
229     }
230 }
231
232 fn is_relevant_block(tcx: TyCtxt, tables: &ty::TypeckTables, block: &Block) -> bool {
233     if let Some(stmt) = block.stmts.first() {
234         match stmt.node {
235             StmtDecl(_, _) => true,
236             StmtExpr(ref expr, _) | StmtSemi(ref expr, _) => is_relevant_expr(tcx, tables, expr),
237         }
238     } else {
239         block
240             .expr
241             .as_ref()
242             .map_or(false, |e| is_relevant_expr(tcx, tables, e))
243     }
244 }
245
246 fn is_relevant_expr(tcx: TyCtxt, tables: &ty::TypeckTables, expr: &Expr) -> bool {
247     match expr.node {
248         ExprBlock(ref block) => is_relevant_block(tcx, tables, block),
249         ExprRet(Some(ref e)) => is_relevant_expr(tcx, tables, e),
250         ExprRet(None) | ExprBreak(_, None) => false,
251         ExprCall(ref path_expr, _) => if let ExprPath(ref qpath) = path_expr.node {
252             if let Some(fun_id) = opt_def_id(tables.qpath_def(qpath, path_expr.hir_id)) {
253                 !match_def_path(tcx, fun_id, &paths::BEGIN_PANIC)
254             } else {
255                 true
256             }
257         } else {
258             true
259         },
260         _ => true,
261     }
262 }
263
264 fn check_attrs(cx: &LateContext, span: Span, name: &Name, attrs: &[Attribute]) {
265     if in_macro(span) {
266         return;
267     }
268
269     for attr in attrs {
270         if attr.is_sugared_doc {
271             return;
272         }
273         if attr.style == AttrStyle::Outer {
274             if attr.tokens.is_empty() || !is_present_in_source(cx, attr.span) {
275                 return;
276             }
277
278             let begin_of_attr_to_item = Span::new(attr.span.lo(), span.lo(), span.ctxt());
279             let end_of_attr_to_item = Span::new(attr.span.hi(), span.lo(), span.ctxt());
280
281             if let Some(snippet) = snippet_opt(cx, end_of_attr_to_item) {
282                 let lines = snippet.split('\n').collect::<Vec<_>>();
283                 let lines = without_block_comments(lines);
284
285                 if lines.iter().filter(|l| l.trim().is_empty()).count() > 2 {
286                     span_lint(
287                         cx,
288                         EMPTY_LINE_AFTER_OUTER_ATTR,
289                         begin_of_attr_to_item,
290                         "Found an empty line after an outer attribute. Perhaps you forgot to add a '!' to make it an inner attribute?"
291                     );
292                 }
293             }
294         }
295
296         if let Some(ref values) = attr.meta_item_list() {
297             if values.len() != 1 || attr.name().map_or(true, |n| n != "inline") {
298                 continue;
299             }
300             if is_word(&values[0], "always") {
301                 span_lint(
302                     cx,
303                     INLINE_ALWAYS,
304                     attr.span,
305                     &format!(
306                         "you have declared `#[inline(always)]` on `{}`. This is usually a bad idea",
307                         name
308                     ),
309                 );
310             }
311         }
312     }
313 }
314
315 fn check_semver(cx: &LateContext, span: Span, lit: &Lit) {
316     if let LitKind::Str(ref is, _) = lit.node {
317         if Version::parse(&is.as_str()).is_ok() {
318             return;
319         }
320     }
321     span_lint(
322         cx,
323         DEPRECATED_SEMVER,
324         span,
325         "the since field must contain a semver-compliant version",
326     );
327 }
328
329 fn is_word(nmi: &NestedMetaItem, expected: &str) -> bool {
330     if let NestedMetaItemKind::MetaItem(ref mi) = nmi.node {
331         mi.is_word() && mi.name() == expected
332     } else {
333         false
334     }
335 }
336
337 // If the snippet is empty, it's an attribute that was inserted during macro
338 // expansion and we want to ignore those, because they could come from external
339 // sources that the user has no control over.
340 // For some reason these attributes don't have any expansion info on them, so
341 // we have to check it this way until there is a better way.
342 fn is_present_in_source(cx: &LateContext, span: Span) -> bool {
343     if let Some(snippet) = snippet_opt(cx, span) {
344         if snippet.is_empty() {
345             return false;
346         }
347     }
348     true
349 }