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_errors
::ErrorGuaranteed
;
12 use rustc_hir
::def
::DefKind
;
13 use rustc_infer
::infer
::InferCtxt
;
14 use rustc_middle
::mir
::interpret
::ErrorHandled
;
15 use rustc_middle
::ty
::abstract_const
::{
16 walk_abstract_const
, AbstractConst
, FailureKind
, Node
, NotConstEvaluatable
,
18 use rustc_middle
::ty
::{self, TyCtxt, TypeVisitable}
;
19 use rustc_session
::lint
;
23 use std
::ops
::ControlFlow
;
25 pub struct ConstUnifyCtxt
<'tcx
> {
26 pub tcx
: TyCtxt
<'tcx
>,
27 pub param_env
: ty
::ParamEnv
<'tcx
>,
30 impl<'tcx
> ConstUnifyCtxt
<'tcx
> {
31 // Substitutes generics repeatedly to allow AbstractConsts to unify where a
32 // ConstKind::Unevaluated could be turned into an AbstractConst that would unify e.g.
33 // Param(N) should unify with Param(T), substs: [Unevaluated("T2", [Unevaluated("T3", [Param(N)])])]
35 #[instrument(skip(self), level = "debug")]
36 fn try_replace_substs_in_root(
38 mut abstr_const
: AbstractConst
<'tcx
>,
39 ) -> Option
<AbstractConst
<'tcx
>> {
40 while let Node
::Leaf(ct
) = abstr_const
.root(self.tcx
) {
41 match AbstractConst
::from_const(self.tcx
, ct
) {
42 Ok(Some(act
)) => abstr_const
= act
,
44 Err(_
) => return None
,
51 /// Tries to unify two abstract constants using structural equality.
52 #[instrument(skip(self), level = "debug")]
53 pub fn try_unify(&self, a
: AbstractConst
<'tcx
>, b
: AbstractConst
<'tcx
>) -> bool
{
54 let a
= if let Some(a
) = self.try_replace_substs_in_root(a
) {
60 let b
= if let Some(b
) = self.try_replace_substs_in_root(b
) {
66 let a_root
= a
.root(self.tcx
);
67 let b_root
= b
.root(self.tcx
);
68 debug
!(?a_root
, ?b_root
);
70 match (a_root
, b_root
) {
71 (Node
::Leaf(a_ct
), Node
::Leaf(b_ct
)) => {
72 let a_ct
= a_ct
.eval(self.tcx
, self.param_env
);
73 debug
!("a_ct evaluated: {:?}", a_ct
);
74 let b_ct
= b_ct
.eval(self.tcx
, self.param_env
);
75 debug
!("b_ct evaluated: {:?}", b_ct
);
77 if a_ct
.ty() != b_ct
.ty() {
81 match (a_ct
.kind(), b_ct
.kind()) {
82 // We can just unify errors with everything to reduce the amount of
83 // emitted errors here.
84 (ty
::ConstKind
::Error(_
), _
) | (_
, ty
::ConstKind
::Error(_
)) => true,
85 (ty
::ConstKind
::Param(a_param
), ty
::ConstKind
::Param(b_param
)) => {
88 (ty
::ConstKind
::Value(a_val
), ty
::ConstKind
::Value(b_val
)) => a_val
== b_val
,
89 // If we have `fn a<const N: usize>() -> [u8; N + 1]` and `fn b<const M: usize>() -> [u8; 1 + M]`
90 // we do not want to use `assert_eq!(a(), b())` to infer that `N` and `M` have to be `1`. This
91 // means that we only allow inference variables if they are equal.
92 (ty
::ConstKind
::Infer(a_val
), ty
::ConstKind
::Infer(b_val
)) => a_val
== b_val
,
93 // We expand generic anonymous constants at the start of this function, so this
94 // branch should only be taking when dealing with associated constants, at
95 // which point directly comparing them seems like the desired behavior.
97 // FIXME(generic_const_exprs): This isn't actually the case.
98 // We also take this branch for concrete anonymous constants and
99 // expand generic anonymous constants with concrete substs.
100 (ty
::ConstKind
::Unevaluated(a_uv
), ty
::ConstKind
::Unevaluated(b_uv
)) => {
103 // FIXME(generic_const_exprs): We may want to either actually try
104 // to evaluate `a_ct` and `b_ct` if they are are fully concrete or something like
105 // this, for now we just return false here.
109 (Node
::Binop(a_op
, al
, ar
), Node
::Binop(b_op
, bl
, br
)) if a_op
== b_op
=> {
110 self.try_unify(a
.subtree(al
), b
.subtree(bl
))
111 && self.try_unify(a
.subtree(ar
), b
.subtree(br
))
113 (Node
::UnaryOp(a_op
, av
), Node
::UnaryOp(b_op
, bv
)) if a_op
== b_op
=> {
114 self.try_unify(a
.subtree(av
), b
.subtree(bv
))
116 (Node
::FunctionCall(a_f
, a_args
), Node
::FunctionCall(b_f
, b_args
))
117 if a_args
.len() == b_args
.len() =>
119 self.try_unify(a
.subtree(a_f
), b
.subtree(b_f
))
120 && iter
::zip(a_args
, b_args
)
121 .all(|(&an
, &bn
)| self.try_unify(a
.subtree(an
), b
.subtree(bn
)))
123 (Node
::Cast(a_kind
, a_operand
, a_ty
), Node
::Cast(b_kind
, b_operand
, b_ty
))
124 if (a_ty
== b_ty
) && (a_kind
== b_kind
) =>
126 self.try_unify(a
.subtree(a_operand
), b
.subtree(b_operand
))
128 // use this over `_ => false` to make adding variants to `Node` less error prone
130 | (Node
::FunctionCall(..), _
)
131 | (Node
::UnaryOp(..), _
)
132 | (Node
::Binop(..), _
)
133 | (Node
::Leaf(..), _
) => false,
138 #[instrument(skip(tcx), level = "debug")]
139 pub fn try_unify_abstract_consts
<'tcx
>(
141 (a
, b
): (ty
::Unevaluated
<'tcx
, ()>, ty
::Unevaluated
<'tcx
, ()>),
142 param_env
: ty
::ParamEnv
<'tcx
>,
145 if let Some(a
) = AbstractConst
::new(tcx
, a
)?
{
146 if let Some(b
) = AbstractConst
::new(tcx
, b
)?
{
147 let const_unify_ctxt
= ConstUnifyCtxt { tcx, param_env }
;
148 return Ok(const_unify_ctxt
.try_unify(a
, b
));
154 .unwrap_or_else(|_
: ErrorGuaranteed
| true)
155 // FIXME(generic_const_exprs): We should instead have this
156 // method return the resulting `ty::Const` and return `ConstKind::Error`
157 // on `ErrorGuaranteed`.
160 /// Check if a given constant can be evaluated.
161 #[instrument(skip(infcx), level = "debug")]
162 pub fn is_const_evaluatable
<'cx
, 'tcx
>(
163 infcx
: &InferCtxt
<'cx
, 'tcx
>,
164 uv
: ty
::Unevaluated
<'tcx
, ()>,
165 param_env
: ty
::ParamEnv
<'tcx
>,
167 ) -> Result
<(), NotConstEvaluatable
> {
170 if tcx
.features().generic_const_exprs
{
171 if let Some(ct
) = AbstractConst
::new(tcx
, uv
)?
{
172 if satisfied_from_param_env(tcx
, ct
, param_env
)?
{
175 match ct
.unify_failure_kind(tcx
) {
176 FailureKind
::MentionsInfer
=> {
177 return Err(NotConstEvaluatable
::MentionsInfer
);
179 FailureKind
::MentionsParam
=> {
180 return Err(NotConstEvaluatable
::MentionsParam
);
183 FailureKind
::Concrete
=> {}
186 let concrete
= infcx
.const_eval_resolve(param_env
, uv
.expand(), Some(span
));
188 Err(ErrorHandled
::TooGeneric
) => {
189 Err(NotConstEvaluatable
::Error(infcx
.tcx
.sess
.delay_span_bug(
191 format
!("Missing value for constant, but no error reported?"),
194 Err(ErrorHandled
::Linted
) => {
198 .delay_span_bug(span
, "constant in type had error reported as lint");
199 Err(NotConstEvaluatable
::Error(reported
))
201 Err(ErrorHandled
::Reported(e
)) => Err(NotConstEvaluatable
::Error(e
)),
205 // FIXME: We should only try to evaluate a given constant here if it is fully concrete
206 // as we don't want to allow things like `[u8; std::mem::size_of::<*mut T>()]`.
208 // We previously did not check this, so we only emit a future compat warning if
209 // const evaluation succeeds and the given constant is still polymorphic for now
210 // and hopefully soon change this to an error.
212 // See #74595 for more details about this.
213 let concrete
= infcx
.const_eval_resolve(param_env
, uv
.expand(), Some(span
));
216 // If we're evaluating a foreign constant, under a nightly compiler without generic
217 // const exprs, AND it would've passed if that expression had been evaluated with
218 // generic const exprs, then suggest using generic const exprs.
219 Err(_
) if tcx
.sess
.is_nightly_build()
220 && let Ok(Some(ct
)) = AbstractConst
::new(tcx
, uv
)
221 && satisfied_from_param_env(tcx
, ct
, param_env
) == Ok(true) => {
224 // Slightly better span than just using `span` alone
225 if span
== rustc_span
::DUMMY_SP { tcx.def_span(uv.def.did) }
else { span }
,
226 "failed to evaluate generic const expression",
228 .note("the crate this constant originates from uses `#![feature(generic_const_exprs)]`")
229 .span_suggestion_verbose(
230 rustc_span
::DUMMY_SP
,
231 "consider enabling this feature",
232 "#![feature(generic_const_exprs)]\n",
233 rustc_errors
::Applicability
::MaybeIncorrect
,
238 Err(ErrorHandled
::TooGeneric
) => Err(if uv
.has_infer_types_or_consts() {
239 NotConstEvaluatable
::MentionsInfer
240 } else if uv
.has_param_types_or_consts() {
241 NotConstEvaluatable
::MentionsParam
243 let guar
= infcx
.tcx
.sess
.delay_span_bug(span
, format
!("Missing value for constant, but no error reported?"));
244 NotConstEvaluatable
::Error(guar
)
246 Err(ErrorHandled
::Linted
) => {
248 infcx
.tcx
.sess
.delay_span_bug(span
, "constant in type had error reported as lint");
249 Err(NotConstEvaluatable
::Error(reported
))
251 Err(ErrorHandled
::Reported(e
)) => Err(NotConstEvaluatable
::Error(e
)),
253 if uv
.substs
.has_param_types_or_consts() {
254 assert
!(matches
!(infcx
.tcx
.def_kind(uv
.def
.did
), DefKind
::AnonConst
));
255 let mir_body
= infcx
.tcx
.mir_for_ctfe_opt_const_arg(uv
.def
);
257 if mir_body
.is_polymorphic
{
258 let Some(local_def_id
) = uv
.def
.did
.as_local() else { return Ok(()) }
;
259 tcx
.struct_span_lint_hir(
260 lint
::builtin
::CONST_EVALUATABLE_UNCHECKED
,
261 tcx
.hir().local_def_id_to_hir_id(local_def_id
),
264 err
.build("cannot use constants which depend on generic parameters in types").emit();
275 #[instrument(skip(tcx), level = "debug")]
276 fn satisfied_from_param_env
<'tcx
>(
278 ct
: AbstractConst
<'tcx
>,
279 param_env
: ty
::ParamEnv
<'tcx
>,
280 ) -> Result
<bool
, NotConstEvaluatable
> {
281 for pred
in param_env
.caller_bounds() {
282 match pred
.kind().skip_binder() {
283 ty
::PredicateKind
::ConstEvaluatable(uv
) => {
284 if let Some(b_ct
) = AbstractConst
::new(tcx
, uv
)?
{
285 let const_unify_ctxt
= ConstUnifyCtxt { tcx, param_env }
;
287 // Try to unify with each subtree in the AbstractConst to allow for
288 // `N + 1` being const evaluatable even if theres only a `ConstEvaluatable`
289 // predicate for `(N + 1) * 2`
290 let result
= walk_abstract_const(tcx
, b_ct
, |b_ct
| {
291 match const_unify_ctxt
.try_unify(ct
, b_ct
) {
292 true => ControlFlow
::BREAK
,
293 false => ControlFlow
::CONTINUE
,
297 if let ControlFlow
::Break(()) = result
{
298 debug
!("is_const_evaluatable: abstract_const ~~> ok");
303 _
=> {}
// don't care