Skip to content

Commit aeb8dd7

Browse files
authored
Rollup merge of rust-lang#73066 - ecstatic-morse:query-structural-eq2, r=pnkfelix
Querify whether a type has structural equality (Take 2) Alternative to rust-lang#72177. Unlike in rust-lang#72177, this helper method works for all types, falling back to a query for `TyKind::Adt`s that determines whether the `{Partial,}StructuralEq` traits are implemented. This is my preferred interface for this method. I think this is better than just documenting that the helper only works for ADTs. If others disagree, we can just merge rust-lang#72177 with the fixes applied. This has already taken far too long.
2 parents f27f659 + 2801761 commit aeb8dd7

File tree

6 files changed

+86
-20
lines changed

6 files changed

+86
-20
lines changed

src/librustc_middle/query/mod.rs

+11
Original file line numberDiff line numberDiff line change
@@ -789,6 +789,17 @@ rustc_queries! {
789789
desc { "computing whether `{}` needs drop", env.value }
790790
}
791791

792+
/// Query backing `TyS::is_structural_eq_shallow`.
793+
///
794+
/// This is only correct for ADTs. Call `is_structural_eq_shallow` to handle all types
795+
/// correctly.
796+
query has_structural_eq_impls(ty: Ty<'tcx>) -> bool {
797+
desc {
798+
"computing whether `{:?}` implements `PartialStructuralEq` and `StructuralEq`",
799+
ty
800+
}
801+
}
802+
792803
/// A list of types where the ADT requires drop if and only if any of
793804
/// those types require drop. If the ADT is known to always need drop
794805
/// then `Err(AlwaysRequiresDrop)` is returned.

src/librustc_middle/ty/util.rs

+51
Original file line numberDiff line numberDiff line change
@@ -778,6 +778,57 @@ impl<'tcx> ty::TyS<'tcx> {
778778
}
779779
}
780780

