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