@@ -101,10 +101,10 @@ use rustc_hir::hir_id::{HirIdMap, HirIdSet};
101101use rustc_hir:: intravisit:: { walk_expr, FnKind , Visitor } ;
102102use rustc_hir:: LangItem :: { OptionNone , OptionSome , ResultErr , ResultOk } ;
103103use rustc_hir:: {
104- self as hir, def, Arm , ArrayLen , BindingMode , Block , BlockCheckMode , Body , ByRef , Closure , Destination , Expr ,
105- ExprField , ExprKind , FnDecl , FnRetTy , GenericArgs , HirId , Impl , ImplItem , ImplItemKind , ImplItemRef , Item ,
106- ItemKind , LangItem , LetStmt , MatchSource , Mutability , Node , OwnerId , Param , Pat , PatKind , Path , PathSegment ,
107- PrimTy , QPath , Stmt , StmtKind , TraitItem , TraitItemKind , TraitItemRef , TraitRef , TyKind , UnOp ,
104+ self as hir, def, Arm , ArrayLen , BindingMode , Block , BlockCheckMode , Body , ByRef , Closure , ConstContext ,
105+ Destination , Expr , ExprField , ExprKind , FnDecl , FnRetTy , GenericArgs , HirId , Impl , ImplItem , ImplItemKind ,
106+ ImplItemRef , Item , ItemKind , LangItem , LetStmt , MatchSource , Mutability , Node , OwnerId , Param , Pat , PatKind , Path ,
107+ PathSegment , PrimTy , QPath , Stmt , StmtKind , TraitItem , TraitItemKind , TraitItemRef , TraitRef , TyKind , UnOp ,
108108} ;
109109use rustc_lexer:: { tokenize, TokenKind } ;
110110use rustc_lint:: { LateContext , Level , Lint , LintContext } ;
@@ -209,7 +209,10 @@ pub fn local_is_initialized(cx: &LateContext<'_>, local: HirId) -> bool {
209209 false
210210}
211211
212- /// Returns `true` if the given `NodeId` is inside a constant context
212+ /// Returns `true` if the given `HirId` is inside a constant context.
213+ ///
214+ /// This is the same as `is_inside_always_const_context`, but also includes
215+ /// `const fn`.
213216///
214217/// # Example
215218///
@@ -222,6 +225,24 @@ pub fn in_constant(cx: &LateContext<'_>, id: HirId) -> bool {
222225 cx. tcx . hir ( ) . is_inside_const_context ( id)
223226}
224227
228+ /// Returns `true` if the given `HirId` is inside an always constant context.
229+ ///
230+ /// This context includes:
231+ /// * const/static items
232+ /// * const blocks (or inline consts)
233+ /// * associated constants
234+ pub fn is_inside_always_const_context ( tcx : TyCtxt < ' _ > , hir_id : HirId ) -> bool {
235+ use ConstContext :: { Const , ConstFn , Static } ;
236+ let hir = tcx. hir ( ) ;
237+ let Some ( ctx) = hir. body_const_context ( hir. enclosing_body_owner ( hir_id) ) else {
238+ return false ;
239+ } ;
240+ match ctx {
241+ ConstFn => false ,
242+ Static ( _) | Const { inline : _ } => true ,
243+ }
244+ }
245+
225246/// Checks if a `Res` refers to a constructor of a `LangItem`
226247/// For example, use this to check whether a function call or a pattern is `Some(..)`.
227248pub fn is_res_lang_ctor ( cx : & LateContext < ' _ > , res : Res , lang_item : LangItem ) -> bool {
0 commit comments