1use std::ops::ControlFlow;
2
3use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
4use rustc_errors::codes::*;
5use rustc_errors::struct_span_code_err;
6use rustc_hir as hir;
7use rustc_hir::def::{DefKind, Res};
8use rustc_hir::def_id::DefId;
9use rustc_hir::{PolyTraitRef, find_attr};
10use rustc_middle::bug;
11use rustc_middle::ty::{
12 self as ty, IsSuggestable, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitableExt,
13 TypeVisitor, Upcast,
14};
15use rustc_span::{ErrorGuaranteed, Ident, Span, kw};
16use rustc_trait_selection::traits;
17use tracing::{debug, instrument};
18
19use crate::diagnostics;
20use crate::hir_ty_lowering::{
21 AssocItemQSelf, GenericsArgsErrExtend, HirTyLowerer, ImpliedBoundsContext,
22 OverlappingAsssocItemConstraints, PredicateFilter, RegionInferReason,
23};
24
25#[derive(#[automatically_derived]
impl ::core::fmt::Debug for CollectedBound {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field3_finish(f,
"CollectedBound", "positive", &self.positive, "maybe",
&self.maybe, "negative", &&self.negative)
}
}Debug, #[automatically_derived]
impl ::core::default::Default for CollectedBound {
#[inline]
fn default() -> CollectedBound {
CollectedBound {
positive: ::core::default::Default::default(),
maybe: ::core::default::Default::default(),
negative: ::core::default::Default::default(),
}
}
}Default)]
26struct CollectedBound {
27 positive: bool,
29 maybe: bool,
31 negative: bool,
33}
34
35impl CollectedBound {
36 fn any(&self) -> bool {
38 self.positive || self.maybe || self.negative
39 }
40}
41
42#[derive(#[automatically_derived]
impl ::core::fmt::Debug for CollectedSizednessBounds {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field3_finish(f,
"CollectedSizednessBounds", "sized", &self.sized, "meta_sized",
&self.meta_sized, "pointee_sized", &&self.pointee_sized)
}
}Debug)]
43struct CollectedSizednessBounds {
44 sized: CollectedBound,
46 meta_sized: CollectedBound,
48 pointee_sized: CollectedBound,
50}
51
52impl CollectedSizednessBounds {
53 fn any(&self) -> bool {
56 self.sized.any() || self.meta_sized.any() || self.pointee_sized.any()
57 }
58}
59
60fn search_bounds_for<'tcx>(
61 hir_bounds: &'tcx [hir::GenericBound<'tcx>],
62 context: ImpliedBoundsContext<'tcx>,
63 mut f: impl FnMut(&'tcx PolyTraitRef<'tcx>),
64) {
65 let mut search_bounds = |hir_bounds: &'tcx [hir::GenericBound<'tcx>]| {
66 for hir_bound in hir_bounds {
67 let hir::GenericBound::Trait(ptr) = hir_bound else {
68 continue;
69 };
70
71 f(ptr)
72 }
73 };
74
75 search_bounds(hir_bounds);
76 if let ImpliedBoundsContext::TyParam(self_ty, where_clause) = context {
77 for clause in where_clause {
78 if let hir::WherePredicateKind::BoundPredicate(pred) = clause.kind
79 && pred.is_param_bound(self_ty.to_def_id())
80 {
81 search_bounds(pred.bounds);
82 }
83 }
84 }
85}
86
87fn collect_bounds<'a, 'tcx>(
88 hir_bounds: &'a [hir::GenericBound<'tcx>],
89 context: ImpliedBoundsContext<'tcx>,
90 target_did: DefId,
91) -> CollectedBound {
92 let mut collect_into = CollectedBound::default();
93 search_bounds_for(hir_bounds, context, |ptr| {
94 if !#[allow(non_exhaustive_omitted_patterns)] match ptr.trait_ref.path.res {
Res::Def(DefKind::Trait, did) if did == target_did => true,
_ => false,
}matches!(ptr.trait_ref.path.res, Res::Def(DefKind::Trait, did) if did == target_did) {
95 return;
96 }
97
98 match ptr.modifiers.polarity {
99 hir::BoundPolarity::Maybe(_) => collect_into.maybe = true,
100 hir::BoundPolarity::Negative(_) => collect_into.negative = true,
101 hir::BoundPolarity::Positive => collect_into.positive = true,
102 }
103 });
104 collect_into
105}
106
107fn collect_sizedness_bounds<'tcx>(
108 tcx: TyCtxt<'tcx>,
109 hir_bounds: &'tcx [hir::GenericBound<'tcx>],
110 context: ImpliedBoundsContext<'tcx>,
111 span: Span,
112) -> CollectedSizednessBounds {
113 let sized_did = tcx.require_lang_item(hir::LangItem::Sized, span);
114 let sized = collect_bounds(hir_bounds, context, sized_did);
115
116 let meta_sized_did = tcx.require_lang_item(hir::LangItem::MetaSized, span);
117 let meta_sized = collect_bounds(hir_bounds, context, meta_sized_did);
118
119 let pointee_sized_did = tcx.require_lang_item(hir::LangItem::PointeeSized, span);
120 let pointee_sized = collect_bounds(hir_bounds, context, pointee_sized_did);
121
122 CollectedSizednessBounds { sized, meta_sized, pointee_sized }
123}
124
125fn add_trait_bound<'tcx>(
127 tcx: TyCtxt<'tcx>,
128 bounds: &mut Vec<(ty::Clause<'tcx>, Span)>,
129 self_ty: Ty<'tcx>,
130 did: DefId,
131 span: Span,
132) {
133 let trait_ref = ty::TraitRef::new(tcx, did, [self_ty]);
134 bounds.insert(0, (trait_ref.upcast(tcx), span));
137}
138
139impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
140 pub(crate) fn add_implicit_sizedness_bounds(
149 &self,
150 bounds: &mut Vec<(ty::Clause<'tcx>, Span)>,
151 self_ty: Ty<'tcx>,
152 hir_bounds: &'tcx [hir::GenericBound<'tcx>],
153 context: ImpliedBoundsContext<'tcx>,
154 span: Span,
155 ) {
156 let tcx = self.tcx();
157
158 if {
'done:
{
for i in tcx.hir_krate_attrs() {
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(RustcNoImplicitBounds) => {
break 'done Some(());
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}.is_some()find_attr!(tcx, crate, RustcNoImplicitBounds) {
160 return;
161 }
162
163 let meta_sized_did = tcx.require_lang_item(hir::LangItem::MetaSized, span);
164 let pointee_sized_did = tcx.require_lang_item(hir::LangItem::PointeeSized, span);
165
166 match context {
168 ImpliedBoundsContext::TraitDef(trait_did) => {
169 let trait_did = trait_did.to_def_id();
170 if trait_did == pointee_sized_did {
172 return;
173 }
174 if tcx.trait_is_auto(trait_did) {
177 return;
178 }
179 }
180 ImpliedBoundsContext::TyParam(..) | ImpliedBoundsContext::AssociatedTypeOrImplTrait => {
181 }
182 }
183
184 let collected = collect_sizedness_bounds(tcx, hir_bounds, context, span);
185 if (collected.sized.maybe || collected.sized.negative)
186 && !collected.sized.positive
187 && !collected.meta_sized.any()
188 && !collected.pointee_sized.any()
189 {
190 add_trait_bound(tcx, bounds, self_ty, meta_sized_did, span);
193 } else if !collected.any() {
194 match context {
195 ImpliedBoundsContext::TraitDef(..) => {
196 add_trait_bound(tcx, bounds, self_ty, meta_sized_did, span);
199 }
200 ImpliedBoundsContext::TyParam(..)
201 | ImpliedBoundsContext::AssociatedTypeOrImplTrait => {
202 let sized_did = tcx.require_lang_item(hir::LangItem::Sized, span);
205 add_trait_bound(tcx, bounds, self_ty, sized_did, span);
206 }
207 }
208 }
209 }
210
211 pub(crate) fn add_default_traits(
212 &self,
213 bounds: &mut Vec<(ty::Clause<'tcx>, Span)>,
214 self_ty: Ty<'tcx>,
215 hir_bounds: &[hir::GenericBound<'tcx>],
216 context: ImpliedBoundsContext<'tcx>,
217 span: Span,
218 ) {
219 self.tcx().default_traits().iter().for_each(|default_trait| {
220 self.add_default_trait(*default_trait, bounds, self_ty, hir_bounds, context, span);
221 });
222 }
223
224 pub(crate) fn add_default_trait(
228 &self,
229 trait_: hir::LangItem,
230 bounds: &mut Vec<(ty::Clause<'tcx>, Span)>,
231 self_ty: Ty<'tcx>,
232 hir_bounds: &[hir::GenericBound<'tcx>],
233 context: ImpliedBoundsContext<'tcx>,
234 span: Span,
235 ) {
236 let tcx = self.tcx();
237
238 if let ImpliedBoundsContext::TraitDef(trait_did) = context
241 && self.tcx().trait_is_auto(trait_did.into())
242 {
243 return;
244 }
245
246 if let Some(trait_did) = tcx.lang_items().get(trait_)
247 && self.should_add_default_traits(trait_did, hir_bounds, context)
248 {
249 add_trait_bound(tcx, bounds, self_ty, trait_did, span);
250 }
251 }
252
253 fn should_add_default_traits<'a>(
255 &self,
256 trait_def_id: DefId,
257 hir_bounds: &'a [hir::GenericBound<'tcx>],
258 context: ImpliedBoundsContext<'tcx>,
259 ) -> bool {
260 let collected = collect_bounds(hir_bounds, context, trait_def_id);
261 !{
'done:
{
for i in self.tcx().hir_krate_attrs() {
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(RustcNoImplicitBounds) => {
break 'done Some(());
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}.is_some()find_attr!(self.tcx(), crate, RustcNoImplicitBounds) && !collected.any()
262 }
263
264 pub(crate) fn require_bound_to_relax_default_trait(
265 &self,
266 trait_ref: hir::TraitRef<'_>,
267 span: Span,
268 ) {
269 let tcx = self.tcx();
270
271 if let Res::Def(DefKind::Trait, def_id) = trait_ref.path.res
272 && (tcx.is_lang_item(def_id, hir::LangItem::Sized) || tcx.is_default_trait(def_id))
273 {
274 return;
275 }
276
277 self.dcx().span_err(
278 span,
279 if tcx.sess.opts.unstable_opts.experimental_default_bounds
280 || tcx.features().more_maybe_bounds()
281 {
282 "bound modifier `?` can only be applied to default traits"
283 } else {
284 "bound modifier `?` can only be applied to `Sized`"
285 },
286 );
287 }
288
289 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("lower_bounds",
"rustc_hir_analysis::hir_ty_lowering::bounds",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs"),
::tracing_core::__macro_support::Option::Some(310u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering::bounds"),
::tracing_core::field::FieldSet::new(&["param_ty",
"bound_vars", "predicate_filter",
"overlapping_assoc_constraints"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(¶m_ty)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&bound_vars)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&predicate_filter)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&overlapping_assoc_constraints)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
for hir_bound in hir_bounds {
if let PredicateFilter::SelfTraitThatDefines(assoc_ident) =
predicate_filter {
if let Some(trait_ref) = hir_bound.trait_ref() &&
let Some(trait_did) = trait_ref.trait_def_id() &&
self.tcx().trait_may_define_assoc_item(trait_did,
assoc_ident) {} else { continue; }
}
match hir_bound {
hir::GenericBound::Trait(poly_trait_ref) => {
let _ =
self.lower_poly_trait_ref(poly_trait_ref, param_ty, bounds,
predicate_filter, overlapping_assoc_constraints);
}
hir::GenericBound::Outlives(lifetime) => {
if #[allow(non_exhaustive_omitted_patterns)] match predicate_filter
{
PredicateFilter::ConstIfConst |
PredicateFilter::SelfConstIfConst => true,
_ => false,
} {
continue;
}
let region =
self.lower_lifetime(lifetime,
RegionInferReason::OutlivesBound);
let bound =
ty::Binder::bind_with_vars(ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(param_ty,
region)), bound_vars);
bounds.push((bound.upcast(self.tcx()),
lifetime.ident.span));
}
hir::GenericBound::Use(..) => {}
}
}
}
}
}#[instrument(level = "debug", skip(self, hir_bounds, bounds))]
311 pub(crate) fn lower_bounds<'hir, I: IntoIterator<Item = &'hir hir::GenericBound<'tcx>>>(
312 &self,
313 param_ty: Ty<'tcx>,
314 hir_bounds: I,
315 bounds: &mut Vec<(ty::Clause<'tcx>, Span)>,
316 bound_vars: &'tcx ty::List<ty::BoundVariableKind<'tcx>>,
317 predicate_filter: PredicateFilter,
318 overlapping_assoc_constraints: OverlappingAsssocItemConstraints,
319 ) where
320 'tcx: 'hir,
321 {
322 for hir_bound in hir_bounds {
323 if let PredicateFilter::SelfTraitThatDefines(assoc_ident) = predicate_filter {
326 if let Some(trait_ref) = hir_bound.trait_ref()
327 && let Some(trait_did) = trait_ref.trait_def_id()
328 && self.tcx().trait_may_define_assoc_item(trait_did, assoc_ident)
329 {
330 } else {
332 continue;
333 }
334 }
335
336 match hir_bound {
337 hir::GenericBound::Trait(poly_trait_ref) => {
338 let _ = self.lower_poly_trait_ref(
339 poly_trait_ref,
340 param_ty,
341 bounds,
342 predicate_filter,
343 overlapping_assoc_constraints,
344 );
345 }
346 hir::GenericBound::Outlives(lifetime) => {
347 if matches!(
349 predicate_filter,
350 PredicateFilter::ConstIfConst | PredicateFilter::SelfConstIfConst
351 ) {
352 continue;
353 }
354
355 let region = self.lower_lifetime(lifetime, RegionInferReason::OutlivesBound);
356 let bound = ty::Binder::bind_with_vars(
357 ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(param_ty, region)),
358 bound_vars,
359 );
360 bounds.push((bound.upcast(self.tcx()), lifetime.ident.span));
361 }
362 hir::GenericBound::Use(..) => {
363 }
365 }
366 }
367 }
368
369 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("lower_assoc_item_constraint",
"rustc_hir_analysis::hir_ty_lowering::bounds",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs"),
::tracing_core::__macro_support::Option::Some(377u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering::bounds"),
::tracing_core::field::FieldSet::new(&["hir_ref_id",
"trait_ref", "constraint", "predicate_filter"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&hir_ref_id)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_ref)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&constraint)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&predicate_filter)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Result<(), ErrorGuaranteed> =
loop {};
return __tracing_attr_fake_return;
}
{
let tcx = self.tcx();
let assoc_tag =
if constraint.gen_args.parenthesized ==
hir::GenericArgsParentheses::ReturnTypeNotation {
ty::AssocTag::Fn
} else if let hir::AssocItemConstraintKind::Equality {
term: hir::Term::Const(_) } = constraint.kind {
ty::AssocTag::Const
} else { ty::AssocTag::Type };
let candidate =
if self.probe_trait_that_defines_assoc_item(trait_ref.def_id(),
assoc_tag, constraint.ident) {
trait_ref
} else {
self.probe_single_bound_for_assoc_item(||
traits::supertraits(tcx, trait_ref),
AssocItemQSelf::Trait(trait_ref.def_id()), assoc_tag,
constraint.ident, path_span, Some(constraint))?
};
let assoc_item =
self.probe_assoc_item(constraint.ident, assoc_tag, hir_ref_id,
constraint.span,
candidate.def_id()).expect("failed to find associated item");
if let Some(duplicates) = duplicates {
duplicates.entry(assoc_item.def_id).and_modify(|prev_span|
{
self.dcx().emit_err(diagnostics::ValueOfAssociatedStructAlreadySpecified {
span: constraint.span,
prev_span: *prev_span,
item_name: constraint.ident,
def_path: tcx.def_path_str(assoc_item.container_id(tcx)),
});
}).or_insert(constraint.span);
}
let projection_term =
if let ty::AssocTag::Fn = assoc_tag {
let bound_vars = tcx.late_bound_vars(constraint.hir_id);
ty::Binder::bind_with_vars(self.lower_return_type_notation_ty(candidate,
assoc_item.def_id, path_span)?.into(), bound_vars)
} else {
candidate.map_bound(|trait_ref|
{
let item_segment =
hir::PathSegment {
ident: constraint.ident,
hir_id: constraint.hir_id,
res: Res::Err,
args: Some(constraint.gen_args),
infer_args: false,
};
let alias_args =
self.lower_generic_args_of_assoc_item(path_span,
assoc_item.def_id, &item_segment, trait_ref.args);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs:479",
"rustc_hir_analysis::hir_ty_lowering::bounds",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs"),
::tracing_core::__macro_support::Option::Some(479u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering::bounds"),
::tracing_core::field::FieldSet::new(&["alias_args"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&alias_args)
as &dyn Value))])
});
} else { ; }
};
ty::AliasTerm::new_from_def_id(tcx, assoc_item.def_id,
alias_args)
})
};
match constraint.kind {
hir::AssocItemConstraintKind::Equality { .. } if
let ty::AssocTag::Fn = assoc_tag => {
return Err(self.dcx().emit_err(crate::diagnostics::ReturnTypeNotationEqualityBound {
span: constraint.span,
}));
}
hir::AssocItemConstraintKind::Equality { term } => {
let term =
match term {
hir::Term::Ty(ty) => self.lower_ty(ty).into(),
hir::Term::Const(ct) => {
let ty =
projection_term.map_bound(|alias|
alias.expect_ct().type_of(tcx).skip_norm_wip());
let ty =
check_assoc_const_binding_type(self, constraint.ident, ty,
constraint.hir_id);
self.lower_const_arg(ct, ty).into()
}
};
let late_bound_in_projection_ty =
tcx.collect_constrained_late_bound_regions(projection_term);
let late_bound_in_term =
tcx.collect_referenced_late_bound_regions(trait_ref.rebind(term));
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs:521",
"rustc_hir_analysis::hir_ty_lowering::bounds",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs"),
::tracing_core::__macro_support::Option::Some(521u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering::bounds"),
::tracing_core::field::FieldSet::new(&["late_bound_in_projection_ty"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&late_bound_in_projection_ty)
as &dyn Value))])
});
} else { ; }
};
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs:522",
"rustc_hir_analysis::hir_ty_lowering::bounds",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs"),
::tracing_core::__macro_support::Option::Some(522u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering::bounds"),
::tracing_core::field::FieldSet::new(&["late_bound_in_term"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&late_bound_in_term)
as &dyn Value))])
});
} else { ; }
};
self.validate_late_bound_regions(late_bound_in_projection_ty,
late_bound_in_term,
|br_name|
{
{
self.dcx().struct_span_err(constraint.span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("binding for associated type `{0}` references {1}, which does not appear in the trait input types",
constraint.ident, br_name))
})).with_code(E0582)
}
});
match predicate_filter {
PredicateFilter::All | PredicateFilter::SelfOnly |
PredicateFilter::SelfAndAssociatedTypeBounds => {
let bound =
projection_term.map_bound(|projection_term|
{
ty::ClauseKind::Projection(ty::ProjectionPredicate {
projection_term,
term,
})
});
if let ty::AssocTag::Const = assoc_tag &&
!self.tcx().is_type_const(assoc_item.def_id) {
if tcx.features().min_generic_const_args() {
let mut err =
self.dcx().struct_span_err(constraint.span,
"use of trait associated const not defined as `type const`");
err.note("the declaration in the trait must begin with `type const` not just `const` alone");
return Err(err.emit());
} else {
let err =
self.dcx().span_delayed_bug(constraint.span,
"use of trait associated const defined as `type const`");
return Err(err);
}
} else {
bounds.push((bound.upcast(tcx), constraint.span));
}
}
PredicateFilter::SelfTraitThatDefines(_) => {}
PredicateFilter::ConstIfConst |
PredicateFilter::SelfConstIfConst => {}
}
}
hir::AssocItemConstraintKind::Bound { bounds: hir_bounds } =>
{
match predicate_filter {
PredicateFilter::All |
PredicateFilter::SelfAndAssociatedTypeBounds |
PredicateFilter::ConstIfConst => {
let projection_ty =
projection_term.map_bound(|projection_term|
projection_term.expect_ty());
let param_ty =
Ty::new_alias(tcx, projection_ty.skip_binder());
self.lower_bounds(param_ty, hir_bounds, bounds,
projection_ty.bound_vars(), predicate_filter,
OverlappingAsssocItemConstraints::Allowed);
}
PredicateFilter::SelfOnly |
PredicateFilter::SelfTraitThatDefines(_) |
PredicateFilter::SelfConstIfConst => {}
}
}
}
Ok(())
}
}
}#[instrument(level = "debug", skip(self, bounds, duplicates, path_span))]
378 pub(super) fn lower_assoc_item_constraint(
379 &self,
380 hir_ref_id: hir::HirId,
381 trait_ref: ty::PolyTraitRef<'tcx>,
382 constraint: &hir::AssocItemConstraint<'tcx>,
383 bounds: &mut Vec<(ty::Clause<'tcx>, Span)>,
384 duplicates: Option<&mut FxIndexMap<DefId, Span>>,
385 path_span: Span,
386 predicate_filter: PredicateFilter,
387 ) -> Result<(), ErrorGuaranteed> {
388 let tcx = self.tcx();
389
390 let assoc_tag = if constraint.gen_args.parenthesized
391 == hir::GenericArgsParentheses::ReturnTypeNotation
392 {
393 ty::AssocTag::Fn
394 } else if let hir::AssocItemConstraintKind::Equality { term: hir::Term::Const(_) } =
395 constraint.kind
396 {
397 ty::AssocTag::Const
398 } else {
399 ty::AssocTag::Type
400 };
401
402 let candidate = if self.probe_trait_that_defines_assoc_item(
411 trait_ref.def_id(),
412 assoc_tag,
413 constraint.ident,
414 ) {
415 trait_ref
417 } else {
418 self.probe_single_bound_for_assoc_item(
421 || traits::supertraits(tcx, trait_ref),
422 AssocItemQSelf::Trait(trait_ref.def_id()),
423 assoc_tag,
424 constraint.ident,
425 path_span,
426 Some(constraint),
427 )?
428 };
429
430 let assoc_item = self
431 .probe_assoc_item(
432 constraint.ident,
433 assoc_tag,
434 hir_ref_id,
435 constraint.span,
436 candidate.def_id(),
437 )
438 .expect("failed to find associated item");
439
440 if let Some(duplicates) = duplicates {
441 duplicates
442 .entry(assoc_item.def_id)
443 .and_modify(|prev_span| {
444 self.dcx().emit_err(diagnostics::ValueOfAssociatedStructAlreadySpecified {
445 span: constraint.span,
446 prev_span: *prev_span,
447 item_name: constraint.ident,
448 def_path: tcx.def_path_str(assoc_item.container_id(tcx)),
449 });
450 })
451 .or_insert(constraint.span);
452 }
453
454 let projection_term = if let ty::AssocTag::Fn = assoc_tag {
455 let bound_vars = tcx.late_bound_vars(constraint.hir_id);
456 ty::Binder::bind_with_vars(
457 self.lower_return_type_notation_ty(candidate, assoc_item.def_id, path_span)?.into(),
458 bound_vars,
459 )
460 } else {
461 candidate.map_bound(|trait_ref| {
465 let item_segment = hir::PathSegment {
466 ident: constraint.ident,
467 hir_id: constraint.hir_id,
468 res: Res::Err,
469 args: Some(constraint.gen_args),
470 infer_args: false,
471 };
472
473 let alias_args = self.lower_generic_args_of_assoc_item(
474 path_span,
475 assoc_item.def_id,
476 &item_segment,
477 trait_ref.args,
478 );
479 debug!(?alias_args);
480
481 ty::AliasTerm::new_from_def_id(tcx, assoc_item.def_id, alias_args)
482 })
483 };
484
485 match constraint.kind {
486 hir::AssocItemConstraintKind::Equality { .. } if let ty::AssocTag::Fn = assoc_tag => {
487 return Err(self.dcx().emit_err(
488 crate::diagnostics::ReturnTypeNotationEqualityBound { span: constraint.span },
489 ));
490 }
491 hir::AssocItemConstraintKind::Equality { term } => {
494 let term = match term {
495 hir::Term::Ty(ty) => self.lower_ty(ty).into(),
496 hir::Term::Const(ct) => {
497 let ty = projection_term
498 .map_bound(|alias| alias.expect_ct().type_of(tcx).skip_norm_wip());
499 let ty = check_assoc_const_binding_type(
500 self,
501 constraint.ident,
502 ty,
503 constraint.hir_id,
504 );
505
506 self.lower_const_arg(ct, ty).into()
507 }
508 };
509
510 let late_bound_in_projection_ty =
518 tcx.collect_constrained_late_bound_regions(projection_term);
519 let late_bound_in_term =
520 tcx.collect_referenced_late_bound_regions(trait_ref.rebind(term));
521 debug!(?late_bound_in_projection_ty);
522 debug!(?late_bound_in_term);
523
524 self.validate_late_bound_regions(
529 late_bound_in_projection_ty,
530 late_bound_in_term,
531 |br_name| {
532 struct_span_code_err!(
533 self.dcx(),
534 constraint.span,
535 E0582,
536 "binding for associated type `{}` references {}, \
537 which does not appear in the trait input types",
538 constraint.ident,
539 br_name
540 )
541 },
542 );
543
544 match predicate_filter {
545 PredicateFilter::All
546 | PredicateFilter::SelfOnly
547 | PredicateFilter::SelfAndAssociatedTypeBounds => {
548 let bound = projection_term.map_bound(|projection_term| {
549 ty::ClauseKind::Projection(ty::ProjectionPredicate {
550 projection_term,
551 term,
552 })
553 });
554
555 if let ty::AssocTag::Const = assoc_tag
556 && !self.tcx().is_type_const(assoc_item.def_id)
557 {
558 if tcx.features().min_generic_const_args() {
559 let mut err = self.dcx().struct_span_err(
560 constraint.span,
561 "use of trait associated const not defined as `type const`",
562 );
563 err.note("the declaration in the trait must begin with `type const` not just `const` alone");
564 return Err(err.emit());
565 } else {
566 let err = self.dcx().span_delayed_bug(
567 constraint.span,
568 "use of trait associated const defined as `type const`",
569 );
570 return Err(err);
571 }
572 } else {
573 bounds.push((bound.upcast(tcx), constraint.span));
574 }
575 }
576 PredicateFilter::SelfTraitThatDefines(_) => {}
578 PredicateFilter::ConstIfConst | PredicateFilter::SelfConstIfConst => {}
580 }
581 }
582 hir::AssocItemConstraintKind::Bound { bounds: hir_bounds } => {
585 match predicate_filter {
586 PredicateFilter::All
587 | PredicateFilter::SelfAndAssociatedTypeBounds
588 | PredicateFilter::ConstIfConst => {
589 let projection_ty = projection_term
590 .map_bound(|projection_term| projection_term.expect_ty());
591 let param_ty = Ty::new_alias(tcx, projection_ty.skip_binder());
594 self.lower_bounds(
595 param_ty,
596 hir_bounds,
597 bounds,
598 projection_ty.bound_vars(),
599 predicate_filter,
600 OverlappingAsssocItemConstraints::Allowed,
601 );
602 }
603 PredicateFilter::SelfOnly
604 | PredicateFilter::SelfTraitThatDefines(_)
605 | PredicateFilter::SelfConstIfConst => {}
606 }
607 }
608 }
609 Ok(())
610 }
611
612 pub fn lower_ty_maybe_return_type_notation(&self, hir_ty: &hir::Ty<'tcx>) -> Ty<'tcx> {
615 let hir::TyKind::Path(qpath) = hir_ty.kind else {
616 return self.lower_ty(hir_ty);
617 };
618
619 let tcx = self.tcx();
620 match qpath {
621 hir::QPath::Resolved(opt_self_ty, path)
622 if let [mod_segments @ .., trait_segment, item_segment] = &path.segments[..]
623 && item_segment.args.is_some_and(|args| {
624 #[allow(non_exhaustive_omitted_patterns)] match args.parenthesized {
hir::GenericArgsParentheses::ReturnTypeNotation => true,
_ => false,
}matches!(
625 args.parenthesized,
626 hir::GenericArgsParentheses::ReturnTypeNotation
627 )
628 }) =>
629 {
630 let _ =
632 self.prohibit_generic_args(mod_segments.iter(), GenericsArgsErrExtend::None);
633
634 let item_def_id = match path.res {
635 Res::Def(DefKind::AssocFn, item_def_id) => item_def_id,
636 Res::Err => {
637 return Ty::new_error_with_message(
638 tcx,
639 hir_ty.span,
640 "failed to resolve RTN",
641 );
642 }
643 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("only expected method resolution for fully qualified RTN"))bug!("only expected method resolution for fully qualified RTN"),
644 };
645 let trait_def_id = tcx.parent(item_def_id);
646
647 let Some(self_ty) = opt_self_ty else {
649 let guar = self.report_missing_self_ty_for_resolved_path(
650 trait_def_id,
651 hir_ty.span,
652 item_segment,
653 ty::AssocTag::Type,
654 );
655 return Ty::new_error(tcx, guar);
656 };
657 let self_ty = self.lower_ty(self_ty);
658
659 let trait_ref = self.lower_mono_trait_ref(
660 hir_ty.span,
661 trait_def_id,
662 self_ty,
663 trait_segment,
664 false,
665 );
666
667 let candidate =
680 ty::Binder::bind_with_vars(trait_ref, tcx.late_bound_vars(item_segment.hir_id));
681
682 match self.lower_return_type_notation_ty(candidate, item_def_id, hir_ty.span) {
683 Ok(ty) => Ty::new_alias(tcx, ty),
684 Err(guar) => Ty::new_error(tcx, guar),
685 }
686 }
687 hir::QPath::TypeRelative(hir_self_ty, segment)
688 if segment.args.is_some_and(|args| {
689 #[allow(non_exhaustive_omitted_patterns)] match args.parenthesized {
hir::GenericArgsParentheses::ReturnTypeNotation => true,
_ => false,
}matches!(args.parenthesized, hir::GenericArgsParentheses::ReturnTypeNotation)
690 }) =>
691 {
692 let self_ty = self.lower_ty(hir_self_ty);
693 let (item_def_id, bound) = match self.resolve_type_relative_path(
694 self_ty,
695 hir_self_ty,
696 ty::AssocTag::Fn,
697 segment,
698 hir_ty.hir_id,
699 hir_ty.span,
700 None,
701 ) {
702 Ok(result) => result,
703 Err(guar) => return Ty::new_error(tcx, guar),
704 };
705
706 if bound.has_bound_vars() {
713 return Ty::new_error(
714 tcx,
715 self.dcx().emit_err(
716 diagnostics::AssociatedItemTraitUninferredGenericParams {
717 span: hir_ty.span,
718 inferred_sugg: Some(hir_ty.span.with_hi(segment.ident.span.lo())),
719 bound: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}::",
tcx.anonymize_bound_vars(bound).skip_binder()))
})format!(
720 "{}::",
721 tcx.anonymize_bound_vars(bound).skip_binder()
722 ),
723 mpart_sugg: None,
724 what: tcx.def_descr(item_def_id),
725 },
726 ),
727 );
728 }
729
730 match self.lower_return_type_notation_ty(bound, item_def_id, hir_ty.span) {
731 Ok(ty) => Ty::new_alias(tcx, ty),
732 Err(guar) => Ty::new_error(tcx, guar),
733 }
734 }
735 _ => self.lower_ty(hir_ty),
736 }
737 }
738
739 fn lower_return_type_notation_ty(
744 &self,
745 candidate: ty::PolyTraitRef<'tcx>,
746 item_def_id: DefId,
747 path_span: Span,
748 ) -> Result<ty::AliasTy<'tcx>, ErrorGuaranteed> {
749 let tcx = self.tcx();
750 let mut emitted_bad_param_err = None;
751 let mut num_bound_vars = candidate.bound_vars().len();
754 let args = candidate.skip_binder().args.extend_to(tcx, item_def_id, |param, _| {
755 let arg = match param.kind {
756 ty::GenericParamDefKind::Lifetime => ty::Region::new_bound(
757 tcx,
758 ty::INNERMOST,
759 ty::BoundRegion {
760 var: ty::BoundVar::from_usize(num_bound_vars),
761 kind: ty::BoundRegionKind::Named(param.def_id),
762 },
763 )
764 .into(),
765 ty::GenericParamDefKind::Type { .. } => {
766 let guar = *emitted_bad_param_err.get_or_insert_with(|| {
767 self.dcx().emit_err(
768 crate::diagnostics::ReturnTypeNotationIllegalParam::Type {
769 span: path_span,
770 param_span: tcx.def_span(param.def_id),
771 },
772 )
773 });
774 Ty::new_error(tcx, guar).into()
775 }
776 ty::GenericParamDefKind::Const { .. } => {
777 let guar = *emitted_bad_param_err.get_or_insert_with(|| {
778 self.dcx().emit_err(
779 crate::diagnostics::ReturnTypeNotationIllegalParam::Const {
780 span: path_span,
781 param_span: tcx.def_span(param.def_id),
782 },
783 )
784 });
785 ty::Const::new_error(tcx, guar).into()
786 }
787 };
788 num_bound_vars += 1;
789 arg
790 });
791
792 let output = tcx.fn_sig(item_def_id).skip_binder().output();
795 let output = if let ty::Alias(alias_ty) = *output.skip_binder().kind()
796 && let ty::AliasTy { kind: ty::Projection { def_id: projection_def_id }, .. } = alias_ty
797 && tcx.is_impl_trait_in_trait(projection_def_id)
798 {
799 alias_ty
800 } else {
801 return Err(self.dcx().emit_err(crate::diagnostics::ReturnTypeNotationOnNonRpitit {
802 span: path_span,
803 ty: tcx.liberate_late_bound_regions(item_def_id, output),
804 fn_span: tcx.hir_span_if_local(item_def_id),
805 note: (),
806 }));
807 };
808
809 let shifted_output = tcx.shift_bound_var_indices(num_bound_vars, output);
814 Ok(ty::EarlyBinder::bind(shifted_output).instantiate(tcx, args).skip_norm_wip())
815 }
816}
817
818pub(crate) fn check_assoc_const_binding_type<'tcx>(
830 cx: &dyn HirTyLowerer<'tcx>,
831 assoc_const: Ident,
832 ty: ty::Binder<'tcx, Ty<'tcx>>,
833 hir_id: hir::HirId,
834) -> Ty<'tcx> {
835 let ty = ty.skip_binder();
842 if !ty.has_param() && !ty.has_escaping_bound_vars() {
843 return ty;
844 }
845
846 let mut collector = GenericParamAndBoundVarCollector {
847 cx,
848 params: Default::default(),
849 vars: Default::default(),
850 depth: ty::INNERMOST,
851 };
852 let mut guar = ty.visit_with(&mut collector).break_value();
853
854 let tcx = cx.tcx();
855 let ty_note = ty
856 .make_suggestable(tcx, false, None)
857 .map(|ty| crate::diagnostics::TyOfAssocConstBindingNote { assoc_const, ty });
858
859 let enclosing_item_owner_id = tcx
860 .hir_parent_owner_iter(hir_id)
861 .find_map(|(owner_id, parent)| parent.generics().map(|_| owner_id))
862 .unwrap();
863 let generics = tcx.generics_of(enclosing_item_owner_id);
864 for index in collector.params {
865 let param = generics.param_at(index as _, tcx);
866 let is_self_param = param.name == kw::SelfUpper;
867 guar.get_or_insert(cx.dcx().emit_err(crate::diagnostics::ParamInTyOfAssocConstBinding {
868 span: assoc_const.span,
869 assoc_const,
870 param_name: param.name,
871 param_def_kind: tcx.def_descr(param.def_id),
872 param_category: if is_self_param {
873 "self"
874 } else if param.kind.is_synthetic() {
875 "synthetic"
876 } else {
877 "normal"
878 },
879 param_defined_here_label:
880 (!is_self_param).then(|| tcx.def_ident_span(param.def_id).unwrap()),
881 ty_note,
882 }));
883 }
884 for var_def_id in collector.vars {
885 guar.get_or_insert(cx.dcx().emit_err(
886 crate::diagnostics::EscapingBoundVarInTyOfAssocConstBinding {
887 span: assoc_const.span,
888 assoc_const,
889 var_name: cx.tcx().item_name(var_def_id),
890 var_def_kind: tcx.def_descr(var_def_id),
891 var_defined_here_label: tcx.def_ident_span(var_def_id).unwrap(),
892 ty_note,
893 },
894 ));
895 }
896
897 let guar = guar.unwrap_or_else(|| ::rustc_middle::util::bug::bug_fmt(format_args!("failed to find gen params or bound vars in ty"))bug!("failed to find gen params or bound vars in ty"));
898 Ty::new_error(tcx, guar)
899}
900
901struct GenericParamAndBoundVarCollector<'a, 'tcx> {
902 cx: &'a dyn HirTyLowerer<'tcx>,
903 params: FxIndexSet<u32>,
904 vars: FxIndexSet<DefId>,
905 depth: ty::DebruijnIndex,
906}
907
908impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for GenericParamAndBoundVarCollector<'_, 'tcx> {
909 type Result = ControlFlow<ErrorGuaranteed>;
910
911 fn visit_binder<T: TypeVisitable<TyCtxt<'tcx>>>(
912 &mut self,
913 binder: &ty::Binder<'tcx, T>,
914 ) -> Self::Result {
915 self.depth.shift_in(1);
916 let result = binder.super_visit_with(self);
917 self.depth.shift_out(1);
918 result
919 }
920
921 fn visit_ty(&mut self, ty: Ty<'tcx>) -> Self::Result {
922 match ty.kind() {
923 ty::Param(param) => {
924 self.params.insert(param.index);
925 }
926 ty::Bound(ty::BoundVarIndexKind::Bound(db), bt) if *db >= self.depth => {
927 self.vars.insert(match bt.kind {
928 ty::BoundTyKind::Param(def_id) => def_id,
929 ty::BoundTyKind::Anon => {
930 let reported = self
931 .cx
932 .dcx()
933 .delayed_bug(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("unexpected anon bound ty: {0:?}",
bt.var))
})format!("unexpected anon bound ty: {:?}", bt.var));
934 return ControlFlow::Break(reported);
935 }
936 });
937 }
938 _ if ty.has_param() || ty.has_bound_vars() => return ty.super_visit_with(self),
939 _ => {}
940 }
941 ControlFlow::Continue(())
942 }
943
944 fn visit_region(&mut self, re: ty::Region<'tcx>) -> Self::Result {
945 match re.kind() {
946 ty::ReEarlyParam(param) => {
947 self.params.insert(param.index);
948 }
949 ty::ReBound(ty::BoundVarIndexKind::Bound(db), br) if db >= self.depth => {
950 self.vars.insert(match br.kind {
951 ty::BoundRegionKind::Named(def_id) => def_id,
952 ty::BoundRegionKind::Anon | ty::BoundRegionKind::ClosureEnv => {
953 let guar = self
954 .cx
955 .dcx()
956 .delayed_bug(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("unexpected bound region kind: {0:?}",
br.kind))
})format!("unexpected bound region kind: {:?}", br.kind));
957 return ControlFlow::Break(guar);
958 }
959 ty::BoundRegionKind::NamedForPrinting(_) => {
960 ::rustc_middle::util::bug::bug_fmt(format_args!("only used for pretty printing"))bug!("only used for pretty printing")
961 }
962 });
963 }
964 _ => {}
965 }
966 ControlFlow::Continue(())
967 }
968
969 fn visit_const(&mut self, ct: ty::Const<'tcx>) -> Self::Result {
970 match ct.kind() {
971 ty::ConstKind::Param(param) => {
972 self.params.insert(param.index);
973 }
974 ty::ConstKind::Bound(ty::BoundVarIndexKind::Bound(db), _) if db >= self.depth => {
975 let guar = self.cx.dcx().delayed_bug("unexpected escaping late-bound const var");
976 return ControlFlow::Break(guar);
977 }
978 _ if ct.has_param() || ct.has_bound_vars() => return ct.super_visit_with(self),
979 _ => {}
980 }
981 ControlFlow::Continue(())
982 }
983}