Skip to content

Commit 405d52a

Browse files
committed
Make sure the new aggregate equality comparison is excluded from const contexts
This is unless the `const_cmp` feature is enabled, in which case `PartialEq` becomes available in said contexts.
1 parent 02dcd9e commit 405d52a

2 files changed

Lines changed: 19 additions & 0 deletions

File tree

compiler/rustc_mir_build/src/builder/matches/match_pair.rs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ use rustc_middle::mir::*;
55
use rustc_middle::span_bug;
66
use rustc_middle::thir::*;
77
use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitableExt};
8+
use rustc_span::sym;
89

910
use crate::builder::Builder;
1011
use crate::builder::expr::as_place::{PlaceBase, PlaceBuilder};
@@ -39,6 +40,21 @@ fn try_reconstruct_aggregate_constant<'tcx>(
3940
Some(ty::Value { ty: aggregate_ty, valtree })
4041
}
4142

43+
impl<'a, 'tcx> Builder<'a, 'tcx> {
44+
/// Check if we can use aggregate `PartialEq::eq` comparisons for constant array/slice patterns.
45+
/// This is not possible in const contexts unless `#![feature(const_cmp, const_trait_impl)]` are enabled,
46+
/// because`PartialEq` is not const-stable.
47+
fn can_use_aggregate_eq(&self) -> bool {
48+
let const_partial_eq_enabled = {
49+
let features = self.tcx.features();
50+
features.enabled(sym::const_trait_impl) && features.enabled(sym::const_cmp)
51+
};
52+
let in_const_context = self.tcx.is_const_fn(self.def_id.to_def_id())
53+
|| !self.tcx.hir_body_owner_kind(self.def_id).is_fn_or_closure();
54+
!in_const_context || const_partial_eq_enabled
55+
}
56+
}
57+
4258
/// For an array or slice pattern's subpatterns (prefix/slice/suffix), returns a list
4359
/// of those subpatterns, each paired with a suitably-projected [`PlaceBuilder`].
4460
fn prefix_slice_suffix<'a, 'tcx>(
@@ -252,6 +268,7 @@ impl<'tcx> MatchPairTree<'tcx> {
252268
// `PartialEq::eq` rather than element by element.
253269
if slice.is_none()
254270
&& suffix.is_empty()
271+
&& cx.can_use_aggregate_eq()
255272
&& let Some(aggregate_value) =
256273
try_reconstruct_aggregate_constant(cx.tcx, pattern.ty, prefix)
257274
{
@@ -297,6 +314,7 @@ impl<'tcx> MatchPairTree<'tcx> {
297314
// is performed after the length check.
298315
if slice.is_none()
299316
&& suffix.is_empty()
317+
&& cx.can_use_aggregate_eq()
300318
&& let Some(aggregate_value) =
301319
try_reconstruct_aggregate_constant(cx.tcx, pattern.ty, prefix)
302320
{

compiler/rustc_span/src/symbol.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -648,6 +648,7 @@ symbols! {
648648
const_block_items,
649649
const_c_variadic,
650650
const_closures,
651+
const_cmp,
651652
const_compare_raw_pointers,
652653
const_constructor,
653654
const_continue,

0 commit comments

Comments
 (0)