1use rustc_errors::ErrorGuaranteed;
2use rustc_hir::def::DefKind;
3use rustc_hir::def_id::LocalDefId;
4use rustc_middle::query::Providers;
5use rustc_middle::thir::visit;
6use rustc_middle::thir::visit::Visitor;
7use rustc_middle::ty::abstract_const::CastKind;
8use rustc_middle::ty::{self, Expr, LitToConstInput, TyCtxt, TypeVisitableExt};
9use rustc_middle::{mir, thir};
10use rustc_span::{Span, bug};
11use tracing::instrument;
12
13use crate::diagnostics::{GenericConstantTooComplex, GenericConstantTooComplexSub};
14
15fn check_binop(op: mir::BinOp) -> bool {
17 use mir::BinOp::*;
18 match op {
19 Add | AddUnchecked | AddWithOverflow | Sub | SubUnchecked | SubWithOverflow | Mul
20 | MulUnchecked | MulWithOverflow | Div | Rem | BitXor | BitAnd | BitOr | Shl
21 | ShlUnchecked | Shr | ShrUnchecked | Eq | Lt | Le | Ne | Ge | Gt | Cmp => true,
22 Offset => false,
23 }
24}
25
26fn check_unop(op: mir::UnOp) -> bool {
29 use mir::UnOp::*;
30 match op {
31 Not | Neg | PtrMetadata => true,
32 }
33}
34
35fn recurse_build<'tcx>(
36 tcx: TyCtxt<'tcx>,
37 body: &thir::Thir<'tcx>,
38 node: thir::ExprId,
39 root_span: Span,
40) -> Result<ty::Const<'tcx>, ErrorGuaranteed> {
41 use thir::ExprKind;
42 let node = &body.exprs[node];
43
44 let maybe_supported_error = |a| maybe_supported_error(tcx, a, root_span);
45 let error = |a| error(tcx, a, root_span);
46
47 Ok(match &node.kind {
48 &ExprKind::Scope { value, .. } => recurse_build(tcx, body, value, root_span)?,
50 &ExprKind::PlaceTypeAscription { source, .. }
51 | &ExprKind::ValueTypeAscription { source, .. } => {
52 recurse_build(tcx, body, source, root_span)?
53 }
54 &ExprKind::PlaceUnwrapUnsafeBinder { .. }
55 | &ExprKind::ValueUnwrapUnsafeBinder { .. }
56 | &ExprKind::WrapUnsafeBinder { .. } => {
57 {
::core::panicking::panic_fmt(format_args!("not implemented: {0}",
format_args!("FIXME(unsafe_binders)")));
}unimplemented!("FIXME(unsafe_binders)")
58 }
59 &ExprKind::Literal { lit, neg } => {
60 let sp = node.span;
61 match tcx.at(sp).lit_to_const(LitToConstInput { lit: lit.node, ty: Some(node.ty), neg })
62 {
63 Some(value) => ty::Const::new_value(tcx, value.valtree, value.ty),
64 None => ty::Const::new_misc_error(tcx),
65 }
66 }
67 &ExprKind::NonHirLiteral { lit, user_ty: _ } => {
68 let val = ty::ValTree::from_scalar_int(tcx, lit);
69 ty::Const::new_value(tcx, val, node.ty)
70 }
71 &ExprKind::ZstLiteral { user_ty: _ } => ty::Const::zero_sized(tcx, node.ty),
72 &ExprKind::NamedConst { def_id, args, user_ty: _ } => {
73 let kind = match tcx.def_kind(def_id) {
74 DefKind::AssocConst => {
75 if let DefKind::Impl { of_trait: false } = tcx.def_kind(tcx.parent(def_id)) {
76 ty::AliasConstKind::InherentImpl { def_id }
77 } else {
78 ty::AliasConstKind::Projection { def_id }
79 }
80 }
81 DefKind::Const => ty::AliasConstKind::Free { def_id },
82 DefKind::AnonConst => ty::AliasConstKind::Anon { def_id },
83 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:?}"),
84 };
85
86 let alias = ty::AliasConst::new(tcx, kind, args);
87 ty::Const::new_alias(tcx, ty::IsRigid::No, alias)
88 }
89 ExprKind::ConstParam { param, .. } => ty::Const::new_param(tcx, *param),
90
91 ExprKind::Call { fun, args, .. } => {
92 let fun_ty = body.exprs[*fun].ty;
93 let fun = recurse_build(tcx, body, *fun, root_span)?;
94
95 let mut new_args = Vec::<ty::Const<'tcx>>::with_capacity(args.len());
96 for &id in args.iter() {
97 new_args.push(recurse_build(tcx, body, id, root_span)?);
98 }
99 ty::Const::new_expr(tcx, Expr::new_call(tcx, fun_ty, fun, new_args))
100 }
101 &ExprKind::Binary { op, lhs, rhs } if check_binop(op) => {
102 let lhs_ty = body.exprs[lhs].ty;
103 let lhs = recurse_build(tcx, body, lhs, root_span)?;
104 let rhs_ty = body.exprs[rhs].ty;
105 let rhs = recurse_build(tcx, body, rhs, root_span)?;
106 ty::Const::new_expr(tcx, Expr::new_binop(tcx, op, lhs_ty, rhs_ty, lhs, rhs))
107 }
108 &ExprKind::Unary { op, arg } if check_unop(op) => {
109 let arg_ty = body.exprs[arg].ty;
110 let arg = recurse_build(tcx, body, arg, root_span)?;
111 ty::Const::new_expr(tcx, Expr::new_unop(tcx, op, arg_ty, arg))
112 }
113 ExprKind::Block { block } => {
121 if let thir::Block { stmts: [], expr: Some(e), .. } = &body.blocks[*block] {
122 recurse_build(tcx, body, *e, root_span)?
123 } else {
124 maybe_supported_error(GenericConstantTooComplexSub::BlockNotSupported(node.span))?
125 }
126 }
127 &ExprKind::ValueExpr { source } => {
131 let value_ty = body.exprs[source].ty;
132 let value = recurse_build(tcx, body, source, root_span)?;
133 ty::Const::new_expr(tcx, Expr::new_cast(tcx, CastKind::Use, value_ty, value, node.ty))
134 }
135 &ExprKind::Cast { source } => {
136 let value_ty = body.exprs[source].ty;
137 let value = recurse_build(tcx, body, source, root_span)?;
138 ty::Const::new_expr(tcx, Expr::new_cast(tcx, CastKind::As, value_ty, value, node.ty))
139 }
140 ExprKind::Borrow { arg, .. } => {
141 let arg_node = &body.exprs[*arg];
142
143 if let ExprKind::Deref { arg } = arg_node.kind {
147 recurse_build(tcx, body, arg, root_span)?
148 } else {
149 maybe_supported_error(GenericConstantTooComplexSub::BorrowNotSupported(node.span))?
150 }
151 }
152 ExprKind::RawBorrow { .. } | ExprKind::Deref { .. } => maybe_supported_error(
154 GenericConstantTooComplexSub::AddressAndDerefNotSupported(node.span),
155 )?,
156 ExprKind::Repeat { .. } | ExprKind::Array { .. } => {
157 maybe_supported_error(GenericConstantTooComplexSub::ArrayNotSupported(node.span))?
158 }
159 ExprKind::NeverToAny { .. } => {
160 maybe_supported_error(GenericConstantTooComplexSub::NeverToAnyNotSupported(node.span))?
161 }
162 ExprKind::Tuple { .. } => {
163 maybe_supported_error(GenericConstantTooComplexSub::TupleNotSupported(node.span))?
164 }
165 ExprKind::Index { .. } => {
166 maybe_supported_error(GenericConstantTooComplexSub::IndexNotSupported(node.span))?
167 }
168 ExprKind::Field { .. } => {
169 maybe_supported_error(GenericConstantTooComplexSub::FieldNotSupported(node.span))?
170 }
171 ExprKind::ConstBlock { .. } => {
172 maybe_supported_error(GenericConstantTooComplexSub::ConstBlockNotSupported(node.span))?
173 }
174 ExprKind::Adt(_) => {
175 maybe_supported_error(GenericConstantTooComplexSub::AdtNotSupported(node.span))?
176 }
177 ExprKind::PointerCoercion { .. } => {
179 error(GenericConstantTooComplexSub::PointerNotSupported(node.span))?
180 }
181 ExprKind::Yield { .. } => {
182 error(GenericConstantTooComplexSub::YieldNotSupported(node.span))?
183 }
184 ExprKind::Continue { .. }
185 | ExprKind::ConstContinue { .. }
186 | ExprKind::Break { .. }
187 | ExprKind::Loop { .. }
188 | ExprKind::LoopMatch { .. } => {
189 error(GenericConstantTooComplexSub::LoopNotSupported(node.span))?
190 }
191 ExprKind::ByUse { .. } => {
192 error(GenericConstantTooComplexSub::ByUseNotSupported(node.span))?
193 }
194 ExprKind::Unary { .. } => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
195 ExprKind::Binary { .. } => {
197 error(GenericConstantTooComplexSub::BinaryNotSupported(node.span))?
198 }
199 ExprKind::LogicalOp { .. } => {
200 error(GenericConstantTooComplexSub::LogicalOpNotSupported(node.span))?
201 }
202 ExprKind::Assign { .. } | ExprKind::AssignOp { .. } => {
203 error(GenericConstantTooComplexSub::AssignNotSupported(node.span))?
204 }
205 ExprKind::Closure { .. } | ExprKind::Return { .. } | ExprKind::Become { .. } => {
207 error(GenericConstantTooComplexSub::ClosureAndReturnNotSupported(node.span))?
208 }
209 ExprKind::Match { .. } | ExprKind::If { .. } | ExprKind::Let { .. } => {
211 error(GenericConstantTooComplexSub::ControlFlowNotSupported(node.span))?
212 }
213 ExprKind::InlineAsm { .. } => {
214 error(GenericConstantTooComplexSub::InlineAsmNotSupported(node.span))?
215 }
216
217 ExprKind::VarRef { .. }
219 | ExprKind::UpvarRef { .. }
220 | ExprKind::StaticRef { .. }
221 | ExprKind::ThreadLocalRef(_) => {
222 error(GenericConstantTooComplexSub::OperationNotSupported(node.span))?
223 }
224 ExprKind::Reborrow { .. } => {
225 ::core::panicking::panic("not implemented");unimplemented!();
226 }
227 })
228}
229
230struct IsThirPolymorphic<'a, 'tcx> {
231 is_poly: bool,
232 thir: &'a thir::Thir<'tcx>,
233}
234
235fn error(
236 tcx: TyCtxt<'_>,
237 sub: GenericConstantTooComplexSub,
238 root_span: Span,
239) -> Result<!, ErrorGuaranteed> {
240 let reported = tcx.dcx().emit_err(GenericConstantTooComplex {
241 span: root_span,
242 maybe_supported: false,
243 sub,
244 });
245
246 Err(reported)
247}
248
249fn maybe_supported_error(
250 tcx: TyCtxt<'_>,
251 sub: GenericConstantTooComplexSub,
252 root_span: Span,
253) -> Result<!, ErrorGuaranteed> {
254 let reported = tcx.dcx().emit_err(GenericConstantTooComplex {
255 span: root_span,
256 maybe_supported: true,
257 sub,
258 });
259
260 Err(reported)
261}
262
263impl<'a, 'tcx> IsThirPolymorphic<'a, 'tcx> {
264 fn expr_is_poly(&mut self, expr: &thir::Expr<'tcx>) -> bool {
265 if expr.ty.has_non_region_param() {
266 return true;
267 }
268
269 match expr.kind {
270 thir::ExprKind::NamedConst { args, .. } | thir::ExprKind::ConstBlock { args, .. } => {
271 args.has_non_region_param()
272 }
273 thir::ExprKind::ConstParam { .. } => true,
274 thir::ExprKind::Repeat { value, count } => {
275 self.visit_expr(&self.thir()[value]);
276 count.has_non_region_param()
277 }
278 thir::ExprKind::Scope { .. }
279 | thir::ExprKind::If { .. }
280 | thir::ExprKind::Call { .. }
281 | thir::ExprKind::ByUse { .. }
282 | thir::ExprKind::Deref { .. }
283 | thir::ExprKind::Binary { .. }
284 | thir::ExprKind::LogicalOp { .. }
285 | thir::ExprKind::Unary { .. }
286 | thir::ExprKind::Cast { .. }
287 | thir::ExprKind::ValueExpr { .. }
288 | thir::ExprKind::NeverToAny { .. }
289 | thir::ExprKind::PointerCoercion { .. }
290 | thir::ExprKind::Loop { .. }
291 | thir::ExprKind::LoopMatch { .. }
292 | thir::ExprKind::Let { .. }
293 | thir::ExprKind::Match { .. }
294 | thir::ExprKind::Block { .. }
295 | thir::ExprKind::Assign { .. }
296 | thir::ExprKind::AssignOp { .. }
297 | thir::ExprKind::Field { .. }
298 | thir::ExprKind::Index { .. }
299 | thir::ExprKind::VarRef { .. }
300 | thir::ExprKind::UpvarRef { .. }
301 | thir::ExprKind::Borrow { .. }
302 | thir::ExprKind::RawBorrow { .. }
303 | thir::ExprKind::Break { .. }
304 | thir::ExprKind::Continue { .. }
305 | thir::ExprKind::ConstContinue { .. }
306 | thir::ExprKind::Return { .. }
307 | thir::ExprKind::Become { .. }
308 | thir::ExprKind::Array { .. }
309 | thir::ExprKind::Tuple { .. }
310 | thir::ExprKind::Adt(_)
311 | thir::ExprKind::PlaceTypeAscription { .. }
312 | thir::ExprKind::ValueTypeAscription { .. }
313 | thir::ExprKind::PlaceUnwrapUnsafeBinder { .. }
314 | thir::ExprKind::ValueUnwrapUnsafeBinder { .. }
315 | thir::ExprKind::WrapUnsafeBinder { .. }
316 | thir::ExprKind::Closure(_)
317 | thir::ExprKind::Literal { .. }
318 | thir::ExprKind::NonHirLiteral { .. }
319 | thir::ExprKind::ZstLiteral { .. }
320 | thir::ExprKind::StaticRef { .. }
321 | thir::ExprKind::InlineAsm(_)
322 | thir::ExprKind::ThreadLocalRef(_)
323 | thir::ExprKind::Yield { .. } => false,
324 thir::ExprKind::Reborrow { .. } => {
325 ::core::panicking::panic("not implemented");unimplemented!();
326 }
327 }
328 }
329 fn pat_is_poly(&mut self, pat: &thir::Pat<'tcx>) -> bool {
330 if pat.ty.has_non_region_param() {
331 return true;
332 }
333
334 match pat.kind {
335 thir::PatKind::Constant { value } => value.has_non_region_param(),
336 thir::PatKind::Range(ref range) => {
337 let &thir::PatRange { lo, hi, .. } = range.as_ref();
338 lo.has_non_region_param() || hi.has_non_region_param()
339 }
340 _ => false,
341 }
342 }
343}
344
345impl<'a, 'tcx> visit::Visitor<'a, 'tcx> for IsThirPolymorphic<'a, 'tcx> {
346 fn thir(&self) -> &'a thir::Thir<'tcx> {
347 self.thir
348 }
349
350 {}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::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("visit_expr",
"rustc_ty_utils::consts", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/1303417c416e1595173d9689e7394c31e136ae95/compiler/rustc_ty_utils/src/consts.rs"),
::tracing_core::__macro_support::Option::Some(350u32),
::tracing_core::__macro_support::Option::Some("rustc_ty_utils::consts"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("expr")
}> =
::tracing::__macro_support::FieldName::new("expr");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::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,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expr)
as &dyn ::tracing::field::Value))])
})
} 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: () = loop {};
return __tracing_attr_fake_return;
}
{
self.is_poly |= self.expr_is_poly(expr);
if !self.is_poly { visit::walk_expr(self, expr) }
}
}
}#[instrument(skip(self), level = "debug")]
351 fn visit_expr(&mut self, expr: &'a thir::Expr<'tcx>) {
352 self.is_poly |= self.expr_is_poly(expr);
353 if !self.is_poly {
354 visit::walk_expr(self, expr)
355 }
356 }
357
358 {}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::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("visit_pat",
"rustc_ty_utils::consts", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/1303417c416e1595173d9689e7394c31e136ae95/compiler/rustc_ty_utils/src/consts.rs"),
::tracing_core::__macro_support::Option::Some(358u32),
::tracing_core::__macro_support::Option::Some("rustc_ty_utils::consts"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("pat")
}> =
::tracing::__macro_support::FieldName::new("pat");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::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,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&pat)
as &dyn ::tracing::field::Value))])
})
} 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: () = loop {};
return __tracing_attr_fake_return;
}
{
self.is_poly |= self.pat_is_poly(pat);
if !self.is_poly { visit::walk_pat(self, pat); }
}
}
}#[instrument(skip(self), level = "debug")]
359 fn visit_pat(&mut self, pat: &'a thir::Pat<'tcx>) {
360 self.is_poly |= self.pat_is_poly(pat);
361 if !self.is_poly {
362 visit::walk_pat(self, pat);
363 }
364 }
365}
366
367fn thir_abstract_const<'tcx>(
369 tcx: TyCtxt<'tcx>,
370 def: LocalDefId,
371) -> Result<Option<ty::EarlyBinder<'tcx, ty::Const<'tcx>>>, ErrorGuaranteed> {
372 if !tcx.features().generic_const_exprs() {
373 return Ok(None);
374 }
375
376 match tcx.def_kind(def) {
377 DefKind::AnonConst => (),
383 _ => return Ok(None),
384 }
385
386 let body = tcx.thir_body(def)?;
387 let (body, body_id) = (&*body.0.borrow(), body.1);
388
389 let mut is_poly_vis = IsThirPolymorphic { is_poly: false, thir: body };
390 visit::walk_expr(&mut is_poly_vis, &body[body_id]);
391 if !is_poly_vis.is_poly {
392 return Ok(None);
393 }
394
395 let root_span = body.exprs[body_id].span;
396
397 Ok(Some(ty::EarlyBinder::bind(tcx, recurse_build(tcx, body, body_id, root_span)?)))
398}
399
400pub(crate) fn provide(providers: &mut Providers) {
401 *providers = Providers { thir_abstract_const, ..*providers };
402}