Skip to content

Commit 898ed88

Browse files
committed
feat: make const_is_empty lint ignore external constants
1 parent 1159e2c commit 898ed88

File tree

2 files changed

+16
-0
lines changed

2 files changed

+16
-0
lines changed

clippy_utils/src/consts.rs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ use rustc_middle::mir::interpret::{alloc_range, Scalar};
1313
use rustc_middle::mir::ConstValue;
1414
use rustc_middle::ty::{self, EarlyBinder, FloatTy, GenericArgsRef, IntTy, List, ScalarInt, Ty, TyCtxt, UintTy};
1515
use rustc_middle::{bug, mir, span_bug};
16+
use rustc_span::def_id::DefId;
1617
use rustc_span::symbol::{Ident, Symbol};
1718
use rustc_span::SyntaxContext;
1819
use rustc_target::abi::Size;
@@ -482,11 +483,21 @@ impl<'a, 'tcx> ConstEvalLateContext<'a, 'tcx> {
482483
}
483484

484485
/// Simple constant folding to determine if an expression is an empty slice, str, array, …
486+
/// `None` will be returned if the constness cannot be determined, or if the resolution
487+
/// leaves the local crate.
485488
pub fn expr_is_empty(&mut self, e: &Expr<'_>) -> Option<bool> {
486489
match e.kind {
487490
ExprKind::ConstBlock(ConstBlock { body, .. }) => self.expr_is_empty(self.lcx.tcx.hir().body(body).value),
488491
ExprKind::DropTemps(e) => self.expr_is_empty(e),
489492
ExprKind::Path(ref qpath) => {
493+
if !self
494+
.typeck_results
495+
.qpath_res(qpath, e.hir_id)
496+
.opt_def_id()
497+
.is_some_and(DefId::is_local)
498+
{
499+
return None;
500+
}
490501
self.fetch_path_and_apply(qpath, e.hir_id, self.typeck_results.expr_ty(e), |this, result| {
491502
mir_is_empty(this.lcx, result)
492503
})

tests/ui/const_is_empty.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,3 +167,8 @@ fn const_expressions() {
167167
let _ = const_rand().is_empty();
168168
// Do not lint, we do not recurse into functions
169169
}
170+
171+
fn constant_from_external_crate() {
172+
let _ = std::env::consts::EXE_EXTENSION.is_empty();
173+
// Do not lint, `exe_ext` comes from the `std` crate
174+
}

0 commit comments

Comments
 (0)