]> git.proxmox.com Git - rustc.git/blob - src/librustc_mir_build/build/expr/as_constant.rs
New upstream version 1.44.1+dfsg1
[rustc.git] / src / librustc_mir_build / build / expr / as_constant.rs
1 //! See docs in build/expr/mod.rs
2
3 use crate::build::Builder;
4 use crate::hair::*;
5 use rustc_middle::mir::*;
6 use rustc_middle::ty::CanonicalUserTypeAnnotation;
7
8 impl<'a, 'tcx> Builder<'a, 'tcx> {
9 /// Compile `expr`, yielding a compile-time constant. Assumes that
10 /// `expr` is a valid compile-time constant!
11 crate fn as_constant<M>(&mut self, expr: M) -> Constant<'tcx>
12 where
13 M: Mirror<'tcx, Output = Expr<'tcx>>,
14 {
15 let expr = self.hir.mirror(expr);
16 self.expr_as_constant(expr)
17 }
18
19 fn expr_as_constant(&mut self, expr: Expr<'tcx>) -> Constant<'tcx> {
20 let this = self;
21 let Expr { ty, temp_lifetime: _, span, kind } = expr;
22 match kind {
23 ExprKind::Scope { region_scope: _, lint_level: _, value } => this.as_constant(value),
24 ExprKind::Literal { literal, user_ty } => {
25 let user_ty = user_ty.map(|user_ty| {
26 this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
27 span,
28 user_ty,
29 inferred_ty: ty,
30 })
31 });
32 assert_eq!(literal.ty, ty);
33 Constant { span, user_ty, literal }
34 }
35 ExprKind::StaticRef { literal, .. } => Constant { span, user_ty: None, literal },
36 _ => span_bug!(span, "expression is not a valid constant {:?}", kind),
37 }
38 }
39 }