1 //! Checking that constant values used in types can be successfully evaluated.
3 //! For concrete constants, this is fairly simple as we can just try and evaluate it.
5 //! When dealing with polymorphic constants, for example `std::mem::size_of::<T>() - 1`,
6 //! this is not as easy.
8 //! In this case we try to build an abstract representation of this constant using
9 //! `thir_abstract_const` which can then be checked for structural equality with other
10 //! generic constants mentioned in the `caller_bounds` of the current environment.
11 use rustc_infer::infer::InferCtxt;
12 use rustc_middle::mir::interpret::ErrorHandled;
14 use rustc_middle::traits::ObligationCause;
15 use rustc_middle::ty::abstract_const::NotConstEvaluatable;
16 use rustc_middle::ty::{self, TyCtxt, TypeVisitable, TypeVisitor};
19 use std::ops::ControlFlow;
21 /// Check if a given constant can be evaluated.
22 #[instrument(skip(infcx), level = "debug")]
23 pub fn is_const_evaluatable<'tcx>(
24 infcx: &InferCtxt<'tcx>,
26 param_env: ty::ParamEnv<'tcx>,
28 ) -> Result<(), NotConstEvaluatable> {
30 let uv = match ct.kind() {
31 ty::ConstKind::Unevaluated(uv) => uv,
32 ty::ConstKind::Expr(_) => bug!("unexpected expr in `is_const_evaluatable: {ct:?}"),
33 ty::ConstKind::Param(_)
34 | ty::ConstKind::Bound(_, _)
35 | ty::ConstKind::Placeholder(_)
36 | ty::ConstKind::Value(_)
37 | ty::ConstKind::Error(_) => return Ok(()),
38 ty::ConstKind::Infer(_) => return Err(NotConstEvaluatable::MentionsInfer),
41 if tcx.features().generic_const_exprs {
42 if let Some(ct) = tcx.expand_abstract_consts(ct)? {
43 if satisfied_from_param_env(tcx, infcx, ct, param_env)? {
46 if ct.has_non_region_infer() {
47 return Err(NotConstEvaluatable::MentionsInfer);
48 } else if ct.has_non_region_param() {
49 return Err(NotConstEvaluatable::MentionsParam);
52 let concrete = infcx.const_eval_resolve(param_env, uv, Some(span));
54 Err(ErrorHandled::TooGeneric) => Err(NotConstEvaluatable::Error(
58 .delay_span_bug(span, "Missing value for constant, but no error reported?"),
60 Err(ErrorHandled::Reported(e)) => Err(NotConstEvaluatable::Error(e)),
64 // FIXME: We should only try to evaluate a given constant here if it is fully concrete
65 // as we don't want to allow things like `[u8; std::mem::size_of::<*mut T>()]`.
67 // We previously did not check this, so we only emit a future compat warning if
68 // const evaluation succeeds and the given constant is still polymorphic for now
69 // and hopefully soon change this to an error.
71 // See #74595 for more details about this.
72 let concrete = infcx.const_eval_resolve(param_env, uv, Some(span));
74 // If we're evaluating a generic foreign constant, under a nightly compiler while
75 // the current crate does not enable `feature(generic_const_exprs)`, abort
76 // compilation with a useful error.
77 Err(_) if tcx.sess.is_nightly_build()
78 && let Ok(Some(ac)) = tcx.expand_abstract_consts(ct)
79 && let ty::ConstKind::Expr(_) = ac.kind() => {
82 // Slightly better span than just using `span` alone
83 if span == rustc_span::DUMMY_SP { tcx.def_span(uv.def.did) } else { span },
84 "failed to evaluate generic const expression",
86 .note("the crate this constant originates from uses `#![feature(generic_const_exprs)]`")
87 .span_suggestion_verbose(
89 "consider enabling this feature",
90 "#![feature(generic_const_exprs)]\n",
91 rustc_errors::Applicability::MaybeIncorrect,
96 Err(ErrorHandled::TooGeneric) => {
97 let err = if uv.has_non_region_infer() {
98 NotConstEvaluatable::MentionsInfer
99 } else if uv.has_non_region_param() {
100 NotConstEvaluatable::MentionsParam
102 let guar = infcx.tcx.sess.delay_span_bug(span, format!("Missing value for constant, but no error reported?"));
103 NotConstEvaluatable::Error(guar)
108 Err(ErrorHandled::Reported(e)) => Err(NotConstEvaluatable::Error(e)),
114 #[instrument(skip(infcx, tcx), level = "debug")]
115 fn satisfied_from_param_env<'tcx>(
117 infcx: &InferCtxt<'tcx>,
119 param_env: ty::ParamEnv<'tcx>,
120 ) -> Result<bool, NotConstEvaluatable> {
121 // Try to unify with each subtree in the AbstractConst to allow for
122 // `N + 1` being const evaluatable even if theres only a `ConstEvaluatable`
123 // predicate for `(N + 1) * 2`
124 struct Visitor<'a, 'tcx> {
126 param_env: ty::ParamEnv<'tcx>,
128 infcx: &'a InferCtxt<'tcx>,
130 impl<'a, 'tcx> TypeVisitor<'tcx> for Visitor<'a, 'tcx> {
132 fn visit_const(&mut self, c: ty::Const<'tcx>) -> ControlFlow<Self::BreakTy> {
133 if c.ty() == self.ct.ty()
134 && let Ok(_nested_obligations) = self
136 .at(&ObligationCause::dummy(), self.param_env)
140 } else if let ty::ConstKind::Expr(e) = c.kind() {
143 ControlFlow::CONTINUE
148 for pred in param_env.caller_bounds() {
149 match pred.kind().skip_binder() {
150 ty::PredicateKind::ConstEvaluatable(ce) => {
151 let ty::ConstKind::Unevaluated(_) = ce.kind() else {
154 let Some(b_ct) = tcx.expand_abstract_consts(ce)? else {
158 let mut v = Visitor { ct, infcx, param_env };
159 let result = b_ct.visit_with(&mut v);
161 if let ControlFlow::Break(()) = result {
162 debug!("is_const_evaluatable: abstract_const ~~> ok");
166 _ => {} // don't care