1mod bounds;
17mod cmse;
18mod dyn_trait;
19pub mod errors;
20pub mod generics;
21
22use std::assert_matches::assert_matches;
23use std::slice;
24
25use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet};
26use rustc_errors::codes::*;
27use rustc_errors::{
28 Applicability, Diag, DiagCtxtHandle, ErrorGuaranteed, FatalError, struct_span_code_err,
29};
30use rustc_hir::attrs::AttributeKind;
31use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res};
32use rustc_hir::def_id::{DefId, LocalDefId};
33use rustc_hir::{self as hir, AnonConst, GenericArg, GenericArgs, HirId, find_attr};
34use rustc_infer::infer::{InferCtxt, TyCtxtInferExt};
35use rustc_infer::traits::DynCompatibilityViolation;
36use rustc_macros::{TypeFoldable, TypeVisitable};
37use rustc_middle::middle::stability::AllowUnstable;
38use rustc_middle::mir::interpret::LitToConstInput;
39use rustc_middle::ty::print::PrintPolyTraitRefExt as _;
40use rustc_middle::ty::{
41 self, Const, GenericArgKind, GenericArgsRef, GenericParamDefKind, Ty, TyCtxt,
42 TypeSuperFoldable, TypeVisitableExt, TypingMode, Upcast, fold_regions,
43};
44use rustc_middle::{bug, span_bug};
45use rustc_session::lint::builtin::AMBIGUOUS_ASSOCIATED_ITEMS;
46use rustc_session::parse::feature_err;
47use rustc_span::{DUMMY_SP, Ident, Span, kw, sym};
48use rustc_trait_selection::infer::InferCtxtExt;
49use rustc_trait_selection::traits::wf::object_region_bounds;
50use rustc_trait_selection::traits::{self, FulfillmentError};
51use tracing::{debug, instrument};
52
53use crate::check::check_abi;
54use crate::check_c_variadic_abi;
55use crate::errors::{AmbiguousLifetimeBound, BadReturnTypeNotation};
56use crate::hir_ty_lowering::errors::{GenericsArgsErrExtend, prohibit_assoc_item_constraint};
57use crate::hir_ty_lowering::generics::{check_generic_arg_count, lower_generic_args};
58use crate::middle::resolve_bound_vars as rbv;
59
60#[derive(Clone, Copy)]
63pub(crate) enum ImpliedBoundsContext<'tcx> {
64 TraitDef(LocalDefId),
67 TyParam(LocalDefId, &'tcx [hir::WherePredicate<'tcx>]),
69 AssociatedTypeOrImplTrait,
71}
72
73#[derive(Debug)]
75pub struct GenericPathSegment(pub DefId, pub usize);
76
77#[derive(Copy, Clone, Debug)]
78pub enum PredicateFilter {
79 All,
81
82 SelfOnly,
84
85 SelfTraitThatDefines(Ident),
89
90 SelfAndAssociatedTypeBounds,
94
95 ConstIfConst,
97
98 SelfConstIfConst,
100}
101
102#[derive(Debug)]
103pub enum RegionInferReason<'a> {
104 ExplicitObjectLifetime,
106 ObjectLifetimeDefault,
108 Param(&'a ty::GenericParamDef),
110 RegionPredicate,
111 Reference,
112 OutlivesBound,
113}
114
115#[derive(Copy, Clone, TypeFoldable, TypeVisitable, Debug)]
116pub struct InherentAssocCandidate {
117 pub impl_: DefId,
118 pub assoc_item: DefId,
119 pub scope: DefId,
120}
121
122pub trait HirTyLowerer<'tcx> {
127 fn tcx(&self) -> TyCtxt<'tcx>;
128
129 fn dcx(&self) -> DiagCtxtHandle<'_>;
130
131 fn item_def_id(&self) -> LocalDefId;
133
134 fn re_infer(&self, span: Span, reason: RegionInferReason<'_>) -> ty::Region<'tcx>;
136
137 fn ty_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx>;
139
140 fn ct_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Const<'tcx>;
142
143 fn register_trait_ascription_bounds(
144 &self,
145 bounds: Vec<(ty::Clause<'tcx>, Span)>,
146 hir_id: HirId,
147 span: Span,
148 );
149
150 fn probe_ty_param_bounds(
165 &self,
166 span: Span,
167 def_id: LocalDefId,
168 assoc_ident: Ident,
169 ) -> ty::EarlyBinder<'tcx, &'tcx [(ty::Clause<'tcx>, Span)]>;
170
171 fn select_inherent_assoc_candidates(
172 &self,
173 span: Span,
174 self_ty: Ty<'tcx>,
175 candidates: Vec<InherentAssocCandidate>,
176 ) -> (Vec<InherentAssocCandidate>, Vec<FulfillmentError<'tcx>>);
177
178 fn lower_assoc_item_path(
191 &self,
192 span: Span,
193 item_def_id: DefId,
194 item_segment: &hir::PathSegment<'tcx>,
195 poly_trait_ref: ty::PolyTraitRef<'tcx>,
196 ) -> Result<(DefId, GenericArgsRef<'tcx>), ErrorGuaranteed>;
197
198 fn lower_fn_sig(
199 &self,
200 decl: &hir::FnDecl<'tcx>,
201 generics: Option<&hir::Generics<'_>>,
202 hir_id: HirId,
203 hir_ty: Option<&hir::Ty<'_>>,
204 ) -> (Vec<Ty<'tcx>>, Ty<'tcx>);
205
206 fn probe_adt(&self, span: Span, ty: Ty<'tcx>) -> Option<ty::AdtDef<'tcx>>;
213
214 fn record_ty(&self, hir_id: HirId, ty: Ty<'tcx>, span: Span);
216
217 fn infcx(&self) -> Option<&InferCtxt<'tcx>>;
219
220 fn lowerer(&self) -> &dyn HirTyLowerer<'tcx>
225 where
226 Self: Sized,
227 {
228 self
229 }
230
231 fn dyn_compatibility_violations(&self, trait_def_id: DefId) -> Vec<DynCompatibilityViolation>;
234}
235
236enum AssocItemQSelf {
240 Trait(DefId),
241 TyParam(LocalDefId, Span),
242 SelfTyAlias,
243}
244
245impl AssocItemQSelf {
246 fn to_string(&self, tcx: TyCtxt<'_>) -> String {
247 match *self {
248 Self::Trait(def_id) => tcx.def_path_str(def_id),
249 Self::TyParam(def_id, _) => tcx.hir_ty_param_name(def_id).to_string(),
250 Self::SelfTyAlias => kw::SelfUpper.to_string(),
251 }
252 }
253}
254
255#[derive(Debug, Clone, Copy)]
262pub enum FeedConstTy<'a, 'tcx> {
263 Param(DefId, &'a [ty::GenericArg<'tcx>]),
271 No,
273}
274
275#[derive(Debug, Clone, Copy)]
276enum LowerTypeRelativePathMode {
277 Type(PermitVariants),
278 Const,
279}
280
281impl LowerTypeRelativePathMode {
282 fn assoc_tag(self) -> ty::AssocTag {
283 match self {
284 Self::Type(_) => ty::AssocTag::Type,
285 Self::Const => ty::AssocTag::Const,
286 }
287 }
288
289 fn def_kind(self) -> DefKind {
290 match self {
291 Self::Type(_) => DefKind::AssocTy,
292 Self::Const => DefKind::AssocConst,
293 }
294 }
295
296 fn permit_variants(self) -> PermitVariants {
297 match self {
298 Self::Type(permit_variants) => permit_variants,
299 Self::Const => PermitVariants::No,
302 }
303 }
304}
305
306#[derive(Debug, Clone, Copy)]
308pub enum PermitVariants {
309 Yes,
310 No,
311}
312
313#[derive(Debug, Clone, Copy)]
314enum TypeRelativePath<'tcx> {
315 AssocItem(DefId, GenericArgsRef<'tcx>),
316 Variant { adt: Ty<'tcx>, variant_did: DefId },
317 Ctor { ctor_def_id: DefId, args: GenericArgsRef<'tcx> },
318}
319
320#[derive(Copy, Clone, PartialEq, Debug)]
330pub enum ExplicitLateBound {
331 Yes,
332 No,
333}
334
335#[derive(Copy, Clone, PartialEq)]
336pub enum IsMethodCall {
337 Yes,
338 No,
339}
340
341#[derive(Copy, Clone, PartialEq)]
344pub(crate) enum GenericArgPosition {
345 Type,
346 Value, MethodCall,
348}
349
350#[derive(Clone, Copy, Debug, PartialEq)]
354pub(crate) enum OverlappingAsssocItemConstraints {
355 Allowed,
356 Forbidden,
357}
358
359#[derive(Clone, Debug)]
362pub struct GenericArgCountMismatch {
363 pub reported: ErrorGuaranteed,
364 pub invalid_args: Vec<usize>,
366}
367
368#[derive(Clone, Debug)]
371pub struct GenericArgCountResult {
372 pub explicit_late_bound: ExplicitLateBound,
373 pub correct: Result<(), GenericArgCountMismatch>,
374}
375
376pub trait GenericArgsLowerer<'a, 'tcx> {
381 fn args_for_def_id(&mut self, def_id: DefId) -> (Option<&'a GenericArgs<'tcx>>, bool);
382
383 fn provided_kind(
384 &mut self,
385 preceding_args: &[ty::GenericArg<'tcx>],
386 param: &ty::GenericParamDef,
387 arg: &GenericArg<'tcx>,
388 ) -> ty::GenericArg<'tcx>;
389
390 fn inferred_kind(
391 &mut self,
392 preceding_args: &[ty::GenericArg<'tcx>],
393 param: &ty::GenericParamDef,
394 infer_args: bool,
395 ) -> ty::GenericArg<'tcx>;
396}
397
398struct ForbidMCGParamUsesFolder<'tcx> {
399 tcx: TyCtxt<'tcx>,
400 anon_const_def_id: LocalDefId,
401 span: Span,
402 is_self_alias: bool,
403}
404
405impl<'tcx> ForbidMCGParamUsesFolder<'tcx> {
406 fn error(&self) -> ErrorGuaranteed {
407 let msg = if self.is_self_alias {
408 "generic `Self` types are currently not permitted in anonymous constants"
409 } else {
410 "generic parameters may not be used in const operations"
411 };
412 let mut diag = self.tcx.dcx().struct_span_err(self.span, msg);
413 if self.is_self_alias {
414 let anon_const_hir_id: HirId = HirId::make_owner(self.anon_const_def_id);
415 let parent_impl = self.tcx.hir_parent_owner_iter(anon_const_hir_id).find_map(
416 |(_, node)| match node {
417 hir::OwnerNode::Item(hir::Item {
418 kind: hir::ItemKind::Impl(impl_), ..
419 }) => Some(impl_),
420 _ => None,
421 },
422 );
423 if let Some(impl_) = parent_impl {
424 diag.span_note(impl_.self_ty.span, "not a concrete type");
425 }
426 }
427 diag.emit()
428 }
429}
430
431impl<'tcx> ty::TypeFolder<TyCtxt<'tcx>> for ForbidMCGParamUsesFolder<'tcx> {
432 fn cx(&self) -> TyCtxt<'tcx> {
433 self.tcx
434 }
435
436 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
437 if matches!(t.kind(), ty::Param(..)) {
438 return Ty::new_error(self.tcx, self.error());
439 }
440 t.super_fold_with(self)
441 }
442
443 fn fold_const(&mut self, c: Const<'tcx>) -> Const<'tcx> {
444 if matches!(c.kind(), ty::ConstKind::Param(..)) {
445 return Const::new_error(self.tcx, self.error());
446 }
447 c.super_fold_with(self)
448 }
449
450 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
451 if matches!(r.kind(), ty::RegionKind::ReEarlyParam(..) | ty::RegionKind::ReLateParam(..)) {
452 return ty::Region::new_error(self.tcx, self.error());
453 }
454 r
455 }
456}
457
458impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
459 pub fn check_param_res_if_mcg_for_instantiate_value_path(
463 &self,
464 res: Res,
465 span: Span,
466 ) -> Result<(), ErrorGuaranteed> {
467 let tcx = self.tcx();
468 let parent_def_id = self.item_def_id();
469 if let Res::Def(DefKind::ConstParam, _) = res
470 && tcx.def_kind(parent_def_id) == DefKind::AnonConst
471 && let ty::AnonConstKind::MCG = tcx.anon_const_kind(parent_def_id)
472 {
473 let folder = ForbidMCGParamUsesFolder {
474 tcx,
475 anon_const_def_id: parent_def_id,
476 span,
477 is_self_alias: false,
478 };
479 return Err(folder.error());
480 }
481 Ok(())
482 }
483
484 #[must_use = "need to use transformed output"]
487 fn check_param_uses_if_mcg<T>(&self, term: T, span: Span, is_self_alias: bool) -> T
488 where
489 T: ty::TypeFoldable<TyCtxt<'tcx>>,
490 {
491 let tcx = self.tcx();
492 let parent_def_id = self.item_def_id();
493 if tcx.def_kind(parent_def_id) == DefKind::AnonConst
494 && let ty::AnonConstKind::MCG = tcx.anon_const_kind(parent_def_id)
495 && (term.has_param() || term.has_escaping_bound_vars())
497 {
498 let mut folder = ForbidMCGParamUsesFolder {
499 tcx,
500 anon_const_def_id: parent_def_id,
501 span,
502 is_self_alias,
503 };
504 term.fold_with(&mut folder)
505 } else {
506 term
507 }
508 }
509
510 #[instrument(level = "debug", skip(self), ret)]
512 pub fn lower_lifetime(
513 &self,
514 lifetime: &hir::Lifetime,
515 reason: RegionInferReason<'_>,
516 ) -> ty::Region<'tcx> {
517 if let Some(resolved) = self.tcx().named_bound_var(lifetime.hir_id) {
518 let region = self.lower_resolved_lifetime(resolved);
519 self.check_param_uses_if_mcg(region, lifetime.ident.span, false)
520 } else {
521 self.re_infer(lifetime.ident.span, reason)
522 }
523 }
524
525 #[instrument(level = "debug", skip(self), ret)]
527 fn lower_resolved_lifetime(&self, resolved: rbv::ResolvedArg) -> ty::Region<'tcx> {
528 let tcx = self.tcx();
529
530 match resolved {
531 rbv::ResolvedArg::StaticLifetime => tcx.lifetimes.re_static,
532
533 rbv::ResolvedArg::LateBound(debruijn, index, def_id) => {
534 let br = ty::BoundRegion {
535 var: ty::BoundVar::from_u32(index),
536 kind: ty::BoundRegionKind::Named(def_id.to_def_id()),
537 };
538 ty::Region::new_bound(tcx, debruijn, br)
539 }
540
541 rbv::ResolvedArg::EarlyBound(def_id) => {
542 let name = tcx.hir_ty_param_name(def_id);
543 let item_def_id = tcx.hir_ty_param_owner(def_id);
544 let generics = tcx.generics_of(item_def_id);
545 let index = generics.param_def_id_to_index[&def_id.to_def_id()];
546 ty::Region::new_early_param(tcx, ty::EarlyParamRegion { index, name })
547 }
548
549 rbv::ResolvedArg::Free(scope, id) => {
550 ty::Region::new_late_param(
551 tcx,
552 scope.to_def_id(),
553 ty::LateParamRegionKind::Named(id.to_def_id()),
554 )
555
556 }
558
559 rbv::ResolvedArg::Error(guar) => ty::Region::new_error(tcx, guar),
560 }
561 }
562
563 pub fn lower_generic_args_of_path_segment(
564 &self,
565 span: Span,
566 def_id: DefId,
567 item_segment: &hir::PathSegment<'tcx>,
568 ) -> GenericArgsRef<'tcx> {
569 let (args, _) = self.lower_generic_args_of_path(span, def_id, &[], item_segment, None);
570 if let Some(c) = item_segment.args().constraints.first() {
571 prohibit_assoc_item_constraint(self, c, Some((def_id, item_segment, span)));
572 }
573 args
574 }
575
576 #[instrument(level = "debug", skip(self, span), ret)]
611 fn lower_generic_args_of_path(
612 &self,
613 span: Span,
614 def_id: DefId,
615 parent_args: &[ty::GenericArg<'tcx>],
616 segment: &hir::PathSegment<'tcx>,
617 self_ty: Option<Ty<'tcx>>,
618 ) -> (GenericArgsRef<'tcx>, GenericArgCountResult) {
619 let tcx = self.tcx();
624 let generics = tcx.generics_of(def_id);
625 debug!(?generics);
626
627 if generics.has_self {
628 if generics.parent.is_some() {
629 assert!(!parent_args.is_empty())
632 } else {
633 assert!(self_ty.is_some());
635 }
636 } else {
637 assert!(self_ty.is_none());
638 }
639
640 let arg_count = check_generic_arg_count(
641 self,
642 def_id,
643 segment,
644 generics,
645 GenericArgPosition::Type,
646 self_ty.is_some(),
647 );
648
649 if generics.is_own_empty() {
654 return (tcx.mk_args(parent_args), arg_count);
655 }
656
657 struct GenericArgsCtxt<'a, 'tcx> {
658 lowerer: &'a dyn HirTyLowerer<'tcx>,
659 def_id: DefId,
660 generic_args: &'a GenericArgs<'tcx>,
661 span: Span,
662 infer_args: bool,
663 incorrect_args: &'a Result<(), GenericArgCountMismatch>,
664 }
665
666 impl<'a, 'tcx> GenericArgsLowerer<'a, 'tcx> for GenericArgsCtxt<'a, 'tcx> {
667 fn args_for_def_id(&mut self, did: DefId) -> (Option<&'a GenericArgs<'tcx>>, bool) {
668 if did == self.def_id {
669 (Some(self.generic_args), self.infer_args)
670 } else {
671 (None, false)
673 }
674 }
675
676 fn provided_kind(
677 &mut self,
678 preceding_args: &[ty::GenericArg<'tcx>],
679 param: &ty::GenericParamDef,
680 arg: &GenericArg<'tcx>,
681 ) -> ty::GenericArg<'tcx> {
682 let tcx = self.lowerer.tcx();
683
684 if let Err(incorrect) = self.incorrect_args {
685 if incorrect.invalid_args.contains(&(param.index as usize)) {
686 return param.to_error(tcx);
687 }
688 }
689
690 let handle_ty_args = |has_default, ty: &hir::Ty<'tcx>| {
691 if has_default {
692 tcx.check_optional_stability(
693 param.def_id,
694 Some(arg.hir_id()),
695 arg.span(),
696 None,
697 AllowUnstable::No,
698 |_, _| {
699 },
705 );
706 }
707 self.lowerer.lower_ty(ty).into()
708 };
709
710 match (¶m.kind, arg) {
711 (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => {
712 self.lowerer.lower_lifetime(lt, RegionInferReason::Param(param)).into()
713 }
714 (&GenericParamDefKind::Type { has_default, .. }, GenericArg::Type(ty)) => {
715 handle_ty_args(has_default, ty.as_unambig_ty())
717 }
718 (&GenericParamDefKind::Type { has_default, .. }, GenericArg::Infer(inf)) => {
719 handle_ty_args(has_default, &inf.to_ty())
720 }
721 (GenericParamDefKind::Const { .. }, GenericArg::Const(ct)) => self
722 .lowerer
723 .lower_const_arg(
725 ct.as_unambig_ct(),
726 FeedConstTy::Param(param.def_id, preceding_args),
727 )
728 .into(),
729 (&GenericParamDefKind::Const { .. }, GenericArg::Infer(inf)) => {
730 self.lowerer.ct_infer(Some(param), inf.span).into()
731 }
732 (kind, arg) => span_bug!(
733 self.span,
734 "mismatched path argument for kind {kind:?}: found arg {arg:?}"
735 ),
736 }
737 }
738
739 fn inferred_kind(
740 &mut self,
741 preceding_args: &[ty::GenericArg<'tcx>],
742 param: &ty::GenericParamDef,
743 infer_args: bool,
744 ) -> ty::GenericArg<'tcx> {
745 let tcx = self.lowerer.tcx();
746
747 if let Err(incorrect) = self.incorrect_args {
748 if incorrect.invalid_args.contains(&(param.index as usize)) {
749 return param.to_error(tcx);
750 }
751 }
752 match param.kind {
753 GenericParamDefKind::Lifetime => {
754 self.lowerer.re_infer(self.span, RegionInferReason::Param(param)).into()
755 }
756 GenericParamDefKind::Type { has_default, .. } => {
757 if !infer_args && has_default {
758 if let Some(prev) =
760 preceding_args.iter().find_map(|arg| match arg.kind() {
761 GenericArgKind::Type(ty) => ty.error_reported().err(),
762 _ => None,
763 })
764 {
765 return Ty::new_error(tcx, prev).into();
767 }
768 tcx.at(self.span)
769 .type_of(param.def_id)
770 .instantiate(tcx, preceding_args)
771 .into()
772 } else if infer_args {
773 self.lowerer.ty_infer(Some(param), self.span).into()
774 } else {
775 Ty::new_misc_error(tcx).into()
777 }
778 }
779 GenericParamDefKind::Const { has_default, .. } => {
780 let ty = tcx
781 .at(self.span)
782 .type_of(param.def_id)
783 .instantiate(tcx, preceding_args);
784 if let Err(guar) = ty.error_reported() {
785 return ty::Const::new_error(tcx, guar).into();
786 }
787 if !infer_args && has_default {
788 tcx.const_param_default(param.def_id)
789 .instantiate(tcx, preceding_args)
790 .into()
791 } else if infer_args {
792 self.lowerer.ct_infer(Some(param), self.span).into()
793 } else {
794 ty::Const::new_misc_error(tcx).into()
796 }
797 }
798 }
799 }
800 }
801
802 let mut args_ctx = GenericArgsCtxt {
803 lowerer: self,
804 def_id,
805 span,
806 generic_args: segment.args(),
807 infer_args: segment.infer_args,
808 incorrect_args: &arg_count.correct,
809 };
810 let args = lower_generic_args(
811 self,
812 def_id,
813 parent_args,
814 self_ty.is_some(),
815 self_ty,
816 &arg_count,
817 &mut args_ctx,
818 );
819
820 (args, arg_count)
821 }
822
823 #[instrument(level = "debug", skip(self))]
824 pub fn lower_generic_args_of_assoc_item(
825 &self,
826 span: Span,
827 item_def_id: DefId,
828 item_segment: &hir::PathSegment<'tcx>,
829 parent_args: GenericArgsRef<'tcx>,
830 ) -> GenericArgsRef<'tcx> {
831 let (args, _) =
832 self.lower_generic_args_of_path(span, item_def_id, parent_args, item_segment, None);
833 if let Some(c) = item_segment.args().constraints.first() {
834 prohibit_assoc_item_constraint(self, c, Some((item_def_id, item_segment, span)));
835 }
836 args
837 }
838
839 pub fn lower_impl_trait_ref(
843 &self,
844 trait_ref: &hir::TraitRef<'tcx>,
845 self_ty: Ty<'tcx>,
846 ) -> ty::TraitRef<'tcx> {
847 let [leading_segments @ .., segment] = trait_ref.path.segments else { bug!() };
848
849 let _ = self.prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
850
851 self.lower_mono_trait_ref(
852 trait_ref.path.span,
853 trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise()),
854 self_ty,
855 segment,
856 true,
857 )
858 }
859
860 #[instrument(level = "debug", skip(self, bounds))]
884 pub(crate) fn lower_poly_trait_ref(
885 &self,
886 &hir::PolyTraitRef {
887 bound_generic_params,
888 modifiers: hir::TraitBoundModifiers { constness, polarity },
889 trait_ref,
890 span,
891 }: &hir::PolyTraitRef<'tcx>,
892 self_ty: Ty<'tcx>,
893 bounds: &mut Vec<(ty::Clause<'tcx>, Span)>,
894 predicate_filter: PredicateFilter,
895 overlapping_assoc_item_constraints: OverlappingAsssocItemConstraints,
896 ) -> GenericArgCountResult {
897 let tcx = self.tcx();
898
899 let _ = bound_generic_params;
902
903 let trait_def_id = trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise());
904
905 let transient = match polarity {
910 hir::BoundPolarity::Positive => {
911 tcx.is_lang_item(trait_def_id, hir::LangItem::PointeeSized)
917 }
918 hir::BoundPolarity::Negative(_) => false,
919 hir::BoundPolarity::Maybe(_) => {
920 self.require_bound_to_relax_default_trait(trait_ref, span);
921 true
922 }
923 };
924 let bounds = if transient { &mut Vec::new() } else { bounds };
925
926 let polarity = match polarity {
927 hir::BoundPolarity::Positive | hir::BoundPolarity::Maybe(_) => {
928 ty::PredicatePolarity::Positive
929 }
930 hir::BoundPolarity::Negative(_) => ty::PredicatePolarity::Negative,
931 };
932
933 let [leading_segments @ .., segment] = trait_ref.path.segments else { bug!() };
934
935 let _ = self.prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
936 self.report_internal_fn_trait(span, trait_def_id, segment, false);
937
938 let (generic_args, arg_count) = self.lower_generic_args_of_path(
939 trait_ref.path.span,
940 trait_def_id,
941 &[],
942 segment,
943 Some(self_ty),
944 );
945
946 let constraints = segment.args().constraints;
947
948 if transient && (!generic_args[1..].is_empty() || !constraints.is_empty()) {
949 self.dcx()
959 .span_delayed_bug(span, "transient bound should not have args or constraints");
960 }
961
962 let bound_vars = tcx.late_bound_vars(trait_ref.hir_ref_id);
963 debug!(?bound_vars);
964
965 let poly_trait_ref = ty::Binder::bind_with_vars(
966 ty::TraitRef::new_from_args(tcx, trait_def_id, generic_args),
967 bound_vars,
968 );
969
970 debug!(?poly_trait_ref);
971
972 match predicate_filter {
974 PredicateFilter::All
975 | PredicateFilter::SelfOnly
976 | PredicateFilter::SelfTraitThatDefines(..)
977 | PredicateFilter::SelfAndAssociatedTypeBounds => {
978 let bound = poly_trait_ref.map_bound(|trait_ref| {
979 ty::ClauseKind::Trait(ty::TraitPredicate { trait_ref, polarity })
980 });
981 let bound = (bound.upcast(tcx), span);
982 if tcx.is_lang_item(trait_def_id, rustc_hir::LangItem::Sized) {
988 bounds.insert(0, bound);
989 } else {
990 bounds.push(bound);
991 }
992 }
993 PredicateFilter::ConstIfConst | PredicateFilter::SelfConstIfConst => {}
994 }
995
996 if let hir::BoundConstness::Always(span) | hir::BoundConstness::Maybe(span) = constness
997 && !tcx.is_const_trait(trait_def_id)
998 {
999 let (def_span, suggestion, suggestion_pre) =
1000 match (trait_def_id.as_local(), tcx.sess.is_nightly_build()) {
1001 (Some(trait_def_id), true) => {
1002 let span = tcx.hir_expect_item(trait_def_id).vis_span;
1003 let span = tcx.sess.source_map().span_extend_while_whitespace(span);
1004
1005 (
1006 None,
1007 Some(span.shrink_to_hi()),
1008 if self.tcx().features().const_trait_impl() {
1009 ""
1010 } else {
1011 "enable `#![feature(const_trait_impl)]` in your crate and "
1012 },
1013 )
1014 }
1015 (None, _) | (_, false) => (Some(tcx.def_span(trait_def_id)), None, ""),
1016 };
1017 self.dcx().emit_err(crate::errors::ConstBoundForNonConstTrait {
1018 span,
1019 modifier: constness.as_str(),
1020 def_span,
1021 trait_name: tcx.def_path_str(trait_def_id),
1022 suggestion,
1023 suggestion_pre,
1024 });
1025 } else {
1026 match predicate_filter {
1027 PredicateFilter::SelfTraitThatDefines(..) => {}
1029 PredicateFilter::All
1030 | PredicateFilter::SelfOnly
1031 | PredicateFilter::SelfAndAssociatedTypeBounds => {
1032 match constness {
1033 hir::BoundConstness::Always(_) => {
1034 if polarity == ty::PredicatePolarity::Positive {
1035 bounds.push((
1036 poly_trait_ref
1037 .to_host_effect_clause(tcx, ty::BoundConstness::Const),
1038 span,
1039 ));
1040 }
1041 }
1042 hir::BoundConstness::Maybe(_) => {
1043 }
1048 hir::BoundConstness::Never => {}
1049 }
1050 }
1051 PredicateFilter::ConstIfConst | PredicateFilter::SelfConstIfConst => {
1058 match constness {
1059 hir::BoundConstness::Maybe(_) => {
1060 if polarity == ty::PredicatePolarity::Positive {
1061 bounds.push((
1062 poly_trait_ref
1063 .to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
1064 span,
1065 ));
1066 }
1067 }
1068 hir::BoundConstness::Always(_) | hir::BoundConstness::Never => {}
1069 }
1070 }
1071 }
1072 }
1073
1074 let mut dup_constraints = (overlapping_assoc_item_constraints
1075 == OverlappingAsssocItemConstraints::Forbidden)
1076 .then_some(FxIndexMap::default());
1077
1078 for constraint in constraints {
1079 if polarity == ty::PredicatePolarity::Negative {
1083 self.dcx().span_delayed_bug(
1084 constraint.span,
1085 "negative trait bounds should not have assoc item constraints",
1086 );
1087 break;
1088 }
1089
1090 let _: Result<_, ErrorGuaranteed> = self.lower_assoc_item_constraint(
1092 trait_ref.hir_ref_id,
1093 poly_trait_ref,
1094 constraint,
1095 bounds,
1096 dup_constraints.as_mut(),
1097 constraint.span,
1098 predicate_filter,
1099 );
1100 }
1102
1103 arg_count
1104 }
1105
1106 fn lower_mono_trait_ref(
1110 &self,
1111 span: Span,
1112 trait_def_id: DefId,
1113 self_ty: Ty<'tcx>,
1114 trait_segment: &hir::PathSegment<'tcx>,
1115 is_impl: bool,
1116 ) -> ty::TraitRef<'tcx> {
1117 self.report_internal_fn_trait(span, trait_def_id, trait_segment, is_impl);
1118
1119 let (generic_args, _) =
1120 self.lower_generic_args_of_path(span, trait_def_id, &[], trait_segment, Some(self_ty));
1121 if let Some(c) = trait_segment.args().constraints.first() {
1122 prohibit_assoc_item_constraint(self, c, Some((trait_def_id, trait_segment, span)));
1123 }
1124 ty::TraitRef::new_from_args(self.tcx(), trait_def_id, generic_args)
1125 }
1126
1127 fn probe_trait_that_defines_assoc_item(
1128 &self,
1129 trait_def_id: DefId,
1130 assoc_tag: ty::AssocTag,
1131 assoc_ident: Ident,
1132 ) -> bool {
1133 self.tcx()
1134 .associated_items(trait_def_id)
1135 .find_by_ident_and_kind(self.tcx(), assoc_ident, assoc_tag, trait_def_id)
1136 .is_some()
1137 }
1138
1139 fn lower_path_segment(
1140 &self,
1141 span: Span,
1142 did: DefId,
1143 item_segment: &hir::PathSegment<'tcx>,
1144 ) -> Ty<'tcx> {
1145 let tcx = self.tcx();
1146 let args = self.lower_generic_args_of_path_segment(span, did, item_segment);
1147
1148 if let DefKind::TyAlias = tcx.def_kind(did)
1149 && tcx.type_alias_is_lazy(did)
1150 {
1151 let alias_ty = ty::AliasTy::new_from_args(tcx, did, args);
1155 Ty::new_alias(tcx, ty::Free, alias_ty)
1156 } else {
1157 tcx.at(span).type_of(did).instantiate(tcx, args)
1158 }
1159 }
1160
1161 #[instrument(level = "debug", skip_all, ret)]
1169 fn probe_single_ty_param_bound_for_assoc_item(
1170 &self,
1171 ty_param_def_id: LocalDefId,
1172 ty_param_span: Span,
1173 assoc_tag: ty::AssocTag,
1174 assoc_ident: Ident,
1175 span: Span,
1176 ) -> Result<ty::PolyTraitRef<'tcx>, ErrorGuaranteed> {
1177 debug!(?ty_param_def_id, ?assoc_ident, ?span);
1178 let tcx = self.tcx();
1179
1180 let predicates = &self.probe_ty_param_bounds(span, ty_param_def_id, assoc_ident);
1181 debug!("predicates={:#?}", predicates);
1182
1183 self.probe_single_bound_for_assoc_item(
1184 || {
1185 let trait_refs = predicates
1186 .iter_identity_copied()
1187 .filter_map(|(p, _)| Some(p.as_trait_clause()?.map_bound(|t| t.trait_ref)));
1188 traits::transitive_bounds_that_define_assoc_item(tcx, trait_refs, assoc_ident)
1189 },
1190 AssocItemQSelf::TyParam(ty_param_def_id, ty_param_span),
1191 assoc_tag,
1192 assoc_ident,
1193 span,
1194 None,
1195 )
1196 }
1197
1198 #[instrument(level = "debug", skip(self, all_candidates, qself, constraint), ret)]
1204 fn probe_single_bound_for_assoc_item<I>(
1205 &self,
1206 all_candidates: impl Fn() -> I,
1207 qself: AssocItemQSelf,
1208 assoc_tag: ty::AssocTag,
1209 assoc_ident: Ident,
1210 span: Span,
1211 constraint: Option<&hir::AssocItemConstraint<'tcx>>,
1212 ) -> Result<ty::PolyTraitRef<'tcx>, ErrorGuaranteed>
1213 where
1214 I: Iterator<Item = ty::PolyTraitRef<'tcx>>,
1215 {
1216 let tcx = self.tcx();
1217
1218 let mut matching_candidates = all_candidates().filter(|r| {
1219 self.probe_trait_that_defines_assoc_item(r.def_id(), assoc_tag, assoc_ident)
1220 });
1221
1222 let Some(bound) = matching_candidates.next() else {
1223 return Err(self.report_unresolved_assoc_item(
1224 all_candidates,
1225 qself,
1226 assoc_tag,
1227 assoc_ident,
1228 span,
1229 constraint,
1230 ));
1231 };
1232 debug!(?bound);
1233
1234 if let Some(bound2) = matching_candidates.next() {
1235 debug!(?bound2);
1236
1237 let assoc_kind_str = errors::assoc_tag_str(assoc_tag);
1238 let qself_str = qself.to_string(tcx);
1239 let mut err = self.dcx().create_err(crate::errors::AmbiguousAssocItem {
1240 span,
1241 assoc_kind: assoc_kind_str,
1242 assoc_ident,
1243 qself: &qself_str,
1244 });
1245 err.code(
1247 if let Some(constraint) = constraint
1248 && let hir::AssocItemConstraintKind::Equality { .. } = constraint.kind
1249 {
1250 E0222
1251 } else {
1252 E0221
1253 },
1254 );
1255
1256 let mut where_bounds = vec![];
1260 for bound in [bound, bound2].into_iter().chain(matching_candidates) {
1261 let bound_id = bound.def_id();
1262 let bound_span = tcx
1263 .associated_items(bound_id)
1264 .find_by_ident_and_kind(tcx, assoc_ident, assoc_tag, bound_id)
1265 .and_then(|item| tcx.hir_span_if_local(item.def_id));
1266
1267 if let Some(bound_span) = bound_span {
1268 err.span_label(
1269 bound_span,
1270 format!("ambiguous `{assoc_ident}` from `{}`", bound.print_trait_sugared(),),
1271 );
1272 if let Some(constraint) = constraint {
1273 match constraint.kind {
1274 hir::AssocItemConstraintKind::Equality { term } => {
1275 let term: ty::Term<'_> = match term {
1276 hir::Term::Ty(ty) => self.lower_ty(ty).into(),
1277 hir::Term::Const(ct) => {
1278 self.lower_const_arg(ct, FeedConstTy::No).into()
1279 }
1280 };
1281 if term.references_error() {
1282 continue;
1283 }
1284 where_bounds.push(format!(
1286 " T: {trait}::{assoc_ident} = {term}",
1287 trait = bound.print_only_trait_path(),
1288 ));
1289 }
1290 hir::AssocItemConstraintKind::Bound { bounds: _ } => {}
1292 }
1293 } else {
1294 err.span_suggestion_verbose(
1295 span.with_hi(assoc_ident.span.lo()),
1296 "use fully-qualified syntax to disambiguate",
1297 format!("<{qself_str} as {}>::", bound.print_only_trait_path()),
1298 Applicability::MaybeIncorrect,
1299 );
1300 }
1301 } else {
1302 let trait_ =
1303 tcx.short_string(bound.print_only_trait_path(), err.long_ty_path());
1304 err.note(format!(
1305 "associated {assoc_kind_str} `{assoc_ident}` could derive from `{trait_}`",
1306 ));
1307 }
1308 }
1309 if !where_bounds.is_empty() {
1310 err.help(format!(
1311 "consider introducing a new type parameter `T` and adding `where` constraints:\
1312 \n where\n T: {qself_str},\n{}",
1313 where_bounds.join(",\n"),
1314 ));
1315 let reported = err.emit();
1316 return Err(reported);
1317 }
1318 err.emit();
1319 }
1320
1321 Ok(bound)
1322 }
1323
1324 #[instrument(level = "debug", skip_all, ret)]
1351 pub fn lower_type_relative_ty_path(
1352 &self,
1353 self_ty: Ty<'tcx>,
1354 hir_self_ty: &'tcx hir::Ty<'tcx>,
1355 segment: &'tcx hir::PathSegment<'tcx>,
1356 qpath_hir_id: HirId,
1357 span: Span,
1358 permit_variants: PermitVariants,
1359 ) -> Result<(Ty<'tcx>, DefKind, DefId), ErrorGuaranteed> {
1360 let tcx = self.tcx();
1361 match self.lower_type_relative_path(
1362 self_ty,
1363 hir_self_ty,
1364 segment,
1365 qpath_hir_id,
1366 span,
1367 LowerTypeRelativePathMode::Type(permit_variants),
1368 )? {
1369 TypeRelativePath::AssocItem(def_id, args) => {
1370 let alias_ty = ty::AliasTy::new_from_args(tcx, def_id, args);
1371 let ty = Ty::new_alias(tcx, alias_ty.kind(tcx), alias_ty);
1372 let ty = self.check_param_uses_if_mcg(ty, span, false);
1373 Ok((ty, tcx.def_kind(def_id), def_id))
1374 }
1375 TypeRelativePath::Variant { adt, variant_did } => {
1376 let adt = self.check_param_uses_if_mcg(adt, span, false);
1377 Ok((adt, DefKind::Variant, variant_did))
1378 }
1379 TypeRelativePath::Ctor { .. } => {
1380 let e = tcx.dcx().span_err(span, "expected type, found tuple constructor");
1381 Err(e)
1382 }
1383 }
1384 }
1385
1386 #[instrument(level = "debug", skip_all, ret)]
1388 fn lower_type_relative_const_path(
1389 &self,
1390 self_ty: Ty<'tcx>,
1391 hir_self_ty: &'tcx hir::Ty<'tcx>,
1392 segment: &'tcx hir::PathSegment<'tcx>,
1393 qpath_hir_id: HirId,
1394 span: Span,
1395 ) -> Result<Const<'tcx>, ErrorGuaranteed> {
1396 let tcx = self.tcx();
1397 match self.lower_type_relative_path(
1398 self_ty,
1399 hir_self_ty,
1400 segment,
1401 qpath_hir_id,
1402 span,
1403 LowerTypeRelativePathMode::Const,
1404 )? {
1405 TypeRelativePath::AssocItem(def_id, args) => {
1406 if !find_attr!(self.tcx().get_all_attrs(def_id), AttributeKind::TypeConst(_)) {
1407 let mut err = self.dcx().struct_span_err(
1408 span,
1409 "use of trait associated const without `#[type_const]`",
1410 );
1411 err.note("the declaration in the trait must be marked with `#[type_const]`");
1412 return Err(err.emit());
1413 }
1414 let ct = Const::new_unevaluated(tcx, ty::UnevaluatedConst::new(def_id, args));
1415 let ct = self.check_param_uses_if_mcg(ct, span, false);
1416 Ok(ct)
1417 }
1418 TypeRelativePath::Ctor { ctor_def_id, args } => match tcx.def_kind(ctor_def_id) {
1419 DefKind::Ctor(_, CtorKind::Fn) => {
1420 Ok(ty::Const::zero_sized(tcx, Ty::new_fn_def(tcx, ctor_def_id, args)))
1421 }
1422 DefKind::Ctor(ctor_of, CtorKind::Const) => {
1423 Ok(self.construct_const_ctor_value(ctor_def_id, ctor_of, args))
1424 }
1425 _ => unreachable!(),
1426 },
1427 TypeRelativePath::Variant { .. } => {
1430 span_bug!(span, "unexpected variant res for type associated const path")
1431 }
1432 }
1433 }
1434
1435 #[instrument(level = "debug", skip_all, ret)]
1437 fn lower_type_relative_path(
1438 &self,
1439 self_ty: Ty<'tcx>,
1440 hir_self_ty: &'tcx hir::Ty<'tcx>,
1441 segment: &'tcx hir::PathSegment<'tcx>,
1442 qpath_hir_id: HirId,
1443 span: Span,
1444 mode: LowerTypeRelativePathMode,
1445 ) -> Result<TypeRelativePath<'tcx>, ErrorGuaranteed> {
1446 debug!(%self_ty, ?segment.ident);
1447 let tcx = self.tcx();
1448
1449 let mut variant_def_id = None;
1451 if let Some(adt_def) = self.probe_adt(span, self_ty) {
1452 if adt_def.is_enum() {
1453 let variant_def = adt_def
1454 .variants()
1455 .iter()
1456 .find(|vd| tcx.hygienic_eq(segment.ident, vd.ident(tcx), adt_def.did()));
1457 if let Some(variant_def) = variant_def {
1458 if matches!(mode, LowerTypeRelativePathMode::Const)
1461 && let Some((_, ctor_def_id)) = variant_def.ctor
1462 {
1463 tcx.check_stability(variant_def.def_id, Some(qpath_hir_id), span, None);
1464 let _ = self.prohibit_generic_args(
1465 slice::from_ref(segment).iter(),
1466 GenericsArgsErrExtend::EnumVariant {
1467 qself: hir_self_ty,
1468 assoc_segment: segment,
1469 adt_def,
1470 },
1471 );
1472 let ty::Adt(_, enum_args) = self_ty.kind() else { unreachable!() };
1473 return Ok(TypeRelativePath::Ctor { ctor_def_id, args: enum_args });
1474 }
1475 if let PermitVariants::Yes = mode.permit_variants() {
1476 tcx.check_stability(variant_def.def_id, Some(qpath_hir_id), span, None);
1477 let _ = self.prohibit_generic_args(
1478 slice::from_ref(segment).iter(),
1479 GenericsArgsErrExtend::EnumVariant {
1480 qself: hir_self_ty,
1481 assoc_segment: segment,
1482 adt_def,
1483 },
1484 );
1485 return Ok(TypeRelativePath::Variant {
1486 adt: self_ty,
1487 variant_did: variant_def.def_id,
1488 });
1489 } else {
1490 variant_def_id = Some(variant_def.def_id);
1491 }
1492 }
1493 }
1494
1495 if let Some((did, args)) = self.probe_inherent_assoc_item(
1497 segment,
1498 adt_def.did(),
1499 self_ty,
1500 qpath_hir_id,
1501 span,
1502 mode.assoc_tag(),
1503 )? {
1504 return Ok(TypeRelativePath::AssocItem(did, args));
1505 }
1506 }
1507
1508 let (item_def_id, bound) = self.resolve_type_relative_path(
1509 self_ty,
1510 hir_self_ty,
1511 mode.assoc_tag(),
1512 segment,
1513 qpath_hir_id,
1514 span,
1515 variant_def_id,
1516 )?;
1517
1518 let (item_def_id, args) = self.lower_assoc_item_path(span, item_def_id, segment, bound)?;
1519
1520 if let Some(variant_def_id) = variant_def_id {
1521 tcx.node_span_lint(AMBIGUOUS_ASSOCIATED_ITEMS, qpath_hir_id, span, |lint| {
1522 lint.primary_message("ambiguous associated item");
1523 let mut could_refer_to = |kind: DefKind, def_id, also| {
1524 let note_msg = format!(
1525 "`{}` could{} refer to the {} defined here",
1526 segment.ident,
1527 also,
1528 tcx.def_kind_descr(kind, def_id)
1529 );
1530 lint.span_note(tcx.def_span(def_id), note_msg);
1531 };
1532
1533 could_refer_to(DefKind::Variant, variant_def_id, "");
1534 could_refer_to(mode.def_kind(), item_def_id, " also");
1535
1536 lint.span_suggestion(
1537 span,
1538 "use fully-qualified syntax",
1539 format!(
1540 "<{} as {}>::{}",
1541 self_ty,
1542 tcx.item_name(bound.def_id()),
1543 segment.ident
1544 ),
1545 Applicability::MachineApplicable,
1546 );
1547 });
1548 }
1549
1550 Ok(TypeRelativePath::AssocItem(item_def_id, args))
1551 }
1552
1553 fn resolve_type_relative_path(
1555 &self,
1556 self_ty: Ty<'tcx>,
1557 hir_self_ty: &'tcx hir::Ty<'tcx>,
1558 assoc_tag: ty::AssocTag,
1559 segment: &'tcx hir::PathSegment<'tcx>,
1560 qpath_hir_id: HirId,
1561 span: Span,
1562 variant_def_id: Option<DefId>,
1563 ) -> Result<(DefId, ty::PolyTraitRef<'tcx>), ErrorGuaranteed> {
1564 let tcx = self.tcx();
1565
1566 let self_ty_res = match hir_self_ty.kind {
1567 hir::TyKind::Path(hir::QPath::Resolved(_, path)) => path.res,
1568 _ => Res::Err,
1569 };
1570
1571 let bound = match (self_ty.kind(), self_ty_res) {
1573 (_, Res::SelfTyAlias { alias_to: impl_def_id, is_trait_impl: true, .. }) => {
1574 let trait_ref = tcx.impl_trait_ref(impl_def_id);
1577
1578 self.probe_single_bound_for_assoc_item(
1579 || {
1580 let trait_ref = ty::Binder::dummy(trait_ref.instantiate_identity());
1581 traits::supertraits(tcx, trait_ref)
1582 },
1583 AssocItemQSelf::SelfTyAlias,
1584 assoc_tag,
1585 segment.ident,
1586 span,
1587 None,
1588 )?
1589 }
1590 (
1591 &ty::Param(_),
1592 Res::SelfTyParam { trait_: param_did } | Res::Def(DefKind::TyParam, param_did),
1593 ) => self.probe_single_ty_param_bound_for_assoc_item(
1594 param_did.expect_local(),
1595 hir_self_ty.span,
1596 assoc_tag,
1597 segment.ident,
1598 span,
1599 )?,
1600 _ => {
1601 return Err(self.report_unresolved_type_relative_path(
1602 self_ty,
1603 hir_self_ty,
1604 assoc_tag,
1605 segment.ident,
1606 qpath_hir_id,
1607 span,
1608 variant_def_id,
1609 ));
1610 }
1611 };
1612
1613 let assoc_item = self
1614 .probe_assoc_item(segment.ident, assoc_tag, qpath_hir_id, span, bound.def_id())
1615 .expect("failed to find associated item");
1616
1617 Ok((assoc_item.def_id, bound))
1618 }
1619
1620 fn probe_inherent_assoc_item(
1622 &self,
1623 segment: &hir::PathSegment<'tcx>,
1624 adt_did: DefId,
1625 self_ty: Ty<'tcx>,
1626 block: HirId,
1627 span: Span,
1628 assoc_tag: ty::AssocTag,
1629 ) -> Result<Option<(DefId, GenericArgsRef<'tcx>)>, ErrorGuaranteed> {
1630 let tcx = self.tcx();
1631
1632 if !tcx.features().inherent_associated_types() {
1633 match assoc_tag {
1634 ty::AssocTag::Type => return Ok(None),
1639 ty::AssocTag::Const => {
1640 return Err(feature_err(
1644 &tcx.sess,
1645 sym::inherent_associated_types,
1646 span,
1647 "inherent associated types are unstable",
1648 )
1649 .emit());
1650 }
1651 ty::AssocTag::Fn => unreachable!(),
1652 }
1653 }
1654
1655 let name = segment.ident;
1656 let candidates: Vec<_> = tcx
1657 .inherent_impls(adt_did)
1658 .iter()
1659 .filter_map(|&impl_| {
1660 let (item, scope) =
1661 self.probe_assoc_item_unchecked(name, assoc_tag, block, impl_)?;
1662 Some(InherentAssocCandidate { impl_, assoc_item: item.def_id, scope })
1663 })
1664 .collect();
1665
1666 if candidates.is_empty() {
1671 return Ok(None);
1672 }
1673
1674 let (applicable_candidates, fulfillment_errors) =
1675 self.select_inherent_assoc_candidates(span, self_ty, candidates.clone());
1676
1677 let InherentAssocCandidate { impl_, assoc_item, scope: def_scope } =
1679 match &applicable_candidates[..] {
1680 &[] => Err(self.report_unresolved_inherent_assoc_item(
1681 name,
1682 self_ty,
1683 candidates,
1684 fulfillment_errors,
1685 span,
1686 assoc_tag,
1687 )),
1688
1689 &[applicable_candidate] => Ok(applicable_candidate),
1690
1691 &[_, ..] => Err(self.report_ambiguous_inherent_assoc_item(
1692 name,
1693 candidates.into_iter().map(|cand| cand.assoc_item).collect(),
1694 span,
1695 )),
1696 }?;
1697
1698 self.check_assoc_item(assoc_item, name, def_scope, block, span);
1701
1702 let parent_args = ty::GenericArgs::identity_for_item(tcx, impl_);
1706 let args = self.lower_generic_args_of_assoc_item(span, assoc_item, segment, parent_args);
1707 let args = tcx.mk_args_from_iter(
1708 std::iter::once(ty::GenericArg::from(self_ty))
1709 .chain(args.into_iter().skip(parent_args.len())),
1710 );
1711
1712 Ok(Some((assoc_item, args)))
1713 }
1714
1715 fn probe_assoc_item(
1719 &self,
1720 ident: Ident,
1721 assoc_tag: ty::AssocTag,
1722 block: HirId,
1723 span: Span,
1724 scope: DefId,
1725 ) -> Option<ty::AssocItem> {
1726 let (item, scope) = self.probe_assoc_item_unchecked(ident, assoc_tag, block, scope)?;
1727 self.check_assoc_item(item.def_id, ident, scope, block, span);
1728 Some(item)
1729 }
1730
1731 fn probe_assoc_item_unchecked(
1736 &self,
1737 ident: Ident,
1738 assoc_tag: ty::AssocTag,
1739 block: HirId,
1740 scope: DefId,
1741 ) -> Option<(ty::AssocItem, DefId)> {
1742 let tcx = self.tcx();
1743
1744 let (ident, def_scope) = tcx.adjust_ident_and_get_scope(ident, scope, block);
1745 let item = tcx
1749 .associated_items(scope)
1750 .filter_by_name_unhygienic(ident.name)
1751 .find(|i| i.as_tag() == assoc_tag && i.ident(tcx).normalize_to_macros_2_0() == ident)?;
1752
1753 Some((*item, def_scope))
1754 }
1755
1756 fn check_assoc_item(
1758 &self,
1759 item_def_id: DefId,
1760 ident: Ident,
1761 scope: DefId,
1762 block: HirId,
1763 span: Span,
1764 ) {
1765 let tcx = self.tcx();
1766
1767 if !tcx.visibility(item_def_id).is_accessible_from(scope, tcx) {
1768 self.dcx().emit_err(crate::errors::AssocItemIsPrivate {
1769 span,
1770 kind: tcx.def_descr(item_def_id),
1771 name: ident,
1772 defined_here_label: tcx.def_span(item_def_id),
1773 });
1774 }
1775
1776 tcx.check_stability(item_def_id, Some(block), span, None);
1777 }
1778
1779 fn probe_traits_that_match_assoc_ty(
1780 &self,
1781 qself_ty: Ty<'tcx>,
1782 assoc_ident: Ident,
1783 ) -> Vec<String> {
1784 let tcx = self.tcx();
1785
1786 let infcx_;
1789 let infcx = if let Some(infcx) = self.infcx() {
1790 infcx
1791 } else {
1792 assert!(!qself_ty.has_infer());
1793 infcx_ = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
1794 &infcx_
1795 };
1796
1797 tcx.all_traits_including_private()
1798 .filter(|trait_def_id| {
1799 tcx.associated_items(*trait_def_id)
1801 .in_definition_order()
1802 .any(|i| {
1803 i.is_type()
1804 && !i.is_impl_trait_in_trait()
1805 && i.ident(tcx).normalize_to_macros_2_0() == assoc_ident
1806 })
1807 && tcx.visibility(*trait_def_id)
1809 .is_accessible_from(self.item_def_id(), tcx)
1810 && tcx.all_impls(*trait_def_id)
1811 .any(|impl_def_id| {
1812 let header = tcx.impl_trait_header(impl_def_id);
1813 let trait_ref = header.trait_ref.instantiate(
1814 tcx,
1815 infcx.fresh_args_for_item(DUMMY_SP, impl_def_id),
1816 );
1817
1818 let value = fold_regions(tcx, qself_ty, |_, _| tcx.lifetimes.re_erased);
1819 if value.has_escaping_bound_vars() {
1821 return false;
1822 }
1823 infcx
1824 .can_eq(
1825 ty::ParamEnv::empty(),
1826 trait_ref.self_ty(),
1827 value,
1828 ) && header.polarity != ty::ImplPolarity::Negative
1829 })
1830 })
1831 .map(|trait_def_id| tcx.def_path_str(trait_def_id))
1832 .collect()
1833 }
1834
1835 #[instrument(level = "debug", skip_all)]
1837 fn lower_resolved_assoc_ty_path(
1838 &self,
1839 span: Span,
1840 opt_self_ty: Option<Ty<'tcx>>,
1841 item_def_id: DefId,
1842 trait_segment: Option<&hir::PathSegment<'tcx>>,
1843 item_segment: &hir::PathSegment<'tcx>,
1844 ) -> Ty<'tcx> {
1845 match self.lower_resolved_assoc_item_path(
1846 span,
1847 opt_self_ty,
1848 item_def_id,
1849 trait_segment,
1850 item_segment,
1851 ty::AssocTag::Type,
1852 ) {
1853 Ok((item_def_id, item_args)) => {
1854 Ty::new_projection_from_args(self.tcx(), item_def_id, item_args)
1855 }
1856 Err(guar) => Ty::new_error(self.tcx(), guar),
1857 }
1858 }
1859
1860 #[instrument(level = "debug", skip_all)]
1862 fn lower_resolved_assoc_const_path(
1863 &self,
1864 span: Span,
1865 opt_self_ty: Option<Ty<'tcx>>,
1866 item_def_id: DefId,
1867 trait_segment: Option<&hir::PathSegment<'tcx>>,
1868 item_segment: &hir::PathSegment<'tcx>,
1869 ) -> Const<'tcx> {
1870 match self.lower_resolved_assoc_item_path(
1871 span,
1872 opt_self_ty,
1873 item_def_id,
1874 trait_segment,
1875 item_segment,
1876 ty::AssocTag::Const,
1877 ) {
1878 Ok((item_def_id, item_args)) => {
1879 if !find_attr!(self.tcx().get_all_attrs(item_def_id), AttributeKind::TypeConst(_)) {
1880 let mut err = self.dcx().struct_span_err(
1881 span,
1882 "use of `const` in the type system without `#[type_const]`",
1883 );
1884 err.note("the declaration must be marked with `#[type_const]`");
1885 return Const::new_error(self.tcx(), err.emit());
1886 }
1887
1888 let uv = ty::UnevaluatedConst::new(item_def_id, item_args);
1889 Const::new_unevaluated(self.tcx(), uv)
1890 }
1891 Err(guar) => Const::new_error(self.tcx(), guar),
1892 }
1893 }
1894
1895 #[instrument(level = "debug", skip_all)]
1897 fn lower_resolved_assoc_item_path(
1898 &self,
1899 span: Span,
1900 opt_self_ty: Option<Ty<'tcx>>,
1901 item_def_id: DefId,
1902 trait_segment: Option<&hir::PathSegment<'tcx>>,
1903 item_segment: &hir::PathSegment<'tcx>,
1904 assoc_tag: ty::AssocTag,
1905 ) -> Result<(DefId, GenericArgsRef<'tcx>), ErrorGuaranteed> {
1906 let tcx = self.tcx();
1907
1908 let trait_def_id = tcx.parent(item_def_id);
1909 debug!(?trait_def_id);
1910
1911 let Some(self_ty) = opt_self_ty else {
1912 return Err(self.report_missing_self_ty_for_resolved_path(
1913 trait_def_id,
1914 span,
1915 item_segment,
1916 assoc_tag,
1917 ));
1918 };
1919 debug!(?self_ty);
1920
1921 let trait_ref =
1922 self.lower_mono_trait_ref(span, trait_def_id, self_ty, trait_segment.unwrap(), false);
1923 debug!(?trait_ref);
1924
1925 let item_args =
1926 self.lower_generic_args_of_assoc_item(span, item_def_id, item_segment, trait_ref.args);
1927
1928 Ok((item_def_id, item_args))
1929 }
1930
1931 pub fn prohibit_generic_args<'a>(
1932 &self,
1933 segments: impl Iterator<Item = &'a hir::PathSegment<'a>> + Clone,
1934 err_extend: GenericsArgsErrExtend<'a>,
1935 ) -> Result<(), ErrorGuaranteed> {
1936 let args_visitors = segments.clone().flat_map(|segment| segment.args().args);
1937 let mut result = Ok(());
1938 if let Some(_) = args_visitors.clone().next() {
1939 result = Err(self.report_prohibited_generic_args(
1940 segments.clone(),
1941 args_visitors,
1942 err_extend,
1943 ));
1944 }
1945
1946 for segment in segments {
1947 if let Some(c) = segment.args().constraints.first() {
1949 return Err(prohibit_assoc_item_constraint(self, c, None));
1950 }
1951 }
1952
1953 result
1954 }
1955
1956 pub fn probe_generic_path_segments(
1974 &self,
1975 segments: &[hir::PathSegment<'_>],
1976 self_ty: Option<Ty<'tcx>>,
1977 kind: DefKind,
1978 def_id: DefId,
1979 span: Span,
1980 ) -> Vec<GenericPathSegment> {
1981 let tcx = self.tcx();
2027
2028 assert!(!segments.is_empty());
2029 let last = segments.len() - 1;
2030
2031 let mut generic_segments = vec![];
2032
2033 match kind {
2034 DefKind::Ctor(CtorOf::Struct, ..) => {
2036 let generics = tcx.generics_of(def_id);
2039 let generics_def_id = generics.parent.unwrap_or(def_id);
2042 generic_segments.push(GenericPathSegment(generics_def_id, last));
2043 }
2044
2045 DefKind::Ctor(CtorOf::Variant, ..) | DefKind::Variant => {
2047 let (generics_def_id, index) = if let Some(self_ty) = self_ty {
2048 let adt_def = self.probe_adt(span, self_ty).unwrap();
2049 debug_assert!(adt_def.is_enum());
2050 (adt_def.did(), last)
2051 } else if last >= 1 && segments[last - 1].args.is_some() {
2052 let mut def_id = def_id;
2055
2056 if let DefKind::Ctor(..) = kind {
2058 def_id = tcx.parent(def_id);
2059 }
2060
2061 let enum_def_id = tcx.parent(def_id);
2063 (enum_def_id, last - 1)
2064 } else {
2065 let generics = tcx.generics_of(def_id);
2071 (generics.parent.unwrap_or(def_id), last)
2074 };
2075 generic_segments.push(GenericPathSegment(generics_def_id, index));
2076 }
2077
2078 DefKind::Fn | DefKind::Const | DefKind::ConstParam | DefKind::Static { .. } => {
2080 generic_segments.push(GenericPathSegment(def_id, last));
2081 }
2082
2083 DefKind::AssocFn | DefKind::AssocConst => {
2085 if segments.len() >= 2 {
2086 let generics = tcx.generics_of(def_id);
2087 generic_segments.push(GenericPathSegment(generics.parent.unwrap(), last - 1));
2088 }
2089 generic_segments.push(GenericPathSegment(def_id, last));
2090 }
2091
2092 kind => bug!("unexpected definition kind {:?} for {:?}", kind, def_id),
2093 }
2094
2095 debug!(?generic_segments);
2096
2097 generic_segments
2098 }
2099
2100 #[instrument(level = "debug", skip_all)]
2102 pub fn lower_resolved_ty_path(
2103 &self,
2104 opt_self_ty: Option<Ty<'tcx>>,
2105 path: &hir::Path<'tcx>,
2106 hir_id: HirId,
2107 permit_variants: PermitVariants,
2108 ) -> Ty<'tcx> {
2109 debug!(?path.res, ?opt_self_ty, ?path.segments);
2110 let tcx = self.tcx();
2111
2112 let span = path.span;
2113 match path.res {
2114 Res::Def(DefKind::OpaqueTy, did) => {
2115 assert_matches!(tcx.opaque_ty_origin(did), hir::OpaqueTyOrigin::TyAlias { .. });
2117 let [leading_segments @ .., segment] = path.segments else { bug!() };
2118 let _ = self.prohibit_generic_args(
2119 leading_segments.iter(),
2120 GenericsArgsErrExtend::OpaqueTy,
2121 );
2122 let args = self.lower_generic_args_of_path_segment(span, did, segment);
2123 Ty::new_opaque(tcx, did, args)
2124 }
2125 Res::Def(
2126 DefKind::Enum
2127 | DefKind::TyAlias
2128 | DefKind::Struct
2129 | DefKind::Union
2130 | DefKind::ForeignTy,
2131 did,
2132 ) => {
2133 assert_eq!(opt_self_ty, None);
2134 let [leading_segments @ .., segment] = path.segments else { bug!() };
2135 let _ = self
2136 .prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
2137 self.lower_path_segment(span, did, segment)
2138 }
2139 Res::Def(kind @ DefKind::Variant, def_id)
2140 if let PermitVariants::Yes = permit_variants =>
2141 {
2142 assert_eq!(opt_self_ty, None);
2145
2146 let generic_segments =
2147 self.probe_generic_path_segments(path.segments, None, kind, def_id, span);
2148 let indices: FxHashSet<_> =
2149 generic_segments.iter().map(|GenericPathSegment(_, index)| index).collect();
2150 let _ = self.prohibit_generic_args(
2151 path.segments.iter().enumerate().filter_map(|(index, seg)| {
2152 if !indices.contains(&index) { Some(seg) } else { None }
2153 }),
2154 GenericsArgsErrExtend::DefVariant(&path.segments),
2155 );
2156
2157 let &GenericPathSegment(def_id, index) = generic_segments.last().unwrap();
2158 self.lower_path_segment(span, def_id, &path.segments[index])
2159 }
2160 Res::Def(DefKind::TyParam, def_id) => {
2161 assert_eq!(opt_self_ty, None);
2162 let _ = self.prohibit_generic_args(
2163 path.segments.iter(),
2164 GenericsArgsErrExtend::Param(def_id),
2165 );
2166 self.lower_ty_param(hir_id)
2167 }
2168 Res::SelfTyParam { .. } => {
2169 assert_eq!(opt_self_ty, None);
2171 let _ = self.prohibit_generic_args(
2172 path.segments.iter(),
2173 if let [hir::PathSegment { args: Some(args), ident, .. }] = &path.segments {
2174 GenericsArgsErrExtend::SelfTyParam(
2175 ident.span.shrink_to_hi().to(args.span_ext),
2176 )
2177 } else {
2178 GenericsArgsErrExtend::None
2179 },
2180 );
2181 self.check_param_uses_if_mcg(tcx.types.self_param, span, false)
2182 }
2183 Res::SelfTyAlias { alias_to: def_id, .. } => {
2184 assert_eq!(opt_self_ty, None);
2186 let ty = tcx.at(span).type_of(def_id).instantiate_identity();
2188 let _ = self.prohibit_generic_args(
2189 path.segments.iter(),
2190 GenericsArgsErrExtend::SelfTyAlias { def_id, span },
2191 );
2192 self.check_param_uses_if_mcg(ty, span, true)
2193 }
2194 Res::Def(DefKind::AssocTy, def_id) => {
2195 let trait_segment = if let [modules @ .., trait_, _item] = path.segments {
2196 let _ = self.prohibit_generic_args(modules.iter(), GenericsArgsErrExtend::None);
2197 Some(trait_)
2198 } else {
2199 None
2200 };
2201 self.lower_resolved_assoc_ty_path(
2202 span,
2203 opt_self_ty,
2204 def_id,
2205 trait_segment,
2206 path.segments.last().unwrap(),
2207 )
2208 }
2209 Res::PrimTy(prim_ty) => {
2210 assert_eq!(opt_self_ty, None);
2211 let _ = self.prohibit_generic_args(
2212 path.segments.iter(),
2213 GenericsArgsErrExtend::PrimTy(prim_ty),
2214 );
2215 match prim_ty {
2216 hir::PrimTy::Bool => tcx.types.bool,
2217 hir::PrimTy::Char => tcx.types.char,
2218 hir::PrimTy::Int(it) => Ty::new_int(tcx, it),
2219 hir::PrimTy::Uint(uit) => Ty::new_uint(tcx, uit),
2220 hir::PrimTy::Float(ft) => Ty::new_float(tcx, ft),
2221 hir::PrimTy::Str => tcx.types.str_,
2222 }
2223 }
2224 Res::Err => {
2225 let e = self
2226 .tcx()
2227 .dcx()
2228 .span_delayed_bug(path.span, "path with `Res::Err` but no error emitted");
2229 Ty::new_error(tcx, e)
2230 }
2231 Res::Def(..) => {
2232 assert_eq!(
2233 path.segments.get(0).map(|seg| seg.ident.name),
2234 Some(kw::SelfUpper),
2235 "only expected incorrect resolution for `Self`"
2236 );
2237 Ty::new_error(
2238 self.tcx(),
2239 self.dcx().span_delayed_bug(span, "incorrect resolution for `Self`"),
2240 )
2241 }
2242 _ => span_bug!(span, "unexpected resolution: {:?}", path.res),
2243 }
2244 }
2245
2246 pub(crate) fn lower_ty_param(&self, hir_id: HirId) -> Ty<'tcx> {
2251 let tcx = self.tcx();
2252
2253 let ty = match tcx.named_bound_var(hir_id) {
2254 Some(rbv::ResolvedArg::LateBound(debruijn, index, def_id)) => {
2255 let br = ty::BoundTy {
2256 var: ty::BoundVar::from_u32(index),
2257 kind: ty::BoundTyKind::Param(def_id.to_def_id()),
2258 };
2259 Ty::new_bound(tcx, debruijn, br)
2260 }
2261 Some(rbv::ResolvedArg::EarlyBound(def_id)) => {
2262 let item_def_id = tcx.hir_ty_param_owner(def_id);
2263 let generics = tcx.generics_of(item_def_id);
2264 let index = generics.param_def_id_to_index[&def_id.to_def_id()];
2265 Ty::new_param(tcx, index, tcx.hir_ty_param_name(def_id))
2266 }
2267 Some(rbv::ResolvedArg::Error(guar)) => Ty::new_error(tcx, guar),
2268 arg => bug!("unexpected bound var resolution for {hir_id:?}: {arg:?}"),
2269 };
2270 self.check_param_uses_if_mcg(ty, tcx.hir_span(hir_id), false)
2271 }
2272
2273 pub(crate) fn lower_const_param(&self, param_def_id: DefId, path_hir_id: HirId) -> Const<'tcx> {
2278 let tcx = self.tcx();
2279
2280 let ct = match tcx.named_bound_var(path_hir_id) {
2281 Some(rbv::ResolvedArg::EarlyBound(_)) => {
2282 let item_def_id = tcx.parent(param_def_id);
2285 let generics = tcx.generics_of(item_def_id);
2286 let index = generics.param_def_id_to_index[¶m_def_id];
2287 let name = tcx.item_name(param_def_id);
2288 ty::Const::new_param(tcx, ty::ParamConst::new(index, name))
2289 }
2290 Some(rbv::ResolvedArg::LateBound(debruijn, index, _)) => ty::Const::new_bound(
2291 tcx,
2292 debruijn,
2293 ty::BoundConst { var: ty::BoundVar::from_u32(index) },
2294 ),
2295 Some(rbv::ResolvedArg::Error(guar)) => ty::Const::new_error(tcx, guar),
2296 arg => bug!("unexpected bound var resolution for {:?}: {arg:?}", path_hir_id),
2297 };
2298 self.check_param_uses_if_mcg(ct, tcx.hir_span(path_hir_id), false)
2299 }
2300
2301 #[instrument(skip(self), level = "debug")]
2303 pub fn lower_const_arg(
2304 &self,
2305 const_arg: &hir::ConstArg<'tcx>,
2306 feed: FeedConstTy<'_, 'tcx>,
2307 ) -> Const<'tcx> {
2308 let tcx = self.tcx();
2309
2310 if let FeedConstTy::Param(param_def_id, args) = feed
2311 && let hir::ConstArgKind::Anon(anon) = &const_arg.kind
2312 {
2313 let anon_const_type = tcx.type_of(param_def_id).instantiate(tcx, args);
2314
2315 if tcx.features().generic_const_parameter_types()
2324 && (anon_const_type.has_free_regions() || anon_const_type.has_erased_regions())
2325 {
2326 let e = self.dcx().span_err(
2327 const_arg.span(),
2328 "anonymous constants with lifetimes in their type are not yet supported",
2329 );
2330 tcx.feed_anon_const_type(anon.def_id, ty::EarlyBinder::bind(Ty::new_error(tcx, e)));
2331 return ty::Const::new_error(tcx, e);
2332 }
2333 if anon_const_type.has_non_region_infer() {
2337 let e = self.dcx().span_err(
2338 const_arg.span(),
2339 "anonymous constants with inferred types are not yet supported",
2340 );
2341 tcx.feed_anon_const_type(anon.def_id, ty::EarlyBinder::bind(Ty::new_error(tcx, e)));
2342 return ty::Const::new_error(tcx, e);
2343 }
2344 if anon_const_type.has_non_region_param() {
2347 let e = self.dcx().span_err(
2348 const_arg.span(),
2349 "anonymous constants referencing generics are not yet supported",
2350 );
2351 tcx.feed_anon_const_type(anon.def_id, ty::EarlyBinder::bind(Ty::new_error(tcx, e)));
2352 return ty::Const::new_error(tcx, e);
2353 }
2354
2355 tcx.feed_anon_const_type(
2356 anon.def_id,
2357 ty::EarlyBinder::bind(tcx.type_of(param_def_id).instantiate(tcx, args)),
2358 );
2359 }
2360
2361 let hir_id = const_arg.hir_id;
2362 match const_arg.kind {
2363 hir::ConstArgKind::Path(hir::QPath::Resolved(maybe_qself, path)) => {
2364 debug!(?maybe_qself, ?path);
2365 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
2366 self.lower_resolved_const_path(opt_self_ty, path, hir_id)
2367 }
2368 hir::ConstArgKind::Path(hir::QPath::TypeRelative(hir_self_ty, segment)) => {
2369 debug!(?hir_self_ty, ?segment);
2370 let self_ty = self.lower_ty(hir_self_ty);
2371 self.lower_type_relative_const_path(
2372 self_ty,
2373 hir_self_ty,
2374 segment,
2375 hir_id,
2376 const_arg.span(),
2377 )
2378 .unwrap_or_else(|guar| Const::new_error(tcx, guar))
2379 }
2380 hir::ConstArgKind::Struct(qpath, inits) => {
2381 self.lower_const_arg_struct(hir_id, qpath, inits, const_arg.span())
2382 }
2383 hir::ConstArgKind::TupleCall(qpath, args) => {
2384 self.lower_const_arg_tuple_call(hir_id, qpath, args, const_arg.span())
2385 }
2386 hir::ConstArgKind::Anon(anon) => self.lower_const_arg_anon(anon),
2387 hir::ConstArgKind::Infer(span, ()) => self.ct_infer(None, span),
2388 hir::ConstArgKind::Error(_, e) => ty::Const::new_error(tcx, e),
2389 }
2390 }
2391
2392 fn lower_const_arg_tuple_call(
2393 &self,
2394 hir_id: HirId,
2395 qpath: hir::QPath<'tcx>,
2396 args: &'tcx [&'tcx hir::ConstArg<'tcx>],
2397 span: Span,
2398 ) -> Const<'tcx> {
2399 let tcx = self.tcx();
2400
2401 let non_adt_or_variant_res = || {
2402 let e = tcx.dcx().span_err(span, "tuple constructor with invalid base path");
2403 ty::Const::new_error(tcx, e)
2404 };
2405
2406 let ctor_const = match qpath {
2407 hir::QPath::Resolved(maybe_qself, path) => {
2408 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
2409 self.lower_resolved_const_path(opt_self_ty, path, hir_id)
2410 }
2411 hir::QPath::TypeRelative(hir_self_ty, segment) => {
2412 let self_ty = self.lower_ty(hir_self_ty);
2413 match self.lower_type_relative_const_path(
2414 self_ty,
2415 hir_self_ty,
2416 segment,
2417 hir_id,
2418 span,
2419 ) {
2420 Ok(c) => c,
2421 Err(_) => return non_adt_or_variant_res(),
2422 }
2423 }
2424 };
2425
2426 let Some(value) = ctor_const.try_to_value() else {
2427 return non_adt_or_variant_res();
2428 };
2429
2430 let (adt_def, adt_args, variant_did) = match value.ty.kind() {
2431 ty::FnDef(def_id, fn_args)
2432 if let DefKind::Ctor(CtorOf::Variant, _) = tcx.def_kind(*def_id) =>
2433 {
2434 let parent_did = tcx.parent(*def_id);
2435 let enum_did = tcx.parent(parent_did);
2436 (tcx.adt_def(enum_did), fn_args, parent_did)
2437 }
2438 ty::FnDef(def_id, fn_args)
2439 if let DefKind::Ctor(CtorOf::Struct, _) = tcx.def_kind(*def_id) =>
2440 {
2441 let parent_did = tcx.parent(*def_id);
2442 (tcx.adt_def(parent_did), fn_args, parent_did)
2443 }
2444 _ => return non_adt_or_variant_res(),
2445 };
2446
2447 let variant_def = adt_def.variant_with_id(variant_did);
2448 let variant_idx = adt_def.variant_index_with_id(variant_did).as_u32();
2449
2450 if args.len() != variant_def.fields.len() {
2451 let e = tcx.dcx().span_err(
2452 span,
2453 format!(
2454 "tuple constructor has {} arguments but {} were provided",
2455 variant_def.fields.len(),
2456 args.len()
2457 ),
2458 );
2459 return ty::Const::new_error(tcx, e);
2460 }
2461
2462 let fields = variant_def
2463 .fields
2464 .iter()
2465 .zip(args)
2466 .map(|(field_def, arg)| {
2467 self.lower_const_arg(arg, FeedConstTy::Param(field_def.did, adt_args))
2468 })
2469 .collect::<Vec<_>>();
2470
2471 let opt_discr_const = if adt_def.is_enum() {
2472 let valtree = ty::ValTree::from_scalar_int(tcx, variant_idx.into());
2473 Some(ty::Const::new_value(tcx, valtree, tcx.types.u32))
2474 } else {
2475 None
2476 };
2477
2478 let valtree = ty::ValTree::from_branches(tcx, opt_discr_const.into_iter().chain(fields));
2479 let adt_ty = Ty::new_adt(tcx, adt_def, adt_args);
2480 ty::Const::new_value(tcx, valtree, adt_ty)
2481 }
2482
2483 fn lower_const_arg_struct(
2484 &self,
2485 hir_id: HirId,
2486 qpath: hir::QPath<'tcx>,
2487 inits: &'tcx [&'tcx hir::ConstArgExprField<'tcx>],
2488 span: Span,
2489 ) -> Const<'tcx> {
2490 let tcx = self.tcx();
2493
2494 let non_adt_or_variant_res = || {
2495 let e = tcx.dcx().span_err(span, "struct expression with invalid base path");
2496 ty::Const::new_error(tcx, e)
2497 };
2498
2499 let (ty, variant_did) = match qpath {
2500 hir::QPath::Resolved(maybe_qself, path) => {
2501 debug!(?maybe_qself, ?path);
2502 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
2503 let ty =
2504 self.lower_resolved_ty_path(opt_self_ty, path, hir_id, PermitVariants::Yes);
2505 let variant_did = match path.res {
2506 Res::Def(DefKind::Variant | DefKind::Struct, did) => did,
2507 _ => return non_adt_or_variant_res(),
2508 };
2509
2510 (ty, variant_did)
2511 }
2512 hir::QPath::TypeRelative(hir_self_ty, segment) => {
2513 debug!(?hir_self_ty, ?segment);
2514 let self_ty = self.lower_ty(hir_self_ty);
2515 let opt_res = self.lower_type_relative_ty_path(
2516 self_ty,
2517 hir_self_ty,
2518 segment,
2519 hir_id,
2520 span,
2521 PermitVariants::Yes,
2522 );
2523
2524 let (ty, _, res_def_id) = match opt_res {
2525 Ok(r @ (_, DefKind::Variant | DefKind::Struct, _)) => r,
2526 Ok(_) => return non_adt_or_variant_res(),
2527 Err(e) => return ty::Const::new_error(tcx, e),
2528 };
2529
2530 (ty, res_def_id)
2531 }
2532 };
2533
2534 let ty::Adt(adt_def, adt_args) = ty.kind() else { unreachable!() };
2535
2536 let variant_def = adt_def.variant_with_id(variant_did);
2537 let variant_idx = adt_def.variant_index_with_id(variant_did).as_u32();
2538
2539 let fields = variant_def
2540 .fields
2541 .iter()
2542 .map(|field_def| {
2543 let mut init_expr =
2546 inits.iter().filter(|init_expr| init_expr.field.name == field_def.name);
2547
2548 match init_expr.next() {
2549 Some(expr) => {
2550 if let Some(expr) = init_expr.next() {
2551 let e = tcx.dcx().span_err(
2552 expr.span,
2553 format!(
2554 "struct expression with multiple initialisers for `{}`",
2555 field_def.name,
2556 ),
2557 );
2558 return ty::Const::new_error(tcx, e);
2559 }
2560
2561 self.lower_const_arg(expr.expr, FeedConstTy::Param(field_def.did, adt_args))
2562 }
2563 None => {
2564 let e = tcx.dcx().span_err(
2565 span,
2566 format!(
2567 "struct expression with missing field initialiser for `{}`",
2568 field_def.name
2569 ),
2570 );
2571 ty::Const::new_error(tcx, e)
2572 }
2573 }
2574 })
2575 .collect::<Vec<_>>();
2576
2577 let opt_discr_const = if adt_def.is_enum() {
2578 let valtree = ty::ValTree::from_scalar_int(tcx, variant_idx.into());
2579 Some(ty::Const::new_value(tcx, valtree, tcx.types.u32))
2580 } else {
2581 None
2582 };
2583
2584 let valtree = ty::ValTree::from_branches(tcx, opt_discr_const.into_iter().chain(fields));
2585 ty::Const::new_value(tcx, valtree, ty)
2586 }
2587
2588 fn lower_resolved_const_path(
2590 &self,
2591 opt_self_ty: Option<Ty<'tcx>>,
2592 path: &hir::Path<'tcx>,
2593 hir_id: HirId,
2594 ) -> Const<'tcx> {
2595 let tcx = self.tcx();
2596 let span = path.span;
2597 let ct = match path.res {
2598 Res::Def(DefKind::ConstParam, def_id) => {
2599 assert_eq!(opt_self_ty, None);
2600 let _ = self.prohibit_generic_args(
2601 path.segments.iter(),
2602 GenericsArgsErrExtend::Param(def_id),
2603 );
2604 self.lower_const_param(def_id, hir_id)
2605 }
2606 Res::Def(DefKind::Const, did) => {
2607 assert_eq!(opt_self_ty, None);
2608 let [leading_segments @ .., segment] = path.segments else { bug!() };
2609 let _ = self
2610 .prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
2611 let args = self.lower_generic_args_of_path_segment(span, did, segment);
2612 ty::Const::new_unevaluated(tcx, ty::UnevaluatedConst::new(did, args))
2613 }
2614 Res::Def(DefKind::Ctor(ctor_of, CtorKind::Const), did) => {
2615 assert_eq!(opt_self_ty, None);
2616 let [leading_segments @ .., segment] = path.segments else { bug!() };
2617 let _ = self
2618 .prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
2619
2620 let parent_did = tcx.parent(did);
2621 let generics_did = match ctor_of {
2622 CtorOf::Variant => tcx.parent(parent_did),
2623 CtorOf::Struct => parent_did,
2624 };
2625 let args = self.lower_generic_args_of_path_segment(span, generics_did, segment);
2626
2627 self.construct_const_ctor_value(did, ctor_of, args)
2628 }
2629 Res::Def(DefKind::Ctor(_, CtorKind::Fn), did) => {
2630 assert_eq!(opt_self_ty, None);
2631 let [leading_segments @ .., segment] = path.segments else { bug!() };
2632 let _ = self
2633 .prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
2634 let parent_did = tcx.parent(did);
2635 let generics_did = if let DefKind::Ctor(CtorOf::Variant, _) = tcx.def_kind(did) {
2636 tcx.parent(parent_did)
2637 } else {
2638 parent_did
2639 };
2640 let args = self.lower_generic_args_of_path_segment(span, generics_did, segment);
2641 ty::Const::zero_sized(tcx, Ty::new_fn_def(tcx, did, args))
2642 }
2643 Res::Def(DefKind::AssocConst, did) => {
2644 let trait_segment = if let [modules @ .., trait_, _item] = path.segments {
2645 let _ = self.prohibit_generic_args(modules.iter(), GenericsArgsErrExtend::None);
2646 Some(trait_)
2647 } else {
2648 None
2649 };
2650 self.lower_resolved_assoc_const_path(
2651 span,
2652 opt_self_ty,
2653 did,
2654 trait_segment,
2655 path.segments.last().unwrap(),
2656 )
2657 }
2658 Res::Def(DefKind::Static { .. }, _) => {
2659 span_bug!(span, "use of bare `static` ConstArgKind::Path's not yet supported")
2660 }
2661 Res::Def(DefKind::Fn | DefKind::AssocFn, did) => {
2663 self.dcx().span_delayed_bug(span, "function items cannot be used as const args");
2664 let args = self.lower_generic_args_of_path_segment(
2665 span,
2666 did,
2667 path.segments.last().unwrap(),
2668 );
2669 ty::Const::zero_sized(tcx, Ty::new_fn_def(tcx, did, args))
2670 }
2671
2672 res @ (Res::Def(
2675 DefKind::Mod
2676 | DefKind::Enum
2677 | DefKind::Variant
2678 | DefKind::Struct
2679 | DefKind::OpaqueTy
2680 | DefKind::TyAlias
2681 | DefKind::TraitAlias
2682 | DefKind::AssocTy
2683 | DefKind::Union
2684 | DefKind::Trait
2685 | DefKind::ForeignTy
2686 | DefKind::TyParam
2687 | DefKind::Macro(_)
2688 | DefKind::LifetimeParam
2689 | DefKind::Use
2690 | DefKind::ForeignMod
2691 | DefKind::AnonConst
2692 | DefKind::InlineConst
2693 | DefKind::Field
2694 | DefKind::Impl { .. }
2695 | DefKind::Closure
2696 | DefKind::ExternCrate
2697 | DefKind::GlobalAsm
2698 | DefKind::SyntheticCoroutineBody,
2699 _,
2700 )
2701 | Res::PrimTy(_)
2702 | Res::SelfTyParam { .. }
2703 | Res::SelfTyAlias { .. }
2704 | Res::SelfCtor(_)
2705 | Res::Local(_)
2706 | Res::ToolMod
2707 | Res::NonMacroAttr(_)
2708 | Res::Err) => Const::new_error_with_message(
2709 tcx,
2710 span,
2711 format!("invalid Res {res:?} for const path"),
2712 ),
2713 };
2714 self.check_param_uses_if_mcg(ct, span, false)
2715 }
2716
2717 #[instrument(skip(self), level = "debug")]
2719 fn lower_const_arg_anon(&self, anon: &AnonConst) -> Const<'tcx> {
2720 let tcx = self.tcx();
2721
2722 let expr = &tcx.hir_body(anon.body).value;
2723 debug!(?expr);
2724
2725 let ty = tcx.type_of(anon.def_id).instantiate_identity();
2729
2730 match self.try_lower_anon_const_lit(ty, expr) {
2731 Some(v) => v,
2732 None => ty::Const::new_unevaluated(
2733 tcx,
2734 ty::UnevaluatedConst {
2735 def: anon.def_id.to_def_id(),
2736 args: ty::GenericArgs::identity_for_item(tcx, anon.def_id.to_def_id()),
2737 },
2738 ),
2739 }
2740 }
2741
2742 #[instrument(skip(self), level = "debug")]
2743 fn try_lower_anon_const_lit(
2744 &self,
2745 ty: Ty<'tcx>,
2746 expr: &'tcx hir::Expr<'tcx>,
2747 ) -> Option<Const<'tcx>> {
2748 let tcx = self.tcx();
2749
2750 let expr = match &expr.kind {
2753 hir::ExprKind::Block(block, _) if block.stmts.is_empty() && block.expr.is_some() => {
2754 block.expr.as_ref().unwrap()
2755 }
2756 _ => expr,
2757 };
2758
2759 let lit_input = match expr.kind {
2760 hir::ExprKind::Lit(lit) => Some(LitToConstInput { lit: lit.node, ty, neg: false }),
2761 hir::ExprKind::Unary(hir::UnOp::Neg, expr) => match expr.kind {
2762 hir::ExprKind::Lit(lit) => Some(LitToConstInput { lit: lit.node, ty, neg: true }),
2763 _ => None,
2764 },
2765 _ => None,
2766 };
2767
2768 lit_input
2769 .filter(|l| !l.ty.has_aliases())
2772 .map(|l| tcx.at(expr.span).lit_to_const(l))
2773 }
2774
2775 fn lower_delegation_ty(&self, idx: hir::InferDelegationKind) -> Ty<'tcx> {
2776 let delegation_sig = self.tcx().inherit_sig_for_delegation_item(self.item_def_id());
2777 match idx {
2778 hir::InferDelegationKind::Input(idx) => delegation_sig[idx],
2779 hir::InferDelegationKind::Output => *delegation_sig.last().unwrap(),
2780 }
2781 }
2782
2783 #[instrument(level = "debug", skip(self), ret)]
2785 pub fn lower_ty(&self, hir_ty: &hir::Ty<'tcx>) -> Ty<'tcx> {
2786 let tcx = self.tcx();
2787
2788 let result_ty = match &hir_ty.kind {
2789 hir::TyKind::InferDelegation(_, idx) => self.lower_delegation_ty(*idx),
2790 hir::TyKind::Slice(ty) => Ty::new_slice(tcx, self.lower_ty(ty)),
2791 hir::TyKind::Ptr(mt) => Ty::new_ptr(tcx, self.lower_ty(mt.ty), mt.mutbl),
2792 hir::TyKind::Ref(region, mt) => {
2793 let r = self.lower_lifetime(region, RegionInferReason::Reference);
2794 debug!(?r);
2795 let t = self.lower_ty(mt.ty);
2796 Ty::new_ref(tcx, r, t, mt.mutbl)
2797 }
2798 hir::TyKind::Never => tcx.types.never,
2799 hir::TyKind::Tup(fields) => {
2800 Ty::new_tup_from_iter(tcx, fields.iter().map(|t| self.lower_ty(t)))
2801 }
2802 hir::TyKind::FnPtr(bf) => {
2803 check_c_variadic_abi(tcx, bf.decl, bf.abi, hir_ty.span);
2804
2805 Ty::new_fn_ptr(
2806 tcx,
2807 self.lower_fn_ty(hir_ty.hir_id, bf.safety, bf.abi, bf.decl, None, Some(hir_ty)),
2808 )
2809 }
2810 hir::TyKind::UnsafeBinder(binder) => Ty::new_unsafe_binder(
2811 tcx,
2812 ty::Binder::bind_with_vars(
2813 self.lower_ty(binder.inner_ty),
2814 tcx.late_bound_vars(hir_ty.hir_id),
2815 ),
2816 ),
2817 hir::TyKind::TraitObject(bounds, tagged_ptr) => {
2818 let lifetime = tagged_ptr.pointer();
2819 let syntax = tagged_ptr.tag();
2820 self.lower_trait_object_ty(hir_ty.span, hir_ty.hir_id, bounds, lifetime, syntax)
2821 }
2822 hir::TyKind::Path(hir::QPath::Resolved(_, path))
2826 if path.segments.last().and_then(|segment| segment.args).is_some_and(|args| {
2827 matches!(args.parenthesized, hir::GenericArgsParentheses::ReturnTypeNotation)
2828 }) =>
2829 {
2830 let guar = self.dcx().emit_err(BadReturnTypeNotation { span: hir_ty.span });
2831 Ty::new_error(tcx, guar)
2832 }
2833 hir::TyKind::Path(hir::QPath::Resolved(maybe_qself, path)) => {
2834 debug!(?maybe_qself, ?path);
2835 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
2836 self.lower_resolved_ty_path(opt_self_ty, path, hir_ty.hir_id, PermitVariants::No)
2837 }
2838 &hir::TyKind::OpaqueDef(opaque_ty) => {
2839 let in_trait = match opaque_ty.origin {
2843 hir::OpaqueTyOrigin::FnReturn {
2844 parent,
2845 in_trait_or_impl: Some(hir::RpitContext::Trait),
2846 ..
2847 }
2848 | hir::OpaqueTyOrigin::AsyncFn {
2849 parent,
2850 in_trait_or_impl: Some(hir::RpitContext::Trait),
2851 ..
2852 } => Some(parent),
2853 hir::OpaqueTyOrigin::FnReturn {
2854 in_trait_or_impl: None | Some(hir::RpitContext::TraitImpl),
2855 ..
2856 }
2857 | hir::OpaqueTyOrigin::AsyncFn {
2858 in_trait_or_impl: None | Some(hir::RpitContext::TraitImpl),
2859 ..
2860 }
2861 | hir::OpaqueTyOrigin::TyAlias { .. } => None,
2862 };
2863
2864 self.lower_opaque_ty(opaque_ty.def_id, in_trait)
2865 }
2866 hir::TyKind::TraitAscription(hir_bounds) => {
2867 let self_ty = self.ty_infer(None, hir_ty.span);
2870 let mut bounds = Vec::new();
2871 self.lower_bounds(
2872 self_ty,
2873 hir_bounds.iter(),
2874 &mut bounds,
2875 ty::List::empty(),
2876 PredicateFilter::All,
2877 OverlappingAsssocItemConstraints::Allowed,
2878 );
2879 self.add_implicit_sizedness_bounds(
2880 &mut bounds,
2881 self_ty,
2882 hir_bounds,
2883 ImpliedBoundsContext::AssociatedTypeOrImplTrait,
2884 hir_ty.span,
2885 );
2886 self.register_trait_ascription_bounds(bounds, hir_ty.hir_id, hir_ty.span);
2887 self_ty
2888 }
2889 hir::TyKind::Path(hir::QPath::TypeRelative(_, segment))
2893 if segment.args.is_some_and(|args| {
2894 matches!(args.parenthesized, hir::GenericArgsParentheses::ReturnTypeNotation)
2895 }) =>
2896 {
2897 let guar = self.dcx().emit_err(BadReturnTypeNotation { span: hir_ty.span });
2898 Ty::new_error(tcx, guar)
2899 }
2900 hir::TyKind::Path(hir::QPath::TypeRelative(hir_self_ty, segment)) => {
2901 debug!(?hir_self_ty, ?segment);
2902 let self_ty = self.lower_ty(hir_self_ty);
2903 self.lower_type_relative_ty_path(
2904 self_ty,
2905 hir_self_ty,
2906 segment,
2907 hir_ty.hir_id,
2908 hir_ty.span,
2909 PermitVariants::No,
2910 )
2911 .map(|(ty, _, _)| ty)
2912 .unwrap_or_else(|guar| Ty::new_error(tcx, guar))
2913 }
2914 hir::TyKind::Array(ty, length) => {
2915 let length = self.lower_const_arg(length, FeedConstTy::No);
2916 Ty::new_array_with_const_len(tcx, self.lower_ty(ty), length)
2917 }
2918 hir::TyKind::Infer(()) => {
2919 self.ty_infer(None, hir_ty.span)
2924 }
2925 hir::TyKind::Pat(ty, pat) => {
2926 let ty_span = ty.span;
2927 let ty = self.lower_ty(ty);
2928 let pat_ty = match self.lower_pat_ty_pat(ty, ty_span, pat) {
2929 Ok(kind) => Ty::new_pat(tcx, ty, tcx.mk_pat(kind)),
2930 Err(guar) => Ty::new_error(tcx, guar),
2931 };
2932 self.record_ty(pat.hir_id, ty, pat.span);
2933 pat_ty
2934 }
2935 hir::TyKind::Err(guar) => Ty::new_error(tcx, *guar),
2936 };
2937
2938 self.record_ty(hir_ty.hir_id, result_ty, hir_ty.span);
2939 result_ty
2940 }
2941
2942 fn lower_pat_ty_pat(
2943 &self,
2944 ty: Ty<'tcx>,
2945 ty_span: Span,
2946 pat: &hir::TyPat<'tcx>,
2947 ) -> Result<ty::PatternKind<'tcx>, ErrorGuaranteed> {
2948 let tcx = self.tcx();
2949 match pat.kind {
2950 hir::TyPatKind::Range(start, end) => {
2951 match ty.kind() {
2952 ty::Int(_) | ty::Uint(_) | ty::Char => {
2955 let start = self.lower_const_arg(start, FeedConstTy::No);
2956 let end = self.lower_const_arg(end, FeedConstTy::No);
2957 Ok(ty::PatternKind::Range { start, end })
2958 }
2959 _ => Err(self
2960 .dcx()
2961 .span_delayed_bug(ty_span, "invalid base type for range pattern")),
2962 }
2963 }
2964 hir::TyPatKind::NotNull => Ok(ty::PatternKind::NotNull),
2965 hir::TyPatKind::Or(patterns) => {
2966 self.tcx()
2967 .mk_patterns_from_iter(patterns.iter().map(|pat| {
2968 self.lower_pat_ty_pat(ty, ty_span, pat).map(|pat| tcx.mk_pat(pat))
2969 }))
2970 .map(ty::PatternKind::Or)
2971 }
2972 hir::TyPatKind::Err(e) => Err(e),
2973 }
2974 }
2975
2976 #[instrument(level = "debug", skip(self), ret)]
2978 fn lower_opaque_ty(&self, def_id: LocalDefId, in_trait: Option<LocalDefId>) -> Ty<'tcx> {
2979 let tcx = self.tcx();
2980
2981 let lifetimes = tcx.opaque_captured_lifetimes(def_id);
2982 debug!(?lifetimes);
2983
2984 let def_id = if let Some(parent_def_id) = in_trait {
2988 *tcx.associated_types_for_impl_traits_in_associated_fn(parent_def_id.to_def_id())
2989 .iter()
2990 .find(|rpitit| match tcx.opt_rpitit_info(**rpitit) {
2991 Some(ty::ImplTraitInTraitData::Trait { opaque_def_id, .. }) => {
2992 opaque_def_id.expect_local() == def_id
2993 }
2994 _ => unreachable!(),
2995 })
2996 .unwrap()
2997 } else {
2998 def_id.to_def_id()
2999 };
3000
3001 let generics = tcx.generics_of(def_id);
3002 debug!(?generics);
3003
3004 let offset = generics.count() - lifetimes.len();
3008
3009 let args = ty::GenericArgs::for_item(tcx, def_id, |param, _| {
3010 if let Some(i) = (param.index as usize).checked_sub(offset) {
3011 let (lifetime, _) = lifetimes[i];
3012 self.lower_resolved_lifetime(lifetime).into()
3014 } else {
3015 tcx.mk_param_from_def(param)
3016 }
3017 });
3018 debug!(?args);
3019
3020 if in_trait.is_some() {
3021 Ty::new_projection_from_args(tcx, def_id, args)
3022 } else {
3023 Ty::new_opaque(tcx, def_id, args)
3024 }
3025 }
3026
3027 #[instrument(level = "debug", skip(self, hir_id, safety, abi, decl, generics, hir_ty), ret)]
3029 pub fn lower_fn_ty(
3030 &self,
3031 hir_id: HirId,
3032 safety: hir::Safety,
3033 abi: rustc_abi::ExternAbi,
3034 decl: &hir::FnDecl<'tcx>,
3035 generics: Option<&hir::Generics<'_>>,
3036 hir_ty: Option<&hir::Ty<'_>>,
3037 ) -> ty::PolyFnSig<'tcx> {
3038 let tcx = self.tcx();
3039 let bound_vars = tcx.late_bound_vars(hir_id);
3040 debug!(?bound_vars);
3041
3042 let (input_tys, output_ty) = self.lower_fn_sig(decl, generics, hir_id, hir_ty);
3043
3044 debug!(?output_ty);
3045
3046 let fn_ty = tcx.mk_fn_sig(input_tys, output_ty, decl.c_variadic, safety, abi);
3047 let fn_ptr_ty = ty::Binder::bind_with_vars(fn_ty, bound_vars);
3048
3049 if let hir::Node::Ty(hir::Ty { kind: hir::TyKind::FnPtr(fn_ptr_ty), span, .. }) =
3050 tcx.hir_node(hir_id)
3051 {
3052 check_abi(tcx, hir_id, *span, fn_ptr_ty.abi);
3053 }
3054
3055 cmse::validate_cmse_abi(self.tcx(), self.dcx(), hir_id, abi, fn_ptr_ty);
3057
3058 if !fn_ptr_ty.references_error() {
3059 let inputs = fn_ptr_ty.inputs();
3066 let late_bound_in_args =
3067 tcx.collect_constrained_late_bound_regions(inputs.map_bound(|i| i.to_owned()));
3068 let output = fn_ptr_ty.output();
3069 let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(output);
3070
3071 self.validate_late_bound_regions(late_bound_in_args, late_bound_in_ret, |br_name| {
3072 struct_span_code_err!(
3073 self.dcx(),
3074 decl.output.span(),
3075 E0581,
3076 "return type references {}, which is not constrained by the fn input types",
3077 br_name
3078 )
3079 });
3080 }
3081
3082 fn_ptr_ty
3083 }
3084
3085 pub(super) fn suggest_trait_fn_ty_for_impl_fn_infer(
3090 &self,
3091 fn_hir_id: HirId,
3092 arg_idx: Option<usize>,
3093 ) -> Option<Ty<'tcx>> {
3094 let tcx = self.tcx();
3095 let hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), ident, .. }) =
3096 tcx.hir_node(fn_hir_id)
3097 else {
3098 return None;
3099 };
3100 let i = tcx.parent_hir_node(fn_hir_id).expect_item().expect_impl();
3101
3102 let trait_ref = self.lower_impl_trait_ref(&i.of_trait?.trait_ref, self.lower_ty(i.self_ty));
3103
3104 let assoc = tcx.associated_items(trait_ref.def_id).find_by_ident_and_kind(
3105 tcx,
3106 *ident,
3107 ty::AssocTag::Fn,
3108 trait_ref.def_id,
3109 )?;
3110
3111 let fn_sig = tcx.fn_sig(assoc.def_id).instantiate(
3112 tcx,
3113 trait_ref.args.extend_to(tcx, assoc.def_id, |param, _| tcx.mk_param_from_def(param)),
3114 );
3115 let fn_sig = tcx.liberate_late_bound_regions(fn_hir_id.expect_owner().to_def_id(), fn_sig);
3116
3117 Some(if let Some(arg_idx) = arg_idx {
3118 *fn_sig.inputs().get(arg_idx)?
3119 } else {
3120 fn_sig.output()
3121 })
3122 }
3123
3124 #[instrument(level = "trace", skip(self, generate_err))]
3125 fn validate_late_bound_regions<'cx>(
3126 &'cx self,
3127 constrained_regions: FxIndexSet<ty::BoundRegionKind>,
3128 referenced_regions: FxIndexSet<ty::BoundRegionKind>,
3129 generate_err: impl Fn(&str) -> Diag<'cx>,
3130 ) {
3131 for br in referenced_regions.difference(&constrained_regions) {
3132 let br_name = if let Some(name) = br.get_name(self.tcx()) {
3133 format!("lifetime `{name}`")
3134 } else {
3135 "an anonymous lifetime".to_string()
3136 };
3137
3138 let mut err = generate_err(&br_name);
3139
3140 if !br.is_named(self.tcx()) {
3141 err.note(
3148 "lifetimes appearing in an associated or opaque type are not considered constrained",
3149 );
3150 err.note("consider introducing a named lifetime parameter");
3151 }
3152
3153 err.emit();
3154 }
3155 }
3156
3157 #[instrument(level = "debug", skip(self, span), ret)]
3165 fn compute_object_lifetime_bound(
3166 &self,
3167 span: Span,
3168 existential_predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
3169 ) -> Option<ty::Region<'tcx>> {
3171 let tcx = self.tcx();
3172
3173 let derived_region_bounds = object_region_bounds(tcx, existential_predicates);
3176
3177 if derived_region_bounds.is_empty() {
3180 return None;
3181 }
3182
3183 if derived_region_bounds.iter().any(|r| r.is_static()) {
3186 return Some(tcx.lifetimes.re_static);
3187 }
3188
3189 let r = derived_region_bounds[0];
3193 if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
3194 self.dcx().emit_err(AmbiguousLifetimeBound { span });
3195 }
3196 Some(r)
3197 }
3198
3199 fn construct_const_ctor_value(
3200 &self,
3201 ctor_def_id: DefId,
3202 ctor_of: CtorOf,
3203 args: GenericArgsRef<'tcx>,
3204 ) -> Const<'tcx> {
3205 let tcx = self.tcx();
3206 let parent_did = tcx.parent(ctor_def_id);
3207
3208 let adt_def = tcx.adt_def(match ctor_of {
3209 CtorOf::Variant => tcx.parent(parent_did),
3210 CtorOf::Struct => parent_did,
3211 });
3212
3213 let variant_idx = adt_def.variant_index_with_id(parent_did);
3214
3215 let valtree = if adt_def.is_enum() {
3216 let discr = ty::ValTree::from_scalar_int(tcx, variant_idx.as_u32().into());
3217 ty::ValTree::from_branches(tcx, [ty::Const::new_value(tcx, discr, tcx.types.u32)])
3218 } else {
3219 ty::ValTree::zst(tcx)
3220 };
3221
3222 let adt_ty = Ty::new_adt(tcx, adt_def, args);
3223 ty::Const::new_value(tcx, valtree, adt_ty)
3224 }
3225}