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