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 /// Destructures array, ADT or tuple constants into the constants
16 pub(crate) fn destructure_const<'tcx>(
18 const_: ty::Const<'tcx>,
19 ) -> ty::DestructuredConst<'tcx> {
20 let ty::ConstKind::Value(valtree) = const_.kind() else {
21 bug!("cannot destructure constant {:?}", const_)
24 let branches = match valtree {
25 ty::ValTree::Branch(b) => b,
26 _ => bug!("cannot destructure constant {:?}", const_),
29 let (fields, variant) = match const_.ty().kind() {
30 ty::Array(inner_ty, _) | ty::Slice(inner_ty) => {
31 // construct the consts for the elements of the array/slice
32 let field_consts = branches
34 .map(|b| tcx.mk_const(ty::ConstS { kind: ty::ConstKind::Value(*b), ty: *inner_ty }))
36 debug!(?field_consts);
40 ty::Adt(def, _) if def.variants().is_empty() => bug!("unreachable"),
41 ty::Adt(def, substs) => {
42 let (variant_idx, branches) = if def.is_enum() {
43 let (head, rest) = branches.split_first().unwrap();
44 (VariantIdx::from_u32(head.unwrap_leaf().try_to_u32().unwrap()), rest)
46 (VariantIdx::from_u32(0), branches)
48 let fields = &def.variant(variant_idx).fields;
49 let mut field_consts = Vec::with_capacity(fields.len());
51 for (field, field_valtree) in iter::zip(fields, branches) {
52 let field_ty = field.ty(tcx, substs);
53 let field_const = tcx.mk_const(ty::ConstS {
54 kind: ty::ConstKind::Value(*field_valtree),
57 field_consts.push(field_const);
59 debug!(?field_consts);
61 (field_consts, Some(variant_idx))
63 ty::Tuple(elem_tys) => {
64 let fields = iter::zip(*elem_tys, branches)
65 .map(|(elem_ty, elem_valtree)| {
66 tcx.mk_const(ty::ConstS {
67 kind: ty::ConstKind::Value(*elem_valtree),
75 _ => bug!("cannot destructure constant {:?}", const_),
78 let fields = tcx.arena.alloc_from_iter(fields.into_iter());
80 ty::DestructuredConst { variant, fields }
83 pub struct AbstractConstBuilder<'a, 'tcx> {
85 body_id: thir::ExprId,
86 body: &'a thir::Thir<'tcx>,
87 /// The current WIP node tree.
88 nodes: IndexVec<NodeId, Node<'tcx>>,
91 impl<'a, 'tcx> AbstractConstBuilder<'a, 'tcx> {
92 fn root_span(&self) -> Span {
93 self.body.exprs[self.body_id].span
96 fn error(&mut self, span: Span, msg: &str) -> Result<!, ErrorGuaranteed> {
100 .struct_span_err(self.root_span(), "overly complex generic constant")
101 .span_label(span, msg)
102 .help("consider moving this anonymous constant into a `const` function")
107 fn maybe_supported_error(&mut self, span: Span, msg: &str) -> Result<!, ErrorGuaranteed> {
111 .struct_span_err(self.root_span(), "overly complex generic constant")
112 .span_label(span, msg)
113 .help("consider moving this anonymous constant into a `const` function")
114 .note("this operation may be supported in the future")
120 #[instrument(skip(tcx, body, body_id), level = "debug")]
123 (body, body_id): (&'a thir::Thir<'tcx>, thir::ExprId),
124 ) -> Result<Option<AbstractConstBuilder<'a, 'tcx>>, ErrorGuaranteed> {
125 let builder = AbstractConstBuilder { tcx, body_id, body, nodes: IndexVec::new() };
127 struct IsThirPolymorphic<'a, 'tcx> {
129 thir: &'a thir::Thir<'tcx>,
132 use crate::rustc_middle::thir::visit::Visitor;
135 impl<'a, 'tcx> IsThirPolymorphic<'a, 'tcx> {
136 fn expr_is_poly(&mut self, expr: &thir::Expr<'tcx>) -> bool {
137 if expr.ty.has_param_types_or_consts() {
142 thir::ExprKind::NamedConst { substs, .. } => substs.has_param_types_or_consts(),
143 thir::ExprKind::ConstParam { .. } => true,
144 thir::ExprKind::Repeat { value, count } => {
145 self.visit_expr(&self.thir()[value]);
146 count.has_param_types_or_consts()
152 fn pat_is_poly(&mut self, pat: &thir::Pat<'tcx>) -> bool {
153 if pat.ty.has_param_types_or_consts() {
157 match pat.kind.as_ref() {
158 thir::PatKind::Constant { value } => value.has_param_types_or_consts(),
159 thir::PatKind::Range(thir::PatRange { lo, hi, .. }) => {
160 lo.has_param_types_or_consts() || hi.has_param_types_or_consts()
167 impl<'a, 'tcx> visit::Visitor<'a, 'tcx> for IsThirPolymorphic<'a, 'tcx> {
168 fn thir(&self) -> &'a thir::Thir<'tcx> {
172 #[instrument(skip(self), level = "debug")]
173 fn visit_expr(&mut self, expr: &thir::Expr<'tcx>) {
174 self.is_poly |= self.expr_is_poly(expr);
176 visit::walk_expr(self, expr)
180 #[instrument(skip(self), level = "debug")]
181 fn visit_pat(&mut self, pat: &thir::Pat<'tcx>) {
182 self.is_poly |= self.pat_is_poly(pat);
184 visit::walk_pat(self, pat);
189 let mut is_poly_vis = IsThirPolymorphic { is_poly: false, thir: body };
190 visit::walk_expr(&mut is_poly_vis, &body[body_id]);
191 debug!("AbstractConstBuilder: is_poly={}", is_poly_vis.is_poly);
192 if !is_poly_vis.is_poly {
199 /// We do not allow all binary operations in abstract consts, so filter disallowed ones.
200 fn check_binop(op: mir::BinOp) -> bool {
203 Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Shl | Shr | Eq | Lt | Le
204 | Ne | Ge | Gt => true,
209 /// While we currently allow all unary operations, we still want to explicitly guard against
210 /// future changes here.
211 fn check_unop(op: mir::UnOp) -> bool {
218 /// Builds the abstract const by walking the thir and bailing out when
219 /// encountering an unsupported operation.
220 pub fn build(mut self) -> Result<&'tcx [Node<'tcx>], ErrorGuaranteed> {
221 debug!("AbstractConstBuilder::build: body={:?}", &*self.body);
222 self.recurse_build(self.body_id)?;
224 for n in self.nodes.iter() {
225 if let Node::Leaf(ct) = n {
226 if let ty::ConstKind::Unevaluated(ct) = ct.kind() {
227 // `AbstractConst`s should not contain any promoteds as they require references which
229 assert_eq!(ct.promoted, None);
230 assert_eq!(ct, self.tcx.erase_regions(ct));
235 Ok(self.tcx.arena.alloc_from_iter(self.nodes.into_iter()))
238 fn recurse_build(&mut self, node: thir::ExprId) -> Result<NodeId, ErrorGuaranteed> {
240 let node = &self.body.exprs[node];
241 Ok(match &node.kind {
242 // I dont know if handling of these 3 is correct
243 &ExprKind::Scope { value, .. } => self.recurse_build(value)?,
244 &ExprKind::PlaceTypeAscription { source, .. }
245 | &ExprKind::ValueTypeAscription { source, .. } => self.recurse_build(source)?,
246 &ExprKind::Literal { lit, neg} => {
249 match self.tcx.at(sp).lit_to_const(LitToConstInput { lit: &lit.node, ty: node.ty, neg }) {
251 Err(LitToConstError::Reported) => {
252 self.tcx.const_error(node.ty)
254 Err(LitToConstError::TypeError) => {
255 bug!("encountered type error in lit_to_const")
259 self.nodes.push(Node::Leaf(constant))
261 &ExprKind::NonHirLiteral { lit , user_ty: _} => {
262 let val = ty::ValTree::from_scalar_int(lit);
263 self.nodes.push(Node::Leaf(ty::Const::from_value(self.tcx, val, node.ty)))
265 &ExprKind::ZstLiteral { user_ty: _ } => {
266 let val = ty::ValTree::zst();
267 self.nodes.push(Node::Leaf(ty::Const::from_value(self.tcx, val, node.ty)))
269 &ExprKind::NamedConst { def_id, substs, user_ty: _ } => {
270 let uneval = ty::Unevaluated::new(ty::WithOptConstParam::unknown(def_id), substs);
272 let constant = self.tcx.mk_const(ty::ConstS {
273 kind: ty::ConstKind::Unevaluated(uneval),
277 self.nodes.push(Node::Leaf(constant))
280 ExprKind::ConstParam {param, ..} => {
281 let const_param = self.tcx.mk_const(ty::ConstS {
282 kind: ty::ConstKind::Param(*param),
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 { body: thir::Block { stmts: box [], expr: Some(e), .. } } => {
315 self.recurse_build(*e)?
317 // `ExprKind::Use` happens when a `hir::ExprKind::Cast` is a
318 // "coercion cast" i.e. using a coercion or is a no-op.
319 // This is important so that `N as usize as usize` doesnt unify with `N as usize`. (untested)
320 &ExprKind::Use { source } => {
321 let arg = self.recurse_build(source)?;
322 self.nodes.push(Node::Cast(CastKind::Use, arg, node.ty))
324 &ExprKind::Cast { source } => {
325 let arg = self.recurse_build(source)?;
326 self.nodes.push(Node::Cast(CastKind::As, arg, node.ty))
328 ExprKind::Borrow{ arg, ..} => {
329 let arg_node = &self.body.exprs[*arg];
331 // Skip reborrows for now until we allow Deref/Borrow/AddressOf
333 // FIXME(generic_const_exprs): Verify/explain why this is sound
334 if let ExprKind::Deref { arg } = arg_node.kind {
335 self.recurse_build(arg)?
337 self.maybe_supported_error(
339 "borrowing is not supported in generic constants",
343 // FIXME(generic_const_exprs): We may want to support these.
344 ExprKind::AddressOf { .. } | ExprKind::Deref {..}=> self.maybe_supported_error(
346 "dereferencing or taking the address is not supported in generic constants",
348 ExprKind::Repeat { .. } | ExprKind::Array { .. } => self.maybe_supported_error(
350 "array construction is not supported in generic constants",
352 ExprKind::Block { .. } => self.maybe_supported_error(
354 "blocks are not supported in generic constant",
356 ExprKind::NeverToAny { .. } => self.maybe_supported_error(
358 "converting nevers to any is not supported in generic constant",
360 ExprKind::Tuple { .. } => self.maybe_supported_error(
362 "tuple construction is not supported in generic constants",
364 ExprKind::Index { .. } => self.maybe_supported_error(
366 "indexing is not supported in generic constant",
368 ExprKind::Field { .. } => self.maybe_supported_error(
370 "field access is not supported in generic constant",
372 ExprKind::ConstBlock { .. } => self.maybe_supported_error(
374 "const blocks are not supported in generic constant",
376 ExprKind::Adt(_) => self.maybe_supported_error(
378 "struct/enum construction is not supported in generic constants",
380 // dont know if this is correct
381 ExprKind::Pointer { .. } =>
382 self.error(node.span, "pointer casts are not allowed in generic constants")?,
383 ExprKind::Yield { .. } =>
384 self.error(node.span, "generator control flow is not allowed in generic constants")?,
385 ExprKind::Continue { .. } | ExprKind::Break { .. } | ExprKind::Loop { .. } => self
388 "loops and loop control flow are not supported in generic constants",
390 ExprKind::Box { .. } =>
391 self.error(node.span, "allocations are not allowed in generic constants")?,
393 ExprKind::Unary { .. } => unreachable!(),
394 // we handle valid unary/binary ops above
395 ExprKind::Binary { .. } =>
396 self.error(node.span, "unsupported binary operation in generic constants")?,
397 ExprKind::LogicalOp { .. } =>
398 self.error(node.span, "unsupported operation in generic constants, short-circuiting operations would imply control flow")?,
399 ExprKind::Assign { .. } | ExprKind::AssignOp { .. } => {
400 self.error(node.span, "assignment is not supported in generic constants")?
402 ExprKind::Closure { .. } | ExprKind::Return { .. } => self.error(
404 "closures and function keywords are not supported in generic constants",
406 // let expressions imply control flow
407 ExprKind::Match { .. } | ExprKind::If { .. } | ExprKind::Let { .. } =>
408 self.error(node.span, "control flow is not supported in generic constants")?,
409 ExprKind::InlineAsm { .. } => {
410 self.error(node.span, "assembly is not supported in generic constants")?
413 // we dont permit let stmts so `VarRef` and `UpvarRef` cant happen
414 ExprKind::VarRef { .. }
415 | ExprKind::UpvarRef { .. }
416 | ExprKind::StaticRef { .. }
417 | ExprKind::ThreadLocalRef(_) => {
418 self.error(node.span, "unsupported operation in generic constant")?
424 /// Builds an abstract const, do not use this directly, but use `AbstractConst::new` instead.
425 pub fn thir_abstract_const<'tcx>(
427 def: ty::WithOptConstParam<LocalDefId>,
428 ) -> Result<Option<&'tcx [Node<'tcx>]>, ErrorGuaranteed> {
429 if tcx.features().generic_const_exprs {
430 match tcx.def_kind(def.did) {
431 // FIXME(generic_const_exprs): We currently only do this for anonymous constants,
432 // meaning that we do not look into associated constants. I(@lcnr) am not yet sure whether
433 // we want to look into them or treat them as opaque projections.
435 // Right now we do neither of that and simply always fail to unify them.
436 DefKind::AnonConst | DefKind::InlineConst => (),
437 _ => return Ok(None),
440 let body = tcx.thir_body(def)?;
442 AbstractConstBuilder::new(tcx, (&*body.0.borrow(), body.1))?
443 .map(AbstractConstBuilder::build)
450 pub fn provide(providers: &mut ty::query::Providers) {
451 *providers = ty::query::Providers {
453 thir_abstract_const: |tcx, def_id| {
454 let def_id = def_id.expect_local();
455 if let Some(def) = ty::WithOptConstParam::try_lookup(def_id, tcx) {
456 tcx.thir_abstract_const_of_const_arg(def)
458 thir_abstract_const(tcx, ty::WithOptConstParam::unknown(def_id))
461 thir_abstract_const_of_const_arg: |tcx, (did, param_did)| {
464 ty::WithOptConstParam { did, const_param_did: Some(param_did) },