1
Fork 0

Update local variables and tracing calls

Most of the tracing calls didn't fully leverage the power of `tracing`.
For example, several of them used to hard-code method names / tracing spans
as well as variable names. Use `#[instrument]` and `?var` / `%var` (etc.) instead.

In my opinion, this is the proper way to migrate them from the old
AstConv nomenclature to the new HIR ty lowering one.
This commit is contained in:
León Orell Valerian Liehr 2024-02-11 09:24:35 +01:00
parent 82c2c8deb1
commit b79335dbed
No known key found for this signature in database
GPG key ID: D17A07215F68E713
11 changed files with 136 additions and 148 deletions

View file

@ -24,7 +24,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
&self, &self,
bounds: &mut Bounds<'tcx>, bounds: &mut Bounds<'tcx>,
self_ty: Ty<'tcx>, self_ty: Ty<'tcx>,
ast_bounds: &'tcx [hir::GenericBound<'tcx>], hir_bounds: &'tcx [hir::GenericBound<'tcx>],
self_ty_where_predicates: Option<(LocalDefId, &'tcx [hir::WherePredicate<'tcx>])>, self_ty_where_predicates: Option<(LocalDefId, &'tcx [hir::WherePredicate<'tcx>])>,
span: Span, span: Span,
) { ) {
@ -35,9 +35,9 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
// Try to find an unbound in bounds. // Try to find an unbound in bounds.
let mut unbounds: SmallVec<[_; 1]> = SmallVec::new(); let mut unbounds: SmallVec<[_; 1]> = SmallVec::new();
let mut search_bounds = |ast_bounds: &'tcx [hir::GenericBound<'tcx>]| { let mut search_bounds = |hir_bounds: &'tcx [hir::GenericBound<'tcx>]| {
for ab in ast_bounds { for hir_bound in hir_bounds {
let hir::GenericBound::Trait(ptr, modifier) = ab else { let hir::GenericBound::Trait(ptr, modifier) = hir_bound else {
continue; continue;
}; };
match modifier { match modifier {
@ -60,7 +60,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
} }
} }
}; };
search_bounds(ast_bounds); search_bounds(hir_bounds);
if let Some((self_ty, where_clause)) = self_ty_where_predicates { if let Some((self_ty, where_clause)) = self_ty_where_predicates {
for clause in where_clause { for clause in where_clause {
if let hir::WherePredicate::BoundPredicate(pred) = clause if let hir::WherePredicate::BoundPredicate(pred) = clause
@ -109,34 +109,34 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
/// ///
/// ```ignore (illustrative) /// ```ignore (illustrative)
/// fn foo<T>() where for<'a> T: Trait<'a> + Copy {} /// fn foo<T>() where for<'a> T: Trait<'a> + Copy {}
/// // ^^^^^^^ ^ ^^^^^^^^^^^^^^^^ `ast_bounds`, in HIR form /// // ^^^^^^^ ^ ^^^^^^^^^^^^^^^^ `hir_bounds`, in HIR form
/// // | | /// // | |
/// // | `param_ty`, in ty form /// // | `param_ty`, in ty form
/// // `bound_vars`, in ty form /// // `bound_vars`, in ty form
/// ///
/// fn bar<T>() where T: for<'a> Trait<'a> + Copy {} // no overarching `bound_vars` here! /// fn bar<T>() where T: for<'a> Trait<'a> + Copy {} // no overarching `bound_vars` here!
/// // ^ ^^^^^^^^^^^^^^^^^^^^^^^^ `ast_bounds`, in HIR form /// // ^ ^^^^^^^^^^^^^^^^^^^^^^^^ `hir_bounds`, in HIR form
/// // | /// // |
/// // `param_ty`, in ty form /// // `param_ty`, in ty form
/// ``` /// ```
/// ///
/// ### A Note on Binders /// ### A Note on Binders
/// ///
/// There is an implied binder around `param_ty` and `ast_bounds`. /// There is an implied binder around `param_ty` and `hir_bounds`.
/// See `lower_poly_trait_ref` for more details. /// See `lower_poly_trait_ref` for more details.
#[instrument(level = "debug", skip(self, ast_bounds, bounds))] #[instrument(level = "debug", skip(self, hir_bounds, bounds))]
pub(crate) fn lower_poly_bounds<'hir, I: Iterator<Item = &'hir hir::GenericBound<'tcx>>>( pub(crate) fn lower_poly_bounds<'hir, I: Iterator<Item = &'hir hir::GenericBound<'tcx>>>(
&self, &self,
param_ty: Ty<'tcx>, param_ty: Ty<'tcx>,
ast_bounds: I, hir_bounds: I,
bounds: &mut Bounds<'tcx>, bounds: &mut Bounds<'tcx>,
bound_vars: &'tcx ty::List<ty::BoundVariableKind>, bound_vars: &'tcx ty::List<ty::BoundVariableKind>,
only_self_bounds: OnlySelfBounds, only_self_bounds: OnlySelfBounds,
) where ) where
'tcx: 'hir, 'tcx: 'hir,
{ {
for ast_bound in ast_bounds { for hir_bound in hir_bounds {
match ast_bound { match hir_bound {
hir::GenericBound::Trait(poly_trait_ref, modifier) => { hir::GenericBound::Trait(poly_trait_ref, modifier) => {
let (constness, polarity) = match modifier { let (constness, polarity) = match modifier {
hir::TraitBoundModifier::Const => { hir::TraitBoundModifier::Const => {
@ -183,14 +183,14 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
/// ### Example /// ### Example
/// ///
/// ```ignore (illustrative) /// ```ignore (illustrative)
/// fn foo<T: Bar + Baz>() {} /// fn foo<T: Bar + Baz>() { }
/// // ^ ^^^^^^^^^ ast_bounds /// // ^ ^^^^^^^^^ hir_bounds
/// // param_ty /// // param_ty
/// ``` /// ```
pub(crate) fn lower_mono_bounds( pub(crate) fn lower_mono_bounds(
&self, &self,
param_ty: Ty<'tcx>, param_ty: Ty<'tcx>,
ast_bounds: &[hir::GenericBound<'tcx>], hir_bounds: &[hir::GenericBound<'tcx>],
filter: PredicateFilter, filter: PredicateFilter,
) -> Bounds<'tcx> { ) -> Bounds<'tcx> {
let mut bounds = Bounds::default(); let mut bounds = Bounds::default();
@ -204,7 +204,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
self.lower_poly_bounds( self.lower_poly_bounds(
param_ty, param_ty,
ast_bounds.iter().filter(|bound| match filter { hir_bounds.iter().filter(|bound| match filter {
PredicateFilter::All PredicateFilter::All
| PredicateFilter::SelfOnly | PredicateFilter::SelfOnly
| PredicateFilter::SelfAndAssociatedTypeBounds => true, | PredicateFilter::SelfAndAssociatedTypeBounds => true,
@ -496,7 +496,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
} }
// Lower a constraint like `Item: Debug` as found in HIR bound `T: Iterator<Item: Debug>` // Lower a constraint like `Item: Debug` as found in HIR bound `T: Iterator<Item: Debug>`
// to a bound involving a projection: `<T as Iterator>::Item: Debug`. // to a bound involving a projection: `<T as Iterator>::Item: Debug`.
hir::TypeBindingKind::Constraint { bounds: ast_bounds } => { hir::TypeBindingKind::Constraint { bounds: hir_bounds } => {
// NOTE: If `only_self_bounds` is true, do NOT expand this associated type bound into // NOTE: If `only_self_bounds` is true, do NOT expand this associated type bound into
// a trait predicate, since we only want to add predicates for the `Self` type. // a trait predicate, since we only want to add predicates for the `Self` type.
if !only_self_bounds.0 { if !only_self_bounds.0 {
@ -505,7 +505,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
let param_ty = Ty::new_alias(tcx, ty::Projection, projection_ty.skip_binder()); let param_ty = Ty::new_alias(tcx, ty::Projection, projection_ty.skip_binder());
self.lower_poly_bounds( self.lower_poly_bounds(
param_ty, param_ty,
ast_bounds.iter(), hir_bounds.iter(),
bounds, bounds,
projection_ty.bound_vars(), projection_ty.bound_vars(),
only_self_bounds, only_self_bounds,

View file

@ -376,7 +376,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
let tcx = self.tcx(); let tcx = self.tcx();
let generics = tcx.generics_of(def_id); let generics = tcx.generics_of(def_id);
debug!("generics: {:?}", generics); debug!(?generics);
if generics.has_self { if generics.has_self {
if generics.parent.is_some() { if generics.parent.is_some() {
@ -601,6 +601,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
(args, arg_count) (args, arg_count)
} }
#[instrument(level = "debug", skip_all)]
pub fn lower_generic_args_of_assoc_item( pub fn lower_generic_args_of_assoc_item(
&self, &self,
span: Span, span: Span,
@ -608,10 +609,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
item_segment: &hir::PathSegment<'tcx>, item_segment: &hir::PathSegment<'tcx>,
parent_args: GenericArgsRef<'tcx>, parent_args: GenericArgsRef<'tcx>,
) -> GenericArgsRef<'tcx> { ) -> GenericArgsRef<'tcx> {
debug!( debug!(?span, ?item_def_id, ?item_segment);
"create_args_for_associated_item(span: {:?}, item_def_id: {:?}, item_segment: {:?}",
span, item_def_id, item_segment
);
let (args, _) = self.lower_generic_args_of_path( let (args, _) = self.lower_generic_args_of_path(
span, span,
item_def_id, item_def_id,
@ -805,22 +803,18 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
/// candidates in which case it reports ambiguity. /// candidates in which case it reports ambiguity.
/// ///
/// `ty_param_def_id` is the `LocalDefId` of the type parameter. /// `ty_param_def_id` is the `LocalDefId` of the type parameter.
#[instrument(level = "debug", skip_all, ret)]
fn probe_single_ty_param_bound_for_assoc_ty( fn probe_single_ty_param_bound_for_assoc_ty(
&self, &self,
ty_param_def_id: LocalDefId, ty_param_def_id: LocalDefId,
assoc_name: Ident, assoc_name: Ident,
span: Span, span: Span,
) -> Result<ty::PolyTraitRef<'tcx>, ErrorGuaranteed> { ) -> Result<ty::PolyTraitRef<'tcx>, ErrorGuaranteed> {
debug!(?ty_param_def_id, ?assoc_name, ?span);
let tcx = self.tcx(); let tcx = self.tcx();
debug!(
"find_bound_for_assoc_item(ty_param_def_id={:?}, assoc_name={:?}, span={:?})",
ty_param_def_id, assoc_name, span,
);
let predicates = &self.probe_ty_param_bounds(span, ty_param_def_id, assoc_name).predicates; let predicates = &self.probe_ty_param_bounds(span, ty_param_def_id, assoc_name).predicates;
debug!("predicates={:#?}", predicates);
debug!("find_bound_for_assoc_item: predicates={:#?}", predicates);
let param_name = tcx.hir().ty_param_name(ty_param_def_id); let param_name = tcx.hir().ty_param_name(ty_param_def_id);
self.probe_single_bound_for_assoc_item( self.probe_single_bound_for_assoc_item(
@ -995,7 +989,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
// //
// NOTE: When this function starts resolving `Trait::AssocTy` successfully // NOTE: When this function starts resolving `Trait::AssocTy` successfully
// it should also start reporting the `BARE_TRAIT_OBJECTS` lint. // it should also start reporting the `BARE_TRAIT_OBJECTS` lint.
#[instrument(level = "debug", skip(self, hir_ref_id, span, qself, assoc_segment), fields(assoc_ident=?assoc_segment.ident), ret)] #[instrument(level = "debug", skip_all, ret)]
pub fn lower_assoc_path( pub fn lower_assoc_path(
&self, &self,
hir_ref_id: hir::HirId, hir_ref_id: hir::HirId,
@ -1005,7 +999,9 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
assoc_segment: &hir::PathSegment<'tcx>, assoc_segment: &hir::PathSegment<'tcx>,
permit_variants: bool, permit_variants: bool,
) -> Result<(Ty<'tcx>, DefKind, DefId), ErrorGuaranteed> { ) -> Result<(Ty<'tcx>, DefKind, DefId), ErrorGuaranteed> {
debug!(%qself_ty, ?assoc_segment.ident);
let tcx = self.tcx(); let tcx = self.tcx();
let assoc_ident = assoc_segment.ident; let assoc_ident = assoc_segment.ident;
let qself_res = if let hir::TyKind::Path(hir::QPath::Resolved(_, path)) = &qself.kind { let qself_res = if let hir::TyKind::Path(hir::QPath::Resolved(_, path)) = &qself.kind {
path.res path.res
@ -1553,6 +1549,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
} }
/// Lower a qualified path to a type. /// Lower a qualified path to a type.
#[instrument(level = "debug", skip_all)]
fn lower_qpath( fn lower_qpath(
&self, &self,
span: Span, span: Span,
@ -1565,22 +1562,19 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
let tcx = self.tcx(); let tcx = self.tcx();
let trait_def_id = tcx.parent(item_def_id); let trait_def_id = tcx.parent(item_def_id);
debug!(?trait_def_id);
debug!("qpath_to_ty: trait_def_id={:?}", trait_def_id);
let Some(self_ty) = opt_self_ty else { let Some(self_ty) = opt_self_ty else {
let path_str = tcx.def_path_str(trait_def_id); let path_str = tcx.def_path_str(trait_def_id);
let def_id = self.item_def_id(); let def_id = self.item_def_id();
debug!(item_def_id = ?def_id);
debug!("qpath_to_ty: self.item_def_id()={:?}", def_id);
let parent_def_id = def_id let parent_def_id = def_id
.as_local() .as_local()
.map(|def_id| tcx.local_def_id_to_hir_id(def_id)) .map(|def_id| tcx.local_def_id_to_hir_id(def_id))
.map(|hir_id| tcx.hir().get_parent_item(hir_id).to_def_id()); .map(|hir_id| tcx.hir().get_parent_item(hir_id).to_def_id());
debug!(?parent_def_id);
debug!("qpath_to_ty: parent_def_id={:?}", parent_def_id);
// If the trait in segment is the same as the trait defining the item, // If the trait in segment is the same as the trait defining the item,
// use the `<Self as ..>` syntax in the error. // use the `<Self as ..>` syntax in the error.
@ -1615,17 +1609,15 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
); );
return Ty::new_error(tcx, reported); return Ty::new_error(tcx, reported);
}; };
debug!(?self_ty);
debug!("qpath_to_ty: self_type={:?}", self_ty);
let trait_ref = let trait_ref =
self.lower_mono_trait_ref(span, trait_def_id, self_ty, trait_segment, false, constness); self.lower_mono_trait_ref(span, trait_def_id, self_ty, trait_segment, false, constness);
debug!(?trait_ref);
let item_args = let item_args =
self.lower_generic_args_of_assoc_item(span, item_def_id, item_segment, trait_ref.args); self.lower_generic_args_of_assoc_item(span, item_def_id, item_segment, trait_ref.args);
debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
Ty::new_projection(tcx, item_def_id, item_args) Ty::new_projection(tcx, item_def_id, item_args)
} }
@ -1878,12 +1870,13 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
kind => bug!("unexpected definition kind {:?} for {:?}", kind, def_id), kind => bug!("unexpected definition kind {:?} for {:?}", kind, def_id),
} }
debug!("path_segs = {:?}", generic_segments); debug!(?generic_segments);
generic_segments generic_segments
} }
/// Lower a type `Path` to a type. /// Lower a type `Path` to a type.
#[instrument(level = "debug", skip_all)]
pub fn lower_path( pub fn lower_path(
&self, &self,
opt_self_ty: Option<Ty<'tcx>>, opt_self_ty: Option<Ty<'tcx>>,
@ -1891,13 +1884,9 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
hir_id: hir::HirId, hir_id: hir::HirId,
permit_variants: bool, permit_variants: bool,
) -> Ty<'tcx> { ) -> Ty<'tcx> {
debug!(?path.res, ?opt_self_ty, ?path.segments);
let tcx = self.tcx(); let tcx = self.tcx();
debug!(
"res_to_ty(res={:?}, opt_self_ty={:?}, path_segments={:?})",
path.res, opt_self_ty, path.segments
);
let span = path.span; let span = path.span;
match path.res { match path.res {
Res::Def(DefKind::OpaqueTy, did) => { Res::Def(DefKind::OpaqueTy, did) => {
@ -2176,13 +2165,13 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
} }
/// Lower a type from the HIR to our internal notion of a type. /// Lower a type from the HIR to our internal notion of a type.
pub fn lower_ty(&self, ast_ty: &hir::Ty<'tcx>) -> Ty<'tcx> { pub fn lower_ty(&self, hir_ty: &hir::Ty<'tcx>) -> Ty<'tcx> {
self.lower_ty_common(ast_ty, false, false) self.lower_ty_common(hir_ty, false, false)
} }
/// Lower a type inside of a path from the HIR to our internal notion of a type. /// Lower a type inside of a path from the HIR to our internal notion of a type.
pub fn lower_ty_in_path(&self, ast_ty: &hir::Ty<'tcx>) -> Ty<'tcx> { pub fn lower_ty_in_path(&self, hir_ty: &hir::Ty<'tcx>) -> Ty<'tcx> {
self.lower_ty_common(ast_ty, false, true) self.lower_ty_common(hir_ty, false, true)
} }
fn check_delegation_constraints(&self, sig_id: DefId, span: Span, emit: bool) -> bool { fn check_delegation_constraints(&self, sig_id: DefId, span: Span, emit: bool) -> bool {
@ -2302,12 +2291,12 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
/// 2. `in_path`: Whether the type appears inside of a path. /// 2. `in_path`: Whether the type appears inside of a path.
/// Used to provide correct diagnostics for bare trait object types. /// Used to provide correct diagnostics for bare trait object types.
#[instrument(level = "debug", skip(self), ret)] #[instrument(level = "debug", skip(self), ret)]
fn lower_ty_common(&self, ast_ty: &hir::Ty<'tcx>, borrowed: bool, in_path: bool) -> Ty<'tcx> { fn lower_ty_common(&self, hir_ty: &hir::Ty<'tcx>, borrowed: bool, in_path: bool) -> Ty<'tcx> {
let tcx = self.tcx(); let tcx = self.tcx();
let result_ty = match &ast_ty.kind { let result_ty = match &hir_ty.kind {
hir::TyKind::InferDelegation(sig_id, idx) => { hir::TyKind::InferDelegation(sig_id, idx) => {
self.lower_delegation_ty(*sig_id, *idx, ast_ty.span) self.lower_delegation_ty(*sig_id, *idx, hir_ty.span)
} }
hir::TyKind::Slice(ty) => Ty::new_slice(tcx, self.lower_ty(ty)), hir::TyKind::Slice(ty) => Ty::new_slice(tcx, self.lower_ty(ty)),
hir::TyKind::Ptr(mt) => { hir::TyKind::Ptr(mt) => {
@ -2324,43 +2313,43 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
Ty::new_tup_from_iter(tcx, fields.iter().map(|t| self.lower_ty(t))) Ty::new_tup_from_iter(tcx, fields.iter().map(|t| self.lower_ty(t)))
} }
hir::TyKind::AnonAdt(item_id) => { hir::TyKind::AnonAdt(item_id) => {
let _guard = debug_span!("AnonAdt");
let did = item_id.owner_id.def_id; let did = item_id.owner_id.def_id;
let adt_def = tcx.adt_def(did); let adt_def = tcx.adt_def(did);
let generics = tcx.generics_of(did);
debug!("ast_ty_to_ty_inner(AnonAdt): generics={:?}", generics);
let args = ty::GenericArgs::for_item(tcx, did.to_def_id(), |param, _| { let args = ty::GenericArgs::for_item(tcx, did.to_def_id(), |param, _| {
tcx.mk_param_from_def(param) tcx.mk_param_from_def(param)
}); });
debug!("ast_ty_to_ty_inner(AnonAdt): args={:?}", args); debug!(?args);
Ty::new_adt(tcx, adt_def, tcx.mk_args(args)) Ty::new_adt(tcx, adt_def, tcx.mk_args(args))
} }
hir::TyKind::BareFn(bf) => { hir::TyKind::BareFn(bf) => {
require_c_abi_if_c_variadic(tcx, bf.decl, bf.abi, ast_ty.span); require_c_abi_if_c_variadic(tcx, bf.decl, bf.abi, hir_ty.span);
Ty::new_fn_ptr( Ty::new_fn_ptr(
tcx, tcx,
self.lower_fn_ty( self.lower_fn_ty(
ast_ty.hir_id, hir_ty.hir_id,
bf.unsafety, bf.unsafety,
bf.abi, bf.abi,
bf.decl, bf.decl,
None, None,
Some(ast_ty), Some(hir_ty),
), ),
) )
} }
hir::TyKind::TraitObject(bounds, lifetime, repr) => { hir::TyKind::TraitObject(bounds, lifetime, repr) => {
self.maybe_lint_bare_trait(ast_ty, in_path); self.maybe_lint_bare_trait(hir_ty, in_path);
let repr = match repr { let repr = match repr {
TraitObjectSyntax::Dyn | TraitObjectSyntax::None => ty::Dyn, TraitObjectSyntax::Dyn | TraitObjectSyntax::None => ty::Dyn,
TraitObjectSyntax::DynStar => ty::DynStar, TraitObjectSyntax::DynStar => ty::DynStar,
}; };
self.lower_trait_object_ty( self.lower_trait_object_ty(
ast_ty.span, hir_ty.span,
ast_ty.hir_id, hir_ty.hir_id,
bounds, bounds,
lifetime, lifetime,
borrowed, borrowed,
@ -2370,7 +2359,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
hir::TyKind::Path(hir::QPath::Resolved(maybe_qself, path)) => { hir::TyKind::Path(hir::QPath::Resolved(maybe_qself, path)) => {
debug!(?maybe_qself, ?path); debug!(?maybe_qself, ?path);
let opt_self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself)); let opt_self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself));
self.lower_path(opt_self_ty, path, ast_ty.hir_id, false) self.lower_path(opt_self_ty, path, hir_ty.hir_id, false)
} }
&hir::TyKind::OpaqueDef(item_id, lifetimes, in_trait) => { &hir::TyKind::OpaqueDef(item_id, lifetimes, in_trait) => {
let opaque_ty = tcx.hir().item(item_id); let opaque_ty = tcx.hir().item(item_id);
@ -2394,7 +2383,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
hir::TyKind::Path(hir::QPath::TypeRelative(qself, segment)) => { hir::TyKind::Path(hir::QPath::TypeRelative(qself, segment)) => {
debug!(?qself, ?segment); debug!(?qself, ?segment);
let ty = self.lower_ty_common(qself, false, true); let ty = self.lower_ty_common(qself, false, true);
self.lower_assoc_path(ast_ty.hir_id, ast_ty.span, ty, qself, segment, false) self.lower_assoc_path(hir_ty.hir_id, hir_ty.span, ty, qself, segment, false)
.map(|(ty, _, _)| ty) .map(|(ty, _, _)| ty)
.unwrap_or_else(|guar| Ty::new_error(tcx, guar)) .unwrap_or_else(|guar| Ty::new_error(tcx, guar))
} }
@ -2426,29 +2415,29 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
// values in an ExprKind::Closure, or as // values in an ExprKind::Closure, or as
// the type of local variables. Both of these cases are // the type of local variables. Both of these cases are
// handled specially and will not descend into this routine. // handled specially and will not descend into this routine.
self.ty_infer(None, ast_ty.span) self.ty_infer(None, hir_ty.span)
} }
hir::TyKind::Err(guar) => Ty::new_error(tcx, *guar), hir::TyKind::Err(guar) => Ty::new_error(tcx, *guar),
}; };
self.record_ty(ast_ty.hir_id, result_ty, ast_ty.span); self.record_ty(hir_ty.hir_id, result_ty, hir_ty.span);
result_ty result_ty
} }
/// Lower an opaque type (i.e., an existential impl-Trait type) from the HIR. /// Lower an opaque type (i.e., an existential impl-Trait type) from the HIR.
#[instrument(level = "debug", skip(self), ret)] #[instrument(level = "debug", skip_all, ret)]
fn lower_opaque_ty( fn lower_opaque_ty(
&self, &self,
def_id: DefId, def_id: DefId,
lifetimes: &[hir::GenericArg<'_>], lifetimes: &[hir::GenericArg<'_>],
in_trait: bool, in_trait: bool,
) -> Ty<'tcx> { ) -> Ty<'tcx> {
debug!("impl_trait_ty_to_ty(def_id={:?}, lifetimes={:?})", def_id, lifetimes); debug!(?def_id, ?lifetimes);
let tcx = self.tcx(); let tcx = self.tcx();
let generics = tcx.generics_of(def_id); let generics = tcx.generics_of(def_id);
debug!(?generics);
debug!("impl_trait_ty_to_ty: generics={:?}", generics);
let args = ty::GenericArgs::for_item(tcx, def_id, |param, _| { let args = ty::GenericArgs::for_item(tcx, def_id, |param, _| {
// We use `generics.count() - lifetimes.len()` here instead of `generics.parent_count` // We use `generics.count() - lifetimes.len()` here instead of `generics.parent_count`
// since return-position impl trait in trait squashes all of the generics from its source fn // since return-position impl trait in trait squashes all of the generics from its source fn
@ -2474,7 +2463,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
tcx.mk_param_from_def(param) tcx.mk_param_from_def(param)
} }
}); });
debug!("impl_trait_ty_to_ty: args={:?}", args); debug!(?args);
if in_trait { if in_trait {
Ty::new_projection(tcx, def_id, args) Ty::new_projection(tcx, def_id, args)

View file

@ -19,6 +19,7 @@ use super::HirTyLowerer;
impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
/// Lower a trait object type from the HIR to our internal notion of a type. /// Lower a trait object type from the HIR to our internal notion of a type.
#[instrument(level = "debug", skip_all, ret)]
pub(super) fn lower_trait_object_ty( pub(super) fn lower_trait_object_ty(
&self, &self,
span: Span, span: Span,
@ -157,7 +158,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
for (base_trait_ref, span) in regular_traits_refs_spans { for (base_trait_ref, span) in regular_traits_refs_spans {
let base_pred: ty::Predicate<'tcx> = base_trait_ref.to_predicate(tcx); let base_pred: ty::Predicate<'tcx> = base_trait_ref.to_predicate(tcx);
for pred in traits::elaborate(tcx, [base_pred]).filter_only_self() { for pred in traits::elaborate(tcx, [base_pred]).filter_only_self() {
debug!("conv_object_ty_poly_trait_ref: observing object predicate `{:?}`", pred); debug!("observing object predicate `{pred:?}`");
let bound_predicate = pred.kind(); let bound_predicate = pred.kind();
match bound_predicate.skip_binder() { match bound_predicate.skip_binder() {
@ -244,8 +245,8 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
// the bounds // the bounds
let mut duplicates = FxHashSet::default(); let mut duplicates = FxHashSet::default();
auto_traits.retain(|i| duplicates.insert(i.trait_ref().def_id())); auto_traits.retain(|i| duplicates.insert(i.trait_ref().def_id()));
debug!("regular_traits: {:?}", regular_traits); debug!(?regular_traits);
debug!("auto_traits: {:?}", auto_traits); debug!(?auto_traits);
// Erase the `dummy_self` (`trait_object_dummy_self`) used above. // Erase the `dummy_self` (`trait_object_dummy_self`) used above.
let existential_trait_refs = regular_traits.iter().map(|i| { let existential_trait_refs = regular_traits.iter().map(|i| {
@ -390,10 +391,8 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
} }
}) })
}; };
debug!("region_bound: {:?}", region_bound); debug!(?region_bound);
let ty = Ty::new_dynamic(tcx, existential_predicates, region_bound, representation); Ty::new_dynamic(tcx, existential_predicates, region_bound, representation)
debug!("trait_object_type: {:?}", ty);
ty
} }
} }

View file

@ -343,8 +343,8 @@ impl<'tcx> ItemCtxt<'tcx> {
ItemCtxt { tcx, item_def_id, tainted_by_errors: Cell::new(None) } ItemCtxt { tcx, item_def_id, tainted_by_errors: Cell::new(None) }
} }
pub fn lower_ty(&self, ast_ty: &hir::Ty<'tcx>) -> Ty<'tcx> { pub fn lower_ty(&self, hir_ty: &hir::Ty<'tcx>) -> Ty<'tcx> {
self.lowerer().lower_ty(ast_ty) self.lowerer().lower_ty(hir_ty)
} }
pub fn hir_id(&self) -> hir::HirId { pub fn hir_id(&self) -> hir::HirId {
@ -546,9 +546,10 @@ fn get_new_lifetime_name<'tcx>(
(1..).flat_map(a_to_z_repeat_n).find(|lt| !existing_lifetimes.contains(lt.as_str())).unwrap() (1..).flat_map(a_to_z_repeat_n).find(|lt| !existing_lifetimes.contains(lt.as_str())).unwrap()
} }
#[instrument(level = "debug", skip_all)]
fn lower_item(tcx: TyCtxt<'_>, item_id: hir::ItemId) { fn lower_item(tcx: TyCtxt<'_>, item_id: hir::ItemId) {
let it = tcx.hir().item(item_id); let it = tcx.hir().item(item_id);
debug!("convert: item {} with id {}", it.ident, it.hir_id()); debug!(item = %it.ident, id = %it.hir_id());
let def_id = item_id.owner_id.def_id; let def_id = item_id.owner_id.def_id;
match &it.kind { match &it.kind {
@ -1532,19 +1533,19 @@ fn impl_trait_header(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option<ty::ImplTrai
impl_ impl_
.of_trait .of_trait
.as_ref() .as_ref()
.map(|ast_trait_ref| { .map(|hir_trait_ref| {
let selfty = tcx.type_of(def_id).instantiate_identity(); let self_ty = tcx.type_of(def_id).instantiate_identity();
let trait_ref = if let Some(ErrorGuaranteed { .. }) = check_impl_constness( let trait_ref = if let Some(ErrorGuaranteed { .. }) = check_impl_constness(
tcx, tcx,
tcx.is_const_trait_impl_raw(def_id.to_def_id()), tcx.is_const_trait_impl_raw(def_id.to_def_id()),
ast_trait_ref, hir_trait_ref,
) { ) {
// we have a const impl, but for a trait without `#[const_trait]`, so // we have a const impl, but for a trait without `#[const_trait]`, so
// without the host param. If we continue with the HIR trait ref, we get // without the host param. If we continue with the HIR trait ref, we get
// ICEs for generic arg count mismatch. We do a little HIR editing to // ICEs for generic arg count mismatch. We do a little HIR editing to
// make HIR ty lowering happy. // make HIR ty lowering happy.
let mut path_segments = ast_trait_ref.path.segments.to_vec(); let mut path_segments = hir_trait_ref.path.segments.to_vec();
let last_segment = path_segments.len() - 1; let last_segment = path_segments.len() - 1;
let mut args = *path_segments[last_segment].args(); let mut args = *path_segments[last_segment].args();
let last_arg = args.args.len() - 1; let last_arg = args.args.len() - 1;
@ -1552,14 +1553,14 @@ fn impl_trait_header(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option<ty::ImplTrai
args.args = &args.args[..args.args.len() - 1]; args.args = &args.args[..args.args.len() - 1];
path_segments[last_segment].args = Some(tcx.hir_arena.alloc(args)); path_segments[last_segment].args = Some(tcx.hir_arena.alloc(args));
let path = hir::Path { let path = hir::Path {
span: ast_trait_ref.path.span, span: hir_trait_ref.path.span,
res: ast_trait_ref.path.res, res: hir_trait_ref.path.res,
segments: tcx.hir_arena.alloc_slice(&path_segments), segments: tcx.hir_arena.alloc_slice(&path_segments),
}; };
let trait_ref = tcx.hir_arena.alloc(hir::TraitRef { path: tcx.hir_arena.alloc(path), hir_ref_id: ast_trait_ref.hir_ref_id }); let trait_ref = tcx.hir_arena.alloc(hir::TraitRef { path: tcx.hir_arena.alloc(path), hir_ref_id: hir_trait_ref.hir_ref_id });
icx.lowerer().lower_impl_trait_ref(trait_ref, selfty) icx.lowerer().lower_impl_trait_ref(trait_ref, self_ty)
} else { } else {
icx.lowerer().lower_impl_trait_ref(ast_trait_ref, selfty) icx.lowerer().lower_impl_trait_ref(hir_trait_ref, self_ty)
}; };
ty::ImplTraitHeader { ty::ImplTraitHeader {
trait_ref: ty::EarlyBinder::bind(trait_ref), trait_ref: ty::EarlyBinder::bind(trait_ref),
@ -1572,20 +1573,20 @@ fn impl_trait_header(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option<ty::ImplTrai
fn check_impl_constness( fn check_impl_constness(
tcx: TyCtxt<'_>, tcx: TyCtxt<'_>,
is_const: bool, is_const: bool,
ast_trait_ref: &hir::TraitRef<'_>, hir_trait_ref: &hir::TraitRef<'_>,
) -> Option<ErrorGuaranteed> { ) -> Option<ErrorGuaranteed> {
if !is_const { if !is_const {
return None; return None;
} }
let trait_def_id = ast_trait_ref.trait_def_id()?; let trait_def_id = hir_trait_ref.trait_def_id()?;
if tcx.has_attr(trait_def_id, sym::const_trait) { if tcx.has_attr(trait_def_id, sym::const_trait) {
return None; return None;
} }
let trait_name = tcx.item_name(trait_def_id).to_string(); let trait_name = tcx.item_name(trait_def_id).to_string();
Some(tcx.dcx().emit_err(errors::ConstImplForNonConstTrait { Some(tcx.dcx().emit_err(errors::ConstImplForNonConstTrait {
trait_ref_span: ast_trait_ref.path.span, trait_ref_span: hir_trait_ref.path.span,
trait_name, trait_name,
local_trait_span: local_trait_span:
trait_def_id.as_local().map(|_| tcx.def_span(trait_def_id).shrink_to_lo()), trait_def_id.as_local().map(|_| tcx.def_span(trait_def_id).shrink_to_lo()),
@ -1686,14 +1687,14 @@ fn compute_sig_of_foreign_fn_decl<'tcx>(
// Feature gate SIMD types in FFI, since I am not sure that the // Feature gate SIMD types in FFI, since I am not sure that the
// ABIs are handled at all correctly. -huonw // ABIs are handled at all correctly. -huonw
if abi != abi::Abi::RustIntrinsic && !tcx.features().simd_ffi { if abi != abi::Abi::RustIntrinsic && !tcx.features().simd_ffi {
let check = |ast_ty: &hir::Ty<'_>, ty: Ty<'_>| { let check = |hir_ty: &hir::Ty<'_>, ty: Ty<'_>| {
if ty.is_simd() { if ty.is_simd() {
let snip = tcx let snip = tcx
.sess .sess
.source_map() .source_map()
.span_to_snippet(ast_ty.span) .span_to_snippet(hir_ty.span)
.map_or_else(|_| String::new(), |s| format!(" `{s}`")); .map_or_else(|_| String::new(), |s| format!(" `{s}`"));
tcx.dcx().emit_err(errors::SIMDFFIHighlyExperimental { span: ast_ty.span, snip }); tcx.dcx().emit_err(errors::SIMDFFIHighlyExperimental { span: hir_ty.span, snip });
} }
}; };
for (input, ty) in iter::zip(decl.inputs, fty.inputs().skip_binder()) { for (input, ty) in iter::zip(decl.inputs, fty.inputs().skip_binder()) {

View file

@ -218,8 +218,7 @@ pub(super) fn generics_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Generics {
Deny, Deny,
} }
let no_generics = hir::Generics::empty(); let hir_generics = node.generics().unwrap_or(hir::Generics::empty());
let ast_generics = node.generics().unwrap_or(no_generics);
let (opt_self, allow_defaults) = match node { let (opt_self, allow_defaults) = match node {
Node::Item(item) => { Node::Item(item) => {
match item.kind { match item.kind {
@ -275,13 +274,13 @@ pub(super) fn generics_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Generics {
generics.parent_count + generics.params.len() generics.parent_count + generics.params.len()
}); });
let mut params: Vec<_> = Vec::with_capacity(ast_generics.params.len() + has_self as usize); let mut params: Vec<_> = Vec::with_capacity(hir_generics.params.len() + has_self as usize);
if let Some(opt_self) = opt_self { if let Some(opt_self) = opt_self {
params.push(opt_self); params.push(opt_self);
} }
let early_lifetimes = super::early_bound_lifetimes_from_generics(tcx, ast_generics); let early_lifetimes = super::early_bound_lifetimes_from_generics(tcx, hir_generics);
params.extend(early_lifetimes.enumerate().map(|(i, param)| ty::GenericParamDef { params.extend(early_lifetimes.enumerate().map(|(i, param)| ty::GenericParamDef {
name: param.name.ident().name, name: param.name.ident().name,
index: own_start + i as u32, index: own_start + i as u32,
@ -302,7 +301,7 @@ pub(super) fn generics_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Generics {
const TYPE_DEFAULT_NOT_ALLOWED: &'static str = "defaults for type parameters are only allowed in \ const TYPE_DEFAULT_NOT_ALLOWED: &'static str = "defaults for type parameters are only allowed in \
`struct`, `enum`, `type`, or `trait` definitions"; `struct`, `enum`, `type`, or `trait` definitions";
params.extend(ast_generics.params.iter().filter_map(|param| match param.kind { params.extend(hir_generics.params.iter().filter_map(|param| match param.kind {
GenericParamKind::Lifetime { .. } => None, GenericParamKind::Lifetime { .. } => None,
GenericParamKind::Type { default, synthetic, .. } => { GenericParamKind::Type { default, synthetic, .. } => {
if default.is_some() { if default.is_some() {

View file

@ -18,7 +18,7 @@ use rustc_span::Span;
fn associated_type_bounds<'tcx>( fn associated_type_bounds<'tcx>(
tcx: TyCtxt<'tcx>, tcx: TyCtxt<'tcx>,
assoc_item_def_id: LocalDefId, assoc_item_def_id: LocalDefId,
ast_bounds: &'tcx [hir::GenericBound<'tcx>], hir_bounds: &'tcx [hir::GenericBound<'tcx>],
span: Span, span: Span,
filter: PredicateFilter, filter: PredicateFilter,
) -> &'tcx [(ty::Clause<'tcx>, Span)] { ) -> &'tcx [(ty::Clause<'tcx>, Span)] {
@ -29,9 +29,9 @@ fn associated_type_bounds<'tcx>(
); );
let icx = ItemCtxt::new(tcx, assoc_item_def_id); let icx = ItemCtxt::new(tcx, assoc_item_def_id);
let mut bounds = icx.lowerer().lower_mono_bounds(item_ty, ast_bounds, filter); let mut bounds = icx.lowerer().lower_mono_bounds(item_ty, hir_bounds, filter);
// Associated types are implicitly sized unless a `?Sized` bound is found // Associated types are implicitly sized unless a `?Sized` bound is found
icx.lowerer().add_sized_bound(&mut bounds, item_ty, ast_bounds, None, span); icx.lowerer().add_sized_bound(&mut bounds, item_ty, hir_bounds, None, span);
let trait_def_id = tcx.local_parent(assoc_item_def_id); let trait_def_id = tcx.local_parent(assoc_item_def_id);
let trait_predicates = tcx.trait_explicit_predicates_and_bounds(trait_def_id); let trait_predicates = tcx.trait_explicit_predicates_and_bounds(trait_def_id);
@ -62,16 +62,16 @@ fn associated_type_bounds<'tcx>(
fn opaque_type_bounds<'tcx>( fn opaque_type_bounds<'tcx>(
tcx: TyCtxt<'tcx>, tcx: TyCtxt<'tcx>,
opaque_def_id: LocalDefId, opaque_def_id: LocalDefId,
ast_bounds: &'tcx [hir::GenericBound<'tcx>], hir_bounds: &'tcx [hir::GenericBound<'tcx>],
item_ty: Ty<'tcx>, item_ty: Ty<'tcx>,
span: Span, span: Span,
filter: PredicateFilter, filter: PredicateFilter,
) -> &'tcx [(ty::Clause<'tcx>, Span)] { ) -> &'tcx [(ty::Clause<'tcx>, Span)] {
ty::print::with_reduced_queries!({ ty::print::with_reduced_queries!({
let icx = ItemCtxt::new(tcx, opaque_def_id); let icx = ItemCtxt::new(tcx, opaque_def_id);
let mut bounds = icx.lowerer().lower_mono_bounds(item_ty, ast_bounds, filter); let mut bounds = icx.lowerer().lower_mono_bounds(item_ty, hir_bounds, filter);
// Opaque types are implicitly sized unless a `?Sized` bound is found // Opaque types are implicitly sized unless a `?Sized` bound is found
icx.lowerer().add_sized_bound(&mut bounds, item_ty, ast_bounds, None, span); icx.lowerer().add_sized_bound(&mut bounds, item_ty, hir_bounds, None, span);
debug!(?bounds); debug!(?bounds);
tcx.arena.alloc_from_iter(bounds.clauses()) tcx.arena.alloc_from_iter(bounds.clauses())

View file

@ -123,7 +123,7 @@ fn gather_explicit_predicates_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Gen
// Preserving the order of insertion is important here so as not to break UI tests. // Preserving the order of insertion is important here so as not to break UI tests.
let mut predicates: FxIndexSet<(ty::Clause<'_>, Span)> = FxIndexSet::default(); let mut predicates: FxIndexSet<(ty::Clause<'_>, Span)> = FxIndexSet::default();
let ast_generics = node.generics().unwrap_or(NO_GENERICS); let hir_generics = node.generics().unwrap_or(NO_GENERICS);
if let Node::Item(item) = node { if let Node::Item(item) = node {
match item.kind { match item.kind {
ItemKind::Impl(impl_) => { ItemKind::Impl(impl_) => {
@ -170,7 +170,7 @@ fn gather_explicit_predicates_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Gen
// Collect the predicates that were written inline by the user on each // Collect the predicates that were written inline by the user on each
// type parameter (e.g., `<T: Foo>`). Also add `ConstArgHasType` predicates // type parameter (e.g., `<T: Foo>`). Also add `ConstArgHasType` predicates
// for each const parameter. // for each const parameter.
for param in ast_generics.params { for param in hir_generics.params {
match param.kind { match param.kind {
// We already dealt with early bound lifetimes above. // We already dealt with early bound lifetimes above.
GenericParamKind::Lifetime { .. } => (), GenericParamKind::Lifetime { .. } => (),
@ -182,7 +182,7 @@ fn gather_explicit_predicates_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Gen
&mut bounds, &mut bounds,
param_ty, param_ty,
&[], &[],
Some((param.def_id, ast_generics.predicates)), Some((param.def_id, hir_generics.predicates)),
param.span, param.span,
); );
trace!(?bounds); trace!(?bounds);
@ -205,7 +205,7 @@ fn gather_explicit_predicates_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Gen
trace!(?predicates); trace!(?predicates);
// Add in the bounds that appear in the where-clause. // Add in the bounds that appear in the where-clause.
for predicate in ast_generics.predicates { for predicate in hir_generics.predicates {
match predicate { match predicate {
hir::WherePredicate::BoundPredicate(bound_pred) => { hir::WherePredicate::BoundPredicate(bound_pred) => {
let ty = icx.lower_ty(bound_pred.bounded_ty); let ty = icx.lower_ty(bound_pred.bounded_ty);
@ -684,7 +684,7 @@ pub(super) fn type_param_predicates(
let item_hir_id = tcx.local_def_id_to_hir_id(item_def_id); let item_hir_id = tcx.local_def_id_to_hir_id(item_def_id);
let hir_node = tcx.hir_node(item_hir_id); let hir_node = tcx.hir_node(item_hir_id);
let Some(ast_generics) = hir_node.generics() else { return result }; let Some(hir_generics) = hir_node.generics() else { return result };
if let Node::Item(item) = hir_node if let Node::Item(item) = hir_node
&& let ItemKind::Trait(..) = item.kind && let ItemKind::Trait(..) = item.kind
// Implied `Self: Trait` and supertrait bounds. // Implied `Self: Trait` and supertrait bounds.
@ -697,7 +697,7 @@ pub(super) fn type_param_predicates(
let icx = ItemCtxt::new(tcx, item_def_id); let icx = ItemCtxt::new(tcx, item_def_id);
let extra_predicates = extend.into_iter().chain( let extra_predicates = extend.into_iter().chain(
icx.probe_ty_param_bounds_in_generics( icx.probe_ty_param_bounds_in_generics(
ast_generics, hir_generics,
def_id, def_id,
ty, ty,
PredicateFilter::SelfThatDefines(assoc_name), PredicateFilter::SelfThatDefines(assoc_name),
@ -719,17 +719,17 @@ impl<'tcx> ItemCtxt<'tcx> {
/// This requires scanning through the HIR. /// This requires scanning through the HIR.
/// We do this to avoid having to lower *all* the bounds, which would create artificial cycles. /// We do this to avoid having to lower *all* the bounds, which would create artificial cycles.
/// Instead, we can only lower the bounds for a type parameter `X` if `X::Foo` is used. /// Instead, we can only lower the bounds for a type parameter `X` if `X::Foo` is used.
#[instrument(level = "trace", skip(self, ast_generics))] #[instrument(level = "trace", skip(self, hir_generics))]
fn probe_ty_param_bounds_in_generics( fn probe_ty_param_bounds_in_generics(
&self, &self,
ast_generics: &'tcx hir::Generics<'tcx>, hir_generics: &'tcx hir::Generics<'tcx>,
param_def_id: LocalDefId, param_def_id: LocalDefId,
ty: Ty<'tcx>, ty: Ty<'tcx>,
filter: PredicateFilter, filter: PredicateFilter,
) -> Vec<(ty::Clause<'tcx>, Span)> { ) -> Vec<(ty::Clause<'tcx>, Span)> {
let mut bounds = Bounds::default(); let mut bounds = Bounds::default();
for predicate in ast_generics.predicates { for predicate in hir_generics.predicates {
let hir::WherePredicate::BoundPredicate(predicate) = predicate else { let hir::WherePredicate::BoundPredicate(predicate) = predicate else {
continue; continue;
}; };

View file

@ -1679,7 +1679,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
expr: &hir::Expr<'_>, expr: &hir::Expr<'_>,
span: Span, span: Span,
variant: &'tcx ty::VariantDef, variant: &'tcx ty::VariantDef,
ast_fields: &'tcx [hir::ExprField<'tcx>], hir_fields: &'tcx [hir::ExprField<'tcx>],
base_expr: &'tcx Option<&'tcx hir::Expr<'tcx>>, base_expr: &'tcx Option<&'tcx hir::Expr<'tcx>>,
) { ) {
let tcx = self.tcx; let tcx = self.tcx;
@ -1710,7 +1710,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let mut error_happened = false; let mut error_happened = false;
// Type-check each field. // Type-check each field.
for (idx, field) in ast_fields.iter().enumerate() { for (idx, field) in hir_fields.iter().enumerate() {
let ident = tcx.adjust_ident(field.ident, variant.def_id); let ident = tcx.adjust_ident(field.ident, variant.def_id);
let field_type = if let Some((i, v_field)) = remaining_fields.remove(&ident) { let field_type = if let Some((i, v_field)) = remaining_fields.remove(&ident) {
seen_fields.insert(ident, field.span); seen_fields.insert(ident, field.span);
@ -1739,7 +1739,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
variant, variant,
expr, expr,
field, field,
ast_fields, hir_fields,
adt.variant_descr(), adt.variant_descr(),
) )
}; };
@ -1754,7 +1754,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
self.demand_coerce_diag(field.expr, ty, field_type, None, AllowTwoPhase::No); self.demand_coerce_diag(field.expr, ty, field_type, None, AllowTwoPhase::No);
if let Some(diag) = diag { if let Some(diag) = diag {
if idx == ast_fields.len() - 1 { if idx == hir_fields.len() - 1 {
if remaining_fields.is_empty() { if remaining_fields.is_empty() {
self.suggest_fru_from_range_and_emit(field, variant, args, diag); self.suggest_fru_from_range_and_emit(field, variant, args, diag);
} else { } else {
@ -1768,7 +1768,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
// Make sure the programmer specified correct number of fields. // Make sure the programmer specified correct number of fields.
if adt_kind == AdtKind::Union { if adt_kind == AdtKind::Union {
if ast_fields.len() != 1 { if hir_fields.len() != 1 {
struct_span_code_err!( struct_span_code_err!(
tcx.dcx(), tcx.dcx(),
span, span,
@ -1905,14 +1905,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
.collect(); .collect();
if !private_fields.is_empty() { if !private_fields.is_empty() {
self.report_private_fields(adt_ty, span, expr.span, private_fields, ast_fields); self.report_private_fields(adt_ty, span, expr.span, private_fields, hir_fields);
} else { } else {
self.report_missing_fields( self.report_missing_fields(
adt_ty, adt_ty,
span, span,
remaining_fields, remaining_fields,
variant, variant,
ast_fields, hir_fields,
args, args,
); );
} }
@ -1949,7 +1949,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
span: Span, span: Span,
remaining_fields: UnordMap<Ident, (FieldIdx, &ty::FieldDef)>, remaining_fields: UnordMap<Ident, (FieldIdx, &ty::FieldDef)>,
variant: &'tcx ty::VariantDef, variant: &'tcx ty::VariantDef,
ast_fields: &'tcx [hir::ExprField<'tcx>], hir_fields: &'tcx [hir::ExprField<'tcx>],
args: GenericArgsRef<'tcx>, args: GenericArgsRef<'tcx>,
) { ) {
let len = remaining_fields.len(); let len = remaining_fields.len();
@ -1986,8 +1986,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
); );
err.span_label(span, format!("missing {remaining_fields_names}{truncated_fields_error}")); err.span_label(span, format!("missing {remaining_fields_names}{truncated_fields_error}"));
if let Some(last) = ast_fields.last() { if let Some(hir_field) = hir_fields.last() {
self.suggest_fru_from_range_and_emit(last, variant, args, err); self.suggest_fru_from_range_and_emit(hir_field, variant, args, err);
} else { } else {
err.emit(); err.emit();
} }

View file

@ -392,20 +392,21 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
} }
} }
pub fn lower_ty(&self, ast_t: &hir::Ty<'tcx>) -> LoweredTy<'tcx> { pub fn lower_ty(&self, hir_ty: &hir::Ty<'tcx>) -> LoweredTy<'tcx> {
let t = self.lowerer().lower_ty(ast_t); let ty = self.lowerer().lower_ty(hir_ty);
self.register_wf_obligation(t.into(), ast_t.span, traits::WellFormed(None)); self.register_wf_obligation(ty.into(), hir_ty.span, traits::WellFormed(None));
LoweredTy::from_raw(self, ast_t.span, t) LoweredTy::from_raw(self, hir_ty.span, ty)
} }
pub fn lower_ty_saving_user_provided_ty(&self, ast_ty: &hir::Ty<'tcx>) -> Ty<'tcx> { #[instrument(level = "debug", skip_all)]
let ty = self.lower_ty(ast_ty); pub fn lower_ty_saving_user_provided_ty(&self, hir_ty: &hir::Ty<'tcx>) -> Ty<'tcx> {
debug!("to_ty_saving_user_provided_ty: ty={:?}", ty); let ty = self.lower_ty(hir_ty);
debug!(?ty);
if Self::can_contain_user_lifetime_bounds(ty.raw) { if Self::can_contain_user_lifetime_bounds(ty.raw) {
let c_ty = self.canonicalize_response(UserType::Ty(ty.raw)); let c_ty = self.canonicalize_response(UserType::Ty(ty.raw));
debug!("to_ty_saving_user_provided_ty: c_ty={:?}", c_ty); debug!(?c_ty);
self.typeck_results.borrow_mut().user_provided_types_mut().insert(ast_ty.hir_id, c_ty); self.typeck_results.borrow_mut().user_provided_types_mut().insert(hir_ty.hir_id, c_ty);
} }
ty.normalized ty.normalized
@ -434,16 +435,16 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
} }
} }
pub fn lower_const_arg(&self, ast_c: &hir::AnonConst, param_def_id: DefId) -> ty::Const<'tcx> { pub fn lower_const_arg(&self, hir_ct: &hir::AnonConst, param_def_id: DefId) -> ty::Const<'tcx> {
let did = ast_c.def_id; let did = hir_ct.def_id;
self.tcx.feed_anon_const_type(did, self.tcx.type_of(param_def_id)); self.tcx.feed_anon_const_type(did, self.tcx.type_of(param_def_id));
let c = ty::Const::from_anon_const(self.tcx, did); let ct = ty::Const::from_anon_const(self.tcx, did);
self.register_wf_obligation( self.register_wf_obligation(
c.into(), ct.into(),
self.tcx.hir().span(ast_c.hir_id), self.tcx.hir().span(hir_ct.hir_id),
ObligationCauseCode::WellFormed(None), ObligationCauseCode::WellFormed(None),
); );
c ct
} }
// If the type given by the user has free regions, save it for later, since // If the type given by the user has free regions, save it for later, since

View file

@ -3264,8 +3264,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
Colon, Colon,
Nothing, Nothing,
} }
let ast_generics = hir.get_generics(id.owner.def_id).unwrap(); let hir_generics = hir.get_generics(id.owner.def_id).unwrap();
let trait_def_ids: DefIdSet = ast_generics let trait_def_ids: DefIdSet = hir_generics
.bounds_for_param(def_id) .bounds_for_param(def_id)
.flat_map(|bp| bp.bounds.iter()) .flat_map(|bp| bp.bounds.iter())
.filter_map(|bound| bound.trait_ref()?.trait_def_id()) .filter_map(|bound| bound.trait_ref()?.trait_def_id())
@ -3277,7 +3277,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
"restrict type parameter `{}` with", "restrict type parameter `{}` with",
param.name.ident(), param.name.ident(),
)); ));
let bounds_span = ast_generics.bounds_span_for_suggestions(def_id); let bounds_span = hir_generics.bounds_span_for_suggestions(def_id);
if rcvr_ty.is_ref() && param.is_impl_trait() && bounds_span.is_some() { if rcvr_ty.is_ref() && param.is_impl_trait() && bounds_span.is_some() {
err.multipart_suggestions( err.multipart_suggestions(
msg, msg,

View file

@ -37,6 +37,7 @@ pub use crate::traits::{MethodViolationCode, ObjectSafetyViolation};
/// Currently that is `Self` in supertraits. This is needed /// Currently that is `Self` in supertraits. This is needed
/// because `object_safety_violations` can't be used during /// because `object_safety_violations` can't be used during
/// type collection. /// type collection.
#[instrument(level = "debug", skip(tcx))]
pub fn hir_ty_lowering_object_safety_violations( pub fn hir_ty_lowering_object_safety_violations(
tcx: TyCtxt<'_>, tcx: TyCtxt<'_>,
trait_def_id: DefId, trait_def_id: DefId,
@ -47,9 +48,7 @@ pub fn hir_ty_lowering_object_safety_violations(
.filter(|spans| !spans.is_empty()) .filter(|spans| !spans.is_empty())
.map(ObjectSafetyViolation::SupertraitSelf) .map(ObjectSafetyViolation::SupertraitSelf)
.collect(); .collect();
debug!(?violations);
debug!("astconv_object_safety_violations(trait_def_id={:?}) = {:?}", trait_def_id, violations);
violations violations
} }