]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_ty_utils/src/consts.rs
Rollup merge of #103694 - WaffleLapkin:mask_doc_example, r=scottmcm
[rust.git] / compiler / rustc_ty_utils / src / consts.rs
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};
9 use rustc_span::Span;
10 use rustc_target::abi::VariantIdx;
11
12 use std::iter;
13
14 use crate::errors::{GenericConstantTooComplex, GenericConstantTooComplexSub};
15
16 /// Destructures array, ADT or tuple constants into the constants
17 /// of their fields.
18 pub(crate) fn destructure_const<'tcx>(
19     tcx: TyCtxt<'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_)
24     };
25
26     let branches = match valtree {
27         ty::ValTree::Branch(b) => b,
28         _ => bug!("cannot destructure constant {:?}", const_),
29     };
30
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
35                 .iter()
36                 .map(|b| tcx.mk_const(ty::ConstKind::Value(*b), *inner_ty))
37                 .collect::<Vec<_>>();
38             debug!(?field_consts);
39
40             (field_consts, None)
41         }
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)
47             } else {
48                 (VariantIdx::from_u32(0), branches)
49             };
50             let fields = &def.variant(variant_idx).fields;
51             let mut field_consts = Vec::with_capacity(fields.len());
52
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::ConstKind::Value(*field_valtree), field_ty);
56                 field_consts.push(field_const);
57             }
58             debug!(?field_consts);
59
60             (field_consts, Some(variant_idx))
61         }
62         ty::Tuple(elem_tys) => {
63             let fields = iter::zip(*elem_tys, branches)
64                 .map(|(elem_ty, elem_valtree)| {
65                     tcx.mk_const(ty::ConstKind::Value(*elem_valtree), elem_ty)
66                 })
67                 .collect::<Vec<_>>();
68
69             (fields, None)
70         }
71         _ => bug!("cannot destructure constant {:?}", const_),
72     };
73
74     let fields = tcx.arena.alloc_from_iter(fields.into_iter());
75
76     ty::DestructuredConst { variant, fields }
77 }
78
79 pub struct AbstractConstBuilder<'a, 'tcx> {
80     tcx: TyCtxt<'tcx>,
81     body_id: thir::ExprId,
82     body: &'a thir::Thir<'tcx>,
83     /// The current WIP node tree.
84     nodes: IndexVec<NodeId, Node<'tcx>>,
85 }
86
87 impl<'a, 'tcx> AbstractConstBuilder<'a, 'tcx> {
88     fn root_span(&self) -> Span {
89         self.body.exprs[self.body_id].span
90     }
91
92     fn error(&mut self, sub: GenericConstantTooComplexSub) -> Result<!, ErrorGuaranteed> {
93         let reported = self.tcx.sess.emit_err(GenericConstantTooComplex {
94             span: self.root_span(),
95             maybe_supported: None,
96             sub,
97         });
98
99         Err(reported)
100     }
101
102     fn maybe_supported_error(
103         &mut self,
104         sub: GenericConstantTooComplexSub,
105     ) -> Result<!, ErrorGuaranteed> {
106         let reported = self.tcx.sess.emit_err(GenericConstantTooComplex {
107             span: self.root_span(),
108             maybe_supported: Some(()),
109             sub,
110         });
111
112         Err(reported)
113     }
114
115     #[instrument(skip(tcx, body, body_id), level = "debug")]
116     pub fn new(
117         tcx: TyCtxt<'tcx>,
118         (body, body_id): (&'a thir::Thir<'tcx>, thir::ExprId),
119     ) -> Result<Option<AbstractConstBuilder<'a, 'tcx>>, ErrorGuaranteed> {
120         let builder = AbstractConstBuilder { tcx, body_id, body, nodes: IndexVec::new() };
121
122         struct IsThirPolymorphic<'a, 'tcx> {
123             is_poly: bool,
124             thir: &'a thir::Thir<'tcx>,
125         }
126
127         use crate::rustc_middle::thir::visit::Visitor;
128         use thir::visit;
129
130         impl<'a, 'tcx> IsThirPolymorphic<'a, 'tcx> {
131             fn expr_is_poly(&mut self, expr: &thir::Expr<'tcx>) -> bool {
132                 if expr.ty.has_non_region_param() {
133                     return true;
134                 }
135
136                 match expr.kind {
137                     thir::ExprKind::NamedConst { substs, .. } => substs.has_non_region_param(),
138                     thir::ExprKind::ConstParam { .. } => true,
139                     thir::ExprKind::Repeat { value, count } => {
140                         self.visit_expr(&self.thir()[value]);
141                         count.has_non_region_param()
142                     }
143                     _ => false,
144                 }
145             }
146
147             fn pat_is_poly(&mut self, pat: &thir::Pat<'tcx>) -> bool {
148                 if pat.ty.has_non_region_param() {
149                     return true;
150                 }
151
152                 match pat.kind {
153                     thir::PatKind::Constant { value } => value.has_non_region_param(),
154                     thir::PatKind::Range(box thir::PatRange { lo, hi, .. }) => {
155                         lo.has_non_region_param() || hi.has_non_region_param()
156                     }
157                     _ => false,
158                 }
159             }
160         }
161
162         impl<'a, 'tcx> visit::Visitor<'a, 'tcx> for IsThirPolymorphic<'a, 'tcx> {
163             fn thir(&self) -> &'a thir::Thir<'tcx> {
164                 &self.thir
165             }
166
167             #[instrument(skip(self), level = "debug")]
168             fn visit_expr(&mut self, expr: &thir::Expr<'tcx>) {
169                 self.is_poly |= self.expr_is_poly(expr);
170                 if !self.is_poly {
171                     visit::walk_expr(self, expr)
172                 }
173             }
174
175             #[instrument(skip(self), level = "debug")]
176             fn visit_pat(&mut self, pat: &thir::Pat<'tcx>) {
177                 self.is_poly |= self.pat_is_poly(pat);
178                 if !self.is_poly {
179                     visit::walk_pat(self, pat);
180                 }
181             }
182         }
183
184         let mut is_poly_vis = IsThirPolymorphic { is_poly: false, thir: body };
185         visit::walk_expr(&mut is_poly_vis, &body[body_id]);
186         debug!("AbstractConstBuilder: is_poly={}", is_poly_vis.is_poly);
187         if !is_poly_vis.is_poly {
188             return Ok(None);
189         }
190
191         Ok(Some(builder))
192     }
193
194     /// We do not allow all binary operations in abstract consts, so filter disallowed ones.
195     fn check_binop(op: mir::BinOp) -> bool {
196         use mir::BinOp::*;
197         match op {
198             Add | Sub | Mul | Div | Rem | BitXor | BitAnd | BitOr | Shl | Shr | Eq | Lt | Le
199             | Ne | Ge | Gt => true,
200             Offset => false,
201         }
202     }
203
204     /// While we currently allow all unary operations, we still want to explicitly guard against
205     /// future changes here.
206     fn check_unop(op: mir::UnOp) -> bool {
207         use mir::UnOp::*;
208         match op {
209             Not | Neg => true,
210         }
211     }
212
213     /// Builds the abstract const by walking the thir and bailing out when
214     /// encountering an unsupported operation.
215     pub fn build(mut self) -> Result<&'tcx [Node<'tcx>], ErrorGuaranteed> {
216         debug!("AbstractConstBuilder::build: body={:?}", &*self.body);
217         self.recurse_build(self.body_id)?;
218
219         Ok(self.tcx.arena.alloc_from_iter(self.nodes.into_iter()))
220     }
221
222     fn recurse_build(&mut self, node: thir::ExprId) -> Result<NodeId, ErrorGuaranteed> {
223         use thir::ExprKind;
224         let node = &self.body.exprs[node];
225         Ok(match &node.kind {
226             // I dont know if handling of these 3 is correct
227             &ExprKind::Scope { value, .. } => self.recurse_build(value)?,
228             &ExprKind::PlaceTypeAscription { source, .. }
229             | &ExprKind::ValueTypeAscription { source, .. } => self.recurse_build(source)?,
230             &ExprKind::Literal { lit, neg } => {
231                 let sp = node.span;
232                 let constant = match self.tcx.at(sp).lit_to_const(LitToConstInput {
233                     lit: &lit.node,
234                     ty: node.ty,
235                     neg,
236                 }) {
237                     Ok(c) => c,
238                     Err(LitToConstError::Reported) => self.tcx.const_error(node.ty),
239                     Err(LitToConstError::TypeError) => {
240                         bug!("encountered type error in lit_to_const")
241                     }
242                 };
243
244                 self.nodes.push(Node::Leaf(constant))
245             }
246             &ExprKind::NonHirLiteral { lit, user_ty: _ } => {
247                 let val = ty::ValTree::from_scalar_int(lit);
248                 self.nodes.push(Node::Leaf(ty::Const::from_value(self.tcx, val, node.ty)))
249             }
250             &ExprKind::ZstLiteral { user_ty: _ } => {
251                 let val = ty::ValTree::zst();
252                 self.nodes.push(Node::Leaf(ty::Const::from_value(self.tcx, val, node.ty)))
253             }
254             &ExprKind::NamedConst { def_id, substs, user_ty: _ } => {
255                 let uneval =
256                     ty::UnevaluatedConst::new(ty::WithOptConstParam::unknown(def_id), substs);
257
258                 let constant = self.tcx.mk_const(ty::ConstKind::Unevaluated(uneval), node.ty);
259
260                 self.nodes.push(Node::Leaf(constant))
261             }
262
263             ExprKind::ConstParam { param, .. } => {
264                 let const_param = self.tcx.mk_const(ty::ConstKind::Param(*param), node.ty);
265                 self.nodes.push(Node::Leaf(const_param))
266             }
267
268             ExprKind::Call { fun, args, .. } => {
269                 let fun = self.recurse_build(*fun)?;
270
271                 let mut new_args = Vec::<NodeId>::with_capacity(args.len());
272                 for &id in args.iter() {
273                     new_args.push(self.recurse_build(id)?);
274                 }
275                 let new_args = self.tcx.arena.alloc_slice(&new_args);
276                 self.nodes.push(Node::FunctionCall(fun, new_args))
277             }
278             &ExprKind::Binary { op, lhs, rhs } if Self::check_binop(op) => {
279                 let lhs = self.recurse_build(lhs)?;
280                 let rhs = self.recurse_build(rhs)?;
281                 self.nodes.push(Node::Binop(op, lhs, rhs))
282             }
283             &ExprKind::Unary { op, arg } if Self::check_unop(op) => {
284                 let arg = self.recurse_build(arg)?;
285                 self.nodes.push(Node::UnaryOp(op, arg))
286             }
287             // This is necessary so that the following compiles:
288             //
289             // ```
290             // fn foo<const N: usize>(a: [(); N + 1]) {
291             //     bar::<{ N + 1 }>();
292             // }
293             // ```
294             ExprKind::Block { block } => {
295                 if let thir::Block { stmts: box [], expr: Some(e), .. } = &self.body.blocks[*block]
296                 {
297                     self.recurse_build(*e)?
298                 } else {
299                     self.maybe_supported_error(GenericConstantTooComplexSub::BlockNotSupported(
300                         node.span,
301                     ))?
302                 }
303             }
304             // `ExprKind::Use` happens when a `hir::ExprKind::Cast` is a
305             // "coercion cast" i.e. using a coercion or is a no-op.
306             // This is important so that `N as usize as usize` doesnt unify with `N as usize`. (untested)
307             &ExprKind::Use { source } => {
308                 let arg = self.recurse_build(source)?;
309                 self.nodes.push(Node::Cast(CastKind::Use, arg, node.ty))
310             }
311             &ExprKind::Cast { source } => {
312                 let arg = self.recurse_build(source)?;
313                 self.nodes.push(Node::Cast(CastKind::As, arg, node.ty))
314             }
315             ExprKind::Borrow { arg, .. } => {
316                 let arg_node = &self.body.exprs[*arg];
317
318                 // Skip reborrows for now until we allow Deref/Borrow/AddressOf
319                 // expressions.
320                 // FIXME(generic_const_exprs): Verify/explain why this is sound
321                 if let ExprKind::Deref { arg } = arg_node.kind {
322                     self.recurse_build(arg)?
323                 } else {
324                     self.maybe_supported_error(GenericConstantTooComplexSub::BorrowNotSupported(
325                         node.span,
326                     ))?
327                 }
328             }
329             // FIXME(generic_const_exprs): We may want to support these.
330             ExprKind::AddressOf { .. } | ExprKind::Deref { .. } => self.maybe_supported_error(
331                 GenericConstantTooComplexSub::AddressAndDerefNotSupported(node.span),
332             )?,
333             ExprKind::Repeat { .. } | ExprKind::Array { .. } => self.maybe_supported_error(
334                 GenericConstantTooComplexSub::ArrayNotSupported(node.span),
335             )?,
336             ExprKind::NeverToAny { .. } => self.maybe_supported_error(
337                 GenericConstantTooComplexSub::NeverToAnyNotSupported(node.span),
338             )?,
339             ExprKind::Tuple { .. } => self.maybe_supported_error(
340                 GenericConstantTooComplexSub::TupleNotSupported(node.span),
341             )?,
342             ExprKind::Index { .. } => self.maybe_supported_error(
343                 GenericConstantTooComplexSub::IndexNotSupported(node.span),
344             )?,
345             ExprKind::Field { .. } => self.maybe_supported_error(
346                 GenericConstantTooComplexSub::FieldNotSupported(node.span),
347             )?,
348             ExprKind::ConstBlock { .. } => self.maybe_supported_error(
349                 GenericConstantTooComplexSub::ConstBlockNotSupported(node.span),
350             )?,
351             ExprKind::Adt(_) => self
352                 .maybe_supported_error(GenericConstantTooComplexSub::AdtNotSupported(node.span))?,
353             // dont know if this is correct
354             ExprKind::Pointer { .. } => {
355                 self.error(GenericConstantTooComplexSub::PointerNotSupported(node.span))?
356             }
357             ExprKind::Yield { .. } => {
358                 self.error(GenericConstantTooComplexSub::YieldNotSupported(node.span))?
359             }
360             ExprKind::Continue { .. } | ExprKind::Break { .. } | ExprKind::Loop { .. } => {
361                 self.error(GenericConstantTooComplexSub::LoopNotSupported(node.span))?
362             }
363             ExprKind::Box { .. } => {
364                 self.error(GenericConstantTooComplexSub::BoxNotSupported(node.span))?
365             }
366
367             ExprKind::Unary { .. } => unreachable!(),
368             // we handle valid unary/binary ops above
369             ExprKind::Binary { .. } => {
370                 self.error(GenericConstantTooComplexSub::BinaryNotSupported(node.span))?
371             }
372             ExprKind::LogicalOp { .. } => {
373                 self.error(GenericConstantTooComplexSub::LogicalOpNotSupported(node.span))?
374             }
375             ExprKind::Assign { .. } | ExprKind::AssignOp { .. } => {
376                 self.error(GenericConstantTooComplexSub::AssignNotSupported(node.span))?
377             }
378             ExprKind::Closure { .. } | ExprKind::Return { .. } => {
379                 self.error(GenericConstantTooComplexSub::ClosureAndReturnNotSupported(node.span))?
380             }
381             // let expressions imply control flow
382             ExprKind::Match { .. } | ExprKind::If { .. } | ExprKind::Let { .. } => {
383                 self.error(GenericConstantTooComplexSub::ControlFlowNotSupported(node.span))?
384             }
385             ExprKind::InlineAsm { .. } => {
386                 self.error(GenericConstantTooComplexSub::InlineAsmNotSupported(node.span))?
387             }
388
389             // we dont permit let stmts so `VarRef` and `UpvarRef` cant happen
390             ExprKind::VarRef { .. }
391             | ExprKind::UpvarRef { .. }
392             | ExprKind::StaticRef { .. }
393             | ExprKind::ThreadLocalRef(_) => {
394                 self.error(GenericConstantTooComplexSub::OperationNotSupported(node.span))?
395             }
396         })
397     }
398 }
399
400 /// Builds an abstract const, do not use this directly, but use `AbstractConst::new` instead.
401 pub fn thir_abstract_const<'tcx>(
402     tcx: TyCtxt<'tcx>,
403     def: ty::WithOptConstParam<LocalDefId>,
404 ) -> Result<Option<&'tcx [Node<'tcx>]>, ErrorGuaranteed> {
405     if tcx.features().generic_const_exprs {
406         match tcx.def_kind(def.did) {
407             // FIXME(generic_const_exprs): We currently only do this for anonymous constants,
408             // meaning that we do not look into associated constants. I(@lcnr) am not yet sure whether
409             // we want to look into them or treat them as opaque projections.
410             //
411             // Right now we do neither of that and simply always fail to unify them.
412             DefKind::AnonConst | DefKind::InlineConst => (),
413             _ => return Ok(None),
414         }
415
416         let body = tcx.thir_body(def)?;
417
418         AbstractConstBuilder::new(tcx, (&*body.0.borrow(), body.1))?
419             .map(AbstractConstBuilder::build)
420             .transpose()
421     } else {
422         Ok(None)
423     }
424 }
425
426 pub fn provide(providers: &mut ty::query::Providers) {
427     *providers = ty::query::Providers {
428         destructure_const,
429         thir_abstract_const: |tcx, def_id| {
430             let def_id = def_id.expect_local();
431             if let Some(def) = ty::WithOptConstParam::try_lookup(def_id, tcx) {
432                 tcx.thir_abstract_const_of_const_arg(def)
433             } else {
434                 thir_abstract_const(tcx, ty::WithOptConstParam::unknown(def_id))
435             }
436         },
437         thir_abstract_const_of_const_arg: |tcx, (did, param_did)| {
438             thir_abstract_const(
439                 tcx,
440                 ty::WithOptConstParam { did, const_param_did: Some(param_did) },
441             )
442         },
443         ..*providers
444     };
445 }