1mod bounds;
17mod cmse;
18mod dyn_trait;
19pub mod errors;
20pub mod generics;
21
22use std::{assert_matches, slice};
23
24use rustc_abi::FIRST_VARIANT;
25use rustc_ast::LitKind;
26use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet};
27use rustc_errors::codes::*;
28use rustc_errors::{
29 Applicability, Diag, DiagCtxtHandle, Diagnostic, ErrorGuaranteed, FatalError, Level,
30 struct_span_code_err,
31};
32use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res};
33use rustc_hir::def_id::{DefId, LocalDefId};
34use rustc_hir::{self as hir, AnonConst, GenericArg, GenericArgs, HirId};
35use rustc_infer::infer::{InferCtxt, TyCtxtInferExt};
36use rustc_infer::traits::DynCompatibilityViolation;
37use rustc_macros::{TypeFoldable, TypeVisitable};
38use rustc_middle::middle::stability::AllowUnstable;
39use rustc_middle::ty::print::PrintPolyTraitRefExt as _;
40use rustc_middle::ty::{
41 self, Const, GenericArgKind, GenericArgsRef, GenericParamDefKind, LitToConstInput, Ty, TyCtxt,
42 TypeSuperFoldable, TypeVisitableExt, TypingMode, Upcast, const_lit_matches_ty, fold_regions,
43};
44use rustc_middle::{bug, span_bug};
45use rustc_session::lint::builtin::AMBIGUOUS_ASSOCIATED_ITEMS;
46use rustc_session::parse::feature_err;
47use rustc_span::{DUMMY_SP, Ident, Span, kw, sym};
48use rustc_trait_selection::infer::InferCtxtExt;
49use rustc_trait_selection::traits::wf::object_region_bounds;
50use rustc_trait_selection::traits::{self, FulfillmentError};
51use tracing::{debug, instrument};
52
53use crate::check::check_abi;
54use crate::errors::{AmbiguousLifetimeBound, BadReturnTypeNotation, NoFieldOnType};
55use crate::hir_ty_lowering::errors::{GenericsArgsErrExtend, prohibit_assoc_item_constraint};
56use crate::hir_ty_lowering::generics::{check_generic_arg_count, lower_generic_args};
57use crate::middle::resolve_bound_vars as rbv;
58use crate::{NoVariantNamed, check_c_variadic_abi};
59
60#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for ImpliedBoundsContext<'tcx> {
#[inline]
fn clone(&self) -> ImpliedBoundsContext<'tcx> {
let _: ::core::clone::AssertParamIsClone<LocalDefId>;
let _:
::core::clone::AssertParamIsClone<&'tcx [hir::WherePredicate<'tcx>]>;
*self
}
}Clone, #[automatically_derived]
impl<'tcx> ::core::marker::Copy for ImpliedBoundsContext<'tcx> { }Copy)]
63pub(crate) enum ImpliedBoundsContext<'tcx> {
64 TraitDef(LocalDefId),
67 TyParam(LocalDefId, &'tcx [hir::WherePredicate<'tcx>]),
69 AssociatedTypeOrImplTrait,
71}
72
73#[derive(#[automatically_derived]
impl ::core::fmt::Debug for GenericPathSegment {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"GenericPathSegment", &self.0, &&self.1)
}
}Debug)]
75pub struct GenericPathSegment(pub DefId, pub usize);
76
77#[derive(#[automatically_derived]
impl ::core::marker::Copy for PredicateFilter { }Copy, #[automatically_derived]
impl ::core::clone::Clone for PredicateFilter {
#[inline]
fn clone(&self) -> PredicateFilter {
let _: ::core::clone::AssertParamIsClone<Ident>;
*self
}
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for PredicateFilter {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
PredicateFilter::All =>
::core::fmt::Formatter::write_str(f, "All"),
PredicateFilter::SelfOnly =>
::core::fmt::Formatter::write_str(f, "SelfOnly"),
PredicateFilter::SelfTraitThatDefines(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"SelfTraitThatDefines", &__self_0),
PredicateFilter::SelfAndAssociatedTypeBounds =>
::core::fmt::Formatter::write_str(f,
"SelfAndAssociatedTypeBounds"),
PredicateFilter::ConstIfConst =>
::core::fmt::Formatter::write_str(f, "ConstIfConst"),
PredicateFilter::SelfConstIfConst =>
::core::fmt::Formatter::write_str(f, "SelfConstIfConst"),
}
}
}Debug)]
78pub enum PredicateFilter {
79 All,
81
82 SelfOnly,
84
85 SelfTraitThatDefines(Ident),
89
90 SelfAndAssociatedTypeBounds,
94
95 ConstIfConst,
97
98 SelfConstIfConst,
100}
101
102#[derive(#[automatically_derived]
impl<'a> ::core::fmt::Debug for RegionInferReason<'a> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
RegionInferReason::ExplicitObjectLifetime =>
::core::fmt::Formatter::write_str(f,
"ExplicitObjectLifetime"),
RegionInferReason::ObjectLifetimeDefault(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"ObjectLifetimeDefault", &__self_0),
RegionInferReason::Param(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Param",
&__self_0),
RegionInferReason::RegionPredicate =>
::core::fmt::Formatter::write_str(f, "RegionPredicate"),
RegionInferReason::Reference =>
::core::fmt::Formatter::write_str(f, "Reference"),
RegionInferReason::OutlivesBound =>
::core::fmt::Formatter::write_str(f, "OutlivesBound"),
}
}
}Debug)]
103pub enum RegionInferReason<'a> {
104 ExplicitObjectLifetime,
106 ObjectLifetimeDefault(Span),
108 Param(&'a ty::GenericParamDef),
110 RegionPredicate,
111 Reference,
112 OutlivesBound,
113}
114
115#[derive(#[automatically_derived]
impl ::core::marker::Copy for InherentAssocCandidate { }Copy, #[automatically_derived]
impl ::core::clone::Clone for InherentAssocCandidate {
#[inline]
fn clone(&self) -> InherentAssocCandidate {
let _: ::core::clone::AssertParamIsClone<DefId>;
*self
}
}Clone, const _: () =
{
impl<'tcx>
::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
for InherentAssocCandidate {
fn try_fold_with<__F: ::rustc_middle::ty::FallibleTypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
__folder: &mut __F) -> Result<Self, __F::Error> {
Ok(match self {
InherentAssocCandidate {
impl_: __binding_0,
assoc_item: __binding_1,
scope: __binding_2 } => {
InherentAssocCandidate {
impl_: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
__folder)?,
assoc_item: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_1,
__folder)?,
scope: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_2,
__folder)?,
}
}
})
}
fn fold_with<__F: ::rustc_middle::ty::TypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
__folder: &mut __F) -> Self {
match self {
InherentAssocCandidate {
impl_: __binding_0,
assoc_item: __binding_1,
scope: __binding_2 } => {
InherentAssocCandidate {
impl_: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
__folder),
assoc_item: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_1,
__folder),
scope: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_2,
__folder),
}
}
}
}
}
};TypeFoldable, const _: () =
{
impl<'tcx>
::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
for InherentAssocCandidate {
fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
__visitor: &mut __V) -> __V::Result {
match *self {
InherentAssocCandidate {
impl_: ref __binding_0,
assoc_item: ref __binding_1,
scope: ref __binding_2 } => {
{
match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
__visitor)) {
::core::ops::ControlFlow::Continue(()) => {}
::core::ops::ControlFlow::Break(r) => {
return ::rustc_middle::ty::VisitorResult::from_residual(r);
}
}
}
{
match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_1,
__visitor)) {
::core::ops::ControlFlow::Continue(()) => {}
::core::ops::ControlFlow::Break(r) => {
return ::rustc_middle::ty::VisitorResult::from_residual(r);
}
}
}
{
match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_2,
__visitor)) {
::core::ops::ControlFlow::Continue(()) => {}
::core::ops::ControlFlow::Break(r) => {
return ::rustc_middle::ty::VisitorResult::from_residual(r);
}
}
}
}
}
<__V::Result as ::rustc_middle::ty::VisitorResult>::output()
}
}
};TypeVisitable, #[automatically_derived]
impl ::core::fmt::Debug for InherentAssocCandidate {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field3_finish(f,
"InherentAssocCandidate", "impl_", &self.impl_, "assoc_item",
&self.assoc_item, "scope", &&self.scope)
}
}Debug)]
116pub struct InherentAssocCandidate {
117 pub impl_: DefId,
118 pub assoc_item: DefId,
119 pub scope: DefId,
120}
121
122pub trait HirTyLowerer<'tcx> {
127 fn tcx(&self) -> TyCtxt<'tcx>;
128
129 fn dcx(&self) -> DiagCtxtHandle<'_>;
130
131 fn item_def_id(&self) -> LocalDefId;
133
134 fn re_infer(&self, span: Span, reason: RegionInferReason<'_>) -> ty::Region<'tcx>;
136
137 fn ty_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx>;
139
140 fn ct_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Const<'tcx>;
142
143 fn register_trait_ascription_bounds(
144 &self,
145 bounds: Vec<(ty::Clause<'tcx>, Span)>,
146 hir_id: HirId,
147 span: Span,
148 );
149
150 fn probe_ty_param_bounds(
165 &self,
166 span: Span,
167 def_id: LocalDefId,
168 assoc_ident: Ident,
169 ) -> ty::EarlyBinder<'tcx, &'tcx [(ty::Clause<'tcx>, Span)]>;
170
171 fn select_inherent_assoc_candidates(
172 &self,
173 span: Span,
174 self_ty: Ty<'tcx>,
175 candidates: Vec<InherentAssocCandidate>,
176 ) -> (Vec<InherentAssocCandidate>, Vec<FulfillmentError<'tcx>>);
177
178 fn lower_assoc_item_path(
191 &self,
192 span: Span,
193 item_def_id: DefId,
194 item_segment: &hir::PathSegment<'tcx>,
195 poly_trait_ref: ty::PolyTraitRef<'tcx>,
196 ) -> Result<(DefId, GenericArgsRef<'tcx>), ErrorGuaranteed>;
197
198 fn lower_fn_sig(
199 &self,
200 decl: &hir::FnDecl<'tcx>,
201 generics: Option<&hir::Generics<'_>>,
202 hir_id: HirId,
203 hir_ty: Option<&hir::Ty<'_>>,
204 ) -> (Vec<Ty<'tcx>>, Ty<'tcx>);
205
206 fn probe_adt(&self, span: Span, ty: Ty<'tcx>) -> Option<ty::AdtDef<'tcx>>;
213
214 fn record_ty(&self, hir_id: HirId, ty: Ty<'tcx>, span: Span);
216
217 fn infcx(&self) -> Option<&InferCtxt<'tcx>>;
219
220 fn lowerer(&self) -> &dyn HirTyLowerer<'tcx>
225 where
226 Self: Sized,
227 {
228 self
229 }
230
231 fn dyn_compatibility_violations(&self, trait_def_id: DefId) -> Vec<DynCompatibilityViolation>;
234}
235
236enum AssocItemQSelf {
240 Trait(DefId),
241 TyParam(LocalDefId, Span),
242 SelfTyAlias,
243}
244
245impl AssocItemQSelf {
246 fn to_string(&self, tcx: TyCtxt<'_>) -> String {
247 match *self {
248 Self::Trait(def_id) => tcx.def_path_str(def_id),
249 Self::TyParam(def_id, _) => tcx.hir_ty_param_name(def_id).to_string(),
250 Self::SelfTyAlias => kw::SelfUpper.to_string(),
251 }
252 }
253}
254
255#[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)]
256enum LowerTypeRelativePathMode {
257 Type(PermitVariants),
258 Const,
259}
260
261impl LowerTypeRelativePathMode {
262 fn assoc_tag(self) -> ty::AssocTag {
263 match self {
264 Self::Type(_) => ty::AssocTag::Type,
265 Self::Const => ty::AssocTag::Const,
266 }
267 }
268
269 fn def_kind_for_diagnostics(self) -> DefKind {
271 match self {
272 Self::Type(_) => DefKind::AssocTy,
273 Self::Const => DefKind::AssocConst { is_type_const: false },
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::fmt::Debug for GenericArgPosition {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
GenericArgPosition::Type => "Type",
GenericArgPosition::Value => "Value",
GenericArgPosition::MethodCall => "MethodCall",
})
}
}Debug, #[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 if self.tcx.features().opaque_generic_const_args() {
391 "generic parameters in const blocks are only allowed as the direct value of a `type const`"
392 } else {
393 "generic parameters may not be used in const operations"
394 };
395 let mut diag = self.tcx.dcx().struct_span_err(self.span, msg);
396 if self.is_self_alias {
397 let anon_const_hir_id: HirId = HirId::make_owner(self.anon_const_def_id);
398 let parent_impl = self.tcx.hir_parent_owner_iter(anon_const_hir_id).find_map(
399 |(_, node)| match node {
400 hir::OwnerNode::Item(hir::Item {
401 kind: hir::ItemKind::Impl(impl_), ..
402 }) => Some(impl_),
403 _ => None,
404 },
405 );
406 if let Some(impl_) = parent_impl {
407 diag.span_note(impl_.self_ty.span, "not a concrete type");
408 }
409 }
410 if self.tcx.features().min_generic_const_args() {
411 if !self.tcx.features().opaque_generic_const_args() {
412 diag.help("add `#![feature(opaque_generic_const_args)]` to allow generic expressions as the RHS of const items");
413 } else {
414 diag.help("consider factoring the expression into a `type const` item and use it as the const argument instead");
415 }
416 };
417 diag.emit()
418 }
419}
420
421impl<'tcx> ty::TypeFolder<TyCtxt<'tcx>> for ForbidMCGParamUsesFolder<'tcx> {
422 fn cx(&self) -> TyCtxt<'tcx> {
423 self.tcx
424 }
425
426 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
427 if #[allow(non_exhaustive_omitted_patterns)] match t.kind() {
ty::Param(..) => true,
_ => false,
}matches!(t.kind(), ty::Param(..)) {
428 return Ty::new_error(self.tcx, self.error());
429 }
430 t.super_fold_with(self)
431 }
432
433 fn fold_const(&mut self, c: Const<'tcx>) -> Const<'tcx> {
434 if #[allow(non_exhaustive_omitted_patterns)] match c.kind() {
ty::ConstKind::Param(..) => true,
_ => false,
}matches!(c.kind(), ty::ConstKind::Param(..)) {
435 return Const::new_error(self.tcx, self.error());
436 }
437 c.super_fold_with(self)
438 }
439
440 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
441 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(..)) {
442 return ty::Region::new_error(self.tcx, self.error());
443 }
444 r
445 }
446}
447
448impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
449 pub fn check_param_res_if_mcg_for_instantiate_value_path(
453 &self,
454 res: Res,
455 span: Span,
456 ) -> Result<(), ErrorGuaranteed> {
457 let tcx = self.tcx();
458 let parent_def_id = self.item_def_id();
459 if let Res::Def(DefKind::ConstParam, _) = res
460 && tcx.def_kind(parent_def_id) == DefKind::AnonConst
461 && let ty::AnonConstKind::MCG = tcx.anon_const_kind(parent_def_id)
462 {
463 let folder = ForbidMCGParamUsesFolder {
464 tcx,
465 anon_const_def_id: parent_def_id,
466 span,
467 is_self_alias: false,
468 };
469 return Err(folder.error());
470 }
471 Ok(())
472 }
473
474 #[must_use = "need to use transformed output"]
477 fn check_param_uses_if_mcg<T>(&self, term: T, span: Span, is_self_alias: bool) -> T
478 where
479 T: ty::TypeFoldable<TyCtxt<'tcx>>,
480 {
481 let tcx = self.tcx();
482 let parent_def_id = self.item_def_id();
483 if tcx.def_kind(parent_def_id) == DefKind::AnonConst
484 && let ty::AnonConstKind::MCG = tcx.anon_const_kind(parent_def_id)
485 && (term.has_param() || term.has_escaping_bound_vars())
487 {
488 let mut folder = ForbidMCGParamUsesFolder {
489 tcx,
490 anon_const_def_id: parent_def_id,
491 span,
492 is_self_alias,
493 };
494 term.fold_with(&mut folder)
495 } else {
496 term
497 }
498 }
499
500 x;#[instrument(level = "debug", skip(self), ret)]
502 pub fn lower_lifetime(
503 &self,
504 lifetime: &hir::Lifetime,
505 reason: RegionInferReason<'_>,
506 ) -> ty::Region<'tcx> {
507 if let Some(resolved) = self.tcx().named_bound_var(lifetime.hir_id) {
508 let region = self.lower_resolved_lifetime(resolved);
509 self.check_param_uses_if_mcg(region, lifetime.ident.span, false)
510 } else {
511 self.re_infer(lifetime.ident.span, reason)
512 }
513 }
514
515 x;#[instrument(level = "debug", skip(self), ret)]
517 fn lower_resolved_lifetime(&self, resolved: rbv::ResolvedArg) -> ty::Region<'tcx> {
518 let tcx = self.tcx();
519
520 match resolved {
521 rbv::ResolvedArg::StaticLifetime => tcx.lifetimes.re_static,
522
523 rbv::ResolvedArg::LateBound(debruijn, index, def_id) => {
524 let br = ty::BoundRegion {
525 var: ty::BoundVar::from_u32(index),
526 kind: ty::BoundRegionKind::Named(def_id.to_def_id()),
527 };
528 ty::Region::new_bound(tcx, debruijn, br)
529 }
530
531 rbv::ResolvedArg::EarlyBound(def_id) => {
532 let name = tcx.hir_ty_param_name(def_id);
533 let item_def_id = tcx.hir_ty_param_owner(def_id);
534 let generics = tcx.generics_of(item_def_id);
535 let index = generics.param_def_id_to_index[&def_id.to_def_id()];
536 ty::Region::new_early_param(tcx, ty::EarlyParamRegion { index, name })
537 }
538
539 rbv::ResolvedArg::Free(scope, id) => {
540 ty::Region::new_late_param(
541 tcx,
542 scope.to_def_id(),
543 ty::LateParamRegionKind::Named(id.to_def_id()),
544 )
545
546 }
548
549 rbv::ResolvedArg::Error(guar) => ty::Region::new_error(tcx, guar),
550 }
551 }
552
553 pub fn lower_generic_args_of_path_segment(
554 &self,
555 span: Span,
556 def_id: DefId,
557 item_segment: &hir::PathSegment<'tcx>,
558 ) -> GenericArgsRef<'tcx> {
559 let (args, _) = self.lower_generic_args_of_path(
560 span,
561 def_id,
562 &[],
563 item_segment,
564 None,
565 GenericArgPosition::Type,
566 );
567 if let Some(c) = item_segment.args().constraints.first() {
568 prohibit_assoc_item_constraint(self, c, Some((def_id, item_segment, span)));
569 }
570 args
571 }
572
573 x;#[instrument(level = "debug", skip(self, span), ret)]
608 pub(crate) fn lower_generic_args_of_path(
609 &self,
610 span: Span,
611 def_id: DefId,
612 parent_args: &[ty::GenericArg<'tcx>],
613 segment: &hir::PathSegment<'tcx>,
614 self_ty: Option<Ty<'tcx>>,
615 pos: GenericArgPosition,
616 ) -> (GenericArgsRef<'tcx>, GenericArgCountResult) {
617 let tcx = self.tcx();
622 let generics = tcx.generics_of(def_id);
623 debug!(?generics);
624
625 if generics.has_self {
626 if generics.parent.is_some() {
627 assert!(!parent_args.is_empty())
630 } else {
631 assert!(self_ty.is_some());
633 }
634 } else {
635 assert!(self_ty.is_none());
636 }
637
638 let arg_count =
639 check_generic_arg_count(self, def_id, segment, generics, pos, self_ty.is_some());
640
641 if generics.is_own_empty() {
646 return (tcx.mk_args(parent_args), arg_count);
647 }
648
649 struct GenericArgsCtxt<'a, 'tcx> {
650 lowerer: &'a dyn HirTyLowerer<'tcx>,
651 def_id: DefId,
652 generic_args: &'a GenericArgs<'tcx>,
653 span: Span,
654 infer_args: bool,
655 incorrect_args: &'a Result<(), GenericArgCountMismatch>,
656 }
657
658 impl<'a, 'tcx> GenericArgsLowerer<'a, 'tcx> for GenericArgsCtxt<'a, 'tcx> {
659 fn args_for_def_id(&mut self, did: DefId) -> (Option<&'a GenericArgs<'tcx>>, bool) {
660 if did == self.def_id {
661 (Some(self.generic_args), self.infer_args)
662 } else {
663 (None, false)
665 }
666 }
667
668 fn provided_kind(
669 &mut self,
670 preceding_args: &[ty::GenericArg<'tcx>],
671 param: &ty::GenericParamDef,
672 arg: &GenericArg<'tcx>,
673 ) -> ty::GenericArg<'tcx> {
674 let tcx = self.lowerer.tcx();
675
676 if let Err(incorrect) = self.incorrect_args {
677 if incorrect.invalid_args.contains(&(param.index as usize)) {
678 return param.to_error(tcx);
679 }
680 }
681
682 let handle_ty_args = |has_default, ty: &hir::Ty<'tcx>| {
683 if has_default {
684 tcx.check_optional_stability(
685 param.def_id,
686 Some(arg.hir_id()),
687 arg.span(),
688 None,
689 AllowUnstable::No,
690 |_, _| {
691 },
697 );
698 }
699 self.lowerer.lower_ty(ty).into()
700 };
701
702 match (¶m.kind, arg) {
703 (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => {
704 self.lowerer.lower_lifetime(lt, RegionInferReason::Param(param)).into()
705 }
706 (&GenericParamDefKind::Type { has_default, .. }, GenericArg::Type(ty)) => {
707 handle_ty_args(has_default, ty.as_unambig_ty())
709 }
710 (&GenericParamDefKind::Type { has_default, .. }, GenericArg::Infer(inf)) => {
711 handle_ty_args(has_default, &inf.to_ty())
712 }
713 (GenericParamDefKind::Const { .. }, GenericArg::Const(ct)) => self
714 .lowerer
715 .lower_const_arg(
717 ct.as_unambig_ct(),
718 tcx.type_of(param.def_id).instantiate(tcx, preceding_args),
719 )
720 .into(),
721 (&GenericParamDefKind::Const { .. }, GenericArg::Infer(inf)) => {
722 self.lowerer.ct_infer(Some(param), inf.span).into()
723 }
724 (kind, arg) => span_bug!(
725 self.span,
726 "mismatched path argument for kind {kind:?}: found arg {arg:?}"
727 ),
728 }
729 }
730
731 fn inferred_kind(
732 &mut self,
733 preceding_args: &[ty::GenericArg<'tcx>],
734 param: &ty::GenericParamDef,
735 infer_args: bool,
736 ) -> ty::GenericArg<'tcx> {
737 let tcx = self.lowerer.tcx();
738
739 if let Err(incorrect) = self.incorrect_args {
740 if incorrect.invalid_args.contains(&(param.index as usize)) {
741 return param.to_error(tcx);
742 }
743 }
744 match param.kind {
745 GenericParamDefKind::Lifetime => {
746 self.lowerer.re_infer(self.span, RegionInferReason::Param(param)).into()
747 }
748 GenericParamDefKind::Type { has_default, .. } => {
749 if !infer_args && has_default {
750 if let Some(prev) =
752 preceding_args.iter().find_map(|arg| match arg.kind() {
753 GenericArgKind::Type(ty) => ty.error_reported().err(),
754 _ => None,
755 })
756 {
757 return Ty::new_error(tcx, prev).into();
759 }
760 tcx.at(self.span)
761 .type_of(param.def_id)
762 .instantiate(tcx, preceding_args)
763 .into()
764 } else if infer_args {
765 self.lowerer.ty_infer(Some(param), self.span).into()
766 } else {
767 Ty::new_misc_error(tcx).into()
769 }
770 }
771 GenericParamDefKind::Const { has_default, .. } => {
772 let ty = tcx
773 .at(self.span)
774 .type_of(param.def_id)
775 .instantiate(tcx, preceding_args);
776 if let Err(guar) = ty.error_reported() {
777 return ty::Const::new_error(tcx, guar).into();
778 }
779 if !infer_args && has_default {
780 tcx.const_param_default(param.def_id)
781 .instantiate(tcx, preceding_args)
782 .into()
783 } else if infer_args {
784 self.lowerer.ct_infer(Some(param), self.span).into()
785 } else {
786 ty::Const::new_misc_error(tcx).into()
788 }
789 }
790 }
791 }
792 }
793
794 let mut args_ctx = GenericArgsCtxt {
795 lowerer: self,
796 def_id,
797 span,
798 generic_args: segment.args(),
799 infer_args: segment.infer_args,
800 incorrect_args: &arg_count.correct,
801 };
802
803 let args = lower_generic_args(
804 self,
805 def_id,
806 parent_args,
807 self_ty.is_some(),
808 self_ty,
809 &arg_count,
810 &mut args_ctx,
811 );
812
813 (args, arg_count)
814 }
815
816 #[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(816u32),
::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, GenericArgPosition::Type);
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))]
817 pub fn lower_generic_args_of_assoc_item(
818 &self,
819 span: Span,
820 item_def_id: DefId,
821 item_segment: &hir::PathSegment<'tcx>,
822 parent_args: GenericArgsRef<'tcx>,
823 ) -> GenericArgsRef<'tcx> {
824 let (args, _) = self.lower_generic_args_of_path(
825 span,
826 item_def_id,
827 parent_args,
828 item_segment,
829 None,
830 GenericArgPosition::Type,
831 );
832 if let Some(c) = item_segment.args().constraints.first() {
833 prohibit_assoc_item_constraint(self, c, Some((item_def_id, item_segment, span)));
834 }
835 args
836 }
837
838 pub fn lower_impl_trait_ref(
842 &self,
843 trait_ref: &hir::TraitRef<'tcx>,
844 self_ty: Ty<'tcx>,
845 ) -> ty::TraitRef<'tcx> {
846 let [leading_segments @ .., segment] = trait_ref.path.segments else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
847
848 let _ = self.prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
849
850 self.lower_mono_trait_ref(
851 trait_ref.path.span,
852 trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise()),
853 self_ty,
854 segment,
855 true,
856 )
857 }
858
859 #[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(882u32),
::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),
GenericArgPosition::Type);
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:963",
"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(963u32),
::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:970",
"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(970u32),
::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))]
883 pub(crate) fn lower_poly_trait_ref(
884 &self,
885 &hir::PolyTraitRef {
886 bound_generic_params,
887 modifiers: hir::TraitBoundModifiers { constness, polarity },
888 trait_ref,
889 span,
890 }: &hir::PolyTraitRef<'tcx>,
891 self_ty: Ty<'tcx>,
892 bounds: &mut Vec<(ty::Clause<'tcx>, Span)>,
893 predicate_filter: PredicateFilter,
894 overlapping_assoc_item_constraints: OverlappingAsssocItemConstraints,
895 ) -> GenericArgCountResult {
896 let tcx = self.tcx();
897
898 let _ = bound_generic_params;
901
902 let trait_def_id = trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise());
903
904 let transient = match polarity {
909 hir::BoundPolarity::Positive => {
910 tcx.is_lang_item(trait_def_id, hir::LangItem::PointeeSized)
916 }
917 hir::BoundPolarity::Negative(_) => false,
918 hir::BoundPolarity::Maybe(_) => {
919 self.require_bound_to_relax_default_trait(trait_ref, span);
920 true
921 }
922 };
923 let bounds = if transient { &mut Vec::new() } else { bounds };
924
925 let polarity = match polarity {
926 hir::BoundPolarity::Positive | hir::BoundPolarity::Maybe(_) => {
927 ty::PredicatePolarity::Positive
928 }
929 hir::BoundPolarity::Negative(_) => ty::PredicatePolarity::Negative,
930 };
931
932 let [leading_segments @ .., segment] = trait_ref.path.segments else { bug!() };
933
934 let _ = self.prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
935 self.report_internal_fn_trait(span, trait_def_id, segment, false);
936
937 let (generic_args, arg_count) = self.lower_generic_args_of_path(
938 trait_ref.path.span,
939 trait_def_id,
940 &[],
941 segment,
942 Some(self_ty),
943 GenericArgPosition::Type,
944 );
945
946 let constraints = segment.args().constraints;
947
948 if transient && (!generic_args[1..].is_empty() || !constraints.is_empty()) {
949 self.dcx()
959 .span_delayed_bug(span, "transient bound should not have args or constraints");
960 }
961
962 let bound_vars = tcx.late_bound_vars(trait_ref.hir_ref_id);
963 debug!(?bound_vars);
964
965 let poly_trait_ref = ty::Binder::bind_with_vars(
966 ty::TraitRef::new_from_args(tcx, trait_def_id, generic_args),
967 bound_vars,
968 );
969
970 debug!(?poly_trait_ref);
971
972 match predicate_filter {
974 PredicateFilter::All
975 | PredicateFilter::SelfOnly
976 | PredicateFilter::SelfTraitThatDefines(..)
977 | PredicateFilter::SelfAndAssociatedTypeBounds => {
978 let bound = poly_trait_ref.map_bound(|trait_ref| {
979 ty::ClauseKind::Trait(ty::TraitPredicate { trait_ref, polarity })
980 });
981 let bound = (bound.upcast(tcx), span);
982 if tcx.is_lang_item(trait_def_id, rustc_hir::LangItem::Sized) {
988 bounds.insert(0, bound);
989 } else {
990 bounds.push(bound);
991 }
992 }
993 PredicateFilter::ConstIfConst | PredicateFilter::SelfConstIfConst => {}
994 }
995
996 if let hir::BoundConstness::Always(span) | hir::BoundConstness::Maybe(span) = constness
997 && !tcx.is_const_trait(trait_def_id)
998 {
999 let (def_span, suggestion, suggestion_pre) =
1000 match (trait_def_id.as_local(), tcx.sess.is_nightly_build()) {
1001 (Some(trait_def_id), true) => {
1002 let span = tcx.hir_expect_item(trait_def_id).vis_span;
1003 let span = tcx.sess.source_map().span_extend_while_whitespace(span);
1004
1005 (
1006 None,
1007 Some(span.shrink_to_hi()),
1008 if self.tcx().features().const_trait_impl() {
1009 ""
1010 } else {
1011 "enable `#![feature(const_trait_impl)]` in your crate and "
1012 },
1013 )
1014 }
1015 (None, _) | (_, false) => (Some(tcx.def_span(trait_def_id)), None, ""),
1016 };
1017 self.dcx().emit_err(crate::errors::ConstBoundForNonConstTrait {
1018 span,
1019 modifier: constness.as_str(),
1020 def_span,
1021 trait_name: tcx.def_path_str(trait_def_id),
1022 suggestion,
1023 suggestion_pre,
1024 });
1025 } else {
1026 match predicate_filter {
1027 PredicateFilter::SelfTraitThatDefines(..) => {}
1029 PredicateFilter::All
1030 | PredicateFilter::SelfOnly
1031 | PredicateFilter::SelfAndAssociatedTypeBounds => {
1032 match constness {
1033 hir::BoundConstness::Always(_) => {
1034 if polarity == ty::PredicatePolarity::Positive {
1035 bounds.push((
1036 poly_trait_ref
1037 .to_host_effect_clause(tcx, ty::BoundConstness::Const),
1038 span,
1039 ));
1040 }
1041 }
1042 hir::BoundConstness::Maybe(_) => {
1043 }
1048 hir::BoundConstness::Never => {}
1049 }
1050 }
1051 PredicateFilter::ConstIfConst | PredicateFilter::SelfConstIfConst => {
1058 match constness {
1059 hir::BoundConstness::Maybe(_) => {
1060 if polarity == ty::PredicatePolarity::Positive {
1061 bounds.push((
1062 poly_trait_ref
1063 .to_host_effect_clause(tcx, ty::BoundConstness::Maybe),
1064 span,
1065 ));
1066 }
1067 }
1068 hir::BoundConstness::Always(_) | hir::BoundConstness::Never => {}
1069 }
1070 }
1071 }
1072 }
1073
1074 let mut dup_constraints = (overlapping_assoc_item_constraints
1075 == OverlappingAsssocItemConstraints::Forbidden)
1076 .then_some(FxIndexMap::default());
1077
1078 for constraint in constraints {
1079 if polarity == ty::PredicatePolarity::Negative {
1083 self.dcx().span_delayed_bug(
1084 constraint.span,
1085 "negative trait bounds should not have assoc item constraints",
1086 );
1087 break;
1088 }
1089
1090 let _: Result<_, ErrorGuaranteed> = self.lower_assoc_item_constraint(
1092 trait_ref.hir_ref_id,
1093 poly_trait_ref,
1094 constraint,
1095 bounds,
1096 dup_constraints.as_mut(),
1097 constraint.span,
1098 predicate_filter,
1099 );
1100 }
1102
1103 arg_count
1104 }
1105
1106 fn lower_mono_trait_ref(
1110 &self,
1111 span: Span,
1112 trait_def_id: DefId,
1113 self_ty: Ty<'tcx>,
1114 trait_segment: &hir::PathSegment<'tcx>,
1115 is_impl: bool,
1116 ) -> ty::TraitRef<'tcx> {
1117 self.report_internal_fn_trait(span, trait_def_id, trait_segment, is_impl);
1118
1119 let (generic_args, _) = self.lower_generic_args_of_path(
1120 span,
1121 trait_def_id,
1122 &[],
1123 trait_segment,
1124 Some(self_ty),
1125 GenericArgPosition::Type,
1126 );
1127 if let Some(c) = trait_segment.args().constraints.first() {
1128 prohibit_assoc_item_constraint(self, c, Some((trait_def_id, trait_segment, span)));
1129 }
1130 ty::TraitRef::new_from_args(self.tcx(), trait_def_id, generic_args)
1131 }
1132
1133 fn probe_trait_that_defines_assoc_item(
1134 &self,
1135 trait_def_id: DefId,
1136 assoc_tag: ty::AssocTag,
1137 assoc_ident: Ident,
1138 ) -> bool {
1139 self.tcx()
1140 .associated_items(trait_def_id)
1141 .find_by_ident_and_kind(self.tcx(), assoc_ident, assoc_tag, trait_def_id)
1142 .is_some()
1143 }
1144
1145 fn lower_path_segment(
1146 &self,
1147 span: Span,
1148 did: DefId,
1149 item_segment: &hir::PathSegment<'tcx>,
1150 ) -> Ty<'tcx> {
1151 let tcx = self.tcx();
1152 let args = self.lower_generic_args_of_path_segment(span, did, item_segment);
1153
1154 if let DefKind::TyAlias = tcx.def_kind(did)
1155 && tcx.type_alias_is_lazy(did)
1156 {
1157 let alias_ty = ty::AliasTy::new_from_args(tcx, did, args);
1161 Ty::new_alias(tcx, ty::Free, alias_ty)
1162 } else {
1163 tcx.at(span).type_of(did).instantiate(tcx, args)
1164 }
1165 }
1166
1167 x;#[instrument(level = "debug", skip_all, ret)]
1175 fn probe_single_ty_param_bound_for_assoc_item(
1176 &self,
1177 ty_param_def_id: LocalDefId,
1178 ty_param_span: Span,
1179 assoc_tag: ty::AssocTag,
1180 assoc_ident: Ident,
1181 span: Span,
1182 ) -> Result<ty::PolyTraitRef<'tcx>, ErrorGuaranteed> {
1183 debug!(?ty_param_def_id, ?assoc_ident, ?span);
1184 let tcx = self.tcx();
1185
1186 let predicates = &self.probe_ty_param_bounds(span, ty_param_def_id, assoc_ident);
1187 debug!("predicates={:#?}", predicates);
1188
1189 self.probe_single_bound_for_assoc_item(
1190 || {
1191 let trait_refs = predicates
1192 .iter_identity_copied()
1193 .filter_map(|(p, _)| Some(p.as_trait_clause()?.map_bound(|t| t.trait_ref)));
1194 traits::transitive_bounds_that_define_assoc_item(tcx, trait_refs, assoc_ident)
1195 },
1196 AssocItemQSelf::TyParam(ty_param_def_id, ty_param_span),
1197 assoc_tag,
1198 assoc_ident,
1199 span,
1200 None,
1201 )
1202 }
1203
1204 x;#[instrument(level = "debug", skip(self, all_candidates, qself, constraint), ret)]
1210 fn probe_single_bound_for_assoc_item<I>(
1211 &self,
1212 all_candidates: impl Fn() -> I,
1213 qself: AssocItemQSelf,
1214 assoc_tag: ty::AssocTag,
1215 assoc_ident: Ident,
1216 span: Span,
1217 constraint: Option<&hir::AssocItemConstraint<'tcx>>,
1218 ) -> Result<ty::PolyTraitRef<'tcx>, ErrorGuaranteed>
1219 where
1220 I: Iterator<Item = ty::PolyTraitRef<'tcx>>,
1221 {
1222 let tcx = self.tcx();
1223
1224 let mut matching_candidates = all_candidates().filter(|r| {
1225 self.probe_trait_that_defines_assoc_item(r.def_id(), assoc_tag, assoc_ident)
1226 });
1227
1228 let Some(bound) = matching_candidates.next() else {
1229 return Err(self.report_unresolved_assoc_item(
1230 all_candidates,
1231 qself,
1232 assoc_tag,
1233 assoc_ident,
1234 span,
1235 constraint,
1236 ));
1237 };
1238 debug!(?bound);
1239
1240 if let Some(bound2) = matching_candidates.next() {
1241 debug!(?bound2);
1242
1243 let assoc_kind_str = errors::assoc_tag_str(assoc_tag);
1244 let qself_str = qself.to_string(tcx);
1245 let mut err = self.dcx().create_err(crate::errors::AmbiguousAssocItem {
1246 span,
1247 assoc_kind: assoc_kind_str,
1248 assoc_ident,
1249 qself: &qself_str,
1250 });
1251 err.code(
1253 if let Some(constraint) = constraint
1254 && let hir::AssocItemConstraintKind::Equality { .. } = constraint.kind
1255 {
1256 E0222
1257 } else {
1258 E0221
1259 },
1260 );
1261
1262 let mut where_bounds = vec![];
1266 for bound in [bound, bound2].into_iter().chain(matching_candidates) {
1267 let bound_id = bound.def_id();
1268 let assoc_item = tcx.associated_items(bound_id).find_by_ident_and_kind(
1269 tcx,
1270 assoc_ident,
1271 assoc_tag,
1272 bound_id,
1273 );
1274 let bound_span = assoc_item.and_then(|item| tcx.hir_span_if_local(item.def_id));
1275
1276 if let Some(bound_span) = bound_span {
1277 err.span_label(
1278 bound_span,
1279 format!("ambiguous `{assoc_ident}` from `{}`", bound.print_trait_sugared(),),
1280 );
1281 if let Some(constraint) = constraint {
1282 match constraint.kind {
1283 hir::AssocItemConstraintKind::Equality { term } => {
1284 let term: ty::Term<'_> = match term {
1285 hir::Term::Ty(ty) => self.lower_ty(ty).into(),
1286 hir::Term::Const(ct) => {
1287 let assoc_item =
1288 assoc_item.expect("assoc_item should be present");
1289 let projection_term = bound.map_bound(|trait_ref| {
1290 let item_segment = hir::PathSegment {
1291 ident: constraint.ident,
1292 hir_id: constraint.hir_id,
1293 res: Res::Err,
1294 args: Some(constraint.gen_args),
1295 infer_args: false,
1296 };
1297
1298 let alias_args = self.lower_generic_args_of_assoc_item(
1299 constraint.ident.span,
1300 assoc_item.def_id,
1301 &item_segment,
1302 trait_ref.args,
1303 );
1304 ty::AliasTerm::new_from_args(
1305 tcx,
1306 assoc_item.def_id,
1307 alias_args,
1308 )
1309 });
1310
1311 let ty = projection_term.map_bound(|alias| {
1314 tcx.type_of(alias.def_id).instantiate(tcx, alias.args)
1315 });
1316 let ty = bounds::check_assoc_const_binding_type(
1317 self,
1318 constraint.ident,
1319 ty,
1320 constraint.hir_id,
1321 );
1322
1323 self.lower_const_arg(ct, ty).into()
1324 }
1325 };
1326 if term.references_error() {
1327 continue;
1328 }
1329 where_bounds.push(format!(
1331 " T: {trait}::{assoc_ident} = {term}",
1332 trait = bound.print_only_trait_path(),
1333 ));
1334 }
1335 hir::AssocItemConstraintKind::Bound { bounds: _ } => {}
1337 }
1338 } else {
1339 err.span_suggestion_verbose(
1340 span.with_hi(assoc_ident.span.lo()),
1341 "use fully-qualified syntax to disambiguate",
1342 format!("<{qself_str} as {}>::", bound.print_only_trait_path()),
1343 Applicability::MaybeIncorrect,
1344 );
1345 }
1346 } else {
1347 let trait_ =
1348 tcx.short_string(bound.print_only_trait_path(), err.long_ty_path());
1349 err.note(format!(
1350 "associated {assoc_kind_str} `{assoc_ident}` could derive from `{trait_}`",
1351 ));
1352 }
1353 }
1354 if !where_bounds.is_empty() {
1355 err.help(format!(
1356 "consider introducing a new type parameter `T` and adding `where` constraints:\
1357 \n where\n T: {qself_str},\n{}",
1358 where_bounds.join(",\n"),
1359 ));
1360 let reported = err.emit();
1361 return Err(reported);
1362 }
1363 err.emit();
1364 }
1365
1366 Ok(bound)
1367 }
1368
1369 x;#[instrument(level = "debug", skip_all, ret)]
1396 pub fn lower_type_relative_ty_path(
1397 &self,
1398 self_ty: Ty<'tcx>,
1399 hir_self_ty: &'tcx hir::Ty<'tcx>,
1400 segment: &'tcx hir::PathSegment<'tcx>,
1401 qpath_hir_id: HirId,
1402 span: Span,
1403 permit_variants: PermitVariants,
1404 ) -> Result<(Ty<'tcx>, DefKind, DefId), ErrorGuaranteed> {
1405 let tcx = self.tcx();
1406 match self.lower_type_relative_path(
1407 self_ty,
1408 hir_self_ty,
1409 segment,
1410 qpath_hir_id,
1411 span,
1412 LowerTypeRelativePathMode::Type(permit_variants),
1413 )? {
1414 TypeRelativePath::AssocItem(def_id, args) => {
1415 let alias_ty = ty::AliasTy::new_from_args(tcx, def_id, args);
1416 let ty = Ty::new_alias(tcx, alias_ty.kind(tcx), alias_ty);
1417 let ty = self.check_param_uses_if_mcg(ty, span, false);
1418 Ok((ty, tcx.def_kind(def_id), def_id))
1419 }
1420 TypeRelativePath::Variant { adt, variant_did } => {
1421 let adt = self.check_param_uses_if_mcg(adt, span, false);
1422 Ok((adt, DefKind::Variant, variant_did))
1423 }
1424 TypeRelativePath::Ctor { .. } => {
1425 let e = tcx.dcx().span_err(span, "expected type, found tuple constructor");
1426 Err(e)
1427 }
1428 }
1429 }
1430
1431 x;#[instrument(level = "debug", skip_all, ret)]
1433 fn lower_type_relative_const_path(
1434 &self,
1435 self_ty: Ty<'tcx>,
1436 hir_self_ty: &'tcx hir::Ty<'tcx>,
1437 segment: &'tcx hir::PathSegment<'tcx>,
1438 qpath_hir_id: HirId,
1439 span: Span,
1440 ) -> Result<Const<'tcx>, ErrorGuaranteed> {
1441 let tcx = self.tcx();
1442 match self.lower_type_relative_path(
1443 self_ty,
1444 hir_self_ty,
1445 segment,
1446 qpath_hir_id,
1447 span,
1448 LowerTypeRelativePathMode::Const,
1449 )? {
1450 TypeRelativePath::AssocItem(def_id, args) => {
1451 self.require_type_const_attribute(def_id, span)?;
1452 let ct = Const::new_unevaluated(tcx, ty::UnevaluatedConst::new(def_id, args));
1453 let ct = self.check_param_uses_if_mcg(ct, span, false);
1454 Ok(ct)
1455 }
1456 TypeRelativePath::Ctor { ctor_def_id, args } => match tcx.def_kind(ctor_def_id) {
1457 DefKind::Ctor(_, CtorKind::Fn) => {
1458 Ok(ty::Const::zero_sized(tcx, Ty::new_fn_def(tcx, ctor_def_id, args)))
1459 }
1460 DefKind::Ctor(ctor_of, CtorKind::Const) => {
1461 Ok(self.construct_const_ctor_value(ctor_def_id, ctor_of, args))
1462 }
1463 _ => unreachable!(),
1464 },
1465 TypeRelativePath::Variant { .. } => {
1468 span_bug!(span, "unexpected variant res for type associated const path")
1469 }
1470 }
1471 }
1472
1473 x;#[instrument(level = "debug", skip_all, ret)]
1475 fn lower_type_relative_path(
1476 &self,
1477 self_ty: Ty<'tcx>,
1478 hir_self_ty: &'tcx hir::Ty<'tcx>,
1479 segment: &'tcx hir::PathSegment<'tcx>,
1480 qpath_hir_id: HirId,
1481 span: Span,
1482 mode: LowerTypeRelativePathMode,
1483 ) -> Result<TypeRelativePath<'tcx>, ErrorGuaranteed> {
1484 struct AmbiguousAssocItem<'tcx> {
1485 variant_def_id: DefId,
1486 item_def_id: DefId,
1487 span: Span,
1488 segment_ident: Ident,
1489 bound_def_id: DefId,
1490 self_ty: Ty<'tcx>,
1491 tcx: TyCtxt<'tcx>,
1492 mode: LowerTypeRelativePathMode,
1493 }
1494
1495 impl<'a, 'tcx> Diagnostic<'a, ()> for AmbiguousAssocItem<'tcx> {
1496 fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, ()> {
1497 let Self {
1498 variant_def_id,
1499 item_def_id,
1500 span,
1501 segment_ident,
1502 bound_def_id,
1503 self_ty,
1504 tcx,
1505 mode,
1506 } = self;
1507 let mut lint = Diag::new(dcx, level, "ambiguous associated item");
1508
1509 let mut could_refer_to = |kind: DefKind, def_id, also| {
1510 let note_msg = format!(
1511 "`{}` could{} refer to the {} defined here",
1512 segment_ident,
1513 also,
1514 tcx.def_kind_descr(kind, def_id)
1515 );
1516 lint.span_note(tcx.def_span(def_id), note_msg);
1517 };
1518
1519 could_refer_to(DefKind::Variant, variant_def_id, "");
1520 could_refer_to(mode.def_kind_for_diagnostics(), item_def_id, " also");
1521
1522 lint.span_suggestion(
1523 span,
1524 "use fully-qualified syntax",
1525 format!("<{} as {}>::{}", self_ty, tcx.item_name(bound_def_id), segment_ident),
1526 Applicability::MachineApplicable,
1527 );
1528 lint
1529 }
1530 }
1531
1532 debug!(%self_ty, ?segment.ident);
1533 let tcx = self.tcx();
1534
1535 let mut variant_def_id = None;
1537 if let Some(adt_def) = self.probe_adt(span, self_ty) {
1538 if adt_def.is_enum() {
1539 let variant_def = adt_def
1540 .variants()
1541 .iter()
1542 .find(|vd| tcx.hygienic_eq(segment.ident, vd.ident(tcx), adt_def.did()));
1543 if let Some(variant_def) = variant_def {
1544 if matches!(mode, LowerTypeRelativePathMode::Const)
1547 && let Some((_, ctor_def_id)) = variant_def.ctor
1548 {
1549 tcx.check_stability(variant_def.def_id, Some(qpath_hir_id), span, None);
1550 let _ = self.prohibit_generic_args(
1551 slice::from_ref(segment).iter(),
1552 GenericsArgsErrExtend::EnumVariant {
1553 qself: hir_self_ty,
1554 assoc_segment: segment,
1555 adt_def,
1556 },
1557 );
1558 let ty::Adt(_, enum_args) = self_ty.kind() else { unreachable!() };
1559 return Ok(TypeRelativePath::Ctor { ctor_def_id, args: enum_args });
1560 }
1561 if let PermitVariants::Yes = mode.permit_variants() {
1562 tcx.check_stability(variant_def.def_id, Some(qpath_hir_id), span, None);
1563 let _ = self.prohibit_generic_args(
1564 slice::from_ref(segment).iter(),
1565 GenericsArgsErrExtend::EnumVariant {
1566 qself: hir_self_ty,
1567 assoc_segment: segment,
1568 adt_def,
1569 },
1570 );
1571 return Ok(TypeRelativePath::Variant {
1572 adt: self_ty,
1573 variant_did: variant_def.def_id,
1574 });
1575 } else {
1576 variant_def_id = Some(variant_def.def_id);
1577 }
1578 }
1579 }
1580
1581 if let Some((did, args)) = self.probe_inherent_assoc_item(
1583 segment,
1584 adt_def.did(),
1585 self_ty,
1586 qpath_hir_id,
1587 span,
1588 mode.assoc_tag(),
1589 )? {
1590 return Ok(TypeRelativePath::AssocItem(did, args));
1591 }
1592 }
1593
1594 let (item_def_id, bound) = self.resolve_type_relative_path(
1595 self_ty,
1596 hir_self_ty,
1597 mode.assoc_tag(),
1598 segment,
1599 qpath_hir_id,
1600 span,
1601 variant_def_id,
1602 )?;
1603
1604 let (item_def_id, args) = self.lower_assoc_item_path(span, item_def_id, segment, bound)?;
1605
1606 if let Some(variant_def_id) = variant_def_id {
1607 tcx.emit_node_span_lint(
1608 AMBIGUOUS_ASSOCIATED_ITEMS,
1609 qpath_hir_id,
1610 span,
1611 AmbiguousAssocItem {
1612 variant_def_id,
1613 item_def_id,
1614 span,
1615 segment_ident: segment.ident,
1616 bound_def_id: bound.def_id(),
1617 self_ty,
1618 tcx,
1619 mode,
1620 },
1621 );
1622 }
1623
1624 Ok(TypeRelativePath::AssocItem(item_def_id, args))
1625 }
1626
1627 fn resolve_type_relative_path(
1629 &self,
1630 self_ty: Ty<'tcx>,
1631 hir_self_ty: &'tcx hir::Ty<'tcx>,
1632 assoc_tag: ty::AssocTag,
1633 segment: &'tcx hir::PathSegment<'tcx>,
1634 qpath_hir_id: HirId,
1635 span: Span,
1636 variant_def_id: Option<DefId>,
1637 ) -> Result<(DefId, ty::PolyTraitRef<'tcx>), ErrorGuaranteed> {
1638 let tcx = self.tcx();
1639
1640 let self_ty_res = match hir_self_ty.kind {
1641 hir::TyKind::Path(hir::QPath::Resolved(_, path)) => path.res,
1642 _ => Res::Err,
1643 };
1644
1645 let bound = match (self_ty.kind(), self_ty_res) {
1647 (_, Res::SelfTyAlias { alias_to: impl_def_id, is_trait_impl: true, .. }) => {
1648 let trait_ref = tcx.impl_trait_ref(impl_def_id);
1651
1652 self.probe_single_bound_for_assoc_item(
1653 || {
1654 let trait_ref = ty::Binder::dummy(trait_ref.instantiate_identity());
1655 traits::supertraits(tcx, trait_ref)
1656 },
1657 AssocItemQSelf::SelfTyAlias,
1658 assoc_tag,
1659 segment.ident,
1660 span,
1661 None,
1662 )?
1663 }
1664 (
1665 &ty::Param(_),
1666 Res::SelfTyParam { trait_: param_did } | Res::Def(DefKind::TyParam, param_did),
1667 ) => self.probe_single_ty_param_bound_for_assoc_item(
1668 param_did.expect_local(),
1669 hir_self_ty.span,
1670 assoc_tag,
1671 segment.ident,
1672 span,
1673 )?,
1674 _ => {
1675 return Err(self.report_unresolved_type_relative_path(
1676 self_ty,
1677 hir_self_ty,
1678 assoc_tag,
1679 segment.ident,
1680 qpath_hir_id,
1681 span,
1682 variant_def_id,
1683 ));
1684 }
1685 };
1686
1687 let assoc_item = self
1688 .probe_assoc_item(segment.ident, assoc_tag, qpath_hir_id, span, bound.def_id())
1689 .expect("failed to find associated item");
1690
1691 Ok((assoc_item.def_id, bound))
1692 }
1693
1694 fn probe_inherent_assoc_item(
1696 &self,
1697 segment: &hir::PathSegment<'tcx>,
1698 adt_did: DefId,
1699 self_ty: Ty<'tcx>,
1700 block: HirId,
1701 span: Span,
1702 assoc_tag: ty::AssocTag,
1703 ) -> Result<Option<(DefId, GenericArgsRef<'tcx>)>, ErrorGuaranteed> {
1704 let tcx = self.tcx();
1705
1706 if !tcx.features().inherent_associated_types() {
1707 match assoc_tag {
1708 ty::AssocTag::Type => return Ok(None),
1713 ty::AssocTag::Const => {
1714 return Err(feature_err(
1718 &tcx.sess,
1719 sym::inherent_associated_types,
1720 span,
1721 "inherent associated types are unstable",
1722 )
1723 .emit());
1724 }
1725 ty::AssocTag::Fn => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1726 }
1727 }
1728
1729 let name = segment.ident;
1730 let candidates: Vec<_> = tcx
1731 .inherent_impls(adt_did)
1732 .iter()
1733 .filter_map(|&impl_| {
1734 let (item, scope) =
1735 self.probe_assoc_item_unchecked(name, assoc_tag, block, impl_)?;
1736 Some(InherentAssocCandidate { impl_, assoc_item: item.def_id, scope })
1737 })
1738 .collect();
1739
1740 if candidates.is_empty() {
1745 return Ok(None);
1746 }
1747
1748 let (applicable_candidates, fulfillment_errors) =
1749 self.select_inherent_assoc_candidates(span, self_ty, candidates.clone());
1750
1751 let InherentAssocCandidate { impl_, assoc_item, scope: def_scope } =
1753 match &applicable_candidates[..] {
1754 &[] => Err(self.report_unresolved_inherent_assoc_item(
1755 name,
1756 self_ty,
1757 candidates,
1758 fulfillment_errors,
1759 span,
1760 assoc_tag,
1761 )),
1762
1763 &[applicable_candidate] => Ok(applicable_candidate),
1764
1765 &[_, ..] => Err(self.report_ambiguous_inherent_assoc_item(
1766 name,
1767 candidates.into_iter().map(|cand| cand.assoc_item).collect(),
1768 span,
1769 )),
1770 }?;
1771
1772 self.check_assoc_item(assoc_item, name, def_scope, block, span);
1775
1776 let parent_args = ty::GenericArgs::identity_for_item(tcx, impl_);
1780 let args = self.lower_generic_args_of_assoc_item(span, assoc_item, segment, parent_args);
1781 let args = tcx.mk_args_from_iter(
1782 std::iter::once(ty::GenericArg::from(self_ty))
1783 .chain(args.into_iter().skip(parent_args.len())),
1784 );
1785
1786 Ok(Some((assoc_item, args)))
1787 }
1788
1789 fn probe_assoc_item(
1793 &self,
1794 ident: Ident,
1795 assoc_tag: ty::AssocTag,
1796 block: HirId,
1797 span: Span,
1798 scope: DefId,
1799 ) -> Option<ty::AssocItem> {
1800 let (item, scope) = self.probe_assoc_item_unchecked(ident, assoc_tag, block, scope)?;
1801 self.check_assoc_item(item.def_id, ident, scope, block, span);
1802 Some(item)
1803 }
1804
1805 fn probe_assoc_item_unchecked(
1810 &self,
1811 ident: Ident,
1812 assoc_tag: ty::AssocTag,
1813 block: HirId,
1814 scope: DefId,
1815 ) -> Option<(ty::AssocItem, DefId)> {
1816 let tcx = self.tcx();
1817
1818 let (ident, def_scope) = tcx.adjust_ident_and_get_scope(ident, scope, block);
1819 let item = tcx
1823 .associated_items(scope)
1824 .filter_by_name_unhygienic(ident.name)
1825 .find(|i| i.tag() == assoc_tag && i.ident(tcx).normalize_to_macros_2_0() == ident)?;
1826
1827 Some((*item, def_scope))
1828 }
1829
1830 fn check_assoc_item(
1832 &self,
1833 item_def_id: DefId,
1834 ident: Ident,
1835 scope: DefId,
1836 block: HirId,
1837 span: Span,
1838 ) {
1839 let tcx = self.tcx();
1840
1841 if !tcx.visibility(item_def_id).is_accessible_from(scope, tcx) {
1842 self.dcx().emit_err(crate::errors::AssocItemIsPrivate {
1843 span,
1844 kind: tcx.def_descr(item_def_id),
1845 name: ident,
1846 defined_here_label: tcx.def_span(item_def_id),
1847 });
1848 }
1849
1850 tcx.check_stability(item_def_id, Some(block), span, None);
1851 }
1852
1853 fn probe_traits_that_match_assoc_ty(
1854 &self,
1855 qself_ty: Ty<'tcx>,
1856 assoc_ident: Ident,
1857 ) -> Vec<String> {
1858 let tcx = self.tcx();
1859
1860 let infcx_;
1863 let infcx = if let Some(infcx) = self.infcx() {
1864 infcx
1865 } else {
1866 if !!qself_ty.has_infer() {
::core::panicking::panic("assertion failed: !qself_ty.has_infer()")
};assert!(!qself_ty.has_infer());
1867 infcx_ = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
1868 &infcx_
1869 };
1870
1871 tcx.all_traits_including_private()
1872 .filter(|trait_def_id| {
1873 tcx.associated_items(*trait_def_id)
1875 .in_definition_order()
1876 .any(|i| {
1877 i.is_type()
1878 && !i.is_impl_trait_in_trait()
1879 && i.ident(tcx).normalize_to_macros_2_0() == assoc_ident
1880 })
1881 && tcx.visibility(*trait_def_id)
1883 .is_accessible_from(self.item_def_id(), tcx)
1884 && tcx.all_impls(*trait_def_id)
1885 .any(|impl_def_id| {
1886 let header = tcx.impl_trait_header(impl_def_id);
1887 let trait_ref = header.trait_ref.instantiate(
1888 tcx,
1889 infcx.fresh_args_for_item(DUMMY_SP, impl_def_id),
1890 );
1891
1892 let value = fold_regions(tcx, qself_ty, |_, _| tcx.lifetimes.re_erased);
1893 if value.has_escaping_bound_vars() {
1895 return false;
1896 }
1897 infcx
1898 .can_eq(
1899 ty::ParamEnv::empty(),
1900 trait_ref.self_ty(),
1901 value,
1902 ) && header.polarity != ty::ImplPolarity::Negative
1903 })
1904 })
1905 .map(|trait_def_id| tcx.def_path_str(trait_def_id))
1906 .collect()
1907 }
1908
1909 #[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(1910u32),
::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)]
1911 fn lower_resolved_assoc_ty_path(
1912 &self,
1913 span: Span,
1914 opt_self_ty: Option<Ty<'tcx>>,
1915 item_def_id: DefId,
1916 trait_segment: Option<&hir::PathSegment<'tcx>>,
1917 item_segment: &hir::PathSegment<'tcx>,
1918 ) -> Ty<'tcx> {
1919 match self.lower_resolved_assoc_item_path(
1920 span,
1921 opt_self_ty,
1922 item_def_id,
1923 trait_segment,
1924 item_segment,
1925 ty::AssocTag::Type,
1926 ) {
1927 Ok((item_def_id, item_args)) => {
1928 Ty::new_projection_from_args(self.tcx(), item_def_id, item_args)
1929 }
1930 Err(guar) => Ty::new_error(self.tcx(), guar),
1931 }
1932 }
1933
1934 #[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(1935u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&[],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{ meta.fields().value_set(&[]) })
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return:
Result<Const<'tcx>, ErrorGuaranteed> = loop {};
return __tracing_attr_fake_return;
}
{
let (item_def_id, item_args) =
self.lower_resolved_assoc_item_path(span, opt_self_ty,
item_def_id, trait_segment, item_segment,
ty::AssocTag::Const)?;
self.require_type_const_attribute(item_def_id, span)?;
let uv = ty::UnevaluatedConst::new(item_def_id, item_args);
Ok(Const::new_unevaluated(self.tcx(), uv))
}
}
}#[instrument(level = "debug", skip_all)]
1936 fn lower_resolved_assoc_const_path(
1937 &self,
1938 span: Span,
1939 opt_self_ty: Option<Ty<'tcx>>,
1940 item_def_id: DefId,
1941 trait_segment: Option<&hir::PathSegment<'tcx>>,
1942 item_segment: &hir::PathSegment<'tcx>,
1943 ) -> Result<Const<'tcx>, ErrorGuaranteed> {
1944 let (item_def_id, item_args) = self.lower_resolved_assoc_item_path(
1945 span,
1946 opt_self_ty,
1947 item_def_id,
1948 trait_segment,
1949 item_segment,
1950 ty::AssocTag::Const,
1951 )?;
1952 self.require_type_const_attribute(item_def_id, span)?;
1953 let uv = ty::UnevaluatedConst::new(item_def_id, item_args);
1954 Ok(Const::new_unevaluated(self.tcx(), uv))
1955 }
1956
1957 #[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(1958u32),
::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:1971",
"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(1971u32),
::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:1981",
"rustc_hir_analysis::hir_ty_lowering",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs"),
::tracing_core::__macro_support::Option::Some(1981u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&["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:1985",
"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(1985u32),
::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)]
1959 fn lower_resolved_assoc_item_path(
1960 &self,
1961 span: Span,
1962 opt_self_ty: Option<Ty<'tcx>>,
1963 item_def_id: DefId,
1964 trait_segment: Option<&hir::PathSegment<'tcx>>,
1965 item_segment: &hir::PathSegment<'tcx>,
1966 assoc_tag: ty::AssocTag,
1967 ) -> Result<(DefId, GenericArgsRef<'tcx>), ErrorGuaranteed> {
1968 let tcx = self.tcx();
1969
1970 let trait_def_id = tcx.parent(item_def_id);
1971 debug!(?trait_def_id);
1972
1973 let Some(self_ty) = opt_self_ty else {
1974 return Err(self.report_missing_self_ty_for_resolved_path(
1975 trait_def_id,
1976 span,
1977 item_segment,
1978 assoc_tag,
1979 ));
1980 };
1981 debug!(?self_ty);
1982
1983 let trait_ref =
1984 self.lower_mono_trait_ref(span, trait_def_id, self_ty, trait_segment.unwrap(), false);
1985 debug!(?trait_ref);
1986
1987 let item_args =
1988 self.lower_generic_args_of_assoc_item(span, item_def_id, item_segment, trait_ref.args);
1989
1990 Ok((item_def_id, item_args))
1991 }
1992
1993 pub fn prohibit_generic_args<'a>(
1994 &self,
1995 segments: impl Iterator<Item = &'a hir::PathSegment<'a>> + Clone,
1996 err_extend: GenericsArgsErrExtend<'a>,
1997 ) -> Result<(), ErrorGuaranteed> {
1998 let args_visitors = segments.clone().flat_map(|segment| segment.args().args);
1999 let mut result = Ok(());
2000 if let Some(_) = args_visitors.clone().next() {
2001 result = Err(self.report_prohibited_generic_args(
2002 segments.clone(),
2003 args_visitors,
2004 err_extend,
2005 ));
2006 }
2007
2008 for segment in segments {
2009 if let Some(c) = segment.args().constraints.first() {
2011 return Err(prohibit_assoc_item_constraint(self, c, None));
2012 }
2013 }
2014
2015 result
2016 }
2017
2018 pub fn probe_generic_path_segments(
2036 &self,
2037 segments: &[hir::PathSegment<'_>],
2038 self_ty: Option<Ty<'tcx>>,
2039 kind: DefKind,
2040 def_id: DefId,
2041 span: Span,
2042 ) -> Vec<GenericPathSegment> {
2043 let tcx = self.tcx();
2089
2090 if !!segments.is_empty() {
::core::panicking::panic("assertion failed: !segments.is_empty()")
};assert!(!segments.is_empty());
2091 let last = segments.len() - 1;
2092
2093 let mut generic_segments = ::alloc::vec::Vec::new()vec![];
2094
2095 match kind {
2096 DefKind::Ctor(CtorOf::Struct, ..) => {
2098 let generics = tcx.generics_of(def_id);
2101 let generics_def_id = generics.parent.unwrap_or(def_id);
2104 generic_segments.push(GenericPathSegment(generics_def_id, last));
2105 }
2106
2107 DefKind::Ctor(CtorOf::Variant, ..) | DefKind::Variant => {
2109 let (generics_def_id, index) = if let Some(self_ty) = self_ty {
2110 let adt_def = self.probe_adt(span, self_ty).unwrap();
2111 if true {
if !adt_def.is_enum() {
::core::panicking::panic("assertion failed: adt_def.is_enum()")
};
};debug_assert!(adt_def.is_enum());
2112 (adt_def.did(), last)
2113 } else if last >= 1 && segments[last - 1].args.is_some() {
2114 let mut def_id = def_id;
2117
2118 if let DefKind::Ctor(..) = kind {
2120 def_id = tcx.parent(def_id);
2121 }
2122
2123 let enum_def_id = tcx.parent(def_id);
2125 (enum_def_id, last - 1)
2126 } else {
2127 let generics = tcx.generics_of(def_id);
2133 (generics.parent.unwrap_or(def_id), last)
2136 };
2137 generic_segments.push(GenericPathSegment(generics_def_id, index));
2138 }
2139
2140 DefKind::Fn | DefKind::Const { .. } | DefKind::ConstParam | DefKind::Static { .. } => {
2142 generic_segments.push(GenericPathSegment(def_id, last));
2143 }
2144
2145 DefKind::AssocFn | DefKind::AssocConst { .. } => {
2147 if segments.len() >= 2 {
2148 let generics = tcx.generics_of(def_id);
2149 generic_segments.push(GenericPathSegment(generics.parent.unwrap(), last - 1));
2150 }
2151 generic_segments.push(GenericPathSegment(def_id, last));
2152 }
2153
2154 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),
2155 }
2156
2157 {
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:2157",
"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(2157u32),
::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);
2158
2159 generic_segments
2160 }
2161
2162 #[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(2163u32),
::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:2171",
"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(2171u32),
::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)]
2164 pub fn lower_resolved_ty_path(
2165 &self,
2166 opt_self_ty: Option<Ty<'tcx>>,
2167 path: &hir::Path<'tcx>,
2168 hir_id: HirId,
2169 permit_variants: PermitVariants,
2170 ) -> Ty<'tcx> {
2171 debug!(?path.res, ?opt_self_ty, ?path.segments);
2172 let tcx = self.tcx();
2173
2174 let span = path.span;
2175 match path.res {
2176 Res::Def(DefKind::OpaqueTy, did) => {
2177 assert_matches!(tcx.opaque_ty_origin(did), hir::OpaqueTyOrigin::TyAlias { .. });
2179 let [leading_segments @ .., segment] = path.segments else { bug!() };
2180 let _ = self.prohibit_generic_args(
2181 leading_segments.iter(),
2182 GenericsArgsErrExtend::OpaqueTy,
2183 );
2184 let args = self.lower_generic_args_of_path_segment(span, did, segment);
2185 Ty::new_opaque(tcx, did, args)
2186 }
2187 Res::Def(
2188 DefKind::Enum
2189 | DefKind::TyAlias
2190 | DefKind::Struct
2191 | DefKind::Union
2192 | DefKind::ForeignTy,
2193 did,
2194 ) => {
2195 assert_eq!(opt_self_ty, None);
2196 let [leading_segments @ .., segment] = path.segments else { bug!() };
2197 let _ = self
2198 .prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
2199 self.lower_path_segment(span, did, segment)
2200 }
2201 Res::Def(kind @ DefKind::Variant, def_id)
2202 if let PermitVariants::Yes = permit_variants =>
2203 {
2204 assert_eq!(opt_self_ty, None);
2207
2208 let generic_segments =
2209 self.probe_generic_path_segments(path.segments, None, kind, def_id, span);
2210 let indices: FxHashSet<_> =
2211 generic_segments.iter().map(|GenericPathSegment(_, index)| index).collect();
2212 let _ = self.prohibit_generic_args(
2213 path.segments.iter().enumerate().filter_map(|(index, seg)| {
2214 if !indices.contains(&index) { Some(seg) } else { None }
2215 }),
2216 GenericsArgsErrExtend::DefVariant(&path.segments),
2217 );
2218
2219 let &GenericPathSegment(def_id, index) = generic_segments.last().unwrap();
2220 self.lower_path_segment(span, def_id, &path.segments[index])
2221 }
2222 Res::Def(DefKind::TyParam, def_id) => {
2223 assert_eq!(opt_self_ty, None);
2224 let _ = self.prohibit_generic_args(
2225 path.segments.iter(),
2226 GenericsArgsErrExtend::Param(def_id),
2227 );
2228 self.lower_ty_param(hir_id)
2229 }
2230 Res::SelfTyParam { .. } => {
2231 assert_eq!(opt_self_ty, None);
2233 let _ = self.prohibit_generic_args(
2234 path.segments.iter(),
2235 if let [hir::PathSegment { args: Some(args), ident, .. }] = &path.segments {
2236 GenericsArgsErrExtend::SelfTyParam(
2237 ident.span.shrink_to_hi().to(args.span_ext),
2238 )
2239 } else {
2240 GenericsArgsErrExtend::None
2241 },
2242 );
2243 self.check_param_uses_if_mcg(tcx.types.self_param, span, false)
2244 }
2245 Res::SelfTyAlias { alias_to: def_id, .. } => {
2246 assert_eq!(opt_self_ty, None);
2248 let ty = tcx.at(span).type_of(def_id).instantiate_identity();
2250 let _ = self.prohibit_generic_args(
2251 path.segments.iter(),
2252 GenericsArgsErrExtend::SelfTyAlias { def_id, span },
2253 );
2254 self.check_param_uses_if_mcg(ty, span, true)
2255 }
2256 Res::Def(DefKind::AssocTy, def_id) => {
2257 let trait_segment = if let [modules @ .., trait_, _item] = path.segments {
2258 let _ = self.prohibit_generic_args(modules.iter(), GenericsArgsErrExtend::None);
2259 Some(trait_)
2260 } else {
2261 None
2262 };
2263 self.lower_resolved_assoc_ty_path(
2264 span,
2265 opt_self_ty,
2266 def_id,
2267 trait_segment,
2268 path.segments.last().unwrap(),
2269 )
2270 }
2271 Res::PrimTy(prim_ty) => {
2272 assert_eq!(opt_self_ty, None);
2273 let _ = self.prohibit_generic_args(
2274 path.segments.iter(),
2275 GenericsArgsErrExtend::PrimTy(prim_ty),
2276 );
2277 match prim_ty {
2278 hir::PrimTy::Bool => tcx.types.bool,
2279 hir::PrimTy::Char => tcx.types.char,
2280 hir::PrimTy::Int(it) => Ty::new_int(tcx, it),
2281 hir::PrimTy::Uint(uit) => Ty::new_uint(tcx, uit),
2282 hir::PrimTy::Float(ft) => Ty::new_float(tcx, ft),
2283 hir::PrimTy::Str => tcx.types.str_,
2284 }
2285 }
2286 Res::Err => {
2287 let e = self
2288 .tcx()
2289 .dcx()
2290 .span_delayed_bug(path.span, "path with `Res::Err` but no error emitted");
2291 Ty::new_error(tcx, e)
2292 }
2293 Res::Def(..) => {
2294 assert_eq!(
2295 path.segments.get(0).map(|seg| seg.ident.name),
2296 Some(kw::SelfUpper),
2297 "only expected incorrect resolution for `Self`"
2298 );
2299 Ty::new_error(
2300 self.tcx(),
2301 self.dcx().span_delayed_bug(span, "incorrect resolution for `Self`"),
2302 )
2303 }
2304 _ => span_bug!(span, "unexpected resolution: {:?}", path.res),
2305 }
2306 }
2307
2308 pub(crate) fn lower_ty_param(&self, hir_id: HirId) -> Ty<'tcx> {
2313 let tcx = self.tcx();
2314
2315 let ty = match tcx.named_bound_var(hir_id) {
2316 Some(rbv::ResolvedArg::LateBound(debruijn, index, def_id)) => {
2317 let br = ty::BoundTy {
2318 var: ty::BoundVar::from_u32(index),
2319 kind: ty::BoundTyKind::Param(def_id.to_def_id()),
2320 };
2321 Ty::new_bound(tcx, debruijn, br)
2322 }
2323 Some(rbv::ResolvedArg::EarlyBound(def_id)) => {
2324 let item_def_id = tcx.hir_ty_param_owner(def_id);
2325 let generics = tcx.generics_of(item_def_id);
2326 let index = generics.param_def_id_to_index[&def_id.to_def_id()];
2327 Ty::new_param(tcx, index, tcx.hir_ty_param_name(def_id))
2328 }
2329 Some(rbv::ResolvedArg::Error(guar)) => Ty::new_error(tcx, guar),
2330 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:?}"),
2331 };
2332 self.check_param_uses_if_mcg(ty, tcx.hir_span(hir_id), false)
2333 }
2334
2335 pub(crate) fn lower_const_param(&self, param_def_id: DefId, path_hir_id: HirId) -> Const<'tcx> {
2340 let tcx = self.tcx();
2341
2342 let ct = match tcx.named_bound_var(path_hir_id) {
2343 Some(rbv::ResolvedArg::EarlyBound(_)) => {
2344 let item_def_id = tcx.parent(param_def_id);
2347 let generics = tcx.generics_of(item_def_id);
2348 let index = generics.param_def_id_to_index[¶m_def_id];
2349 let name = tcx.item_name(param_def_id);
2350 ty::Const::new_param(tcx, ty::ParamConst::new(index, name))
2351 }
2352 Some(rbv::ResolvedArg::LateBound(debruijn, index, _)) => ty::Const::new_bound(
2353 tcx,
2354 debruijn,
2355 ty::BoundConst::new(ty::BoundVar::from_u32(index)),
2356 ),
2357 Some(rbv::ResolvedArg::Error(guar)) => ty::Const::new_error(tcx, guar),
2358 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),
2359 };
2360 self.check_param_uses_if_mcg(ct, tcx.hir_span(path_hir_id), false)
2361 }
2362
2363 #[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(2364u32),
::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:2416",
"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(2416u32),
::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:2421",
"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(2421u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&["hir_self_ty",
"segment"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&hir_self_ty)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&segment) as
&dyn Value))])
});
} else { ; }
};
let self_ty = self.lower_ty(hir_self_ty);
self.lower_type_relative_const_path(self_ty, hir_self_ty,
segment, hir_id,
const_arg.span).unwrap_or_else(|guar|
Const::new_error(tcx, guar))
}
hir::ConstArgKind::Struct(qpath, inits) => {
self.lower_const_arg_struct(hir_id, qpath, inits,
const_arg.span)
}
hir::ConstArgKind::TupleCall(qpath, args) => {
self.lower_const_arg_tuple_call(hir_id, qpath, args,
const_arg.span)
}
hir::ConstArgKind::Array(array_expr) =>
self.lower_const_arg_array(array_expr, ty),
hir::ConstArgKind::Anon(anon) =>
self.lower_const_arg_anon(anon),
hir::ConstArgKind::Infer(()) =>
self.ct_infer(None, const_arg.span),
hir::ConstArgKind::Error(e) => ty::Const::new_error(tcx, e),
hir::ConstArgKind::Literal { lit, negated } => {
self.lower_const_arg_literal(&lit, negated, ty,
const_arg.span)
}
}
}
}
}#[instrument(skip(self), level = "debug")]
2365 pub fn lower_const_arg(&self, const_arg: &hir::ConstArg<'tcx>, ty: Ty<'tcx>) -> Const<'tcx> {
2366 let tcx = self.tcx();
2367
2368 if let hir::ConstArgKind::Anon(anon) = &const_arg.kind {
2369 if tcx.features().generic_const_parameter_types()
2378 && (ty.has_free_regions() || ty.has_erased_regions())
2379 {
2380 let e = self.dcx().span_err(
2381 const_arg.span,
2382 "anonymous constants with lifetimes in their type are not yet supported",
2383 );
2384 tcx.feed_anon_const_type(anon.def_id, ty::EarlyBinder::bind(Ty::new_error(tcx, e)));
2385 return ty::Const::new_error(tcx, e);
2386 }
2387 if ty.has_non_region_infer() {
2391 let e = self.dcx().span_err(
2392 const_arg.span,
2393 "anonymous constants with inferred types are not yet supported",
2394 );
2395 tcx.feed_anon_const_type(anon.def_id, ty::EarlyBinder::bind(Ty::new_error(tcx, e)));
2396 return ty::Const::new_error(tcx, e);
2397 }
2398 if ty.has_non_region_param() {
2401 let e = self.dcx().span_err(
2402 const_arg.span,
2403 "anonymous constants referencing generics are not yet supported",
2404 );
2405 tcx.feed_anon_const_type(anon.def_id, ty::EarlyBinder::bind(Ty::new_error(tcx, e)));
2406 return ty::Const::new_error(tcx, e);
2407 }
2408
2409 tcx.feed_anon_const_type(anon.def_id, ty::EarlyBinder::bind(ty));
2410 }
2411
2412 let hir_id = const_arg.hir_id;
2413 match const_arg.kind {
2414 hir::ConstArgKind::Tup(exprs) => self.lower_const_arg_tup(exprs, ty, const_arg.span),
2415 hir::ConstArgKind::Path(hir::QPath::Resolved(maybe_qself, path)) => {
2416 debug!(?maybe_qself, ?path);
2417 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
2418 self.lower_resolved_const_path(opt_self_ty, path, hir_id)
2419 }
2420 hir::ConstArgKind::Path(hir::QPath::TypeRelative(hir_self_ty, segment)) => {
2421 debug!(?hir_self_ty, ?segment);
2422 let self_ty = self.lower_ty(hir_self_ty);
2423 self.lower_type_relative_const_path(
2424 self_ty,
2425 hir_self_ty,
2426 segment,
2427 hir_id,
2428 const_arg.span,
2429 )
2430 .unwrap_or_else(|guar| Const::new_error(tcx, guar))
2431 }
2432 hir::ConstArgKind::Struct(qpath, inits) => {
2433 self.lower_const_arg_struct(hir_id, qpath, inits, const_arg.span)
2434 }
2435 hir::ConstArgKind::TupleCall(qpath, args) => {
2436 self.lower_const_arg_tuple_call(hir_id, qpath, args, const_arg.span)
2437 }
2438 hir::ConstArgKind::Array(array_expr) => self.lower_const_arg_array(array_expr, ty),
2439 hir::ConstArgKind::Anon(anon) => self.lower_const_arg_anon(anon),
2440 hir::ConstArgKind::Infer(()) => self.ct_infer(None, const_arg.span),
2441 hir::ConstArgKind::Error(e) => ty::Const::new_error(tcx, e),
2442 hir::ConstArgKind::Literal { lit, negated } => {
2443 self.lower_const_arg_literal(&lit, negated, ty, const_arg.span)
2444 }
2445 }
2446 }
2447
2448 fn lower_const_arg_array(
2449 &self,
2450 array_expr: &'tcx hir::ConstArgArrayExpr<'tcx>,
2451 ty: Ty<'tcx>,
2452 ) -> Const<'tcx> {
2453 let tcx = self.tcx();
2454
2455 let elem_ty = match ty.kind() {
2456 ty::Array(elem_ty, _) => elem_ty,
2457 ty::Error(e) => return Const::new_error(tcx, *e),
2458 _ => {
2459 let e = tcx
2460 .dcx()
2461 .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));
2462 return Const::new_error(tcx, e);
2463 }
2464 };
2465
2466 let elems = array_expr
2467 .elems
2468 .iter()
2469 .map(|elem| self.lower_const_arg(elem, *elem_ty))
2470 .collect::<Vec<_>>();
2471
2472 let valtree = ty::ValTree::from_branches(tcx, elems);
2473
2474 ty::Const::new_value(tcx, valtree, ty)
2475 }
2476
2477 fn lower_const_arg_tuple_call(
2478 &self,
2479 hir_id: HirId,
2480 qpath: hir::QPath<'tcx>,
2481 args: &'tcx [&'tcx hir::ConstArg<'tcx>],
2482 span: Span,
2483 ) -> Const<'tcx> {
2484 let tcx = self.tcx();
2485
2486 let non_adt_or_variant_res = || {
2487 let e = tcx.dcx().span_err(span, "tuple constructor with invalid base path");
2488 ty::Const::new_error(tcx, e)
2489 };
2490
2491 let ctor_const = match qpath {
2492 hir::QPath::Resolved(maybe_qself, path) => {
2493 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
2494 self.lower_resolved_const_path(opt_self_ty, path, hir_id)
2495 }
2496 hir::QPath::TypeRelative(hir_self_ty, segment) => {
2497 let self_ty = self.lower_ty(hir_self_ty);
2498 match self.lower_type_relative_const_path(
2499 self_ty,
2500 hir_self_ty,
2501 segment,
2502 hir_id,
2503 span,
2504 ) {
2505 Ok(c) => c,
2506 Err(_) => return non_adt_or_variant_res(),
2507 }
2508 }
2509 };
2510
2511 let Some(value) = ctor_const.try_to_value() else {
2512 return non_adt_or_variant_res();
2513 };
2514
2515 let (adt_def, adt_args, variant_did) = match value.ty.kind() {
2516 ty::FnDef(def_id, fn_args)
2517 if let DefKind::Ctor(CtorOf::Variant, _) = tcx.def_kind(*def_id) =>
2518 {
2519 let parent_did = tcx.parent(*def_id);
2520 let enum_did = tcx.parent(parent_did);
2521 (tcx.adt_def(enum_did), fn_args, parent_did)
2522 }
2523 ty::FnDef(def_id, fn_args)
2524 if let DefKind::Ctor(CtorOf::Struct, _) = tcx.def_kind(*def_id) =>
2525 {
2526 let parent_did = tcx.parent(*def_id);
2527 (tcx.adt_def(parent_did), fn_args, parent_did)
2528 }
2529 _ => {
2530 let e = self.dcx().span_err(
2531 span,
2532 "complex const arguments must be placed inside of a `const` block",
2533 );
2534 return Const::new_error(tcx, e);
2535 }
2536 };
2537
2538 let variant_def = adt_def.variant_with_id(variant_did);
2539 let variant_idx = adt_def.variant_index_with_id(variant_did).as_u32();
2540
2541 if args.len() != variant_def.fields.len() {
2542 let e = tcx.dcx().span_err(
2543 span,
2544 ::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!(
2545 "tuple constructor has {} arguments but {} were provided",
2546 variant_def.fields.len(),
2547 args.len()
2548 ),
2549 );
2550 return ty::Const::new_error(tcx, e);
2551 }
2552
2553 let fields = variant_def
2554 .fields
2555 .iter()
2556 .zip(args)
2557 .map(|(field_def, arg)| {
2558 self.lower_const_arg(arg, tcx.type_of(field_def.did).instantiate(tcx, adt_args))
2559 })
2560 .collect::<Vec<_>>();
2561
2562 let opt_discr_const = if adt_def.is_enum() {
2563 let valtree = ty::ValTree::from_scalar_int(tcx, variant_idx.into());
2564 Some(ty::Const::new_value(tcx, valtree, tcx.types.u32))
2565 } else {
2566 None
2567 };
2568
2569 let valtree = ty::ValTree::from_branches(tcx, opt_discr_const.into_iter().chain(fields));
2570 let adt_ty = Ty::new_adt(tcx, adt_def, adt_args);
2571 ty::Const::new_value(tcx, valtree, adt_ty)
2572 }
2573
2574 fn lower_const_arg_tup(
2575 &self,
2576 exprs: &'tcx [&'tcx hir::ConstArg<'tcx>],
2577 ty: Ty<'tcx>,
2578 span: Span,
2579 ) -> Const<'tcx> {
2580 let tcx = self.tcx();
2581
2582 let tys = match ty.kind() {
2583 ty::Tuple(tys) => tys,
2584 ty::Error(e) => return Const::new_error(tcx, *e),
2585 _ => {
2586 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));
2587 return Const::new_error(tcx, e);
2588 }
2589 };
2590
2591 let exprs = exprs
2592 .iter()
2593 .zip(tys.iter())
2594 .map(|(expr, ty)| self.lower_const_arg(expr, ty))
2595 .collect::<Vec<_>>();
2596
2597 let valtree = ty::ValTree::from_branches(tcx, exprs);
2598 ty::Const::new_value(tcx, valtree, ty)
2599 }
2600
2601 fn lower_const_arg_struct(
2602 &self,
2603 hir_id: HirId,
2604 qpath: hir::QPath<'tcx>,
2605 inits: &'tcx [&'tcx hir::ConstArgExprField<'tcx>],
2606 span: Span,
2607 ) -> Const<'tcx> {
2608 let tcx = self.tcx();
2611
2612 let non_adt_or_variant_res = || {
2613 let e = tcx.dcx().span_err(span, "struct expression with invalid base path");
2614 ty::Const::new_error(tcx, e)
2615 };
2616
2617 let (ty, variant_did) = match qpath {
2618 hir::QPath::Resolved(maybe_qself, path) => {
2619 {
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:2619",
"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(2619u32),
::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);
2620 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
2621 let ty =
2622 self.lower_resolved_ty_path(opt_self_ty, path, hir_id, PermitVariants::Yes);
2623 let variant_did = match path.res {
2624 Res::Def(DefKind::Variant | DefKind::Struct, did) => did,
2625 _ => return non_adt_or_variant_res(),
2626 };
2627
2628 (ty, variant_did)
2629 }
2630 hir::QPath::TypeRelative(hir_self_ty, segment) => {
2631 {
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:2631",
"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(2631u32),
::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);
2632 let self_ty = self.lower_ty(hir_self_ty);
2633 let opt_res = self.lower_type_relative_ty_path(
2634 self_ty,
2635 hir_self_ty,
2636 segment,
2637 hir_id,
2638 span,
2639 PermitVariants::Yes,
2640 );
2641
2642 let (ty, _, res_def_id) = match opt_res {
2643 Ok(r @ (_, DefKind::Variant | DefKind::Struct, _)) => r,
2644 Ok(_) => return non_adt_or_variant_res(),
2645 Err(e) => return ty::Const::new_error(tcx, e),
2646 };
2647
2648 (ty, res_def_id)
2649 }
2650 };
2651
2652 let ty::Adt(adt_def, adt_args) = ty.kind() else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
2653
2654 let variant_def = adt_def.variant_with_id(variant_did);
2655 let variant_idx = adt_def.variant_index_with_id(variant_did).as_u32();
2656
2657 let fields = variant_def
2658 .fields
2659 .iter()
2660 .map(|field_def| {
2661 let mut init_expr =
2664 inits.iter().filter(|init_expr| init_expr.field.name == field_def.name);
2665
2666 match init_expr.next() {
2667 Some(expr) => {
2668 if let Some(expr) = init_expr.next() {
2669 let e = tcx.dcx().span_err(
2670 expr.span,
2671 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("struct expression with multiple initialisers for `{0}`",
field_def.name))
})format!(
2672 "struct expression with multiple initialisers for `{}`",
2673 field_def.name,
2674 ),
2675 );
2676 return ty::Const::new_error(tcx, e);
2677 }
2678
2679 self.lower_const_arg(
2680 expr.expr,
2681 tcx.type_of(field_def.did).instantiate(tcx, adt_args),
2682 )
2683 }
2684 None => {
2685 let e = tcx.dcx().span_err(
2686 span,
2687 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("struct expression with missing field initialiser for `{0}`",
field_def.name))
})format!(
2688 "struct expression with missing field initialiser for `{}`",
2689 field_def.name
2690 ),
2691 );
2692 ty::Const::new_error(tcx, e)
2693 }
2694 }
2695 })
2696 .collect::<Vec<_>>();
2697
2698 let opt_discr_const = if adt_def.is_enum() {
2699 let valtree = ty::ValTree::from_scalar_int(tcx, variant_idx.into());
2700 Some(ty::Const::new_value(tcx, valtree, tcx.types.u32))
2701 } else {
2702 None
2703 };
2704
2705 let valtree = ty::ValTree::from_branches(tcx, opt_discr_const.into_iter().chain(fields));
2706 ty::Const::new_value(tcx, valtree, ty)
2707 }
2708
2709 fn lower_resolved_const_path(
2711 &self,
2712 opt_self_ty: Option<Ty<'tcx>>,
2713 path: &hir::Path<'tcx>,
2714 hir_id: HirId,
2715 ) -> Const<'tcx> {
2716 let tcx = self.tcx();
2717 let span = path.span;
2718 let ct = match path.res {
2719 Res::Def(DefKind::ConstParam, def_id) => {
2720 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);
2721 let _ = self.prohibit_generic_args(
2722 path.segments.iter(),
2723 GenericsArgsErrExtend::Param(def_id),
2724 );
2725 self.lower_const_param(def_id, hir_id)
2726 }
2727 Res::Def(DefKind::Const { .. }, did) => {
2728 if let Err(guar) = self.require_type_const_attribute(did, span) {
2729 return Const::new_error(self.tcx(), guar);
2730 }
2731
2732 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);
2733 let [leading_segments @ .., segment] = path.segments else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
2734 let _ = self
2735 .prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
2736 let args = self.lower_generic_args_of_path_segment(span, did, segment);
2737 ty::Const::new_unevaluated(tcx, ty::UnevaluatedConst::new(did, args))
2738 }
2739 Res::Def(DefKind::Ctor(ctor_of, CtorKind::Const), did) => {
2740 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);
2741 let [leading_segments @ .., segment] = path.segments else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
2742 let _ = self
2743 .prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
2744
2745 let parent_did = tcx.parent(did);
2746 let generics_did = match ctor_of {
2747 CtorOf::Variant => tcx.parent(parent_did),
2748 CtorOf::Struct => parent_did,
2749 };
2750 let args = self.lower_generic_args_of_path_segment(span, generics_did, segment);
2751
2752 self.construct_const_ctor_value(did, ctor_of, args)
2753 }
2754 Res::Def(DefKind::Ctor(_, CtorKind::Fn), did) => {
2755 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);
2756 let [leading_segments @ .., segment] = path.segments else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
2757 let _ = self
2758 .prohibit_generic_args(leading_segments.iter(), GenericsArgsErrExtend::None);
2759 let parent_did = tcx.parent(did);
2760 let generics_did = if let DefKind::Ctor(CtorOf::Variant, _) = tcx.def_kind(did) {
2761 tcx.parent(parent_did)
2762 } else {
2763 parent_did
2764 };
2765 let args = self.lower_generic_args_of_path_segment(span, generics_did, segment);
2766 ty::Const::zero_sized(tcx, Ty::new_fn_def(tcx, did, args))
2767 }
2768 Res::Def(DefKind::AssocConst { .. }, did) => {
2769 let trait_segment = if let [modules @ .., trait_, _item] = path.segments {
2770 let _ = self.prohibit_generic_args(modules.iter(), GenericsArgsErrExtend::None);
2771 Some(trait_)
2772 } else {
2773 None
2774 };
2775 self.lower_resolved_assoc_const_path(
2776 span,
2777 opt_self_ty,
2778 did,
2779 trait_segment,
2780 path.segments.last().unwrap(),
2781 )
2782 .unwrap_or_else(|guar| Const::new_error(tcx, guar))
2783 }
2784 Res::Def(DefKind::Static { .. }, _) => {
2785 ::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")
2786 }
2787 Res::Def(DefKind::Fn | DefKind::AssocFn, did) => {
2789 self.dcx().span_delayed_bug(span, "function items cannot be used as const args");
2790 let args = self.lower_generic_args_of_path_segment(
2791 span,
2792 did,
2793 path.segments.last().unwrap(),
2794 );
2795 ty::Const::zero_sized(tcx, Ty::new_fn_def(tcx, did, args))
2796 }
2797
2798 res @ (Res::Def(
2801 DefKind::Mod
2802 | DefKind::Enum
2803 | DefKind::Variant
2804 | DefKind::Struct
2805 | DefKind::OpaqueTy
2806 | DefKind::TyAlias
2807 | DefKind::TraitAlias
2808 | DefKind::AssocTy
2809 | DefKind::Union
2810 | DefKind::Trait
2811 | DefKind::ForeignTy
2812 | DefKind::TyParam
2813 | DefKind::Macro(_)
2814 | DefKind::LifetimeParam
2815 | DefKind::Use
2816 | DefKind::ForeignMod
2817 | DefKind::AnonConst
2818 | DefKind::InlineConst
2819 | DefKind::Field
2820 | DefKind::Impl { .. }
2821 | DefKind::Closure
2822 | DefKind::ExternCrate
2823 | DefKind::GlobalAsm
2824 | DefKind::SyntheticCoroutineBody,
2825 _,
2826 )
2827 | Res::PrimTy(_)
2828 | Res::SelfTyParam { .. }
2829 | Res::SelfTyAlias { .. }
2830 | Res::SelfCtor(_)
2831 | Res::Local(_)
2832 | Res::ToolMod
2833 | Res::NonMacroAttr(_)
2834 | Res::Err) => Const::new_error_with_message(
2835 tcx,
2836 span,
2837 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("invalid Res {0:?} for const path",
res))
})format!("invalid Res {res:?} for const path"),
2838 ),
2839 };
2840 self.check_param_uses_if_mcg(ct, span, false)
2841 }
2842
2843 #[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(2844u32),
::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:2849",
"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(2849u32),
::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")]
2845 fn lower_const_arg_anon(&self, anon: &AnonConst) -> Const<'tcx> {
2846 let tcx = self.tcx();
2847
2848 let expr = &tcx.hir_body(anon.body).value;
2849 debug!(?expr);
2850
2851 let ty = tcx.type_of(anon.def_id).instantiate_identity();
2855
2856 match self.try_lower_anon_const_lit(ty, expr) {
2857 Some(v) => v,
2858 None => ty::Const::new_unevaluated(
2859 tcx,
2860 ty::UnevaluatedConst {
2861 def: anon.def_id.to_def_id(),
2862 args: ty::GenericArgs::identity_for_item(tcx, anon.def_id.to_def_id()),
2863 },
2864 ),
2865 }
2866 }
2867
2868 #[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(2868u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_analysis::hir_ty_lowering"),
::tracing_core::field::FieldSet::new(&["kind", "neg", "ty",
"span"], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&kind)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&neg as
&dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
as &dyn Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Const<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{
let tcx = self.tcx();
if let LitKind::Err(guar) = *kind {
return ty::Const::new_error(tcx, guar);
}
let input = LitToConstInput { lit: *kind, ty, neg };
match tcx.at(span).lit_to_const(input) {
Some(value) =>
ty::Const::new_value(tcx, value.valtree, value.ty),
None => {
let e =
tcx.dcx().span_err(span,
"type annotations needed for the literal");
ty::Const::new_error(tcx, e)
}
}
}
}
}#[instrument(skip(self), level = "debug")]
2869 fn lower_const_arg_literal(
2870 &self,
2871 kind: &LitKind,
2872 neg: bool,
2873 ty: Ty<'tcx>,
2874 span: Span,
2875 ) -> Const<'tcx> {
2876 let tcx = self.tcx();
2877 if let LitKind::Err(guar) = *kind {
2878 return ty::Const::new_error(tcx, guar);
2879 }
2880 let input = LitToConstInput { lit: *kind, ty, neg };
2881 match tcx.at(span).lit_to_const(input) {
2882 Some(value) => ty::Const::new_value(tcx, value.valtree, value.ty),
2883 None => {
2884 let e = tcx.dcx().span_err(span, "type annotations needed for the literal");
2885 ty::Const::new_error(tcx, e)
2886 }
2887 }
2888 }
2889
2890 #[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(2890u32),
::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.and_then(|l|
{
if const_lit_matches_ty(tcx, &l.lit, l.ty, l.neg) {
tcx.at(expr.span).lit_to_const(l).map(|value|
ty::Const::new_value(tcx, value.valtree, value.ty))
} else { None }
})
}
}
}#[instrument(skip(self), level = "debug")]
2891 fn try_lower_anon_const_lit(
2892 &self,
2893 ty: Ty<'tcx>,
2894 expr: &'tcx hir::Expr<'tcx>,
2895 ) -> Option<Const<'tcx>> {
2896 let tcx = self.tcx();
2897
2898 let expr = match &expr.kind {
2901 hir::ExprKind::Block(block, _) if block.stmts.is_empty() && block.expr.is_some() => {
2902 block.expr.as_ref().unwrap()
2903 }
2904 _ => expr,
2905 };
2906
2907 let lit_input = match expr.kind {
2908 hir::ExprKind::Lit(lit) => Some(LitToConstInput { lit: lit.node, ty, neg: false }),
2909 hir::ExprKind::Unary(hir::UnOp::Neg, expr) => match expr.kind {
2910 hir::ExprKind::Lit(lit) => Some(LitToConstInput { lit: lit.node, ty, neg: true }),
2911 _ => None,
2912 },
2913 _ => None,
2914 };
2915
2916 lit_input.and_then(|l| {
2917 if const_lit_matches_ty(tcx, &l.lit, l.ty, l.neg) {
2918 tcx.at(expr.span)
2919 .lit_to_const(l)
2920 .map(|value| ty::Const::new_value(tcx, value.valtree, value.ty))
2921 } else {
2922 None
2923 }
2924 })
2925 }
2926
2927 fn require_type_const_attribute(
2928 &self,
2929 def_id: DefId,
2930 span: Span,
2931 ) -> Result<(), ErrorGuaranteed> {
2932 let tcx = self.tcx();
2933 if tcx.is_type_const(def_id) {
2934 Ok(())
2935 } else {
2936 let mut err = self.dcx().struct_span_err(
2937 span,
2938 "use of `const` in the type system not defined as `type const`",
2939 );
2940 if def_id.is_local() {
2941 let name = tcx.def_path_str(def_id);
2942 err.span_suggestion(
2943 tcx.def_span(def_id).shrink_to_lo(),
2944 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("add `type` before `const` for `{0}`",
name))
})format!("add `type` before `const` for `{name}`"),
2945 ::alloc::__export::must_use({ ::alloc::fmt::format(format_args!("type ")) })format!("type "),
2946 Applicability::MaybeIncorrect,
2947 );
2948 } else {
2949 err.note("only consts marked defined as `type const` may be used in types");
2950 }
2951 Err(err.emit())
2952 }
2953 }
2954
2955 fn lower_delegation_ty(&self, idx: hir::InferDelegationKind<'tcx>) -> Ty<'tcx> {
2956 let delegation_sig = self.tcx().inherit_sig_for_delegation_item(self.item_def_id());
2957
2958 match idx {
2959 hir::InferDelegationKind::Input(idx) => delegation_sig[idx],
2960 hir::InferDelegationKind::Output { .. } => *delegation_sig.last().unwrap(),
2961 }
2962 }
2963
2964 x;#[instrument(level = "debug", skip(self), ret)]
2966 pub fn lower_ty(&self, hir_ty: &hir::Ty<'tcx>) -> Ty<'tcx> {
2967 let tcx = self.tcx();
2968
2969 let result_ty = match &hir_ty.kind {
2970 hir::TyKind::InferDelegation(_, idx) => self.lower_delegation_ty(*idx),
2971 hir::TyKind::Slice(ty) => Ty::new_slice(tcx, self.lower_ty(ty)),
2972 hir::TyKind::Ptr(mt) => Ty::new_ptr(tcx, self.lower_ty(mt.ty), mt.mutbl),
2973 hir::TyKind::Ref(region, mt) => {
2974 let r = self.lower_lifetime(region, RegionInferReason::Reference);
2975 debug!(?r);
2976 let t = self.lower_ty(mt.ty);
2977 Ty::new_ref(tcx, r, t, mt.mutbl)
2978 }
2979 hir::TyKind::Never => tcx.types.never,
2980 hir::TyKind::Tup(fields) => {
2981 Ty::new_tup_from_iter(tcx, fields.iter().map(|t| self.lower_ty(t)))
2982 }
2983 hir::TyKind::FnPtr(bf) => {
2984 check_c_variadic_abi(tcx, bf.decl, bf.abi, hir_ty.span);
2985
2986 Ty::new_fn_ptr(
2987 tcx,
2988 self.lower_fn_ty(hir_ty.hir_id, bf.safety, bf.abi, bf.decl, None, Some(hir_ty)),
2989 )
2990 }
2991 hir::TyKind::UnsafeBinder(binder) => Ty::new_unsafe_binder(
2992 tcx,
2993 ty::Binder::bind_with_vars(
2994 self.lower_ty(binder.inner_ty),
2995 tcx.late_bound_vars(hir_ty.hir_id),
2996 ),
2997 ),
2998 hir::TyKind::TraitObject(bounds, tagged_ptr) => {
2999 let lifetime = tagged_ptr.pointer();
3000 let syntax = tagged_ptr.tag();
3001 self.lower_trait_object_ty(hir_ty.span, hir_ty.hir_id, bounds, lifetime, syntax)
3002 }
3003 hir::TyKind::Path(hir::QPath::Resolved(_, path))
3007 if path.segments.last().and_then(|segment| segment.args).is_some_and(|args| {
3008 matches!(args.parenthesized, hir::GenericArgsParentheses::ReturnTypeNotation)
3009 }) =>
3010 {
3011 let guar = self.dcx().emit_err(BadReturnTypeNotation { span: hir_ty.span });
3012 Ty::new_error(tcx, guar)
3013 }
3014 hir::TyKind::Path(hir::QPath::Resolved(maybe_qself, path)) => {
3015 debug!(?maybe_qself, ?path);
3016 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
3017 self.lower_resolved_ty_path(opt_self_ty, path, hir_ty.hir_id, PermitVariants::No)
3018 }
3019 &hir::TyKind::OpaqueDef(opaque_ty) => {
3020 let in_trait = match opaque_ty.origin {
3024 hir::OpaqueTyOrigin::FnReturn {
3025 parent,
3026 in_trait_or_impl: Some(hir::RpitContext::Trait),
3027 ..
3028 }
3029 | hir::OpaqueTyOrigin::AsyncFn {
3030 parent,
3031 in_trait_or_impl: Some(hir::RpitContext::Trait),
3032 ..
3033 } => Some(parent),
3034 hir::OpaqueTyOrigin::FnReturn {
3035 in_trait_or_impl: None | Some(hir::RpitContext::TraitImpl),
3036 ..
3037 }
3038 | hir::OpaqueTyOrigin::AsyncFn {
3039 in_trait_or_impl: None | Some(hir::RpitContext::TraitImpl),
3040 ..
3041 }
3042 | hir::OpaqueTyOrigin::TyAlias { .. } => None,
3043 };
3044
3045 self.lower_opaque_ty(opaque_ty.def_id, in_trait)
3046 }
3047 hir::TyKind::TraitAscription(hir_bounds) => {
3048 let self_ty = self.ty_infer(None, hir_ty.span);
3051 let mut bounds = Vec::new();
3052 self.lower_bounds(
3053 self_ty,
3054 hir_bounds.iter(),
3055 &mut bounds,
3056 ty::List::empty(),
3057 PredicateFilter::All,
3058 OverlappingAsssocItemConstraints::Allowed,
3059 );
3060 self.add_implicit_sizedness_bounds(
3061 &mut bounds,
3062 self_ty,
3063 hir_bounds,
3064 ImpliedBoundsContext::AssociatedTypeOrImplTrait,
3065 hir_ty.span,
3066 );
3067 self.register_trait_ascription_bounds(bounds, hir_ty.hir_id, hir_ty.span);
3068 self_ty
3069 }
3070 hir::TyKind::Path(hir::QPath::TypeRelative(_, segment))
3074 if segment.args.is_some_and(|args| {
3075 matches!(args.parenthesized, hir::GenericArgsParentheses::ReturnTypeNotation)
3076 }) =>
3077 {
3078 let guar = self.dcx().emit_err(BadReturnTypeNotation { span: hir_ty.span });
3079 Ty::new_error(tcx, guar)
3080 }
3081 hir::TyKind::Path(hir::QPath::TypeRelative(hir_self_ty, segment)) => {
3082 debug!(?hir_self_ty, ?segment);
3083 let self_ty = self.lower_ty(hir_self_ty);
3084 self.lower_type_relative_ty_path(
3085 self_ty,
3086 hir_self_ty,
3087 segment,
3088 hir_ty.hir_id,
3089 hir_ty.span,
3090 PermitVariants::No,
3091 )
3092 .map(|(ty, _, _)| ty)
3093 .unwrap_or_else(|guar| Ty::new_error(tcx, guar))
3094 }
3095 hir::TyKind::Array(ty, length) => {
3096 let length = self.lower_const_arg(length, tcx.types.usize);
3097 Ty::new_array_with_const_len(tcx, self.lower_ty(ty), length)
3098 }
3099 hir::TyKind::Infer(()) => {
3100 self.ty_infer(None, hir_ty.span)
3105 }
3106 hir::TyKind::Pat(ty, pat) => {
3107 let ty_span = ty.span;
3108 let ty = self.lower_ty(ty);
3109 let pat_ty = match self.lower_pat_ty_pat(ty, ty_span, pat) {
3110 Ok(kind) => Ty::new_pat(tcx, ty, tcx.mk_pat(kind)),
3111 Err(guar) => Ty::new_error(tcx, guar),
3112 };
3113 self.record_ty(pat.hir_id, ty, pat.span);
3114 pat_ty
3115 }
3116 hir::TyKind::FieldOf(ty, hir::TyFieldPath { variant, field }) => self.lower_field_of(
3117 self.lower_ty(ty),
3118 self.item_def_id(),
3119 ty.span,
3120 hir_ty.hir_id,
3121 *variant,
3122 *field,
3123 ),
3124 hir::TyKind::Err(guar) => Ty::new_error(tcx, *guar),
3125 };
3126
3127 self.record_ty(hir_ty.hir_id, result_ty, hir_ty.span);
3128 result_ty
3129 }
3130
3131 fn lower_pat_ty_pat(
3132 &self,
3133 ty: Ty<'tcx>,
3134 ty_span: Span,
3135 pat: &hir::TyPat<'tcx>,
3136 ) -> Result<ty::PatternKind<'tcx>, ErrorGuaranteed> {
3137 let tcx = self.tcx();
3138 match pat.kind {
3139 hir::TyPatKind::Range(start, end) => {
3140 match ty.kind() {
3141 ty::Int(_) | ty::Uint(_) | ty::Char => {
3144 let start = self.lower_const_arg(start, ty);
3145 let end = self.lower_const_arg(end, ty);
3146 Ok(ty::PatternKind::Range { start, end })
3147 }
3148 _ => Err(self
3149 .dcx()
3150 .span_delayed_bug(ty_span, "invalid base type for range pattern")),
3151 }
3152 }
3153 hir::TyPatKind::NotNull => Ok(ty::PatternKind::NotNull),
3154 hir::TyPatKind::Or(patterns) => {
3155 self.tcx()
3156 .mk_patterns_from_iter(patterns.iter().map(|pat| {
3157 self.lower_pat_ty_pat(ty, ty_span, pat).map(|pat| tcx.mk_pat(pat))
3158 }))
3159 .map(ty::PatternKind::Or)
3160 }
3161 hir::TyPatKind::Err(e) => Err(e),
3162 }
3163 }
3164
3165 fn lower_field_of(
3166 &self,
3167 ty: Ty<'tcx>,
3168 item_def_id: LocalDefId,
3169 ty_span: Span,
3170 hir_id: HirId,
3171 variant: Option<Ident>,
3172 field: Ident,
3173 ) -> Ty<'tcx> {
3174 let dcx = self.dcx();
3175 let tcx = self.tcx();
3176 match ty.kind() {
3177 ty::Adt(def, _) => {
3178 let base_did = def.did();
3179 let kind_name = tcx.def_descr(base_did);
3180 let (variant_idx, variant) = if def.is_enum() {
3181 let Some(variant) = variant else {
3182 let err = dcx
3183 .create_err(NoVariantNamed { span: field.span, ident: field, ty })
3184 .with_span_help(
3185 field.span.shrink_to_lo(),
3186 "you might be missing a variant here: `Variant.`",
3187 )
3188 .emit();
3189 return Ty::new_error(tcx, err);
3190 };
3191
3192 if let Some(res) = def
3193 .variants()
3194 .iter_enumerated()
3195 .find(|(_, f)| f.ident(tcx).normalize_to_macros_2_0() == variant)
3196 {
3197 res
3198 } else {
3199 let err = dcx
3200 .create_err(NoVariantNamed { span: variant.span, ident: variant, ty })
3201 .emit();
3202 return Ty::new_error(tcx, err);
3203 }
3204 } else {
3205 if let Some(variant) = variant {
3206 let adt_path = tcx.def_path_str(base_did);
3207 {
dcx.struct_span_err(variant.span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} `{1}` does not have any variants",
kind_name, adt_path))
})).with_code(E0609)
}struct_span_code_err!(
3208 dcx,
3209 variant.span,
3210 E0609,
3211 "{kind_name} `{adt_path}` does not have any variants",
3212 )
3213 .with_span_label(variant.span, "variant unknown")
3214 .emit();
3215 }
3216 (FIRST_VARIANT, def.non_enum_variant())
3217 };
3218 let block = tcx.local_def_id_to_hir_id(item_def_id);
3219 let (ident, def_scope) = tcx.adjust_ident_and_get_scope(field, def.did(), block);
3220 if let Some((field_idx, field)) = variant
3221 .fields
3222 .iter_enumerated()
3223 .find(|(_, f)| f.ident(tcx).normalize_to_macros_2_0() == ident)
3224 {
3225 if field.vis.is_accessible_from(def_scope, tcx) {
3226 tcx.check_stability(field.did, Some(hir_id), ident.span, None);
3227 } else {
3228 let adt_path = tcx.def_path_str(base_did);
3229 {
dcx.struct_span_err(ident.span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("field `{0}` of {1} `{2}` is private",
ident, kind_name, adt_path))
})).with_code(E0616)
}struct_span_code_err!(
3230 dcx,
3231 ident.span,
3232 E0616,
3233 "field `{ident}` of {kind_name} `{adt_path}` is private",
3234 )
3235 .with_span_label(ident.span, "private field")
3236 .emit();
3237 }
3238 Ty::new_field_representing_type(tcx, ty, variant_idx, field_idx)
3239 } else {
3240 let err =
3241 dcx.create_err(NoFieldOnType { span: ident.span, field: ident, ty }).emit();
3242 Ty::new_error(tcx, err)
3243 }
3244 }
3245 ty::Tuple(tys) => {
3246 let index = match field.as_str().parse::<usize>() {
3247 Ok(idx) => idx,
3248 Err(_) => {
3249 let err =
3250 dcx.create_err(NoFieldOnType { span: field.span, field, ty }).emit();
3251 return Ty::new_error(tcx, err);
3252 }
3253 };
3254 if field.name != sym::integer(index) {
3255 ::rustc_middle::util::bug::bug_fmt(format_args!("we parsed above, but now not equal?"));bug!("we parsed above, but now not equal?");
3256 }
3257 if tys.get(index).is_some() {
3258 Ty::new_field_representing_type(tcx, ty, FIRST_VARIANT, index.into())
3259 } else {
3260 let err = dcx.create_err(NoFieldOnType { span: field.span, field, ty }).emit();
3261 Ty::new_error(tcx, err)
3262 }
3263 }
3264 ty::Alias(..) => Ty::new_error(
3277 tcx,
3278 dcx.span_err(ty_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("could not resolve fields of `{0}`",
ty))
})format!("could not resolve fields of `{ty}`")),
3279 ),
3280 ty::Error(err) => Ty::new_error(tcx, *err),
3281 ty::Bool
3282 | ty::Char
3283 | ty::Int(_)
3284 | ty::Uint(_)
3285 | ty::Float(_)
3286 | ty::Foreign(_)
3287 | ty::Str
3288 | ty::RawPtr(_, _)
3289 | ty::Ref(_, _, _)
3290 | ty::FnDef(_, _)
3291 | ty::FnPtr(_, _)
3292 | ty::UnsafeBinder(_)
3293 | ty::Dynamic(_, _)
3294 | ty::Closure(_, _)
3295 | ty::CoroutineClosure(_, _)
3296 | ty::Coroutine(_, _)
3297 | ty::CoroutineWitness(_, _)
3298 | ty::Never
3299 | ty::Param(_)
3300 | ty::Bound(_, _)
3301 | ty::Placeholder(_)
3302 | ty::Slice(..) => Ty::new_error(
3303 tcx,
3304 dcx.span_err(ty_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("type `{0}` doesn\'t have fields",
ty))
})format!("type `{ty}` doesn't have fields")),
3305 ),
3306 ty::Infer(_) => Ty::new_error(
3307 tcx,
3308 dcx.span_err(ty_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cannot use `{0}` in this position",
ty))
})format!("cannot use `{ty}` in this position")),
3309 ),
3310 ty::Array(..) | ty::Pat(..) => Ty::new_error(
3312 tcx,
3313 dcx.span_err(ty_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("type `{0}` is not yet supported in `field_of!`",
ty))
})format!("type `{ty}` is not yet supported in `field_of!`")),
3314 ),
3315 }
3316 }
3317
3318 x;#[instrument(level = "debug", skip(self), ret)]
3320 fn lower_opaque_ty(&self, def_id: LocalDefId, in_trait: Option<LocalDefId>) -> Ty<'tcx> {
3321 let tcx = self.tcx();
3322
3323 let lifetimes = tcx.opaque_captured_lifetimes(def_id);
3324 debug!(?lifetimes);
3325
3326 let def_id = if let Some(parent_def_id) = in_trait {
3330 *tcx.associated_types_for_impl_traits_in_associated_fn(parent_def_id.to_def_id())
3331 .iter()
3332 .find(|rpitit| match tcx.opt_rpitit_info(**rpitit) {
3333 Some(ty::ImplTraitInTraitData::Trait { opaque_def_id, .. }) => {
3334 opaque_def_id.expect_local() == def_id
3335 }
3336 _ => unreachable!(),
3337 })
3338 .unwrap()
3339 } else {
3340 def_id.to_def_id()
3341 };
3342
3343 let generics = tcx.generics_of(def_id);
3344 debug!(?generics);
3345
3346 let offset = generics.count() - lifetimes.len();
3350
3351 let args = ty::GenericArgs::for_item(tcx, def_id, |param, _| {
3352 if let Some(i) = (param.index as usize).checked_sub(offset) {
3353 let (lifetime, _) = lifetimes[i];
3354 self.lower_resolved_lifetime(lifetime).into()
3356 } else {
3357 tcx.mk_param_from_def(param)
3358 }
3359 });
3360 debug!(?args);
3361
3362 if in_trait.is_some() {
3363 Ty::new_projection_from_args(tcx, def_id, args)
3364 } else {
3365 Ty::new_opaque(tcx, def_id, args)
3366 }
3367 }
3368
3369 x;#[instrument(level = "debug", skip(self, hir_id, safety, abi, decl, generics, hir_ty), ret)]
3371 pub fn lower_fn_ty(
3372 &self,
3373 hir_id: HirId,
3374 safety: hir::Safety,
3375 abi: rustc_abi::ExternAbi,
3376 decl: &hir::FnDecl<'tcx>,
3377 generics: Option<&hir::Generics<'_>>,
3378 hir_ty: Option<&hir::Ty<'_>>,
3379 ) -> ty::PolyFnSig<'tcx> {
3380 let tcx = self.tcx();
3381 let bound_vars = tcx.late_bound_vars(hir_id);
3382 debug!(?bound_vars);
3383
3384 let (input_tys, output_ty) = self.lower_fn_sig(decl, generics, hir_id, hir_ty);
3385
3386 debug!(?output_ty);
3387
3388 let fn_ty = tcx.mk_fn_sig(input_tys, output_ty, decl.c_variadic, safety, abi);
3389 let fn_ptr_ty = ty::Binder::bind_with_vars(fn_ty, bound_vars);
3390
3391 if let hir::Node::Ty(hir::Ty { kind: hir::TyKind::FnPtr(fn_ptr_ty), span, .. }) =
3392 tcx.hir_node(hir_id)
3393 {
3394 check_abi(tcx, hir_id, *span, fn_ptr_ty.abi);
3395 }
3396
3397 cmse::validate_cmse_abi(self.tcx(), self.dcx(), hir_id, abi, fn_ptr_ty);
3399
3400 if !fn_ptr_ty.references_error() {
3401 let inputs = fn_ptr_ty.inputs();
3408 let late_bound_in_args =
3409 tcx.collect_constrained_late_bound_regions(inputs.map_bound(|i| i.to_owned()));
3410 let output = fn_ptr_ty.output();
3411 let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(output);
3412
3413 self.validate_late_bound_regions(late_bound_in_args, late_bound_in_ret, |br_name| {
3414 struct_span_code_err!(
3415 self.dcx(),
3416 decl.output.span(),
3417 E0581,
3418 "return type references {}, which is not constrained by the fn input types",
3419 br_name
3420 )
3421 });
3422 }
3423
3424 fn_ptr_ty
3425 }
3426
3427 pub(super) fn suggest_trait_fn_ty_for_impl_fn_infer(
3432 &self,
3433 fn_hir_id: HirId,
3434 arg_idx: Option<usize>,
3435 ) -> Option<Ty<'tcx>> {
3436 let tcx = self.tcx();
3437 let hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), ident, .. }) =
3438 tcx.hir_node(fn_hir_id)
3439 else {
3440 return None;
3441 };
3442 let i = tcx.parent_hir_node(fn_hir_id).expect_item().expect_impl();
3443
3444 let trait_ref = self.lower_impl_trait_ref(&i.of_trait?.trait_ref, self.lower_ty(i.self_ty));
3445
3446 let assoc = tcx.associated_items(trait_ref.def_id).find_by_ident_and_kind(
3447 tcx,
3448 *ident,
3449 ty::AssocTag::Fn,
3450 trait_ref.def_id,
3451 )?;
3452
3453 let fn_sig = tcx.fn_sig(assoc.def_id).instantiate(
3454 tcx,
3455 trait_ref.args.extend_to(tcx, assoc.def_id, |param, _| tcx.mk_param_from_def(param)),
3456 );
3457 let fn_sig = tcx.liberate_late_bound_regions(fn_hir_id.expect_owner().to_def_id(), fn_sig);
3458
3459 Some(if let Some(arg_idx) = arg_idx {
3460 *fn_sig.inputs().get(arg_idx)?
3461 } else {
3462 fn_sig.output()
3463 })
3464 }
3465
3466 #[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(3466u32),
::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))]
3467 fn validate_late_bound_regions<'cx>(
3468 &'cx self,
3469 constrained_regions: FxIndexSet<ty::BoundRegionKind<'tcx>>,
3470 referenced_regions: FxIndexSet<ty::BoundRegionKind<'tcx>>,
3471 generate_err: impl Fn(&str) -> Diag<'cx>,
3472 ) {
3473 for br in referenced_regions.difference(&constrained_regions) {
3474 let br_name = if let Some(name) = br.get_name(self.tcx()) {
3475 format!("lifetime `{name}`")
3476 } else {
3477 "an anonymous lifetime".to_string()
3478 };
3479
3480 let mut err = generate_err(&br_name);
3481
3482 if !br.is_named(self.tcx()) {
3483 err.note(
3490 "lifetimes appearing in an associated or opaque type are not considered constrained",
3491 );
3492 err.note("consider introducing a named lifetime parameter");
3493 }
3494
3495 err.emit();
3496 }
3497 }
3498
3499 x;#[instrument(level = "debug", skip(self, span), ret)]
3507 fn compute_object_lifetime_bound(
3508 &self,
3509 span: Span,
3510 existential_predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
3511 ) -> Option<ty::Region<'tcx>> {
3513 let tcx = self.tcx();
3514
3515 let derived_region_bounds = object_region_bounds(tcx, existential_predicates);
3518
3519 if derived_region_bounds.is_empty() {
3522 return None;
3523 }
3524
3525 if derived_region_bounds.iter().any(|r| r.is_static()) {
3528 return Some(tcx.lifetimes.re_static);
3529 }
3530
3531 let r = derived_region_bounds[0];
3535 if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
3536 self.dcx().emit_err(AmbiguousLifetimeBound { span });
3537 }
3538 Some(r)
3539 }
3540
3541 fn construct_const_ctor_value(
3542 &self,
3543 ctor_def_id: DefId,
3544 ctor_of: CtorOf,
3545 args: GenericArgsRef<'tcx>,
3546 ) -> Const<'tcx> {
3547 let tcx = self.tcx();
3548 let parent_did = tcx.parent(ctor_def_id);
3549
3550 let adt_def = tcx.adt_def(match ctor_of {
3551 CtorOf::Variant => tcx.parent(parent_did),
3552 CtorOf::Struct => parent_did,
3553 });
3554
3555 let variant_idx = adt_def.variant_index_with_id(parent_did);
3556
3557 let valtree = if adt_def.is_enum() {
3558 let discr = ty::ValTree::from_scalar_int(tcx, variant_idx.as_u32().into());
3559 ty::ValTree::from_branches(tcx, [ty::Const::new_value(tcx, discr, tcx.types.u32)])
3560 } else {
3561 ty::ValTree::zst(tcx)
3562 };
3563
3564 let adt_ty = Ty::new_adt(tcx, adt_def, args);
3565 ty::Const::new_value(tcx, valtree, adt_ty)
3566 }
3567}