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_data_structures::intern::Interned;
12 use rustc_errors::ErrorGuaranteed;
13 use rustc_hir::def::DefKind;
14 use rustc_index::vec::IndexVec;
15 use rustc_infer::infer::InferCtxt;
16 use rustc_middle::mir;
17 use rustc_middle::mir::interpret::{
18 ConstValue, ErrorHandled, LitToConstError, LitToConstInput, Scalar,
20 use rustc_middle::thir;
21 use rustc_middle::thir::abstract_const::{self, Node, NodeId, NotConstEvaluatable};
22 use rustc_middle::ty::subst::{Subst, SubstsRef};
23 use rustc_middle::ty::{self, DelaySpanBugEmitted, TyCtxt, TypeFoldable};
24 use rustc_session::lint;
25 use rustc_span::def_id::LocalDefId;
30 use std::ops::ControlFlow;
32 /// Check if a given constant can be evaluated.
33 #[instrument(skip(infcx), level = "debug")]
34 pub fn is_const_evaluatable<'cx, 'tcx>(
35 infcx: &InferCtxt<'cx, 'tcx>,
36 uv: ty::Unevaluated<'tcx, ()>,
37 param_env: ty::ParamEnv<'tcx>,
39 ) -> Result<(), NotConstEvaluatable> {
42 if tcx.features().generic_const_exprs {
43 match AbstractConst::new(tcx, uv)? {
44 // We are looking at a generic abstract constant.
46 if satisfied_from_param_env(tcx, ct, param_env)? {
50 // We were unable to unify the abstract constant with
51 // a constant found in the caller bounds, there are
52 // now three possible cases here.
53 #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
55 /// The abstract const still references an inference
56 /// variable, in this case we return `TooGeneric`.
58 /// The abstract const references a generic parameter,
59 /// this means that we emit an error here.
61 /// The substs are concrete enough that we can simply
62 /// try and evaluate the given constant.
65 let mut failure_kind = FailureKind::Concrete;
66 walk_abstract_const::<!, _>(tcx, ct, |node| match node.root(tcx) {
68 if leaf.has_infer_types_or_consts() {
69 failure_kind = FailureKind::MentionsInfer;
70 } else if leaf.has_param_types_or_consts() {
71 failure_kind = cmp::min(failure_kind, FailureKind::MentionsParam);
76 Node::Cast(_, _, ty) => {
77 if ty.has_infer_types_or_consts() {
78 failure_kind = FailureKind::MentionsInfer;
79 } else if ty.has_param_types_or_consts() {
80 failure_kind = cmp::min(failure_kind, FailureKind::MentionsParam);
85 Node::Binop(_, _, _) | Node::UnaryOp(_, _) | Node::FunctionCall(_, _) => {
91 FailureKind::MentionsInfer => {
92 return Err(NotConstEvaluatable::MentionsInfer);
94 FailureKind::MentionsParam => {
95 return Err(NotConstEvaluatable::MentionsParam);
97 FailureKind::Concrete => {
98 // Dealt with below by the same code which handles this
99 // without the feature gate.
104 // If we are dealing with a concrete constant, we can
105 // reuse the old code path and try to evaluate
111 let future_compat_lint = || {
112 if let Some(local_def_id) = uv.def.did.as_local() {
113 infcx.tcx.struct_span_lint_hir(
114 lint::builtin::CONST_EVALUATABLE_UNCHECKED,
115 infcx.tcx.hir().local_def_id_to_hir_id(local_def_id),
118 err.build("cannot use constants which depend on generic parameters in types")
125 // FIXME: We should only try to evaluate a given constant here if it is fully concrete
126 // as we don't want to allow things like `[u8; std::mem::size_of::<*mut T>()]`.
128 // We previously did not check this, so we only emit a future compat warning if
129 // const evaluation succeeds and the given constant is still polymorphic for now
130 // and hopefully soon change this to an error.
132 // See #74595 for more details about this.
133 let concrete = infcx.const_eval_resolve(param_env, uv.expand(), Some(span));
135 if concrete.is_ok() && uv.substs.has_param_types_or_consts() {
136 match infcx.tcx.def_kind(uv.def.did) {
137 DefKind::AnonConst | DefKind::InlineConst => {
138 let mir_body = infcx.tcx.mir_for_ctfe_opt_const_arg(uv.def);
140 if mir_body.is_polymorphic {
141 future_compat_lint();
144 _ => future_compat_lint(),
148 // If we're evaluating a foreign constant, under a nightly compiler without generic
149 // const exprs, AND it would've passed if that expression had been evaluated with
150 // generic const exprs, then suggest using generic const exprs.
152 && tcx.sess.is_nightly_build()
153 && !uv.def.did.is_local()
154 && !tcx.features().generic_const_exprs
155 && let Ok(Some(ct)) = AbstractConst::new(tcx, uv)
156 && satisfied_from_param_env(tcx, ct, param_env) == Ok(true)
160 // Slightly better span than just using `span` alone
161 if span == rustc_span::DUMMY_SP { tcx.def_span(uv.def.did) } else { span },
162 "failed to evaluate generic const expression",
164 .note("the crate this constant originates from uses `#![feature(generic_const_exprs)]`")
165 .span_suggestion_verbose(
166 rustc_span::DUMMY_SP,
167 "consider enabling this feature",
168 "#![feature(generic_const_exprs)]\n".to_string(),
169 rustc_errors::Applicability::MaybeIncorrect,
174 debug!(?concrete, "is_const_evaluatable");
176 Err(ErrorHandled::TooGeneric) => Err(match uv.has_infer_types_or_consts() {
177 true => NotConstEvaluatable::MentionsInfer,
178 false => NotConstEvaluatable::MentionsParam,
180 Err(ErrorHandled::Linted) => {
182 infcx.tcx.sess.delay_span_bug(span, "constant in type had error reported as lint");
183 Err(NotConstEvaluatable::Error(reported))
185 Err(ErrorHandled::Reported(e)) => Err(NotConstEvaluatable::Error(e)),
190 #[instrument(skip(tcx), level = "debug")]
191 fn satisfied_from_param_env<'tcx>(
193 ct: AbstractConst<'tcx>,
194 param_env: ty::ParamEnv<'tcx>,
195 ) -> Result<bool, NotConstEvaluatable> {
196 for pred in param_env.caller_bounds() {
197 match pred.kind().skip_binder() {
198 ty::PredicateKind::ConstEvaluatable(uv) => {
199 if let Some(b_ct) = AbstractConst::new(tcx, uv)? {
200 let const_unify_ctxt = ConstUnifyCtxt { tcx, param_env };
202 // Try to unify with each subtree in the AbstractConst to allow for
203 // `N + 1` being const evaluatable even if theres only a `ConstEvaluatable`
204 // predicate for `(N + 1) * 2`
205 let result = walk_abstract_const(tcx, b_ct, |b_ct| {
206 match const_unify_ctxt.try_unify(ct, b_ct) {
207 true => ControlFlow::BREAK,
208 false => ControlFlow::CONTINUE,
212 if let ControlFlow::Break(()) = result {
213 debug!("is_const_evaluatable: abstract_const ~~> ok");
218 _ => {} // don't care
225 /// A tree representing an anonymous constant.
227 /// This is only able to represent a subset of `MIR`,
228 /// and should not leak any information about desugarings.
229 #[derive(Debug, Clone, Copy)]
230 pub struct AbstractConst<'tcx> {
231 // FIXME: Consider adding something like `IndexSlice`
232 // and use this here.
233 inner: &'tcx [Node<'tcx>],
234 substs: SubstsRef<'tcx>,
237 impl<'tcx> AbstractConst<'tcx> {
240 uv: ty::Unevaluated<'tcx, ()>,
241 ) -> Result<Option<AbstractConst<'tcx>>, ErrorGuaranteed> {
242 let inner = tcx.thir_abstract_const_opt_const_arg(uv.def)?;
243 debug!("AbstractConst::new({:?}) = {:?}", uv, inner);
244 Ok(inner.map(|inner| AbstractConst { inner, substs: uv.substs }))
250 ) -> Result<Option<AbstractConst<'tcx>>, ErrorGuaranteed> {
252 ty::ConstKind::Unevaluated(uv) => AbstractConst::new(tcx, uv.shrink()),
253 ty::ConstKind::Error(DelaySpanBugEmitted { reported, .. }) => Err(reported),
259 pub fn subtree(self, node: NodeId) -> AbstractConst<'tcx> {
260 AbstractConst { inner: &self.inner[..=node.index()], substs: self.substs }
264 pub fn root(self, tcx: TyCtxt<'tcx>) -> Node<'tcx> {
265 let node = self.inner.last().copied().unwrap();
267 Node::Leaf(leaf) => Node::Leaf(leaf.subst(tcx, self.substs)),
268 Node::Cast(kind, operand, ty) => Node::Cast(kind, operand, ty.subst(tcx, self.substs)),
269 // Don't perform substitution on the following as they can't directly contain generic params
270 Node::Binop(_, _, _) | Node::UnaryOp(_, _) | Node::FunctionCall(_, _) => node,
275 struct AbstractConstBuilder<'a, 'tcx> {
277 body_id: thir::ExprId,
278 body: &'a thir::Thir<'tcx>,
279 /// The current WIP node tree.
280 nodes: IndexVec<NodeId, Node<'tcx>>,
283 impl<'a, 'tcx> AbstractConstBuilder<'a, 'tcx> {
284 fn root_span(&self) -> Span {
285 self.body.exprs[self.body_id].span
288 fn error(&mut self, span: Span, msg: &str) -> Result<!, ErrorGuaranteed> {
292 .struct_span_err(self.root_span(), "overly complex generic constant")
293 .span_label(span, msg)
294 .help("consider moving this anonymous constant into a `const` function")
299 fn maybe_supported_error(&mut self, span: Span, msg: &str) -> Result<!, ErrorGuaranteed> {
303 .struct_span_err(self.root_span(), "overly complex generic constant")
304 .span_label(span, msg)
305 .help("consider moving this anonymous constant into a `const` function")
306 .note("this operation may be supported in the future")
312 #[instrument(skip(tcx, body, body_id), level = "debug")]
315 (body, body_id): (&'a thir::Thir<'tcx>, thir::ExprId),
316 ) -> Result<Option<AbstractConstBuilder<'a, 'tcx>>, ErrorGuaranteed> {
317 let builder = AbstractConstBuilder { tcx, body_id, body, nodes: IndexVec::new() };
319 struct IsThirPolymorphic<'a, 'tcx> {
321 thir: &'a thir::Thir<'tcx>,
324 use crate::rustc_middle::thir::visit::Visitor;
327 impl<'a, 'tcx> IsThirPolymorphic<'a, 'tcx> {
328 fn expr_is_poly(&mut self, expr: &thir::Expr<'tcx>) -> bool {
329 if expr.ty.has_param_types_or_consts() {
334 thir::ExprKind::NamedConst { substs, .. } => substs.has_param_types_or_consts(),
335 thir::ExprKind::ConstParam { .. } => true,
336 thir::ExprKind::Repeat { value, count } => {
337 self.visit_expr(&self.thir()[value]);
338 count.has_param_types_or_consts()
344 fn pat_is_poly(&mut self, pat: &thir::Pat<'tcx>) -> bool {
345 if pat.ty.has_param_types_or_consts() {
349 match pat.kind.as_ref() {
350 thir::PatKind::Constant { value } => value.has_param_types_or_consts(),
351 thir::PatKind::Range(thir::PatRange { lo, hi, .. }) => {
352 lo.has_param_types_or_consts() || hi.has_param_types_or_consts()
359 impl<'a, 'tcx> visit::Visitor<'a, 'tcx> for IsThirPolymorphic<'a, 'tcx> {
360 fn thir(&self) -> &'a thir::Thir<'tcx> {
364 #[instrument(skip(self), level = "debug")]
365 fn visit_expr(&mut self, expr: &thir::Expr<'tcx>) {
366 self.is_poly |= self.expr_is_poly(expr);
368 visit::walk_expr(self, expr)
372 #[instrument(skip(self), level = "debug")]
373 fn visit_pat(&mut self, pat: &thir::Pat<'tcx>) {
374 self.is_poly |= self.pat_is_poly(pat);
376 visit::walk_pat(self, pat);
380 fn visit_const(&mut self, ct: ty::Const<'tcx>) {
381 self.is_poly |= ct.has_param_types_or_consts();
384 fn visit_constant(&mut self, ct: mir::ConstantKind<'tcx>) {
385 self.is_poly |= ct.has_param_types_or_consts();
389 let mut is_poly_vis = IsThirPolymorphic { is_poly: false, thir: body };
390 visit::walk_expr(&mut is_poly_vis, &body[body_id]);
391 debug!("AbstractConstBuilder: is_poly={}", is_poly_vis.is_poly);
392 if !is_poly_vis.is_poly {
399 /// We do not allow all binary operations in abstract consts, so filter disallowed ones.
400 fn check_binop(op: mir::BinOp) -> bool {
403 Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Shl | Shr | Eq | Lt | Le
404 | Ne | Ge | Gt => true,
409 /// While we currently allow all unary operations, we still want to explicitly guard against
410 /// future changes here.
411 fn check_unop(op: mir::UnOp) -> bool {
418 /// Builds the abstract const by walking the thir and bailing out when
419 /// encountering an unsupported operation.
420 fn build(mut self) -> Result<&'tcx [Node<'tcx>], ErrorGuaranteed> {
421 debug!("Abstractconstbuilder::build: body={:?}", &*self.body);
422 self.recurse_build(self.body_id)?;
424 for n in self.nodes.iter() {
425 if let Node::Leaf(ty::Const(Interned(
426 ty::ConstS { val: ty::ConstKind::Unevaluated(ct), ty: _ },
430 // `AbstractConst`s should not contain any promoteds as they require references which
432 assert_eq!(ct.promoted, None);
436 Ok(self.tcx.arena.alloc_from_iter(self.nodes.into_iter()))
439 fn recurse_build(&mut self, node: thir::ExprId) -> Result<NodeId, ErrorGuaranteed> {
441 let node = &self.body.exprs[node];
442 Ok(match &node.kind {
443 // I dont know if handling of these 3 is correct
444 &ExprKind::Scope { value, .. } => self.recurse_build(value)?,
445 &ExprKind::PlaceTypeAscription { source, .. }
446 | &ExprKind::ValueTypeAscription { source, .. } => self.recurse_build(source)?,
447 &ExprKind::Literal { lit, neg} => {
450 match self.tcx.at(sp).lit_to_const(LitToConstInput { lit: &lit.node, ty: node.ty, neg }) {
452 Err(LitToConstError::Reported) => {
453 self.tcx.const_error(node.ty)
455 Err(LitToConstError::TypeError) => {
456 bug!("encountered type error in lit_to_const")
460 self.nodes.push(Node::Leaf(constant))
462 &ExprKind::NonHirLiteral { lit , user_ty: _} => {
463 // FIXME Construct a Valtree from this ScalarInt when introducing Valtrees
464 let const_value = ConstValue::Scalar(Scalar::Int(lit));
465 self.nodes.push(Node::Leaf(ty::Const::from_value(self.tcx, const_value, node.ty)))
467 &ExprKind::NamedConst { def_id, substs, user_ty: _ } => {
468 let uneval = ty::Unevaluated::new(ty::WithOptConstParam::unknown(def_id), substs);
470 let constant = self.tcx.mk_const(ty::ConstS {
471 val: ty::ConstKind::Unevaluated(uneval),
475 self.nodes.push(Node::Leaf(constant))
478 ExprKind::ConstParam {param, ..} => {
479 let const_param = self.tcx.mk_const(ty::ConstS {
480 val: ty::ConstKind::Param(*param),
483 self.nodes.push(Node::Leaf(const_param))
486 ExprKind::Call { fun, args, .. } => {
487 let fun = self.recurse_build(*fun)?;
489 let mut new_args = Vec::<NodeId>::with_capacity(args.len());
490 for &id in args.iter() {
491 new_args.push(self.recurse_build(id)?);
493 let new_args = self.tcx.arena.alloc_slice(&new_args);
494 self.nodes.push(Node::FunctionCall(fun, new_args))
496 &ExprKind::Binary { op, lhs, rhs } if Self::check_binop(op) => {
497 let lhs = self.recurse_build(lhs)?;
498 let rhs = self.recurse_build(rhs)?;
499 self.nodes.push(Node::Binop(op, lhs, rhs))
501 &ExprKind::Unary { op, arg } if Self::check_unop(op) => {
502 let arg = self.recurse_build(arg)?;
503 self.nodes.push(Node::UnaryOp(op, arg))
505 // This is necessary so that the following compiles:
508 // fn foo<const N: usize>(a: [(); N + 1]) {
509 // bar::<{ N + 1 }>();
512 ExprKind::Block { body: thir::Block { stmts: box [], expr: Some(e), .. } } => {
513 self.recurse_build(*e)?
515 // `ExprKind::Use` happens when a `hir::ExprKind::Cast` is a
516 // "coercion cast" i.e. using a coercion or is a no-op.
517 // This is important so that `N as usize as usize` doesnt unify with `N as usize`. (untested)
518 &ExprKind::Use { source } => {
519 let arg = self.recurse_build(source)?;
520 self.nodes.push(Node::Cast(abstract_const::CastKind::Use, arg, node.ty))
522 &ExprKind::Cast { source } => {
523 let arg = self.recurse_build(source)?;
524 self.nodes.push(Node::Cast(abstract_const::CastKind::As, arg, node.ty))
526 ExprKind::Borrow{ arg, ..} => {
527 let arg_node = &self.body.exprs[*arg];
529 // Skip reborrows for now until we allow Deref/Borrow/AddressOf
531 // FIXME(generic_const_exprs): Verify/explain why this is sound
532 if let ExprKind::Deref {arg} = arg_node.kind {
533 self.recurse_build(arg)?
535 self.maybe_supported_error(
537 "borrowing is not supported in generic constants",
541 // FIXME(generic_const_exprs): We may want to support these.
542 ExprKind::AddressOf { .. } | ExprKind::Deref {..}=> self.maybe_supported_error(
544 "dereferencing or taking the address is not supported in generic constants",
546 ExprKind::Repeat { .. } | ExprKind::Array { .. } => self.maybe_supported_error(
548 "array construction is not supported in generic constants",
550 ExprKind::Block { .. } => self.maybe_supported_error(
552 "blocks are not supported in generic constant",
554 ExprKind::NeverToAny { .. } => self.maybe_supported_error(
556 "converting nevers to any is not supported in generic constant",
558 ExprKind::Tuple { .. } => self.maybe_supported_error(
560 "tuple construction is not supported in generic constants",
562 ExprKind::Index { .. } => self.maybe_supported_error(
564 "indexing is not supported in generic constant",
566 ExprKind::Field { .. } => self.maybe_supported_error(
568 "field access is not supported in generic constant",
570 ExprKind::ConstBlock { .. } => self.maybe_supported_error(
572 "const blocks are not supported in generic constant",
574 ExprKind::Adt(_) => self.maybe_supported_error(
576 "struct/enum construction is not supported in generic constants",
578 // dont know if this is correct
579 ExprKind::Pointer { .. } =>
580 self.error(node.span, "pointer casts are not allowed in generic constants")?,
581 ExprKind::Yield { .. } =>
582 self.error(node.span, "generator control flow is not allowed in generic constants")?,
583 ExprKind::Continue { .. } | ExprKind::Break { .. } | ExprKind::Loop { .. } => self
586 "loops and loop control flow are not supported in generic constants",
588 ExprKind::Box { .. } =>
589 self.error(node.span, "allocations are not allowed in generic constants")?,
591 ExprKind::Unary { .. } => unreachable!(),
592 // we handle valid unary/binary ops above
593 ExprKind::Binary { .. } =>
594 self.error(node.span, "unsupported binary operation in generic constants")?,
595 ExprKind::LogicalOp { .. } =>
596 self.error(node.span, "unsupported operation in generic constants, short-circuiting operations would imply control flow")?,
597 ExprKind::Assign { .. } | ExprKind::AssignOp { .. } => {
598 self.error(node.span, "assignment is not supported in generic constants")?
600 ExprKind::Closure { .. } | ExprKind::Return { .. } => self.error(
602 "closures and function keywords are not supported in generic constants",
604 // let expressions imply control flow
605 ExprKind::Match { .. } | ExprKind::If { .. } | ExprKind::Let { .. } =>
606 self.error(node.span, "control flow is not supported in generic constants")?,
607 ExprKind::InlineAsm { .. } => {
608 self.error(node.span, "assembly is not supported in generic constants")?
611 // we dont permit let stmts so `VarRef` and `UpvarRef` cant happen
612 ExprKind::VarRef { .. }
613 | ExprKind::UpvarRef { .. }
614 | ExprKind::StaticRef { .. }
615 | ExprKind::ThreadLocalRef(_) => {
616 self.error(node.span, "unsupported operation in generic constant")?
622 /// Builds an abstract const, do not use this directly, but use `AbstractConst::new` instead.
623 pub(super) fn thir_abstract_const<'tcx>(
625 def: ty::WithOptConstParam<LocalDefId>,
626 ) -> Result<Option<&'tcx [thir::abstract_const::Node<'tcx>]>, ErrorGuaranteed> {
627 if tcx.features().generic_const_exprs {
628 match tcx.def_kind(def.did) {
629 // FIXME(generic_const_exprs): We currently only do this for anonymous constants,
630 // meaning that we do not look into associated constants. I(@lcnr) am not yet sure whether
631 // we want to look into them or treat them as opaque projections.
633 // Right now we do neither of that and simply always fail to unify them.
634 DefKind::AnonConst | DefKind::InlineConst => (),
635 _ => return Ok(None),
638 let body = tcx.thir_body(def)?;
640 AbstractConstBuilder::new(tcx, (&*body.0.borrow(), body.1))?
641 .map(AbstractConstBuilder::build)
648 #[instrument(skip(tcx), level = "debug")]
649 pub(super) fn try_unify_abstract_consts<'tcx>(
651 (a, b): (ty::Unevaluated<'tcx, ()>, ty::Unevaluated<'tcx, ()>),
652 param_env: ty::ParamEnv<'tcx>,
655 if let Some(a) = AbstractConst::new(tcx, a)? {
656 if let Some(b) = AbstractConst::new(tcx, b)? {
657 let const_unify_ctxt = ConstUnifyCtxt { tcx, param_env };
658 return Ok(const_unify_ctxt.try_unify(a, b));
664 .unwrap_or_else(|_: ErrorGuaranteed| true)
665 // FIXME(generic_const_exprs): We should instead have this
666 // method return the resulting `ty::Const` and return `ConstKind::Error`
667 // on `ErrorGuaranteed`.
670 #[instrument(skip(tcx, f), level = "debug")]
671 pub fn walk_abstract_const<'tcx, R, F>(
673 ct: AbstractConst<'tcx>,
677 F: FnMut(AbstractConst<'tcx>) -> ControlFlow<R>,
679 #[instrument(skip(tcx, f), level = "debug")]
682 ct: AbstractConst<'tcx>,
683 f: &mut dyn FnMut(AbstractConst<'tcx>) -> ControlFlow<R>,
684 ) -> ControlFlow<R> {
686 let root = ct.root(tcx);
689 Node::Leaf(_) => ControlFlow::CONTINUE,
690 Node::Binop(_, l, r) => {
691 recurse(tcx, ct.subtree(l), f)?;
692 recurse(tcx, ct.subtree(r), f)
694 Node::UnaryOp(_, v) => recurse(tcx, ct.subtree(v), f),
695 Node::FunctionCall(func, args) => {
696 recurse(tcx, ct.subtree(func), f)?;
697 args.iter().try_for_each(|&arg| recurse(tcx, ct.subtree(arg), f))
699 Node::Cast(_, operand, _) => recurse(tcx, ct.subtree(operand), f),
703 recurse(tcx, ct, &mut f)
706 struct ConstUnifyCtxt<'tcx> {
708 param_env: ty::ParamEnv<'tcx>,
711 impl<'tcx> ConstUnifyCtxt<'tcx> {
712 // Substitutes generics repeatedly to allow AbstractConsts to unify where a
713 // ConstKind::Unevaluated could be turned into an AbstractConst that would unify e.g.
714 // Param(N) should unify with Param(T), substs: [Unevaluated("T2", [Unevaluated("T3", [Param(N)])])]
716 #[instrument(skip(self), level = "debug")]
717 fn try_replace_substs_in_root(
719 mut abstr_const: AbstractConst<'tcx>,
720 ) -> Option<AbstractConst<'tcx>> {
721 while let Node::Leaf(ct) = abstr_const.root(self.tcx) {
722 match AbstractConst::from_const(self.tcx, ct) {
723 Ok(Some(act)) => abstr_const = act,
725 Err(_) => return None,
732 /// Tries to unify two abstract constants using structural equality.
733 #[instrument(skip(self), level = "debug")]
734 fn try_unify(&self, a: AbstractConst<'tcx>, b: AbstractConst<'tcx>) -> bool {
735 let a = if let Some(a) = self.try_replace_substs_in_root(a) {
741 let b = if let Some(b) = self.try_replace_substs_in_root(b) {
747 let a_root = a.root(self.tcx);
748 let b_root = b.root(self.tcx);
749 debug!(?a_root, ?b_root);
751 match (a_root, b_root) {
752 (Node::Leaf(a_ct), Node::Leaf(b_ct)) => {
753 let a_ct = a_ct.eval(self.tcx, self.param_env);
754 debug!("a_ct evaluated: {:?}", a_ct);
755 let b_ct = b_ct.eval(self.tcx, self.param_env);
756 debug!("b_ct evaluated: {:?}", b_ct);
758 if a_ct.ty() != b_ct.ty() {
762 match (a_ct.val(), b_ct.val()) {
763 // We can just unify errors with everything to reduce the amount of
764 // emitted errors here.
765 (ty::ConstKind::Error(_), _) | (_, ty::ConstKind::Error(_)) => true,
766 (ty::ConstKind::Param(a_param), ty::ConstKind::Param(b_param)) => {
769 (ty::ConstKind::Value(a_val), ty::ConstKind::Value(b_val)) => a_val == b_val,
770 // If we have `fn a<const N: usize>() -> [u8; N + 1]` and `fn b<const M: usize>() -> [u8; 1 + M]`
771 // we do not want to use `assert_eq!(a(), b())` to infer that `N` and `M` have to be `1`. This
772 // means that we only allow inference variables if they are equal.
773 (ty::ConstKind::Infer(a_val), ty::ConstKind::Infer(b_val)) => a_val == b_val,
774 // We expand generic anonymous constants at the start of this function, so this
775 // branch should only be taking when dealing with associated constants, at
776 // which point directly comparing them seems like the desired behavior.
778 // FIXME(generic_const_exprs): This isn't actually the case.
779 // We also take this branch for concrete anonymous constants and
780 // expand generic anonymous constants with concrete substs.
781 (ty::ConstKind::Unevaluated(a_uv), ty::ConstKind::Unevaluated(b_uv)) => {
784 // FIXME(generic_const_exprs): We may want to either actually try
785 // to evaluate `a_ct` and `b_ct` if they are are fully concrete or something like
786 // this, for now we just return false here.
790 (Node::Binop(a_op, al, ar), Node::Binop(b_op, bl, br)) if a_op == b_op => {
791 self.try_unify(a.subtree(al), b.subtree(bl))
792 && self.try_unify(a.subtree(ar), b.subtree(br))
794 (Node::UnaryOp(a_op, av), Node::UnaryOp(b_op, bv)) if a_op == b_op => {
795 self.try_unify(a.subtree(av), b.subtree(bv))
797 (Node::FunctionCall(a_f, a_args), Node::FunctionCall(b_f, b_args))
798 if a_args.len() == b_args.len() =>
800 self.try_unify(a.subtree(a_f), b.subtree(b_f))
801 && iter::zip(a_args, b_args)
802 .all(|(&an, &bn)| self.try_unify(a.subtree(an), b.subtree(bn)))
804 (Node::Cast(a_kind, a_operand, a_ty), Node::Cast(b_kind, b_operand, b_ty))
805 if (a_ty == b_ty) && (a_kind == b_kind) =>
807 self.try_unify(a.subtree(a_operand), b.subtree(b_operand))
809 // use this over `_ => false` to make adding variants to `Node` less error prone
811 | (Node::FunctionCall(..), _)
812 | (Node::UnaryOp(..), _)
813 | (Node::Binop(..), _)
814 | (Node::Leaf(..), _) => false,
819 /* Think I need these changes
822 (mir::ConstantKind::Ty(a_ct), mir::ConstantKind::Ty(b_ct)) => {
823 match (a_ct.val(), b_ct.val()) {
824 // We can just unify errors with everything to reduce the amount of
825 // emitted errors here.
826 (ty::ConstKind::Error(_), _) | (_, ty::ConstKind::Error(_)) => true,
827 (ty::ConstKind::Param(a_param), ty::ConstKind::Param(b_param)) => {
830 (ty::ConstKind::Value(a_val), ty::ConstKind::Value(b_val)) => {
834 // If we have `fn a<const N: usize>() -> [u8; N + 1]` and `fn b<const M: usize>() -> [u8; 1 + M]`
835 // we do not want to use `assert_eq!(a(), b())` to infer that `N` and `M` have to be `1`. This
836 // means that we only allow inference variables if they are equal.
837 (ty::ConstKind::Infer(a_val), ty::ConstKind::Infer(b_val)) => {
840 // We expand generic anonymous constants at the start of this function, so this
841 // branch should only be taking when dealing with associated constants, at
842 // which point directly comparing them seems like the desired behavior.
844 // FIXME(generic_const_exprs): This isn't actually the case.
845 // We also take this branch for concrete anonymous constants and
846 // expand generic anonymous constants with concrete substs.
847 (ty::ConstKind::Unevaluated(a_uv), ty::ConstKind::Unevaluated(b_uv)) => {
850 // FIXME(generic_const_exprs): We may want to either actually try
851 // to evaluate `a_ct` and `b_ct` if they are are fully concrete or something like
852 // this, for now we just return false here.
856 (mir::ConstantKind::Val(a_val, a_ty), mir::ConstantKind::Val(b_val, b_ty)) => {
857 a_val == b_val && a_ty == b_ty
860 // FIXME Can it happen that we need to compare ConstantKind::Ty(ConstKind::Value)
861 // with a ConstantKind::Val and vice versa?
863 >>>>>>> 6064f16d846 (change thir to use mir::ConstantKind instead of ty::Const)