]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_trait_selection/src/traits/structural_match.rs
Rollup merge of #99386 - AngelicosPhosphoros:add_retain_test_maybeuninit, r=JohnTitor
[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::{TraitEngine, TraitEngineExt};
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, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitor};
10 use rustc_span::Span;
11 use std::ops::ControlFlow;
12
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).
17 ///
18 /// The "structure of a type" includes all components that would be
19 /// considered when doing a pattern match on a constant of that
20 /// type.
21 ///
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`
24 ///
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>`.
28 ///
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.
34 ///
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>(
39     span: Span,
40     tcx: TyCtxt<'tcx>,
41     ty: Ty<'tcx>,
42 ) -> Option<Ty<'tcx>> {
43     ty.visit_with(&mut Search { tcx, span, seen: FxHashSet::default(), adt_const_param: false })
44         .break_value()
45 }
46
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.
49 ///
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>(
55     span: Span,
56     tcx: TyCtxt<'tcx>,
57     ty: Ty<'tcx>,
58 ) -> Option<Ty<'tcx>> {
59     ty.visit_with(&mut Search { tcx, span, seen: FxHashSet::default(), adt_const_param: true })
60         .break_value()
61 }
62
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)]`).
67 ///
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>,
72     adt_ty: Ty<'tcx>,
73     cause: ObligationCause<'tcx>,
74 ) -> bool {
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(
80         infcx,
81         ty::ParamEnv::empty(),
82         adt_ty,
83         structural_peq_def_id,
84         cause.clone(),
85     );
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(
91         infcx,
92         ty::ParamEnv::empty(),
93         adt_ty,
94         structural_teq_def_id,
95         cause,
96     );
97
98     // We deliberately skip *reporting* fulfillment errors (via
99     // `report_fulfillment_errors`), for two reasons:
100     //
101     // 1. The error messages would mention `std::marker::StructuralPartialEq`
102     //    (a trait which is solely meant as an implementation detail
103     //    for now), and
104     //
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()
108 }
109
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> {
114     span: Span,
115
116     tcx: TyCtxt<'tcx>,
117
118     /// Tracks ADTs previously encountered during search, so that
119     /// we will not recur on them again.
120     seen: FxHashSet<hir::def_id::DefId>,
121
122     // Additionally deny things that have been allowed in patterns,
123     // but are not allowed in adt const params, such as floats and
124     // fn ptrs.
125     adt_const_param: bool,
126 }
127
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)
131     }
132 }
133
134 impl<'tcx> TypeVisitor<'tcx> for Search<'tcx> {
135     type BreakTy = Ty<'tcx>;
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(ty);
144             }
145             ty::Dynamic(..) => {
146                 return ControlFlow::Break(ty);
147             }
148             ty::Foreign(_) => {
149                 return ControlFlow::Break(ty);
150             }
151             ty::Opaque(..) => {
152                 return ControlFlow::Break(ty);
153             }
154             ty::Projection(..) => {
155                 return ControlFlow::Break(ty);
156             }
157             ty::Closure(..) => {
158                 return ControlFlow::Break(ty);
159             }
160             ty::Generator(..) | ty::GeneratorWitness(..) => {
161                 return ControlFlow::Break(ty);
162             }
163             ty::FnDef(..) => {
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;
167             }
168             ty::Array(_, n)
169                 if { n.try_eval_usize(self.tcx, ty::ParamEnv::reveal_all()) == Some(0) } =>
170             {
171                 // rust-lang/rust#62336: ignore type of contents
172                 // for empty array.
173                 return ControlFlow::CONTINUE;
174             }
175             ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Str | ty::Never => {
176                 // These primitive types are always structural match.
177                 //
178                 // `Never` is kind of special here, but as it is not inhabitable, this should be fine.
179                 return ControlFlow::CONTINUE;
180             }
181
182             ty::FnPtr(..) => {
183                 if !self.adt_const_param {
184                     return ControlFlow::CONTINUE;
185                 } else {
186                     return ControlFlow::Break(ty);
187                 }
188             }
189
190             ty::RawPtr(..) => {
191                 if !self.adt_const_param {
192                     // structural-match ignores substructure of
193                     // `*const _`/`*mut _`, so skip `super_visit_with`.
194                     //
195                     // For example, if you have:
196                     // ```
197                     // struct NonStructural;
198                     // #[derive(PartialEq, Eq)]
199                     // struct T(*const NonStructural);
200                     // const C: T = T(std::ptr::null());
201                     // ```
202                     //
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;
207                 } else {
208                     return ControlFlow::Break(ty);
209                 }
210             }
211
212             ty::Float(_) => {
213                 if !self.adt_const_param {
214                     return ControlFlow::CONTINUE;
215                 } else {
216                     return ControlFlow::Break(ty);
217                 }
218             }
219
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);
223             }
224             ty::Infer(_) | ty::Placeholder(_) | ty::Bound(..) => {
225                 bug!("unexpected type during structural-match checking: {:?}", ty);
226             }
227             ty::Error(_) => {
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;
232             }
233         };
234
235         if !self.seen.insert(adt_def.did()) {
236             debug!("Search already seen adt_def: {:?}", adt_def);
237             return ControlFlow::CONTINUE;
238         }
239
240         if !self.type_marked_structural(ty) {
241             debug!("Search found ty: {:?}", ty);
242             return ControlFlow::Break(ty);
243         }
244
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.
249         //
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`.)
254
255         // even though we skip super_visit_with, we must recur on
256         // fields of ADT.
257         let tcx = self.tcx;
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);
261             ty.visit_with(self)
262         })
263     }
264 }
265
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)
271         })
272     };
273 }