Skip to content

Commit 2bca5c4

Browse files
authored
Rollup merge of rust-lang#130714 - compiler-errors:try-structurally-resolve-const, r=BoxyUwU
Introduce `structurally_normalize_const`, use it in `rustc_hir_typeck` Introduces `structurally_normalize_const` to typecking to separate the "eval a const" step from the "try to turn a valtree into a target usize" in HIR typeck, where we may still have infer vars and stuff around. I also changed `check_expr_repeat` to move a double evaluation of a const into a single one. I'll leave inline comments. r? ```@BoxyUwU``` I hesitated to really test this on the new solver where it probably matters for unevaluated consts. If you're worried about the side-effects, I'd be happy to craft some more tests 😄
2 parents 8bb69b1 + 3b8089a commit 2bca5c4

File tree

8 files changed

+122
-39
lines changed

8 files changed

+122
-39
lines changed

compiler/rustc_hir/src/hir.rs

+10-3
Original file line numberDiff line numberDiff line change
@@ -1668,10 +1668,17 @@ pub enum ArrayLen<'hir> {
16681668
}
16691669

16701670
impl ArrayLen<'_> {
1671-
pub fn hir_id(&self) -> HirId {
1671+
pub fn span(self) -> Span {
1672+
match self {
1673+
ArrayLen::Infer(arg) => arg.span,
1674+
ArrayLen::Body(body) => body.span(),
1675+
}
1676+
}
1677+
1678+
pub fn hir_id(self) -> HirId {
16721679
match self {
1673-
ArrayLen::Infer(InferArg { hir_id, .. }) | ArrayLen::Body(ConstArg { hir_id, .. }) => {
1674-
*hir_id
1680+
ArrayLen::Infer(InferArg { hir_id, .. }) | ArrayLen::Body(&ConstArg { hir_id, .. }) => {
1681+
hir_id
16751682
}
16761683
}
16771684
}

compiler/rustc_hir_typeck/src/expr.rs

+35-31
Original file line numberDiff line numberDiff line change
@@ -1491,8 +1491,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
14911491
expr: &'tcx hir::Expr<'tcx>,
14921492
) -> Ty<'tcx> {
14931493
let tcx = self.tcx;
1494-
let count = self.lower_array_length(count);
1495-
if let Some(count) = count.try_eval_target_usize(tcx, self.param_env) {
1494+
let count_span = count.span();
1495+
let count = self.try_structurally_resolve_const(count_span, self.lower_array_length(count));
1496+
1497+
if let Some(count) = count.try_to_target_usize(tcx) {
14961498
self.suggest_array_len(expr, count);
14971499
}
14981500

@@ -1520,19 +1522,24 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
15201522
return Ty::new_error(tcx, guar);
15211523
}
15221524

1523-
self.check_repeat_element_needs_copy_bound(element, count, element_ty);
1525+
// If the length is 0, we don't create any elements, so we don't copy any.
1526+
// If the length is 1, we don't copy that one element, we move it. Only check
1527+
// for `Copy` if the length is larger, or unevaluated.
1528+
// FIXME(min_const_generic_exprs): We could perhaps defer this check so that
1529+
// we don't require `<?0t as Tr>::CONST` doesn't unnecessarily require `Copy`.
1530+
if count.try_to_target_usize(tcx).is_none_or(|x| x > 1) {
1531+
self.enforce_repeat_element_needs_copy_bound(element, element_ty);
1532+
}
15241533

15251534
let ty = Ty::new_array_with_const_len(tcx, t, count);
1526-
15271535
self.register_wf_obligation(ty.into(), expr.span, ObligationCauseCode::WellFormed(None));
1528-
15291536
ty
15301537
}
15311538

