]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/attrs.rs
Merge pull request #2764 from phansch/integration_tests
[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() != "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                         match &*attr.name().as_str() {
153                             "allow" | "warn" | "deny" | "forbid" => {
154                                 // whitelist `unused_imports` and `deprecated`
155                                 for lint in lint_list {
156                                     if is_word(lint, "unused_imports") || is_word(lint, "deprecated") {
157                                         if let ItemUse(_, _) = item.node {
158                                             return;
159                                         }
160                                     }
161                                 }
162                                 let line_span = last_line_of_span(cx, attr.span);
163
164                                 if let Some(mut sugg) = snippet_opt(cx, line_span) {
165                                     if sugg.contains("#[") {
166                                         span_lint_and_then(
167                                             cx,
168                                             USELESS_ATTRIBUTE,
169                                             line_span,
170                                             "useless lint attribute",
171                                             |db| {
172                                                 sugg = sugg.replacen("#[", "#![", 1);
173                                                 db.span_suggestion(
174                                                     line_span,
175                                                     "if you just forgot a `!`, use",
176                                                     sugg,
177                                                 );
178                                             },
179                                         );
180                                     }
181                                 }
182                             },
183                             _ => {},
184                         }
185                     }
186                 }
187             },
188             _ => {},
189         }
190     }
191
192     fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx ImplItem) {
193         if is_relevant_impl(cx.tcx, item) {
194             check_attrs(cx, item.span, &item.name, &item.attrs)
195         }
196     }
197
198     fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx TraitItem) {
199         if is_relevant_trait(cx.tcx, item) {
200             check_attrs(cx, item.span, &item.name, &item.attrs)
201         }
202     }
203 }
204
205 fn is_relevant_item(tcx: TyCtxt, item: &Item) -> bool {
206     if let ItemFn(_, _, _, _, _, eid) = item.node {
207         is_relevant_expr(tcx, tcx.body_tables(eid), &tcx.hir.body(eid).value)
208     } else {
209         true
210     }
211 }
212
213 fn is_relevant_impl(tcx: TyCtxt, item: &ImplItem) -> bool {
214     match item.node {
215         ImplItemKind::Method(_, eid) => is_relevant_expr(tcx, tcx.body_tables(eid), &tcx.hir.body(eid).value),
216         _ => false,
217     }
218 }
219
220 fn is_relevant_trait(tcx: TyCtxt, item: &TraitItem) -> bool {
221     match item.node {
222         TraitItemKind::Method(_, TraitMethod::Required(_)) => true,
223         TraitItemKind::Method(_, TraitMethod::Provided(eid)) => {
224             is_relevant_expr(tcx, tcx.body_tables(eid), &tcx.hir.body(eid).value)
225         },
226         _ => false,
227     }
228 }
229
230 fn is_relevant_block(tcx: TyCtxt, tables: &ty::TypeckTables, block: &Block) -> bool {
231     if let Some(stmt) = block.stmts.first() {
232         match stmt.node {
233             StmtDecl(_, _) => true,
234             StmtExpr(ref expr, _) | StmtSemi(ref expr, _) => is_relevant_expr(tcx, tables, expr),
235         }
236     } else {
237         block
238             .expr
239             .as_ref()
240             .map_or(false, |e| is_relevant_expr(tcx, tables, e))
241     }
242 }
243
244 fn is_relevant_expr(tcx: TyCtxt, tables: &ty::TypeckTables, expr: &Expr) -> bool {
245     match expr.node {
246         ExprBlock(ref block, _) => is_relevant_block(tcx, tables, block),
247         ExprRet(Some(ref e)) => is_relevant_expr(tcx, tables, e),
248         ExprRet(None) | ExprBreak(_, None) => false,
249         ExprCall(ref path_expr, _) => if let ExprPath(ref qpath) = path_expr.node {
250             if let Some(fun_id) = opt_def_id(tables.qpath_def(qpath, path_expr.hir_id)) {
251                 !match_def_path(tcx, fun_id, &paths::BEGIN_PANIC)
252             } else {
253                 true
254             }
255         } else {
256             true
257         },
258         _ => true,
259     }
260 }
261
262 fn check_attrs(cx: &LateContext, span: Span, name: &Name, attrs: &[Attribute]) {
263     if in_macro(span) {
264         return;
265     }
266
267     for attr in attrs {
268         if attr.is_sugared_doc {
269             return;
270         }
271         if attr.style == AttrStyle::Outer {
272             if attr.tokens.is_empty() || !is_present_in_source(cx, attr.span) {
273                 return;
274             }
275
276             let begin_of_attr_to_item = Span::new(attr.span.lo(), span.lo(), span.ctxt());
277             let end_of_attr_to_item = Span::new(attr.span.hi(), span.lo(), span.ctxt());
278
279             if let Some(snippet) = snippet_opt(cx, end_of_attr_to_item) {
280                 let lines = snippet.split('\n').collect::<Vec<_>>();
281                 let lines = without_block_comments(lines);
282
283                 if lines.iter().filter(|l| l.trim().is_empty()).count() > 2 {
284                     span_lint(
285                         cx,
286                         EMPTY_LINE_AFTER_OUTER_ATTR,
287                         begin_of_attr_to_item,
288                         "Found an empty line after an outer attribute. Perhaps you forgot to add a '!' to make it an inner attribute?"
289                     );
290                 }
291             }
292         }
293
294         if let Some(ref values) = attr.meta_item_list() {
295             if values.len() != 1 || attr.name() != "inline" {
296                 continue;
297             }
298             if is_word(&values[0], "always") {
299                 span_lint(
300                     cx,
301                     INLINE_ALWAYS,
302                     attr.span,
303                     &format!(
304                         "you have declared `#[inline(always)]` on `{}`. This is usually a bad idea",
305                         name
306                     ),
307                 );
308             }
309         }
310     }
311 }
312
313 fn check_semver(cx: &LateContext, span: Span, lit: &Lit) {
314     if let LitKind::Str(ref is, _) = lit.node {
315         if Version::parse(&is.as_str()).is_ok() {
316             return;
317         }
318     }
319     span_lint(
320         cx,
321         DEPRECATED_SEMVER,
322         span,
323         "the since field must contain a semver-compliant version",
324     );
325 }
326
327 fn is_word(nmi: &NestedMetaItem, expected: &str) -> bool {
328     if let NestedMetaItemKind::MetaItem(ref mi) = nmi.node {
329         mi.is_word() && mi.name() == expected
330     } else {
331         false
332     }
333 }
334
335 // If the snippet is empty, it's an attribute that was inserted during macro
336 // expansion and we want to ignore those, because they could come from external
337 // sources that the user has no control over.
338 // For some reason these attributes don't have any expansion info on them, so
339 // we have to check it this way until there is a better way.
340 fn is_present_in_source(cx: &LateContext, span: Span) -> bool {
341     if let Some(snippet) = snippet_opt(cx, span) {
342         if snippet.is_empty() {
343             return false;
344         }
345     }
346     true
347 }