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::ErrorReported;
12 use rustc_hir::def::DefKind;
13 use rustc_index::vec::IndexVec;
14 use rustc_infer::infer::InferCtxt;
15 use rustc_middle::mir;
16 use rustc_middle::mir::interpret::ErrorHandled;
17 use rustc_middle::thir;
18 use rustc_middle::thir::abstract_const::{self, Node, NodeId, NotConstEvaluatable};
19 use rustc_middle::ty::subst::{Subst, SubstsRef};
20 use rustc_middle::ty::{self, TyCtxt, TypeFoldable};
21 use rustc_session::lint;
22 use rustc_span::def_id::LocalDefId;
27 use std::ops::ControlFlow;
29 /// Check if a given constant can be evaluated.
30 pub fn is_const_evaluatable<'cx, 'tcx>(
31 infcx: &InferCtxt<'cx, 'tcx>,
32 uv: ty::Unevaluated<'tcx, ()>,
33 param_env: ty::ParamEnv<'tcx>,
35 ) -> Result<(), NotConstEvaluatable> {
36 debug!("is_const_evaluatable({:?})", uv);
37 if infcx.tcx.features().generic_const_exprs {
39 match AbstractConst::new(tcx, uv)? {
40 // We are looking at a generic abstract constant.
42 for pred in param_env.caller_bounds() {
43 match pred.kind().skip_binder() {
44 ty::PredicateKind::ConstEvaluatable(uv) => {
45 if let Some(b_ct) = AbstractConst::new(tcx, uv)? {
46 // Try to unify with each subtree in the AbstractConst to allow for
47 // `N + 1` being const evaluatable even if theres only a `ConstEvaluatable`
48 // predicate for `(N + 1) * 2`
50 walk_abstract_const(tcx, b_ct, |b_ct| {
51 match try_unify(tcx, ct, b_ct) {
52 true => ControlFlow::BREAK,
53 false => ControlFlow::CONTINUE,
57 if let ControlFlow::Break(()) = result {
58 debug!("is_const_evaluatable: abstract_const ~~> ok");
67 // We were unable to unify the abstract constant with
68 // a constant found in the caller bounds, there are
69 // now three possible cases here.
70 #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
72 /// The abstract const still references an inference
73 /// variable, in this case we return `TooGeneric`.
75 /// The abstract const references a generic parameter,
76 /// this means that we emit an error here.
78 /// The substs are concrete enough that we can simply
79 /// try and evaluate the given constant.
82 let mut failure_kind = FailureKind::Concrete;
83 walk_abstract_const::<!, _>(tcx, ct, |node| match node.root(tcx) {
85 if leaf.has_infer_types_or_consts() {
86 failure_kind = FailureKind::MentionsInfer;
87 } else if leaf.definitely_has_param_types_or_consts(tcx) {
88 failure_kind = cmp::min(failure_kind, FailureKind::MentionsParam);
93 Node::Cast(_, _, ty) => {
94 if ty.has_infer_types_or_consts() {
95 failure_kind = FailureKind::MentionsInfer;
96 } else if ty.definitely_has_param_types_or_consts(tcx) {
97 failure_kind = cmp::min(failure_kind, FailureKind::MentionsParam);
100 ControlFlow::CONTINUE
102 Node::Binop(_, _, _) | Node::UnaryOp(_, _) | Node::FunctionCall(_, _) => {
103 ControlFlow::CONTINUE
108 FailureKind::MentionsInfer => {
109 return Err(NotConstEvaluatable::MentionsInfer);
111 FailureKind::MentionsParam => {
112 return Err(NotConstEvaluatable::MentionsParam);
114 FailureKind::Concrete => {
115 // Dealt with below by the same code which handles this
116 // without the feature gate.
121 // If we are dealing with a concrete constant, we can
122 // reuse the old code path and try to evaluate
128 let future_compat_lint = || {
129 if let Some(local_def_id) = uv.def.did.as_local() {
130 infcx.tcx.struct_span_lint_hir(
131 lint::builtin::CONST_EVALUATABLE_UNCHECKED,
132 infcx.tcx.hir().local_def_id_to_hir_id(local_def_id),
135 err.build("cannot use constants which depend on generic parameters in types")
142 // FIXME: We should only try to evaluate a given constant here if it is fully concrete
143 // as we don't want to allow things like `[u8; std::mem::size_of::<*mut T>()]`.
145 // We previously did not check this, so we only emit a future compat warning if
146 // const evaluation succeeds and the given constant is still polymorphic for now
147 // and hopefully soon change this to an error.
149 // See #74595 for more details about this.
150 let concrete = infcx.const_eval_resolve(param_env, uv.expand(), Some(span));
152 if concrete.is_ok() && uv.substs(infcx.tcx).definitely_has_param_types_or_consts(infcx.tcx) {
153 match infcx.tcx.def_kind(uv.def.did) {
154 DefKind::AnonConst | DefKind::InlineConst => {
155 let mir_body = infcx.tcx.mir_for_ctfe_opt_const_arg(uv.def);
157 if mir_body.is_polymorphic {
158 future_compat_lint();
161 _ => future_compat_lint(),
165 debug!(?concrete, "is_const_evaluatable");
167 Err(ErrorHandled::TooGeneric) => Err(match uv.has_infer_types_or_consts() {
168 true => NotConstEvaluatable::MentionsInfer,
169 false => NotConstEvaluatable::MentionsParam,
171 Err(ErrorHandled::Linted) => {
172 infcx.tcx.sess.delay_span_bug(span, "constant in type had error reported as lint");
173 Err(NotConstEvaluatable::Error(ErrorReported))
175 Err(ErrorHandled::Reported(e)) => Err(NotConstEvaluatable::Error(e)),
180 /// A tree representing an anonymous constant.
182 /// This is only able to represent a subset of `MIR`,
183 /// and should not leak any information about desugarings.
184 #[derive(Debug, Clone, Copy)]
185 pub struct AbstractConst<'tcx> {
186 // FIXME: Consider adding something like `IndexSlice`
187 // and use this here.
188 inner: &'tcx [Node<'tcx>],
189 substs: SubstsRef<'tcx>,
192 impl<'tcx> AbstractConst<'tcx> {
195 uv: ty::Unevaluated<'tcx, ()>,
196 ) -> Result<Option<AbstractConst<'tcx>>, ErrorReported> {
197 let inner = tcx.thir_abstract_const_opt_const_arg(uv.def)?;
198 debug!("AbstractConst::new({:?}) = {:?}", uv, inner);
199 Ok(inner.map(|inner| AbstractConst { inner, substs: uv.substs(tcx) }))
204 ct: &ty::Const<'tcx>,
205 ) -> Result<Option<AbstractConst<'tcx>>, ErrorReported> {
207 ty::ConstKind::Unevaluated(uv) => AbstractConst::new(tcx, uv.shrink()),
208 ty::ConstKind::Error(_) => Err(ErrorReported),
214 pub fn subtree(self, node: NodeId) -> AbstractConst<'tcx> {
215 AbstractConst { inner: &self.inner[..=node.index()], substs: self.substs }
219 pub fn root(self, tcx: TyCtxt<'tcx>) -> Node<'tcx> {
220 let node = self.inner.last().copied().unwrap();
222 Node::Leaf(leaf) => Node::Leaf(leaf.subst(tcx, self.substs)),
223 Node::Cast(kind, operand, ty) => Node::Cast(kind, operand, ty.subst(tcx, self.substs)),
224 // Don't perform substitution on the following as they can't directly contain generic params
225 Node::Binop(_, _, _) | Node::UnaryOp(_, _) | Node::FunctionCall(_, _) => node,
230 struct AbstractConstBuilder<'a, 'tcx> {
232 body_id: thir::ExprId,
233 body: &'a thir::Thir<'tcx>,
234 /// The current WIP node tree.
235 nodes: IndexVec<NodeId, Node<'tcx>>,
238 impl<'a, 'tcx> AbstractConstBuilder<'a, 'tcx> {
239 fn root_span(&self) -> Span {
240 self.body.exprs[self.body_id].span
243 fn error(&mut self, span: Span, msg: &str) -> Result<!, ErrorReported> {
246 .struct_span_err(self.root_span(), "overly complex generic constant")
247 .span_label(span, msg)
248 .help("consider moving this anonymous constant into a `const` function")
253 fn maybe_supported_error(&mut self, span: Span, msg: &str) -> Result<!, ErrorReported> {
256 .struct_span_err(self.root_span(), "overly complex generic constant")
257 .span_label(span, msg)
258 .help("consider moving this anonymous constant into a `const` function")
259 .note("this operation may be supported in the future")
267 (body, body_id): (&'a thir::Thir<'tcx>, thir::ExprId),
268 ) -> Result<Option<AbstractConstBuilder<'a, 'tcx>>, ErrorReported> {
269 let builder = AbstractConstBuilder { tcx, body_id, body, nodes: IndexVec::new() };
271 struct IsThirPolymorphic<'a, 'tcx> {
273 thir: &'a thir::Thir<'tcx>,
278 impl<'a, 'tcx: 'a> visit::Visitor<'a, 'tcx> for IsThirPolymorphic<'a, 'tcx> {
279 fn thir(&self) -> &'a thir::Thir<'tcx> {
283 fn visit_expr(&mut self, expr: &thir::Expr<'tcx>) {
284 self.is_poly |= expr.ty.definitely_has_param_types_or_consts(self.tcx);
286 visit::walk_expr(self, expr)
290 fn visit_pat(&mut self, pat: &thir::Pat<'tcx>) {
291 self.is_poly |= pat.ty.definitely_has_param_types_or_consts(self.tcx);
293 visit::walk_pat(self, pat);
297 fn visit_const(&mut self, ct: &'tcx ty::Const<'tcx>) {
298 self.is_poly |= ct.definitely_has_param_types_or_consts(self.tcx);
302 let mut is_poly_vis = IsThirPolymorphic { is_poly: false, thir: body, tcx };
303 visit::walk_expr(&mut is_poly_vis, &body[body_id]);
304 debug!("AbstractConstBuilder: is_poly={}", is_poly_vis.is_poly);
305 if !is_poly_vis.is_poly {
312 /// We do not allow all binary operations in abstract consts, so filter disallowed ones.
313 fn check_binop(op: mir::BinOp) -> bool {
316 Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Shl | Shr | Eq | Lt | Le
317 | Ne | Ge | Gt => true,
322 /// While we currently allow all unary operations, we still want to explicitly guard against
323 /// future changes here.
324 fn check_unop(op: mir::UnOp) -> bool {
331 /// Builds the abstract const by walking the thir and bailing out when
332 /// encountering an unspported operation.
333 fn build(mut self) -> Result<&'tcx [Node<'tcx>], ErrorReported> {
334 debug!("Abstractconstbuilder::build: body={:?}", &*self.body);
335 self.recurse_build(self.body_id)?;
337 for n in self.nodes.iter() {
338 if let Node::Leaf(ty::Const { val: ty::ConstKind::Unevaluated(ct), ty: _ }) = n {
339 // `AbstractConst`s should not contain any promoteds as they require references which
341 assert_eq!(ct.promoted, None);
345 Ok(self.tcx.arena.alloc_from_iter(self.nodes.into_iter()))
348 fn recurse_build(&mut self, node: thir::ExprId) -> Result<NodeId, ErrorReported> {
350 let node = &self.body.exprs[node];
351 debug!("recurse_build: node={:?}", node);
352 Ok(match &node.kind {
353 // I dont know if handling of these 3 is correct
354 &ExprKind::Scope { value, .. } => self.recurse_build(value)?,
355 &ExprKind::PlaceTypeAscription { source, .. }
356 | &ExprKind::ValueTypeAscription { source, .. } => self.recurse_build(source)?,
358 // subtle: associated consts are literals this arm handles
359 // `<T as Trait>::ASSOC` as well as `12`
360 &ExprKind::Literal { literal, .. } => self.nodes.push(Node::Leaf(literal)),
362 ExprKind::Call { fun, args, .. } => {
363 let fun = self.recurse_build(*fun)?;
365 let mut new_args = Vec::<NodeId>::with_capacity(args.len());
366 for &id in args.iter() {
367 new_args.push(self.recurse_build(id)?);
369 let new_args = self.tcx.arena.alloc_slice(&new_args);
370 self.nodes.push(Node::FunctionCall(fun, new_args))
372 &ExprKind::Binary { op, lhs, rhs } if Self::check_binop(op) => {
373 let lhs = self.recurse_build(lhs)?;
374 let rhs = self.recurse_build(rhs)?;
375 self.nodes.push(Node::Binop(op, lhs, rhs))
377 &ExprKind::Unary { op, arg } if Self::check_unop(op) => {
378 let arg = self.recurse_build(arg)?;
379 self.nodes.push(Node::UnaryOp(op, arg))
381 // This is necessary so that the following compiles:
384 // fn foo<const N: usize>(a: [(); N + 1]) {
385 // bar::<{ N + 1 }>();
388 ExprKind::Block { body: thir::Block { stmts: box [], expr: Some(e), .. } } => {
389 self.recurse_build(*e)?
391 // `ExprKind::Use` happens when a `hir::ExprKind::Cast` is a
392 // "coercion cast" i.e. using a coercion or is a no-op.
393 // This is important so that `N as usize as usize` doesnt unify with `N as usize`. (untested)
394 &ExprKind::Use { source } => {
395 let arg = self.recurse_build(source)?;
396 self.nodes.push(Node::Cast(abstract_const::CastKind::Use, arg, node.ty))
398 &ExprKind::Cast { source } => {
399 let arg = self.recurse_build(source)?;
400 self.nodes.push(Node::Cast(abstract_const::CastKind::As, arg, node.ty))
403 // FIXME(generic_const_exprs): We may want to support these.
404 ExprKind::AddressOf { .. }
405 | ExprKind::Borrow { .. }
406 | ExprKind::Deref { .. } => self.maybe_supported_error(
408 "dereferencing is not supported in generic constants",
410 ExprKind::Repeat { .. } | ExprKind::Array { .. } => self.maybe_supported_error(
412 "array construction is not supported in generic constants",
414 ExprKind::Block { .. } => self.maybe_supported_error(
416 "blocks are not supported in generic constant",
418 ExprKind::NeverToAny { .. } => self.maybe_supported_error(
420 "converting nevers to any is not supported in generic constant",
422 ExprKind::Tuple { .. } => self.maybe_supported_error(
424 "tuple construction is not supported in generic constants",
426 ExprKind::Index { .. } => self.maybe_supported_error(
428 "indexing is not supported in generic constant",
430 ExprKind::Field { .. } => self.maybe_supported_error(
432 "field access is not supported in generic constant",
434 ExprKind::ConstBlock { .. } => self.maybe_supported_error(
436 "const blocks are not supported in generic constant",
438 ExprKind::Adt(_) => self.maybe_supported_error(
440 "struct/enum construction is not supported in generic constants",
442 // dont know if this is correct
443 ExprKind::Pointer { .. } =>
444 self.error(node.span, "pointer casts are not allowed in generic constants")?,
445 ExprKind::Yield { .. } =>
446 self.error(node.span, "generator control flow is not allowed in generic constants")?,
447 ExprKind::Continue { .. } | ExprKind::Break { .. } | ExprKind::Loop { .. } => self
450 "loops and loop control flow are not supported in generic constants",
452 ExprKind::Box { .. } =>
453 self.error(node.span, "allocations are not allowed in generic constants")?,
455 ExprKind::Unary { .. } => unreachable!(),
456 // we handle valid unary/binary ops above
457 ExprKind::Binary { .. } =>
458 self.error(node.span, "unsupported binary operation in generic constants")?,
459 ExprKind::LogicalOp { .. } =>
460 self.error(node.span, "unsupported operation in generic constants, short-circuiting operations would imply control flow")?,
461 ExprKind::Assign { .. } | ExprKind::AssignOp { .. } => {
462 self.error(node.span, "assignment is not supported in generic constants")?
464 ExprKind::Closure { .. } | ExprKind::Return { .. } => self.error(
466 "closures and function keywords are not supported in generic constants",
468 // let expressions imply control flow
469 ExprKind::Match { .. } | ExprKind::If { .. } | ExprKind::Let { .. } =>
470 self.error(node.span, "control flow is not supported in generic constants")?,
471 ExprKind::LlvmInlineAsm { .. } | ExprKind::InlineAsm { .. } => {
472 self.error(node.span, "assembly is not supported in generic constants")?
475 // we dont permit let stmts so `VarRef` and `UpvarRef` cant happen
476 ExprKind::VarRef { .. }
477 | ExprKind::UpvarRef { .. }
478 | ExprKind::StaticRef { .. }
479 | ExprKind::ThreadLocalRef(_) => {
480 self.error(node.span, "unsupported operation in generic constant")?
486 /// Builds an abstract const, do not use this directly, but use `AbstractConst::new` instead.
487 pub(super) fn thir_abstract_const<'tcx>(
489 def: ty::WithOptConstParam<LocalDefId>,
490 ) -> Result<Option<&'tcx [thir::abstract_const::Node<'tcx>]>, ErrorReported> {
491 if tcx.features().generic_const_exprs {
492 match tcx.def_kind(def.did) {
493 // FIXME(generic_const_exprs): We currently only do this for anonymous constants,
494 // meaning that we do not look into associated constants. I(@lcnr) am not yet sure whether
495 // we want to look into them or treat them as opaque projections.
497 // Right now we do neither of that and simply always fail to unify them.
498 DefKind::AnonConst | DefKind::InlineConst => (),
499 _ => return Ok(None),
502 let body = tcx.thir_body(def);
503 if body.0.borrow().exprs.is_empty() {
504 // type error in constant, there is no thir
505 return Err(ErrorReported);
508 AbstractConstBuilder::new(tcx, (&*body.0.borrow(), body.1))?
509 .map(AbstractConstBuilder::build)
516 pub(super) fn try_unify_abstract_consts<'tcx>(
518 (a, b): (ty::Unevaluated<'tcx, ()>, ty::Unevaluated<'tcx, ()>),
521 if let Some(a) = AbstractConst::new(tcx, a)? {
522 if let Some(b) = AbstractConst::new(tcx, b)? {
523 return Ok(try_unify(tcx, a, b));
529 .unwrap_or_else(|ErrorReported| true)
530 // FIXME(generic_const_exprs): We should instead have this
531 // method return the resulting `ty::Const` and return `ConstKind::Error`
532 // on `ErrorReported`.
535 pub fn walk_abstract_const<'tcx, R, F>(
537 ct: AbstractConst<'tcx>,
541 F: FnMut(AbstractConst<'tcx>) -> ControlFlow<R>,
545 ct: AbstractConst<'tcx>,
546 f: &mut dyn FnMut(AbstractConst<'tcx>) -> ControlFlow<R>,
547 ) -> ControlFlow<R> {
549 let root = ct.root(tcx);
551 Node::Leaf(_) => ControlFlow::CONTINUE,
552 Node::Binop(_, l, r) => {
553 recurse(tcx, ct.subtree(l), f)?;
554 recurse(tcx, ct.subtree(r), f)
556 Node::UnaryOp(_, v) => recurse(tcx, ct.subtree(v), f),
557 Node::FunctionCall(func, args) => {
558 recurse(tcx, ct.subtree(func), f)?;
559 args.iter().try_for_each(|&arg| recurse(tcx, ct.subtree(arg), f))
561 Node::Cast(_, operand, _) => recurse(tcx, ct.subtree(operand), f),
565 recurse(tcx, ct, &mut f)
568 /// Tries to unify two abstract constants using structural equality.
569 pub(super) fn try_unify<'tcx>(
571 mut a: AbstractConst<'tcx>,
572 mut b: AbstractConst<'tcx>,
574 // We substitute generics repeatedly to allow AbstractConsts to unify where a
575 // ConstKind::Unevalated could be turned into an AbstractConst that would unify e.g.
576 // Param(N) should unify with Param(T), substs: [Unevaluated("T2", [Unevaluated("T3", [Param(N)])])]
577 while let Node::Leaf(a_ct) = a.root(tcx) {
578 match AbstractConst::from_const(tcx, a_ct) {
579 Ok(Some(a_act)) => a = a_act,
581 Err(_) => return true,
584 while let Node::Leaf(b_ct) = b.root(tcx) {
585 match AbstractConst::from_const(tcx, b_ct) {
586 Ok(Some(b_act)) => b = b_act,
588 Err(_) => return true,
592 match (a.root(tcx), b.root(tcx)) {
593 (Node::Leaf(a_ct), Node::Leaf(b_ct)) => {
594 if a_ct.ty != b_ct.ty {
598 match (a_ct.val, b_ct.val) {
599 // We can just unify errors with everything to reduce the amount of
600 // emitted errors here.
601 (ty::ConstKind::Error(_), _) | (_, ty::ConstKind::Error(_)) => true,
602 (ty::ConstKind::Param(a_param), ty::ConstKind::Param(b_param)) => {
605 (ty::ConstKind::Value(a_val), ty::ConstKind::Value(b_val)) => a_val == b_val,
606 // If we have `fn a<const N: usize>() -> [u8; N + 1]` and `fn b<const M: usize>() -> [u8; 1 + M]`
607 // we do not want to use `assert_eq!(a(), b())` to infer that `N` and `M` have to be `1`. This
608 // means that we only allow inference variables if they are equal.
609 (ty::ConstKind::Infer(a_val), ty::ConstKind::Infer(b_val)) => a_val == b_val,
610 // We expand generic anonymous constants at the start of this function, so this
611 // branch should only be taking when dealing with associated constants, at
612 // which point directly comparing them seems like the desired behavior.
614 // FIXME(generic_const_exprs): This isn't actually the case.
615 // We also take this branch for concrete anonymous constants and
616 // expand generic anonymous constants with concrete substs.
617 (ty::ConstKind::Unevaluated(a_uv), ty::ConstKind::Unevaluated(b_uv)) => {
620 // FIXME(generic_const_exprs): We may want to either actually try
621 // to evaluate `a_ct` and `b_ct` if they are are fully concrete or something like
622 // this, for now we just return false here.
626 (Node::Binop(a_op, al, ar), Node::Binop(b_op, bl, br)) if a_op == b_op => {
627 try_unify(tcx, a.subtree(al), b.subtree(bl))
628 && try_unify(tcx, a.subtree(ar), b.subtree(br))
630 (Node::UnaryOp(a_op, av), Node::UnaryOp(b_op, bv)) if a_op == b_op => {
631 try_unify(tcx, a.subtree(av), b.subtree(bv))
633 (Node::FunctionCall(a_f, a_args), Node::FunctionCall(b_f, b_args))
634 if a_args.len() == b_args.len() =>
636 try_unify(tcx, a.subtree(a_f), b.subtree(b_f))
637 && iter::zip(a_args, b_args)
638 .all(|(&an, &bn)| try_unify(tcx, a.subtree(an), b.subtree(bn)))
640 (Node::Cast(a_kind, a_operand, a_ty), Node::Cast(b_kind, b_operand, b_ty))
641 if (a_ty == b_ty) && (a_kind == b_kind) =>
643 try_unify(tcx, a.subtree(a_operand), b.subtree(b_operand))
645 // use this over `_ => false` to make adding variants to `Node` less error prone
647 | (Node::FunctionCall(..), _)
648 | (Node::UnaryOp(..), _)
649 | (Node::Binop(..), _)
650 | (Node::Leaf(..), _) => false,