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