]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_trait_selection/src/traits/const_evaluatable.rs
Rollup merge of #83791 - the8472:relax-zip-side-effect-guarantee, r=dtolnay
[rust.git] / compiler / rustc_trait_selection / src / traits / const_evaluatable.rs
1 //! Checking that constant values used in types can be successfully evaluated.
2 //!
3 //! For concrete constants, this is fairly simple as we can just try and evaluate it.
4 //!
5 //! When dealing with polymorphic constants, for example `std::mem::size_of::<T>() - 1`,
6 //! this is not as easy.
7 //!
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;
23 use rustc_span::Span;
24
25 use std::cmp;
26 use std::iter;
27 use std::ops::ControlFlow;
28
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>,
34     span: Span,
35 ) -> Result<(), NotConstEvaluatable> {
36     debug!("is_const_evaluatable({:?})", uv);
37     if infcx.tcx.features().generic_const_exprs {
38         let tcx = infcx.tcx;
39         match AbstractConst::new(tcx, uv)? {
40             // We are looking at a generic abstract constant.
41             Some(ct) => {
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`
49                                 let result =
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,
54                                         }
55                                     });
56
57                                 if let ControlFlow::Break(()) = result {
58                                     debug!("is_const_evaluatable: abstract_const ~~> ok");
59                                     return Ok(());
60                                 }
61                             }
62                         }
63                         _ => {} // don't care
64                     }
65                 }
66
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)]
71                 enum FailureKind {
72                     /// The abstract const still references an inference
73                     /// variable, in this case we return `TooGeneric`.
74                     MentionsInfer,
75                     /// The abstract const references a generic parameter,
76                     /// this means that we emit an error here.
77                     MentionsParam,
78                     /// The substs are concrete enough that we can simply
79                     /// try and evaluate the given constant.
80                     Concrete,
81                 }
82                 let mut failure_kind = FailureKind::Concrete;
83                 walk_abstract_const::<!, _>(tcx, ct, |node| match node.root(tcx) {
84                     Node::Leaf(leaf) => {
85                         if leaf.has_infer_types_or_consts() {
86                             failure_kind = FailureKind::MentionsInfer;
87                         } else if leaf.definitely_has_param_types_or_consts(tcx) {
88                             failure_kind = cmp::min(failure_kind, FailureKind::MentionsParam);
89                         }
90
91                         ControlFlow::CONTINUE
92                     }
93                     Node::Cast(_, _, ty) => {
94                         if ty.has_infer_types_or_consts() {
95                             failure_kind = FailureKind::MentionsInfer;
96                         } else if ty.definitely_has_param_types_or_consts(tcx) {
97                             failure_kind = cmp::min(failure_kind, FailureKind::MentionsParam);
98                         }
99
100                         ControlFlow::CONTINUE
101                     }
102                     Node::Binop(_, _, _) | Node::UnaryOp(_, _) | Node::FunctionCall(_, _) => {
103                         ControlFlow::CONTINUE
104                     }
105                 });
106
107                 match failure_kind {
108                     FailureKind::MentionsInfer => {
109                         return Err(NotConstEvaluatable::MentionsInfer);
110                     }
111                     FailureKind::MentionsParam => {
112                         return Err(NotConstEvaluatable::MentionsParam);
113                     }
114                     FailureKind::Concrete => {
115                         // Dealt with below by the same code which handles this
116                         // without the feature gate.
117                     }
118                 }
119             }
120             None => {
121                 // If we are dealing with a concrete constant, we can
122                 // reuse the old code path and try to evaluate
123                 // the constant.
124             }
125         }
126     }
127
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),
133                 span,
134                 |err| {
135                     err.build("cannot use constants which depend on generic parameters in types")
136                         .emit();
137                 },
138             );
139         }
140     };
141
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>()]`.
144     //
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.
148     //
149     // See #74595 for more details about this.
150     let concrete = infcx.const_eval_resolve(param_env, uv.expand(), Some(span));
151
152     if concrete.is_ok() && uv.substs(infcx.tcx).definitely_has_param_types_or_consts(infcx.tcx) {
153         match infcx.tcx.def_kind(uv.def.did) {
154             DefKind::AnonConst | DefKind::InlineConst => {
155                 let mir_body = infcx.tcx.mir_for_ctfe_opt_const_arg(uv.def);
156
157                 if mir_body.is_polymorphic {
158                     future_compat_lint();
159                 }
160             }
161             _ => future_compat_lint(),
162         }
163     }
164
165     debug!(?concrete, "is_const_evaluatable");
166     match concrete {
167         Err(ErrorHandled::TooGeneric) => Err(match uv.has_infer_types_or_consts() {
168             true => NotConstEvaluatable::MentionsInfer,
169             false => NotConstEvaluatable::MentionsParam,
170         }),
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))
174         }
175         Err(ErrorHandled::Reported(e)) => Err(NotConstEvaluatable::Error(e)),
176         Ok(_) => Ok(()),
177     }
178 }
179
180 /// A tree representing an anonymous constant.
181 ///
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>,
190 }
191
192 impl<'tcx> AbstractConst<'tcx> {
193     pub fn new(
194         tcx: TyCtxt<'tcx>,
195         uv: ty::Unevaluated<'tcx, ()>,
196     ) -> Result<Option<AbstractConst<'tcx>>, ErrorReported> {
197         let inner = tcx.thir_abstract_const_opt_const_arg(uv.def)?;
198         debug!("AbstractConst::new({:?}) = {:?}", uv, inner);
199         Ok(inner.map(|inner| AbstractConst { inner, substs: uv.substs(tcx) }))
200     }
201
202     pub fn from_const(
203         tcx: TyCtxt<'tcx>,
204         ct: &ty::Const<'tcx>,
205     ) -> Result<Option<AbstractConst<'tcx>>, ErrorReported> {
206         match ct.val {
207             ty::ConstKind::Unevaluated(uv) => AbstractConst::new(tcx, uv.shrink()),
208             ty::ConstKind::Error(_) => Err(ErrorReported),
209             _ => Ok(None),
210         }
211     }
212
213     #[inline]
214     pub fn subtree(self, node: NodeId) -> AbstractConst<'tcx> {
215         AbstractConst { inner: &self.inner[..=node.index()], substs: self.substs }
216     }
217
218     #[inline]
219     pub fn root(self, tcx: TyCtxt<'tcx>) -> Node<'tcx> {
220         let node = self.inner.last().copied().unwrap();
221         match node {
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,
226         }
227     }
228 }
229
230 struct AbstractConstBuilder<'a, 'tcx> {
231     tcx: TyCtxt<'tcx>,
232     body_id: thir::ExprId,
233     body: &'a thir::Thir<'tcx>,
234     /// The current WIP node tree.
235     nodes: IndexVec<NodeId, Node<'tcx>>,
236 }
237
238 impl<'a, 'tcx> AbstractConstBuilder<'a, 'tcx> {
239     fn root_span(&self) -> Span {
240         self.body.exprs[self.body_id].span
241     }
242
243     fn error(&mut self, span: Span, msg: &str) -> Result<!, ErrorReported> {
244         self.tcx
245             .sess
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")
249             .emit();
250
251         Err(ErrorReported)
252     }
253     fn maybe_supported_error(&mut self, span: Span, msg: &str) -> Result<!, ErrorReported> {
254         self.tcx
255             .sess
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")
260             .emit();
261
262         Err(ErrorReported)
263     }
264
265     fn new(
266         tcx: TyCtxt<'tcx>,
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() };
270
271         struct IsThirPolymorphic<'a, 'tcx> {
272             is_poly: bool,
273             thir: &'a thir::Thir<'tcx>,
274             tcx: TyCtxt<'tcx>,
275         }
276
277         use thir::visit;
278         impl<'a, 'tcx: 'a> visit::Visitor<'a, 'tcx> for IsThirPolymorphic<'a, 'tcx> {
279             fn thir(&self) -> &'a thir::Thir<'tcx> {
280                 &self.thir
281             }
282
283             fn visit_expr(&mut self, expr: &thir::Expr<'tcx>) {
284                 self.is_poly |= expr.ty.definitely_has_param_types_or_consts(self.tcx);
285                 if !self.is_poly {
286                     visit::walk_expr(self, expr)
287                 }
288             }
289
290             fn visit_pat(&mut self, pat: &thir::Pat<'tcx>) {
291                 self.is_poly |= pat.ty.definitely_has_param_types_or_consts(self.tcx);
292                 if !self.is_poly {
293                     visit::walk_pat(self, pat);
294                 }
295             }
296
297             fn visit_const(&mut self, ct: &'tcx ty::Const<'tcx>) {
298                 self.is_poly |= ct.definitely_has_param_types_or_consts(self.tcx);
299             }
300         }
301
302         let mut is_poly_vis = IsThirPolymorphic { is_poly: false, thir: body, tcx };
303         visit::walk_expr(&mut is_poly_vis, &body[body_id]);
304         debug!("AbstractConstBuilder: is_poly={}", is_poly_vis.is_poly);
305         if !is_poly_vis.is_poly {
306             return Ok(None);
307         }
308
309         Ok(Some(builder))
310     }
311
312     /// We do not allow all binary operations in abstract consts, so filter disallowed ones.
313     fn check_binop(op: mir::BinOp) -> bool {
314         use mir::BinOp::*;
315         match op {
316             Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Shl | Shr | Eq | Lt | Le
317             | Ne | Ge | Gt => true,
318             Offset => false,
319         }
320     }
321
322     /// While we currently allow all unary operations, we still want to explicitly guard against
323     /// future changes here.
324     fn check_unop(op: mir::UnOp) -> bool {
325         use mir::UnOp::*;
326         match op {
327             Not | Neg => true,
328         }
329     }
330
331     /// Builds the abstract const by walking the thir and bailing out when
332     /// encountering an unspported operation.
333     fn build(mut self) -> Result<&'tcx [Node<'tcx>], ErrorReported> {
334         debug!("Abstractconstbuilder::build: body={:?}", &*self.body);
335         self.recurse_build(self.body_id)?;
336
337         for n in self.nodes.iter() {
338             if let Node::Leaf(ty::Const { val: ty::ConstKind::Unevaluated(ct), ty: _ }) = n {
339                 // `AbstractConst`s should not contain any promoteds as they require references which
340                 // are not allowed.
341                 assert_eq!(ct.promoted, None);
342             }
343         }
344
345         Ok(self.tcx.arena.alloc_from_iter(self.nodes.into_iter()))
346     }
347
348     fn recurse_build(&mut self, node: thir::ExprId) -> Result<NodeId, ErrorReported> {
349         use thir::ExprKind;
350         let node = &self.body.exprs[node];
351         debug!("recurse_build: node={:?}", node);
352         Ok(match &node.kind {
353             // I dont know if handling of these 3 is correct
354             &ExprKind::Scope { value, .. } => self.recurse_build(value)?,
355             &ExprKind::PlaceTypeAscription { source, .. }
356             | &ExprKind::ValueTypeAscription { source, .. } => self.recurse_build(source)?,
357
358             // subtle: associated consts are literals this arm handles
359             // `<T as Trait>::ASSOC` as well as `12`
360             &ExprKind::Literal { literal, .. } => self.nodes.push(Node::Leaf(literal)),
361
362             ExprKind::Call { fun, args, .. } => {
363                 let fun = self.recurse_build(*fun)?;
364
365                 let mut new_args = Vec::<NodeId>::with_capacity(args.len());
366                 for &id in args.iter() {
367                     new_args.push(self.recurse_build(id)?);
368                 }
369                 let new_args = self.tcx.arena.alloc_slice(&new_args);
370                 self.nodes.push(Node::FunctionCall(fun, new_args))
371             }
372             &ExprKind::Binary { op, lhs, rhs } if Self::check_binop(op) => {
373                 let lhs = self.recurse_build(lhs)?;
374                 let rhs = self.recurse_build(rhs)?;
375                 self.nodes.push(Node::Binop(op, lhs, rhs))
376             }
377             &ExprKind::Unary { op, arg } if Self::check_unop(op) => {
378                 let arg = self.recurse_build(arg)?;
379                 self.nodes.push(Node::UnaryOp(op, arg))
380             }
381             // This is necessary so that the following compiles:
382             //
383             // ```
384             // fn foo<const N: usize>(a: [(); N + 1]) {
385             //     bar::<{ N + 1 }>();
386             // }
387             // ```
388             ExprKind::Block { body: thir::Block { stmts: box [], expr: Some(e), .. } } => {
389                 self.recurse_build(*e)?
390             }
391             // `ExprKind::Use` happens when a `hir::ExprKind::Cast` is a
392             // "coercion cast" i.e. using a coercion or is a no-op.
393             // This is important so that `N as usize as usize` doesnt unify with `N as usize`. (untested)
394             &ExprKind::Use { source } => {
395                 let arg = self.recurse_build(source)?;
396                 self.nodes.push(Node::Cast(abstract_const::CastKind::Use, arg, node.ty))
397             }
398             &ExprKind::Cast { source } => {
399                 let arg = self.recurse_build(source)?;
400                 self.nodes.push(Node::Cast(abstract_const::CastKind::As, arg, node.ty))
401             }
402
403             // FIXME(generic_const_exprs): We may want to support these.
404             ExprKind::AddressOf { .. }
405             | ExprKind::Borrow { .. }
406             | ExprKind::Deref { .. } => self.maybe_supported_error(
407                 node.span,
408                 "dereferencing is not supported in generic constants",
409             )?,
410             ExprKind::Repeat { .. } | ExprKind::Array { .. } =>  self.maybe_supported_error(
411                 node.span,
412                 "array construction is not supported in generic constants",
413             )?,
414             ExprKind::Block { .. } => self.maybe_supported_error(
415                 node.span,
416                 "blocks are not supported in generic constant",
417             )?,
418             ExprKind::NeverToAny { .. } => self.maybe_supported_error(
419                 node.span,
420                 "converting nevers to any is not supported in generic constant",
421             )?,
422             ExprKind::Tuple { .. } => self.maybe_supported_error(
423                 node.span,
424                 "tuple construction is not supported in generic constants",
425             )?,
426             ExprKind::Index { .. } => self.maybe_supported_error(
427                 node.span,
428                 "indexing is not supported in generic constant",
429             )?,
430             ExprKind::Field { .. } => self.maybe_supported_error(
431                 node.span,
432                 "field access is not supported in generic constant",
433             )?,
434             ExprKind::ConstBlock { .. } => self.maybe_supported_error(
435                 node.span,
436                 "const blocks are not supported in generic constant",
437             )?,
438             ExprKind::Adt(_) => self.maybe_supported_error(
439                 node.span,
440                 "struct/enum construction is not supported in generic constants",
441             )?,
442             // dont know if this is correct
443             ExprKind::Pointer { .. } =>
444                 self.error(node.span, "pointer casts are not allowed in generic constants")?,
445             ExprKind::Yield { .. } =>
446                 self.error(node.span, "generator control flow is not allowed in generic constants")?,
447             ExprKind::Continue { .. } | ExprKind::Break { .. } | ExprKind::Loop { .. } => self
448                 .error(
449                     node.span,
450                     "loops and loop control flow are not supported in generic constants",
451                 )?,
452             ExprKind::Box { .. } =>
453                 self.error(node.span, "allocations are not allowed in generic constants")?,
454
455             ExprKind::Unary { .. } => unreachable!(),
456             // we handle valid unary/binary ops above
457             ExprKind::Binary { .. } =>
458                 self.error(node.span, "unsupported binary operation in generic constants")?,
459             ExprKind::LogicalOp { .. } =>
460                 self.error(node.span, "unsupported operation in generic constants, short-circuiting operations would imply control flow")?,
461             ExprKind::Assign { .. } | ExprKind::AssignOp { .. } => {
462                 self.error(node.span, "assignment is not supported in generic constants")?
463             }
464             ExprKind::Closure { .. } | ExprKind::Return { .. } => self.error(
465                 node.span,
466                 "closures and function keywords are not supported in generic constants",
467             )?,
468             // let expressions imply control flow
469             ExprKind::Match { .. } | ExprKind::If { .. } | ExprKind::Let { .. } =>
470                 self.error(node.span, "control flow is not supported in generic constants")?,
471             ExprKind::LlvmInlineAsm { .. } | ExprKind::InlineAsm { .. } => {
472                 self.error(node.span, "assembly is not supported in generic constants")?
473             }
474
475             // we dont permit let stmts so `VarRef` and `UpvarRef` cant happen
476             ExprKind::VarRef { .. }
477             | ExprKind::UpvarRef { .. }
478             | ExprKind::StaticRef { .. }
479             | ExprKind::ThreadLocalRef(_) => {
480                 self.error(node.span, "unsupported operation in generic constant")?
481             }
482         })
483     }
484 }
485
486 /// Builds an abstract const, do not use this directly, but use `AbstractConst::new` instead.
487 pub(super) fn thir_abstract_const<'tcx>(
488     tcx: TyCtxt<'tcx>,
489     def: ty::WithOptConstParam<LocalDefId>,
490 ) -> Result<Option<&'tcx [thir::abstract_const::Node<'tcx>]>, ErrorReported> {
491     if tcx.features().generic_const_exprs {
492         match tcx.def_kind(def.did) {
493             // FIXME(generic_const_exprs): We currently only do this for anonymous constants,
494             // meaning that we do not look into associated constants. I(@lcnr) am not yet sure whether
495             // we want to look into them or treat them as opaque projections.
496             //
497             // Right now we do neither of that and simply always fail to unify them.
498             DefKind::AnonConst | DefKind::InlineConst => (),
499             _ => return Ok(None),
500         }
501
502         let body = tcx.thir_body(def);
503         if body.0.borrow().exprs.is_empty() {
504             // type error in constant, there is no thir
505             return Err(ErrorReported);
506         }
507
508         AbstractConstBuilder::new(tcx, (&*body.0.borrow(), body.1))?
509             .map(AbstractConstBuilder::build)
510             .transpose()
511     } else {
512         Ok(None)
513     }
514 }
515
516 pub(super) fn try_unify_abstract_consts<'tcx>(
517     tcx: TyCtxt<'tcx>,
518     (a, b): (ty::Unevaluated<'tcx, ()>, ty::Unevaluated<'tcx, ()>),
519 ) -> bool {
520     (|| {
521         if let Some(a) = AbstractConst::new(tcx, a)? {
522             if let Some(b) = AbstractConst::new(tcx, b)? {
523                 return Ok(try_unify(tcx, a, b));
524             }
525         }
526
527         Ok(false)
528     })()
529     .unwrap_or_else(|ErrorReported| true)
530     // FIXME(generic_const_exprs): We should instead have this
531     // method return the resulting `ty::Const` and return `ConstKind::Error`
532     // on `ErrorReported`.
533 }
534
535 pub fn walk_abstract_const<'tcx, R, F>(
536     tcx: TyCtxt<'tcx>,
537     ct: AbstractConst<'tcx>,
538     mut f: F,
539 ) -> ControlFlow<R>
540 where
541     F: FnMut(AbstractConst<'tcx>) -> ControlFlow<R>,
542 {
543     fn recurse<'tcx, R>(
544         tcx: TyCtxt<'tcx>,
545         ct: AbstractConst<'tcx>,
546         f: &mut dyn FnMut(AbstractConst<'tcx>) -> ControlFlow<R>,
547     ) -> ControlFlow<R> {
548         f(ct)?;
549         let root = ct.root(tcx);
550         match root {
551             Node::Leaf(_) => ControlFlow::CONTINUE,
552             Node::Binop(_, l, r) => {
553                 recurse(tcx, ct.subtree(l), f)?;
554                 recurse(tcx, ct.subtree(r), f)
555             }
556             Node::UnaryOp(_, v) => recurse(tcx, ct.subtree(v), f),
557             Node::FunctionCall(func, args) => {
558                 recurse(tcx, ct.subtree(func), f)?;
559                 args.iter().try_for_each(|&arg| recurse(tcx, ct.subtree(arg), f))
560             }
561             Node::Cast(_, operand, _) => recurse(tcx, ct.subtree(operand), f),
562         }
563     }
564
565     recurse(tcx, ct, &mut f)
566 }
567
568 /// Tries to unify two abstract constants using structural equality.
569 pub(super) fn try_unify<'tcx>(
570     tcx: TyCtxt<'tcx>,
571     mut a: AbstractConst<'tcx>,
572     mut b: AbstractConst<'tcx>,
573 ) -> bool {
574     // We substitute generics repeatedly to allow AbstractConsts to unify where a
575     // ConstKind::Unevalated could be turned into an AbstractConst that would unify e.g.
576     // Param(N) should unify with Param(T), substs: [Unevaluated("T2", [Unevaluated("T3", [Param(N)])])]
577     while let Node::Leaf(a_ct) = a.root(tcx) {
578         match AbstractConst::from_const(tcx, a_ct) {
579             Ok(Some(a_act)) => a = a_act,
580             Ok(None) => break,
581             Err(_) => return true,
582         }
583     }
584     while let Node::Leaf(b_ct) = b.root(tcx) {
585         match AbstractConst::from_const(tcx, b_ct) {
586             Ok(Some(b_act)) => b = b_act,
587             Ok(None) => break,
588             Err(_) => return true,
589         }
590     }
591
592     match (a.root(tcx), b.root(tcx)) {
593         (Node::Leaf(a_ct), Node::Leaf(b_ct)) => {
594             if a_ct.ty != b_ct.ty {
595                 return false;
596             }
597
598             match (a_ct.val, b_ct.val) {
599                 // We can just unify errors with everything to reduce the amount of
600                 // emitted errors here.
601                 (ty::ConstKind::Error(_), _) | (_, ty::ConstKind::Error(_)) => true,
602                 (ty::ConstKind::Param(a_param), ty::ConstKind::Param(b_param)) => {
603                     a_param == b_param
604                 }
605                 (ty::ConstKind::Value(a_val), ty::ConstKind::Value(b_val)) => a_val == b_val,
606                 // If we have `fn a<const N: usize>() -> [u8; N + 1]` and `fn b<const M: usize>() -> [u8; 1 + M]`
607                 // we do not want to use `assert_eq!(a(), b())` to infer that `N` and `M` have to be `1`. This
608                 // means that we only allow inference variables if they are equal.
609                 (ty::ConstKind::Infer(a_val), ty::ConstKind::Infer(b_val)) => a_val == b_val,
610                 // We expand generic anonymous constants at the start of this function, so this
611                 // branch should only be taking when dealing with associated constants, at
612                 // which point directly comparing them seems like the desired behavior.
613                 //
614                 // FIXME(generic_const_exprs): This isn't actually the case.
615                 // We also take this branch for concrete anonymous constants and
616                 // expand generic anonymous constants with concrete substs.
617                 (ty::ConstKind::Unevaluated(a_uv), ty::ConstKind::Unevaluated(b_uv)) => {
618                     a_uv == b_uv
619                 }
620                 // FIXME(generic_const_exprs): We may want to either actually try
621                 // to evaluate `a_ct` and `b_ct` if they are are fully concrete or something like
622                 // this, for now we just return false here.
623                 _ => false,
624             }
625         }
626         (Node::Binop(a_op, al, ar), Node::Binop(b_op, bl, br)) if a_op == b_op => {
627             try_unify(tcx, a.subtree(al), b.subtree(bl))
628                 && try_unify(tcx, a.subtree(ar), b.subtree(br))
629         }
630         (Node::UnaryOp(a_op, av), Node::UnaryOp(b_op, bv)) if a_op == b_op => {
631             try_unify(tcx, a.subtree(av), b.subtree(bv))
632         }
633         (Node::FunctionCall(a_f, a_args), Node::FunctionCall(b_f, b_args))
634             if a_args.len() == b_args.len() =>
635         {
636             try_unify(tcx, a.subtree(a_f), b.subtree(b_f))
637                 && iter::zip(a_args, b_args)
638                     .all(|(&an, &bn)| try_unify(tcx, a.subtree(an), b.subtree(bn)))
639         }
640         (Node::Cast(a_kind, a_operand, a_ty), Node::Cast(b_kind, b_operand, b_ty))
641             if (a_ty == b_ty) && (a_kind == b_kind) =>
642         {
643             try_unify(tcx, a.subtree(a_operand), b.subtree(b_operand))
644         }
645         // use this over `_ => false` to make adding variants to `Node` less error prone
646         (Node::Cast(..), _)
647         | (Node::FunctionCall(..), _)
648         | (Node::UnaryOp(..), _)
649         | (Node::Binop(..), _)
650         | (Node::Leaf(..), _) => false,
651     }
652 }