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