781+
/// Returns `true` if equality for this type is both reflexive and structural.
782+
///
783+
/// Reflexive equality for a type is indicated by an `Eq` impl for that type.
784+
///
785+
/// Primitive types (`u32`, `str`) have structural equality by definition. For composite data
786+
/// types, equality for the type as a whole is structural when it is the same as equality
787+
/// between all components (fields, array elements, etc.) of that type. For ADTs, structural
788+
/// equality is indicated by an implementation of `PartialStructuralEq` and `StructuralEq` for
789+
/// that type.
790+
///
791+
/// This function is "shallow" because it may return `true` for a composite type whose fields
792+
/// are not `StructuralEq`. For example, `[T; 4]` has structural equality regardless of `T`
793+
/// because equality for arrays is determined by the equality of each array element. If you
794+
/// want to know whether a given call to `PartialEq::eq` will proceed structurally all the way
795+
/// down, you will need to use a type visitor.
796+
#[inline]
797+
pub fn is_structural_eq_shallow(&'tcx self, tcx: TyCtxt<'tcx>) -> bool {
798+
match self.kind {
799+
// Look for an impl of both `PartialStructuralEq` and `StructuralEq`.
800+
Adt(..) => tcx.has_structural_eq_impls(self),
801+
802+
// Primitive types that satisfy `Eq`.
803+
Bool | Char | Int(_) | Uint(_) | Str | Never => true,
804+
805+
// Composite types that satisfy `Eq` when all of their fields do.
806+
//
807+
// Because this function is "shallow", we return `true` for these composites regardless
808+
// of the type(s) contained within.
809+
Ref(..) | Array(..) | Slice(_) | Tuple(..) => true,
810+
811+
// Raw pointers use bitwise comparison.
812+
RawPtr(_) | FnPtr(_) => true,
813+
814+
// Floating point numbers are not `Eq`.
815+
Float(_) => false,
816+
817+
// Conservatively return `false` for all others...
818+
819+
// Anonymous function types
820+
FnDef(..) | Closure(..) | Dynamic(..) | Generator(..) => false,
821+
822+
// Generic or inferred types
823+
//
824+
// FIXME(ecstaticmorse): Maybe we should `bug` here? This should probably only be
825+
// called for known, fully-monomorphized types.
826+
Projection(_) | Opaque(..) | Param(_) | Bound(..) | Placeholder(_) | Infer(_) => false,
827+
828+
Foreign(_) | GeneratorWitness(..) | Error => false,
829+
}
830+
}
831+
781832
pub fn same_type(a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
782833
match (&a.kind, &b.kind) {
783834
(&Adt(did_a, substs_a), &Adt(did_b, substs_b)) => {

src/librustc_mir/transform/check_consts/qualifs.rs

+1-5
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
//!
33
//! See the `Qualif` trait for more info.
44
5-
use rustc_infer::infer::TyCtxtInferExt;
65
use rustc_middle::mir::*;
76
use rustc_middle::ty::{self, subst::SubstsRef, AdtDef, Ty};
87
use rustc_span::DUMMY_SP;
@@ -137,10 +136,7 @@ impl Qualif for CustomEq {
137136
substs: SubstsRef<'tcx>,
138137
) -> bool {
139138
let ty = cx.tcx.mk_ty(ty::Adt(adt, substs));
140-
let id = cx.tcx.hir().local_def_id_to_hir_id(cx.def_id.as_local().unwrap());
141-
cx.tcx
142-
.infer_ctxt()
143-
.enter(|infcx| !traits::type_marked_structural(id, cx.body.span, &infcx, ty))
139+
!ty.is_structural_eq_shallow(cx.tcx)
144140
}
145141
}
146142

src/librustc_mir_build/hair/pattern/const_to_pat.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ impl<'a, 'tcx> ConstToPat<'a, 'tcx> {
8080
}
8181

8282
fn type_marked_structural(&self, ty: Ty<'tcx>) -> bool {
83-
traits::type_marked_structural(self.id, self.span, &self.infcx, ty)
83+
ty.is_structural_eq_shallow(self.infcx.tcx)
8484
}
8585

8686
fn to_pat(

src/librustc_trait_selection/traits/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,6 @@ pub use self::specialize::specialization_graph::FutureCompatOverlapError;
6060
pub use self::specialize::specialization_graph::FutureCompatOverlapErrorKind;
6161
pub use self::specialize::{specialization_graph, translate_substs, OverlapError};
6262
pub use self::structural_match::search_for_structural_match_violation;
63-
pub use self::structural_match::type_marked_structural;
6463
pub use self::structural_match::NonStructuralMatchTy;
6564
pub use self::util::{elaborate_predicates, elaborate_trait_ref, elaborate_trait_refs};
6665
pub use self::util::{expand_trait_aliases, TraitAliasExpander};
@@ -553,6 +552,7 @@ fn type_implements_trait<'tcx>(
553552

554553
pub fn provide(providers: &mut ty::query::Providers<'_>) {
555554
object_safety::provide(providers);
555+
structural_match::provide(providers);
556556
*providers = ty::query::Providers {
557557
specialization_graph_of: specialize::specialization_graph_provider,
558558
specializes: specialize::specializes,

src/librustc_trait_selection/traits/structural_match.rs

+21-13
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
use crate::infer::{InferCtxt, TyCtxtInferExt};
22
use crate::traits::ObligationCause;
3-
use crate::traits::{self, ConstPatternStructural, TraitEngine};
3+
use crate::traits::{self, TraitEngine};
44

55
use rustc_data_structures::fx::FxHashSet;
66
use rustc_hir as hir;
77
use rustc_hir::lang_items::{StructuralPeqTraitLangItem, StructuralTeqTraitLangItem};
8+
use rustc_middle::ty::query::Providers;
89
use rustc_middle::ty::{self, AdtDef, Ty, TyCtxt, TypeFoldable, TypeVisitor};
910
use rustc_span::Span;
1011

@@ -45,14 +46,14 @@ pub enum NonStructuralMatchTy<'tcx> {
4546
/// that arose when the requirement was not enforced completely, see
4647
/// Rust RFC 1445, rust-lang/rust#61188, and rust-lang/rust#62307.
4748
pub fn search_for_structural_match_violation<'tcx>(
48-
id: hir::HirId,
49+
_id: hir::HirId,
4950
span: Span,
5051
tcx: TyCtxt<'tcx>,
5152
ty: Ty<'tcx>,
5253
) -> Option<NonStructuralMatchTy<'tcx>> {
5354
// FIXME: we should instead pass in an `infcx` from the outside.
5455
tcx.infer_ctxt().enter(|infcx| {
55-
let mut search = Search { id, span, infcx, found: None, seen: FxHashSet::default() };
56+
let mut search = Search { infcx, span, found: None, seen: FxHashSet::default() };
5657
ty.visit_with(&mut search);
5758
search.found
5859
})
@@ -65,27 +66,26 @@ pub fn search_for_structural_match_violation<'tcx>(
6566
///
6667
/// Note that this does *not* recursively check if the substructure of `adt_ty`
6768
/// implements the traits.
68-
pub fn type_marked_structural(
69-
id: hir::HirId,
70-
span: Span,
69+
fn type_marked_structural(
7170
infcx: &InferCtxt<'_, 'tcx>,
7271
adt_ty: Ty<'tcx>,
72+
cause: ObligationCause<'tcx>,
7373
) -> bool {
7474
let mut fulfillment_cx = traits::FulfillmentContext::new();
75-
let cause = ObligationCause::new(span, id, ConstPatternStructural);
7675
// require `#[derive(PartialEq)]`
77-
let structural_peq_def_id = infcx.tcx.require_lang_item(StructuralPeqTraitLangItem, Some(span));
76+
let structural_peq_def_id =
77+
infcx.tcx.require_lang_item(StructuralPeqTraitLangItem, Some(cause.span));
7878
fulfillment_cx.register_bound(
7979
infcx,
8080
ty::ParamEnv::empty(),
8181
adt_ty,
8282
structural_peq_def_id,
83-
cause,
83+
cause.clone(),
8484
);
8585
// for now, require `#[derive(Eq)]`. (Doing so is a hack to work around
8686
// the type `for<'a> fn(&'a ())` failing to implement `Eq` itself.)
87-
let cause = ObligationCause::new(span, id, ConstPatternStructural);
88-
let structural_teq_def_id = infcx.tcx.require_lang_item(StructuralTeqTraitLangItem, Some(span));
87+
let structural_teq_def_id =
88+
infcx.tcx.require_lang_item(StructuralTeqTraitLangItem, Some(cause.span));
8989
fulfillment_cx.register_bound(
9090
infcx,
9191
ty::ParamEnv::empty(),
@@ -110,7 +110,6 @@ pub fn type_marked_structural(
110110
/// find instances of ADTs (specifically structs or enums) that do not implement
111111
/// the structural-match traits (`StructuralPartialEq` and `StructuralEq`).
112112
struct Search<'a, 'tcx> {
113-
id: hir::HirId,
114113
span: Span,
115114

116115
infcx: InferCtxt<'a, 'tcx>,
@@ -129,7 +128,7 @@ impl Search<'a, 'tcx> {
129128
}
130129

131130
fn type_marked_structural(&self, adt_ty: Ty<'tcx>) -> bool {
132-
type_marked_structural(self.id, self.span, &self.infcx, adt_ty)
131+
adt_ty.is_structural_eq_shallow(self.tcx())
133132
}
134133
}
135134

@@ -266,3 +265,12 @@ impl<'a, 'tcx> TypeVisitor<'tcx> for Search<'a, 'tcx> {
266265
false
267266
}
268267
}
268+
269+
pub fn provide(providers: &mut Providers<'_>) {
270+
providers.has_structural_eq_impls = |tcx, ty| {
271+
tcx.infer_ctxt().enter(|infcx| {
272+
let cause = ObligationCause::dummy();
273+
type_marked_structural(&infcx, ty, cause)
274+
})
275+
};
276+
}

0 commit comments

Comments
 (0)