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