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 //! `mir_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::bit_set::BitSet;
14 use rustc_index::vec::IndexVec;
15 use rustc_infer::infer::InferCtxt;
16 use rustc_middle::mir::abstract_const::{Node, NodeId};
17 use rustc_middle::mir::interpret::ErrorHandled;
18 use rustc_middle::mir::{self, Rvalue, StatementKind, TerminatorKind};
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::{DefId, LocalDefId};
26 use std::ops::ControlFlow;
28 /// Check if a given constant can be evaluated.
29 pub fn is_const_evaluatable<'cx, 'tcx>(
30 infcx: &InferCtxt<'cx, 'tcx>,
31 def: ty::WithOptConstParam<DefId>,
32 substs: SubstsRef<'tcx>,
33 param_env: ty::ParamEnv<'tcx>,
35 ) -> Result<(), ErrorHandled> {
36 debug!("is_const_evaluatable({:?}, {:?})", def, substs);
37 if infcx.tcx.features().const_evaluatable_checked {
39 match AbstractConst::new(tcx, def, substs)? {
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(b_def, b_substs) => {
45 if b_def == def && b_substs == substs {
46 debug!("is_const_evaluatable: caller_bound ~~> ok");
50 if let Some(b_ct) = AbstractConst::new(tcx, b_def, b_substs)? {
51 // Try to unify with each subtree in the AbstractConst to allow for
52 // `N + 1` being const evaluatable even if theres only a `ConstEvaluatable`
53 // predicate for `(N + 1) * 2`
55 walk_abstract_const(tcx, b_ct, |b_ct| {
56 match try_unify(tcx, ct, b_ct) {
57 true => ControlFlow::BREAK,
58 false => ControlFlow::CONTINUE,
62 if let ControlFlow::Break(()) = result {
63 debug!("is_const_evaluatable: abstract_const ~~> ok");
72 // We were unable to unify the abstract constant with
73 // a constant found in the caller bounds, there are
74 // now three possible cases here.
75 #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
77 /// The abstract const still references an inference
78 /// variable, in this case we return `TooGeneric`.
80 /// The abstract const references a generic parameter,
81 /// this means that we emit an error here.
83 /// The substs are concrete enough that we can simply
84 /// try and evaluate the given constant.
87 let mut failure_kind = FailureKind::Concrete;
88 walk_abstract_const::<!, _>(tcx, ct, |node| match node.root() {
90 let leaf = leaf.subst(tcx, ct.substs);
91 if leaf.has_infer_types_or_consts() {
92 failure_kind = FailureKind::MentionsInfer;
93 } else if leaf.has_param_types_or_consts() {
94 failure_kind = cmp::min(failure_kind, FailureKind::MentionsParam);
99 Node::Binop(_, _, _) | Node::UnaryOp(_, _) | Node::FunctionCall(_, _) => {
100 ControlFlow::CONTINUE
105 FailureKind::MentionsInfer => {
106 return Err(ErrorHandled::TooGeneric);
108 FailureKind::MentionsParam => {
109 // FIXME(const_evaluatable_checked): Better error message.
111 infcx.tcx.sess.struct_span_err(span, "unconstrained generic constant");
112 let const_span = tcx.def_span(def.did);
113 // FIXME(const_evaluatable_checked): Update this suggestion once
114 // explicit const evaluatable bounds are implemented.
115 if let Ok(snippet) = infcx.tcx.sess.source_map().span_to_snippet(const_span)
118 tcx.def_span(def.did),
119 &format!("try adding a `where` bound using this expression: `where [u8; {}]: Sized`", snippet),
124 "consider adding a `where` bound for this expression",
128 return Err(ErrorHandled::Reported(ErrorReported));
130 FailureKind::Concrete => {
131 // Dealt with below by the same code which handles this
132 // without the feature gate.
137 // If we are dealing with a concrete constant, we can
138 // reuse the old code path and try to evaluate
144 let future_compat_lint = || {
145 if let Some(local_def_id) = def.did.as_local() {
146 infcx.tcx.struct_span_lint_hir(
147 lint::builtin::CONST_EVALUATABLE_UNCHECKED,
148 infcx.tcx.hir().local_def_id_to_hir_id(local_def_id),
151 err.build("cannot use constants which depend on generic parameters in types")
158 // FIXME: We should only try to evaluate a given constant here if it is fully concrete
159 // as we don't want to allow things like `[u8; std::mem::size_of::<*mut T>()]`.
161 // We previously did not check this, so we only emit a future compat warning if
162 // const evaluation succeeds and the given constant is still polymorphic for now
163 // and hopefully soon change this to an error.
165 // See #74595 for more details about this.
166 let concrete = infcx.const_eval_resolve(param_env, def, substs, None, Some(span));
168 if concrete.is_ok() && substs.has_param_types_or_consts() {
169 match infcx.tcx.def_kind(def.did) {
170 DefKind::AnonConst => {
171 let mir_body = infcx.tcx.mir_for_ctfe_opt_const_arg(def);
173 if mir_body.is_polymorphic {
174 future_compat_lint();
177 _ => future_compat_lint(),
181 debug!(?concrete, "is_const_evaluatable");
183 Err(ErrorHandled::TooGeneric) if !substs.has_infer_types_or_consts() => {
184 // FIXME(const_evaluatable_checked): We really should move
185 // emitting this error message to fulfill instead. For
186 // now this is easier.
188 // This is not a problem without `const_evaluatable_checked` as
189 // all `ConstEvaluatable` predicates have to be fulfilled for compilation
192 // @lcnr: We already emit an error for things like
193 // `fn test<const N: usize>() -> [0 - N]` eagerly here,
194 // so until we fix this I don't really care.
199 .struct_span_err(span, "constant expression depends on a generic parameter");
200 // FIXME(const_generics): we should suggest to the user how they can resolve this
201 // issue. However, this is currently not actually possible
202 // (see https://github.com/rust-lang/rust/issues/66962#issuecomment-575907083).
204 // Note that with `feature(const_evaluatable_checked)` this case should not
206 err.note("this may fail depending on what value the parameter takes");
208 Err(ErrorHandled::Reported(ErrorReported))
214 /// A tree representing an anonymous constant.
216 /// This is only able to represent a subset of `MIR`,
217 /// and should not leak any information about desugarings.
218 #[derive(Debug, Clone, Copy)]
219 pub struct AbstractConst<'tcx> {
220 // FIXME: Consider adding something like `IndexSlice`
221 // and use this here.
222 pub inner: &'tcx [Node<'tcx>],
223 pub substs: SubstsRef<'tcx>,
226 impl AbstractConst<'tcx> {
229 def: ty::WithOptConstParam<DefId>,
230 substs: SubstsRef<'tcx>,
231 ) -> Result<Option<AbstractConst<'tcx>>, ErrorReported> {
232 let inner = tcx.mir_abstract_const_opt_const_arg(def)?;
233 debug!("AbstractConst::new({:?}) = {:?}", def, inner);
234 Ok(inner.map(|inner| AbstractConst { inner, substs }))
239 ct: &ty::Const<'tcx>,
240 ) -> Result<Option<AbstractConst<'tcx>>, ErrorReported> {
242 ty::ConstKind::Unevaluated(def, substs, None) => AbstractConst::new(tcx, def, substs),
243 ty::ConstKind::Error(_) => Err(ErrorReported),
249 pub fn subtree(self, node: NodeId) -> AbstractConst<'tcx> {
250 AbstractConst { inner: &self.inner[..=node.index()], substs: self.substs }
254 pub fn root(self) -> Node<'tcx> {
255 self.inner.last().copied().unwrap()
259 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
260 struct WorkNode<'tcx> {
266 struct AbstractConstBuilder<'a, 'tcx> {
268 body: &'a mir::Body<'tcx>,
269 /// The current WIP node tree.
271 /// We require all nodes to be used in the final abstract const,
272 /// so we store this here. Note that we also consider nodes as used
273 /// if they are mentioned in an assert, so some used nodes are never
274 /// actually reachable by walking the [`AbstractConst`].
275 nodes: IndexVec<NodeId, WorkNode<'tcx>>,
276 locals: IndexVec<mir::Local, NodeId>,
277 /// We only allow field accesses if they access
278 /// the result of a checked operation.
279 checked_op_locals: BitSet<mir::Local>,
282 impl<'a, 'tcx> AbstractConstBuilder<'a, 'tcx> {
283 fn error(&mut self, span: Option<Span>, msg: &str) -> Result<!, ErrorReported> {
286 .struct_span_err(self.body.span, "overly complex generic constant")
287 .span_label(span.unwrap_or(self.body.span), msg)
288 .help("consider moving this anonymous constant into a `const` function")
296 body: &'a mir::Body<'tcx>,
297 ) -> Result<Option<AbstractConstBuilder<'a, 'tcx>>, ErrorReported> {
298 let mut builder = AbstractConstBuilder {
301 nodes: IndexVec::new(),
302 locals: IndexVec::from_elem(NodeId::MAX, &body.local_decls),
303 checked_op_locals: BitSet::new_empty(body.local_decls.len()),
306 // We don't have to look at concrete constants, as we
307 // can just evaluate them.
308 if !body.is_polymorphic {
312 // We only allow consts without control flow, so
313 // we check for cycles here which simplifies the
314 // rest of this implementation.
315 if body.is_cfg_cyclic() {
316 builder.error(None, "cyclic anonymous constants are forbidden")?;
322 fn add_node(&mut self, node: Node<'tcx>, span: Span) -> NodeId {
326 Node::Binop(_, lhs, rhs) => {
327 self.nodes[lhs].used = true;
328 self.nodes[rhs].used = true;
330 Node::UnaryOp(_, input) => {
331 self.nodes[input].used = true;
333 Node::FunctionCall(func, nodes) => {
334 self.nodes[func].used = true;
335 nodes.iter().for_each(|&n| self.nodes[n].used = true);
339 // Nodes start as unused.
340 self.nodes.push(WorkNode { node, span, used: false })
346 p: &mir::Place<'tcx>,
347 ) -> Result<mir::Local, ErrorReported> {
348 const ZERO_FIELD: mir::Field = mir::Field::from_usize(0);
349 // Do not allow any projections.
351 // One exception are field accesses on the result of checked operations,
352 // which are required to support things like `1 + 2`.
353 if let Some(p) = p.as_local() {
354 debug_assert!(!self.checked_op_locals.contains(p));
356 } else if let &[mir::ProjectionElem::Field(ZERO_FIELD, _)] = p.projection.as_ref() {
357 // Only allow field accesses if the given local
358 // contains the result of a checked operation.
359 if self.checked_op_locals.contains(p.local) {
362 self.error(Some(span), "unsupported projection")?;
365 self.error(Some(span), "unsupported projection")?;
372 op: &mir::Operand<'tcx>,
373 ) -> Result<NodeId, ErrorReported> {
374 debug!("operand_to_node: op={:?}", op);
376 mir::Operand::Copy(p) | mir::Operand::Move(p) => {
377 let local = self.place_to_local(span, p)?;
378 Ok(self.locals[local])
380 mir::Operand::Constant(ct) => Ok(self.add_node(Node::Leaf(ct.literal), span)),
384 /// We do not allow all binary operations in abstract consts, so filter disallowed ones.
385 fn check_binop(op: mir::BinOp) -> bool {
388 Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Shl | Shr | Eq | Lt | Le
389 | Ne | Ge | Gt => true,
394 /// While we currently allow all unary operations, we still want to explicitly guard against
395 /// future changes here.
396 fn check_unop(op: mir::UnOp) -> bool {
403 fn build_statement(&mut self, stmt: &mir::Statement<'tcx>) -> Result<(), ErrorReported> {
404 debug!("AbstractConstBuilder: stmt={:?}", stmt);
405 let span = stmt.source_info.span;
407 StatementKind::Assign(box (ref place, ref rvalue)) => {
408 let local = self.place_to_local(span, place)?;
410 Rvalue::Use(ref operand) => {
411 self.locals[local] = self.operand_to_node(span, operand)?;
414 Rvalue::BinaryOp(op, ref lhs, ref rhs) if Self::check_binop(op) => {
415 let lhs = self.operand_to_node(span, lhs)?;
416 let rhs = self.operand_to_node(span, rhs)?;
417 self.locals[local] = self.add_node(Node::Binop(op, lhs, rhs), span);
418 if op.is_checkable() {
419 bug!("unexpected unchecked checkable binary operation");
424 Rvalue::CheckedBinaryOp(op, ref lhs, ref rhs) if Self::check_binop(op) => {
425 let lhs = self.operand_to_node(span, lhs)?;
426 let rhs = self.operand_to_node(span, rhs)?;
427 self.locals[local] = self.add_node(Node::Binop(op, lhs, rhs), span);
428 self.checked_op_locals.insert(local);
431 Rvalue::UnaryOp(op, ref operand) if Self::check_unop(op) => {
432 let operand = self.operand_to_node(span, operand)?;
433 self.locals[local] = self.add_node(Node::UnaryOp(op, operand), span);
436 _ => self.error(Some(span), "unsupported rvalue")?,
439 // These are not actually relevant for us here, so we can ignore them.
440 StatementKind::StorageLive(_) | StatementKind::StorageDead(_) => Ok(()),
441 _ => self.error(Some(stmt.source_info.span), "unsupported statement")?,
445 /// Possible return values:
447 /// - `None`: unsupported terminator, stop building
448 /// - `Some(None)`: supported terminator, finish building
449 /// - `Some(Some(block))`: support terminator, build `block` next
452 terminator: &mir::Terminator<'tcx>,
453 ) -> Result<Option<mir::BasicBlock>, ErrorReported> {
454 debug!("AbstractConstBuilder: terminator={:?}", terminator);
455 match terminator.kind {
456 TerminatorKind::Goto { target } => Ok(Some(target)),
457 TerminatorKind::Return => Ok(None),
458 TerminatorKind::Call {
461 destination: Some((ref place, target)),
462 // We do not care about `cleanup` here. Any branch which
463 // uses `cleanup` will fail const-eval and they therefore
464 // do not matter when checking for const evaluatability.
466 // Do note that even if `panic::catch_unwind` is made const,
467 // we still do not have to care about this, as we do not look
470 // Do not allow overloaded operators for now,
471 // we probably do want to allow this in the future.
473 // This is currently fairly irrelevant as it requires `const Trait`s.
477 let local = self.place_to_local(fn_span, place)?;
478 let func = self.operand_to_node(fn_span, func)?;
479 let args = self.tcx.arena.alloc_from_iter(
481 .map(|arg| self.operand_to_node(terminator.source_info.span, arg))
482 .collect::<Result<Vec<NodeId>, _>>()?,
484 self.locals[local] = self.add_node(Node::FunctionCall(func, args), fn_span);
487 TerminatorKind::Assert { ref cond, expected: false, target, .. } => {
489 mir::Operand::Copy(p) | mir::Operand::Move(p) => p,
490 mir::Operand::Constant(_) => bug!("unexpected assert"),
493 const ONE_FIELD: mir::Field = mir::Field::from_usize(1);
494 debug!("proj: {:?}", p.projection);
495 if let Some(p) = p.as_local() {
496 debug_assert!(!self.checked_op_locals.contains(p));
497 // Mark locals directly used in asserts as used.
499 // This is needed because division does not use `CheckedBinop` but instead
500 // adds an explicit assert for `divisor != 0`.
501 self.nodes[self.locals[p]].used = true;
502 return Ok(Some(target));
503 } else if let &[mir::ProjectionElem::Field(ONE_FIELD, _)] = p.projection.as_ref() {
504 // Only allow asserts checking the result of a checked operation.
505 if self.checked_op_locals.contains(p.local) {
506 return Ok(Some(target));
510 self.error(Some(terminator.source_info.span), "unsupported assertion")?;
512 _ => self.error(Some(terminator.source_info.span), "unsupported terminator")?,
516 /// Builds the abstract const by walking the mir from start to finish
517 /// and bailing out when encountering an unsupported operation.
518 fn build(mut self) -> Result<&'tcx [Node<'tcx>], ErrorReported> {
519 let mut block = &self.body.basic_blocks()[mir::START_BLOCK];
520 // We checked for a cyclic cfg above, so this should terminate.
522 debug!("AbstractConstBuilder: block={:?}", block);
523 for stmt in block.statements.iter() {
524 self.build_statement(stmt)?;
527 if let Some(next) = self.build_terminator(block.terminator())? {
528 block = &self.body.basic_blocks()[next];
530 assert_eq!(self.locals[mir::RETURN_PLACE], self.nodes.last().unwrap());
531 // `AbstractConst`s should not contain any promoteds as they require references which
533 assert!(!self.nodes.iter().any(|n| matches!(
535 Node::Leaf(ty::Const { val: ty::ConstKind::Unevaluated(_, _, Some(_)), ty: _ })
538 self.nodes[self.locals[mir::RETURN_PLACE]].used = true;
539 if let Some(&unused) = self.nodes.iter().find(|n| !n.used) {
540 self.error(Some(unused.span), "dead code")?;
543 return Ok(self.tcx.arena.alloc_from_iter(self.nodes.into_iter().map(|n| n.node)));
549 /// Builds an abstract const, do not use this directly, but use `AbstractConst::new` instead.
550 pub(super) fn mir_abstract_const<'tcx>(
552 def: ty::WithOptConstParam<LocalDefId>,
553 ) -> Result<Option<&'tcx [mir::abstract_const::Node<'tcx>]>, ErrorReported> {
554 if tcx.features().const_evaluatable_checked {
555 match tcx.def_kind(def.did) {
556 // FIXME(const_evaluatable_checked): We currently only do this for anonymous constants,
557 // meaning that we do not look into associated constants. I(@lcnr) am not yet sure whether
558 // we want to look into them or treat them as opaque projections.
560 // Right now we do neither of that and simply always fail to unify them.
561 DefKind::AnonConst => (),
562 _ => return Ok(None),
564 let body = tcx.mir_const(def).borrow();
565 AbstractConstBuilder::new(tcx, &body)?.map(AbstractConstBuilder::build).transpose()
571 pub(super) fn try_unify_abstract_consts<'tcx>(
573 ((a, a_substs), (b, b_substs)): (
574 (ty::WithOptConstParam<DefId>, SubstsRef<'tcx>),
575 (ty::WithOptConstParam<DefId>, SubstsRef<'tcx>),
579 if let Some(a) = AbstractConst::new(tcx, a, a_substs)? {
580 if let Some(b) = AbstractConst::new(tcx, b, b_substs)? {
581 return Ok(try_unify(tcx, a, b));
587 .unwrap_or_else(|ErrorReported| true)
588 // FIXME(const_evaluatable_checked): We should instead have this
589 // method return the resulting `ty::Const` and return `ConstKind::Error`
590 // on `ErrorReported`.
593 pub fn walk_abstract_const<'tcx, R, F>(
595 ct: AbstractConst<'tcx>,
599 F: FnMut(AbstractConst<'tcx>) -> ControlFlow<R>,
603 ct: AbstractConst<'tcx>,
604 f: &mut dyn FnMut(AbstractConst<'tcx>) -> ControlFlow<R>,
605 ) -> ControlFlow<R> {
607 let root = ct.root();
609 Node::Leaf(_) => ControlFlow::CONTINUE,
610 Node::Binop(_, l, r) => {
611 recurse(tcx, ct.subtree(l), f)?;
612 recurse(tcx, ct.subtree(r), f)
614 Node::UnaryOp(_, v) => recurse(tcx, ct.subtree(v), f),
615 Node::FunctionCall(func, args) => {
616 recurse(tcx, ct.subtree(func), f)?;
617 args.iter().try_for_each(|&arg| recurse(tcx, ct.subtree(arg), f))
622 recurse(tcx, ct, &mut f)
625 /// Tries to unify two abstract constants using structural equality.
626 pub(super) fn try_unify<'tcx>(
628 mut a: AbstractConst<'tcx>,
629 mut b: AbstractConst<'tcx>,
631 // We substitute generics repeatedly to allow AbstractConsts to unify where a
632 // ConstKind::Unevalated could be turned into an AbstractConst that would unify e.g.
633 // Param(N) should unify with Param(T), substs: [Unevaluated("T2", [Unevaluated("T3", [Param(N)])])]
634 while let Node::Leaf(a_ct) = a.root() {
635 let a_ct = a_ct.subst(tcx, a.substs);
636 match AbstractConst::from_const(tcx, a_ct) {
637 Ok(Some(a_act)) => a = a_act,
639 Err(_) => return true,
642 while let Node::Leaf(b_ct) = b.root() {
643 let b_ct = b_ct.subst(tcx, b.substs);
644 match AbstractConst::from_const(tcx, b_ct) {
645 Ok(Some(b_act)) => b = b_act,
647 Err(_) => return true,
651 match (a.root(), b.root()) {
652 (Node::Leaf(a_ct), Node::Leaf(b_ct)) => {
653 let a_ct = a_ct.subst(tcx, a.substs);
654 let b_ct = b_ct.subst(tcx, b.substs);
655 if a_ct.ty != b_ct.ty {
659 match (a_ct.val, b_ct.val) {
660 // We can just unify errors with everything to reduce the amount of
661 // emitted errors here.
662 (ty::ConstKind::Error(_), _) | (_, ty::ConstKind::Error(_)) => true,
663 (ty::ConstKind::Param(a_param), ty::ConstKind::Param(b_param)) => {
666 (ty::ConstKind::Value(a_val), ty::ConstKind::Value(b_val)) => a_val == b_val,
667 // If we have `fn a<const N: usize>() -> [u8; N + 1]` and `fn b<const M: usize>() -> [u8; 1 + M]`
668 // we do not want to use `assert_eq!(a(), b())` to infer that `N` and `M` have to be `1`. This
669 // means that we only allow inference variables if they are equal.
670 (ty::ConstKind::Infer(a_val), ty::ConstKind::Infer(b_val)) => a_val == b_val,
672 ty::ConstKind::Unevaluated(a_def, a_substs, None),
673 ty::ConstKind::Unevaluated(b_def, b_substs, None),
674 ) => a_def == b_def && a_substs == b_substs,
675 // FIXME(const_evaluatable_checked): We may want to either actually try
676 // to evaluate `a_ct` and `b_ct` if they are are fully concrete or something like
677 // this, for now we just return false here.
681 (Node::Binop(a_op, al, ar), Node::Binop(b_op, bl, br)) if a_op == b_op => {
682 try_unify(tcx, a.subtree(al), b.subtree(bl))
683 && try_unify(tcx, a.subtree(ar), b.subtree(br))
685 (Node::UnaryOp(a_op, av), Node::UnaryOp(b_op, bv)) if a_op == b_op => {
686 try_unify(tcx, a.subtree(av), b.subtree(bv))
688 (Node::FunctionCall(a_f, a_args), Node::FunctionCall(b_f, b_args))
689 if a_args.len() == b_args.len() =>
691 try_unify(tcx, a.subtree(a_f), b.subtree(b_f))
695 .all(|(&an, &bn)| try_unify(tcx, a.subtree(an), b.subtree(bn)))