|
| 1 | +use rustc_ast::{Attribute, MetaItemInner, MetaItemKind}; |
| 2 | +use rustc_session::{declare_lint, declare_lint_pass}; |
| 3 | +use rustc_span::sym; |
| 4 | + |
| 5 | +use crate::{EarlyContext, EarlyLintPass, LintContext, lints}; |
| 6 | + |
| 7 | +declare_lint! { |
| 8 | + /// The `empty_cfg_predicate` lint detects the use of empty `cfg` predicate lists. |
| 9 | + /// |
| 10 | + /// ### Example |
| 11 | + /// |
| 12 | + /// ```rust,compile_fail |
| 13 | + /// #![deny(empty_cfg_predicate)] |
| 14 | + /// #[cfg(any())] |
| 15 | + /// fn foo() {} |
| 16 | + /// |
| 17 | + /// #[cfg(all())] |
| 18 | + /// fn bar() {} |
| 19 | + /// ``` |
| 20 | + /// |
| 21 | + /// {{produces}} |
| 22 | + /// |
| 23 | + /// ### Explanation |
| 24 | + /// |
| 25 | + /// The meaning of `cfg(any())` and `cfg(all())` is not immediately obvious; |
| 26 | + /// `cfg(false)` and `cfg(true)` respectively may be used instead. |
| 27 | + pub EMPTY_CFG_PREDICATE, |
| 28 | + Warn, |
| 29 | + "detects use of empty `cfg(any())` and `cfg(all())`" |
| 30 | +} |
| 31 | + |
| 32 | +declare_lint_pass!(EmptyCfgPredicate => [EMPTY_CFG_PREDICATE]); |
| 33 | + |
| 34 | +impl EarlyLintPass for EmptyCfgPredicate { |
| 35 | + fn check_attribute(&mut self, cx: &EarlyContext<'_>, attr: &Attribute) { |
| 36 | + if attr.has_any_name(&[sym::cfg, sym::cfg_attr]) |
| 37 | + && let Some(items) = attr.meta_item_list() |
| 38 | + && let Some(predicate) = items.get(0) |
| 39 | + { |
| 40 | + check_predicate(cx, predicate); |
| 41 | + } |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +fn check_predicate(cx: &EarlyContext<'_>, predicate: &MetaItemInner) { |
| 46 | + if let MetaItemInner::MetaItem(predicate) = predicate |
| 47 | + && let MetaItemKind::List(mis) = &predicate.kind |
| 48 | + { |
| 49 | + match predicate.name() { |
| 50 | + Some(predicate_name @ (sym::any | sym::all)) => { |
| 51 | + if mis.is_empty() { |
| 52 | + let span = predicate.span; |
| 53 | + cx.emit_span_lint( |
| 54 | + EMPTY_CFG_PREDICATE, |
| 55 | + span, |
| 56 | + lints::EmptyCfgPredicate { |
| 57 | + predicate_span: span, |
| 58 | + predicate: predicate_name, |
| 59 | + lit: predicate_name == sym::all, |
| 60 | + }, |
| 61 | + ); |
| 62 | + } else { |
| 63 | + for item in mis { |
| 64 | + check_predicate(cx, item); |
| 65 | + } |
| 66 | + } |
| 67 | + } |
| 68 | + Some(sym::not) => { |
| 69 | + for item in mis { |
| 70 | + check_predicate(cx, item); |
| 71 | + } |
| 72 | + } |
| 73 | + _ => (), |
| 74 | + } |
| 75 | + } |
| 76 | +} |
0 commit comments