1mod bounds;
17mod cmse;
18mod dyn_trait;
19pub mod errors;
20pub mod generics;
21
22use std::slice;
23
24use rustc_ast::LitKind;
25use rustc_data_structures::assert_matches;
26use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet};
27use rustc_errors::codes::*;
28use rustc_errors::{
29 Applicability, Diag, DiagCtxtHandle, ErrorGuaranteed, FatalError, struct_span_code_err,
30};
31use rustc_hir::attrs::AttributeKind;
32use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res};
33use rustc_hir::def_id::{DefId, LocalDefId};
34use rustc_hir::{self as hir, AnonConst, GenericArg, GenericArgs, HirId, find_attr};
35use rustc_infer::infer::{InferCtxt, TyCtxtInferExt};
36use rustc_infer::traits::DynCompatibilityViolation;
37use rustc_macros::{TypeFoldable, TypeVisitable};
38use rustc_middle::middle::stability::AllowUnstable;
39use rustc_middle::mir::interpret::LitToConstInput;
40use rustc_middle::ty::print::PrintPolyTraitRefExt as _;
41use rustc_middle::ty::{
42 self, Const, GenericArgKind, GenericArgsRef, GenericParamDefKind, Ty, TyCtxt,
43 TypeSuperFoldable, TypeVisitableExt, TypingMode, Upcast, fold_regions,
44};
45use rustc_middle::{bug, span_bug};
46use rustc_session::lint::builtin::AMBIGUOUS_ASSOCIATED_ITEMS;
47use rustc_session::parse::feature_err;
48use rustc_span::{DUMMY_SP, Ident, Span, kw, sym};
49use rustc_trait_selection::infer::InferCtxtExt;
50use rustc_trait_selection::traits::wf::object_region_bounds;
51use rustc_trait_selection::traits::{self, FulfillmentError};
52use tracing::{debug, instrument};
53
54use crate::check::check_abi;
55use crate::check_c_variadic_abi;
56use crate::errors::{AmbiguousLifetimeBound, BadReturnTypeNotation};
57use crate::hir_ty_lowering::errors::{GenericsArgsErrExtend, prohibit_assoc_item_constraint};
58use crate::hir_ty_lowering::generics::{check_generic_arg_count, lower_generic_args};
59use crate::middle::resolve_bound_vars as rbv;
60
61#[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)]
64pub(crate) enum ImpliedBoundsContext<'tcx> {
65 TraitDef(LocalDefId),
68 TyParam(LocalDefId, &'tcx [hir::WherePredicate<'tcx>]),
70 AssociatedTypeOrImplTrait,
72}
73
74#[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)]
76pub struct GenericPathSegment(pub DefId, pub usize);
77
78#[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)]
79pub enum PredicateFilter {
80 All,
82
83 SelfOnly,
85
86 SelfTraitThatDefines(Ident),
90
91 SelfAndAssociatedTypeBounds,
95
96 ConstIfConst,
98
99 SelfConstIfConst,
101}
102
103#[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 =>
::core::fmt::Formatter::write_str(f, "ObjectLifetimeDefault"),
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)]
104pub enum RegionInferReason<'a> {
105 ExplicitObjectLifetime,
107 ObjectLifetimeDefault,
109 Param(&'a ty::GenericParamDef),
111 RegionPredicate,
112 Reference,
113 OutlivesBound,
114}
115
116#[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)]
117pub struct InherentAssocCandidate {
118 pub impl_: DefId,
119 pub assoc_item: DefId,
120 pub scope: DefId,
121}
122
123pub trait HirTyLowerer<'tcx> {
128 fn tcx(&self) -> TyCtxt<'tcx>;
129
130 fn dcx(&self) -> DiagCtxtHandle<'_>;
131
132 fn item_def_id(&self) -> LocalDefId;
134
135 fn re_infer(&self, span: Span, reason: RegionInferReason<'_>) -> ty::Region<'tcx>;
137
138 fn ty_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx>;
140
141 fn ct_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Const<'tcx>;
143
144 fn register_trait_ascription_bounds(
145 &self,
146 bounds: Vec<(ty::Clause<'tcx>, Span)>,
147 hir_id: HirId,
148 span: Span,
149 );
150
151 fn probe_ty_param_bounds(
166 &self,
167 span: Span,
168 def_id: LocalDefId,
169 assoc_ident: Ident,
170 ) -> ty::EarlyBinder<'tcx, &'tcx [(ty::Clause<'tcx>, Span)]>;
171
172 fn select_inherent_assoc_candidates(
173 &self,
174 span: Span,
175 self_ty: Ty<'tcx>,
176 candidates: Vec<InherentAssocCandidate>,
177 ) -> (Vec<InherentAssocCandidate>, Vec<FulfillmentError<'tcx>>);
178
179 fn lower_assoc_item_path(
192 &self,
193 span: Span,
194 item_def_id: DefId,
195 item_segment: &hir::PathSegment<'tcx>,
196 poly_trait_ref: ty::PolyTraitRef<'tcx>,
197 ) -> Result<(DefId, GenericArgsRef<'tcx>), ErrorGuaranteed>;
198
199 fn lower_fn_sig(
200 &self,
201 decl: &hir::FnDecl<'tcx>,
202 generics: Option<&hir::Generics<'_>>,
203 hir_id: HirId,
204 hir_ty: Option<&hir::Ty<'_>>,
205 ) -> (Vec<Ty<'tcx>>, Ty<'tcx>);
206
207 fn probe_adt(&self, span: Span, ty: Ty<'tcx>) -> Option<ty::AdtDef<'tcx>>;
214
215 fn record_ty(&self, hir_id: HirId, ty: Ty<'tcx>, span: Span);
217
218 fn infcx(&self) -> Option<&InferCtxt<'tcx>>;
220
221 fn lowerer(&self) -> &dyn HirTyLowerer<'tcx>
226 where
227 Self: Sized,
228 {
229 self
230 }
231
232 fn dyn_compatibility_violations(&self, trait_def_id: DefId) -> Vec<DynCompatibilityViolation>;
235}
236
237enum AssocItemQSelf {
241 Trait(DefId),
242 TyParam(LocalDefId, Span),
243 SelfTyAlias,
244}
245
246impl AssocItemQSelf {
247 fn to_string(&self, tcx: TyCtxt<'_>) -> String {
248 match *self {
249 Self::Trait(def_id) => tcx.def_path_str(def_id),
250 Self::TyParam(def_id, _) => tcx.hir_ty_param_name(def_id).to_string(),
251 Self::SelfTyAlias => kw::SelfUpper.to_string(),
252 }
253 }
254}
255
256#[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)]
257enum LowerTypeRelativePathMode {
258 Type(PermitVariants),
259 Const,
260}
261
262impl LowerTypeRelativePathMode {
263 fn assoc_tag(self) -> ty::AssocTag {
264 match self {
265 Self::Type(_) => ty::AssocTag::Type,
266 Self::Const => ty::AssocTag::Const,
267 }
268 }
269
270 fn def_kind(self) -> DefKind {
271 match self {
272 Self::Type(_) => DefKind::AssocTy,
273 Self::Const => DefKind::AssocConst,
274 }
275 }
276
277 fn permit_variants(self) -> PermitVariants {
278 match self {
279 Self::Type(permit_variants) => permit_variants,
280 Self::Const => PermitVariants::No,
283 }
284 }
285}
286
287#[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)]
289pub enum PermitVariants {
290 Yes,
291 No,
292}
293
294#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for TypeRelativePath<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
TypeRelativePath::AssocItem(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"AssocItem", __self_0, &__self_1),
TypeRelativePath::Variant { adt: __self_0, variant_did: __self_1 }
=>
::core::fmt::Formatter::debug_struct_field2_finish(f,
"Variant", "adt", __self_0, "variant_did", &__self_1),
TypeRelativePath::Ctor { ctor_def_id: __self_0, args: __self_1 }
=>
::core::fmt::Formatter::debug_struct_field2_finish(f, "Ctor",
"ctor_def_id", __self_0, "args", &__self_1),
}
}
}Debug, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for TypeRelativePath<'tcx> {
#[inline]
fn clone(&self) -> TypeRelativePath<'tcx> {
let _: ::core::clone::AssertParamIsClone<DefId>;
let _: ::core::clone::AssertParamIsClone<GenericArgsRef<'tcx>>;
let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
let _: ::core::clone::AssertParamIsClone<GenericArgsRef<'tcx>>;
*self
}
}Clone, #[automatically_derived]
impl<'tcx> ::core::marker::Copy for TypeRelativePath<'tcx> { }Copy)]
295enum TypeRelativePath<'tcx> {
296 AssocItem(DefId, GenericArgsRef<'tcx>),
297 Variant { adt: Ty<'tcx>, variant_did: DefId },
298 Ctor { ctor_def_id: DefId, args: GenericArgsRef<'tcx> },
299}
300
301#[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)]
311pub enum ExplicitLateBound {
312 Yes,
313 No,
314}
315
316#[derive(#[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)]
317pub enum IsMethodCall {
318 Yes,
319 No,
320}
321
322#[derive(#[automatically_derived]
impl ::core::marker::Copy for GenericArgPosition { }Copy, #[automatically_derived]
impl ::core::clone::Clone for GenericArgPosition {
#[inline]
fn clone(&self) -> GenericArgPosition { *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
}
}PartialEq)]
325pub(crate) enum GenericArgPosition {
326 Type,
327 Value, MethodCall,
329}
330
331#[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)]
335pub(crate) enum OverlappingAsssocItemConstraints {
336 Allowed,
337 Forbidden,
338}
339
340#[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)]
343pub struct GenericArgCountMismatch {
344 pub reported: ErrorGuaranteed,
345 pub invalid_args: Vec<usize>,
347}
348
349#[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)]
352pub struct GenericArgCountResult {
353 pub explicit_late_bound: ExplicitLateBound,
354 pub correct: Result<(), GenericArgCountMismatch>,
355}
356
357pub trait GenericArgsLowerer<'a, 'tcx> {
362 fn args_for_def_id(&mut self, def_id: DefId) -> (Option<&'a GenericArgs<'tcx>>, bool);
363
364 fn provided_kind(
365 &mut self,
366 preceding_args: &[ty::GenericArg<'tcx>],
367 param: &ty::GenericParamDef,
368 arg: &GenericArg<'tcx>,
369 ) -> ty::GenericArg<'tcx>;
370
371 fn inferred_kind(
372 &mut self,
373 preceding_args: &[ty::GenericArg<'tcx>],
374 param: &ty::GenericParamDef,
375 infer_args: bool,
376 ) -> ty::GenericArg<'tcx>;
377}
378
379struct ForbidMCGParamUsesFolder<'tcx> {
380 tcx: TyCtxt<'tcx>,
381 anon_const_def_id: LocalDefId,
382 span: Span,
383 is_self_alias: bool,
384}
385
386impl<'tcx> ForbidMCGParamUsesFolder<'tcx> {
387 fn error(&self) -> ErrorGuaranteed {
388 let msg = if self.is_self_alias {
389 "generic `Self` types are currently not permitted in anonymous constants"
390 } else {
391 "generic parameters may not be used in const operations"
392 };
393 let mut diag = self.tcx.dcx().struct_span_err(self.span, msg);
394 if self.is_self_alias {
395 let anon_const_hir_id: HirId = HirId::make_owner(self.anon_const_def_id);
396 let parent_impl = self.tcx.hir_parent_owner_iter(anon_const_hir_id).find_map(
397 |(_, node)| match node {
398 hir::OwnerNode::Item(hir::Item {
399 kind: hir::ItemKind::Impl(impl_), ..
400 }) => Some(impl_),
401 _ => None,
402 },
403 );
404 if let Some(impl_) = parent_impl {
405 diag.span_note(impl_.self_ty.span, "not a concrete type");
406 }
407 }
408 diag.emit()
409 }
410}
411
412impl<'tcx> ty::TypeFolder<TyCtxt<'tcx>> for ForbidMCGParamUsesFolder<'tcx> {
413 fn cx(&self) -> TyCtxt<'tcx> {
414 self.tcx
415 }
416
417 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
418 if #[allow(non_exhaustive_omitted_patterns)] match t.kind() {
ty::Param(..) => true,
_ => false,
}matches!(t.kind(), ty::Param(..)) {
419 return Ty::new_error(self.tcx, self.error());
420 }
421 t.super_fold_with(self)
422 }
423
424 fn fold_const(&mut self, c: Const<'tcx>) -> Const<'tcx> {
425 if #[allow(non_exhaustive_omitted_patterns)] match c.kind() {
ty::ConstKind::Param(..) => true,
_ => false,
}matches!(c.kind(), ty::ConstKind::Param(..)) {
426 return Const::new_error(self.tcx, self.error());
427 }
428 c.super_fold_with(self)
429 }
430
431 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
432 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(..)) {
433 return ty::Region::new_error(self.tcx, self.error());
434 }
435 r
436 }
437}
438
439impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
440 pub fn check_param_res_if_mcg_for_instantiate_value_path(
444 &self,
445 res: Res,
446 span: Span,
447 ) -> Result<(), ErrorGuaranteed> {
448 let tcx = self.tcx();
449 let parent_def_id = self.item_def_id();
450 if let Res::Def(DefKind::ConstParam, _) = res
451 && tcx.def_kind(parent_def_id) == DefKind::AnonConst
452 && let ty::AnonConstKind::MCG = tcx.anon_const_kind(parent_def_id)
453 {
454 let folder = ForbidMCGParamUsesFolder {
455 tcx,
456 anon_const_def_id: parent_def_id,
457 span,
458 is_self_alias: false,
459 };
460 return Err(folder.error());
461 }
462 Ok(())
463 }
464
465 #[must_use = "need to use transformed output"]
468 fn check_param_uses_if_mcg<T>(&self, term: T, span: Span, is_self_alias: bool) -> T
469 where
470 T: ty::TypeFoldable<TyCtxt<'tcx>>,
471 {
472 let tcx = self.tcx();
473 let parent_def_id = self.item_def_id();
474 if tcx.def_kind(parent_def_id) == DefKind::AnonConst
475 && let ty::AnonConstKind::MCG = tcx.anon_const_kind(parent_def_id)
476 && (term.has_param() || term.has_escaping_bound_vars())
478 {
479 let mut folder = ForbidMCGParamUsesFolder {
480 tcx,
481 anon_const_def_id: parent_def_id,
482 span,
483 is_self_alias,
484 };
485 term.fold_with(&mut folder)
486 } else {
487 term
488 }
489 }
490
491 x;#[instrument(level = "debug", skip(self), ret)]
493 pub fn lower_lifetime(
494 &self,
495 lifetime: &hir::Lifetime,
496 reason: RegionInferReason<'_>,
497 ) -> ty::Region<'tcx> {
498 if let Some(resolved) = self.tcx().named_bound_var(lifetime.hir_id) {
499 let region = self.lower_resolved_lifetime(resolved);
500 self.check_param_uses_if_mcg(region, lifetime.ident.span, false)
501 } else {
502 self.re_infer(lifetime.ident.span, reason)
503 }
504 }
505
506 x;#[instrument(level = "debug", skip(self), ret)]
508 fn lower_resolved_lifetime(&self, resolved: rbv::ResolvedArg) -> ty::Region<'tcx> {
509 let tcx = self.tcx();
510
511 match resolved {
512 rbv::ResolvedArg::StaticLifetime => tcx.lifetimes.re_static,
513
514 rbv::ResolvedArg::LateBound(debruijn, index, def_id) => {
515 let br = ty::BoundRegion {
516 var: ty::BoundVar::from_u32(index),
517 kind: ty::BoundRegionKind::Named(def_id.to_def_id()),
518 };
519 ty::Region::new_bound(tcx, debruijn, br)
520 }
521
522 rbv::ResolvedArg::EarlyBound(def_id) => {
523 let name = tcx.hir_ty_param_name(def_id);
524 let item_def_id = tcx.hir_ty_param_owner(def_id);
525 let generics = tcx.generics_of(item_def_id);
526 let index = generics.param_def_id_to_index[&def_id.to_def_id()];
527 ty::Region::new_early_param(tcx, ty::EarlyParamRegion { index, name })
528 }
529
530 rbv::ResolvedArg::Free(scope, id) => {
531 ty::Region::new_late_param(
532 tcx,
533 scope.to_def_id(),
534 ty::LateParamRegionKind::Named(id.to_def_id()),
535 )
536
537 }
539
540 rbv::ResolvedArg::Error(guar) => ty::Region::new_error(tcx, guar),
541 }
542 }
543
544 pub fn lower_generic_args_of_path_segment(
545 &self,
546 span: Span,
547 def_id: DefId,
548 item_segment: &hir::PathSegment<'tcx>,
549 ) -> GenericArgsRef<'tcx> {
550 let (args, _) = self.lower_generic_args_of_path(span, def_id, &[], item_segment, None);
551 if let Some(c) = item_segment.args().constraints.first() {
552 prohibit_assoc_item_constraint(self, c, Some((def_id, item_segment, span)));
553 }
554 args
555 }
556
557 x;#[instrument(level = "debug", skip(self, span), ret)]
592 fn lower_generic_args_of_path(
593 &self,
594 span: Span,
595 def_id: DefId,
596 parent_args: &[ty::GenericArg<'tcx>],
597 segment: &hir::PathSegment<'tcx>,
598 self_ty: Option<Ty<'tcx>>,
599 ) -> (GenericArgsRef<'tcx>, GenericArgCountResult) {
600 let tcx = self.tcx();
605 let generics = tcx.generics_of(def_id);
606 debug!(?generics);
607
608 if generics.has_self {
609 if generics.parent.is_some() {
610 assert!(!parent_args.is_empty())
613 } else {
614 assert!(self_ty.is_some());
616 }
617 } else {
618 assert!(self_ty.is_none());
619 }
620
621 let arg_count = check_generic_arg_count(
622 self,
623 def_id,
624 segment,
625 generics,
626 GenericArgPosition::Type,
627 self_ty.is_some(),
628 );
629
630 if generics.is_own_empty() {
635 return (tcx.mk_args(parent_args), arg_count);
636 }
637
638 struct GenericArgsCtxt<'a, 'tcx> {
639 lowerer: &'a dyn HirTyLowerer<'tcx>,
640 def_id: DefId,
641 generic_args: &'a GenericArgs<'tcx>,
642 span: Span,
643 infer_args: bool,
644 incorrect_args: &'a Result<(), GenericArgCountMismatch>,
645 }
646
647 impl<'a, 'tcx> GenericArgsLowerer<'a, 'tcx> for GenericArgsCtxt<'a, 'tcx> {
648 fn args_for_def_id(&mut self, did: DefId) -> (Option<&'a GenericArgs<'tcx>>, bool) {
649 if did == self.def_id {
650 (Some(self.generic_args), self.infer_args)
651 } else {
652 (None, false)
654 }
655 }
656
657 fn provided_kind(
658 &mut self,
659 preceding_args: &[ty::GenericArg<'tcx>],
660 param: &ty::GenericParamDef,
661 arg: &GenericArg<'tcx>,
662 ) -> ty::GenericArg<'tcx> {
663 let tcx = self.lowerer.tcx();
664
665 if let Err(incorrect) = self.incorrect_args {
666 if incorrect.invalid_args.contains(&(param.index as usize)) {
667 return param.to_error(tcx);
668 }
669 }
670
671 let handle_ty_args = |has_default, ty: &hir::Ty<'tcx>| {
672 if has_default {
673 tcx.check_optional_stability(
674 param.def_id,
675 Some(arg.hir_id()),
676 arg.span(),
677 None,
678 AllowUnstable::No,
679 |_, _| {
680 },
686 );
687 }
688 self.lowerer.lower_ty(ty).into()
689 };
690
691 match (¶m.kind, arg) {
692 (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => {
693 self.lowerer.lower_lifetime(lt, RegionInferReason::Param(param)).into()
694 }
695 (&GenericParamDefKind::Type { has_default, .. }, GenericArg::Type(ty)) => {
696 handle_ty_args(has_default, ty.as_unambig_ty())
698 }
699 (&GenericParamDefKind::Type { has_default, .. }, GenericArg::Infer(inf)) => {
700 handle_ty_args(has_default, &inf.to_ty())
701 }
702 (GenericParamDefKind::Const { .. }, GenericArg::Const(ct)) => self
703 .lowerer
704 .lower_const_arg(
706 ct.as_unambig_ct(),
707 tcx.type_of(param.def_id).instantiate(tcx, preceding_args),
708 )
709 .into(),
710 (&GenericParamDefKind::Const { .. }, GenericArg::Infer(inf)) => {
711 self.lowerer.ct_infer(Some(param), inf.span).into()
712 }
713 (kind, arg) => span_bug!(
714 self.span,
715 "mismatched path argument for kind {kind:?}: found arg {arg:?}"
716 ),
717 }
718 }
719
720 fn inferred_kind(
721 &mut self,
722 preceding_args: &[ty::GenericArg<'tcx>],
723 param: &ty::GenericParamDef,
724 infer_args: bool,
725 ) -> ty::GenericArg<'tcx> {
726 let tcx = self.lowerer.tcx();
727
728 if let Err(incorrect) = self.incorrect_args {
729 if incorrect.invalid_args.contains(&(param.index as usize)) {
730 return param.to_error(tcx);
731 }
732 }
733 match param.kind {
734 GenericParamDefKind::Lifetime => {
735 self.lowerer.re_infer(self.span, RegionInferReason::Param(param)).into()
736 }
737 GenericParamDefKind::Type { has_default, .. } => {
738 if !infer_args && has_default {
739 if let Some(prev) =
741 preceding_args.iter().find_map(|arg| match arg.kind() {
742 GenericArgKind::Type(ty) => ty.error_reported().err(),
743 _ => None,
744 })
745 {
746 return Ty::new_error(tcx, prev).into();
748 }
749 tcx.at(self.span)
750 .type_of(param.def_id)
751 .instantiate(tcx, preceding_args)
752 .into()
753 } else if infer_args {
754 self.lowerer.ty_infer(Some(param), self.span).into()
755 } else {
756 Ty::new_misc_error(tcx).into()
758 }
759 }
760 GenericParamDefKind::Const { has_default, .. } => {
761 let ty = tcx
762 .at(self.span)
763 .type_of(param.def_id)
764 .instantiate(tcx, preceding_args);
765 if let Err(guar) = ty.error_reported() {
766 return ty::Const::new_error(tcx, guar).into();
767 }
768 if !infer_args && has_default {
769 tcx.const_param_default(param.def_id)
770 .instantiate(tcx, preceding_args)
771 .into()
772 } else if infer_args {
773 self.lowerer.ct_infer(Some(param), self.span).into()
774 } else {
775 ty::Const::new_misc_error(tcx).into()
777 }
778 }
779 }
780 }
781 }
782
783 let mut args_ctx = GenericArgsCtxt {
784 lowerer: self,
785 def_id,
786 span,
787 generic_args: segment.args(),
788 infer_args: segment.infer_args,
789 incorrect_args: &arg_count.correct,
790 };
791 let args = lower_generic_args(
792 self,
793 def_id,
794 parent_args,
795 self_ty.is_some(),
796 self_ty,
797 &arg_count,
798 &mut args_ctx,
799 );
800
801 (args, arg_count)
802 }
803
804 #[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(804u32),
::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))]
805 pub fn lower_generic_args_of_assoc_item(
806 &self,
807 span: Span,
808 item_def_id: DefId,
809 item_segment: &hir::PathSegment<'tcx>,
810 parent_args: GenericArgsRef<'tcx>,
811 ) -> GenericArgsRef<'tcx> {
812 let (args, _) =
813 self.lower_generic_args_of_path(span, item_def_id, parent_args, item_segment, None);
814 if let Some(c) = item_segment.args().constraints.first() {
815 prohibit_assoc_item_constraint(self, c, Some((item_def_id, item_segment, span)));
816 }
817 args
818 }
819
820 pub fn lower_impl_trait_ref(
824 &self,
825 trait_ref: &hir::TraitRef<'tcx>,
826 self_ty: Ty<'tcx>,
827 ) -> ty::TraitRef<'tcx> {
828 let [leading_segments @ .., segment] = trait_ref.path.segments else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
829
830 let _ = self.prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
831
832 self.lower_mono_trait_ref(
833 trait_ref.path.span,
834 trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise()),
835 self_ty,
836 segment,
837 true,
838 )
839 }
840
841 #[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(864u32),
::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:944",
"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(944u32),
::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:951",
"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(&["poly_trait_ref"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&poly_trait_ref)
as &dyn Value))])
});
} else { ; }
};
match predicate_filter {
PredicateFilter::All | PredicateFilter::SelfOnly |
PredicateFilter::SelfTraitThatDefines(..) |
PredicateFilter::SelfAndAssociatedTypeBounds => {
let bound =
poly_trait_ref.map_bound(|trait_ref|
{
ty::ClauseKind::Trait(ty::TraitPredicate {
trait_ref,
polarity,
})
});
let bound = (bound.upcast(tcx), span);
if tcx.is_lang_item(trait_def_id,
rustc_hir::LangItem::Sized) {
bounds.insert(0, bound);
} else { bounds.push(bound); }
}
PredicateFilter::ConstIfConst |
PredicateFilter::SelfConstIfConst => {}
}
if let hir::BoundConstness::Always(span) |
hir::BoundConstness::Maybe(span) = constness &&
!tcx.is_const_trait(trait_def_id) {
let (def_span, suggestion, suggestion_pre) =
match (trait_def_id.as_local(), tcx.sess.is_nightly_build())
{
(Some(trait_def_id), true) => {
let span = tcx.hir_expect_item(trait_def_id).vis_span;
let span =
tcx.sess.source_map().span_extend_while_whitespace(span);
(None, Some(span.shrink_to_hi()),
if self.tcx().features().const_trait_impl() {
""
} else {
"enable `#![feature(const_trait_impl)]` in your crate and "
})
}
(None, _) | (_, false) =>
(Some(tcx.def_span(trait_def_id)), None, ""),
};
self.dcx().emit_err(crate::errors::ConstBoundForNonConstTrait {
span,
modifier: constness.as_str(),
def_span,
trait_name: tcx.def_path_str(trait_def_id),
suggestion,
suggestion_pre,
});
} else {
match predicate_filter {
PredicateFilter::SelfTraitThatDefines(..) => {}
PredicateFilter::All | PredicateFilter::SelfOnly |
PredicateFilter::SelfAndAssociatedTypeBounds => {
match constness {
hir::BoundConstness::Always(_) => {
if polarity == ty::PredicatePolarity::Positive {
bounds.push((poly_trait_ref.to_host_effect_clause(tcx,
ty::BoundConstness::Const), span));
}
}
hir::BoundConstness::Maybe(_) => {}
hir::BoundConstness::Never => {}
}
}
PredicateFilter::ConstIfConst |
PredicateFilter::SelfConstIfConst => {
match constness {
hir::BoundConstness::Maybe(_) => {
if polarity == ty::PredicatePolarity::Positive {
bounds.push((poly_trait_ref.to_host_effect_clause(tcx,
ty::BoundConstness::Maybe), span));
}
}
hir::BoundConstness::Always(_) | hir::BoundConstness::Never
=> {}
}
}
}
}
let mut dup_constraints =
(overlapping_assoc_item_constraints ==
OverlappingAsssocItemConstraints::Forbidden).then_some(FxIndexMap::default());
for constraint in constraints {
if polarity == ty::PredicatePolarity::Negative {
self.dcx().span_delayed_bug(constraint.span,
"negative trait bounds should not have assoc item constraints");
break;
}
let _: Result<_, ErrorGuaranteed> =
self.lower_assoc_item_constraint(trait_ref.hir_ref_id,
poly_trait_ref, constraint, bounds,
dup_constraints.as_mut(), constraint.span,
predicate_filter);
}
arg_count
}
}
}#[instrument(level = "debug", skip(self, bounds))]
865 pub(crate) fn lower_poly_trait_ref(
866 &self,
867 &hir::PolyTraitRef {
868 bound_generic_params,
869 modifiers: hir::TraitBoundModifiers { constness, polarity },
870 trait_ref,
871 span,
872 }: &hir::PolyTraitRef<'tcx>,
873 self_ty: Ty<'tcx>,
874 bounds: &mut Vec<(ty::Clause<'tcx>, Span)>,
875 predicate_filter: PredicateFilter,
876 overlapping_assoc_item_constraints: OverlappingAsssocItemConstraints,
877 ) -> GenericArgCountResult {
878 let tcx = self.tcx();
879
880 let _ = bound_generic_params;
883
884 let trait_def_id = trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise());
885
886 let transient = match polarity {
891 hir::BoundPolarity::Positive => {
892 tcx.is_lang_item(trait_def_id, hir::LangItem::PointeeSized)
898 }
899 hir::BoundPolarity::Negative(_) => false,
900 hir::BoundPolarity::Maybe(_) => {
901 self.require_bound_to_relax_default_trait(trait_ref, span);
902 true
903 }
904 };
905 let bounds = if transient { &mut Vec::new() } else { bounds };
906
907 let polarity = match polarity {
908 hir::BoundPolarity::Positive | hir::BoundPolarity::Maybe(_) => {
909 ty::PredicatePolarity::Positive
910 }
911 hir::BoundPolarity::Negative(_) => ty::PredicatePolarity::Negative,
912 };
913
914 let [leading_segments @ .., segment] = trait_ref.path.segments else { bug!() };
915
916 let _ = self.prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
917 self.report_internal_fn_trait(span, trait_def_id, segment, false);
918
919 let (generic_args, arg_count) = self.lower_generic_args_of_path(
920 trait_ref.path.span,
921 trait_def_id,
922 &[],
923 segment,
924 Some(self_ty),
925 );
926
927 let constraints = segment.args().constraints;
928
929 if transient && (!generic_args[1..].is_empty() || !constraints.is_empty()) {
930 self.dcx()
940 .span_delayed_bug(span, "transient bound should not have args or constraints");
941 }
942
943 let bound_vars = tcx.late_bound_vars(trait_ref.hir_ref_id);
944 debug!(?bound_vars);
945
946 let poly_trait_ref = ty::Binder::bind_with_vars(
947 ty::TraitRef::new_from_args(tcx, trait_def_id, generic_args),
948 bound_vars,
949 );
950
951 debug!(?poly_trait_ref);
952
953 match predicate_filter {
955 PredicateFilter::All
956 | PredicateFilter::SelfOnly
957 | PredicateFilter::SelfTraitThatDefines(..)
958 | PredicateFilter::SelfAndAssociatedTypeBounds => {
959 let bound = poly_trait_ref.map_bound(|trait_ref| {
960 ty::ClauseKind::Trait(ty::TraitPredicate { trait_ref, polarity })
961 });
962 let bound = (bound.upcast(tcx), span);
963 if tcx.is_lang_item(trait_def_id, rustc_hir::LangItem::Sized) {
969 bounds.insert(0, bound);
970 } else {
971 bounds.push(bound);
972 }
973 }
974 PredicateFilter::ConstIfConst | PredicateFilter::SelfConstIfConst => {}
975 }
976
977 if let hir::BoundConstness::Always(span) | hir::BoundConstness::Maybe(span) = constness
978 && !tcx.is_const_trait(trait_def_id)
979 {
980 let (def_span, suggestion, suggestion_pre) =
981 match (trait_def_id.as_local(), tcx.sess.is_nightly_build()) {
982 (Some(trait_def_id), true) => {
983 let span = tcx.hir_expect_item(trait_def_id).vis_span;
984 let span = tcx.sess.source_map().span_extend_while_whitespace(span);
985
986 (
987 None,
988 Some(span.shrink_to_hi()),
989 if self.tcx().features().const_trait_impl() {
990 ""
991 } else {
992 "enable `#![feature(const_trait_impl)]` in your crate and "
993 },
994 )
995 }
996 (None, _) | (_, false) => (Some(tcx.def_span(trait_def_id)), None, ""),
997 };
998 self.dcx().emit_err(crate::errors::ConstBoundForNonConstTrait {
999 span,
1000 modifier: constness.as_str(),
1001 def_span,
1002 trait_name: tcx.def_path_str(trait_def_id),
1003 suggestion,
1004 suggestion_pre,
1005 });
1006 } else {
1007 match predicate_filter {
1008 PredicateFilter::SelfTraitThatDefines(..) => {}
1010 PredicateFilter::All
1011 | PredicateFilter::SelfOnly
1012 | PredicateFilter::SelfAndAssociatedTypeBounds => {
1013 match constness {
1014 hir::BoundConstness::Always(_) => {
1015 if polarity == ty::PredicatePolarity::Positive {
1016 bounds.push((
1017 poly_trait_ref
1018 .to_host_effect_clause(tcx, ty::BoundConstness::Const),
1019 span,
1020 ));
1021 }
1022 }
1023 hir::BoundConstness::Maybe(_) => {
1024 }
1029 hir::BoundConstness::Never => {}
1030 }
1031 }
1032 PredicateFilter::ConstIfConst | PredicateFilter::SelfConstIfConst => {
1039 match constness {
1040 hir::BoundConstness::Maybe(_) => {
1041 if polarity == ty::PredicatePolarity::Positive {
1042 bounds.push((
1043 poly_trait_ref
1044 .to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
1045 span,
1046 ));
1047 }
1048 }
1049 hir::BoundConstness::Always(_) | hir::BoundConstness::Never => {}
1050 }
1051 }
1052 }
1053 }
1054
1055 let mut dup_constraints = (overlapping_assoc_item_constraints
1056 == OverlappingAsssocItemConstraints::Forbidden)
1057 .then_some(FxIndexMap::default());
1058
1059 for constraint in constraints {
1060 if polarity == ty::PredicatePolarity::Negative {
1064 self.dcx().span_delayed_bug(
1065 constraint.span,
1066 "negative trait bounds should not have assoc item constraints",
1067 );
1068 break;
1069 }
1070
1071 let _: Result<_, ErrorGuaranteed> = self.lower_assoc_item_constraint(
1073 trait_ref.hir_ref_id,
1074 poly_trait_ref,
1075 constraint,
1076 bounds,
1077 dup_constraints.as_mut(),
1078 constraint.span,
1079 predicate_filter,
1080 );
1081 }
1083
1084 arg_count
1085 }
1086
1087 fn lower_mono_trait_ref(
1091 &self,
1092 span: Span,
1093 trait_def_id: DefId,
1094 self_ty: Ty<'tcx>,
1095 trait_segment: &hir::PathSegment<'tcx>,
1096 is_impl: bool,
1097 ) -> ty::TraitRef<'tcx> {
1098 self.report_internal_fn_trait(span, trait_def_id, trait_segment, is_impl);
1099
1100 let (generic_args, _) =
1101 self.lower_generic_args_of_path(span, trait_def_id, &[], trait_segment, Some(self_ty));
1102 if let Some(c) = trait_segment.args().constraints.first() {
1103 prohibit_assoc_item_constraint(self, c, Some((trait_def_id, trait_segment, span)));
1104 }
1105 ty::TraitRef::new_from_args(self.tcx(), trait_def_id, generic_args)
1106 }
1107
1108 fn probe_trait_that_defines_assoc_item(
1109 &self,
1110 trait_def_id: DefId,
1111 assoc_tag: ty::AssocTag,
1112 assoc_ident: Ident,
1113 ) -> bool {
1114 self.tcx()
1115 .associated_items(trait_def_id)
1116 .find_by_ident_and_kind(self.tcx(), assoc_ident, assoc_tag, trait_def_id)
1117 .is_some()
1118 }
1119
1120 fn lower_path_segment(
1121 &self,
1122 span: Span,
1123 did: DefId,
1124 item_segment: &hir::PathSegment<'tcx>,
1125 ) -> Ty<'tcx> {
1126 let tcx = self.tcx();
1127 let args = self.lower_generic_args_of_path_segment(span, did, item_segment);
1128
1129 if let DefKind::TyAlias = tcx.def_kind(did)
1130 && tcx.type_alias_is_lazy(did)
1131 {
1132 let alias_ty = ty::AliasTy::new_from_args(tcx, did, args);
1136 Ty::new_alias(tcx, ty::Free, alias_ty)
1137 } else {
1138 tcx.at(span).type_of(did).instantiate(tcx, args)
1139 }
1140 }
1141
1142 x;#[instrument(level = "debug", skip_all, ret)]
1150 fn probe_single_ty_param_bound_for_assoc_item(
1151 &self,
1152 ty_param_def_id: LocalDefId,
1153 ty_param_span: Span,
1154 assoc_tag: ty::AssocTag,
1155 assoc_ident: Ident,
1156 span: Span,
1157 ) -> Result<ty::PolyTraitRef<'tcx>, ErrorGuaranteed> {
1158 debug!(?ty_param_def_id, ?assoc_ident, ?span);
1159 let tcx = self.tcx();
1160
1161 let predicates = &self.probe_ty_param_bounds(span, ty_param_def_id, assoc_ident);
1162 debug!("predicates={:#?}", predicates);
1163
1164 self.probe_single_bound_for_assoc_item(
1165 || {
1166 let trait_refs = predicates
1167 .iter_identity_copied()
1168 .filter_map(|(p, _)| Some(p.as_trait_clause()?.map_bound(|t| t.trait_ref)));
1169 traits::transitive_bounds_that_define_assoc_item(tcx, trait_refs, assoc_ident)
1170 },
1171 AssocItemQSelf::TyParam(ty_param_def_id, ty_param_span),
1172 assoc_tag,
1173 assoc_ident,
1174 span,
1175 None,
1176 )
1177 }
1178
1179 x;#[instrument(level = "debug", skip(self, all_candidates, qself, constraint), ret)]
1185 fn probe_single_bound_for_assoc_item<I>(
1186 &self,
1187 all_candidates: impl Fn() -> I,
1188 qself: AssocItemQSelf,
1189 assoc_tag: ty::AssocTag,
1190 assoc_ident: Ident,
1191 span: Span,
1192 constraint: Option<&hir::AssocItemConstraint<'tcx>>,
1193 ) -> Result<ty::PolyTraitRef<'tcx>, ErrorGuaranteed>
1194 where
1195 I: Iterator<Item = ty::PolyTraitRef<'tcx>>,
1196 {
1197 let tcx = self.tcx();
1198
1199 let mut matching_candidates = all_candidates().filter(|r| {
1200 self.probe_trait_that_defines_assoc_item(r.def_id(), assoc_tag, assoc_ident)
1201 });
1202
1203 let Some(bound) = matching_candidates.next() else {
1204 return Err(self.report_unresolved_assoc_item(
1205 all_candidates,
1206 qself,
1207 assoc_tag,
1208 assoc_ident,
1209 span,
1210 constraint,
1211 ));
1212 };
1213 debug!(?bound);
1214
1215 if let Some(bound2) = matching_candidates.next() {
1216 debug!(?bound2);
1217
1218 let assoc_kind_str = errors::assoc_tag_str(assoc_tag);
1219 let qself_str = qself.to_string(tcx);
1220 let mut err = self.dcx().create_err(crate::errors::AmbiguousAssocItem {
1221 span,
1222 assoc_kind: assoc_kind_str,
1223 assoc_ident,
1224 qself: &qself_str,
1225 });
1226 err.code(
1228 if let Some(constraint) = constraint
1229 && let hir::AssocItemConstraintKind::Equality { .. } = constraint.kind
1230 {
1231 E0222
1232 } else {
1233 E0221
1234 },
1235 );
1236
1237 let mut where_bounds = vec![];
1241 for bound in [bound, bound2].into_iter().chain(matching_candidates) {
1242 let bound_id = bound.def_id();
1243 let assoc_item = tcx.associated_items(bound_id).find_by_ident_and_kind(
1244 tcx,
1245 assoc_ident,
1246 assoc_tag,
1247 bound_id,
1248 );
1249 let bound_span = assoc_item.and_then(|item| tcx.hir_span_if_local(item.def_id));
1250
1251 if let Some(bound_span) = bound_span {
1252 err.span_label(
1253 bound_span,
1254 format!("ambiguous `{assoc_ident}` from `{}`", bound.print_trait_sugared(),),
1255 );
1256 if let Some(constraint) = constraint {
1257 match constraint.kind {
1258 hir::AssocItemConstraintKind::Equality { term } => {
1259 let term: ty::Term<'_> = match term {
1260 hir::Term::Ty(ty) => self.lower_ty(ty).into(),
1261 hir::Term::Const(ct) => {
1262 let assoc_item =
1263 assoc_item.expect("assoc_item should be present");
1264 let projection_term = bound.map_bound(|trait_ref| {
1265 let item_segment = hir::PathSegment {
1266 ident: constraint.ident,
1267 hir_id: constraint.hir_id,
1268 res: Res::Err,
1269 args: Some(constraint.gen_args),
1270 infer_args: false,
1271 };
1272
1273 let alias_args = self.lower_generic_args_of_assoc_item(
1274 constraint.ident.span,
1275 assoc_item.def_id,
1276 &item_segment,
1277 trait_ref.args,
1278 );
1279 ty::AliasTerm::new_from_args(
1280 tcx,
1281 assoc_item.def_id,
1282 alias_args,
1283 )
1284 });
1285
1286 let ty = projection_term.map_bound(|alias| {
1289 tcx.type_of(alias.def_id).instantiate(tcx, alias.args)
1290 });
1291 let ty = bounds::check_assoc_const_binding_type(
1292 self,
1293 constraint.ident,
1294 ty,
1295 constraint.hir_id,
1296 );
1297
1298 self.lower_const_arg(ct, ty).into()
1299 }
1300 };
1301 if term.references_error() {
1302 continue;
1303 }
1304 where_bounds.push(format!(
1306 " T: {trait}::{assoc_ident} = {term}",
1307 trait = bound.print_only_trait_path(),
1308 ));
1309 }
1310 hir::AssocItemConstraintKind::Bound { bounds: _ } => {}
1312 }
1313 } else {
1314 err.span_suggestion_verbose(
1315 span.with_hi(assoc_ident.span.lo()),
1316 "use fully-qualified syntax to disambiguate",
1317 format!("<{qself_str} as {}>::", bound.print_only_trait_path()),
1318 Applicability::MaybeIncorrect,
1319 );
1320 }
1321 } else {
1322 let trait_ =
1323 tcx.short_string(bound.print_only_trait_path(), err.long_ty_path());
1324 err.note(format!(
1325 "associated {assoc_kind_str} `{assoc_ident}` could derive from `{trait_}`",
1326 ));
1327 }
1328 }
1329 if !where_bounds.is_empty() {
1330 err.help(format!(
1331 "consider introducing a new type parameter `T` and adding `where` constraints:\
1332 \n where\n T: {qself_str},\n{}",
1333 where_bounds.join(",\n"),
1334 ));
1335 let reported = err.emit();
1336 return Err(reported);
1337 }
1338 err.emit();
1339 }
1340
1341 Ok(bound)
1342 }
1343
1344 x;#[instrument(level = "debug", skip_all, ret)]
1371 pub fn lower_type_relative_ty_path(
1372 &self,
1373 self_ty: Ty<'tcx>,
1374 hir_self_ty: &'tcx hir::Ty<'tcx>,
1375 segment: &'tcx hir::PathSegment<'tcx>,
1376 qpath_hir_id: HirId,
1377 span: Span,
1378 permit_variants: PermitVariants,
1379 ) -> Result<(Ty<'tcx>, DefKind, DefId), ErrorGuaranteed> {
1380 let tcx = self.tcx();
1381 match self.lower_type_relative_path(
1382 self_ty,
1383 hir_self_ty,
1384 segment,
1385 qpath_hir_id,
1386 span,
1387 LowerTypeRelativePathMode::Type(permit_variants),
1388 )? {
1389 TypeRelativePath::AssocItem(def_id, args) => {
1390 let alias_ty = ty::AliasTy::new_from_args(tcx, def_id, args);
1391 let ty = Ty::new_alias(tcx, alias_ty.kind(tcx), alias_ty);
1392 let ty = self.check_param_uses_if_mcg(ty, span, false);
1393 Ok((ty, tcx.def_kind(def_id), def_id))
1394 }
1395 TypeRelativePath::Variant { adt, variant_did } => {
1396 let adt = self.check_param_uses_if_mcg(adt, span, false);
1397 Ok((adt, DefKind::Variant, variant_did))
1398 }
1399 TypeRelativePath::Ctor { .. } => {
1400 let e = tcx.dcx().span_err(span, "expected type, found tuple constructor");
1401 Err(e)
1402 }
1403 }
1404 }
1405
1406 x;#[instrument(level = "debug", skip_all, ret)]
1408 fn lower_type_relative_const_path(
1409 &self,
1410 self_ty: Ty<'tcx>,
1411 hir_self_ty: &'tcx hir::Ty<'tcx>,
1412 segment: &'tcx hir::PathSegment<'tcx>,
1413 qpath_hir_id: HirId,
1414 span: Span,
1415 ) -> Result<Const<'tcx>, ErrorGuaranteed> {
1416 let tcx = self.tcx();
1417 match self.lower_type_relative_path(
1418 self_ty,
1419 hir_self_ty,
1420 segment,
1421 qpath_hir_id,
1422 span,
1423 LowerTypeRelativePathMode::Const,
1424 )? {
1425 TypeRelativePath::AssocItem(def_id, args) => {
1426 if !find_attr!(self.tcx().get_all_attrs(def_id), AttributeKind::TypeConst(_)) {
1427 let mut err = self.dcx().struct_span_err(
1428 span,
1429 "use of trait associated const without `#[type_const]`",
1430 );
1431 err.note("the declaration in the trait must be marked with `#[type_const]`");
1432 return Err(err.emit());
1433 }
1434 let ct = Const::new_unevaluated(tcx, ty::UnevaluatedConst::new(def_id, args));
1435 let ct = self.check_param_uses_if_mcg(ct, span, false);
1436 Ok(ct)
1437 }
1438 TypeRelativePath::Ctor { ctor_def_id, args } => match tcx.def_kind(ctor_def_id) {
1439 DefKind::Ctor(_, CtorKind::Fn) => {
1440 Ok(ty::Const::zero_sized(tcx, Ty::new_fn_def(tcx, ctor_def_id, args)))
1441 }
1442 DefKind::Ctor(ctor_of, CtorKind::Const) => {
1443 Ok(self.construct_const_ctor_value(ctor_def_id, ctor_of, args))
1444 }
1445 _ => unreachable!(),
1446 },
1447 TypeRelativePath::Variant { .. } => {
1450 span_bug!(span, "unexpected variant res for type associated const path")
1451 }
1452 }
1453 }
1454
1455 x;#[instrument(level = "debug", skip_all, ret)]
1457 fn lower_type_relative_path(
1458 &self,
1459 self_ty: Ty<'tcx>,
1460 hir_self_ty: &'tcx hir::Ty<'tcx>,
1461 segment: &'tcx hir::PathSegment<'tcx>,
1462 qpath_hir_id: HirId,
1463 span: Span,
1464 mode: LowerTypeRelativePathMode,
1465 ) -> Result<TypeRelativePath<'tcx>, ErrorGuaranteed> {
1466 debug!(%self_ty, ?segment.ident);
1467 let tcx = self.tcx();
1468
1469 let mut variant_def_id = None;
1471 if let Some(adt_def) = self.probe_adt(span, self_ty) {
1472 if adt_def.is_enum() {
1473 let variant_def = adt_def
1474 .variants()
1475 .iter()
1476 .find(|vd| tcx.hygienic_eq(segment.ident, vd.ident(tcx), adt_def.did()));
1477 if let Some(variant_def) = variant_def {
1478 if matches!(mode, LowerTypeRelativePathMode::Const)
1481 && let Some((_, ctor_def_id)) = variant_def.ctor
1482 {
1483 tcx.check_stability(variant_def.def_id, Some(qpath_hir_id), span, None);
1484 let _ = self.prohibit_generic_args(
1485 slice::from_ref(segment).iter(),
1486 GenericsArgsErrExtend::EnumVariant {
1487 qself: hir_self_ty,
1488 assoc_segment: segment,
1489 adt_def,
1490 },
1491 );
1492 let ty::Adt(_, enum_args) = self_ty.kind() else { unreachable!() };
1493 return Ok(TypeRelativePath::Ctor { ctor_def_id, args: enum_args });
1494 }
1495 if let PermitVariants::Yes = mode.permit_variants() {
1496 tcx.check_stability(variant_def.def_id, Some(qpath_hir_id), span, None);
1497 let _ = self.prohibit_generic_args(
1498 slice::from_ref(segment).iter(),
1499 GenericsArgsErrExtend::EnumVariant {
1500 qself: hir_self_ty,
1501 assoc_segment: segment,
1502 adt_def,
1503 },
1504 );
1505 return Ok(TypeRelativePath::Variant {
1506 adt: self_ty,
1507 variant_did: variant_def.def_id,
1508 });
1509 } else {
1510 variant_def_id = Some(variant_def.def_id);
1511 }
1512 }
1513 }
1514
1515 if let Some((did, args)) = self.probe_inherent_assoc_item(
1517 segment,
1518 adt_def.did(),
1519 self_ty,
1520 qpath_hir_id,
1521 span,
1522 mode.assoc_tag(),
1523 )? {
1524 return Ok(TypeRelativePath::AssocItem(did, args));
1525 }
1526 }
1527
1528 let (item_def_id, bound) = self.resolve_type_relative_path(
1529 self_ty,
1530 hir_self_ty,
1531 mode.assoc_tag(),
1532 segment,
1533 qpath_hir_id,
1534 span,
1535 variant_def_id,
1536 )?;
1537
1538 let (item_def_id, args) = self.lower_assoc_item_path(span, item_def_id, segment, bound)?;
1539
1540 if let Some(variant_def_id) = variant_def_id {
1541 tcx.node_span_lint(AMBIGUOUS_ASSOCIATED_ITEMS, qpath_hir_id, span, |lint| {
1542 lint.primary_message("ambiguous associated item");
1543 let mut could_refer_to = |kind: DefKind, def_id, also| {
1544 let note_msg = format!(
1545 "`{}` could{} refer to the {} defined here",
1546 segment.ident,
1547 also,
1548 tcx.def_kind_descr(kind, def_id)
1549 );
1550 lint.span_note(tcx.def_span(def_id), note_msg);
1551 };
1552
1553 could_refer_to(DefKind::Variant, variant_def_id, "");
1554 could_refer_to(mode.def_kind(), item_def_id, " also");
1555
1556 lint.span_suggestion(
1557 span,
1558 "use fully-qualified syntax",
1559 format!(
1560 "<{} as {}>::{}",
1561 self_ty,
1562 tcx.item_name(bound.def_id()),
1563 segment.ident
1564 ),
1565 Applicability::MachineApplicable,
1566 );
1567 });
1568 }
1569
1570 Ok(TypeRelativePath::AssocItem(item_def_id, args))
1571 }
1572
1573 fn resolve_type_relative_path(
1575 &self,
1576 self_ty: Ty<'tcx>,
1577 hir_self_ty: &'tcx hir::Ty<'tcx>,
1578 assoc_tag: ty::AssocTag,
1579 segment: &'tcx hir::PathSegment<'tcx>,
1580 qpath_hir_id: HirId,
1581 span: Span,
1582 variant_def_id: Option<DefId>,
1583 ) -> Result<(DefId, ty::PolyTraitRef<'tcx>), ErrorGuaranteed> {
1584 let tcx = self.tcx();
1585
1586 let self_ty_res = match hir_self_ty.kind {
1587 hir::TyKind::Path(hir::QPath::Resolved(_, path)) => path.res,
1588 _ => Res::Err,
1589 };
1590
1591 let bound = match (self_ty.kind(), self_ty_res) {
1593 (_, Res::SelfTyAlias { alias_to: impl_def_id, is_trait_impl: true, .. }) => {
1594 let trait_ref = tcx.impl_trait_ref(impl_def_id);
1597
1598 self.probe_single_bound_for_assoc_item(
1599 || {
1600 let trait_ref = ty::Binder::dummy(trait_ref.instantiate_identity());
1601 traits::supertraits(tcx, trait_ref)
1602 },
1603 AssocItemQSelf::SelfTyAlias,
1604 assoc_tag,
1605 segment.ident,
1606 span,
1607 None,
1608 )?
1609 }
1610 (
1611 &ty::Param(_),
1612 Res::SelfTyParam { trait_: param_did } | Res::Def(DefKind::TyParam, param_did),
1613 ) => self.probe_single_ty_param_bound_for_assoc_item(
1614 param_did.expect_local(),
1615 hir_self_ty.span,
1616 assoc_tag,
1617 segment.ident,
1618 span,
1619 )?,
1620 _ => {
1621 return Err(self.report_unresolved_type_relative_path(
1622 self_ty,
1623 hir_self_ty,
1624 assoc_tag,
1625 segment.ident,
1626 qpath_hir_id,
1627 span,
1628 variant_def_id,
1629 ));
1630 }
1631 };
1632
1633 let assoc_item = self
1634 .probe_assoc_item(segment.ident, assoc_tag, qpath_hir_id, span, bound.def_id())
1635 .expect("failed to find associated item");
1636
1637 Ok((assoc_item.def_id, bound))
1638 }
1639
1640 fn probe_inherent_assoc_item(
1642 &self,
1643 segment: &hir::PathSegment<'tcx>,
1644 adt_did: DefId,
1645 self_ty: Ty<'tcx>,
1646 block: HirId,
1647 span: Span,
1648 assoc_tag: ty::AssocTag,
1649 ) -> Result<Option<(DefId, GenericArgsRef<'tcx>)>, ErrorGuaranteed> {
1650 let tcx = self.tcx();
1651
1652 if !tcx.features().inherent_associated_types() {
1653 match assoc_tag {
1654 ty::AssocTag::Type => return Ok(None),
1659 ty::AssocTag::Const => {
1660 return Err(feature_err(
1664 &tcx.sess,
1665 sym::inherent_associated_types,
1666 span,
1667 "inherent associated types are unstable",
1668 )
1669 .emit());
1670 }
1671 ty::AssocTag::Fn => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1672 }
1673 }
1674
1675 let name = segment.ident;
1676 let candidates: Vec<_> = tcx
1677 .inherent_impls(adt_did)
1678 .iter()
1679 .filter_map(|&impl_| {
1680 let (item, scope) =
1681 self.probe_assoc_item_unchecked(name, assoc_tag, block, impl_)?;
1682 Some(InherentAssocCandidate { impl_, assoc_item: item.def_id, scope })
1683 })
1684 .collect();
1685
1686 if candidates.is_empty() {
1691 return Ok(None);
1692 }
1693
1694 let (applicable_candidates, fulfillment_errors) =
1695 self.select_inherent_assoc_candidates(span, self_ty, candidates.clone());
1696
1697 let InherentAssocCandidate { impl_, assoc_item, scope: def_scope } =
1699 match &applicable_candidates[..] {
1700 &[] => Err(self.report_unresolved_inherent_assoc_item(
1701 name,
1702 self_ty,
1703 candidates,
1704 fulfillment_errors,
1705 span,
1706 assoc_tag,
1707 )),
1708
1709 &[applicable_candidate] => Ok(applicable_candidate),
1710
1711 &[_, ..] => Err(self.report_ambiguous_inherent_assoc_item(
1712 name,
1713 candidates.into_iter().map(|cand| cand.assoc_item).collect(),
1714 span,
1715 )),
1716 }?;
1717
1718 self.check_assoc_item(assoc_item, name, def_scope, block, span);
1721
1722 let parent_args = ty::GenericArgs::identity_for_item(tcx, impl_);
1726 let args = self.lower_generic_args_of_assoc_item(span, assoc_item, segment, parent_args);
1727 let args = tcx.mk_args_from_iter(
1728 std::iter::once(ty::GenericArg::from(self_ty))
1729 .chain(args.into_iter().skip(parent_args.len())),
1730 );
1731
1732 Ok(Some((assoc_item, args)))
1733 }
1734
1735 fn probe_assoc_item(
1739 &self,
1740 ident: Ident,
1741 assoc_tag: ty::AssocTag,
1742 block: HirId,
1743 span: Span,
1744 scope: DefId,
1745 ) -> Option<ty::AssocItem> {
1746 let (item, scope) = self.probe_assoc_item_unchecked(ident, assoc_tag, block, scope)?;
1747 self.check_assoc_item(item.def_id, ident, scope, block, span);
1748 Some(item)
1749 }
1750
1751 fn probe_assoc_item_unchecked(
1756 &self,
1757 ident: Ident,
1758 assoc_tag: ty::AssocTag,
1759 block: HirId,
1760 scope: DefId,
1761 ) -> Option<(ty::AssocItem, DefId)> {
1762 let tcx = self.tcx();
1763
1764 let (ident, def_scope) = tcx.adjust_ident_and_get_scope(ident, scope, block);
1765 let item = tcx
1769 .associated_items(scope)
1770 .filter_by_name_unhygienic(ident.name)
1771 .find(|i| i.tag() == assoc_tag && i.ident(tcx).normalize_to_macros_2_0() == ident)?;
1772
1773 Some((*item, def_scope))
1774 }
1775
1776 fn check_assoc_item(
1778 &self,
1779 item_def_id: DefId,
1780 ident: Ident,
1781 scope: DefId,
1782 block: HirId,
1783 span: Span,
1784 ) {
1785 let tcx = self.tcx();
1786
1787 if !tcx.visibility(item_def_id).is_accessible_from(scope, tcx) {
1788 self.dcx().emit_err(crate::errors::AssocItemIsPrivate {
1789 span,
1790 kind: tcx.def_descr(item_def_id),
1791 name: ident,
1792 defined_here_label: tcx.def_span(item_def_id),
1793 });
1794 }
1795
1796 tcx.check_stability(item_def_id, Some(block), span, None);
1797 }
1798
1799 fn probe_traits_that_match_assoc_ty(
1800 &self,
1801 qself_ty: Ty<'tcx>,
1802 assoc_ident: Ident,
1803 ) -> Vec<String> {
1804 let tcx = self.tcx();
1805
1806 let infcx_;
1809 let infcx = if let Some(infcx) = self.infcx() {
1810 infcx
1811 } else {
1812 if !!qself_ty.has_infer() {
::core::panicking::panic("assertion failed: !qself_ty.has_infer()")
};assert!(!qself_ty.has_infer());
1813 infcx_ = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
1814 &infcx_
1815 };
1816
1817 tcx.all_traits_including_private()
1818 .filter(|trait_def_id| {
1819 tcx.associated_items(*trait_def_id)
1821 .in_definition_order()
1822 .any(|i| {
1823 i.is_type()
1824 && !i.is_impl_trait_in_trait()
1825 && i.ident(tcx).normalize_to_macros_2_0() == assoc_ident
1826 })
1827 && tcx.visibility(*trait_def_id)
1829 .is_accessible_from(self.item_def_id(), tcx)
1830 && tcx.all_impls(*trait_def_id)
1831 .any(|impl_def_id| {
1832 let header = tcx.impl_trait_header(impl_def_id);
1833 let trait_ref = header.trait_ref.instantiate(
1834 tcx,
1835 infcx.fresh_args_for_item(DUMMY_SP, impl_def_id),
1836 );
1837
1838 let value = fold_regions(tcx, qself_ty, |_, _| tcx.lifetimes.re_erased);
1839 if value.has_escaping_bound_vars() {
1841 return false;
1842 }
1843 infcx
1844 .can_eq(
1845 ty::ParamEnv::empty(),
1846 trait_ref.self_ty(),
1847 value,
1848 ) && header.polarity != ty::ImplPolarity::Negative
1849 })
1850 })
1851 .map(|trait_def_id| tcx.def_path_str(trait_def_id))
1852 .collect()
1853 }
1854
1855 #[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(1856u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&[],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{ meta.fields().value_set(&[]) })
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Ty<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{
match self.lower_resolved_assoc_item_path(span, opt_self_ty,
item_def_id, trait_segment, item_segment,
ty::AssocTag::Type) {
Ok((item_def_id, item_args)) => {
Ty::new_projection_from_args(self.tcx(), item_def_id,
item_args)
}
Err(guar) => Ty::new_error(self.tcx(), guar),
}
}
}
}#[instrument(level = "debug", skip_all)]
1857 fn lower_resolved_assoc_ty_path(
1858 &self,
1859 span: Span,
1860 opt_self_ty: Option<Ty<'tcx>>,
1861 item_def_id: DefId,
1862 trait_segment: Option<&hir::PathSegment<'tcx>>,
1863 item_segment: &hir::PathSegment<'tcx>,
1864 ) -> Ty<'tcx> {
1865 match self.lower_resolved_assoc_item_path(
1866 span,
1867 opt_self_ty,
1868 item_def_id,
1869 trait_segment,
1870 item_segment,
1871 ty::AssocTag::Type,
1872 ) {
1873 Ok((item_def_id, item_args)) => {
1874 Ty::new_projection_from_args(self.tcx(), item_def_id, item_args)
1875 }
1876 Err(guar) => Ty::new_error(self.tcx(), guar),
1877 }
1878 }
1879
1880 #[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(1881u32),
::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: Const<'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::Const) {
Ok((item_def_id, item_args)) => {
if !{
{
'done:
{
for i in self.tcx().get_all_attrs(item_def_id) {
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(AttributeKind::TypeConst(_)) =>
{
break 'done Some(());
}
_ => {}
}
}
None
}
}.is_some()
} {
let mut err =
self.dcx().struct_span_err(span,
"use of `const` in the type system without `#[type_const]`");
err.note("the declaration must be marked with `#[type_const]`");
return Const::new_error(self.tcx(), err.emit());
}
let uv = ty::UnevaluatedConst::new(item_def_id, item_args);
Const::new_unevaluated(self.tcx(), uv)
}
Err(guar) => Const::new_error(self.tcx(), guar),
}
}
}
}#[instrument(level = "debug", skip_all)]
1882 fn lower_resolved_assoc_const_path(
1883 &self,
1884 span: Span,
1885 opt_self_ty: Option<Ty<'tcx>>,
1886 item_def_id: DefId,
1887 trait_segment: Option<&hir::PathSegment<'tcx>>,
1888 item_segment: &hir::PathSegment<'tcx>,
1889 ) -> Const<'tcx> {
1890 match self.lower_resolved_assoc_item_path(
1891 span,
1892 opt_self_ty,
1893 item_def_id,
1894 trait_segment,
1895 item_segment,
1896 ty::AssocTag::Const,
1897 ) {
1898 Ok((item_def_id, item_args)) => {
1899 if !find_attr!(self.tcx().get_all_attrs(item_def_id), AttributeKind::TypeConst(_)) {
1900 let mut err = self.dcx().struct_span_err(
1901 span,
1902 "use of `const` in the type system without `#[type_const]`",
1903 );
1904 err.note("the declaration must be marked with `#[type_const]`");
1905 return Const::new_error(self.tcx(), err.emit());
1906 }
1907
1908 let uv = ty::UnevaluatedConst::new(item_def_id, item_args);
1909 Const::new_unevaluated(self.tcx(), uv)
1910 }
1911 Err(guar) => Const::new_error(self.tcx(), guar),
1912 }
1913 }
1914
1915 #[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(1916u32),
::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:1929",
"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(1929u32),
::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:1939",
"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(1939u32),
::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:1943",
"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(1943u32),
::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)]
1917 fn lower_resolved_assoc_item_path(
1918 &self,
1919 span: Span,
1920 opt_self_ty: Option<Ty<'tcx>>,
1921 item_def_id: DefId,
1922 trait_segment: Option<&hir::PathSegment<'tcx>>,
1923 item_segment: &hir::PathSegment<'tcx>,
1924 assoc_tag: ty::AssocTag,
1925 ) -> Result<(DefId, GenericArgsRef<'tcx>), ErrorGuaranteed> {
1926 let tcx = self.tcx();
1927
1928 let trait_def_id = tcx.parent(item_def_id);
1929 debug!(?trait_def_id);
1930
1931 let Some(self_ty) = opt_self_ty else {
1932 return Err(self.report_missing_self_ty_for_resolved_path(
1933 trait_def_id,
1934 span,
1935 item_segment,
1936 assoc_tag,
1937 ));
1938 };
1939 debug!(?self_ty);
1940
1941 let trait_ref =
1942 self.lower_mono_trait_ref(span, trait_def_id, self_ty, trait_segment.unwrap(), false);
1943 debug!(?trait_ref);
1944
1945 let item_args =
1946 self.lower_generic_args_of_assoc_item(span, item_def_id, item_segment, trait_ref.args);
1947
1948 Ok((item_def_id, item_args))
1949 }
1950
1951 pub fn prohibit_generic_args<'a>(
1952 &self,
1953 segments: impl Iterator<Item = &'a hir::PathSegment<'a>> + Clone,
1954 err_extend: GenericsArgsErrExtend<'a>,
1955 ) -> Result<(), ErrorGuaranteed> {
1956 let args_visitors = segments.clone().flat_map(|segment| segment.args().args);
1957 let mut result = Ok(());
1958 if let Some(_) = args_visitors.clone().next() {
1959 result = Err(self.report_prohibited_generic_args(
1960 segments.clone(),
1961 args_visitors,
1962 err_extend,
1963 ));
1964 }
1965
1966 for segment in segments {
1967 if let Some(c) = segment.args().constraints.first() {
1969 return Err(prohibit_assoc_item_constraint(self, c, None));
1970 }
1971 }
1972
1973 result
1974 }
1975
1976 pub fn probe_generic_path_segments(
1994 &self,
1995 segments: &[hir::PathSegment<'_>],
1996 self_ty: Option<Ty<'tcx>>,
1997 kind: DefKind,
1998 def_id: DefId,
1999 span: Span,
2000 ) -> Vec<GenericPathSegment> {
2001 let tcx = self.tcx();
2047
2048 if !!segments.is_empty() {
::core::panicking::panic("assertion failed: !segments.is_empty()")
};assert!(!segments.is_empty());
2049 let last = segments.len() - 1;
2050
2051 let mut generic_segments = ::alloc::vec::Vec::new()vec![];
2052
2053 match kind {
2054 DefKind::Ctor(CtorOf::Struct, ..) => {
2056 let generics = tcx.generics_of(def_id);
2059 let generics_def_id = generics.parent.unwrap_or(def_id);
2062 generic_segments.push(GenericPathSegment(generics_def_id, last));
2063 }
2064
2065 DefKind::Ctor(CtorOf::Variant, ..) | DefKind::Variant => {
2067 let (generics_def_id, index) = if let Some(self_ty) = self_ty {
2068 let adt_def = self.probe_adt(span, self_ty).unwrap();
2069 if true {
if !adt_def.is_enum() {
::core::panicking::panic("assertion failed: adt_def.is_enum()")
};
};debug_assert!(adt_def.is_enum());
2070 (adt_def.did(), last)
2071 } else if last >= 1 && segments[last - 1].args.is_some() {
2072 let mut def_id = def_id;
2075
2076 if let DefKind::Ctor(..) = kind {
2078 def_id = tcx.parent(def_id);
2079 }
2080
2081 let enum_def_id = tcx.parent(def_id);
2083 (enum_def_id, last - 1)
2084 } else {
2085 let generics = tcx.generics_of(def_id);
2091 (generics.parent.unwrap_or(def_id), last)
2094 };
2095 generic_segments.push(GenericPathSegment(generics_def_id, index));
2096 }
2097
2098 DefKind::Fn | DefKind::Const | DefKind::ConstParam | DefKind::Static { .. } => {
2100 generic_segments.push(GenericPathSegment(def_id, last));
2101 }
2102
2103 DefKind::AssocFn | DefKind::AssocConst => {
2105 if segments.len() >= 2 {
2106 let generics = tcx.generics_of(def_id);
2107 generic_segments.push(GenericPathSegment(generics.parent.unwrap(), last - 1));
2108 }
2109 generic_segments.push(GenericPathSegment(def_id, last));
2110 }
2111
2112 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),
2113 }
2114
2115 {
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:2115",
"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(2115u32),
::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);
2116
2117 generic_segments
2118 }
2119
2120 #[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(2121u32),
::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:2129",
"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(2129u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&["path.res",
"opt_self_ty", "path.segments"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&path.res)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&opt_self_ty)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&path.segments)
as &dyn Value))])
});
} else { ; }
};
let tcx = self.tcx();
let span = path.span;
match path.res {
Res::Def(DefKind::OpaqueTy, did) => {
match tcx.opaque_ty_origin(did) {
hir::OpaqueTyOrigin::TyAlias { .. } => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val,
"hir::OpaqueTyOrigin::TyAlias { .. }",
::core::option::Option::None);
}
};
let [leading_segments @ .., segment] =
path.segments else {
::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))
};
let _ =
self.prohibit_generic_args(leading_segments.iter(),
GenericsArgsErrExtend::OpaqueTy);
let args =
self.lower_generic_args_of_path_segment(span, did, segment);
Ty::new_opaque(tcx, did, args)
}
Res::Def(DefKind::Enum | DefKind::TyAlias | DefKind::Struct |
DefKind::Union | DefKind::ForeignTy, did) => {
match (&opt_self_ty, &None) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
};
let [leading_segments @ .., segment] =
path.segments else {
::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))
};
let _ =
self.prohibit_generic_args(leading_segments.iter(),
GenericsArgsErrExtend::None);
self.lower_path_segment(span, did, segment)
}
Res::Def(kind @ DefKind::Variant, def_id) if
let PermitVariants::Yes = permit_variants => {
match (&opt_self_ty, &None) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
};
let generic_segments =
self.probe_generic_path_segments(path.segments, None, kind,
def_id, span);
let indices: FxHashSet<_> =
generic_segments.iter().map(|GenericPathSegment(_, index)|
index).collect();
let _ =
self.prohibit_generic_args(path.segments.iter().enumerate().filter_map(|(index,
seg)|
{
if !indices.contains(&index) { Some(seg) } else { None }
}), GenericsArgsErrExtend::DefVariant(&path.segments));
let &GenericPathSegment(def_id, index) =
generic_segments.last().unwrap();
self.lower_path_segment(span, def_id, &path.segments[index])
}
Res::Def(DefKind::TyParam, def_id) => {
match (&opt_self_ty, &None) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
};
let _ =
self.prohibit_generic_args(path.segments.iter(),
GenericsArgsErrExtend::Param(def_id));
self.lower_ty_param(hir_id)
}
Res::SelfTyParam { .. } => {
match (&opt_self_ty, &None) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
};
let _ =
self.prohibit_generic_args(path.segments.iter(),
if let [hir::PathSegment { args: Some(args), ident, .. }] =
&path.segments {
GenericsArgsErrExtend::SelfTyParam(ident.span.shrink_to_hi().to(args.span_ext))
} else { GenericsArgsErrExtend::None });
self.check_param_uses_if_mcg(tcx.types.self_param, span,
false)
}
Res::SelfTyAlias { alias_to: def_id, .. } => {
match (&opt_self_ty, &None) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
};
let ty =
tcx.at(span).type_of(def_id).instantiate_identity();
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)]
2122 pub fn lower_resolved_ty_path(
2123 &self,
2124 opt_self_ty: Option<Ty<'tcx>>,
2125 path: &hir::Path<'tcx>,
2126 hir_id: HirId,
2127 permit_variants: PermitVariants,
2128 ) -> Ty<'tcx> {
2129 debug!(?path.res, ?opt_self_ty, ?path.segments);
2130 let tcx = self.tcx();
2131
2132 let span = path.span;
2133 match path.res {
2134 Res::Def(DefKind::OpaqueTy, did) => {
2135 assert_matches!(tcx.opaque_ty_origin(did), hir::OpaqueTyOrigin::TyAlias { .. });
2137 let [leading_segments @ .., segment] = path.segments else { bug!() };
2138 let _ = self.prohibit_generic_args(
2139 leading_segments.iter(),
2140 GenericsArgsErrExtend::OpaqueTy,
2141 );
2142 let args = self.lower_generic_args_of_path_segment(span, did, segment);
2143 Ty::new_opaque(tcx, did, args)
2144 }
2145 Res::Def(
2146 DefKind::Enum
2147 | DefKind::TyAlias
2148 | DefKind::Struct
2149 | DefKind::Union
2150 | DefKind::ForeignTy,
2151 did,
2152 ) => {
2153 assert_eq!(opt_self_ty, None);
2154 let [leading_segments @ .., segment] = path.segments else { bug!() };
2155 let _ = self
2156 .prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
2157 self.lower_path_segment(span, did, segment)
2158 }
2159 Res::Def(kind @ DefKind::Variant, def_id)
2160 if let PermitVariants::Yes = permit_variants =>
2161 {
2162 assert_eq!(opt_self_ty, None);
2165
2166 let generic_segments =
2167 self.probe_generic_path_segments(path.segments, None, kind, def_id, span);
2168 let indices: FxHashSet<_> =
2169 generic_segments.iter().map(|GenericPathSegment(_, index)| index).collect();
2170 let _ = self.prohibit_generic_args(
2171 path.segments.iter().enumerate().filter_map(|(index, seg)| {
2172 if !indices.contains(&index) { Some(seg) } else { None }
2173 }),
2174 GenericsArgsErrExtend::DefVariant(&path.segments),
2175 );
2176
2177 let &GenericPathSegment(def_id, index) = generic_segments.last().unwrap();
2178 self.lower_path_segment(span, def_id, &path.segments[index])
2179 }
2180 Res::Def(DefKind::TyParam, def_id) => {
2181 assert_eq!(opt_self_ty, None);
2182 let _ = self.prohibit_generic_args(
2183 path.segments.iter(),
2184 GenericsArgsErrExtend::Param(def_id),
2185 );
2186 self.lower_ty_param(hir_id)
2187 }
2188 Res::SelfTyParam { .. } => {
2189 assert_eq!(opt_self_ty, None);
2191 let _ = self.prohibit_generic_args(
2192 path.segments.iter(),
2193 if let [hir::PathSegment { args: Some(args), ident, .. }] = &path.segments {
2194 GenericsArgsErrExtend::SelfTyParam(
2195 ident.span.shrink_to_hi().to(args.span_ext),
2196 )
2197 } else {
2198 GenericsArgsErrExtend::None
2199 },
2200 );
2201 self.check_param_uses_if_mcg(tcx.types.self_param, span, false)
2202 }
2203 Res::SelfTyAlias { alias_to: def_id, .. } => {
2204 assert_eq!(opt_self_ty, None);
2206 let ty = tcx.at(span).type_of(def_id).instantiate_identity();
2208 let _ = self.prohibit_generic_args(
2209 path.segments.iter(),
2210 GenericsArgsErrExtend::SelfTyAlias { def_id, span },
2211 );
2212 self.check_param_uses_if_mcg(ty, span, true)
2213 }
2214 Res::Def(DefKind::AssocTy, def_id) => {
2215 let trait_segment = if let [modules @ .., trait_, _item] = path.segments {
2216 let _ = self.prohibit_generic_args(modules.iter(), GenericsArgsErrExtend::None);
2217 Some(trait_)
2218 } else {
2219 None
2220 };
2221 self.lower_resolved_assoc_ty_path(
2222 span,
2223 opt_self_ty,
2224 def_id,
2225 trait_segment,
2226 path.segments.last().unwrap(),
2227 )
2228 }
2229 Res::PrimTy(prim_ty) => {
2230 assert_eq!(opt_self_ty, None);
2231 let _ = self.prohibit_generic_args(
2232 path.segments.iter(),
2233 GenericsArgsErrExtend::PrimTy(prim_ty),
2234 );
2235 match prim_ty {
2236 hir::PrimTy::Bool => tcx.types.bool,
2237 hir::PrimTy::Char => tcx.types.char,
2238 hir::PrimTy::Int(it) => Ty::new_int(tcx, it),
2239 hir::PrimTy::Uint(uit) => Ty::new_uint(tcx, uit),
2240 hir::PrimTy::Float(ft) => Ty::new_float(tcx, ft),
2241 hir::PrimTy::Str => tcx.types.str_,
2242 }
2243 }
2244 Res::Err => {
2245 let e = self
2246 .tcx()
2247 .dcx()
2248 .span_delayed_bug(path.span, "path with `Res::Err` but no error emitted");
2249 Ty::new_error(tcx, e)
2250 }
2251 Res::Def(..) => {
2252 assert_eq!(
2253 path.segments.get(0).map(|seg| seg.ident.name),
2254 Some(kw::SelfUpper),
2255 "only expected incorrect resolution for `Self`"
2256 );
2257 Ty::new_error(
2258 self.tcx(),
2259 self.dcx().span_delayed_bug(span, "incorrect resolution for `Self`"),
2260 )
2261 }
2262 _ => span_bug!(span, "unexpected resolution: {:?}", path.res),
2263 }
2264 }
2265
2266 pub(crate) fn lower_ty_param(&self, hir_id: HirId) -> Ty<'tcx> {
2271 let tcx = self.tcx();
2272
2273 let ty = match tcx.named_bound_var(hir_id) {
2274 Some(rbv::ResolvedArg::LateBound(debruijn, index, def_id)) => {
2275 let br = ty::BoundTy {
2276 var: ty::BoundVar::from_u32(index),
2277 kind: ty::BoundTyKind::Param(def_id.to_def_id()),
2278 };
2279 Ty::new_bound(tcx, debruijn, br)
2280 }
2281 Some(rbv::ResolvedArg::EarlyBound(def_id)) => {
2282 let item_def_id = tcx.hir_ty_param_owner(def_id);
2283 let generics = tcx.generics_of(item_def_id);
2284 let index = generics.param_def_id_to_index[&def_id.to_def_id()];
2285 Ty::new_param(tcx, index, tcx.hir_ty_param_name(def_id))
2286 }
2287 Some(rbv::ResolvedArg::Error(guar)) => Ty::new_error(tcx, guar),
2288 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:?}"),
2289 };
2290 self.check_param_uses_if_mcg(ty, tcx.hir_span(hir_id), false)
2291 }
2292
2293 pub(crate) fn lower_const_param(&self, param_def_id: DefId, path_hir_id: HirId) -> Const<'tcx> {
2298 let tcx = self.tcx();
2299
2300 let ct = match tcx.named_bound_var(path_hir_id) {
2301 Some(rbv::ResolvedArg::EarlyBound(_)) => {
2302 let item_def_id = tcx.parent(param_def_id);
2305 let generics = tcx.generics_of(item_def_id);
2306 let index = generics.param_def_id_to_index[¶m_def_id];
2307 let name = tcx.item_name(param_def_id);
2308 ty::Const::new_param(tcx, ty::ParamConst::new(index, name))
2309 }
2310 Some(rbv::ResolvedArg::LateBound(debruijn, index, _)) => ty::Const::new_bound(
2311 tcx,
2312 debruijn,
2313 ty::BoundConst::new(ty::BoundVar::from_u32(index)),
2314 ),
2315 Some(rbv::ResolvedArg::Error(guar)) => ty::Const::new_error(tcx, guar),
2316 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),
2317 };
2318 self.check_param_uses_if_mcg(ct, tcx.hir_span(path_hir_id), false)
2319 }
2320
2321 #[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(2322u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&["const_arg", "ty"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&const_arg)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Const<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{
let tcx = self.tcx();
if let hir::ConstArgKind::Anon(anon) = &const_arg.kind {
if tcx.features().generic_const_parameter_types() &&
(ty.has_free_regions() || ty.has_erased_regions()) {
let e =
self.dcx().span_err(const_arg.span,
"anonymous constants with lifetimes in their type are not yet supported");
tcx.feed_anon_const_type(anon.def_id,
ty::EarlyBinder::bind(Ty::new_error(tcx, e)));
return ty::Const::new_error(tcx, e);
}
if ty.has_non_region_infer() {
let e =
self.dcx().span_err(const_arg.span,
"anonymous constants with inferred types are not yet supported");
tcx.feed_anon_const_type(anon.def_id,
ty::EarlyBinder::bind(Ty::new_error(tcx, e)));
return ty::Const::new_error(tcx, e);
}
if ty.has_non_region_param() {
let e =
self.dcx().span_err(const_arg.span,
"anonymous constants referencing generics are not yet supported");
tcx.feed_anon_const_type(anon.def_id,
ty::EarlyBinder::bind(Ty::new_error(tcx, e)));
return ty::Const::new_error(tcx, e);
}
tcx.feed_anon_const_type(anon.def_id,
ty::EarlyBinder::bind(ty));
}
let hir_id = const_arg.hir_id;
match const_arg.kind {
hir::ConstArgKind::Tup(exprs) =>
self.lower_const_arg_tup(exprs, ty, const_arg.span),
hir::ConstArgKind::Path(hir::QPath::Resolved(maybe_qself,
path)) => {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs:2374",
"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(2374u32),
::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:2379",
"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(2379u32),
::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(kind) => {
self.lower_const_arg_literal(&kind, ty, const_arg.span)
}
}
}
}
}#[instrument(skip(self), level = "debug")]
2323 pub fn lower_const_arg(&self, const_arg: &hir::ConstArg<'tcx>, ty: Ty<'tcx>) -> Const<'tcx> {
2324 let tcx = self.tcx();
2325
2326 if let hir::ConstArgKind::Anon(anon) = &const_arg.kind {
2327 if tcx.features().generic_const_parameter_types()
2336 && (ty.has_free_regions() || ty.has_erased_regions())
2337 {
2338 let e = self.dcx().span_err(
2339 const_arg.span,
2340 "anonymous constants with lifetimes in their type are not yet supported",
2341 );
2342 tcx.feed_anon_const_type(anon.def_id, ty::EarlyBinder::bind(Ty::new_error(tcx, e)));
2343 return ty::Const::new_error(tcx, e);
2344 }
2345 if ty.has_non_region_infer() {
2349 let e = self.dcx().span_err(
2350 const_arg.span,
2351 "anonymous constants with inferred types are not yet supported",
2352 );
2353 tcx.feed_anon_const_type(anon.def_id, ty::EarlyBinder::bind(Ty::new_error(tcx, e)));
2354 return ty::Const::new_error(tcx, e);
2355 }
2356 if ty.has_non_region_param() {
2359 let e = self.dcx().span_err(
2360 const_arg.span,
2361 "anonymous constants referencing generics are not yet supported",
2362 );
2363 tcx.feed_anon_const_type(anon.def_id, ty::EarlyBinder::bind(Ty::new_error(tcx, e)));
2364 return ty::Const::new_error(tcx, e);
2365 }
2366
2367 tcx.feed_anon_const_type(anon.def_id, ty::EarlyBinder::bind(ty));
2368 }
2369
2370 let hir_id = const_arg.hir_id;
2371 match const_arg.kind {
2372 hir::ConstArgKind::Tup(exprs) => self.lower_const_arg_tup(exprs, ty, const_arg.span),
2373 hir::ConstArgKind::Path(hir::QPath::Resolved(maybe_qself, path)) => {
2374 debug!(?maybe_qself, ?path);
2375 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
2376 self.lower_resolved_const_path(opt_self_ty, path, hir_id)
2377 }
2378 hir::ConstArgKind::Path(hir::QPath::TypeRelative(hir_self_ty, segment)) => {
2379 debug!(?hir_self_ty, ?segment);
2380 let self_ty = self.lower_ty(hir_self_ty);
2381 self.lower_type_relative_const_path(
2382 self_ty,
2383 hir_self_ty,
2384 segment,
2385 hir_id,
2386 const_arg.span,
2387 )
2388 .unwrap_or_else(|guar| Const::new_error(tcx, guar))
2389 }
2390 hir::ConstArgKind::Struct(qpath, inits) => {
2391 self.lower_const_arg_struct(hir_id, qpath, inits, const_arg.span)
2392 }
2393 hir::ConstArgKind::TupleCall(qpath, args) => {
2394 self.lower_const_arg_tuple_call(hir_id, qpath, args, const_arg.span)
2395 }
2396 hir::ConstArgKind::Array(array_expr) => self.lower_const_arg_array(array_expr, ty),
2397 hir::ConstArgKind::Anon(anon) => self.lower_const_arg_anon(anon),
2398 hir::ConstArgKind::Infer(()) => self.ct_infer(None, const_arg.span),
2399 hir::ConstArgKind::Error(e) => ty::Const::new_error(tcx, e),
2400 hir::ConstArgKind::Literal(kind) => {
2401 self.lower_const_arg_literal(&kind, ty, const_arg.span)
2402 }
2403 }
2404 }
2405
2406 fn lower_const_arg_array(
2407 &self,
2408 array_expr: &'tcx hir::ConstArgArrayExpr<'tcx>,
2409 ty: Ty<'tcx>,
2410 ) -> Const<'tcx> {
2411 let tcx = self.tcx();
2412
2413 let ty::Array(elem_ty, _) = ty.kind() else {
2414 let e = tcx
2415 .dcx()
2416 .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));
2417 return Const::new_error(tcx, e);
2418 };
2419
2420 let elems = array_expr
2421 .elems
2422 .iter()
2423 .map(|elem| self.lower_const_arg(elem, *elem_ty))
2424 .collect::<Vec<_>>();
2425
2426 let valtree = ty::ValTree::from_branches(tcx, elems);
2427
2428 ty::Const::new_value(tcx, valtree, ty)
2429 }
2430
2431 fn lower_const_arg_tuple_call(
2432 &self,
2433 hir_id: HirId,
2434 qpath: hir::QPath<'tcx>,
2435 args: &'tcx [&'tcx hir::ConstArg<'tcx>],
2436 span: Span,
2437 ) -> Const<'tcx> {
2438 let tcx = self.tcx();
2439
2440 let non_adt_or_variant_res = || {
2441 let e = tcx.dcx().span_err(span, "tuple constructor with invalid base path");
2442 ty::Const::new_error(tcx, e)
2443 };
2444
2445 let ctor_const = match qpath {
2446 hir::QPath::Resolved(maybe_qself, path) => {
2447 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
2448 self.lower_resolved_const_path(opt_self_ty, path, hir_id)
2449 }
2450 hir::QPath::TypeRelative(hir_self_ty, segment) => {
2451 let self_ty = self.lower_ty(hir_self_ty);
2452 match self.lower_type_relative_const_path(
2453 self_ty,
2454 hir_self_ty,
2455 segment,
2456 hir_id,
2457 span,
2458 ) {
2459 Ok(c) => c,
2460 Err(_) => return non_adt_or_variant_res(),
2461 }
2462 }
2463 };
2464
2465 let Some(value) = ctor_const.try_to_value() else {
2466 return non_adt_or_variant_res();
2467 };
2468
2469 let (adt_def, adt_args, variant_did) = match value.ty.kind() {
2470 ty::FnDef(def_id, fn_args)
2471 if let DefKind::Ctor(CtorOf::Variant, _) = tcx.def_kind(*def_id) =>
2472 {
2473 let parent_did = tcx.parent(*def_id);
2474 let enum_did = tcx.parent(parent_did);
2475 (tcx.adt_def(enum_did), fn_args, parent_did)
2476 }
2477 ty::FnDef(def_id, fn_args)
2478 if let DefKind::Ctor(CtorOf::Struct, _) = tcx.def_kind(*def_id) =>
2479 {
2480 let parent_did = tcx.parent(*def_id);
2481 (tcx.adt_def(parent_did), fn_args, parent_did)
2482 }
2483 _ => return non_adt_or_variant_res(),
2484 };
2485
2486 let variant_def = adt_def.variant_with_id(variant_did);
2487 let variant_idx = adt_def.variant_index_with_id(variant_did).as_u32();
2488
2489 if args.len() != variant_def.fields.len() {
2490 let e = tcx.dcx().span_err(
2491 span,
2492 ::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!(
2493 "tuple constructor has {} arguments but {} were provided",
2494 variant_def.fields.len(),
2495 args.len()
2496 ),
2497 );
2498 return ty::Const::new_error(tcx, e);
2499 }
2500
2501 let fields = variant_def
2502 .fields
2503 .iter()
2504 .zip(args)
2505 .map(|(field_def, arg)| {
2506 self.lower_const_arg(arg, tcx.type_of(field_def.did).instantiate(tcx, adt_args))
2507 })
2508 .collect::<Vec<_>>();
2509
2510 let opt_discr_const = if adt_def.is_enum() {
2511 let valtree = ty::ValTree::from_scalar_int(tcx, variant_idx.into());
2512 Some(ty::Const::new_value(tcx, valtree, tcx.types.u32))
2513 } else {
2514 None
2515 };
2516
2517 let valtree = ty::ValTree::from_branches(tcx, opt_discr_const.into_iter().chain(fields));
2518 let adt_ty = Ty::new_adt(tcx, adt_def, adt_args);
2519 ty::Const::new_value(tcx, valtree, adt_ty)
2520 }
2521
2522 fn lower_const_arg_tup(
2523 &self,
2524 exprs: &'tcx [&'tcx hir::ConstArg<'tcx>],
2525 ty: Ty<'tcx>,
2526 span: Span,
2527 ) -> Const<'tcx> {
2528 let tcx = self.tcx();
2529
2530 let ty::Tuple(tys) = ty.kind() else {
2531 let e = tcx.dcx().span_err(span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected `{0}`, found const tuple",
ty))
})format!("expected `{}`, found const tuple", ty));
2532 return Const::new_error(tcx, e);
2533 };
2534
2535 let exprs = exprs
2536 .iter()
2537 .zip(tys.iter())
2538 .map(|(expr, ty)| self.lower_const_arg(expr, ty))
2539 .collect::<Vec<_>>();
2540
2541 let valtree = ty::ValTree::from_branches(tcx, exprs);
2542 ty::Const::new_value(tcx, valtree, ty)
2543 }
2544
2545 fn lower_const_arg_struct(
2546 &self,
2547 hir_id: HirId,
2548 qpath: hir::QPath<'tcx>,
2549 inits: &'tcx [&'tcx hir::ConstArgExprField<'tcx>],
2550 span: Span,
2551 ) -> Const<'tcx> {
2552 let tcx = self.tcx();
2555
2556 let non_adt_or_variant_res = || {
2557 let e = tcx.dcx().span_err(span, "struct expression with invalid base path");
2558 ty::Const::new_error(tcx, e)
2559 };
2560
2561 let (ty, variant_did) = match qpath {
2562 hir::QPath::Resolved(maybe_qself, path) => {
2563 {
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:2563",
"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(2563u32),
::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);
2564 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
2565 let ty =
2566 self.lower_resolved_ty_path(opt_self_ty, path, hir_id, PermitVariants::Yes);
2567 let variant_did = match path.res {
2568 Res::Def(DefKind::Variant | DefKind::Struct, did) => did,
2569 _ => return non_adt_or_variant_res(),
2570 };
2571
2572 (ty, variant_did)
2573 }
2574 hir::QPath::TypeRelative(hir_self_ty, segment) => {
2575 {
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:2575",
"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(2575u32),
::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);
2576 let self_ty = self.lower_ty(hir_self_ty);
2577 let opt_res = self.lower_type_relative_ty_path(
2578 self_ty,
2579 hir_self_ty,
2580 segment,
2581 hir_id,
2582 span,
2583 PermitVariants::Yes,
2584 );
2585
2586 let (ty, _, res_def_id) = match opt_res {
2587 Ok(r @ (_, DefKind::Variant | DefKind::Struct, _)) => r,
2588 Ok(_) => return non_adt_or_variant_res(),
2589 Err(e) => return ty::Const::new_error(tcx, e),
2590 };
2591
2592 (ty, res_def_id)
2593 }
2594 };
2595
2596 let ty::Adt(adt_def, adt_args) = ty.kind() else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
2597
2598 let variant_def = adt_def.variant_with_id(variant_did);
2599 let variant_idx = adt_def.variant_index_with_id(variant_did).as_u32();
2600
2601 let fields = variant_def
2602 .fields
2603 .iter()
2604 .map(|field_def| {
2605 let mut init_expr =
2608 inits.iter().filter(|init_expr| init_expr.field.name == field_def.name);
2609
2610 match init_expr.next() {
2611 Some(expr) => {
2612 if let Some(expr) = init_expr.next() {
2613 let e = tcx.dcx().span_err(
2614 expr.span,
2615 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("struct expression with multiple initialisers for `{0}`",
field_def.name))
})format!(
2616 "struct expression with multiple initialisers for `{}`",
2617 field_def.name,
2618 ),
2619 );
2620 return ty::Const::new_error(tcx, e);
2621 }
2622
2623 self.lower_const_arg(
2624 expr.expr,
2625 tcx.type_of(field_def.did).instantiate(tcx, adt_args),
2626 )
2627 }
2628 None => {
2629 let e = tcx.dcx().span_err(
2630 span,
2631 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("struct expression with missing field initialiser for `{0}`",
field_def.name))
})format!(
2632 "struct expression with missing field initialiser for `{}`",
2633 field_def.name
2634 ),
2635 );
2636 ty::Const::new_error(tcx, e)
2637 }
2638 }
2639 })
2640 .collect::<Vec<_>>();
2641
2642 let opt_discr_const = if adt_def.is_enum() {
2643 let valtree = ty::ValTree::from_scalar_int(tcx, variant_idx.into());
2644 Some(ty::Const::new_value(tcx, valtree, tcx.types.u32))
2645 } else {
2646 None
2647 };
2648
2649 let valtree = ty::ValTree::from_branches(tcx, opt_discr_const.into_iter().chain(fields));
2650 ty::Const::new_value(tcx, valtree, ty)
2651 }
2652
2653 fn lower_resolved_const_path(
2655 &self,
2656 opt_self_ty: Option<Ty<'tcx>>,
2657 path: &hir::Path<'tcx>,
2658 hir_id: HirId,
2659 ) -> Const<'tcx> {
2660 let tcx = self.tcx();
2661 let span = path.span;
2662 let ct = match path.res {
2663 Res::Def(DefKind::ConstParam, def_id) => {
2664 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);
2665 let _ = self.prohibit_generic_args(
2666 path.segments.iter(),
2667 GenericsArgsErrExtend::Param(def_id),
2668 );
2669 self.lower_const_param(def_id, hir_id)
2670 }
2671 Res::Def(DefKind::Const, did) => {
2672 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);
2673 let [leading_segments @ .., segment] = path.segments else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
2674 let _ = self
2675 .prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
2676 let args = self.lower_generic_args_of_path_segment(span, did, segment);
2677 ty::Const::new_unevaluated(tcx, ty::UnevaluatedConst::new(did, args))
2678 }
2679 Res::Def(DefKind::Ctor(ctor_of, CtorKind::Const), did) => {
2680 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);
2681 let [leading_segments @ .., segment] = path.segments else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
2682 let _ = self
2683 .prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
2684
2685 let parent_did = tcx.parent(did);
2686 let generics_did = match ctor_of {
2687 CtorOf::Variant => tcx.parent(parent_did),
2688 CtorOf::Struct => parent_did,
2689 };
2690 let args = self.lower_generic_args_of_path_segment(span, generics_did, segment);
2691
2692 self.construct_const_ctor_value(did, ctor_of, args)
2693 }
2694 Res::Def(DefKind::Ctor(_, CtorKind::Fn), did) => {
2695 match (&opt_self_ty, &None) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::None);
}
}
};assert_eq!(opt_self_ty, None);
2696 let [leading_segments @ .., segment] = path.segments else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
2697 let _ = self
2698 .prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
2699 let parent_did = tcx.parent(did);
2700 let generics_did = if let DefKind::Ctor(CtorOf::Variant, _) = tcx.def_kind(did) {
2701 tcx.parent(parent_did)
2702 } else {
2703 parent_did
2704 };
2705 let args = self.lower_generic_args_of_path_segment(span, generics_did, segment);
2706 ty::Const::zero_sized(tcx, Ty::new_fn_def(tcx, did, args))
2707 }
2708 Res::Def(DefKind::AssocConst, did) => {
2709 let trait_segment = if let [modules @ .., trait_, _item] = path.segments {
2710 let _ = self.prohibit_generic_args(modules.iter(), GenericsArgsErrExtend::None);
2711 Some(trait_)
2712 } else {
2713 None
2714 };
2715 self.lower_resolved_assoc_const_path(
2716 span,
2717 opt_self_ty,
2718 did,
2719 trait_segment,
2720 path.segments.last().unwrap(),
2721 )
2722 }
2723 Res::Def(DefKind::Static { .. }, _) => {
2724 ::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")
2725 }
2726 Res::Def(DefKind::Fn | DefKind::AssocFn, did) => {
2728 self.dcx().span_delayed_bug(span, "function items cannot be used as const args");
2729 let args = self.lower_generic_args_of_path_segment(
2730 span,
2731 did,
2732 path.segments.last().unwrap(),
2733 );
2734 ty::Const::zero_sized(tcx, Ty::new_fn_def(tcx, did, args))
2735 }
2736
2737 res @ (Res::Def(
2740 DefKind::Mod
2741 | DefKind::Enum
2742 | DefKind::Variant
2743 | DefKind::Struct
2744 | DefKind::OpaqueTy
2745 | DefKind::TyAlias
2746 | DefKind::TraitAlias
2747 | DefKind::AssocTy
2748 | DefKind::Union
2749 | DefKind::Trait
2750 | DefKind::ForeignTy
2751 | DefKind::TyParam
2752 | DefKind::Macro(_)
2753 | DefKind::LifetimeParam
2754 | DefKind::Use
2755 | DefKind::ForeignMod
2756 | DefKind::AnonConst
2757 | DefKind::InlineConst
2758 | DefKind::Field
2759 | DefKind::Impl { .. }
2760 | DefKind::Closure
2761 | DefKind::ExternCrate
2762 | DefKind::GlobalAsm
2763 | DefKind::SyntheticCoroutineBody,
2764 _,
2765 )
2766 | Res::PrimTy(_)
2767 | Res::SelfTyParam { .. }
2768 | Res::SelfTyAlias { .. }
2769 | Res::SelfCtor(_)
2770 | Res::Local(_)
2771 | Res::ToolMod
2772 | Res::NonMacroAttr(_)
2773 | Res::Err) => Const::new_error_with_message(
2774 tcx,
2775 span,
2776 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("invalid Res {0:?} for const path",
res))
})format!("invalid Res {res:?} for const path"),
2777 ),
2778 };
2779 self.check_param_uses_if_mcg(ct, span, false)
2780 }
2781
2782 #[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(2783u32),
::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:2788",
"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(2788u32),
::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();
match self.try_lower_anon_const_lit(ty, expr) {
Some(v) => v,
None =>
ty::Const::new_unevaluated(tcx,
ty::UnevaluatedConst {
def: anon.def_id.to_def_id(),
args: ty::GenericArgs::identity_for_item(tcx,
anon.def_id.to_def_id()),
}),
}
}
}
}#[instrument(skip(self), level = "debug")]
2784 fn lower_const_arg_anon(&self, anon: &AnonConst) -> Const<'tcx> {
2785 let tcx = self.tcx();
2786
2787 let expr = &tcx.hir_body(anon.body).value;
2788 debug!(?expr);
2789
2790 let ty = tcx.type_of(anon.def_id).instantiate_identity();
2794
2795 match self.try_lower_anon_const_lit(ty, expr) {
2796 Some(v) => v,
2797 None => ty::Const::new_unevaluated(
2798 tcx,
2799 ty::UnevaluatedConst {
2800 def: anon.def_id.to_def_id(),
2801 args: ty::GenericArgs::identity_for_item(tcx, anon.def_id.to_def_id()),
2802 },
2803 ),
2804 }
2805 }
2806
2807 #[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(2807u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&["kind", "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(&::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 input = LitToConstInput { lit: *kind, ty, neg: false };
tcx.at(span).lit_to_const(input)
}
}
}#[instrument(skip(self), level = "debug")]
2808 fn lower_const_arg_literal(&self, kind: &LitKind, ty: Ty<'tcx>, span: Span) -> Const<'tcx> {
2809 let tcx = self.tcx();
2810 let input = LitToConstInput { lit: *kind, ty, neg: false };
2811 tcx.at(span).lit_to_const(input)
2812 }
2813
2814 #[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(2814u32),
::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, neg: false }),
hir::ExprKind::Unary(hir::UnOp::Neg, expr) =>
match expr.kind {
hir::ExprKind::Lit(lit) =>
Some(LitToConstInput { lit: lit.node, ty, neg: true }),
_ => None,
},
_ => None,
};
lit_input.filter(|l|
!l.ty.has_aliases()).map(|l|
tcx.at(expr.span).lit_to_const(l))
}
}
}#[instrument(skip(self), level = "debug")]
2815 fn try_lower_anon_const_lit(
2816 &self,
2817 ty: Ty<'tcx>,
2818 expr: &'tcx hir::Expr<'tcx>,
2819 ) -> Option<Const<'tcx>> {
2820 let tcx = self.tcx();
2821
2822 let expr = match &expr.kind {
2825 hir::ExprKind::Block(block, _) if block.stmts.is_empty() && block.expr.is_some() => {
2826 block.expr.as_ref().unwrap()
2827 }
2828 _ => expr,
2829 };
2830
2831 let lit_input = match expr.kind {
2832 hir::ExprKind::Lit(lit) => Some(LitToConstInput { lit: lit.node, ty, neg: false }),
2833 hir::ExprKind::Unary(hir::UnOp::Neg, expr) => match expr.kind {
2834 hir::ExprKind::Lit(lit) => Some(LitToConstInput { lit: lit.node, ty, neg: true }),
2835 _ => None,
2836 },
2837 _ => None,
2838 };
2839
2840 lit_input
2841 .filter(|l| !l.ty.has_aliases())
2844 .map(|l| tcx.at(expr.span).lit_to_const(l))
2845 }
2846
2847 fn lower_delegation_ty(&self, idx: hir::InferDelegationKind) -> Ty<'tcx> {
2848 let delegation_sig = self.tcx().inherit_sig_for_delegation_item(self.item_def_id());
2849 match idx {
2850 hir::InferDelegationKind::Input(idx) => delegation_sig[idx],
2851 hir::InferDelegationKind::Output => *delegation_sig.last().unwrap(),
2852 }
2853 }
2854
2855 x;#[instrument(level = "debug", skip(self), ret)]
2857 pub fn lower_ty(&self, hir_ty: &hir::Ty<'tcx>) -> Ty<'tcx> {
2858 let tcx = self.tcx();
2859
2860 let result_ty = match &hir_ty.kind {
2861 hir::TyKind::InferDelegation(_, idx) => self.lower_delegation_ty(*idx),
2862 hir::TyKind::Slice(ty) => Ty::new_slice(tcx, self.lower_ty(ty)),
2863 hir::TyKind::Ptr(mt) => Ty::new_ptr(tcx, self.lower_ty(mt.ty), mt.mutbl),
2864 hir::TyKind::Ref(region, mt) => {
2865 let r = self.lower_lifetime(region, RegionInferReason::Reference);
2866 debug!(?r);
2867 let t = self.lower_ty(mt.ty);
2868 Ty::new_ref(tcx, r, t, mt.mutbl)
2869 }
2870 hir::TyKind::Never => tcx.types.never,
2871 hir::TyKind::Tup(fields) => {
2872 Ty::new_tup_from_iter(tcx, fields.iter().map(|t| self.lower_ty(t)))
2873 }
2874 hir::TyKind::FnPtr(bf) => {
2875 check_c_variadic_abi(tcx, bf.decl, bf.abi, hir_ty.span);
2876
2877 Ty::new_fn_ptr(
2878 tcx,
2879 self.lower_fn_ty(hir_ty.hir_id, bf.safety, bf.abi, bf.decl, None, Some(hir_ty)),
2880 )
2881 }
2882 hir::TyKind::UnsafeBinder(binder) => Ty::new_unsafe_binder(
2883 tcx,
2884 ty::Binder::bind_with_vars(
2885 self.lower_ty(binder.inner_ty),
2886 tcx.late_bound_vars(hir_ty.hir_id),
2887 ),
2888 ),
2889 hir::TyKind::TraitObject(bounds, tagged_ptr) => {
2890 let lifetime = tagged_ptr.pointer();
2891 let syntax = tagged_ptr.tag();
2892 self.lower_trait_object_ty(hir_ty.span, hir_ty.hir_id, bounds, lifetime, syntax)
2893 }
2894 hir::TyKind::Path(hir::QPath::Resolved(_, path))
2898 if path.segments.last().and_then(|segment| segment.args).is_some_and(|args| {
2899 matches!(args.parenthesized, hir::GenericArgsParentheses::ReturnTypeNotation)
2900 }) =>
2901 {
2902 let guar = self.dcx().emit_err(BadReturnTypeNotation { span: hir_ty.span });
2903 Ty::new_error(tcx, guar)
2904 }
2905 hir::TyKind::Path(hir::QPath::Resolved(maybe_qself, path)) => {
2906 debug!(?maybe_qself, ?path);
2907 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
2908 self.lower_resolved_ty_path(opt_self_ty, path, hir_ty.hir_id, PermitVariants::No)
2909 }
2910 &hir::TyKind::OpaqueDef(opaque_ty) => {
2911 let in_trait = match opaque_ty.origin {
2915 hir::OpaqueTyOrigin::FnReturn {
2916 parent,
2917 in_trait_or_impl: Some(hir::RpitContext::Trait),
2918 ..
2919 }
2920 | hir::OpaqueTyOrigin::AsyncFn {
2921 parent,
2922 in_trait_or_impl: Some(hir::RpitContext::Trait),
2923 ..
2924 } => Some(parent),
2925 hir::OpaqueTyOrigin::FnReturn {
2926 in_trait_or_impl: None | Some(hir::RpitContext::TraitImpl),
2927 ..
2928 }
2929 | hir::OpaqueTyOrigin::AsyncFn {
2930 in_trait_or_impl: None | Some(hir::RpitContext::TraitImpl),
2931 ..
2932 }
2933 | hir::OpaqueTyOrigin::TyAlias { .. } => None,
2934 };
2935
2936 self.lower_opaque_ty(opaque_ty.def_id, in_trait)
2937 }
2938 hir::TyKind::TraitAscription(hir_bounds) => {
2939 let self_ty = self.ty_infer(None, hir_ty.span);
2942 let mut bounds = Vec::new();
2943 self.lower_bounds(
2944 self_ty,
2945 hir_bounds.iter(),
2946 &mut bounds,
2947 ty::List::empty(),
2948 PredicateFilter::All,
2949 OverlappingAsssocItemConstraints::Allowed,
2950 );
2951 self.add_implicit_sizedness_bounds(
2952 &mut bounds,
2953 self_ty,
2954 hir_bounds,
2955 ImpliedBoundsContext::AssociatedTypeOrImplTrait,
2956 hir_ty.span,
2957 );
2958 self.register_trait_ascription_bounds(bounds, hir_ty.hir_id, hir_ty.span);
2959 self_ty
2960 }
2961 hir::TyKind::Path(hir::QPath::TypeRelative(_, segment))
2965 if segment.args.is_some_and(|args| {
2966 matches!(args.parenthesized, hir::GenericArgsParentheses::ReturnTypeNotation)
2967 }) =>
2968 {
2969 let guar = self.dcx().emit_err(BadReturnTypeNotation { span: hir_ty.span });
2970 Ty::new_error(tcx, guar)
2971 }
2972 hir::TyKind::Path(hir::QPath::TypeRelative(hir_self_ty, segment)) => {
2973 debug!(?hir_self_ty, ?segment);
2974 let self_ty = self.lower_ty(hir_self_ty);
2975 self.lower_type_relative_ty_path(
2976 self_ty,
2977 hir_self_ty,
2978 segment,
2979 hir_ty.hir_id,
2980 hir_ty.span,
2981 PermitVariants::No,
2982 )
2983 .map(|(ty, _, _)| ty)
2984 .unwrap_or_else(|guar| Ty::new_error(tcx, guar))
2985 }
2986 hir::TyKind::Array(ty, length) => {
2987 let length = self.lower_const_arg(length, tcx.types.usize);
2988 Ty::new_array_with_const_len(tcx, self.lower_ty(ty), length)
2989 }
2990 hir::TyKind::Infer(()) => {
2991 self.ty_infer(None, hir_ty.span)
2996 }
2997 hir::TyKind::Pat(ty, pat) => {
2998 let ty_span = ty.span;
2999 let ty = self.lower_ty(ty);
3000 let pat_ty = match self.lower_pat_ty_pat(ty, ty_span, pat) {
3001 Ok(kind) => Ty::new_pat(tcx, ty, tcx.mk_pat(kind)),
3002 Err(guar) => Ty::new_error(tcx, guar),
3003 };
3004 self.record_ty(pat.hir_id, ty, pat.span);
3005 pat_ty
3006 }
3007 hir::TyKind::Err(guar) => Ty::new_error(tcx, *guar),
3008 };
3009
3010 self.record_ty(hir_ty.hir_id, result_ty, hir_ty.span);
3011 result_ty
3012 }
3013
3014 fn lower_pat_ty_pat(
3015 &self,
3016 ty: Ty<'tcx>,
3017 ty_span: Span,
3018 pat: &hir::TyPat<'tcx>,
3019 ) -> Result<ty::PatternKind<'tcx>, ErrorGuaranteed> {
3020 let tcx = self.tcx();
3021 match pat.kind {
3022 hir::TyPatKind::Range(start, end) => {
3023 match ty.kind() {
3024 ty::Int(_) | ty::Uint(_) | ty::Char => {
3027 let start = self.lower_const_arg(start, ty);
3028 let end = self.lower_const_arg(end, ty);
3029 Ok(ty::PatternKind::Range { start, end })
3030 }
3031 _ => Err(self
3032 .dcx()
3033 .span_delayed_bug(ty_span, "invalid base type for range pattern")),
3034 }
3035 }
3036 hir::TyPatKind::NotNull => Ok(ty::PatternKind::NotNull),
3037 hir::TyPatKind::Or(patterns) => {
3038 self.tcx()
3039 .mk_patterns_from_iter(patterns.iter().map(|pat| {
3040 self.lower_pat_ty_pat(ty, ty_span, pat).map(|pat| tcx.mk_pat(pat))
3041 }))
3042 .map(ty::PatternKind::Or)
3043 }
3044 hir::TyPatKind::Err(e) => Err(e),
3045 }
3046 }
3047
3048 x;#[instrument(level = "debug", skip(self), ret)]
3050 fn lower_opaque_ty(&self, def_id: LocalDefId, in_trait: Option<LocalDefId>) -> Ty<'tcx> {
3051 let tcx = self.tcx();
3052
3053 let lifetimes = tcx.opaque_captured_lifetimes(def_id);
3054 debug!(?lifetimes);
3055
3056 let def_id = if let Some(parent_def_id) = in_trait {
3060 *tcx.associated_types_for_impl_traits_in_associated_fn(parent_def_id.to_def_id())
3061 .iter()
3062 .find(|rpitit| match tcx.opt_rpitit_info(**rpitit) {
3063 Some(ty::ImplTraitInTraitData::Trait { opaque_def_id, .. }) => {
3064 opaque_def_id.expect_local() == def_id
3065 }
3066 _ => unreachable!(),
3067 })
3068 .unwrap()
3069 } else {
3070 def_id.to_def_id()
3071 };
3072
3073 let generics = tcx.generics_of(def_id);
3074 debug!(?generics);
3075
3076 let offset = generics.count() - lifetimes.len();
3080
3081 let args = ty::GenericArgs::for_item(tcx, def_id, |param, _| {
3082 if let Some(i) = (param.index as usize).checked_sub(offset) {
3083 let (lifetime, _) = lifetimes[i];
3084 self.lower_resolved_lifetime(lifetime).into()
3086 } else {
3087 tcx.mk_param_from_def(param)
3088 }
3089 });
3090 debug!(?args);
3091
3092 if in_trait.is_some() {
3093 Ty::new_projection_from_args(tcx, def_id, args)
3094 } else {
3095 Ty::new_opaque(tcx, def_id, args)
3096 }
3097 }
3098
3099 x;#[instrument(level = "debug", skip(self, hir_id, safety, abi, decl, generics, hir_ty), ret)]
3101 pub fn lower_fn_ty(
3102 &self,
3103 hir_id: HirId,
3104 safety: hir::Safety,
3105 abi: rustc_abi::ExternAbi,
3106 decl: &hir::FnDecl<'tcx>,
3107 generics: Option<&hir::Generics<'_>>,
3108 hir_ty: Option<&hir::Ty<'_>>,
3109 ) -> ty::PolyFnSig<'tcx> {
3110 let tcx = self.tcx();
3111 let bound_vars = tcx.late_bound_vars(hir_id);
3112 debug!(?bound_vars);
3113
3114 let (input_tys, output_ty) = self.lower_fn_sig(decl, generics, hir_id, hir_ty);
3115
3116 debug!(?output_ty);
3117
3118 let fn_ty = tcx.mk_fn_sig(input_tys, output_ty, decl.c_variadic, safety, abi);
3119 let fn_ptr_ty = ty::Binder::bind_with_vars(fn_ty, bound_vars);
3120
3121 if let hir::Node::Ty(hir::Ty { kind: hir::TyKind::FnPtr(fn_ptr_ty), span, .. }) =
3122 tcx.hir_node(hir_id)
3123 {
3124 check_abi(tcx, hir_id, *span, fn_ptr_ty.abi);
3125 }
3126
3127 cmse::validate_cmse_abi(self.tcx(), self.dcx(), hir_id, abi, fn_ptr_ty);
3129
3130 if !fn_ptr_ty.references_error() {
3131 let inputs = fn_ptr_ty.inputs();
3138 let late_bound_in_args =
3139 tcx.collect_constrained_late_bound_regions(inputs.map_bound(|i| i.to_owned()));
3140 let output = fn_ptr_ty.output();
3141 let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(output);
3142
3143 self.validate_late_bound_regions(late_bound_in_args, late_bound_in_ret, |br_name| {
3144 struct_span_code_err!(
3145 self.dcx(),
3146 decl.output.span(),
3147 E0581,
3148 "return type references {}, which is not constrained by the fn input types",
3149 br_name
3150 )
3151 });
3152 }
3153
3154 fn_ptr_ty
3155 }
3156
3157 pub(super) fn suggest_trait_fn_ty_for_impl_fn_infer(
3162 &self,
3163 fn_hir_id: HirId,
3164 arg_idx: Option<usize>,
3165 ) -> Option<Ty<'tcx>> {
3166 let tcx = self.tcx();
3167 let hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), ident, .. }) =
3168 tcx.hir_node(fn_hir_id)
3169 else {
3170 return None;
3171 };
3172 let i = tcx.parent_hir_node(fn_hir_id).expect_item().expect_impl();
3173
3174 let trait_ref = self.lower_impl_trait_ref(&i.of_trait?.trait_ref, self.lower_ty(i.self_ty));
3175
3176 let assoc = tcx.associated_items(trait_ref.def_id).find_by_ident_and_kind(
3177 tcx,
3178 *ident,
3179 ty::AssocTag::Fn,
3180 trait_ref.def_id,
3181 )?;
3182
3183 let fn_sig = tcx.fn_sig(assoc.def_id).instantiate(
3184 tcx,
3185 trait_ref.args.extend_to(tcx, assoc.def_id, |param, _| tcx.mk_param_from_def(param)),
3186 );
3187 let fn_sig = tcx.liberate_late_bound_regions(fn_hir_id.expect_owner().to_def_id(), fn_sig);
3188
3189 Some(if let Some(arg_idx) = arg_idx {
3190 *fn_sig.inputs().get(arg_idx)?
3191 } else {
3192 fn_sig.output()
3193 })
3194 }
3195
3196 #[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(3196u32),
::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))]
3197 fn validate_late_bound_regions<'cx>(
3198 &'cx self,
3199 constrained_regions: FxIndexSet<ty::BoundRegionKind<'tcx>>,
3200 referenced_regions: FxIndexSet<ty::BoundRegionKind<'tcx>>,
3201 generate_err: impl Fn(&str) -> Diag<'cx>,
3202 ) {
3203 for br in referenced_regions.difference(&constrained_regions) {
3204 let br_name = if let Some(name) = br.get_name(self.tcx()) {
3205 format!("lifetime `{name}`")
3206 } else {
3207 "an anonymous lifetime".to_string()
3208 };
3209
3210 let mut err = generate_err(&br_name);
3211
3212 if !br.is_named(self.tcx()) {
3213 err.note(
3220 "lifetimes appearing in an associated or opaque type are not considered constrained",
3221 );
3222 err.note("consider introducing a named lifetime parameter");
3223 }
3224
3225 err.emit();
3226 }
3227 }
3228
3229 x;#[instrument(level = "debug", skip(self, span), ret)]
3237 fn compute_object_lifetime_bound(
3238 &self,
3239 span: Span,
3240 existential_predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
3241 ) -> Option<ty::Region<'tcx>> {
3243 let tcx = self.tcx();
3244
3245 let derived_region_bounds = object_region_bounds(tcx, existential_predicates);
3248
3249 if derived_region_bounds.is_empty() {
3252 return None;
3253 }
3254
3255 if derived_region_bounds.iter().any(|r| r.is_static()) {
3258 return Some(tcx.lifetimes.re_static);
3259 }
3260
3261 let r = derived_region_bounds[0];
3265 if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
3266 self.dcx().emit_err(AmbiguousLifetimeBound { span });
3267 }
3268 Some(r)
3269 }
3270
3271 fn construct_const_ctor_value(
3272 &self,
3273 ctor_def_id: DefId,
3274 ctor_of: CtorOf,
3275 args: GenericArgsRef<'tcx>,
3276 ) -> Const<'tcx> {
3277 let tcx = self.tcx();
3278 let parent_did = tcx.parent(ctor_def_id);
3279
3280 let adt_def = tcx.adt_def(match ctor_of {
3281 CtorOf::Variant => tcx.parent(parent_did),
3282 CtorOf::Struct => parent_did,
3283 });
3284
3285 let variant_idx = adt_def.variant_index_with_id(parent_did);
3286
3287 let valtree = if adt_def.is_enum() {
3288 let discr = ty::ValTree::from_scalar_int(tcx, variant_idx.as_u32().into());
3289 ty::ValTree::from_branches(tcx, [ty::Const::new_value(tcx, discr, tcx.types.u32)])
3290 } else {
3291 ty::ValTree::zst(tcx)
3292 };
3293
3294 let adt_ty = Ty::new_adt(tcx, adt_def, args);
3295 ty::Const::new_value(tcx, valtree, adt_ty)
3296 }
3297}