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