1532-
fn check_repeat_element_needs_copy_bound(
1539+
/// Requires that `element_ty` is `Copy` (unless it's a const expression itself).
1540+
fn enforce_repeat_element_needs_copy_bound(
15331541
&self,
15341542
element: &hir::Expr<'_>,
1535-
count: ty::Const<'tcx>,
15361543
element_ty: Ty<'tcx>,
15371544
) {
15381545
let tcx = self.tcx;
@@ -1565,27 +1572,23 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
15651572
_ => traits::IsConstable::No,
15661573
};
15671574

1568-
// If the length is 0, we don't create any elements, so we don't copy any. If the length is 1, we
1569-
// don't copy that one element, we move it. Only check for Copy if the length is larger.
1570-
if count.try_eval_target_usize(tcx, self.param_env).is_none_or(|len| len > 1) {
1571-
let lang_item = self.tcx.require_lang_item(LangItem::Copy, None);
1572-
let code = traits::ObligationCauseCode::RepeatElementCopy {
1573-
is_constable,
1574-
elt_type: element_ty,
1575-
elt_span: element.span,
1576-
elt_stmt_span: self
1577-
.tcx
1578-
.hir()
1579-
.parent_iter(element.hir_id)
1580-
.find_map(|(_, node)| match node {
1581-
hir::Node::Item(it) => Some(it.span),
1582-
hir::Node::Stmt(stmt) => Some(stmt.span),
1583-
_ => None,
1584-
})
1585-
.expect("array repeat expressions must be inside an item or statement"),
1586-
};
1587-
self.require_type_meets(element_ty, element.span, code, lang_item);
1588-
}
1575+
let lang_item = self.tcx.require_lang_item(LangItem::Copy, None);
1576+
let code = traits::ObligationCauseCode::RepeatElementCopy {
1577+
is_constable,
1578+
elt_type: element_ty,
1579+
elt_span: element.span,
1580+
elt_stmt_span: self
1581+
.tcx
1582+
.hir()
1583+
.parent_iter(element.hir_id)
1584+
.find_map(|(_, node)| match node {
1585+
hir::Node::Item(it) => Some(it.span),
1586+
hir::Node::Stmt(stmt) => Some(stmt.span),
1587+
_ => None,
1588+
})
1589+
.expect("array repeat expressions must be inside an item or statement"),
1590+
};
1591+
self.require_type_meets(element_ty, element.span, code, lang_item);
15891592
}
15901593

