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