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