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