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