@@ -3,7 +3,7 @@ use super::{ErrorHandled, EvalToConstValueResult, EvalToValTreeResult, GlobalId}
33use crate :: mir;
44use crate :: ty:: fold:: TypeFoldable ;
55use crate :: ty:: subst:: InternalSubsts ;
6- use crate :: ty:: { self , query:: TyCtxtAt , TyCtxt } ;
6+ use crate :: ty:: { self , query:: TyCtxtAt , query :: TyCtxtEnsure , TyCtxt } ;
77use rustc_hir:: def_id:: DefId ;
88use rustc_span:: { Span , DUMMY_SP } ;
99
@@ -171,6 +171,39 @@ impl<'tcx> TyCtxtAt<'tcx> {
171171 }
172172}
173173
174+ impl < ' tcx > TyCtxtEnsure < ' tcx > {
175+ /// Evaluates a constant without providing any substitutions. This is useful to evaluate consts
176+ /// that can't take any generic arguments like statics, const items or enum discriminants. If a
177+ /// generic parameter is used within the constant `ErrorHandled::ToGeneric` will be returned.
178+ #[ instrument( skip( self ) , level = "debug" ) ]
179+ pub fn const_eval_poly ( self , def_id : DefId ) {
180+ // In some situations def_id will have substitutions within scope, but they aren't allowed
181+ // to be used. So we can't use `Instance::mono`, instead we feed unresolved substitutions
182+ // into `const_eval` which will return `ErrorHandled::ToGeneric` if any of them are
183+ // encountered.
184+ let substs = InternalSubsts :: identity_for_item ( self . tcx , def_id) ;
185+ let instance = ty:: Instance :: new ( def_id, substs) ;
186+ let cid = GlobalId { instance, promoted : None } ;
187+ let param_env =
188+ self . tcx . param_env ( def_id) . with_reveal_all_normalized ( self . tcx ) . with_const ( ) ;
189+ // Const-eval shouldn't depend on lifetimes at all, so we can erase them, which should
190+ // improve caching of queries.
191+ let inputs = self . tcx . erase_regions ( param_env. and ( cid) ) ;
192+ self . eval_to_const_value_raw ( inputs)
193+ }
194+
195+ /// Evaluate a static's initializer, returning the allocation of the initializer's memory.
196+ pub fn eval_static_initializer ( self , def_id : DefId ) {
197+ trace ! ( "eval_static_initializer: Need to compute {:?}" , def_id) ;
198+ assert ! ( self . tcx. is_static( def_id) ) ;
199+ let instance = ty:: Instance :: mono ( self . tcx , def_id) ;
200+ let gid = GlobalId { instance, promoted : None } ;
201+ let param_env = ty:: ParamEnv :: reveal_all ( ) . with_const ( ) ;
202+ trace ! ( "eval_to_allocation: Need to compute {:?}" , gid) ;
203+ self . eval_to_allocation_raw ( param_env. and ( gid) )
204+ }
205+ }
206+
174207impl < ' tcx > TyCtxt < ' tcx > {
175208 /// Destructure a type-level constant ADT or array into its variant index and its field values.
176209 /// Panics if the destructuring fails, use `try_destructure_const` for fallible version.
0 commit comments