1mod bounds;
17mod cmse;
18mod dyn_compatibility;
19pub mod errors;
20pub mod generics;
21mod lint;
22
23use std::assert_matches::assert_matches;
24use std::slice;
25
26use rustc_ast::TraitObjectSyntax;
27use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet};
28use rustc_errors::codes::*;
29use rustc_errors::{
30 Applicability, Diag, DiagCtxtHandle, ErrorGuaranteed, FatalError, struct_span_code_err,
31};
32use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res};
33use rustc_hir::def_id::{DefId, LocalDefId};
34use rustc_hir::{self as hir, AnonConst, GenericArg, GenericArgs, HirId};
35use rustc_infer::infer::{InferCtxt, TyCtxtInferExt};
36use rustc_infer::traits::DynCompatibilityViolation;
37use rustc_macros::{TypeFoldable, TypeVisitable};
38use rustc_middle::middle::stability::AllowUnstable;
39use rustc_middle::mir::interpret::LitToConstInput;
40use rustc_middle::ty::print::PrintPolyTraitRefExt as _;
41use rustc_middle::ty::{
42 self, Const, GenericArgKind, GenericArgsRef, GenericParamDefKind, Ty, TyCtxt, TypeVisitableExt,
43 TypingMode, Upcast, fold_regions,
44};
45use rustc_middle::{bug, span_bug};
46use rustc_session::lint::builtin::AMBIGUOUS_ASSOCIATED_ITEMS;
47use rustc_session::parse::feature_err;
48use rustc_span::{DUMMY_SP, Ident, Span, kw, sym};
49use rustc_trait_selection::infer::InferCtxtExt;
50use rustc_trait_selection::traits::wf::object_region_bounds;
51use rustc_trait_selection::traits::{self, FulfillmentError};
52use tracing::{debug, instrument};
53
54use crate::check::check_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;
59use crate::require_c_abi_if_c_variadic;
60
61#[derive(Debug)]
63pub struct GenericPathSegment(pub DefId, pub usize);
64
65#[derive(Copy, Clone, Debug)]
66pub enum PredicateFilter {
67 All,
69
70 SelfOnly,
72
73 SelfTraitThatDefines(Ident),
77
78 SelfAndAssociatedTypeBounds,
82
83 ConstIfConst,
85
86 SelfConstIfConst,
88}
89
90#[derive(Debug)]
91pub enum RegionInferReason<'a> {
92 ExplicitObjectLifetime,
94 ObjectLifetimeDefault,
96 Param(&'a ty::GenericParamDef),
98 RegionPredicate,
99 Reference,
100 OutlivesBound,
101}
102
103#[derive(Copy, Clone, TypeFoldable, TypeVisitable, Debug)]
104pub struct InherentAssocCandidate {
105 pub impl_: DefId,
106 pub assoc_item: DefId,
107 pub scope: DefId,
108}
109
110pub trait HirTyLowerer<'tcx> {
115 fn tcx(&self) -> TyCtxt<'tcx>;
116
117 fn dcx(&self) -> DiagCtxtHandle<'_>;
118
119 fn item_def_id(&self) -> LocalDefId;
121
122 fn re_infer(&self, span: Span, reason: RegionInferReason<'_>) -> ty::Region<'tcx>;
124
125 fn ty_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx>;
127
128 fn ct_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Const<'tcx>;
130
131 fn register_trait_ascription_bounds(
132 &self,
133 bounds: Vec<(ty::Clause<'tcx>, Span)>,
134 hir_id: HirId,
135 span: Span,
136 );
137
138 fn probe_ty_param_bounds(
153 &self,
154 span: Span,
155 def_id: LocalDefId,
156 assoc_ident: Ident,
157 ) -> ty::EarlyBinder<'tcx, &'tcx [(ty::Clause<'tcx>, Span)]>;
158
159 fn select_inherent_assoc_candidates(
160 &self,
161 span: Span,
162 self_ty: Ty<'tcx>,
163 candidates: Vec<InherentAssocCandidate>,
164 ) -> (Vec<InherentAssocCandidate>, Vec<FulfillmentError<'tcx>>);
165
166 fn lower_assoc_item_path(
179 &self,
180 span: Span,
181 item_def_id: DefId,
182 item_segment: &hir::PathSegment<'tcx>,
183 poly_trait_ref: ty::PolyTraitRef<'tcx>,
184 ) -> Result<(DefId, GenericArgsRef<'tcx>), ErrorGuaranteed>;
185
186 fn lower_fn_sig(
187 &self,
188 decl: &hir::FnDecl<'tcx>,
189 generics: Option<&hir::Generics<'_>>,
190 hir_id: HirId,
191 hir_ty: Option<&hir::Ty<'_>>,
192 ) -> (Vec<Ty<'tcx>>, Ty<'tcx>);
193
194 fn probe_adt(&self, span: Span, ty: Ty<'tcx>) -> Option<ty::AdtDef<'tcx>>;
201
202 fn record_ty(&self, hir_id: HirId, ty: Ty<'tcx>, span: Span);
204
205 fn infcx(&self) -> Option<&InferCtxt<'tcx>>;
207
208 fn lowerer(&self) -> &dyn HirTyLowerer<'tcx>
213 where
214 Self: Sized,
215 {
216 self
217 }
218
219 fn dyn_compatibility_violations(&self, trait_def_id: DefId) -> Vec<DynCompatibilityViolation>;
222}
223
224enum AssocItemQSelf {
228 Trait(DefId),
229 TyParam(LocalDefId, Span),
230 SelfTyAlias,
231}
232
233impl AssocItemQSelf {
234 fn to_string(&self, tcx: TyCtxt<'_>) -> String {
235 match *self {
236 Self::Trait(def_id) => tcx.def_path_str(def_id),
237 Self::TyParam(def_id, _) => tcx.hir_ty_param_name(def_id).to_string(),
238 Self::SelfTyAlias => kw::SelfUpper.to_string(),
239 }
240 }
241}
242
243#[derive(Debug, Clone, Copy)]
250pub enum FeedConstTy<'a, 'tcx> {
251 Param(DefId, &'a [ty::GenericArg<'tcx>]),
259 No,
261}
262
263#[derive(Debug, Clone, Copy)]
264enum LowerTypeRelativePathMode {
265 Type(PermitVariants),
266 Const,
267}
268
269impl LowerTypeRelativePathMode {
270 fn assoc_tag(self) -> ty::AssocTag {
271 match self {
272 Self::Type(_) => ty::AssocTag::Type,
273 Self::Const => ty::AssocTag::Const,
274 }
275 }
276
277 fn def_kind(self) -> DefKind {
278 match self {
279 Self::Type(_) => DefKind::AssocTy,
280 Self::Const => DefKind::AssocConst,
281 }
282 }
283
284 fn permit_variants(self) -> PermitVariants {
285 match self {
286 Self::Type(permit_variants) => permit_variants,
287 Self::Const => PermitVariants::No,
290 }
291 }
292}
293
294#[derive(Debug, Clone, Copy)]
296pub enum PermitVariants {
297 Yes,
298 No,
299}
300
301#[derive(Debug, Clone, Copy)]
302enum TypeRelativePath<'tcx> {
303 AssocItem(DefId, GenericArgsRef<'tcx>),
304 Variant { adt: Ty<'tcx>, variant_did: DefId },
305}
306
307#[derive(Copy, Clone, PartialEq, Debug)]
317pub enum ExplicitLateBound {
318 Yes,
319 No,
320}
321
322#[derive(Copy, Clone, PartialEq)]
323pub enum IsMethodCall {
324 Yes,
325 No,
326}
327
328#[derive(Copy, Clone, PartialEq)]
331pub(crate) enum GenericArgPosition {
332 Type,
333 Value, MethodCall,
335}
336
337#[derive(Clone, Debug)]
340pub struct GenericArgCountMismatch {
341 pub reported: ErrorGuaranteed,
342 pub invalid_args: Vec<usize>,
344}
345
346#[derive(Clone, Debug)]
349pub struct GenericArgCountResult {
350 pub explicit_late_bound: ExplicitLateBound,
351 pub correct: Result<(), GenericArgCountMismatch>,
352}
353
354pub trait GenericArgsLowerer<'a, 'tcx> {
359 fn args_for_def_id(&mut self, def_id: DefId) -> (Option<&'a GenericArgs<'tcx>>, bool);
360
361 fn provided_kind(
362 &mut self,
363 preceding_args: &[ty::GenericArg<'tcx>],
364 param: &ty::GenericParamDef,
365 arg: &GenericArg<'tcx>,
366 ) -> ty::GenericArg<'tcx>;
367
368 fn inferred_kind(
369 &mut self,
370 preceding_args: &[ty::GenericArg<'tcx>],
371 param: &ty::GenericParamDef,
372 infer_args: bool,
373 ) -> ty::GenericArg<'tcx>;
374}
375
376impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
377 #[instrument(level = "debug", skip(self), ret)]
379 pub fn lower_lifetime(
380 &self,
381 lifetime: &hir::Lifetime,
382 reason: RegionInferReason<'_>,
383 ) -> ty::Region<'tcx> {
384 if let Some(resolved) = self.tcx().named_bound_var(lifetime.hir_id) {
385 self.lower_resolved_lifetime(resolved)
386 } else {
387 self.re_infer(lifetime.ident.span, reason)
388 }
389 }
390
391 #[instrument(level = "debug", skip(self), ret)]
393 pub fn lower_resolved_lifetime(&self, resolved: rbv::ResolvedArg) -> ty::Region<'tcx> {
394 let tcx = self.tcx();
395
396 match resolved {
397 rbv::ResolvedArg::StaticLifetime => tcx.lifetimes.re_static,
398
399 rbv::ResolvedArg::LateBound(debruijn, index, def_id) => {
400 let br = ty::BoundRegion {
401 var: ty::BoundVar::from_u32(index),
402 kind: ty::BoundRegionKind::Named(def_id.to_def_id()),
403 };
404 ty::Region::new_bound(tcx, debruijn, br)
405 }
406
407 rbv::ResolvedArg::EarlyBound(def_id) => {
408 let name = tcx.hir_ty_param_name(def_id);
409 let item_def_id = tcx.hir_ty_param_owner(def_id);
410 let generics = tcx.generics_of(item_def_id);
411 let index = generics.param_def_id_to_index[&def_id.to_def_id()];
412 ty::Region::new_early_param(tcx, ty::EarlyParamRegion { index, name })
413 }
414
415 rbv::ResolvedArg::Free(scope, id) => {
416 ty::Region::new_late_param(
417 tcx,
418 scope.to_def_id(),
419 ty::LateParamRegionKind::Named(id.to_def_id()),
420 )
421
422 }
424
425 rbv::ResolvedArg::Error(guar) => ty::Region::new_error(tcx, guar),
426 }
427 }
428
429 pub fn lower_generic_args_of_path_segment(
430 &self,
431 span: Span,
432 def_id: DefId,
433 item_segment: &hir::PathSegment<'tcx>,
434 ) -> GenericArgsRef<'tcx> {
435 let (args, _) = self.lower_generic_args_of_path(span, def_id, &[], item_segment, None);
436 if let Some(c) = item_segment.args().constraints.first() {
437 prohibit_assoc_item_constraint(self, c, Some((def_id, item_segment, span)));
438 }
439 args
440 }
441
442 #[instrument(level = "debug", skip(self, span), ret)]
477 fn lower_generic_args_of_path(
478 &self,
479 span: Span,
480 def_id: DefId,
481 parent_args: &[ty::GenericArg<'tcx>],
482 segment: &hir::PathSegment<'tcx>,
483 self_ty: Option<Ty<'tcx>>,
484 ) -> (GenericArgsRef<'tcx>, GenericArgCountResult) {
485 let tcx = self.tcx();
490 let generics = tcx.generics_of(def_id);
491 debug!(?generics);
492
493 if generics.has_self {
494 if generics.parent.is_some() {
495 assert!(!parent_args.is_empty())
498 } else {
499 assert!(self_ty.is_some());
501 }
502 } else {
503 assert!(self_ty.is_none());
504 }
505
506 let arg_count = check_generic_arg_count(
507 self,
508 def_id,
509 segment,
510 generics,
511 GenericArgPosition::Type,
512 self_ty.is_some(),
513 );
514
515 if generics.is_own_empty() {
520 return (tcx.mk_args(parent_args), arg_count);
521 }
522
523 struct GenericArgsCtxt<'a, 'tcx> {
524 lowerer: &'a dyn HirTyLowerer<'tcx>,
525 def_id: DefId,
526 generic_args: &'a GenericArgs<'tcx>,
527 span: Span,
528 infer_args: bool,
529 incorrect_args: &'a Result<(), GenericArgCountMismatch>,
530 }
531
532 impl<'a, 'tcx> GenericArgsLowerer<'a, 'tcx> for GenericArgsCtxt<'a, 'tcx> {
533 fn args_for_def_id(&mut self, did: DefId) -> (Option<&'a GenericArgs<'tcx>>, bool) {
534 if did == self.def_id {
535 (Some(self.generic_args), self.infer_args)
536 } else {
537 (None, false)
539 }
540 }
541
542 fn provided_kind(
543 &mut self,
544 preceding_args: &[ty::GenericArg<'tcx>],
545 param: &ty::GenericParamDef,
546 arg: &GenericArg<'tcx>,
547 ) -> ty::GenericArg<'tcx> {
548 let tcx = self.lowerer.tcx();
549
550 if let Err(incorrect) = self.incorrect_args {
551 if incorrect.invalid_args.contains(&(param.index as usize)) {
552 return param.to_error(tcx);
553 }
554 }
555
556 let handle_ty_args = |has_default, ty: &hir::Ty<'tcx>| {
557 if has_default {
558 tcx.check_optional_stability(
559 param.def_id,
560 Some(arg.hir_id()),
561 arg.span(),
562 None,
563 AllowUnstable::No,
564 |_, _| {
565 },
571 );
572 }
573 self.lowerer.lower_ty(ty).into()
574 };
575
576 match (¶m.kind, arg) {
577 (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => {
578 self.lowerer.lower_lifetime(lt, RegionInferReason::Param(param)).into()
579 }
580 (&GenericParamDefKind::Type { has_default, .. }, GenericArg::Type(ty)) => {
581 handle_ty_args(has_default, ty.as_unambig_ty())
583 }
584 (&GenericParamDefKind::Type { has_default, .. }, GenericArg::Infer(inf)) => {
585 handle_ty_args(has_default, &inf.to_ty())
586 }
587 (GenericParamDefKind::Const { .. }, GenericArg::Const(ct)) => self
588 .lowerer
589 .lower_const_arg(
591 ct.as_unambig_ct(),
592 FeedConstTy::Param(param.def_id, preceding_args),
593 )
594 .into(),
595 (&GenericParamDefKind::Const { .. }, GenericArg::Infer(inf)) => {
596 self.lowerer.ct_infer(Some(param), inf.span).into()
597 }
598 (kind, arg) => span_bug!(
599 self.span,
600 "mismatched path argument for kind {kind:?}: found arg {arg:?}"
601 ),
602 }
603 }
604
605 fn inferred_kind(
606 &mut self,
607 preceding_args: &[ty::GenericArg<'tcx>],
608 param: &ty::GenericParamDef,
609 infer_args: bool,
610 ) -> ty::GenericArg<'tcx> {
611 let tcx = self.lowerer.tcx();
612
613 if let Err(incorrect) = self.incorrect_args {
614 if incorrect.invalid_args.contains(&(param.index as usize)) {
615 return param.to_error(tcx);
616 }
617 }
618 match param.kind {
619 GenericParamDefKind::Lifetime => {
620 self.lowerer.re_infer(self.span, RegionInferReason::Param(param)).into()
621 }
622 GenericParamDefKind::Type { has_default, .. } => {
623 if !infer_args && has_default {
624 if let Some(prev) =
626 preceding_args.iter().find_map(|arg| match arg.kind() {
627 GenericArgKind::Type(ty) => ty.error_reported().err(),
628 _ => None,
629 })
630 {
631 return Ty::new_error(tcx, prev).into();
633 }
634 tcx.at(self.span)
635 .type_of(param.def_id)
636 .instantiate(tcx, preceding_args)
637 .into()
638 } else if infer_args {
639 self.lowerer.ty_infer(Some(param), self.span).into()
640 } else {
641 Ty::new_misc_error(tcx).into()
643 }
644 }
645 GenericParamDefKind::Const { has_default, .. } => {
646 let ty = tcx
647 .at(self.span)
648 .type_of(param.def_id)
649 .instantiate(tcx, preceding_args);
650 if let Err(guar) = ty.error_reported() {
651 return ty::Const::new_error(tcx, guar).into();
652 }
653 if !infer_args && has_default {
654 tcx.const_param_default(param.def_id)
655 .instantiate(tcx, preceding_args)
656 .into()
657 } else if infer_args {
658 self.lowerer.ct_infer(Some(param), self.span).into()
659 } else {
660 ty::Const::new_misc_error(tcx).into()
662 }
663 }
664 }
665 }
666 }
667
668 let mut args_ctx = GenericArgsCtxt {
669 lowerer: self,
670 def_id,
671 span,
672 generic_args: segment.args(),
673 infer_args: segment.infer_args,
674 incorrect_args: &arg_count.correct,
675 };
676 let args = lower_generic_args(
677 self,
678 def_id,
679 parent_args,
680 self_ty.is_some(),
681 self_ty,
682 &arg_count,
683 &mut args_ctx,
684 );
685
686 (args, arg_count)
687 }
688
689 #[instrument(level = "debug", skip(self))]
690 pub fn lower_generic_args_of_assoc_item(
691 &self,
692 span: Span,
693 item_def_id: DefId,
694 item_segment: &hir::PathSegment<'tcx>,
695 parent_args: GenericArgsRef<'tcx>,
696 ) -> GenericArgsRef<'tcx> {
697 let (args, _) =
698 self.lower_generic_args_of_path(span, item_def_id, parent_args, item_segment, None);
699 if let Some(c) = item_segment.args().constraints.first() {
700 prohibit_assoc_item_constraint(self, c, Some((item_def_id, item_segment, span)));
701 }
702 args
703 }
704
705 pub fn lower_impl_trait_ref(
709 &self,
710 trait_ref: &hir::TraitRef<'tcx>,
711 self_ty: Ty<'tcx>,
712 ) -> ty::TraitRef<'tcx> {
713 let _ = self.prohibit_generic_args(
714 trait_ref.path.segments.split_last().unwrap().1.iter(),
715 GenericsArgsErrExtend::None,
716 );
717
718 self.lower_mono_trait_ref(
719 trait_ref.path.span,
720 trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise()),
721 self_ty,
722 trait_ref.path.segments.last().unwrap(),
723 true,
724 )
725 }
726
727 #[instrument(level = "debug", skip(self, bounds))]
751 pub(crate) fn lower_poly_trait_ref(
752 &self,
753 poly_trait_ref: &hir::PolyTraitRef<'tcx>,
754 self_ty: Ty<'tcx>,
755 bounds: &mut Vec<(ty::Clause<'tcx>, Span)>,
756 predicate_filter: PredicateFilter,
757 ) -> GenericArgCountResult {
758 let tcx = self.tcx();
759
760 let hir::PolyTraitRef { bound_generic_params: _, modifiers, ref trait_ref, span } =
763 *poly_trait_ref;
764 let hir::TraitBoundModifiers { constness, polarity } = modifiers;
765
766 let trait_def_id = trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise());
767
768 let (polarity, bounds) = match polarity {
773 rustc_ast::BoundPolarity::Positive
774 if tcx.is_lang_item(trait_def_id, hir::LangItem::PointeeSized) =>
775 {
776 (ty::PredicatePolarity::Positive, &mut Vec::new())
782 }
783 rustc_ast::BoundPolarity::Positive => (ty::PredicatePolarity::Positive, bounds),
784 rustc_ast::BoundPolarity::Negative(_) => (ty::PredicatePolarity::Negative, bounds),
785 rustc_ast::BoundPolarity::Maybe(_) => {
786 (ty::PredicatePolarity::Positive, &mut Vec::new())
787 }
788 };
789
790 let trait_segment = trait_ref.path.segments.last().unwrap();
791
792 let _ = self.prohibit_generic_args(
793 trait_ref.path.segments.split_last().unwrap().1.iter(),
794 GenericsArgsErrExtend::None,
795 );
796 self.report_internal_fn_trait(span, trait_def_id, trait_segment, false);
797
798 let (generic_args, arg_count) = self.lower_generic_args_of_path(
799 trait_ref.path.span,
800 trait_def_id,
801 &[],
802 trait_segment,
803 Some(self_ty),
804 );
805
806 let bound_vars = tcx.late_bound_vars(trait_ref.hir_ref_id);
807 debug!(?bound_vars);
808
809 let poly_trait_ref = ty::Binder::bind_with_vars(
810 ty::TraitRef::new_from_args(tcx, trait_def_id, generic_args),
811 bound_vars,
812 );
813
814 debug!(?poly_trait_ref);
815
816 match predicate_filter {
818 PredicateFilter::All
819 | PredicateFilter::SelfOnly
820 | PredicateFilter::SelfTraitThatDefines(..)
821 | PredicateFilter::SelfAndAssociatedTypeBounds => {
822 let bound = poly_trait_ref.map_bound(|trait_ref| {
823 ty::ClauseKind::Trait(ty::TraitPredicate { trait_ref, polarity })
824 });
825 let bound = (bound.upcast(tcx), span);
826 if tcx.is_lang_item(trait_def_id, rustc_hir::LangItem::Sized) {
832 bounds.insert(0, bound);
833 } else {
834 bounds.push(bound);
835 }
836 }
837 PredicateFilter::ConstIfConst | PredicateFilter::SelfConstIfConst => {}
838 }
839
840 if let hir::BoundConstness::Always(span) | hir::BoundConstness::Maybe(span) = constness
841 && !self.tcx().is_const_trait(trait_def_id)
842 {
843 let (def_span, suggestion, suggestion_pre) =
844 match (trait_def_id.is_local(), self.tcx().sess.is_nightly_build()) {
845 (true, true) => (
846 None,
847 Some(tcx.def_span(trait_def_id).shrink_to_lo()),
848 if self.tcx().features().const_trait_impl() {
849 ""
850 } else {
851 "enable `#![feature(const_trait_impl)]` in your crate and "
852 },
853 ),
854 (false, _) | (_, false) => (Some(tcx.def_span(trait_def_id)), None, ""),
855 };
856 self.dcx().emit_err(crate::errors::ConstBoundForNonConstTrait {
857 span,
858 modifier: constness.as_str(),
859 def_span,
860 trait_name: self.tcx().def_path_str(trait_def_id),
861 suggestion_pre,
862 suggestion,
863 });
864 } else {
865 match predicate_filter {
866 PredicateFilter::SelfTraitThatDefines(..) => {}
868 PredicateFilter::All
869 | PredicateFilter::SelfOnly
870 | PredicateFilter::SelfAndAssociatedTypeBounds => {
871 match constness {
872 hir::BoundConstness::Always(_) => {
873 if polarity == ty::PredicatePolarity::Positive {
874 bounds.push((
875 poly_trait_ref
876 .to_host_effect_clause(tcx, ty::BoundConstness::Const),
877 span,
878 ));
879 }
880 }
881 hir::BoundConstness::Maybe(_) => {
882 }
887 hir::BoundConstness::Never => {}
888 }
889 }
890 PredicateFilter::ConstIfConst | PredicateFilter::SelfConstIfConst => {
897 match constness {
898 hir::BoundConstness::Maybe(_) => {
899 if polarity == ty::PredicatePolarity::Positive {
900 bounds.push((
901 poly_trait_ref
902 .to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
903 span,
904 ));
905 }
906 }
907 hir::BoundConstness::Always(_) | hir::BoundConstness::Never => {}
908 }
909 }
910 }
911 }
912
913 let mut dup_constraints = FxIndexMap::default();
914 for constraint in trait_segment.args().constraints {
915 if polarity == ty::PredicatePolarity::Negative {
919 self.dcx().span_delayed_bug(
920 constraint.span,
921 "negative trait bounds should not have assoc item constraints",
922 );
923 break;
924 }
925
926 let _: Result<_, ErrorGuaranteed> = self.lower_assoc_item_constraint(
928 trait_ref.hir_ref_id,
929 poly_trait_ref,
930 constraint,
931 bounds,
932 &mut dup_constraints,
933 constraint.span,
934 predicate_filter,
935 );
936 }
938
939 arg_count
940 }
941
942 fn lower_mono_trait_ref(
946 &self,
947 span: Span,
948 trait_def_id: DefId,
949 self_ty: Ty<'tcx>,
950 trait_segment: &hir::PathSegment<'tcx>,
951 is_impl: bool,
952 ) -> ty::TraitRef<'tcx> {
953 self.report_internal_fn_trait(span, trait_def_id, trait_segment, is_impl);
954
955 let (generic_args, _) =
956 self.lower_generic_args_of_path(span, trait_def_id, &[], trait_segment, Some(self_ty));
957 if let Some(c) = trait_segment.args().constraints.first() {
958 prohibit_assoc_item_constraint(self, c, Some((trait_def_id, trait_segment, span)));
959 }
960 ty::TraitRef::new_from_args(self.tcx(), trait_def_id, generic_args)
961 }
962
963 fn probe_trait_that_defines_assoc_item(
964 &self,
965 trait_def_id: DefId,
966 assoc_tag: ty::AssocTag,
967 assoc_ident: Ident,
968 ) -> bool {
969 self.tcx()
970 .associated_items(trait_def_id)
971 .find_by_ident_and_kind(self.tcx(), assoc_ident, assoc_tag, trait_def_id)
972 .is_some()
973 }
974
975 fn lower_path_segment(
976 &self,
977 span: Span,
978 did: DefId,
979 item_segment: &hir::PathSegment<'tcx>,
980 ) -> Ty<'tcx> {
981 let tcx = self.tcx();
982 let args = self.lower_generic_args_of_path_segment(span, did, item_segment);
983
984 if let DefKind::TyAlias = tcx.def_kind(did)
985 && tcx.type_alias_is_lazy(did)
986 {
987 let alias_ty = ty::AliasTy::new_from_args(tcx, did, args);
991 Ty::new_alias(tcx, ty::Free, alias_ty)
992 } else {
993 tcx.at(span).type_of(did).instantiate(tcx, args)
994 }
995 }
996
997 #[instrument(level = "debug", skip_all, ret)]
1005 fn probe_single_ty_param_bound_for_assoc_item(
1006 &self,
1007 ty_param_def_id: LocalDefId,
1008 ty_param_span: Span,
1009 assoc_tag: ty::AssocTag,
1010 assoc_ident: Ident,
1011 span: Span,
1012 ) -> Result<ty::PolyTraitRef<'tcx>, ErrorGuaranteed> {
1013 debug!(?ty_param_def_id, ?assoc_ident, ?span);
1014 let tcx = self.tcx();
1015
1016 let predicates = &self.probe_ty_param_bounds(span, ty_param_def_id, assoc_ident);
1017 debug!("predicates={:#?}", predicates);
1018
1019 self.probe_single_bound_for_assoc_item(
1020 || {
1021 let trait_refs = predicates
1022 .iter_identity_copied()
1023 .filter_map(|(p, _)| Some(p.as_trait_clause()?.map_bound(|t| t.trait_ref)));
1024 traits::transitive_bounds_that_define_assoc_item(tcx, trait_refs, assoc_ident)
1025 },
1026 AssocItemQSelf::TyParam(ty_param_def_id, ty_param_span),
1027 assoc_tag,
1028 assoc_ident,
1029 span,
1030 None,
1031 )
1032 }
1033
1034 #[instrument(level = "debug", skip(self, all_candidates, qself, constraint), ret)]
1040 fn probe_single_bound_for_assoc_item<I>(
1041 &self,
1042 all_candidates: impl Fn() -> I,
1043 qself: AssocItemQSelf,
1044 assoc_tag: ty::AssocTag,
1045 assoc_ident: Ident,
1046 span: Span,
1047 constraint: Option<&hir::AssocItemConstraint<'tcx>>,
1048 ) -> Result<ty::PolyTraitRef<'tcx>, ErrorGuaranteed>
1049 where
1050 I: Iterator<Item = ty::PolyTraitRef<'tcx>>,
1051 {
1052 let tcx = self.tcx();
1053
1054 let mut matching_candidates = all_candidates().filter(|r| {
1055 self.probe_trait_that_defines_assoc_item(r.def_id(), assoc_tag, assoc_ident)
1056 });
1057
1058 let Some(bound) = matching_candidates.next() else {
1059 return Err(self.report_unresolved_assoc_item(
1060 all_candidates,
1061 qself,
1062 assoc_tag,
1063 assoc_ident,
1064 span,
1065 constraint,
1066 ));
1067 };
1068 debug!(?bound);
1069
1070 if let Some(bound2) = matching_candidates.next() {
1071 debug!(?bound2);
1072
1073 let assoc_kind_str = errors::assoc_tag_str(assoc_tag);
1074 let qself_str = qself.to_string(tcx);
1075 let mut err = self.dcx().create_err(crate::errors::AmbiguousAssocItem {
1076 span,
1077 assoc_kind: assoc_kind_str,
1078 assoc_ident,
1079 qself: &qself_str,
1080 });
1081 err.code(
1083 if let Some(constraint) = constraint
1084 && let hir::AssocItemConstraintKind::Equality { .. } = constraint.kind
1085 {
1086 E0222
1087 } else {
1088 E0221
1089 },
1090 );
1091
1092 let mut where_bounds = vec![];
1096 for bound in [bound, bound2].into_iter().chain(matching_candidates) {
1097 let bound_id = bound.def_id();
1098 let bound_span = tcx
1099 .associated_items(bound_id)
1100 .find_by_ident_and_kind(tcx, assoc_ident, assoc_tag, bound_id)
1101 .and_then(|item| tcx.hir_span_if_local(item.def_id));
1102
1103 if let Some(bound_span) = bound_span {
1104 err.span_label(
1105 bound_span,
1106 format!("ambiguous `{assoc_ident}` from `{}`", bound.print_trait_sugared(),),
1107 );
1108 if let Some(constraint) = constraint {
1109 match constraint.kind {
1110 hir::AssocItemConstraintKind::Equality { term } => {
1111 let term: ty::Term<'_> = match term {
1112 hir::Term::Ty(ty) => self.lower_ty(ty).into(),
1113 hir::Term::Const(ct) => {
1114 self.lower_const_arg(ct, FeedConstTy::No).into()
1115 }
1116 };
1117 if term.references_error() {
1118 continue;
1119 }
1120 where_bounds.push(format!(
1122 " T: {trait}::{assoc_ident} = {term}",
1123 trait = bound.print_only_trait_path(),
1124 ));
1125 }
1126 hir::AssocItemConstraintKind::Bound { bounds: _ } => {}
1128 }
1129 } else {
1130 err.span_suggestion_verbose(
1131 span.with_hi(assoc_ident.span.lo()),
1132 "use fully-qualified syntax to disambiguate",
1133 format!("<{qself_str} as {}>::", bound.print_only_trait_path()),
1134 Applicability::MaybeIncorrect,
1135 );
1136 }
1137 } else {
1138 err.note(format!(
1139 "associated {assoc_kind_str} `{assoc_ident}` could derive from `{}`",
1140 bound.print_only_trait_path(),
1141 ));
1142 }
1143 }
1144 if !where_bounds.is_empty() {
1145 err.help(format!(
1146 "consider introducing a new type parameter `T` and adding `where` constraints:\
1147 \n where\n T: {qself_str},\n{}",
1148 where_bounds.join(",\n"),
1149 ));
1150 let reported = err.emit();
1151 return Err(reported);
1152 }
1153 err.emit();
1154 }
1155
1156 Ok(bound)
1157 }
1158
1159 #[instrument(level = "debug", skip_all, ret)]
1186 pub fn lower_type_relative_ty_path(
1187 &self,
1188 self_ty: Ty<'tcx>,
1189 hir_self_ty: &'tcx hir::Ty<'tcx>,
1190 segment: &'tcx hir::PathSegment<'tcx>,
1191 qpath_hir_id: HirId,
1192 span: Span,
1193 permit_variants: PermitVariants,
1194 ) -> Result<(Ty<'tcx>, DefKind, DefId), ErrorGuaranteed> {
1195 let tcx = self.tcx();
1196 match self.lower_type_relative_path(
1197 self_ty,
1198 hir_self_ty,
1199 segment,
1200 qpath_hir_id,
1201 span,
1202 LowerTypeRelativePathMode::Type(permit_variants),
1203 )? {
1204 TypeRelativePath::AssocItem(def_id, args) => {
1205 let alias_ty = ty::AliasTy::new_from_args(tcx, def_id, args);
1206 let ty = Ty::new_alias(tcx, alias_ty.kind(tcx), alias_ty);
1207 Ok((ty, tcx.def_kind(def_id), def_id))
1208 }
1209 TypeRelativePath::Variant { adt, variant_did } => {
1210 Ok((adt, DefKind::Variant, variant_did))
1211 }
1212 }
1213 }
1214
1215 #[instrument(level = "debug", skip_all, ret)]
1217 fn lower_type_relative_const_path(
1218 &self,
1219 self_ty: Ty<'tcx>,
1220 hir_self_ty: &'tcx hir::Ty<'tcx>,
1221 segment: &'tcx hir::PathSegment<'tcx>,
1222 qpath_hir_id: HirId,
1223 span: Span,
1224 ) -> Result<Const<'tcx>, ErrorGuaranteed> {
1225 let tcx = self.tcx();
1226 let (def_id, args) = match self.lower_type_relative_path(
1227 self_ty,
1228 hir_self_ty,
1229 segment,
1230 qpath_hir_id,
1231 span,
1232 LowerTypeRelativePathMode::Const,
1233 )? {
1234 TypeRelativePath::AssocItem(def_id, args) => {
1235 if !tcx.associated_item(def_id).is_type_const_capable(tcx) {
1236 let mut err = self.dcx().struct_span_err(
1237 span,
1238 "use of trait associated const without `#[type_const]`",
1239 );
1240 err.note("the declaration in the trait must be marked with `#[type_const]`");
1241 return Err(err.emit());
1242 }
1243 (def_id, args)
1244 }
1245 TypeRelativePath::Variant { .. } => {
1248 span_bug!(span, "unexpected variant res for type associated const path")
1249 }
1250 };
1251 Ok(Const::new_unevaluated(tcx, ty::UnevaluatedConst::new(def_id, args)))
1252 }
1253
1254 #[instrument(level = "debug", skip_all, ret)]
1256 fn lower_type_relative_path(
1257 &self,
1258 self_ty: Ty<'tcx>,
1259 hir_self_ty: &'tcx hir::Ty<'tcx>,
1260 segment: &'tcx hir::PathSegment<'tcx>,
1261 qpath_hir_id: HirId,
1262 span: Span,
1263 mode: LowerTypeRelativePathMode,
1264 ) -> Result<TypeRelativePath<'tcx>, ErrorGuaranteed> {
1265 debug!(%self_ty, ?segment.ident);
1266 let tcx = self.tcx();
1267
1268 let mut variant_def_id = None;
1270 if let Some(adt_def) = self.probe_adt(span, self_ty) {
1271 if adt_def.is_enum() {
1272 let variant_def = adt_def
1273 .variants()
1274 .iter()
1275 .find(|vd| tcx.hygienic_eq(segment.ident, vd.ident(tcx), adt_def.did()));
1276 if let Some(variant_def) = variant_def {
1277 if let PermitVariants::Yes = mode.permit_variants() {
1278 tcx.check_stability(variant_def.def_id, Some(qpath_hir_id), span, None);
1279 let _ = self.prohibit_generic_args(
1280 slice::from_ref(segment).iter(),
1281 GenericsArgsErrExtend::EnumVariant {
1282 qself: hir_self_ty,
1283 assoc_segment: segment,
1284 adt_def,
1285 },
1286 );
1287 return Ok(TypeRelativePath::Variant {
1288 adt: self_ty,
1289 variant_did: variant_def.def_id,
1290 });
1291 } else {
1292 variant_def_id = Some(variant_def.def_id);
1293 }
1294 }
1295 }
1296
1297 if let Some((did, args)) = self.probe_inherent_assoc_item(
1299 segment,
1300 adt_def.did(),
1301 self_ty,
1302 qpath_hir_id,
1303 span,
1304 mode.assoc_tag(),
1305 )? {
1306 return Ok(TypeRelativePath::AssocItem(did, args));
1307 }
1308 }
1309
1310 let (item_def_id, bound) = self.resolve_type_relative_path(
1311 self_ty,
1312 hir_self_ty,
1313 mode.assoc_tag(),
1314 segment,
1315 qpath_hir_id,
1316 span,
1317 variant_def_id,
1318 )?;
1319
1320 let (item_def_id, args) = self.lower_assoc_item_path(span, item_def_id, segment, bound)?;
1321
1322 if let Some(variant_def_id) = variant_def_id {
1323 tcx.node_span_lint(AMBIGUOUS_ASSOCIATED_ITEMS, qpath_hir_id, span, |lint| {
1324 lint.primary_message("ambiguous associated item");
1325 let mut could_refer_to = |kind: DefKind, def_id, also| {
1326 let note_msg = format!(
1327 "`{}` could{} refer to the {} defined here",
1328 segment.ident,
1329 also,
1330 tcx.def_kind_descr(kind, def_id)
1331 );
1332 lint.span_note(tcx.def_span(def_id), note_msg);
1333 };
1334
1335 could_refer_to(DefKind::Variant, variant_def_id, "");
1336 could_refer_to(mode.def_kind(), item_def_id, " also");
1337
1338 lint.span_suggestion(
1339 span,
1340 "use fully-qualified syntax",
1341 format!(
1342 "<{} as {}>::{}",
1343 self_ty,
1344 tcx.item_name(bound.def_id()),
1345 segment.ident
1346 ),
1347 Applicability::MachineApplicable,
1348 );
1349 });
1350 }
1351
1352 Ok(TypeRelativePath::AssocItem(item_def_id, args))
1353 }
1354
1355 fn resolve_type_relative_path(
1357 &self,
1358 self_ty: Ty<'tcx>,
1359 hir_self_ty: &'tcx hir::Ty<'tcx>,
1360 assoc_tag: ty::AssocTag,
1361 segment: &'tcx hir::PathSegment<'tcx>,
1362 qpath_hir_id: HirId,
1363 span: Span,
1364 variant_def_id: Option<DefId>,
1365 ) -> Result<(DefId, ty::PolyTraitRef<'tcx>), ErrorGuaranteed> {
1366 let tcx = self.tcx();
1367
1368 let self_ty_res = match hir_self_ty.kind {
1369 hir::TyKind::Path(hir::QPath::Resolved(_, path)) => path.res,
1370 _ => Res::Err,
1371 };
1372
1373 let bound = match (self_ty.kind(), self_ty_res) {
1375 (_, Res::SelfTyAlias { alias_to: impl_def_id, is_trait_impl: true, .. }) => {
1376 let Some(trait_ref) = tcx.impl_trait_ref(impl_def_id) else {
1379 self.dcx().span_bug(span, "expected cycle error");
1381 };
1382
1383 self.probe_single_bound_for_assoc_item(
1384 || {
1385 let trait_ref = ty::Binder::dummy(trait_ref.instantiate_identity());
1386 traits::supertraits(tcx, trait_ref)
1387 },
1388 AssocItemQSelf::SelfTyAlias,
1389 assoc_tag,
1390 segment.ident,
1391 span,
1392 None,
1393 )?
1394 }
1395 (
1396 &ty::Param(_),
1397 Res::SelfTyParam { trait_: param_did } | Res::Def(DefKind::TyParam, param_did),
1398 ) => self.probe_single_ty_param_bound_for_assoc_item(
1399 param_did.expect_local(),
1400 hir_self_ty.span,
1401 assoc_tag,
1402 segment.ident,
1403 span,
1404 )?,
1405 _ => {
1406 return Err(self.report_unresolved_type_relative_path(
1407 self_ty,
1408 hir_self_ty,
1409 assoc_tag,
1410 segment.ident,
1411 qpath_hir_id,
1412 span,
1413 variant_def_id,
1414 ));
1415 }
1416 };
1417
1418 let assoc_item = self
1419 .probe_assoc_item(segment.ident, assoc_tag, qpath_hir_id, span, bound.def_id())
1420 .expect("failed to find associated item");
1421
1422 Ok((assoc_item.def_id, bound))
1423 }
1424
1425 fn probe_inherent_assoc_item(
1427 &self,
1428 segment: &hir::PathSegment<'tcx>,
1429 adt_did: DefId,
1430 self_ty: Ty<'tcx>,
1431 block: HirId,
1432 span: Span,
1433 assoc_tag: ty::AssocTag,
1434 ) -> Result<Option<(DefId, GenericArgsRef<'tcx>)>, ErrorGuaranteed> {
1435 let tcx = self.tcx();
1436
1437 if !tcx.features().inherent_associated_types() {
1438 match assoc_tag {
1439 ty::AssocTag::Type => return Ok(None),
1447 ty::AssocTag::Const => {
1448 return Err(feature_err(
1452 &tcx.sess,
1453 sym::inherent_associated_types,
1454 span,
1455 "inherent associated types are unstable",
1456 )
1457 .emit());
1458 }
1459 ty::AssocTag::Fn => unreachable!(),
1460 }
1461 }
1462
1463 let name = segment.ident;
1464 let candidates: Vec<_> = tcx
1465 .inherent_impls(adt_did)
1466 .iter()
1467 .filter_map(|&impl_| {
1468 let (item, scope) =
1469 self.probe_assoc_item_unchecked(name, assoc_tag, block, impl_)?;
1470 Some(InherentAssocCandidate { impl_, assoc_item: item.def_id, scope })
1471 })
1472 .collect();
1473
1474 let (applicable_candidates, fulfillment_errors) =
1475 self.select_inherent_assoc_candidates(span, self_ty, candidates.clone());
1476
1477 let InherentAssocCandidate { impl_, assoc_item, scope: def_scope } =
1478 match &applicable_candidates[..] {
1479 &[] => Err(self.report_unresolved_inherent_assoc_item(
1480 name,
1481 self_ty,
1482 candidates,
1483 fulfillment_errors,
1484 span,
1485 assoc_tag,
1486 )),
1487
1488 &[applicable_candidate] => Ok(applicable_candidate),
1489
1490 &[_, ..] => Err(self.report_ambiguous_inherent_assoc_item(
1491 name,
1492 candidates.into_iter().map(|cand| cand.assoc_item).collect(),
1493 span,
1494 )),
1495 }?;
1496
1497 self.check_assoc_item(assoc_item, name, def_scope, block, span);
1498
1499 let parent_args = ty::GenericArgs::identity_for_item(tcx, impl_);
1503 let args = self.lower_generic_args_of_assoc_item(span, assoc_item, segment, parent_args);
1504 let args = tcx.mk_args_from_iter(
1505 std::iter::once(ty::GenericArg::from(self_ty))
1506 .chain(args.into_iter().skip(parent_args.len())),
1507 );
1508
1509 Ok(Some((assoc_item, args)))
1510 }
1511
1512 fn probe_assoc_item(
1516 &self,
1517 ident: Ident,
1518 assoc_tag: ty::AssocTag,
1519 block: HirId,
1520 span: Span,
1521 scope: DefId,
1522 ) -> Option<ty::AssocItem> {
1523 let (item, scope) = self.probe_assoc_item_unchecked(ident, assoc_tag, block, scope)?;
1524 self.check_assoc_item(item.def_id, ident, scope, block, span);
1525 Some(item)
1526 }
1527
1528 fn probe_assoc_item_unchecked(
1533 &self,
1534 ident: Ident,
1535 assoc_tag: ty::AssocTag,
1536 block: HirId,
1537 scope: DefId,
1538 ) -> Option<(ty::AssocItem, DefId)> {
1539 let tcx = self.tcx();
1540
1541 let (ident, def_scope) = tcx.adjust_ident_and_get_scope(ident, scope, block);
1542 let item = tcx
1546 .associated_items(scope)
1547 .filter_by_name_unhygienic(ident.name)
1548 .find(|i| i.as_tag() == assoc_tag && i.ident(tcx).normalize_to_macros_2_0() == ident)?;
1549
1550 Some((*item, def_scope))
1551 }
1552
1553 fn check_assoc_item(
1555 &self,
1556 item_def_id: DefId,
1557 ident: Ident,
1558 scope: DefId,
1559 block: HirId,
1560 span: Span,
1561 ) {
1562 let tcx = self.tcx();
1563
1564 if !tcx.visibility(item_def_id).is_accessible_from(scope, tcx) {
1565 self.dcx().emit_err(crate::errors::AssocItemIsPrivate {
1566 span,
1567 kind: tcx.def_descr(item_def_id),
1568 name: ident,
1569 defined_here_label: tcx.def_span(item_def_id),
1570 });
1571 }
1572
1573 tcx.check_stability(item_def_id, Some(block), span, None);
1574 }
1575
1576 fn probe_traits_that_match_assoc_ty(
1577 &self,
1578 qself_ty: Ty<'tcx>,
1579 assoc_ident: Ident,
1580 ) -> Vec<String> {
1581 let tcx = self.tcx();
1582
1583 let infcx_;
1586 let infcx = if let Some(infcx) = self.infcx() {
1587 infcx
1588 } else {
1589 assert!(!qself_ty.has_infer());
1590 infcx_ = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
1591 &infcx_
1592 };
1593
1594 tcx.all_traits_including_private()
1595 .filter(|trait_def_id| {
1596 tcx.associated_items(*trait_def_id)
1598 .in_definition_order()
1599 .any(|i| {
1600 i.is_type()
1601 && !i.is_impl_trait_in_trait()
1602 && i.ident(tcx).normalize_to_macros_2_0() == assoc_ident
1603 })
1604 && tcx.visibility(*trait_def_id)
1606 .is_accessible_from(self.item_def_id(), tcx)
1607 && tcx.all_impls(*trait_def_id)
1608 .any(|impl_def_id| {
1609 let header = tcx.impl_trait_header(impl_def_id).unwrap();
1610 let trait_ref = header.trait_ref.instantiate(
1611 tcx,
1612 infcx.fresh_args_for_item(DUMMY_SP, impl_def_id),
1613 );
1614
1615 let value = fold_regions(tcx, qself_ty, |_, _| tcx.lifetimes.re_erased);
1616 if value.has_escaping_bound_vars() {
1618 return false;
1619 }
1620 infcx
1621 .can_eq(
1622 ty::ParamEnv::empty(),
1623 trait_ref.self_ty(),
1624 value,
1625 ) && header.polarity != ty::ImplPolarity::Negative
1626 })
1627 })
1628 .map(|trait_def_id| tcx.def_path_str(trait_def_id))
1629 .collect()
1630 }
1631
1632 #[instrument(level = "debug", skip_all)]
1634 fn lower_resolved_assoc_ty_path(
1635 &self,
1636 span: Span,
1637 opt_self_ty: Option<Ty<'tcx>>,
1638 item_def_id: DefId,
1639 trait_segment: Option<&hir::PathSegment<'tcx>>,
1640 item_segment: &hir::PathSegment<'tcx>,
1641 ) -> Ty<'tcx> {
1642 match self.lower_resolved_assoc_item_path(
1643 span,
1644 opt_self_ty,
1645 item_def_id,
1646 trait_segment,
1647 item_segment,
1648 ty::AssocTag::Type,
1649 ) {
1650 Ok((item_def_id, item_args)) => {
1651 Ty::new_projection_from_args(self.tcx(), item_def_id, item_args)
1652 }
1653 Err(guar) => Ty::new_error(self.tcx(), guar),
1654 }
1655 }
1656
1657 #[instrument(level = "debug", skip_all)]
1659 fn lower_resolved_assoc_const_path(
1660 &self,
1661 span: Span,
1662 opt_self_ty: Option<Ty<'tcx>>,
1663 item_def_id: DefId,
1664 trait_segment: Option<&hir::PathSegment<'tcx>>,
1665 item_segment: &hir::PathSegment<'tcx>,
1666 ) -> Const<'tcx> {
1667 match self.lower_resolved_assoc_item_path(
1668 span,
1669 opt_self_ty,
1670 item_def_id,
1671 trait_segment,
1672 item_segment,
1673 ty::AssocTag::Const,
1674 ) {
1675 Ok((item_def_id, item_args)) => {
1676 let uv = ty::UnevaluatedConst::new(item_def_id, item_args);
1677 Const::new_unevaluated(self.tcx(), uv)
1678 }
1679 Err(guar) => Const::new_error(self.tcx(), guar),
1680 }
1681 }
1682
1683 #[instrument(level = "debug", skip_all)]
1685 fn lower_resolved_assoc_item_path(
1686 &self,
1687 span: Span,
1688 opt_self_ty: Option<Ty<'tcx>>,
1689 item_def_id: DefId,
1690 trait_segment: Option<&hir::PathSegment<'tcx>>,
1691 item_segment: &hir::PathSegment<'tcx>,
1692 assoc_tag: ty::AssocTag,
1693 ) -> Result<(DefId, GenericArgsRef<'tcx>), ErrorGuaranteed> {
1694 let tcx = self.tcx();
1695
1696 let trait_def_id = tcx.parent(item_def_id);
1697 debug!(?trait_def_id);
1698
1699 let Some(self_ty) = opt_self_ty else {
1700 return Err(self.report_missing_self_ty_for_resolved_path(
1701 trait_def_id,
1702 span,
1703 item_segment,
1704 assoc_tag,
1705 ));
1706 };
1707 debug!(?self_ty);
1708
1709 let trait_ref =
1710 self.lower_mono_trait_ref(span, trait_def_id, self_ty, trait_segment.unwrap(), false);
1711 debug!(?trait_ref);
1712
1713 let item_args =
1714 self.lower_generic_args_of_assoc_item(span, item_def_id, item_segment, trait_ref.args);
1715
1716 Ok((item_def_id, item_args))
1717 }
1718
1719 pub fn prohibit_generic_args<'a>(
1720 &self,
1721 segments: impl Iterator<Item = &'a hir::PathSegment<'a>> + Clone,
1722 err_extend: GenericsArgsErrExtend<'a>,
1723 ) -> Result<(), ErrorGuaranteed> {
1724 let args_visitors = segments.clone().flat_map(|segment| segment.args().args);
1725 let mut result = Ok(());
1726 if let Some(_) = args_visitors.clone().next() {
1727 result = Err(self.report_prohibited_generic_args(
1728 segments.clone(),
1729 args_visitors,
1730 err_extend,
1731 ));
1732 }
1733
1734 for segment in segments {
1735 if let Some(c) = segment.args().constraints.first() {
1737 return Err(prohibit_assoc_item_constraint(self, c, None));
1738 }
1739 }
1740
1741 result
1742 }
1743
1744 pub fn probe_generic_path_segments(
1762 &self,
1763 segments: &[hir::PathSegment<'_>],
1764 self_ty: Option<Ty<'tcx>>,
1765 kind: DefKind,
1766 def_id: DefId,
1767 span: Span,
1768 ) -> Vec<GenericPathSegment> {
1769 let tcx = self.tcx();
1815
1816 assert!(!segments.is_empty());
1817 let last = segments.len() - 1;
1818
1819 let mut generic_segments = vec![];
1820
1821 match kind {
1822 DefKind::Ctor(CtorOf::Struct, ..) => {
1824 let generics = tcx.generics_of(def_id);
1827 let generics_def_id = generics.parent.unwrap_or(def_id);
1830 generic_segments.push(GenericPathSegment(generics_def_id, last));
1831 }
1832
1833 DefKind::Ctor(CtorOf::Variant, ..) | DefKind::Variant => {
1835 let (generics_def_id, index) = if let Some(self_ty) = self_ty {
1836 let adt_def = self.probe_adt(span, self_ty).unwrap();
1837 debug_assert!(adt_def.is_enum());
1838 (adt_def.did(), last)
1839 } else if last >= 1 && segments[last - 1].args.is_some() {
1840 let mut def_id = def_id;
1843
1844 if let DefKind::Ctor(..) = kind {
1846 def_id = tcx.parent(def_id);
1847 }
1848
1849 let enum_def_id = tcx.parent(def_id);
1851 (enum_def_id, last - 1)
1852 } else {
1853 let generics = tcx.generics_of(def_id);
1859 (generics.parent.unwrap_or(def_id), last)
1862 };
1863 generic_segments.push(GenericPathSegment(generics_def_id, index));
1864 }
1865
1866 DefKind::Fn | DefKind::Const | DefKind::ConstParam | DefKind::Static { .. } => {
1868 generic_segments.push(GenericPathSegment(def_id, last));
1869 }
1870
1871 DefKind::AssocFn | DefKind::AssocConst => {
1873 if segments.len() >= 2 {
1874 let generics = tcx.generics_of(def_id);
1875 generic_segments.push(GenericPathSegment(generics.parent.unwrap(), last - 1));
1876 }
1877 generic_segments.push(GenericPathSegment(def_id, last));
1878 }
1879
1880 kind => bug!("unexpected definition kind {:?} for {:?}", kind, def_id),
1881 }
1882
1883 debug!(?generic_segments);
1884
1885 generic_segments
1886 }
1887
1888 #[instrument(level = "debug", skip_all)]
1890 pub fn lower_resolved_ty_path(
1891 &self,
1892 opt_self_ty: Option<Ty<'tcx>>,
1893 path: &hir::Path<'tcx>,
1894 hir_id: HirId,
1895 permit_variants: PermitVariants,
1896 ) -> Ty<'tcx> {
1897 debug!(?path.res, ?opt_self_ty, ?path.segments);
1898 let tcx = self.tcx();
1899
1900 let span = path.span;
1901 match path.res {
1902 Res::Def(DefKind::OpaqueTy, did) => {
1903 assert_matches!(tcx.opaque_ty_origin(did), hir::OpaqueTyOrigin::TyAlias { .. });
1905 let item_segment = path.segments.split_last().unwrap();
1906 let _ = self
1907 .prohibit_generic_args(item_segment.1.iter(), GenericsArgsErrExtend::OpaqueTy);
1908 let args = self.lower_generic_args_of_path_segment(span, did, item_segment.0);
1909 Ty::new_opaque(tcx, did, args)
1910 }
1911 Res::Def(
1912 DefKind::Enum
1913 | DefKind::TyAlias
1914 | DefKind::Struct
1915 | DefKind::Union
1916 | DefKind::ForeignTy,
1917 did,
1918 ) => {
1919 assert_eq!(opt_self_ty, None);
1920 let _ = self.prohibit_generic_args(
1921 path.segments.split_last().unwrap().1.iter(),
1922 GenericsArgsErrExtend::None,
1923 );
1924 self.lower_path_segment(span, did, path.segments.last().unwrap())
1925 }
1926 Res::Def(kind @ DefKind::Variant, def_id)
1927 if let PermitVariants::Yes = permit_variants =>
1928 {
1929 assert_eq!(opt_self_ty, None);
1932
1933 let generic_segments =
1934 self.probe_generic_path_segments(path.segments, None, kind, def_id, span);
1935 let indices: FxHashSet<_> =
1936 generic_segments.iter().map(|GenericPathSegment(_, index)| index).collect();
1937 let _ = self.prohibit_generic_args(
1938 path.segments.iter().enumerate().filter_map(|(index, seg)| {
1939 if !indices.contains(&index) { Some(seg) } else { None }
1940 }),
1941 GenericsArgsErrExtend::DefVariant(&path.segments),
1942 );
1943
1944 let GenericPathSegment(def_id, index) = generic_segments.last().unwrap();
1945 self.lower_path_segment(span, *def_id, &path.segments[*index])
1946 }
1947 Res::Def(DefKind::TyParam, def_id) => {
1948 assert_eq!(opt_self_ty, None);
1949 let _ = self.prohibit_generic_args(
1950 path.segments.iter(),
1951 GenericsArgsErrExtend::Param(def_id),
1952 );
1953 self.lower_ty_param(hir_id)
1954 }
1955 Res::SelfTyParam { .. } => {
1956 assert_eq!(opt_self_ty, None);
1958 let _ = self.prohibit_generic_args(
1959 path.segments.iter(),
1960 if let [hir::PathSegment { args: Some(args), ident, .. }] = &path.segments {
1961 GenericsArgsErrExtend::SelfTyParam(
1962 ident.span.shrink_to_hi().to(args.span_ext),
1963 )
1964 } else {
1965 GenericsArgsErrExtend::None
1966 },
1967 );
1968 tcx.types.self_param
1969 }
1970 Res::SelfTyAlias { alias_to: def_id, forbid_generic, .. } => {
1971 assert_eq!(opt_self_ty, None);
1973 let ty = tcx.at(span).type_of(def_id).instantiate_identity();
1975 let _ = self.prohibit_generic_args(
1976 path.segments.iter(),
1977 GenericsArgsErrExtend::SelfTyAlias { def_id, span },
1978 );
1979 if forbid_generic && ty.has_param() {
1999 let mut err = self.dcx().struct_span_err(
2000 path.span,
2001 "generic `Self` types are currently not permitted in anonymous constants",
2002 );
2003 if let Some(hir::Node::Item(&hir::Item {
2004 kind: hir::ItemKind::Impl(impl_),
2005 ..
2006 })) = tcx.hir_get_if_local(def_id)
2007 {
2008 err.span_note(impl_.self_ty.span, "not a concrete type");
2009 }
2010 let reported = err.emit();
2011 Ty::new_error(tcx, reported)
2012 } else {
2013 ty
2014 }
2015 }
2016 Res::Def(DefKind::AssocTy, def_id) => {
2017 let trait_segment = if let [modules @ .., trait_, _item] = path.segments {
2018 let _ = self.prohibit_generic_args(modules.iter(), GenericsArgsErrExtend::None);
2019 Some(trait_)
2020 } else {
2021 None
2022 };
2023 self.lower_resolved_assoc_ty_path(
2024 span,
2025 opt_self_ty,
2026 def_id,
2027 trait_segment,
2028 path.segments.last().unwrap(),
2029 )
2030 }
2031 Res::PrimTy(prim_ty) => {
2032 assert_eq!(opt_self_ty, None);
2033 let _ = self.prohibit_generic_args(
2034 path.segments.iter(),
2035 GenericsArgsErrExtend::PrimTy(prim_ty),
2036 );
2037 match prim_ty {
2038 hir::PrimTy::Bool => tcx.types.bool,
2039 hir::PrimTy::Char => tcx.types.char,
2040 hir::PrimTy::Int(it) => Ty::new_int(tcx, ty::int_ty(it)),
2041 hir::PrimTy::Uint(uit) => Ty::new_uint(tcx, ty::uint_ty(uit)),
2042 hir::PrimTy::Float(ft) => Ty::new_float(tcx, ty::float_ty(ft)),
2043 hir::PrimTy::Str => tcx.types.str_,
2044 }
2045 }
2046 Res::Err => {
2047 let e = self
2048 .tcx()
2049 .dcx()
2050 .span_delayed_bug(path.span, "path with `Res::Err` but no error emitted");
2051 Ty::new_error(tcx, e)
2052 }
2053 Res::Def(..) => {
2054 assert_eq!(
2055 path.segments.get(0).map(|seg| seg.ident.name),
2056 Some(kw::SelfUpper),
2057 "only expected incorrect resolution for `Self`"
2058 );
2059 Ty::new_error(
2060 self.tcx(),
2061 self.dcx().span_delayed_bug(span, "incorrect resolution for `Self`"),
2062 )
2063 }
2064 _ => span_bug!(span, "unexpected resolution: {:?}", path.res),
2065 }
2066 }
2067
2068 pub(crate) fn lower_ty_param(&self, hir_id: HirId) -> Ty<'tcx> {
2073 let tcx = self.tcx();
2074 match tcx.named_bound_var(hir_id) {
2075 Some(rbv::ResolvedArg::LateBound(debruijn, index, def_id)) => {
2076 let br = ty::BoundTy {
2077 var: ty::BoundVar::from_u32(index),
2078 kind: ty::BoundTyKind::Param(def_id.to_def_id()),
2079 };
2080 Ty::new_bound(tcx, debruijn, br)
2081 }
2082 Some(rbv::ResolvedArg::EarlyBound(def_id)) => {
2083 let item_def_id = tcx.hir_ty_param_owner(def_id);
2084 let generics = tcx.generics_of(item_def_id);
2085 let index = generics.param_def_id_to_index[&def_id.to_def_id()];
2086 Ty::new_param(tcx, index, tcx.hir_ty_param_name(def_id))
2087 }
2088 Some(rbv::ResolvedArg::Error(guar)) => Ty::new_error(tcx, guar),
2089 arg => bug!("unexpected bound var resolution for {hir_id:?}: {arg:?}"),
2090 }
2091 }
2092
2093 pub(crate) fn lower_const_param(&self, param_def_id: DefId, path_hir_id: HirId) -> Const<'tcx> {
2098 let tcx = self.tcx();
2099
2100 match tcx.named_bound_var(path_hir_id) {
2101 Some(rbv::ResolvedArg::EarlyBound(_)) => {
2102 let item_def_id = tcx.parent(param_def_id);
2105 let generics = tcx.generics_of(item_def_id);
2106 let index = generics.param_def_id_to_index[¶m_def_id];
2107 let name = tcx.item_name(param_def_id);
2108 ty::Const::new_param(tcx, ty::ParamConst::new(index, name))
2109 }
2110 Some(rbv::ResolvedArg::LateBound(debruijn, index, _)) => {
2111 ty::Const::new_bound(tcx, debruijn, ty::BoundVar::from_u32(index))
2112 }
2113 Some(rbv::ResolvedArg::Error(guar)) => ty::Const::new_error(tcx, guar),
2114 arg => bug!("unexpected bound var resolution for {:?}: {arg:?}", path_hir_id),
2115 }
2116 }
2117
2118 #[instrument(skip(self), level = "debug")]
2120 pub fn lower_const_arg(
2121 &self,
2122 const_arg: &hir::ConstArg<'tcx>,
2123 feed: FeedConstTy<'_, 'tcx>,
2124 ) -> Const<'tcx> {
2125 let tcx = self.tcx();
2126
2127 if let FeedConstTy::Param(param_def_id, args) = feed
2128 && let hir::ConstArgKind::Anon(anon) = &const_arg.kind
2129 {
2130 let anon_const_type = tcx.type_of(param_def_id).instantiate(tcx, args);
2131
2132 if tcx.features().generic_const_parameter_types()
2141 && (anon_const_type.has_free_regions() || anon_const_type.has_erased_regions())
2142 {
2143 let e = self.dcx().span_err(
2144 const_arg.span(),
2145 "anonymous constants with lifetimes in their type are not yet supported",
2146 );
2147 tcx.feed_anon_const_type(anon.def_id, ty::EarlyBinder::bind(Ty::new_error(tcx, e)));
2148 return ty::Const::new_error(tcx, e);
2149 }
2150 if anon_const_type.has_non_region_infer() {
2154 let e = self.dcx().span_err(
2155 const_arg.span(),
2156 "anonymous constants with inferred types are not yet supported",
2157 );
2158 tcx.feed_anon_const_type(anon.def_id, ty::EarlyBinder::bind(Ty::new_error(tcx, e)));
2159 return ty::Const::new_error(tcx, e);
2160 }
2161 if anon_const_type.has_non_region_param() {
2164 let e = self.dcx().span_err(
2165 const_arg.span(),
2166 "anonymous constants referencing generics are not yet supported",
2167 );
2168 tcx.feed_anon_const_type(anon.def_id, ty::EarlyBinder::bind(Ty::new_error(tcx, e)));
2169 return ty::Const::new_error(tcx, e);
2170 }
2171
2172 tcx.feed_anon_const_type(
2173 anon.def_id,
2174 ty::EarlyBinder::bind(tcx.type_of(param_def_id).instantiate(tcx, args)),
2175 );
2176 }
2177
2178 let hir_id = const_arg.hir_id;
2179 match const_arg.kind {
2180 hir::ConstArgKind::Path(hir::QPath::Resolved(maybe_qself, path)) => {
2181 debug!(?maybe_qself, ?path);
2182 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
2183 self.lower_resolved_const_path(opt_self_ty, path, hir_id)
2184 }
2185 hir::ConstArgKind::Path(hir::QPath::TypeRelative(hir_self_ty, segment)) => {
2186 debug!(?hir_self_ty, ?segment);
2187 let self_ty = self.lower_ty(hir_self_ty);
2188 self.lower_type_relative_const_path(
2189 self_ty,
2190 hir_self_ty,
2191 segment,
2192 hir_id,
2193 const_arg.span(),
2194 )
2195 .unwrap_or_else(|guar| Const::new_error(tcx, guar))
2196 }
2197 hir::ConstArgKind::Path(qpath @ hir::QPath::LangItem(..)) => {
2198 ty::Const::new_error_with_message(
2199 tcx,
2200 qpath.span(),
2201 format!("Const::lower_const_arg: invalid qpath {qpath:?}"),
2202 )
2203 }
2204 hir::ConstArgKind::Anon(anon) => self.lower_anon_const(anon),
2205 hir::ConstArgKind::Infer(span, ()) => self.ct_infer(None, span),
2206 }
2207 }
2208
2209 fn lower_resolved_const_path(
2211 &self,
2212 opt_self_ty: Option<Ty<'tcx>>,
2213 path: &hir::Path<'tcx>,
2214 hir_id: HirId,
2215 ) -> Const<'tcx> {
2216 let tcx = self.tcx();
2217 let span = path.span;
2218 match path.res {
2219 Res::Def(DefKind::ConstParam, def_id) => {
2220 assert_eq!(opt_self_ty, None);
2221 let _ = self.prohibit_generic_args(
2222 path.segments.iter(),
2223 GenericsArgsErrExtend::Param(def_id),
2224 );
2225 self.lower_const_param(def_id, hir_id)
2226 }
2227 Res::Def(DefKind::Const | DefKind::Ctor(_, CtorKind::Const), did) => {
2228 assert_eq!(opt_self_ty, None);
2229 let _ = self.prohibit_generic_args(
2230 path.segments.split_last().unwrap().1.iter(),
2231 GenericsArgsErrExtend::None,
2232 );
2233 let args = self.lower_generic_args_of_path_segment(
2234 span,
2235 did,
2236 path.segments.last().unwrap(),
2237 );
2238 ty::Const::new_unevaluated(tcx, ty::UnevaluatedConst::new(did, args))
2239 }
2240 Res::Def(DefKind::AssocConst, did) => {
2241 let trait_segment = if let [modules @ .., trait_, _item] = path.segments {
2242 let _ = self.prohibit_generic_args(modules.iter(), GenericsArgsErrExtend::None);
2243 Some(trait_)
2244 } else {
2245 None
2246 };
2247 self.lower_resolved_assoc_const_path(
2248 span,
2249 opt_self_ty,
2250 did,
2251 trait_segment,
2252 path.segments.last().unwrap(),
2253 )
2254 }
2255 Res::Def(DefKind::Static { .. }, _) => {
2256 span_bug!(span, "use of bare `static` ConstArgKind::Path's not yet supported")
2257 }
2258 Res::Def(DefKind::Fn | DefKind::AssocFn, did) => {
2260 self.dcx().span_delayed_bug(span, "function items cannot be used as const args");
2261 let args = self.lower_generic_args_of_path_segment(
2262 span,
2263 did,
2264 path.segments.last().unwrap(),
2265 );
2266 ty::Const::zero_sized(tcx, Ty::new_fn_def(tcx, did, args))
2267 }
2268
2269 res @ (Res::Def(
2272 DefKind::Mod
2273 | DefKind::Enum
2274 | DefKind::Variant
2275 | DefKind::Ctor(CtorOf::Variant, CtorKind::Fn)
2276 | DefKind::Struct
2277 | DefKind::Ctor(CtorOf::Struct, CtorKind::Fn)
2278 | DefKind::OpaqueTy
2279 | DefKind::TyAlias
2280 | DefKind::TraitAlias
2281 | DefKind::AssocTy
2282 | DefKind::Union
2283 | DefKind::Trait
2284 | DefKind::ForeignTy
2285 | DefKind::TyParam
2286 | DefKind::Macro(_)
2287 | DefKind::LifetimeParam
2288 | DefKind::Use
2289 | DefKind::ForeignMod
2290 | DefKind::AnonConst
2291 | DefKind::InlineConst
2292 | DefKind::Field
2293 | DefKind::Impl { .. }
2294 | DefKind::Closure
2295 | DefKind::ExternCrate
2296 | DefKind::GlobalAsm
2297 | DefKind::SyntheticCoroutineBody,
2298 _,
2299 )
2300 | Res::PrimTy(_)
2301 | Res::SelfTyParam { .. }
2302 | Res::SelfTyAlias { .. }
2303 | Res::SelfCtor(_)
2304 | Res::Local(_)
2305 | Res::ToolMod
2306 | Res::NonMacroAttr(_)
2307 | Res::Err) => Const::new_error_with_message(
2308 tcx,
2309 span,
2310 format!("invalid Res {res:?} for const path"),
2311 ),
2312 }
2313 }
2314
2315 #[instrument(skip(self), level = "debug")]
2317 fn lower_anon_const(&self, anon: &AnonConst) -> Const<'tcx> {
2318 let tcx = self.tcx();
2319
2320 let expr = &tcx.hir_body(anon.body).value;
2321 debug!(?expr);
2322
2323 let ty = tcx.type_of(anon.def_id).instantiate_identity();
2327
2328 match self.try_lower_anon_const_lit(ty, expr) {
2329 Some(v) => v,
2330 None => ty::Const::new_unevaluated(
2331 tcx,
2332 ty::UnevaluatedConst {
2333 def: anon.def_id.to_def_id(),
2334 args: ty::GenericArgs::identity_for_item(tcx, anon.def_id.to_def_id()),
2335 },
2336 ),
2337 }
2338 }
2339
2340 #[instrument(skip(self), level = "debug")]
2341 fn try_lower_anon_const_lit(
2342 &self,
2343 ty: Ty<'tcx>,
2344 expr: &'tcx hir::Expr<'tcx>,
2345 ) -> Option<Const<'tcx>> {
2346 let tcx = self.tcx();
2347
2348 let expr = match &expr.kind {
2351 hir::ExprKind::Block(block, _) if block.stmts.is_empty() && block.expr.is_some() => {
2352 block.expr.as_ref().unwrap()
2353 }
2354 _ => expr,
2355 };
2356
2357 if let hir::ExprKind::Path(hir::QPath::Resolved(
2358 _,
2359 &hir::Path { res: Res::Def(DefKind::ConstParam, _), .. },
2360 )) = expr.kind
2361 {
2362 span_bug!(
2363 expr.span,
2364 "try_lower_anon_const_lit: received const param which shouldn't be possible"
2365 );
2366 };
2367
2368 let lit_input = match expr.kind {
2369 hir::ExprKind::Lit(lit) => Some(LitToConstInput { lit: lit.node, ty, neg: false }),
2370 hir::ExprKind::Unary(hir::UnOp::Neg, expr) => match expr.kind {
2371 hir::ExprKind::Lit(lit) => Some(LitToConstInput { lit: lit.node, ty, neg: true }),
2372 _ => None,
2373 },
2374 _ => None,
2375 };
2376
2377 lit_input
2378 .filter(|l| !l.ty.has_aliases())
2381 .map(|l| tcx.at(expr.span).lit_to_const(l))
2382 }
2383
2384 fn lower_delegation_ty(&self, idx: hir::InferDelegationKind) -> Ty<'tcx> {
2385 let delegation_sig = self.tcx().inherit_sig_for_delegation_item(self.item_def_id());
2386 match idx {
2387 hir::InferDelegationKind::Input(idx) => delegation_sig[idx],
2388 hir::InferDelegationKind::Output => *delegation_sig.last().unwrap(),
2389 }
2390 }
2391
2392 #[instrument(level = "debug", skip(self), ret)]
2394 pub fn lower_ty(&self, hir_ty: &hir::Ty<'tcx>) -> Ty<'tcx> {
2395 let tcx = self.tcx();
2396
2397 let result_ty = match &hir_ty.kind {
2398 hir::TyKind::InferDelegation(_, idx) => self.lower_delegation_ty(*idx),
2399 hir::TyKind::Slice(ty) => Ty::new_slice(tcx, self.lower_ty(ty)),
2400 hir::TyKind::Ptr(mt) => Ty::new_ptr(tcx, self.lower_ty(mt.ty), mt.mutbl),
2401 hir::TyKind::Ref(region, mt) => {
2402 let r = self.lower_lifetime(region, RegionInferReason::Reference);
2403 debug!(?r);
2404 let t = self.lower_ty(mt.ty);
2405 Ty::new_ref(tcx, r, t, mt.mutbl)
2406 }
2407 hir::TyKind::Never => tcx.types.never,
2408 hir::TyKind::Tup(fields) => {
2409 Ty::new_tup_from_iter(tcx, fields.iter().map(|t| self.lower_ty(t)))
2410 }
2411 hir::TyKind::FnPtr(bf) => {
2412 require_c_abi_if_c_variadic(tcx, bf.decl, bf.abi, hir_ty.span);
2413
2414 Ty::new_fn_ptr(
2415 tcx,
2416 self.lower_fn_ty(hir_ty.hir_id, bf.safety, bf.abi, bf.decl, None, Some(hir_ty)),
2417 )
2418 }
2419 hir::TyKind::UnsafeBinder(binder) => Ty::new_unsafe_binder(
2420 tcx,
2421 ty::Binder::bind_with_vars(
2422 self.lower_ty(binder.inner_ty),
2423 tcx.late_bound_vars(hir_ty.hir_id),
2424 ),
2425 ),
2426 hir::TyKind::TraitObject(bounds, tagged_ptr) => {
2427 let lifetime = tagged_ptr.pointer();
2428 let repr = tagged_ptr.tag();
2429
2430 if let Some(guar) = self.prohibit_or_lint_bare_trait_object_ty(hir_ty) {
2431 Ty::new_error(tcx, guar)
2435 } else {
2436 let repr = match repr {
2437 TraitObjectSyntax::Dyn | TraitObjectSyntax::None => ty::Dyn,
2438 };
2439 self.lower_trait_object_ty(hir_ty.span, hir_ty.hir_id, bounds, lifetime, repr)
2440 }
2441 }
2442 hir::TyKind::Path(hir::QPath::Resolved(_, path))
2446 if path.segments.last().and_then(|segment| segment.args).is_some_and(|args| {
2447 matches!(args.parenthesized, hir::GenericArgsParentheses::ReturnTypeNotation)
2448 }) =>
2449 {
2450 let guar = self.dcx().emit_err(BadReturnTypeNotation { span: hir_ty.span });
2451 Ty::new_error(tcx, guar)
2452 }
2453 hir::TyKind::Path(hir::QPath::Resolved(maybe_qself, path)) => {
2454 debug!(?maybe_qself, ?path);
2455 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
2456 self.lower_resolved_ty_path(opt_self_ty, path, hir_ty.hir_id, PermitVariants::No)
2457 }
2458 &hir::TyKind::OpaqueDef(opaque_ty) => {
2459 let in_trait = match opaque_ty.origin {
2463 hir::OpaqueTyOrigin::FnReturn {
2464 parent,
2465 in_trait_or_impl: Some(hir::RpitContext::Trait),
2466 ..
2467 }
2468 | hir::OpaqueTyOrigin::AsyncFn {
2469 parent,
2470 in_trait_or_impl: Some(hir::RpitContext::Trait),
2471 ..
2472 } => Some(parent),
2473 hir::OpaqueTyOrigin::FnReturn {
2474 in_trait_or_impl: None | Some(hir::RpitContext::TraitImpl),
2475 ..
2476 }
2477 | hir::OpaqueTyOrigin::AsyncFn {
2478 in_trait_or_impl: None | Some(hir::RpitContext::TraitImpl),
2479 ..
2480 }
2481 | hir::OpaqueTyOrigin::TyAlias { .. } => None,
2482 };
2483
2484 self.lower_opaque_ty(opaque_ty.def_id, in_trait)
2485 }
2486 hir::TyKind::TraitAscription(hir_bounds) => {
2487 let self_ty = self.ty_infer(None, hir_ty.span);
2490 let mut bounds = Vec::new();
2491 self.lower_bounds(
2492 self_ty,
2493 hir_bounds.iter(),
2494 &mut bounds,
2495 ty::List::empty(),
2496 PredicateFilter::All,
2497 );
2498 self.register_trait_ascription_bounds(bounds, hir_ty.hir_id, hir_ty.span);
2499 self_ty
2500 }
2501 hir::TyKind::Path(hir::QPath::TypeRelative(_, segment))
2505 if segment.args.is_some_and(|args| {
2506 matches!(args.parenthesized, hir::GenericArgsParentheses::ReturnTypeNotation)
2507 }) =>
2508 {
2509 let guar = self.dcx().emit_err(BadReturnTypeNotation { span: hir_ty.span });
2510 Ty::new_error(tcx, guar)
2511 }
2512 hir::TyKind::Path(hir::QPath::TypeRelative(hir_self_ty, segment)) => {
2513 debug!(?hir_self_ty, ?segment);
2514 let self_ty = self.lower_ty(hir_self_ty);
2515 self.lower_type_relative_ty_path(
2516 self_ty,
2517 hir_self_ty,
2518 segment,
2519 hir_ty.hir_id,
2520 hir_ty.span,
2521 PermitVariants::No,
2522 )
2523 .map(|(ty, _, _)| ty)
2524 .unwrap_or_else(|guar| Ty::new_error(tcx, guar))
2525 }
2526 &hir::TyKind::Path(hir::QPath::LangItem(lang_item, span)) => {
2527 let def_id = tcx.require_lang_item(lang_item, span);
2528 let (args, _) = self.lower_generic_args_of_path(
2529 span,
2530 def_id,
2531 &[],
2532 &hir::PathSegment::invalid(),
2533 None,
2534 );
2535 tcx.at(span).type_of(def_id).instantiate(tcx, args)
2536 }
2537 hir::TyKind::Array(ty, length) => {
2538 let length = self.lower_const_arg(length, FeedConstTy::No);
2539 Ty::new_array_with_const_len(tcx, self.lower_ty(ty), length)
2540 }
2541 hir::TyKind::Typeof(e) => tcx.type_of(e.def_id).instantiate_identity(),
2542 hir::TyKind::Infer(()) => {
2543 self.ty_infer(None, hir_ty.span)
2548 }
2549 hir::TyKind::Pat(ty, pat) => {
2550 let ty_span = ty.span;
2551 let ty = self.lower_ty(ty);
2552 let pat_ty = match self.lower_pat_ty_pat(ty, ty_span, pat) {
2553 Ok(kind) => Ty::new_pat(tcx, ty, tcx.mk_pat(kind)),
2554 Err(guar) => Ty::new_error(tcx, guar),
2555 };
2556 self.record_ty(pat.hir_id, ty, pat.span);
2557 pat_ty
2558 }
2559 hir::TyKind::Err(guar) => Ty::new_error(tcx, *guar),
2560 };
2561
2562 self.record_ty(hir_ty.hir_id, result_ty, hir_ty.span);
2563 result_ty
2564 }
2565
2566 fn lower_pat_ty_pat(
2567 &self,
2568 ty: Ty<'tcx>,
2569 ty_span: Span,
2570 pat: &hir::TyPat<'tcx>,
2571 ) -> Result<ty::PatternKind<'tcx>, ErrorGuaranteed> {
2572 let tcx = self.tcx();
2573 match pat.kind {
2574 hir::TyPatKind::Range(start, end) => {
2575 match ty.kind() {
2576 ty::Int(_) | ty::Uint(_) | ty::Char => {
2579 let start = self.lower_const_arg(start, FeedConstTy::No);
2580 let end = self.lower_const_arg(end, FeedConstTy::No);
2581 Ok(ty::PatternKind::Range { start, end })
2582 }
2583 _ => Err(self
2584 .dcx()
2585 .span_delayed_bug(ty_span, "invalid base type for range pattern")),
2586 }
2587 }
2588 hir::TyPatKind::Or(patterns) => {
2589 self.tcx()
2590 .mk_patterns_from_iter(patterns.iter().map(|pat| {
2591 self.lower_pat_ty_pat(ty, ty_span, pat).map(|pat| tcx.mk_pat(pat))
2592 }))
2593 .map(ty::PatternKind::Or)
2594 }
2595 hir::TyPatKind::Err(e) => Err(e),
2596 }
2597 }
2598
2599 #[instrument(level = "debug", skip(self), ret)]
2601 fn lower_opaque_ty(&self, def_id: LocalDefId, in_trait: Option<LocalDefId>) -> Ty<'tcx> {
2602 let tcx = self.tcx();
2603
2604 let lifetimes = tcx.opaque_captured_lifetimes(def_id);
2605 debug!(?lifetimes);
2606
2607 let def_id = if let Some(parent_def_id) = in_trait {
2611 *tcx.associated_types_for_impl_traits_in_associated_fn(parent_def_id.to_def_id())
2612 .iter()
2613 .find(|rpitit| match tcx.opt_rpitit_info(**rpitit) {
2614 Some(ty::ImplTraitInTraitData::Trait { opaque_def_id, .. }) => {
2615 opaque_def_id.expect_local() == def_id
2616 }
2617 _ => unreachable!(),
2618 })
2619 .unwrap()
2620 } else {
2621 def_id.to_def_id()
2622 };
2623
2624 let generics = tcx.generics_of(def_id);
2625 debug!(?generics);
2626
2627 let offset = generics.count() - lifetimes.len();
2631
2632 let args = ty::GenericArgs::for_item(tcx, def_id, |param, _| {
2633 if let Some(i) = (param.index as usize).checked_sub(offset) {
2634 let (lifetime, _) = lifetimes[i];
2635 self.lower_resolved_lifetime(lifetime).into()
2636 } else {
2637 tcx.mk_param_from_def(param)
2638 }
2639 });
2640 debug!(?args);
2641
2642 if in_trait.is_some() {
2643 Ty::new_projection_from_args(tcx, def_id, args)
2644 } else {
2645 Ty::new_opaque(tcx, def_id, args)
2646 }
2647 }
2648
2649 #[instrument(level = "debug", skip(self, hir_id, safety, abi, decl, generics, hir_ty), ret)]
2651 pub fn lower_fn_ty(
2652 &self,
2653 hir_id: HirId,
2654 safety: hir::Safety,
2655 abi: rustc_abi::ExternAbi,
2656 decl: &hir::FnDecl<'tcx>,
2657 generics: Option<&hir::Generics<'_>>,
2658 hir_ty: Option<&hir::Ty<'_>>,
2659 ) -> ty::PolyFnSig<'tcx> {
2660 let tcx = self.tcx();
2661 let bound_vars = tcx.late_bound_vars(hir_id);
2662 debug!(?bound_vars);
2663
2664 let (input_tys, output_ty) = self.lower_fn_sig(decl, generics, hir_id, hir_ty);
2665
2666 debug!(?output_ty);
2667
2668 let fn_ty = tcx.mk_fn_sig(input_tys, output_ty, decl.c_variadic, safety, abi);
2669 let fn_ptr_ty = ty::Binder::bind_with_vars(fn_ty, bound_vars);
2670
2671 if let hir::Node::Ty(hir::Ty { kind: hir::TyKind::FnPtr(fn_ptr_ty), span, .. }) =
2672 tcx.hir_node(hir_id)
2673 {
2674 check_abi(tcx, hir_id, *span, fn_ptr_ty.abi);
2675 }
2676
2677 cmse::validate_cmse_abi(self.tcx(), self.dcx(), hir_id, abi, fn_ptr_ty);
2679
2680 if !fn_ptr_ty.references_error() {
2681 let inputs = fn_ptr_ty.inputs();
2688 let late_bound_in_args =
2689 tcx.collect_constrained_late_bound_regions(inputs.map_bound(|i| i.to_owned()));
2690 let output = fn_ptr_ty.output();
2691 let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(output);
2692
2693 self.validate_late_bound_regions(late_bound_in_args, late_bound_in_ret, |br_name| {
2694 struct_span_code_err!(
2695 self.dcx(),
2696 decl.output.span(),
2697 E0581,
2698 "return type references {}, which is not constrained by the fn input types",
2699 br_name
2700 )
2701 });
2702 }
2703
2704 fn_ptr_ty
2705 }
2706
2707 pub(super) fn suggest_trait_fn_ty_for_impl_fn_infer(
2712 &self,
2713 fn_hir_id: HirId,
2714 arg_idx: Option<usize>,
2715 ) -> Option<Ty<'tcx>> {
2716 let tcx = self.tcx();
2717 let hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), ident, .. }) =
2718 tcx.hir_node(fn_hir_id)
2719 else {
2720 return None;
2721 };
2722 let i = tcx.parent_hir_node(fn_hir_id).expect_item().expect_impl();
2723
2724 let trait_ref = self.lower_impl_trait_ref(i.of_trait.as_ref()?, self.lower_ty(i.self_ty));
2725
2726 let assoc = tcx.associated_items(trait_ref.def_id).find_by_ident_and_kind(
2727 tcx,
2728 *ident,
2729 ty::AssocTag::Fn,
2730 trait_ref.def_id,
2731 )?;
2732
2733 let fn_sig = tcx.fn_sig(assoc.def_id).instantiate(
2734 tcx,
2735 trait_ref.args.extend_to(tcx, assoc.def_id, |param, _| tcx.mk_param_from_def(param)),
2736 );
2737 let fn_sig = tcx.liberate_late_bound_regions(fn_hir_id.expect_owner().to_def_id(), fn_sig);
2738
2739 Some(if let Some(arg_idx) = arg_idx {
2740 *fn_sig.inputs().get(arg_idx)?
2741 } else {
2742 fn_sig.output()
2743 })
2744 }
2745
2746 #[instrument(level = "trace", skip(self, generate_err))]
2747 fn validate_late_bound_regions<'cx>(
2748 &'cx self,
2749 constrained_regions: FxIndexSet<ty::BoundRegionKind>,
2750 referenced_regions: FxIndexSet<ty::BoundRegionKind>,
2751 generate_err: impl Fn(&str) -> Diag<'cx>,
2752 ) {
2753 for br in referenced_regions.difference(&constrained_regions) {
2754 let br_name = if let Some(name) = br.get_name(self.tcx()) {
2755 format!("lifetime `{name}`")
2756 } else {
2757 "an anonymous lifetime".to_string()
2758 };
2759
2760 let mut err = generate_err(&br_name);
2761
2762 if !br.is_named(self.tcx()) {
2763 err.note(
2770 "lifetimes appearing in an associated or opaque type are not considered constrained",
2771 );
2772 err.note("consider introducing a named lifetime parameter");
2773 }
2774
2775 err.emit();
2776 }
2777 }
2778
2779 #[instrument(level = "debug", skip(self, span), ret)]
2787 fn compute_object_lifetime_bound(
2788 &self,
2789 span: Span,
2790 existential_predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
2791 ) -> Option<ty::Region<'tcx>> {
2793 let tcx = self.tcx();
2794
2795 let derived_region_bounds = object_region_bounds(tcx, existential_predicates);
2798
2799 if derived_region_bounds.is_empty() {
2802 return None;
2803 }
2804
2805 if derived_region_bounds.iter().any(|r| r.is_static()) {
2808 return Some(tcx.lifetimes.re_static);
2809 }
2810
2811 let r = derived_region_bounds[0];
2815 if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
2816 self.dcx().emit_err(AmbiguousLifetimeBound { span });
2817 }
2818 Some(r)
2819 }
2820}