]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/attrs.rs
formatting fix
[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_sugg,
6     span_lint_and_then, without_block_comments,
7 };
8 use if_chain::if_chain;
9 use rustc::hir::*;
10 use rustc::lint::{
11     CheckLintNameResult, EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintArray, LintContext, LintPass,
12 };
13 use rustc::ty::{self, TyCtxt};
14 use rustc::{declare_tool_lint, lint_array};
15 use rustc_errors::Applicability;
16 use semver::Version;
17 use syntax::ast::{AttrStyle, Attribute, Lit, LitKind, MetaItemKind, NestedMetaItem, NestedMetaItemKind};
18 use syntax::source_map::Span;
19
20 /// **What it does:** Checks for items annotated with `#[inline(always)]`,
21 /// unless the annotated function is empty or simply panics.
22 ///
23 /// **Why is this bad?** While there are valid uses of this annotation (and once
24 /// you know when to use it, by all means `allow` this lint), it's a common
25 /// newbie-mistake to pepper one's code with it.
26 ///
27 /// As a rule of thumb, before slapping `#[inline(always)]` on a function,
28 /// measure if that additional function call really affects your runtime profile
29 /// sufficiently to make up for the increase in compile time.
30 ///
31 /// **Known problems:** False positives, big time. This lint is meant to be
32 /// deactivated by everyone doing serious performance work. This means having
33 /// done the measurement.
34 ///
35 /// **Example:**
36 /// ```rust
37 /// #[inline(always)]
38 /// fn not_quite_hot_code(..) { ... }
39 /// ```
40 declare_clippy_lint! {
41     pub INLINE_ALWAYS,
42     pedantic,
43     "use of `#[inline(always)]`"
44 }
45
46 /// **What it does:** Checks for `extern crate` and `use` items annotated with
47 /// lint attributes.
48 ///
49 /// This lint whitelists `#[allow(unused_imports)]` and `#[allow(deprecated)]` on
50 /// `use` items and `#[allow(unused_imports)]` on `extern crate` items with a
51 /// `#[macro_use]` attribute.
52 ///
53 /// **Why is this bad?** Lint attributes have no effect on crate imports. Most
54 /// likely a `!` was forgotten.
55 ///
56 /// **Known problems:** None.
57 ///
58 /// **Example:**
59 /// ```rust
60 /// // Bad
61 /// #[deny(dead_code)]
62 /// extern crate foo;
63 /// #[forbid(dead_code)]
64 /// use foo::bar;
65 ///
66 /// // Ok
67 /// #[allow(unused_imports)]
68 /// use foo::baz;
69 /// #[allow(unused_imports)]
70 /// #[macro_use]
71 /// extern crate baz;
72 /// ```
73 declare_clippy_lint! {
74     pub USELESS_ATTRIBUTE,
75     correctness,
76     "use of lint attributes on `extern crate` items"
77 }
78
79 /// **What it does:** Checks for `#[deprecated]` annotations with a `since`
80 /// field that is not a valid semantic version.
81 ///
82 /// **Why is this bad?** For checking the version of the deprecation, it must be
83 /// a valid semver. Failing that, the contained information is useless.
84 ///
85 /// **Known problems:** None.
86 ///
87 /// **Example:**
88 /// ```rust
89 /// #[deprecated(since = "forever")]
90 /// fn something_else(..) { ... }
91 /// ```
92 declare_clippy_lint! {
93     pub DEPRECATED_SEMVER,
94     correctness,
95     "use of `#[deprecated(since = \"x\")]` where x is not semver"
96 }
97
98 /// **What it does:** Checks for empty lines after outer attributes
99 ///
100 /// **Why is this bad?**
101 /// Most likely the attribute was meant to be an inner attribute using a '!'.
102 /// If it was meant to be an outer attribute, then the following item
103 /// should not be separated by empty lines.
104 ///
105 /// **Known problems:** Can cause false positives.
106 ///
107 /// From the clippy side it's difficult to detect empty lines between an attributes and the
108 /// following item because empty lines and comments are not part of the AST. The parsing
109 /// currently works for basic cases but is not perfect.
110 ///
111 /// **Example:**
112 /// ```rust
113 /// // Bad
114 /// #[inline(always)]
115 ///
116 /// fn not_quite_good_code(..) { ... }
117 ///
118 /// // Good (as inner attribute)
119 /// #![inline(always)]
120 ///
121 /// fn this_is_fine(..) { ... }
122 ///
123 /// // Good (as outer attribute)
124 /// #[inline(always)]
125 /// fn this_is_fine_too(..) { ... }
126 /// ```
127 declare_clippy_lint! {
128     pub EMPTY_LINE_AFTER_OUTER_ATTR,
129     nursery,
130     "empty line after outer attribute"
131 }
132
133 /// **What it does:** Checks for `allow`/`warn`/`deny`/`forbid` attributes with scoped clippy
134 /// lints and if those lints exist in clippy. If there is a uppercase letter in the lint name
135 /// (not the tool name) and a lowercase version of this lint exists, it will suggest to lowercase
136 /// the lint name.
137 ///
138 /// **Why is this bad?** A lint attribute with a mistyped lint name won't have an effect.
139 ///
140 /// **Known problems:** None.
141 ///
142 /// **Example:**
143 /// Bad:
144 /// ```rust
145 /// #![warn(if_not_els)]
146 /// #![deny(clippy::All)]
147 /// ```
148 ///
149 /// Good:
150 /// ```rust
151 /// #![warn(if_not_else)]
152 /// #![deny(clippy::all)]
153 /// ```
154 declare_clippy_lint! {
155     pub UNKNOWN_CLIPPY_LINTS,
156     style,
157     "unknown_lints for scoped Clippy lints"
158 }
159
160 /// **What it does:** Checks for `#[cfg_attr(rustfmt, rustfmt_skip)]` and suggests to replace it
161 /// with `#[rustfmt::skip]`.
162 ///
163 /// **Why is this bad?** Since tool_attributes ([rust-lang/rust#44690](https://github.com/rust-lang/rust/issues/44690))
164 /// are stable now, they should be used instead of the old `cfg_attr(rustfmt)` attributes.
165 ///
166 /// **Known problems:** This lint doesn't detect crate level inner attributes, because they get
167 /// processed before the PreExpansionPass lints get executed. See
168 /// [#3123](https://github.com/rust-lang/rust-clippy/pull/3123#issuecomment-422321765)
169 ///
170 /// **Example:**
171 ///
172 /// Bad:
173 /// ```rust
174 /// #[cfg_attr(rustfmt, rustfmt_skip)]
175 /// fn main() { }
176 /// ```
177 ///
178 /// Good:
179 /// ```rust
180 /// #[rustfmt::skip]
181 /// fn main() { }
182 /// ```
183 declare_clippy_lint! {
184     pub DEPRECATED_CFG_ATTR,
185     complexity,
186     "usage of `cfg_attr(rustfmt)` instead of `tool_attributes`"
187 }
188
189 #[derive(Copy, Clone)]
190 pub struct AttrPass;
191
192 impl LintPass for AttrPass {
193     fn get_lints(&self) -> LintArray {
194         lint_array!(
195             INLINE_ALWAYS,
196             DEPRECATED_SEMVER,
197             USELESS_ATTRIBUTE,
198             EMPTY_LINE_AFTER_OUTER_ATTR,
199             UNKNOWN_CLIPPY_LINTS,
200         )
201     }
202 }
203
204 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AttrPass {
205     fn check_attribute(&mut self, cx: &LateContext<'a, 'tcx>, attr: &'tcx Attribute) {
206         if let Some(items) = &attr.meta_item_list() {
207             match &*attr.name().as_str() {
208                 "allow" | "warn" | "deny" | "forbid" => {
209                     check_clippy_lint_names(cx, items);
210                 },
211                 _ => {},
212             }
213             if items.is_empty() || attr.name() != "deprecated" {
214                 return;
215             }
216             for item in items {
217                 if_chain! {
218                     if let NestedMetaItemKind::MetaItem(mi) = &item.node;
219                     if let MetaItemKind::NameValue(lit) = &mi.node;
220                     if mi.name() == "since";
221                     then {
222                         check_semver(cx, item.span, lit);
223                     }
224                 }
225             }
226         }
227     }
228
229     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
230         if is_relevant_item(cx.tcx, item) {
231             check_attrs(cx, item.span, item.ident.name, &item.attrs)
232         }
233         match item.node {
234             ItemKind::ExternCrate(..) | ItemKind::Use(..) => {
235                 let skip_unused_imports = item.attrs.iter().any(|attr| attr.name() == "macro_use");
236
237                 for attr in &item.attrs {
238                     if let Some(lint_list) = &attr.meta_item_list() {
239                         match &*attr.name().as_str() {
240                             "allow" | "warn" | "deny" | "forbid" => {
241                                 // whitelist `unused_imports` and `deprecated` for `use` items
242                                 // and `unused_imports` for `extern crate` items with `macro_use`
243                                 for lint in lint_list {
244                                     match item.node {
245                                         ItemKind::Use(..) => {
246                                             if is_word(lint, "unused_imports") || is_word(lint, "deprecated") {
247                                                 return;
248                                             }
249                                         },
250                                         ItemKind::ExternCrate(..) => {
251                                             if is_word(lint, "unused_imports") && skip_unused_imports {
252                                                 return;
253                                             }
254                                             if is_word(lint, "unused_extern_crates") {
255                                                 return;
256                                             }
257                                         },
258                                         _ => {},
259                                     }
260                                 }
261                                 let line_span = last_line_of_span(cx, attr.span);
262
263                                 if let Some(mut sugg) = snippet_opt(cx, line_span) {
264                                     if sugg.contains("#[") {
265                                         span_lint_and_then(
266                                             cx,
267                                             USELESS_ATTRIBUTE,
268                                             line_span,
269                                             "useless lint attribute",
270                                             |db| {
271                                                 sugg = sugg.replacen("#[", "#![", 1);
272                                                 db.span_suggestion_with_applicability(
273                                                     line_span,
274                                                     "if you just forgot a `!`, use",
275                                                     sugg,
276                                                     Applicability::MachineApplicable,
277                                                 );
278                                             },
279                                         );
280                                     }
281                                 }
282                             },
283                             _ => {},
284                         }
285                     }
286                 }
287             },
288             _ => {},
289         }
290     }
291
292     fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx ImplItem) {
293         if is_relevant_impl(cx.tcx, item) {
294             check_attrs(cx, item.span, item.ident.name, &item.attrs)
295         }
296     }
297
298     fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx TraitItem) {
299         if is_relevant_trait(cx.tcx, item) {
300             check_attrs(cx, item.span, item.ident.name, &item.attrs)
301         }
302     }
303 }
304
305 #[allow(clippy::single_match_else)]
306 fn check_clippy_lint_names(cx: &LateContext<'_, '_>, items: &[NestedMetaItem]) {
307     let lint_store = cx.lints();
308     for lint in items {
309         if_chain! {
310             if let Some(word) = lint.word();
311             if let Some(tool_name) = word.is_scoped();
312             if tool_name.as_str() == "clippy";
313             let name = word.name();
314             if let CheckLintNameResult::Tool(Err((None, _))) = lint_store.check_lint_name(
315                 &name.as_str(),
316                 Some(tool_name.as_str()),
317             );
318             then {
319                 span_lint_and_then(
320                     cx,
321                     UNKNOWN_CLIPPY_LINTS,
322                     lint.span,
323                     &format!("unknown clippy lint: clippy::{}", name),
324                     |db| {
325                         if name.as_str().chars().any(|c| c.is_uppercase()) {
326                             let name_lower = name.as_str().to_lowercase();
327                             match lint_store.check_lint_name(
328                                 &name_lower,
329                                 Some(tool_name.as_str())
330                             ) {
331                                 // FIXME: can we suggest similar lint names here?
332                                 // https://github.com/rust-lang/rust/pull/56992
333                                 CheckLintNameResult::NoLint(None) => (),
334                                 _ => {
335                                     db.span_suggestion_with_applicability(
336                                         lint.span,
337                                         "lowercase the lint name",
338                                         name_lower,
339                                         Applicability::MaybeIncorrect,
340                                     );
341                                 }
342                             }
343                         }
344                     }
345                 );
346             }
347         };
348     }
349 }
350
351 fn is_relevant_item(tcx: TyCtxt<'_, '_, '_>, item: &Item) -> bool {
352     if let ItemKind::Fn(_, _, _, eid) = item.node {
353         is_relevant_expr(tcx, tcx.body_tables(eid), &tcx.hir().body(eid).value)
354     } else {
355         true
356     }
357 }
358
359 fn is_relevant_impl(tcx: TyCtxt<'_, '_, '_>, item: &ImplItem) -> bool {
360     match item.node {
361         ImplItemKind::Method(_, eid) => is_relevant_expr(tcx, tcx.body_tables(eid), &tcx.hir().body(eid).value),
362         _ => false,
363     }
364 }
365
366 fn is_relevant_trait(tcx: TyCtxt<'_, '_, '_>, item: &TraitItem) -> bool {
367     match item.node {
368         TraitItemKind::Method(_, TraitMethod::Required(_)) => true,
369         TraitItemKind::Method(_, TraitMethod::Provided(eid)) => {
370             is_relevant_expr(tcx, tcx.body_tables(eid), &tcx.hir().body(eid).value)
371         },
372         _ => false,
373     }
374 }
375
376 fn is_relevant_block(tcx: TyCtxt<'_, '_, '_>, tables: &ty::TypeckTables<'_>, block: &Block) -> bool {
377     if let Some(stmt) = block.stmts.first() {
378         match &stmt.node {
379             StmtKind::Decl(_, _) => true,
380             StmtKind::Expr(expr, _) | StmtKind::Semi(expr, _) => is_relevant_expr(tcx, tables, expr),
381         }
382     } else {
383         block.expr.as_ref().map_or(false, |e| is_relevant_expr(tcx, tables, e))
384     }
385 }
386
387 fn is_relevant_expr(tcx: TyCtxt<'_, '_, '_>, tables: &ty::TypeckTables<'_>, expr: &Expr) -> bool {
388     match &expr.node {
389         ExprKind::Block(block, _) => is_relevant_block(tcx, tables, block),
390         ExprKind::Ret(Some(e)) => is_relevant_expr(tcx, tables, e),
391         ExprKind::Ret(None) | ExprKind::Break(_, None) => false,
392         ExprKind::Call(path_expr, _) => {
393             if let ExprKind::Path(qpath) = &path_expr.node {
394                 if let Some(fun_id) = opt_def_id(tables.qpath_def(qpath, path_expr.hir_id)) {
395                     !match_def_path(tcx, fun_id, &paths::BEGIN_PANIC)
396                 } else {
397                     true
398                 }
399             } else {
400                 true
401             }
402         },
403         _ => true,
404     }
405 }
406
407 fn check_attrs(cx: &LateContext<'_, '_>, span: Span, name: Name, attrs: &[Attribute]) {
408     if in_macro(span) {
409         return;
410     }
411
412     for attr in attrs {
413         if attr.is_sugared_doc {
414             return;
415         }
416         if attr.style == AttrStyle::Outer {
417             if attr.tokens.is_empty() || !is_present_in_source(cx, attr.span) {
418                 return;
419             }
420
421             let begin_of_attr_to_item = Span::new(attr.span.lo(), span.lo(), span.ctxt());
422             let end_of_attr_to_item = Span::new(attr.span.hi(), span.lo(), span.ctxt());
423
424             if let Some(snippet) = snippet_opt(cx, end_of_attr_to_item) {
425                 let lines = snippet.split('\n').collect::<Vec<_>>();
426                 let lines = without_block_comments(lines);
427
428                 if lines.iter().filter(|l| l.trim().is_empty()).count() > 2 {
429                     span_lint(
430                         cx,
431                         EMPTY_LINE_AFTER_OUTER_ATTR,
432                         begin_of_attr_to_item,
433                         "Found an empty line after an outer attribute. \
434                          Perhaps you forgot to add a '!' to make it an inner attribute?",
435                     );
436                 }
437             }
438         }
439
440         if let Some(values) = attr.meta_item_list() {
441             if values.len() != 1 || attr.name() != "inline" {
442                 continue;
443             }
444             if is_word(&values[0], "always") {
445                 span_lint(
446                     cx,
447                     INLINE_ALWAYS,
448                     attr.span,
449                     &format!(
450                         "you have declared `#[inline(always)]` on `{}`. This is usually a bad idea",
451                         name
452                     ),
453                 );
454             }
455         }
456     }
457 }
458
459 fn check_semver(cx: &LateContext<'_, '_>, span: Span, lit: &Lit) {
460     if let LitKind::Str(is, _) = lit.node {
461         if Version::parse(&is.as_str()).is_ok() {
462             return;
463         }
464     }
465     span_lint(
466         cx,
467         DEPRECATED_SEMVER,
468         span,
469         "the since field must contain a semver-compliant version",
470     );
471 }
472
473 fn is_word(nmi: &NestedMetaItem, expected: &str) -> bool {
474     if let NestedMetaItemKind::MetaItem(mi) = &nmi.node {
475         mi.is_word() && mi.name() == expected
476     } else {
477         false
478     }
479 }
480
481 // If the snippet is empty, it's an attribute that was inserted during macro
482 // expansion and we want to ignore those, because they could come from external
483 // sources that the user has no control over.
484 // For some reason these attributes don't have any expansion info on them, so
485 // we have to check it this way until there is a better way.
486 fn is_present_in_source(cx: &LateContext<'_, '_>, span: Span) -> bool {
487     if let Some(snippet) = snippet_opt(cx, span) {
488         if snippet.is_empty() {
489             return false;
490         }
491     }
492     true
493 }
494
495 #[derive(Copy, Clone)]
496 pub struct CfgAttrPass;
497
498 impl LintPass for CfgAttrPass {
499     fn get_lints(&self) -> LintArray {
500         lint_array!(DEPRECATED_CFG_ATTR,)
501     }
502 }
503
504 impl EarlyLintPass for CfgAttrPass {
505     fn check_attribute(&mut self, cx: &EarlyContext<'_>, attr: &Attribute) {
506         if_chain! {
507             // check cfg_attr
508             if attr.name() == "cfg_attr";
509             if let Some(items) = attr.meta_item_list();
510             if items.len() == 2;
511             // check for `rustfmt`
512             if let Some(feature_item) = items[0].meta_item();
513             if feature_item.name() == "rustfmt";
514             // check for `rustfmt_skip` and `rustfmt::skip`
515             if let Some(skip_item) = &items[1].meta_item();
516             if skip_item.name() == "rustfmt_skip" || skip_item.name() == "skip";
517             // Only lint outer attributes, because custom inner attributes are unstable
518             // Tracking issue: https://github.com/rust-lang/rust/issues/54726
519             if let AttrStyle::Outer = attr.style;
520             then {
521                 span_lint_and_sugg(
522                     cx,
523                     DEPRECATED_CFG_ATTR,
524                     attr.span,
525                     "`cfg_attr` is deprecated for rustfmt and got replaced by tool_attributes",
526                     "use",
527                     "#[rustfmt::skip]".to_string(),
528                     Applicability::MachineApplicable,
529                 );
530             }
531         }
532     }
533 }