1mod bounds;
17mod cmse;
18mod dyn_trait;
19pub mod errors;
20pub mod generics;
21
22use std::{assert_matches, slice};
23
24use rustc_abi::FIRST_VARIANT;
25use rustc_ast::LitKind;
26use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet};
27use rustc_errors::codes::*;
28use rustc_errors::{
29 Applicability, Diag, DiagCtxtHandle, ErrorGuaranteed, FatalError, StashKey,
30 struct_span_code_err,
31};
32use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res};
33use rustc_hir::def_id::{DefId, LocalDefId};
34use rustc_hir::{self as hir, AnonConst, GenericArg, GenericArgs, HirId};
35use rustc_infer::infer::{InferCtxt, TyCtxtInferExt};
36use rustc_infer::traits::DynCompatibilityViolation;
37use rustc_macros::{TypeFoldable, TypeVisitable};
38use rustc_middle::middle::stability::AllowUnstable;
39use rustc_middle::ty::{
40 self, Const, FnSigKind, GenericArgKind, GenericArgsRef, GenericParamDefKind, LitToConstInput,
41 Ty, TyCtxt, TypeSuperFoldable, TypeVisitableExt, TypingMode, Unnormalized, Upcast,
42 const_lit_matches_ty, fold_regions,
43};
44use rustc_middle::{bug, span_bug};
45use rustc_session::errors::feature_err;
46use rustc_session::lint::builtin::AMBIGUOUS_ASSOCIATED_ITEMS;
47use rustc_span::{DUMMY_SP, Ident, Span, kw, sym};
48use rustc_trait_selection::infer::InferCtxtExt;
49use rustc_trait_selection::traits::{self, FulfillmentError};
50use tracing::{debug, instrument};
51
52use crate::check::check_abi;
53use crate::errors::{BadReturnTypeNotation, NoFieldOnType};
54use crate::hir_ty_lowering::errors::{GenericsArgsErrExtend, prohibit_assoc_item_constraint};
55use crate::hir_ty_lowering::generics::{check_generic_arg_count, lower_generic_args};
56use crate::middle::resolve_bound_vars as rbv;
57use crate::{NoVariantNamed, check_c_variadic_abi};
58
59#[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)]
62pub(crate) enum ImpliedBoundsContext<'tcx> {
63 TraitDef(LocalDefId),
66 TyParam(LocalDefId, &'tcx [hir::WherePredicate<'tcx>]),
68 AssociatedTypeOrImplTrait,
70}
71
72#[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)]
74pub struct GenericPathSegment(pub DefId, pub usize);
75
76#[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)]
77pub enum PredicateFilter {
78 All,
80
81 SelfOnly,
83
84 SelfTraitThatDefines(Ident),
88
89 SelfAndAssociatedTypeBounds,
93
94 ConstIfConst,
96
97 SelfConstIfConst,
99}
100
101#[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)]
102pub enum RegionInferReason<'a> {
103 ExplicitObjectLifetime,
105 ObjectLifetimeDefault(Span),
107 Param(&'a ty::GenericParamDef),
109 RegionPredicate,
110 Reference,
111 OutlivesBound,
112}
113
114#[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)]
115pub struct InherentAssocCandidate {
116 pub impl_: DefId,
117 pub assoc_item: DefId,
118 pub scope: DefId,
119}
120
121pub struct ResolvedStructPath<'tcx> {
122 pub res: Result<Res, ErrorGuaranteed>,
123 pub ty: Ty<'tcx>,
124}
125
126pub trait HirTyLowerer<'tcx> {
131 fn tcx(&self) -> TyCtxt<'tcx>;
132
133 fn dcx(&self) -> DiagCtxtHandle<'_>;
134
135 fn item_def_id(&self) -> LocalDefId;
137
138 fn re_infer(&self, span: Span, reason: RegionInferReason<'_>) -> ty::Region<'tcx>;
140
141 fn ty_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx>;
143
144 fn ct_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Const<'tcx>;
146
147 fn register_trait_ascription_bounds(
148 &self,
149 bounds: Vec<(ty::Clause<'tcx>, Span)>,
150 hir_id: HirId,
151 span: Span,
152 );
153
154 fn probe_ty_param_bounds(
169 &self,
170 span: Span,
171 def_id: LocalDefId,
172 assoc_ident: Ident,
173 ) -> ty::EarlyBinder<'tcx, &'tcx [(ty::Clause<'tcx>, Span)]>;
174
175 fn select_inherent_assoc_candidates(
176 &self,
177 span: Span,
178 self_ty: Ty<'tcx>,
179 candidates: Vec<InherentAssocCandidate>,
180 ) -> (Vec<InherentAssocCandidate>, Vec<FulfillmentError<'tcx>>);
181
182 fn lower_assoc_item_path(
195 &self,
196 span: Span,
197 item_def_id: DefId,
198 item_segment: &hir::PathSegment<'tcx>,
199 poly_trait_ref: ty::PolyTraitRef<'tcx>,
200 ) -> Result<(DefId, GenericArgsRef<'tcx>), ErrorGuaranteed>;
201
202 fn lower_fn_sig(
203 &self,
204 decl: &hir::FnDecl<'tcx>,
205 generics: Option<&hir::Generics<'_>>,
206 hir_id: HirId,
207 hir_ty: Option<&hir::Ty<'_>>,
208 ) -> (Vec<Ty<'tcx>>, Ty<'tcx>);
209
210 fn probe_adt(&self, span: Span, ty: Ty<'tcx>) -> Option<ty::AdtDef<'tcx>>;
217
218 fn record_ty(&self, hir_id: HirId, ty: Ty<'tcx>, span: Span);
220
221 fn infcx(&self) -> Option<&InferCtxt<'tcx>>;
223
224 fn lowerer(&self) -> &dyn HirTyLowerer<'tcx>
229 where
230 Self: Sized,
231 {
232 self
233 }
234
235 fn dyn_compatibility_violations(&self, trait_def_id: DefId) -> Vec<DynCompatibilityViolation>;
238}
239
240enum AssocItemQSelf {
244 Trait(DefId),
245 TyParam(LocalDefId, Span),
246 SelfTyAlias,
247}
248
249impl AssocItemQSelf {
250 fn to_string(&self, tcx: TyCtxt<'_>) -> String {
251 match *self {
252 Self::Trait(def_id) => tcx.def_path_str(def_id),
253 Self::TyParam(def_id, _) => tcx.hir_ty_param_name(def_id).to_string(),
254 Self::SelfTyAlias => kw::SelfUpper.to_string(),
255 }
256 }
257}
258
259#[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)]
260enum LowerTypeRelativePathMode {
261 Type(PermitVariants),
262 Const,
263}
264
265impl LowerTypeRelativePathMode {
266 fn assoc_tag(self) -> ty::AssocTag {
267 match self {
268 Self::Type(_) => ty::AssocTag::Type,
269 Self::Const => ty::AssocTag::Const,
270 }
271 }
272
273 fn def_kind_for_diagnostics(self) -> DefKind {
275 match self {
276 Self::Type(_) => DefKind::AssocTy,
277 Self::Const => DefKind::AssocConst { is_type_const: false },
278 }
279 }
280
281 fn permit_variants(self) -> PermitVariants {
282 match self {
283 Self::Type(permit_variants) => permit_variants,
284 Self::Const => PermitVariants::No,
287 }
288 }
289}
290
291#[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)]
293pub enum PermitVariants {
294 Yes,
295 No,
296}
297
298#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for TypeRelativePath<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
TypeRelativePath::AssocItem(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"AssocItem", __self_0, &__self_1),
TypeRelativePath::Variant { adt: __self_0, variant_did: __self_1 }
=>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"Variant", "adt", __self_0, "variant_did", &__self_1),
TypeRelativePath::Ctor { ctor_def_id: __self_0, args: __self_1 }
=>
::core::fmt::Formatter::debug_struct_field2_finish(f, "Ctor",
"ctor_def_id", __self_0, "args", &__self_1),
}
}
}Debug, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for TypeRelativePath<'tcx> {
#[inline]
fn clone(&self) -> TypeRelativePath<'tcx> {
let _: ::core::clone::AssertParamIsClone<DefId>;
let _: ::core::clone::AssertParamIsClone<GenericArgsRef<'tcx>>;
let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
let _: ::core::clone::AssertParamIsClone<GenericArgsRef<'tcx>>;
*self
}
}Clone, #[automatically_derived]
impl<'tcx> ::core::marker::Copy for TypeRelativePath<'tcx> { }Copy)]
299enum TypeRelativePath<'tcx> {
300 AssocItem(DefId, GenericArgsRef<'tcx>),
301 Variant { adt: Ty<'tcx>, variant_did: DefId },
302 Ctor { ctor_def_id: DefId, args: GenericArgsRef<'tcx> },
303}
304
305#[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)]
315pub enum ExplicitLateBound {
316 Yes,
317 No,
318}
319
320#[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)]
321pub enum IsMethodCall {
322 Yes,
323 No,
324}
325
326#[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)]
329pub(crate) enum GenericArgPosition {
330 Type,
331 Value(IsMethodCall),
332}
333
334#[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)]
338pub(crate) enum OverlappingAsssocItemConstraints {
339 Allowed,
340 Forbidden,
341}
342
343#[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)]
346pub struct GenericArgCountMismatch {
347 pub reported: ErrorGuaranteed,
348 pub invalid_args: Vec<usize>,
350}
351
352#[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)]
355pub struct GenericArgCountResult {
356 pub explicit_late_bound: ExplicitLateBound,
357 pub correct: Result<(), GenericArgCountMismatch>,
358}
359
360pub trait GenericArgsLowerer<'a, 'tcx> {
365 fn args_for_def_id(&mut self, def_id: DefId) -> (Option<&'a GenericArgs<'tcx>>, bool);
366
367 fn provided_kind(
368 &mut self,
369 preceding_args: &[ty::GenericArg<'tcx>],
370 param: &ty::GenericParamDef,
371 arg: &GenericArg<'tcx>,
372 ) -> ty::GenericArg<'tcx>;
373
374 fn inferred_kind(
375 &mut self,
376 preceding_args: &[ty::GenericArg<'tcx>],
377 param: &ty::GenericParamDef,
378 infer_args: bool,
379 ) -> ty::GenericArg<'tcx>;
380}
381
382enum ForbidParamContext {
384 ConstArgument,
386 EnumDiscriminant,
388}
389
390struct ForbidParamUsesFolder<'tcx> {
391 tcx: TyCtxt<'tcx>,
392 anon_const_def_id: LocalDefId,
393 span: Span,
394 is_self_alias: bool,
395 context: ForbidParamContext,
396}
397
398impl<'tcx> ForbidParamUsesFolder<'tcx> {
399 fn error(&self) -> ErrorGuaranteed {
400 let msg = match self.context {
401 ForbidParamContext::EnumDiscriminant if self.is_self_alias => {
402 "generic `Self` types are not permitted in enum discriminant values"
403 }
404 ForbidParamContext::EnumDiscriminant => {
405 "generic parameters may not be used in enum discriminant values"
406 }
407 ForbidParamContext::ConstArgument if self.is_self_alias => {
408 "generic `Self` types are currently not permitted in anonymous constants"
409 }
410 ForbidParamContext::ConstArgument => {
411 if self.tcx.features().generic_const_args() {
412 "generic parameters in const blocks are only allowed as the direct value of a `type const`"
413 } else {
414 "generic parameters may not be used in const operations"
415 }
416 }
417 };
418 let mut diag = self.tcx.dcx().struct_span_err(self.span, msg);
419 if self.is_self_alias && #[allow(non_exhaustive_omitted_patterns)] match self.context {
ForbidParamContext::ConstArgument => true,
_ => false,
}matches!(self.context, ForbidParamContext::ConstArgument) {
420 let anon_const_hir_id: HirId = HirId::make_owner(self.anon_const_def_id);
421 let parent_impl = self.tcx.hir_parent_owner_iter(anon_const_hir_id).find_map(
422 |(_, node)| match node {
423 hir::OwnerNode::Item(hir::Item {
424 kind: hir::ItemKind::Impl(impl_), ..
425 }) => Some(impl_),
426 _ => None,
427 },
428 );
429 if let Some(impl_) = parent_impl {
430 diag.span_note(impl_.self_ty.span, "not a concrete type");
431 }
432 }
433 if #[allow(non_exhaustive_omitted_patterns)] match self.context {
ForbidParamContext::ConstArgument => true,
_ => false,
}matches!(self.context, ForbidParamContext::ConstArgument)
434 && self.tcx.features().min_generic_const_args()
435 {
436 if !self.tcx.features().generic_const_args() {
437 diag.help("add `#![feature(generic_const_args)]` to allow generic expressions as the RHS of const items");
438 } else {
439 diag.help("consider factoring the expression into a `type const` item and use it as the const argument instead");
440 }
441 }
442 diag.emit()
443 }
444}
445
446impl<'tcx> ty::TypeFolder<TyCtxt<'tcx>> for ForbidParamUsesFolder<'tcx> {
447 fn cx(&self) -> TyCtxt<'tcx> {
448 self.tcx
449 }
450
451 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
452 if #[allow(non_exhaustive_omitted_patterns)] match t.kind() {
ty::Param(..) => true,
_ => false,
}matches!(t.kind(), ty::Param(..)) {
453 return Ty::new_error(self.tcx, self.error());
454 }
455 t.super_fold_with(self)
456 }
457
458 fn fold_const(&mut self, c: Const<'tcx>) -> Const<'tcx> {
459 if #[allow(non_exhaustive_omitted_patterns)] match c.kind() {
ty::ConstKind::Param(..) => true,
_ => false,
}matches!(c.kind(), ty::ConstKind::Param(..)) {
460 return Const::new_error(self.tcx, self.error());
461 }
462 c.super_fold_with(self)
463 }
464
465 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
466 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(..)) {
467 return ty::Region::new_error(self.tcx, self.error());
468 }
469 r
470 }
471}
472
473impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
474 pub fn check_param_res_if_mcg_for_instantiate_value_path(
478 &self,
479 res: Res,
480 span: Span,
481 ) -> Result<(), ErrorGuaranteed> {
482 let tcx = self.tcx();
483 let parent_def_id = self.item_def_id();
484 if let Res::Def(DefKind::ConstParam, _) = res
485 && tcx.def_kind(parent_def_id) == DefKind::AnonConst
486 && let ty::AnonConstKind::MCG = tcx.anon_const_kind(parent_def_id)
487 {
488 let folder = ForbidParamUsesFolder {
489 tcx,
490 anon_const_def_id: parent_def_id,
491 span,
492 is_self_alias: false,
493 context: ForbidParamContext::ConstArgument,
494 };
495 return Err(folder.error());
496 }
497 Ok(())
498 }
499
500 fn anon_const_forbids_generic_params(&self) -> Option<ForbidParamContext> {
508 let tcx = self.tcx();
509 let parent_def_id = self.item_def_id();
510
511 let anon_const_def_id = match tcx.def_kind(parent_def_id) {
515 DefKind::AnonConst => parent_def_id,
516 DefKind::InlineConst | DefKind::Closure => {
517 let root = tcx.typeck_root_def_id(parent_def_id.into());
518 match tcx.def_kind(root) {
519 DefKind::AnonConst => root.expect_local(),
520 _ => return None,
521 }
522 }
523 _ => return None,
524 };
525
526 match tcx.anon_const_kind(anon_const_def_id) {
527 ty::AnonConstKind::MCG => Some(ForbidParamContext::ConstArgument),
528 ty::AnonConstKind::NonTypeSystem => {
529 if tcx.generics_of(anon_const_def_id).count() == 0 {
533 Some(ForbidParamContext::EnumDiscriminant)
534 } else {
535 None
536 }
537 }
538 ty::AnonConstKind::GCE
539 | ty::AnonConstKind::GCA
540 | ty::AnonConstKind::RepeatExprCount => None,
541 }
542 }
543
544 #[must_use = "need to use transformed output"]
550 fn check_param_uses_if_mcg<T>(&self, term: T, span: Span, is_self_alias: bool) -> T
551 where
552 T: ty::TypeFoldable<TyCtxt<'tcx>>,
553 {
554 let tcx = self.tcx();
555 if let Some(context) = self.anon_const_forbids_generic_params()
556 && (term.has_param() || term.has_escaping_bound_vars())
558 {
559 let anon_const_def_id = self.item_def_id();
560 let mut folder =
561 ForbidParamUsesFolder { tcx, anon_const_def_id, span, is_self_alias, context };
562 term.fold_with(&mut folder)
563 } else {
564 term
565 }
566 }
567
568 x;#[instrument(level = "debug", skip(self), ret)]
570 pub fn lower_lifetime(
571 &self,
572 lifetime: &hir::Lifetime,
573 reason: RegionInferReason<'_>,
574 ) -> ty::Region<'tcx> {
575 if let Some(resolved) = self.tcx().named_bound_var(lifetime.hir_id) {
576 let region = self.lower_resolved_lifetime(resolved);
577 self.check_param_uses_if_mcg(region, lifetime.ident.span, false)
578 } else {
579 self.re_infer(lifetime.ident.span, reason)
580 }
581 }
582
583 x;#[instrument(level = "debug", skip(self), ret)]
585 fn lower_resolved_lifetime(&self, resolved: rbv::ResolvedArg) -> ty::Region<'tcx> {
586 let tcx = self.tcx();
587
588 match resolved {
589 rbv::ResolvedArg::StaticLifetime => tcx.lifetimes.re_static,
590
591 rbv::ResolvedArg::LateBound(debruijn, index, def_id) => {
592 let br = ty::BoundRegion {
593 var: ty::BoundVar::from_u32(index),
594 kind: ty::BoundRegionKind::Named(def_id.to_def_id()),
595 };
596 ty::Region::new_bound(tcx, debruijn, br)
597 }
598
599 rbv::ResolvedArg::EarlyBound(def_id) => {
600 let name = tcx.hir_ty_param_name(def_id);
601 let item_def_id = tcx.hir_ty_param_owner(def_id);
602 let generics = tcx.generics_of(item_def_id);
603 let index = generics.param_def_id_to_index[&def_id.to_def_id()];
604 ty::Region::new_early_param(tcx, ty::EarlyParamRegion { index, name })
605 }
606
607 rbv::ResolvedArg::Free(scope, id) => {
608 ty::Region::new_late_param(
609 tcx,
610 scope.to_def_id(),
611 ty::LateParamRegionKind::Named(id.to_def_id()),
612 )
613
614 }
616
617 rbv::ResolvedArg::Error(guar) => ty::Region::new_error(tcx, guar),
618 }
619 }
620
621 pub fn lower_generic_args_of_path_segment(
622 &self,
623 span: Span,
624 def_id: DefId,
625 item_segment: &hir::PathSegment<'tcx>,
626 ) -> GenericArgsRef<'tcx> {
627 let (args, _) = self.lower_generic_args_of_path(span, def_id, &[], item_segment, None);
628 if let Some(c) = item_segment.args().constraints.first() {
629 prohibit_assoc_item_constraint(self, c, Some((def_id, item_segment, span)));
630 }
631 args
632 }
633
634 x;#[instrument(level = "debug", skip(self, span), ret)]
669 pub(crate) fn lower_generic_args_of_path(
670 &self,
671 span: Span,
672 def_id: DefId,
673 parent_args: &[ty::GenericArg<'tcx>],
674 segment: &hir::PathSegment<'tcx>,
675 self_ty: Option<Ty<'tcx>>,
676 ) -> (GenericArgsRef<'tcx>, GenericArgCountResult) {
677 let tcx = self.tcx();
682 let generics = tcx.generics_of(def_id);
683 debug!(?generics);
684
685 if generics.has_self {
686 if generics.parent.is_some() {
687 assert!(!parent_args.is_empty())
690 } else {
691 assert!(self_ty.is_some());
693 }
694 } else {
695 assert!(self_ty.is_none());
696 }
697
698 let arg_count = check_generic_arg_count(
699 self,
700 def_id,
701 segment,
702 generics,
703 GenericArgPosition::Type,
704 self_ty.is_some(),
705 );
706
707 if generics.is_own_empty() {
712 return (tcx.mk_args(parent_args), arg_count);
713 }
714
715 struct GenericArgsCtxt<'a, 'tcx> {
716 lowerer: &'a dyn HirTyLowerer<'tcx>,
717 def_id: DefId,
718 generic_args: &'a GenericArgs<'tcx>,
719 span: Span,
720 infer_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 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 incorrect_args: &arg_count.correct,
874 };
875
876 let args = lower_generic_args(
877 self,
878 def_id,
879 parent_args,
880 self_ty.is_some(),
881 self_ty,
882 &arg_count,
883 &mut args_ctx,
884 );
885
886 (args, arg_count)
887 }
888
889 #[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(889u32),
::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))]
890 pub fn lower_generic_args_of_assoc_item(
891 &self,
892 span: Span,
893 item_def_id: DefId,
894 item_segment: &hir::PathSegment<'tcx>,
895 parent_args: GenericArgsRef<'tcx>,
896 ) -> GenericArgsRef<'tcx> {
897 let (args, _) =
898 self.lower_generic_args_of_path(span, item_def_id, parent_args, item_segment, None);
899 if let Some(c) = item_segment.args().constraints.first() {
900 prohibit_assoc_item_constraint(self, c, Some((item_def_id, item_segment, span)));
901 }
902 args
903 }
904
905 pub fn lower_impl_trait_ref(
909 &self,
910 trait_ref: &hir::TraitRef<'tcx>,
911 self_ty: Ty<'tcx>,
912 ) -> ty::TraitRef<'tcx> {
913 let [leading_segments @ .., segment] = trait_ref.path.segments else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
914
915 let _ = self.prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
916
917 self.lower_mono_trait_ref(
918 trait_ref.path.span,
919 trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise()),
920 self_ty,
921 segment,
922 true,
923 )
924 }
925
926 #[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(949u32),
::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:1029",
"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(1029u32),
::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:1036",
"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(1036u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&["poly_trait_ref"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&poly_trait_ref)
as &dyn Value))])
});
} else { ; }
};
match predicate_filter {
PredicateFilter::All | PredicateFilter::SelfOnly |
PredicateFilter::SelfTraitThatDefines(..) |
PredicateFilter::SelfAndAssociatedTypeBounds => {
let bound =
poly_trait_ref.map_bound(|trait_ref|
{
ty::ClauseKind::Trait(ty::TraitPredicate {
trait_ref,
polarity,
})
});
let bound = (bound.upcast(tcx), span);
if tcx.is_lang_item(trait_def_id,
rustc_hir::LangItem::Sized) {
bounds.insert(0, bound);
} else { bounds.push(bound); }
}
PredicateFilter::ConstIfConst |
PredicateFilter::SelfConstIfConst => {}
}
if let hir::BoundConstness::Always(span) |
hir::BoundConstness::Maybe(span) = constness &&
!tcx.is_const_trait(trait_def_id) {
let (def_span, suggestion, suggestion_pre) =
match (trait_def_id.as_local(), tcx.sess.is_nightly_build())
{
(Some(trait_def_id), true) => {
let span = tcx.hir_expect_item(trait_def_id).vis_span;
let span =
tcx.sess.source_map().span_extend_while_whitespace(span);
(None, Some(span.shrink_to_hi()),
if self.tcx().features().const_trait_impl() {
""
} else {
"enable `#![feature(const_trait_impl)]` in your crate and "
})
}
(None, _) | (_, false) =>
(Some(tcx.def_span(trait_def_id)), None, ""),
};
self.dcx().emit_err(crate::errors::ConstBoundForNonConstTrait {
span,
modifier: constness.as_str(),
def_span,
trait_name: tcx.def_path_str(trait_def_id),
suggestion,
suggestion_pre,
});
} else {
match predicate_filter {
PredicateFilter::SelfTraitThatDefines(..) => {}
PredicateFilter::All | PredicateFilter::SelfOnly |
PredicateFilter::SelfAndAssociatedTypeBounds => {
match constness {
hir::BoundConstness::Always(_) => {
if polarity == ty::PredicatePolarity::Positive {
bounds.push((poly_trait_ref.to_host_effect_clause(tcx,
ty::BoundConstness::Const), span));
}
}
hir::BoundConstness::Maybe(_) => {}
hir::BoundConstness::Never => {}
}
}
PredicateFilter::ConstIfConst |
PredicateFilter::SelfConstIfConst => {
match constness {
hir::BoundConstness::Maybe(_) => {
if polarity == ty::PredicatePolarity::Positive {
bounds.push((poly_trait_ref.to_host_effect_clause(tcx,
ty::BoundConstness::Maybe), span));
}
}
hir::BoundConstness::Always(_) | hir::BoundConstness::Never
=> {}
}
}
}
}
let mut dup_constraints =
(overlapping_assoc_item_constraints ==
OverlappingAsssocItemConstraints::Forbidden).then_some(FxIndexMap::default());
for constraint in constraints {
if polarity == ty::PredicatePolarity::Negative {
self.dcx().span_delayed_bug(constraint.span,
"negative trait bounds should not have assoc item constraints");
break;
}
let _: Result<_, ErrorGuaranteed> =
self.lower_assoc_item_constraint(trait_ref.hir_ref_id,
poly_trait_ref, constraint, bounds,
dup_constraints.as_mut(), constraint.span,
predicate_filter);
}
arg_count
}
}
}#[instrument(level = "debug", skip(self, bounds))]
950 pub(crate) fn lower_poly_trait_ref(
951 &self,
952 &hir::PolyTraitRef {
953 bound_generic_params,
954 modifiers: hir::TraitBoundModifiers { constness, polarity },
955 trait_ref,
956 span,
957 }: &hir::PolyTraitRef<'tcx>,
958 self_ty: Ty<'tcx>,
959 bounds: &mut Vec<(ty::Clause<'tcx>, Span)>,
960 predicate_filter: PredicateFilter,
961 overlapping_assoc_item_constraints: OverlappingAsssocItemConstraints,
962 ) -> GenericArgCountResult {
963 let tcx = self.tcx();
964
965 let _ = bound_generic_params;
968
969 let trait_def_id = trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise());
970
971 let transient = match polarity {
976 hir::BoundPolarity::Positive => {
977 tcx.is_lang_item(trait_def_id, hir::LangItem::PointeeSized)
983 }
984 hir::BoundPolarity::Negative(_) => false,
985 hir::BoundPolarity::Maybe(_) => {
986 self.require_bound_to_relax_default_trait(trait_ref, span);
987 true
988 }
989 };
990 let bounds = if transient { &mut Vec::new() } else { bounds };
991
992 let polarity = match polarity {
993 hir::BoundPolarity::Positive | hir::BoundPolarity::Maybe(_) => {
994 ty::PredicatePolarity::Positive
995 }
996 hir::BoundPolarity::Negative(_) => ty::PredicatePolarity::Negative,
997 };
998
999 let [leading_segments @ .., segment] = trait_ref.path.segments else { bug!() };
1000
1001 let _ = self.prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
1002 self.report_internal_fn_trait(span, trait_def_id, segment, false);
1003
1004 let (generic_args, arg_count) = self.lower_generic_args_of_path(
1005 trait_ref.path.span,
1006 trait_def_id,
1007 &[],
1008 segment,
1009 Some(self_ty),
1010 );
1011
1012 let constraints = segment.args().constraints;
1013
1014 if transient && (!generic_args[1..].is_empty() || !constraints.is_empty()) {
1015 self.dcx()
1025 .span_delayed_bug(span, "transient bound should not have args or constraints");
1026 }
1027
1028 let bound_vars = tcx.late_bound_vars(trait_ref.hir_ref_id);
1029 debug!(?bound_vars);
1030
1031 let poly_trait_ref = ty::Binder::bind_with_vars(
1032 ty::TraitRef::new_from_args(tcx, trait_def_id, generic_args),
1033 bound_vars,
1034 );
1035
1036 debug!(?poly_trait_ref);
1037
1038 match predicate_filter {
1040 PredicateFilter::All
1041 | PredicateFilter::SelfOnly
1042 | PredicateFilter::SelfTraitThatDefines(..)
1043 | PredicateFilter::SelfAndAssociatedTypeBounds => {
1044 let bound = poly_trait_ref.map_bound(|trait_ref| {
1045 ty::ClauseKind::Trait(ty::TraitPredicate { trait_ref, polarity })
1046 });
1047 let bound = (bound.upcast(tcx), span);
1048 if tcx.is_lang_item(trait_def_id, rustc_hir::LangItem::Sized) {
1054 bounds.insert(0, bound);
1055 } else {
1056 bounds.push(bound);
1057 }
1058 }
1059 PredicateFilter::ConstIfConst | PredicateFilter::SelfConstIfConst => {}
1060 }
1061
1062 if let hir::BoundConstness::Always(span) | hir::BoundConstness::Maybe(span) = constness
1063 && !tcx.is_const_trait(trait_def_id)
1064 {
1065 let (def_span, suggestion, suggestion_pre) =
1066 match (trait_def_id.as_local(), tcx.sess.is_nightly_build()) {
1067 (Some(trait_def_id), true) => {
1068 let span = tcx.hir_expect_item(trait_def_id).vis_span;
1069 let span = tcx.sess.source_map().span_extend_while_whitespace(span);
1070
1071 (
1072 None,
1073 Some(span.shrink_to_hi()),
1074 if self.tcx().features().const_trait_impl() {
1075 ""
1076 } else {
1077 "enable `#![feature(const_trait_impl)]` in your crate and "
1078 },
1079 )
1080 }
1081 (None, _) | (_, false) => (Some(tcx.def_span(trait_def_id)), None, ""),
1082 };
1083 self.dcx().emit_err(crate::errors::ConstBoundForNonConstTrait {
1084 span,
1085 modifier: constness.as_str(),
1086 def_span,
1087 trait_name: tcx.def_path_str(trait_def_id),
1088 suggestion,
1089 suggestion_pre,
1090 });
1091 } else {
1092 match predicate_filter {
1093 PredicateFilter::SelfTraitThatDefines(..) => {}
1095 PredicateFilter::All
1096 | PredicateFilter::SelfOnly
1097 | PredicateFilter::SelfAndAssociatedTypeBounds => {
1098 match constness {
1099 hir::BoundConstness::Always(_) => {
1100 if polarity == ty::PredicatePolarity::Positive {
1101 bounds.push((
1102 poly_trait_ref
1103 .to_host_effect_clause(tcx, ty::BoundConstness::Const),
1104 span,
1105 ));
1106 }
1107 }
1108 hir::BoundConstness::Maybe(_) => {
1109 }
1114 hir::BoundConstness::Never => {}
1115 }
1116 }
1117 PredicateFilter::ConstIfConst | PredicateFilter::SelfConstIfConst => {
1124 match constness {
1125 hir::BoundConstness::Maybe(_) => {
1126 if polarity == ty::PredicatePolarity::Positive {
1127 bounds.push((
1128 poly_trait_ref
1129 .to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
1130 span,
1131 ));
1132 }
1133 }
1134 hir::BoundConstness::Always(_) | hir::BoundConstness::Never => {}
1135 }
1136 }
1137 }
1138 }
1139
1140 let mut dup_constraints = (overlapping_assoc_item_constraints
1141 == OverlappingAsssocItemConstraints::Forbidden)
1142 .then_some(FxIndexMap::default());
1143
1144 for constraint in constraints {
1145 if polarity == ty::PredicatePolarity::Negative {
1149 self.dcx().span_delayed_bug(
1150 constraint.span,
1151 "negative trait bounds should not have assoc item constraints",
1152 );
1153 break;
1154 }
1155
1156 let _: Result<_, ErrorGuaranteed> = self.lower_assoc_item_constraint(
1158 trait_ref.hir_ref_id,
1159 poly_trait_ref,
1160 constraint,
1161 bounds,
1162 dup_constraints.as_mut(),
1163 constraint.span,
1164 predicate_filter,
1165 );
1166 }
1168
1169 arg_count
1170 }
1171
1172 fn lower_mono_trait_ref(
1176 &self,
1177 span: Span,
1178 trait_def_id: DefId,
1179 self_ty: Ty<'tcx>,
1180 trait_segment: &hir::PathSegment<'tcx>,
1181 is_impl: bool,
1182 ) -> ty::TraitRef<'tcx> {
1183 self.report_internal_fn_trait(span, trait_def_id, trait_segment, is_impl);
1184
1185 let (generic_args, _) =
1186 self.lower_generic_args_of_path(span, trait_def_id, &[], trait_segment, Some(self_ty));
1187 if let Some(c) = trait_segment.args().constraints.first() {
1188 prohibit_assoc_item_constraint(self, c, Some((trait_def_id, trait_segment, span)));
1189 }
1190 ty::TraitRef::new_from_args(self.tcx(), trait_def_id, generic_args)
1191 }
1192
1193 fn probe_trait_that_defines_assoc_item(
1194 &self,
1195 trait_def_id: DefId,
1196 assoc_tag: ty::AssocTag,
1197 assoc_ident: Ident,
1198 ) -> bool {
1199 self.tcx()
1200 .associated_items(trait_def_id)
1201 .find_by_ident_and_kind(self.tcx(), assoc_ident, assoc_tag, trait_def_id)
1202 .is_some()
1203 }
1204
1205 fn lower_path_segment(
1206 &self,
1207 span: Span,
1208 def_id: DefId,
1209 item_segment: &hir::PathSegment<'tcx>,
1210 ) -> Ty<'tcx> {
1211 let tcx = self.tcx();
1212 let args = self.lower_generic_args_of_path_segment(span, def_id, item_segment);
1213
1214 if let DefKind::TyAlias = tcx.def_kind(def_id)
1215 && tcx.type_alias_is_lazy(def_id)
1216 {
1217 let alias_ty = ty::AliasTy::new_from_args(tcx, ty::Free { def_id }, args);
1221 Ty::new_alias(tcx, alias_ty)
1222 } else {
1223 tcx.at(span).type_of(def_id).instantiate(tcx, args).skip_norm_wip()
1224 }
1225 }
1226
1227 x;#[instrument(level = "debug", skip_all, ret)]
1235 fn probe_single_ty_param_bound_for_assoc_item(
1236 &self,
1237 ty_param_def_id: LocalDefId,
1238 ty_param_span: Span,
1239 assoc_tag: ty::AssocTag,
1240 assoc_ident: Ident,
1241 span: Span,
1242 ) -> Result<ty::PolyTraitRef<'tcx>, ErrorGuaranteed> {
1243 debug!(?ty_param_def_id, ?assoc_ident, ?span);
1244 let tcx = self.tcx();
1245
1246 let predicates = &self.probe_ty_param_bounds(span, ty_param_def_id, assoc_ident);
1247 debug!("predicates={:#?}", predicates);
1248
1249 self.probe_single_bound_for_assoc_item(
1250 || {
1251 let trait_refs = predicates
1252 .iter_identity_copied()
1253 .map(Unnormalized::skip_norm_wip)
1254 .filter_map(|(p, _)| Some(p.as_trait_clause()?.map_bound(|t| t.trait_ref)));
1255 traits::transitive_bounds_that_define_assoc_item(tcx, trait_refs, assoc_ident)
1256 },
1257 AssocItemQSelf::TyParam(ty_param_def_id, ty_param_span),
1258 assoc_tag,
1259 assoc_ident,
1260 span,
1261 None,
1262 )
1263 }
1264
1265 x;#[instrument(level = "debug", skip(self, all_candidates, qself, constraint), ret)]
1271 fn probe_single_bound_for_assoc_item<I>(
1272 &self,
1273 all_candidates: impl Fn() -> I,
1274 qself: AssocItemQSelf,
1275 assoc_tag: ty::AssocTag,
1276 assoc_ident: Ident,
1277 span: Span,
1278 constraint: Option<&hir::AssocItemConstraint<'tcx>>,
1279 ) -> Result<ty::PolyTraitRef<'tcx>, ErrorGuaranteed>
1280 where
1281 I: Iterator<Item = ty::PolyTraitRef<'tcx>>,
1282 {
1283 let mut matching_candidates = all_candidates().filter(|r| {
1284 self.probe_trait_that_defines_assoc_item(r.def_id(), assoc_tag, assoc_ident)
1285 });
1286
1287 let Some(bound1) = matching_candidates.next() else {
1288 return Err(self.report_unresolved_assoc_item(
1289 all_candidates,
1290 qself,
1291 assoc_tag,
1292 assoc_ident,
1293 span,
1294 constraint,
1295 ));
1296 };
1297
1298 if let Some(bound2) = matching_candidates.next() {
1299 return Err(self.report_ambiguous_assoc_item(
1300 bound1,
1301 bound2,
1302 matching_candidates,
1303 qself,
1304 assoc_tag,
1305 assoc_ident,
1306 span,
1307 constraint,
1308 ));
1309 }
1310
1311 Ok(bound1)
1312 }
1313
1314 x;#[instrument(level = "debug", skip_all, ret)]
1341 pub fn lower_type_relative_ty_path(
1342 &self,
1343 self_ty: Ty<'tcx>,
1344 hir_self_ty: &'tcx hir::Ty<'tcx>,
1345 segment: &'tcx hir::PathSegment<'tcx>,
1346 qpath_hir_id: HirId,
1347 span: Span,
1348 permit_variants: PermitVariants,
1349 ) -> Result<(Ty<'tcx>, DefKind, DefId), ErrorGuaranteed> {
1350 let tcx = self.tcx();
1351 match self.lower_type_relative_path(
1352 self_ty,
1353 hir_self_ty,
1354 segment,
1355 qpath_hir_id,
1356 span,
1357 LowerTypeRelativePathMode::Type(permit_variants),
1358 )? {
1359 TypeRelativePath::AssocItem(def_id, args) => {
1360 let alias_ty = ty::AliasTy::new_from_args(
1361 tcx,
1362 ty::AliasTyKind::new_from_def_id(tcx, def_id),
1363 args,
1364 );
1365 let ty = Ty::new_alias(tcx, alias_ty);
1366 let ty = self.check_param_uses_if_mcg(ty, span, false);
1367 Ok((ty, tcx.def_kind(def_id), def_id))
1368 }
1369 TypeRelativePath::Variant { adt, variant_did } => {
1370 let adt = self.check_param_uses_if_mcg(adt, span, false);
1371 Ok((adt, DefKind::Variant, variant_did))
1372 }
1373 TypeRelativePath::Ctor { .. } => {
1374 let e = tcx.dcx().span_err(span, "expected type, found tuple constructor");
1375 Err(e)
1376 }
1377 }
1378 }
1379
1380 x;#[instrument(level = "debug", skip_all, ret)]
1382 fn lower_type_relative_const_path(
1383 &self,
1384 self_ty: Ty<'tcx>,
1385 hir_self_ty: &'tcx hir::Ty<'tcx>,
1386 segment: &'tcx hir::PathSegment<'tcx>,
1387 qpath_hir_id: HirId,
1388 span: Span,
1389 ) -> Result<Const<'tcx>, ErrorGuaranteed> {
1390 let tcx = self.tcx();
1391 match self.lower_type_relative_path(
1392 self_ty,
1393 hir_self_ty,
1394 segment,
1395 qpath_hir_id,
1396 span,
1397 LowerTypeRelativePathMode::Const,
1398 )? {
1399 TypeRelativePath::AssocItem(def_id, args) => {
1400 self.require_type_const_attribute(def_id, span)?;
1401 let ct = Const::new_unevaluated(
1402 tcx,
1403 ty::UnevaluatedConst::new(
1404 tcx,
1405 ty::UnevaluatedConstKind::new_from_def_id(tcx, def_id),
1406 args,
1407 ),
1408 );
1409 let ct = self.check_param_uses_if_mcg(ct, span, false);
1410 Ok(ct)
1411 }
1412 TypeRelativePath::Ctor { ctor_def_id, args } => match tcx.def_kind(ctor_def_id) {
1413 DefKind::Ctor(_, CtorKind::Fn) => {
1414 Ok(ty::Const::zero_sized(tcx, Ty::new_fn_def(tcx, ctor_def_id, args)))
1415 }
1416 DefKind::Ctor(ctor_of, CtorKind::Const) => {
1417 Ok(self.construct_const_ctor_value(ctor_def_id, ctor_of, args))
1418 }
1419 _ => unreachable!(),
1420 },
1421 TypeRelativePath::Variant { .. } => {
1424 span_bug!(span, "unexpected variant res for type associated const path")
1425 }
1426 }
1427 }
1428
1429 x;#[instrument(level = "debug", skip_all, ret)]
1431 fn lower_type_relative_path(
1432 &self,
1433 self_ty: Ty<'tcx>,
1434 hir_self_ty: &'tcx hir::Ty<'tcx>,
1435 segment: &'tcx hir::PathSegment<'tcx>,
1436 qpath_hir_id: HirId,
1437 span: Span,
1438 mode: LowerTypeRelativePathMode,
1439 ) -> Result<TypeRelativePath<'tcx>, ErrorGuaranteed> {
1440 debug!(%self_ty, ?segment.ident);
1441 let tcx = self.tcx();
1442
1443 let mut variant_def_id = None;
1445 if let Some(adt_def) = self.probe_adt(span, self_ty) {
1446 if adt_def.is_enum() {
1447 let variant_def = adt_def
1448 .variants()
1449 .iter()
1450 .find(|vd| tcx.hygienic_eq(segment.ident, vd.ident(tcx), adt_def.did()));
1451 if let Some(variant_def) = variant_def {
1452 if matches!(mode, LowerTypeRelativePathMode::Const)
1455 && let Some((_, ctor_def_id)) = variant_def.ctor
1456 {
1457 tcx.check_stability(variant_def.def_id, Some(qpath_hir_id), span, None);
1458 let _ = self.prohibit_generic_args(
1459 slice::from_ref(segment).iter(),
1460 GenericsArgsErrExtend::EnumVariant {
1461 qself: hir_self_ty,
1462 assoc_segment: segment,
1463 adt_def,
1464 },
1465 );
1466 let ty::Adt(_, enum_args) = self_ty.kind() else { unreachable!() };
1467 return Ok(TypeRelativePath::Ctor { ctor_def_id, args: enum_args });
1468 }
1469 if let PermitVariants::Yes = mode.permit_variants() {
1470 tcx.check_stability(variant_def.def_id, Some(qpath_hir_id), span, None);
1471 let _ = self.prohibit_generic_args(
1472 slice::from_ref(segment).iter(),
1473 GenericsArgsErrExtend::EnumVariant {
1474 qself: hir_self_ty,
1475 assoc_segment: segment,
1476 adt_def,
1477 },
1478 );
1479 return Ok(TypeRelativePath::Variant {
1480 adt: self_ty,
1481 variant_did: variant_def.def_id,
1482 });
1483 } else {
1484 variant_def_id = Some(variant_def.def_id);
1485 }
1486 }
1487 }
1488
1489 if let Some((did, args)) = self.probe_inherent_assoc_item(
1491 segment,
1492 adt_def.did(),
1493 self_ty,
1494 qpath_hir_id,
1495 span,
1496 mode.assoc_tag(),
1497 )? {
1498 return Ok(TypeRelativePath::AssocItem(did, args));
1499 }
1500 }
1501
1502 let (item_def_id, bound) = self.resolve_type_relative_path(
1503 self_ty,
1504 hir_self_ty,
1505 mode.assoc_tag(),
1506 segment,
1507 qpath_hir_id,
1508 span,
1509 variant_def_id,
1510 )?;
1511
1512 let (item_def_id, args) = self.lower_assoc_item_path(span, item_def_id, segment, bound)?;
1513
1514 if let Some(variant_def_id) = variant_def_id {
1515 tcx.emit_node_span_lint(
1516 AMBIGUOUS_ASSOCIATED_ITEMS,
1517 qpath_hir_id,
1518 span,
1519 errors::AmbiguityBetweenVariantAndAssocItem {
1520 variant_def_id,
1521 item_def_id,
1522 span,
1523 segment_ident: segment.ident,
1524 bound_def_id: bound.def_id(),
1525 self_ty,
1526 tcx,
1527 mode,
1528 },
1529 );
1530 }
1531
1532 Ok(TypeRelativePath::AssocItem(item_def_id, args))
1533 }
1534
1535 fn resolve_type_relative_path(
1537 &self,
1538 self_ty: Ty<'tcx>,
1539 hir_self_ty: &'tcx hir::Ty<'tcx>,
1540 assoc_tag: ty::AssocTag,
1541 segment: &'tcx hir::PathSegment<'tcx>,
1542 qpath_hir_id: HirId,
1543 span: Span,
1544 variant_def_id: Option<DefId>,
1545 ) -> Result<(DefId, ty::PolyTraitRef<'tcx>), ErrorGuaranteed> {
1546 let tcx = self.tcx();
1547
1548 let self_ty_res = match hir_self_ty.kind {
1549 hir::TyKind::Path(hir::QPath::Resolved(_, path)) => path.res,
1550 _ => Res::Err,
1551 };
1552
1553 let bound = match (self_ty.kind(), self_ty_res) {
1555 (_, Res::SelfTyAlias { alias_to: impl_def_id, is_trait_impl: true, .. }) => {
1556 let trait_ref = tcx.impl_trait_ref(impl_def_id);
1559
1560 self.probe_single_bound_for_assoc_item(
1561 || {
1562 let trait_ref =
1563 ty::Binder::dummy(trait_ref.instantiate_identity().skip_norm_wip());
1564 traits::supertraits(tcx, trait_ref)
1565 },
1566 AssocItemQSelf::SelfTyAlias,
1567 assoc_tag,
1568 segment.ident,
1569 span,
1570 None,
1571 )?
1572 }
1573 (
1574 &ty::Param(_),
1575 Res::SelfTyParam { trait_: param_did } | Res::Def(DefKind::TyParam, param_did),
1576 ) => self.probe_single_ty_param_bound_for_assoc_item(
1577 param_did.expect_local(),
1578 hir_self_ty.span,
1579 assoc_tag,
1580 segment.ident,
1581 span,
1582 )?,
1583 _ => {
1584 return Err(self.report_unresolved_type_relative_path(
1585 self_ty,
1586 hir_self_ty,
1587 assoc_tag,
1588 segment.ident,
1589 qpath_hir_id,
1590 span,
1591 variant_def_id,
1592 ));
1593 }
1594 };
1595
1596 let assoc_item = self
1597 .probe_assoc_item(segment.ident, assoc_tag, qpath_hir_id, span, bound.def_id())
1598 .expect("failed to find associated item");
1599
1600 Ok((assoc_item.def_id, bound))
1601 }
1602
1603 fn probe_inherent_assoc_item(
1605 &self,
1606 segment: &hir::PathSegment<'tcx>,
1607 adt_did: DefId,
1608 self_ty: Ty<'tcx>,
1609 block: HirId,
1610 span: Span,
1611 assoc_tag: ty::AssocTag,
1612 ) -> Result<Option<(DefId, GenericArgsRef<'tcx>)>, ErrorGuaranteed> {
1613 let tcx = self.tcx();
1614
1615 if !tcx.features().inherent_associated_types() {
1616 match assoc_tag {
1617 ty::AssocTag::Type => return Ok(None),
1622 ty::AssocTag::Const => {
1623 return Err(feature_err(
1627 &tcx.sess,
1628 sym::inherent_associated_types,
1629 span,
1630 "inherent associated types are unstable",
1631 )
1632 .emit());
1633 }
1634 ty::AssocTag::Fn => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1635 }
1636 }
1637
1638 let name = segment.ident;
1639 let candidates: Vec<_> = tcx
1640 .inherent_impls(adt_did)
1641 .iter()
1642 .filter_map(|&impl_| {
1643 let (item, scope) =
1644 self.probe_assoc_item_unchecked(name, assoc_tag, block, impl_)?;
1645 Some(InherentAssocCandidate { impl_, assoc_item: item.def_id, scope })
1646 })
1647 .collect();
1648
1649 if candidates.is_empty() {
1654 return Ok(None);
1655 }
1656
1657 let (applicable_candidates, fulfillment_errors) =
1658 self.select_inherent_assoc_candidates(span, self_ty, candidates.clone());
1659
1660 let InherentAssocCandidate { impl_, assoc_item, scope: def_scope } =
1662 match &applicable_candidates[..] {
1663 &[] => Err(self.report_unresolved_inherent_assoc_item(
1664 name,
1665 self_ty,
1666 candidates,
1667 fulfillment_errors,
1668 span,
1669 assoc_tag,
1670 )),
1671
1672 &[applicable_candidate] => Ok(applicable_candidate),
1673
1674 &[_, ..] => Err(self.report_ambiguous_inherent_assoc_item(
1675 name,
1676 candidates.into_iter().map(|cand| cand.assoc_item).collect(),
1677 span,
1678 )),
1679 }?;
1680
1681 self.check_assoc_item(assoc_item, name, def_scope, block, span);
1684
1685 let parent_args = ty::GenericArgs::identity_for_item(tcx, impl_);
1689 let args = self.lower_generic_args_of_assoc_item(span, assoc_item, segment, parent_args);
1690 let args = tcx.mk_args_from_iter(
1691 std::iter::once(ty::GenericArg::from(self_ty))
1692 .chain(args.into_iter().skip(parent_args.len())),
1693 );
1694
1695 Ok(Some((assoc_item, args)))
1696 }
1697
1698 fn probe_assoc_item(
1702 &self,
1703 ident: Ident,
1704 assoc_tag: ty::AssocTag,
1705 block: HirId,
1706 span: Span,
1707 scope: DefId,
1708 ) -> Option<ty::AssocItem> {
1709 let (item, scope) = self.probe_assoc_item_unchecked(ident, assoc_tag, block, scope)?;
1710 self.check_assoc_item(item.def_id, ident, scope, block, span);
1711 Some(item)
1712 }
1713
1714 fn probe_assoc_item_unchecked(
1719 &self,
1720 ident: Ident,
1721 assoc_tag: ty::AssocTag,
1722 block: HirId,
1723 scope: DefId,
1724 ) -> Option<(ty::AssocItem, DefId)> {
1725 let tcx = self.tcx();
1726
1727 let (ident, def_scope) = tcx.adjust_ident_and_get_scope(ident, scope, block);
1728 let item = tcx
1732 .associated_items(scope)
1733 .filter_by_name_unhygienic(ident.name)
1734 .find(|i| i.tag() == assoc_tag && i.ident(tcx).normalize_to_macros_2_0() == ident)?;
1735
1736 Some((*item, def_scope))
1737 }
1738
1739 fn check_assoc_item(
1741 &self,
1742 item_def_id: DefId,
1743 ident: Ident,
1744 scope: DefId,
1745 block: HirId,
1746 span: Span,
1747 ) {
1748 let tcx = self.tcx();
1749
1750 if !tcx.visibility(item_def_id).is_accessible_from(scope, tcx) {
1751 self.dcx().emit_err(crate::errors::AssocItemIsPrivate {
1752 span,
1753 kind: tcx.def_descr(item_def_id),
1754 name: ident,
1755 defined_here_label: tcx.def_span(item_def_id),
1756 });
1757 }
1758
1759 tcx.check_stability(item_def_id, Some(block), span, None);
1760 }
1761
1762 fn probe_traits_that_match_assoc_ty(
1763 &self,
1764 qself_ty: Ty<'tcx>,
1765 assoc_ident: Ident,
1766 ) -> Vec<String> {
1767 let tcx = self.tcx();
1768
1769 let infcx_;
1772 let infcx = if let Some(infcx) = self.infcx() {
1773 infcx
1774 } else {
1775 if !!qself_ty.has_infer() {
::core::panicking::panic("assertion failed: !qself_ty.has_infer()")
};assert!(!qself_ty.has_infer());
1776 infcx_ = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
1777 &infcx_
1778 };
1779
1780 tcx.all_traits_including_private()
1781 .filter(|trait_def_id| {
1782 tcx.associated_items(*trait_def_id)
1784 .in_definition_order()
1785 .any(|i| {
1786 i.is_type()
1787 && !i.is_impl_trait_in_trait()
1788 && i.ident(tcx).normalize_to_macros_2_0() == assoc_ident
1789 })
1790 && tcx.visibility(*trait_def_id)
1792 .is_accessible_from(self.item_def_id(), tcx)
1793 && tcx.all_impls(*trait_def_id)
1794 .any(|impl_def_id| {
1795 let header = tcx.impl_trait_header(impl_def_id);
1796 let trait_ref = header.trait_ref.instantiate(tcx, infcx.fresh_args_for_item(DUMMY_SP, impl_def_id)).skip_norm_wip();
1797
1798 let value = fold_regions(tcx, qself_ty, |_, _| tcx.lifetimes.re_erased);
1799 if value.has_escaping_bound_vars() {
1801 return false;
1802 }
1803 infcx
1804 .can_eq(
1805 ty::ParamEnv::empty(),
1806 trait_ref.self_ty(),
1807 value,
1808 ) && header.polarity != ty::ImplPolarity::Negative
1809 })
1810 })
1811 .map(|trait_def_id| tcx.def_path_str(trait_def_id))
1812 .collect()
1813 }
1814
1815 #[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(1816u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&[],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{ meta.fields().value_set(&[]) })
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Ty<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{
match self.lower_resolved_assoc_item_path(span, opt_self_ty,
item_def_id, trait_segment, item_segment,
ty::AssocTag::Type) {
Ok((item_def_id, item_args)) => {
Ty::new_projection_from_args(self.tcx(), item_def_id,
item_args)
}
Err(guar) => Ty::new_error(self.tcx(), guar),
}
}
}
}#[instrument(level = "debug", skip_all)]
1817 fn lower_resolved_assoc_ty_path(
1818 &self,
1819 span: Span,
1820 opt_self_ty: Option<Ty<'tcx>>,
1821 item_def_id: DefId,
1822 trait_segment: Option<&hir::PathSegment<'tcx>>,
1823 item_segment: &hir::PathSegment<'tcx>,
1824 ) -> Ty<'tcx> {
1825 match self.lower_resolved_assoc_item_path(
1826 span,
1827 opt_self_ty,
1828 item_def_id,
1829 trait_segment,
1830 item_segment,
1831 ty::AssocTag::Type,
1832 ) {
1833 Ok((item_def_id, item_args)) => {
1834 Ty::new_projection_from_args(self.tcx(), item_def_id, item_args)
1835 }
1836 Err(guar) => Ty::new_error(self.tcx(), guar),
1837 }
1838 }
1839
1840 #[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(1841u32),
::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 uv =
ty::UnevaluatedConst::new(tcx,
ty::UnevaluatedConstKind::new_from_def_id(tcx, item_def_id),
item_args);
Ok(Const::new_unevaluated(tcx, uv))
}
}
}#[instrument(level = "debug", skip_all)]
1842 fn lower_resolved_assoc_const_path(
1843 &self,
1844 span: Span,
1845 opt_self_ty: Option<Ty<'tcx>>,
1846 item_def_id: DefId,
1847 trait_segment: Option<&hir::PathSegment<'tcx>>,
1848 item_segment: &hir::PathSegment<'tcx>,
1849 ) -> Result<Const<'tcx>, ErrorGuaranteed> {
1850 let tcx = self.tcx();
1851 let (item_def_id, item_args) = self.lower_resolved_assoc_item_path(
1852 span,
1853 opt_self_ty,
1854 item_def_id,
1855 trait_segment,
1856 item_segment,
1857 ty::AssocTag::Const,
1858 )?;
1859 self.require_type_const_attribute(item_def_id, span)?;
1860 let uv = ty::UnevaluatedConst::new(
1861 tcx,
1862 ty::UnevaluatedConstKind::new_from_def_id(tcx, item_def_id),
1863 item_args,
1864 );
1865 Ok(Const::new_unevaluated(tcx, uv))
1866 }
1867
1868 #[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(1869u32),
::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:1882",
"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(1882u32),
::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:1892",
"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(1892u32),
::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:1896",
"rustc_hir_analysis::hir_ty_lowering",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
::tracing_core::__macro_support::Option::Some(1896u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&["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)]
1870 fn lower_resolved_assoc_item_path(
1871 &self,
1872 span: Span,
1873 opt_self_ty: Option<Ty<'tcx>>,
1874 item_def_id: DefId,
1875 trait_segment: Option<&hir::PathSegment<'tcx>>,
1876 item_segment: &hir::PathSegment<'tcx>,
1877 assoc_tag: ty::AssocTag,
1878 ) -> Result<(DefId, GenericArgsRef<'tcx>), ErrorGuaranteed> {
1879 let tcx = self.tcx();
1880
1881 let trait_def_id = tcx.parent(item_def_id);
1882 debug!(?trait_def_id);
1883
1884 let Some(self_ty) = opt_self_ty else {
1885 return Err(self.report_missing_self_ty_for_resolved_path(
1886 trait_def_id,
1887 span,
1888 item_segment,
1889 assoc_tag,
1890 ));
1891 };
1892 debug!(?self_ty);
1893
1894 let trait_ref =
1895 self.lower_mono_trait_ref(span, trait_def_id, self_ty, trait_segment.unwrap(), false);
1896 debug!(?trait_ref);
1897
1898 let item_args =
1899 self.lower_generic_args_of_assoc_item(span, item_def_id, item_segment, trait_ref.args);
1900
1901 Ok((item_def_id, item_args))
1902 }
1903
1904 pub fn prohibit_generic_args<'a>(
1905 &self,
1906 segments: impl Iterator<Item = &'a hir::PathSegment<'a>> + Clone,
1907 err_extend: GenericsArgsErrExtend<'a>,
1908 ) -> Result<(), ErrorGuaranteed> {
1909 let args_visitors = segments.clone().flat_map(|segment| segment.args().args);
1910 let mut result = Ok(());
1911 if let Some(_) = args_visitors.clone().next() {
1912 result = Err(self.report_prohibited_generic_args(
1913 segments.clone(),
1914 args_visitors,
1915 err_extend,
1916 ));
1917 }
1918
1919 for segment in segments {
1920 if let Some(c) = segment.args().constraints.first() {
1922 return Err(prohibit_assoc_item_constraint(self, c, None));
1923 }
1924 }
1925
1926 result
1927 }
1928
1929 pub fn probe_generic_path_segments(
1947 &self,
1948 segments: &[hir::PathSegment<'_>],
1949 self_ty: Option<Ty<'tcx>>,
1950 kind: DefKind,
1951 def_id: DefId,
1952 span: Span,
1953 ) -> Vec<GenericPathSegment> {
1954 let tcx = self.tcx();
2000
2001 if !!segments.is_empty() {
::core::panicking::panic("assertion failed: !segments.is_empty()")
};assert!(!segments.is_empty());
2002 let last = segments.len() - 1;
2003
2004 let mut generic_segments = ::alloc::vec::Vec::new()vec![];
2005
2006 match kind {
2007 DefKind::Ctor(CtorOf::Struct, ..) => {
2009 let generics = tcx.generics_of(def_id);
2012 let generics_def_id = generics.parent.unwrap_or(def_id);
2015 generic_segments.push(GenericPathSegment(generics_def_id, last));
2016 }
2017
2018 DefKind::Ctor(CtorOf::Variant, ..) | DefKind::Variant => {
2020 let (generics_def_id, index) = if let Some(self_ty) = self_ty {
2021 let adt_def = self.probe_adt(span, self_ty).unwrap();
2024 if true {
if !adt_def.is_enum() {
::core::panicking::panic("assertion failed: adt_def.is_enum()")
};
};debug_assert!(adt_def.is_enum());
2025
2026 (adt_def.did(), last)
2038 } else if let [.., second_to_last, _] = segments
2039 && second_to_last.args.is_some()
2040 && let Res::Def(DefKind::Enum, _) = second_to_last.res
2041 {
2042 let def_id = match kind {
2051 DefKind::Ctor(..) => tcx.parent(def_id),
2052 _ => def_id,
2053 };
2054
2055 let enum_def_id = tcx.parent(def_id);
2057
2058 (enum_def_id, last - 1)
2059 } else {
2060 let generics = tcx.generics_of(def_id);
2067 (generics.parent.unwrap_or(def_id), last)
2070 };
2071 generic_segments.push(GenericPathSegment(generics_def_id, index));
2072 }
2073
2074 DefKind::Fn | DefKind::Const { .. } | DefKind::ConstParam | DefKind::Static { .. } => {
2076 generic_segments.push(GenericPathSegment(def_id, last));
2077 }
2078
2079 DefKind::AssocFn | DefKind::AssocConst { .. } => {
2081 if segments.len() >= 2 {
2082 let generics = tcx.generics_of(def_id);
2083 generic_segments.push(GenericPathSegment(generics.parent.unwrap(), last - 1));
2084 }
2085 generic_segments.push(GenericPathSegment(def_id, last));
2086 }
2087
2088 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),
2089 }
2090
2091 {
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:2091",
"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(2091u32),
::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);
2092
2093 generic_segments
2094 }
2095
2096 #[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(2097u32),
::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:2105",
"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(2105u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&["path.res",
"opt_self_ty", "path.segments"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&path.res)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&opt_self_ty)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&path.segments)
as &dyn Value))])
});
} else { ; }
};
let tcx = self.tcx();
let span = path.span;
match path.res {
Res::Def(DefKind::OpaqueTy, did) => {
{
match tcx.opaque_ty_origin(did) {
hir::OpaqueTyOrigin::TyAlias { .. } => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val,
"hir::OpaqueTyOrigin::TyAlias { .. }",
::core::option::Option::None);
}
}
};
let [leading_segments @ .., segment] =
path.segments else {
::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))
};
let _ =
self.prohibit_generic_args(leading_segments.iter(),
GenericsArgsErrExtend::OpaqueTy);
let args =
self.lower_generic_args_of_path_segment(span, did, segment);
Ty::new_opaque(tcx, did, args)
}
Res::Def(DefKind::Enum | DefKind::TyAlias | DefKind::Struct |
DefKind::Union | DefKind::ForeignTy, did) => {
match (&opt_self_ty, &None) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
};
let [leading_segments @ .., segment] =
path.segments else {
::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))
};
let _ =
self.prohibit_generic_args(leading_segments.iter(),
GenericsArgsErrExtend::None);
self.lower_path_segment(span, did, segment)
}
Res::Def(kind @ DefKind::Variant, def_id) if
let PermitVariants::Yes = permit_variants => {
match (&opt_self_ty, &None) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
};
let generic_segments =
self.probe_generic_path_segments(path.segments, None, kind,
def_id, span);
let indices: FxHashSet<_> =
generic_segments.iter().map(|GenericPathSegment(_, index)|
index).collect();
let _ =
self.prohibit_generic_args(path.segments.iter().enumerate().filter_map(|(index,
seg)|
{
if !indices.contains(&index) { Some(seg) } else { None }
}), GenericsArgsErrExtend::DefVariant(&path.segments));
let &GenericPathSegment(def_id, index) =
generic_segments.last().unwrap();
self.lower_path_segment(span, def_id, &path.segments[index])
}
Res::Def(DefKind::TyParam, def_id) => {
match (&opt_self_ty, &None) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
};
let _ =
self.prohibit_generic_args(path.segments.iter(),
GenericsArgsErrExtend::Param(def_id));
self.lower_ty_param(hir_id)
}
Res::SelfTyParam { .. } => {
match (&opt_self_ty, &None) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
};
let _ =
self.prohibit_generic_args(path.segments.iter(),
if let [hir::PathSegment { args: Some(args), ident, .. }] =
&path.segments {
GenericsArgsErrExtend::SelfTyParam(ident.span.shrink_to_hi().to(args.span_ext))
} else { GenericsArgsErrExtend::None });
self.check_param_uses_if_mcg(tcx.types.self_param, span,
false)
}
Res::SelfTyAlias { alias_to: def_id, .. } => {
match (&opt_self_ty, &None) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
};
let ty =
tcx.at(span).type_of(def_id).instantiate_identity().skip_norm_wip();
let _ =
self.prohibit_generic_args(path.segments.iter(),
GenericsArgsErrExtend::SelfTyAlias { def_id, span });
self.check_param_uses_if_mcg(ty, span, true)
}
Res::Def(DefKind::AssocTy, def_id) => {
let trait_segment =
if let [modules @ .., trait_, _item] = path.segments {
let _ =
self.prohibit_generic_args(modules.iter(),
GenericsArgsErrExtend::None);
Some(trait_)
} else { None };
self.lower_resolved_assoc_ty_path(span, opt_self_ty, def_id,
trait_segment, path.segments.last().unwrap())
}
Res::PrimTy(prim_ty) => {
match (&opt_self_ty, &None) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
};
let _ =
self.prohibit_generic_args(path.segments.iter(),
GenericsArgsErrExtend::PrimTy(prim_ty));
match prim_ty {
hir::PrimTy::Bool => tcx.types.bool,
hir::PrimTy::Char => tcx.types.char,
hir::PrimTy::Int(it) => Ty::new_int(tcx, it),
hir::PrimTy::Uint(uit) => Ty::new_uint(tcx, uit),
hir::PrimTy::Float(ft) => Ty::new_float(tcx, ft),
hir::PrimTy::Str => tcx.types.str_,
}
}
Res::Err => {
let e =
self.tcx().dcx().span_delayed_bug(path.span,
"path with `Res::Err` but no error emitted");
Ty::new_error(tcx, e)
}
Res::Def(..) => {
match (&path.segments.get(0).map(|seg| seg.ident.name),
&Some(kw::SelfUpper)) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val,
::core::option::Option::Some(format_args!("only expected incorrect resolution for `Self`")));
}
}
};
Ty::new_error(self.tcx(),
self.dcx().span_delayed_bug(span,
"incorrect resolution for `Self`"))
}
_ =>
::rustc_middle::util::bug::span_bug_fmt(span,
format_args!("unexpected resolution: {0:?}", path.res)),
}
}
}
}#[instrument(level = "debug", skip_all)]
2098 pub fn lower_resolved_ty_path(
2099 &self,
2100 opt_self_ty: Option<Ty<'tcx>>,
2101 path: &hir::Path<'tcx>,
2102 hir_id: HirId,
2103 permit_variants: PermitVariants,
2104 ) -> Ty<'tcx> {
2105 debug!(?path.res, ?opt_self_ty, ?path.segments);
2106 let tcx = self.tcx();
2107
2108 let span = path.span;
2109 match path.res {
2110 Res::Def(DefKind::OpaqueTy, did) => {
2111 assert_matches!(tcx.opaque_ty_origin(did), hir::OpaqueTyOrigin::TyAlias { .. });
2113 let [leading_segments @ .., segment] = path.segments else { bug!() };
2114 let _ = self.prohibit_generic_args(
2115 leading_segments.iter(),
2116 GenericsArgsErrExtend::OpaqueTy,
2117 );
2118 let args = self.lower_generic_args_of_path_segment(span, did, segment);
2119 Ty::new_opaque(tcx, did, args)
2120 }
2121 Res::Def(
2122 DefKind::Enum
2123 | DefKind::TyAlias
2124 | DefKind::Struct
2125 | DefKind::Union
2126 | DefKind::ForeignTy,
2127 did,
2128 ) => {
2129 assert_eq!(opt_self_ty, None);
2130 let [leading_segments @ .., segment] = path.segments else { bug!() };
2131 let _ = self
2132 .prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
2133 self.lower_path_segment(span, did, segment)
2134 }
2135 Res::Def(kind @ DefKind::Variant, def_id)
2136 if let PermitVariants::Yes = permit_variants =>
2137 {
2138 assert_eq!(opt_self_ty, None);
2141
2142 let generic_segments =
2143 self.probe_generic_path_segments(path.segments, None, kind, def_id, span);
2144 let indices: FxHashSet<_> =
2145 generic_segments.iter().map(|GenericPathSegment(_, index)| index).collect();
2146 let _ = self.prohibit_generic_args(
2147 path.segments.iter().enumerate().filter_map(|(index, seg)| {
2148 if !indices.contains(&index) { Some(seg) } else { None }
2149 }),
2150 GenericsArgsErrExtend::DefVariant(&path.segments),
2151 );
2152
2153 let &GenericPathSegment(def_id, index) = generic_segments.last().unwrap();
2154 self.lower_path_segment(span, def_id, &path.segments[index])
2155 }
2156 Res::Def(DefKind::TyParam, def_id) => {
2157 assert_eq!(opt_self_ty, None);
2158 let _ = self.prohibit_generic_args(
2159 path.segments.iter(),
2160 GenericsArgsErrExtend::Param(def_id),
2161 );
2162 self.lower_ty_param(hir_id)
2163 }
2164 Res::SelfTyParam { .. } => {
2165 assert_eq!(opt_self_ty, None);
2167 let _ = self.prohibit_generic_args(
2168 path.segments.iter(),
2169 if let [hir::PathSegment { args: Some(args), ident, .. }] = &path.segments {
2170 GenericsArgsErrExtend::SelfTyParam(
2171 ident.span.shrink_to_hi().to(args.span_ext),
2172 )
2173 } else {
2174 GenericsArgsErrExtend::None
2175 },
2176 );
2177 self.check_param_uses_if_mcg(tcx.types.self_param, span, false)
2178 }
2179 Res::SelfTyAlias { alias_to: def_id, .. } => {
2180 assert_eq!(opt_self_ty, None);
2182 let ty = tcx.at(span).type_of(def_id).instantiate_identity().skip_norm_wip();
2184 let _ = self.prohibit_generic_args(
2185 path.segments.iter(),
2186 GenericsArgsErrExtend::SelfTyAlias { def_id, span },
2187 );
2188 self.check_param_uses_if_mcg(ty, span, true)
2189 }
2190 Res::Def(DefKind::AssocTy, def_id) => {
2191 let trait_segment = if let [modules @ .., trait_, _item] = path.segments {
2192 let _ = self.prohibit_generic_args(modules.iter(), GenericsArgsErrExtend::None);
2193 Some(trait_)
2194 } else {
2195 None
2196 };
2197 self.lower_resolved_assoc_ty_path(
2198 span,
2199 opt_self_ty,
2200 def_id,
2201 trait_segment,
2202 path.segments.last().unwrap(),
2203 )
2204 }
2205 Res::PrimTy(prim_ty) => {
2206 assert_eq!(opt_self_ty, None);
2207 let _ = self.prohibit_generic_args(
2208 path.segments.iter(),
2209 GenericsArgsErrExtend::PrimTy(prim_ty),
2210 );
2211 match prim_ty {
2212 hir::PrimTy::Bool => tcx.types.bool,
2213 hir::PrimTy::Char => tcx.types.char,
2214 hir::PrimTy::Int(it) => Ty::new_int(tcx, it),
2215 hir::PrimTy::Uint(uit) => Ty::new_uint(tcx, uit),
2216 hir::PrimTy::Float(ft) => Ty::new_float(tcx, ft),
2217 hir::PrimTy::Str => tcx.types.str_,
2218 }
2219 }
2220 Res::Err => {
2221 let e = self
2222 .tcx()
2223 .dcx()
2224 .span_delayed_bug(path.span, "path with `Res::Err` but no error emitted");
2225 Ty::new_error(tcx, e)
2226 }
2227 Res::Def(..) => {
2228 assert_eq!(
2229 path.segments.get(0).map(|seg| seg.ident.name),
2230 Some(kw::SelfUpper),
2231 "only expected incorrect resolution for `Self`"
2232 );
2233 Ty::new_error(
2234 self.tcx(),
2235 self.dcx().span_delayed_bug(span, "incorrect resolution for `Self`"),
2236 )
2237 }
2238 _ => span_bug!(span, "unexpected resolution: {:?}", path.res),
2239 }
2240 }
2241
2242 pub(crate) fn lower_ty_param(&self, hir_id: HirId) -> Ty<'tcx> {
2247 let tcx = self.tcx();
2248
2249 let ty = match tcx.named_bound_var(hir_id) {
2250 Some(rbv::ResolvedArg::LateBound(debruijn, index, def_id)) => {
2251 let br = ty::BoundTy {
2252 var: ty::BoundVar::from_u32(index),
2253 kind: ty::BoundTyKind::Param(def_id.to_def_id()),
2254 };
2255 Ty::new_bound(tcx, debruijn, br)
2256 }
2257 Some(rbv::ResolvedArg::EarlyBound(def_id)) => {
2258 let item_def_id = tcx.hir_ty_param_owner(def_id);
2259 let generics = tcx.generics_of(item_def_id);
2260 let index = generics.param_def_id_to_index[&def_id.to_def_id()];
2261 Ty::new_param(tcx, index, tcx.hir_ty_param_name(def_id))
2262 }
2263 Some(rbv::ResolvedArg::Error(guar)) => Ty::new_error(tcx, guar),
2264 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:?}"),
2265 };
2266 self.check_param_uses_if_mcg(ty, tcx.hir_span(hir_id), false)
2267 }
2268
2269 pub(crate) fn lower_const_param(&self, param_def_id: DefId, path_hir_id: HirId) -> Const<'tcx> {
2274 let tcx = self.tcx();
2275
2276 let ct = match tcx.named_bound_var(path_hir_id) {
2277 Some(rbv::ResolvedArg::EarlyBound(_)) => {
2278 let item_def_id = tcx.parent(param_def_id);
2281 let generics = tcx.generics_of(item_def_id);
2282 let index = generics.param_def_id_to_index[¶m_def_id];
2283 let name = tcx.item_name(param_def_id);
2284 ty::Const::new_param(tcx, ty::ParamConst::new(index, name))
2285 }
2286 Some(rbv::ResolvedArg::LateBound(debruijn, index, _)) => ty::Const::new_bound(
2287 tcx,
2288 debruijn,
2289 ty::BoundConst::new(ty::BoundVar::from_u32(index)),
2290 ),
2291 Some(rbv::ResolvedArg::Error(guar)) => ty::Const::new_error(tcx, guar),
2292 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),
2293 };
2294 self.check_param_uses_if_mcg(ct, tcx.hir_span(path_hir_id), false)
2295 }
2296
2297 #[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(2298u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&["const_arg", "ty"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&const_arg)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Const<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{
let tcx = self.tcx();
if let hir::ConstArgKind::Anon(anon) = &const_arg.kind {
if tcx.features().generic_const_parameter_types() &&
(ty.has_free_regions() || ty.has_erased_regions()) {
let e =
self.dcx().span_err(const_arg.span,
"anonymous constants with lifetimes in their type are not yet supported");
tcx.feed_anon_const_type(anon.def_id,
ty::EarlyBinder::bind(Ty::new_error(tcx, e)));
return ty::Const::new_error(tcx, e);
}
if ty.has_non_region_infer() {
let e =
self.dcx().span_err(const_arg.span,
"anonymous constants with inferred types are not yet supported");
tcx.feed_anon_const_type(anon.def_id,
ty::EarlyBinder::bind(Ty::new_error(tcx, e)));
return ty::Const::new_error(tcx, e);
}
if ty.has_non_region_param() {
let e =
self.dcx().span_err(const_arg.span,
"anonymous constants referencing generics are not yet supported");
tcx.feed_anon_const_type(anon.def_id,
ty::EarlyBinder::bind(Ty::new_error(tcx, e)));
return ty::Const::new_error(tcx, e);
}
tcx.feed_anon_const_type(anon.def_id,
ty::EarlyBinder::bind(ty));
}
let hir_id = const_arg.hir_id;
match const_arg.kind {
hir::ConstArgKind::Tup(exprs) =>
self.lower_const_arg_tup(exprs, ty, const_arg.span),
hir::ConstArgKind::Path(hir::QPath::Resolved(maybe_qself,
path)) => {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs:2350",
"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(2350u32),
::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:2355",
"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(2355u32),
::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")]
2299 pub fn lower_const_arg(&self, const_arg: &hir::ConstArg<'tcx>, ty: Ty<'tcx>) -> Const<'tcx> {
2300 let tcx = self.tcx();
2301
2302 if let hir::ConstArgKind::Anon(anon) = &const_arg.kind {
2303 if tcx.features().generic_const_parameter_types()
2312 && (ty.has_free_regions() || ty.has_erased_regions())
2313 {
2314 let e = self.dcx().span_err(
2315 const_arg.span,
2316 "anonymous constants with lifetimes in their type are not yet supported",
2317 );
2318 tcx.feed_anon_const_type(anon.def_id, ty::EarlyBinder::bind(Ty::new_error(tcx, e)));
2319 return ty::Const::new_error(tcx, e);
2320 }
2321 if ty.has_non_region_infer() {
2325 let e = self.dcx().span_err(
2326 const_arg.span,
2327 "anonymous constants with inferred types are not yet supported",
2328 );
2329 tcx.feed_anon_const_type(anon.def_id, ty::EarlyBinder::bind(Ty::new_error(tcx, e)));
2330 return ty::Const::new_error(tcx, e);
2331 }
2332 if ty.has_non_region_param() {
2335 let e = self.dcx().span_err(
2336 const_arg.span,
2337 "anonymous constants referencing generics are not yet supported",
2338 );
2339 tcx.feed_anon_const_type(anon.def_id, ty::EarlyBinder::bind(Ty::new_error(tcx, e)));
2340 return ty::Const::new_error(tcx, e);
2341 }
2342
2343 tcx.feed_anon_const_type(anon.def_id, ty::EarlyBinder::bind(ty));
2344 }
2345
2346 let hir_id = const_arg.hir_id;
2347 match const_arg.kind {
2348 hir::ConstArgKind::Tup(exprs) => self.lower_const_arg_tup(exprs, ty, const_arg.span),
2349 hir::ConstArgKind::Path(hir::QPath::Resolved(maybe_qself, path)) => {
2350 debug!(?maybe_qself, ?path);
2351 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
2352 self.lower_resolved_const_path(opt_self_ty, path, hir_id)
2353 }
2354 hir::ConstArgKind::Path(hir::QPath::TypeRelative(hir_self_ty, segment)) => {
2355 debug!(?hir_self_ty, ?segment);
2356 let self_ty = self.lower_ty(hir_self_ty);
2357 self.lower_type_relative_const_path(
2358 self_ty,
2359 hir_self_ty,
2360 segment,
2361 hir_id,
2362 const_arg.span,
2363 )
2364 .unwrap_or_else(|guar| Const::new_error(tcx, guar))
2365 }
2366 hir::ConstArgKind::Struct(qpath, inits) => {
2367 self.lower_const_arg_struct(hir_id, qpath, inits, const_arg.span)
2368 }
2369 hir::ConstArgKind::TupleCall(qpath, args) => {
2370 self.lower_const_arg_tuple_call(hir_id, qpath, args, const_arg.span)
2371 }
2372 hir::ConstArgKind::Array(array_expr) => self.lower_const_arg_array(array_expr, ty),
2373 hir::ConstArgKind::Anon(anon) => self.lower_const_arg_anon(anon),
2374 hir::ConstArgKind::Infer(()) => self.ct_infer(None, const_arg.span),
2375 hir::ConstArgKind::Error(e) => ty::Const::new_error(tcx, e),
2376 hir::ConstArgKind::Literal { lit, negated } => {
2377 self.lower_const_arg_literal(&lit, negated, ty, const_arg.span)
2378 }
2379 }
2380 }
2381
2382 fn lower_const_arg_array(
2383 &self,
2384 array_expr: &'tcx hir::ConstArgArrayExpr<'tcx>,
2385 ty: Ty<'tcx>,
2386 ) -> Const<'tcx> {
2387 let tcx = self.tcx();
2388
2389 let elem_ty = match ty.kind() {
2390 ty::Array(elem_ty, _) => elem_ty,
2391 ty::Error(e) => return Const::new_error(tcx, *e),
2392 _ => {
2393 let e = tcx
2394 .dcx()
2395 .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));
2396 return Const::new_error(tcx, e);
2397 }
2398 };
2399
2400 let elems = array_expr
2401 .elems
2402 .iter()
2403 .map(|elem| self.lower_const_arg(elem, *elem_ty))
2404 .collect::<Vec<_>>();
2405
2406 let valtree = ty::ValTree::from_branches(tcx, elems);
2407
2408 ty::Const::new_value(tcx, valtree, ty)
2409 }
2410
2411 fn lower_const_arg_tuple_call(
2412 &self,
2413 hir_id: HirId,
2414 qpath: hir::QPath<'tcx>,
2415 args: &'tcx [&'tcx hir::ConstArg<'tcx>],
2416 span: Span,
2417 ) -> Const<'tcx> {
2418 let tcx = self.tcx();
2419
2420 let non_adt_or_variant_res = || {
2421 let e = tcx.dcx().span_err(span, "tuple constructor with invalid base path");
2422 ty::Const::new_error(tcx, e)
2423 };
2424
2425 let ctor_const = match qpath {
2426 hir::QPath::Resolved(maybe_qself, path) => {
2427 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
2428 self.lower_resolved_const_path(opt_self_ty, path, hir_id)
2429 }
2430 hir::QPath::TypeRelative(hir_self_ty, segment) => {
2431 let self_ty = self.lower_ty(hir_self_ty);
2432 match self.lower_type_relative_const_path(
2433 self_ty,
2434 hir_self_ty,
2435 segment,
2436 hir_id,
2437 span,
2438 ) {
2439 Ok(c) => c,
2440 Err(_) => return non_adt_or_variant_res(),
2441 }
2442 }
2443 };
2444
2445 let Some(value) = ctor_const.try_to_value() else {
2446 return non_adt_or_variant_res();
2447 };
2448
2449 let (adt_def, adt_args, variant_did) = match value.ty.kind() {
2450 ty::FnDef(def_id, fn_args)
2451 if let DefKind::Ctor(CtorOf::Variant, _) = tcx.def_kind(*def_id) =>
2452 {
2453 let parent_did = tcx.parent(*def_id);
2454 let enum_did = tcx.parent(parent_did);
2455 (tcx.adt_def(enum_did), fn_args, parent_did)
2456 }
2457 ty::FnDef(def_id, fn_args)
2458 if let DefKind::Ctor(CtorOf::Struct, _) = tcx.def_kind(*def_id) =>
2459 {
2460 let parent_did = tcx.parent(*def_id);
2461 (tcx.adt_def(parent_did), fn_args, parent_did)
2462 }
2463 _ => {
2464 let e = self.dcx().span_err(
2465 span,
2466 "complex const arguments must be placed inside of a `const` block",
2467 );
2468 return Const::new_error(tcx, e);
2469 }
2470 };
2471
2472 let variant_def = adt_def.variant_with_id(variant_did);
2473 let variant_idx = adt_def.variant_index_with_id(variant_did).as_u32();
2474
2475 if args.len() != variant_def.fields.len() {
2476 let e = tcx.dcx().span_err(
2477 span,
2478 ::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!(
2479 "tuple constructor has {} arguments but {} were provided",
2480 variant_def.fields.len(),
2481 args.len()
2482 ),
2483 );
2484 return ty::Const::new_error(tcx, e);
2485 }
2486
2487 let fields = variant_def
2488 .fields
2489 .iter()
2490 .zip(args)
2491 .map(|(field_def, arg)| {
2492 self.lower_const_arg(
2493 arg,
2494 tcx.type_of(field_def.did).instantiate(tcx, adt_args).skip_norm_wip(),
2495 )
2496 })
2497 .collect::<Vec<_>>();
2498
2499 let opt_discr_const = if adt_def.is_enum() {
2500 let valtree = ty::ValTree::from_scalar_int(tcx, variant_idx.into());
2501 Some(ty::Const::new_value(tcx, valtree, tcx.types.u32))
2502 } else {
2503 None
2504 };
2505
2506 let valtree = ty::ValTree::from_branches(tcx, opt_discr_const.into_iter().chain(fields));
2507 let adt_ty = Ty::new_adt(tcx, adt_def, adt_args);
2508 ty::Const::new_value(tcx, valtree, adt_ty)
2509 }
2510
2511 fn lower_const_arg_tup(
2512 &self,
2513 exprs: &'tcx [&'tcx hir::ConstArg<'tcx>],
2514 ty: Ty<'tcx>,
2515 span: Span,
2516 ) -> Const<'tcx> {
2517 let tcx = self.tcx();
2518
2519 let tys = match ty.kind() {
2520 ty::Tuple(tys) => tys,
2521 ty::Error(e) => return Const::new_error(tcx, *e),
2522 _ => {
2523 let e = tcx.dcx().span_err(span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected `{0}`, found const tuple",
ty))
})format!("expected `{}`, found const tuple", ty));
2524 return Const::new_error(tcx, e);
2525 }
2526 };
2527
2528 let exprs = exprs
2529 .iter()
2530 .zip(tys.iter())
2531 .map(|(expr, ty)| self.lower_const_arg(expr, ty))
2532 .collect::<Vec<_>>();
2533
2534 let valtree = ty::ValTree::from_branches(tcx, exprs);
2535 ty::Const::new_value(tcx, valtree, ty)
2536 }
2537
2538 fn lower_const_arg_struct(
2539 &self,
2540 hir_id: HirId,
2541 qpath: hir::QPath<'tcx>,
2542 inits: &'tcx [&'tcx hir::ConstArgExprField<'tcx>],
2543 span: Span,
2544 ) -> Const<'tcx> {
2545 let tcx = self.tcx();
2548
2549 let non_adt_or_variant_res = || {
2550 let e = tcx.dcx().span_err(span, "struct expression with invalid base path");
2551 ty::Const::new_error(tcx, e)
2552 };
2553
2554 let ResolvedStructPath { res: opt_res, ty } =
2555 self.lower_path_for_struct_expr(qpath, span, hir_id);
2556
2557 let variant_did = match qpath {
2558 hir::QPath::Resolved(maybe_qself, path) => {
2559 {
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:2559",
"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(2559u32),
::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);
2560 let variant_did = match path.res {
2561 Res::Def(DefKind::Variant | DefKind::Struct, did) => did,
2562 _ => return non_adt_or_variant_res(),
2563 };
2564
2565 variant_did
2566 }
2567 hir::QPath::TypeRelative(hir_self_ty, segment) => {
2568 {
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:2568",
"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(2568u32),
::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);
2569
2570 let res_def_id = match opt_res {
2571 Ok(r)
2572 if #[allow(non_exhaustive_omitted_patterns)] match tcx.def_kind(r.def_id()) {
DefKind::Variant | DefKind::Struct => true,
_ => false,
}matches!(
2573 tcx.def_kind(r.def_id()),
2574 DefKind::Variant | DefKind::Struct
2575 ) =>
2576 {
2577 r.def_id()
2578 }
2579 Ok(_) => return non_adt_or_variant_res(),
2580 Err(e) => return ty::Const::new_error(tcx, e),
2581 };
2582
2583 res_def_id
2584 }
2585 };
2586
2587 let ty::Adt(adt_def, adt_args) = ty.kind() else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
2588
2589 let variant_def = adt_def.variant_with_id(variant_did);
2590 let variant_idx = adt_def.variant_index_with_id(variant_did).as_u32();
2591
2592 let fields = variant_def
2593 .fields
2594 .iter()
2595 .map(|field_def| {
2596 let mut init_expr =
2599 inits.iter().filter(|init_expr| init_expr.field.name == field_def.name);
2600
2601 match init_expr.next() {
2602 Some(expr) => {
2603 if let Some(expr) = init_expr.next() {
2604 let e = tcx.dcx().span_err(
2605 expr.span,
2606 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("struct expression with multiple initialisers for `{0}`",
field_def.name))
})format!(
2607 "struct expression with multiple initialisers for `{}`",
2608 field_def.name,
2609 ),
2610 );
2611 return ty::Const::new_error(tcx, e);
2612 }
2613
2614 self.lower_const_arg(
2615 expr.expr,
2616 tcx.type_of(field_def.did).instantiate(tcx, adt_args).skip_norm_wip(),
2617 )
2618 }
2619 None => {
2620 let e = tcx.dcx().span_err(
2621 span,
2622 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("struct expression with missing field initialiser for `{0}`",
field_def.name))
})format!(
2623 "struct expression with missing field initialiser for `{}`",
2624 field_def.name
2625 ),
2626 );
2627 ty::Const::new_error(tcx, e)
2628 }
2629 }
2630 })
2631 .collect::<Vec<_>>();
2632
2633 let opt_discr_const = if adt_def.is_enum() {
2634 let valtree = ty::ValTree::from_scalar_int(tcx, variant_idx.into());
2635 Some(ty::Const::new_value(tcx, valtree, tcx.types.u32))
2636 } else {
2637 None
2638 };
2639
2640 let valtree = ty::ValTree::from_branches(tcx, opt_discr_const.into_iter().chain(fields));
2641 ty::Const::new_value(tcx, valtree, ty)
2642 }
2643
2644 pub fn lower_path_for_struct_expr(
2645 &self,
2646 qpath: hir::QPath<'tcx>,
2647 path_span: Span,
2648 hir_id: HirId,
2649 ) -> ResolvedStructPath<'tcx> {
2650 match qpath {
2651 hir::QPath::Resolved(ref maybe_qself, path) => {
2652 let self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
2653 let ty = self.lower_resolved_ty_path(self_ty, path, hir_id, PermitVariants::Yes);
2654 ResolvedStructPath { res: Ok(path.res), ty }
2655 }
2656 hir::QPath::TypeRelative(hir_self_ty, segment) => {
2657 let self_ty = self.lower_ty(hir_self_ty);
2658
2659 let result = self.lower_type_relative_ty_path(
2660 self_ty,
2661 hir_self_ty,
2662 segment,
2663 hir_id,
2664 path_span,
2665 PermitVariants::Yes,
2666 );
2667 let ty = result
2668 .map(|(ty, _, _)| ty)
2669 .unwrap_or_else(|guar| Ty::new_error(self.tcx(), guar));
2670
2671 ResolvedStructPath {
2672 res: result.map(|(_, kind, def_id)| Res::Def(kind, def_id)),
2673 ty,
2674 }
2675 }
2676 }
2677 }
2678
2679 fn lower_resolved_const_path(
2681 &self,
2682 opt_self_ty: Option<Ty<'tcx>>,
2683 path: &hir::Path<'tcx>,
2684 hir_id: HirId,
2685 ) -> Const<'tcx> {
2686 let tcx = self.tcx();
2687 let span = path.span;
2688 let ct = match path.res {
2689 Res::Def(DefKind::ConstParam, def_id) => {
2690 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);
2691 let _ = self.prohibit_generic_args(
2692 path.segments.iter(),
2693 GenericsArgsErrExtend::Param(def_id),
2694 );
2695 self.lower_const_param(def_id, hir_id)
2696 }
2697 Res::Def(DefKind::Const { .. }, did) => {
2698 if let Err(guar) = self.require_type_const_attribute(did, span) {
2699 return Const::new_error(self.tcx(), guar);
2700 }
2701
2702 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);
2703 let [leading_segments @ .., segment] = path.segments else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
2704 let _ = self
2705 .prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
2706 let args = self.lower_generic_args_of_path_segment(span, did, segment);
2707 ty::Const::new_unevaluated(
2708 tcx,
2709 ty::UnevaluatedConst::new(
2710 tcx,
2711 ty::UnevaluatedConstKind::new_from_def_id(tcx, did),
2712 args,
2713 ),
2714 )
2715 }
2716 Res::Def(DefKind::Ctor(ctor_of, CtorKind::Const), did) => {
2717 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);
2718 let [leading_segments @ .., segment] = path.segments else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
2719 let _ = self
2720 .prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
2721
2722 let parent_did = tcx.parent(did);
2723 let generics_did = match ctor_of {
2724 CtorOf::Variant => tcx.parent(parent_did),
2725 CtorOf::Struct => parent_did,
2726 };
2727 let args = self.lower_generic_args_of_path_segment(span, generics_did, segment);
2728
2729 self.construct_const_ctor_value(did, ctor_of, args)
2730 }
2731 Res::Def(DefKind::Ctor(_, CtorKind::Fn), did) => {
2732 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);
2733 let [leading_segments @ .., segment] = path.segments else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
2734 let _ = self
2735 .prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
2736 let parent_did = tcx.parent(did);
2737 let generics_did = if let DefKind::Ctor(CtorOf::Variant, _) = tcx.def_kind(did) {
2738 tcx.parent(parent_did)
2739 } else {
2740 parent_did
2741 };
2742 let args = self.lower_generic_args_of_path_segment(span, generics_did, segment);
2743 ty::Const::zero_sized(tcx, Ty::new_fn_def(tcx, did, args))
2744 }
2745 Res::Def(DefKind::AssocConst { .. }, did) => {
2746 let trait_segment = if let [modules @ .., trait_, _item] = path.segments {
2747 let _ = self.prohibit_generic_args(modules.iter(), GenericsArgsErrExtend::None);
2748 Some(trait_)
2749 } else {
2750 None
2751 };
2752 self.lower_resolved_assoc_const_path(
2753 span,
2754 opt_self_ty,
2755 did,
2756 trait_segment,
2757 path.segments.last().unwrap(),
2758 )
2759 .unwrap_or_else(|guar| Const::new_error(tcx, guar))
2760 }
2761 Res::Def(DefKind::Static { .. }, _) => {
2762 ::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")
2763 }
2764 Res::Def(DefKind::Fn | DefKind::AssocFn, did) => {
2766 self.dcx().span_delayed_bug(span, "function items cannot be used as const args");
2767 let args = self.lower_generic_args_of_path_segment(
2768 span,
2769 did,
2770 path.segments.last().unwrap(),
2771 );
2772 ty::Const::zero_sized(tcx, Ty::new_fn_def(tcx, did, args))
2773 }
2774
2775 res @ (Res::Def(
2778 DefKind::Mod
2779 | DefKind::Enum
2780 | DefKind::Variant
2781 | DefKind::Struct
2782 | DefKind::OpaqueTy
2783 | DefKind::TyAlias
2784 | DefKind::TraitAlias
2785 | DefKind::AssocTy
2786 | DefKind::Union
2787 | DefKind::Trait
2788 | DefKind::ForeignTy
2789 | DefKind::TyParam
2790 | DefKind::Macro(_)
2791 | DefKind::LifetimeParam
2792 | DefKind::Use
2793 | DefKind::ForeignMod
2794 | DefKind::AnonConst
2795 | DefKind::InlineConst
2796 | DefKind::Field
2797 | DefKind::Impl { .. }
2798 | DefKind::Closure
2799 | DefKind::ExternCrate
2800 | DefKind::GlobalAsm
2801 | DefKind::SyntheticCoroutineBody,
2802 _,
2803 )
2804 | Res::PrimTy(_)
2805 | Res::SelfTyParam { .. }
2806 | Res::SelfTyAlias { .. }
2807 | Res::SelfCtor(_)
2808 | Res::Local(_)
2809 | Res::ToolMod
2810 | Res::OpenMod(..)
2811 | Res::NonMacroAttr(_)
2812 | Res::Err) => Const::new_error_with_message(
2813 tcx,
2814 span,
2815 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("invalid Res {0:?} for const path",
res))
})format!("invalid Res {res:?} for const path"),
2816 ),
2817 };
2818 self.check_param_uses_if_mcg(ct, span, false)
2819 }
2820
2821 #[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(2822u32),
::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:2827",
"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(2827u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&["expr"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&expr) as
&dyn Value))])
});
} else { ; }
};
let ty =
tcx.type_of(anon.def_id).instantiate_identity().skip_norm_wip();
match self.try_lower_anon_const_lit(ty, expr) {
Some(v) => v,
None =>
ty::Const::new_unevaluated(tcx,
ty::UnevaluatedConst::new(tcx,
ty::UnevaluatedConstKind::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")]
2823 fn lower_const_arg_anon(&self, anon: &AnonConst) -> Const<'tcx> {
2824 let tcx = self.tcx();
2825
2826 let expr = &tcx.hir_body(anon.body).value;
2827 debug!(?expr);
2828
2829 let ty = tcx.type_of(anon.def_id).instantiate_identity().skip_norm_wip();
2833
2834 match self.try_lower_anon_const_lit(ty, expr) {
2835 Some(v) => v,
2836 None => ty::Const::new_unevaluated(
2837 tcx,
2838 ty::UnevaluatedConst::new(
2839 tcx,
2840 ty::UnevaluatedConstKind::Anon { def_id: anon.def_id.to_def_id() },
2841 ty::GenericArgs::identity_for_item(tcx, anon.def_id.to_def_id()),
2842 ),
2843 ),
2844 }
2845 }
2846
2847 #[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(2847u32),
::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")]
2848 fn lower_const_arg_literal(
2849 &self,
2850 kind: &LitKind,
2851 neg: bool,
2852 ty: Ty<'tcx>,
2853 span: Span,
2854 ) -> Const<'tcx> {
2855 let tcx = self.tcx();
2856
2857 let ty = if !ty.has_infer() { Some(ty) } else { None };
2858
2859 if let LitKind::Err(guar) = *kind {
2860 return ty::Const::new_error(tcx, guar);
2861 }
2862 let input = LitToConstInput { lit: *kind, ty, neg };
2863 match tcx.at(span).lit_to_const(input) {
2864 Some(value) => ty::Const::new_value(tcx, value.valtree, value.ty),
2865 None => {
2866 let e = tcx.dcx().span_err(span, "type annotations needed for the literal");
2867 ty::Const::new_error(tcx, e)
2868 }
2869 }
2870 }
2871
2872 #[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(2872u32),
::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")]
2873 fn try_lower_anon_const_lit(
2874 &self,
2875 ty: Ty<'tcx>,
2876 expr: &'tcx hir::Expr<'tcx>,
2877 ) -> Option<Const<'tcx>> {
2878 let tcx = self.tcx();
2879
2880 let expr = match &expr.kind {
2883 hir::ExprKind::Block(block, _) if block.stmts.is_empty() && block.expr.is_some() => {
2884 block.expr.as_ref().unwrap()
2885 }
2886 _ => expr,
2887 };
2888
2889 let lit_input = match expr.kind {
2890 hir::ExprKind::Lit(lit) => {
2891 Some(LitToConstInput { lit: lit.node, ty: Some(ty), neg: false })
2892 }
2893 hir::ExprKind::Unary(hir::UnOp::Neg, expr) => match expr.kind {
2894 hir::ExprKind::Lit(lit) => {
2895 Some(LitToConstInput { lit: lit.node, ty: Some(ty), neg: true })
2896 }
2897 _ => None,
2898 },
2899 _ => None,
2900 };
2901
2902 lit_input.and_then(|l| {
2903 if const_lit_matches_ty(tcx, &l.lit, ty, l.neg) {
2904 tcx.at(expr.span)
2905 .lit_to_const(l)
2906 .map(|value| ty::Const::new_value(tcx, value.valtree, value.ty))
2907 } else {
2908 None
2909 }
2910 })
2911 }
2912
2913 fn require_type_const_attribute(
2914 &self,
2915 def_id: DefId,
2916 span: Span,
2917 ) -> Result<(), ErrorGuaranteed> {
2918 let tcx = self.tcx();
2919 let is_inherent_assoc_const = tcx.def_kind(def_id)
2922 == DefKind::AssocConst { is_type_const: false }
2923 && tcx.def_kind(tcx.parent(def_id)) == DefKind::Impl { of_trait: false };
2924 if tcx.is_type_const(def_id)
2925 || tcx.features().generic_const_args() && !is_inherent_assoc_const
2926 {
2927 Ok(())
2928 } else {
2929 let mut err = self.dcx().struct_span_err(
2930 span,
2931 "use of `const` in the type system not defined as `type const`",
2932 );
2933 if def_id.is_local() {
2934 let name = tcx.def_path_str(def_id);
2935 err.span_suggestion_verbose(
2936 tcx.def_span(def_id).shrink_to_lo(),
2937 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("add `type` before `const` for `{0}`",
name))
})format!("add `type` before `const` for `{name}`"),
2938 ::alloc::__export::must_use({ ::alloc::fmt::format(format_args!("type ")) })format!("type "),
2939 Applicability::MaybeIncorrect,
2940 );
2941 } else {
2942 err.note("only consts marked defined as `type const` may be used in types");
2943 }
2944 Err(err.emit())
2945 }
2946 }
2947
2948 fn lower_delegation_ty(&self, infer: hir::InferDelegation<'tcx>) -> Ty<'tcx> {
2949 match infer {
2950 hir::InferDelegation::DefId(def_id) => {
2951 self.tcx().type_of(def_id).instantiate_identity().skip_norm_wip()
2952 }
2953 rustc_hir::InferDelegation::Sig(_, idx) => {
2954 let delegation_sig = self.tcx().inherit_sig_for_delegation_item(self.item_def_id());
2955
2956 match idx {
2957 hir::InferDelegationSig::Input(idx) => delegation_sig[idx],
2958 hir::InferDelegationSig::Output { .. } => *delegation_sig.last().unwrap(),
2959 }
2960 }
2961 }
2962 }
2963
2964 x;#[instrument(level = "debug", skip(self), ret)]
2966 pub fn lower_ty(&self, hir_ty: &hir::Ty<'tcx>) -> Ty<'tcx> {
2967 let tcx = self.tcx();
2968
2969 let result_ty = match &hir_ty.kind {
2970 hir::TyKind::InferDelegation(infer) => self.lower_delegation_ty(*infer),
2971 hir::TyKind::Slice(ty) => Ty::new_slice(tcx, self.lower_ty(ty)),
2972 hir::TyKind::Ptr(mt) => Ty::new_ptr(tcx, self.lower_ty(mt.ty), mt.mutbl),
2973 hir::TyKind::Ref(region, mt) => {
2974 let r = self.lower_lifetime(region, RegionInferReason::Reference);
2975 debug!(?r);
2976 let t = self.lower_ty(mt.ty);
2977 Ty::new_ref(tcx, r, t, mt.mutbl)
2978 }
2979 hir::TyKind::Never => tcx.types.never,
2980 hir::TyKind::Tup(fields) => {
2981 Ty::new_tup_from_iter(tcx, fields.iter().map(|t| self.lower_ty(t)))
2982 }
2983 hir::TyKind::FnPtr(bf) => {
2984 check_c_variadic_abi(tcx, bf.decl, bf.abi, hir_ty.span);
2985
2986 Ty::new_fn_ptr(
2987 tcx,
2988 self.lower_fn_ty(hir_ty.hir_id, bf.safety, bf.abi, bf.decl, None, Some(hir_ty)),
2989 )
2990 }
2991 hir::TyKind::UnsafeBinder(binder) => Ty::new_unsafe_binder(
2992 tcx,
2993 ty::Binder::bind_with_vars(
2994 self.lower_ty(binder.inner_ty),
2995 tcx.late_bound_vars(hir_ty.hir_id),
2996 ),
2997 ),
2998 hir::TyKind::TraitObject(bounds, tagged_ptr) => {
2999 let lifetime = tagged_ptr.pointer();
3000 let syntax = tagged_ptr.tag();
3001 self.lower_trait_object_ty(hir_ty.span, hir_ty.hir_id, bounds, lifetime, syntax)
3002 }
3003 hir::TyKind::Path(hir::QPath::Resolved(_, path))
3007 if path.segments.last().and_then(|segment| segment.args).is_some_and(|args| {
3008 matches!(args.parenthesized, hir::GenericArgsParentheses::ReturnTypeNotation)
3009 }) =>
3010 {
3011 let guar = self
3012 .dcx()
3013 .emit_err(BadReturnTypeNotation { span: hir_ty.span, suggestion: None });
3014 Ty::new_error(tcx, guar)
3015 }
3016 hir::TyKind::Path(hir::QPath::Resolved(maybe_qself, path)) => {
3017 debug!(?maybe_qself, ?path);
3018 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
3019 self.lower_resolved_ty_path(opt_self_ty, path, hir_ty.hir_id, PermitVariants::No)
3020 }
3021 &hir::TyKind::OpaqueDef(opaque_ty) => {
3022 let in_trait = match opaque_ty.origin {
3026 hir::OpaqueTyOrigin::FnReturn {
3027 parent,
3028 in_trait_or_impl: Some(hir::RpitContext::Trait),
3029 ..
3030 }
3031 | hir::OpaqueTyOrigin::AsyncFn {
3032 parent,
3033 in_trait_or_impl: Some(hir::RpitContext::Trait),
3034 ..
3035 } => Some(parent),
3036 hir::OpaqueTyOrigin::FnReturn {
3037 in_trait_or_impl: None | Some(hir::RpitContext::TraitImpl),
3038 ..
3039 }
3040 | hir::OpaqueTyOrigin::AsyncFn {
3041 in_trait_or_impl: None | Some(hir::RpitContext::TraitImpl),
3042 ..
3043 }
3044 | hir::OpaqueTyOrigin::TyAlias { .. } => None,
3045 };
3046
3047 self.lower_opaque_ty(opaque_ty.def_id, in_trait)
3048 }
3049 hir::TyKind::TraitAscription(hir_bounds) => {
3050 let self_ty = self.ty_infer(None, hir_ty.span);
3053 let mut bounds = Vec::new();
3054 self.lower_bounds(
3055 self_ty,
3056 hir_bounds.iter(),
3057 &mut bounds,
3058 ty::List::empty(),
3059 PredicateFilter::All,
3060 OverlappingAsssocItemConstraints::Allowed,
3061 );
3062 self.add_implicit_sizedness_bounds(
3063 &mut bounds,
3064 self_ty,
3065 hir_bounds,
3066 ImpliedBoundsContext::AssociatedTypeOrImplTrait,
3067 hir_ty.span,
3068 );
3069 self.register_trait_ascription_bounds(bounds, hir_ty.hir_id, hir_ty.span);
3070 self_ty
3071 }
3072 hir::TyKind::Path(hir::QPath::TypeRelative(hir_self_ty, segment))
3076 if segment.args.is_some_and(|args| {
3077 matches!(args.parenthesized, hir::GenericArgsParentheses::ReturnTypeNotation)
3078 }) =>
3079 {
3080 let guar = if let hir::Node::LetStmt(stmt) = tcx.parent_hir_node(hir_ty.hir_id)
3081 && let None = stmt.init
3082 && let hir::TyKind::Path(hir::QPath::Resolved(_, self_ty_path)) =
3083 hir_self_ty.kind
3084 && let Res::Def(DefKind::Enum | DefKind::Struct | DefKind::Union, def_id) =
3085 self_ty_path.res
3086 && let Some(_) = tcx
3087 .inherent_impls(def_id)
3088 .iter()
3089 .flat_map(|imp| {
3090 tcx.associated_items(*imp).filter_by_name_unhygienic(segment.ident.name)
3091 })
3092 .filter(|assoc| {
3093 matches!(assoc.kind, ty::AssocKind::Fn { has_self: false, .. })
3094 })
3095 .next()
3096 {
3097 let err = tcx
3099 .dcx()
3100 .struct_span_err(
3101 hir_ty.span,
3102 "expected type, found associated function call",
3103 )
3104 .with_span_suggestion_verbose(
3105 stmt.pat.span.between(hir_ty.span),
3106 "use `=` if you meant to assign",
3107 " = ".to_string(),
3108 Applicability::MaybeIncorrect,
3109 );
3110 self.dcx().try_steal_replace_and_emit_err(
3111 hir_ty.span,
3112 StashKey::ReturnTypeNotation,
3113 err,
3114 )
3115 } else if let hir::Node::LetStmt(stmt) = tcx.parent_hir_node(hir_ty.hir_id)
3116 && let None = stmt.init
3117 && let hir::TyKind::Path(hir::QPath::Resolved(_, self_ty_path)) =
3118 hir_self_ty.kind
3119 && let Res::PrimTy(_) = self_ty_path.res
3120 && self.dcx().has_stashed_diagnostic(hir_ty.span, StashKey::ReturnTypeNotation)
3121 {
3122 let err = tcx
3125 .dcx()
3126 .struct_span_err(
3127 hir_ty.span,
3128 "expected type, found associated function call",
3129 )
3130 .with_span_suggestion_verbose(
3131 stmt.pat.span.between(hir_ty.span),
3132 "use `=` if you meant to assign",
3133 " = ".to_string(),
3134 Applicability::MaybeIncorrect,
3135 );
3136 self.dcx().try_steal_replace_and_emit_err(
3137 hir_ty.span,
3138 StashKey::ReturnTypeNotation,
3139 err,
3140 )
3141 } else {
3142 let suggestion = if self
3143 .dcx()
3144 .has_stashed_diagnostic(hir_ty.span, StashKey::ReturnTypeNotation)
3145 {
3146 Some(segment.ident.span.shrink_to_hi().with_hi(hir_ty.span.hi()))
3152 } else {
3153 None
3154 };
3155 let err = self
3156 .dcx()
3157 .create_err(BadReturnTypeNotation { span: hir_ty.span, suggestion });
3158 self.dcx().try_steal_replace_and_emit_err(
3159 hir_ty.span,
3160 StashKey::ReturnTypeNotation,
3161 err,
3162 )
3163 };
3164 Ty::new_error(tcx, guar)
3165 }
3166 hir::TyKind::Path(hir::QPath::TypeRelative(hir_self_ty, segment)) => {
3167 debug!(?hir_self_ty, ?segment);
3168 let self_ty = self.lower_ty(hir_self_ty);
3169 self.lower_type_relative_ty_path(
3170 self_ty,
3171 hir_self_ty,
3172 segment,
3173 hir_ty.hir_id,
3174 hir_ty.span,
3175 PermitVariants::No,
3176 )
3177 .map(|(ty, _, _)| ty)
3178 .unwrap_or_else(|guar| Ty::new_error(tcx, guar))
3179 }
3180 hir::TyKind::Array(ty, length) => {
3181 let length = self.lower_const_arg(length, tcx.types.usize);
3182 Ty::new_array_with_const_len(tcx, self.lower_ty(ty), length)
3183 }
3184 hir::TyKind::Infer(()) => {
3185 self.ty_infer(None, hir_ty.span)
3190 }
3191 hir::TyKind::Pat(ty, pat) => {
3192 let ty_span = ty.span;
3193 let ty = self.lower_ty(ty);
3194 let pat_ty = match self.lower_pat_ty_pat(ty, ty_span, pat) {
3195 Ok(kind) => Ty::new_pat(tcx, ty, tcx.mk_pat(kind)),
3196 Err(guar) => Ty::new_error(tcx, guar),
3197 };
3198 self.record_ty(pat.hir_id, ty, pat.span);
3199 pat_ty
3200 }
3201 hir::TyKind::FieldOf(ty, hir::TyFieldPath { variant, field }) => self.lower_field_of(
3202 self.lower_ty(ty),
3203 self.item_def_id(),
3204 ty.span,
3205 hir_ty.hir_id,
3206 *variant,
3207 *field,
3208 ),
3209 hir::TyKind::Err(guar) => Ty::new_error(tcx, *guar),
3210 };
3211
3212 self.record_ty(hir_ty.hir_id, result_ty, hir_ty.span);
3213 result_ty
3214 }
3215
3216 fn lower_pat_ty_pat(
3217 &self,
3218 ty: Ty<'tcx>,
3219 ty_span: Span,
3220 pat: &hir::TyPat<'tcx>,
3221 ) -> Result<ty::PatternKind<'tcx>, ErrorGuaranteed> {
3222 let tcx = self.tcx();
3223 match pat.kind {
3224 hir::TyPatKind::Range(start, end) => {
3225 match ty.kind() {
3226 ty::Int(_) | ty::Uint(_) | ty::Char => {
3229 let start = self.lower_const_arg(start, ty);
3230 let end = self.lower_const_arg(end, ty);
3231 Ok(ty::PatternKind::Range { start, end })
3232 }
3233 _ => Err(self
3234 .dcx()
3235 .span_delayed_bug(ty_span, "invalid base type for range pattern")),
3236 }
3237 }
3238 hir::TyPatKind::NotNull => Ok(ty::PatternKind::NotNull),
3239 hir::TyPatKind::Or(patterns) => {
3240 self.tcx()
3241 .mk_patterns_from_iter(patterns.iter().map(|pat| {
3242 self.lower_pat_ty_pat(ty, ty_span, pat).map(|pat| tcx.mk_pat(pat))
3243 }))
3244 .map(ty::PatternKind::Or)
3245 }
3246 hir::TyPatKind::Err(e) => Err(e),
3247 }
3248 }
3249
3250 fn lower_field_of(
3251 &self,
3252 ty: Ty<'tcx>,
3253 item_def_id: LocalDefId,
3254 ty_span: Span,
3255 hir_id: HirId,
3256 variant: Option<Ident>,
3257 field: Ident,
3258 ) -> Ty<'tcx> {
3259 let dcx = self.dcx();
3260 let tcx = self.tcx();
3261 match ty.kind() {
3262 ty::Adt(def, _) => {
3263 let base_did = def.did();
3264 let kind_name = tcx.def_descr(base_did);
3265 let (variant_idx, variant) = if def.is_enum() {
3266 let Some(variant) = variant else {
3267 let err = dcx
3268 .create_err(NoVariantNamed { span: field.span, ident: field, ty })
3269 .with_span_help(
3270 field.span.shrink_to_lo(),
3271 "you might be missing a variant here: `Variant.`",
3272 )
3273 .emit();
3274 return Ty::new_error(tcx, err);
3275 };
3276
3277 if let Some(res) = def
3278 .variants()
3279 .iter_enumerated()
3280 .find(|(_, f)| f.ident(tcx).normalize_to_macros_2_0() == variant)
3281 {
3282 res
3283 } else {
3284 let err = dcx
3285 .create_err(NoVariantNamed { span: variant.span, ident: variant, ty })
3286 .emit();
3287 return Ty::new_error(tcx, err);
3288 }
3289 } else {
3290 if let Some(variant) = variant {
3291 let adt_path = tcx.def_path_str(base_did);
3292 {
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!(
3293 dcx,
3294 variant.span,
3295 E0609,
3296 "{kind_name} `{adt_path}` does not have any variants",
3297 )
3298 .with_span_label(variant.span, "variant unknown")
3299 .emit();
3300 }
3301 (FIRST_VARIANT, def.non_enum_variant())
3302 };
3303 let block = tcx.local_def_id_to_hir_id(item_def_id);
3304 let (ident, def_scope) = tcx.adjust_ident_and_get_scope(field, def.did(), block);
3305 if let Some((field_idx, field)) = variant
3306 .fields
3307 .iter_enumerated()
3308 .find(|(_, f)| f.ident(tcx).normalize_to_macros_2_0() == ident)
3309 {
3310 if field.vis.is_accessible_from(def_scope, tcx) {
3311 tcx.check_stability(field.did, Some(hir_id), ident.span, None);
3312 } else {
3313 let adt_path = tcx.def_path_str(base_did);
3314 {
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!(
3315 dcx,
3316 ident.span,
3317 E0616,
3318 "field `{ident}` of {kind_name} `{adt_path}` is private",
3319 )
3320 .with_span_label(ident.span, "private field")
3321 .emit();
3322 }
3323 Ty::new_field_representing_type(tcx, ty, variant_idx, field_idx)
3324 } else {
3325 let err =
3326 dcx.create_err(NoFieldOnType { span: ident.span, field: ident, ty }).emit();
3327 Ty::new_error(tcx, err)
3328 }
3329 }
3330 ty::Tuple(tys) => {
3331 let index = match field.as_str().parse::<usize>() {
3332 Ok(idx) => idx,
3333 Err(_) => {
3334 let err =
3335 dcx.create_err(NoFieldOnType { span: field.span, field, ty }).emit();
3336 return Ty::new_error(tcx, err);
3337 }
3338 };
3339 if field.name != sym::integer(index) {
3340 ::rustc_middle::util::bug::bug_fmt(format_args!("we parsed above, but now not equal?"));bug!("we parsed above, but now not equal?");
3341 }
3342 if tys.get(index).is_some() {
3343 Ty::new_field_representing_type(tcx, ty, FIRST_VARIANT, index.into())
3344 } else {
3345 let err = dcx.create_err(NoFieldOnType { span: field.span, field, ty }).emit();
3346 Ty::new_error(tcx, err)
3347 }
3348 }
3349 ty::Alias(..) => Ty::new_error(
3362 tcx,
3363 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}`")),
3364 ),
3365 ty::Error(err) => Ty::new_error(tcx, *err),
3366 ty::Bool
3367 | ty::Char
3368 | ty::Int(_)
3369 | ty::Uint(_)
3370 | ty::Float(_)
3371 | ty::Foreign(_)
3372 | ty::Str
3373 | ty::RawPtr(_, _)
3374 | ty::Ref(_, _, _)
3375 | ty::FnDef(_, _)
3376 | ty::FnPtr(_, _)
3377 | ty::UnsafeBinder(_)
3378 | ty::Dynamic(_, _)
3379 | ty::Closure(_, _)
3380 | ty::CoroutineClosure(_, _)
3381 | ty::Coroutine(_, _)
3382 | ty::CoroutineWitness(_, _)
3383 | ty::Never
3384 | ty::Param(_)
3385 | ty::Bound(_, _)
3386 | ty::Placeholder(_)
3387 | ty::Slice(..) => Ty::new_error(
3388 tcx,
3389 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")),
3390 ),
3391 ty::Infer(_) => Ty::new_error(
3392 tcx,
3393 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")),
3394 ),
3395 ty::Array(..) | ty::Pat(..) => Ty::new_error(
3397 tcx,
3398 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!`")),
3399 ),
3400 }
3401 }
3402
3403 x;#[instrument(level = "debug", skip(self), ret)]
3405 fn lower_opaque_ty(&self, def_id: LocalDefId, in_trait: Option<LocalDefId>) -> Ty<'tcx> {
3406 let tcx = self.tcx();
3407
3408 let lifetimes = tcx.opaque_captured_lifetimes(def_id);
3409 debug!(?lifetimes);
3410
3411 let def_id = if let Some(parent_def_id) = in_trait {
3415 *tcx.associated_types_for_impl_traits_in_associated_fn(parent_def_id.to_def_id())
3416 .iter()
3417 .find(|rpitit| match tcx.opt_rpitit_info(**rpitit) {
3418 Some(ty::ImplTraitInTraitData::Trait { opaque_def_id, .. }) => {
3419 opaque_def_id.expect_local() == def_id
3420 }
3421 _ => unreachable!(),
3422 })
3423 .unwrap()
3424 } else {
3425 def_id.to_def_id()
3426 };
3427
3428 let generics = tcx.generics_of(def_id);
3429 debug!(?generics);
3430
3431 let offset = generics.count() - lifetimes.len();
3435
3436 let args = ty::GenericArgs::for_item(tcx, def_id, |param, _| {
3437 if let Some(i) = (param.index as usize).checked_sub(offset) {
3438 let (lifetime, _) = lifetimes[i];
3439 self.lower_resolved_lifetime(lifetime).into()
3441 } else {
3442 tcx.mk_param_from_def(param)
3443 }
3444 });
3445 debug!(?args);
3446
3447 if in_trait.is_some() {
3448 Ty::new_projection_from_args(tcx, def_id, args)
3449 } else {
3450 Ty::new_opaque(tcx, def_id, args)
3451 }
3452 }
3453
3454 x;#[instrument(level = "debug", skip(self, hir_id, safety, abi, decl, generics, hir_ty), ret)]
3456 pub fn lower_fn_ty(
3457 &self,
3458 hir_id: HirId,
3459 safety: hir::Safety,
3460 abi: rustc_abi::ExternAbi,
3461 decl: &hir::FnDecl<'tcx>,
3462 generics: Option<&hir::Generics<'_>>,
3463 hir_ty: Option<&hir::Ty<'_>>,
3464 ) -> ty::PolyFnSig<'tcx> {
3465 let tcx = self.tcx();
3466 let bound_vars = tcx.late_bound_vars(hir_id);
3467 debug!(?bound_vars);
3468
3469 let (input_tys, output_ty) = self.lower_fn_sig(decl, generics, hir_id, hir_ty);
3470
3471 debug!(?output_ty);
3472
3473 let fn_sig_kind = FnSigKind::default()
3474 .set_abi(abi)
3475 .set_safety(safety)
3476 .set_c_variadic(decl.fn_decl_kind.c_variadic());
3477 let fn_ty = tcx.mk_fn_sig(input_tys, output_ty, fn_sig_kind);
3478 let fn_ptr_ty = ty::Binder::bind_with_vars(fn_ty, bound_vars);
3479
3480 if let hir::Node::Ty(hir::Ty { kind: hir::TyKind::FnPtr(fn_ptr_ty), span, .. }) =
3481 tcx.hir_node(hir_id)
3482 {
3483 check_abi(tcx, hir_id, *span, fn_ptr_ty.abi);
3484 }
3485
3486 cmse::validate_cmse_abi(self.tcx(), self.dcx(), hir_id, abi, fn_ptr_ty);
3488
3489 if !fn_ptr_ty.references_error() {
3490 let inputs = fn_ptr_ty.inputs();
3497 let late_bound_in_args =
3498 tcx.collect_constrained_late_bound_regions(inputs.map_bound(|i| i.to_owned()));
3499 let output = fn_ptr_ty.output();
3500 let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(output);
3501
3502 self.validate_late_bound_regions(late_bound_in_args, late_bound_in_ret, |br_name| {
3503 struct_span_code_err!(
3504 self.dcx(),
3505 decl.output.span(),
3506 E0581,
3507 "return type references {}, which is not constrained by the fn input types",
3508 br_name
3509 )
3510 });
3511 }
3512
3513 fn_ptr_ty
3514 }
3515
3516 pub(super) fn suggest_trait_fn_ty_for_impl_fn_infer(
3521 &self,
3522 fn_hir_id: HirId,
3523 arg_idx: Option<usize>,
3524 ) -> Option<Ty<'tcx>> {
3525 let tcx = self.tcx();
3526 let hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), ident, .. }) =
3527 tcx.hir_node(fn_hir_id)
3528 else {
3529 return None;
3530 };
3531 let i = tcx.parent_hir_node(fn_hir_id).expect_item().expect_impl();
3532
3533 let trait_ref = self.lower_impl_trait_ref(&i.of_trait?.trait_ref, self.lower_ty(i.self_ty));
3534
3535 let assoc = tcx.associated_items(trait_ref.def_id).find_by_ident_and_kind(
3536 tcx,
3537 *ident,
3538 ty::AssocTag::Fn,
3539 trait_ref.def_id,
3540 )?;
3541
3542 let fn_sig = tcx
3543 .fn_sig(assoc.def_id)
3544 .instantiate(
3545 tcx,
3546 trait_ref
3547 .args
3548 .extend_to(tcx, assoc.def_id, |param, _| tcx.mk_param_from_def(param)),
3549 )
3550 .skip_norm_wip();
3551 let fn_sig = tcx.liberate_late_bound_regions(fn_hir_id.expect_owner().to_def_id(), fn_sig);
3552
3553 Some(if let Some(arg_idx) = arg_idx {
3554 *fn_sig.inputs().get(arg_idx)?
3555 } else {
3556 fn_sig.output()
3557 })
3558 }
3559
3560 #[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(3560u32),
::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))]
3561 fn validate_late_bound_regions<'cx>(
3562 &'cx self,
3563 constrained_regions: FxIndexSet<ty::BoundRegionKind<'tcx>>,
3564 referenced_regions: FxIndexSet<ty::BoundRegionKind<'tcx>>,
3565 generate_err: impl Fn(&str) -> Diag<'cx>,
3566 ) {
3567 for br in referenced_regions.difference(&constrained_regions) {
3568 let br_name = if let Some(name) = br.get_name(self.tcx()) {
3569 format!("lifetime `{name}`")
3570 } else {
3571 "an anonymous lifetime".to_string()
3572 };
3573
3574 let mut err = generate_err(&br_name);
3575
3576 if !br.is_named(self.tcx()) {
3577 err.note(
3584 "lifetimes appearing in an associated or opaque type are not considered constrained",
3585 );
3586 err.note("consider introducing a named lifetime parameter");
3587 }
3588
3589 err.emit();
3590 }
3591 }
3592
3593 fn construct_const_ctor_value(
3594 &self,
3595 ctor_def_id: DefId,
3596 ctor_of: CtorOf,
3597 args: GenericArgsRef<'tcx>,
3598 ) -> Const<'tcx> {
3599 let tcx = self.tcx();
3600 let parent_did = tcx.parent(ctor_def_id);
3601
3602 let adt_def = tcx.adt_def(match ctor_of {
3603 CtorOf::Variant => tcx.parent(parent_did),
3604 CtorOf::Struct => parent_did,
3605 });
3606
3607 let variant_idx = adt_def.variant_index_with_id(parent_did);
3608
3609 let valtree = if adt_def.is_enum() {
3610 let discr = ty::ValTree::from_scalar_int(tcx, variant_idx.as_u32().into());
3611 ty::ValTree::from_branches(tcx, [ty::Const::new_value(tcx, discr, tcx.types.u32)])
3612 } else {
3613 ty::ValTree::zst(tcx)
3614 };
3615
3616 let adt_ty = Ty::new_adt(tcx, adt_def, args);
3617 ty::Const::new_value(tcx, valtree, adt_ty)
3618 }
3619}