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_index::vec::IndexVec;
14 use rustc_infer::infer::InferCtxt;
15 use rustc_middle::mir;
16 use rustc_middle::mir::interpret::{ErrorHandled, LitToConstError, LitToConstInput};
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, DelaySpanBugEmitted, EarlyBinder, 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 #[instrument(skip(infcx), level = "debug")]
31 pub fn is_const_evaluatable<'cx, 'tcx>(
32 infcx: &InferCtxt<'cx, 'tcx>,
33 uv: ty::Unevaluated<'tcx, ()>,
34 param_env: ty::ParamEnv<'tcx>,
36 ) -> Result<(), NotConstEvaluatable> {
39 if tcx.features().generic_const_exprs {
40 if let Some(ct) = AbstractConst::new(tcx, uv)? {
41 if satisfied_from_param_env(tcx, ct, param_env)? {
45 // We were unable to unify the abstract constant with
46 // a constant found in the caller bounds, there are
47 // now three possible cases here.
48 #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
50 /// The abstract const still references an inference
51 /// variable, in this case we return `TooGeneric`.
53 /// The abstract const references a generic parameter,
54 /// this means that we emit an error here.
56 /// The substs are concrete enough that we can simply
57 /// try and evaluate the given constant.
60 let mut failure_kind = FailureKind::Concrete;
61 walk_abstract_const::<!, _>(tcx, ct, |node| match node.root(tcx) {
63 if leaf.has_infer_types_or_consts() {
64 failure_kind = FailureKind::MentionsInfer;
65 } else if leaf.has_param_types_or_consts() {
66 failure_kind = cmp::min(failure_kind, FailureKind::MentionsParam);
71 Node::Cast(_, _, ty) => {
72 if ty.has_infer_types_or_consts() {
73 failure_kind = FailureKind::MentionsInfer;
74 } else if ty.has_param_types_or_consts() {
75 failure_kind = cmp::min(failure_kind, FailureKind::MentionsParam);
80 Node::Binop(_, _, _) | Node::UnaryOp(_, _) | Node::FunctionCall(_, _) => {
86 FailureKind::MentionsInfer => {
87 return Err(NotConstEvaluatable::MentionsInfer);
89 FailureKind::MentionsParam => {
90 return Err(NotConstEvaluatable::MentionsParam);
93 FailureKind::Concrete => {}
96 let concrete = infcx.const_eval_resolve(param_env, uv.expand(), Some(span));
98 Err(ErrorHandled::TooGeneric) => Err(if !uv.has_infer_types_or_consts() {
102 .delay_span_bug(span, &format!("unexpected `TooGeneric` for {:?}", uv));
103 NotConstEvaluatable::MentionsParam
105 NotConstEvaluatable::MentionsInfer
107 Err(ErrorHandled::Linted) => {
111 .delay_span_bug(span, "constant in type had error reported as lint");
112 Err(NotConstEvaluatable::Error(reported))
114 Err(ErrorHandled::Reported(e)) => Err(NotConstEvaluatable::Error(e)),
118 // FIXME: We should only try to evaluate a given constant here if it is fully concrete
119 // as we don't want to allow things like `[u8; std::mem::size_of::<*mut T>()]`.
121 // We previously did not check this, so we only emit a future compat warning if
122 // const evaluation succeeds and the given constant is still polymorphic for now
123 // and hopefully soon change this to an error.
125 // See #74595 for more details about this.
126 let concrete = infcx.const_eval_resolve(param_env, uv.expand(), Some(span));
129 // If we're evaluating a foreign constant, under a nightly compiler without generic
130 // const exprs, AND it would've passed if that expression had been evaluated with
131 // generic const exprs, then suggest using generic const exprs.
132 Err(_) if tcx.sess.is_nightly_build()
133 && let Ok(Some(ct)) = AbstractConst::new(tcx, uv)
134 && satisfied_from_param_env(tcx, ct, param_env) == Ok(true) => {
137 // Slightly better span than just using `span` alone
138 if span == rustc_span::DUMMY_SP { tcx.def_span(uv.def.did) } else { span },
139 "failed to evaluate generic const expression",
141 .note("the crate this constant originates from uses `#![feature(generic_const_exprs)]`")
142 .span_suggestion_verbose(
143 rustc_span::DUMMY_SP,
144 "consider enabling this feature",
145 "#![feature(generic_const_exprs)]\n",
146 rustc_errors::Applicability::MaybeIncorrect,
151 Err(ErrorHandled::TooGeneric) => Err(if uv.has_infer_types_or_consts() {
152 NotConstEvaluatable::MentionsInfer
154 NotConstEvaluatable::MentionsParam
156 Err(ErrorHandled::Linted) => {
158 infcx.tcx.sess.delay_span_bug(span, "constant in type had error reported as lint");
159 Err(NotConstEvaluatable::Error(reported))
161 Err(ErrorHandled::Reported(e)) => Err(NotConstEvaluatable::Error(e)),
163 if uv.substs.has_param_types_or_consts() {
164 assert!(matches!(infcx.tcx.def_kind(uv.def.did), DefKind::AnonConst));
165 let mir_body = infcx.tcx.mir_for_ctfe_opt_const_arg(uv.def);
167 if mir_body.is_polymorphic {
168 let Some(local_def_id) = uv.def.did.as_local() else { return Ok(()) };
169 tcx.struct_span_lint_hir(
170 lint::builtin::CONST_EVALUATABLE_UNCHECKED,
171 tcx.hir().local_def_id_to_hir_id(local_def_id),
174 err.build("cannot use constants which depend on generic parameters in types").emit();
185 #[instrument(skip(tcx), level = "debug")]
186 fn satisfied_from_param_env<'tcx>(
188 ct: AbstractConst<'tcx>,
189 param_env: ty::ParamEnv<'tcx>,
190 ) -> Result<bool, NotConstEvaluatable> {
191 for pred in param_env.caller_bounds() {
192 match pred.kind().skip_binder() {
193 ty::PredicateKind::ConstEvaluatable(uv) => {
194 if let Some(b_ct) = AbstractConst::new(tcx, uv)? {
195 let const_unify_ctxt = ConstUnifyCtxt { tcx, param_env };
197 // Try to unify with each subtree in the AbstractConst to allow for
198 // `N + 1` being const evaluatable even if theres only a `ConstEvaluatable`
199 // predicate for `(N + 1) * 2`
200 let result = walk_abstract_const(tcx, b_ct, |b_ct| {
201 match const_unify_ctxt.try_unify(ct, b_ct) {
202 true => ControlFlow::BREAK,
203 false => ControlFlow::CONTINUE,
207 if let ControlFlow::Break(()) = result {
208 debug!("is_const_evaluatable: abstract_const ~~> ok");
213 _ => {} // don't care
220 /// A tree representing an anonymous constant.
222 /// This is only able to represent a subset of `MIR`,
223 /// and should not leak any information about desugarings.
224 #[derive(Debug, Clone, Copy)]
225 pub struct AbstractConst<'tcx> {
226 // FIXME: Consider adding something like `IndexSlice`
227 // and use this here.
228 inner: &'tcx [Node<'tcx>],
229 substs: SubstsRef<'tcx>,
232 impl<'tcx> AbstractConst<'tcx> {
235 uv: ty::Unevaluated<'tcx, ()>,
236 ) -> Result<Option<AbstractConst<'tcx>>, ErrorGuaranteed> {
237 let inner = tcx.thir_abstract_const_opt_const_arg(uv.def)?;
238 debug!("AbstractConst::new({:?}) = {:?}", uv, inner);
239 Ok(inner.map(|inner| AbstractConst { inner, substs: tcx.erase_regions(uv.substs) }))
245 ) -> Result<Option<AbstractConst<'tcx>>, ErrorGuaranteed> {
247 ty::ConstKind::Unevaluated(uv) => AbstractConst::new(tcx, uv.shrink()),
248 ty::ConstKind::Error(DelaySpanBugEmitted { reported, .. }) => Err(reported),
254 pub fn subtree(self, node: NodeId) -> AbstractConst<'tcx> {
255 AbstractConst { inner: &self.inner[..=node.index()], substs: self.substs }
259 pub fn root(self, tcx: TyCtxt<'tcx>) -> Node<'tcx> {
260 let node = self.inner.last().copied().unwrap();
262 Node::Leaf(leaf) => Node::Leaf(EarlyBinder(leaf).subst(tcx, self.substs)),
263 Node::Cast(kind, operand, ty) => {
264 Node::Cast(kind, operand, EarlyBinder(ty).subst(tcx, self.substs))
266 // Don't perform substitution on the following as they can't directly contain generic params
267 Node::Binop(_, _, _) | Node::UnaryOp(_, _) | Node::FunctionCall(_, _) => node,
272 struct AbstractConstBuilder<'a, 'tcx> {
274 body_id: thir::ExprId,
275 body: &'a thir::Thir<'tcx>,
276 /// The current WIP node tree.
277 nodes: IndexVec<NodeId, Node<'tcx>>,
280 impl<'a, 'tcx> AbstractConstBuilder<'a, 'tcx> {
281 fn root_span(&self) -> Span {
282 self.body.exprs[self.body_id].span
285 fn error(&mut self, span: Span, msg: &str) -> Result<!, ErrorGuaranteed> {
289 .struct_span_err(self.root_span(), "overly complex generic constant")
290 .span_label(span, msg)
291 .help("consider moving this anonymous constant into a `const` function")
296 fn maybe_supported_error(&mut self, span: Span, msg: &str) -> Result<!, ErrorGuaranteed> {
300 .struct_span_err(self.root_span(), "overly complex generic constant")
301 .span_label(span, msg)
302 .help("consider moving this anonymous constant into a `const` function")
303 .note("this operation may be supported in the future")
309 #[instrument(skip(tcx, body, body_id), level = "debug")]
312 (body, body_id): (&'a thir::Thir<'tcx>, thir::ExprId),
313 ) -> Result<Option<AbstractConstBuilder<'a, 'tcx>>, ErrorGuaranteed> {
314 let builder = AbstractConstBuilder { tcx, body_id, body, nodes: IndexVec::new() };
316 struct IsThirPolymorphic<'a, 'tcx> {
318 thir: &'a thir::Thir<'tcx>,
321 use crate::rustc_middle::thir::visit::Visitor;
324 impl<'a, 'tcx> IsThirPolymorphic<'a, 'tcx> {
325 fn expr_is_poly(&mut self, expr: &thir::Expr<'tcx>) -> bool {
326 if expr.ty.has_param_types_or_consts() {
331 thir::ExprKind::NamedConst { substs, .. } => substs.has_param_types_or_consts(),
332 thir::ExprKind::ConstParam { .. } => true,
333 thir::ExprKind::Repeat { value, count } => {
334 self.visit_expr(&self.thir()[value]);
335 count.has_param_types_or_consts()
341 fn pat_is_poly(&mut self, pat: &thir::Pat<'tcx>) -> bool {
342 if pat.ty.has_param_types_or_consts() {
346 match pat.kind.as_ref() {
347 thir::PatKind::Constant { value } => value.has_param_types_or_consts(),
348 thir::PatKind::Range(thir::PatRange { lo, hi, .. }) => {
349 lo.has_param_types_or_consts() || hi.has_param_types_or_consts()
356 impl<'a, 'tcx> visit::Visitor<'a, 'tcx> for IsThirPolymorphic<'a, 'tcx> {
357 fn thir(&self) -> &'a thir::Thir<'tcx> {
361 #[instrument(skip(self), level = "debug")]
362 fn visit_expr(&mut self, expr: &thir::Expr<'tcx>) {
363 self.is_poly |= self.expr_is_poly(expr);
365 visit::walk_expr(self, expr)
369 #[instrument(skip(self), level = "debug")]
370 fn visit_pat(&mut self, pat: &thir::Pat<'tcx>) {
371 self.is_poly |= self.pat_is_poly(pat);
373 visit::walk_pat(self, pat);
378 let mut is_poly_vis = IsThirPolymorphic { is_poly: false, thir: body };
379 visit::walk_expr(&mut is_poly_vis, &body[body_id]);
380 debug!("AbstractConstBuilder: is_poly={}", is_poly_vis.is_poly);
381 if !is_poly_vis.is_poly {
388 /// We do not allow all binary operations in abstract consts, so filter disallowed ones.
389 fn check_binop(op: mir::BinOp) -> bool {
392 Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Shl | Shr | Eq | Lt | Le
393 | Ne | Ge | Gt => true,
398 /// While we currently allow all unary operations, we still want to explicitly guard against
399 /// future changes here.
400 fn check_unop(op: mir::UnOp) -> bool {
407 /// Builds the abstract const by walking the thir and bailing out when
408 /// encountering an unsupported operation.
409 fn build(mut self) -> Result<&'tcx [Node<'tcx>], ErrorGuaranteed> {
410 debug!("Abstractconstbuilder::build: body={:?}", &*self.body);
411 self.recurse_build(self.body_id)?;
413 for n in self.nodes.iter() {
414 if let Node::Leaf(ct) = n {
415 if let ty::ConstKind::Unevaluated(ct) = ct.kind() {
416 // `AbstractConst`s should not contain any promoteds as they require references which
418 assert_eq!(ct.promoted, None);
419 assert_eq!(ct, self.tcx.erase_regions(ct));
424 Ok(self.tcx.arena.alloc_from_iter(self.nodes.into_iter()))
427 fn recurse_build(&mut self, node: thir::ExprId) -> Result<NodeId, ErrorGuaranteed> {
429 let node = &self.body.exprs[node];
430 Ok(match &node.kind {
431 // I dont know if handling of these 3 is correct
432 &ExprKind::Scope { value, .. } => self.recurse_build(value)?,
433 &ExprKind::PlaceTypeAscription { source, .. }
434 | &ExprKind::ValueTypeAscription { source, .. } => self.recurse_build(source)?,
435 &ExprKind::Literal { lit, neg} => {
438 match self.tcx.at(sp).lit_to_const(LitToConstInput { lit: &lit.node, ty: node.ty, neg }) {
440 Err(LitToConstError::Reported) => {
441 self.tcx.const_error(node.ty)
443 Err(LitToConstError::TypeError) => {
444 bug!("encountered type error in lit_to_const")
448 self.nodes.push(Node::Leaf(constant))
450 &ExprKind::NonHirLiteral { lit , user_ty: _} => {
451 let val = ty::ValTree::from_scalar_int(lit);
452 self.nodes.push(Node::Leaf(ty::Const::from_value(self.tcx, val, node.ty)))
454 &ExprKind::NamedConst { def_id, substs, user_ty: _ } => {
455 let uneval = ty::Unevaluated::new(ty::WithOptConstParam::unknown(def_id), substs);
457 let constant = self.tcx.mk_const(ty::ConstS {
458 kind: ty::ConstKind::Unevaluated(uneval),
462 self.nodes.push(Node::Leaf(constant))
465 ExprKind::ConstParam {param, ..} => {
466 let const_param = self.tcx.mk_const(ty::ConstS {
467 kind: ty::ConstKind::Param(*param),
470 self.nodes.push(Node::Leaf(const_param))
473 ExprKind::Call { fun, args, .. } => {
474 let fun = self.recurse_build(*fun)?;
476 let mut new_args = Vec::<NodeId>::with_capacity(args.len());
477 for &id in args.iter() {
478 new_args.push(self.recurse_build(id)?);
480 let new_args = self.tcx.arena.alloc_slice(&new_args);
481 self.nodes.push(Node::FunctionCall(fun, new_args))
483 &ExprKind::Binary { op, lhs, rhs } if Self::check_binop(op) => {
484 let lhs = self.recurse_build(lhs)?;
485 let rhs = self.recurse_build(rhs)?;
486 self.nodes.push(Node::Binop(op, lhs, rhs))
488 &ExprKind::Unary { op, arg } if Self::check_unop(op) => {
489 let arg = self.recurse_build(arg)?;
490 self.nodes.push(Node::UnaryOp(op, arg))
492 // This is necessary so that the following compiles:
495 // fn foo<const N: usize>(a: [(); N + 1]) {
496 // bar::<{ N + 1 }>();
499 ExprKind::Block { body: thir::Block { stmts: box [], expr: Some(e), .. } } => {
500 self.recurse_build(*e)?
502 // `ExprKind::Use` happens when a `hir::ExprKind::Cast` is a
503 // "coercion cast" i.e. using a coercion or is a no-op.
504 // This is important so that `N as usize as usize` doesnt unify with `N as usize`. (untested)
505 &ExprKind::Use { source } => {
506 let arg = self.recurse_build(source)?;
507 self.nodes.push(Node::Cast(abstract_const::CastKind::Use, arg, node.ty))
509 &ExprKind::Cast { source } => {
510 let arg = self.recurse_build(source)?;
511 self.nodes.push(Node::Cast(abstract_const::CastKind::As, arg, node.ty))
513 ExprKind::Borrow{ arg, ..} => {
514 let arg_node = &self.body.exprs[*arg];
516 // Skip reborrows for now until we allow Deref/Borrow/AddressOf
518 // FIXME(generic_const_exprs): Verify/explain why this is sound
519 if let ExprKind::Deref {arg} = arg_node.kind {
520 self.recurse_build(arg)?
522 self.maybe_supported_error(
524 "borrowing is not supported in generic constants",
528 // FIXME(generic_const_exprs): We may want to support these.
529 ExprKind::AddressOf { .. } | ExprKind::Deref {..}=> self.maybe_supported_error(
531 "dereferencing or taking the address is not supported in generic constants",
533 ExprKind::Repeat { .. } | ExprKind::Array { .. } => self.maybe_supported_error(
535 "array construction is not supported in generic constants",
537 ExprKind::Block { .. } => self.maybe_supported_error(
539 "blocks are not supported in generic constant",
541 ExprKind::NeverToAny { .. } => self.maybe_supported_error(
543 "converting nevers to any is not supported in generic constant",
545 ExprKind::Tuple { .. } => self.maybe_supported_error(
547 "tuple construction is not supported in generic constants",
549 ExprKind::Index { .. } => self.maybe_supported_error(
551 "indexing is not supported in generic constant",
553 ExprKind::Field { .. } => self.maybe_supported_error(
555 "field access is not supported in generic constant",
557 ExprKind::ConstBlock { .. } => self.maybe_supported_error(
559 "const blocks are not supported in generic constant",
561 ExprKind::Adt(_) => self.maybe_supported_error(
563 "struct/enum construction is not supported in generic constants",
565 // dont know if this is correct
566 ExprKind::Pointer { .. } =>
567 self.error(node.span, "pointer casts are not allowed in generic constants")?,
568 ExprKind::Yield { .. } =>
569 self.error(node.span, "generator control flow is not allowed in generic constants")?,
570 ExprKind::Continue { .. } | ExprKind::Break { .. } | ExprKind::Loop { .. } => self
573 "loops and loop control flow are not supported in generic constants",
575 ExprKind::Box { .. } =>
576 self.error(node.span, "allocations are not allowed in generic constants")?,
578 ExprKind::Unary { .. } => unreachable!(),
579 // we handle valid unary/binary ops above
580 ExprKind::Binary { .. } =>
581 self.error(node.span, "unsupported binary operation in generic constants")?,
582 ExprKind::LogicalOp { .. } =>
583 self.error(node.span, "unsupported operation in generic constants, short-circuiting operations would imply control flow")?,
584 ExprKind::Assign { .. } | ExprKind::AssignOp { .. } => {
585 self.error(node.span, "assignment is not supported in generic constants")?
587 ExprKind::Closure { .. } | ExprKind::Return { .. } => self.error(
589 "closures and function keywords are not supported in generic constants",
591 // let expressions imply control flow
592 ExprKind::Match { .. } | ExprKind::If { .. } | ExprKind::Let { .. } =>
593 self.error(node.span, "control flow is not supported in generic constants")?,
594 ExprKind::InlineAsm { .. } => {
595 self.error(node.span, "assembly is not supported in generic constants")?
598 // we dont permit let stmts so `VarRef` and `UpvarRef` cant happen
599 ExprKind::VarRef { .. }
600 | ExprKind::UpvarRef { .. }
601 | ExprKind::StaticRef { .. }
602 | ExprKind::ThreadLocalRef(_) => {
603 self.error(node.span, "unsupported operation in generic constant")?
609 /// Builds an abstract const, do not use this directly, but use `AbstractConst::new` instead.
610 pub(super) fn thir_abstract_const<'tcx>(
612 def: ty::WithOptConstParam<LocalDefId>,
613 ) -> Result<Option<&'tcx [thir::abstract_const::Node<'tcx>]>, ErrorGuaranteed> {
614 if tcx.features().generic_const_exprs {
615 match tcx.def_kind(def.did) {
616 // FIXME(generic_const_exprs): We currently only do this for anonymous constants,
617 // meaning that we do not look into associated constants. I(@lcnr) am not yet sure whether
618 // we want to look into them or treat them as opaque projections.
620 // Right now we do neither of that and simply always fail to unify them.
621 DefKind::AnonConst | DefKind::InlineConst => (),
622 _ => return Ok(None),
625 let body = tcx.thir_body(def)?;
627 AbstractConstBuilder::new(tcx, (&*body.0.borrow(), body.1))?
628 .map(AbstractConstBuilder::build)
635 #[instrument(skip(tcx), level = "debug")]
636 pub(super) fn try_unify_abstract_consts<'tcx>(
638 (a, b): (ty::Unevaluated<'tcx, ()>, ty::Unevaluated<'tcx, ()>),
639 param_env: ty::ParamEnv<'tcx>,
642 if let Some(a) = AbstractConst::new(tcx, a)? {
643 if let Some(b) = AbstractConst::new(tcx, b)? {
644 let const_unify_ctxt = ConstUnifyCtxt { tcx, param_env };
645 return Ok(const_unify_ctxt.try_unify(a, b));
651 .unwrap_or_else(|_: ErrorGuaranteed| true)
652 // FIXME(generic_const_exprs): We should instead have this
653 // method return the resulting `ty::Const` and return `ConstKind::Error`
654 // on `ErrorGuaranteed`.
657 #[instrument(skip(tcx, f), level = "debug")]
658 pub fn walk_abstract_const<'tcx, R, F>(
660 ct: AbstractConst<'tcx>,
664 F: FnMut(AbstractConst<'tcx>) -> ControlFlow<R>,
666 #[instrument(skip(tcx, f), level = "debug")]
669 ct: AbstractConst<'tcx>,
670 f: &mut dyn FnMut(AbstractConst<'tcx>) -> ControlFlow<R>,
671 ) -> ControlFlow<R> {
673 let root = ct.root(tcx);
676 Node::Leaf(_) => ControlFlow::CONTINUE,
677 Node::Binop(_, l, r) => {
678 recurse(tcx, ct.subtree(l), f)?;
679 recurse(tcx, ct.subtree(r), f)
681 Node::UnaryOp(_, v) => recurse(tcx, ct.subtree(v), f),
682 Node::FunctionCall(func, args) => {
683 recurse(tcx, ct.subtree(func), f)?;
684 args.iter().try_for_each(|&arg| recurse(tcx, ct.subtree(arg), f))
686 Node::Cast(_, operand, _) => recurse(tcx, ct.subtree(operand), f),
690 recurse(tcx, ct, &mut f)
693 struct ConstUnifyCtxt<'tcx> {
695 param_env: ty::ParamEnv<'tcx>,
698 impl<'tcx> ConstUnifyCtxt<'tcx> {
699 // Substitutes generics repeatedly to allow AbstractConsts to unify where a
700 // ConstKind::Unevaluated could be turned into an AbstractConst that would unify e.g.
701 // Param(N) should unify with Param(T), substs: [Unevaluated("T2", [Unevaluated("T3", [Param(N)])])]
703 #[instrument(skip(self), level = "debug")]
704 fn try_replace_substs_in_root(
706 mut abstr_const: AbstractConst<'tcx>,
707 ) -> Option<AbstractConst<'tcx>> {
708 while let Node::Leaf(ct) = abstr_const.root(self.tcx) {
709 match AbstractConst::from_const(self.tcx, ct) {
710 Ok(Some(act)) => abstr_const = act,
712 Err(_) => return None,
719 /// Tries to unify two abstract constants using structural equality.
720 #[instrument(skip(self), level = "debug")]
721 fn try_unify(&self, a: AbstractConst<'tcx>, b: AbstractConst<'tcx>) -> bool {
722 let a = if let Some(a) = self.try_replace_substs_in_root(a) {
728 let b = if let Some(b) = self.try_replace_substs_in_root(b) {
734 let a_root = a.root(self.tcx);
735 let b_root = b.root(self.tcx);
736 debug!(?a_root, ?b_root);
738 match (a_root, b_root) {
739 (Node::Leaf(a_ct), Node::Leaf(b_ct)) => {
740 let a_ct = a_ct.eval(self.tcx, self.param_env);
741 debug!("a_ct evaluated: {:?}", a_ct);
742 let b_ct = b_ct.eval(self.tcx, self.param_env);
743 debug!("b_ct evaluated: {:?}", b_ct);
745 if a_ct.ty() != b_ct.ty() {
749 match (a_ct.kind(), b_ct.kind()) {
750 // We can just unify errors with everything to reduce the amount of
751 // emitted errors here.
752 (ty::ConstKind::Error(_), _) | (_, ty::ConstKind::Error(_)) => true,
753 (ty::ConstKind::Param(a_param), ty::ConstKind::Param(b_param)) => {
756 (ty::ConstKind::Value(a_val), ty::ConstKind::Value(b_val)) => a_val == b_val,
757 // If we have `fn a<const N: usize>() -> [u8; N + 1]` and `fn b<const M: usize>() -> [u8; 1 + M]`
758 // we do not want to use `assert_eq!(a(), b())` to infer that `N` and `M` have to be `1`. This
759 // means that we only allow inference variables if they are equal.
760 (ty::ConstKind::Infer(a_val), ty::ConstKind::Infer(b_val)) => a_val == b_val,
761 // We expand generic anonymous constants at the start of this function, so this
762 // branch should only be taking when dealing with associated constants, at
763 // which point directly comparing them seems like the desired behavior.
765 // FIXME(generic_const_exprs): This isn't actually the case.
766 // We also take this branch for concrete anonymous constants and
767 // expand generic anonymous constants with concrete substs.
768 (ty::ConstKind::Unevaluated(a_uv), ty::ConstKind::Unevaluated(b_uv)) => {
771 // FIXME(generic_const_exprs): We may want to either actually try
772 // to evaluate `a_ct` and `b_ct` if they are are fully concrete or something like
773 // this, for now we just return false here.
777 (Node::Binop(a_op, al, ar), Node::Binop(b_op, bl, br)) if a_op == b_op => {
778 self.try_unify(a.subtree(al), b.subtree(bl))
779 && self.try_unify(a.subtree(ar), b.subtree(br))
781 (Node::UnaryOp(a_op, av), Node::UnaryOp(b_op, bv)) if a_op == b_op => {
782 self.try_unify(a.subtree(av), b.subtree(bv))
784 (Node::FunctionCall(a_f, a_args), Node::FunctionCall(b_f, b_args))
785 if a_args.len() == b_args.len() =>
787 self.try_unify(a.subtree(a_f), b.subtree(b_f))
788 && iter::zip(a_args, b_args)
789 .all(|(&an, &bn)| self.try_unify(a.subtree(an), b.subtree(bn)))
791 (Node::Cast(a_kind, a_operand, a_ty), Node::Cast(b_kind, b_operand, b_ty))
792 if (a_ty == b_ty) && (a_kind == b_kind) =>
794 self.try_unify(a.subtree(a_operand), b.subtree(b_operand))
796 // use this over `_ => false` to make adding variants to `Node` less error prone
798 | (Node::FunctionCall(..), _)
799 | (Node::UnaryOp(..), _)
800 | (Node::Binop(..), _)
801 | (Node::Leaf(..), _) => false,