]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_trait_selection/src/traits/structural_match.rs
Auto merge of #92740 - cuviper:update-rayons, r=Mark-Simulacrum
[rust.git] / compiler / rustc_trait_selection / src / traits / structural_match.rs
1 use crate::infer::{InferCtxt, TyCtxtInferExt};
2 use crate::traits::ObligationCause;
3 use crate::traits::{self, TraitEngine};
4
5 use rustc_data_structures::fx::FxHashSet;
6 use rustc_hir as hir;
7 use rustc_hir::lang_items::LangItem;
8 use rustc_middle::ty::query::Providers;
9 use rustc_middle::ty::{self, AdtDef, Ty, TyCtxt, TypeFoldable, TypeVisitor};
10 use rustc_span::Span;
11 use std::ops::ControlFlow;
12
13 #[derive(Debug)]
14 pub enum NonStructuralMatchTy<'tcx> {
15     Adt(&'tcx AdtDef),
16     Param,
17     Dynamic,
18     Foreign,
19     Opaque,
20     Closure,
21     Generator,
22     Projection,
23 }
24
25 /// This method traverses the structure of `ty`, trying to find an
26 /// instance of an ADT (i.e. struct or enum) that doesn't implement
27 /// the structural-match traits, or a generic type parameter
28 /// (which cannot be determined to be structural-match).
29 ///
30 /// The "structure of a type" includes all components that would be
31 /// considered when doing a pattern match on a constant of that
32 /// type.
33 ///
34 ///  * This means this method descends into fields of structs/enums,
35 ///    and also descends into the inner type `T` of `&T` and `&mut T`
36 ///
37 ///  * The traversal doesn't dereference unsafe pointers (`*const T`,
38 ///    `*mut T`), and it does not visit the type arguments of an
39 ///    instantiated generic like `PhantomData<T>`.
40 ///
41 /// The reason we do this search is Rust currently require all ADTs
42 /// reachable from a constant's type to implement the
43 /// structural-match traits, which essentially say that
44 /// the implementation of `PartialEq::eq` behaves *equivalently* to a
45 /// comparison against the unfolded structure.
46 ///
47 /// For more background on why Rust has this requirement, and issues
48 /// that arose when the requirement was not enforced completely, see
49 /// Rust RFC 1445, rust-lang/rust#61188, and rust-lang/rust#62307.
50 pub fn search_for_structural_match_violation<'tcx>(
51     span: Span,
52     tcx: TyCtxt<'tcx>,
53     ty: Ty<'tcx>,
54 ) -> Option<NonStructuralMatchTy<'tcx>> {
55     // FIXME: we should instead pass in an `infcx` from the outside.
56     tcx.infer_ctxt().enter(|infcx| {
57         ty.visit_with(&mut Search { infcx, span, seen: FxHashSet::default() }).break_value()
58     })
59 }
60
61 /// This method returns true if and only if `adt_ty` itself has been marked as
62 /// eligible for structural-match: namely, if it implements both
63 /// `StructuralPartialEq` and `StructuralEq` (which are respectively injected by
64 /// `#[derive(PartialEq)]` and `#[derive(Eq)]`).
65 ///
66 /// Note that this does *not* recursively check if the substructure of `adt_ty`
67 /// implements the traits.
68 fn type_marked_structural<'tcx>(
69     infcx: &InferCtxt<'_, 'tcx>,
70     adt_ty: Ty<'tcx>,
71     cause: ObligationCause<'tcx>,
72 ) -> bool {
73     let mut fulfillment_cx = traits::FulfillmentContext::new();
74     // require `#[derive(PartialEq)]`
75     let structural_peq_def_id =
76         infcx.tcx.require_lang_item(LangItem::StructuralPeq, Some(cause.span));
77     fulfillment_cx.register_bound(
78         infcx,
79         ty::ParamEnv::empty(),
80         adt_ty,
81         structural_peq_def_id,
82         cause.clone(),
83     );
84     // for now, require `#[derive(Eq)]`. (Doing so is a hack to work around
85     // the type `for<'a> fn(&'a ())` failing to implement `Eq` itself.)
86     let structural_teq_def_id =
87         infcx.tcx.require_lang_item(LangItem::StructuralTeq, Some(cause.span));
88     fulfillment_cx.register_bound(
89         infcx,
90         ty::ParamEnv::empty(),
91         adt_ty,
92         structural_teq_def_id,
93         cause,
94     );
95
96     // We deliberately skip *reporting* fulfillment errors (via
97     // `report_fulfillment_errors`), for two reasons:
98     //
99     // 1. The error messages would mention `std::marker::StructuralPartialEq`
100     //    (a trait which is solely meant as an implementation detail
101     //    for now), and
102     //
103     // 2. We are sometimes doing future-incompatibility lints for
104     //    now, so we do not want unconditional errors here.
105     fulfillment_cx.select_all_or_error(infcx).is_empty()
106 }
107
108 /// This implements the traversal over the structure of a given type to try to
109 /// find instances of ADTs (specifically structs or enums) that do not implement
110 /// the structural-match traits (`StructuralPartialEq` and `StructuralEq`).
111 struct Search<'a, 'tcx> {
112     span: Span,
113
114     infcx: InferCtxt<'a, 'tcx>,
115
116     /// Tracks ADTs previously encountered during search, so that
117     /// we will not recur on them again.
118     seen: FxHashSet<hir::def_id::DefId>,
119 }
120
121 impl<'a, 'tcx> Search<'a, 'tcx> {
122     fn tcx(&self) -> TyCtxt<'tcx> {
123         self.infcx.tcx
124     }
125
126     fn type_marked_structural(&self, adt_ty: Ty<'tcx>) -> bool {
127         adt_ty.is_structural_eq_shallow(self.tcx())
128     }
129 }
130
131 impl<'a, 'tcx> TypeVisitor<'tcx> for Search<'a, 'tcx> {
132     type BreakTy = NonStructuralMatchTy<'tcx>;
133     fn tcx_for_anon_const_substs(&self) -> Option<TyCtxt<'tcx>> {
134         Some(self.tcx())
135     }
136
137     fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
138         debug!("Search visiting ty: {:?}", ty);
139
140         let (adt_def, substs) = match *ty.kind() {
141             ty::Adt(adt_def, substs) => (adt_def, substs),
142             ty::Param(_) => {
143                 return ControlFlow::Break(NonStructuralMatchTy::Param);
144             }
145             ty::Dynamic(..) => {
146                 return ControlFlow::Break(NonStructuralMatchTy::Dynamic);
147             }
148             ty::Foreign(_) => {
149                 return ControlFlow::Break(NonStructuralMatchTy::Foreign);
150             }
151             ty::Opaque(..) => {
152                 return ControlFlow::Break(NonStructuralMatchTy::Opaque);
153             }
154             ty::Projection(..) => {
155                 return ControlFlow::Break(NonStructuralMatchTy::Projection);
156             }
157             ty::Closure(..) => {
158                 return ControlFlow::Break(NonStructuralMatchTy::Closure);
159             }
160             ty::Generator(..) | ty::GeneratorWitness(..) => {
161                 return ControlFlow::Break(NonStructuralMatchTy::Generator);
162             }
163             ty::RawPtr(..) => {
164                 // structural-match ignores substructure of
165                 // `*const _`/`*mut _`, so skip `super_visit_with`.
166                 //
167                 // For example, if you have:
168                 // ```
169                 // struct NonStructural;
170                 // #[derive(PartialEq, Eq)]
171                 // struct T(*const NonStructural);
172                 // const C: T = T(std::ptr::null());
173                 // ```
174                 //
175                 // Even though `NonStructural` does not implement `PartialEq`,
176                 // structural equality on `T` does not recur into the raw
177                 // pointer. Therefore, one can still use `C` in a pattern.
178                 return ControlFlow::CONTINUE;
179             }
180             ty::FnDef(..) | ty::FnPtr(..) => {
181                 // Types of formals and return in `fn(_) -> _` are also irrelevant;
182                 // so we do not recur into them via `super_visit_with`
183                 return ControlFlow::CONTINUE;
184             }
185             ty::Array(_, n)
186                 if { n.try_eval_usize(self.tcx(), ty::ParamEnv::reveal_all()) == Some(0) } =>
187             {
188                 // rust-lang/rust#62336: ignore type of contents
189                 // for empty array.
190                 return ControlFlow::CONTINUE;
191             }
192             ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Str | ty::Never => {
193                 // These primitive types are always structural match.
194                 //
195                 // `Never` is kind of special here, but as it is not inhabitable, this should be fine.
196                 return ControlFlow::CONTINUE;
197             }
198
199             ty::Array(..) | ty::Slice(_) | ty::Ref(..) | ty::Tuple(..) => {
200                 // First check all contained types and then tell the caller to continue searching.
201                 return ty.super_visit_with(self);
202             }
203             ty::Infer(_) | ty::Placeholder(_) | ty::Bound(..) => {
204                 bug!("unexpected type during structural-match checking: {:?}", ty);
205             }
206             ty::Error(_) => {
207                 self.tcx().sess.delay_span_bug(self.span, "ty::Error in structural-match check");
208                 // We still want to check other types after encountering an error,
209                 // as this may still emit relevant errors.
210                 return ControlFlow::CONTINUE;
211             }
212         };
213
214         if !self.seen.insert(adt_def.did) {
215             debug!("Search already seen adt_def: {:?}", adt_def);
216             return ControlFlow::CONTINUE;
217         }
218
219         if !self.type_marked_structural(ty) {
220             debug!("Search found ty: {:?}", ty);
221             return ControlFlow::Break(NonStructuralMatchTy::Adt(&adt_def));
222         }
223
224         // structural-match does not care about the
225         // instantiation of the generics in an ADT (it
226         // instead looks directly at its fields outside
227         // this match), so we skip super_visit_with.
228         //
229         // (Must not recur on substs for `PhantomData<T>` cf
230         // rust-lang/rust#55028 and rust-lang/rust#55837; but also
231         // want to skip substs when only uses of generic are
232         // behind unsafe pointers `*const T`/`*mut T`.)
233
234         // even though we skip super_visit_with, we must recur on
235         // fields of ADT.
236         let tcx = self.tcx();
237         adt_def.all_fields().map(|field| field.ty(tcx, substs)).try_for_each(|field_ty| {
238             let ty = self.tcx().normalize_erasing_regions(ty::ParamEnv::empty(), field_ty);
239             debug!("structural-match ADT: field_ty={:?}, ty={:?}", field_ty, ty);
240             ty.visit_with(self)
241         })
242     }
243 }
244
245 pub fn provide(providers: &mut Providers) {
246     providers.has_structural_eq_impls = |tcx, ty| {
247         tcx.infer_ctxt().enter(|infcx| {
248             let cause = ObligationCause::dummy();
249             type_marked_structural(&infcx, ty, cause)
250         })
251     };
252 }