Skip to content

Commit 6aa2e47

Browse files
committed
add utils is_inside_always_const_context
1 parent 3b4c263 commit 6aa2e47

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

clippy_lints/src/default_numeric_fallback.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,8 @@ declare_lint_pass!(DefaultNumericFallback => [DEFAULT_NUMERIC_FALLBACK]);
5151
impl<'tcx> LateLintPass<'tcx> for DefaultNumericFallback {
5252
fn check_body(&mut self, cx: &LateContext<'tcx>, body: &'tcx Body<'_>) {
5353
let hir = cx.tcx.hir();
54+
// NOTE: this is different from `clippy_utils::is_inside_always_const_context`.
55+
// Inline const supports type inference.
5456
let is_parent_const = matches!(
5557
hir.body_const_context(hir.body_owner_def_id(body.id())),
5658
Some(ConstContext::Const { inline: false } | ConstContext::Static(_))

clippy_utils/src/lib.rs

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -208,7 +208,10 @@ pub fn local_is_initialized(cx: &LateContext<'_>, local: HirId) -> bool {
208208
false
209209
}
210210

211-
/// Returns `true` if the given `NodeId` is inside a constant context
211+
/// Returns `true` if the given `HirId` is inside a constant context.
212+
///
213+
/// This is the same as `is_inside_always_const_context`, but also includes
214+
/// `const fn`.
212215
///
213216
/// # Example
214217
///
@@ -221,6 +224,24 @@ pub fn in_constant(cx: &LateContext<'_>, id: HirId) -> bool {
221224
cx.tcx.hir().is_inside_const_context(id)
222225
}
223226

227+
/// Returns `true` if the given `HirId` is inside an always constant context.
228+
///
229+
/// This context includes:
230+
/// * const/static items
231+
/// * const blocks (or inline consts)
232+
/// * associated constants
233+
pub fn is_inside_always_const_context(tcx: TyCtxt<'_>, hir_id: HirId) -> bool {
234+
use ConstContext::{Const, ConstFn, Static};
235+
let hir = tcx.hir();
236+
let Some(ctx) = hir.body_const_context(hir.enclosing_body_owner(hir_id)) else {
237+
return false;
238+
};
239+
match ctx {
240+
ConstFn => false,
241+
Static(_) | Const { inline: _ } => true,
242+
}
243+
}
244+
224245
/// Checks if a `Res` refers to a constructor of a `LangItem`
225246
/// For example, use this to check whether a function call or a pattern is `Some(..)`.
226247
pub fn is_res_lang_ctor(cx: &LateContext<'_>, res: Res, lang_item: LangItem) -> bool {

0 commit comments

Comments
 (0)