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