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