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