]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/attrs.rs
Merge commit 'f51aade56f93175dde89177a92e3669ebd8e7592' into clippyup
[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, 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::sym;
21 use rustc_span::symbol::Symbol;
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_attribute(&mut self, cx: &LateContext<'tcx>, attr: &'tcx Attribute) {
307         if let Some(items) = &attr.meta_item_list() {
308             if let Some(ident) = attr.ident() {
309                 if is_lint_level(ident.name) {
310                     check_clippy_lint_names(cx, ident.name, items);
311                 }
312                 if matches!(ident.name, sym::allow | sym::expect) {
313                     check_lint_reason(cx, ident.name, items, attr);
314                 }
315                 if items.is_empty() || !attr.has_name(sym::deprecated) {
316                     return;
317                 }
318                 for item in items {
319                     if_chain! {
320                         if let NestedMetaItem::MetaItem(mi) = &item;
321                         if let MetaItemKind::NameValue(lit) = &mi.kind;
322                         if mi.has_name(sym::since);
323                         then {
324                             check_semver(cx, item.span(), lit);
325                         }
326                     }
327                 }
328             }
329         }
330     }
331
332     fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
333         let attrs = cx.tcx.hir().attrs(item.hir_id());
334         if is_relevant_item(cx, item) {
335             check_attrs(cx, item.span, item.ident.name, attrs);
336         }
337         match item.kind {
338             ItemKind::ExternCrate(..) | ItemKind::Use(..) => {
339                 let skip_unused_imports = attrs.iter().any(|attr| attr.has_name(sym::macro_use));
340
341                 for attr in attrs {
342                     if in_external_macro(cx.sess(), attr.span) {
343                         return;
344                     }
345                     if let Some(lint_list) = &attr.meta_item_list() {
346                         if attr.ident().map_or(false, |ident| is_lint_level(ident.name)) {
347                             for lint in lint_list {
348                                 match item.kind {
349                                     ItemKind::Use(..) => {
350                                         if is_word(lint, sym::unused_imports)
351                                             || is_word(lint, sym::deprecated)
352                                             || is_word(lint, sym!(unreachable_pub))
353                                             || is_word(lint, sym!(unused))
354                                             || extract_clippy_lint(lint).map_or(false, |s| {
355                                                 matches!(
356                                                     s.as_str(),
357                                                     "wildcard_imports"
358                                                         | "enum_glob_use"
359                                                         | "redundant_pub_crate"
360                                                         | "macro_use_imports",
361                                                 )
362                                             })
363                                         {
364                                             return;
365                                         }
366                                     },
367                                     ItemKind::ExternCrate(..) => {
368                                         if is_word(lint, sym::unused_imports) && skip_unused_imports {
369                                             return;
370                                         }
371                                         if is_word(lint, sym!(unused_extern_crates)) {
372                                             return;
373                                         }
374                                     },
375                                     _ => {},
376                                 }
377                             }
378                             let line_span = first_line_of_span(cx, attr.span);
379
380                             if let Some(mut sugg) = snippet_opt(cx, line_span) {
381                                 if sugg.contains("#[") {
382                                     span_lint_and_then(
383                                         cx,
384                                         USELESS_ATTRIBUTE,
385                                         line_span,
386                                         "useless lint attribute",
387                                         |diag| {
388                                             sugg = sugg.replacen("#[", "#![", 1);
389                                             diag.span_suggestion(
390                                                 line_span,
391                                                 "if you just forgot a `!`, use",
392                                                 sugg,
393                                                 Applicability::MaybeIncorrect,
394                                             );
395                                         },
396                                     );
397                                 }
398                             }
399                         }
400                     }
401                 }
402             },
403             _ => {},
404         }
405     }
406
407     fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx ImplItem<'_>) {
408         if is_relevant_impl(cx, item) {
409             check_attrs(cx, item.span, item.ident.name, cx.tcx.hir().attrs(item.hir_id()));
410         }
411     }
412
413     fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
414         if is_relevant_trait(cx, item) {
415             check_attrs(cx, item.span, item.ident.name, cx.tcx.hir().attrs(item.hir_id()));
416         }
417     }
418 }
419
420 /// Returns the lint name if it is clippy lint.
421 fn extract_clippy_lint(lint: &NestedMetaItem) -> Option<Symbol> {
422     if_chain! {
423         if let Some(meta_item) = lint.meta_item();
424         if meta_item.path.segments.len() > 1;
425         if let tool_name = meta_item.path.segments[0].ident;
426         if tool_name.name == sym::clippy;
427         then {
428             let lint_name = meta_item.path.segments.last().unwrap().ident.name;
429             return Some(lint_name);
430         }
431     }
432     None
433 }
434
435 fn check_clippy_lint_names(cx: &LateContext<'_>, name: Symbol, items: &[NestedMetaItem]) {
436     for lint in items {
437         if let Some(lint_name) = extract_clippy_lint(lint) {
438             if lint_name.as_str() == "restriction" && name != sym::allow {
439                 span_lint_and_help(
440                     cx,
441                     BLANKET_CLIPPY_RESTRICTION_LINTS,
442                     lint.span(),
443                     "restriction lints are not meant to be all enabled",
444                     None,
445                     "try enabling only the lints you really need",
446                 );
447             }
448         }
449     }
450 }
451
452 fn check_lint_reason(cx: &LateContext<'_>, name: Symbol, items: &[NestedMetaItem], attr: &'_ Attribute) {
453     // Check for the feature
454     if !cx.tcx.sess.features_untracked().lint_reasons {
455         return;
456     }
457
458     // Check if the reason is present
459     if let Some(item) = items.last().and_then(NestedMetaItem::meta_item)
460         && let MetaItemKind::NameValue(_) = &item.kind
461         && item.path == sym::reason
462     {
463         return;
464     }
465
466     span_lint_and_help(
467         cx,
468         ALLOW_ATTRIBUTES_WITHOUT_REASON,
469         attr.span,
470         &format!("`{}` attribute without specifying a reason", name.as_str()),
471         None,
472         "try adding a reason at the end with `, reason = \"..\"`",
473     );
474 }
475
476 fn is_relevant_item(cx: &LateContext<'_>, item: &Item<'_>) -> bool {
477     if let ItemKind::Fn(_, _, eid) = item.kind {
478         is_relevant_expr(cx, cx.tcx.typeck_body(eid), &cx.tcx.hir().body(eid).value)
479     } else {
480         true
481     }
482 }
483
484 fn is_relevant_impl(cx: &LateContext<'_>, item: &ImplItem<'_>) -> bool {
485     match item.kind {
486         ImplItemKind::Fn(_, eid) => is_relevant_expr(cx, cx.tcx.typeck_body(eid), &cx.tcx.hir().body(eid).value),
487         _ => false,
488     }
489 }
490
491 fn is_relevant_trait(cx: &LateContext<'_>, item: &TraitItem<'_>) -> bool {
492     match item.kind {
493         TraitItemKind::Fn(_, TraitFn::Required(_)) => true,
494         TraitItemKind::Fn(_, TraitFn::Provided(eid)) => {
495             is_relevant_expr(cx, cx.tcx.typeck_body(eid), &cx.tcx.hir().body(eid).value)
496         },
497         _ => false,
498     }
499 }
500
501 fn is_relevant_block(cx: &LateContext<'_>, typeck_results: &ty::TypeckResults<'_>, block: &Block<'_>) -> bool {
502     block.stmts.first().map_or(
503         block
504             .expr
505             .as_ref()
506             .map_or(false, |e| is_relevant_expr(cx, typeck_results, e)),
507         |stmt| match &stmt.kind {
508             StmtKind::Local(_) => true,
509             StmtKind::Expr(expr) | StmtKind::Semi(expr) => is_relevant_expr(cx, typeck_results, expr),
510             StmtKind::Item(_) => false,
511         },
512     )
513 }
514
515 fn is_relevant_expr(cx: &LateContext<'_>, typeck_results: &ty::TypeckResults<'_>, expr: &Expr<'_>) -> bool {
516     if macro_backtrace(expr.span).last().map_or(false, |macro_call| {
517         is_panic(cx, macro_call.def_id) || cx.tcx.item_name(macro_call.def_id) == sym::unreachable
518     }) {
519         return false;
520     }
521     match &expr.kind {
522         ExprKind::Block(block, _) => is_relevant_block(cx, typeck_results, block),
523         ExprKind::Ret(Some(e)) => is_relevant_expr(cx, typeck_results, e),
524         ExprKind::Ret(None) | ExprKind::Break(_, None) => false,
525         _ => true,
526     }
527 }
528
529 fn check_attrs(cx: &LateContext<'_>, span: Span, name: Symbol, attrs: &[Attribute]) {
530     if span.from_expansion() {
531         return;
532     }
533
534     for attr in attrs {
535         if let Some(values) = attr.meta_item_list() {
536             if values.len() != 1 || !attr.has_name(sym::inline) {
537                 continue;
538             }
539             if is_word(&values[0], sym::always) {
540                 span_lint(
541                     cx,
542                     INLINE_ALWAYS,
543                     attr.span,
544                     &format!(
545                         "you have declared `#[inline(always)]` on `{}`. This is usually a bad idea",
546                         name
547                     ),
548                 );
549             }
550         }
551     }
552 }
553
554 fn check_semver(cx: &LateContext<'_>, span: Span, lit: &Lit) {
555     if let LitKind::Str(is, _) = lit.kind {
556         if Version::parse(is.as_str()).is_ok() {
557             return;
558         }
559     }
560     span_lint(
561         cx,
562         DEPRECATED_SEMVER,
563         span,
564         "the since field must contain a semver-compliant version",
565     );
566 }
567
568 fn is_word(nmi: &NestedMetaItem, expected: Symbol) -> bool {
569     if let NestedMetaItem::MetaItem(mi) = &nmi {
570         mi.is_word() && mi.has_name(expected)
571     } else {
572         false
573     }
574 }
575
576 pub struct EarlyAttributes {
577     pub msrv: Option<RustcVersion>,
578 }
579
580 impl_lint_pass!(EarlyAttributes => [
581     DEPRECATED_CFG_ATTR,
582     MISMATCHED_TARGET_OS,
583     EMPTY_LINE_AFTER_OUTER_ATTR,
584 ]);
585
586 impl EarlyLintPass for EarlyAttributes {
587     fn check_item(&mut self, cx: &EarlyContext<'_>, item: &rustc_ast::Item) {
588         check_empty_line_after_outer_attr(cx, item);
589     }
590
591     fn check_attribute(&mut self, cx: &EarlyContext<'_>, attr: &Attribute) {
592         check_deprecated_cfg_attr(cx, attr, self.msrv);
593         check_mismatched_target_os(cx, attr);
594     }
595
596     extract_msrv_attr!(EarlyContext);
597 }
598
599 fn check_empty_line_after_outer_attr(cx: &EarlyContext<'_>, item: &rustc_ast::Item) {
600     let mut iter = item.attrs.iter().peekable();
601     while let Some(attr) = iter.next() {
602         if matches!(attr.kind, AttrKind::Normal(..))
603             && attr.style == AttrStyle::Outer
604             && is_present_in_source(cx, attr.span)
605         {
606             let begin_of_attr_to_item = Span::new(attr.span.lo(), item.span.lo(), item.span.ctxt(), item.span.parent());
607             let end_of_attr_to_next_attr_or_item = Span::new(
608                 attr.span.hi(),
609                 iter.peek().map_or(item.span.lo(), |next_attr| next_attr.span.lo()),
610                 item.span.ctxt(),
611                 item.span.parent(),
612             );
613
614             if let Some(snippet) = snippet_opt(cx, end_of_attr_to_next_attr_or_item) {
615                 let lines = snippet.split('\n').collect::<Vec<_>>();
616                 let lines = without_block_comments(lines);
617
618                 if lines.iter().filter(|l| l.trim().is_empty()).count() > 2 {
619                     span_lint(
620                         cx,
621                         EMPTY_LINE_AFTER_OUTER_ATTR,
622                         begin_of_attr_to_item,
623                         "found an empty line after an outer attribute. \
624                         Perhaps you forgot to add a `!` to make it an inner attribute?",
625                     );
626                 }
627             }
628         }
629     }
630 }
631
632 fn check_deprecated_cfg_attr(cx: &EarlyContext<'_>, attr: &Attribute, msrv: Option<RustcVersion>) {
633     if_chain! {
634         if meets_msrv(msrv, msrvs::TOOL_ATTRIBUTES);
635         // check cfg_attr
636         if attr.has_name(sym::cfg_attr);
637         if let Some(items) = attr.meta_item_list();
638         if items.len() == 2;
639         // check for `rustfmt`
640         if let Some(feature_item) = items[0].meta_item();
641         if feature_item.has_name(sym::rustfmt);
642         // check for `rustfmt_skip` and `rustfmt::skip`
643         if let Some(skip_item) = &items[1].meta_item();
644         if skip_item.has_name(sym!(rustfmt_skip))
645             || skip_item
646                 .path
647                 .segments
648                 .last()
649                 .expect("empty path in attribute")
650                 .ident
651                 .name
652                 == sym::skip;
653         // Only lint outer attributes, because custom inner attributes are unstable
654         // Tracking issue: https://github.com/rust-lang/rust/issues/54726
655         if attr.style == AttrStyle::Outer;
656         then {
657             span_lint_and_sugg(
658                 cx,
659                 DEPRECATED_CFG_ATTR,
660                 attr.span,
661                 "`cfg_attr` is deprecated for rustfmt and got replaced by tool attributes",
662                 "use",
663                 "#[rustfmt::skip]".to_string(),
664                 Applicability::MachineApplicable,
665             );
666         }
667     }
668 }
669
670 fn check_mismatched_target_os(cx: &EarlyContext<'_>, attr: &Attribute) {
671     fn find_os(name: &str) -> Option<&'static str> {
672         UNIX_SYSTEMS
673             .iter()
674             .chain(NON_UNIX_SYSTEMS.iter())
675             .find(|&&os| os == name)
676             .copied()
677     }
678
679     fn is_unix(name: &str) -> bool {
680         UNIX_SYSTEMS.iter().any(|&os| os == name)
681     }
682
683     fn find_mismatched_target_os(items: &[NestedMetaItem]) -> Vec<(&str, Span)> {
684         let mut mismatched = Vec::new();
685
686         for item in items {
687             if let NestedMetaItem::MetaItem(meta) = item {
688                 match &meta.kind {
689                     MetaItemKind::List(list) => {
690                         mismatched.extend(find_mismatched_target_os(list));
691                     },
692                     MetaItemKind::Word => {
693                         if_chain! {
694                             if let Some(ident) = meta.ident();
695                             if let Some(os) = find_os(ident.name.as_str());
696                             then {
697                                 mismatched.push((os, ident.span));
698                             }
699                         }
700                     },
701                     MetaItemKind::NameValue(..) => {},
702                 }
703             }
704         }
705
706         mismatched
707     }
708
709     if_chain! {
710         if attr.has_name(sym::cfg);
711         if let Some(list) = attr.meta_item_list();
712         let mismatched = find_mismatched_target_os(&list);
713         if !mismatched.is_empty();
714         then {
715             let mess = "operating system used in target family position";
716
717             span_lint_and_then(cx, MISMATCHED_TARGET_OS, attr.span, mess, |diag| {
718                 // Avoid showing the unix suggestion multiple times in case
719                 // we have more than one mismatch for unix-like systems
720                 let mut unix_suggested = false;
721
722                 for (os, span) in mismatched {
723                     let sugg = format!("target_os = \"{}\"", os);
724                     diag.span_suggestion(span, "try", sugg, Applicability::MaybeIncorrect);
725
726                     if !unix_suggested && is_unix(os) {
727                         diag.help("did you mean `unix`?");
728                         unix_suggested = true;
729                     }
730                 }
731             });
732         }
733     }
734 }
735
736 fn is_lint_level(symbol: Symbol) -> bool {
737     matches!(symbol, sym::allow | sym::expect | sym::warn | sym::deny | sym::forbid)
738 }