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