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