rust/compiler/rustc_mir_build/src/build/expr/as_constant.rs

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

153 lines
6.8 KiB
Rust
Raw Normal View History

2015-08-18 17:59:21 -04:00
//! See docs in build/expr/mod.rs
use crate::build::{parse_float_into_constval, Builder};
use rustc_ast as ast;
2022-03-11 12:07:53 +01:00
use rustc_hir::def_id::DefId;
use rustc_middle::mir::interpret::{
Allocation, ConstValue, LitToConstError, LitToConstInput, Scalar,
};
2020-03-29 16:41:09 +02:00
use rustc_middle::mir::*;
2021-04-04 18:42:17 +02:00
use rustc_middle::thir::*;
2022-03-11 12:07:53 +01:00
use rustc_middle::ty::subst::SubstsRef;
use rustc_middle::ty::{self, CanonicalUserTypeAnnotation, Ty, TyCtxt};
use rustc_target::abi::Size;
2015-08-18 17:59:21 -04:00
impl<'a, 'tcx> Builder<'a, 'tcx> {
2015-08-18 17:59:21 -04:00
/// Compile `expr`, yielding a compile-time constant. Assumes that
/// `expr` is a valid compile-time constant!
pub(crate) fn as_constant(&mut self, expr: &Expr<'tcx>) -> Constant<'tcx> {
2022-03-11 12:07:53 +01:00
let create_uneval_from_def_id =
|tcx: TyCtxt<'tcx>, def_id: DefId, ty: Ty<'tcx>, substs: SubstsRef<'tcx>| {
let uneval = ty::Unevaluated::new(ty::WithOptConstParam::unknown(def_id), substs);
tcx.mk_const(ty::ConstS { kind: ty::ConstKind::Unevaluated(uneval), ty })
2022-03-11 12:07:53 +01:00
};
2015-08-18 17:59:21 -04:00
let this = self;
2022-03-11 12:07:53 +01:00
let tcx = this.tcx;
2021-03-06 22:24:04 +01:00
let Expr { ty, temp_lifetime: _, span, ref kind } = *expr;
match *kind {
ExprKind::Scope { region_scope: _, lint_level: _, value } => {
this.as_constant(&this.thir[value])
}
2022-03-11 12:07:53 +01:00
ExprKind::Literal { lit, neg } => {
2022-03-23 19:41:35 +01:00
let literal =
2022-04-08 11:56:21 +02:00
match lit_to_mir_constant(tcx, LitToConstInput { lit: &lit.node, ty, neg }) {
2022-03-23 19:41:35 +01:00
Ok(c) => c,
Err(LitToConstError::Reported) => ConstantKind::Ty(tcx.const_error(ty)),
Err(LitToConstError::TypeError) => {
bug!("encountered type error in `lit_to_mir_constant")
2022-03-23 19:41:35 +01:00
}
};
2022-03-11 12:07:53 +01:00
2022-04-13 22:51:34 +02:00
Constant { span, user_ty: None, literal }
2022-03-11 12:07:53 +01:00
}
ExprKind::NonHirLiteral { lit, ref user_ty } => {
let user_ty = user_ty.as_ref().map(|user_ty| {
2022-03-11 12:07:53 +01:00
this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
span,
user_ty: user_ty.clone(),
2022-03-11 12:07:53 +01:00
inferred_ty: ty,
})
});
let literal = ConstantKind::Val(ConstValue::Scalar(Scalar::Int(lit)), ty);
Constant { span, user_ty: user_ty, literal }
}
ExprKind::ZstLiteral { ref user_ty } => {
let user_ty = user_ty.as_ref().map(|user_ty| {
this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
span,
user_ty: user_ty.clone(),
inferred_ty: ty,
})
});
2022-07-06 10:14:46 -04:00
let literal = ConstantKind::Val(ConstValue::ZeroSized, ty);
Constant { span, user_ty: user_ty, literal }
}
ExprKind::NamedConst { def_id, substs, ref user_ty } => {
let user_ty = user_ty.as_ref().map(|user_ty| {
2022-03-11 12:07:53 +01:00
this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
span,
user_ty: user_ty.clone(),
2022-03-11 12:07:53 +01:00
inferred_ty: ty,
})
});
let literal = ConstantKind::Ty(create_uneval_from_def_id(tcx, def_id, ty, substs));
Constant { user_ty, span, literal }
}
2022-03-15 16:32:40 +01:00
ExprKind::ConstParam { param, def_id: _ } => {
let const_param =
tcx.mk_const(ty::ConstS { kind: ty::ConstKind::Param(param), ty: expr.ty });
2022-03-15 16:32:40 +01:00
let literal = ConstantKind::Ty(const_param);
2022-03-11 12:07:53 +01:00
2022-03-15 16:20:46 +01:00
Constant { user_ty: None, span, literal }
2022-03-11 12:07:53 +01:00
}
ExprKind::ConstBlock { did: def_id, substs } => {
let literal = ConstantKind::Ty(create_uneval_from_def_id(tcx, def_id, ty, substs));
Constant { user_ty: None, span, literal }
2021-02-24 21:29:09 +01:00
}
ExprKind::StaticRef { alloc_id, ty, .. } => {
2022-03-11 12:07:53 +01:00
let const_val = ConstValue::Scalar(Scalar::from_pointer(alloc_id.into(), &tcx));
let literal = ConstantKind::Val(const_val, ty);
Constant { span, user_ty: None, literal }
2021-03-12 13:46:39 +00:00
}
2021-03-06 22:24:04 +01:00
_ => span_bug!(span, "expression is not a valid constant {:?}", kind),
}
2015-08-18 17:59:21 -04:00
}
}
#[instrument(skip(tcx, lit_input))]
pub(crate) fn lit_to_mir_constant<'tcx>(
tcx: TyCtxt<'tcx>,
lit_input: LitToConstInput<'tcx>,
) -> Result<ConstantKind<'tcx>, LitToConstError> {
let LitToConstInput { lit, ty, neg } = lit_input;
let trunc = |n| {
let param_ty = ty::ParamEnv::reveal_all().and(ty);
let width = tcx.layout_of(param_ty).map_err(|_| LitToConstError::Reported)?.size;
trace!("trunc {} with size {} and shift {}", n, width.bits(), 128 - width.bits());
let result = width.truncate(n);
trace!("trunc result: {}", result);
Ok(ConstValue::Scalar(Scalar::from_uint(result, width)))
};
let value = match (lit, &ty.kind()) {
(ast::LitKind::Str(s, _), ty::Ref(_, inner_ty, _)) if inner_ty.is_str() => {
let s = s.as_str();
let allocation = Allocation::from_bytes_byte_aligned_immutable(s.as_bytes());
let allocation = tcx.intern_const_alloc(allocation);
ConstValue::Slice { data: allocation, start: 0, end: s.len() }
}
(ast::LitKind::ByteStr(data), ty::Ref(_, inner_ty, _))
if matches!(inner_ty.kind(), ty::Slice(_)) =>
{
let allocation = Allocation::from_bytes_byte_aligned_immutable(data as &[u8]);
let allocation = tcx.intern_const_alloc(allocation);
ConstValue::Slice { data: allocation, start: 0, end: data.len() }
}
(ast::LitKind::ByteStr(data), ty::Ref(_, inner_ty, _)) if inner_ty.is_array() => {
let id = tcx.allocate_bytes(data);
ConstValue::Scalar(Scalar::from_pointer(id.into(), &tcx))
}
(ast::LitKind::Byte(n), ty::Uint(ty::UintTy::U8)) => {
ConstValue::Scalar(Scalar::from_uint(*n, Size::from_bytes(1)))
}
(ast::LitKind::Int(n, _), ty::Uint(_)) | (ast::LitKind::Int(n, _), ty::Int(_)) => {
trunc(if neg { (*n as i128).overflowing_neg().0 as u128 } else { *n })?
}
(ast::LitKind::Float(n, _), ty::Float(fty)) => {
parse_float_into_constval(*n, *fty, neg).ok_or(LitToConstError::Reported)?
}
(ast::LitKind::Bool(b), ty::Bool) => ConstValue::Scalar(Scalar::from_bool(*b)),
(ast::LitKind::Char(c), ty::Char) => ConstValue::Scalar(Scalar::from_char(*c)),
(ast::LitKind::Err, _) => return Err(LitToConstError::Reported),
_ => return Err(LitToConstError::TypeError),
};
Ok(ConstantKind::Val(value, ty))
}