1 use crate::infer::{InferCtxt, TyCtxtInferExt};
2 use crate::traits::ObligationCause;
3 use crate::traits::{TraitEngine, TraitEngineExt};
5 use rustc_data_structures::fx::FxHashSet;
7 use rustc_hir::lang_items::LangItem;
8 use rustc_middle::ty::query::Providers;
9 use rustc_middle::ty::{self, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitor};
11 use std::ops::ControlFlow;
13 /// This method traverses the structure of `ty`, trying to find an
14 /// instance of an ADT (i.e. struct or enum) that doesn't implement
15 /// the structural-match traits, or a generic type parameter
16 /// (which cannot be determined to be structural-match).
18 /// The "structure of a type" includes all components that would be
19 /// considered when doing a pattern match on a constant of that
22 /// * This means this method descends into fields of structs/enums,
23 /// and also descends into the inner type `T` of `&T` and `&mut T`
25 /// * The traversal doesn't dereference unsafe pointers (`*const T`,
26 /// `*mut T`), and it does not visit the type arguments of an
27 /// instantiated generic like `PhantomData<T>`.
29 /// The reason we do this search is Rust currently require all ADTs
30 /// reachable from a constant's type to implement the
31 /// structural-match traits, which essentially say that
32 /// the implementation of `PartialEq::eq` behaves *equivalently* to a
33 /// comparison against the unfolded structure.
35 /// For more background on why Rust has this requirement, and issues
36 /// that arose when the requirement was not enforced completely, see
37 /// Rust RFC 1445, rust-lang/rust#61188, and rust-lang/rust#62307.
38 pub fn search_for_structural_match_violation<'tcx>(
42 ) -> Option<Ty<'tcx>> {
43 ty.visit_with(&mut Search { tcx, span, seen: FxHashSet::default(), adt_const_param: false })
47 /// This method traverses the structure of `ty`, trying to find any
48 /// types that are not allowed to be used in a const generic.
50 /// This is either because the type does not implement `StructuralEq`
51 /// and `StructuralPartialEq`, or because the type is intentionally
52 /// not supported in const generics (such as floats and raw pointers,
53 /// which are allowed in match blocks).
54 pub fn search_for_adt_const_param_violation<'tcx>(
58 ) -> Option<Ty<'tcx>> {
59 ty.visit_with(&mut Search { tcx, span, seen: FxHashSet::default(), adt_const_param: true })
63 /// This method returns true if and only if `adt_ty` itself has been marked as
64 /// eligible for structural-match: namely, if it implements both
65 /// `StructuralPartialEq` and `StructuralEq` (which are respectively injected by
66 /// `#[derive(PartialEq)]` and `#[derive(Eq)]`).
68 /// Note that this does *not* recursively check if the substructure of `adt_ty`
69 /// implements the traits.
70 fn type_marked_structural<'tcx>(
71 infcx: &InferCtxt<'_, 'tcx>,
73 cause: ObligationCause<'tcx>,
75 let mut fulfillment_cx = <dyn TraitEngine<'tcx>>::new(infcx.tcx);
76 // require `#[derive(PartialEq)]`
77 let structural_peq_def_id =
78 infcx.tcx.require_lang_item(LangItem::StructuralPeq, Some(cause.span));
79 fulfillment_cx.register_bound(
81 ty::ParamEnv::empty(),
83 structural_peq_def_id,
86 // for now, require `#[derive(Eq)]`. (Doing so is a hack to work around
87 // the type `for<'a> fn(&'a ())` failing to implement `Eq` itself.)
88 let structural_teq_def_id =
89 infcx.tcx.require_lang_item(LangItem::StructuralTeq, Some(cause.span));
90 fulfillment_cx.register_bound(
92 ty::ParamEnv::empty(),
94 structural_teq_def_id,
98 // We deliberately skip *reporting* fulfillment errors (via
99 // `report_fulfillment_errors`), for two reasons:
101 // 1. The error messages would mention `std::marker::StructuralPartialEq`
102 // (a trait which is solely meant as an implementation detail
105 // 2. We are sometimes doing future-incompatibility lints for
106 // now, so we do not want unconditional errors here.
107 fulfillment_cx.select_all_or_error(infcx).is_empty()
110 /// This implements the traversal over the structure of a given type to try to
111 /// find instances of ADTs (specifically structs or enums) that do not implement
112 /// the structural-match traits (`StructuralPartialEq` and `StructuralEq`).
113 struct Search<'tcx> {
118 /// Tracks ADTs previously encountered during search, so that
119 /// we will not recur on them again.
120 seen: FxHashSet<hir::def_id::DefId>,
122 // Additionally deny things that have been allowed in patterns,
123 // but are not allowed in adt const params, such as floats and
125 adt_const_param: bool,
128 impl<'tcx> Search<'tcx> {
129 fn type_marked_structural(&self, adt_ty: Ty<'tcx>) -> bool {
130 adt_ty.is_structural_eq_shallow(self.tcx)
134 impl<'tcx> TypeVisitor<'tcx> for Search<'tcx> {
135 type BreakTy = Ty<'tcx>;
137 fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
138 debug!("Search visiting ty: {:?}", ty);
140 let (adt_def, substs) = match *ty.kind() {
141 ty::Adt(adt_def, substs) => (adt_def, substs),
143 return ControlFlow::Break(ty);
146 return ControlFlow::Break(ty);
149 return ControlFlow::Break(ty);
152 return ControlFlow::Break(ty);
154 ty::Projection(..) => {
155 return ControlFlow::Break(ty);
158 return ControlFlow::Break(ty);
160 ty::Generator(..) | ty::GeneratorWitness(..) => {
161 return ControlFlow::Break(ty);
164 // Types of formals and return in `fn(_) -> _` are also irrelevant;
165 // so we do not recur into them via `super_visit_with`
166 return ControlFlow::CONTINUE;
169 if { n.try_eval_usize(self.tcx, ty::ParamEnv::reveal_all()) == Some(0) } =>
171 // rust-lang/rust#62336: ignore type of contents
173 return ControlFlow::CONTINUE;
175 ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Str | ty::Never => {
176 // These primitive types are always structural match.
178 // `Never` is kind of special here, but as it is not inhabitable, this should be fine.
179 return ControlFlow::CONTINUE;
183 if !self.adt_const_param {
184 return ControlFlow::CONTINUE;
186 return ControlFlow::Break(ty);
191 if !self.adt_const_param {
192 // structural-match ignores substructure of
193 // `*const _`/`*mut _`, so skip `super_visit_with`.
195 // For example, if you have:
197 // struct NonStructural;
198 // #[derive(PartialEq, Eq)]
199 // struct T(*const NonStructural);
200 // const C: T = T(std::ptr::null());
203 // Even though `NonStructural` does not implement `PartialEq`,
204 // structural equality on `T` does not recur into the raw
205 // pointer. Therefore, one can still use `C` in a pattern.
206 return ControlFlow::CONTINUE;
208 return ControlFlow::Break(ty);
213 if !self.adt_const_param {
214 return ControlFlow::CONTINUE;
216 return ControlFlow::Break(ty);
220 ty::Array(..) | ty::Slice(_) | ty::Ref(..) | ty::Tuple(..) => {
221 // First check all contained types and then tell the caller to continue searching.
222 return ty.super_visit_with(self);
224 ty::Infer(_) | ty::Placeholder(_) | ty::Bound(..) => {
225 bug!("unexpected type during structural-match checking: {:?}", ty);
228 self.tcx.sess.delay_span_bug(self.span, "ty::Error in structural-match check");
229 // We still want to check other types after encountering an error,
230 // as this may still emit relevant errors.
231 return ControlFlow::CONTINUE;
235 if !self.seen.insert(adt_def.did()) {
236 debug!("Search already seen adt_def: {:?}", adt_def);
237 return ControlFlow::CONTINUE;
240 if !self.type_marked_structural(ty) {
241 debug!("Search found ty: {:?}", ty);
242 return ControlFlow::Break(ty);
245 // structural-match does not care about the
246 // instantiation of the generics in an ADT (it
247 // instead looks directly at its fields outside
248 // this match), so we skip super_visit_with.
250 // (Must not recur on substs for `PhantomData<T>` cf
251 // rust-lang/rust#55028 and rust-lang/rust#55837; but also
252 // want to skip substs when only uses of generic are
253 // behind unsafe pointers `*const T`/`*mut T`.)
255 // even though we skip super_visit_with, we must recur on
258 adt_def.all_fields().map(|field| field.ty(tcx, substs)).try_for_each(|field_ty| {
259 let ty = self.tcx.normalize_erasing_regions(ty::ParamEnv::empty(), field_ty);
260 debug!("structural-match ADT: field_ty={:?}, ty={:?}", field_ty, ty);
266 pub fn provide(providers: &mut Providers) {
267 providers.has_structural_eq_impls = |tcx, ty| {
268 tcx.infer_ctxt().enter(|infcx| {
269 let cause = ObligationCause::dummy();
270 type_marked_structural(&infcx, ty, cause)