]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_trait_selection/src/traits/util.rs
Replace `&mut DiagnosticBuilder`, in signatures, with `&mut Diagnostic`.
[rust.git] / compiler / rustc_trait_selection / src / traits / util.rs
1 use rustc_errors::Diagnostic;
2 use rustc_span::Span;
3 use smallvec::smallvec;
4 use smallvec::SmallVec;
5
6 use rustc_data_structures::fx::FxHashSet;
7 use rustc_hir::def_id::DefId;
8 use rustc_middle::ty::subst::{GenericArg, Subst, SubstsRef};
9 use rustc_middle::ty::{self, ToPredicate, Ty, TyCtxt, TypeFoldable};
10
11 use super::{Normalized, Obligation, ObligationCause, PredicateObligation, SelectionContext};
12 pub use rustc_infer::traits::{self, util::*};
13
14 use std::iter;
15
16 ///////////////////////////////////////////////////////////////////////////
17 // `TraitAliasExpander` iterator
18 ///////////////////////////////////////////////////////////////////////////
19
20 /// "Trait alias expansion" is the process of expanding a sequence of trait
21 /// references into another sequence by transitively following all trait
22 /// aliases. e.g. If you have bounds like `Foo + Send`, a trait alias
23 /// `trait Foo = Bar + Sync;`, and another trait alias
24 /// `trait Bar = Read + Write`, then the bounds would expand to
25 /// `Read + Write + Sync + Send`.
26 /// Expansion is done via a DFS (depth-first search), and the `visited` field
27 /// is used to avoid cycles.
28 pub struct TraitAliasExpander<'tcx> {
29     tcx: TyCtxt<'tcx>,
30     stack: Vec<TraitAliasExpansionInfo<'tcx>>,
31 }
32
33 /// Stores information about the expansion of a trait via a path of zero or more trait aliases.
34 #[derive(Debug, Clone)]
35 pub struct TraitAliasExpansionInfo<'tcx> {
36     pub path: SmallVec<[(ty::PolyTraitRef<'tcx>, Span); 4]>,
37 }
38
39 impl<'tcx> TraitAliasExpansionInfo<'tcx> {
40     fn new(trait_ref: ty::PolyTraitRef<'tcx>, span: Span) -> Self {
41         Self { path: smallvec![(trait_ref, span)] }
42     }
43
44     /// Adds diagnostic labels to `diag` for the expansion path of a trait through all intermediate
45     /// trait aliases.
46     pub fn label_with_exp_info(&self, diag: &mut Diagnostic, top_label: &str, use_desc: &str) {
47         diag.span_label(self.top().1, top_label);
48         if self.path.len() > 1 {
49             for (_, sp) in self.path.iter().rev().skip(1).take(self.path.len() - 2) {
50                 diag.span_label(*sp, format!("referenced here ({})", use_desc));
51             }
52         }
53         if self.top().1 != self.bottom().1 {
54             // When the trait object is in a return type these two spans match, we don't want
55             // redundant labels.
56             diag.span_label(
57                 self.bottom().1,
58                 format!("trait alias used in trait object type ({})", use_desc),
59             );
60         }
61     }
62
63     pub fn trait_ref(&self) -> ty::PolyTraitRef<'tcx> {
64         self.top().0
65     }
66
67     pub fn top(&self) -> &(ty::PolyTraitRef<'tcx>, Span) {
68         self.path.last().unwrap()
69     }
70
71     pub fn bottom(&self) -> &(ty::PolyTraitRef<'tcx>, Span) {
72         self.path.first().unwrap()
73     }
74
75     fn clone_and_push(&self, trait_ref: ty::PolyTraitRef<'tcx>, span: Span) -> Self {
76         let mut path = self.path.clone();
77         path.push((trait_ref, span));
78
79         Self { path }
80     }
81 }
82
83 pub fn expand_trait_aliases<'tcx>(
84     tcx: TyCtxt<'tcx>,
85     trait_refs: impl Iterator<Item = (ty::PolyTraitRef<'tcx>, Span)>,
86 ) -> TraitAliasExpander<'tcx> {
87     let items: Vec<_> =
88         trait_refs.map(|(trait_ref, span)| TraitAliasExpansionInfo::new(trait_ref, span)).collect();
89     TraitAliasExpander { tcx, stack: items }
90 }
91
92 impl<'tcx> TraitAliasExpander<'tcx> {
93     /// If `item` is a trait alias and its predicate has not yet been visited, then expands `item`
94     /// to the definition, pushes the resulting expansion onto `self.stack`, and returns `false`.
95     /// Otherwise, immediately returns `true` if `item` is a regular trait, or `false` if it is a
96     /// trait alias.
97     /// The return value indicates whether `item` should be yielded to the user.
98     fn expand(&mut self, item: &TraitAliasExpansionInfo<'tcx>) -> bool {
99         let tcx = self.tcx;
100         let trait_ref = item.trait_ref();
101         let pred = trait_ref.without_const().to_predicate(tcx);
102
103         debug!("expand_trait_aliases: trait_ref={:?}", trait_ref);
104
105         // Don't recurse if this bound is not a trait alias.
106         let is_alias = tcx.is_trait_alias(trait_ref.def_id());
107         if !is_alias {
108             return true;
109         }
110
111         // Don't recurse if this trait alias is already on the stack for the DFS search.
112         let anon_pred = anonymize_predicate(tcx, pred);
113         if item.path.iter().rev().skip(1).any(|&(tr, _)| {
114             anonymize_predicate(tcx, tr.without_const().to_predicate(tcx)) == anon_pred
115         }) {
116             return false;
117         }
118
119         // Get components of trait alias.
120         let predicates = tcx.super_predicates_of(trait_ref.def_id());
121
122         let items = predicates.predicates.iter().rev().filter_map(|(pred, span)| {
123             pred.subst_supertrait(tcx, &trait_ref)
124                 .to_opt_poly_trait_pred()
125                 .map(|trait_ref| item.clone_and_push(trait_ref.map_bound(|t| t.trait_ref), *span))
126         });
127         debug!("expand_trait_aliases: items={:?}", items.clone());
128
129         self.stack.extend(items);
130
131         false
132     }
133 }
134
135 impl<'tcx> Iterator for TraitAliasExpander<'tcx> {
136     type Item = TraitAliasExpansionInfo<'tcx>;
137
138     fn size_hint(&self) -> (usize, Option<usize>) {
139         (self.stack.len(), None)
140     }
141
142     fn next(&mut self) -> Option<TraitAliasExpansionInfo<'tcx>> {
143         while let Some(item) = self.stack.pop() {
144             if self.expand(&item) {
145                 return Some(item);
146             }
147         }
148         None
149     }
150 }
151
152 ///////////////////////////////////////////////////////////////////////////
153 // Iterator over def-IDs of supertraits
154 ///////////////////////////////////////////////////////////////////////////
155
156 pub struct SupertraitDefIds<'tcx> {
157     tcx: TyCtxt<'tcx>,
158     stack: Vec<DefId>,
159     visited: FxHashSet<DefId>,
160 }
161
162 pub fn supertrait_def_ids(tcx: TyCtxt<'_>, trait_def_id: DefId) -> SupertraitDefIds<'_> {
163     SupertraitDefIds {
164         tcx,
165         stack: vec![trait_def_id],
166         visited: Some(trait_def_id).into_iter().collect(),
167     }
168 }
169
170 impl Iterator for SupertraitDefIds<'_> {
171     type Item = DefId;
172
173     fn next(&mut self) -> Option<DefId> {
174         let def_id = self.stack.pop()?;
175         let predicates = self.tcx.super_predicates_of(def_id);
176         let visited = &mut self.visited;
177         self.stack.extend(
178             predicates
179                 .predicates
180                 .iter()
181                 .filter_map(|(pred, _)| pred.to_opt_poly_trait_pred())
182                 .map(|trait_ref| trait_ref.def_id())
183                 .filter(|&super_def_id| visited.insert(super_def_id)),
184         );
185         Some(def_id)
186     }
187 }
188
189 ///////////////////////////////////////////////////////////////////////////
190 // Other
191 ///////////////////////////////////////////////////////////////////////////
192
193 /// Instantiate all bound parameters of the impl with the given substs,
194 /// returning the resulting trait ref and all obligations that arise.
195 /// The obligations are closed under normalization.
196 pub fn impl_trait_ref_and_oblig<'a, 'tcx>(
197     selcx: &mut SelectionContext<'a, 'tcx>,
198     param_env: ty::ParamEnv<'tcx>,
199     impl_def_id: DefId,
200     impl_substs: SubstsRef<'tcx>,
201 ) -> (ty::TraitRef<'tcx>, impl Iterator<Item = PredicateObligation<'tcx>>) {
202     let impl_trait_ref = selcx.tcx().impl_trait_ref(impl_def_id).unwrap();
203     let impl_trait_ref = impl_trait_ref.subst(selcx.tcx(), impl_substs);
204     let Normalized { value: impl_trait_ref, obligations: normalization_obligations1 } =
205         super::normalize(selcx, param_env, ObligationCause::dummy(), impl_trait_ref);
206
207     let predicates = selcx.tcx().predicates_of(impl_def_id);
208     let predicates = predicates.instantiate(selcx.tcx(), impl_substs);
209     let Normalized { value: predicates, obligations: normalization_obligations2 } =
210         super::normalize(selcx, param_env, ObligationCause::dummy(), predicates);
211     let impl_obligations =
212         predicates_for_generics(ObligationCause::dummy(), 0, param_env, predicates);
213
214     let impl_obligations = impl_obligations
215         .chain(normalization_obligations1.into_iter())
216         .chain(normalization_obligations2.into_iter());
217
218     (impl_trait_ref, impl_obligations)
219 }
220
221 pub fn predicates_for_generics<'tcx>(
222     cause: ObligationCause<'tcx>,
223     recursion_depth: usize,
224     param_env: ty::ParamEnv<'tcx>,
225     generic_bounds: ty::InstantiatedPredicates<'tcx>,
226 ) -> impl Iterator<Item = PredicateObligation<'tcx>> {
227     debug!("predicates_for_generics(generic_bounds={:?})", generic_bounds);
228
229     iter::zip(generic_bounds.predicates, generic_bounds.spans).map(move |(predicate, span)| {
230         let cause = match *cause.code() {
231             traits::ItemObligation(def_id) if !span.is_dummy() => traits::ObligationCause::new(
232                 cause.span,
233                 cause.body_id,
234                 traits::BindingObligation(def_id, span),
235             ),
236             _ => cause.clone(),
237         };
238         Obligation { cause, recursion_depth, param_env, predicate }
239     })
240 }
241
242 pub fn predicate_for_trait_ref<'tcx>(
243     tcx: TyCtxt<'tcx>,
244     cause: ObligationCause<'tcx>,
245     param_env: ty::ParamEnv<'tcx>,
246     trait_ref: ty::TraitRef<'tcx>,
247     recursion_depth: usize,
248 ) -> PredicateObligation<'tcx> {
249     Obligation {
250         cause,
251         param_env,
252         recursion_depth,
253         predicate: ty::Binder::dummy(trait_ref).without_const().to_predicate(tcx),
254     }
255 }
256
257 pub fn predicate_for_trait_def<'tcx>(
258     tcx: TyCtxt<'tcx>,
259     param_env: ty::ParamEnv<'tcx>,
260     cause: ObligationCause<'tcx>,
261     trait_def_id: DefId,
262     recursion_depth: usize,
263     self_ty: Ty<'tcx>,
264     params: &[GenericArg<'tcx>],
265 ) -> PredicateObligation<'tcx> {
266     let trait_ref =
267         ty::TraitRef { def_id: trait_def_id, substs: tcx.mk_substs_trait(self_ty, params) };
268     predicate_for_trait_ref(tcx, cause, param_env, trait_ref, recursion_depth)
269 }
270
271 /// Casts a trait reference into a reference to one of its super
272 /// traits; returns `None` if `target_trait_def_id` is not a
273 /// supertrait.
274 pub fn upcast_choices<'tcx>(
275     tcx: TyCtxt<'tcx>,
276     source_trait_ref: ty::PolyTraitRef<'tcx>,
277     target_trait_def_id: DefId,
278 ) -> Vec<ty::PolyTraitRef<'tcx>> {
279     if source_trait_ref.def_id() == target_trait_def_id {
280         return vec![source_trait_ref]; // Shortcut the most common case.
281     }
282
283     supertraits(tcx, source_trait_ref).filter(|r| r.def_id() == target_trait_def_id).collect()
284 }
285
286 /// Given a trait `trait_ref`, returns the number of vtable entries
287 /// that come from `trait_ref`, excluding its supertraits. Used in
288 /// computing the vtable base for an upcast trait of a trait object.
289 pub fn count_own_vtable_entries<'tcx>(
290     tcx: TyCtxt<'tcx>,
291     trait_ref: ty::PolyTraitRef<'tcx>,
292 ) -> usize {
293     let existential_trait_ref =
294         trait_ref.map_bound(|trait_ref| ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref));
295     let existential_trait_ref = tcx.erase_regions(existential_trait_ref);
296     tcx.own_existential_vtable_entries(existential_trait_ref).len()
297 }
298
299 /// Given an upcast trait object described by `object`, returns the
300 /// index of the method `method_def_id` (which should be part of
301 /// `object.upcast_trait_ref`) within the vtable for `object`.
302 pub fn get_vtable_index_of_object_method<'tcx, N>(
303     tcx: TyCtxt<'tcx>,
304     object: &super::ImplSourceObjectData<'tcx, N>,
305     method_def_id: DefId,
306 ) -> usize {
307     let existential_trait_ref = object
308         .upcast_trait_ref
309         .map_bound(|trait_ref| ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref));
310     let existential_trait_ref = tcx.erase_regions(existential_trait_ref);
311     // Count number of methods preceding the one we are selecting and
312     // add them to the total offset.
313     let index = tcx
314         .own_existential_vtable_entries(existential_trait_ref)
315         .iter()
316         .copied()
317         .position(|def_id| def_id == method_def_id)
318         .unwrap_or_else(|| {
319             bug!("get_vtable_index_of_object_method: {:?} was not found", method_def_id);
320         });
321     object.vtable_base + index
322 }
323
324 pub fn closure_trait_ref_and_return_type<'tcx>(
325     tcx: TyCtxt<'tcx>,
326     fn_trait_def_id: DefId,
327     self_ty: Ty<'tcx>,
328     sig: ty::PolyFnSig<'tcx>,
329     tuple_arguments: TupleArgumentsFlag,
330 ) -> ty::Binder<'tcx, (ty::TraitRef<'tcx>, Ty<'tcx>)> {
331     let arguments_tuple = match tuple_arguments {
332         TupleArgumentsFlag::No => sig.skip_binder().inputs()[0],
333         TupleArgumentsFlag::Yes => tcx.intern_tup(sig.skip_binder().inputs()),
334     };
335     debug_assert!(!self_ty.has_escaping_bound_vars());
336     let trait_ref = ty::TraitRef {
337         def_id: fn_trait_def_id,
338         substs: tcx.mk_substs_trait(self_ty, &[arguments_tuple.into()]),
339     };
340     sig.map_bound(|sig| (trait_ref, sig.output()))
341 }
342
343 pub fn generator_trait_ref_and_outputs<'tcx>(
344     tcx: TyCtxt<'tcx>,
345     fn_trait_def_id: DefId,
346     self_ty: Ty<'tcx>,
347     sig: ty::PolyGenSig<'tcx>,
348 ) -> ty::Binder<'tcx, (ty::TraitRef<'tcx>, Ty<'tcx>, Ty<'tcx>)> {
349     debug_assert!(!self_ty.has_escaping_bound_vars());
350     let trait_ref = ty::TraitRef {
351         def_id: fn_trait_def_id,
352         substs: tcx.mk_substs_trait(self_ty, &[sig.skip_binder().resume_ty.into()]),
353     };
354     sig.map_bound(|sig| (trait_ref, sig.yield_ty, sig.return_ty))
355 }
356
357 pub fn impl_item_is_final(tcx: TyCtxt<'_>, assoc_item: &ty::AssocItem) -> bool {
358     assoc_item.defaultness.is_final() && tcx.impl_defaultness(assoc_item.container.id()).is_final()
359 }
360
361 pub enum TupleArgumentsFlag {
362     Yes,
363     No,
364 }