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