]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_trait_selection/src/traits/const_evaluatable.rs
attempt to re-add `ty::Unevaluated` visitor and friends
[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.has_param_types_or_consts() {
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.has_param_types_or_consts() {
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.has_param_types_or_consts() {
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 }))
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         }
275
276         use thir::visit;
277         impl<'a, 'tcx: 'a> visit::Visitor<'a, 'tcx> for IsThirPolymorphic<'a, 'tcx> {
278             fn thir(&self) -> &'a thir::Thir<'tcx> {
279                 &self.thir
280             }
281
282             fn visit_expr(&mut self, expr: &thir::Expr<'tcx>) {
283                 self.is_poly |= expr.ty.has_param_types_or_consts();
284                 if !self.is_poly {
285                     visit::walk_expr(self, expr)
286                 }
287             }
288
289             fn visit_pat(&mut self, pat: &thir::Pat<'tcx>) {
290                 self.is_poly |= pat.ty.has_param_types_or_consts();
291                 if !self.is_poly {
292                     visit::walk_pat(self, pat);
293                 }
294             }
295
296             fn visit_const(&mut self, ct: &'tcx ty::Const<'tcx>) {
297                 self.is_poly |= ct.has_param_types_or_consts();
298             }
299         }
300
301         let mut is_poly_vis = IsThirPolymorphic { is_poly: false, thir: body };
302         visit::walk_expr(&mut is_poly_vis, &body[body_id]);
303         debug!("AbstractConstBuilder: is_poly={}", is_poly_vis.is_poly);
304         if !is_poly_vis.is_poly {
305             return Ok(None);
306         }
307
308         Ok(Some(builder))
309     }
310
311     /// We do not allow all binary operations in abstract consts, so filter disallowed ones.
312     fn check_binop(op: mir::BinOp) -> bool {
313         use mir::BinOp::*;
314         match op {
315             Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Shl | Shr | Eq | Lt | Le
316             | Ne | Ge | Gt => true,
317             Offset => false,
318         }
319     }
320
321     /// While we currently allow all unary operations, we still want to explicitly guard against
322     /// future changes here.
323     fn check_unop(op: mir::UnOp) -> bool {
324         use mir::UnOp::*;
325         match op {
326             Not | Neg => true,
327         }
328     }
329
330     /// Builds the abstract const by walking the thir and bailing out when
331     /// encountering an unspported operation.
332     fn build(mut self) -> Result<&'tcx [Node<'tcx>], ErrorReported> {
333         debug!("Abstractconstbuilder::build: body={:?}", &*self.body);
334         self.recurse_build(self.body_id)?;
335
336         for n in self.nodes.iter() {
337             if let Node::Leaf(ty::Const { val: ty::ConstKind::Unevaluated(ct), ty: _ }) = n {
338                 // `AbstractConst`s should not contain any promoteds as they require references which
339                 // are not allowed.
340                 assert_eq!(ct.promoted, None);
341             }
342         }
343
344         Ok(self.tcx.arena.alloc_from_iter(self.nodes.into_iter()))
345     }
346
347     fn recurse_build(&mut self, node: thir::ExprId) -> Result<NodeId, ErrorReported> {
348         use thir::ExprKind;
349         let node = &self.body.exprs[node];
350         debug!("recurse_build: node={:?}", node);
351         Ok(match &node.kind {
352             // I dont know if handling of these 3 is correct
353             &ExprKind::Scope { value, .. } => self.recurse_build(value)?,
354             &ExprKind::PlaceTypeAscription { source, .. }
355             | &ExprKind::ValueTypeAscription { source, .. } => self.recurse_build(source)?,
356
357             // subtle: associated consts are literals this arm handles
358             // `<T as Trait>::ASSOC` as well as `12`
359             &ExprKind::Literal { literal, .. } => self.nodes.push(Node::Leaf(literal)),
360
361             ExprKind::Call { fun, args, .. } => {
362                 let fun = self.recurse_build(*fun)?;
363
364                 let mut new_args = Vec::<NodeId>::with_capacity(args.len());
365                 for &id in args.iter() {
366                     new_args.push(self.recurse_build(id)?);
367                 }
368                 let new_args = self.tcx.arena.alloc_slice(&new_args);
369                 self.nodes.push(Node::FunctionCall(fun, new_args))
370             }
371             &ExprKind::Binary { op, lhs, rhs } if Self::check_binop(op) => {
372                 let lhs = self.recurse_build(lhs)?;
373                 let rhs = self.recurse_build(rhs)?;
374                 self.nodes.push(Node::Binop(op, lhs, rhs))
375             }
376             &ExprKind::Unary { op, arg } if Self::check_unop(op) => {
377                 let arg = self.recurse_build(arg)?;
378                 self.nodes.push(Node::UnaryOp(op, arg))
379             }
380             // This is necessary so that the following compiles:
381             //
382             // ```
383             // fn foo<const N: usize>(a: [(); N + 1]) {
384             //     bar::<{ N + 1 }>();
385             // }
386             // ```
387             ExprKind::Block { body: thir::Block { stmts: box [], expr: Some(e), .. } } => {
388                 self.recurse_build(*e)?
389             }
390             // `ExprKind::Use` happens when a `hir::ExprKind::Cast` is a
391             // "coercion cast" i.e. using a coercion or is a no-op.
392             // This is important so that `N as usize as usize` doesnt unify with `N as usize`. (untested)
393             &ExprKind::Use { source } => {
394                 let arg = self.recurse_build(source)?;
395                 self.nodes.push(Node::Cast(abstract_const::CastKind::Use, arg, node.ty))
396             }
397             &ExprKind::Cast { source } => {
398                 let arg = self.recurse_build(source)?;
399                 self.nodes.push(Node::Cast(abstract_const::CastKind::As, arg, node.ty))
400             }
401             ExprKind::Borrow{ arg, ..} => {
402                 let arg_node = &self.body.exprs[*arg];
403
404                 // Skip reborrows for now until we allow Deref/Borrow/AddressOf
405                 // expressions.
406                 // FIXME(generic_const_exprs): Verify/explain why this is sound
407                 if let ExprKind::Deref {arg} = arg_node.kind {
408                     self.recurse_build(arg)?
409                 } else {
410                     self.maybe_supported_error(
411                         node.span,
412                         "borrowing is not supported in generic constants",
413                     )?
414                 }
415             }
416             // FIXME(generic_const_exprs): We may want to support these.
417             ExprKind::AddressOf { .. } | ExprKind::Deref {..}=> self.maybe_supported_error(
418                 node.span,
419                 "dereferencing or taking the address is not supported in generic constants",
420             )?,
421             ExprKind::Repeat { .. } | ExprKind::Array { .. } =>  self.maybe_supported_error(
422                 node.span,
423                 "array construction is not supported in generic constants",
424             )?,
425             ExprKind::Block { .. } => self.maybe_supported_error(
426                 node.span,
427                 "blocks are not supported in generic constant",
428             )?,
429             ExprKind::NeverToAny { .. } => self.maybe_supported_error(
430                 node.span,
431                 "converting nevers to any is not supported in generic constant",
432             )?,
433             ExprKind::Tuple { .. } => self.maybe_supported_error(
434                 node.span,
435                 "tuple construction is not supported in generic constants",
436             )?,
437             ExprKind::Index { .. } => self.maybe_supported_error(
438                 node.span,
439                 "indexing is not supported in generic constant",
440             )?,
441             ExprKind::Field { .. } => self.maybe_supported_error(
442                 node.span,
443                 "field access is not supported in generic constant",
444             )?,
445             ExprKind::ConstBlock { .. } => self.maybe_supported_error(
446                 node.span,
447                 "const blocks are not supported in generic constant",
448             )?,
449             ExprKind::Adt(_) => self.maybe_supported_error(
450                 node.span,
451                 "struct/enum construction is not supported in generic constants",
452             )?,
453             // dont know if this is correct
454             ExprKind::Pointer { .. } =>
455                 self.error(node.span, "pointer casts are not allowed in generic constants")?,
456             ExprKind::Yield { .. } =>
457                 self.error(node.span, "generator control flow is not allowed in generic constants")?,
458             ExprKind::Continue { .. } | ExprKind::Break { .. } | ExprKind::Loop { .. } => self
459                 .error(
460                     node.span,
461                     "loops and loop control flow are not supported in generic constants",
462                 )?,
463             ExprKind::Box { .. } =>
464                 self.error(node.span, "allocations are not allowed in generic constants")?,
465
466             ExprKind::Unary { .. } => unreachable!(),
467             // we handle valid unary/binary ops above
468             ExprKind::Binary { .. } =>
469                 self.error(node.span, "unsupported binary operation in generic constants")?,
470             ExprKind::LogicalOp { .. } =>
471                 self.error(node.span, "unsupported operation in generic constants, short-circuiting operations would imply control flow")?,
472             ExprKind::Assign { .. } | ExprKind::AssignOp { .. } => {
473                 self.error(node.span, "assignment is not supported in generic constants")?
474             }
475             ExprKind::Closure { .. } | ExprKind::Return { .. } => self.error(
476                 node.span,
477                 "closures and function keywords are not supported in generic constants",
478             )?,
479             // let expressions imply control flow
480             ExprKind::Match { .. } | ExprKind::If { .. } | ExprKind::Let { .. } =>
481                 self.error(node.span, "control flow is not supported in generic constants")?,
482             ExprKind::LlvmInlineAsm { .. } | ExprKind::InlineAsm { .. } => {
483                 self.error(node.span, "assembly is not supported in generic constants")?
484             }
485
486             // we dont permit let stmts so `VarRef` and `UpvarRef` cant happen
487             ExprKind::VarRef { .. }
488             | ExprKind::UpvarRef { .. }
489             | ExprKind::StaticRef { .. }
490             | ExprKind::ThreadLocalRef(_) => {
491                 self.error(node.span, "unsupported operation in generic constant")?
492             }
493         })
494     }
495 }
496
497 /// Builds an abstract const, do not use this directly, but use `AbstractConst::new` instead.
498 pub(super) fn thir_abstract_const<'tcx>(
499     tcx: TyCtxt<'tcx>,
500     def: ty::WithOptConstParam<LocalDefId>,
501 ) -> Result<Option<&'tcx [thir::abstract_const::Node<'tcx>]>, ErrorReported> {
502     if tcx.features().generic_const_exprs {
503         match tcx.def_kind(def.did) {
504             // FIXME(generic_const_exprs): We currently only do this for anonymous constants,
505             // meaning that we do not look into associated constants. I(@lcnr) am not yet sure whether
506             // we want to look into them or treat them as opaque projections.
507             //
508             // Right now we do neither of that and simply always fail to unify them.
509             DefKind::AnonConst | DefKind::InlineConst => (),
510             _ => return Ok(None),
511         }
512
513         let body = tcx.thir_body(def);
514         if body.0.borrow().exprs.is_empty() {
515             // type error in constant, there is no thir
516             return Err(ErrorReported);
517         }
518
519         AbstractConstBuilder::new(tcx, (&*body.0.borrow(), body.1))?
520             .map(AbstractConstBuilder::build)
521             .transpose()
522     } else {
523         Ok(None)
524     }
525 }
526
527 pub(super) fn try_unify_abstract_consts<'tcx>(
528     tcx: TyCtxt<'tcx>,
529     (a, b): (ty::Unevaluated<'tcx, ()>, ty::Unevaluated<'tcx, ()>),
530 ) -> bool {
531     (|| {
532         if let Some(a) = AbstractConst::new(tcx, a)? {
533             if let Some(b) = AbstractConst::new(tcx, b)? {
534                 return Ok(try_unify(tcx, a, b));
535             }
536         }
537
538         Ok(false)
539     })()
540     .unwrap_or_else(|ErrorReported| true)
541     // FIXME(generic_const_exprs): We should instead have this
542     // method return the resulting `ty::Const` and return `ConstKind::Error`
543     // on `ErrorReported`.
544 }
545
546 pub fn walk_abstract_const<'tcx, R, F>(
547     tcx: TyCtxt<'tcx>,
548     ct: AbstractConst<'tcx>,
549     mut f: F,
550 ) -> ControlFlow<R>
551 where
552     F: FnMut(AbstractConst<'tcx>) -> ControlFlow<R>,
553 {
554     fn recurse<'tcx, R>(
555         tcx: TyCtxt<'tcx>,
556         ct: AbstractConst<'tcx>,
557         f: &mut dyn FnMut(AbstractConst<'tcx>) -> ControlFlow<R>,
558     ) -> ControlFlow<R> {
559         f(ct)?;
560         let root = ct.root(tcx);
561         match root {
562             Node::Leaf(_) => ControlFlow::CONTINUE,
563             Node::Binop(_, l, r) => {
564                 recurse(tcx, ct.subtree(l), f)?;
565                 recurse(tcx, ct.subtree(r), f)
566             }
567             Node::UnaryOp(_, v) => recurse(tcx, ct.subtree(v), f),
568             Node::FunctionCall(func, args) => {
569                 recurse(tcx, ct.subtree(func), f)?;
570                 args.iter().try_for_each(|&arg| recurse(tcx, ct.subtree(arg), f))
571             }
572             Node::Cast(_, operand, _) => recurse(tcx, ct.subtree(operand), f),
573         }
574     }
575
576     recurse(tcx, ct, &mut f)
577 }
578
579 /// Tries to unify two abstract constants using structural equality.
580 pub(super) fn try_unify<'tcx>(
581     tcx: TyCtxt<'tcx>,
582     mut a: AbstractConst<'tcx>,
583     mut b: AbstractConst<'tcx>,
584 ) -> bool {
585     // We substitute generics repeatedly to allow AbstractConsts to unify where a
586     // ConstKind::Unevalated could be turned into an AbstractConst that would unify e.g.
587     // Param(N) should unify with Param(T), substs: [Unevaluated("T2", [Unevaluated("T3", [Param(N)])])]
588     while let Node::Leaf(a_ct) = a.root(tcx) {
589         match AbstractConst::from_const(tcx, a_ct) {
590             Ok(Some(a_act)) => a = a_act,
591             Ok(None) => break,
592             Err(_) => return true,
593         }
594     }
595     while let Node::Leaf(b_ct) = b.root(tcx) {
596         match AbstractConst::from_const(tcx, b_ct) {
597             Ok(Some(b_act)) => b = b_act,
598             Ok(None) => break,
599             Err(_) => return true,
600         }
601     }
602
603     match (a.root(tcx), b.root(tcx)) {
604         (Node::Leaf(a_ct), Node::Leaf(b_ct)) => {
605             if a_ct.ty != b_ct.ty {
606                 return false;
607             }
608
609             match (a_ct.val, b_ct.val) {
610                 // We can just unify errors with everything to reduce the amount of
611                 // emitted errors here.
612                 (ty::ConstKind::Error(_), _) | (_, ty::ConstKind::Error(_)) => true,
613                 (ty::ConstKind::Param(a_param), ty::ConstKind::Param(b_param)) => {
614                     a_param == b_param
615                 }
616                 (ty::ConstKind::Value(a_val), ty::ConstKind::Value(b_val)) => a_val == b_val,
617                 // If we have `fn a<const N: usize>() -> [u8; N + 1]` and `fn b<const M: usize>() -> [u8; 1 + M]`
618                 // we do not want to use `assert_eq!(a(), b())` to infer that `N` and `M` have to be `1`. This
619                 // means that we only allow inference variables if they are equal.
620                 (ty::ConstKind::Infer(a_val), ty::ConstKind::Infer(b_val)) => a_val == b_val,
621                 // We expand generic anonymous constants at the start of this function, so this
622                 // branch should only be taking when dealing with associated constants, at
623                 // which point directly comparing them seems like the desired behavior.
624                 //
625                 // FIXME(generic_const_exprs): This isn't actually the case.
626                 // We also take this branch for concrete anonymous constants and
627                 // expand generic anonymous constants with concrete substs.
628                 (ty::ConstKind::Unevaluated(a_uv), ty::ConstKind::Unevaluated(b_uv)) => {
629                     a_uv == b_uv
630                 }
631                 // FIXME(generic_const_exprs): We may want to either actually try
632                 // to evaluate `a_ct` and `b_ct` if they are are fully concrete or something like
633                 // this, for now we just return false here.
634                 _ => false,
635             }
636         }
637         (Node::Binop(a_op, al, ar), Node::Binop(b_op, bl, br)) if a_op == b_op => {
638             try_unify(tcx, a.subtree(al), b.subtree(bl))
639                 && try_unify(tcx, a.subtree(ar), b.subtree(br))
640         }
641         (Node::UnaryOp(a_op, av), Node::UnaryOp(b_op, bv)) if a_op == b_op => {
642             try_unify(tcx, a.subtree(av), b.subtree(bv))
643         }
644         (Node::FunctionCall(a_f, a_args), Node::FunctionCall(b_f, b_args))
645             if a_args.len() == b_args.len() =>
646         {
647             try_unify(tcx, a.subtree(a_f), b.subtree(b_f))
648                 && iter::zip(a_args, b_args)
649                     .all(|(&an, &bn)| try_unify(tcx, a.subtree(an), b.subtree(bn)))
650         }
651         (Node::Cast(a_kind, a_operand, a_ty), Node::Cast(b_kind, b_operand, b_ty))
652             if (a_ty == b_ty) && (a_kind == b_kind) =>
653         {
654             try_unify(tcx, a.subtree(a_operand), b.subtree(b_operand))
655         }
656         // use this over `_ => false` to make adding variants to `Node` less error prone
657         (Node::Cast(..), _)
658         | (Node::FunctionCall(..), _)
659         | (Node::UnaryOp(..), _)
660         | (Node::Binop(..), _)
661         | (Node::Leaf(..), _) => false,
662     }
663 }