1mod bounds;
17mod cmse;
18mod dyn_trait;
19pub mod errors;
20pub mod generics;
21
22use std::{assert_matches, slice};
23
24use rustc_abi::FIRST_VARIANT;
25use rustc_ast::LitKind;
26use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet};
27use rustc_data_structures::sso::SsoHashSet;
28use rustc_errors::codes::*;
29use rustc_errors::{
30 Applicability, Diag, DiagCtxtHandle, ErrorGuaranteed, FatalError, StashKey,
31 struct_span_code_err,
32};
33use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res};
34use rustc_hir::def_id::{DefId, LocalDefId};
35use rustc_hir::{self as hir, AnonConst, GenericArg, GenericArgs, HirId};
36use rustc_infer::infer::{InferCtxt, TyCtxtInferExt};
37use rustc_infer::traits::DynCompatibilityViolation;
38use rustc_macros::{TypeFoldable, TypeVisitable};
39use rustc_middle::middle::stability::AllowUnstable;
40use rustc_middle::ty::{
41 self, Const, FnSigKind, GenericArgKind, GenericArgsRef, GenericParamDefKind, LitToConstInput,
42 RegionExt, Ty, TyCtxt, TypeSuperFoldable, TypeVisitableExt, TypingMode, Unnormalized, Upcast,
43 const_lit_matches_ty, fold_regions,
44};
45use rustc_middle::{bug, span_bug};
46use rustc_session::diagnostics::feature_err;
47use rustc_session::lint::builtin::AMBIGUOUS_ASSOCIATED_ITEMS;
48use rustc_span::def_id::ModId;
49use rustc_span::{DUMMY_SP, Ident, Span, kw, sym};
50use rustc_trait_selection::infer::InferCtxtExt;
51use rustc_trait_selection::traits::{self, FulfillmentError};
52use tracing::{debug, instrument};
53
54use crate::check::check_abi;
55use crate::diagnostics::{self, BadReturnTypeNotation, NoFieldOnType};
56use crate::hir_ty_lowering::errors::{GenericsArgsErrExtend, prohibit_assoc_item_constraint};
57use crate::hir_ty_lowering::generics::{check_generic_arg_count, lower_generic_args};
58use crate::middle::resolve_bound_vars as rbv;
59use crate::{NoVariantNamed, check_c_variadic_abi};
60
61#[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)]
64pub(crate) enum ImpliedBoundsContext<'tcx> {
65 TraitDef(LocalDefId),
68 TyParam(LocalDefId, &'tcx [hir::WherePredicate<'tcx>]),
70 AssociatedTypeOrImplTrait,
72}
73
74#[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)]
76pub struct GenericPathSegment(pub DefId, pub usize);
77
78#[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)]
79pub enum PredicateFilter {
80 All,
82
83 SelfOnly,
85
86 SelfTraitThatDefines(Ident),
90
91 SelfAndAssociatedTypeBounds,
95
96 ConstIfConst,
98
99 SelfConstIfConst,
101}
102
103#[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(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"ObjectLifetimeDefault", &__self_0),
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)]
104pub enum RegionInferReason<'a> {
105 ExplicitObjectLifetime,
107 ObjectLifetimeDefault(Span),
109 Param(&'a ty::GenericParamDef),
111 RegionPredicate,
112 Reference,
113 OutlivesBound,
114}
115
116#[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>;
let _: ::core::clone::AssertParamIsClone<ModId>;
*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)]
117pub struct InherentAssocCandidate {
118 pub impl_: DefId,
119 pub assoc_item: DefId,
120 pub scope: ModId,
121}
122
123pub struct ResolvedStructPath<'tcx> {
124 pub res: Result<Res, ErrorGuaranteed>,
125 pub ty: Ty<'tcx>,
126}
127
128pub trait HirTyLowerer<'tcx> {
133 fn tcx(&self) -> TyCtxt<'tcx>;
134
135 fn dcx(&self) -> DiagCtxtHandle<'_>;
136
137 fn item_def_id(&self) -> LocalDefId;
139
140 fn re_infer(&self, span: Span, reason: RegionInferReason<'_>) -> ty::Region<'tcx>;
142
143 fn ty_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx>;
145
146 fn ct_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Const<'tcx>;
148
149 fn register_trait_ascription_bounds(
150 &self,
151 bounds: Vec<(ty::Clause<'tcx>, Span)>,
152 hir_id: HirId,
153 span: Span,
154 );
155
156 fn probe_ty_param_bounds(
171 &self,
172 span: Span,
173 def_id: LocalDefId,
174 assoc_ident: Ident,
175 ) -> ty::EarlyBinder<'tcx, &'tcx [(ty::Clause<'tcx>, Span)]>;
176
177 fn select_inherent_assoc_candidates(
178 &self,
179 span: Span,
180 self_ty: Ty<'tcx>,
181 candidates: Vec<InherentAssocCandidate>,
182 ) -> (Vec<InherentAssocCandidate>, Vec<FulfillmentError<'tcx>>);
183
184 fn lower_assoc_item_path(
197 &self,
198 span: Span,
199 item_def_id: DefId,
200 item_segment: &hir::PathSegment<'tcx>,
201 poly_trait_ref: ty::PolyTraitRef<'tcx>,
202 ) -> Result<(DefId, GenericArgsRef<'tcx>), ErrorGuaranteed>;
203
204 fn lower_fn_sig(
205 &self,
206 decl: &hir::FnDecl<'tcx>,
207 generics: Option<&hir::Generics<'_>>,
208 hir_id: HirId,
209 hir_ty: Option<&hir::Ty<'_>>,
210 ) -> (Vec<Ty<'tcx>>, Ty<'tcx>);
211
212 fn probe_adt(&self, span: Span, ty: Ty<'tcx>) -> Option<ty::AdtDef<'tcx>>;
219
220 fn record_ty(&self, hir_id: HirId, ty: Ty<'tcx>, span: Span);
222
223 fn infcx(&self) -> Option<&InferCtxt<'tcx>>;
225
226 fn lowerer(&self) -> &dyn HirTyLowerer<'tcx>
231 where
232 Self: Sized,
233 {
234 self
235 }
236
237 fn dyn_compatibility_violations(&self, trait_def_id: DefId) -> Vec<DynCompatibilityViolation>;
240}
241
242enum AssocItemQSelf {
246 Trait(DefId),
247 TyParam(LocalDefId, Span),
248 SelfTyAlias,
249}
250
251impl AssocItemQSelf {
252 fn to_string(&self, tcx: TyCtxt<'_>) -> String {
253 match *self {
254 Self::Trait(def_id) => tcx.def_path_str(def_id),
255 Self::TyParam(def_id, _) => tcx.hir_ty_param_name(def_id).to_string(),
256 Self::SelfTyAlias => kw::SelfUpper.to_string(),
257 }
258 }
259}
260
261#[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)]
262enum LowerTypeRelativePathMode {
263 Type(PermitVariants),
264 Const,
265}
266
267impl LowerTypeRelativePathMode {
268 fn assoc_tag(self) -> ty::AssocTag {
269 match self {
270 Self::Type(_) => ty::AssocTag::Type,
271 Self::Const => ty::AssocTag::Const,
272 }
273 }
274
275 fn def_kind_for_diagnostics(self) -> DefKind {
277 match self {
278 Self::Type(_) => DefKind::AssocTy,
279 Self::Const => DefKind::AssocConst { is_type_const: false },
280 }
281 }
282
283 fn permit_variants(self) -> PermitVariants {
284 match self {
285 Self::Type(permit_variants) => permit_variants,
286 Self::Const => PermitVariants::No,
289 }
290 }
291}
292
293#[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)]
295pub enum PermitVariants {
296 Yes,
297 No,
298}
299
300#[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) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"AssocItem", &__self_0),
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<ty::AliasTerm<'tcx>>;
let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
let _: ::core::clone::AssertParamIsClone<DefId>;
let _: ::core::clone::AssertParamIsClone<GenericArgsRef<'tcx>>;
*self
}
}Clone, #[automatically_derived]
impl<'tcx> ::core::marker::Copy for TypeRelativePath<'tcx> { }Copy)]
301enum TypeRelativePath<'tcx> {
302 AssocItem(ty::AliasTerm<'tcx>),
303 Variant { adt: Ty<'tcx>, variant_did: DefId },
304 Ctor { ctor_def_id: DefId, args: GenericArgsRef<'tcx> },
305}
306
307#[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)]
317pub enum ExplicitLateBound {
318 Yes,
319 No,
320}
321
322#[derive(#[automatically_derived]
impl ::core::fmt::Debug for IsMethodCall {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
IsMethodCall::Yes => "Yes",
IsMethodCall::No => "No",
})
}
}Debug, #[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)]
323pub enum IsMethodCall {
324 Yes,
325 No,
326}
327
328#[derive(#[automatically_derived]
impl ::core::fmt::Debug for GenericArgPosition {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
GenericArgPosition::Type =>
::core::fmt::Formatter::write_str(f, "Type"),
GenericArgPosition::Value(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Value",
&__self_0),
}
}
}Debug, #[automatically_derived]
impl ::core::marker::Copy for GenericArgPosition { }Copy, #[automatically_derived]
impl ::core::clone::Clone for GenericArgPosition {
#[inline]
fn clone(&self) -> GenericArgPosition {
let _: ::core::clone::AssertParamIsClone<IsMethodCall>;
*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 &&
match (self, other) {
(GenericArgPosition::Value(__self_0),
GenericArgPosition::Value(__arg1_0)) =>
__self_0 == __arg1_0,
_ => true,
}
}
}PartialEq)]
331pub(crate) enum GenericArgPosition {
332 Type,
333 Value(IsMethodCall),
334}
335
336#[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)]
340pub(crate) enum OverlappingAsssocItemConstraints {
341 Allowed,
342 Forbidden,
343}
344
345#[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)]
348pub struct GenericArgCountMismatch {
349 pub reported: ErrorGuaranteed,
350 pub invalid_args: Vec<usize>,
352}
353
354#[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)]
357pub struct GenericArgCountResult {
358 pub explicit_late_bound: ExplicitLateBound,
359 pub correct: Result<(), GenericArgCountMismatch>,
360}
361
362pub trait GenericArgsLowerer<'a, 'tcx> {
367 fn args_for_def_id(&mut self, def_id: DefId) -> (Option<&'a GenericArgs<'tcx>>, bool);
368
369 fn provided_kind(
370 &mut self,
371 preceding_args: &[ty::GenericArg<'tcx>],
372 param: &ty::GenericParamDef,
373 arg: &GenericArg<'tcx>,
374 ) -> ty::GenericArg<'tcx>;
375
376 fn inferred_kind(
377 &mut self,
378 preceding_args: &[ty::GenericArg<'tcx>],
379 param: &ty::GenericParamDef,
380 infer_args: bool,
381 ) -> ty::GenericArg<'tcx>;
382}
383
384enum ForbidParamContext {
386 ConstArgument,
388 EnumDiscriminant,
390}
391
392struct ForbidParamUsesFolder<'tcx> {
393 tcx: TyCtxt<'tcx>,
394 anon_const_def_id: LocalDefId,
395 span: Span,
396 is_self_alias: bool,
397 context: ForbidParamContext,
398}
399
400impl<'tcx> ForbidParamUsesFolder<'tcx> {
401 fn error(&self) -> ErrorGuaranteed {
402 let msg = match self.context {
403 ForbidParamContext::EnumDiscriminant if self.is_self_alias => {
404 "generic `Self` types are not permitted in enum discriminant values"
405 }
406 ForbidParamContext::EnumDiscriminant => {
407 "generic parameters may not be used in enum discriminant values"
408 }
409 ForbidParamContext::ConstArgument if self.is_self_alias => {
410 "generic `Self` types are currently not permitted in anonymous constants"
411 }
412 ForbidParamContext::ConstArgument => {
413 if self.tcx.features().generic_const_args() {
414 "generic parameters in const blocks are not allowed; use a named `const` item instead"
415 } else {
416 "generic parameters may not be used in const operations"
417 }
418 }
419 };
420 let mut diag = self.tcx.dcx().struct_span_err(self.span, msg);
421 if self.is_self_alias && #[allow(non_exhaustive_omitted_patterns)] match self.context {
ForbidParamContext::ConstArgument => true,
_ => false,
}matches!(self.context, ForbidParamContext::ConstArgument) {
422 let anon_const_hir_id: HirId = HirId::make_owner(self.anon_const_def_id);
423 let parent_impl = self.tcx.hir_parent_owner_iter(anon_const_hir_id).find_map(
424 |(_, node)| match node {
425 hir::OwnerNode::Item(hir::Item {
426 kind: hir::ItemKind::Impl(impl_), ..
427 }) => Some(impl_),
428 _ => None,
429 },
430 );
431 if let Some(impl_) = parent_impl {
432 diag.span_note(impl_.self_ty.span, "not a concrete type");
433 }
434 }
435 if #[allow(non_exhaustive_omitted_patterns)] match self.context {
ForbidParamContext::ConstArgument => true,
_ => false,
}matches!(self.context, ForbidParamContext::ConstArgument) {
436 if self.tcx.features().generic_const_args() {
437 diag.help("consider factoring the expression into a `type const` item and use it as the const argument instead");
438 } else if self.tcx.features().min_generic_const_args() {
439 diag.help("add `#![feature(generic_const_args)]` and extract the expression into a `type const` item");
440 } else if self.tcx.sess.is_nightly_build() {
441 diag.help(
442 "add `#![feature(generic_const_exprs)]` to allow generic const expressions",
443 );
444 diag.help("alternatively, you can use `#![feature(generic_const_args)]` and extract the expression into a `type const` item");
445 }
446 }
447 diag.emit()
448 }
449}
450
451impl<'tcx> ty::TypeFolder<TyCtxt<'tcx>> for ForbidParamUsesFolder<'tcx> {
452 fn cx(&self) -> TyCtxt<'tcx> {
453 self.tcx
454 }
455
456 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
457 if #[allow(non_exhaustive_omitted_patterns)] match t.kind() {
ty::Param(..) => true,
_ => false,
}matches!(t.kind(), ty::Param(..)) {
458 return Ty::new_error(self.tcx, self.error());
459 }
460 t.super_fold_with(self)
461 }
462
463 fn fold_const(&mut self, c: Const<'tcx>) -> Const<'tcx> {
464 if #[allow(non_exhaustive_omitted_patterns)] match c.kind() {
ty::ConstKind::Param(..) => true,
_ => false,
}matches!(c.kind(), ty::ConstKind::Param(..)) {
465 return Const::new_error(self.tcx, self.error());
466 }
467 c.super_fold_with(self)
468 }
469
470 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
471 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(..)) {
472 return ty::Region::new_error(self.tcx, self.error());
473 }
474 r
475 }
476}
477
478impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
479 pub fn check_param_res_if_mcg_for_instantiate_value_path(
483 &self,
484 res: Res,
485 span: Span,
486 ) -> Result<(), ErrorGuaranteed> {
487 let tcx = self.tcx();
488 let parent_def_id = self.item_def_id();
489 if let Res::Def(DefKind::ConstParam, _) = res
493 && let Some(context) = self.anon_const_forbids_generic_params()
494 {
495 let folder = ForbidParamUsesFolder {
496 tcx,
497 anon_const_def_id: parent_def_id,
498 span,
499 is_self_alias: false,
500 context,
501 };
502 return Err(folder.error());
503 }
504 Ok(())
505 }
506
507 fn anon_const_forbids_generic_params(&self) -> Option<ForbidParamContext> {
515 let tcx = self.tcx();
516 let item_def_id = self.item_def_id();
517
518 let anon_const_def_id = tcx.typeck_root_def_id_local(item_def_id);
522
523 if tcx.def_kind(anon_const_def_id) != DefKind::AnonConst {
524 return None;
525 }
526
527 match tcx.anon_const_kind(anon_const_def_id) {
528 ty::AnonConstKind::MCG => Some(ForbidParamContext::ConstArgument),
529 ty::AnonConstKind::NonTypeSystemAnon => {
530 if tcx.generics_of(anon_const_def_id).count() == 0 {
534 Some(ForbidParamContext::EnumDiscriminant)
535 } else {
536 None
537 }
538 }
539 ty::AnonConstKind::NonTypeSystemInline
540 | ty::AnonConstKind::GCE
541 | ty::AnonConstKind::RepeatExprCount => None,
542 }
543 }
544
545 #[must_use = "need to use transformed output"]
551 fn check_param_uses_if_mcg<T>(&self, term: T, span: Span, is_self_alias: bool) -> T
552 where
553 T: ty::TypeFoldable<TyCtxt<'tcx>>,
554 {
555 let tcx = self.tcx();
556 if let Some(context) = self.anon_const_forbids_generic_params()
557 && (term.has_param() || term.has_escaping_bound_vars())
559 {
560 let anon_const_def_id = self.item_def_id();
561 let mut folder =
562 ForbidParamUsesFolder { tcx, anon_const_def_id, span, is_self_alias, context };
563 term.fold_with(&mut folder)
564 } else {
565 term
566 }
567 }
568
569 x;#[instrument(level = "debug", skip(self), ret)]
571 pub fn lower_lifetime(
572 &self,
573 lifetime: &hir::Lifetime,
574 reason: RegionInferReason<'_>,
575 ) -> ty::Region<'tcx> {
576 if let Some(resolved) = self.tcx().named_bound_var(lifetime.hir_id) {
577 let region = self.lower_resolved_lifetime(resolved);
578 self.check_param_uses_if_mcg(region, lifetime.ident.span, false)
579 } else {
580 self.re_infer(lifetime.ident.span, reason)
581 }
582 }
583
584 x;#[instrument(level = "debug", skip(self), ret)]
586 fn lower_resolved_lifetime(&self, resolved: rbv::ResolvedArg) -> ty::Region<'tcx> {
587 let tcx = self.tcx();
588
589 match resolved {
590 rbv::ResolvedArg::StaticLifetime => tcx.lifetimes.re_static,
591
592 rbv::ResolvedArg::LateBound(debruijn, index, def_id) => {
593 let br = ty::BoundRegion {
594 var: ty::BoundVar::from_u32(index),
595 kind: ty::BoundRegionKind::Named(def_id.to_def_id()),
596 };
597 ty::Region::new_bound(tcx, debruijn, br)
598 }
599
600 rbv::ResolvedArg::EarlyBound(def_id) => {
601 let name = tcx.hir_ty_param_name(def_id);
602 let item_def_id = tcx.hir_ty_param_owner(def_id);
603 let generics = tcx.generics_of(item_def_id);
604 let index = generics.param_def_id_to_index[&def_id.to_def_id()];
605 ty::Region::new_early_param(tcx, ty::EarlyParamRegion { index, name })
606 }
607
608 rbv::ResolvedArg::Free(scope, id) => {
609 ty::Region::new_late_param(
610 tcx,
611 scope.to_def_id(),
612 ty::LateParamRegionKind::Named(id.to_def_id()),
613 )
614
615 }
617
618 rbv::ResolvedArg::Error(guar) => ty::Region::new_error(tcx, guar),
619 }
620 }
621
622 pub fn lower_generic_args_of_path_segment(
623 &self,
624 span: Span,
625 def_id: DefId,
626 item_segment: &hir::PathSegment<'tcx>,
627 ) -> GenericArgsRef<'tcx> {
628 let (args, _) = self.lower_generic_args_of_path(span, def_id, &[], item_segment, None);
629 if let Some(c) = item_segment.args().constraints.first() {
630 prohibit_assoc_item_constraint(self, c, Some((def_id, item_segment, span)));
631 }
632 args
633 }
634
635 x;#[instrument(level = "debug", skip(self, span), ret)]
670 pub(crate) fn lower_generic_args_of_path(
671 &self,
672 span: Span,
673 def_id: DefId,
674 parent_args: &[ty::GenericArg<'tcx>],
675 segment: &hir::PathSegment<'tcx>,
676 self_ty: Option<Ty<'tcx>>,
677 ) -> (GenericArgsRef<'tcx>, GenericArgCountResult) {
678 let tcx = self.tcx();
683 let generics = tcx.generics_of(def_id);
684 debug!(?generics);
685
686 if generics.has_self {
687 if generics.parent.is_some() {
688 assert!(!parent_args.is_empty())
691 } else {
692 assert!(self_ty.is_some());
694 }
695 } else {
696 assert!(self_ty.is_none());
697 }
698
699 let arg_count = check_generic_arg_count(
700 self,
701 def_id,
702 segment,
703 generics,
704 GenericArgPosition::Type,
705 self_ty.is_some(),
706 );
707
708 if generics.is_own_empty() {
713 return (tcx.mk_args(parent_args), arg_count);
714 }
715
716 struct GenericArgsCtxt<'a, 'tcx> {
717 lowerer: &'a dyn HirTyLowerer<'tcx>,
718 def_id: DefId,
719 generic_args: &'a GenericArgs<'tcx>,
720 span: Span,
721 infer_args: bool,
722 create_synth_args: bool,
723 incorrect_args: &'a Result<(), GenericArgCountMismatch>,
724 }
725
726 impl<'a, 'tcx> GenericArgsLowerer<'a, 'tcx> for GenericArgsCtxt<'a, 'tcx> {
727 fn args_for_def_id(&mut self, did: DefId) -> (Option<&'a GenericArgs<'tcx>>, bool) {
728 if did == self.def_id {
729 (Some(self.generic_args), self.infer_args)
730 } else {
731 (None, false)
733 }
734 }
735
736 fn provided_kind(
737 &mut self,
738 preceding_args: &[ty::GenericArg<'tcx>],
739 param: &ty::GenericParamDef,
740 arg: &GenericArg<'tcx>,
741 ) -> ty::GenericArg<'tcx> {
742 let tcx = self.lowerer.tcx();
743
744 if let Err(incorrect) = self.incorrect_args {
745 if incorrect.invalid_args.contains(&(param.index as usize)) {
746 return param.to_error(tcx);
747 }
748 }
749
750 let handle_ty_args = |has_default, ty: &hir::Ty<'tcx>| {
751 if has_default {
752 tcx.check_optional_stability(
753 param.def_id,
754 Some(arg.hir_id()),
755 arg.span(),
756 None,
757 AllowUnstable::No,
758 |_, _| {
759 },
765 );
766 }
767 self.lowerer.lower_ty(ty).into()
768 };
769
770 match (¶m.kind, arg) {
771 (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => {
772 self.lowerer.lower_lifetime(lt, RegionInferReason::Param(param)).into()
773 }
774 (&GenericParamDefKind::Type { has_default, .. }, GenericArg::Type(ty)) => {
775 handle_ty_args(has_default, ty.as_unambig_ty())
777 }
778 (&GenericParamDefKind::Type { has_default, .. }, GenericArg::Infer(inf)) => {
779 handle_ty_args(has_default, &inf.to_ty())
780 }
781 (GenericParamDefKind::Const { .. }, GenericArg::Const(ct)) => self
782 .lowerer
783 .lower_const_arg(
785 ct.as_unambig_ct(),
786 tcx.type_of(param.def_id)
787 .instantiate(tcx, preceding_args)
788 .skip_norm_wip(),
789 )
790 .into(),
791 (&GenericParamDefKind::Const { .. }, GenericArg::Infer(inf)) => {
792 self.lowerer.ct_infer(Some(param), inf.span).into()
793 }
794 (kind, arg) => span_bug!(
795 self.span,
796 "mismatched path argument for kind {kind:?}: found arg {arg:?}"
797 ),
798 }
799 }
800
801 fn inferred_kind(
802 &mut self,
803 preceding_args: &[ty::GenericArg<'tcx>],
804 param: &ty::GenericParamDef,
805 infer_args: bool,
806 ) -> ty::GenericArg<'tcx> {
807 let tcx = self.lowerer.tcx();
808
809 if let Err(incorrect) = self.incorrect_args {
810 if incorrect.invalid_args.contains(&(param.index as usize)) {
811 return param.to_error(tcx);
812 }
813 }
814 match param.kind {
815 GenericParamDefKind::Lifetime => {
816 self.lowerer.re_infer(self.span, RegionInferReason::Param(param)).into()
817 }
818 GenericParamDefKind::Type { has_default, synthetic } => {
819 if !infer_args && has_default {
820 if let Some(prev) =
822 preceding_args.iter().find_map(|arg| match arg.kind() {
823 GenericArgKind::Type(ty) => ty.error_reported().err(),
824 _ => None,
825 })
826 {
827 return Ty::new_error(tcx, prev).into();
829 }
830 tcx.at(self.span)
831 .type_of(param.def_id)
832 .instantiate(tcx, preceding_args)
833 .skip_norm_wip()
834 .into()
835 } else if self.create_synth_args && synthetic {
836 Ty::new_param(tcx, param.index, param.name).into()
837 } else if infer_args {
838 self.lowerer.ty_infer(Some(param), self.span).into()
839 } else {
840 Ty::new_misc_error(tcx).into()
842 }
843 }
844 GenericParamDefKind::Const { has_default, .. } => {
845 let ty = tcx
846 .at(self.span)
847 .type_of(param.def_id)
848 .instantiate(tcx, preceding_args)
849 .skip_norm_wip();
850 if let Err(guar) = ty.error_reported() {
851 return ty::Const::new_error(tcx, guar).into();
852 }
853 if !infer_args && has_default {
854 tcx.const_param_default(param.def_id)
855 .instantiate(tcx, preceding_args)
856 .skip_norm_wip()
857 .into()
858 } else if infer_args {
859 self.lowerer.ct_infer(Some(param), self.span).into()
860 } else {
861 ty::Const::new_misc_error(tcx).into()
863 }
864 }
865 }
866 }
867 }
868
869 let mut args_ctx = GenericArgsCtxt {
870 lowerer: self,
871 def_id,
872 span,
873 generic_args: segment.args(),
874 infer_args: segment.infer_args,
875 create_synth_args: segment.delegation_child_segment,
876 incorrect_args: &arg_count.correct,
877 };
878
879 let args = lower_generic_args(
880 self,
881 def_id,
882 parent_args,
883 self_ty.is_some(),
884 self_ty,
885 &arg_count,
886 &mut args_ctx,
887 );
888
889 (args, arg_count)
890 }
891
892 #[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(892u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("span")
}> =
::tracing::__macro_support::FieldName::new("span");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("item_def_id")
}> =
::tracing::__macro_support::FieldName::new("item_def_id");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("item_segment")
}> =
::tracing::__macro_support::FieldName::new("item_segment");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("parent_args")
}> =
::tracing::__macro_support::FieldName::new("parent_args");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item_def_id)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item_segment)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&parent_args)
as &dyn ::tracing::field::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))]
893 pub fn lower_generic_args_of_assoc_item(
894 &self,
895 span: Span,
896 item_def_id: DefId,
897 item_segment: &hir::PathSegment<'tcx>,
898 parent_args: GenericArgsRef<'tcx>,
899 ) -> GenericArgsRef<'tcx> {
900 let (args, _) =
901 self.lower_generic_args_of_path(span, item_def_id, parent_args, item_segment, None);
902 if let Some(c) = item_segment.args().constraints.first() {
903 prohibit_assoc_item_constraint(self, c, Some((item_def_id, item_segment, span)));
904 }
905 args
906 }
907
908 pub fn lower_impl_trait_ref(
912 &self,
913 trait_ref: &hir::TraitRef<'tcx>,
914 self_ty: Ty<'tcx>,
915 ) -> ty::TraitRef<'tcx> {
916 let [leading_segments @ .., segment] = trait_ref.path.segments else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
917
918 let _ = self.prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
919
920 self.lower_mono_trait_ref(
921 trait_ref.path.span,
922 trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise()),
923 self_ty,
924 segment,
925 true,
926 )
927 }
928
929 #[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(952u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("bound_generic_params")
}> =
::tracing::__macro_support::FieldName::new("bound_generic_params");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("constness")
}> =
::tracing::__macro_support::FieldName::new("constness");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("polarity")
}> =
::tracing::__macro_support::FieldName::new("polarity");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("trait_ref")
}> =
::tracing::__macro_support::FieldName::new("trait_ref");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("span")
}> =
::tracing::__macro_support::FieldName::new("span");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("self_ty")
}> =
::tracing::__macro_support::FieldName::new("self_ty");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("predicate_filter")
}> =
::tracing::__macro_support::FieldName::new("predicate_filter");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("overlapping_assoc_item_constraints")
}> =
::tracing::__macro_support::FieldName::new("overlapping_assoc_item_constraints");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&bound_generic_params)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&constness)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&polarity)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_ref)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self_ty)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&predicate_filter)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&overlapping_assoc_item_constraints)
as &dyn ::tracing::field::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:1032",
"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(1032u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("bound_vars")
}> =
::tracing::__macro_support::FieldName::new("bound_vars");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&bound_vars)
as &dyn ::tracing::field::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:1039",
"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(1039u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("poly_trait_ref")
}> =
::tracing::__macro_support::FieldName::new("poly_trait_ref");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&poly_trait_ref)
as &dyn ::tracing::field::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::diagnostics::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))]
953 pub(crate) fn lower_poly_trait_ref(
954 &self,
955 &hir::PolyTraitRef {
956 bound_generic_params,
957 modifiers: hir::TraitBoundModifiers { constness, polarity },
958 trait_ref,
959 span,
960 }: &hir::PolyTraitRef<'tcx>,
961 self_ty: Ty<'tcx>,
962 bounds: &mut Vec<(ty::Clause<'tcx>, Span)>,
963 predicate_filter: PredicateFilter,
964 overlapping_assoc_item_constraints: OverlappingAsssocItemConstraints,
965 ) -> GenericArgCountResult {
966 let tcx = self.tcx();
967
968 let _ = bound_generic_params;
971
972 let trait_def_id = trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise());
973
974 let transient = match polarity {
979 hir::BoundPolarity::Positive => {
980 tcx.is_lang_item(trait_def_id, hir::LangItem::PointeeSized)
986 }
987 hir::BoundPolarity::Negative(_) => false,
988 hir::BoundPolarity::Maybe(_) => {
989 self.require_bound_to_relax_default_trait(trait_ref, span);
990 true
991 }
992 };
993 let bounds = if transient { &mut Vec::new() } else { bounds };
994
995 let polarity = match polarity {
996 hir::BoundPolarity::Positive | hir::BoundPolarity::Maybe(_) => {
997 ty::PredicatePolarity::Positive
998 }
999 hir::BoundPolarity::Negative(_) => ty::PredicatePolarity::Negative,
1000 };
1001
1002 let [leading_segments @ .., segment] = trait_ref.path.segments else { bug!() };
1003
1004 let _ = self.prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
1005 self.report_internal_fn_trait(span, trait_def_id, segment, false);
1006
1007 let (generic_args, arg_count) = self.lower_generic_args_of_path(
1008 trait_ref.path.span,
1009 trait_def_id,
1010 &[],
1011 segment,
1012 Some(self_ty),
1013 );
1014
1015 let constraints = segment.args().constraints;
1016
1017 if transient && (!generic_args[1..].is_empty() || !constraints.is_empty()) {
1018 self.dcx()
1028 .span_delayed_bug(span, "transient bound should not have args or constraints");
1029 }
1030
1031 let bound_vars = tcx.late_bound_vars(trait_ref.hir_ref_id);
1032 debug!(?bound_vars);
1033
1034 let poly_trait_ref = ty::Binder::bind_with_vars(
1035 ty::TraitRef::new_from_args(tcx, trait_def_id, generic_args),
1036 bound_vars,
1037 );
1038
1039 debug!(?poly_trait_ref);
1040
1041 match predicate_filter {
1043 PredicateFilter::All
1044 | PredicateFilter::SelfOnly
1045 | PredicateFilter::SelfTraitThatDefines(..)
1046 | PredicateFilter::SelfAndAssociatedTypeBounds => {
1047 let bound = poly_trait_ref.map_bound(|trait_ref| {
1048 ty::ClauseKind::Trait(ty::TraitPredicate { trait_ref, polarity })
1049 });
1050 let bound = (bound.upcast(tcx), span);
1051 if tcx.is_lang_item(trait_def_id, rustc_hir::LangItem::Sized) {
1057 bounds.insert(0, bound);
1058 } else {
1059 bounds.push(bound);
1060 }
1061 }
1062 PredicateFilter::ConstIfConst | PredicateFilter::SelfConstIfConst => {}
1063 }
1064
1065 if let hir::BoundConstness::Always(span) | hir::BoundConstness::Maybe(span) = constness
1066 && !tcx.is_const_trait(trait_def_id)
1067 {
1068 let (def_span, suggestion, suggestion_pre) =
1069 match (trait_def_id.as_local(), tcx.sess.is_nightly_build()) {
1070 (Some(trait_def_id), true) => {
1071 let span = tcx.hir_expect_item(trait_def_id).vis_span;
1072 let span = tcx.sess.source_map().span_extend_while_whitespace(span);
1073
1074 (
1075 None,
1076 Some(span.shrink_to_hi()),
1077 if self.tcx().features().const_trait_impl() {
1078 ""
1079 } else {
1080 "enable `#![feature(const_trait_impl)]` in your crate and "
1081 },
1082 )
1083 }
1084 (None, _) | (_, false) => (Some(tcx.def_span(trait_def_id)), None, ""),
1085 };
1086 self.dcx().emit_err(crate::diagnostics::ConstBoundForNonConstTrait {
1087 span,
1088 modifier: constness.as_str(),
1089 def_span,
1090 trait_name: tcx.def_path_str(trait_def_id),
1091 suggestion,
1092 suggestion_pre,
1093 });
1094 } else {
1095 match predicate_filter {
1096 PredicateFilter::SelfTraitThatDefines(..) => {}
1098 PredicateFilter::All
1099 | PredicateFilter::SelfOnly
1100 | PredicateFilter::SelfAndAssociatedTypeBounds => {
1101 match constness {
1102 hir::BoundConstness::Always(_) => {
1103 if polarity == ty::PredicatePolarity::Positive {
1104 bounds.push((
1105 poly_trait_ref
1106 .to_host_effect_clause(tcx, ty::BoundConstness::Const),
1107 span,
1108 ));
1109 }
1110 }
1111 hir::BoundConstness::Maybe(_) => {
1112 }
1117 hir::BoundConstness::Never => {}
1118 }
1119 }
1120 PredicateFilter::ConstIfConst | PredicateFilter::SelfConstIfConst => {
1127 match constness {
1128 hir::BoundConstness::Maybe(_) => {
1129 if polarity == ty::PredicatePolarity::Positive {
1130 bounds.push((
1131 poly_trait_ref
1132 .to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
1133 span,
1134 ));
1135 }
1136 }
1137 hir::BoundConstness::Always(_) | hir::BoundConstness::Never => {}
1138 }
1139 }
1140 }
1141 }
1142
1143 let mut dup_constraints = (overlapping_assoc_item_constraints
1144 == OverlappingAsssocItemConstraints::Forbidden)
1145 .then_some(FxIndexMap::default());
1146
1147 for constraint in constraints {
1148 if polarity == ty::PredicatePolarity::Negative {
1152 self.dcx().span_delayed_bug(
1153 constraint.span,
1154 "negative trait bounds should not have assoc item constraints",
1155 );
1156 break;
1157 }
1158
1159 let _: Result<_, ErrorGuaranteed> = self.lower_assoc_item_constraint(
1161 trait_ref.hir_ref_id,
1162 poly_trait_ref,
1163 constraint,
1164 bounds,
1165 dup_constraints.as_mut(),
1166 constraint.span,
1167 predicate_filter,
1168 );
1169 }
1171
1172 arg_count
1173 }
1174
1175 fn lower_mono_trait_ref(
1179 &self,
1180 span: Span,
1181 trait_def_id: DefId,
1182 self_ty: Ty<'tcx>,
1183 trait_segment: &hir::PathSegment<'tcx>,
1184 is_impl: bool,
1185 ) -> ty::TraitRef<'tcx> {
1186 self.report_internal_fn_trait(span, trait_def_id, trait_segment, is_impl);
1187
1188 let (generic_args, _) =
1189 self.lower_generic_args_of_path(span, trait_def_id, &[], trait_segment, Some(self_ty));
1190 if let Some(c) = trait_segment.args().constraints.first() {
1191 prohibit_assoc_item_constraint(self, c, Some((trait_def_id, trait_segment, span)));
1192 }
1193 ty::TraitRef::new_from_args(self.tcx(), trait_def_id, generic_args)
1194 }
1195
1196 fn probe_trait_that_defines_assoc_item(
1197 &self,
1198 trait_def_id: DefId,
1199 assoc_tag: ty::AssocTag,
1200 assoc_ident: Ident,
1201 ) -> bool {
1202 self.tcx()
1203 .associated_items(trait_def_id)
1204 .find_by_ident_and_kind(self.tcx(), assoc_ident, assoc_tag, trait_def_id)
1205 .is_some()
1206 }
1207
1208 fn lower_path_segment(
1209 &self,
1210 span: Span,
1211 def_id: DefId,
1212 item_segment: &hir::PathSegment<'tcx>,
1213 ) -> Ty<'tcx> {
1214 let tcx = self.tcx();
1215 let args = self.lower_generic_args_of_path_segment(span, def_id, item_segment);
1216
1217 if let DefKind::TyAlias = tcx.def_kind(def_id)
1218 && tcx.type_alias_is_checked(def_id)
1219 {
1220 let alias_ty = ty::AliasTy::new_from_args(tcx, ty::Free { def_id }, args);
1224 Ty::new_alias(tcx, ty::IsRigid::No, alias_ty)
1225 } else {
1226 tcx.at(span).type_of(def_id).instantiate(tcx, args).skip_norm_wip()
1227 }
1228 }
1229
1230 x;#[instrument(level = "debug", skip_all, ret)]
1238 fn probe_single_ty_param_bound_for_assoc_item(
1239 &self,
1240 ty_param_def_id: LocalDefId,
1241 ty_param_span: Span,
1242 assoc_tag: ty::AssocTag,
1243 assoc_ident: Ident,
1244 span: Span,
1245 ) -> Result<ty::PolyTraitRef<'tcx>, ErrorGuaranteed> {
1246 debug!(?ty_param_def_id, ?assoc_ident, ?span);
1247 let tcx = self.tcx();
1248
1249 let predicates = &self.probe_ty_param_bounds(span, ty_param_def_id, assoc_ident);
1250 debug!("predicates={:#?}", predicates);
1251
1252 self.probe_single_bound_for_assoc_item(
1253 || {
1254 let trait_refs = predicates
1255 .iter_identity_copied()
1256 .map(Unnormalized::skip_norm_wip)
1257 .filter_map(|(p, _)| Some(p.as_trait_clause()?.map_bound(|t| t.trait_ref)));
1258 traits::transitive_bounds_that_define_assoc_item(tcx, trait_refs, assoc_ident)
1259 },
1260 AssocItemQSelf::TyParam(ty_param_def_id, ty_param_span),
1261 assoc_tag,
1262 assoc_ident,
1263 span,
1264 None,
1265 )
1266 }
1267
1268 fn collapse_candidates_to_subtrait_pick(
1278 &self,
1279 matching_candidates: &[ty::PolyTraitRef<'tcx>],
1280 ) -> Option<ty::PolyTraitRef<'tcx>> {
1281 if !self.tcx().features().supertrait_item_shadowing() {
1282 return None;
1283 }
1284
1285 let mut child_trait = matching_candidates[0];
1286 let mut supertraits: SsoHashSet<_> =
1287 traits::supertrait_def_ids(self.tcx(), child_trait.def_id()).collect();
1288
1289 let mut remaining_candidates: Vec<_> = matching_candidates[1..].iter().copied().collect();
1290 while !remaining_candidates.is_empty() {
1291 let mut made_progress = false;
1292 let mut next_round = ::alloc::vec::Vec::new()vec![];
1293
1294 for remaining_trait in remaining_candidates {
1295 if supertraits.contains(&remaining_trait.def_id()) {
1296 made_progress = true;
1297 continue;
1298 }
1299
1300 let remaining_trait_supertraits: SsoHashSet<_> =
1306 traits::supertrait_def_ids(self.tcx(), remaining_trait.def_id()).collect();
1307 if remaining_trait_supertraits.contains(&child_trait.def_id()) {
1308 child_trait = remaining_trait;
1309 supertraits = remaining_trait_supertraits;
1310 made_progress = true;
1311 continue;
1312 }
1313
1314 next_round.push(remaining_trait);
1321 }
1322
1323 if made_progress {
1324 remaining_candidates = next_round;
1326 } else {
1327 return None;
1330 }
1331 }
1332
1333 Some(child_trait)
1334 }
1335
1336 x;#[instrument(level = "debug", skip(self, all_candidates, qself, constraint), ret)]
1342 fn probe_single_bound_for_assoc_item<I>(
1343 &self,
1344 all_candidates: impl Fn() -> I,
1345 qself: AssocItemQSelf,
1346 assoc_tag: ty::AssocTag,
1347 assoc_ident: Ident,
1348 span: Span,
1349 constraint: Option<&hir::AssocItemConstraint<'tcx>>,
1350 ) -> Result<ty::PolyTraitRef<'tcx>, ErrorGuaranteed>
1351 where
1352 I: Iterator<Item = ty::PolyTraitRef<'tcx>>,
1353 {
1354 let mut matching_candidates = all_candidates().filter(|r| {
1355 self.probe_trait_that_defines_assoc_item(r.def_id(), assoc_tag, assoc_ident)
1356 });
1357
1358 let Some(bound1) = matching_candidates.next() else {
1359 return Err(self.report_unresolved_assoc_item(
1360 all_candidates,
1361 qself,
1362 assoc_tag,
1363 assoc_ident,
1364 span,
1365 constraint,
1366 ));
1367 };
1368
1369 if let Some(bound2) = matching_candidates.next() {
1370 let all_matching_candidates: Vec<_> =
1371 [bound1, bound2].into_iter().chain(matching_candidates).collect();
1372 if let Some(bound) = self.collapse_candidates_to_subtrait_pick(&all_matching_candidates)
1373 {
1374 return Ok(bound);
1375 }
1376
1377 return Err(self.report_ambiguous_assoc_item(
1378 &all_matching_candidates,
1379 qself,
1380 assoc_tag,
1381 assoc_ident,
1382 span,
1383 constraint,
1384 ));
1385 }
1386
1387 Ok(bound1)
1388 }
1389
1390 x;#[instrument(level = "debug", skip_all, ret)]
1417 pub fn lower_type_relative_ty_path(
1418 &self,
1419 self_ty: Ty<'tcx>,
1420 hir_self_ty: &'tcx hir::Ty<'tcx>,
1421 segment: &'tcx hir::PathSegment<'tcx>,
1422 qpath_hir_id: HirId,
1423 span: Span,
1424 permit_variants: PermitVariants,
1425 ) -> Result<(Ty<'tcx>, DefKind, DefId), ErrorGuaranteed> {
1426 let tcx = self.tcx();
1427 match self.lower_type_relative_path(
1428 self_ty,
1429 hir_self_ty,
1430 segment,
1431 qpath_hir_id,
1432 span,
1433 LowerTypeRelativePathMode::Type(permit_variants),
1434 )? {
1435 TypeRelativePath::AssocItem(alias_term) => {
1436 let alias_ty = alias_term.expect_ty();
1437 let def_id = match alias_ty.kind {
1438 ty::AliasTyKind::Projection { def_id } => def_id,
1439 ty::AliasTyKind::Inherent { def_id } => def_id,
1440 kind => bug!("expected projection or inherent alias, got {kind:?}"),
1441 };
1442 let ty = alias_ty.to_ty(tcx, ty::IsRigid::No);
1443 let ty = self.check_param_uses_if_mcg(ty, span, false);
1444 Ok((ty, tcx.def_kind(def_id), def_id))
1445 }
1446 TypeRelativePath::Variant { adt, variant_did } => {
1447 let adt = self.check_param_uses_if_mcg(adt, span, false);
1448 Ok((adt, DefKind::Variant, variant_did))
1449 }
1450 TypeRelativePath::Ctor { .. } => {
1451 let e = tcx.dcx().span_err(span, "expected type, found tuple constructor");
1452 Err(e)
1453 }
1454 }
1455 }
1456
1457 x;#[instrument(level = "debug", skip_all, ret)]
1459 fn lower_type_relative_const_path(
1460 &self,
1461 self_ty: Ty<'tcx>,
1462 hir_self_ty: &'tcx hir::Ty<'tcx>,
1463 segment: &'tcx hir::PathSegment<'tcx>,
1464 qpath_hir_id: HirId,
1465 span: Span,
1466 ) -> Result<Const<'tcx>, ErrorGuaranteed> {
1467 let tcx = self.tcx();
1468 match self.lower_type_relative_path(
1469 self_ty,
1470 hir_self_ty,
1471 segment,
1472 qpath_hir_id,
1473 span,
1474 LowerTypeRelativePathMode::Const,
1475 )? {
1476 TypeRelativePath::AssocItem(alias_term) => {
1477 let alias_ct = alias_term.expect_ct();
1478 if let Some(def_id) = alias_ct.kind.opt_def_id() {
1479 self.require_type_const_attribute(def_id, span)?;
1480 }
1481 let ct = Const::new_alias(tcx, ty::IsRigid::No, alias_ct);
1482 let ct = self.check_param_uses_if_mcg(ct, span, false);
1483 Ok(ct)
1484 }
1485 TypeRelativePath::Ctor { ctor_def_id, args } => match tcx.def_kind(ctor_def_id) {
1486 DefKind::Ctor(_, CtorKind::Fn) => {
1487 Ok(ty::Const::zero_sized(
1489 tcx,
1490 Ty::new_fn_def(tcx, ctor_def_id, ty::Binder::dummy(args)),
1491 ))
1492 }
1493 DefKind::Ctor(ctor_of, CtorKind::Const) => {
1494 Ok(self.construct_const_ctor_value(ctor_def_id, ctor_of, args))
1495 }
1496 _ => unreachable!(),
1497 },
1498 TypeRelativePath::Variant { .. } => {
1501 span_bug!(span, "unexpected variant res for type associated const path")
1502 }
1503 }
1504 }
1505
1506 x;#[instrument(level = "debug", skip_all, ret)]
1508 fn lower_type_relative_path(
1509 &self,
1510 self_ty: Ty<'tcx>,
1511 hir_self_ty: &'tcx hir::Ty<'tcx>,
1512 segment: &'tcx hir::PathSegment<'tcx>,
1513 qpath_hir_id: HirId,
1514 span: Span,
1515 mode: LowerTypeRelativePathMode,
1516 ) -> Result<TypeRelativePath<'tcx>, ErrorGuaranteed> {
1517 debug!(%self_ty, ?segment.ident);
1518 let tcx = self.tcx();
1519
1520 let mut variant_def_id = None;
1522 if let Some(adt_def) = self.probe_adt(span, self_ty) {
1523 if adt_def.is_enum() {
1524 let variant_def = adt_def
1525 .variants()
1526 .iter()
1527 .find(|vd| tcx.hygienic_eq(segment.ident, vd.ident(tcx), adt_def.did()));
1528 if let Some(variant_def) = variant_def {
1529 if matches!(mode, LowerTypeRelativePathMode::Const)
1532 && let Some((_, ctor_def_id)) = variant_def.ctor
1533 {
1534 tcx.check_stability(variant_def.def_id, Some(qpath_hir_id), span, None);
1535 let _ = self.prohibit_generic_args(
1536 slice::from_ref(segment).iter(),
1537 GenericsArgsErrExtend::EnumVariant {
1538 qself: hir_self_ty,
1539 assoc_segment: segment,
1540 adt_def,
1541 },
1542 );
1543 let ty::Adt(_, enum_args) = self_ty.kind() else { unreachable!() };
1544 return Ok(TypeRelativePath::Ctor { ctor_def_id, args: enum_args });
1545 }
1546 if let PermitVariants::Yes = mode.permit_variants() {
1547 tcx.check_stability(variant_def.def_id, Some(qpath_hir_id), span, None);
1548 let _ = self.prohibit_generic_args(
1549 slice::from_ref(segment).iter(),
1550 GenericsArgsErrExtend::EnumVariant {
1551 qself: hir_self_ty,
1552 assoc_segment: segment,
1553 adt_def,
1554 },
1555 );
1556 return Ok(TypeRelativePath::Variant {
1557 adt: self_ty,
1558 variant_did: variant_def.def_id,
1559 });
1560 } else {
1561 variant_def_id = Some(variant_def.def_id);
1562 }
1563 }
1564 }
1565
1566 if let Some(alias_term) = self.probe_inherent_assoc_item(
1568 segment,
1569 adt_def.did(),
1570 self_ty,
1571 qpath_hir_id,
1572 span,
1573 mode.assoc_tag(),
1574 )? {
1575 return Ok(TypeRelativePath::AssocItem(alias_term));
1576 }
1577 }
1578
1579 let (item_def_id, bound) = self.resolve_type_relative_path(
1580 self_ty,
1581 hir_self_ty,
1582 mode.assoc_tag(),
1583 segment,
1584 qpath_hir_id,
1585 span,
1586 variant_def_id,
1587 )?;
1588
1589 let (item_def_id, args) = self.lower_assoc_item_path(span, item_def_id, segment, bound)?;
1590
1591 if let Some(variant_def_id) = variant_def_id {
1592 tcx.emit_node_span_lint(
1593 AMBIGUOUS_ASSOCIATED_ITEMS,
1594 qpath_hir_id,
1595 span,
1596 errors::AmbiguityBetweenVariantAndAssocItem {
1597 variant_def_id,
1598 item_def_id,
1599 span,
1600 segment_ident: segment.ident,
1601 bound_def_id: bound.def_id(),
1602 self_ty,
1603 tcx,
1604 mode,
1605 },
1606 );
1607 }
1608
1609 Ok(TypeRelativePath::AssocItem(ty::AliasTerm::new_from_def_id(tcx, item_def_id, args)))
1610 }
1611
1612 fn resolve_type_relative_path(
1614 &self,
1615 self_ty: Ty<'tcx>,
1616 hir_self_ty: &'tcx hir::Ty<'tcx>,
1617 assoc_tag: ty::AssocTag,
1618 segment: &'tcx hir::PathSegment<'tcx>,
1619 qpath_hir_id: HirId,
1620 span: Span,
1621 variant_def_id: Option<DefId>,
1622 ) -> Result<(DefId, ty::PolyTraitRef<'tcx>), ErrorGuaranteed> {
1623 let tcx = self.tcx();
1624
1625 let self_ty_res = match hir_self_ty.kind {
1626 hir::TyKind::Path(hir::QPath::Resolved(_, path)) => path.res,
1627 _ => Res::Err,
1628 };
1629
1630 let bound = match (self_ty.kind(), self_ty_res) {
1632 (_, Res::SelfTyAlias { alias_to: impl_def_id, is_trait_impl: true, .. }) => {
1633 let trait_ref = tcx.impl_trait_ref(impl_def_id);
1636
1637 self.probe_single_bound_for_assoc_item(
1638 || {
1639 let trait_ref =
1640 ty::Binder::dummy(trait_ref.instantiate_identity().skip_norm_wip());
1641 traits::supertraits(tcx, trait_ref)
1642 },
1643 AssocItemQSelf::SelfTyAlias,
1644 assoc_tag,
1645 segment.ident,
1646 span,
1647 None,
1648 )?
1649 }
1650 (
1651 &ty::Param(_),
1652 Res::SelfTyParam { trait_: param_did } | Res::Def(DefKind::TyParam, param_did),
1653 ) => self.probe_single_ty_param_bound_for_assoc_item(
1654 param_did.expect_local(),
1655 hir_self_ty.span,
1656 assoc_tag,
1657 segment.ident,
1658 span,
1659 )?,
1660 _ => {
1661 return Err(self.report_unresolved_type_relative_path(
1662 self_ty,
1663 hir_self_ty,
1664 assoc_tag,
1665 segment.ident,
1666 qpath_hir_id,
1667 span,
1668 variant_def_id,
1669 ));
1670 }
1671 };
1672
1673 let assoc_item = self
1674 .probe_assoc_item(segment.ident, assoc_tag, qpath_hir_id, span, bound.def_id())
1675 .expect("failed to find associated item");
1676
1677 Ok((assoc_item.def_id, bound))
1678 }
1679
1680 fn probe_inherent_assoc_item(
1682 &self,
1683 segment: &hir::PathSegment<'tcx>,
1684 adt_did: DefId,
1685 self_ty: Ty<'tcx>,
1686 block: HirId,
1687 span: Span,
1688 assoc_tag: ty::AssocTag,
1689 ) -> Result<Option<ty::AliasTerm<'tcx>>, ErrorGuaranteed> {
1690 let tcx = self.tcx();
1691
1692 if !tcx.features().inherent_associated_types() {
1693 match assoc_tag {
1694 ty::AssocTag::Type => return Ok(None),
1699 ty::AssocTag::Const => {
1700 return Err(feature_err(
1704 &tcx.sess,
1705 sym::inherent_associated_types,
1706 span,
1707 "inherent associated types are unstable",
1708 )
1709 .emit());
1710 }
1711 ty::AssocTag::Fn => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1712 }
1713 }
1714
1715 let name = segment.ident;
1716 let candidates: Vec<_> = tcx
1717 .inherent_impls(adt_did)
1718 .iter()
1719 .filter_map(|&impl_| {
1720 let (item, scope) = self.probe_assoc_item_unchecked(name, assoc_tag, impl_)?;
1721 Some(InherentAssocCandidate { impl_, assoc_item: item.def_id, scope })
1722 })
1723 .collect();
1724
1725 if candidates.is_empty() {
1730 return Ok(None);
1731 }
1732
1733 let (applicable_candidates, fulfillment_errors) =
1734 self.select_inherent_assoc_candidates(span, self_ty, candidates.clone());
1735
1736 let InherentAssocCandidate { impl_, assoc_item, scope: def_scope } =
1738 match &applicable_candidates[..] {
1739 &[] => Err(self.report_unresolved_inherent_assoc_item(
1740 name,
1741 self_ty,
1742 candidates,
1743 fulfillment_errors,
1744 span,
1745 assoc_tag,
1746 )),
1747
1748 &[applicable_candidate] => Ok(applicable_candidate),
1749
1750 &[_, ..] => Err(self.report_ambiguous_inherent_assoc_item(
1751 name,
1752 candidates.into_iter().map(|cand| cand.assoc_item).collect(),
1753 span,
1754 )),
1755 }?;
1756
1757 self.check_assoc_item(assoc_item, name, def_scope, block, span);
1760
1761 let parent_args = ty::GenericArgs::identity_for_item(tcx, impl_);
1765 let args = self.lower_generic_args_of_assoc_item(span, assoc_item, segment, parent_args);
1766 let args = tcx.mk_args_from_iter(
1767 std::iter::once(ty::GenericArg::from(self_ty))
1768 .chain(args.into_iter().skip(parent_args.len())),
1769 );
1770
1771 let kind = match assoc_tag {
1772 ty::AssocTag::Type => ty::AliasTermKind::InherentTy { def_id: assoc_item },
1773 ty::AssocTag::Const => {
1774 self.require_type_const_attribute(assoc_item, span)?;
1777 ty::AliasTermKind::InherentConst { def_id: assoc_item }
1778 }
1779 ty::AssocTag::Fn => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1780 };
1781
1782 Ok(Some(ty::AliasTerm::new_from_args(tcx, kind, args)))
1783 }
1784
1785 fn probe_assoc_item(
1789 &self,
1790 ident: Ident,
1791 assoc_tag: ty::AssocTag,
1792 block: HirId,
1793 span: Span,
1794 scope: DefId,
1795 ) -> Option<ty::AssocItem> {
1796 let (item, scope) = self.probe_assoc_item_unchecked(ident, assoc_tag, scope)?;
1797 self.check_assoc_item(item.def_id, ident, scope, block, span);
1798 Some(item)
1799 }
1800
1801 fn probe_assoc_item_unchecked(
1806 &self,
1807 ident: Ident,
1808 assoc_tag: ty::AssocTag,
1809 scope: DefId,
1810 ) -> Option<(ty::AssocItem, ModId)> {
1811 let tcx = self.tcx();
1812
1813 let (ident, def_scope) = tcx.adjust_ident_and_get_scope(ident, scope, self.item_def_id());
1814 let item = tcx
1818 .associated_items(scope)
1819 .filter_by_name_unhygienic(ident.name)
1820 .find(|i| i.tag() == assoc_tag && i.ident(tcx).normalize_to_macros_2_0() == ident)?;
1821
1822 Some((*item, def_scope))
1823 }
1824
1825 fn check_assoc_item(
1827 &self,
1828 item_def_id: DefId,
1829 ident: Ident,
1830 scope: ModId,
1831 block: HirId,
1832 span: Span,
1833 ) {
1834 let tcx = self.tcx();
1835
1836 if !tcx.visibility(item_def_id).is_accessible_from(scope, tcx) {
1837 self.dcx().emit_err(crate::diagnostics::AssocItemIsPrivate {
1838 span,
1839 kind: tcx.def_descr(item_def_id),
1840 name: ident,
1841 defined_here_label: tcx.def_span(item_def_id),
1842 });
1843 }
1844
1845 tcx.check_stability(item_def_id, Some(block), span, None);
1846 }
1847
1848 fn probe_traits_that_match_assoc_ty(
1849 &self,
1850 qself_ty: Ty<'tcx>,
1851 assoc_ident: Ident,
1852 ) -> Vec<String> {
1853 let tcx = self.tcx();
1854
1855 let infcx_;
1858 let infcx = if let Some(infcx) = self.infcx() {
1859 infcx
1860 } else {
1861 if !!qself_ty.has_infer() {
::core::panicking::panic("assertion failed: !qself_ty.has_infer()")
};assert!(!qself_ty.has_infer());
1862 infcx_ = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
1863 &infcx_
1864 };
1865
1866 tcx.all_traits_including_private()
1867 .filter(|trait_def_id| {
1868 tcx.associated_items(*trait_def_id)
1870 .in_definition_order()
1871 .any(|i| {
1872 i.is_type()
1873 && !i.is_impl_trait_in_trait()
1874 && i.ident(tcx).normalize_to_macros_2_0() == assoc_ident
1875 })
1876 && tcx.visibility(*trait_def_id)
1878 .is_accessible_from(self.item_def_id(), tcx)
1879 && tcx.all_impls(*trait_def_id)
1880 .any(|impl_def_id| {
1881 let header = tcx.impl_trait_header(impl_def_id);
1882 let trait_ref = header.trait_ref.instantiate(tcx, infcx.fresh_args_for_item(DUMMY_SP, impl_def_id)).skip_norm_wip();
1883
1884 let value = fold_regions(tcx, qself_ty, |_, _| tcx.lifetimes.re_erased);
1885 if value.has_escaping_bound_vars() {
1887 return false;
1888 }
1889 infcx
1890 .can_eq(
1891 ty::ParamEnv::empty(),
1892 trait_ref.self_ty(),
1893 value,
1894 ) && header.polarity != ty::ImplPolarity::Negative
1895 })
1896 })
1897 .map(|trait_def_id| tcx.def_path_str(trait_def_id))
1898 .collect()
1899 }
1900
1901 #[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(1902u32),
::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_all(&[]) })
} 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(), ty::IsRigid::No,
item_def_id, item_args)
}
Err(guar) => Ty::new_error(self.tcx(), guar),
}
}
}
}#[instrument(level = "debug", skip_all)]
1903 fn lower_resolved_assoc_ty_path(
1904 &self,
1905 span: Span,
1906 opt_self_ty: Option<Ty<'tcx>>,
1907 item_def_id: DefId,
1908 trait_segment: Option<&hir::PathSegment<'tcx>>,
1909 item_segment: &hir::PathSegment<'tcx>,
1910 ) -> Ty<'tcx> {
1911 match self.lower_resolved_assoc_item_path(
1912 span,
1913 opt_self_ty,
1914 item_def_id,
1915 trait_segment,
1916 item_segment,
1917 ty::AssocTag::Type,
1918 ) {
1919 Ok((item_def_id, item_args)) => {
1920 Ty::new_projection_from_args(self.tcx(), ty::IsRigid::No, item_def_id, item_args)
1921 }
1922 Err(guar) => Ty::new_error(self.tcx(), guar),
1923 }
1924 }
1925
1926 #[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(1927u32),
::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_all(&[]) })
} 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 tcx = self.tcx();
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 alias_const =
ty::AliasConst::new(tcx,
ty::AliasConstKind::new_from_def_id(tcx, item_def_id),
item_args);
Ok(Const::new_alias(tcx, ty::IsRigid::No, alias_const))
}
}
}#[instrument(level = "debug", skip_all)]
1928 fn lower_resolved_assoc_const_path(
1929 &self,
1930 span: Span,
1931 opt_self_ty: Option<Ty<'tcx>>,
1932 item_def_id: DefId,
1933 trait_segment: Option<&hir::PathSegment<'tcx>>,
1934 item_segment: &hir::PathSegment<'tcx>,
1935 ) -> Result<Const<'tcx>, ErrorGuaranteed> {
1936 let tcx = self.tcx();
1937 let (item_def_id, item_args) = self.lower_resolved_assoc_item_path(
1938 span,
1939 opt_self_ty,
1940 item_def_id,
1941 trait_segment,
1942 item_segment,
1943 ty::AssocTag::Const,
1944 )?;
1945 self.require_type_const_attribute(item_def_id, span)?;
1946 let alias_const = ty::AliasConst::new(
1947 tcx,
1948 ty::AliasConstKind::new_from_def_id(tcx, item_def_id),
1949 item_args,
1950 );
1951 Ok(Const::new_alias(tcx, ty::IsRigid::No, alias_const))
1952 }
1953
1954 #[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(1955u32),
::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_all(&[]) })
} 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:1968",
"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(1968u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("trait_def_id")
}> =
::tracing::__macro_support::FieldName::new("trait_def_id");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_def_id)
as &dyn ::tracing::field::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:1978",
"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(1978u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("self_ty")
}> =
::tracing::__macro_support::FieldName::new("self_ty");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self_ty)
as &dyn ::tracing::field::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:1982",
"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(1982u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("trait_ref")
}> =
::tracing::__macro_support::FieldName::new("trait_ref");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_ref)
as &dyn ::tracing::field::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)]
1956 fn lower_resolved_assoc_item_path(
1957 &self,
1958 span: Span,
1959 opt_self_ty: Option<Ty<'tcx>>,
1960 item_def_id: DefId,
1961 trait_segment: Option<&hir::PathSegment<'tcx>>,
1962 item_segment: &hir::PathSegment<'tcx>,
1963 assoc_tag: ty::AssocTag,
1964 ) -> Result<(DefId, GenericArgsRef<'tcx>), ErrorGuaranteed> {
1965 let tcx = self.tcx();
1966
1967 let trait_def_id = tcx.parent(item_def_id);
1968 debug!(?trait_def_id);
1969
1970 let Some(self_ty) = opt_self_ty else {
1971 return Err(self.report_missing_self_ty_for_resolved_path(
1972 trait_def_id,
1973 span,
1974 item_segment,
1975 assoc_tag,
1976 ));
1977 };
1978 debug!(?self_ty);
1979
1980 let trait_ref =
1981 self.lower_mono_trait_ref(span, trait_def_id, self_ty, trait_segment.unwrap(), false);
1982 debug!(?trait_ref);
1983
1984 let item_args =
1985 self.lower_generic_args_of_assoc_item(span, item_def_id, item_segment, trait_ref.args);
1986
1987 Ok((item_def_id, item_args))
1988 }
1989
1990 pub fn prohibit_generic_args<'a>(
1991 &self,
1992 segments: impl Iterator<Item = &'a hir::PathSegment<'a>> + Clone,
1993 err_extend: GenericsArgsErrExtend<'a>,
1994 ) -> Result<(), ErrorGuaranteed> {
1995 let args_visitors = segments.clone().flat_map(|segment| segment.args().args);
1996 let mut result = Ok(());
1997 if let Some(_) = args_visitors.clone().next() {
1998 result = Err(self.report_prohibited_generic_args(
1999 segments.clone(),
2000 args_visitors,
2001 err_extend,
2002 ));
2003 }
2004
2005 for segment in segments {
2006 if let Some(c) = segment.args().constraints.first() {
2008 return Err(prohibit_assoc_item_constraint(self, c, None));
2009 }
2010 }
2011
2012 result
2013 }
2014
2015 pub fn probe_generic_path_segments(
2033 &self,
2034 segments: &[hir::PathSegment<'_>],
2035 self_ty: Option<Ty<'tcx>>,
2036 kind: DefKind,
2037 def_id: DefId,
2038 span: Span,
2039 ) -> Vec<GenericPathSegment> {
2040 let tcx = self.tcx();
2086
2087 if !!segments.is_empty() {
::core::panicking::panic("assertion failed: !segments.is_empty()")
};assert!(!segments.is_empty());
2088 let last = segments.len() - 1;
2089
2090 let mut generic_segments = ::alloc::vec::Vec::new()vec![];
2091
2092 match kind {
2093 DefKind::Ctor(CtorOf::Struct, ..) => {
2095 let generics = tcx.generics_of(def_id);
2098 let generics_def_id = generics.parent.unwrap_or(def_id);
2101 generic_segments.push(GenericPathSegment(generics_def_id, last));
2102 }
2103
2104 DefKind::Ctor(CtorOf::Variant, ..) | DefKind::Variant => {
2106 let (generics_def_id, index) = if let Some(self_ty) = self_ty {
2107 let adt_def = self.probe_adt(span, self_ty).unwrap();
2110 if true {
if !adt_def.is_enum() {
::core::panicking::panic("assertion failed: adt_def.is_enum()")
};
};debug_assert!(adt_def.is_enum());
2111
2112 (adt_def.did(), last)
2124 } else if let [.., second_to_last, _] = segments
2125 && second_to_last.args.is_some()
2126 && let Res::Def(DefKind::Enum, _) = second_to_last.res
2127 {
2128 let def_id = match kind {
2137 DefKind::Ctor(..) => tcx.parent(def_id),
2138 _ => def_id,
2139 };
2140
2141 let enum_def_id = tcx.parent(def_id);
2143
2144 (enum_def_id, last - 1)
2145 } else {
2146 let generics = tcx.generics_of(def_id);
2153 (generics.parent.unwrap_or(def_id), last)
2156 };
2157 generic_segments.push(GenericPathSegment(generics_def_id, index));
2158 }
2159
2160 DefKind::Fn | DefKind::Const { .. } | DefKind::ConstParam | DefKind::Static { .. } => {
2162 generic_segments.push(GenericPathSegment(def_id, last));
2163 }
2164
2165 DefKind::AssocFn | DefKind::AssocConst { .. } => {
2167 if segments.len() >= 2 {
2168 let generics = tcx.generics_of(def_id);
2169 generic_segments.push(GenericPathSegment(generics.parent.unwrap(), last - 1));
2170 }
2171 generic_segments.push(GenericPathSegment(def_id, last));
2172 }
2173
2174 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),
2175 }
2176
2177 {
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:2177",
"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(2177u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("generic_segments")
}> =
::tracing::__macro_support::FieldName::new("generic_segments");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&generic_segments)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?generic_segments);
2178
2179 generic_segments
2180 }
2181
2182 #[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(2183u32),
::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_all(&[]) })
} 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:2191",
"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(2191u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("path.res")
}> =
::tracing::__macro_support::FieldName::new("path.res");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("opt_self_ty")
}> =
::tracing::__macro_support::FieldName::new("opt_self_ty");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("path.segments")
}> =
::tracing::__macro_support::FieldName::new("path.segments");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&path.res)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&opt_self_ty)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&path.segments)
as &dyn ::tracing::field::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, ty::IsRigid::No, 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().skip_norm_wip();
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)]
2184 pub fn lower_resolved_ty_path(
2185 &self,
2186 opt_self_ty: Option<Ty<'tcx>>,
2187 path: &hir::Path<'tcx>,
2188 hir_id: HirId,
2189 permit_variants: PermitVariants,
2190 ) -> Ty<'tcx> {
2191 debug!(?path.res, ?opt_self_ty, ?path.segments);
2192 let tcx = self.tcx();
2193
2194 let span = path.span;
2195 match path.res {
2196 Res::Def(DefKind::OpaqueTy, did) => {
2197 assert_matches!(tcx.opaque_ty_origin(did), hir::OpaqueTyOrigin::TyAlias { .. });
2199 let [leading_segments @ .., segment] = path.segments else { bug!() };
2200 let _ = self.prohibit_generic_args(
2201 leading_segments.iter(),
2202 GenericsArgsErrExtend::OpaqueTy,
2203 );
2204 let args = self.lower_generic_args_of_path_segment(span, did, segment);
2205 Ty::new_opaque(tcx, ty::IsRigid::No, did, args)
2206 }
2207 Res::Def(
2208 DefKind::Enum
2209 | DefKind::TyAlias
2210 | DefKind::Struct
2211 | DefKind::Union
2212 | DefKind::ForeignTy,
2213 did,
2214 ) => {
2215 assert_eq!(opt_self_ty, None);
2216 let [leading_segments @ .., segment] = path.segments else { bug!() };
2217 let _ = self
2218 .prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
2219 self.lower_path_segment(span, did, segment)
2220 }
2221 Res::Def(kind @ DefKind::Variant, def_id)
2222 if let PermitVariants::Yes = permit_variants =>
2223 {
2224 assert_eq!(opt_self_ty, None);
2227
2228 let generic_segments =
2229 self.probe_generic_path_segments(path.segments, None, kind, def_id, span);
2230 let indices: FxHashSet<_> =
2231 generic_segments.iter().map(|GenericPathSegment(_, index)| index).collect();
2232 let _ = self.prohibit_generic_args(
2233 path.segments.iter().enumerate().filter_map(|(index, seg)| {
2234 if !indices.contains(&index) { Some(seg) } else { None }
2235 }),
2236 GenericsArgsErrExtend::DefVariant(&path.segments),
2237 );
2238
2239 let &GenericPathSegment(def_id, index) = generic_segments.last().unwrap();
2240 self.lower_path_segment(span, def_id, &path.segments[index])
2241 }
2242 Res::Def(DefKind::TyParam, def_id) => {
2243 assert_eq!(opt_self_ty, None);
2244 let _ = self.prohibit_generic_args(
2245 path.segments.iter(),
2246 GenericsArgsErrExtend::Param(def_id),
2247 );
2248 self.lower_ty_param(hir_id)
2249 }
2250 Res::SelfTyParam { .. } => {
2251 assert_eq!(opt_self_ty, None);
2253 let _ = self.prohibit_generic_args(
2254 path.segments.iter(),
2255 if let [hir::PathSegment { args: Some(args), ident, .. }] = &path.segments {
2256 GenericsArgsErrExtend::SelfTyParam(
2257 ident.span.shrink_to_hi().to(args.span_ext),
2258 )
2259 } else {
2260 GenericsArgsErrExtend::None
2261 },
2262 );
2263 self.check_param_uses_if_mcg(tcx.types.self_param, span, false)
2264 }
2265 Res::SelfTyAlias { alias_to: def_id, .. } => {
2266 assert_eq!(opt_self_ty, None);
2268 let ty = tcx.at(span).type_of(def_id).instantiate_identity().skip_norm_wip();
2270 let _ = self.prohibit_generic_args(
2271 path.segments.iter(),
2272 GenericsArgsErrExtend::SelfTyAlias { def_id, span },
2273 );
2274 self.check_param_uses_if_mcg(ty, span, true)
2275 }
2276 Res::Def(DefKind::AssocTy, def_id) => {
2277 let trait_segment = if let [modules @ .., trait_, _item] = path.segments {
2278 let _ = self.prohibit_generic_args(modules.iter(), GenericsArgsErrExtend::None);
2279 Some(trait_)
2280 } else {
2281 None
2282 };
2283 self.lower_resolved_assoc_ty_path(
2284 span,
2285 opt_self_ty,
2286 def_id,
2287 trait_segment,
2288 path.segments.last().unwrap(),
2289 )
2290 }
2291 Res::PrimTy(prim_ty) => {
2292 assert_eq!(opt_self_ty, None);
2293 let _ = self.prohibit_generic_args(
2294 path.segments.iter(),
2295 GenericsArgsErrExtend::PrimTy(prim_ty),
2296 );
2297 match prim_ty {
2298 hir::PrimTy::Bool => tcx.types.bool,
2299 hir::PrimTy::Char => tcx.types.char,
2300 hir::PrimTy::Int(it) => Ty::new_int(tcx, it),
2301 hir::PrimTy::Uint(uit) => Ty::new_uint(tcx, uit),
2302 hir::PrimTy::Float(ft) => Ty::new_float(tcx, ft),
2303 hir::PrimTy::Str => tcx.types.str_,
2304 }
2305 }
2306 Res::Err => {
2307 let e = self
2308 .tcx()
2309 .dcx()
2310 .span_delayed_bug(path.span, "path with `Res::Err` but no error emitted");
2311 Ty::new_error(tcx, e)
2312 }
2313 Res::Def(..) => {
2314 assert_eq!(
2315 path.segments.get(0).map(|seg| seg.ident.name),
2316 Some(kw::SelfUpper),
2317 "only expected incorrect resolution for `Self`"
2318 );
2319 Ty::new_error(
2320 self.tcx(),
2321 self.dcx().span_delayed_bug(span, "incorrect resolution for `Self`"),
2322 )
2323 }
2324 _ => span_bug!(span, "unexpected resolution: {:?}", path.res),
2325 }
2326 }
2327
2328 pub(crate) fn lower_ty_param(&self, hir_id: HirId) -> Ty<'tcx> {
2333 let tcx = self.tcx();
2334
2335 let ty = match tcx.named_bound_var(hir_id) {
2336 Some(rbv::ResolvedArg::LateBound(debruijn, index, def_id)) => {
2337 let br = ty::BoundTy {
2338 var: ty::BoundVar::from_u32(index),
2339 kind: ty::BoundTyKind::Param(def_id.to_def_id()),
2340 };
2341 Ty::new_bound(tcx, debruijn, br)
2342 }
2343 Some(rbv::ResolvedArg::EarlyBound(def_id)) => {
2344 let item_def_id = tcx.hir_ty_param_owner(def_id);
2345 let generics = tcx.generics_of(item_def_id);
2346 let index = generics.param_def_id_to_index[&def_id.to_def_id()];
2347 Ty::new_param(tcx, index, tcx.hir_ty_param_name(def_id))
2348 }
2349 Some(rbv::ResolvedArg::Error(guar)) => Ty::new_error(tcx, guar),
2350 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:?}"),
2351 };
2352 self.check_param_uses_if_mcg(ty, tcx.hir_span(hir_id), false)
2353 }
2354
2355 pub(crate) fn lower_const_param(&self, param_def_id: DefId, path_hir_id: HirId) -> Const<'tcx> {
2360 let tcx = self.tcx();
2361
2362 let ct = match tcx.named_bound_var(path_hir_id) {
2363 Some(rbv::ResolvedArg::EarlyBound(_)) => {
2364 let item_def_id = tcx.parent(param_def_id);
2367 let generics = tcx.generics_of(item_def_id);
2368 let index = generics.param_def_id_to_index[¶m_def_id];
2369 let name = tcx.item_name(param_def_id);
2370 ty::Const::new_param(tcx, ty::ParamConst::new(index, name))
2371 }
2372 Some(rbv::ResolvedArg::LateBound(debruijn, index, _)) => ty::Const::new_bound(
2373 tcx,
2374 debruijn,
2375 ty::BoundConst::new(ty::BoundVar::from_u32(index)),
2376 ),
2377 Some(rbv::ResolvedArg::Error(guar)) => ty::Const::new_error(tcx, guar),
2378 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),
2379 };
2380 self.check_param_uses_if_mcg(ct, tcx.hir_span(path_hir_id), false)
2381 }
2382
2383 #[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(2384u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("const_arg")
}> =
::tracing::__macro_support::FieldName::new("const_arg");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("ty")
}> =
::tracing::__macro_support::FieldName::new("ty");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&const_arg)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty)
as &dyn ::tracing::field::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(tcx, 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(tcx, 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(tcx, Ty::new_error(tcx, e)));
return ty::Const::new_error(tcx, e);
}
tcx.feed_anon_const_type(anon.def_id,
ty::EarlyBinder::bind(tcx, 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:2445",
"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(2445u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("maybe_qself")
}> =
::tracing::__macro_support::FieldName::new("maybe_qself");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("path")
}> =
::tracing::__macro_support::FieldName::new("path");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&maybe_qself)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&path)
as &dyn ::tracing::field::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:2450",
"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(2450u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("hir_self_ty")
}> =
::tracing::__macro_support::FieldName::new("hir_self_ty");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("segment")
}> =
::tracing::__macro_support::FieldName::new("segment");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&hir_self_ty)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&segment)
as &dyn ::tracing::field::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")]
2385 pub fn lower_const_arg(&self, const_arg: &hir::ConstArg<'tcx>, ty: Ty<'tcx>) -> Const<'tcx> {
2386 let tcx = self.tcx();
2387
2388 if let hir::ConstArgKind::Anon(anon) = &const_arg.kind {
2389 if tcx.features().generic_const_parameter_types()
2398 && (ty.has_free_regions() || ty.has_erased_regions())
2399 {
2400 let e = self.dcx().span_err(
2401 const_arg.span,
2402 "anonymous constants with lifetimes in their type are not yet supported",
2403 );
2404 tcx.feed_anon_const_type(
2405 anon.def_id,
2406 ty::EarlyBinder::bind(tcx, Ty::new_error(tcx, e)),
2407 );
2408 return ty::Const::new_error(tcx, e);
2409 }
2410 if ty.has_non_region_infer() {
2414 let e = self.dcx().span_err(
2415 const_arg.span,
2416 "anonymous constants with inferred types are not yet supported",
2417 );
2418 tcx.feed_anon_const_type(
2419 anon.def_id,
2420 ty::EarlyBinder::bind(tcx, Ty::new_error(tcx, e)),
2421 );
2422 return ty::Const::new_error(tcx, e);
2423 }
2424 if ty.has_non_region_param() {
2427 let e = self.dcx().span_err(
2428 const_arg.span,
2429 "anonymous constants referencing generics are not yet supported",
2430 );
2431 tcx.feed_anon_const_type(
2432 anon.def_id,
2433 ty::EarlyBinder::bind(tcx, Ty::new_error(tcx, e)),
2434 );
2435 return ty::Const::new_error(tcx, e);
2436 }
2437
2438 tcx.feed_anon_const_type(anon.def_id, ty::EarlyBinder::bind(tcx, ty));
2439 }
2440
2441 let hir_id = const_arg.hir_id;
2442 match const_arg.kind {
2443 hir::ConstArgKind::Tup(exprs) => self.lower_const_arg_tup(exprs, ty, const_arg.span),
2444 hir::ConstArgKind::Path(hir::QPath::Resolved(maybe_qself, path)) => {
2445 debug!(?maybe_qself, ?path);
2446 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
2447 self.lower_resolved_const_path(opt_self_ty, path, hir_id)
2448 }
2449 hir::ConstArgKind::Path(hir::QPath::TypeRelative(hir_self_ty, segment)) => {
2450 debug!(?hir_self_ty, ?segment);
2451 let self_ty = self.lower_ty(hir_self_ty);
2452 self.lower_type_relative_const_path(
2453 self_ty,
2454 hir_self_ty,
2455 segment,
2456 hir_id,
2457 const_arg.span,
2458 )
2459 .unwrap_or_else(|guar| Const::new_error(tcx, guar))
2460 }
2461 hir::ConstArgKind::Struct(qpath, inits) => {
2462 self.lower_const_arg_struct(hir_id, qpath, inits, const_arg.span)
2463 }
2464 hir::ConstArgKind::TupleCall(qpath, args) => {
2465 self.lower_const_arg_tuple_call(hir_id, qpath, args, const_arg.span)
2466 }
2467 hir::ConstArgKind::Array(array_expr) => self.lower_const_arg_array(array_expr, ty),
2468 hir::ConstArgKind::Anon(anon) => self.lower_const_arg_anon(anon),
2469 hir::ConstArgKind::Infer(()) => self.ct_infer(None, const_arg.span),
2470 hir::ConstArgKind::Error(e) => ty::Const::new_error(tcx, e),
2471 hir::ConstArgKind::Literal { lit, negated } => {
2472 self.lower_const_arg_literal(&lit, negated, ty, const_arg.span)
2473 }
2474 }
2475 }
2476
2477 fn lower_const_arg_array(
2478 &self,
2479 array_expr: &'tcx hir::ConstArgArrayExpr<'tcx>,
2480 ty: Ty<'tcx>,
2481 ) -> Const<'tcx> {
2482 let tcx = self.tcx();
2483
2484 let elem_ty = match ty.kind() {
2485 ty::Array(elem_ty, _) => elem_ty,
2486 ty::Error(e) => return Const::new_error(tcx, *e),
2487 _ => {
2488 let e = tcx
2489 .dcx()
2490 .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));
2491 return Const::new_error(tcx, e);
2492 }
2493 };
2494
2495 let elems = array_expr
2496 .elems
2497 .iter()
2498 .map(|elem| self.lower_const_arg(elem, *elem_ty))
2499 .collect::<Vec<_>>();
2500
2501 let valtree = ty::ValTree::from_branches(tcx, elems);
2502
2503 ty::Const::new_value(tcx, valtree, ty)
2504 }
2505
2506 fn lower_const_arg_tuple_call(
2507 &self,
2508 hir_id: HirId,
2509 qpath: hir::QPath<'tcx>,
2510 args: &'tcx [&'tcx hir::ConstArg<'tcx>],
2511 span: Span,
2512 ) -> Const<'tcx> {
2513 let tcx = self.tcx();
2514
2515 let non_adt_or_variant_res = || {
2516 let e = tcx.dcx().span_err(span, "tuple constructor with invalid base path");
2517 ty::Const::new_error(tcx, e)
2518 };
2519
2520 let ctor_const = match qpath {
2521 hir::QPath::Resolved(maybe_qself, path) => {
2522 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
2523 self.lower_resolved_const_path(opt_self_ty, path, hir_id)
2524 }
2525 hir::QPath::TypeRelative(hir_self_ty, segment) => {
2526 let self_ty = self.lower_ty(hir_self_ty);
2527 match self.lower_type_relative_const_path(
2528 self_ty,
2529 hir_self_ty,
2530 segment,
2531 hir_id,
2532 span,
2533 ) {
2534 Ok(c) => c,
2535 Err(_) => return non_adt_or_variant_res(),
2536 }
2537 }
2538 };
2539
2540 let Some(value) = ctor_const.try_to_value() else {
2541 return non_adt_or_variant_res();
2542 };
2543
2544 let (adt_def, adt_args, variant_did) = match value.ty.kind() {
2545 ty::FnDef(def_id, fn_args)
2546 if let DefKind::Ctor(CtorOf::Variant, _) = tcx.def_kind(*def_id) =>
2547 {
2548 let parent_did = tcx.parent(*def_id);
2549 let enum_did = tcx.parent(parent_did);
2550 (tcx.adt_def(enum_did), fn_args, parent_did)
2551 }
2552 ty::FnDef(def_id, fn_args)
2553 if let DefKind::Ctor(CtorOf::Struct, _) = tcx.def_kind(*def_id) =>
2554 {
2555 let parent_did = tcx.parent(*def_id);
2556 (tcx.adt_def(parent_did), fn_args, parent_did)
2557 }
2558 _ => {
2559 let e = self.dcx().span_err(
2560 span,
2561 "complex const arguments must be placed inside of a `const` block",
2562 );
2563 return Const::new_error(tcx, e);
2564 }
2565 };
2566
2567 let variant_def = adt_def.variant_with_id(variant_did);
2568 let variant_idx = adt_def.variant_index_with_id(variant_did).as_u32();
2569
2570 if args.len() != variant_def.fields.len() {
2571 let e = tcx.dcx().span_err(
2572 span,
2573 ::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!(
2574 "tuple constructor has {} arguments but {} were provided",
2575 variant_def.fields.len(),
2576 args.len()
2577 ),
2578 );
2579 return ty::Const::new_error(tcx, e);
2580 }
2581
2582 let fields = variant_def
2583 .fields
2584 .iter()
2585 .zip(args)
2586 .map(|(field_def, arg)| {
2587 self.lower_const_arg(
2588 arg,
2589 tcx.type_of(field_def.did)
2590 .instantiate(tcx, adt_args.no_bound_vars().unwrap())
2591 .skip_norm_wip(),
2592 )
2593 })
2594 .collect::<Vec<_>>();
2595
2596 let opt_discr_const = if adt_def.is_enum() {
2597 let valtree = ty::ValTree::from_scalar_int(tcx, variant_idx.into());
2598 Some(ty::Const::new_value(tcx, valtree, tcx.types.u32))
2599 } else {
2600 None
2601 };
2602
2603 let valtree = ty::ValTree::from_branches(tcx, opt_discr_const.into_iter().chain(fields));
2604 let adt_ty = Ty::new_adt(tcx, adt_def, adt_args.no_bound_vars().unwrap());
2605 ty::Const::new_value(tcx, valtree, adt_ty)
2606 }
2607
2608 fn lower_const_arg_tup(
2609 &self,
2610 exprs: &'tcx [&'tcx hir::ConstArg<'tcx>],
2611 ty: Ty<'tcx>,
2612 span: Span,
2613 ) -> Const<'tcx> {
2614 let tcx = self.tcx();
2615
2616 let found_tuple = || {
2617 tcx.sess
2618 .source_map()
2619 .span_to_snippet(span)
2620 .map(|snippet| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", snippet))
})format!("`{snippet}`"))
2621 .unwrap_or_else(|_| "const tuple".to_string())
2622 };
2623
2624 let tys = match ty.kind() {
2625 ty::Tuple(tys) => tys,
2626 ty::Error(e) => return Const::new_error(tcx, *e),
2627 _ => {
2628 let e =
2629 tcx.dcx().span_err(span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected `{0}`, found {1}", ty,
found_tuple()))
})format!("expected `{}`, found {}", ty, found_tuple()));
2630 return Const::new_error(tcx, e);
2631 }
2632 };
2633
2634 if exprs.len() != tys.len() {
2635 let e = tcx.dcx().span_err(span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected `{0}`, found {1}", ty,
found_tuple()))
})format!("expected `{}`, found {}", ty, found_tuple()));
2636 return Const::new_error(tcx, e);
2637 }
2638
2639 let exprs = exprs
2640 .iter()
2641 .zip(tys.iter())
2642 .map(|(expr, ty)| self.lower_const_arg(expr, ty))
2643 .collect::<Vec<_>>();
2644
2645 let valtree = ty::ValTree::from_branches(tcx, exprs);
2646 ty::Const::new_value(tcx, valtree, ty)
2647 }
2648
2649 fn lower_const_arg_struct(
2650 &self,
2651 hir_id: HirId,
2652 qpath: hir::QPath<'tcx>,
2653 inits: &'tcx [&'tcx hir::ConstArgExprField<'tcx>],
2654 span: Span,
2655 ) -> Const<'tcx> {
2656 let tcx = self.tcx();
2659
2660 let non_adt_or_variant_res = || {
2661 let e = tcx.dcx().span_err(span, "struct expression with invalid base path");
2662 ty::Const::new_error(tcx, e)
2663 };
2664
2665 let ResolvedStructPath { res: opt_res, ty } =
2666 self.lower_path_for_struct_expr(qpath, span, hir_id);
2667
2668 let variant_did = match qpath {
2669 hir::QPath::Resolved(maybe_qself, path) => {
2670 {
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:2670",
"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(2670u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("maybe_qself")
}> =
::tracing::__macro_support::FieldName::new("maybe_qself");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("path")
}> =
::tracing::__macro_support::FieldName::new("path");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&maybe_qself)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&path)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?maybe_qself, ?path);
2671 let variant_did = match path.res {
2672 Res::Def(DefKind::Variant | DefKind::Struct, did) => did,
2673 _ => return non_adt_or_variant_res(),
2674 };
2675
2676 variant_did
2677 }
2678 hir::QPath::TypeRelative(hir_self_ty, segment) => {
2679 {
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:2679",
"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(2679u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("hir_self_ty")
}> =
::tracing::__macro_support::FieldName::new("hir_self_ty");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("segment")
}> =
::tracing::__macro_support::FieldName::new("segment");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&hir_self_ty)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&segment)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?hir_self_ty, ?segment);
2680
2681 let res_def_id = match opt_res {
2682 Ok(r)
2683 if #[allow(non_exhaustive_omitted_patterns)] match tcx.def_kind(r.def_id()) {
DefKind::Variant | DefKind::Struct => true,
_ => false,
}matches!(
2684 tcx.def_kind(r.def_id()),
2685 DefKind::Variant | DefKind::Struct
2686 ) =>
2687 {
2688 r.def_id()
2689 }
2690 Ok(_) => return non_adt_or_variant_res(),
2691 Err(e) => return ty::Const::new_error(tcx, e),
2692 };
2693
2694 res_def_id
2695 }
2696 };
2697
2698 let ty::Adt(adt_def, adt_args) = ty.kind() else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
2699
2700 let variant_def = adt_def.variant_with_id(variant_did);
2701 let variant_idx = adt_def.variant_index_with_id(variant_did).as_u32();
2702
2703 for init in inits {
2704 if !variant_def.fields.iter().any(|field_def| field_def.name == init.field.name) {
2705 let mut err = if adt_def.is_enum() {
2706 {
tcx.dcx().struct_span_err(init.field.span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("variant `{0}::{1}` has no field named `{2}`",
ty, variant_def.name, init.field))
})).with_code(E0559)
}struct_span_code_err!(
2707 tcx.dcx(),
2708 init.field.span,
2709 E0559,
2710 "variant `{}::{}` has no field named `{}`",
2711 ty,
2712 variant_def.name,
2713 init.field
2714 )
2715 } else {
2716 {
tcx.dcx().struct_span_err(init.field.span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("struct `{0}` has no field named `{1}`",
variant_def.name, init.field))
})).with_code(E0560)
}struct_span_code_err!(
2717 tcx.dcx(),
2718 init.field.span,
2719 E0560,
2720 "struct `{}` has no field named `{}`",
2721 variant_def.name,
2722 init.field
2723 )
2724 };
2725 if adt_def.is_enum() {
2726 err.span_label(
2727 init.field.span,
2728 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}::{1}` does not have this field",
ty, variant_def.name))
})format!("`{}::{}` does not have this field", ty, variant_def.name),
2729 );
2730 } else {
2731 err.span_label(
2732 init.field.span,
2733 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` does not have this field",
variant_def.name))
})format!("`{}` does not have this field", variant_def.name),
2734 );
2735 }
2736 return ty::Const::new_error(tcx, err.emit());
2737 }
2738 }
2739
2740 let fields = variant_def
2741 .fields
2742 .iter()
2743 .map(|field_def| {
2744 let mut init_expr =
2747 inits.iter().filter(|init_expr| init_expr.field.name == field_def.name);
2748
2749 match init_expr.next() {
2750 Some(expr) => {
2751 if let Some(expr) = init_expr.next() {
2752 let e = tcx.dcx().span_err(
2753 expr.span,
2754 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("struct expression with multiple initialisers for `{0}`",
field_def.name))
})format!(
2755 "struct expression with multiple initialisers for `{}`",
2756 field_def.name,
2757 ),
2758 );
2759 return ty::Const::new_error(tcx, e);
2760 }
2761
2762 self.lower_const_arg(
2763 expr.expr,
2764 tcx.type_of(field_def.did).instantiate(tcx, adt_args).skip_norm_wip(),
2765 )
2766 }
2767 None => {
2768 let e = tcx.dcx().span_err(
2769 span,
2770 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("struct expression with missing field initialiser for `{0}`",
field_def.name))
})format!(
2771 "struct expression with missing field initialiser for `{}`",
2772 field_def.name
2773 ),
2774 );
2775 ty::Const::new_error(tcx, e)
2776 }
2777 }
2778 })
2779 .collect::<Vec<_>>();
2780
2781 let opt_discr_const = if adt_def.is_enum() {
2782 let valtree = ty::ValTree::from_scalar_int(tcx, variant_idx.into());
2783 Some(ty::Const::new_value(tcx, valtree, tcx.types.u32))
2784 } else {
2785 None
2786 };
2787
2788 let valtree = ty::ValTree::from_branches(tcx, opt_discr_const.into_iter().chain(fields));
2789 ty::Const::new_value(tcx, valtree, ty)
2790 }
2791
2792 pub fn lower_path_for_struct_expr(
2793 &self,
2794 qpath: hir::QPath<'tcx>,
2795 path_span: Span,
2796 hir_id: HirId,
2797 ) -> ResolvedStructPath<'tcx> {
2798 match qpath {
2799 hir::QPath::Resolved(ref maybe_qself, path) => {
2800 let self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
2801 let ty = self.lower_resolved_ty_path(self_ty, path, hir_id, PermitVariants::Yes);
2802 ResolvedStructPath { res: Ok(path.res), ty }
2803 }
2804 hir::QPath::TypeRelative(hir_self_ty, segment) => {
2805 let self_ty = self.lower_ty(hir_self_ty);
2806
2807 let result = self.lower_type_relative_ty_path(
2808 self_ty,
2809 hir_self_ty,
2810 segment,
2811 hir_id,
2812 path_span,
2813 PermitVariants::Yes,
2814 );
2815 let ty = result
2816 .map(|(ty, _, _)| ty)
2817 .unwrap_or_else(|guar| Ty::new_error(self.tcx(), guar));
2818
2819 ResolvedStructPath {
2820 res: result.map(|(_, kind, def_id)| Res::Def(kind, def_id)),
2821 ty,
2822 }
2823 }
2824 }
2825 }
2826
2827 fn lower_resolved_const_path(
2829 &self,
2830 opt_self_ty: Option<Ty<'tcx>>,
2831 path: &hir::Path<'tcx>,
2832 hir_id: HirId,
2833 ) -> Const<'tcx> {
2834 let tcx = self.tcx();
2835 let span = path.span;
2836 let ct = match path.res {
2837 Res::Def(DefKind::ConstParam, def_id) => {
2838 {
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);
2839 let _ = self.prohibit_generic_args(
2840 path.segments.iter(),
2841 GenericsArgsErrExtend::Param(def_id),
2842 );
2843 self.lower_const_param(def_id, hir_id)
2844 }
2845 Res::Def(DefKind::Const { .. }, did) => {
2846 if let Err(guar) = self.require_type_const_attribute(did, span) {
2847 return Const::new_error(self.tcx(), guar);
2848 }
2849
2850 {
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);
2851 let [leading_segments @ .., segment] = path.segments else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
2852 let _ = self
2853 .prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
2854 let args = self.lower_generic_args_of_path_segment(span, did, segment);
2855 ty::Const::new_alias(
2856 tcx,
2857 ty::IsRigid::No,
2858 ty::AliasConst::new(tcx, ty::AliasConstKind::new_from_def_id(tcx, did), args),
2859 )
2860 }
2861 Res::Def(kind @ DefKind::Ctor(ctor_of, CtorKind::Const), did) => {
2862 {
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);
2863 let generic_segments =
2864 self.probe_generic_path_segments(path.segments, opt_self_ty, kind, did, span);
2865 let indices: FxHashSet<_> =
2866 generic_segments.iter().map(|GenericPathSegment(_, index)| index).collect();
2867 let _ = self.prohibit_generic_args(
2868 path.segments.iter().enumerate().filter_map(|(index, seg)| {
2869 if !indices.contains(&index) { Some(seg) } else { None }
2870 }),
2871 GenericsArgsErrExtend::DefVariant(&path.segments),
2872 );
2873
2874 let parent_did = tcx.parent(did);
2875 let generics_did = match ctor_of {
2876 CtorOf::Variant => tcx.parent(parent_did),
2877 CtorOf::Struct => parent_did,
2878 };
2879 let args = self.lower_generic_args_of_path_segment(
2880 span,
2881 generics_did,
2882 &path.segments[generic_segments[0].1],
2883 );
2884 self.construct_const_ctor_value(did, ctor_of, args)
2885 }
2886 Res::Def(DefKind::Ctor(ctor_of, CtorKind::Fn), did) => {
2887 {
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);
2888 let generic_segments = self.probe_generic_path_segments(
2889 path.segments,
2890 opt_self_ty,
2891 DefKind::Ctor(ctor_of, CtorKind::Const),
2892 did,
2893 span,
2894 );
2895 let indices: FxHashSet<_> =
2896 generic_segments.iter().map(|GenericPathSegment(_, index)| index).collect();
2897 let _ = self.prohibit_generic_args(
2898 path.segments.iter().enumerate().filter_map(|(index, seg)| {
2899 if !indices.contains(&index) { Some(seg) } else { None }
2900 }),
2901 GenericsArgsErrExtend::DefVariant(&path.segments),
2902 );
2903
2904 let parent_did = tcx.parent(did);
2905 let generics_did = if let DefKind::Ctor(CtorOf::Variant, _) = tcx.def_kind(did) {
2906 tcx.parent(parent_did)
2907 } else {
2908 parent_did
2909 };
2910 let args = self.lower_generic_args_of_path_segment(
2911 span,
2912 generics_did,
2913 &path.segments[generic_segments[0].1],
2914 );
2915
2916 ty::Const::zero_sized(tcx, Ty::new_fn_def(tcx, did, ty::Binder::dummy(args)))
2918 }
2919 Res::Def(DefKind::AssocConst { .. }, did) => {
2920 let trait_segment = if let [modules @ .., trait_, _item] = path.segments {
2921 let _ = self.prohibit_generic_args(modules.iter(), GenericsArgsErrExtend::None);
2922 Some(trait_)
2923 } else {
2924 None
2925 };
2926 self.lower_resolved_assoc_const_path(
2927 span,
2928 opt_self_ty,
2929 did,
2930 trait_segment,
2931 path.segments.last().unwrap(),
2932 )
2933 .unwrap_or_else(|guar| Const::new_error(tcx, guar))
2934 }
2935 Res::Def(DefKind::Static { .. }, _) => {
2936 ::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")
2937 }
2938 Res::Def(DefKind::Fn | DefKind::AssocFn, did) => {
2940 self.dcx().span_delayed_bug(span, "function items cannot be used as const args");
2941 let args = self.lower_generic_args_of_path_segment(
2942 span,
2943 did,
2944 path.segments.last().unwrap(),
2945 );
2946
2947 if self.tcx().generics_of(did).own_synthetic_params_count() == 0 {
2948 ty::Const::zero_sized(tcx, Ty::new_fn_def(tcx, did, ty::Binder::dummy(args)))
2950 } else {
2951 let tcx = self.tcx();
2952 let generics = tcx.generics_of(did);
2953
2954 let args = args.iter().enumerate().map(|(index, arg)| {
2958 let param = generics.param_at(index, tcx);
2959 if param.kind.is_synthetic() {
2960 self.ty_infer(Some(param), span).into()
2961 } else {
2962 arg
2963 }
2964 });
2965
2966 ty::Const::zero_sized(
2968 tcx,
2969 Ty::new_fn_def(tcx, did, ty::Binder::dummy(args.collect::<Box<_>>())),
2970 )
2971 }
2972 }
2973
2974 res @ (Res::Def(
2977 DefKind::Mod
2978 | DefKind::Enum
2979 | DefKind::Variant
2980 | DefKind::Struct
2981 | DefKind::OpaqueTy
2982 | DefKind::TyAlias
2983 | DefKind::TraitAlias
2984 | DefKind::AssocTy
2985 | DefKind::Union
2986 | DefKind::Trait
2987 | DefKind::ForeignTy
2988 | DefKind::TyParam
2989 | DefKind::Macro(_)
2990 | DefKind::LifetimeParam
2991 | DefKind::Use
2992 | DefKind::ForeignMod
2993 | DefKind::AnonConst
2994 | DefKind::Field
2995 | DefKind::Impl { .. }
2996 | DefKind::Closure
2997 | DefKind::ExternCrate
2998 | DefKind::GlobalAsm
2999 | DefKind::SyntheticCoroutineBody,
3000 _,
3001 )
3002 | Res::PrimTy(_)
3003 | Res::SelfTyParam { .. }
3004 | Res::SelfTyAlias { .. }
3005 | Res::SelfCtor(_)
3006 | Res::Local(_)
3007 | Res::ToolMod
3008 | Res::OpenMod(..)
3009 | Res::NonMacroAttr(_)
3010 | Res::Err) => Const::new_error_with_message(
3011 tcx,
3012 span,
3013 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("invalid Res {0:?} for const path",
res))
})format!("invalid Res {res:?} for const path"),
3014 ),
3015 };
3016 self.check_param_uses_if_mcg(ct, span, false)
3017 }
3018
3019 #[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(3020u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("anon")
}> =
::tracing::__macro_support::FieldName::new("anon");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&anon)
as &dyn ::tracing::field::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:3025",
"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(3025u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("expr")
}> =
::tracing::__macro_support::FieldName::new("expr");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expr)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
let ty =
tcx.type_of(anon.def_id).instantiate_identity().skip_norm_wip();
match self.try_lower_anon_const_lit(ty, expr) {
Some(v) => v,
None =>
ty::Const::new_alias(tcx, ty::IsRigid::No,
ty::AliasConst::new(tcx,
ty::AliasConstKind::Anon {
def_id: anon.def_id.to_def_id(),
},
ty::GenericArgs::identity_for_item(tcx,
anon.def_id.to_def_id()))),
}
}
}
}#[instrument(skip(self), level = "debug")]
3021 fn lower_const_arg_anon(&self, anon: &AnonConst) -> Const<'tcx> {
3022 let tcx = self.tcx();
3023
3024 let expr = &tcx.hir_body(anon.body).value;
3025 debug!(?expr);
3026
3027 let ty = tcx.type_of(anon.def_id).instantiate_identity().skip_norm_wip();
3031
3032 match self.try_lower_anon_const_lit(ty, expr) {
3033 Some(v) => v,
3034 None => ty::Const::new_alias(
3035 tcx,
3036 ty::IsRigid::No,
3037 ty::AliasConst::new(
3038 tcx,
3039 ty::AliasConstKind::Anon { def_id: anon.def_id.to_def_id() },
3040 ty::GenericArgs::identity_for_item(tcx, anon.def_id.to_def_id()),
3041 ),
3042 ),
3043 }
3044 }
3045
3046 #[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(3046u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("kind")
}> =
::tracing::__macro_support::FieldName::new("kind");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("neg")
}> =
::tracing::__macro_support::FieldName::new("neg");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("ty")
}> =
::tracing::__macro_support::FieldName::new("ty");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("span")
}> =
::tracing::__macro_support::FieldName::new("span");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&kind)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&neg as
&dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
as &dyn ::tracing::field::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 ty = if !ty.has_infer() { Some(ty) } else { None };
if let LitKind::Err(guar) = *kind {
return ty::Const::new_error(tcx, guar);
}
let input = LitToConstInput { lit: *kind, ty, neg };
match tcx.at(span).lit_to_const(input) {
Some(value) =>
ty::Const::new_value(tcx, value.valtree, value.ty),
None => {
let e =
tcx.dcx().span_err(span,
"type annotations needed for the literal");
ty::Const::new_error(tcx, e)
}
}
}
}
}#[instrument(skip(self), level = "debug")]
3047 fn lower_const_arg_literal(
3048 &self,
3049 kind: &LitKind,
3050 neg: bool,
3051 ty: Ty<'tcx>,
3052 span: Span,
3053 ) -> Const<'tcx> {
3054 let tcx = self.tcx();
3055
3056 let ty = if !ty.has_infer() { Some(ty) } else { None };
3057
3058 if let LitKind::Err(guar) = *kind {
3059 return ty::Const::new_error(tcx, guar);
3060 }
3061 let input = LitToConstInput { lit: *kind, ty, neg };
3062 match tcx.at(span).lit_to_const(input) {
3063 Some(value) => ty::Const::new_value(tcx, value.valtree, value.ty),
3064 None => {
3065 let e = tcx.dcx().span_err(span, "type annotations needed for the literal");
3066 ty::Const::new_error(tcx, e)
3067 }
3068 }
3069 }
3070
3071 #[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(3071u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("ty")
}> =
::tracing::__macro_support::FieldName::new("ty");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("expr")
}> =
::tracing::__macro_support::FieldName::new("expr");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expr)
as &dyn ::tracing::field::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: Some(ty),
neg: false,
})
}
hir::ExprKind::Unary(hir::UnOp::Neg, expr) =>
match expr.kind {
hir::ExprKind::Lit(lit) => {
Some(LitToConstInput {
lit: lit.node,
ty: Some(ty),
neg: true,
})
}
_ => None,
},
_ => None,
};
lit_input.and_then(|l|
{
if const_lit_matches_ty(tcx, &l.lit, ty, l.neg) {
tcx.at(expr.span).lit_to_const(l).map(|value|
ty::Const::new_value(tcx, value.valtree, value.ty))
} else { None }
})
}
}
}#[instrument(skip(self), level = "debug")]
3072 fn try_lower_anon_const_lit(
3073 &self,
3074 ty: Ty<'tcx>,
3075 expr: &'tcx hir::Expr<'tcx>,
3076 ) -> Option<Const<'tcx>> {
3077 let tcx = self.tcx();
3078
3079 let expr = match &expr.kind {
3082 hir::ExprKind::Block(block, _) if block.stmts.is_empty() && block.expr.is_some() => {
3083 block.expr.as_ref().unwrap()
3084 }
3085 _ => expr,
3086 };
3087
3088 let lit_input = match expr.kind {
3089 hir::ExprKind::Lit(lit) => {
3090 Some(LitToConstInput { lit: lit.node, ty: Some(ty), neg: false })
3091 }
3092 hir::ExprKind::Unary(hir::UnOp::Neg, expr) => match expr.kind {
3093 hir::ExprKind::Lit(lit) => {
3094 Some(LitToConstInput { lit: lit.node, ty: Some(ty), neg: true })
3095 }
3096 _ => None,
3097 },
3098 _ => None,
3099 };
3100
3101 lit_input.and_then(|l| {
3102 if const_lit_matches_ty(tcx, &l.lit, ty, l.neg) {
3103 tcx.at(expr.span)
3104 .lit_to_const(l)
3105 .map(|value| ty::Const::new_value(tcx, value.valtree, value.ty))
3106 } else {
3107 None
3108 }
3109 })
3110 }
3111
3112 fn require_type_const_attribute(
3113 &self,
3114 def_id: DefId,
3115 span: Span,
3116 ) -> Result<(), ErrorGuaranteed> {
3117 let tcx = self.tcx();
3118 let is_inherent_assoc_const = tcx.def_kind(def_id)
3121 == DefKind::AssocConst { is_type_const: false }
3122 && tcx.def_kind(tcx.parent(def_id)) == DefKind::Impl { of_trait: false };
3123 if tcx.is_type_const(def_id)
3124 || tcx.features().generic_const_args() && !is_inherent_assoc_const
3125 {
3126 Ok(())
3127 } else {
3128 let mut err = self.dcx().struct_span_err(
3129 span,
3130 "use of `const` in the type system not defined as `type const`",
3131 );
3132 if let Some(local_def_id) = def_id.as_local() {
3133 let name = tcx.def_path_str(def_id);
3134 let (insertion_span, sugg) = match tcx.hir_node_by_def_id(local_def_id) {
3135 hir::Node::Item(item) if !item.vis_span.is_empty() => {
3136 (item.vis_span.shrink_to_hi(), " type")
3137 }
3138 hir::Node::ImplItem(impl_item)
3139 if let Some(vis_span) =
3140 impl_item.vis_span().filter(|span| !span.is_empty()) =>
3141 {
3142 (vis_span.shrink_to_hi(), " type")
3143 }
3144 _ => (tcx.def_span(def_id).shrink_to_lo(), "type "),
3145 };
3146
3147 err.span_suggestion_verbose(
3148 insertion_span,
3149 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("add `type` before `const` for `{0}`",
name))
})format!("add `type` before `const` for `{name}`"),
3150 sugg,
3151 Applicability::MaybeIncorrect,
3152 );
3153 } else {
3154 err.note("only consts marked defined as `type const` may be used in types");
3155 }
3156 Err(err.emit())
3157 }
3158 }
3159
3160 fn lower_delegation_ty(&self, infer: hir::InferDelegation<'tcx>) -> Ty<'tcx> {
3161 match infer {
3162 hir::InferDelegation::DefId(def_id) => {
3163 self.tcx().type_of(def_id).instantiate_identity().skip_norm_wip()
3164 }
3165 rustc_hir::InferDelegation::Sig(_, idx) => {
3166 let delegation_sig = self.tcx().inherit_sig_for_delegation_item(self.item_def_id());
3167
3168 match idx {
3169 hir::InferDelegationSig::Input(idx) => delegation_sig[idx],
3170 hir::InferDelegationSig::Output { .. } => *delegation_sig.last().unwrap(),
3171 }
3172 }
3173 }
3174 }
3175
3176 x;#[instrument(level = "debug", skip(self), ret)]
3178 pub fn lower_ty(&self, hir_ty: &hir::Ty<'tcx>) -> Ty<'tcx> {
3179 let tcx = self.tcx();
3180
3181 let result_ty = match &hir_ty.kind {
3182 hir::TyKind::InferDelegation(infer) => self.lower_delegation_ty(*infer),
3183 hir::TyKind::Slice(ty) => Ty::new_slice(tcx, self.lower_ty(ty)),
3184 hir::TyKind::Ptr(mt) => Ty::new_ptr(tcx, self.lower_ty(mt.ty), mt.mutbl),
3185 hir::TyKind::Ref(region, mt) => {
3186 let r = self.lower_lifetime(region, RegionInferReason::Reference);
3187 debug!(?r);
3188 let t = self.lower_ty(mt.ty);
3189 Ty::new_ref(tcx, r, t, mt.mutbl)
3190 }
3191 hir::TyKind::Never => tcx.types.never,
3192 hir::TyKind::Tup(fields) => {
3193 Ty::new_tup_from_iter(tcx, fields.iter().map(|t| self.lower_ty(t)))
3194 }
3195 hir::TyKind::FnPtr(bf) => {
3196 check_c_variadic_abi(tcx, bf.decl, bf.abi, hir_ty.span);
3197
3198 Ty::new_fn_ptr(
3199 tcx,
3200 self.lower_fn_ty(hir_ty.hir_id, bf.safety, bf.abi, bf.decl, None, Some(hir_ty)),
3201 )
3202 }
3203 hir::TyKind::UnsafeBinder(binder) => Ty::new_unsafe_binder(
3204 tcx,
3205 ty::Binder::bind_with_vars(
3206 self.lower_ty(binder.inner_ty),
3207 tcx.late_bound_vars(hir_ty.hir_id),
3208 ),
3209 ),
3210 hir::TyKind::TraitObject(bounds, tagged_ptr) => {
3211 let lifetime = tagged_ptr.pointer();
3212 let syntax = tagged_ptr.tag();
3213 self.lower_trait_object_ty(hir_ty.span, hir_ty.hir_id, bounds, lifetime, syntax)
3214 }
3215 hir::TyKind::Path(hir::QPath::Resolved(_, path))
3219 if path.segments.last().and_then(|segment| segment.args).is_some_and(|args| {
3220 matches!(args.parenthesized, hir::GenericArgsParentheses::ReturnTypeNotation)
3221 }) =>
3222 {
3223 let guar = self
3224 .dcx()
3225 .emit_err(BadReturnTypeNotation { span: hir_ty.span, suggestion: None });
3226 Ty::new_error(tcx, guar)
3227 }
3228 hir::TyKind::Path(hir::QPath::Resolved(maybe_qself, path)) => {
3229 debug!(?maybe_qself, ?path);
3230 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
3231 self.lower_resolved_ty_path(opt_self_ty, path, hir_ty.hir_id, PermitVariants::No)
3232 }
3233 &hir::TyKind::OpaqueDef(opaque_ty) => {
3234 let in_trait = match opaque_ty.origin {
3238 hir::OpaqueTyOrigin::FnReturn {
3239 parent,
3240 in_trait_or_impl: Some(hir::RpitContext::Trait),
3241 ..
3242 }
3243 | hir::OpaqueTyOrigin::AsyncFn {
3244 parent,
3245 in_trait_or_impl: Some(hir::RpitContext::Trait),
3246 ..
3247 } => Some(parent),
3248 hir::OpaqueTyOrigin::FnReturn {
3249 in_trait_or_impl: None | Some(hir::RpitContext::TraitImpl),
3250 ..
3251 }
3252 | hir::OpaqueTyOrigin::AsyncFn {
3253 in_trait_or_impl: None | Some(hir::RpitContext::TraitImpl),
3254 ..
3255 }
3256 | hir::OpaqueTyOrigin::TyAlias { .. } => None,
3257 };
3258
3259 self.lower_opaque_ty(opaque_ty.def_id, in_trait)
3260 }
3261 hir::TyKind::TraitAscription(hir_bounds) => {
3262 let self_ty = self.ty_infer(None, hir_ty.span);
3265 let mut bounds = Vec::new();
3266 self.lower_bounds(
3267 self_ty,
3268 hir_bounds.iter(),
3269 &mut bounds,
3270 ty::List::empty(),
3271 PredicateFilter::All,
3272 OverlappingAsssocItemConstraints::Allowed,
3273 );
3274 self.add_implicit_sizedness_bounds(
3275 &mut bounds,
3276 self_ty,
3277 hir_bounds,
3278 ImpliedBoundsContext::AssociatedTypeOrImplTrait,
3279 hir_ty.span,
3280 );
3281 self.register_trait_ascription_bounds(bounds, hir_ty.hir_id, hir_ty.span);
3282 self_ty
3283 }
3284 hir::TyKind::Path(hir::QPath::TypeRelative(hir_self_ty, segment))
3288 if segment.args.is_some_and(|args| {
3289 matches!(args.parenthesized, hir::GenericArgsParentheses::ReturnTypeNotation)
3290 }) =>
3291 {
3292 let guar = if let hir::Node::LetStmt(stmt) = tcx.parent_hir_node(hir_ty.hir_id)
3293 && let None = stmt.init
3294 && let hir::TyKind::Path(hir::QPath::Resolved(_, self_ty_path)) =
3295 hir_self_ty.kind
3296 && let Res::Def(DefKind::Enum | DefKind::Struct | DefKind::Union, def_id) =
3297 self_ty_path.res
3298 && let Some(_) = tcx
3299 .inherent_impls(def_id)
3300 .iter()
3301 .flat_map(|imp| {
3302 tcx.associated_items(*imp).filter_by_name_unhygienic(segment.ident.name)
3303 })
3304 .filter(|assoc| {
3305 matches!(assoc.kind, ty::AssocKind::Fn { has_self: false, .. })
3306 })
3307 .next()
3308 {
3309 let err = tcx
3311 .dcx()
3312 .struct_span_err(
3313 hir_ty.span,
3314 "expected type, found associated function call",
3315 )
3316 .with_span_suggestion_verbose(
3317 stmt.pat.span.between(hir_ty.span),
3318 "use `=` if you meant to assign",
3319 " = ".to_string(),
3320 Applicability::MaybeIncorrect,
3321 );
3322 self.dcx().try_steal_replace_and_emit_err(
3323 hir_ty.span,
3324 StashKey::ReturnTypeNotation,
3325 err,
3326 )
3327 } else if let hir::Node::LetStmt(stmt) = tcx.parent_hir_node(hir_ty.hir_id)
3328 && let None = stmt.init
3329 && let hir::TyKind::Path(hir::QPath::Resolved(_, self_ty_path)) =
3330 hir_self_ty.kind
3331 && let Res::PrimTy(_) = self_ty_path.res
3332 && self.dcx().has_stashed_diagnostic(hir_ty.span, StashKey::ReturnTypeNotation)
3333 {
3334 let err = tcx
3337 .dcx()
3338 .struct_span_err(
3339 hir_ty.span,
3340 "expected type, found associated function call",
3341 )
3342 .with_span_suggestion_verbose(
3343 stmt.pat.span.between(hir_ty.span),
3344 "use `=` if you meant to assign",
3345 " = ".to_string(),
3346 Applicability::MaybeIncorrect,
3347 );
3348 self.dcx().try_steal_replace_and_emit_err(
3349 hir_ty.span,
3350 StashKey::ReturnTypeNotation,
3351 err,
3352 )
3353 } else {
3354 let suggestion = if self
3355 .dcx()
3356 .has_stashed_diagnostic(hir_ty.span, StashKey::ReturnTypeNotation)
3357 {
3358 Some(segment.ident.span.shrink_to_hi().with_hi(hir_ty.span.hi()))
3364 } else {
3365 None
3366 };
3367 let err = self
3368 .dcx()
3369 .create_err(BadReturnTypeNotation { span: hir_ty.span, suggestion });
3370 self.dcx().try_steal_replace_and_emit_err(
3371 hir_ty.span,
3372 StashKey::ReturnTypeNotation,
3373 err,
3374 )
3375 };
3376 Ty::new_error(tcx, guar)
3377 }
3378 hir::TyKind::Path(hir::QPath::TypeRelative(hir_self_ty, segment)) => {
3379 debug!(?hir_self_ty, ?segment);
3380 let self_ty = self.lower_ty(hir_self_ty);
3381 self.lower_type_relative_ty_path(
3382 self_ty,
3383 hir_self_ty,
3384 segment,
3385 hir_ty.hir_id,
3386 hir_ty.span,
3387 PermitVariants::No,
3388 )
3389 .map(|(ty, _, _)| ty)
3390 .unwrap_or_else(|guar| Ty::new_error(tcx, guar))
3391 }
3392 hir::TyKind::Array(ty, length) => {
3393 let length = self.lower_const_arg(length, tcx.types.usize);
3394 Ty::new_array_with_const_len(tcx, self.lower_ty(ty), length)
3395 }
3396 hir::TyKind::Infer(()) => {
3397 self.ty_infer(None, hir_ty.span)
3402 }
3403 hir::TyKind::Pat(ty, pat) => {
3404 let ty_span = ty.span;
3405 let ty = self.lower_ty(ty);
3406 let pat_ty = match self.lower_pat_ty_pat(ty, ty_span, pat) {
3407 Ok(kind) => Ty::new_pat(tcx, ty, tcx.mk_pat(kind)),
3408 Err(guar) => Ty::new_error(tcx, guar),
3409 };
3410 self.record_ty(pat.hir_id, ty, pat.span);
3411 pat_ty
3412 }
3413 hir::TyKind::FieldOf(ty, hir::TyFieldPath { variant, field }) => self.lower_field_of(
3414 self.lower_ty(ty),
3415 self.item_def_id(),
3416 ty.span,
3417 hir_ty.hir_id,
3418 *variant,
3419 *field,
3420 ),
3421 hir::TyKind::View(ty, fields) => {
3422 self.lower_view(self.lower_ty(ty), fields, hir_ty.span)
3423 }
3424
3425 hir::TyKind::Err(guar) => Ty::new_error(tcx, *guar),
3426 };
3427
3428 self.record_ty(hir_ty.hir_id, result_ty, hir_ty.span);
3429 result_ty
3430 }
3431
3432 fn lower_pat_ty_pat(
3433 &self,
3434 ty: Ty<'tcx>,
3435 ty_span: Span,
3436 pat: &hir::TyPat<'tcx>,
3437 ) -> Result<ty::PatternKind<'tcx>, ErrorGuaranteed> {
3438 let tcx = self.tcx();
3439 match pat.kind {
3440 hir::TyPatKind::Range(start, end) => {
3441 match ty.kind() {
3442 ty::Int(_) | ty::Uint(_) | ty::Char => {
3445 let start = self.lower_const_arg(start, ty);
3446 let end = self.lower_const_arg(end, ty);
3447 Ok(ty::PatternKind::Range { start, end })
3448 }
3449 _ => Err(self
3450 .dcx()
3451 .span_delayed_bug(ty_span, "invalid base type for range pattern")),
3452 }
3453 }
3454 hir::TyPatKind::NotNull => Ok(ty::PatternKind::NotNull),
3455 hir::TyPatKind::Or(patterns) => {
3456 self.tcx()
3457 .mk_patterns_from_iter(patterns.iter().map(|pat| {
3458 self.lower_pat_ty_pat(ty, ty_span, pat).map(|pat| tcx.mk_pat(pat))
3459 }))
3460 .map(ty::PatternKind::Or)
3461 }
3462 hir::TyPatKind::Err(e) => Err(e),
3463 }
3464 }
3465
3466 fn lower_field_of(
3467 &self,
3468 ty: Ty<'tcx>,
3469 item_def_id: LocalDefId,
3470 ty_span: Span,
3471 hir_id: HirId,
3472 variant: Option<Ident>,
3473 field: Ident,
3474 ) -> Ty<'tcx> {
3475 let dcx = self.dcx();
3476 let tcx = self.tcx();
3477 match ty.kind() {
3478 ty::Adt(def, _) => {
3479 let base_did = def.did();
3480 let kind_name = tcx.def_descr(base_did);
3481 let (variant_idx, variant) = if def.is_enum() {
3482 let Some(variant) = variant else {
3483 let err = dcx
3484 .create_err(NoVariantNamed { span: field.span, ident: field, ty })
3485 .with_span_help(
3486 field.span.shrink_to_lo(),
3487 "you might be missing a variant here: `Variant.`",
3488 )
3489 .emit();
3490 return Ty::new_error(tcx, err);
3491 };
3492
3493 if let Some(res) = def
3494 .variants()
3495 .iter_enumerated()
3496 .find(|(_, f)| f.ident(tcx).normalize_to_macros_2_0() == variant)
3497 {
3498 res
3499 } else {
3500 let err = dcx
3501 .create_err(NoVariantNamed { span: variant.span, ident: variant, ty })
3502 .emit();
3503 return Ty::new_error(tcx, err);
3504 }
3505 } else {
3506 if let Some(variant) = variant {
3507 let adt_path = tcx.def_path_str(base_did);
3508 {
dcx.struct_span_err(variant.span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} `{1}` does not have any variants",
kind_name, adt_path))
})).with_code(E0609)
}struct_span_code_err!(
3509 dcx,
3510 variant.span,
3511 E0609,
3512 "{kind_name} `{adt_path}` does not have any variants",
3513 )
3514 .with_span_label(variant.span, "variant unknown")
3515 .emit();
3516 }
3517 (FIRST_VARIANT, def.non_enum_variant())
3518 };
3519 let (ident, def_scope) =
3520 tcx.adjust_ident_and_get_scope(field, def.did(), item_def_id);
3521 if let Some((field_idx, field)) = variant
3522 .fields
3523 .iter_enumerated()
3524 .find(|(_, f)| f.ident(tcx).normalize_to_macros_2_0() == ident)
3525 {
3526 if field.vis.is_accessible_from(def_scope, tcx) {
3527 tcx.check_stability(field.did, Some(hir_id), ident.span, None);
3528 } else {
3529 let adt_path = tcx.def_path_str(base_did);
3530 {
dcx.struct_span_err(ident.span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("field `{0}` of {1} `{2}` is private",
ident, kind_name, adt_path))
})).with_code(E0616)
}struct_span_code_err!(
3531 dcx,
3532 ident.span,
3533 E0616,
3534 "field `{ident}` of {kind_name} `{adt_path}` is private",
3535 )
3536 .with_span_label(ident.span, "private field")
3537 .emit();
3538 }
3539 Ty::new_field_representing_type(tcx, ty, variant_idx, field_idx)
3540 } else {
3541 let err =
3542 dcx.create_err(NoFieldOnType { span: ident.span, field: ident, ty }).emit();
3543 Ty::new_error(tcx, err)
3544 }
3545 }
3546 ty::Tuple(tys) => {
3547 let index = match field.as_str().parse::<usize>() {
3548 Ok(idx) => idx,
3549 Err(_) => {
3550 let err =
3551 dcx.create_err(NoFieldOnType { span: field.span, field, ty }).emit();
3552 return Ty::new_error(tcx, err);
3553 }
3554 };
3555 if field.name != sym::integer(index) {
3556 ::rustc_middle::util::bug::bug_fmt(format_args!("we parsed above, but now not equal?"));bug!("we parsed above, but now not equal?");
3557 }
3558 if tys.get(index).is_some() {
3559 Ty::new_field_representing_type(tcx, ty, FIRST_VARIANT, index.into())
3560 } else {
3561 let err = dcx.create_err(NoFieldOnType { span: field.span, field, ty }).emit();
3562 Ty::new_error(tcx, err)
3563 }
3564 }
3565 ty::Alias(..) => Ty::new_error(
3578 tcx,
3579 dcx.span_err(ty_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("could not resolve fields of `{0}`",
ty))
})format!("could not resolve fields of `{ty}`")),
3580 ),
3581 ty::Error(err) => Ty::new_error(tcx, *err),
3582 ty::Bool
3583 | ty::Char
3584 | ty::Int(_)
3585 | ty::Uint(_)
3586 | ty::Float(_)
3587 | ty::Foreign(_)
3588 | ty::Str
3589 | ty::RawPtr(_, _)
3590 | ty::Ref(_, _, _)
3591 | ty::FnDef(_, _)
3592 | ty::FnPtr(_, _)
3593 | ty::UnsafeBinder(_)
3594 | ty::Dynamic(_, _)
3595 | ty::Closure(_, _)
3596 | ty::CoroutineClosure(_, _)
3597 | ty::Coroutine(_, _)
3598 | ty::CoroutineWitness(_, _)
3599 | ty::Never
3600 | ty::Param(_)
3601 | ty::Bound(_, _)
3602 | ty::Placeholder(_)
3603 | ty::Slice(..) => Ty::new_error(
3604 tcx,
3605 dcx.span_err(ty_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("type `{0}` doesn\'t have fields",
ty))
})format!("type `{ty}` doesn't have fields")),
3606 ),
3607 ty::Infer(_) => Ty::new_error(
3608 tcx,
3609 dcx.span_err(ty_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cannot use `{0}` in this position",
ty))
})format!("cannot use `{ty}` in this position")),
3610 ),
3611 ty::Array(..) | ty::Pat(..) => Ty::new_error(
3613 tcx,
3614 dcx.span_err(ty_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("type `{0}` is not yet supported in `field_of!`",
ty))
})format!("type `{ty}` is not yet supported in `field_of!`")),
3615 ),
3616 }
3617 }
3618
3619 x;#[instrument(level = "debug", skip(self), ret)]
3621 fn lower_opaque_ty(&self, def_id: LocalDefId, in_trait: Option<LocalDefId>) -> Ty<'tcx> {
3622 let tcx = self.tcx();
3623
3624 let lifetimes = tcx.opaque_captured_lifetimes(def_id);
3625 debug!(?lifetimes);
3626
3627 let def_id = if let Some(parent_def_id) = in_trait {
3631 *tcx.associated_types_for_impl_traits_in_associated_fn(parent_def_id.to_def_id())
3632 .iter()
3633 .find(|rpitit| match tcx.opt_rpitit_info(**rpitit) {
3634 Some(ty::ImplTraitInTraitData::Trait { opaque_def_id, .. }) => {
3635 opaque_def_id.expect_local() == def_id
3636 }
3637 _ => unreachable!(),
3638 })
3639 .unwrap()
3640 } else {
3641 def_id.to_def_id()
3642 };
3643
3644 let generics = tcx.generics_of(def_id);
3645 debug!(?generics);
3646
3647 let offset = generics.count() - lifetimes.len();
3651
3652 let args = ty::GenericArgs::for_item(tcx, def_id, |param, _| {
3653 if let Some(i) = (param.index as usize).checked_sub(offset) {
3654 let (lifetime, _) = lifetimes[i];
3655 self.lower_resolved_lifetime(lifetime).into()
3657 } else {
3658 tcx.mk_param_from_def(param)
3659 }
3660 });
3661 debug!(?args);
3662
3663 if in_trait.is_some() {
3664 Ty::new_projection_from_args(tcx, ty::IsRigid::No, def_id, args)
3665 } else {
3666 Ty::new_opaque(tcx, ty::IsRigid::No, def_id, args)
3667 }
3668 }
3669
3670 x;#[instrument(level = "debug", skip(self, hir_id, safety, abi, decl, generics, hir_ty), ret)]
3672 pub fn lower_fn_ty(
3673 &self,
3674 hir_id: HirId,
3675 safety: hir::Safety,
3676 abi: rustc_abi::ExternAbi,
3677 decl: &hir::FnDecl<'tcx>,
3678 generics: Option<&hir::Generics<'_>>,
3679 hir_ty: Option<&hir::Ty<'_>>,
3680 ) -> ty::PolyFnSig<'tcx> {
3681 let tcx = self.tcx();
3682 let bound_vars = tcx.late_bound_vars(hir_id);
3683 debug!(?bound_vars);
3684
3685 let (input_tys, output_ty) = self.lower_fn_sig(decl, generics, hir_id, hir_ty);
3686
3687 debug!(?output_ty);
3688
3689 debug!(?abi, ?safety, ?decl.fn_decl_kind, input_tys_len = ?input_tys.len());
3690 let fn_sig_kind = FnSigKind::default()
3691 .set_abi(abi)
3692 .set_safety(safety)
3693 .set_c_variadic(decl.fn_decl_kind.c_variadic())
3694 .set_splatted(decl.splatted(), input_tys.len())
3695 .unwrap();
3696 let fn_ty = tcx.mk_fn_sig(input_tys, output_ty, fn_sig_kind);
3697 let fn_ptr_ty = ty::Binder::bind_with_vars(fn_ty, bound_vars);
3698
3699 if let Some(hir::Ty { kind: hir::TyKind::FnPtr(fn_ptr_ty), span, .. }) = hir_ty {
3700 check_abi(tcx, hir_id, *span, fn_ptr_ty.abi);
3701 }
3702
3703 cmse::validate_cmse_abi(self.tcx(), self.dcx(), hir_id, abi, fn_ptr_ty);
3705
3706 if !fn_ptr_ty.references_error() {
3707 let inputs = fn_ptr_ty.inputs();
3714 let late_bound_in_args =
3715 tcx.collect_constrained_late_bound_regions(inputs.map_bound(|i| i.to_owned()));
3716 let output = fn_ptr_ty.output();
3717 let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(output);
3718
3719 self.validate_late_bound_regions(late_bound_in_args, late_bound_in_ret, |br_name| {
3720 struct_span_code_err!(
3721 self.dcx(),
3722 decl.output.span(),
3723 E0581,
3724 "return type references {}, which is not constrained by the fn input types",
3725 br_name
3726 )
3727 });
3728 }
3729
3730 fn_ptr_ty
3731 }
3732
3733 pub(super) fn suggest_trait_fn_ty_for_impl_fn_infer(
3738 &self,
3739 fn_hir_id: HirId,
3740 arg_idx: Option<usize>,
3741 ) -> Option<Ty<'tcx>> {
3742 let tcx = self.tcx();
3743 let hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), ident, .. }) =
3744 tcx.hir_node(fn_hir_id)
3745 else {
3746 return None;
3747 };
3748 let i = tcx.parent_hir_node(fn_hir_id).expect_item().expect_impl();
3749
3750 let trait_ref = self.lower_impl_trait_ref(&i.of_trait?.trait_ref, self.lower_ty(i.self_ty));
3751
3752 let assoc = tcx.associated_items(trait_ref.def_id).find_by_ident_and_kind(
3753 tcx,
3754 *ident,
3755 ty::AssocTag::Fn,
3756 trait_ref.def_id,
3757 )?;
3758
3759 let fn_sig = tcx
3760 .fn_sig(assoc.def_id)
3761 .instantiate(
3762 tcx,
3763 trait_ref
3764 .args
3765 .extend_to(tcx, assoc.def_id, |param, _| tcx.mk_param_from_def(param)),
3766 )
3767 .skip_norm_wip();
3768 let fn_sig = tcx.liberate_late_bound_regions(fn_hir_id.expect_owner().to_def_id(), fn_sig);
3769
3770 Some(if let Some(arg_idx) = arg_idx {
3771 *fn_sig.inputs().get(arg_idx)?
3772 } else {
3773 fn_sig.output()
3774 })
3775 }
3776
3777 #[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(3777u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("constrained_regions")
}> =
::tracing::__macro_support::FieldName::new("constrained_regions");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("referenced_regions")
}> =
::tracing::__macro_support::FieldName::new("referenced_regions");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::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};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&constrained_regions)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&referenced_regions)
as &dyn ::tracing::field::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))]
3778 fn validate_late_bound_regions<'cx>(
3779 &'cx self,
3780 constrained_regions: FxIndexSet<ty::BoundRegionKind<'tcx>>,
3781 referenced_regions: FxIndexSet<ty::BoundRegionKind<'tcx>>,
3782 generate_err: impl Fn(&str) -> Diag<'cx>,
3783 ) {
3784 for br in referenced_regions.difference(&constrained_regions) {
3785 let br_name = if let Some(name) = br.get_name(self.tcx()) {
3786 format!("lifetime `{name}`")
3787 } else {
3788 "an anonymous lifetime".to_string()
3789 };
3790
3791 let mut err = generate_err(&br_name);
3792
3793 if !br.is_named(self.tcx()) {
3794 err.note(
3801 "lifetimes appearing in an associated or opaque type are not considered constrained",
3802 );
3803 err.note("consider introducing a named lifetime parameter");
3804 }
3805
3806 err.emit();
3807 }
3808 }
3809
3810 fn construct_const_ctor_value(
3811 &self,
3812 ctor_def_id: DefId,
3813 ctor_of: CtorOf,
3814 args: GenericArgsRef<'tcx>,
3815 ) -> Const<'tcx> {
3816 let tcx = self.tcx();
3817 let parent_did = tcx.parent(ctor_def_id);
3818
3819 let adt_def = tcx.adt_def(match ctor_of {
3820 CtorOf::Variant => tcx.parent(parent_did),
3821 CtorOf::Struct => parent_did,
3822 });
3823
3824 let variant_idx = adt_def.variant_index_with_id(parent_did);
3825
3826 let valtree = if adt_def.is_enum() {
3827 let discr = ty::ValTree::from_scalar_int(tcx, variant_idx.as_u32().into());
3828 ty::ValTree::from_branches(tcx, [ty::Const::new_value(tcx, discr, tcx.types.u32)])
3829 } else {
3830 ty::ValTree::zst(tcx)
3831 };
3832
3833 let adt_ty = Ty::new_adt(tcx, adt_def, args);
3834 ty::Const::new_value(tcx, valtree, adt_ty)
3835 }
3836
3837 fn lower_view(&self, inner_ty: Ty<'tcx>, fields: &[Ident], ty_span: Span) -> Ty<'tcx> {
3838 let mut viewed_fields = Vec::<Ident>::with_capacity(fields.len());
3841
3842 for f in fields {
3843 let f = f.normalize_to_macros_2_0();
3844 if let Some(previous_field_span) =
3846 viewed_fields.iter().find_map(|f_| (*f_ == f).then_some(f_.span))
3847 {
3848 self.dcx().emit_err(diagnostics::ViewedFieldIsAlreadyPartOfTheView {
3849 name: f.name,
3850 span: f.span,
3851 previous_field_span,
3852 });
3853 continue;
3854 }
3855 viewed_fields.push(f);
3856 }
3857
3858 let variant = match inner_ty.kind() {
3860 ty::Adt(def, _) if def.is_struct() => def.non_enum_variant(),
3861
3862 ty::Adt(def, _) => {
3863 let guar = self.dcx().emit_err(diagnostics::OnlyStructsCanBeViewedAdt {
3864 ty: inner_ty,
3865 span: ty_span,
3866 article: def.article(),
3867 kind: def.descr(),
3868 });
3869 return Ty::new_error(self.tcx(), guar);
3870 }
3871
3872 _ => {
3873 let guar = self.dcx().emit_err(diagnostics::OnlyStructsCanBeViewedNonAdt {
3874 ty: inner_ty,
3875 span: ty_span,
3876 });
3877 return Ty::new_error(self.tcx(), guar);
3878 }
3879 };
3880
3881 let mut viewed_indices = Vec::with_capacity(viewed_fields.len());
3883 let mut error = None;
3884 for field in viewed_fields {
3885 let Some((_, field)) = variant
3886 .fields
3887 .iter_enumerated()
3888 .find(|(_, f)| f.ident(self.tcx()).normalize_to_macros_2_0() == field)
3889 else {
3890 let err =
3891 self.dcx().emit_err(NoFieldOnType { span: field.span, field, ty: inner_ty });
3892 error = Some(err);
3893 continue;
3894 };
3895
3896 viewed_indices.push(field);
3897 }
3898 if let Some(guar) = error {
3899 return Ty::new_error(self.tcx(), guar);
3900 }
3901
3902 inner_ty
3904 }
3905}