rust/src/librustc_mir_build/build/expr/as_constant.rs

40 lines
1.4 KiB
Rust
Raw Normal View History

2015-08-18 23:59:21 +02:00
//! See docs in build/expr/mod.rs
2019-02-07 22:28:15 +01:00
use crate::build::Builder;
use crate::hair::*;
2016-09-19 22:50:00 +02:00
use rustc::mir::*;
2019-01-06 18:10:53 +01:00
use rustc::ty::CanonicalUserTypeAnnotation;
2015-08-18 23:59:21 +02:00
impl<'a, 'tcx> Builder<'a, 'tcx> {
2015-08-18 23:59:21 +02:00
/// Compile `expr`, yielding a compile-time constant. Assumes that
/// `expr` is a valid compile-time constant!
crate fn as_constant<M>(&mut self, expr: M) -> Constant<'tcx>
2018-09-06 23:34:26 +02:00
where
M: Mirror<'tcx, Output = Expr<'tcx>>,
2015-08-18 23:59:21 +02:00
{
let expr = self.hir.mirror(expr);
self.expr_as_constant(expr)
}
fn expr_as_constant(&mut self, expr: Expr<'tcx>) -> Constant<'tcx> {
2015-08-18 23:59:21 +02:00
let this = self;
2019-12-22 23:42:04 +01:00
let Expr { ty, temp_lifetime: _, span, kind } = expr;
match kind {
2019-12-22 23:42:04 +01:00
ExprKind::Scope { region_scope: _, lint_level: _, value } => this.as_constant(value),
ExprKind::Literal { literal, user_ty } => {
let user_ty = user_ty.map(|user_ty| {
2019-01-06 18:10:53 +01:00
this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
span,
user_ty,
inferred_ty: ty,
2019-01-06 18:10:53 +01:00
})
});
assert_eq!(literal.ty, ty);
2019-12-22 23:42:04 +01:00
Constant { span, user_ty, literal }
2019-11-19 00:04:06 +01:00
}
2019-12-22 23:42:04 +01:00
ExprKind::StaticRef { literal, .. } => Constant { span, user_ty: None, literal },
2018-09-06 23:34:26 +02:00
_ => span_bug!(span, "expression is not a valid constant {:?}", kind),
}
2015-08-18 23:59:21 +02:00
}
}