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::lint::builtin::AMBIGUOUS_ASSOCIATED_ITEMS;
47use rustc_session::parse::feature_err;
48use rustc_span::{DUMMY_SP, Ident, Span, kw, sym};
49use rustc_trait_selection::infer::InferCtxtExt;
50use rustc_trait_selection::traits::wf::object_region_bounds;
51use rustc_trait_selection::traits::{self, FulfillmentError};
52use tracing::{debug, instrument};
53
54use crate::check::check_abi;
55use crate::errors::{AmbiguousLifetimeBound, BadReturnTypeNotation, 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();
2178 if true {
if !adt_def.is_enum() {
::core::panicking::panic("assertion failed: adt_def.is_enum()")
};
};debug_assert!(adt_def.is_enum());
2179 (adt_def.did(), last)
2180 } else if last >= 1 && segments[last - 1].args.is_some() {
2181 let mut def_id = def_id;
2184
2185 if let DefKind::Ctor(..) = kind {
2187 def_id = tcx.parent(def_id);
2188 }
2189
2190 let enum_def_id = tcx.parent(def_id);
2192 (enum_def_id, last - 1)
2193 } else {
2194 let generics = tcx.generics_of(def_id);
2200 (generics.parent.unwrap_or(def_id), last)
2203 };
2204 generic_segments.push(GenericPathSegment(generics_def_id, index));
2205 }
2206
2207 DefKind::Fn | DefKind::Const { .. } | DefKind::ConstParam | DefKind::Static { .. } => {
2209 generic_segments.push(GenericPathSegment(def_id, last));
2210 }
2211
2212 DefKind::AssocFn | DefKind::AssocConst { .. } => {
2214 if segments.len() >= 2 {
2215 let generics = tcx.generics_of(def_id);
2216 generic_segments.push(GenericPathSegment(generics.parent.unwrap(), last - 1));
2217 }
2218 generic_segments.push(GenericPathSegment(def_id, last));
2219 }
2220
2221 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),
2222 }
2223
2224 {
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:2224",
"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(2224u32),
::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);
2225
2226 generic_segments
2227 }
2228
2229 #[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(2230u32),
::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:2238",
"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(2238u32),
::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)]
2231 pub fn lower_resolved_ty_path(
2232 &self,
2233 opt_self_ty: Option<Ty<'tcx>>,
2234 path: &hir::Path<'tcx>,
2235 hir_id: HirId,
2236 permit_variants: PermitVariants,
2237 ) -> Ty<'tcx> {
2238 debug!(?path.res, ?opt_self_ty, ?path.segments);
2239 let tcx = self.tcx();
2240
2241 let span = path.span;
2242 match path.res {
2243 Res::Def(DefKind::OpaqueTy, did) => {
2244 assert_matches!(tcx.opaque_ty_origin(did), hir::OpaqueTyOrigin::TyAlias { .. });
2246 let [leading_segments @ .., segment] = path.segments else { bug!() };
2247 let _ = self.prohibit_generic_args(
2248 leading_segments.iter(),
2249 GenericsArgsErrExtend::OpaqueTy,
2250 );
2251 let args = self.lower_generic_args_of_path_segment(span, did, segment);
2252 Ty::new_opaque(tcx, did, args)
2253 }
2254 Res::Def(
2255 DefKind::Enum
2256 | DefKind::TyAlias
2257 | DefKind::Struct
2258 | DefKind::Union
2259 | DefKind::ForeignTy,
2260 did,
2261 ) => {
2262 assert_eq!(opt_self_ty, None);
2263 let [leading_segments @ .., segment] = path.segments else { bug!() };
2264 let _ = self
2265 .prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
2266 self.lower_path_segment(span, did, segment)
2267 }
2268 Res::Def(kind @ DefKind::Variant, def_id)
2269 if let PermitVariants::Yes = permit_variants =>
2270 {
2271 assert_eq!(opt_self_ty, None);
2274
2275 let generic_segments =
2276 self.probe_generic_path_segments(path.segments, None, kind, def_id, span);
2277 let indices: FxHashSet<_> =
2278 generic_segments.iter().map(|GenericPathSegment(_, index)| index).collect();
2279 let _ = self.prohibit_generic_args(
2280 path.segments.iter().enumerate().filter_map(|(index, seg)| {
2281 if !indices.contains(&index) { Some(seg) } else { None }
2282 }),
2283 GenericsArgsErrExtend::DefVariant(&path.segments),
2284 );
2285
2286 let &GenericPathSegment(def_id, index) = generic_segments.last().unwrap();
2287 self.lower_path_segment(span, def_id, &path.segments[index])
2288 }
2289 Res::Def(DefKind::TyParam, def_id) => {
2290 assert_eq!(opt_self_ty, None);
2291 let _ = self.prohibit_generic_args(
2292 path.segments.iter(),
2293 GenericsArgsErrExtend::Param(def_id),
2294 );
2295 self.lower_ty_param(hir_id)
2296 }
2297 Res::SelfTyParam { .. } => {
2298 assert_eq!(opt_self_ty, None);
2300 let _ = self.prohibit_generic_args(
2301 path.segments.iter(),
2302 if let [hir::PathSegment { args: Some(args), ident, .. }] = &path.segments {
2303 GenericsArgsErrExtend::SelfTyParam(
2304 ident.span.shrink_to_hi().to(args.span_ext),
2305 )
2306 } else {
2307 GenericsArgsErrExtend::None
2308 },
2309 );
2310 self.check_param_uses_if_mcg(tcx.types.self_param, span, false)
2311 }
2312 Res::SelfTyAlias { alias_to: def_id, .. } => {
2313 assert_eq!(opt_self_ty, None);
2315 let ty = tcx.at(span).type_of(def_id).instantiate_identity().skip_norm_wip();
2317 let _ = self.prohibit_generic_args(
2318 path.segments.iter(),
2319 GenericsArgsErrExtend::SelfTyAlias { def_id, span },
2320 );
2321 self.check_param_uses_if_mcg(ty, span, true)
2322 }
2323 Res::Def(DefKind::AssocTy, def_id) => {
2324 let trait_segment = if let [modules @ .., trait_, _item] = path.segments {
2325 let _ = self.prohibit_generic_args(modules.iter(), GenericsArgsErrExtend::None);
2326 Some(trait_)
2327 } else {
2328 None
2329 };
2330 self.lower_resolved_assoc_ty_path(
2331 span,
2332 opt_self_ty,
2333 def_id,
2334 trait_segment,
2335 path.segments.last().unwrap(),
2336 )
2337 }
2338 Res::PrimTy(prim_ty) => {
2339 assert_eq!(opt_self_ty, None);
2340 let _ = self.prohibit_generic_args(
2341 path.segments.iter(),
2342 GenericsArgsErrExtend::PrimTy(prim_ty),
2343 );
2344 match prim_ty {
2345 hir::PrimTy::Bool => tcx.types.bool,
2346 hir::PrimTy::Char => tcx.types.char,
2347 hir::PrimTy::Int(it) => Ty::new_int(tcx, it),
2348 hir::PrimTy::Uint(uit) => Ty::new_uint(tcx, uit),
2349 hir::PrimTy::Float(ft) => Ty::new_float(tcx, ft),
2350 hir::PrimTy::Str => tcx.types.str_,
2351 }
2352 }
2353 Res::Err => {
2354 let e = self
2355 .tcx()
2356 .dcx()
2357 .span_delayed_bug(path.span, "path with `Res::Err` but no error emitted");
2358 Ty::new_error(tcx, e)
2359 }
2360 Res::Def(..) => {
2361 assert_eq!(
2362 path.segments.get(0).map(|seg| seg.ident.name),
2363 Some(kw::SelfUpper),
2364 "only expected incorrect resolution for `Self`"
2365 );
2366 Ty::new_error(
2367 self.tcx(),
2368 self.dcx().span_delayed_bug(span, "incorrect resolution for `Self`"),
2369 )
2370 }
2371 _ => span_bug!(span, "unexpected resolution: {:?}", path.res),
2372 }
2373 }
2374
2375 pub(crate) fn lower_ty_param(&self, hir_id: HirId) -> Ty<'tcx> {
2380 let tcx = self.tcx();
2381
2382 let ty = match tcx.named_bound_var(hir_id) {
2383 Some(rbv::ResolvedArg::LateBound(debruijn, index, def_id)) => {
2384 let br = ty::BoundTy {
2385 var: ty::BoundVar::from_u32(index),
2386 kind: ty::BoundTyKind::Param(def_id.to_def_id()),
2387 };
2388 Ty::new_bound(tcx, debruijn, br)
2389 }
2390 Some(rbv::ResolvedArg::EarlyBound(def_id)) => {
2391 let item_def_id = tcx.hir_ty_param_owner(def_id);
2392 let generics = tcx.generics_of(item_def_id);
2393 let index = generics.param_def_id_to_index[&def_id.to_def_id()];
2394 Ty::new_param(tcx, index, tcx.hir_ty_param_name(def_id))
2395 }
2396 Some(rbv::ResolvedArg::Error(guar)) => Ty::new_error(tcx, guar),
2397 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:?}"),
2398 };
2399 self.check_param_uses_if_mcg(ty, tcx.hir_span(hir_id), false)
2400 }
2401
2402 pub(crate) fn lower_const_param(&self, param_def_id: DefId, path_hir_id: HirId) -> Const<'tcx> {
2407 let tcx = self.tcx();
2408
2409 let ct = match tcx.named_bound_var(path_hir_id) {
2410 Some(rbv::ResolvedArg::EarlyBound(_)) => {
2411 let item_def_id = tcx.parent(param_def_id);
2414 let generics = tcx.generics_of(item_def_id);
2415 let index = generics.param_def_id_to_index[¶m_def_id];
2416 let name = tcx.item_name(param_def_id);
2417 ty::Const::new_param(tcx, ty::ParamConst::new(index, name))
2418 }
2419 Some(rbv::ResolvedArg::LateBound(debruijn, index, _)) => ty::Const::new_bound(
2420 tcx,
2421 debruijn,
2422 ty::BoundConst::new(ty::BoundVar::from_u32(index)),
2423 ),
2424 Some(rbv::ResolvedArg::Error(guar)) => ty::Const::new_error(tcx, guar),
2425 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),
2426 };
2427 self.check_param_uses_if_mcg(ct, tcx.hir_span(path_hir_id), false)
2428 }
2429
2430 #[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(2431u32),
::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:2483",
"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(2483u32),
::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:2488",
"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(2488u32),
::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")]
2432 pub fn lower_const_arg(&self, const_arg: &hir::ConstArg<'tcx>, ty: Ty<'tcx>) -> Const<'tcx> {
2433 let tcx = self.tcx();
2434
2435 if let hir::ConstArgKind::Anon(anon) = &const_arg.kind {
2436 if tcx.features().generic_const_parameter_types()
2445 && (ty.has_free_regions() || ty.has_erased_regions())
2446 {
2447 let e = self.dcx().span_err(
2448 const_arg.span,
2449 "anonymous constants with lifetimes in their type are not yet supported",
2450 );
2451 tcx.feed_anon_const_type(anon.def_id, ty::EarlyBinder::bind(Ty::new_error(tcx, e)));
2452 return ty::Const::new_error(tcx, e);
2453 }
2454 if ty.has_non_region_infer() {
2458 let e = self.dcx().span_err(
2459 const_arg.span,
2460 "anonymous constants with inferred types are not yet supported",
2461 );
2462 tcx.feed_anon_const_type(anon.def_id, ty::EarlyBinder::bind(Ty::new_error(tcx, e)));
2463 return ty::Const::new_error(tcx, e);
2464 }
2465 if ty.has_non_region_param() {
2468 let e = self.dcx().span_err(
2469 const_arg.span,
2470 "anonymous constants referencing generics are not yet supported",
2471 );
2472 tcx.feed_anon_const_type(anon.def_id, ty::EarlyBinder::bind(Ty::new_error(tcx, e)));
2473 return ty::Const::new_error(tcx, e);
2474 }
2475
2476 tcx.feed_anon_const_type(anon.def_id, ty::EarlyBinder::bind(ty));
2477 }
2478
2479 let hir_id = const_arg.hir_id;
2480 match const_arg.kind {
2481 hir::ConstArgKind::Tup(exprs) => self.lower_const_arg_tup(exprs, ty, const_arg.span),
2482 hir::ConstArgKind::Path(hir::QPath::Resolved(maybe_qself, path)) => {
2483 debug!(?maybe_qself, ?path);
2484 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
2485 self.lower_resolved_const_path(opt_self_ty, path, hir_id)
2486 }
2487 hir::ConstArgKind::Path(hir::QPath::TypeRelative(hir_self_ty, segment)) => {
2488 debug!(?hir_self_ty, ?segment);
2489 let self_ty = self.lower_ty(hir_self_ty);
2490 self.lower_type_relative_const_path(
2491 self_ty,
2492 hir_self_ty,
2493 segment,
2494 hir_id,
2495 const_arg.span,
2496 )
2497 .unwrap_or_else(|guar| Const::new_error(tcx, guar))
2498 }
2499 hir::ConstArgKind::Struct(qpath, inits) => {
2500 self.lower_const_arg_struct(hir_id, qpath, inits, const_arg.span)
2501 }
2502 hir::ConstArgKind::TupleCall(qpath, args) => {
2503 self.lower_const_arg_tuple_call(hir_id, qpath, args, const_arg.span)
2504 }
2505 hir::ConstArgKind::Array(array_expr) => self.lower_const_arg_array(array_expr, ty),
2506 hir::ConstArgKind::Anon(anon) => self.lower_const_arg_anon(anon),
2507 hir::ConstArgKind::Infer(()) => self.ct_infer(None, const_arg.span),
2508 hir::ConstArgKind::Error(e) => ty::Const::new_error(tcx, e),
2509 hir::ConstArgKind::Literal { lit, negated } => {
2510 self.lower_const_arg_literal(&lit, negated, ty, const_arg.span)
2511 }
2512 }
2513 }
2514
2515 fn lower_const_arg_array(
2516 &self,
2517 array_expr: &'tcx hir::ConstArgArrayExpr<'tcx>,
2518 ty: Ty<'tcx>,
2519 ) -> Const<'tcx> {
2520 let tcx = self.tcx();
2521
2522 let elem_ty = match ty.kind() {
2523 ty::Array(elem_ty, _) => elem_ty,
2524 ty::Error(e) => return Const::new_error(tcx, *e),
2525 _ => {
2526 let e = tcx
2527 .dcx()
2528 .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));
2529 return Const::new_error(tcx, e);
2530 }
2531 };
2532
2533 let elems = array_expr
2534 .elems
2535 .iter()
2536 .map(|elem| self.lower_const_arg(elem, *elem_ty))
2537 .collect::<Vec<_>>();
2538
2539 let valtree = ty::ValTree::from_branches(tcx, elems);
2540
2541 ty::Const::new_value(tcx, valtree, ty)
2542 }
2543
2544 fn lower_const_arg_tuple_call(
2545 &self,
2546 hir_id: HirId,
2547 qpath: hir::QPath<'tcx>,
2548 args: &'tcx [&'tcx hir::ConstArg<'tcx>],
2549 span: Span,
2550 ) -> Const<'tcx> {
2551 let tcx = self.tcx();
2552
2553 let non_adt_or_variant_res = || {
2554 let e = tcx.dcx().span_err(span, "tuple constructor with invalid base path");
2555 ty::Const::new_error(tcx, e)
2556 };
2557
2558 let ctor_const = match qpath {
2559 hir::QPath::Resolved(maybe_qself, path) => {
2560 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
2561 self.lower_resolved_const_path(opt_self_ty, path, hir_id)
2562 }
2563 hir::QPath::TypeRelative(hir_self_ty, segment) => {
2564 let self_ty = self.lower_ty(hir_self_ty);
2565 match self.lower_type_relative_const_path(
2566 self_ty,
2567 hir_self_ty,
2568 segment,
2569 hir_id,
2570 span,
2571 ) {
2572 Ok(c) => c,
2573 Err(_) => return non_adt_or_variant_res(),
2574 }
2575 }
2576 };
2577
2578 let Some(value) = ctor_const.try_to_value() else {
2579 return non_adt_or_variant_res();
2580 };
2581
2582 let (adt_def, adt_args, variant_did) = match value.ty.kind() {
2583 ty::FnDef(def_id, fn_args)
2584 if let DefKind::Ctor(CtorOf::Variant, _) = tcx.def_kind(*def_id) =>
2585 {
2586 let parent_did = tcx.parent(*def_id);
2587 let enum_did = tcx.parent(parent_did);
2588 (tcx.adt_def(enum_did), fn_args, parent_did)
2589 }
2590 ty::FnDef(def_id, fn_args)
2591 if let DefKind::Ctor(CtorOf::Struct, _) = tcx.def_kind(*def_id) =>
2592 {
2593 let parent_did = tcx.parent(*def_id);
2594 (tcx.adt_def(parent_did), fn_args, parent_did)
2595 }
2596 _ => {
2597 let e = self.dcx().span_err(
2598 span,
2599 "complex const arguments must be placed inside of a `const` block",
2600 );
2601 return Const::new_error(tcx, e);
2602 }
2603 };
2604
2605 let variant_def = adt_def.variant_with_id(variant_did);
2606 let variant_idx = adt_def.variant_index_with_id(variant_did).as_u32();
2607
2608 if args.len() != variant_def.fields.len() {
2609 let e = tcx.dcx().span_err(
2610 span,
2611 ::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!(
2612 "tuple constructor has {} arguments but {} were provided",
2613 variant_def.fields.len(),
2614 args.len()
2615 ),
2616 );
2617 return ty::Const::new_error(tcx, e);
2618 }
2619
2620 let fields = variant_def
2621 .fields
2622 .iter()
2623 .zip(args)
2624 .map(|(field_def, arg)| {
2625 self.lower_const_arg(
2626 arg,
2627 tcx.type_of(field_def.did).instantiate(tcx, adt_args).skip_norm_wip(),
2628 )
2629 })
2630 .collect::<Vec<_>>();
2631
2632 let opt_discr_const = if adt_def.is_enum() {
2633 let valtree = ty::ValTree::from_scalar_int(tcx, variant_idx.into());
2634 Some(ty::Const::new_value(tcx, valtree, tcx.types.u32))
2635 } else {
2636 None
2637 };
2638
2639 let valtree = ty::ValTree::from_branches(tcx, opt_discr_const.into_iter().chain(fields));
2640 let adt_ty = Ty::new_adt(tcx, adt_def, adt_args);
2641 ty::Const::new_value(tcx, valtree, adt_ty)
2642 }
2643
2644 fn lower_const_arg_tup(
2645 &self,
2646 exprs: &'tcx [&'tcx hir::ConstArg<'tcx>],
2647 ty: Ty<'tcx>,
2648 span: Span,
2649 ) -> Const<'tcx> {
2650 let tcx = self.tcx();
2651
2652 let tys = match ty.kind() {
2653 ty::Tuple(tys) => tys,
2654 ty::Error(e) => return Const::new_error(tcx, *e),
2655 _ => {
2656 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));
2657 return Const::new_error(tcx, e);
2658 }
2659 };
2660
2661 let exprs = exprs
2662 .iter()
2663 .zip(tys.iter())
2664 .map(|(expr, ty)| self.lower_const_arg(expr, ty))
2665 .collect::<Vec<_>>();
2666
2667 let valtree = ty::ValTree::from_branches(tcx, exprs);
2668 ty::Const::new_value(tcx, valtree, ty)
2669 }
2670
2671 fn lower_const_arg_struct(
2672 &self,
2673 hir_id: HirId,
2674 qpath: hir::QPath<'tcx>,
2675 inits: &'tcx [&'tcx hir::ConstArgExprField<'tcx>],
2676 span: Span,
2677 ) -> Const<'tcx> {
2678 let tcx = self.tcx();
2681
2682 let non_adt_or_variant_res = || {
2683 let e = tcx.dcx().span_err(span, "struct expression with invalid base path");
2684 ty::Const::new_error(tcx, e)
2685 };
2686
2687 let ResolvedStructPath { res: opt_res, ty } =
2688 self.lower_path_for_struct_expr(qpath, span, hir_id);
2689
2690 let variant_did = match qpath {
2691 hir::QPath::Resolved(maybe_qself, path) => {
2692 {
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:2692",
"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(2692u32),
::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);
2693 let variant_did = match path.res {
2694 Res::Def(DefKind::Variant | DefKind::Struct, did) => did,
2695 _ => return non_adt_or_variant_res(),
2696 };
2697
2698 variant_did
2699 }
2700 hir::QPath::TypeRelative(hir_self_ty, segment) => {
2701 {
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:2701",
"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(2701u32),
::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);
2702
2703 let res_def_id = match opt_res {
2704 Ok(r)
2705 if #[allow(non_exhaustive_omitted_patterns)] match tcx.def_kind(r.def_id()) {
DefKind::Variant | DefKind::Struct => true,
_ => false,
}matches!(
2706 tcx.def_kind(r.def_id()),
2707 DefKind::Variant | DefKind::Struct
2708 ) =>
2709 {
2710 r.def_id()
2711 }
2712 Ok(_) => return non_adt_or_variant_res(),
2713 Err(e) => return ty::Const::new_error(tcx, e),
2714 };
2715
2716 res_def_id
2717 }
2718 };
2719
2720 let ty::Adt(adt_def, adt_args) = ty.kind() else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
2721
2722 let variant_def = adt_def.variant_with_id(variant_did);
2723 let variant_idx = adt_def.variant_index_with_id(variant_did).as_u32();
2724
2725 let fields = variant_def
2726 .fields
2727 .iter()
2728 .map(|field_def| {
2729 let mut init_expr =
2732 inits.iter().filter(|init_expr| init_expr.field.name == field_def.name);
2733
2734 match init_expr.next() {
2735 Some(expr) => {
2736 if let Some(expr) = init_expr.next() {
2737 let e = tcx.dcx().span_err(
2738 expr.span,
2739 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("struct expression with multiple initialisers for `{0}`",
field_def.name))
})format!(
2740 "struct expression with multiple initialisers for `{}`",
2741 field_def.name,
2742 ),
2743 );
2744 return ty::Const::new_error(tcx, e);
2745 }
2746
2747 self.lower_const_arg(
2748 expr.expr,
2749 tcx.type_of(field_def.did).instantiate(tcx, adt_args).skip_norm_wip(),
2750 )
2751 }
2752 None => {
2753 let e = tcx.dcx().span_err(
2754 span,
2755 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("struct expression with missing field initialiser for `{0}`",
field_def.name))
})format!(
2756 "struct expression with missing field initialiser for `{}`",
2757 field_def.name
2758 ),
2759 );
2760 ty::Const::new_error(tcx, e)
2761 }
2762 }
2763 })
2764 .collect::<Vec<_>>();
2765
2766 let opt_discr_const = if adt_def.is_enum() {
2767 let valtree = ty::ValTree::from_scalar_int(tcx, variant_idx.into());
2768 Some(ty::Const::new_value(tcx, valtree, tcx.types.u32))
2769 } else {
2770 None
2771 };
2772
2773 let valtree = ty::ValTree::from_branches(tcx, opt_discr_const.into_iter().chain(fields));
2774 ty::Const::new_value(tcx, valtree, ty)
2775 }
2776
2777 pub fn lower_path_for_struct_expr(
2778 &self,
2779 qpath: hir::QPath<'tcx>,
2780 path_span: Span,
2781 hir_id: HirId,
2782 ) -> ResolvedStructPath<'tcx> {
2783 match qpath {
2784 hir::QPath::Resolved(ref maybe_qself, path) => {
2785 let self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
2786 let ty = self.lower_resolved_ty_path(self_ty, path, hir_id, PermitVariants::Yes);
2787 ResolvedStructPath { res: Ok(path.res), ty }
2788 }
2789 hir::QPath::TypeRelative(hir_self_ty, segment) => {
2790 let self_ty = self.lower_ty(hir_self_ty);
2791
2792 let result = self.lower_type_relative_ty_path(
2793 self_ty,
2794 hir_self_ty,
2795 segment,
2796 hir_id,
2797 path_span,
2798 PermitVariants::Yes,
2799 );
2800 let ty = result
2801 .map(|(ty, _, _)| ty)
2802 .unwrap_or_else(|guar| Ty::new_error(self.tcx(), guar));
2803
2804 ResolvedStructPath {
2805 res: result.map(|(_, kind, def_id)| Res::Def(kind, def_id)),
2806 ty,
2807 }
2808 }
2809 }
2810 }
2811
2812 fn lower_resolved_const_path(
2814 &self,
2815 opt_self_ty: Option<Ty<'tcx>>,
2816 path: &hir::Path<'tcx>,
2817 hir_id: HirId,
2818 ) -> Const<'tcx> {
2819 let tcx = self.tcx();
2820 let span = path.span;
2821 let ct = match path.res {
2822 Res::Def(DefKind::ConstParam, def_id) => {
2823 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);
2824 let _ = self.prohibit_generic_args(
2825 path.segments.iter(),
2826 GenericsArgsErrExtend::Param(def_id),
2827 );
2828 self.lower_const_param(def_id, hir_id)
2829 }
2830 Res::Def(DefKind::Const { .. }, did) => {
2831 if let Err(guar) = self.require_type_const_attribute(did, span) {
2832 return Const::new_error(self.tcx(), guar);
2833 }
2834
2835 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);
2836 let [leading_segments @ .., segment] = path.segments else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
2837 let _ = self
2838 .prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
2839 let args = self.lower_generic_args_of_path_segment(span, did, segment);
2840 ty::Const::new_unevaluated(tcx, ty::UnevaluatedConst::new(did, args))
2841 }
2842 Res::Def(DefKind::Ctor(ctor_of, CtorKind::Const), did) => {
2843 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);
2844 let [leading_segments @ .., segment] = path.segments else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
2845 let _ = self
2846 .prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
2847
2848 let parent_did = tcx.parent(did);
2849 let generics_did = match ctor_of {
2850 CtorOf::Variant => tcx.parent(parent_did),
2851 CtorOf::Struct => parent_did,
2852 };
2853 let args = self.lower_generic_args_of_path_segment(span, generics_did, segment);
2854
2855 self.construct_const_ctor_value(did, ctor_of, args)
2856 }
2857 Res::Def(DefKind::Ctor(_, CtorKind::Fn), did) => {
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 parent_did = tcx.parent(did);
2863 let generics_did = if let DefKind::Ctor(CtorOf::Variant, _) = tcx.def_kind(did) {
2864 tcx.parent(parent_did)
2865 } else {
2866 parent_did
2867 };
2868 let args = self.lower_generic_args_of_path_segment(span, generics_did, segment);
2869 ty::Const::zero_sized(tcx, Ty::new_fn_def(tcx, did, args))
2870 }
2871 Res::Def(DefKind::AssocConst { .. }, did) => {
2872 let trait_segment = if let [modules @ .., trait_, _item] = path.segments {
2873 let _ = self.prohibit_generic_args(modules.iter(), GenericsArgsErrExtend::None);
2874 Some(trait_)
2875 } else {
2876 None
2877 };
2878 self.lower_resolved_assoc_const_path(
2879 span,
2880 opt_self_ty,
2881 did,
2882 trait_segment,
2883 path.segments.last().unwrap(),
2884 )
2885 .unwrap_or_else(|guar| Const::new_error(tcx, guar))
2886 }
2887 Res::Def(DefKind::Static { .. }, _) => {
2888 ::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")
2889 }
2890 Res::Def(DefKind::Fn | DefKind::AssocFn, did) => {
2892 self.dcx().span_delayed_bug(span, "function items cannot be used as const args");
2893 let args = self.lower_generic_args_of_path_segment(
2894 span,
2895 did,
2896 path.segments.last().unwrap(),
2897 );
2898 ty::Const::zero_sized(tcx, Ty::new_fn_def(tcx, did, args))
2899 }
2900
2901 res @ (Res::Def(
2904 DefKind::Mod
2905 | DefKind::Enum
2906 | DefKind::Variant
2907 | DefKind::Struct
2908 | DefKind::OpaqueTy
2909 | DefKind::TyAlias
2910 | DefKind::TraitAlias
2911 | DefKind::AssocTy
2912 | DefKind::Union
2913 | DefKind::Trait
2914 | DefKind::ForeignTy
2915 | DefKind::TyParam
2916 | DefKind::Macro(_)
2917 | DefKind::LifetimeParam
2918 | DefKind::Use
2919 | DefKind::ForeignMod
2920 | DefKind::AnonConst
2921 | DefKind::InlineConst
2922 | DefKind::Field
2923 | DefKind::Impl { .. }
2924 | DefKind::Closure
2925 | DefKind::ExternCrate
2926 | DefKind::GlobalAsm
2927 | DefKind::SyntheticCoroutineBody,
2928 _,
2929 )
2930 | Res::PrimTy(_)
2931 | Res::SelfTyParam { .. }
2932 | Res::SelfTyAlias { .. }
2933 | Res::SelfCtor(_)
2934 | Res::Local(_)
2935 | Res::ToolMod
2936 | Res::OpenMod(..)
2937 | Res::NonMacroAttr(_)
2938 | Res::Err) => Const::new_error_with_message(
2939 tcx,
2940 span,
2941 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("invalid Res {0:?} for const path",
res))
})format!("invalid Res {res:?} for const path"),
2942 ),
2943 };
2944 self.check_param_uses_if_mcg(ct, span, false)
2945 }
2946
2947 #[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(2948u32),
::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:2953",
"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(2953u32),
::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")]
2949 fn lower_const_arg_anon(&self, anon: &AnonConst) -> Const<'tcx> {
2950 let tcx = self.tcx();
2951
2952 let expr = &tcx.hir_body(anon.body).value;
2953 debug!(?expr);
2954
2955 let ty = tcx.type_of(anon.def_id).instantiate_identity().skip_norm_wip();
2959
2960 match self.try_lower_anon_const_lit(ty, expr) {
2961 Some(v) => v,
2962 None => ty::Const::new_unevaluated(
2963 tcx,
2964 ty::UnevaluatedConst {
2965 def: anon.def_id.to_def_id(),
2966 args: ty::GenericArgs::identity_for_item(tcx, anon.def_id.to_def_id()),
2967 },
2968 ),
2969 }
2970 }
2971
2972 #[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(2972u32),
::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")]
2973 fn lower_const_arg_literal(
2974 &self,
2975 kind: &LitKind,
2976 neg: bool,
2977 ty: Ty<'tcx>,
2978 span: Span,
2979 ) -> Const<'tcx> {
2980 let tcx = self.tcx();
2981
2982 let ty = if !ty.has_infer() { Some(ty) } else { None };
2983
2984 if let LitKind::Err(guar) = *kind {
2985 return ty::Const::new_error(tcx, guar);
2986 }
2987 let input = LitToConstInput { lit: *kind, ty, neg };
2988 match tcx.at(span).lit_to_const(input) {
2989 Some(value) => ty::Const::new_value(tcx, value.valtree, value.ty),
2990 None => {
2991 let e = tcx.dcx().span_err(span, "type annotations needed for the literal");
2992 ty::Const::new_error(tcx, e)
2993 }
2994 }
2995 }
2996
2997 #[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(2997u32),
::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")]
2998 fn try_lower_anon_const_lit(
2999 &self,
3000 ty: Ty<'tcx>,
3001 expr: &'tcx hir::Expr<'tcx>,
3002 ) -> Option<Const<'tcx>> {
3003 let tcx = self.tcx();
3004
3005 let expr = match &expr.kind {
3008 hir::ExprKind::Block(block, _) if block.stmts.is_empty() && block.expr.is_some() => {
3009 block.expr.as_ref().unwrap()
3010 }
3011 _ => expr,
3012 };
3013
3014 let lit_input = match expr.kind {
3015 hir::ExprKind::Lit(lit) => {
3016 Some(LitToConstInput { lit: lit.node, ty: Some(ty), neg: false })
3017 }
3018 hir::ExprKind::Unary(hir::UnOp::Neg, expr) => match expr.kind {
3019 hir::ExprKind::Lit(lit) => {
3020 Some(LitToConstInput { lit: lit.node, ty: Some(ty), neg: true })
3021 }
3022 _ => None,
3023 },
3024 _ => None,
3025 };
3026
3027 lit_input.and_then(|l| {
3028 if const_lit_matches_ty(tcx, &l.lit, ty, l.neg) {
3029 tcx.at(expr.span)
3030 .lit_to_const(l)
3031 .map(|value| ty::Const::new_value(tcx, value.valtree, value.ty))
3032 } else {
3033 None
3034 }
3035 })
3036 }
3037
3038 fn require_type_const_attribute(
3039 &self,
3040 def_id: DefId,
3041 span: Span,
3042 ) -> Result<(), ErrorGuaranteed> {
3043 let tcx = self.tcx();
3044 if tcx.is_type_const(def_id) {
3045 Ok(())
3046 } else {
3047 let mut err = self.dcx().struct_span_err(
3048 span,
3049 "use of `const` in the type system not defined as `type const`",
3050 );
3051 if def_id.is_local() {
3052 let name = tcx.def_path_str(def_id);
3053 err.span_suggestion_verbose(
3054 tcx.def_span(def_id).shrink_to_lo(),
3055 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("add `type` before `const` for `{0}`",
name))
})format!("add `type` before `const` for `{name}`"),
3056 ::alloc::__export::must_use({ ::alloc::fmt::format(format_args!("type ")) })format!("type "),
3057 Applicability::MaybeIncorrect,
3058 );
3059 } else {
3060 err.note("only consts marked defined as `type const` may be used in types");
3061 }
3062 Err(err.emit())
3063 }
3064 }
3065
3066 fn lower_delegation_ty(&self, infer: hir::InferDelegation<'tcx>) -> Ty<'tcx> {
3067 match infer {
3068 hir::InferDelegation::DefId(def_id) => {
3069 self.tcx().type_of(def_id).instantiate_identity().skip_norm_wip()
3070 }
3071 rustc_hir::InferDelegation::Sig(_, idx) => {
3072 let delegation_sig = self.tcx().inherit_sig_for_delegation_item(self.item_def_id());
3073
3074 match idx {
3075 hir::InferDelegationSig::Input(idx) => delegation_sig[idx],
3076 hir::InferDelegationSig::Output { .. } => *delegation_sig.last().unwrap(),
3077 }
3078 }
3079 }
3080 }
3081
3082 x;#[instrument(level = "debug", skip(self), ret)]
3084 pub fn lower_ty(&self, hir_ty: &hir::Ty<'tcx>) -> Ty<'tcx> {
3085 let tcx = self.tcx();
3086
3087 let result_ty = match &hir_ty.kind {
3088 hir::TyKind::InferDelegation(infer) => self.lower_delegation_ty(*infer),
3089 hir::TyKind::Slice(ty) => Ty::new_slice(tcx, self.lower_ty(ty)),
3090 hir::TyKind::Ptr(mt) => Ty::new_ptr(tcx, self.lower_ty(mt.ty), mt.mutbl),
3091 hir::TyKind::Ref(region, mt) => {
3092 let r = self.lower_lifetime(region, RegionInferReason::Reference);
3093 debug!(?r);
3094 let t = self.lower_ty(mt.ty);
3095 Ty::new_ref(tcx, r, t, mt.mutbl)
3096 }
3097 hir::TyKind::Never => tcx.types.never,
3098 hir::TyKind::Tup(fields) => {
3099 Ty::new_tup_from_iter(tcx, fields.iter().map(|t| self.lower_ty(t)))
3100 }
3101 hir::TyKind::FnPtr(bf) => {
3102 check_c_variadic_abi(tcx, bf.decl, bf.abi, hir_ty.span);
3103
3104 Ty::new_fn_ptr(
3105 tcx,
3106 self.lower_fn_ty(hir_ty.hir_id, bf.safety, bf.abi, bf.decl, None, Some(hir_ty)),
3107 )
3108 }
3109 hir::TyKind::UnsafeBinder(binder) => Ty::new_unsafe_binder(
3110 tcx,
3111 ty::Binder::bind_with_vars(
3112 self.lower_ty(binder.inner_ty),
3113 tcx.late_bound_vars(hir_ty.hir_id),
3114 ),
3115 ),
3116 hir::TyKind::TraitObject(bounds, tagged_ptr) => {
3117 let lifetime = tagged_ptr.pointer();
3118 let syntax = tagged_ptr.tag();
3119 self.lower_trait_object_ty(hir_ty.span, hir_ty.hir_id, bounds, lifetime, syntax)
3120 }
3121 hir::TyKind::Path(hir::QPath::Resolved(_, path))
3125 if path.segments.last().and_then(|segment| segment.args).is_some_and(|args| {
3126 matches!(args.parenthesized, hir::GenericArgsParentheses::ReturnTypeNotation)
3127 }) =>
3128 {
3129 let guar = self
3130 .dcx()
3131 .emit_err(BadReturnTypeNotation { span: hir_ty.span, suggestion: None });
3132 Ty::new_error(tcx, guar)
3133 }
3134 hir::TyKind::Path(hir::QPath::Resolved(maybe_qself, path)) => {
3135 debug!(?maybe_qself, ?path);
3136 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
3137 self.lower_resolved_ty_path(opt_self_ty, path, hir_ty.hir_id, PermitVariants::No)
3138 }
3139 &hir::TyKind::OpaqueDef(opaque_ty) => {
3140 let in_trait = match opaque_ty.origin {
3144 hir::OpaqueTyOrigin::FnReturn {
3145 parent,
3146 in_trait_or_impl: Some(hir::RpitContext::Trait),
3147 ..
3148 }
3149 | hir::OpaqueTyOrigin::AsyncFn {
3150 parent,
3151 in_trait_or_impl: Some(hir::RpitContext::Trait),
3152 ..
3153 } => Some(parent),
3154 hir::OpaqueTyOrigin::FnReturn {
3155 in_trait_or_impl: None | Some(hir::RpitContext::TraitImpl),
3156 ..
3157 }
3158 | hir::OpaqueTyOrigin::AsyncFn {
3159 in_trait_or_impl: None | Some(hir::RpitContext::TraitImpl),
3160 ..
3161 }
3162 | hir::OpaqueTyOrigin::TyAlias { .. } => None,
3163 };
3164
3165 self.lower_opaque_ty(opaque_ty.def_id, in_trait)
3166 }
3167 hir::TyKind::TraitAscription(hir_bounds) => {
3168 let self_ty = self.ty_infer(None, hir_ty.span);
3171 let mut bounds = Vec::new();
3172 self.lower_bounds(
3173 self_ty,
3174 hir_bounds.iter(),
3175 &mut bounds,
3176 ty::List::empty(),
3177 PredicateFilter::All,
3178 OverlappingAsssocItemConstraints::Allowed,
3179 );
3180 self.add_implicit_sizedness_bounds(
3181 &mut bounds,
3182 self_ty,
3183 hir_bounds,
3184 ImpliedBoundsContext::AssociatedTypeOrImplTrait,
3185 hir_ty.span,
3186 );
3187 self.register_trait_ascription_bounds(bounds, hir_ty.hir_id, hir_ty.span);
3188 self_ty
3189 }
3190 hir::TyKind::Path(hir::QPath::TypeRelative(hir_self_ty, segment))
3194 if segment.args.is_some_and(|args| {
3195 matches!(args.parenthesized, hir::GenericArgsParentheses::ReturnTypeNotation)
3196 }) =>
3197 {
3198 let guar = if let hir::Node::LetStmt(stmt) = tcx.parent_hir_node(hir_ty.hir_id)
3199 && let None = stmt.init
3200 && let hir::TyKind::Path(hir::QPath::Resolved(_, self_ty_path)) =
3201 hir_self_ty.kind
3202 && let Res::Def(DefKind::Enum | DefKind::Struct | DefKind::Union, def_id) =
3203 self_ty_path.res
3204 && let Some(_) = tcx
3205 .inherent_impls(def_id)
3206 .iter()
3207 .flat_map(|imp| {
3208 tcx.associated_items(*imp).filter_by_name_unhygienic(segment.ident.name)
3209 })
3210 .filter(|assoc| {
3211 matches!(assoc.kind, ty::AssocKind::Fn { has_self: false, .. })
3212 })
3213 .next()
3214 {
3215 let err = tcx
3217 .dcx()
3218 .struct_span_err(
3219 hir_ty.span,
3220 "expected type, found associated function call",
3221 )
3222 .with_span_suggestion_verbose(
3223 stmt.pat.span.between(hir_ty.span),
3224 "use `=` if you meant to assign",
3225 " = ".to_string(),
3226 Applicability::MaybeIncorrect,
3227 );
3228 self.dcx().try_steal_replace_and_emit_err(
3229 hir_ty.span,
3230 StashKey::ReturnTypeNotation,
3231 err,
3232 )
3233 } else if let hir::Node::LetStmt(stmt) = tcx.parent_hir_node(hir_ty.hir_id)
3234 && let None = stmt.init
3235 && let hir::TyKind::Path(hir::QPath::Resolved(_, self_ty_path)) =
3236 hir_self_ty.kind
3237 && let Res::PrimTy(_) = self_ty_path.res
3238 && self.dcx().has_stashed_diagnostic(hir_ty.span, StashKey::ReturnTypeNotation)
3239 {
3240 let err = tcx
3243 .dcx()
3244 .struct_span_err(
3245 hir_ty.span,
3246 "expected type, found associated function call",
3247 )
3248 .with_span_suggestion_verbose(
3249 stmt.pat.span.between(hir_ty.span),
3250 "use `=` if you meant to assign",
3251 " = ".to_string(),
3252 Applicability::MaybeIncorrect,
3253 );
3254 self.dcx().try_steal_replace_and_emit_err(
3255 hir_ty.span,
3256 StashKey::ReturnTypeNotation,
3257 err,
3258 )
3259 } else {
3260 let suggestion = if self
3261 .dcx()
3262 .has_stashed_diagnostic(hir_ty.span, StashKey::ReturnTypeNotation)
3263 {
3264 Some(segment.ident.span.shrink_to_hi().with_hi(hir_ty.span.hi()))
3270 } else {
3271 None
3272 };
3273 let err = self
3274 .dcx()
3275 .create_err(BadReturnTypeNotation { span: hir_ty.span, suggestion });
3276 self.dcx().try_steal_replace_and_emit_err(
3277 hir_ty.span,
3278 StashKey::ReturnTypeNotation,
3279 err,
3280 )
3281 };
3282 Ty::new_error(tcx, guar)
3283 }
3284 hir::TyKind::Path(hir::QPath::TypeRelative(hir_self_ty, segment)) => {
3285 debug!(?hir_self_ty, ?segment);
3286 let self_ty = self.lower_ty(hir_self_ty);
3287 self.lower_type_relative_ty_path(
3288 self_ty,
3289 hir_self_ty,
3290 segment,
3291 hir_ty.hir_id,
3292 hir_ty.span,
3293 PermitVariants::No,
3294 )
3295 .map(|(ty, _, _)| ty)
3296 .unwrap_or_else(|guar| Ty::new_error(tcx, guar))
3297 }
3298 hir::TyKind::Array(ty, length) => {
3299 let length = self.lower_const_arg(length, tcx.types.usize);
3300 Ty::new_array_with_const_len(tcx, self.lower_ty(ty), length)
3301 }
3302 hir::TyKind::Infer(()) => {
3303 self.ty_infer(None, hir_ty.span)
3308 }
3309 hir::TyKind::Pat(ty, pat) => {
3310 let ty_span = ty.span;
3311 let ty = self.lower_ty(ty);
3312 let pat_ty = match self.lower_pat_ty_pat(ty, ty_span, pat) {
3313 Ok(kind) => Ty::new_pat(tcx, ty, tcx.mk_pat(kind)),
3314 Err(guar) => Ty::new_error(tcx, guar),
3315 };
3316 self.record_ty(pat.hir_id, ty, pat.span);
3317 pat_ty
3318 }
3319 hir::TyKind::FieldOf(ty, hir::TyFieldPath { variant, field }) => self.lower_field_of(
3320 self.lower_ty(ty),
3321 self.item_def_id(),
3322 ty.span,
3323 hir_ty.hir_id,
3324 *variant,
3325 *field,
3326 ),
3327 hir::TyKind::Err(guar) => Ty::new_error(tcx, *guar),
3328 };
3329
3330 self.record_ty(hir_ty.hir_id, result_ty, hir_ty.span);
3331 result_ty
3332 }
3333
3334 fn lower_pat_ty_pat(
3335 &self,
3336 ty: Ty<'tcx>,
3337 ty_span: Span,
3338 pat: &hir::TyPat<'tcx>,
3339 ) -> Result<ty::PatternKind<'tcx>, ErrorGuaranteed> {
3340 let tcx = self.tcx();
3341 match pat.kind {
3342 hir::TyPatKind::Range(start, end) => {
3343 match ty.kind() {
3344 ty::Int(_) | ty::Uint(_) | ty::Char => {
3347 let start = self.lower_const_arg(start, ty);
3348 let end = self.lower_const_arg(end, ty);
3349 Ok(ty::PatternKind::Range { start, end })
3350 }
3351 _ => Err(self
3352 .dcx()
3353 .span_delayed_bug(ty_span, "invalid base type for range pattern")),
3354 }
3355 }
3356 hir::TyPatKind::NotNull => Ok(ty::PatternKind::NotNull),
3357 hir::TyPatKind::Or(patterns) => {
3358 self.tcx()
3359 .mk_patterns_from_iter(patterns.iter().map(|pat| {
3360 self.lower_pat_ty_pat(ty, ty_span, pat).map(|pat| tcx.mk_pat(pat))
3361 }))
3362 .map(ty::PatternKind::Or)
3363 }
3364 hir::TyPatKind::Err(e) => Err(e),
3365 }
3366 }
3367
3368 fn lower_field_of(
3369 &self,
3370 ty: Ty<'tcx>,
3371 item_def_id: LocalDefId,
3372 ty_span: Span,
3373 hir_id: HirId,
3374 variant: Option<Ident>,
3375 field: Ident,
3376 ) -> Ty<'tcx> {
3377 let dcx = self.dcx();
3378 let tcx = self.tcx();
3379 match ty.kind() {
3380 ty::Adt(def, _) => {
3381 let base_did = def.did();
3382 let kind_name = tcx.def_descr(base_did);
3383 let (variant_idx, variant) = if def.is_enum() {
3384 let Some(variant) = variant else {
3385 let err = dcx
3386 .create_err(NoVariantNamed { span: field.span, ident: field, ty })
3387 .with_span_help(
3388 field.span.shrink_to_lo(),
3389 "you might be missing a variant here: `Variant.`",
3390 )
3391 .emit();
3392 return Ty::new_error(tcx, err);
3393 };
3394
3395 if let Some(res) = def
3396 .variants()
3397 .iter_enumerated()
3398 .find(|(_, f)| f.ident(tcx).normalize_to_macros_2_0() == variant)
3399 {
3400 res
3401 } else {
3402 let err = dcx
3403 .create_err(NoVariantNamed { span: variant.span, ident: variant, ty })
3404 .emit();
3405 return Ty::new_error(tcx, err);
3406 }
3407 } else {
3408 if let Some(variant) = variant {
3409 let adt_path = tcx.def_path_str(base_did);
3410 {
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!(
3411 dcx,
3412 variant.span,
3413 E0609,
3414 "{kind_name} `{adt_path}` does not have any variants",
3415 )
3416 .with_span_label(variant.span, "variant unknown")
3417 .emit();
3418 }
3419 (FIRST_VARIANT, def.non_enum_variant())
3420 };
3421 let block = tcx.local_def_id_to_hir_id(item_def_id);
3422 let (ident, def_scope) = tcx.adjust_ident_and_get_scope(field, def.did(), block);
3423 if let Some((field_idx, field)) = variant
3424 .fields
3425 .iter_enumerated()
3426 .find(|(_, f)| f.ident(tcx).normalize_to_macros_2_0() == ident)
3427 {
3428 if field.vis.is_accessible_from(def_scope, tcx) {
3429 tcx.check_stability(field.did, Some(hir_id), ident.span, None);
3430 } else {
3431 let adt_path = tcx.def_path_str(base_did);
3432 {
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!(
3433 dcx,
3434 ident.span,
3435 E0616,
3436 "field `{ident}` of {kind_name} `{adt_path}` is private",
3437 )
3438 .with_span_label(ident.span, "private field")
3439 .emit();
3440 }
3441 Ty::new_field_representing_type(tcx, ty, variant_idx, field_idx)
3442 } else {
3443 let err =
3444 dcx.create_err(NoFieldOnType { span: ident.span, field: ident, ty }).emit();
3445 Ty::new_error(tcx, err)
3446 }
3447 }
3448 ty::Tuple(tys) => {
3449 let index = match field.as_str().parse::<usize>() {
3450 Ok(idx) => idx,
3451 Err(_) => {
3452 let err =
3453 dcx.create_err(NoFieldOnType { span: field.span, field, ty }).emit();
3454 return Ty::new_error(tcx, err);
3455 }
3456 };
3457 if field.name != sym::integer(index) {
3458 ::rustc_middle::util::bug::bug_fmt(format_args!("we parsed above, but now not equal?"));bug!("we parsed above, but now not equal?");
3459 }
3460 if tys.get(index).is_some() {
3461 Ty::new_field_representing_type(tcx, ty, FIRST_VARIANT, index.into())
3462 } else {
3463 let err = dcx.create_err(NoFieldOnType { span: field.span, field, ty }).emit();
3464 Ty::new_error(tcx, err)
3465 }
3466 }
3467 ty::Alias(..) => Ty::new_error(
3480 tcx,
3481 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}`")),
3482 ),
3483 ty::Error(err) => Ty::new_error(tcx, *err),
3484 ty::Bool
3485 | ty::Char
3486 | ty::Int(_)
3487 | ty::Uint(_)
3488 | ty::Float(_)
3489 | ty::Foreign(_)
3490 | ty::Str
3491 | ty::RawPtr(_, _)
3492 | ty::Ref(_, _, _)
3493 | ty::FnDef(_, _)
3494 | ty::FnPtr(_, _)
3495 | ty::UnsafeBinder(_)
3496 | ty::Dynamic(_, _)
3497 | ty::Closure(_, _)
3498 | ty::CoroutineClosure(_, _)
3499 | ty::Coroutine(_, _)
3500 | ty::CoroutineWitness(_, _)
3501 | ty::Never
3502 | ty::Param(_)
3503 | ty::Bound(_, _)
3504 | ty::Placeholder(_)
3505 | ty::Slice(..) => Ty::new_error(
3506 tcx,
3507 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")),
3508 ),
3509 ty::Infer(_) => Ty::new_error(
3510 tcx,
3511 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")),
3512 ),
3513 ty::Array(..) | ty::Pat(..) => Ty::new_error(
3515 tcx,
3516 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!`")),
3517 ),
3518 }
3519 }
3520
3521 x;#[instrument(level = "debug", skip(self), ret)]
3523 fn lower_opaque_ty(&self, def_id: LocalDefId, in_trait: Option<LocalDefId>) -> Ty<'tcx> {
3524 let tcx = self.tcx();
3525
3526 let lifetimes = tcx.opaque_captured_lifetimes(def_id);
3527 debug!(?lifetimes);
3528
3529 let def_id = if let Some(parent_def_id) = in_trait {
3533 *tcx.associated_types_for_impl_traits_in_associated_fn(parent_def_id.to_def_id())
3534 .iter()
3535 .find(|rpitit| match tcx.opt_rpitit_info(**rpitit) {
3536 Some(ty::ImplTraitInTraitData::Trait { opaque_def_id, .. }) => {
3537 opaque_def_id.expect_local() == def_id
3538 }
3539 _ => unreachable!(),
3540 })
3541 .unwrap()
3542 } else {
3543 def_id.to_def_id()
3544 };
3545
3546 let generics = tcx.generics_of(def_id);
3547 debug!(?generics);
3548
3549 let offset = generics.count() - lifetimes.len();
3553
3554 let args = ty::GenericArgs::for_item(tcx, def_id, |param, _| {
3555 if let Some(i) = (param.index as usize).checked_sub(offset) {
3556 let (lifetime, _) = lifetimes[i];
3557 self.lower_resolved_lifetime(lifetime).into()
3559 } else {
3560 tcx.mk_param_from_def(param)
3561 }
3562 });
3563 debug!(?args);
3564
3565 if in_trait.is_some() {
3566 Ty::new_projection_from_args(tcx, def_id, args)
3567 } else {
3568 Ty::new_opaque(tcx, def_id, args)
3569 }
3570 }
3571
3572 x;#[instrument(level = "debug", skip(self, hir_id, safety, abi, decl, generics, hir_ty), ret)]
3574 pub fn lower_fn_ty(
3575 &self,
3576 hir_id: HirId,
3577 safety: hir::Safety,
3578 abi: rustc_abi::ExternAbi,
3579 decl: &hir::FnDecl<'tcx>,
3580 generics: Option<&hir::Generics<'_>>,
3581 hir_ty: Option<&hir::Ty<'_>>,
3582 ) -> ty::PolyFnSig<'tcx> {
3583 let tcx = self.tcx();
3584 let bound_vars = tcx.late_bound_vars(hir_id);
3585 debug!(?bound_vars);
3586
3587 let (input_tys, output_ty) = self.lower_fn_sig(decl, generics, hir_id, hir_ty);
3588
3589 debug!(?output_ty);
3590
3591 let fn_sig_kind = FnSigKind::default()
3592 .set_abi(abi)
3593 .set_safe(safety.is_safe())
3594 .set_c_variadic(decl.fn_decl_kind.c_variadic());
3595 let fn_ty = tcx.mk_fn_sig(input_tys, output_ty, fn_sig_kind);
3596 let fn_ptr_ty = ty::Binder::bind_with_vars(fn_ty, bound_vars);
3597
3598 if let hir::Node::Ty(hir::Ty { kind: hir::TyKind::FnPtr(fn_ptr_ty), span, .. }) =
3599 tcx.hir_node(hir_id)
3600 {
3601 check_abi(tcx, hir_id, *span, fn_ptr_ty.abi);
3602 }
3603
3604 cmse::validate_cmse_abi(self.tcx(), self.dcx(), hir_id, abi, fn_ptr_ty);
3606
3607 if !fn_ptr_ty.references_error() {
3608 let inputs = fn_ptr_ty.inputs();
3615 let late_bound_in_args =
3616 tcx.collect_constrained_late_bound_regions(inputs.map_bound(|i| i.to_owned()));
3617 let output = fn_ptr_ty.output();
3618 let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(output);
3619
3620 self.validate_late_bound_regions(late_bound_in_args, late_bound_in_ret, |br_name| {
3621 struct_span_code_err!(
3622 self.dcx(),
3623 decl.output.span(),
3624 E0581,
3625 "return type references {}, which is not constrained by the fn input types",
3626 br_name
3627 )
3628 });
3629 }
3630
3631 fn_ptr_ty
3632 }
3633
3634 pub(super) fn suggest_trait_fn_ty_for_impl_fn_infer(
3639 &self,
3640 fn_hir_id: HirId,
3641 arg_idx: Option<usize>,
3642 ) -> Option<Ty<'tcx>> {
3643 let tcx = self.tcx();
3644 let hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), ident, .. }) =
3645 tcx.hir_node(fn_hir_id)
3646 else {
3647 return None;
3648 };
3649 let i = tcx.parent_hir_node(fn_hir_id).expect_item().expect_impl();
3650
3651 let trait_ref = self.lower_impl_trait_ref(&i.of_trait?.trait_ref, self.lower_ty(i.self_ty));
3652
3653 let assoc = tcx.associated_items(trait_ref.def_id).find_by_ident_and_kind(
3654 tcx,
3655 *ident,
3656 ty::AssocTag::Fn,
3657 trait_ref.def_id,
3658 )?;
3659
3660 let fn_sig = tcx
3661 .fn_sig(assoc.def_id)
3662 .instantiate(
3663 tcx,
3664 trait_ref
3665 .args
3666 .extend_to(tcx, assoc.def_id, |param, _| tcx.mk_param_from_def(param)),
3667 )
3668 .skip_norm_wip();
3669 let fn_sig = tcx.liberate_late_bound_regions(fn_hir_id.expect_owner().to_def_id(), fn_sig);
3670
3671 Some(if let Some(arg_idx) = arg_idx {
3672 *fn_sig.inputs().get(arg_idx)?
3673 } else {
3674 fn_sig.output()
3675 })
3676 }
3677
3678 #[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(3678u32),
::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))]
3679 fn validate_late_bound_regions<'cx>(
3680 &'cx self,
3681 constrained_regions: FxIndexSet<ty::BoundRegionKind<'tcx>>,
3682 referenced_regions: FxIndexSet<ty::BoundRegionKind<'tcx>>,
3683 generate_err: impl Fn(&str) -> Diag<'cx>,
3684 ) {
3685 for br in referenced_regions.difference(&constrained_regions) {
3686 let br_name = if let Some(name) = br.get_name(self.tcx()) {
3687 format!("lifetime `{name}`")
3688 } else {
3689 "an anonymous lifetime".to_string()
3690 };
3691
3692 let mut err = generate_err(&br_name);
3693
3694 if !br.is_named(self.tcx()) {
3695 err.note(
3702 "lifetimes appearing in an associated or opaque type are not considered constrained",
3703 );
3704 err.note("consider introducing a named lifetime parameter");
3705 }
3706
3707 err.emit();
3708 }
3709 }
3710
3711 x;#[instrument(level = "debug", skip(self, span), ret)]
3719 fn compute_object_lifetime_bound(
3720 &self,
3721 span: Span,
3722 existential_predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
3723 ) -> Option<ty::Region<'tcx>> {
3725 let tcx = self.tcx();
3726
3727 let derived_region_bounds = object_region_bounds(tcx, existential_predicates);
3730
3731 if derived_region_bounds.is_empty() {
3734 return None;
3735 }
3736
3737 if derived_region_bounds.iter().any(|r| r.is_static()) {
3740 return Some(tcx.lifetimes.re_static);
3741 }
3742
3743 let r = derived_region_bounds[0];
3747 if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
3748 self.dcx().emit_err(AmbiguousLifetimeBound { span });
3749 }
3750 Some(r)
3751 }
3752
3753 fn construct_const_ctor_value(
3754 &self,
3755 ctor_def_id: DefId,
3756 ctor_of: CtorOf,
3757 args: GenericArgsRef<'tcx>,
3758 ) -> Const<'tcx> {
3759 let tcx = self.tcx();
3760 let parent_did = tcx.parent(ctor_def_id);
3761
3762 let adt_def = tcx.adt_def(match ctor_of {
3763 CtorOf::Variant => tcx.parent(parent_did),
3764 CtorOf::Struct => parent_did,
3765 });
3766
3767 let variant_idx = adt_def.variant_index_with_id(parent_did);
3768
3769 let valtree = if adt_def.is_enum() {
3770 let discr = ty::ValTree::from_scalar_int(tcx, variant_idx.as_u32().into());
3771 ty::ValTree::from_branches(tcx, [ty::Const::new_value(tcx, discr, tcx.types.u32)])
3772 } else {
3773 ty::ValTree::zst(tcx)
3774 };
3775
3776 let adt_ty = Ty::new_adt(tcx, adt_def, args);
3777 ty::Const::new_value(tcx, valtree, adt_ty)
3778 }
3779}