]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/attrs.rs
Auto merge of #74060 - kpp:remove_length_at_most_32, r=dtolnay
[rust.git] / src / tools / clippy / 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_help,
6     span_lint_and_sugg, 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, 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] = &["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 permits `#[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 `warn`/`deny`/`forbid` attributes targeting the whole clippy::restriction category.
187     ///
188     /// **Why is this bad?** Restriction lints sometimes are in contrast with other lints or even go against idiomatic rust.
189     /// These lints should only be enabled on a lint-by-lint basis and with careful consideration.
190     ///
191     /// **Known problems:** None.
192     ///
193     /// **Example:**
194     /// Bad:
195     /// ```rust
196     /// #![deny(clippy::restriction)]
197     /// ```
198     ///
199     /// Good:
200     /// ```rust
201     /// #![deny(clippy::as_conversions)]
202     /// ```
203     pub BLANKET_CLIPPY_RESTRICTION_LINTS,
204     style,
205     "enabling the complete restriction group"
206 }
207
208 declare_clippy_lint! {
209     /// **What it does:** Checks for `#[cfg_attr(rustfmt, rustfmt_skip)]` and suggests to replace it
210     /// with `#[rustfmt::skip]`.
211     ///
212     /// **Why is this bad?** Since tool_attributes ([rust-lang/rust#44690](https://github.com/rust-lang/rust/issues/44690))
213     /// are stable now, they should be used instead of the old `cfg_attr(rustfmt)` attributes.
214     ///
215     /// **Known problems:** This lint doesn't detect crate level inner attributes, because they get
216     /// processed before the PreExpansionPass lints get executed. See
217     /// [#3123](https://github.com/rust-lang/rust-clippy/pull/3123#issuecomment-422321765)
218     ///
219     /// **Example:**
220     ///
221     /// Bad:
222     /// ```rust
223     /// #[cfg_attr(rustfmt, rustfmt_skip)]
224     /// fn main() { }
225     /// ```
226     ///
227     /// Good:
228     /// ```rust
229     /// #[rustfmt::skip]
230     /// fn main() { }
231     /// ```
232     pub DEPRECATED_CFG_ATTR,
233     complexity,
234     "usage of `cfg_attr(rustfmt)` instead of tool attributes"
235 }
236
237 declare_clippy_lint! {
238     /// **What it does:** Checks for cfg attributes having operating systems used in target family position.
239     ///
240     /// **Why is this bad?** The configuration option will not be recognised and the related item will not be included
241     /// by the conditional compilation engine.
242     ///
243     /// **Known problems:** None.
244     ///
245     /// **Example:**
246     ///
247     /// Bad:
248     /// ```rust
249     /// #[cfg(linux)]
250     /// fn conditional() { }
251     /// ```
252     ///
253     /// Good:
254     /// ```rust
255     /// #[cfg(target_os = "linux")]
256     /// fn conditional() { }
257     /// ```
258     ///
259     /// Or:
260     /// ```rust
261     /// #[cfg(unix)]
262     /// fn conditional() { }
263     /// ```
264     /// Check the [Rust Reference](https://doc.rust-lang.org/reference/conditional-compilation.html#target_os) for more details.
265     pub MISMATCHED_TARGET_OS,
266     correctness,
267     "usage of `cfg(operating_system)` instead of `cfg(target_os = \"operating_system\")`"
268 }
269
270 declare_lint_pass!(Attributes => [
271     INLINE_ALWAYS,
272     DEPRECATED_SEMVER,
273     USELESS_ATTRIBUTE,
274     UNKNOWN_CLIPPY_LINTS,
275     BLANKET_CLIPPY_RESTRICTION_LINTS,
276 ]);
277
278 impl<'tcx> LateLintPass<'tcx> for Attributes {
279     fn check_attribute(&mut self, cx: &LateContext<'tcx>, attr: &'tcx Attribute) {
280         if let Some(items) = &attr.meta_item_list() {
281             if let Some(ident) = attr.ident() {
282                 let ident = &*ident.as_str();
283                 match ident {
284                     "allow" | "warn" | "deny" | "forbid" => {
285                         check_clippy_lint_names(cx, ident, items);
286                     },
287                     _ => {},
288                 }
289                 if items.is_empty() || !attr.check_name(sym!(deprecated)) {
290                     return;
291                 }
292                 for item in items {
293                     if_chain! {
294                         if let NestedMetaItem::MetaItem(mi) = &item;
295                         if let MetaItemKind::NameValue(lit) = &mi.kind;
296                         if mi.check_name(sym!(since));
297                         then {
298                             check_semver(cx, item.span(), lit);
299                         }
300                     }
301                 }
302             }
303         }
304     }
305
306     fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
307         if is_relevant_item(cx, item) {
308             check_attrs(cx, item.span, item.ident.name, &item.attrs)
309         }
310         match item.kind {
311             ItemKind::ExternCrate(..) | ItemKind::Use(..) => {
312                 let skip_unused_imports = item.attrs.iter().any(|attr| attr.check_name(sym!(macro_use)));
313
314                 for attr in item.attrs {
315                     if in_external_macro(cx.sess(), attr.span) {
316                         return;
317                     }
318                     if let Some(lint_list) = &attr.meta_item_list() {
319                         if let Some(ident) = attr.ident() {
320                             match &*ident.as_str() {
321                                 "allow" | "warn" | "deny" | "forbid" => {
322                                     // permit `unused_imports`, `deprecated` and `unreachable_pub` for `use` items
323                                     // and `unused_imports` for `extern crate` items with `macro_use`
324                                     for lint in lint_list {
325                                         match item.kind {
326                                             ItemKind::Use(..) => {
327                                                 if is_word(lint, sym!(unused_imports))
328                                                     || is_word(lint, sym!(deprecated))
329                                                     || is_word(lint, sym!(unreachable_pub))
330                                                     || is_word(lint, sym!(unused))
331                                                 {
332                                                     return;
333                                                 }
334                                             },
335                                             ItemKind::ExternCrate(..) => {
336                                                 if is_word(lint, sym!(unused_imports)) && skip_unused_imports {
337                                                     return;
338                                                 }
339                                                 if is_word(lint, sym!(unused_extern_crates)) {
340                                                     return;
341                                                 }
342                                             },
343                                             _ => {},
344                                         }
345                                     }
346                                     let line_span = first_line_of_span(cx, attr.span);
347
348                                     if let Some(mut sugg) = snippet_opt(cx, line_span) {
349                                         if sugg.contains("#[") {
350                                             span_lint_and_then(
351                                                 cx,
352                                                 USELESS_ATTRIBUTE,
353                                                 line_span,
354                                                 "useless lint attribute",
355                                                 |diag| {
356                                                     sugg = sugg.replacen("#[", "#![", 1);
357                                                     diag.span_suggestion(
358                                                         line_span,
359                                                         "if you just forgot a `!`, use",
360                                                         sugg,
361                                                         Applicability::MaybeIncorrect,
362                                                     );
363                                                 },
364                                             );
365                                         }
366                                     }
367                                 },
368                                 _ => {},
369                             }
370                         }
371                     }
372                 }
373             },
374             _ => {},
375         }
376     }
377
378     fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx ImplItem<'_>) {
379         if is_relevant_impl(cx, item) {
380             check_attrs(cx, item.span, item.ident.name, &item.attrs)
381         }
382     }
383
384     fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
385         if is_relevant_trait(cx, item) {
386             check_attrs(cx, item.span, item.ident.name, &item.attrs)
387         }
388     }
389 }
390
391 fn check_clippy_lint_names(cx: &LateContext<'_>, ident: &str, items: &[NestedMetaItem]) {
392     fn extract_name(lint: &NestedMetaItem) -> Option<SymbolStr> {
393         if_chain! {
394             if let Some(meta_item) = lint.meta_item();
395             if meta_item.path.segments.len() > 1;
396             if let tool_name = meta_item.path.segments[0].ident;
397             if tool_name.as_str() == "clippy";
398             let lint_name = meta_item.path.segments.last().unwrap().ident.name;
399             then {
400                 return Some(lint_name.as_str());
401             }
402         }
403         None
404     }
405
406     let lint_store = cx.lints();
407     for lint in items {
408         if let Some(lint_name) = extract_name(lint) {
409             if let CheckLintNameResult::Tool(Err((None, _))) =
410                 lint_store.check_lint_name(&lint_name, Some(sym!(clippy)))
411             {
412                 span_lint_and_then(
413                     cx,
414                     UNKNOWN_CLIPPY_LINTS,
415                     lint.span(),
416                     &format!("unknown clippy lint: clippy::{}", lint_name),
417                     |diag| {
418                         let name_lower = lint_name.to_lowercase();
419                         let symbols = lint_store
420                             .get_lints()
421                             .iter()
422                             .map(|l| Symbol::intern(&l.name_lower()))
423                             .collect::<Vec<_>>();
424                         let sugg = find_best_match_for_name(
425                             symbols.iter(),
426                             Symbol::intern(&format!("clippy::{}", name_lower)),
427                             None,
428                         );
429                         if lint_name.chars().any(char::is_uppercase)
430                             && lint_store.find_lints(&format!("clippy::{}", name_lower)).is_ok()
431                         {
432                             diag.span_suggestion(
433                                 lint.span(),
434                                 "lowercase the lint name",
435                                 format!("clippy::{}", name_lower),
436                                 Applicability::MachineApplicable,
437                             );
438                         } else if let Some(sugg) = sugg {
439                             diag.span_suggestion(
440                                 lint.span(),
441                                 "did you mean",
442                                 sugg.to_string(),
443                                 Applicability::MachineApplicable,
444                             );
445                         }
446                     },
447                 );
448             } else if lint_name == "restriction" && ident != "allow" {
449                 span_lint_and_help(
450                     cx,
451                     BLANKET_CLIPPY_RESTRICTION_LINTS,
452                     lint.span(),
453                     "restriction lints are not meant to be all enabled",
454                     None,
455                     "try enabling only the lints you really need",
456                 );
457             }
458         }
459     }
460 }
461
462 fn is_relevant_item(cx: &LateContext<'_>, item: &Item<'_>) -> bool {
463     if let ItemKind::Fn(_, _, eid) = item.kind {
464         is_relevant_expr(cx, cx.tcx.typeck_body(eid), &cx.tcx.hir().body(eid).value)
465     } else {
466         true
467     }
468 }
469
470 fn is_relevant_impl(cx: &LateContext<'_>, item: &ImplItem<'_>) -> bool {
471     match item.kind {
472         ImplItemKind::Fn(_, eid) => is_relevant_expr(cx, cx.tcx.typeck_body(eid), &cx.tcx.hir().body(eid).value),
473         _ => false,
474     }
475 }
476
477 fn is_relevant_trait(cx: &LateContext<'_>, item: &TraitItem<'_>) -> bool {
478     match item.kind {
479         TraitItemKind::Fn(_, TraitFn::Required(_)) => true,
480         TraitItemKind::Fn(_, TraitFn::Provided(eid)) => {
481             is_relevant_expr(cx, cx.tcx.typeck_body(eid), &cx.tcx.hir().body(eid).value)
482         },
483         _ => false,
484     }
485 }
486
487 fn is_relevant_block(cx: &LateContext<'_>, typeck_results: &ty::TypeckResults<'_>, block: &Block<'_>) -> bool {
488     block.stmts.first().map_or(
489         block
490             .expr
491             .as_ref()
492             .map_or(false, |e| is_relevant_expr(cx, typeck_results, e)),
493         |stmt| match &stmt.kind {
494             StmtKind::Local(_) => true,
495             StmtKind::Expr(expr) | StmtKind::Semi(expr) => is_relevant_expr(cx, typeck_results, expr),
496             _ => false,
497         },
498     )
499 }
500
501 fn is_relevant_expr(cx: &LateContext<'_>, typeck_results: &ty::TypeckResults<'_>, expr: &Expr<'_>) -> bool {
502     match &expr.kind {
503         ExprKind::Block(block, _) => is_relevant_block(cx, typeck_results, block),
504         ExprKind::Ret(Some(e)) => is_relevant_expr(cx, typeck_results, e),
505         ExprKind::Ret(None) | ExprKind::Break(_, None) => false,
506         ExprKind::Call(path_expr, _) => {
507             if let ExprKind::Path(qpath) = &path_expr.kind {
508                 typeck_results
509                     .qpath_res(qpath, path_expr.hir_id)
510                     .opt_def_id()
511                     .map_or(true, |fun_id| !match_def_path(cx, fun_id, &paths::BEGIN_PANIC))
512             } else {
513                 true
514             }
515         },
516         _ => true,
517     }
518 }
519
520 fn check_attrs(cx: &LateContext<'_>, span: Span, name: Name, attrs: &[Attribute]) {
521     if span.from_expansion() {
522         return;
523     }
524
525     for attr in attrs {
526         if let Some(values) = attr.meta_item_list() {
527             if values.len() != 1 || !attr.check_name(sym!(inline)) {
528                 continue;
529             }
530             if is_word(&values[0], sym!(always)) {
531                 span_lint(
532                     cx,
533                     INLINE_ALWAYS,
534                     attr.span,
535                     &format!(
536                         "you have declared `#[inline(always)]` on `{}`. This is usually a bad idea",
537                         name
538                     ),
539                 );
540             }
541         }
542     }
543 }
544
545 fn check_semver(cx: &LateContext<'_>, span: Span, lit: &Lit) {
546     if let LitKind::Str(is, _) = lit.kind {
547         if Version::parse(&is.as_str()).is_ok() {
548             return;
549         }
550     }
551     span_lint(
552         cx,
553         DEPRECATED_SEMVER,
554         span,
555         "the since field must contain a semver-compliant version",
556     );
557 }
558
559 fn is_word(nmi: &NestedMetaItem, expected: Symbol) -> bool {
560     if let NestedMetaItem::MetaItem(mi) = &nmi {
561         mi.is_word() && mi.check_name(expected)
562     } else {
563         false
564     }
565 }
566
567 declare_lint_pass!(EarlyAttributes => [
568     DEPRECATED_CFG_ATTR,
569     MISMATCHED_TARGET_OS,
570     EMPTY_LINE_AFTER_OUTER_ATTR,
571 ]);
572
573 impl EarlyLintPass for EarlyAttributes {
574     fn check_item(&mut self, cx: &EarlyContext<'_>, item: &rustc_ast::ast::Item) {
575         check_empty_line_after_outer_attr(cx, item);
576     }
577
578     fn check_attribute(&mut self, cx: &EarlyContext<'_>, attr: &Attribute) {
579         check_deprecated_cfg_attr(cx, attr);
580         check_mismatched_target_os(cx, attr);
581     }
582 }
583
584 fn check_empty_line_after_outer_attr(cx: &EarlyContext<'_>, item: &rustc_ast::ast::Item) {
585     for attr in &item.attrs {
586         let attr_item = if let AttrKind::Normal(ref attr) = attr.kind {
587             attr
588         } else {
589             return;
590         };
591
592         if attr.style == AttrStyle::Outer {
593             if attr_item.args.inner_tokens().is_empty() || !is_present_in_source(cx, attr.span) {
594                 return;
595             }
596
597             let begin_of_attr_to_item = Span::new(attr.span.lo(), item.span.lo(), item.span.ctxt());
598             let end_of_attr_to_item = Span::new(attr.span.hi(), item.span.lo(), item.span.ctxt());
599
600             if let Some(snippet) = snippet_opt(cx, end_of_attr_to_item) {
601                 let lines = snippet.split('\n').collect::<Vec<_>>();
602                 let lines = without_block_comments(lines);
603
604                 if lines.iter().filter(|l| l.trim().is_empty()).count() > 2 {
605                     span_lint(
606                         cx,
607                         EMPTY_LINE_AFTER_OUTER_ATTR,
608                         begin_of_attr_to_item,
609                         "Found an empty line after an outer attribute. \
610                         Perhaps you forgot to add a `!` to make it an inner attribute?",
611                     );
612                 }
613             }
614         }
615     }
616 }
617
618 fn check_deprecated_cfg_attr(cx: &EarlyContext<'_>, attr: &Attribute) {
619     if_chain! {
620         // check cfg_attr
621         if attr.check_name(sym!(cfg_attr));
622         if let Some(items) = attr.meta_item_list();
623         if items.len() == 2;
624         // check for `rustfmt`
625         if let Some(feature_item) = items[0].meta_item();
626         if feature_item.check_name(sym!(rustfmt));
627         // check for `rustfmt_skip` and `rustfmt::skip`
628         if let Some(skip_item) = &items[1].meta_item();
629         if skip_item.check_name(sym!(rustfmt_skip)) ||
630             skip_item.path.segments.last().expect("empty path in attribute").ident.name == sym!(skip);
631         // Only lint outer attributes, because custom inner attributes are unstable
632         // Tracking issue: https://github.com/rust-lang/rust/issues/54726
633         if let AttrStyle::Outer = attr.style;
634         then {
635             span_lint_and_sugg(
636                 cx,
637                 DEPRECATED_CFG_ATTR,
638                 attr.span,
639                 "`cfg_attr` is deprecated for rustfmt and got replaced by tool attributes",
640                 "use",
641                 "#[rustfmt::skip]".to_string(),
642                 Applicability::MachineApplicable,
643             );
644         }
645     }
646 }
647
648 fn check_mismatched_target_os(cx: &EarlyContext<'_>, attr: &Attribute) {
649     fn find_os(name: &str) -> Option<&'static str> {
650         UNIX_SYSTEMS
651             .iter()
652             .chain(NON_UNIX_SYSTEMS.iter())
653             .find(|&&os| os == name)
654             .copied()
655     }
656
657     fn is_unix(name: &str) -> bool {
658         UNIX_SYSTEMS.iter().any(|&os| os == name)
659     }
660
661     fn find_mismatched_target_os(items: &[NestedMetaItem]) -> Vec<(&str, Span)> {
662         let mut mismatched = Vec::new();
663
664         for item in items {
665             if let NestedMetaItem::MetaItem(meta) = item {
666                 match &meta.kind {
667                     MetaItemKind::List(list) => {
668                         mismatched.extend(find_mismatched_target_os(&list));
669                     },
670                     MetaItemKind::Word => {
671                         if_chain! {
672                             if let Some(ident) = meta.ident();
673                             if let Some(os) = find_os(&*ident.name.as_str());
674                             then {
675                                 mismatched.push((os, ident.span));
676                             }
677                         }
678                     },
679                     _ => {},
680                 }
681             }
682         }
683
684         mismatched
685     }
686
687     if_chain! {
688         if attr.check_name(sym!(cfg));
689         if let Some(list) = attr.meta_item_list();
690         let mismatched = find_mismatched_target_os(&list);
691         if !mismatched.is_empty();
692         then {
693             let mess = "operating system used in target family position";
694
695             span_lint_and_then(cx, MISMATCHED_TARGET_OS, attr.span, &mess, |diag| {
696                 // Avoid showing the unix suggestion multiple times in case
697                 // we have more than one mismatch for unix-like systems
698                 let mut unix_suggested = false;
699
700                 for (os, span) in mismatched {
701                     let sugg = format!("target_os = \"{}\"", os);
702                     diag.span_suggestion(span, "try", sugg, Applicability::MaybeIncorrect);
703
704                     if !unix_suggested && is_unix(os) {
705                         diag.help("Did you mean `unix`?");
706                         unix_suggested = true;
707                     }
708                 }
709             });
710         }
711     }
712 }