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