]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_trait_selection/src/traits/const_evaluatable.rs
Rollup merge of #91065 - wesleywiser:add_incr_test, r=jackh726
[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             ExprKind::Borrow{ arg, ..} => {
403                 let arg_node = &self.body.exprs[*arg];
404
405                 // Skip reborrows for now until we allow Deref/Borrow/AddressOf
406                 // expressions.
407                 // FIXME(generic_const_exprs): Verify/explain why this is sound
408                 if let ExprKind::Deref {arg} = arg_node.kind {
409                     self.recurse_build(arg)?
410                 } else {
411                     self.maybe_supported_error(
412                         node.span,
413                         "borrowing is not supported in generic constants",
414                     )?
415                 }
416             }
417             // FIXME(generic_const_exprs): We may want to support these.
418             ExprKind::AddressOf { .. } | ExprKind::Deref {..}=> self.maybe_supported_error(
419                 node.span,
420                 "dereferencing or taking the address is not supported in generic constants",
421             )?,
422             ExprKind::Repeat { .. } | ExprKind::Array { .. } =>  self.maybe_supported_error(
423                 node.span,
424                 "array construction is not supported in generic constants",
425             )?,
426             ExprKind::Block { .. } => self.maybe_supported_error(
427                 node.span,
428                 "blocks are not supported in generic constant",
429             )?,
430             ExprKind::NeverToAny { .. } => self.maybe_supported_error(
431                 node.span,
432                 "converting nevers to any is not supported in generic constant",
433             )?,
434             ExprKind::Tuple { .. } => self.maybe_supported_error(
435                 node.span,
436                 "tuple construction is not supported in generic constants",
437             )?,
438             ExprKind::Index { .. } => self.maybe_supported_error(
439                 node.span,
440                 "indexing is not supported in generic constant",
441             )?,
442             ExprKind::Field { .. } => self.maybe_supported_error(
443                 node.span,
444                 "field access is not supported in generic constant",
445             )?,
446             ExprKind::ConstBlock { .. } => self.maybe_supported_error(
447                 node.span,
448                 "const blocks are not supported in generic constant",
449             )?,
450             ExprKind::Adt(_) => self.maybe_supported_error(
451                 node.span,
452                 "struct/enum construction is not supported in generic constants",
453             )?,
454             // dont know if this is correct
455             ExprKind::Pointer { .. } =>
456                 self.error(node.span, "pointer casts are not allowed in generic constants")?,
457             ExprKind::Yield { .. } =>
458                 self.error(node.span, "generator control flow is not allowed in generic constants")?,
459             ExprKind::Continue { .. } | ExprKind::Break { .. } | ExprKind::Loop { .. } => self
460                 .error(
461                     node.span,
462                     "loops and loop control flow are not supported in generic constants",
463                 )?,
464             ExprKind::Box { .. } =>
465                 self.error(node.span, "allocations are not allowed in generic constants")?,
466
467             ExprKind::Unary { .. } => unreachable!(),
468             // we handle valid unary/binary ops above
469             ExprKind::Binary { .. } =>
470                 self.error(node.span, "unsupported binary operation in generic constants")?,
471             ExprKind::LogicalOp { .. } =>
472                 self.error(node.span, "unsupported operation in generic constants, short-circuiting operations would imply control flow")?,
473             ExprKind::Assign { .. } | ExprKind::AssignOp { .. } => {
474                 self.error(node.span, "assignment is not supported in generic constants")?
475             }
476             ExprKind::Closure { .. } | ExprKind::Return { .. } => self.error(
477                 node.span,
478                 "closures and function keywords are not supported in generic constants",
479             )?,
480             // let expressions imply control flow
481             ExprKind::Match { .. } | ExprKind::If { .. } | ExprKind::Let { .. } =>
482                 self.error(node.span, "control flow is not supported in generic constants")?,
483             ExprKind::LlvmInlineAsm { .. } | ExprKind::InlineAsm { .. } => {
484                 self.error(node.span, "assembly is not supported in generic constants")?
485             }
486
487             // we dont permit let stmts so `VarRef` and `UpvarRef` cant happen
488             ExprKind::VarRef { .. }
489             | ExprKind::UpvarRef { .. }
490             | ExprKind::StaticRef { .. }
491             | ExprKind::ThreadLocalRef(_) => {
492                 self.error(node.span, "unsupported operation in generic constant")?
493             }
494         })
495     }
496 }
497
498 /// Builds an abstract const, do not use this directly, but use `AbstractConst::new` instead.
499 pub(super) fn thir_abstract_const<'tcx>(
500     tcx: TyCtxt<'tcx>,
501     def: ty::WithOptConstParam<LocalDefId>,
502 ) -> Result<Option<&'tcx [thir::abstract_const::Node<'tcx>]>, ErrorReported> {
503     if tcx.features().generic_const_exprs {
504         match tcx.def_kind(def.did) {
505             // FIXME(generic_const_exprs): We currently only do this for anonymous constants,
506             // meaning that we do not look into associated constants. I(@lcnr) am not yet sure whether
507             // we want to look into them or treat them as opaque projections.
508             //
509             // Right now we do neither of that and simply always fail to unify them.
510             DefKind::AnonConst | DefKind::InlineConst => (),
511             _ => return Ok(None),
512         }
513
514         let body = tcx.thir_body(def);
515         if body.0.borrow().exprs.is_empty() {
516             // type error in constant, there is no thir
517             return Err(ErrorReported);
518         }
519
520         AbstractConstBuilder::new(tcx, (&*body.0.borrow(), body.1))?
521             .map(AbstractConstBuilder::build)
522             .transpose()
523     } else {
524         Ok(None)
525     }
526 }
527
528 pub(super) fn try_unify_abstract_consts<'tcx>(
529     tcx: TyCtxt<'tcx>,
530     (a, b): (ty::Unevaluated<'tcx, ()>, ty::Unevaluated<'tcx, ()>),
531 ) -> bool {
532     (|| {
533         if let Some(a) = AbstractConst::new(tcx, a)? {
534             if let Some(b) = AbstractConst::new(tcx, b)? {
535                 return Ok(try_unify(tcx, a, b));
536             }
537         }
538
539         Ok(false)
540     })()
541     .unwrap_or_else(|ErrorReported| true)
542     // FIXME(generic_const_exprs): We should instead have this
543     // method return the resulting `ty::Const` and return `ConstKind::Error`
544     // on `ErrorReported`.
545 }
546
547 pub fn walk_abstract_const<'tcx, R, F>(
548     tcx: TyCtxt<'tcx>,
549     ct: AbstractConst<'tcx>,
550     mut f: F,
551 ) -> ControlFlow<R>
552 where
553     F: FnMut(AbstractConst<'tcx>) -> ControlFlow<R>,
554 {
555     fn recurse<'tcx, R>(
556         tcx: TyCtxt<'tcx>,
557         ct: AbstractConst<'tcx>,
558         f: &mut dyn FnMut(AbstractConst<'tcx>) -> ControlFlow<R>,
559     ) -> ControlFlow<R> {
560         f(ct)?;
561         let root = ct.root(tcx);
562         match root {
563             Node::Leaf(_) => ControlFlow::CONTINUE,
564             Node::Binop(_, l, r) => {
565                 recurse(tcx, ct.subtree(l), f)?;
566                 recurse(tcx, ct.subtree(r), f)
567             }
568             Node::UnaryOp(_, v) => recurse(tcx, ct.subtree(v), f),
569             Node::FunctionCall(func, args) => {
570                 recurse(tcx, ct.subtree(func), f)?;
571                 args.iter().try_for_each(|&arg| recurse(tcx, ct.subtree(arg), f))
572             }
573             Node::Cast(_, operand, _) => recurse(tcx, ct.subtree(operand), f),
574         }
575     }
576
577     recurse(tcx, ct, &mut f)
578 }
579
580 /// Tries to unify two abstract constants using structural equality.
581 pub(super) fn try_unify<'tcx>(
582     tcx: TyCtxt<'tcx>,
583     mut a: AbstractConst<'tcx>,
584     mut b: AbstractConst<'tcx>,
585 ) -> bool {
586     // We substitute generics repeatedly to allow AbstractConsts to unify where a
587     // ConstKind::Unevalated could be turned into an AbstractConst that would unify e.g.
588     // Param(N) should unify with Param(T), substs: [Unevaluated("T2", [Unevaluated("T3", [Param(N)])])]
589     while let Node::Leaf(a_ct) = a.root(tcx) {
590         match AbstractConst::from_const(tcx, a_ct) {
591             Ok(Some(a_act)) => a = a_act,
592             Ok(None) => break,
593             Err(_) => return true,
594         }
595     }
596     while let Node::Leaf(b_ct) = b.root(tcx) {
597         match AbstractConst::from_const(tcx, b_ct) {
598             Ok(Some(b_act)) => b = b_act,
599             Ok(None) => break,
600             Err(_) => return true,
601         }
602     }
603
604     match (a.root(tcx), b.root(tcx)) {
605         (Node::Leaf(a_ct), Node::Leaf(b_ct)) => {
606             if a_ct.ty != b_ct.ty {
607                 return false;
608             }
609
610             match (a_ct.val, b_ct.val) {
611                 // We can just unify errors with everything to reduce the amount of
612                 // emitted errors here.
613                 (ty::ConstKind::Error(_), _) | (_, ty::ConstKind::Error(_)) => true,
614                 (ty::ConstKind::Param(a_param), ty::ConstKind::Param(b_param)) => {
615                     a_param == b_param
616                 }
617                 (ty::ConstKind::Value(a_val), ty::ConstKind::Value(b_val)) => a_val == b_val,
618                 // If we have `fn a<const N: usize>() -> [u8; N + 1]` and `fn b<const M: usize>() -> [u8; 1 + M]`
619                 // we do not want to use `assert_eq!(a(), b())` to infer that `N` and `M` have to be `1`. This
620                 // means that we only allow inference variables if they are equal.
621                 (ty::ConstKind::Infer(a_val), ty::ConstKind::Infer(b_val)) => a_val == b_val,
622                 // We expand generic anonymous constants at the start of this function, so this
623                 // branch should only be taking when dealing with associated constants, at
624                 // which point directly comparing them seems like the desired behavior.
625                 //
626                 // FIXME(generic_const_exprs): This isn't actually the case.
627                 // We also take this branch for concrete anonymous constants and
628                 // expand generic anonymous constants with concrete substs.
629                 (ty::ConstKind::Unevaluated(a_uv), ty::ConstKind::Unevaluated(b_uv)) => {
630                     a_uv == b_uv
631                 }
632                 // FIXME(generic_const_exprs): We may want to either actually try
633                 // to evaluate `a_ct` and `b_ct` if they are are fully concrete or something like
634                 // this, for now we just return false here.
635                 _ => false,
636             }
637         }
638         (Node::Binop(a_op, al, ar), Node::Binop(b_op, bl, br)) if a_op == b_op => {
639             try_unify(tcx, a.subtree(al), b.subtree(bl))
640                 && try_unify(tcx, a.subtree(ar), b.subtree(br))
641         }
642         (Node::UnaryOp(a_op, av), Node::UnaryOp(b_op, bv)) if a_op == b_op => {
643             try_unify(tcx, a.subtree(av), b.subtree(bv))
644         }
645         (Node::FunctionCall(a_f, a_args), Node::FunctionCall(b_f, b_args))
646             if a_args.len() == b_args.len() =>
647         {
648             try_unify(tcx, a.subtree(a_f), b.subtree(b_f))
649                 && iter::zip(a_args, b_args)
650                     .all(|(&an, &bn)| try_unify(tcx, a.subtree(an), b.subtree(bn)))
651         }
652         (Node::Cast(a_kind, a_operand, a_ty), Node::Cast(b_kind, b_operand, b_ty))
653             if (a_ty == b_ty) && (a_kind == b_kind) =>
654         {
655             try_unify(tcx, a.subtree(a_operand), b.subtree(b_operand))
656         }
657         // use this over `_ => false` to make adding variants to `Node` less error prone
658         (Node::Cast(..), _)
659         | (Node::FunctionCall(..), _)
660         | (Node::UnaryOp(..), _)
661         | (Node::Binop(..), _)
662         | (Node::Leaf(..), _) => false,
663     }
664 }