diff --git a/compiler/rustc_ast/src/visit.rs b/compiler/rustc_ast/src/visit.rs index 8d084ee29a7db..e2a7c1c1a2cb7 100644 --- a/compiler/rustc_ast/src/visit.rs +++ b/compiler/rustc_ast/src/visit.rs @@ -466,7 +466,7 @@ pub fn walk_use_tree<'a, V: Visitor<'a>>(visitor: &mut V, use_tree: &'a UseTree, visitor.visit_path(&use_tree.prefix, id); match &use_tree.kind { UseTreeKind::Simple(rename) => { - // The extra IDs are handled during HIR lowering. + // The extra IDs are handled during AST lowering. if let &Some(rename) = rename { visitor.visit_ident(rename); } diff --git a/compiler/rustc_ast_lowering/src/delegation.rs b/compiler/rustc_ast_lowering/src/delegation.rs index d1ba93f067553..494eea58699fd 100644 --- a/compiler/rustc_ast_lowering/src/delegation.rs +++ b/compiler/rustc_ast_lowering/src/delegation.rs @@ -29,11 +29,12 @@ //! item id (`item_id`) in case of impl trait or path resolution id (`path_id`) otherwise. //! //! Since we do not have a proper way to obtain function type information by path resolution -//! in AST, we mark each function parameter type as `InferDelegation` and inherit it in `AstConv`. +//! in AST, we mark each function parameter type as `InferDelegation` and inherit it during +//! HIR/ty lowering. //! //! Similarly generics, predicates and header are set to the "default" values. //! In case of discrepancy with callee function the `NotSupportedDelegation` error will -//! also be emitted in `AstConv`. +//! also be emitted during HIR/ty lowering. use crate::{ImplTraitPosition, ResolverAstLoweringExt}; @@ -133,7 +134,7 @@ impl<'hir> LoweringContext<'_, 'hir> { ) -> &'hir hir::FnDecl<'hir> { let args_count = if let Some(local_sig_id) = sig_id.as_local() { // Map may be filled incorrectly due to recursive delegation. - // Error will be emmited later in astconv. + // Error will be emitted later during HIR/ty lowering. self.resolver.fn_parameter_counts.get(&local_sig_id).cloned().unwrap_or_default() } else { self.tcx.fn_arg_names(sig_id).len() diff --git a/compiler/rustc_ast_lowering/src/item.rs b/compiler/rustc_ast_lowering/src/item.rs index fb52f9cf58f26..5cbffea7c41fc 100644 --- a/compiler/rustc_ast_lowering/src/item.rs +++ b/compiler/rustc_ast_lowering/src/item.rs @@ -1413,8 +1413,8 @@ impl<'hir> LoweringContext<'_, 'hir> { // Error if `?Trait` bounds in where clauses don't refer directly to type parameters. // Note: we used to clone these bounds directly onto the type parameter (and avoid lowering // these into hir when we lower thee where clauses), but this makes it quite difficult to - // keep track of the Span info. Now, `add_implicitly_sized` in `AstConv` checks both param bounds and - // where clauses for `?Sized`. + // keep track of the Span info. Now, `::add_implicitly_sized` checks both + // param bounds and where clauses for `?Sized`. for pred in &generics.where_clause.predicates { let WherePredicate::BoundPredicate(bound_pred) = pred else { continue; diff --git a/compiler/rustc_borrowck/src/diagnostics/region_name.rs b/compiler/rustc_borrowck/src/diagnostics/region_name.rs index e008d230656f9..148ec60898f2c 100644 --- a/compiler/rustc_borrowck/src/diagnostics/region_name.rs +++ b/compiler/rustc_borrowck/src/diagnostics/region_name.rs @@ -626,7 +626,7 @@ impl<'tcx> MirBorrowckCtxt<'_, 'tcx> { | GenericArgKind::Const(_), _, ) => { - // HIR lowering sometimes doesn't catch this in erroneous + // HIR/ty lowering sometimes doesn't catch this in erroneous // programs, so we need to use span_delayed_bug here. See #82126. self.dcx().span_delayed_bug( hir_arg.span(), diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index abf7a695fd2d1..5a0376b2a63da 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -1845,7 +1845,7 @@ pub enum ExprKind<'hir> { /// Wraps the expression in a terminating scope. /// This makes it semantically equivalent to `{ let _t = expr; _t }`. /// - /// This construct only exists to tweak the drop order in HIR lowering. + /// This construct only exists to tweak the drop order in AST lowering. /// An example of that is the desugaring of `for` loops. DropTemps(&'hir Expr<'hir>), /// A `let $pat = $expr` expression. @@ -2278,7 +2278,7 @@ pub enum ImplItemKind<'hir> { /// Bind a type to an associated type (i.e., `A = Foo`). /// /// Bindings like `A: Debug` are represented as a special type `A = -/// $::Debug` that is understood by the astconv code. +/// $::Debug` that is understood by the HIR/ty lowering code. /// /// FIXME(alexreg): why have a separate type for the binding case, /// wouldn't it be better to make the `ty` field an enum like the diff --git a/compiler/rustc_hir_analysis/src/bounds.rs b/compiler/rustc_hir_analysis/src/bounds.rs index b69f679880dbf..d659d2c5235e8 100644 --- a/compiler/rustc_hir_analysis/src/bounds.rs +++ b/compiler/rustc_hir_analysis/src/bounds.rs @@ -1,5 +1,5 @@ -//! Bounds are restrictions applied to some types after they've been converted into the -//! `ty` form from the HIR. +//! Bounds are restrictions applied to some types after they've been lowered from the HIR to the +//! [`rustc_middle::ty`] form. use rustc_hir::LangItem; use rustc_middle::ty::{self, ToPredicate, Ty, TyCtxt}; diff --git a/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs b/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs index 6edd68f1baebe..55b9254a46be2 100644 --- a/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs +++ b/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs @@ -745,7 +745,7 @@ pub(super) fn collect_return_position_impl_trait_in_trait_tys<'tcx>( // We may not collect all RPITITs that we see in the HIR for a trait signature // because an RPITIT was located within a missing item. Like if we have a sig - // returning `-> Missing`, that gets converted to `-> [type error]`, + // returning `-> Missing`, that gets converted to `-> {type error}`, // and when walking through the signature we end up never collecting the def id // of the `impl Sized`. Insert that here, so we don't ICE later. for assoc_item in tcx.associated_types_for_impl_traits_in_associated_fn(trait_m.def_id) { diff --git a/compiler/rustc_hir_analysis/src/check/region.rs b/compiler/rustc_hir_analysis/src/check/region.rs index 1c0a1a6951398..d0233888d8c71 100644 --- a/compiler/rustc_hir_analysis/src/check/region.rs +++ b/compiler/rustc_hir_analysis/src/check/region.rs @@ -765,7 +765,7 @@ impl<'tcx> RegionResolutionVisitor<'tcx> { fn enter_node_scope_with_dtor(&mut self, id: hir::ItemLocalId) { // If node was previously marked as a terminating scope during the - // recursive visit of its parent node in the AST, then we need to + // recursive visit of its parent node in the HIR, then we need to // account for the destruction scope representing the scope of // the destructors that run immediately after it completes. if self.terminating_scopes.contains(&id) { diff --git a/compiler/rustc_hir_analysis/src/check/wfcheck.rs b/compiler/rustc_hir_analysis/src/check/wfcheck.rs index 646a84b043c82..907dda5cc235b 100644 --- a/compiler/rustc_hir_analysis/src/check/wfcheck.rs +++ b/compiler/rustc_hir_analysis/src/check/wfcheck.rs @@ -265,7 +265,7 @@ fn check_item<'tcx>(tcx: TyCtxt<'tcx>, item: &'tcx hir::Item<'tcx>) -> Result<() } ty::ImplPolarity::Negative => { let ast::ImplPolarity::Negative(span) = impl_.polarity else { - bug!("impl_polarity query disagrees with impl's polarity in AST"); + bug!("impl_polarity query disagrees with impl's polarity in HIR"); }; // FIXME(#27579): what amount of WF checking do we need for neg impls? if let hir::Defaultness::Default { .. } = impl_.defaultness { @@ -295,31 +295,31 @@ fn check_item<'tcx>(tcx: TyCtxt<'tcx>, item: &'tcx hir::Item<'tcx>) -> Result<() hir::ItemKind::Const(ty, ..) => { check_item_type(tcx, def_id, ty.span, UnsizedHandling::Forbid) } - hir::ItemKind::Struct(_, ast_generics) => { + hir::ItemKind::Struct(_, hir_generics) => { let res = check_type_defn(tcx, item, false); - check_variances_for_type_defn(tcx, item, ast_generics); + check_variances_for_type_defn(tcx, item, hir_generics); res } - hir::ItemKind::Union(_, ast_generics) => { + hir::ItemKind::Union(_, hir_generics) => { let res = check_type_defn(tcx, item, true); - check_variances_for_type_defn(tcx, item, ast_generics); + check_variances_for_type_defn(tcx, item, hir_generics); res } - hir::ItemKind::Enum(_, ast_generics) => { + hir::ItemKind::Enum(_, hir_generics) => { let res = check_type_defn(tcx, item, true); - check_variances_for_type_defn(tcx, item, ast_generics); + check_variances_for_type_defn(tcx, item, hir_generics); res } hir::ItemKind::Trait(..) => check_trait(tcx, item), hir::ItemKind::TraitAlias(..) => check_trait(tcx, item), // `ForeignItem`s are handled separately. hir::ItemKind::ForeignMod { .. } => Ok(()), - hir::ItemKind::TyAlias(hir_ty, ast_generics) => { + hir::ItemKind::TyAlias(hir_ty, hir_generics) => { if tcx.type_alias_is_lazy(item.owner_id) { // Bounds of lazy type aliases and of eager ones that contain opaque types are respected. // E.g: `type X = impl Trait;`, `type X = (impl Trait, Y);`. let res = check_item_type(tcx, def_id, hir_ty.span, UnsizedHandling::Allow); - check_variances_for_type_defn(tcx, item, ast_generics); + check_variances_for_type_defn(tcx, item, hir_generics); res } else { Ok(()) @@ -1282,16 +1282,16 @@ fn check_item_type( }) } -#[instrument(level = "debug", skip(tcx, ast_self_ty, ast_trait_ref))] +#[instrument(level = "debug", skip(tcx, hir_self_ty, hir_trait_ref))] fn check_impl<'tcx>( tcx: TyCtxt<'tcx>, item: &'tcx hir::Item<'tcx>, - ast_self_ty: &hir::Ty<'_>, - ast_trait_ref: &Option>, + hir_self_ty: &hir::Ty<'_>, + hir_trait_ref: &Option>, ) -> Result<(), ErrorGuaranteed> { enter_wf_checking_ctxt(tcx, item.span, item.owner_id.def_id, |wfcx| { - match ast_trait_ref { - Some(ast_trait_ref) => { + match hir_trait_ref { + Some(hir_trait_ref) => { // `#[rustc_reservation_impl]` impls are not real impls and // therefore don't need to be WF (the trait's `Self: Trait` predicate // won't hold). @@ -1300,7 +1300,7 @@ fn check_impl<'tcx>( // other `Foo` impls are incoherent. tcx.ensure().coherent_trait(trait_ref.def_id)?; let trait_ref = wfcx.normalize( - ast_trait_ref.path.span, + hir_trait_ref.path.span, Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)), trait_ref, ); @@ -1311,14 +1311,14 @@ fn check_impl<'tcx>( wfcx.param_env, wfcx.body_def_id, trait_pred, - ast_trait_ref.path.span, + hir_trait_ref.path.span, item, ); for obligation in &mut obligations { if let Some(pred) = obligation.predicate.to_opt_poly_trait_pred() && pred.self_ty().skip_binder() == trait_ref.self_ty() { - obligation.cause.span = ast_self_ty.span; + obligation.cause.span = hir_self_ty.span; } } debug!(?obligations); @@ -1332,7 +1332,7 @@ fn check_impl<'tcx>( self_ty, ); wfcx.register_wf_obligation( - ast_self_ty.span, + hir_self_ty.span, Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)), self_ty.into(), ); @@ -1835,7 +1835,7 @@ fn check_variances_for_type_defn<'tcx>( .iter() .filter_map(|predicate| match predicate { hir::WherePredicate::BoundPredicate(predicate) => { - match icx.to_ty(predicate.bounded_ty).kind() { + match icx.lower_ty(predicate.bounded_ty).kind() { ty::Param(data) => Some(Parameter(data.index)), _ => None, } diff --git a/compiler/rustc_hir_analysis/src/collect.rs b/compiler/rustc_hir_analysis/src/collect.rs index fbcebb7c87c9b..66fbcd9ea92d0 100644 --- a/compiler/rustc_hir_analysis/src/collect.rs +++ b/compiler/rustc_hir_analysis/src/collect.rs @@ -39,9 +39,9 @@ use std::cell::Cell; use std::iter; use std::ops::Bound; -use crate::astconv::AstConv; use crate::check::intrinsic::intrinsic_operation_unsafety; use crate::errors; +use crate::lowering::HirTyLowerer; pub use type_of::test_opaque_hidden_types; mod generics_of; @@ -90,13 +90,12 @@ pub fn provide(providers: &mut Providers) { /////////////////////////////////////////////////////////////////////////// -/// Context specific to some particular item. This is what implements -/// [`AstConv`]. +/// Context specific to some particular item. This is what implements [`HirTyLowerer`]. /// /// # `ItemCtxt` vs `FnCtxt` /// /// `ItemCtxt` is primarily used to type-check item signatures and lower them -/// from HIR to their [`ty::Ty`] representation, which is exposed using [`AstConv`]. +/// from HIR to their [`ty::Ty`] representation, which is exposed using [`HirTyLowerer`]. /// It's also used for the bodies of items like structs where the body (the fields) /// are just signatures. /// @@ -113,11 +112,11 @@ pub fn provide(providers: &mut Providers) { /// `ItemCtxt` has information about the predicates that are defined /// on the trait. Unfortunately, this predicate information is /// available in various different forms at various points in the -/// process. So we can't just store a pointer to e.g., the AST or the +/// process. So we can't just store a pointer to e.g., the HIR or the /// parsed ty form, we have to be more flexible. To this end, the /// `ItemCtxt` is parameterized by a `DefId` that it uses to satisfy /// `get_type_parameter_bounds` requests, drawing the information from -/// the AST (`hir::Generics`), recursively. +/// the HIR (`hir::Generics`), recursively. pub struct ItemCtxt<'tcx> { tcx: TyCtxt<'tcx>, item_def_id: LocalDefId, @@ -282,7 +281,7 @@ impl<'tcx> Visitor<'tcx> for CollectItemTypesVisitor<'tcx> { } fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) { - convert_item(self.tcx, item.item_id()); + lower_item(self.tcx, item.item_id()); reject_placeholder_type_signatures_in_item(self.tcx, item); intravisit::walk_item(self, item); } @@ -320,12 +319,12 @@ impl<'tcx> Visitor<'tcx> for CollectItemTypesVisitor<'tcx> { } fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) { - convert_trait_item(self.tcx, trait_item.trait_item_id()); + lower_trait_item(self.tcx, trait_item.trait_item_id()); intravisit::walk_trait_item(self, trait_item); } fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) { - convert_impl_item(self.tcx, impl_item.impl_item_id()); + lower_impl_item(self.tcx, impl_item.impl_item_id()); intravisit::walk_impl_item(self, impl_item); } } @@ -349,8 +348,8 @@ impl<'tcx> ItemCtxt<'tcx> { ItemCtxt { tcx, item_def_id, tainted_by_errors: Cell::new(None) } } - pub fn to_ty(&self, ast_ty: &hir::Ty<'tcx>) -> Ty<'tcx> { - self.astconv().ast_ty_to_ty(ast_ty) + pub fn lower_ty(&self, hir_ty: &hir::Ty<'tcx>) -> Ty<'tcx> { + self.lowerer().lower_ty(hir_ty) } pub fn hir_id(&self) -> hir::HirId { @@ -369,7 +368,7 @@ impl<'tcx> ItemCtxt<'tcx> { } } -impl<'tcx> AstConv<'tcx> for ItemCtxt<'tcx> { +impl<'tcx> HirTyLowerer<'tcx> for ItemCtxt<'tcx> { fn tcx(&self) -> TyCtxt<'tcx> { self.tcx } @@ -417,7 +416,7 @@ impl<'tcx> AstConv<'tcx> for ItemCtxt<'tcx> { poly_trait_ref: ty::PolyTraitRef<'tcx>, ) -> Ty<'tcx> { if let Some(trait_ref) = poly_trait_ref.no_bound_vars() { - let item_args = self.astconv().create_args_for_associated_item( + let item_args = self.lowerer().lower_args_for_assoc_item( span, item_def_id, item_segment, @@ -552,9 +551,9 @@ fn get_new_lifetime_name<'tcx>( (1..).flat_map(a_to_z_repeat_n).find(|lt| !existing_lifetimes.contains(lt.as_str())).unwrap() } -fn convert_item(tcx: TyCtxt<'_>, item_id: hir::ItemId) { +fn lower_item(tcx: TyCtxt<'_>, item_id: hir::ItemId) { let it = tcx.hir().item(item_id); - debug!("convert: item {} with id {}", it.ident, it.hir_id()); + debug!("lower_item: item {} with id {}", it.ident, it.hir_id()); let def_id = item_id.owner_id.def_id; match &it.kind { @@ -596,7 +595,7 @@ fn convert_item(tcx: TyCtxt<'_>, item_id: hir::ItemId) { tcx.ensure().generics_of(def_id); tcx.ensure().type_of(def_id); tcx.ensure().predicates_of(def_id); - convert_enum_variant_types(tcx, def_id.to_def_id()); + lower_enum_variant_types(tcx, def_id.to_def_id()); } hir::ItemKind::Impl { .. } => { tcx.ensure().generics_of(def_id); @@ -628,7 +627,7 @@ fn convert_item(tcx: TyCtxt<'_>, item_id: hir::ItemId) { } if let Some(ctor_def_id) = struct_def.ctor_def_id() { - convert_variant_ctor(tcx, ctor_def_id); + lower_variant_ctor(tcx, ctor_def_id); } } @@ -669,7 +668,7 @@ fn convert_item(tcx: TyCtxt<'_>, item_id: hir::ItemId) { } } -fn convert_trait_item(tcx: TyCtxt<'_>, trait_item_id: hir::TraitItemId) { +fn lower_trait_item(tcx: TyCtxt<'_>, trait_item_id: hir::TraitItemId) { let trait_item = tcx.hir().trait_item(trait_item_id); let def_id = trait_item_id.owner_id; tcx.ensure().generics_of(def_id); @@ -716,7 +715,7 @@ fn convert_trait_item(tcx: TyCtxt<'_>, trait_item_id: hir::TraitItemId) { tcx.ensure().predicates_of(def_id); } -fn convert_impl_item(tcx: TyCtxt<'_>, impl_item_id: hir::ImplItemId) { +fn lower_impl_item(tcx: TyCtxt<'_>, impl_item_id: hir::ImplItemId) { let def_id = impl_item_id.owner_id; tcx.ensure().generics_of(def_id); tcx.ensure().type_of(def_id); @@ -745,13 +744,13 @@ fn convert_impl_item(tcx: TyCtxt<'_>, impl_item_id: hir::ImplItemId) { } } -fn convert_variant_ctor(tcx: TyCtxt<'_>, def_id: LocalDefId) { +fn lower_variant_ctor(tcx: TyCtxt<'_>, def_id: LocalDefId) { tcx.ensure().generics_of(def_id); tcx.ensure().type_of(def_id); tcx.ensure().predicates_of(def_id); } -fn convert_enum_variant_types(tcx: TyCtxt<'_>, def_id: DefId) { +fn lower_enum_variant_types(tcx: TyCtxt<'_>, def_id: DefId) { let def = tcx.adt_def(def_id); let repr_type = def.repr().discr_type(); let initial = repr_type.initial_discriminant(tcx); @@ -787,12 +786,12 @@ fn convert_enum_variant_types(tcx: TyCtxt<'_>, def_id: DefId) { // Convert the ctor, if any. This also registers the variant as // an item. if let Some(ctor_def_id) = variant.ctor_def_id() { - convert_variant_ctor(tcx, ctor_def_id.expect_local()); + lower_variant_ctor(tcx, ctor_def_id.expect_local()); } } } -fn convert_variant( +fn lower_variant( tcx: TyCtxt<'_>, variant_did: Option, ident: Ident, @@ -866,7 +865,7 @@ fn adt_def(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::AdtDef<'_> { }; distance_from_explicit += 1; - convert_variant( + lower_variant( tcx, Some(v.def_id), v.ident, @@ -885,7 +884,7 @@ fn adt_def(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::AdtDef<'_> { ItemKind::Struct(..) => AdtKind::Struct, _ => AdtKind::Union, }; - let variants = std::iter::once(convert_variant( + let variants = std::iter::once(lower_variant( tcx, None, item.ident, @@ -1088,7 +1087,7 @@ fn fn_sig(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::EarlyBinder, def_id: LocalDefId) -> ty::EarlyBinder { - icx.astconv().ty_of_fn(hir_id, header.unsafety, header.abi, decl, Some(generics), None) - } + }) => icx.lowerer().lower_fn_ty( + hir_id, + header.unsafety, + header.abi, + decl, + Some(generics), + None, + ), ForeignItem(&hir::ForeignItem { kind: ForeignItemKind::Fn(fn_decl, _, _), .. }) => { let abi = tcx.hir().get_foreign_abi(hir_id); @@ -1215,7 +1219,7 @@ fn infer_return_ty_for_fn_sig<'tcx>( )) } } - None => icx.astconv().ty_of_fn( + None => icx.lowerer().lower_fn_ty( hir_id, sig.header.unsafety, sig.header.abi, @@ -1335,19 +1339,19 @@ fn impl_trait_ref( impl_ .of_trait .as_ref() - .map(|ast_trait_ref| { - let selfty = tcx.type_of(def_id).instantiate_identity(); + .map(|hir_trait_ref| { + let self_ty = tcx.type_of(def_id).instantiate_identity(); if let Some(ErrorGuaranteed { .. }) = check_impl_constness( tcx, 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 // 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 - // make astconv happy. - let mut path_segments = ast_trait_ref.path.segments.to_vec(); + // make HIR/ty lowering happy. + let mut path_segments = hir_trait_ref.path.segments.to_vec(); let last_segment = path_segments.len() - 1; let mut args = *path_segments[last_segment].args(); let last_arg = args.args.len() - 1; @@ -1355,14 +1359,14 @@ fn impl_trait_ref( args.args = &args.args[..args.args.len() - 1]; path_segments[last_segment].args = Some(tcx.hir_arena.alloc(args)); let path = hir::Path { - span: ast_trait_ref.path.span, - res: ast_trait_ref.path.res, + span: hir_trait_ref.path.span, + res: hir_trait_ref.path.res, 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 }); - icx.astconv().instantiate_mono_trait_ref(trait_ref, selfty) + 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().instantiate_mono_trait_ref(trait_ref, self_ty) } else { - icx.astconv().instantiate_mono_trait_ref(ast_trait_ref, selfty) + icx.lowerer().instantiate_mono_trait_ref(hir_trait_ref, self_ty) } }) .map(ty::EarlyBinder::bind) @@ -1371,20 +1375,20 @@ fn impl_trait_ref( fn check_impl_constness( tcx: TyCtxt<'_>, is_const: bool, - ast_trait_ref: &hir::TraitRef<'_>, + hir_trait_ref: &hir::TraitRef<'_>, ) -> Option { if !is_const { 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) { return None; } let trait_name = tcx.item_name(trait_def_id).to_string(); 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, local_trait_span: trait_def_id.as_local().map(|_| tcx.def_span(trait_def_id).shrink_to_lo()), @@ -1489,7 +1493,7 @@ fn compute_sig_of_foreign_fn_decl<'tcx>( }; let hir_id = tcx.local_def_id_to_hir_id(def_id); let fty = - ItemCtxt::new(tcx, def_id).astconv().ty_of_fn(hir_id, unsafety, abi, decl, None, None); + ItemCtxt::new(tcx, def_id).lowerer().lower_fn_ty(hir_id, unsafety, abi, decl, None, None); // Feature gate SIMD types in FFI, since I am not sure that the // ABIs are handled at all correctly. -huonw @@ -1497,14 +1501,14 @@ fn compute_sig_of_foreign_fn_decl<'tcx>( && abi != abi::Abi::PlatformIntrinsic && !tcx.features().simd_ffi { - let check = |ast_ty: &hir::Ty<'_>, ty: Ty<'_>| { + let check = |hir_ty: &hir::Ty<'_>, ty: Ty<'_>| { if ty.is_simd() { let snip = tcx .sess .source_map() - .span_to_snippet(ast_ty.span) + .span_to_snippet(hir_ty.span) .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()) { diff --git a/compiler/rustc_hir_analysis/src/collect/generics_of.rs b/compiler/rustc_hir_analysis/src/collect/generics_of.rs index 4860555de2056..dc5f5a24eb570 100644 --- a/compiler/rustc_hir_analysis/src/collect/generics_of.rs +++ b/compiler/rustc_hir_analysis/src/collect/generics_of.rs @@ -181,8 +181,7 @@ pub(super) fn generics_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Generics { Deny, } - let no_generics = hir::Generics::empty(); - let ast_generics = node.generics().unwrap_or(no_generics); + let hir_generics = node.generics().unwrap_or(hir::Generics::empty()); let (opt_self, allow_defaults) = match node { Node::Item(item) => { match item.kind { @@ -238,13 +237,13 @@ pub(super) fn generics_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Generics { 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 { 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 { name: param.name.ident().name, index: own_start + i as u32, @@ -265,7 +264,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 \ `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::Type { default, synthetic, .. } => { if default.is_some() { diff --git a/compiler/rustc_hir_analysis/src/collect/item_bounds.rs b/compiler/rustc_hir_analysis/src/collect/item_bounds.rs index 39ca1bba06545..e95d729da636f 100644 --- a/compiler/rustc_hir_analysis/src/collect/item_bounds.rs +++ b/compiler/rustc_hir_analysis/src/collect/item_bounds.rs @@ -1,5 +1,5 @@ use super::ItemCtxt; -use crate::astconv::{AstConv, PredicateFilter}; +use crate::lowering::{HirTyLowerer, PredicateFilter}; use rustc_hir as hir; use rustc_infer::traits::util; use rustc_middle::ty::GenericArgs; @@ -17,7 +17,7 @@ use rustc_span::Span; fn associated_type_bounds<'tcx>( tcx: TyCtxt<'tcx>, assoc_item_def_id: LocalDefId, - ast_bounds: &'tcx [hir::GenericBound<'tcx>], + hir_bounds: &'tcx [hir::GenericBound<'tcx>], span: Span, ) -> &'tcx [(ty::Clause<'tcx>, Span)] { let item_ty = Ty::new_projection( @@ -27,9 +27,9 @@ fn associated_type_bounds<'tcx>( ); let icx = ItemCtxt::new(tcx, assoc_item_def_id); - let mut bounds = icx.astconv().compute_bounds(item_ty, ast_bounds, PredicateFilter::All); + let mut bounds = icx.lowerer().compute_bounds(item_ty, hir_bounds, PredicateFilter::All); // Associated types are implicitly sized unless a `?Sized` bound is found - icx.astconv().add_implicitly_sized(&mut bounds, item_ty, ast_bounds, None, span); + icx.lowerer().add_implicitly_sized(&mut bounds, item_ty, hir_bounds, None, span); let trait_def_id = tcx.local_parent(assoc_item_def_id); let trait_predicates = tcx.trait_explicit_predicates_and_bounds(trait_def_id); @@ -60,15 +60,15 @@ fn associated_type_bounds<'tcx>( fn opaque_type_bounds<'tcx>( tcx: TyCtxt<'tcx>, opaque_def_id: LocalDefId, - ast_bounds: &'tcx [hir::GenericBound<'tcx>], + hir_bounds: &'tcx [hir::GenericBound<'tcx>], item_ty: Ty<'tcx>, span: Span, ) -> &'tcx [(ty::Clause<'tcx>, Span)] { ty::print::with_no_queries!({ let icx = ItemCtxt::new(tcx, opaque_def_id); - let mut bounds = icx.astconv().compute_bounds(item_ty, ast_bounds, PredicateFilter::All); + let mut bounds = icx.lowerer().compute_bounds(item_ty, hir_bounds, PredicateFilter::All); // Opaque types are implicitly sized unless a `?Sized` bound is found - icx.astconv().add_implicitly_sized(&mut bounds, item_ty, ast_bounds, None, span); + icx.lowerer().add_implicitly_sized(&mut bounds, item_ty, hir_bounds, None, span); debug!(?bounds); tcx.arena.alloc_from_iter(bounds.clauses()) @@ -119,8 +119,8 @@ pub(super) fn explicit_item_bounds( let item_ty = Ty::new_opaque(tcx, def_id.to_def_id(), args); opaque_type_bounds(tcx, def_id, bounds, item_ty, *span) } - // Since RPITITs are astconv'd as projections in `ast_ty_to_ty`, when we're asking - // for the item bounds of the *opaques* in a trait's default method signature, we + // Since RPITITs are lowered as projections in `::lower_ty`, when we're + // asking for the item bounds of the *opaques* in a trait's default method signature, we // need to map these projections back to opaques. hir::Node::Item(hir::Item { kind: hir::ItemKind::OpaqueTy(hir::OpaqueTy { bounds, in_trait: true, origin, .. }), diff --git a/compiler/rustc_hir_analysis/src/collect/predicates_of.rs b/compiler/rustc_hir_analysis/src/collect/predicates_of.rs index ab9ed6ef98d9f..582fef2b5ff08 100644 --- a/compiler/rustc_hir_analysis/src/collect/predicates_of.rs +++ b/compiler/rustc_hir_analysis/src/collect/predicates_of.rs @@ -1,7 +1,7 @@ -use crate::astconv::{AstConv, OnlySelfBounds, PredicateFilter}; use crate::bounds::Bounds; use crate::collect::ItemCtxt; use crate::constrained_generic_params as cgp; +use crate::lowering::{HirTyLowerer, OnlySelfBounds, PredicateFilter}; use hir::{HirId, Node}; use rustc_data_structures::fx::FxIndexSet; use rustc_hir as hir; @@ -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. let mut predicates: FxIndexSet<(ty::Clause<'_>, Span)> = FxIndexSet::default(); - let ast_generics = match node { + let hir_generics = match node { Node::TraitItem(item) => item.generics, Node::ImplItem(item) => item.generics, @@ -170,7 +170,7 @@ fn gather_explicit_predicates_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Gen // like `trait Foo: A + B + C`. if let Some(self_bounds) = is_trait { predicates.extend( - icx.astconv() + icx.lowerer() .compute_bounds(tcx.types.self_param, self_bounds, PredicateFilter::All) .clauses(), ); @@ -191,19 +191,19 @@ fn gather_explicit_predicates_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Gen // Collect the predicates that were written inline by the user on each // type parameter (e.g., ``). Also add `ConstArgHasType` predicates // for each const parameter. - for param in ast_generics.params { + for param in hir_generics.params { match param.kind { // We already dealt with early bound lifetimes above. GenericParamKind::Lifetime { .. } => (), GenericParamKind::Type { .. } => { - let param_ty = icx.astconv().hir_id_to_bound_ty(param.hir_id); + let param_ty = icx.lowerer().lower_ty_param(param.hir_id); let mut bounds = Bounds::default(); // Params are implicitly sized unless a `?Sized` bound is found - icx.astconv().add_implicitly_sized( + icx.lowerer().add_implicitly_sized( &mut bounds, param_ty, &[], - Some((param.def_id, ast_generics.predicates)), + Some((param.def_id, hir_generics.predicates)), param.span, ); trace!(?bounds); @@ -215,7 +215,7 @@ fn gather_explicit_predicates_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Gen .type_of(param.def_id.to_def_id()) .no_bound_vars() .expect("const parameters cannot be generic"); - let ct = icx.astconv().hir_id_to_bound_const(param.hir_id, ct_ty); + let ct = icx.lowerer().lower_const_param(param.hir_id, ct_ty); predicates.insert(( ty::ClauseKind::ConstArgHasType(ct, ct_ty).to_predicate(tcx), param.span, @@ -226,10 +226,10 @@ fn gather_explicit_predicates_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Gen trace!(?predicates); // Add in the bounds that appear in the where-clause. - for predicate in ast_generics.predicates { + for predicate in hir_generics.predicates { match predicate { hir::WherePredicate::BoundPredicate(bound_pred) => { - let ty = icx.to_ty(bound_pred.bounded_ty); + let ty = icx.lower_ty(bound_pred.bounded_ty); let bound_vars = tcx.late_bound_vars(bound_pred.hir_id); // Keep the type around in a dummy predicate, in case of no bounds. // That way, `where Ty:` is not a complete noop (see #53696) and `Ty` @@ -253,7 +253,7 @@ fn gather_explicit_predicates_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Gen } let mut bounds = Bounds::default(); - icx.astconv().add_bounds( + icx.lowerer().add_bounds( ty, bound_pred.bounds.iter(), &mut bounds, @@ -264,11 +264,11 @@ fn gather_explicit_predicates_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Gen } hir::WherePredicate::RegionPredicate(region_pred) => { - let r1 = icx.astconv().ast_region_to_region(region_pred.lifetime, None); + let r1 = icx.lowerer().lower_region(region_pred.lifetime, None); predicates.extend(region_pred.bounds.iter().map(|bound| { let (r2, span) = match bound { hir::GenericBound::Outlives(lt) => { - (icx.astconv().ast_region_to_region(lt, None), lt.ident.span) + (icx.lowerer().lower_region(lt, None), lt.ident.span) } bound => { span_bug!( @@ -564,8 +564,8 @@ pub(super) fn explicit_predicates_of<'tcx>( } /// Ensures that the super-predicates of the trait with a `DefId` -/// of `trait_def_id` are converted and stored. This also ensures that -/// the transitive super-predicates are converted. +/// of `trait_def_id` are lowered and stored. This also ensures that +/// the transitive super-predicates are lowered. pub(super) fn super_predicates_of( tcx: TyCtxt<'_>, trait_def_id: LocalDefId, @@ -596,8 +596,8 @@ pub(super) fn implied_predicates_of( } /// Ensures that the super-predicates of the trait with a `DefId` -/// of `trait_def_id` are converted and stored. This also ensures that -/// the transitive super-predicates are converted. +/// of `trait_def_id` are lowered and stored. This also ensures that +/// the transitive super-predicates are lowered. pub(super) fn implied_predicates_with_filter( tcx: TyCtxt<'_>, trait_def_id: DefId, @@ -625,7 +625,7 @@ pub(super) fn implied_predicates_with_filter( let icx = ItemCtxt::new(tcx, trait_def_id); let self_param_ty = tcx.types.self_param; - let superbounds = icx.astconv().compute_bounds(self_param_ty, bounds, filter); + let superbounds = icx.lowerer().compute_bounds(self_param_ty, bounds, filter); let where_bounds_that_match = icx.type_parameter_bounds_in_generics( generics, @@ -639,7 +639,7 @@ pub(super) fn implied_predicates_with_filter( &*tcx.arena.alloc_from_iter(superbounds.clauses().chain(where_bounds_that_match)); debug!(?implied_bounds); - // Now require that immediate supertraits are converted, which will, in + // Now require that immediate supertraits are lowered, which will, in // turn, reach indirect supertraits, so we detect cycles now instead of // overflowing during elaboration. if matches!(filter, PredicateFilter::SelfOnly) { @@ -666,7 +666,7 @@ pub(super) fn type_param_predicates( use rustc_hir::*; use rustc_middle::ty::Ty; - // In the AST, bounds can derive from two places. Either + // In the HIR, bounds can derive from two places. Either // written inline like `` or in a where-clause like // `where T: Foo`. @@ -692,7 +692,7 @@ pub(super) fn type_param_predicates( let mut extend = None; let item_hir_id = tcx.local_def_id_to_hir_id(item_def_id); - let ast_generics = match tcx.hir_node(item_hir_id) { + let hir_generics = match tcx.hir_node(item_hir_id) { Node::TraitItem(item) => item.generics, Node::ImplItem(item) => item.generics, @@ -735,7 +735,7 @@ pub(super) fn type_param_predicates( let icx = ItemCtxt::new(tcx, item_def_id); let extra_predicates = extend.into_iter().chain( icx.type_parameter_bounds_in_generics( - ast_generics, + hir_generics, def_id, ty, PredicateFilter::SelfThatDefines(assoc_name), @@ -752,21 +752,22 @@ pub(super) fn type_param_predicates( } impl<'tcx> ItemCtxt<'tcx> { - /// Finds bounds from `hir::Generics`. This requires scanning through the - /// AST. We do this to avoid having to convert *all* the bounds, which - /// would create artificial cycles. Instead, we can only convert the - /// bounds for a type parameter `X` if `X::Foo` is used. - #[instrument(level = "trace", skip(self, ast_generics))] + /// Finds bounds from `hir::Generics`. + /// + /// This requires scanning through the HIR. + /// 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. + #[instrument(level = "trace", skip(self, hir_generics))] fn type_parameter_bounds_in_generics( &self, - ast_generics: &'tcx hir::Generics<'tcx>, + hir_generics: &'tcx hir::Generics<'tcx>, param_def_id: LocalDefId, ty: Ty<'tcx>, filter: PredicateFilter, ) -> Vec<(ty::Clause<'tcx>, Span)> { let mut bounds = Bounds::default(); - for predicate in ast_generics.predicates { + for predicate in hir_generics.predicates { let hir::WherePredicate::BoundPredicate(predicate) = predicate else { continue; }; @@ -788,13 +789,13 @@ impl<'tcx> ItemCtxt<'tcx> { let bound_ty = if predicate.is_param_bound(param_def_id.to_def_id()) { ty } else if matches!(filter, PredicateFilter::All) { - self.to_ty(predicate.bounded_ty) + self.lower_ty(predicate.bounded_ty) } else { continue; }; let bound_vars = self.tcx.late_bound_vars(predicate.hir_id); - self.astconv().add_bounds( + self.lowerer().add_bounds( bound_ty, predicate.bounds.iter().filter(|bound| { assoc_name diff --git a/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs index 3849c0893f471..e197db3679cf1 100644 --- a/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs +++ b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs @@ -1962,19 +1962,19 @@ fn is_late_bound_map( /// /// If we conservatively considered `'a` unconstrained then we could break users who had written code before /// we started correctly handling aliases. If we considered `'a` constrained then it would become late bound - /// causing an error during astconv as the `'a` is not constrained by the input type `<() as Trait<'a>>::Assoc` + /// causing an error during HIR/ty lowering as the `'a` is not constrained by the input type `<() as Trait<'a>>::Assoc` /// but appears in the output type `<() as Trait<'a>>::Assoc`. /// /// We must therefore "look into" the `Alias` to see whether we should consider `'a` constrained or not. /// /// See #100508 #85533 #47511 for additional context - struct ConstrainedCollectorPostAstConv { + struct ConstrainedCollectorPostHirTyLowering { arg_is_constrained: Box<[bool]>, } use std::ops::ControlFlow; use ty::Ty; - impl<'tcx> TypeVisitor> for ConstrainedCollectorPostAstConv { + impl<'tcx> TypeVisitor> for ConstrainedCollectorPostHirTyLowering { fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow { match t.kind() { ty::Param(param_ty) => { @@ -2020,10 +2020,10 @@ fn is_late_bound_map( None, hir::Path { res: Res::Def(DefKind::TyAlias, alias_def), segments, span }, )) => { - // See comments on `ConstrainedCollectorPostAstConv` for why this arm does not just consider - // args to be unconstrained. + // See comments on `ConstrainedCollectorPostHirTyLowering` for why this arm does not + // just consider args to be unconstrained. let generics = self.tcx.generics_of(alias_def); - let mut walker = ConstrainedCollectorPostAstConv { + let mut walker = ConstrainedCollectorPostHirTyLowering { arg_is_constrained: vec![false; generics.params.len()].into_boxed_slice(), }; walker.visit_ty(self.tcx.type_of(alias_def).instantiate_identity()); diff --git a/compiler/rustc_hir_analysis/src/collect/type_of.rs b/compiler/rustc_hir_analysis/src/collect/type_of.rs index 20a7663f86441..26403403d7045 100644 --- a/compiler/rustc_hir_analysis/src/collect/type_of.rs +++ b/compiler/rustc_hir_analysis/src/collect/type_of.rs @@ -10,6 +10,7 @@ use rustc_span::symbol::Ident; use rustc_span::{Span, DUMMY_SP}; use crate::errors::TypeofReservedKeywordUsed; +use crate::lowering::HirTyLowerer; use super::bad_placeholder; use super::ItemCtxt; @@ -127,10 +128,10 @@ fn anon_const_type_of<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> Ty<'tcx> { // I believe this match arm is only needed for GAT but I am not 100% sure - BoxyUwU Node::Ty(hir_ty @ hir::Ty { kind: TyKind::Path(QPath::TypeRelative(_, segment)), .. }) => { // Find the Item containing the associated type so we can create an ItemCtxt. - // Using the ItemCtxt convert the HIR for the unresolved assoc type into a + // Using the ItemCtxt lower the HIR for the unresolved assoc type into a // ty which is a fully resolved projection. - // For the code example above, this would mean converting Self::Assoc<3> - // into a ty::Alias(ty::Projection, ::Assoc<3>) + // For the code example above, this would mean lowering `Self::Assoc<3>` + // to a ty::Alias(ty::Projection, `::Assoc<3>`). let item_def_id = tcx .hir() .parent_owner_iter(hir_id) @@ -138,8 +139,7 @@ fn anon_const_type_of<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> Ty<'tcx> { .unwrap() .0 .def_id; - let item_ctxt = &ItemCtxt::new(tcx, item_def_id) as &dyn crate::astconv::AstConv<'_>; - let ty = item_ctxt.ast_ty_to_ty(hir_ty); + let ty = ItemCtxt::new(tcx, item_def_id).lowerer().lower_ty(hir_ty); // Iterate through the generics of the projection to find the one that corresponds to // the def_id that this query was called with. We filter to only type and const args here @@ -391,8 +391,8 @@ pub(super) fn type_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::EarlyBinder icx.to_ty(ty), + .unwrap_or_else(|| icx.lower_ty(ty)), + TraitItemKind::Type(_, Some(ty)) => icx.lower_ty(ty), TraitItemKind::Type(_, None) => { span_bug!(item.span, "associated type missing default"); } @@ -414,7 +414,7 @@ pub(super) fn type_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::EarlyBinder { @@ -422,7 +422,7 @@ pub(super) fn type_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::EarlyBinder, def_id: LocalDefId) -> ty::EarlyBinder { if ty.is_suggestable_infer_ty() { infer_placeholder_type(tcx, def_id, body_id, ty.span, item.ident, "constant") } else { - icx.to_ty(ty) + icx.lower_ty(ty) } } - ItemKind::TyAlias(self_ty, _) => icx.to_ty(self_ty), + ItemKind::TyAlias(self_ty, _) => icx.lower_ty(self_ty), ItemKind::Impl(hir::Impl { self_ty, .. }) => match self_ty.find_self_aliases() { spans if spans.len() > 0 => { let guar = tcx @@ -456,7 +456,7 @@ pub(super) fn type_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::EarlyBinder icx.to_ty(*self_ty), + _ => icx.lower_ty(*self_ty), }, ItemKind::Fn(..) => { let args = ty::GenericArgs::identity_for_item(tcx, def_id); @@ -488,7 +488,7 @@ pub(super) fn type_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::EarlyBinder icx.to_ty(t), + ForeignItemKind::Static(t, _) => icx.lower_ty(t), ForeignItemKind::Type => Ty::new_foreign(tcx, def_id.to_def_id()), }, @@ -502,7 +502,7 @@ pub(super) fn type_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::EarlyBinder icx.to_ty(field.ty), + Node::Field(field) => icx.lower_ty(field.ty), Node::Expr(&Expr { kind: ExprKind::Closure { .. }, .. }) => { tcx.typeck(def_id).node_type(hir_id) @@ -517,7 +517,7 @@ pub(super) fn type_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::EarlyBinder match ¶m.kind { GenericParamKind::Type { default: Some(ty), .. } - | GenericParamKind::Const { ty, .. } => icx.to_ty(ty), + | GenericParamKind::Const { ty, .. } => icx.lower_ty(ty), x => bug!("unexpected non-type Node::GenericParam: {:?}", x), }, diff --git a/compiler/rustc_hir_analysis/src/hir_wf_check.rs b/compiler/rustc_hir_analysis/src/hir_wf_check.rs index 2a9101b3808fa..f932acc5e8393 100644 --- a/compiler/rustc_hir_analysis/src/hir_wf_check.rs +++ b/compiler/rustc_hir_analysis/src/hir_wf_check.rs @@ -68,7 +68,7 @@ fn diagnostic_hir_wf_check<'tcx>( let infcx = self.tcx.infer_ctxt().build(); let ocx = ObligationCtxt::new(&infcx); - let tcx_ty = self.icx.to_ty(ty); + let tcx_ty = self.icx.lower_ty(ty); // This visitor can walk into binders, resulting in the `tcx_ty` to // potentially reference escaping bound variables. We simply erase // those here. diff --git a/compiler/rustc_hir_analysis/src/lib.rs b/compiler/rustc_hir_analysis/src/lib.rs index 1aaefc5b52087..9961a3291466c 100644 --- a/compiler/rustc_hir_analysis/src/lib.rs +++ b/compiler/rustc_hir_analysis/src/lib.rs @@ -30,8 +30,8 @@ several major phases: The type checker is defined into various submodules which are documented independently: -- astconv: converts the AST representation of types - into the `ty` representation. +- lowering: lowers type-system entities from HIR to `rustc_middle::ty` + representation. - collect: computes the types of each top-level item and enters them into the `tcx.types` table for later use. @@ -82,11 +82,11 @@ extern crate rustc_middle; // These are used by Clippy. pub mod check; -pub mod astconv; pub mod autoderef; mod bounds; mod check_unused; mod coherence; +pub mod lowering; // FIXME: This module shouldn't be public. pub mod collect; mod constrained_generic_params; @@ -108,8 +108,8 @@ use rustc_span::{symbol::sym, Span, DUMMY_SP}; use rustc_target::spec::abi::Abi; use rustc_trait_selection::traits; -use astconv::{AstConv, OnlySelfBounds}; use bounds::Bounds; +use lowering::{HirTyLowerer, OnlySelfBounds}; use rustc_hir::def::DefKind; rustc_fluent_macro::fluent_messages! { "../messages.ftl" } @@ -214,18 +214,23 @@ pub fn check_crate(tcx: TyCtxt<'_>) -> Result<(), ErrorGuaranteed> { Ok(()) } -/// A quasi-deprecated helper used in rustdoc and clippy to get -/// the type from a HIR node. -pub fn hir_ty_to_ty<'tcx>(tcx: TyCtxt<'tcx>, hir_ty: &hir::Ty<'tcx>) -> Ty<'tcx> { +/// Helper to lower a [`hir::Ty`] to a [`Ty`]. +/// +///
+/// +/// This function is **quasi-deprecated**. It can cause ICEs if called inside of a body +/// (of a function or constant) and especially if it contains inferred types (`_`). +/// +///
+pub fn lower_ty<'tcx>(tcx: TyCtxt<'tcx>, hir_ty: &hir::Ty<'tcx>) -> Ty<'tcx> { // In case there are any projections, etc., find the "environment" // def-ID that will be used to determine the traits/predicates in // scope. This is derived from the enclosing item-like thing. let env_def_id = tcx.hir().get_parent_item(hir_ty.hir_id); - let item_cx = self::collect::ItemCtxt::new(tcx, env_def_id.def_id); - item_cx.astconv().ast_ty_to_ty(hir_ty) + collect::ItemCtxt::new(tcx, env_def_id.def_id).lowerer().lower_ty(hir_ty) } -pub fn hir_trait_to_predicates<'tcx>( +pub fn lower_trait_to_predicates<'tcx>( tcx: TyCtxt<'tcx>, hir_trait: &hir::TraitRef<'tcx>, self_ty: Ty<'tcx>, @@ -234,9 +239,9 @@ pub fn hir_trait_to_predicates<'tcx>( // def-ID that will be used to determine the traits/predicates in // scope. This is derived from the enclosing item-like thing. let env_def_id = tcx.hir().get_parent_item(hir_trait.hir_ref_id); - let item_cx = self::collect::ItemCtxt::new(tcx, env_def_id.def_id); + let item_cx = collect::ItemCtxt::new(tcx, env_def_id.def_id); let mut bounds = Bounds::default(); - let _ = &item_cx.astconv().instantiate_poly_trait_ref( + let _ = item_cx.lowerer().instantiate_poly_trait_ref( hir_trait, DUMMY_SP, ty::BoundConstness::NotConst, diff --git a/compiler/rustc_hir_analysis/src/astconv/bounds.rs b/compiler/rustc_hir_analysis/src/lowering/bounds.rs similarity index 91% rename from compiler/rustc_hir_analysis/src/astconv/bounds.rs rename to compiler/rustc_hir_analysis/src/lowering/bounds.rs index 1ae267d1a4059..805f2532a7c36 100644 --- a/compiler/rustc_hir_analysis/src/astconv/bounds.rs +++ b/compiler/rustc_hir_analysis/src/lowering/bounds.rs @@ -9,19 +9,20 @@ use rustc_span::{ErrorGuaranteed, Span}; use rustc_trait_selection::traits; use smallvec::SmallVec; -use crate::astconv::{ - AstConv, ConvertedBinding, ConvertedBindingKind, OnlySelfBounds, PredicateFilter, -}; use crate::bounds::Bounds; use crate::errors; +use crate::lowering::{ + HirTyLowerer, LoweredBinding, LoweredBindingKind, OnlySelfBounds, PredicateFilter, +}; -impl<'tcx> dyn AstConv<'tcx> + '_ { - /// Sets `implicitly_sized` to true on `Bounds` if necessary +impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { + /// Adds a `Sized` bound to the list of `bounds` unless the HIR bounds contain any of + /// `Sized`, `?Sized` or `!Sized`. pub(crate) fn add_implicitly_sized( &self, bounds: &mut Bounds<'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>])>, span: Span, ) { @@ -32,9 +33,9 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { // Try to find an unbound in bounds. let mut unbounds: SmallVec<[_; 1]> = SmallVec::new(); - let mut search_bounds = |ast_bounds: &'tcx [hir::GenericBound<'tcx>]| { - for ab in ast_bounds { - let hir::GenericBound::Trait(ptr, modifier) = ab else { + let mut search_bounds = |hir_bounds: &'tcx [hir::GenericBound<'tcx>]| { + for hir_bound in hir_bounds { + let hir::GenericBound::Trait(ptr, modifier) = hir_bound else { continue; }; match modifier { @@ -57,7 +58,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { } } }; - search_bounds(ast_bounds); + search_bounds(hir_bounds); if let Some((self_ty, where_clause)) = self_ty_where_predicates { for clause in where_clause { if let hir::WherePredicate::BoundPredicate(pred) = clause @@ -100,34 +101,31 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { } } - /// This helper takes a *converted* parameter type (`param_ty`) - /// and an *unconverted* list of bounds: + /// Lower bounds into `bounds`. /// /// ```text /// fn foo - /// ^ ^^^^^ `ast_bounds` parameter, in HIR form + /// ^ ^^^^^ `hir_bounds` parameter, in HIR form /// | /// `param_ty`, in ty form /// ``` /// - /// It adds these `ast_bounds` into the `bounds` structure. - /// /// **A note on binders:** there is an implied binder around - /// `param_ty` and `ast_bounds`. See `instantiate_poly_trait_ref` + /// `param_ty` and `hir_bounds`. See `instantiate_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 add_bounds<'hir, I: Iterator>>( &self, param_ty: Ty<'tcx>, - ast_bounds: I, + hir_bounds: I, bounds: &mut Bounds<'tcx>, bound_vars: &'tcx ty::List, only_self_bounds: OnlySelfBounds, ) where 'tcx: 'hir, { - for ast_bound in ast_bounds { - match ast_bound { + for hir_bound in hir_bounds { + match hir_bound { hir::GenericBound::Trait(poly_trait_ref, modifier) => { let (constness, polarity) = match modifier { hir::TraitBoundModifier::Const => { @@ -156,7 +154,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { ); } hir::GenericBound::Outlives(lifetime) => { - let region = self.ast_region_to_region(lifetime, None); + let region = self.lower_region(lifetime, None); bounds.push_region_bound( self.tcx(), ty::Binder::bind_with_vars( @@ -177,7 +175,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { /// /// ```ignore (illustrative) /// fn foo() { } - /// // ^ ^^^^^^^^^ ast_bounds + /// // ^ ^^^^^^^^^ hir_bounds /// // param_ty /// ``` /// @@ -189,7 +187,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { pub(crate) fn compute_bounds( &self, param_ty: Ty<'tcx>, - ast_bounds: &[hir::GenericBound<'tcx>], + hir_bounds: &[hir::GenericBound<'tcx>], filter: PredicateFilter, ) -> Bounds<'tcx> { let mut bounds = Bounds::default(); @@ -203,7 +201,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { self.add_bounds( param_ty, - ast_bounds.iter().filter(|bound| match filter { + hir_bounds.iter().filter(|bound| match filter { PredicateFilter::All | PredicateFilter::SelfOnly | PredicateFilter::SelfAndAssociatedTypeBounds => true, @@ -234,11 +232,11 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { /// `trait_ref` here will be `for<'a> T: Iterator`. The `binding` data however is from *inside* /// the binder (e.g., `&'a u32`) and hence may reference bound regions. #[instrument(level = "debug", skip(self, bounds, speculative, dup_bindings, path_span))] - pub(super) fn add_predicates_for_ast_type_binding( + pub(super) fn lower_type_bindings_to_predicates( &self, hir_ref_id: hir::HirId, trait_ref: ty::PolyTraitRef<'tcx>, - binding: &ConvertedBinding<'_, 'tcx>, + binding: &LoweredBinding<'_, 'tcx>, bounds: &mut Bounds<'tcx>, speculative: bool, dup_bindings: &mut FxHashMap, @@ -266,7 +264,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { let assoc_kind = if binding.gen_args.parenthesized == hir::GenericArgsParentheses::ReturnTypeNotation { ty::AssocKind::Fn - } else if let ConvertedBindingKind::Equality(term) = binding.kind + } else if let LoweredBindingKind::Equality(term) = binding.kind && let ty::TermKind::Const(_) = term.node.unpack() { ty::AssocKind::Const @@ -274,7 +272,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { ty::AssocKind::Type }; - let candidate = if self.trait_defines_associated_item_named( + let candidate = if self.trait_defines_assoc_item_named( trait_ref.def_id(), assoc_kind, binding.item_name, @@ -420,7 +418,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { infer_args: false, }; - let args_trait_ref_and_assoc_item = self.create_args_for_associated_item( + let args_trait_ref_and_assoc_item = self.lower_args_for_assoc_item( path_span, assoc_item.def_id, &item_segment, @@ -441,7 +439,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { // // for<'a> ::Item = &'a str // <-- 'a is bad // for<'a> >::Output = &'a str // <-- 'a is ok - if let ConvertedBindingKind::Equality(ty) = binding.kind { + if let LoweredBindingKind::Equality(ty) = binding.kind { let late_bound_in_trait_ref = tcx.collect_constrained_late_bound_regions(&projection_ty); let late_bound_in_ty = @@ -471,12 +469,12 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { } match binding.kind { - ConvertedBindingKind::Equality(..) if let ty::AssocKind::Fn = assoc_kind => { + LoweredBindingKind::Equality(..) if let ty::AssocKind::Fn = assoc_kind => { return Err(self.tcx().dcx().emit_err( crate::errors::ReturnTypeNotationEqualityBound { span: binding.span }, )); } - ConvertedBindingKind::Equality(term) => { + LoweredBindingKind::Equality(term) => { // "Desugar" a constraint like `T: Iterator` this to // the "projection predicate" for: // @@ -490,7 +488,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { binding.span, ); } - ConvertedBindingKind::Constraint(ast_bounds) => { + LoweredBindingKind::Constraint(hir_bounds) => { // "Desugar" a constraint like `T: Iterator` to // // `::Item: Debug` @@ -505,7 +503,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { let param_ty = Ty::new_alias(tcx, ty::Projection, projection_ty.skip_binder()); self.add_bounds( param_ty, - ast_bounds.iter(), + hir_bounds.iter(), bounds, projection_ty.bound_vars(), only_self_bounds, diff --git a/compiler/rustc_hir_analysis/src/astconv/errors.rs b/compiler/rustc_hir_analysis/src/lowering/errors.rs similarity index 98% rename from compiler/rustc_hir_analysis/src/astconv/errors.rs rename to compiler/rustc_hir_analysis/src/lowering/errors.rs index 3c64b102bae8d..b0d713bc0c43a 100644 --- a/compiler/rustc_hir_analysis/src/astconv/errors.rs +++ b/compiler/rustc_hir_analysis/src/lowering/errors.rs @@ -1,9 +1,9 @@ -use crate::astconv::{AstConv, ConvertedBindingKind}; use crate::errors::{ self, AssocTypeBindingNotAllowed, ManualImplementation, MissingTypeParams, ParenthesizedFnTraitExpansion, }; use crate::fluent_generated as fluent; +use crate::lowering::{HirTyLowerer, LoweredBindingKind}; use crate::traits::error_reporting::report_object_safety_error; use rustc_data_structures::fx::{FxHashMap, FxIndexMap, FxIndexSet}; use rustc_data_structures::sorted_map::SortedMap; @@ -22,7 +22,7 @@ use rustc_span::symbol::{sym, Ident}; use rustc_span::{Span, Symbol, DUMMY_SP}; use rustc_trait_selection::traits::object_safety_violations_for_assoc_item; -impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { +impl<'o, 'tcx> dyn HirTyLowerer<'tcx> + 'o { /// On missing type parameters, emit an E0393 error and provide a structured suggestion using /// the type parameter's name as a placeholder. pub(crate) fn complain_about_missing_type_params( @@ -111,7 +111,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { assoc_kind: ty::AssocKind, assoc_name: Ident, span: Span, - binding: Option<&super::ConvertedBinding<'_, 'tcx>>, + binding: Option<&super::LoweredBinding<'_, 'tcx>>, ) -> ErrorGuaranteed where I: Iterator>, @@ -289,13 +289,13 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { assoc_kind: ty::AssocKind, ident: Ident, span: Span, - binding: Option<&super::ConvertedBinding<'_, 'tcx>>, + binding: Option<&super::LoweredBinding<'_, 'tcx>>, ) -> ErrorGuaranteed { let tcx = self.tcx(); let bound_on_assoc_const_label = if let ty::AssocKind::Const = assoc_item.kind && let Some(binding) = binding - && let ConvertedBindingKind::Constraint(_) = binding.kind + && let LoweredBindingKind::Constraint(_) = binding.kind { let lo = if binding.gen_args.span_ext.is_dummy() { ident.span @@ -309,7 +309,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { // FIXME(associated_const_equality): This has quite a few false positives and negatives. let wrap_in_braces_sugg = if let Some(binding) = binding - && let ConvertedBindingKind::Equality(term) = binding.kind + && let LoweredBindingKind::Equality(term) = binding.kind && let ty::TermKind::Ty(ty) = term.node.unpack() && (ty.is_enum() || ty.references_error()) && tcx.features().associated_const_equality @@ -325,7 +325,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { // For equality bounds, we want to blame the term (RHS) instead of the item (LHS) since // one can argue that that's more “untuitive” to the user. let (span, expected_because_label, expected, got) = if let Some(binding) = binding - && let ConvertedBindingKind::Equality(term) = binding.kind + && let LoweredBindingKind::Equality(term) = binding.kind { (term.span, Some(ident.span), assoc_item.kind, assoc_kind) } else { diff --git a/compiler/rustc_hir_analysis/src/astconv/generics.rs b/compiler/rustc_hir_analysis/src/lowering/generics.rs similarity index 99% rename from compiler/rustc_hir_analysis/src/astconv/generics.rs rename to compiler/rustc_hir_analysis/src/lowering/generics.rs index aa826c1f26805..7e7408e8ce1f6 100644 --- a/compiler/rustc_hir_analysis/src/astconv/generics.rs +++ b/compiler/rustc_hir_analysis/src/lowering/generics.rs @@ -1,7 +1,7 @@ use super::IsMethodCall; -use crate::astconv::{ - errors::prohibit_assoc_ty_binding, CreateSubstsForGenericArgsCtxt, ExplicitLateBound, - GenericArgCountMismatch, GenericArgCountResult, GenericArgPosition, +use crate::lowering::{ + errors::prohibit_assoc_ty_binding, ExplicitLateBound, GenericArgCountMismatch, + GenericArgCountResult, GenericArgPosition, GenericArgsLowerer, }; use crate::structured_errors::{GenericArgsInfo, StructuredDiagnostic, WrongNumberOfGenericArgs}; use rustc_ast::ast::ParamKindOrd; @@ -177,7 +177,7 @@ pub fn create_args_for_parent_generic_args<'tcx: 'a, 'a>( has_self: bool, self_ty: Option>, arg_count: &GenericArgCountResult, - ctx: &mut impl CreateSubstsForGenericArgsCtxt<'a, 'tcx>, + ctx: &mut impl GenericArgsLowerer<'a, 'tcx>, ) -> GenericArgsRef<'tcx> { // Collect the segments of the path; we need to substitute arguments // for parameters throughout the entire path (wherever there are diff --git a/compiler/rustc_hir_analysis/src/astconv/lint.rs b/compiler/rustc_hir_analysis/src/lowering/lint.rs similarity index 99% rename from compiler/rustc_hir_analysis/src/astconv/lint.rs rename to compiler/rustc_hir_analysis/src/lowering/lint.rs index a6ac8ecd950ea..36542260bbe42 100644 --- a/compiler/rustc_hir_analysis/src/astconv/lint.rs +++ b/compiler/rustc_hir_analysis/src/lowering/lint.rs @@ -6,9 +6,9 @@ use rustc_lint_defs::{builtin::BARE_TRAIT_OBJECTS, Applicability}; use rustc_span::Span; use rustc_trait_selection::traits::error_reporting::suggestions::NextTypeParamName; -use super::AstConv; +use super::HirTyLowerer; -impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { +impl<'o, 'tcx> dyn HirTyLowerer<'tcx> + 'o { /// Make sure that we are in the condition to suggest the blanket implementation. pub(super) fn maybe_lint_blanket_trait_impl( &self, diff --git a/compiler/rustc_hir_analysis/src/astconv/mod.rs b/compiler/rustc_hir_analysis/src/lowering/mod.rs similarity index 92% rename from compiler/rustc_hir_analysis/src/astconv/mod.rs rename to compiler/rustc_hir_analysis/src/lowering/mod.rs index d438d3e7c60bb..60bee551290f4 100644 --- a/compiler/rustc_hir_analysis/src/astconv/mod.rs +++ b/compiler/rustc_hir_analysis/src/lowering/mod.rs @@ -1,6 +1,9 @@ -//! Conversion from AST representation of types to the `ty.rs` representation. -//! The main routine here is `ast_ty_to_ty()`; each use is parameterized by an -//! instance of `AstConv`. +//! HIR/ty lowering: Lowers type-system entities from HIR to `rustc_middle::ty` representation. +//! +//! Not to be confused with *AST lowering* which lowers AST constructs to HIR ones. +//! +//! The main routine here is `::lower_ty()`. The other routines +//! are defined on `dyn HirTyLowerer` (see [`HirTyLowerer`]). mod bounds; mod errors; @@ -8,11 +11,11 @@ pub mod generics; mod lint; mod object_safety; -use crate::astconv::errors::prohibit_assoc_ty_binding; -use crate::astconv::generics::{check_generic_arg_count, create_args_for_parent_generic_args}; use crate::bounds::Bounds; use crate::collect::HirPlaceholderCollector; use crate::errors::AmbiguousLifetimeBound; +use crate::lowering::errors::prohibit_assoc_ty_binding; +use crate::lowering::generics::{check_generic_arg_count, create_args_for_parent_generic_args}; use crate::middle::resolve_bound_vars as rbv; use crate::require_c_abi_if_c_variadic; use rustc_ast::TraitObjectSyntax; @@ -69,7 +72,10 @@ pub enum PredicateFilter { SelfAndAssociatedTypeBounds, } -pub trait AstConv<'tcx> { +/// A context which can lower type-system entities from [HIR][hir] to [`rustc_middle::ty`] representation. +/// +/// This used to be called `AstConv`. +pub trait HirTyLowerer<'tcx> { fn tcx(&self) -> TyCtxt<'tcx>; fn item_def_id(&self) -> DefId; @@ -127,6 +133,7 @@ pub trait AstConv<'tcx> { ) -> Ty<'tcx>; /// Returns `AdtDef` if `ty` is an ADT. + /// /// Note that `ty` might be a projection type that needs normalization. /// This used to get the enum variants in scope of the type. /// For example, `Self::A` could refer to an associated type @@ -141,7 +148,7 @@ pub trait AstConv<'tcx> { fn record_ty(&self, hir_id: hir::HirId, ty: Ty<'tcx>, span: Span); - fn astconv(&self) -> &dyn AstConv<'tcx> + fn lowerer(&self) -> &dyn HirTyLowerer<'tcx> where Self: Sized, { @@ -152,16 +159,16 @@ pub trait AstConv<'tcx> { } #[derive(Debug)] -struct ConvertedBinding<'a, 'tcx> { +struct LoweredBinding<'a, 'tcx> { hir_id: hir::HirId, item_name: Ident, - kind: ConvertedBindingKind<'a, 'tcx>, + kind: LoweredBindingKind<'a, 'tcx>, gen_args: &'tcx GenericArgs<'tcx>, span: Span, } #[derive(Debug)] -enum ConvertedBindingKind<'a, 'tcx> { +enum LoweredBindingKind<'a, 'tcx> { Equality(Spanned>), Constraint(&'a [hir::GenericBound<'tcx>]), } @@ -214,7 +221,8 @@ pub struct GenericArgCountResult { pub correct: Result<(), GenericArgCountMismatch>, } -pub trait CreateSubstsForGenericArgsCtxt<'a, 'tcx> { +/// A context which can lower HIR's [`GenericArg`] to `rustc_middle`'s [`ty::GenericArg`]. +pub trait GenericArgsLowerer<'a, 'tcx> { fn args_for_def_id(&mut self, def_id: DefId) -> (Option<&'a GenericArgs<'tcx>>, bool); fn provided_kind( @@ -231,9 +239,9 @@ pub trait CreateSubstsForGenericArgsCtxt<'a, 'tcx> { ) -> ty::GenericArg<'tcx>; } -impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { +impl<'o, 'tcx> dyn HirTyLowerer<'tcx> + 'o { #[instrument(level = "debug", skip(self), ret)] - pub fn ast_region_to_region( + pub fn lower_region( &self, lifetime: &hir::Lifetime, def: Option<&ty::GenericParamDef>, @@ -290,13 +298,13 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`, /// returns an appropriate set of generic arguments for this particular reference to `I`. - pub fn ast_path_args_for_ty( + pub fn lower_path_args_for_ty( &self, span: Span, def_id: DefId, item_segment: &hir::PathSegment<'tcx>, ) -> GenericArgsRef<'tcx> { - let (args, _) = self.create_args_for_ast_path( + let (args, _) = self.lower_args_for_path( span, def_id, &[], @@ -309,7 +317,6 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { if let Some(b) = item_segment.args().bindings.first() { prohibit_assoc_ty_binding(self.tcx(), b.span, Some((item_segment, span))); } - args } @@ -345,7 +352,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { /// type itself: `['a]`. The returned `GenericArgsRef` concatenates these two /// lists: `[Vec, u8, 'a]`. #[instrument(level = "debug", skip(self, span), ret)] - fn create_args_for_ast_path<'a>( + fn lower_args_for_path<'a>( &self, span: Span, def_id: DefId, @@ -362,7 +369,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { let tcx = self.tcx(); let generics = tcx.generics_of(def_id); - debug!("generics: {:?}", generics); + debug!(?generics); if generics.has_self { if generics.parent.is_some() { @@ -402,8 +409,8 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { return (tcx.mk_args(parent_args), arg_count); } - struct SubstsForAstPathCtxt<'a, 'tcx> { - astconv: &'a (dyn AstConv<'tcx> + 'a), + struct GenericArgsLoweringCtxt<'a, 'tcx> { + lowerer: &'a dyn HirTyLowerer<'tcx>, def_id: DefId, generic_args: &'a GenericArgs<'tcx>, span: Span, @@ -411,7 +418,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { infer_args: bool, } - impl<'a, 'tcx> CreateSubstsForGenericArgsCtxt<'a, 'tcx> for SubstsForAstPathCtxt<'a, 'tcx> { + impl<'a, 'tcx> GenericArgsLowerer<'a, 'tcx> for GenericArgsLoweringCtxt<'a, 'tcx> { fn args_for_def_id(&mut self, did: DefId) -> (Option<&'a GenericArgs<'tcx>>, bool) { if did == self.def_id { (Some(self.generic_args), self.infer_args) @@ -426,7 +433,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { param: &ty::GenericParamDef, arg: &GenericArg<'tcx>, ) -> ty::GenericArg<'tcx> { - let tcx = self.astconv.tcx(); + let tcx = self.lowerer.tcx(); let mut handle_ty_args = |has_default, ty: &hir::Ty<'tcx>| { if has_default { @@ -445,17 +452,17 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { }, ); } - if let (hir::TyKind::Infer, false) = (&ty.kind, self.astconv.allow_ty_infer()) { + if let (hir::TyKind::Infer, false) = (&ty.kind, self.lowerer.allow_ty_infer()) { self.inferred_params.push(ty.span); Ty::new_misc_error(tcx).into() } else { - self.astconv.ast_ty_to_ty(ty).into() + self.lowerer.lower_ty(ty).into() } }; match (¶m.kind, arg) { (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => { - self.astconv.ast_region_to_region(lt, Some(param)).into() + self.lowerer.lower_region(lt, Some(param)).into() } (&GenericParamDefKind::Type { has_default, .. }, GenericArg::Type(ty)) => { handle_ty_args(has_default, ty) @@ -474,8 +481,8 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { .type_of(param.def_id) .no_bound_vars() .expect("const parameter types cannot be generic"); - if self.astconv.allow_ty_infer() { - self.astconv.ct_infer(ty, Some(param), inf.span).into() + if self.lowerer.allow_ty_infer() { + self.lowerer.ct_infer(ty, Some(param), inf.span).into() } else { self.inferred_params.push(inf.span); ty::Const::new_misc_error(tcx, ty).into() @@ -494,10 +501,10 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { param: &ty::GenericParamDef, infer_args: bool, ) -> ty::GenericArg<'tcx> { - let tcx = self.astconv.tcx(); + let tcx = self.lowerer.tcx(); match param.kind { GenericParamDefKind::Lifetime => self - .astconv + .lowerer .re_infer(Some(param), self.span) .unwrap_or_else(|| { debug!(?param, "unelided lifetime in signature"); @@ -523,7 +530,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { } tcx.at(self.span).type_of(param.def_id).instantiate(tcx, args).into() } else if infer_args { - self.astconv.ty_infer(Some(param), self.span).into() + self.lowerer.ty_infer(Some(param), self.span).into() } else { // We've already errored above about the mismatch. Ty::new_misc_error(tcx).into() @@ -545,7 +552,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { .into() } else { if infer_args { - self.astconv.ct_infer(ty, Some(param), self.span).into() + self.lowerer.ct_infer(ty, Some(param), self.span).into() } else { // We've already errored above about the mismatch. ty::Const::new_misc_error(tcx, ty).into() @@ -556,8 +563,8 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { } } - let mut args_ctx = SubstsForAstPathCtxt { - astconv: self, + let mut args_ctx = GenericArgsLoweringCtxt { + lowerer: self, def_id, span, generic_args, @@ -592,8 +599,8 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { fn create_assoc_bindings_for_generic_args<'a>( &self, generic_args: &'a hir::GenericArgs<'tcx>, - ) -> Vec> { - // Convert associated-type bindings or constraints into a separate vector. + ) -> Vec> { + // Lower associated-type bindings or constraints into a separate vector. // Example: Given this: // // T: Iterator @@ -608,21 +615,20 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { .map(|binding| { let kind = match &binding.kind { hir::TypeBindingKind::Equality { term } => match term { - hir::Term::Ty(ty) => ConvertedBindingKind::Equality(respan( - ty.span, - self.ast_ty_to_ty(ty).into(), - )), + hir::Term::Ty(ty) => { + LoweredBindingKind::Equality(respan(ty.span, self.lower_ty(ty).into())) + } hir::Term::Const(c) => { let span = self.tcx().def_span(c.def_id); let c = Const::from_anon_const(self.tcx(), c.def_id); - ConvertedBindingKind::Equality(respan(span, c.into())) + LoweredBindingKind::Equality(respan(span, c.into())) } }, hir::TypeBindingKind::Constraint { bounds } => { - ConvertedBindingKind::Constraint(bounds) + LoweredBindingKind::Constraint(bounds) } }; - ConvertedBinding { + LoweredBinding { hir_id: binding.hir_id, item_name: binding.ident, kind, @@ -635,18 +641,15 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { assoc_bindings } - pub fn create_args_for_associated_item( + #[instrument(level = "debug", skip(self, parent_args), ret)] + pub fn lower_args_for_assoc_item( &self, span: Span, item_def_id: DefId, item_segment: &hir::PathSegment<'tcx>, parent_args: GenericArgsRef<'tcx>, ) -> GenericArgsRef<'tcx> { - debug!( - "create_args_for_associated_item(span: {:?}, item_def_id: {:?}, item_segment: {:?}", - span, item_def_id, item_segment - ); - let (args, _) = self.create_args_for_ast_path( + let (args, _) = self.lower_args_for_path( span, item_def_id, parent_args, @@ -656,11 +659,9 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { None, ty::BoundConstness::NotConst, ); - if let Some(b) = item_segment.args().bindings.first() { prohibit_assoc_ty_binding(self.tcx(), b.span, Some((item_segment, span))); } - args } @@ -677,7 +678,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { ) -> ty::TraitRef<'tcx> { self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1.iter(), |_| {}); - self.ast_path_to_mono_trait_ref( + self.lower_path_to_mono_trait_ref( trait_ref.path.span, trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise()), self_ty, @@ -725,7 +726,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1.iter(), |_| {}); self.complain_about_internal_fn_trait(span, trait_def_id, trait_segment, false); - let (generic_args, arg_count) = self.create_args_for_ast_path( + let (generic_args, arg_count) = self.lower_args_for_path( trait_ref.path.span, trait_def_id, &[], @@ -764,7 +765,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { } // Specify type to assert that error was already reported in `Err` case. - let _: Result<_, ErrorGuaranteed> = self.add_predicates_for_ast_type_binding( + let _: Result<_, ErrorGuaranteed> = self.lower_type_bindings_to_predicates( trait_ref.hir_ref_id, poly_trait_ref, binding, @@ -780,17 +781,17 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { arg_count } - fn ast_path_to_mono_trait_ref( + fn lower_path_to_mono_trait_ref( &self, span: Span, trait_def_id: DefId, self_ty: Ty<'tcx>, trait_segment: &hir::PathSegment<'tcx>, is_impl: bool, - // FIXME(effects) move all host param things in astconv to hir lowering + // FIXME(effects): Move all host param things in HIR/ty lowering to AST lowering. constness: ty::BoundConstness, ) -> ty::TraitRef<'tcx> { - let (generic_args, _) = self.create_args_for_ast_trait_ref( + let (generic_args, _) = self.lower_args_for_trait_ref( span, trait_def_id, self_ty, @@ -805,7 +806,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { } #[instrument(level = "debug", skip(self, span))] - fn create_args_for_ast_trait_ref<'a>( + fn lower_args_for_trait_ref<'a>( &self, span: Span, trait_def_id: DefId, @@ -816,7 +817,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { ) -> (GenericArgsRef<'tcx>, GenericArgCountResult) { self.complain_about_internal_fn_trait(span, trait_def_id, trait_segment, is_impl); - self.create_args_for_ast_path( + self.lower_args_for_path( span, trait_def_id, &[], @@ -828,7 +829,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { ) } - fn trait_defines_associated_item_named( + fn trait_defines_assoc_item_named( &self, trait_def_id: DefId, assoc_kind: ty::AssocKind, @@ -840,14 +841,14 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { .is_some() } - fn ast_path_to_ty( + fn lower_path_to_ty( &self, span: Span, did: DefId, item_segment: &hir::PathSegment<'tcx>, ) -> Ty<'tcx> { let tcx = self.tcx(); - let args = self.ast_path_args_for_ty(span, did, item_segment); + let args = self.lower_path_args_for_ty(span, did, item_segment); if let DefKind::TyAlias = tcx.def_kind(did) && tcx.type_alias_is_lazy(did) @@ -862,7 +863,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { } } - fn report_ambiguous_associated_type( + fn report_ambiguous_assoc_type( &self, span: Span, types: &[String], @@ -974,10 +975,11 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { reported } - // Search for a bound on a type parameter which includes the associated item - // given by `assoc_name`. `ty_param_def_id` is the `DefId` of the type parameter - // This function will fail if there are no suitable bounds or there is - // any ambiguity. + /// Search for a bound on a type parameter which includes the associated item given by `assoc_name`. + /// + /// `ty_param_def_id` is the `DefId` of the type parameter. + /// This function will fail if there are no suitable bounds or there is any ambiguity. + #[instrument(level = "debug", skip(self), ret)] fn find_bound_for_assoc_item( &self, ty_param_def_id: LocalDefId, @@ -986,15 +988,9 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { ) -> Result, ErrorGuaranteed> { 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.get_type_parameter_bounds(span, ty_param_def_id, assoc_name).predicates; - - debug!("find_bound_for_assoc_item: predicates={:#?}", predicates); + debug!(?predicates); let param_name = tcx.hir().ty_param_name(ty_param_def_id); self.one_bound_for_assoc_item( @@ -1016,8 +1012,8 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { ) } - // Checks that `bounds` contains exactly one element and reports appropriate - // errors otherwise. + // FIXME(fmease): This also *resolves* the bound. Update docs! + /// Checks that `bounds` contains exactly one element and reports appropriate errors otherwise. #[instrument(level = "debug", skip(self, all_candidates, ty_param_name, binding), ret)] fn one_bound_for_assoc_item( &self, @@ -1027,16 +1023,15 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { assoc_kind: ty::AssocKind, assoc_name: Ident, span: Span, - binding: Option<&ConvertedBinding<'_, 'tcx>>, + binding: Option<&LoweredBinding<'_, 'tcx>>, ) -> Result, ErrorGuaranteed> where I: Iterator>, { let tcx = self.tcx(); - let mut matching_candidates = all_candidates().filter(|r| { - self.trait_defines_associated_item_named(r.def_id(), assoc_kind, assoc_name) - }); + let mut matching_candidates = all_candidates() + .filter(|r| self.trait_defines_assoc_item_named(r.def_id(), assoc_kind, assoc_name)); let Some(bound) = matching_candidates.next() else { let reported = self.complain_about_assoc_item_not_found( @@ -1067,7 +1062,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { // Provide a more specific error code index entry for equality bindings. err.code( if let Some(binding) = binding - && let ConvertedBindingKind::Equality(_) = binding.kind + && let LoweredBindingKind::Equality(_) = binding.kind { E0222 } else { @@ -1092,7 +1087,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { ); if let Some(binding) = binding { match binding.kind { - ConvertedBindingKind::Equality(term) => { + LoweredBindingKind::Equality(term) => { // FIXME(#97583): This isn't syntactically well-formed! where_bounds.push(format!( " T: {trait}::{assoc_name} = {term}", @@ -1101,7 +1096,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { )); } // FIXME: Provide a suggestion. - ConvertedBindingKind::Constraint(_bounds) => {} + LoweredBindingKind::Constraint(_bounds) => {} } } else { err.span_suggestion_verbose( @@ -1135,16 +1130,17 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { Ok(bound) } - // Create a type from a path to an associated type or to an enum variant. - // For a path `A::B::C::D`, `qself_ty` and `qself_def` are the type and def for `A::B::C` - // and item_segment is the path segment for `D`. We return a type and a def for - // the whole path. - // Will fail except for `T::A` and `Self::A`; i.e., if `qself_ty`/`qself_def` are not a type - // parameter or `Self`. + /// Create a type from a path to an associated type or to an enum variant. + /// + /// For a path `A::B::C::D`, `qself_ty` and `qself` are the type and def for `A::B::C` + /// and item_segment is the path segment for `D`. We return a type and a def for + /// the whole path. + /// + /// Will fail except for `T::A` and `Self::A`; i.e., if `qself_ty`/`qself` are not a type + /// parameter or `Self`. // NOTE: When this function starts resolving `Trait::AssocTy` successfully // 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)] - pub fn associated_path_to_ty( + pub fn lower_assoc_path_to_ty( &self, hir_ref_id: hir::HirId, span: Span, @@ -1153,7 +1149,10 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { assoc_segment: &hir::PathSegment<'tcx>, permit_variants: bool, ) -> Result<(Ty<'tcx>, DefKind, DefId), ErrorGuaranteed> { + let _guard = tracing::debug_span!("lower_assoc_path_to_ty").entered(); + debug!(%qself_ty, ?assoc_segment.ident); let tcx = self.tcx(); + let assoc_ident = assoc_segment.ident; let qself_res = if let hir::TyKind::Path(hir::QPath::Resolved(_, path)) = &qself.kind { path.res @@ -1376,7 +1375,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { self.probe_traits_that_match_assoc_ty(qself_ty, assoc_ident); // Don't print `ty::Error` to the user. - self.report_ambiguous_associated_type( + self.report_ambiguous_assoc_type( span, &[qself_ty.to_string()], &traits, @@ -1438,8 +1437,9 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { // Don't attempt to look up inherent associated types when the feature is not enabled. // Theoretically it'd be fine to do so since we feature-gate their definition site. // However, due to current limitations of the implementation (caused by us performing - // selection in AstConv), IATs can lead to cycle errors (#108491, #110106) which mask the - // feature-gate error, needlessly confusing users that use IATs by accident (#113265). + // selection during HIR/ty lowering instead of in the trait solver), IATs can lead to cycle + // errors (#108491, #110106) which mask the feature-gate error, needlessly confusing users + // who use IATs by accident (#113265). if !tcx.features().inherent_associated_types { return Ok(None); } @@ -1498,7 +1498,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { // `create_args_for_associated_item`. Modify the latter instead (or sth. similar) to // not require the parent args logic. let parent_args = ty::GenericArgs::identity_for_item(tcx, impl_); - let args = self.create_args_for_associated_item(span, assoc_item, segment, parent_args); + let args = self.lower_args_for_assoc_item(span, assoc_item, segment, parent_args); let args = tcx.mk_args_from_iter( std::iter::once(ty::GenericArg::from(self_ty)) .chain(args.into_iter().skip(parent_args.len())), @@ -1696,7 +1696,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { .collect() } - fn qpath_to_ty( + fn lower_qpath_to_ty( &self, span: Span, opt_self_ty: Option>, @@ -1705,25 +1705,23 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { item_segment: &hir::PathSegment<'tcx>, constness: ty::BoundConstness, ) -> Ty<'tcx> { + let _guard = tracing::debug_span!("lower_qpath_to_ty").entered(); let tcx = self.tcx(); let trait_def_id = tcx.parent(item_def_id); - - debug!("qpath_to_ty: trait_def_id={:?}", trait_def_id); + debug!(?trait_def_id); let Some(self_ty) = opt_self_ty else { let path_str = tcx.def_path_str(trait_def_id); let def_id = self.item_def_id(); - - debug!("qpath_to_ty: self.item_def_id()={:?}", def_id); + debug!(item_def_id = ?def_id); let parent_def_id = def_id .as_local() .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()); - - debug!("qpath_to_ty: parent_def_id={:?}", parent_def_id); + debug!(?parent_def_id); // If the trait in segment is the same as the trait defining the item, // use the `` syntax in the error. @@ -1750,7 +1748,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { // FIXME: also look at `tcx.generics_of(self.item_def_id()).params` any that // references the trait. Relevant for the first case in // `src/test/ui/associated-types/associated-types-in-ambiguous-context.rs` - let reported = self.report_ambiguous_associated_type( + let reported = self.report_ambiguous_assoc_type( span, &type_names, &[path_str], @@ -1758,10 +1756,9 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { ); return Ty::new_error(tcx, reported); }; + debug!(?self_ty); - debug!("qpath_to_ty: self_type={:?}", self_ty); - - let trait_ref = self.ast_path_to_mono_trait_ref( + let trait_ref = self.lower_path_to_mono_trait_ref( span, trait_def_id, self_ty, @@ -1769,11 +1766,10 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { false, constness, ); + debug!(?trait_ref); let item_args = - self.create_args_for_associated_item(span, item_def_id, item_segment, trait_ref.args); - - debug!("qpath_to_ty: trait_ref={:?}", trait_ref); + self.lower_args_for_assoc_item(span, item_def_id, item_segment, trait_ref.args); Ty::new_projection(tcx, item_def_id, item_args) } @@ -2016,21 +2012,18 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { path_segs } - /// Check a type `Path` and convert it to a `Ty`. - pub fn res_to_ty( + /// Check a type `Path` and lower it to a `Ty`. + pub fn lower_res_to_ty( &self, opt_self_ty: Option>, path: &hir::Path<'tcx>, hir_id: hir::HirId, permit_variants: bool, ) -> Ty<'tcx> { + let _guard = tracing::debug_span!("lower_res_to_ty").entered(); + debug!(?path.res, ?opt_self_ty, ?path.segments); 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; match path.res { Res::Def(DefKind::OpaqueTy, did) => { @@ -2040,7 +2033,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { self.prohibit_generics(item_segment.1.iter(), |err| { err.note("`impl Trait` types can't have type parameters"); }); - let args = self.ast_path_args_for_ty(span, did, item_segment.0); + let args = self.lower_path_args_for_ty(span, did, item_segment.0); Ty::new_opaque(tcx, did, args) } Res::Def( @@ -2053,10 +2046,10 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { ) => { assert_eq!(opt_self_ty, None); self.prohibit_generics(path.segments.split_last().unwrap().1.iter(), |_| {}); - self.ast_path_to_ty(span, did, path.segments.last().unwrap()) + self.lower_path_to_ty(span, did, path.segments.last().unwrap()) } Res::Def(kind @ DefKind::Variant, def_id) if permit_variants => { - // Convert "variant type" as if it were a real type. + // Lower "variant type" as if it were a real type. // The resulting `Ty` is type of the variant's enum for now. assert_eq!(opt_self_ty, None); @@ -2074,7 +2067,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { ); let PathSeg(def_id, index) = path_segs.last().unwrap(); - self.ast_path_to_ty(span, *def_id, &path.segments[*index]) + self.lower_path_to_ty(span, *def_id, &path.segments[*index]) } Res::Def(DefKind::TyParam, def_id) => { assert_eq!(opt_self_ty, None); @@ -2084,7 +2077,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { err.span_note(span, format!("type parameter `{name}` defined here")); } }); - self.hir_id_to_bound_ty(hir_id) + self.lower_ty_param(hir_id) } Res::SelfTyParam { .. } => { // `Self` in trait or type alias. @@ -2212,7 +2205,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { } else { ty::BoundConstness::NotConst }; - self.qpath_to_ty( + self.lower_qpath_to_ty( span, opt_self_ty, def_id, @@ -2257,9 +2250,9 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { } } - // Converts a hir id corresponding to a type parameter to - // a early-bound `ty::Param` or late-bound `ty::Bound`. - pub(crate) fn hir_id_to_bound_ty(&self, hir_id: hir::HirId) -> Ty<'tcx> { + /// Lower a `HirId` corresponding to a type parameter to an early-bound + /// [`ty::Param`] or late-bound [`ty::Bound`]. + pub(crate) fn lower_ty_param(&self, hir_id: hir::HirId) -> Ty<'tcx> { let tcx = self.tcx(); match tcx.named_bound_var(hir_id) { Some(rbv::ResolvedArg::LateBound(debruijn, index, def_id)) => { @@ -2282,13 +2275,9 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { } } - // Converts a hir id corresponding to a const parameter to - // a early-bound `ConstKind::Param` or late-bound `ConstKind::Bound`. - pub(crate) fn hir_id_to_bound_const( - &self, - hir_id: hir::HirId, - param_ty: Ty<'tcx>, - ) -> Const<'tcx> { + /// Lower a `HirId` corresponding to a const parameter to an early-bound + /// [`ty::ConstKind::Param`] or late-bound [`ty::ConstKind::Bound`]. + pub(crate) fn lower_const_param(&self, hir_id: hir::HirId, param_ty: Ty<'tcx>) -> Const<'tcx> { let tcx = self.tcx(); match tcx.named_bound_var(hir_id) { Some(rbv::ResolvedArg::EarlyBound(def_id)) => { @@ -2310,14 +2299,14 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { /// Parses the programmer's textual representation of a type into our /// internal notion of a type. - pub fn ast_ty_to_ty(&self, ast_ty: &hir::Ty<'tcx>) -> Ty<'tcx> { - self.ast_ty_to_ty_inner(ast_ty, false, false) + pub fn lower_ty(&self, hir_ty: &hir::Ty<'tcx>) -> Ty<'tcx> { + self.lower_ty_inner(hir_ty, false, false) } /// Parses the programmer's textual representation of a type into our /// internal notion of a type. This is meant to be used within a path. - pub fn ast_ty_to_ty_in_path(&self, ast_ty: &hir::Ty<'tcx>) -> Ty<'tcx> { - self.ast_ty_to_ty_inner(ast_ty, false, true) + pub fn lower_ty_in_path(&self, hir_ty: &hir::Ty<'tcx>) -> Ty<'tcx> { + self.lower_ty_inner(hir_ty, false, true) } fn check_delegation_constraints(&self, sig_id: DefId, span: Span, emit: bool) -> bool { @@ -2384,7 +2373,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { error_occured } - fn ty_from_delegation( + fn lower_delegation_ty( &self, sig_id: DefId, idx: hir::InferDelegationKind, @@ -2428,53 +2417,57 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { } } - /// Turns a `hir::Ty` into a `Ty`. For diagnostics' purposes we keep track of whether trait - /// objects are borrowed like `&dyn Trait` to avoid emitting redundant errors. + /// Lowers a [`hir::Ty`] to a [`Ty`]. + /// + /// For diagnostics' purposes we keep track of whether trait objects are + /// borrowed like `&dyn Trait` to avoid emitting redundant errors. #[instrument(level = "debug", skip(self), ret)] - fn ast_ty_to_ty_inner( - &self, - ast_ty: &hir::Ty<'tcx>, - borrowed: bool, - in_path: bool, - ) -> Ty<'tcx> { + fn lower_ty_inner(&self, hir_ty: &hir::Ty<'tcx>, borrowed: bool, in_path: bool) -> Ty<'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) => { - self.ty_from_delegation(*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.ast_ty_to_ty(ty)), + hir::TyKind::Slice(ty) => Ty::new_slice(tcx, self.lower_ty(ty)), hir::TyKind::Ptr(mt) => { - Ty::new_ptr(tcx, ty::TypeAndMut { ty: self.ast_ty_to_ty(mt.ty), mutbl: mt.mutbl }) + Ty::new_ptr(tcx, ty::TypeAndMut { ty: self.lower_ty(mt.ty), mutbl: mt.mutbl }) } hir::TyKind::Ref(region, mt) => { - let r = self.ast_region_to_region(region, None); + let r = self.lower_region(region, None); debug!(?r); - let t = self.ast_ty_to_ty_inner(mt.ty, true, false); + let t = self.lower_ty_inner(mt.ty, true, false); Ty::new_ref(tcx, r, ty::TypeAndMut { ty: t, mutbl: mt.mutbl }) } hir::TyKind::Never => tcx.types.never, hir::TyKind::Tup(fields) => { - Ty::new_tup_from_iter(tcx, fields.iter().map(|t| self.ast_ty_to_ty(t))) + Ty::new_tup_from_iter(tcx, fields.iter().map(|t| self.lower_ty(t))) } 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( tcx, - self.ty_of_fn(ast_ty.hir_id, bf.unsafety, bf.abi, bf.decl, None, Some(ast_ty)), + self.lower_fn_ty( + hir_ty.hir_id, + bf.unsafety, + bf.abi, + bf.decl, + None, + Some(hir_ty), + ), ) } 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 { TraitObjectSyntax::Dyn | TraitObjectSyntax::None => ty::Dyn, TraitObjectSyntax::DynStar => ty::DynStar, }; - self.conv_object_ty_poly_trait_ref( - ast_ty.span, - ast_ty.hir_id, + self.lower_object_ty_to_poly_trait_ref( + hir_ty.span, + hir_ty.hir_id, bounds, lifetime, borrowed, @@ -2483,8 +2476,8 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { } hir::TyKind::Path(hir::QPath::Resolved(maybe_qself, path)) => { debug!(?maybe_qself, ?path); - let opt_self_ty = maybe_qself.as_ref().map(|qself| self.ast_ty_to_ty(qself)); - self.res_to_ty(opt_self_ty, path, ast_ty.hir_id, false) + let opt_self_ty = maybe_qself.as_ref().map(|qself| self.lower_ty(qself)); + self.lower_res_to_ty(opt_self_ty, path, hir_ty.hir_id, false) } &hir::TyKind::OpaqueDef(item_id, lifetimes, in_trait) => { let opaque_ty = tcx.hir().item(item_id); @@ -2500,21 +2493,21 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { } else { local_def_id.to_def_id() }; - self.impl_trait_ty_to_ty(def_id, lifetimes, in_trait) + self.lower_impl_trait_ty(def_id, lifetimes, in_trait) } ref i => bug!("`impl Trait` pointed to non-opaque type?? {:#?}", i), } } hir::TyKind::Path(hir::QPath::TypeRelative(qself, segment)) => { debug!(?qself, ?segment); - let ty = self.ast_ty_to_ty_inner(qself, false, true); - self.associated_path_to_ty(ast_ty.hir_id, ast_ty.span, ty, qself, segment, false) + let ty = self.lower_ty_inner(qself, false, true); + self.lower_assoc_path_to_ty(hir_ty.hir_id, hir_ty.span, ty, qself, segment, false) .map(|(ty, _, _)| ty) .unwrap_or_else(|guar| Ty::new_error(tcx, guar)) } &hir::TyKind::Path(hir::QPath::LangItem(lang_item, span)) => { let def_id = tcx.require_lang_item(lang_item, Some(span)); - let (args, _) = self.create_args_for_ast_path( + let (args, _) = self.lower_args_for_path( span, def_id, &[], @@ -2534,7 +2527,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { } }; - Ty::new_array_with_const_len(tcx, self.ast_ty_to_ty(ty), length) + Ty::new_array_with_const_len(tcx, self.lower_ty(ty), length) } hir::TyKind::Typeof(e) => tcx.type_of(e.def_id).instantiate_identity(), hir::TyKind::Infer => { @@ -2542,28 +2535,27 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { // values in an ExprKind::Closure, or as // the type of local variables. Both of these cases are // 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), }; - 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 } #[instrument(level = "debug", skip(self), ret)] - fn impl_trait_ty_to_ty( + fn lower_impl_trait_ty( &self, def_id: DefId, lifetimes: &[hir::GenericArg<'_>], in_trait: bool, ) -> Ty<'tcx> { - debug!("impl_trait_ty_to_ty(def_id={:?}, lifetimes={:?})", def_id, lifetimes); let tcx = self.tcx(); 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, _| { // 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 @@ -2584,12 +2576,12 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { &lifetimes[i] ) }; - self.ast_region_to_region(lifetime, None).into() + self.lower_region(lifetime, None).into() } else { tcx.mk_param_from_def(param) } }); - debug!("impl_trait_ty_to_ty: args={:?}", args); + debug!(?args); if in_trait { Ty::new_projection(tcx, def_id, args) @@ -2598,18 +2590,18 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { } } - pub fn ty_of_arg(&self, ty: &hir::Ty<'tcx>, expected_ty: Option>) -> Ty<'tcx> { + pub fn lower_arg_ty(&self, ty: &hir::Ty<'tcx>, expected_ty: Option>) -> Ty<'tcx> { match ty.kind { hir::TyKind::Infer if expected_ty.is_some() => { self.record_ty(ty.hir_id, expected_ty.unwrap(), ty.span); expected_ty.unwrap() } - _ => self.ast_ty_to_ty(ty), + _ => self.lower_ty(ty), } } #[instrument(level = "debug", skip(self, hir_id, unsafety, abi, decl, generics, hir_ty), ret)] - pub fn ty_of_fn( + pub fn lower_fn_ty( &self, hir_id: hir::HirId, unsafety: hir::Unsafety, @@ -2658,7 +2650,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { // Only visit the type looking for `_` if we didn't fix the type above visitor.visit_ty(a); - self.ty_of_arg(a, None) + self.lower_arg_ty(a, None) }) .collect(); @@ -2673,7 +2665,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { Ty::new_error_with_message(self.tcx(), output.span, suggested_ty.to_string()) } else { visitor.visit_ty(output); - self.ast_ty_to_ty(output) + self.lower_ty(output) } } hir::FnRetTy::DefaultReturn(..) => Ty::new_unit(tcx), @@ -2759,7 +2751,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { let i = hir.get_parent(fn_hir_id).expect_item().expect_impl(); let trait_ref = - self.instantiate_mono_trait_ref(i.of_trait.as_ref()?, self.ast_ty_to_ty(i.self_ty)); + self.instantiate_mono_trait_ref(i.of_trait.as_ref()?, self.lower_ty(i.self_ty)); let assoc = tcx.associated_items(trait_ref.def_id).find_by_name_and_kind( tcx, @@ -2816,7 +2808,9 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { } /// Given the bounds on an object, determines what single region bound (if any) we can - /// use to summarize this type. The basic idea is that we will use the bound the user + /// use to summarize this type. + /// + /// The basic idea is that we will use the bound the user /// provided, if they provided one, and otherwise search the supertypes of trait bounds /// for region bounds. It may be that we can derive no bound at all, in which case /// we return `None`. diff --git a/compiler/rustc_hir_analysis/src/astconv/object_safety.rs b/compiler/rustc_hir_analysis/src/lowering/object_safety.rs similarity index 95% rename from compiler/rustc_hir_analysis/src/astconv/object_safety.rs rename to compiler/rustc_hir_analysis/src/lowering/object_safety.rs index 2d85ad5789ecc..e423797e9f77d 100644 --- a/compiler/rustc_hir_analysis/src/astconv/object_safety.rs +++ b/compiler/rustc_hir_analysis/src/lowering/object_safety.rs @@ -1,6 +1,6 @@ -use crate::astconv::{GenericArgCountMismatch, GenericArgCountResult, OnlySelfBounds}; use crate::bounds::Bounds; use crate::errors::TraitObjectDeclaredWithNoTraits; +use crate::lowering::{GenericArgCountMismatch, GenericArgCountResult, OnlySelfBounds}; use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet}; use rustc_errors::{codes::*, struct_span_code_err}; use rustc_hir as hir; @@ -11,14 +11,14 @@ use rustc_middle::ty::{self, Ty}; use rustc_middle::ty::{DynKind, ToPredicate}; use rustc_span::Span; use rustc_trait_selection::traits::error_reporting::report_object_safety_error; -use rustc_trait_selection::traits::{self, astconv_object_safety_violations}; +use rustc_trait_selection::traits::{self, hir_ty_lowering_object_safety_violations}; use smallvec::{smallvec, SmallVec}; -use super::AstConv; +use super::HirTyLowerer; -impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { - pub(super) fn conv_object_ty_poly_trait_ref( +impl<'o, 'tcx> dyn HirTyLowerer<'tcx> + 'o { + pub(super) fn lower_object_ty_to_poly_trait_ref( &self, span: Span, hir_id: hir::HirId, @@ -27,6 +27,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { borrowed: bool, representation: DynKind, ) -> Ty<'tcx> { + let _guard = trace::debug_span!("lower_object_ty_to_poly_trait_ref"); let tcx = self.tcx(); let mut bounds = Bounds::default(); @@ -136,7 +137,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { // to avoid ICEs. for item in ®ular_traits { let object_safety_violations = - astconv_object_safety_violations(tcx, item.trait_ref().def_id()); + hir_ty_lowering_object_safety_violations(tcx, item.trait_ref().def_id()); if !object_safety_violations.is_empty() { let reported = report_object_safety_error( tcx, @@ -159,7 +160,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { for (base_trait_ref, span) in regular_traits_refs_spans { let base_pred: ty::Predicate<'tcx> = base_trait_ref.to_predicate(tcx); for pred in traits::elaborate(tcx, [base_pred]) { - debug!("conv_object_ty_poly_trait_ref: observing object predicate `{:?}`", pred); + debug!("observing object predicate `{:?}`", pred); let bound_predicate = pred.kind(); match bound_predicate.skip_binder() { @@ -245,8 +246,8 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { // the bounds let mut duplicates = FxHashSet::default(); auto_traits.retain(|i| duplicates.insert(i.trait_ref().def_id())); - debug!("regular_traits: {:?}", regular_traits); - debug!("auto_traits: {:?}", auto_traits); + debug!(?regular_traits); + debug!(?auto_traits); // Erase the `dummy_self` (`trait_object_dummy_self`) used above. let existential_trait_refs = regular_traits.iter().map(|i| { @@ -370,11 +371,11 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { // Use explicitly-specified region bound. let region_bound = if !lifetime.is_elided() { - self.ast_region_to_region(lifetime, None) + self.lower_region(lifetime, None) } else { self.compute_object_lifetime_bound(span, existential_predicates).unwrap_or_else(|| { if tcx.named_bound_var(lifetime.hir_id).is_some() { - self.ast_region_to_region(lifetime, None) + self.lower_region(lifetime, None) } else { self.re_infer(None, span).unwrap_or_else(|| { let err = struct_span_code_err!( @@ -397,10 +398,10 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { } }) }; - debug!("region_bound: {:?}", region_bound); + debug!(?region_bound); let ty = Ty::new_dynamic(tcx, existential_predicates, region_bound, representation); - debug!("trait_object_type: {:?}", ty); + debug!(trait_object_type = ?ty); ty } } diff --git a/compiler/rustc_hir_analysis/src/variance/constraints.rs b/compiler/rustc_hir_analysis/src/variance/constraints.rs index 580cdb4a3a209..93a0e9240999e 100644 --- a/compiler/rustc_hir_analysis/src/variance/constraints.rs +++ b/compiler/rustc_hir_analysis/src/variance/constraints.rs @@ -1,6 +1,6 @@ //! Constraint construction and representation //! -//! The second pass over the AST determines the set of constraints. +//! The second pass over the HIR determines the set of constraints. //! We walk the set of items and, for each member, generate new constraints. use hir::def_id::{DefId, LocalDefId}; diff --git a/compiler/rustc_hir_typeck/src/closure.rs b/compiler/rustc_hir_typeck/src/closure.rs index 5bdd9412d0e51..7547a51a8a16a 100644 --- a/compiler/rustc_hir_typeck/src/closure.rs +++ b/compiler/rustc_hir_typeck/src/closure.rs @@ -5,7 +5,7 @@ use super::{check_fn, CoroutineTypes, Expectation, FnCtxt}; use rustc_errors::ErrorGuaranteed; use rustc_hir as hir; use rustc_hir::lang_items::LangItem; -use rustc_hir_analysis::astconv::AstConv; +use rustc_hir_analysis::lowering::HirTyLowerer; use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind}; use rustc_infer::infer::{BoundRegionConversionTime, DefineOpaqueTypes}; use rustc_infer::infer::{InferOk, InferResult}; @@ -753,7 +753,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { decl: &hir::FnDecl<'tcx>, closure_kind: hir::ClosureKind, ) -> ty::PolyFnSig<'tcx> { - let astconv: &dyn AstConv<'_> = self; + let lowerer = self.lowerer(); trace!("decl = {:#?}", decl); debug!(?closure_kind); @@ -762,9 +762,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let bound_vars = self.tcx.late_bound_vars(hir_id); // First, convert the types that the user supplied (if any). - let supplied_arguments = decl.inputs.iter().map(|a| astconv.ast_ty_to_ty(a)); + let supplied_arguments = decl.inputs.iter().map(|a| lowerer.lower_ty(a)); let supplied_return = match decl.output { - hir::FnRetTy::Return(ref output) => astconv.ast_ty_to_ty(output), + hir::FnRetTy::Return(ref output) => lowerer.lower_ty(output), hir::FnRetTy::DefaultReturn(_) => match closure_kind { // In the case of the async block that we create for a function body, // we expect the return type of the block to match that of the enclosing @@ -782,7 +782,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // easily (and locally) prove that we // *have* reported an // error. --nikomatsakis - astconv.ty_infer(None, decl.output.span()) + lowerer.ty_infer(None, decl.output.span()) }) } // All `gen {}` and `async gen {}` must return unit. @@ -801,7 +801,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { | hir::ClosureKind::Coroutine(hir::CoroutineKind::Coroutine(_)) | hir::ClosureKind::Closure | hir::ClosureKind::CoroutineClosure(_) => { - astconv.ty_infer(None, decl.output.span()) + lowerer.ty_infer(None, decl.output.span()) } }, }; @@ -958,17 +958,17 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { decl: &hir::FnDecl<'tcx>, guar: ErrorGuaranteed, ) -> ty::PolyFnSig<'tcx> { - let astconv: &dyn AstConv<'_> = self; + let lowerer = self.lowerer(); let err_ty = Ty::new_error(self.tcx, guar); let supplied_arguments = decl.inputs.iter().map(|a| { // Convert the types that the user supplied (if any), but ignore them. - astconv.ast_ty_to_ty(a); + lowerer.lower_ty(a); err_ty }); if let hir::FnRetTy::Return(ref output) = decl.output { - astconv.ast_ty_to_ty(output); + lowerer.lower_ty(output); } let result = ty::Binder::dummy(self.tcx.mk_fn_sig( diff --git a/compiler/rustc_hir_typeck/src/coercion.rs b/compiler/rustc_hir_typeck/src/coercion.rs index 2beabc0835db1..acc3c5feb6cdc 100644 --- a/compiler/rustc_hir_typeck/src/coercion.rs +++ b/compiler/rustc_hir_typeck/src/coercion.rs @@ -43,7 +43,7 @@ use rustc_hir as hir; use rustc_hir::def_id::DefId; use rustc_hir::intravisit::{self, Visitor}; use rustc_hir::Expr; -use rustc_hir_analysis::astconv::AstConv; +use rustc_hir_analysis::lowering::HirTyLowerer; use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind}; use rustc_infer::infer::{Coercion, DefineOpaqueTypes, InferOk, InferResult}; use rustc_infer::traits::{Obligation, PredicateObligation}; diff --git a/compiler/rustc_hir_typeck/src/expr.rs b/compiler/rustc_hir_typeck/src/expr.rs index 292b85eb97f7f..5b8eb9a569688 100644 --- a/compiler/rustc_hir_typeck/src/expr.rs +++ b/compiler/rustc_hir_typeck/src/expr.rs @@ -34,8 +34,8 @@ use rustc_hir::def_id::DefId; use rustc_hir::intravisit::Visitor; use rustc_hir::lang_items::LangItem; use rustc_hir::{ExprKind, HirId, QPath}; -use rustc_hir_analysis::astconv::AstConv as _; use rustc_hir_analysis::check::ty_kind_suggestion; +use rustc_hir_analysis::lowering::HirTyLowerer as _; use rustc_infer::infer; use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind}; use rustc_infer::infer::DefineOpaqueTypes; diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs index 36c3eef82fccb..b54c194f23a94 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs @@ -11,12 +11,12 @@ use rustc_hir::def::{CtorOf, DefKind, Res}; use rustc_hir::def_id::DefId; use rustc_hir::lang_items::LangItem; use rustc_hir::{ExprKind, GenericArg, Node, QPath}; -use rustc_hir_analysis::astconv::generics::{ +use rustc_hir_analysis::lowering::generics::{ check_generic_arg_count_for_call, create_args_for_parent_generic_args, }; -use rustc_hir_analysis::astconv::{ - AstConv, CreateSubstsForGenericArgsCtxt, ExplicitLateBound, GenericArgCountMismatch, - GenericArgCountResult, IsMethodCall, PathSeg, +use rustc_hir_analysis::lowering::{ + ExplicitLateBound, GenericArgCountMismatch, GenericArgCountResult, GenericArgsLowerer, + HirTyLowerer, IsMethodCall, PathSeg, }; use rustc_infer::infer::canonical::{Canonical, OriginalQueryValues, QueryResponse}; use rustc_infer::infer::error_reporting::TypeAnnotationNeeded::E0282; @@ -374,7 +374,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } pub fn to_ty(&self, ast_t: &hir::Ty<'tcx>) -> LoweredTy<'tcx> { - let t = self.astconv().ast_ty_to_ty(ast_t); + let t = self.lowerer().lower_ty(ast_t); self.register_wf_obligation(t.into(), ast_t.span, traits::WellFormed(None)); LoweredTy::from_raw(self, ast_t.span, t) } @@ -820,7 +820,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // to be object-safe. // We manually call `register_wf_obligation` in the success path // below. - let ty = self.astconv().ast_ty_to_ty_in_path(qself); + let ty = self.lowerer().lower_ty_in_path(qself); (LoweredTy::from_raw(self, span, ty), qself, segment) } QPath::LangItem(..) => { @@ -1080,7 +1080,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let path_segs = match res { Res::Local(_) | Res::SelfCtor(_) => vec![], - Res::Def(kind, def_id) => self.astconv().def_ids_for_value_path_segments( + Res::Def(kind, def_id) => self.lowerer().def_ids_for_value_path_segments( segments, self_ty.map(|ty| ty.raw), kind, @@ -1138,7 +1138,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // errors if type parameters are provided in an inappropriate place. let generic_segs: FxHashSet<_> = path_segs.iter().map(|PathSeg(_, index)| index).collect(); - let generics_has_err = self.astconv().prohibit_generics( + let generics_has_err = self.lowerer().prohibit_generics( segments.iter().enumerate().filter_map(|(index, seg)| { if !generic_segs.contains(&index) || is_alias_variant_ctor { Some(seg) @@ -1260,7 +1260,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { infer_args_for_err: &'a FxHashSet, segments: &'tcx [hir::PathSegment<'tcx>], } - impl<'tcx, 'a> CreateSubstsForGenericArgsCtxt<'a, 'tcx> for CreateCtorSubstsContext<'a, 'tcx> { + impl<'tcx, 'a> GenericArgsLowerer<'a, 'tcx> for CreateCtorSubstsContext<'a, 'tcx> { fn args_for_def_id( &mut self, def_id: DefId, @@ -1289,7 +1289,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ) -> ty::GenericArg<'tcx> { match (¶m.kind, arg) { (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => { - self.fcx.astconv().ast_region_to_region(lt, Some(param)).into() + self.fcx.lowerer().lower_region(lt, Some(param)).into() } (GenericParamDefKind::Type { .. }, GenericArg::Type(ty)) => { self.fcx.to_ty(ty).raw.into() diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs index 35b3f27d79127..c1609615130c9 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs @@ -20,9 +20,9 @@ use rustc_hir::def::{CtorOf, DefKind, Res}; use rustc_hir::def_id::DefId; use rustc_hir::intravisit::Visitor; use rustc_hir::{ExprKind, Node, QPath}; -use rustc_hir_analysis::astconv::AstConv; use rustc_hir_analysis::check::intrinsicck::InlineAsmCtxt; use rustc_hir_analysis::check::potentially_plural_count; +use rustc_hir_analysis::lowering::HirTyLowerer; use rustc_hir_analysis::structured_errors::StructuredDiagnostic; use rustc_index::IndexVec; use rustc_infer::infer::error_reporting::{FailureCode, ObligationCauseExt}; @@ -1794,15 +1794,15 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { match *qpath { QPath::Resolved(ref maybe_qself, path) => { let self_ty = maybe_qself.as_ref().map(|qself| self.to_ty(qself).raw); - let ty = self.astconv().res_to_ty(self_ty, path, hir_id, true); + let ty = self.lowerer().lower_res_to_ty(self_ty, path, hir_id, true); (path.res, LoweredTy::from_raw(self, path_span, ty)) } QPath::TypeRelative(qself, segment) => { let ty = self.to_ty(qself); let result = self - .astconv() - .associated_path_to_ty(hir_id, path_span, ty.raw, qself, segment, true); + .lowerer() + .lower_assoc_path_to_ty(hir_id, path_span, ty.raw, qself, segment, true); let ty = result .map(|(ty, _, _)| ty) .unwrap_or_else(|guar| Ty::new_error(self.tcx(), guar)); diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs index ad4546c09b546..4fa8d30fa2c27 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs @@ -9,7 +9,7 @@ use crate::{CoroutineTypes, Diverges, EnclosingBreakables, Inherited}; use rustc_errors::{DiagCtxt, ErrorGuaranteed}; use rustc_hir as hir; use rustc_hir::def_id::{DefId, LocalDefId}; -use rustc_hir_analysis::astconv::AstConv; +use rustc_hir_analysis::lowering::HirTyLowerer; use rustc_infer::infer; use rustc_infer::infer::error_reporting::TypeErrCtxt; use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind}; @@ -195,7 +195,7 @@ impl<'a, 'tcx> Deref for FnCtxt<'a, 'tcx> { } } -impl<'a, 'tcx> AstConv<'tcx> for FnCtxt<'a, 'tcx> { +impl<'a, 'tcx> HirTyLowerer<'tcx> for FnCtxt<'a, 'tcx> { fn tcx<'b>(&'b self) -> TyCtxt<'tcx> { self.tcx } @@ -288,7 +288,7 @@ impl<'a, 'tcx> AstConv<'tcx> for FnCtxt<'a, 'tcx> { poly_trait_ref, ); - let item_args = self.astconv().create_args_for_associated_item( + let item_args = self.lowerer().lower_args_for_assoc_item( span, item_def_id, item_segment, @@ -343,8 +343,8 @@ impl<'a, 'tcx> AstConv<'tcx> for FnCtxt<'a, 'tcx> { /// The `ty` representation of a user-provided type. Depending on the use-site /// we want to either use the unnormalized or the normalized form of this type. /// -/// This is a bridge between the interface of `AstConv`, which outputs a raw `Ty`, -/// and the API in this module, which expect `Ty` to be fully normalized. +/// This is a bridge between the interface of HIR/ty lowering, which outputs a raw +/// `Ty`, and the API in this module, which expect `Ty` to be fully normalized. #[derive(Clone, Copy, Debug)] pub struct LoweredTy<'tcx> { /// The unnormalized type provided by the user. diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs index ed0bdb9bdaa0d..fc0df6b32ee48 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs @@ -21,7 +21,7 @@ use rustc_hir::{ CoroutineDesugaring, CoroutineKind, CoroutineSource, Expr, ExprKind, GenericBound, HirId, Node, Path, QPath, Stmt, StmtKind, TyKind, WherePredicate, }; -use rustc_hir_analysis::astconv::AstConv; +use rustc_hir_analysis::lowering::HirTyLowerer; use rustc_infer::traits::{self, StatementAsExpression}; use rustc_middle::lint::in_external_macro; use rustc_middle::middle::stability::EvalResult; @@ -859,7 +859,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Only point to return type if the expected type is the return type, as if they // are not, the expectation must have been caused by something else. debug!("return type {:?}", hir_ty); - let ty = self.astconv().ast_ty_to_ty(hir_ty); + let ty = self.lowerer().lower_ty(hir_ty); debug!("return type {:?}", ty); debug!("expected type {:?}", expected); let bound_vars = self.tcx.late_bound_vars(hir_ty.hir_id.owner.into()); @@ -939,8 +939,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { bounded_ty, .. }) => { - // FIXME: Maybe these calls to `ast_ty_to_ty` can be removed (and the ones below) - let ty = self.astconv().ast_ty_to_ty(bounded_ty); + // FIXME: Maybe these calls to `lower_ty` can be removed (and the ones below) + let ty = self.lowerer().lower_ty(bounded_ty); Some((ty, bounds)) } _ => None, @@ -978,7 +978,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let all_bounds_str = all_matching_bounds_strs.join(" + "); let ty_param_used_in_fn_params = fn_parameters.iter().any(|param| { - let ty = self.astconv().ast_ty_to_ty( param); + let ty = self.lowerer().lower_ty( param); matches!(ty.kind(), ty::Param(fn_param_ty_param) if expected_ty_as_param == fn_param_ty_param) }); @@ -1040,7 +1040,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } if let hir::FnRetTy::Return(ty) = fn_decl.output { - let ty = self.astconv().ast_ty_to_ty(ty); + let ty = self.lowerer().lower_ty(ty); let bound_vars = self.tcx.late_bound_vars(fn_id); let ty = self .tcx diff --git a/compiler/rustc_hir_typeck/src/lib.rs b/compiler/rustc_hir_typeck/src/lib.rs index 06a1461356707..e3acfed5509ff 100644 --- a/compiler/rustc_hir_typeck/src/lib.rs +++ b/compiler/rustc_hir_typeck/src/lib.rs @@ -58,8 +58,8 @@ use rustc_hir as hir; use rustc_hir::def::{DefKind, Res}; use rustc_hir::intravisit::Visitor; use rustc_hir::{HirIdMap, Node}; -use rustc_hir_analysis::astconv::AstConv; use rustc_hir_analysis::check::check_abi; +use rustc_hir_analysis::lowering::HirTyLowerer; use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind}; use rustc_infer::traits::ObligationInspector; use rustc_middle::query::Providers; @@ -201,7 +201,7 @@ fn typeck_with_fallback<'tcx>( if let Some(hir::FnSig { header, decl, .. }) = fn_sig { let fn_sig = if decl.output.get_infer_ret_ty().is_some() { - fcx.astconv().ty_of_fn(id, header.unsafety, header.abi, decl, None, None) + fcx.lowerer().lower_fn_ty(id, header.unsafety, header.abi, decl, None, None) } else { tcx.fn_sig(def_id).instantiate_identity() }; diff --git a/compiler/rustc_hir_typeck/src/method/confirm.rs b/compiler/rustc_hir_typeck/src/method/confirm.rs index 3a44c6c241041..a905db2d55449 100644 --- a/compiler/rustc_hir_typeck/src/method/confirm.rs +++ b/compiler/rustc_hir_typeck/src/method/confirm.rs @@ -4,10 +4,10 @@ use crate::{callee, FnCtxt}; use rustc_hir as hir; use rustc_hir::def_id::DefId; use rustc_hir::GenericArg; -use rustc_hir_analysis::astconv::generics::{ +use rustc_hir_analysis::lowering::generics::{ check_generic_arg_count_for_call, create_args_for_parent_generic_args, }; -use rustc_hir_analysis::astconv::{AstConv, CreateSubstsForGenericArgsCtxt, IsMethodCall}; +use rustc_hir_analysis::lowering::{GenericArgsLowerer, HirTyLowerer, IsMethodCall}; use rustc_infer::infer::{self, DefineOpaqueTypes, InferOk}; use rustc_middle::traits::{ObligationCauseCode, UnifyReceiverContext}; use rustc_middle::ty::adjustment::{Adjust, Adjustment, PointerCoercion}; @@ -371,7 +371,7 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { pick: &'a probe::Pick<'tcx>, seg: &'a hir::PathSegment<'tcx>, } - impl<'a, 'tcx> CreateSubstsForGenericArgsCtxt<'a, 'tcx> for MethodSubstsCtxt<'a, 'tcx> { + impl<'a, 'tcx> GenericArgsLowerer<'a, 'tcx> for MethodSubstsCtxt<'a, 'tcx> { fn args_for_def_id( &mut self, def_id: DefId, @@ -391,7 +391,7 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { ) -> ty::GenericArg<'tcx> { match (¶m.kind, arg) { (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => { - self.cfcx.fcx.astconv().ast_region_to_region(lt, Some(param)).into() + self.cfcx.fcx.lowerer().lower_region(lt, Some(param)).into() } (GenericParamDefKind::Type { .. }, GenericArg::Type(ty)) => { self.cfcx.to_ty(ty).raw.into() diff --git a/compiler/rustc_span/src/hygiene.rs b/compiler/rustc_span/src/hygiene.rs index 527938daae410..37fea6c122c7a 100644 --- a/compiler/rustc_span/src/hygiene.rs +++ b/compiler/rustc_span/src/hygiene.rs @@ -1062,7 +1062,7 @@ pub enum ExpnKind { Macro(MacroKind, Symbol), /// Transform done by the compiler on the AST. AstPass(AstPass), - /// Desugaring done by the compiler during HIR lowering. + /// Desugaring done by the compiler during AST lowering. Desugaring(DesugaringKind), } diff --git a/compiler/rustc_trait_selection/src/solve/normalizes_to/inherent.rs b/compiler/rustc_trait_selection/src/solve/normalizes_to/inherent.rs index b2dff9b48ff38..8daea7549bc9a 100644 --- a/compiler/rustc_trait_selection/src/solve/normalizes_to/inherent.rs +++ b/compiler/rustc_trait_selection/src/solve/normalizes_to/inherent.rs @@ -1,7 +1,7 @@ //! Computes a normalizes-to (projection) goal for inherent associated types, -//! `#![feature(inherent_associated_type)]`. Since astconv already determines +//! `#![feature(inherent_associated_type)]`. Since HIR/ty lowering already determines //! which impl the IAT is being projected from, we just: -//! 1. instantiate substs, +//! 1. instantiate generic args, //! 2. equate the self type, and //! 3. instantiate and register where clauses. use rustc_middle::traits::solve::{Certainty, Goal, GoalSource, QueryResult}; diff --git a/compiler/rustc_trait_selection/src/traits/mod.rs b/compiler/rustc_trait_selection/src/traits/mod.rs index a7f6021d57a96..4642f896375c4 100644 --- a/compiler/rustc_trait_selection/src/traits/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/mod.rs @@ -46,7 +46,7 @@ pub use self::coherence::{add_placeholder_note, orphan_check, overlapping_impls} pub use self::coherence::{OrphanCheckErr, OverlapResult}; pub use self::engine::{ObligationCtxt, TraitEngineExt}; pub use self::fulfill::{FulfillmentContext, PendingPredicateObligation}; -pub use self::object_safety::astconv_object_safety_violations; +pub use self::object_safety::hir_ty_lowering_object_safety_violations; pub use self::object_safety::is_vtable_safe_method; pub use self::object_safety::object_safety_violations_for_assoc_item; pub use self::object_safety::ObjectSafetyViolation; diff --git a/compiler/rustc_trait_selection/src/traits/object_safety.rs b/compiler/rustc_trait_selection/src/traits/object_safety.rs index 3289dfe343e1a..2070e542b3bae 100644 --- a/compiler/rustc_trait_selection/src/traits/object_safety.rs +++ b/compiler/rustc_trait_selection/src/traits/object_safety.rs @@ -32,11 +32,12 @@ use std::ops::ControlFlow; pub use crate::traits::{MethodViolationCode, ObjectSafetyViolation}; -/// Returns the object safety violations that affect -/// astconv -- currently, `Self` in supertraits. This is needed +/// Returns the object safety violations that affect HIR/ty lowering. +/// +/// Currently that is `Self` in supertraits. This is needed /// because `object_safety_violations` can't be used during /// type collection. -pub fn astconv_object_safety_violations( +pub fn hir_ty_lowering_object_safety_violations( tcx: TyCtxt<'_>, trait_def_id: DefId, ) -> Vec { @@ -47,7 +48,10 @@ pub fn astconv_object_safety_violations( .map(ObjectSafetyViolation::SupertraitSelf) .collect(); - debug!("astconv_object_safety_violations(trait_def_id={:?}) = {:?}", trait_def_id, violations); + debug!( + "hir_ty_lowering_object_safety_violations(trait_def_id={:?}) = {:?}", + trait_def_id, violations + ); violations } diff --git a/compiler/rustc_trait_selection/src/traits/select/confirmation.rs b/compiler/rustc_trait_selection/src/traits/select/confirmation.rs index 6ca249339791c..f5d52abe77ff0 100644 --- a/compiler/rustc_trait_selection/src/traits/select/confirmation.rs +++ b/compiler/rustc_trait_selection/src/traits/select/confirmation.rs @@ -1241,7 +1241,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { // Extract `TailField` and `TailField` from `Struct` and `Struct`, // normalizing in the process, since `type_of` returns something directly from - // astconv (which means it's un-normalized). + // HIR/ty lowering (which means it's un-normalized). let source_tail = normalize_with_depth_to( self, obligation.param_env, diff --git a/compiler/rustc_trait_selection/src/traits/specialize/specialization_graph.rs b/compiler/rustc_trait_selection/src/traits/specialize/specialization_graph.rs index e9a592bdee799..54dc9ecad7e6e 100644 --- a/compiler/rustc_trait_selection/src/traits/specialize/specialization_graph.rs +++ b/compiler/rustc_trait_selection/src/traits/specialize/specialization_graph.rs @@ -421,7 +421,7 @@ pub(crate) fn assoc_def( // associated type. Normally this situation // could only arise through a compiler bug -- // if the user wrote a bad item name, it - // should have failed in astconv. + // should have failed during HIR/ty lowering. bug!( "No associated type `{}` for {}", tcx.item_name(assoc_def_id), diff --git a/compiler/rustc_type_ir/src/ty_kind.rs b/compiler/rustc_type_ir/src/ty_kind.rs index a4fe572067b03..112bd8d33c99a 100644 --- a/compiler/rustc_type_ir/src/ty_kind.rs +++ b/compiler/rustc_type_ir/src/ty_kind.rs @@ -108,7 +108,7 @@ pub enum AliasKind { /// Defines the kinds of types used by the type system. /// /// Types written by the user start out as `hir::TyKind` and get -/// converted to this representation using `AstConv::ast_ty_to_ty`. +/// converted to this representation using `::lower_ty`. #[cfg_attr(feature = "nightly", rustc_diagnostic_item = "IrTyKind")] #[derive(derivative::Derivative)] #[derivative( diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index b8e0d75e7dc37..e3e4fabef37b4 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -20,7 +20,7 @@ use rustc_hir as hir; use rustc_hir::def::{CtorKind, DefKind, Res}; use rustc_hir::def_id::{DefId, DefIdMap, DefIdSet, LocalDefId, LOCAL_CRATE}; use rustc_hir::PredicateOrigin; -use rustc_hir_analysis::hir_ty_to_ty; +use rustc_hir_analysis::lower_ty; use rustc_infer::infer::region_constraints::{Constraint, RegionConstraintData}; use rustc_middle::metadata::Reexport; use rustc_middle::middle::resolve_bound_vars as rbv; @@ -1257,12 +1257,8 @@ fn clean_trait_item<'tcx>(trait_item: &hir::TraitItem<'tcx>, cx: &mut DocContext hir::TraitItemKind::Type(bounds, Some(default)) => { let generics = enter_impl_trait(cx, |cx| clean_generics(trait_item.generics, cx)); let bounds = bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect(); - let item_type = clean_middle_ty( - ty::Binder::dummy(hir_ty_to_ty(cx.tcx, default)), - cx, - None, - None, - ); + let item_type = + clean_middle_ty(ty::Binder::dummy(lower_ty(cx.tcx, default)), cx, None, None); AssocTypeItem( Box::new(TypeAlias { type_: clean_ty(default, cx), @@ -1303,12 +1299,8 @@ pub(crate) fn clean_impl_item<'tcx>( hir::ImplItemKind::Type(hir_ty) => { let type_ = clean_ty(hir_ty, cx); let generics = clean_generics(impl_.generics, cx); - let item_type = clean_middle_ty( - ty::Binder::dummy(hir_ty_to_ty(cx.tcx, hir_ty)), - cx, - None, - None, - ); + let item_type = + clean_middle_ty(ty::Binder::dummy(lower_ty(cx.tcx, hir_ty)), cx, None, None); AssocTypeItem( Box::new(TypeAlias { type_, @@ -1696,7 +1688,7 @@ fn clean_qpath<'tcx>(hir_ty: &hir::Ty<'tcx>, cx: &mut DocContext<'tcx>) -> Type } hir::QPath::Resolved(Some(qself), p) => { // Try to normalize `::T` to a type - let ty = hir_ty_to_ty(cx.tcx, hir_ty); + let ty = lower_ty(cx.tcx, hir_ty); // `hir_to_ty` can return projection types with escaping vars for GATs, e.g. `<() as Trait>::Gat<'_>` if !ty.has_escaping_bound_vars() && let Some(normalized_value) = normalize(cx, ty::Binder::dummy(ty)) @@ -1722,7 +1714,7 @@ fn clean_qpath<'tcx>(hir_ty: &hir::Ty<'tcx>, cx: &mut DocContext<'tcx>) -> Type })) } hir::QPath::TypeRelative(qself, segment) => { - let ty = hir_ty_to_ty(cx.tcx, hir_ty); + let ty = lower_ty(cx.tcx, hir_ty); let self_type = clean_ty(qself, cx); let (trait_, should_show_cast) = match ty.kind() { @@ -2761,12 +2753,8 @@ fn clean_maybe_renamed_item<'tcx>( ItemKind::TyAlias(hir_ty, generics) => { *cx.current_type_aliases.entry(def_id).or_insert(0) += 1; let rustdoc_ty = clean_ty(hir_ty, cx); - let type_ = clean_middle_ty( - ty::Binder::dummy(hir_ty_to_ty(cx.tcx, hir_ty)), - cx, - None, - None, - ); + let type_ = + clean_middle_ty(ty::Binder::dummy(lower_ty(cx.tcx, hir_ty)), cx, None, None); let generics = clean_generics(generics, cx); if let Some(count) = cx.current_type_aliases.get_mut(&def_id) { *count -= 1; diff --git a/src/tools/clippy/book/src/development/type_checking.md b/src/tools/clippy/book/src/development/type_checking.md index dc29ab5d08dad..eda1cfc47ba3b 100644 --- a/src/tools/clippy/book/src/development/type_checking.md +++ b/src/tools/clippy/book/src/development/type_checking.md @@ -118,10 +118,10 @@ Here the HIR sees the types without "thinking" about them, it knows that the fun an `u32`. As far as `hir::Ty` is concerned those might be different types. But at the `ty::Ty` level the compiler understands that they're the same type, in-depth lifetimes, etc... -To get from a `hir::Ty` to a `ty::Ty`, you can use the [`hir_ty_to_ty`][hir_ty_to_ty] function outside of bodies or +To get from a `hir::Ty` to a `ty::Ty`, you can use the [`lower_ty`][lower_ty] function outside of bodies or the [`TypeckResults::node_type()`][node_type] method inside of bodies. -> **Warning**: Don't use `hir_ty_to_ty` inside of bodies, because this can cause ICEs. +> **Warning**: Don't use `lower_ty` inside of bodies, because this can cause ICEs. ## Useful Links @@ -146,6 +146,6 @@ in this chapter: [Ty]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/ty/struct.Ty.html [TyKind]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_type_ir/ty_kind/enum.TyKind.html [TypeckResults]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/ty/struct.TypeckResults.html -[middle_ty]: https://doc.rust-lang.org/beta/nightly-rustc/rustc_middle/ty/struct.Ty.html -[hir_ty]: https://doc.rust-lang.org/beta/nightly-rustc/rustc_hir/struct.Ty.html -[hir_ty_to_ty]: https://doc.rust-lang.org/beta/nightly-rustc/rustc_hir_analysis/fn.hir_ty_to_ty.html +[middle_ty]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/ty/struct.Ty.html +[hir_ty]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_hir/struct.Ty.html +[lower_ty]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_hir_analysis/fn.lower_ty.html diff --git a/src/tools/clippy/clippy_lints/src/implicit_hasher.rs b/src/tools/clippy/clippy_lints/src/implicit_hasher.rs index 87f6f5e7959e1..2a9abc373a800 100644 --- a/src/tools/clippy/clippy_lints/src/implicit_hasher.rs +++ b/src/tools/clippy/clippy_lints/src/implicit_hasher.rs @@ -5,7 +5,7 @@ use rustc_errors::Diagnostic; use rustc_hir as hir; use rustc_hir::intravisit::{walk_body, walk_expr, walk_inf, walk_ty, Visitor}; use rustc_hir::{Body, Expr, ExprKind, GenericArg, Item, ItemKind, QPath, TyKind}; -use rustc_hir_analysis::hir_ty_to_ty; +use rustc_hir_analysis::lower_ty; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::hir::nested_filter; use rustc_middle::ty::{Ty, TypeckResults}; @@ -227,7 +227,7 @@ impl<'tcx> ImplicitHasherType<'tcx> { .collect(); let params_len = params.len(); - let ty = hir_ty_to_ty(cx.tcx, hir_ty); + let ty = lower_ty(cx.tcx, hir_ty); if is_type_diagnostic_item(cx, ty, sym::HashMap) && params_len == 2 { Some(ImplicitHasherType::HashMap( diff --git a/src/tools/clippy/clippy_lints/src/implied_bounds_in_impls.rs b/src/tools/clippy/clippy_lints/src/implied_bounds_in_impls.rs index fab8ffedb9493..ecf382955c00a 100644 --- a/src/tools/clippy/clippy_lints/src/implied_bounds_in_impls.rs +++ b/src/tools/clippy/clippy_lints/src/implied_bounds_in_impls.rs @@ -7,7 +7,7 @@ use rustc_hir::{ Body, FnDecl, FnRetTy, GenericArg, GenericBound, ImplItem, ImplItemKind, ItemKind, TraitBoundModifier, TraitItem, TraitItemKind, TyKind, }; -use rustc_hir_analysis::hir_ty_to_ty; +use rustc_hir_analysis::lower_ty; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty::{self, ClauseKind, Generics, Ty, TyCtxt}; use rustc_session::declare_lint_pass; @@ -150,7 +150,7 @@ fn try_resolve_type<'tcx>( index: usize, ) -> Option> { match args.get(index - 1) { - Some(GenericArg::Type(ty)) => Some(hir_ty_to_ty(tcx, ty)), + Some(GenericArg::Type(ty)) => Some(lower_ty(tcx, ty)), Some(_) => None, None => Some(tcx.type_of(generics.params[index].def_id).skip_binder()), } diff --git a/src/tools/clippy/clippy_lints/src/types/redundant_allocation.rs b/src/tools/clippy/clippy_lints/src/types/redundant_allocation.rs index a0d609501a0c0..37437cbfbec4a 100644 --- a/src/tools/clippy/clippy_lints/src/types/redundant_allocation.rs +++ b/src/tools/clippy/clippy_lints/src/types/redundant_allocation.rs @@ -4,7 +4,7 @@ use clippy_utils::{path_def_id, qpath_generic_tys}; use rustc_errors::Applicability; use rustc_hir::def_id::DefId; use rustc_hir::{self as hir, QPath, TyKind}; -use rustc_hir_analysis::hir_ty_to_ty; +use rustc_hir_analysis::lower_ty; use rustc_lint::LateContext; use rustc_middle::ty::TypeVisitableExt; use rustc_span::symbol::sym; @@ -56,10 +56,10 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, hir_ty: &hir::Ty<'tcx>, qpath: }; let inner_span = match qpath_generic_tys(inner_qpath).next() { Some(hir_ty) => { - // Reallocation of a fat pointer causes it to become thin. `hir_ty_to_ty` is safe to use + // Reallocation of a fat pointer causes it to become thin. `lower_ty` is safe to use // here because `mod.rs` guarantees this lint is only run on types outside of bodies and // is not run on locals. - let ty = hir_ty_to_ty(cx.tcx, hir_ty); + let ty = lower_ty(cx.tcx, hir_ty); if ty.has_escaping_bound_vars() || !ty.is_sized(cx.tcx, cx.param_env) { return false; } diff --git a/src/tools/clippy/clippy_lints/src/types/vec_box.rs b/src/tools/clippy/clippy_lints/src/types/vec_box.rs index a285f771f1b1c..7ffd428d67dd5 100644 --- a/src/tools/clippy/clippy_lints/src/types/vec_box.rs +++ b/src/tools/clippy/clippy_lints/src/types/vec_box.rs @@ -5,7 +5,7 @@ use clippy_utils::{last_path_segment, match_def_path}; use rustc_errors::Applicability; use rustc_hir::def_id::DefId; use rustc_hir::{self as hir, GenericArg, QPath, TyKind}; -use rustc_hir_analysis::hir_ty_to_ty; +use rustc_hir_analysis::lower_ty; use rustc_lint::LateContext; use rustc_middle::ty::layout::LayoutOf; use rustc_middle::ty::TypeVisitableExt; @@ -36,7 +36,7 @@ pub(super) fn check<'tcx>( && let Some(GenericArg::Type(boxed_ty)) = last.args.first() // extract allocator from the Box for later && let boxed_alloc_ty = last.args.get(1) - && let ty_ty = hir_ty_to_ty(cx.tcx, boxed_ty) + && let ty_ty = lower_ty(cx.tcx, boxed_ty) && !ty_ty.has_escaping_bound_vars() && ty_ty.is_sized(cx.tcx, cx.param_env) && let Ok(ty_ty_size) = cx.layout_of(ty_ty).map(|l| l.size.bytes()) @@ -56,7 +56,7 @@ pub(super) fn check<'tcx>( } }, (Some(GenericArg::Type(l)), Some(GenericArg::Type(r))) => - hir_ty_to_ty(cx.tcx, l) == hir_ty_to_ty(cx.tcx, r), + lower_ty(cx.tcx, l) == lower_ty(cx.tcx, r), _ => false } { diff --git a/src/tools/clippy/clippy_lints/src/unconditional_recursion.rs b/src/tools/clippy/clippy_lints/src/unconditional_recursion.rs index 224ec475c5107..a45b157489df3 100644 --- a/src/tools/clippy/clippy_lints/src/unconditional_recursion.rs +++ b/src/tools/clippy/clippy_lints/src/unconditional_recursion.rs @@ -7,7 +7,7 @@ use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::intravisit::{walk_body, walk_expr, FnKind, Visitor}; use rustc_hir::{Body, Expr, ExprKind, FnDecl, HirId, Item, ItemKind, Node, QPath, TyKind}; -use rustc_hir_analysis::hir_ty_to_ty; +use rustc_hir_analysis::lower_ty; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::hir::map::Map; use rustc_middle::hir::nested_filter; @@ -74,7 +74,7 @@ fn get_hir_ty_def_id<'tcx>(tcx: TyCtxt<'tcx>, hir_ty: rustc_hir::Ty<'tcx>) -> Op match qpath { QPath::Resolved(_, path) => path.res.opt_def_id(), QPath::TypeRelative(_, _) => { - let ty = hir_ty_to_ty(tcx, &hir_ty); + let ty = lower_ty(tcx, &hir_ty); match ty.kind() { ty::Alias(ty::Projection, proj) => { diff --git a/src/tools/clippy/clippy_lints/src/uninhabited_references.rs b/src/tools/clippy/clippy_lints/src/uninhabited_references.rs index 6732a43a19ec5..88039372ebd2c 100644 --- a/src/tools/clippy/clippy_lints/src/uninhabited_references.rs +++ b/src/tools/clippy/clippy_lints/src/uninhabited_references.rs @@ -1,7 +1,7 @@ use clippy_utils::diagnostics::span_lint; use rustc_hir::intravisit::FnKind; use rustc_hir::{Body, Expr, ExprKind, FnDecl, FnRetTy, TyKind, UnOp}; -use rustc_hir_analysis::hir_ty_to_ty; +use rustc_hir_analysis::lower_ty; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::lint::in_external_macro; use rustc_session::declare_lint_pass; @@ -71,7 +71,7 @@ impl LateLintPass<'_> for UninhabitedReferences { } if let FnRetTy::Return(hir_ty) = fndecl.output && let TyKind::Ref(_, mut_ty) = hir_ty.kind - && hir_ty_to_ty(cx.tcx, mut_ty.ty).is_privately_uninhabited(cx.tcx, cx.param_env) + && lower_ty(cx.tcx, mut_ty.ty).is_privately_uninhabited(cx.tcx, cx.param_env) { span_lint( cx, diff --git a/src/tools/clippy/clippy_lints/src/use_self.rs b/src/tools/clippy/clippy_lints/src/use_self.rs index a1b08d105b9d9..5b8255c91d828 100644 --- a/src/tools/clippy/clippy_lints/src/use_self.rs +++ b/src/tools/clippy/clippy_lints/src/use_self.rs @@ -11,7 +11,7 @@ use rustc_hir::{ self as hir, Expr, ExprKind, FnRetTy, FnSig, GenericArg, GenericArgsParentheses, GenericParam, GenericParamKind, HirId, Impl, ImplItemKind, Item, ItemKind, Pat, PatKind, Path, QPath, Ty, TyKind, }; -use rustc_hir_analysis::hir_ty_to_ty; +use rustc_hir_analysis::lower_ty; use rustc_lint::{LateContext, LateLintPass}; use rustc_session::impl_lint_pass; use rustc_span::Span; @@ -193,7 +193,7 @@ impl<'tcx> LateLintPass<'tcx> for UseSelf { } fn check_body(&mut self, _: &LateContext<'_>, _: &hir::Body<'_>) { - // `hir_ty_to_ty` cannot be called in `Body`s or it will panic (sometimes). But in bodies + // `lower_ty` cannot be called in `Body`s or it will panic (sometimes). But in bodies // we can use `cx.typeck_results.node_type(..)` to get the `ty::Ty` from a `hir::Ty`. // However the `node_type()` method can *only* be called in bodies. if let Some(&mut StackItem::Check { ref mut in_body, .. }) = self.stack.last_mut() { @@ -224,7 +224,7 @@ impl<'tcx> LateLintPass<'tcx> for UseSelf { && let ty = if in_body > 0 { cx.typeck_results().node_type(hir_ty.hir_id) } else { - hir_ty_to_ty(cx.tcx, hir_ty) + lower_ty(cx.tcx, hir_ty) } && same_type_and_consts(ty, cx.tcx.type_of(impl_id).instantiate_identity()) { diff --git a/src/tools/clippy/clippy_lints/src/zero_sized_map_values.rs b/src/tools/clippy/clippy_lints/src/zero_sized_map_values.rs index 81d4a26e9da43..70a0f4eb806ab 100644 --- a/src/tools/clippy/clippy_lints/src/zero_sized_map_values.rs +++ b/src/tools/clippy/clippy_lints/src/zero_sized_map_values.rs @@ -1,7 +1,7 @@ use clippy_utils::diagnostics::span_lint_and_help; use clippy_utils::ty::{is_normalizable, is_type_diagnostic_item}; use rustc_hir::{self as hir, HirId, ItemKind, Node}; -use rustc_hir_analysis::hir_ty_to_ty; +use rustc_hir_analysis::lower_ty; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty::layout::LayoutOf as _; use rustc_middle::ty::{Adt, Ty, TypeVisitableExt}; @@ -91,5 +91,5 @@ fn ty_from_hir_ty<'tcx>(cx: &LateContext<'tcx>, hir_ty: &hir::Ty<'tcx>) -> Ty<'t None } }) - .unwrap_or_else(|| hir_ty_to_ty(cx.tcx, hir_ty)) + .unwrap_or_else(|| lower_ty(cx.tcx, hir_ty)) } diff --git a/src/tools/clippy/tests/ui/crashes/ice-6179.rs b/src/tools/clippy/tests/ui/crashes/ice-6179.rs index ce1895851e2d9..132bf8ba3e1c0 100644 --- a/src/tools/clippy/tests/ui/crashes/ice-6179.rs +++ b/src/tools/clippy/tests/ui/crashes/ice-6179.rs @@ -1,5 +1,5 @@ //! This is a minimal reproducer for the ICE in https://github.com/rust-lang/rust-clippy/pull/6179. -//! The ICE is mainly caused by using `hir_ty_to_ty`. See the discussion in the PR for details. +//! The ICE is mainly caused by using `lower_ty`. See the discussion in the PR for details. #![warn(clippy::use_self)] #![allow(dead_code, clippy::let_with_type_underscore)]