@@ -100,10 +100,10 @@ use rustc_hir::hir_id::{HirIdMap, HirIdSet};
100
100
use rustc_hir:: intravisit:: { walk_expr, FnKind , Visitor } ;
101
101
use rustc_hir:: LangItem :: { OptionNone , OptionSome , ResultErr , ResultOk } ;
102
102
use 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 ,
107
107
} ;
108
108
use rustc_lexer:: { tokenize, TokenKind } ;
109
109
use rustc_lint:: { LateContext , Level , Lint , LintContext } ;
@@ -208,7 +208,10 @@ pub fn local_is_initialized(cx: &LateContext<'_>, local: HirId) -> bool {
208
208
false
209
209
}
210
210
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`.
212
215
///
213
216
/// # Example
214
217
///
@@ -221,6 +224,24 @@ pub fn in_constant(cx: &LateContext<'_>, id: HirId) -> bool {
221
224
cx. tcx . hir ( ) . is_inside_const_context ( id)
222
225
}
223
226
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
+
224
245
/// Checks if a `Res` refers to a constructor of a `LangItem`
225
246
/// For example, use this to check whether a function call or a pattern is `Some(..)`.
226
247
pub fn is_res_lang_ctor ( cx : & LateContext < ' _ > , res : Res , lang_item : LangItem ) -> bool {
0 commit comments