15911594
fn check_expr_tuple(
@@ -2800,9 +2803,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
28002803
len: ty::Const<'tcx>,
28012804
) {
28022805
err.span_label(field.span, "unknown field");
2803-
if let (Some(len), Ok(user_index)) =
2804-
(len.try_eval_target_usize(self.tcx, self.param_env), field.as_str().parse::<u64>())
2805-
{
2806+
if let (Some(len), Ok(user_index)) = (
2807+
self.try_structurally_resolve_const(base.span, len).try_to_target_usize(self.tcx),
2808+
field.as_str().parse::<u64>(),
2809+
) {
28062810
let help = "instead of using tuple indexing, use array indexing";
28072811
let applicability = if len < user_index {
28082812
Applicability::MachineApplicable

compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs

+27
Original file line numberDiff line numberDiff line change
@@ -1470,6 +1470,33 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
14701470
}
14711471
}
14721472

1473+
#[instrument(level = "debug", skip(self, sp), ret)]
1474+
pub fn try_structurally_resolve_const(&self, sp: Span, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
1475+
// FIXME(min_const_generic_exprs): We could process obligations here if `ct` is a var.
1476+
1477+
if self.next_trait_solver()
1478+
&& let ty::ConstKind::Unevaluated(..) = ct.kind()
1479+
{
1480+
// We need to use a separate variable here as otherwise the temporary for
1481+
// `self.fulfillment_cx.borrow_mut()` is alive in the `Err` branch, resulting
1482+
// in a reentrant borrow, causing an ICE.
1483+
let result = self
1484+
.at(&self.misc(sp), self.param_env)
1485+
.structurally_normalize_const(ct, &mut **self.fulfillment_cx.borrow_mut());
1486+
match result {
1487+
Ok(normalized_ct) => normalized_ct,
1488+
Err(errors) => {
1489+
let guar = self.err_ctxt().report_fulfillment_errors(errors);
1490+
return ty::Const::new_error(self.tcx, guar);
1491+
}
1492+
}
1493+
} else if self.tcx.features().generic_const_exprs {
1494+
ct.normalize(self.tcx, self.param_env)
1495+
} else {
1496+
ct
1497+
}
1498+
}
1499+
14731500
/// Resolves `ty` by a single level if `ty` is a type variable.
14741501
///
14751502
/// When the new solver is enabled, this will also attempt to normalize

compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs

+4-1
Original file line numberDiff line numberDiff line change
@@ -1502,7 +1502,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
15021502
// Create an dummy type `&[_]` so that both &[] and `&Vec<T>` can coerce to it.
15031503
let dummy_ty = if let ty::Array(elem_ty, size) = peeled.kind()
15041504
&& let ty::Infer(_) = elem_ty.kind()
1505-
&& size.try_eval_target_usize(self.tcx, self.param_env) == Some(0)
1505+
&& self
1506+
.try_structurally_resolve_const(provided_expr.span, *size)
1507+
.try_to_target_usize(self.tcx)
1508+
== Some(0)
15061509
{
15071510
let slice = Ty::new_slice(self.tcx, *elem_ty);
15081511
Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_static, slice)

compiler/rustc_hir_typeck/src/intrinsicck.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
101101
}
102102
}
103103
Ok(SizeSkeleton::Generic(size)) => {
104-
if let Some(size) = size.try_eval_target_usize(tcx, self.param_env) {
104+
if let Some(size) =
105+
self.try_structurally_resolve_const(span, size).try_to_target_usize(tcx)
106+
{
105107
format!("{size} bytes")
106108
} else {
107109
format!("generic size {size}")

compiler/rustc_hir_typeck/src/pat.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -2412,7 +2412,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
24122412
len: ty::Const<'tcx>,
24132413
min_len: u64,
24142414
) -> (Option<Ty<'tcx>>, Ty<'tcx>) {
2415-
let len = len.try_eval_target_usize(self.tcx, self.param_env);
2415+
let len = self.try_structurally_resolve_const(span, len).try_to_target_usize(self.tcx);
24162416

24172417
let guar = if let Some(len) = len {
24182418
// Now we know the length...

compiler/rustc_trait_selection/src/traits/structural_normalize.rs

+40
Original file line numberDiff line numberDiff line change
@@ -46,4 +46,44 @@ impl<'tcx> At<'_, 'tcx> {
4646
Ok(self.normalize(ty).into_value_registering_obligations(self.infcx, fulfill_cx))
4747
}
4848
}
49+
50+
fn structurally_normalize_const<E: 'tcx>(
51+
&self,
52+
ct: ty::Const<'tcx>,
53+
fulfill_cx: &mut dyn TraitEngine<'tcx, E>,
54+
) -> Result<ty::Const<'tcx>, Vec<E>> {
55+
assert!(!ct.is_ct_infer(), "should have resolved vars before calling");
56+
57+
if self.infcx.next_trait_solver() {
58+
let ty::ConstKind::Unevaluated(..) = ct.kind() else {
59+
return Ok(ct);
60+
};
61+
62+
let new_infer_ct = self.infcx.next_const_var(self.cause.span);
63+
64+
// We simply emit an `alias-eq` goal here, since that will take care of
65+
// normalizing the LHS of the projection until it is a rigid projection
66+
// (or a not-yet-defined opaque in scope).
67+
let obligation = Obligation::new(
68+
self.infcx.tcx,
69+
self.cause.clone(),
70+
self.param_env,
71+
ty::PredicateKind::AliasRelate(
72+
ct.into(),
73+
new_infer_ct.into(),
74+
ty::AliasRelationDirection::Equate,
75+
),
76+
);
77+
78+
fulfill_cx.register_predicate_obligation(self.infcx, obligation);
79+
let errors = fulfill_cx.select_where_possible(self.infcx);
80+
if !errors.is_empty() {
81+
return Err(errors);
82+
}
83+
84+
Ok(self.infcx.resolve_vars_if_possible(new_infer_ct))
85+
} else {
86+
Ok(self.normalize(ct).into_value_registering_obligations(self.infcx, fulfill_cx))
87+
}
88+
}
4989
}

tests/ui/const-generics/generic_const_exprs/different-fn.stderr

+2-2
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,10 @@ error[E0308]: mismatched types
22
--> $DIR/different-fn.rs:10:5
33
|
44
LL | [0; size_of::<Foo<T>>()]
5-
| ^^^^^^^^^^^^^^^^^^^^^^^^ expected `size_of::<T>()`, found `size_of::<Foo<T>>()`
5+
| ^^^^^^^^^^^^^^^^^^^^^^^^ expected `size_of::<T>()`, found `0`
66
|
77
= note: expected constant `size_of::<T>()`
8-
found constant `size_of::<Foo<T>>()`
8+
found constant `0`
99

1010
error: unconstrained generic constant
1111
--> $DIR/different-fn.rs:10:9

0 commit comments

Comments
 (0)