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