1 use crate::infer
::{InferCtxt, TyCtxtInferExt}
;
2 use crate::traits
::ObligationCause
;
3 use crate::traits
::{self, ConstPatternStructural, TraitEngine}
;
5 use rustc
::ty
::{self, AdtDef, Ty, TyCtxt, TypeFoldable, TypeVisitor}
;
6 use rustc_data_structures
::fx
::FxHashSet
;
11 pub enum NonStructuralMatchTy
<'tcx
> {
16 /// This method traverses the structure of `ty`, trying to find an
17 /// instance of an ADT (i.e. struct or enum) that was declared without
18 /// the `#[structural_match]` attribute, or a generic type parameter
19 /// (which cannot be determined to be `structural_match`).
21 /// The "structure of a type" includes all components that would be
22 /// considered when doing a pattern match on a constant of that
25 /// * This means this method descends into fields of structs/enums,
26 /// and also descends into the inner type `T` of `&T` and `&mut T`
28 /// * The traversal doesn't dereference unsafe pointers (`*const T`,
29 /// `*mut T`), and it does not visit the type arguments of an
30 /// instantiated generic like `PhantomData<T>`.
32 /// The reason we do this search is Rust currently require all ADTs
33 /// reachable from a constant's type to be annotated with
34 /// `#[structural_match]`, an attribute which essentially says that
35 /// the implementation of `PartialEq::eq` behaves *equivalently* to a
36 /// comparison against the unfolded structure.
38 /// For more background on why Rust has this requirement, and issues
39 /// that arose when the requirement was not enforced completely, see
40 /// Rust RFC 1445, rust-lang/rust#61188, and rust-lang/rust#62307.
41 pub fn search_for_structural_match_violation
<'tcx
>(
46 ) -> Option
<NonStructuralMatchTy
<'tcx
>> {
47 // FIXME: we should instead pass in an `infcx` from the outside.
48 tcx
.infer_ctxt().enter(|infcx
| {
49 let mut search
= Search { id, span, infcx, found: None, seen: FxHashSet::default() }
;
50 ty
.visit_with(&mut search
);
55 /// This method returns true if and only if `adt_ty` itself has been marked as
56 /// eligible for structural-match: namely, if it implements both
57 /// `StructuralPartialEq` and `StructuralEq` (which are respectively injected by
58 /// `#[derive(PartialEq)]` and `#[derive(Eq)]`).
60 /// Note that this does *not* recursively check if the substructure of `adt_ty`
61 /// implements the traits.
62 pub fn type_marked_structural(
65 infcx
: &InferCtxt
<'_
, 'tcx
>,
68 let mut fulfillment_cx
= traits
::FulfillmentContext
::new();
69 let cause
= ObligationCause
::new(span
, id
, ConstPatternStructural
);
70 // require `#[derive(PartialEq)]`
71 let structural_peq_def_id
= infcx
.tcx
.lang_items().structural_peq_trait().unwrap();
72 fulfillment_cx
.register_bound(
74 ty
::ParamEnv
::empty(),
76 structural_peq_def_id
,
79 // for now, require `#[derive(Eq)]`. (Doing so is a hack to work around
80 // the type `for<'a> fn(&'a ())` failing to implement `Eq` itself.)
81 let cause
= ObligationCause
::new(span
, id
, ConstPatternStructural
);
82 let structural_teq_def_id
= infcx
.tcx
.lang_items().structural_teq_trait().unwrap();
83 fulfillment_cx
.register_bound(
85 ty
::ParamEnv
::empty(),
87 structural_teq_def_id
,
91 // We deliberately skip *reporting* fulfillment errors (via
92 // `report_fulfillment_errors`), for two reasons:
94 // 1. The error messages would mention `std::marker::StructuralPartialEq`
95 // (a trait which is solely meant as an implementation detail
98 // 2. We are sometimes doing future-incompatibility lints for
99 // now, so we do not want unconditional errors here.
100 fulfillment_cx
.select_all_or_error(infcx
).is_ok()
103 /// This implements the traversal over the structure of a given type to try to
104 /// find instances of ADTs (specifically structs or enums) that do not implement
105 /// the structural-match traits (`StructuralPartialEq` and `StructuralEq`).
106 struct Search
<'a
, 'tcx
> {
110 infcx
: InferCtxt
<'a
, 'tcx
>,
112 /// Records first ADT that does not implement a structural-match trait.
113 found
: Option
<NonStructuralMatchTy
<'tcx
>>,
115 /// Tracks ADTs previously encountered during search, so that
116 /// we will not recur on them again.
117 seen
: FxHashSet
<hir
::def_id
::DefId
>,
120 impl Search
<'a
, 'tcx
> {
121 fn tcx(&self) -> TyCtxt
<'tcx
> {
125 fn type_marked_structural(&self, adt_ty
: Ty
<'tcx
>) -> bool
{
126 type_marked_structural(self.id
, self.span
, &self.infcx
, adt_ty
)
130 impl<'a
, 'tcx
> TypeVisitor
<'tcx
> for Search
<'a
, 'tcx
> {
131 fn visit_ty(&mut self, ty
: Ty
<'tcx
>) -> bool
{
132 debug
!("Search visiting ty: {:?}", ty
);
134 let (adt_def
, substs
) = match ty
.kind
{
135 ty
::Adt(adt_def
, substs
) => (adt_def
, substs
),
137 self.found
= Some(NonStructuralMatchTy
::Param
);
138 return true; // Stop visiting.
141 // structural-match ignores substructure of
142 // `*const _`/`*mut _`, so skip `super_visit_with`.
144 // For example, if you have:
146 // struct NonStructural;
147 // #[derive(PartialEq, Eq)]
148 // struct T(*const NonStructural);
149 // const C: T = T(std::ptr::null());
152 // Even though `NonStructural` does not implement `PartialEq`,
153 // structural equality on `T` does not recur into the raw
154 // pointer. Therefore, one can still use `C` in a pattern.
156 // (But still tell caller to continue search.)
159 ty
::FnDef(..) | ty
::FnPtr(..) => {
160 // types of formals and return in `fn(_) -> _` are also irrelevant;
161 // so we do not recur into them via `super_visit_with`
163 // (But still tell caller to continue search.)
167 if { n.try_eval_usize(self.tcx(), ty::ParamEnv::reveal_all()) == Some(0) }
=>
169 // rust-lang/rust#62336: ignore type of contents
174 ty
.super_visit_with(self);
179 if !self.seen
.insert(adt_def
.did
) {
180 debug
!("Search already seen adt_def: {:?}", adt_def
);
181 // let caller continue its search
185 if !self.type_marked_structural(ty
) {
186 debug
!("Search found ty: {:?}", ty
);
187 self.found
= Some(NonStructuralMatchTy
::Adt(&adt_def
));
188 return true; // Halt visiting!
191 // structural-match does not care about the
192 // instantiation of the generics in an ADT (it
193 // instead looks directly at its fields outside
194 // this match), so we skip super_visit_with.
196 // (Must not recur on substs for `PhantomData<T>` cf
197 // rust-lang/rust#55028 and rust-lang/rust#55837; but also
198 // want to skip substs when only uses of generic are
199 // behind unsafe pointers `*const T`/`*mut T`.)
201 // even though we skip super_visit_with, we must recur on
203 let tcx
= self.tcx();
204 for field_ty
in adt_def
.all_fields().map(|field
| field
.ty(tcx
, substs
)) {
205 if field_ty
.visit_with(self) {
206 // found an ADT without structural-match; halt visiting!
207 assert
!(self.found
.is_some());
212 // Even though we do not want to recur on substs, we do
213 // want our caller to continue its own search.