Skip to content

Commit c2c1b7a

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

File tree

2 files changed

+39
-5
lines changed

2 files changed

+39
-5
lines changed

clippy_utils/src/consts.rs

Lines changed: 27 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
#![allow(clippy::float_cmp)]
66

77
use crate::source::{SpanRangeExt, walk_span_to_context};
8-
use crate::{clip, is_direct_expn_of, sext, unsext};
8+
use crate::{clip, inherits_cfg, is_direct_expn_of, sext, unsext};
99

1010
use rustc_abi::Size;
1111
use rustc_apfloat::Float;
@@ -643,16 +643,38 @@ impl<'tcx> ConstEvalCtxt<'tcx> {
643643
if let Some(node) = self.tcx.hir_get_if_local(def_id)
644644
&& let Node::Item(Item {
645645
kind: ItemKind::Const(.., body_id),
646+
owner_id,
646647
..
647648
}) = node
648-
&& let Node::Expr(Expr {
649+
{
650+
// check for `const C: _ = cfg!(foo);`
651+
if let Node::Expr(Expr {
649652
kind: ExprKind::Lit(_),
650653
span,
651654
..
652655
}) = self.tcx.hir_node(body_id.hir_id)
653-
&& is_direct_expn_of(*span, sym::cfg).is_some()
654-
{
655-
return None;
656+
&& is_direct_expn_of(*span, sym::cfg).is_some()
657+
{
658+
return None;
659+
}
660+
661+
// check for:
662+
// ```
663+
// #[cfg(foo)]
664+
// const C: _ = _;
665+
// ```
666+
//
667+
// NOTE: it shouldn't be possible to have `#[cfg]` applied to the initializer, because e.g.
668+
// something like this wouldn't work:
669+
// const C: _ = {
670+
// #[cfg(foo)]
671+
// 1
672+
// #[cfg(bar)]
673+
// 2
674+
// };
675+
if inherits_cfg(self.tcx, owner_id.def_id) {
676+
return None;
677+
}
656678
}
657679

658680
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)