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.has_param_types_or_consts() {
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.has_param_types_or_consts() {
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.has_param_types_or_consts() {
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 }))
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>,
277 impl<'a, 'tcx: 'a> visit::Visitor<'a, 'tcx> for IsThirPolymorphic<'a, 'tcx> {
278 fn thir(&self) -> &'a thir::Thir<'tcx> {
282 fn visit_expr(&mut self, expr: &thir::Expr<'tcx>) {
283 self.is_poly |= expr.ty.has_param_types_or_consts();
285 visit::walk_expr(self, expr)
289 fn visit_pat(&mut self, pat: &thir::Pat<'tcx>) {
290 self.is_poly |= pat.ty.has_param_types_or_consts();
292 visit::walk_pat(self, pat);
296 fn visit_const(&mut self, ct: &'tcx ty::Const<'tcx>) {
297 self.is_poly |= ct.has_param_types_or_consts();
301 let mut is_poly_vis = IsThirPolymorphic { is_poly: false, thir: body };
302 visit::walk_expr(&mut is_poly_vis, &body[body_id]);
303 debug!("AbstractConstBuilder: is_poly={}", is_poly_vis.is_poly);
304 if !is_poly_vis.is_poly {
311 /// We do not allow all binary operations in abstract consts, so filter disallowed ones.
312 fn check_binop(op: mir::BinOp) -> bool {
315 Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Shl | Shr | Eq | Lt | Le
316 | Ne | Ge | Gt => true,
321 /// While we currently allow all unary operations, we still want to explicitly guard against
322 /// future changes here.
323 fn check_unop(op: mir::UnOp) -> bool {
330 /// Builds the abstract const by walking the thir and bailing out when
331 /// encountering an unspported operation.
332 fn build(mut self) -> Result<&'tcx [Node<'tcx>], ErrorReported> {
333 debug!("Abstractconstbuilder::build: body={:?}", &*self.body);
334 self.recurse_build(self.body_id)?;
336 for n in self.nodes.iter() {
337 if let Node::Leaf(ty::Const { val: ty::ConstKind::Unevaluated(ct), ty: _ }) = n {
338 // `AbstractConst`s should not contain any promoteds as they require references which
340 assert_eq!(ct.promoted, None);
344 Ok(self.tcx.arena.alloc_from_iter(self.nodes.into_iter()))
347 fn recurse_build(&mut self, node: thir::ExprId) -> Result<NodeId, ErrorReported> {
349 let node = &self.body.exprs[node];
350 debug!("recurse_build: node={:?}", node);
351 Ok(match &node.kind {
352 // I dont know if handling of these 3 is correct
353 &ExprKind::Scope { value, .. } => self.recurse_build(value)?,
354 &ExprKind::PlaceTypeAscription { source, .. }
355 | &ExprKind::ValueTypeAscription { source, .. } => self.recurse_build(source)?,
357 // subtle: associated consts are literals this arm handles
358 // `<T as Trait>::ASSOC` as well as `12`
359 &ExprKind::Literal { literal, .. } => self.nodes.push(Node::Leaf(literal)),
361 ExprKind::Call { fun, args, .. } => {
362 let fun = self.recurse_build(*fun)?;
364 let mut new_args = Vec::<NodeId>::with_capacity(args.len());
365 for &id in args.iter() {
366 new_args.push(self.recurse_build(id)?);
368 let new_args = self.tcx.arena.alloc_slice(&new_args);
369 self.nodes.push(Node::FunctionCall(fun, new_args))
371 &ExprKind::Binary { op, lhs, rhs } if Self::check_binop(op) => {
372 let lhs = self.recurse_build(lhs)?;
373 let rhs = self.recurse_build(rhs)?;
374 self.nodes.push(Node::Binop(op, lhs, rhs))
376 &ExprKind::Unary { op, arg } if Self::check_unop(op) => {
377 let arg = self.recurse_build(arg)?;
378 self.nodes.push(Node::UnaryOp(op, arg))
380 // This is necessary so that the following compiles:
383 // fn foo<const N: usize>(a: [(); N + 1]) {
384 // bar::<{ N + 1 }>();
387 ExprKind::Block { body: thir::Block { stmts: box [], expr: Some(e), .. } } => {
388 self.recurse_build(*e)?
390 // `ExprKind::Use` happens when a `hir::ExprKind::Cast` is a
391 // "coercion cast" i.e. using a coercion or is a no-op.
392 // This is important so that `N as usize as usize` doesnt unify with `N as usize`. (untested)
393 &ExprKind::Use { source } => {
394 let arg = self.recurse_build(source)?;
395 self.nodes.push(Node::Cast(abstract_const::CastKind::Use, arg, node.ty))
397 &ExprKind::Cast { source } => {
398 let arg = self.recurse_build(source)?;
399 self.nodes.push(Node::Cast(abstract_const::CastKind::As, arg, node.ty))
401 ExprKind::Borrow{ arg, ..} => {
402 let arg_node = &self.body.exprs[*arg];
404 // Skip reborrows for now until we allow Deref/Borrow/AddressOf
406 // FIXME(generic_const_exprs): Verify/explain why this is sound
407 if let ExprKind::Deref {arg} = arg_node.kind {
408 self.recurse_build(arg)?
410 self.maybe_supported_error(
412 "borrowing is not supported in generic constants",
416 // FIXME(generic_const_exprs): We may want to support these.
417 ExprKind::AddressOf { .. } | ExprKind::Deref {..}=> self.maybe_supported_error(
419 "dereferencing or taking the address is not supported in generic constants",
421 ExprKind::Repeat { .. } | ExprKind::Array { .. } => self.maybe_supported_error(
423 "array construction is not supported in generic constants",
425 ExprKind::Block { .. } => self.maybe_supported_error(
427 "blocks are not supported in generic constant",
429 ExprKind::NeverToAny { .. } => self.maybe_supported_error(
431 "converting nevers to any is not supported in generic constant",
433 ExprKind::Tuple { .. } => self.maybe_supported_error(
435 "tuple construction is not supported in generic constants",
437 ExprKind::Index { .. } => self.maybe_supported_error(
439 "indexing is not supported in generic constant",
441 ExprKind::Field { .. } => self.maybe_supported_error(
443 "field access is not supported in generic constant",
445 ExprKind::ConstBlock { .. } => self.maybe_supported_error(
447 "const blocks are not supported in generic constant",
449 ExprKind::Adt(_) => self.maybe_supported_error(
451 "struct/enum construction is not supported in generic constants",
453 // dont know if this is correct
454 ExprKind::Pointer { .. } =>
455 self.error(node.span, "pointer casts are not allowed in generic constants")?,
456 ExprKind::Yield { .. } =>
457 self.error(node.span, "generator control flow is not allowed in generic constants")?,
458 ExprKind::Continue { .. } | ExprKind::Break { .. } | ExprKind::Loop { .. } => self
461 "loops and loop control flow are not supported in generic constants",
463 ExprKind::Box { .. } =>
464 self.error(node.span, "allocations are not allowed in generic constants")?,
466 ExprKind::Unary { .. } => unreachable!(),
467 // we handle valid unary/binary ops above
468 ExprKind::Binary { .. } =>
469 self.error(node.span, "unsupported binary operation in generic constants")?,
470 ExprKind::LogicalOp { .. } =>
471 self.error(node.span, "unsupported operation in generic constants, short-circuiting operations would imply control flow")?,
472 ExprKind::Assign { .. } | ExprKind::AssignOp { .. } => {
473 self.error(node.span, "assignment is not supported in generic constants")?
475 ExprKind::Closure { .. } | ExprKind::Return { .. } => self.error(
477 "closures and function keywords are not supported in generic constants",
479 // let expressions imply control flow
480 ExprKind::Match { .. } | ExprKind::If { .. } | ExprKind::Let { .. } =>
481 self.error(node.span, "control flow is not supported in generic constants")?,
482 ExprKind::InlineAsm { .. } => {
483 self.error(node.span, "assembly is not supported in generic constants")?
486 // we dont permit let stmts so `VarRef` and `UpvarRef` cant happen
487 ExprKind::VarRef { .. }
488 | ExprKind::UpvarRef { .. }
489 | ExprKind::StaticRef { .. }
490 | ExprKind::ThreadLocalRef(_) => {
491 self.error(node.span, "unsupported operation in generic constant")?
497 /// Builds an abstract const, do not use this directly, but use `AbstractConst::new` instead.
498 pub(super) fn thir_abstract_const<'tcx>(
500 def: ty::WithOptConstParam<LocalDefId>,
501 ) -> Result<Option<&'tcx [thir::abstract_const::Node<'tcx>]>, ErrorReported> {
502 if tcx.features().generic_const_exprs {
503 match tcx.def_kind(def.did) {
504 // FIXME(generic_const_exprs): We currently only do this for anonymous constants,
505 // meaning that we do not look into associated constants. I(@lcnr) am not yet sure whether
506 // we want to look into them or treat them as opaque projections.
508 // Right now we do neither of that and simply always fail to unify them.
509 DefKind::AnonConst | DefKind::InlineConst => (),
510 _ => return Ok(None),
513 let body = tcx.thir_body(def);
514 if body.0.borrow().exprs.is_empty() {
515 // type error in constant, there is no thir
516 return Err(ErrorReported);
519 AbstractConstBuilder::new(tcx, (&*body.0.borrow(), body.1))?
520 .map(AbstractConstBuilder::build)
527 pub(super) fn try_unify_abstract_consts<'tcx>(
529 (a, b): (ty::Unevaluated<'tcx, ()>, ty::Unevaluated<'tcx, ()>),
532 if let Some(a) = AbstractConst::new(tcx, a)? {
533 if let Some(b) = AbstractConst::new(tcx, b)? {
534 return Ok(try_unify(tcx, a, b));
540 .unwrap_or_else(|ErrorReported| true)
541 // FIXME(generic_const_exprs): We should instead have this
542 // method return the resulting `ty::Const` and return `ConstKind::Error`
543 // on `ErrorReported`.
546 pub fn walk_abstract_const<'tcx, R, F>(
548 ct: AbstractConst<'tcx>,
552 F: FnMut(AbstractConst<'tcx>) -> ControlFlow<R>,
556 ct: AbstractConst<'tcx>,
557 f: &mut dyn FnMut(AbstractConst<'tcx>) -> ControlFlow<R>,
558 ) -> ControlFlow<R> {
560 let root = ct.root(tcx);
562 Node::Leaf(_) => ControlFlow::CONTINUE,
563 Node::Binop(_, l, r) => {
564 recurse(tcx, ct.subtree(l), f)?;
565 recurse(tcx, ct.subtree(r), f)
567 Node::UnaryOp(_, v) => recurse(tcx, ct.subtree(v), f),
568 Node::FunctionCall(func, args) => {
569 recurse(tcx, ct.subtree(func), f)?;
570 args.iter().try_for_each(|&arg| recurse(tcx, ct.subtree(arg), f))
572 Node::Cast(_, operand, _) => recurse(tcx, ct.subtree(operand), f),
576 recurse(tcx, ct, &mut f)
579 /// Tries to unify two abstract constants using structural equality.
580 pub(super) fn try_unify<'tcx>(
582 mut a: AbstractConst<'tcx>,
583 mut b: AbstractConst<'tcx>,
585 // We substitute generics repeatedly to allow AbstractConsts to unify where a
586 // ConstKind::Unevalated could be turned into an AbstractConst that would unify e.g.
587 // Param(N) should unify with Param(T), substs: [Unevaluated("T2", [Unevaluated("T3", [Param(N)])])]
588 while let Node::Leaf(a_ct) = a.root(tcx) {
589 match AbstractConst::from_const(tcx, a_ct) {
590 Ok(Some(a_act)) => a = a_act,
592 Err(_) => return true,
595 while let Node::Leaf(b_ct) = b.root(tcx) {
596 match AbstractConst::from_const(tcx, b_ct) {
597 Ok(Some(b_act)) => b = b_act,
599 Err(_) => return true,
603 match (a.root(tcx), b.root(tcx)) {
604 (Node::Leaf(a_ct), Node::Leaf(b_ct)) => {
605 if a_ct.ty != b_ct.ty {
609 match (a_ct.val, b_ct.val) {
610 // We can just unify errors with everything to reduce the amount of
611 // emitted errors here.
612 (ty::ConstKind::Error(_), _) | (_, ty::ConstKind::Error(_)) => true,
613 (ty::ConstKind::Param(a_param), ty::ConstKind::Param(b_param)) => {
616 (ty::ConstKind::Value(a_val), ty::ConstKind::Value(b_val)) => a_val == b_val,
617 // If we have `fn a<const N: usize>() -> [u8; N + 1]` and `fn b<const M: usize>() -> [u8; 1 + M]`
618 // we do not want to use `assert_eq!(a(), b())` to infer that `N` and `M` have to be `1`. This
619 // means that we only allow inference variables if they are equal.
620 (ty::ConstKind::Infer(a_val), ty::ConstKind::Infer(b_val)) => a_val == b_val,
621 // We expand generic anonymous constants at the start of this function, so this
622 // branch should only be taking when dealing with associated constants, at
623 // which point directly comparing them seems like the desired behavior.
625 // FIXME(generic_const_exprs): This isn't actually the case.
626 // We also take this branch for concrete anonymous constants and
627 // expand generic anonymous constants with concrete substs.
628 (ty::ConstKind::Unevaluated(a_uv), ty::ConstKind::Unevaluated(b_uv)) => {
631 // FIXME(generic_const_exprs): We may want to either actually try
632 // to evaluate `a_ct` and `b_ct` if they are are fully concrete or something like
633 // this, for now we just return false here.
637 (Node::Binop(a_op, al, ar), Node::Binop(b_op, bl, br)) if a_op == b_op => {
638 try_unify(tcx, a.subtree(al), b.subtree(bl))
639 && try_unify(tcx, a.subtree(ar), b.subtree(br))
641 (Node::UnaryOp(a_op, av), Node::UnaryOp(b_op, bv)) if a_op == b_op => {
642 try_unify(tcx, a.subtree(av), b.subtree(bv))
644 (Node::FunctionCall(a_f, a_args), Node::FunctionCall(b_f, b_args))
645 if a_args.len() == b_args.len() =>
647 try_unify(tcx, a.subtree(a_f), b.subtree(b_f))
648 && iter::zip(a_args, b_args)
649 .all(|(&an, &bn)| try_unify(tcx, a.subtree(an), b.subtree(bn)))
651 (Node::Cast(a_kind, a_operand, a_ty), Node::Cast(b_kind, b_operand, b_ty))
652 if (a_ty == b_ty) && (a_kind == b_kind) =>
654 try_unify(tcx, a.subtree(a_operand), b.subtree(b_operand))
656 // use this over `_ => false` to make adding variants to `Node` less error prone
658 | (Node::FunctionCall(..), _)
659 | (Node::UnaryOp(..), _)
660 | (Node::Binop(..), _)
661 | (Node::Leaf(..), _) => false,