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