Skip to content

Commit 1d0027e

Browse files
committed
fix(ConstEvalCtxt): check if the const item is behind #[cfg]
1 parent 1c9c249 commit 1d0027e

File tree

2 files changed

+38
-6
lines changed

2 files changed

+38
-6
lines changed

clippy_utils/src/consts.rs

Lines changed: 26 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -638,21 +638,41 @@ impl<'tcx> ConstEvalCtxt<'tcx> {
638638
let res = self.typeck.qpath_res(qpath, id);
639639
match res {
640640
Res::Def(DefKind::Const | DefKind::AssocConst, def_id) => {
641-
// Check if this constant is based on `cfg!(..)`,
642-
// which is NOT constant for our purposes.
643641
if let Some(node) = self.tcx.hir_get_if_local(def_id)
644642
&& let Node::Item(Item {
645643
kind: ItemKind::Const(.., body_id),
644+
owner_id,
646645
..
647646
}) = node
648-
&& let Node::Expr(Expr {
647+
{
648+
// check for `const C: _ = cfg!(foo);`
649+
if let Node::Expr(Expr {
649650
kind: ExprKind::Lit(_),
650651
span,
651652
..
652653
}) = self.tcx.hir_node(body_id.hir_id)
653-
&& is_direct_expn_of(*span, sym::cfg).is_some()
654-
{
655-
return None;
654+
&& is_direct_expn_of(*span, sym::cfg).is_some()
655+
{
656+
return None;
657+
}
658+
659+
// check for:
660+
// ```
661+
// #[cfg(foo)]
662+
// const C: _ = _;
663+
// ```
664+
//
665+
// NOTE: it shouldn't be possible to have `#[cfg]` applied to the initializer, because e.g.
666+
// something like this wouldn't work:
667+
// const C: _ = {
668+
// #[cfg(foo)]
669+
// 1
670+
// #[cfg(bar)]
671+
// 2
672+
// };
673+
if self.tcx.has_attr(owner_id.def_id, sym::cfg_trace) {
674+
return None;
675+
}
656676
}
657677

658678
let args = self.typeck.node_args(id);

tests/ui/bit_masks.rs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,3 +86,15 @@ fn ineffective() {
8686
x | 3 > 4; // not an error (yet), better written as x >= 4
8787
x | 4 <= 19;
8888
}
89+
90+
fn issue14167() {
91+
#[cfg(test)]
92+
const FORCE_DYNAMIC_DETECTION: u8 = 0b00010000;
93+
94+
#[cfg(not(test))]
95+
const FORCE_DYNAMIC_DETECTION: u8 = 0b0000000;
96+
97+
const CAPS_STATIC: u8 = 0b00001111;
98+
99+
CAPS_STATIC & FORCE_DYNAMIC_DETECTION == 0;
100+
}

0 commit comments

Comments
 (0)