1 use rustc_errors::ErrorGuaranteed;
2 use rustc_hir::def::DefKind;
3 use rustc_hir::def_id::LocalDefId;
4 use rustc_index::vec::IndexVec;
5 use rustc_middle::mir::interpret::{LitToConstError, LitToConstInput};
6 use rustc_middle::ty::abstract_const::{CastKind, Node, NodeId};
7 use rustc_middle::ty::{self, TyCtxt, TypeVisitable};
8 use rustc_middle::{mir, thir};
10 use rustc_target::abi::VariantIdx;
14 use crate::errors::{GenericConstantTooComplex, GenericConstantTooComplexSub};
16 /// Destructures array, ADT or tuple constants into the constants
18 pub(crate) fn destructure_const<'tcx>(
20 const_: ty::Const<'tcx>,
21 ) -> ty::DestructuredConst<'tcx> {
22 let ty::ConstKind::Value(valtree) = const_.kind() else {
23 bug!("cannot destructure constant {:?}", const_)
26 let branches = match valtree {
27 ty::ValTree::Branch(b) => b,
28 _ => bug!("cannot destructure constant {:?}", const_),
31 let (fields, variant) = match const_.ty().kind() {
32 ty::Array(inner_ty, _) | ty::Slice(inner_ty) => {
33 // construct the consts for the elements of the array/slice
34 let field_consts = branches
36 .map(|b| tcx.mk_const(ty::ConstS { kind: ty::ConstKind::Value(*b), ty: *inner_ty }))
38 debug!(?field_consts);
42 ty::Adt(def, _) if def.variants().is_empty() => bug!("unreachable"),
43 ty::Adt(def, substs) => {
44 let (variant_idx, branches) = if def.is_enum() {
45 let (head, rest) = branches.split_first().unwrap();
46 (VariantIdx::from_u32(head.unwrap_leaf().try_to_u32().unwrap()), rest)
48 (VariantIdx::from_u32(0), branches)
50 let fields = &def.variant(variant_idx).fields;
51 let mut field_consts = Vec::with_capacity(fields.len());
53 for (field, field_valtree) in iter::zip(fields, branches) {
54 let field_ty = field.ty(tcx, substs);
55 let field_const = tcx.mk_const(ty::ConstS {
56 kind: ty::ConstKind::Value(*field_valtree),
59 field_consts.push(field_const);
61 debug!(?field_consts);
63 (field_consts, Some(variant_idx))
65 ty::Tuple(elem_tys) => {
66 let fields = iter::zip(*elem_tys, branches)
67 .map(|(elem_ty, elem_valtree)| {
68 tcx.mk_const(ty::ConstS {
69 kind: ty::ConstKind::Value(*elem_valtree),
77 _ => bug!("cannot destructure constant {:?}", const_),
80 let fields = tcx.arena.alloc_from_iter(fields.into_iter());
82 ty::DestructuredConst { variant, fields }
85 pub struct AbstractConstBuilder<'a, 'tcx> {
87 body_id: thir::ExprId,
88 body: &'a thir::Thir<'tcx>,
89 /// The current WIP node tree.
90 nodes: IndexVec<NodeId, Node<'tcx>>,
93 impl<'a, 'tcx> AbstractConstBuilder<'a, 'tcx> {
94 fn root_span(&self) -> Span {
95 self.body.exprs[self.body_id].span
98 fn error(&mut self, sub: GenericConstantTooComplexSub) -> Result<!, ErrorGuaranteed> {
99 let reported = self.tcx.sess.emit_err(GenericConstantTooComplex {
100 span: self.root_span(),
101 maybe_supported: None,
108 fn maybe_supported_error(
110 sub: GenericConstantTooComplexSub,
111 ) -> Result<!, ErrorGuaranteed> {
112 let reported = self.tcx.sess.emit_err(GenericConstantTooComplex {
113 span: self.root_span(),
114 maybe_supported: Some(()),
121 #[instrument(skip(tcx, body, body_id), level = "debug")]
124 (body, body_id): (&'a thir::Thir<'tcx>, thir::ExprId),
125 ) -> Result<Option<AbstractConstBuilder<'a, 'tcx>>, ErrorGuaranteed> {
126 let builder = AbstractConstBuilder { tcx, body_id, body, nodes: IndexVec::new() };
128 struct IsThirPolymorphic<'a, 'tcx> {
130 thir: &'a thir::Thir<'tcx>,
133 use crate::rustc_middle::thir::visit::Visitor;
136 impl<'a, 'tcx> IsThirPolymorphic<'a, 'tcx> {
137 fn expr_is_poly(&mut self, expr: &thir::Expr<'tcx>) -> bool {
138 if expr.ty.has_param_types_or_consts() {
143 thir::ExprKind::NamedConst { substs, .. } => substs.has_param_types_or_consts(),
144 thir::ExprKind::ConstParam { .. } => true,
145 thir::ExprKind::Repeat { value, count } => {
146 self.visit_expr(&self.thir()[value]);
147 count.has_param_types_or_consts()
153 fn pat_is_poly(&mut self, pat: &thir::Pat<'tcx>) -> bool {
154 if pat.ty.has_param_types_or_consts() {
158 match pat.kind.as_ref() {
159 thir::PatKind::Constant { value } => value.has_param_types_or_consts(),
160 thir::PatKind::Range(thir::PatRange { lo, hi, .. }) => {
161 lo.has_param_types_or_consts() || hi.has_param_types_or_consts()
168 impl<'a, 'tcx> visit::Visitor<'a, 'tcx> for IsThirPolymorphic<'a, 'tcx> {
169 fn thir(&self) -> &'a thir::Thir<'tcx> {
173 #[instrument(skip(self), level = "debug")]
174 fn visit_expr(&mut self, expr: &thir::Expr<'tcx>) {
175 self.is_poly |= self.expr_is_poly(expr);
177 visit::walk_expr(self, expr)
181 #[instrument(skip(self), level = "debug")]
182 fn visit_pat(&mut self, pat: &thir::Pat<'tcx>) {
183 self.is_poly |= self.pat_is_poly(pat);
185 visit::walk_pat(self, pat);
190 let mut is_poly_vis = IsThirPolymorphic { is_poly: false, thir: body };
191 visit::walk_expr(&mut is_poly_vis, &body[body_id]);
192 debug!("AbstractConstBuilder: is_poly={}", is_poly_vis.is_poly);
193 if !is_poly_vis.is_poly {
200 /// We do not allow all binary operations in abstract consts, so filter disallowed ones.
201 fn check_binop(op: mir::BinOp) -> bool {
204 Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Shl | Shr | Eq | Lt | Le
205 | Ne | Ge | Gt => true,
210 /// While we currently allow all unary operations, we still want to explicitly guard against
211 /// future changes here.
212 fn check_unop(op: mir::UnOp) -> bool {
219 /// Builds the abstract const by walking the thir and bailing out when
220 /// encountering an unsupported operation.
221 pub fn build(mut self) -> Result<&'tcx [Node<'tcx>], ErrorGuaranteed> {
222 debug!("AbstractConstBuilder::build: body={:?}", &*self.body);
223 self.recurse_build(self.body_id)?;
225 for n in self.nodes.iter() {
226 if let Node::Leaf(ct) = n {
227 if let ty::ConstKind::Unevaluated(ct) = ct.kind() {
228 // `AbstractConst`s should not contain any promoteds as they require references which
230 assert_eq!(ct.promoted, None);
231 assert_eq!(ct, self.tcx.erase_regions(ct));
236 Ok(self.tcx.arena.alloc_from_iter(self.nodes.into_iter()))
239 fn recurse_build(&mut self, node: thir::ExprId) -> Result<NodeId, ErrorGuaranteed> {
241 let node = &self.body.exprs[node];
242 Ok(match &node.kind {
243 // I dont know if handling of these 3 is correct
244 &ExprKind::Scope { value, .. } => self.recurse_build(value)?,
245 &ExprKind::PlaceTypeAscription { source, .. }
246 | &ExprKind::ValueTypeAscription { source, .. } => self.recurse_build(source)?,
247 &ExprKind::Literal { lit, neg } => {
249 let constant = match self.tcx.at(sp).lit_to_const(LitToConstInput {
255 Err(LitToConstError::Reported) => self.tcx.const_error(node.ty),
256 Err(LitToConstError::TypeError) => {
257 bug!("encountered type error in lit_to_const")
261 self.nodes.push(Node::Leaf(constant))
263 &ExprKind::NonHirLiteral { lit, user_ty: _ } => {
264 let val = ty::ValTree::from_scalar_int(lit);
265 self.nodes.push(Node::Leaf(ty::Const::from_value(self.tcx, val, node.ty)))
267 &ExprKind::ZstLiteral { user_ty: _ } => {
268 let val = ty::ValTree::zst();
269 self.nodes.push(Node::Leaf(ty::Const::from_value(self.tcx, val, node.ty)))
271 &ExprKind::NamedConst { def_id, substs, user_ty: _ } => {
272 let uneval = ty::Unevaluated::new(ty::WithOptConstParam::unknown(def_id), substs);
276 .mk_const(ty::ConstS { kind: ty::ConstKind::Unevaluated(uneval), ty: node.ty });
278 self.nodes.push(Node::Leaf(constant))
281 ExprKind::ConstParam { param, .. } => {
282 let const_param = self
284 .mk_const(ty::ConstS { kind: ty::ConstKind::Param(*param), ty: node.ty });
285 self.nodes.push(Node::Leaf(const_param))
288 ExprKind::Call { fun, args, .. } => {
289 let fun = self.recurse_build(*fun)?;
291 let mut new_args = Vec::<NodeId>::with_capacity(args.len());
292 for &id in args.iter() {
293 new_args.push(self.recurse_build(id)?);
295 let new_args = self.tcx.arena.alloc_slice(&new_args);
296 self.nodes.push(Node::FunctionCall(fun, new_args))
298 &ExprKind::Binary { op, lhs, rhs } if Self::check_binop(op) => {
299 let lhs = self.recurse_build(lhs)?;
300 let rhs = self.recurse_build(rhs)?;
301 self.nodes.push(Node::Binop(op, lhs, rhs))
303 &ExprKind::Unary { op, arg } if Self::check_unop(op) => {
304 let arg = self.recurse_build(arg)?;
305 self.nodes.push(Node::UnaryOp(op, arg))
307 // This is necessary so that the following compiles:
310 // fn foo<const N: usize>(a: [(); N + 1]) {
311 // bar::<{ N + 1 }>();
314 ExprKind::Block { block } => {
315 if let thir::Block { stmts: box [], expr: Some(e), .. } = &self.body.blocks[*block]
317 self.recurse_build(*e)?
319 self.maybe_supported_error(GenericConstantTooComplexSub::BlockNotSupported(
324 // `ExprKind::Use` happens when a `hir::ExprKind::Cast` is a
325 // "coercion cast" i.e. using a coercion or is a no-op.
326 // This is important so that `N as usize as usize` doesnt unify with `N as usize`. (untested)
327 &ExprKind::Use { source } => {
328 let arg = self.recurse_build(source)?;
329 self.nodes.push(Node::Cast(CastKind::Use, arg, node.ty))
331 &ExprKind::Cast { source } => {
332 let arg = self.recurse_build(source)?;
333 self.nodes.push(Node::Cast(CastKind::As, arg, node.ty))
335 ExprKind::Borrow { arg, .. } => {
336 let arg_node = &self.body.exprs[*arg];
338 // Skip reborrows for now until we allow Deref/Borrow/AddressOf
340 // FIXME(generic_const_exprs): Verify/explain why this is sound
341 if let ExprKind::Deref { arg } = arg_node.kind {
342 self.recurse_build(arg)?
344 self.maybe_supported_error(GenericConstantTooComplexSub::BorrowNotSupported(
349 // FIXME(generic_const_exprs): We may want to support these.
350 ExprKind::AddressOf { .. } | ExprKind::Deref { .. } => self.maybe_supported_error(
351 GenericConstantTooComplexSub::AddressAndDerefNotSupported(node.span),
353 ExprKind::Repeat { .. } | ExprKind::Array { .. } => self.maybe_supported_error(
354 GenericConstantTooComplexSub::ArrayNotSupported(node.span),
356 ExprKind::NeverToAny { .. } => self.maybe_supported_error(
357 GenericConstantTooComplexSub::NeverToAnyNotSupported(node.span),
359 ExprKind::Tuple { .. } => self.maybe_supported_error(
360 GenericConstantTooComplexSub::TupleNotSupported(node.span),
362 ExprKind::Index { .. } => self.maybe_supported_error(
363 GenericConstantTooComplexSub::IndexNotSupported(node.span),
365 ExprKind::Field { .. } => self.maybe_supported_error(
366 GenericConstantTooComplexSub::FieldNotSupported(node.span),
368 ExprKind::ConstBlock { .. } => self.maybe_supported_error(
369 GenericConstantTooComplexSub::ConstBlockNotSupported(node.span),
371 ExprKind::Adt(_) => self
372 .maybe_supported_error(GenericConstantTooComplexSub::AdtNotSupported(node.span))?,
373 // dont know if this is correct
374 ExprKind::Pointer { .. } => {
375 self.error(GenericConstantTooComplexSub::PointerNotSupported(node.span))?
377 ExprKind::Yield { .. } => {
378 self.error(GenericConstantTooComplexSub::YieldNotSupported(node.span))?
380 ExprKind::Continue { .. } | ExprKind::Break { .. } | ExprKind::Loop { .. } => {
381 self.error(GenericConstantTooComplexSub::LoopNotSupported(node.span))?
383 ExprKind::Box { .. } => {
384 self.error(GenericConstantTooComplexSub::BoxNotSupported(node.span))?
387 ExprKind::Unary { .. } => unreachable!(),
388 // we handle valid unary/binary ops above
389 ExprKind::Binary { .. } => {
390 self.error(GenericConstantTooComplexSub::BinaryNotSupported(node.span))?
392 ExprKind::LogicalOp { .. } => {
393 self.error(GenericConstantTooComplexSub::LogicalOpNotSupported(node.span))?
395 ExprKind::Assign { .. } | ExprKind::AssignOp { .. } => {
396 self.error(GenericConstantTooComplexSub::AssignNotSupported(node.span))?
398 ExprKind::Closure { .. } | ExprKind::Return { .. } => {
399 self.error(GenericConstantTooComplexSub::ClosureAndReturnNotSupported(node.span))?
401 // let expressions imply control flow
402 ExprKind::Match { .. } | ExprKind::If { .. } | ExprKind::Let { .. } => {
403 self.error(GenericConstantTooComplexSub::ControlFlowNotSupported(node.span))?
405 ExprKind::InlineAsm { .. } => {
406 self.error(GenericConstantTooComplexSub::InlineAsmNotSupported(node.span))?
409 // we dont permit let stmts so `VarRef` and `UpvarRef` cant happen
410 ExprKind::VarRef { .. }
411 | ExprKind::UpvarRef { .. }
412 | ExprKind::StaticRef { .. }
413 | ExprKind::ThreadLocalRef(_) => {
414 self.error(GenericConstantTooComplexSub::OperationNotSupported(node.span))?
420 /// Builds an abstract const, do not use this directly, but use `AbstractConst::new` instead.
421 pub fn thir_abstract_const<'tcx>(
423 def: ty::WithOptConstParam<LocalDefId>,
424 ) -> Result<Option<&'tcx [Node<'tcx>]>, ErrorGuaranteed> {
425 if tcx.features().generic_const_exprs {
426 match tcx.def_kind(def.did) {
427 // FIXME(generic_const_exprs): We currently only do this for anonymous constants,
428 // meaning that we do not look into associated constants. I(@lcnr) am not yet sure whether
429 // we want to look into them or treat them as opaque projections.
431 // Right now we do neither of that and simply always fail to unify them.
432 DefKind::AnonConst | DefKind::InlineConst => (),
433 _ => return Ok(None),
436 let body = tcx.thir_body(def)?;
438 AbstractConstBuilder::new(tcx, (&*body.0.borrow(), body.1))?
439 .map(AbstractConstBuilder::build)
446 pub fn provide(providers: &mut ty::query::Providers) {
447 *providers = ty::query::Providers {
449 thir_abstract_const: |tcx, def_id| {
450 let def_id = def_id.expect_local();
451 if let Some(def) = ty::WithOptConstParam::try_lookup(def_id, tcx) {
452 tcx.thir_abstract_const_of_const_arg(def)
454 thir_abstract_const(tcx, ty::WithOptConstParam::unknown(def_id))
457 thir_abstract_const_of_const_arg: |tcx, (did, param_did)| {
460 ty::WithOptConstParam { did, const_param_did: Some(param_did) },