]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_trait_selection/src/traits/const_evaluatable.rs
Rollup merge of #81664 - bjorn3:no_codegen_hir, r=lcnr
[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 //! `mir_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::bit_set::BitSet;
14 use rustc_index::vec::IndexVec;
15 use rustc_infer::infer::InferCtxt;
16 use rustc_middle::mir::abstract_const::{Node, NodeId};
17 use rustc_middle::mir::interpret::ErrorHandled;
18 use rustc_middle::mir::{self, Rvalue, StatementKind, TerminatorKind};
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::{DefId, LocalDefId};
23 use rustc_span::Span;
24
25 use std::cmp;
26 use std::ops::ControlFlow;
27
28 /// Check if a given constant can be evaluated.
29 pub fn is_const_evaluatable<'cx, 'tcx>(
30     infcx: &InferCtxt<'cx, 'tcx>,
31     def: ty::WithOptConstParam<DefId>,
32     substs: SubstsRef<'tcx>,
33     param_env: ty::ParamEnv<'tcx>,
34     span: Span,
35 ) -> Result<(), ErrorHandled> {
36     debug!("is_const_evaluatable({:?}, {:?})", def, substs);
37     if infcx.tcx.features().const_evaluatable_checked {
38         let tcx = infcx.tcx;
39         match AbstractConst::new(tcx, def, substs)? {
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(b_def, b_substs) => {
45                             if b_def == def && b_substs == substs {
46                                 debug!("is_const_evaluatable: caller_bound ~~> ok");
47                                 return Ok(());
48                             }
49
50                             if let Some(b_ct) = AbstractConst::new(tcx, b_def, b_substs)? {
51                                 // Try to unify with each subtree in the AbstractConst to allow for
52                                 // `N + 1` being const evaluatable even if theres only a `ConstEvaluatable`
53                                 // predicate for `(N + 1) * 2`
54                                 let result =
55                                     walk_abstract_const(tcx, b_ct, |b_ct| {
56                                         match try_unify(tcx, ct, b_ct) {
57                                             true => ControlFlow::BREAK,
58                                             false => ControlFlow::CONTINUE,
59                                         }
60                                     });
61
62                                 if let ControlFlow::Break(()) = result {
63                                     debug!("is_const_evaluatable: abstract_const ~~> ok");
64                                     return Ok(());
65                                 }
66                             }
67                         }
68                         _ => {} // don't care
69                     }
70                 }
71
72                 // We were unable to unify the abstract constant with
73                 // a constant found in the caller bounds, there are
74                 // now three possible cases here.
75                 //
76                 // - The substs are concrete enough that we can simply
77                 //   try and evaluate the given constant.
78                 // - The abstract const still references an inference
79                 //   variable, in this case we return `TooGeneric`.
80                 // - The abstract const references a generic parameter,
81                 //   this means that we emit an error here.
82                 #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
83                 enum FailureKind {
84                     MentionsInfer,
85                     MentionsParam,
86                     Concrete,
87                 }
88                 let mut failure_kind = FailureKind::Concrete;
89                 walk_abstract_const::<!, _>(tcx, ct, |node| match node.root() {
90                     Node::Leaf(leaf) => {
91                         let leaf = leaf.subst(tcx, ct.substs);
92                         if leaf.has_infer_types_or_consts() {
93                             failure_kind = FailureKind::MentionsInfer;
94                         } else if leaf.has_param_types_or_consts() {
95                             failure_kind = cmp::min(failure_kind, FailureKind::MentionsParam);
96                         }
97
98                         ControlFlow::CONTINUE
99                     }
100                     Node::Binop(_, _, _) | Node::UnaryOp(_, _) | Node::FunctionCall(_, _) => {
101                         ControlFlow::CONTINUE
102                     }
103                 });
104
105                 match failure_kind {
106                     FailureKind::MentionsInfer => {
107                         return Err(ErrorHandled::TooGeneric);
108                     }
109                     FailureKind::MentionsParam => {
110                         // FIXME(const_evaluatable_checked): Better error message.
111                         let mut err =
112                             infcx.tcx.sess.struct_span_err(span, "unconstrained generic constant");
113                         let const_span = tcx.def_span(def.did);
114                         // FIXME(const_evaluatable_checked): Update this suggestion once
115                         // explicit const evaluatable bounds are implemented.
116                         if let Ok(snippet) = infcx.tcx.sess.source_map().span_to_snippet(const_span)
117                         {
118                             err.span_help(
119                                 tcx.def_span(def.did),
120                                 &format!("try adding a `where` bound using this expression: where [u8; {}]: Sized", snippet),
121                             );
122                         } else {
123                             err.span_help(
124                                 const_span,
125                                 "consider adding a `where` bound for this expression",
126                             );
127                         }
128                         err.emit();
129                         return Err(ErrorHandled::Reported(ErrorReported));
130                     }
131                     FailureKind::Concrete => {
132                         // Dealt with below by the same code which handles this
133                         // without the feature gate.
134                     }
135                 }
136             }
137             None => {
138                 // If we are dealing with a concrete constant, we can
139                 // reuse the old code path and try to evaluate
140                 // the constant.
141             }
142         }
143     }
144
145     let future_compat_lint = || {
146         if let Some(local_def_id) = def.did.as_local() {
147             infcx.tcx.struct_span_lint_hir(
148                 lint::builtin::CONST_EVALUATABLE_UNCHECKED,
149                 infcx.tcx.hir().local_def_id_to_hir_id(local_def_id),
150                 span,
151                 |err| {
152                     err.build("cannot use constants which depend on generic parameters in types")
153                         .emit();
154                 },
155             );
156         }
157     };
158
159     // FIXME: We should only try to evaluate a given constant here if it is fully concrete
160     // as we don't want to allow things like `[u8; std::mem::size_of::<*mut T>()]`.
161     //
162     // We previously did not check this, so we only emit a future compat warning if
163     // const evaluation succeeds and the given constant is still polymorphic for now
164     // and hopefully soon change this to an error.
165     //
166     // See #74595 for more details about this.
167     let concrete = infcx.const_eval_resolve(param_env, def, substs, None, Some(span));
168
169     if concrete.is_ok() && substs.has_param_types_or_consts() {
170         match infcx.tcx.def_kind(def.did) {
171             DefKind::AnonConst => {
172                 let mir_body = infcx.tcx.mir_for_ctfe_opt_const_arg(def);
173
174                 if mir_body.is_polymorphic {
175                     future_compat_lint();
176                 }
177             }
178             _ => future_compat_lint(),
179         }
180     }
181
182     debug!(?concrete, "is_const_evaluatable");
183     match concrete {
184         Err(ErrorHandled::TooGeneric) if !substs.has_infer_types_or_consts() => {
185             // FIXME(const_evaluatable_checked): We really should move
186             // emitting this error message to fulfill instead. For
187             // now this is easier.
188             //
189             // This is not a problem without `const_evaluatable_checked` as
190             // all `ConstEvaluatable` predicates have to be fulfilled for compilation
191             // to succeed.
192             //
193             // @lcnr: We already emit an error for things like
194             // `fn test<const N: usize>() -> [0 - N]` eagerly here,
195             // so until we fix this I don't really care.
196
197             let mut err = infcx
198                 .tcx
199                 .sess
200                 .struct_span_err(span, "constant expression depends on a generic parameter");
201             // FIXME(const_generics): we should suggest to the user how they can resolve this
202             // issue. However, this is currently not actually possible
203             // (see https://github.com/rust-lang/rust/issues/66962#issuecomment-575907083).
204             //
205             // Note that with `feature(const_evaluatable_checked)` this case should not
206             // be reachable.
207             err.note("this may fail depending on what value the parameter takes");
208             err.emit();
209             Err(ErrorHandled::Reported(ErrorReported))
210         }
211         c => c.map(drop),
212     }
213 }
214
215 /// A tree representing an anonymous constant.
216 ///
217 /// This is only able to represent a subset of `MIR`,
218 /// and should not leak any information about desugarings.
219 #[derive(Debug, Clone, Copy)]
220 pub struct AbstractConst<'tcx> {
221     // FIXME: Consider adding something like `IndexSlice`
222     // and use this here.
223     pub inner: &'tcx [Node<'tcx>],
224     pub substs: SubstsRef<'tcx>,
225 }
226
227 impl AbstractConst<'tcx> {
228     pub fn new(
229         tcx: TyCtxt<'tcx>,
230         def: ty::WithOptConstParam<DefId>,
231         substs: SubstsRef<'tcx>,
232     ) -> Result<Option<AbstractConst<'tcx>>, ErrorReported> {
233         let inner = tcx.mir_abstract_const_opt_const_arg(def)?;
234         debug!("AbstractConst::new({:?}) = {:?}", def, inner);
235         Ok(inner.map(|inner| AbstractConst { inner, substs }))
236     }
237
238     pub fn from_const(
239         tcx: TyCtxt<'tcx>,
240         ct: &ty::Const<'tcx>,
241     ) -> Result<Option<AbstractConst<'tcx>>, ErrorReported> {
242         match ct.val {
243             ty::ConstKind::Unevaluated(def, substs, None) => AbstractConst::new(tcx, def, substs),
244             ty::ConstKind::Error(_) => Err(ErrorReported),
245             _ => Ok(None),
246         }
247     }
248
249     #[inline]
250     pub fn subtree(self, node: NodeId) -> AbstractConst<'tcx> {
251         AbstractConst { inner: &self.inner[..=node.index()], substs: self.substs }
252     }
253
254     #[inline]
255     pub fn root(self) -> Node<'tcx> {
256         self.inner.last().copied().unwrap()
257     }
258 }
259
260 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
261 struct WorkNode<'tcx> {
262     node: Node<'tcx>,
263     span: Span,
264     used: bool,
265 }
266
267 struct AbstractConstBuilder<'a, 'tcx> {
268     tcx: TyCtxt<'tcx>,
269     body: &'a mir::Body<'tcx>,
270     /// The current WIP node tree.
271     ///
272     /// We require all nodes to be used in the final abstract const,
273     /// so we store this here. Note that we also consider nodes as used
274     /// if they are mentioned in an assert, so some used nodes are never
275     /// actually reachable by walking the [`AbstractConst`].
276     nodes: IndexVec<NodeId, WorkNode<'tcx>>,
277     locals: IndexVec<mir::Local, NodeId>,
278     /// We only allow field accesses if they access
279     /// the result of a checked operation.
280     checked_op_locals: BitSet<mir::Local>,
281 }
282
283 impl<'a, 'tcx> AbstractConstBuilder<'a, 'tcx> {
284     fn error(&mut self, span: Option<Span>, msg: &str) -> Result<!, ErrorReported> {
285         self.tcx
286             .sess
287             .struct_span_err(self.body.span, "overly complex generic constant")
288             .span_label(span.unwrap_or(self.body.span), msg)
289             .help("consider moving this anonymous constant into a `const` function")
290             .emit();
291
292         Err(ErrorReported)
293     }
294
295     fn new(
296         tcx: TyCtxt<'tcx>,
297         body: &'a mir::Body<'tcx>,
298     ) -> Result<Option<AbstractConstBuilder<'a, 'tcx>>, ErrorReported> {
299         let mut builder = AbstractConstBuilder {
300             tcx,
301             body,
302             nodes: IndexVec::new(),
303             locals: IndexVec::from_elem(NodeId::MAX, &body.local_decls),
304             checked_op_locals: BitSet::new_empty(body.local_decls.len()),
305         };
306
307         // We don't have to look at concrete constants, as we
308         // can just evaluate them.
309         if !body.is_polymorphic {
310             return Ok(None);
311         }
312
313         // We only allow consts without control flow, so
314         // we check for cycles here which simplifies the
315         // rest of this implementation.
316         if body.is_cfg_cyclic() {
317             builder.error(None, "cyclic anonymous constants are forbidden")?;
318         }
319
320         Ok(Some(builder))
321     }
322
323     fn add_node(&mut self, node: Node<'tcx>, span: Span) -> NodeId {
324         // Mark used nodes.
325         match node {
326             Node::Leaf(_) => (),
327             Node::Binop(_, lhs, rhs) => {
328                 self.nodes[lhs].used = true;
329                 self.nodes[rhs].used = true;
330             }
331             Node::UnaryOp(_, input) => {
332                 self.nodes[input].used = true;
333             }
334             Node::FunctionCall(func, nodes) => {
335                 self.nodes[func].used = true;
336                 nodes.iter().for_each(|&n| self.nodes[n].used = true);
337             }
338         }
339
340         // Nodes start as unused.
341         self.nodes.push(WorkNode { node, span, used: false })
342     }
343
344     fn place_to_local(
345         &mut self,
346         span: Span,
347         p: &mir::Place<'tcx>,
348     ) -> Result<mir::Local, ErrorReported> {
349         const ZERO_FIELD: mir::Field = mir::Field::from_usize(0);
350         // Do not allow any projections.
351         //
352         // One exception are field accesses on the result of checked operations,
353         // which are required to support things like `1 + 2`.
354         if let Some(p) = p.as_local() {
355             debug_assert!(!self.checked_op_locals.contains(p));
356             Ok(p)
357         } else if let &[mir::ProjectionElem::Field(ZERO_FIELD, _)] = p.projection.as_ref() {
358             // Only allow field accesses if the given local
359             // contains the result of a checked operation.
360             if self.checked_op_locals.contains(p.local) {
361                 Ok(p.local)
362             } else {
363                 self.error(Some(span), "unsupported projection")?;
364             }
365         } else {
366             self.error(Some(span), "unsupported projection")?;
367         }
368     }
369
370     fn operand_to_node(
371         &mut self,
372         span: Span,
373         op: &mir::Operand<'tcx>,
374     ) -> Result<NodeId, ErrorReported> {
375         debug!("operand_to_node: op={:?}", op);
376         match op {
377             mir::Operand::Copy(p) | mir::Operand::Move(p) => {
378                 let local = self.place_to_local(span, p)?;
379                 Ok(self.locals[local])
380             }
381             mir::Operand::Constant(ct) => Ok(self.add_node(Node::Leaf(ct.literal), span)),
382         }
383     }
384
385     /// We do not allow all binary operations in abstract consts, so filter disallowed ones.
386     fn check_binop(op: mir::BinOp) -> bool {
387         use mir::BinOp::*;
388         match op {
389             Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Shl | Shr | Eq | Lt | Le
390             | Ne | Ge | Gt => true,
391             Offset => false,
392         }
393     }
394
395     /// While we currently allow all unary operations, we still want to explicitly guard against
396     /// future changes here.
397     fn check_unop(op: mir::UnOp) -> bool {
398         use mir::UnOp::*;
399         match op {
400             Not | Neg => true,
401         }
402     }
403
404     fn build_statement(&mut self, stmt: &mir::Statement<'tcx>) -> Result<(), ErrorReported> {
405         debug!("AbstractConstBuilder: stmt={:?}", stmt);
406         let span = stmt.source_info.span;
407         match stmt.kind {
408             StatementKind::Assign(box (ref place, ref rvalue)) => {
409                 let local = self.place_to_local(span, place)?;
410                 match *rvalue {
411                     Rvalue::Use(ref operand) => {
412                         self.locals[local] = self.operand_to_node(span, operand)?;
413                         Ok(())
414                     }
415                     Rvalue::BinaryOp(op, ref lhs, ref rhs) if Self::check_binop(op) => {
416                         let lhs = self.operand_to_node(span, lhs)?;
417                         let rhs = self.operand_to_node(span, rhs)?;
418                         self.locals[local] = self.add_node(Node::Binop(op, lhs, rhs), span);
419                         if op.is_checkable() {
420                             bug!("unexpected unchecked checkable binary operation");
421                         } else {
422                             Ok(())
423                         }
424                     }
425                     Rvalue::CheckedBinaryOp(op, ref lhs, ref rhs) if Self::check_binop(op) => {
426                         let lhs = self.operand_to_node(span, lhs)?;
427                         let rhs = self.operand_to_node(span, rhs)?;
428                         self.locals[local] = self.add_node(Node::Binop(op, lhs, rhs), span);
429                         self.checked_op_locals.insert(local);
430                         Ok(())
431                     }
432                     Rvalue::UnaryOp(op, ref operand) if Self::check_unop(op) => {
433                         let operand = self.operand_to_node(span, operand)?;
434                         self.locals[local] = self.add_node(Node::UnaryOp(op, operand), span);
435                         Ok(())
436                     }
437                     _ => self.error(Some(span), "unsupported rvalue")?,
438                 }
439             }
440             // These are not actually relevant for us here, so we can ignore them.
441             StatementKind::StorageLive(_) | StatementKind::StorageDead(_) => Ok(()),
442             _ => self.error(Some(stmt.source_info.span), "unsupported statement")?,
443         }
444     }
445
446     /// Possible return values:
447     ///
448     /// - `None`: unsupported terminator, stop building
449     /// - `Some(None)`: supported terminator, finish building
450     /// - `Some(Some(block))`: support terminator, build `block` next
451     fn build_terminator(
452         &mut self,
453         terminator: &mir::Terminator<'tcx>,
454     ) -> Result<Option<mir::BasicBlock>, ErrorReported> {
455         debug!("AbstractConstBuilder: terminator={:?}", terminator);
456         match terminator.kind {
457             TerminatorKind::Goto { target } => Ok(Some(target)),
458             TerminatorKind::Return => Ok(None),
459             TerminatorKind::Call {
460                 ref func,
461                 ref args,
462                 destination: Some((ref place, target)),
463                 // We do not care about `cleanup` here. Any branch which
464                 // uses `cleanup` will fail const-eval and they therefore
465                 // do not matter when checking for const evaluatability.
466                 //
467                 // Do note that even if `panic::catch_unwind` is made const,
468                 // we still do not have to care about this, as we do not look
469                 // into functions.
470                 cleanup: _,
471                 // Do not allow overloaded operators for now,
472                 // we probably do want to allow this in the future.
473                 //
474                 // This is currently fairly irrelevant as it requires `const Trait`s.
475                 from_hir_call: true,
476                 fn_span,
477             } => {
478                 let local = self.place_to_local(fn_span, place)?;
479                 let func = self.operand_to_node(fn_span, func)?;
480                 let args = self.tcx.arena.alloc_from_iter(
481                     args.iter()
482                         .map(|arg| self.operand_to_node(terminator.source_info.span, arg))
483                         .collect::<Result<Vec<NodeId>, _>>()?,
484                 );
485                 self.locals[local] = self.add_node(Node::FunctionCall(func, args), fn_span);
486                 Ok(Some(target))
487             }
488             TerminatorKind::Assert { ref cond, expected: false, target, .. } => {
489                 let p = match cond {
490                     mir::Operand::Copy(p) | mir::Operand::Move(p) => p,
491                     mir::Operand::Constant(_) => bug!("unexpected assert"),
492                 };
493
494                 const ONE_FIELD: mir::Field = mir::Field::from_usize(1);
495                 debug!("proj: {:?}", p.projection);
496                 if let Some(p) = p.as_local() {
497                     debug_assert!(!self.checked_op_locals.contains(p));
498                     // Mark locals directly used in asserts as used.
499                     //
500                     // This is needed because division does not use `CheckedBinop` but instead
501                     // adds an explicit assert for `divisor != 0`.
502                     self.nodes[self.locals[p]].used = true;
503                     return Ok(Some(target));
504                 } else if let &[mir::ProjectionElem::Field(ONE_FIELD, _)] = p.projection.as_ref() {
505                     // Only allow asserts checking the result of a checked operation.
506                     if self.checked_op_locals.contains(p.local) {
507                         return Ok(Some(target));
508                     }
509                 }
510
511                 self.error(Some(terminator.source_info.span), "unsupported assertion")?;
512             }
513             _ => self.error(Some(terminator.source_info.span), "unsupported terminator")?,
514         }
515     }
516
517     /// Builds the abstract const by walking the mir from start to finish
518     /// and bailing out when encountering an unsupported operation.
519     fn build(mut self) -> Result<&'tcx [Node<'tcx>], ErrorReported> {
520         let mut block = &self.body.basic_blocks()[mir::START_BLOCK];
521         // We checked for a cyclic cfg above, so this should terminate.
522         loop {
523             debug!("AbstractConstBuilder: block={:?}", block);
524             for stmt in block.statements.iter() {
525                 self.build_statement(stmt)?;
526             }
527
528             if let Some(next) = self.build_terminator(block.terminator())? {
529                 block = &self.body.basic_blocks()[next];
530             } else {
531                 assert_eq!(self.locals[mir::RETURN_PLACE], self.nodes.last().unwrap());
532                 // `AbstractConst`s should not contain any promoteds as they require references which
533                 // are not allowed.
534                 assert!(!self.nodes.iter().any(|n| matches!(
535                     n.node,
536                     Node::Leaf(ty::Const { val: ty::ConstKind::Unevaluated(_, _, Some(_)), ty: _ })
537                 )));
538
539                 self.nodes[self.locals[mir::RETURN_PLACE]].used = true;
540                 if let Some(&unused) = self.nodes.iter().find(|n| !n.used) {
541                     self.error(Some(unused.span), "dead code")?;
542                 }
543
544                 return Ok(self.tcx.arena.alloc_from_iter(self.nodes.into_iter().map(|n| n.node)));
545             }
546         }
547     }
548 }
549
550 /// Builds an abstract const, do not use this directly, but use `AbstractConst::new` instead.
551 pub(super) fn mir_abstract_const<'tcx>(
552     tcx: TyCtxt<'tcx>,
553     def: ty::WithOptConstParam<LocalDefId>,
554 ) -> Result<Option<&'tcx [mir::abstract_const::Node<'tcx>]>, ErrorReported> {
555     if tcx.features().const_evaluatable_checked {
556         match tcx.def_kind(def.did) {
557             // FIXME(const_evaluatable_checked): We currently only do this for anonymous constants,
558             // meaning that we do not look into associated constants. I(@lcnr) am not yet sure whether
559             // we want to look into them or treat them as opaque projections.
560             //
561             // Right now we do neither of that and simply always fail to unify them.
562             DefKind::AnonConst => (),
563             _ => return Ok(None),
564         }
565         let body = tcx.mir_const(def).borrow();
566         AbstractConstBuilder::new(tcx, &body)?.map(AbstractConstBuilder::build).transpose()
567     } else {
568         Ok(None)
569     }
570 }
571
572 pub(super) fn try_unify_abstract_consts<'tcx>(
573     tcx: TyCtxt<'tcx>,
574     ((a, a_substs), (b, b_substs)): (
575         (ty::WithOptConstParam<DefId>, SubstsRef<'tcx>),
576         (ty::WithOptConstParam<DefId>, SubstsRef<'tcx>),
577     ),
578 ) -> bool {
579     (|| {
580         if let Some(a) = AbstractConst::new(tcx, a, a_substs)? {
581             if let Some(b) = AbstractConst::new(tcx, b, b_substs)? {
582                 return Ok(try_unify(tcx, a, b));
583             }
584         }
585
586         Ok(false)
587     })()
588     .unwrap_or_else(|ErrorReported| true)
589     // FIXME(const_evaluatable_checked): We should instead have this
590     // method return the resulting `ty::Const` and return `ConstKind::Error`
591     // on `ErrorReported`.
592 }
593
594 pub fn walk_abstract_const<'tcx, R, F>(
595     tcx: TyCtxt<'tcx>,
596     ct: AbstractConst<'tcx>,
597     mut f: F,
598 ) -> ControlFlow<R>
599 where
600     F: FnMut(AbstractConst<'tcx>) -> ControlFlow<R>,
601 {
602     fn recurse<'tcx, R>(
603         tcx: TyCtxt<'tcx>,
604         ct: AbstractConst<'tcx>,
605         f: &mut dyn FnMut(AbstractConst<'tcx>) -> ControlFlow<R>,
606     ) -> ControlFlow<R> {
607         f(ct)?;
608         let root = ct.root();
609         match root {
610             Node::Leaf(_) => ControlFlow::CONTINUE,
611             Node::Binop(_, l, r) => {
612                 recurse(tcx, ct.subtree(l), f)?;
613                 recurse(tcx, ct.subtree(r), f)
614             }
615             Node::UnaryOp(_, v) => recurse(tcx, ct.subtree(v), f),
616             Node::FunctionCall(func, args) => {
617                 recurse(tcx, ct.subtree(func), f)?;
618                 args.iter().try_for_each(|&arg| recurse(tcx, ct.subtree(arg), f))
619             }
620         }
621     }
622
623     recurse(tcx, ct, &mut f)
624 }
625
626 /// Tries to unify two abstract constants using structural equality.
627 pub(super) fn try_unify<'tcx>(
628     tcx: TyCtxt<'tcx>,
629     mut a: AbstractConst<'tcx>,
630     mut b: AbstractConst<'tcx>,
631 ) -> bool {
632     // We substitute generics repeatedly to allow AbstractConsts to unify where a
633     // ConstKind::Unevalated could be turned into an AbstractConst that would unify e.g.
634     // Param(N) should unify with Param(T), substs: [Unevaluated("T2", [Unevaluated("T3", [Param(N)])])]
635     while let Node::Leaf(a_ct) = a.root() {
636         let a_ct = a_ct.subst(tcx, a.substs);
637         match AbstractConst::from_const(tcx, a_ct) {
638             Ok(Some(a_act)) => a = a_act,
639             Ok(None) => break,
640             Err(_) => return true,
641         }
642     }
643     while let Node::Leaf(b_ct) = b.root() {
644         let b_ct = b_ct.subst(tcx, b.substs);
645         match AbstractConst::from_const(tcx, b_ct) {
646             Ok(Some(b_act)) => b = b_act,
647             Ok(None) => break,
648             Err(_) => return true,
649         }
650     }
651
652     match (a.root(), b.root()) {
653         (Node::Leaf(a_ct), Node::Leaf(b_ct)) => {
654             let a_ct = a_ct.subst(tcx, a.substs);
655             let b_ct = b_ct.subst(tcx, b.substs);
656             if a_ct.ty != b_ct.ty {
657                 return false;
658             }
659
660             match (a_ct.val, b_ct.val) {
661                 // We can just unify errors with everything to reduce the amount of
662                 // emitted errors here.
663                 (ty::ConstKind::Error(_), _) | (_, ty::ConstKind::Error(_)) => true,
664                 (ty::ConstKind::Param(a_param), ty::ConstKind::Param(b_param)) => {
665                     a_param == b_param
666                 }
667                 (ty::ConstKind::Value(a_val), ty::ConstKind::Value(b_val)) => a_val == b_val,
668                 // If we have `fn a<const N: usize>() -> [u8; N + 1]` and `fn b<const M: usize>() -> [u8; 1 + M]`
669                 // we do not want to use `assert_eq!(a(), b())` to infer that `N` and `M` have to be `1`. This
670                 // means that we only allow inference variables if they are equal.
671                 (ty::ConstKind::Infer(a_val), ty::ConstKind::Infer(b_val)) => a_val == b_val,
672                 (
673                     ty::ConstKind::Unevaluated(a_def, a_substs, None),
674                     ty::ConstKind::Unevaluated(b_def, b_substs, None),
675                 ) => a_def == b_def && a_substs == b_substs,
676                 // FIXME(const_evaluatable_checked): We may want to either actually try
677                 // to evaluate `a_ct` and `b_ct` if they are are fully concrete or something like
678                 // this, for now we just return false here.
679                 _ => false,
680             }
681         }
682         (Node::Binop(a_op, al, ar), Node::Binop(b_op, bl, br)) if a_op == b_op => {
683             try_unify(tcx, a.subtree(al), b.subtree(bl))
684                 && try_unify(tcx, a.subtree(ar), b.subtree(br))
685         }
686         (Node::UnaryOp(a_op, av), Node::UnaryOp(b_op, bv)) if a_op == b_op => {
687             try_unify(tcx, a.subtree(av), b.subtree(bv))
688         }
689         (Node::FunctionCall(a_f, a_args), Node::FunctionCall(b_f, b_args))
690             if a_args.len() == b_args.len() =>
691         {
692             try_unify(tcx, a.subtree(a_f), b.subtree(b_f))
693                 && a_args
694                     .iter()
695                     .zip(b_args)
696                     .all(|(&an, &bn)| try_unify(tcx, a.subtree(an), b.subtree(bn)))
697         }
698         _ => false,
699     }
700 }