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_errors::codes::*;
28use rustc_errors::{
29 Applicability, Diag, DiagCtxtHandle, Diagnostic, ErrorGuaranteed, FatalError, Level, StashKey,
30 struct_span_code_err,
31};
32use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res};
33use rustc_hir::def_id::{DefId, LocalDefId};
34use rustc_hir::{self as hir, AnonConst, GenericArg, GenericArgs, HirId};
35use rustc_infer::infer::{InferCtxt, TyCtxtInferExt};
36use rustc_infer::traits::DynCompatibilityViolation;
37use rustc_macros::{TypeFoldable, TypeVisitable};
38use rustc_middle::middle::stability::AllowUnstable;
39use rustc_middle::ty::print::PrintPolyTraitRefExt as _;
40use rustc_middle::ty::{
41 self, Const, FnSigKind, GenericArgKind, GenericArgsRef, GenericParamDefKind, LitToConstInput,
42 Ty, TyCtxt, TypeSuperFoldable, TypeVisitableExt, TypingMode, Unnormalized, Upcast,
43 const_lit_matches_ty, fold_regions,
44};
45use rustc_middle::{bug, span_bug};
46use rustc_session::errors::feature_err;
47use rustc_session::lint::builtin::AMBIGUOUS_ASSOCIATED_ITEMS;
48use rustc_span::{DUMMY_SP, Ident, Span, kw, sym};
49use rustc_trait_selection::infer::InferCtxtExt;
50use rustc_trait_selection::traits::wf::object_region_bounds;
51use rustc_trait_selection::traits::{self, FulfillmentError};
52use tracing::{debug, instrument};
53
54use crate::check::check_abi;
55use crate::errors::{AmbiguousLifetimeBound, BadReturnTypeNotation, 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>;
*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: DefId,
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, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"AssocItem", __self_0, &__self_1),
TypeRelativePath::Variant { adt: __self_0, variant_did: __self_1 }
=>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"Variant", "adt", __self_0, "variant_did", &__self_1),
TypeRelativePath::Ctor { ctor_def_id: __self_0, args: __self_1 }
=>
::core::fmt::Formatter::debug_struct_field2_finish(f, "Ctor",
"ctor_def_id", __self_0, "args", &__self_1),
}
}
}Debug, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for TypeRelativePath<'tcx> {
#[inline]
fn clone(&self) -> TypeRelativePath<'tcx> {
let _: ::core::clone::AssertParamIsClone<DefId>;
let _: ::core::clone::AssertParamIsClone<GenericArgsRef<'tcx>>;
let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
let _: ::core::clone::AssertParamIsClone<GenericArgsRef<'tcx>>;
*self
}
}Clone, #[automatically_derived]
impl<'tcx> ::core::marker::Copy for TypeRelativePath<'tcx> { }Copy)]
301enum TypeRelativePath<'tcx> {
302 AssocItem(DefId, GenericArgsRef<'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 only allowed as the direct value of a `type const`"
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 && self.tcx.features().min_generic_const_args()
437 {
438 if !self.tcx.features().generic_const_args() {
439 diag.help("add `#![feature(generic_const_args)]` to allow generic expressions as the RHS of const items");
440 } else {
441 diag.help("consider factoring the expression into a `type const` item and use it as the const argument instead");
442 }
443 }
444 diag.emit()
445 }
446}
447
448impl<'tcx> ty::TypeFolder<TyCtxt<'tcx>> for ForbidParamUsesFolder<'tcx> {
449 fn cx(&self) -> TyCtxt<'tcx> {
450 self.tcx
451 }
452
453 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
454 if #[allow(non_exhaustive_omitted_patterns)] match t.kind() {
ty::Param(..) => true,
_ => false,
}matches!(t.kind(), ty::Param(..)) {
455 return Ty::new_error(self.tcx, self.error());
456 }
457 t.super_fold_with(self)
458 }
459
460 fn fold_const(&mut self, c: Const<'tcx>) -> Const<'tcx> {
461 if #[allow(non_exhaustive_omitted_patterns)] match c.kind() {
ty::ConstKind::Param(..) => true,
_ => false,
}matches!(c.kind(), ty::ConstKind::Param(..)) {
462 return Const::new_error(self.tcx, self.error());
463 }
464 c.super_fold_with(self)
465 }
466
467 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
468 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(..)) {
469 return ty::Region::new_error(self.tcx, self.error());
470 }
471 r
472 }
473}
474
475impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
476 pub fn check_param_res_if_mcg_for_instantiate_value_path(
480 &self,
481 res: Res,
482 span: Span,
483 ) -> Result<(), ErrorGuaranteed> {
484 let tcx = self.tcx();
485 let parent_def_id = self.item_def_id();
486 if let Res::Def(DefKind::ConstParam, _) = res
487 && tcx.def_kind(parent_def_id) == DefKind::AnonConst
488 && let ty::AnonConstKind::MCG = tcx.anon_const_kind(parent_def_id)
489 {
490 let folder = ForbidParamUsesFolder {
491 tcx,
492 anon_const_def_id: parent_def_id,
493 span,
494 is_self_alias: false,
495 context: ForbidParamContext::ConstArgument,
496 };
497 return Err(folder.error());
498 }
499 Ok(())
500 }
501
502 fn anon_const_forbids_generic_params(&self) -> Option<ForbidParamContext> {
510 let tcx = self.tcx();
511 let parent_def_id = self.item_def_id();
512
513 let anon_const_def_id = match tcx.def_kind(parent_def_id) {
517 DefKind::AnonConst => parent_def_id,
518 DefKind::InlineConst | DefKind::Closure => {
519 let root = tcx.typeck_root_def_id(parent_def_id.into());
520 match tcx.def_kind(root) {
521 DefKind::AnonConst => root.expect_local(),
522 _ => return None,
523 }
524 }
525 _ => return None,
526 };
527
528 match tcx.anon_const_kind(anon_const_def_id) {
529 ty::AnonConstKind::MCG => Some(ForbidParamContext::ConstArgument),
530 ty::AnonConstKind::NonTypeSystem => {
531 if tcx.generics_of(anon_const_def_id).count() == 0 {
535 Some(ForbidParamContext::EnumDiscriminant)
536 } else {
537 None
538 }
539 }
540 ty::AnonConstKind::GCE
541 | ty::AnonConstKind::GCA
542 | ty::AnonConstKind::RepeatExprCount => None,
543 }
544 }
545
546 #[must_use = "need to use transformed output"]
552 fn check_param_uses_if_mcg<T>(&self, term: T, span: Span, is_self_alias: bool) -> T
553 where
554 T: ty::TypeFoldable<TyCtxt<'tcx>>,
555 {
556 let tcx = self.tcx();
557 if let Some(context) = self.anon_const_forbids_generic_params()
558 && (term.has_param() || term.has_escaping_bound_vars())
560 {
561 let anon_const_def_id = self.item_def_id();
562 let mut folder =
563 ForbidParamUsesFolder { tcx, anon_const_def_id, span, is_self_alias, context };
564 term.fold_with(&mut folder)
565 } else {
566 term
567 }
568 }
569
570 x;#[instrument(level = "debug", skip(self), ret)]
572 pub fn lower_lifetime(
573 &self,
574 lifetime: &hir::Lifetime,
575 reason: RegionInferReason<'_>,
576 ) -> ty::Region<'tcx> {
577 if let Some(resolved) = self.tcx().named_bound_var(lifetime.hir_id) {
578 let region = self.lower_resolved_lifetime(resolved);
579 self.check_param_uses_if_mcg(region, lifetime.ident.span, false)
580 } else {
581 self.re_infer(lifetime.ident.span, reason)
582 }
583 }
584
585 x;#[instrument(level = "debug", skip(self), ret)]
587 fn lower_resolved_lifetime(&self, resolved: rbv::ResolvedArg) -> ty::Region<'tcx> {
588 let tcx = self.tcx();
589
590 match resolved {
591 rbv::ResolvedArg::StaticLifetime => tcx.lifetimes.re_static,
592
593 rbv::ResolvedArg::LateBound(debruijn, index, def_id) => {
594 let br = ty::BoundRegion {
595 var: ty::BoundVar::from_u32(index),
596 kind: ty::BoundRegionKind::Named(def_id.to_def_id()),
597 };
598 ty::Region::new_bound(tcx, debruijn, br)
599 }
600
601 rbv::ResolvedArg::EarlyBound(def_id) => {
602 let name = tcx.hir_ty_param_name(def_id);
603 let item_def_id = tcx.hir_ty_param_owner(def_id);
604 let generics = tcx.generics_of(item_def_id);
605 let index = generics.param_def_id_to_index[&def_id.to_def_id()];
606 ty::Region::new_early_param(tcx, ty::EarlyParamRegion { index, name })
607 }
608
609 rbv::ResolvedArg::Free(scope, id) => {
610 ty::Region::new_late_param(
611 tcx,
612 scope.to_def_id(),
613 ty::LateParamRegionKind::Named(id.to_def_id()),
614 )
615
616 }
618
619 rbv::ResolvedArg::Error(guar) => ty::Region::new_error(tcx, guar),
620 }
621 }
622
623 pub fn lower_generic_args_of_path_segment(
624 &self,
625 span: Span,
626 def_id: DefId,
627 item_segment: &hir::PathSegment<'tcx>,
628 ) -> GenericArgsRef<'tcx> {
629 let (args, _) = self.lower_generic_args_of_path(span, def_id, &[], item_segment, None);
630 if let Some(c) = item_segment.args().constraints.first() {
631 prohibit_assoc_item_constraint(self, c, Some((def_id, item_segment, span)));
632 }
633 args
634 }
635
636 x;#[instrument(level = "debug", skip(self, span), ret)]
671 pub(crate) fn lower_generic_args_of_path(
672 &self,
673 span: Span,
674 def_id: DefId,
675 parent_args: &[ty::GenericArg<'tcx>],
676 segment: &hir::PathSegment<'tcx>,
677 self_ty: Option<Ty<'tcx>>,
678 ) -> (GenericArgsRef<'tcx>, GenericArgCountResult) {
679 let tcx = self.tcx();
684 let generics = tcx.generics_of(def_id);
685 debug!(?generics);
686
687 if generics.has_self {
688 if generics.parent.is_some() {
689 assert!(!parent_args.is_empty())
692 } else {
693 assert!(self_ty.is_some());
695 }
696 } else {
697 assert!(self_ty.is_none());
698 }
699
700 let arg_count = check_generic_arg_count(
701 self,
702 def_id,
703 segment,
704 generics,
705 GenericArgPosition::Type,
706 self_ty.is_some(),
707 );
708
709 if generics.is_own_empty() {
714 return (tcx.mk_args(parent_args), arg_count);
715 }
716
717 struct GenericArgsCtxt<'a, 'tcx> {
718 lowerer: &'a dyn HirTyLowerer<'tcx>,
719 def_id: DefId,
720 generic_args: &'a GenericArgs<'tcx>,
721 span: Span,
722 infer_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 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 incorrect_args: &arg_count.correct,
876 };
877
878 let args = lower_generic_args(
879 self,
880 def_id,
881 parent_args,
882 self_ty.is_some(),
883 self_ty,
884 &arg_count,
885 &mut args_ctx,
886 );
887
888 (args, arg_count)
889 }
890
891 #[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(891u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&["span",
"item_def_id", "item_segment", "parent_args"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item_def_id)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item_segment)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&parent_args)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: GenericArgsRef<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{
let (args, _) =
self.lower_generic_args_of_path(span, item_def_id,
parent_args, item_segment, None);
if let Some(c) = item_segment.args().constraints.first() {
prohibit_assoc_item_constraint(self, c,
Some((item_def_id, item_segment, span)));
}
args
}
}
}#[instrument(level = "debug", skip(self))]
892 pub fn lower_generic_args_of_assoc_item(
893 &self,
894 span: Span,
895 item_def_id: DefId,
896 item_segment: &hir::PathSegment<'tcx>,
897 parent_args: GenericArgsRef<'tcx>,
898 ) -> GenericArgsRef<'tcx> {
899 let (args, _) =
900 self.lower_generic_args_of_path(span, item_def_id, parent_args, item_segment, None);
901 if let Some(c) = item_segment.args().constraints.first() {
902 prohibit_assoc_item_constraint(self, c, Some((item_def_id, item_segment, span)));
903 }
904 args
905 }
906
907 pub fn lower_impl_trait_ref(
911 &self,
912 trait_ref: &hir::TraitRef<'tcx>,
913 self_ty: Ty<'tcx>,
914 ) -> ty::TraitRef<'tcx> {
915 let [leading_segments @ .., segment] = trait_ref.path.segments else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
916
917 let _ = self.prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
918
919 self.lower_mono_trait_ref(
920 trait_ref.path.span,
921 trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise()),
922 self_ty,
923 segment,
924 true,
925 )
926 }
927
928 #[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(951u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&["bound_generic_params",
"constness", "polarity", "trait_ref", "span", "self_ty",
"predicate_filter", "overlapping_assoc_item_constraints"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&bound_generic_params)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&constness)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&polarity)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_ref)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self_ty)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&predicate_filter)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&overlapping_assoc_item_constraints)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: GenericArgCountResult = loop {};
return __tracing_attr_fake_return;
}
{
let tcx = self.tcx();
let _ = bound_generic_params;
let trait_def_id =
trait_ref.trait_def_id().unwrap_or_else(||
FatalError.raise());
let transient =
match polarity {
hir::BoundPolarity::Positive => {
tcx.is_lang_item(trait_def_id, hir::LangItem::PointeeSized)
}
hir::BoundPolarity::Negative(_) => false,
hir::BoundPolarity::Maybe(_) => {
self.require_bound_to_relax_default_trait(trait_ref, span);
true
}
};
let bounds = if transient { &mut Vec::new() } else { bounds };
let polarity =
match polarity {
hir::BoundPolarity::Positive | hir::BoundPolarity::Maybe(_)
=> {
ty::PredicatePolarity::Positive
}
hir::BoundPolarity::Negative(_) =>
ty::PredicatePolarity::Negative,
};
let [leading_segments @ .., segment] =
trait_ref.path.segments else {
::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))
};
let _ =
self.prohibit_generic_args(leading_segments.iter(),
GenericsArgsErrExtend::None);
self.report_internal_fn_trait(span, trait_def_id, segment, false);
let (generic_args, arg_count) =
self.lower_generic_args_of_path(trait_ref.path.span,
trait_def_id, &[], segment, Some(self_ty));
let constraints = segment.args().constraints;
if transient &&
(!generic_args[1..].is_empty() || !constraints.is_empty()) {
self.dcx().span_delayed_bug(span,
"transient bound should not have args or constraints");
}
let bound_vars = tcx.late_bound_vars(trait_ref.hir_ref_id);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs:1031",
"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(1031u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&["bound_vars"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&bound_vars)
as &dyn Value))])
});
} else { ; }
};
let poly_trait_ref =
ty::Binder::bind_with_vars(ty::TraitRef::new_from_args(tcx,
trait_def_id, generic_args), bound_vars);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs:1038",
"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(1038u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&["poly_trait_ref"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&poly_trait_ref)
as &dyn Value))])
});
} else { ; }
};
match predicate_filter {
PredicateFilter::All | PredicateFilter::SelfOnly |
PredicateFilter::SelfTraitThatDefines(..) |
PredicateFilter::SelfAndAssociatedTypeBounds => {
let bound =
poly_trait_ref.map_bound(|trait_ref|
{
ty::ClauseKind::Trait(ty::TraitPredicate {
trait_ref,
polarity,
})
});
let bound = (bound.upcast(tcx), span);
if tcx.is_lang_item(trait_def_id,
rustc_hir::LangItem::Sized) {
bounds.insert(0, bound);
} else { bounds.push(bound); }
}
PredicateFilter::ConstIfConst |
PredicateFilter::SelfConstIfConst => {}
}
if let hir::BoundConstness::Always(span) |
hir::BoundConstness::Maybe(span) = constness &&
!tcx.is_const_trait(trait_def_id) {
let (def_span, suggestion, suggestion_pre) =
match (trait_def_id.as_local(), tcx.sess.is_nightly_build())
{
(Some(trait_def_id), true) => {
let span = tcx.hir_expect_item(trait_def_id).vis_span;
let span =
tcx.sess.source_map().span_extend_while_whitespace(span);
(None, Some(span.shrink_to_hi()),
if self.tcx().features().const_trait_impl() {
""
} else {
"enable `#![feature(const_trait_impl)]` in your crate and "
})
}
(None, _) | (_, false) =>
(Some(tcx.def_span(trait_def_id)), None, ""),
};
self.dcx().emit_err(crate::errors::ConstBoundForNonConstTrait {
span,
modifier: constness.as_str(),
def_span,
trait_name: tcx.def_path_str(trait_def_id),
suggestion,
suggestion_pre,
});
} else {
match predicate_filter {
PredicateFilter::SelfTraitThatDefines(..) => {}
PredicateFilter::All | PredicateFilter::SelfOnly |
PredicateFilter::SelfAndAssociatedTypeBounds => {
match constness {
hir::BoundConstness::Always(_) => {
if polarity == ty::PredicatePolarity::Positive {
bounds.push((poly_trait_ref.to_host_effect_clause(tcx,
ty::BoundConstness::Const), span));
}
}
hir::BoundConstness::Maybe(_) => {}
hir::BoundConstness::Never => {}
}
}
PredicateFilter::ConstIfConst |
PredicateFilter::SelfConstIfConst => {
match constness {
hir::BoundConstness::Maybe(_) => {
if polarity == ty::PredicatePolarity::Positive {
bounds.push((poly_trait_ref.to_host_effect_clause(tcx,
ty::BoundConstness::Maybe), span));
}
}
hir::BoundConstness::Always(_) | hir::BoundConstness::Never
=> {}
}
}
}
}
let mut dup_constraints =
(overlapping_assoc_item_constraints ==
OverlappingAsssocItemConstraints::Forbidden).then_some(FxIndexMap::default());
for constraint in constraints {
if polarity == ty::PredicatePolarity::Negative {
self.dcx().span_delayed_bug(constraint.span,
"negative trait bounds should not have assoc item constraints");
break;
}
let _: Result<_, ErrorGuaranteed> =
self.lower_assoc_item_constraint(trait_ref.hir_ref_id,
poly_trait_ref, constraint, bounds,
dup_constraints.as_mut(), constraint.span,
predicate_filter);
}
arg_count
}
}
}#[instrument(level = "debug", skip(self, bounds))]
952 pub(crate) fn lower_poly_trait_ref(
953 &self,
954 &hir::PolyTraitRef {
955 bound_generic_params,
956 modifiers: hir::TraitBoundModifiers { constness, polarity },
957 trait_ref,
958 span,
959 }: &hir::PolyTraitRef<'tcx>,
960 self_ty: Ty<'tcx>,
961 bounds: &mut Vec<(ty::Clause<'tcx>, Span)>,
962 predicate_filter: PredicateFilter,
963 overlapping_assoc_item_constraints: OverlappingAsssocItemConstraints,
964 ) -> GenericArgCountResult {
965 let tcx = self.tcx();
966
967 let _ = bound_generic_params;
970
971 let trait_def_id = trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise());
972
973 let transient = match polarity {
978 hir::BoundPolarity::Positive => {
979 tcx.is_lang_item(trait_def_id, hir::LangItem::PointeeSized)
985 }
986 hir::BoundPolarity::Negative(_) => false,
987 hir::BoundPolarity::Maybe(_) => {
988 self.require_bound_to_relax_default_trait(trait_ref, span);
989 true
990 }
991 };
992 let bounds = if transient { &mut Vec::new() } else { bounds };
993
994 let polarity = match polarity {
995 hir::BoundPolarity::Positive | hir::BoundPolarity::Maybe(_) => {
996 ty::PredicatePolarity::Positive
997 }
998 hir::BoundPolarity::Negative(_) => ty::PredicatePolarity::Negative,
999 };
1000
1001 let [leading_segments @ .., segment] = trait_ref.path.segments else { bug!() };
1002
1003 let _ = self.prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
1004 self.report_internal_fn_trait(span, trait_def_id, segment, false);
1005
1006 let (generic_args, arg_count) = self.lower_generic_args_of_path(
1007 trait_ref.path.span,
1008 trait_def_id,
1009 &[],
1010 segment,
1011 Some(self_ty),
1012 );
1013
1014 let constraints = segment.args().constraints;
1015
1016 if transient && (!generic_args[1..].is_empty() || !constraints.is_empty()) {
1017 self.dcx()
1027 .span_delayed_bug(span, "transient bound should not have args or constraints");
1028 }
1029
1030 let bound_vars = tcx.late_bound_vars(trait_ref.hir_ref_id);
1031 debug!(?bound_vars);
1032
1033 let poly_trait_ref = ty::Binder::bind_with_vars(
1034 ty::TraitRef::new_from_args(tcx, trait_def_id, generic_args),
1035 bound_vars,
1036 );
1037
1038 debug!(?poly_trait_ref);
1039
1040 match predicate_filter {
1042 PredicateFilter::All
1043 | PredicateFilter::SelfOnly
1044 | PredicateFilter::SelfTraitThatDefines(..)
1045 | PredicateFilter::SelfAndAssociatedTypeBounds => {
1046 let bound = poly_trait_ref.map_bound(|trait_ref| {
1047 ty::ClauseKind::Trait(ty::TraitPredicate { trait_ref, polarity })
1048 });
1049 let bound = (bound.upcast(tcx), span);
1050 if tcx.is_lang_item(trait_def_id, rustc_hir::LangItem::Sized) {
1056 bounds.insert(0, bound);
1057 } else {
1058 bounds.push(bound);
1059 }
1060 }
1061 PredicateFilter::ConstIfConst | PredicateFilter::SelfConstIfConst => {}
1062 }
1063
1064 if let hir::BoundConstness::Always(span) | hir::BoundConstness::Maybe(span) = constness
1065 && !tcx.is_const_trait(trait_def_id)
1066 {
1067 let (def_span, suggestion, suggestion_pre) =
1068 match (trait_def_id.as_local(), tcx.sess.is_nightly_build()) {
1069 (Some(trait_def_id), true) => {
1070 let span = tcx.hir_expect_item(trait_def_id).vis_span;
1071 let span = tcx.sess.source_map().span_extend_while_whitespace(span);
1072
1073 (
1074 None,
1075 Some(span.shrink_to_hi()),
1076 if self.tcx().features().const_trait_impl() {
1077 ""
1078 } else {
1079 "enable `#![feature(const_trait_impl)]` in your crate and "
1080 },
1081 )
1082 }
1083 (None, _) | (_, false) => (Some(tcx.def_span(trait_def_id)), None, ""),
1084 };
1085 self.dcx().emit_err(crate::errors::ConstBoundForNonConstTrait {
1086 span,
1087 modifier: constness.as_str(),
1088 def_span,
1089 trait_name: tcx.def_path_str(trait_def_id),
1090 suggestion,
1091 suggestion_pre,
1092 });
1093 } else {
1094 match predicate_filter {
1095 PredicateFilter::SelfTraitThatDefines(..) => {}
1097 PredicateFilter::All
1098 | PredicateFilter::SelfOnly
1099 | PredicateFilter::SelfAndAssociatedTypeBounds => {
1100 match constness {
1101 hir::BoundConstness::Always(_) => {
1102 if polarity == ty::PredicatePolarity::Positive {
1103 bounds.push((
1104 poly_trait_ref
1105 .to_host_effect_clause(tcx, ty::BoundConstness::Const),
1106 span,
1107 ));
1108 }
1109 }
1110 hir::BoundConstness::Maybe(_) => {
1111 }
1116 hir::BoundConstness::Never => {}
1117 }
1118 }
1119 PredicateFilter::ConstIfConst | PredicateFilter::SelfConstIfConst => {
1126 match constness {
1127 hir::BoundConstness::Maybe(_) => {
1128 if polarity == ty::PredicatePolarity::Positive {
1129 bounds.push((
1130 poly_trait_ref
1131 .to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
1132 span,
1133 ));
1134 }
1135 }
1136 hir::BoundConstness::Always(_) | hir::BoundConstness::Never => {}
1137 }
1138 }
1139 }
1140 }
1141
1142 let mut dup_constraints = (overlapping_assoc_item_constraints
1143 == OverlappingAsssocItemConstraints::Forbidden)
1144 .then_some(FxIndexMap::default());
1145
1146 for constraint in constraints {
1147 if polarity == ty::PredicatePolarity::Negative {
1151 self.dcx().span_delayed_bug(
1152 constraint.span,
1153 "negative trait bounds should not have assoc item constraints",
1154 );
1155 break;
1156 }
1157
1158 let _: Result<_, ErrorGuaranteed> = self.lower_assoc_item_constraint(
1160 trait_ref.hir_ref_id,
1161 poly_trait_ref,
1162 constraint,
1163 bounds,
1164 dup_constraints.as_mut(),
1165 constraint.span,
1166 predicate_filter,
1167 );
1168 }
1170
1171 arg_count
1172 }
1173
1174 fn lower_mono_trait_ref(
1178 &self,
1179 span: Span,
1180 trait_def_id: DefId,
1181 self_ty: Ty<'tcx>,
1182 trait_segment: &hir::PathSegment<'tcx>,
1183 is_impl: bool,
1184 ) -> ty::TraitRef<'tcx> {
1185 self.report_internal_fn_trait(span, trait_def_id, trait_segment, is_impl);
1186
1187 let (generic_args, _) =
1188 self.lower_generic_args_of_path(span, trait_def_id, &[], trait_segment, Some(self_ty));
1189 if let Some(c) = trait_segment.args().constraints.first() {
1190 prohibit_assoc_item_constraint(self, c, Some((trait_def_id, trait_segment, span)));
1191 }
1192 ty::TraitRef::new_from_args(self.tcx(), trait_def_id, generic_args)
1193 }
1194
1195 fn probe_trait_that_defines_assoc_item(
1196 &self,
1197 trait_def_id: DefId,
1198 assoc_tag: ty::AssocTag,
1199 assoc_ident: Ident,
1200 ) -> bool {
1201 self.tcx()
1202 .associated_items(trait_def_id)
1203 .find_by_ident_and_kind(self.tcx(), assoc_ident, assoc_tag, trait_def_id)
1204 .is_some()
1205 }
1206
1207 fn lower_path_segment(
1208 &self,
1209 span: Span,
1210 def_id: DefId,
1211 item_segment: &hir::PathSegment<'tcx>,
1212 ) -> Ty<'tcx> {
1213 let tcx = self.tcx();
1214 let args = self.lower_generic_args_of_path_segment(span, def_id, item_segment);
1215
1216 if let DefKind::TyAlias = tcx.def_kind(def_id)
1217 && tcx.type_alias_is_lazy(def_id)
1218 {
1219 let alias_ty = ty::AliasTy::new_from_args(tcx, ty::Free { def_id }, args);
1223 Ty::new_alias(tcx, alias_ty)
1224 } else {
1225 tcx.at(span).type_of(def_id).instantiate(tcx, args).skip_norm_wip()
1226 }
1227 }
1228
1229 x;#[instrument(level = "debug", skip_all, ret)]
1237 fn probe_single_ty_param_bound_for_assoc_item(
1238 &self,
1239 ty_param_def_id: LocalDefId,
1240 ty_param_span: Span,
1241 assoc_tag: ty::AssocTag,
1242 assoc_ident: Ident,
1243 span: Span,
1244 ) -> Result<ty::PolyTraitRef<'tcx>, ErrorGuaranteed> {
1245 debug!(?ty_param_def_id, ?assoc_ident, ?span);
1246 let tcx = self.tcx();
1247
1248 let predicates = &self.probe_ty_param_bounds(span, ty_param_def_id, assoc_ident);
1249 debug!("predicates={:#?}", predicates);
1250
1251 self.probe_single_bound_for_assoc_item(
1252 || {
1253 let trait_refs = predicates
1254 .iter_identity_copied()
1255 .map(Unnormalized::skip_norm_wip)
1256 .filter_map(|(p, _)| Some(p.as_trait_clause()?.map_bound(|t| t.trait_ref)));
1257 traits::transitive_bounds_that_define_assoc_item(tcx, trait_refs, assoc_ident)
1258 },
1259 AssocItemQSelf::TyParam(ty_param_def_id, ty_param_span),
1260 assoc_tag,
1261 assoc_ident,
1262 span,
1263 None,
1264 )
1265 }
1266
1267 x;#[instrument(level = "debug", skip(self, all_candidates, qself, constraint), ret)]
1273 fn probe_single_bound_for_assoc_item<I>(
1274 &self,
1275 all_candidates: impl Fn() -> I,
1276 qself: AssocItemQSelf,
1277 assoc_tag: ty::AssocTag,
1278 assoc_ident: Ident,
1279 span: Span,
1280 constraint: Option<&hir::AssocItemConstraint<'tcx>>,
1281 ) -> Result<ty::PolyTraitRef<'tcx>, ErrorGuaranteed>
1282 where
1283 I: Iterator<Item = ty::PolyTraitRef<'tcx>>,
1284 {
1285 let tcx = self.tcx();
1286
1287 let mut matching_candidates = all_candidates().filter(|r| {
1288 self.probe_trait_that_defines_assoc_item(r.def_id(), assoc_tag, assoc_ident)
1289 });
1290
1291 let Some(bound) = matching_candidates.next() else {
1292 return Err(self.report_unresolved_assoc_item(
1293 all_candidates,
1294 qself,
1295 assoc_tag,
1296 assoc_ident,
1297 span,
1298 constraint,
1299 ));
1300 };
1301 debug!(?bound);
1302
1303 if let Some(bound2) = matching_candidates.next() {
1304 debug!(?bound2);
1305
1306 let assoc_kind_str = errors::assoc_tag_str(assoc_tag);
1307 let qself_str = qself.to_string(tcx);
1308 let mut err = self.dcx().create_err(crate::errors::AmbiguousAssocItem {
1309 span,
1310 assoc_kind: assoc_kind_str,
1311 assoc_ident,
1312 qself: &qself_str,
1313 });
1314 err.code(
1316 if let Some(constraint) = constraint
1317 && let hir::AssocItemConstraintKind::Equality { .. } = constraint.kind
1318 {
1319 E0222
1320 } else {
1321 E0221
1322 },
1323 );
1324
1325 let mut where_bounds = vec![];
1329 for bound in [bound, bound2].into_iter().chain(matching_candidates) {
1330 let bound_id = bound.def_id();
1331 let assoc_item = tcx.associated_items(bound_id).find_by_ident_and_kind(
1332 tcx,
1333 assoc_ident,
1334 assoc_tag,
1335 bound_id,
1336 );
1337 let bound_span = assoc_item.and_then(|item| tcx.hir_span_if_local(item.def_id));
1338
1339 if let Some(bound_span) = bound_span {
1340 err.span_label(
1341 bound_span,
1342 format!("ambiguous `{assoc_ident}` from `{}`", bound.print_trait_sugared(),),
1343 );
1344 if let Some(constraint) = constraint {
1345 match constraint.kind {
1346 hir::AssocItemConstraintKind::Equality { term } => {
1347 let term: ty::Term<'_> = match term {
1348 hir::Term::Ty(ty) => self.lower_ty(ty).into(),
1349 hir::Term::Const(ct) => {
1350 let assoc_item =
1351 assoc_item.expect("assoc_item should be present");
1352 let projection_term = bound.map_bound(|trait_ref| {
1353 let item_segment = hir::PathSegment {
1354 ident: constraint.ident,
1355 hir_id: constraint.hir_id,
1356 res: Res::Err,
1357 args: Some(constraint.gen_args),
1358 infer_args: false,
1359 };
1360
1361 let alias_args = self.lower_generic_args_of_assoc_item(
1362 constraint.ident.span,
1363 assoc_item.def_id,
1364 &item_segment,
1365 trait_ref.args,
1366 );
1367 ty::AliasTerm::new_from_def_id(
1368 tcx,
1369 assoc_item.def_id,
1370 alias_args,
1371 )
1372 });
1373
1374 let ty = projection_term.map_bound(|alias| {
1377 tcx.type_of(alias.def_id())
1378 .instantiate(tcx, alias.args)
1379 .skip_norm_wip()
1380 });
1381 let ty = bounds::check_assoc_const_binding_type(
1382 self,
1383 constraint.ident,
1384 ty,
1385 constraint.hir_id,
1386 );
1387
1388 self.lower_const_arg(ct, ty).into()
1389 }
1390 };
1391 if term.references_error() {
1392 continue;
1393 }
1394 where_bounds.push(format!(
1396 " T: {trait}::{assoc_ident} = {term}",
1397 trait = bound.print_only_trait_path(),
1398 ));
1399 }
1400 hir::AssocItemConstraintKind::Bound { bounds: _ } => {}
1402 }
1403 } else {
1404 err.span_suggestion_verbose(
1405 span.with_hi(assoc_ident.span.lo()),
1406 "use fully-qualified syntax to disambiguate",
1407 format!("<{qself_str} as {}>::", bound.print_only_trait_path()),
1408 Applicability::MaybeIncorrect,
1409 );
1410 }
1411 } else {
1412 let trait_ =
1413 tcx.short_string(bound.print_only_trait_path(), err.long_ty_path());
1414 err.note(format!(
1415 "associated {assoc_kind_str} `{assoc_ident}` could derive from `{trait_}`",
1416 ));
1417 }
1418 }
1419 if !where_bounds.is_empty() {
1420 err.help(format!(
1421 "consider introducing a new type parameter `T` and adding `where` constraints:\
1422 \n where\n T: {qself_str},\n{}",
1423 where_bounds.join(",\n"),
1424 ));
1425 let reported = err.emit();
1426 return Err(reported);
1427 }
1428 err.emit();
1429 }
1430
1431 Ok(bound)
1432 }
1433
1434 x;#[instrument(level = "debug", skip_all, ret)]
1461 pub fn lower_type_relative_ty_path(
1462 &self,
1463 self_ty: Ty<'tcx>,
1464 hir_self_ty: &'tcx hir::Ty<'tcx>,
1465 segment: &'tcx hir::PathSegment<'tcx>,
1466 qpath_hir_id: HirId,
1467 span: Span,
1468 permit_variants: PermitVariants,
1469 ) -> Result<(Ty<'tcx>, DefKind, DefId), ErrorGuaranteed> {
1470 let tcx = self.tcx();
1471 match self.lower_type_relative_path(
1472 self_ty,
1473 hir_self_ty,
1474 segment,
1475 qpath_hir_id,
1476 span,
1477 LowerTypeRelativePathMode::Type(permit_variants),
1478 )? {
1479 TypeRelativePath::AssocItem(def_id, args) => {
1480 let alias_ty = ty::AliasTy::new_from_args(
1481 tcx,
1482 ty::AliasTyKind::new_from_def_id(tcx, def_id),
1483 args,
1484 );
1485 let ty = Ty::new_alias(tcx, alias_ty);
1486 let ty = self.check_param_uses_if_mcg(ty, span, false);
1487 Ok((ty, tcx.def_kind(def_id), def_id))
1488 }
1489 TypeRelativePath::Variant { adt, variant_did } => {
1490 let adt = self.check_param_uses_if_mcg(adt, span, false);
1491 Ok((adt, DefKind::Variant, variant_did))
1492 }
1493 TypeRelativePath::Ctor { .. } => {
1494 let e = tcx.dcx().span_err(span, "expected type, found tuple constructor");
1495 Err(e)
1496 }
1497 }
1498 }
1499
1500 x;#[instrument(level = "debug", skip_all, ret)]
1502 fn lower_type_relative_const_path(
1503 &self,
1504 self_ty: Ty<'tcx>,
1505 hir_self_ty: &'tcx hir::Ty<'tcx>,
1506 segment: &'tcx hir::PathSegment<'tcx>,
1507 qpath_hir_id: HirId,
1508 span: Span,
1509 ) -> Result<Const<'tcx>, ErrorGuaranteed> {
1510 let tcx = self.tcx();
1511 match self.lower_type_relative_path(
1512 self_ty,
1513 hir_self_ty,
1514 segment,
1515 qpath_hir_id,
1516 span,
1517 LowerTypeRelativePathMode::Const,
1518 )? {
1519 TypeRelativePath::AssocItem(def_id, args) => {
1520 self.require_type_const_attribute(def_id, span)?;
1521 let ct = Const::new_unevaluated(tcx, ty::UnevaluatedConst::new(def_id, args));
1522 let ct = self.check_param_uses_if_mcg(ct, span, false);
1523 Ok(ct)
1524 }
1525 TypeRelativePath::Ctor { ctor_def_id, args } => match tcx.def_kind(ctor_def_id) {
1526 DefKind::Ctor(_, CtorKind::Fn) => {
1527 Ok(ty::Const::zero_sized(tcx, Ty::new_fn_def(tcx, ctor_def_id, args)))
1528 }
1529 DefKind::Ctor(ctor_of, CtorKind::Const) => {
1530 Ok(self.construct_const_ctor_value(ctor_def_id, ctor_of, args))
1531 }
1532 _ => unreachable!(),
1533 },
1534 TypeRelativePath::Variant { .. } => {
1537 span_bug!(span, "unexpected variant res for type associated const path")
1538 }
1539 }
1540 }
1541
1542 x;#[instrument(level = "debug", skip_all, ret)]
1544 fn lower_type_relative_path(
1545 &self,
1546 self_ty: Ty<'tcx>,
1547 hir_self_ty: &'tcx hir::Ty<'tcx>,
1548 segment: &'tcx hir::PathSegment<'tcx>,
1549 qpath_hir_id: HirId,
1550 span: Span,
1551 mode: LowerTypeRelativePathMode,
1552 ) -> Result<TypeRelativePath<'tcx>, ErrorGuaranteed> {
1553 struct AmbiguousAssocItem<'tcx> {
1554 variant_def_id: DefId,
1555 item_def_id: DefId,
1556 span: Span,
1557 segment_ident: Ident,
1558 bound_def_id: DefId,
1559 self_ty: Ty<'tcx>,
1560 tcx: TyCtxt<'tcx>,
1561 mode: LowerTypeRelativePathMode,
1562 }
1563
1564 impl<'a, 'tcx> Diagnostic<'a, ()> for AmbiguousAssocItem<'tcx> {
1565 fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, ()> {
1566 let Self {
1567 variant_def_id,
1568 item_def_id,
1569 span,
1570 segment_ident,
1571 bound_def_id,
1572 self_ty,
1573 tcx,
1574 mode,
1575 } = self;
1576 let mut lint = Diag::new(dcx, level, "ambiguous associated item");
1577
1578 let mut could_refer_to = |kind: DefKind, def_id, also| {
1579 let note_msg = format!(
1580 "`{}` could{} refer to the {} defined here",
1581 segment_ident,
1582 also,
1583 tcx.def_kind_descr(kind, def_id)
1584 );
1585 lint.span_note(tcx.def_span(def_id), note_msg);
1586 };
1587
1588 could_refer_to(DefKind::Variant, variant_def_id, "");
1589 could_refer_to(mode.def_kind_for_diagnostics(), item_def_id, " also");
1590
1591 lint.span_suggestion(
1592 span,
1593 "use fully-qualified syntax",
1594 format!("<{} as {}>::{}", self_ty, tcx.item_name(bound_def_id), segment_ident),
1595 Applicability::MachineApplicable,
1596 );
1597 lint
1598 }
1599 }
1600
1601 debug!(%self_ty, ?segment.ident);
1602 let tcx = self.tcx();
1603
1604 let mut variant_def_id = None;
1606 if let Some(adt_def) = self.probe_adt(span, self_ty) {
1607 if adt_def.is_enum() {
1608 let variant_def = adt_def
1609 .variants()
1610 .iter()
1611 .find(|vd| tcx.hygienic_eq(segment.ident, vd.ident(tcx), adt_def.did()));
1612 if let Some(variant_def) = variant_def {
1613 if matches!(mode, LowerTypeRelativePathMode::Const)
1616 && let Some((_, ctor_def_id)) = variant_def.ctor
1617 {
1618 tcx.check_stability(variant_def.def_id, Some(qpath_hir_id), span, None);
1619 let _ = self.prohibit_generic_args(
1620 slice::from_ref(segment).iter(),
1621 GenericsArgsErrExtend::EnumVariant {
1622 qself: hir_self_ty,
1623 assoc_segment: segment,
1624 adt_def,
1625 },
1626 );
1627 let ty::Adt(_, enum_args) = self_ty.kind() else { unreachable!() };
1628 return Ok(TypeRelativePath::Ctor { ctor_def_id, args: enum_args });
1629 }
1630 if let PermitVariants::Yes = mode.permit_variants() {
1631 tcx.check_stability(variant_def.def_id, Some(qpath_hir_id), span, None);
1632 let _ = self.prohibit_generic_args(
1633 slice::from_ref(segment).iter(),
1634 GenericsArgsErrExtend::EnumVariant {
1635 qself: hir_self_ty,
1636 assoc_segment: segment,
1637 adt_def,
1638 },
1639 );
1640 return Ok(TypeRelativePath::Variant {
1641 adt: self_ty,
1642 variant_did: variant_def.def_id,
1643 });
1644 } else {
1645 variant_def_id = Some(variant_def.def_id);
1646 }
1647 }
1648 }
1649
1650 if let Some((did, args)) = self.probe_inherent_assoc_item(
1652 segment,
1653 adt_def.did(),
1654 self_ty,
1655 qpath_hir_id,
1656 span,
1657 mode.assoc_tag(),
1658 )? {
1659 return Ok(TypeRelativePath::AssocItem(did, args));
1660 }
1661 }
1662
1663 let (item_def_id, bound) = self.resolve_type_relative_path(
1664 self_ty,
1665 hir_self_ty,
1666 mode.assoc_tag(),
1667 segment,
1668 qpath_hir_id,
1669 span,
1670 variant_def_id,
1671 )?;
1672
1673 let (item_def_id, args) = self.lower_assoc_item_path(span, item_def_id, segment, bound)?;
1674
1675 if let Some(variant_def_id) = variant_def_id {
1676 tcx.emit_node_span_lint(
1677 AMBIGUOUS_ASSOCIATED_ITEMS,
1678 qpath_hir_id,
1679 span,
1680 AmbiguousAssocItem {
1681 variant_def_id,
1682 item_def_id,
1683 span,
1684 segment_ident: segment.ident,
1685 bound_def_id: bound.def_id(),
1686 self_ty,
1687 tcx,
1688 mode,
1689 },
1690 );
1691 }
1692
1693 Ok(TypeRelativePath::AssocItem(item_def_id, args))
1694 }
1695
1696 fn resolve_type_relative_path(
1698 &self,
1699 self_ty: Ty<'tcx>,
1700 hir_self_ty: &'tcx hir::Ty<'tcx>,
1701 assoc_tag: ty::AssocTag,
1702 segment: &'tcx hir::PathSegment<'tcx>,
1703 qpath_hir_id: HirId,
1704 span: Span,
1705 variant_def_id: Option<DefId>,
1706 ) -> Result<(DefId, ty::PolyTraitRef<'tcx>), ErrorGuaranteed> {
1707 let tcx = self.tcx();
1708
1709 let self_ty_res = match hir_self_ty.kind {
1710 hir::TyKind::Path(hir::QPath::Resolved(_, path)) => path.res,
1711 _ => Res::Err,
1712 };
1713
1714 let bound = match (self_ty.kind(), self_ty_res) {
1716 (_, Res::SelfTyAlias { alias_to: impl_def_id, is_trait_impl: true, .. }) => {
1717 let trait_ref = tcx.impl_trait_ref(impl_def_id);
1720
1721 self.probe_single_bound_for_assoc_item(
1722 || {
1723 let trait_ref =
1724 ty::Binder::dummy(trait_ref.instantiate_identity().skip_norm_wip());
1725 traits::supertraits(tcx, trait_ref)
1726 },
1727 AssocItemQSelf::SelfTyAlias,
1728 assoc_tag,
1729 segment.ident,
1730 span,
1731 None,
1732 )?
1733 }
1734 (
1735 &ty::Param(_),
1736 Res::SelfTyParam { trait_: param_did } | Res::Def(DefKind::TyParam, param_did),
1737 ) => self.probe_single_ty_param_bound_for_assoc_item(
1738 param_did.expect_local(),
1739 hir_self_ty.span,
1740 assoc_tag,
1741 segment.ident,
1742 span,
1743 )?,
1744 _ => {
1745 return Err(self.report_unresolved_type_relative_path(
1746 self_ty,
1747 hir_self_ty,
1748 assoc_tag,
1749 segment.ident,
1750 qpath_hir_id,
1751 span,
1752 variant_def_id,
1753 ));
1754 }
1755 };
1756
1757 let assoc_item = self
1758 .probe_assoc_item(segment.ident, assoc_tag, qpath_hir_id, span, bound.def_id())
1759 .expect("failed to find associated item");
1760
1761 Ok((assoc_item.def_id, bound))
1762 }
1763
1764 fn probe_inherent_assoc_item(
1766 &self,
1767 segment: &hir::PathSegment<'tcx>,
1768 adt_did: DefId,
1769 self_ty: Ty<'tcx>,
1770 block: HirId,
1771 span: Span,
1772 assoc_tag: ty::AssocTag,
1773 ) -> Result<Option<(DefId, GenericArgsRef<'tcx>)>, ErrorGuaranteed> {
1774 let tcx = self.tcx();
1775
1776 if !tcx.features().inherent_associated_types() {
1777 match assoc_tag {
1778 ty::AssocTag::Type => return Ok(None),
1783 ty::AssocTag::Const => {
1784 return Err(feature_err(
1788 &tcx.sess,
1789 sym::inherent_associated_types,
1790 span,
1791 "inherent associated types are unstable",
1792 )
1793 .emit());
1794 }
1795 ty::AssocTag::Fn => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1796 }
1797 }
1798
1799 let name = segment.ident;
1800 let candidates: Vec<_> = tcx
1801 .inherent_impls(adt_did)
1802 .iter()
1803 .filter_map(|&impl_| {
1804 let (item, scope) =
1805 self.probe_assoc_item_unchecked(name, assoc_tag, block, impl_)?;
1806 Some(InherentAssocCandidate { impl_, assoc_item: item.def_id, scope })
1807 })
1808 .collect();
1809
1810 if candidates.is_empty() {
1815 return Ok(None);
1816 }
1817
1818 let (applicable_candidates, fulfillment_errors) =
1819 self.select_inherent_assoc_candidates(span, self_ty, candidates.clone());
1820
1821 let InherentAssocCandidate { impl_, assoc_item, scope: def_scope } =
1823 match &applicable_candidates[..] {
1824 &[] => Err(self.report_unresolved_inherent_assoc_item(
1825 name,
1826 self_ty,
1827 candidates,
1828 fulfillment_errors,
1829 span,
1830 assoc_tag,
1831 )),
1832
1833 &[applicable_candidate] => Ok(applicable_candidate),
1834
1835 &[_, ..] => Err(self.report_ambiguous_inherent_assoc_item(
1836 name,
1837 candidates.into_iter().map(|cand| cand.assoc_item).collect(),
1838 span,
1839 )),
1840 }?;
1841
1842 self.check_assoc_item(assoc_item, name, def_scope, block, span);
1845
1846 let parent_args = ty::GenericArgs::identity_for_item(tcx, impl_);
1850 let args = self.lower_generic_args_of_assoc_item(span, assoc_item, segment, parent_args);
1851 let args = tcx.mk_args_from_iter(
1852 std::iter::once(ty::GenericArg::from(self_ty))
1853 .chain(args.into_iter().skip(parent_args.len())),
1854 );
1855
1856 Ok(Some((assoc_item, args)))
1857 }
1858
1859 fn probe_assoc_item(
1863 &self,
1864 ident: Ident,
1865 assoc_tag: ty::AssocTag,
1866 block: HirId,
1867 span: Span,
1868 scope: DefId,
1869 ) -> Option<ty::AssocItem> {
1870 let (item, scope) = self.probe_assoc_item_unchecked(ident, assoc_tag, block, scope)?;
1871 self.check_assoc_item(item.def_id, ident, scope, block, span);
1872 Some(item)
1873 }
1874
1875 fn probe_assoc_item_unchecked(
1880 &self,
1881 ident: Ident,
1882 assoc_tag: ty::AssocTag,
1883 block: HirId,
1884 scope: DefId,
1885 ) -> Option<(ty::AssocItem, DefId)> {
1886 let tcx = self.tcx();
1887
1888 let (ident, def_scope) = tcx.adjust_ident_and_get_scope(ident, scope, block);
1889 let item = tcx
1893 .associated_items(scope)
1894 .filter_by_name_unhygienic(ident.name)
1895 .find(|i| i.tag() == assoc_tag && i.ident(tcx).normalize_to_macros_2_0() == ident)?;
1896
1897 Some((*item, def_scope))
1898 }
1899
1900 fn check_assoc_item(
1902 &self,
1903 item_def_id: DefId,
1904 ident: Ident,
1905 scope: DefId,
1906 block: HirId,
1907 span: Span,
1908 ) {
1909 let tcx = self.tcx();
1910
1911 if !tcx.visibility(item_def_id).is_accessible_from(scope, tcx) {
1912 self.dcx().emit_err(crate::errors::AssocItemIsPrivate {
1913 span,
1914 kind: tcx.def_descr(item_def_id),
1915 name: ident,
1916 defined_here_label: tcx.def_span(item_def_id),
1917 });
1918 }
1919
1920 tcx.check_stability(item_def_id, Some(block), span, None);
1921 }
1922
1923 fn probe_traits_that_match_assoc_ty(
1924 &self,
1925 qself_ty: Ty<'tcx>,
1926 assoc_ident: Ident,
1927 ) -> Vec<String> {
1928 let tcx = self.tcx();
1929
1930 let infcx_;
1933 let infcx = if let Some(infcx) = self.infcx() {
1934 infcx
1935 } else {
1936 if !!qself_ty.has_infer() {
::core::panicking::panic("assertion failed: !qself_ty.has_infer()")
};assert!(!qself_ty.has_infer());
1937 infcx_ = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
1938 &infcx_
1939 };
1940
1941 tcx.all_traits_including_private()
1942 .filter(|trait_def_id| {
1943 tcx.associated_items(*trait_def_id)
1945 .in_definition_order()
1946 .any(|i| {
1947 i.is_type()
1948 && !i.is_impl_trait_in_trait()
1949 && i.ident(tcx).normalize_to_macros_2_0() == assoc_ident
1950 })
1951 && tcx.visibility(*trait_def_id)
1953 .is_accessible_from(self.item_def_id(), tcx)
1954 && tcx.all_impls(*trait_def_id)
1955 .any(|impl_def_id| {
1956 let header = tcx.impl_trait_header(impl_def_id);
1957 let trait_ref = header.trait_ref.instantiate(tcx, infcx.fresh_args_for_item(DUMMY_SP, impl_def_id)).skip_norm_wip();
1958
1959 let value = fold_regions(tcx, qself_ty, |_, _| tcx.lifetimes.re_erased);
1960 if value.has_escaping_bound_vars() {
1962 return false;
1963 }
1964 infcx
1965 .can_eq(
1966 ty::ParamEnv::empty(),
1967 trait_ref.self_ty(),
1968 value,
1969 ) && header.polarity != ty::ImplPolarity::Negative
1970 })
1971 })
1972 .map(|trait_def_id| tcx.def_path_str(trait_def_id))
1973 .collect()
1974 }
1975
1976 #[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(1977u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&[],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{ meta.fields().value_set(&[]) })
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Ty<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{
match self.lower_resolved_assoc_item_path(span, opt_self_ty,
item_def_id, trait_segment, item_segment,
ty::AssocTag::Type) {
Ok((item_def_id, item_args)) => {
Ty::new_projection_from_args(self.tcx(), item_def_id,
item_args)
}
Err(guar) => Ty::new_error(self.tcx(), guar),
}
}
}
}#[instrument(level = "debug", skip_all)]
1978 fn lower_resolved_assoc_ty_path(
1979 &self,
1980 span: Span,
1981 opt_self_ty: Option<Ty<'tcx>>,
1982 item_def_id: DefId,
1983 trait_segment: Option<&hir::PathSegment<'tcx>>,
1984 item_segment: &hir::PathSegment<'tcx>,
1985 ) -> Ty<'tcx> {
1986 match self.lower_resolved_assoc_item_path(
1987 span,
1988 opt_self_ty,
1989 item_def_id,
1990 trait_segment,
1991 item_segment,
1992 ty::AssocTag::Type,
1993 ) {
1994 Ok((item_def_id, item_args)) => {
1995 Ty::new_projection_from_args(self.tcx(), item_def_id, item_args)
1996 }
1997 Err(guar) => Ty::new_error(self.tcx(), guar),
1998 }
1999 }
2000
2001 #[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(2002u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&[],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{ meta.fields().value_set(&[]) })
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return:
Result<Const<'tcx>, ErrorGuaranteed> = loop {};
return __tracing_attr_fake_return;
}
{
let (item_def_id, item_args) =
self.lower_resolved_assoc_item_path(span, opt_self_ty,
item_def_id, trait_segment, item_segment,
ty::AssocTag::Const)?;
self.require_type_const_attribute(item_def_id, span)?;
let uv = ty::UnevaluatedConst::new(item_def_id, item_args);
Ok(Const::new_unevaluated(self.tcx(), uv))
}
}
}#[instrument(level = "debug", skip_all)]
2003 fn lower_resolved_assoc_const_path(
2004 &self,
2005 span: Span,
2006 opt_self_ty: Option<Ty<'tcx>>,
2007 item_def_id: DefId,
2008 trait_segment: Option<&hir::PathSegment<'tcx>>,
2009 item_segment: &hir::PathSegment<'tcx>,
2010 ) -> Result<Const<'tcx>, ErrorGuaranteed> {
2011 let (item_def_id, item_args) = self.lower_resolved_assoc_item_path(
2012 span,
2013 opt_self_ty,
2014 item_def_id,
2015 trait_segment,
2016 item_segment,
2017 ty::AssocTag::Const,
2018 )?;
2019 self.require_type_const_attribute(item_def_id, span)?;
2020 let uv = ty::UnevaluatedConst::new(item_def_id, item_args);
2021 Ok(Const::new_unevaluated(self.tcx(), uv))
2022 }
2023
2024 #[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(2025u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&[],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{ meta.fields().value_set(&[]) })
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return:
Result<(DefId, GenericArgsRef<'tcx>), ErrorGuaranteed> =
loop {};
return __tracing_attr_fake_return;
}
{
let tcx = self.tcx();
let trait_def_id = tcx.parent(item_def_id);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs:2038",
"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(2038u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&["trait_def_id"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&trait_def_id)
as &dyn Value))])
});
} else { ; }
};
let Some(self_ty) =
opt_self_ty else {
return Err(self.report_missing_self_ty_for_resolved_path(trait_def_id,
span, item_segment, assoc_tag));
};
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs:2048",
"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(2048u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&["self_ty"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&self_ty) as
&dyn Value))])
});
} else { ; }
};
let trait_ref =
self.lower_mono_trait_ref(span, trait_def_id, self_ty,
trait_segment.unwrap(), false);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs:2052",
"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(2052u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&["trait_ref"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&trait_ref)
as &dyn Value))])
});
} else { ; }
};
let item_args =
self.lower_generic_args_of_assoc_item(span, item_def_id,
item_segment, trait_ref.args);
Ok((item_def_id, item_args))
}
}
}#[instrument(level = "debug", skip_all)]
2026 fn lower_resolved_assoc_item_path(
2027 &self,
2028 span: Span,
2029 opt_self_ty: Option<Ty<'tcx>>,
2030 item_def_id: DefId,
2031 trait_segment: Option<&hir::PathSegment<'tcx>>,
2032 item_segment: &hir::PathSegment<'tcx>,
2033 assoc_tag: ty::AssocTag,
2034 ) -> Result<(DefId, GenericArgsRef<'tcx>), ErrorGuaranteed> {
2035 let tcx = self.tcx();
2036
2037 let trait_def_id = tcx.parent(item_def_id);
2038 debug!(?trait_def_id);
2039
2040 let Some(self_ty) = opt_self_ty else {
2041 return Err(self.report_missing_self_ty_for_resolved_path(
2042 trait_def_id,
2043 span,
2044 item_segment,
2045 assoc_tag,
2046 ));
2047 };
2048 debug!(?self_ty);
2049
2050 let trait_ref =
2051 self.lower_mono_trait_ref(span, trait_def_id, self_ty, trait_segment.unwrap(), false);
2052 debug!(?trait_ref);
2053
2054 let item_args =
2055 self.lower_generic_args_of_assoc_item(span, item_def_id, item_segment, trait_ref.args);
2056
2057 Ok((item_def_id, item_args))
2058 }
2059
2060 pub fn prohibit_generic_args<'a>(
2061 &self,
2062 segments: impl Iterator<Item = &'a hir::PathSegment<'a>> + Clone,
2063 err_extend: GenericsArgsErrExtend<'a>,
2064 ) -> Result<(), ErrorGuaranteed> {
2065 let args_visitors = segments.clone().flat_map(|segment| segment.args().args);
2066 let mut result = Ok(());
2067 if let Some(_) = args_visitors.clone().next() {
2068 result = Err(self.report_prohibited_generic_args(
2069 segments.clone(),
2070 args_visitors,
2071 err_extend,
2072 ));
2073 }
2074
2075 for segment in segments {
2076 if let Some(c) = segment.args().constraints.first() {
2078 return Err(prohibit_assoc_item_constraint(self, c, None));
2079 }
2080 }
2081
2082 result
2083 }
2084
2085 pub fn probe_generic_path_segments(
2103 &self,
2104 segments: &[hir::PathSegment<'_>],
2105 self_ty: Option<Ty<'tcx>>,
2106 kind: DefKind,
2107 def_id: DefId,
2108 span: Span,
2109 ) -> Vec<GenericPathSegment> {
2110 let tcx = self.tcx();
2156
2157 if !!segments.is_empty() {
::core::panicking::panic("assertion failed: !segments.is_empty()")
};assert!(!segments.is_empty());
2158 let last = segments.len() - 1;
2159
2160 let mut generic_segments = ::alloc::vec::Vec::new()vec![];
2161
2162 match kind {
2163 DefKind::Ctor(CtorOf::Struct, ..) => {
2165 let generics = tcx.generics_of(def_id);
2168 let generics_def_id = generics.parent.unwrap_or(def_id);
2171 generic_segments.push(GenericPathSegment(generics_def_id, last));
2172 }
2173
2174 DefKind::Ctor(CtorOf::Variant, ..) | DefKind::Variant => {
2176 let (generics_def_id, index) = if let Some(self_ty) = self_ty {
2177 let adt_def = self.probe_adt(span, self_ty).unwrap();
2180 if true {
if !adt_def.is_enum() {
::core::panicking::panic("assertion failed: adt_def.is_enum()")
};
};debug_assert!(adt_def.is_enum());
2181
2182 (adt_def.did(), last)
2194 } else if let [.., second_to_last, _] = segments
2195 && second_to_last.args.is_some()
2196 && let Res::Def(DefKind::Enum, _) = second_to_last.res
2197 {
2198 let def_id = match kind {
2207 DefKind::Ctor(..) => tcx.parent(def_id),
2208 _ => def_id,
2209 };
2210
2211 let enum_def_id = tcx.parent(def_id);
2213
2214 (enum_def_id, last - 1)
2215 } else {
2216 let generics = tcx.generics_of(def_id);
2223 (generics.parent.unwrap_or(def_id), last)
2226 };
2227 generic_segments.push(GenericPathSegment(generics_def_id, index));
2228 }
2229
2230 DefKind::Fn | DefKind::Const { .. } | DefKind::ConstParam | DefKind::Static { .. } => {
2232 generic_segments.push(GenericPathSegment(def_id, last));
2233 }
2234
2235 DefKind::AssocFn | DefKind::AssocConst { .. } => {
2237 if segments.len() >= 2 {
2238 let generics = tcx.generics_of(def_id);
2239 generic_segments.push(GenericPathSegment(generics.parent.unwrap(), last - 1));
2240 }
2241 generic_segments.push(GenericPathSegment(def_id, last));
2242 }
2243
2244 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),
2245 }
2246
2247 {
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:2247",
"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(2247u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&["generic_segments"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&generic_segments)
as &dyn Value))])
});
} else { ; }
};debug!(?generic_segments);
2248
2249 generic_segments
2250 }
2251
2252 #[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(2253u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&[],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{ meta.fields().value_set(&[]) })
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Ty<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs:2261",
"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(2261u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&["path.res",
"opt_self_ty", "path.segments"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&path.res)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&opt_self_ty)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&path.segments)
as &dyn Value))])
});
} else { ; }
};
let tcx = self.tcx();
let span = path.span;
match path.res {
Res::Def(DefKind::OpaqueTy, did) => {
{
match tcx.opaque_ty_origin(did) {
hir::OpaqueTyOrigin::TyAlias { .. } => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val,
"hir::OpaqueTyOrigin::TyAlias { .. }",
::core::option::Option::None);
}
}
};
let [leading_segments @ .., segment] =
path.segments else {
::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))
};
let _ =
self.prohibit_generic_args(leading_segments.iter(),
GenericsArgsErrExtend::OpaqueTy);
let args =
self.lower_generic_args_of_path_segment(span, did, segment);
Ty::new_opaque(tcx, did, args)
}
Res::Def(DefKind::Enum | DefKind::TyAlias | DefKind::Struct |
DefKind::Union | DefKind::ForeignTy, did) => {
match (&opt_self_ty, &None) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
};
let [leading_segments @ .., segment] =
path.segments else {
::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))
};
let _ =
self.prohibit_generic_args(leading_segments.iter(),
GenericsArgsErrExtend::None);
self.lower_path_segment(span, did, segment)
}
Res::Def(kind @ DefKind::Variant, def_id) if
let PermitVariants::Yes = permit_variants => {
match (&opt_self_ty, &None) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
};
let generic_segments =
self.probe_generic_path_segments(path.segments, None, kind,
def_id, span);
let indices: FxHashSet<_> =
generic_segments.iter().map(|GenericPathSegment(_, index)|
index).collect();
let _ =
self.prohibit_generic_args(path.segments.iter().enumerate().filter_map(|(index,
seg)|
{
if !indices.contains(&index) { Some(seg) } else { None }
}), GenericsArgsErrExtend::DefVariant(&path.segments));
let &GenericPathSegment(def_id, index) =
generic_segments.last().unwrap();
self.lower_path_segment(span, def_id, &path.segments[index])
}
Res::Def(DefKind::TyParam, def_id) => {
match (&opt_self_ty, &None) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
};
let _ =
self.prohibit_generic_args(path.segments.iter(),
GenericsArgsErrExtend::Param(def_id));
self.lower_ty_param(hir_id)
}
Res::SelfTyParam { .. } => {
match (&opt_self_ty, &None) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
};
let _ =
self.prohibit_generic_args(path.segments.iter(),
if let [hir::PathSegment { args: Some(args), ident, .. }] =
&path.segments {
GenericsArgsErrExtend::SelfTyParam(ident.span.shrink_to_hi().to(args.span_ext))
} else { GenericsArgsErrExtend::None });
self.check_param_uses_if_mcg(tcx.types.self_param, span,
false)
}
Res::SelfTyAlias { alias_to: def_id, .. } => {
match (&opt_self_ty, &None) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
};
let ty =
tcx.at(span).type_of(def_id).instantiate_identity().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)]
2254 pub fn lower_resolved_ty_path(
2255 &self,
2256 opt_self_ty: Option<Ty<'tcx>>,
2257 path: &hir::Path<'tcx>,
2258 hir_id: HirId,
2259 permit_variants: PermitVariants,
2260 ) -> Ty<'tcx> {
2261 debug!(?path.res, ?opt_self_ty, ?path.segments);
2262 let tcx = self.tcx();
2263
2264 let span = path.span;
2265 match path.res {
2266 Res::Def(DefKind::OpaqueTy, did) => {
2267 assert_matches!(tcx.opaque_ty_origin(did), hir::OpaqueTyOrigin::TyAlias { .. });
2269 let [leading_segments @ .., segment] = path.segments else { bug!() };
2270 let _ = self.prohibit_generic_args(
2271 leading_segments.iter(),
2272 GenericsArgsErrExtend::OpaqueTy,
2273 );
2274 let args = self.lower_generic_args_of_path_segment(span, did, segment);
2275 Ty::new_opaque(tcx, did, args)
2276 }
2277 Res::Def(
2278 DefKind::Enum
2279 | DefKind::TyAlias
2280 | DefKind::Struct
2281 | DefKind::Union
2282 | DefKind::ForeignTy,
2283 did,
2284 ) => {
2285 assert_eq!(opt_self_ty, None);
2286 let [leading_segments @ .., segment] = path.segments else { bug!() };
2287 let _ = self
2288 .prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
2289 self.lower_path_segment(span, did, segment)
2290 }
2291 Res::Def(kind @ DefKind::Variant, def_id)
2292 if let PermitVariants::Yes = permit_variants =>
2293 {
2294 assert_eq!(opt_self_ty, None);
2297
2298 let generic_segments =
2299 self.probe_generic_path_segments(path.segments, None, kind, def_id, span);
2300 let indices: FxHashSet<_> =
2301 generic_segments.iter().map(|GenericPathSegment(_, index)| index).collect();
2302 let _ = self.prohibit_generic_args(
2303 path.segments.iter().enumerate().filter_map(|(index, seg)| {
2304 if !indices.contains(&index) { Some(seg) } else { None }
2305 }),
2306 GenericsArgsErrExtend::DefVariant(&path.segments),
2307 );
2308
2309 let &GenericPathSegment(def_id, index) = generic_segments.last().unwrap();
2310 self.lower_path_segment(span, def_id, &path.segments[index])
2311 }
2312 Res::Def(DefKind::TyParam, def_id) => {
2313 assert_eq!(opt_self_ty, None);
2314 let _ = self.prohibit_generic_args(
2315 path.segments.iter(),
2316 GenericsArgsErrExtend::Param(def_id),
2317 );
2318 self.lower_ty_param(hir_id)
2319 }
2320 Res::SelfTyParam { .. } => {
2321 assert_eq!(opt_self_ty, None);
2323 let _ = self.prohibit_generic_args(
2324 path.segments.iter(),
2325 if let [hir::PathSegment { args: Some(args), ident, .. }] = &path.segments {
2326 GenericsArgsErrExtend::SelfTyParam(
2327 ident.span.shrink_to_hi().to(args.span_ext),
2328 )
2329 } else {
2330 GenericsArgsErrExtend::None
2331 },
2332 );
2333 self.check_param_uses_if_mcg(tcx.types.self_param, span, false)
2334 }
2335 Res::SelfTyAlias { alias_to: def_id, .. } => {
2336 assert_eq!(opt_self_ty, None);
2338 let ty = tcx.at(span).type_of(def_id).instantiate_identity().skip_norm_wip();
2340 let _ = self.prohibit_generic_args(
2341 path.segments.iter(),
2342 GenericsArgsErrExtend::SelfTyAlias { def_id, span },
2343 );
2344 self.check_param_uses_if_mcg(ty, span, true)
2345 }
2346 Res::Def(DefKind::AssocTy, def_id) => {
2347 let trait_segment = if let [modules @ .., trait_, _item] = path.segments {
2348 let _ = self.prohibit_generic_args(modules.iter(), GenericsArgsErrExtend::None);
2349 Some(trait_)
2350 } else {
2351 None
2352 };
2353 self.lower_resolved_assoc_ty_path(
2354 span,
2355 opt_self_ty,
2356 def_id,
2357 trait_segment,
2358 path.segments.last().unwrap(),
2359 )
2360 }
2361 Res::PrimTy(prim_ty) => {
2362 assert_eq!(opt_self_ty, None);
2363 let _ = self.prohibit_generic_args(
2364 path.segments.iter(),
2365 GenericsArgsErrExtend::PrimTy(prim_ty),
2366 );
2367 match prim_ty {
2368 hir::PrimTy::Bool => tcx.types.bool,
2369 hir::PrimTy::Char => tcx.types.char,
2370 hir::PrimTy::Int(it) => Ty::new_int(tcx, it),
2371 hir::PrimTy::Uint(uit) => Ty::new_uint(tcx, uit),
2372 hir::PrimTy::Float(ft) => Ty::new_float(tcx, ft),
2373 hir::PrimTy::Str => tcx.types.str_,
2374 }
2375 }
2376 Res::Err => {
2377 let e = self
2378 .tcx()
2379 .dcx()
2380 .span_delayed_bug(path.span, "path with `Res::Err` but no error emitted");
2381 Ty::new_error(tcx, e)
2382 }
2383 Res::Def(..) => {
2384 assert_eq!(
2385 path.segments.get(0).map(|seg| seg.ident.name),
2386 Some(kw::SelfUpper),
2387 "only expected incorrect resolution for `Self`"
2388 );
2389 Ty::new_error(
2390 self.tcx(),
2391 self.dcx().span_delayed_bug(span, "incorrect resolution for `Self`"),
2392 )
2393 }
2394 _ => span_bug!(span, "unexpected resolution: {:?}", path.res),
2395 }
2396 }
2397
2398 pub(crate) fn lower_ty_param(&self, hir_id: HirId) -> Ty<'tcx> {
2403 let tcx = self.tcx();
2404
2405 let ty = match tcx.named_bound_var(hir_id) {
2406 Some(rbv::ResolvedArg::LateBound(debruijn, index, def_id)) => {
2407 let br = ty::BoundTy {
2408 var: ty::BoundVar::from_u32(index),
2409 kind: ty::BoundTyKind::Param(def_id.to_def_id()),
2410 };
2411 Ty::new_bound(tcx, debruijn, br)
2412 }
2413 Some(rbv::ResolvedArg::EarlyBound(def_id)) => {
2414 let item_def_id = tcx.hir_ty_param_owner(def_id);
2415 let generics = tcx.generics_of(item_def_id);
2416 let index = generics.param_def_id_to_index[&def_id.to_def_id()];
2417 Ty::new_param(tcx, index, tcx.hir_ty_param_name(def_id))
2418 }
2419 Some(rbv::ResolvedArg::Error(guar)) => Ty::new_error(tcx, guar),
2420 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:?}"),
2421 };
2422 self.check_param_uses_if_mcg(ty, tcx.hir_span(hir_id), false)
2423 }
2424
2425 pub(crate) fn lower_const_param(&self, param_def_id: DefId, path_hir_id: HirId) -> Const<'tcx> {
2430 let tcx = self.tcx();
2431
2432 let ct = match tcx.named_bound_var(path_hir_id) {
2433 Some(rbv::ResolvedArg::EarlyBound(_)) => {
2434 let item_def_id = tcx.parent(param_def_id);
2437 let generics = tcx.generics_of(item_def_id);
2438 let index = generics.param_def_id_to_index[¶m_def_id];
2439 let name = tcx.item_name(param_def_id);
2440 ty::Const::new_param(tcx, ty::ParamConst::new(index, name))
2441 }
2442 Some(rbv::ResolvedArg::LateBound(debruijn, index, _)) => ty::Const::new_bound(
2443 tcx,
2444 debruijn,
2445 ty::BoundConst::new(ty::BoundVar::from_u32(index)),
2446 ),
2447 Some(rbv::ResolvedArg::Error(guar)) => ty::Const::new_error(tcx, guar),
2448 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),
2449 };
2450 self.check_param_uses_if_mcg(ct, tcx.hir_span(path_hir_id), false)
2451 }
2452
2453 #[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(2454u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&["const_arg", "ty"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&const_arg)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Const<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{
let tcx = self.tcx();
if let hir::ConstArgKind::Anon(anon) = &const_arg.kind {
if tcx.features().generic_const_parameter_types() &&
(ty.has_free_regions() || ty.has_erased_regions()) {
let e =
self.dcx().span_err(const_arg.span,
"anonymous constants with lifetimes in their type are not yet supported");
tcx.feed_anon_const_type(anon.def_id,
ty::EarlyBinder::bind(Ty::new_error(tcx, e)));
return ty::Const::new_error(tcx, e);
}
if ty.has_non_region_infer() {
let e =
self.dcx().span_err(const_arg.span,
"anonymous constants with inferred types are not yet supported");
tcx.feed_anon_const_type(anon.def_id,
ty::EarlyBinder::bind(Ty::new_error(tcx, e)));
return ty::Const::new_error(tcx, e);
}
if ty.has_non_region_param() {
let e =
self.dcx().span_err(const_arg.span,
"anonymous constants referencing generics are not yet supported");
tcx.feed_anon_const_type(anon.def_id,
ty::EarlyBinder::bind(Ty::new_error(tcx, e)));
return ty::Const::new_error(tcx, e);
}
tcx.feed_anon_const_type(anon.def_id,
ty::EarlyBinder::bind(ty));
}
let hir_id = const_arg.hir_id;
match const_arg.kind {
hir::ConstArgKind::Tup(exprs) =>
self.lower_const_arg_tup(exprs, ty, const_arg.span),
hir::ConstArgKind::Path(hir::QPath::Resolved(maybe_qself,
path)) => {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs:2506",
"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(2506u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&["maybe_qself",
"path"], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&maybe_qself)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&path) as
&dyn Value))])
});
} else { ; }
};
let opt_self_ty =
maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
self.lower_resolved_const_path(opt_self_ty, path, hir_id)
}
hir::ConstArgKind::Path(hir::QPath::TypeRelative(hir_self_ty,
segment)) => {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs:2511",
"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(2511u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&["hir_self_ty",
"segment"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&hir_self_ty)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&segment) as
&dyn Value))])
});
} else { ; }
};
let self_ty = self.lower_ty(hir_self_ty);
self.lower_type_relative_const_path(self_ty, hir_self_ty,
segment, hir_id,
const_arg.span).unwrap_or_else(|guar|
Const::new_error(tcx, guar))
}
hir::ConstArgKind::Struct(qpath, inits) => {
self.lower_const_arg_struct(hir_id, qpath, inits,
const_arg.span)
}
hir::ConstArgKind::TupleCall(qpath, args) => {
self.lower_const_arg_tuple_call(hir_id, qpath, args,
const_arg.span)
}
hir::ConstArgKind::Array(array_expr) =>
self.lower_const_arg_array(array_expr, ty),
hir::ConstArgKind::Anon(anon) =>
self.lower_const_arg_anon(anon),
hir::ConstArgKind::Infer(()) =>
self.ct_infer(None, const_arg.span),
hir::ConstArgKind::Error(e) => ty::Const::new_error(tcx, e),
hir::ConstArgKind::Literal { lit, negated } => {
self.lower_const_arg_literal(&lit, negated, ty,
const_arg.span)
}
}
}
}
}#[instrument(skip(self), level = "debug")]
2455 pub fn lower_const_arg(&self, const_arg: &hir::ConstArg<'tcx>, ty: Ty<'tcx>) -> Const<'tcx> {
2456 let tcx = self.tcx();
2457
2458 if let hir::ConstArgKind::Anon(anon) = &const_arg.kind {
2459 if tcx.features().generic_const_parameter_types()
2468 && (ty.has_free_regions() || ty.has_erased_regions())
2469 {
2470 let e = self.dcx().span_err(
2471 const_arg.span,
2472 "anonymous constants with lifetimes in their type are not yet supported",
2473 );
2474 tcx.feed_anon_const_type(anon.def_id, ty::EarlyBinder::bind(Ty::new_error(tcx, e)));
2475 return ty::Const::new_error(tcx, e);
2476 }
2477 if ty.has_non_region_infer() {
2481 let e = self.dcx().span_err(
2482 const_arg.span,
2483 "anonymous constants with inferred types are not yet supported",
2484 );
2485 tcx.feed_anon_const_type(anon.def_id, ty::EarlyBinder::bind(Ty::new_error(tcx, e)));
2486 return ty::Const::new_error(tcx, e);
2487 }
2488 if ty.has_non_region_param() {
2491 let e = self.dcx().span_err(
2492 const_arg.span,
2493 "anonymous constants referencing generics are not yet supported",
2494 );
2495 tcx.feed_anon_const_type(anon.def_id, ty::EarlyBinder::bind(Ty::new_error(tcx, e)));
2496 return ty::Const::new_error(tcx, e);
2497 }
2498
2499 tcx.feed_anon_const_type(anon.def_id, ty::EarlyBinder::bind(ty));
2500 }
2501
2502 let hir_id = const_arg.hir_id;
2503 match const_arg.kind {
2504 hir::ConstArgKind::Tup(exprs) => self.lower_const_arg_tup(exprs, ty, const_arg.span),
2505 hir::ConstArgKind::Path(hir::QPath::Resolved(maybe_qself, path)) => {
2506 debug!(?maybe_qself, ?path);
2507 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
2508 self.lower_resolved_const_path(opt_self_ty, path, hir_id)
2509 }
2510 hir::ConstArgKind::Path(hir::QPath::TypeRelative(hir_self_ty, segment)) => {
2511 debug!(?hir_self_ty, ?segment);
2512 let self_ty = self.lower_ty(hir_self_ty);
2513 self.lower_type_relative_const_path(
2514 self_ty,
2515 hir_self_ty,
2516 segment,
2517 hir_id,
2518 const_arg.span,
2519 )
2520 .unwrap_or_else(|guar| Const::new_error(tcx, guar))
2521 }
2522 hir::ConstArgKind::Struct(qpath, inits) => {
2523 self.lower_const_arg_struct(hir_id, qpath, inits, const_arg.span)
2524 }
2525 hir::ConstArgKind::TupleCall(qpath, args) => {
2526 self.lower_const_arg_tuple_call(hir_id, qpath, args, const_arg.span)
2527 }
2528 hir::ConstArgKind::Array(array_expr) => self.lower_const_arg_array(array_expr, ty),
2529 hir::ConstArgKind::Anon(anon) => self.lower_const_arg_anon(anon),
2530 hir::ConstArgKind::Infer(()) => self.ct_infer(None, const_arg.span),
2531 hir::ConstArgKind::Error(e) => ty::Const::new_error(tcx, e),
2532 hir::ConstArgKind::Literal { lit, negated } => {
2533 self.lower_const_arg_literal(&lit, negated, ty, const_arg.span)
2534 }
2535 }
2536 }
2537
2538 fn lower_const_arg_array(
2539 &self,
2540 array_expr: &'tcx hir::ConstArgArrayExpr<'tcx>,
2541 ty: Ty<'tcx>,
2542 ) -> Const<'tcx> {
2543 let tcx = self.tcx();
2544
2545 let elem_ty = match ty.kind() {
2546 ty::Array(elem_ty, _) => elem_ty,
2547 ty::Error(e) => return Const::new_error(tcx, *e),
2548 _ => {
2549 let e = tcx
2550 .dcx()
2551 .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));
2552 return Const::new_error(tcx, e);
2553 }
2554 };
2555
2556 let elems = array_expr
2557 .elems
2558 .iter()
2559 .map(|elem| self.lower_const_arg(elem, *elem_ty))
2560 .collect::<Vec<_>>();
2561
2562 let valtree = ty::ValTree::from_branches(tcx, elems);
2563
2564 ty::Const::new_value(tcx, valtree, ty)
2565 }
2566
2567 fn lower_const_arg_tuple_call(
2568 &self,
2569 hir_id: HirId,
2570 qpath: hir::QPath<'tcx>,
2571 args: &'tcx [&'tcx hir::ConstArg<'tcx>],
2572 span: Span,
2573 ) -> Const<'tcx> {
2574 let tcx = self.tcx();
2575
2576 let non_adt_or_variant_res = || {
2577 let e = tcx.dcx().span_err(span, "tuple constructor with invalid base path");
2578 ty::Const::new_error(tcx, e)
2579 };
2580
2581 let ctor_const = match qpath {
2582 hir::QPath::Resolved(maybe_qself, path) => {
2583 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
2584 self.lower_resolved_const_path(opt_self_ty, path, hir_id)
2585 }
2586 hir::QPath::TypeRelative(hir_self_ty, segment) => {
2587 let self_ty = self.lower_ty(hir_self_ty);
2588 match self.lower_type_relative_const_path(
2589 self_ty,
2590 hir_self_ty,
2591 segment,
2592 hir_id,
2593 span,
2594 ) {
2595 Ok(c) => c,
2596 Err(_) => return non_adt_or_variant_res(),
2597 }
2598 }
2599 };
2600
2601 let Some(value) = ctor_const.try_to_value() else {
2602 return non_adt_or_variant_res();
2603 };
2604
2605 let (adt_def, adt_args, variant_did) = match value.ty.kind() {
2606 ty::FnDef(def_id, fn_args)
2607 if let DefKind::Ctor(CtorOf::Variant, _) = tcx.def_kind(*def_id) =>
2608 {
2609 let parent_did = tcx.parent(*def_id);
2610 let enum_did = tcx.parent(parent_did);
2611 (tcx.adt_def(enum_did), fn_args, parent_did)
2612 }
2613 ty::FnDef(def_id, fn_args)
2614 if let DefKind::Ctor(CtorOf::Struct, _) = tcx.def_kind(*def_id) =>
2615 {
2616 let parent_did = tcx.parent(*def_id);
2617 (tcx.adt_def(parent_did), fn_args, parent_did)
2618 }
2619 _ => {
2620 let e = self.dcx().span_err(
2621 span,
2622 "complex const arguments must be placed inside of a `const` block",
2623 );
2624 return Const::new_error(tcx, e);
2625 }
2626 };
2627
2628 let variant_def = adt_def.variant_with_id(variant_did);
2629 let variant_idx = adt_def.variant_index_with_id(variant_did).as_u32();
2630
2631 if args.len() != variant_def.fields.len() {
2632 let e = tcx.dcx().span_err(
2633 span,
2634 ::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!(
2635 "tuple constructor has {} arguments but {} were provided",
2636 variant_def.fields.len(),
2637 args.len()
2638 ),
2639 );
2640 return ty::Const::new_error(tcx, e);
2641 }
2642
2643 let fields = variant_def
2644 .fields
2645 .iter()
2646 .zip(args)
2647 .map(|(field_def, arg)| {
2648 self.lower_const_arg(
2649 arg,
2650 tcx.type_of(field_def.did).instantiate(tcx, adt_args).skip_norm_wip(),
2651 )
2652 })
2653 .collect::<Vec<_>>();
2654
2655 let opt_discr_const = if adt_def.is_enum() {
2656 let valtree = ty::ValTree::from_scalar_int(tcx, variant_idx.into());
2657 Some(ty::Const::new_value(tcx, valtree, tcx.types.u32))
2658 } else {
2659 None
2660 };
2661
2662 let valtree = ty::ValTree::from_branches(tcx, opt_discr_const.into_iter().chain(fields));
2663 let adt_ty = Ty::new_adt(tcx, adt_def, adt_args);
2664 ty::Const::new_value(tcx, valtree, adt_ty)
2665 }
2666
2667 fn lower_const_arg_tup(
2668 &self,
2669 exprs: &'tcx [&'tcx hir::ConstArg<'tcx>],
2670 ty: Ty<'tcx>,
2671 span: Span,
2672 ) -> Const<'tcx> {
2673 let tcx = self.tcx();
2674
2675 let tys = match ty.kind() {
2676 ty::Tuple(tys) => tys,
2677 ty::Error(e) => return Const::new_error(tcx, *e),
2678 _ => {
2679 let e = tcx.dcx().span_err(span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected `{0}`, found const tuple",
ty))
})format!("expected `{}`, found const tuple", ty));
2680 return Const::new_error(tcx, e);
2681 }
2682 };
2683
2684 let exprs = exprs
2685 .iter()
2686 .zip(tys.iter())
2687 .map(|(expr, ty)| self.lower_const_arg(expr, ty))
2688 .collect::<Vec<_>>();
2689
2690 let valtree = ty::ValTree::from_branches(tcx, exprs);
2691 ty::Const::new_value(tcx, valtree, ty)
2692 }
2693
2694 fn lower_const_arg_struct(
2695 &self,
2696 hir_id: HirId,
2697 qpath: hir::QPath<'tcx>,
2698 inits: &'tcx [&'tcx hir::ConstArgExprField<'tcx>],
2699 span: Span,
2700 ) -> Const<'tcx> {
2701 let tcx = self.tcx();
2704
2705 let non_adt_or_variant_res = || {
2706 let e = tcx.dcx().span_err(span, "struct expression with invalid base path");
2707 ty::Const::new_error(tcx, e)
2708 };
2709
2710 let ResolvedStructPath { res: opt_res, ty } =
2711 self.lower_path_for_struct_expr(qpath, span, hir_id);
2712
2713 let variant_did = match qpath {
2714 hir::QPath::Resolved(maybe_qself, path) => {
2715 {
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:2715",
"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(2715u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&["maybe_qself",
"path"], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&maybe_qself)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&path) as
&dyn Value))])
});
} else { ; }
};debug!(?maybe_qself, ?path);
2716 let variant_did = match path.res {
2717 Res::Def(DefKind::Variant | DefKind::Struct, did) => did,
2718 _ => return non_adt_or_variant_res(),
2719 };
2720
2721 variant_did
2722 }
2723 hir::QPath::TypeRelative(hir_self_ty, segment) => {
2724 {
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:2724",
"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(2724u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&["hir_self_ty",
"segment"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&hir_self_ty)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&segment) as
&dyn Value))])
});
} else { ; }
};debug!(?hir_self_ty, ?segment);
2725
2726 let res_def_id = match opt_res {
2727 Ok(r)
2728 if #[allow(non_exhaustive_omitted_patterns)] match tcx.def_kind(r.def_id()) {
DefKind::Variant | DefKind::Struct => true,
_ => false,
}matches!(
2729 tcx.def_kind(r.def_id()),
2730 DefKind::Variant | DefKind::Struct
2731 ) =>
2732 {
2733 r.def_id()
2734 }
2735 Ok(_) => return non_adt_or_variant_res(),
2736 Err(e) => return ty::Const::new_error(tcx, e),
2737 };
2738
2739 res_def_id
2740 }
2741 };
2742
2743 let ty::Adt(adt_def, adt_args) = ty.kind() else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
2744
2745 let variant_def = adt_def.variant_with_id(variant_did);
2746 let variant_idx = adt_def.variant_index_with_id(variant_did).as_u32();
2747
2748 let fields = variant_def
2749 .fields
2750 .iter()
2751 .map(|field_def| {
2752 let mut init_expr =
2755 inits.iter().filter(|init_expr| init_expr.field.name == field_def.name);
2756
2757 match init_expr.next() {
2758 Some(expr) => {
2759 if let Some(expr) = init_expr.next() {
2760 let e = tcx.dcx().span_err(
2761 expr.span,
2762 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("struct expression with multiple initialisers for `{0}`",
field_def.name))
})format!(
2763 "struct expression with multiple initialisers for `{}`",
2764 field_def.name,
2765 ),
2766 );
2767 return ty::Const::new_error(tcx, e);
2768 }
2769
2770 self.lower_const_arg(
2771 expr.expr,
2772 tcx.type_of(field_def.did).instantiate(tcx, adt_args).skip_norm_wip(),
2773 )
2774 }
2775 None => {
2776 let e = tcx.dcx().span_err(
2777 span,
2778 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("struct expression with missing field initialiser for `{0}`",
field_def.name))
})format!(
2779 "struct expression with missing field initialiser for `{}`",
2780 field_def.name
2781 ),
2782 );
2783 ty::Const::new_error(tcx, e)
2784 }
2785 }
2786 })
2787 .collect::<Vec<_>>();
2788
2789 let opt_discr_const = if adt_def.is_enum() {
2790 let valtree = ty::ValTree::from_scalar_int(tcx, variant_idx.into());
2791 Some(ty::Const::new_value(tcx, valtree, tcx.types.u32))
2792 } else {
2793 None
2794 };
2795
2796 let valtree = ty::ValTree::from_branches(tcx, opt_discr_const.into_iter().chain(fields));
2797 ty::Const::new_value(tcx, valtree, ty)
2798 }
2799
2800 pub fn lower_path_for_struct_expr(
2801 &self,
2802 qpath: hir::QPath<'tcx>,
2803 path_span: Span,
2804 hir_id: HirId,
2805 ) -> ResolvedStructPath<'tcx> {
2806 match qpath {
2807 hir::QPath::Resolved(ref maybe_qself, path) => {
2808 let self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
2809 let ty = self.lower_resolved_ty_path(self_ty, path, hir_id, PermitVariants::Yes);
2810 ResolvedStructPath { res: Ok(path.res), ty }
2811 }
2812 hir::QPath::TypeRelative(hir_self_ty, segment) => {
2813 let self_ty = self.lower_ty(hir_self_ty);
2814
2815 let result = self.lower_type_relative_ty_path(
2816 self_ty,
2817 hir_self_ty,
2818 segment,
2819 hir_id,
2820 path_span,
2821 PermitVariants::Yes,
2822 );
2823 let ty = result
2824 .map(|(ty, _, _)| ty)
2825 .unwrap_or_else(|guar| Ty::new_error(self.tcx(), guar));
2826
2827 ResolvedStructPath {
2828 res: result.map(|(_, kind, def_id)| Res::Def(kind, def_id)),
2829 ty,
2830 }
2831 }
2832 }
2833 }
2834
2835 fn lower_resolved_const_path(
2837 &self,
2838 opt_self_ty: Option<Ty<'tcx>>,
2839 path: &hir::Path<'tcx>,
2840 hir_id: HirId,
2841 ) -> Const<'tcx> {
2842 let tcx = self.tcx();
2843 let span = path.span;
2844 let ct = match path.res {
2845 Res::Def(DefKind::ConstParam, def_id) => {
2846 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);
2847 let _ = self.prohibit_generic_args(
2848 path.segments.iter(),
2849 GenericsArgsErrExtend::Param(def_id),
2850 );
2851 self.lower_const_param(def_id, hir_id)
2852 }
2853 Res::Def(DefKind::Const { .. }, did) => {
2854 if let Err(guar) = self.require_type_const_attribute(did, span) {
2855 return Const::new_error(self.tcx(), guar);
2856 }
2857
2858 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);
2859 let [leading_segments @ .., segment] = path.segments else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
2860 let _ = self
2861 .prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
2862 let args = self.lower_generic_args_of_path_segment(span, did, segment);
2863 ty::Const::new_unevaluated(tcx, ty::UnevaluatedConst::new(did, args))
2864 }
2865 Res::Def(DefKind::Ctor(ctor_of, CtorKind::Const), did) => {
2866 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);
2867 let [leading_segments @ .., segment] = path.segments else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
2868 let _ = self
2869 .prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
2870
2871 let parent_did = tcx.parent(did);
2872 let generics_did = match ctor_of {
2873 CtorOf::Variant => tcx.parent(parent_did),
2874 CtorOf::Struct => parent_did,
2875 };
2876 let args = self.lower_generic_args_of_path_segment(span, generics_did, segment);
2877
2878 self.construct_const_ctor_value(did, ctor_of, args)
2879 }
2880 Res::Def(DefKind::Ctor(_, CtorKind::Fn), did) => {
2881 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);
2882 let [leading_segments @ .., segment] = path.segments else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
2883 let _ = self
2884 .prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
2885 let parent_did = tcx.parent(did);
2886 let generics_did = if let DefKind::Ctor(CtorOf::Variant, _) = tcx.def_kind(did) {
2887 tcx.parent(parent_did)
2888 } else {
2889 parent_did
2890 };
2891 let args = self.lower_generic_args_of_path_segment(span, generics_did, segment);
2892 ty::Const::zero_sized(tcx, Ty::new_fn_def(tcx, did, args))
2893 }
2894 Res::Def(DefKind::AssocConst { .. }, did) => {
2895 let trait_segment = if let [modules @ .., trait_, _item] = path.segments {
2896 let _ = self.prohibit_generic_args(modules.iter(), GenericsArgsErrExtend::None);
2897 Some(trait_)
2898 } else {
2899 None
2900 };
2901 self.lower_resolved_assoc_const_path(
2902 span,
2903 opt_self_ty,
2904 did,
2905 trait_segment,
2906 path.segments.last().unwrap(),
2907 )
2908 .unwrap_or_else(|guar| Const::new_error(tcx, guar))
2909 }
2910 Res::Def(DefKind::Static { .. }, _) => {
2911 ::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")
2912 }
2913 Res::Def(DefKind::Fn | DefKind::AssocFn, did) => {
2915 self.dcx().span_delayed_bug(span, "function items cannot be used as const args");
2916 let args = self.lower_generic_args_of_path_segment(
2917 span,
2918 did,
2919 path.segments.last().unwrap(),
2920 );
2921 ty::Const::zero_sized(tcx, Ty::new_fn_def(tcx, did, args))
2922 }
2923
2924 res @ (Res::Def(
2927 DefKind::Mod
2928 | DefKind::Enum
2929 | DefKind::Variant
2930 | DefKind::Struct
2931 | DefKind::OpaqueTy
2932 | DefKind::TyAlias
2933 | DefKind::TraitAlias
2934 | DefKind::AssocTy
2935 | DefKind::Union
2936 | DefKind::Trait
2937 | DefKind::ForeignTy
2938 | DefKind::TyParam
2939 | DefKind::Macro(_)
2940 | DefKind::LifetimeParam
2941 | DefKind::Use
2942 | DefKind::ForeignMod
2943 | DefKind::AnonConst
2944 | DefKind::InlineConst
2945 | DefKind::Field
2946 | DefKind::Impl { .. }
2947 | DefKind::Closure
2948 | DefKind::ExternCrate
2949 | DefKind::GlobalAsm
2950 | DefKind::SyntheticCoroutineBody,
2951 _,
2952 )
2953 | Res::PrimTy(_)
2954 | Res::SelfTyParam { .. }
2955 | Res::SelfTyAlias { .. }
2956 | Res::SelfCtor(_)
2957 | Res::Local(_)
2958 | Res::ToolMod
2959 | Res::OpenMod(..)
2960 | Res::NonMacroAttr(_)
2961 | Res::Err) => Const::new_error_with_message(
2962 tcx,
2963 span,
2964 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("invalid Res {0:?} for const path",
res))
})format!("invalid Res {res:?} for const path"),
2965 ),
2966 };
2967 self.check_param_uses_if_mcg(ct, span, false)
2968 }
2969
2970 #[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(2971u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&["anon"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&anon)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Const<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{
let tcx = self.tcx();
let expr = &tcx.hir_body(anon.body).value;
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs:2976",
"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(2976u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&["expr"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&expr) as
&dyn Value))])
});
} else { ; }
};
let ty =
tcx.type_of(anon.def_id).instantiate_identity().skip_norm_wip();
match self.try_lower_anon_const_lit(ty, expr) {
Some(v) => v,
None =>
ty::Const::new_unevaluated(tcx,
ty::UnevaluatedConst {
def: anon.def_id.to_def_id(),
args: ty::GenericArgs::identity_for_item(tcx,
anon.def_id.to_def_id()),
}),
}
}
}
}#[instrument(skip(self), level = "debug")]
2972 fn lower_const_arg_anon(&self, anon: &AnonConst) -> Const<'tcx> {
2973 let tcx = self.tcx();
2974
2975 let expr = &tcx.hir_body(anon.body).value;
2976 debug!(?expr);
2977
2978 let ty = tcx.type_of(anon.def_id).instantiate_identity().skip_norm_wip();
2982
2983 match self.try_lower_anon_const_lit(ty, expr) {
2984 Some(v) => v,
2985 None => ty::Const::new_unevaluated(
2986 tcx,
2987 ty::UnevaluatedConst {
2988 def: anon.def_id.to_def_id(),
2989 args: ty::GenericArgs::identity_for_item(tcx, anon.def_id.to_def_id()),
2990 },
2991 ),
2992 }
2993 }
2994
2995 #[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(2995u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&["kind", "neg", "ty",
"span"], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&kind)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&neg as
&dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Const<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{
let tcx = self.tcx();
let 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")]
2996 fn lower_const_arg_literal(
2997 &self,
2998 kind: &LitKind,
2999 neg: bool,
3000 ty: Ty<'tcx>,
3001 span: Span,
3002 ) -> Const<'tcx> {
3003 let tcx = self.tcx();
3004
3005 let ty = if !ty.has_infer() { Some(ty) } else { None };
3006
3007 if let LitKind::Err(guar) = *kind {
3008 return ty::Const::new_error(tcx, guar);
3009 }
3010 let input = LitToConstInput { lit: *kind, ty, neg };
3011 match tcx.at(span).lit_to_const(input) {
3012 Some(value) => ty::Const::new_value(tcx, value.valtree, value.ty),
3013 None => {
3014 let e = tcx.dcx().span_err(span, "type annotations needed for the literal");
3015 ty::Const::new_error(tcx, e)
3016 }
3017 }
3018 }
3019
3020 #[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(3020u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&["ty", "expr"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expr)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Option<Const<'tcx>> = loop {};
return __tracing_attr_fake_return;
}
{
let tcx = self.tcx();
let expr =
match &expr.kind {
hir::ExprKind::Block(block, _) if
block.stmts.is_empty() && block.expr.is_some() => {
block.expr.as_ref().unwrap()
}
_ => expr,
};
let lit_input =
match expr.kind {
hir::ExprKind::Lit(lit) => {
Some(LitToConstInput {
lit: lit.node,
ty: 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")]
3021 fn try_lower_anon_const_lit(
3022 &self,
3023 ty: Ty<'tcx>,
3024 expr: &'tcx hir::Expr<'tcx>,
3025 ) -> Option<Const<'tcx>> {
3026 let tcx = self.tcx();
3027
3028 let expr = match &expr.kind {
3031 hir::ExprKind::Block(block, _) if block.stmts.is_empty() && block.expr.is_some() => {
3032 block.expr.as_ref().unwrap()
3033 }
3034 _ => expr,
3035 };
3036
3037 let lit_input = match expr.kind {
3038 hir::ExprKind::Lit(lit) => {
3039 Some(LitToConstInput { lit: lit.node, ty: Some(ty), neg: false })
3040 }
3041 hir::ExprKind::Unary(hir::UnOp::Neg, expr) => match expr.kind {
3042 hir::ExprKind::Lit(lit) => {
3043 Some(LitToConstInput { lit: lit.node, ty: Some(ty), neg: true })
3044 }
3045 _ => None,
3046 },
3047 _ => None,
3048 };
3049
3050 lit_input.and_then(|l| {
3051 if const_lit_matches_ty(tcx, &l.lit, ty, l.neg) {
3052 tcx.at(expr.span)
3053 .lit_to_const(l)
3054 .map(|value| ty::Const::new_value(tcx, value.valtree, value.ty))
3055 } else {
3056 None
3057 }
3058 })
3059 }
3060
3061 fn require_type_const_attribute(
3062 &self,
3063 def_id: DefId,
3064 span: Span,
3065 ) -> Result<(), ErrorGuaranteed> {
3066 let tcx = self.tcx();
3067 if tcx.is_type_const(def_id) {
3068 Ok(())
3069 } else {
3070 let mut err = self.dcx().struct_span_err(
3071 span,
3072 "use of `const` in the type system not defined as `type const`",
3073 );
3074 if def_id.is_local() {
3075 let name = tcx.def_path_str(def_id);
3076 err.span_suggestion_verbose(
3077 tcx.def_span(def_id).shrink_to_lo(),
3078 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("add `type` before `const` for `{0}`",
name))
})format!("add `type` before `const` for `{name}`"),
3079 ::alloc::__export::must_use({ ::alloc::fmt::format(format_args!("type ")) })format!("type "),
3080 Applicability::MaybeIncorrect,
3081 );
3082 } else {
3083 err.note("only consts marked defined as `type const` may be used in types");
3084 }
3085 Err(err.emit())
3086 }
3087 }
3088
3089 fn lower_delegation_ty(&self, infer: hir::InferDelegation<'tcx>) -> Ty<'tcx> {
3090 match infer {
3091 hir::InferDelegation::DefId(def_id) => {
3092 self.tcx().type_of(def_id).instantiate_identity().skip_norm_wip()
3093 }
3094 rustc_hir::InferDelegation::Sig(_, idx) => {
3095 let delegation_sig = self.tcx().inherit_sig_for_delegation_item(self.item_def_id());
3096
3097 match idx {
3098 hir::InferDelegationSig::Input(idx) => delegation_sig[idx],
3099 hir::InferDelegationSig::Output { .. } => *delegation_sig.last().unwrap(),
3100 }
3101 }
3102 }
3103 }
3104
3105 x;#[instrument(level = "debug", skip(self), ret)]
3107 pub fn lower_ty(&self, hir_ty: &hir::Ty<'tcx>) -> Ty<'tcx> {
3108 let tcx = self.tcx();
3109
3110 let result_ty = match &hir_ty.kind {
3111 hir::TyKind::InferDelegation(infer) => self.lower_delegation_ty(*infer),
3112 hir::TyKind::Slice(ty) => Ty::new_slice(tcx, self.lower_ty(ty)),
3113 hir::TyKind::Ptr(mt) => Ty::new_ptr(tcx, self.lower_ty(mt.ty), mt.mutbl),
3114 hir::TyKind::Ref(region, mt) => {
3115 let r = self.lower_lifetime(region, RegionInferReason::Reference);
3116 debug!(?r);
3117 let t = self.lower_ty(mt.ty);
3118 Ty::new_ref(tcx, r, t, mt.mutbl)
3119 }
3120 hir::TyKind::Never => tcx.types.never,
3121 hir::TyKind::Tup(fields) => {
3122 Ty::new_tup_from_iter(tcx, fields.iter().map(|t| self.lower_ty(t)))
3123 }
3124 hir::TyKind::FnPtr(bf) => {
3125 check_c_variadic_abi(tcx, bf.decl, bf.abi, hir_ty.span);
3126
3127 Ty::new_fn_ptr(
3128 tcx,
3129 self.lower_fn_ty(hir_ty.hir_id, bf.safety, bf.abi, bf.decl, None, Some(hir_ty)),
3130 )
3131 }
3132 hir::TyKind::UnsafeBinder(binder) => Ty::new_unsafe_binder(
3133 tcx,
3134 ty::Binder::bind_with_vars(
3135 self.lower_ty(binder.inner_ty),
3136 tcx.late_bound_vars(hir_ty.hir_id),
3137 ),
3138 ),
3139 hir::TyKind::TraitObject(bounds, tagged_ptr) => {
3140 let lifetime = tagged_ptr.pointer();
3141 let syntax = tagged_ptr.tag();
3142 self.lower_trait_object_ty(hir_ty.span, hir_ty.hir_id, bounds, lifetime, syntax)
3143 }
3144 hir::TyKind::Path(hir::QPath::Resolved(_, path))
3148 if path.segments.last().and_then(|segment| segment.args).is_some_and(|args| {
3149 matches!(args.parenthesized, hir::GenericArgsParentheses::ReturnTypeNotation)
3150 }) =>
3151 {
3152 let guar = self
3153 .dcx()
3154 .emit_err(BadReturnTypeNotation { span: hir_ty.span, suggestion: None });
3155 Ty::new_error(tcx, guar)
3156 }
3157 hir::TyKind::Path(hir::QPath::Resolved(maybe_qself, path)) => {
3158 debug!(?maybe_qself, ?path);
3159 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
3160 self.lower_resolved_ty_path(opt_self_ty, path, hir_ty.hir_id, PermitVariants::No)
3161 }
3162 &hir::TyKind::OpaqueDef(opaque_ty) => {
3163 let in_trait = match opaque_ty.origin {
3167 hir::OpaqueTyOrigin::FnReturn {
3168 parent,
3169 in_trait_or_impl: Some(hir::RpitContext::Trait),
3170 ..
3171 }
3172 | hir::OpaqueTyOrigin::AsyncFn {
3173 parent,
3174 in_trait_or_impl: Some(hir::RpitContext::Trait),
3175 ..
3176 } => Some(parent),
3177 hir::OpaqueTyOrigin::FnReturn {
3178 in_trait_or_impl: None | Some(hir::RpitContext::TraitImpl),
3179 ..
3180 }
3181 | hir::OpaqueTyOrigin::AsyncFn {
3182 in_trait_or_impl: None | Some(hir::RpitContext::TraitImpl),
3183 ..
3184 }
3185 | hir::OpaqueTyOrigin::TyAlias { .. } => None,
3186 };
3187
3188 self.lower_opaque_ty(opaque_ty.def_id, in_trait)
3189 }
3190 hir::TyKind::TraitAscription(hir_bounds) => {
3191 let self_ty = self.ty_infer(None, hir_ty.span);
3194 let mut bounds = Vec::new();
3195 self.lower_bounds(
3196 self_ty,
3197 hir_bounds.iter(),
3198 &mut bounds,
3199 ty::List::empty(),
3200 PredicateFilter::All,
3201 OverlappingAsssocItemConstraints::Allowed,
3202 );
3203 self.add_implicit_sizedness_bounds(
3204 &mut bounds,
3205 self_ty,
3206 hir_bounds,
3207 ImpliedBoundsContext::AssociatedTypeOrImplTrait,
3208 hir_ty.span,
3209 );
3210 self.register_trait_ascription_bounds(bounds, hir_ty.hir_id, hir_ty.span);
3211 self_ty
3212 }
3213 hir::TyKind::Path(hir::QPath::TypeRelative(hir_self_ty, segment))
3217 if segment.args.is_some_and(|args| {
3218 matches!(args.parenthesized, hir::GenericArgsParentheses::ReturnTypeNotation)
3219 }) =>
3220 {
3221 let guar = if let hir::Node::LetStmt(stmt) = tcx.parent_hir_node(hir_ty.hir_id)
3222 && let None = stmt.init
3223 && let hir::TyKind::Path(hir::QPath::Resolved(_, self_ty_path)) =
3224 hir_self_ty.kind
3225 && let Res::Def(DefKind::Enum | DefKind::Struct | DefKind::Union, def_id) =
3226 self_ty_path.res
3227 && let Some(_) = tcx
3228 .inherent_impls(def_id)
3229 .iter()
3230 .flat_map(|imp| {
3231 tcx.associated_items(*imp).filter_by_name_unhygienic(segment.ident.name)
3232 })
3233 .filter(|assoc| {
3234 matches!(assoc.kind, ty::AssocKind::Fn { has_self: false, .. })
3235 })
3236 .next()
3237 {
3238 let err = tcx
3240 .dcx()
3241 .struct_span_err(
3242 hir_ty.span,
3243 "expected type, found associated function call",
3244 )
3245 .with_span_suggestion_verbose(
3246 stmt.pat.span.between(hir_ty.span),
3247 "use `=` if you meant to assign",
3248 " = ".to_string(),
3249 Applicability::MaybeIncorrect,
3250 );
3251 self.dcx().try_steal_replace_and_emit_err(
3252 hir_ty.span,
3253 StashKey::ReturnTypeNotation,
3254 err,
3255 )
3256 } else if let hir::Node::LetStmt(stmt) = tcx.parent_hir_node(hir_ty.hir_id)
3257 && let None = stmt.init
3258 && let hir::TyKind::Path(hir::QPath::Resolved(_, self_ty_path)) =
3259 hir_self_ty.kind
3260 && let Res::PrimTy(_) = self_ty_path.res
3261 && self.dcx().has_stashed_diagnostic(hir_ty.span, StashKey::ReturnTypeNotation)
3262 {
3263 let err = tcx
3266 .dcx()
3267 .struct_span_err(
3268 hir_ty.span,
3269 "expected type, found associated function call",
3270 )
3271 .with_span_suggestion_verbose(
3272 stmt.pat.span.between(hir_ty.span),
3273 "use `=` if you meant to assign",
3274 " = ".to_string(),
3275 Applicability::MaybeIncorrect,
3276 );
3277 self.dcx().try_steal_replace_and_emit_err(
3278 hir_ty.span,
3279 StashKey::ReturnTypeNotation,
3280 err,
3281 )
3282 } else {
3283 let suggestion = if self
3284 .dcx()
3285 .has_stashed_diagnostic(hir_ty.span, StashKey::ReturnTypeNotation)
3286 {
3287 Some(segment.ident.span.shrink_to_hi().with_hi(hir_ty.span.hi()))
3293 } else {
3294 None
3295 };
3296 let err = self
3297 .dcx()
3298 .create_err(BadReturnTypeNotation { span: hir_ty.span, suggestion });
3299 self.dcx().try_steal_replace_and_emit_err(
3300 hir_ty.span,
3301 StashKey::ReturnTypeNotation,
3302 err,
3303 )
3304 };
3305 Ty::new_error(tcx, guar)
3306 }
3307 hir::TyKind::Path(hir::QPath::TypeRelative(hir_self_ty, segment)) => {
3308 debug!(?hir_self_ty, ?segment);
3309 let self_ty = self.lower_ty(hir_self_ty);
3310 self.lower_type_relative_ty_path(
3311 self_ty,
3312 hir_self_ty,
3313 segment,
3314 hir_ty.hir_id,
3315 hir_ty.span,
3316 PermitVariants::No,
3317 )
3318 .map(|(ty, _, _)| ty)
3319 .unwrap_or_else(|guar| Ty::new_error(tcx, guar))
3320 }
3321 hir::TyKind::Array(ty, length) => {
3322 let length = self.lower_const_arg(length, tcx.types.usize);
3323 Ty::new_array_with_const_len(tcx, self.lower_ty(ty), length)
3324 }
3325 hir::TyKind::Infer(()) => {
3326 self.ty_infer(None, hir_ty.span)
3331 }
3332 hir::TyKind::Pat(ty, pat) => {
3333 let ty_span = ty.span;
3334 let ty = self.lower_ty(ty);
3335 let pat_ty = match self.lower_pat_ty_pat(ty, ty_span, pat) {
3336 Ok(kind) => Ty::new_pat(tcx, ty, tcx.mk_pat(kind)),
3337 Err(guar) => Ty::new_error(tcx, guar),
3338 };
3339 self.record_ty(pat.hir_id, ty, pat.span);
3340 pat_ty
3341 }
3342 hir::TyKind::FieldOf(ty, hir::TyFieldPath { variant, field }) => self.lower_field_of(
3343 self.lower_ty(ty),
3344 self.item_def_id(),
3345 ty.span,
3346 hir_ty.hir_id,
3347 *variant,
3348 *field,
3349 ),
3350 hir::TyKind::Err(guar) => Ty::new_error(tcx, *guar),
3351 };
3352
3353 self.record_ty(hir_ty.hir_id, result_ty, hir_ty.span);
3354 result_ty
3355 }
3356
3357 fn lower_pat_ty_pat(
3358 &self,
3359 ty: Ty<'tcx>,
3360 ty_span: Span,
3361 pat: &hir::TyPat<'tcx>,
3362 ) -> Result<ty::PatternKind<'tcx>, ErrorGuaranteed> {
3363 let tcx = self.tcx();
3364 match pat.kind {
3365 hir::TyPatKind::Range(start, end) => {
3366 match ty.kind() {
3367 ty::Int(_) | ty::Uint(_) | ty::Char => {
3370 let start = self.lower_const_arg(start, ty);
3371 let end = self.lower_const_arg(end, ty);
3372 Ok(ty::PatternKind::Range { start, end })
3373 }
3374 _ => Err(self
3375 .dcx()
3376 .span_delayed_bug(ty_span, "invalid base type for range pattern")),
3377 }
3378 }
3379 hir::TyPatKind::NotNull => Ok(ty::PatternKind::NotNull),
3380 hir::TyPatKind::Or(patterns) => {
3381 self.tcx()
3382 .mk_patterns_from_iter(patterns.iter().map(|pat| {
3383 self.lower_pat_ty_pat(ty, ty_span, pat).map(|pat| tcx.mk_pat(pat))
3384 }))
3385 .map(ty::PatternKind::Or)
3386 }
3387 hir::TyPatKind::Err(e) => Err(e),
3388 }
3389 }
3390
3391 fn lower_field_of(
3392 &self,
3393 ty: Ty<'tcx>,
3394 item_def_id: LocalDefId,
3395 ty_span: Span,
3396 hir_id: HirId,
3397 variant: Option<Ident>,
3398 field: Ident,
3399 ) -> Ty<'tcx> {
3400 let dcx = self.dcx();
3401 let tcx = self.tcx();
3402 match ty.kind() {
3403 ty::Adt(def, _) => {
3404 let base_did = def.did();
3405 let kind_name = tcx.def_descr(base_did);
3406 let (variant_idx, variant) = if def.is_enum() {
3407 let Some(variant) = variant else {
3408 let err = dcx
3409 .create_err(NoVariantNamed { span: field.span, ident: field, ty })
3410 .with_span_help(
3411 field.span.shrink_to_lo(),
3412 "you might be missing a variant here: `Variant.`",
3413 )
3414 .emit();
3415 return Ty::new_error(tcx, err);
3416 };
3417
3418 if let Some(res) = def
3419 .variants()
3420 .iter_enumerated()
3421 .find(|(_, f)| f.ident(tcx).normalize_to_macros_2_0() == variant)
3422 {
3423 res
3424 } else {
3425 let err = dcx
3426 .create_err(NoVariantNamed { span: variant.span, ident: variant, ty })
3427 .emit();
3428 return Ty::new_error(tcx, err);
3429 }
3430 } else {
3431 if let Some(variant) = variant {
3432 let adt_path = tcx.def_path_str(base_did);
3433 {
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!(
3434 dcx,
3435 variant.span,
3436 E0609,
3437 "{kind_name} `{adt_path}` does not have any variants",
3438 )
3439 .with_span_label(variant.span, "variant unknown")
3440 .emit();
3441 }
3442 (FIRST_VARIANT, def.non_enum_variant())
3443 };
3444 let block = tcx.local_def_id_to_hir_id(item_def_id);
3445 let (ident, def_scope) = tcx.adjust_ident_and_get_scope(field, def.did(), block);
3446 if let Some((field_idx, field)) = variant
3447 .fields
3448 .iter_enumerated()
3449 .find(|(_, f)| f.ident(tcx).normalize_to_macros_2_0() == ident)
3450 {
3451 if field.vis.is_accessible_from(def_scope, tcx) {
3452 tcx.check_stability(field.did, Some(hir_id), ident.span, None);
3453 } else {
3454 let adt_path = tcx.def_path_str(base_did);
3455 {
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!(
3456 dcx,
3457 ident.span,
3458 E0616,
3459 "field `{ident}` of {kind_name} `{adt_path}` is private",
3460 )
3461 .with_span_label(ident.span, "private field")
3462 .emit();
3463 }
3464 Ty::new_field_representing_type(tcx, ty, variant_idx, field_idx)
3465 } else {
3466 let err =
3467 dcx.create_err(NoFieldOnType { span: ident.span, field: ident, ty }).emit();
3468 Ty::new_error(tcx, err)
3469 }
3470 }
3471 ty::Tuple(tys) => {
3472 let index = match field.as_str().parse::<usize>() {
3473 Ok(idx) => idx,
3474 Err(_) => {
3475 let err =
3476 dcx.create_err(NoFieldOnType { span: field.span, field, ty }).emit();
3477 return Ty::new_error(tcx, err);
3478 }
3479 };
3480 if field.name != sym::integer(index) {
3481 ::rustc_middle::util::bug::bug_fmt(format_args!("we parsed above, but now not equal?"));bug!("we parsed above, but now not equal?");
3482 }
3483 if tys.get(index).is_some() {
3484 Ty::new_field_representing_type(tcx, ty, FIRST_VARIANT, index.into())
3485 } else {
3486 let err = dcx.create_err(NoFieldOnType { span: field.span, field, ty }).emit();
3487 Ty::new_error(tcx, err)
3488 }
3489 }
3490 ty::Alias(..) => Ty::new_error(
3503 tcx,
3504 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}`")),
3505 ),
3506 ty::Error(err) => Ty::new_error(tcx, *err),
3507 ty::Bool
3508 | ty::Char
3509 | ty::Int(_)
3510 | ty::Uint(_)
3511 | ty::Float(_)
3512 | ty::Foreign(_)
3513 | ty::Str
3514 | ty::RawPtr(_, _)
3515 | ty::Ref(_, _, _)
3516 | ty::FnDef(_, _)
3517 | ty::FnPtr(_, _)
3518 | ty::UnsafeBinder(_)
3519 | ty::Dynamic(_, _)
3520 | ty::Closure(_, _)
3521 | ty::CoroutineClosure(_, _)
3522 | ty::Coroutine(_, _)
3523 | ty::CoroutineWitness(_, _)
3524 | ty::Never
3525 | ty::Param(_)
3526 | ty::Bound(_, _)
3527 | ty::Placeholder(_)
3528 | ty::Slice(..) => Ty::new_error(
3529 tcx,
3530 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")),
3531 ),
3532 ty::Infer(_) => Ty::new_error(
3533 tcx,
3534 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")),
3535 ),
3536 ty::Array(..) | ty::Pat(..) => Ty::new_error(
3538 tcx,
3539 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!`")),
3540 ),
3541 }
3542 }
3543
3544 x;#[instrument(level = "debug", skip(self), ret)]
3546 fn lower_opaque_ty(&self, def_id: LocalDefId, in_trait: Option<LocalDefId>) -> Ty<'tcx> {
3547 let tcx = self.tcx();
3548
3549 let lifetimes = tcx.opaque_captured_lifetimes(def_id);
3550 debug!(?lifetimes);
3551
3552 let def_id = if let Some(parent_def_id) = in_trait {
3556 *tcx.associated_types_for_impl_traits_in_associated_fn(parent_def_id.to_def_id())
3557 .iter()
3558 .find(|rpitit| match tcx.opt_rpitit_info(**rpitit) {
3559 Some(ty::ImplTraitInTraitData::Trait { opaque_def_id, .. }) => {
3560 opaque_def_id.expect_local() == def_id
3561 }
3562 _ => unreachable!(),
3563 })
3564 .unwrap()
3565 } else {
3566 def_id.to_def_id()
3567 };
3568
3569 let generics = tcx.generics_of(def_id);
3570 debug!(?generics);
3571
3572 let offset = generics.count() - lifetimes.len();
3576
3577 let args = ty::GenericArgs::for_item(tcx, def_id, |param, _| {
3578 if let Some(i) = (param.index as usize).checked_sub(offset) {
3579 let (lifetime, _) = lifetimes[i];
3580 self.lower_resolved_lifetime(lifetime).into()
3582 } else {
3583 tcx.mk_param_from_def(param)
3584 }
3585 });
3586 debug!(?args);
3587
3588 if in_trait.is_some() {
3589 Ty::new_projection_from_args(tcx, def_id, args)
3590 } else {
3591 Ty::new_opaque(tcx, def_id, args)
3592 }
3593 }
3594
3595 x;#[instrument(level = "debug", skip(self, hir_id, safety, abi, decl, generics, hir_ty), ret)]
3597 pub fn lower_fn_ty(
3598 &self,
3599 hir_id: HirId,
3600 safety: hir::Safety,
3601 abi: rustc_abi::ExternAbi,
3602 decl: &hir::FnDecl<'tcx>,
3603 generics: Option<&hir::Generics<'_>>,
3604 hir_ty: Option<&hir::Ty<'_>>,
3605 ) -> ty::PolyFnSig<'tcx> {
3606 let tcx = self.tcx();
3607 let bound_vars = tcx.late_bound_vars(hir_id);
3608 debug!(?bound_vars);
3609
3610 let (input_tys, output_ty) = self.lower_fn_sig(decl, generics, hir_id, hir_ty);
3611
3612 debug!(?output_ty);
3613
3614 let fn_sig_kind = FnSigKind::default()
3615 .set_abi(abi)
3616 .set_safety(safety)
3617 .set_c_variadic(decl.fn_decl_kind.c_variadic());
3618 let fn_ty = tcx.mk_fn_sig(input_tys, output_ty, fn_sig_kind);
3619 let fn_ptr_ty = ty::Binder::bind_with_vars(fn_ty, bound_vars);
3620
3621 if let hir::Node::Ty(hir::Ty { kind: hir::TyKind::FnPtr(fn_ptr_ty), span, .. }) =
3622 tcx.hir_node(hir_id)
3623 {
3624 check_abi(tcx, hir_id, *span, fn_ptr_ty.abi);
3625 }
3626
3627 cmse::validate_cmse_abi(self.tcx(), self.dcx(), hir_id, abi, fn_ptr_ty);
3629
3630 if !fn_ptr_ty.references_error() {
3631 let inputs = fn_ptr_ty.inputs();
3638 let late_bound_in_args =
3639 tcx.collect_constrained_late_bound_regions(inputs.map_bound(|i| i.to_owned()));
3640 let output = fn_ptr_ty.output();
3641 let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(output);
3642
3643 self.validate_late_bound_regions(late_bound_in_args, late_bound_in_ret, |br_name| {
3644 struct_span_code_err!(
3645 self.dcx(),
3646 decl.output.span(),
3647 E0581,
3648 "return type references {}, which is not constrained by the fn input types",
3649 br_name
3650 )
3651 });
3652 }
3653
3654 fn_ptr_ty
3655 }
3656
3657 pub(super) fn suggest_trait_fn_ty_for_impl_fn_infer(
3662 &self,
3663 fn_hir_id: HirId,
3664 arg_idx: Option<usize>,
3665 ) -> Option<Ty<'tcx>> {
3666 let tcx = self.tcx();
3667 let hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), ident, .. }) =
3668 tcx.hir_node(fn_hir_id)
3669 else {
3670 return None;
3671 };
3672 let i = tcx.parent_hir_node(fn_hir_id).expect_item().expect_impl();
3673
3674 let trait_ref = self.lower_impl_trait_ref(&i.of_trait?.trait_ref, self.lower_ty(i.self_ty));
3675
3676 let assoc = tcx.associated_items(trait_ref.def_id).find_by_ident_and_kind(
3677 tcx,
3678 *ident,
3679 ty::AssocTag::Fn,
3680 trait_ref.def_id,
3681 )?;
3682
3683 let fn_sig = tcx
3684 .fn_sig(assoc.def_id)
3685 .instantiate(
3686 tcx,
3687 trait_ref
3688 .args
3689 .extend_to(tcx, assoc.def_id, |param, _| tcx.mk_param_from_def(param)),
3690 )
3691 .skip_norm_wip();
3692 let fn_sig = tcx.liberate_late_bound_regions(fn_hir_id.expect_owner().to_def_id(), fn_sig);
3693
3694 Some(if let Some(arg_idx) = arg_idx {
3695 *fn_sig.inputs().get(arg_idx)?
3696 } else {
3697 fn_sig.output()
3698 })
3699 }
3700
3701 #[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(3701u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&["constrained_regions",
"referenced_regions"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::TRACE <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::TRACE <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&constrained_regions)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&referenced_regions)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
for br in referenced_regions.difference(&constrained_regions) {
let br_name =
if let Some(name) = br.get_name(self.tcx()) {
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("lifetime `{0}`", name))
})
} else { "an anonymous lifetime".to_string() };
let mut err = generate_err(&br_name);
if !br.is_named(self.tcx()) {
err.note("lifetimes appearing in an associated or opaque type are not considered constrained");
err.note("consider introducing a named lifetime parameter");
}
err.emit();
}
}
}
}#[instrument(level = "trace", skip(self, generate_err))]
3702 fn validate_late_bound_regions<'cx>(
3703 &'cx self,
3704 constrained_regions: FxIndexSet<ty::BoundRegionKind<'tcx>>,
3705 referenced_regions: FxIndexSet<ty::BoundRegionKind<'tcx>>,
3706 generate_err: impl Fn(&str) -> Diag<'cx>,
3707 ) {
3708 for br in referenced_regions.difference(&constrained_regions) {
3709 let br_name = if let Some(name) = br.get_name(self.tcx()) {
3710 format!("lifetime `{name}`")
3711 } else {
3712 "an anonymous lifetime".to_string()
3713 };
3714
3715 let mut err = generate_err(&br_name);
3716
3717 if !br.is_named(self.tcx()) {
3718 err.note(
3725 "lifetimes appearing in an associated or opaque type are not considered constrained",
3726 );
3727 err.note("consider introducing a named lifetime parameter");
3728 }
3729
3730 err.emit();
3731 }
3732 }
3733
3734 x;#[instrument(level = "debug", skip(self, span), ret)]
3742 fn compute_object_lifetime_bound(
3743 &self,
3744 span: Span,
3745 existential_predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
3746 ) -> Option<ty::Region<'tcx>> {
3748 let tcx = self.tcx();
3749
3750 let derived_region_bounds = object_region_bounds(tcx, existential_predicates);
3753
3754 if derived_region_bounds.is_empty() {
3757 return None;
3758 }
3759
3760 if derived_region_bounds.iter().any(|r| r.is_static()) {
3763 return Some(tcx.lifetimes.re_static);
3764 }
3765
3766 let r = derived_region_bounds[0];
3770 if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
3771 self.dcx().emit_err(AmbiguousLifetimeBound { span });
3772 }
3773 Some(r)
3774 }
3775
3776 fn construct_const_ctor_value(
3777 &self,
3778 ctor_def_id: DefId,
3779 ctor_of: CtorOf,
3780 args: GenericArgsRef<'tcx>,
3781 ) -> Const<'tcx> {
3782 let tcx = self.tcx();
3783 let parent_did = tcx.parent(ctor_def_id);
3784
3785 let adt_def = tcx.adt_def(match ctor_of {
3786 CtorOf::Variant => tcx.parent(parent_did),
3787 CtorOf::Struct => parent_did,
3788 });
3789
3790 let variant_idx = adt_def.variant_index_with_id(parent_did);
3791
3792 let valtree = if adt_def.is_enum() {
3793 let discr = ty::ValTree::from_scalar_int(tcx, variant_idx.as_u32().into());
3794 ty::ValTree::from_branches(tcx, [ty::Const::new_value(tcx, discr, tcx.types.u32)])
3795 } else {
3796 ty::ValTree::zst(tcx)
3797 };
3798
3799 let adt_ty = Ty::new_adt(tcx, adt_def, args);
3800 ty::Const::new_value(tcx, valtree, adt_ty)
3801 }
3802}