]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/attrs.rs
Skip useless_attribute lint on allow(unused_imports) on extern crate items with macro_use
[rust.git] / clippy_lints / src / attrs.rs
1 //! checks for attributes
2
3 use crate::reexport::*;
4 use crate::utils::{
5     in_macro, last_line_of_span, match_def_path, opt_def_id, paths, snippet_opt, span_lint, span_lint_and_then,
6     without_block_comments,
7 };
8 use rustc::hir::*;
9 use rustc::lint::*;
10 use rustc::ty::{self, TyCtxt};
11 use semver::Version;
12 use syntax::ast::{AttrStyle, Attribute, Lit, LitKind, MetaItemKind, NestedMetaItem, NestedMetaItemKind};
13 use syntax::codemap::Span;
14
15 /// **What it does:** Checks for items annotated with `#[inline(always)]`,
16 /// unless the annotated function is empty or simply panics.
17 ///
18 /// **Why is this bad?** While there are valid uses of this annotation (and once
19 /// you know when to use it, by all means `allow` this lint), it's a common
20 /// newbie-mistake to pepper one's code with it.
21 ///
22 /// As a rule of thumb, before slapping `#[inline(always)]` on a function,
23 /// measure if that additional function call really affects your runtime profile
24 /// sufficiently to make up for the increase in compile time.
25 ///
26 /// **Known problems:** False positives, big time. This lint is meant to be
27 /// deactivated by everyone doing serious performance work. This means having
28 /// done the measurement.
29 ///
30 /// **Example:**
31 /// ```rust
32 /// #[inline(always)]
33 /// fn not_quite_hot_code(..) { ... }
34 /// ```
35 declare_clippy_lint! {
36     pub INLINE_ALWAYS,
37     pedantic,
38     "use of `#[inline(always)]`"
39 }
40
41 /// **What it does:** Checks for `extern crate` and `use` items annotated with
42 /// lint attributes.
43 ///
44 /// This lint whitelists `#[allow(unused_imports)]` and `#[allow(deprecated)]` on
45 /// `use` items and `#[allow(unused_imports)]` on `extern crate` items with a
46 /// `#[macro_use]` attribute.
47 ///
48 /// **Why is this bad?** Lint attributes have no effect on crate imports. Most
49 /// likely a `!` was forgotten.
50 ///
51 /// **Known problems:** None.
52 ///
53 /// **Example:**
54 /// ```rust
55 /// // Bad
56 /// #[deny(dead_code)]
57 /// extern crate foo;
58 /// #[forbid(dead_code)]
59 /// use foo::bar;
60 ///
61 /// // Ok
62 /// #[allow(unused_imports)]
63 /// use foo::baz;
64 /// #[allow(unused_imports)]
65 /// #[macro_use]
66 /// extern crate baz;
67 /// ```
68 declare_clippy_lint! {
69     pub USELESS_ATTRIBUTE,
70     correctness,
71     "use of lint attributes on `extern crate` items"
72 }
73
74 /// **What it does:** Checks for `#[deprecated]` annotations with a `since`
75 /// field that is not a valid semantic version.
76 ///
77 /// **Why is this bad?** For checking the version of the deprecation, it must be
78 /// a valid semver. Failing that, the contained information is useless.
79 ///
80 /// **Known problems:** None.
81 ///
82 /// **Example:**
83 /// ```rust
84 /// #[deprecated(since = "forever")]
85 /// fn something_else(..) { ... }
86 /// ```
87 declare_clippy_lint! {
88     pub DEPRECATED_SEMVER,
89     correctness,
90     "use of `#[deprecated(since = \"x\")]` where x is not semver"
91 }
92
93 /// **What it does:** Checks for empty lines after outer attributes
94 ///
95 /// **Why is this bad?**
96 /// Most likely the attribute was meant to be an inner attribute using a '!'.
97 /// If it was meant to be an outer attribute, then the following item
98 /// should not be separated by empty lines.
99 ///
100 /// **Known problems:** Can cause false positives.
101 ///
102 /// From the clippy side it's difficult to detect empty lines between an attributes and the
103 /// following item because empty lines and comments are not part of the AST. The parsing
104 /// currently works for basic cases but is not perfect.
105 ///
106 /// **Example:**
107 /// ```rust
108 /// // Bad
109 /// #[inline(always)]
110 ///
111 /// fn not_quite_good_code(..) { ... }
112 ///
113 /// // Good (as inner attribute)
114 /// #![inline(always)]
115 ///
116 /// fn this_is_fine(..) { ... }
117 ///
118 /// // Good (as outer attribute)
119 /// #[inline(always)]
120 /// fn this_is_fine_too(..) { ... }
121 /// ```
122 declare_clippy_lint! {
123     pub EMPTY_LINE_AFTER_OUTER_ATTR,
124     nursery,
125     "empty line after outer attribute"
126 }
127
128 #[derive(Copy, Clone)]
129 pub struct AttrPass;
130
131 impl LintPass for AttrPass {
132     fn get_lints(&self) -> LintArray {
133         lint_array!(
134             INLINE_ALWAYS,
135             DEPRECATED_SEMVER,
136             USELESS_ATTRIBUTE,
137             EMPTY_LINE_AFTER_OUTER_ATTR
138         )
139     }
140 }
141
142 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AttrPass {
143     fn check_attribute(&mut self, cx: &LateContext<'a, 'tcx>, attr: &'tcx Attribute) {
144         if let Some(ref items) = attr.meta_item_list() {
145             if items.is_empty() || attr.name() != "deprecated" {
146                 return;
147             }
148             for item in items {
149                 if_chain! {
150                     if let NestedMetaItemKind::MetaItem(ref mi) = item.node;
151                     if let MetaItemKind::NameValue(ref lit) = mi.node;
152                     if mi.name() == "since";
153                     then {
154                         check_semver(cx, item.span, lit);
155                     }
156                 }
157             }
158         }
159     }
160
161     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
162         if is_relevant_item(cx.tcx, item) {
163             check_attrs(cx, item.span, item.name, &item.attrs)
164         }
165         match item.node {
166             ItemKind::ExternCrate(..) | ItemKind::Use(..) => {
167                 let skip_unused_imports = item.attrs.iter().any(|attr| attr.name() == "macro_use");
168
169                 for attr in &item.attrs {
170                     if let Some(ref lint_list) = attr.meta_item_list() {
171                         match &*attr.name().as_str() {
172                             "allow" | "warn" | "deny" | "forbid" => {
173                                 // whitelist `unused_imports` and `deprecated` for `use` items
174                                 // and `unused_imports` for `extern crate` items with `macro_use`
175                                 for lint in lint_list {
176                                     match item.node {
177                                         ItemKind::Use(..) => if is_word(lint, "unused_imports")
178                                                                 || is_word(lint, "deprecated") {
179                                                 return
180                                         },
181                                         ItemKind::ExternCrate(..) => if is_word(lint, "unused_imports")
182                                                                         && skip_unused_imports {
183                                                 return
184                                         },
185                                         _ => {},
186                                     }
187                                 }
188                                 let line_span = last_line_of_span(cx, attr.span);
189
190                                 if let Some(mut sugg) = snippet_opt(cx, line_span) {
191                                     if sugg.contains("#[") {
192                                         span_lint_and_then(
193                                             cx,
194                                             USELESS_ATTRIBUTE,
195                                             line_span,
196                                             "useless lint attribute",
197                                             |db| {
198                                                 sugg = sugg.replacen("#[", "#![", 1);
199                                                 db.span_suggestion(line_span, "if you just forgot a `!`, use", sugg);
200                                             },
201                                         );
202                                     }
203                                 }
204                             },
205                             _ => {},
206                         }
207                     }
208                 }
209             },
210             _ => {},
211         }
212     }
213
214     fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx ImplItem) {
215         if is_relevant_impl(cx.tcx, item) {
216             check_attrs(cx, item.span, item.ident.name, &item.attrs)
217         }
218     }
219
220     fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx TraitItem) {
221         if is_relevant_trait(cx.tcx, item) {
222             check_attrs(cx, item.span, item.ident.name, &item.attrs)
223         }
224     }
225 }
226
227 fn is_relevant_item(tcx: TyCtxt, item: &Item) -> bool {
228     if let ItemKind::Fn(_, _, _, eid) = item.node {
229         is_relevant_expr(tcx, tcx.body_tables(eid), &tcx.hir.body(eid).value)
230     } else {
231         true
232     }
233 }
234
235 fn is_relevant_impl(tcx: TyCtxt, item: &ImplItem) -> bool {
236     match item.node {
237         ImplItemKind::Method(_, eid) => is_relevant_expr(tcx, tcx.body_tables(eid), &tcx.hir.body(eid).value),
238         _ => false,
239     }
240 }
241
242 fn is_relevant_trait(tcx: TyCtxt, item: &TraitItem) -> bool {
243     match item.node {
244         TraitItemKind::Method(_, TraitMethod::Required(_)) => true,
245         TraitItemKind::Method(_, TraitMethod::Provided(eid)) => {
246             is_relevant_expr(tcx, tcx.body_tables(eid), &tcx.hir.body(eid).value)
247         },
248         _ => false,
249     }
250 }
251
252 fn is_relevant_block(tcx: TyCtxt, tables: &ty::TypeckTables, block: &Block) -> bool {
253     if let Some(stmt) = block.stmts.first() {
254         match stmt.node {
255             StmtKind::Decl(_, _) => true,
256             StmtKind::Expr(ref expr, _) | StmtKind::Semi(ref expr, _) => is_relevant_expr(tcx, tables, expr),
257         }
258     } else {
259         block.expr.as_ref().map_or(false, |e| is_relevant_expr(tcx, tables, e))
260     }
261 }
262
263 fn is_relevant_expr(tcx: TyCtxt, tables: &ty::TypeckTables, expr: &Expr) -> bool {
264     match expr.node {
265         ExprKind::Block(ref block, _) => is_relevant_block(tcx, tables, block),
266         ExprKind::Ret(Some(ref e)) => is_relevant_expr(tcx, tables, e),
267         ExprKind::Ret(None) | ExprKind::Break(_, None) => false,
268         ExprKind::Call(ref path_expr, _) => if let ExprKind::Path(ref qpath) = path_expr.node {
269             if let Some(fun_id) = opt_def_id(tables.qpath_def(qpath, path_expr.hir_id)) {
270                 !match_def_path(tcx, fun_id, &paths::BEGIN_PANIC)
271             } else {
272                 true
273             }
274         } else {
275             true
276         },
277         _ => true,
278     }
279 }
280
281 fn check_attrs(cx: &LateContext, span: Span, name: Name, attrs: &[Attribute]) {
282     if in_macro(span) {
283         return;
284     }
285
286     for attr in attrs {
287         if attr.is_sugared_doc {
288             return;
289         }
290         if attr.style == AttrStyle::Outer {
291             if attr.tokens.is_empty() || !is_present_in_source(cx, attr.span) {
292                 return;
293             }
294
295             let begin_of_attr_to_item = Span::new(attr.span.lo(), span.lo(), span.ctxt());
296             let end_of_attr_to_item = Span::new(attr.span.hi(), span.lo(), span.ctxt());
297
298             if let Some(snippet) = snippet_opt(cx, end_of_attr_to_item) {
299                 let lines = snippet.split('\n').collect::<Vec<_>>();
300                 let lines = without_block_comments(lines);
301
302                 if lines.iter().filter(|l| l.trim().is_empty()).count() > 2 {
303                     span_lint(
304                         cx,
305                         EMPTY_LINE_AFTER_OUTER_ATTR,
306                         begin_of_attr_to_item,
307                         "Found an empty line after an outer attribute. Perhaps you forgot to add a '!' to make it an inner attribute?"
308                     );
309                 }
310             }
311         }
312
313         if let Some(ref values) = attr.meta_item_list() {
314             if values.len() != 1 || attr.name() != "inline" {
315                 continue;
316             }
317             if is_word(&values[0], "always") {
318                 span_lint(
319                     cx,
320                     INLINE_ALWAYS,
321                     attr.span,
322                     &format!(
323                         "you have declared `#[inline(always)]` on `{}`. This is usually a bad idea",
324                         name
325                     ),
326                 );
327             }
328         }
329     }
330 }
331
332 fn check_semver(cx: &LateContext, span: Span, lit: &Lit) {
333     if let LitKind::Str(ref is, _) = lit.node {
334         if Version::parse(&is.as_str()).is_ok() {
335             return;
336         }
337     }
338     span_lint(
339         cx,
340         DEPRECATED_SEMVER,
341         span,
342         "the since field must contain a semver-compliant version",
343     );
344 }
345
346 fn is_word(nmi: &NestedMetaItem, expected: &str) -> bool {
347     if let NestedMetaItemKind::MetaItem(ref mi) = nmi.node {
348         mi.is_word() && mi.name() == expected
349     } else {
350         false
351     }
352 }
353
354 // If the snippet is empty, it's an attribute that was inserted during macro
355 // expansion and we want to ignore those, because they could come from external
356 // sources that the user has no control over.
357 // For some reason these attributes don't have any expansion info on them, so
358 // we have to check it this way until there is a better way.
359 fn is_present_in_source(cx: &LateContext, span: Span) -> bool {
360     if let Some(snippet) = snippet_opt(cx, span) {
361         if snippet.is_empty() {
362             return false;
363         }
364     }
365     true
366 }