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(tcx, ty::UnevaluatedConst::new(def_id, args));
1402 let ct = self.check_param_uses_if_mcg(ct, span, false);
1403 Ok(ct)
1404 }
1405 TypeRelativePath::Ctor { ctor_def_id, args } => match tcx.def_kind(ctor_def_id) {
1406 DefKind::Ctor(_, CtorKind::Fn) => {
1407 Ok(ty::Const::zero_sized(tcx, Ty::new_fn_def(tcx, ctor_def_id, args)))
1408 }
1409 DefKind::Ctor(ctor_of, CtorKind::Const) => {
1410 Ok(self.construct_const_ctor_value(ctor_def_id, ctor_of, args))
1411 }
1412 _ => unreachable!(),
1413 },
1414 TypeRelativePath::Variant { .. } => {
1417 span_bug!(span, "unexpected variant res for type associated const path")
1418 }
1419 }
1420 }
1421
1422 x;#[instrument(level = "debug", skip_all, ret)]
1424 fn lower_type_relative_path(
1425 &self,
1426 self_ty: Ty<'tcx>,
1427 hir_self_ty: &'tcx hir::Ty<'tcx>,
1428 segment: &'tcx hir::PathSegment<'tcx>,
1429 qpath_hir_id: HirId,
1430 span: Span,
1431 mode: LowerTypeRelativePathMode,
1432 ) -> Result<TypeRelativePath<'tcx>, ErrorGuaranteed> {
1433 debug!(%self_ty, ?segment.ident);
1434 let tcx = self.tcx();
1435
1436 let mut variant_def_id = None;
1438 if let Some(adt_def) = self.probe_adt(span, self_ty) {
1439 if adt_def.is_enum() {
1440 let variant_def = adt_def
1441 .variants()
1442 .iter()
1443 .find(|vd| tcx.hygienic_eq(segment.ident, vd.ident(tcx), adt_def.did()));
1444 if let Some(variant_def) = variant_def {
1445 if matches!(mode, LowerTypeRelativePathMode::Const)
1448 && let Some((_, ctor_def_id)) = variant_def.ctor
1449 {
1450 tcx.check_stability(variant_def.def_id, Some(qpath_hir_id), span, None);
1451 let _ = self.prohibit_generic_args(
1452 slice::from_ref(segment).iter(),
1453 GenericsArgsErrExtend::EnumVariant {
1454 qself: hir_self_ty,
1455 assoc_segment: segment,
1456 adt_def,
1457 },
1458 );
1459 let ty::Adt(_, enum_args) = self_ty.kind() else { unreachable!() };
1460 return Ok(TypeRelativePath::Ctor { ctor_def_id, args: enum_args });
1461 }
1462 if let PermitVariants::Yes = mode.permit_variants() {
1463 tcx.check_stability(variant_def.def_id, Some(qpath_hir_id), span, None);
1464 let _ = self.prohibit_generic_args(
1465 slice::from_ref(segment).iter(),
1466 GenericsArgsErrExtend::EnumVariant {
1467 qself: hir_self_ty,
1468 assoc_segment: segment,
1469 adt_def,
1470 },
1471 );
1472 return Ok(TypeRelativePath::Variant {
1473 adt: self_ty,
1474 variant_did: variant_def.def_id,
1475 });
1476 } else {
1477 variant_def_id = Some(variant_def.def_id);
1478 }
1479 }
1480 }
1481
1482 if let Some((did, args)) = self.probe_inherent_assoc_item(
1484 segment,
1485 adt_def.did(),
1486 self_ty,
1487 qpath_hir_id,
1488 span,
1489 mode.assoc_tag(),
1490 )? {
1491 return Ok(TypeRelativePath::AssocItem(did, args));
1492 }
1493 }
1494
1495 let (item_def_id, bound) = self.resolve_type_relative_path(
1496 self_ty,
1497 hir_self_ty,
1498 mode.assoc_tag(),
1499 segment,
1500 qpath_hir_id,
1501 span,
1502 variant_def_id,
1503 )?;
1504
1505 let (item_def_id, args) = self.lower_assoc_item_path(span, item_def_id, segment, bound)?;
1506
1507 if let Some(variant_def_id) = variant_def_id {
1508 tcx.emit_node_span_lint(
1509 AMBIGUOUS_ASSOCIATED_ITEMS,
1510 qpath_hir_id,
1511 span,
1512 errors::AmbiguityBetweenVariantAndAssocItem {
1513 variant_def_id,
1514 item_def_id,
1515 span,
1516 segment_ident: segment.ident,
1517 bound_def_id: bound.def_id(),
1518 self_ty,
1519 tcx,
1520 mode,
1521 },
1522 );
1523 }
1524
1525 Ok(TypeRelativePath::AssocItem(item_def_id, args))
1526 }
1527
1528 fn resolve_type_relative_path(
1530 &self,
1531 self_ty: Ty<'tcx>,
1532 hir_self_ty: &'tcx hir::Ty<'tcx>,
1533 assoc_tag: ty::AssocTag,
1534 segment: &'tcx hir::PathSegment<'tcx>,
1535 qpath_hir_id: HirId,
1536 span: Span,
1537 variant_def_id: Option<DefId>,
1538 ) -> Result<(DefId, ty::PolyTraitRef<'tcx>), ErrorGuaranteed> {
1539 let tcx = self.tcx();
1540
1541 let self_ty_res = match hir_self_ty.kind {
1542 hir::TyKind::Path(hir::QPath::Resolved(_, path)) => path.res,
1543 _ => Res::Err,
1544 };
1545
1546 let bound = match (self_ty.kind(), self_ty_res) {
1548 (_, Res::SelfTyAlias { alias_to: impl_def_id, is_trait_impl: true, .. }) => {
1549 let trait_ref = tcx.impl_trait_ref(impl_def_id);
1552
1553 self.probe_single_bound_for_assoc_item(
1554 || {
1555 let trait_ref =
1556 ty::Binder::dummy(trait_ref.instantiate_identity().skip_norm_wip());
1557 traits::supertraits(tcx, trait_ref)
1558 },
1559 AssocItemQSelf::SelfTyAlias,
1560 assoc_tag,
1561 segment.ident,
1562 span,
1563 None,
1564 )?
1565 }
1566 (
1567 &ty::Param(_),
1568 Res::SelfTyParam { trait_: param_did } | Res::Def(DefKind::TyParam, param_did),
1569 ) => self.probe_single_ty_param_bound_for_assoc_item(
1570 param_did.expect_local(),
1571 hir_self_ty.span,
1572 assoc_tag,
1573 segment.ident,
1574 span,
1575 )?,
1576 _ => {
1577 return Err(self.report_unresolved_type_relative_path(
1578 self_ty,
1579 hir_self_ty,
1580 assoc_tag,
1581 segment.ident,
1582 qpath_hir_id,
1583 span,
1584 variant_def_id,
1585 ));
1586 }
1587 };
1588
1589 let assoc_item = self
1590 .probe_assoc_item(segment.ident, assoc_tag, qpath_hir_id, span, bound.def_id())
1591 .expect("failed to find associated item");
1592
1593 Ok((assoc_item.def_id, bound))
1594 }
1595
1596 fn probe_inherent_assoc_item(
1598 &self,
1599 segment: &hir::PathSegment<'tcx>,
1600 adt_did: DefId,
1601 self_ty: Ty<'tcx>,
1602 block: HirId,
1603 span: Span,
1604 assoc_tag: ty::AssocTag,
1605 ) -> Result<Option<(DefId, GenericArgsRef<'tcx>)>, ErrorGuaranteed> {
1606 let tcx = self.tcx();
1607
1608 if !tcx.features().inherent_associated_types() {
1609 match assoc_tag {
1610 ty::AssocTag::Type => return Ok(None),
1615 ty::AssocTag::Const => {
1616 return Err(feature_err(
1620 &tcx.sess,
1621 sym::inherent_associated_types,
1622 span,
1623 "inherent associated types are unstable",
1624 )
1625 .emit());
1626 }
1627 ty::AssocTag::Fn => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1628 }
1629 }
1630
1631 let name = segment.ident;
1632 let candidates: Vec<_> = tcx
1633 .inherent_impls(adt_did)
1634 .iter()
1635 .filter_map(|&impl_| {
1636 let (item, scope) =
1637 self.probe_assoc_item_unchecked(name, assoc_tag, block, impl_)?;
1638 Some(InherentAssocCandidate { impl_, assoc_item: item.def_id, scope })
1639 })
1640 .collect();
1641
1642 if candidates.is_empty() {
1647 return Ok(None);
1648 }
1649
1650 let (applicable_candidates, fulfillment_errors) =
1651 self.select_inherent_assoc_candidates(span, self_ty, candidates.clone());
1652
1653 let InherentAssocCandidate { impl_, assoc_item, scope: def_scope } =
1655 match &applicable_candidates[..] {
1656 &[] => Err(self.report_unresolved_inherent_assoc_item(
1657 name,
1658 self_ty,
1659 candidates,
1660 fulfillment_errors,
1661 span,
1662 assoc_tag,
1663 )),
1664
1665 &[applicable_candidate] => Ok(applicable_candidate),
1666
1667 &[_, ..] => Err(self.report_ambiguous_inherent_assoc_item(
1668 name,
1669 candidates.into_iter().map(|cand| cand.assoc_item).collect(),
1670 span,
1671 )),
1672 }?;
1673
1674 self.check_assoc_item(assoc_item, name, def_scope, block, span);
1677
1678 let parent_args = ty::GenericArgs::identity_for_item(tcx, impl_);
1682 let args = self.lower_generic_args_of_assoc_item(span, assoc_item, segment, parent_args);
1683 let args = tcx.mk_args_from_iter(
1684 std::iter::once(ty::GenericArg::from(self_ty))
1685 .chain(args.into_iter().skip(parent_args.len())),
1686 );
1687
1688 Ok(Some((assoc_item, args)))
1689 }
1690
1691 fn probe_assoc_item(
1695 &self,
1696 ident: Ident,
1697 assoc_tag: ty::AssocTag,
1698 block: HirId,
1699 span: Span,
1700 scope: DefId,
1701 ) -> Option<ty::AssocItem> {
1702 let (item, scope) = self.probe_assoc_item_unchecked(ident, assoc_tag, block, scope)?;
1703 self.check_assoc_item(item.def_id, ident, scope, block, span);
1704 Some(item)
1705 }
1706
1707 fn probe_assoc_item_unchecked(
1712 &self,
1713 ident: Ident,
1714 assoc_tag: ty::AssocTag,
1715 block: HirId,
1716 scope: DefId,
1717 ) -> Option<(ty::AssocItem, DefId)> {
1718 let tcx = self.tcx();
1719
1720 let (ident, def_scope) = tcx.adjust_ident_and_get_scope(ident, scope, block);
1721 let item = tcx
1725 .associated_items(scope)
1726 .filter_by_name_unhygienic(ident.name)
1727 .find(|i| i.tag() == assoc_tag && i.ident(tcx).normalize_to_macros_2_0() == ident)?;
1728
1729 Some((*item, def_scope))
1730 }
1731
1732 fn check_assoc_item(
1734 &self,
1735 item_def_id: DefId,
1736 ident: Ident,
1737 scope: DefId,
1738 block: HirId,
1739 span: Span,
1740 ) {
1741 let tcx = self.tcx();
1742
1743 if !tcx.visibility(item_def_id).is_accessible_from(scope, tcx) {
1744 self.dcx().emit_err(crate::errors::AssocItemIsPrivate {
1745 span,
1746 kind: tcx.def_descr(item_def_id),
1747 name: ident,
1748 defined_here_label: tcx.def_span(item_def_id),
1749 });
1750 }
1751
1752 tcx.check_stability(item_def_id, Some(block), span, None);
1753 }
1754
1755 fn probe_traits_that_match_assoc_ty(
1756 &self,
1757 qself_ty: Ty<'tcx>,
1758 assoc_ident: Ident,
1759 ) -> Vec<String> {
1760 let tcx = self.tcx();
1761
1762 let infcx_;
1765 let infcx = if let Some(infcx) = self.infcx() {
1766 infcx
1767 } else {
1768 if !!qself_ty.has_infer() {
::core::panicking::panic("assertion failed: !qself_ty.has_infer()")
};assert!(!qself_ty.has_infer());
1769 infcx_ = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
1770 &infcx_
1771 };
1772
1773 tcx.all_traits_including_private()
1774 .filter(|trait_def_id| {
1775 tcx.associated_items(*trait_def_id)
1777 .in_definition_order()
1778 .any(|i| {
1779 i.is_type()
1780 && !i.is_impl_trait_in_trait()
1781 && i.ident(tcx).normalize_to_macros_2_0() == assoc_ident
1782 })
1783 && tcx.visibility(*trait_def_id)
1785 .is_accessible_from(self.item_def_id(), tcx)
1786 && tcx.all_impls(*trait_def_id)
1787 .any(|impl_def_id| {
1788 let header = tcx.impl_trait_header(impl_def_id);
1789 let trait_ref = header.trait_ref.instantiate(tcx, infcx.fresh_args_for_item(DUMMY_SP, impl_def_id)).skip_norm_wip();
1790
1791 let value = fold_regions(tcx, qself_ty, |_, _| tcx.lifetimes.re_erased);
1792 if value.has_escaping_bound_vars() {
1794 return false;
1795 }
1796 infcx
1797 .can_eq(
1798 ty::ParamEnv::empty(),
1799 trait_ref.self_ty(),
1800 value,
1801 ) && header.polarity != ty::ImplPolarity::Negative
1802 })
1803 })
1804 .map(|trait_def_id| tcx.def_path_str(trait_def_id))
1805 .collect()
1806 }
1807
1808 #[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(1809u32),
::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)]
1810 fn lower_resolved_assoc_ty_path(
1811 &self,
1812 span: Span,
1813 opt_self_ty: Option<Ty<'tcx>>,
1814 item_def_id: DefId,
1815 trait_segment: Option<&hir::PathSegment<'tcx>>,
1816 item_segment: &hir::PathSegment<'tcx>,
1817 ) -> Ty<'tcx> {
1818 match self.lower_resolved_assoc_item_path(
1819 span,
1820 opt_self_ty,
1821 item_def_id,
1822 trait_segment,
1823 item_segment,
1824 ty::AssocTag::Type,
1825 ) {
1826 Ok((item_def_id, item_args)) => {
1827 Ty::new_projection_from_args(self.tcx(), item_def_id, item_args)
1828 }
1829 Err(guar) => Ty::new_error(self.tcx(), guar),
1830 }
1831 }
1832
1833 #[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(1834u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&[],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{ meta.fields().value_set(&[]) })
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return:
Result<Const<'tcx>, ErrorGuaranteed> = loop {};
return __tracing_attr_fake_return;
}
{
let (item_def_id, item_args) =
self.lower_resolved_assoc_item_path(span, opt_self_ty,
item_def_id, trait_segment, item_segment,
ty::AssocTag::Const)?;
self.require_type_const_attribute(item_def_id, span)?;
let uv = ty::UnevaluatedConst::new(item_def_id, item_args);
Ok(Const::new_unevaluated(self.tcx(), uv))
}
}
}#[instrument(level = "debug", skip_all)]
1835 fn lower_resolved_assoc_const_path(
1836 &self,
1837 span: Span,
1838 opt_self_ty: Option<Ty<'tcx>>,
1839 item_def_id: DefId,
1840 trait_segment: Option<&hir::PathSegment<'tcx>>,
1841 item_segment: &hir::PathSegment<'tcx>,
1842 ) -> Result<Const<'tcx>, ErrorGuaranteed> {
1843 let (item_def_id, item_args) = self.lower_resolved_assoc_item_path(
1844 span,
1845 opt_self_ty,
1846 item_def_id,
1847 trait_segment,
1848 item_segment,
1849 ty::AssocTag::Const,
1850 )?;
1851 self.require_type_const_attribute(item_def_id, span)?;
1852 let uv = ty::UnevaluatedConst::new(item_def_id, item_args);
1853 Ok(Const::new_unevaluated(self.tcx(), uv))
1854 }
1855
1856 #[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(1857u32),
::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:1870",
"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(1870u32),
::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:1880",
"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(1880u32),
::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:1884",
"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(1884u32),
::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)]
1858 fn lower_resolved_assoc_item_path(
1859 &self,
1860 span: Span,
1861 opt_self_ty: Option<Ty<'tcx>>,
1862 item_def_id: DefId,
1863 trait_segment: Option<&hir::PathSegment<'tcx>>,
1864 item_segment: &hir::PathSegment<'tcx>,
1865 assoc_tag: ty::AssocTag,
1866 ) -> Result<(DefId, GenericArgsRef<'tcx>), ErrorGuaranteed> {
1867 let tcx = self.tcx();
1868
1869 let trait_def_id = tcx.parent(item_def_id);
1870 debug!(?trait_def_id);
1871
1872 let Some(self_ty) = opt_self_ty else {
1873 return Err(self.report_missing_self_ty_for_resolved_path(
1874 trait_def_id,
1875 span,
1876 item_segment,
1877 assoc_tag,
1878 ));
1879 };
1880 debug!(?self_ty);
1881
1882 let trait_ref =
1883 self.lower_mono_trait_ref(span, trait_def_id, self_ty, trait_segment.unwrap(), false);
1884 debug!(?trait_ref);
1885
1886 let item_args =
1887 self.lower_generic_args_of_assoc_item(span, item_def_id, item_segment, trait_ref.args);
1888
1889 Ok((item_def_id, item_args))
1890 }
1891
1892 pub fn prohibit_generic_args<'a>(
1893 &self,
1894 segments: impl Iterator<Item = &'a hir::PathSegment<'a>> + Clone,
1895 err_extend: GenericsArgsErrExtend<'a>,
1896 ) -> Result<(), ErrorGuaranteed> {
1897 let args_visitors = segments.clone().flat_map(|segment| segment.args().args);
1898 let mut result = Ok(());
1899 if let Some(_) = args_visitors.clone().next() {
1900 result = Err(self.report_prohibited_generic_args(
1901 segments.clone(),
1902 args_visitors,
1903 err_extend,
1904 ));
1905 }
1906
1907 for segment in segments {
1908 if let Some(c) = segment.args().constraints.first() {
1910 return Err(prohibit_assoc_item_constraint(self, c, None));
1911 }
1912 }
1913
1914 result
1915 }
1916
1917 pub fn probe_generic_path_segments(
1935 &self,
1936 segments: &[hir::PathSegment<'_>],
1937 self_ty: Option<Ty<'tcx>>,
1938 kind: DefKind,
1939 def_id: DefId,
1940 span: Span,
1941 ) -> Vec<GenericPathSegment> {
1942 let tcx = self.tcx();
1988
1989 if !!segments.is_empty() {
::core::panicking::panic("assertion failed: !segments.is_empty()")
};assert!(!segments.is_empty());
1990 let last = segments.len() - 1;
1991
1992 let mut generic_segments = ::alloc::vec::Vec::new()vec![];
1993
1994 match kind {
1995 DefKind::Ctor(CtorOf::Struct, ..) => {
1997 let generics = tcx.generics_of(def_id);
2000 let generics_def_id = generics.parent.unwrap_or(def_id);
2003 generic_segments.push(GenericPathSegment(generics_def_id, last));
2004 }
2005
2006 DefKind::Ctor(CtorOf::Variant, ..) | DefKind::Variant => {
2008 let (generics_def_id, index) = if let Some(self_ty) = self_ty {
2009 let adt_def = self.probe_adt(span, self_ty).unwrap();
2012 if true {
if !adt_def.is_enum() {
::core::panicking::panic("assertion failed: adt_def.is_enum()")
};
};debug_assert!(adt_def.is_enum());
2013
2014 (adt_def.did(), last)
2026 } else if let [.., second_to_last, _] = segments
2027 && second_to_last.args.is_some()
2028 && let Res::Def(DefKind::Enum, _) = second_to_last.res
2029 {
2030 let def_id = match kind {
2039 DefKind::Ctor(..) => tcx.parent(def_id),
2040 _ => def_id,
2041 };
2042
2043 let enum_def_id = tcx.parent(def_id);
2045
2046 (enum_def_id, last - 1)
2047 } else {
2048 let generics = tcx.generics_of(def_id);
2055 (generics.parent.unwrap_or(def_id), last)
2058 };
2059 generic_segments.push(GenericPathSegment(generics_def_id, index));
2060 }
2061
2062 DefKind::Fn | DefKind::Const { .. } | DefKind::ConstParam | DefKind::Static { .. } => {
2064 generic_segments.push(GenericPathSegment(def_id, last));
2065 }
2066
2067 DefKind::AssocFn | DefKind::AssocConst { .. } => {
2069 if segments.len() >= 2 {
2070 let generics = tcx.generics_of(def_id);
2071 generic_segments.push(GenericPathSegment(generics.parent.unwrap(), last - 1));
2072 }
2073 generic_segments.push(GenericPathSegment(def_id, last));
2074 }
2075
2076 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),
2077 }
2078
2079 {
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:2079",
"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(2079u32),
::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);
2080
2081 generic_segments
2082 }
2083
2084 #[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(2085u32),
::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:2093",
"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(2093u32),
::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)]
2086 pub fn lower_resolved_ty_path(
2087 &self,
2088 opt_self_ty: Option<Ty<'tcx>>,
2089 path: &hir::Path<'tcx>,
2090 hir_id: HirId,
2091 permit_variants: PermitVariants,
2092 ) -> Ty<'tcx> {
2093 debug!(?path.res, ?opt_self_ty, ?path.segments);
2094 let tcx = self.tcx();
2095
2096 let span = path.span;
2097 match path.res {
2098 Res::Def(DefKind::OpaqueTy, did) => {
2099 assert_matches!(tcx.opaque_ty_origin(did), hir::OpaqueTyOrigin::TyAlias { .. });
2101 let [leading_segments @ .., segment] = path.segments else { bug!() };
2102 let _ = self.prohibit_generic_args(
2103 leading_segments.iter(),
2104 GenericsArgsErrExtend::OpaqueTy,
2105 );
2106 let args = self.lower_generic_args_of_path_segment(span, did, segment);
2107 Ty::new_opaque(tcx, did, args)
2108 }
2109 Res::Def(
2110 DefKind::Enum
2111 | DefKind::TyAlias
2112 | DefKind::Struct
2113 | DefKind::Union
2114 | DefKind::ForeignTy,
2115 did,
2116 ) => {
2117 assert_eq!(opt_self_ty, None);
2118 let [leading_segments @ .., segment] = path.segments else { bug!() };
2119 let _ = self
2120 .prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
2121 self.lower_path_segment(span, did, segment)
2122 }
2123 Res::Def(kind @ DefKind::Variant, def_id)
2124 if let PermitVariants::Yes = permit_variants =>
2125 {
2126 assert_eq!(opt_self_ty, None);
2129
2130 let generic_segments =
2131 self.probe_generic_path_segments(path.segments, None, kind, def_id, span);
2132 let indices: FxHashSet<_> =
2133 generic_segments.iter().map(|GenericPathSegment(_, index)| index).collect();
2134 let _ = self.prohibit_generic_args(
2135 path.segments.iter().enumerate().filter_map(|(index, seg)| {
2136 if !indices.contains(&index) { Some(seg) } else { None }
2137 }),
2138 GenericsArgsErrExtend::DefVariant(&path.segments),
2139 );
2140
2141 let &GenericPathSegment(def_id, index) = generic_segments.last().unwrap();
2142 self.lower_path_segment(span, def_id, &path.segments[index])
2143 }
2144 Res::Def(DefKind::TyParam, def_id) => {
2145 assert_eq!(opt_self_ty, None);
2146 let _ = self.prohibit_generic_args(
2147 path.segments.iter(),
2148 GenericsArgsErrExtend::Param(def_id),
2149 );
2150 self.lower_ty_param(hir_id)
2151 }
2152 Res::SelfTyParam { .. } => {
2153 assert_eq!(opt_self_ty, None);
2155 let _ = self.prohibit_generic_args(
2156 path.segments.iter(),
2157 if let [hir::PathSegment { args: Some(args), ident, .. }] = &path.segments {
2158 GenericsArgsErrExtend::SelfTyParam(
2159 ident.span.shrink_to_hi().to(args.span_ext),
2160 )
2161 } else {
2162 GenericsArgsErrExtend::None
2163 },
2164 );
2165 self.check_param_uses_if_mcg(tcx.types.self_param, span, false)
2166 }
2167 Res::SelfTyAlias { alias_to: def_id, .. } => {
2168 assert_eq!(opt_self_ty, None);
2170 let ty = tcx.at(span).type_of(def_id).instantiate_identity().skip_norm_wip();
2172 let _ = self.prohibit_generic_args(
2173 path.segments.iter(),
2174 GenericsArgsErrExtend::SelfTyAlias { def_id, span },
2175 );
2176 self.check_param_uses_if_mcg(ty, span, true)
2177 }
2178 Res::Def(DefKind::AssocTy, def_id) => {
2179 let trait_segment = if let [modules @ .., trait_, _item] = path.segments {
2180 let _ = self.prohibit_generic_args(modules.iter(), GenericsArgsErrExtend::None);
2181 Some(trait_)
2182 } else {
2183 None
2184 };
2185 self.lower_resolved_assoc_ty_path(
2186 span,
2187 opt_self_ty,
2188 def_id,
2189 trait_segment,
2190 path.segments.last().unwrap(),
2191 )
2192 }
2193 Res::PrimTy(prim_ty) => {
2194 assert_eq!(opt_self_ty, None);
2195 let _ = self.prohibit_generic_args(
2196 path.segments.iter(),
2197 GenericsArgsErrExtend::PrimTy(prim_ty),
2198 );
2199 match prim_ty {
2200 hir::PrimTy::Bool => tcx.types.bool,
2201 hir::PrimTy::Char => tcx.types.char,
2202 hir::PrimTy::Int(it) => Ty::new_int(tcx, it),
2203 hir::PrimTy::Uint(uit) => Ty::new_uint(tcx, uit),
2204 hir::PrimTy::Float(ft) => Ty::new_float(tcx, ft),
2205 hir::PrimTy::Str => tcx.types.str_,
2206 }
2207 }
2208 Res::Err => {
2209 let e = self
2210 .tcx()
2211 .dcx()
2212 .span_delayed_bug(path.span, "path with `Res::Err` but no error emitted");
2213 Ty::new_error(tcx, e)
2214 }
2215 Res::Def(..) => {
2216 assert_eq!(
2217 path.segments.get(0).map(|seg| seg.ident.name),
2218 Some(kw::SelfUpper),
2219 "only expected incorrect resolution for `Self`"
2220 );
2221 Ty::new_error(
2222 self.tcx(),
2223 self.dcx().span_delayed_bug(span, "incorrect resolution for `Self`"),
2224 )
2225 }
2226 _ => span_bug!(span, "unexpected resolution: {:?}", path.res),
2227 }
2228 }
2229
2230 pub(crate) fn lower_ty_param(&self, hir_id: HirId) -> Ty<'tcx> {
2235 let tcx = self.tcx();
2236
2237 let ty = match tcx.named_bound_var(hir_id) {
2238 Some(rbv::ResolvedArg::LateBound(debruijn, index, def_id)) => {
2239 let br = ty::BoundTy {
2240 var: ty::BoundVar::from_u32(index),
2241 kind: ty::BoundTyKind::Param(def_id.to_def_id()),
2242 };
2243 Ty::new_bound(tcx, debruijn, br)
2244 }
2245 Some(rbv::ResolvedArg::EarlyBound(def_id)) => {
2246 let item_def_id = tcx.hir_ty_param_owner(def_id);
2247 let generics = tcx.generics_of(item_def_id);
2248 let index = generics.param_def_id_to_index[&def_id.to_def_id()];
2249 Ty::new_param(tcx, index, tcx.hir_ty_param_name(def_id))
2250 }
2251 Some(rbv::ResolvedArg::Error(guar)) => Ty::new_error(tcx, guar),
2252 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:?}"),
2253 };
2254 self.check_param_uses_if_mcg(ty, tcx.hir_span(hir_id), false)
2255 }
2256
2257 pub(crate) fn lower_const_param(&self, param_def_id: DefId, path_hir_id: HirId) -> Const<'tcx> {
2262 let tcx = self.tcx();
2263
2264 let ct = match tcx.named_bound_var(path_hir_id) {
2265 Some(rbv::ResolvedArg::EarlyBound(_)) => {
2266 let item_def_id = tcx.parent(param_def_id);
2269 let generics = tcx.generics_of(item_def_id);
2270 let index = generics.param_def_id_to_index[¶m_def_id];
2271 let name = tcx.item_name(param_def_id);
2272 ty::Const::new_param(tcx, ty::ParamConst::new(index, name))
2273 }
2274 Some(rbv::ResolvedArg::LateBound(debruijn, index, _)) => ty::Const::new_bound(
2275 tcx,
2276 debruijn,
2277 ty::BoundConst::new(ty::BoundVar::from_u32(index)),
2278 ),
2279 Some(rbv::ResolvedArg::Error(guar)) => ty::Const::new_error(tcx, guar),
2280 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),
2281 };
2282 self.check_param_uses_if_mcg(ct, tcx.hir_span(path_hir_id), false)
2283 }
2284
2285 #[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(2286u32),
::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:2338",
"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(2338u32),
::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:2343",
"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(2343u32),
::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")]
2287 pub fn lower_const_arg(&self, const_arg: &hir::ConstArg<'tcx>, ty: Ty<'tcx>) -> Const<'tcx> {
2288 let tcx = self.tcx();
2289
2290 if let hir::ConstArgKind::Anon(anon) = &const_arg.kind {
2291 if tcx.features().generic_const_parameter_types()
2300 && (ty.has_free_regions() || ty.has_erased_regions())
2301 {
2302 let e = self.dcx().span_err(
2303 const_arg.span,
2304 "anonymous constants with lifetimes in their type are not yet supported",
2305 );
2306 tcx.feed_anon_const_type(anon.def_id, ty::EarlyBinder::bind(Ty::new_error(tcx, e)));
2307 return ty::Const::new_error(tcx, e);
2308 }
2309 if ty.has_non_region_infer() {
2313 let e = self.dcx().span_err(
2314 const_arg.span,
2315 "anonymous constants with inferred types are not yet supported",
2316 );
2317 tcx.feed_anon_const_type(anon.def_id, ty::EarlyBinder::bind(Ty::new_error(tcx, e)));
2318 return ty::Const::new_error(tcx, e);
2319 }
2320 if ty.has_non_region_param() {
2323 let e = self.dcx().span_err(
2324 const_arg.span,
2325 "anonymous constants referencing generics are not yet supported",
2326 );
2327 tcx.feed_anon_const_type(anon.def_id, ty::EarlyBinder::bind(Ty::new_error(tcx, e)));
2328 return ty::Const::new_error(tcx, e);
2329 }
2330
2331 tcx.feed_anon_const_type(anon.def_id, ty::EarlyBinder::bind(ty));
2332 }
2333
2334 let hir_id = const_arg.hir_id;
2335 match const_arg.kind {
2336 hir::ConstArgKind::Tup(exprs) => self.lower_const_arg_tup(exprs, ty, const_arg.span),
2337 hir::ConstArgKind::Path(hir::QPath::Resolved(maybe_qself, path)) => {
2338 debug!(?maybe_qself, ?path);
2339 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
2340 self.lower_resolved_const_path(opt_self_ty, path, hir_id)
2341 }
2342 hir::ConstArgKind::Path(hir::QPath::TypeRelative(hir_self_ty, segment)) => {
2343 debug!(?hir_self_ty, ?segment);
2344 let self_ty = self.lower_ty(hir_self_ty);
2345 self.lower_type_relative_const_path(
2346 self_ty,
2347 hir_self_ty,
2348 segment,
2349 hir_id,
2350 const_arg.span,
2351 )
2352 .unwrap_or_else(|guar| Const::new_error(tcx, guar))
2353 }
2354 hir::ConstArgKind::Struct(qpath, inits) => {
2355 self.lower_const_arg_struct(hir_id, qpath, inits, const_arg.span)
2356 }
2357 hir::ConstArgKind::TupleCall(qpath, args) => {
2358 self.lower_const_arg_tuple_call(hir_id, qpath, args, const_arg.span)
2359 }
2360 hir::ConstArgKind::Array(array_expr) => self.lower_const_arg_array(array_expr, ty),
2361 hir::ConstArgKind::Anon(anon) => self.lower_const_arg_anon(anon),
2362 hir::ConstArgKind::Infer(()) => self.ct_infer(None, const_arg.span),
2363 hir::ConstArgKind::Error(e) => ty::Const::new_error(tcx, e),
2364 hir::ConstArgKind::Literal { lit, negated } => {
2365 self.lower_const_arg_literal(&lit, negated, ty, const_arg.span)
2366 }
2367 }
2368 }
2369
2370 fn lower_const_arg_array(
2371 &self,
2372 array_expr: &'tcx hir::ConstArgArrayExpr<'tcx>,
2373 ty: Ty<'tcx>,
2374 ) -> Const<'tcx> {
2375 let tcx = self.tcx();
2376
2377 let elem_ty = match ty.kind() {
2378 ty::Array(elem_ty, _) => elem_ty,
2379 ty::Error(e) => return Const::new_error(tcx, *e),
2380 _ => {
2381 let e = tcx
2382 .dcx()
2383 .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));
2384 return Const::new_error(tcx, e);
2385 }
2386 };
2387
2388 let elems = array_expr
2389 .elems
2390 .iter()
2391 .map(|elem| self.lower_const_arg(elem, *elem_ty))
2392 .collect::<Vec<_>>();
2393
2394 let valtree = ty::ValTree::from_branches(tcx, elems);
2395
2396 ty::Const::new_value(tcx, valtree, ty)
2397 }
2398
2399 fn lower_const_arg_tuple_call(
2400 &self,
2401 hir_id: HirId,
2402 qpath: hir::QPath<'tcx>,
2403 args: &'tcx [&'tcx hir::ConstArg<'tcx>],
2404 span: Span,
2405 ) -> Const<'tcx> {
2406 let tcx = self.tcx();
2407
2408 let non_adt_or_variant_res = || {
2409 let e = tcx.dcx().span_err(span, "tuple constructor with invalid base path");
2410 ty::Const::new_error(tcx, e)
2411 };
2412
2413 let ctor_const = match qpath {
2414 hir::QPath::Resolved(maybe_qself, path) => {
2415 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
2416 self.lower_resolved_const_path(opt_self_ty, path, hir_id)
2417 }
2418 hir::QPath::TypeRelative(hir_self_ty, segment) => {
2419 let self_ty = self.lower_ty(hir_self_ty);
2420 match self.lower_type_relative_const_path(
2421 self_ty,
2422 hir_self_ty,
2423 segment,
2424 hir_id,
2425 span,
2426 ) {
2427 Ok(c) => c,
2428 Err(_) => return non_adt_or_variant_res(),
2429 }
2430 }
2431 };
2432
2433 let Some(value) = ctor_const.try_to_value() else {
2434 return non_adt_or_variant_res();
2435 };
2436
2437 let (adt_def, adt_args, variant_did) = match value.ty.kind() {
2438 ty::FnDef(def_id, fn_args)
2439 if let DefKind::Ctor(CtorOf::Variant, _) = tcx.def_kind(*def_id) =>
2440 {
2441 let parent_did = tcx.parent(*def_id);
2442 let enum_did = tcx.parent(parent_did);
2443 (tcx.adt_def(enum_did), fn_args, parent_did)
2444 }
2445 ty::FnDef(def_id, fn_args)
2446 if let DefKind::Ctor(CtorOf::Struct, _) = tcx.def_kind(*def_id) =>
2447 {
2448 let parent_did = tcx.parent(*def_id);
2449 (tcx.adt_def(parent_did), fn_args, parent_did)
2450 }
2451 _ => {
2452 let e = self.dcx().span_err(
2453 span,
2454 "complex const arguments must be placed inside of a `const` block",
2455 );
2456 return Const::new_error(tcx, e);
2457 }
2458 };
2459
2460 let variant_def = adt_def.variant_with_id(variant_did);
2461 let variant_idx = adt_def.variant_index_with_id(variant_did).as_u32();
2462
2463 if args.len() != variant_def.fields.len() {
2464 let e = tcx.dcx().span_err(
2465 span,
2466 ::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!(
2467 "tuple constructor has {} arguments but {} were provided",
2468 variant_def.fields.len(),
2469 args.len()
2470 ),
2471 );
2472 return ty::Const::new_error(tcx, e);
2473 }
2474
2475 let fields = variant_def
2476 .fields
2477 .iter()
2478 .zip(args)
2479 .map(|(field_def, arg)| {
2480 self.lower_const_arg(
2481 arg,
2482 tcx.type_of(field_def.did).instantiate(tcx, adt_args).skip_norm_wip(),
2483 )
2484 })
2485 .collect::<Vec<_>>();
2486
2487 let opt_discr_const = if adt_def.is_enum() {
2488 let valtree = ty::ValTree::from_scalar_int(tcx, variant_idx.into());
2489 Some(ty::Const::new_value(tcx, valtree, tcx.types.u32))
2490 } else {
2491 None
2492 };
2493
2494 let valtree = ty::ValTree::from_branches(tcx, opt_discr_const.into_iter().chain(fields));
2495 let adt_ty = Ty::new_adt(tcx, adt_def, adt_args);
2496 ty::Const::new_value(tcx, valtree, adt_ty)
2497 }
2498
2499 fn lower_const_arg_tup(
2500 &self,
2501 exprs: &'tcx [&'tcx hir::ConstArg<'tcx>],
2502 ty: Ty<'tcx>,
2503 span: Span,
2504 ) -> Const<'tcx> {
2505 let tcx = self.tcx();
2506
2507 let tys = match ty.kind() {
2508 ty::Tuple(tys) => tys,
2509 ty::Error(e) => return Const::new_error(tcx, *e),
2510 _ => {
2511 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));
2512 return Const::new_error(tcx, e);
2513 }
2514 };
2515
2516 let exprs = exprs
2517 .iter()
2518 .zip(tys.iter())
2519 .map(|(expr, ty)| self.lower_const_arg(expr, ty))
2520 .collect::<Vec<_>>();
2521
2522 let valtree = ty::ValTree::from_branches(tcx, exprs);
2523 ty::Const::new_value(tcx, valtree, ty)
2524 }
2525
2526 fn lower_const_arg_struct(
2527 &self,
2528 hir_id: HirId,
2529 qpath: hir::QPath<'tcx>,
2530 inits: &'tcx [&'tcx hir::ConstArgExprField<'tcx>],
2531 span: Span,
2532 ) -> Const<'tcx> {
2533 let tcx = self.tcx();
2536
2537 let non_adt_or_variant_res = || {
2538 let e = tcx.dcx().span_err(span, "struct expression with invalid base path");
2539 ty::Const::new_error(tcx, e)
2540 };
2541
2542 let ResolvedStructPath { res: opt_res, ty } =
2543 self.lower_path_for_struct_expr(qpath, span, hir_id);
2544
2545 let variant_did = match qpath {
2546 hir::QPath::Resolved(maybe_qself, path) => {
2547 {
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:2547",
"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(2547u32),
::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);
2548 let variant_did = match path.res {
2549 Res::Def(DefKind::Variant | DefKind::Struct, did) => did,
2550 _ => return non_adt_or_variant_res(),
2551 };
2552
2553 variant_did
2554 }
2555 hir::QPath::TypeRelative(hir_self_ty, segment) => {
2556 {
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:2556",
"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(2556u32),
::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);
2557
2558 let res_def_id = match opt_res {
2559 Ok(r)
2560 if #[allow(non_exhaustive_omitted_patterns)] match tcx.def_kind(r.def_id()) {
DefKind::Variant | DefKind::Struct => true,
_ => false,
}matches!(
2561 tcx.def_kind(r.def_id()),
2562 DefKind::Variant | DefKind::Struct
2563 ) =>
2564 {
2565 r.def_id()
2566 }
2567 Ok(_) => return non_adt_or_variant_res(),
2568 Err(e) => return ty::Const::new_error(tcx, e),
2569 };
2570
2571 res_def_id
2572 }
2573 };
2574
2575 let ty::Adt(adt_def, adt_args) = ty.kind() else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
2576
2577 let variant_def = adt_def.variant_with_id(variant_did);
2578 let variant_idx = adt_def.variant_index_with_id(variant_did).as_u32();
2579
2580 let fields = variant_def
2581 .fields
2582 .iter()
2583 .map(|field_def| {
2584 let mut init_expr =
2587 inits.iter().filter(|init_expr| init_expr.field.name == field_def.name);
2588
2589 match init_expr.next() {
2590 Some(expr) => {
2591 if let Some(expr) = init_expr.next() {
2592 let e = tcx.dcx().span_err(
2593 expr.span,
2594 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("struct expression with multiple initialisers for `{0}`",
field_def.name))
})format!(
2595 "struct expression with multiple initialisers for `{}`",
2596 field_def.name,
2597 ),
2598 );
2599 return ty::Const::new_error(tcx, e);
2600 }
2601
2602 self.lower_const_arg(
2603 expr.expr,
2604 tcx.type_of(field_def.did).instantiate(tcx, adt_args).skip_norm_wip(),
2605 )
2606 }
2607 None => {
2608 let e = tcx.dcx().span_err(
2609 span,
2610 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("struct expression with missing field initialiser for `{0}`",
field_def.name))
})format!(
2611 "struct expression with missing field initialiser for `{}`",
2612 field_def.name
2613 ),
2614 );
2615 ty::Const::new_error(tcx, e)
2616 }
2617 }
2618 })
2619 .collect::<Vec<_>>();
2620
2621 let opt_discr_const = if adt_def.is_enum() {
2622 let valtree = ty::ValTree::from_scalar_int(tcx, variant_idx.into());
2623 Some(ty::Const::new_value(tcx, valtree, tcx.types.u32))
2624 } else {
2625 None
2626 };
2627
2628 let valtree = ty::ValTree::from_branches(tcx, opt_discr_const.into_iter().chain(fields));
2629 ty::Const::new_value(tcx, valtree, ty)
2630 }
2631
2632 pub fn lower_path_for_struct_expr(
2633 &self,
2634 qpath: hir::QPath<'tcx>,
2635 path_span: Span,
2636 hir_id: HirId,
2637 ) -> ResolvedStructPath<'tcx> {
2638 match qpath {
2639 hir::QPath::Resolved(ref maybe_qself, path) => {
2640 let self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
2641 let ty = self.lower_resolved_ty_path(self_ty, path, hir_id, PermitVariants::Yes);
2642 ResolvedStructPath { res: Ok(path.res), ty }
2643 }
2644 hir::QPath::TypeRelative(hir_self_ty, segment) => {
2645 let self_ty = self.lower_ty(hir_self_ty);
2646
2647 let result = self.lower_type_relative_ty_path(
2648 self_ty,
2649 hir_self_ty,
2650 segment,
2651 hir_id,
2652 path_span,
2653 PermitVariants::Yes,
2654 );
2655 let ty = result
2656 .map(|(ty, _, _)| ty)
2657 .unwrap_or_else(|guar| Ty::new_error(self.tcx(), guar));
2658
2659 ResolvedStructPath {
2660 res: result.map(|(_, kind, def_id)| Res::Def(kind, def_id)),
2661 ty,
2662 }
2663 }
2664 }
2665 }
2666
2667 fn lower_resolved_const_path(
2669 &self,
2670 opt_self_ty: Option<Ty<'tcx>>,
2671 path: &hir::Path<'tcx>,
2672 hir_id: HirId,
2673 ) -> Const<'tcx> {
2674 let tcx = self.tcx();
2675 let span = path.span;
2676 let ct = match path.res {
2677 Res::Def(DefKind::ConstParam, def_id) => {
2678 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);
2679 let _ = self.prohibit_generic_args(
2680 path.segments.iter(),
2681 GenericsArgsErrExtend::Param(def_id),
2682 );
2683 self.lower_const_param(def_id, hir_id)
2684 }
2685 Res::Def(DefKind::Const { .. }, did) => {
2686 if let Err(guar) = self.require_type_const_attribute(did, span) {
2687 return Const::new_error(self.tcx(), guar);
2688 }
2689
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 [leading_segments @ .., segment] = path.segments else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
2692 let _ = self
2693 .prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
2694 let args = self.lower_generic_args_of_path_segment(span, did, segment);
2695 ty::Const::new_unevaluated(tcx, ty::UnevaluatedConst::new(did, args))
2696 }
2697 Res::Def(DefKind::Ctor(ctor_of, CtorKind::Const), did) => {
2698 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);
2699 let [leading_segments @ .., segment] = path.segments else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
2700 let _ = self
2701 .prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
2702
2703 let parent_did = tcx.parent(did);
2704 let generics_did = match ctor_of {
2705 CtorOf::Variant => tcx.parent(parent_did),
2706 CtorOf::Struct => parent_did,
2707 };
2708 let args = self.lower_generic_args_of_path_segment(span, generics_did, segment);
2709
2710 self.construct_const_ctor_value(did, ctor_of, args)
2711 }
2712 Res::Def(DefKind::Ctor(_, CtorKind::Fn), did) => {
2713 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);
2714 let [leading_segments @ .., segment] = path.segments else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
2715 let _ = self
2716 .prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
2717 let parent_did = tcx.parent(did);
2718 let generics_did = if let DefKind::Ctor(CtorOf::Variant, _) = tcx.def_kind(did) {
2719 tcx.parent(parent_did)
2720 } else {
2721 parent_did
2722 };
2723 let args = self.lower_generic_args_of_path_segment(span, generics_did, segment);
2724 ty::Const::zero_sized(tcx, Ty::new_fn_def(tcx, did, args))
2725 }
2726 Res::Def(DefKind::AssocConst { .. }, did) => {
2727 let trait_segment = if let [modules @ .., trait_, _item] = path.segments {
2728 let _ = self.prohibit_generic_args(modules.iter(), GenericsArgsErrExtend::None);
2729 Some(trait_)
2730 } else {
2731 None
2732 };
2733 self.lower_resolved_assoc_const_path(
2734 span,
2735 opt_self_ty,
2736 did,
2737 trait_segment,
2738 path.segments.last().unwrap(),
2739 )
2740 .unwrap_or_else(|guar| Const::new_error(tcx, guar))
2741 }
2742 Res::Def(DefKind::Static { .. }, _) => {
2743 ::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")
2744 }
2745 Res::Def(DefKind::Fn | DefKind::AssocFn, did) => {
2747 self.dcx().span_delayed_bug(span, "function items cannot be used as const args");
2748 let args = self.lower_generic_args_of_path_segment(
2749 span,
2750 did,
2751 path.segments.last().unwrap(),
2752 );
2753 ty::Const::zero_sized(tcx, Ty::new_fn_def(tcx, did, args))
2754 }
2755
2756 res @ (Res::Def(
2759 DefKind::Mod
2760 | DefKind::Enum
2761 | DefKind::Variant
2762 | DefKind::Struct
2763 | DefKind::OpaqueTy
2764 | DefKind::TyAlias
2765 | DefKind::TraitAlias
2766 | DefKind::AssocTy
2767 | DefKind::Union
2768 | DefKind::Trait
2769 | DefKind::ForeignTy
2770 | DefKind::TyParam
2771 | DefKind::Macro(_)
2772 | DefKind::LifetimeParam
2773 | DefKind::Use
2774 | DefKind::ForeignMod
2775 | DefKind::AnonConst
2776 | DefKind::InlineConst
2777 | DefKind::Field
2778 | DefKind::Impl { .. }
2779 | DefKind::Closure
2780 | DefKind::ExternCrate
2781 | DefKind::GlobalAsm
2782 | DefKind::SyntheticCoroutineBody,
2783 _,
2784 )
2785 | Res::PrimTy(_)
2786 | Res::SelfTyParam { .. }
2787 | Res::SelfTyAlias { .. }
2788 | Res::SelfCtor(_)
2789 | Res::Local(_)
2790 | Res::ToolMod
2791 | Res::OpenMod(..)
2792 | Res::NonMacroAttr(_)
2793 | Res::Err) => Const::new_error_with_message(
2794 tcx,
2795 span,
2796 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("invalid Res {0:?} for const path",
res))
})format!("invalid Res {res:?} for const path"),
2797 ),
2798 };
2799 self.check_param_uses_if_mcg(ct, span, false)
2800 }
2801
2802 #[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(2803u32),
::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:2808",
"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(2808u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&["expr"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&expr) as
&dyn Value))])
});
} else { ; }
};
let ty =
tcx.type_of(anon.def_id).instantiate_identity().skip_norm_wip();
match self.try_lower_anon_const_lit(ty, expr) {
Some(v) => v,
None =>
ty::Const::new_unevaluated(tcx,
ty::UnevaluatedConst {
def: anon.def_id.to_def_id(),
args: ty::GenericArgs::identity_for_item(tcx,
anon.def_id.to_def_id()),
}),
}
}
}
}#[instrument(skip(self), level = "debug")]
2804 fn lower_const_arg_anon(&self, anon: &AnonConst) -> Const<'tcx> {
2805 let tcx = self.tcx();
2806
2807 let expr = &tcx.hir_body(anon.body).value;
2808 debug!(?expr);
2809
2810 let ty = tcx.type_of(anon.def_id).instantiate_identity().skip_norm_wip();
2814
2815 match self.try_lower_anon_const_lit(ty, expr) {
2816 Some(v) => v,
2817 None => ty::Const::new_unevaluated(
2818 tcx,
2819 ty::UnevaluatedConst {
2820 def: anon.def_id.to_def_id(),
2821 args: ty::GenericArgs::identity_for_item(tcx, anon.def_id.to_def_id()),
2822 },
2823 ),
2824 }
2825 }
2826
2827 #[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(2827u32),
::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")]
2828 fn lower_const_arg_literal(
2829 &self,
2830 kind: &LitKind,
2831 neg: bool,
2832 ty: Ty<'tcx>,
2833 span: Span,
2834 ) -> Const<'tcx> {
2835 let tcx = self.tcx();
2836
2837 let ty = if !ty.has_infer() { Some(ty) } else { None };
2838
2839 if let LitKind::Err(guar) = *kind {
2840 return ty::Const::new_error(tcx, guar);
2841 }
2842 let input = LitToConstInput { lit: *kind, ty, neg };
2843 match tcx.at(span).lit_to_const(input) {
2844 Some(value) => ty::Const::new_value(tcx, value.valtree, value.ty),
2845 None => {
2846 let e = tcx.dcx().span_err(span, "type annotations needed for the literal");
2847 ty::Const::new_error(tcx, e)
2848 }
2849 }
2850 }
2851
2852 #[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(2852u32),
::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")]
2853 fn try_lower_anon_const_lit(
2854 &self,
2855 ty: Ty<'tcx>,
2856 expr: &'tcx hir::Expr<'tcx>,
2857 ) -> Option<Const<'tcx>> {
2858 let tcx = self.tcx();
2859
2860 let expr = match &expr.kind {
2863 hir::ExprKind::Block(block, _) if block.stmts.is_empty() && block.expr.is_some() => {
2864 block.expr.as_ref().unwrap()
2865 }
2866 _ => expr,
2867 };
2868
2869 let lit_input = match expr.kind {
2870 hir::ExprKind::Lit(lit) => {
2871 Some(LitToConstInput { lit: lit.node, ty: Some(ty), neg: false })
2872 }
2873 hir::ExprKind::Unary(hir::UnOp::Neg, expr) => match expr.kind {
2874 hir::ExprKind::Lit(lit) => {
2875 Some(LitToConstInput { lit: lit.node, ty: Some(ty), neg: true })
2876 }
2877 _ => None,
2878 },
2879 _ => None,
2880 };
2881
2882 lit_input.and_then(|l| {
2883 if const_lit_matches_ty(tcx, &l.lit, ty, l.neg) {
2884 tcx.at(expr.span)
2885 .lit_to_const(l)
2886 .map(|value| ty::Const::new_value(tcx, value.valtree, value.ty))
2887 } else {
2888 None
2889 }
2890 })
2891 }
2892
2893 fn require_type_const_attribute(
2894 &self,
2895 def_id: DefId,
2896 span: Span,
2897 ) -> Result<(), ErrorGuaranteed> {
2898 let tcx = self.tcx();
2899 let is_inherent_assoc_const = tcx.def_kind(def_id)
2902 == DefKind::AssocConst { is_type_const: false }
2903 && tcx.def_kind(tcx.parent(def_id)) == DefKind::Impl { of_trait: false };
2904 if tcx.is_type_const(def_id)
2905 || tcx.features().generic_const_args() && !is_inherent_assoc_const
2906 {
2907 Ok(())
2908 } else {
2909 let mut err = self.dcx().struct_span_err(
2910 span,
2911 "use of `const` in the type system not defined as `type const`",
2912 );
2913 if def_id.is_local() {
2914 let name = tcx.def_path_str(def_id);
2915 err.span_suggestion_verbose(
2916 tcx.def_span(def_id).shrink_to_lo(),
2917 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("add `type` before `const` for `{0}`",
name))
})format!("add `type` before `const` for `{name}`"),
2918 ::alloc::__export::must_use({ ::alloc::fmt::format(format_args!("type ")) })format!("type "),
2919 Applicability::MaybeIncorrect,
2920 );
2921 } else {
2922 err.note("only consts marked defined as `type const` may be used in types");
2923 }
2924 Err(err.emit())
2925 }
2926 }
2927
2928 fn lower_delegation_ty(&self, infer: hir::InferDelegation<'tcx>) -> Ty<'tcx> {
2929 match infer {
2930 hir::InferDelegation::DefId(def_id) => {
2931 self.tcx().type_of(def_id).instantiate_identity().skip_norm_wip()
2932 }
2933 rustc_hir::InferDelegation::Sig(_, idx) => {
2934 let delegation_sig = self.tcx().inherit_sig_for_delegation_item(self.item_def_id());
2935
2936 match idx {
2937 hir::InferDelegationSig::Input(idx) => delegation_sig[idx],
2938 hir::InferDelegationSig::Output { .. } => *delegation_sig.last().unwrap(),
2939 }
2940 }
2941 }
2942 }
2943
2944 x;#[instrument(level = "debug", skip(self), ret)]
2946 pub fn lower_ty(&self, hir_ty: &hir::Ty<'tcx>) -> Ty<'tcx> {
2947 let tcx = self.tcx();
2948
2949 let result_ty = match &hir_ty.kind {
2950 hir::TyKind::InferDelegation(infer) => self.lower_delegation_ty(*infer),
2951 hir::TyKind::Slice(ty) => Ty::new_slice(tcx, self.lower_ty(ty)),
2952 hir::TyKind::Ptr(mt) => Ty::new_ptr(tcx, self.lower_ty(mt.ty), mt.mutbl),
2953 hir::TyKind::Ref(region, mt) => {
2954 let r = self.lower_lifetime(region, RegionInferReason::Reference);
2955 debug!(?r);
2956 let t = self.lower_ty(mt.ty);
2957 Ty::new_ref(tcx, r, t, mt.mutbl)
2958 }
2959 hir::TyKind::Never => tcx.types.never,
2960 hir::TyKind::Tup(fields) => {
2961 Ty::new_tup_from_iter(tcx, fields.iter().map(|t| self.lower_ty(t)))
2962 }
2963 hir::TyKind::FnPtr(bf) => {
2964 check_c_variadic_abi(tcx, bf.decl, bf.abi, hir_ty.span);
2965
2966 Ty::new_fn_ptr(
2967 tcx,
2968 self.lower_fn_ty(hir_ty.hir_id, bf.safety, bf.abi, bf.decl, None, Some(hir_ty)),
2969 )
2970 }
2971 hir::TyKind::UnsafeBinder(binder) => Ty::new_unsafe_binder(
2972 tcx,
2973 ty::Binder::bind_with_vars(
2974 self.lower_ty(binder.inner_ty),
2975 tcx.late_bound_vars(hir_ty.hir_id),
2976 ),
2977 ),
2978 hir::TyKind::TraitObject(bounds, tagged_ptr) => {
2979 let lifetime = tagged_ptr.pointer();
2980 let syntax = tagged_ptr.tag();
2981 self.lower_trait_object_ty(hir_ty.span, hir_ty.hir_id, bounds, lifetime, syntax)
2982 }
2983 hir::TyKind::Path(hir::QPath::Resolved(_, path))
2987 if path.segments.last().and_then(|segment| segment.args).is_some_and(|args| {
2988 matches!(args.parenthesized, hir::GenericArgsParentheses::ReturnTypeNotation)
2989 }) =>
2990 {
2991 let guar = self
2992 .dcx()
2993 .emit_err(BadReturnTypeNotation { span: hir_ty.span, suggestion: None });
2994 Ty::new_error(tcx, guar)
2995 }
2996 hir::TyKind::Path(hir::QPath::Resolved(maybe_qself, path)) => {
2997 debug!(?maybe_qself, ?path);
2998 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
2999 self.lower_resolved_ty_path(opt_self_ty, path, hir_ty.hir_id, PermitVariants::No)
3000 }
3001 &hir::TyKind::OpaqueDef(opaque_ty) => {
3002 let in_trait = match opaque_ty.origin {
3006 hir::OpaqueTyOrigin::FnReturn {
3007 parent,
3008 in_trait_or_impl: Some(hir::RpitContext::Trait),
3009 ..
3010 }
3011 | hir::OpaqueTyOrigin::AsyncFn {
3012 parent,
3013 in_trait_or_impl: Some(hir::RpitContext::Trait),
3014 ..
3015 } => Some(parent),
3016 hir::OpaqueTyOrigin::FnReturn {
3017 in_trait_or_impl: None | Some(hir::RpitContext::TraitImpl),
3018 ..
3019 }
3020 | hir::OpaqueTyOrigin::AsyncFn {
3021 in_trait_or_impl: None | Some(hir::RpitContext::TraitImpl),
3022 ..
3023 }
3024 | hir::OpaqueTyOrigin::TyAlias { .. } => None,
3025 };
3026
3027 self.lower_opaque_ty(opaque_ty.def_id, in_trait)
3028 }
3029 hir::TyKind::TraitAscription(hir_bounds) => {
3030 let self_ty = self.ty_infer(None, hir_ty.span);
3033 let mut bounds = Vec::new();
3034 self.lower_bounds(
3035 self_ty,
3036 hir_bounds.iter(),
3037 &mut bounds,
3038 ty::List::empty(),
3039 PredicateFilter::All,
3040 OverlappingAsssocItemConstraints::Allowed,
3041 );
3042 self.add_implicit_sizedness_bounds(
3043 &mut bounds,
3044 self_ty,
3045 hir_bounds,
3046 ImpliedBoundsContext::AssociatedTypeOrImplTrait,
3047 hir_ty.span,
3048 );
3049 self.register_trait_ascription_bounds(bounds, hir_ty.hir_id, hir_ty.span);
3050 self_ty
3051 }
3052 hir::TyKind::Path(hir::QPath::TypeRelative(hir_self_ty, segment))
3056 if segment.args.is_some_and(|args| {
3057 matches!(args.parenthesized, hir::GenericArgsParentheses::ReturnTypeNotation)
3058 }) =>
3059 {
3060 let guar = if let hir::Node::LetStmt(stmt) = tcx.parent_hir_node(hir_ty.hir_id)
3061 && let None = stmt.init
3062 && let hir::TyKind::Path(hir::QPath::Resolved(_, self_ty_path)) =
3063 hir_self_ty.kind
3064 && let Res::Def(DefKind::Enum | DefKind::Struct | DefKind::Union, def_id) =
3065 self_ty_path.res
3066 && let Some(_) = tcx
3067 .inherent_impls(def_id)
3068 .iter()
3069 .flat_map(|imp| {
3070 tcx.associated_items(*imp).filter_by_name_unhygienic(segment.ident.name)
3071 })
3072 .filter(|assoc| {
3073 matches!(assoc.kind, ty::AssocKind::Fn { has_self: false, .. })
3074 })
3075 .next()
3076 {
3077 let err = tcx
3079 .dcx()
3080 .struct_span_err(
3081 hir_ty.span,
3082 "expected type, found associated function call",
3083 )
3084 .with_span_suggestion_verbose(
3085 stmt.pat.span.between(hir_ty.span),
3086 "use `=` if you meant to assign",
3087 " = ".to_string(),
3088 Applicability::MaybeIncorrect,
3089 );
3090 self.dcx().try_steal_replace_and_emit_err(
3091 hir_ty.span,
3092 StashKey::ReturnTypeNotation,
3093 err,
3094 )
3095 } else if let hir::Node::LetStmt(stmt) = tcx.parent_hir_node(hir_ty.hir_id)
3096 && let None = stmt.init
3097 && let hir::TyKind::Path(hir::QPath::Resolved(_, self_ty_path)) =
3098 hir_self_ty.kind
3099 && let Res::PrimTy(_) = self_ty_path.res
3100 && self.dcx().has_stashed_diagnostic(hir_ty.span, StashKey::ReturnTypeNotation)
3101 {
3102 let err = tcx
3105 .dcx()
3106 .struct_span_err(
3107 hir_ty.span,
3108 "expected type, found associated function call",
3109 )
3110 .with_span_suggestion_verbose(
3111 stmt.pat.span.between(hir_ty.span),
3112 "use `=` if you meant to assign",
3113 " = ".to_string(),
3114 Applicability::MaybeIncorrect,
3115 );
3116 self.dcx().try_steal_replace_and_emit_err(
3117 hir_ty.span,
3118 StashKey::ReturnTypeNotation,
3119 err,
3120 )
3121 } else {
3122 let suggestion = if self
3123 .dcx()
3124 .has_stashed_diagnostic(hir_ty.span, StashKey::ReturnTypeNotation)
3125 {
3126 Some(segment.ident.span.shrink_to_hi().with_hi(hir_ty.span.hi()))
3132 } else {
3133 None
3134 };
3135 let err = self
3136 .dcx()
3137 .create_err(BadReturnTypeNotation { span: hir_ty.span, suggestion });
3138 self.dcx().try_steal_replace_and_emit_err(
3139 hir_ty.span,
3140 StashKey::ReturnTypeNotation,
3141 err,
3142 )
3143 };
3144 Ty::new_error(tcx, guar)
3145 }
3146 hir::TyKind::Path(hir::QPath::TypeRelative(hir_self_ty, segment)) => {
3147 debug!(?hir_self_ty, ?segment);
3148 let self_ty = self.lower_ty(hir_self_ty);
3149 self.lower_type_relative_ty_path(
3150 self_ty,
3151 hir_self_ty,
3152 segment,
3153 hir_ty.hir_id,
3154 hir_ty.span,
3155 PermitVariants::No,
3156 )
3157 .map(|(ty, _, _)| ty)
3158 .unwrap_or_else(|guar| Ty::new_error(tcx, guar))
3159 }
3160 hir::TyKind::Array(ty, length) => {
3161 let length = self.lower_const_arg(length, tcx.types.usize);
3162 Ty::new_array_with_const_len(tcx, self.lower_ty(ty), length)
3163 }
3164 hir::TyKind::Infer(()) => {
3165 self.ty_infer(None, hir_ty.span)
3170 }
3171 hir::TyKind::Pat(ty, pat) => {
3172 let ty_span = ty.span;
3173 let ty = self.lower_ty(ty);
3174 let pat_ty = match self.lower_pat_ty_pat(ty, ty_span, pat) {
3175 Ok(kind) => Ty::new_pat(tcx, ty, tcx.mk_pat(kind)),
3176 Err(guar) => Ty::new_error(tcx, guar),
3177 };
3178 self.record_ty(pat.hir_id, ty, pat.span);
3179 pat_ty
3180 }
3181 hir::TyKind::FieldOf(ty, hir::TyFieldPath { variant, field }) => self.lower_field_of(
3182 self.lower_ty(ty),
3183 self.item_def_id(),
3184 ty.span,
3185 hir_ty.hir_id,
3186 *variant,
3187 *field,
3188 ),
3189 hir::TyKind::Err(guar) => Ty::new_error(tcx, *guar),
3190 };
3191
3192 self.record_ty(hir_ty.hir_id, result_ty, hir_ty.span);
3193 result_ty
3194 }
3195
3196 fn lower_pat_ty_pat(
3197 &self,
3198 ty: Ty<'tcx>,
3199 ty_span: Span,
3200 pat: &hir::TyPat<'tcx>,
3201 ) -> Result<ty::PatternKind<'tcx>, ErrorGuaranteed> {
3202 let tcx = self.tcx();
3203 match pat.kind {
3204 hir::TyPatKind::Range(start, end) => {
3205 match ty.kind() {
3206 ty::Int(_) | ty::Uint(_) | ty::Char => {
3209 let start = self.lower_const_arg(start, ty);
3210 let end = self.lower_const_arg(end, ty);
3211 Ok(ty::PatternKind::Range { start, end })
3212 }
3213 _ => Err(self
3214 .dcx()
3215 .span_delayed_bug(ty_span, "invalid base type for range pattern")),
3216 }
3217 }
3218 hir::TyPatKind::NotNull => Ok(ty::PatternKind::NotNull),
3219 hir::TyPatKind::Or(patterns) => {
3220 self.tcx()
3221 .mk_patterns_from_iter(patterns.iter().map(|pat| {
3222 self.lower_pat_ty_pat(ty, ty_span, pat).map(|pat| tcx.mk_pat(pat))
3223 }))
3224 .map(ty::PatternKind::Or)
3225 }
3226 hir::TyPatKind::Err(e) => Err(e),
3227 }
3228 }
3229
3230 fn lower_field_of(
3231 &self,
3232 ty: Ty<'tcx>,
3233 item_def_id: LocalDefId,
3234 ty_span: Span,
3235 hir_id: HirId,
3236 variant: Option<Ident>,
3237 field: Ident,
3238 ) -> Ty<'tcx> {
3239 let dcx = self.dcx();
3240 let tcx = self.tcx();
3241 match ty.kind() {
3242 ty::Adt(def, _) => {
3243 let base_did = def.did();
3244 let kind_name = tcx.def_descr(base_did);
3245 let (variant_idx, variant) = if def.is_enum() {
3246 let Some(variant) = variant else {
3247 let err = dcx
3248 .create_err(NoVariantNamed { span: field.span, ident: field, ty })
3249 .with_span_help(
3250 field.span.shrink_to_lo(),
3251 "you might be missing a variant here: `Variant.`",
3252 )
3253 .emit();
3254 return Ty::new_error(tcx, err);
3255 };
3256
3257 if let Some(res) = def
3258 .variants()
3259 .iter_enumerated()
3260 .find(|(_, f)| f.ident(tcx).normalize_to_macros_2_0() == variant)
3261 {
3262 res
3263 } else {
3264 let err = dcx
3265 .create_err(NoVariantNamed { span: variant.span, ident: variant, ty })
3266 .emit();
3267 return Ty::new_error(tcx, err);
3268 }
3269 } else {
3270 if let Some(variant) = variant {
3271 let adt_path = tcx.def_path_str(base_did);
3272 {
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!(
3273 dcx,
3274 variant.span,
3275 E0609,
3276 "{kind_name} `{adt_path}` does not have any variants",
3277 )
3278 .with_span_label(variant.span, "variant unknown")
3279 .emit();
3280 }
3281 (FIRST_VARIANT, def.non_enum_variant())
3282 };
3283 let block = tcx.local_def_id_to_hir_id(item_def_id);
3284 let (ident, def_scope) = tcx.adjust_ident_and_get_scope(field, def.did(), block);
3285 if let Some((field_idx, field)) = variant
3286 .fields
3287 .iter_enumerated()
3288 .find(|(_, f)| f.ident(tcx).normalize_to_macros_2_0() == ident)
3289 {
3290 if field.vis.is_accessible_from(def_scope, tcx) {
3291 tcx.check_stability(field.did, Some(hir_id), ident.span, None);
3292 } else {
3293 let adt_path = tcx.def_path_str(base_did);
3294 {
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!(
3295 dcx,
3296 ident.span,
3297 E0616,
3298 "field `{ident}` of {kind_name} `{adt_path}` is private",
3299 )
3300 .with_span_label(ident.span, "private field")
3301 .emit();
3302 }
3303 Ty::new_field_representing_type(tcx, ty, variant_idx, field_idx)
3304 } else {
3305 let err =
3306 dcx.create_err(NoFieldOnType { span: ident.span, field: ident, ty }).emit();
3307 Ty::new_error(tcx, err)
3308 }
3309 }
3310 ty::Tuple(tys) => {
3311 let index = match field.as_str().parse::<usize>() {
3312 Ok(idx) => idx,
3313 Err(_) => {
3314 let err =
3315 dcx.create_err(NoFieldOnType { span: field.span, field, ty }).emit();
3316 return Ty::new_error(tcx, err);
3317 }
3318 };
3319 if field.name != sym::integer(index) {
3320 ::rustc_middle::util::bug::bug_fmt(format_args!("we parsed above, but now not equal?"));bug!("we parsed above, but now not equal?");
3321 }
3322 if tys.get(index).is_some() {
3323 Ty::new_field_representing_type(tcx, ty, FIRST_VARIANT, index.into())
3324 } else {
3325 let err = dcx.create_err(NoFieldOnType { span: field.span, field, ty }).emit();
3326 Ty::new_error(tcx, err)
3327 }
3328 }
3329 ty::Alias(..) => Ty::new_error(
3342 tcx,
3343 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}`")),
3344 ),
3345 ty::Error(err) => Ty::new_error(tcx, *err),
3346 ty::Bool
3347 | ty::Char
3348 | ty::Int(_)
3349 | ty::Uint(_)
3350 | ty::Float(_)
3351 | ty::Foreign(_)
3352 | ty::Str
3353 | ty::RawPtr(_, _)
3354 | ty::Ref(_, _, _)
3355 | ty::FnDef(_, _)
3356 | ty::FnPtr(_, _)
3357 | ty::UnsafeBinder(_)
3358 | ty::Dynamic(_, _)
3359 | ty::Closure(_, _)
3360 | ty::CoroutineClosure(_, _)
3361 | ty::Coroutine(_, _)
3362 | ty::CoroutineWitness(_, _)
3363 | ty::Never
3364 | ty::Param(_)
3365 | ty::Bound(_, _)
3366 | ty::Placeholder(_)
3367 | ty::Slice(..) => Ty::new_error(
3368 tcx,
3369 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")),
3370 ),
3371 ty::Infer(_) => Ty::new_error(
3372 tcx,
3373 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")),
3374 ),
3375 ty::Array(..) | ty::Pat(..) => Ty::new_error(
3377 tcx,
3378 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!`")),
3379 ),
3380 }
3381 }
3382
3383 x;#[instrument(level = "debug", skip(self), ret)]
3385 fn lower_opaque_ty(&self, def_id: LocalDefId, in_trait: Option<LocalDefId>) -> Ty<'tcx> {
3386 let tcx = self.tcx();
3387
3388 let lifetimes = tcx.opaque_captured_lifetimes(def_id);
3389 debug!(?lifetimes);
3390
3391 let def_id = if let Some(parent_def_id) = in_trait {
3395 *tcx.associated_types_for_impl_traits_in_associated_fn(parent_def_id.to_def_id())
3396 .iter()
3397 .find(|rpitit| match tcx.opt_rpitit_info(**rpitit) {
3398 Some(ty::ImplTraitInTraitData::Trait { opaque_def_id, .. }) => {
3399 opaque_def_id.expect_local() == def_id
3400 }
3401 _ => unreachable!(),
3402 })
3403 .unwrap()
3404 } else {
3405 def_id.to_def_id()
3406 };
3407
3408 let generics = tcx.generics_of(def_id);
3409 debug!(?generics);
3410
3411 let offset = generics.count() - lifetimes.len();
3415
3416 let args = ty::GenericArgs::for_item(tcx, def_id, |param, _| {
3417 if let Some(i) = (param.index as usize).checked_sub(offset) {
3418 let (lifetime, _) = lifetimes[i];
3419 self.lower_resolved_lifetime(lifetime).into()
3421 } else {
3422 tcx.mk_param_from_def(param)
3423 }
3424 });
3425 debug!(?args);
3426
3427 if in_trait.is_some() {
3428 Ty::new_projection_from_args(tcx, def_id, args)
3429 } else {
3430 Ty::new_opaque(tcx, def_id, args)
3431 }
3432 }
3433
3434 x;#[instrument(level = "debug", skip(self, hir_id, safety, abi, decl, generics, hir_ty), ret)]
3436 pub fn lower_fn_ty(
3437 &self,
3438 hir_id: HirId,
3439 safety: hir::Safety,
3440 abi: rustc_abi::ExternAbi,
3441 decl: &hir::FnDecl<'tcx>,
3442 generics: Option<&hir::Generics<'_>>,
3443 hir_ty: Option<&hir::Ty<'_>>,
3444 ) -> ty::PolyFnSig<'tcx> {
3445 let tcx = self.tcx();
3446 let bound_vars = tcx.late_bound_vars(hir_id);
3447 debug!(?bound_vars);
3448
3449 let (input_tys, output_ty) = self.lower_fn_sig(decl, generics, hir_id, hir_ty);
3450
3451 debug!(?output_ty);
3452
3453 let fn_sig_kind = FnSigKind::default()
3454 .set_abi(abi)
3455 .set_safety(safety)
3456 .set_c_variadic(decl.fn_decl_kind.c_variadic());
3457 let fn_ty = tcx.mk_fn_sig(input_tys, output_ty, fn_sig_kind);
3458 let fn_ptr_ty = ty::Binder::bind_with_vars(fn_ty, bound_vars);
3459
3460 if let hir::Node::Ty(hir::Ty { kind: hir::TyKind::FnPtr(fn_ptr_ty), span, .. }) =
3461 tcx.hir_node(hir_id)
3462 {
3463 check_abi(tcx, hir_id, *span, fn_ptr_ty.abi);
3464 }
3465
3466 cmse::validate_cmse_abi(self.tcx(), self.dcx(), hir_id, abi, fn_ptr_ty);
3468
3469 if !fn_ptr_ty.references_error() {
3470 let inputs = fn_ptr_ty.inputs();
3477 let late_bound_in_args =
3478 tcx.collect_constrained_late_bound_regions(inputs.map_bound(|i| i.to_owned()));
3479 let output = fn_ptr_ty.output();
3480 let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(output);
3481
3482 self.validate_late_bound_regions(late_bound_in_args, late_bound_in_ret, |br_name| {
3483 struct_span_code_err!(
3484 self.dcx(),
3485 decl.output.span(),
3486 E0581,
3487 "return type references {}, which is not constrained by the fn input types",
3488 br_name
3489 )
3490 });
3491 }
3492
3493 fn_ptr_ty
3494 }
3495
3496 pub(super) fn suggest_trait_fn_ty_for_impl_fn_infer(
3501 &self,
3502 fn_hir_id: HirId,
3503 arg_idx: Option<usize>,
3504 ) -> Option<Ty<'tcx>> {
3505 let tcx = self.tcx();
3506 let hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), ident, .. }) =
3507 tcx.hir_node(fn_hir_id)
3508 else {
3509 return None;
3510 };
3511 let i = tcx.parent_hir_node(fn_hir_id).expect_item().expect_impl();
3512
3513 let trait_ref = self.lower_impl_trait_ref(&i.of_trait?.trait_ref, self.lower_ty(i.self_ty));
3514
3515 let assoc = tcx.associated_items(trait_ref.def_id).find_by_ident_and_kind(
3516 tcx,
3517 *ident,
3518 ty::AssocTag::Fn,
3519 trait_ref.def_id,
3520 )?;
3521
3522 let fn_sig = tcx
3523 .fn_sig(assoc.def_id)
3524 .instantiate(
3525 tcx,
3526 trait_ref
3527 .args
3528 .extend_to(tcx, assoc.def_id, |param, _| tcx.mk_param_from_def(param)),
3529 )
3530 .skip_norm_wip();
3531 let fn_sig = tcx.liberate_late_bound_regions(fn_hir_id.expect_owner().to_def_id(), fn_sig);
3532
3533 Some(if let Some(arg_idx) = arg_idx {
3534 *fn_sig.inputs().get(arg_idx)?
3535 } else {
3536 fn_sig.output()
3537 })
3538 }
3539
3540 #[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(3540u32),
::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))]
3541 fn validate_late_bound_regions<'cx>(
3542 &'cx self,
3543 constrained_regions: FxIndexSet<ty::BoundRegionKind<'tcx>>,
3544 referenced_regions: FxIndexSet<ty::BoundRegionKind<'tcx>>,
3545 generate_err: impl Fn(&str) -> Diag<'cx>,
3546 ) {
3547 for br in referenced_regions.difference(&constrained_regions) {
3548 let br_name = if let Some(name) = br.get_name(self.tcx()) {
3549 format!("lifetime `{name}`")
3550 } else {
3551 "an anonymous lifetime".to_string()
3552 };
3553
3554 let mut err = generate_err(&br_name);
3555
3556 if !br.is_named(self.tcx()) {
3557 err.note(
3564 "lifetimes appearing in an associated or opaque type are not considered constrained",
3565 );
3566 err.note("consider introducing a named lifetime parameter");
3567 }
3568
3569 err.emit();
3570 }
3571 }
3572
3573 fn construct_const_ctor_value(
3574 &self,
3575 ctor_def_id: DefId,
3576 ctor_of: CtorOf,
3577 args: GenericArgsRef<'tcx>,
3578 ) -> Const<'tcx> {
3579 let tcx = self.tcx();
3580 let parent_did = tcx.parent(ctor_def_id);
3581
3582 let adt_def = tcx.adt_def(match ctor_of {
3583 CtorOf::Variant => tcx.parent(parent_did),
3584 CtorOf::Struct => parent_did,
3585 });
3586
3587 let variant_idx = adt_def.variant_index_with_id(parent_did);
3588
3589 let valtree = if adt_def.is_enum() {
3590 let discr = ty::ValTree::from_scalar_int(tcx, variant_idx.as_u32().into());
3591 ty::ValTree::from_branches(tcx, [ty::Const::new_value(tcx, discr, tcx.types.u32)])
3592 } else {
3593 ty::ValTree::zst(tcx)
3594 };
3595
3596 let adt_ty = Ty::new_adt(tcx, adt_def, args);
3597 ty::Const::new_value(tcx, valtree, adt_ty)
3598 }
3599}