]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_hir_analysis/src/collect/predicates_of.rs
change usages of impl_trait_ref to bound_impl_trait_ref
[rust.git] / compiler / rustc_hir_analysis / src / collect / predicates_of.rs
1 use crate::astconv::AstConv;
2 use crate::bounds::Bounds;
3 use crate::collect::ItemCtxt;
4 use crate::constrained_generic_params as cgp;
5 use hir::{HirId, Node};
6 use rustc_data_structures::fx::FxIndexSet;
7 use rustc_hir as hir;
8 use rustc_hir::def::DefKind;
9 use rustc_hir::def_id::{DefId, LocalDefId};
10 use rustc_hir::intravisit::{self, Visitor};
11 use rustc_middle::ty::subst::InternalSubsts;
12 use rustc_middle::ty::ToPredicate;
13 use rustc_middle::ty::{self, Ty, TyCtxt};
14 use rustc_span::symbol::{sym, Ident};
15 use rustc_span::{Span, DUMMY_SP};
16
17 #[derive(Debug)]
18 struct OnlySelfBounds(bool);
19
20 /// Returns a list of all type predicates (explicit and implicit) for the definition with
21 /// ID `def_id`. This includes all predicates returned by `predicates_defined_on`, plus
22 /// `Self: Trait` predicates for traits.
23 pub(super) fn predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
24     let mut result = tcx.predicates_defined_on(def_id);
25
26     if tcx.is_trait(def_id) {
27         // For traits, add `Self: Trait` predicate. This is
28         // not part of the predicates that a user writes, but it
29         // is something that one must prove in order to invoke a
30         // method or project an associated type.
31         //
32         // In the chalk setup, this predicate is not part of the
33         // "predicates" for a trait item. But it is useful in
34         // rustc because if you directly (e.g.) invoke a trait
35         // method like `Trait::method(...)`, you must naturally
36         // prove that the trait applies to the types that were
37         // used, and adding the predicate into this list ensures
38         // that this is done.
39         //
40         // We use a DUMMY_SP here as a way to signal trait bounds that come
41         // from the trait itself that *shouldn't* be shown as the source of
42         // an obligation and instead be skipped. Otherwise we'd use
43         // `tcx.def_span(def_id);`
44
45         let constness = if tcx.has_attr(def_id, sym::const_trait) {
46             ty::BoundConstness::ConstIfConst
47         } else {
48             ty::BoundConstness::NotConst
49         };
50
51         let span = rustc_span::DUMMY_SP;
52         result.predicates =
53             tcx.arena.alloc_from_iter(result.predicates.iter().copied().chain(std::iter::once((
54                 ty::TraitRef::identity(tcx, def_id).with_constness(constness).to_predicate(tcx),
55                 span,
56             ))));
57     }
58     debug!("predicates_of(def_id={:?}) = {:?}", def_id, result);
59     result
60 }
61
62 /// Returns a list of user-specified type predicates for the definition with ID `def_id`.
63 /// N.B., this does not include any implied/inferred constraints.
64 #[instrument(level = "trace", skip(tcx), ret)]
65 fn gather_explicit_predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> {
66     use rustc_hir::*;
67
68     let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
69     let node = tcx.hir().get(hir_id);
70
71     let mut is_trait = None;
72     let mut is_default_impl_trait = None;
73
74     let icx = ItemCtxt::new(tcx, def_id);
75
76     const NO_GENERICS: &hir::Generics<'_> = hir::Generics::empty();
77
78     // We use an `IndexSet` to preserve order of insertion.
79     // Preserving the order of insertion is important here so as not to break UI tests.
80     let mut predicates: FxIndexSet<(ty::Predicate<'_>, Span)> = FxIndexSet::default();
81
82     let ast_generics = match node {
83         Node::TraitItem(item) => item.generics,
84
85         Node::ImplItem(item) => item.generics,
86
87         Node::Item(item) => match item.kind {
88             ItemKind::Impl(ref impl_) => {
89                 if impl_.defaultness.is_default() {
90                     is_default_impl_trait = tcx
91                         .bound_impl_trait_ref(def_id)
92                         .map(|t| ty::Binder::dummy(t.subst_identity()));
93                 }
94                 &impl_.generics
95             }
96             ItemKind::Fn(.., ref generics, _)
97             | ItemKind::TyAlias(_, ref generics)
98             | ItemKind::Enum(_, ref generics)
99             | ItemKind::Struct(_, ref generics)
100             | ItemKind::Union(_, ref generics) => *generics,
101
102             ItemKind::Trait(_, _, ref generics, ..) | ItemKind::TraitAlias(ref generics, _) => {
103                 is_trait = Some(ty::TraitRef::identity(tcx, def_id));
104                 *generics
105             }
106             ItemKind::OpaqueTy(OpaqueTy { ref generics, .. }) => generics,
107             _ => NO_GENERICS,
108         },
109
110         Node::ForeignItem(item) => match item.kind {
111             ForeignItemKind::Static(..) => NO_GENERICS,
112             ForeignItemKind::Fn(_, _, ref generics) => *generics,
113             ForeignItemKind::Type => NO_GENERICS,
114         },
115
116         _ => NO_GENERICS,
117     };
118
119     let generics = tcx.generics_of(def_id);
120     let parent_count = generics.parent_count as u32;
121     let has_own_self = generics.has_self && parent_count == 0;
122
123     // Below we'll consider the bounds on the type parameters (including `Self`)
124     // and the explicit where-clauses, but to get the full set of predicates
125     // on a trait we need to add in the supertrait bounds and bounds found on
126     // associated types.
127     if let Some(_trait_ref) = is_trait {
128         predicates.extend(tcx.super_predicates_of(def_id).predicates.iter().cloned());
129     }
130
131     // In default impls, we can assume that the self type implements
132     // the trait. So in:
133     //
134     //     default impl Foo for Bar { .. }
135     //
136     // we add a default where clause `Foo: Bar`. We do a similar thing for traits
137     // (see below). Recall that a default impl is not itself an impl, but rather a
138     // set of defaults that can be incorporated into another impl.
139     if let Some(trait_ref) = is_default_impl_trait {
140         predicates.insert((trait_ref.without_const().to_predicate(tcx), tcx.def_span(def_id)));
141     }
142
143     // Collect the region predicates that were declared inline as
144     // well. In the case of parameters declared on a fn or method, we
145     // have to be careful to only iterate over early-bound regions.
146     let mut index = parent_count
147         + has_own_self as u32
148         + super::early_bound_lifetimes_from_generics(tcx, ast_generics).count() as u32;
149
150     trace!(?predicates);
151     trace!(?ast_generics);
152     trace!(?generics);
153
154     // Collect the predicates that were written inline by the user on each
155     // type parameter (e.g., `<T: Foo>`).
156     for param in ast_generics.params {
157         match param.kind {
158             // We already dealt with early bound lifetimes above.
159             GenericParamKind::Lifetime { .. } => (),
160             GenericParamKind::Type { .. } => {
161                 let name = param.name.ident().name;
162                 let param_ty = ty::ParamTy::new(index, name).to_ty(tcx);
163                 index += 1;
164
165                 let mut bounds = Bounds::default();
166                 // Params are implicitly sized unless a `?Sized` bound is found
167                 icx.astconv().add_implicitly_sized(
168                     &mut bounds,
169                     param_ty,
170                     &[],
171                     Some((param.def_id, ast_generics.predicates)),
172                     param.span,
173                 );
174                 trace!(?bounds);
175                 predicates.extend(bounds.predicates());
176                 trace!(?predicates);
177             }
178             GenericParamKind::Const { .. } => {
179                 // Bounds on const parameters are currently not possible.
180                 index += 1;
181             }
182         }
183     }
184
185     trace!(?predicates);
186     // Add in the bounds that appear in the where-clause.
187     for predicate in ast_generics.predicates {
188         match predicate {
189             hir::WherePredicate::BoundPredicate(bound_pred) => {
190                 let ty = icx.to_ty(bound_pred.bounded_ty);
191                 let bound_vars = icx.tcx.late_bound_vars(bound_pred.hir_id);
192
193                 // Keep the type around in a dummy predicate, in case of no bounds.
194                 // That way, `where Ty:` is not a complete noop (see #53696) and `Ty`
195                 // is still checked for WF.
196                 if bound_pred.bounds.is_empty() {
197                     if let ty::Param(_) = ty.kind() {
198                         // This is a `where T:`, which can be in the HIR from the
199                         // transformation that moves `?Sized` to `T`'s declaration.
200                         // We can skip the predicate because type parameters are
201                         // trivially WF, but also we *should*, to avoid exposing
202                         // users who never wrote `where Type:,` themselves, to
203                         // compiler/tooling bugs from not handling WF predicates.
204                     } else {
205                         let span = bound_pred.bounded_ty.span;
206                         let predicate = ty::Binder::bind_with_vars(
207                             ty::PredicateKind::WellFormed(ty.into()),
208                             bound_vars,
209                         );
210                         predicates.insert((predicate.to_predicate(tcx), span));
211                     }
212                 }
213
214                 let mut bounds = Bounds::default();
215                 icx.astconv().add_bounds(ty, bound_pred.bounds.iter(), &mut bounds, bound_vars);
216                 predicates.extend(bounds.predicates());
217             }
218
219             hir::WherePredicate::RegionPredicate(region_pred) => {
220                 let r1 = icx.astconv().ast_region_to_region(&region_pred.lifetime, None);
221                 predicates.extend(region_pred.bounds.iter().map(|bound| {
222                     let (r2, span) = match bound {
223                         hir::GenericBound::Outlives(lt) => {
224                             (icx.astconv().ast_region_to_region(lt, None), lt.ident.span)
225                         }
226                         _ => bug!(),
227                     };
228                     let pred = ty::Binder::dummy(ty::PredicateKind::Clause(
229                         ty::Clause::RegionOutlives(ty::OutlivesPredicate(r1, r2)),
230                     ))
231                     .to_predicate(icx.tcx);
232
233                     (pred, span)
234                 }))
235             }
236
237             hir::WherePredicate::EqPredicate(..) => {
238                 // FIXME(#20041)
239             }
240         }
241     }
242
243     if tcx.features().generic_const_exprs {
244         predicates.extend(const_evaluatable_predicates_of(tcx, def_id.expect_local()));
245     }
246
247     let mut predicates: Vec<_> = predicates.into_iter().collect();
248
249     // Subtle: before we store the predicates into the tcx, we
250     // sort them so that predicates like `T: Foo<Item=U>` come
251     // before uses of `U`.  This avoids false ambiguity errors
252     // in trait checking. See `setup_constraining_predicates`
253     // for details.
254     if let Node::Item(&Item { kind: ItemKind::Impl { .. }, .. }) = node {
255         let self_ty = tcx.type_of(def_id);
256         let trait_ref = tcx.bound_impl_trait_ref(def_id).map(ty::EarlyBinder::subst_identity);
257         cgp::setup_constraining_predicates(
258             tcx,
259             &mut predicates,
260             trait_ref,
261             &mut cgp::parameters_for_impl(self_ty, trait_ref),
262         );
263     }
264
265     // Opaque types duplicate some of their generic parameters.
266     // We create bi-directional Outlives predicates between the original
267     // and the duplicated parameter, to ensure that they do not get out of sync.
268     if let Node::Item(&Item { kind: ItemKind::OpaqueTy(..), .. }) = node {
269         let opaque_ty_id = tcx.hir().parent_id(hir_id);
270         let opaque_ty_node = tcx.hir().get(opaque_ty_id);
271         let Node::Ty(&Ty { kind: TyKind::OpaqueDef(_, lifetimes, _), .. }) = opaque_ty_node else {
272             bug!("unexpected {opaque_ty_node:?}")
273         };
274         debug!(?lifetimes);
275         for (arg, duplicate) in std::iter::zip(lifetimes, ast_generics.params) {
276             let hir::GenericArg::Lifetime(arg) = arg else { bug!() };
277             let orig_region = icx.astconv().ast_region_to_region(&arg, None);
278             if !matches!(orig_region.kind(), ty::ReEarlyBound(..)) {
279                 // Only early-bound regions can point to the original generic parameter.
280                 continue;
281             }
282
283             let hir::GenericParamKind::Lifetime { .. } = duplicate.kind else { continue };
284             let dup_def = tcx.hir().local_def_id(duplicate.hir_id).to_def_id();
285
286             let Some(dup_index) = generics.param_def_id_to_index(tcx, dup_def) else { bug!() };
287
288             let dup_region = tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion {
289                 def_id: dup_def,
290                 index: dup_index,
291                 name: duplicate.name.ident().name,
292             }));
293             predicates.push((
294                 ty::Binder::dummy(ty::PredicateKind::Clause(ty::Clause::RegionOutlives(
295                     ty::OutlivesPredicate(orig_region, dup_region),
296                 )))
297                 .to_predicate(icx.tcx),
298                 duplicate.span,
299             ));
300             predicates.push((
301                 ty::Binder::dummy(ty::PredicateKind::Clause(ty::Clause::RegionOutlives(
302                     ty::OutlivesPredicate(dup_region, orig_region),
303                 )))
304                 .to_predicate(icx.tcx),
305                 duplicate.span,
306             ));
307         }
308         debug!(?predicates);
309     }
310
311     ty::GenericPredicates {
312         parent: generics.parent,
313         predicates: tcx.arena.alloc_from_iter(predicates),
314     }
315 }
316
317 fn const_evaluatable_predicates_of(
318     tcx: TyCtxt<'_>,
319     def_id: LocalDefId,
320 ) -> FxIndexSet<(ty::Predicate<'_>, Span)> {
321     struct ConstCollector<'tcx> {
322         tcx: TyCtxt<'tcx>,
323         preds: FxIndexSet<(ty::Predicate<'tcx>, Span)>,
324     }
325
326     impl<'tcx> intravisit::Visitor<'tcx> for ConstCollector<'tcx> {
327         fn visit_anon_const(&mut self, c: &'tcx hir::AnonConst) {
328             let ct = ty::Const::from_anon_const(self.tcx, c.def_id);
329             if let ty::ConstKind::Unevaluated(_) = ct.kind() {
330                 let span = self.tcx.def_span(c.def_id);
331                 self.preds.insert((
332                     ty::Binder::dummy(ty::PredicateKind::ConstEvaluatable(ct))
333                         .to_predicate(self.tcx),
334                     span,
335                 ));
336             }
337         }
338
339         fn visit_const_param_default(&mut self, _param: HirId, _ct: &'tcx hir::AnonConst) {
340             // Do not look into const param defaults,
341             // these get checked when they are actually instantiated.
342             //
343             // We do not want the following to error:
344             //
345             //     struct Foo<const N: usize, const M: usize = { N + 1 }>;
346             //     struct Bar<const N: usize>(Foo<N, 3>);
347         }
348     }
349
350     let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
351     let node = tcx.hir().get(hir_id);
352
353     let mut collector = ConstCollector { tcx, preds: FxIndexSet::default() };
354     if let hir::Node::Item(item) = node && let hir::ItemKind::Impl(ref impl_) = item.kind {
355         if let Some(of_trait) = &impl_.of_trait {
356             debug!("const_evaluatable_predicates_of({:?}): visit impl trait_ref", def_id);
357             collector.visit_trait_ref(of_trait);
358         }
359
360         debug!("const_evaluatable_predicates_of({:?}): visit_self_ty", def_id);
361         collector.visit_ty(impl_.self_ty);
362     }
363
364     if let Some(generics) = node.generics() {
365         debug!("const_evaluatable_predicates_of({:?}): visit_generics", def_id);
366         collector.visit_generics(generics);
367     }
368
369     if let Some(fn_sig) = tcx.hir().fn_sig_by_hir_id(hir_id) {
370         debug!("const_evaluatable_predicates_of({:?}): visit_fn_decl", def_id);
371         collector.visit_fn_decl(fn_sig.decl);
372     }
373     debug!("const_evaluatable_predicates_of({:?}) = {:?}", def_id, collector.preds);
374
375     collector.preds
376 }
377
378 pub(super) fn trait_explicit_predicates_and_bounds(
379     tcx: TyCtxt<'_>,
380     def_id: LocalDefId,
381 ) -> ty::GenericPredicates<'_> {
382     assert_eq!(tcx.def_kind(def_id), DefKind::Trait);
383     gather_explicit_predicates_of(tcx, def_id.to_def_id())
384 }
385
386 pub(super) fn explicit_predicates_of<'tcx>(
387     tcx: TyCtxt<'tcx>,
388     def_id: DefId,
389 ) -> ty::GenericPredicates<'tcx> {
390     let def_kind = tcx.def_kind(def_id);
391     if let DefKind::Trait = def_kind {
392         // Remove bounds on associated types from the predicates, they will be
393         // returned by `explicit_item_bounds`.
394         let predicates_and_bounds = tcx.trait_explicit_predicates_and_bounds(def_id.expect_local());
395         let trait_identity_substs = InternalSubsts::identity_for_item(tcx, def_id);
396
397         let is_assoc_item_ty = |ty: Ty<'tcx>| {
398             // For a predicate from a where clause to become a bound on an
399             // associated type:
400             // * It must use the identity substs of the item.
401             //   * We're in the scope of the trait, so we can't name any
402             //     parameters of the GAT. That means that all we need to
403             //     check are that the substs of the projection are the
404             //     identity substs of the trait.
405             // * It must be an associated type for this trait (*not* a
406             //   supertrait).
407             if let ty::Alias(ty::Projection, projection) = ty.kind() {
408                 projection.substs == trait_identity_substs
409                     && tcx.associated_item(projection.def_id).container_id(tcx) == def_id
410             } else {
411                 false
412             }
413         };
414
415         let predicates: Vec<_> = predicates_and_bounds
416             .predicates
417             .iter()
418             .copied()
419             .filter(|(pred, _)| match pred.kind().skip_binder() {
420                 ty::PredicateKind::Clause(ty::Clause::Trait(tr)) => !is_assoc_item_ty(tr.self_ty()),
421                 ty::PredicateKind::Clause(ty::Clause::Projection(proj)) => {
422                     !is_assoc_item_ty(proj.projection_ty.self_ty())
423                 }
424                 ty::PredicateKind::Clause(ty::Clause::TypeOutlives(outlives)) => {
425                     !is_assoc_item_ty(outlives.0)
426                 }
427                 _ => true,
428             })
429             .collect();
430         if predicates.len() == predicates_and_bounds.predicates.len() {
431             predicates_and_bounds
432         } else {
433             ty::GenericPredicates {
434                 parent: predicates_and_bounds.parent,
435                 predicates: tcx.arena.alloc_slice(&predicates),
436             }
437         }
438     } else {
439         if matches!(def_kind, DefKind::AnonConst) && tcx.lazy_normalization() {
440             let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
441             let parent_def_id = tcx.hir().get_parent_item(hir_id);
442
443             if tcx.hir().opt_const_param_default_param_def_id(hir_id).is_some() {
444                 // In `generics_of` we set the generics' parent to be our parent's parent which means that
445                 // we lose out on the predicates of our actual parent if we dont return those predicates here.
446                 // (See comment in `generics_of` for more information on why the parent shenanigans is necessary)
447                 //
448                 // struct Foo<T, const N: usize = { <T as Trait>::ASSOC }>(T) where T: Trait;
449                 //        ^^^                     ^^^^^^^^^^^^^^^^^^^^^^^ the def id we are calling
450                 //        ^^^                                             explicit_predicates_of on
451                 //        parent item we dont have set as the
452                 //        parent of generics returned by `generics_of`
453                 //
454                 // In the above code we want the anon const to have predicates in its param env for `T: Trait`
455                 // and we would be calling `explicit_predicates_of(Foo)` here
456                 return tcx.explicit_predicates_of(parent_def_id);
457             }
458
459             let parent_def_kind = tcx.def_kind(parent_def_id);
460             if matches!(parent_def_kind, DefKind::OpaqueTy) {
461                 // In `instantiate_identity` we inherit the predicates of our parent.
462                 // However, opaque types do not have a parent (see `gather_explicit_predicates_of`), which means
463                 // that we lose out on the predicates of our actual parent if we dont return those predicates here.
464                 //
465                 //
466                 // fn foo<T: Trait>() -> impl Iterator<Output = Another<{ <T as Trait>::ASSOC }> > { todo!() }
467                 //                                                        ^^^^^^^^^^^^^^^^^^^ the def id we are calling
468                 //                                                                            explicit_predicates_of on
469                 //
470                 // In the above code we want the anon const to have predicates in its param env for `T: Trait`.
471                 // However, the anon const cannot inherit predicates from its parent since it's opaque.
472                 //
473                 // To fix this, we call `explicit_predicates_of` directly on `foo`, the parent's parent.
474
475                 // In the above example this is `foo::{opaque#0}` or `impl Iterator`
476                 let parent_hir_id = tcx.hir().local_def_id_to_hir_id(parent_def_id.def_id);
477
478                 // In the above example this is the function `foo`
479                 let item_def_id = tcx.hir().get_parent_item(parent_hir_id);
480
481                 // In the above code example we would be calling `explicit_predicates_of(foo)` here
482                 return tcx.explicit_predicates_of(item_def_id);
483             }
484         }
485         gather_explicit_predicates_of(tcx, def_id)
486     }
487 }
488
489 /// Ensures that the super-predicates of the trait with a `DefId`
490 /// of `trait_def_id` are converted and stored. This also ensures that
491 /// the transitive super-predicates are converted.
492 pub(super) fn super_predicates_of(
493     tcx: TyCtxt<'_>,
494     trait_def_id: DefId,
495 ) -> ty::GenericPredicates<'_> {
496     tcx.super_predicates_that_define_assoc_type((trait_def_id, None))
497 }
498
499 /// Ensures that the super-predicates of the trait with a `DefId`
500 /// of `trait_def_id` are converted and stored. This also ensures that
501 /// the transitive super-predicates are converted.
502 pub(super) fn super_predicates_that_define_assoc_type(
503     tcx: TyCtxt<'_>,
504     (trait_def_id, assoc_name): (DefId, Option<Ident>),
505 ) -> ty::GenericPredicates<'_> {
506     if trait_def_id.is_local() {
507         debug!("local trait");
508         let trait_hir_id = tcx.hir().local_def_id_to_hir_id(trait_def_id.expect_local());
509
510         let Node::Item(item) = tcx.hir().get(trait_hir_id) else {
511             bug!("trait_node_id {} is not an item", trait_hir_id);
512         };
513
514         let (generics, bounds) = match item.kind {
515             hir::ItemKind::Trait(.., ref generics, ref supertraits, _) => (generics, supertraits),
516             hir::ItemKind::TraitAlias(ref generics, ref supertraits) => (generics, supertraits),
517             _ => span_bug!(item.span, "super_predicates invoked on non-trait"),
518         };
519
520         let icx = ItemCtxt::new(tcx, trait_def_id);
521
522         // Convert the bounds that follow the colon, e.g., `Bar + Zed` in `trait Foo: Bar + Zed`.
523         let self_param_ty = tcx.types.self_param;
524         let superbounds1 = if let Some(assoc_name) = assoc_name {
525             icx.astconv().compute_bounds_that_match_assoc_type(self_param_ty, bounds, assoc_name)
526         } else {
527             icx.astconv().compute_bounds(self_param_ty, bounds)
528         };
529
530         let superbounds1 = superbounds1.predicates();
531
532         // Convert any explicit superbounds in the where-clause,
533         // e.g., `trait Foo where Self: Bar`.
534         // In the case of trait aliases, however, we include all bounds in the where-clause,
535         // so e.g., `trait Foo = where u32: PartialEq<Self>` would include `u32: PartialEq<Self>`
536         // as one of its "superpredicates".
537         let is_trait_alias = tcx.is_trait_alias(trait_def_id);
538         let superbounds2 = icx.type_parameter_bounds_in_generics(
539             generics,
540             item.owner_id.def_id,
541             self_param_ty,
542             OnlySelfBounds(!is_trait_alias),
543             assoc_name,
544         );
545
546         // Combine the two lists to form the complete set of superbounds:
547         let superbounds = &*tcx.arena.alloc_from_iter(superbounds1.into_iter().chain(superbounds2));
548         debug!(?superbounds);
549
550         // Now require that immediate supertraits are converted,
551         // which will, in turn, reach indirect supertraits.
552         if assoc_name.is_none() {
553             // Now require that immediate supertraits are converted,
554             // which will, in turn, reach indirect supertraits.
555             for &(pred, span) in superbounds {
556                 debug!("superbound: {:?}", pred);
557                 if let ty::PredicateKind::Clause(ty::Clause::Trait(bound)) =
558                     pred.kind().skip_binder()
559                 {
560                     tcx.at(span).super_predicates_of(bound.def_id());
561                 }
562             }
563         }
564
565         ty::GenericPredicates { parent: None, predicates: superbounds }
566     } else {
567         // if `assoc_name` is None, then the query should've been redirected to an
568         // external provider
569         assert!(assoc_name.is_some());
570         tcx.super_predicates_of(trait_def_id)
571     }
572 }
573
574 /// Returns the predicates defined on `item_def_id` of the form
575 /// `X: Foo` where `X` is the type parameter `def_id`.
576 #[instrument(level = "trace", skip(tcx))]
577 pub(super) fn type_param_predicates(
578     tcx: TyCtxt<'_>,
579     (item_def_id, def_id, assoc_name): (DefId, LocalDefId, Ident),
580 ) -> ty::GenericPredicates<'_> {
581     use rustc_hir::*;
582
583     // In the AST, bounds can derive from two places. Either
584     // written inline like `<T: Foo>` or in a where-clause like
585     // `where T: Foo`.
586
587     let param_id = tcx.hir().local_def_id_to_hir_id(def_id);
588     let param_owner = tcx.hir().ty_param_owner(def_id);
589     let generics = tcx.generics_of(param_owner);
590     let index = generics.param_def_id_to_index[&def_id.to_def_id()];
591     let ty = tcx.mk_ty_param(index, tcx.hir().ty_param_name(def_id));
592
593     // Don't look for bounds where the type parameter isn't in scope.
594     let parent = if item_def_id == param_owner.to_def_id() {
595         None
596     } else {
597         tcx.generics_of(item_def_id).parent
598     };
599
600     let mut result = parent
601         .map(|parent| {
602             let icx = ItemCtxt::new(tcx, parent);
603             icx.get_type_parameter_bounds(DUMMY_SP, def_id.to_def_id(), assoc_name)
604         })
605         .unwrap_or_default();
606     let mut extend = None;
607
608     let item_hir_id = tcx.hir().local_def_id_to_hir_id(item_def_id.expect_local());
609     let ast_generics = match tcx.hir().get(item_hir_id) {
610         Node::TraitItem(item) => &item.generics,
611
612         Node::ImplItem(item) => &item.generics,
613
614         Node::Item(item) => {
615             match item.kind {
616                 ItemKind::Fn(.., ref generics, _)
617                 | ItemKind::Impl(hir::Impl { ref generics, .. })
618                 | ItemKind::TyAlias(_, ref generics)
619                 | ItemKind::OpaqueTy(OpaqueTy {
620                     ref generics,
621                     origin: hir::OpaqueTyOrigin::TyAlias,
622                     ..
623                 })
624                 | ItemKind::Enum(_, ref generics)
625                 | ItemKind::Struct(_, ref generics)
626                 | ItemKind::Union(_, ref generics) => generics,
627                 ItemKind::Trait(_, _, ref generics, ..) => {
628                     // Implied `Self: Trait` and supertrait bounds.
629                     if param_id == item_hir_id {
630                         let identity_trait_ref = ty::TraitRef::identity(tcx, item_def_id);
631                         extend =
632                             Some((identity_trait_ref.without_const().to_predicate(tcx), item.span));
633                     }
634                     generics
635                 }
636                 _ => return result,
637             }
638         }
639
640         Node::ForeignItem(item) => match item.kind {
641             ForeignItemKind::Fn(_, _, ref generics) => generics,
642             _ => return result,
643         },
644
645         _ => return result,
646     };
647
648     let icx = ItemCtxt::new(tcx, item_def_id);
649     let extra_predicates = extend.into_iter().chain(
650         icx.type_parameter_bounds_in_generics(
651             ast_generics,
652             def_id,
653             ty,
654             OnlySelfBounds(true),
655             Some(assoc_name),
656         )
657         .into_iter()
658         .filter(|(predicate, _)| match predicate.kind().skip_binder() {
659             ty::PredicateKind::Clause(ty::Clause::Trait(data)) => data.self_ty().is_param(index),
660             _ => false,
661         }),
662     );
663     result.predicates =
664         tcx.arena.alloc_from_iter(result.predicates.iter().copied().chain(extra_predicates));
665     result
666 }
667
668 impl<'tcx> ItemCtxt<'tcx> {
669     /// Finds bounds from `hir::Generics`. This requires scanning through the
670     /// AST. We do this to avoid having to convert *all* the bounds, which
671     /// would create artificial cycles. Instead, we can only convert the
672     /// bounds for a type parameter `X` if `X::Foo` is used.
673     #[instrument(level = "trace", skip(self, ast_generics))]
674     fn type_parameter_bounds_in_generics(
675         &self,
676         ast_generics: &'tcx hir::Generics<'tcx>,
677         param_def_id: LocalDefId,
678         ty: Ty<'tcx>,
679         only_self_bounds: OnlySelfBounds,
680         assoc_name: Option<Ident>,
681     ) -> Vec<(ty::Predicate<'tcx>, Span)> {
682         ast_generics
683             .predicates
684             .iter()
685             .filter_map(|wp| match *wp {
686                 hir::WherePredicate::BoundPredicate(ref bp) => Some(bp),
687                 _ => None,
688             })
689             .flat_map(|bp| {
690                 let bt = if bp.is_param_bound(param_def_id.to_def_id()) {
691                     Some(ty)
692                 } else if !only_self_bounds.0 {
693                     Some(self.to_ty(bp.bounded_ty))
694                 } else {
695                     None
696                 };
697                 let bvars = self.tcx.late_bound_vars(bp.hir_id);
698
699                 bp.bounds.iter().filter_map(move |b| bt.map(|bt| (bt, b, bvars))).filter(
700                     |(_, b, _)| match assoc_name {
701                         Some(assoc_name) => self.bound_defines_assoc_item(b, assoc_name),
702                         None => true,
703                     },
704                 )
705             })
706             .flat_map(|(bt, b, bvars)| predicates_from_bound(self, bt, b, bvars))
707             .collect()
708     }
709
710     #[instrument(level = "trace", skip(self))]
711     fn bound_defines_assoc_item(&self, b: &hir::GenericBound<'_>, assoc_name: Ident) -> bool {
712         match b {
713             hir::GenericBound::Trait(poly_trait_ref, _) => {
714                 let trait_ref = &poly_trait_ref.trait_ref;
715                 if let Some(trait_did) = trait_ref.trait_def_id() {
716                     self.tcx.trait_may_define_assoc_type(trait_did, assoc_name)
717                 } else {
718                     false
719                 }
720             }
721             _ => false,
722         }
723     }
724 }
725
726 /// Converts a specific `GenericBound` from the AST into a set of
727 /// predicates that apply to the self type. A vector is returned
728 /// because this can be anywhere from zero predicates (`T: ?Sized` adds no
729 /// predicates) to one (`T: Foo`) to many (`T: Bar<X = i32>` adds `T: Bar`
730 /// and `<T as Bar>::X == i32`).
731 fn predicates_from_bound<'tcx>(
732     astconv: &dyn AstConv<'tcx>,
733     param_ty: Ty<'tcx>,
734     bound: &'tcx hir::GenericBound<'tcx>,
735     bound_vars: &'tcx ty::List<ty::BoundVariableKind>,
736 ) -> Vec<(ty::Predicate<'tcx>, Span)> {
737     let mut bounds = Bounds::default();
738     astconv.add_bounds(param_ty, [bound].into_iter(), &mut bounds, bound_vars);
739     bounds.predicates().collect()
740 }