]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/attrs.rs
Merge pull request #3189 from eddyb/rextern
[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 crate::rustc::hir::*;
9 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
10 use crate::rustc::{declare_tool_lint, lint_array};
11 use if_chain::if_chain;
12 use crate::rustc::ty::{self, TyCtxt};
13 use semver::Version;
14 use crate::syntax::ast::{AttrStyle, Attribute, Lit, LitKind, MetaItemKind, NestedMetaItem, NestedMetaItemKind};
15 use crate::syntax::source_map::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(..) => {
184                                             if is_word(lint, "unused_imports")
185                                                 && skip_unused_imports {
186                                                     return
187                                             }
188                                             if is_word(lint, "unused_extern_crates") {
189                                                 return
190                                             }
191                                         }
192                                         _ => {},
193                                     }
194                                 }
195                                 let line_span = last_line_of_span(cx, attr.span);
196
197                                 if let Some(mut sugg) = snippet_opt(cx, line_span) {
198                                     if sugg.contains("#[") {
199                                         span_lint_and_then(
200                                             cx,
201                                             USELESS_ATTRIBUTE,
202                                             line_span,
203                                             "useless lint attribute",
204                                             |db| {
205                                                 sugg = sugg.replacen("#[", "#![", 1);
206                                                 db.span_suggestion(line_span, "if you just forgot a `!`, use", sugg);
207                                             },
208                                         );
209                                     }
210                                 }
211                             },
212                             _ => {},
213                         }
214                     }
215                 }
216             },
217             _ => {},
218         }
219     }
220
221     fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx ImplItem) {
222         if is_relevant_impl(cx.tcx, item) {
223             check_attrs(cx, item.span, item.ident.name, &item.attrs)
224         }
225     }
226
227     fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx TraitItem) {
228         if is_relevant_trait(cx.tcx, item) {
229             check_attrs(cx, item.span, item.ident.name, &item.attrs)
230         }
231     }
232 }
233
234 fn is_relevant_item(tcx: TyCtxt<'_, '_, '_>, item: &Item) -> bool {
235     if let ItemKind::Fn(_, _, _, eid) = item.node {
236         is_relevant_expr(tcx, tcx.body_tables(eid), &tcx.hir.body(eid).value)
237     } else {
238         true
239     }
240 }
241
242 fn is_relevant_impl(tcx: TyCtxt<'_, '_, '_>, item: &ImplItem) -> bool {
243     match item.node {
244         ImplItemKind::Method(_, eid) => is_relevant_expr(tcx, tcx.body_tables(eid), &tcx.hir.body(eid).value),
245         _ => false,
246     }
247 }
248
249 fn is_relevant_trait(tcx: TyCtxt<'_, '_, '_>, item: &TraitItem) -> bool {
250     match item.node {
251         TraitItemKind::Method(_, TraitMethod::Required(_)) => true,
252         TraitItemKind::Method(_, TraitMethod::Provided(eid)) => {
253             is_relevant_expr(tcx, tcx.body_tables(eid), &tcx.hir.body(eid).value)
254         },
255         _ => false,
256     }
257 }
258
259 fn is_relevant_block(tcx: TyCtxt<'_, '_, '_>, tables: &ty::TypeckTables<'_>, block: &Block) -> bool {
260     if let Some(stmt) = block.stmts.first() {
261         match stmt.node {
262             StmtKind::Decl(_, _) => true,
263             StmtKind::Expr(ref expr, _) | StmtKind::Semi(ref expr, _) => is_relevant_expr(tcx, tables, expr),
264         }
265     } else {
266         block.expr.as_ref().map_or(false, |e| is_relevant_expr(tcx, tables, e))
267     }
268 }
269
270 fn is_relevant_expr(tcx: TyCtxt<'_, '_, '_>, tables: &ty::TypeckTables<'_>, expr: &Expr) -> bool {
271     match expr.node {
272         ExprKind::Block(ref block, _) => is_relevant_block(tcx, tables, block),
273         ExprKind::Ret(Some(ref e)) => is_relevant_expr(tcx, tables, e),
274         ExprKind::Ret(None) | ExprKind::Break(_, None) => false,
275         ExprKind::Call(ref path_expr, _) => if let ExprKind::Path(ref qpath) = path_expr.node {
276             if let Some(fun_id) = opt_def_id(tables.qpath_def(qpath, path_expr.hir_id)) {
277                 !match_def_path(tcx, fun_id, &paths::BEGIN_PANIC)
278             } else {
279                 true
280             }
281         } else {
282             true
283         },
284         _ => true,
285     }
286 }
287
288 fn check_attrs(cx: &LateContext<'_, '_>, span: Span, name: Name, attrs: &[Attribute]) {
289     if in_macro(span) {
290         return;
291     }
292
293     for attr in attrs {
294         if attr.is_sugared_doc {
295             return;
296         }
297         if attr.style == AttrStyle::Outer {
298             if attr.tokens.is_empty() || !is_present_in_source(cx, attr.span) {
299                 return;
300             }
301
302             let begin_of_attr_to_item = Span::new(attr.span.lo(), span.lo(), span.ctxt());
303             let end_of_attr_to_item = Span::new(attr.span.hi(), span.lo(), span.ctxt());
304
305             if let Some(snippet) = snippet_opt(cx, end_of_attr_to_item) {
306                 let lines = snippet.split('\n').collect::<Vec<_>>();
307                 let lines = without_block_comments(lines);
308
309                 if lines.iter().filter(|l| l.trim().is_empty()).count() > 2 {
310                     span_lint(
311                         cx,
312                         EMPTY_LINE_AFTER_OUTER_ATTR,
313                         begin_of_attr_to_item,
314                         "Found an empty line after an outer attribute. Perhaps you forgot to add a '!' to make it an inner attribute?"
315                     );
316                 }
317             }
318         }
319
320         if let Some(ref values) = attr.meta_item_list() {
321             if values.len() != 1 || attr.name() != "inline" {
322                 continue;
323             }
324             if is_word(&values[0], "always") {
325                 span_lint(
326                     cx,
327                     INLINE_ALWAYS,
328                     attr.span,
329                     &format!(
330                         "you have declared `#[inline(always)]` on `{}`. This is usually a bad idea",
331                         name
332                     ),
333                 );
334             }
335         }
336     }
337 }
338
339 fn check_semver(cx: &LateContext<'_, '_>, span: Span, lit: &Lit) {
340     if let LitKind::Str(ref is, _) = lit.node {
341         if Version::parse(&is.as_str()).is_ok() {
342             return;
343         }
344     }
345     span_lint(
346         cx,
347         DEPRECATED_SEMVER,
348         span,
349         "the since field must contain a semver-compliant version",
350     );
351 }
352
353 fn is_word(nmi: &NestedMetaItem, expected: &str) -> bool {
354     if let NestedMetaItemKind::MetaItem(ref mi) = nmi.node {
355         mi.is_word() && mi.name() == expected
356     } else {
357         false
358     }
359 }
360
361 // If the snippet is empty, it's an attribute that was inserted during macro
362 // expansion and we want to ignore those, because they could come from external
363 // sources that the user has no control over.
364 // For some reason these attributes don't have any expansion info on them, so
365 // we have to check it this way until there is a better way.
366 fn is_present_in_source(cx: &LateContext<'_, '_>, span: Span) -> bool {
367     if let Some(snippet) = snippet_opt(cx, span) {
368         if snippet.is_empty() {
369             return false;
370         }
371     }
372     true
373 }