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