1use rustc_abi::Size;
4use rustc_ast as ast;
5use rustc_attr_ir::lang_items::LangItem;
6use rustc_hir::def::DefKind;
7use rustc_middle::mir;
8use rustc_middle::mir::interpret::{CTFE_ALLOC_SALT, Scalar};
9use rustc_middle::mir::*;
10use rustc_middle::thir::*;
11use rustc_middle::ty::{
12 self, CanonicalUserType, CanonicalUserTypeAnnotation, LitToConstInput, Ty, TyCtxt,
13 TypeVisitableExt as _, UserTypeAnnotationIndex,
14};
15use rustc_span::{bug, span_bug};
16use tracing::{instrument, trace};
17
18use crate::builder::{Builder, parse_float_into_constval};
19
20impl<'a, 'tcx> Builder<'a, 'tcx> {
21 pub(crate) fn as_constant(&mut self, expr: &Expr<'tcx>) -> ConstOperand<'tcx> {
24 let this = self; let tcx = this.tcx;
26 let Expr { ty, temp_scope_id: _, span, ref kind } = *expr;
27 match kind {
28 ExprKind::Scope { region_scope: _, hir_id: _, value } => {
29 this.as_constant(&this.thir[*value])
30 }
31 _ => as_constant_inner(
32 expr,
33 |user_ty| {
34 Some(this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
35 span,
36 user_ty: user_ty.clone(),
37 inferred_ty: ty,
38 }))
39 },
40 tcx,
41 ),
42 }
43 }
44}
45
46pub(crate) fn as_constant_inner<'tcx>(
47 expr: &Expr<'tcx>,
48 push_cuta: impl FnMut(&Box<CanonicalUserType<'tcx>>) -> Option<UserTypeAnnotationIndex>,
49 tcx: TyCtxt<'tcx>,
50) -> ConstOperand<'tcx> {
51 let Expr { ty, temp_scope_id: _, span, ref kind } = *expr;
52
53 match *kind {
54 ExprKind::Literal { lit, neg } => {
55 let const_ =
56 lit_to_mir_constant(tcx, LitToConstInput { lit: lit.node, ty: Some(ty), neg });
57
58 ConstOperand { span, user_ty: None, const_ }
59 }
60 ExprKind::NonHirLiteral { lit, ref user_ty } => {
61 let user_ty = user_ty.as_ref().and_then(push_cuta);
62
63 let const_ = Const::Val(ConstValue::Scalar(Scalar::Int(lit)), ty);
64
65 ConstOperand { span, user_ty, const_ }
66 }
67 ExprKind::ZstLiteral { ref user_ty } => {
68 let user_ty = user_ty.as_ref().and_then(push_cuta);
69
70 let const_ = Const::Val(ConstValue::ZeroSized, ty);
71
72 ConstOperand { span, user_ty, const_ }
73 }
74 ExprKind::NamedConst { def_id, args, ref user_ty } => {
75 let user_ty = user_ty.as_ref().and_then(push_cuta);
76
77 let get_kind = |def_id, def_kind| match def_kind {
78 DefKind::AssocConst => {
79 if let DefKind::Impl { of_trait: false } = tcx.def_kind(tcx.parent(def_id)) {
80 ty::AliasConstKind::InherentImpl { def_id }
81 } else {
82 ty::AliasConstKind::Projection { def_id }
83 }
84 }
85 DefKind::Const => ty::AliasConstKind::Free { def_id },
86 kind => ::rustc_span::macros::bug_impl(None,
format_args!("unexpected DefKind in THIR ExprKind::NamedConst: {0:?}",
kind), Location::caller())bug!("unexpected DefKind in THIR ExprKind::NamedConst: {kind:?}"),
87 };
88
89 let could_be_direct_const = |def_id| {
90 let def_kind = tcx.def_kind(def_id);
91 let (DefKind::Const | DefKind::AssocConst) = def_kind else {
92 return None;
93 };
94 if tcx.is_direct_const(def_id) {
95 return Some(get_kind(def_id, def_kind));
96 }
97 if tcx.features().gca_const_items()
104 && let kind @ ty::AliasConstKind::Projection { .. } = get_kind(def_id, def_kind)
105 {
106 return Some(kind);
107 }
108 None
109 };
110
111 if let Some(kind) = could_be_direct_const(def_id) {
112 let alias = ty::AliasConst::new(tcx, kind, args);
113 let ct = ty::Const::new_alias(tcx, ty::IsRigid::No, alias);
114 let const_ = Const::Ty(ty, ct);
115 return ConstOperand { span, user_ty, const_ };
116 }
117
118 let uneval = mir::UnevaluatedConst::new(def_id, args);
119 let const_ = Const::Unevaluated(uneval, ty);
120 ConstOperand { user_ty, span, const_ }
121 }
122 ExprKind::ConstParam { param, def_id: _ } => {
123 let const_param = ty::Const::new_param(tcx, param);
124 let const_ = Const::Ty(expr.ty, const_param);
125
126 ConstOperand { user_ty: None, span, const_ }
127 }
128 ExprKind::ConstBlock { did: def_id, args } => {
129 let uneval = mir::UnevaluatedConst::new(def_id, args);
130 let const_ = Const::Unevaluated(uneval, ty);
131
132 ConstOperand { user_ty: None, span, const_ }
133 }
134 ExprKind::StaticRef { alloc_id, ty, .. } => {
135 let const_val = ConstValue::Scalar(Scalar::from_pointer(alloc_id.into(), &tcx));
136 let const_ = Const::Val(const_val, ty);
137
138 ConstOperand { span, user_ty: None, const_ }
139 }
140 _ => ::rustc_span::macros::bug_impl(Some(span),
format_args!("expression is not a valid constant {0:?}", kind),
Location::caller())span_bug!(span, "expression is not a valid constant {:?}", kind),
141 }
142}
143
144{}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("lit_to_mir_constant",
"rustc_mir_build::builder::expr::as_constant",
::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/1d81eb4ad9cd207e3e638bd32b17ec4fce8412a6/compiler/rustc_mir_build/src/builder/expr/as_constant.rs"),
::tracing_core::__macro_support::Option::Some(144u32),
::tracing_core::__macro_support::Option::Some("rustc_mir_build::builder::expr::as_constant"),
::tracing_core::field::FieldSet::new(&[],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::INFO <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{ meta.fields().value_set_all(&[]) })
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Const<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{
let LitToConstInput { lit, ty, neg } = lit_input;
let ty = ty.expect("type of literal must be known at this point");
if let Err(guar) = ty.error_reported() {
return Const::Ty(Ty::new_error(tcx, guar),
ty::Const::new_error(tcx, guar));
}
let lit_ty =
match *ty.kind() { ty::Pat(base, _) => base, _ => ty, };
let trunc =
|n|
{
let width = lit_ty.primitive_size(tcx);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/1d81eb4ad9cd207e3e638bd32b17ec4fce8412a6/compiler/rustc_mir_build/src/builder/expr/as_constant.rs:161",
"rustc_mir_build::builder::expr::as_constant",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("/rustc-dev/1d81eb4ad9cd207e3e638bd32b17ec4fce8412a6/compiler/rustc_mir_build/src/builder/expr/as_constant.rs"),
::tracing_core::__macro_support::Option::Some(161u32),
::tracing_core::__macro_support::Option::Some("rustc_mir_build::builder::expr::as_constant"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("trunc {0} with size {1} and shift {2}",
n, width.bits(), 128 - width.bits()) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};
let result = width.truncate(n);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/1d81eb4ad9cd207e3e638bd32b17ec4fce8412a6/compiler/rustc_mir_build/src/builder/expr/as_constant.rs:163",
"rustc_mir_build::builder::expr::as_constant",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("/rustc-dev/1d81eb4ad9cd207e3e638bd32b17ec4fce8412a6/compiler/rustc_mir_build/src/builder/expr/as_constant.rs"),
::tracing_core::__macro_support::Option::Some(163u32),
::tracing_core::__macro_support::Option::Some("rustc_mir_build::builder::expr::as_constant"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("trunc result: {0}",
result) as &dyn ::tracing::field::Value))])
});
} else { ; }
};
ConstValue::Scalar(Scalar::from_uint(result, width))
};
let value =
match (lit, lit_ty.kind()) {
(ast::LitKind::Str(s, _), ty::Ref(_, inner_ty, _)) if
inner_ty.is_str() => {
let s = s.as_str().as_bytes();
let len = s.len();
let allocation =
tcx.allocate_bytes_dedup(s, CTFE_ALLOC_SALT);
ConstValue::Slice {
alloc_id: allocation,
meta: len.try_into().unwrap(),
}
}
(ast::LitKind::ByteStr(byte_sym, _),
ty::Ref(_, inner_ty, _)) if
#[allow(non_exhaustive_omitted_patterns)] match inner_ty.kind()
{
ty::Slice(_) => true,
_ => false,
} => {
let data = byte_sym.as_byte_str();
let len = data.len();
let allocation =
tcx.allocate_bytes_dedup(data, CTFE_ALLOC_SALT);
ConstValue::Slice {
alloc_id: allocation,
meta: len.try_into().unwrap(),
}
}
(ast::LitKind::ByteStr(byte_sym, _),
ty::Ref(_, inner_ty, _)) if inner_ty.is_array() => {
let id =
tcx.allocate_bytes_dedup(byte_sym.as_byte_str(),
CTFE_ALLOC_SALT);
ConstValue::Scalar(Scalar::from_pointer(id.into(), &tcx))
}
(ast::LitKind::CStr(byte_sym, _), ty::Ref(_, inner_ty, _))
if
#[allow(non_exhaustive_omitted_patterns)] match inner_ty.kind()
{
ty::Adt(def, _) if
tcx.is_lang_item(def.did(), LangItem::CStr) => true,
_ => false,
} => {
let data = byte_sym.as_byte_str();
let len = data.len();
let allocation =
tcx.allocate_bytes_dedup(data, CTFE_ALLOC_SALT);
ConstValue::Slice {
alloc_id: allocation,
meta: len.try_into().unwrap(),
}
}
(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(_)) if !neg =>
trunc(n.get()),
(ast::LitKind::Int(n, _), ty::Int(_)) => {
trunc(if neg {
u128::wrapping_neg(n.get())
} else { n.get() })
}
(ast::LitKind::Float(n, _), ty::Float(fty)) => {
parse_float_into_constval(n, *fty, neg).unwrap()
}
(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(guar), _) => {
return Const::Ty(Ty::new_error(tcx, guar),
ty::Const::new_error(tcx, guar));
}
_ =>
::rustc_span::macros::bug_impl(None,
format_args!("invalid lit/ty combination in `lit_to_mir_constant`: {0:?}: {1:?}",
lit, ty), Location::caller()),
};
Const::Val(value, ty)
}
}
}#[instrument(skip(tcx, lit_input))]
145fn lit_to_mir_constant<'tcx>(tcx: TyCtxt<'tcx>, lit_input: LitToConstInput<'tcx>) -> Const<'tcx> {
146 let LitToConstInput { lit, ty, neg } = lit_input;
147
148 let ty = ty.expect("type of literal must be known at this point");
149
150 if let Err(guar) = ty.error_reported() {
151 return Const::Ty(Ty::new_error(tcx, guar), ty::Const::new_error(tcx, guar));
152 }
153
154 let lit_ty = match *ty.kind() {
155 ty::Pat(base, _) => base,
156 _ => ty,
157 };
158
159 let trunc = |n| {
160 let width = lit_ty.primitive_size(tcx);
161 trace!("trunc {} with size {} and shift {}", n, width.bits(), 128 - width.bits());
162 let result = width.truncate(n);
163 trace!("trunc result: {}", result);
164 ConstValue::Scalar(Scalar::from_uint(result, width))
165 };
166
167 let value = match (lit, lit_ty.kind()) {
168 (ast::LitKind::Str(s, _), ty::Ref(_, inner_ty, _)) if inner_ty.is_str() => {
169 let s = s.as_str().as_bytes();
170 let len = s.len();
171 let allocation = tcx.allocate_bytes_dedup(s, CTFE_ALLOC_SALT);
172 ConstValue::Slice { alloc_id: allocation, meta: len.try_into().unwrap() }
173 }
174 (ast::LitKind::ByteStr(byte_sym, _), ty::Ref(_, inner_ty, _))
175 if matches!(inner_ty.kind(), ty::Slice(_)) =>
176 {
177 let data = byte_sym.as_byte_str();
178 let len = data.len();
179 let allocation = tcx.allocate_bytes_dedup(data, CTFE_ALLOC_SALT);
180 ConstValue::Slice { alloc_id: allocation, meta: len.try_into().unwrap() }
181 }
182 (ast::LitKind::ByteStr(byte_sym, _), ty::Ref(_, inner_ty, _)) if inner_ty.is_array() => {
183 let id = tcx.allocate_bytes_dedup(byte_sym.as_byte_str(), CTFE_ALLOC_SALT);
184 ConstValue::Scalar(Scalar::from_pointer(id.into(), &tcx))
185 }
186 (ast::LitKind::CStr(byte_sym, _), ty::Ref(_, inner_ty, _)) if matches!(inner_ty.kind(), ty::Adt(def, _) if tcx.is_lang_item(def.did(), LangItem::CStr)) =>
187 {
188 let data = byte_sym.as_byte_str();
189 let len = data.len();
190 let allocation = tcx.allocate_bytes_dedup(data, CTFE_ALLOC_SALT);
191 ConstValue::Slice { alloc_id: allocation, meta: len.try_into().unwrap() }
192 }
193 (ast::LitKind::Byte(n), ty::Uint(ty::UintTy::U8)) => {
194 ConstValue::Scalar(Scalar::from_uint(n, Size::from_bytes(1)))
195 }
196 (ast::LitKind::Int(n, _), ty::Uint(_)) if !neg => trunc(n.get()),
197 (ast::LitKind::Int(n, _), ty::Int(_)) => {
198 trunc(if neg { u128::wrapping_neg(n.get()) } else { n.get() })
201 }
202 (ast::LitKind::Float(n, _), ty::Float(fty)) => {
203 parse_float_into_constval(n, *fty, neg).unwrap()
204 }
205 (ast::LitKind::Bool(b), ty::Bool) => ConstValue::Scalar(Scalar::from_bool(b)),
206 (ast::LitKind::Char(c), ty::Char) => ConstValue::Scalar(Scalar::from_char(c)),
207 (ast::LitKind::Err(guar), _) => {
208 return Const::Ty(Ty::new_error(tcx, guar), ty::Const::new_error(tcx, guar));
209 }
210 _ => bug!("invalid lit/ty combination in `lit_to_mir_constant`: {lit:?}: {ty:?}"),
211 };
212
213 Const::Val(value, ty)
214}