Skip to content

Commit 80bcd9b

Browse files
committed
Auto merge of rust-lang#8614 - pitaj:fix-7597, r=giraffate
assertions_on_constants: ignore indirect `cfg!` Fixes rust-lang#7597 changelog: [`assertions_on_constants`] ignore constants indirectly based on `cfg!`
2 parents aade96f + 9f131e5 commit 80bcd9b

File tree

2 files changed

+25
-3
lines changed

2 files changed

+25
-3
lines changed

clippy_utils/src/consts.rs

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ use if_chain::if_chain;
55
use rustc_ast::ast::{self, LitFloatType, LitKind};
66
use rustc_data_structures::sync::Lrc;
77
use rustc_hir::def::{DefKind, Res};
8-
use rustc_hir::{BinOp, BinOpKind, Block, Expr, ExprKind, HirId, QPath, UnOp};
8+
use rustc_hir::{BinOp, BinOpKind, Block, Expr, ExprKind, HirId, Item, ItemKind, Node, QPath, UnOp};
99
use rustc_lint::LateContext;
1010
use rustc_middle::mir::interpret::Scalar;
1111
use rustc_middle::ty::subst::{Subst, SubstsRef};
@@ -400,6 +400,22 @@ impl<'a, 'tcx> ConstEvalLateContext<'a, 'tcx> {
400400
let res = self.typeck_results.qpath_res(qpath, id);
401401
match res {
402402
Res::Def(DefKind::Const | DefKind::AssocConst, def_id) => {
403+
// Check if this constant is based on `cfg!(..)`,
404+
// which is NOT constant for our purposes.
405+
if let Some(node) = self.lcx.tcx.hir().get_if_local(def_id) &&
406+
let Node::Item(&Item {
407+
kind: ItemKind::Const(_, body_id),
408+
..
409+
}) = node &&
410+
let Node::Expr(&Expr {
411+
kind: ExprKind::Lit(_),
412+
span,
413+
..
414+
}) = self.lcx.tcx.hir().get(body_id.hir_id) &&
415+
is_direct_expn_of(span, "cfg").is_some() {
416+
return None;
417+
}
418+
403419
let substs = self.typeck_results.node_substs(id);
404420
let substs = if self.substs.is_empty() {
405421
substs

tests/ui/assertions_on_constants.rs

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
#![allow(non_fmt_panics)]
1+
#![allow(non_fmt_panics, clippy::needless_bool)]
22

33
macro_rules! assert_const {
44
($len:expr) => {
@@ -28,6 +28,12 @@ fn main() {
2828
assert_const!(3);
2929
assert_const!(-1);
3030

31-
// Don't lint on this:
31+
// Don't lint if based on `cfg!(..)`:
3232
assert!(cfg!(feature = "hey") || cfg!(not(feature = "asdf")));
33+
34+
let flag: bool = cfg!(not(feature = "asdf"));
35+
assert!(flag);
36+
37+
const CFG_FLAG: &bool = &cfg!(feature = "hey");
38+
assert!(!CFG_FLAG);
3339
}

0 commit comments

Comments
 (0)