@@ -100,10 +100,10 @@ use rustc_hir::hir_id::{HirIdMap, HirIdSet};
100100use rustc_hir:: intravisit:: { walk_expr, FnKind , Visitor } ;
101101use rustc_hir:: LangItem :: { OptionNone , OptionSome , ResultErr , ResultOk } ;
102102use rustc_hir:: {
103- self as hir, def, Arm , ArrayLen , BindingMode , Block , BlockCheckMode , Body , ByRef , Closure , Destination , Expr ,
104- ExprField , ExprKind , FnDecl , FnRetTy , GenericArgs , HirId , Impl , ImplItem , ImplItemKind , ImplItemRef , Item ,
105- ItemKind , LangItem , LetStmt , MatchSource , Mutability , Node , OwnerId , Param , Pat , PatKind , Path , PathSegment ,
106- PrimTy , QPath , Stmt , StmtKind , TraitItem , TraitItemKind , TraitItemRef , TraitRef , TyKind , UnOp ,
103+ self as hir, def, Arm , ArrayLen , BindingMode , Block , BlockCheckMode , Body , ByRef , Closure , ConstContext ,
104+ Destination , Expr , ExprField , ExprKind , FnDecl , FnRetTy , GenericArgs , HirId , Impl , ImplItem , ImplItemKind ,
105+ ImplItemRef , Item , ItemKind , LangItem , LetStmt , MatchSource , Mutability , Node , OwnerId , Param , Pat , PatKind , Path ,
106+ PathSegment , PrimTy , QPath , Stmt , StmtKind , TraitItem , TraitItemKind , TraitItemRef , TraitRef , TyKind , UnOp ,
107107} ;
108108use rustc_lexer:: { tokenize, TokenKind } ;
109109use rustc_lint:: { LateContext , Level , Lint , LintContext } ;
@@ -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(..)`.
226247pub fn is_res_lang_ctor ( cx : & LateContext < ' _ > , res : Res , lang_item : LangItem ) -> bool {
0 commit comments