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