]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_trait_selection/src/traits/const_evaluatable.rs
424eff2f6212a6dfcb71b1792781cbae049fd05a
[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::ErrorGuaranteed;
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, LitToConstError, LitToConstInput};
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, DelaySpanBugEmitted, EarlyBinder, 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 #[instrument(skip(infcx), level = "debug")]
31 pub fn is_const_evaluatable<'cx, 'tcx>(
32     infcx: &InferCtxt<'cx, 'tcx>,
33     uv: ty::Unevaluated<'tcx, ()>,
34     param_env: ty::ParamEnv<'tcx>,
35     span: Span,
36 ) -> Result<(), NotConstEvaluatable> {
37     let tcx = infcx.tcx;
38
39     if tcx.features().generic_const_exprs {
40         if let Some(ct) = AbstractConst::new(tcx, uv)? {
41             if satisfied_from_param_env(tcx, ct, param_env)? {
42                 return Ok(());
43             }
44
45             // We were unable to unify the abstract constant with
46             // a constant found in the caller bounds, there are
47             // now three possible cases here.
48             #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
49             enum FailureKind {
50                 /// The abstract const still references an inference
51                 /// variable, in this case we return `TooGeneric`.
52                 MentionsInfer,
53                 /// The abstract const references a generic parameter,
54                 /// this means that we emit an error here.
55                 MentionsParam,
56                 /// The substs are concrete enough that we can simply
57                 /// try and evaluate the given constant.
58                 Concrete,
59             }
60             let mut failure_kind = FailureKind::Concrete;
61             walk_abstract_const::<!, _>(tcx, ct, |node| match node.root(tcx) {
62                 Node::Leaf(leaf) => {
63                     if leaf.has_infer_types_or_consts() {
64                         failure_kind = FailureKind::MentionsInfer;
65                     } else if leaf.has_param_types_or_consts() {
66                         failure_kind = cmp::min(failure_kind, FailureKind::MentionsParam);
67                     }
68
69                     ControlFlow::CONTINUE
70                 }
71                 Node::Cast(_, _, ty) => {
72                     if ty.has_infer_types_or_consts() {
73                         failure_kind = FailureKind::MentionsInfer;
74                     } else if ty.has_param_types_or_consts() {
75                         failure_kind = cmp::min(failure_kind, FailureKind::MentionsParam);
76                     }
77
78                     ControlFlow::CONTINUE
79                 }
80                 Node::Binop(_, _, _) | Node::UnaryOp(_, _) | Node::FunctionCall(_, _) => {
81                     ControlFlow::CONTINUE
82                 }
83             });
84
85             match failure_kind {
86                 FailureKind::MentionsInfer => {
87                     return Err(NotConstEvaluatable::MentionsInfer);
88                 }
89                 FailureKind::MentionsParam => {
90                     return Err(NotConstEvaluatable::MentionsParam);
91                 }
92                 // returned below
93                 FailureKind::Concrete => {}
94             }
95         }
96         let concrete = infcx.const_eval_resolve(param_env, uv.expand(), Some(span));
97         match concrete {
98             Err(ErrorHandled::TooGeneric) => Err(if !uv.has_infer_types_or_consts() {
99                 infcx
100                     .tcx
101                     .sess
102                     .delay_span_bug(span, &format!("unexpected `TooGeneric` for {:?}", uv));
103                 NotConstEvaluatable::MentionsParam
104             } else {
105                 NotConstEvaluatable::MentionsInfer
106             }),
107             Err(ErrorHandled::Linted) => {
108                 let reported = infcx
109                     .tcx
110                     .sess
111                     .delay_span_bug(span, "constant in type had error reported as lint");
112                 Err(NotConstEvaluatable::Error(reported))
113             }
114             Err(ErrorHandled::Reported(e)) => Err(NotConstEvaluatable::Error(e)),
115             Ok(_) => Ok(()),
116         }
117     } else {
118         // FIXME: We should only try to evaluate a given constant here if it is fully concrete
119         // as we don't want to allow things like `[u8; std::mem::size_of::<*mut T>()]`.
120         //
121         // We previously did not check this, so we only emit a future compat warning if
122         // const evaluation succeeds and the given constant is still polymorphic for now
123         // and hopefully soon change this to an error.
124         //
125         // See #74595 for more details about this.
126         let concrete = infcx.const_eval_resolve(param_env, uv.expand(), Some(span));
127
128         match concrete {
129           // If we're evaluating a foreign constant, under a nightly compiler without generic
130           // const exprs, AND it would've passed if that expression had been evaluated with
131           // generic const exprs, then suggest using generic const exprs.
132           Err(_) if tcx.sess.is_nightly_build()
133             && let Ok(Some(ct)) = AbstractConst::new(tcx, uv)
134             && satisfied_from_param_env(tcx, ct, param_env) == Ok(true) => {
135               tcx.sess
136                   .struct_span_fatal(
137                       // Slightly better span than just using `span` alone
138                       if span == rustc_span::DUMMY_SP { tcx.def_span(uv.def.did) } else { span },
139                       "failed to evaluate generic const expression",
140                   )
141                   .note("the crate this constant originates from uses `#![feature(generic_const_exprs)]`")
142                   .span_suggestion_verbose(
143                       rustc_span::DUMMY_SP,
144                       "consider enabling this feature",
145                       "#![feature(generic_const_exprs)]\n",
146                       rustc_errors::Applicability::MaybeIncorrect,
147                   )
148                   .emit()
149             }
150
151             Err(ErrorHandled::TooGeneric) => Err(if uv.has_infer_types_or_consts() {
152                 NotConstEvaluatable::MentionsInfer
153                 } else {
154                 NotConstEvaluatable::MentionsParam
155             }),
156             Err(ErrorHandled::Linted) => {
157                 let reported =
158                     infcx.tcx.sess.delay_span_bug(span, "constant in type had error reported as lint");
159                 Err(NotConstEvaluatable::Error(reported))
160             }
161             Err(ErrorHandled::Reported(e)) => Err(NotConstEvaluatable::Error(e)),
162             Ok(_) => {
163               if uv.substs.has_param_types_or_consts() {
164                   assert!(matches!(infcx.tcx.def_kind(uv.def.did), DefKind::AnonConst));
165                   let mir_body = infcx.tcx.mir_for_ctfe_opt_const_arg(uv.def);
166
167                   if mir_body.is_polymorphic {
168                       let Some(local_def_id) = uv.def.did.as_local() else { return Ok(()) };
169                       tcx.struct_span_lint_hir(
170                           lint::builtin::CONST_EVALUATABLE_UNCHECKED,
171                           tcx.hir().local_def_id_to_hir_id(local_def_id),
172                           span,
173                           |err| {
174                               err.build("cannot use constants which depend on generic parameters in types").emit();
175                         })
176                   }
177               }
178
179               Ok(())
180             },
181         }
182     }
183 }
184
185 #[instrument(skip(tcx), level = "debug")]
186 fn satisfied_from_param_env<'tcx>(
187     tcx: TyCtxt<'tcx>,
188     ct: AbstractConst<'tcx>,
189     param_env: ty::ParamEnv<'tcx>,
190 ) -> Result<bool, NotConstEvaluatable> {
191     for pred in param_env.caller_bounds() {
192         match pred.kind().skip_binder() {
193             ty::PredicateKind::ConstEvaluatable(uv) => {
194                 if let Some(b_ct) = AbstractConst::new(tcx, uv)? {
195                     let const_unify_ctxt = ConstUnifyCtxt { tcx, param_env };
196
197                     // Try to unify with each subtree in the AbstractConst to allow for
198                     // `N + 1` being const evaluatable even if theres only a `ConstEvaluatable`
199                     // predicate for `(N + 1) * 2`
200                     let result = walk_abstract_const(tcx, b_ct, |b_ct| {
201                         match const_unify_ctxt.try_unify(ct, b_ct) {
202                             true => ControlFlow::BREAK,
203                             false => ControlFlow::CONTINUE,
204                         }
205                     });
206
207                     if let ControlFlow::Break(()) = result {
208                         debug!("is_const_evaluatable: abstract_const ~~> ok");
209                         return Ok(true);
210                     }
211                 }
212             }
213             _ => {} // don't care
214         }
215     }
216
217     Ok(false)
218 }
219
220 /// A tree representing an anonymous constant.
221 ///
222 /// This is only able to represent a subset of `MIR`,
223 /// and should not leak any information about desugarings.
224 #[derive(Debug, Clone, Copy)]
225 pub struct AbstractConst<'tcx> {
226     // FIXME: Consider adding something like `IndexSlice`
227     // and use this here.
228     inner: &'tcx [Node<'tcx>],
229     substs: SubstsRef<'tcx>,
230 }
231
232 impl<'tcx> AbstractConst<'tcx> {
233     pub fn new(
234         tcx: TyCtxt<'tcx>,
235         uv: ty::Unevaluated<'tcx, ()>,
236     ) -> Result<Option<AbstractConst<'tcx>>, ErrorGuaranteed> {
237         let inner = tcx.thir_abstract_const_opt_const_arg(uv.def)?;
238         debug!("AbstractConst::new({:?}) = {:?}", uv, inner);
239         Ok(inner.map(|inner| AbstractConst { inner, substs: tcx.erase_regions(uv.substs) }))
240     }
241
242     pub fn from_const(
243         tcx: TyCtxt<'tcx>,
244         ct: ty::Const<'tcx>,
245     ) -> Result<Option<AbstractConst<'tcx>>, ErrorGuaranteed> {
246         match ct.kind() {
247             ty::ConstKind::Unevaluated(uv) => AbstractConst::new(tcx, uv.shrink()),
248             ty::ConstKind::Error(DelaySpanBugEmitted { reported, .. }) => Err(reported),
249             _ => Ok(None),
250         }
251     }
252
253     #[inline]
254     pub fn subtree(self, node: NodeId) -> AbstractConst<'tcx> {
255         AbstractConst { inner: &self.inner[..=node.index()], substs: self.substs }
256     }
257
258     #[inline]
259     pub fn root(self, tcx: TyCtxt<'tcx>) -> Node<'tcx> {
260         let node = self.inner.last().copied().unwrap();
261         match node {
262             Node::Leaf(leaf) => Node::Leaf(EarlyBinder(leaf).subst(tcx, self.substs)),
263             Node::Cast(kind, operand, ty) => {
264                 Node::Cast(kind, operand, EarlyBinder(ty).subst(tcx, self.substs))
265             }
266             // Don't perform substitution on the following as they can't directly contain generic params
267             Node::Binop(_, _, _) | Node::UnaryOp(_, _) | Node::FunctionCall(_, _) => node,
268         }
269     }
270 }
271
272 struct AbstractConstBuilder<'a, 'tcx> {
273     tcx: TyCtxt<'tcx>,
274     body_id: thir::ExprId,
275     body: &'a thir::Thir<'tcx>,
276     /// The current WIP node tree.
277     nodes: IndexVec<NodeId, Node<'tcx>>,
278 }
279
280 impl<'a, 'tcx> AbstractConstBuilder<'a, 'tcx> {
281     fn root_span(&self) -> Span {
282         self.body.exprs[self.body_id].span
283     }
284
285     fn error(&mut self, span: Span, msg: &str) -> Result<!, ErrorGuaranteed> {
286         let reported = self
287             .tcx
288             .sess
289             .struct_span_err(self.root_span(), "overly complex generic constant")
290             .span_label(span, msg)
291             .help("consider moving this anonymous constant into a `const` function")
292             .emit();
293
294         Err(reported)
295     }
296     fn maybe_supported_error(&mut self, span: Span, msg: &str) -> Result<!, ErrorGuaranteed> {
297         let reported = self
298             .tcx
299             .sess
300             .struct_span_err(self.root_span(), "overly complex generic constant")
301             .span_label(span, msg)
302             .help("consider moving this anonymous constant into a `const` function")
303             .note("this operation may be supported in the future")
304             .emit();
305
306         Err(reported)
307     }
308
309     #[instrument(skip(tcx, body, body_id), level = "debug")]
310     fn new(
311         tcx: TyCtxt<'tcx>,
312         (body, body_id): (&'a thir::Thir<'tcx>, thir::ExprId),
313     ) -> Result<Option<AbstractConstBuilder<'a, 'tcx>>, ErrorGuaranteed> {
314         let builder = AbstractConstBuilder { tcx, body_id, body, nodes: IndexVec::new() };
315
316         struct IsThirPolymorphic<'a, 'tcx> {
317             is_poly: bool,
318             thir: &'a thir::Thir<'tcx>,
319         }
320
321         use crate::rustc_middle::thir::visit::Visitor;
322         use thir::visit;
323
324         impl<'a, 'tcx> IsThirPolymorphic<'a, 'tcx> {
325             fn expr_is_poly(&mut self, expr: &thir::Expr<'tcx>) -> bool {
326                 if expr.ty.has_param_types_or_consts() {
327                     return true;
328                 }
329
330                 match expr.kind {
331                     thir::ExprKind::NamedConst { substs, .. } => substs.has_param_types_or_consts(),
332                     thir::ExprKind::ConstParam { .. } => true,
333                     thir::ExprKind::Repeat { value, count } => {
334                         self.visit_expr(&self.thir()[value]);
335                         count.has_param_types_or_consts()
336                     }
337                     _ => false,
338                 }
339             }
340
341             fn pat_is_poly(&mut self, pat: &thir::Pat<'tcx>) -> bool {
342                 if pat.ty.has_param_types_or_consts() {
343                     return true;
344                 }
345
346                 match pat.kind.as_ref() {
347                     thir::PatKind::Constant { value } => value.has_param_types_or_consts(),
348                     thir::PatKind::Range(thir::PatRange { lo, hi, .. }) => {
349                         lo.has_param_types_or_consts() || hi.has_param_types_or_consts()
350                     }
351                     _ => false,
352                 }
353             }
354         }
355
356         impl<'a, 'tcx> visit::Visitor<'a, 'tcx> for IsThirPolymorphic<'a, 'tcx> {
357             fn thir(&self) -> &'a thir::Thir<'tcx> {
358                 &self.thir
359             }
360
361             #[instrument(skip(self), level = "debug")]
362             fn visit_expr(&mut self, expr: &thir::Expr<'tcx>) {
363                 self.is_poly |= self.expr_is_poly(expr);
364                 if !self.is_poly {
365                     visit::walk_expr(self, expr)
366                 }
367             }
368
369             #[instrument(skip(self), level = "debug")]
370             fn visit_pat(&mut self, pat: &thir::Pat<'tcx>) {
371                 self.is_poly |= self.pat_is_poly(pat);
372                 if !self.is_poly {
373                     visit::walk_pat(self, pat);
374                 }
375             }
376         }
377
378         let mut is_poly_vis = IsThirPolymorphic { is_poly: false, thir: body };
379         visit::walk_expr(&mut is_poly_vis, &body[body_id]);
380         debug!("AbstractConstBuilder: is_poly={}", is_poly_vis.is_poly);
381         if !is_poly_vis.is_poly {
382             return Ok(None);
383         }
384
385         Ok(Some(builder))
386     }
387
388     /// We do not allow all binary operations in abstract consts, so filter disallowed ones.
389     fn check_binop(op: mir::BinOp) -> bool {
390         use mir::BinOp::*;
391         match op {
392             Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Shl | Shr | Eq | Lt | Le
393             | Ne | Ge | Gt => true,
394             Offset => false,
395         }
396     }
397
398     /// While we currently allow all unary operations, we still want to explicitly guard against
399     /// future changes here.
400     fn check_unop(op: mir::UnOp) -> bool {
401         use mir::UnOp::*;
402         match op {
403             Not | Neg => true,
404         }
405     }
406
407     /// Builds the abstract const by walking the thir and bailing out when
408     /// encountering an unsupported operation.
409     fn build(mut self) -> Result<&'tcx [Node<'tcx>], ErrorGuaranteed> {
410         debug!("Abstractconstbuilder::build: body={:?}", &*self.body);
411         self.recurse_build(self.body_id)?;
412
413         for n in self.nodes.iter() {
414             if let Node::Leaf(ct) = n {
415                 if let ty::ConstKind::Unevaluated(ct) = ct.kind() {
416                     // `AbstractConst`s should not contain any promoteds as they require references which
417                     // are not allowed.
418                     assert_eq!(ct.promoted, None);
419                     assert_eq!(ct, self.tcx.erase_regions(ct));
420                 }
421             }
422         }
423
424         Ok(self.tcx.arena.alloc_from_iter(self.nodes.into_iter()))
425     }
426
427     fn recurse_build(&mut self, node: thir::ExprId) -> Result<NodeId, ErrorGuaranteed> {
428         use thir::ExprKind;
429         let node = &self.body.exprs[node];
430         Ok(match &node.kind {
431             // I dont know if handling of these 3 is correct
432             &ExprKind::Scope { value, .. } => self.recurse_build(value)?,
433             &ExprKind::PlaceTypeAscription { source, .. }
434             | &ExprKind::ValueTypeAscription { source, .. } => self.recurse_build(source)?,
435             &ExprKind::Literal { lit, neg} => {
436                 let sp = node.span;
437                 let constant =
438                     match self.tcx.at(sp).lit_to_const(LitToConstInput { lit: &lit.node, ty: node.ty, neg }) {
439                         Ok(c) => c,
440                         Err(LitToConstError::Reported) => {
441                             self.tcx.const_error(node.ty)
442                         }
443                         Err(LitToConstError::TypeError) => {
444                             bug!("encountered type error in lit_to_const")
445                         }
446                     };
447
448                 self.nodes.push(Node::Leaf(constant))
449             }
450             &ExprKind::NonHirLiteral { lit , user_ty: _} => {
451                 let val = ty::ValTree::from_scalar_int(lit);
452                 self.nodes.push(Node::Leaf(ty::Const::from_value(self.tcx, val, node.ty)))
453             }
454             &ExprKind::NamedConst { def_id, substs, user_ty: _ } => {
455                 let uneval = ty::Unevaluated::new(ty::WithOptConstParam::unknown(def_id), substs);
456
457                 let constant = self.tcx.mk_const(ty::ConstS {
458                                 kind: ty::ConstKind::Unevaluated(uneval),
459                                 ty: node.ty,
460                             });
461
462                 self.nodes.push(Node::Leaf(constant))
463             }
464
465             ExprKind::ConstParam {param, ..} => {
466                 let const_param = self.tcx.mk_const(ty::ConstS {
467                         kind: ty::ConstKind::Param(*param),
468                         ty: node.ty,
469                     });
470                 self.nodes.push(Node::Leaf(const_param))
471             }
472
473             ExprKind::Call { fun, args, .. } => {
474                 let fun = self.recurse_build(*fun)?;
475
476                 let mut new_args = Vec::<NodeId>::with_capacity(args.len());
477                 for &id in args.iter() {
478                     new_args.push(self.recurse_build(id)?);
479                 }
480                 let new_args = self.tcx.arena.alloc_slice(&new_args);
481                 self.nodes.push(Node::FunctionCall(fun, new_args))
482             }
483             &ExprKind::Binary { op, lhs, rhs } if Self::check_binop(op) => {
484                 let lhs = self.recurse_build(lhs)?;
485                 let rhs = self.recurse_build(rhs)?;
486                 self.nodes.push(Node::Binop(op, lhs, rhs))
487             }
488             &ExprKind::Unary { op, arg } if Self::check_unop(op) => {
489                 let arg = self.recurse_build(arg)?;
490                 self.nodes.push(Node::UnaryOp(op, arg))
491             }
492             // This is necessary so that the following compiles:
493             //
494             // ```
495             // fn foo<const N: usize>(a: [(); N + 1]) {
496             //     bar::<{ N + 1 }>();
497             // }
498             // ```
499             ExprKind::Block { body: thir::Block { stmts: box [], expr: Some(e), .. } } => {
500                 self.recurse_build(*e)?
501             }
502             // `ExprKind::Use` happens when a `hir::ExprKind::Cast` is a
503             // "coercion cast" i.e. using a coercion or is a no-op.
504             // This is important so that `N as usize as usize` doesnt unify with `N as usize`. (untested)
505             &ExprKind::Use { source } => {
506                 let arg = self.recurse_build(source)?;
507                 self.nodes.push(Node::Cast(abstract_const::CastKind::Use, arg, node.ty))
508             }
509             &ExprKind::Cast { source } => {
510                 let arg = self.recurse_build(source)?;
511                 self.nodes.push(Node::Cast(abstract_const::CastKind::As, arg, node.ty))
512             }
513             ExprKind::Borrow{ arg, ..} => {
514                 let arg_node = &self.body.exprs[*arg];
515
516                 // Skip reborrows for now until we allow Deref/Borrow/AddressOf
517                 // expressions.
518                 // FIXME(generic_const_exprs): Verify/explain why this is sound
519                 if let ExprKind::Deref {arg} = arg_node.kind {
520                     self.recurse_build(arg)?
521                 } else {
522                     self.maybe_supported_error(
523                         node.span,
524                         "borrowing is not supported in generic constants",
525                     )?
526                 }
527             }
528             // FIXME(generic_const_exprs): We may want to support these.
529             ExprKind::AddressOf { .. } | ExprKind::Deref {..}=> self.maybe_supported_error(
530                 node.span,
531                 "dereferencing or taking the address is not supported in generic constants",
532             )?,
533             ExprKind::Repeat { .. } | ExprKind::Array { .. } =>  self.maybe_supported_error(
534                 node.span,
535                 "array construction is not supported in generic constants",
536             )?,
537             ExprKind::Block { .. } => self.maybe_supported_error(
538                 node.span,
539                 "blocks are not supported in generic constant",
540             )?,
541             ExprKind::NeverToAny { .. } => self.maybe_supported_error(
542                 node.span,
543                 "converting nevers to any is not supported in generic constant",
544             )?,
545             ExprKind::Tuple { .. } => self.maybe_supported_error(
546                 node.span,
547                 "tuple construction is not supported in generic constants",
548             )?,
549             ExprKind::Index { .. } => self.maybe_supported_error(
550                 node.span,
551                 "indexing is not supported in generic constant",
552             )?,
553             ExprKind::Field { .. } => self.maybe_supported_error(
554                 node.span,
555                 "field access is not supported in generic constant",
556             )?,
557             ExprKind::ConstBlock { .. } => self.maybe_supported_error(
558                 node.span,
559                 "const blocks are not supported in generic constant",
560             )?,
561             ExprKind::Adt(_) => self.maybe_supported_error(
562                 node.span,
563                 "struct/enum construction is not supported in generic constants",
564             )?,
565             // dont know if this is correct
566             ExprKind::Pointer { .. } =>
567                 self.error(node.span, "pointer casts are not allowed in generic constants")?,
568             ExprKind::Yield { .. } =>
569                 self.error(node.span, "generator control flow is not allowed in generic constants")?,
570             ExprKind::Continue { .. } | ExprKind::Break { .. } | ExprKind::Loop { .. } => self
571                 .error(
572                     node.span,
573                     "loops and loop control flow are not supported in generic constants",
574                 )?,
575             ExprKind::Box { .. } =>
576                 self.error(node.span, "allocations are not allowed in generic constants")?,
577
578             ExprKind::Unary { .. } => unreachable!(),
579             // we handle valid unary/binary ops above
580             ExprKind::Binary { .. } =>
581                 self.error(node.span, "unsupported binary operation in generic constants")?,
582             ExprKind::LogicalOp { .. } =>
583                 self.error(node.span, "unsupported operation in generic constants, short-circuiting operations would imply control flow")?,
584             ExprKind::Assign { .. } | ExprKind::AssignOp { .. } => {
585                 self.error(node.span, "assignment is not supported in generic constants")?
586             }
587             ExprKind::Closure { .. } | ExprKind::Return { .. } => self.error(
588                 node.span,
589                 "closures and function keywords are not supported in generic constants",
590             )?,
591             // let expressions imply control flow
592             ExprKind::Match { .. } | ExprKind::If { .. } | ExprKind::Let { .. } =>
593                 self.error(node.span, "control flow is not supported in generic constants")?,
594             ExprKind::InlineAsm { .. } => {
595                 self.error(node.span, "assembly is not supported in generic constants")?
596             }
597
598             // we dont permit let stmts so `VarRef` and `UpvarRef` cant happen
599             ExprKind::VarRef { .. }
600             | ExprKind::UpvarRef { .. }
601             | ExprKind::StaticRef { .. }
602             | ExprKind::ThreadLocalRef(_) => {
603                 self.error(node.span, "unsupported operation in generic constant")?
604             }
605         })
606     }
607 }
608
609 /// Builds an abstract const, do not use this directly, but use `AbstractConst::new` instead.
610 pub(super) fn thir_abstract_const<'tcx>(
611     tcx: TyCtxt<'tcx>,
612     def: ty::WithOptConstParam<LocalDefId>,
613 ) -> Result<Option<&'tcx [thir::abstract_const::Node<'tcx>]>, ErrorGuaranteed> {
614     if tcx.features().generic_const_exprs {
615         match tcx.def_kind(def.did) {
616             // FIXME(generic_const_exprs): We currently only do this for anonymous constants,
617             // meaning that we do not look into associated constants. I(@lcnr) am not yet sure whether
618             // we want to look into them or treat them as opaque projections.
619             //
620             // Right now we do neither of that and simply always fail to unify them.
621             DefKind::AnonConst | DefKind::InlineConst => (),
622             _ => return Ok(None),
623         }
624
625         let body = tcx.thir_body(def)?;
626
627         AbstractConstBuilder::new(tcx, (&*body.0.borrow(), body.1))?
628             .map(AbstractConstBuilder::build)
629             .transpose()
630     } else {
631         Ok(None)
632     }
633 }
634
635 #[instrument(skip(tcx), level = "debug")]
636 pub(super) fn try_unify_abstract_consts<'tcx>(
637     tcx: TyCtxt<'tcx>,
638     (a, b): (ty::Unevaluated<'tcx, ()>, ty::Unevaluated<'tcx, ()>),
639     param_env: ty::ParamEnv<'tcx>,
640 ) -> bool {
641     (|| {
642         if let Some(a) = AbstractConst::new(tcx, a)? {
643             if let Some(b) = AbstractConst::new(tcx, b)? {
644                 let const_unify_ctxt = ConstUnifyCtxt { tcx, param_env };
645                 return Ok(const_unify_ctxt.try_unify(a, b));
646             }
647         }
648
649         Ok(false)
650     })()
651     .unwrap_or_else(|_: ErrorGuaranteed| true)
652     // FIXME(generic_const_exprs): We should instead have this
653     // method return the resulting `ty::Const` and return `ConstKind::Error`
654     // on `ErrorGuaranteed`.
655 }
656
657 #[instrument(skip(tcx, f), level = "debug")]
658 pub fn walk_abstract_const<'tcx, R, F>(
659     tcx: TyCtxt<'tcx>,
660     ct: AbstractConst<'tcx>,
661     mut f: F,
662 ) -> ControlFlow<R>
663 where
664     F: FnMut(AbstractConst<'tcx>) -> ControlFlow<R>,
665 {
666     #[instrument(skip(tcx, f), level = "debug")]
667     fn recurse<'tcx, R>(
668         tcx: TyCtxt<'tcx>,
669         ct: AbstractConst<'tcx>,
670         f: &mut dyn FnMut(AbstractConst<'tcx>) -> ControlFlow<R>,
671     ) -> ControlFlow<R> {
672         f(ct)?;
673         let root = ct.root(tcx);
674         debug!(?root);
675         match root {
676             Node::Leaf(_) => ControlFlow::CONTINUE,
677             Node::Binop(_, l, r) => {
678                 recurse(tcx, ct.subtree(l), f)?;
679                 recurse(tcx, ct.subtree(r), f)
680             }
681             Node::UnaryOp(_, v) => recurse(tcx, ct.subtree(v), f),
682             Node::FunctionCall(func, args) => {
683                 recurse(tcx, ct.subtree(func), f)?;
684                 args.iter().try_for_each(|&arg| recurse(tcx, ct.subtree(arg), f))
685             }
686             Node::Cast(_, operand, _) => recurse(tcx, ct.subtree(operand), f),
687         }
688     }
689
690     recurse(tcx, ct, &mut f)
691 }
692
693 struct ConstUnifyCtxt<'tcx> {
694     tcx: TyCtxt<'tcx>,
695     param_env: ty::ParamEnv<'tcx>,
696 }
697
698 impl<'tcx> ConstUnifyCtxt<'tcx> {
699     // Substitutes generics repeatedly to allow AbstractConsts to unify where a
700     // ConstKind::Unevaluated could be turned into an AbstractConst that would unify e.g.
701     // Param(N) should unify with Param(T), substs: [Unevaluated("T2", [Unevaluated("T3", [Param(N)])])]
702     #[inline]
703     #[instrument(skip(self), level = "debug")]
704     fn try_replace_substs_in_root(
705         &self,
706         mut abstr_const: AbstractConst<'tcx>,
707     ) -> Option<AbstractConst<'tcx>> {
708         while let Node::Leaf(ct) = abstr_const.root(self.tcx) {
709             match AbstractConst::from_const(self.tcx, ct) {
710                 Ok(Some(act)) => abstr_const = act,
711                 Ok(None) => break,
712                 Err(_) => return None,
713             }
714         }
715
716         Some(abstr_const)
717     }
718
719     /// Tries to unify two abstract constants using structural equality.
720     #[instrument(skip(self), level = "debug")]
721     fn try_unify(&self, a: AbstractConst<'tcx>, b: AbstractConst<'tcx>) -> bool {
722         let a = if let Some(a) = self.try_replace_substs_in_root(a) {
723             a
724         } else {
725             return true;
726         };
727
728         let b = if let Some(b) = self.try_replace_substs_in_root(b) {
729             b
730         } else {
731             return true;
732         };
733
734         let a_root = a.root(self.tcx);
735         let b_root = b.root(self.tcx);
736         debug!(?a_root, ?b_root);
737
738         match (a_root, b_root) {
739             (Node::Leaf(a_ct), Node::Leaf(b_ct)) => {
740                 let a_ct = a_ct.eval(self.tcx, self.param_env);
741                 debug!("a_ct evaluated: {:?}", a_ct);
742                 let b_ct = b_ct.eval(self.tcx, self.param_env);
743                 debug!("b_ct evaluated: {:?}", b_ct);
744
745                 if a_ct.ty() != b_ct.ty() {
746                     return false;
747                 }
748
749                 match (a_ct.kind(), b_ct.kind()) {
750                     // We can just unify errors with everything to reduce the amount of
751                     // emitted errors here.
752                     (ty::ConstKind::Error(_), _) | (_, ty::ConstKind::Error(_)) => true,
753                     (ty::ConstKind::Param(a_param), ty::ConstKind::Param(b_param)) => {
754                         a_param == b_param
755                     }
756                     (ty::ConstKind::Value(a_val), ty::ConstKind::Value(b_val)) => a_val == b_val,
757                     // If we have `fn a<const N: usize>() -> [u8; N + 1]` and `fn b<const M: usize>() -> [u8; 1 + M]`
758                     // we do not want to use `assert_eq!(a(), b())` to infer that `N` and `M` have to be `1`. This
759                     // means that we only allow inference variables if they are equal.
760                     (ty::ConstKind::Infer(a_val), ty::ConstKind::Infer(b_val)) => a_val == b_val,
761                     // We expand generic anonymous constants at the start of this function, so this
762                     // branch should only be taking when dealing with associated constants, at
763                     // which point directly comparing them seems like the desired behavior.
764                     //
765                     // FIXME(generic_const_exprs): This isn't actually the case.
766                     // We also take this branch for concrete anonymous constants and
767                     // expand generic anonymous constants with concrete substs.
768                     (ty::ConstKind::Unevaluated(a_uv), ty::ConstKind::Unevaluated(b_uv)) => {
769                         a_uv == b_uv
770                     }
771                     // FIXME(generic_const_exprs): We may want to either actually try
772                     // to evaluate `a_ct` and `b_ct` if they are are fully concrete or something like
773                     // this, for now we just return false here.
774                     _ => false,
775                 }
776             }
777             (Node::Binop(a_op, al, ar), Node::Binop(b_op, bl, br)) if a_op == b_op => {
778                 self.try_unify(a.subtree(al), b.subtree(bl))
779                     && self.try_unify(a.subtree(ar), b.subtree(br))
780             }
781             (Node::UnaryOp(a_op, av), Node::UnaryOp(b_op, bv)) if a_op == b_op => {
782                 self.try_unify(a.subtree(av), b.subtree(bv))
783             }
784             (Node::FunctionCall(a_f, a_args), Node::FunctionCall(b_f, b_args))
785                 if a_args.len() == b_args.len() =>
786             {
787                 self.try_unify(a.subtree(a_f), b.subtree(b_f))
788                     && iter::zip(a_args, b_args)
789                         .all(|(&an, &bn)| self.try_unify(a.subtree(an), b.subtree(bn)))
790             }
791             (Node::Cast(a_kind, a_operand, a_ty), Node::Cast(b_kind, b_operand, b_ty))
792                 if (a_ty == b_ty) && (a_kind == b_kind) =>
793             {
794                 self.try_unify(a.subtree(a_operand), b.subtree(b_operand))
795             }
796             // use this over `_ => false` to make adding variants to `Node` less error prone
797             (Node::Cast(..), _)
798             | (Node::FunctionCall(..), _)
799             | (Node::UnaryOp(..), _)
800             | (Node::Binop(..), _)
801             | (Node::Leaf(..), _) => false,
802         }
803     }
804 }