1mod bounds;
17mod cmse;
18mod dyn_trait;
19pub mod errors;
20pub mod generics;
21
22use std::slice;
23
24use rustc_ast::LitKind;
25use rustc_data_structures::assert_matches;
26use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet};
27use rustc_errors::codes::*;
28use rustc_errors::{
29 Applicability, Diag, DiagCtxtHandle, ErrorGuaranteed, FatalError, struct_span_code_err,
30};
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};
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(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for ImpliedBoundsContext<'tcx> {
#[inline]
fn clone(&self) -> ImpliedBoundsContext<'tcx> {
let _: ::core::clone::AssertParamIsClone<LocalDefId>;
let _:
::core::clone::AssertParamIsClone<&'tcx [hir::WherePredicate<'tcx>]>;
*self
}
}Clone, #[automatically_derived]
impl<'tcx> ::core::marker::Copy for ImpliedBoundsContext<'tcx> { }Copy)]
63pub(crate) enum ImpliedBoundsContext<'tcx> {
64 TraitDef(LocalDefId),
67 TyParam(LocalDefId, &'tcx [hir::WherePredicate<'tcx>]),
69 AssociatedTypeOrImplTrait,
71}
72
73#[derive(#[automatically_derived]
impl ::core::fmt::Debug for GenericPathSegment {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"GenericPathSegment", &self.0, &&self.1)
}
}Debug)]
75pub struct GenericPathSegment(pub DefId, pub usize);
76
77#[derive(#[automatically_derived]
impl ::core::marker::Copy for PredicateFilter { }Copy, #[automatically_derived]
impl ::core::clone::Clone for PredicateFilter {
#[inline]
fn clone(&self) -> PredicateFilter {
let _: ::core::clone::AssertParamIsClone<Ident>;
*self
}
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for PredicateFilter {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
PredicateFilter::All =>
::core::fmt::Formatter::write_str(f, "All"),
PredicateFilter::SelfOnly =>
::core::fmt::Formatter::write_str(f, "SelfOnly"),
PredicateFilter::SelfTraitThatDefines(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"SelfTraitThatDefines", &__self_0),
PredicateFilter::SelfAndAssociatedTypeBounds =>
::core::fmt::Formatter::write_str(f,
"SelfAndAssociatedTypeBounds"),
PredicateFilter::ConstIfConst =>
::core::fmt::Formatter::write_str(f, "ConstIfConst"),
PredicateFilter::SelfConstIfConst =>
::core::fmt::Formatter::write_str(f, "SelfConstIfConst"),
}
}
}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(#[automatically_derived]
impl<'a> ::core::fmt::Debug for RegionInferReason<'a> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
RegionInferReason::ExplicitObjectLifetime =>
::core::fmt::Formatter::write_str(f,
"ExplicitObjectLifetime"),
RegionInferReason::ObjectLifetimeDefault =>
::core::fmt::Formatter::write_str(f, "ObjectLifetimeDefault"),
RegionInferReason::Param(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Param",
&__self_0),
RegionInferReason::RegionPredicate =>
::core::fmt::Formatter::write_str(f, "RegionPredicate"),
RegionInferReason::Reference =>
::core::fmt::Formatter::write_str(f, "Reference"),
RegionInferReason::OutlivesBound =>
::core::fmt::Formatter::write_str(f, "OutlivesBound"),
}
}
}Debug)]
103pub enum RegionInferReason<'a> {
104 ExplicitObjectLifetime,
106 ObjectLifetimeDefault,
108 Param(&'a ty::GenericParamDef),
110 RegionPredicate,
111 Reference,
112 OutlivesBound,
113}
114
115#[derive(#[automatically_derived]
impl ::core::marker::Copy for InherentAssocCandidate { }Copy, #[automatically_derived]
impl ::core::clone::Clone for InherentAssocCandidate {
#[inline]
fn clone(&self) -> InherentAssocCandidate {
let _: ::core::clone::AssertParamIsClone<DefId>;
*self
}
}Clone, const _: () =
{
impl<'tcx>
::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
for InherentAssocCandidate {
fn try_fold_with<__F: ::rustc_middle::ty::FallibleTypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
__folder: &mut __F) -> Result<Self, __F::Error> {
Ok(match self {
InherentAssocCandidate {
impl_: __binding_0,
assoc_item: __binding_1,
scope: __binding_2 } => {
InherentAssocCandidate {
impl_: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
__folder)?,
assoc_item: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_1,
__folder)?,
scope: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_2,
__folder)?,
}
}
})
}
fn fold_with<__F: ::rustc_middle::ty::TypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
__folder: &mut __F) -> Self {
match self {
InherentAssocCandidate {
impl_: __binding_0,
assoc_item: __binding_1,
scope: __binding_2 } => {
InherentAssocCandidate {
impl_: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
__folder),
assoc_item: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_1,
__folder),
scope: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_2,
__folder),
}
}
}
}
}
};TypeFoldable, const _: () =
{
impl<'tcx>
::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
for InherentAssocCandidate {
fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
__visitor: &mut __V) -> __V::Result {
match *self {
InherentAssocCandidate {
impl_: ref __binding_0,
assoc_item: ref __binding_1,
scope: ref __binding_2 } => {
{
match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
__visitor)) {
::core::ops::ControlFlow::Continue(()) => {}
::core::ops::ControlFlow::Break(r) => {
return ::rustc_middle::ty::VisitorResult::from_residual(r);
}
}
}
{
match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_1,
__visitor)) {
::core::ops::ControlFlow::Continue(()) => {}
::core::ops::ControlFlow::Break(r) => {
return ::rustc_middle::ty::VisitorResult::from_residual(r);
}
}
}
{
match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_2,
__visitor)) {
::core::ops::ControlFlow::Continue(()) => {}
::core::ops::ControlFlow::Break(r) => {
return ::rustc_middle::ty::VisitorResult::from_residual(r);
}
}
}
}
}
<__V::Result as ::rustc_middle::ty::VisitorResult>::output()
}
}
};TypeVisitable, #[automatically_derived]
impl ::core::fmt::Debug for InherentAssocCandidate {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field3_finish(f,
"InherentAssocCandidate", "impl_", &self.impl_, "assoc_item",
&self.assoc_item, "scope", &&self.scope)
}
}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(#[automatically_derived]
impl ::core::fmt::Debug for LowerTypeRelativePathMode {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
LowerTypeRelativePathMode::Type(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Type",
&__self_0),
LowerTypeRelativePathMode::Const =>
::core::fmt::Formatter::write_str(f, "Const"),
}
}
}Debug, #[automatically_derived]
impl ::core::clone::Clone for LowerTypeRelativePathMode {
#[inline]
fn clone(&self) -> LowerTypeRelativePathMode {
let _: ::core::clone::AssertParamIsClone<PermitVariants>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for LowerTypeRelativePathMode { }Copy)]
256enum LowerTypeRelativePathMode {
257 Type(PermitVariants),
258 Const,
259}
260
261impl LowerTypeRelativePathMode {
262 fn assoc_tag(self) -> ty::AssocTag {
263 match self {
264 Self::Type(_) => ty::AssocTag::Type,
265 Self::Const => ty::AssocTag::Const,
266 }
267 }
268
269 fn def_kind(self) -> DefKind {
270 match self {
271 Self::Type(_) => DefKind::AssocTy,
272 Self::Const => DefKind::AssocConst,
273 }
274 }
275
276 fn permit_variants(self) -> PermitVariants {
277 match self {
278 Self::Type(permit_variants) => permit_variants,
279 Self::Const => PermitVariants::No,
282 }
283 }
284}
285
286#[derive(#[automatically_derived]
impl ::core::fmt::Debug for PermitVariants {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
PermitVariants::Yes => "Yes",
PermitVariants::No => "No",
})
}
}Debug, #[automatically_derived]
impl ::core::clone::Clone for PermitVariants {
#[inline]
fn clone(&self) -> PermitVariants { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for PermitVariants { }Copy)]
288pub enum PermitVariants {
289 Yes,
290 No,
291}
292
293#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for TypeRelativePath<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
TypeRelativePath::AssocItem(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"AssocItem", __self_0, &__self_1),
TypeRelativePath::Variant { adt: __self_0, variant_did: __self_1 }
=>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"Variant", "adt", __self_0, "variant_did", &__self_1),
TypeRelativePath::Ctor { ctor_def_id: __self_0, args: __self_1 }
=>
::core::fmt::Formatter::debug_struct_field2_finish(f, "Ctor",
"ctor_def_id", __self_0, "args", &__self_1),
}
}
}Debug, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for TypeRelativePath<'tcx> {
#[inline]
fn clone(&self) -> TypeRelativePath<'tcx> {
let _: ::core::clone::AssertParamIsClone<DefId>;
let _: ::core::clone::AssertParamIsClone<GenericArgsRef<'tcx>>;
let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
let _: ::core::clone::AssertParamIsClone<GenericArgsRef<'tcx>>;
*self
}
}Clone, #[automatically_derived]
impl<'tcx> ::core::marker::Copy for TypeRelativePath<'tcx> { }Copy)]
294enum TypeRelativePath<'tcx> {
295 AssocItem(DefId, GenericArgsRef<'tcx>),
296 Variant { adt: Ty<'tcx>, variant_did: DefId },
297 Ctor { ctor_def_id: DefId, args: GenericArgsRef<'tcx> },
298}
299
300#[derive(#[automatically_derived]
impl ::core::marker::Copy for ExplicitLateBound { }Copy, #[automatically_derived]
impl ::core::clone::Clone for ExplicitLateBound {
#[inline]
fn clone(&self) -> ExplicitLateBound { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for ExplicitLateBound {
#[inline]
fn eq(&self, other: &ExplicitLateBound) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::fmt::Debug for ExplicitLateBound {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
ExplicitLateBound::Yes => "Yes",
ExplicitLateBound::No => "No",
})
}
}Debug)]
310pub enum ExplicitLateBound {
311 Yes,
312 No,
313}
314
315#[derive(#[automatically_derived]
impl ::core::marker::Copy for IsMethodCall { }Copy, #[automatically_derived]
impl ::core::clone::Clone for IsMethodCall {
#[inline]
fn clone(&self) -> IsMethodCall { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for IsMethodCall {
#[inline]
fn eq(&self, other: &IsMethodCall) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq)]
316pub enum IsMethodCall {
317 Yes,
318 No,
319}
320
321#[derive(#[automatically_derived]
impl ::core::marker::Copy for GenericArgPosition { }Copy, #[automatically_derived]
impl ::core::clone::Clone for GenericArgPosition {
#[inline]
fn clone(&self) -> GenericArgPosition { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for GenericArgPosition {
#[inline]
fn eq(&self, other: &GenericArgPosition) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq)]
324pub(crate) enum GenericArgPosition {
325 Type,
326 Value, MethodCall,
328}
329
330#[derive(#[automatically_derived]
impl ::core::clone::Clone for OverlappingAsssocItemConstraints {
#[inline]
fn clone(&self) -> OverlappingAsssocItemConstraints { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for OverlappingAsssocItemConstraints { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for OverlappingAsssocItemConstraints {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
OverlappingAsssocItemConstraints::Allowed => "Allowed",
OverlappingAsssocItemConstraints::Forbidden => "Forbidden",
})
}
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for OverlappingAsssocItemConstraints {
#[inline]
fn eq(&self, other: &OverlappingAsssocItemConstraints) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq)]
334pub(crate) enum OverlappingAsssocItemConstraints {
335 Allowed,
336 Forbidden,
337}
338
339#[derive(#[automatically_derived]
impl ::core::clone::Clone for GenericArgCountMismatch {
#[inline]
fn clone(&self) -> GenericArgCountMismatch {
GenericArgCountMismatch {
reported: ::core::clone::Clone::clone(&self.reported),
invalid_args: ::core::clone::Clone::clone(&self.invalid_args),
}
}
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for GenericArgCountMismatch {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f,
"GenericArgCountMismatch", "reported", &self.reported,
"invalid_args", &&self.invalid_args)
}
}Debug)]
342pub struct GenericArgCountMismatch {
343 pub reported: ErrorGuaranteed,
344 pub invalid_args: Vec<usize>,
346}
347
348#[derive(#[automatically_derived]
impl ::core::clone::Clone for GenericArgCountResult {
#[inline]
fn clone(&self) -> GenericArgCountResult {
GenericArgCountResult {
explicit_late_bound: ::core::clone::Clone::clone(&self.explicit_late_bound),
correct: ::core::clone::Clone::clone(&self.correct),
}
}
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for GenericArgCountResult {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f,
"GenericArgCountResult", "explicit_late_bound",
&self.explicit_late_bound, "correct", &&self.correct)
}
}Debug)]
351pub struct GenericArgCountResult {
352 pub explicit_late_bound: ExplicitLateBound,
353 pub correct: Result<(), GenericArgCountMismatch>,
354}
355
356pub trait GenericArgsLowerer<'a, 'tcx> {
361 fn args_for_def_id(&mut self, def_id: DefId) -> (Option<&'a GenericArgs<'tcx>>, bool);
362
363 fn provided_kind(
364 &mut self,
365 preceding_args: &[ty::GenericArg<'tcx>],
366 param: &ty::GenericParamDef,
367 arg: &GenericArg<'tcx>,
368 ) -> ty::GenericArg<'tcx>;
369
370 fn inferred_kind(
371 &mut self,
372 preceding_args: &[ty::GenericArg<'tcx>],
373 param: &ty::GenericParamDef,
374 infer_args: bool,
375 ) -> ty::GenericArg<'tcx>;
376}
377
378struct ForbidMCGParamUsesFolder<'tcx> {
379 tcx: TyCtxt<'tcx>,
380 anon_const_def_id: LocalDefId,
381 span: Span,
382 is_self_alias: bool,
383}
384
385impl<'tcx> ForbidMCGParamUsesFolder<'tcx> {
386 fn error(&self) -> ErrorGuaranteed {
387 let msg = if self.is_self_alias {
388 "generic `Self` types are currently not permitted in anonymous constants"
389 } else {
390 "generic parameters may not be used in const operations"
391 };
392 let mut diag = self.tcx.dcx().struct_span_err(self.span, msg);
393 if self.is_self_alias {
394 let anon_const_hir_id: HirId = HirId::make_owner(self.anon_const_def_id);
395 let parent_impl = self.tcx.hir_parent_owner_iter(anon_const_hir_id).find_map(
396 |(_, node)| match node {
397 hir::OwnerNode::Item(hir::Item {
398 kind: hir::ItemKind::Impl(impl_), ..
399 }) => Some(impl_),
400 _ => None,
401 },
402 );
403 if let Some(impl_) = parent_impl {
404 diag.span_note(impl_.self_ty.span, "not a concrete type");
405 }
406 }
407 diag.emit()
408 }
409}
410
411impl<'tcx> ty::TypeFolder<TyCtxt<'tcx>> for ForbidMCGParamUsesFolder<'tcx> {
412 fn cx(&self) -> TyCtxt<'tcx> {
413 self.tcx
414 }
415
416 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
417 if #[allow(non_exhaustive_omitted_patterns)] match t.kind() {
ty::Param(..) => true,
_ => false,
}matches!(t.kind(), ty::Param(..)) {
418 return Ty::new_error(self.tcx, self.error());
419 }
420 t.super_fold_with(self)
421 }
422
423 fn fold_const(&mut self, c: Const<'tcx>) -> Const<'tcx> {
424 if #[allow(non_exhaustive_omitted_patterns)] match c.kind() {
ty::ConstKind::Param(..) => true,
_ => false,
}matches!(c.kind(), ty::ConstKind::Param(..)) {
425 return Const::new_error(self.tcx, self.error());
426 }
427 c.super_fold_with(self)
428 }
429
430 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
431 if #[allow(non_exhaustive_omitted_patterns)] match r.kind() {
ty::RegionKind::ReEarlyParam(..) | ty::RegionKind::ReLateParam(..) =>
true,
_ => false,
}matches!(r.kind(), ty::RegionKind::ReEarlyParam(..) | ty::RegionKind::ReLateParam(..)) {
432 return ty::Region::new_error(self.tcx, self.error());
433 }
434 r
435 }
436}
437
438impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
439 pub fn check_param_res_if_mcg_for_instantiate_value_path(
443 &self,
444 res: Res,
445 span: Span,
446 ) -> Result<(), ErrorGuaranteed> {
447 let tcx = self.tcx();
448 let parent_def_id = self.item_def_id();
449 if let Res::Def(DefKind::ConstParam, _) = res
450 && tcx.def_kind(parent_def_id) == DefKind::AnonConst
451 && let ty::AnonConstKind::MCG = tcx.anon_const_kind(parent_def_id)
452 {
453 let folder = ForbidMCGParamUsesFolder {
454 tcx,
455 anon_const_def_id: parent_def_id,
456 span,
457 is_self_alias: false,
458 };
459 return Err(folder.error());
460 }
461 Ok(())
462 }
463
464 #[must_use = "need to use transformed output"]
467 fn check_param_uses_if_mcg<T>(&self, term: T, span: Span, is_self_alias: bool) -> T
468 where
469 T: ty::TypeFoldable<TyCtxt<'tcx>>,
470 {
471 let tcx = self.tcx();
472 let parent_def_id = self.item_def_id();
473 if tcx.def_kind(parent_def_id) == DefKind::AnonConst
474 && let ty::AnonConstKind::MCG = tcx.anon_const_kind(parent_def_id)
475 && (term.has_param() || term.has_escaping_bound_vars())
477 {
478 let mut folder = ForbidMCGParamUsesFolder {
479 tcx,
480 anon_const_def_id: parent_def_id,
481 span,
482 is_self_alias,
483 };
484 term.fold_with(&mut folder)
485 } else {
486 term
487 }
488 }
489
490 x;#[instrument(level = "debug", skip(self), ret)]
492 pub fn lower_lifetime(
493 &self,
494 lifetime: &hir::Lifetime,
495 reason: RegionInferReason<'_>,
496 ) -> ty::Region<'tcx> {
497 if let Some(resolved) = self.tcx().named_bound_var(lifetime.hir_id) {
498 let region = self.lower_resolved_lifetime(resolved);
499 self.check_param_uses_if_mcg(region, lifetime.ident.span, false)
500 } else {
501 self.re_infer(lifetime.ident.span, reason)
502 }
503 }
504
505 x;#[instrument(level = "debug", skip(self), ret)]
507 fn lower_resolved_lifetime(&self, resolved: rbv::ResolvedArg) -> ty::Region<'tcx> {
508 let tcx = self.tcx();
509
510 match resolved {
511 rbv::ResolvedArg::StaticLifetime => tcx.lifetimes.re_static,
512
513 rbv::ResolvedArg::LateBound(debruijn, index, def_id) => {
514 let br = ty::BoundRegion {
515 var: ty::BoundVar::from_u32(index),
516 kind: ty::BoundRegionKind::Named(def_id.to_def_id()),
517 };
518 ty::Region::new_bound(tcx, debruijn, br)
519 }
520
521 rbv::ResolvedArg::EarlyBound(def_id) => {
522 let name = tcx.hir_ty_param_name(def_id);
523 let item_def_id = tcx.hir_ty_param_owner(def_id);
524 let generics = tcx.generics_of(item_def_id);
525 let index = generics.param_def_id_to_index[&def_id.to_def_id()];
526 ty::Region::new_early_param(tcx, ty::EarlyParamRegion { index, name })
527 }
528
529 rbv::ResolvedArg::Free(scope, id) => {
530 ty::Region::new_late_param(
531 tcx,
532 scope.to_def_id(),
533 ty::LateParamRegionKind::Named(id.to_def_id()),
534 )
535
536 }
538
539 rbv::ResolvedArg::Error(guar) => ty::Region::new_error(tcx, guar),
540 }
541 }
542
543 pub fn lower_generic_args_of_path_segment(
544 &self,
545 span: Span,
546 def_id: DefId,
547 item_segment: &hir::PathSegment<'tcx>,
548 ) -> GenericArgsRef<'tcx> {
549 let (args, _) = self.lower_generic_args_of_path(span, def_id, &[], item_segment, None);
550 if let Some(c) = item_segment.args().constraints.first() {
551 prohibit_assoc_item_constraint(self, c, Some((def_id, item_segment, span)));
552 }
553 args
554 }
555
556 x;#[instrument(level = "debug", skip(self, span), ret)]
591 fn lower_generic_args_of_path(
592 &self,
593 span: Span,
594 def_id: DefId,
595 parent_args: &[ty::GenericArg<'tcx>],
596 segment: &hir::PathSegment<'tcx>,
597 self_ty: Option<Ty<'tcx>>,
598 ) -> (GenericArgsRef<'tcx>, GenericArgCountResult) {
599 let tcx = self.tcx();
604 let generics = tcx.generics_of(def_id);
605 debug!(?generics);
606
607 if generics.has_self {
608 if generics.parent.is_some() {
609 assert!(!parent_args.is_empty())
612 } else {
613 assert!(self_ty.is_some());
615 }
616 } else {
617 assert!(self_ty.is_none());
618 }
619
620 let arg_count = check_generic_arg_count(
621 self,
622 def_id,
623 segment,
624 generics,
625 GenericArgPosition::Type,
626 self_ty.is_some(),
627 );
628
629 if generics.is_own_empty() {
634 return (tcx.mk_args(parent_args), arg_count);
635 }
636
637 struct GenericArgsCtxt<'a, 'tcx> {
638 lowerer: &'a dyn HirTyLowerer<'tcx>,
639 def_id: DefId,
640 generic_args: &'a GenericArgs<'tcx>,
641 span: Span,
642 infer_args: bool,
643 incorrect_args: &'a Result<(), GenericArgCountMismatch>,
644 }
645
646 impl<'a, 'tcx> GenericArgsLowerer<'a, 'tcx> for GenericArgsCtxt<'a, 'tcx> {
647 fn args_for_def_id(&mut self, did: DefId) -> (Option<&'a GenericArgs<'tcx>>, bool) {
648 if did == self.def_id {
649 (Some(self.generic_args), self.infer_args)
650 } else {
651 (None, false)
653 }
654 }
655
656 fn provided_kind(
657 &mut self,
658 preceding_args: &[ty::GenericArg<'tcx>],
659 param: &ty::GenericParamDef,
660 arg: &GenericArg<'tcx>,
661 ) -> ty::GenericArg<'tcx> {
662 let tcx = self.lowerer.tcx();
663
664 if let Err(incorrect) = self.incorrect_args {
665 if incorrect.invalid_args.contains(&(param.index as usize)) {
666 return param.to_error(tcx);
667 }
668 }
669
670 let handle_ty_args = |has_default, ty: &hir::Ty<'tcx>| {
671 if has_default {
672 tcx.check_optional_stability(
673 param.def_id,
674 Some(arg.hir_id()),
675 arg.span(),
676 None,
677 AllowUnstable::No,
678 |_, _| {
679 },
685 );
686 }
687 self.lowerer.lower_ty(ty).into()
688 };
689
690 match (¶m.kind, arg) {
691 (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => {
692 self.lowerer.lower_lifetime(lt, RegionInferReason::Param(param)).into()
693 }
694 (&GenericParamDefKind::Type { has_default, .. }, GenericArg::Type(ty)) => {
695 handle_ty_args(has_default, ty.as_unambig_ty())
697 }
698 (&GenericParamDefKind::Type { has_default, .. }, GenericArg::Infer(inf)) => {
699 handle_ty_args(has_default, &inf.to_ty())
700 }
701 (GenericParamDefKind::Const { .. }, GenericArg::Const(ct)) => self
702 .lowerer
703 .lower_const_arg(
705 ct.as_unambig_ct(),
706 tcx.type_of(param.def_id).instantiate(tcx, preceding_args),
707 )
708 .into(),
709 (&GenericParamDefKind::Const { .. }, GenericArg::Infer(inf)) => {
710 self.lowerer.ct_infer(Some(param), inf.span).into()
711 }
712 (kind, arg) => span_bug!(
713 self.span,
714 "mismatched path argument for kind {kind:?}: found arg {arg:?}"
715 ),
716 }
717 }
718
719 fn inferred_kind(
720 &mut self,
721 preceding_args: &[ty::GenericArg<'tcx>],
722 param: &ty::GenericParamDef,
723 infer_args: bool,
724 ) -> ty::GenericArg<'tcx> {
725 let tcx = self.lowerer.tcx();
726
727 if let Err(incorrect) = self.incorrect_args {
728 if incorrect.invalid_args.contains(&(param.index as usize)) {
729 return param.to_error(tcx);
730 }
731 }
732 match param.kind {
733 GenericParamDefKind::Lifetime => {
734 self.lowerer.re_infer(self.span, RegionInferReason::Param(param)).into()
735 }
736 GenericParamDefKind::Type { has_default, .. } => {
737 if !infer_args && has_default {
738 if let Some(prev) =
740 preceding_args.iter().find_map(|arg| match arg.kind() {
741 GenericArgKind::Type(ty) => ty.error_reported().err(),
742 _ => None,
743 })
744 {
745 return Ty::new_error(tcx, prev).into();
747 }
748 tcx.at(self.span)
749 .type_of(param.def_id)
750 .instantiate(tcx, preceding_args)
751 .into()
752 } else if infer_args {
753 self.lowerer.ty_infer(Some(param), self.span).into()
754 } else {
755 Ty::new_misc_error(tcx).into()
757 }
758 }
759 GenericParamDefKind::Const { has_default, .. } => {
760 let ty = tcx
761 .at(self.span)
762 .type_of(param.def_id)
763 .instantiate(tcx, preceding_args);
764 if let Err(guar) = ty.error_reported() {
765 return ty::Const::new_error(tcx, guar).into();
766 }
767 if !infer_args && has_default {
768 tcx.const_param_default(param.def_id)
769 .instantiate(tcx, preceding_args)
770 .into()
771 } else if infer_args {
772 self.lowerer.ct_infer(Some(param), self.span).into()
773 } else {
774 ty::Const::new_misc_error(tcx).into()
776 }
777 }
778 }
779 }
780 }
781
782 let mut args_ctx = GenericArgsCtxt {
783 lowerer: self,
784 def_id,
785 span,
786 generic_args: segment.args(),
787 infer_args: segment.infer_args,
788 incorrect_args: &arg_count.correct,
789 };
790 let args = lower_generic_args(
791 self,
792 def_id,
793 parent_args,
794 self_ty.is_some(),
795 self_ty,
796 &arg_count,
797 &mut args_ctx,
798 );
799
800 (args, arg_count)
801 }
802
803 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("lower_generic_args_of_assoc_item",
"rustc_hir_analysis::hir_ty_lowering",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
::tracing_core::__macro_support::Option::Some(803u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&["span",
"item_def_id", "item_segment", "parent_args"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item_def_id)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item_segment)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&parent_args)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: GenericArgsRef<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{
let (args, _) =
self.lower_generic_args_of_path(span, item_def_id,
parent_args, item_segment, None);
if let Some(c) = item_segment.args().constraints.first() {
prohibit_assoc_item_constraint(self, c,
Some((item_def_id, item_segment, span)));
}
args
}
}
}#[instrument(level = "debug", skip(self))]
804 pub fn lower_generic_args_of_assoc_item(
805 &self,
806 span: Span,
807 item_def_id: DefId,
808 item_segment: &hir::PathSegment<'tcx>,
809 parent_args: GenericArgsRef<'tcx>,
810 ) -> GenericArgsRef<'tcx> {
811 let (args, _) =
812 self.lower_generic_args_of_path(span, item_def_id, parent_args, item_segment, None);
813 if let Some(c) = item_segment.args().constraints.first() {
814 prohibit_assoc_item_constraint(self, c, Some((item_def_id, item_segment, span)));
815 }
816 args
817 }
818
819 pub fn lower_impl_trait_ref(
823 &self,
824 trait_ref: &hir::TraitRef<'tcx>,
825 self_ty: Ty<'tcx>,
826 ) -> ty::TraitRef<'tcx> {
827 let [leading_segments @ .., segment] = trait_ref.path.segments else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
828
829 let _ = self.prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
830
831 self.lower_mono_trait_ref(
832 trait_ref.path.span,
833 trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise()),
834 self_ty,
835 segment,
836 true,
837 )
838 }
839
840 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("lower_poly_trait_ref",
"rustc_hir_analysis::hir_ty_lowering",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
::tracing_core::__macro_support::Option::Some(863u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&["bound_generic_params",
"constness", "polarity", "trait_ref", "span", "self_ty",
"predicate_filter", "overlapping_assoc_item_constraints"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&bound_generic_params)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&constness)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&polarity)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_ref)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self_ty)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&predicate_filter)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&overlapping_assoc_item_constraints)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: GenericArgCountResult = loop {};
return __tracing_attr_fake_return;
}
{
let tcx = self.tcx();
let _ = bound_generic_params;
let trait_def_id =
trait_ref.trait_def_id().unwrap_or_else(||
FatalError.raise());
let transient =
match polarity {
hir::BoundPolarity::Positive => {
tcx.is_lang_item(trait_def_id, hir::LangItem::PointeeSized)
}
hir::BoundPolarity::Negative(_) => false,
hir::BoundPolarity::Maybe(_) => {
self.require_bound_to_relax_default_trait(trait_ref, span);
true
}
};
let bounds = if transient { &mut Vec::new() } else { bounds };
let polarity =
match polarity {
hir::BoundPolarity::Positive | hir::BoundPolarity::Maybe(_)
=> {
ty::PredicatePolarity::Positive
}
hir::BoundPolarity::Negative(_) =>
ty::PredicatePolarity::Negative,
};
let [leading_segments @ .., segment] =
trait_ref.path.segments else {
::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))
};
let _ =
self.prohibit_generic_args(leading_segments.iter(),
GenericsArgsErrExtend::None);
self.report_internal_fn_trait(span, trait_def_id, segment, false);
let (generic_args, arg_count) =
self.lower_generic_args_of_path(trait_ref.path.span,
trait_def_id, &[], segment, Some(self_ty));
let constraints = segment.args().constraints;
if transient &&
(!generic_args[1..].is_empty() || !constraints.is_empty()) {
self.dcx().span_delayed_bug(span,
"transient bound should not have args or constraints");
}
let bound_vars = tcx.late_bound_vars(trait_ref.hir_ref_id);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs:943",
"rustc_hir_analysis::hir_ty_lowering",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
::tracing_core::__macro_support::Option::Some(943u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&["bound_vars"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&bound_vars)
as &dyn Value))])
});
} else { ; }
};
let poly_trait_ref =
ty::Binder::bind_with_vars(ty::TraitRef::new_from_args(tcx,
trait_def_id, generic_args), bound_vars);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs:950",
"rustc_hir_analysis::hir_ty_lowering",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
::tracing_core::__macro_support::Option::Some(950u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&["poly_trait_ref"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&poly_trait_ref)
as &dyn Value))])
});
} else { ; }
};
match predicate_filter {
PredicateFilter::All | PredicateFilter::SelfOnly |
PredicateFilter::SelfTraitThatDefines(..) |
PredicateFilter::SelfAndAssociatedTypeBounds => {
let bound =
poly_trait_ref.map_bound(|trait_ref|
{
ty::ClauseKind::Trait(ty::TraitPredicate {
trait_ref,
polarity,
})
});
let bound = (bound.upcast(tcx), span);
if tcx.is_lang_item(trait_def_id,
rustc_hir::LangItem::Sized) {
bounds.insert(0, bound);
} else { bounds.push(bound); }
}
PredicateFilter::ConstIfConst |
PredicateFilter::SelfConstIfConst => {}
}
if let hir::BoundConstness::Always(span) |
hir::BoundConstness::Maybe(span) = constness &&
!tcx.is_const_trait(trait_def_id) {
let (def_span, suggestion, suggestion_pre) =
match (trait_def_id.as_local(), tcx.sess.is_nightly_build())
{
(Some(trait_def_id), true) => {
let span = tcx.hir_expect_item(trait_def_id).vis_span;
let span =
tcx.sess.source_map().span_extend_while_whitespace(span);
(None, Some(span.shrink_to_hi()),
if self.tcx().features().const_trait_impl() {
""
} else {
"enable `#![feature(const_trait_impl)]` in your crate and "
})
}
(None, _) | (_, false) =>
(Some(tcx.def_span(trait_def_id)), None, ""),
};
self.dcx().emit_err(crate::errors::ConstBoundForNonConstTrait {
span,
modifier: constness.as_str(),
def_span,
trait_name: tcx.def_path_str(trait_def_id),
suggestion,
suggestion_pre,
});
} else {
match predicate_filter {
PredicateFilter::SelfTraitThatDefines(..) => {}
PredicateFilter::All | PredicateFilter::SelfOnly |
PredicateFilter::SelfAndAssociatedTypeBounds => {
match constness {
hir::BoundConstness::Always(_) => {
if polarity == ty::PredicatePolarity::Positive {
bounds.push((poly_trait_ref.to_host_effect_clause(tcx,
ty::BoundConstness::Const), span));
}
}
hir::BoundConstness::Maybe(_) => {}
hir::BoundConstness::Never => {}
}
}
PredicateFilter::ConstIfConst |
PredicateFilter::SelfConstIfConst => {
match constness {
hir::BoundConstness::Maybe(_) => {
if polarity == ty::PredicatePolarity::Positive {
bounds.push((poly_trait_ref.to_host_effect_clause(tcx,
ty::BoundConstness::Maybe), span));
}
}
hir::BoundConstness::Always(_) | hir::BoundConstness::Never
=> {}
}
}
}
}
let mut dup_constraints =
(overlapping_assoc_item_constraints ==
OverlappingAsssocItemConstraints::Forbidden).then_some(FxIndexMap::default());
for constraint in constraints {
if polarity == ty::PredicatePolarity::Negative {
self.dcx().span_delayed_bug(constraint.span,
"negative trait bounds should not have assoc item constraints");
break;
}
let _: Result<_, ErrorGuaranteed> =
self.lower_assoc_item_constraint(trait_ref.hir_ref_id,
poly_trait_ref, constraint, bounds,
dup_constraints.as_mut(), constraint.span,
predicate_filter);
}
arg_count
}
}
}#[instrument(level = "debug", skip(self, bounds))]
864 pub(crate) fn lower_poly_trait_ref(
865 &self,
866 &hir::PolyTraitRef {
867 bound_generic_params,
868 modifiers: hir::TraitBoundModifiers { constness, polarity },
869 trait_ref,
870 span,
871 }: &hir::PolyTraitRef<'tcx>,
872 self_ty: Ty<'tcx>,
873 bounds: &mut Vec<(ty::Clause<'tcx>, Span)>,
874 predicate_filter: PredicateFilter,
875 overlapping_assoc_item_constraints: OverlappingAsssocItemConstraints,
876 ) -> GenericArgCountResult {
877 let tcx = self.tcx();
878
879 let _ = bound_generic_params;
882
883 let trait_def_id = trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise());
884
885 let transient = match polarity {
890 hir::BoundPolarity::Positive => {
891 tcx.is_lang_item(trait_def_id, hir::LangItem::PointeeSized)
897 }
898 hir::BoundPolarity::Negative(_) => false,
899 hir::BoundPolarity::Maybe(_) => {
900 self.require_bound_to_relax_default_trait(trait_ref, span);
901 true
902 }
903 };
904 let bounds = if transient { &mut Vec::new() } else { bounds };
905
906 let polarity = match polarity {
907 hir::BoundPolarity::Positive | hir::BoundPolarity::Maybe(_) => {
908 ty::PredicatePolarity::Positive
909 }
910 hir::BoundPolarity::Negative(_) => ty::PredicatePolarity::Negative,
911 };
912
913 let [leading_segments @ .., segment] = trait_ref.path.segments else { bug!() };
914
915 let _ = self.prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
916 self.report_internal_fn_trait(span, trait_def_id, segment, false);
917
918 let (generic_args, arg_count) = self.lower_generic_args_of_path(
919 trait_ref.path.span,
920 trait_def_id,
921 &[],
922 segment,
923 Some(self_ty),
924 );
925
926 let constraints = segment.args().constraints;
927
928 if transient && (!generic_args[1..].is_empty() || !constraints.is_empty()) {
929 self.dcx()
939 .span_delayed_bug(span, "transient bound should not have args or constraints");
940 }
941
942 let bound_vars = tcx.late_bound_vars(trait_ref.hir_ref_id);
943 debug!(?bound_vars);
944
945 let poly_trait_ref = ty::Binder::bind_with_vars(
946 ty::TraitRef::new_from_args(tcx, trait_def_id, generic_args),
947 bound_vars,
948 );
949
950 debug!(?poly_trait_ref);
951
952 match predicate_filter {
954 PredicateFilter::All
955 | PredicateFilter::SelfOnly
956 | PredicateFilter::SelfTraitThatDefines(..)
957 | PredicateFilter::SelfAndAssociatedTypeBounds => {
958 let bound = poly_trait_ref.map_bound(|trait_ref| {
959 ty::ClauseKind::Trait(ty::TraitPredicate { trait_ref, polarity })
960 });
961 let bound = (bound.upcast(tcx), span);
962 if tcx.is_lang_item(trait_def_id, rustc_hir::LangItem::Sized) {
968 bounds.insert(0, bound);
969 } else {
970 bounds.push(bound);
971 }
972 }
973 PredicateFilter::ConstIfConst | PredicateFilter::SelfConstIfConst => {}
974 }
975
976 if let hir::BoundConstness::Always(span) | hir::BoundConstness::Maybe(span) = constness
977 && !tcx.is_const_trait(trait_def_id)
978 {
979 let (def_span, suggestion, suggestion_pre) =
980 match (trait_def_id.as_local(), tcx.sess.is_nightly_build()) {
981 (Some(trait_def_id), true) => {
982 let span = tcx.hir_expect_item(trait_def_id).vis_span;
983 let span = tcx.sess.source_map().span_extend_while_whitespace(span);
984
985 (
986 None,
987 Some(span.shrink_to_hi()),
988 if self.tcx().features().const_trait_impl() {
989 ""
990 } else {
991 "enable `#![feature(const_trait_impl)]` in your crate and "
992 },
993 )
994 }
995 (None, _) | (_, false) => (Some(tcx.def_span(trait_def_id)), None, ""),
996 };
997 self.dcx().emit_err(crate::errors::ConstBoundForNonConstTrait {
998 span,
999 modifier: constness.as_str(),
1000 def_span,
1001 trait_name: tcx.def_path_str(trait_def_id),
1002 suggestion,
1003 suggestion_pre,
1004 });
1005 } else {
1006 match predicate_filter {
1007 PredicateFilter::SelfTraitThatDefines(..) => {}
1009 PredicateFilter::All
1010 | PredicateFilter::SelfOnly
1011 | PredicateFilter::SelfAndAssociatedTypeBounds => {
1012 match constness {
1013 hir::BoundConstness::Always(_) => {
1014 if polarity == ty::PredicatePolarity::Positive {
1015 bounds.push((
1016 poly_trait_ref
1017 .to_host_effect_clause(tcx, ty::BoundConstness::Const),
1018 span,
1019 ));
1020 }
1021 }
1022 hir::BoundConstness::Maybe(_) => {
1023 }
1028 hir::BoundConstness::Never => {}
1029 }
1030 }
1031 PredicateFilter::ConstIfConst | PredicateFilter::SelfConstIfConst => {
1038 match constness {
1039 hir::BoundConstness::Maybe(_) => {
1040 if polarity == ty::PredicatePolarity::Positive {
1041 bounds.push((
1042 poly_trait_ref
1043 .to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
1044 span,
1045 ));
1046 }
1047 }
1048 hir::BoundConstness::Always(_) | hir::BoundConstness::Never => {}
1049 }
1050 }
1051 }
1052 }
1053
1054 let mut dup_constraints = (overlapping_assoc_item_constraints
1055 == OverlappingAsssocItemConstraints::Forbidden)
1056 .then_some(FxIndexMap::default());
1057
1058 for constraint in constraints {
1059 if polarity == ty::PredicatePolarity::Negative {
1063 self.dcx().span_delayed_bug(
1064 constraint.span,
1065 "negative trait bounds should not have assoc item constraints",
1066 );
1067 break;
1068 }
1069
1070 let _: Result<_, ErrorGuaranteed> = self.lower_assoc_item_constraint(
1072 trait_ref.hir_ref_id,
1073 poly_trait_ref,
1074 constraint,
1075 bounds,
1076 dup_constraints.as_mut(),
1077 constraint.span,
1078 predicate_filter,
1079 );
1080 }
1082
1083 arg_count
1084 }
1085
1086 fn lower_mono_trait_ref(
1090 &self,
1091 span: Span,
1092 trait_def_id: DefId,
1093 self_ty: Ty<'tcx>,
1094 trait_segment: &hir::PathSegment<'tcx>,
1095 is_impl: bool,
1096 ) -> ty::TraitRef<'tcx> {
1097 self.report_internal_fn_trait(span, trait_def_id, trait_segment, is_impl);
1098
1099 let (generic_args, _) =
1100 self.lower_generic_args_of_path(span, trait_def_id, &[], trait_segment, Some(self_ty));
1101 if let Some(c) = trait_segment.args().constraints.first() {
1102 prohibit_assoc_item_constraint(self, c, Some((trait_def_id, trait_segment, span)));
1103 }
1104 ty::TraitRef::new_from_args(self.tcx(), trait_def_id, generic_args)
1105 }
1106
1107 fn probe_trait_that_defines_assoc_item(
1108 &self,
1109 trait_def_id: DefId,
1110 assoc_tag: ty::AssocTag,
1111 assoc_ident: Ident,
1112 ) -> bool {
1113 self.tcx()
1114 .associated_items(trait_def_id)
1115 .find_by_ident_and_kind(self.tcx(), assoc_ident, assoc_tag, trait_def_id)
1116 .is_some()
1117 }
1118
1119 fn lower_path_segment(
1120 &self,
1121 span: Span,
1122 did: DefId,
1123 item_segment: &hir::PathSegment<'tcx>,
1124 ) -> Ty<'tcx> {
1125 let tcx = self.tcx();
1126 let args = self.lower_generic_args_of_path_segment(span, did, item_segment);
1127
1128 if let DefKind::TyAlias = tcx.def_kind(did)
1129 && tcx.type_alias_is_lazy(did)
1130 {
1131 let alias_ty = ty::AliasTy::new_from_args(tcx, did, args);
1135 Ty::new_alias(tcx, ty::Free, alias_ty)
1136 } else {
1137 tcx.at(span).type_of(did).instantiate(tcx, args)
1138 }
1139 }
1140
1141 x;#[instrument(level = "debug", skip_all, ret)]
1149 fn probe_single_ty_param_bound_for_assoc_item(
1150 &self,
1151 ty_param_def_id: LocalDefId,
1152 ty_param_span: Span,
1153 assoc_tag: ty::AssocTag,
1154 assoc_ident: Ident,
1155 span: Span,
1156 ) -> Result<ty::PolyTraitRef<'tcx>, ErrorGuaranteed> {
1157 debug!(?ty_param_def_id, ?assoc_ident, ?span);
1158 let tcx = self.tcx();
1159
1160 let predicates = &self.probe_ty_param_bounds(span, ty_param_def_id, assoc_ident);
1161 debug!("predicates={:#?}", predicates);
1162
1163 self.probe_single_bound_for_assoc_item(
1164 || {
1165 let trait_refs = predicates
1166 .iter_identity_copied()
1167 .filter_map(|(p, _)| Some(p.as_trait_clause()?.map_bound(|t| t.trait_ref)));
1168 traits::transitive_bounds_that_define_assoc_item(tcx, trait_refs, assoc_ident)
1169 },
1170 AssocItemQSelf::TyParam(ty_param_def_id, ty_param_span),
1171 assoc_tag,
1172 assoc_ident,
1173 span,
1174 None,
1175 )
1176 }
1177
1178 x;#[instrument(level = "debug", skip(self, all_candidates, qself, constraint), ret)]
1184 fn probe_single_bound_for_assoc_item<I>(
1185 &self,
1186 all_candidates: impl Fn() -> I,
1187 qself: AssocItemQSelf,
1188 assoc_tag: ty::AssocTag,
1189 assoc_ident: Ident,
1190 span: Span,
1191 constraint: Option<&hir::AssocItemConstraint<'tcx>>,
1192 ) -> Result<ty::PolyTraitRef<'tcx>, ErrorGuaranteed>
1193 where
1194 I: Iterator<Item = ty::PolyTraitRef<'tcx>>,
1195 {
1196 let tcx = self.tcx();
1197
1198 let mut matching_candidates = all_candidates().filter(|r| {
1199 self.probe_trait_that_defines_assoc_item(r.def_id(), assoc_tag, assoc_ident)
1200 });
1201
1202 let Some(bound) = matching_candidates.next() else {
1203 return Err(self.report_unresolved_assoc_item(
1204 all_candidates,
1205 qself,
1206 assoc_tag,
1207 assoc_ident,
1208 span,
1209 constraint,
1210 ));
1211 };
1212 debug!(?bound);
1213
1214 if let Some(bound2) = matching_candidates.next() {
1215 debug!(?bound2);
1216
1217 let assoc_kind_str = errors::assoc_tag_str(assoc_tag);
1218 let qself_str = qself.to_string(tcx);
1219 let mut err = self.dcx().create_err(crate::errors::AmbiguousAssocItem {
1220 span,
1221 assoc_kind: assoc_kind_str,
1222 assoc_ident,
1223 qself: &qself_str,
1224 });
1225 err.code(
1227 if let Some(constraint) = constraint
1228 && let hir::AssocItemConstraintKind::Equality { .. } = constraint.kind
1229 {
1230 E0222
1231 } else {
1232 E0221
1233 },
1234 );
1235
1236 let mut where_bounds = vec![];
1240 for bound in [bound, bound2].into_iter().chain(matching_candidates) {
1241 let bound_id = bound.def_id();
1242 let assoc_item = tcx.associated_items(bound_id).find_by_ident_and_kind(
1243 tcx,
1244 assoc_ident,
1245 assoc_tag,
1246 bound_id,
1247 );
1248 let bound_span = assoc_item.and_then(|item| tcx.hir_span_if_local(item.def_id));
1249
1250 if let Some(bound_span) = bound_span {
1251 err.span_label(
1252 bound_span,
1253 format!("ambiguous `{assoc_ident}` from `{}`", bound.print_trait_sugared(),),
1254 );
1255 if let Some(constraint) = constraint {
1256 match constraint.kind {
1257 hir::AssocItemConstraintKind::Equality { term } => {
1258 let term: ty::Term<'_> = match term {
1259 hir::Term::Ty(ty) => self.lower_ty(ty).into(),
1260 hir::Term::Const(ct) => {
1261 let assoc_item =
1262 assoc_item.expect("assoc_item should be present");
1263 let projection_term = bound.map_bound(|trait_ref| {
1264 let item_segment = hir::PathSegment {
1265 ident: constraint.ident,
1266 hir_id: constraint.hir_id,
1267 res: Res::Err,
1268 args: Some(constraint.gen_args),
1269 infer_args: false,
1270 };
1271
1272 let alias_args = self.lower_generic_args_of_assoc_item(
1273 constraint.ident.span,
1274 assoc_item.def_id,
1275 &item_segment,
1276 trait_ref.args,
1277 );
1278 ty::AliasTerm::new_from_args(
1279 tcx,
1280 assoc_item.def_id,
1281 alias_args,
1282 )
1283 });
1284
1285 let ty = projection_term.map_bound(|alias| {
1288 tcx.type_of(alias.def_id).instantiate(tcx, alias.args)
1289 });
1290 let ty = bounds::check_assoc_const_binding_type(
1291 self,
1292 constraint.ident,
1293 ty,
1294 constraint.hir_id,
1295 );
1296
1297 self.lower_const_arg(ct, ty).into()
1298 }
1299 };
1300 if term.references_error() {
1301 continue;
1302 }
1303 where_bounds.push(format!(
1305 " T: {trait}::{assoc_ident} = {term}",
1306 trait = bound.print_only_trait_path(),
1307 ));
1308 }
1309 hir::AssocItemConstraintKind::Bound { bounds: _ } => {}
1311 }
1312 } else {
1313 err.span_suggestion_verbose(
1314 span.with_hi(assoc_ident.span.lo()),
1315 "use fully-qualified syntax to disambiguate",
1316 format!("<{qself_str} as {}>::", bound.print_only_trait_path()),
1317 Applicability::MaybeIncorrect,
1318 );
1319 }
1320 } else {
1321 let trait_ =
1322 tcx.short_string(bound.print_only_trait_path(), err.long_ty_path());
1323 err.note(format!(
1324 "associated {assoc_kind_str} `{assoc_ident}` could derive from `{trait_}`",
1325 ));
1326 }
1327 }
1328 if !where_bounds.is_empty() {
1329 err.help(format!(
1330 "consider introducing a new type parameter `T` and adding `where` constraints:\
1331 \n where\n T: {qself_str},\n{}",
1332 where_bounds.join(",\n"),
1333 ));
1334 let reported = err.emit();
1335 return Err(reported);
1336 }
1337 err.emit();
1338 }
1339
1340 Ok(bound)
1341 }
1342
1343 x;#[instrument(level = "debug", skip_all, ret)]
1370 pub fn lower_type_relative_ty_path(
1371 &self,
1372 self_ty: Ty<'tcx>,
1373 hir_self_ty: &'tcx hir::Ty<'tcx>,
1374 segment: &'tcx hir::PathSegment<'tcx>,
1375 qpath_hir_id: HirId,
1376 span: Span,
1377 permit_variants: PermitVariants,
1378 ) -> Result<(Ty<'tcx>, DefKind, DefId), ErrorGuaranteed> {
1379 let tcx = self.tcx();
1380 match self.lower_type_relative_path(
1381 self_ty,
1382 hir_self_ty,
1383 segment,
1384 qpath_hir_id,
1385 span,
1386 LowerTypeRelativePathMode::Type(permit_variants),
1387 )? {
1388 TypeRelativePath::AssocItem(def_id, args) => {
1389 let alias_ty = ty::AliasTy::new_from_args(tcx, def_id, args);
1390 let ty = Ty::new_alias(tcx, alias_ty.kind(tcx), alias_ty);
1391 let ty = self.check_param_uses_if_mcg(ty, span, false);
1392 Ok((ty, tcx.def_kind(def_id), def_id))
1393 }
1394 TypeRelativePath::Variant { adt, variant_did } => {
1395 let adt = self.check_param_uses_if_mcg(adt, span, false);
1396 Ok((adt, DefKind::Variant, variant_did))
1397 }
1398 TypeRelativePath::Ctor { .. } => {
1399 let e = tcx.dcx().span_err(span, "expected type, found tuple constructor");
1400 Err(e)
1401 }
1402 }
1403 }
1404
1405 x;#[instrument(level = "debug", skip_all, ret)]
1407 fn lower_type_relative_const_path(
1408 &self,
1409 self_ty: Ty<'tcx>,
1410 hir_self_ty: &'tcx hir::Ty<'tcx>,
1411 segment: &'tcx hir::PathSegment<'tcx>,
1412 qpath_hir_id: HirId,
1413 span: Span,
1414 ) -> Result<Const<'tcx>, ErrorGuaranteed> {
1415 let tcx = self.tcx();
1416 match self.lower_type_relative_path(
1417 self_ty,
1418 hir_self_ty,
1419 segment,
1420 qpath_hir_id,
1421 span,
1422 LowerTypeRelativePathMode::Const,
1423 )? {
1424 TypeRelativePath::AssocItem(def_id, args) => {
1425 self.require_type_const_attribute(def_id, span)?;
1426 let ct = Const::new_unevaluated(tcx, ty::UnevaluatedConst::new(def_id, args));
1427 let ct = self.check_param_uses_if_mcg(ct, span, false);
1428 Ok(ct)
1429 }
1430 TypeRelativePath::Ctor { ctor_def_id, args } => match tcx.def_kind(ctor_def_id) {
1431 DefKind::Ctor(_, CtorKind::Fn) => {
1432 Ok(ty::Const::zero_sized(tcx, Ty::new_fn_def(tcx, ctor_def_id, args)))
1433 }
1434 DefKind::Ctor(ctor_of, CtorKind::Const) => {
1435 Ok(self.construct_const_ctor_value(ctor_def_id, ctor_of, args))
1436 }
1437 _ => unreachable!(),
1438 },
1439 TypeRelativePath::Variant { .. } => {
1442 span_bug!(span, "unexpected variant res for type associated const path")
1443 }
1444 }
1445 }
1446
1447 x;#[instrument(level = "debug", skip_all, ret)]
1449 fn lower_type_relative_path(
1450 &self,
1451 self_ty: Ty<'tcx>,
1452 hir_self_ty: &'tcx hir::Ty<'tcx>,
1453 segment: &'tcx hir::PathSegment<'tcx>,
1454 qpath_hir_id: HirId,
1455 span: Span,
1456 mode: LowerTypeRelativePathMode,
1457 ) -> Result<TypeRelativePath<'tcx>, ErrorGuaranteed> {
1458 debug!(%self_ty, ?segment.ident);
1459 let tcx = self.tcx();
1460
1461 let mut variant_def_id = None;
1463 if let Some(adt_def) = self.probe_adt(span, self_ty) {
1464 if adt_def.is_enum() {
1465 let variant_def = adt_def
1466 .variants()
1467 .iter()
1468 .find(|vd| tcx.hygienic_eq(segment.ident, vd.ident(tcx), adt_def.did()));
1469 if let Some(variant_def) = variant_def {
1470 if matches!(mode, LowerTypeRelativePathMode::Const)
1473 && let Some((_, ctor_def_id)) = variant_def.ctor
1474 {
1475 tcx.check_stability(variant_def.def_id, Some(qpath_hir_id), span, None);
1476 let _ = self.prohibit_generic_args(
1477 slice::from_ref(segment).iter(),
1478 GenericsArgsErrExtend::EnumVariant {
1479 qself: hir_self_ty,
1480 assoc_segment: segment,
1481 adt_def,
1482 },
1483 );
1484 let ty::Adt(_, enum_args) = self_ty.kind() else { unreachable!() };
1485 return Ok(TypeRelativePath::Ctor { ctor_def_id, args: enum_args });
1486 }
1487 if let PermitVariants::Yes = mode.permit_variants() {
1488 tcx.check_stability(variant_def.def_id, Some(qpath_hir_id), span, None);
1489 let _ = self.prohibit_generic_args(
1490 slice::from_ref(segment).iter(),
1491 GenericsArgsErrExtend::EnumVariant {
1492 qself: hir_self_ty,
1493 assoc_segment: segment,
1494 adt_def,
1495 },
1496 );
1497 return Ok(TypeRelativePath::Variant {
1498 adt: self_ty,
1499 variant_did: variant_def.def_id,
1500 });
1501 } else {
1502 variant_def_id = Some(variant_def.def_id);
1503 }
1504 }
1505 }
1506
1507 if let Some((did, args)) = self.probe_inherent_assoc_item(
1509 segment,
1510 adt_def.did(),
1511 self_ty,
1512 qpath_hir_id,
1513 span,
1514 mode.assoc_tag(),
1515 )? {
1516 return Ok(TypeRelativePath::AssocItem(did, args));
1517 }
1518 }
1519
1520 let (item_def_id, bound) = self.resolve_type_relative_path(
1521 self_ty,
1522 hir_self_ty,
1523 mode.assoc_tag(),
1524 segment,
1525 qpath_hir_id,
1526 span,
1527 variant_def_id,
1528 )?;
1529
1530 let (item_def_id, args) = self.lower_assoc_item_path(span, item_def_id, segment, bound)?;
1531
1532 if let Some(variant_def_id) = variant_def_id {
1533 tcx.node_span_lint(AMBIGUOUS_ASSOCIATED_ITEMS, qpath_hir_id, span, |lint| {
1534 lint.primary_message("ambiguous associated item");
1535 let mut could_refer_to = |kind: DefKind, def_id, also| {
1536 let note_msg = format!(
1537 "`{}` could{} refer to the {} defined here",
1538 segment.ident,
1539 also,
1540 tcx.def_kind_descr(kind, def_id)
1541 );
1542 lint.span_note(tcx.def_span(def_id), note_msg);
1543 };
1544
1545 could_refer_to(DefKind::Variant, variant_def_id, "");
1546 could_refer_to(mode.def_kind(), item_def_id, " also");
1547
1548 lint.span_suggestion(
1549 span,
1550 "use fully-qualified syntax",
1551 format!(
1552 "<{} as {}>::{}",
1553 self_ty,
1554 tcx.item_name(bound.def_id()),
1555 segment.ident
1556 ),
1557 Applicability::MachineApplicable,
1558 );
1559 });
1560 }
1561
1562 Ok(TypeRelativePath::AssocItem(item_def_id, args))
1563 }
1564
1565 fn resolve_type_relative_path(
1567 &self,
1568 self_ty: Ty<'tcx>,
1569 hir_self_ty: &'tcx hir::Ty<'tcx>,
1570 assoc_tag: ty::AssocTag,
1571 segment: &'tcx hir::PathSegment<'tcx>,
1572 qpath_hir_id: HirId,
1573 span: Span,
1574 variant_def_id: Option<DefId>,
1575 ) -> Result<(DefId, ty::PolyTraitRef<'tcx>), ErrorGuaranteed> {
1576 let tcx = self.tcx();
1577
1578 let self_ty_res = match hir_self_ty.kind {
1579 hir::TyKind::Path(hir::QPath::Resolved(_, path)) => path.res,
1580 _ => Res::Err,
1581 };
1582
1583 let bound = match (self_ty.kind(), self_ty_res) {
1585 (_, Res::SelfTyAlias { alias_to: impl_def_id, is_trait_impl: true, .. }) => {
1586 let trait_ref = tcx.impl_trait_ref(impl_def_id);
1589
1590 self.probe_single_bound_for_assoc_item(
1591 || {
1592 let trait_ref = ty::Binder::dummy(trait_ref.instantiate_identity());
1593 traits::supertraits(tcx, trait_ref)
1594 },
1595 AssocItemQSelf::SelfTyAlias,
1596 assoc_tag,
1597 segment.ident,
1598 span,
1599 None,
1600 )?
1601 }
1602 (
1603 &ty::Param(_),
1604 Res::SelfTyParam { trait_: param_did } | Res::Def(DefKind::TyParam, param_did),
1605 ) => self.probe_single_ty_param_bound_for_assoc_item(
1606 param_did.expect_local(),
1607 hir_self_ty.span,
1608 assoc_tag,
1609 segment.ident,
1610 span,
1611 )?,
1612 _ => {
1613 return Err(self.report_unresolved_type_relative_path(
1614 self_ty,
1615 hir_self_ty,
1616 assoc_tag,
1617 segment.ident,
1618 qpath_hir_id,
1619 span,
1620 variant_def_id,
1621 ));
1622 }
1623 };
1624
1625 let assoc_item = self
1626 .probe_assoc_item(segment.ident, assoc_tag, qpath_hir_id, span, bound.def_id())
1627 .expect("failed to find associated item");
1628
1629 Ok((assoc_item.def_id, bound))
1630 }
1631
1632 fn probe_inherent_assoc_item(
1634 &self,
1635 segment: &hir::PathSegment<'tcx>,
1636 adt_did: DefId,
1637 self_ty: Ty<'tcx>,
1638 block: HirId,
1639 span: Span,
1640 assoc_tag: ty::AssocTag,
1641 ) -> Result<Option<(DefId, GenericArgsRef<'tcx>)>, ErrorGuaranteed> {
1642 let tcx = self.tcx();
1643
1644 if !tcx.features().inherent_associated_types() {
1645 match assoc_tag {
1646 ty::AssocTag::Type => return Ok(None),
1651 ty::AssocTag::Const => {
1652 return Err(feature_err(
1656 &tcx.sess,
1657 sym::inherent_associated_types,
1658 span,
1659 "inherent associated types are unstable",
1660 )
1661 .emit());
1662 }
1663 ty::AssocTag::Fn => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1664 }
1665 }
1666
1667 let name = segment.ident;
1668 let candidates: Vec<_> = tcx
1669 .inherent_impls(adt_did)
1670 .iter()
1671 .filter_map(|&impl_| {
1672 let (item, scope) =
1673 self.probe_assoc_item_unchecked(name, assoc_tag, block, impl_)?;
1674 Some(InherentAssocCandidate { impl_, assoc_item: item.def_id, scope })
1675 })
1676 .collect();
1677
1678 if candidates.is_empty() {
1683 return Ok(None);
1684 }
1685
1686 let (applicable_candidates, fulfillment_errors) =
1687 self.select_inherent_assoc_candidates(span, self_ty, candidates.clone());
1688
1689 let InherentAssocCandidate { impl_, assoc_item, scope: def_scope } =
1691 match &applicable_candidates[..] {
1692 &[] => Err(self.report_unresolved_inherent_assoc_item(
1693 name,
1694 self_ty,
1695 candidates,
1696 fulfillment_errors,
1697 span,
1698 assoc_tag,
1699 )),
1700
1701 &[applicable_candidate] => Ok(applicable_candidate),
1702
1703 &[_, ..] => Err(self.report_ambiguous_inherent_assoc_item(
1704 name,
1705 candidates.into_iter().map(|cand| cand.assoc_item).collect(),
1706 span,
1707 )),
1708 }?;
1709
1710 self.check_assoc_item(assoc_item, name, def_scope, block, span);
1713
1714 let parent_args = ty::GenericArgs::identity_for_item(tcx, impl_);
1718 let args = self.lower_generic_args_of_assoc_item(span, assoc_item, segment, parent_args);
1719 let args = tcx.mk_args_from_iter(
1720 std::iter::once(ty::GenericArg::from(self_ty))
1721 .chain(args.into_iter().skip(parent_args.len())),
1722 );
1723
1724 Ok(Some((assoc_item, args)))
1725 }
1726
1727 fn probe_assoc_item(
1731 &self,
1732 ident: Ident,
1733 assoc_tag: ty::AssocTag,
1734 block: HirId,
1735 span: Span,
1736 scope: DefId,
1737 ) -> Option<ty::AssocItem> {
1738 let (item, scope) = self.probe_assoc_item_unchecked(ident, assoc_tag, block, scope)?;
1739 self.check_assoc_item(item.def_id, ident, scope, block, span);
1740 Some(item)
1741 }
1742
1743 fn probe_assoc_item_unchecked(
1748 &self,
1749 ident: Ident,
1750 assoc_tag: ty::AssocTag,
1751 block: HirId,
1752 scope: DefId,
1753 ) -> Option<(ty::AssocItem, DefId)> {
1754 let tcx = self.tcx();
1755
1756 let (ident, def_scope) = tcx.adjust_ident_and_get_scope(ident, scope, block);
1757 let item = tcx
1761 .associated_items(scope)
1762 .filter_by_name_unhygienic(ident.name)
1763 .find(|i| i.tag() == assoc_tag && i.ident(tcx).normalize_to_macros_2_0() == ident)?;
1764
1765 Some((*item, def_scope))
1766 }
1767
1768 fn check_assoc_item(
1770 &self,
1771 item_def_id: DefId,
1772 ident: Ident,
1773 scope: DefId,
1774 block: HirId,
1775 span: Span,
1776 ) {
1777 let tcx = self.tcx();
1778
1779 if !tcx.visibility(item_def_id).is_accessible_from(scope, tcx) {
1780 self.dcx().emit_err(crate::errors::AssocItemIsPrivate {
1781 span,
1782 kind: tcx.def_descr(item_def_id),
1783 name: ident,
1784 defined_here_label: tcx.def_span(item_def_id),
1785 });
1786 }
1787
1788 tcx.check_stability(item_def_id, Some(block), span, None);
1789 }
1790
1791 fn probe_traits_that_match_assoc_ty(
1792 &self,
1793 qself_ty: Ty<'tcx>,
1794 assoc_ident: Ident,
1795 ) -> Vec<String> {
1796 let tcx = self.tcx();
1797
1798 let infcx_;
1801 let infcx = if let Some(infcx) = self.infcx() {
1802 infcx
1803 } else {
1804 if !!qself_ty.has_infer() {
::core::panicking::panic("assertion failed: !qself_ty.has_infer()")
};assert!(!qself_ty.has_infer());
1805 infcx_ = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
1806 &infcx_
1807 };
1808
1809 tcx.all_traits_including_private()
1810 .filter(|trait_def_id| {
1811 tcx.associated_items(*trait_def_id)
1813 .in_definition_order()
1814 .any(|i| {
1815 i.is_type()
1816 && !i.is_impl_trait_in_trait()
1817 && i.ident(tcx).normalize_to_macros_2_0() == assoc_ident
1818 })
1819 && tcx.visibility(*trait_def_id)
1821 .is_accessible_from(self.item_def_id(), tcx)
1822 && tcx.all_impls(*trait_def_id)
1823 .any(|impl_def_id| {
1824 let header = tcx.impl_trait_header(impl_def_id);
1825 let trait_ref = header.trait_ref.instantiate(
1826 tcx,
1827 infcx.fresh_args_for_item(DUMMY_SP, impl_def_id),
1828 );
1829
1830 let value = fold_regions(tcx, qself_ty, |_, _| tcx.lifetimes.re_erased);
1831 if value.has_escaping_bound_vars() {
1833 return false;
1834 }
1835 infcx
1836 .can_eq(
1837 ty::ParamEnv::empty(),
1838 trait_ref.self_ty(),
1839 value,
1840 ) && header.polarity != ty::ImplPolarity::Negative
1841 })
1842 })
1843 .map(|trait_def_id| tcx.def_path_str(trait_def_id))
1844 .collect()
1845 }
1846
1847 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("lower_resolved_assoc_ty_path",
"rustc_hir_analysis::hir_ty_lowering",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
::tracing_core::__macro_support::Option::Some(1848u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&[],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{ meta.fields().value_set(&[]) })
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Ty<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{
match self.lower_resolved_assoc_item_path(span, opt_self_ty,
item_def_id, trait_segment, item_segment,
ty::AssocTag::Type) {
Ok((item_def_id, item_args)) => {
Ty::new_projection_from_args(self.tcx(), item_def_id,
item_args)
}
Err(guar) => Ty::new_error(self.tcx(), guar),
}
}
}
}#[instrument(level = "debug", skip_all)]
1849 fn lower_resolved_assoc_ty_path(
1850 &self,
1851 span: Span,
1852 opt_self_ty: Option<Ty<'tcx>>,
1853 item_def_id: DefId,
1854 trait_segment: Option<&hir::PathSegment<'tcx>>,
1855 item_segment: &hir::PathSegment<'tcx>,
1856 ) -> Ty<'tcx> {
1857 match self.lower_resolved_assoc_item_path(
1858 span,
1859 opt_self_ty,
1860 item_def_id,
1861 trait_segment,
1862 item_segment,
1863 ty::AssocTag::Type,
1864 ) {
1865 Ok((item_def_id, item_args)) => {
1866 Ty::new_projection_from_args(self.tcx(), item_def_id, item_args)
1867 }
1868 Err(guar) => Ty::new_error(self.tcx(), guar),
1869 }
1870 }
1871
1872 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("lower_resolved_assoc_const_path",
"rustc_hir_analysis::hir_ty_lowering",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
::tracing_core::__macro_support::Option::Some(1873u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&[],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{ meta.fields().value_set(&[]) })
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return:
Result<Const<'tcx>, ErrorGuaranteed> = loop {};
return __tracing_attr_fake_return;
}
{
let (item_def_id, item_args) =
self.lower_resolved_assoc_item_path(span, opt_self_ty,
item_def_id, trait_segment, item_segment,
ty::AssocTag::Const)?;
self.require_type_const_attribute(item_def_id, span)?;
let uv = ty::UnevaluatedConst::new(item_def_id, item_args);
Ok(Const::new_unevaluated(self.tcx(), uv))
}
}
}#[instrument(level = "debug", skip_all)]
1874 fn lower_resolved_assoc_const_path(
1875 &self,
1876 span: Span,
1877 opt_self_ty: Option<Ty<'tcx>>,
1878 item_def_id: DefId,
1879 trait_segment: Option<&hir::PathSegment<'tcx>>,
1880 item_segment: &hir::PathSegment<'tcx>,
1881 ) -> Result<Const<'tcx>, ErrorGuaranteed> {
1882 let (item_def_id, item_args) = self.lower_resolved_assoc_item_path(
1883 span,
1884 opt_self_ty,
1885 item_def_id,
1886 trait_segment,
1887 item_segment,
1888 ty::AssocTag::Const,
1889 )?;
1890 self.require_type_const_attribute(item_def_id, span)?;
1891 let uv = ty::UnevaluatedConst::new(item_def_id, item_args);
1892 Ok(Const::new_unevaluated(self.tcx(), uv))
1893 }
1894
1895 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("lower_resolved_assoc_item_path",
"rustc_hir_analysis::hir_ty_lowering",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
::tracing_core::__macro_support::Option::Some(1896u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&[],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{ meta.fields().value_set(&[]) })
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return:
Result<(DefId, GenericArgsRef<'tcx>), ErrorGuaranteed> =
loop {};
return __tracing_attr_fake_return;
}
{
let tcx = self.tcx();
let trait_def_id = tcx.parent(item_def_id);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs:1909",
"rustc_hir_analysis::hir_ty_lowering",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
::tracing_core::__macro_support::Option::Some(1909u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&["trait_def_id"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&trait_def_id)
as &dyn Value))])
});
} else { ; }
};
let Some(self_ty) =
opt_self_ty else {
return Err(self.report_missing_self_ty_for_resolved_path(trait_def_id,
span, item_segment, assoc_tag));
};
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs:1919",
"rustc_hir_analysis::hir_ty_lowering",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
::tracing_core::__macro_support::Option::Some(1919u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&["self_ty"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&self_ty) as
&dyn Value))])
});
} else { ; }
};
let trait_ref =
self.lower_mono_trait_ref(span, trait_def_id, self_ty,
trait_segment.unwrap(), false);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs:1923",
"rustc_hir_analysis::hir_ty_lowering",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
::tracing_core::__macro_support::Option::Some(1923u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&["trait_ref"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&trait_ref)
as &dyn Value))])
});
} else { ; }
};
let item_args =
self.lower_generic_args_of_assoc_item(span, item_def_id,
item_segment, trait_ref.args);
Ok((item_def_id, item_args))
}
}
}#[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 if !!segments.is_empty() {
::core::panicking::panic("assertion failed: !segments.is_empty()")
};assert!(!segments.is_empty());
2029 let last = segments.len() - 1;
2030
2031 let mut generic_segments = ::alloc::vec::Vec::new()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 if true {
if !adt_def.is_enum() {
::core::panicking::panic("assertion failed: adt_def.is_enum()")
};
};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 => ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected definition kind {0:?} for {1:?}",
kind, def_id))bug!("unexpected definition kind {:?} for {:?}", kind, def_id),
2093 }
2094
2095 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs:2095",
"rustc_hir_analysis::hir_ty_lowering",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
::tracing_core::__macro_support::Option::Some(2095u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&["generic_segments"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&generic_segments)
as &dyn Value))])
});
} else { ; }
};debug!(?generic_segments);
2096
2097 generic_segments
2098 }
2099
2100 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("lower_resolved_ty_path",
"rustc_hir_analysis::hir_ty_lowering",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
::tracing_core::__macro_support::Option::Some(2101u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&[],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{ meta.fields().value_set(&[]) })
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Ty<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs:2109",
"rustc_hir_analysis::hir_ty_lowering",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
::tracing_core::__macro_support::Option::Some(2109u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&["path.res",
"opt_self_ty", "path.segments"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&path.res)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&opt_self_ty)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&path.segments)
as &dyn Value))])
});
} else { ; }
};
let tcx = self.tcx();
let span = path.span;
match path.res {
Res::Def(DefKind::OpaqueTy, did) => {
match tcx.opaque_ty_origin(did) {
hir::OpaqueTyOrigin::TyAlias { .. } => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val,
"hir::OpaqueTyOrigin::TyAlias { .. }",
::core::option::Option::None);
}
};
let [leading_segments @ .., segment] =
path.segments else {
::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))
};
let _ =
self.prohibit_generic_args(leading_segments.iter(),
GenericsArgsErrExtend::OpaqueTy);
let args =
self.lower_generic_args_of_path_segment(span, did, segment);
Ty::new_opaque(tcx, did, args)
}
Res::Def(DefKind::Enum | DefKind::TyAlias | DefKind::Struct |
DefKind::Union | DefKind::ForeignTy, did) => {
match (&opt_self_ty, &None) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
};
let [leading_segments @ .., segment] =
path.segments else {
::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))
};
let _ =
self.prohibit_generic_args(leading_segments.iter(),
GenericsArgsErrExtend::None);
self.lower_path_segment(span, did, segment)
}
Res::Def(kind @ DefKind::Variant, def_id) if
let PermitVariants::Yes = permit_variants => {
match (&opt_self_ty, &None) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
};
let generic_segments =
self.probe_generic_path_segments(path.segments, None, kind,
def_id, span);
let indices: FxHashSet<_> =
generic_segments.iter().map(|GenericPathSegment(_, index)|
index).collect();
let _ =
self.prohibit_generic_args(path.segments.iter().enumerate().filter_map(|(index,
seg)|
{
if !indices.contains(&index) { Some(seg) } else { None }
}), GenericsArgsErrExtend::DefVariant(&path.segments));
let &GenericPathSegment(def_id, index) =
generic_segments.last().unwrap();
self.lower_path_segment(span, def_id, &path.segments[index])
}
Res::Def(DefKind::TyParam, def_id) => {
match (&opt_self_ty, &None) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
};
let _ =
self.prohibit_generic_args(path.segments.iter(),
GenericsArgsErrExtend::Param(def_id));
self.lower_ty_param(hir_id)
}
Res::SelfTyParam { .. } => {
match (&opt_self_ty, &None) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
};
let _ =
self.prohibit_generic_args(path.segments.iter(),
if let [hir::PathSegment { args: Some(args), ident, .. }] =
&path.segments {
GenericsArgsErrExtend::SelfTyParam(ident.span.shrink_to_hi().to(args.span_ext))
} else { GenericsArgsErrExtend::None });
self.check_param_uses_if_mcg(tcx.types.self_param, span,
false)
}
Res::SelfTyAlias { alias_to: def_id, .. } => {
match (&opt_self_ty, &None) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
};
let ty =
tcx.at(span).type_of(def_id).instantiate_identity();
let _ =
self.prohibit_generic_args(path.segments.iter(),
GenericsArgsErrExtend::SelfTyAlias { def_id, span });
self.check_param_uses_if_mcg(ty, span, true)
}
Res::Def(DefKind::AssocTy, def_id) => {
let trait_segment =
if let [modules @ .., trait_, _item] = path.segments {
let _ =
self.prohibit_generic_args(modules.iter(),
GenericsArgsErrExtend::None);
Some(trait_)
} else { None };
self.lower_resolved_assoc_ty_path(span, opt_self_ty, def_id,
trait_segment, path.segments.last().unwrap())
}
Res::PrimTy(prim_ty) => {
match (&opt_self_ty, &None) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
};
let _ =
self.prohibit_generic_args(path.segments.iter(),
GenericsArgsErrExtend::PrimTy(prim_ty));
match prim_ty {
hir::PrimTy::Bool => tcx.types.bool,
hir::PrimTy::Char => tcx.types.char,
hir::PrimTy::Int(it) => Ty::new_int(tcx, it),
hir::PrimTy::Uint(uit) => Ty::new_uint(tcx, uit),
hir::PrimTy::Float(ft) => Ty::new_float(tcx, ft),
hir::PrimTy::Str => tcx.types.str_,
}
}
Res::Err => {
let e =
self.tcx().dcx().span_delayed_bug(path.span,
"path with `Res::Err` but no error emitted");
Ty::new_error(tcx, e)
}
Res::Def(..) => {
match (&path.segments.get(0).map(|seg| seg.ident.name),
&Some(kw::SelfUpper)) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val,
::core::option::Option::Some(format_args!("only expected incorrect resolution for `Self`")));
}
}
};
Ty::new_error(self.tcx(),
self.dcx().span_delayed_bug(span,
"incorrect resolution for `Self`"))
}
_ =>
::rustc_middle::util::bug::span_bug_fmt(span,
format_args!("unexpected resolution: {0:?}", path.res)),
}
}
}
}#[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 => ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected bound var resolution for {0:?}: {1:?}",
hir_id, 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::new(ty::BoundVar::from_u32(index)),
2294 ),
2295 Some(rbv::ResolvedArg::Error(guar)) => ty::Const::new_error(tcx, guar),
2296 arg => ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected bound var resolution for {0:?}: {1:?}",
path_hir_id, 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 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("lower_const_arg",
"rustc_hir_analysis::hir_ty_lowering",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
::tracing_core::__macro_support::Option::Some(2302u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&["const_arg", "ty"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&const_arg)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Const<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{
let tcx = self.tcx();
if let hir::ConstArgKind::Anon(anon) = &const_arg.kind {
if tcx.features().generic_const_parameter_types() &&
(ty.has_free_regions() || ty.has_erased_regions()) {
let e =
self.dcx().span_err(const_arg.span,
"anonymous constants with lifetimes in their type are not yet supported");
tcx.feed_anon_const_type(anon.def_id,
ty::EarlyBinder::bind(Ty::new_error(tcx, e)));
return ty::Const::new_error(tcx, e);
}
if ty.has_non_region_infer() {
let e =
self.dcx().span_err(const_arg.span,
"anonymous constants with inferred types are not yet supported");
tcx.feed_anon_const_type(anon.def_id,
ty::EarlyBinder::bind(Ty::new_error(tcx, e)));
return ty::Const::new_error(tcx, e);
}
if ty.has_non_region_param() {
let e =
self.dcx().span_err(const_arg.span,
"anonymous constants referencing generics are not yet supported");
tcx.feed_anon_const_type(anon.def_id,
ty::EarlyBinder::bind(Ty::new_error(tcx, e)));
return ty::Const::new_error(tcx, e);
}
tcx.feed_anon_const_type(anon.def_id,
ty::EarlyBinder::bind(ty));
}
let hir_id = const_arg.hir_id;
match const_arg.kind {
hir::ConstArgKind::Tup(exprs) =>
self.lower_const_arg_tup(exprs, ty, const_arg.span),
hir::ConstArgKind::Path(hir::QPath::Resolved(maybe_qself,
path)) => {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs:2354",
"rustc_hir_analysis::hir_ty_lowering",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
::tracing_core::__macro_support::Option::Some(2354u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&["maybe_qself",
"path"], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&maybe_qself)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&path) as
&dyn Value))])
});
} else { ; }
};
let opt_self_ty =
maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
self.lower_resolved_const_path(opt_self_ty, path, hir_id)
}
hir::ConstArgKind::Path(hir::QPath::TypeRelative(hir_self_ty,
segment)) => {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs:2359",
"rustc_hir_analysis::hir_ty_lowering",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
::tracing_core::__macro_support::Option::Some(2359u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&["hir_self_ty",
"segment"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&hir_self_ty)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&segment) as
&dyn Value))])
});
} else { ; }
};
let self_ty = self.lower_ty(hir_self_ty);
self.lower_type_relative_const_path(self_ty, hir_self_ty,
segment, hir_id,
const_arg.span).unwrap_or_else(|guar|
Const::new_error(tcx, guar))
}
hir::ConstArgKind::Struct(qpath, inits) => {
self.lower_const_arg_struct(hir_id, qpath, inits,
const_arg.span)
}
hir::ConstArgKind::TupleCall(qpath, args) => {
self.lower_const_arg_tuple_call(hir_id, qpath, args,
const_arg.span)
}
hir::ConstArgKind::Array(array_expr) =>
self.lower_const_arg_array(array_expr, ty),
hir::ConstArgKind::Anon(anon) =>
self.lower_const_arg_anon(anon),
hir::ConstArgKind::Infer(()) =>
self.ct_infer(None, const_arg.span),
hir::ConstArgKind::Error(e) => ty::Const::new_error(tcx, e),
hir::ConstArgKind::Literal { lit, negated } => {
self.lower_const_arg_literal(&lit, negated, ty,
const_arg.span)
}
}
}
}
}#[instrument(skip(self), level = "debug")]
2303 pub fn lower_const_arg(&self, const_arg: &hir::ConstArg<'tcx>, ty: Ty<'tcx>) -> Const<'tcx> {
2304 let tcx = self.tcx();
2305
2306 if let hir::ConstArgKind::Anon(anon) = &const_arg.kind {
2307 if tcx.features().generic_const_parameter_types()
2316 && (ty.has_free_regions() || ty.has_erased_regions())
2317 {
2318 let e = self.dcx().span_err(
2319 const_arg.span,
2320 "anonymous constants with lifetimes in their type are not yet supported",
2321 );
2322 tcx.feed_anon_const_type(anon.def_id, ty::EarlyBinder::bind(Ty::new_error(tcx, e)));
2323 return ty::Const::new_error(tcx, e);
2324 }
2325 if ty.has_non_region_infer() {
2329 let e = self.dcx().span_err(
2330 const_arg.span,
2331 "anonymous constants with inferred types are not yet supported",
2332 );
2333 tcx.feed_anon_const_type(anon.def_id, ty::EarlyBinder::bind(Ty::new_error(tcx, e)));
2334 return ty::Const::new_error(tcx, e);
2335 }
2336 if ty.has_non_region_param() {
2339 let e = self.dcx().span_err(
2340 const_arg.span,
2341 "anonymous constants referencing generics are not yet supported",
2342 );
2343 tcx.feed_anon_const_type(anon.def_id, ty::EarlyBinder::bind(Ty::new_error(tcx, e)));
2344 return ty::Const::new_error(tcx, e);
2345 }
2346
2347 tcx.feed_anon_const_type(anon.def_id, ty::EarlyBinder::bind(ty));
2348 }
2349
2350 let hir_id = const_arg.hir_id;
2351 match const_arg.kind {
2352 hir::ConstArgKind::Tup(exprs) => self.lower_const_arg_tup(exprs, ty, const_arg.span),
2353 hir::ConstArgKind::Path(hir::QPath::Resolved(maybe_qself, path)) => {
2354 debug!(?maybe_qself, ?path);
2355 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
2356 self.lower_resolved_const_path(opt_self_ty, path, hir_id)
2357 }
2358 hir::ConstArgKind::Path(hir::QPath::TypeRelative(hir_self_ty, segment)) => {
2359 debug!(?hir_self_ty, ?segment);
2360 let self_ty = self.lower_ty(hir_self_ty);
2361 self.lower_type_relative_const_path(
2362 self_ty,
2363 hir_self_ty,
2364 segment,
2365 hir_id,
2366 const_arg.span,
2367 )
2368 .unwrap_or_else(|guar| Const::new_error(tcx, guar))
2369 }
2370 hir::ConstArgKind::Struct(qpath, inits) => {
2371 self.lower_const_arg_struct(hir_id, qpath, inits, const_arg.span)
2372 }
2373 hir::ConstArgKind::TupleCall(qpath, args) => {
2374 self.lower_const_arg_tuple_call(hir_id, qpath, args, const_arg.span)
2375 }
2376 hir::ConstArgKind::Array(array_expr) => self.lower_const_arg_array(array_expr, ty),
2377 hir::ConstArgKind::Anon(anon) => self.lower_const_arg_anon(anon),
2378 hir::ConstArgKind::Infer(()) => self.ct_infer(None, const_arg.span),
2379 hir::ConstArgKind::Error(e) => ty::Const::new_error(tcx, e),
2380 hir::ConstArgKind::Literal { lit, negated } => {
2381 self.lower_const_arg_literal(&lit, negated, ty, const_arg.span)
2382 }
2383 }
2384 }
2385
2386 fn lower_const_arg_array(
2387 &self,
2388 array_expr: &'tcx hir::ConstArgArrayExpr<'tcx>,
2389 ty: Ty<'tcx>,
2390 ) -> Const<'tcx> {
2391 let tcx = self.tcx();
2392
2393 let ty::Array(elem_ty, _) = ty.kind() else {
2394 let e = tcx
2395 .dcx()
2396 .span_err(array_expr.span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected `{0}`, found const array",
ty))
})format!("expected `{}`, found const array", ty));
2397 return Const::new_error(tcx, e);
2398 };
2399
2400 let elems = array_expr
2401 .elems
2402 .iter()
2403 .map(|elem| self.lower_const_arg(elem, *elem_ty))
2404 .collect::<Vec<_>>();
2405
2406 let valtree = ty::ValTree::from_branches(tcx, elems);
2407
2408 ty::Const::new_value(tcx, valtree, ty)
2409 }
2410
2411 fn lower_const_arg_tuple_call(
2412 &self,
2413 hir_id: HirId,
2414 qpath: hir::QPath<'tcx>,
2415 args: &'tcx [&'tcx hir::ConstArg<'tcx>],
2416 span: Span,
2417 ) -> Const<'tcx> {
2418 let tcx = self.tcx();
2419
2420 let non_adt_or_variant_res = || {
2421 let e = tcx.dcx().span_err(span, "tuple constructor with invalid base path");
2422 ty::Const::new_error(tcx, e)
2423 };
2424
2425 let ctor_const = match qpath {
2426 hir::QPath::Resolved(maybe_qself, path) => {
2427 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
2428 self.lower_resolved_const_path(opt_self_ty, path, hir_id)
2429 }
2430 hir::QPath::TypeRelative(hir_self_ty, segment) => {
2431 let self_ty = self.lower_ty(hir_self_ty);
2432 match self.lower_type_relative_const_path(
2433 self_ty,
2434 hir_self_ty,
2435 segment,
2436 hir_id,
2437 span,
2438 ) {
2439 Ok(c) => c,
2440 Err(_) => return non_adt_or_variant_res(),
2441 }
2442 }
2443 };
2444
2445 let Some(value) = ctor_const.try_to_value() else {
2446 return non_adt_or_variant_res();
2447 };
2448
2449 let (adt_def, adt_args, variant_did) = match value.ty.kind() {
2450 ty::FnDef(def_id, fn_args)
2451 if let DefKind::Ctor(CtorOf::Variant, _) = tcx.def_kind(*def_id) =>
2452 {
2453 let parent_did = tcx.parent(*def_id);
2454 let enum_did = tcx.parent(parent_did);
2455 (tcx.adt_def(enum_did), fn_args, parent_did)
2456 }
2457 ty::FnDef(def_id, fn_args)
2458 if let DefKind::Ctor(CtorOf::Struct, _) = tcx.def_kind(*def_id) =>
2459 {
2460 let parent_did = tcx.parent(*def_id);
2461 (tcx.adt_def(parent_did), fn_args, parent_did)
2462 }
2463 _ => return non_adt_or_variant_res(),
2464 };
2465
2466 let variant_def = adt_def.variant_with_id(variant_did);
2467 let variant_idx = adt_def.variant_index_with_id(variant_did).as_u32();
2468
2469 if args.len() != variant_def.fields.len() {
2470 let e = tcx.dcx().span_err(
2471 span,
2472 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("tuple constructor has {0} arguments but {1} were provided",
variant_def.fields.len(), args.len()))
})format!(
2473 "tuple constructor has {} arguments but {} were provided",
2474 variant_def.fields.len(),
2475 args.len()
2476 ),
2477 );
2478 return ty::Const::new_error(tcx, e);
2479 }
2480
2481 let fields = variant_def
2482 .fields
2483 .iter()
2484 .zip(args)
2485 .map(|(field_def, arg)| {
2486 self.lower_const_arg(arg, tcx.type_of(field_def.did).instantiate(tcx, adt_args))
2487 })
2488 .collect::<Vec<_>>();
2489
2490 let opt_discr_const = if adt_def.is_enum() {
2491 let valtree = ty::ValTree::from_scalar_int(tcx, variant_idx.into());
2492 Some(ty::Const::new_value(tcx, valtree, tcx.types.u32))
2493 } else {
2494 None
2495 };
2496
2497 let valtree = ty::ValTree::from_branches(tcx, opt_discr_const.into_iter().chain(fields));
2498 let adt_ty = Ty::new_adt(tcx, adt_def, adt_args);
2499 ty::Const::new_value(tcx, valtree, adt_ty)
2500 }
2501
2502 fn lower_const_arg_tup(
2503 &self,
2504 exprs: &'tcx [&'tcx hir::ConstArg<'tcx>],
2505 ty: Ty<'tcx>,
2506 span: Span,
2507 ) -> Const<'tcx> {
2508 let tcx = self.tcx();
2509
2510 let ty::Tuple(tys) = ty.kind() else {
2511 let e = tcx.dcx().span_err(span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected `{0}`, found const tuple",
ty))
})format!("expected `{}`, found const tuple", ty));
2512 return Const::new_error(tcx, e);
2513 };
2514
2515 let exprs = exprs
2516 .iter()
2517 .zip(tys.iter())
2518 .map(|(expr, ty)| self.lower_const_arg(expr, ty))
2519 .collect::<Vec<_>>();
2520
2521 let valtree = ty::ValTree::from_branches(tcx, exprs);
2522 ty::Const::new_value(tcx, valtree, ty)
2523 }
2524
2525 fn lower_const_arg_struct(
2526 &self,
2527 hir_id: HirId,
2528 qpath: hir::QPath<'tcx>,
2529 inits: &'tcx [&'tcx hir::ConstArgExprField<'tcx>],
2530 span: Span,
2531 ) -> Const<'tcx> {
2532 let tcx = self.tcx();
2535
2536 let non_adt_or_variant_res = || {
2537 let e = tcx.dcx().span_err(span, "struct expression with invalid base path");
2538 ty::Const::new_error(tcx, e)
2539 };
2540
2541 let (ty, variant_did) = match qpath {
2542 hir::QPath::Resolved(maybe_qself, path) => {
2543 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs:2543",
"rustc_hir_analysis::hir_ty_lowering",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
::tracing_core::__macro_support::Option::Some(2543u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&["maybe_qself",
"path"], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&maybe_qself)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&path) as
&dyn Value))])
});
} else { ; }
};debug!(?maybe_qself, ?path);
2544 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
2545 let ty =
2546 self.lower_resolved_ty_path(opt_self_ty, path, hir_id, PermitVariants::Yes);
2547 let variant_did = match path.res {
2548 Res::Def(DefKind::Variant | DefKind::Struct, did) => did,
2549 _ => return non_adt_or_variant_res(),
2550 };
2551
2552 (ty, variant_did)
2553 }
2554 hir::QPath::TypeRelative(hir_self_ty, segment) => {
2555 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs:2555",
"rustc_hir_analysis::hir_ty_lowering",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
::tracing_core::__macro_support::Option::Some(2555u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&["hir_self_ty",
"segment"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&hir_self_ty)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&segment) as
&dyn Value))])
});
} else { ; }
};debug!(?hir_self_ty, ?segment);
2556 let self_ty = self.lower_ty(hir_self_ty);
2557 let opt_res = self.lower_type_relative_ty_path(
2558 self_ty,
2559 hir_self_ty,
2560 segment,
2561 hir_id,
2562 span,
2563 PermitVariants::Yes,
2564 );
2565
2566 let (ty, _, res_def_id) = match opt_res {
2567 Ok(r @ (_, DefKind::Variant | DefKind::Struct, _)) => r,
2568 Ok(_) => return non_adt_or_variant_res(),
2569 Err(e) => return ty::Const::new_error(tcx, e),
2570 };
2571
2572 (ty, res_def_id)
2573 }
2574 };
2575
2576 let ty::Adt(adt_def, adt_args) = ty.kind() else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
2577
2578 let variant_def = adt_def.variant_with_id(variant_did);
2579 let variant_idx = adt_def.variant_index_with_id(variant_did).as_u32();
2580
2581 let fields = variant_def
2582 .fields
2583 .iter()
2584 .map(|field_def| {
2585 let mut init_expr =
2588 inits.iter().filter(|init_expr| init_expr.field.name == field_def.name);
2589
2590 match init_expr.next() {
2591 Some(expr) => {
2592 if let Some(expr) = init_expr.next() {
2593 let e = tcx.dcx().span_err(
2594 expr.span,
2595 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("struct expression with multiple initialisers for `{0}`",
field_def.name))
})format!(
2596 "struct expression with multiple initialisers for `{}`",
2597 field_def.name,
2598 ),
2599 );
2600 return ty::Const::new_error(tcx, e);
2601 }
2602
2603 self.lower_const_arg(
2604 expr.expr,
2605 tcx.type_of(field_def.did).instantiate(tcx, adt_args),
2606 )
2607 }
2608 None => {
2609 let e = tcx.dcx().span_err(
2610 span,
2611 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("struct expression with missing field initialiser for `{0}`",
field_def.name))
})format!(
2612 "struct expression with missing field initialiser for `{}`",
2613 field_def.name
2614 ),
2615 );
2616 ty::Const::new_error(tcx, e)
2617 }
2618 }
2619 })
2620 .collect::<Vec<_>>();
2621
2622 let opt_discr_const = if adt_def.is_enum() {
2623 let valtree = ty::ValTree::from_scalar_int(tcx, variant_idx.into());
2624 Some(ty::Const::new_value(tcx, valtree, tcx.types.u32))
2625 } else {
2626 None
2627 };
2628
2629 let valtree = ty::ValTree::from_branches(tcx, opt_discr_const.into_iter().chain(fields));
2630 ty::Const::new_value(tcx, valtree, ty)
2631 }
2632
2633 fn lower_resolved_const_path(
2635 &self,
2636 opt_self_ty: Option<Ty<'tcx>>,
2637 path: &hir::Path<'tcx>,
2638 hir_id: HirId,
2639 ) -> Const<'tcx> {
2640 let tcx = self.tcx();
2641 let span = path.span;
2642 let ct = match path.res {
2643 Res::Def(DefKind::ConstParam, def_id) => {
2644 match (&opt_self_ty, &None) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::None);
}
}
};assert_eq!(opt_self_ty, None);
2645 let _ = self.prohibit_generic_args(
2646 path.segments.iter(),
2647 GenericsArgsErrExtend::Param(def_id),
2648 );
2649 self.lower_const_param(def_id, hir_id)
2650 }
2651 Res::Def(DefKind::Const, did) => {
2652 if let Err(guar) = self.require_type_const_attribute(did, span) {
2653 return Const::new_error(self.tcx(), guar);
2654 }
2655
2656 match (&opt_self_ty, &None) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::None);
}
}
};assert_eq!(opt_self_ty, None);
2657 let [leading_segments @ .., segment] = path.segments else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
2658 let _ = self
2659 .prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
2660 let args = self.lower_generic_args_of_path_segment(span, did, segment);
2661 ty::Const::new_unevaluated(tcx, ty::UnevaluatedConst::new(did, args))
2662 }
2663 Res::Def(DefKind::Ctor(ctor_of, CtorKind::Const), did) => {
2664 match (&opt_self_ty, &None) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::None);
}
}
};assert_eq!(opt_self_ty, None);
2665 let [leading_segments @ .., segment] = path.segments else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
2666 let _ = self
2667 .prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
2668
2669 let parent_did = tcx.parent(did);
2670 let generics_did = match ctor_of {
2671 CtorOf::Variant => tcx.parent(parent_did),
2672 CtorOf::Struct => parent_did,
2673 };
2674 let args = self.lower_generic_args_of_path_segment(span, generics_did, segment);
2675
2676 self.construct_const_ctor_value(did, ctor_of, args)
2677 }
2678 Res::Def(DefKind::Ctor(_, CtorKind::Fn), did) => {
2679 match (&opt_self_ty, &None) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::None);
}
}
};assert_eq!(opt_self_ty, None);
2680 let [leading_segments @ .., segment] = path.segments else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
2681 let _ = self
2682 .prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
2683 let parent_did = tcx.parent(did);
2684 let generics_did = if let DefKind::Ctor(CtorOf::Variant, _) = tcx.def_kind(did) {
2685 tcx.parent(parent_did)
2686 } else {
2687 parent_did
2688 };
2689 let args = self.lower_generic_args_of_path_segment(span, generics_did, segment);
2690 ty::Const::zero_sized(tcx, Ty::new_fn_def(tcx, did, args))
2691 }
2692 Res::Def(DefKind::AssocConst, did) => {
2693 let trait_segment = if let [modules @ .., trait_, _item] = path.segments {
2694 let _ = self.prohibit_generic_args(modules.iter(), GenericsArgsErrExtend::None);
2695 Some(trait_)
2696 } else {
2697 None
2698 };
2699 self.lower_resolved_assoc_const_path(
2700 span,
2701 opt_self_ty,
2702 did,
2703 trait_segment,
2704 path.segments.last().unwrap(),
2705 )
2706 .unwrap_or_else(|guar| Const::new_error(tcx, guar))
2707 }
2708 Res::Def(DefKind::Static { .. }, _) => {
2709 ::rustc_middle::util::bug::span_bug_fmt(span,
format_args!("use of bare `static` ConstArgKind::Path\'s not yet supported"))span_bug!(span, "use of bare `static` ConstArgKind::Path's not yet supported")
2710 }
2711 Res::Def(DefKind::Fn | DefKind::AssocFn, did) => {
2713 self.dcx().span_delayed_bug(span, "function items cannot be used as const args");
2714 let args = self.lower_generic_args_of_path_segment(
2715 span,
2716 did,
2717 path.segments.last().unwrap(),
2718 );
2719 ty::Const::zero_sized(tcx, Ty::new_fn_def(tcx, did, args))
2720 }
2721
2722 res @ (Res::Def(
2725 DefKind::Mod
2726 | DefKind::Enum
2727 | DefKind::Variant
2728 | DefKind::Struct
2729 | DefKind::OpaqueTy
2730 | DefKind::TyAlias
2731 | DefKind::TraitAlias
2732 | DefKind::AssocTy
2733 | DefKind::Union
2734 | DefKind::Trait
2735 | DefKind::ForeignTy
2736 | DefKind::TyParam
2737 | DefKind::Macro(_)
2738 | DefKind::LifetimeParam
2739 | DefKind::Use
2740 | DefKind::ForeignMod
2741 | DefKind::AnonConst
2742 | DefKind::InlineConst
2743 | DefKind::Field
2744 | DefKind::Impl { .. }
2745 | DefKind::Closure
2746 | DefKind::ExternCrate
2747 | DefKind::GlobalAsm
2748 | DefKind::SyntheticCoroutineBody,
2749 _,
2750 )
2751 | Res::PrimTy(_)
2752 | Res::SelfTyParam { .. }
2753 | Res::SelfTyAlias { .. }
2754 | Res::SelfCtor(_)
2755 | Res::Local(_)
2756 | Res::ToolMod
2757 | Res::NonMacroAttr(_)
2758 | Res::Err) => Const::new_error_with_message(
2759 tcx,
2760 span,
2761 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("invalid Res {0:?} for const path",
res))
})format!("invalid Res {res:?} for const path"),
2762 ),
2763 };
2764 self.check_param_uses_if_mcg(ct, span, false)
2765 }
2766
2767 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("lower_const_arg_anon",
"rustc_hir_analysis::hir_ty_lowering",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
::tracing_core::__macro_support::Option::Some(2768u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&["anon"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&anon)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Const<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{
let tcx = self.tcx();
let expr = &tcx.hir_body(anon.body).value;
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs:2773",
"rustc_hir_analysis::hir_ty_lowering",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
::tracing_core::__macro_support::Option::Some(2773u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&["expr"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&expr) as
&dyn Value))])
});
} else { ; }
};
let ty = tcx.type_of(anon.def_id).instantiate_identity();
match self.try_lower_anon_const_lit(ty, expr) {
Some(v) => v,
None =>
ty::Const::new_unevaluated(tcx,
ty::UnevaluatedConst {
def: anon.def_id.to_def_id(),
args: ty::GenericArgs::identity_for_item(tcx,
anon.def_id.to_def_id()),
}),
}
}
}
}#[instrument(skip(self), level = "debug")]
2769 fn lower_const_arg_anon(&self, anon: &AnonConst) -> Const<'tcx> {
2770 let tcx = self.tcx();
2771
2772 let expr = &tcx.hir_body(anon.body).value;
2773 debug!(?expr);
2774
2775 let ty = tcx.type_of(anon.def_id).instantiate_identity();
2779
2780 match self.try_lower_anon_const_lit(ty, expr) {
2781 Some(v) => v,
2782 None => ty::Const::new_unevaluated(
2783 tcx,
2784 ty::UnevaluatedConst {
2785 def: anon.def_id.to_def_id(),
2786 args: ty::GenericArgs::identity_for_item(tcx, anon.def_id.to_def_id()),
2787 },
2788 ),
2789 }
2790 }
2791
2792 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("lower_const_arg_literal",
"rustc_hir_analysis::hir_ty_lowering",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
::tracing_core::__macro_support::Option::Some(2792u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&["kind", "neg", "ty",
"span"], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&kind)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&neg as
&dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Const<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{
let tcx = self.tcx();
let input = LitToConstInput { lit: *kind, ty, neg };
tcx.at(span).lit_to_const(input)
}
}
}#[instrument(skip(self), level = "debug")]
2793 fn lower_const_arg_literal(
2794 &self,
2795 kind: &LitKind,
2796 neg: bool,
2797 ty: Ty<'tcx>,
2798 span: Span,
2799 ) -> Const<'tcx> {
2800 let tcx = self.tcx();
2801 let input = LitToConstInput { lit: *kind, ty, neg };
2802 tcx.at(span).lit_to_const(input)
2803 }
2804
2805 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("try_lower_anon_const_lit",
"rustc_hir_analysis::hir_ty_lowering",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
::tracing_core::__macro_support::Option::Some(2805u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&["ty", "expr"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expr)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Option<Const<'tcx>> = loop {};
return __tracing_attr_fake_return;
}
{
let tcx = self.tcx();
let expr =
match &expr.kind {
hir::ExprKind::Block(block, _) if
block.stmts.is_empty() && block.expr.is_some() => {
block.expr.as_ref().unwrap()
}
_ => expr,
};
let lit_input =
match expr.kind {
hir::ExprKind::Lit(lit) =>
Some(LitToConstInput { lit: lit.node, ty, neg: false }),
hir::ExprKind::Unary(hir::UnOp::Neg, expr) =>
match expr.kind {
hir::ExprKind::Lit(lit) =>
Some(LitToConstInput { lit: lit.node, ty, neg: true }),
_ => None,
},
_ => None,
};
lit_input.filter(|l|
!l.ty.has_aliases()).map(|l|
tcx.at(expr.span).lit_to_const(l))
}
}
}#[instrument(skip(self), level = "debug")]
2806 fn try_lower_anon_const_lit(
2807 &self,
2808 ty: Ty<'tcx>,
2809 expr: &'tcx hir::Expr<'tcx>,
2810 ) -> Option<Const<'tcx>> {
2811 let tcx = self.tcx();
2812
2813 let expr = match &expr.kind {
2816 hir::ExprKind::Block(block, _) if block.stmts.is_empty() && block.expr.is_some() => {
2817 block.expr.as_ref().unwrap()
2818 }
2819 _ => expr,
2820 };
2821
2822 let lit_input = match expr.kind {
2823 hir::ExprKind::Lit(lit) => Some(LitToConstInput { lit: lit.node, ty, neg: false }),
2824 hir::ExprKind::Unary(hir::UnOp::Neg, expr) => match expr.kind {
2825 hir::ExprKind::Lit(lit) => Some(LitToConstInput { lit: lit.node, ty, neg: true }),
2826 _ => None,
2827 },
2828 _ => None,
2829 };
2830
2831 lit_input
2832 .filter(|l| !l.ty.has_aliases())
2835 .map(|l| tcx.at(expr.span).lit_to_const(l))
2836 }
2837
2838 fn require_type_const_attribute(
2839 &self,
2840 def_id: DefId,
2841 span: Span,
2842 ) -> Result<(), ErrorGuaranteed> {
2843 let tcx = self.tcx();
2844 if tcx.is_type_const(def_id) {
2845 Ok(())
2846 } else {
2847 let mut err = self
2848 .dcx()
2849 .struct_span_err(span, "use of `const` in the type system without `#[type_const]`");
2850 if def_id.is_local() {
2851 let name = tcx.def_path_str(def_id);
2852 err.span_suggestion(
2853 tcx.def_span(def_id).shrink_to_lo(),
2854 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("add `#[type_const]` attribute to `{0}`",
name))
})format!("add `#[type_const]` attribute to `{name}`"),
2855 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("#[type_const]\n"))
})format!("#[type_const]\n"),
2856 Applicability::MaybeIncorrect,
2857 );
2858 } else {
2859 err.note("only consts marked with `#[type_const]` may be used in types");
2860 }
2861 Err(err.emit())
2862 }
2863 }
2864
2865 fn lower_delegation_ty(&self, idx: hir::InferDelegationKind) -> Ty<'tcx> {
2866 let delegation_sig = self.tcx().inherit_sig_for_delegation_item(self.item_def_id());
2867 match idx {
2868 hir::InferDelegationKind::Input(idx) => delegation_sig[idx],
2869 hir::InferDelegationKind::Output => *delegation_sig.last().unwrap(),
2870 }
2871 }
2872
2873 x;#[instrument(level = "debug", skip(self), ret)]
2875 pub fn lower_ty(&self, hir_ty: &hir::Ty<'tcx>) -> Ty<'tcx> {
2876 let tcx = self.tcx();
2877
2878 let result_ty = match &hir_ty.kind {
2879 hir::TyKind::InferDelegation(_, idx) => self.lower_delegation_ty(*idx),
2880 hir::TyKind::Slice(ty) => Ty::new_slice(tcx, self.lower_ty(ty)),
2881 hir::TyKind::Ptr(mt) => Ty::new_ptr(tcx, self.lower_ty(mt.ty), mt.mutbl),
2882 hir::TyKind::Ref(region, mt) => {
2883 let r = self.lower_lifetime(region, RegionInferReason::Reference);
2884 debug!(?r);
2885 let t = self.lower_ty(mt.ty);
2886 Ty::new_ref(tcx, r, t, mt.mutbl)
2887 }
2888 hir::TyKind::Never => tcx.types.never,
2889 hir::TyKind::Tup(fields) => {
2890 Ty::new_tup_from_iter(tcx, fields.iter().map(|t| self.lower_ty(t)))
2891 }
2892 hir::TyKind::FnPtr(bf) => {
2893 check_c_variadic_abi(tcx, bf.decl, bf.abi, hir_ty.span);
2894
2895 Ty::new_fn_ptr(
2896 tcx,
2897 self.lower_fn_ty(hir_ty.hir_id, bf.safety, bf.abi, bf.decl, None, Some(hir_ty)),
2898 )
2899 }
2900 hir::TyKind::UnsafeBinder(binder) => Ty::new_unsafe_binder(
2901 tcx,
2902 ty::Binder::bind_with_vars(
2903 self.lower_ty(binder.inner_ty),
2904 tcx.late_bound_vars(hir_ty.hir_id),
2905 ),
2906 ),
2907 hir::TyKind::TraitObject(bounds, tagged_ptr) => {
2908 let lifetime = tagged_ptr.pointer();
2909 let syntax = tagged_ptr.tag();
2910 self.lower_trait_object_ty(hir_ty.span, hir_ty.hir_id, bounds, lifetime, syntax)
2911 }
2912 hir::TyKind::Path(hir::QPath::Resolved(_, path))
2916 if path.segments.last().and_then(|segment| segment.args).is_some_and(|args| {
2917 matches!(args.parenthesized, hir::GenericArgsParentheses::ReturnTypeNotation)
2918 }) =>
2919 {
2920 let guar = self.dcx().emit_err(BadReturnTypeNotation { span: hir_ty.span });
2921 Ty::new_error(tcx, guar)
2922 }
2923 hir::TyKind::Path(hir::QPath::Resolved(maybe_qself, path)) => {
2924 debug!(?maybe_qself, ?path);
2925 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
2926 self.lower_resolved_ty_path(opt_self_ty, path, hir_ty.hir_id, PermitVariants::No)
2927 }
2928 &hir::TyKind::OpaqueDef(opaque_ty) => {
2929 let in_trait = match opaque_ty.origin {
2933 hir::OpaqueTyOrigin::FnReturn {
2934 parent,
2935 in_trait_or_impl: Some(hir::RpitContext::Trait),
2936 ..
2937 }
2938 | hir::OpaqueTyOrigin::AsyncFn {
2939 parent,
2940 in_trait_or_impl: Some(hir::RpitContext::Trait),
2941 ..
2942 } => Some(parent),
2943 hir::OpaqueTyOrigin::FnReturn {
2944 in_trait_or_impl: None | Some(hir::RpitContext::TraitImpl),
2945 ..
2946 }
2947 | hir::OpaqueTyOrigin::AsyncFn {
2948 in_trait_or_impl: None | Some(hir::RpitContext::TraitImpl),
2949 ..
2950 }
2951 | hir::OpaqueTyOrigin::TyAlias { .. } => None,
2952 };
2953
2954 self.lower_opaque_ty(opaque_ty.def_id, in_trait)
2955 }
2956 hir::TyKind::TraitAscription(hir_bounds) => {
2957 let self_ty = self.ty_infer(None, hir_ty.span);
2960 let mut bounds = Vec::new();
2961 self.lower_bounds(
2962 self_ty,
2963 hir_bounds.iter(),
2964 &mut bounds,
2965 ty::List::empty(),
2966 PredicateFilter::All,
2967 OverlappingAsssocItemConstraints::Allowed,
2968 );
2969 self.add_implicit_sizedness_bounds(
2970 &mut bounds,
2971 self_ty,
2972 hir_bounds,
2973 ImpliedBoundsContext::AssociatedTypeOrImplTrait,
2974 hir_ty.span,
2975 );
2976 self.register_trait_ascription_bounds(bounds, hir_ty.hir_id, hir_ty.span);
2977 self_ty
2978 }
2979 hir::TyKind::Path(hir::QPath::TypeRelative(_, segment))
2983 if segment.args.is_some_and(|args| {
2984 matches!(args.parenthesized, hir::GenericArgsParentheses::ReturnTypeNotation)
2985 }) =>
2986 {
2987 let guar = self.dcx().emit_err(BadReturnTypeNotation { span: hir_ty.span });
2988 Ty::new_error(tcx, guar)
2989 }
2990 hir::TyKind::Path(hir::QPath::TypeRelative(hir_self_ty, segment)) => {
2991 debug!(?hir_self_ty, ?segment);
2992 let self_ty = self.lower_ty(hir_self_ty);
2993 self.lower_type_relative_ty_path(
2994 self_ty,
2995 hir_self_ty,
2996 segment,
2997 hir_ty.hir_id,
2998 hir_ty.span,
2999 PermitVariants::No,
3000 )
3001 .map(|(ty, _, _)| ty)
3002 .unwrap_or_else(|guar| Ty::new_error(tcx, guar))
3003 }
3004 hir::TyKind::Array(ty, length) => {
3005 let length = self.lower_const_arg(length, tcx.types.usize);
3006 Ty::new_array_with_const_len(tcx, self.lower_ty(ty), length)
3007 }
3008 hir::TyKind::Infer(()) => {
3009 self.ty_infer(None, hir_ty.span)
3014 }
3015 hir::TyKind::Pat(ty, pat) => {
3016 let ty_span = ty.span;
3017 let ty = self.lower_ty(ty);
3018 let pat_ty = match self.lower_pat_ty_pat(ty, ty_span, pat) {
3019 Ok(kind) => Ty::new_pat(tcx, ty, tcx.mk_pat(kind)),
3020 Err(guar) => Ty::new_error(tcx, guar),
3021 };
3022 self.record_ty(pat.hir_id, ty, pat.span);
3023 pat_ty
3024 }
3025 hir::TyKind::Err(guar) => Ty::new_error(tcx, *guar),
3026 };
3027
3028 self.record_ty(hir_ty.hir_id, result_ty, hir_ty.span);
3029 result_ty
3030 }
3031
3032 fn lower_pat_ty_pat(
3033 &self,
3034 ty: Ty<'tcx>,
3035 ty_span: Span,
3036 pat: &hir::TyPat<'tcx>,
3037 ) -> Result<ty::PatternKind<'tcx>, ErrorGuaranteed> {
3038 let tcx = self.tcx();
3039 match pat.kind {
3040 hir::TyPatKind::Range(start, end) => {
3041 match ty.kind() {
3042 ty::Int(_) | ty::Uint(_) | ty::Char => {
3045 let start = self.lower_const_arg(start, ty);
3046 let end = self.lower_const_arg(end, ty);
3047 Ok(ty::PatternKind::Range { start, end })
3048 }
3049 _ => Err(self
3050 .dcx()
3051 .span_delayed_bug(ty_span, "invalid base type for range pattern")),
3052 }
3053 }
3054 hir::TyPatKind::NotNull => Ok(ty::PatternKind::NotNull),
3055 hir::TyPatKind::Or(patterns) => {
3056 self.tcx()
3057 .mk_patterns_from_iter(patterns.iter().map(|pat| {
3058 self.lower_pat_ty_pat(ty, ty_span, pat).map(|pat| tcx.mk_pat(pat))
3059 }))
3060 .map(ty::PatternKind::Or)
3061 }
3062 hir::TyPatKind::Err(e) => Err(e),
3063 }
3064 }
3065
3066 x;#[instrument(level = "debug", skip(self), ret)]
3068 fn lower_opaque_ty(&self, def_id: LocalDefId, in_trait: Option<LocalDefId>) -> Ty<'tcx> {
3069 let tcx = self.tcx();
3070
3071 let lifetimes = tcx.opaque_captured_lifetimes(def_id);
3072 debug!(?lifetimes);
3073
3074 let def_id = if let Some(parent_def_id) = in_trait {
3078 *tcx.associated_types_for_impl_traits_in_associated_fn(parent_def_id.to_def_id())
3079 .iter()
3080 .find(|rpitit| match tcx.opt_rpitit_info(**rpitit) {
3081 Some(ty::ImplTraitInTraitData::Trait { opaque_def_id, .. }) => {
3082 opaque_def_id.expect_local() == def_id
3083 }
3084 _ => unreachable!(),
3085 })
3086 .unwrap()
3087 } else {
3088 def_id.to_def_id()
3089 };
3090
3091 let generics = tcx.generics_of(def_id);
3092 debug!(?generics);
3093
3094 let offset = generics.count() - lifetimes.len();
3098
3099 let args = ty::GenericArgs::for_item(tcx, def_id, |param, _| {
3100 if let Some(i) = (param.index as usize).checked_sub(offset) {
3101 let (lifetime, _) = lifetimes[i];
3102 self.lower_resolved_lifetime(lifetime).into()
3104 } else {
3105 tcx.mk_param_from_def(param)
3106 }
3107 });
3108 debug!(?args);
3109
3110 if in_trait.is_some() {
3111 Ty::new_projection_from_args(tcx, def_id, args)
3112 } else {
3113 Ty::new_opaque(tcx, def_id, args)
3114 }
3115 }
3116
3117 x;#[instrument(level = "debug", skip(self, hir_id, safety, abi, decl, generics, hir_ty), ret)]
3119 pub fn lower_fn_ty(
3120 &self,
3121 hir_id: HirId,
3122 safety: hir::Safety,
3123 abi: rustc_abi::ExternAbi,
3124 decl: &hir::FnDecl<'tcx>,
3125 generics: Option<&hir::Generics<'_>>,
3126 hir_ty: Option<&hir::Ty<'_>>,
3127 ) -> ty::PolyFnSig<'tcx> {
3128 let tcx = self.tcx();
3129 let bound_vars = tcx.late_bound_vars(hir_id);
3130 debug!(?bound_vars);
3131
3132 let (input_tys, output_ty) = self.lower_fn_sig(decl, generics, hir_id, hir_ty);
3133
3134 debug!(?output_ty);
3135
3136 let fn_ty = tcx.mk_fn_sig(input_tys, output_ty, decl.c_variadic, safety, abi);
3137 let fn_ptr_ty = ty::Binder::bind_with_vars(fn_ty, bound_vars);
3138
3139 if let hir::Node::Ty(hir::Ty { kind: hir::TyKind::FnPtr(fn_ptr_ty), span, .. }) =
3140 tcx.hir_node(hir_id)
3141 {
3142 check_abi(tcx, hir_id, *span, fn_ptr_ty.abi);
3143 }
3144
3145 cmse::validate_cmse_abi(self.tcx(), self.dcx(), hir_id, abi, fn_ptr_ty);
3147
3148 if !fn_ptr_ty.references_error() {
3149 let inputs = fn_ptr_ty.inputs();
3156 let late_bound_in_args =
3157 tcx.collect_constrained_late_bound_regions(inputs.map_bound(|i| i.to_owned()));
3158 let output = fn_ptr_ty.output();
3159 let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(output);
3160
3161 self.validate_late_bound_regions(late_bound_in_args, late_bound_in_ret, |br_name| {
3162 struct_span_code_err!(
3163 self.dcx(),
3164 decl.output.span(),
3165 E0581,
3166 "return type references {}, which is not constrained by the fn input types",
3167 br_name
3168 )
3169 });
3170 }
3171
3172 fn_ptr_ty
3173 }
3174
3175 pub(super) fn suggest_trait_fn_ty_for_impl_fn_infer(
3180 &self,
3181 fn_hir_id: HirId,
3182 arg_idx: Option<usize>,
3183 ) -> Option<Ty<'tcx>> {
3184 let tcx = self.tcx();
3185 let hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), ident, .. }) =
3186 tcx.hir_node(fn_hir_id)
3187 else {
3188 return None;
3189 };
3190 let i = tcx.parent_hir_node(fn_hir_id).expect_item().expect_impl();
3191
3192 let trait_ref = self.lower_impl_trait_ref(&i.of_trait?.trait_ref, self.lower_ty(i.self_ty));
3193
3194 let assoc = tcx.associated_items(trait_ref.def_id).find_by_ident_and_kind(
3195 tcx,
3196 *ident,
3197 ty::AssocTag::Fn,
3198 trait_ref.def_id,
3199 )?;
3200
3201 let fn_sig = tcx.fn_sig(assoc.def_id).instantiate(
3202 tcx,
3203 trait_ref.args.extend_to(tcx, assoc.def_id, |param, _| tcx.mk_param_from_def(param)),
3204 );
3205 let fn_sig = tcx.liberate_late_bound_regions(fn_hir_id.expect_owner().to_def_id(), fn_sig);
3206
3207 Some(if let Some(arg_idx) = arg_idx {
3208 *fn_sig.inputs().get(arg_idx)?
3209 } else {
3210 fn_sig.output()
3211 })
3212 }
3213
3214 #[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("validate_late_bound_regions",
"rustc_hir_analysis::hir_ty_lowering",
::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
::tracing_core::__macro_support::Option::Some(3214u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&["constrained_regions",
"referenced_regions"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&constrained_regions)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&referenced_regions)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
for br in referenced_regions.difference(&constrained_regions) {
let br_name =
if let Some(name) = br.get_name(self.tcx()) {
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("lifetime `{0}`", name))
})
} else { "an anonymous lifetime".to_string() };
let mut err = generate_err(&br_name);
if !br.is_named(self.tcx()) {
err.note("lifetimes appearing in an associated or opaque type are not considered constrained");
err.note("consider introducing a named lifetime parameter");
}
err.emit();
}
}
}
}#[instrument(level = "trace", skip(self, generate_err))]
3215 fn validate_late_bound_regions<'cx>(
3216 &'cx self,
3217 constrained_regions: FxIndexSet<ty::BoundRegionKind<'tcx>>,
3218 referenced_regions: FxIndexSet<ty::BoundRegionKind<'tcx>>,
3219 generate_err: impl Fn(&str) -> Diag<'cx>,
3220 ) {
3221 for br in referenced_regions.difference(&constrained_regions) {
3222 let br_name = if let Some(name) = br.get_name(self.tcx()) {
3223 format!("lifetime `{name}`")
3224 } else {
3225 "an anonymous lifetime".to_string()
3226 };
3227
3228 let mut err = generate_err(&br_name);
3229
3230 if !br.is_named(self.tcx()) {
3231 err.note(
3238 "lifetimes appearing in an associated or opaque type are not considered constrained",
3239 );
3240 err.note("consider introducing a named lifetime parameter");
3241 }
3242
3243 err.emit();
3244 }
3245 }
3246
3247 x;#[instrument(level = "debug", skip(self, span), ret)]
3255 fn compute_object_lifetime_bound(
3256 &self,
3257 span: Span,
3258 existential_predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
3259 ) -> Option<ty::Region<'tcx>> {
3261 let tcx = self.tcx();
3262
3263 let derived_region_bounds = object_region_bounds(tcx, existential_predicates);
3266
3267 if derived_region_bounds.is_empty() {
3270 return None;
3271 }
3272
3273 if derived_region_bounds.iter().any(|r| r.is_static()) {
3276 return Some(tcx.lifetimes.re_static);
3277 }
3278
3279 let r = derived_region_bounds[0];
3283 if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
3284 self.dcx().emit_err(AmbiguousLifetimeBound { span });
3285 }
3286 Some(r)
3287 }
3288
3289 fn construct_const_ctor_value(
3290 &self,
3291 ctor_def_id: DefId,
3292 ctor_of: CtorOf,
3293 args: GenericArgsRef<'tcx>,
3294 ) -> Const<'tcx> {
3295 let tcx = self.tcx();
3296 let parent_did = tcx.parent(ctor_def_id);
3297
3298 let adt_def = tcx.adt_def(match ctor_of {
3299 CtorOf::Variant => tcx.parent(parent_did),
3300 CtorOf::Struct => parent_did,
3301 });
3302
3303 let variant_idx = adt_def.variant_index_with_id(parent_did);
3304
3305 let valtree = if adt_def.is_enum() {
3306 let discr = ty::ValTree::from_scalar_int(tcx, variant_idx.as_u32().into());
3307 ty::ValTree::from_branches(tcx, [ty::Const::new_value(tcx, discr, tcx.types.u32)])
3308 } else {
3309 ty::ValTree::zst(tcx)
3310 };
3311
3312 let adt_ty = Ty::new_adt(tcx, adt_def, args);
3313 ty::Const::new_value(tcx, valtree, adt_ty)
3314 }
3315}