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