1use std::cell::Cell;
18use std::{assert_matches, debug_assert_matches, iter};
19
20use rustc_abi::{ExternAbi, Size};
21use rustc_ast::Recovered;
22use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
23use rustc_data_structures::thin_vec::{ThinVec, thin_vec};
24use rustc_errors::{
25 Applicability, Diag, DiagCtxtHandle, Diagnostic, E0228, ErrorGuaranteed, Level, StashKey,
26};
27use rustc_hir::def::DefKind;
28use rustc_hir::def_id::{DefId, LocalDefId};
29use rustc_hir::intravisit::{InferKind, Visitor};
30use rustc_hir::{self as hir, GenericParamKind, HirId, Node, PreciseCapturingArgKind, find_attr};
31use rustc_infer::infer::{InferCtxt, SolverRegionConstraint, TyCtxtInferExt};
32use rustc_infer::traits::{DynCompatibilityViolation, ObligationCause};
33use rustc_lint_defs::builtin::REPR_C_ENUMS_LARGER_THAN_INT;
34use rustc_middle::query::Providers;
35use rustc_middle::ty::util::{Discr, IntTypeExt};
36use rustc_middle::ty::{
37 self, AdtKind, Const, IsSuggestable, Ty, TyCtxt, TypeVisitableExt, TypingMode, Unnormalized,
38 fold_regions,
39};
40use rustc_middle::{bug, span_bug};
41use rustc_span::{DUMMY_SP, Ident, Span, Symbol, kw, sym};
42use rustc_trait_selection::error_reporting::traits::suggestions::NextTypeParamName;
43use rustc_trait_selection::infer::InferCtxtExt;
44use rustc_trait_selection::traits::{
45 FulfillmentError, ObligationCtxt, hir_ty_lowering_dyn_compatibility_violations,
46};
47use tracing::{debug, instrument};
48use ty::region_constraint::LeafRegionConstraint;
49
50use crate::check::wfcheck::{TestBinderBody, TestBinderExists, TestBinderForall};
51use crate::diagnostics::{self, ElidedLifetimesAreNotAllowedInDelegations};
52use crate::hir_ty_lowering::{HirTyLowerer, InherentAssocCandidate, RegionInferReason};
53
54mod clauses_of;
55pub(crate) mod dump;
56mod generics_of;
57mod item_bounds;
58mod resolve_bound_vars;
59mod type_of;
60
61pub(crate) fn provide(providers: &mut Providers) {
65 resolve_bound_vars::provide(providers);
66 *providers = Providers {
67 type_of: type_of::type_of,
68 type_of_opaque: type_of::type_of_opaque,
69 type_of_opaque_hir_typeck: type_of::type_of_opaque_hir_typeck,
70 type_alias_is_checked: type_of::type_alias_is_checked,
71 item_bounds: item_bounds::item_bounds,
72 explicit_item_bounds: item_bounds::explicit_item_bounds,
73 item_self_bounds: item_bounds::item_self_bounds,
74 explicit_item_self_bounds: item_bounds::explicit_item_self_bounds,
75 item_non_self_bounds: item_bounds::item_non_self_bounds,
76 impl_super_outlives: item_bounds::impl_super_outlives,
77 generics_of: generics_of::generics_of,
78 clauses_of: clauses_of::clauses_of,
79 explicit_clauses_of: clauses_of::explicit_clauses_of,
80 explicit_super_clauses_of: clauses_of::explicit_super_clauses_of,
81 explicit_implied_clauses_of: clauses_of::explicit_implied_clauses_of,
82 explicit_supertraits_containing_assoc_item:
83 clauses_of::explicit_supertraits_containing_assoc_item,
84 trait_explicit_clauses_and_bounds: clauses_of::trait_explicit_clauses_and_bounds,
85 const_conditions: clauses_of::const_conditions,
86 explicit_implied_const_bounds: clauses_of::explicit_implied_const_bounds,
87 type_param_clauses: clauses_of::type_param_clauses,
88 trait_def,
89 adt_def,
90 fn_sig,
91 impl_trait_header,
92 impl_is_fully_generic_for_reflection,
93 coroutine_kind,
94 coroutine_for_closure,
95 opaque_ty_origin,
96 rendered_precise_capturing_args,
97 const_param_default,
98 anon_const_kind,
99 const_of_item,
100 ..*providers
101 };
102}
103
104pub(crate) struct ItemCtxt<'tcx> {
134 tcx: TyCtxt<'tcx>,
135 item_def_id: LocalDefId,
136 tainted_by_errors: Cell<Option<ErrorGuaranteed>>,
137 lowering_delegation_segment: bool,
138}
139
140#[derive(#[automatically_derived]
impl ::core::default::Default for HirPlaceholderCollector {
#[inline]
fn default() -> HirPlaceholderCollector {
HirPlaceholderCollector {
spans: ::core::default::Default::default(),
may_contain_const_infer: ::core::default::Default::default(),
}
}
}Default)]
143pub(crate) struct HirPlaceholderCollector {
144 pub spans: Vec<Span>,
145 pub may_contain_const_infer: bool,
148}
149
150impl<'v> Visitor<'v> for HirPlaceholderCollector {
151 fn visit_infer(&mut self, _inf_id: HirId, inf_span: Span, kind: InferKind<'v>) -> Self::Result {
152 self.spans.push(inf_span);
153
154 if let InferKind::Const(_) | InferKind::Ambig(_) = kind {
155 self.may_contain_const_infer = true;
156 }
157 }
158}
159
160fn placeholder_type_error_diag<'cx, 'tcx>(
161 cx: &'cx dyn HirTyLowerer<'tcx>,
162 generics: Option<&hir::Generics<'_>>,
163 placeholder_types: Vec<Span>,
164 additional_spans: Vec<Span>,
165 suggest: bool,
166 hir_ty: Option<&hir::Ty<'_>>,
167 kind: &'static str,
168) -> Diag<'cx> {
169 if placeholder_types.is_empty() {
170 return bad_placeholder(cx, additional_spans, kind);
171 }
172
173 let params = generics.map(|g| g.params).unwrap_or_default();
174 let type_name = params.next_type_param_name(None);
175 let mut sugg: Vec<_> =
176 placeholder_types.iter().map(|sp| (*sp, (*type_name).to_string())).collect();
177
178 if let Some(generics) = generics {
179 if let Some(span) = params.iter().find_map(|arg| match arg.name {
180 hir::ParamName::Plain(Ident { name: kw::Underscore, span }) => Some(span),
181 _ => None,
182 }) {
183 sugg.push((span, (*type_name).to_string()));
186 } else if let Some(span) = generics.span_for_param_suggestion() {
187 sugg.push((span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(", {0}", type_name))
})format!(", {type_name}")));
189 } else {
190 sugg.push((generics.span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<{0}>", type_name))
})format!("<{type_name}>")));
191 }
192 }
193
194 let mut err =
195 bad_placeholder(cx, placeholder_types.into_iter().chain(additional_spans).collect(), kind);
196
197 if suggest {
199 let mut is_fn = false;
200 let mut is_const_or_static = false;
201
202 if let Some(hir_ty) = hir_ty
203 && let hir::TyKind::FnPtr(_) = hir_ty.kind
204 {
205 is_fn = true;
206
207 is_const_or_static = #[allow(non_exhaustive_omitted_patterns)] match cx.tcx().parent_hir_node(hir_ty.hir_id)
{
Node::Item(&hir::Item {
kind: hir::ItemKind::Const(..) | hir::ItemKind::Static(..), .. }) |
Node::TraitItem(&hir::TraitItem { kind: hir::TraitItemKind::Const(..),
.. }) |
Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Const(..), ..
}) => true,
_ => false,
}matches!(
209 cx.tcx().parent_hir_node(hir_ty.hir_id),
210 Node::Item(&hir::Item {
211 kind: hir::ItemKind::Const(..) | hir::ItemKind::Static(..),
212 ..
213 }) | Node::TraitItem(&hir::TraitItem { kind: hir::TraitItemKind::Const(..), .. })
214 | Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Const(..), .. })
215 );
216 }
217
218 if !(is_fn && is_const_or_static) {
221 err.multipart_suggestion(
222 "use type parameters instead",
223 sugg,
224 Applicability::HasPlaceholders,
225 );
226 }
227 }
228
229 err
230}
231
232fn bad_placeholder<'cx, 'tcx>(
236 cx: &'cx dyn HirTyLowerer<'tcx>,
237 mut spans: Vec<Span>,
238 kind: &'static str,
239) -> Diag<'cx> {
240 let kind = if kind.ends_with('s') { ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}es", kind))
})format!("{kind}es") } else { ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}s", kind))
})format!("{kind}s") };
241
242 spans.sort();
243 cx.dcx().create_err(diagnostics::PlaceholderNotAllowedItemSignatures { spans, kind })
244}
245
246impl<'tcx> ItemCtxt<'tcx> {
247 pub(crate) fn new(tcx: TyCtxt<'tcx>, item_def_id: LocalDefId) -> ItemCtxt<'tcx> {
248 ItemCtxt::new_internal(tcx, item_def_id, false)
249 }
250
251 fn new_internal(
252 tcx: TyCtxt<'tcx>,
253 item_def_id: LocalDefId,
254 delegation: bool,
255 ) -> ItemCtxt<'tcx> {
256 ItemCtxt {
257 tcx,
258 item_def_id,
259 tainted_by_errors: Cell::new(None),
260 lowering_delegation_segment: delegation,
261 }
262 }
263
264 pub(crate) fn new_for_delegation(tcx: TyCtxt<'tcx>, item_def_id: LocalDefId) -> ItemCtxt<'tcx> {
265 ItemCtxt::new_internal(tcx, item_def_id, true)
266 }
267
268 pub(crate) fn lower_ty(&self, hir_ty: &hir::Ty<'_>) -> Ty<'tcx> {
269 self.lowerer().lower_ty(hir_ty)
270 }
271
272 pub(crate) fn hir_id(&self) -> hir::HirId {
273 self.tcx.local_def_id_to_hir_id(self.item_def_id)
274 }
275
276 pub(crate) fn node(&self) -> hir::Node<'tcx> {
277 self.tcx.hir_node(self.hir_id())
278 }
279
280 fn check_tainted_by_errors(&self) -> Result<(), ErrorGuaranteed> {
281 match self.tainted_by_errors.get() {
282 Some(err) => Err(err),
283 None => Ok(()),
284 }
285 }
286
287 fn report_placeholder_type_error(
288 &self,
289 placeholder_types: Vec<Span>,
290 infer_replacements: Vec<(Span, String)>,
291 ) -> ErrorGuaranteed {
292 let node = self.tcx.hir_node_by_def_id(self.item_def_id);
293 let generics = node.generics();
294 let kind_id = match node {
295 Node::GenericParam(_) | Node::WherePredicate(_) | Node::Field(_) => {
296 self.tcx.local_parent(self.item_def_id)
297 }
298 _ => self.item_def_id,
299 };
300 let kind = self.tcx.def_descr(kind_id.into());
301 let mut diag = placeholder_type_error_diag(
302 self,
303 generics,
304 placeholder_types,
305 infer_replacements.iter().map(|&(span, _)| span).collect(),
306 false,
307 None,
308 kind,
309 );
310 if !infer_replacements.is_empty() {
311 diag.multipart_suggestion(
312 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("try replacing `_` with the type{0} in the corresponding trait method signature",
if infer_replacements.len() == 1 { "" } else { "s" }))
})format!(
313 "try replacing `_` with the type{} in the corresponding trait method \
314 signature",
315 rustc_errors::pluralize!(infer_replacements.len()),
316 ),
317 infer_replacements,
318 Applicability::MachineApplicable,
319 );
320 }
321
322 diag.emit()
323 }
324
325 {}
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_test_binder_body",
"rustc_hir_analysis::collect", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect.rs"),
::tracing_core::__macro_support::Option::Some(325u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("item")
}> =
::tracing::__macro_support::FieldName::new("item");
NAME.as_str()
}], ::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
(move ||
{
#[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: TestBinderBody<'tcx> =
loop {};
return __tracing_attr_fake_return;
}
{
let hir::TestBinderBody {
foralls, exists, constraints, predicates } = item;
let foralls =
foralls.iter().map(|forall|
self.lower_test_binder_forall(forall)).collect();
let exists =
exists.iter().map(|exists|
self.lower_test_binder_exists(exists)).collect();
let constraints =
self.lower_test_binder_constraint(&constraints);
let mut clauses = Default::default();
for predicate in *predicates {
clauses_of::where_predicate_clauses(self, predicate,
&mut clauses);
}
let predicates =
clauses.into_iter().map(|(c, span)|
(c.kind(), span)).collect();
TestBinderBody { foralls, exists, constraints, predicates }
}
})();
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect.rs:325",
"rustc_hir_analysis::collect", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect.rs"),
::tracing_core::__macro_support::Option::Some(325u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("return")
}> =
::tracing::__macro_support::FieldName::new("return");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
x;#[instrument(level = "debug", skip(self), ret)]
326 pub(super) fn lower_test_binder_body(
327 &self,
328 item: &hir::TestBinderBody<'tcx>,
329 ) -> TestBinderBody<'tcx> {
330 let hir::TestBinderBody { foralls, exists, constraints, predicates } = item;
331 let foralls = foralls.iter().map(|forall| self.lower_test_binder_forall(forall)).collect();
332 let exists = exists.iter().map(|exists| self.lower_test_binder_exists(exists)).collect();
333 let constraints = self.lower_test_binder_constraint(&constraints);
334 let mut clauses = Default::default();
335 for predicate in *predicates {
336 clauses_of::where_predicate_clauses(self, predicate, &mut clauses);
337 }
338 let predicates = clauses.into_iter().map(|(c, span)| (c.kind(), span)).collect();
339 TestBinderBody { foralls, exists, constraints, predicates }
340 }
341
342 {}
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_test_binder_forall",
"rustc_hir_analysis::collect", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect.rs"),
::tracing_core::__macro_support::Option::Some(342u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("forall")
}> =
::tracing::__macro_support::FieldName::new("forall");
NAME.as_str()
}], ::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&forall)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
(move ||
{
#[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: TestBinderForall<'tcx> =
loop {};
return __tracing_attr_fake_return;
}
{
let bound_vars = self.tcx.late_bound_vars(forall.hir_id);
let value = self.lower_test_binder_body(forall.body);
let mut type_outlives = ::alloc::vec::Vec::new();
let mut region_outlives = ::alloc::vec::Vec::new();
for predicate in forall.generics.predicates {
self.lower_test_binder_assumptions(predicate,
&mut type_outlives, &mut region_outlives);
}
let body =
crate::check::wfcheck::WithWhereClauses {
value,
type_outlives,
region_outlives,
};
let binder = ty::Binder::bind_with_vars(body, bound_vars);
let assert_on_exit =
forall.assert_on_exit.map(|assert_on_exit|
self.lower_test_binder_constraint(assert_on_exit));
TestBinderForall {
span: forall.span,
binder,
assert_on_exit,
}
}
})();
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect.rs:342",
"rustc_hir_analysis::collect", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect.rs"),
::tracing_core::__macro_support::Option::Some(342u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("return")
}> =
::tracing::__macro_support::FieldName::new("return");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
x;#[instrument(level = "debug", skip(self), ret)]
343 pub(super) fn lower_test_binder_forall(
344 &self,
345 forall: &hir::TestBinderForall<'tcx>,
346 ) -> TestBinderForall<'tcx> {
347 let bound_vars = self.tcx.late_bound_vars(forall.hir_id);
348 let value = self.lower_test_binder_body(forall.body);
349 let mut type_outlives = vec![];
350 let mut region_outlives = vec![];
351 for predicate in forall.generics.predicates {
352 self.lower_test_binder_assumptions(predicate, &mut type_outlives, &mut region_outlives);
353 }
354 let body =
355 crate::check::wfcheck::WithWhereClauses { value, type_outlives, region_outlives };
356 let binder = ty::Binder::bind_with_vars(body, bound_vars);
357 let assert_on_exit = forall
358 .assert_on_exit
359 .map(|assert_on_exit| self.lower_test_binder_constraint(assert_on_exit));
360 TestBinderForall { span: forall.span, binder, assert_on_exit }
361 }
362
363 {}
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_test_binder_exists",
"rustc_hir_analysis::collect", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect.rs"),
::tracing_core::__macro_support::Option::Some(363u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("exists")
}> =
::tracing::__macro_support::FieldName::new("exists");
NAME.as_str()
}], ::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&exists)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
(move ||
{
#[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: TestBinderExists<'tcx> =
loop {};
return __tracing_attr_fake_return;
}
{
let bound_vars = self.tcx.late_bound_vars(exists.hir_id);
let body = self.lower_test_binder_body(exists.body);
let binder = ty::Binder::bind_with_vars(body, bound_vars);
TestBinderExists { span: exists.span, binder }
}
})();
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect.rs:363",
"rustc_hir_analysis::collect", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect.rs"),
::tracing_core::__macro_support::Option::Some(363u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("return")
}> =
::tracing::__macro_support::FieldName::new("return");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
x;#[instrument(level = "debug", skip(self), ret)]
364 pub(super) fn lower_test_binder_exists(
365 &self,
366 exists: &hir::TestBinderExists<'tcx>,
367 ) -> TestBinderExists<'tcx> {
368 let bound_vars = self.tcx.late_bound_vars(exists.hir_id);
369 let body = self.lower_test_binder_body(exists.body);
370 let binder = ty::Binder::bind_with_vars(body, bound_vars);
371 TestBinderExists { span: exists.span, binder }
372 }
373
374 fn lower_test_binder_assumptions(
379 &self,
380 predicate: &hir::WherePredicate<'tcx>,
381 type_outlives: &mut Vec<ty::Binder<'tcx, ty::OutlivesClause<'tcx, Ty<'tcx>>>>,
382 region_outlives: &mut Vec<(ty::Region<'tcx>, ty::Region<'tcx>)>,
383 ) {
384 match predicate.kind {
385 hir::WherePredicateKind::BoundPredicate(p) => {
386 let bound_vars = self.tcx.late_bound_vars(predicate.hir_id);
387 let ty = self.lower_ty(p.bounded_ty);
388 for bound in p.bounds {
389 match bound {
390 hir::GenericBound::Trait(poly_trait_ref) => {
391 self.dcx()
392 .span_err(poly_trait_ref.span, "trait bounds aren't supported yet");
393 }
394 hir::GenericBound::Outlives(lifetime) => {
395 let region = self
396 .lowerer()
397 .lower_lifetime(lifetime, RegionInferReason::RegionPredicate);
398 let binder = ty::Binder::bind_with_vars(
399 ty::OutlivesClause(ty, region),
400 bound_vars,
401 );
402 type_outlives.push(binder);
403 }
404 hir::GenericBound::Use(_, span) => {
405 self.dcx().span_err(*span, "use bounds aren't supported yet");
406 }
407 }
408 }
409 }
410 hir::WherePredicateKind::RegionPredicate(predicate) => {
411 let lhs = self
412 .lowerer()
413 .lower_lifetime(predicate.lifetime, RegionInferReason::RegionPredicate);
414 for bound in predicate.bounds {
415 match bound {
416 hir::GenericBound::Trait(poly_trait_ref) => {
417 self.dcx()
418 .span_err(poly_trait_ref.span, "trait bounds aren't supported yet");
419 }
420 hir::GenericBound::Outlives(lifetime) => {
421 let rhs = self
422 .lowerer()
423 .lower_lifetime(lifetime, RegionInferReason::RegionPredicate);
424 region_outlives.push((lhs, rhs));
425 }
426 hir::GenericBound::Use(_, span) => {
427 self.dcx().span_err(*span, "use bounds aren't supported yet");
428 }
429 }
430 }
431 }
432 }
433 }
434
435 fn lower_test_binder_constraint(
436 &self,
437 constraint: &hir::TestBinderConstraint<'tcx>,
438 ) -> SolverRegionConstraint<'tcx> {
439 match constraint {
440 hir::TestBinderConstraint::And { items } => items
441 .into_iter()
442 .map(|item| self.lower_test_binder_constraint(item))
443 .reduce(SolverRegionConstraint::build_and)
444 .unwrap_or(SolverRegionConstraint::new_true()),
445 hir::TestBinderConstraint::Or { items } => items
446 .into_iter()
447 .map(|item| self.lower_test_binder_constraint(item))
448 .reduce(SolverRegionConstraint::build_or)
449 .unwrap_or(SolverRegionConstraint::new_false()),
450 hir::TestBinderConstraint::Lifetime { lhs, rhs } => {
451 let span = lhs.ident.span.to(rhs.ident.span);
452 let lhs = self.lowerer().lower_lifetime(lhs, RegionInferReason::RegionPredicate);
453 let rhs = self.lowerer().lower_lifetime(rhs, RegionInferReason::RegionPredicate);
454 SolverRegionConstraint::new_leaf(LeafRegionConstraint::RegionOutlives(
455 lhs, rhs, span,
456 ))
457 }
458 hir::TestBinderConstraint::PlaceholderOutlives { lhs, rhs } => {
459 let span = lhs.span.to(rhs.ident.span);
460 let lhs = self.lower_ty(lhs);
461 let rhs = self.lowerer().lower_lifetime(rhs, RegionInferReason::RegionPredicate);
462 SolverRegionConstraint::new_leaf(LeafRegionConstraint::PlaceholderTyOutlives(
466 lhs, rhs, span,
467 ))
468 }
469 hir::TestBinderConstraint::AliasOutlives {
470 bound_type_constraint:
471 hir::TestBinderBoundTypeConstraint { span, hir_id, params: _, lhs, rhs },
472 } => {
473 let bound_vars = self.tcx.late_bound_vars(*hir_id);
474 let &ty::Alias(_, lhs) = self.lower_ty(lhs).kind() else {
475 self.dcx().span_err(lhs.span, "bound type test binder constraint must be alias (it's a AliasTyOutlivesViaEnv)");
476 return SolverRegionConstraint::new_true();
477 };
478 let rhs = self.lowerer().lower_lifetime(rhs, RegionInferReason::RegionPredicate);
479 SolverRegionConstraint::new_leaf(LeafRegionConstraint::AliasTyOutlivesViaEnv(
480 ty::Binder::bind_with_vars((lhs, rhs), bound_vars),
481 *span,
482 ))
483 }
484 }
485 }
486}
487
488impl<'tcx> HirTyLowerer<'tcx> for ItemCtxt<'tcx> {
489 fn tcx(&self) -> TyCtxt<'tcx> {
490 self.tcx
491 }
492
493 fn dcx(&self) -> DiagCtxtHandle<'_> {
494 self.tcx.dcx().into_taintable(&self.tainted_by_errors)
495 }
496
497 fn item_def_id(&self) -> LocalDefId {
498 self.item_def_id
499 }
500
501 fn re_infer(&self, span: Span, reason: RegionInferReason<'_>) -> ty::Region<'tcx> {
502 if let RegionInferReason::ObjectLifetimeDefault(sugg_sp) = reason {
503 let guar = self
506 .dcx()
507 .struct_span_err(
508 span,
509 "cannot deduce the lifetime bound for this trait object type from context",
510 )
511 .with_code(E0228)
512 .with_span_suggestion_verbose(
513 sugg_sp,
514 "please supply an explicit bound",
515 " + /* 'a */",
516 Applicability::HasPlaceholders,
517 )
518 .emit();
519 ty::Region::new_error(self.tcx(), guar)
520 } else {
521 if self.lowering_delegation_segment {
525 self.tcx.dcx().emit_err(ElidedLifetimesAreNotAllowedInDelegations { span });
526 }
527
528 ty::Region::new_error_with_message(self.tcx(), span, "inferred lifetime in signature")
530 }
531 }
532
533 fn ty_infer(&self, _: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx> {
534 if !self.tcx.dcx().has_stashed_diagnostic(span, StashKey::ItemNoType) {
535 self.report_placeholder_type_error(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[span]))vec![span], ::alloc::vec::Vec::new()vec![]);
536 }
537 Ty::new_error_with_message(self.tcx(), span, "bad placeholder type")
538 }
539
540 fn ct_infer(&self, _: Option<&ty::GenericParamDef>, span: Span) -> Const<'tcx> {
541 self.report_placeholder_type_error(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[span]))vec![span], ::alloc::vec::Vec::new()vec![]);
542 ty::Const::new_error_with_message(self.tcx(), span, "bad placeholder constant")
543 }
544
545 fn register_trait_ascription_bounds(
546 &self,
547 _: Vec<(ty::Clause<'tcx>, Span)>,
548 _: HirId,
549 span: Span,
550 ) {
551 self.dcx().span_delayed_bug(span, "trait ascription type not allowed here");
552 }
553
554 fn probe_ty_param_bounds(
555 &self,
556 span: Span,
557 def_id: LocalDefId,
558 assoc_ident: Ident,
559 ) -> ty::EarlyBinder<'tcx, &'tcx [(ty::Clause<'tcx>, Span)]> {
560 self.tcx.at(span).type_param_clauses((self.item_def_id, def_id, assoc_ident))
561 }
562
563 {}
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("select_inherent_assoc_candidates",
"rustc_hir_analysis::collect", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect.rs"),
::tracing_core::__macro_support::Option::Some(563u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("self_ty")
}> =
::tracing::__macro_support::FieldName::new("self_ty");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("candidates")
}> =
::tracing::__macro_support::FieldName::new("candidates");
NAME.as_str()
}], ::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self_ty)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&candidates)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
(move ||
{
#[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:
(Vec<InherentAssocCandidate>,
ThinVec<FulfillmentError<'tcx>>) = loop {};
return __tracing_attr_fake_return;
}
{
if !!self_ty.has_infer() {
::core::panicking::panic("assertion failed: !self_ty.has_infer()")
};
let self_ty = self.tcx.expand_free_alias_tys(self_ty);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect.rs:577",
"rustc_hir_analysis::collect", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect.rs"),
::tracing_core::__macro_support::Option::Some(577u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect"),
::tracing_core::field::FieldSet::new(&["message"],
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("select_inherent_assoc_candidates: self_ty={0:?}",
self_ty) as &dyn ::tracing::field::Value))])
});
} else { ; }
};
let candidates =
candidates.into_iter().filter(|&InherentAssocCandidate {
impl_, .. }|
{
let impl_ty =
self.tcx().type_of(impl_).instantiate_identity().skip_norm_wip();
let impl_ty = self.tcx.expand_free_alias_tys(impl_ty);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect.rs:586",
"rustc_hir_analysis::collect", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect.rs"),
::tracing_core::__macro_support::Option::Some(586u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect"),
::tracing_core::field::FieldSet::new(&["message"],
::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("select_inherent_assoc_candidates: impl_ty={0:?}",
impl_ty) as &dyn ::tracing::field::Value))])
});
} else { ; }
};
ty::DeepRejectCtxt::relate_rigid_infer(self.tcx).types_may_unify_with_depth(self_ty,
impl_ty, usize::MAX)
}).collect();
(candidates, ::thin_vec::ThinVec::new())
}
})();
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect.rs:563",
"rustc_hir_analysis::collect", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect.rs"),
::tracing_core::__macro_support::Option::Some(563u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("return")
}> =
::tracing::__macro_support::FieldName::new("return");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
x;#[instrument(level = "debug", skip(self, _span), ret)]
564 fn select_inherent_assoc_candidates(
565 &self,
566 _span: Span,
567 self_ty: Ty<'tcx>,
568 candidates: Vec<InherentAssocCandidate>,
569 ) -> (Vec<InherentAssocCandidate>, ThinVec<FulfillmentError<'tcx>>) {
570 assert!(!self_ty.has_infer());
571
572 let self_ty = self.tcx.expand_free_alias_tys(self_ty);
577 debug!("select_inherent_assoc_candidates: self_ty={:?}", self_ty);
578
579 let candidates = candidates
580 .into_iter()
581 .filter(|&InherentAssocCandidate { impl_, .. }| {
582 let impl_ty = self.tcx().type_of(impl_).instantiate_identity().skip_norm_wip();
583
584 let impl_ty = self.tcx.expand_free_alias_tys(impl_ty);
586 debug!("select_inherent_assoc_candidates: impl_ty={:?}", impl_ty);
587
588 ty::DeepRejectCtxt::relate_rigid_infer(self.tcx).types_may_unify_with_depth(
605 self_ty,
606 impl_ty,
607 usize::MAX,
608 )
609 })
610 .collect();
611
612 (candidates, thin_vec![])
613 }
614
615 fn lower_assoc_item_path(
616 &self,
617 span: Span,
618 item_def_id: DefId,
619 item_segment: &rustc_hir::PathSegment<'_>,
620 poly_trait_ref: ty::PolyTraitRef<'tcx>,
621 ) -> Result<(DefId, ty::GenericArgsRef<'tcx>), ErrorGuaranteed> {
622 if let Some(trait_ref) = poly_trait_ref.no_bound_vars() {
623 let item_args = self.lowerer().lower_generic_args_of_assoc_item(
624 span,
625 item_def_id,
626 item_segment,
627 trait_ref.args,
628 );
629 Ok((item_def_id, item_args))
630 } else {
631 let (mut mpart_sugg, mut inferred_sugg) = (None, None);
633 let mut bound = String::new();
634
635 match self.node() {
636 hir::Node::Field(_) | hir::Node::Ctor(_) | hir::Node::Variant(_) => {
637 let item = self
638 .tcx
639 .hir_expect_item(self.tcx.hir_get_parent_item(self.hir_id()).def_id);
640 match &item.kind {
641 hir::ItemKind::Enum(_, generics, _)
642 | hir::ItemKind::Struct(_, generics, _)
643 | hir::ItemKind::Union(_, generics, _) => {
644 let lt_name = get_new_lifetime_name(self.tcx, poly_trait_ref, generics);
645 let (lt_sp, sugg) = match generics.params {
646 [] => (generics.span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<{0}>", lt_name))
})format!("<{lt_name}>")),
647 [bound, ..] => (bound.span.shrink_to_lo(), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}, ", lt_name))
})format!("{lt_name}, ")),
648 };
649 mpart_sugg = Some(diagnostics::AssociatedItemTraitUninferredGenericParamsMultipartSuggestion {
650 fspan: lt_sp,
651 first: sugg,
652 sspan: span.with_hi(item_segment.ident.span.lo()),
653 second: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}::",
self.tcx.instantiate_bound_regions_uncached(poly_trait_ref,
|_|
{
ty::Region::new_early_param(self.tcx,
ty::EarlyParamRegion {
index: 0,
name: Symbol::intern(<_name),
})
})))
})format!(
654 "{}::",
655 self.tcx.instantiate_bound_regions_uncached(
657 poly_trait_ref,
658 |_| {
659 ty::Region::new_early_param(self.tcx, ty::EarlyParamRegion {
660 index: 0,
661 name: Symbol::intern(<_name),
662 })
663 }
664 ),
665 ),
666 });
667 }
668 _ => {}
669 }
670 }
671 hir::Node::Item(hir::Item {
672 kind:
673 hir::ItemKind::Struct(..) | hir::ItemKind::Enum(..) | hir::ItemKind::Union(..),
674 ..
675 }) => {}
676 hir::Node::Item(_)
677 | hir::Node::ForeignItem(_)
678 | hir::Node::TraitItem(_)
679 | hir::Node::ImplItem(_) => {
680 inferred_sugg = Some(span.with_hi(item_segment.ident.span.lo()));
681 bound = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}::",
self.tcx.anonymize_bound_vars(poly_trait_ref).skip_binder()))
})format!(
682 "{}::",
683 self.tcx.anonymize_bound_vars(poly_trait_ref).skip_binder(),
685 );
686 }
687 _ => {}
688 }
689
690 Err(self.tcx().dcx().emit_err(
691 diagnostics::AssociatedItemTraitUninferredGenericParams {
692 span,
693 inferred_sugg,
694 bound,
695 mpart_sugg,
696 what: self.tcx.def_descr(item_def_id),
697 },
698 ))
699 }
700 }
701
702 fn probe_adt(&self, _span: Span, ty: Ty<'tcx>) -> Option<ty::AdtDef<'tcx>> {
703 ty.ty_adt_def()
705 }
706
707 fn record_ty(&self, _hir_id: hir::HirId, _ty: Ty<'tcx>, _span: Span) {
708 }
710
711 fn infcx(&self) -> Option<&InferCtxt<'tcx>> {
712 None
713 }
714
715 fn lower_fn_sig(
716 &self,
717 decl: &hir::FnDecl<'_>,
718 _generics: Option<&hir::Generics<'_>>,
719 hir_id: rustc_hir::HirId,
720 _hir_ty: Option<&hir::Ty<'_>>,
721 ) -> (Vec<Ty<'tcx>>, Ty<'tcx>) {
722 let tcx = self.tcx();
723
724 let mut infer_replacements = ::alloc::vec::Vec::new()vec![];
725
726 let input_tys = decl
727 .inputs
728 .iter()
729 .enumerate()
730 .map(|(i, a)| {
731 if let hir::TyKind::Infer(()) = a.kind
732 && let Some(suggested_ty) =
733 self.lowerer().suggest_trait_fn_ty_for_impl_fn_infer(hir_id, Some(i))
734 {
735 infer_replacements.push((a.span, suggested_ty.to_string()));
736 return Ty::new_error_with_message(tcx, a.span, suggested_ty.to_string());
737 }
738
739 self.lowerer().lower_ty(a)
740 })
741 .collect();
742
743 let output_ty = match decl.output {
744 hir::FnRetTy::Return(output) => {
745 if let hir::TyKind::Infer(()) = output.kind
746 && let Some(suggested_ty) =
747 self.lowerer().suggest_trait_fn_ty_for_impl_fn_infer(hir_id, None)
748 {
749 infer_replacements.push((output.span, suggested_ty.to_string()));
750 Ty::new_error_with_message(tcx, output.span, suggested_ty.to_string())
751 } else {
752 self.lower_ty(output)
753 }
754 }
755 hir::FnRetTy::DefaultReturn(..) => tcx.types.unit,
756 };
757
758 if !infer_replacements.is_empty() {
759 self.report_placeholder_type_error(::alloc::vec::Vec::new()vec![], infer_replacements);
760 }
761 (input_tys, output_ty)
762 }
763
764 fn dyn_compatibility_violations(&self, trait_def_id: DefId) -> Vec<DynCompatibilityViolation> {
765 hir_ty_lowering_dyn_compatibility_violations(self.tcx, trait_def_id)
766 }
767}
768
769fn get_new_lifetime_name<'tcx>(
771 tcx: TyCtxt<'tcx>,
772 poly_trait_ref: ty::PolyTraitRef<'tcx>,
773 generics: &hir::Generics<'tcx>,
774) -> String {
775 let existing_lifetimes = tcx
776 .collect_referenced_late_bound_regions(poly_trait_ref)
777 .into_iter()
778 .filter_map(|lt| lt.get_name(tcx).map(|name| name.as_str().to_string()))
779 .chain(generics.params.iter().filter_map(|param| {
780 if let hir::GenericParamKind::Lifetime { .. } = ¶m.kind {
781 Some(param.name.ident().as_str().to_string())
782 } else {
783 None
784 }
785 }))
786 .collect::<FxHashSet<String>>();
787
788 let a_to_z_repeat_n = |n| {
789 (b'a'..=b'z').map(move |c| {
790 let mut s = '\''.to_string();
791 s.extend(std::iter::repeat_n(char::from(c), n));
792 s
793 })
794 };
795
796 (1..).flat_map(a_to_z_repeat_n).find(|lt| !existing_lifetimes.contains(lt.as_str())).unwrap()
798}
799
800pub(super) fn check_ctor(tcx: TyCtxt<'_>, def_id: LocalDefId) {
801 tcx.ensure_ok().generics_of(def_id);
802 tcx.ensure_ok().type_of(def_id);
803 tcx.ensure_ok().clauses_of(def_id);
804}
805
806pub(super) fn check_enum_variant_types(tcx: TyCtxt<'_>, def_id: LocalDefId) {
807 struct ReprCIssue {
808 msg: &'static str,
809 }
810
811 impl<'a> Diagnostic<'a, ()> for ReprCIssue {
812 fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, ()> {
813 let Self { msg } = self;
814 Diag::new(dcx, level, msg)
815 .with_note("`repr(C)` enums with big discriminants are non-portable, and their size in Rust might not match their size in C")
816 .with_help("use `repr($int_ty)` instead to explicitly set the size of this enum")
817 }
818 }
819
820 let def = tcx.adt_def(def_id);
821 let repr_type = def.repr().discr_type();
822 let initial = repr_type.initial_discriminant(tcx);
823 let mut prev_discr = None::<Discr<'_>>;
824 if !(tcx.sess.target.c_int_width < 128) {
::core::panicking::panic("assertion failed: tcx.sess.target.c_int_width < 128")
};assert!(tcx.sess.target.c_int_width < 128);
826 let mut min_discr = i128::MAX;
827 let mut max_discr = i128::MIN;
828
829 for variant in def.variants() {
831 let wrapped_discr = prev_discr.map_or(initial, |d| d.wrap_incr(tcx));
832 let cur_discr = if let ty::VariantDiscr::Explicit(const_def_id) = variant.discr {
833 def.eval_explicit_discr(tcx, const_def_id).ok()
834 } else if let Some(discr) = repr_type.disr_incr(tcx, prev_discr) {
835 Some(discr)
836 } else {
837 let span = tcx.def_span(variant.def_id);
838 tcx.dcx().emit_err(diagnostics::EnumDiscriminantOverflowed {
839 span,
840 discr: prev_discr.unwrap().to_string(),
841 item_name: tcx.item_ident(variant.def_id),
842 wrapped_discr: wrapped_discr.to_string(),
843 });
844 None
845 }
846 .unwrap_or(wrapped_discr);
847
848 if def.repr().c() {
849 let c_int = Size::from_bits(tcx.sess.target.c_int_width);
850 let c_uint_max = i128::try_from(c_int.unsigned_int_max()).unwrap();
851 let discr_size = cur_discr.ty.int_size_and_signed(tcx).0;
853 let discr_val = discr_size.sign_extend(cur_discr.val);
854 min_discr = min_discr.min(discr_val);
855 max_discr = max_discr.max(discr_val);
856
857 if !(min_discr >= c_int.signed_int_min() && max_discr <= c_int.signed_int_max())
859 && !(min_discr >= 0 && max_discr <= c_uint_max)
860 {
861 let span = tcx.def_span(variant.def_id);
862 let msg = if discr_val < c_int.signed_int_min() || discr_val > c_uint_max {
863 "`repr(C)` enum discriminant does not fit into C `int` nor into C `unsigned int`"
864 } else if discr_val < 0 {
865 "`repr(C)` enum discriminant does not fit into C `unsigned int`, and a previous discriminant does not fit into C `int`"
866 } else {
867 "`repr(C)` enum discriminant does not fit into C `int`, and a previous discriminant does not fit into C `unsigned int`"
868 };
869 tcx.emit_node_span_lint(
870 REPR_C_ENUMS_LARGER_THAN_INT,
871 tcx.local_def_id_to_hir_id(def_id),
872 span,
873 ReprCIssue { msg },
874 );
875 }
876 }
877
878 prev_discr = Some(cur_discr);
879
880 for f in &variant.fields {
881 tcx.ensure_ok().generics_of(f.did);
882 tcx.ensure_ok().type_of(f.did);
883 tcx.ensure_ok().clauses_of(f.did);
884 }
885
886 if let Some(ctor_def_id) = variant.ctor_def_id() {
888 check_ctor(tcx, ctor_def_id.expect_local());
889 }
890 }
891}
892
893#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for NestedSpan { }
#[automatically_derived]
impl ::core::clone::Clone for NestedSpan {
#[inline]
fn clone(&self) -> NestedSpan {
let _: ::core::clone::AssertParamIsClone<Span>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for NestedSpan { }Copy)]
894struct NestedSpan {
895 span: Span,
896 nested_field_span: Span,
897}
898
899impl NestedSpan {
900 fn to_field_already_declared_nested_help(&self) -> diagnostics::FieldAlreadyDeclaredNestedHelp {
901 diagnostics::FieldAlreadyDeclaredNestedHelp { span: self.span }
902 }
903}
904
905#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for FieldDeclSpan { }
#[automatically_derived]
impl ::core::clone::Clone for FieldDeclSpan {
#[inline]
fn clone(&self) -> FieldDeclSpan {
let _: ::core::clone::AssertParamIsClone<Span>;
let _: ::core::clone::AssertParamIsClone<NestedSpan>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for FieldDeclSpan { }Copy)]
906enum FieldDeclSpan {
907 NotNested(Span),
908 Nested(NestedSpan),
909}
910
911impl From<Span> for FieldDeclSpan {
912 fn from(span: Span) -> Self {
913 Self::NotNested(span)
914 }
915}
916
917impl From<NestedSpan> for FieldDeclSpan {
918 fn from(span: NestedSpan) -> Self {
919 Self::Nested(span)
920 }
921}
922
923struct FieldUniquenessCheckContext<'tcx> {
924 tcx: TyCtxt<'tcx>,
925 seen_fields: FxIndexMap<Ident, FieldDeclSpan>,
926}
927
928impl<'tcx> FieldUniquenessCheckContext<'tcx> {
929 fn new(tcx: TyCtxt<'tcx>) -> Self {
930 Self { tcx, seen_fields: FxIndexMap::default() }
931 }
932
933 fn check_field_decl(&mut self, field_name: Ident, field_decl: FieldDeclSpan) {
935 use FieldDeclSpan::*;
936 let field_name = field_name.normalize_to_macros_2_0();
937 match (field_decl, self.seen_fields.get(&field_name).copied()) {
938 (NotNested(span), Some(NotNested(prev_span))) => {
939 self.tcx.dcx().emit_err(diagnostics::FieldAlreadyDeclared::NotNested {
940 field_name,
941 span,
942 prev_span,
943 });
944 }
945 (NotNested(span), Some(Nested(prev))) => {
946 self.tcx.dcx().emit_err(diagnostics::FieldAlreadyDeclared::PreviousNested {
947 field_name,
948 span,
949 prev_span: prev.span,
950 prev_nested_field_span: prev.nested_field_span,
951 prev_help: prev.to_field_already_declared_nested_help(),
952 });
953 }
954 (
955 Nested(current @ NestedSpan { span, nested_field_span, .. }),
956 Some(NotNested(prev_span)),
957 ) => {
958 self.tcx.dcx().emit_err(diagnostics::FieldAlreadyDeclared::CurrentNested {
959 field_name,
960 span,
961 nested_field_span,
962 help: current.to_field_already_declared_nested_help(),
963 prev_span,
964 });
965 }
966 (Nested(current @ NestedSpan { span, nested_field_span }), Some(Nested(prev))) => {
967 self.tcx.dcx().emit_err(diagnostics::FieldAlreadyDeclared::BothNested {
968 field_name,
969 span,
970 nested_field_span,
971 help: current.to_field_already_declared_nested_help(),
972 prev_span: prev.span,
973 prev_nested_field_span: prev.nested_field_span,
974 prev_help: prev.to_field_already_declared_nested_help(),
975 });
976 }
977 (field_decl, None) => {
978 self.seen_fields.insert(field_name, field_decl);
979 }
980 }
981 }
982}
983
984fn lower_variant<'tcx>(
985 tcx: TyCtxt<'tcx>,
986 variant_did: Option<LocalDefId>,
987 ident: Ident,
988 discr: ty::VariantDiscr,
989 def: &hir::VariantData<'tcx>,
990 adt_kind: ty::AdtKind,
991 parent_did: LocalDefId,
992) -> ty::VariantDef {
993 let mut field_uniqueness_check_ctx = FieldUniquenessCheckContext::new(tcx);
994 let fields = def
995 .fields()
996 .iter()
997 .inspect(|field| {
998 field_uniqueness_check_ctx.check_field_decl(field.ident, field.span.into());
999 })
1000 .map(|f| ty::FieldDef {
1001 did: f.def_id.to_def_id(),
1002 name: f.ident.name,
1003 vis: tcx.visibility(f.def_id),
1004 mut_restriction: match f.mut_restriction.kind {
1005 hir::RestrictionKind::Unrestricted => ty::RestrictionKind::Unrestricted,
1006 hir::RestrictionKind::Restricted(path) => {
1007 ty::RestrictionKind::Restricted(path.res, f.mut_restriction.span)
1008 }
1009 },
1010 safety: f.safety,
1011 value: f.default.map(|v| v.def_id.to_def_id()),
1012 })
1013 .collect();
1014 let recovered = match def {
1015 hir::VariantData::Struct { recovered: Recovered::Yes(guar), .. } => Some(*guar),
1016 _ => None,
1017 };
1018 ty::VariantDef::new(
1019 ident.name,
1020 variant_did.map(LocalDefId::to_def_id),
1021 def.ctor().map(|(kind, _, def_id)| (kind, def_id.to_def_id())),
1022 discr,
1023 fields,
1024 parent_did.to_def_id(),
1025 recovered,
1026 adt_kind == AdtKind::Struct && {
{
'done:
{
for i in
::rustc_attr_ir::HasAttrs::get_attrs(parent_did, &tcx) {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(NonExhaustive(..)) => {
break 'done Some(());
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}.is_some()find_attr!(tcx, parent_did, NonExhaustive(..))
1027 || variant_did
1028 .is_some_and(|variant_did| {
{
'done:
{
for i in
::rustc_attr_ir::HasAttrs::get_attrs(variant_did, &tcx) {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(NonExhaustive(..)) => {
break 'done Some(());
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}.is_some()find_attr!(tcx, variant_did, NonExhaustive(..))),
1029 )
1030}
1031
1032fn adt_def(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::AdtDef<'_> {
1033 use rustc_hir::*;
1034
1035 let Node::Item(item) = tcx.hir_node_by_def_id(def_id) else {
1036 ::rustc_middle::util::bug::bug_fmt(format_args!("expected ADT to be an item"));bug!("expected ADT to be an item");
1037 };
1038
1039 let repr = tcx.repr_options_of_def(def_id);
1040 let (kind, variants) = match &item.kind {
1041 ItemKind::Enum(_, _, def) => {
1042 let mut distance_from_explicit = 0;
1043 let variants = def
1044 .variants
1045 .iter()
1046 .map(|v| {
1047 let discr = if let Some(e) = &v.disr_expr {
1048 distance_from_explicit = 0;
1049 ty::VariantDiscr::Explicit(e.def_id.to_def_id())
1050 } else {
1051 ty::VariantDiscr::Relative(distance_from_explicit)
1052 };
1053 distance_from_explicit += 1;
1054
1055 lower_variant(
1056 tcx,
1057 Some(v.def_id),
1058 v.ident,
1059 discr,
1060 &v.data,
1061 AdtKind::Enum,
1062 def_id,
1063 )
1064 })
1065 .collect();
1066
1067 (AdtKind::Enum, variants)
1068 }
1069 ItemKind::Struct(ident, _, def) | ItemKind::Union(ident, _, def) => {
1070 let adt_kind = match item.kind {
1071 ItemKind::Struct(..) => AdtKind::Struct,
1072 _ => AdtKind::Union,
1073 };
1074 let variants = std::iter::once(lower_variant(
1075 tcx,
1076 None,
1077 *ident,
1078 ty::VariantDiscr::Relative(0),
1079 def,
1080 adt_kind,
1081 def_id,
1082 ))
1083 .collect();
1084
1085 (adt_kind, variants)
1086 }
1087 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("{0:?} is not an ADT",
item.owner_id.def_id))bug!("{:?} is not an ADT", item.owner_id.def_id),
1088 };
1089 tcx.mk_adt_def(def_id.to_def_id(), kind, variants, repr)
1090}
1091
1092fn trait_def(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::TraitDef {
1093 let item = tcx.hir_expect_item(def_id);
1094
1095 let (constness, is_alias, is_auto, safety, impl_restriction) = match item.kind {
1096 hir::ItemKind::Trait { impl_restriction, constness, is_auto, safety, .. } => (
1097 constness,
1098 false,
1099 is_auto == hir::IsAuto::Yes,
1100 safety,
1101 match impl_restriction.kind {
1102 hir::RestrictionKind::Restricted(path) => {
1103 ty::RestrictionKind::Restricted(path.res, impl_restriction.span)
1104 }
1105 hir::RestrictionKind::Unrestricted => ty::RestrictionKind::Unrestricted,
1106 },
1107 ),
1108 hir::ItemKind::TraitAlias(constness, ..) => {
1109 (constness, true, false, hir::Safety::Safe, ty::RestrictionKind::Unrestricted)
1110 }
1111 _ => ::rustc_middle::util::bug::span_bug_fmt(item.span,
format_args!("trait_def_of_item invoked on non-trait"))span_bug!(item.span, "trait_def_of_item invoked on non-trait"),
1112 };
1113
1114 #[allow(deprecated)]
1116 let attrs = tcx.get_all_attrs(def_id);
1117
1118 let paren_sugar = {
{
'done:
{
for i in attrs {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(RustcParenSugar) => {
break 'done Some(());
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}.is_some()
}find_attr!(attrs, RustcParenSugar);
1119
1120 let is_marker = !is_alias && {
{
'done:
{
for i in attrs {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(Marker) => {
break 'done Some(());
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}.is_some()
}find_attr!(attrs, Marker);
1122
1123 let rustc_coinductive = {
{
'done:
{
for i in attrs {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(RustcCoinductive) => {
break 'done Some(());
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}.is_some()
}find_attr!(attrs, RustcCoinductive);
1124 let is_fundamental = {
{
'done:
{
for i in attrs {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(Fundamental) => {
break 'done Some(());
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}.is_some()
}find_attr!(attrs, Fundamental);
1125
1126 let [skip_array_during_method_dispatch, skip_boxed_slice_during_method_dispatch] = {
'done:
{
for i in attrs {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(RustcSkipDuringMethodDispatch {
array, boxed_slice }) => {
break 'done Some([*array, *boxed_slice]);
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}find_attr!(
1127 attrs,
1128 RustcSkipDuringMethodDispatch { array, boxed_slice } => [*array, *boxed_slice]
1129 )
1130 .unwrap_or([false; 2]);
1131
1132 let specialization_kind = if {
{
'done:
{
for i in attrs {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(RustcAllowLifetimeDependentSpecialization)
=> {
break 'done Some(());
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}.is_some()
}find_attr!(attrs, RustcAllowLifetimeDependentSpecialization) {
1133 ty::trait_def::TraitSpecializationKind::Marker
1134 } else if {
{
'done:
{
for i in attrs {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(RustcSpecializationTrait)
=> {
break 'done Some(());
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}.is_some()
}find_attr!(attrs, RustcSpecializationTrait) {
1135 ty::trait_def::TraitSpecializationKind::AlwaysApplicable
1136 } else {
1137 ty::trait_def::TraitSpecializationKind::None
1138 };
1139
1140 let must_implement_one_of = {
'done:
{
for i in attrs {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(RustcMustImplementOneOf {
fn_names, .. }) => {
break 'done
Some(fn_names.iter().cloned().collect::<Box<[_]>>());
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}find_attr!(
1141 attrs,
1142 RustcMustImplementOneOf { fn_names, .. } =>
1143 fn_names
1144 .iter()
1145 .cloned()
1146 .collect::<Box<[_]>>()
1147 );
1148
1149 let deny_explicit_impl = {
{
'done:
{
for i in attrs {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(RustcDenyExplicitImpl) =>
{
break 'done Some(());
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}.is_some()
}find_attr!(attrs, RustcDenyExplicitImpl);
1150 let force_dyn_incompatible = {
'done:
{
for i in attrs {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(RustcDynIncompatibleTrait(span))
=> {
break 'done Some(*span);
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}find_attr!(attrs, RustcDynIncompatibleTrait(span) => *span);
1151
1152 ty::TraitDef {
1153 def_id: def_id.to_def_id(),
1154 impl_restriction,
1155 safety,
1156 constness,
1157 paren_sugar,
1158 has_auto_impl: is_auto,
1159 is_marker,
1160 is_coinductive: rustc_coinductive || is_auto,
1161 is_fundamental,
1162 skip_array_during_method_dispatch,
1163 skip_boxed_slice_during_method_dispatch,
1164 specialization_kind,
1165 must_implement_one_of,
1166 force_dyn_incompatible,
1167 deny_explicit_impl,
1168 }
1169}
1170
1171{}
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("fn_sig",
"rustc_hir_analysis::collect", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect.rs"),
::tracing_core::__macro_support::Option::Some(1171u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("def_id")
}> =
::tracing::__macro_support::FieldName::new("def_id");
NAME.as_str()
}], ::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
(move ||
{
#[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:
ty::EarlyBinder<'_, ty::PolyFnSig<'_>> = loop {};
return __tracing_attr_fake_return;
}
{
use rustc_hir::Node::*;
use rustc_hir::*;
let hir_id = tcx.local_def_id_to_hir_id(def_id);
let icx = ItemCtxt::new(tcx, def_id);
let output =
match tcx.hir_node(hir_id) {
TraitItem(hir::TraitItem {
kind: TraitItemKind::Fn(sig, TraitFn::Provided(_)),
generics, .. }) |
Item(hir::Item { kind: ItemKind::Fn { sig, generics, .. },
.. }) => {
lower_fn_sig_recovering_infer_ret_ty(&icx, sig, generics,
def_id)
}
ImplItem(hir::ImplItem {
kind: ImplItemKind::Fn(sig, _), generics, .. }) => {
if let Item(hir::Item { kind: ItemKind::Impl(i), .. }) =
tcx.parent_hir_node(hir_id) && i.of_trait.is_some() {
icx.lowerer().lower_fn_ty(hir_id, sig.header.safety(),
sig.header.abi, sig.decl, Some(generics), None)
} else {
lower_fn_sig_recovering_infer_ret_ty(&icx, sig, generics,
def_id)
}
}
TraitItem(hir::TraitItem {
kind: TraitItemKind::Fn(FnSig { header, decl, span: _ }, _),
generics, .. }) =>
icx.lowerer().lower_fn_ty(hir_id, header.safety(),
header.abi, decl, Some(generics), None),
ForeignItem(&hir::ForeignItem {
kind: ForeignItemKind::Fn(sig, _, _), .. }) => {
let abi = tcx.hir_get_foreign_abi(hir_id);
compute_sig_of_foreign_fn_decl(tcx, def_id, sig.decl, abi,
sig.header.safety())
}
Ctor(data) => {
{
match data.ctor() {
Some(_) => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val,
"Some(_)", ::core::option::Option::None);
}
}
};
let adt_def_id =
tcx.hir_get_parent_item(hir_id).def_id.to_def_id();
let ty =
tcx.type_of(adt_def_id).instantiate_identity().skip_norm_wip();
let inputs =
data.fields().iter().map(|f|
tcx.type_of(f.def_id).instantiate_identity().skip_norm_wip());
ty::Binder::dummy(tcx.mk_fn_sig_rust_abi(inputs, ty,
hir::Safety::Safe))
}
Expr(&hir::Expr { kind: hir::ExprKind::Closure { .. }, .. })
=> {
::rustc_middle::util::bug::bug_fmt(format_args!("to get the signature of a closure, use `args.as_closure().sig()` not `fn_sig()`"));
}
x => {
::rustc_middle::util::bug::bug_fmt(format_args!("unexpected sort of node in fn_sig(): {0:?}",
x));
}
};
ty::EarlyBinder::bind(tcx, output)
}
})();
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect.rs:1171",
"rustc_hir_analysis::collect", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect.rs"),
::tracing_core::__macro_support::Option::Some(1171u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("return")
}> =
::tracing::__macro_support::FieldName::new("return");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
x;#[instrument(level = "debug", skip(tcx), ret)]
1172fn fn_sig(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::EarlyBinder<'_, ty::PolyFnSig<'_>> {
1173 use rustc_hir::Node::*;
1174 use rustc_hir::*;
1175
1176 let hir_id = tcx.local_def_id_to_hir_id(def_id);
1177
1178 let icx = ItemCtxt::new(tcx, def_id);
1179
1180 let output = match tcx.hir_node(hir_id) {
1181 TraitItem(hir::TraitItem {
1182 kind: TraitItemKind::Fn(sig, TraitFn::Provided(_)),
1183 generics,
1184 ..
1185 })
1186 | Item(hir::Item { kind: ItemKind::Fn { sig, generics, .. }, .. }) => {
1187 lower_fn_sig_recovering_infer_ret_ty(&icx, sig, generics, def_id)
1188 }
1189
1190 ImplItem(hir::ImplItem { kind: ImplItemKind::Fn(sig, _), generics, .. }) => {
1191 if let Item(hir::Item { kind: ItemKind::Impl(i), .. }) = tcx.parent_hir_node(hir_id)
1193 && i.of_trait.is_some()
1194 {
1195 icx.lowerer().lower_fn_ty(
1196 hir_id,
1197 sig.header.safety(),
1198 sig.header.abi,
1199 sig.decl,
1200 Some(generics),
1201 None,
1202 )
1203 } else {
1204 lower_fn_sig_recovering_infer_ret_ty(&icx, sig, generics, def_id)
1205 }
1206 }
1207
1208 TraitItem(hir::TraitItem {
1209 kind: TraitItemKind::Fn(FnSig { header, decl, span: _ }, _),
1210 generics,
1211 ..
1212 }) => icx.lowerer().lower_fn_ty(
1213 hir_id,
1214 header.safety(),
1215 header.abi,
1216 decl,
1217 Some(generics),
1218 None,
1219 ),
1220
1221 ForeignItem(&hir::ForeignItem { kind: ForeignItemKind::Fn(sig, _, _), .. }) => {
1222 let abi = tcx.hir_get_foreign_abi(hir_id);
1223 compute_sig_of_foreign_fn_decl(tcx, def_id, sig.decl, abi, sig.header.safety())
1224 }
1225
1226 Ctor(data) => {
1227 assert_matches!(data.ctor(), Some(_));
1228 let adt_def_id = tcx.hir_get_parent_item(hir_id).def_id.to_def_id();
1229 let ty = tcx.type_of(adt_def_id).instantiate_identity().skip_norm_wip();
1230 let inputs = data
1231 .fields()
1232 .iter()
1233 .map(|f| tcx.type_of(f.def_id).instantiate_identity().skip_norm_wip());
1234 ty::Binder::dummy(tcx.mk_fn_sig_rust_abi(inputs, ty, hir::Safety::Safe))
1235 }
1236
1237 Expr(&hir::Expr { kind: hir::ExprKind::Closure { .. }, .. }) => {
1238 bug!("to get the signature of a closure, use `args.as_closure().sig()` not `fn_sig()`",);
1249 }
1250
1251 x => {
1252 bug!("unexpected sort of node in fn_sig(): {:?}", x);
1253 }
1254 };
1255 ty::EarlyBinder::bind(tcx, output)
1256}
1257
1258fn lower_fn_sig_recovering_infer_ret_ty<'tcx>(
1259 icx: &ItemCtxt<'tcx>,
1260 sig: &'tcx hir::FnSig<'tcx>,
1261 generics: &'tcx hir::Generics<'tcx>,
1262 def_id: LocalDefId,
1263) -> ty::PolyFnSig<'tcx> {
1264 if let Some(infer_ret_ty) = sig.decl.output.is_suggestable_infer_ty() {
1265 return recover_infer_ret_ty(icx, infer_ret_ty, generics, def_id);
1266 }
1267
1268 icx.lowerer().lower_fn_ty(
1269 icx.tcx().local_def_id_to_hir_id(def_id),
1270 sig.header.safety(),
1271 sig.header.abi,
1272 sig.decl,
1273 Some(generics),
1274 None,
1275 )
1276}
1277
1278fn late_param_regions_to_bound<'tcx, T>(
1280 tcx: TyCtxt<'tcx>,
1281 scope: DefId,
1282 bound_vars: &'tcx ty::List<ty::BoundVariableKind<'tcx>>,
1283 value: T,
1284) -> ty::Binder<'tcx, T>
1285where
1286 T: ty::TypeFoldable<TyCtxt<'tcx>>,
1287{
1288 let value = fold_regions(tcx, value, |r, debruijn| match r.kind() {
1289 ty::ReLateParam(lp) => {
1290 {
match (&lp.scope, &scope) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(lp.scope, scope);
1292
1293 let br = match lp.kind {
1294 kind @ (ty::LateParamRegionKind::Anon(idx)
1296 | ty::LateParamRegionKind::NamedAnon(idx, _)) => {
1297 let idx = idx as usize;
1298 let var = ty::BoundVar::from_usize(idx);
1299
1300 let Some(ty::BoundVariableKind::Region(kind)) = bound_vars.get(idx).copied()
1301 else {
1302 ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected late-bound region {0:?} for bound vars {1:?}",
kind, bound_vars));bug!("unexpected late-bound region {kind:?} for bound vars {bound_vars:?}");
1303 };
1304
1305 ty::BoundRegion { var, kind }
1306 }
1307
1308 ty::LateParamRegionKind::Named(def_id) => bound_vars
1310 .iter()
1311 .enumerate()
1312 .find_map(|(idx, bv)| match bv {
1313 ty::BoundVariableKind::Region(kind @ ty::BoundRegionKind::Named(did))
1314 if did == def_id =>
1315 {
1316 Some(ty::BoundRegion { var: ty::BoundVar::from_usize(idx), kind })
1317 }
1318 _ => None,
1319 })
1320 .unwrap(),
1321
1322 ty::LateParamRegionKind::ClosureEnv => bound_vars
1323 .iter()
1324 .enumerate()
1325 .find_map(|(idx, bv)| match bv {
1326 ty::BoundVariableKind::Region(kind @ ty::BoundRegionKind::ClosureEnv) => {
1327 Some(ty::BoundRegion { var: ty::BoundVar::from_usize(idx), kind })
1328 }
1329 _ => None,
1330 })
1331 .unwrap(),
1332 };
1333
1334 ty::Region::new_bound(tcx, debruijn, br)
1335 }
1336 _ => r,
1337 });
1338
1339 ty::Binder::bind_with_vars(value, bound_vars)
1340}
1341
1342fn recover_infer_ret_ty<'tcx>(
1343 icx: &ItemCtxt<'tcx>,
1344 infer_ret_ty: &'tcx hir::Ty<'tcx>,
1345 generics: &'tcx hir::Generics<'tcx>,
1346 def_id: LocalDefId,
1347) -> ty::PolyFnSig<'tcx> {
1348 let tcx = icx.tcx;
1349 let hir_id = tcx.local_def_id_to_hir_id(def_id);
1350
1351 let fn_sig = tcx.typeck(def_id).liberated_fn_sigs()[hir_id];
1352
1353 let has_region_params = generics.params.iter().any(|param| match param.kind {
1358 GenericParamKind::Lifetime { .. } => true,
1359 _ => false,
1360 });
1361 let fn_sig = fold_regions(tcx, fn_sig, |r, _| match r.kind() {
1362 ty::ReErased => {
1363 if has_region_params {
1364 ty::Region::new_error_with_message(
1365 tcx,
1366 DUMMY_SP,
1367 "erased region is not allowed here in return type",
1368 )
1369 } else {
1370 tcx.lifetimes.re_static
1371 }
1372 }
1373 _ => r,
1374 });
1375
1376 let mut visitor = HirPlaceholderCollector::default();
1377 visitor.visit_ty_unambig(infer_ret_ty);
1378
1379 let mut diag = bad_placeholder(icx.lowerer(), visitor.spans, "return type");
1380 let ret_ty = fn_sig.output();
1381
1382 let mut recovered_ret_ty = None;
1386 if let Some(suggestable_ret_ty) = ret_ty.make_suggestable(tcx, false, None) {
1387 diag.span_suggestion_verbose(
1388 infer_ret_ty.span,
1389 "replace with the correct return type",
1390 suggestable_ret_ty,
1391 Applicability::MachineApplicable,
1392 );
1393 recovered_ret_ty = Some(suggestable_ret_ty);
1394 } else if let Some(sugg) = suggest_impl_trait(
1395 &tcx.infer_ctxt().build(TypingMode::non_body_analysis()),
1396 tcx.param_env(def_id),
1397 ret_ty,
1398 ) {
1399 diag.span_suggestion_verbose(
1400 infer_ret_ty.span,
1401 "replace with an appropriate return type",
1402 sugg,
1403 Applicability::MachineApplicable,
1404 );
1405 } else if ret_ty.is_closure() {
1406 diag.help("consider using an `Fn`, `FnMut`, or `FnOnce` trait bound");
1407 }
1408
1409 if ret_ty.is_closure() {
1411 diag.note(
1412 "for more information on `Fn` traits and closure types, see \
1413 https://doc.rust-lang.org/book/ch13-01-closures.html",
1414 );
1415 }
1416 let guar = diag.emit();
1417
1418 let bound_vars = tcx.late_bound_vars(hir_id);
1422 let scope = def_id.to_def_id();
1423
1424 let fn_sig = tcx.mk_fn_sig(
1425 fn_sig.inputs().iter().copied(),
1426 recovered_ret_ty.unwrap_or_else(|| Ty::new_error(tcx, guar)),
1427 fn_sig.fn_sig_kind,
1428 );
1429
1430 late_param_regions_to_bound(tcx, scope, bound_vars, fn_sig)
1431}
1432
1433pub fn suggest_impl_trait<'tcx>(
1434 infcx: &InferCtxt<'tcx>,
1435 param_env: ty::ParamEnv<'tcx>,
1436 ret_ty: Ty<'tcx>,
1437) -> Option<String> {
1438 let format_as_assoc: fn(_, _, _, _, _) -> _ =
1439 |tcx: TyCtxt<'tcx>,
1440 _: ty::GenericArgsRef<'tcx>,
1441 trait_def_id: DefId,
1442 assoc_item_def_id: DefId,
1443 item_ty: Ty<'tcx>| {
1444 let trait_name = tcx.item_name(trait_def_id);
1445 let assoc_name = tcx.item_name(assoc_item_def_id);
1446 Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("impl {0}<{1} = {2}>", trait_name,
assoc_name, item_ty))
})format!("impl {trait_name}<{assoc_name} = {item_ty}>"))
1447 };
1448 let format_as_parenthesized: fn(_, _, _, _, _) -> _ =
1449 |tcx: TyCtxt<'tcx>,
1450 args: ty::GenericArgsRef<'tcx>,
1451 trait_def_id: DefId,
1452 _: DefId,
1453 item_ty: Ty<'tcx>| {
1454 let trait_name = tcx.item_name(trait_def_id);
1455 let args_tuple = args.type_at(1);
1456 let ty::Tuple(types) = *args_tuple.kind() else {
1457 return None;
1458 };
1459 let types = types.make_suggestable(tcx, false, None)?;
1460 let maybe_ret =
1461 if item_ty.is_unit() { String::new() } else { ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" -> {0}", item_ty))
})format!(" -> {item_ty}") };
1462 Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("impl {1}({0}){2}",
types.iter().map(|ty|
ty.to_string()).collect::<Vec<_>>().join(", "), trait_name,
maybe_ret))
})format!(
1463 "impl {trait_name}({}){maybe_ret}",
1464 types.iter().map(|ty| ty.to_string()).collect::<Vec<_>>().join(", ")
1465 ))
1466 };
1467
1468 for (trait_def_id, assoc_item_def_id, formatter) in [
1469 (
1470 infcx.tcx.get_diagnostic_item(sym::Iterator),
1471 infcx.tcx.get_diagnostic_item(sym::IteratorItem),
1472 format_as_assoc,
1473 ),
1474 (
1475 infcx.tcx.lang_items().future_trait(),
1476 infcx.tcx.lang_items().future_output(),
1477 format_as_assoc,
1478 ),
1479 (
1480 infcx.tcx.lang_items().async_fn_trait(),
1481 infcx.tcx.lang_items().async_fn_once_output(),
1482 format_as_parenthesized,
1483 ),
1484 (
1485 infcx.tcx.lang_items().async_fn_mut_trait(),
1486 infcx.tcx.lang_items().async_fn_once_output(),
1487 format_as_parenthesized,
1488 ),
1489 (
1490 infcx.tcx.lang_items().async_fn_once_trait(),
1491 infcx.tcx.lang_items().async_fn_once_output(),
1492 format_as_parenthesized,
1493 ),
1494 (
1495 infcx.tcx.lang_items().fn_trait(),
1496 infcx.tcx.lang_items().fn_once_output(),
1497 format_as_parenthesized,
1498 ),
1499 (
1500 infcx.tcx.lang_items().fn_mut_trait(),
1501 infcx.tcx.lang_items().fn_once_output(),
1502 format_as_parenthesized,
1503 ),
1504 (
1505 infcx.tcx.lang_items().fn_once_trait(),
1506 infcx.tcx.lang_items().fn_once_output(),
1507 format_as_parenthesized,
1508 ),
1509 ] {
1510 let Some(trait_def_id) = trait_def_id else {
1511 continue;
1512 };
1513 let Some(assoc_item_def_id) = assoc_item_def_id else {
1514 continue;
1515 };
1516 if infcx.tcx.def_kind(assoc_item_def_id) != DefKind::AssocTy {
1517 continue;
1518 }
1519 let sugg = infcx.probe(|_| {
1520 let args = ty::GenericArgs::for_item(infcx.tcx, trait_def_id, |param, _| {
1521 if param.index == 0 { ret_ty.into() } else { infcx.var_for_def(DUMMY_SP, param) }
1522 });
1523 if !infcx
1524 .type_implements_trait(trait_def_id, args, param_env)
1525 .must_apply_modulo_regions()
1526 {
1527 return None;
1528 }
1529 let ocx = ObligationCtxt::new(&infcx);
1530 let item_ty = ocx.normalize(
1531 &ObligationCause::dummy(),
1532 param_env,
1533 Unnormalized::new(Ty::new_projection_from_args(
1534 infcx.tcx,
1535 ty::IsRigid::No,
1536 assoc_item_def_id,
1537 args,
1538 )),
1539 );
1540 if ocx.try_evaluate_obligations().no_errors()
1542 && let item_ty = infcx.deeply_resolve_ignoring_regions(item_ty)
1543 && let Some(item_ty) = item_ty.make_suggestable(infcx.tcx, false, None)
1544 && let Some(sugg) = formatter(
1545 infcx.tcx,
1546 infcx.deeply_resolve_ignoring_regions(args),
1547 trait_def_id,
1548 assoc_item_def_id,
1549 item_ty,
1550 )
1551 {
1552 return Some(sugg);
1553 }
1554
1555 None
1556 });
1557
1558 if sugg.is_some() {
1559 return sugg;
1560 }
1561 }
1562 None
1563}
1564
1565fn impl_is_fully_generic_for_reflection(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool {
1566 tcx.impl_trait_header(def_id).is_fully_generic_for_reflection()
1567 && tcx.explicit_clauses_of(def_id).is_fully_generic_for_reflection()
1568}
1569
1570fn impl_trait_header(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::ImplTraitHeader<'_> {
1571 let icx = ItemCtxt::new(tcx, def_id);
1572 let item = tcx.hir_expect_item(def_id);
1573 let impl_ = item.expect_impl();
1574 let of_trait = impl_
1575 .of_trait
1576 .unwrap_or_else(|| {
::core::panicking::panic_fmt(format_args!("expected impl trait, found inherent impl on {0:?}",
def_id));
}panic!("expected impl trait, found inherent impl on {def_id:?}"));
1577 let selfty = tcx.type_of(def_id).instantiate_identity().skip_norm_wip();
1578
1579 check_impl_constness(tcx, impl_.constness, &of_trait.trait_ref);
1580
1581 let trait_ref = icx.lowerer().lower_impl_trait_ref(&of_trait.trait_ref, selfty);
1582
1583 ty::ImplTraitHeader {
1584 trait_ref: ty::EarlyBinder::bind(tcx, trait_ref),
1585 safety: of_trait.safety,
1586 polarity: polarity_of_impl(of_trait),
1587 constness: impl_.constness,
1588 }
1589}
1590
1591fn check_impl_constness(
1592 tcx: TyCtxt<'_>,
1593 constness: hir::Constness,
1594 hir_trait_ref: &hir::TraitRef<'_>,
1595) {
1596 if let hir::Constness::NotConst = constness {
1597 return;
1598 }
1599
1600 let Some(trait_def_id) = hir_trait_ref.trait_def_id() else { return };
1601 if tcx.is_const_trait(trait_def_id) {
1602 return;
1603 }
1604
1605 let trait_name = tcx.item_name(trait_def_id).to_string();
1606 let (suggestion, suggestion_pre) = match (trait_def_id.as_local(), tcx.sess.is_nightly_build())
1607 {
1608 (Some(trait_def_id), true) => {
1609 let span = tcx.hir_expect_item(trait_def_id).vis_span;
1610 let span = tcx.sess.source_map().span_extend_while_whitespace(span);
1611
1612 (
1613 Some(span.shrink_to_hi()),
1614 if tcx.features().const_trait_impl() {
1615 ""
1616 } else {
1617 "enable `#![feature(const_trait_impl)]` in your crate and "
1618 },
1619 )
1620 }
1621 (None, _) | (_, false) => (None, ""),
1622 };
1623 tcx.dcx().emit_err(diagnostics::ConstImplForNonConstTrait {
1624 trait_ref_span: hir_trait_ref.path.span,
1625 trait_name,
1626 suggestion,
1627 suggestion_pre,
1628 marking: (),
1629 adding: (),
1630 });
1631}
1632
1633fn polarity_of_impl(of_trait: &hir::TraitImplHeader<'_>) -> ty::ImplPolarity {
1634 match of_trait.polarity {
1635 hir::ImplPolarity::Negative(_) => ty::ImplPolarity::Negative,
1636 hir::ImplPolarity::Positive => ty::ImplPolarity::Positive,
1637 }
1638}
1639
1640fn early_bound_lifetimes_from_generics<'a, 'tcx>(
1646 tcx: TyCtxt<'tcx>,
1647 generics: &'a hir::Generics<'a>,
1648) -> impl Iterator<Item = &'a hir::GenericParam<'a>> {
1649 generics.params.iter().filter(move |param| match param.kind {
1650 GenericParamKind::Lifetime { .. } => !tcx.is_late_bound(param.hir_id),
1651 _ => false,
1652 })
1653}
1654
1655fn compute_sig_of_foreign_fn_decl<'tcx>(
1656 tcx: TyCtxt<'tcx>,
1657 def_id: LocalDefId,
1658 decl: &'tcx hir::FnDecl<'tcx>,
1659 abi: ExternAbi,
1660 safety: hir::Safety,
1661) -> ty::PolyFnSig<'tcx> {
1662 let hir_id = tcx.local_def_id_to_hir_id(def_id);
1663 let fty =
1664 ItemCtxt::new(tcx, def_id).lowerer().lower_fn_ty(hir_id, safety, abi, decl, None, None);
1665
1666 if !tcx.features().simd_ffi() {
1669 let check = |hir_ty: &hir::Ty<'_>, ty: Ty<'_>| {
1670 if ty.is_simd() {
1671 let snip = tcx
1672 .sess
1673 .source_map()
1674 .span_to_snippet(hir_ty.span)
1675 .map_or_else(|_| String::new(), |s| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" `{0}`", s))
})format!(" `{s}`"));
1676 tcx.dcx()
1677 .emit_err(diagnostics::SIMDFFIHighlyExperimental { span: hir_ty.span, snip });
1678 }
1679 };
1680 for (input, ty) in iter::zip(decl.inputs, fty.inputs().skip_binder()) {
1681 check(input, *ty)
1682 }
1683 if let hir::FnRetTy::Return(ty) = decl.output {
1684 check(ty, fty.output().skip_binder())
1685 }
1686 }
1687
1688 fty
1689}
1690
1691fn coroutine_kind(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option<hir::CoroutineKind> {
1692 match tcx.hir_node_by_def_id(def_id) {
1693 Node::Expr(&hir::Expr {
1694 kind:
1695 hir::ExprKind::Closure(&rustc_hir::Closure {
1696 kind: hir::ClosureKind::Coroutine(kind),
1697 ..
1698 }),
1699 ..
1700 }) => Some(kind),
1701 _ => None,
1702 }
1703}
1704
1705fn coroutine_for_closure(tcx: TyCtxt<'_>, def_id: LocalDefId) -> DefId {
1706 let &rustc_hir::Closure { kind: hir::ClosureKind::CoroutineClosure(_), body, .. } =
1707 tcx.hir_node_by_def_id(def_id).expect_closure()
1708 else {
1709 ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!()
1710 };
1711
1712 let &hir::Expr {
1713 kind:
1714 hir::ExprKind::Closure(&rustc_hir::Closure {
1715 def_id,
1716 kind: hir::ClosureKind::Coroutine(_),
1717 ..
1718 }),
1719 ..
1720 } = tcx.hir_body(body).value
1721 else {
1722 ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!()
1723 };
1724
1725 def_id.to_def_id()
1726}
1727
1728fn opaque_ty_origin<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> hir::OpaqueTyOrigin<DefId> {
1729 match tcx.hir_node_by_def_id(def_id).expect_opaque_ty().origin {
1730 hir::OpaqueTyOrigin::FnReturn { parent, in_trait_or_impl } => {
1731 hir::OpaqueTyOrigin::FnReturn { parent: parent.to_def_id(), in_trait_or_impl }
1732 }
1733 hir::OpaqueTyOrigin::AsyncFn { parent, in_trait_or_impl } => {
1734 hir::OpaqueTyOrigin::AsyncFn { parent: parent.to_def_id(), in_trait_or_impl }
1735 }
1736 hir::OpaqueTyOrigin::TyAlias { parent, in_assoc_ty } => {
1737 hir::OpaqueTyOrigin::TyAlias { parent: parent.to_def_id(), in_assoc_ty }
1738 }
1739 }
1740}
1741
1742fn rendered_precise_capturing_args<'tcx>(
1743 tcx: TyCtxt<'tcx>,
1744 def_id: LocalDefId,
1745) -> Option<&'tcx [PreciseCapturingArgKind<Symbol, Symbol>]> {
1746 if let Some(ty::ImplTraitInTraitData::Trait { opaque_def_id, .. }) =
1747 tcx.opt_rpitit_info(def_id.to_def_id())
1748 {
1749 return tcx.rendered_precise_capturing_args(opaque_def_id);
1750 }
1751
1752 tcx.hir_node_by_def_id(def_id).expect_opaque_ty().bounds.iter().find_map(|bound| match bound {
1753 hir::GenericBound::Use(args, ..) => {
1754 Some(&*tcx.arena.alloc_from_iter(args.iter().map(|arg| match arg {
1755 PreciseCapturingArgKind::Lifetime(_) => {
1756 PreciseCapturingArgKind::Lifetime(arg.name())
1757 }
1758 PreciseCapturingArgKind::Param(_) => PreciseCapturingArgKind::Param(arg.name()),
1759 })))
1760 }
1761 _ => None,
1762 })
1763}
1764
1765fn const_param_default<'tcx>(
1766 tcx: TyCtxt<'tcx>,
1767 local_def_id: LocalDefId,
1768) -> ty::EarlyBinder<'tcx, Const<'tcx>> {
1769 let hir::Node::GenericParam(hir::GenericParam {
1770 kind: hir::GenericParamKind::Const { default: Some(default_ct), .. },
1771 ..
1772 }) = tcx.hir_node_by_def_id(local_def_id)
1773 else {
1774 ::rustc_middle::util::bug::span_bug_fmt(tcx.def_span(local_def_id),
format_args!("`const_param_default` expected a generic parameter with a constant"))span_bug!(
1775 tcx.def_span(local_def_id),
1776 "`const_param_default` expected a generic parameter with a constant"
1777 )
1778 };
1779
1780 let icx = ItemCtxt::new(tcx, local_def_id);
1781
1782 let def_id = local_def_id.to_def_id();
1783 let identity_args = ty::GenericArgs::identity_for_item(tcx, tcx.parent(def_id));
1784
1785 let ct = icx.lowerer().lower_const_arg(
1786 default_ct,
1787 tcx.type_of(def_id).instantiate(tcx, identity_args).skip_norm_wip(),
1788 );
1789 ty::EarlyBinder::bind(tcx, ct)
1790}
1791
1792fn anon_const_kind<'tcx>(tcx: TyCtxt<'tcx>, def: LocalDefId) -> ty::AnonConstKind {
1793 if true {
{
match tcx.def_kind(def) {
DefKind::AnonConst => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val,
"DefKind::AnonConst", ::core::option::Option::None);
}
}
};
};debug_assert_matches!(tcx.def_kind(def), DefKind::AnonConst);
1794 let hir_id = tcx.local_def_id_to_hir_id(def);
1795 let parent_node_id = tcx.parent_hir_id(hir_id);
1796 match tcx.hir_node(parent_node_id) {
1797 hir::Node::ConstArg(const_arg) => {
1798 if true {
{
match const_arg.kind {
hir::ConstArgKind::Anon(hir::AnonConst { def_id, .. }) if
*def_id == def => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val,
"hir::ConstArgKind::Anon(hir::AnonConst { def_id, .. }) if *def_id == def",
::core::option::Option::None);
}
}
};
};debug_assert_matches!(const_arg.kind, hir::ConstArgKind::Anon(hir::AnonConst { def_id, .. }) if *def_id == def);
1799 if tcx.features().generic_const_exprs() {
1800 ty::AnonConstKind::GCE
1801 } else if tcx.features().min_generic_const_args() {
1802 ty::AnonConstKind::MCG
1803 } else if let hir::Node::Expr(hir::Expr {
1804 kind: hir::ExprKind::Repeat(_, repeat_count),
1805 ..
1806 }) = tcx.parent_hir_node(parent_node_id)
1807 && repeat_count.hir_id == parent_node_id
1808 {
1809 ty::AnonConstKind::RepeatExprCount
1810 } else {
1811 ty::AnonConstKind::MCG
1812 }
1813 }
1814 hir::Node::Expr(hir::Expr {
1815 kind: hir::ExprKind::ConstBlock(..) | hir::ExprKind::InlineAsm(..),
1816 ..
1817 }) => ty::AnonConstKind::NonTypeSystemInline,
1818 _ => ty::AnonConstKind::NonTypeSystemAnon,
1819 }
1820}
1821
1822{}
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("const_of_item",
"rustc_hir_analysis::collect", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect.rs"),
::tracing_core::__macro_support::Option::Some(1822u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("def_id")
}> =
::tracing::__macro_support::FieldName::new("def_id");
NAME.as_str()
}], ::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
(move ||
{
#[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:
Option<ty::EarlyBinder<'tcx, Const<'tcx>>> = loop {};
return __tracing_attr_fake_return;
}
{
let ct_rhs =
match tcx.hir_node_by_def_id(def_id) {
hir::Node::Item(&hir::Item {
kind: hir::ItemKind::Const(.., ct), .. }) => ct,
hir::Node::TraitItem(&hir::TraitItem {
kind: hir::TraitItemKind::Const(_, ct), .. }) => ct?,
hir::Node::ImplItem(&hir::ImplItem {
kind: hir::ImplItemKind::Const(.., ct), .. }) => ct,
node => {
::rustc_middle::util::bug::span_bug_fmt(tcx.def_span(def_id),
format_args!("`const_of_item` expected a const or assoc const item, got {0:?}",
node))
}
};
let ct_arg =
match ct_rhs {
hir::ConstItemRhs::Direct(ct_arg) => ct_arg,
hir::ConstItemRhs::Body(_) => { return None; }
};
let icx = ItemCtxt::new(tcx, def_id);
let identity_args =
ty::GenericArgs::identity_for_item(tcx, def_id);
let ct =
icx.lowerer().lower_const_arg(ct_arg,
tcx.type_of(def_id.to_def_id()).instantiate(tcx,
identity_args).skip_norm_wip());
if let Err(e) = icx.check_tainted_by_errors() &&
!ct.references_error() {
Some(ty::EarlyBinder::bind(tcx, Const::new_error(tcx, e)))
} else { Some(ty::EarlyBinder::bind(tcx, ct)) }
}
})();
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect.rs:1822",
"rustc_hir_analysis::collect", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/0fc141305da7a8a222f65aef1f1acc739c46282b/compiler/rustc_hir_analysis/src/collect.rs"),
::tracing_core::__macro_support::Option::Some(1822u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::collect"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("return")
}> =
::tracing::__macro_support::FieldName::new("return");
NAME.as_str()
}], ::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};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
x;#[instrument(level = "debug", skip(tcx), ret)]
1823fn const_of_item<'tcx>(
1824 tcx: TyCtxt<'tcx>,
1825 def_id: LocalDefId,
1826) -> Option<ty::EarlyBinder<'tcx, Const<'tcx>>> {
1827 let ct_rhs = match tcx.hir_node_by_def_id(def_id) {
1828 hir::Node::Item(&hir::Item { kind: hir::ItemKind::Const(.., ct), .. }) => ct,
1829 hir::Node::TraitItem(&hir::TraitItem {
1830 kind: hir::TraitItemKind::Const(_, ct), ..
1831 }) => ct?,
1832 hir::Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Const(.., ct), .. }) => ct,
1833 node => {
1834 span_bug!(
1835 tcx.def_span(def_id),
1836 "`const_of_item` expected a const or assoc const item, got {node:?}"
1837 )
1838 }
1839 };
1840 let ct_arg = match ct_rhs {
1841 hir::ConstItemRhs::Direct(ct_arg) => ct_arg,
1842 hir::ConstItemRhs::Body(_) => {
1843 return None;
1844 }
1845 };
1846 let icx = ItemCtxt::new(tcx, def_id);
1847 let identity_args = ty::GenericArgs::identity_for_item(tcx, def_id);
1848 let ct = icx.lowerer().lower_const_arg(
1849 ct_arg,
1850 tcx.type_of(def_id.to_def_id()).instantiate(tcx, identity_args).skip_norm_wip(),
1851 );
1852 if let Err(e) = icx.check_tainted_by_errors()
1853 && !ct.references_error()
1854 {
1855 Some(ty::EarlyBinder::bind(tcx, Const::new_error(tcx, e)))
1856 } else {
1857 Some(ty::EarlyBinder::bind(tcx, ct))
1858 }
1859}